From cd0665694edd36b905826ade6cf94f915e619ecb Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Tue, 26 Dec 2023 22:58:33 +1100 Subject: [PATCH 01/18] Draft cleanup of the folder definition mess --- source/Makefile | 311 +++++++++--------------------------------------- 1 file changed, 57 insertions(+), 254 deletions(-) diff --git a/source/Makefile b/source/Makefile index de352c5f39..227d462dd4 100644 --- a/source/Makefile +++ b/source/Makefile @@ -55,149 +55,25 @@ HOST_OUTPUT_DIR=Objects/host DEVICE_DFU_ADDRESS=0x08000000 DEVICE_DFU_VID_PID=0x28E9:0x0189 + # Enumerate all of the include directories (HAL source dirs are used for clang-format only) -APP_INC_DIR=./Core/Inc -BRIEFLZ_INC_DIR=./Core/brieflz -MINIWARE_INC_CMSIS_DEVICE=./Core/BSP/Miniware/Vendor/CMSIS/Device/ST/STM32F1xx/Include -MINIWARE_CMSIS_CORE_INC_DIR=./Core/BSP/Miniware/Vendor/CMSIS/Include -MINIWARE_HAL_SRC_DIR=./Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver -MINIWARE_HAL_INC_DIR=./Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Inc -MINIWARE_HAL_LEGACY_INC_DIR=./Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Inc/Legacy -MINIWARE_STARTUP_DIR=./Startup -MINIWARE_INC_DIR=./Core/BSP/Miniware -MINIWARE_LD_FILE=./Core/BSP/Miniware/stm32f103.ld - -S60_INC_CMSIS_DEVICE=./Core/BSP/Sequre_S60/Vendor/CMSIS/Device/ST/STM32F1xx/Include -S60_CMSIS_CORE_INC_DIR=./Core/BSP/Sequre_S60/Vendor/CMSIS/Include -S60_HAL_SRC_DIR=./Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver -S60_HAL_INC_DIR=./Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc -S60_HAL_LEGACY_INC_DIR=./Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/Legacy -S60_STARTUP_DIR=./Startup -S60_INC_DIR=./Core/BSP/Sequre_S60 -S60_LD_FILE=./Core/BSP/Sequre_S60/stm32f103.ld - -MHP30_INC_CMSIS_DEVICE=./Core/BSP/MHP30/Vendor/CMSIS/Device/ST/STM32F1xx/Include -MHP30_CMSIS_CORE_INC_DIR=./Core/BSP/MHP30/Vendor/CMSIS/Include -MHP30_HAL_SRC_DIR=./Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver -MHP30_HAL_INC_DIR=./Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Inc -MHP30_HAL_LEGACY_INC_DIR=./Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Inc/Legacy -MHP30_STARTUP_DIR=./Startup -MHP30_INC_DIR=./Core/BSP/MHP30 -MHP30_LD_FILE=./Core/BSP/MHP30/stm32f103.ld - -PINE_INC_DIR=./Core/BSP/Pinecil -PINE_VENDOR_SRC_DIR=./Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source -PINE_VENDOR_INC_DIR=./Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Include -PINE_VENDOR_USB_INC_DIR=./Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Include/Usb -PINE_NMSIS_INC_DIR=./Core/BSP/Pinecil/Vendor/NMSIS/Core/Include -PINE_FREERTOS_PORT_INC_DIR=./Core/BSP/Pinecil/Vendor/OS/FreeRTOS/Source/portable/GCC - -PINECILV2_DIR=./Core/BSP/Pinecilv2 -PINECILV2_MEM_DIR=$(PINECILV2_DIR)/MemMang -PINECILV2_SDK_DIR=$(PINECILV2_DIR)/bl_mcu_sdk - -PINECILV2_VENDOR_BSP_DIR=$(PINECILV2_SDK_DIR)/bsp -PINECILV2_VENDOR_BSP_COMMON_DIR=$(PINECILV2_VENDOR_BSP_DIR)/bsp_common -PINECILV2_VENDOR_BSP_BOARD_DIR=$(PINECILV2_VENDOR_BSP_DIR)/board -PINECILV2_VENDOR_BSP_PLATFORM_DIR=$(PINECILV2_VENDOR_BSP_COMMON_DIR)/platform -PINECILV2_VENDOR_BSP_USB_DIR=$(PINECILV2_VENDOR_BSP_COMMON_DIR)/usb - -PINECILV2_COMMON_DIR=$(PINECILV2_SDK_DIR)/common -PINECILV2_COMMON_BL_MATH_DIR=$(PINECILV2_COMMON_DIR)/bl_math -PINECILV2_COMMON_DEVICE_DIR=$(PINECILV2_COMMON_DIR)/device -PINECILV2_COMMON_LIST_DIR=$(PINECILV2_COMMON_DIR)/list -PINECILV2_COMMON_MISC_DIR=$(PINECILV2_COMMON_DIR)/misc -PINECILV2_COMMON_PARTITION_DIR=$(PINECILV2_COMMON_DIR)/partition -PINECILV2_COMMON_PID_DIR=$(PINECILV2_COMMON_DIR)/pid -PINECILV2_COMMON_RING_BUFFERDIR=$(PINECILV2_COMMON_DIR)/ring_buffer -PINECILV2_COMMON_SOFT_CRC_DIR=$(PINECILV2_COMMON_DIR)/soft_crc -PINECILV2_COMMON_TIMESTAMP_DIR=$(PINECILV2_COMMON_DIR)/timestamp - -PINECILV2_COMPONENTS_DIR=$(PINECILV2_SDK_DIR)/components -PINECILV2_COMPONENTS_FREERTOS_DIR=$(PINECILV2_COMPONENTS_DIR)/freertos -PINECILV2_COMPONENTS_FREERTOS_BL602_DIR=$(PINECILV2_COMPONENTS_FREERTOS_DIR)/portable/gcc/risc-v/bl702 - -PINECILV2_COMPONENTS_BLE_STACK_PORT_INCLUDE_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/port/include -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/include -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_DRIVERS_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/include/drivers -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_DRIVERS_BLUETOOTH_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/include/drivers/bluetooth -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_BLUETOOTH_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/include/bluetooth -PINECILV2_COMPONENTS_BLE_STACK_COMMON_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common -PINECILV2_COMPONENTS_BLE_STACK_COMMON_INCLUDE_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common/include -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_MISC_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common/include/misc -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_ZEPHYR_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common/include/zephyr -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_NET_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common/include/net -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_TOOLCHAIN_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common/include/toolchain -PINECILV2_COMPONENTS_BLE_STACK_TINYCRYPT_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common/tinycrypt/include -PINECILV2_COMPONENTS_BLE_STACK_TINYCRYPT_INCLUDE_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common/tinycrypt/include/tinycrypt -PINECILV2_COMPONENTS_BLE_STACK_HOST_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/host -PINECILV2_COMPONENTS_BLE_STACK_BL_HCI_WRAPPER_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/bl_hci_wrapper -PINECILV2_COMPONENTS_BLE_CONTROLLER_BLE_INC_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/blecontroller/ble_inc -PINECILV2_COMPONENTS_BLE_STACK_BC_DEC_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/sbc/dec - -# Binary blobs suck and they should be ashamed -PINECILV2_BLE_CRAPWARE_BLOB_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/blecontroller/lib -PINECILV2_RF_CRAPWARE_BLOB_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/bl702_rf/lib - -PINECILV2_COMPONENTS_NMSIS_DIR=$(PINECILV2_COMPONENTS_DIR)/nmsis -PINECILV2_COMPONENTS_NMSIS_CORE_INC_DIR=$(PINECILV2_COMPONENTS_NMSIS_DIR)/core/inc - -PINECILV2_COMPONENTS_USB_STACK_DIR=$(PINECILV2_COMPONENTS_DIR)/usb_stack -PINECILV2_COMPONENTS_USB_STACK_COMMON_DIR=$(PINECILV2_COMPONENTS_USB_STACK_DIR)/common -PINECILV2_COMPONENTS_USB_STACK_CORE_DIR=$(PINECILV2_COMPONENTS_USB_STACK_DIR)/core -PINECILV2_COMPONENTS_USB_STACK_CDC_DIR=$(PINECILV2_COMPONENTS_USB_STACK_DIR)/class/cdc -PINECILV2_COMPONENTS_USB_STACK_WINUSB_DIR=$(PINECILV2_COMPONENTS_USB_STACK_DIR)/class/winusb - -PINECILV2_DRIVERS_DIR=$(PINECILV2_SDK_DIR)/drivers/bl702_driver -PINECILV2_DRIVERS_HAL_DRV_INC_DIR=$(PINECILV2_DRIVERS_DIR)/hal_drv/inc -PINECILV2_DRIVERS_HAL_DRV_DEF_DIR=$(PINECILV2_DRIVERS_DIR)/hal_drv/default_config -PINECILV2_DRIVERS_REGS_DIR=$(PINECILV2_DRIVERS_DIR)/regs -PINECILV2_DRIVERS_RISCV_DIR=$(PINECILV2_DRIVERS_DIR)/risc-v -PINECILV2_DRIVERS_STARTUP_DIR=$(PINECILV2_DRIVERS_DIR)/startup -PINECILV2_DRIVERS_STD_DRV_DIR=$(PINECILV2_DRIVERS_DIR)/std_drv/inc - -SOURCE_MIDDLEWARES_DIR=./Middlewares -FRTOS_CMIS_INC_DIR=./Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS -FRTOS_INC_DIR=./Middlewares/Third_Party/FreeRTOS/Source/include -DRIVER_INC_DIR=./Core/Drivers -BSP_INC_DIR=./Core/BSP -THREADS_INC_DIR=./Core/Threads -THREADS_OP_MODES_INC_DIR=./Core/Threads/OperatingModes -THREADS_OP_MODES_TOOLS_INC_DIR=./Core/Threads/OperatingModes/utils - -SOURCE_THREADS_DIR=./Core/Threads -SOURCE_CORE_DIR=./Core/Src -SOURCE_BRIEFLZ_DIR=./Core/brieflz -SOURCE_DRIVERS_DIR=./Core/Drivers -INC_PD_DRIVERS_DIR=./Core/Drivers/usb-pd/include +APP_INC_DIR=./Core/Inc/ +MIDDLEWARES_DIR=./Middlewares/ +BSP_INC_DIR=./Core/BSP/ +THREADS_DIR=./Core/Threads/ +SOURCE_CORE_DIR=./Core/Src/ +BRIEFLZ_DIR=./Core/brieflz/ +DRIVERS_DIR=./Core/Drivers/ + +# Exclude USB-PD tests PD_DRIVER_TESTS_DIR=./Core/Drivers/usb-pd/tests -PD_DRIVER_DIR=./Core/Drivers/usb-pd + # Excludes for clang-format -ALL_INCLUDES_EXCEPT:=-path $(BRIEFLZ_INC_DIR) \ - -o -path $(PD_DRIVER_DIR) \ - -o -path $(PINECILV2_SDK_DIR) \ - -o -path $(MINIWARE_HAL_INC_DIR) \ - -o -path $(S60_HAL_INC_DIR) \ - -o -path $(MHP30_HAL_INC_DIR) \ - -o -path $(PINE_VENDOR_INC_DIR) \ - -o -path $(MINIWARE_CMSIS_CORE_INC_DIR) \ - -o -path $(S60_CMSIS_CORE_INC_DIR) \ - -o -path $(MINIWARE_INC_CMSIS_DEVICE) \ - -o -path $(S60_INC_CMSIS_DEVICE) \ - -o -path $(MHP30_INC_CMSIS_DEVICE) \ +ALL_INCLUDES_EXCEPT:=-path $(PD_DRIVER_DIR) \ -o -not -name "configuration.h" - -ALL_SOURCE_EXCEPT:=-path $(SOURCE_BRIEFLZ_DIR) \ - -o -path $(PD_DRIVER_DIR) \ - -o -path $(PINECILV2_SDK_DIR) \ - -o -path $(MINIWARE_HAL_SRC_DIR) \ - -o -path $(S60_HAL_SRC_DIR) \ - -o -path $(MHP30_HAL_SRC_DIR) \ - -o -path $(PINE_VENDOR_SRC_DIR) \ - -o -path $(PINECILV2_MEM_DIR) - +ALL_SOURCE_EXCEPT:=-path $(PD_DRIVER_DIR) # Find-all's used for formatting; have to exclude external modules ALL_INCLUDES=$(shell find ./Core -type d \( $(ALL_INCLUDES_EXCEPT) \) -prune -false -o \( -type f \( -name '*.h' -o -name '*.hpp' \) \) ) ALL_SOURCE=$(shell find ./Core -type d \( $(ALL_SOURCE_EXCEPT) \) -prune -false -o \( -type f \( -name '*.c' -o -name '*.cpp' \) \) ) @@ -205,15 +81,8 @@ ALL_SOURCE=$(shell find ./Core -type d \( $(ALL_SOURCE_EXCEPT) \) -prune -f # Device dependent settings ifeq ($(model),$(filter $(model),$(ALL_MINIWARE_MODELS))) $(info Building for Miniware ) -DEVICE_INCLUDES=-I$(MINIWARE_INC_DIR) \ - -I$(MINIWARE_INC_CMSIS_DEVICE) \ - -I$(MINIWARE_CMSIS_CORE_INC_DIR) \ - -I$(MINIWARE_HAL_INC_DIR) \ - -I$(MINIWARE_HAL_LEGACY_INC_DIR) - -DEVICE_BSP_DIR=./Core/BSP/Miniware -S_SRCS:=$(shell find $(MINIWARE_STARTUP_DIR) -type f -name '*.S') -LDSCRIPT=$(MINIWARE_LD_FILE) +DEVICE_BSP_DIR=./Core/BSP/Miniware/ +LDSCRIPT=./Core/BSP/Miniware/stm32f103.ld ifeq ($(model),$(filter $(model),TS101)) flash_size=126k @@ -249,15 +118,10 @@ endif # ALL_MINIWARE_MODELS ifeq ($(model),$(filter $(model),$(ALL_SEQURE_MODELS))) $(info Building for Sequre ) -DEVICE_INCLUDES=-I$(S60_INC_DIR) \ - -I$(S60_INC_CMSIS_DEVICE) \ - -I$(S60_CMSIS_CORE_INC_DIR) \ - -I$(S60_HAL_INC_DIR) \ - -I$(S60_HAL_LEGACY_INC_DIR) -DEVICE_BSP_DIR=./Core/BSP/Sequre_S60 +DEVICE_BSP_DIR=./Core/BSP/Sequre_S60/ S_SRCS:=$(shell find $(S60_STARTUP_DIR) -type f -name '*.S') -LDSCRIPT=$(S60_LD_FILE) +LDSCRIPT=./Core/BSP/Sequre_S60/stm32f103.ld DEV_GLOBAL_DEFS=-D STM32F103T8Ux \ -D STM32F1 \ -D STM32 \ @@ -285,15 +149,9 @@ endif # ALL_SEQURE_MODELS ifeq ($(model),$(filter $(model),$(ALL_MHP30_MODELS))) $(info Building for MHP30 ) -DEVICE_INCLUDES=-I$(MHP30_INC_DIR) \ - -I$(MHP30_INC_CMSIS_DEVICE) \ - -I$(MHP30_CMSIS_CORE_INC_DIR) \ - -I$(MHP30_HAL_INC_DIR) \ - -I$(MHP30_HAL_LEGACY_INC_DIR) - -DEVICE_BSP_DIR=./Core/BSP/MHP30 -S_SRCS:=$(shell find $(MHP30_STARTUP_DIR) -type f -name '*.S') -LDSCRIPT=$(MHP30_LD_FILE) + +DEVICE_BSP_DIR=./Core/BSP/MHP30/ +LDSCRIPT=./Core/BSP/MHP30/stm32f103.ld DEV_GLOBAL_DEFS=-D STM32F103T8Ux \ -D STM32F1 \ -D STM32 \ @@ -320,15 +178,10 @@ endif # ALL_MHP30_MODELS ifeq ($(model),$(ALL_PINECIL_MODELS)) $(info Building for Pine64 Pinecilv1) -DEVICE_INCLUDES=-I$(PINE_INC_DIR) \ - -I$(PINE_VENDOR_INC_DIR) \ - -I$(PINE_VENDOR_USB_INC_DIR) \ - -I$(PINE_NMSIS_INC_DIR) \ - -I$(PINE_FREERTOS_PORT_INC_DIR) - -DEVICE_BSP_DIR=./Core/BSP/Pinecil -S_SRCS:=$(shell find $(PINE_INC_DIR) -type f -name '*.S') $(info $(S_SRCS) ) -ASM_INC=-I$(PINE_RISCV_INC_DIR) + + +DEVICE_BSP_DIR=./Core/BSP/Pinecil/ +S_SRCS:=$(shell find $(DEVICE_BSP_DIR) -type f -name '*.S') LDSCRIPT=./Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Board/pinecil/Source/GCC/gcc_gd32vf103_flashxip.ld flash_size=128k bootldr_size=0x0 @@ -351,61 +204,8 @@ endif # ALL_PINECIL_MODELS ifeq ($(model),$(ALL_PINECIL_V2_MODELS)) $(info Building for Pine64 Pinecilv2 ) -DEVICE_INCLUDES=-I$(PINECILV2_DIR) \ - -I$(PINECILV2_SDK_DIR) \ - -I$(PINECILV2_VENDOR_BSP_COMMON_DIR) \ - -I$(PINECILV2_VENDOR_BSP_PLATFORM_DIR) \ - -I$(PINECILV2_COMMON_DIR) \ - -I$(PINECILV2_COMMON_BL_MATH_DIR) \ - -I$(PINECILV2_COMMON_DEVICE_DIR) \ - -I$(PINECILV2_COMMON_LIST_DIR) \ - -I$(PINECILV2_COMMON_MISC_DIR) \ - -I$(PINECILV2_COMMON_PARTITION_DIR) \ - -I$(PINECILV2_COMMON_PID_DIR) \ - -I$(PINECILV2_COMMON_RING_BUFFERDIR) \ - -I$(PINECILV2_COMMON_SOFT_CRC_DIR) \ - -I$(PINECILV2_COMMON_TIMESTAMP_DIR) \ - -I$(PINECILV2_COMPONENTS_DIR) \ - -I$(PINECILV2_COMPONENTS_FREERTOS_DIR) \ - -I$(PINECILV2_COMPONENTS_FREERTOS_BL602_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_DRIVERS_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_DRIVERS_BLUETOOTH_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_PORT_INCLUDE_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_BLUETOOTH_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_COMMON_INCLUDE_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_COMMON_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_MISC_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_ZEPHYR_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_NET_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_TOOLCHAIN_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_TOOLCHAIN_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_TINYCRYPT_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_TINYCRYPT_INCLUDE_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_HOST_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_BL_HCI_WRAPPER_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_CONTROLLER_BLE_INC_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_BC_DEC_DIR) \ - -I$(PINECILV2_COMPONENTS_NMSIS_DIR) \ - -I$(PINECILV2_COMPONENTS_USB_STACK_DIR) \ - -I$(PINECILV2_DRIVERS_DIR) \ - -I$(PINECILV2_DRIVERS_HAL_DRV_INC_DIR) \ - -I$(PINECILV2_DRIVERS_HAL_DRV_DEF_DIR) \ - -I$(PINECILV2_DRIVERS_REGS_DIR) \ - -I$(PINECILV2_DRIVERS_RISCV_DIR) \ - -I$(PINECILV2_DRIVERS_STARTUP_DIR) \ - -I$(PINECILV2_DRIVERS_STD_DRV_DIR) \ - -I$(PINECILV2_VENDOR_BSP_PLATFORM_DIR) \ - -I$(PINECILV2_VENDOR_BSP_USB_DIR) \ - -I$(PINECILV2_COMPONENTS_USB_STACK_COMMON_DIR) \ - -I$(PINECILV2_COMPONENTS_USB_STACK_CORE_DIR) \ - -I$(PINECILV2_COMPONENTS_USB_STACK_CDC_DIR) \ - -I$(PINECILV2_COMPONENTS_USB_STACK_WINUSB_DIR) \ - -I$(PINECILV2_COMPONENTS_NMSIS_CORE_INC_DIR) - -DEVICE_BSP_DIR=./Core/BSP/Pinecilv2 -S_SRCS:=$(shell find $(PINECILV2_DIR) -type d \( -path $(PINECILV2_VENDOR_BSP_COMMON_DIR) \) -prune -false -o -type f -name '*.S') $(info $(S_SRCS) ) -ASM_INC=$(DEVICE_INCLUDES) + +DEVICE_BSP_DIR=./Core/BSP/Pinecilv2/ LDSCRIPT=./Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/bl702_flash.ld DEVICE_DFU_ADDRESS=0x23000000 # DFU starts at the beginning of flash @@ -482,38 +282,41 @@ bootldr_size=0x0 endif # ALL_PINECIL_V2_MODELS +DEVICE_BSP_INCLUDE_DIRS:= ${shell find ${DEVICE_BSP_DIR} -type d -print} +THREADS_INCLUDE_DIRS:= ${shell find ${THREADS_DIR} -type d -print} +DRIVERS_INCLUDE_DIRS:= ${shell find ${DRIVERS_DIR} -type d -print} +BRIEFLZ_INCLUDE_DIRS:= ${shell find ${BRIEFLZ_DIR} -type d -print} +MIDDLEWARES_INCLUDE_DIRS:= ${shell find ${MIDDLEWARES_DIR} -type d -print} + + INCLUDES=-I$(APP_INC_DIR) \ - -I$(BRIEFLZ_INC_DIR) \ - -I$(FRTOS_CMIS_INC_DIR) \ - -I$(FRTOS_INC_DIR) \ - -I$(DRIVER_INC_DIR) \ -I$(BSP_INC_DIR) \ - -I$(THREADS_INC_DIR) \ - -I$(THREADS_OP_MODES_INC_DIR) \ - -I$(THREADS_OP_MODES_TOOLS_INC_DIR) \ - -I$(INC_PD_DRIVERS_DIR) \ - $(DEVICE_INCLUDES) - -EXCLUDED_DIRS:=-path $(PINECILV2_VENDOR_BSP_ES8388_DIR) \ - -o -path $(PINECILV2_VENDOR_BSP_IMAGE_SENSOR_DIR) \ - -o -path $(PINECILV2_VENDOR_BSP_LVGL_DIR) \ - -o -path $(PINECILV2_VENDOR_BSP_MCU_LCD_DIR) \ - -o -path $(PINECILV2_VENDOR_BSP_BOARD_DIR) \ - -o -path $(PINECILV2_VENDOR_BSP_USB_DIR) - -SOURCE:=$(shell find $(SOURCE_THREADS_DIR) -type f -name '*.c') \ - $(shell find $(SOURCE_CORE_DIR) -type f -name '*.c') \ - $(shell find $(SOURCE_DRIVERS_DIR) -type f -name '*.c') \ - $(shell find $(DEVICE_BSP_DIR) -type d \( $(EXCLUDED_DIRS) \) -prune -false -o -type f -name '*.c') \ - $(shell find $(SOURCE_MIDDLEWARES_DIR) -type f -name '*.c') \ - $(SOURCE_BRIEFLZ_DIR)/depack.c + ${patsubst %,-I%,${DEVICE_BSP_INCLUDE_DIRS}} \ + ${patsubst %,-I%,${THREADS_INCLUDE_DIRS}} \ + ${patsubst %,-I%,${DRIVERS_INCLUDE_DIRS}} \ + ${patsubst %,-I%,${BRIEFLZ_INCLUDE_DIRS}} \ + ${patsubst %,-I%,${MIDDLEWARES_INCLUDE_DIRS}} + +ASM_INC=$(INCLUDES) + + +SOURCE:=$(shell find ${THREADS_DIR} -type f -name '*.c') \ + $(shell find ${SOURCE_CORE_DIR} -type f -name '*.c') \ + $(shell find ${DRIVERS_DIR} -type f -name '*.c') \ + $(shell find ${DEVICE_BSP_DIR} -type f -name '*.c') \ + $(shell find ${MIDDLEWARES_DIR} -type f -name '*.c') \ + $(BRIEFLZ_DIR)/depack.c # We exclude the USB-PD stack tests $(PD_DRIVER_TESTS_DIR) -SOURCE_CPP:=$(shell find $(SOURCE_THREADS_DIR) -type f -name '*.cpp') \ - $(shell find $(SOURCE_CORE_DIR) -type f -name '*.cpp') \ - $(shell find $(SOURCE_DRIVERS_DIR) -path $(PD_DRIVER_TESTS_DIR) -prune -false -o -type f -name '*.cpp') \ - $(shell find $(DEVICE_BSP_DIR) -type d \( $(EXCLUDED_DIRS) \) -prune -false -o -type f -name '*.cpp') \ - $(shell find $(SOURCE_MIDDLEWARES_DIR) -type f -name '*.cpp') +SOURCE_CPP:=$(shell find ${THREADS_DIR} -type f -name '*.cpp') \ + $(shell find ${SOURCE_CORE_DIR} -type f -name '*.cpp') \ + $(shell find ${DRIVERS_DIR} -type f -name '*.cpp' -not -path "${PD_DRIVER_TESTS_DIR}/*" ) \ + $(shell find ${DEVICE_BSP_DIR} -type f -name '*.cpp') \ + $(shell find ${MIDDLEWARES_DIR} -type f -name '*.cpp') + + +S_SRCS:=$(shell find $(DEVICE_BSP_DIR) -type f -name '*.S') + # Code optimisation ------------------------------------------------------------ OPTIM=-Os \ From 7e3fb6522e76a47c92ec48310773ddff2216c5b2 Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Tue, 26 Dec 2023 23:00:59 +1100 Subject: [PATCH 02/18] Move old startup --- .../MHP30}/Startup/startup_stm32f103t8ux.S | 0 .../Miniware/Startup/startup_stm32f103t8ux.S | 344 ++++++++++++++++++ .../Startup/startup_stm32f103t8ux.S | 344 ++++++++++++++++++ 3 files changed, 688 insertions(+) rename source/{ => Core/BSP/MHP30}/Startup/startup_stm32f103t8ux.S (100%) create mode 100644 source/Core/BSP/Miniware/Startup/startup_stm32f103t8ux.S create mode 100644 source/Core/BSP/Sequre_S60/Startup/startup_stm32f103t8ux.S diff --git a/source/Startup/startup_stm32f103t8ux.S b/source/Core/BSP/MHP30/Startup/startup_stm32f103t8ux.S similarity index 100% rename from source/Startup/startup_stm32f103t8ux.S rename to source/Core/BSP/MHP30/Startup/startup_stm32f103t8ux.S diff --git a/source/Core/BSP/Miniware/Startup/startup_stm32f103t8ux.S b/source/Core/BSP/Miniware/Startup/startup_stm32f103t8ux.S new file mode 100644 index 0000000000..f8d1c8ed78 --- /dev/null +++ b/source/Core/BSP/Miniware/Startup/startup_stm32f103t8ux.S @@ -0,0 +1,344 @@ +/** + ****************************************************************************** + * @file startup_stm32.s + * @author Ac6 + * @version V1.0.0 + * @date 12-June-2014 + ****************************************************************************** + */ + + .syntax unified + .cpu cortex-m3 + .thumb + +.global g_pfnVectors +.global Default_Handler + +/* start address for the initialization values of the .data section. +defined in linker script */ +.word _sidata +/* start address for the .data section. defined in linker script */ +.word _sdata +/* end address for the .data section. defined in linker script */ +.word _edata +/* start address for the .bss section. defined in linker script */ +.word _sbss +/* end address for the .bss section. defined in linker script */ +.word _ebss + +.equ BootRAM, 0xF1E0F85F +/** + * @brief This is the code that gets called when the processor first + * starts execution following a reset event. Only the absolutely + * necessary set is performed, after which the application + * supplied main() routine is called. + * @param None + * @retval : None +*/ + + .section .text.Reset_Handler + .weak Reset_Handler + .type Reset_Handler, %function +Reset_Handler: + +/* Copy the data segment initializers from flash to SRAM */ + movs r1, #0 + b LoopCopyDataInit + +CopyDataInit: + ldr r3, =_sidata + ldr r3, [r3, r1] + str r3, [r0, r1] + adds r1, r1, #4 + +LoopCopyDataInit: + ldr r0, =_sdata + ldr r3, =_edata + adds r2, r0, r1 + cmp r2, r3 + bcc CopyDataInit + ldr r2, =_sbss + b LoopFillZerobss +/* Zero fill the bss segment. */ +FillZerobss: + movs r3, #0 + str r3, [r2] + adds r2, r2, #4 + +LoopFillZerobss: + ldr r3, = _ebss + cmp r2, r3 + bcc FillZerobss + +/* Call the clock system intitialization function.*/ + bl SystemInit +/* Call static constructors */ + bl __libc_init_array +/* Call the application's entry point.*/ + bl main + +LoopForever: + b LoopForever + +.size Reset_Handler, .-Reset_Handler + +/** + * @brief This is the code that gets called when the processor receives an + * unexpected interrupt. This simply enters an infinite loop, preserving + * the system state for examination by a debugger. + * + * @param None + * @retval : None +*/ + .section .text.Default_Handler,"ax",%progbits +Default_Handler: +Infinite_Loop: + b Infinite_Loop + .size Default_Handler, .-Default_Handler +/****************************************************************************** +* +* The minimal vector table for a Cortex-M. Note that the proper constructs +* must be placed on this to ensure that it ends up at physical address +* 0x0000.0000. +* +******************************************************************************/ + .section .isr_vector,"a",%progbits + .type g_pfnVectors, %object + .size g_pfnVectors, .-g_pfnVectors + +g_pfnVectors: + .word _estack + .word Reset_Handler + .word NMI_Handler + .word HardFault_Handler + .word MemManage_Handler + .word BusFault_Handler + .word UsageFault_Handler + .word 0 + .word 0 + .word 0 + .word 0 + .word SVC_Handler + .word DebugMon_Handler + .word 0 + .word PendSV_Handler + .word SysTick_Handler + .word WWDG_IRQHandler + .word PVD_IRQHandler + .word TAMPER_IRQHandler + .word RTC_IRQHandler + .word FLASH_IRQHandler + .word RCC_IRQHandler + .word EXTI0_IRQHandler + .word EXTI1_IRQHandler + .word EXTI2_IRQHandler + .word EXTI3_IRQHandler + .word EXTI4_IRQHandler + .word DMA1_Channel1_IRQHandler + .word DMA1_Channel2_IRQHandler + .word DMA1_Channel3_IRQHandler + .word DMA1_Channel4_IRQHandler + .word DMA1_Channel5_IRQHandler + .word DMA1_Channel6_IRQHandler + .word DMA1_Channel7_IRQHandler + .word ADC1_2_IRQHandler + .word USB_HP_CAN1_TX_IRQHandler + .word USB_LP_CAN1_RX0_IRQHandler + .word CAN1_RX1_IRQHandler + .word CAN1_SCE_IRQHandler + .word EXTI9_5_IRQHandler + .word TIM1_BRK_IRQHandler + .word TIM1_UP_IRQHandler + .word TIM1_TRG_COM_IRQHandler + .word TIM1_CC_IRQHandler + .word TIM2_IRQHandler + .word TIM3_IRQHandler + .word TIM4_IRQHandler + .word I2C1_EV_IRQHandler + .word I2C1_ER_IRQHandler + .word I2C2_EV_IRQHandler + .word I2C2_ER_IRQHandler + .word SPI1_IRQHandler + .word SPI2_IRQHandler + .word USART1_IRQHandler + .word USART2_IRQHandler + .word USART3_IRQHandler + .word EXTI15_10_IRQHandler + .word RTC_Alarm_IRQHandler + .word USBWakeUp_IRQHandler + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + .word BootRAM /* @0x108. This is for boot in RAM mode for + STM32F10x Medium Density devices. */ + +/******************************************************************************* +* +* Provide weak aliases for each Exception handler to the Default_Handler. +* As they are weak aliases, any function with the same name will override +* this definition. +* +*******************************************************************************/ + + .weak NMI_Handler + .thumb_set NMI_Handler,Default_Handler + + .weak HardFault_Handler + .thumb_set HardFault_Handler,Default_Handler + + .weak MemManage_Handler + .thumb_set MemManage_Handler,Default_Handler + + .weak BusFault_Handler + .thumb_set BusFault_Handler,Default_Handler + + .weak UsageFault_Handler + .thumb_set UsageFault_Handler,Default_Handler + + .weak SVC_Handler + .thumb_set SVC_Handler,Default_Handler + + .weak DebugMon_Handler + .thumb_set DebugMon_Handler,Default_Handler + + .weak PendSV_Handler + .thumb_set PendSV_Handler,Default_Handler + + .weak SysTick_Handler + .thumb_set SysTick_Handler,Default_Handler + + .weak WWDG_IRQHandler + .thumb_set WWDG_IRQHandler,Default_Handler + + .weak PVD_IRQHandler + .thumb_set PVD_IRQHandler,Default_Handler + + .weak TAMPER_IRQHandler + .thumb_set TAMPER_IRQHandler,Default_Handler + + .weak RTC_IRQHandler + .thumb_set RTC_IRQHandler,Default_Handler + + .weak FLASH_IRQHandler + .thumb_set FLASH_IRQHandler,Default_Handler + + .weak RCC_IRQHandler + .thumb_set RCC_IRQHandler,Default_Handler + + .weak EXTI0_IRQHandler + .thumb_set EXTI0_IRQHandler,Default_Handler + + .weak EXTI1_IRQHandler + .thumb_set EXTI1_IRQHandler,Default_Handler + + .weak EXTI2_IRQHandler + .thumb_set EXTI2_IRQHandler,Default_Handler + + .weak EXTI3_IRQHandler + .thumb_set EXTI3_IRQHandler,Default_Handler + + .weak EXTI4_IRQHandler + .thumb_set EXTI4_IRQHandler,Default_Handler + + .weak DMA1_Channel1_IRQHandler + .thumb_set DMA1_Channel1_IRQHandler,Default_Handler + + .weak DMA1_Channel2_IRQHandler + .thumb_set DMA1_Channel2_IRQHandler,Default_Handler + + .weak DMA1_Channel3_IRQHandler + .thumb_set DMA1_Channel3_IRQHandler,Default_Handler + + .weak DMA1_Channel4_IRQHandler + .thumb_set DMA1_Channel4_IRQHandler,Default_Handler + + .weak DMA1_Channel5_IRQHandler + .thumb_set DMA1_Channel5_IRQHandler,Default_Handler + + .weak DMA1_Channel6_IRQHandler + .thumb_set DMA1_Channel6_IRQHandler,Default_Handler + + .weak DMA1_Channel7_IRQHandler + .thumb_set DMA1_Channel7_IRQHandler,Default_Handler + + .weak ADC1_2_IRQHandler + .thumb_set ADC1_2_IRQHandler,Default_Handler + + .weak USB_HP_CAN1_TX_IRQHandler + .thumb_set USB_HP_CAN1_TX_IRQHandler,Default_Handler + + .weak USB_LP_CAN1_RX0_IRQHandler + .thumb_set USB_LP_CAN1_RX0_IRQHandler,Default_Handler + + .weak CAN1_RX1_IRQHandler + .thumb_set CAN1_RX1_IRQHandler,Default_Handler + + .weak CAN1_SCE_IRQHandler + .thumb_set CAN1_SCE_IRQHandler,Default_Handler + + .weak EXTI9_5_IRQHandler + .thumb_set EXTI9_5_IRQHandler,Default_Handler + + .weak TIM1_BRK_IRQHandler + .thumb_set TIM1_BRK_IRQHandler,Default_Handler + + .weak TIM1_UP_IRQHandler + .thumb_set TIM1_UP_IRQHandler,Default_Handler + + .weak TIM1_TRG_COM_IRQHandler + .thumb_set TIM1_TRG_COM_IRQHandler,Default_Handler + + .weak TIM1_CC_IRQHandler + .thumb_set TIM1_CC_IRQHandler,Default_Handler + + .weak TIM2_IRQHandler + .thumb_set TIM2_IRQHandler,Default_Handler + + .weak TIM3_IRQHandler + .thumb_set TIM3_IRQHandler,Default_Handler + + .weak TIM4_IRQHandler + .thumb_set TIM4_IRQHandler,Default_Handler + + .weak I2C1_EV_IRQHandler + .thumb_set I2C1_EV_IRQHandler,Default_Handler + + .weak I2C1_ER_IRQHandler + .thumb_set I2C1_ER_IRQHandler,Default_Handler + + .weak I2C2_EV_IRQHandler + .thumb_set I2C2_EV_IRQHandler,Default_Handler + + .weak I2C2_ER_IRQHandler + .thumb_set I2C2_ER_IRQHandler,Default_Handler + + .weak SPI1_IRQHandler + .thumb_set SPI1_IRQHandler,Default_Handler + + .weak SPI2_IRQHandler + .thumb_set SPI2_IRQHandler,Default_Handler + + .weak USART1_IRQHandler + .thumb_set USART1_IRQHandler,Default_Handler + + .weak USART2_IRQHandler + .thumb_set USART2_IRQHandler,Default_Handler + + .weak USART3_IRQHandler + .thumb_set USART3_IRQHandler,Default_Handler + + .weak EXTI15_10_IRQHandler + .thumb_set EXTI15_10_IRQHandler,Default_Handler + + .weak RTC_Alarm_IRQHandler + .thumb_set RTC_Alarm_IRQHandler,Default_Handler + + .weak USBWakeUp_IRQHandler + .thumb_set USBWakeUp_IRQHandler,Default_Handler + + +/************************ (C) COPYRIGHT Ac6 *****END OF FILE****/ diff --git a/source/Core/BSP/Sequre_S60/Startup/startup_stm32f103t8ux.S b/source/Core/BSP/Sequre_S60/Startup/startup_stm32f103t8ux.S new file mode 100644 index 0000000000..f8d1c8ed78 --- /dev/null +++ b/source/Core/BSP/Sequre_S60/Startup/startup_stm32f103t8ux.S @@ -0,0 +1,344 @@ +/** + ****************************************************************************** + * @file startup_stm32.s + * @author Ac6 + * @version V1.0.0 + * @date 12-June-2014 + ****************************************************************************** + */ + + .syntax unified + .cpu cortex-m3 + .thumb + +.global g_pfnVectors +.global Default_Handler + +/* start address for the initialization values of the .data section. +defined in linker script */ +.word _sidata +/* start address for the .data section. defined in linker script */ +.word _sdata +/* end address for the .data section. defined in linker script */ +.word _edata +/* start address for the .bss section. defined in linker script */ +.word _sbss +/* end address for the .bss section. defined in linker script */ +.word _ebss + +.equ BootRAM, 0xF1E0F85F +/** + * @brief This is the code that gets called when the processor first + * starts execution following a reset event. Only the absolutely + * necessary set is performed, after which the application + * supplied main() routine is called. + * @param None + * @retval : None +*/ + + .section .text.Reset_Handler + .weak Reset_Handler + .type Reset_Handler, %function +Reset_Handler: + +/* Copy the data segment initializers from flash to SRAM */ + movs r1, #0 + b LoopCopyDataInit + +CopyDataInit: + ldr r3, =_sidata + ldr r3, [r3, r1] + str r3, [r0, r1] + adds r1, r1, #4 + +LoopCopyDataInit: + ldr r0, =_sdata + ldr r3, =_edata + adds r2, r0, r1 + cmp r2, r3 + bcc CopyDataInit + ldr r2, =_sbss + b LoopFillZerobss +/* Zero fill the bss segment. */ +FillZerobss: + movs r3, #0 + str r3, [r2] + adds r2, r2, #4 + +LoopFillZerobss: + ldr r3, = _ebss + cmp r2, r3 + bcc FillZerobss + +/* Call the clock system intitialization function.*/ + bl SystemInit +/* Call static constructors */ + bl __libc_init_array +/* Call the application's entry point.*/ + bl main + +LoopForever: + b LoopForever + +.size Reset_Handler, .-Reset_Handler + +/** + * @brief This is the code that gets called when the processor receives an + * unexpected interrupt. This simply enters an infinite loop, preserving + * the system state for examination by a debugger. + * + * @param None + * @retval : None +*/ + .section .text.Default_Handler,"ax",%progbits +Default_Handler: +Infinite_Loop: + b Infinite_Loop + .size Default_Handler, .-Default_Handler +/****************************************************************************** +* +* The minimal vector table for a Cortex-M. Note that the proper constructs +* must be placed on this to ensure that it ends up at physical address +* 0x0000.0000. +* +******************************************************************************/ + .section .isr_vector,"a",%progbits + .type g_pfnVectors, %object + .size g_pfnVectors, .-g_pfnVectors + +g_pfnVectors: + .word _estack + .word Reset_Handler + .word NMI_Handler + .word HardFault_Handler + .word MemManage_Handler + .word BusFault_Handler + .word UsageFault_Handler + .word 0 + .word 0 + .word 0 + .word 0 + .word SVC_Handler + .word DebugMon_Handler + .word 0 + .word PendSV_Handler + .word SysTick_Handler + .word WWDG_IRQHandler + .word PVD_IRQHandler + .word TAMPER_IRQHandler + .word RTC_IRQHandler + .word FLASH_IRQHandler + .word RCC_IRQHandler + .word EXTI0_IRQHandler + .word EXTI1_IRQHandler + .word EXTI2_IRQHandler + .word EXTI3_IRQHandler + .word EXTI4_IRQHandler + .word DMA1_Channel1_IRQHandler + .word DMA1_Channel2_IRQHandler + .word DMA1_Channel3_IRQHandler + .word DMA1_Channel4_IRQHandler + .word DMA1_Channel5_IRQHandler + .word DMA1_Channel6_IRQHandler + .word DMA1_Channel7_IRQHandler + .word ADC1_2_IRQHandler + .word USB_HP_CAN1_TX_IRQHandler + .word USB_LP_CAN1_RX0_IRQHandler + .word CAN1_RX1_IRQHandler + .word CAN1_SCE_IRQHandler + .word EXTI9_5_IRQHandler + .word TIM1_BRK_IRQHandler + .word TIM1_UP_IRQHandler + .word TIM1_TRG_COM_IRQHandler + .word TIM1_CC_IRQHandler + .word TIM2_IRQHandler + .word TIM3_IRQHandler + .word TIM4_IRQHandler + .word I2C1_EV_IRQHandler + .word I2C1_ER_IRQHandler + .word I2C2_EV_IRQHandler + .word I2C2_ER_IRQHandler + .word SPI1_IRQHandler + .word SPI2_IRQHandler + .word USART1_IRQHandler + .word USART2_IRQHandler + .word USART3_IRQHandler + .word EXTI15_10_IRQHandler + .word RTC_Alarm_IRQHandler + .word USBWakeUp_IRQHandler + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + .word BootRAM /* @0x108. This is for boot in RAM mode for + STM32F10x Medium Density devices. */ + +/******************************************************************************* +* +* Provide weak aliases for each Exception handler to the Default_Handler. +* As they are weak aliases, any function with the same name will override +* this definition. +* +*******************************************************************************/ + + .weak NMI_Handler + .thumb_set NMI_Handler,Default_Handler + + .weak HardFault_Handler + .thumb_set HardFault_Handler,Default_Handler + + .weak MemManage_Handler + .thumb_set MemManage_Handler,Default_Handler + + .weak BusFault_Handler + .thumb_set BusFault_Handler,Default_Handler + + .weak UsageFault_Handler + .thumb_set UsageFault_Handler,Default_Handler + + .weak SVC_Handler + .thumb_set SVC_Handler,Default_Handler + + .weak DebugMon_Handler + .thumb_set DebugMon_Handler,Default_Handler + + .weak PendSV_Handler + .thumb_set PendSV_Handler,Default_Handler + + .weak SysTick_Handler + .thumb_set SysTick_Handler,Default_Handler + + .weak WWDG_IRQHandler + .thumb_set WWDG_IRQHandler,Default_Handler + + .weak PVD_IRQHandler + .thumb_set PVD_IRQHandler,Default_Handler + + .weak TAMPER_IRQHandler + .thumb_set TAMPER_IRQHandler,Default_Handler + + .weak RTC_IRQHandler + .thumb_set RTC_IRQHandler,Default_Handler + + .weak FLASH_IRQHandler + .thumb_set FLASH_IRQHandler,Default_Handler + + .weak RCC_IRQHandler + .thumb_set RCC_IRQHandler,Default_Handler + + .weak EXTI0_IRQHandler + .thumb_set EXTI0_IRQHandler,Default_Handler + + .weak EXTI1_IRQHandler + .thumb_set EXTI1_IRQHandler,Default_Handler + + .weak EXTI2_IRQHandler + .thumb_set EXTI2_IRQHandler,Default_Handler + + .weak EXTI3_IRQHandler + .thumb_set EXTI3_IRQHandler,Default_Handler + + .weak EXTI4_IRQHandler + .thumb_set EXTI4_IRQHandler,Default_Handler + + .weak DMA1_Channel1_IRQHandler + .thumb_set DMA1_Channel1_IRQHandler,Default_Handler + + .weak DMA1_Channel2_IRQHandler + .thumb_set DMA1_Channel2_IRQHandler,Default_Handler + + .weak DMA1_Channel3_IRQHandler + .thumb_set DMA1_Channel3_IRQHandler,Default_Handler + + .weak DMA1_Channel4_IRQHandler + .thumb_set DMA1_Channel4_IRQHandler,Default_Handler + + .weak DMA1_Channel5_IRQHandler + .thumb_set DMA1_Channel5_IRQHandler,Default_Handler + + .weak DMA1_Channel6_IRQHandler + .thumb_set DMA1_Channel6_IRQHandler,Default_Handler + + .weak DMA1_Channel7_IRQHandler + .thumb_set DMA1_Channel7_IRQHandler,Default_Handler + + .weak ADC1_2_IRQHandler + .thumb_set ADC1_2_IRQHandler,Default_Handler + + .weak USB_HP_CAN1_TX_IRQHandler + .thumb_set USB_HP_CAN1_TX_IRQHandler,Default_Handler + + .weak USB_LP_CAN1_RX0_IRQHandler + .thumb_set USB_LP_CAN1_RX0_IRQHandler,Default_Handler + + .weak CAN1_RX1_IRQHandler + .thumb_set CAN1_RX1_IRQHandler,Default_Handler + + .weak CAN1_SCE_IRQHandler + .thumb_set CAN1_SCE_IRQHandler,Default_Handler + + .weak EXTI9_5_IRQHandler + .thumb_set EXTI9_5_IRQHandler,Default_Handler + + .weak TIM1_BRK_IRQHandler + .thumb_set TIM1_BRK_IRQHandler,Default_Handler + + .weak TIM1_UP_IRQHandler + .thumb_set TIM1_UP_IRQHandler,Default_Handler + + .weak TIM1_TRG_COM_IRQHandler + .thumb_set TIM1_TRG_COM_IRQHandler,Default_Handler + + .weak TIM1_CC_IRQHandler + .thumb_set TIM1_CC_IRQHandler,Default_Handler + + .weak TIM2_IRQHandler + .thumb_set TIM2_IRQHandler,Default_Handler + + .weak TIM3_IRQHandler + .thumb_set TIM3_IRQHandler,Default_Handler + + .weak TIM4_IRQHandler + .thumb_set TIM4_IRQHandler,Default_Handler + + .weak I2C1_EV_IRQHandler + .thumb_set I2C1_EV_IRQHandler,Default_Handler + + .weak I2C1_ER_IRQHandler + .thumb_set I2C1_ER_IRQHandler,Default_Handler + + .weak I2C2_EV_IRQHandler + .thumb_set I2C2_EV_IRQHandler,Default_Handler + + .weak I2C2_ER_IRQHandler + .thumb_set I2C2_ER_IRQHandler,Default_Handler + + .weak SPI1_IRQHandler + .thumb_set SPI1_IRQHandler,Default_Handler + + .weak SPI2_IRQHandler + .thumb_set SPI2_IRQHandler,Default_Handler + + .weak USART1_IRQHandler + .thumb_set USART1_IRQHandler,Default_Handler + + .weak USART2_IRQHandler + .thumb_set USART2_IRQHandler,Default_Handler + + .weak USART3_IRQHandler + .thumb_set USART3_IRQHandler,Default_Handler + + .weak EXTI15_10_IRQHandler + .thumb_set EXTI15_10_IRQHandler,Default_Handler + + .weak RTC_Alarm_IRQHandler + .thumb_set RTC_Alarm_IRQHandler,Default_Handler + + .weak USBWakeUp_IRQHandler + .thumb_set USBWakeUp_IRQHandler,Default_Handler + + +/************************ (C) COPYRIGHT Ac6 *****END OF FILE****/ From 42e2cc8ed67d35fb1065fbc73d3817df5b5e66b4 Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Tue, 26 Dec 2023 23:07:15 +1100 Subject: [PATCH 03/18] Fixup! broken hacky includes --- .../components/ble/ble_stack/common/tinycrypt/source/ecc.c | 6 +++--- .../bl_mcu_sdk/components/ble/ble_stack/host/ecc.h | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c index eb3fa22380..711d223a0b 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c @@ -52,10 +52,10 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include "ecc.h" -#include "ecc_platform_specific.h" +#include "../include/tinycrypt/ecc.h" +#include "../include/tinycrypt/ecc_platform_specific.h" #include - +#include /* IMPORTANT: Make sure a cryptographically-secure PRNG is set and the platform * has access to enough entropy in order to feed the PRNG regularly. */ #if default_RNG_defined diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/ecc.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/ecc.h index 70908c7faf..f740dc180f 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/ecc.h +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/ecc.h @@ -1,5 +1,5 @@ /* ecc.h - ECDH helpers */ - +#include "types.h" /* * Copyright (c) 2016 Intel Corporation * From 8a74efaca2068700cd134a2e538afc2a1260f2da Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Tue, 26 Dec 2023 23:10:39 +1100 Subject: [PATCH 04/18] Update Makefile --- source/Makefile | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/source/Makefile b/source/Makefile index 227d462dd4..8fe7d1c5b1 100644 --- a/source/Makefile +++ b/source/Makefile @@ -222,6 +222,12 @@ CPUFLAGS=-march=rv32imafczicsr \ -DBL702 \ -DBFLB_USE_ROM_DRIVER=1 \ +# Binary blobs suck and they should be ashamed +PINECILV2_SDK_DIR=$(DEVICE_BSP_DIR)/bl_mcu_sdk +PINECILV2_COMPONENTS_DIR=$(PINECILV2_SDK_DIR)/components +PINECILV2_BLE_CRAPWARE_BLOB_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/blecontroller/lib +PINECILV2_RF_CRAPWARE_BLOB_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/bl702_rf/lib + DEV_LDFLAGS=-nostartfiles \ -L $(PINECILV2_BLE_CRAPWARE_BLOB_DIR) \ -L $(PINECILV2_RF_CRAPWARE_BLOB_DIR) \ From 10b400ace8f3d5967232688e81507ec32764c111 Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Tue, 26 Dec 2023 23:11:48 +1100 Subject: [PATCH 05/18] Update Makefile --- source/Makefile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/Makefile b/source/Makefile index 8fe7d1c5b1..08d747b068 100644 --- a/source/Makefile +++ b/source/Makefile @@ -332,7 +332,7 @@ OPTIM=-Os \ -fdevirtualize-at-ltrans \ -fmerge-all-constants \ -fshort-wchar \ - -flto \ + -flto=auto \ -finline-small-functions \ -finline-functions \ -findirect-inlining \ @@ -557,12 +557,12 @@ Core/Gen/macros.txt: Makefile $(OUTPUT_DIR)/Core/Gen/translation.files/%.o: Core/Gen/Translation.%.cpp @test -d $(@D) || mkdir -p $(@D) @echo Generating $@ - @$(CPP) -c $(filter-out -flto ,$(CXXFLAGS)) $< -o $@ + @$(CPP) -c $(filter-out -flto=auto ,$(CXXFLAGS)) $< -o $@ $(OUTPUT_DIR)/Core/Gen/translation.files/multi.%.o: Core/Gen/Translation_multi.%.cpp @test -d $(@D) || mkdir -p $(@D) @echo Generating $@ - @$(CPP) -c $(filter-out -flto ,$(CXXFLAGS)) $< -o $@ + @$(CPP) -c $(filter-out -flto=auto ,$(CXXFLAGS)) $< -o $@ $(HOST_OUTPUT_DIR)/brieflz/libbrieflz.so: Core/brieflz/brieflz.c Core/brieflz/depack.c @test -d $(@D) || mkdir -p $(@D) From 3fadac83ae2dc5c403855ad5240f723bab340e08 Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Tue, 26 Dec 2023 23:23:34 +1100 Subject: [PATCH 06/18] Update Makefile --- source/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/Makefile b/source/Makefile index 08d747b068..4822cffeb3 100644 --- a/source/Makefile +++ b/source/Makefile @@ -64,7 +64,7 @@ THREADS_DIR=./Core/Threads/ SOURCE_CORE_DIR=./Core/Src/ BRIEFLZ_DIR=./Core/brieflz/ DRIVERS_DIR=./Core/Drivers/ - +PD_DRIVER_DIR=./Core/Drivers/usb-pd # Exclude USB-PD tests PD_DRIVER_TESTS_DIR=./Core/Drivers/usb-pd/tests From c2fb1e7a75998f6ed2d52e75cc7d7e2cf99f55f6 Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Tue, 26 Dec 2023 23:32:08 +1100 Subject: [PATCH 07/18] Bulk format --- .../Src/stm32f1xx_hal_rcc_ex.c | 8 +- .../Src/stm32f1xx_hal_adc.c | 15 +- .../Src/stm32f1xx_hal_adc_ex.c | 7 +- .../Src/stm32f1xx_hal_i2c.c | 5 - .../Src/stm32f1xx_hal_rcc_ex.c | 8 +- .../Common/Source/Drivers/Usb/drv_usbd_int.c | 2 +- .../Common/Source/Drivers/Usb/usbh_enum.c | 2 +- .../Common/Source/Drivers/n200_func.c | 4 +- source/Core/BSP/Pinecilv2/MemMang/heap_5.c | 154 +- .../bsp/bsp_common/usb/uart_interface.c | 236 +- .../bl_mcu_sdk/bsp/bsp_common/usb/usb_dc.c | 60 +- .../common/bl_math/arm_dsp_wrapper.c | 37 +- .../bl_mcu_sdk/common/device/drv_device.c | 214 +- .../Pinecilv2/bl_mcu_sdk/common/misc/misc.c | 334 +- .../bl_mcu_sdk/common/partition/partition.c | 828 +- .../BSP/Pinecilv2/bl_mcu_sdk/common/pid/pid.c | 57 +- .../common/ring_buffer/ring_buffer.c | 979 +- .../bl_mcu_sdk/common/soft_crc/softcrc.c | 222 +- .../bl_mcu_sdk/common/timestamp/timestamp.c | 159 +- .../ble_stack/bl_hci_wrapper/bl_hci_wrapper.c | 529 +- .../ble/ble_stack/common/atomic_c.c | 203 +- .../components/ble/ble_stack/common/buf.c | 1211 +- .../components/ble/ble_stack/common/dec.c | 39 +- .../components/ble/ble_stack/common/dummy.c | 3 +- .../components/ble/ble_stack/common/hex.c | 3 +- .../components/ble/ble_stack/common/log.c | 53 +- .../components/ble/ble_stack/common/poll.c | 336 +- .../components/ble/ble_stack/common/rpa.c | 118 +- .../common/tinycrypt/source/aes_decrypt.c | 202 +- .../common/tinycrypt/source/aes_encrypt.c | 251 +- .../common/tinycrypt/source/cbc_mode.c | 109 +- .../common/tinycrypt/source/ccm_mode.c | 376 +- .../common/tinycrypt/source/cmac_mode.c | 267 +- .../common/tinycrypt/source/ctr_mode.c | 79 +- .../common/tinycrypt/source/ctr_prng.c | 352 +- .../ble_stack/common/tinycrypt/source/ecc.c | 1347 +- .../common/tinycrypt/source/ecc_dh.c | 199 +- .../common/tinycrypt/source/ecc_dsa.c | 390 +- .../tinycrypt/source/ecc_platform_specific.c | 49 +- .../ble_stack/common/tinycrypt/source/hmac.c | 164 +- .../common/tinycrypt/source/hmac_prng.c | 219 +- .../common/tinycrypt/source/sha256.c | 326 +- .../ble_stack/common/tinycrypt/source/utils.c | 43 +- .../components/ble/ble_stack/common/utils.c | 199 +- .../components/ble/ble_stack/common/work_q.c | 452 +- .../ble/ble_stack/hci_onchip/hci_driver.c | 697 +- .../components/ble/ble_stack/host/a2dp.c | 423 +- .../components/ble/ble_stack/host/at.c | 687 +- .../components/ble/ble_stack/host/att.c | 3348 +++-- .../ble/ble_stack/host/att_internal.h | 2 +- .../components/ble/ble_stack/host/conn.c | 3712 +++--- .../components/ble/ble_stack/host/crypto.c | 190 +- .../components/ble/ble_stack/host/gatt.c | 6298 +++++----- .../components/ble/ble_stack/host/hci_core.c | 10407 ++++++++-------- .../components/ble/ble_stack/host/hci_ecc.c | 433 +- .../components/ble/ble_stack/host/hfp_hf.c | 1195 +- .../components/ble/ble_stack/host/keys.c | 625 +- .../components/ble/ble_stack/host/keys_br.c | 247 +- .../components/ble/ble_stack/host/l2cap.c | 2671 ++-- .../components/ble/ble_stack/host/monitor.c | 16 +- .../components/ble/ble_stack/host/multi_adv.c | 748 +- .../components/ble/ble_stack/host/sdp.c | 3525 +++--- .../components/ble/ble_stack/host/settings.c | 564 +- .../components/ble/ble_stack/host/smp_null.c | 93 +- .../components/ble/ble_stack/host/uuid.c | 185 +- .../ble/ble_stack/include/bluetooth/gatt.h | 1 + .../components/ble/ble_stack/port/bl_port.c | 462 +- .../components/ble/ble_stack/sbc/dec/alloc.c | 83 +- .../ble/ble_stack/sbc/dec/bitalloc-sbc.c | 181 +- .../ble/ble_stack/sbc/dec/bitalloc.c | 405 +- .../ble/ble_stack/sbc/dec/bitstream-decode.c | 71 +- .../ble/ble_stack/sbc/dec/decoder-oina.c | 117 +- .../ble/ble_stack/sbc/dec/decoder-private.c | 313 +- .../ble/ble_stack/sbc/dec/decoder-sbc.c | 659 +- .../ble/ble_stack/sbc/dec/dequant.c | 96 +- .../ble/ble_stack/sbc/dec/framing-sbc.c | 31 +- .../ble/ble_stack/sbc/dec/framing.c | 396 +- .../ble/ble_stack/sbc/dec/oi_codec_version.c | 7 +- .../ble_stack/sbc/dec/synthesis-8-generated.c | 233 +- .../ble/ble_stack/sbc/dec/synthesis-dct8.c | 387 +- .../ble/ble_stack/sbc/dec/synthesis-sbc.c | 407 +- .../ble/ble_stack/sbc/enc/sbc_analysis.c | 1555 ++- .../ble/ble_stack/sbc/enc/sbc_dct.c | 258 +- .../ble/ble_stack/sbc/enc/sbc_dct_coeffs.c | 192 +- .../sbc/enc/sbc_enc_bit_alloc_mono.c | 268 +- .../ble_stack/sbc/enc/sbc_enc_bit_alloc_ste.c | 277 +- .../ble/ble_stack/sbc/enc/sbc_enc_coeffs.c | 380 +- .../ble/ble_stack/sbc/enc/sbc_encoder.c | 471 +- .../ble/ble_stack/sbc/enc/sbc_packing.c | 371 +- .../components/ble/ble_stack/services/bas.c | 57 +- .../components/ble/ble_stack/services/dis.c | 253 +- .../components/ble/ble_stack/services/hog.c | 180 +- .../components/ble/ble_stack/services/scps.c | 65 +- .../freertos/portable/gcc/risc-v/bl702/port.c | 156 +- .../usb_stack/class/audio/usbd_audio.c | 191 +- .../components/usb_stack/class/cdc/usbd_cdc.c | 220 +- .../components/usb_stack/class/hid/usbd_hid.c | 413 +- .../components/usb_stack/class/msc/usbd_msc.c | 1417 +-- .../usb_stack/class/video/usbd_video.c | 157 +- .../components/usb_stack/core/usbd_core.c | 1675 ++- .../bl702_driver/hal_drv/src/hal_boot2.c | 591 +- .../bl702_driver/hal_drv/src/hal_clock.c | 6 +- .../bl702_driver/hal_drv/src/hal_common.c | 98 +- .../bl702_driver/hal_drv/src/hal_dma.c | 551 +- .../bl702_driver/hal_drv/src/hal_flash.c | 326 +- .../bl702_driver/hal_drv/src/hal_mtimer.c | 127 +- .../bl702_driver/hal_drv/src/hal_pm_util.c | 426 +- .../bl702_driver/hal_drv/src/hal_rtc.c | 107 +- .../bl702_driver/hal_drv/src/hal_sec_aes.c | 134 +- .../bl702_driver/hal_drv/src/hal_sec_dsa.c | 468 +- .../bl702_driver/hal_drv/src/hal_sec_ecdsa.c | 2232 ++-- .../bl702_driver/hal_drv/src/hal_sec_hash.c | 433 +- .../bl702_driver/hal_drv/src/hal_uart.c | 616 +- .../bl702_driver/hal_drv/src/hal_usb.c | 1721 ++- .../bl702_driver/hal_drv/src/hal_wdt.c | 217 +- .../drivers/bl702_driver/startup/drv_mmheap.c | 555 +- .../drivers/bl702_driver/startup/interrupt.c | 317 +- .../bl702_driver/std_drv/src/bl702_acomp.c | 265 +- .../bl702_driver/std_drv/src/bl702_aon.c | 848 +- .../bl702_driver/std_drv/src/bl702_cam.c | 1152 +- .../bl702_driver/std_drv/src/bl702_clock.c | 182 +- .../bl702_driver/std_drv/src/bl702_common.c | 298 +- .../bl702_driver/std_drv/src/bl702_dac.c | 790 +- .../bl702_driver/std_drv/src/bl702_dma.c | 1193 +- .../bl702_driver/std_drv/src/bl702_emac.c | 1047 +- .../bl702_driver/std_drv/src/bl702_glb.c | 7032 +++++------ .../bl702_driver/std_drv/src/bl702_hbn.c | 3106 +++-- .../bl702_driver/std_drv/src/bl702_i2s.c | 671 +- .../bl702_driver/std_drv/src/bl702_ir.c | 1843 ++- .../bl702_driver/std_drv/src/bl702_kys.c | 349 +- .../bl702_driver/std_drv/src/bl702_l1c.c | 933 +- .../bl702_driver/std_drv/src/bl702_mjpeg.c | 1129 +- .../bl702_driver/std_drv/src/bl702_pds.c | 2074 ++- .../bl702_driver/std_drv/src/bl702_psram.c | 1072 +- .../bl702_driver/std_drv/src/bl702_pwm.c | 2 +- .../bl702_driver/std_drv/src/bl702_qdec.c | 854 +- .../bl702_driver/std_drv/src/bl702_romapi.c | 1005 +- .../bl702_driver/std_drv/src/bl702_sec_dbg.c | 172 +- .../bl702_driver/std_drv/src/bl702_sec_eng.c | 5504 ++++---- .../bl702_driver/std_drv/src/bl702_sf_cfg.c | 3005 +++-- .../std_drv/src/bl702_sf_cfg_ext.c | 801 +- .../bl702_driver/std_drv/src/bl702_sf_ctrl.c | 2245 ++-- .../bl702_driver/std_drv/src/bl702_sflash.c | 1 - .../std_drv/src/bl702_sflash_ext.c | 347 +- .../bl702_driver/std_drv/src/bl702_spi.c | 2979 +++-- .../bl702_driver/std_drv/src/bl702_timer.c | 1381 +- .../bl702_driver/std_drv/src/bl702_uart.c | 1989 ++- .../bl702_driver/std_drv/src/bl702_usb.c | 4277 ++++--- .../std_drv/src/bl702_xip_sflash.c | 519 +- .../std_drv/src/bl702_xip_sflash_ext.c | 162 +- .../Src/stm32f1xx_hal_adc.c | 15 +- .../Src/stm32f1xx_hal_adc_ex.c | 7 +- .../Src/stm32f1xx_hal_i2c.c | 5 - .../Src/stm32f1xx_hal_rcc_ex.c | 8 +- source/Core/brieflz/brieflz.c | 809 +- source/Core/brieflz/depack.c | 618 +- 156 files changed, 56415 insertions(+), 62520 deletions(-) diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c index d82d6fea60..63f0523b67 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c @@ -454,8 +454,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { /* Check if PLLI2S is enabled */ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) { /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; + pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul)); } } @@ -474,8 +474,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { /* Check if PLLI2S is enabled */ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) { /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; + pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul)); } } diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c index f29ea6c512..712af4d4c1 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c @@ -1194,7 +1194,6 @@ HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef *hadc, uint32_t *pData, ui /* Set the DMA transfer complete callback */ hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt; - /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */ /* start (in case of SW start): */ @@ -1352,7 +1351,6 @@ void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc) { } } - /* Clear regular group conversion flag */ __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_STRT | ADC_FLAG_EOC); } @@ -1393,12 +1391,8 @@ void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc) { __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_JSTRT | ADC_FLAG_JEOC)); } } - - } - - /** * @} */ @@ -1438,7 +1432,7 @@ void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc) { * @retval HAL status */ HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef *hadc, ADC_ChannelConfTypeDef *sConfig) { - HAL_StatusTypeDef tmp_hal_status = HAL_OK; + HAL_StatusTypeDef tmp_hal_status = HAL_OK; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); @@ -1472,8 +1466,6 @@ HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef *hadc, ADC_ChannelConf MODIFY_REG(hadc->Instance->SMPR2, ADC_SMPR2(ADC_SMPR2_SMP0, sConfig->Channel), ADC_SMPR2(sConfig->SamplingTime, sConfig->Channel)); } - - /* Process unlocked */ __HAL_UNLOCK(hadc); @@ -1712,11 +1704,6 @@ void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma) { } } - - - - - /** * @} */ diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c index dc2e20e8ad..8412668478 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c @@ -661,7 +661,6 @@ HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef *hadc, uint32_t /* Set the DMA transfer complete callback */ hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt; - /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */ /* start (in case of SW start): */ @@ -899,7 +898,7 @@ __weak void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc) { * @retval None */ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_InjectionConfTypeDef *sConfigInjected) { - HAL_StatusTypeDef tmp_hal_status = HAL_OK; + HAL_StatusTypeDef tmp_hal_status = HAL_OK; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); @@ -1028,9 +1027,6 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_I MODIFY_REG(hadc->Instance->SMPR2, ADC_SMPR2(ADC_SMPR2_SMP0, sConfigInjected->InjectedChannel), ADC_SMPR2(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel)); } - - - /* Configure the offset: offset enable/disable, InjectedChannel, offset value */ switch (sConfigInjected->InjectedRank) { case 1: @@ -1051,7 +1047,6 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_I break; } - /* Process unlocked */ __HAL_UNLOCK(hadc); diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c index 5dd8b7c771..b442a4432b 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c @@ -956,8 +956,6 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData /* Clear ADDR flag */ __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - while (hi2c->XferSize > 0U) { /* Wait until TXE flag is set */ if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { @@ -3717,7 +3715,6 @@ static HAL_StatusTypeDef I2C_Master_SB(I2C_HandleTypeDef *hi2c) { return HAL_OK; } - /** * @brief Handle ADDR flag for Master * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains @@ -3963,7 +3960,6 @@ static HAL_StatusTypeDef I2C_MasterRequestWrite(I2C_HandleTypeDef *hi2c, uint16_ /* Send slave address */ hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(DevAddress); } - /* Wait until ADDR flag is set */ if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { @@ -4012,7 +4008,6 @@ static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t /* Send slave address */ hi2c->Instance->DR = I2C_7BIT_ADD_READ(DevAddress); } - /* Wait until ADDR flag is set */ if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c index d700f0caba..a3735b9b82 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c @@ -470,8 +470,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { /* Check if PLLI2S is enabled */ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) { /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; + pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul)); } } @@ -490,8 +490,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { /* Check if PLLI2S is enabled */ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) { /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; + pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul)); } } diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usbd_int.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usbd_int.c index 4a7d0e9c1c..f8733ef13a 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usbd_int.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usbd_int.c @@ -32,7 +32,7 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSI OF SUCH DAMAGE. */ #include "gd32vf103_libopt.h" -//#include "usbd_conf.h" +// #include "usbd_conf.h" #include "drv_usbd_int.h" #include "usbd_transc.h" diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbh_enum.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbh_enum.c index 22b474c06b..2ab5b8fae9 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbh_enum.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbh_enum.c @@ -318,7 +318,7 @@ static void usbh_cfgdesc_parse(usb_desc_config *cfg_desc, uint8_t *buf) { \retval operation status */ static void usbh_cfgset_parse(usb_dev_prop *udev, uint8_t *buf) { - usb_desc_ep * ep = NULL; + usb_desc_ep *ep = NULL; usb_desc_itf *itf = NULL, itf_value; usb_desc_header *pdesc = (usb_desc_header *)buf; diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/n200_func.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/n200_func.c index c4f213d12f..15aa0fb128 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/n200_func.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/n200_func.c @@ -278,8 +278,8 @@ void eclic_mode_enable() { write_csr(CSR_MTVEC, mtvec_value); #elif defined(__GNUC__) uint32_t mtvec_value = read_csr(mtvec); - mtvec_value = mtvec_value & 0xFFFFFFC0; - mtvec_value = mtvec_value | 0x00000003; + mtvec_value = mtvec_value & 0xFFFFFFC0; + mtvec_value = mtvec_value | 0x00000003; write_csr(mtvec, mtvec_value); #endif } diff --git a/source/Core/BSP/Pinecilv2/MemMang/heap_5.c b/source/Core/BSP/Pinecilv2/MemMang/heap_5.c index 3ee2639b0b..d84de815c4 100644 --- a/source/Core/BSP/Pinecilv2/MemMang/heap_5.c +++ b/source/Core/BSP/Pinecilv2/MemMang/heap_5.c @@ -79,21 +79,21 @@ #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE -#if ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) +#if (configSUPPORT_DYNAMIC_ALLOCATION == 0) #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 #endif /* Block sizes must not get too small. */ -#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) +#define heapMINIMUM_BLOCK_SIZE ((size_t)(xHeapStructSize << 1)) /* Assumes 8bit bytes! */ -#define heapBITS_PER_BYTE ( ( size_t ) 8 ) +#define heapBITS_PER_BYTE ((size_t)8) /* Define the linked list structure. This is used to link free blocks in order * of their memory address. */ typedef struct A_BLOCK_LINK { - struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ - size_t xBlockSize; /*<< The size of the free block. */ + struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ + size_t xBlockSize; /*<< The size of the free block. */ } BlockLink_t; /*-----------------------------------------------------------*/ @@ -104,13 +104,13 @@ typedef struct A_BLOCK_LINK { * the block in front it and/or the block behind it if the memory blocks are * adjacent to each other. */ -static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ); +static void prvInsertBlockIntoFreeList(BlockLink_t *pxBlockToInsert); /*-----------------------------------------------------------*/ /* The size of the structure placed at the beginning of each allocated memory * block must by correctly byte aligned. */ -static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); +static const size_t xHeapStructSize = (sizeof(BlockLink_t) + ((size_t)(portBYTE_ALIGNMENT - 1))) & ~((size_t)portBYTE_ALIGNMENT_MASK); /* Create a couple of list links to mark the start and end of the list. */ static BlockLink_t xStart, *pxEnd = NULL; @@ -130,13 +130,13 @@ static size_t xBlockAllocatedBit = 0; /*-----------------------------------------------------------*/ -void *pvPortMalloc( size_t xWantedSize ) { +void *pvPortMalloc(size_t xWantedSize) { BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink; void *pvReturn = NULL; /* The heap must be initialised before the first call to * prvPortMalloc(). */ - configASSERT( pxEnd ); + configASSERT(pxEnd); vTaskSuspendAll(); { @@ -144,17 +144,17 @@ void *pvPortMalloc( size_t xWantedSize ) { * set. The top bit of the block size member of the BlockLink_t structure * is used to determine who owns the block - the application or the * kernel, so it must be free. */ - if ( ( xWantedSize & xBlockAllocatedBit ) == 0 ) { + if ((xWantedSize & xBlockAllocatedBit) == 0) { /* The wanted size is increased so it can contain a BlockLink_t * structure in addition to the requested amount of bytes. */ - if ( xWantedSize > 0 ) { + if (xWantedSize > 0) { xWantedSize += xHeapStructSize; /* Ensure that blocks are always aligned to the required number * of bytes. */ - if ( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) { + if ((xWantedSize & portBYTE_ALIGNMENT_MASK) != 0x00) { /* Byte alignment required. */ - xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + xWantedSize += (portBYTE_ALIGNMENT - (xWantedSize & portBYTE_ALIGNMENT_MASK)); } else { mtCOVERAGE_TEST_MARKER(); } @@ -162,23 +162,23 @@ void *pvPortMalloc( size_t xWantedSize ) { mtCOVERAGE_TEST_MARKER(); } - if ( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) { + if ((xWantedSize > 0) && (xWantedSize <= xFreeBytesRemaining)) { /* Traverse the list from the start (lowest address) block until * one of adequate size is found. */ pxPreviousBlock = &xStart; - pxBlock = xStart.pxNextFreeBlock; + pxBlock = xStart.pxNextFreeBlock; - while ( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) { + while ((pxBlock->xBlockSize < xWantedSize) && (pxBlock->pxNextFreeBlock != NULL)) { pxPreviousBlock = pxBlock; pxBlock = pxBlock->pxNextFreeBlock; } /* If the end marker was reached then a block of adequate size * was not found. */ - if ( pxBlock != pxEnd ) { + if (pxBlock != pxEnd) { /* Return the memory space pointed to - jumping over the * BlockLink_t structure at its start. */ - pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); + pvReturn = (void *)(((uint8_t *)pxPreviousBlock->pxNextFreeBlock) + xHeapStructSize); /* This block is being returned for use so must be taken out * of the list of free blocks. */ @@ -186,12 +186,12 @@ void *pvPortMalloc( size_t xWantedSize ) { /* If the block is larger than required it can be split into * two. */ - if ( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) { + if ((pxBlock->xBlockSize - xWantedSize) > heapMINIMUM_BLOCK_SIZE) { /* This block is to be split into two. Create a new * block following the number of bytes requested. The void * cast is used to prevent byte alignment warnings from the * compiler. */ - pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); + pxNewBlockLink = (void *)(((uint8_t *)pxBlock) + xWantedSize); /* Calculate the sizes of two blocks split from the * single block. */ @@ -199,14 +199,14 @@ void *pvPortMalloc( size_t xWantedSize ) { pxBlock->xBlockSize = xWantedSize; /* Insert the new block into the list of free blocks. */ - prvInsertBlockIntoFreeList( ( pxNewBlockLink ) ); + prvInsertBlockIntoFreeList((pxNewBlockLink)); } else { mtCOVERAGE_TEST_MARKER(); } xFreeBytesRemaining -= pxBlock->xBlockSize; - if ( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) { + if (xFreeBytesRemaining < xMinimumEverFreeBytesRemaining) { xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; } else { mtCOVERAGE_TEST_MARKER(); @@ -227,14 +227,14 @@ void *pvPortMalloc( size_t xWantedSize ) { mtCOVERAGE_TEST_MARKER(); } - traceMALLOC( pvReturn, xWantedSize ); + traceMALLOC(pvReturn, xWantedSize); } - ( void ) xTaskResumeAll(); + (void)xTaskResumeAll(); -#if ( configUSE_MALLOC_FAILED_HOOK == 1 ) +#if (configUSE_MALLOC_FAILED_HOOK == 1) { - if ( pvReturn == NULL ) { - extern void vApplicationMallocFailedHook( void ); + if (pvReturn == NULL) { + extern void vApplicationMallocFailedHook(void); vApplicationMallocFailedHook(); } else { mtCOVERAGE_TEST_MARKER(); @@ -246,24 +246,24 @@ void *pvPortMalloc( size_t xWantedSize ) { } /*-----------------------------------------------------------*/ -void vPortFree( void *pv ) { - uint8_t *puc = ( uint8_t * ) pv; +void vPortFree(void *pv) { + uint8_t *puc = (uint8_t *)pv; BlockLink_t *pxLink; - if ( pv != NULL ) { + if (pv != NULL) { /* The memory being freed will have an BlockLink_t structure immediately * before it. */ puc -= xHeapStructSize; /* This casting is to keep the compiler from issuing warnings. */ - pxLink = ( void * ) puc; + pxLink = (void *)puc; /* Check the block is actually allocated. */ - configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); - configASSERT( pxLink->pxNextFreeBlock == NULL ); + configASSERT((pxLink->xBlockSize & xBlockAllocatedBit) != 0); + configASSERT(pxLink->pxNextFreeBlock == NULL); - if ( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) { - if ( pxLink->pxNextFreeBlock == NULL ) { + if ((pxLink->xBlockSize & xBlockAllocatedBit) != 0) { + if (pxLink->pxNextFreeBlock == NULL) { /* The block is being returned to the heap - it is no longer * allocated. */ pxLink->xBlockSize &= ~xBlockAllocatedBit; @@ -272,11 +272,11 @@ void vPortFree( void *pv ) { { /* Add this block to the list of free blocks. */ xFreeBytesRemaining += pxLink->xBlockSize; - traceFREE( pv, pxLink->xBlockSize ); - prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); + traceFREE(pv, pxLink->xBlockSize); + prvInsertBlockIntoFreeList(((BlockLink_t *)pxLink)); xNumberOfSuccessfulFrees++; } - ( void ) xTaskResumeAll(); + (void)xTaskResumeAll(); } else { mtCOVERAGE_TEST_MARKER(); } @@ -287,27 +287,27 @@ void vPortFree( void *pv ) { } /*-----------------------------------------------------------*/ -size_t xPortGetFreeHeapSize( void ) { return xFreeBytesRemaining; } +size_t xPortGetFreeHeapSize(void) { return xFreeBytesRemaining; } /*-----------------------------------------------------------*/ -size_t xPortGetMinimumEverFreeHeapSize( void ) { return xMinimumEverFreeBytesRemaining; } +size_t xPortGetMinimumEverFreeHeapSize(void) { return xMinimumEverFreeBytesRemaining; } /*-----------------------------------------------------------*/ -static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) { +static void prvInsertBlockIntoFreeList(BlockLink_t *pxBlockToInsert) { BlockLink_t *pxIterator; uint8_t *puc; /* Iterate through the list until a block is found that has a higher address * than the block being inserted. */ - for ( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) { + for (pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock) { /* Nothing to do here, just iterate to the right position. */ } /* Do the block being inserted, and the block it is being inserted after * make a contiguous block of memory? */ - puc = ( uint8_t * ) pxIterator; + puc = (uint8_t *)pxIterator; - if ( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) { + if ((puc + pxIterator->xBlockSize) == (uint8_t *)pxBlockToInsert) { pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; pxBlockToInsert = pxIterator; } else { @@ -316,10 +316,10 @@ static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) { /* Do the block being inserted, and the block it is being inserted before * make a contiguous block of memory? */ - puc = ( uint8_t * ) pxBlockToInsert; + puc = (uint8_t *)pxBlockToInsert; - if ( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) { - if ( pxIterator->pxNextFreeBlock != pxEnd ) { + if ((puc + pxBlockToInsert->xBlockSize) == (uint8_t *)pxIterator->pxNextFreeBlock) { + if (pxIterator->pxNextFreeBlock != pxEnd) { /* Form one big block from the two blocks. */ pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; @@ -334,7 +334,7 @@ static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) { * before and the block after, then it's pxNextFreeBlock pointer will have * already been set, and should not be set here as that would make it point * to itself. */ - if ( pxIterator != pxBlockToInsert ) { + if (pxIterator != pxBlockToInsert) { pxIterator->pxNextFreeBlock = pxBlockToInsert; } else { mtCOVERAGE_TEST_MARKER(); @@ -342,7 +342,7 @@ static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) { } /*-----------------------------------------------------------*/ -void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) { +void vPortDefineHeapRegions(const HeapRegion_t *const pxHeapRegions) { BlockLink_t *pxFirstFreeBlockInRegion = NULL, *pxPreviousFreeBlock; size_t xAlignedHeap; size_t xTotalRegionSize, xTotalHeapSize = 0; @@ -351,39 +351,39 @@ void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) { const HeapRegion_t *pxHeapRegion; /* Can only call once! */ - configASSERT( pxEnd == NULL ); + configASSERT(pxEnd == NULL); - pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] ); + pxHeapRegion = &(pxHeapRegions[xDefinedRegions]); - while ( pxHeapRegion->xSizeInBytes > 0 ) { + while (pxHeapRegion->xSizeInBytes > 0) { xTotalRegionSize = pxHeapRegion->xSizeInBytes; /* Ensure the heap region starts on a correctly aligned boundary. */ - xAddress = ( size_t ) pxHeapRegion->pucStartAddress; + xAddress = (size_t)pxHeapRegion->pucStartAddress; - if ( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) { - xAddress += ( portBYTE_ALIGNMENT - 1 ); + if ((xAddress & portBYTE_ALIGNMENT_MASK) != 0) { + xAddress += (portBYTE_ALIGNMENT - 1); xAddress &= ~portBYTE_ALIGNMENT_MASK; /* Adjust the size for the bytes lost to alignment. */ - xTotalRegionSize -= xAddress - ( size_t ) pxHeapRegion->pucStartAddress; + xTotalRegionSize -= xAddress - (size_t)pxHeapRegion->pucStartAddress; } xAlignedHeap = xAddress; /* Set xStart if it has not already been set. */ - if ( xDefinedRegions == 0 ) { + if (xDefinedRegions == 0) { /* xStart is used to hold a pointer to the first item in the list of * free blocks. The void cast is used to prevent compiler warnings. */ - xStart.pxNextFreeBlock = ( BlockLink_t * ) xAlignedHeap; - xStart.xBlockSize = ( size_t ) 0; + xStart.pxNextFreeBlock = (BlockLink_t *)xAlignedHeap; + xStart.xBlockSize = (size_t)0; } else { /* Should only get here if one region has already been added to the * heap. */ - configASSERT( pxEnd != NULL ); + configASSERT(pxEnd != NULL); /* Check blocks are passed in with increasing start addresses. */ - configASSERT( xAddress > ( size_t ) pxEnd ); + configASSERT(xAddress > (size_t)pxEnd); } /* Remember the location of the end marker in the previous region, if @@ -392,24 +392,24 @@ void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) { /* pxEnd is used to mark the end of the list of free blocks and is * inserted at the end of the region space. */ - xAddress = xAlignedHeap + xTotalRegionSize; + xAddress = xAlignedHeap + xTotalRegionSize; xAddress -= xHeapStructSize; xAddress &= ~portBYTE_ALIGNMENT_MASK; - pxEnd = ( BlockLink_t * ) xAddress; + pxEnd = (BlockLink_t *)xAddress; pxEnd->xBlockSize = 0; pxEnd->pxNextFreeBlock = NULL; /* To start with there is a single free block in this region that is * sized to take up the entire heap region minus the space taken by the * free block structure. */ - pxFirstFreeBlockInRegion = ( BlockLink_t * ) xAlignedHeap; - pxFirstFreeBlockInRegion->xBlockSize = xAddress - ( size_t ) pxFirstFreeBlockInRegion; + pxFirstFreeBlockInRegion = (BlockLink_t *)xAlignedHeap; + pxFirstFreeBlockInRegion->xBlockSize = xAddress - (size_t)pxFirstFreeBlockInRegion; pxFirstFreeBlockInRegion->pxNextFreeBlock = pxEnd; /* If this is not the first region that makes up the entire heap space * then link the previous region to this region. */ - if ( pxPreviousFreeBlock != NULL ) { + if (pxPreviousFreeBlock != NULL) { pxPreviousFreeBlock->pxNextFreeBlock = pxFirstFreeBlockInRegion; } @@ -417,21 +417,21 @@ void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) { /* Move onto the next HeapRegion_t structure. */ xDefinedRegions++; - pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] ); + pxHeapRegion = &(pxHeapRegions[xDefinedRegions]); } xMinimumEverFreeBytesRemaining = xTotalHeapSize; xFreeBytesRemaining = xTotalHeapSize; /* Check something was actually defined before it is accessed. */ - configASSERT( xTotalHeapSize ); + configASSERT(xTotalHeapSize); /* Work out the position of the top bit in a size_t variable. */ - xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); + xBlockAllocatedBit = ((size_t)1) << ((sizeof(size_t) * heapBITS_PER_BYTE) - 1); } /*-----------------------------------------------------------*/ -void vPortGetHeapStats( HeapStats_t *pxHeapStats ) { +void vPortGetHeapStats(HeapStats_t *pxHeapStats) { BlockLink_t *pxBlock; size_t xBlocks = 0, xMaxSize = 0, xMinSize = portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */ @@ -441,21 +441,21 @@ void vPortGetHeapStats( HeapStats_t *pxHeapStats ) { /* pxBlock will be NULL if the heap has not been initialised. The heap * is initialised automatically when the first allocation is made. */ - if ( pxBlock != NULL ) { + if (pxBlock != NULL) { do { /* Increment the number of blocks and record the largest block seen * so far. */ xBlocks++; - if ( pxBlock->xBlockSize > xMaxSize ) { - xMaxSize = pxBlock->xBlockSize; + if (pxBlock->xBlockSize > xMaxSize) { + xMaxSize = pxBlock->xBlockSize; } /* Heap five will have a zero sized block at the end of each * each region - the block is only used to link to the next * heap region so it not a real block. */ - if ( pxBlock->xBlockSize != 0 ) { - if ( pxBlock->xBlockSize < xMinSize ) { + if (pxBlock->xBlockSize != 0) { + if (pxBlock->xBlockSize < xMinSize) { xMinSize = pxBlock->xBlockSize; } } @@ -463,10 +463,10 @@ void vPortGetHeapStats( HeapStats_t *pxHeapStats ) { /* Move to the next block in the chain until the last block is * reached. */ pxBlock = pxBlock->pxNextFreeBlock; - } while ( pxBlock != pxEnd ); + } while (pxBlock != pxEnd); } } - ( void ) xTaskResumeAll(); + (void)xTaskResumeAll(); pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize; pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.c index 9fe57a5ed7..82d6675a22 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.c @@ -20,11 +20,11 @@ * under the License. * */ +#include "uart_interface.h" #include "bflb_platform.h" +#include "hal_dma.h" #include "hal_gpio.h" -#include "uart_interface.h" #include "hal_usb.h" -#include "hal_dma.h" #define USB_OUT_RINGBUFFER_SIZE (8 * 1024) #define UART_RX_RINGBUFFER_SIZE (8 * 1024) @@ -41,154 +41,118 @@ struct device *dma_ch2; Ring_Buffer_Type usb_rx_rb; Ring_Buffer_Type uart1_rx_rb; -void uart_irq_callback(struct device *dev, void *args, uint32_t size, uint32_t state) -{ - if (state == UART_EVENT_RX_FIFO) { - if (size && size < Ring_Buffer_Get_Empty_Length(&uart1_rx_rb)) { - Ring_Buffer_Write(&uart1_rx_rb, (uint8_t *)args, size); - } else { - MSG("RF OV\r\n"); - } - } else if (state == UART_EVENT_RTO) { - if (size && size < Ring_Buffer_Get_Empty_Length(&uart1_rx_rb)) { - Ring_Buffer_Write(&uart1_rx_rb, (uint8_t *)args, size); - } else { - MSG("RTO OV\r\n"); - } - } else if (state == UART_RX_FER_IT) { - MSG("RX ERR\r\n"); +void uart_irq_callback(struct device *dev, void *args, uint32_t size, uint32_t state) { + if (state == UART_EVENT_RX_FIFO) { + if (size && size < Ring_Buffer_Get_Empty_Length(&uart1_rx_rb)) { + Ring_Buffer_Write(&uart1_rx_rb, (uint8_t *)args, size); + } else { + MSG("RF OV\r\n"); + } + } else if (state == UART_EVENT_RTO) { + if (size && size < Ring_Buffer_Get_Empty_Length(&uart1_rx_rb)) { + Ring_Buffer_Write(&uart1_rx_rb, (uint8_t *)args, size); + } else { + MSG("RTO OV\r\n"); } + } else if (state == UART_RX_FER_IT) { + MSG("RX ERR\r\n"); + } } -void uart1_init(void) -{ +void uart1_init(void) { #ifdef UART1_INDEX - uart_register(UART1_INDEX, "uart1"); - uart1 = device_find("uart1"); - - if (uart1) { - // device_open(uart1, DEVICE_OFLAG_DMA_TX | DEVICE_OFLAG_INT_RX); - // device_set_callback(uart1, uart_irq_callback); - // device_control(uart1, DEVICE_CTRL_SET_INT, (void *)(UART_RX_FIFO_IT | UART_RTO_IT)); - } - - dma_register(DMA0_CH2_INDEX, "ch2"); - dma_ch2 = device_find("ch2"); - - if (dma_ch2) { - DMA_DEV(dma_ch2)->direction = DMA_MEMORY_TO_PERIPH; - DMA_DEV(dma_ch2)->transfer_mode = DMA_LLI_ONCE_MODE; - DMA_DEV(dma_ch2)->src_req = DMA_REQUEST_NONE; - DMA_DEV(dma_ch2)->dst_req = DMA_REQUEST_UART1_TX; - DMA_DEV(dma_ch2)->src_addr_inc = DMA_ADDR_INCREMENT_ENABLE; - DMA_DEV(dma_ch2)->dst_addr_inc = DMA_ADDR_INCREMENT_DISABLE; - DMA_DEV(dma_ch2)->src_burst_size = DMA_BURST_1BYTE; - DMA_DEV(dma_ch2)->dst_burst_size = DMA_BURST_1BYTE; - DMA_DEV(dma_ch2)->src_width = DMA_TRANSFER_WIDTH_8BIT; - DMA_DEV(dma_ch2)->dst_width = DMA_TRANSFER_WIDTH_8BIT; - device_open(dma_ch2, 0); - } + uart_register(UART1_INDEX, "uart1"); + uart1 = device_find("uart1"); + + if (uart1) { + // device_open(uart1, DEVICE_OFLAG_DMA_TX | DEVICE_OFLAG_INT_RX); + // device_set_callback(uart1, uart_irq_callback); + // device_control(uart1, DEVICE_CTRL_SET_INT, (void *)(UART_RX_FIFO_IT | UART_RTO_IT)); + } + + dma_register(DMA0_CH2_INDEX, "ch2"); + dma_ch2 = device_find("ch2"); + + if (dma_ch2) { + DMA_DEV(dma_ch2)->direction = DMA_MEMORY_TO_PERIPH; + DMA_DEV(dma_ch2)->transfer_mode = DMA_LLI_ONCE_MODE; + DMA_DEV(dma_ch2)->src_req = DMA_REQUEST_NONE; + DMA_DEV(dma_ch2)->dst_req = DMA_REQUEST_UART1_TX; + DMA_DEV(dma_ch2)->src_addr_inc = DMA_ADDR_INCREMENT_ENABLE; + DMA_DEV(dma_ch2)->dst_addr_inc = DMA_ADDR_INCREMENT_DISABLE; + DMA_DEV(dma_ch2)->src_burst_size = DMA_BURST_1BYTE; + DMA_DEV(dma_ch2)->dst_burst_size = DMA_BURST_1BYTE; + DMA_DEV(dma_ch2)->src_width = DMA_TRANSFER_WIDTH_8BIT; + DMA_DEV(dma_ch2)->dst_width = DMA_TRANSFER_WIDTH_8BIT; + device_open(dma_ch2, 0); + } #endif } -void uart1_config(uint32_t baudrate, uart_databits_t databits, uart_parity_t parity, uart_stopbits_t stopbits) -{ - device_close(uart1); - UART_DEV(uart1)->baudrate = baudrate; - UART_DEV(uart1)->stopbits = stopbits; - UART_DEV(uart1)->parity = parity; - UART_DEV(uart1)->databits = (databits - 5); - device_open(uart1, DEVICE_OFLAG_DMA_TX | DEVICE_OFLAG_INT_RX); - device_set_callback(uart1, uart_irq_callback); - device_control(uart1, DEVICE_CTRL_SET_INT, (void *)(UART_RX_FIFO_IT | UART_RTO_IT)); - Ring_Buffer_Reset(&usb_rx_rb); - Ring_Buffer_Reset(&uart1_rx_rb); +void uart1_config(uint32_t baudrate, uart_databits_t databits, uart_parity_t parity, uart_stopbits_t stopbits) { + device_close(uart1); + UART_DEV(uart1)->baudrate = baudrate; + UART_DEV(uart1)->stopbits = stopbits; + UART_DEV(uart1)->parity = parity; + UART_DEV(uart1)->databits = (databits - 5); + device_open(uart1, DEVICE_OFLAG_DMA_TX | DEVICE_OFLAG_INT_RX); + device_set_callback(uart1, uart_irq_callback); + device_control(uart1, DEVICE_CTRL_SET_INT, (void *)(UART_RX_FIFO_IT | UART_RTO_IT)); + Ring_Buffer_Reset(&usb_rx_rb); + Ring_Buffer_Reset(&uart1_rx_rb); } static uint8_t uart1_dtr; static uint8_t uart1_rts; -void uart1_set_dtr_rts(uint8_t dtr, uint8_t rts) -{ - uart1_dtr = dtr; - uart1_rts = rts; +void uart1_set_dtr_rts(uint8_t dtr, uint8_t rts) { + uart1_dtr = dtr; + uart1_rts = rts; } -void uart1_dtr_init(void) -{ - gpio_set_mode(uart1_dtr, GPIO_OUTPUT_MODE); -} -void uart1_rts_init(void) -{ - gpio_set_mode(uart1_rts, GPIO_OUTPUT_MODE); -} -void uart1_dtr_deinit(void) -{ - gpio_set_mode(uart1_dtr, GPIO_INPUT_MODE); -} -void uart1_rts_deinit(void) -{ - gpio_set_mode(uart1_rts, GPIO_INPUT_MODE); -} -void dtr_pin_set(uint8_t status) -{ - gpio_write(uart1_dtr, status); -} -void rts_pin_set(uint8_t status) -{ - gpio_write(uart1_rts, status); -} -void ringbuffer_lock() -{ - cpu_global_irq_disable(); -} -void ringbuffer_unlock() -{ - cpu_global_irq_enable(); -} - -void uart_ringbuffer_init(void) -{ - /* init mem for ring_buffer */ - memset(usb_rx_mem, 0, USB_OUT_RINGBUFFER_SIZE); - memset(uart_rx_mem, 0, UART_RX_RINGBUFFER_SIZE); - - /* init ring_buffer */ - Ring_Buffer_Init(&usb_rx_rb, usb_rx_mem, USB_OUT_RINGBUFFER_SIZE, ringbuffer_lock, ringbuffer_unlock); - Ring_Buffer_Init(&uart1_rx_rb, uart_rx_mem, UART_RX_RINGBUFFER_SIZE, ringbuffer_lock, ringbuffer_unlock); +void uart1_dtr_init(void) { gpio_set_mode(uart1_dtr, GPIO_OUTPUT_MODE); } +void uart1_rts_init(void) { gpio_set_mode(uart1_rts, GPIO_OUTPUT_MODE); } +void uart1_dtr_deinit(void) { gpio_set_mode(uart1_dtr, GPIO_INPUT_MODE); } +void uart1_rts_deinit(void) { gpio_set_mode(uart1_rts, GPIO_INPUT_MODE); } +void dtr_pin_set(uint8_t status) { gpio_write(uart1_dtr, status); } +void rts_pin_set(uint8_t status) { gpio_write(uart1_rts, status); } +void ringbuffer_lock() { cpu_global_irq_disable(); } +void ringbuffer_unlock() { cpu_global_irq_enable(); } + +void uart_ringbuffer_init(void) { + /* init mem for ring_buffer */ + memset(usb_rx_mem, 0, USB_OUT_RINGBUFFER_SIZE); + memset(uart_rx_mem, 0, UART_RX_RINGBUFFER_SIZE); + + /* init ring_buffer */ + Ring_Buffer_Init(&usb_rx_rb, usb_rx_mem, USB_OUT_RINGBUFFER_SIZE, ringbuffer_lock, ringbuffer_unlock); + Ring_Buffer_Init(&uart1_rx_rb, uart_rx_mem, UART_RX_RINGBUFFER_SIZE, ringbuffer_lock, ringbuffer_unlock); } -static dma_control_data_t uart_dma_ctrl_cfg = { - .bits.fix_cnt = 0, - .bits.dst_min_mode = 0, - .bits.dst_add_mode = 0, - .bits.SI = 1, - .bits.DI = 0, - .bits.SWidth = DMA_TRANSFER_WIDTH_8BIT, - .bits.DWidth = DMA_TRANSFER_WIDTH_8BIT, - .bits.SBSize = 0, - .bits.DBSize = 0, - .bits.I = 0, - .bits.TransferSize = 4095 -}; -static dma_lli_ctrl_t uart_lli_list = { - .src_addr = (uint32_t)src_buffer, - .dst_addr = DMA_ADDR_UART1_TDR, - .nextlli = 0 -}; - -void uart_send_from_ringbuffer(void) -{ - if (Ring_Buffer_Get_Length(&usb_rx_rb)) { - if (!dma_channel_check_busy(dma_ch2)) { - uint32_t avalibleCnt = Ring_Buffer_Read(&usb_rx_rb, src_buffer, UART_TX_DMA_SIZE); - - if (avalibleCnt) { - dma_channel_stop(dma_ch2); - uart_dma_ctrl_cfg.bits.TransferSize = avalibleCnt; - memcpy(&uart_lli_list.cfg, &uart_dma_ctrl_cfg, sizeof(dma_control_data_t)); - dma_channel_update(dma_ch2, (void *)((uint32_t)&uart_lli_list)); - dma_channel_start(dma_ch2); - } - } +static dma_control_data_t uart_dma_ctrl_cfg = {.bits.fix_cnt = 0, + .bits.dst_min_mode = 0, + .bits.dst_add_mode = 0, + .bits.SI = 1, + .bits.DI = 0, + .bits.SWidth = DMA_TRANSFER_WIDTH_8BIT, + .bits.DWidth = DMA_TRANSFER_WIDTH_8BIT, + .bits.SBSize = 0, + .bits.DBSize = 0, + .bits.I = 0, + .bits.TransferSize = 4095}; +static dma_lli_ctrl_t uart_lli_list = {.src_addr = (uint32_t)src_buffer, .dst_addr = DMA_ADDR_UART1_TDR, .nextlli = 0}; + +void uart_send_from_ringbuffer(void) { + if (Ring_Buffer_Get_Length(&usb_rx_rb)) { + if (!dma_channel_check_busy(dma_ch2)) { + uint32_t avalibleCnt = Ring_Buffer_Read(&usb_rx_rb, src_buffer, UART_TX_DMA_SIZE); + + if (avalibleCnt) { + dma_channel_stop(dma_ch2); + uart_dma_ctrl_cfg.bits.TransferSize = avalibleCnt; + memcpy(&uart_lli_list.cfg, &uart_dma_ctrl_cfg, sizeof(dma_control_data_t)); + dma_channel_update(dma_ch2, (void *)((uint32_t)&uart_lli_list)); + dma_channel_start(dma_ch2); + } } + } } \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/usb_dc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/usb_dc.c index 60dffbd095..8b5712bafa 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/usb_dc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/usb_dc.c @@ -28,55 +28,27 @@ struct device *usb; #ifdef USB_INDEX -static void usb_dc_event_callback(struct device *dev, void *args, uint32_t size, uint32_t state) -{ - usbd_event_notify_handler(state, args); -} +static void usb_dc_event_callback(struct device *dev, void *args, uint32_t size, uint32_t state) { usbd_event_notify_handler(state, args); } #endif -struct device *usb_dc_init(void) -{ +struct device *usb_dc_init(void) { #ifdef USB_INDEX - usb_dc_register(USB_INDEX, "usb"); - usb = device_find("usb"); - device_set_callback(usb, usb_dc_event_callback); - device_open(usb, 0); - return usb; + usb_dc_register(USB_INDEX, "usb"); + usb = device_find("usb"); + device_set_callback(usb, usb_dc_event_callback); + device_open(usb, 0); + return usb; #endif - return NULL; + return NULL; } -int usbd_set_address(const uint8_t addr) -{ - return usb_dc_set_dev_address(addr); -} +int usbd_set_address(const uint8_t addr) { return usb_dc_set_dev_address(addr); } -int usbd_ep_open(const struct usbd_endpoint_cfg *ep_cfg) -{ - return usb_dc_ep_open(usb, (const struct usb_dc_ep_cfg *)ep_cfg); -} -int usbd_ep_close(const uint8_t ep) -{ - return usb_dc_ep_close(ep); -} -int usbd_ep_set_stall(const uint8_t ep) -{ - return usb_dc_ep_set_stall(ep); -} -int usbd_ep_clear_stall(const uint8_t ep) -{ - return usb_dc_ep_clear_stall(ep); -} -int usbd_ep_is_stalled(const uint8_t ep, uint8_t *stalled) -{ - return usb_dc_ep_is_stalled(usb, ep, stalled); -} +int usbd_ep_open(const struct usbd_endpoint_cfg *ep_cfg) { return usb_dc_ep_open(usb, (const struct usb_dc_ep_cfg *)ep_cfg); } +int usbd_ep_close(const uint8_t ep) { return usb_dc_ep_close(ep); } +int usbd_ep_set_stall(const uint8_t ep) { return usb_dc_ep_set_stall(ep); } +int usbd_ep_clear_stall(const uint8_t ep) { return usb_dc_ep_clear_stall(ep); } +int usbd_ep_is_stalled(const uint8_t ep, uint8_t *stalled) { return usb_dc_ep_is_stalled(usb, ep, stalled); } -int usbd_ep_write(const uint8_t ep, const uint8_t *data, uint32_t data_len, uint32_t *ret_bytes) -{ - return usb_dc_ep_write(usb, ep, data, data_len, ret_bytes); -} +int usbd_ep_write(const uint8_t ep, const uint8_t *data, uint32_t data_len, uint32_t *ret_bytes) { return usb_dc_ep_write(usb, ep, data, data_len, ret_bytes); } -int usbd_ep_read(const uint8_t ep, uint8_t *data, uint32_t max_data_len, uint32_t *read_bytes) -{ - return usb_dc_ep_read(usb, ep, data, max_data_len, read_bytes); -} +int usbd_ep_read(const uint8_t ep, uint8_t *data, uint32_t max_data_len, uint32_t *read_bytes) { return usb_dc_ep_read(usb, ep, data, max_data_len, read_bytes); } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/bl_math/arm_dsp_wrapper.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/bl_math/arm_dsp_wrapper.c index 05c627927f..28c478c0c6 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/bl_math/arm_dsp_wrapper.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/bl_math/arm_dsp_wrapper.c @@ -23,28 +23,27 @@ #include "arm_dsp_wrapper.h" -void arm_fill_f32(float32_t value, float32_t *pDst, uint32_t blockSize) -{ - uint32_t blkCnt = blockSize >> 2u; +void arm_fill_f32(float32_t value, float32_t *pDst, uint32_t blockSize) { + uint32_t blkCnt = blockSize >> 2u; - float32_t in1 = value; - float32_t in2 = value; - float32_t in3 = value; - float32_t in4 = value; + float32_t in1 = value; + float32_t in2 = value; + float32_t in3 = value; + float32_t in4 = value; - while (blkCnt > 0u) { - *pDst++ = in1; - *pDst++ = in2; - *pDst++ = in3; - *pDst++ = in4; + while (blkCnt > 0u) { + *pDst++ = in1; + *pDst++ = in2; + *pDst++ = in3; + *pDst++ = in4; - blkCnt--; - } + blkCnt--; + } - blkCnt = blockSize % 0x4u; + blkCnt = blockSize % 0x4u; - while (blkCnt > 0u) { - *pDst++ = value; - blkCnt--; - } + while (blkCnt > 0u) { + *pDst++ = value; + blkCnt--; + } } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/device/drv_device.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/device/drv_device.c index e02a837105..d3dc7330ac 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/device/drv_device.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/device/drv_device.c @@ -38,10 +38,7 @@ dlist_t device_head = DLIST_OBJECT_INIT(device_head); * * @return device header */ -dlist_t *device_get_list_header(void) -{ - return &device_head; -} +dlist_t *device_get_list_header(void) { return &device_head; } /** * This function registers a device driver with specified name. @@ -52,25 +49,23 @@ dlist_t *device_get_list_header(void) * * @return the error code, DEVICE_EOK on initialization successfully. */ -int device_register(struct device *dev, const char *name) -{ - dlist_t *node; +int device_register(struct device *dev, const char *name) { + dlist_t *node; - dlist_for_each(node, &device_head) - { - struct device *dev_obj; - dev_obj = dlist_entry(node, struct device, list); + dlist_for_each(node, &device_head) { + struct device *dev_obj; + dev_obj = dlist_entry(node, struct device, list); - if (dev_obj == dev) { - return -DEVICE_EEXIST; - } + if (dev_obj == dev) { + return -DEVICE_EEXIST; } + } - strcpy(dev->name, name); + strcpy(dev->name, name); - dlist_insert_after(&device_head, &(dev->list)); - dev->status = DEVICE_REGISTERED; - return DEVICE_EOK; + dlist_insert_after(&device_head, &(dev->list)); + dev->status = DEVICE_REGISTERED; + return DEVICE_EOK; } /** @@ -82,17 +77,16 @@ int device_register(struct device *dev, const char *name) * * @return the error code, DEVICE_EOK on initialization successfully. */ -int device_unregister(const char *name) -{ - struct device *dev = device_find(name); +int device_unregister(const char *name) { + struct device *dev = device_find(name); - if (!dev) { - return -DEVICE_ENODEV; - } - dev->status = DEVICE_UNREGISTER; - /* remove from old list */ - dlist_remove(&(dev->list)); - return DEVICE_EOK; + if (!dev) { + return -DEVICE_ENODEV; + } + dev->status = DEVICE_UNREGISTER; + /* remove from old list */ + dlist_remove(&(dev->list)); + return DEVICE_EOK; } /** @@ -102,20 +96,18 @@ int device_unregister(const char *name) * * @return the registered device driver on successful, or NULL on failure. */ -struct device *device_find(const char *name) -{ - struct device *dev; - dlist_t *node; +struct device *device_find(const char *name) { + struct device *dev; + dlist_t *node; - dlist_for_each(node, &device_head) - { - dev = dlist_entry(node, struct device, list); + dlist_for_each(node, &device_head) { + dev = dlist_entry(node, struct device, list); - if (strncmp(dev->name, name, DEVICE_NAME_MAX) == 0) { - return dev; - } + if (strncmp(dev->name, name, DEVICE_NAME_MAX) == 0) { + return dev; } - return NULL; + } + return NULL; } /** @@ -126,26 +118,25 @@ struct device *device_find(const char *name) * * @return the result */ -int device_open(struct device *dev, uint16_t oflag) -{ +int device_open(struct device *dev, uint16_t oflag) { #ifdef DEVICE_CHECK_PARAM - int retval = DEVICE_EOK; + int retval = DEVICE_EOK; - if ((dev->status == DEVICE_REGISTERED) || (dev->status == DEVICE_CLOSED)) { - if (dev_open != NULL) { - retval = dev_open(dev, oflag); - dev->status = DEVICE_OPENED; - dev->oflag |= oflag; - } else { - retval = -DEVICE_EFAULT; - } + if ((dev->status == DEVICE_REGISTERED) || (dev->status == DEVICE_CLOSED)) { + if (dev_open != NULL) { + retval = dev_open(dev, oflag); + dev->status = DEVICE_OPENED; + dev->oflag |= oflag; } else { - retval = -DEVICE_EINVAL; + retval = -DEVICE_EFAULT; } + } else { + retval = -DEVICE_EINVAL; + } - return retval; + return retval; #else - return dev_open(dev, oflag); + return dev_open(dev, oflag); #endif } /** @@ -155,26 +146,25 @@ int device_open(struct device *dev, uint16_t oflag) * * @return the result */ -int device_close(struct device *dev) -{ +int device_close(struct device *dev) { #ifdef DEVICE_CHECK_PARAM - int retval = DEVICE_EOK; + int retval = DEVICE_EOK; - if (dev->status == DEVICE_OPENED) { - if (dev_close != NULL) { - retval = dev_close(dev); - dev->status = DEVICE_CLOSED; - dev->oflag = 0; - } else { - retval = -DEVICE_EFAULT; - } + if (dev->status == DEVICE_OPENED) { + if (dev_close != NULL) { + retval = dev_close(dev); + dev->status = DEVICE_CLOSED; + dev->oflag = 0; } else { - retval = -DEVICE_EINVAL; + retval = -DEVICE_EFAULT; } + } else { + retval = -DEVICE_EINVAL; + } - return retval; + return retval; #else - return dev_close(dev); + return dev_close(dev); #endif } /** @@ -186,24 +176,23 @@ int device_close(struct device *dev) * * @return the result */ -int device_control(struct device *dev, int cmd, void *args) -{ +int device_control(struct device *dev, int cmd, void *args) { #ifdef DEVICE_CHECK_PARAM - int retval = DEVICE_EOK; + int retval = DEVICE_EOK; - if (dev->status > DEVICE_UNREGISTER) { - if (dev_control != NULL) { - retval = dev_control(dev, cmd, args); - } else { - retval = -DEVICE_EFAULT; - } + if (dev->status > DEVICE_UNREGISTER) { + if (dev_control != NULL) { + retval = dev_control(dev, cmd, args); } else { - retval = -DEVICE_EINVAL; + retval = -DEVICE_EFAULT; } + } else { + retval = -DEVICE_EINVAL; + } - return retval; + return retval; #else - return dev_control(dev, cmd, args); + return dev_control(dev, cmd, args); #endif } /** @@ -216,24 +205,23 @@ int device_control(struct device *dev, int cmd, void *args) * * @return the actually written size on successful, otherwise negative returned. */ -int device_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size) -{ +int device_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size) { #ifdef DEVICE_CHECK_PARAM - int retval = DEVICE_EOK; + int retval = DEVICE_EOK; - if (dev->status == DEVICE_OPENED) { - if (dev_write != NULL) { - retval = dev_write(dev, pos, buffer, size); - } else { - retval = -DEVICE_EFAULT; - } + if (dev->status == DEVICE_OPENED) { + if (dev_write != NULL) { + retval = dev_write(dev, pos, buffer, size); } else { - retval = -DEVICE_EINVAL; + retval = -DEVICE_EFAULT; } + } else { + retval = -DEVICE_EINVAL; + } - return retval; + return retval; #else - return dev_write(dev, pos, buffer, size); + return dev_write(dev, pos, buffer, size); #endif } /** @@ -246,24 +234,23 @@ int device_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t * * @return the actually read size on successful, otherwise negative returned. */ -int device_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size) -{ +int device_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size) { #ifdef DEVICE_CHECK_PARAM - int retval = DEVICE_EOK; + int retval = DEVICE_EOK; - if (dev->status == DEVICE_OPENED) { - if (dev_read != NULL) { - retval = dev_read(dev, pos, buffer, size); - } else { - retval = -DEVICE_EFAULT; - } + if (dev->status == DEVICE_OPENED) { + if (dev_read != NULL) { + retval = dev_read(dev, pos, buffer, size); } else { - retval = -DEVICE_EINVAL; + retval = -DEVICE_EFAULT; } + } else { + retval = -DEVICE_EINVAL; + } - return retval; + return retval; #else - return dev_read(dev, pos, buffer, size); + return dev_read(dev, pos, buffer, size); #endif } /** @@ -276,19 +263,18 @@ int device_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size) * * @return the actually read size on successful, otherwise negative returned. */ -int device_set_callback(struct device *dev, void (*callback)(struct device *dev, void *args, uint32_t size, uint32_t event)) -{ - int retval = DEVICE_EOK; +int device_set_callback(struct device *dev, void (*callback)(struct device *dev, void *args, uint32_t size, uint32_t event)) { + int retval = DEVICE_EOK; - if (dev->status > DEVICE_UNREGISTER) { - if (callback != NULL) { - dev->callback = callback; - } else { - retval = -DEVICE_EFAULT; - } + if (dev->status > DEVICE_UNREGISTER) { + if (callback != NULL) { + dev->callback = callback; } else { - retval = -DEVICE_EINVAL; + retval = -DEVICE_EFAULT; } + } else { + retval = -DEVICE_EINVAL; + } - return retval; + return retval; } \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c index 3292a68359..be8d852fbf 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c @@ -24,208 +24,197 @@ #ifndef BFLB_USE_ROM_DRIVER /****************************************************************************/ /** - * @brief Char memcpy - * - * @param dst: Destination - * @param src: Source - * @param n: Count of char - * - * @return Destination pointer - * - *******************************************************************************/ -__WEAK__ void *ATTR_TCM_SECTION arch_memcpy(void *dst, const void *src, uint32_t n) -{ - const uint8_t *p = src; - uint8_t *q = dst; - - while (n--) { - *q++ = *p++; - } - - return dst; + * @brief Char memcpy + * + * @param dst: Destination + * @param src: Source + * @param n: Count of char + * + * @return Destination pointer + * + *******************************************************************************/ +__WEAK__ void *ATTR_TCM_SECTION arch_memcpy(void *dst, const void *src, uint32_t n) { + const uint8_t *p = src; + uint8_t *q = dst; + + while (n--) { + *q++ = *p++; + } + + return dst; } /****************************************************************************/ /** - * @brief Word memcpy - * - * @param dst: Destination - * @param src: Source - * @param n: Count of words - * - * @return Destination pointer - * - *******************************************************************************/ -__WEAK__ uint32_t *ATTR_TCM_SECTION arch_memcpy4(uint32_t *dst, const uint32_t *src, uint32_t n) -{ - const uint32_t *p = src; - uint32_t *q = dst; - - while (n--) { - *q++ = *p++; - } - - return dst; + * @brief Word memcpy + * + * @param dst: Destination + * @param src: Source + * @param n: Count of words + * + * @return Destination pointer + * + *******************************************************************************/ +__WEAK__ uint32_t *ATTR_TCM_SECTION arch_memcpy4(uint32_t *dst, const uint32_t *src, uint32_t n) { + const uint32_t *p = src; + uint32_t *q = dst; + + while (n--) { + *q++ = *p++; + } + + return dst; } /****************************************************************************/ /** - * @brief Fast memcpy - * - * @param dst: Destination - * @param src: Source - * @param n: Count of bytes - * - * @return Destination pointer - * - *******************************************************************************/ -__WEAK__ void *ATTR_TCM_SECTION arch_memcpy_fast(void *pdst, const void *psrc, uint32_t n) -{ - uint32_t left, done, i = 0; - uint8_t *dst = (uint8_t *)pdst; - uint8_t *src = (uint8_t *)psrc; - - if (((uint32_t)(uintptr_t)dst & 0x3) == 0 && ((uint32_t)(uintptr_t)src & 0x3) == 0) { - arch_memcpy4((uint32_t *)dst, (const uint32_t *)src, n >> 2); - left = n % 4; - done = n - left; - - while (i < left) { - dst[done + i] = src[done + i]; - i++; - } - } else { - arch_memcpy(dst, src, n); + * @brief Fast memcpy + * + * @param dst: Destination + * @param src: Source + * @param n: Count of bytes + * + * @return Destination pointer + * + *******************************************************************************/ +__WEAK__ void *ATTR_TCM_SECTION arch_memcpy_fast(void *pdst, const void *psrc, uint32_t n) { + uint32_t left, done, i = 0; + uint8_t *dst = (uint8_t *)pdst; + uint8_t *src = (uint8_t *)psrc; + + if (((uint32_t)(uintptr_t)dst & 0x3) == 0 && ((uint32_t)(uintptr_t)src & 0x3) == 0) { + arch_memcpy4((uint32_t *)dst, (const uint32_t *)src, n >> 2); + left = n % 4; + done = n - left; + + while (i < left) { + dst[done + i] = src[done + i]; + i++; } + } else { + arch_memcpy(dst, src, n); + } - return dst; + return dst; } /****************************************************************************/ /** - * @brief char memset - * - * @param dst: Destination - * @param val: Value to set - * @param n: Count of char - * - * @return Destination pointer - * - *******************************************************************************/ -__WEAK__ void *ATTR_TCM_SECTION arch_memset(void *s, uint8_t c, uint32_t n) -{ - uint8_t *p = (uint8_t *)s; - - while (n > 0) { - *p++ = (uint8_t)c; - --n; - } - - return s; + * @brief char memset + * + * @param dst: Destination + * @param val: Value to set + * @param n: Count of char + * + * @return Destination pointer + * + *******************************************************************************/ +__WEAK__ void *ATTR_TCM_SECTION arch_memset(void *s, uint8_t c, uint32_t n) { + uint8_t *p = (uint8_t *)s; + + while (n > 0) { + *p++ = (uint8_t)c; + --n; + } + + return s; } /****************************************************************************/ /** - * @brief Word memset - * - * @param dst: Destination - * @param val: Value to set - * @param n: Count of words - * - * @return Destination pointer - * - *******************************************************************************/ -__WEAK__ uint32_t *ATTR_TCM_SECTION arch_memset4(uint32_t *dst, const uint32_t val, uint32_t n) -{ - uint32_t *q = dst; - - while (n--) { - *q++ = val; - } - - return dst; + * @brief Word memset + * + * @param dst: Destination + * @param val: Value to set + * @param n: Count of words + * + * @return Destination pointer + * + *******************************************************************************/ +__WEAK__ uint32_t *ATTR_TCM_SECTION arch_memset4(uint32_t *dst, const uint32_t val, uint32_t n) { + uint32_t *q = dst; + + while (n--) { + *q++ = val; + } + + return dst; } /****************************************************************************/ /** - * @brief string compare - * - * @param s1: string 1 - * @param s2: string 2 - * @param n: Count of chars - * - * @return compare result - * - *******************************************************************************/ -__WEAK__ int ATTR_TCM_SECTION arch_memcmp(const void *s1, const void *s2, uint32_t n) -{ - const unsigned char *c1 = s1, *c2 = s2; - int d = 0; - - while (n--) { - d = (int)*c1++ - (int)*c2++; - - if (d) { - break; - } + * @brief string compare + * + * @param s1: string 1 + * @param s2: string 2 + * @param n: Count of chars + * + * @return compare result + * + *******************************************************************************/ +__WEAK__ int ATTR_TCM_SECTION arch_memcmp(const void *s1, const void *s2, uint32_t n) { + const unsigned char *c1 = s1, *c2 = s2; + int d = 0; + + while (n--) { + d = (int)*c1++ - (int)*c2++; + + if (d) { + break; } + } - return d; + return d; } #endif -void memcopy_to_fifo(void *fifo_addr, uint8_t *data, uint32_t length) -{ - uint8_t *p = (uint8_t *)fifo_addr; - uint8_t *q = data; +void memcopy_to_fifo(void *fifo_addr, uint8_t *data, uint32_t length) { + uint8_t *p = (uint8_t *)fifo_addr; + uint8_t *q = data; - while (length--) { - *p = *q++; - } + while (length--) { + *p = *q++; + } } -void fifocopy_to_mem(void *fifo_addr, uint8_t *data, uint32_t length) -{ - uint8_t *p = (uint8_t *)fifo_addr; - uint8_t *q = data; +void fifocopy_to_mem(void *fifo_addr, uint8_t *data, uint32_t length) { + uint8_t *p = (uint8_t *)fifo_addr; + uint8_t *q = data; - while (length--) { - *q++ = *p; - } + while (length--) { + *q++ = *p; + } } /****************************************************************************/ /** - * @brief get u64 first number 1 from right to left - * - * @param val: target value - * @param bit: first 1 in bit - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -int arch_ffsll(uint64_t *val, uint32_t *bit) -{ - if (!*val) { - return ERROR; - } - - *bit = __builtin_ffsll(*val) - 1; - *val &= ~((1ULL) << (*bit)); - return 0; + * @brief get u64 first number 1 from right to left + * + * @param val: target value + * @param bit: first 1 in bit + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +int arch_ffsll(uint64_t *val, uint32_t *bit) { + if (!*val) { + return ERROR; + } + + *bit = __builtin_ffsll(*val) - 1; + *val &= ~((1ULL) << (*bit)); + return 0; } -int arch_ctzll(uint64_t *val, uint32_t *bit) -{ - if (!*val) - return -1; +int arch_ctzll(uint64_t *val, uint32_t *bit) { + if (!*val) + return -1; - *bit = __builtin_ctzll(*val); - *val &= ~((1ULL) << (*bit)); - return 0; + *bit = __builtin_ctzll(*val); + *val &= ~((1ULL) << (*bit)); + return 0; } -int arch_clzll(uint64_t *val, uint32_t *bit) -{ - if (!*val) - return -1; +int arch_clzll(uint64_t *val, uint32_t *bit) { + if (!*val) + return -1; - *bit = __builtin_clzll(*val); - *val &= ~((1ULL) << (*bit)); - return 0; + *bit = __builtin_clzll(*val); + *val &= ~((1ULL) << (*bit)); + return 0; } #ifdef DEBUG @@ -238,11 +227,10 @@ int arch_clzll(uint64_t *val, uint32_t *bit) * @return None *******************************************************************************/ -void check_failed(uint8_t *file, uint32_t line) -{ - /* Infinite loop */ - while (1) - ; +void check_failed(uint8_t *file, uint32_t line) { + /* Infinite loop */ + while (1) + ; } #endif /* DEBUG */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/partition/partition.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/partition/partition.c index 673dcbe88b..a96f0b593d 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/partition/partition.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/partition/partition.c @@ -1,42 +1,42 @@ /** - ****************************************************************************** - * @file partition.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2019 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file partition.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2019 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "partition.h" -#include "softcrc.h" #include "bflb_platform.h" +#include "softcrc.h" /** @addtogroup BFLB_Common_Driver * @{ @@ -61,9 +61,9 @@ /** @defgroup PARTITION_Private_Variables * @{ */ -p_pt_table_flash_erase gp_pt_table_flash_erase = NULL; -p_pt_table_flash_write gp_pt_table_flash_write = NULL; -p_pt_table_flash_read gp_pt_table_flash_read = NULL; +p_pt_table_flash_erase gp_pt_table_flash_erase = NULL; +p_pt_table_flash_write gp_pt_table_flash_write = NULL; +p_pt_table_flash_read gp_pt_table_flash_read = NULL; pt_table_iap_param_type p_iap_param; /*@} end of group PARTITION_Private_Variables */ @@ -86,44 +86,42 @@ extern int main(void); */ /****************************************************************************/ /** - * @brief Judge partition table valid - * - * @param ptStuff: Partition table stuff pointer - * - * @return 0 for invalid and 1 for valid - * -*******************************************************************************/ -static uint8_t pt_table_valid(pt_table_stuff_config *pt_stuff) -{ - pt_table_config *pt_table = &pt_stuff->pt_table; - pt_table_entry_config *pt_entries = pt_stuff->pt_entries; - uint32_t *p_crc32; - uint32_t entriesLen = sizeof(pt_table_entry_config) * pt_table->entryCnt; - - if (pt_table->magicCode == BFLB_PT_MAGIC_CODE) { - if (pt_table->entryCnt > PT_ENTRY_MAX) { - MSG("PT Entry Count Error\r\n"); - return 0; - } - - if (pt_table->crc32 != - BFLB_Soft_CRC32((uint8_t *)pt_table, sizeof(pt_table_config) - 4)) { - MSG("PT CRC Error\r\n"); - return 0; - } - - /* ToDo it is a trap here, when entryCnt > 8, crc32 will overflow, comment by zhangcheng */ - p_crc32 = (uint32_t *)((uintptr_t)pt_entries + entriesLen); - - if (*p_crc32 != BFLB_Soft_CRC32((uint8_t *)pt_entries, entriesLen)) { - MSG("PT Entry CRC Error\r\n"); - return 0; - } - - return 1; + * @brief Judge partition table valid + * + * @param ptStuff: Partition table stuff pointer + * + * @return 0 for invalid and 1 for valid + * + *******************************************************************************/ +static uint8_t pt_table_valid(pt_table_stuff_config *pt_stuff) { + pt_table_config *pt_table = &pt_stuff->pt_table; + pt_table_entry_config *pt_entries = pt_stuff->pt_entries; + uint32_t *p_crc32; + uint32_t entriesLen = sizeof(pt_table_entry_config) * pt_table->entryCnt; + + if (pt_table->magicCode == BFLB_PT_MAGIC_CODE) { + if (pt_table->entryCnt > PT_ENTRY_MAX) { + MSG("PT Entry Count Error\r\n"); + return 0; } - return 0; + if (pt_table->crc32 != BFLB_Soft_CRC32((uint8_t *)pt_table, sizeof(pt_table_config) - 4)) { + MSG("PT CRC Error\r\n"); + return 0; + } + + /* ToDo it is a trap here, when entryCnt > 8, crc32 will overflow, comment by zhangcheng */ + p_crc32 = (uint32_t *)((uintptr_t)pt_entries + entriesLen); + + if (*p_crc32 != BFLB_Soft_CRC32((uint8_t *)pt_entries, entriesLen)) { + MSG("PT Entry CRC Error\r\n"); + return 0; + } + + return 1; + } + + return 0; } /*@} end of group PARTITION_Private_Functions */ @@ -133,408 +131,392 @@ static uint8_t pt_table_valid(pt_table_stuff_config *pt_stuff) */ /****************************************************************************/ /** - * @brief Register partition flash read write erase fucntion - * - * @param erase: Flash erase function - * @param write: Flash write function - * @param read: Flash read function - * - * @return None - * -*******************************************************************************/ -void pt_table_set_flash_operation(p_pt_table_flash_erase erase, p_pt_table_flash_write write, p_pt_table_flash_read read) -{ - gp_pt_table_flash_erase = erase; - gp_pt_table_flash_write = write; - gp_pt_table_flash_read = read; + * @brief Register partition flash read write erase fucntion + * + * @param erase: Flash erase function + * @param write: Flash write function + * @param read: Flash read function + * + * @return None + * + *******************************************************************************/ +void pt_table_set_flash_operation(p_pt_table_flash_erase erase, p_pt_table_flash_write write, p_pt_table_flash_read read) { + gp_pt_table_flash_erase = erase; + gp_pt_table_flash_write = write; + gp_pt_table_flash_read = read; } /****************************************************************************/ /** - * @brief Get active partition table whole stuff - * - * @param ptStuff[2]: Partition table stuff pointer - * - * @return Active partition table ID - * -*******************************************************************************/ -pt_table_id_type pt_table_get_active_partition_need_lock(pt_table_stuff_config ptStuff[2]) -{ - uint32_t pt_valid[2] = { 0, 0 }; - pt_table_id_type activePtID; - - if (ptStuff == NULL) { - return PT_TABLE_ID_INVALID; - } - - activePtID = PT_TABLE_ID_INVALID; - - gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&ptStuff[0], sizeof(pt_table_stuff_config)); - pt_valid[0] = pt_table_valid(&ptStuff[0]); - - gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&ptStuff[1], sizeof(pt_table_stuff_config)); - pt_valid[1] = pt_table_valid(&ptStuff[1]); - - if (pt_valid[0] == 1 && pt_valid[1] == 1) { - if (ptStuff[0].pt_table.age >= ptStuff[1].pt_table.age) { - activePtID = PT_TABLE_ID_0; - } else { - activePtID = PT_TABLE_ID_1; - } - } else if (pt_valid[0] == 1) { - activePtID = PT_TABLE_ID_0; - } else if (pt_valid[1] == 1) { - activePtID = PT_TABLE_ID_1; + * @brief Get active partition table whole stuff + * + * @param ptStuff[2]: Partition table stuff pointer + * + * @return Active partition table ID + * + *******************************************************************************/ +pt_table_id_type pt_table_get_active_partition_need_lock(pt_table_stuff_config ptStuff[2]) { + uint32_t pt_valid[2] = {0, 0}; + pt_table_id_type activePtID; + + if (ptStuff == NULL) { + return PT_TABLE_ID_INVALID; + } + + activePtID = PT_TABLE_ID_INVALID; + + gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&ptStuff[0], sizeof(pt_table_stuff_config)); + pt_valid[0] = pt_table_valid(&ptStuff[0]); + + gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&ptStuff[1], sizeof(pt_table_stuff_config)); + pt_valid[1] = pt_table_valid(&ptStuff[1]); + + if (pt_valid[0] == 1 && pt_valid[1] == 1) { + if (ptStuff[0].pt_table.age >= ptStuff[1].pt_table.age) { + activePtID = PT_TABLE_ID_0; + } else { + activePtID = PT_TABLE_ID_1; } + } else if (pt_valid[0] == 1) { + activePtID = PT_TABLE_ID_0; + } else if (pt_valid[1] == 1) { + activePtID = PT_TABLE_ID_1; + } - return activePtID; + return activePtID; } /****************************************************************************/ /** - * @brief Get partition entry according to entry ID - * - * @param ptStuff: Partition table stuff pointer - * @param type: Type of partition entry - * @param ptEntry: Partition entry pointer to store read data - * - * @return PT_ERROR_SUCCESS or PT_ERROR_ENTRY_NOT_FOUND or PT_ERROR_PARAMETER - * -*******************************************************************************/ -pt_table_error_type pt_table_get_active_entries_by_id(pt_table_stuff_config *pt_stuff, - pt_table_entry_type type, - pt_table_entry_config *pt_entry) -{ - uint32_t i = 0; - - if (pt_stuff == NULL || pt_entry == NULL) { - return PT_ERROR_PARAMETER; - } - - for (i = 0; i < pt_stuff->pt_table.entryCnt; i++) { - if (pt_stuff->pt_entries[i].type == type) { - ARCH_MemCpy_Fast(pt_entry, &pt_stuff->pt_entries[i], sizeof(pt_table_entry_config)); - return PT_ERROR_SUCCESS; - } + * @brief Get partition entry according to entry ID + * + * @param ptStuff: Partition table stuff pointer + * @param type: Type of partition entry + * @param ptEntry: Partition entry pointer to store read data + * + * @return PT_ERROR_SUCCESS or PT_ERROR_ENTRY_NOT_FOUND or PT_ERROR_PARAMETER + * + *******************************************************************************/ +pt_table_error_type pt_table_get_active_entries_by_id(pt_table_stuff_config *pt_stuff, pt_table_entry_type type, pt_table_entry_config *pt_entry) { + uint32_t i = 0; + + if (pt_stuff == NULL || pt_entry == NULL) { + return PT_ERROR_PARAMETER; + } + + for (i = 0; i < pt_stuff->pt_table.entryCnt; i++) { + if (pt_stuff->pt_entries[i].type == type) { + ARCH_MemCpy_Fast(pt_entry, &pt_stuff->pt_entries[i], sizeof(pt_table_entry_config)); + return PT_ERROR_SUCCESS; } + } - return PT_ERROR_ENTRY_NOT_FOUND; + return PT_ERROR_ENTRY_NOT_FOUND; } /****************************************************************************/ /** - * @brief Get partition entry according to entry name - * - * @param ptStuff: Partition table stuff pointer - * @param name: Name of partition entry - * @param ptEntry: Partition entry pointer to store read data - * - * @return PT_ERROR_SUCCESS or PT_ERROR_ENTRY_NOT_FOUND or PT_ERROR_PARAMETER - * -*******************************************************************************/ -pt_table_error_type pt_table_get_active_entries_by_name(pt_table_stuff_config *pt_stuff, - uint8_t *name, - pt_table_entry_config *pt_entry) -{ - uint32_t i = 0; - uint32_t len = strlen((char *)name); - - if (pt_stuff == NULL || pt_entry == NULL) { - return PT_ERROR_PARAMETER; - } - - for (i = 0; i < pt_stuff->pt_table.entryCnt; i++) { - if (strlen((char *)pt_stuff->pt_entries[i].name) == len && - memcmp((char *)pt_stuff->pt_entries[i].name, (char *)name, len) == 0) { - ARCH_MemCpy_Fast(pt_entry, &pt_stuff->pt_entries[i], sizeof(pt_table_entry_config)); - return PT_ERROR_SUCCESS; - } + * @brief Get partition entry according to entry name + * + * @param ptStuff: Partition table stuff pointer + * @param name: Name of partition entry + * @param ptEntry: Partition entry pointer to store read data + * + * @return PT_ERROR_SUCCESS or PT_ERROR_ENTRY_NOT_FOUND or PT_ERROR_PARAMETER + * + *******************************************************************************/ +pt_table_error_type pt_table_get_active_entries_by_name(pt_table_stuff_config *pt_stuff, uint8_t *name, pt_table_entry_config *pt_entry) { + uint32_t i = 0; + uint32_t len = strlen((char *)name); + + if (pt_stuff == NULL || pt_entry == NULL) { + return PT_ERROR_PARAMETER; + } + + for (i = 0; i < pt_stuff->pt_table.entryCnt; i++) { + if (strlen((char *)pt_stuff->pt_entries[i].name) == len && memcmp((char *)pt_stuff->pt_entries[i].name, (char *)name, len) == 0) { + ARCH_MemCpy_Fast(pt_entry, &pt_stuff->pt_entries[i], sizeof(pt_table_entry_config)); + return PT_ERROR_SUCCESS; } + } - return PT_ERROR_ENTRY_NOT_FOUND; + return PT_ERROR_ENTRY_NOT_FOUND; } /****************************************************************************/ /** - * @brief Update partition entry - * - * @param targetTableID: Target partition table to update - * @param ptStuff: Partition table stuff pointer - * @param ptEntry: Partition entry pointer to update - * - * @return Partition update result - * -*******************************************************************************/ -pt_table_error_type pt_table_update_entry(pt_table_id_type target_table_id, - pt_table_stuff_config *pt_stuff, - pt_table_entry_config *pt_entry) -{ - uint32_t i = 0; - BL_Err_Type ret; - uint32_t write_addr; - uint32_t entries_len; - pt_table_config *pt_table; - pt_table_entry_config *pt_entries; - uint32_t *crc32; - - if (pt_entry == NULL || pt_stuff == NULL) { - return PT_ERROR_PARAMETER; + * @brief Update partition entry + * + * @param targetTableID: Target partition table to update + * @param ptStuff: Partition table stuff pointer + * @param ptEntry: Partition entry pointer to update + * + * @return Partition update result + * + *******************************************************************************/ +pt_table_error_type pt_table_update_entry(pt_table_id_type target_table_id, pt_table_stuff_config *pt_stuff, pt_table_entry_config *pt_entry) { + uint32_t i = 0; + BL_Err_Type ret; + uint32_t write_addr; + uint32_t entries_len; + pt_table_config *pt_table; + pt_table_entry_config *pt_entries; + uint32_t *crc32; + + if (pt_entry == NULL || pt_stuff == NULL) { + return PT_ERROR_PARAMETER; + } + + pt_table = &pt_stuff->pt_table; + pt_entries = pt_stuff->pt_entries; + + if (target_table_id == PT_TABLE_ID_INVALID) { + return PT_ERROR_TABLE_NOT_VALID; + } + + if (target_table_id == PT_TABLE_ID_0) { + write_addr = BFLB_PT_TABLE0_ADDRESS; + } else { + write_addr = BFLB_PT_TABLE1_ADDRESS; + } + + for (i = 0; i < pt_table->entryCnt; i++) { + if (pt_entries[i].type == pt_entry->type) { + ARCH_MemCpy_Fast(&pt_entries[i], pt_entry, sizeof(pt_table_entry_config)); + break; } + } - pt_table = &pt_stuff->pt_table; - pt_entries = pt_stuff->pt_entries; - - if (target_table_id == PT_TABLE_ID_INVALID) { - return PT_ERROR_TABLE_NOT_VALID; - } - - if (target_table_id == PT_TABLE_ID_0) { - write_addr = BFLB_PT_TABLE0_ADDRESS; + if (i == pt_table->entryCnt) { + /* Not found this entry ,add new one */ + if (pt_table->entryCnt < PT_ENTRY_MAX) { + ARCH_MemCpy_Fast(&pt_entries[pt_table->entryCnt], pt_entry, sizeof(pt_table_entry_config)); + pt_table->entryCnt++; } else { - write_addr = BFLB_PT_TABLE1_ADDRESS; - } - - for (i = 0; i < pt_table->entryCnt; i++) { - if (pt_entries[i].type == pt_entry->type) { - ARCH_MemCpy_Fast(&pt_entries[i], pt_entry, sizeof(pt_table_entry_config)); - break; - } - } - - if (i == pt_table->entryCnt) { - /* Not found this entry ,add new one */ - if (pt_table->entryCnt < PT_ENTRY_MAX) { - ARCH_MemCpy_Fast(&pt_entries[pt_table->entryCnt], pt_entry, sizeof(pt_table_entry_config)); - pt_table->entryCnt++; - } else { - return PT_ERROR_ENTRY_UPDATE_FAIL; - } + return PT_ERROR_ENTRY_UPDATE_FAIL; } + } - /* Prepare write back to flash */ - /* Update age */ - pt_table->age++; - pt_table->crc32 = BFLB_Soft_CRC32((uint8_t *)pt_table, sizeof(pt_table_config) - 4); + /* Prepare write back to flash */ + /* Update age */ + pt_table->age++; + pt_table->crc32 = BFLB_Soft_CRC32((uint8_t *)pt_table, sizeof(pt_table_config) - 4); - /* Update entries CRC */ - entries_len = pt_table->entryCnt * sizeof(pt_table_entry_config); - crc32 = (uint32_t *)((uintptr_t)pt_entries + entries_len); - *crc32 = BFLB_Soft_CRC32((uint8_t *)&pt_entries[0], entries_len); + /* Update entries CRC */ + entries_len = pt_table->entryCnt * sizeof(pt_table_entry_config); + crc32 = (uint32_t *)((uintptr_t)pt_entries + entries_len); + *crc32 = BFLB_Soft_CRC32((uint8_t *)&pt_entries[0], entries_len); - /* Write back to flash */ - /* Erase flash first */ - //ret = gp_pt_table_flash_erase(write_addr, write_addr + sizeof(pt_table_config) + entries_len + 4 - 1); - ret = gp_pt_table_flash_erase(write_addr, sizeof(pt_table_config) + entries_len + 4); + /* Write back to flash */ + /* Erase flash first */ + // ret = gp_pt_table_flash_erase(write_addr, write_addr + sizeof(pt_table_config) + entries_len + 4 - 1); + ret = gp_pt_table_flash_erase(write_addr, sizeof(pt_table_config) + entries_len + 4); - if (ret != SUCCESS) { - MSG_ERR("Flash Erase error\r\n"); - return PT_ERROR_FALSH_WRITE; - } + if (ret != SUCCESS) { + MSG_ERR("Flash Erase error\r\n"); + return PT_ERROR_FALSH_WRITE; + } - /* Write flash */ - ret = gp_pt_table_flash_write(write_addr, (uint8_t *)pt_stuff, sizeof(pt_table_stuff_config)); + /* Write flash */ + ret = gp_pt_table_flash_write(write_addr, (uint8_t *)pt_stuff, sizeof(pt_table_stuff_config)); - if (ret != SUCCESS) { - MSG_ERR("Flash Write error\r\n"); - return PT_ERROR_FALSH_WRITE; - } + if (ret != SUCCESS) { + MSG_ERR("Flash Write error\r\n"); + return PT_ERROR_FALSH_WRITE; + } - return PT_ERROR_SUCCESS; + return PT_ERROR_SUCCESS; } /****************************************************************************/ /** - * @brief Create partition entry - * - * @param ptID: Partition table ID - * - * @return Partition create result - * -*******************************************************************************/ -pt_table_error_type pt_table_create(pt_table_id_type pt_id) -{ - uint32_t write_addr; - BL_Err_Type ret; - pt_table_config pt_table; - - if (pt_id == PT_TABLE_ID_INVALID) { - return PT_ERROR_TABLE_NOT_VALID; - } - - if (pt_id == PT_TABLE_ID_0) { - write_addr = BFLB_PT_TABLE0_ADDRESS; - } else { - write_addr = BFLB_PT_TABLE1_ADDRESS; - } - - /* Prepare write back to flash */ - pt_table.magicCode = BFLB_PT_MAGIC_CODE; - pt_table.version = 0; - pt_table.entryCnt = 0; - pt_table.age = 0; - pt_table.crc32 = BFLB_Soft_CRC32((uint8_t *)&pt_table, sizeof(pt_table_config) - 4); - /* Write back to flash */ - //ret = gp_pt_table_flash_erase(write_addr, write_addr + sizeof(pt_table_config) - 1); - ret = gp_pt_table_flash_erase(write_addr,sizeof(pt_table_config)); - - if (ret != SUCCESS) { - MSG_ERR("Flash Erase error\r\n"); - return PT_ERROR_FALSH_ERASE; - } - - ret = gp_pt_table_flash_write(write_addr, (uint8_t *)&pt_table, sizeof(pt_table_config)); + * @brief Create partition entry + * + * @param ptID: Partition table ID + * + * @return Partition create result + * + *******************************************************************************/ +pt_table_error_type pt_table_create(pt_table_id_type pt_id) { + uint32_t write_addr; + BL_Err_Type ret; + pt_table_config pt_table; + + if (pt_id == PT_TABLE_ID_INVALID) { + return PT_ERROR_TABLE_NOT_VALID; + } + + if (pt_id == PT_TABLE_ID_0) { + write_addr = BFLB_PT_TABLE0_ADDRESS; + } else { + write_addr = BFLB_PT_TABLE1_ADDRESS; + } + + /* Prepare write back to flash */ + pt_table.magicCode = BFLB_PT_MAGIC_CODE; + pt_table.version = 0; + pt_table.entryCnt = 0; + pt_table.age = 0; + pt_table.crc32 = BFLB_Soft_CRC32((uint8_t *)&pt_table, sizeof(pt_table_config) - 4); + /* Write back to flash */ + // ret = gp_pt_table_flash_erase(write_addr, write_addr + sizeof(pt_table_config) - 1); + ret = gp_pt_table_flash_erase(write_addr, sizeof(pt_table_config)); + + if (ret != SUCCESS) { + MSG_ERR("Flash Erase error\r\n"); + return PT_ERROR_FALSH_ERASE; + } + + ret = gp_pt_table_flash_write(write_addr, (uint8_t *)&pt_table, sizeof(pt_table_config)); + + if (ret != SUCCESS) { + MSG_ERR("Flash Write error\r\n"); + return PT_ERROR_FALSH_WRITE; + } + + return PT_ERROR_SUCCESS; +} - if (ret != SUCCESS) { - MSG_ERR("Flash Write error\r\n"); - return PT_ERROR_FALSH_WRITE; +pt_table_error_type pt_table_dump(void) { + uint32_t pt_valid[2] = {0, 0}; + pt_table_stuff_config pt_stuff[2]; + + gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff[0], sizeof(pt_table_stuff_config)); + pt_valid[0] = pt_table_valid(&pt_stuff[0]); + + gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff[1], sizeof(pt_table_stuff_config)); + pt_valid[1] = pt_table_valid(&pt_stuff[1]); + + if (pt_valid[0]) { + MSG("PT TABLE0 valid\r\n"); + } else { + MSG("PT TABLE0 invalid\r\n"); + } + + if (pt_valid[1]) { + MSG("PT TABLE1 valid\r\n"); + } else { + MSG("PT TABLE1 invalid\r\n"); + } + + for (int i = 0; i < 2; i++) { + if (pt_valid[i] == 1) { + MSG("ptStuff[%d].pt_table.magicCode 0x%08x\r\n", i, pt_stuff[i].pt_table.magicCode); + MSG("ptStuff[%d].pt_table.version 0x%08x\r\n", i, pt_stuff[i].pt_table.version); + MSG("ptStuff[%d].pt_table.entryCnt 0x%08x\r\n", i, pt_stuff[i].pt_table.entryCnt); + MSG("ptStuff[%d].pt_table.age 0x%08x\r\n", i, pt_stuff[i].pt_table.age); + MSG("ptStuff[%d].pt_table.crc32 0x%08x\r\n", i, pt_stuff[i].pt_table.crc32); + + for (int j = 0; j < pt_stuff[i].pt_table.entryCnt; j++) { + MSG("ptStuff[%d].pt_entries[%d].type 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].type); + MSG("ptStuff[%d].pt_entries[%d].device 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].device); + MSG("ptStuff[%d].pt_entries[%d].active_index 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].active_index); + MSG("ptStuff[%d].pt_entries[%d].Address[0] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].start_address[0]); + MSG("ptStuff[%d].pt_entries[%d].Address[1] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].start_address[1]); + MSG("ptStuff[%d].pt_entries[%d].maxLen[0] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].max_len[0]); + MSG("ptStuff[%d].pt_entries[%d].maxLen[1] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].max_len[1]); + MSG("ptStuff[%d].pt_entries[%d].len 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].len); + MSG("ptStuff[%d].pt_entries[%d].age 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].age); + } } + } - return PT_ERROR_SUCCESS; + return PT_ERROR_SUCCESS; } -pt_table_error_type pt_table_dump(void) -{ - uint32_t pt_valid[2] = { 0, 0 }; - pt_table_stuff_config pt_stuff[2]; +pt_table_error_type pt_table_get_iap_para(pt_table_iap_param_type *para) { + uint32_t pt_valid[2] = {0, 0}; + pt_table_stuff_config pt_stuff[2]; + uint8_t active_index; - gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff[0], sizeof(pt_table_stuff_config)); - pt_valid[0] = pt_table_valid(&pt_stuff[0]); + gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff[0], sizeof(pt_table_stuff_config)); + pt_valid[0] = pt_table_valid(&pt_stuff[0]); - gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff[1], sizeof(pt_table_stuff_config)); - pt_valid[1] = pt_table_valid(&pt_stuff[1]); + gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff[1], sizeof(pt_table_stuff_config)); + pt_valid[1] = pt_table_valid(&pt_stuff[1]); - if (pt_valid[0]) { - MSG("PT TABLE0 valid\r\n"); - } else { - MSG("PT TABLE0 invalid\r\n"); - } + if ((pt_valid[0] == 1) && (pt_valid[1] == 1)) { + if (pt_stuff[0].pt_table.age >= pt_stuff[1].pt_table.age) { + active_index = pt_stuff[0].pt_entries[0].active_index; + para->iap_write_addr = para->iap_start_addr = pt_stuff[0].pt_entries[0].start_address[!(active_index & 0x01)]; + para->inactive_index = !(active_index & 0x01); + para->inactive_table_index = 1; - if (pt_valid[1]) { - MSG("PT TABLE1 valid\r\n"); } else { - MSG("PT TABLE1 invalid\r\n"); - } - - for (int i = 0; i < 2; i++) { - if (pt_valid[i] == 1) { - MSG("ptStuff[%d].pt_table.magicCode 0x%08x\r\n", i, pt_stuff[i].pt_table.magicCode); - MSG("ptStuff[%d].pt_table.version 0x%08x\r\n", i, pt_stuff[i].pt_table.version); - MSG("ptStuff[%d].pt_table.entryCnt 0x%08x\r\n", i, pt_stuff[i].pt_table.entryCnt); - MSG("ptStuff[%d].pt_table.age 0x%08x\r\n", i, pt_stuff[i].pt_table.age); - MSG("ptStuff[%d].pt_table.crc32 0x%08x\r\n", i, pt_stuff[i].pt_table.crc32); - - for (int j = 0; j < pt_stuff[i].pt_table.entryCnt; j++) { - MSG("ptStuff[%d].pt_entries[%d].type 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].type); - MSG("ptStuff[%d].pt_entries[%d].device 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].device); - MSG("ptStuff[%d].pt_entries[%d].active_index 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].active_index); - MSG("ptStuff[%d].pt_entries[%d].Address[0] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].start_address[0]); - MSG("ptStuff[%d].pt_entries[%d].Address[1] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].start_address[1]); - MSG("ptStuff[%d].pt_entries[%d].maxLen[0] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].max_len[0]); - MSG("ptStuff[%d].pt_entries[%d].maxLen[1] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].max_len[1]); - MSG("ptStuff[%d].pt_entries[%d].len 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].len); - MSG("ptStuff[%d].pt_entries[%d].age 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].age); - } - } + active_index = pt_stuff[1].pt_entries[0].active_index; + para->iap_write_addr = para->iap_start_addr = pt_stuff[1].pt_entries[0].start_address[!(active_index & 0x01)]; + para->inactive_index = !(active_index & 0x01); + para->inactive_table_index = 0; } - return PT_ERROR_SUCCESS; + } else if (pt_valid[1] == 1) { + active_index = pt_stuff[1].pt_entries[0].active_index; + para->iap_write_addr = para->iap_start_addr = pt_stuff[1].pt_entries[0].start_address[!(active_index & 0x01)]; + para->inactive_index = !(active_index & 0x01); + para->inactive_table_index = 0; + } else if (pt_valid[0] == 1) { + active_index = pt_stuff[0].pt_entries[0].active_index; + para->iap_write_addr = para->iap_start_addr = pt_stuff[0].pt_entries[0].start_address[!(active_index & 0x01)]; + para->inactive_index = !(active_index & 0x01); + para->inactive_table_index = 1; + } else { + return PT_ERROR_TABLE_NOT_VALID; + } + + MSG("inactive_table_index %d, inactive index %d , IAP start addr %08x \r\n", para->inactive_table_index, para->inactive_index, para->iap_start_addr); + return PT_ERROR_SUCCESS; } -pt_table_error_type pt_table_get_iap_para(pt_table_iap_param_type *para) -{ - uint32_t pt_valid[2] = { 0, 0 }; - pt_table_stuff_config pt_stuff[2]; - uint8_t active_index; - - gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff[0], sizeof(pt_table_stuff_config)); - pt_valid[0] = pt_table_valid(&pt_stuff[0]); - - gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff[1], sizeof(pt_table_stuff_config)); - pt_valid[1] = pt_table_valid(&pt_stuff[1]); - - if ((pt_valid[0] == 1) && (pt_valid[1] == 1)) { - if (pt_stuff[0].pt_table.age >= pt_stuff[1].pt_table.age) { - active_index = pt_stuff[0].pt_entries[0].active_index; - para->iap_write_addr = para->iap_start_addr = pt_stuff[0].pt_entries[0].start_address[!(active_index & 0x01)]; - para->inactive_index = !(active_index & 0x01); - para->inactive_table_index = 1; - - } else { - active_index = pt_stuff[1].pt_entries[0].active_index; - para->iap_write_addr = para->iap_start_addr = pt_stuff[1].pt_entries[0].start_address[!(active_index & 0x01)]; - para->inactive_index = !(active_index & 0x01); - para->inactive_table_index = 0; - } - - } else if (pt_valid[1] == 1) { - active_index = pt_stuff[1].pt_entries[0].active_index; - para->iap_write_addr = para->iap_start_addr = pt_stuff[1].pt_entries[0].start_address[!(active_index & 0x01)]; - para->inactive_index = !(active_index & 0x01); - para->inactive_table_index = 0; - } else if (pt_valid[0] == 1) { - active_index = pt_stuff[0].pt_entries[0].active_index; - para->iap_write_addr = para->iap_start_addr = pt_stuff[0].pt_entries[0].start_address[!(active_index & 0x01)]; - para->inactive_index = !(active_index & 0x01); - para->inactive_table_index = 1; - } else { - return PT_ERROR_TABLE_NOT_VALID; +pt_table_error_type pt_table_set_iap_para(pt_table_iap_param_type *para) { + pt_table_stuff_config pt_stuff, pt_stuff_write; + int32_t ret; + uint32_t *p_crc32; + uint32_t entries_len; + + if (para->inactive_table_index == 1) { + gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff, sizeof(pt_table_stuff_config)); + } else if (para->inactive_table_index == 0) { + gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff, sizeof(pt_table_stuff_config)); + } + + ARCH_MemCpy_Fast((void *)&pt_stuff_write, (void *)&pt_stuff, sizeof(pt_table_stuff_config)); + pt_stuff_write.pt_table.age += 1; + pt_stuff_write.pt_entries[0].active_index = !(pt_stuff_write.pt_entries[0].active_index & 0x01); + pt_stuff_write.pt_table.crc32 = BFLB_Soft_CRC32((uint8_t *)&pt_stuff_write, sizeof(pt_table_config) - 4); + entries_len = sizeof(pt_table_entry_config) * pt_stuff_write.pt_table.entryCnt; + // pt_stuff_write.crc32 = BFLB_Soft_CRC32((uint8_t*)pt_stuff_write.pt_entries,entries_len); + p_crc32 = (uint32_t *)((uintptr_t)pt_stuff_write.pt_entries + entries_len); + *p_crc32 = BFLB_Soft_CRC32((uint8_t *)pt_stuff_write.pt_entries, entries_len); + + if (para->inactive_table_index == 1) { + // ret = gp_pt_table_flash_erase(BFLB_PT_TABLE1_ADDRESS, BFLB_PT_TABLE1_ADDRESS + sizeof(pt_table_stuff_config) - 1); + ret = gp_pt_table_flash_erase(BFLB_PT_TABLE1_ADDRESS, sizeof(pt_table_stuff_config)); + + if (ret != SUCCESS) { + MSG_ERR("Flash Erase error\r\n"); + return PT_ERROR_FALSH_ERASE; } - MSG("inactive_table_index %d, inactive index %d , IAP start addr %08x \r\n", para->inactive_table_index, para->inactive_index, para->iap_start_addr); - return PT_ERROR_SUCCESS; -} + ret = gp_pt_table_flash_write(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff_write, sizeof(pt_table_stuff_config)); + + if (ret != SUCCESS) { + MSG_ERR("Flash Write error\r\n"); + return PT_ERROR_FALSH_WRITE; + } + } else if (para->inactive_table_index == 0) { + // ret = gp_pt_table_flash_erase(BFLB_PT_TABLE0_ADDRESS, BFLB_PT_TABLE0_ADDRESS + sizeof(pt_table_stuff_config) - 1); + ret = gp_pt_table_flash_erase(BFLB_PT_TABLE0_ADDRESS, sizeof(pt_table_stuff_config)); -pt_table_error_type pt_table_set_iap_para(pt_table_iap_param_type *para) -{ - pt_table_stuff_config pt_stuff, pt_stuff_write; - int32_t ret; - uint32_t *p_crc32; - uint32_t entries_len; - - if (para->inactive_table_index == 1) { - gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff, sizeof(pt_table_stuff_config)); - } else if (para->inactive_table_index == 0) { - gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff, sizeof(pt_table_stuff_config)); + if (ret != SUCCESS) { + MSG_ERR("Flash Erase error\r\n"); + return PT_ERROR_FALSH_ERASE; } - ARCH_MemCpy_Fast((void *)&pt_stuff_write, (void *)&pt_stuff, sizeof(pt_table_stuff_config)); - pt_stuff_write.pt_table.age += 1; - pt_stuff_write.pt_entries[0].active_index = !(pt_stuff_write.pt_entries[0].active_index & 0x01); - pt_stuff_write.pt_table.crc32 = BFLB_Soft_CRC32((uint8_t *)&pt_stuff_write, sizeof(pt_table_config) - 4); - entries_len = sizeof(pt_table_entry_config) * pt_stuff_write.pt_table.entryCnt; - //pt_stuff_write.crc32 = BFLB_Soft_CRC32((uint8_t*)pt_stuff_write.pt_entries,entries_len); - p_crc32 = (uint32_t *)((uintptr_t)pt_stuff_write.pt_entries + entries_len); - *p_crc32 = BFLB_Soft_CRC32((uint8_t *)pt_stuff_write.pt_entries, entries_len); - - if (para->inactive_table_index == 1) { - //ret = gp_pt_table_flash_erase(BFLB_PT_TABLE1_ADDRESS, BFLB_PT_TABLE1_ADDRESS + sizeof(pt_table_stuff_config) - 1); - ret = gp_pt_table_flash_erase(BFLB_PT_TABLE1_ADDRESS, sizeof(pt_table_stuff_config)); - - if (ret != SUCCESS) { - MSG_ERR("Flash Erase error\r\n"); - return PT_ERROR_FALSH_ERASE; - } - - ret = gp_pt_table_flash_write(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff_write, sizeof(pt_table_stuff_config)); - - if (ret != SUCCESS) { - MSG_ERR("Flash Write error\r\n"); - return PT_ERROR_FALSH_WRITE; - } - } else if (para->inactive_table_index == 0) { - //ret = gp_pt_table_flash_erase(BFLB_PT_TABLE0_ADDRESS, BFLB_PT_TABLE0_ADDRESS + sizeof(pt_table_stuff_config) - 1); - ret = gp_pt_table_flash_erase(BFLB_PT_TABLE0_ADDRESS, sizeof(pt_table_stuff_config)); - - if (ret != SUCCESS) { - MSG_ERR("Flash Erase error\r\n"); - return PT_ERROR_FALSH_ERASE; - } - - ret = gp_pt_table_flash_write(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff_write, sizeof(pt_table_stuff_config)); - - if (ret != SUCCESS) { - MSG_ERR("Flash Write error\r\n"); - return PT_ERROR_FALSH_WRITE; - } + ret = gp_pt_table_flash_write(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff_write, sizeof(pt_table_stuff_config)); + + if (ret != SUCCESS) { + MSG_ERR("Flash Write error\r\n"); + return PT_ERROR_FALSH_WRITE; } + } - MSG("Update pt_table suss\r\n"); - return PT_ERROR_SUCCESS; + MSG("Update pt_table suss\r\n"); + return PT_ERROR_SUCCESS; } /*@} end of group PARTITION_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/pid/pid.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/pid/pid.c index dc0602003e..e5534ce930 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/pid/pid.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/pid/pid.c @@ -23,46 +23,43 @@ #include "pid.h" -void pid_init(pid_alg_t *pid) -{ - pid->set_val = 0.0f; - pid->out_val = 0.0f; +void pid_init(pid_alg_t *pid) { + pid->set_val = 0.0f; + pid->out_val = 0.0f; - pid->last_error = 0.0f; - pid->prev_error = 0.0f; + pid->last_error = 0.0f; + pid->prev_error = 0.0f; - pid->kp = 3.0f; - pid->ki = 0.0f; - pid->kd = 0.0f; + pid->kp = 3.0f; + pid->ki = 0.0f; + pid->kd = 0.0f; - pid->i_error = 0.0f; - pid->sum_error = 0.0f; + pid->i_error = 0.0f; + pid->sum_error = 0.0f; - pid->max_val = 32; - pid->min_val = -32; + pid->max_val = 32; + pid->min_val = -32; } // standard pid -float standard_pid_cal(pid_alg_t *pid, float next_val) -{ - pid->set_val = next_val; - pid->i_error = pid->set_val - pid->out_val; - pid->sum_error += pid->i_error; - pid->out_val = pid->kp * pid->i_error + pid->ki * pid->sum_error + pid->kd * (pid->i_error - pid->last_error); - pid->last_error = pid->i_error; +float standard_pid_cal(pid_alg_t *pid, float next_val) { + pid->set_val = next_val; + pid->i_error = pid->set_val - pid->out_val; + pid->sum_error += pid->i_error; + pid->out_val = pid->kp * pid->i_error + pid->ki * pid->sum_error + pid->kd * (pid->i_error - pid->last_error); + pid->last_error = pid->i_error; - return pid->out_val; + return pid->out_val; } // increment pid -float increment_pid_cal(pid_alg_t *pid, float next_val) -{ - pid->set_val = next_val; - pid->i_error = pid->set_val - pid->out_val; - float increment = pid->kp * (pid->i_error - pid->prev_error) + pid->ki * pid->i_error + pid->kd * (pid->i_error - 2 * pid->prev_error + pid->last_error); - pid->out_val += increment; - pid->last_error = pid->prev_error; - pid->prev_error = pid->i_error; +float increment_pid_cal(pid_alg_t *pid, float next_val) { + pid->set_val = next_val; + pid->i_error = pid->set_val - pid->out_val; + float increment = pid->kp * (pid->i_error - pid->prev_error) + pid->ki * pid->i_error + pid->kd * (pid->i_error - 2 * pid->prev_error + pid->last_error); + pid->out_val += increment; + pid->last_error = pid->prev_error; + pid->prev_error = pid->i_error; - return pid->out_val; + return pid->out_val; } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/ring_buffer/ring_buffer.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/ring_buffer/ring_buffer.c index ec91c71578..4810f819b6 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/ring_buffer/ring_buffer.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/ring_buffer/ring_buffer.c @@ -71,605 +71,582 @@ */ /****************************************************************************/ /** - * @brief Ring buffer init function - * - * @param rbType: Ring buffer type structure pointer - * @param buffer: Pointer of ring buffer - * @param size: Size of ring buffer - * @param lockCb: Ring buffer lock callback function pointer - * @param unlockCb: Ring buffer unlock callback function pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Ring_Buffer_Init(Ring_Buffer_Type *rbType, uint8_t *buffer, uint32_t size, ringBuffer_Lock_Callback *lockCb, ringBuffer_Lock_Callback *unlockCb) -{ - /* Init ring buffer pointer */ - rbType->pointer = buffer; - - /* Init read/write mirror and index */ - rbType->readMirror = 0; - rbType->readIndex = 0; - rbType->writeMirror = 0; - rbType->writeIndex = 0; - - /* Set ring buffer size */ - rbType->size = size; - - /* Set lock and unlock callback function */ - rbType->lock = lockCb; - rbType->unlock = unlockCb; - - return SUCCESS; + * @brief Ring buffer init function + * + * @param rbType: Ring buffer type structure pointer + * @param buffer: Pointer of ring buffer + * @param size: Size of ring buffer + * @param lockCb: Ring buffer lock callback function pointer + * @param unlockCb: Ring buffer unlock callback function pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Ring_Buffer_Init(Ring_Buffer_Type *rbType, uint8_t *buffer, uint32_t size, ringBuffer_Lock_Callback *lockCb, ringBuffer_Lock_Callback *unlockCb) { + /* Init ring buffer pointer */ + rbType->pointer = buffer; + + /* Init read/write mirror and index */ + rbType->readMirror = 0; + rbType->readIndex = 0; + rbType->writeMirror = 0; + rbType->writeIndex = 0; + + /* Set ring buffer size */ + rbType->size = size; + + /* Set lock and unlock callback function */ + rbType->lock = lockCb; + rbType->unlock = unlockCb; + + return SUCCESS; } /****************************************************************************/ /** - * @brief Ring buffer reset function - * - * @param rbType: Ring buffer type structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Ring_Buffer_Reset(Ring_Buffer_Type *rbType) -{ - if (rbType->lock != NULL) { - rbType->lock(); - } - - /* Clear read/write mirror and index */ - rbType->readMirror = 0; - rbType->readIndex = 0; - rbType->writeMirror = 0; - rbType->writeIndex = 0; - - if (rbType->unlock != NULL) { - rbType->unlock(); - } - - return SUCCESS; + * @brief Ring buffer reset function + * + * @param rbType: Ring buffer type structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Ring_Buffer_Reset(Ring_Buffer_Type *rbType) { + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Clear read/write mirror and index */ + rbType->readMirror = 0; + rbType->readIndex = 0; + rbType->writeMirror = 0; + rbType->writeIndex = 0; + + if (rbType->unlock != NULL) { + rbType->unlock(); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief Use callback function to write ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * @param length: Length of data want to write - * @param writeCb: Callback function pointer - * @param parameter: Parameter that callback function may use - * - * @return Length of data actually write - * -*******************************************************************************/ -uint32_t Ring_Buffer_Write_Callback(Ring_Buffer_Type *rbType, uint32_t length, ringBuffer_Write_Callback *writeCb, void *parameter) -{ - uint32_t sizeRemained = Ring_Buffer_Get_Empty_Length(rbType); - - if (writeCb == NULL) { - return 0; + * @brief Use callback function to write ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * @param length: Length of data want to write + * @param writeCb: Callback function pointer + * @param parameter: Parameter that callback function may use + * + * @return Length of data actually write + * + *******************************************************************************/ +uint32_t Ring_Buffer_Write_Callback(Ring_Buffer_Type *rbType, uint32_t length, ringBuffer_Write_Callback *writeCb, void *parameter) { + uint32_t sizeRemained = Ring_Buffer_Get_Empty_Length(rbType); + + if (writeCb == NULL) { + return 0; + } + + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Ring buffer has no space for new data */ + if (sizeRemained == 0) { + if (rbType->unlock != NULL) { + rbType->unlock(); } - if (rbType->lock != NULL) { - rbType->lock(); - } + return 0; + } - /* Ring buffer has no space for new data */ - if (sizeRemained == 0) { - if (rbType->unlock != NULL) { - rbType->unlock(); - } + /* Drop part of data when length out of space remained */ + if (length > sizeRemained) { + length = sizeRemained; + } - return 0; - } + /* Get size of space remained in current mirror */ + sizeRemained = rbType->size - rbType->writeIndex; - /* Drop part of data when length out of space remained */ - if (length > sizeRemained) { - length = sizeRemained; - } - - /* Get size of space remained in current mirror */ - sizeRemained = rbType->size - rbType->writeIndex; - - if (sizeRemained > length) { - /* Space remained is enough for data in current mirror */ - writeCb(parameter, &rbType->pointer[rbType->writeIndex], length); - rbType->writeIndex += length; - } else { - /* Data is divided to two parts with different mirror */ - writeCb(parameter, &rbType->pointer[rbType->writeIndex], sizeRemained); - writeCb(parameter, &rbType->pointer[0], length - sizeRemained); - rbType->writeIndex = length - sizeRemained; - rbType->writeMirror = ~rbType->writeMirror; - } + if (sizeRemained > length) { + /* Space remained is enough for data in current mirror */ + writeCb(parameter, &rbType->pointer[rbType->writeIndex], length); + rbType->writeIndex += length; + } else { + /* Data is divided to two parts with different mirror */ + writeCb(parameter, &rbType->pointer[rbType->writeIndex], sizeRemained); + writeCb(parameter, &rbType->pointer[0], length - sizeRemained); + rbType->writeIndex = length - sizeRemained; + rbType->writeMirror = ~rbType->writeMirror; + } - if (rbType->unlock != NULL) { - rbType->unlock(); - } + if (rbType->unlock != NULL) { + rbType->unlock(); + } - return length; + return length; } /****************************************************************************/ /** - * @brief Copy data from data buffer to ring buffer function - * - * @param parameter: Pointer to source pointer - * @param dest: Ring buffer to write - * @param length: Length of data to write - * - * @return None - * -*******************************************************************************/ -static void Ring_Buffer_Write_Copy(void *parameter, uint8_t *dest, uint32_t length) -{ - uint8_t **src = (uint8_t **)parameter; - - ARCH_MemCpy_Fast(dest, *src, length); - *src += length; + * @brief Copy data from data buffer to ring buffer function + * + * @param parameter: Pointer to source pointer + * @param dest: Ring buffer to write + * @param length: Length of data to write + * + * @return None + * + *******************************************************************************/ +static void Ring_Buffer_Write_Copy(void *parameter, uint8_t *dest, uint32_t length) { + uint8_t **src = (uint8_t **)parameter; + + ARCH_MemCpy_Fast(dest, *src, length); + *src += length; } /****************************************************************************/ /** - * @brief Write ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * @param data: Data to write - * @param length: Length of data - * - * @return Length of data writted actually - * -*******************************************************************************/ -uint32_t Ring_Buffer_Write(Ring_Buffer_Type *rbType, const uint8_t *data, uint32_t length) -{ - return Ring_Buffer_Write_Callback(rbType, length, Ring_Buffer_Write_Copy, &data); -} + * @brief Write ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * @param data: Data to write + * @param length: Length of data + * + * @return Length of data writted actually + * + *******************************************************************************/ +uint32_t Ring_Buffer_Write(Ring_Buffer_Type *rbType, const uint8_t *data, uint32_t length) { return Ring_Buffer_Write_Callback(rbType, length, Ring_Buffer_Write_Copy, &data); } /****************************************************************************/ /** - * @brief Write 1 byte to ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * @param data: Data to write - * - * @return Length of data writted actually - * -*******************************************************************************/ -uint32_t Ring_Buffer_Write_Byte(Ring_Buffer_Type *rbType, const uint8_t data) -{ - if (rbType->lock != NULL) { - rbType->lock(); + * @brief Write 1 byte to ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * @param data: Data to write + * + * @return Length of data writted actually + * + *******************************************************************************/ +uint32_t Ring_Buffer_Write_Byte(Ring_Buffer_Type *rbType, const uint8_t data) { + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Ring buffer has no space for new data */ + if (!Ring_Buffer_Get_Empty_Length(rbType)) { + if (rbType->unlock != NULL) { + rbType->unlock(); } - /* Ring buffer has no space for new data */ - if (!Ring_Buffer_Get_Empty_Length(rbType)) { - if (rbType->unlock != NULL) { - rbType->unlock(); - } + return 0; + } - return 0; - } + rbType->pointer[rbType->writeIndex] = data; - rbType->pointer[rbType->writeIndex] = data; - - /* Judge to change index and mirror */ - if (rbType->writeIndex != (rbType->size - 1)) { - rbType->writeIndex++; - } else { - rbType->writeIndex = 0; - rbType->writeMirror = ~rbType->writeMirror; - } + /* Judge to change index and mirror */ + if (rbType->writeIndex != (rbType->size - 1)) { + rbType->writeIndex++; + } else { + rbType->writeIndex = 0; + rbType->writeMirror = ~rbType->writeMirror; + } - if (rbType->unlock != NULL) { - rbType->unlock(); - } + if (rbType->unlock != NULL) { + rbType->unlock(); + } - return 1; + return 1; } /****************************************************************************/ /** - * @brief Write ring buffer function, old data will be covered by new data when ring buffer is - * full - * - * @param rbType: Ring buffer type structure pointer - * @param data: Data to write - * @param length: Length of data - * - * @return Length of data writted actually - * -*******************************************************************************/ -uint32_t Ring_Buffer_Write_Force(Ring_Buffer_Type *rbType, const uint8_t *data, uint32_t length) -{ - uint32_t sizeRemained = Ring_Buffer_Get_Empty_Length(rbType); - uint32_t indexRemained = rbType->size - rbType->writeIndex; - - if (rbType->lock != NULL) { - rbType->lock(); + * @brief Write ring buffer function, old data will be covered by new data when ring buffer is + * full + * + * @param rbType: Ring buffer type structure pointer + * @param data: Data to write + * @param length: Length of data + * + * @return Length of data writted actually + * + *******************************************************************************/ +uint32_t Ring_Buffer_Write_Force(Ring_Buffer_Type *rbType, const uint8_t *data, uint32_t length) { + uint32_t sizeRemained = Ring_Buffer_Get_Empty_Length(rbType); + uint32_t indexRemained = rbType->size - rbType->writeIndex; + + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Drop extra data when data length is large than size of ring buffer */ + if (length > rbType->size) { + data = &data[length - rbType->size]; + length = rbType->size; + } + + if (indexRemained > length) { + /* Space remained is enough for data in current mirror */ + ARCH_MemCpy_Fast(&rbType->pointer[rbType->writeIndex], data, length); + rbType->writeIndex += length; + + /* Update read index */ + if (length > sizeRemained) { + rbType->readIndex = rbType->writeIndex; } + } else { + /* Data is divided to two parts with different mirror */ + ARCH_MemCpy_Fast(&rbType->pointer[rbType->writeIndex], data, indexRemained); + ARCH_MemCpy_Fast(&rbType->pointer[0], &data[indexRemained], length - indexRemained); + rbType->writeIndex = length - indexRemained; + rbType->writeMirror = ~rbType->writeMirror; - /* Drop extra data when data length is large than size of ring buffer */ - if (length > rbType->size) { - data = &data[length - rbType->size]; - length = rbType->size; + /* Update read index and mirror */ + if (length > sizeRemained) { + rbType->readIndex = rbType->writeIndex; + rbType->readMirror = ~rbType->readMirror; } + } - if (indexRemained > length) { - /* Space remained is enough for data in current mirror */ - ARCH_MemCpy_Fast(&rbType->pointer[rbType->writeIndex], data, length); - rbType->writeIndex += length; + if (rbType->unlock != NULL) { + rbType->unlock(); + } - /* Update read index */ - if (length > sizeRemained) { - rbType->readIndex = rbType->writeIndex; - } - } else { - /* Data is divided to two parts with different mirror */ - ARCH_MemCpy_Fast(&rbType->pointer[rbType->writeIndex], data, indexRemained); - ARCH_MemCpy_Fast(&rbType->pointer[0], &data[indexRemained], length - indexRemained); - rbType->writeIndex = length - indexRemained; - rbType->writeMirror = ~rbType->writeMirror; - - /* Update read index and mirror */ - if (length > sizeRemained) { - rbType->readIndex = rbType->writeIndex; - rbType->readMirror = ~rbType->readMirror; - } - } - - if (rbType->unlock != NULL) { - rbType->unlock(); - } - - return length; + return length; } /****************************************************************************/ /** - * @brief Write 1 byte to ring buffer function, old data will be covered by new data when ring - * buffer is full - * - * @param rbType: Ring buffer type structure pointer - * @param data: Data to write - * - * @return Length of data writted actually - * -*******************************************************************************/ -uint32_t Ring_Buffer_Write_Byte_Force(Ring_Buffer_Type *rbType, const uint8_t data) -{ - Ring_Buffer_Status_Type status = Ring_Buffer_Get_Status(rbType); + * @brief Write 1 byte to ring buffer function, old data will be covered by new data when ring + * buffer is full + * + * @param rbType: Ring buffer type structure pointer + * @param data: Data to write + * + * @return Length of data writted actually + * + *******************************************************************************/ +uint32_t Ring_Buffer_Write_Byte_Force(Ring_Buffer_Type *rbType, const uint8_t data) { + Ring_Buffer_Status_Type status = Ring_Buffer_Get_Status(rbType); + + if (rbType->lock != NULL) { + rbType->lock(); + } + + rbType->pointer[rbType->writeIndex] = data; + + /* Judge to change index and mirror */ + if (rbType->writeIndex == rbType->size - 1) { + rbType->writeIndex = 0; + rbType->writeMirror = ~rbType->writeMirror; - if (rbType->lock != NULL) { - rbType->lock(); + /* Update read index and mirror */ + if (status == RING_BUFFER_FULL) { + rbType->readIndex = rbType->writeIndex; + rbType->readMirror = ~rbType->readMirror; } + } else { + rbType->writeIndex++; - rbType->pointer[rbType->writeIndex] = data; - - /* Judge to change index and mirror */ - if (rbType->writeIndex == rbType->size - 1) { - rbType->writeIndex = 0; - rbType->writeMirror = ~rbType->writeMirror; - - /* Update read index and mirror */ - if (status == RING_BUFFER_FULL) { - rbType->readIndex = rbType->writeIndex; - rbType->readMirror = ~rbType->readMirror; - } - } else { - rbType->writeIndex++; - - /* Update read index */ - if (status == RING_BUFFER_FULL) { - rbType->readIndex = rbType->writeIndex; - } + /* Update read index */ + if (status == RING_BUFFER_FULL) { + rbType->readIndex = rbType->writeIndex; } + } - if (rbType->unlock != NULL) { - rbType->unlock(); - } + if (rbType->unlock != NULL) { + rbType->unlock(); + } - return 1; + return 1; } /****************************************************************************/ /** - * @brief Use callback function to read ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * @param length: Length of data want to read - * @param readCb: Callback function pointer - * @param parameter: Parameter that callback function may use - * - * @return Length of data actually read - * -*******************************************************************************/ -uint32_t Ring_Buffer_Read_Callback(Ring_Buffer_Type *rbType, uint32_t length, ringBuffer_Read_Callback *readCb, void *parameter) -{ - uint32_t size = Ring_Buffer_Get_Length(rbType); - - if (readCb == NULL) { - return 0; - } - - if (rbType->lock != NULL) { - rbType->lock(); + * @brief Use callback function to read ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * @param length: Length of data want to read + * @param readCb: Callback function pointer + * @param parameter: Parameter that callback function may use + * + * @return Length of data actually read + * + *******************************************************************************/ +uint32_t Ring_Buffer_Read_Callback(Ring_Buffer_Type *rbType, uint32_t length, ringBuffer_Read_Callback *readCb, void *parameter) { + uint32_t size = Ring_Buffer_Get_Length(rbType); + + if (readCb == NULL) { + return 0; + } + + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Ring buffer has no data */ + if (!size) { + if (rbType->unlock != NULL) { + rbType->unlock(); } - /* Ring buffer has no data */ - if (!size) { - if (rbType->unlock != NULL) { - rbType->unlock(); - } + return 0; + } - return 0; - } + /* Ring buffer do not have enough data */ + if (size < length) { + length = size; + } - /* Ring buffer do not have enough data */ - if (size < length) { - length = size; - } + /* Get size of space remained in current mirror */ + size = rbType->size - rbType->readIndex; - /* Get size of space remained in current mirror */ - size = rbType->size - rbType->readIndex; - - if (size > length) { - /* Read all data needed */ - readCb(parameter, &rbType->pointer[rbType->readIndex], length); - rbType->readIndex += length; - } else { - /* Read two part of data in different mirror */ - readCb(parameter, &rbType->pointer[rbType->readIndex], size); - readCb(parameter, &rbType->pointer[0], length - size); - rbType->readIndex = length - size; - rbType->readMirror = ~rbType->readMirror; - } + if (size > length) { + /* Read all data needed */ + readCb(parameter, &rbType->pointer[rbType->readIndex], length); + rbType->readIndex += length; + } else { + /* Read two part of data in different mirror */ + readCb(parameter, &rbType->pointer[rbType->readIndex], size); + readCb(parameter, &rbType->pointer[0], length - size); + rbType->readIndex = length - size; + rbType->readMirror = ~rbType->readMirror; + } - if (rbType->unlock != NULL) { - rbType->unlock(); - } + if (rbType->unlock != NULL) { + rbType->unlock(); + } - return length; + return length; } /****************************************************************************/ /** - * @brief Copy data from ring buffer to data buffer function - * - * @param parameter: Pointer to destination pointer - * @param data: Data buffer to copy - * @param length: Length of data to copy - * - * @return None - * -*******************************************************************************/ -static void Ring_Buffer_Read_Copy(void *parameter, uint8_t *data, uint32_t length) -{ - uint8_t **dest = (uint8_t **)parameter; - - ARCH_MemCpy_Fast(*dest, data, length); - *dest += length; + * @brief Copy data from ring buffer to data buffer function + * + * @param parameter: Pointer to destination pointer + * @param data: Data buffer to copy + * @param length: Length of data to copy + * + * @return None + * + *******************************************************************************/ +static void Ring_Buffer_Read_Copy(void *parameter, uint8_t *data, uint32_t length) { + uint8_t **dest = (uint8_t **)parameter; + + ARCH_MemCpy_Fast(*dest, data, length); + *dest += length; } /****************************************************************************/ /** - * @brief Read ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * @param data: Buffer for data read - * @param length: Length of data to read - * - * @return Length of data read actually - * -*******************************************************************************/ -uint32_t Ring_Buffer_Read(Ring_Buffer_Type *rbType, uint8_t *data, uint32_t length) -{ - return Ring_Buffer_Read_Callback(rbType, length, Ring_Buffer_Read_Copy, &data); -} + * @brief Read ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * @param data: Buffer for data read + * @param length: Length of data to read + * + * @return Length of data read actually + * + *******************************************************************************/ +uint32_t Ring_Buffer_Read(Ring_Buffer_Type *rbType, uint8_t *data, uint32_t length) { return Ring_Buffer_Read_Callback(rbType, length, Ring_Buffer_Read_Copy, &data); } /****************************************************************************/ /** - * @brief Read 1 byte from ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * @param data: Data read - * - * @return Length of data actually read - * -*******************************************************************************/ -uint32_t Ring_Buffer_Read_Byte(Ring_Buffer_Type *rbType, uint8_t *data) -{ - if (rbType->lock != NULL) { - rbType->lock(); + * @brief Read 1 byte from ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * @param data: Data read + * + * @return Length of data actually read + * + *******************************************************************************/ +uint32_t Ring_Buffer_Read_Byte(Ring_Buffer_Type *rbType, uint8_t *data) { + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Ring buffer has no data */ + if (!Ring_Buffer_Get_Length(rbType)) { + if (rbType->unlock != NULL) { + rbType->unlock(); } - /* Ring buffer has no data */ - if (!Ring_Buffer_Get_Length(rbType)) { - if (rbType->unlock != NULL) { - rbType->unlock(); - } - - return 0; - } + return 0; + } - /* Read data */ - *data = rbType->pointer[rbType->readIndex]; + /* Read data */ + *data = rbType->pointer[rbType->readIndex]; - /* Update read index and mirror */ - if (rbType->readIndex == rbType->size - 1) { - rbType->readIndex = 0; - rbType->readMirror = ~rbType->readMirror; - } else { - rbType->readIndex++; - } + /* Update read index and mirror */ + if (rbType->readIndex == rbType->size - 1) { + rbType->readIndex = 0; + rbType->readMirror = ~rbType->readMirror; + } else { + rbType->readIndex++; + } - if (rbType->unlock != NULL) { - rbType->unlock(); - } + if (rbType->unlock != NULL) { + rbType->unlock(); + } - return 1; + return 1; } /****************************************************************************/ /** - * @brief Read ring buffer function, do not remove from buffer actually - * - * @param rbType: Ring buffer type structure pointer - * @param data: Buffer for data read - * @param length: Length of data to read - * - * @return Length of data read actually - * -*******************************************************************************/ -uint32_t Ring_Buffer_Peek(Ring_Buffer_Type *rbType, uint8_t *data, uint32_t length) -{ - uint32_t size = Ring_Buffer_Get_Length(rbType); - - if (rbType->lock != NULL) { - rbType->lock(); + * @brief Read ring buffer function, do not remove from buffer actually + * + * @param rbType: Ring buffer type structure pointer + * @param data: Buffer for data read + * @param length: Length of data to read + * + * @return Length of data read actually + * + *******************************************************************************/ +uint32_t Ring_Buffer_Peek(Ring_Buffer_Type *rbType, uint8_t *data, uint32_t length) { + uint32_t size = Ring_Buffer_Get_Length(rbType); + + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Ring buffer has no data */ + if (!size) { + if (rbType->unlock != NULL) { + rbType->unlock(); } - /* Ring buffer has no data */ - if (!size) { - if (rbType->unlock != NULL) { - rbType->unlock(); - } + return 0; + } - return 0; - } + /* Ring buffer do not have enough data */ + if (size < length) { + length = size; + } - /* Ring buffer do not have enough data */ - if (size < length) { - length = size; - } - - /* Get size of space remained in current mirror */ - size = rbType->size - rbType->readIndex; + /* Get size of space remained in current mirror */ + size = rbType->size - rbType->readIndex; - if (size > length) { - /* Read all data needed */ - ARCH_MemCpy_Fast(data, &rbType->pointer[rbType->readIndex], length); - } else { - /* Read two part of data in different mirror */ - ARCH_MemCpy_Fast(data, &rbType->pointer[rbType->readIndex], size); - ARCH_MemCpy_Fast(&data[size], &rbType->pointer[0], length - size); - } + if (size > length) { + /* Read all data needed */ + ARCH_MemCpy_Fast(data, &rbType->pointer[rbType->readIndex], length); + } else { + /* Read two part of data in different mirror */ + ARCH_MemCpy_Fast(data, &rbType->pointer[rbType->readIndex], size); + ARCH_MemCpy_Fast(&data[size], &rbType->pointer[0], length - size); + } - if (rbType->unlock != NULL) { - rbType->unlock(); - } + if (rbType->unlock != NULL) { + rbType->unlock(); + } - return length; + return length; } /****************************************************************************/ /** - * @brief Read 1 byte from ring buffer function, do not remove from buffer actually - * - * @param rbType: Ring buffer type structure pointer - * @param data: Data read - * - * @return Length of data actually read - * -*******************************************************************************/ -uint32_t Ring_Buffer_Peek_Byte(Ring_Buffer_Type *rbType, uint8_t *data) -{ - if (rbType->lock != NULL) { - rbType->lock(); - } - - /* Ring buffer has no data */ - if (!Ring_Buffer_Get_Length(rbType)) { - if (rbType->unlock != NULL) { - rbType->unlock(); - } - - return 0; - } - - /* Read data */ - *data = rbType->pointer[rbType->readIndex]; - + * @brief Read 1 byte from ring buffer function, do not remove from buffer actually + * + * @param rbType: Ring buffer type structure pointer + * @param data: Data read + * + * @return Length of data actually read + * + *******************************************************************************/ +uint32_t Ring_Buffer_Peek_Byte(Ring_Buffer_Type *rbType, uint8_t *data) { + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Ring buffer has no data */ + if (!Ring_Buffer_Get_Length(rbType)) { if (rbType->unlock != NULL) { - rbType->unlock(); + rbType->unlock(); } - return 1; -} + return 0; + } -/****************************************************************************/ /** - * @brief Get length of data in ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * - * @return Length of data - * -*******************************************************************************/ -uint32_t Ring_Buffer_Get_Length(Ring_Buffer_Type *rbType) -{ - uint32_t readMirror = 0; - uint32_t writeMirror = 0; - uint32_t readIndex = 0; - uint32_t writeIndex = 0; - uint32_t size = 0; - - if (rbType->lock != NULL) { - rbType->lock(); - } + /* Read data */ + *data = rbType->pointer[rbType->readIndex]; - readMirror = rbType->readMirror; - writeMirror = rbType->writeMirror; - readIndex = rbType->readIndex; - writeIndex = rbType->writeIndex; - size = rbType->size; + if (rbType->unlock != NULL) { + rbType->unlock(); + } - if (rbType->unlock != NULL) { - rbType->unlock(); - } - - if (readMirror == writeMirror) { - return writeIndex - readIndex; - } else { - return size - (readIndex - writeIndex); - } + return 1; } /****************************************************************************/ /** - * @brief Get space remained in ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * - * @return Length of space remained - * -*******************************************************************************/ -uint32_t Ring_Buffer_Get_Empty_Length(Ring_Buffer_Type *rbType) -{ - return (rbType->size - Ring_Buffer_Get_Length(rbType)); + * @brief Get length of data in ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * + * @return Length of data + * + *******************************************************************************/ +uint32_t Ring_Buffer_Get_Length(Ring_Buffer_Type *rbType) { + uint32_t readMirror = 0; + uint32_t writeMirror = 0; + uint32_t readIndex = 0; + uint32_t writeIndex = 0; + uint32_t size = 0; + + if (rbType->lock != NULL) { + rbType->lock(); + } + + readMirror = rbType->readMirror; + writeMirror = rbType->writeMirror; + readIndex = rbType->readIndex; + writeIndex = rbType->writeIndex; + size = rbType->size; + + if (rbType->unlock != NULL) { + rbType->unlock(); + } + + if (readMirror == writeMirror) { + return writeIndex - readIndex; + } else { + return size - (readIndex - writeIndex); + } } /****************************************************************************/ /** - * @brief Get ring buffer status function - * - * @param rbType: Ring buffer type structure pointer - * - * @return Status of ring buffer - * -*******************************************************************************/ -Ring_Buffer_Status_Type Ring_Buffer_Get_Status(Ring_Buffer_Type *rbType) -{ - if (rbType->lock != NULL) { - rbType->lock(); - } + * @brief Get space remained in ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * + * @return Length of space remained + * + *******************************************************************************/ +uint32_t Ring_Buffer_Get_Empty_Length(Ring_Buffer_Type *rbType) { return (rbType->size - Ring_Buffer_Get_Length(rbType)); } - /* Judge empty or full */ - if (rbType->readIndex == rbType->writeIndex) { - if (rbType->readMirror == rbType->writeMirror) { - if (rbType->unlock != NULL) { - rbType->unlock(); - } - - return RING_BUFFER_EMPTY; - } else { - if (rbType->unlock != NULL) { - rbType->unlock(); - } - - return RING_BUFFER_FULL; - } - } +/****************************************************************************/ /** + * @brief Get ring buffer status function + * + * @param rbType: Ring buffer type structure pointer + * + * @return Status of ring buffer + * + *******************************************************************************/ +Ring_Buffer_Status_Type Ring_Buffer_Get_Status(Ring_Buffer_Type *rbType) { + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Judge empty or full */ + if (rbType->readIndex == rbType->writeIndex) { + if (rbType->readMirror == rbType->writeMirror) { + if (rbType->unlock != NULL) { + rbType->unlock(); + } - if (rbType->unlock != NULL) { + return RING_BUFFER_EMPTY; + } else { + if (rbType->unlock != NULL) { rbType->unlock(); + } + + return RING_BUFFER_FULL; } + } + + if (rbType->unlock != NULL) { + rbType->unlock(); + } - return RING_BUFFER_PARTIAL; + return RING_BUFFER_PARTIAL; } /*@} end of group RING_BUFFER_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/soft_crc/softcrc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/soft_crc/softcrc.c index 4c4cbe55cb..10c5635d56 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/soft_crc/softcrc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/soft_crc/softcrc.c @@ -27,168 +27,104 @@ // CRC-16: x^16 + x^15 + x^2 + x^0 (0x8005,init 0xFFFF) // we use 0x8005 here and -const uint8_t chCRCHTalbe[] = { - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40 -}; +const uint8_t chCRCHTalbe[] + = {0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40}; -const uint8_t chCRCLTalbe[] = { - 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, - 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, - 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, - 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, - 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, - 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, - 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, - 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, - 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, - 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, - 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, - 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, - 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, - 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, - 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, - 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, - 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, - 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, - 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, - 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, - 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, - 0x41, 0x81, 0x80, 0x40 -}; +const uint8_t chCRCLTalbe[] + = {0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, + 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, 0x11, 0xD1, 0xD0, 0x10, + 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, + 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, + 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, + 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, + 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, + 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, 0x40}; -uint16_t BFLB_Soft_CRC16(void *dataIn, uint32_t len) -{ - uint8_t chCRCHi = 0xFF; - uint8_t chCRCLo = 0xFF; - uint16_t wIndex; - uint8_t *data = (uint8_t *)dataIn; +uint16_t BFLB_Soft_CRC16(void *dataIn, uint32_t len) { + uint8_t chCRCHi = 0xFF; + uint8_t chCRCLo = 0xFF; + uint16_t wIndex; + uint8_t *data = (uint8_t *)dataIn; - while (len--) { - wIndex = chCRCLo ^ *data++; - chCRCLo = chCRCHi ^ chCRCHTalbe[wIndex]; - chCRCHi = chCRCLTalbe[wIndex]; - } + while (len--) { + wIndex = chCRCLo ^ *data++; + chCRCLo = chCRCHi ^ chCRCHTalbe[wIndex]; + chCRCHi = chCRCLTalbe[wIndex]; + } - return ((chCRCHi << 8) | chCRCLo); + return ((chCRCHi << 8) | chCRCLo); } /* x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1 */ -const uint32_t crc32Tab[256] = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, - 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, - 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, - 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, - 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, - 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, - 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, - 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, - 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, - 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, - 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, - 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, - 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, - 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, - 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, - 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, - 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, - 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, - 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, - 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, - 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, - 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, - 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, - 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, - 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, - 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d -}; +const uint32_t crc32Tab[256] + = {0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, + 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, + 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, + 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, + 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, + 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, + 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, + 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, + 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, + 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, + 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, + 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, + 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, + 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d}; -uint32_t BFLB_Soft_CRC32_Table(void *dataIn, uint32_t len) -{ - uint32_t crc = 0; - uint8_t *data = (uint8_t *)dataIn; +uint32_t BFLB_Soft_CRC32_Table(void *dataIn, uint32_t len) { + uint32_t crc = 0; + uint8_t *data = (uint8_t *)dataIn; - crc = crc ^ 0xffffffff; + crc = crc ^ 0xffffffff; - while (len--) { - crc = crc32Tab[(crc ^ *data++) & 0xFF] ^ (crc >> 8); - } + while (len--) { + crc = crc32Tab[(crc ^ *data++) & 0xFF] ^ (crc >> 8); + } - return crc ^ 0xffffffff; + return crc ^ 0xffffffff; } /****************************************************************************** -* Name: CRC-32 x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1 -* Poly: 0x4C11DB7 -* Init: 0xFFFFFFF -* Refin: True -* Refout: True -* Xorout: 0xFFFFFFF -* Alias: CRC_32/ADCCP -* Use: WinRAR,ect. -*****************************************************************************/ -uint32_t ATTR_TCM_SECTION BFLB_Soft_CRC32_Ex(uint32_t initial, void *dataIn, uint32_t len) -{ - uint8_t i; - uint32_t crc = ~initial; // Initial value - uint8_t *data=(uint8_t *)dataIn; - - while(len--){ - crc ^= *data++; // crc ^= *data; data++; - for (i = 0; i < 8; ++i){ - if (crc & 1){ - crc = (crc >> 1) ^ 0xEDB88320;// 0xEDB88320= reverse 0x04C11DB7 - }else{ - crc = (crc >> 1); - } - } + * Name: CRC-32 x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1 + * Poly: 0x4C11DB7 + * Init: 0xFFFFFFF + * Refin: True + * Refout: True + * Xorout: 0xFFFFFFF + * Alias: CRC_32/ADCCP + * Use: WinRAR,ect. + *****************************************************************************/ +uint32_t ATTR_TCM_SECTION BFLB_Soft_CRC32_Ex(uint32_t initial, void *dataIn, uint32_t len) { + uint8_t i; + uint32_t crc = ~initial; // Initial value + uint8_t *data = (uint8_t *)dataIn; + + while (len--) { + crc ^= *data++; // crc ^= *data; data++; + for (i = 0; i < 8; ++i) { + if (crc & 1) { + crc = (crc >> 1) ^ 0xEDB88320; // 0xEDB88320= reverse 0x04C11DB7 + } else { + crc = (crc >> 1); + } } - return ~crc; + } + return ~crc; } #ifndef BFLB_USE_ROM_DRIVER __WEAK__ -uint32_t ATTR_TCM_SECTION BFLB_Soft_CRC32(void *dataIn, uint32_t len) -{ - return BFLB_Soft_CRC32_Ex(0,dataIn,len); -} +uint32_t ATTR_TCM_SECTION BFLB_Soft_CRC32(void *dataIn, uint32_t len) { return BFLB_Soft_CRC32_Ex(0, dataIn, len); } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/timestamp/timestamp.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/timestamp/timestamp.c index 3454ff47ae..bf281746a9 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/timestamp/timestamp.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/timestamp/timestamp.c @@ -23,114 +23,107 @@ #include "timestamp.h" -#define FOUR_YEAR_DAY ((365 << 2) + 1) //The total number of days in a 4-year cycle -#define TIMEZONE (8) //Beijing time Zone adjustment +#define FOUR_YEAR_DAY ((365 << 2) + 1) // The total number of days in a 4-year cycle +#define TIMEZONE (8) // Beijing time Zone adjustment #define SEC_NUM_PER_DAY (24 * 60 * 60) #define SEC_NUM_PER_HOUR (60 * 60) #define SEC_NUM_PER_MINUTE (60) -static uint8_t month_day[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; //平年 -static uint8_t Leap_month_day[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; //闰年 +static uint8_t month_day[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 平年 +static uint8_t Leap_month_day[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 闰年 /** -* @bref judge if it is a leap year -* @para year to be judge -* @return 1:leap year 0: nonleap year -*/ -bool check_leap_year(uint16_t year) -{ - if (year % 4) { - return false; + * @bref judge if it is a leap year + * @para year to be judge + * @return 1:leap year 0: nonleap year + */ +bool check_leap_year(uint16_t year) { + if (year % 4) { + return false; + } else { + if ((year % 100 == 0) && (year % 400 != 0)) { + return false; } else { - if ((year % 100 == 0) && (year % 400 != 0)) { - return false; - } else { - return true; - } + return true; } + } } -void cal_weekday(rtc_time *beijing_time) -{ - uint32_t y,m,d,w; - - y=beijing_time->year; - m=beijing_time->month; - d=beijing_time->day; - - if((m==1)||(m==2)) - { - m+=12; - y--; - } - /* - 把一月和二月看成是上一年的十三月和十四月,例:如果是2004-1-10则换算成:2003-13-10来代入公式计算。 - 以公元元年为参考,公元元年1月1日为星期一
程序如下:
-	利用基姆拉尔森计算日期公式  w=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)
-	*/
-	w=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400+1)%7;
-
-	beijing_time->week=(uint8_t)w;
+void cal_weekday(rtc_time *beijing_time) {
+  uint32_t y, m, d, w;
+
+  y = beijing_time->year;
+  m = beijing_time->month;
+  d = beijing_time->day;
+
+  if ((m == 1) || (m == 2)) {
+    m += 12;
+    y--;
+  }
+  /*
+  把一月和二月看成是上一年的十三月和十四月,例:如果是2004-1-10则换算成:2003-13-10来代入公式计算。
+  以公元元年为参考,公元元年1月1日为星期一
程序如下:
+  利用基姆拉尔森计算日期公式  w=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)
+  */
+  w = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400 + 1) % 7;
+
+  beijing_time->week = (uint8_t)w;
 }
 
-void unixtime2bejingtime(uint32_t unixtime, rtc_time *beijing_time)
-{
-    uint32_t totle_day_num;
-    uint32_t current_sec_num;
-
-    uint16_t remain_day;
+void unixtime2bejingtime(uint32_t unixtime, rtc_time *beijing_time) {
+  uint32_t totle_day_num;
+  uint32_t current_sec_num;
 
-    uint16_t temp_year;
+  uint16_t remain_day;
 
-    uint8_t *p = NULL;
+  uint16_t temp_year;
 
-    totle_day_num = unixtime / SEC_NUM_PER_DAY;   //The total number of days
-    current_sec_num = unixtime % SEC_NUM_PER_DAY; //The number of seconds this day
+  uint8_t *p = NULL;
 
-    /* use the number of seconds this day, To calculate hour\minute\second */
-    beijing_time->hour = current_sec_num / SEC_NUM_PER_HOUR;
-    beijing_time->minute = (current_sec_num % SEC_NUM_PER_HOUR) / SEC_NUM_PER_MINUTE;
-    beijing_time->second = (current_sec_num % SEC_NUM_PER_HOUR) % SEC_NUM_PER_MINUTE;
+  totle_day_num   = unixtime / SEC_NUM_PER_DAY; // The total number of days
+  current_sec_num = unixtime % SEC_NUM_PER_DAY; // The number of seconds this day
 
-    /* Adjust the time zone and check whether the date is +1 */
-    beijing_time->hour += 8;
-    if (beijing_time->hour > 23) {
-        beijing_time->hour -= 24;
-        totle_day_num++;
-    }
+  /* use the number of seconds this day, To calculate hour\minute\second */
+  beijing_time->hour   = current_sec_num / SEC_NUM_PER_HOUR;
+  beijing_time->minute = (current_sec_num % SEC_NUM_PER_HOUR) / SEC_NUM_PER_MINUTE;
+  beijing_time->second = (current_sec_num % SEC_NUM_PER_HOUR) % SEC_NUM_PER_MINUTE;
 
+  /* Adjust the time zone and check whether the date is +1 */
+  beijing_time->hour += 8;
+  if (beijing_time->hour > 23) {
+    beijing_time->hour -= 24;
+    totle_day_num++;
+  }
 
-    /* calculate year */
-    beijing_time->year = 1970 + (totle_day_num / FOUR_YEAR_DAY) * 4; // 4-year as a cycle
-    remain_day = totle_day_num % FOUR_YEAR_DAY;                      //remaining day nym( < 4 year )
+  /* calculate year */
+  beijing_time->year = 1970 + (totle_day_num / FOUR_YEAR_DAY) * 4; // 4-year as a cycle
+  remain_day         = totle_day_num % FOUR_YEAR_DAY;              // remaining day nym( < 4 year )
 
-    /* calculate year & day */
+  /* calculate year & day */
+  temp_year = check_leap_year(beijing_time->year) ? 366 : 365;
+  while (remain_day >= temp_year) {
+    beijing_time->year++;
+    remain_day -= temp_year;
     temp_year = check_leap_year(beijing_time->year) ? 366 : 365;
-    while (remain_day >= temp_year) {
-        beijing_time->year++;
-        remain_day -= temp_year;
-        temp_year = check_leap_year(beijing_time->year) ? 366 : 365;
-    }
-
-    /* Calculate specific dates(month\day)*/
-    p = check_leap_year(beijing_time->year) ? Leap_month_day : month_day;
-    remain_day++; //The actual day starts at 1
-    beijing_time->month = 0;
-    while (remain_day > *(p + beijing_time->month)) {
-        remain_day -= *(p + beijing_time->month);
-        beijing_time->month++;
-    }
-
-    beijing_time->month++; //The actual month starts at 1
-    beijing_time->day = remain_day;
+  }
 
+  /* Calculate specific dates(month\day)*/
+  p = check_leap_year(beijing_time->year) ? Leap_month_day : month_day;
+  remain_day++; // The actual day starts at 1
+  beijing_time->month = 0;
+  while (remain_day > *(p + beijing_time->month)) {
+    remain_day -= *(p + beijing_time->month);
+    beijing_time->month++;
+  }
 
+  beijing_time->month++; // The actual month starts at 1
+  beijing_time->day = remain_day;
 
-	/*利用基姆拉尔森计算日期公式  w=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)*/
+  /*利用基姆拉尔森计算日期公式  w=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)*/
 
-	beijing_time->week = beijing_time->day + 2*beijing_time->month + 3*(beijing_time->month+1)/5 + \
-	beijing_time->year + beijing_time->year/4 - beijing_time->year/100 +beijing_time->year/400 ;
+  beijing_time->week
+      = beijing_time->day + 2 * beijing_time->month + 3 * (beijing_time->month + 1) / 5 + beijing_time->year + beijing_time->year / 4 - beijing_time->year / 100 + beijing_time->year / 400;
 
-	cal_weekday(beijing_time);
+  cal_weekday(beijing_time);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c
index 238b9b2023..3fa6a18581 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c
@@ -1,323 +1,316 @@
 /*****************************************************************************************
-*
-* @file bl_hci_wrapper.c
-*
-* @brief Bouffalo Lab hci wrapper functions
-*
-* Copyright (C) Bouffalo Lab 2018
-*
-* History: 2018-08 crealted by llgong @ Shanghai
-*
-*****************************************************************************************/
+ *
+ * @file bl_hci_wrapper.c
+ *
+ * @brief Bouffalo Lab hci wrapper functions
+ *
+ * Copyright (C) Bouffalo Lab 2018
+ *
+ * History: 2018-08 crealted by llgong @ Shanghai
+ *
+ *****************************************************************************************/
 
-#include 
-#include 
-#include "hci_host.h"
 #include "bl_hci_wrapper.h"
-#include "hci_driver.h"
 #include "../common/include/errno.h"
 #include "byteorder.h"
+#include "hci_driver.h"
+#include "hci_host.h"
 #include "hci_onchip.h"
+#include 
+#include 
 
 #define DATA_MSG_CNT 10
 
 struct rx_msg_struct data_msg[DATA_MSG_CNT];
-struct k_queue msg_queue;
+struct k_queue       msg_queue;
 #if defined(BFLB_BLE_NOTIFY_ADV_DISCARDED)
 extern void ble_controller_notify_adv_discarded(uint8_t *adv_bd_addr, uint8_t adv_type);
 #endif
 
-struct rx_msg_struct *bl_find_valid_data_msg()
-{
-    struct rx_msg_struct empty_msg;
-    memset(&empty_msg, 0, sizeof(struct rx_msg_struct));
+struct rx_msg_struct *bl_find_valid_data_msg() {
+  struct rx_msg_struct empty_msg;
+  memset(&empty_msg, 0, sizeof(struct rx_msg_struct));
 
-    for (int i = 0; i < DATA_MSG_CNT; i++) {
-        if (!memcmp(&data_msg[i], &empty_msg, sizeof(struct rx_msg_struct))) {
-            return (data_msg + i);
-        }
+  for (int i = 0; i < DATA_MSG_CNT; i++) {
+    if (!memcmp(&data_msg[i], &empty_msg, sizeof(struct rx_msg_struct))) {
+      return (data_msg + i);
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-int bl_onchiphci_send_2_controller(struct net_buf *buf)
-{
-    uint16_t opcode;
-    uint16_t dest_id = 0x00;
-    uint8_t buf_type;
-    uint8_t pkt_type;
-    hci_pkt_struct pkt;
-
-    buf_type = bt_buf_get_type(buf);
-    switch (buf_type) {
-        case BT_BUF_CMD: {
-            struct bt_hci_cmd_hdr *chdr;
-
-            if (buf->len < sizeof(struct bt_hci_cmd_hdr)) {
-                return -EINVAL;
-            }
-
-            chdr = (void *)buf->data;
-
-            if (buf->len < chdr->param_len) {
-                return -EINVAL;
-            }
-
-            pkt_type = BT_HCI_CMD;
-            opcode = sys_le16_to_cpu(chdr->opcode);
-            //move buf to the payload
-            net_buf_pull(buf, sizeof(struct bt_hci_cmd_hdr));
-            switch (opcode) {
-                //ble refer to hci_cmd_desc_tab_le, for the ones of which dest_ll is BLE_CTRL
-                case BT_HCI_OP_LE_CONN_UPDATE:
-                case BT_HCI_OP_LE_READ_CHAN_MAP:
-                case BT_HCI_OP_LE_READ_REMOTE_FEATURES:
-                case BT_HCI_OP_LE_START_ENCRYPTION:
-                case BT_HCI_OP_LE_LTK_REQ_REPLY:
-                case BT_HCI_OP_LE_LTK_REQ_NEG_REPLY:
-                case BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY:
-                case BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY:
-                case BT_HCI_OP_LE_SET_DATA_LEN:
-                case BT_HCI_OP_LE_READ_PHY:
-                case BT_HCI_OP_LE_SET_PHY:
-                //bredr identify link id, according to dest_id
-                case BT_HCI_OP_READ_REMOTE_FEATURES:
-                case BT_HCI_OP_READ_REMOTE_EXT_FEATURES:
-                case BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE: {
-                    //dest_id is connectin handle
-                    dest_id = buf->data[0];
-                }
-                default:
-                    break;
-            }
-            pkt.p.hci_cmd.opcode = opcode;
-            pkt.p.hci_cmd.param_len = chdr->param_len;
-            pkt.p.hci_cmd.params = buf->data;
-
-            break;
-        }
-
-        case BT_BUF_ACL_OUT: {
-            struct bt_hci_acl_hdr *acl;
-            //connhandle +l2cap field
-            uint16_t connhdl_l2cf, tlt_len;
-
-            if (buf->len < sizeof(struct bt_hci_acl_hdr)) {
-                return -EINVAL;
-            }
-
-            pkt_type = BT_HCI_ACL_DATA;
-            acl = (void *)buf->data;
-            tlt_len = sys_le16_to_cpu(acl->len);
-            connhdl_l2cf = sys_le16_to_cpu(acl->handle);
-            //move buf to the payload
-            net_buf_pull(buf, sizeof(struct bt_hci_acl_hdr));
-
-            if (buf->len < tlt_len) {
-                return -EINVAL;
-            }
-
-            //get connection_handle
-            dest_id = bt_acl_handle(connhdl_l2cf);
-            pkt.p.acl_data.conhdl = dest_id;
-            pkt.p.acl_data.pb_bc_flag = bt_acl_flags(connhdl_l2cf);
-            pkt.p.acl_data.len = tlt_len;
-            pkt.p.acl_data.buffer = (uint8_t *)buf->data;
-
-            break;
-        }
-
-        default:
-            return -EINVAL;
+int bl_onchiphci_send_2_controller(struct net_buf *buf) {
+  uint16_t       opcode;
+  uint16_t       dest_id = 0x00;
+  uint8_t        buf_type;
+  uint8_t        pkt_type;
+  hci_pkt_struct pkt;
+
+  buf_type = bt_buf_get_type(buf);
+  switch (buf_type) {
+  case BT_BUF_CMD: {
+    struct bt_hci_cmd_hdr *chdr;
+
+    if (buf->len < sizeof(struct bt_hci_cmd_hdr)) {
+      return -EINVAL;
     }
 
-    return bt_onchiphci_send(pkt_type, dest_id, &pkt);
-}
+    chdr = (void *)buf->data;
 
-void bl_packet_to_host(uint8_t pkt_type, uint16_t src_id, uint8_t *param, uint8_t param_len, struct net_buf *buf)
-{
-    uint16_t tlt_len;
-    bool prio = true;
-    uint8_t nb_h2c_cmd_pkts = 0x01;
-
-    uint8_t *buf_data = net_buf_tail(buf);
-    bt_buf_set_rx_adv(buf, false);
-
-    switch (pkt_type) {
-        case BT_HCI_CMD_CMP_EVT: {
-            tlt_len = BT_HCI_EVT_CC_PARAM_OFFSET + param_len;
-            *buf_data++ = BT_HCI_EVT_CMD_COMPLETE;
-            *buf_data++ = BT_HCI_CCEVT_HDR_PARLEN + param_len;
-            *buf_data++ = nb_h2c_cmd_pkts;
-            sys_put_le16(src_id, buf_data);
-            buf_data += 2;
-            memcpy(buf_data, param, param_len);
-            break;
-        }
-        case BT_HCI_CMD_STAT_EVT: {
-            tlt_len = BT_HCI_CSEVT_LEN;
-            *buf_data++ = BT_HCI_EVT_CMD_STATUS;
-            *buf_data++ = BT_HCI_CSVT_PARLEN;
-            *buf_data++ = *(uint8_t *)param;
-            *buf_data++ = nb_h2c_cmd_pkts;
-            sys_put_le16(src_id, buf_data);
-            break;
-        }
-        case BT_HCI_LE_EVT: {
-            prio = false;
-            bt_buf_set_type(buf, BT_BUF_EVT);
-            if (param[0] == BT_HCI_EVT_LE_ADVERTISING_REPORT) {
-                bt_buf_set_rx_adv(buf, true);
-            }
-            tlt_len = BT_HCI_EVT_LE_PARAM_OFFSET + param_len;
-            *buf_data++ = BT_HCI_EVT_LE_META_EVENT;
-            *buf_data++ = param_len;
-            memcpy(buf_data, param, param_len);
-            break;
-        }
-        case BT_HCI_EVT: {
-            if (src_id != BT_HCI_EVT_NUM_COMPLETED_PACKETS) {
-                prio = false;
-            }
-            bt_buf_set_type(buf, BT_BUF_EVT);
-            tlt_len = BT_HCI_EVT_LE_PARAM_OFFSET + param_len;
-            *buf_data++ = src_id;
-            *buf_data++ = param_len;
-            memcpy(buf_data, param, param_len);
-            break;
-        }
-        case BT_HCI_ACL_DATA: {
-            prio = false;
-            bt_buf_set_type(buf, BT_BUF_ACL_IN);
-            tlt_len = bt_onchiphci_hanlde_rx_acl(param, buf_data);
-            break;
-        }
-        default: {
-            net_buf_unref(buf);
-            return;
-        }
+    if (buf->len < chdr->param_len) {
+      return -EINVAL;
     }
 
-    net_buf_add(buf, tlt_len);
+    pkt_type = BT_HCI_CMD;
+    opcode   = sys_le16_to_cpu(chdr->opcode);
+    // move buf to the payload
+    net_buf_pull(buf, sizeof(struct bt_hci_cmd_hdr));
+    switch (opcode) {
+    // ble refer to hci_cmd_desc_tab_le, for the ones of which dest_ll is BLE_CTRL
+    case BT_HCI_OP_LE_CONN_UPDATE:
+    case BT_HCI_OP_LE_READ_CHAN_MAP:
+    case BT_HCI_OP_LE_READ_REMOTE_FEATURES:
+    case BT_HCI_OP_LE_START_ENCRYPTION:
+    case BT_HCI_OP_LE_LTK_REQ_REPLY:
+    case BT_HCI_OP_LE_LTK_REQ_NEG_REPLY:
+    case BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY:
+    case BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY:
+    case BT_HCI_OP_LE_SET_DATA_LEN:
+    case BT_HCI_OP_LE_READ_PHY:
+    case BT_HCI_OP_LE_SET_PHY:
+    // bredr identify link id, according to dest_id
+    case BT_HCI_OP_READ_REMOTE_FEATURES:
+    case BT_HCI_OP_READ_REMOTE_EXT_FEATURES:
+    case BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE: {
+      // dest_id is connectin handle
+      dest_id = buf->data[0];
+    }
+    default:
+      break;
+    }
+    pkt.p.hci_cmd.opcode    = opcode;
+    pkt.p.hci_cmd.param_len = chdr->param_len;
+    pkt.p.hci_cmd.params    = buf->data;
 
-    if (prio) {
-        bt_recv_prio(buf);
-    } else {
-        hci_driver_enque_recvq(buf);
+    break;
+  }
+
+  case BT_BUF_ACL_OUT: {
+    struct bt_hci_acl_hdr *acl;
+    // connhandle +l2cap field
+    uint16_t connhdl_l2cf, tlt_len;
+
+    if (buf->len < sizeof(struct bt_hci_acl_hdr)) {
+      return -EINVAL;
     }
+
+    pkt_type     = BT_HCI_ACL_DATA;
+    acl          = (void *)buf->data;
+    tlt_len      = sys_le16_to_cpu(acl->len);
+    connhdl_l2cf = sys_le16_to_cpu(acl->handle);
+    // move buf to the payload
+    net_buf_pull(buf, sizeof(struct bt_hci_acl_hdr));
+
+    if (buf->len < tlt_len) {
+      return -EINVAL;
+    }
+
+    // get connection_handle
+    dest_id                   = bt_acl_handle(connhdl_l2cf);
+    pkt.p.acl_data.conhdl     = dest_id;
+    pkt.p.acl_data.pb_bc_flag = bt_acl_flags(connhdl_l2cf);
+    pkt.p.acl_data.len        = tlt_len;
+    pkt.p.acl_data.buffer     = (uint8_t *)buf->data;
+
+    break;
+  }
+
+  default:
+    return -EINVAL;
+  }
+
+  return bt_onchiphci_send(pkt_type, dest_id, &pkt);
 }
 
-void bl_trigger_queued_msg()
-{
-    struct net_buf *buf = NULL;
-    struct rx_msg_struct *msg = NULL;
+void bl_packet_to_host(uint8_t pkt_type, uint16_t src_id, uint8_t *param, uint8_t param_len, struct net_buf *buf) {
+  uint16_t tlt_len;
+  bool     prio            = true;
+  uint8_t  nb_h2c_cmd_pkts = 0x01;
+
+  uint8_t *buf_data = net_buf_tail(buf);
+  bt_buf_set_rx_adv(buf, false);
+
+  switch (pkt_type) {
+  case BT_HCI_CMD_CMP_EVT: {
+    tlt_len     = BT_HCI_EVT_CC_PARAM_OFFSET + param_len;
+    *buf_data++ = BT_HCI_EVT_CMD_COMPLETE;
+    *buf_data++ = BT_HCI_CCEVT_HDR_PARLEN + param_len;
+    *buf_data++ = nb_h2c_cmd_pkts;
+    sys_put_le16(src_id, buf_data);
+    buf_data += 2;
+    memcpy(buf_data, param, param_len);
+    break;
+  }
+  case BT_HCI_CMD_STAT_EVT: {
+    tlt_len     = BT_HCI_CSEVT_LEN;
+    *buf_data++ = BT_HCI_EVT_CMD_STATUS;
+    *buf_data++ = BT_HCI_CSVT_PARLEN;
+    *buf_data++ = *(uint8_t *)param;
+    *buf_data++ = nb_h2c_cmd_pkts;
+    sys_put_le16(src_id, buf_data);
+    break;
+  }
+  case BT_HCI_LE_EVT: {
+    prio = false;
+    bt_buf_set_type(buf, BT_BUF_EVT);
+    if (param[0] == BT_HCI_EVT_LE_ADVERTISING_REPORT) {
+      bt_buf_set_rx_adv(buf, true);
+    }
+    tlt_len     = BT_HCI_EVT_LE_PARAM_OFFSET + param_len;
+    *buf_data++ = BT_HCI_EVT_LE_META_EVENT;
+    *buf_data++ = param_len;
+    memcpy(buf_data, param, param_len);
+    break;
+  }
+  case BT_HCI_EVT: {
+    if (src_id != BT_HCI_EVT_NUM_COMPLETED_PACKETS) {
+      prio = false;
+    }
+    bt_buf_set_type(buf, BT_BUF_EVT);
+    tlt_len     = BT_HCI_EVT_LE_PARAM_OFFSET + param_len;
+    *buf_data++ = src_id;
+    *buf_data++ = param_len;
+    memcpy(buf_data, param, param_len);
+    break;
+  }
+  case BT_HCI_ACL_DATA: {
+    prio = false;
+    bt_buf_set_type(buf, BT_BUF_ACL_IN);
+    tlt_len = bt_onchiphci_hanlde_rx_acl(param, buf_data);
+    break;
+  }
+  default: {
+    net_buf_unref(buf);
+    return;
+  }
+  }
+
+  net_buf_add(buf, tlt_len);
+
+  if (prio) {
+    bt_recv_prio(buf);
+  } else {
+    hci_driver_enque_recvq(buf);
+  }
+}
 
-    do {
-        unsigned int lock = irq_lock();
+void bl_trigger_queued_msg() {
+  struct net_buf       *buf = NULL;
+  struct rx_msg_struct *msg = NULL;
 
-        if (k_queue_is_empty(&msg_queue)) {
-            break;
-        }
+  do {
+    unsigned int lock = irq_lock();
 
-        if (bt_buf_get_rx_avail_cnt() <= CONFIG_BT_RX_BUF_RSV_COUNT)
-            break;
+    if (k_queue_is_empty(&msg_queue)) {
+      break;
+    }
 
-        buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
-        if (!buf) {
-            break;
-        }
+    if (bt_buf_get_rx_avail_cnt() <= CONFIG_BT_RX_BUF_RSV_COUNT)
+      break;
 
-        msg = k_fifo_get(&msg_queue, K_NO_WAIT);
+    buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
+    if (!buf) {
+      break;
+    }
 
-        BT_ASSERT(msg);
+    msg = k_fifo_get(&msg_queue, K_NO_WAIT);
 
-        bl_packet_to_host(msg->pkt_type, msg->src_id, msg->param, msg->param_len, buf);
+    BT_ASSERT(msg);
 
-        irq_unlock(lock);
+    bl_packet_to_host(msg->pkt_type, msg->src_id, msg->param, msg->param_len, buf);
 
-        if (msg->param) {
-            k_free(msg->param);
-        }
-        memset(msg, 0, sizeof(struct rx_msg_struct));
+    irq_unlock(lock);
 
-    } while (buf);
-}
+    if (msg->param) {
+      k_free(msg->param);
+    }
+    memset(msg, 0, sizeof(struct rx_msg_struct));
 
-static void bl_onchiphci_rx_packet_handler(uint8_t pkt_type, uint16_t src_id, uint8_t *param, uint8_t param_len)
-{
-    struct net_buf *buf = NULL;
-    struct rx_msg_struct *rx_msg = NULL;
+  } while (buf);
+}
 
-    if (pkt_type == BT_HCI_CMD_CMP_EVT || pkt_type == BT_HCI_CMD_STAT_EVT) {
-        buf = bt_buf_get_cmd_complete(K_FOREVER);
-        bl_packet_to_host(pkt_type, src_id, param, param_len, buf);
-        return;
-    } else if (pkt_type == BT_HCI_LE_EVT && param[0] == BT_HCI_EVT_LE_ADVERTISING_REPORT) {
-        if (bt_buf_get_rx_avail_cnt() <= CONFIG_BT_RX_BUF_RSV_COUNT) {
-            BT_INFO("Discard adv report.");
+static void bl_onchiphci_rx_packet_handler(uint8_t pkt_type, uint16_t src_id, uint8_t *param, uint8_t param_len) {
+  struct net_buf       *buf    = NULL;
+  struct rx_msg_struct *rx_msg = NULL;
+
+  if (pkt_type == BT_HCI_CMD_CMP_EVT || pkt_type == BT_HCI_CMD_STAT_EVT) {
+    buf = bt_buf_get_cmd_complete(K_FOREVER);
+    bl_packet_to_host(pkt_type, src_id, param, param_len, buf);
+    return;
+  } else if (pkt_type == BT_HCI_LE_EVT && param[0] == BT_HCI_EVT_LE_ADVERTISING_REPORT) {
+    if (bt_buf_get_rx_avail_cnt() <= CONFIG_BT_RX_BUF_RSV_COUNT) {
+      BT_INFO("Discard adv report.");
 #if defined(BFLB_BLE_NOTIFY_ADV_DISCARDED)
-            ble_controller_notify_adv_discarded(¶m[4], param[2]);
+      ble_controller_notify_adv_discarded(¶m[4], param[2]);
 #endif
-            return;
-        }
-        buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
-        if (buf)
-            bl_packet_to_host(pkt_type, src_id, param, param_len, buf);
+      return;
+    }
+    buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
+    if (buf)
+      bl_packet_to_host(pkt_type, src_id, param, param_len, buf);
+    return;
+  } else {
+    if (pkt_type != BT_HCI_ACL_DATA) {
+      /* Using the reserved buf (CONFIG_BT_RX_BUF_RSV_COUNT) firstly. */
+      buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
+      if (buf) {
+        bl_packet_to_host(pkt_type, src_id, param, param_len, buf);
         return;
-    } else {
-        if (pkt_type != BT_HCI_ACL_DATA) {
-            /* Using the reserved buf (CONFIG_BT_RX_BUF_RSV_COUNT) firstly. */
-            buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
-            if (buf) {
-                bl_packet_to_host(pkt_type, src_id, param, param_len, buf);
-                return;
-            }
-        }
-
-        rx_msg = bl_find_valid_data_msg();
+      }
     }
 
-    BT_ASSERT(rx_msg);
+    rx_msg = bl_find_valid_data_msg();
+  }
 
-    rx_msg->pkt_type = pkt_type;
-    rx_msg->src_id = src_id;
-    rx_msg->param_len = param_len;
-    if (param_len) {
-        rx_msg->param = k_malloc(param_len);
-        memcpy(rx_msg->param, param, param_len);
-    }
+  BT_ASSERT(rx_msg);
+
+  rx_msg->pkt_type  = pkt_type;
+  rx_msg->src_id    = src_id;
+  rx_msg->param_len = param_len;
+  if (param_len) {
+    rx_msg->param = k_malloc(param_len);
+    memcpy(rx_msg->param, param, param_len);
+  }
 
-    k_fifo_put(&msg_queue, rx_msg);
+  k_fifo_put(&msg_queue, rx_msg);
 
-    bl_trigger_queued_msg();
+  bl_trigger_queued_msg();
 }
 
-uint8_t bl_onchiphci_interface_init(void)
-{
-    for (int i = 0; i < DATA_MSG_CNT; i++) {
-        memset(data_msg + i, 0, sizeof(struct rx_msg_struct));
-    }
+uint8_t bl_onchiphci_interface_init(void) {
+  for (int i = 0; i < DATA_MSG_CNT; i++) {
+    memset(data_msg + i, 0, sizeof(struct rx_msg_struct));
+  }
 
-    k_queue_init(&msg_queue, DATA_MSG_CNT);
+  k_queue_init(&msg_queue, DATA_MSG_CNT);
 
-    return bt_onchiphci_interface_init(bl_onchiphci_rx_packet_handler);
+  return bt_onchiphci_interface_init(bl_onchiphci_rx_packet_handler);
 }
 
-void bl_onchiphci_interface_deinit(void)
-{
-    struct rx_msg_struct *msg;
-
-    do {
-        msg = k_fifo_get(&msg_queue, K_NO_WAIT);
-        if (msg) {
-            if (msg->param) {
-                k_free(msg->param);
-            }
-        } else {
-            break;
-        }
-    } while (1);
-
-    k_queue_free(&msg_queue);
+void bl_onchiphci_interface_deinit(void) {
+  struct rx_msg_struct *msg;
+
+  do {
+    msg = k_fifo_get(&msg_queue, K_NO_WAIT);
+    if (msg) {
+      if (msg->param) {
+        k_free(msg->param);
+      }
+    } else {
+      break;
+    }
+  } while (1);
+
+  k_queue_free(&msg_queue);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/atomic_c.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/atomic_c.c
index 25c27fb663..34beb7ce76 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/atomic_c.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/atomic_c.c
@@ -17,11 +17,11 @@
  *
  * (originally from x86's atomic.c)
  */
+#include "bl_port.h"
 #include 
 #include 
-#include "bl_port.h"
-//#include 
-//#include 
+// #include 
+// #include 
 
 /**
  *
@@ -43,22 +43,20 @@
  * @param new_value value to compare against
  * @return Returns 1 if  is written, 0 otherwise.
  */
-int atomic_cas(atomic_t *target, atomic_val_t old_value,
-               atomic_val_t new_value)
-{
-    unsigned int key;
-    int ret = 0;
+int atomic_cas(atomic_t *target, atomic_val_t old_value, atomic_val_t new_value) {
+  unsigned int key;
+  int          ret = 0;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    if (*target == old_value) {
-        *target = new_value;
-        ret = 1;
-    }
+  if (*target == old_value) {
+    *target = new_value;
+    ret     = 1;
+  }
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -74,19 +72,18 @@ int atomic_cas(atomic_t *target, atomic_val_t old_value,
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_add(atomic_t *target, atomic_val_t value)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_add(atomic_t *target, atomic_val_t value) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target += value;
+  ret = *target;
+  *target += value;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -102,19 +99,18 @@ atomic_val_t atomic_add(atomic_t *target, atomic_val_t value)
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target -= value;
+  ret = *target;
+  *target -= value;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -128,19 +124,18 @@ atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value)
  *
  * @return The value from  before the increment
  */
-atomic_val_t atomic_inc(atomic_t *target)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_inc(atomic_t *target) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    (*target)++;
+  ret = *target;
+  (*target)++;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -154,19 +149,18 @@ atomic_val_t atomic_inc(atomic_t *target)
  *
  * @return The value from  prior to the decrement
  */
-atomic_val_t atomic_dec(atomic_t *target)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_dec(atomic_t *target) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    (*target)--;
+  ret = *target;
+  (*target)--;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -181,10 +175,7 @@ atomic_val_t atomic_dec(atomic_t *target)
  *
  * @return The value read from 
  */
-atomic_val_t atomic_get(const atomic_t *target)
-{
-    return *target;
-}
+atomic_val_t atomic_get(const atomic_t *target) { return *target; }
 
 /**
  *
@@ -198,19 +189,18 @@ atomic_val_t atomic_get(const atomic_t *target)
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_set(atomic_t *target, atomic_val_t value)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_set(atomic_t *target, atomic_val_t value) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target = value;
+  ret     = *target;
+  *target = value;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -225,19 +215,18 @@ atomic_val_t atomic_set(atomic_t *target, atomic_val_t value)
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_clear(atomic_t *target)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_clear(atomic_t *target) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target = 0;
+  ret     = *target;
+  *target = 0;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -253,19 +242,18 @@ atomic_val_t atomic_clear(atomic_t *target)
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_or(atomic_t *target, atomic_val_t value)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_or(atomic_t *target, atomic_val_t value) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target |= value;
+  ret = *target;
+  *target |= value;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -281,19 +269,18 @@ atomic_val_t atomic_or(atomic_t *target, atomic_val_t value)
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target ^= value;
+  ret = *target;
+  *target ^= value;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -309,19 +296,18 @@ atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value)
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_and(atomic_t *target, atomic_val_t value)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_and(atomic_t *target, atomic_val_t value) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target &= value;
+  ret = *target;
+  *target &= value;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -337,17 +323,16 @@ atomic_val_t atomic_and(atomic_t *target, atomic_val_t value)
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_nand(atomic_t *target, atomic_val_t value)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_nand(atomic_t *target, atomic_val_t value) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target = ~(*target & value);
+  ret     = *target;
+  *target = ~(*target & value);
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c
index 44bdbda0d6..9fb971cb09 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c
@@ -13,14 +13,14 @@
 #endif
 
 #include 
-//LOG_MODULE_REGISTER(LOG_MODULE_NAME);
+// LOG_MODULE_REGISTER(LOG_MODULE_NAME);
 
-#include 
 #include 
-#include 
-#include 
 #include 
 #include 
+#include 
+#include 
+#include 
 #if defined(BFLB_BLE)
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
 #include "bl_port.h"
@@ -29,17 +29,16 @@
 #endif
 
 #if defined(CONFIG_NET_BUF_LOG)
-#define NET_BUF_DBG(fmt, ...) LOG_DBG("(%p) " fmt, k_current_get(), \
-                                      ##__VA_ARGS__)
+#define NET_BUF_DBG(fmt, ...)  LOG_DBG("(%p) " fmt, k_current_get(), ##__VA_ARGS__)
 #define NET_BUF_ERR(fmt, ...)  LOG_ERR(fmt, ##__VA_ARGS__)
 #define NET_BUF_WARN(fmt, ...) LOG_WRN(fmt, ##__VA_ARGS__)
 #define NET_BUF_INFO(fmt, ...) LOG_INF(fmt, ##__VA_ARGS__)
-#define NET_BUF_ASSERT(cond)                           \
-    do {                                               \
-        if (!(cond)) {                                 \
-            NET_BUF_ERR("assert: '" #cond "' failed"); \
-        }                                              \
-    } while (0)
+#define NET_BUF_ASSERT(cond)                     \
+  do {                                           \
+    if (!(cond)) {                               \
+      NET_BUF_ERR("assert: '" #cond "' failed"); \
+    }                                            \
+  } while (0)
 #else
 
 #define NET_BUF_DBG(fmt, ...)
@@ -50,7 +49,7 @@
 #endif /* CONFIG_NET_BUF_LOG */
 
 #if defined(CONFIG_NET_BUF_WARN_ALLOC_INTERVAL) && (CONFIG_NET_BUF_WARN_ALLOC_INTERVAL > 0)
-//#if CONFIG_NET_BUF_WARN_ALLOC_INTERVAL > 0
+// #if CONFIG_NET_BUF_WARN_ALLOC_INTERVAL > 0
 #define WARN_ALLOC_INTERVAL K_SECONDS(CONFIG_NET_BUF_WARN_ALLOC_INTERVAL)
 #else
 #define WARN_ALLOC_INTERVAL K_FOREVER
@@ -71,7 +70,7 @@ extern struct net_buf_pool acl_in_pool;
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
 extern struct net_buf_pool frag_pool;
 #endif
-#endif //CONFIG_BT_CONN
+#endif // CONFIG_BT_CONN
 #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT)
 extern struct net_buf_pool discardable_pool;
 #endif
@@ -80,7 +79,7 @@ extern struct net_buf_pool adv_buf_pool;
 extern struct net_buf_pool loopback_buf_pool;
 #if defined(CONFIG_BT_MESH_FRIEND)
 extern struct net_buf_pool friend_buf_pool;
-#endif //CONFIG_BT_MESH_FRIEND
+#endif // CONFIG_BT_MESH_FRIEND
 #endif
 #if defined(CONFIG_BT_BREDR)
 extern struct net_buf_pool br_sig_pool;
@@ -95,12 +94,10 @@ extern struct net_buf_pool data_pool;
 #endif
 
 struct net_buf_pool *_net_buf_pool_list[] = {
-    &hci_cmd_pool,
-    &hci_rx_pool,
+    &hci_cmd_pool,    &hci_rx_pool,
 
 #if defined(CONFIG_BT_CONN)
-    &acl_tx_pool,
-    &num_complete_pool,
+    &acl_tx_pool,     &num_complete_pool,
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
     &prep_pool,
 #endif
@@ -110,194 +107,171 @@ struct net_buf_pool *_net_buf_pool_list[] = {
 #if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0
     &frag_pool,
 #endif
-#endif //defined(CONFIG_BT_CONN)
+#endif // defined(CONFIG_BT_CONN)
 #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT)
     discardable_pool,
 #endif
 #ifdef CONFIG_BT_MESH
-    &adv_buf_pool,
-    &loopback_buf_pool,
+    &adv_buf_pool,    &loopback_buf_pool,
 #if defined(CONFIG_BT_MESH_FRIEND)
     &friend_buf_pool,
 #endif
 #endif
 #if defined(CONFIG_BT_BREDR)
-    &sdp_pool,
-    &br_sig_pool,
-    &hf_pool,
-    &dummy_pool,
+    &sdp_pool,        &br_sig_pool,       &hf_pool, &dummy_pool,
 #endif
 #if defined(CONFIG_AUTO_PTS)
-    &server_pool,
-    &data_pool,
+    &server_pool,     &data_pool,
 #endif
 };
 
 #else
 extern struct net_buf_pool _net_buf_pool_list[];
-#endif //BFLB_DYNAMIC_ALLOC_MEM
+#endif // BFLB_DYNAMIC_ALLOC_MEM
 
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-void net_buf_init(struct net_buf_pool *buf_pool, u16_t buf_count, size_t data_size, destroy_cb_t destroy)
-{
-    struct net_buf_pool_fixed *buf_fixed;
-    buf_pool->alloc = (struct net_buf_data_alloc *)k_malloc(sizeof(void *));
-    buf_pool->alloc->alloc_data = (struct net_buf_pool_fixed *)k_malloc(sizeof(void *));
-
-    buf_fixed = (struct net_buf_pool_fixed *)buf_pool->alloc->alloc_data;
-
-    buf_pool->alloc->cb = &net_buf_fixed_cb;
-    buf_fixed->data_size = data_size;
-    buf_fixed->data_pool = (u8_t *)k_malloc(buf_count * data_size);
-    buf_pool->__bufs = (struct net_buf *)k_malloc(buf_count * sizeof(struct net_buf));
-    buf_pool->buf_count = buf_count;
-    buf_pool->uninit_count = buf_count;
+void net_buf_init(struct net_buf_pool *buf_pool, u16_t buf_count, size_t data_size, destroy_cb_t destroy) {
+  struct net_buf_pool_fixed *buf_fixed;
+  buf_pool->alloc             = (struct net_buf_data_alloc *)k_malloc(sizeof(void *));
+  buf_pool->alloc->alloc_data = (struct net_buf_pool_fixed *)k_malloc(sizeof(void *));
+
+  buf_fixed = (struct net_buf_pool_fixed *)buf_pool->alloc->alloc_data;
+
+  buf_pool->alloc->cb    = &net_buf_fixed_cb;
+  buf_fixed->data_size   = data_size;
+  buf_fixed->data_pool   = (u8_t *)k_malloc(buf_count * data_size);
+  buf_pool->__bufs       = (struct net_buf *)k_malloc(buf_count * sizeof(struct net_buf));
+  buf_pool->buf_count    = buf_count;
+  buf_pool->uninit_count = buf_count;
 #if defined(CONFIG_NET_BUF_POOL_USAGE)
-    buf_pool->avail_count = buf_count;
+  buf_pool->avail_count = buf_count;
 #endif
-    buf_pool->destroy = destroy;
+  buf_pool->destroy = destroy;
 
-    k_lifo_init(&(buf_pool->free), buf_count);
+  k_lifo_init(&(buf_pool->free), buf_count);
 }
 
-void net_buf_deinit(struct net_buf_pool *buf_pool)
-{
-    extern void bt_delete_queue(struct k_fifo * queue_to_del);
-    bt_delete_queue((struct k_fifo *)(&(buf_pool->free)));
-
-    struct net_buf_pool_fixed *buf_fixed = (struct net_buf_pool_fixed *)buf_pool->alloc->alloc_data;
-    k_free(buf_fixed->data_pool);
-    k_free(buf_pool->__bufs);
-    k_free(buf_pool->alloc->alloc_data);
-    k_free(buf_pool->alloc);
+void net_buf_deinit(struct net_buf_pool *buf_pool) {
+  extern void bt_delete_queue(struct k_fifo * queue_to_del);
+  bt_delete_queue((struct k_fifo *)(&(buf_pool->free)));
+
+  struct net_buf_pool_fixed *buf_fixed = (struct net_buf_pool_fixed *)buf_pool->alloc->alloc_data;
+  k_free(buf_fixed->data_pool);
+  k_free(buf_pool->__bufs);
+  k_free(buf_pool->alloc->alloc_data);
+  k_free(buf_pool->alloc);
 }
 #endif
 
-struct net_buf_pool *net_buf_pool_get(int id)
-{
+struct net_buf_pool *net_buf_pool_get(int id) {
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    return _net_buf_pool_list[id];
+  return _net_buf_pool_list[id];
 #else
-    return &_net_buf_pool_list[id];
+  return &_net_buf_pool_list[id];
 #endif
 }
 
-static int pool_id(struct net_buf_pool *pool)
-{
+static int pool_id(struct net_buf_pool *pool) {
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    int index;
+  int index;
 
-    for (index = 0; index < (sizeof(_net_buf_pool_list) / 4); index++) {
-        if (_net_buf_pool_list[index] == pool) {
-            break;
-        }
+  for (index = 0; index < (sizeof(_net_buf_pool_list) / 4); index++) {
+    if (_net_buf_pool_list[index] == pool) {
+      break;
     }
-    NET_BUF_ASSERT(index < (sizeof(_net_buf_pool_list) / 4));
-    return index;
+  }
+  NET_BUF_ASSERT(index < (sizeof(_net_buf_pool_list) / 4));
+  return index;
 #else
-    return pool - _net_buf_pool_list;
+  return pool - _net_buf_pool_list;
 #endif
 }
 
-int net_buf_id(struct net_buf *buf)
-{
-    struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
+int net_buf_id(struct net_buf *buf) {
+  struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
 
-    return buf - pool->__bufs;
+  return buf - pool->__bufs;
 }
 
-static inline struct net_buf *pool_get_uninit(struct net_buf_pool *pool,
-                                              u16_t uninit_count)
-{
-    struct net_buf *buf;
+static inline struct net_buf *pool_get_uninit(struct net_buf_pool *pool, u16_t uninit_count) {
+  struct net_buf *buf;
 
-    buf = &pool->__bufs[pool->buf_count - uninit_count];
+  buf = &pool->__bufs[pool->buf_count - uninit_count];
 
-    buf->pool_id = pool_id(pool);
+  buf->pool_id = pool_id(pool);
 
-    return buf;
+  return buf;
 }
 
-void net_buf_reset(struct net_buf *buf)
-{
-    NET_BUF_ASSERT(buf->flags == 0U);
-    NET_BUF_ASSERT(buf->frags == NULL);
+void net_buf_reset(struct net_buf *buf) {
+  NET_BUF_ASSERT(buf->flags == 0U);
+  NET_BUF_ASSERT(buf->frags == NULL);
 
-    net_buf_simple_reset(&buf->b);
+  net_buf_simple_reset(&buf->b);
 }
 
 #if !defined(BFLB_BLE)
-static u8_t *generic_data_ref(struct net_buf *buf, u8_t *data)
-{
-    u8_t *ref_count;
+static u8_t *generic_data_ref(struct net_buf *buf, u8_t *data) {
+  u8_t *ref_count;
 
-    ref_count = data - 1;
-    (*ref_count)++;
+  ref_count = data - 1;
+  (*ref_count)++;
 
-    return data;
+  return data;
 }
 
-static u8_t *mem_pool_data_alloc(struct net_buf *buf, size_t *size,
-                                 s32_t timeout)
-{
-    struct net_buf_pool *buf_pool = net_buf_pool_get(buf->pool_id);
-    struct k_mem_pool *pool = buf_pool->alloc->alloc_data;
-    struct k_mem_block block;
-    u8_t *ref_count;
-
-    /* Reserve extra space for k_mem_block_id and ref-count (u8_t) */
-    if (k_mem_pool_alloc(pool, &block,
-                         sizeof(struct k_mem_block_id) + 1 + *size,
-                         timeout)) {
-        return NULL;
-    }
+static u8_t *mem_pool_data_alloc(struct net_buf *buf, size_t *size, s32_t timeout) {
+  struct net_buf_pool *buf_pool = net_buf_pool_get(buf->pool_id);
+  struct k_mem_pool   *pool     = buf_pool->alloc->alloc_data;
+  struct k_mem_block   block;
+  u8_t                *ref_count;
+
+  /* Reserve extra space for k_mem_block_id and ref-count (u8_t) */
+  if (k_mem_pool_alloc(pool, &block, sizeof(struct k_mem_block_id) + 1 + *size, timeout)) {
+    return NULL;
+  }
 
-    /* save the block descriptor info at the start of the actual block */
-    memcpy(block.data, &block.id, sizeof(block.id));
+  /* save the block descriptor info at the start of the actual block */
+  memcpy(block.data, &block.id, sizeof(block.id));
 
-    ref_count = (u8_t *)block.data + sizeof(block.id);
-    *ref_count = 1U;
+  ref_count  = (u8_t *)block.data + sizeof(block.id);
+  *ref_count = 1U;
 
-    /* Return pointer to the byte following the ref count */
-    return ref_count + 1;
+  /* Return pointer to the byte following the ref count */
+  return ref_count + 1;
 }
 
-static void mem_pool_data_unref(struct net_buf *buf, u8_t *data)
-{
-    struct k_mem_block_id id;
-    u8_t *ref_count;
+static void mem_pool_data_unref(struct net_buf *buf, u8_t *data) {
+  struct k_mem_block_id id;
+  u8_t                 *ref_count;
 
-    ref_count = data - 1;
-    if (--(*ref_count)) {
-        return;
-    }
+  ref_count = data - 1;
+  if (--(*ref_count)) {
+    return;
+  }
 
-    /* Need to copy to local variable due to alignment */
-    memcpy(&id, ref_count - sizeof(id), sizeof(id));
-    k_mem_pool_free_id(&id);
+  /* Need to copy to local variable due to alignment */
+  memcpy(&id, ref_count - sizeof(id), sizeof(id));
+  k_mem_pool_free_id(&id);
 }
 
 const struct net_buf_data_cb net_buf_var_cb = {
     .alloc = mem_pool_data_alloc,
-    .ref = generic_data_ref,
+    .ref   = generic_data_ref,
     .unref = mem_pool_data_unref,
 };
 #endif
 
-static u8_t *fixed_data_alloc(struct net_buf *buf, size_t *size, s32_t timeout)
-{
-    struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
-    const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data;
+static u8_t *fixed_data_alloc(struct net_buf *buf, size_t *size, s32_t timeout) {
+  struct net_buf_pool             *pool  = net_buf_pool_get(buf->pool_id);
+  const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data;
 
-    *size = MIN(fixed->data_size, *size);
+  *size = MIN(fixed->data_size, *size);
 
-    return fixed->data_pool + fixed->data_size * net_buf_id(buf);
+  return fixed->data_pool + fixed->data_size * net_buf_id(buf);
 }
 
-static void fixed_data_unref(struct net_buf *buf, u8_t *data)
-{
-    /* Nothing needed for fixed-size data pools */
-}
+static void fixed_data_unref(struct net_buf *buf, u8_t *data) { /* Nothing needed for fixed-size data pools */ }
 
 const struct net_buf_data_cb net_buf_fixed_cb = {
     .alloc = fixed_data_alloc,
@@ -306,35 +280,33 @@ const struct net_buf_data_cb net_buf_fixed_cb = {
 
 #if defined(CONFIG_HEAP_MEM_POOL_SIZE) && (CONFIG_HEAP_MEM_POOL_SIZE > 0)
 
-static u8_t *heap_data_alloc(struct net_buf *buf, size_t *size, s32_t timeout)
-{
-    u8_t *ref_count;
+static u8_t *heap_data_alloc(struct net_buf *buf, size_t *size, s32_t timeout) {
+  u8_t *ref_count;
 
-    ref_count = k_malloc(1 + *size);
-    if (!ref_count) {
-        return NULL;
-    }
+  ref_count = k_malloc(1 + *size);
+  if (!ref_count) {
+    return NULL;
+  }
 
-    *ref_count = 1U;
+  *ref_count = 1U;
 
-    return ref_count + 1;
+  return ref_count + 1;
 }
 
-static void heap_data_unref(struct net_buf *buf, u8_t *data)
-{
-    u8_t *ref_count;
+static void heap_data_unref(struct net_buf *buf, u8_t *data) {
+  u8_t *ref_count;
 
-    ref_count = data - 1;
-    if (--(*ref_count)) {
-        return;
-    }
+  ref_count = data - 1;
+  if (--(*ref_count)) {
+    return;
+  }
 
-    k_free(ref_count);
+  k_free(ref_count);
 }
 
 static const struct net_buf_data_cb net_buf_heap_cb = {
     .alloc = heap_data_alloc,
-    .ref = generic_data_ref,
+    .ref   = generic_data_ref,
     .unref = heap_data_unref,
 };
 
@@ -344,313 +316,282 @@ const struct net_buf_data_alloc net_buf_heap_alloc = {
 
 #endif /* CONFIG_HEAP_MEM_POOL_SIZE > 0 */
 
-static u8_t *data_alloc(struct net_buf *buf, size_t *size, s32_t timeout)
-{
-    struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
+static u8_t *data_alloc(struct net_buf *buf, size_t *size, s32_t timeout) {
+  struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
 
-    return pool->alloc->cb->alloc(buf, size, timeout);
+  return pool->alloc->cb->alloc(buf, size, timeout);
 }
 
-static u8_t *data_ref(struct net_buf *buf, u8_t *data)
-{
-    struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
+static u8_t *data_ref(struct net_buf *buf, u8_t *data) {
+  struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
 
-    return pool->alloc->cb->ref(buf, data);
+  return pool->alloc->cb->ref(buf, data);
 }
 
-static void data_unref(struct net_buf *buf, u8_t *data)
-{
-    struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
+static void data_unref(struct net_buf *buf, u8_t *data) {
+  struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
 
-    if (buf->flags & NET_BUF_EXTERNAL_DATA) {
-        return;
-    }
+  if (buf->flags & NET_BUF_EXTERNAL_DATA) {
+    return;
+  }
 
-    pool->alloc->cb->unref(buf, data);
+  pool->alloc->cb->unref(buf, data);
 }
 
 #if defined(CONFIG_NET_BUF_LOG)
-struct net_buf *net_buf_alloc_len_debug(struct net_buf_pool *pool, size_t size,
-                                        s32_t timeout, const char *func,
-                                        int line)
+struct net_buf *net_buf_alloc_len_debug(struct net_buf_pool *pool, size_t size, s32_t timeout, const char *func, int line)
 #else
-struct net_buf *net_buf_alloc_len(struct net_buf_pool *pool, size_t size,
-                                  s32_t timeout)
+struct net_buf *net_buf_alloc_len(struct net_buf_pool *pool, size_t size, s32_t timeout)
 #endif
 {
-    u32_t alloc_start = k_uptime_get_32();
-    struct net_buf *buf;
-    unsigned int key;
-
-    NET_BUF_ASSERT(pool);
-
-    NET_BUF_DBG("%s():%d: pool %p size %zu timeout %d", func, line, pool,
-                size, timeout);
-
-    /* We need to lock interrupts temporarily to prevent race conditions
-	 * when accessing pool->uninit_count.
-	 */
-    key = irq_lock();
-
-    /* If there are uninitialized buffers we're guaranteed to succeed
-	 * with the allocation one way or another.
-	 */
-    if (pool->uninit_count) {
-        u16_t uninit_count;
-
-        /* If this is not the first access to the pool, we can
-		 * be opportunistic and try to fetch a previously used
-		 * buffer from the LIFO with K_NO_WAIT.
-		 */
-        if (pool->uninit_count < pool->buf_count) {
-            buf = k_lifo_get(&pool->free, K_NO_WAIT);
-            if (buf) {
-                irq_unlock(key);
-                goto success;
-            }
-        }
-
-        uninit_count = pool->uninit_count--;
+  u32_t           alloc_start = k_uptime_get_32();
+  struct net_buf *buf;
+  unsigned int    key;
+
+  NET_BUF_ASSERT(pool);
+
+  NET_BUF_DBG("%s():%d: pool %p size %zu timeout %d", func, line, pool, size, timeout);
+
+  /* We need to lock interrupts temporarily to prevent race conditions
+   * when accessing pool->uninit_count.
+   */
+  key = irq_lock();
+
+  /* If there are uninitialized buffers we're guaranteed to succeed
+   * with the allocation one way or another.
+   */
+  if (pool->uninit_count) {
+    u16_t uninit_count;
+
+    /* If this is not the first access to the pool, we can
+     * be opportunistic and try to fetch a previously used
+     * buffer from the LIFO with K_NO_WAIT.
+     */
+    if (pool->uninit_count < pool->buf_count) {
+      buf = k_lifo_get(&pool->free, K_NO_WAIT);
+      if (buf) {
         irq_unlock(key);
-
-        buf = pool_get_uninit(pool, uninit_count);
         goto success;
+      }
     }
 
+    uninit_count = pool->uninit_count--;
     irq_unlock(key);
 
+    buf = pool_get_uninit(pool, uninit_count);
+    goto success;
+  }
+
+  irq_unlock(key);
+
 #if defined(CONFIG_NET_BUF_LOG) && (CONFIG_NET_BUF_LOG_LEVEL >= LOG_LEVEL_WRN)
-    if (timeout == K_FOREVER) {
-        u32_t ref = k_uptime_get_32();
-        buf = k_lifo_get(&pool->free, K_NO_WAIT);
-        while (!buf) {
+  if (timeout == K_FOREVER) {
+    u32_t ref = k_uptime_get_32();
+    buf       = k_lifo_get(&pool->free, K_NO_WAIT);
+    while (!buf) {
 #if defined(CONFIG_NET_BUF_POOL_USAGE)
-            NET_BUF_WARN("%s():%d: Pool %s low on buffers.",
-                         func, line, pool->name);
+      NET_BUF_WARN("%s():%d: Pool %s low on buffers.", func, line, pool->name);
 #else
-            NET_BUF_WARN("%s():%d: Pool %p low on buffers.",
-                         func, line, pool);
+      NET_BUF_WARN("%s():%d: Pool %p low on buffers.", func, line, pool);
 #endif
-            buf = k_lifo_get(&pool->free, WARN_ALLOC_INTERVAL);
+      buf = k_lifo_get(&pool->free, WARN_ALLOC_INTERVAL);
 #if defined(CONFIG_NET_BUF_POOL_USAGE)
-            NET_BUF_WARN("%s():%d: Pool %s blocked for %u secs",
-                         func, line, pool->name,
-                         (k_uptime_get_32() - ref) / MSEC_PER_SEC);
+      NET_BUF_WARN("%s():%d: Pool %s blocked for %u secs", func, line, pool->name, (k_uptime_get_32() - ref) / MSEC_PER_SEC);
 #else
-            NET_BUF_WARN("%s():%d: Pool %p blocked for %u secs",
-                         func, line, pool,
-                         (k_uptime_get_32() - ref) / MSEC_PER_SEC);
+      NET_BUF_WARN("%s():%d: Pool %p blocked for %u secs", func, line, pool, (k_uptime_get_32() - ref) / MSEC_PER_SEC);
 #endif
-        }
-    } else {
-        buf = k_lifo_get(&pool->free, timeout);
     }
-#else
+  } else {
     buf = k_lifo_get(&pool->free, timeout);
+  }
+#else
+  buf = k_lifo_get(&pool->free, timeout);
 #endif
-    if (!buf) {
-        NET_BUF_ERR("%s():%d: Failed to get free buffer", func, line);
-        return NULL;
-    }
+  if (!buf) {
+    NET_BUF_ERR("%s():%d: Failed to get free buffer", func, line);
+    return NULL;
+  }
 
 success:
-    NET_BUF_DBG("allocated buf %p", buf);
-
-    if (size) {
-        if (timeout != K_NO_WAIT && timeout != K_FOREVER) {
-            u32_t diff = k_uptime_get_32() - alloc_start;
-
-            timeout -= MIN(timeout, diff);
-        }
-
-        buf->__buf = data_alloc(buf, &size, timeout);
-        if (!buf->__buf) {
-            NET_BUF_ERR("%s():%d: Failed to allocate data",
-                        func, line);
-            net_buf_destroy(buf);
-            return NULL;
-        }
-    } else {
-        buf->__buf = NULL;
+  NET_BUF_DBG("allocated buf %p", buf);
+
+  if (size) {
+    if (timeout != K_NO_WAIT && timeout != K_FOREVER) {
+      u32_t diff = k_uptime_get_32() - alloc_start;
+
+      timeout -= MIN(timeout, diff);
     }
 
-    buf->ref = 1U;
-    buf->flags = 0U;
-    buf->frags = NULL;
-    buf->size = size;
-    net_buf_reset(buf);
+    buf->__buf = data_alloc(buf, &size, timeout);
+    if (!buf->__buf) {
+      NET_BUF_ERR("%s():%d: Failed to allocate data", func, line);
+      net_buf_destroy(buf);
+      return NULL;
+    }
+  } else {
+    buf->__buf = NULL;
+  }
+
+  buf->ref   = 1U;
+  buf->flags = 0U;
+  buf->frags = NULL;
+  buf->size  = size;
+  net_buf_reset(buf);
 
 #if defined(CONFIG_NET_BUF_POOL_USAGE)
-    pool->avail_count--;
-    NET_BUF_ASSERT(pool->avail_count >= 0);
+  pool->avail_count--;
+  NET_BUF_ASSERT(pool->avail_count >= 0);
 #endif
 
-    return buf;
+  return buf;
 }
 
 #if defined(CONFIG_NET_BUF_LOG)
-struct net_buf *net_buf_alloc_fixed_debug(struct net_buf_pool *pool,
-                                          s32_t timeout, const char *func,
-                                          int line)
-{
-    const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data;
+struct net_buf *net_buf_alloc_fixed_debug(struct net_buf_pool *pool, s32_t timeout, const char *func, int line) {
+  const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data;
 
-    return net_buf_alloc_len_debug(pool, fixed->data_size, timeout, func,
-                                   line);
+  return net_buf_alloc_len_debug(pool, fixed->data_size, timeout, func, line);
 }
 #else
-struct net_buf *net_buf_alloc_fixed(struct net_buf_pool *pool, s32_t timeout)
-{
-    const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data;
+struct net_buf *net_buf_alloc_fixed(struct net_buf_pool *pool, s32_t timeout) {
+  const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data;
 
-    return net_buf_alloc_len(pool, fixed->data_size, timeout);
+  return net_buf_alloc_len(pool, fixed->data_size, timeout);
 }
 #endif
 
 #if defined(CONFIG_NET_BUF_LOG)
-struct net_buf *net_buf_alloc_with_data_debug(struct net_buf_pool *pool,
-                                              void *data, size_t size,
-                                              s32_t timeout, const char *func,
-                                              int line)
+struct net_buf *net_buf_alloc_with_data_debug(struct net_buf_pool *pool, void *data, size_t size, s32_t timeout, const char *func, int line)
 #else
-struct net_buf *net_buf_alloc_with_data(struct net_buf_pool *pool,
-                                        void *data, size_t size,
-                                        s32_t timeout)
+struct net_buf *net_buf_alloc_with_data(struct net_buf_pool *pool, void *data, size_t size, s32_t timeout)
 #endif
 {
-    struct net_buf *buf;
+  struct net_buf *buf;
 
 #if defined(CONFIG_NET_BUF_LOG)
-    buf = net_buf_alloc_len_debug(pool, 0, timeout, func, line);
+  buf = net_buf_alloc_len_debug(pool, 0, timeout, func, line);
 #else
-    buf = net_buf_alloc_len(pool, 0, timeout);
+  buf = net_buf_alloc_len(pool, 0, timeout);
 #endif
-    if (!buf) {
-        return NULL;
-    }
+  if (!buf) {
+    return NULL;
+  }
 
-    buf->__buf = data;
-    buf->data = data;
-    buf->size = size;
-    buf->len = size;
-    buf->flags = NET_BUF_EXTERNAL_DATA;
+  buf->__buf = data;
+  buf->data  = data;
+  buf->size  = size;
+  buf->len   = size;
+  buf->flags = NET_BUF_EXTERNAL_DATA;
 
-    return buf;
+  return buf;
 }
 
 #if defined(CONFIG_NET_BUF_LOG)
-struct net_buf *net_buf_get_debug(struct k_fifo *fifo, s32_t timeout,
-                                  const char *func, int line)
+struct net_buf *net_buf_get_debug(struct k_fifo *fifo, s32_t timeout, const char *func, int line)
 #else
 struct net_buf *net_buf_get(struct k_fifo *fifo, s32_t timeout)
 #endif
 {
-    struct net_buf *buf, *frag;
+  struct net_buf *buf, *frag;
 
-    NET_BUF_DBG("%s():%d: fifo %p timeout %d", func, line, fifo, timeout);
+  NET_BUF_DBG("%s():%d: fifo %p timeout %d", func, line, fifo, timeout);
 
-    buf = k_fifo_get(fifo, timeout);
-    if (!buf) {
-        return NULL;
-    }
+  buf = k_fifo_get(fifo, timeout);
+  if (!buf) {
+    return NULL;
+  }
 
-    NET_BUF_DBG("%s():%d: buf %p fifo %p", func, line, buf, fifo);
+  NET_BUF_DBG("%s():%d: buf %p fifo %p", func, line, buf, fifo);
 
-    /* Get any fragments belonging to this buffer */
-    for (frag = buf; (frag->flags & NET_BUF_FRAGS); frag = frag->frags) {
-        frag->frags = k_fifo_get(fifo, K_NO_WAIT);
-        NET_BUF_ASSERT(frag->frags);
+  /* Get any fragments belonging to this buffer */
+  for (frag = buf; (frag->flags & NET_BUF_FRAGS); frag = frag->frags) {
+    frag->frags = k_fifo_get(fifo, K_NO_WAIT);
+    NET_BUF_ASSERT(frag->frags);
 
-        /* The fragments flag is only for FIFO-internal usage */
-        frag->flags &= ~NET_BUF_FRAGS;
-    }
+    /* The fragments flag is only for FIFO-internal usage */
+    frag->flags &= ~NET_BUF_FRAGS;
+  }
 
-    /* Mark the end of the fragment list */
-    frag->frags = NULL;
+  /* Mark the end of the fragment list */
+  frag->frags = NULL;
 
-    return buf;
+  return buf;
 }
 
-void net_buf_simple_init_with_data(struct net_buf_simple *buf,
-                                   void *data, size_t size)
-{
-    buf->__buf = data;
-    buf->data = data;
-    buf->size = size;
-    buf->len = size;
+void net_buf_simple_init_with_data(struct net_buf_simple *buf, void *data, size_t size) {
+  buf->__buf = data;
+  buf->data  = data;
+  buf->size  = size;
+  buf->len   = size;
 }
 
-void net_buf_simple_reserve(struct net_buf_simple *buf, size_t reserve)
-{
-    NET_BUF_ASSERT(buf);
-    NET_BUF_ASSERT(buf->len == 0U);
-    NET_BUF_DBG("buf %p reserve %zu", buf, reserve);
+void net_buf_simple_reserve(struct net_buf_simple *buf, size_t reserve) {
+  NET_BUF_ASSERT(buf);
+  NET_BUF_ASSERT(buf->len == 0U);
+  NET_BUF_DBG("buf %p reserve %zu", buf, reserve);
 
-    buf->data = buf->__buf + reserve;
+  buf->data = buf->__buf + reserve;
 }
 
-void net_buf_slist_put(sys_slist_t *list, struct net_buf *buf)
-{
-    struct net_buf *tail;
-    unsigned int key;
+void net_buf_slist_put(sys_slist_t *list, struct net_buf *buf) {
+  struct net_buf *tail;
+  unsigned int    key;
 
-    NET_BUF_ASSERT(list);
-    NET_BUF_ASSERT(buf);
+  NET_BUF_ASSERT(list);
+  NET_BUF_ASSERT(buf);
 
-    for (tail = buf; tail->frags; tail = tail->frags) {
-        tail->flags |= NET_BUF_FRAGS;
-    }
+  for (tail = buf; tail->frags; tail = tail->frags) {
+    tail->flags |= NET_BUF_FRAGS;
+  }
 
-    key = irq_lock();
-    sys_slist_append_list(list, &buf->node, &tail->node);
-    irq_unlock(key);
+  key = irq_lock();
+  sys_slist_append_list(list, &buf->node, &tail->node);
+  irq_unlock(key);
 }
 
-struct net_buf *net_buf_slist_get(sys_slist_t *list)
-{
-    struct net_buf *buf, *frag;
-    unsigned int key;
+struct net_buf *net_buf_slist_get(sys_slist_t *list) {
+  struct net_buf *buf, *frag;
+  unsigned int    key;
 
-    NET_BUF_ASSERT(list);
+  NET_BUF_ASSERT(list);
 
-    key = irq_lock();
-    buf = (void *)sys_slist_get(list);
-    irq_unlock(key);
+  key = irq_lock();
+  buf = (void *)sys_slist_get(list);
+  irq_unlock(key);
 
-    if (!buf) {
-        return NULL;
-    }
+  if (!buf) {
+    return NULL;
+  }
 
-    /* Get any fragments belonging to this buffer */
-    for (frag = buf; (frag->flags & NET_BUF_FRAGS); frag = frag->frags) {
-        key = irq_lock();
-        frag->frags = (void *)sys_slist_get(list);
-        irq_unlock(key);
+  /* Get any fragments belonging to this buffer */
+  for (frag = buf; (frag->flags & NET_BUF_FRAGS); frag = frag->frags) {
+    key         = irq_lock();
+    frag->frags = (void *)sys_slist_get(list);
+    irq_unlock(key);
 
-        NET_BUF_ASSERT(frag->frags);
+    NET_BUF_ASSERT(frag->frags);
 
-        /* The fragments flag is only for list-internal usage */
-        frag->flags &= ~NET_BUF_FRAGS;
-    }
+    /* The fragments flag is only for list-internal usage */
+    frag->flags &= ~NET_BUF_FRAGS;
+  }
 
-    /* Mark the end of the fragment list */
-    frag->frags = NULL;
+  /* Mark the end of the fragment list */
+  frag->frags = NULL;
 
-    return buf;
+  return buf;
 }
 
-void net_buf_put(struct k_fifo *fifo, struct net_buf *buf)
-{
-    struct net_buf *tail;
+void net_buf_put(struct k_fifo *fifo, struct net_buf *buf) {
+  struct net_buf *tail;
 
-    NET_BUF_ASSERT(fifo);
-    NET_BUF_ASSERT(buf);
+  NET_BUF_ASSERT(fifo);
+  NET_BUF_ASSERT(buf);
 
-    for (tail = buf; tail->frags; tail = tail->frags) {
-        tail->flags |= NET_BUF_FRAGS;
-    }
+  for (tail = buf; tail->frags; tail = tail->frags) {
+    tail->flags |= NET_BUF_FRAGS;
+  }
 
-    k_fifo_put_list(fifo, buf, tail);
+  k_fifo_put_list(fifo, buf, tail);
 }
 
 #if defined(CONFIG_NET_BUF_LOG)
@@ -659,257 +600,242 @@ void net_buf_unref_debug(struct net_buf *buf, const char *func, int line)
 void net_buf_unref(struct net_buf *buf)
 #endif
 {
-    NET_BUF_ASSERT(buf);
+  NET_BUF_ASSERT(buf);
 
-    while (buf) {
-        struct net_buf *frags = buf->frags;
-        struct net_buf_pool *pool;
+  while (buf) {
+    struct net_buf      *frags = buf->frags;
+    struct net_buf_pool *pool;
 
 #if defined(CONFIG_NET_BUF_LOG)
-        if (!buf->ref) {
-            NET_BUF_ERR("%s():%d: buf %p double free", func, line,
-                        buf);
-            return;
-        }
+    if (!buf->ref) {
+      NET_BUF_ERR("%s():%d: buf %p double free", func, line, buf);
+      return;
+    }
 #endif
-        NET_BUF_DBG("buf %p ref %u pool_id %u frags %p", buf, buf->ref,
-                    buf->pool_id, buf->frags);
+    NET_BUF_DBG("buf %p ref %u pool_id %u frags %p", buf, buf->ref, buf->pool_id, buf->frags);
 
-        unsigned int key = irq_lock(); /* Added by bouffalo lab, to protect ref decrease */
-        if (--buf->ref > 0) {
-            irq_unlock(key); /* Added by bouffalo lab */
-            return;
-        }
-        irq_unlock(key); /* Added by bouffalo lab */
+    unsigned int key = irq_lock(); /* Added by bouffalo lab, to protect ref decrease */
+    if (--buf->ref > 0) {
+      irq_unlock(key); /* Added by bouffalo lab */
+      return;
+    }
+    irq_unlock(key); /* Added by bouffalo lab */
 
-        if (buf->__buf) {
-            data_unref(buf, buf->__buf);
-            buf->__buf = NULL;
-        }
+    if (buf->__buf) {
+      data_unref(buf, buf->__buf);
+      buf->__buf = NULL;
+    }
 
-        buf->data = NULL;
-        buf->frags = NULL;
+    buf->data  = NULL;
+    buf->frags = NULL;
 
-        pool = net_buf_pool_get(buf->pool_id);
+    pool = net_buf_pool_get(buf->pool_id);
 
 #if defined(CONFIG_NET_BUF_POOL_USAGE)
-        pool->avail_count++;
-        NET_BUF_ASSERT(pool->avail_count <= pool->buf_count);
+    pool->avail_count++;
+    NET_BUF_ASSERT(pool->avail_count <= pool->buf_count);
 #endif
 
-        if (pool->destroy) {
-            pool->destroy(buf);
-        } else {
-            net_buf_destroy(buf);
-        }
+    if (pool->destroy) {
+      pool->destroy(buf);
+    } else {
+      net_buf_destroy(buf);
+    }
 
-        buf = frags;
+    buf = frags;
 
 #if defined(BFLB_BLE)
-        if (pool == &hci_rx_pool) {
-            bl_trigger_queued_msg();
-            return;
-        }
-#endif
+    if (pool == &hci_rx_pool) {
+      bl_trigger_queued_msg();
+      return;
     }
+#endif
+  }
 }
 
-struct net_buf *net_buf_ref(struct net_buf *buf)
-{
-    NET_BUF_ASSERT(buf);
+struct net_buf *net_buf_ref(struct net_buf *buf) {
+  NET_BUF_ASSERT(buf);
 
-    NET_BUF_DBG("buf %p (old) ref %u pool_id %u",
-                buf, buf->ref, buf->pool_id);
+  NET_BUF_DBG("buf %p (old) ref %u pool_id %u", buf, buf->ref, buf->pool_id);
 
-    unsigned int key = irq_lock(); /* Added by bouffalo lab,  to protect ref increase */
-    buf->ref++;
-    irq_unlock(key); /* Added by bouffalo lab */
-    return buf;
+  unsigned int key = irq_lock(); /* Added by bouffalo lab,  to protect ref increase */
+  buf->ref++;
+  irq_unlock(key); /* Added by bouffalo lab */
+  return buf;
 }
 
-struct net_buf *net_buf_clone(struct net_buf *buf, s32_t timeout)
-{
-    u32_t alloc_start = k_uptime_get_32();
-    struct net_buf_pool *pool;
-    struct net_buf *clone;
+struct net_buf *net_buf_clone(struct net_buf *buf, s32_t timeout) {
+  u32_t                alloc_start = k_uptime_get_32();
+  struct net_buf_pool *pool;
+  struct net_buf      *clone;
 
-    NET_BUF_ASSERT(buf);
+  NET_BUF_ASSERT(buf);
 
-    pool = net_buf_pool_get(buf->pool_id);
+  pool = net_buf_pool_get(buf->pool_id);
 
-    clone = net_buf_alloc_len(pool, 0, timeout);
-    if (!clone) {
-        return NULL;
-    }
-
-    /* If the pool supports data referencing use that. Otherwise
-	 * we need to allocate new data and make a copy.
-	 */
-    if (pool->alloc->cb->ref && !(buf->flags & NET_BUF_EXTERNAL_DATA)) {
-        clone->__buf = data_ref(buf, buf->__buf);
-        clone->data = buf->data;
-        clone->len = buf->len;
-        clone->size = buf->size;
-    } else {
-        size_t size = buf->size;
+  clone = net_buf_alloc_len(pool, 0, timeout);
+  if (!clone) {
+    return NULL;
+  }
 
-        if (timeout != K_NO_WAIT && timeout != K_FOREVER) {
-            u32_t diff = k_uptime_get_32() - alloc_start;
+  /* If the pool supports data referencing use that. Otherwise
+   * we need to allocate new data and make a copy.
+   */
+  if (pool->alloc->cb->ref && !(buf->flags & NET_BUF_EXTERNAL_DATA)) {
+    clone->__buf = data_ref(buf, buf->__buf);
+    clone->data  = buf->data;
+    clone->len   = buf->len;
+    clone->size  = buf->size;
+  } else {
+    size_t size = buf->size;
 
-            timeout -= MIN(timeout, diff);
-        }
+    if (timeout != K_NO_WAIT && timeout != K_FOREVER) {
+      u32_t diff = k_uptime_get_32() - alloc_start;
 
-        clone->__buf = data_alloc(clone, &size, timeout);
-        if (!clone->__buf || size < buf->size) {
-            net_buf_destroy(clone);
-            return NULL;
-        }
+      timeout -= MIN(timeout, diff);
+    }
 
-        clone->size = size;
-        clone->data = clone->__buf + net_buf_headroom(buf);
-        net_buf_add_mem(clone, buf->data, buf->len);
+    clone->__buf = data_alloc(clone, &size, timeout);
+    if (!clone->__buf || size < buf->size) {
+      net_buf_destroy(clone);
+      return NULL;
     }
 
-    return clone;
+    clone->size = size;
+    clone->data = clone->__buf + net_buf_headroom(buf);
+    net_buf_add_mem(clone, buf->data, buf->len);
+  }
+
+  return clone;
 }
 
-struct net_buf *net_buf_frag_last(struct net_buf *buf)
-{
-    NET_BUF_ASSERT(buf);
+struct net_buf *net_buf_frag_last(struct net_buf *buf) {
+  NET_BUF_ASSERT(buf);
 
-    while (buf->frags) {
-        buf = buf->frags;
-    }
+  while (buf->frags) {
+    buf = buf->frags;
+  }
 
-    return buf;
+  return buf;
 }
 
-void net_buf_frag_insert(struct net_buf *parent, struct net_buf *frag)
-{
-    NET_BUF_ASSERT(parent);
-    NET_BUF_ASSERT(frag);
+void net_buf_frag_insert(struct net_buf *parent, struct net_buf *frag) {
+  NET_BUF_ASSERT(parent);
+  NET_BUF_ASSERT(frag);
 
-    if (parent->frags) {
-        net_buf_frag_last(frag)->frags = parent->frags;
-    }
-    /* Take ownership of the fragment reference */
-    parent->frags = frag;
+  if (parent->frags) {
+    net_buf_frag_last(frag)->frags = parent->frags;
+  }
+  /* Take ownership of the fragment reference */
+  parent->frags = frag;
 }
 
-struct net_buf *net_buf_frag_add(struct net_buf *head, struct net_buf *frag)
-{
-    NET_BUF_ASSERT(frag);
+struct net_buf *net_buf_frag_add(struct net_buf *head, struct net_buf *frag) {
+  NET_BUF_ASSERT(frag);
 
-    if (!head) {
-        return net_buf_ref(frag);
-    }
+  if (!head) {
+    return net_buf_ref(frag);
+  }
 
-    net_buf_frag_insert(net_buf_frag_last(head), frag);
+  net_buf_frag_insert(net_buf_frag_last(head), frag);
 
-    return head;
+  return head;
 }
 
 #if defined(CONFIG_NET_BUF_LOG)
-struct net_buf *net_buf_frag_del_debug(struct net_buf *parent,
-                                       struct net_buf *frag,
-                                       const char *func, int line)
+struct net_buf *net_buf_frag_del_debug(struct net_buf *parent, struct net_buf *frag, const char *func, int line)
 #else
 struct net_buf *net_buf_frag_del(struct net_buf *parent, struct net_buf *frag)
 #endif
 {
-    struct net_buf *next_frag;
+  struct net_buf *next_frag;
 
-    NET_BUF_ASSERT(frag);
+  NET_BUF_ASSERT(frag);
 
-    if (parent) {
-        NET_BUF_ASSERT(parent->frags);
-        NET_BUF_ASSERT(parent->frags == frag);
-        parent->frags = frag->frags;
-    }
+  if (parent) {
+    NET_BUF_ASSERT(parent->frags);
+    NET_BUF_ASSERT(parent->frags == frag);
+    parent->frags = frag->frags;
+  }
 
-    next_frag = frag->frags;
+  next_frag = frag->frags;
 
-    frag->frags = NULL;
+  frag->frags = NULL;
 
 #if defined(CONFIG_NET_BUF_LOG)
-    net_buf_unref_debug(frag, func, line);
+  net_buf_unref_debug(frag, func, line);
 #else
-    net_buf_unref(frag);
+  net_buf_unref(frag);
 #endif
 
-    return next_frag;
+  return next_frag;
 }
 
-size_t net_buf_linearize(void *dst, size_t dst_len, struct net_buf *src,
-                         size_t offset, size_t len)
-{
-    struct net_buf *frag;
-    size_t to_copy;
-    size_t copied;
+size_t net_buf_linearize(void *dst, size_t dst_len, struct net_buf *src, size_t offset, size_t len) {
+  struct net_buf *frag;
+  size_t          to_copy;
+  size_t          copied;
 
-    len = MIN(len, dst_len);
+  len = MIN(len, dst_len);
 
-    frag = src;
+  frag = src;
 
-    /* find the right fragment to start copying from */
-    while (frag && offset >= frag->len) {
-        offset -= frag->len;
-        frag = frag->frags;
-    }
+  /* find the right fragment to start copying from */
+  while (frag && offset >= frag->len) {
+    offset -= frag->len;
+    frag = frag->frags;
+  }
 
-    /* traverse the fragment chain until len bytes are copied */
-    copied = 0;
-    while (frag && len > 0) {
-        to_copy = MIN(len, frag->len - offset);
-        memcpy((u8_t *)dst + copied, frag->data + offset, to_copy);
+  /* traverse the fragment chain until len bytes are copied */
+  copied = 0;
+  while (frag && len > 0) {
+    to_copy = MIN(len, frag->len - offset);
+    memcpy((u8_t *)dst + copied, frag->data + offset, to_copy);
 
-        copied += to_copy;
+    copied += to_copy;
 
-        /* to_copy is always <= len */
-        len -= to_copy;
-        frag = frag->frags;
+    /* to_copy is always <= len */
+    len -= to_copy;
+    frag = frag->frags;
 
-        /* after the first iteration, this value will be 0 */
-        offset = 0;
-    }
+    /* after the first iteration, this value will be 0 */
+    offset = 0;
+  }
 
-    return copied;
+  return copied;
 }
 
 /* This helper routine will append multiple bytes, if there is no place for
  * the data in current fragment then create new fragment and add it to
  * the buffer. It assumes that the buffer has at least one fragment.
  */
-size_t net_buf_append_bytes(struct net_buf *buf, size_t len,
-                            const void *value, s32_t timeout,
-                            net_buf_allocator_cb allocate_cb, void *user_data)
-{
-    struct net_buf *frag = net_buf_frag_last(buf);
-    size_t added_len = 0;
-    const u8_t *value8 = value;
+size_t net_buf_append_bytes(struct net_buf *buf, size_t len, const void *value, s32_t timeout, net_buf_allocator_cb allocate_cb, void *user_data) {
+  struct net_buf *frag      = net_buf_frag_last(buf);
+  size_t          added_len = 0;
+  const u8_t     *value8    = value;
 
-    do {
-        u16_t count = MIN(len, net_buf_tailroom(frag));
+  do {
+    u16_t count = MIN(len, net_buf_tailroom(frag));
 
-        net_buf_add_mem(frag, value8, count);
-        len -= count;
-        added_len += count;
-        value8 += count;
+    net_buf_add_mem(frag, value8, count);
+    len -= count;
+    added_len += count;
+    value8 += count;
 
-        if (len == 0) {
-            return added_len;
-        }
+    if (len == 0) {
+      return added_len;
+    }
 
-        frag = allocate_cb(timeout, user_data);
-        if (!frag) {
-            return added_len;
-        }
+    frag = allocate_cb(timeout, user_data);
+    if (!frag) {
+      return added_len;
+    }
 
-        net_buf_frag_add(buf, frag);
-    } while (1);
+    net_buf_frag_add(buf, frag);
+  } while (1);
 
-    /* Unreachable */
-    return 0;
+  /* Unreachable */
+  return 0;
 }
 
 #if defined(CONFIG_NET_BUF_SIMPLE_LOG)
@@ -926,212 +852,179 @@ size_t net_buf_append_bytes(struct net_buf *buf, size_t len,
 #define NET_BUF_SIMPLE_ASSERT(cond)
 #endif /* CONFIG_NET_BUF_SIMPLE_LOG */
 
-void net_buf_simple_clone(const struct net_buf_simple *original,
-                          struct net_buf_simple *clone)
-{
-    memcpy(clone, original, sizeof(struct net_buf_simple));
-}
+void net_buf_simple_clone(const struct net_buf_simple *original, struct net_buf_simple *clone) { memcpy(clone, original, sizeof(struct net_buf_simple)); }
 
-void *net_buf_simple_add(struct net_buf_simple *buf, size_t len)
-{
-    u8_t *tail = net_buf_simple_tail(buf);
+void *net_buf_simple_add(struct net_buf_simple *buf, size_t len) {
+  u8_t *tail = net_buf_simple_tail(buf);
 
-    NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
+  NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
 
-    NET_BUF_SIMPLE_ASSERT(net_buf_simple_tailroom(buf) >= len);
+  NET_BUF_SIMPLE_ASSERT(net_buf_simple_tailroom(buf) >= len);
 
-    buf->len += len;
-    return tail;
+  buf->len += len;
+  return tail;
 }
 
-void *net_buf_simple_add_mem(struct net_buf_simple *buf, const void *mem,
-                             size_t len)
-{
-    NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
+void *net_buf_simple_add_mem(struct net_buf_simple *buf, const void *mem, size_t len) {
+  NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
 
-    return memcpy(net_buf_simple_add(buf, len), mem, len);
+  return memcpy(net_buf_simple_add(buf, len), mem, len);
 }
 
-u8_t *net_buf_simple_add_u8(struct net_buf_simple *buf, u8_t val)
-{
-    u8_t *u8;
+u8_t *net_buf_simple_add_u8(struct net_buf_simple *buf, u8_t val) {
+  u8_t *u8;
 
-    NET_BUF_SIMPLE_DBG("buf %p val 0x%02x", buf, val);
+  NET_BUF_SIMPLE_DBG("buf %p val 0x%02x", buf, val);
 
-    u8 = net_buf_simple_add(buf, 1);
-    *u8 = val;
+  u8  = net_buf_simple_add(buf, 1);
+  *u8 = val;
 
-    return u8;
+  return u8;
 }
 
-void net_buf_simple_add_le16(struct net_buf_simple *buf, u16_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_add_le16(struct net_buf_simple *buf, u16_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_le16(val, net_buf_simple_add(buf, sizeof(val)));
+  sys_put_le16(val, net_buf_simple_add(buf, sizeof(val)));
 }
 
-void net_buf_simple_add_be16(struct net_buf_simple *buf, u16_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_add_be16(struct net_buf_simple *buf, u16_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_be16(val, net_buf_simple_add(buf, sizeof(val)));
+  sys_put_be16(val, net_buf_simple_add(buf, sizeof(val)));
 }
 
-void net_buf_simple_add_le24(struct net_buf_simple *buf, uint32_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_add_le24(struct net_buf_simple *buf, uint32_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_le24(val, net_buf_simple_add(buf, 3));
+  sys_put_le24(val, net_buf_simple_add(buf, 3));
 }
 
-void net_buf_simple_add_be24(struct net_buf_simple *buf, uint32_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_add_be24(struct net_buf_simple *buf, uint32_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_be24(val, net_buf_simple_add(buf, 3));
+  sys_put_be24(val, net_buf_simple_add(buf, 3));
 }
 
-void net_buf_simple_add_le32(struct net_buf_simple *buf, u32_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_add_le32(struct net_buf_simple *buf, u32_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_le32(val, net_buf_simple_add(buf, sizeof(val)));
+  sys_put_le32(val, net_buf_simple_add(buf, sizeof(val)));
 }
 
-void net_buf_simple_add_be32(struct net_buf_simple *buf, u32_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_add_be32(struct net_buf_simple *buf, u32_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_be32(val, net_buf_simple_add(buf, sizeof(val)));
+  sys_put_be32(val, net_buf_simple_add(buf, sizeof(val)));
 }
 
-void *net_buf_simple_push(struct net_buf_simple *buf, size_t len)
-{
-    NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
+void *net_buf_simple_push(struct net_buf_simple *buf, size_t len) {
+  NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
 
-    NET_BUF_SIMPLE_ASSERT(net_buf_simple_headroom(buf) >= len);
+  NET_BUF_SIMPLE_ASSERT(net_buf_simple_headroom(buf) >= len);
 
-    buf->data -= len;
-    buf->len += len;
-    return buf->data;
+  buf->data -= len;
+  buf->len += len;
+  return buf->data;
 }
 
-void net_buf_simple_push_le16(struct net_buf_simple *buf, u16_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_push_le16(struct net_buf_simple *buf, u16_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_le16(val, net_buf_simple_push(buf, sizeof(val)));
+  sys_put_le16(val, net_buf_simple_push(buf, sizeof(val)));
 }
 
-void net_buf_simple_push_be16(struct net_buf_simple *buf, u16_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_push_be16(struct net_buf_simple *buf, u16_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_be16(val, net_buf_simple_push(buf, sizeof(val)));
+  sys_put_be16(val, net_buf_simple_push(buf, sizeof(val)));
 }
 
-void net_buf_simple_push_u8(struct net_buf_simple *buf, u8_t val)
-{
-    u8_t *data = net_buf_simple_push(buf, 1);
+void net_buf_simple_push_u8(struct net_buf_simple *buf, u8_t val) {
+  u8_t *data = net_buf_simple_push(buf, 1);
 
-    *data = val;
+  *data = val;
 }
 
-void net_buf_simple_push_le24(struct net_buf_simple *buf, uint32_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_push_le24(struct net_buf_simple *buf, uint32_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_le24(val, net_buf_simple_push(buf, 3));
+  sys_put_le24(val, net_buf_simple_push(buf, 3));
 }
 
-void net_buf_simple_push_be24(struct net_buf_simple *buf, uint32_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_push_be24(struct net_buf_simple *buf, uint32_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_be24(val, net_buf_simple_push(buf, 3));
+  sys_put_be24(val, net_buf_simple_push(buf, 3));
 }
 
-void *net_buf_simple_pull(struct net_buf_simple *buf, size_t len)
-{
-    NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
+void *net_buf_simple_pull(struct net_buf_simple *buf, size_t len) {
+  NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
 
-    NET_BUF_SIMPLE_ASSERT(buf->len >= len);
+  NET_BUF_SIMPLE_ASSERT(buf->len >= len);
 
-    buf->len -= len;
-    return buf->data += len;
+  buf->len -= len;
+  return buf->data += len;
 }
 
-void *net_buf_simple_pull_mem(struct net_buf_simple *buf, size_t len)
-{
-    void *data = buf->data;
+void *net_buf_simple_pull_mem(struct net_buf_simple *buf, size_t len) {
+  void *data = buf->data;
 
-    NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
+  NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
 
-    NET_BUF_SIMPLE_ASSERT(buf->len >= len);
+  NET_BUF_SIMPLE_ASSERT(buf->len >= len);
 
-    buf->len -= len;
-    buf->data += len;
+  buf->len -= len;
+  buf->data += len;
 
-    return data;
+  return data;
 }
 
-u8_t net_buf_simple_pull_u8(struct net_buf_simple *buf)
-{
-    u8_t val;
+u8_t net_buf_simple_pull_u8(struct net_buf_simple *buf) {
+  u8_t val;
 
-    val = buf->data[0];
-    net_buf_simple_pull(buf, 1);
+  val = buf->data[0];
+  net_buf_simple_pull(buf, 1);
 
-    return val;
+  return val;
 }
 
-u16_t net_buf_simple_pull_le16(struct net_buf_simple *buf)
-{
-    u16_t val;
+u16_t net_buf_simple_pull_le16(struct net_buf_simple *buf) {
+  u16_t val;
 
-    val = UNALIGNED_GET((u16_t *)buf->data);
-    net_buf_simple_pull(buf, sizeof(val));
+  val = UNALIGNED_GET((u16_t *)buf->data);
+  net_buf_simple_pull(buf, sizeof(val));
 
-    return sys_le16_to_cpu(val);
+  return sys_le16_to_cpu(val);
 }
 
-u16_t net_buf_simple_pull_be16(struct net_buf_simple *buf)
-{
-    u16_t val;
+u16_t net_buf_simple_pull_be16(struct net_buf_simple *buf) {
+  u16_t val;
 
-    val = UNALIGNED_GET((u16_t *)buf->data);
-    net_buf_simple_pull(buf, sizeof(val));
+  val = UNALIGNED_GET((u16_t *)buf->data);
+  net_buf_simple_pull(buf, sizeof(val));
 
-    return sys_be16_to_cpu(val);
+  return sys_be16_to_cpu(val);
 }
 
-u32_t net_buf_simple_pull_le32(struct net_buf_simple *buf)
-{
-    u32_t val;
+u32_t net_buf_simple_pull_le32(struct net_buf_simple *buf) {
+  u32_t val;
 
-    val = UNALIGNED_GET((u32_t *)buf->data);
-    net_buf_simple_pull(buf, sizeof(val));
+  val = UNALIGNED_GET((u32_t *)buf->data);
+  net_buf_simple_pull(buf, sizeof(val));
 
-    return sys_le32_to_cpu(val);
+  return sys_le32_to_cpu(val);
 }
 
-u32_t net_buf_simple_pull_be32(struct net_buf_simple *buf)
-{
-    u32_t val;
+u32_t net_buf_simple_pull_be32(struct net_buf_simple *buf) {
+  u32_t val;
 
-    val = UNALIGNED_GET((u32_t *)buf->data);
-    net_buf_simple_pull(buf, sizeof(val));
+  val = UNALIGNED_GET((u32_t *)buf->data);
+  net_buf_simple_pull(buf, sizeof(val));
 
-    return sys_be32_to_cpu(val);
+  return sys_be32_to_cpu(val);
 }
 
-size_t net_buf_simple_headroom(struct net_buf_simple *buf)
-{
-    return buf->data - buf->__buf;
-}
+size_t net_buf_simple_headroom(struct net_buf_simple *buf) { return buf->data - buf->__buf; }
 
-size_t net_buf_simple_tailroom(struct net_buf_simple *buf)
-{
-    return buf->size - net_buf_simple_headroom(buf) - buf->len;
-}
+size_t net_buf_simple_tailroom(struct net_buf_simple *buf) { return buf->size - net_buf_simple_headroom(buf) - buf->len; }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dec.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dec.c
index 7c7f30c0a8..e0fd7b794a 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dec.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dec.c
@@ -6,28 +6,27 @@
 
 #include 
 
-u8_t u8_to_dec(char *buf, u8_t buflen, u8_t value)
-{
-    u8_t divisor = 100;
-    u8_t num_digits = 0;
-    u8_t digit;
+u8_t u8_to_dec(char *buf, u8_t buflen, u8_t value) {
+  u8_t divisor    = 100;
+  u8_t num_digits = 0;
+  u8_t digit;
 
-    while (buflen > 0 && divisor > 0) {
-        digit = value / divisor;
-        if (digit != 0 || divisor == 1 || num_digits != 0) {
-            *buf = (char)digit + '0';
-            buf++;
-            buflen--;
-            num_digits++;
-        }
-
-        value -= digit * divisor;
-        divisor /= 10;
+  while (buflen > 0 && divisor > 0) {
+    digit = value / divisor;
+    if (digit != 0 || divisor == 1 || num_digits != 0) {
+      *buf = (char)digit + '0';
+      buf++;
+      buflen--;
+      num_digits++;
     }
 
-    if (buflen) {
-        *buf = '\0';
-    }
+    value -= digit * divisor;
+    divisor /= 10;
+  }
+
+  if (buflen) {
+    *buf = '\0';
+  }
 
-    return num_digits;
+  return num_digits;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dummy.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dummy.c
index db90bb43cd..30184dcba5 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dummy.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dummy.c
@@ -33,8 +33,7 @@ BUILD_ASSERT(CONFIG_BT_CTLR_RX_PRIO < CONFIG_BT_HCI_TX_PRIO);
  * since it introduces ISR latency due to outputting log messages with
  * interrupts disabled.
  */
-#if !defined(CONFIG_TEST) && !defined(CONFIG_ARCH_POSIX) && \
-    (defined(CONFIG_BT_LL_SW_SPLIT) || defined(CONFIG_BT_LL_SW_LEGACY))
+#if !defined(CONFIG_TEST) && !defined(CONFIG_ARCH_POSIX) && (defined(CONFIG_BT_LL_SW_SPLIT) || defined(CONFIG_BT_LL_SW_LEGACY))
 BUILD_ASSERT_MSG(!IS_ENABLED(CONFIG_LOG_IMMEDIATE), "Immediate logging not "
                                                     "supported with the software Link Layer");
 #endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/hex.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/hex.c
index 2d2425c067..3161702053 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/hex.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/hex.c
@@ -4,8 +4,7 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
+#include 
 #include 
 #include 
-#include 
 // #include 
-
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/log.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/log.c
index 3a57907926..2f43ff2bd1 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/log.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/log.c
@@ -12,50 +12,47 @@
  * in a single printk call.
  */
 
-#include 
-#include 
-#include 
-#include 
 #include 
 #include 
+#include 
+#include 
+#include 
+#include 
 
-const char *bt_hex_real(const void *buf, size_t len)
-{
-    static const char hex[] = "0123456789abcdef";
+const char *bt_hex_real(const void *buf, size_t len) {
+  static const char hex[] = "0123456789abcdef";
 #if defined(CONFIG_BT_DEBUG_MONITOR)
-    static char str[255];
+  static char str[255];
 #else
-    static char str[128];
+  static char str[128];
 #endif
-    const u8_t *b = buf;
-    int i;
+  const u8_t *b = buf;
+  int         i;
 
-    len = MIN(len, (sizeof(str) - 1) / 2);
+  len = MIN(len, (sizeof(str) - 1) / 2);
 
-    for (i = 0; i < len; i++) {
-        str[i * 2] = hex[b[i] >> 4];
-        str[i * 2 + 1] = hex[b[i] & 0xf];
-    }
+  for (i = 0; i < len; i++) {
+    str[i * 2]     = hex[b[i] >> 4];
+    str[i * 2 + 1] = hex[b[i] & 0xf];
+  }
 
-    str[i * 2] = '\0';
+  str[i * 2] = '\0';
 
-    return str;
+  return str;
 }
 
-const char *bt_addr_str_real(const bt_addr_t *addr)
-{
-    static char str[BT_ADDR_STR_LEN];
+const char *bt_addr_str_real(const bt_addr_t *addr) {
+  static char str[BT_ADDR_STR_LEN];
 
-    bt_addr_to_str(addr, str, sizeof(str));
+  bt_addr_to_str(addr, str, sizeof(str));
 
-    return str;
+  return str;
 }
 
-const char *bt_addr_le_str_real(const bt_addr_le_t *addr)
-{
-    static char str[BT_ADDR_LE_STR_LEN];
+const char *bt_addr_le_str_real(const bt_addr_le_t *addr) {
+  static char str[BT_ADDR_LE_STR_LEN];
 
-    bt_addr_le_to_str(addr, str, sizeof(str));
+  bt_addr_le_to_str(addr, str, sizeof(str));
 
-    return str;
+  return str;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/poll.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/poll.c
index b97a4f798c..8dce95e29e 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/poll.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/poll.c
@@ -16,225 +16,203 @@
 
 #include 
 
+#include 
+#include 
+#include 
 #include 
 #include 
-#include 
-#include 
-#include 
 
 struct k_sem g_poll_sem;
 
-void k_poll_event_init(struct k_poll_event *event, u32_t type,
-                       int mode, void *obj)
-{
-    __ASSERT(mode == K_POLL_MODE_NOTIFY_ONLY,
-             "only NOTIFY_ONLY mode is supported\n");
-    __ASSERT(type < (1 << _POLL_NUM_TYPES), "invalid type\n");
-    __ASSERT(obj, "must provide an object\n");
-
-    event->poller = NULL;
-    /* event->tag is left uninitialized: the user will set it if needed */
-    event->type = type;
-    event->state = K_POLL_STATE_NOT_READY;
-    event->mode = mode;
-    event->unused = 0;
-    event->obj = obj;
+void k_poll_event_init(struct k_poll_event *event, u32_t type, int mode, void *obj) {
+  __ASSERT(mode == K_POLL_MODE_NOTIFY_ONLY, "only NOTIFY_ONLY mode is supported\n");
+  __ASSERT(type < (1 << _POLL_NUM_TYPES), "invalid type\n");
+  __ASSERT(obj, "must provide an object\n");
+
+  event->poller = NULL;
+  /* event->tag is left uninitialized: the user will set it if needed */
+  event->type   = type;
+  event->state  = K_POLL_STATE_NOT_READY;
+  event->mode   = mode;
+  event->unused = 0;
+  event->obj    = obj;
 }
 
 /* must be called with interrupts locked */
-static inline int is_condition_met(struct k_poll_event *event, u32_t *state)
-{
-    switch (event->type) {
-        case K_POLL_TYPE_SEM_AVAILABLE:
-            if (k_sem_count_get(event->sem) > 0) {
-                *state = K_POLL_STATE_SEM_AVAILABLE;
-                return 1;
-            }
-            break;
-        case K_POLL_TYPE_DATA_AVAILABLE:
-            if (!k_queue_is_empty(event->queue)) {
-                *state = K_POLL_STATE_FIFO_DATA_AVAILABLE;
-                return 1;
-            }
-            break;
-        case K_POLL_TYPE_SIGNAL:
-            if (event->signal->signaled) {
-                *state = K_POLL_STATE_SIGNALED;
-                return 1;
-            }
-            break;
-        case K_POLL_TYPE_IGNORE:
-            return 0;
-        default:
-            __ASSERT(0, "invalid event type (0x%x)\n", event->type);
-            break;
+static inline int is_condition_met(struct k_poll_event *event, u32_t *state) {
+  switch (event->type) {
+  case K_POLL_TYPE_SEM_AVAILABLE:
+    if (k_sem_count_get(event->sem) > 0) {
+      *state = K_POLL_STATE_SEM_AVAILABLE;
+      return 1;
     }
-
+    break;
+  case K_POLL_TYPE_DATA_AVAILABLE:
+    if (!k_queue_is_empty(event->queue)) {
+      *state = K_POLL_STATE_FIFO_DATA_AVAILABLE;
+      return 1;
+    }
+    break;
+  case K_POLL_TYPE_SIGNAL:
+    if (event->signal->signaled) {
+      *state = K_POLL_STATE_SIGNALED;
+      return 1;
+    }
+    break;
+  case K_POLL_TYPE_IGNORE:
     return 0;
-}
+  default:
+    __ASSERT(0, "invalid event type (0x%x)\n", event->type);
+    break;
+  }
 
-static inline void add_event(sys_dlist_t *events, struct k_poll_event *event,
-                             struct _poller *poller)
-{
-    sys_dlist_append(events, &event->_node);
+  return 0;
 }
 
-/* must be called with interrupts locked */
-static inline int register_event(struct k_poll_event *event,
-                                 struct _poller *poller)
-{
-    switch (event->type) {
-        case K_POLL_TYPE_SEM_AVAILABLE:
-            __ASSERT(event->sem, "invalid semaphore\n");
-            add_event(&event->sem->poll_events, event, poller);
-            break;
-        case K_POLL_TYPE_DATA_AVAILABLE:
-            __ASSERT(event->queue, "invalid queue\n");
-            add_event(&event->queue->poll_events, event, poller);
-            break;
-        case K_POLL_TYPE_SIGNAL:
-            __ASSERT(event->signal, "invalid poll signal\n");
-            add_event(&event->signal->poll_events, event, poller);
-            break;
-        case K_POLL_TYPE_IGNORE:
-            /* nothing to do */
-            break;
-        default:
-            __ASSERT(0, "invalid event type\n");
-            break;
-    }
-
-    event->poller = poller;
+static inline void add_event(sys_dlist_t *events, struct k_poll_event *event, struct _poller *poller) { sys_dlist_append(events, &event->_node); }
 
-    return 0;
+/* must be called with interrupts locked */
+static inline int register_event(struct k_poll_event *event, struct _poller *poller) {
+  switch (event->type) {
+  case K_POLL_TYPE_SEM_AVAILABLE:
+    __ASSERT(event->sem, "invalid semaphore\n");
+    add_event(&event->sem->poll_events, event, poller);
+    break;
+  case K_POLL_TYPE_DATA_AVAILABLE:
+    __ASSERT(event->queue, "invalid queue\n");
+    add_event(&event->queue->poll_events, event, poller);
+    break;
+  case K_POLL_TYPE_SIGNAL:
+    __ASSERT(event->signal, "invalid poll signal\n");
+    add_event(&event->signal->poll_events, event, poller);
+    break;
+  case K_POLL_TYPE_IGNORE:
+    /* nothing to do */
+    break;
+  default:
+    __ASSERT(0, "invalid event type\n");
+    break;
+  }
+
+  event->poller = poller;
+
+  return 0;
 }
 
 /* must be called with interrupts locked */
-static inline void clear_event_registration(struct k_poll_event *event)
-{
-    event->poller = NULL;
-
-    switch (event->type) {
-        case K_POLL_TYPE_SEM_AVAILABLE:
-            __ASSERT(event->sem, "invalid semaphore\n");
-            sys_dlist_remove(&event->_node);
-            break;
-        case K_POLL_TYPE_DATA_AVAILABLE:
-            __ASSERT(event->queue, "invalid queue\n");
-            sys_dlist_remove(&event->_node);
-            break;
-        case K_POLL_TYPE_SIGNAL:
-            __ASSERT(event->signal, "invalid poll signal\n");
-            sys_dlist_remove(&event->_node);
-            break;
-        case K_POLL_TYPE_IGNORE:
-            /* nothing to do */
-            break;
-        default:
-            __ASSERT(0, "invalid event type\n");
-            break;
-    }
+static inline void clear_event_registration(struct k_poll_event *event) {
+  event->poller = NULL;
+
+  switch (event->type) {
+  case K_POLL_TYPE_SEM_AVAILABLE:
+    __ASSERT(event->sem, "invalid semaphore\n");
+    sys_dlist_remove(&event->_node);
+    break;
+  case K_POLL_TYPE_DATA_AVAILABLE:
+    __ASSERT(event->queue, "invalid queue\n");
+    sys_dlist_remove(&event->_node);
+    break;
+  case K_POLL_TYPE_SIGNAL:
+    __ASSERT(event->signal, "invalid poll signal\n");
+    sys_dlist_remove(&event->_node);
+    break;
+  case K_POLL_TYPE_IGNORE:
+    /* nothing to do */
+    break;
+  default:
+    __ASSERT(0, "invalid event type\n");
+    break;
+  }
 }
 
 /* must be called with interrupts locked */
-static inline void clear_event_registrations(struct k_poll_event *events,
-                                             int last_registered,
-                                             unsigned int key)
-{
-    for (; last_registered >= 0; last_registered--) {
-        clear_event_registration(&events[last_registered]);
-        irq_unlock(key);
-        key = irq_lock();
-    }
+static inline void clear_event_registrations(struct k_poll_event *events, int last_registered, unsigned int key) {
+  for (; last_registered >= 0; last_registered--) {
+    clear_event_registration(&events[last_registered]);
+    irq_unlock(key);
+    key = irq_lock();
+  }
 }
 
-static inline void set_event_ready(struct k_poll_event *event, u32_t state)
-{
-    event->poller = NULL;
-    event->state |= state;
+static inline void set_event_ready(struct k_poll_event *event, u32_t state) {
+  event->poller = NULL;
+  event->state |= state;
 }
 
-static bool polling_events(struct k_poll_event *events, int num_events,
-                           s32_t timeout, int *last_registered)
-{
-    int rc;
-    bool polling = true;
-    unsigned int key;
-
-    for (int ii = 0; ii < num_events; ii++) {
-        u32_t state;
-        key = irq_lock();
-        if (is_condition_met(&events[ii], &state)) {
-            set_event_ready(&events[ii], state);
-            polling = false;
-        } else if (timeout != K_NO_WAIT && polling) {
-            rc = register_event(&events[ii], NULL);
-            if (rc == 0) {
-                ++(*last_registered);
-            } else {
-                __ASSERT(0, "unexpected return code\n");
-            }
-        }
-        irq_unlock(key);
+static bool polling_events(struct k_poll_event *events, int num_events, s32_t timeout, int *last_registered) {
+  int          rc;
+  bool         polling = true;
+  unsigned int key;
+
+  for (int ii = 0; ii < num_events; ii++) {
+    u32_t state;
+    key = irq_lock();
+    if (is_condition_met(&events[ii], &state)) {
+      set_event_ready(&events[ii], state);
+      polling = false;
+    } else if (timeout != K_NO_WAIT && polling) {
+      rc = register_event(&events[ii], NULL);
+      if (rc == 0) {
+        ++(*last_registered);
+      } else {
+        __ASSERT(0, "unexpected return code\n");
+      }
     }
-    return polling;
+    irq_unlock(key);
+  }
+  return polling;
 }
 
-int k_poll(struct k_poll_event *events, int num_events, s32_t timeout)
-{
-    __ASSERT(events, "NULL events\n");
-    __ASSERT(num_events > 0, "zero events\n");
+int k_poll(struct k_poll_event *events, int num_events, s32_t timeout) {
+  __ASSERT(events, "NULL events\n");
+  __ASSERT(num_events > 0, "zero events\n");
 
-    int last_registered = -1;
-    unsigned int key;
-    bool polling = true;
+  int          last_registered = -1;
+  unsigned int key;
+  bool         polling = true;
 
-    /* find events whose condition is already fulfilled */
-    polling = polling_events(events, num_events, timeout, &last_registered);
+  /* find events whose condition is already fulfilled */
+  polling = polling_events(events, num_events, timeout, &last_registered);
 
-    if (polling == false) {
-        goto exit;
-    }
+  if (polling == false) {
+    goto exit;
+  }
 
-    k_sem_take(&g_poll_sem, timeout);
+  k_sem_take(&g_poll_sem, timeout);
 
-    last_registered = -1;
-    polling_events(events, num_events, timeout, &last_registered);
+  last_registered = -1;
+  polling_events(events, num_events, timeout, &last_registered);
 exit:
-    key = irq_lock();
-    clear_event_registrations(events, last_registered, key);
-    irq_unlock(key);
-    return 0;
+  key = irq_lock();
+  clear_event_registrations(events, last_registered, key);
+  irq_unlock(key);
+  return 0;
 }
 
 /* must be called with interrupts locked */
-static int _signal_poll_event(struct k_poll_event *event, u32_t state,
-                              int *must_reschedule)
-{
-    *must_reschedule = 0;
-    set_event_ready(event, state);
-    return 0;
+static int _signal_poll_event(struct k_poll_event *event, u32_t state, int *must_reschedule) {
+  *must_reschedule = 0;
+  set_event_ready(event, state);
+  return 0;
 }
 
-int k_poll_signal_raise(struct k_poll_signal *signal, int result)
-{
-    unsigned int key = irq_lock();
-    struct k_poll_event *poll_event;
-    int must_reschedule;
+int k_poll_signal_raise(struct k_poll_signal *signal, int result) {
+  unsigned int         key = irq_lock();
+  struct k_poll_event *poll_event;
+  int                  must_reschedule;
 
-    signal->result = result;
-    signal->signaled = 1;
+  signal->result   = result;
+  signal->signaled = 1;
 
-    poll_event = (struct k_poll_event *)sys_dlist_get(&signal->poll_events);
-    if (!poll_event) {
-        irq_unlock(key);
-        return 0;
-    }
+  poll_event = (struct k_poll_event *)sys_dlist_get(&signal->poll_events);
+  if (!poll_event) {
+    irq_unlock(key);
+    return 0;
+  }
 
-    int rc = _signal_poll_event(poll_event, K_POLL_STATE_SIGNALED,
-                                &must_reschedule);
+  int rc = _signal_poll_event(poll_event, K_POLL_STATE_SIGNALED, &must_reschedule);
 
-    k_sem_give(&g_poll_sem);
-    irq_unlock(key);
-    return rc;
+  k_sem_give(&g_poll_sem);
+  irq_unlock(key);
+  return rc;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/rpa.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/rpa.c
index 231ca2215c..ef5d96c2aa 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/rpa.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/rpa.c
@@ -10,97 +10,91 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
-#include 
-#include 
 #include 
+#include 
 #include 
-#include 
 #include 
 #include 
+#include 
+#include 
+#include 
+#include 
 
-#include 
+#include <../include/bluetooth/crypto.h>
 #include 
-#include 
 #include 
-#include <../include/bluetooth/crypto.h>
+#include 
+#include 
 
 #define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_RPA)
 #define LOG_MODULE_NAME bt_rpa
 #include "log.h"
 
 #if defined(CONFIG_BT_CTLR_PRIVACY) || defined(CONFIG_BT_PRIVACY) || defined(CONFIG_BT_SMP)
-static int ah(const u8_t irk[16], const u8_t r[3], u8_t out[3])
-{
-    u8_t res[16];
-    int err;
-
-    BT_DBG("irk %s", bt_hex(irk, 16));
-    BT_DBG("r %s", bt_hex(r, 3));
-
-    /* r' = padding || r */
-    memcpy(res, r, 3);
-    (void)memset(res + 3, 0, 13);
-
-    err = bt_encrypt_le(irk, res, res);
-    if (err) {
-        return err;
-    }
-
-    /* The output of the random address function ah is:
-	 *      ah(h, r) = e(k, r') mod 2^24
-	 * The output of the security function e is then truncated to 24 bits
-	 * by taking the least significant 24 bits of the output of e as the
-	 * result of ah.
-	 */
-    memcpy(out, res, 3);
-
-    return 0;
+static int ah(const u8_t irk[16], const u8_t r[3], u8_t out[3]) {
+  u8_t res[16];
+  int  err;
+
+  BT_DBG("irk %s", bt_hex(irk, 16));
+  BT_DBG("r %s", bt_hex(r, 3));
+
+  /* r' = padding || r */
+  memcpy(res, r, 3);
+  (void)memset(res + 3, 0, 13);
+
+  err = bt_encrypt_le(irk, res, res);
+  if (err) {
+    return err;
+  }
+
+  /* The output of the random address function ah is:
+   *      ah(h, r) = e(k, r') mod 2^24
+   * The output of the security function e is then truncated to 24 bits
+   * by taking the least significant 24 bits of the output of e as the
+   * result of ah.
+   */
+  memcpy(out, res, 3);
+
+  return 0;
 }
 #endif
 
 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_CTLR_PRIVACY)
-bool bt_rpa_irk_matches(const u8_t irk[16], const bt_addr_t *addr)
-{
-    u8_t hash[3];
-    int err;
+bool bt_rpa_irk_matches(const u8_t irk[16], const bt_addr_t *addr) {
+  u8_t hash[3];
+  int  err;
 
-    BT_DBG("IRK %s bdaddr %s", bt_hex(irk, 16), bt_addr_str(addr));
+  BT_DBG("IRK %s bdaddr %s", bt_hex(irk, 16), bt_addr_str(addr));
 
-    err = ah(irk, addr->val + 3, hash);
-    if (err) {
-        return false;
-    }
+  err = ah(irk, addr->val + 3, hash);
+  if (err) {
+    return false;
+  }
 
-    return !memcmp(addr->val, hash, 3);
+  return !memcmp(addr->val, hash, 3);
 }
 #endif
 
 #if defined(CONFIG_BT_PRIVACY) || defined(CONFIG_BT_CTLR_PRIVACY)
-int bt_rpa_create(const u8_t irk[16], bt_addr_t *rpa)
-{
-    int err;
+int bt_rpa_create(const u8_t irk[16], bt_addr_t *rpa) {
+  int err;
 
-    err = bt_rand(rpa->val + 3, 3);
-    if (err) {
-        return err;
-    }
+  err = bt_rand(rpa->val + 3, 3);
+  if (err) {
+    return err;
+  }
 
-    BT_ADDR_SET_RPA(rpa);
+  BT_ADDR_SET_RPA(rpa);
 
-    err = ah(irk, rpa->val + 3, rpa->val);
-    if (err) {
-        return err;
-    }
+  err = ah(irk, rpa->val + 3, rpa->val);
+  if (err) {
+    return err;
+  }
 
-    BT_DBG("Created RPA %s", bt_addr_str((bt_addr_t *)rpa->val));
+  BT_DBG("Created RPA %s", bt_addr_str((bt_addr_t *)rpa->val));
 
-    return 0;
+  return 0;
 }
 #else
-int bt_rpa_create(const u8_t irk[16], bt_addr_t *rpa)
-{
-    return -ENOTSUP;
-}
+int bt_rpa_create(const u8_t irk[16], bt_addr_t *rpa) { return -ENOTSUP; }
 #endif /* CONFIG_BT_PRIVACY */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_decrypt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_decrypt.c
index 83719acc85..fa89d3b0bd 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_decrypt.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_decrypt.c
@@ -34,35 +34,17 @@
 #include 
 #include 
 
-static const uint8_t inv_sbox[256] = {
-    0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e,
-    0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
-    0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32,
-    0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
-    0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49,
-    0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
-    0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50,
-    0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
-    0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05,
-    0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
-    0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
-    0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
-    0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8,
-    0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
-    0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b,
-    0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
-    0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59,
-    0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
-    0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d,
-    0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
-    0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63,
-    0x55, 0x21, 0x0c, 0x7d
-};
-
-int tc_aes128_set_decrypt_key(TCAesKeySched_t s, const uint8_t *k)
-{
-    return tc_aes128_set_encrypt_key(s, k);
-}
+static const uint8_t inv_sbox[256]
+    = {0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
+       0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
+       0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
+       0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
+       0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
+       0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
+       0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
+       0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d};
+
+int tc_aes128_set_decrypt_key(TCAesKeySched_t s, const uint8_t *k) { return tc_aes128_set_encrypt_key(s, k); }
 
 #define mult8(a) (_double_byte(_double_byte(_double_byte(a))))
 #define mult9(a) (mult8(a) ^ (a))
@@ -70,52 +52,48 @@ int tc_aes128_set_decrypt_key(TCAesKeySched_t s, const uint8_t *k)
 #define multd(a) (mult8(a) ^ _double_byte(_double_byte(a)) ^ (a))
 #define multe(a) (mult8(a) ^ _double_byte(_double_byte(a)) ^ _double_byte(a))
 
-static inline void mult_row_column(uint8_t *out, const uint8_t *in)
-{
-    out[0] = multe(in[0]) ^ multb(in[1]) ^ multd(in[2]) ^ mult9(in[3]);
-    out[1] = mult9(in[0]) ^ multe(in[1]) ^ multb(in[2]) ^ multd(in[3]);
-    out[2] = multd(in[0]) ^ mult9(in[1]) ^ multe(in[2]) ^ multb(in[3]);
-    out[3] = multb(in[0]) ^ multd(in[1]) ^ mult9(in[2]) ^ multe(in[3]);
+static inline void mult_row_column(uint8_t *out, const uint8_t *in) {
+  out[0] = multe(in[0]) ^ multb(in[1]) ^ multd(in[2]) ^ mult9(in[3]);
+  out[1] = mult9(in[0]) ^ multe(in[1]) ^ multb(in[2]) ^ multd(in[3]);
+  out[2] = multd(in[0]) ^ mult9(in[1]) ^ multe(in[2]) ^ multb(in[3]);
+  out[3] = multb(in[0]) ^ multd(in[1]) ^ mult9(in[2]) ^ multe(in[3]);
 }
 
-static inline void inv_mix_columns(uint8_t *s)
-{
-    uint8_t t[Nb * Nk];
+static inline void inv_mix_columns(uint8_t *s) {
+  uint8_t t[Nb * Nk];
 
-    mult_row_column(t, s);
-    mult_row_column(&t[Nb], s + Nb);
-    mult_row_column(&t[2 * Nb], s + (2 * Nb));
-    mult_row_column(&t[3 * Nb], s + (3 * Nb));
-    (void)_copy(s, sizeof(t), t, sizeof(t));
+  mult_row_column(t, s);
+  mult_row_column(&t[Nb], s + Nb);
+  mult_row_column(&t[2 * Nb], s + (2 * Nb));
+  mult_row_column(&t[3 * Nb], s + (3 * Nb));
+  (void)_copy(s, sizeof(t), t, sizeof(t));
 }
 
-static inline void add_round_key(uint8_t *s, const unsigned int *k)
-{
-    s[0] ^= (uint8_t)(k[0] >> 24);
-    s[1] ^= (uint8_t)(k[0] >> 16);
-    s[2] ^= (uint8_t)(k[0] >> 8);
-    s[3] ^= (uint8_t)(k[0]);
-    s[4] ^= (uint8_t)(k[1] >> 24);
-    s[5] ^= (uint8_t)(k[1] >> 16);
-    s[6] ^= (uint8_t)(k[1] >> 8);
-    s[7] ^= (uint8_t)(k[1]);
-    s[8] ^= (uint8_t)(k[2] >> 24);
-    s[9] ^= (uint8_t)(k[2] >> 16);
-    s[10] ^= (uint8_t)(k[2] >> 8);
-    s[11] ^= (uint8_t)(k[2]);
-    s[12] ^= (uint8_t)(k[3] >> 24);
-    s[13] ^= (uint8_t)(k[3] >> 16);
-    s[14] ^= (uint8_t)(k[3] >> 8);
-    s[15] ^= (uint8_t)(k[3]);
+static inline void add_round_key(uint8_t *s, const unsigned int *k) {
+  s[0] ^= (uint8_t)(k[0] >> 24);
+  s[1] ^= (uint8_t)(k[0] >> 16);
+  s[2] ^= (uint8_t)(k[0] >> 8);
+  s[3] ^= (uint8_t)(k[0]);
+  s[4] ^= (uint8_t)(k[1] >> 24);
+  s[5] ^= (uint8_t)(k[1] >> 16);
+  s[6] ^= (uint8_t)(k[1] >> 8);
+  s[7] ^= (uint8_t)(k[1]);
+  s[8] ^= (uint8_t)(k[2] >> 24);
+  s[9] ^= (uint8_t)(k[2] >> 16);
+  s[10] ^= (uint8_t)(k[2] >> 8);
+  s[11] ^= (uint8_t)(k[2]);
+  s[12] ^= (uint8_t)(k[3] >> 24);
+  s[13] ^= (uint8_t)(k[3] >> 16);
+  s[14] ^= (uint8_t)(k[3] >> 8);
+  s[15] ^= (uint8_t)(k[3]);
 }
 
-static inline void inv_sub_bytes(uint8_t *s)
-{
-    unsigned int i;
+static inline void inv_sub_bytes(uint8_t *s) {
+  unsigned int i;
 
-    for (i = 0; i < (Nb * Nk); ++i) {
-        s[i] = inv_sbox[s[i]];
-    }
+  for (i = 0; i < (Nb * Nk); ++i) {
+    s[i] = inv_sbox[s[i]];
+  }
 }
 
 /*
@@ -123,61 +101,59 @@ static inline void inv_sub_bytes(uint8_t *s)
  * inv_mix_columns, but performs it here to reduce the number of memory
  * operations.
  */
-static inline void inv_shift_rows(uint8_t *s)
-{
-    uint8_t t[Nb * Nk];
-
-    t[0] = s[0];
-    t[1] = s[13];
-    t[2] = s[10];
-    t[3] = s[7];
-    t[4] = s[4];
-    t[5] = s[1];
-    t[6] = s[14];
-    t[7] = s[11];
-    t[8] = s[8];
-    t[9] = s[5];
-    t[10] = s[2];
-    t[11] = s[15];
-    t[12] = s[12];
-    t[13] = s[9];
-    t[14] = s[6];
-    t[15] = s[3];
-    (void)_copy(s, sizeof(t), t, sizeof(t));
+static inline void inv_shift_rows(uint8_t *s) {
+  uint8_t t[Nb * Nk];
+
+  t[0]  = s[0];
+  t[1]  = s[13];
+  t[2]  = s[10];
+  t[3]  = s[7];
+  t[4]  = s[4];
+  t[5]  = s[1];
+  t[6]  = s[14];
+  t[7]  = s[11];
+  t[8]  = s[8];
+  t[9]  = s[5];
+  t[10] = s[2];
+  t[11] = s[15];
+  t[12] = s[12];
+  t[13] = s[9];
+  t[14] = s[6];
+  t[15] = s[3];
+  (void)_copy(s, sizeof(t), t, sizeof(t));
 }
 
-int tc_aes_decrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s)
-{
-    uint8_t state[Nk * Nb];
-    unsigned int i;
-
-    if (out == (uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    } else if (in == (const uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    } else if (s == (TCAesKeySched_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_aes_decrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s) {
+  uint8_t      state[Nk * Nb];
+  unsigned int i;
 
-    (void)_copy(state, sizeof(state), in, sizeof(state));
+  if (out == (uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  } else if (in == (const uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  } else if (s == (TCAesKeySched_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    add_round_key(state, s->words + Nb * Nr);
+  (void)_copy(state, sizeof(state), in, sizeof(state));
 
-    for (i = Nr - 1; i > 0; --i) {
-        inv_shift_rows(state);
-        inv_sub_bytes(state);
-        add_round_key(state, s->words + Nb * i);
-        inv_mix_columns(state);
-    }
+  add_round_key(state, s->words + Nb * Nr);
 
+  for (i = Nr - 1; i > 0; --i) {
     inv_shift_rows(state);
     inv_sub_bytes(state);
-    add_round_key(state, s->words);
+    add_round_key(state, s->words + Nb * i);
+    inv_mix_columns(state);
+  }
+
+  inv_shift_rows(state);
+  inv_sub_bytes(state);
+  add_round_key(state, s->words);
 
-    (void)_copy(out, sizeof(state), state, sizeof(state));
+  (void)_copy(out, sizeof(state), state, sizeof(state));
 
-    /*zeroing out the state buffer */
-    _set(state, TC_ZERO_BYTE, sizeof(state));
+  /*zeroing out the state buffer */
+  _set(state, TC_ZERO_BYTE, sizeof(state));
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_encrypt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_encrypt.c
index 0cb47b84d0..c46a0cbb14 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_encrypt.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_encrypt.c
@@ -31,181 +31,152 @@
  */
 
 #include "aes.h"
-#include "utils.h"
 #include "constants.h"
+#include "utils.h"
 
-static const uint8_t sbox[256] = {
-    0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b,
-    0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
-    0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26,
-    0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
-    0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2,
-    0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
-    0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed,
-    0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
-    0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f,
-    0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
-    0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
-    0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
-    0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14,
-    0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
-    0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d,
-    0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
-    0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f,
-    0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
-    0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11,
-    0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
-    0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f,
-    0xb0, 0x54, 0xbb, 0x16
-};
-
-static inline unsigned int rotword(unsigned int a)
-{
-    return (((a) >> 24) | ((a) << 8));
-}
+static const uint8_t sbox[256]
+    = {0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
+       0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
+       0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
+       0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
+       0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
+       0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
+       0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
+       0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16};
+
+static inline unsigned int rotword(unsigned int a) { return (((a) >> 24) | ((a) << 8)); }
 
 #define subbyte(a, o) (sbox[((a) >> (o)) & 0xff] << (o))
 #define subword(a)    (subbyte(a, 24) | subbyte(a, 16) | subbyte(a, 8) | subbyte(a, 0))
 
-int tc_aes128_set_encrypt_key(TCAesKeySched_t s, const uint8_t *k)
-{
-    const unsigned int rconst[11] = {
-        0x00000000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000,
-        0x20000000, 0x40000000, 0x80000000, 0x1b000000, 0x36000000
-    };
-    unsigned int i;
-    unsigned int t;
-
-    if (s == (TCAesKeySched_t)0) {
-        return TC_CRYPTO_FAIL;
-    } else if (k == (const uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    }
-
-    for (i = 0; i < Nk; ++i) {
-        s->words[i] = (k[Nb * i] << 24) | (k[Nb * i + 1] << 16) |
-                      (k[Nb * i + 2] << 8) | (k[Nb * i + 3]);
+int tc_aes128_set_encrypt_key(TCAesKeySched_t s, const uint8_t *k) {
+  const unsigned int rconst[11] = {0x00000000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000, 0x1b000000, 0x36000000};
+  unsigned int       i;
+  unsigned int       t;
+
+  if (s == (TCAesKeySched_t)0) {
+    return TC_CRYPTO_FAIL;
+  } else if (k == (const uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  }
+
+  for (i = 0; i < Nk; ++i) {
+    s->words[i] = (k[Nb * i] << 24) | (k[Nb * i + 1] << 16) | (k[Nb * i + 2] << 8) | (k[Nb * i + 3]);
+  }
+
+  for (; i < (Nb * (Nr + 1)); ++i) {
+    t = s->words[i - 1];
+    if ((i % Nk) == 0) {
+      t = subword(rotword(t)) ^ rconst[i / Nk];
     }
+    s->words[i] = s->words[i - Nk] ^ t;
+  }
 
-    for (; i < (Nb * (Nr + 1)); ++i) {
-        t = s->words[i - 1];
-        if ((i % Nk) == 0) {
-            t = subword(rotword(t)) ^ rconst[i / Nk];
-        }
-        s->words[i] = s->words[i - Nk] ^ t;
-    }
-
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-static inline void add_round_key(uint8_t *s, const unsigned int *k)
-{
-    s[0] ^= (uint8_t)(k[0] >> 24);
-    s[1] ^= (uint8_t)(k[0] >> 16);
-    s[2] ^= (uint8_t)(k[0] >> 8);
-    s[3] ^= (uint8_t)(k[0]);
-    s[4] ^= (uint8_t)(k[1] >> 24);
-    s[5] ^= (uint8_t)(k[1] >> 16);
-    s[6] ^= (uint8_t)(k[1] >> 8);
-    s[7] ^= (uint8_t)(k[1]);
-    s[8] ^= (uint8_t)(k[2] >> 24);
-    s[9] ^= (uint8_t)(k[2] >> 16);
-    s[10] ^= (uint8_t)(k[2] >> 8);
-    s[11] ^= (uint8_t)(k[2]);
-    s[12] ^= (uint8_t)(k[3] >> 24);
-    s[13] ^= (uint8_t)(k[3] >> 16);
-    s[14] ^= (uint8_t)(k[3] >> 8);
-    s[15] ^= (uint8_t)(k[3]);
+static inline void add_round_key(uint8_t *s, const unsigned int *k) {
+  s[0] ^= (uint8_t)(k[0] >> 24);
+  s[1] ^= (uint8_t)(k[0] >> 16);
+  s[2] ^= (uint8_t)(k[0] >> 8);
+  s[3] ^= (uint8_t)(k[0]);
+  s[4] ^= (uint8_t)(k[1] >> 24);
+  s[5] ^= (uint8_t)(k[1] >> 16);
+  s[6] ^= (uint8_t)(k[1] >> 8);
+  s[7] ^= (uint8_t)(k[1]);
+  s[8] ^= (uint8_t)(k[2] >> 24);
+  s[9] ^= (uint8_t)(k[2] >> 16);
+  s[10] ^= (uint8_t)(k[2] >> 8);
+  s[11] ^= (uint8_t)(k[2]);
+  s[12] ^= (uint8_t)(k[3] >> 24);
+  s[13] ^= (uint8_t)(k[3] >> 16);
+  s[14] ^= (uint8_t)(k[3] >> 8);
+  s[15] ^= (uint8_t)(k[3]);
 }
 
-static inline void sub_bytes(uint8_t *s)
-{
-    unsigned int i;
+static inline void sub_bytes(uint8_t *s) {
+  unsigned int i;
 
-    for (i = 0; i < (Nb * Nk); ++i) {
-        s[i] = sbox[s[i]];
-    }
+  for (i = 0; i < (Nb * Nk); ++i) {
+    s[i] = sbox[s[i]];
+  }
 }
 
 #define triple(a) (_double_byte(a) ^ (a))
 
-static inline void mult_row_column(uint8_t *out, const uint8_t *in)
-{
-    out[0] = _double_byte(in[0]) ^ triple(in[1]) ^ in[2] ^ in[3];
-    out[1] = in[0] ^ _double_byte(in[1]) ^ triple(in[2]) ^ in[3];
-    out[2] = in[0] ^ in[1] ^ _double_byte(in[2]) ^ triple(in[3]);
-    out[3] = triple(in[0]) ^ in[1] ^ in[2] ^ _double_byte(in[3]);
+static inline void mult_row_column(uint8_t *out, const uint8_t *in) {
+  out[0] = _double_byte(in[0]) ^ triple(in[1]) ^ in[2] ^ in[3];
+  out[1] = in[0] ^ _double_byte(in[1]) ^ triple(in[2]) ^ in[3];
+  out[2] = in[0] ^ in[1] ^ _double_byte(in[2]) ^ triple(in[3]);
+  out[3] = triple(in[0]) ^ in[1] ^ in[2] ^ _double_byte(in[3]);
 }
 
-static inline void mix_columns(uint8_t *s)
-{
-    uint8_t t[Nb * Nk];
+static inline void mix_columns(uint8_t *s) {
+  uint8_t t[Nb * Nk];
 
-    mult_row_column(t, s);
-    mult_row_column(&t[Nb], s + Nb);
-    mult_row_column(&t[2 * Nb], s + (2 * Nb));
-    mult_row_column(&t[3 * Nb], s + (3 * Nb));
-    (void)_copy(s, sizeof(t), t, sizeof(t));
+  mult_row_column(t, s);
+  mult_row_column(&t[Nb], s + Nb);
+  mult_row_column(&t[2 * Nb], s + (2 * Nb));
+  mult_row_column(&t[3 * Nb], s + (3 * Nb));
+  (void)_copy(s, sizeof(t), t, sizeof(t));
 }
 
 /*
  * This shift_rows also implements the matrix flip required for mix_columns, but
  * performs it here to reduce the number of memory operations.
  */
-static inline void shift_rows(uint8_t *s)
-{
-    uint8_t t[Nb * Nk];
-
-    t[0] = s[0];
-    t[1] = s[5];
-    t[2] = s[10];
-    t[3] = s[15];
-    t[4] = s[4];
-    t[5] = s[9];
-    t[6] = s[14];
-    t[7] = s[3];
-    t[8] = s[8];
-    t[9] = s[13];
-    t[10] = s[2];
-    t[11] = s[7];
-    t[12] = s[12];
-    t[13] = s[1];
-    t[14] = s[6];
-    t[15] = s[11];
-    (void)_copy(s, sizeof(t), t, sizeof(t));
+static inline void shift_rows(uint8_t *s) {
+  uint8_t t[Nb * Nk];
+
+  t[0]  = s[0];
+  t[1]  = s[5];
+  t[2]  = s[10];
+  t[3]  = s[15];
+  t[4]  = s[4];
+  t[5]  = s[9];
+  t[6]  = s[14];
+  t[7]  = s[3];
+  t[8]  = s[8];
+  t[9]  = s[13];
+  t[10] = s[2];
+  t[11] = s[7];
+  t[12] = s[12];
+  t[13] = s[1];
+  t[14] = s[6];
+  t[15] = s[11];
+  (void)_copy(s, sizeof(t), t, sizeof(t));
 }
 
-int tc_aes_encrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s)
-{
-    uint8_t state[Nk * Nb];
-    unsigned int i;
-
-    if (out == (uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    } else if (in == (const uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    } else if (s == (TCAesKeySched_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_aes_encrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s) {
+  uint8_t      state[Nk * Nb];
+  unsigned int i;
 
-    (void)_copy(state, sizeof(state), in, sizeof(state));
-    add_round_key(state, s->words);
+  if (out == (uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  } else if (in == (const uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  } else if (s == (TCAesKeySched_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    for (i = 0; i < (Nr - 1); ++i) {
-        sub_bytes(state);
-        shift_rows(state);
-        mix_columns(state);
-        add_round_key(state, s->words + Nb * (i + 1));
-    }
+  (void)_copy(state, sizeof(state), in, sizeof(state));
+  add_round_key(state, s->words);
 
+  for (i = 0; i < (Nr - 1); ++i) {
     sub_bytes(state);
     shift_rows(state);
+    mix_columns(state);
     add_round_key(state, s->words + Nb * (i + 1));
+  }
+
+  sub_bytes(state);
+  shift_rows(state);
+  add_round_key(state, s->words + Nb * (i + 1));
 
-    (void)_copy(out, sizeof(state), state, sizeof(state));
+  (void)_copy(out, sizeof(state), state, sizeof(state));
 
-    /* zeroing out the state buffer */
-    _set(state, TC_ZERO_BYTE, sizeof(state));
+  /* zeroing out the state buffer */
+  _set(state, TC_ZERO_BYTE, sizeof(state));
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cbc_mode.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cbc_mode.c
index b405d7d297..7b8e1fd327 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cbc_mode.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cbc_mode.c
@@ -34,79 +34,60 @@
 #include "constants.h"
 #include "utils.h"
 
-int tc_cbc_mode_encrypt(uint8_t *out, unsigned int outlen, const uint8_t *in,
-                        unsigned int inlen, const uint8_t *iv,
-                        const TCAesKeySched_t sched)
-{
-    uint8_t buffer[TC_AES_BLOCK_SIZE];
-    unsigned int n, m;
+int tc_cbc_mode_encrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, const uint8_t *iv, const TCAesKeySched_t sched) {
+  uint8_t      buffer[TC_AES_BLOCK_SIZE];
+  unsigned int n, m;
 
-    /* input sanity check: */
-    if (out == (uint8_t *)0 ||
-        in == (const uint8_t *)0 ||
-        sched == (TCAesKeySched_t)0 ||
-        inlen == 0 ||
-        outlen == 0 ||
-        (inlen % TC_AES_BLOCK_SIZE) != 0 ||
-        (outlen % TC_AES_BLOCK_SIZE) != 0 ||
-        outlen != inlen + TC_AES_BLOCK_SIZE) {
-        return TC_CRYPTO_FAIL;
-    }
+  /* input sanity check: */
+  if (out == (uint8_t *)0 || in == (const uint8_t *)0 || sched == (TCAesKeySched_t)0 || inlen == 0 || outlen == 0 || (inlen % TC_AES_BLOCK_SIZE) != 0 || (outlen % TC_AES_BLOCK_SIZE) != 0
+      || outlen != inlen + TC_AES_BLOCK_SIZE) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    /* copy iv to the buffer */
-    (void)_copy(buffer, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE);
-    /* copy iv to the output buffer */
-    (void)_copy(out, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE);
-    out += TC_AES_BLOCK_SIZE;
+  /* copy iv to the buffer */
+  (void)_copy(buffer, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE);
+  /* copy iv to the output buffer */
+  (void)_copy(out, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE);
+  out += TC_AES_BLOCK_SIZE;
 
-    for (n = m = 0; n < inlen; ++n) {
-        buffer[m++] ^= *in++;
-        if (m == TC_AES_BLOCK_SIZE) {
-            (void)tc_aes_encrypt(buffer, buffer, sched);
-            (void)_copy(out, TC_AES_BLOCK_SIZE,
-                        buffer, TC_AES_BLOCK_SIZE);
-            out += TC_AES_BLOCK_SIZE;
-            m = 0;
-        }
+  for (n = m = 0; n < inlen; ++n) {
+    buffer[m++] ^= *in++;
+    if (m == TC_AES_BLOCK_SIZE) {
+      (void)tc_aes_encrypt(buffer, buffer, sched);
+      (void)_copy(out, TC_AES_BLOCK_SIZE, buffer, TC_AES_BLOCK_SIZE);
+      out += TC_AES_BLOCK_SIZE;
+      m = 0;
     }
+  }
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_cbc_mode_decrypt(uint8_t *out, unsigned int outlen, const uint8_t *in,
-                        unsigned int inlen, const uint8_t *iv,
-                        const TCAesKeySched_t sched)
-{
-    uint8_t buffer[TC_AES_BLOCK_SIZE];
-    const uint8_t *p;
-    unsigned int n, m;
+int tc_cbc_mode_decrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, const uint8_t *iv, const TCAesKeySched_t sched) {
+  uint8_t        buffer[TC_AES_BLOCK_SIZE];
+  const uint8_t *p;
+  unsigned int   n, m;
 
-    /* sanity check the inputs */
-    if (out == (uint8_t *)0 ||
-        in == (const uint8_t *)0 ||
-        sched == (TCAesKeySched_t)0 ||
-        inlen == 0 ||
-        outlen == 0 ||
-        (inlen % TC_AES_BLOCK_SIZE) != 0 ||
-        (outlen % TC_AES_BLOCK_SIZE) != 0 ||
-        outlen != inlen) {
-        return TC_CRYPTO_FAIL;
-    }
+  /* sanity check the inputs */
+  if (out == (uint8_t *)0 || in == (const uint8_t *)0 || sched == (TCAesKeySched_t)0 || inlen == 0 || outlen == 0 || (inlen % TC_AES_BLOCK_SIZE) != 0 || (outlen % TC_AES_BLOCK_SIZE) != 0
+      || outlen != inlen) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    /*
-	 * Note that in == iv + ciphertext, i.e. the iv and the ciphertext are
-	 * contiguous. This allows for a very efficient decryption algorithm
-	 * that would not otherwise be possible.
-	 */
-    p = iv;
-    for (n = m = 0; n < outlen; ++n) {
-        if ((n % TC_AES_BLOCK_SIZE) == 0) {
-            (void)tc_aes_decrypt(buffer, in, sched);
-            in += TC_AES_BLOCK_SIZE;
-            m = 0;
-        }
-        *out++ = buffer[m++] ^ *p++;
+  /*
+   * Note that in == iv + ciphertext, i.e. the iv and the ciphertext are
+   * contiguous. This allows for a very efficient decryption algorithm
+   * that would not otherwise be possible.
+   */
+  p = iv;
+  for (n = m = 0; n < outlen; ++n) {
+    if ((n % TC_AES_BLOCK_SIZE) == 0) {
+      (void)tc_aes_decrypt(buffer, in, sched);
+      in += TC_AES_BLOCK_SIZE;
+      m = 0;
     }
+    *out++ = buffer[m++] ^ *p++;
+  }
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ccm_mode.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ccm_mode.c
index ed94e75bb0..321473e258 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ccm_mode.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ccm_mode.c
@@ -36,50 +36,44 @@
 
 #include 
 
-int tc_ccm_config(TCCcmMode_t c, TCAesKeySched_t sched, uint8_t *nonce,
-                  unsigned int nlen, unsigned int mlen)
-{
-    /* input sanity check: */
-    if (c == (TCCcmMode_t)0 ||
-        sched == (TCAesKeySched_t)0 ||
-        nonce == (uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    } else if (nlen != 13) {
-        return TC_CRYPTO_FAIL; /* The allowed nonce size is: 13. See documentation.*/
-    } else if ((mlen < 4) || (mlen > 16) || (mlen & 1)) {
-        return TC_CRYPTO_FAIL; /* The allowed mac sizes are: 4, 6, 8, 10, 12, 14, 16.*/
-    }
-
-    c->mlen = mlen;
-    c->sched = sched;
-    c->nonce = nonce;
-
-    return TC_CRYPTO_SUCCESS;
+int tc_ccm_config(TCCcmMode_t c, TCAesKeySched_t sched, uint8_t *nonce, unsigned int nlen, unsigned int mlen) {
+  /* input sanity check: */
+  if (c == (TCCcmMode_t)0 || sched == (TCAesKeySched_t)0 || nonce == (uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  } else if (nlen != 13) {
+    return TC_CRYPTO_FAIL; /* The allowed nonce size is: 13. See documentation.*/
+  } else if ((mlen < 4) || (mlen > 16) || (mlen & 1)) {
+    return TC_CRYPTO_FAIL; /* The allowed mac sizes are: 4, 6, 8, 10, 12, 14, 16.*/
+  }
+
+  c->mlen  = mlen;
+  c->sched = sched;
+  c->nonce = nonce;
+
+  return TC_CRYPTO_SUCCESS;
 }
 
 /**
  * Variation of CBC-MAC mode used in CCM.
  */
-static void ccm_cbc_mac(uint8_t *T, const uint8_t *data, unsigned int dlen,
-                        unsigned int flag, TCAesKeySched_t sched)
-{
-    unsigned int i;
-
-    if (flag > 0) {
-        T[0] ^= (uint8_t)(dlen >> 8);
-        T[1] ^= (uint8_t)(dlen);
-        dlen += 2;
-        i = 2;
-    } else {
-        i = 0;
-    }
-
-    while (i < dlen) {
-        T[i++ % (Nb * Nk)] ^= *data++;
-        if (((i % (Nb * Nk)) == 0) || dlen == i) {
-            (void)tc_aes_encrypt(T, T, sched);
-        }
-    }
+static void ccm_cbc_mac(uint8_t *T, const uint8_t *data, unsigned int dlen, unsigned int flag, TCAesKeySched_t sched) {
+  unsigned int i;
+
+  if (flag > 0) {
+    T[0] ^= (uint8_t)(dlen >> 8);
+    T[1] ^= (uint8_t)(dlen);
+    dlen += 2;
+    i = 2;
+  } else {
+    i = 0;
+  }
+
+  while (i < dlen) {
+    T[i++ % (Nb * Nk)] ^= *data++;
+    if (((i % (Nb * Nk)) == 0) || dlen == i) {
+      (void)tc_aes_encrypt(T, T, sched);
+    }
+  }
 }
 
 /**
@@ -89,175 +83,153 @@ static void ccm_cbc_mac(uint8_t *T, const uint8_t *data, unsigned int dlen,
  * encryption). Besides, it is assumed that the counter is stored in the last
  * 2 bytes of the nonce.
  */
-static int ccm_ctr_mode(uint8_t *out, unsigned int outlen, const uint8_t *in,
-                        unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched)
-{
-    uint8_t buffer[TC_AES_BLOCK_SIZE];
-    uint8_t nonce[TC_AES_BLOCK_SIZE];
-    uint16_t block_num;
-    unsigned int i;
-
-    /* input sanity check: */
-    if (out == (uint8_t *)0 ||
-        in == (uint8_t *)0 ||
-        ctr == (uint8_t *)0 ||
-        sched == (TCAesKeySched_t)0 ||
-        inlen == 0 ||
-        outlen == 0 ||
-        outlen != inlen) {
+static int ccm_ctr_mode(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched) {
+  uint8_t      buffer[TC_AES_BLOCK_SIZE];
+  uint8_t      nonce[TC_AES_BLOCK_SIZE];
+  uint16_t     block_num;
+  unsigned int i;
+
+  /* input sanity check: */
+  if (out == (uint8_t *)0 || in == (uint8_t *)0 || ctr == (uint8_t *)0 || sched == (TCAesKeySched_t)0 || inlen == 0 || outlen == 0 || outlen != inlen) {
+    return TC_CRYPTO_FAIL;
+  }
+
+  /* copy the counter to the nonce */
+  (void)_copy(nonce, sizeof(nonce), ctr, sizeof(nonce));
+
+  /* select the last 2 bytes of the nonce to be incremented */
+  block_num = (uint16_t)((nonce[14] << 8) | (nonce[15]));
+  for (i = 0; i < inlen; ++i) {
+    if ((i % (TC_AES_BLOCK_SIZE)) == 0) {
+      block_num++;
+      nonce[14] = (uint8_t)(block_num >> 8);
+      nonce[15] = (uint8_t)(block_num);
+      if (!tc_aes_encrypt(buffer, nonce, sched)) {
         return TC_CRYPTO_FAIL;
+      }
     }
+    /* update the output */
+    *out++ = buffer[i % (TC_AES_BLOCK_SIZE)] ^ *in++;
+  }
 
-    /* copy the counter to the nonce */
-    (void)_copy(nonce, sizeof(nonce), ctr, sizeof(nonce));
-
-    /* select the last 2 bytes of the nonce to be incremented */
-    block_num = (uint16_t)((nonce[14] << 8) | (nonce[15]));
-    for (i = 0; i < inlen; ++i) {
-        if ((i % (TC_AES_BLOCK_SIZE)) == 0) {
-            block_num++;
-            nonce[14] = (uint8_t)(block_num >> 8);
-            nonce[15] = (uint8_t)(block_num);
-            if (!tc_aes_encrypt(buffer, nonce, sched)) {
-                return TC_CRYPTO_FAIL;
-            }
-        }
-        /* update the output */
-        *out++ = buffer[i % (TC_AES_BLOCK_SIZE)] ^ *in++;
-    }
-
-    /* update the counter */
-    ctr[14] = nonce[14];
-    ctr[15] = nonce[15];
+  /* update the counter */
+  ctr[14] = nonce[14];
+  ctr[15] = nonce[15];
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_ccm_generation_encryption(uint8_t *out, unsigned int olen,
-                                 const uint8_t *associated_data,
-                                 unsigned int alen, const uint8_t *payload,
-                                 unsigned int plen, TCCcmMode_t c)
-{
-    /* input sanity check: */
-    if ((out == (uint8_t *)0) ||
-        (c == (TCCcmMode_t)0) ||
-        ((plen > 0) && (payload == (uint8_t *)0)) ||
-        ((alen > 0) && (associated_data == (uint8_t *)0)) ||
-        (alen >= TC_CCM_AAD_MAX_BYTES) ||     /* associated data size unsupported */
-        (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */
-        (olen < (plen + c->mlen))) {          /* invalid output buffer size */
-        return TC_CRYPTO_FAIL;
-    }
-
-    uint8_t b[Nb * Nk];
-    uint8_t tag[Nb * Nk];
-    unsigned int i;
-
-    /* GENERATING THE AUTHENTICATION TAG: */
-
-    /* formatting the sequence b for authentication: */
-    b[0] = ((alen > 0) ? 0x40 : 0) | (((c->mlen - 2) / 2 << 3)) | (1);
-    for (i = 1; i <= 13; ++i) {
-        b[i] = c->nonce[i - 1];
-    }
-    b[14] = (uint8_t)(plen >> 8);
-    b[15] = (uint8_t)(plen);
-
-    /* computing the authentication tag using cbc-mac: */
-    (void)tc_aes_encrypt(tag, b, c->sched);
-    if (alen > 0) {
-        ccm_cbc_mac(tag, associated_data, alen, 1, c->sched);
-    }
-    if (plen > 0) {
-        ccm_cbc_mac(tag, payload, plen, 0, c->sched);
-    }
-
-    /* ENCRYPTION: */
-
-    /* formatting the sequence b for encryption: */
-    b[0] = 1; /* q - 1 = 2 - 1 = 1 */
-    b[14] = b[15] = TC_ZERO_BYTE;
-
-    /* encrypting payload using ctr mode: */
-    ccm_ctr_mode(out, plen, payload, plen, b, c->sched);
-
-    b[14] = b[15] = TC_ZERO_BYTE; /* restoring initial counter for ctr_mode (0):*/
-
-    /* encrypting b and adding the tag to the output: */
-    (void)tc_aes_encrypt(b, b, c->sched);
-    out += plen;
-    for (i = 0; i < c->mlen; ++i) {
-        *out++ = tag[i] ^ b[i];
-    }
-
-    return TC_CRYPTO_SUCCESS;
+int tc_ccm_generation_encryption(uint8_t *out, unsigned int olen, const uint8_t *associated_data, unsigned int alen, const uint8_t *payload, unsigned int plen, TCCcmMode_t c) {
+  /* input sanity check: */
+  if ((out == (uint8_t *)0) || (c == (TCCcmMode_t)0) || ((plen > 0) && (payload == (uint8_t *)0)) || ((alen > 0) && (associated_data == (uint8_t *)0)) || (alen >= TC_CCM_AAD_MAX_BYTES)
+      ||                                    /* associated data size unsupported */
+      (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */
+      (olen < (plen + c->mlen))) {          /* invalid output buffer size */
+    return TC_CRYPTO_FAIL;
+  }
+
+  uint8_t      b[Nb * Nk];
+  uint8_t      tag[Nb * Nk];
+  unsigned int i;
+
+  /* GENERATING THE AUTHENTICATION TAG: */
+
+  /* formatting the sequence b for authentication: */
+  b[0] = ((alen > 0) ? 0x40 : 0) | (((c->mlen - 2) / 2 << 3)) | (1);
+  for (i = 1; i <= 13; ++i) {
+    b[i] = c->nonce[i - 1];
+  }
+  b[14] = (uint8_t)(plen >> 8);
+  b[15] = (uint8_t)(plen);
+
+  /* computing the authentication tag using cbc-mac: */
+  (void)tc_aes_encrypt(tag, b, c->sched);
+  if (alen > 0) {
+    ccm_cbc_mac(tag, associated_data, alen, 1, c->sched);
+  }
+  if (plen > 0) {
+    ccm_cbc_mac(tag, payload, plen, 0, c->sched);
+  }
+
+  /* ENCRYPTION: */
+
+  /* formatting the sequence b for encryption: */
+  b[0]  = 1; /* q - 1 = 2 - 1 = 1 */
+  b[14] = b[15] = TC_ZERO_BYTE;
+
+  /* encrypting payload using ctr mode: */
+  ccm_ctr_mode(out, plen, payload, plen, b, c->sched);
+
+  b[14] = b[15] = TC_ZERO_BYTE; /* restoring initial counter for ctr_mode (0):*/
+
+  /* encrypting b and adding the tag to the output: */
+  (void)tc_aes_encrypt(b, b, c->sched);
+  out += plen;
+  for (i = 0; i < c->mlen; ++i) {
+    *out++ = tag[i] ^ b[i];
+  }
+
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_ccm_decryption_verification(uint8_t *out, unsigned int olen,
-                                   const uint8_t *associated_data,
-                                   unsigned int alen, const uint8_t *payload,
-                                   unsigned int plen, TCCcmMode_t c)
-{
-    /* input sanity check: */
-    if ((out == (uint8_t *)0) ||
-        (c == (TCCcmMode_t)0) ||
-        ((plen > 0) && (payload == (uint8_t *)0)) ||
-        ((alen > 0) && (associated_data == (uint8_t *)0)) ||
-        (alen >= TC_CCM_AAD_MAX_BYTES) ||     /* associated data size unsupported */
-        (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */
-        (olen < plen - c->mlen)) {            /* invalid output buffer size */
-        return TC_CRYPTO_FAIL;
-    }
-
-    uint8_t b[Nb * Nk];
-    uint8_t tag[Nb * Nk];
-    unsigned int i;
-
-    /* DECRYPTION: */
-
-    /* formatting the sequence b for decryption: */
-    b[0] = 1; /* q - 1 = 2 - 1 = 1 */
-    for (i = 1; i < 14; ++i) {
-        b[i] = c->nonce[i - 1];
-    }
-    b[14] = b[15] = TC_ZERO_BYTE; /* initial counter value is 0 */
-
-    /* decrypting payload using ctr mode: */
-    ccm_ctr_mode(out, plen - c->mlen, payload, plen - c->mlen, b, c->sched);
-
-    b[14] = b[15] = TC_ZERO_BYTE; /* restoring initial counter value (0) */
-
-    /* encrypting b and restoring the tag from input: */
-    (void)tc_aes_encrypt(b, b, c->sched);
-    for (i = 0; i < c->mlen; ++i) {
-        tag[i] = *(payload + plen - c->mlen + i) ^ b[i];
-    }
-
-    /* VERIFYING THE AUTHENTICATION TAG: */
-
-    /* formatting the sequence b for authentication: */
-    b[0] = ((alen > 0) ? 0x40 : 0) | (((c->mlen - 2) / 2 << 3)) | (1);
-    for (i = 1; i < 14; ++i) {
-        b[i] = c->nonce[i - 1];
-    }
-    b[14] = (uint8_t)((plen - c->mlen) >> 8);
-    b[15] = (uint8_t)(plen - c->mlen);
-
-    /* computing the authentication tag using cbc-mac: */
-    (void)tc_aes_encrypt(b, b, c->sched);
-    if (alen > 0) {
-        ccm_cbc_mac(b, associated_data, alen, 1, c->sched);
-    }
-    if (plen > 0) {
-        ccm_cbc_mac(b, out, plen - c->mlen, 0, c->sched);
-    }
-
-    /* comparing the received tag and the computed one: */
-    if (_compare(b, tag, c->mlen) == 0) {
-        return TC_CRYPTO_SUCCESS;
-    } else {
-        /* erase the decrypted buffer in case of mac validation failure: */
-        _set(out, 0, plen - c->mlen);
-        return TC_CRYPTO_FAIL;
-    }
+int tc_ccm_decryption_verification(uint8_t *out, unsigned int olen, const uint8_t *associated_data, unsigned int alen, const uint8_t *payload, unsigned int plen, TCCcmMode_t c) {
+  /* input sanity check: */
+  if ((out == (uint8_t *)0) || (c == (TCCcmMode_t)0) || ((plen > 0) && (payload == (uint8_t *)0)) || ((alen > 0) && (associated_data == (uint8_t *)0)) || (alen >= TC_CCM_AAD_MAX_BYTES)
+      ||                                    /* associated data size unsupported */
+      (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */
+      (olen < plen - c->mlen)) {            /* invalid output buffer size */
+    return TC_CRYPTO_FAIL;
+  }
+
+  uint8_t      b[Nb * Nk];
+  uint8_t      tag[Nb * Nk];
+  unsigned int i;
+
+  /* DECRYPTION: */
+
+  /* formatting the sequence b for decryption: */
+  b[0] = 1; /* q - 1 = 2 - 1 = 1 */
+  for (i = 1; i < 14; ++i) {
+    b[i] = c->nonce[i - 1];
+  }
+  b[14] = b[15] = TC_ZERO_BYTE; /* initial counter value is 0 */
+
+  /* decrypting payload using ctr mode: */
+  ccm_ctr_mode(out, plen - c->mlen, payload, plen - c->mlen, b, c->sched);
+
+  b[14] = b[15] = TC_ZERO_BYTE; /* restoring initial counter value (0) */
+
+  /* encrypting b and restoring the tag from input: */
+  (void)tc_aes_encrypt(b, b, c->sched);
+  for (i = 0; i < c->mlen; ++i) {
+    tag[i] = *(payload + plen - c->mlen + i) ^ b[i];
+  }
+
+  /* VERIFYING THE AUTHENTICATION TAG: */
+
+  /* formatting the sequence b for authentication: */
+  b[0] = ((alen > 0) ? 0x40 : 0) | (((c->mlen - 2) / 2 << 3)) | (1);
+  for (i = 1; i < 14; ++i) {
+    b[i] = c->nonce[i - 1];
+  }
+  b[14] = (uint8_t)((plen - c->mlen) >> 8);
+  b[15] = (uint8_t)(plen - c->mlen);
+
+  /* computing the authentication tag using cbc-mac: */
+  (void)tc_aes_encrypt(b, b, c->sched);
+  if (alen > 0) {
+    ccm_cbc_mac(b, associated_data, alen, 1, c->sched);
+  }
+  if (plen > 0) {
+    ccm_cbc_mac(b, out, plen - c->mlen, 0, c->sched);
+  }
+
+  /* comparing the received tag and the computed one: */
+  if (_compare(b, tag, c->mlen) == 0) {
+    return TC_CRYPTO_SUCCESS;
+  } else {
+    /* erase the decrypted buffer in case of mac validation failure: */
+    _set(out, 0, plen - c->mlen);
+    return TC_CRYPTO_FAIL;
+  }
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cmac_mode.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cmac_mode.c
index 97e7dd34cb..fa517db9b8 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cmac_mode.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cmac_mode.c
@@ -30,8 +30,8 @@
  *  POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "aes.h"
 #include "cmac_mode.h"
+#include "aes.h"
 #include "constants.h"
 #include "utils.h"
 
@@ -75,178 +75,167 @@ const unsigned char gf_wrap = 0x87;
  *  effects: doubles the GF(2^n) value pointed to by "in" and places
  *           the result in the GF(2^n) value pointed to by "out."
  */
-void gf_double(uint8_t *out, uint8_t *in)
-{
-    /* start with low order byte */
-    uint8_t *x = in + (TC_AES_BLOCK_SIZE - 1);
-
-    /* if msb == 1, we need to add the gf_wrap value, otherwise add 0 */
-    uint8_t carry = (in[0] >> 7) ? gf_wrap : 0;
-
-    out += (TC_AES_BLOCK_SIZE - 1);
-    for (;;) {
-        *out-- = (*x << 1) ^ carry;
-        if (x == in) {
-            break;
-        }
-        carry = *x-- >> 7;
+void gf_double(uint8_t *out, uint8_t *in) {
+  /* start with low order byte */
+  uint8_t *x = in + (TC_AES_BLOCK_SIZE - 1);
+
+  /* if msb == 1, we need to add the gf_wrap value, otherwise add 0 */
+  uint8_t carry = (in[0] >> 7) ? gf_wrap : 0;
+
+  out += (TC_AES_BLOCK_SIZE - 1);
+  for (;;) {
+    *out-- = (*x << 1) ^ carry;
+    if (x == in) {
+      break;
     }
+    carry = *x-- >> 7;
+  }
 }
 
-int tc_cmac_setup(TCCmacState_t s, const uint8_t *key, TCAesKeySched_t sched)
-{
-    /* input sanity check: */
-    if (s == (TCCmacState_t)0 ||
-        key == (const uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_cmac_setup(TCCmacState_t s, const uint8_t *key, TCAesKeySched_t sched) {
+  /* input sanity check: */
+  if (s == (TCCmacState_t)0 || key == (const uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    /* put s into a known state */
-    _set(s, 0, sizeof(*s));
-    s->sched = sched;
+  /* put s into a known state */
+  _set(s, 0, sizeof(*s));
+  s->sched = sched;
 
-    /* configure the encryption key used by the underlying block cipher */
-    tc_aes128_set_encrypt_key(s->sched, key);
+  /* configure the encryption key used by the underlying block cipher */
+  tc_aes128_set_encrypt_key(s->sched, key);
 
-    /* compute s->K1 and s->K2 from s->iv using s->keyid */
-    _set(s->iv, 0, TC_AES_BLOCK_SIZE);
-    tc_aes_encrypt(s->iv, s->iv, s->sched);
-    gf_double(s->K1, s->iv);
-    gf_double(s->K2, s->K1);
+  /* compute s->K1 and s->K2 from s->iv using s->keyid */
+  _set(s->iv, 0, TC_AES_BLOCK_SIZE);
+  tc_aes_encrypt(s->iv, s->iv, s->sched);
+  gf_double(s->K1, s->iv);
+  gf_double(s->K2, s->K1);
 
-    /* reset s->iv to 0 in case someone wants to compute now */
-    tc_cmac_init(s);
+  /* reset s->iv to 0 in case someone wants to compute now */
+  tc_cmac_init(s);
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_cmac_erase(TCCmacState_t s)
-{
-    if (s == (TCCmacState_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_cmac_erase(TCCmacState_t s) {
+  if (s == (TCCmacState_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    /* destroy the current state */
-    _set(s, 0, sizeof(*s));
+  /* destroy the current state */
+  _set(s, 0, sizeof(*s));
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_cmac_init(TCCmacState_t s)
-{
-    /* input sanity check: */
-    if (s == (TCCmacState_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_cmac_init(TCCmacState_t s) {
+  /* input sanity check: */
+  if (s == (TCCmacState_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    /* CMAC starts with an all zero initialization vector */
-    _set(s->iv, 0, TC_AES_BLOCK_SIZE);
+  /* CMAC starts with an all zero initialization vector */
+  _set(s->iv, 0, TC_AES_BLOCK_SIZE);
 
-    /* and the leftover buffer is empty */
-    _set(s->leftover, 0, TC_AES_BLOCK_SIZE);
-    s->leftover_offset = 0;
+  /* and the leftover buffer is empty */
+  _set(s->leftover, 0, TC_AES_BLOCK_SIZE);
+  s->leftover_offset = 0;
 
-    /* Set countdown to max number of calls allowed before re-keying: */
-    s->countdown = MAX_CALLS;
+  /* Set countdown to max number of calls allowed before re-keying: */
+  s->countdown = MAX_CALLS;
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_cmac_update(TCCmacState_t s, const uint8_t *data, size_t data_length)
-{
-    unsigned int i;
-
-    /* input sanity check: */
-    if (s == (TCCmacState_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
-    if (data_length == 0) {
-        return TC_CRYPTO_SUCCESS;
-    }
-    if (data == (const uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_cmac_update(TCCmacState_t s, const uint8_t *data, size_t data_length) {
+  unsigned int i;
 
-    if (s->countdown == 0) {
-        return TC_CRYPTO_FAIL;
+  /* input sanity check: */
+  if (s == (TCCmacState_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
+  if (data_length == 0) {
+    return TC_CRYPTO_SUCCESS;
+  }
+  if (data == (const uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  }
+
+  if (s->countdown == 0) {
+    return TC_CRYPTO_FAIL;
+  }
+
+  s->countdown--;
+
+  if (s->leftover_offset > 0) {
+    /* last data added to s didn't end on a TC_AES_BLOCK_SIZE byte boundary */
+    size_t remaining_space = TC_AES_BLOCK_SIZE - s->leftover_offset;
+
+    if (data_length < remaining_space) {
+      /* still not enough data to encrypt this time either */
+      _copy(&s->leftover[s->leftover_offset], data_length, data, data_length);
+      s->leftover_offset += data_length;
+      return TC_CRYPTO_SUCCESS;
     }
+    /* leftover block is now full; encrypt it first */
+    _copy(&s->leftover[s->leftover_offset], remaining_space, data, remaining_space);
+    data_length -= remaining_space;
+    data += remaining_space;
+    s->leftover_offset = 0;
 
-    s->countdown--;
-
-    if (s->leftover_offset > 0) {
-        /* last data added to s didn't end on a TC_AES_BLOCK_SIZE byte boundary */
-        size_t remaining_space = TC_AES_BLOCK_SIZE - s->leftover_offset;
-
-        if (data_length < remaining_space) {
-            /* still not enough data to encrypt this time either */
-            _copy(&s->leftover[s->leftover_offset], data_length, data, data_length);
-            s->leftover_offset += data_length;
-            return TC_CRYPTO_SUCCESS;
-        }
-        /* leftover block is now full; encrypt it first */
-        _copy(&s->leftover[s->leftover_offset],
-              remaining_space,
-              data,
-              remaining_space);
-        data_length -= remaining_space;
-        data += remaining_space;
-        s->leftover_offset = 0;
-
-        for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) {
-            s->iv[i] ^= s->leftover[i];
-        }
-        tc_aes_encrypt(s->iv, s->iv, s->sched);
+    for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) {
+      s->iv[i] ^= s->leftover[i];
     }
+    tc_aes_encrypt(s->iv, s->iv, s->sched);
+  }
 
-    /* CBC encrypt each (except the last) of the data blocks */
-    while (data_length > TC_AES_BLOCK_SIZE) {
-        for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) {
-            s->iv[i] ^= data[i];
-        }
-        tc_aes_encrypt(s->iv, s->iv, s->sched);
-        data += TC_AES_BLOCK_SIZE;
-        data_length -= TC_AES_BLOCK_SIZE;
+  /* CBC encrypt each (except the last) of the data blocks */
+  while (data_length > TC_AES_BLOCK_SIZE) {
+    for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) {
+      s->iv[i] ^= data[i];
     }
+    tc_aes_encrypt(s->iv, s->iv, s->sched);
+    data += TC_AES_BLOCK_SIZE;
+    data_length -= TC_AES_BLOCK_SIZE;
+  }
 
-    if (data_length > 0) {
-        /* save leftover data for next time */
-        _copy(s->leftover, data_length, data, data_length);
-        s->leftover_offset = data_length;
-    }
+  if (data_length > 0) {
+    /* save leftover data for next time */
+    _copy(s->leftover, data_length, data, data_length);
+    s->leftover_offset = data_length;
+  }
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_cmac_final(uint8_t *tag, TCCmacState_t s)
-{
-    uint8_t *k;
-    unsigned int i;
+int tc_cmac_final(uint8_t *tag, TCCmacState_t s) {
+  uint8_t     *k;
+  unsigned int i;
 
-    /* input sanity check: */
-    if (tag == (uint8_t *)0 ||
-        s == (TCCmacState_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+  /* input sanity check: */
+  if (tag == (uint8_t *)0 || s == (TCCmacState_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    if (s->leftover_offset == TC_AES_BLOCK_SIZE) {
-        /* the last message block is a full-sized block */
-        k = (uint8_t *)s->K1;
-    } else {
-        /* the final message block is not a full-sized  block */
-        size_t remaining = TC_AES_BLOCK_SIZE - s->leftover_offset;
+  if (s->leftover_offset == TC_AES_BLOCK_SIZE) {
+    /* the last message block is a full-sized block */
+    k = (uint8_t *)s->K1;
+  } else {
+    /* the final message block is not a full-sized  block */
+    size_t remaining = TC_AES_BLOCK_SIZE - s->leftover_offset;
 
-        _set(&s->leftover[s->leftover_offset], 0, remaining);
-        s->leftover[s->leftover_offset] = TC_CMAC_PADDING;
-        k = (uint8_t *)s->K2;
-    }
-    for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) {
-        s->iv[i] ^= s->leftover[i] ^ k[i];
-    }
+    _set(&s->leftover[s->leftover_offset], 0, remaining);
+    s->leftover[s->leftover_offset] = TC_CMAC_PADDING;
+    k                               = (uint8_t *)s->K2;
+  }
+  for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) {
+    s->iv[i] ^= s->leftover[i] ^ k[i];
+  }
 
-    tc_aes_encrypt(tag, s->iv, s->sched);
+  tc_aes_encrypt(tag, s->iv, s->sched);
 
-    /* erasing state: */
-    tc_cmac_erase(s);
+  /* erasing state: */
+  tc_cmac_erase(s);
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_mode.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_mode.c
index c9808338b2..eaa14bc5e1 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_mode.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_mode.c
@@ -30,57 +30,48 @@
  *  POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "constants.h"
 #include "ctr_mode.h"
+#include "constants.h"
 #include "utils.h"
 
-int tc_ctr_mode(uint8_t *out, unsigned int outlen, const uint8_t *in,
-                unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched)
-{
-    uint8_t buffer[TC_AES_BLOCK_SIZE];
-    uint8_t nonce[TC_AES_BLOCK_SIZE];
-    unsigned int block_num;
-    unsigned int i;
+int tc_ctr_mode(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched) {
+  uint8_t      buffer[TC_AES_BLOCK_SIZE];
+  uint8_t      nonce[TC_AES_BLOCK_SIZE];
+  unsigned int block_num;
+  unsigned int i;
 
-    /* input sanity check: */
-    if (out == (uint8_t *)0 ||
-        in == (uint8_t *)0 ||
-        ctr == (uint8_t *)0 ||
-        sched == (TCAesKeySched_t)0 ||
-        inlen == 0 ||
-        outlen == 0 ||
-        outlen != inlen) {
-        return TC_CRYPTO_FAIL;
-    }
+  /* input sanity check: */
+  if (out == (uint8_t *)0 || in == (uint8_t *)0 || ctr == (uint8_t *)0 || sched == (TCAesKeySched_t)0 || inlen == 0 || outlen == 0 || outlen != inlen) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    /* copy the ctr to the nonce */
-    (void)_copy(nonce, sizeof(nonce), ctr, sizeof(nonce));
+  /* copy the ctr to the nonce */
+  (void)_copy(nonce, sizeof(nonce), ctr, sizeof(nonce));
 
-    /* select the last 4 bytes of the nonce to be incremented */
-    block_num = (nonce[12] << 24) | (nonce[13] << 16) |
-                (nonce[14] << 8) | (nonce[15]);
-    for (i = 0; i < inlen; ++i) {
-        if ((i % (TC_AES_BLOCK_SIZE)) == 0) {
-            /* encrypt data using the current nonce */
-            if (tc_aes_encrypt(buffer, nonce, sched)) {
-                block_num++;
-                nonce[12] = (uint8_t)(block_num >> 24);
-                nonce[13] = (uint8_t)(block_num >> 16);
-                nonce[14] = (uint8_t)(block_num >> 8);
-                nonce[15] = (uint8_t)(block_num);
-            } else {
-                return TC_CRYPTO_FAIL;
-            }
-        }
-        /* update the output */
-        *out++ = buffer[i % (TC_AES_BLOCK_SIZE)] ^ *in++;
+  /* select the last 4 bytes of the nonce to be incremented */
+  block_num = (nonce[12] << 24) | (nonce[13] << 16) | (nonce[14] << 8) | (nonce[15]);
+  for (i = 0; i < inlen; ++i) {
+    if ((i % (TC_AES_BLOCK_SIZE)) == 0) {
+      /* encrypt data using the current nonce */
+      if (tc_aes_encrypt(buffer, nonce, sched)) {
+        block_num++;
+        nonce[12] = (uint8_t)(block_num >> 24);
+        nonce[13] = (uint8_t)(block_num >> 16);
+        nonce[14] = (uint8_t)(block_num >> 8);
+        nonce[15] = (uint8_t)(block_num);
+      } else {
+        return TC_CRYPTO_FAIL;
+      }
     }
+    /* update the output */
+    *out++ = buffer[i % (TC_AES_BLOCK_SIZE)] ^ *in++;
+  }
 
-    /* update the counter */
-    ctr[12] = nonce[12];
-    ctr[13] = nonce[13];
-    ctr[14] = nonce[14];
-    ctr[15] = nonce[15];
+  /* update the counter */
+  ctr[12] = nonce[12];
+  ctr[13] = nonce[13];
+  ctr[14] = nonce[14];
+  ctr[15] = nonce[15];
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_prng.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_prng.c
index d3410bc57c..e53f550bf7 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_prng.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_prng.c
@@ -28,8 +28,8 @@
  */
 
 #include "ctr_prng.h"
-#include "utils.h"
 #include "constants.h"
+#include "utils.h"
 #include 
 
 /*
@@ -50,16 +50,15 @@
  *  @param arr IN/OUT -- array to be incremented
  *  @param len IN -- size of arr in bytes
  */
-static void arrInc(uint8_t arr[], unsigned int len)
-{
-    unsigned int i;
-    if (0 != arr) {
-        for (i = len; i > 0U; i--) {
-            if (++arr[i - 1] != 0U) {
-                break;
-            }
-        }
+static void arrInc(uint8_t arr[], unsigned int len) {
+  unsigned int i;
+  if (0 != arr) {
+    for (i = len; i > 0U; i--) {
+      if (++arr[i - 1] != 0U) {
+        break;
+      }
     }
+  }
 }
 
 /**
@@ -71,209 +70,192 @@ static void arrInc(uint8_t arr[], unsigned int len)
  *  @param ctx IN/OUT -- CTR PRNG state
  *  @param providedData IN -- data used when updating the internal state
  */
-static void tc_ctr_prng_update(TCCtrPrng_t *const ctx, uint8_t const *const providedData)
-{
-    if (0 != ctx) {
-        /* 10.2.1.2 step 1 */
-        uint8_t temp[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE];
-        unsigned int len = 0U;
-
-        /* 10.2.1.2 step 2 */
-        while (len < sizeof temp) {
-            unsigned int blocklen = sizeof(temp) - len;
-            uint8_t output_block[TC_AES_BLOCK_SIZE];
-
-            /* 10.2.1.2 step 2.1 */
-            arrInc(ctx->V, sizeof ctx->V);
-
-            /* 10.2.1.2 step 2.2 */
-            if (blocklen > TC_AES_BLOCK_SIZE) {
-                blocklen = TC_AES_BLOCK_SIZE;
-            }
-            (void)tc_aes_encrypt(output_block, ctx->V, &ctx->key);
-
-            /* 10.2.1.2 step 2.3/step 3 */
-            memcpy(&(temp[len]), output_block, blocklen);
-
-            len += blocklen;
-        }
+static void tc_ctr_prng_update(TCCtrPrng_t *const ctx, uint8_t const *const providedData) {
+  if (0 != ctx) {
+    /* 10.2.1.2 step 1 */
+    uint8_t      temp[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE];
+    unsigned int len = 0U;
+
+    /* 10.2.1.2 step 2 */
+    while (len < sizeof temp) {
+      unsigned int blocklen = sizeof(temp) - len;
+      uint8_t      output_block[TC_AES_BLOCK_SIZE];
+
+      /* 10.2.1.2 step 2.1 */
+      arrInc(ctx->V, sizeof ctx->V);
+
+      /* 10.2.1.2 step 2.2 */
+      if (blocklen > TC_AES_BLOCK_SIZE) {
+        blocklen = TC_AES_BLOCK_SIZE;
+      }
+      (void)tc_aes_encrypt(output_block, ctx->V, &ctx->key);
+
+      /* 10.2.1.2 step 2.3/step 3 */
+      memcpy(&(temp[len]), output_block, blocklen);
+
+      len += blocklen;
+    }
 
-        /* 10.2.1.2 step 4 */
-        if (0 != providedData) {
-            unsigned int i;
-            for (i = 0U; i < sizeof temp; i++) {
-                temp[i] ^= providedData[i];
-            }
-        }
+    /* 10.2.1.2 step 4 */
+    if (0 != providedData) {
+      unsigned int i;
+      for (i = 0U; i < sizeof temp; i++) {
+        temp[i] ^= providedData[i];
+      }
+    }
 
-        /* 10.2.1.2 step 5 */
-        (void)tc_aes128_set_encrypt_key(&ctx->key, temp);
+    /* 10.2.1.2 step 5 */
+    (void)tc_aes128_set_encrypt_key(&ctx->key, temp);
 
-        /* 10.2.1.2 step 6 */
-        memcpy(ctx->V, &(temp[TC_AES_KEY_SIZE]), TC_AES_BLOCK_SIZE);
-    }
+    /* 10.2.1.2 step 6 */
+    memcpy(ctx->V, &(temp[TC_AES_KEY_SIZE]), TC_AES_BLOCK_SIZE);
+  }
 }
 
-int tc_ctr_prng_init(TCCtrPrng_t *const ctx,
-                     uint8_t const *const entropy,
-                     unsigned int entropyLen,
-                     uint8_t const *const personalization,
-                     unsigned int pLen)
-{
-    int result = TC_CRYPTO_FAIL;
-    unsigned int i;
-    uint8_t personalization_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = { 0U };
-    uint8_t seed_material[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE];
-    uint8_t zeroArr[TC_AES_BLOCK_SIZE] = { 0U };
-
-    if (0 != personalization) {
-        /* 10.2.1.3.1 step 1 */
-        unsigned int len = pLen;
-        if (len > sizeof personalization_buf) {
-            len = sizeof personalization_buf;
-        }
+int tc_ctr_prng_init(TCCtrPrng_t *const ctx, uint8_t const *const entropy, unsigned int entropyLen, uint8_t const *const personalization, unsigned int pLen) {
+  int          result = TC_CRYPTO_FAIL;
+  unsigned int i;
+  uint8_t      personalization_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = {0U};
+  uint8_t      seed_material[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE];
+  uint8_t      zeroArr[TC_AES_BLOCK_SIZE] = {0U};
+
+  if (0 != personalization) {
+    /* 10.2.1.3.1 step 1 */
+    unsigned int len = pLen;
+    if (len > sizeof personalization_buf) {
+      len = sizeof personalization_buf;
+    }
 
-        /* 10.2.1.3.1 step 2 */
-        memcpy(personalization_buf, personalization, len);
+    /* 10.2.1.3.1 step 2 */
+    memcpy(personalization_buf, personalization, len);
+  }
+
+  if ((0 != ctx) && (0 != entropy) && (entropyLen >= sizeof seed_material)) {
+    /* 10.2.1.3.1 step 3 */
+    memcpy(seed_material, entropy, sizeof seed_material);
+    for (i = 0U; i < sizeof seed_material; i++) {
+      seed_material[i] ^= personalization_buf[i];
     }
 
-    if ((0 != ctx) && (0 != entropy) && (entropyLen >= sizeof seed_material)) {
-        /* 10.2.1.3.1 step 3 */
-        memcpy(seed_material, entropy, sizeof seed_material);
-        for (i = 0U; i < sizeof seed_material; i++) {
-            seed_material[i] ^= personalization_buf[i];
-        }
+    /* 10.2.1.3.1 step 4 */
+    (void)tc_aes128_set_encrypt_key(&ctx->key, zeroArr);
 
-        /* 10.2.1.3.1 step 4 */
-        (void)tc_aes128_set_encrypt_key(&ctx->key, zeroArr);
+    /* 10.2.1.3.1 step 5 */
+    memset(ctx->V, 0x00, sizeof ctx->V);
 
-        /* 10.2.1.3.1 step 5 */
-        memset(ctx->V, 0x00, sizeof ctx->V);
+    /* 10.2.1.3.1 step 6 */
+    tc_ctr_prng_update(ctx, seed_material);
 
-        /* 10.2.1.3.1 step 6 */
-        tc_ctr_prng_update(ctx, seed_material);
+    /* 10.2.1.3.1 step 7 */
+    ctx->reseedCount = 1U;
+
+    result = TC_CRYPTO_SUCCESS;
+  }
+  return result;
+}
+
+int tc_ctr_prng_reseed(TCCtrPrng_t *const ctx, uint8_t const *const entropy, unsigned int entropyLen, uint8_t const *const additional_input, unsigned int additionallen) {
+  unsigned int i;
+  int          result                                                    = TC_CRYPTO_FAIL;
+  uint8_t      additional_input_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = {0U};
+  uint8_t      seed_material[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE];
+
+  if (0 != additional_input) {
+    /* 10.2.1.4.1 step 1 */
+    unsigned int len = additionallen;
+    if (len > sizeof additional_input_buf) {
+      len = sizeof additional_input_buf;
+    }
 
-        /* 10.2.1.3.1 step 7 */
-        ctx->reseedCount = 1U;
+    /* 10.2.1.4.1 step 2 */
+    memcpy(additional_input_buf, additional_input, len);
+  }
 
-        result = TC_CRYPTO_SUCCESS;
+  unsigned int seedlen = (unsigned int)TC_AES_KEY_SIZE + (unsigned int)TC_AES_BLOCK_SIZE;
+  if ((0 != ctx) && (entropyLen >= seedlen)) {
+    /* 10.2.1.4.1 step 3 */
+    memcpy(seed_material, entropy, sizeof seed_material);
+    for (i = 0U; i < sizeof seed_material; i++) {
+      seed_material[i] ^= additional_input_buf[i];
     }
-    return result;
+
+    /* 10.2.1.4.1 step 4 */
+    tc_ctr_prng_update(ctx, seed_material);
+
+    /* 10.2.1.4.1 step 5 */
+    ctx->reseedCount = 1U;
+
+    result = TC_CRYPTO_SUCCESS;
+  }
+  return result;
 }
 
-int tc_ctr_prng_reseed(TCCtrPrng_t *const ctx,
-                       uint8_t const *const entropy,
-                       unsigned int entropyLen,
-                       uint8_t const *const additional_input,
-                       unsigned int additionallen)
-{
-    unsigned int i;
-    int result = TC_CRYPTO_FAIL;
-    uint8_t additional_input_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = { 0U };
-    uint8_t seed_material[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE];
-
-    if (0 != additional_input) {
-        /* 10.2.1.4.1 step 1 */
+int tc_ctr_prng_generate(TCCtrPrng_t *const ctx, uint8_t const *const additional_input, unsigned int additionallen, uint8_t *const out, unsigned int outlen) {
+  /* 2^48 - see section 10.2.1 */
+  static const uint64_t MAX_REQS_BEFORE_RESEED = 0x1000000000000ULL;
+
+  /* 2^19 bits - see section 10.2.1 */
+  static const unsigned int MAX_BYTES_PER_REQ = 65536U;
+
+  unsigned int result = TC_CRYPTO_FAIL;
+
+  if ((0 != ctx) && (0 != out) && (outlen < MAX_BYTES_PER_REQ)) {
+    /* 10.2.1.5.1 step 1 */
+    if (ctx->reseedCount > MAX_REQS_BEFORE_RESEED) {
+      result = TC_CTR_PRNG_RESEED_REQ;
+    } else {
+      uint8_t additional_input_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = {0U};
+      if (0 != additional_input) {
+        /* 10.2.1.5.1 step 2  */
         unsigned int len = additionallen;
         if (len > sizeof additional_input_buf) {
-            len = sizeof additional_input_buf;
+          len = sizeof additional_input_buf;
         }
-
-        /* 10.2.1.4.1 step 2 */
         memcpy(additional_input_buf, additional_input, len);
-    }
+        tc_ctr_prng_update(ctx, additional_input_buf);
+      }
 
-    unsigned int seedlen = (unsigned int)TC_AES_KEY_SIZE + (unsigned int)TC_AES_BLOCK_SIZE;
-    if ((0 != ctx) && (entropyLen >= seedlen)) {
-        /* 10.2.1.4.1 step 3 */
-        memcpy(seed_material, entropy, sizeof seed_material);
-        for (i = 0U; i < sizeof seed_material; i++) {
-            seed_material[i] ^= additional_input_buf[i];
-        }
+      /* 10.2.1.5.1 step 3 - implicit */
 
-        /* 10.2.1.4.1 step 4 */
-        tc_ctr_prng_update(ctx, seed_material);
+      /* 10.2.1.5.1 step 4 */
+      unsigned int len = 0U;
+      while (len < outlen) {
+        unsigned int blocklen = outlen - len;
+        uint8_t      output_block[TC_AES_BLOCK_SIZE];
 
-        /* 10.2.1.4.1 step 5 */
-        ctx->reseedCount = 1U;
+        /* 10.2.1.5.1 step 4.1 */
+        arrInc(ctx->V, sizeof ctx->V);
 
-        result = TC_CRYPTO_SUCCESS;
-    }
-    return result;
-}
+        /* 10.2.1.5.1 step 4.2 */
+        (void)tc_aes_encrypt(output_block, ctx->V, &ctx->key);
 
-int tc_ctr_prng_generate(TCCtrPrng_t *const ctx,
-                         uint8_t const *const additional_input,
-                         unsigned int additionallen,
-                         uint8_t *const out,
-                         unsigned int outlen)
-{
-    /* 2^48 - see section 10.2.1 */
-    static const uint64_t MAX_REQS_BEFORE_RESEED = 0x1000000000000ULL;
-
-    /* 2^19 bits - see section 10.2.1 */
-    static const unsigned int MAX_BYTES_PER_REQ = 65536U;
-
-    unsigned int result = TC_CRYPTO_FAIL;
-
-    if ((0 != ctx) && (0 != out) && (outlen < MAX_BYTES_PER_REQ)) {
-        /* 10.2.1.5.1 step 1 */
-        if (ctx->reseedCount > MAX_REQS_BEFORE_RESEED) {
-            result = TC_CTR_PRNG_RESEED_REQ;
-        } else {
-            uint8_t additional_input_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = { 0U };
-            if (0 != additional_input) {
-                /* 10.2.1.5.1 step 2  */
-                unsigned int len = additionallen;
-                if (len > sizeof additional_input_buf) {
-                    len = sizeof additional_input_buf;
-                }
-                memcpy(additional_input_buf, additional_input, len);
-                tc_ctr_prng_update(ctx, additional_input_buf);
-            }
-
-            /* 10.2.1.5.1 step 3 - implicit */
-
-            /* 10.2.1.5.1 step 4 */
-            unsigned int len = 0U;
-            while (len < outlen) {
-                unsigned int blocklen = outlen - len;
-                uint8_t output_block[TC_AES_BLOCK_SIZE];
-
-                /* 10.2.1.5.1 step 4.1 */
-                arrInc(ctx->V, sizeof ctx->V);
-
-                /* 10.2.1.5.1 step 4.2 */
-                (void)tc_aes_encrypt(output_block, ctx->V, &ctx->key);
-
-                /* 10.2.1.5.1 step 4.3/step 5 */
-                if (blocklen > TC_AES_BLOCK_SIZE) {
-                    blocklen = TC_AES_BLOCK_SIZE;
-                }
-                memcpy(&(out[len]), output_block, blocklen);
-
-                len += blocklen;
-            }
-
-            /* 10.2.1.5.1 step 6 */
-            tc_ctr_prng_update(ctx, additional_input_buf);
-
-            /* 10.2.1.5.1 step 7 */
-            ctx->reseedCount++;
-
-            /* 10.2.1.5.1 step 8 */
-            result = TC_CRYPTO_SUCCESS;
+        /* 10.2.1.5.1 step 4.3/step 5 */
+        if (blocklen > TC_AES_BLOCK_SIZE) {
+          blocklen = TC_AES_BLOCK_SIZE;
         }
+        memcpy(&(out[len]), output_block, blocklen);
+
+        len += blocklen;
+      }
+
+      /* 10.2.1.5.1 step 6 */
+      tc_ctr_prng_update(ctx, additional_input_buf);
+
+      /* 10.2.1.5.1 step 7 */
+      ctx->reseedCount++;
+
+      /* 10.2.1.5.1 step 8 */
+      result = TC_CRYPTO_SUCCESS;
     }
+  }
 
-    return result;
+  return result;
 }
 
-void tc_ctr_prng_uninstantiate(TCCtrPrng_t *const ctx)
-{
-    if (0 != ctx) {
-        memset(ctx->key.words, 0x00, sizeof ctx->key.words);
-        memset(ctx->V, 0x00, sizeof ctx->V);
-        ctx->reseedCount = 0U;
-    }
+void tc_ctr_prng_uninstantiate(TCCtrPrng_t *const ctx) {
+  if (0 != ctx) {
+    memset(ctx->key.words, 0x00, sizeof ctx->key.words);
+    memset(ctx->V, 0x00, sizeof ctx->V);
+    ctx->reseedCount = 0U;
+  }
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c
index 711d223a0b..a1befa180e 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c
@@ -54,8 +54,8 @@
 
 #include "../include/tinycrypt/ecc.h"
 #include "../include/tinycrypt/ecc_platform_specific.h"
-#include 
 #include 
+#include 
 /* IMPORTANT: Make sure a cryptographically-secure PRNG is set and the platform
  * has access to enough entropy in order to feed the PRNG regularly. */
 #if default_RNG_defined
@@ -64,860 +64,733 @@ static uECC_RNG_Function g_rng_function = &default_CSPRNG;
 static uECC_RNG_Function g_rng_function = 0;
 #endif
 
-void uECC_set_rng(uECC_RNG_Function rng_function)
-{
-    g_rng_function = rng_function;
-}
+void uECC_set_rng(uECC_RNG_Function rng_function) { g_rng_function = rng_function; }
 
-uECC_RNG_Function uECC_get_rng(void)
-{
-    return g_rng_function;
-}
+uECC_RNG_Function uECC_get_rng(void) { return g_rng_function; }
 
-int uECC_curve_private_key_size(uECC_Curve curve)
-{
-    return BITS_TO_BYTES(curve->num_n_bits);
-}
+int uECC_curve_private_key_size(uECC_Curve curve) { return BITS_TO_BYTES(curve->num_n_bits); }
 
-int uECC_curve_public_key_size(uECC_Curve curve)
-{
-    return 2 * curve->num_bytes;
-}
+int uECC_curve_public_key_size(uECC_Curve curve) { return 2 * curve->num_bytes; }
 
-void uECC_vli_clear(uECC_word_t *vli, wordcount_t num_words)
-{
-    wordcount_t i;
-    for (i = 0; i < num_words; ++i) {
-        vli[i] = 0;
-    }
+void uECC_vli_clear(uECC_word_t *vli, wordcount_t num_words) {
+  wordcount_t i;
+  for (i = 0; i < num_words; ++i) {
+    vli[i] = 0;
+  }
 }
 
-uECC_word_t uECC_vli_isZero(const uECC_word_t *vli, wordcount_t num_words)
-{
-    uECC_word_t bits = 0;
-    wordcount_t i;
-    for (i = 0; i < num_words; ++i) {
-        bits |= vli[i];
-    }
-    return (bits == 0);
+uECC_word_t uECC_vli_isZero(const uECC_word_t *vli, wordcount_t num_words) {
+  uECC_word_t bits = 0;
+  wordcount_t i;
+  for (i = 0; i < num_words; ++i) {
+    bits |= vli[i];
+  }
+  return (bits == 0);
 }
 
-uECC_word_t uECC_vli_testBit(const uECC_word_t *vli, bitcount_t bit)
-{
-    return (vli[bit >> uECC_WORD_BITS_SHIFT] &
-            ((uECC_word_t)1 << (bit & uECC_WORD_BITS_MASK)));
-}
+uECC_word_t uECC_vli_testBit(const uECC_word_t *vli, bitcount_t bit) { return (vli[bit >> uECC_WORD_BITS_SHIFT] & ((uECC_word_t)1 << (bit & uECC_WORD_BITS_MASK))); }
 
 /* Counts the number of words in vli. */
-static wordcount_t vli_numDigits(const uECC_word_t *vli,
-                                 const wordcount_t max_words)
-{
-    wordcount_t i;
-    /* Search from the end until we find a non-zero digit. We do it in reverse
-	 * because we expect that most digits will be nonzero. */
-    for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) {
-    }
+static wordcount_t vli_numDigits(const uECC_word_t *vli, const wordcount_t max_words) {
+  wordcount_t i;
+  /* Search from the end until we find a non-zero digit. We do it in reverse
+   * because we expect that most digits will be nonzero. */
+  for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) {}
 
-    return (i + 1);
+  return (i + 1);
 }
 
-bitcount_t uECC_vli_numBits(const uECC_word_t *vli,
-                            const wordcount_t max_words)
-{
-    uECC_word_t i;
-    uECC_word_t digit;
+bitcount_t uECC_vli_numBits(const uECC_word_t *vli, const wordcount_t max_words) {
+  uECC_word_t i;
+  uECC_word_t digit;
 
-    wordcount_t num_digits = vli_numDigits(vli, max_words);
-    if (num_digits == 0) {
-        return 0;
-    }
+  wordcount_t num_digits = vli_numDigits(vli, max_words);
+  if (num_digits == 0) {
+    return 0;
+  }
 
-    digit = vli[num_digits - 1];
-    for (i = 0; digit; ++i) {
-        digit >>= 1;
-    }
+  digit = vli[num_digits - 1];
+  for (i = 0; digit; ++i) {
+    digit >>= 1;
+  }
 
-    return (((bitcount_t)(num_digits - 1) << uECC_WORD_BITS_SHIFT) + i);
+  return (((bitcount_t)(num_digits - 1) << uECC_WORD_BITS_SHIFT) + i);
 }
 
-void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src,
-                  wordcount_t num_words)
-{
-    wordcount_t i;
+void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src, wordcount_t num_words) {
+  wordcount_t i;
 
-    for (i = 0; i < num_words; ++i) {
-        dest[i] = src[i];
-    }
+  for (i = 0; i < num_words; ++i) {
+    dest[i] = src[i];
+  }
 }
 
-cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left,
-                                const uECC_word_t *right,
-                                wordcount_t num_words)
-{
-    wordcount_t i;
+cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) {
+  wordcount_t i;
 
-    for (i = num_words - 1; i >= 0; --i) {
-        if (left[i] > right[i]) {
-            return 1;
-        } else if (left[i] < right[i]) {
-            return -1;
-        }
+  for (i = num_words - 1; i >= 0; --i) {
+    if (left[i] > right[i]) {
+      return 1;
+    } else if (left[i] < right[i]) {
+      return -1;
     }
-    return 0;
+  }
+  return 0;
 }
 
-uECC_word_t uECC_vli_equal(const uECC_word_t *left, const uECC_word_t *right,
-                           wordcount_t num_words)
-{
-    uECC_word_t diff = 0;
-    wordcount_t i;
+uECC_word_t uECC_vli_equal(const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) {
+  uECC_word_t diff = 0;
+  wordcount_t i;
 
-    for (i = num_words - 1; i >= 0; --i) {
-        diff |= (left[i] ^ right[i]);
-    }
-    return !(diff == 0);
+  for (i = num_words - 1; i >= 0; --i) {
+    diff |= (left[i] ^ right[i]);
+  }
+  return !(diff == 0);
 }
 
-uECC_word_t cond_set(uECC_word_t p_true, uECC_word_t p_false, unsigned int cond)
-{
-    return (p_true * (cond)) | (p_false * (!cond));
-}
+uECC_word_t cond_set(uECC_word_t p_true, uECC_word_t p_false, unsigned int cond) { return (p_true * (cond)) | (p_false * (!cond)); }
 
 /* Computes result = left - right, returning borrow, in constant time.
  * Can modify in place. */
-uECC_word_t uECC_vli_sub(uECC_word_t *result, const uECC_word_t *left,
-                         const uECC_word_t *right, wordcount_t num_words)
-{
-    uECC_word_t borrow = 0;
-    wordcount_t i;
-    for (i = 0; i < num_words; ++i) {
-        uECC_word_t diff = left[i] - right[i] - borrow;
-        uECC_word_t val = (diff > left[i]);
-        borrow = cond_set(val, borrow, (diff != left[i]));
+uECC_word_t uECC_vli_sub(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) {
+  uECC_word_t borrow = 0;
+  wordcount_t i;
+  for (i = 0; i < num_words; ++i) {
+    uECC_word_t diff = left[i] - right[i] - borrow;
+    uECC_word_t val  = (diff > left[i]);
+    borrow           = cond_set(val, borrow, (diff != left[i]));
 
-        result[i] = diff;
-    }
-    return borrow;
+    result[i] = diff;
+  }
+  return borrow;
 }
 
 /* Computes result = left + right, returning carry, in constant time.
  * Can modify in place. */
-static uECC_word_t uECC_vli_add(uECC_word_t *result, const uECC_word_t *left,
-                                const uECC_word_t *right, wordcount_t num_words)
-{
-    uECC_word_t carry = 0;
-    wordcount_t i;
-    for (i = 0; i < num_words; ++i) {
-        uECC_word_t sum = left[i] + right[i] + carry;
-        uECC_word_t val = (sum < left[i]);
-        carry = cond_set(val, carry, (sum != left[i]));
-        result[i] = sum;
-    }
-    return carry;
+static uECC_word_t uECC_vli_add(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) {
+  uECC_word_t carry = 0;
+  wordcount_t i;
+  for (i = 0; i < num_words; ++i) {
+    uECC_word_t sum = left[i] + right[i] + carry;
+    uECC_word_t val = (sum < left[i]);
+    carry           = cond_set(val, carry, (sum != left[i]));
+    result[i]       = sum;
+  }
+  return carry;
 }
 
-cmpresult_t uECC_vli_cmp(const uECC_word_t *left, const uECC_word_t *right,
-                         wordcount_t num_words)
-{
-    uECC_word_t tmp[NUM_ECC_WORDS];
-    uECC_word_t neg = !!uECC_vli_sub(tmp, left, right, num_words);
-    uECC_word_t equal = uECC_vli_isZero(tmp, num_words);
-    return (!equal - 2 * neg);
+cmpresult_t uECC_vli_cmp(const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) {
+  uECC_word_t tmp[NUM_ECC_WORDS];
+  uECC_word_t neg   = !!uECC_vli_sub(tmp, left, right, num_words);
+  uECC_word_t equal = uECC_vli_isZero(tmp, num_words);
+  return (!equal - 2 * neg);
 }
 
 /* Computes vli = vli >> 1. */
-static void uECC_vli_rshift1(uECC_word_t *vli, wordcount_t num_words)
-{
-    uECC_word_t *end = vli;
-    uECC_word_t carry = 0;
-
-    vli += num_words;
-    while (vli-- > end) {
-        uECC_word_t temp = *vli;
-        *vli = (temp >> 1) | carry;
-        carry = temp << (uECC_WORD_BITS - 1);
-    }
-}
+static void uECC_vli_rshift1(uECC_word_t *vli, wordcount_t num_words) {
+  uECC_word_t *end   = vli;
+  uECC_word_t  carry = 0;
 
-static void muladd(uECC_word_t a, uECC_word_t b, uECC_word_t *r0,
-                   uECC_word_t *r1, uECC_word_t *r2)
-{
-    uECC_dword_t p = (uECC_dword_t)a * b;
-    uECC_dword_t r01 = ((uECC_dword_t)(*r1) << uECC_WORD_BITS) | *r0;
-    r01 += p;
-    *r2 += (r01 < p);
-    *r1 = r01 >> uECC_WORD_BITS;
-    *r0 = (uECC_word_t)r01;
+  vli += num_words;
+  while (vli-- > end) {
+    uECC_word_t temp = *vli;
+    *vli             = (temp >> 1) | carry;
+    carry            = temp << (uECC_WORD_BITS - 1);
+  }
 }
 
-/* Computes result = left * right. Result must be 2 * num_words long. */
-static void uECC_vli_mult(uECC_word_t *result, const uECC_word_t *left,
-                          const uECC_word_t *right, wordcount_t num_words)
-{
-    uECC_word_t r0 = 0;
-    uECC_word_t r1 = 0;
-    uECC_word_t r2 = 0;
-    wordcount_t i, k;
-
-    /* Compute each digit of result in sequence, maintaining the carries. */
-    for (k = 0; k < num_words; ++k) {
-        for (i = 0; i <= k; ++i) {
-            muladd(left[i], right[k - i], &r0, &r1, &r2);
-        }
-
-        result[k] = r0;
-        r0 = r1;
-        r1 = r2;
-        r2 = 0;
-    }
-
-    for (k = num_words; k < num_words * 2 - 1; ++k) {
-        for (i = (k + 1) - num_words; i < num_words; ++i) {
-            muladd(left[i], right[k - i], &r0, &r1, &r2);
-        }
-        result[k] = r0;
-        r0 = r1;
-        r1 = r2;
-        r2 = 0;
-    }
-    result[num_words * 2 - 1] = r0;
-}
-
-void uECC_vli_modAdd(uECC_word_t *result, const uECC_word_t *left,
-                     const uECC_word_t *right, const uECC_word_t *mod,
-                     wordcount_t num_words)
-{
-    uECC_word_t carry = uECC_vli_add(result, left, right, num_words);
-    if (carry || uECC_vli_cmp_unsafe(mod, result, num_words) != 1) {
-        /* result > mod (result = mod + remainder), so subtract mod to get
-	 * remainder. */
-        uECC_vli_sub(result, result, mod, num_words);
-    }
+static void muladd(uECC_word_t a, uECC_word_t b, uECC_word_t *r0, uECC_word_t *r1, uECC_word_t *r2) {
+  uECC_dword_t p   = (uECC_dword_t)a * b;
+  uECC_dword_t r01 = ((uECC_dword_t)(*r1) << uECC_WORD_BITS) | *r0;
+  r01 += p;
+  *r2 += (r01 < p);
+  *r1 = r01 >> uECC_WORD_BITS;
+  *r0 = (uECC_word_t)r01;
 }
 
-void uECC_vli_modSub(uECC_word_t *result, const uECC_word_t *left,
-                     const uECC_word_t *right, const uECC_word_t *mod,
-                     wordcount_t num_words)
-{
-    uECC_word_t l_borrow = uECC_vli_sub(result, left, right, num_words);
-    if (l_borrow) {
-        /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x,
-		 * we can get the correct result from result + mod (with overflow). */
-        uECC_vli_add(result, result, mod, num_words);
-    }
+/* Computes result = left * right. Result must be 2 * num_words long. */
+static void uECC_vli_mult(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) {
+  uECC_word_t r0 = 0;
+  uECC_word_t r1 = 0;
+  uECC_word_t r2 = 0;
+  wordcount_t i, k;
+
+  /* Compute each digit of result in sequence, maintaining the carries. */
+  for (k = 0; k < num_words; ++k) {
+    for (i = 0; i <= k; ++i) {
+      muladd(left[i], right[k - i], &r0, &r1, &r2);
+    }
+
+    result[k] = r0;
+    r0        = r1;
+    r1        = r2;
+    r2        = 0;
+  }
+
+  for (k = num_words; k < num_words * 2 - 1; ++k) {
+    for (i = (k + 1) - num_words; i < num_words; ++i) {
+      muladd(left[i], right[k - i], &r0, &r1, &r2);
+    }
+    result[k] = r0;
+    r0        = r1;
+    r1        = r2;
+    r2        = 0;
+  }
+  result[num_words * 2 - 1] = r0;
+}
+
+void uECC_vli_modAdd(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, const uECC_word_t *mod, wordcount_t num_words) {
+  uECC_word_t carry = uECC_vli_add(result, left, right, num_words);
+  if (carry || uECC_vli_cmp_unsafe(mod, result, num_words) != 1) {
+    /* result > mod (result = mod + remainder), so subtract mod to get
+     * remainder. */
+    uECC_vli_sub(result, result, mod, num_words);
+  }
+}
+
+void uECC_vli_modSub(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, const uECC_word_t *mod, wordcount_t num_words) {
+  uECC_word_t l_borrow = uECC_vli_sub(result, left, right, num_words);
+  if (l_borrow) {
+    /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x,
+     * we can get the correct result from result + mod (with overflow). */
+    uECC_vli_add(result, result, mod, num_words);
+  }
 }
 
 /* Computes result = product % mod, where product is 2N words long. */
 /* Currently only designed to work for curve_p or curve_n. */
-void uECC_vli_mmod(uECC_word_t *result, uECC_word_t *product,
-                   const uECC_word_t *mod, wordcount_t num_words)
-{
-    uECC_word_t mod_multiple[2 * NUM_ECC_WORDS];
-    uECC_word_t tmp[2 * NUM_ECC_WORDS];
-    uECC_word_t *v[2] = { tmp, product };
-    uECC_word_t index;
-
-    /* Shift mod so its highest set bit is at the maximum position. */
-    bitcount_t shift = (num_words * 2 * uECC_WORD_BITS) -
-                       uECC_vli_numBits(mod, num_words);
-    wordcount_t word_shift = shift / uECC_WORD_BITS;
-    wordcount_t bit_shift = shift % uECC_WORD_BITS;
-    uECC_word_t carry = 0;
-    uECC_vli_clear(mod_multiple, word_shift);
-    if (bit_shift > 0) {
-        for (index = 0; index < (uECC_word_t)num_words; ++index) {
-            mod_multiple[word_shift + index] = (mod[index] << bit_shift) | carry;
-            carry = mod[index] >> (uECC_WORD_BITS - bit_shift);
-        }
-    } else {
-        uECC_vli_set(mod_multiple + word_shift, mod, num_words);
-    }
-
-    for (index = 1; shift >= 0; --shift) {
-        uECC_word_t borrow = 0;
-        wordcount_t i;
-        for (i = 0; i < num_words * 2; ++i) {
-            uECC_word_t diff = v[index][i] - mod_multiple[i] - borrow;
-            if (diff != v[index][i]) {
-                borrow = (diff > v[index][i]);
-            }
-            v[1 - index][i] = diff;
-        }
-        /* Swap the index if there was no borrow */
-        index = !(index ^ borrow);
-        uECC_vli_rshift1(mod_multiple, num_words);
-        mod_multiple[num_words - 1] |= mod_multiple[num_words] << (uECC_WORD_BITS - 1);
-        uECC_vli_rshift1(mod_multiple + num_words, num_words);
+void uECC_vli_mmod(uECC_word_t *result, uECC_word_t *product, const uECC_word_t *mod, wordcount_t num_words) {
+  uECC_word_t  mod_multiple[2 * NUM_ECC_WORDS];
+  uECC_word_t  tmp[2 * NUM_ECC_WORDS];
+  uECC_word_t *v[2] = {tmp, product};
+  uECC_word_t  index;
+
+  /* Shift mod so its highest set bit is at the maximum position. */
+  bitcount_t  shift      = (num_words * 2 * uECC_WORD_BITS) - uECC_vli_numBits(mod, num_words);
+  wordcount_t word_shift = shift / uECC_WORD_BITS;
+  wordcount_t bit_shift  = shift % uECC_WORD_BITS;
+  uECC_word_t carry      = 0;
+  uECC_vli_clear(mod_multiple, word_shift);
+  if (bit_shift > 0) {
+    for (index = 0; index < (uECC_word_t)num_words; ++index) {
+      mod_multiple[word_shift + index] = (mod[index] << bit_shift) | carry;
+      carry                            = mod[index] >> (uECC_WORD_BITS - bit_shift);
+    }
+  } else {
+    uECC_vli_set(mod_multiple + word_shift, mod, num_words);
+  }
+
+  for (index = 1; shift >= 0; --shift) {
+    uECC_word_t borrow = 0;
+    wordcount_t i;
+    for (i = 0; i < num_words * 2; ++i) {
+      uECC_word_t diff = v[index][i] - mod_multiple[i] - borrow;
+      if (diff != v[index][i]) {
+        borrow = (diff > v[index][i]);
+      }
+      v[1 - index][i] = diff;
     }
-    uECC_vli_set(result, v[index], num_words);
+    /* Swap the index if there was no borrow */
+    index = !(index ^ borrow);
+    uECC_vli_rshift1(mod_multiple, num_words);
+    mod_multiple[num_words - 1] |= mod_multiple[num_words] << (uECC_WORD_BITS - 1);
+    uECC_vli_rshift1(mod_multiple + num_words, num_words);
+  }
+  uECC_vli_set(result, v[index], num_words);
 }
 
-void uECC_vli_modMult(uECC_word_t *result, const uECC_word_t *left,
-                      const uECC_word_t *right, const uECC_word_t *mod,
-                      wordcount_t num_words)
-{
-    uECC_word_t product[2 * NUM_ECC_WORDS];
-    uECC_vli_mult(product, left, right, num_words);
-    uECC_vli_mmod(result, product, mod, num_words);
+void uECC_vli_modMult(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, const uECC_word_t *mod, wordcount_t num_words) {
+  uECC_word_t product[2 * NUM_ECC_WORDS];
+  uECC_vli_mult(product, left, right, num_words);
+  uECC_vli_mmod(result, product, mod, num_words);
 }
 
-void uECC_vli_modMult_fast(uECC_word_t *result, const uECC_word_t *left,
-                           const uECC_word_t *right, uECC_Curve curve)
-{
-    uECC_word_t product[2 * NUM_ECC_WORDS];
-    uECC_vli_mult(product, left, right, curve->num_words);
+void uECC_vli_modMult_fast(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, uECC_Curve curve) {
+  uECC_word_t product[2 * NUM_ECC_WORDS];
+  uECC_vli_mult(product, left, right, curve->num_words);
 
-    curve->mmod_fast(result, product);
+  curve->mmod_fast(result, product);
 }
 
-static void uECC_vli_modSquare_fast(uECC_word_t *result,
-                                    const uECC_word_t *left,
-                                    uECC_Curve curve)
-{
-    uECC_vli_modMult_fast(result, left, left, curve);
-}
+static void uECC_vli_modSquare_fast(uECC_word_t *result, const uECC_word_t *left, uECC_Curve curve) { uECC_vli_modMult_fast(result, left, left, curve); }
 
 #define EVEN(vli) (!(vli[0] & 1))
 
-static void vli_modInv_update(uECC_word_t *uv,
-                              const uECC_word_t *mod,
-                              wordcount_t num_words)
-{
-    uECC_word_t carry = 0;
-
-    if (!EVEN(uv)) {
-        carry = uECC_vli_add(uv, uv, mod, num_words);
-    }
-    uECC_vli_rshift1(uv, num_words);
-    if (carry) {
-        uv[num_words - 1] |= HIGH_BIT_SET;
-    }
-}
-
-void uECC_vli_modInv(uECC_word_t *result, const uECC_word_t *input,
-                     const uECC_word_t *mod, wordcount_t num_words)
-{
-    uECC_word_t a[NUM_ECC_WORDS], b[NUM_ECC_WORDS];
-    uECC_word_t u[NUM_ECC_WORDS], v[NUM_ECC_WORDS];
-    cmpresult_t cmpResult;
-
-    if (uECC_vli_isZero(input, num_words)) {
-        uECC_vli_clear(result, num_words);
-        return;
-    }
-
-    uECC_vli_set(a, input, num_words);
-    uECC_vli_set(b, mod, num_words);
-    uECC_vli_clear(u, num_words);
-    u[0] = 1;
-    uECC_vli_clear(v, num_words);
-    while ((cmpResult = uECC_vli_cmp_unsafe(a, b, num_words)) != 0) {
-        if (EVEN(a)) {
-            uECC_vli_rshift1(a, num_words);
-            vli_modInv_update(u, mod, num_words);
-        } else if (EVEN(b)) {
-            uECC_vli_rshift1(b, num_words);
-            vli_modInv_update(v, mod, num_words);
-        } else if (cmpResult > 0) {
-            uECC_vli_sub(a, a, b, num_words);
-            uECC_vli_rshift1(a, num_words);
-            if (uECC_vli_cmp_unsafe(u, v, num_words) < 0) {
-                uECC_vli_add(u, u, mod, num_words);
-            }
-            uECC_vli_sub(u, u, v, num_words);
-            vli_modInv_update(u, mod, num_words);
-        } else {
-            uECC_vli_sub(b, b, a, num_words);
-            uECC_vli_rshift1(b, num_words);
-            if (uECC_vli_cmp_unsafe(v, u, num_words) < 0) {
-                uECC_vli_add(v, v, mod, num_words);
-            }
-            uECC_vli_sub(v, v, u, num_words);
-            vli_modInv_update(v, mod, num_words);
-        }
-    }
-    uECC_vli_set(result, u, num_words);
-}
-
-/* ------ Point operations ------ */
-
-void double_jacobian_default(uECC_word_t *X1, uECC_word_t *Y1,
-                             uECC_word_t *Z1, uECC_Curve curve)
-{
-    /* t1 = X, t2 = Y, t3 = Z */
-    uECC_word_t t4[NUM_ECC_WORDS];
-    uECC_word_t t5[NUM_ECC_WORDS];
-    wordcount_t num_words = curve->num_words;
-
-    if (uECC_vli_isZero(Z1, num_words)) {
-        return;
-    }
-
-    uECC_vli_modSquare_fast(t4, Y1, curve);   /* t4 = y1^2 */
-    uECC_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */
-    uECC_vli_modSquare_fast(t4, t4, curve);   /* t4 = y1^4 */
-    uECC_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */
-    uECC_vli_modSquare_fast(Z1, Z1, curve);   /* t3 = z1^2 */
-
-    uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */
-    uECC_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */
-    uECC_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */
-    uECC_vli_modMult_fast(X1, X1, Z1, curve);         /* t1 = x1^2 - z1^4 */
-
-    uECC_vli_modAdd(Z1, X1, X1, curve->p, num_words); /* t3 = 2*(x1^2 - z1^4) */
-    uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = 3*(x1^2 - z1^4) */
-    if (uECC_vli_testBit(X1, 0)) {
-        uECC_word_t l_carry = uECC_vli_add(X1, X1, curve->p, num_words);
-        uECC_vli_rshift1(X1, num_words);
-        X1[num_words - 1] |= l_carry << (uECC_WORD_BITS - 1);
-    } else {
-        uECC_vli_rshift1(X1, num_words);
-    }
-
-    /* t1 = 3/2*(x1^2 - z1^4) = B */
-    uECC_vli_modSquare_fast(Z1, X1, curve);           /* t3 = B^2 */
-    uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */
-    uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */
-    uECC_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */
-    uECC_vli_modMult_fast(X1, X1, t5, curve);         /* t1 = B * (A - x3) */
-    /* t4 = B * (A - x3) - y1^4 = y3: */
-    uECC_vli_modSub(t4, X1, t4, curve->p, num_words);
-
-    uECC_vli_set(X1, Z1, num_words);
-    uECC_vli_set(Z1, Y1, num_words);
-    uECC_vli_set(Y1, t4, num_words);
-}
-
-void x_side_default(uECC_word_t *result,
-                    const uECC_word_t *x,
-                    uECC_Curve curve)
-{
-    uECC_word_t _3[NUM_ECC_WORDS] = { 3 }; /* -a = 3 */
-    wordcount_t num_words = curve->num_words;
-
-    uECC_vli_modSquare_fast(result, x, curve);                /* r = x^2 */
-    uECC_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */
-    uECC_vli_modMult_fast(result, result, x, curve);          /* r = x^3 - 3x */
-    /* r = x^3 - 3x + b: */
-    uECC_vli_modAdd(result, result, curve->b, curve->p, num_words);
-}
-
-uECC_Curve uECC_secp256r1(void)
-{
-    return &curve_secp256r1;
-}
-
-void vli_mmod_fast_secp256r1(unsigned int *result, unsigned int *product)
-{
-    unsigned int tmp[NUM_ECC_WORDS];
-    int carry;
-
-    /* t */
-    uECC_vli_set(result, product, NUM_ECC_WORDS);
-
-    /* s1 */
-    tmp[0] = tmp[1] = tmp[2] = 0;
-    tmp[3] = product[11];
-    tmp[4] = product[12];
-    tmp[5] = product[13];
-    tmp[6] = product[14];
-    tmp[7] = product[15];
-    carry = uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS);
-    carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
-
-    /* s2 */
-    tmp[3] = product[12];
-    tmp[4] = product[13];
-    tmp[5] = product[14];
-    tmp[6] = product[15];
-    tmp[7] = 0;
-    carry += uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS);
-    carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
-
-    /* s3 */
-    tmp[0] = product[8];
-    tmp[1] = product[9];
-    tmp[2] = product[10];
-    tmp[3] = tmp[4] = tmp[5] = 0;
-    tmp[6] = product[14];
-    tmp[7] = product[15];
-    carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
-
-    /* s4 */
-    tmp[0] = product[9];
-    tmp[1] = product[10];
-    tmp[2] = product[11];
-    tmp[3] = product[13];
-    tmp[4] = product[14];
-    tmp[5] = product[15];
-    tmp[6] = product[13];
-    tmp[7] = product[8];
-    carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
-
-    /* d1 */
-    tmp[0] = product[11];
-    tmp[1] = product[12];
-    tmp[2] = product[13];
-    tmp[3] = tmp[4] = tmp[5] = 0;
-    tmp[6] = product[8];
-    tmp[7] = product[10];
-    carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
-
-    /* d2 */
-    tmp[0] = product[12];
-    tmp[1] = product[13];
-    tmp[2] = product[14];
-    tmp[3] = product[15];
-    tmp[4] = tmp[5] = 0;
-    tmp[6] = product[9];
-    tmp[7] = product[11];
-    carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
-
-    /* d3 */
-    tmp[0] = product[13];
-    tmp[1] = product[14];
-    tmp[2] = product[15];
-    tmp[3] = product[8];
-    tmp[4] = product[9];
-    tmp[5] = product[10];
-    tmp[6] = 0;
-    tmp[7] = product[12];
-    carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
-
-    /* d4 */
-    tmp[0] = product[14];
-    tmp[1] = product[15];
-    tmp[2] = 0;
-    tmp[3] = product[9];
-    tmp[4] = product[10];
-    tmp[5] = product[11];
-    tmp[6] = 0;
-    tmp[7] = product[13];
-    carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
-
-    if (carry < 0) {
-        do {
-            carry += uECC_vli_add(result, result, curve_secp256r1.p, NUM_ECC_WORDS);
-        } while (carry < 0);
+static void vli_modInv_update(uECC_word_t *uv, const uECC_word_t *mod, wordcount_t num_words) {
+  uECC_word_t carry = 0;
+
+  if (!EVEN(uv)) {
+    carry = uECC_vli_add(uv, uv, mod, num_words);
+  }
+  uECC_vli_rshift1(uv, num_words);
+  if (carry) {
+    uv[num_words - 1] |= HIGH_BIT_SET;
+  }
+}
+
+void uECC_vli_modInv(uECC_word_t *result, const uECC_word_t *input, const uECC_word_t *mod, wordcount_t num_words) {
+  uECC_word_t a[NUM_ECC_WORDS], b[NUM_ECC_WORDS];
+  uECC_word_t u[NUM_ECC_WORDS], v[NUM_ECC_WORDS];
+  cmpresult_t cmpResult;
+
+  if (uECC_vli_isZero(input, num_words)) {
+    uECC_vli_clear(result, num_words);
+    return;
+  }
+
+  uECC_vli_set(a, input, num_words);
+  uECC_vli_set(b, mod, num_words);
+  uECC_vli_clear(u, num_words);
+  u[0] = 1;
+  uECC_vli_clear(v, num_words);
+  while ((cmpResult = uECC_vli_cmp_unsafe(a, b, num_words)) != 0) {
+    if (EVEN(a)) {
+      uECC_vli_rshift1(a, num_words);
+      vli_modInv_update(u, mod, num_words);
+    } else if (EVEN(b)) {
+      uECC_vli_rshift1(b, num_words);
+      vli_modInv_update(v, mod, num_words);
+    } else if (cmpResult > 0) {
+      uECC_vli_sub(a, a, b, num_words);
+      uECC_vli_rshift1(a, num_words);
+      if (uECC_vli_cmp_unsafe(u, v, num_words) < 0) {
+        uECC_vli_add(u, u, mod, num_words);
+      }
+      uECC_vli_sub(u, u, v, num_words);
+      vli_modInv_update(u, mod, num_words);
     } else {
-        while (carry ||
-               uECC_vli_cmp_unsafe(curve_secp256r1.p, result, NUM_ECC_WORDS) != 1) {
-            carry -= uECC_vli_sub(result, result, curve_secp256r1.p, NUM_ECC_WORDS);
-        }
+      uECC_vli_sub(b, b, a, num_words);
+      uECC_vli_rshift1(b, num_words);
+      if (uECC_vli_cmp_unsafe(v, u, num_words) < 0) {
+        uECC_vli_add(v, v, mod, num_words);
+      }
+      uECC_vli_sub(v, v, u, num_words);
+      vli_modInv_update(v, mod, num_words);
     }
+  }
+  uECC_vli_set(result, u, num_words);
 }
 
-uECC_word_t EccPoint_isZero(const uECC_word_t *point, uECC_Curve curve)
-{
-    return uECC_vli_isZero(point, curve->num_words * 2);
-}
-
-void apply_z(uECC_word_t *X1, uECC_word_t *Y1, const uECC_word_t *const Z,
-             uECC_Curve curve)
-{
-    uECC_word_t t1[NUM_ECC_WORDS];
+/* ------ Point operations ------ */
 
-    uECC_vli_modSquare_fast(t1, Z, curve);    /* z^2 */
-    uECC_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */
-    uECC_vli_modMult_fast(t1, t1, Z, curve);  /* z^3 */
-    uECC_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */
+void double_jacobian_default(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *Z1, uECC_Curve curve) {
+  /* t1 = X, t2 = Y, t3 = Z */
+  uECC_word_t t4[NUM_ECC_WORDS];
+  uECC_word_t t5[NUM_ECC_WORDS];
+  wordcount_t num_words = curve->num_words;
+
+  if (uECC_vli_isZero(Z1, num_words)) {
+    return;
+  }
+
+  uECC_vli_modSquare_fast(t4, Y1, curve);   /* t4 = y1^2 */
+  uECC_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */
+  uECC_vli_modSquare_fast(t4, t4, curve);   /* t4 = y1^4 */
+  uECC_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */
+  uECC_vli_modSquare_fast(Z1, Z1, curve);   /* t3 = z1^2 */
+
+  uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */
+  uECC_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */
+  uECC_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */
+  uECC_vli_modMult_fast(X1, X1, Z1, curve);         /* t1 = x1^2 - z1^4 */
+
+  uECC_vli_modAdd(Z1, X1, X1, curve->p, num_words); /* t3 = 2*(x1^2 - z1^4) */
+  uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = 3*(x1^2 - z1^4) */
+  if (uECC_vli_testBit(X1, 0)) {
+    uECC_word_t l_carry = uECC_vli_add(X1, X1, curve->p, num_words);
+    uECC_vli_rshift1(X1, num_words);
+    X1[num_words - 1] |= l_carry << (uECC_WORD_BITS - 1);
+  } else {
+    uECC_vli_rshift1(X1, num_words);
+  }
+
+  /* t1 = 3/2*(x1^2 - z1^4) = B */
+  uECC_vli_modSquare_fast(Z1, X1, curve);           /* t3 = B^2 */
+  uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */
+  uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */
+  uECC_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */
+  uECC_vli_modMult_fast(X1, X1, t5, curve);         /* t1 = B * (A - x3) */
+  /* t4 = B * (A - x3) - y1^4 = y3: */
+  uECC_vli_modSub(t4, X1, t4, curve->p, num_words);
+
+  uECC_vli_set(X1, Z1, num_words);
+  uECC_vli_set(Z1, Y1, num_words);
+  uECC_vli_set(Y1, t4, num_words);
+}
+
+void x_side_default(uECC_word_t *result, const uECC_word_t *x, uECC_Curve curve) {
+  uECC_word_t _3[NUM_ECC_WORDS] = {3}; /* -a = 3 */
+  wordcount_t num_words         = curve->num_words;
+
+  uECC_vli_modSquare_fast(result, x, curve);                /* r = x^2 */
+  uECC_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */
+  uECC_vli_modMult_fast(result, result, x, curve);          /* r = x^3 - 3x */
+  /* r = x^3 - 3x + b: */
+  uECC_vli_modAdd(result, result, curve->b, curve->p, num_words);
+}
+
+uECC_Curve uECC_secp256r1(void) { return &curve_secp256r1; }
+
+void vli_mmod_fast_secp256r1(unsigned int *result, unsigned int *product) {
+  unsigned int tmp[NUM_ECC_WORDS];
+  int          carry;
+
+  /* t */
+  uECC_vli_set(result, product, NUM_ECC_WORDS);
+
+  /* s1 */
+  tmp[0] = tmp[1] = tmp[2] = 0;
+  tmp[3]                   = product[11];
+  tmp[4]                   = product[12];
+  tmp[5]                   = product[13];
+  tmp[6]                   = product[14];
+  tmp[7]                   = product[15];
+  carry                    = uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS);
+  carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
+
+  /* s2 */
+  tmp[3] = product[12];
+  tmp[4] = product[13];
+  tmp[5] = product[14];
+  tmp[6] = product[15];
+  tmp[7] = 0;
+  carry += uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS);
+  carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
+
+  /* s3 */
+  tmp[0] = product[8];
+  tmp[1] = product[9];
+  tmp[2] = product[10];
+  tmp[3] = tmp[4] = tmp[5] = 0;
+  tmp[6]                   = product[14];
+  tmp[7]                   = product[15];
+  carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
+
+  /* s4 */
+  tmp[0] = product[9];
+  tmp[1] = product[10];
+  tmp[2] = product[11];
+  tmp[3] = product[13];
+  tmp[4] = product[14];
+  tmp[5] = product[15];
+  tmp[6] = product[13];
+  tmp[7] = product[8];
+  carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
+
+  /* d1 */
+  tmp[0] = product[11];
+  tmp[1] = product[12];
+  tmp[2] = product[13];
+  tmp[3] = tmp[4] = tmp[5] = 0;
+  tmp[6]                   = product[8];
+  tmp[7]                   = product[10];
+  carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
+
+  /* d2 */
+  tmp[0] = product[12];
+  tmp[1] = product[13];
+  tmp[2] = product[14];
+  tmp[3] = product[15];
+  tmp[4] = tmp[5] = 0;
+  tmp[6]          = product[9];
+  tmp[7]          = product[11];
+  carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
+
+  /* d3 */
+  tmp[0] = product[13];
+  tmp[1] = product[14];
+  tmp[2] = product[15];
+  tmp[3] = product[8];
+  tmp[4] = product[9];
+  tmp[5] = product[10];
+  tmp[6] = 0;
+  tmp[7] = product[12];
+  carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
+
+  /* d4 */
+  tmp[0] = product[14];
+  tmp[1] = product[15];
+  tmp[2] = 0;
+  tmp[3] = product[9];
+  tmp[4] = product[10];
+  tmp[5] = product[11];
+  tmp[6] = 0;
+  tmp[7] = product[13];
+  carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
+
+  if (carry < 0) {
+    do {
+      carry += uECC_vli_add(result, result, curve_secp256r1.p, NUM_ECC_WORDS);
+    } while (carry < 0);
+  } else {
+    while (carry || uECC_vli_cmp_unsafe(curve_secp256r1.p, result, NUM_ECC_WORDS) != 1) {
+      carry -= uECC_vli_sub(result, result, curve_secp256r1.p, NUM_ECC_WORDS);
+    }
+  }
+}
+
+uECC_word_t EccPoint_isZero(const uECC_word_t *point, uECC_Curve curve) { return uECC_vli_isZero(point, curve->num_words * 2); }
+
+void apply_z(uECC_word_t *X1, uECC_word_t *Y1, const uECC_word_t *const Z, uECC_Curve curve) {
+  uECC_word_t t1[NUM_ECC_WORDS];
+
+  uECC_vli_modSquare_fast(t1, Z, curve);    /* z^2 */
+  uECC_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */
+  uECC_vli_modMult_fast(t1, t1, Z, curve);  /* z^3 */
+  uECC_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */
 }
 
 /* P = (x1, y1) => 2P, (x2, y2) => P' */
-static void XYcZ_initial_double(uECC_word_t *X1, uECC_word_t *Y1,
-                                uECC_word_t *X2, uECC_word_t *Y2,
-                                const uECC_word_t *const initial_Z,
-                                uECC_Curve curve)
-{
-    uECC_word_t z[NUM_ECC_WORDS];
-    wordcount_t num_words = curve->num_words;
-    if (initial_Z) {
-        uECC_vli_set(z, initial_Z, num_words);
-    } else {
-        uECC_vli_clear(z, num_words);
-        z[0] = 1;
-    }
-
-    uECC_vli_set(X2, X1, num_words);
-    uECC_vli_set(Y2, Y1, num_words);
-
-    apply_z(X1, Y1, z, curve);
-    curve->double_jacobian(X1, Y1, z, curve);
-    apply_z(X2, Y2, z, curve);
-}
-
-void XYcZ_add(uECC_word_t *X1, uECC_word_t *Y1,
-              uECC_word_t *X2, uECC_word_t *Y2,
-              uECC_Curve curve)
-{
-    /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
-    uECC_word_t t5[NUM_ECC_WORDS];
-    wordcount_t num_words = curve->num_words;
-
-    uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
-    uECC_vli_modSquare_fast(t5, t5, curve);           /* t5 = (x2 - x1)^2 = A */
-    uECC_vli_modMult_fast(X1, X1, t5, curve);         /* t1 = x1*A = B */
-    uECC_vli_modMult_fast(X2, X2, t5, curve);         /* t3 = x2*A = C */
-    uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
-    uECC_vli_modSquare_fast(t5, Y2, curve);           /* t5 = (y2 - y1)^2 = D */
-
-    uECC_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */
-    uECC_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */
-    uECC_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */
-    uECC_vli_modMult_fast(Y1, Y1, X2, curve);         /* t2 = y1*(C - B) */
-    uECC_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */
-    uECC_vli_modMult_fast(Y2, Y2, X2, curve);         /* t4 = (y2 - y1)*(B - x3) */
-    uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */
-
-    uECC_vli_set(X2, t5, num_words);
+static void XYcZ_initial_double(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *X2, uECC_word_t *Y2, const uECC_word_t *const initial_Z, uECC_Curve curve) {
+  uECC_word_t z[NUM_ECC_WORDS];
+  wordcount_t num_words = curve->num_words;
+  if (initial_Z) {
+    uECC_vli_set(z, initial_Z, num_words);
+  } else {
+    uECC_vli_clear(z, num_words);
+    z[0] = 1;
+  }
+
+  uECC_vli_set(X2, X1, num_words);
+  uECC_vli_set(Y2, Y1, num_words);
+
+  apply_z(X1, Y1, z, curve);
+  curve->double_jacobian(X1, Y1, z, curve);
+  apply_z(X2, Y2, z, curve);
+}
+
+void XYcZ_add(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *X2, uECC_word_t *Y2, uECC_Curve curve) {
+  /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
+  uECC_word_t t5[NUM_ECC_WORDS];
+  wordcount_t num_words = curve->num_words;
+
+  uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
+  uECC_vli_modSquare_fast(t5, t5, curve);           /* t5 = (x2 - x1)^2 = A */
+  uECC_vli_modMult_fast(X1, X1, t5, curve);         /* t1 = x1*A = B */
+  uECC_vli_modMult_fast(X2, X2, t5, curve);         /* t3 = x2*A = C */
+  uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
+  uECC_vli_modSquare_fast(t5, Y2, curve);           /* t5 = (y2 - y1)^2 = D */
+
+  uECC_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */
+  uECC_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */
+  uECC_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */
+  uECC_vli_modMult_fast(Y1, Y1, X2, curve);         /* t2 = y1*(C - B) */
+  uECC_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */
+  uECC_vli_modMult_fast(Y2, Y2, X2, curve);         /* t4 = (y2 - y1)*(B - x3) */
+  uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */
+
+  uECC_vli_set(X2, t5, num_words);
 }
 
 /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
    Output P + Q = (x3, y3, Z3), P - Q = (x3', y3', Z3)
    or P => P - Q, Q => P + Q
  */
-static void XYcZ_addC(uECC_word_t *X1, uECC_word_t *Y1,
-                      uECC_word_t *X2, uECC_word_t *Y2,
-                      uECC_Curve curve)
-{
-    /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
-    uECC_word_t t5[NUM_ECC_WORDS];
-    uECC_word_t t6[NUM_ECC_WORDS];
-    uECC_word_t t7[NUM_ECC_WORDS];
-    wordcount_t num_words = curve->num_words;
-
-    uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
-    uECC_vli_modSquare_fast(t5, t5, curve);           /* t5 = (x2 - x1)^2 = A */
-    uECC_vli_modMult_fast(X1, X1, t5, curve);         /* t1 = x1*A = B */
-    uECC_vli_modMult_fast(X2, X2, t5, curve);         /* t3 = x2*A = C */
-    uECC_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */
-    uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
-
-    uECC_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */
-    uECC_vli_modMult_fast(Y1, Y1, t6, curve);         /* t2 = y1 * (C - B) = E */
-    uECC_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */
-    uECC_vli_modSquare_fast(X2, Y2, curve);           /* t3 = (y2 - y1)^2 = D */
-    uECC_vli_modSub(X2, X2, t6, curve->p, num_words); /* t3 = D - (B + C) = x3 */
-
-    uECC_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */
-    uECC_vli_modMult_fast(Y2, Y2, t7, curve);         /* t4 = (y2 - y1)*(B - x3) */
-    /* t4 = (y2 - y1)*(B - x3) - E = y3: */
-    uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words);
-
-    uECC_vli_modSquare_fast(t7, t5, curve);           /* t7 = (y2 + y1)^2 = F */
-    uECC_vli_modSub(t7, t7, t6, curve->p, num_words); /* t7 = F - (B + C) = x3' */
-    uECC_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */
-    uECC_vli_modMult_fast(t6, t6, t5, curve);         /* t6 = (y2+y1)*(x3' - B) */
-    /* t2 = (y2+y1)*(x3' - B) - E = y3': */
-    uECC_vli_modSub(Y1, t6, Y1, curve->p, num_words);
-
-    uECC_vli_set(X1, t7, num_words);
-}
-
-void EccPoint_mult(uECC_word_t *result, const uECC_word_t *point,
-                   const uECC_word_t *scalar,
-                   const uECC_word_t *initial_Z,
-                   bitcount_t num_bits, uECC_Curve curve)
-{
-    /* R0 and R1 */
-    uECC_word_t Rx[2][NUM_ECC_WORDS];
-    uECC_word_t Ry[2][NUM_ECC_WORDS];
-    uECC_word_t z[NUM_ECC_WORDS];
-    bitcount_t i;
-    uECC_word_t nb;
-    wordcount_t num_words = curve->num_words;
-
-    uECC_vli_set(Rx[1], point, num_words);
-    uECC_vli_set(Ry[1], point + num_words, num_words);
-
-    XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve);
-
-    for (i = num_bits - 2; i > 0; --i) {
-        nb = !uECC_vli_testBit(scalar, i);
-        XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
-        XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
-    }
-
-    nb = !uECC_vli_testBit(scalar, 0);
+static void XYcZ_addC(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *X2, uECC_word_t *Y2, uECC_Curve curve) {
+  /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
+  uECC_word_t t5[NUM_ECC_WORDS];
+  uECC_word_t t6[NUM_ECC_WORDS];
+  uECC_word_t t7[NUM_ECC_WORDS];
+  wordcount_t num_words = curve->num_words;
+
+  uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
+  uECC_vli_modSquare_fast(t5, t5, curve);           /* t5 = (x2 - x1)^2 = A */
+  uECC_vli_modMult_fast(X1, X1, t5, curve);         /* t1 = x1*A = B */
+  uECC_vli_modMult_fast(X2, X2, t5, curve);         /* t3 = x2*A = C */
+  uECC_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */
+  uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
+
+  uECC_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */
+  uECC_vli_modMult_fast(Y1, Y1, t6, curve);         /* t2 = y1 * (C - B) = E */
+  uECC_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */
+  uECC_vli_modSquare_fast(X2, Y2, curve);           /* t3 = (y2 - y1)^2 = D */
+  uECC_vli_modSub(X2, X2, t6, curve->p, num_words); /* t3 = D - (B + C) = x3 */
+
+  uECC_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */
+  uECC_vli_modMult_fast(Y2, Y2, t7, curve);         /* t4 = (y2 - y1)*(B - x3) */
+  /* t4 = (y2 - y1)*(B - x3) - E = y3: */
+  uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words);
+
+  uECC_vli_modSquare_fast(t7, t5, curve);           /* t7 = (y2 + y1)^2 = F */
+  uECC_vli_modSub(t7, t7, t6, curve->p, num_words); /* t7 = F - (B + C) = x3' */
+  uECC_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */
+  uECC_vli_modMult_fast(t6, t6, t5, curve);         /* t6 = (y2+y1)*(x3' - B) */
+  /* t2 = (y2+y1)*(x3' - B) - E = y3': */
+  uECC_vli_modSub(Y1, t6, Y1, curve->p, num_words);
+
+  uECC_vli_set(X1, t7, num_words);
+}
+
+void EccPoint_mult(uECC_word_t *result, const uECC_word_t *point, const uECC_word_t *scalar, const uECC_word_t *initial_Z, bitcount_t num_bits, uECC_Curve curve) {
+  /* R0 and R1 */
+  uECC_word_t Rx[2][NUM_ECC_WORDS];
+  uECC_word_t Ry[2][NUM_ECC_WORDS];
+  uECC_word_t z[NUM_ECC_WORDS];
+  bitcount_t  i;
+  uECC_word_t nb;
+  wordcount_t num_words = curve->num_words;
+
+  uECC_vli_set(Rx[1], point, num_words);
+  uECC_vli_set(Ry[1], point + num_words, num_words);
+
+  XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve);
+
+  for (i = num_bits - 2; i > 0; --i) {
+    nb = !uECC_vli_testBit(scalar, i);
     XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
+    XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
+  }
 
-    /* Find final 1/Z value. */
-    uECC_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */
-    uECC_vli_modMult_fast(z, z, Ry[1 - nb], curve);        /* Yb * (X1 - X0) */
-    uECC_vli_modMult_fast(z, z, point, curve);             /* xP * Yb * (X1 - X0) */
-    uECC_vli_modInv(z, z, curve->p, num_words);            /* 1 / (xP * Yb * (X1 - X0))*/
-    /* yP / (xP * Yb * (X1 - X0)) */
-    uECC_vli_modMult_fast(z, z, point + num_words, curve);
-    /* Xb * yP / (xP * Yb * (X1 - X0)) */
-    uECC_vli_modMult_fast(z, z, Rx[1 - nb], curve);
-    /* End 1/Z calculation */
+  nb = !uECC_vli_testBit(scalar, 0);
+  XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
 
-    XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
-    apply_z(Rx[0], Ry[0], z, curve);
+  /* Find final 1/Z value. */
+  uECC_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */
+  uECC_vli_modMult_fast(z, z, Ry[1 - nb], curve);        /* Yb * (X1 - X0) */
+  uECC_vli_modMult_fast(z, z, point, curve);             /* xP * Yb * (X1 - X0) */
+  uECC_vli_modInv(z, z, curve->p, num_words);            /* 1 / (xP * Yb * (X1 - X0))*/
+  /* yP / (xP * Yb * (X1 - X0)) */
+  uECC_vli_modMult_fast(z, z, point + num_words, curve);
+  /* Xb * yP / (xP * Yb * (X1 - X0)) */
+  uECC_vli_modMult_fast(z, z, Rx[1 - nb], curve);
+  /* End 1/Z calculation */
 
-    uECC_vli_set(result, Rx[0], num_words);
-    uECC_vli_set(result + num_words, Ry[0], num_words);
+  XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
+  apply_z(Rx[0], Ry[0], z, curve);
+
+  uECC_vli_set(result, Rx[0], num_words);
+  uECC_vli_set(result + num_words, Ry[0], num_words);
 }
 
-uECC_word_t regularize_k(const uECC_word_t *const k, uECC_word_t *k0,
-                         uECC_word_t *k1, uECC_Curve curve)
-{
-    wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
+uECC_word_t regularize_k(const uECC_word_t *const k, uECC_word_t *k0, uECC_word_t *k1, uECC_Curve curve) {
+  wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
 
-    bitcount_t num_n_bits = curve->num_n_bits;
+  bitcount_t num_n_bits = curve->num_n_bits;
 
-    uECC_word_t carry = uECC_vli_add(k0, k, curve->n, num_n_words) ||
-                        (num_n_bits < ((bitcount_t)num_n_words * uECC_WORD_SIZE * 8) &&
-                         uECC_vli_testBit(k0, num_n_bits));
+  uECC_word_t carry = uECC_vli_add(k0, k, curve->n, num_n_words) || (num_n_bits < ((bitcount_t)num_n_words * uECC_WORD_SIZE * 8) && uECC_vli_testBit(k0, num_n_bits));
 
-    uECC_vli_add(k1, k0, curve->n, num_n_words);
+  uECC_vli_add(k1, k0, curve->n, num_n_words);
 
-    return carry;
+  return carry;
 }
 
-uECC_word_t EccPoint_compute_public_key(uECC_word_t *result,
-                                        uECC_word_t *private_key,
-                                        uECC_Curve curve)
-{
-    uECC_word_t tmp1[NUM_ECC_WORDS];
-    uECC_word_t tmp2[NUM_ECC_WORDS];
-    uECC_word_t *p2[2] = { tmp1, tmp2 };
-    uECC_word_t carry;
+uECC_word_t EccPoint_compute_public_key(uECC_word_t *result, uECC_word_t *private_key, uECC_Curve curve) {
+  uECC_word_t  tmp1[NUM_ECC_WORDS];
+  uECC_word_t  tmp2[NUM_ECC_WORDS];
+  uECC_word_t *p2[2] = {tmp1, tmp2};
+  uECC_word_t  carry;
 
-    /* Regularize the bitcount for the private key so that attackers cannot
-	 * use a side channel attack to learn the number of leading zeros. */
-    carry = regularize_k(private_key, tmp1, tmp2, curve);
+  /* Regularize the bitcount for the private key so that attackers cannot
+   * use a side channel attack to learn the number of leading zeros. */
+  carry = regularize_k(private_key, tmp1, tmp2, curve);
 
-    EccPoint_mult(result, curve->G, p2[!carry], 0, curve->num_n_bits + 1, curve);
+  EccPoint_mult(result, curve->G, p2[!carry], 0, curve->num_n_bits + 1, curve);
 
-    if (EccPoint_isZero(result, curve)) {
-        return 0;
-    }
-    return 1;
+  if (EccPoint_isZero(result, curve)) {
+    return 0;
+  }
+  return 1;
 }
 
 /* Converts an integer in uECC native format to big-endian bytes. */
-void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
-                            const unsigned int *native)
-{
-    wordcount_t i;
-    for (i = 0; i < num_bytes; ++i) {
-        unsigned b = num_bytes - 1 - i;
-        bytes[i] = native[b / uECC_WORD_SIZE] >> (8 * (b % uECC_WORD_SIZE));
-    }
+void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes, const unsigned int *native) {
+  wordcount_t i;
+  for (i = 0; i < num_bytes; ++i) {
+    unsigned b = num_bytes - 1 - i;
+    bytes[i]   = native[b / uECC_WORD_SIZE] >> (8 * (b % uECC_WORD_SIZE));
+  }
 }
 
 /* Converts big-endian bytes to an integer in uECC native format. */
-void uECC_vli_bytesToNative(unsigned int *native, const uint8_t *bytes,
-                            int num_bytes)
-{
-    wordcount_t i;
-    uECC_vli_clear(native, (num_bytes + (uECC_WORD_SIZE - 1)) / uECC_WORD_SIZE);
-    for (i = 0; i < num_bytes; ++i) {
-        unsigned b = num_bytes - 1 - i;
-        native[b / uECC_WORD_SIZE] |=
-            (uECC_word_t)bytes[i] << (8 * (b % uECC_WORD_SIZE));
-    }
+void uECC_vli_bytesToNative(unsigned int *native, const uint8_t *bytes, int num_bytes) {
+  wordcount_t i;
+  uECC_vli_clear(native, (num_bytes + (uECC_WORD_SIZE - 1)) / uECC_WORD_SIZE);
+  for (i = 0; i < num_bytes; ++i) {
+    unsigned b = num_bytes - 1 - i;
+    native[b / uECC_WORD_SIZE] |= (uECC_word_t)bytes[i] << (8 * (b % uECC_WORD_SIZE));
+  }
 }
 
-int uECC_generate_random_int(uECC_word_t *random, const uECC_word_t *top,
-                             wordcount_t num_words)
-{
-    uECC_word_t mask = (uECC_word_t)-1;
-    uECC_word_t tries;
-    bitcount_t num_bits = uECC_vli_numBits(top, num_words);
+int uECC_generate_random_int(uECC_word_t *random, const uECC_word_t *top, wordcount_t num_words) {
+  uECC_word_t mask = (uECC_word_t)-1;
+  uECC_word_t tries;
+  bitcount_t  num_bits = uECC_vli_numBits(top, num_words);
 
-    if (!g_rng_function) {
-        return 0;
-    }
+  if (!g_rng_function) {
+    return 0;
+  }
 
-    for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
-        if (!g_rng_function((uint8_t *)random, num_words * uECC_WORD_SIZE)) {
-            return 0;
-        }
-        random[num_words - 1] &=
-            mask >> ((bitcount_t)(num_words * uECC_WORD_SIZE * 8 - num_bits));
-        if (!uECC_vli_isZero(random, num_words) &&
-            uECC_vli_cmp(top, random, num_words) == 1) {
-            return 1;
-        }
+  for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
+    if (!g_rng_function((uint8_t *)random, num_words * uECC_WORD_SIZE)) {
+      return 0;
     }
-    return 0;
+    random[num_words - 1] &= mask >> ((bitcount_t)(num_words * uECC_WORD_SIZE * 8 - num_bits));
+    if (!uECC_vli_isZero(random, num_words) && uECC_vli_cmp(top, random, num_words) == 1) {
+      return 1;
+    }
+  }
+  return 0;
 }
 
-int uECC_valid_point(const uECC_word_t *point, uECC_Curve curve)
-{
-    uECC_word_t tmp1[NUM_ECC_WORDS];
-    uECC_word_t tmp2[NUM_ECC_WORDS];
-    wordcount_t num_words = curve->num_words;
+int uECC_valid_point(const uECC_word_t *point, uECC_Curve curve) {
+  uECC_word_t tmp1[NUM_ECC_WORDS];
+  uECC_word_t tmp2[NUM_ECC_WORDS];
+  wordcount_t num_words = curve->num_words;
 
-    /* The point at infinity is invalid. */
-    if (EccPoint_isZero(point, curve)) {
-        return -1;
-    }
+  /* The point at infinity is invalid. */
+  if (EccPoint_isZero(point, curve)) {
+    return -1;
+  }
 
-    /* x and y must be smaller than p. */
-    if (uECC_vli_cmp_unsafe(curve->p, point, num_words) != 1 ||
-        uECC_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) {
-        return -2;
-    }
+  /* x and y must be smaller than p. */
+  if (uECC_vli_cmp_unsafe(curve->p, point, num_words) != 1 || uECC_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) {
+    return -2;
+  }
 
-    uECC_vli_modSquare_fast(tmp1, point + num_words, curve);
-    curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */
+  uECC_vli_modSquare_fast(tmp1, point + num_words, curve);
+  curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */
 
-    /* Make sure that y^2 == x^3 + ax + b */
-    if (uECC_vli_equal(tmp1, tmp2, num_words) != 0)
-        return -3;
+  /* Make sure that y^2 == x^3 + ax + b */
+  if (uECC_vli_equal(tmp1, tmp2, num_words) != 0)
+    return -3;
 
-    return 0;
+  return 0;
 }
 
-int uECC_valid_public_key(const uint8_t *public_key, uECC_Curve curve)
-{
-    uECC_word_t _public[NUM_ECC_WORDS * 2];
+int uECC_valid_public_key(const uint8_t *public_key, uECC_Curve curve) {
+  uECC_word_t _public[NUM_ECC_WORDS * 2];
 
-    uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
-    uECC_vli_bytesToNative(
-        _public + curve->num_words,
-        public_key + curve->num_bytes,
-        curve->num_bytes);
+  uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
+  uECC_vli_bytesToNative(_public + curve->num_words, public_key + curve->num_bytes, curve->num_bytes);
 
-    if (uECC_vli_cmp_unsafe(_public, curve->G, NUM_ECC_WORDS * 2) == 0) {
-        return -4;
-    }
+  if (uECC_vli_cmp_unsafe(_public, curve->G, NUM_ECC_WORDS * 2) == 0) {
+    return -4;
+  }
 
-    return uECC_valid_point(_public, curve);
+  return uECC_valid_point(_public, curve);
 }
 
-int uECC_compute_public_key(const uint8_t *private_key, uint8_t *public_key,
-                            uECC_Curve curve)
-{
-    uECC_word_t _private[NUM_ECC_WORDS];
-    uECC_word_t _public[NUM_ECC_WORDS * 2];
+int uECC_compute_public_key(const uint8_t *private_key, uint8_t *public_key, uECC_Curve curve) {
+  uECC_word_t _private[NUM_ECC_WORDS];
+  uECC_word_t _public[NUM_ECC_WORDS * 2];
 
-    uECC_vli_bytesToNative(
-        _private,
-        private_key,
-        BITS_TO_BYTES(curve->num_n_bits));
+  uECC_vli_bytesToNative(_private, private_key, BITS_TO_BYTES(curve->num_n_bits));
 
-    /* Make sure the private key is in the range [1, n-1]. */
-    if (uECC_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) {
-        return 0;
-    }
+  /* Make sure the private key is in the range [1, n-1]. */
+  if (uECC_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) {
+    return 0;
+  }
 
-    if (uECC_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) != 1) {
-        return 0;
-    }
+  if (uECC_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) != 1) {
+    return 0;
+  }
 
-    /* Compute public key. */
-    if (!EccPoint_compute_public_key(_public, _private, curve)) {
-        return 0;
-    }
+  /* Compute public key. */
+  if (!EccPoint_compute_public_key(_public, _private, curve)) {
+    return 0;
+  }
 
-    uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public);
-    uECC_vli_nativeToBytes(
-        public_key +
-            curve->num_bytes,
-        curve->num_bytes, _public + curve->num_words);
-    return 1;
+  uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public);
+  uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, _public + curve->num_words);
+  return 1;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dh.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dh.c
index e2995ef2a5..e26b152644 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dh.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dh.c
@@ -1,6 +1,6 @@
 /* ec_dh.c - TinyCrypt implementation of EC-DH */
 
-/* 
+/*
  * Copyright (c) 2014, Kenneth MacKay
  * All rights reserved.
  *
@@ -54,9 +54,9 @@
  *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  *  POSSIBILITY OF SUCH DAMAGE.
  */
+#include "ecc_dh.h"
 #include "constants.h"
 #include "ecc.h"
-#include "ecc_dh.h"
 #if defined(BFLB_BLE)
 #include "utils.h"
 #endif
@@ -71,128 +71,103 @@ static uECC_RNG_Function g_rng_function = &default_CSPRNG;
 static uECC_RNG_Function g_rng_function = 0;
 #endif
 
-int uECC_make_key_with_d(uint8_t *public_key, uint8_t *private_key,
-                         unsigned int *d, uECC_Curve curve)
-{
-    uECC_word_t _private[NUM_ECC_WORDS];
-    uECC_word_t _public[NUM_ECC_WORDS * 2];
+int uECC_make_key_with_d(uint8_t *public_key, uint8_t *private_key, unsigned int *d, uECC_Curve curve) {
+  uECC_word_t _private[NUM_ECC_WORDS];
+  uECC_word_t _public[NUM_ECC_WORDS * 2];
 
-    /* This function is designed for test purposes-only (such as validating NIST
-	 * test vectors) as it uses a provided value for d instead of generating
-	 * it uniformly at random. */
-    memcpy(_private, d, NUM_ECC_BYTES);
+  /* This function is designed for test purposes-only (such as validating NIST
+   * test vectors) as it uses a provided value for d instead of generating
+   * it uniformly at random. */
+  memcpy(_private, d, NUM_ECC_BYTES);
 
-    /* Computing public-key from private: */
-    if (EccPoint_compute_public_key(_public, _private, curve)) {
-        /* Converting buffers to correct bit order: */
-        uECC_vli_nativeToBytes(private_key,
-                               BITS_TO_BYTES(curve->num_n_bits),
-                               _private);
-        uECC_vli_nativeToBytes(public_key,
-                               curve->num_bytes,
-                               _public);
-        uECC_vli_nativeToBytes(public_key + curve->num_bytes,
-                               curve->num_bytes,
-                               _public + curve->num_words);
-
-        /* erasing temporary buffer used to store secret: */
-        _set_secure(_private, 0, NUM_ECC_BYTES);
-
-        return 1;
-    }
-    return 0;
+  /* Computing public-key from private: */
+  if (EccPoint_compute_public_key(_public, _private, curve)) {
+    /* Converting buffers to correct bit order: */
+    uECC_vli_nativeToBytes(private_key, BITS_TO_BYTES(curve->num_n_bits), _private);
+    uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public);
+    uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, _public + curve->num_words);
+
+    /* erasing temporary buffer used to store secret: */
+    _set_secure(_private, 0, NUM_ECC_BYTES);
+
+    return 1;
+  }
+  return 0;
 }
 
-int uECC_make_key(uint8_t *public_key, uint8_t *private_key, uECC_Curve curve)
-{
-    uECC_word_t _random[NUM_ECC_WORDS * 2];
-    uECC_word_t _private[NUM_ECC_WORDS];
-    uECC_word_t _public[NUM_ECC_WORDS * 2];
-    uECC_word_t tries;
-
-    for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
-        /* Generating _private uniformly at random: */
-        uECC_RNG_Function rng_function = uECC_get_rng();
-        if (!rng_function ||
-            !rng_function((uint8_t *)_random, 2 * NUM_ECC_WORDS * uECC_WORD_SIZE)) {
-            return 0;
-        }
-
-        /* computing modular reduction of _random (see FIPS 186.4 B.4.1): */
-        uECC_vli_mmod(_private, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits));
-
-        /* Computing public-key from private: */
-        if (EccPoint_compute_public_key(_public, _private, curve)) {
-            /* Converting buffers to correct bit order: */
-            uECC_vli_nativeToBytes(private_key,
-                                   BITS_TO_BYTES(curve->num_n_bits),
-                                   _private);
-            uECC_vli_nativeToBytes(public_key,
-                                   curve->num_bytes,
-                                   _public);
-            uECC_vli_nativeToBytes(public_key + curve->num_bytes,
-                                   curve->num_bytes,
-                                   _public + curve->num_words);
-
-            /* erasing temporary buffer that stored secret: */
-            _set_secure(_private, 0, NUM_ECC_BYTES);
-
-            return 1;
-        }
+int uECC_make_key(uint8_t *public_key, uint8_t *private_key, uECC_Curve curve) {
+  uECC_word_t _random[NUM_ECC_WORDS * 2];
+  uECC_word_t _private[NUM_ECC_WORDS];
+  uECC_word_t _public[NUM_ECC_WORDS * 2];
+  uECC_word_t tries;
+
+  for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
+    /* Generating _private uniformly at random: */
+    uECC_RNG_Function rng_function = uECC_get_rng();
+    if (!rng_function || !rng_function((uint8_t *)_random, 2 * NUM_ECC_WORDS * uECC_WORD_SIZE)) {
+      return 0;
     }
-    return 0;
-}
 
-int uECC_shared_secret(const uint8_t *public_key, const uint8_t *private_key,
-                       uint8_t *secret, uECC_Curve curve)
-{
-    uECC_word_t _public[NUM_ECC_WORDS * 2];
-    uECC_word_t _private[NUM_ECC_WORDS];
+    /* computing modular reduction of _random (see FIPS 186.4 B.4.1): */
+    uECC_vli_mmod(_private, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits));
 
-    uECC_word_t tmp[NUM_ECC_WORDS];
-    uECC_word_t *p2[2] = { _private, tmp };
-    uECC_word_t *initial_Z = 0;
-    uECC_word_t carry;
-    wordcount_t num_words = curve->num_words;
-    wordcount_t num_bytes = curve->num_bytes;
-    int r;
+    /* Computing public-key from private: */
+    if (EccPoint_compute_public_key(_public, _private, curve)) {
+      /* Converting buffers to correct bit order: */
+      uECC_vli_nativeToBytes(private_key, BITS_TO_BYTES(curve->num_n_bits), _private);
+      uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public);
+      uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, _public + curve->num_words);
 
-    /* Converting buffers to correct bit order: */
-    uECC_vli_bytesToNative(_private,
-                           private_key,
-                           BITS_TO_BYTES(curve->num_n_bits));
-    uECC_vli_bytesToNative(_public,
-                           public_key,
-                           num_bytes);
-    uECC_vli_bytesToNative(_public + num_words,
-                           public_key + num_bytes,
-                           num_bytes);
-
-    /* Regularize the bitcount for the private key so that attackers cannot use a
-	 * side channel attack to learn the number of leading zeros. */
-    carry = regularize_k(_private, _private, tmp, curve);
-
-    /* If an RNG function was specified, try to get a random initial Z value to
-	 * improve protection against side-channel attacks. */
-    if (g_rng_function) {
-        if (!uECC_generate_random_int(p2[carry], curve->p, num_words)) {
-            r = 0;
-            goto clear_and_out;
-        }
-        initial_Z = p2[carry];
+      /* erasing temporary buffer that stored secret: */
+      _set_secure(_private, 0, NUM_ECC_BYTES);
+
+      return 1;
     }
+  }
+  return 0;
+}
+
+int uECC_shared_secret(const uint8_t *public_key, const uint8_t *private_key, uint8_t *secret, uECC_Curve curve) {
+  uECC_word_t _public[NUM_ECC_WORDS * 2];
+  uECC_word_t _private[NUM_ECC_WORDS];
+
+  uECC_word_t  tmp[NUM_ECC_WORDS];
+  uECC_word_t *p2[2]     = {_private, tmp};
+  uECC_word_t *initial_Z = 0;
+  uECC_word_t  carry;
+  wordcount_t  num_words = curve->num_words;
+  wordcount_t  num_bytes = curve->num_bytes;
+  int          r;
+
+  /* Converting buffers to correct bit order: */
+  uECC_vli_bytesToNative(_private, private_key, BITS_TO_BYTES(curve->num_n_bits));
+  uECC_vli_bytesToNative(_public, public_key, num_bytes);
+  uECC_vli_bytesToNative(_public + num_words, public_key + num_bytes, num_bytes);
+
+  /* Regularize the bitcount for the private key so that attackers cannot use a
+   * side channel attack to learn the number of leading zeros. */
+  carry = regularize_k(_private, _private, tmp, curve);
+
+  /* If an RNG function was specified, try to get a random initial Z value to
+   * improve protection against side-channel attacks. */
+  if (g_rng_function) {
+    if (!uECC_generate_random_int(p2[carry], curve->p, num_words)) {
+      r = 0;
+      goto clear_and_out;
+    }
+    initial_Z = p2[carry];
+  }
 
-    EccPoint_mult(_public, _public, p2[!carry], initial_Z, curve->num_n_bits + 1,
-                  curve);
+  EccPoint_mult(_public, _public, p2[!carry], initial_Z, curve->num_n_bits + 1, curve);
 
-    uECC_vli_nativeToBytes(secret, num_bytes, _public);
-    r = !EccPoint_isZero(_public, curve);
+  uECC_vli_nativeToBytes(secret, num_bytes, _public);
+  r = !EccPoint_isZero(_public, curve);
 
 clear_and_out:
-    /* erasing temporary buffer used to store secret: */
-    _set_secure(p2, 0, sizeof(p2));
-    _set_secure(tmp, 0, sizeof(tmp));
-    _set_secure(_private, 0, sizeof(_private));
+  /* erasing temporary buffer used to store secret: */
+  _set_secure(p2, 0, sizeof(p2));
+  _set_secure(tmp, 0, sizeof(tmp));
+  _set_secure(_private, 0, sizeof(_private));
 
-    return r;
+  return r;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dsa.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dsa.c
index 117e3d26dd..6bad09339e 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dsa.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dsa.c
@@ -53,9 +53,9 @@
  *  POSSIBILITY OF SUCH DAMAGE.
  */
 
+#include "ecc_dsa.h"
 #include "constants.h"
 #include "ecc.h"
-#include "ecc_dsa.h"
 #if defined(BL_MCU_SDK)
 #include "ecc_platform_specific.h"
 #endif
@@ -66,229 +66,209 @@ static uECC_RNG_Function g_rng_function = &default_CSPRNG;
 static uECC_RNG_Function g_rng_function = 0;
 #endif
 
-static void bits2int(uECC_word_t *native, const uint8_t *bits,
-                     unsigned bits_size, uECC_Curve curve)
-{
-    unsigned num_n_bytes = BITS_TO_BYTES(curve->num_n_bits);
-    unsigned num_n_words = BITS_TO_WORDS(curve->num_n_bits);
-    int shift;
-    uECC_word_t carry;
-    uECC_word_t *ptr;
-
-    if (bits_size > num_n_bytes) {
-        bits_size = num_n_bytes;
-    }
-
-    uECC_vli_clear(native, num_n_words);
-    uECC_vli_bytesToNative(native, bits, bits_size);
-    if (bits_size * 8 <= (unsigned)curve->num_n_bits) {
-        return;
-    }
-    shift = bits_size * 8 - curve->num_n_bits;
-    carry = 0;
-    ptr = native + num_n_words;
-    while (ptr-- > native) {
-        uECC_word_t temp = *ptr;
-        *ptr = (temp >> shift) | carry;
-        carry = temp << (uECC_WORD_BITS - shift);
-    }
-
-    /* Reduce mod curve_n */
-    if (uECC_vli_cmp_unsafe(curve->n, native, num_n_words) != 1) {
-        uECC_vli_sub(native, native, curve->n, num_n_words);
-    }
+static void bits2int(uECC_word_t *native, const uint8_t *bits, unsigned bits_size, uECC_Curve curve) {
+  unsigned     num_n_bytes = BITS_TO_BYTES(curve->num_n_bits);
+  unsigned     num_n_words = BITS_TO_WORDS(curve->num_n_bits);
+  int          shift;
+  uECC_word_t  carry;
+  uECC_word_t *ptr;
+
+  if (bits_size > num_n_bytes) {
+    bits_size = num_n_bytes;
+  }
+
+  uECC_vli_clear(native, num_n_words);
+  uECC_vli_bytesToNative(native, bits, bits_size);
+  if (bits_size * 8 <= (unsigned)curve->num_n_bits) {
+    return;
+  }
+  shift = bits_size * 8 - curve->num_n_bits;
+  carry = 0;
+  ptr   = native + num_n_words;
+  while (ptr-- > native) {
+    uECC_word_t temp = *ptr;
+    *ptr             = (temp >> shift) | carry;
+    carry            = temp << (uECC_WORD_BITS - shift);
+  }
+
+  /* Reduce mod curve_n */
+  if (uECC_vli_cmp_unsafe(curve->n, native, num_n_words) != 1) {
+    uECC_vli_sub(native, native, curve->n, num_n_words);
+  }
 }
 
-int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash,
-                     unsigned hash_size, uECC_word_t *k, uint8_t *signature,
-                     uECC_Curve curve)
-{
-    uECC_word_t tmp[NUM_ECC_WORDS];
-    uECC_word_t s[NUM_ECC_WORDS];
-    uECC_word_t *k2[2] = { tmp, s };
-    uECC_word_t p[NUM_ECC_WORDS * 2];
-    uECC_word_t carry;
-    wordcount_t num_words = curve->num_words;
-    wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
-    bitcount_t num_n_bits = curve->num_n_bits;
-
-    /* Make sure 0 < k < curve_n */
-    if (uECC_vli_isZero(k, num_words) ||
-        uECC_vli_cmp(curve->n, k, num_n_words) != 1) {
-        return 0;
-    }
-
-    carry = regularize_k(k, tmp, s, curve);
-    EccPoint_mult(p, curve->G, k2[!carry], 0, num_n_bits + 1, curve);
-    if (uECC_vli_isZero(p, num_words)) {
-        return 0;
-    }
+int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash, unsigned hash_size, uECC_word_t *k, uint8_t *signature, uECC_Curve curve) {
+  uECC_word_t  tmp[NUM_ECC_WORDS];
+  uECC_word_t  s[NUM_ECC_WORDS];
+  uECC_word_t *k2[2] = {tmp, s};
+  uECC_word_t  p[NUM_ECC_WORDS * 2];
+  uECC_word_t  carry;
+  wordcount_t  num_words   = curve->num_words;
+  wordcount_t  num_n_words = BITS_TO_WORDS(curve->num_n_bits);
+  bitcount_t   num_n_bits  = curve->num_n_bits;
+
+  /* Make sure 0 < k < curve_n */
+  if (uECC_vli_isZero(k, num_words) || uECC_vli_cmp(curve->n, k, num_n_words) != 1) {
+    return 0;
+  }
 
-    /* If an RNG function was specified, get a random number
-	to prevent side channel analysis of k. */
-    if (!g_rng_function) {
-        uECC_vli_clear(tmp, num_n_words);
-        tmp[0] = 1;
-    } else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) {
-        return 0;
-    }
+  carry = regularize_k(k, tmp, s, curve);
+  EccPoint_mult(p, curve->G, k2[!carry], 0, num_n_bits + 1, curve);
+  if (uECC_vli_isZero(p, num_words)) {
+    return 0;
+  }
+
+  /* If an RNG function was specified, get a random number
+      to prevent side channel analysis of k. */
+  if (!g_rng_function) {
+    uECC_vli_clear(tmp, num_n_words);
+    tmp[0] = 1;
+  } else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) {
+    return 0;
+  }
 
-    /* Prevent side channel analysis of uECC_vli_modInv() to determine
-	bits of k / the private key by premultiplying by a random number */
-    uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */
-    uECC_vli_modInv(k, k, curve->n, num_n_words);       /* k = 1 / k' */
-    uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */
+  /* Prevent side channel analysis of uECC_vli_modInv() to determine
+      bits of k / the private key by premultiplying by a random number */
+  uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */
+  uECC_vli_modInv(k, k, curve->n, num_n_words);       /* k = 1 / k' */
+  uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */
 
-    uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */
+  uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */
 
-    /* tmp = d: */
-    uECC_vli_bytesToNative(tmp, private_key, BITS_TO_BYTES(curve->num_n_bits));
+  /* tmp = d: */
+  uECC_vli_bytesToNative(tmp, private_key, BITS_TO_BYTES(curve->num_n_bits));
 
-    s[num_n_words - 1] = 0;
-    uECC_vli_set(s, p, num_words);
-    uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */
+  s[num_n_words - 1] = 0;
+  uECC_vli_set(s, p, num_words);
+  uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */
 
-    bits2int(tmp, message_hash, hash_size, curve);
-    uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */
-    uECC_vli_modMult(s, s, k, curve->n, num_n_words);  /* s = (e + r*d) / k */
-    if (uECC_vli_numBits(s, num_n_words) > (bitcount_t)curve->num_bytes * 8) {
-        return 0;
-    }
+  bits2int(tmp, message_hash, hash_size, curve);
+  uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */
+  uECC_vli_modMult(s, s, k, curve->n, num_n_words);  /* s = (e + r*d) / k */
+  if (uECC_vli_numBits(s, num_n_words) > (bitcount_t)curve->num_bytes * 8) {
+    return 0;
+  }
 
-    uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s);
-    return 1;
+  uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s);
+  return 1;
 }
 
-int uECC_sign(const uint8_t *private_key, const uint8_t *message_hash,
-              unsigned hash_size, uint8_t *signature, uECC_Curve curve)
-{
-    uECC_word_t _random[2 * NUM_ECC_WORDS];
-    uECC_word_t k[NUM_ECC_WORDS];
-    uECC_word_t tries;
-
-    for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
-        /* Generating _random uniformly at random: */
-        uECC_RNG_Function rng_function = uECC_get_rng();
-        if (!rng_function ||
-            !rng_function((uint8_t *)_random, 2 * NUM_ECC_WORDS * uECC_WORD_SIZE)) {
-            return 0;
-        }
-
-        // computing k as modular reduction of _random (see FIPS 186.4 B.5.1):
-        uECC_vli_mmod(k, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits));
-
-        if (uECC_sign_with_k(private_key, message_hash, hash_size, k, signature,
-                             curve)) {
-            return 1;
-        }
+int uECC_sign(const uint8_t *private_key, const uint8_t *message_hash, unsigned hash_size, uint8_t *signature, uECC_Curve curve) {
+  uECC_word_t _random[2 * NUM_ECC_WORDS];
+  uECC_word_t k[NUM_ECC_WORDS];
+  uECC_word_t tries;
+
+  for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
+    /* Generating _random uniformly at random: */
+    uECC_RNG_Function rng_function = uECC_get_rng();
+    if (!rng_function || !rng_function((uint8_t *)_random, 2 * NUM_ECC_WORDS * uECC_WORD_SIZE)) {
+      return 0;
     }
-    return 0;
-}
 
-static bitcount_t smax(bitcount_t a, bitcount_t b)
-{
-    return (a > b ? a : b);
-}
+    // computing k as modular reduction of _random (see FIPS 186.4 B.5.1):
+    uECC_vli_mmod(k, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits));
 
-int uECC_verify(const uint8_t *public_key, const uint8_t *message_hash,
-                unsigned hash_size, const uint8_t *signature,
-                uECC_Curve curve)
-{
-    uECC_word_t u1[NUM_ECC_WORDS], u2[NUM_ECC_WORDS];
-    uECC_word_t z[NUM_ECC_WORDS];
-    uECC_word_t sum[NUM_ECC_WORDS * 2];
-    uECC_word_t rx[NUM_ECC_WORDS];
-    uECC_word_t ry[NUM_ECC_WORDS];
-    uECC_word_t tx[NUM_ECC_WORDS];
-    uECC_word_t ty[NUM_ECC_WORDS];
-    uECC_word_t tz[NUM_ECC_WORDS];
-    const uECC_word_t *points[4];
-    const uECC_word_t *point;
-    bitcount_t num_bits;
-    bitcount_t i;
-
-    uECC_word_t _public[NUM_ECC_WORDS * 2];
-    uECC_word_t r[NUM_ECC_WORDS], s[NUM_ECC_WORDS];
-    wordcount_t num_words = curve->num_words;
-    wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
-
-    rx[num_n_words - 1] = 0;
-    r[num_n_words - 1] = 0;
-    s[num_n_words - 1] = 0;
-
-    uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
-    uECC_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes,
-                           curve->num_bytes);
-    uECC_vli_bytesToNative(r, signature, curve->num_bytes);
-    uECC_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes);
-
-    /* r, s must not be 0. */
-    if (uECC_vli_isZero(r, num_words) || uECC_vli_isZero(s, num_words)) {
-        return 0;
+    if (uECC_sign_with_k(private_key, message_hash, hash_size, k, signature, curve)) {
+      return 1;
     }
+  }
+  return 0;
+}
 
-    /* r, s must be < n. */
-    if (uECC_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 ||
-        uECC_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) {
-        return 0;
-    }
+static bitcount_t smax(bitcount_t a, bitcount_t b) { return (a > b ? a : b); }
+
+int uECC_verify(const uint8_t *public_key, const uint8_t *message_hash, unsigned hash_size, const uint8_t *signature, uECC_Curve curve) {
+  uECC_word_t        u1[NUM_ECC_WORDS], u2[NUM_ECC_WORDS];
+  uECC_word_t        z[NUM_ECC_WORDS];
+  uECC_word_t        sum[NUM_ECC_WORDS * 2];
+  uECC_word_t        rx[NUM_ECC_WORDS];
+  uECC_word_t        ry[NUM_ECC_WORDS];
+  uECC_word_t        tx[NUM_ECC_WORDS];
+  uECC_word_t        ty[NUM_ECC_WORDS];
+  uECC_word_t        tz[NUM_ECC_WORDS];
+  const uECC_word_t *points[4];
+  const uECC_word_t *point;
+  bitcount_t         num_bits;
+  bitcount_t         i;
+
+  uECC_word_t _public[NUM_ECC_WORDS * 2];
+  uECC_word_t r[NUM_ECC_WORDS], s[NUM_ECC_WORDS];
+  wordcount_t num_words   = curve->num_words;
+  wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
+
+  rx[num_n_words - 1] = 0;
+  r[num_n_words - 1]  = 0;
+  s[num_n_words - 1]  = 0;
+
+  uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
+  uECC_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes, curve->num_bytes);
+  uECC_vli_bytesToNative(r, signature, curve->num_bytes);
+  uECC_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes);
+
+  /* r, s must not be 0. */
+  if (uECC_vli_isZero(r, num_words) || uECC_vli_isZero(s, num_words)) {
+    return 0;
+  }
 
-    /* Calculate u1 and u2. */
-    uECC_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */
-    u1[num_n_words - 1] = 0;
-    bits2int(u1, message_hash, hash_size, curve);
-    uECC_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */
-    uECC_vli_modMult(u2, r, z, curve->n, num_n_words);  /* u2 = r/s */
-
-    /* Calculate sum = G + Q. */
-    uECC_vli_set(sum, _public, num_words);
-    uECC_vli_set(sum + num_words, _public + num_words, num_words);
-    uECC_vli_set(tx, curve->G, num_words);
-    uECC_vli_set(ty, curve->G + num_words, num_words);
-    uECC_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */
-    XYcZ_add(tx, ty, sum, sum + num_words, curve);
-    uECC_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */
-    apply_z(sum, sum + num_words, z, curve);
-
-    /* Use Shamir's trick to calculate u1*G + u2*Q */
-    points[0] = 0;
-    points[1] = curve->G;
-    points[2] = _public;
-    points[3] = sum;
-    num_bits = smax(uECC_vli_numBits(u1, num_n_words),
-                    uECC_vli_numBits(u2, num_n_words));
-
-    point = points[(!!uECC_vli_testBit(u1, num_bits - 1)) |
-                   ((!!uECC_vli_testBit(u2, num_bits - 1)) << 1)];
-    uECC_vli_set(rx, point, num_words);
-    uECC_vli_set(ry, point + num_words, num_words);
-    uECC_vli_clear(z, num_words);
-    z[0] = 1;
-
-    for (i = num_bits - 2; i >= 0; --i) {
-        uECC_word_t index;
-        curve->double_jacobian(rx, ry, z, curve);
-
-        index = (!!uECC_vli_testBit(u1, i)) | ((!!uECC_vli_testBit(u2, i)) << 1);
-        point = points[index];
-        if (point) {
-            uECC_vli_set(tx, point, num_words);
-            uECC_vli_set(ty, point + num_words, num_words);
-            apply_z(tx, ty, z, curve);
-            uECC_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */
-            XYcZ_add(tx, ty, rx, ry, curve);
-            uECC_vli_modMult_fast(z, z, tz, curve);
-        }
+  /* r, s must be < n. */
+  if (uECC_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 || uECC_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) {
+    return 0;
+  }
+
+  /* Calculate u1 and u2. */
+  uECC_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */
+  u1[num_n_words - 1] = 0;
+  bits2int(u1, message_hash, hash_size, curve);
+  uECC_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */
+  uECC_vli_modMult(u2, r, z, curve->n, num_n_words);  /* u2 = r/s */
+
+  /* Calculate sum = G + Q. */
+  uECC_vli_set(sum, _public, num_words);
+  uECC_vli_set(sum + num_words, _public + num_words, num_words);
+  uECC_vli_set(tx, curve->G, num_words);
+  uECC_vli_set(ty, curve->G + num_words, num_words);
+  uECC_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */
+  XYcZ_add(tx, ty, sum, sum + num_words, curve);
+  uECC_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */
+  apply_z(sum, sum + num_words, z, curve);
+
+  /* Use Shamir's trick to calculate u1*G + u2*Q */
+  points[0] = 0;
+  points[1] = curve->G;
+  points[2] = _public;
+  points[3] = sum;
+  num_bits  = smax(uECC_vli_numBits(u1, num_n_words), uECC_vli_numBits(u2, num_n_words));
+
+  point = points[(!!uECC_vli_testBit(u1, num_bits - 1)) | ((!!uECC_vli_testBit(u2, num_bits - 1)) << 1)];
+  uECC_vli_set(rx, point, num_words);
+  uECC_vli_set(ry, point + num_words, num_words);
+  uECC_vli_clear(z, num_words);
+  z[0] = 1;
+
+  for (i = num_bits - 2; i >= 0; --i) {
+    uECC_word_t index;
+    curve->double_jacobian(rx, ry, z, curve);
+
+    index = (!!uECC_vli_testBit(u1, i)) | ((!!uECC_vli_testBit(u2, i)) << 1);
+    point = points[index];
+    if (point) {
+      uECC_vli_set(tx, point, num_words);
+      uECC_vli_set(ty, point + num_words, num_words);
+      apply_z(tx, ty, z, curve);
+      uECC_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */
+      XYcZ_add(tx, ty, rx, ry, curve);
+      uECC_vli_modMult_fast(z, z, tz, curve);
     }
+  }
 
-    uECC_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */
-    apply_z(rx, ry, z, curve);
+  uECC_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */
+  apply_z(rx, ry, z, curve);
 
-    /* v = x1 (mod n) */
-    if (uECC_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) {
-        uECC_vli_sub(rx, rx, curve->n, num_n_words);
-    }
+  /* v = x1 (mod n) */
+  if (uECC_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) {
+    uECC_vli_sub(rx, rx, curve->n, num_n_words);
+  }
 
-    /* Accept only if v == r. */
-    return (int)(uECC_vli_equal(rx, r, num_words) == 0);
+  /* Accept only if v == r. */
+  return (int)(uECC_vli_equal(rx, r, num_words) == 0);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_platform_specific.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_platform_specific.c
index 42dfee828d..261ca747fe 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_platform_specific.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_platform_specific.c
@@ -55,13 +55,11 @@
  *  uECC_platform_specific.c -- Implementation of platform specific functions
  */
 
-#if defined(unix) || defined(__linux__) || defined(__unix__) ||    \
-    defined(__unix) | (defined(__APPLE__) && defined(__MACH__)) || \
-    defined(uECC_POSIX)
+#if defined(unix) || defined(__linux__) || defined(__unix__) || defined(__unix) | (defined(__APPLE__) && defined(__MACH__)) || defined(uECC_POSIX)
 
 /* Some POSIX-like system with /dev/urandom or /dev/random. */
-#include 
 #include 
+#include 
 #include 
 
 #include 
@@ -70,34 +68,33 @@
 #define O_CLOEXEC 0
 #endif
 
-int default_CSPRNG(uint8_t *dest, unsigned int size)
-{
-    /* input sanity check: */
-    if (dest == (uint8_t *)0 || (size <= 0))
-        return 0;
+int default_CSPRNG(uint8_t *dest, unsigned int size) {
+  /* input sanity check: */
+  if (dest == (uint8_t *)0 || (size <= 0))
+    return 0;
 
-    int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
+  int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
+  if (fd == -1) {
+    fd = open("/dev/random", O_RDONLY | O_CLOEXEC);
     if (fd == -1) {
-        fd = open("/dev/random", O_RDONLY | O_CLOEXEC);
-        if (fd == -1) {
-            return 0;
-        }
+      return 0;
     }
+  }
 
-    char *ptr = (char *)dest;
-    size_t left = (size_t)size;
-    while (left > 0) {
-        ssize_t bytes_read = read(fd, ptr, left);
-        if (bytes_read <= 0) { // read failed
-            close(fd);
-            return 0;
-        }
-        left -= bytes_read;
-        ptr += bytes_read;
+  char  *ptr  = (char *)dest;
+  size_t left = (size_t)size;
+  while (left > 0) {
+    ssize_t bytes_read = read(fd, ptr, left);
+    if (bytes_read <= 0) { // read failed
+      close(fd);
+      return 0;
     }
+    left -= bytes_read;
+    ptr += bytes_read;
+  }
 
-    close(fd);
-    return 1;
+  close(fd);
+  return 1;
 }
 
 #endif /* platform */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac.c
index aee8a44e2d..287c323e9d 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac.c
@@ -34,112 +34,92 @@
 #include "constants.h"
 #include "utils.h"
 
-static void rekey(uint8_t *key, const uint8_t *new_key, unsigned int key_size)
-{
-    const uint8_t inner_pad = (uint8_t)0x36;
-    const uint8_t outer_pad = (uint8_t)0x5c;
-    unsigned int i;
-
-    for (i = 0; i < key_size; ++i) {
-        key[i] = inner_pad ^ new_key[i];
-        key[i + TC_SHA256_BLOCK_SIZE] = outer_pad ^ new_key[i];
-    }
-    for (; i < TC_SHA256_BLOCK_SIZE; ++i) {
-        key[i] = inner_pad;
-        key[i + TC_SHA256_BLOCK_SIZE] = outer_pad;
-    }
+static void rekey(uint8_t *key, const uint8_t *new_key, unsigned int key_size) {
+  const uint8_t inner_pad = (uint8_t)0x36;
+  const uint8_t outer_pad = (uint8_t)0x5c;
+  unsigned int  i;
+
+  for (i = 0; i < key_size; ++i) {
+    key[i]                        = inner_pad ^ new_key[i];
+    key[i + TC_SHA256_BLOCK_SIZE] = outer_pad ^ new_key[i];
+  }
+  for (; i < TC_SHA256_BLOCK_SIZE; ++i) {
+    key[i]                        = inner_pad;
+    key[i + TC_SHA256_BLOCK_SIZE] = outer_pad;
+  }
 }
 
-int tc_hmac_set_key(TCHmacState_t ctx, const uint8_t *key,
-                    unsigned int key_size)
-{
-    /* Input sanity check */
-    if (ctx == (TCHmacState_t)0 ||
-        key == (const uint8_t *)0 ||
-        key_size == 0) {
-        return TC_CRYPTO_FAIL;
-    }
-
-    const uint8_t dummy_key[TC_SHA256_BLOCK_SIZE];
-    struct tc_hmac_state_struct dummy_state;
-
-    if (key_size <= TC_SHA256_BLOCK_SIZE) {
-        /*
-		 * The next three calls are dummy calls just to avoid
-		 * certain timing attacks. Without these dummy calls,
-		 * adversaries would be able to learn whether the key_size is
-		 * greater than TC_SHA256_BLOCK_SIZE by measuring the time
-		 * consumed in this process.
-		 */
-        (void)tc_sha256_init(&dummy_state.hash_state);
-        (void)tc_sha256_update(&dummy_state.hash_state,
-                               dummy_key,
-                               key_size);
-        (void)tc_sha256_final(&dummy_state.key[TC_SHA256_DIGEST_SIZE],
-                              &dummy_state.hash_state);
-
-        /* Actual code for when key_size <= TC_SHA256_BLOCK_SIZE: */
-        rekey(ctx->key, key, key_size);
-    } else {
-        (void)tc_sha256_init(&ctx->hash_state);
-        (void)tc_sha256_update(&ctx->hash_state, key, key_size);
-        (void)tc_sha256_final(&ctx->key[TC_SHA256_DIGEST_SIZE],
-                              &ctx->hash_state);
-        rekey(ctx->key,
-              &ctx->key[TC_SHA256_DIGEST_SIZE],
-              TC_SHA256_DIGEST_SIZE);
-    }
-
-    return TC_CRYPTO_SUCCESS;
+int tc_hmac_set_key(TCHmacState_t ctx, const uint8_t *key, unsigned int key_size) {
+  /* Input sanity check */
+  if (ctx == (TCHmacState_t)0 || key == (const uint8_t *)0 || key_size == 0) {
+    return TC_CRYPTO_FAIL;
+  }
+
+  const uint8_t               dummy_key[TC_SHA256_BLOCK_SIZE];
+  struct tc_hmac_state_struct dummy_state;
+
+  if (key_size <= TC_SHA256_BLOCK_SIZE) {
+    /*
+     * The next three calls are dummy calls just to avoid
+     * certain timing attacks. Without these dummy calls,
+     * adversaries would be able to learn whether the key_size is
+     * greater than TC_SHA256_BLOCK_SIZE by measuring the time
+     * consumed in this process.
+     */
+    (void)tc_sha256_init(&dummy_state.hash_state);
+    (void)tc_sha256_update(&dummy_state.hash_state, dummy_key, key_size);
+    (void)tc_sha256_final(&dummy_state.key[TC_SHA256_DIGEST_SIZE], &dummy_state.hash_state);
+
+    /* Actual code for when key_size <= TC_SHA256_BLOCK_SIZE: */
+    rekey(ctx->key, key, key_size);
+  } else {
+    (void)tc_sha256_init(&ctx->hash_state);
+    (void)tc_sha256_update(&ctx->hash_state, key, key_size);
+    (void)tc_sha256_final(&ctx->key[TC_SHA256_DIGEST_SIZE], &ctx->hash_state);
+    rekey(ctx->key, &ctx->key[TC_SHA256_DIGEST_SIZE], TC_SHA256_DIGEST_SIZE);
+  }
+
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_hmac_init(TCHmacState_t ctx)
-{
-    /* input sanity check: */
-    if (ctx == (TCHmacState_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_hmac_init(TCHmacState_t ctx) {
+  /* input sanity check: */
+  if (ctx == (TCHmacState_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    (void)tc_sha256_init(&ctx->hash_state);
-    (void)tc_sha256_update(&ctx->hash_state, ctx->key, TC_SHA256_BLOCK_SIZE);
+  (void)tc_sha256_init(&ctx->hash_state);
+  (void)tc_sha256_update(&ctx->hash_state, ctx->key, TC_SHA256_BLOCK_SIZE);
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_hmac_update(TCHmacState_t ctx,
-                   const void *data,
-                   unsigned int data_length)
-{
-    /* input sanity check: */
-    if (ctx == (TCHmacState_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_hmac_update(TCHmacState_t ctx, const void *data, unsigned int data_length) {
+  /* input sanity check: */
+  if (ctx == (TCHmacState_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    (void)tc_sha256_update(&ctx->hash_state, data, data_length);
+  (void)tc_sha256_update(&ctx->hash_state, data, data_length);
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_hmac_final(uint8_t *tag, unsigned int taglen, TCHmacState_t ctx)
-{
-    /* input sanity check: */
-    if (tag == (uint8_t *)0 ||
-        taglen != TC_SHA256_DIGEST_SIZE ||
-        ctx == (TCHmacState_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_hmac_final(uint8_t *tag, unsigned int taglen, TCHmacState_t ctx) {
+  /* input sanity check: */
+  if (tag == (uint8_t *)0 || taglen != TC_SHA256_DIGEST_SIZE || ctx == (TCHmacState_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    (void)tc_sha256_final(tag, &ctx->hash_state);
+  (void)tc_sha256_final(tag, &ctx->hash_state);
 
-    (void)tc_sha256_init(&ctx->hash_state);
-    (void)tc_sha256_update(&ctx->hash_state,
-                           &ctx->key[TC_SHA256_BLOCK_SIZE],
-                           TC_SHA256_BLOCK_SIZE);
-    (void)tc_sha256_update(&ctx->hash_state, tag, TC_SHA256_DIGEST_SIZE);
-    (void)tc_sha256_final(tag, &ctx->hash_state);
+  (void)tc_sha256_init(&ctx->hash_state);
+  (void)tc_sha256_update(&ctx->hash_state, &ctx->key[TC_SHA256_BLOCK_SIZE], TC_SHA256_BLOCK_SIZE);
+  (void)tc_sha256_update(&ctx->hash_state, tag, TC_SHA256_DIGEST_SIZE);
+  (void)tc_sha256_final(tag, &ctx->hash_state);
 
-    /* destroy the current state */
-    _set(ctx, 0, sizeof(*ctx));
+  /* destroy the current state */
+  _set(ctx, 0, sizeof(*ctx));
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac_prng.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac_prng.c
index 8ef3c0c2b1..3fe120442b 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac_prng.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac_prng.c
@@ -31,8 +31,8 @@
  */
 
 #include "hmac_prng.h"
-#include "hmac.h"
 #include "constants.h"
+#include "hmac.h"
 #include "utils.h"
 
 /*
@@ -75,156 +75,133 @@ static const unsigned int MAX_OUT = (1 << 19);
 /*
  * Assumes: prng != NULL
  */
-static void update(TCHmacPrng_t prng, const uint8_t *data, unsigned int datalen, const uint8_t *additional_data, unsigned int additional_datalen)
-{
-    const uint8_t separator0 = 0x00;
-    const uint8_t separator1 = 0x01;
+static void update(TCHmacPrng_t prng, const uint8_t *data, unsigned int datalen, const uint8_t *additional_data, unsigned int additional_datalen) {
+  const uint8_t separator0 = 0x00;
+  const uint8_t separator1 = 0x01;
 
-    /* configure the new prng key into the prng's instance of hmac */
-    tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
+  /* configure the new prng key into the prng's instance of hmac */
+  tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
 
-    /* use current state, e and separator 0 to compute a new prng key: */
-    (void)tc_hmac_init(&prng->h);
-    (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
-    (void)tc_hmac_update(&prng->h, &separator0, sizeof(separator0));
+  /* use current state, e and separator 0 to compute a new prng key: */
+  (void)tc_hmac_init(&prng->h);
+  (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
+  (void)tc_hmac_update(&prng->h, &separator0, sizeof(separator0));
 
-    if (data && datalen)
-        (void)tc_hmac_update(&prng->h, data, datalen);
-    if (additional_data && additional_datalen)
-        (void)tc_hmac_update(&prng->h, additional_data, additional_datalen);
+  if (data && datalen)
+    (void)tc_hmac_update(&prng->h, data, datalen);
+  if (additional_data && additional_datalen)
+    (void)tc_hmac_update(&prng->h, additional_data, additional_datalen);
 
-    (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h);
+  (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h);
 
-    /* configure the new prng key into the prng's instance of hmac */
-    (void)tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
+  /* configure the new prng key into the prng's instance of hmac */
+  (void)tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
 
-    /* use the new key to compute a new state variable v */
-    (void)tc_hmac_init(&prng->h);
-    (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
-    (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h);
+  /* use the new key to compute a new state variable v */
+  (void)tc_hmac_init(&prng->h);
+  (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
+  (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h);
 
-    if (data == 0 || datalen == 0)
-        return;
+  if (data == 0 || datalen == 0)
+    return;
 
-    /* configure the new prng key into the prng's instance of hmac */
-    tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
+  /* configure the new prng key into the prng's instance of hmac */
+  tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
 
-    /* use current state, e and separator 1 to compute a new prng key: */
-    (void)tc_hmac_init(&prng->h);
-    (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
-    (void)tc_hmac_update(&prng->h, &separator1, sizeof(separator1));
-    (void)tc_hmac_update(&prng->h, data, datalen);
-    if (additional_data && additional_datalen)
-        (void)tc_hmac_update(&prng->h, additional_data, additional_datalen);
-    (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h);
+  /* use current state, e and separator 1 to compute a new prng key: */
+  (void)tc_hmac_init(&prng->h);
+  (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
+  (void)tc_hmac_update(&prng->h, &separator1, sizeof(separator1));
+  (void)tc_hmac_update(&prng->h, data, datalen);
+  if (additional_data && additional_datalen)
+    (void)tc_hmac_update(&prng->h, additional_data, additional_datalen);
+  (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h);
 
-    /* configure the new prng key into the prng's instance of hmac */
-    (void)tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
+  /* configure the new prng key into the prng's instance of hmac */
+  (void)tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
 
-    /* use the new key to compute a new state variable v */
-    (void)tc_hmac_init(&prng->h);
-    (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
-    (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h);
+  /* use the new key to compute a new state variable v */
+  (void)tc_hmac_init(&prng->h);
+  (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
+  (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h);
 }
 
-int tc_hmac_prng_init(TCHmacPrng_t prng,
-                      const uint8_t *personalization,
-                      unsigned int plen)
-{
-    /* input sanity check: */
-    if (prng == (TCHmacPrng_t)0 ||
-        personalization == (uint8_t *)0 ||
-        plen > MAX_PLEN) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_hmac_prng_init(TCHmacPrng_t prng, const uint8_t *personalization, unsigned int plen) {
+  /* input sanity check: */
+  if (prng == (TCHmacPrng_t)0 || personalization == (uint8_t *)0 || plen > MAX_PLEN) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    /* put the generator into a known state: */
-    _set(prng->key, 0x00, sizeof(prng->key));
-    _set(prng->v, 0x01, sizeof(prng->v));
+  /* put the generator into a known state: */
+  _set(prng->key, 0x00, sizeof(prng->key));
+  _set(prng->v, 0x01, sizeof(prng->v));
 
-    update(prng, personalization, plen, 0, 0);
+  update(prng, personalization, plen, 0, 0);
 
-    /* force a reseed before allowing tc_hmac_prng_generate to succeed: */
-    prng->countdown = 0;
+  /* force a reseed before allowing tc_hmac_prng_generate to succeed: */
+  prng->countdown = 0;
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_hmac_prng_reseed(TCHmacPrng_t prng,
-                        const uint8_t *seed,
-                        unsigned int seedlen,
-                        const uint8_t *additional_input,
-                        unsigned int additionallen)
-{
-    /* input sanity check: */
-    if (prng == (TCHmacPrng_t)0 ||
-        seed == (const uint8_t *)0 ||
-        seedlen < MIN_SLEN ||
-        seedlen > MAX_SLEN) {
-        return TC_CRYPTO_FAIL;
-    }
-
-    if (additional_input != (const uint8_t *)0) {
-        /*
-		 * Abort if additional_input is provided but has inappropriate
-		 * length
-		 */
-        if (additionallen == 0 ||
-            additionallen > MAX_ALEN) {
-            return TC_CRYPTO_FAIL;
-        } else {
-            /* call update for the seed and additional_input */
-            update(prng, seed, seedlen, additional_input, additionallen);
-        }
+int tc_hmac_prng_reseed(TCHmacPrng_t prng, const uint8_t *seed, unsigned int seedlen, const uint8_t *additional_input, unsigned int additionallen) {
+  /* input sanity check: */
+  if (prng == (TCHmacPrng_t)0 || seed == (const uint8_t *)0 || seedlen < MIN_SLEN || seedlen > MAX_SLEN) {
+    return TC_CRYPTO_FAIL;
+  }
+
+  if (additional_input != (const uint8_t *)0) {
+    /*
+     * Abort if additional_input is provided but has inappropriate
+     * length
+     */
+    if (additionallen == 0 || additionallen > MAX_ALEN) {
+      return TC_CRYPTO_FAIL;
     } else {
-        /* call update only for the seed */
-        update(prng, seed, seedlen, 0, 0);
+      /* call update for the seed and additional_input */
+      update(prng, seed, seedlen, additional_input, additionallen);
     }
+  } else {
+    /* call update only for the seed */
+    update(prng, seed, seedlen, 0, 0);
+  }
 
-    /* ... and enable hmac_prng_generate */
-    prng->countdown = MAX_GENS;
+  /* ... and enable hmac_prng_generate */
+  prng->countdown = MAX_GENS;
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_hmac_prng_generate(uint8_t *out, unsigned int outlen, TCHmacPrng_t prng)
-{
-    unsigned int bufferlen;
-
-    /* input sanity check: */
-    if (out == (uint8_t *)0 ||
-        prng == (TCHmacPrng_t)0 ||
-        outlen == 0 ||
-        outlen > MAX_OUT) {
-        return TC_CRYPTO_FAIL;
-    } else if (prng->countdown == 0) {
-        return TC_HMAC_PRNG_RESEED_REQ;
-    }
+int tc_hmac_prng_generate(uint8_t *out, unsigned int outlen, TCHmacPrng_t prng) {
+  unsigned int bufferlen;
 
-    prng->countdown--;
+  /* input sanity check: */
+  if (out == (uint8_t *)0 || prng == (TCHmacPrng_t)0 || outlen == 0 || outlen > MAX_OUT) {
+    return TC_CRYPTO_FAIL;
+  } else if (prng->countdown == 0) {
+    return TC_HMAC_PRNG_RESEED_REQ;
+  }
 
-    while (outlen != 0) {
-        /* configure the new prng key into the prng's instance of hmac */
-        tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
+  prng->countdown--;
 
-        /* operate HMAC in OFB mode to create "random" outputs */
-        (void)tc_hmac_init(&prng->h);
-        (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
-        (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h);
+  while (outlen != 0) {
+    /* configure the new prng key into the prng's instance of hmac */
+    tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
 
-        bufferlen = (TC_SHA256_DIGEST_SIZE > outlen) ?
-                        outlen :
-                        TC_SHA256_DIGEST_SIZE;
-        (void)_copy(out, bufferlen, prng->v, bufferlen);
+    /* operate HMAC in OFB mode to create "random" outputs */
+    (void)tc_hmac_init(&prng->h);
+    (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
+    (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h);
 
-        out += bufferlen;
-        outlen = (outlen > TC_SHA256_DIGEST_SIZE) ?
-                     (outlen - TC_SHA256_DIGEST_SIZE) :
-                     0;
-    }
+    bufferlen = (TC_SHA256_DIGEST_SIZE > outlen) ? outlen : TC_SHA256_DIGEST_SIZE;
+    (void)_copy(out, bufferlen, prng->v, bufferlen);
+
+    out += bufferlen;
+    outlen = (outlen > TC_SHA256_DIGEST_SIZE) ? (outlen - TC_SHA256_DIGEST_SIZE) : 0;
+  }
 
-    /* block future PRNG compromises from revealing past state */
-    update(prng, 0, 0, 0, 0);
+  /* block future PRNG compromises from revealing past state */
+  update(prng, 0, 0, 0, 0);
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/sha256.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/sha256.c
index 57952104c7..1ee9bdf12a 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/sha256.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/sha256.c
@@ -36,103 +36,96 @@
 
 static void compress(unsigned int *iv, const uint8_t *data);
 
-int tc_sha256_init(TCSha256State_t s)
-{
-    /* input sanity check: */
-    if (s == (TCSha256State_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
-
-    /*
-	 * Setting the initial state values.
-	 * These values correspond to the first 32 bits of the fractional parts
-	 * of the square roots of the first 8 primes: 2, 3, 5, 7, 11, 13, 17
-	 * and 19.
-	 */
-    _set((uint8_t *)s, 0x00, sizeof(*s));
-    s->iv[0] = 0x6a09e667;
-    s->iv[1] = 0xbb67ae85;
-    s->iv[2] = 0x3c6ef372;
-    s->iv[3] = 0xa54ff53a;
-    s->iv[4] = 0x510e527f;
-    s->iv[5] = 0x9b05688c;
-    s->iv[6] = 0x1f83d9ab;
-    s->iv[7] = 0x5be0cd19;
-
-    return TC_CRYPTO_SUCCESS;
+int tc_sha256_init(TCSha256State_t s) {
+  /* input sanity check: */
+  if (s == (TCSha256State_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
+
+  /*
+   * Setting the initial state values.
+   * These values correspond to the first 32 bits of the fractional parts
+   * of the square roots of the first 8 primes: 2, 3, 5, 7, 11, 13, 17
+   * and 19.
+   */
+  _set((uint8_t *)s, 0x00, sizeof(*s));
+  s->iv[0] = 0x6a09e667;
+  s->iv[1] = 0xbb67ae85;
+  s->iv[2] = 0x3c6ef372;
+  s->iv[3] = 0xa54ff53a;
+  s->iv[4] = 0x510e527f;
+  s->iv[5] = 0x9b05688c;
+  s->iv[6] = 0x1f83d9ab;
+  s->iv[7] = 0x5be0cd19;
+
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_sha256_update(TCSha256State_t s, const uint8_t *data, size_t datalen)
-{
-    /* input sanity check: */
-    if (s == (TCSha256State_t)0 ||
-        data == (void *)0) {
-        return TC_CRYPTO_FAIL;
-    } else if (datalen == 0) {
-        return TC_CRYPTO_SUCCESS;
-    }
-
-    while (datalen-- > 0) {
-        s->leftover[s->leftover_offset++] = *(data++);
-        if (s->leftover_offset >= TC_SHA256_BLOCK_SIZE) {
-            compress(s->iv, s->leftover);
-            s->leftover_offset = 0;
-            s->bits_hashed += (TC_SHA256_BLOCK_SIZE << 3);
-        }
+int tc_sha256_update(TCSha256State_t s, const uint8_t *data, size_t datalen) {
+  /* input sanity check: */
+  if (s == (TCSha256State_t)0 || data == (void *)0) {
+    return TC_CRYPTO_FAIL;
+  } else if (datalen == 0) {
+    return TC_CRYPTO_SUCCESS;
+  }
+
+  while (datalen-- > 0) {
+    s->leftover[s->leftover_offset++] = *(data++);
+    if (s->leftover_offset >= TC_SHA256_BLOCK_SIZE) {
+      compress(s->iv, s->leftover);
+      s->leftover_offset = 0;
+      s->bits_hashed += (TC_SHA256_BLOCK_SIZE << 3);
     }
+  }
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_sha256_final(uint8_t *digest, TCSha256State_t s)
-{
-    unsigned int i;
+int tc_sha256_final(uint8_t *digest, TCSha256State_t s) {
+  unsigned int i;
 
-    /* input sanity check: */
-    if (digest == (uint8_t *)0 ||
-        s == (TCSha256State_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+  /* input sanity check: */
+  if (digest == (uint8_t *)0 || s == (TCSha256State_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    s->bits_hashed += (s->leftover_offset << 3);
-
-    s->leftover[s->leftover_offset++] = 0x80; /* always room for one byte */
-    if (s->leftover_offset > (sizeof(s->leftover) - 8)) {
-        /* there is not room for all the padding in this block */
-        _set(s->leftover + s->leftover_offset, 0x00,
-             sizeof(s->leftover) - s->leftover_offset);
-        compress(s->iv, s->leftover);
-        s->leftover_offset = 0;
-    }
+  s->bits_hashed += (s->leftover_offset << 3);
 
-    /* add the padding and the length in big-Endian format */
-    _set(s->leftover + s->leftover_offset, 0x00,
-         sizeof(s->leftover) - 8 - s->leftover_offset);
-    s->leftover[sizeof(s->leftover) - 1] = (uint8_t)(s->bits_hashed);
-    s->leftover[sizeof(s->leftover) - 2] = (uint8_t)(s->bits_hashed >> 8);
-    s->leftover[sizeof(s->leftover) - 3] = (uint8_t)(s->bits_hashed >> 16);
-    s->leftover[sizeof(s->leftover) - 4] = (uint8_t)(s->bits_hashed >> 24);
-    s->leftover[sizeof(s->leftover) - 5] = (uint8_t)(s->bits_hashed >> 32);
-    s->leftover[sizeof(s->leftover) - 6] = (uint8_t)(s->bits_hashed >> 40);
-    s->leftover[sizeof(s->leftover) - 7] = (uint8_t)(s->bits_hashed >> 48);
-    s->leftover[sizeof(s->leftover) - 8] = (uint8_t)(s->bits_hashed >> 56);
-
-    /* hash the padding and length */
+  s->leftover[s->leftover_offset++] = 0x80; /* always room for one byte */
+  if (s->leftover_offset > (sizeof(s->leftover) - 8)) {
+    /* there is not room for all the padding in this block */
+    _set(s->leftover + s->leftover_offset, 0x00, sizeof(s->leftover) - s->leftover_offset);
     compress(s->iv, s->leftover);
-
-    /* copy the iv out to digest */
-    for (i = 0; i < TC_SHA256_STATE_BLOCKS; ++i) {
-        unsigned int t = *((unsigned int *)&s->iv[i]);
-        *digest++ = (uint8_t)(t >> 24);
-        *digest++ = (uint8_t)(t >> 16);
-        *digest++ = (uint8_t)(t >> 8);
-        *digest++ = (uint8_t)(t);
-    }
-
-    /* destroy the current state */
-    _set(s, 0, sizeof(*s));
-
-    return TC_CRYPTO_SUCCESS;
+    s->leftover_offset = 0;
+  }
+
+  /* add the padding and the length in big-Endian format */
+  _set(s->leftover + s->leftover_offset, 0x00, sizeof(s->leftover) - 8 - s->leftover_offset);
+  s->leftover[sizeof(s->leftover) - 1] = (uint8_t)(s->bits_hashed);
+  s->leftover[sizeof(s->leftover) - 2] = (uint8_t)(s->bits_hashed >> 8);
+  s->leftover[sizeof(s->leftover) - 3] = (uint8_t)(s->bits_hashed >> 16);
+  s->leftover[sizeof(s->leftover) - 4] = (uint8_t)(s->bits_hashed >> 24);
+  s->leftover[sizeof(s->leftover) - 5] = (uint8_t)(s->bits_hashed >> 32);
+  s->leftover[sizeof(s->leftover) - 6] = (uint8_t)(s->bits_hashed >> 40);
+  s->leftover[sizeof(s->leftover) - 7] = (uint8_t)(s->bits_hashed >> 48);
+  s->leftover[sizeof(s->leftover) - 8] = (uint8_t)(s->bits_hashed >> 56);
+
+  /* hash the padding and length */
+  compress(s->iv, s->leftover);
+
+  /* copy the iv out to digest */
+  for (i = 0; i < TC_SHA256_STATE_BLOCKS; ++i) {
+    unsigned int t = *((unsigned int *)&s->iv[i]);
+    *digest++      = (uint8_t)(t >> 24);
+    *digest++      = (uint8_t)(t >> 16);
+    *digest++      = (uint8_t)(t >> 8);
+    *digest++      = (uint8_t)(t);
+  }
+
+  /* destroy the current state */
+  _set(s, 0, sizeof(*s));
+
+  return TC_CRYPTO_SUCCESS;
 }
 
 /*
@@ -140,24 +133,13 @@ int tc_sha256_final(uint8_t *digest, TCSha256State_t s)
  * These values correspond to the first 32 bits of the fractional parts of the
  * cube roots of the first 64 primes between 2 and 311.
  */
-static const unsigned int k256[64] = {
-    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
-    0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
-    0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
-    0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
-    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
-    0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
-    0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
-    0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
-    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
-    0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
-    0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
-};
-
-static inline unsigned int ROTR(unsigned int a, unsigned int n)
-{
-    return (((a) >> n) | ((a) << (32 - n)));
-}
+static const unsigned int k256[64]
+    = {0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+       0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
+       0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+       0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
+
+static inline unsigned int ROTR(unsigned int a, unsigned int n) { return (((a) >> n) | ((a) << (32 - n))); }
 
 #define Sigma0(a) (ROTR((a), 2) ^ ROTR((a), 13) ^ ROTR((a), 22))
 #define Sigma1(a) (ROTR((a), 6) ^ ROTR((a), 11) ^ ROTR((a), 25))
@@ -167,75 +149,73 @@ static inline unsigned int ROTR(unsigned int a, unsigned int n)
 #define Ch(a, b, c)  (((a) & (b)) ^ ((~(a)) & (c)))
 #define Maj(a, b, c) (((a) & (b)) ^ ((a) & (c)) ^ ((b) & (c)))
 
-static inline unsigned int BigEndian(const uint8_t **c)
-{
-    unsigned int n = 0;
+static inline unsigned int BigEndian(const uint8_t **c) {
+  unsigned int n = 0;
 
-    n = (((unsigned int)(*((*c)++))) << 24);
-    n |= ((unsigned int)(*((*c)++)) << 16);
-    n |= ((unsigned int)(*((*c)++)) << 8);
-    n |= ((unsigned int)(*((*c)++)));
-    return n;
+  n = (((unsigned int)(*((*c)++))) << 24);
+  n |= ((unsigned int)(*((*c)++)) << 16);
+  n |= ((unsigned int)(*((*c)++)) << 8);
+  n |= ((unsigned int)(*((*c)++)));
+  return n;
 }
 
-static void compress(unsigned int *iv, const uint8_t *data)
-{
-    unsigned int a, b, c, d, e, f, g, h;
-    unsigned int s0, s1;
-    unsigned int t1, t2;
-    unsigned int work_space[16];
-    unsigned int n;
-    unsigned int i;
-
-    a = iv[0];
-    b = iv[1];
-    c = iv[2];
-    d = iv[3];
-    e = iv[4];
-    f = iv[5];
-    g = iv[6];
-    h = iv[7];
-
-    for (i = 0; i < 16; ++i) {
-        n = BigEndian(&data);
-        t1 = work_space[i] = n;
-        t1 += h + Sigma1(e) + Ch(e, f, g) + k256[i];
-        t2 = Sigma0(a) + Maj(a, b, c);
-        h = g;
-        g = f;
-        f = e;
-        e = d + t1;
-        d = c;
-        c = b;
-        b = a;
-        a = t1 + t2;
-    }
-
-    for (; i < 64; ++i) {
-        s0 = work_space[(i + 1) & 0x0f];
-        s0 = sigma0(s0);
-        s1 = work_space[(i + 14) & 0x0f];
-        s1 = sigma1(s1);
-
-        t1 = work_space[i & 0xf] += s0 + s1 + work_space[(i + 9) & 0xf];
-        t1 += h + Sigma1(e) + Ch(e, f, g) + k256[i];
-        t2 = Sigma0(a) + Maj(a, b, c);
-        h = g;
-        g = f;
-        f = e;
-        e = d + t1;
-        d = c;
-        c = b;
-        b = a;
-        a = t1 + t2;
-    }
-
-    iv[0] += a;
-    iv[1] += b;
-    iv[2] += c;
-    iv[3] += d;
-    iv[4] += e;
-    iv[5] += f;
-    iv[6] += g;
-    iv[7] += h;
+static void compress(unsigned int *iv, const uint8_t *data) {
+  unsigned int a, b, c, d, e, f, g, h;
+  unsigned int s0, s1;
+  unsigned int t1, t2;
+  unsigned int work_space[16];
+  unsigned int n;
+  unsigned int i;
+
+  a = iv[0];
+  b = iv[1];
+  c = iv[2];
+  d = iv[3];
+  e = iv[4];
+  f = iv[5];
+  g = iv[6];
+  h = iv[7];
+
+  for (i = 0; i < 16; ++i) {
+    n  = BigEndian(&data);
+    t1 = work_space[i] = n;
+    t1 += h + Sigma1(e) + Ch(e, f, g) + k256[i];
+    t2 = Sigma0(a) + Maj(a, b, c);
+    h  = g;
+    g  = f;
+    f  = e;
+    e  = d + t1;
+    d  = c;
+    c  = b;
+    b  = a;
+    a  = t1 + t2;
+  }
+
+  for (; i < 64; ++i) {
+    s0 = work_space[(i + 1) & 0x0f];
+    s0 = sigma0(s0);
+    s1 = work_space[(i + 14) & 0x0f];
+    s1 = sigma1(s1);
+
+    t1 = work_space[i & 0xf] += s0 + s1 + work_space[(i + 9) & 0xf];
+    t1 += h + Sigma1(e) + Ch(e, f, g) + k256[i];
+    t2 = Sigma0(a) + Maj(a, b, c);
+    h  = g;
+    g  = f;
+    f  = e;
+    e  = d + t1;
+    d  = c;
+    c  = b;
+    b  = a;
+    a  = t1 + t2;
+  }
+
+  iv[0] += a;
+  iv[1] += b;
+  iv[2] += c;
+  iv[3] += d;
+  iv[4] += e;
+  iv[5] += f;
+  iv[6] += g;
+  iv[7] += h;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/utils.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/utils.c
index 137702a868..2cef6b05b5 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/utils.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/utils.c
@@ -37,38 +37,29 @@
 
 #define MASK_TWENTY_SEVEN 0x1b
 
-unsigned int _copy(uint8_t *to, unsigned int to_len,
-                   const uint8_t *from, unsigned int from_len)
-{
-    if (from_len <= to_len) {
-        (void)memcpy(to, from, from_len);
-        return from_len;
-    } else {
-        return TC_CRYPTO_FAIL;
-    }
+unsigned int _copy(uint8_t *to, unsigned int to_len, const uint8_t *from, unsigned int from_len) {
+  if (from_len <= to_len) {
+    (void)memcpy(to, from, from_len);
+    return from_len;
+  } else {
+    return TC_CRYPTO_FAIL;
+  }
 }
 
-void _set(void *to, uint8_t val, unsigned int len)
-{
-    (void)memset(to, val, len);
-}
+void _set(void *to, uint8_t val, unsigned int len) { (void)memset(to, val, len); }
 
 /*
  * Doubles the value of a byte for values up to 127.
  */
-uint8_t _double_byte(uint8_t a)
-{
-    return ((a << 1) ^ ((a >> 7) * MASK_TWENTY_SEVEN));
-}
+uint8_t _double_byte(uint8_t a) { return ((a << 1) ^ ((a >> 7) * MASK_TWENTY_SEVEN)); }
 
-int _compare(const uint8_t *a, const uint8_t *b, size_t size)
-{
-    const uint8_t *tempa = a;
-    const uint8_t *tempb = b;
-    uint8_t result = 0;
+int _compare(const uint8_t *a, const uint8_t *b, size_t size) {
+  const uint8_t *tempa  = a;
+  const uint8_t *tempb  = b;
+  uint8_t        result = 0;
 
-    for (unsigned int i = 0; i < size; i++) {
-        result |= tempa[i] ^ tempb[i];
-    }
-    return result;
+  for (unsigned int i = 0; i < size; i++) {
+    result |= tempa[i] ^ tempb[i];
+  }
+  return result;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/utils.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/utils.c
index bde3392652..76071e3f39 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/utils.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/utils.c
@@ -1,132 +1,125 @@
 /*****************************************************************************************
-*
-* @file utils.c
-*
-* @brief entry
-*
-* Copyright (C) Bouffalo Lab 2019
-*
-* History: 2019-11 crealted by Lanlan Gong @ Shanghai
-*
-*****************************************************************************************/
-#include 
+ *
+ * @file utils.c
+ *
+ * @brief entry
+ *
+ * Copyright (C) Bouffalo Lab 2019
+ *
+ * History: 2019-11 crealted by Lanlan Gong @ Shanghai
+ *
+ *****************************************************************************************/
 #include 
+#include 
 #include 
 
-void reverse_bytearray(uint8_t *src, uint8_t *result, int array_size)
-{
-    for (int i = 0; i < array_size; i++) {
-        result[array_size - i - 1] = src[i];
-    }
+void reverse_bytearray(uint8_t *src, uint8_t *result, int array_size) {
+  for (int i = 0; i < array_size; i++) {
+    result[array_size - i - 1] = src[i];
+  }
 }
 
-unsigned int find_msb_set(uint32_t data)
-{
-    uint32_t count = 0;
-    uint32_t mask = 0x80000000;
+unsigned int find_msb_set(uint32_t data) {
+  uint32_t count = 0;
+  uint32_t mask  = 0x80000000;
 
-    if (!data) {
-        return 0;
-    }
-    while ((data & mask) == 0) {
-        count += 1u;
-        mask = mask >> 1u;
-    }
-    return (32 - count);
+  if (!data) {
+    return 0;
+  }
+  while ((data & mask) == 0) {
+    count += 1u;
+    mask = mask >> 1u;
+  }
+  return (32 - count);
 }
 
-unsigned int find_lsb_set(uint32_t data)
-{
-    uint32_t count = 0;
-    uint32_t mask = 0x00000001;
+unsigned int find_lsb_set(uint32_t data) {
+  uint32_t count = 0;
+  uint32_t mask  = 0x00000001;
 
-    if (!data) {
-        return 0;
-    }
-    while ((data & mask) == 0) {
-        count += 1u;
-        mask = mask << 1u;
-    }
-    return (1 + count);
+  if (!data) {
+    return 0;
+  }
+  while ((data & mask) == 0) {
+    count += 1u;
+    mask = mask << 1u;
+  }
+  return (1 + count);
 }
 
-int char2hex(char c, uint8_t *x)
-{
-    if (c >= '0' && c <= '9') {
-        *x = c - '0';
-    } else if (c >= 'a' && c <= 'f') {
-        *x = c - 'a' + 10;
-    } else if (c >= 'A' && c <= 'F') {
-        *x = c - 'A' + 10;
-    } else {
-        return -1;
-    }
-
-    return 0;
+int char2hex(char c, uint8_t *x) {
+  if (c >= '0' && c <= '9') {
+    *x = c - '0';
+  } else if (c >= 'a' && c <= 'f') {
+    *x = c - 'a' + 10;
+  } else if (c >= 'A' && c <= 'F') {
+    *x = c - 'A' + 10;
+  } else {
+    return -1;
+  }
+
+  return 0;
 }
 
-int hex2char(uint8_t x, char *c)
-{
-    if (x <= 9) {
-        *c = x + '0';
-    } else if (x <= 15) {
-        *c = x - 10 + 'a';
-    } else {
-        return -1;
-    }
+int hex2char(uint8_t x, char *c) {
+  if (x <= 9) {
+    *c = x + '0';
+  } else if (x <= 15) {
+    *c = x - 10 + 'a';
+  } else {
+    return -1;
+  }
 
-    return 0;
+  return 0;
 }
 
-size_t bin2hex(const uint8_t *buf, size_t buflen, char *hex, size_t hexlen)
-{
-    if ((hexlen + 1) < buflen * 2) {
-        return 0;
-    }
+size_t bin2hex(const uint8_t *buf, size_t buflen, char *hex, size_t hexlen) {
+  if ((hexlen + 1) < buflen * 2) {
+    return 0;
+  }
 
-    for (size_t i = 0; i < buflen; i++) {
-        if (hex2char(buf[i] >> 4, &hex[2 * i]) < 0) {
-            return 0;
-        }
-        if (hex2char(buf[i] & 0xf, &hex[2 * i + 1]) < 0) {
-            return 0;
-        }
+  for (size_t i = 0; i < buflen; i++) {
+    if (hex2char(buf[i] >> 4, &hex[2 * i]) < 0) {
+      return 0;
+    }
+    if (hex2char(buf[i] & 0xf, &hex[2 * i + 1]) < 0) {
+      return 0;
     }
+  }
 
-    hex[2 * buflen] = '\0';
-    return 2 * buflen;
+  hex[2 * buflen] = '\0';
+  return 2 * buflen;
 }
 
-size_t hex2bin(const char *hex, size_t hexlen, uint8_t *buf, size_t buflen)
-{
-    uint8_t dec;
+size_t hex2bin(const char *hex, size_t hexlen, uint8_t *buf, size_t buflen) {
+  uint8_t dec;
 
-    if (buflen < hexlen / 2 + hexlen % 2) {
-        return 0;
-    }
+  if (buflen < hexlen / 2 + hexlen % 2) {
+    return 0;
+  }
 
-    /* if hexlen is uneven, insert leading zero nibble */
-    if (hexlen % 2) {
-        if (char2hex(hex[0], &dec) < 0) {
-            return 0;
-        }
-        buf[0] = dec;
-        hex++;
-        buf++;
+  /* if hexlen is uneven, insert leading zero nibble */
+  if (hexlen % 2) {
+    if (char2hex(hex[0], &dec) < 0) {
+      return 0;
+    }
+    buf[0] = dec;
+    hex++;
+    buf++;
+  }
+
+  /* regular hex conversion */
+  for (size_t i = 0; i < hexlen / 2; i++) {
+    if (char2hex(hex[2 * i], &dec) < 0) {
+      return 0;
     }
+    buf[i] = dec << 4;
 
-    /* regular hex conversion */
-    for (size_t i = 0; i < hexlen / 2; i++) {
-        if (char2hex(hex[2 * i], &dec) < 0) {
-            return 0;
-        }
-        buf[i] = dec << 4;
-
-        if (char2hex(hex[2 * i + 1], &dec) < 0) {
-            return 0;
-        }
-        buf[i] += dec;
+    if (char2hex(hex[2 * i + 1], &dec) < 0) {
+      return 0;
     }
+    buf[i] += dec;
+  }
 
-    return hexlen / 2 + hexlen % 2;
+  return hexlen / 2 + hexlen % 2;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/work_q.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/work_q.c
index f8f72ad6f3..4c78637e5b 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/work_q.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/work_q.c
@@ -11,9 +11,9 @@
  * Workqueue support functions
  */
 
-#include 
-#include 
 #include "errno.h"
+#include 
+#include 
 
 struct k_thread work_q_thread;
 #if !defined(BFLB_BLE)
@@ -21,328 +21,294 @@ static BT_STACK_NOINIT(work_q_stack, CONFIG_BT_WORK_QUEUE_STACK_SIZE);
 #endif
 struct k_work_q g_work_queue_main;
 
-static void k_work_submit_to_queue(struct k_work_q *work_q,
-                                   struct k_work *work)
-{
-    if (!atomic_test_and_set_bit(work->flags, K_WORK_STATE_PENDING)) {
-        k_fifo_put(&work_q->fifo, work);
-    }
+static void k_work_submit_to_queue(struct k_work_q *work_q, struct k_work *work) {
+  if (!atomic_test_and_set_bit(work->flags, K_WORK_STATE_PENDING)) {
+    k_fifo_put(&work_q->fifo, work);
+  }
 }
 
 #if defined(BFLB_BLE)
-static void work_queue_main(void *p1)
-{
-    struct k_work *work;
-    UNUSED(p1);
-
-    while (1) {
-        work = k_fifo_get(&g_work_queue_main.fifo, K_FOREVER);
+static void work_queue_main(void *p1) {
+  struct k_work *work;
+  UNUSED(p1);
 
-        if (atomic_test_and_clear_bit(work->flags, K_WORK_STATE_PENDING)) {
-            work->handler(work);
-        }
+  while (1) {
+    work = k_fifo_get(&g_work_queue_main.fifo, K_FOREVER);
 
-        k_yield();
+    if (atomic_test_and_clear_bit(work->flags, K_WORK_STATE_PENDING)) {
+      work->handler(work);
     }
+
+    k_yield();
+  }
 }
 
-int k_work_q_start(void)
-{
-    k_fifo_init(&g_work_queue_main.fifo, 20);
-    return k_thread_create(&work_q_thread, "work_q_thread",
-                           CONFIG_BT_WORK_QUEUE_STACK_SIZE,
-                           work_queue_main, CONFIG_BT_WORK_QUEUE_PRIO);
+int k_work_q_start(void) {
+  k_fifo_init(&g_work_queue_main.fifo, 20);
+  return k_thread_create(&work_q_thread, "work_q_thread", CONFIG_BT_WORK_QUEUE_STACK_SIZE, work_queue_main, CONFIG_BT_WORK_QUEUE_PRIO);
 }
 
-int k_work_init(struct k_work *work, k_work_handler_t handler)
-{
-    ASSERT(work, "work is NULL");
+int k_work_init(struct k_work *work, k_work_handler_t handler) {
+  ASSERT(work, "work is NULL");
 
-    atomic_clear(work->flags);
-    work->handler = handler;
-    return 0;
+  atomic_clear(work->flags);
+  work->handler = handler;
+  return 0;
 }
 
-void k_work_submit(struct k_work *work)
-{
-    k_work_submit_to_queue(&g_work_queue_main, work);
-}
+void k_work_submit(struct k_work *work) { k_work_submit_to_queue(&g_work_queue_main, work); }
 
-static void work_timeout(void *timer)
-{
-    /* Parameter timer type is */
-    struct k_delayed_work *w = (struct k_delayed_work *)k_timer_get_id(timer);
-    if (w->work_q == NULL) {
-        return;
-    }
+static void work_timeout(void *timer) {
+  /* Parameter timer type is */
+  struct k_delayed_work *w = (struct k_delayed_work *)k_timer_get_id(timer);
+  if (w->work_q == NULL) {
+    return;
+  }
 
-    /* submit work to workqueue */
-    if (!atomic_test_bit(w->work.flags, K_WORK_STATE_PERIODIC)) {
-        k_work_submit_to_queue(w->work_q, &w->work);
-        /* detach from workqueue, for cancel to return appropriate status */
-        w->work_q = NULL;
-    } else {
-        /* For periodic timer, restart it.*/
-        k_timer_reset(&w->timer);
-        k_work_submit_to_queue(w->work_q, &w->work);
-    }
+  /* submit work to workqueue */
+  if (!atomic_test_bit(w->work.flags, K_WORK_STATE_PERIODIC)) {
+    k_work_submit_to_queue(w->work_q, &w->work);
+    /* detach from workqueue, for cancel to return appropriate status */
+    w->work_q = NULL;
+  } else {
+    /* For periodic timer, restart it.*/
+    k_timer_reset(&w->timer);
+    k_work_submit_to_queue(w->work_q, &w->work);
+  }
 }
 
-void k_delayed_work_init(struct k_delayed_work *work, k_work_handler_t handler)
-{
-    ASSERT(work, "delay work is NULL");
-    /* Added by bouffalolab */
-    k_work_init(&work->work, handler);
-    k_timer_init(&work->timer, work_timeout, work);
-    work->work_q = NULL;
+void k_delayed_work_init(struct k_delayed_work *work, k_work_handler_t handler) {
+  ASSERT(work, "delay work is NULL");
+  /* Added by bouffalolab */
+  k_work_init(&work->work, handler);
+  k_timer_init(&work->timer, work_timeout, work);
+  work->work_q = NULL;
 }
 
-static int k_delayed_work_submit_to_queue(struct k_work_q *work_q,
-                                          struct k_delayed_work *work,
-                                          uint32_t delay)
-{
-    int err;
+static int k_delayed_work_submit_to_queue(struct k_work_q *work_q, struct k_delayed_work *work, uint32_t delay) {
+  int err;
 
-    /* Work cannot be active in multiple queues */
-    if (work->work_q && work->work_q != work_q) {
-        err = -EADDRINUSE;
-        goto done;
-    }
+  /* Work cannot be active in multiple queues */
+  if (work->work_q && work->work_q != work_q) {
+    err = -EADDRINUSE;
+    goto done;
+  }
 
-    /* Cancel if work has been submitted */
-    if (work->work_q == work_q) {
-        err = k_delayed_work_cancel(work);
+  /* Cancel if work has been submitted */
+  if (work->work_q == work_q) {
+    err = k_delayed_work_cancel(work);
 
-        if (err < 0) {
-            goto done;
-        }
+    if (err < 0) {
+      goto done;
     }
+  }
 
-    if (!delay) {
-        /* Submit work if no ticks is 0 */
-        k_work_submit_to_queue(work_q, &work->work);
-        work->work_q = NULL;
-    } else {
-        /* Add timeout */
-        /* Attach workqueue so the timeout callback can submit it */
-        k_timer_start(&work->timer, delay);
-        work->work_q = work_q;
-    }
+  if (!delay) {
+    /* Submit work if no ticks is 0 */
+    k_work_submit_to_queue(work_q, &work->work);
+    work->work_q = NULL;
+  } else {
+    /* Add timeout */
+    /* Attach workqueue so the timeout callback can submit it */
+    k_timer_start(&work->timer, delay);
+    work->work_q = work_q;
+  }
 
-    err = 0;
+  err = 0;
 
 done:
-    return err;
+  return err;
 }
 
-int k_delayed_work_submit(struct k_delayed_work *work, uint32_t delay)
-{
-    atomic_clear_bit(work->work.flags, K_WORK_STATE_PERIODIC);
-    return k_delayed_work_submit_to_queue(&g_work_queue_main, work, delay);
+int k_delayed_work_submit(struct k_delayed_work *work, uint32_t delay) {
+  atomic_clear_bit(work->work.flags, K_WORK_STATE_PERIODIC);
+  return k_delayed_work_submit_to_queue(&g_work_queue_main, work, delay);
 }
 
 /* Added by bouffalolab */
-int k_delayed_work_submit_periodic(struct k_delayed_work *work, s32_t period)
-{
-    atomic_set_bit(work->work.flags, K_WORK_STATE_PERIODIC);
-    return k_delayed_work_submit_to_queue(&g_work_queue_main, work, period);
+int k_delayed_work_submit_periodic(struct k_delayed_work *work, s32_t period) {
+  atomic_set_bit(work->work.flags, K_WORK_STATE_PERIODIC);
+  return k_delayed_work_submit_to_queue(&g_work_queue_main, work, period);
 }
 
-int k_delayed_work_cancel(struct k_delayed_work *work)
-{
-    int err = 0;
+int k_delayed_work_cancel(struct k_delayed_work *work) {
+  int err = 0;
 
-    if (atomic_test_bit(work->work.flags, K_WORK_STATE_PENDING)) {
-        err = -EINPROGRESS;
-        goto exit;
-    }
+  if (atomic_test_bit(work->work.flags, K_WORK_STATE_PENDING)) {
+    err = -EINPROGRESS;
+    goto exit;
+  }
 
-    if (!work->work_q) {
-        err = -EINVAL;
-        goto exit;
-    }
+  if (!work->work_q) {
+    err = -EINVAL;
+    goto exit;
+  }
 
-    k_timer_stop(&work->timer);
-    work->work_q = NULL;
-    work->timer.timeout = 0;
-    work->timer.start_ms = 0;
+  k_timer_stop(&work->timer);
+  work->work_q         = NULL;
+  work->timer.timeout  = 0;
+  work->timer.start_ms = 0;
 
 exit:
-    return err;
+  return err;
 }
 
-s32_t k_delayed_work_remaining_get(struct k_delayed_work *work)
-{
-    int32_t remain;
-    k_timer_t *timer;
+s32_t k_delayed_work_remaining_get(struct k_delayed_work *work) {
+  int32_t    remain;
+  k_timer_t *timer;
 
-    if (work == NULL) {
-        return 0;
-    }
-
-    timer = &work->timer;
-    remain = timer->timeout - (k_now_ms() - timer->start_ms);
-    if (remain < 0) {
-        remain = 0;
-    }
-    return remain;
+  if (work == NULL) {
+    return 0;
+  }
+
+  timer  = &work->timer;
+  remain = timer->timeout - (k_now_ms() - timer->start_ms);
+  if (remain < 0) {
+    remain = 0;
+  }
+  return remain;
 }
 
-void k_delayed_work_del_timer(struct k_delayed_work *work)
-{
-    if (NULL == work || NULL == work->timer.timer.hdl)
-        return;
+void k_delayed_work_del_timer(struct k_delayed_work *work) {
+  if (NULL == work || NULL == work->timer.timer.hdl)
+    return;
 
-    k_timer_delete(&work->timer);
-    work->timer.timer.hdl = NULL;
+  k_timer_delete(&work->timer);
+  work->timer.timer.hdl = NULL;
 }
 
 /* Added by bouffalolab */
-int k_delayed_work_free(struct k_delayed_work *work)
-{
-    int err = 0;
+int k_delayed_work_free(struct k_delayed_work *work) {
+  int err = 0;
 
-    if (atomic_test_bit(work->work.flags, K_WORK_STATE_PENDING)) {
-        err = -EINPROGRESS;
-        goto exit;
-    }
+  if (atomic_test_bit(work->work.flags, K_WORK_STATE_PENDING)) {
+    err = -EINPROGRESS;
+    goto exit;
+  }
 
-    k_delayed_work_del_timer(work);
-    work->work_q = NULL;
-    work->timer.timeout = 0;
-    work->timer.start_ms = 0;
+  k_delayed_work_del_timer(work);
+  work->work_q         = NULL;
+  work->timer.timeout  = 0;
+  work->timer.start_ms = 0;
 
 exit:
-    return err;
+  return err;
 }
 
 #else
-static void work_q_main(void *work_q_ptr, void *p2, void *p3)
-{
-    struct k_work_q *work_q = work_q_ptr;
-
-    ARG_UNUSED(p2);
-    ARG_UNUSED(p3);
-
-    while (1) {
-        struct k_work *work;
-        k_work_handler_t handler;
-
-        work = k_queue_get(&work_q->queue, K_FOREVER);
-        if (!work) {
-            continue;
-        }
-
-        handler = work->handler;
-
-        /* Reset pending state so it can be resubmitted by handler */
-        if (atomic_test_and_clear_bit(work->flags,
-                                      K_WORK_STATE_PENDING)) {
-            handler(work);
-        }
-
-        /* Make sure we don't hog up the CPU if the FIFO never (or
-		 * very rarely) gets empty.
-		 */
-        k_yield();
+static void work_q_main(void *work_q_ptr, void *p2, void *p3) {
+  struct k_work_q *work_q = work_q_ptr;
+
+  ARG_UNUSED(p2);
+  ARG_UNUSED(p3);
+
+  while (1) {
+    struct k_work   *work;
+    k_work_handler_t handler;
+
+    work = k_queue_get(&work_q->queue, K_FOREVER);
+    if (!work) {
+      continue;
     }
+
+    handler = work->handler;
+
+    /* Reset pending state so it can be resubmitted by handler */
+    if (atomic_test_and_clear_bit(work->flags, K_WORK_STATE_PENDING)) {
+      handler(work);
+    }
+
+    /* Make sure we don't hog up the CPU if the FIFO never (or
+     * very rarely) gets empty.
+     */
+    k_yield();
+  }
 }
 
-void k_work_q_start(struct k_work_q *work_q, k_thread_stack_t *stack,
-                    size_t stack_size, int prio)
-{
-    k_queue_init(&work_q->queue, 20);
-    k_thread_create(&work_q->thread, stack, stack_size, work_q_main,
-                    work_q, 0, 0, prio, 0, 0);
-    _k_object_init(work_q);
+void k_work_q_start(struct k_work_q *work_q, k_thread_stack_t *stack, size_t stack_size, int prio) {
+  k_queue_init(&work_q->queue, 20);
+  k_thread_create(&work_q->thread, stack, stack_size, work_q_main, work_q, 0, 0, prio, 0, 0);
+  _k_object_init(work_q);
 }
 
 #ifdef CONFIG_SYS_CLOCK_EXISTS
-static void work_timeout(struct _timeout *t)
-{
-    struct k_delayed_work *w = CONTAINER_OF(t, struct k_delayed_work,
-                                            timeout);
+static void work_timeout(struct _timeout *t) {
+  struct k_delayed_work *w = CONTAINER_OF(t, struct k_delayed_work, timeout);
 
-    /* submit work to workqueue */
-    k_work_submit_to_queue(w->work_q, &w->work);
+  /* submit work to workqueue */
+  k_work_submit_to_queue(w->work_q, &w->work);
 }
 
-void k_delayed_work_init(struct k_delayed_work *work, k_work_handler_t handler)
-{
-    k_work_init(&work->work, handler);
-    _init_timeout(&work->timeout, work_timeout);
-    work->work_q = NULL;
+void k_delayed_work_init(struct k_delayed_work *work, k_work_handler_t handler) {
+  k_work_init(&work->work, handler);
+  _init_timeout(&work->timeout, work_timeout);
+  work->work_q = NULL;
 
-    _k_object_init(work);
+  _k_object_init(work);
 }
 
-int k_delayed_work_submit_to_queue(struct k_work_q *work_q,
-                                   struct k_delayed_work *work,
-                                   s32_t delay)
-{
-    unsigned int key = irq_lock();
-    int err;
-
-    /* Work cannot be active in multiple queues */
-    if (work->work_q && work->work_q != work_q) {
-        err = -EADDRINUSE;
-        goto done;
+int k_delayed_work_submit_to_queue(struct k_work_q *work_q, struct k_delayed_work *work, s32_t delay) {
+  unsigned int key = irq_lock();
+  int          err;
+
+  /* Work cannot be active in multiple queues */
+  if (work->work_q && work->work_q != work_q) {
+    err = -EADDRINUSE;
+    goto done;
+  }
+
+  /* Cancel if work has been submitted */
+  if (work->work_q == work_q) {
+    err = k_delayed_work_cancel(work);
+    if (err < 0) {
+      goto done;
     }
+  }
 
-    /* Cancel if work has been submitted */
-    if (work->work_q == work_q) {
-        err = k_delayed_work_cancel(work);
-        if (err < 0) {
-            goto done;
-        }
-    }
-
-    /* Attach workqueue so the timeout callback can submit it */
-    work->work_q = work_q;
+  /* Attach workqueue so the timeout callback can submit it */
+  work->work_q = work_q;
 
-    if (!delay) {
-        /* Submit work if no ticks is 0 */
-        k_work_submit_to_queue(work_q, &work->work);
-    } else {
-        /* Add timeout */
-        _add_timeout(NULL, &work->timeout, NULL,
-                     _TICK_ALIGN + _ms_to_ticks(delay));
-    }
+  if (!delay) {
+    /* Submit work if no ticks is 0 */
+    k_work_submit_to_queue(work_q, &work->work);
+  } else {
+    /* Add timeout */
+    _add_timeout(NULL, &work->timeout, NULL, _TICK_ALIGN + _ms_to_ticks(delay));
+  }
 
-    err = 0;
+  err = 0;
 
 done:
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return err;
+  return err;
 }
 
-int k_delayed_work_cancel(struct k_delayed_work *work)
-{
-    unsigned int key = irq_lock();
+int k_delayed_work_cancel(struct k_delayed_work *work) {
+  unsigned int key = irq_lock();
 
-    if (!work->work_q) {
-        irq_unlock(key);
-        return -EINVAL;
-    }
-
-    if (k_work_pending(&work->work)) {
-        /* Remove from the queue if already submitted */
-        if (!k_queue_remove(&work->work_q->queue, &work->work)) {
-            irq_unlock(key);
-            return -EINVAL;
-        }
-    } else {
-        _abort_timeout(&work->timeout);
+  if (!work->work_q) {
+    irq_unlock(key);
+    return -EINVAL;
+  }
+
+  if (k_work_pending(&work->work)) {
+    /* Remove from the queue if already submitted */
+    if (!k_queue_remove(&work->work_q->queue, &work->work)) {
+      irq_unlock(key);
+      return -EINVAL;
     }
+  } else {
+    _abort_timeout(&work->timeout);
+  }
 
-    /* Detach from workqueue */
-    work->work_q = NULL;
+  /* Detach from workqueue */
+  work->work_q = NULL;
 
-    atomic_clear_bit(work->work.flags, K_WORK_STATE_PENDING);
-    irq_unlock(key);
+  atomic_clear_bit(work->work.flags, K_WORK_STATE_PENDING);
+  irq_unlock(key);
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_SYS_CLOCK_EXISTS */
 #endif /* BFLB_BLE */
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/hci_onchip/hci_driver.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/hci_onchip/hci_driver.c
index a992c5d1c6..47b1daf682 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/hci_onchip/hci_driver.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/hci_onchip/hci_driver.c
@@ -10,20 +10,20 @@
 #include 
 
 #include 
-//#include 
-//#include 
-//#include 
-//#include 
+// #include 
+// #include 
+// #include 
+// #include 
 #include 
 #include 
 
-#include 
-#include 
 #include 
+#include 
+#include 
 
 #include 
-#include 
 #include 
+#include 
 
 #ifdef CONFIG_CLOCK_CONTROL_NRF5
 #include 
@@ -32,20 +32,19 @@
 #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_HCI_DRIVER)
 #include "log.h"
 
-//#include "util/util.h"
-//#include "hal/ccm.h"
-//#include "hal/radio.h"
-//#include "ll_sw/pdu.h"
-//#include "ll_sw/ctrl.h"
+// #include "util/util.h"
+// #include "hal/ccm.h"
+// #include "hal/radio.h"
+// #include "ll_sw/pdu.h"
+// #include "ll_sw/ctrl.h"
 #include "hci_internal.h"
-//#include "init.h"
-//#include "hal/debug.h"
+// #include "init.h"
+// #include "hal/debug.h"
 #if defined(BFLB_BLE)
 #include "bl_hci_wrapper.h"
 #endif
 
-#define NODE_RX(_node) CONTAINER_OF(_node, struct radio_pdu_node_rx, \
-                                    hdr.onion.node)
+#define NODE_RX(_node) CONTAINER_OF(_node, struct radio_pdu_node_rx, hdr.onion.node)
 
 #if !defined(BFLB_BLE)
 static K_SEM_DEFINE(sem_prio_recv, 0, BT_UINT_MAX);
@@ -54,13 +53,12 @@ static K_SEM_DEFINE(sem_prio_recv, 0, BT_UINT_MAX);
 K_FIFO_DEFINE(recv_fifo);
 #if (BFLB_BLE_CO_THREAD)
 extern struct k_sem g_poll_sem;
-static int recv_fifo_count = 0;
+static int          recv_fifo_count = 0;
 #endif
 
 #if !defined(BFLB_BLE)
 struct k_thread prio_recv_thread_data;
-static BT_STACK_NOINIT(prio_recv_thread_stack,
-                       CONFIG_BT_CTLR_RX_PRIO_STACK_SIZE);
+static BT_STACK_NOINIT(prio_recv_thread_stack, CONFIG_BT_CTLR_RX_PRIO_STACK_SIZE);
 #endif
 
 struct k_thread recv_thread_data;
@@ -74,487 +72,452 @@ static u32_t rx_ts;
 #endif
 
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-static struct k_poll_signal hbuf_signal =
-    K_POLL_SIGNAL_INITIALIZER(hbuf_signal);
-static sys_slist_t hbuf_pend;
-static s32_t hbuf_count;
+static struct k_poll_signal hbuf_signal = K_POLL_SIGNAL_INITIALIZER(hbuf_signal);
+static sys_slist_t          hbuf_pend;
+static s32_t                hbuf_count;
 #endif
 
 #if !defined(BFLB_BLE)
-static void prio_recv_thread(void *p1, void *p2, void *p3)
-{
-    while (1) {
-        struct radio_pdu_node_rx *node_rx;
-        u8_t num_cmplt;
-        u16_t handle;
-
-        while ((num_cmplt = radio_rx_get(&node_rx, &handle))) {
+static void prio_recv_thread(void *p1, void *p2, void *p3) {
+  while (1) {
+    struct radio_pdu_node_rx *node_rx;
+    u8_t                      num_cmplt;
+    u16_t                     handle;
+
+    while ((num_cmplt = radio_rx_get(&node_rx, &handle))) {
 #if defined(CONFIG_BT_CONN)
-            struct net_buf *buf;
+      struct net_buf *buf;
 
-            buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
-            hci_num_cmplt_encode(buf, handle, num_cmplt);
-            BT_DBG("Num Complete: 0x%04x:%u", handle, num_cmplt);
-            bt_recv_prio(buf);
-            k_yield();
+      buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
+      hci_num_cmplt_encode(buf, handle, num_cmplt);
+      BT_DBG("Num Complete: 0x%04x:%u", handle, num_cmplt);
+      bt_recv_prio(buf);
+      k_yield();
 #endif
-        }
+    }
 
-        if (node_rx) {
-            radio_rx_dequeue();
+    if (node_rx) {
+      radio_rx_dequeue();
 
-            BT_DBG("RX node enqueue");
-            k_fifo_put(&recv_fifo, node_rx);
+      BT_DBG("RX node enqueue");
+      k_fifo_put(&recv_fifo, node_rx);
 
-            continue;
-        }
+      continue;
+    }
 
-        BT_DBG("sem take...");
-        k_sem_take(&sem_prio_recv, K_FOREVER);
-        BT_DBG("sem taken");
+    BT_DBG("sem take...");
+    k_sem_take(&sem_prio_recv, K_FOREVER);
+    BT_DBG("sem taken");
 
 #if defined(CONFIG_INIT_STACKS)
-        if (k_uptime_get_32() - prio_ts > K_SECONDS(5)) {
-            STACK_ANALYZE("prio recv thread stack",
-                          prio_recv_thread_stack);
-            prio_ts = k_uptime_get_32();
-        }
-#endif
+    if (k_uptime_get_32() - prio_ts > K_SECONDS(5)) {
+      STACK_ANALYZE("prio recv thread stack", prio_recv_thread_stack);
+      prio_ts = k_uptime_get_32();
     }
+#endif
+  }
 }
 
-static inline struct net_buf *encode_node(struct radio_pdu_node_rx *node_rx,
-                                          s8_t class)
-{
-    struct net_buf *buf = NULL;
+static inline struct net_buf *encode_node(struct radio_pdu_node_rx *node_rx, s8_t class) {
+  struct net_buf *buf = NULL;
 
-    /* Check if we need to generate an HCI event or ACL data */
-    switch (class) {
-        case HCI_CLASS_EVT_DISCARDABLE:
-        case HCI_CLASS_EVT_REQUIRED:
-        case HCI_CLASS_EVT_CONNECTION:
-            if (class == HCI_CLASS_EVT_DISCARDABLE) {
-                buf = bt_buf_get_rx(BT_BUF_EVT, K_NO_WAIT);
-            } else {
-                buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
-            }
-            if (buf) {
-                hci_evt_encode(node_rx, buf);
-            }
-            break;
+  /* Check if we need to generate an HCI event or ACL data */
+  switch (class) {
+  case HCI_CLASS_EVT_DISCARDABLE:
+  case HCI_CLASS_EVT_REQUIRED:
+  case HCI_CLASS_EVT_CONNECTION:
+    if (class == HCI_CLASS_EVT_DISCARDABLE) {
+      buf = bt_buf_get_rx(BT_BUF_EVT, K_NO_WAIT);
+    } else {
+      buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
+    }
+    if (buf) {
+      hci_evt_encode(node_rx, buf);
+    }
+    break;
 #if defined(CONFIG_BT_CONN)
-        case HCI_CLASS_ACL_DATA:
-            /* generate ACL data */
-            buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_FOREVER);
-            hci_acl_encode(node_rx, buf);
-            break;
+  case HCI_CLASS_ACL_DATA:
+    /* generate ACL data */
+    buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_FOREVER);
+    hci_acl_encode(node_rx, buf);
+    break;
 #endif
-        default:
-            LL_ASSERT(0);
-            break;
-    }
+  default:
+    LL_ASSERT(0);
+    break;
+  }
 
-    radio_rx_fc_set(node_rx->hdr.handle, 0);
-    node_rx->hdr.onion.next = 0;
-    radio_rx_mem_release(&node_rx);
+  radio_rx_fc_set(node_rx->hdr.handle, 0);
+  node_rx->hdr.onion.next = 0;
+  radio_rx_mem_release(&node_rx);
 
-    return buf;
+  return buf;
 }
 
-static inline struct net_buf *process_node(struct radio_pdu_node_rx *node_rx)
-{
-    s8_t class = hci_get_class(node_rx);
-    struct net_buf *buf = NULL;
+static inline struct net_buf *process_node(struct radio_pdu_node_rx *node_rx) {
+  s8_t class          = hci_get_class(node_rx);
+  struct net_buf *buf = NULL;
 
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-    if (hbuf_count != -1) {
-        bool pend = !sys_slist_is_empty(&hbuf_pend);
-
-        /* controller to host flow control enabled */
-        switch (class) {
-            case HCI_CLASS_EVT_DISCARDABLE:
-            case HCI_CLASS_EVT_REQUIRED:
-                break;
-            case HCI_CLASS_EVT_CONNECTION:
-                /* for conn-related events, only pend is relevant */
-                hbuf_count = 1;
-                /* fallthrough */
-            case HCI_CLASS_ACL_DATA:
-                if (pend || !hbuf_count) {
-                    sys_slist_append(&hbuf_pend,
-                                     &node_rx->hdr.onion.node);
-                    BT_DBG("FC: Queuing item: %d", class);
-                    return NULL;
-                }
-                break;
-            default:
-                LL_ASSERT(0);
-                break;
-        }
+  if (hbuf_count != -1) {
+    bool pend = !sys_slist_is_empty(&hbuf_pend);
+
+    /* controller to host flow control enabled */
+    switch (class) {
+    case HCI_CLASS_EVT_DISCARDABLE:
+    case HCI_CLASS_EVT_REQUIRED:
+      break;
+    case HCI_CLASS_EVT_CONNECTION:
+      /* for conn-related events, only pend is relevant */
+      hbuf_count = 1;
+      /* fallthrough */
+    case HCI_CLASS_ACL_DATA:
+      if (pend || !hbuf_count) {
+        sys_slist_append(&hbuf_pend, &node_rx->hdr.onion.node);
+        BT_DBG("FC: Queuing item: %d", class);
+        return NULL;
+      }
+      break;
+    default:
+      LL_ASSERT(0);
+      break;
     }
+  }
 #endif
 
-    /* process regular node from radio */
-    buf = encode_node(node_rx, class);
+  /* process regular node from radio */
+  buf = encode_node(node_rx, class);
 
-    return buf;
+  return buf;
 }
 
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-static inline struct net_buf *process_hbuf(struct radio_pdu_node_rx *n)
-{
-    /* shadow total count in case of preemption */
-    struct radio_pdu_node_rx *node_rx = NULL;
-    s32_t hbuf_total = hci_hbuf_total;
-    struct net_buf *buf = NULL;
-    sys_snode_t *node = NULL;
-    s8_t class;
-    int reset;
-
-    reset = atomic_test_and_clear_bit(&hci_state_mask, HCI_STATE_BIT_RESET);
-    if (reset) {
-        /* flush queue, no need to free, the LL has already done it */
-        sys_slist_init(&hbuf_pend);
+static inline struct net_buf *process_hbuf(struct radio_pdu_node_rx *n) {
+  /* shadow total count in case of preemption */
+  struct radio_pdu_node_rx *node_rx    = NULL;
+  s32_t                     hbuf_total = hci_hbuf_total;
+  struct net_buf           *buf        = NULL;
+  sys_snode_t              *node       = NULL;
+  s8_t class;
+  int reset;
+
+  reset = atomic_test_and_clear_bit(&hci_state_mask, HCI_STATE_BIT_RESET);
+  if (reset) {
+    /* flush queue, no need to free, the LL has already done it */
+    sys_slist_init(&hbuf_pend);
+  }
+
+  if (hbuf_total <= 0) {
+    hbuf_count = -1;
+    return NULL;
+  }
+
+  /* available host buffers */
+  hbuf_count = hbuf_total - (hci_hbuf_sent - hci_hbuf_acked);
+
+  /* host acked ACL packets, try to dequeue from hbuf */
+  node = sys_slist_peek_head(&hbuf_pend);
+  if (!node) {
+    return NULL;
+  }
+
+  /* Return early if this iteration already has a node to process */
+  node_rx = NODE_RX(node);
+  class   = hci_get_class(node_rx);
+  if (n) {
+    if (class == HCI_CLASS_EVT_CONNECTION || (class == HCI_CLASS_ACL_DATA && hbuf_count)) {
+      /* node to process later, schedule an iteration */
+      BT_DBG("FC: signalling");
+      k_poll_signal_raise(&hbuf_signal, 0x0);
     }
-
-    if (hbuf_total <= 0) {
-        hbuf_count = -1;
-        return NULL;
+    return NULL;
+  }
+
+  switch (class) {
+  case HCI_CLASS_EVT_CONNECTION:
+    BT_DBG("FC: dequeueing event");
+    (void)sys_slist_get(&hbuf_pend);
+    break;
+  case HCI_CLASS_ACL_DATA:
+    if (hbuf_count) {
+      BT_DBG("FC: dequeueing ACL data");
+      (void)sys_slist_get(&hbuf_pend);
+    } else {
+      /* no buffers, HCI will signal */
+      node = NULL;
     }
-
-    /* available host buffers */
+    break;
+  case HCI_CLASS_EVT_DISCARDABLE:
+  case HCI_CLASS_EVT_REQUIRED:
+  default:
+    LL_ASSERT(0);
+    break;
+  }
+
+  if (node) {
+    buf = encode_node(node_rx, class);
+    /* Update host buffers after encoding */
     hbuf_count = hbuf_total - (hci_hbuf_sent - hci_hbuf_acked);
-
-    /* host acked ACL packets, try to dequeue from hbuf */
+    /* next node */
     node = sys_slist_peek_head(&hbuf_pend);
-    if (!node) {
-        return NULL;
-    }
-
-    /* Return early if this iteration already has a node to process */
-    node_rx = NODE_RX(node);
-    class = hci_get_class(node_rx);
-    if (n) {
-        if (class == HCI_CLASS_EVT_CONNECTION ||
-            (class == HCI_CLASS_ACL_DATA && hbuf_count)) {
-            /* node to process later, schedule an iteration */
-            BT_DBG("FC: signalling");
-            k_poll_signal_raise(&hbuf_signal, 0x0);
-        }
-        return NULL;
-    }
-
-    switch (class) {
-        case HCI_CLASS_EVT_CONNECTION:
-            BT_DBG("FC: dequeueing event");
-            (void)sys_slist_get(&hbuf_pend);
-            break;
-        case HCI_CLASS_ACL_DATA:
-            if (hbuf_count) {
-                BT_DBG("FC: dequeueing ACL data");
-                (void)sys_slist_get(&hbuf_pend);
-            } else {
-                /* no buffers, HCI will signal */
-                node = NULL;
-            }
-            break;
-        case HCI_CLASS_EVT_DISCARDABLE:
-        case HCI_CLASS_EVT_REQUIRED:
-        default:
-            LL_ASSERT(0);
-            break;
-    }
-
     if (node) {
-        buf = encode_node(node_rx, class);
-        /* Update host buffers after encoding */
-        hbuf_count = hbuf_total - (hci_hbuf_sent - hci_hbuf_acked);
-        /* next node */
-        node = sys_slist_peek_head(&hbuf_pend);
-        if (node) {
-            node_rx = NODE_RX(node);
-            class = hci_get_class(node_rx);
-
-            if (class == HCI_CLASS_EVT_CONNECTION ||
-                (class == HCI_CLASS_ACL_DATA && hbuf_count)) {
-                /* more to process, schedule an
-				 * iteration
-				 */
-                BT_DBG("FC: signalling");
-                k_poll_signal_raise(&hbuf_signal, 0x0);
-            }
-        }
+      node_rx = NODE_RX(node);
+      class   = hci_get_class(node_rx);
+
+      if (class == HCI_CLASS_EVT_CONNECTION || (class == HCI_CLASS_ACL_DATA && hbuf_count)) {
+        /* more to process, schedule an
+         * iteration
+         */
+        BT_DBG("FC: signalling");
+        k_poll_signal_raise(&hbuf_signal, 0x0);
+      }
     }
+  }
 
-    return buf;
+  return buf;
 }
 #endif
 #endif
 
 #if defined(BFLB_BLE)
 #if (BFLB_BLE_CO_THREAD)
-void co_rx_thread()
-{
-    struct net_buf *buf = NULL;
-    buf = net_buf_get(&recv_fifo, K_NO_WAIT);
-    if (buf) {
-        BT_DBG("Calling bt_recv(%p)", buf);
-        bt_recv(buf);
-    }
+void co_rx_thread() {
+  struct net_buf *buf = NULL;
+  buf                 = net_buf_get(&recv_fifo, K_NO_WAIT);
+  if (buf) {
+    BT_DBG("Calling bt_recv(%p)", buf);
+    bt_recv(buf);
+  }
 }
 
-void co_tx_rx_thread(void *p1)
-{
-    UNUSED(p1);
-    BT_DBG("using %s\n", __func__);
-    while (1) {
-        if (k_sem_count_get(&g_poll_sem) > 0) {
-            co_tx_thread();
-        }
-
-        if (recv_fifo_count > 0) {
-            recv_fifo_count--;
-            co_rx_thread();
-        }
-
-        k_sleep(portTICK_PERIOD_MS);
-        k_yield();
+void co_tx_rx_thread(void *p1) {
+  UNUSED(p1);
+  BT_DBG("using %s\n", __func__);
+  while (1) {
+    if (k_sem_count_get(&g_poll_sem) > 0) {
+      co_tx_thread();
     }
+
+    if (recv_fifo_count > 0) {
+      recv_fifo_count--;
+      co_rx_thread();
+    }
+
+    k_sleep(portTICK_PERIOD_MS);
+    k_yield();
+  }
 }
 
 #else
-static void recv_thread(void *p1)
-{
-    UNUSED(p1);
+static void recv_thread(void *p1) {
+  UNUSED(p1);
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-    /* @todo: check if the events structure really needs to be static */
-    static struct k_poll_event events[2] = {
-        K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_SIGNAL,
-                                        K_POLL_MODE_NOTIFY_ONLY,
-                                        &hbuf_signal, 0),
-        K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE,
-                                        K_POLL_MODE_NOTIFY_ONLY,
-                                        &recv_fifo, 0),
-    };
+  /* @todo: check if the events structure really needs to be static */
+  static struct k_poll_event events[2] = {
+      K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_SIGNAL, K_POLL_MODE_NOTIFY_ONLY, &hbuf_signal, 0),
+      K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &recv_fifo, 0),
+  };
 #endif
 
-    while (1) {
+  while (1) {
 #if defined(BFLB_BLE)
-        struct net_buf *buf = NULL;
-        buf = net_buf_get(&recv_fifo, K_FOREVER);
-        if (buf) {
-            BT_DBG("Calling bt_recv(%p)", buf);
-            bt_recv(buf);
-        }
+    struct net_buf *buf = NULL;
+    buf                 = net_buf_get(&recv_fifo, K_FOREVER);
+    if (buf) {
+      BT_DBG("Calling bt_recv(%p)", buf);
+      bt_recv(buf);
+    }
 #else
-        struct radio_pdu_node_rx *node_rx = NULL;
-        struct net_buf *buf = NULL;
+    struct radio_pdu_node_rx *node_rx = NULL;
+    struct net_buf           *buf     = NULL;
 
-        BT_DBG("blocking");
+    BT_DBG("blocking");
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-        int err;
+    int err;
 
-        err = k_poll(events, 2, K_FOREVER);
-        LL_ASSERT(err == 0);
-        if (events[0].state == K_POLL_STATE_SIGNALED) {
-            events[0].signal->signaled = 0;
-        } else if (events[1].state ==
-                   K_POLL_STATE_FIFO_DATA_AVAILABLE) {
-            node_rx = k_fifo_get(events[1].fifo, 0);
-        }
+    err = k_poll(events, 2, K_FOREVER);
+    LL_ASSERT(err == 0);
+    if (events[0].state == K_POLL_STATE_SIGNALED) {
+      events[0].signal->signaled = 0;
+    } else if (events[1].state == K_POLL_STATE_FIFO_DATA_AVAILABLE) {
+      node_rx = k_fifo_get(events[1].fifo, 0);
+    }
 
-        events[0].state = K_POLL_STATE_NOT_READY;
-        events[1].state = K_POLL_STATE_NOT_READY;
+    events[0].state = K_POLL_STATE_NOT_READY;
+    events[1].state = K_POLL_STATE_NOT_READY;
 
-        /* process host buffers first if any */
-        buf = process_hbuf(node_rx);
+    /* process host buffers first if any */
+    buf = process_hbuf(node_rx);
 
 #else
-        node_rx = k_fifo_get(&recv_fifo, K_FOREVER);
+    node_rx = k_fifo_get(&recv_fifo, K_FOREVER);
 #endif
-        BT_DBG("unblocked");
-
-        if (node_rx && !buf) {
-            /* process regular node from radio */
-            buf = process_node(node_rx);
-        }
-
-        if (buf) {
-            if (buf->len) {
-                BT_DBG("Packet in: type:%u len:%u",
-                       bt_buf_get_type(buf), buf->len);
-                bt_recv(buf);
-            } else {
-                net_buf_unref(buf);
-            }
-        }
+    BT_DBG("unblocked");
+
+    if (node_rx && !buf) {
+      /* process regular node from radio */
+      buf = process_node(node_rx);
+    }
+
+    if (buf) {
+      if (buf->len) {
+        BT_DBG("Packet in: type:%u len:%u", bt_buf_get_type(buf), buf->len);
+        bt_recv(buf);
+      } else {
+        net_buf_unref(buf);
+      }
+    }
 #endif
-        k_yield();
+    k_yield();
 
 #if defined(CONFIG_INIT_STACKS)
-        if (k_uptime_get_32() - rx_ts > K_SECONDS(5)) {
-            STACK_ANALYZE("recv thread stack", recv_thread_stack);
-            rx_ts = k_uptime_get_32();
-        }
-#endif
+    if (k_uptime_get_32() - rx_ts > K_SECONDS(5)) {
+      STACK_ANALYZE("recv thread stack", recv_thread_stack);
+      rx_ts = k_uptime_get_32();
     }
+#endif
+  }
 }
 #endif
 #endif
 
 #if !defined(BFLB_BLE)
-static int cmd_handle(struct net_buf *buf)
-{
-    struct net_buf *evt;
-
-    evt = hci_cmd_handle(buf);
-    if (evt) {
-        BT_DBG("Replying with event of %u bytes", evt->len);
-        bt_recv_prio(evt);
-    }
+static int cmd_handle(struct net_buf *buf) {
+  struct net_buf *evt;
+
+  evt = hci_cmd_handle(buf);
+  if (evt) {
+    BT_DBG("Replying with event of %u bytes", evt->len);
+    bt_recv_prio(evt);
+  }
 }
 
 #if defined(CONFIG_BT_CONN)
-static int acl_handle(struct net_buf *buf)
-{
-    struct net_buf *evt;
-    int err;
+static int acl_handle(struct net_buf *buf) {
+  struct net_buf *evt;
+  int             err;
 
-    err = hci_acl_handle(buf, &evt);
-    if (evt) {
-        BT_DBG("Replying with event of %u bytes", evt->len);
-        bt_recv_prio(evt);
-    }
+  err = hci_acl_handle(buf, &evt);
+  if (evt) {
+    BT_DBG("Replying with event of %u bytes", evt->len);
+    bt_recv_prio(evt);
+  }
 
-    return err;
+  return err;
 }
 #endif /* CONFIG_BT_CONN */
 #endif
 
-static int hci_driver_send(struct net_buf *buf)
-{
+static int hci_driver_send(struct net_buf *buf) {
 #if !defined(BFLB_BLE)
-    u8_t type;
+  u8_t type;
 #endif
-    int err;
+  int err;
 
-    BT_DBG("enter");
+  BT_DBG("enter");
 
-    if (!buf->len) {
-        BT_ERR("Empty HCI packet");
-        return -EINVAL;
-    }
+  if (!buf->len) {
+    BT_ERR("Empty HCI packet");
+    return -EINVAL;
+  }
 
 #if defined(BFLB_BLE)
-    err = bl_onchiphci_send_2_controller(buf);
-    net_buf_unref(buf);
-    return err;
+  err = bl_onchiphci_send_2_controller(buf);
+  net_buf_unref(buf);
+  return err;
 #else
-    type = bt_buf_get_type(buf);
-    switch (type) {
+  type = bt_buf_get_type(buf);
+  switch (type) {
 #if defined(CONFIG_BT_CONN)
-        case BT_BUF_ACL_OUT:
-            err = acl_handle(buf);
-            break;
+  case BT_BUF_ACL_OUT:
+    err = acl_handle(buf);
+    break;
 #endif /* CONFIG_BT_CONN */
-        case BT_BUF_CMD:
-            err = cmd_handle(buf);
+  case BT_BUF_CMD:
+    err = cmd_handle(buf);
 
-            break;
-        default:
-            BT_ERR("Unknown HCI type %u", type);
-            return -EINVAL;
-    }
+    break;
+  default:
+    BT_ERR("Unknown HCI type %u", type);
+    return -EINVAL;
+  }
 
-    if (!err) {
-        net_buf_unref(buf);
-    } else {
-    }
+  if (!err) {
+    net_buf_unref(buf);
+  } else {
+  }
 
-    BT_DBG("exit: %d", err);
+  BT_DBG("exit: %d", err);
 #endif
-    return err;
+  return err;
 }
 
-static int hci_driver_open(void)
-{
+static int hci_driver_open(void) {
 #if !defined(BFLB_BLE)
-    u32_t err;
+  u32_t err;
 
-    DEBUG_INIT();
-    k_sem_init(&sem_prio_recv, 0, BT_UINT_MAX);
+  DEBUG_INIT();
+  k_sem_init(&sem_prio_recv, 0, BT_UINT_MAX);
 
-    err = ll_init(&sem_prio_recv);
+  err = ll_init(&sem_prio_recv);
 
-    if (err) {
-        BT_ERR("LL initialization failed: %u", err);
-        return err;
-    }
+  if (err) {
+    BT_ERR("LL initialization failed: %u", err);
+    return err;
+  }
 #endif
 
 #if !defined(BFLB_BLE)
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-    hci_init(&hbuf_signal);
+  hci_init(&hbuf_signal);
 #else
-    hci_init(NULL);
+  hci_init(NULL);
 #endif
 #endif
-    k_fifo_init(&recv_fifo, 20);
+  k_fifo_init(&recv_fifo, 20);
 
 #if defined(BFLB_BLE)
 #if (BFLB_BLE_CO_THREAD)
-    k_thread_create(&recv_thread_data, "co_tx_rx_thread",
-                    CONFIG_BT_RX_STACK_SIZE,
-                    co_tx_rx_thread,
-                    K_PRIO_COOP(CONFIG_BT_RX_PRIO));
+  k_thread_create(&recv_thread_data, "co_tx_rx_thread", CONFIG_BT_RX_STACK_SIZE, co_tx_rx_thread, K_PRIO_COOP(CONFIG_BT_RX_PRIO));
 #else
-    k_thread_create(&recv_thread_data, "recv_thread",
-                    CONFIG_BT_RX_STACK_SIZE /*K_THREAD_STACK_SIZEOF(recv_thread_stack)*/,
-                    recv_thread,
-                    K_PRIO_COOP(CONFIG_BT_RX_PRIO));
+  k_thread_create(&recv_thread_data, "recv_thread", CONFIG_BT_RX_STACK_SIZE /*K_THREAD_STACK_SIZEOF(recv_thread_stack)*/, recv_thread, K_PRIO_COOP(CONFIG_BT_RX_PRIO));
 #endif
 #else
-    k_thread_create(&prio_recv_thread_data, prio_recv_thread_stack,
-                    K_THREAD_STACK_SIZEOF(prio_recv_thread_stack),
-                    prio_recv_thread, NULL, NULL, NULL,
-                    K_PRIO_COOP(CONFIG_BT_CTLR_RX_PRIO), 0, K_NO_WAIT);
+  k_thread_create(&prio_recv_thread_data, prio_recv_thread_stack, K_THREAD_STACK_SIZEOF(prio_recv_thread_stack), prio_recv_thread, NULL, NULL, NULL, K_PRIO_COOP(CONFIG_BT_CTLR_RX_PRIO), 0, K_NO_WAIT);
 #endif
 
-    BT_DBG("Success.");
+  BT_DBG("Success.");
 
-    return 0;
+  return 0;
 }
 
-void hci_driver_enque_recvq(struct net_buf *buf)
-{
-    net_buf_put(&recv_fifo, buf);
+void hci_driver_enque_recvq(struct net_buf *buf) {
+  net_buf_put(&recv_fifo, buf);
 #if (BFLB_BLE_CO_THREAD)
-    recv_fifo_count++;
+  recv_fifo_count++;
 #endif
 }
 
 static const struct bt_hci_driver drv = {
     .name = "Controller",
-    .bus = BT_HCI_DRIVER_BUS_VIRTUAL,
+    .bus  = BT_HCI_DRIVER_BUS_VIRTUAL,
     .open = hci_driver_open,
     .send = hci_driver_send,
 };
 
 #if defined(BFLB_BLE)
-int hci_driver_init(void)
-{
-    bt_hci_driver_register(&drv);
+int hci_driver_init(void) {
+  bt_hci_driver_register(&drv);
 
-    return 0;
+  return 0;
 }
 #else
-static int _hci_driver_init(struct device *unused)
-{
-    ARG_UNUSED(unused);
+static int _hci_driver_init(struct device *unused) {
+  ARG_UNUSED(unused);
 
-    bt_hci_driver_register(&drv);
+  bt_hci_driver_register(&drv);
 
-    return 0;
+  return 0;
 }
-//SYS_INIT(_hci_driver_init, POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE);
+// SYS_INIT(_hci_driver_init, POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE);
 #endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/a2dp.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/a2dp.c
index 82901ed233..6a7ddc1bd3 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/a2dp.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/a2dp.c
@@ -8,84 +8,61 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
-#include 
+#include 
 #include 
 #include 
-#include 
+#include 
 #include 
-#include 
+#include 
+#include 
+#include 
 
+#include 
+#include 
 #include 
 #include 
-#include 
-#include 
 #include 
 
 #define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_A2DP)
 #define LOG_MODULE_NAME bt_a2dp
 #include "log.h"
 
-#include "hci_core.h"
-#include "conn_internal.h"
-#include "avdtp_internal.h"
-#include "a2dp_internal.h"
 #include "a2dp-codec.h"
+#include "a2dp_internal.h"
+#include "avdtp_internal.h"
+#include "conn_internal.h"
+#include "hci_core.h"
 #include "oi_codec_sbc.h"
 
 #define A2DP_NO_SPACE (-1)
 
 struct bt_a2dp {
-    struct bt_avdtp session;
+  struct bt_avdtp session;
 };
 
 typedef struct {
-    OI_CODEC_SBC_DECODER_CONTEXT decoder_context;
-    uint32_t context_data[CODEC_DATA_WORDS(SBC_MAX_CHANNELS, SBC_CODEC_FAST_FILTER_BUFFERS)];
-    int16_t decode_buf[15 * SBC_MAX_SAMPLES_PER_FRAME * SBC_MAX_CHANNELS];
+  OI_CODEC_SBC_DECODER_CONTEXT decoder_context;
+  uint32_t                     context_data[CODEC_DATA_WORDS(SBC_MAX_CHANNELS, SBC_CODEC_FAST_FILTER_BUFFERS)];
+  int16_t                      decode_buf[15 * SBC_MAX_SAMPLES_PER_FRAME * SBC_MAX_CHANNELS];
 } A2DP_SBC_DECODER;
 
 static A2DP_SBC_DECODER sbc_decoder;
 
 /* Connections */
-static struct bt_a2dp connection[CONFIG_BT_MAX_CONN];
+static struct bt_a2dp         connection[CONFIG_BT_MAX_CONN];
 static struct bt_avdtp_stream stream[CONFIG_BT_MAX_CONN];
 
 static struct bt_sdp_attribute a2dp_attrs[] = {
     BT_SDP_NEW_SERVICE,
-    BT_SDP_LIST(
-        BT_SDP_ATTR_SVCLASS_ID_LIST,
-        BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3),
-        BT_SDP_DATA_ELEM_LIST(
-            { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-              BT_SDP_ARRAY_16(BT_SDP_AUDIO_SINK_SVCLASS) }, )),
-    BT_SDP_LIST(
-        BT_SDP_ATTR_PROTO_DESC_LIST,
-        BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 16),
-        BT_SDP_DATA_ELEM_LIST(
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 6),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_SDP_PROTO_L2CAP) },
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UINT16),
-                    BT_SDP_ARRAY_16(BT_L2CAP_PSM_AVDTP) }, ) },
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 6),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_L2CAP_PSM_AVDTP) },
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UINT16),
-                    BT_SDP_ARRAY_16(0x0102) }, ) }, )),
-    BT_SDP_LIST(
-        BT_SDP_ATTR_PROFILE_DESC_LIST,
-        BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 8),
-        BT_SDP_DATA_ELEM_LIST(
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 6),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_SDP_ADVANCED_AUDIO_SVCLASS) },
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UINT16),
-                    BT_SDP_ARRAY_16(0x0102) }, ) }, )),
+    BT_SDP_LIST(BT_SDP_ATTR_SVCLASS_ID_LIST, BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3), BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE(BT_SDP_UUID16), BT_SDP_ARRAY_16(BT_SDP_AUDIO_SINK_SVCLASS)}, )),
+    BT_SDP_LIST(BT_SDP_ATTR_PROTO_DESC_LIST, BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 16),
+                BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 6), BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE(BT_SDP_UUID16), BT_SDP_ARRAY_16(BT_SDP_PROTO_L2CAP)},
+                                                                                                   {BT_SDP_TYPE_SIZE(BT_SDP_UINT16), BT_SDP_ARRAY_16(BT_L2CAP_PSM_AVDTP)}, )},
+                                      {BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 6),
+                                       BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE(BT_SDP_UUID16), BT_SDP_ARRAY_16(BT_L2CAP_PSM_AVDTP)}, {BT_SDP_TYPE_SIZE(BT_SDP_UINT16), BT_SDP_ARRAY_16(0x0102)}, )}, )),
+    BT_SDP_LIST(BT_SDP_ATTR_PROFILE_DESC_LIST, BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 8),
+                BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 6), BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE(BT_SDP_UUID16), BT_SDP_ARRAY_16(BT_SDP_ADVANCED_AUDIO_SVCLASS)},
+                                                                                                   {BT_SDP_TYPE_SIZE(BT_SDP_UINT16), BT_SDP_ARRAY_16(0x0102)}, )}, )),
     BT_SDP_SERVICE_NAME("A2DP sink"),
 };
 
@@ -96,164 +73,131 @@ struct bt_a2dp_endpoint endpoint_2;
 
 struct bt_a2dp_codec_sbc_params sbc_info;
 
-void bt_a2dp_set_sbc_codec_info()
-{
-    sbc_info.config[0] =
-        //Sampling Frequency
-        A2DP_SBC_SAMP_FREQ_48000 |
-        A2DP_SBC_SAMP_FREQ_44100 |
-        A2DP_SBC_SAMP_FREQ_32000 |
-        A2DP_SBC_SAMP_FREQ_16000 |
-        //Channel Mode
-        A2DP_SBC_CH_MODE_JOINT |
-        A2DP_SBC_CH_MODE_STREO |
-        A2DP_SBC_CH_MODE_DUAL |
-        A2DP_SBC_CH_MODE_MONO;
-    sbc_info.config[1] =
-        //Block Length
-        A2DP_SBC_BLK_LEN_16 |
-        A2DP_SBC_BLK_LEN_12 |
-        A2DP_SBC_BLK_LEN_8 |
-        A2DP_SBC_BLK_LEN_4 |
-        //Subbands
-        A2DP_SBC_SUBBAND_8 |
-        A2DP_SBC_SUBBAND_4 |
-        //Allocation Method
-        A2DP_SBC_ALLOC_MTHD_SNR |
-        A2DP_SBC_ALLOC_MTHD_LOUDNESS;
-    sbc_info.min_bitpool = 2;
-    sbc_info.max_bitpool = 53;
+void bt_a2dp_set_sbc_codec_info() {
+  sbc_info.config[0] =
+      // Sampling Frequency
+      A2DP_SBC_SAMP_FREQ_48000 | A2DP_SBC_SAMP_FREQ_44100 | A2DP_SBC_SAMP_FREQ_32000 | A2DP_SBC_SAMP_FREQ_16000 |
+      // Channel Mode
+      A2DP_SBC_CH_MODE_JOINT | A2DP_SBC_CH_MODE_STREO | A2DP_SBC_CH_MODE_DUAL | A2DP_SBC_CH_MODE_MONO;
+  sbc_info.config[1] =
+      // Block Length
+      A2DP_SBC_BLK_LEN_16 | A2DP_SBC_BLK_LEN_12 | A2DP_SBC_BLK_LEN_8 | A2DP_SBC_BLK_LEN_4 |
+      // Subbands
+      A2DP_SBC_SUBBAND_8 | A2DP_SBC_SUBBAND_4 |
+      // Allocation Method
+      A2DP_SBC_ALLOC_MTHD_SNR | A2DP_SBC_ALLOC_MTHD_LOUDNESS;
+  sbc_info.min_bitpool = 2;
+  sbc_info.max_bitpool = 53;
 }
 
-void a2d_reset(struct bt_a2dp *a2dp_conn)
-{
-    (void)memset(a2dp_conn, 0, sizeof(struct bt_a2dp));
-}
+void a2d_reset(struct bt_a2dp *a2dp_conn) { (void)memset(a2dp_conn, 0, sizeof(struct bt_a2dp)); }
 
-void stream_reset(struct bt_avdtp_stream *stream_conn)
-{
-    (void)memset(stream_conn, 0, sizeof(struct bt_avdtp_stream));
-}
+void stream_reset(struct bt_avdtp_stream *stream_conn) { (void)memset(stream_conn, 0, sizeof(struct bt_avdtp_stream)); }
+
+struct bt_a2dp *get_new_connection(struct bt_conn *conn) {
+  int8_t i, free;
 
-struct bt_a2dp *get_new_connection(struct bt_conn *conn)
-{
-    int8_t i, free;
+  free = A2DP_NO_SPACE;
 
-    free = A2DP_NO_SPACE;
+  if (!conn) {
+    BT_ERR("Invalid Input (err: %d)", -EINVAL);
+    return NULL;
+  }
 
-    if (!conn) {
-        BT_ERR("Invalid Input (err: %d)", -EINVAL);
+  /* Find a space */
+  for (i = 0; i < CONFIG_BT_MAX_CONN; i++) {
+    if (connection[i].session.br_chan.chan.conn == conn) {
+      BT_DBG("Conn already exists");
+      if (!connection[i].session.streams->chan.chan.conn) {
+        BT_DBG("Create AV stream");
+        return &connection[i];
+      } else {
+        BT_DBG("A2DP signal stream and AV stream already exists");
         return NULL;
+      }
     }
 
-    /* Find a space */
-    for (i = 0; i < CONFIG_BT_MAX_CONN; i++) {
-        if (connection[i].session.br_chan.chan.conn == conn) {
-            BT_DBG("Conn already exists");
-            if (!connection[i].session.streams->chan.chan.conn) {
-                BT_DBG("Create AV stream");
-                return &connection[i];
-            } else {
-                BT_DBG("A2DP signal stream and AV stream already exists");
-                return NULL;
-            }
-        }
-
-        if (!connection[i].session.br_chan.chan.conn &&
-            free == A2DP_NO_SPACE) {
-            BT_DBG("Create signal stream");
-            free = i;
-        }
+    if (!connection[i].session.br_chan.chan.conn && free == A2DP_NO_SPACE) {
+      BT_DBG("Create signal stream");
+      free = i;
     }
+  }
 
-    if (free == A2DP_NO_SPACE) {
-        BT_DBG("More connection cannot be supported");
-        return NULL;
-    }
+  if (free == A2DP_NO_SPACE) {
+    BT_DBG("More connection cannot be supported");
+    return NULL;
+  }
 
-    /* Clean the memory area before returning */
-    a2d_reset(&connection[free]);
-    stream_reset(&stream[free]);
-    connection[free].session.streams = &stream[free];
+  /* Clean the memory area before returning */
+  a2d_reset(&connection[free]);
+  stream_reset(&stream[free]);
+  connection[free].session.streams = &stream[free];
 
-    return &connection[free];
+  return &connection[free];
 }
 
-int a2dp_accept(struct bt_conn *conn, struct bt_avdtp **session)
-{
-    struct bt_a2dp *a2dp_conn;
+int a2dp_accept(struct bt_conn *conn, struct bt_avdtp **session) {
+  struct bt_a2dp *a2dp_conn;
 
-    a2dp_conn = get_new_connection(conn);
-    if (!a2dp_conn) {
-        return -ENOMEM;
-    }
+  a2dp_conn = get_new_connection(conn);
+  if (!a2dp_conn) {
+    return -ENOMEM;
+  }
 
-    *session = &(a2dp_conn->session);
-    BT_DBG("session: %p", &(a2dp_conn->session));
+  *session = &(a2dp_conn->session);
+  BT_DBG("session: %p", &(a2dp_conn->session));
 
-    return 0;
+  return 0;
 }
 
-int a2dp_sbc_decode_init()
-{
-    OI_STATUS status = OI_CODEC_SBC_DecoderReset(&sbc_decoder.decoder_context,
-                                                 sbc_decoder.context_data,
-                                                 sizeof(sbc_decoder.context_data),
-                                                 2,
-                                                 2,
-                                                 false,
-                                                 false);
-    if (!OI_SUCCESS(status)) {
-        BT_ERR("decode init failed with error: %d\n", status);
-        return status;
-    }
+int a2dp_sbc_decode_init() {
+  OI_STATUS status = OI_CODEC_SBC_DecoderReset(&sbc_decoder.decoder_context, sbc_decoder.context_data, sizeof(sbc_decoder.context_data), 2, 2, false, false);
+  if (!OI_SUCCESS(status)) {
+    BT_ERR("decode init failed with error: %d\n", status);
+    return status;
+  }
 
-    return 0;
+  return 0;
 }
 
 #if PCM_PRINTF
-extern int16_t cool_edit[];
+extern int16_t  cool_edit[];
 extern uint32_t byte_index;
 #endif
-int a2dp_sbc_decode_process(uint8_t media_data[], uint16_t data_len)
-{
-    //remove media header, expose sbc frame
-    const OI_BYTE *data = media_data + 12 + 1;
-    OI_UINT32 data_size = data_len - 12 - 1;
-
-    if (data_size <= 0) {
-        BT_ERR("empty packet\n");
-        return -1;
-    }
+int a2dp_sbc_decode_process(uint8_t media_data[], uint16_t data_len) {
+  // remove media header, expose sbc frame
+  const OI_BYTE *data      = media_data + 12 + 1;
+  OI_UINT32      data_size = data_len - 12 - 1;
 
-    if (data[0] != 0x9c) {
-        BT_ERR("sbc frame syncword error \n");
-    }
+  if (data_size <= 0) {
+    BT_ERR("empty packet\n");
+    return -1;
+  }
 
-    OI_INT16 *pcm = sbc_decoder.decode_buf;
-    OI_UINT32 pcm_size = sizeof(sbc_decoder.decode_buf);
+  if (data[0] != 0x9c) {
+    BT_ERR("sbc frame syncword error \n");
+  }
 
-    OI_INT16 frame_count = OI_CODEC_SBC_FrameCount((OI_BYTE *)data, data_size);
-    BT_DBG("frame_count: %d\n", frame_count);
+  OI_INT16 *pcm      = sbc_decoder.decode_buf;
+  OI_UINT32 pcm_size = sizeof(sbc_decoder.decode_buf);
 
-    for (int i = 0; i < frame_count; i++) {
-        OI_STATUS status = OI_CODEC_SBC_DecodeFrame(&sbc_decoder.decoder_context,
-                                                    &data,
-                                                    &data_size,
-                                                    pcm,
-                                                    &pcm_size);
-        if (!OI_SUCCESS(status)) {
-            BT_ERR("decoding failure with error: %d \n", status);
-            return -1;
-        }
+  OI_INT16 frame_count = OI_CODEC_SBC_FrameCount((OI_BYTE *)data, data_size);
+  BT_DBG("frame_count: %d\n", frame_count);
+
+  for (int i = 0; i < frame_count; i++) {
+    OI_STATUS status = OI_CODEC_SBC_DecodeFrame(&sbc_decoder.decoder_context, &data, &data_size, pcm, &pcm_size);
+    if (!OI_SUCCESS(status)) {
+      BT_ERR("decoding failure with error: %d \n", status);
+      return -1;
+    }
 
 #if PCM_PRINTF
-        memcpy((OI_INT8 *)cool_edit + byte_index, pcm, pcm_size);
-        byte_index += pcm_size;
+    memcpy((OI_INT8 *)cool_edit + byte_index, pcm, pcm_size);
+    byte_index += pcm_size;
 #endif
-    }
+  }
 
-    return 0;
+  return 0;
 }
 
 /* Callback for incoming requests */
@@ -262,82 +206,75 @@ static struct bt_avdtp_ind_cb cb_ind = {
 };
 
 /* The above callback structures need to be packed and passed to AVDTP */
-static struct bt_avdtp_event_cb avdtp_cb = {
-    .ind = &cb_ind,
-    .accept = a2dp_accept
-};
-
-int bt_a2dp_init(void)
-{
-    int err;
-
-    /* Register event handlers with AVDTP */
-    err = bt_avdtp_register(&avdtp_cb);
-    if (err < 0) {
-        BT_ERR("A2DP registration failed");
-        return err;
-    }
-
-    /* Register SDP record */
-    err = bt_sdp_register_service(&a2dp_rec);
-    if (err < 0) {
-        BT_ERR("A2DP regist sdp record failed");
-        return err;
-    }
-
-    int reg_1 = bt_a2dp_register_endpoint(&endpoint_1, BT_A2DP_AUDIO, BT_A2DP_SINK);
-    int reg_2 = bt_a2dp_register_endpoint(&endpoint_2, BT_A2DP_AUDIO, BT_A2DP_SINK);
-    if (reg_1 || reg_2) {
-        BT_ERR("A2DP registration endpoint 1 failed");
-        return err;
-    }
-
-    bt_a2dp_set_sbc_codec_info();
-
-    err = a2dp_sbc_decode_init();
-    if (err < 0) {
-        BT_ERR("sbc codec init failed");
-        return err;
-    }
-
-    BT_DBG("A2DP Initialized successfully.");
-    return 0;
+static struct bt_avdtp_event_cb avdtp_cb = {.ind = &cb_ind, .accept = a2dp_accept};
+
+int bt_a2dp_init(void) {
+  int err;
+
+  /* Register event handlers with AVDTP */
+  err = bt_avdtp_register(&avdtp_cb);
+  if (err < 0) {
+    BT_ERR("A2DP registration failed");
+    return err;
+  }
+
+  /* Register SDP record */
+  err = bt_sdp_register_service(&a2dp_rec);
+  if (err < 0) {
+    BT_ERR("A2DP regist sdp record failed");
+    return err;
+  }
+
+  int reg_1 = bt_a2dp_register_endpoint(&endpoint_1, BT_A2DP_AUDIO, BT_A2DP_SINK);
+  int reg_2 = bt_a2dp_register_endpoint(&endpoint_2, BT_A2DP_AUDIO, BT_A2DP_SINK);
+  if (reg_1 || reg_2) {
+    BT_ERR("A2DP registration endpoint 1 failed");
+    return err;
+  }
+
+  bt_a2dp_set_sbc_codec_info();
+
+  err = a2dp_sbc_decode_init();
+  if (err < 0) {
+    BT_ERR("sbc codec init failed");
+    return err;
+  }
+
+  BT_DBG("A2DP Initialized successfully.");
+  return 0;
 }
 
-struct bt_a2dp *bt_a2dp_connect(struct bt_conn *conn)
-{
-    struct bt_a2dp *a2dp_conn;
-    int err;
-
-    a2dp_conn = get_new_connection(conn);
-    if (!a2dp_conn) {
-        BT_ERR("Cannot allocate memory");
-        return NULL;
-    }
-
-    err = bt_avdtp_connect(conn, &(a2dp_conn->session));
-    if (err < 0) {
-        /* If error occurs, undo the saving and return the error */
-        a2d_reset(a2dp_conn);
-        BT_DBG("AVDTP Connect failed");
-        return NULL;
-    }
-
-    BT_DBG("Connect request sent");
-    return a2dp_conn;
+struct bt_a2dp *bt_a2dp_connect(struct bt_conn *conn) {
+  struct bt_a2dp *a2dp_conn;
+  int             err;
+
+  a2dp_conn = get_new_connection(conn);
+  if (!a2dp_conn) {
+    BT_ERR("Cannot allocate memory");
+    return NULL;
+  }
+
+  err = bt_avdtp_connect(conn, &(a2dp_conn->session));
+  if (err < 0) {
+    /* If error occurs, undo the saving and return the error */
+    a2d_reset(a2dp_conn);
+    BT_DBG("AVDTP Connect failed");
+    return NULL;
+  }
+
+  BT_DBG("Connect request sent");
+  return a2dp_conn;
 }
 
-int bt_a2dp_register_endpoint(struct bt_a2dp_endpoint *endpoint,
-                              uint8_t media_type, uint8_t role)
-{
-    int err;
+int bt_a2dp_register_endpoint(struct bt_a2dp_endpoint *endpoint, uint8_t media_type, uint8_t role) {
+  int err;
 
-    BT_ASSERT(endpoint);
+  BT_ASSERT(endpoint);
 
-    err = bt_avdtp_register_sep(media_type, role, &(endpoint->info));
-    if (err < 0) {
-        return err;
-    }
+  err = bt_avdtp_register_sep(media_type, role, &(endpoint->info));
+  if (err < 0) {
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/at.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/at.c
index 189ff4b2a6..0f1feaf496 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/at.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/at.c
@@ -9,295 +9,264 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
 #include 
-#include 
-#include 
+#include 
 #include 
+#include 
+#include 
 
 #include "at.h"
 
-static void next_list(struct at_client *at)
-{
-    if (at->buf[at->pos] == ',') {
-        at->pos++;
-    }
+static void next_list(struct at_client *at) {
+  if (at->buf[at->pos] == ',') {
+    at->pos++;
+  }
 }
 
-int at_check_byte(struct net_buf *buf, char check_byte)
-{
-    const unsigned char *str = buf->data;
+int at_check_byte(struct net_buf *buf, char check_byte) {
+  const unsigned char *str = buf->data;
 
-    if (*str != check_byte) {
-        return -EINVAL;
-    }
-    net_buf_pull(buf, 1);
+  if (*str != check_byte) {
+    return -EINVAL;
+  }
+  net_buf_pull(buf, 1);
 
-    return 0;
+  return 0;
 }
 
-static void skip_space(struct at_client *at)
-{
-    while (at->buf[at->pos] == ' ') {
-        at->pos++;
-    }
+static void skip_space(struct at_client *at) {
+  while (at->buf[at->pos] == ' ') {
+    at->pos++;
+  }
 }
 
-int at_get_number(struct at_client *at, uint32_t *val)
-{
-    uint32_t i;
+int at_get_number(struct at_client *at, uint32_t *val) {
+  uint32_t i;
 
-    skip_space(at);
+  skip_space(at);
 
-    for (i = 0U, *val = 0U;
-         isdigit((unsigned char)at->buf[at->pos]);
-         at->pos++, i++) {
-        *val = *val * 10U + at->buf[at->pos] - '0';
-    }
+  for (i = 0U, *val = 0U; isdigit((unsigned char)at->buf[at->pos]); at->pos++, i++) {
+    *val = *val * 10U + at->buf[at->pos] - '0';
+  }
 
-    if (i == 0U) {
-        return -ENODATA;
-    }
+  if (i == 0U) {
+    return -ENODATA;
+  }
 
-    next_list(at);
-    return 0;
+  next_list(at);
+  return 0;
 }
 
-static bool str_has_prefix(const char *str, const char *prefix)
-{
-    if (strncmp(str, prefix, strlen(prefix)) != 0) {
-        return false;
-    }
+static bool str_has_prefix(const char *str, const char *prefix) {
+  if (strncmp(str, prefix, strlen(prefix)) != 0) {
+    return false;
+  }
 
-    return true;
+  return true;
 }
 
-static int at_parse_result(const char *str, struct net_buf *buf,
-                           enum at_result *result)
-{
-    /* Map the result and check for end lf */
-    if ((!strncmp(str, "OK", 2)) && (at_check_byte(buf, '\n') == 0)) {
-        *result = AT_RESULT_OK;
-        return 0;
-    }
+static int at_parse_result(const char *str, struct net_buf *buf, enum at_result *result) {
+  /* Map the result and check for end lf */
+  if ((!strncmp(str, "OK", 2)) && (at_check_byte(buf, '\n') == 0)) {
+    *result = AT_RESULT_OK;
+    return 0;
+  }
 
-    if ((!strncmp(str, "ERROR", 5)) && (at_check_byte(buf, '\n')) == 0) {
-        *result = AT_RESULT_ERROR;
-        return 0;
-    }
+  if ((!strncmp(str, "ERROR", 5)) && (at_check_byte(buf, '\n')) == 0) {
+    *result = AT_RESULT_ERROR;
+    return 0;
+  }
 
-    return -ENOMSG;
+  return -ENOMSG;
 }
 
-static int get_cmd_value(struct at_client *at, struct net_buf *buf,
-                         char stop_byte, enum at_cmd_state cmd_state)
-{
-    int cmd_len = 0;
-    uint8_t pos = at->pos;
-    const char *str = (char *)buf->data;
-
-    while (cmd_len < buf->len && at->pos != at->buf_max_len) {
-        if (*str != stop_byte) {
-            at->buf[at->pos++] = *str;
-            cmd_len++;
-            str++;
-            pos = at->pos;
-        } else {
-            cmd_len++;
-            at->buf[at->pos] = '\0';
-            at->pos = 0U;
-            at->cmd_state = cmd_state;
-            break;
-        }
-    }
-    net_buf_pull(buf, cmd_len);
+static int get_cmd_value(struct at_client *at, struct net_buf *buf, char stop_byte, enum at_cmd_state cmd_state) {
+  int         cmd_len = 0;
+  uint8_t     pos     = at->pos;
+  const char *str     = (char *)buf->data;
 
-    if (pos == at->buf_max_len) {
-        return -ENOBUFS;
+  while (cmd_len < buf->len && at->pos != at->buf_max_len) {
+    if (*str != stop_byte) {
+      at->buf[at->pos++] = *str;
+      cmd_len++;
+      str++;
+      pos = at->pos;
+    } else {
+      cmd_len++;
+      at->buf[at->pos] = '\0';
+      at->pos          = 0U;
+      at->cmd_state    = cmd_state;
+      break;
     }
+  }
+  net_buf_pull(buf, cmd_len);
 
-    return 0;
+  if (pos == at->buf_max_len) {
+    return -ENOBUFS;
+  }
+
+  return 0;
 }
 
-static int get_response_string(struct at_client *at, struct net_buf *buf,
-                               char stop_byte, enum at_state state)
-{
-    int cmd_len = 0;
-    uint8_t pos = at->pos;
-    const char *str = (char *)buf->data;
-
-    while (cmd_len < buf->len && at->pos != at->buf_max_len) {
-        if (*str != stop_byte) {
-            at->buf[at->pos++] = *str;
-            cmd_len++;
-            str++;
-            pos = at->pos;
-        } else {
-            cmd_len++;
-            at->buf[at->pos] = '\0';
-            at->pos = 0U;
-            at->state = state;
-            break;
-        }
-    }
-    net_buf_pull(buf, cmd_len);
+static int get_response_string(struct at_client *at, struct net_buf *buf, char stop_byte, enum at_state state) {
+  int         cmd_len = 0;
+  uint8_t     pos     = at->pos;
+  const char *str     = (char *)buf->data;
 
-    if (pos == at->buf_max_len) {
-        return -ENOBUFS;
+  while (cmd_len < buf->len && at->pos != at->buf_max_len) {
+    if (*str != stop_byte) {
+      at->buf[at->pos++] = *str;
+      cmd_len++;
+      str++;
+      pos = at->pos;
+    } else {
+      cmd_len++;
+      at->buf[at->pos] = '\0';
+      at->pos          = 0U;
+      at->state        = state;
+      break;
     }
+  }
+  net_buf_pull(buf, cmd_len);
 
-    return 0;
+  if (pos == at->buf_max_len) {
+    return -ENOBUFS;
+  }
+
+  return 0;
 }
 
-static void reset_buffer(struct at_client *at)
-{
-    (void)memset(at->buf, 0, at->buf_max_len);
-    at->pos = 0U;
+static void reset_buffer(struct at_client *at) {
+  (void)memset(at->buf, 0, at->buf_max_len);
+  at->pos = 0U;
 }
 
-static int at_state_start(struct at_client *at, struct net_buf *buf)
-{
-    int err;
+static int at_state_start(struct at_client *at, struct net_buf *buf) {
+  int err;
 
-    err = at_check_byte(buf, '\r');
-    if (err < 0) {
-        return err;
-    }
-    at->state = AT_STATE_START_CR;
+  err = at_check_byte(buf, '\r');
+  if (err < 0) {
+    return err;
+  }
+  at->state = AT_STATE_START_CR;
 
-    return 0;
+  return 0;
 }
 
-static int at_state_start_cr(struct at_client *at, struct net_buf *buf)
-{
-    int err;
+static int at_state_start_cr(struct at_client *at, struct net_buf *buf) {
+  int err;
 
-    err = at_check_byte(buf, '\n');
-    if (err < 0) {
-        return err;
-    }
-    at->state = AT_STATE_START_LF;
+  err = at_check_byte(buf, '\n');
+  if (err < 0) {
+    return err;
+  }
+  at->state = AT_STATE_START_LF;
 
-    return 0;
+  return 0;
 }
 
-static int at_state_start_lf(struct at_client *at, struct net_buf *buf)
-{
-    reset_buffer(at);
-    if (at_check_byte(buf, '+') == 0) {
-        at->state = AT_STATE_GET_CMD_STRING;
-        return 0;
-    } else if (isalpha(*buf->data)) {
-        at->state = AT_STATE_GET_RESULT_STRING;
-        return 0;
-    }
+static int at_state_start_lf(struct at_client *at, struct net_buf *buf) {
+  reset_buffer(at);
+  if (at_check_byte(buf, '+') == 0) {
+    at->state = AT_STATE_GET_CMD_STRING;
+    return 0;
+  } else if (isalpha(*buf->data)) {
+    at->state = AT_STATE_GET_RESULT_STRING;
+    return 0;
+  }
 
-    return -ENODATA;
+  return -ENODATA;
 }
 
-static int at_state_get_cmd_string(struct at_client *at, struct net_buf *buf)
-{
-    return get_response_string(at, buf, ':', AT_STATE_PROCESS_CMD);
-}
+static int at_state_get_cmd_string(struct at_client *at, struct net_buf *buf) { return get_response_string(at, buf, ':', AT_STATE_PROCESS_CMD); }
 
-static bool is_cmer(struct at_client *at)
-{
-    if (strncmp(at->buf, "CME ERROR", 9) == 0) {
-        return true;
-    }
+static bool is_cmer(struct at_client *at) {
+  if (strncmp(at->buf, "CME ERROR", 9) == 0) {
+    return true;
+  }
 
-    return false;
+  return false;
 }
 
-static int at_state_process_cmd(struct at_client *at, struct net_buf *buf)
-{
-    if (is_cmer(at)) {
-        at->state = AT_STATE_PROCESS_AG_NW_ERR;
-        return 0;
-    }
+static int at_state_process_cmd(struct at_client *at, struct net_buf *buf) {
+  if (is_cmer(at)) {
+    at->state = AT_STATE_PROCESS_AG_NW_ERR;
+    return 0;
+  }
 
-    if (at->resp) {
-        at->resp(at, buf);
-        at->resp = NULL;
-        return 0;
-    }
-    at->state = AT_STATE_UNSOLICITED_CMD;
+  if (at->resp) {
+    at->resp(at, buf);
+    at->resp = NULL;
     return 0;
+  }
+  at->state = AT_STATE_UNSOLICITED_CMD;
+  return 0;
 }
 
-static int at_state_get_result_string(struct at_client *at, struct net_buf *buf)
-{
-    return get_response_string(at, buf, '\r', AT_STATE_PROCESS_RESULT);
-}
+static int at_state_get_result_string(struct at_client *at, struct net_buf *buf) { return get_response_string(at, buf, '\r', AT_STATE_PROCESS_RESULT); }
 
-static bool is_ring(struct at_client *at)
-{
-    if (strncmp(at->buf, "RING", 4) == 0) {
-        return true;
-    }
+static bool is_ring(struct at_client *at) {
+  if (strncmp(at->buf, "RING", 4) == 0) {
+    return true;
+  }
 
-    return false;
+  return false;
 }
 
-static int at_state_process_result(struct at_client *at, struct net_buf *buf)
-{
-    enum at_cme cme_err;
-    enum at_result result;
+static int at_state_process_result(struct at_client *at, struct net_buf *buf) {
+  enum at_cme    cme_err;
+  enum at_result result;
 
-    if (is_ring(at)) {
-        at->state = AT_STATE_UNSOLICITED_CMD;
-        return 0;
-    }
+  if (is_ring(at)) {
+    at->state = AT_STATE_UNSOLICITED_CMD;
+    return 0;
+  }
 
-    if (at_parse_result(at->buf, buf, &result) == 0) {
-        if (at->finish) {
-            /* cme_err is 0 - Is invalid until result is
-			 * AT_RESULT_CME_ERROR
-			 */
-            cme_err = 0;
-            at->finish(at, result, cme_err);
-        }
+  if (at_parse_result(at->buf, buf, &result) == 0) {
+    if (at->finish) {
+      /* cme_err is 0 - Is invalid until result is
+       * AT_RESULT_CME_ERROR
+       */
+      cme_err = 0;
+      at->finish(at, result, cme_err);
     }
+  }
 
-    /* Reset the state to process unsolicited response */
-    at->cmd_state = AT_CMD_START;
-    at->state = AT_STATE_START;
+  /* Reset the state to process unsolicited response */
+  at->cmd_state = AT_CMD_START;
+  at->state     = AT_STATE_START;
 
-    return 0;
+  return 0;
 }
 
-int cme_handle(struct at_client *at)
-{
-    enum at_cme cme_err;
-    uint32_t val;
+int cme_handle(struct at_client *at) {
+  enum at_cme cme_err;
+  uint32_t    val;
 
-    if (!at_get_number(at, &val) && val <= CME_ERROR_NETWORK_NOT_ALLOWED) {
-        cme_err = val;
-    } else {
-        cme_err = CME_ERROR_UNKNOWN;
-    }
+  if (!at_get_number(at, &val) && val <= CME_ERROR_NETWORK_NOT_ALLOWED) {
+    cme_err = val;
+  } else {
+    cme_err = CME_ERROR_UNKNOWN;
+  }
 
-    if (at->finish) {
-        at->finish(at, AT_RESULT_CME_ERROR, cme_err);
-    }
+  if (at->finish) {
+    at->finish(at, AT_RESULT_CME_ERROR, cme_err);
+  }
 
-    return 0;
+  return 0;
 }
 
-static int at_state_process_ag_nw_err(struct at_client *at, struct net_buf *buf)
-{
-    at->cmd_state = AT_CMD_GET_VALUE;
-    return at_parse_cmd_input(at, buf, NULL, cme_handle,
-                              AT_CMD_TYPE_NORMAL);
+static int at_state_process_ag_nw_err(struct at_client *at, struct net_buf *buf) {
+  at->cmd_state = AT_CMD_GET_VALUE;
+  return at_parse_cmd_input(at, buf, NULL, cme_handle, AT_CMD_TYPE_NORMAL);
 }
 
-static int at_state_unsolicited_cmd(struct at_client *at, struct net_buf *buf)
-{
-    if (at->unsolicited) {
-        return at->unsolicited(at, buf);
-    }
+static int at_state_unsolicited_cmd(struct at_client *at, struct net_buf *buf) {
+  if (at->unsolicited) {
+    return at->unsolicited(at, buf);
+  }
 
-    return -ENODATA;
+  return -ENODATA;
 }
 
 /* The order of handler function should match the enum at_state */
@@ -313,84 +282,71 @@ static handle_parse_input_t parser_cb[] = {
     at_state_unsolicited_cmd    /* AT_STATE_UNSOLICITED_CMD */
 };
 
-int at_parse_input(struct at_client *at, struct net_buf *buf)
-{
-    int ret;
-
-    while (buf->len) {
-        if (at->state < AT_STATE_START || at->state >= AT_STATE_END) {
-            return -EINVAL;
-        }
-        ret = parser_cb[at->state](at, buf);
-        if (ret < 0) {
-            /* Reset the state in case of error */
-            at->cmd_state = AT_CMD_START;
-            at->state = AT_STATE_START;
-            return ret;
-        }
+int at_parse_input(struct at_client *at, struct net_buf *buf) {
+  int ret;
+
+  while (buf->len) {
+    if (at->state < AT_STATE_START || at->state >= AT_STATE_END) {
+      return -EINVAL;
     }
+    ret = parser_cb[at->state](at, buf);
+    if (ret < 0) {
+      /* Reset the state in case of error */
+      at->cmd_state = AT_CMD_START;
+      at->state     = AT_STATE_START;
+      return ret;
+    }
+  }
 
-    return 0;
+  return 0;
 }
 
-static int at_cmd_start(struct at_client *at, struct net_buf *buf,
-                        const char *prefix, parse_val_t func,
-                        enum at_cmd_type type)
-{
-    if (!str_has_prefix(at->buf, prefix)) {
-        if (type == AT_CMD_TYPE_NORMAL) {
-            at->state = AT_STATE_UNSOLICITED_CMD;
-        }
-        return -ENODATA;
-    }
-
-    if (type == AT_CMD_TYPE_OTHER) {
-        /* Skip for Other type such as ..RING.. which does not have
-		 * values to get processed.
-		 */
-        at->cmd_state = AT_CMD_PROCESS_VALUE;
-    } else {
-        at->cmd_state = AT_CMD_GET_VALUE;
+static int at_cmd_start(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type) {
+  if (!str_has_prefix(at->buf, prefix)) {
+    if (type == AT_CMD_TYPE_NORMAL) {
+      at->state = AT_STATE_UNSOLICITED_CMD;
     }
+    return -ENODATA;
+  }
+
+  if (type == AT_CMD_TYPE_OTHER) {
+    /* Skip for Other type such as ..RING.. which does not have
+     * values to get processed.
+     */
+    at->cmd_state = AT_CMD_PROCESS_VALUE;
+  } else {
+    at->cmd_state = AT_CMD_GET_VALUE;
+  }
 
-    return 0;
+  return 0;
 }
 
-static int at_cmd_get_value(struct at_client *at, struct net_buf *buf,
-                            const char *prefix, parse_val_t func,
-                            enum at_cmd_type type)
-{
-    /* Reset buffer before getting the values */
-    reset_buffer(at);
-    return get_cmd_value(at, buf, '\r', AT_CMD_PROCESS_VALUE);
+static int at_cmd_get_value(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type) {
+  /* Reset buffer before getting the values */
+  reset_buffer(at);
+  return get_cmd_value(at, buf, '\r', AT_CMD_PROCESS_VALUE);
 }
 
-static int at_cmd_process_value(struct at_client *at, struct net_buf *buf,
-                                const char *prefix, parse_val_t func,
-                                enum at_cmd_type type)
-{
-    int ret;
+static int at_cmd_process_value(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type) {
+  int ret;
 
-    ret = func(at);
-    at->cmd_state = AT_CMD_STATE_END_LF;
+  ret           = func(at);
+  at->cmd_state = AT_CMD_STATE_END_LF;
 
-    return ret;
+  return ret;
 }
 
-static int at_cmd_state_end_lf(struct at_client *at, struct net_buf *buf,
-                               const char *prefix, parse_val_t func,
-                               enum at_cmd_type type)
-{
-    int err;
+static int at_cmd_state_end_lf(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type) {
+  int err;
 
-    err = at_check_byte(buf, '\n');
-    if (err < 0) {
-        return err;
-    }
+  err = at_check_byte(buf, '\n');
+  if (err < 0) {
+    return err;
+  }
 
-    at->cmd_state = AT_CMD_START;
-    at->state = AT_STATE_START;
-    return 0;
+  at->cmd_state = AT_CMD_START;
+  at->state     = AT_STATE_START;
+  return 0;
 }
 
 /* The order of handler function should match the enum at_cmd_state */
@@ -401,137 +357,122 @@ static handle_cmd_input_t cmd_parser_cb[] = {
     at_cmd_state_end_lf   /* AT_CMD_STATE_END_LF */
 };
 
-int at_parse_cmd_input(struct at_client *at, struct net_buf *buf,
-                       const char *prefix, parse_val_t func,
-                       enum at_cmd_type type)
-{
-    int ret;
-
-    while (buf->len) {
-        if (at->cmd_state < AT_CMD_START ||
-            at->cmd_state >= AT_CMD_STATE_END) {
-            return -EINVAL;
-        }
-        ret = cmd_parser_cb[at->cmd_state](at, buf, prefix, func, type);
-        if (ret < 0) {
-            return ret;
-        }
-        /* Check for main state, the end of cmd parsing and return. */
-        if (at->state == AT_STATE_START) {
-            return 0;
-        }
+int at_parse_cmd_input(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type) {
+  int ret;
+
+  while (buf->len) {
+    if (at->cmd_state < AT_CMD_START || at->cmd_state >= AT_CMD_STATE_END) {
+      return -EINVAL;
+    }
+    ret = cmd_parser_cb[at->cmd_state](at, buf, prefix, func, type);
+    if (ret < 0) {
+      return ret;
+    }
+    /* Check for main state, the end of cmd parsing and return. */
+    if (at->state == AT_STATE_START) {
+      return 0;
     }
+  }
 
-    return 0;
+  return 0;
 }
 
-int at_has_next_list(struct at_client *at)
-{
-    return at->buf[at->pos] != '\0';
-}
+int at_has_next_list(struct at_client *at) { return at->buf[at->pos] != '\0'; }
 
-int at_open_list(struct at_client *at)
-{
-    skip_space(at);
+int at_open_list(struct at_client *at) {
+  skip_space(at);
 
-    /* The list shall start with '(' open parenthesis */
-    if (at->buf[at->pos] != '(') {
-        return -ENODATA;
-    }
-    at->pos++;
+  /* The list shall start with '(' open parenthesis */
+  if (at->buf[at->pos] != '(') {
+    return -ENODATA;
+  }
+  at->pos++;
 
-    return 0;
+  return 0;
 }
 
-int at_close_list(struct at_client *at)
-{
-    skip_space(at);
+int at_close_list(struct at_client *at) {
+  skip_space(at);
 
-    if (at->buf[at->pos] != ')') {
-        return -ENODATA;
-    }
-    at->pos++;
+  if (at->buf[at->pos] != ')') {
+    return -ENODATA;
+  }
+  at->pos++;
 
-    next_list(at);
+  next_list(at);
 
-    return 0;
+  return 0;
 }
 
-int at_list_get_string(struct at_client *at, char *name, uint8_t len)
-{
-    int i = 0;
-
-    skip_space(at);
+int at_list_get_string(struct at_client *at, char *name, uint8_t len) {
+  int i = 0;
 
-    if (at->buf[at->pos] != '"') {
-        return -ENODATA;
-    }
-    at->pos++;
+  skip_space(at);
 
-    while (at->buf[at->pos] != '\0' && at->buf[at->pos] != '"') {
-        if (i == len) {
-            return -ENODATA;
-        }
-        name[i++] = at->buf[at->pos++];
-    }
+  if (at->buf[at->pos] != '"') {
+    return -ENODATA;
+  }
+  at->pos++;
 
+  while (at->buf[at->pos] != '\0' && at->buf[at->pos] != '"') {
     if (i == len) {
-        return -ENODATA;
+      return -ENODATA;
     }
+    name[i++] = at->buf[at->pos++];
+  }
 
-    name[i] = '\0';
+  if (i == len) {
+    return -ENODATA;
+  }
 
-    if (at->buf[at->pos] != '"') {
-        return -ENODATA;
-    }
-    at->pos++;
+  name[i] = '\0';
+
+  if (at->buf[at->pos] != '"') {
+    return -ENODATA;
+  }
+  at->pos++;
 
-    skip_space(at);
-    next_list(at);
+  skip_space(at);
+  next_list(at);
 
-    return 0;
+  return 0;
 }
 
-int at_list_get_range(struct at_client *at, uint32_t *min, uint32_t *max)
-{
-    uint32_t low, high;
-    int ret;
+int at_list_get_range(struct at_client *at, uint32_t *min, uint32_t *max) {
+  uint32_t low, high;
+  int      ret;
 
-    ret = at_get_number(at, &low);
-    if (ret < 0) {
-        return ret;
-    }
+  ret = at_get_number(at, &low);
+  if (ret < 0) {
+    return ret;
+  }
 
-    if (at->buf[at->pos] == '-') {
-        at->pos++;
-        goto out;
-    }
+  if (at->buf[at->pos] == '-') {
+    at->pos++;
+    goto out;
+  }
 
-    if (!isdigit((unsigned char)at->buf[at->pos])) {
-        return -ENODATA;
-    }
+  if (!isdigit((unsigned char)at->buf[at->pos])) {
+    return -ENODATA;
+  }
 out:
-    ret = at_get_number(at, &high);
-    if (ret < 0) {
-        return ret;
-    }
+  ret = at_get_number(at, &high);
+  if (ret < 0) {
+    return ret;
+  }
 
-    *min = low;
-    *max = high;
+  *min = low;
+  *max = high;
 
-    next_list(at);
+  next_list(at);
 
-    return 0;
+  return 0;
 }
 
-void at_register_unsolicited(struct at_client *at, at_resp_cb_t unsolicited)
-{
-    at->unsolicited = unsolicited;
-}
+void at_register_unsolicited(struct at_client *at, at_resp_cb_t unsolicited) { at->unsolicited = unsolicited; }
 
-void at_register(struct at_client *at, at_resp_cb_t resp, at_finish_cb_t finish)
-{
-    at->resp = resp;
-    at->finish = finish;
-    at->state = AT_STATE_START;
+void at_register(struct at_client *at, at_resp_cb_t resp, at_finish_cb_t finish) {
+  at->resp   = resp;
+  at->finish = finish;
+  at->state  = AT_STATE_START;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c
index d792f0b6e1..5796f5b38a 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c
@@ -6,29 +6,29 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
-#include 
-#include 
 #include 
+#include 
 #include 
 #include 
+#include 
+#include 
+#include 
 
-#include 
 #include 
-#include 
 #include 
 #include 
+#include 
+#include 
 
 #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_ATT)
 #include "log.h"
 
-#include "hci_core.h"
+#include "att_internal.h"
 #include "conn_internal.h"
+#include "gatt_internal.h"
+#include "hci_core.h"
 #include "l2cap_internal.h"
 #include "smp.h"
-#include "att_internal.h"
-#include "gatt_internal.h"
 
 #define ATT_CHAN(_ch)  CONTAINER_OF(_ch, struct bt_att, chan.chan)
 #define ATT_REQ(_node) CONTAINER_OF(_node, struct bt_att_req, node)
@@ -38,53 +38,52 @@
 #define ATT_TIMEOUT K_SECONDS(30)
 
 typedef enum __packed {
-    ATT_COMMAND,
-    ATT_REQUEST,
-    ATT_RESPONSE,
-    ATT_NOTIFICATION,
-    ATT_CONFIRMATION,
-    ATT_INDICATION,
-    ATT_UNKNOWN,
+  ATT_COMMAND,
+  ATT_REQUEST,
+  ATT_RESPONSE,
+  ATT_NOTIFICATION,
+  ATT_CONFIRMATION,
+  ATT_INDICATION,
+  ATT_UNKNOWN,
 } att_type_t;
 
 static att_type_t att_op_get_type(u8_t op);
 
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
 struct bt_attr_data {
-    u16_t handle;
-    u16_t offset;
+  u16_t handle;
+  u16_t offset;
 };
 
 #if !defined(BFLB_DYNAMIC_ALLOC_MEM)
 /* Pool for incoming ATT packets */
-NET_BUF_POOL_DEFINE(prep_pool, CONFIG_BT_ATT_PREPARE_COUNT, BT_ATT_MTU,
-                    sizeof(struct bt_attr_data), NULL);
+NET_BUF_POOL_DEFINE(prep_pool, CONFIG_BT_ATT_PREPARE_COUNT, BT_ATT_MTU, sizeof(struct bt_attr_data), NULL);
 #else
 struct net_buf_pool prep_pool;
 #endif
 #endif /* CONFIG_BT_ATT_PREPARE_COUNT */
 
 enum {
-    ATT_PENDING_RSP,
-    ATT_PENDING_CFM,
-    ATT_DISCONNECTED,
+  ATT_PENDING_RSP,
+  ATT_PENDING_CFM,
+  ATT_DISCONNECTED,
 
-    /* Total number of flags - must be at the end of the enum */
-    ATT_NUM_FLAGS,
+  /* Total number of flags - must be at the end of the enum */
+  ATT_NUM_FLAGS,
 };
 
 /* ATT channel specific context */
 struct bt_att {
-    /* The channel this context is associated with */
-    struct bt_l2cap_le_chan chan;
-    ATOMIC_DEFINE(flags, ATT_NUM_FLAGS);
-    struct bt_att_req *req;
-    sys_slist_t reqs;
-    struct k_delayed_work timeout_work;
-    struct k_sem tx_sem;
-    struct k_fifo tx_queue;
+  /* The channel this context is associated with */
+  struct bt_l2cap_le_chan chan;
+  ATOMIC_DEFINE(flags, ATT_NUM_FLAGS);
+  struct bt_att_req    *req;
+  sys_slist_t           reqs;
+  struct k_delayed_work timeout_work;
+  struct k_sem          tx_sem;
+  struct k_fifo         tx_queue;
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
-    struct k_fifo prep_queue;
+  struct k_fifo prep_queue;
 #endif
 };
 
@@ -92,2359 +91,2108 @@ struct bt_att {
 extern volatile u8_t event_flag;
 #endif
 
-static struct bt_att bt_req_pool[CONFIG_BT_MAX_CONN];
+static struct bt_att     bt_req_pool[CONFIG_BT_MAX_CONN];
 static struct bt_att_req cancel;
 
 #if defined(CONFIG_BLE_AT_CMD)
 static u16_t mtu_size = BT_ATT_MTU;
-void set_mtu_size(u16_t size)
-{
-    mtu_size = size;
-}
+void         set_mtu_size(u16_t size) { mtu_size = size; }
 #endif
 
-static void att_req_destroy(struct bt_att_req *req)
-{
-    BT_DBG("req %p", req);
+static void att_req_destroy(struct bt_att_req *req) {
+  BT_DBG("req %p", req);
 
-    if (req->buf) {
-        net_buf_unref(req->buf);
-    }
+  if (req->buf) {
+    net_buf_unref(req->buf);
+  }
 
-    if (req->destroy) {
-        req->destroy(req);
-    }
+  if (req->destroy) {
+    req->destroy(req);
+  }
 
-    (void)memset(req, 0, sizeof(*req));
+  (void)memset(req, 0, sizeof(*req));
 }
 
-static struct bt_att *att_get(struct bt_conn *conn)
-{
-    struct bt_l2cap_chan *chan;
+static struct bt_att *att_get(struct bt_conn *conn) {
+  struct bt_l2cap_chan *chan;
 
-    chan = bt_l2cap_le_lookup_tx_cid(conn, BT_L2CAP_CID_ATT);
-    __ASSERT(chan, "No ATT channel found");
+  chan = bt_l2cap_le_lookup_tx_cid(conn, BT_L2CAP_CID_ATT);
+  __ASSERT(chan, "No ATT channel found");
 
-    return CONTAINER_OF(chan, struct bt_att, chan);
+  return CONTAINER_OF(chan, struct bt_att, chan);
 }
 
 static bt_conn_tx_cb_t att_cb(struct net_buf *buf);
 
-static int att_send(struct bt_conn *conn, struct net_buf *buf,
-                    bt_conn_tx_cb_t cb, void *user_data)
-{
-    struct bt_att_hdr *hdr;
+static int att_send(struct bt_conn *conn, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data) {
+  struct bt_att_hdr *hdr;
 
-    hdr = (void *)buf->data;
+  hdr = (void *)buf->data;
 
-    BT_DBG("code 0x%02x", hdr->code);
+  BT_DBG("code 0x%02x", hdr->code);
 
 #if defined(CONFIG_BT_SMP) && defined(CONFIG_BT_SIGNING)
-    if (hdr->code == BT_ATT_OP_SIGNED_WRITE_CMD) {
-        int err;
-
-        err = bt_smp_sign(conn, buf);
-        if (err) {
-            BT_ERR("Error signing data");
-            net_buf_unref(buf);
-            return err;
-        }
+  if (hdr->code == BT_ATT_OP_SIGNED_WRITE_CMD) {
+    int err;
+
+    err = bt_smp_sign(conn, buf);
+    if (err) {
+      BT_ERR("Error signing data");
+      net_buf_unref(buf);
+      return err;
     }
+  }
 #endif
-    return bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf,
-                            cb ? cb : att_cb(buf),
-                            user_data);
+  return bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, cb ? cb : att_cb(buf), user_data);
 }
 
-void att_pdu_sent(struct bt_conn *conn, void *user_data)
-{
-    struct bt_att *att = att_get(conn);
-    struct net_buf *buf;
+void att_pdu_sent(struct bt_conn *conn, void *user_data) {
+  struct bt_att  *att = att_get(conn);
+  struct net_buf *buf;
 
-    BT_DBG("conn %p att %p", conn, att);
+  BT_DBG("conn %p att %p", conn, att);
 
-    while ((buf = net_buf_get(&att->tx_queue, K_NO_WAIT))) {
-        /* Check if the queued buf is a request */
-        if (att->req && att->req->buf == buf) {
-            /* Save request state so it can be resent */
-            net_buf_simple_save(&att->req->buf->b,
-                                &att->req->state);
-        }
+  while ((buf = net_buf_get(&att->tx_queue, K_NO_WAIT))) {
+    /* Check if the queued buf is a request */
+    if (att->req && att->req->buf == buf) {
+      /* Save request state so it can be resent */
+      net_buf_simple_save(&att->req->buf->b, &att->req->state);
+    }
 
-        if (!att_send(conn, buf, NULL, NULL)) {
-            return;
-        }
+    if (!att_send(conn, buf, NULL, NULL)) {
+      return;
     }
+  }
 
-    k_sem_give(&att->tx_sem);
+  k_sem_give(&att->tx_sem);
 }
 
-void att_cfm_sent(struct bt_conn *conn, void *user_data)
-{
-    struct bt_att *att = att_get(conn);
+void att_cfm_sent(struct bt_conn *conn, void *user_data) {
+  struct bt_att *att = att_get(conn);
 
-    BT_DBG("conn %p att %p", conn, att);
+  BT_DBG("conn %p att %p", conn, att);
 
-    if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
-        atomic_clear_bit(att->flags, ATT_PENDING_CFM);
-    }
+  if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
+    atomic_clear_bit(att->flags, ATT_PENDING_CFM);
+  }
 
-    att_pdu_sent(conn, user_data);
+  att_pdu_sent(conn, user_data);
 }
 
-void att_rsp_sent(struct bt_conn *conn, void *user_data)
-{
-    struct bt_att *att = att_get(conn);
+void att_rsp_sent(struct bt_conn *conn, void *user_data) {
+  struct bt_att *att = att_get(conn);
 
-    BT_DBG("conn %p att %p", conn, att);
+  BT_DBG("conn %p att %p", conn, att);
 
-    if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
-        atomic_clear_bit(att->flags, ATT_PENDING_RSP);
-    }
+  if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
+    atomic_clear_bit(att->flags, ATT_PENDING_RSP);
+  }
 
-    att_pdu_sent(conn, user_data);
+  att_pdu_sent(conn, user_data);
 }
 
-void att_req_sent(struct bt_conn *conn, void *user_data)
-{
-    struct bt_att *att = att_get(conn);
+void att_req_sent(struct bt_conn *conn, void *user_data) {
+  struct bt_att *att = att_get(conn);
 
-    BT_DBG("conn %p att %p att->req %p", conn, att, att->req);
+  BT_DBG("conn %p att %p att->req %p", conn, att, att->req);
 
-    /* Start timeout work */
-    if (att->req) {
-        k_delayed_work_submit(&att->timeout_work, ATT_TIMEOUT);
-    }
+  /* Start timeout work */
+  if (att->req) {
+    k_delayed_work_submit(&att->timeout_work, ATT_TIMEOUT);
+  }
 
-    att_pdu_sent(conn, user_data);
-}
-
-static bt_conn_tx_cb_t att_cb(struct net_buf *buf)
-{
-    switch (att_op_get_type(buf->data[0])) {
-        case ATT_RESPONSE:
-            return att_rsp_sent;
-        case ATT_CONFIRMATION:
-            return att_cfm_sent;
-        case ATT_REQUEST:
-        case ATT_INDICATION:
-            return att_req_sent;
-        default:
-            return att_pdu_sent;
-    }
+  att_pdu_sent(conn, user_data);
 }
 
-static void send_err_rsp(struct bt_conn *conn, u8_t req, u16_t handle,
-                         u8_t err)
-{
-    struct bt_att_error_rsp *rsp;
-    struct net_buf *buf;
+static bt_conn_tx_cb_t att_cb(struct net_buf *buf) {
+  switch (att_op_get_type(buf->data[0])) {
+  case ATT_RESPONSE:
+    return att_rsp_sent;
+  case ATT_CONFIRMATION:
+    return att_cfm_sent;
+  case ATT_REQUEST:
+  case ATT_INDICATION:
+    return att_req_sent;
+  default:
+    return att_pdu_sent;
+  }
+}
 
-    /* Ignore opcode 0x00 */
-    if (!req) {
-        return;
-    }
+static void send_err_rsp(struct bt_conn *conn, u8_t req, u16_t handle, u8_t err) {
+  struct bt_att_error_rsp *rsp;
+  struct net_buf          *buf;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_ERROR_RSP, sizeof(*rsp));
-    if (!buf) {
-        return;
-    }
+  /* Ignore opcode 0x00 */
+  if (!req) {
+    return;
+  }
 
-    rsp = net_buf_add(buf, sizeof(*rsp));
-    rsp->request = req;
-    rsp->handle = sys_cpu_to_le16(handle);
-    rsp->error = err;
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_ERROR_RSP, sizeof(*rsp));
+  if (!buf) {
+    return;
+  }
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_rsp_sent, NULL);
+  rsp          = net_buf_add(buf, sizeof(*rsp));
+  rsp->request = req;
+  rsp->handle  = sys_cpu_to_le16(handle);
+  rsp->error   = err;
+
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_rsp_sent, NULL);
 }
 
-static u8_t att_mtu_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct bt_att_exchange_mtu_req *req;
-    struct bt_att_exchange_mtu_rsp *rsp;
-    struct net_buf *pdu;
-    u16_t mtu_client, mtu_server;
+static u8_t att_mtu_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn                 *conn = att->chan.chan.conn;
+  struct bt_att_exchange_mtu_req *req;
+  struct bt_att_exchange_mtu_rsp *rsp;
+  struct net_buf                 *pdu;
+  u16_t                           mtu_client, mtu_server;
 
-    req = (void *)buf->data;
+  req = (void *)buf->data;
 
-    mtu_client = sys_le16_to_cpu(req->mtu);
+  mtu_client = sys_le16_to_cpu(req->mtu);
 
-    BT_DBG("Client MTU %u", mtu_client);
+  BT_DBG("Client MTU %u", mtu_client);
 
-    /* Check if MTU is valid */
-    if (mtu_client < BT_ATT_DEFAULT_LE_MTU) {
-        return BT_ATT_ERR_INVALID_PDU;
-    }
+  /* Check if MTU is valid */
+  if (mtu_client < BT_ATT_DEFAULT_LE_MTU) {
+    return BT_ATT_ERR_INVALID_PDU;
+  }
 
-    pdu = bt_att_create_pdu(conn, BT_ATT_OP_MTU_RSP, sizeof(*rsp));
-    if (!pdu) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  pdu = bt_att_create_pdu(conn, BT_ATT_OP_MTU_RSP, sizeof(*rsp));
+  if (!pdu) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    mtu_server = BT_ATT_MTU;
+  mtu_server = BT_ATT_MTU;
 
-    BT_DBG("Server MTU %u", mtu_server);
+  BT_DBG("Server MTU %u", mtu_server);
 
-    rsp = net_buf_add(pdu, sizeof(*rsp));
-    rsp->mtu = sys_cpu_to_le16(mtu_server);
+  rsp      = net_buf_add(pdu, sizeof(*rsp));
+  rsp->mtu = sys_cpu_to_le16(mtu_server);
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, pdu, att_rsp_sent, NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, pdu, att_rsp_sent, NULL);
 
-    /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 484:
-	 *
-	 * A device's Exchange MTU Request shall contain the same MTU as the
-	 * device's Exchange MTU Response (i.e. the MTU shall be symmetric).
-	 */
-    att->chan.rx.mtu = MIN(mtu_client, mtu_server);
-    att->chan.tx.mtu = att->chan.rx.mtu;
+  /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 484:
+   *
+   * A device's Exchange MTU Request shall contain the same MTU as the
+   * device's Exchange MTU Response (i.e. the MTU shall be symmetric).
+   */
+  att->chan.rx.mtu = MIN(mtu_client, mtu_server);
+  att->chan.tx.mtu = att->chan.rx.mtu;
 
-    BT_DBG("Negotiated MTU %u", att->chan.rx.mtu);
+  BT_DBG("Negotiated MTU %u", att->chan.rx.mtu);
 
 #if defined(BFLB_BLE_MTU_CHANGE_CB)
-    if (att->chan.chan.ops->mtu_changed)
-        att->chan.chan.ops->mtu_changed(&(att->chan.chan), att->chan.rx.mtu);
+  if (att->chan.chan.ops->mtu_changed)
+    att->chan.chan.ops->mtu_changed(&(att->chan.chan), att->chan.rx.mtu);
 #endif
 
-    return 0;
+  return 0;
 }
 
-static inline bool att_is_connected(struct bt_att *att)
-{
-    return (att->chan.chan.conn->state != BT_CONN_CONNECTED ||
-            !atomic_test_bit(att->flags, ATT_DISCONNECTED));
-}
+static inline bool att_is_connected(struct bt_att *att) { return (att->chan.chan.conn->state != BT_CONN_CONNECTED || !atomic_test_bit(att->flags, ATT_DISCONNECTED)); }
 
-static int att_send_req(struct bt_att *att, struct bt_att_req *req)
-{
-    int err;
+static int att_send_req(struct bt_att *att, struct bt_att_req *req) {
+  int err;
 
-    __ASSERT_NO_MSG(req);
-    __ASSERT_NO_MSG(req->func);
-    __ASSERT_NO_MSG(!att->req);
+  __ASSERT_NO_MSG(req);
+  __ASSERT_NO_MSG(req->func);
+  __ASSERT_NO_MSG(!att->req);
 
-    BT_DBG("req %p", req);
+  BT_DBG("req %p", req);
 
-    att->req = req;
+  att->req = req;
 
-    if (k_sem_take(&att->tx_sem, K_NO_WAIT) < 0) {
-        k_fifo_put(&att->tx_queue, req->buf);
-        return 0;
-    }
+  if (k_sem_take(&att->tx_sem, K_NO_WAIT) < 0) {
+    k_fifo_put(&att->tx_queue, req->buf);
+    return 0;
+  }
 
-    /* Save request state so it can be resent */
-    net_buf_simple_save(&req->buf->b, &req->state);
+  /* Save request state so it can be resent */
+  net_buf_simple_save(&req->buf->b, &req->state);
 
-    /* Keep a reference for resending in case of an error */
-    err = bt_l2cap_send_cb(att->chan.chan.conn, BT_L2CAP_CID_ATT,
-                           net_buf_ref(req->buf), att_cb(req->buf), NULL);
-    if (err) {
-        net_buf_unref(req->buf);
-        req->buf = NULL;
-        return err;
-    }
+  /* Keep a reference for resending in case of an error */
+  err = bt_l2cap_send_cb(att->chan.chan.conn, BT_L2CAP_CID_ATT, net_buf_ref(req->buf), att_cb(req->buf), NULL);
+  if (err) {
+    net_buf_unref(req->buf);
+    req->buf = NULL;
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-static void att_process(struct bt_att *att)
-{
-    sys_snode_t *node;
+static void att_process(struct bt_att *att) {
+  sys_snode_t *node;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    /* Pull next request from the list */
-    node = sys_slist_get(&att->reqs);
-    if (!node) {
-        return;
-    }
+  /* Pull next request from the list */
+  node = sys_slist_get(&att->reqs);
+  if (!node) {
+    return;
+  }
 
-    att_send_req(att, ATT_REQ(node));
+  att_send_req(att, ATT_REQ(node));
 }
 
-static u8_t att_handle_rsp(struct bt_att *att, void *pdu, u16_t len, u8_t err)
-{
-    bt_att_func_t func;
+static u8_t att_handle_rsp(struct bt_att *att, void *pdu, u16_t len, u8_t err) {
+  bt_att_func_t func;
 
-    BT_DBG("err 0x%02x len %u: %s", err, len, bt_hex(pdu, len));
+  BT_DBG("err 0x%02x len %u: %s", err, len, bt_hex(pdu, len));
 
-    /* Cancel timeout if ongoing */
-    k_delayed_work_cancel(&att->timeout_work);
+  /* Cancel timeout if ongoing */
+  k_delayed_work_cancel(&att->timeout_work);
 
-    if (!att->req) {
-        BT_WARN("No pending ATT request");
-        goto process;
-    }
+  if (!att->req) {
+    BT_WARN("No pending ATT request");
+    goto process;
+  }
 
-    /* Check if request has been cancelled */
-    if (att->req == &cancel) {
-        att->req = NULL;
-        goto process;
-    }
+  /* Check if request has been cancelled */
+  if (att->req == &cancel) {
+    att->req = NULL;
+    goto process;
+  }
 
-    /* Release original buffer */
-    if (att->req->buf) {
-        net_buf_unref(att->req->buf);
-        att->req->buf = NULL;
-    }
+  /* Release original buffer */
+  if (att->req->buf) {
+    net_buf_unref(att->req->buf);
+    att->req->buf = NULL;
+  }
 
-    /* Reset func so it can be reused by the callback */
-    func = att->req->func;
-    att->req->func = NULL;
+  /* Reset func so it can be reused by the callback */
+  func           = att->req->func;
+  att->req->func = NULL;
 
-    func(att->chan.chan.conn, err, pdu, len, att->req);
+  func(att->chan.chan.conn, err, pdu, len, att->req);
 
-    /* Don't destroy if callback had reused the request */
-    if (!att->req->func) {
-        att_req_destroy(att->req);
-    }
+  /* Don't destroy if callback had reused the request */
+  if (!att->req->func) {
+    att_req_destroy(att->req);
+  }
 
-    att->req = NULL;
+  att->req = NULL;
 
 process:
-    /* Process pending requests */
-    att_process(att);
+  /* Process pending requests */
+  att_process(att);
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_GATT_CLIENT)
-static u8_t att_mtu_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_att_exchange_mtu_rsp *rsp;
-    u16_t mtu;
+static u8_t att_mtu_rsp(struct bt_att *att, struct net_buf *buf) {
+  struct bt_att_exchange_mtu_rsp *rsp;
+  u16_t                           mtu;
 
-    if (!att) {
-        return 0;
-    }
+  if (!att) {
+    return 0;
+  }
 
-    rsp = (void *)buf->data;
+  rsp = (void *)buf->data;
 
-    mtu = sys_le16_to_cpu(rsp->mtu);
+  mtu = sys_le16_to_cpu(rsp->mtu);
 
-    BT_DBG("Server MTU %u", mtu);
+  BT_DBG("Server MTU %u", mtu);
 
-    /* Check if MTU is valid */
-    if (mtu < BT_ATT_DEFAULT_LE_MTU) {
-        return att_handle_rsp(att, NULL, 0, BT_ATT_ERR_INVALID_PDU);
-    }
+  /* Check if MTU is valid */
+  if (mtu < BT_ATT_DEFAULT_LE_MTU) {
+    return att_handle_rsp(att, NULL, 0, BT_ATT_ERR_INVALID_PDU);
+  }
 
-    att->chan.rx.mtu = MIN(mtu, BT_ATT_MTU);
+  att->chan.rx.mtu = MIN(mtu, BT_ATT_MTU);
 
-    /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 484:
-	 *
-	 * A device's Exchange MTU Request shall contain the same MTU as the
-	 * device's Exchange MTU Response (i.e. the MTU shall be symmetric).
-	 */
-    att->chan.tx.mtu = att->chan.rx.mtu;
+  /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 484:
+   *
+   * A device's Exchange MTU Request shall contain the same MTU as the
+   * device's Exchange MTU Response (i.e. the MTU shall be symmetric).
+   */
+  att->chan.tx.mtu = att->chan.rx.mtu;
 
-    BT_DBG("Negotiated MTU %u", att->chan.rx.mtu);
+  BT_DBG("Negotiated MTU %u", att->chan.rx.mtu);
 
-    return att_handle_rsp(att, rsp, buf->len, 0);
+  return att_handle_rsp(att, rsp, buf->len, 0);
 }
 #endif /* CONFIG_BT_GATT_CLIENT */
 
-static bool range_is_valid(u16_t start, u16_t end, u16_t *err)
-{
-    /* Handle 0 is invalid */
-    if (!start || !end) {
-        if (err) {
-            *err = 0U;
-        }
-        return false;
+static bool range_is_valid(u16_t start, u16_t end, u16_t *err) {
+  /* Handle 0 is invalid */
+  if (!start || !end) {
+    if (err) {
+      *err = 0U;
     }
+    return false;
+  }
 
-    /* Check if range is valid */
-    if (start > end) {
-        if (err) {
-            *err = start;
-        }
-        return false;
+  /* Check if range is valid */
+  if (start > end) {
+    if (err) {
+      *err = start;
     }
+    return false;
+  }
 
-    return true;
+  return true;
 }
 
 struct find_info_data {
-    struct bt_att *att;
-    struct net_buf *buf;
-    struct bt_att_find_info_rsp *rsp;
-    union {
-        struct bt_att_info_16 *info16;
-        struct bt_att_info_128 *info128;
-    };
+  struct bt_att               *att;
+  struct net_buf              *buf;
+  struct bt_att_find_info_rsp *rsp;
+  union {
+    struct bt_att_info_16  *info16;
+    struct bt_att_info_128 *info128;
+  };
 };
 
-static u8_t find_info_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct find_info_data *data = user_data;
-    struct bt_att *att = data->att;
+static u8_t find_info_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct find_info_data *data = user_data;
+  struct bt_att         *att  = data->att;
 
-    BT_DBG("handle 0x%04x", attr->handle);
+  BT_DBG("handle 0x%04x", attr->handle);
 
-    /* Initialize rsp at first entry */
-    if (!data->rsp) {
-        data->rsp = net_buf_add(data->buf, sizeof(*data->rsp));
-        data->rsp->format = (attr->uuid->type == BT_UUID_TYPE_16) ?
-                                BT_ATT_INFO_16 :
-                                BT_ATT_INFO_128;
-    }
+  /* Initialize rsp at first entry */
+  if (!data->rsp) {
+    data->rsp         = net_buf_add(data->buf, sizeof(*data->rsp));
+    data->rsp->format = (attr->uuid->type == BT_UUID_TYPE_16) ? BT_ATT_INFO_16 : BT_ATT_INFO_128;
+  }
 
-    switch (data->rsp->format) {
-        case BT_ATT_INFO_16:
-            if (attr->uuid->type != BT_UUID_TYPE_16) {
-                return BT_GATT_ITER_STOP;
-            }
-
-            /* Fast forward to next item position */
-            data->info16 = net_buf_add(data->buf, sizeof(*data->info16));
-            data->info16->handle = sys_cpu_to_le16(attr->handle);
-            data->info16->uuid = sys_cpu_to_le16(BT_UUID_16(attr->uuid)->val);
-
-            if (att->chan.tx.mtu - data->buf->len >
-                sizeof(*data->info16)) {
-                return BT_GATT_ITER_CONTINUE;
-            }
-
-            break;
-        case BT_ATT_INFO_128:
-            if (attr->uuid->type != BT_UUID_TYPE_128) {
-                return BT_GATT_ITER_STOP;
-            }
-
-            /* Fast forward to next item position */
-            data->info128 = net_buf_add(data->buf, sizeof(*data->info128));
-            data->info128->handle = sys_cpu_to_le16(attr->handle);
-            memcpy(data->info128->uuid, BT_UUID_128(attr->uuid)->val,
-                   sizeof(data->info128->uuid));
-
-            if (att->chan.tx.mtu - data->buf->len >
-                sizeof(*data->info128)) {
-                return BT_GATT_ITER_CONTINUE;
-            }
+  switch (data->rsp->format) {
+  case BT_ATT_INFO_16:
+    if (attr->uuid->type != BT_UUID_TYPE_16) {
+      return BT_GATT_ITER_STOP;
     }
 
-    return BT_GATT_ITER_STOP;
-}
-
-static u8_t att_find_info_rsp(struct bt_att *att, u16_t start_handle,
-                              u16_t end_handle)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct find_info_data data;
+    /* Fast forward to next item position */
+    data->info16         = net_buf_add(data->buf, sizeof(*data->info16));
+    data->info16->handle = sys_cpu_to_le16(attr->handle);
+    data->info16->uuid   = sys_cpu_to_le16(BT_UUID_16(attr->uuid)->val);
 
-    (void)memset(&data, 0, sizeof(data));
+    if (att->chan.tx.mtu - data->buf->len > sizeof(*data->info16)) {
+      return BT_GATT_ITER_CONTINUE;
+    }
 
-    data.buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_INFO_RSP, 0);
-    if (!data.buf) {
-        return BT_ATT_ERR_UNLIKELY;
+    break;
+  case BT_ATT_INFO_128:
+    if (attr->uuid->type != BT_UUID_TYPE_128) {
+      return BT_GATT_ITER_STOP;
     }
 
-    data.att = att;
-    bt_gatt_foreach_attr(start_handle, end_handle, find_info_cb, &data);
+    /* Fast forward to next item position */
+    data->info128         = net_buf_add(data->buf, sizeof(*data->info128));
+    data->info128->handle = sys_cpu_to_le16(attr->handle);
+    memcpy(data->info128->uuid, BT_UUID_128(attr->uuid)->val, sizeof(data->info128->uuid));
 
-    if (!data.rsp) {
-        net_buf_unref(data.buf);
-        /* Respond since handle is set */
-        send_err_rsp(conn, BT_ATT_OP_FIND_INFO_REQ, start_handle,
-                     BT_ATT_ERR_ATTRIBUTE_NOT_FOUND);
-        return 0;
+    if (att->chan.tx.mtu - data->buf->len > sizeof(*data->info128)) {
+      return BT_GATT_ITER_CONTINUE;
     }
+  }
+
+  return BT_GATT_ITER_STOP;
+}
+
+static u8_t att_find_info_rsp(struct bt_att *att, u16_t start_handle, u16_t end_handle) {
+  struct bt_conn       *conn = att->chan.chan.conn;
+  struct find_info_data data;
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent,
-                           NULL);
+  (void)memset(&data, 0, sizeof(data));
 
+  data.buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_INFO_RSP, 0);
+  if (!data.buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
+
+  data.att = att;
+  bt_gatt_foreach_attr(start_handle, end_handle, find_info_cb, &data);
+
+  if (!data.rsp) {
+    net_buf_unref(data.buf);
+    /* Respond since handle is set */
+    send_err_rsp(conn, BT_ATT_OP_FIND_INFO_REQ, start_handle, BT_ATT_ERR_ATTRIBUTE_NOT_FOUND);
     return 0;
+  }
+
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
+
+  return 0;
 }
 
-static u8_t att_find_info_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct bt_att_find_info_req *req;
-    u16_t start_handle, end_handle, err_handle;
+static u8_t att_find_info_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn              *conn = att->chan.chan.conn;
+  struct bt_att_find_info_req *req;
+  u16_t                        start_handle, end_handle, err_handle;
 
-    req = (void *)buf->data;
+  req = (void *)buf->data;
 
-    start_handle = sys_le16_to_cpu(req->start_handle);
-    end_handle = sys_le16_to_cpu(req->end_handle);
+  start_handle = sys_le16_to_cpu(req->start_handle);
+  end_handle   = sys_le16_to_cpu(req->end_handle);
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x", start_handle,
-           end_handle);
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x", start_handle, end_handle);
 
-    if (!range_is_valid(start_handle, end_handle, &err_handle)) {
-        send_err_rsp(conn, BT_ATT_OP_FIND_INFO_REQ, err_handle,
-                     BT_ATT_ERR_INVALID_HANDLE);
-        return 0;
-    }
+  if (!range_is_valid(start_handle, end_handle, &err_handle)) {
+    send_err_rsp(conn, BT_ATT_OP_FIND_INFO_REQ, err_handle, BT_ATT_ERR_INVALID_HANDLE);
+    return 0;
+  }
 
-    return att_find_info_rsp(att, start_handle, end_handle);
+  return att_find_info_rsp(att, start_handle, end_handle);
 }
 
 struct find_type_data {
-    struct bt_att *att;
-    struct net_buf *buf;
-    struct bt_att_handle_group *group;
-    const void *value;
-    u8_t value_len;
-    u8_t err;
+  struct bt_att              *att;
+  struct net_buf             *buf;
+  struct bt_att_handle_group *group;
+  const void                 *value;
+  u8_t                        value_len;
+  u8_t                        err;
 };
 
-static u8_t find_type_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct find_type_data *data = user_data;
-    struct bt_att *att = data->att;
-    struct bt_conn *conn = att->chan.chan.conn;
-    int read;
-    u8_t uuid[16];
-
-    /* Skip secondary services */
-    if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) {
-        goto skip;
-    }
+static u8_t find_type_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct find_type_data *data = user_data;
+  struct bt_att         *att  = data->att;
+  struct bt_conn        *conn = att->chan.chan.conn;
+  int                    read;
+  u8_t                   uuid[16];
 
-    /* Update group end_handle if not a primary service */
-    if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY)) {
-        if (data->group &&
-            attr->handle > sys_le16_to_cpu(data->group->end_handle)) {
-            data->group->end_handle = sys_cpu_to_le16(attr->handle);
-        }
-        return BT_GATT_ITER_CONTINUE;
+  /* Skip secondary services */
+  if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) {
+    goto skip;
+  }
+
+  /* Update group end_handle if not a primary service */
+  if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY)) {
+    if (data->group && attr->handle > sys_le16_to_cpu(data->group->end_handle)) {
+      data->group->end_handle = sys_cpu_to_le16(attr->handle);
     }
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    BT_DBG("handle 0x%04x", attr->handle);
+  BT_DBG("handle 0x%04x", attr->handle);
 
-    /* stop if there is no space left */
-    if (att->chan.tx.mtu - data->buf->len < sizeof(*data->group)) {
-        return BT_GATT_ITER_STOP;
-    }
+  /* stop if there is no space left */
+  if (att->chan.tx.mtu - data->buf->len < sizeof(*data->group)) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    /* Read attribute value and store in the buffer */
-    read = attr->read(conn, attr, uuid, sizeof(uuid), 0);
-    if (read < 0) {
-        /*
-		 * Since we don't know if it is the service with requested UUID,
-		 * we cannot respond with an error to this request.
-		 */
-        goto skip;
-    }
+  /* Read attribute value and store in the buffer */
+  read = attr->read(conn, attr, uuid, sizeof(uuid), 0);
+  if (read < 0) {
+    /*
+     * Since we don't know if it is the service with requested UUID,
+     * we cannot respond with an error to this request.
+     */
+    goto skip;
+  }
+
+  /* Check if data matches */
+  if (read != data->value_len) {
+    /* Use bt_uuid_cmp() to compare UUIDs of different form. */
+    struct bt_uuid_128 ref_uuid;
+    struct bt_uuid_128 recvd_uuid;
 
-    /* Check if data matches */
-    if (read != data->value_len) {
-        /* Use bt_uuid_cmp() to compare UUIDs of different form. */
-        struct bt_uuid_128 ref_uuid;
-        struct bt_uuid_128 recvd_uuid;
-
-        if (!bt_uuid_create(&recvd_uuid.uuid, data->value, data->value_len)) {
-            BT_WARN("Unable to create UUID: size %u", data->value_len);
-            goto skip;
-        }
-        if (!bt_uuid_create(&ref_uuid.uuid, uuid, read)) {
-            BT_WARN("Unable to create UUID: size %d", read);
-            goto skip;
-        }
-        if (bt_uuid_cmp(&recvd_uuid.uuid, &ref_uuid.uuid)) {
-            goto skip;
-        }
-    } else if (memcmp(data->value, uuid, read)) {
-        goto skip;
+    if (!bt_uuid_create(&recvd_uuid.uuid, data->value, data->value_len)) {
+      BT_WARN("Unable to create UUID: size %u", data->value_len);
+      goto skip;
     }
+    if (!bt_uuid_create(&ref_uuid.uuid, uuid, read)) {
+      BT_WARN("Unable to create UUID: size %d", read);
+      goto skip;
+    }
+    if (bt_uuid_cmp(&recvd_uuid.uuid, &ref_uuid.uuid)) {
+      goto skip;
+    }
+  } else if (memcmp(data->value, uuid, read)) {
+    goto skip;
+  }
 
-    /* If service has been found, error should be cleared */
-    data->err = 0x00;
+  /* If service has been found, error should be cleared */
+  data->err = 0x00;
 
-    /* Fast forward to next item position */
-    data->group = net_buf_add(data->buf, sizeof(*data->group));
-    data->group->start_handle = sys_cpu_to_le16(attr->handle);
-    data->group->end_handle = sys_cpu_to_le16(attr->handle);
+  /* Fast forward to next item position */
+  data->group               = net_buf_add(data->buf, sizeof(*data->group));
+  data->group->start_handle = sys_cpu_to_le16(attr->handle);
+  data->group->end_handle   = sys_cpu_to_le16(attr->handle);
 
-    /* continue to find the end_handle */
-    return BT_GATT_ITER_CONTINUE;
+  /* continue to find the end_handle */
+  return BT_GATT_ITER_CONTINUE;
 
 skip:
-    data->group = NULL;
-    return BT_GATT_ITER_CONTINUE;
+  data->group = NULL;
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static u8_t att_find_type_rsp(struct bt_att *att, u16_t start_handle,
-                              u16_t end_handle, const void *value,
-                              u8_t value_len)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct find_type_data data;
+static u8_t att_find_type_rsp(struct bt_att *att, u16_t start_handle, u16_t end_handle, const void *value, u8_t value_len) {
+  struct bt_conn       *conn = att->chan.chan.conn;
+  struct find_type_data data;
 
-    (void)memset(&data, 0, sizeof(data));
+  (void)memset(&data, 0, sizeof(data));
 
-    data.buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_TYPE_RSP, 0);
-    if (!data.buf) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  data.buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_TYPE_RSP, 0);
+  if (!data.buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    data.att = att;
-    data.group = NULL;
-    data.value = value;
-    data.value_len = value_len;
+  data.att       = att;
+  data.group     = NULL;
+  data.value     = value;
+  data.value_len = value_len;
 
-    /* Pre-set error in case no service will be found */
-    data.err = BT_ATT_ERR_ATTRIBUTE_NOT_FOUND;
+  /* Pre-set error in case no service will be found */
+  data.err = BT_ATT_ERR_ATTRIBUTE_NOT_FOUND;
 
-    bt_gatt_foreach_attr(start_handle, end_handle, find_type_cb, &data);
+  bt_gatt_foreach_attr(start_handle, end_handle, find_type_cb, &data);
 
-    /* If error has not been cleared, no service has been found */
-    if (data.err) {
-        net_buf_unref(data.buf);
-        /* Respond since handle is set */
-        send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, start_handle,
-                     data.err);
+  /* If error has not been cleared, no service has been found */
+  if (data.err) {
+    net_buf_unref(data.buf);
+    /* Respond since handle is set */
+    send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, start_handle, data.err);
 
 #if defined(CONFIG_BT_STACK_PTS)
-        /*PTS sends a request to the iut discover all primary services it contains */
-        if (event_flag == att_find_by_type_value_ind) {
-            BT_PTS("rsp err : [%d] start_handle = [0x%04x]\r\n", data.err, start_handle);
-        }
-#endif
-        return 0;
+    /*PTS sends a request to the iut discover all primary services it contains */
+    if (event_flag == att_find_by_type_value_ind) {
+      BT_PTS("rsp err : [%d] start_handle = [0x%04x]\r\n", data.err, start_handle);
     }
+#endif
+    return 0;
+  }
 
 #if defined(CONFIG_BT_STACK_PTS)
-    /*when PTS sends a request to the iut discover all primary services it contains, set event flag 
-	 * to @att_find_by_type_value_ind make it easy for the user to check whether the messages is correct in the console.
-	 */
-    if (event_flag == att_find_by_type_value_ind) {
-        u8_t i = 0;
-        u8_t *req_val = (u8_t *)data.value;
-        u8_t src[20];
-
-        (void)memcpy(src, req_val, data.value_len);
+  /*when PTS sends a request to the iut discover all primary services it contains, set event flag
+   * to @att_find_by_type_value_ind make it easy for the user to check whether the messages is correct in the console.
+   */
+  if (event_flag == att_find_by_type_value_ind) {
+    u8_t  i       = 0;
+    u8_t *req_val = (u8_t *)data.value;
+    u8_t  src[20];
 
-        BT_PTS("uuid = [");
-        for (i = 0; i < value_len; i++) {
-            BT_PTS("%02x", src[value_len - 1 - i]);
-        }
-        BT_PTS("]\r\n");
+    (void)memcpy(src, req_val, data.value_len);
 
-        BT_PTS("start_handle = [0x%04x] end_handle = [0x%04x]\r\n", data.buf->data[1] | data.buf->data[2] << 8,
-               data.buf->data[3] | data.buf->data[4] << 8);
+    BT_PTS("uuid = [");
+    for (i = 0; i < value_len; i++) {
+      BT_PTS("%02x", src[value_len - 1 - i]);
     }
+    BT_PTS("]\r\n");
+
+    BT_PTS("start_handle = [0x%04x] end_handle = [0x%04x]\r\n", data.buf->data[1] | data.buf->data[2] << 8, data.buf->data[3] | data.buf->data[4] << 8);
+  }
 #endif
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent,
-                           NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
 
-    return 0;
+  return 0;
 }
 
-static u8_t att_find_type_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct bt_att_find_type_req *req;
-    u16_t start_handle, end_handle, err_handle, type;
-    u8_t *value;
-
-    req = net_buf_pull_mem(buf, sizeof(*req));
+static u8_t att_find_type_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn              *conn = att->chan.chan.conn;
+  struct bt_att_find_type_req *req;
+  u16_t                        start_handle, end_handle, err_handle, type;
+  u8_t                        *value;
 
-    start_handle = sys_le16_to_cpu(req->start_handle);
-    end_handle = sys_le16_to_cpu(req->end_handle);
-    type = sys_le16_to_cpu(req->type);
-    value = buf->data;
+  req = net_buf_pull_mem(buf, sizeof(*req));
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x type %u", start_handle,
-           end_handle, type);
+  start_handle = sys_le16_to_cpu(req->start_handle);
+  end_handle   = sys_le16_to_cpu(req->end_handle);
+  type         = sys_le16_to_cpu(req->type);
+  value        = buf->data;
 
-    if (!range_is_valid(start_handle, end_handle, &err_handle)) {
-        send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, err_handle,
-                     BT_ATT_ERR_INVALID_HANDLE);
-        return 0;
-    }
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x type %u", start_handle, end_handle, type);
 
-    /* The Attribute Protocol Find By Type Value Request shall be used with
-	 * the Attribute Type parameter set to the UUID for "Primary Service"
-	 * and the Attribute Value set to the 16-bit Bluetooth UUID or 128-bit
-	 * UUID for the specific primary service.
-	 */
-    if (bt_uuid_cmp(BT_UUID_DECLARE_16(type), BT_UUID_GATT_PRIMARY)) {
-        send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, start_handle,
-                     BT_ATT_ERR_ATTRIBUTE_NOT_FOUND);
-        return 0;
-    }
+  if (!range_is_valid(start_handle, end_handle, &err_handle)) {
+    send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, err_handle, BT_ATT_ERR_INVALID_HANDLE);
+    return 0;
+  }
+
+  /* The Attribute Protocol Find By Type Value Request shall be used with
+   * the Attribute Type parameter set to the UUID for "Primary Service"
+   * and the Attribute Value set to the 16-bit Bluetooth UUID or 128-bit
+   * UUID for the specific primary service.
+   */
+  if (bt_uuid_cmp(BT_UUID_DECLARE_16(type), BT_UUID_GATT_PRIMARY)) {
+    send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, start_handle, BT_ATT_ERR_ATTRIBUTE_NOT_FOUND);
+    return 0;
+  }
 
-    return att_find_type_rsp(att, start_handle, end_handle, value,
-                             buf->len);
+  return att_find_type_rsp(att, start_handle, end_handle, value, buf->len);
 }
 
-static u8_t err_to_att(int err)
-{
-    BT_DBG("%d", err);
+static u8_t err_to_att(int err) {
+  BT_DBG("%d", err);
 
-    if (err < 0 && err >= -0xff) {
-        return -err;
-    }
+  if (err < 0 && err >= -0xff) {
+    return -err;
+  }
 
-    return BT_ATT_ERR_UNLIKELY;
+  return BT_ATT_ERR_UNLIKELY;
 }
 
 struct read_type_data {
-    struct bt_att *att;
-    struct bt_uuid *uuid;
-    struct net_buf *buf;
-    struct bt_att_read_type_rsp *rsp;
-    struct bt_att_data *item;
-    u8_t err;
+  struct bt_att               *att;
+  struct bt_uuid              *uuid;
+  struct net_buf              *buf;
+  struct bt_att_read_type_rsp *rsp;
+  struct bt_att_data          *item;
+  u8_t                         err;
 };
 
-static u8_t read_type_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct read_type_data *data = user_data;
-    struct bt_att *att = data->att;
-    struct bt_conn *conn = att->chan.chan.conn;
-    int read;
-
-    /* Skip if doesn't match */
-    if (bt_uuid_cmp(attr->uuid, data->uuid)) {
-        return BT_GATT_ITER_CONTINUE;
-    }
-
-    BT_DBG("handle 0x%04x", attr->handle);
-
-    /*
-	 * If an attribute in the set of requested attributes would cause an
-	 * Error Response then this attribute cannot be included in a
-	 * Read By Type Response and the attributes before this attribute
-	 * shall be returned
-	 *
-	 * If the first attribute in the set of requested attributes would
-	 * cause an Error Response then no other attributes in the requested
-	 * attributes can be considered.
-	 */
-    data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK);
-    if (data->err) {
-        if (data->rsp->len) {
-            data->err = 0x00;
-        }
-        return BT_GATT_ITER_STOP;
-    }
-
-    /*
-	 * If any attribute is founded in handle range it means that error
-	 * should be changed from pre-set: attr not found error to no error.
-	 */
-    data->err = 0x00;
+static u8_t read_type_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct read_type_data *data = user_data;
+  struct bt_att         *att  = data->att;
+  struct bt_conn        *conn = att->chan.chan.conn;
+  int                    read;
 
-    /* Fast forward to next item position */
-    data->item = net_buf_add(data->buf, sizeof(*data->item));
-    data->item->handle = sys_cpu_to_le16(attr->handle);
-
-    /* Read attribute value and store in the buffer */
-    read = attr->read(conn, attr, data->buf->data + data->buf->len,
-                      att->chan.tx.mtu - data->buf->len, 0);
-    if (read < 0) {
-        data->err = err_to_att(read);
-        return BT_GATT_ITER_STOP;
-    }
-
-    if (!data->rsp->len) {
-        /* Set len to be the first item found */
-        data->rsp->len = read + sizeof(*data->item);
-    } else if (data->rsp->len != read + sizeof(*data->item)) {
-        /* All items should have the same size */
-        data->buf->len -= sizeof(*data->item);
-        return BT_GATT_ITER_STOP;
+  /* Skip if doesn't match */
+  if (bt_uuid_cmp(attr->uuid, data->uuid)) {
+    return BT_GATT_ITER_CONTINUE;
+  }
+
+  BT_DBG("handle 0x%04x", attr->handle);
+
+  /*
+   * If an attribute in the set of requested attributes would cause an
+   * Error Response then this attribute cannot be included in a
+   * Read By Type Response and the attributes before this attribute
+   * shall be returned
+   *
+   * If the first attribute in the set of requested attributes would
+   * cause an Error Response then no other attributes in the requested
+   * attributes can be considered.
+   */
+  data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK);
+  if (data->err) {
+    if (data->rsp->len) {
+      data->err = 0x00;
     }
+    return BT_GATT_ITER_STOP;
+  }
+
+  /*
+   * If any attribute is founded in handle range it means that error
+   * should be changed from pre-set: attr not found error to no error.
+   */
+  data->err = 0x00;
+
+  /* Fast forward to next item position */
+  data->item         = net_buf_add(data->buf, sizeof(*data->item));
+  data->item->handle = sys_cpu_to_le16(attr->handle);
+
+  /* Read attribute value and store in the buffer */
+  read = attr->read(conn, attr, data->buf->data + data->buf->len, att->chan.tx.mtu - data->buf->len, 0);
+  if (read < 0) {
+    data->err = err_to_att(read);
+    return BT_GATT_ITER_STOP;
+  }
+
+  if (!data->rsp->len) {
+    /* Set len to be the first item found */
+    data->rsp->len = read + sizeof(*data->item);
+  } else if (data->rsp->len != read + sizeof(*data->item)) {
+    /* All items should have the same size */
+    data->buf->len -= sizeof(*data->item);
+    return BT_GATT_ITER_STOP;
+  }
 
-    net_buf_add(data->buf, read);
+  net_buf_add(data->buf, read);
 
-    /* return true only if there are still space for more items */
-    return att->chan.tx.mtu - data->buf->len > data->rsp->len ?
-               BT_GATT_ITER_CONTINUE :
-               BT_GATT_ITER_STOP;
+  /* return true only if there are still space for more items */
+  return att->chan.tx.mtu - data->buf->len > data->rsp->len ? BT_GATT_ITER_CONTINUE : BT_GATT_ITER_STOP;
 }
 
-static u8_t att_read_type_rsp(struct bt_att *att, struct bt_uuid *uuid,
-                              u16_t start_handle, u16_t end_handle)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct read_type_data data;
+static u8_t att_read_type_rsp(struct bt_att *att, struct bt_uuid *uuid, u16_t start_handle, u16_t end_handle) {
+  struct bt_conn       *conn = att->chan.chan.conn;
+  struct read_type_data data;
 
-    (void)memset(&data, 0, sizeof(data));
+  (void)memset(&data, 0, sizeof(data));
 
-    data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_RSP,
-                                 sizeof(*data.rsp));
-    if (!data.buf) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_RSP, sizeof(*data.rsp));
+  if (!data.buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    data.att = att;
-    data.uuid = uuid;
-    data.rsp = net_buf_add(data.buf, sizeof(*data.rsp));
-    data.rsp->len = 0U;
+  data.att      = att;
+  data.uuid     = uuid;
+  data.rsp      = net_buf_add(data.buf, sizeof(*data.rsp));
+  data.rsp->len = 0U;
 
-    /* Pre-set error if no attr will be found in handle */
-    data.err = BT_ATT_ERR_ATTRIBUTE_NOT_FOUND;
+  /* Pre-set error if no attr will be found in handle */
+  data.err = BT_ATT_ERR_ATTRIBUTE_NOT_FOUND;
 
-    bt_gatt_foreach_attr(start_handle, end_handle, read_type_cb, &data);
+  bt_gatt_foreach_attr(start_handle, end_handle, read_type_cb, &data);
 
-    if (data.err) {
-        net_buf_unref(data.buf);
-        /* Response here since handle is set */
-        send_err_rsp(conn, BT_ATT_OP_READ_TYPE_REQ, start_handle,
-                     data.err);
-        return 0;
-    }
+  if (data.err) {
+    net_buf_unref(data.buf);
+    /* Response here since handle is set */
+    send_err_rsp(conn, BT_ATT_OP_READ_TYPE_REQ, start_handle, data.err);
+    return 0;
+  }
 
 #if defined(CONFIG_BT_STACK_PTS)
-    if (event_flag == att_read_by_type_ind)
-        BT_PTS("handle : [0x%04x]\r\n", data.rsp->data->handle);
+  if (event_flag == att_read_by_type_ind)
+    BT_PTS("handle : [0x%04x]\r\n", data.rsp->data->handle);
 #endif
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent,
-                           NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
 
-    return 0;
+  return 0;
 }
 
-static u8_t att_read_type_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct bt_att_read_type_req *req;
-    u16_t start_handle, end_handle, err_handle;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_128 u128;
-    } u;
-    u8_t uuid_len = buf->len - sizeof(*req);
-
-    /* Type can only be UUID16 or UUID128 */
-    if (uuid_len != 2 && uuid_len != 16) {
-        return BT_ATT_ERR_INVALID_PDU;
-    }
+static u8_t att_read_type_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn              *conn = att->chan.chan.conn;
+  struct bt_att_read_type_req *req;
+  u16_t                        start_handle, end_handle, err_handle;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_128 u128;
+  } u;
+  u8_t uuid_len = buf->len - sizeof(*req);
 
-    req = net_buf_pull_mem(buf, sizeof(*req));
+  /* Type can only be UUID16 or UUID128 */
+  if (uuid_len != 2 && uuid_len != 16) {
+    return BT_ATT_ERR_INVALID_PDU;
+  }
 
-    start_handle = sys_le16_to_cpu(req->start_handle);
-    end_handle = sys_le16_to_cpu(req->end_handle);
-    if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  req = net_buf_pull_mem(buf, sizeof(*req));
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s",
-           start_handle, end_handle, bt_uuid_str(&u.uuid));
+  start_handle = sys_le16_to_cpu(req->start_handle);
+  end_handle   = sys_le16_to_cpu(req->end_handle);
+  if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    if (!range_is_valid(start_handle, end_handle, &err_handle)) {
-        send_err_rsp(conn, BT_ATT_OP_READ_TYPE_REQ, err_handle,
-                     BT_ATT_ERR_INVALID_HANDLE);
-        return 0;
-    }
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s", start_handle, end_handle, bt_uuid_str(&u.uuid));
 
-    return att_read_type_rsp(att, &u.uuid, start_handle, end_handle);
+  if (!range_is_valid(start_handle, end_handle, &err_handle)) {
+    send_err_rsp(conn, BT_ATT_OP_READ_TYPE_REQ, err_handle, BT_ATT_ERR_INVALID_HANDLE);
+    return 0;
+  }
+
+  return att_read_type_rsp(att, &u.uuid, start_handle, end_handle);
 }
 
 struct read_data {
-    struct bt_att *att;
-    u16_t offset;
-    struct net_buf *buf;
-    struct bt_att_read_rsp *rsp;
-    u8_t err;
+  struct bt_att          *att;
+  u16_t                   offset;
+  struct net_buf         *buf;
+  struct bt_att_read_rsp *rsp;
+  u8_t                    err;
 };
 
-static u8_t read_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct read_data *data = user_data;
-    struct bt_att *att = data->att;
-    struct bt_conn *conn = att->chan.chan.conn;
-    int read;
+static u8_t read_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct read_data *data = user_data;
+  struct bt_att    *att  = data->att;
+  struct bt_conn   *conn = att->chan.chan.conn;
+  int               read;
 
-    BT_DBG("handle 0x%04x", attr->handle);
+  BT_DBG("handle 0x%04x", attr->handle);
 
-    data->rsp = net_buf_add(data->buf, sizeof(*data->rsp));
+  data->rsp = net_buf_add(data->buf, sizeof(*data->rsp));
 
-    /*
-	 * If any attribute is founded in handle range it means that error
-	 * should be changed from pre-set: invalid handle error to no error.
-	 */
-    data->err = 0x00;
-
-    /* Check attribute permissions */
-    data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK);
-    if (data->err) {
-        return BT_GATT_ITER_STOP;
-    }
+  /*
+   * If any attribute is founded in handle range it means that error
+   * should be changed from pre-set: invalid handle error to no error.
+   */
+  data->err = 0x00;
 
-    /* Read attribute value and store in the buffer */
-    read = attr->read(conn, attr, data->buf->data + data->buf->len,
-                      att->chan.tx.mtu - data->buf->len, data->offset);
-    if (read < 0) {
-        data->err = err_to_att(read);
-        return BT_GATT_ITER_STOP;
-    }
+  /* Check attribute permissions */
+  data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK);
+  if (data->err) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    net_buf_add(data->buf, read);
+  /* Read attribute value and store in the buffer */
+  read = attr->read(conn, attr, data->buf->data + data->buf->len, att->chan.tx.mtu - data->buf->len, data->offset);
+  if (read < 0) {
+    data->err = err_to_att(read);
+    return BT_GATT_ITER_STOP;
+  }
 
-    return BT_GATT_ITER_CONTINUE;
+  net_buf_add(data->buf, read);
+
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static u8_t att_read_rsp(struct bt_att *att, u8_t op, u8_t rsp, u16_t handle,
-                         u16_t offset)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct read_data data;
+static u8_t att_read_rsp(struct bt_att *att, u8_t op, u8_t rsp, u16_t handle, u16_t offset) {
+  struct bt_conn  *conn = att->chan.chan.conn;
+  struct read_data data;
 
-    if (!bt_gatt_change_aware(conn, true)) {
-        return BT_ATT_ERR_DB_OUT_OF_SYNC;
-    }
+  if (!bt_gatt_change_aware(conn, true)) {
+    return BT_ATT_ERR_DB_OUT_OF_SYNC;
+  }
 
-    if (!handle) {
-        return BT_ATT_ERR_INVALID_HANDLE;
-    }
+  if (!handle) {
+    return BT_ATT_ERR_INVALID_HANDLE;
+  }
 
-    (void)memset(&data, 0, sizeof(data));
+  (void)memset(&data, 0, sizeof(data));
 
-    data.buf = bt_att_create_pdu(conn, rsp, 0);
-    if (!data.buf) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  data.buf = bt_att_create_pdu(conn, rsp, 0);
+  if (!data.buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    data.att = att;
-    data.offset = offset;
+  data.att    = att;
+  data.offset = offset;
 
-    /* Pre-set error if no attr will be found in handle */
-    data.err = BT_ATT_ERR_INVALID_HANDLE;
+  /* Pre-set error if no attr will be found in handle */
+  data.err = BT_ATT_ERR_INVALID_HANDLE;
 
-    bt_gatt_foreach_attr(handle, handle, read_cb, &data);
+  bt_gatt_foreach_attr(handle, handle, read_cb, &data);
 
-    /* In case of error discard data and respond with an error */
-    if (data.err) {
-        net_buf_unref(data.buf);
-        /* Respond here since handle is set */
-        send_err_rsp(conn, op, handle, data.err);
-        return 0;
-    }
+  /* In case of error discard data and respond with an error */
+  if (data.err) {
+    net_buf_unref(data.buf);
+    /* Respond here since handle is set */
+    send_err_rsp(conn, op, handle, data.err);
+    return 0;
+  }
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent,
-                           NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
 
-    return 0;
+  return 0;
 }
 
-static u8_t att_read_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_att_read_req *req;
-    u16_t handle;
+static u8_t att_read_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_att_read_req *req;
+  u16_t                   handle;
 
-    req = (void *)buf->data;
+  req = (void *)buf->data;
 
-    handle = sys_le16_to_cpu(req->handle);
+  handle = sys_le16_to_cpu(req->handle);
 
-    BT_DBG("handle 0x%04x", handle);
+  BT_DBG("handle 0x%04x", handle);
 
-    return att_read_rsp(att, BT_ATT_OP_READ_REQ, BT_ATT_OP_READ_RSP,
-                        handle, 0);
+  return att_read_rsp(att, BT_ATT_OP_READ_REQ, BT_ATT_OP_READ_RSP, handle, 0);
 }
 
-static u8_t att_read_blob_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_att_read_blob_req *req;
-    u16_t handle, offset;
+static u8_t att_read_blob_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_att_read_blob_req *req;
+  u16_t                        handle, offset;
 
-    req = (void *)buf->data;
+  req = (void *)buf->data;
 
-    handle = sys_le16_to_cpu(req->handle);
-    offset = sys_le16_to_cpu(req->offset);
+  handle = sys_le16_to_cpu(req->handle);
+  offset = sys_le16_to_cpu(req->offset);
 
-    BT_DBG("handle 0x%04x offset %u", handle, offset);
+  BT_DBG("handle 0x%04x offset %u", handle, offset);
 
-    return att_read_rsp(att, BT_ATT_OP_READ_BLOB_REQ,
-                        BT_ATT_OP_READ_BLOB_RSP, handle, offset);
+  return att_read_rsp(att, BT_ATT_OP_READ_BLOB_REQ, BT_ATT_OP_READ_BLOB_RSP, handle, offset);
 }
 
 #if defined(CONFIG_BT_GATT_READ_MULTIPLE)
-static u8_t att_read_mult_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct read_data data;
-    u16_t handle;
+static u8_t att_read_mult_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn  *conn = att->chan.chan.conn;
+  struct read_data data;
+  u16_t            handle;
 
-    (void)memset(&data, 0, sizeof(data));
+  (void)memset(&data, 0, sizeof(data));
 
-    data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_RSP, 0);
-    if (!data.buf) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_RSP, 0);
+  if (!data.buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    data.att = att;
+  data.att = att;
 
-    while (buf->len >= sizeof(u16_t)) {
-        handle = net_buf_pull_le16(buf);
+  while (buf->len >= sizeof(u16_t)) {
+    handle = net_buf_pull_le16(buf);
 
-        BT_DBG("handle 0x%04x ", handle);
+    BT_DBG("handle 0x%04x ", handle);
 
-        /* An Error Response shall be sent by the server in response to
-		 * the Read Multiple Request [....] if a read operation is not
-		 * permitted on any of the Characteristic Values.
-		 *
-		 * If handle is not valid then return invalid handle error.
-		 * If handle is found error will be cleared by read_cb.
-		 */
-        data.err = BT_ATT_ERR_INVALID_HANDLE;
+    /* An Error Response shall be sent by the server in response to
+     * the Read Multiple Request [....] if a read operation is not
+     * permitted on any of the Characteristic Values.
+     *
+     * If handle is not valid then return invalid handle error.
+     * If handle is found error will be cleared by read_cb.
+     */
+    data.err = BT_ATT_ERR_INVALID_HANDLE;
 
-        bt_gatt_foreach_attr(handle, handle, read_cb, &data);
+    bt_gatt_foreach_attr(handle, handle, read_cb, &data);
 
-        /* Stop reading in case of error */
-        if (data.err) {
-            net_buf_unref(data.buf);
-            /* Respond here since handle is set */
-            send_err_rsp(conn, BT_ATT_OP_READ_MULT_REQ, handle,
-                         data.err);
-            return 0;
-        }
+    /* Stop reading in case of error */
+    if (data.err) {
+      net_buf_unref(data.buf);
+      /* Respond here since handle is set */
+      send_err_rsp(conn, BT_ATT_OP_READ_MULT_REQ, handle, data.err);
+      return 0;
     }
+  }
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent,
-                           NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_BT_GATT_READ_MULTIPLE */
 
 struct read_group_data {
-    struct bt_att *att;
-    struct bt_uuid *uuid;
-    struct net_buf *buf;
-    struct bt_att_read_group_rsp *rsp;
-    struct bt_att_group_data *group;
+  struct bt_att                *att;
+  struct bt_uuid               *uuid;
+  struct net_buf               *buf;
+  struct bt_att_read_group_rsp *rsp;
+  struct bt_att_group_data     *group;
 };
 
-static u8_t read_group_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct read_group_data *data = user_data;
-    struct bt_att *att = data->att;
-    struct bt_conn *conn = att->chan.chan.conn;
-    int read;
-
-    /* Update group end_handle if attribute is not a service */
-    if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) &&
-        bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) {
-        if (data->group &&
-            attr->handle > sys_le16_to_cpu(data->group->end_handle)) {
-            data->group->end_handle = sys_cpu_to_le16(attr->handle);
-        }
-        return BT_GATT_ITER_CONTINUE;
-    }
+static u8_t read_group_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct read_group_data *data = user_data;
+  struct bt_att          *att  = data->att;
+  struct bt_conn         *conn = att->chan.chan.conn;
+  int                     read;
 
-    /* If Group Type don't match skip */
-    if (bt_uuid_cmp(attr->uuid, data->uuid)) {
-        data->group = NULL;
-        return BT_GATT_ITER_CONTINUE;
+  /* Update group end_handle if attribute is not a service */
+  if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) && bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) {
+    if (data->group && attr->handle > sys_le16_to_cpu(data->group->end_handle)) {
+      data->group->end_handle = sys_cpu_to_le16(attr->handle);
     }
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    BT_DBG("handle 0x%04x", attr->handle);
+  /* If Group Type don't match skip */
+  if (bt_uuid_cmp(attr->uuid, data->uuid)) {
+    data->group = NULL;
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    /* Stop if there is no space left */
-    if (data->rsp->len &&
-        att->chan.tx.mtu - data->buf->len < data->rsp->len) {
-        return BT_GATT_ITER_STOP;
-    }
+  BT_DBG("handle 0x%04x", attr->handle);
 
-    /* Fast forward to next group position */
-    data->group = net_buf_add(data->buf, sizeof(*data->group));
+  /* Stop if there is no space left */
+  if (data->rsp->len && att->chan.tx.mtu - data->buf->len < data->rsp->len) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    /* Initialize group handle range */
-    data->group->start_handle = sys_cpu_to_le16(attr->handle);
-    data->group->end_handle = sys_cpu_to_le16(attr->handle);
+  /* Fast forward to next group position */
+  data->group = net_buf_add(data->buf, sizeof(*data->group));
 
-    /* Read attribute value and store in the buffer */
-    read = attr->read(conn, attr, data->buf->data + data->buf->len,
-                      att->chan.tx.mtu - data->buf->len, 0);
-    if (read < 0) {
-        /* TODO: Handle read errors */
-        return BT_GATT_ITER_STOP;
-    }
+  /* Initialize group handle range */
+  data->group->start_handle = sys_cpu_to_le16(attr->handle);
+  data->group->end_handle   = sys_cpu_to_le16(attr->handle);
 
-    if (!data->rsp->len) {
-        /* Set len to be the first group found */
-        data->rsp->len = read + sizeof(*data->group);
-    } else if (data->rsp->len != read + sizeof(*data->group)) {
-        /* All groups entries should have the same size */
-        data->buf->len -= sizeof(*data->group);
-        return false;
-    }
+  /* Read attribute value and store in the buffer */
+  read = attr->read(conn, attr, data->buf->data + data->buf->len, att->chan.tx.mtu - data->buf->len, 0);
+  if (read < 0) {
+    /* TODO: Handle read errors */
+    return BT_GATT_ITER_STOP;
+  }
 
-    net_buf_add(data->buf, read);
+  if (!data->rsp->len) {
+    /* Set len to be the first group found */
+    data->rsp->len = read + sizeof(*data->group);
+  } else if (data->rsp->len != read + sizeof(*data->group)) {
+    /* All groups entries should have the same size */
+    data->buf->len -= sizeof(*data->group);
+    return false;
+  }
 
-    /* Continue to find the end handle */
-    return BT_GATT_ITER_CONTINUE;
+  net_buf_add(data->buf, read);
+
+  /* Continue to find the end handle */
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static u8_t att_read_group_rsp(struct bt_att *att, struct bt_uuid *uuid,
-                               u16_t start_handle, u16_t end_handle)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct read_group_data data;
+static u8_t att_read_group_rsp(struct bt_att *att, struct bt_uuid *uuid, u16_t start_handle, u16_t end_handle) {
+  struct bt_conn        *conn = att->chan.chan.conn;
+  struct read_group_data data;
 
-    (void)memset(&data, 0, sizeof(data));
+  (void)memset(&data, 0, sizeof(data));
 
-    data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_GROUP_RSP,
-                                 sizeof(*data.rsp));
-    if (!data.buf) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_GROUP_RSP, sizeof(*data.rsp));
+  if (!data.buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    data.att = att;
-    data.uuid = uuid;
-    data.rsp = net_buf_add(data.buf, sizeof(*data.rsp));
-    data.rsp->len = 0U;
-    data.group = NULL;
+  data.att      = att;
+  data.uuid     = uuid;
+  data.rsp      = net_buf_add(data.buf, sizeof(*data.rsp));
+  data.rsp->len = 0U;
+  data.group    = NULL;
 
-    bt_gatt_foreach_attr(start_handle, end_handle, read_group_cb, &data);
+  bt_gatt_foreach_attr(start_handle, end_handle, read_group_cb, &data);
 
-    if (!data.rsp->len) {
-        net_buf_unref(data.buf);
-        /* Respond here since handle is set */
-        send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, start_handle,
-                     BT_ATT_ERR_ATTRIBUTE_NOT_FOUND);
-        return 0;
-    }
+  if (!data.rsp->len) {
+    net_buf_unref(data.buf);
+    /* Respond here since handle is set */
+    send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, start_handle, BT_ATT_ERR_ATTRIBUTE_NOT_FOUND);
+    return 0;
+  }
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent,
-                           NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
 
-    return 0;
+  return 0;
 }
 
-static u8_t att_read_group_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct bt_att_read_group_req *req;
-    u16_t start_handle, end_handle, err_handle;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_128 u128;
-    } u;
-    u8_t uuid_len = buf->len - sizeof(*req);
-
-    /* Type can only be UUID16 or UUID128 */
-    if (uuid_len != 2 && uuid_len != 16) {
-        return BT_ATT_ERR_INVALID_PDU;
-    }
+static u8_t att_read_group_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn               *conn = att->chan.chan.conn;
+  struct bt_att_read_group_req *req;
+  u16_t                         start_handle, end_handle, err_handle;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_128 u128;
+  } u;
+  u8_t uuid_len = buf->len - sizeof(*req);
 
-    req = net_buf_pull_mem(buf, sizeof(*req));
+  /* Type can only be UUID16 or UUID128 */
+  if (uuid_len != 2 && uuid_len != 16) {
+    return BT_ATT_ERR_INVALID_PDU;
+  }
 
-    start_handle = sys_le16_to_cpu(req->start_handle);
-    end_handle = sys_le16_to_cpu(req->end_handle);
+  req = net_buf_pull_mem(buf, sizeof(*req));
 
-    if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  start_handle = sys_le16_to_cpu(req->start_handle);
+  end_handle   = sys_le16_to_cpu(req->end_handle);
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s",
-           start_handle, end_handle, bt_uuid_str(&u.uuid));
+  if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    if (!range_is_valid(start_handle, end_handle, &err_handle)) {
-        send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, err_handle,
-                     BT_ATT_ERR_INVALID_HANDLE);
-        return 0;
-    }
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s", start_handle, end_handle, bt_uuid_str(&u.uuid));
 
-    /* Core v4.2, Vol 3, sec 2.5.3 Attribute Grouping:
-	 * Not all of the grouping attributes can be used in the ATT
-	 * Read By Group Type Request. The "Primary Service" and "Secondary
-	 * Service" grouping types may be used in the Read By Group Type
-	 * Request. The "Characteristic" grouping type shall not be used in
-	 * the ATT Read By Group Type Request.
-	 */
-    if (bt_uuid_cmp(&u.uuid, BT_UUID_GATT_PRIMARY) &&
-        bt_uuid_cmp(&u.uuid, BT_UUID_GATT_SECONDARY)) {
-        send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, start_handle,
-                     BT_ATT_ERR_UNSUPPORTED_GROUP_TYPE);
-        return 0;
-    }
+  if (!range_is_valid(start_handle, end_handle, &err_handle)) {
+    send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, err_handle, BT_ATT_ERR_INVALID_HANDLE);
+    return 0;
+  }
+
+  /* Core v4.2, Vol 3, sec 2.5.3 Attribute Grouping:
+   * Not all of the grouping attributes can be used in the ATT
+   * Read By Group Type Request. The "Primary Service" and "Secondary
+   * Service" grouping types may be used in the Read By Group Type
+   * Request. The "Characteristic" grouping type shall not be used in
+   * the ATT Read By Group Type Request.
+   */
+  if (bt_uuid_cmp(&u.uuid, BT_UUID_GATT_PRIMARY) && bt_uuid_cmp(&u.uuid, BT_UUID_GATT_SECONDARY)) {
+    send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, start_handle, BT_ATT_ERR_UNSUPPORTED_GROUP_TYPE);
+    return 0;
+  }
 
-    return att_read_group_rsp(att, &u.uuid, start_handle, end_handle);
+  return att_read_group_rsp(att, &u.uuid, start_handle, end_handle);
 }
 
 struct write_data {
-    struct bt_conn *conn;
-    struct net_buf *buf;
-    u8_t req;
-    const void *value;
-    u16_t len;
-    u16_t offset;
-    u8_t err;
+  struct bt_conn *conn;
+  struct net_buf *buf;
+  u8_t            req;
+  const void     *value;
+  u16_t           len;
+  u16_t           offset;
+  u8_t            err;
 };
 
-static u8_t write_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct write_data *data = user_data;
-    int write;
-    u8_t flags = 0U;
+static u8_t write_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct write_data *data = user_data;
+  int                write;
+  u8_t               flags = 0U;
 
-    BT_DBG("handle 0x%04x offset %u", attr->handle, data->offset);
+  BT_DBG("handle 0x%04x offset %u", attr->handle, data->offset);
 
-    /* Check attribute permissions */
-    data->err = bt_gatt_check_perm(data->conn, attr,
-                                   BT_GATT_PERM_WRITE_MASK);
-    if (data->err) {
-        return BT_GATT_ITER_STOP;
-    }
+  /* Check attribute permissions */
+  data->err = bt_gatt_check_perm(data->conn, attr, BT_GATT_PERM_WRITE_MASK);
+  if (data->err) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    /* Set command flag if not a request */
-    if (!data->req) {
-        flags |= BT_GATT_WRITE_FLAG_CMD;
-    }
+  /* Set command flag if not a request */
+  if (!data->req) {
+    flags |= BT_GATT_WRITE_FLAG_CMD;
+  }
 
-    /* Write attribute value */
-    write = attr->write(data->conn, attr, data->value, data->len,
-                        data->offset, flags);
-    if (write < 0 || write != data->len) {
-        data->err = err_to_att(write);
-        return BT_GATT_ITER_STOP;
-    }
+  /* Write attribute value */
+  write = attr->write(data->conn, attr, data->value, data->len, data->offset, flags);
+  if (write < 0 || write != data->len) {
+    data->err = err_to_att(write);
+    return BT_GATT_ITER_STOP;
+  }
 
-    data->err = 0U;
+  data->err = 0U;
 
-    return BT_GATT_ITER_CONTINUE;
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static u8_t att_write_rsp(struct bt_conn *conn, u8_t req, u8_t rsp,
-                          u16_t handle, u16_t offset, const void *value,
-                          u16_t len)
-{
-    struct write_data data;
+static u8_t att_write_rsp(struct bt_conn *conn, u8_t req, u8_t rsp, u16_t handle, u16_t offset, const void *value, u16_t len) {
+  struct write_data data;
 
-    if (!bt_gatt_change_aware(conn, req ? true : false)) {
-        return BT_ATT_ERR_DB_OUT_OF_SYNC;
-    }
+  if (!bt_gatt_change_aware(conn, req ? true : false)) {
+    return BT_ATT_ERR_DB_OUT_OF_SYNC;
+  }
 
-    if (!handle) {
-        return BT_ATT_ERR_INVALID_HANDLE;
-    }
+  if (!handle) {
+    return BT_ATT_ERR_INVALID_HANDLE;
+  }
 
-    (void)memset(&data, 0, sizeof(data));
+  (void)memset(&data, 0, sizeof(data));
 
-    /* Only allocate buf if required to respond */
-    if (rsp) {
-        data.buf = bt_att_create_pdu(conn, rsp, 0);
-        if (!data.buf) {
-            return BT_ATT_ERR_UNLIKELY;
-        }
+  /* Only allocate buf if required to respond */
+  if (rsp) {
+    data.buf = bt_att_create_pdu(conn, rsp, 0);
+    if (!data.buf) {
+      return BT_ATT_ERR_UNLIKELY;
     }
+  }
 
-    data.conn = conn;
-    data.req = req;
-    data.offset = offset;
-    data.value = value;
-    data.len = len;
-    data.err = BT_ATT_ERR_INVALID_HANDLE;
+  data.conn   = conn;
+  data.req    = req;
+  data.offset = offset;
+  data.value  = value;
+  data.len    = len;
+  data.err    = BT_ATT_ERR_INVALID_HANDLE;
 
-    bt_gatt_foreach_attr(handle, handle, write_cb, &data);
+  bt_gatt_foreach_attr(handle, handle, write_cb, &data);
 
-    if (data.err) {
-        /* In case of error discard data and respond with an error */
-        if (rsp) {
-            net_buf_unref(data.buf);
-            /* Respond here since handle is set */
-            send_err_rsp(conn, req, handle, data.err);
-        }
-        return req == BT_ATT_OP_EXEC_WRITE_REQ ? data.err : 0;
+  if (data.err) {
+    /* In case of error discard data and respond with an error */
+    if (rsp) {
+      net_buf_unref(data.buf);
+      /* Respond here since handle is set */
+      send_err_rsp(conn, req, handle, data.err);
     }
+    return req == BT_ATT_OP_EXEC_WRITE_REQ ? data.err : 0;
+  }
 
-    if (data.buf) {
-        (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf,
-                               att_rsp_sent, NULL);
-    }
+  if (data.buf) {
+    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
+  }
 
-    return 0;
+  return 0;
 }
 
-static u8_t att_write_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    u16_t handle;
+static u8_t att_write_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn *conn = att->chan.chan.conn;
+  u16_t           handle;
 
-    handle = net_buf_pull_le16(buf);
+  handle = net_buf_pull_le16(buf);
 
-    BT_DBG("handle 0x%04x", handle);
+  BT_DBG("handle 0x%04x", handle);
 
-    return att_write_rsp(conn, BT_ATT_OP_WRITE_REQ, BT_ATT_OP_WRITE_RSP,
-                         handle, 0, buf->data, buf->len);
+  return att_write_rsp(conn, BT_ATT_OP_WRITE_REQ, BT_ATT_OP_WRITE_RSP, handle, 0, buf->data, buf->len);
 }
 
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
 struct prep_data {
-    struct bt_conn *conn;
-    struct net_buf *buf;
-    const void *value;
-    u16_t len;
-    u16_t offset;
-    u8_t err;
+  struct bt_conn *conn;
+  struct net_buf *buf;
+  const void     *value;
+  u16_t           len;
+  u16_t           offset;
+  u8_t            err;
 };
 
-static u8_t prep_write_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct prep_data *data = user_data;
-    struct bt_attr_data *attr_data;
-    int write;
+static u8_t prep_write_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct prep_data    *data = user_data;
+  struct bt_attr_data *attr_data;
+  int                  write;
 
-    BT_DBG("handle 0x%04x offset %u", attr->handle, data->offset);
+  BT_DBG("handle 0x%04x offset %u", attr->handle, data->offset);
 
-    /* Check attribute permissions */
-    data->err = bt_gatt_check_perm(data->conn, attr,
-                                   BT_GATT_PERM_WRITE_MASK);
-    if (data->err) {
-        return BT_GATT_ITER_STOP;
-    }
+  /* Check attribute permissions */
+  data->err = bt_gatt_check_perm(data->conn, attr, BT_GATT_PERM_WRITE_MASK);
+  if (data->err) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    /* Check if attribute requires handler to accept the data */
-    if (!(attr->perm & BT_GATT_PERM_PREPARE_WRITE)) {
-        goto append;
-    }
+  /* Check if attribute requires handler to accept the data */
+  if (!(attr->perm & BT_GATT_PERM_PREPARE_WRITE)) {
+    goto append;
+  }
 
-    /* Write attribute value to check if device is authorized */
-    write = attr->write(data->conn, attr, data->value, data->len,
-                        data->offset, BT_GATT_WRITE_FLAG_PREPARE);
-    if (write != 0) {
-        data->err = err_to_att(write);
-        return BT_GATT_ITER_STOP;
-    }
+  /* Write attribute value to check if device is authorized */
+  write = attr->write(data->conn, attr, data->value, data->len, data->offset, BT_GATT_WRITE_FLAG_PREPARE);
+  if (write != 0) {
+    data->err = err_to_att(write);
+    return BT_GATT_ITER_STOP;
+  }
 
 append:
-    /* Copy data into the outstanding queue */
-    data->buf = net_buf_alloc(&prep_pool, K_NO_WAIT);
-    if (!data->buf) {
-        data->err = BT_ATT_ERR_PREPARE_QUEUE_FULL;
-        return BT_GATT_ITER_STOP;
-    }
+  /* Copy data into the outstanding queue */
+  data->buf = net_buf_alloc(&prep_pool, K_NO_WAIT);
+  if (!data->buf) {
+    data->err = BT_ATT_ERR_PREPARE_QUEUE_FULL;
+    return BT_GATT_ITER_STOP;
+  }
 
-    attr_data = net_buf_user_data(data->buf);
-    attr_data->handle = attr->handle;
-    attr_data->offset = data->offset;
+  attr_data         = net_buf_user_data(data->buf);
+  attr_data->handle = attr->handle;
+  attr_data->offset = data->offset;
 
-    net_buf_add_mem(data->buf, data->value, data->len);
+  net_buf_add_mem(data->buf, data->value, data->len);
 
-    data->err = 0U;
+  data->err = 0U;
 
-    return BT_GATT_ITER_CONTINUE;
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static u8_t att_prep_write_rsp(struct bt_att *att, u16_t handle, u16_t offset,
-                               const void *value, u16_t len)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct prep_data data;
-    struct bt_att_prepare_write_rsp *rsp;
+static u8_t att_prep_write_rsp(struct bt_att *att, u16_t handle, u16_t offset, const void *value, u16_t len) {
+  struct bt_conn                  *conn = att->chan.chan.conn;
+  struct prep_data                 data;
+  struct bt_att_prepare_write_rsp *rsp;
 
-    if (!bt_gatt_change_aware(conn, true)) {
-        return BT_ATT_ERR_DB_OUT_OF_SYNC;
-    }
+  if (!bt_gatt_change_aware(conn, true)) {
+    return BT_ATT_ERR_DB_OUT_OF_SYNC;
+  }
 
-    if (!handle) {
-        return BT_ATT_ERR_INVALID_HANDLE;
-    }
+  if (!handle) {
+    return BT_ATT_ERR_INVALID_HANDLE;
+  }
 
-    (void)memset(&data, 0, sizeof(data));
+  (void)memset(&data, 0, sizeof(data));
 
-    data.conn = conn;
-    data.offset = offset;
-    data.value = value;
-    data.len = len;
-    data.err = BT_ATT_ERR_INVALID_HANDLE;
+  data.conn   = conn;
+  data.offset = offset;
+  data.value  = value;
+  data.len    = len;
+  data.err    = BT_ATT_ERR_INVALID_HANDLE;
 
-    bt_gatt_foreach_attr(handle, handle, prep_write_cb, &data);
+  bt_gatt_foreach_attr(handle, handle, prep_write_cb, &data);
 
-    if (data.err) {
-        /* Respond here since handle is set */
-        send_err_rsp(conn, BT_ATT_OP_PREPARE_WRITE_REQ, handle,
-                     data.err);
-        return 0;
-    }
+  if (data.err) {
+    /* Respond here since handle is set */
+    send_err_rsp(conn, BT_ATT_OP_PREPARE_WRITE_REQ, handle, data.err);
+    return 0;
+  }
 
-    BT_DBG("buf %p handle 0x%04x offset %u", data.buf, handle, offset);
+  BT_DBG("buf %p handle 0x%04x offset %u", data.buf, handle, offset);
 
-    /* Store buffer in the outstanding queue */
-    net_buf_put(&att->prep_queue, data.buf);
+  /* Store buffer in the outstanding queue */
+  net_buf_put(&att->prep_queue, data.buf);
 
-    /* Generate response */
-    data.buf = bt_att_create_pdu(conn, BT_ATT_OP_PREPARE_WRITE_RSP, 0);
-    if (!data.buf) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  /* Generate response */
+  data.buf = bt_att_create_pdu(conn, BT_ATT_OP_PREPARE_WRITE_RSP, 0);
+  if (!data.buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    rsp = net_buf_add(data.buf, sizeof(*rsp));
-    rsp->handle = sys_cpu_to_le16(handle);
-    rsp->offset = sys_cpu_to_le16(offset);
-    net_buf_add(data.buf, len);
-    memcpy(rsp->value, value, len);
+  rsp         = net_buf_add(data.buf, sizeof(*rsp));
+  rsp->handle = sys_cpu_to_le16(handle);
+  rsp->offset = sys_cpu_to_le16(offset);
+  net_buf_add(data.buf, len);
+  memcpy(rsp->value, value, len);
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent,
-                           NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_BT_ATT_PREPARE_COUNT */
 
-static u8_t att_prepare_write_req(struct bt_att *att, struct net_buf *buf)
-{
+static u8_t att_prepare_write_req(struct bt_att *att, struct net_buf *buf) {
 #if CONFIG_BT_ATT_PREPARE_COUNT == 0
-    return BT_ATT_ERR_NOT_SUPPORTED;
+  return BT_ATT_ERR_NOT_SUPPORTED;
 #else
-    struct bt_att_prepare_write_req *req;
-    u16_t handle, offset;
+  struct bt_att_prepare_write_req *req;
+  u16_t                            handle, offset;
 
-    req = net_buf_pull_mem(buf, sizeof(*req));
+  req = net_buf_pull_mem(buf, sizeof(*req));
 
-    handle = sys_le16_to_cpu(req->handle);
-    offset = sys_le16_to_cpu(req->offset);
+  handle = sys_le16_to_cpu(req->handle);
+  offset = sys_le16_to_cpu(req->offset);
 
-    BT_DBG("handle 0x%04x offset %u", handle, offset);
+  BT_DBG("handle 0x%04x offset %u", handle, offset);
 
-    return att_prep_write_rsp(att, handle, offset, buf->data, buf->len);
+  return att_prep_write_rsp(att, handle, offset, buf->data, buf->len);
 #endif /* CONFIG_BT_ATT_PREPARE_COUNT */
 }
 
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
-static u8_t att_exec_write_rsp(struct bt_att *att, u8_t flags)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct net_buf *buf;
-    u8_t err = 0U;
-
-    while ((buf = net_buf_get(&att->prep_queue, K_NO_WAIT))) {
-        struct bt_attr_data *data = net_buf_user_data(buf);
-
-        BT_DBG("buf %p handle 0x%04x offset %u", buf, data->handle,
-               data->offset);
-
-        /* Just discard the data if an error was set */
-        if (!err && flags == BT_ATT_FLAG_EXEC) {
-            err = att_write_rsp(conn, BT_ATT_OP_EXEC_WRITE_REQ, 0,
-                                data->handle, data->offset,
-                                buf->data, buf->len);
-            if (err) {
-                /* Respond here since handle is set */
-                send_err_rsp(conn, BT_ATT_OP_EXEC_WRITE_REQ,
-                             data->handle, err);
-            }
-        }
-
-        net_buf_unref(buf);
-    }
+static u8_t att_exec_write_rsp(struct bt_att *att, u8_t flags) {
+  struct bt_conn *conn = att->chan.chan.conn;
+  struct net_buf *buf;
+  u8_t            err = 0U;
 
-    if (err) {
-        return 0;
-    }
+  while ((buf = net_buf_get(&att->prep_queue, K_NO_WAIT))) {
+    struct bt_attr_data *data = net_buf_user_data(buf);
 
-    /* Generate response */
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_EXEC_WRITE_RSP, 0);
-    if (!buf) {
-        return BT_ATT_ERR_UNLIKELY;
+    BT_DBG("buf %p handle 0x%04x offset %u", buf, data->handle, data->offset);
+
+    /* Just discard the data if an error was set */
+    if (!err && flags == BT_ATT_FLAG_EXEC) {
+      err = att_write_rsp(conn, BT_ATT_OP_EXEC_WRITE_REQ, 0, data->handle, data->offset, buf->data, buf->len);
+      if (err) {
+        /* Respond here since handle is set */
+        send_err_rsp(conn, BT_ATT_OP_EXEC_WRITE_REQ, data->handle, err);
+      }
     }
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_rsp_sent, NULL);
+    net_buf_unref(buf);
+  }
 
+  if (err) {
     return 0;
+  }
+
+  /* Generate response */
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_EXEC_WRITE_RSP, 0);
+  if (!buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
+
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_rsp_sent, NULL);
+
+  return 0;
 }
 #endif /* CONFIG_BT_ATT_PREPARE_COUNT */
 
-static u8_t att_exec_write_req(struct bt_att *att, struct net_buf *buf)
-{
+static u8_t att_exec_write_req(struct bt_att *att, struct net_buf *buf) {
 #if CONFIG_BT_ATT_PREPARE_COUNT == 0
-    return BT_ATT_ERR_NOT_SUPPORTED;
+  return BT_ATT_ERR_NOT_SUPPORTED;
 #else
-    struct bt_att_exec_write_req *req;
+  struct bt_att_exec_write_req *req;
 
-    req = (void *)buf->data;
+  req = (void *)buf->data;
 
-    BT_DBG("flags 0x%02x", req->flags);
+  BT_DBG("flags 0x%02x", req->flags);
 
-    return att_exec_write_rsp(att, req->flags);
+  return att_exec_write_rsp(att, req->flags);
 #endif /* CONFIG_BT_ATT_PREPARE_COUNT */
 }
 
-static u8_t att_write_cmd(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    u16_t handle;
+static u8_t att_write_cmd(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn *conn = att->chan.chan.conn;
+  u16_t           handle;
 
-    handle = net_buf_pull_le16(buf);
+  handle = net_buf_pull_le16(buf);
 
-    BT_DBG("handle 0x%04x", handle);
+  BT_DBG("handle 0x%04x", handle);
 
-    return att_write_rsp(conn, 0, 0, handle, 0, buf->data, buf->len);
+  return att_write_rsp(conn, 0, 0, handle, 0, buf->data, buf->len);
 }
 
 #if defined(CONFIG_BT_SIGNING)
-static u8_t att_signed_write_cmd(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct bt_att_signed_write_cmd *req;
-    u16_t handle;
-    int err;
+static u8_t att_signed_write_cmd(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn                 *conn = att->chan.chan.conn;
+  struct bt_att_signed_write_cmd *req;
+  u16_t                           handle;
+  int                             err;
 
-    req = (void *)buf->data;
+  req = (void *)buf->data;
 
-    handle = sys_le16_to_cpu(req->handle);
+  handle = sys_le16_to_cpu(req->handle);
 
-    BT_DBG("handle 0x%04x", handle);
+  BT_DBG("handle 0x%04x", handle);
 
-    /* Verifying data requires full buffer including attribute header */
-    net_buf_push(buf, sizeof(struct bt_att_hdr));
-    err = bt_smp_sign_verify(conn, buf);
-    if (err) {
-        BT_ERR("Error verifying data");
-        /* No response for this command */
-        return 0;
-    }
+  /* Verifying data requires full buffer including attribute header */
+  net_buf_push(buf, sizeof(struct bt_att_hdr));
+  err = bt_smp_sign_verify(conn, buf);
+  if (err) {
+    BT_ERR("Error verifying data");
+    /* No response for this command */
+    return 0;
+  }
 
-    net_buf_pull(buf, sizeof(struct bt_att_hdr));
-    net_buf_pull(buf, sizeof(*req));
+  net_buf_pull(buf, sizeof(struct bt_att_hdr));
+  net_buf_pull(buf, sizeof(*req));
 
-    return att_write_rsp(conn, 0, 0, handle, 0, buf->data,
-                         buf->len - sizeof(struct bt_att_signature));
+  return att_write_rsp(conn, 0, 0, handle, 0, buf->data, buf->len - sizeof(struct bt_att_signature));
 }
 #endif /* CONFIG_BT_SIGNING */
 
 #if defined(CONFIG_BT_GATT_CLIENT)
 #if defined(CONFIG_BT_SMP)
-static int att_change_security(struct bt_conn *conn, u8_t err)
-{
-    bt_security_t sec;
-
-    switch (err) {
-        case BT_ATT_ERR_INSUFFICIENT_ENCRYPTION:
-            if (conn->sec_level >= BT_SECURITY_L2)
-                return -EALREADY;
-            sec = BT_SECURITY_L2;
-            break;
-        case BT_ATT_ERR_AUTHENTICATION:
-            if (conn->sec_level < BT_SECURITY_L2) {
-                /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C]
-			 * page 375:
-			 *
-			 * If an LTK is not available, the service request
-			 * shall be rejected with the error code 'Insufficient
-			 * Authentication'.
-			 * Note: When the link is not encrypted, the error code
-			 * "Insufficient Authentication" does not indicate that
-			 * MITM protection is required.
-			 */
-                sec = BT_SECURITY_L2;
-            } else if (conn->sec_level < BT_SECURITY_L3) {
-                /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C]
-			 * page 375:
-			 *
-			 * If an authenticated pairing is required but only an
-			 * unauthenticated pairing has occurred and the link is
-			 * currently encrypted, the service request shall be
-			 * rejected with the error code 'Insufficient
-			 * Authentication'.
-			 * Note: When unauthenticated pairing has occurred and
-			 * the link is currently encrypted, the error code
-			 * 'Insufficient Authentication' indicates that MITM
-			 * protection is required.
-			 */
-                sec = BT_SECURITY_L3;
-            } else if (conn->sec_level < BT_SECURITY_L4) {
-                /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C]
-			 * page 375:
-			 *
-			 * If LE Secure Connections authenticated pairing is
-			 * required but LE legacy pairing has occurred and the
-			 * link is currently encrypted, the service request
-			 * shall be rejected with the error code ''Insufficient
-			 * Authentication'.
-			 */
-                sec = BT_SECURITY_L4;
-            } else {
-                return -EALREADY;
-            }
-            break;
-        default:
-            return -EINVAL;
+static int att_change_security(struct bt_conn *conn, u8_t err) {
+  bt_security_t sec;
+
+  switch (err) {
+  case BT_ATT_ERR_INSUFFICIENT_ENCRYPTION:
+    if (conn->sec_level >= BT_SECURITY_L2)
+      return -EALREADY;
+    sec = BT_SECURITY_L2;
+    break;
+  case BT_ATT_ERR_AUTHENTICATION:
+    if (conn->sec_level < BT_SECURITY_L2) {
+      /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C]
+       * page 375:
+       *
+       * If an LTK is not available, the service request
+       * shall be rejected with the error code 'Insufficient
+       * Authentication'.
+       * Note: When the link is not encrypted, the error code
+       * "Insufficient Authentication" does not indicate that
+       * MITM protection is required.
+       */
+      sec = BT_SECURITY_L2;
+    } else if (conn->sec_level < BT_SECURITY_L3) {
+      /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C]
+       * page 375:
+       *
+       * If an authenticated pairing is required but only an
+       * unauthenticated pairing has occurred and the link is
+       * currently encrypted, the service request shall be
+       * rejected with the error code 'Insufficient
+       * Authentication'.
+       * Note: When unauthenticated pairing has occurred and
+       * the link is currently encrypted, the error code
+       * 'Insufficient Authentication' indicates that MITM
+       * protection is required.
+       */
+      sec = BT_SECURITY_L3;
+    } else if (conn->sec_level < BT_SECURITY_L4) {
+      /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C]
+       * page 375:
+       *
+       * If LE Secure Connections authenticated pairing is
+       * required but LE legacy pairing has occurred and the
+       * link is currently encrypted, the service request
+       * shall be rejected with the error code ''Insufficient
+       * Authentication'.
+       */
+      sec = BT_SECURITY_L4;
+    } else {
+      return -EALREADY;
     }
+    break;
+  default:
+    return -EINVAL;
+  }
 
-    return bt_conn_set_security(conn, sec);
+  return bt_conn_set_security(conn, sec);
 }
 #endif /* CONFIG_BT_SMP */
 
-static u8_t att_error_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_att_error_rsp *rsp;
-    u8_t err;
+static u8_t att_error_rsp(struct bt_att *att, struct net_buf *buf) {
+  struct bt_att_error_rsp *rsp;
+  u8_t                     err;
 
-    rsp = (void *)buf->data;
+  rsp = (void *)buf->data;
 
-    BT_DBG("request 0x%02x handle 0x%04x error 0x%02x", rsp->request,
-           sys_le16_to_cpu(rsp->handle), rsp->error);
+  BT_DBG("request 0x%02x handle 0x%04x error 0x%02x", rsp->request, sys_le16_to_cpu(rsp->handle), rsp->error);
 
-    /* Don't retry if there is no req pending or it has been cancelled */
-    if (!att->req || att->req == &cancel) {
-        err = BT_ATT_ERR_UNLIKELY;
-        goto done;
-    }
+  /* Don't retry if there is no req pending or it has been cancelled */
+  if (!att->req || att->req == &cancel) {
+    err = BT_ATT_ERR_UNLIKELY;
+    goto done;
+  }
 
-    if (att->req->buf) {
-        /* Restore state to be resent */
-        net_buf_simple_restore(&att->req->buf->b, &att->req->state);
-    }
+  if (att->req->buf) {
+    /* Restore state to be resent */
+    net_buf_simple_restore(&att->req->buf->b, &att->req->state);
+  }
 
-    err = rsp->error;
+  err = rsp->error;
 #if defined(CONFIG_BT_SMP)
-    if (att->req->retrying) {
-        goto done;
-    }
-
-    /* Check if security needs to be changed */
-    if (!att_change_security(att->chan.chan.conn, err)) {
-        att->req->retrying = true;
-        /* Wait security_changed: TODO: Handle fail case */
-        return 0;
-    }
+  if (att->req->retrying) {
+    goto done;
+  }
+
+  /* Check if security needs to be changed */
+  if (!att_change_security(att->chan.chan.conn, err)) {
+    att->req->retrying = true;
+    /* Wait security_changed: TODO: Handle fail case */
+    return 0;
+  }
 #endif /* CONFIG_BT_SMP */
 
 done:
-    return att_handle_rsp(att, NULL, 0, err);
+  return att_handle_rsp(att, NULL, 0, err);
 }
 
-static u8_t att_handle_find_info_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_find_info_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_handle_find_type_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_find_type_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_handle_read_type_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_read_type_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_handle_read_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_read_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_handle_read_blob_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_read_blob_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
 #if defined(CONFIG_BT_GATT_READ_MULTIPLE)
-static u8_t att_handle_read_mult_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_read_mult_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 #endif /* CONFIG_BT_GATT_READ_MULTIPLE */
 
-static u8_t att_handle_read_group_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_read_group_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_handle_write_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_write_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_handle_prepare_write_rsp(struct bt_att *att,
-                                         struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_prepare_write_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_handle_exec_write_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_exec_write_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_notify(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    u16_t handle;
+static u8_t att_notify(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn *conn = att->chan.chan.conn;
+  u16_t           handle;
 
-    handle = net_buf_pull_le16(buf);
-    BT_DBG("handle 0x%04x", handle);
+  handle = net_buf_pull_le16(buf);
+  BT_DBG("handle 0x%04x", handle);
 
-    bt_gatt_notification(conn, handle, buf->data, buf->len);
-    return 0;
+  bt_gatt_notification(conn, handle, buf->data, buf->len);
+  return 0;
 }
 
-static u8_t att_indicate(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    u16_t handle;
+static u8_t att_indicate(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn *conn = att->chan.chan.conn;
+  u16_t           handle;
 
-    handle = net_buf_pull_le16(buf);
+  handle = net_buf_pull_le16(buf);
 
-    BT_DBG("handle 0x%04x", handle);
+  BT_DBG("handle 0x%04x", handle);
 
-    bt_gatt_notification(conn, handle, buf->data, buf->len);
+  bt_gatt_notification(conn, handle, buf->data, buf->len);
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_CONFIRM, 0);
-    if (!buf) {
-        return 0;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_CONFIRM, 0);
+  if (!buf) {
+    return 0;
+  }
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_cfm_sent, NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_cfm_sent, NULL);
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_BT_GATT_CLIENT */
 
-static u8_t att_confirm(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_confirm(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
 static const struct att_handler {
-    u8_t op;
-    u8_t expect_len;
-    att_type_t type;
-    u8_t (*func)(struct bt_att *att, struct net_buf *buf);
+  u8_t       op;
+  u8_t       expect_len;
+  att_type_t type;
+  u8_t (*func)(struct bt_att *att, struct net_buf *buf);
 } handlers[] = {
-    { BT_ATT_OP_MTU_REQ,
-      sizeof(struct bt_att_exchange_mtu_req),
-      ATT_REQUEST,
-      att_mtu_req },
-    { BT_ATT_OP_FIND_INFO_REQ,
-      sizeof(struct bt_att_find_info_req),
-      ATT_REQUEST,
-      att_find_info_req },
-    { BT_ATT_OP_FIND_TYPE_REQ,
-      sizeof(struct bt_att_find_type_req),
-      ATT_REQUEST,
-      att_find_type_req },
-    { BT_ATT_OP_READ_TYPE_REQ,
-      sizeof(struct bt_att_read_type_req),
-      ATT_REQUEST,
-      att_read_type_req },
-    { BT_ATT_OP_READ_REQ,
-      sizeof(struct bt_att_read_req),
-      ATT_REQUEST,
-      att_read_req },
-    { BT_ATT_OP_READ_BLOB_REQ,
-      sizeof(struct bt_att_read_blob_req),
-      ATT_REQUEST,
-      att_read_blob_req },
+    {BT_ATT_OP_MTU_REQ, sizeof(struct bt_att_exchange_mtu_req), ATT_REQUEST, att_mtu_req},
+    {BT_ATT_OP_FIND_INFO_REQ, sizeof(struct bt_att_find_info_req), ATT_REQUEST, att_find_info_req},
+    {BT_ATT_OP_FIND_TYPE_REQ, sizeof(struct bt_att_find_type_req), ATT_REQUEST, att_find_type_req},
+    {BT_ATT_OP_READ_TYPE_REQ, sizeof(struct bt_att_read_type_req), ATT_REQUEST, att_read_type_req},
+    {BT_ATT_OP_READ_REQ, sizeof(struct bt_att_read_req), ATT_REQUEST, att_read_req},
+    {BT_ATT_OP_READ_BLOB_REQ, sizeof(struct bt_att_read_blob_req), ATT_REQUEST, att_read_blob_req},
 #if defined(CONFIG_BT_GATT_READ_MULTIPLE)
-    { BT_ATT_OP_READ_MULT_REQ,
-      BT_ATT_READ_MULT_MIN_LEN_REQ,
-      ATT_REQUEST,
-      att_read_mult_req },
+    {BT_ATT_OP_READ_MULT_REQ, BT_ATT_READ_MULT_MIN_LEN_REQ, ATT_REQUEST, att_read_mult_req},
 #endif /* CONFIG_BT_GATT_READ_MULTIPLE */
-    { BT_ATT_OP_READ_GROUP_REQ,
-      sizeof(struct bt_att_read_group_req),
-      ATT_REQUEST,
-      att_read_group_req },
-    { BT_ATT_OP_WRITE_REQ,
-      sizeof(struct bt_att_write_req),
-      ATT_REQUEST,
-      att_write_req },
-    { BT_ATT_OP_PREPARE_WRITE_REQ,
-      sizeof(struct bt_att_prepare_write_req),
-      ATT_REQUEST,
-      att_prepare_write_req },
-    { BT_ATT_OP_EXEC_WRITE_REQ,
-      sizeof(struct bt_att_exec_write_req),
-      ATT_REQUEST,
-      att_exec_write_req },
-    { BT_ATT_OP_CONFIRM,
-      0,
-      ATT_CONFIRMATION,
-      att_confirm },
-    { BT_ATT_OP_WRITE_CMD,
-      sizeof(struct bt_att_write_cmd),
-      ATT_COMMAND,
-      att_write_cmd },
+    {BT_ATT_OP_READ_GROUP_REQ, sizeof(struct bt_att_read_group_req), ATT_REQUEST, att_read_group_req},
+    {BT_ATT_OP_WRITE_REQ, sizeof(struct bt_att_write_req), ATT_REQUEST, att_write_req},
+    {BT_ATT_OP_PREPARE_WRITE_REQ, sizeof(struct bt_att_prepare_write_req), ATT_REQUEST, att_prepare_write_req},
+    {BT_ATT_OP_EXEC_WRITE_REQ, sizeof(struct bt_att_exec_write_req), ATT_REQUEST, att_exec_write_req},
+    {BT_ATT_OP_CONFIRM, 0, ATT_CONFIRMATION, att_confirm},
+    {BT_ATT_OP_WRITE_CMD, sizeof(struct bt_att_write_cmd), ATT_COMMAND, att_write_cmd},
 #if defined(CONFIG_BT_SIGNING)
-    { BT_ATT_OP_SIGNED_WRITE_CMD,
-      (sizeof(struct bt_att_write_cmd) +
-       sizeof(struct bt_att_signature)),
-      ATT_COMMAND,
-      att_signed_write_cmd },
+    {BT_ATT_OP_SIGNED_WRITE_CMD, (sizeof(struct bt_att_write_cmd) + sizeof(struct bt_att_signature)), ATT_COMMAND, att_signed_write_cmd},
 #endif /* CONFIG_BT_SIGNING */
 #if defined(CONFIG_BT_GATT_CLIENT)
-    { BT_ATT_OP_ERROR_RSP,
-      sizeof(struct bt_att_error_rsp),
-      ATT_RESPONSE,
-      att_error_rsp },
-    { BT_ATT_OP_MTU_RSP,
-      sizeof(struct bt_att_exchange_mtu_rsp),
-      ATT_RESPONSE,
-      att_mtu_rsp },
-    { BT_ATT_OP_FIND_INFO_RSP,
-      sizeof(struct bt_att_find_info_rsp),
-      ATT_RESPONSE,
-      att_handle_find_info_rsp },
-    { BT_ATT_OP_FIND_TYPE_RSP,
-      sizeof(struct bt_att_find_type_rsp),
-      ATT_RESPONSE,
-      att_handle_find_type_rsp },
-    { BT_ATT_OP_READ_TYPE_RSP,
-      sizeof(struct bt_att_read_type_rsp),
-      ATT_RESPONSE,
-      att_handle_read_type_rsp },
-    { BT_ATT_OP_READ_RSP,
-      sizeof(struct bt_att_read_rsp),
-      ATT_RESPONSE,
-      att_handle_read_rsp },
-    { BT_ATT_OP_READ_BLOB_RSP,
-      sizeof(struct bt_att_read_blob_rsp),
-      ATT_RESPONSE,
-      att_handle_read_blob_rsp },
+    {BT_ATT_OP_ERROR_RSP, sizeof(struct bt_att_error_rsp), ATT_RESPONSE, att_error_rsp},
+    {BT_ATT_OP_MTU_RSP, sizeof(struct bt_att_exchange_mtu_rsp), ATT_RESPONSE, att_mtu_rsp},
+    {BT_ATT_OP_FIND_INFO_RSP, sizeof(struct bt_att_find_info_rsp), ATT_RESPONSE, att_handle_find_info_rsp},
+    {BT_ATT_OP_FIND_TYPE_RSP, sizeof(struct bt_att_find_type_rsp), ATT_RESPONSE, att_handle_find_type_rsp},
+    {BT_ATT_OP_READ_TYPE_RSP, sizeof(struct bt_att_read_type_rsp), ATT_RESPONSE, att_handle_read_type_rsp},
+    {BT_ATT_OP_READ_RSP, sizeof(struct bt_att_read_rsp), ATT_RESPONSE, att_handle_read_rsp},
+    {BT_ATT_OP_READ_BLOB_RSP, sizeof(struct bt_att_read_blob_rsp), ATT_RESPONSE, att_handle_read_blob_rsp},
 #if defined(CONFIG_BT_GATT_READ_MULTIPLE)
-    { BT_ATT_OP_READ_MULT_RSP,
-      sizeof(struct bt_att_read_mult_rsp),
-      ATT_RESPONSE,
-      att_handle_read_mult_rsp },
+    {BT_ATT_OP_READ_MULT_RSP, sizeof(struct bt_att_read_mult_rsp), ATT_RESPONSE, att_handle_read_mult_rsp},
 #endif /* CONFIG_BT_GATT_READ_MULTIPLE */
-    { BT_ATT_OP_READ_GROUP_RSP,
-      sizeof(struct bt_att_read_group_rsp),
-      ATT_RESPONSE,
-      att_handle_read_group_rsp },
-    { BT_ATT_OP_WRITE_RSP,
-      0,
-      ATT_RESPONSE,
-      att_handle_write_rsp },
-    { BT_ATT_OP_PREPARE_WRITE_RSP,
-      sizeof(struct bt_att_prepare_write_rsp),
-      ATT_RESPONSE,
-      att_handle_prepare_write_rsp },
-    { BT_ATT_OP_EXEC_WRITE_RSP,
-      0,
-      ATT_RESPONSE,
-      att_handle_exec_write_rsp },
-    { BT_ATT_OP_NOTIFY,
-      sizeof(struct bt_att_notify),
-      ATT_NOTIFICATION,
-      att_notify },
-    { BT_ATT_OP_INDICATE,
-      sizeof(struct bt_att_indicate),
-      ATT_INDICATION,
-      att_indicate },
+    {BT_ATT_OP_READ_GROUP_RSP, sizeof(struct bt_att_read_group_rsp), ATT_RESPONSE, att_handle_read_group_rsp},
+    {BT_ATT_OP_WRITE_RSP, 0, ATT_RESPONSE, att_handle_write_rsp},
+    {BT_ATT_OP_PREPARE_WRITE_RSP, sizeof(struct bt_att_prepare_write_rsp), ATT_RESPONSE, att_handle_prepare_write_rsp},
+    {BT_ATT_OP_EXEC_WRITE_RSP, 0, ATT_RESPONSE, att_handle_exec_write_rsp},
+    {BT_ATT_OP_NOTIFY, sizeof(struct bt_att_notify), ATT_NOTIFICATION, att_notify},
+    {BT_ATT_OP_INDICATE, sizeof(struct bt_att_indicate), ATT_INDICATION, att_indicate},
 #endif /* CONFIG_BT_GATT_CLIENT */
 };
 
-static att_type_t att_op_get_type(u8_t op)
-{
-    switch (op) {
-        case BT_ATT_OP_MTU_REQ:
-        case BT_ATT_OP_FIND_INFO_REQ:
-        case BT_ATT_OP_FIND_TYPE_REQ:
-        case BT_ATT_OP_READ_TYPE_REQ:
-        case BT_ATT_OP_READ_REQ:
-        case BT_ATT_OP_READ_BLOB_REQ:
-        case BT_ATT_OP_READ_MULT_REQ:
-        case BT_ATT_OP_READ_GROUP_REQ:
-        case BT_ATT_OP_WRITE_REQ:
-        case BT_ATT_OP_PREPARE_WRITE_REQ:
-        case BT_ATT_OP_EXEC_WRITE_REQ:
-            return ATT_REQUEST;
-        case BT_ATT_OP_CONFIRM:
-            return ATT_CONFIRMATION;
-        case BT_ATT_OP_WRITE_CMD:
-        case BT_ATT_OP_SIGNED_WRITE_CMD:
-            return ATT_COMMAND;
-        case BT_ATT_OP_ERROR_RSP:
-        case BT_ATT_OP_MTU_RSP:
-        case BT_ATT_OP_FIND_INFO_RSP:
-        case BT_ATT_OP_FIND_TYPE_RSP:
-        case BT_ATT_OP_READ_TYPE_RSP:
-        case BT_ATT_OP_READ_RSP:
-        case BT_ATT_OP_READ_BLOB_RSP:
-        case BT_ATT_OP_READ_MULT_RSP:
-        case BT_ATT_OP_READ_GROUP_RSP:
-        case BT_ATT_OP_WRITE_RSP:
-        case BT_ATT_OP_PREPARE_WRITE_RSP:
-        case BT_ATT_OP_EXEC_WRITE_RSP:
-            return ATT_RESPONSE;
-        case BT_ATT_OP_NOTIFY:
-            return ATT_NOTIFICATION;
-        case BT_ATT_OP_INDICATE:
-            return ATT_INDICATION;
-    }
-
-    if (op & ATT_CMD_MASK) {
-        return ATT_COMMAND;
-    }
-
-    return ATT_UNKNOWN;
-}
-
-static int bt_att_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
-    struct bt_att *att = ATT_CHAN(chan);
-    struct bt_att_hdr *hdr;
-    const struct att_handler *handler;
-    u8_t err;
-    size_t i;
-
-    if (buf->len < sizeof(*hdr)) {
-        BT_ERR("Too small ATT PDU received");
-        return 0;
-    }
-
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    BT_DBG("Received ATT code 0x%02x len %u", hdr->code, buf->len);
-
-    for (i = 0, handler = NULL; i < ARRAY_SIZE(handlers); i++) {
-        if (hdr->code == handlers[i].op) {
-            handler = &handlers[i];
-            break;
-        }
-    }
-
-    if (!handler) {
-        BT_WARN("Unhandled ATT code 0x%02x", hdr->code);
-        if (att_op_get_type(hdr->code) != ATT_COMMAND) {
-            send_err_rsp(chan->conn, hdr->code, 0,
-                         BT_ATT_ERR_NOT_SUPPORTED);
-        }
-        return 0;
-    }
-
-    if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
-        if (handler->type == ATT_REQUEST &&
-            atomic_test_and_set_bit(att->flags, ATT_PENDING_RSP)) {
-            BT_WARN("Ignoring unexpected request");
-            return 0;
-        } else if (handler->type == ATT_INDICATION &&
-                   atomic_test_and_set_bit(att->flags,
-                                           ATT_PENDING_CFM)) {
-            BT_WARN("Ignoring unexpected indication");
-            return 0;
-        }
-    }
-
-    if (buf->len < handler->expect_len) {
-        BT_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code);
-        err = BT_ATT_ERR_INVALID_PDU;
-    } else {
-        err = handler->func(att, buf);
-    }
-
-    if (handler->type == ATT_REQUEST && err) {
-        BT_DBG("ATT error 0x%02x", err);
-        send_err_rsp(chan->conn, hdr->code, 0, err);
-    }
-
+static att_type_t att_op_get_type(u8_t op) {
+  switch (op) {
+  case BT_ATT_OP_MTU_REQ:
+  case BT_ATT_OP_FIND_INFO_REQ:
+  case BT_ATT_OP_FIND_TYPE_REQ:
+  case BT_ATT_OP_READ_TYPE_REQ:
+  case BT_ATT_OP_READ_REQ:
+  case BT_ATT_OP_READ_BLOB_REQ:
+  case BT_ATT_OP_READ_MULT_REQ:
+  case BT_ATT_OP_READ_GROUP_REQ:
+  case BT_ATT_OP_WRITE_REQ:
+  case BT_ATT_OP_PREPARE_WRITE_REQ:
+  case BT_ATT_OP_EXEC_WRITE_REQ:
+    return ATT_REQUEST;
+  case BT_ATT_OP_CONFIRM:
+    return ATT_CONFIRMATION;
+  case BT_ATT_OP_WRITE_CMD:
+  case BT_ATT_OP_SIGNED_WRITE_CMD:
+    return ATT_COMMAND;
+  case BT_ATT_OP_ERROR_RSP:
+  case BT_ATT_OP_MTU_RSP:
+  case BT_ATT_OP_FIND_INFO_RSP:
+  case BT_ATT_OP_FIND_TYPE_RSP:
+  case BT_ATT_OP_READ_TYPE_RSP:
+  case BT_ATT_OP_READ_RSP:
+  case BT_ATT_OP_READ_BLOB_RSP:
+  case BT_ATT_OP_READ_MULT_RSP:
+  case BT_ATT_OP_READ_GROUP_RSP:
+  case BT_ATT_OP_WRITE_RSP:
+  case BT_ATT_OP_PREPARE_WRITE_RSP:
+  case BT_ATT_OP_EXEC_WRITE_RSP:
+    return ATT_RESPONSE;
+  case BT_ATT_OP_NOTIFY:
+    return ATT_NOTIFICATION;
+  case BT_ATT_OP_INDICATE:
+    return ATT_INDICATION;
+  }
+
+  if (op & ATT_CMD_MASK) {
+    return ATT_COMMAND;
+  }
+
+  return ATT_UNKNOWN;
+}
+
+static int bt_att_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) {
+  struct bt_att            *att = ATT_CHAN(chan);
+  struct bt_att_hdr        *hdr;
+  const struct att_handler *handler;
+  u8_t                      err;
+  size_t                    i;
+
+  if (buf->len < sizeof(*hdr)) {
+    BT_ERR("Too small ATT PDU received");
     return 0;
-}
-
-static struct bt_att *att_chan_get(struct bt_conn *conn)
-{
-    struct bt_l2cap_chan *chan;
-    struct bt_att *att;
+  }
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        BT_WARN("Not connected");
-        return NULL;
-    }
+  hdr = net_buf_pull_mem(buf, sizeof(*hdr));
+  BT_DBG("Received ATT code 0x%02x len %u", hdr->code, buf->len);
 
-    chan = bt_l2cap_le_lookup_rx_cid(conn, BT_L2CAP_CID_ATT);
-    if (!chan) {
-        BT_ERR("Unable to find ATT channel");
-        return NULL;
+  for (i = 0, handler = NULL; i < ARRAY_SIZE(handlers); i++) {
+    if (hdr->code == handlers[i].op) {
+      handler = &handlers[i];
+      break;
     }
+  }
 
-    att = ATT_CHAN(chan);
-    if (atomic_test_bit(att->flags, ATT_DISCONNECTED)) {
-        BT_WARN("ATT context flagged as disconnected");
-        return NULL;
+  if (!handler) {
+    BT_WARN("Unhandled ATT code 0x%02x", hdr->code);
+    if (att_op_get_type(hdr->code) != ATT_COMMAND) {
+      send_err_rsp(chan->conn, hdr->code, 0, BT_ATT_ERR_NOT_SUPPORTED);
     }
-
-    return att;
-}
-
-struct net_buf *bt_att_create_pdu(struct bt_conn *conn, u8_t op, size_t len)
-{
-    struct bt_att_hdr *hdr;
-    struct net_buf *buf;
-    struct bt_att *att;
-
-    att = att_chan_get(conn);
-    if (!att) {
-        return NULL;
-    }
-
-    if (len + sizeof(op) > att->chan.tx.mtu) {
-        BT_WARN("ATT MTU exceeded, max %u, wanted %zu",
-                att->chan.tx.mtu, len + sizeof(op));
-        return NULL;
-    }
-
-    switch (att_op_get_type(op)) {
-        case ATT_RESPONSE:
-        case ATT_CONFIRMATION:
-            /* Use a timeout only when responding/confirming */
-            buf = bt_l2cap_create_pdu_timeout(NULL, 0, ATT_TIMEOUT);
-            break;
-        default:
-            buf = bt_l2cap_create_pdu(NULL, 0);
-    }
-
-    if (!buf) {
-        BT_ERR("Unable to allocate buffer for op 0x%02x", op);
-        return NULL;
-    }
-
-    hdr = net_buf_add(buf, sizeof(*hdr));
-    hdr->code = op;
-
-    return buf;
-}
-
-static void att_reset(struct bt_att *att)
-{
-    struct bt_att_req *req, *tmp;
-    int i;
-    struct net_buf *buf;
+    return 0;
+  }
+
+  if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
+    if (handler->type == ATT_REQUEST && atomic_test_and_set_bit(att->flags, ATT_PENDING_RSP)) {
+      BT_WARN("Ignoring unexpected request");
+      return 0;
+    } else if (handler->type == ATT_INDICATION && atomic_test_and_set_bit(att->flags, ATT_PENDING_CFM)) {
+      BT_WARN("Ignoring unexpected indication");
+      return 0;
+    }
+  }
+
+  if (buf->len < handler->expect_len) {
+    BT_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code);
+    err = BT_ATT_ERR_INVALID_PDU;
+  } else {
+    err = handler->func(att, buf);
+  }
+
+  if (handler->type == ATT_REQUEST && err) {
+    BT_DBG("ATT error 0x%02x", err);
+    send_err_rsp(chan->conn, hdr->code, 0, err);
+  }
+
+  return 0;
+}
+
+static struct bt_att *att_chan_get(struct bt_conn *conn) {
+  struct bt_l2cap_chan *chan;
+  struct bt_att        *att;
+
+  if (conn->state != BT_CONN_CONNECTED) {
+    BT_WARN("Not connected");
+    return NULL;
+  }
+
+  chan = bt_l2cap_le_lookup_rx_cid(conn, BT_L2CAP_CID_ATT);
+  if (!chan) {
+    BT_ERR("Unable to find ATT channel");
+    return NULL;
+  }
+
+  att = ATT_CHAN(chan);
+  if (atomic_test_bit(att->flags, ATT_DISCONNECTED)) {
+    BT_WARN("ATT context flagged as disconnected");
+    return NULL;
+  }
+
+  return att;
+}
+
+struct net_buf *bt_att_create_pdu(struct bt_conn *conn, u8_t op, size_t len) {
+  struct bt_att_hdr *hdr;
+  struct net_buf    *buf;
+  struct bt_att     *att;
+
+  att = att_chan_get(conn);
+  if (!att) {
+    return NULL;
+  }
+
+  if (len + sizeof(op) > att->chan.tx.mtu) {
+    BT_WARN("ATT MTU exceeded, max %u, wanted %zu", att->chan.tx.mtu, len + sizeof(op));
+    return NULL;
+  }
+
+  switch (att_op_get_type(op)) {
+  case ATT_RESPONSE:
+  case ATT_CONFIRMATION:
+    /* Use a timeout only when responding/confirming */
+    buf = bt_l2cap_create_pdu_timeout(NULL, 0, ATT_TIMEOUT);
+    break;
+  default:
+    buf = bt_l2cap_create_pdu(NULL, 0);
+  }
+
+  if (!buf) {
+    BT_ERR("Unable to allocate buffer for op 0x%02x", op);
+    return NULL;
+  }
+
+  hdr       = net_buf_add(buf, sizeof(*hdr));
+  hdr->code = op;
+
+  return buf;
+}
+
+static void att_reset(struct bt_att *att) {
+  struct bt_att_req *req, *tmp;
+  int                i;
+  struct net_buf    *buf;
 
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
-    /* Discard queued buffers */
-    while ((buf = k_fifo_get(&att->prep_queue, K_NO_WAIT))) {
-        net_buf_unref(buf);
-    }
+  /* Discard queued buffers */
+  while ((buf = k_fifo_get(&att->prep_queue, K_NO_WAIT))) {
+    net_buf_unref(buf);
+  }
 #endif /* CONFIG_BT_ATT_PREPARE_COUNT > 0 */
 
-    while ((buf = k_fifo_get(&att->tx_queue, K_NO_WAIT))) {
-        net_buf_unref(buf);
-    }
+  while ((buf = k_fifo_get(&att->tx_queue, K_NO_WAIT))) {
+    net_buf_unref(buf);
+  }
 
-    atomic_set_bit(att->flags, ATT_DISCONNECTED);
+  atomic_set_bit(att->flags, ATT_DISCONNECTED);
 
-    /* Ensure that any waiters are woken up */
-    for (i = 0; i < CONFIG_BT_ATT_TX_MAX; i++) {
-        k_sem_give(&att->tx_sem);
-    }
-
-    /* Notify pending requests */
-    SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&att->reqs, req, tmp, node)
-    {
-        if (req->func) {
-            req->func(NULL, BT_ATT_ERR_UNLIKELY, NULL, 0, req);
-        }
+  /* Ensure that any waiters are woken up */
+  for (i = 0; i < CONFIG_BT_ATT_TX_MAX; i++) {
+    k_sem_give(&att->tx_sem);
+  }
 
-        att_req_destroy(req);
+  /* Notify pending requests */
+  SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&att->reqs, req, tmp, node) {
+    if (req->func) {
+      req->func(NULL, BT_ATT_ERR_UNLIKELY, NULL, 0, req);
     }
 
-    /* Reset list */
-    sys_slist_init(&att->reqs);
+    att_req_destroy(req);
+  }
 
-    if (!att->req) {
-        return;
-    }
+  /* Reset list */
+  sys_slist_init(&att->reqs);
+
+  if (!att->req) {
+    return;
+  }
 
-    /* Notify outstanding request */
-    att_handle_rsp(att, NULL, 0, BT_ATT_ERR_UNLIKELY);
+  /* Notify outstanding request */
+  att_handle_rsp(att, NULL, 0, BT_ATT_ERR_UNLIKELY);
 }
 
-static void att_timeout(struct k_work *work)
-{
-    struct bt_att *att = CONTAINER_OF(work, struct bt_att, timeout_work);
-    struct bt_l2cap_le_chan *ch = &att->chan;
+static void att_timeout(struct k_work *work) {
+  struct bt_att           *att = CONTAINER_OF(work, struct bt_att, timeout_work);
+  struct bt_l2cap_le_chan *ch  = &att->chan;
 
-    BT_ERR("ATT Timeout");
+  BT_ERR("ATT Timeout");
 
-    /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 480:
-	 *
-	 * A transaction not completed within 30 seconds shall time out. Such a
-	 * transaction shall be considered to have failed and the local higher
-	 * layers shall be informed of this failure. No more attribute protocol
-	 * requests, commands, indications or notifications shall be sent to the
-	 * target device on this ATT Bearer.
-	 */
-    att_reset(att);
+  /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 480:
+   *
+   * A transaction not completed within 30 seconds shall time out. Such a
+   * transaction shall be considered to have failed and the local higher
+   * layers shall be informed of this failure. No more attribute protocol
+   * requests, commands, indications or notifications shall be sent to the
+   * target device on this ATT Bearer.
+   */
+  att_reset(att);
 
-    /* Consider the channel disconnected */
-    bt_gatt_disconnected(ch->chan.conn);
-    ch->chan.conn = NULL;
+  /* Consider the channel disconnected */
+  bt_gatt_disconnected(ch->chan.conn);
+  ch->chan.conn = NULL;
 }
 
-static void bt_att_connected(struct bt_l2cap_chan *chan)
-{
-    struct bt_att *att = ATT_CHAN(chan);
-    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
+static void bt_att_connected(struct bt_l2cap_chan *chan) {
+  struct bt_att           *att = ATT_CHAN(chan);
+  struct bt_l2cap_le_chan *ch  = BT_L2CAP_LE_CHAN(chan);
 
-    BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
+  BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
 
-    k_fifo_init(&att->tx_queue, 20);
+  k_fifo_init(&att->tx_queue, 20);
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
-    k_fifo_init(&att->prep_queue, 20);
+  k_fifo_init(&att->prep_queue, 20);
 #endif
 
-    ch->tx.mtu = BT_ATT_DEFAULT_LE_MTU;
-    ch->rx.mtu = BT_ATT_DEFAULT_LE_MTU;
+  ch->tx.mtu = BT_ATT_DEFAULT_LE_MTU;
+  ch->rx.mtu = BT_ATT_DEFAULT_LE_MTU;
 
-    k_delayed_work_init(&att->timeout_work, att_timeout);
-    sys_slist_init(&att->reqs);
+  k_delayed_work_init(&att->timeout_work, att_timeout);
+  sys_slist_init(&att->reqs);
 }
 
-static void bt_att_disconnected(struct bt_l2cap_chan *chan)
-{
-    struct bt_att *att = ATT_CHAN(chan);
-    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
+static void bt_att_disconnected(struct bt_l2cap_chan *chan) {
+  struct bt_att           *att = ATT_CHAN(chan);
+  struct bt_l2cap_le_chan *ch  = BT_L2CAP_LE_CHAN(chan);
 
-    BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
+  BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
 
-    att_reset(att);
+  att_reset(att);
 
-    bt_gatt_disconnected(ch->chan.conn);
+  bt_gatt_disconnected(ch->chan.conn);
 
 #ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS
-    if (att->timeout_work.timer.timer.hdl)
-        k_delayed_work_del_timer(&att->timeout_work);
+  if (att->timeout_work.timer.timer.hdl)
+    k_delayed_work_del_timer(&att->timeout_work);
 
-    if (att->tx_queue._queue.hdl) {
-        k_queue_free(&att->tx_queue._queue);
-        att->tx_queue._queue.hdl = NULL;
-    }
+  if (att->tx_queue._queue.hdl) {
+    k_queue_free(&att->tx_queue._queue);
+    att->tx_queue._queue.hdl = NULL;
+  }
 
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
-    if (att->prep_queue._queue.hdl) {
-        k_queue_free(&att->prep_queue._queue);
-        att->prep_queue._queue.hdl = NULL;
-    }
+  if (att->prep_queue._queue.hdl) {
+    k_queue_free(&att->prep_queue._queue);
+    att->prep_queue._queue.hdl = NULL;
+  }
 #endif
 
-    if (att->tx_sem.sem.hdl)
-        k_sem_delete(&att->tx_sem);
+  if (att->tx_sem.sem.hdl)
+    k_sem_delete(&att->tx_sem);
 #endif
 }
 
 #if defined(CONFIG_BT_SMP)
-static void bt_att_encrypt_change(struct bt_l2cap_chan *chan,
-                                  u8_t hci_status)
-{
-    struct bt_att *att = ATT_CHAN(chan);
-    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
-    struct bt_conn *conn = ch->chan.conn;
-
-    BT_DBG("chan %p conn %p handle %u sec_level 0x%02x status 0x%02x", ch,
-           conn, conn->handle, conn->sec_level, hci_status);
-
-    /*
-	 * If status (HCI status of security procedure) is non-zero, notify
-	 * outstanding request about security failure.
-	 */
-    if (hci_status) {
-        att_handle_rsp(att, NULL, 0, BT_ATT_ERR_AUTHENTICATION);
-        return;
-    }
-
-    bt_gatt_encrypt_change(conn);
-
-    if (conn->sec_level == BT_SECURITY_L1) {
-        return;
-    }
-
-    if (!att->req || !att->req->retrying) {
-        return;
-    }
-
-    k_sem_take(&att->tx_sem, K_FOREVER);
-    if (!att_is_connected(att)) {
-        BT_WARN("Disconnected");
-        k_sem_give(&att->tx_sem);
-        return;
-    }
+static void bt_att_encrypt_change(struct bt_l2cap_chan *chan, u8_t hci_status) {
+  struct bt_att           *att  = ATT_CHAN(chan);
+  struct bt_l2cap_le_chan *ch   = BT_L2CAP_LE_CHAN(chan);
+  struct bt_conn          *conn = ch->chan.conn;
+
+  BT_DBG("chan %p conn %p handle %u sec_level 0x%02x status 0x%02x", ch, conn, conn->handle, conn->sec_level, hci_status);
+
+  /*
+   * If status (HCI status of security procedure) is non-zero, notify
+   * outstanding request about security failure.
+   */
+  if (hci_status) {
+    att_handle_rsp(att, NULL, 0, BT_ATT_ERR_AUTHENTICATION);
+    return;
+  }
+
+  bt_gatt_encrypt_change(conn);
+
+  if (conn->sec_level == BT_SECURITY_L1) {
+    return;
+  }
+
+  if (!att->req || !att->req->retrying) {
+    return;
+  }
+
+  k_sem_take(&att->tx_sem, K_FOREVER);
+  if (!att_is_connected(att)) {
+    BT_WARN("Disconnected");
+    k_sem_give(&att->tx_sem);
+    return;
+  }
 
-    BT_DBG("Retrying");
+  BT_DBG("Retrying");
 
-    /* Resend buffer */
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, att->req->buf,
-                           att_cb(att->req->buf), NULL);
-    att->req->buf = NULL;
+  /* Resend buffer */
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, att->req->buf, att_cb(att->req->buf), NULL);
+  att->req->buf = NULL;
 }
 #endif /* CONFIG_BT_SMP */
 
 #if defined(BFLB_BLE_MTU_CHANGE_CB)
-void bt_att_mtu_changed(struct bt_l2cap_chan *chan, u16_t mtu)
-{
-    bt_gatt_mtu_changed(chan->conn, mtu);
-}
+void bt_att_mtu_changed(struct bt_l2cap_chan *chan, u16_t mtu) { bt_gatt_mtu_changed(chan->conn, mtu); }
 #endif
 
-static int bt_att_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan)
-{
-    int i;
-    static struct bt_l2cap_chan_ops ops = {
-        .connected = bt_att_connected,
-        .disconnected = bt_att_disconnected,
-        .recv = bt_att_recv,
+static int bt_att_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) {
+  int                             i;
+  static struct bt_l2cap_chan_ops ops
+      = {.connected    = bt_att_connected,
+         .disconnected = bt_att_disconnected,
+         .recv         = bt_att_recv,
 #if defined(CONFIG_BT_SMP)
-        .encrypt_change = bt_att_encrypt_change,
+         .encrypt_change = bt_att_encrypt_change,
 #endif /* CONFIG_BT_SMP */
 #if defined(BFLB_BLE_MTU_CHANGE_CB)
-        .mtu_changed = bt_att_mtu_changed,
+         .mtu_changed = bt_att_mtu_changed,
 #endif
-    };
+        };
 
-    BT_DBG("conn %p handle %u", conn, conn->handle);
+  BT_DBG("conn %p handle %u", conn, conn->handle);
 
-    for (i = 0; i < ARRAY_SIZE(bt_req_pool); i++) {
-        struct bt_att *att = &bt_req_pool[i];
+  for (i = 0; i < ARRAY_SIZE(bt_req_pool); i++) {
+    struct bt_att *att = &bt_req_pool[i];
 
-        if (att->chan.chan.conn) {
-            continue;
-        }
+    if (att->chan.chan.conn) {
+      continue;
+    }
 
-        (void)memset(att, 0, sizeof(*att));
-        att->chan.chan.ops = &ops;
-        k_sem_init(&att->tx_sem, CONFIG_BT_ATT_TX_MAX,
-                   CONFIG_BT_ATT_TX_MAX);
+    (void)memset(att, 0, sizeof(*att));
+    att->chan.chan.ops = &ops;
+    k_sem_init(&att->tx_sem, CONFIG_BT_ATT_TX_MAX, CONFIG_BT_ATT_TX_MAX);
 
-        *chan = &att->chan.chan;
+    *chan = &att->chan.chan;
 
-        return 0;
-    }
+    return 0;
+  }
 
-    BT_ERR("No available ATT context for conn %p", conn);
+  BT_ERR("No available ATT context for conn %p", conn);
 
-    return -ENOMEM;
+  return -ENOMEM;
 }
 
 BT_L2CAP_CHANNEL_DEFINE(att_fixed_chan, BT_L2CAP_CID_ATT, bt_att_accept);
 
-void bt_att_init(void)
-{
+void bt_att_init(void) {
 #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL)
-    static struct bt_l2cap_fixed_chan chan = {
-        .cid = BT_L2CAP_CID_ATT,
-        .accept = bt_att_accept,
-    };
+  static struct bt_l2cap_fixed_chan chan = {
+      .cid    = BT_L2CAP_CID_ATT,
+      .accept = bt_att_accept,
+  };
 
-    bt_l2cap_le_fixed_chan_register(&chan);
+  bt_l2cap_le_fixed_chan_register(&chan);
 #endif
 
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    net_buf_init(&prep_pool, CONFIG_BT_ATT_PREPARE_COUNT, BT_ATT_MTU, NULL);
+  net_buf_init(&prep_pool, CONFIG_BT_ATT_PREPARE_COUNT, BT_ATT_MTU, NULL);
 #endif
 #endif
 
-    bt_gatt_init();
+  bt_gatt_init();
 }
 
-u16_t bt_att_get_mtu(struct bt_conn *conn)
-{
-    struct bt_att *att;
+u16_t bt_att_get_mtu(struct bt_conn *conn) {
+  struct bt_att *att;
 
-    att = att_chan_get(conn);
-    if (!att) {
-        return 0;
-    }
+  att = att_chan_get(conn);
+  if (!att) {
+    return 0;
+  }
 
-    /* tx and rx MTU shall be symmetric */
-    return att->chan.tx.mtu;
+  /* tx and rx MTU shall be symmetric */
+  return att->chan.tx.mtu;
 }
 
-int bt_att_send(struct bt_conn *conn, struct net_buf *buf, bt_conn_tx_cb_t cb,
-                void *user_data)
-{
-    struct bt_att *att;
-    int err;
+int bt_att_send(struct bt_conn *conn, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data) {
+  struct bt_att *att;
+  int            err;
 
-    __ASSERT_NO_MSG(conn);
-    __ASSERT_NO_MSG(buf);
+  __ASSERT_NO_MSG(conn);
+  __ASSERT_NO_MSG(buf);
 
-    att = att_chan_get(conn);
-    if (!att) {
-        net_buf_unref(buf);
-        return -ENOTCONN;
-    }
+  att = att_chan_get(conn);
+  if (!att) {
+    net_buf_unref(buf);
+    return -ENOTCONN;
+  }
 
-    /* Don't use tx_sem if caller has set it own callback */
-    if (!cb) {
-        /* Queue buffer to be send later */
-        if (k_sem_take(&att->tx_sem, K_NO_WAIT) < 0) {
-            k_fifo_put(&att->tx_queue, buf);
-            return 0;
-        }
+  /* Don't use tx_sem if caller has set it own callback */
+  if (!cb) {
+    /* Queue buffer to be send later */
+    if (k_sem_take(&att->tx_sem, K_NO_WAIT) < 0) {
+      k_fifo_put(&att->tx_queue, buf);
+      return 0;
     }
+  }
 
-    err = att_send(conn, buf, cb, user_data);
-    if (err) {
-        if (!cb) {
-            k_sem_give(&att->tx_sem);
-        }
-        return err;
+  err = att_send(conn, buf, cb, user_data);
+  if (err) {
+    if (!cb) {
+      k_sem_give(&att->tx_sem);
     }
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-int bt_att_req_send(struct bt_conn *conn, struct bt_att_req *req)
-{
-    struct bt_att *att;
+int bt_att_req_send(struct bt_conn *conn, struct bt_att_req *req) {
+  struct bt_att *att;
 
-    BT_DBG("conn %p req %p", conn, req);
+  BT_DBG("conn %p req %p", conn, req);
 
-    __ASSERT_NO_MSG(conn);
-    __ASSERT_NO_MSG(req);
+  __ASSERT_NO_MSG(conn);
+  __ASSERT_NO_MSG(req);
 
-    att = att_chan_get(conn);
-    if (!att) {
-        net_buf_unref(req->buf);
-        req->buf = NULL;
-        return -ENOTCONN;
-    }
+  att = att_chan_get(conn);
+  if (!att) {
+    net_buf_unref(req->buf);
+    req->buf = NULL;
+    return -ENOTCONN;
+  }
 
-    /* Check if there is a request outstanding */
-    if (att->req) {
-        /* Queue the request to be send later */
-        sys_slist_append(&att->reqs, &req->node);
-        return 0;
-    }
+  /* Check if there is a request outstanding */
+  if (att->req) {
+    /* Queue the request to be send later */
+    sys_slist_append(&att->reqs, &req->node);
+    return 0;
+  }
 
-    return att_send_req(att, req);
+  return att_send_req(att, req);
 }
 
-void bt_att_req_cancel(struct bt_conn *conn, struct bt_att_req *req)
-{
-    struct bt_att *att;
+void bt_att_req_cancel(struct bt_conn *conn, struct bt_att_req *req) {
+  struct bt_att *att;
 
-    BT_DBG("req %p", req);
+  BT_DBG("req %p", req);
 
-    if (!conn || !req) {
-        return;
-    }
+  if (!conn || !req) {
+    return;
+  }
 
-    att = att_chan_get(conn);
-    if (!att) {
-        return;
-    }
+  att = att_chan_get(conn);
+  if (!att) {
+    return;
+  }
 
-    /* Check if request is outstanding */
-    if (att->req == req) {
-        att->req = &cancel;
-    } else {
-        /* Remove request from the list */
-        sys_slist_find_and_remove(&att->reqs, &req->node);
-    }
+  /* Check if request is outstanding */
+  if (att->req == req) {
+    att->req = &cancel;
+  } else {
+    /* Remove request from the list */
+    sys_slist_find_and_remove(&att->reqs, &req->node);
+  }
 
-    att_req_destroy(req);
+  att_req_destroy(req);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att_internal.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att_internal.h
index f591a8b895..68fd834846 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att_internal.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att_internal.h
@@ -5,7 +5,7 @@
  *
  * SPDX-License-Identifier: Apache-2.0
  */
-
+#include "conn_internal.h"
 #define BT_ATT_DEFAULT_LE_MTU 23
 
 #if BT_L2CAP_RX_MTU < CONFIG_BT_L2CAP_TX_MTU
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c
index 6644abcd12..bdea4bcf22 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c
@@ -6,49 +6,47 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
-#include 
-#include 
 #include 
+#include 
+#include 
 #include 
-#include 
 #include 
 #include 
-#include 
+#include 
+#include 
+#include 
+#include 
 
-#include 
+#include 
 #include 
 #include 
 #include 
-#include 
+#include 
 
 #define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_CONN)
 #define LOG_MODULE_NAME bt_conn
 #include "log.h"
 
-#include "hci_core.h"
+#include "att_internal.h"
 #include "conn_internal.h"
-#include "l2cap_internal.h"
+#include "gatt_internal.h"
+#include "hci_core.h"
 #include "keys.h"
+#include "l2cap_internal.h"
 #include "smp.h"
-#include "att_internal.h"
-#include "gatt_internal.h"
 #if defined(BFLB_BLE)
 #include "ble_config.h"
 
 extern struct k_sem g_poll_sem;
 #endif
 struct tx_meta {
-    struct bt_conn_tx *tx;
+  struct bt_conn_tx *tx;
 };
 
 #define tx_data(buf) ((struct tx_meta *)net_buf_user_data(buf))
 
 #if !defined(BFLB_DYNAMIC_ALLOC_MEM)
-NET_BUF_POOL_DEFINE(acl_tx_pool, CONFIG_BT_L2CAP_TX_BUF_COUNT,
-                    BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU),
-                    sizeof(struct tx_meta), NULL);
+NET_BUF_POOL_DEFINE(acl_tx_pool, CONFIG_BT_L2CAP_TX_BUF_COUNT, BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU), sizeof(struct tx_meta), NULL);
 #else
 struct net_buf_pool acl_tx_pool;
 #endif
@@ -68,8 +66,7 @@ struct net_buf_pool acl_tx_pool;
  * are queued up in the TX queue. In such a situation, trying to allocate
  * another buffer from the acl_tx_pool would result in a deadlock.
  */
-NET_BUF_POOL_FIXED_DEFINE(frag_pool, CONFIG_BT_L2CAP_TX_FRAG_COUNT, FRAG_SIZE,
-                          NULL);
+NET_BUF_POOL_FIXED_DEFINE(frag_pool, CONFIG_BT_L2CAP_TX_FRAG_COUNT, FRAG_SIZE, NULL);
 #else
 struct net_buf_pool frag_pool;
 #endif
@@ -82,7 +79,7 @@ struct net_buf_pool frag_pool;
 const struct bt_conn_auth_cb *bt_auth;
 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
 
-static struct bt_conn conns[CONFIG_BT_MAX_CONN];
+static struct bt_conn     conns[CONFIG_BT_MAX_CONN];
 static struct bt_conn_cb *callback_list;
 
 static struct bt_conn_tx conn_tx[CONFIG_BT_CONN_TX_MAX];
@@ -92,2605 +89,2410 @@ K_FIFO_DEFINE(free_tx);
 static struct bt_conn sco_conns[CONFIG_BT_MAX_SCO_CONN];
 
 enum pairing_method {
-    LEGACY,          /* Legacy (pre-SSP) pairing */
-    JUST_WORKS,      /* JustWorks pairing */
-    PASSKEY_INPUT,   /* Passkey Entry input */
-    PASSKEY_DISPLAY, /* Passkey Entry display */
-    PASSKEY_CONFIRM, /* Passkey confirm */
+  LEGACY,          /* Legacy (pre-SSP) pairing */
+  JUST_WORKS,      /* JustWorks pairing */
+  PASSKEY_INPUT,   /* Passkey Entry input */
+  PASSKEY_DISPLAY, /* Passkey Entry display */
+  PASSKEY_CONFIRM, /* Passkey confirm */
 };
 
 /* based on table 5.7, Core Spec 4.2, Vol.3 Part C, 5.2.2.6 */
 static const u8_t ssp_method[4 /* remote */][4 /* local */] = {
-    { JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS },
-    { JUST_WORKS, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS },
-    { PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS },
-    { JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS },
+    {JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS},
+    {JUST_WORKS, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS},
+    {PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS},
+    {JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS},
 };
 #endif /* CONFIG_BT_BREDR */
 
-struct k_sem *bt_conn_get_pkts(struct bt_conn *conn)
-{
+struct k_sem *bt_conn_get_pkts(struct bt_conn *conn) {
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR || !bt_dev.le.mtu) {
-        return &bt_dev.br.pkts;
-    }
+  if (conn->type == BT_CONN_TYPE_BR || !bt_dev.le.mtu) {
+    return &bt_dev.br.pkts;
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    return &bt_dev.le.pkts;
+  return &bt_dev.le.pkts;
 }
 
-static inline const char *state2str(bt_conn_state_t state)
-{
-    switch (state) {
-        case BT_CONN_DISCONNECTED:
-            return "disconnected";
-        case BT_CONN_CONNECT_SCAN:
-            return "connect-scan";
-        case BT_CONN_CONNECT_DIR_ADV:
-            return "connect-dir-adv";
-        case BT_CONN_CONNECT:
-            return "connect";
-        case BT_CONN_CONNECTED:
-            return "connected";
-        case BT_CONN_DISCONNECT:
-            return "disconnect";
-        default:
-            return "(unknown)";
-    }
+static inline const char *state2str(bt_conn_state_t state) {
+  switch (state) {
+  case BT_CONN_DISCONNECTED:
+    return "disconnected";
+  case BT_CONN_CONNECT_SCAN:
+    return "connect-scan";
+  case BT_CONN_CONNECT_DIR_ADV:
+    return "connect-dir-adv";
+  case BT_CONN_CONNECT:
+    return "connect";
+  case BT_CONN_CONNECTED:
+    return "connected";
+  case BT_CONN_DISCONNECT:
+    return "disconnect";
+  default:
+    return "(unknown)";
+  }
 }
 
-static void notify_connected(struct bt_conn *conn)
-{
-    struct bt_conn_cb *cb;
+static void notify_connected(struct bt_conn *conn) {
+  struct bt_conn_cb *cb;
 
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR && conn->err) {
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
-            atomic_clear_bit(bt_dev.flags, BT_DEV_ISCAN);
-        }
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
-            atomic_clear_bit(bt_dev.flags, BT_DEV_PSCAN);
-        }
+  if (conn->type == BT_CONN_TYPE_BR && conn->err) {
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
+      atomic_clear_bit(bt_dev.flags, BT_DEV_ISCAN);
+    }
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
+      atomic_clear_bit(bt_dev.flags, BT_DEV_PSCAN);
     }
+  }
 #endif
 
-    for (cb = callback_list; cb; cb = cb->_next) {
-        if (cb->connected) {
-            cb->connected(conn, conn->err);
-        }
+  for (cb = callback_list; cb; cb = cb->_next) {
+    if (cb->connected) {
+      cb->connected(conn, conn->err);
     }
+  }
 
-    if (!conn->err) {
-        bt_gatt_connected(conn);
-    }
+  if (!conn->err) {
+    bt_gatt_connected(conn);
+  }
 }
 
-static void notify_disconnected(struct bt_conn *conn)
-{
-    struct bt_conn_cb *cb;
+static void notify_disconnected(struct bt_conn *conn) {
+  struct bt_conn_cb *cb;
 
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
-            atomic_clear_bit(bt_dev.flags, BT_DEV_ISCAN);
-        }
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
-            atomic_clear_bit(bt_dev.flags, BT_DEV_PSCAN);
-        }
+  if (conn->type == BT_CONN_TYPE_BR) {
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
+      atomic_clear_bit(bt_dev.flags, BT_DEV_ISCAN);
     }
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
+      atomic_clear_bit(bt_dev.flags, BT_DEV_PSCAN);
+    }
+  }
 #endif
 
-    for (cb = callback_list; cb; cb = cb->_next) {
-        if (cb->disconnected) {
-            cb->disconnected(conn, conn->err);
-        }
+  for (cb = callback_list; cb; cb = cb->_next) {
+    if (cb->disconnected) {
+      cb->disconnected(conn, conn->err);
     }
+  }
 }
 
-void notify_le_param_updated(struct bt_conn *conn)
-{
-    struct bt_conn_cb *cb;
+void notify_le_param_updated(struct bt_conn *conn) {
+  struct bt_conn_cb *cb;
 
-    /* If new connection parameters meet requirement of pending
-	 * parameters don't send slave conn param request anymore on timeout
-	 */
-    if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET) &&
-        conn->le.interval >= conn->le.interval_min &&
-        conn->le.interval <= conn->le.interval_max &&
-        conn->le.latency == conn->le.pending_latency &&
-        conn->le.timeout == conn->le.pending_timeout) {
-        atomic_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET);
-    }
+  /* If new connection parameters meet requirement of pending
+   * parameters don't send slave conn param request anymore on timeout
+   */
+  if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET) && conn->le.interval >= conn->le.interval_min && conn->le.interval <= conn->le.interval_max && conn->le.latency == conn->le.pending_latency
+      && conn->le.timeout == conn->le.pending_timeout) {
+    atomic_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET);
+  }
 
-    for (cb = callback_list; cb; cb = cb->_next) {
-        if (cb->le_param_updated) {
-            cb->le_param_updated(conn, conn->le.interval,
-                                 conn->le.latency,
-                                 conn->le.timeout);
-        }
+  for (cb = callback_list; cb; cb = cb->_next) {
+    if (cb->le_param_updated) {
+      cb->le_param_updated(conn, conn->le.interval, conn->le.latency, conn->le.timeout);
     }
+  }
 }
 
-bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param)
-{
-    struct bt_conn_cb *cb;
+bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param) {
+  struct bt_conn_cb *cb;
 
-    if (!bt_le_conn_params_valid(param)) {
-        return false;
-    }
+  if (!bt_le_conn_params_valid(param)) {
+    return false;
+  }
 
-    for (cb = callback_list; cb; cb = cb->_next) {
-        if (!cb->le_param_req) {
-            continue;
-        }
+  for (cb = callback_list; cb; cb = cb->_next) {
+    if (!cb->le_param_req) {
+      continue;
+    }
 
-        if (!cb->le_param_req(conn, param)) {
-            return false;
-        }
+    if (!cb->le_param_req(conn, param)) {
+      return false;
+    }
 
-        /* The callback may modify the parameters so we need to
-		 * double-check that it returned valid parameters.
-		 */
-        if (!bt_le_conn_params_valid(param)) {
-            return false;
-        }
+    /* The callback may modify the parameters so we need to
+     * double-check that it returned valid parameters.
+     */
+    if (!bt_le_conn_params_valid(param)) {
+      return false;
     }
+  }
 
-    /* Default to accepting if there's no app callback */
-    return true;
+  /* Default to accepting if there's no app callback */
+  return true;
 }
 
-static int send_conn_le_param_update(struct bt_conn *conn,
-                                     const struct bt_le_conn_param *param)
-{
-    BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn,
-           conn->le.features[0], param->interval_min,
-           param->interval_max, param->latency, param->timeout);
+static int send_conn_le_param_update(struct bt_conn *conn, const struct bt_le_conn_param *param) {
+  BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, conn->le.features[0], param->interval_min, param->interval_max, param->latency, param->timeout);
 
-    /* Use LE connection parameter request if both local and remote support
-	 * it; or if local role is master then use LE connection update.
-	 */
-    if ((BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features) &&
-         BT_FEAT_LE_CONN_PARAM_REQ_PROC(conn->le.features) &&
-         !atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_L2CAP)) ||
-        (conn->role == BT_HCI_ROLE_MASTER)) {
-        int rc;
+  /* Use LE connection parameter request if both local and remote support
+   * it; or if local role is master then use LE connection update.
+   */
+  if ((BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features) && BT_FEAT_LE_CONN_PARAM_REQ_PROC(conn->le.features) && !atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_L2CAP))
+      || (conn->role == BT_HCI_ROLE_MASTER)) {
+    int rc;
 
-        rc = bt_conn_le_conn_update(conn, param);
+    rc = bt_conn_le_conn_update(conn, param);
 
-        /* store those in case of fallback to L2CAP */
-        if (rc == 0) {
-            conn->le.pending_latency = param->latency;
-            conn->le.pending_timeout = param->timeout;
-        }
-
-        return rc;
+    /* store those in case of fallback to L2CAP */
+    if (rc == 0) {
+      conn->le.pending_latency = param->latency;
+      conn->le.pending_timeout = param->timeout;
     }
 
-    /* If remote master does not support LL Connection Parameters Request
-	 * Procedure
-	 */
-    return bt_l2cap_update_conn_param(conn, param);
+    return rc;
+  }
+
+  /* If remote master does not support LL Connection Parameters Request
+   * Procedure
+   */
+  return bt_l2cap_update_conn_param(conn, param);
 }
 
-static void tx_free(struct bt_conn_tx *tx)
-{
-    tx->cb = NULL;
-    tx->user_data = NULL;
-    tx->pending_no_cb = 0U;
-    k_fifo_put(&free_tx, tx);
+static void tx_free(struct bt_conn_tx *tx) {
+  tx->cb            = NULL;
+  tx->user_data     = NULL;
+  tx->pending_no_cb = 0U;
+  k_fifo_put(&free_tx, tx);
 }
 
-static void tx_notify(struct bt_conn *conn)
-{
-    BT_DBG("conn %p", conn);
+static void tx_notify(struct bt_conn *conn) {
+  BT_DBG("conn %p", conn);
 
-    while (1) {
-        struct bt_conn_tx *tx;
-        unsigned int key;
-        bt_conn_tx_cb_t cb;
-        void *user_data;
+  while (1) {
+    struct bt_conn_tx *tx;
+    unsigned int       key;
+    bt_conn_tx_cb_t    cb;
+    void              *user_data;
 
-        key = irq_lock();
-        if (sys_slist_is_empty(&conn->tx_complete)) {
-            irq_unlock(key);
-            break;
-        }
+    key = irq_lock();
+    if (sys_slist_is_empty(&conn->tx_complete)) {
+      irq_unlock(key);
+      break;
+    }
 
-        tx = (void *)sys_slist_get_not_empty(&conn->tx_complete);
-        irq_unlock(key);
+    tx = (void *)sys_slist_get_not_empty(&conn->tx_complete);
+    irq_unlock(key);
 
-        BT_DBG("tx %p cb %p user_data %p", tx, tx->cb, tx->user_data);
+    BT_DBG("tx %p cb %p user_data %p", tx, tx->cb, tx->user_data);
 
-        /* Copy over the params */
-        cb = tx->cb;
-        user_data = tx->user_data;
+    /* Copy over the params */
+    cb        = tx->cb;
+    user_data = tx->user_data;
 
-        /* Free up TX notify since there may be user waiting */
-        tx_free(tx);
+    /* Free up TX notify since there may be user waiting */
+    tx_free(tx);
 
-        /* Run the callback, at this point it should be safe to
-		 * allocate new buffers since the TX should have been
-		 * unblocked by tx_free.
-		 */
-        cb(conn, user_data);
-    }
+    /* Run the callback, at this point it should be safe to
+     * allocate new buffers since the TX should have been
+     * unblocked by tx_free.
+     */
+    cb(conn, user_data);
+  }
 }
 
-static void tx_complete_work(struct k_work *work)
-{
-    struct bt_conn *conn = CONTAINER_OF(work, struct bt_conn,
-                                        tx_complete_work);
+static void tx_complete_work(struct k_work *work) {
+  struct bt_conn *conn = CONTAINER_OF(work, struct bt_conn, tx_complete_work);
 
-    BT_DBG("conn %p", conn);
+  BT_DBG("conn %p", conn);
 
-    tx_notify(conn);
+  tx_notify(conn);
 }
 
-static void conn_update_timeout(struct k_work *work)
-{
-    struct bt_conn *conn = CONTAINER_OF(work, struct bt_conn, update_work);
-    const struct bt_le_conn_param *param;
+static void conn_update_timeout(struct k_work *work) {
+  struct bt_conn                *conn = CONTAINER_OF(work, struct bt_conn, update_work);
+  const struct bt_le_conn_param *param;
 
-    BT_DBG("conn %p", conn);
+  BT_DBG("conn %p", conn);
 
-    if (conn->state == BT_CONN_DISCONNECTED) {
-        bt_l2cap_disconnected(conn);
-        notify_disconnected(conn);
+  if (conn->state == BT_CONN_DISCONNECTED) {
+    bt_l2cap_disconnected(conn);
+    notify_disconnected(conn);
 
-        /* Release the reference we took for the very first
-		 * state transition.
-		 */
-        bt_conn_unref(conn);
-        return;
-    }
-
-    if (conn->type != BT_CONN_TYPE_LE) {
-        return;
-    }
-
-    if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
-        conn->role == BT_CONN_ROLE_MASTER) {
-        /* we don't call bt_conn_disconnect as it would also clear
-		 * auto connect flag if it was set, instead just cancel
-		 * connection directly
-		 */
-        bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN_CANCEL, NULL, NULL);
-        return;
-    }
+    /* Release the reference we took for the very first
+     * state transition.
+     */
+    bt_conn_unref(conn);
+    return;
+  }
+
+  if (conn->type != BT_CONN_TYPE_LE) {
+    return;
+  }
+
+  if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_CONN_ROLE_MASTER) {
+    /* we don't call bt_conn_disconnect as it would also clear
+     * auto connect flag if it was set, instead just cancel
+     * connection directly
+     */
+    bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN_CANCEL, NULL, NULL);
+    return;
+  }
 
 #if defined(CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS)
-    /* if application set own params use those, otherwise use defaults */
-    if (atomic_test_and_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET)) {
-        param = BT_LE_CONN_PARAM(conn->le.interval_min,
-                                 conn->le.interval_max,
-                                 conn->le.pending_latency,
-                                 conn->le.pending_timeout);
-
-        send_conn_le_param_update(conn, param);
-    } else {
-        param = BT_LE_CONN_PARAM(CONFIG_BT_PERIPHERAL_PREF_MIN_INT,
-                                 CONFIG_BT_PERIPHERAL_PREF_MAX_INT,
-                                 CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY,
-                                 CONFIG_BT_PERIPHERAL_PREF_TIMEOUT);
+  /* if application set own params use those, otherwise use defaults */
+  if (atomic_test_and_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET)) {
+    param = BT_LE_CONN_PARAM(conn->le.interval_min, conn->le.interval_max, conn->le.pending_latency, conn->le.pending_timeout);
 
-        send_conn_le_param_update(conn, param);
-    }
+    send_conn_le_param_update(conn, param);
+  } else {
+    param = BT_LE_CONN_PARAM(CONFIG_BT_PERIPHERAL_PREF_MIN_INT, CONFIG_BT_PERIPHERAL_PREF_MAX_INT, CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY, CONFIG_BT_PERIPHERAL_PREF_TIMEOUT);
+
+    send_conn_le_param_update(conn, param);
+  }
 #else
-    /* update only if application set own params */
-    if (atomic_test_and_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET)) {
-        param = BT_LE_CONN_PARAM(conn->le.interval_min,
-                                 conn->le.interval_max,
-                                 conn->le.latency,
-                                 conn->le.timeout);
+  /* update only if application set own params */
+  if (atomic_test_and_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET)) {
+    param = BT_LE_CONN_PARAM(conn->le.interval_min, conn->le.interval_max, conn->le.latency, conn->le.timeout);
 
-        send_conn_le_param_update(conn, param);
-    }
+    send_conn_le_param_update(conn, param);
+  }
 #endif
 
-    atomic_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE);
+  atomic_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE);
 }
 
 #if defined(CONFIG_BT_AUDIO)
-struct bt_conn *iso_conn_new(struct bt_conn *conns, size_t size)
-{
-    struct bt_conn *conn = NULL;
-    int i;
+struct bt_conn *iso_conn_new(struct bt_conn *conns, size_t size) {
+  struct bt_conn *conn = NULL;
+  int             i;
 
-    for (i = 0; i < size; i++) {
-        if (atomic_cas(&conns[i].ref, 0, 1)) {
-            conn = &conns[i];
-            break;
-        }
+  for (i = 0; i < size; i++) {
+    if (atomic_cas(&conns[i].ref, 0, 1)) {
+      conn = &conns[i];
+      break;
     }
+  }
 
-    if (!conn) {
-        return NULL;
-    }
+  if (!conn) {
+    return NULL;
+  }
 
-    (void)memset(conn, 0, offsetof(struct bt_conn, ref));
+  (void)memset(conn, 0, offsetof(struct bt_conn, ref));
 
-    return conn;
+  return conn;
 }
 #endif
 
-static struct bt_conn *conn_new(void)
-{
-    struct bt_conn *conn = NULL;
-    int i;
+static struct bt_conn *conn_new(void) {
+  struct bt_conn *conn = NULL;
+  int             i;
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (!atomic_get(&conns[i].ref)) {
-            conn = &conns[i];
-            break;
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (!atomic_get(&conns[i].ref)) {
+      conn = &conns[i];
+      break;
     }
+  }
 
-    if (!conn) {
-        return NULL;
-    }
+  if (!conn) {
+    return NULL;
+  }
 
-    (void)memset(conn, 0, sizeof(*conn));
-    k_delayed_work_init(&conn->update_work, conn_update_timeout);
+  (void)memset(conn, 0, sizeof(*conn));
+  k_delayed_work_init(&conn->update_work, conn_update_timeout);
 
-    k_work_init(&conn->tx_complete_work, tx_complete_work);
+  k_work_init(&conn->tx_complete_work, tx_complete_work);
 
-    atomic_set(&conn->ref, 1);
+  atomic_set(&conn->ref, 1);
 
-    return conn;
+  return conn;
 }
 
 #if defined(BFLB_BLE)
-bool le_check_valid_conn(void)
-{
-    int i;
+bool le_check_valid_conn(void) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (atomic_get(&conns[i].ref)) {
-            return true;
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (atomic_get(&conns[i].ref)) {
+      return true;
     }
+  }
 
-    return false;
+  return false;
 }
 
 #if defined(BFLB_HOST_ASSISTANT)
-void bt_notify_disconnected(void)
-{
-    int i;
+void bt_notify_disconnected(void) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (atomic_get(&conns[i].ref)) {
-            conns[i].err = BT_HCI_ERR_UNSPECIFIED;
-            notify_disconnected(&conns[i]);
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (atomic_get(&conns[i].ref)) {
+      conns[i].err = BT_HCI_ERR_UNSPECIFIED;
+      notify_disconnected(&conns[i]);
     }
+  }
 }
-#endif //#if defined(BFLB_HOST_ASSISTANT)
+#endif // #if defined(BFLB_HOST_ASSISTANT)
 #endif
 
 #if defined(CONFIG_BT_BREDR)
-void bt_sco_cleanup(struct bt_conn *sco_conn)
-{
-    bt_conn_unref(sco_conn->sco.acl);
-    sco_conn->sco.acl = NULL;
-    bt_conn_unref(sco_conn);
+void bt_sco_cleanup(struct bt_conn *sco_conn) {
+  bt_conn_unref(sco_conn->sco.acl);
+  sco_conn->sco.acl = NULL;
+  bt_conn_unref(sco_conn);
 }
 
-static struct bt_conn *sco_conn_new(void)
-{
-    struct bt_conn *sco_conn = NULL;
-    int i;
+static struct bt_conn *sco_conn_new(void) {
+  struct bt_conn *sco_conn = NULL;
+  int             i;
 
-    for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
-        if (!atomic_get(&sco_conns[i].ref)) {
-            sco_conn = &sco_conns[i];
-            break;
-        }
+  for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
+    if (!atomic_get(&sco_conns[i].ref)) {
+      sco_conn = &sco_conns[i];
+      break;
     }
+  }
 
-    if (!sco_conn) {
-        return NULL;
-    }
+  if (!sco_conn) {
+    return NULL;
+  }
 
-    (void)memset(sco_conn, 0, sizeof(*sco_conn));
+  (void)memset(sco_conn, 0, sizeof(*sco_conn));
 
-    atomic_set(&sco_conn->ref, 1);
+  atomic_set(&sco_conn->ref, 1);
 
-    return sco_conn;
+  return sco_conn;
 }
 
-struct bt_conn *bt_conn_create_br(const bt_addr_t *peer,
-                                  const struct bt_br_conn_param *param)
-{
-    struct bt_hci_cp_connect *cp;
-    struct bt_conn *conn;
-    struct net_buf *buf;
+struct bt_conn *bt_conn_create_br(const bt_addr_t *peer, const struct bt_br_conn_param *param) {
+  struct bt_hci_cp_connect *cp;
+  struct bt_conn           *conn;
+  struct net_buf           *buf;
 
-    conn = bt_conn_lookup_addr_br(peer);
-    if (conn) {
-        switch (conn->state) {
-            case BT_CONN_CONNECT:
-            case BT_CONN_CONNECTED:
-                return conn;
-            default:
-                bt_conn_unref(conn);
-                return NULL;
-        }
+  conn = bt_conn_lookup_addr_br(peer);
+  if (conn) {
+    switch (conn->state) {
+    case BT_CONN_CONNECT:
+    case BT_CONN_CONNECTED:
+      return conn;
+    default:
+      bt_conn_unref(conn);
+      return NULL;
     }
+  }
 
-    conn = bt_conn_add_br(peer);
-    if (!conn) {
-        return NULL;
-    }
+  conn = bt_conn_add_br(peer);
+  if (!conn) {
+    return NULL;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT, sizeof(*cp));
-    if (!buf) {
-        bt_conn_unref(conn);
-        return NULL;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT, sizeof(*cp));
+  if (!buf) {
+    bt_conn_unref(conn);
+    return NULL;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
 
-    (void)memset(cp, 0, sizeof(*cp));
+  (void)memset(cp, 0, sizeof(*cp));
 
-    memcpy(&cp->bdaddr, peer, sizeof(cp->bdaddr));
-    cp->packet_type = sys_cpu_to_le16(0xcc18); /* DM1 DH1 DM3 DH5 DM5 DH5 */
-    cp->pscan_rep_mode = 0x02;                 /* R2 */
-    cp->allow_role_switch = param->allow_role_switch ? 0x01 : 0x00;
-    cp->clock_offset = 0x0000; /* TODO used cached clock offset */
+  memcpy(&cp->bdaddr, peer, sizeof(cp->bdaddr));
+  cp->packet_type       = sys_cpu_to_le16(0xcc18); /* DM1 DH1 DM3 DH5 DM5 DH5 */
+  cp->pscan_rep_mode    = 0x02;                    /* R2 */
+  cp->allow_role_switch = param->allow_role_switch ? 0x01 : 0x00;
+  cp->clock_offset      = 0x0000; /* TODO used cached clock offset */
 
-    if (bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT, buf, NULL) < 0) {
-        bt_conn_unref(conn);
-        return NULL;
-    }
+  if (bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT, buf, NULL) < 0) {
+    bt_conn_unref(conn);
+    return NULL;
+  }
 
-    bt_conn_set_state(conn, BT_CONN_CONNECT);
-    conn->role = BT_CONN_ROLE_MASTER;
+  bt_conn_set_state(conn, BT_CONN_CONNECT);
+  conn->role = BT_CONN_ROLE_MASTER;
 
-    return conn;
+  return conn;
 }
 
-struct bt_conn *bt_conn_create_sco(const bt_addr_t *peer)
-{
-    struct bt_hci_cp_setup_sync_conn *cp;
-    struct bt_conn *sco_conn;
-    struct net_buf *buf;
-    int link_type;
+struct bt_conn *bt_conn_create_sco(const bt_addr_t *peer) {
+  struct bt_hci_cp_setup_sync_conn *cp;
+  struct bt_conn                   *sco_conn;
+  struct net_buf                   *buf;
+  int                               link_type;
 
-    sco_conn = bt_conn_lookup_addr_sco(peer);
-    if (sco_conn) {
-        switch (sco_conn->state) {
-            case BT_CONN_CONNECT:
-            case BT_CONN_CONNECTED:
-                return sco_conn;
-            default:
-                bt_conn_unref(sco_conn);
-                return NULL;
-        }
+  sco_conn = bt_conn_lookup_addr_sco(peer);
+  if (sco_conn) {
+    switch (sco_conn->state) {
+    case BT_CONN_CONNECT:
+    case BT_CONN_CONNECTED:
+      return sco_conn;
+    default:
+      bt_conn_unref(sco_conn);
+      return NULL;
     }
+  }
 
-    if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) {
-        link_type = BT_HCI_ESCO;
-    } else {
-        link_type = BT_HCI_SCO;
-    }
+  if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) {
+    link_type = BT_HCI_ESCO;
+  } else {
+    link_type = BT_HCI_SCO;
+  }
 
-    sco_conn = bt_conn_add_sco(peer, link_type);
-    if (!sco_conn) {
-        return NULL;
-    }
+  sco_conn = bt_conn_add_sco(peer, link_type);
+  if (!sco_conn) {
+    return NULL;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_SETUP_SYNC_CONN, sizeof(*cp));
-    if (!buf) {
-        bt_sco_cleanup(sco_conn);
-        return NULL;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_SETUP_SYNC_CONN, sizeof(*cp));
+  if (!buf) {
+    bt_sco_cleanup(sco_conn);
+    return NULL;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
 
-    (void)memset(cp, 0, sizeof(*cp));
+  (void)memset(cp, 0, sizeof(*cp));
 
-    BT_ERR("handle : %x", sco_conn->sco.acl->handle);
+  BT_ERR("handle : %x", sco_conn->sco.acl->handle);
 
-    cp->handle = sco_conn->sco.acl->handle;
-    cp->pkt_type = sco_conn->sco.pkt_type;
-    cp->tx_bandwidth = 0x00001f40;
-    cp->rx_bandwidth = 0x00001f40;
-    cp->max_latency = 0x0007;
-    cp->retrans_effort = 0x01;
-    cp->content_format = BT_VOICE_CVSD_16BIT;
+  cp->handle         = sco_conn->sco.acl->handle;
+  cp->pkt_type       = sco_conn->sco.pkt_type;
+  cp->tx_bandwidth   = 0x00001f40;
+  cp->rx_bandwidth   = 0x00001f40;
+  cp->max_latency    = 0x0007;
+  cp->retrans_effort = 0x01;
+  cp->content_format = BT_VOICE_CVSD_16BIT;
 
-    if (bt_hci_cmd_send_sync(BT_HCI_OP_SETUP_SYNC_CONN, buf,
-                             NULL) < 0) {
-        bt_sco_cleanup(sco_conn);
-        return NULL;
-    }
+  if (bt_hci_cmd_send_sync(BT_HCI_OP_SETUP_SYNC_CONN, buf, NULL) < 0) {
+    bt_sco_cleanup(sco_conn);
+    return NULL;
+  }
 
-    bt_conn_set_state(sco_conn, BT_CONN_CONNECT);
+  bt_conn_set_state(sco_conn, BT_CONN_CONNECT);
 
-    return sco_conn;
+  return sco_conn;
 }
 
-struct bt_conn *bt_conn_lookup_addr_sco(const bt_addr_t *peer)
-{
-    int i;
+struct bt_conn *bt_conn_lookup_addr_sco(const bt_addr_t *peer) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
-        if (!atomic_get(&sco_conns[i].ref)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
+    if (!atomic_get(&sco_conns[i].ref)) {
+      continue;
+    }
 
-        if (sco_conns[i].type != BT_CONN_TYPE_SCO) {
-            continue;
-        }
+    if (sco_conns[i].type != BT_CONN_TYPE_SCO) {
+      continue;
+    }
 
-        if (!bt_addr_cmp(peer, &sco_conns[i].sco.acl->br.dst)) {
-            return bt_conn_ref(&sco_conns[i]);
-        }
+    if (!bt_addr_cmp(peer, &sco_conns[i].sco.acl->br.dst)) {
+      return bt_conn_ref(&sco_conns[i]);
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-struct bt_conn *bt_conn_lookup_addr_br(const bt_addr_t *peer)
-{
-    int i;
+struct bt_conn *bt_conn_lookup_addr_br(const bt_addr_t *peer) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (!atomic_get(&conns[i].ref)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (!atomic_get(&conns[i].ref)) {
+      continue;
+    }
 
-        if (conns[i].type != BT_CONN_TYPE_BR) {
-            continue;
-        }
+    if (conns[i].type != BT_CONN_TYPE_BR) {
+      continue;
+    }
 
-        if (!bt_addr_cmp(peer, &conns[i].br.dst)) {
-            return bt_conn_ref(&conns[i]);
-        }
+    if (!bt_addr_cmp(peer, &conns[i].br.dst)) {
+      return bt_conn_ref(&conns[i]);
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-struct bt_conn *bt_conn_add_sco(const bt_addr_t *peer, int link_type)
-{
-    struct bt_conn *sco_conn = sco_conn_new();
+struct bt_conn *bt_conn_add_sco(const bt_addr_t *peer, int link_type) {
+  struct bt_conn *sco_conn = sco_conn_new();
 
-    if (!sco_conn) {
-        return NULL;
-    }
+  if (!sco_conn) {
+    return NULL;
+  }
 
-    sco_conn->sco.acl = bt_conn_lookup_addr_br(peer);
-    sco_conn->type = BT_CONN_TYPE_SCO;
+  sco_conn->sco.acl = bt_conn_lookup_addr_br(peer);
+  sco_conn->type    = BT_CONN_TYPE_SCO;
 
-    if (link_type == BT_HCI_SCO) {
-        if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) {
-            sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type &
-                                      ESCO_PKT_MASK);
-        } else {
-            sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type &
-                                      SCO_PKT_MASK);
-        }
-    } else if (link_type == BT_HCI_ESCO) {
-        sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type &
-                                  ~EDR_ESCO_PKT_MASK);
+  if (link_type == BT_HCI_SCO) {
+    if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) {
+      sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & ESCO_PKT_MASK);
+    } else {
+      sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & SCO_PKT_MASK);
     }
+  } else if (link_type == BT_HCI_ESCO) {
+    sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & ~EDR_ESCO_PKT_MASK);
+  }
 
-    return sco_conn;
+  return sco_conn;
 }
 
-struct bt_conn *bt_conn_add_br(const bt_addr_t *peer)
-{
-    struct bt_conn *conn = conn_new();
+struct bt_conn *bt_conn_add_br(const bt_addr_t *peer) {
+  struct bt_conn *conn = conn_new();
 
-    if (!conn) {
-        return NULL;
-    }
+  if (!conn) {
+    return NULL;
+  }
 
-    bt_addr_copy(&conn->br.dst, peer);
-    conn->type = BT_CONN_TYPE_BR;
+  bt_addr_copy(&conn->br.dst, peer);
+  conn->type = BT_CONN_TYPE_BR;
 
-    return conn;
+  return conn;
 }
 
-static int pin_code_neg_reply(const bt_addr_t *bdaddr)
-{
-    struct bt_hci_cp_pin_code_neg_reply *cp;
-    struct net_buf *buf;
+static int pin_code_neg_reply(const bt_addr_t *bdaddr) {
+  struct bt_hci_cp_pin_code_neg_reply *cp;
+  struct net_buf                      *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_NEG_REPLY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_NEG_REPLY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, bdaddr);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, bdaddr);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_PIN_CODE_NEG_REPLY, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_PIN_CODE_NEG_REPLY, buf, NULL);
 }
 
-static int pin_code_reply(struct bt_conn *conn, const char *pin, u8_t len)
-{
-    struct bt_hci_cp_pin_code_reply *cp;
-    struct net_buf *buf;
+static int pin_code_reply(struct bt_conn *conn, const char *pin, u8_t len) {
+  struct bt_hci_cp_pin_code_reply *cp;
+  struct net_buf                  *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_REPLY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_REPLY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
 
-    bt_addr_copy(&cp->bdaddr, &conn->br.dst);
-    cp->pin_len = len;
-    strncpy((char *)cp->pin_code, pin, sizeof(cp->pin_code));
+  bt_addr_copy(&cp->bdaddr, &conn->br.dst);
+  cp->pin_len = len;
+  strncpy((char *)cp->pin_code, pin, sizeof(cp->pin_code));
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_PIN_CODE_REPLY, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_PIN_CODE_REPLY, buf, NULL);
 }
 
-int bt_conn_auth_pincode_entry(struct bt_conn *conn, const char *pin)
-{
-    size_t len;
+int bt_conn_auth_pincode_entry(struct bt_conn *conn, const char *pin) {
+  size_t len;
 
-    if (!bt_auth) {
-        return -EINVAL;
-    }
+  if (!bt_auth) {
+    return -EINVAL;
+  }
 
-    if (conn->type != BT_CONN_TYPE_BR) {
-        return -EINVAL;
-    }
+  if (conn->type != BT_CONN_TYPE_BR) {
+    return -EINVAL;
+  }
 
-    len = strlen(pin);
-    if (len > 16) {
-        return -EINVAL;
-    }
+  len = strlen(pin);
+  if (len > 16) {
+    return -EINVAL;
+  }
 
-    if (conn->required_sec_level == BT_SECURITY_L3 && len < 16) {
-        BT_WARN("PIN code for %s is not 16 bytes wide",
-                bt_addr_str(&conn->br.dst));
-        return -EPERM;
-    }
+  if (conn->required_sec_level == BT_SECURITY_L3 && len < 16) {
+    BT_WARN("PIN code for %s is not 16 bytes wide", bt_addr_str(&conn->br.dst));
+    return -EPERM;
+  }
 
-    /* Allow user send entered PIN to remote, then reset user state. */
-    if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
-        return -EPERM;
-    }
+  /* Allow user send entered PIN to remote, then reset user state. */
+  if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
+    return -EPERM;
+  }
 
-    if (len == 16) {
-        atomic_set_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE);
-    }
+  if (len == 16) {
+    atomic_set_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE);
+  }
 
-    return pin_code_reply(conn, pin, len);
+  return pin_code_reply(conn, pin, len);
 }
 
-void bt_conn_pin_code_req(struct bt_conn *conn)
-{
-    if (bt_auth && bt_auth->pincode_entry) {
-        bool secure = false;
+void bt_conn_pin_code_req(struct bt_conn *conn) {
+  if (bt_auth && bt_auth->pincode_entry) {
+    bool secure = false;
 
-        if (conn->required_sec_level == BT_SECURITY_L3) {
-            secure = true;
-        }
-
-        atomic_set_bit(conn->flags, BT_CONN_USER);
-        atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING);
-        bt_auth->pincode_entry(conn, secure);
-    } else {
-        pin_code_neg_reply(&conn->br.dst);
+    if (conn->required_sec_level == BT_SECURITY_L3) {
+      secure = true;
     }
+
+    atomic_set_bit(conn->flags, BT_CONN_USER);
+    atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING);
+    bt_auth->pincode_entry(conn, secure);
+  } else {
+    pin_code_neg_reply(&conn->br.dst);
+  }
 }
 
-u8_t bt_conn_get_io_capa(void)
-{
-    if (!bt_auth) {
-        return BT_IO_NO_INPUT_OUTPUT;
-    }
+u8_t bt_conn_get_io_capa(void) {
+  if (!bt_auth) {
+    return BT_IO_NO_INPUT_OUTPUT;
+  }
 
-    if (bt_auth->passkey_confirm && bt_auth->passkey_display) {
-        return BT_IO_DISPLAY_YESNO;
-    }
+  if (bt_auth->passkey_confirm && bt_auth->passkey_display) {
+    return BT_IO_DISPLAY_YESNO;
+  }
 
-    if (bt_auth->passkey_entry) {
-        return BT_IO_KEYBOARD_ONLY;
-    }
+  if (bt_auth->passkey_entry) {
+    return BT_IO_KEYBOARD_ONLY;
+  }
 
-    if (bt_auth->passkey_display) {
-        return BT_IO_DISPLAY_ONLY;
-    }
+  if (bt_auth->passkey_display) {
+    return BT_IO_DISPLAY_ONLY;
+  }
 
-    return BT_IO_NO_INPUT_OUTPUT;
+  return BT_IO_NO_INPUT_OUTPUT;
 }
 
-static u8_t ssp_pair_method(const struct bt_conn *conn)
-{
-    return ssp_method[conn->br.remote_io_capa][bt_conn_get_io_capa()];
-}
+static u8_t ssp_pair_method(const struct bt_conn *conn) { return ssp_method[conn->br.remote_io_capa][bt_conn_get_io_capa()]; }
 
-u8_t bt_conn_ssp_get_auth(const struct bt_conn *conn)
-{
-    /* Validate no bond auth request, and if valid use it. */
-    if ((conn->br.remote_auth == BT_HCI_NO_BONDING) ||
-        ((conn->br.remote_auth == BT_HCI_NO_BONDING_MITM) &&
-         (ssp_pair_method(conn) > JUST_WORKS))) {
-        return conn->br.remote_auth;
-    }
+u8_t bt_conn_ssp_get_auth(const struct bt_conn *conn) {
+  /* Validate no bond auth request, and if valid use it. */
+  if ((conn->br.remote_auth == BT_HCI_NO_BONDING) || ((conn->br.remote_auth == BT_HCI_NO_BONDING_MITM) && (ssp_pair_method(conn) > JUST_WORKS))) {
+    return conn->br.remote_auth;
+  }
 
-    /* Local & remote have enough IO capabilities to get MITM protection. */
-    if (ssp_pair_method(conn) > JUST_WORKS) {
-        return conn->br.remote_auth | BT_MITM;
-    }
+  /* Local & remote have enough IO capabilities to get MITM protection. */
+  if (ssp_pair_method(conn) > JUST_WORKS) {
+    return conn->br.remote_auth | BT_MITM;
+  }
 
-    /* No MITM protection possible so ignore remote MITM requirement. */
-    return (conn->br.remote_auth & ~BT_MITM);
+  /* No MITM protection possible so ignore remote MITM requirement. */
+  return (conn->br.remote_auth & ~BT_MITM);
 }
 
-static int ssp_confirm_reply(struct bt_conn *conn)
-{
-    struct bt_hci_cp_user_confirm_reply *cp;
-    struct net_buf *buf;
+static int ssp_confirm_reply(struct bt_conn *conn) {
+  struct bt_hci_cp_user_confirm_reply *cp;
+  struct net_buf                      *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_USER_CONFIRM_REPLY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_USER_CONFIRM_REPLY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, &conn->br.dst);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, &conn->br.dst);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_USER_CONFIRM_REPLY, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_USER_CONFIRM_REPLY, buf, NULL);
 }
 
-static int ssp_confirm_neg_reply(struct bt_conn *conn)
-{
-    struct bt_hci_cp_user_confirm_reply *cp;
-    struct net_buf *buf;
+static int ssp_confirm_neg_reply(struct bt_conn *conn) {
+  struct bt_hci_cp_user_confirm_reply *cp;
+  struct net_buf                      *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_USER_CONFIRM_NEG_REPLY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_USER_CONFIRM_NEG_REPLY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, &conn->br.dst);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, &conn->br.dst);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_USER_CONFIRM_NEG_REPLY, buf,
-                                NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_USER_CONFIRM_NEG_REPLY, buf, NULL);
 }
 
-void bt_conn_ssp_auth_complete(struct bt_conn *conn, u8_t status)
-{
-    if (!status) {
-        bool bond = !atomic_test_bit(conn->flags, BT_CONN_BR_NOBOND);
+void bt_conn_ssp_auth_complete(struct bt_conn *conn, u8_t status) {
+  if (!status) {
+    bool bond = !atomic_test_bit(conn->flags, BT_CONN_BR_NOBOND);
 
-        if (bt_auth && bt_auth->pairing_complete) {
-            bt_auth->pairing_complete(conn, bond);
-        }
-    } else {
-        if (bt_auth && bt_auth->pairing_failed) {
-            bt_auth->pairing_failed(conn, status);
-        }
+    if (bt_auth && bt_auth->pairing_complete) {
+      bt_auth->pairing_complete(conn, bond);
+    }
+  } else {
+    if (bt_auth && bt_auth->pairing_failed) {
+      bt_auth->pairing_failed(conn, status);
     }
+  }
 }
 
-void bt_conn_ssp_auth(struct bt_conn *conn, u32_t passkey)
-{
-    conn->br.pairing_method = ssp_pair_method(conn);
+void bt_conn_ssp_auth(struct bt_conn *conn, u32_t passkey) {
+  conn->br.pairing_method = ssp_pair_method(conn);
 
+  /*
+   * If local required security is HIGH then MITM is mandatory.
+   * MITM protection is no achievable when SSP 'justworks' is applied.
+   */
+  if (conn->required_sec_level > BT_SECURITY_L2 && conn->br.pairing_method == JUST_WORKS) {
+    BT_DBG("MITM protection infeasible for required security");
+    ssp_confirm_neg_reply(conn);
+    return;
+  }
+
+  switch (conn->br.pairing_method) {
+  case PASSKEY_CONFIRM:
+    atomic_set_bit(conn->flags, BT_CONN_USER);
+    bt_auth->passkey_confirm(conn, passkey);
+    break;
+  case PASSKEY_DISPLAY:
+    atomic_set_bit(conn->flags, BT_CONN_USER);
+    bt_auth->passkey_display(conn, passkey);
+    break;
+  case PASSKEY_INPUT:
+    atomic_set_bit(conn->flags, BT_CONN_USER);
+    bt_auth->passkey_entry(conn);
+    break;
+  case JUST_WORKS:
     /*
-	 * If local required security is HIGH then MITM is mandatory.
-	 * MITM protection is no achievable when SSP 'justworks' is applied.
-	 */
-    if (conn->required_sec_level > BT_SECURITY_L2 &&
-        conn->br.pairing_method == JUST_WORKS) {
-        BT_DBG("MITM protection infeasible for required security");
-        ssp_confirm_neg_reply(conn);
-        return;
+     * When local host works as pairing acceptor and 'justworks'
+     * model is applied then notify user about such pairing request.
+     * [BT Core 4.2 table 5.7, Vol 3, Part C, 5.2.2.6]
+     */
+    if (bt_auth && bt_auth->pairing_confirm && !atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR)) {
+      atomic_set_bit(conn->flags, BT_CONN_USER);
+      bt_auth->pairing_confirm(conn);
+      break;
     }
+    ssp_confirm_reply(conn);
+    break;
+  default:
+    break;
+  }
+}
 
-    switch (conn->br.pairing_method) {
-        case PASSKEY_CONFIRM:
-            atomic_set_bit(conn->flags, BT_CONN_USER);
-            bt_auth->passkey_confirm(conn, passkey);
-            break;
-        case PASSKEY_DISPLAY:
-            atomic_set_bit(conn->flags, BT_CONN_USER);
-            bt_auth->passkey_display(conn, passkey);
-            break;
-        case PASSKEY_INPUT:
-            atomic_set_bit(conn->flags, BT_CONN_USER);
-            bt_auth->passkey_entry(conn);
-            break;
-        case JUST_WORKS:
-            /*
-		 * When local host works as pairing acceptor and 'justworks'
-		 * model is applied then notify user about such pairing request.
-		 * [BT Core 4.2 table 5.7, Vol 3, Part C, 5.2.2.6]
-		 */
-            if (bt_auth && bt_auth->pairing_confirm &&
-                !atomic_test_bit(conn->flags,
-                                 BT_CONN_BR_PAIRING_INITIATOR)) {
-                atomic_set_bit(conn->flags, BT_CONN_USER);
-                bt_auth->pairing_confirm(conn);
-                break;
-            }
-            ssp_confirm_reply(conn);
-            break;
-        default:
-            break;
-    }
-}
-
-static int ssp_passkey_reply(struct bt_conn *conn, unsigned int passkey)
-{
-    struct bt_hci_cp_user_passkey_reply *cp;
-    struct net_buf *buf;
-
-    BT_DBG("");
-
-    buf = bt_hci_cmd_create(BT_HCI_OP_USER_PASSKEY_REPLY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+static int ssp_passkey_reply(struct bt_conn *conn, unsigned int passkey) {
+  struct bt_hci_cp_user_passkey_reply *cp;
+  struct net_buf                      *buf;
+
+  BT_DBG("");
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, &conn->br.dst);
-    cp->passkey = sys_cpu_to_le32(passkey);
+  buf = bt_hci_cmd_create(BT_HCI_OP_USER_PASSKEY_REPLY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_USER_PASSKEY_REPLY, buf, NULL);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, &conn->br.dst);
+  cp->passkey = sys_cpu_to_le32(passkey);
+
+  return bt_hci_cmd_send_sync(BT_HCI_OP_USER_PASSKEY_REPLY, buf, NULL);
 }
 
-static int ssp_passkey_neg_reply(struct bt_conn *conn)
-{
-    struct bt_hci_cp_user_passkey_neg_reply *cp;
-    struct net_buf *buf;
+static int ssp_passkey_neg_reply(struct bt_conn *conn) {
+  struct bt_hci_cp_user_passkey_neg_reply *cp;
+  struct net_buf                          *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_USER_PASSKEY_NEG_REPLY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_USER_PASSKEY_NEG_REPLY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, &conn->br.dst);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, &conn->br.dst);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_USER_PASSKEY_NEG_REPLY, buf,
-                                NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_USER_PASSKEY_NEG_REPLY, buf, NULL);
 }
 
-static int bt_hci_connect_br_cancel(struct bt_conn *conn)
-{
-    struct bt_hci_cp_connect_cancel *cp;
-    struct bt_hci_rp_connect_cancel *rp;
-    struct net_buf *buf, *rsp;
-    int err;
+static int bt_hci_connect_br_cancel(struct bt_conn *conn) {
+  struct bt_hci_cp_connect_cancel *cp;
+  struct bt_hci_rp_connect_cancel *rp;
+  struct net_buf                  *buf, *rsp;
+  int                              err;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT_CANCEL, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT_CANCEL, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    memcpy(&cp->bdaddr, &conn->br.dst, sizeof(cp->bdaddr));
+  cp = net_buf_add(buf, sizeof(*cp));
+  memcpy(&cp->bdaddr, &conn->br.dst, sizeof(cp->bdaddr));
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT_CANCEL, buf, &rsp);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT_CANCEL, buf, &rsp);
+  if (err) {
+    return err;
+  }
 
-    rp = (void *)rsp->data;
+  rp = (void *)rsp->data;
 
-    err = rp->status ? -EIO : 0;
+  err = rp->status ? -EIO : 0;
 
-    net_buf_unref(rsp);
+  net_buf_unref(rsp);
 
-    return err;
+  return err;
 }
 
-static int conn_auth(struct bt_conn *conn)
-{
-    struct bt_hci_cp_auth_requested *auth;
-    struct net_buf *buf;
+static int conn_auth(struct bt_conn *conn) {
+  struct bt_hci_cp_auth_requested *auth;
+  struct net_buf                  *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_AUTH_REQUESTED, sizeof(*auth));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_AUTH_REQUESTED, sizeof(*auth));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    auth = net_buf_add(buf, sizeof(*auth));
-    auth->handle = sys_cpu_to_le16(conn->handle);
+  auth         = net_buf_add(buf, sizeof(*auth));
+  auth->handle = sys_cpu_to_le16(conn->handle);
 
-    atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR);
+  atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_AUTH_REQUESTED, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_AUTH_REQUESTED, buf, NULL);
 }
 #endif /* CONFIG_BT_BREDR */
 
 #if defined(CONFIG_BT_SMP)
-void bt_conn_identity_resolved(struct bt_conn *conn)
-{
-    const bt_addr_le_t *rpa;
-    struct bt_conn_cb *cb;
+void bt_conn_identity_resolved(struct bt_conn *conn) {
+  const bt_addr_le_t *rpa;
+  struct bt_conn_cb  *cb;
 
-    if (conn->role == BT_HCI_ROLE_MASTER) {
-        rpa = &conn->le.resp_addr;
-    } else {
-        rpa = &conn->le.init_addr;
-    }
+  if (conn->role == BT_HCI_ROLE_MASTER) {
+    rpa = &conn->le.resp_addr;
+  } else {
+    rpa = &conn->le.init_addr;
+  }
 
-    for (cb = callback_list; cb; cb = cb->_next) {
-        if (cb->identity_resolved) {
-            cb->identity_resolved(conn, rpa, &conn->le.dst);
-        }
+  for (cb = callback_list; cb; cb = cb->_next) {
+    if (cb->identity_resolved) {
+      cb->identity_resolved(conn, rpa, &conn->le.dst);
     }
+  }
 }
 
-int bt_conn_le_start_encryption(struct bt_conn *conn, u8_t rand[8],
-                                u8_t ediv[2], const u8_t *ltk, size_t len)
-{
-    struct bt_hci_cp_le_start_encryption *cp;
-    struct net_buf *buf;
+int bt_conn_le_start_encryption(struct bt_conn *conn, u8_t rand[8], u8_t ediv[2], const u8_t *ltk, size_t len) {
+  struct bt_hci_cp_le_start_encryption *cp;
+  struct net_buf                       *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_START_ENCRYPTION, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_START_ENCRYPTION, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(conn->handle);
-    memcpy(&cp->rand, rand, sizeof(cp->rand));
-    memcpy(&cp->ediv, ediv, sizeof(cp->ediv));
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = sys_cpu_to_le16(conn->handle);
+  memcpy(&cp->rand, rand, sizeof(cp->rand));
+  memcpy(&cp->ediv, ediv, sizeof(cp->ediv));
 
-    memcpy(cp->ltk, ltk, len);
-    if (len < sizeof(cp->ltk)) {
-        (void)memset(cp->ltk + len, 0, sizeof(cp->ltk) - len);
-    }
+  memcpy(cp->ltk, ltk, len);
+  if (len < sizeof(cp->ltk)) {
+    (void)memset(cp->ltk + len, 0, sizeof(cp->ltk) - len);
+  }
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_START_ENCRYPTION, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_START_ENCRYPTION, buf, NULL);
 }
 #endif /* CONFIG_BT_SMP */
 
 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
-u8_t bt_conn_enc_key_size(struct bt_conn *conn)
-{
-    //GATT/SR/GAR/BV-04-C
-    // if the connection instance is valid
-    if (!conn) {
-        return 0;
-    }
+u8_t bt_conn_enc_key_size(struct bt_conn *conn) {
+  // GATT/SR/GAR/BV-04-C
+  //  if the connection instance is valid
+  if (!conn) {
+    return 0;
+  }
 
-    if (!conn->encrypt) {
-        return 0;
-    }
+  if (!conn->encrypt) {
+    return 0;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_BREDR) &&
-        conn->type == BT_CONN_TYPE_BR) {
-        struct bt_hci_cp_read_encryption_key_size *cp;
-        struct bt_hci_rp_read_encryption_key_size *rp;
-        struct net_buf *buf;
-        struct net_buf *rsp;
-        u8_t key_size;
+  if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
+    struct bt_hci_cp_read_encryption_key_size *cp;
+    struct bt_hci_rp_read_encryption_key_size *rp;
+    struct net_buf                            *buf;
+    struct net_buf                            *rsp;
+    u8_t                                       key_size;
 
-        buf = bt_hci_cmd_create(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE,
-                                sizeof(*cp));
-        if (!buf) {
-            return 0;
-        }
+    buf = bt_hci_cmd_create(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, sizeof(*cp));
+    if (!buf) {
+      return 0;
+    }
 
-        cp = net_buf_add(buf, sizeof(*cp));
-        cp->handle = sys_cpu_to_le16(conn->handle);
+    cp         = net_buf_add(buf, sizeof(*cp));
+    cp->handle = sys_cpu_to_le16(conn->handle);
 
-        if (bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE,
-                                 buf, &rsp)) {
-            return 0;
-        }
+    if (bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, buf, &rsp)) {
+      return 0;
+    }
 
-        rp = (void *)rsp->data;
+    rp = (void *)rsp->data;
 
-        key_size = rp->status ? 0 : rp->key_size;
+    key_size = rp->status ? 0 : rp->key_size;
 
-        net_buf_unref(rsp);
+    net_buf_unref(rsp);
 
-        return key_size;
-    }
+    return key_size;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SMP)) {
-        return conn->le.keys ? conn->le.keys->enc_size : 0;
-    }
+  if (IS_ENABLED(CONFIG_BT_SMP)) {
+    return conn->le.keys ? conn->le.keys->enc_size : 0;
+  }
 
-    return 0;
+  return 0;
 }
 
-void bt_conn_security_changed(struct bt_conn *conn, enum bt_security_err err)
-{
-    struct bt_conn_cb *cb;
+void bt_conn_security_changed(struct bt_conn *conn, enum bt_security_err err) {
+  struct bt_conn_cb *cb;
 
-    for (cb = callback_list; cb; cb = cb->_next) {
-        if (cb->security_changed) {
-            cb->security_changed(conn, conn->sec_level, err);
-        }
+  for (cb = callback_list; cb; cb = cb->_next) {
+    if (cb->security_changed) {
+      cb->security_changed(conn, conn->sec_level, err);
     }
+  }
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-    if (!err && conn->sec_level >= BT_SECURITY_L2) {
-        bt_keys_update_usage(conn->id, bt_conn_get_dst(conn));
-    }
+  if (!err && conn->sec_level >= BT_SECURITY_L2) {
+    bt_keys_update_usage(conn->id, bt_conn_get_dst(conn));
+  }
 #endif
 }
 
-static int start_security(struct bt_conn *conn)
-{
+static int start_security(struct bt_conn *conn) {
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING)) {
-            return -EBUSY;
-        }
-
-        if (conn->required_sec_level > BT_SECURITY_L3) {
-            return -ENOTSUP;
-        }
+  if (conn->type == BT_CONN_TYPE_BR) {
+    if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING)) {
+      return -EBUSY;
+    }
 
-        if (bt_conn_get_io_capa() == BT_IO_NO_INPUT_OUTPUT &&
-            conn->required_sec_level > BT_SECURITY_L2) {
-            return -EINVAL;
-        }
+    if (conn->required_sec_level > BT_SECURITY_L3) {
+      return -ENOTSUP;
+    }
 
-        return conn_auth(conn);
+    if (bt_conn_get_io_capa() == BT_IO_NO_INPUT_OUTPUT && conn->required_sec_level > BT_SECURITY_L2) {
+      return -EINVAL;
     }
+
+    return conn_auth(conn);
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    if (IS_ENABLED(CONFIG_BT_SMP)) {
-        return bt_smp_start_security(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_SMP)) {
+    return bt_smp_start_security(conn);
+  }
 
-    return -EINVAL;
+  return -EINVAL;
 }
 
-int bt_conn_set_security(struct bt_conn *conn, bt_security_t sec)
-{
-    int err;
+int bt_conn_set_security(struct bt_conn *conn, bt_security_t sec) {
+  int err;
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) &&
-        sec < BT_SECURITY_L4) {
-        return -EOPNOTSUPP;
-    }
+  if (IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) && sec < BT_SECURITY_L4) {
+    return -EOPNOTSUPP;
+  }
 
-    /* nothing to do */
-    if (conn->sec_level >= sec || conn->required_sec_level >= sec) {
-        return 0;
-    }
+  /* nothing to do */
+  if (conn->sec_level >= sec || conn->required_sec_level >= sec) {
+    return 0;
+  }
 
-    atomic_set_bit_to(conn->flags, BT_CONN_FORCE_PAIR,
-                      sec & BT_SECURITY_FORCE_PAIR);
-    conn->required_sec_level = sec & ~BT_SECURITY_FORCE_PAIR;
+  atomic_set_bit_to(conn->flags, BT_CONN_FORCE_PAIR, sec & BT_SECURITY_FORCE_PAIR);
+  conn->required_sec_level = sec & ~BT_SECURITY_FORCE_PAIR;
 
-    err = start_security(conn);
+  err = start_security(conn);
 
-    /* reset required security level in case of error */
-    if (err) {
-        conn->required_sec_level = conn->sec_level;
-    }
+  /* reset required security level in case of error */
+  if (err) {
+    conn->required_sec_level = conn->sec_level;
+  }
 
-    return err;
+  return err;
 }
 
-bt_security_t bt_conn_get_security(struct bt_conn *conn)
-{
-    return conn->sec_level;
-}
+bt_security_t bt_conn_get_security(struct bt_conn *conn) { return conn->sec_level; }
 #else
-bt_security_t bt_conn_get_security(struct bt_conn *conn)
-{
-    return BT_SECURITY_L1;
-}
+bt_security_t bt_conn_get_security(struct bt_conn *conn) { return BT_SECURITY_L1; }
 #endif /* CONFIG_BT_SMP */
 
-void bt_conn_cb_register(struct bt_conn_cb *cb)
-{
-    cb->_next = callback_list;
-    callback_list = cb;
+void bt_conn_cb_register(struct bt_conn_cb *cb) {
+  cb->_next     = callback_list;
+  callback_list = cb;
 }
 
-void bt_conn_reset_rx_state(struct bt_conn *conn)
-{
-    if (!conn->rx_len) {
-        return;
-    }
+void bt_conn_reset_rx_state(struct bt_conn *conn) {
+  if (!conn->rx_len) {
+    return;
+  }
 
-    net_buf_unref(conn->rx);
-    conn->rx = NULL;
-    conn->rx_len = 0U;
+  net_buf_unref(conn->rx);
+  conn->rx     = NULL;
+  conn->rx_len = 0U;
 }
 
-void bt_conn_recv(struct bt_conn *conn, struct net_buf *buf, u8_t flags)
-{
-    struct bt_l2cap_hdr *hdr;
-    u16_t len;
-
-    /* Make sure we notify any pending TX callbacks before processing
-	 * new data for this connection.
-	 */
-    tx_notify(conn);
-
-    BT_DBG("handle %u len %u flags %02x", conn->handle, buf->len, flags);
-
-    /* Check packet boundary flags */
-    switch (flags) {
-        case BT_ACL_START:
-            hdr = (void *)buf->data;
-            len = sys_le16_to_cpu(hdr->len);
-
-            BT_DBG("First, len %u final %u", buf->len, len);
-
-            if (conn->rx_len) {
-                BT_ERR("Unexpected first L2CAP frame");
-                bt_conn_reset_rx_state(conn);
-            }
-
-            conn->rx_len = (sizeof(*hdr) + len) - buf->len;
-            BT_DBG("rx_len %u", conn->rx_len);
-            if (conn->rx_len) {
-                conn->rx = buf;
-                return;
-            }
-
-            break;
-        case BT_ACL_CONT:
-            if (!conn->rx_len) {
-                BT_ERR("Unexpected L2CAP continuation");
-                bt_conn_reset_rx_state(conn);
-                net_buf_unref(buf);
-                return;
-            }
-
-            if (buf->len > conn->rx_len) {
-                BT_ERR("L2CAP data overflow");
-                bt_conn_reset_rx_state(conn);
-                net_buf_unref(buf);
-                return;
-            }
-
-            BT_DBG("Cont, len %u rx_len %u", buf->len, conn->rx_len);
-
-            if (buf->len > net_buf_tailroom(conn->rx)) {
-                BT_ERR("Not enough buffer space for L2CAP data");
-                bt_conn_reset_rx_state(conn);
-                net_buf_unref(buf);
-                return;
-            }
-
-            net_buf_add_mem(conn->rx, buf->data, buf->len);
-            conn->rx_len -= buf->len;
-            net_buf_unref(buf);
-
-            if (conn->rx_len) {
-                return;
-            }
-
-            buf = conn->rx;
-            conn->rx = NULL;
-            conn->rx_len = 0U;
-
-            break;
-        default:
-            BT_ERR("Unexpected ACL flags (0x%02x)", flags);
-            bt_conn_reset_rx_state(conn);
-            net_buf_unref(buf);
-            return;
-    }
+void bt_conn_recv(struct bt_conn *conn, struct net_buf *buf, u8_t flags) {
+  struct bt_l2cap_hdr *hdr;
+  u16_t                len;
+
+  /* Make sure we notify any pending TX callbacks before processing
+   * new data for this connection.
+   */
+  tx_notify(conn);
 
+  BT_DBG("handle %u len %u flags %02x", conn->handle, buf->len, flags);
+
+  /* Check packet boundary flags */
+  switch (flags) {
+  case BT_ACL_START:
     hdr = (void *)buf->data;
     len = sys_le16_to_cpu(hdr->len);
 
-    if (sizeof(*hdr) + len != buf->len) {
-        BT_ERR("ACL len mismatch (%u != %u)", len, buf->len);
-        net_buf_unref(buf);
-        return;
+    BT_DBG("First, len %u final %u", buf->len, len);
+
+    if (conn->rx_len) {
+      BT_ERR("Unexpected first L2CAP frame");
+      bt_conn_reset_rx_state(conn);
+    }
+
+    conn->rx_len = (sizeof(*hdr) + len) - buf->len;
+    BT_DBG("rx_len %u", conn->rx_len);
+    if (conn->rx_len) {
+      conn->rx = buf;
+      return;
+    }
+
+    break;
+  case BT_ACL_CONT:
+    if (!conn->rx_len) {
+      BT_ERR("Unexpected L2CAP continuation");
+      bt_conn_reset_rx_state(conn);
+      net_buf_unref(buf);
+      return;
+    }
+
+    if (buf->len > conn->rx_len) {
+      BT_ERR("L2CAP data overflow");
+      bt_conn_reset_rx_state(conn);
+      net_buf_unref(buf);
+      return;
+    }
+
+    BT_DBG("Cont, len %u rx_len %u", buf->len, conn->rx_len);
+
+    if (buf->len > net_buf_tailroom(conn->rx)) {
+      BT_ERR("Not enough buffer space for L2CAP data");
+      bt_conn_reset_rx_state(conn);
+      net_buf_unref(buf);
+      return;
+    }
+
+    net_buf_add_mem(conn->rx, buf->data, buf->len);
+    conn->rx_len -= buf->len;
+    net_buf_unref(buf);
+
+    if (conn->rx_len) {
+      return;
     }
 
-    BT_DBG("Successfully parsed %u byte L2CAP packet", buf->len);
+    buf          = conn->rx;
+    conn->rx     = NULL;
+    conn->rx_len = 0U;
+
+    break;
+  default:
+    BT_ERR("Unexpected ACL flags (0x%02x)", flags);
+    bt_conn_reset_rx_state(conn);
+    net_buf_unref(buf);
+    return;
+  }
+
+  hdr = (void *)buf->data;
+  len = sys_le16_to_cpu(hdr->len);
 
-    bt_l2cap_recv(conn, buf);
+  if (sizeof(*hdr) + len != buf->len) {
+    BT_ERR("ACL len mismatch (%u != %u)", len, buf->len);
+    net_buf_unref(buf);
+    return;
+  }
+
+  BT_DBG("Successfully parsed %u byte L2CAP packet", buf->len);
+
+  bt_l2cap_recv(conn, buf);
 }
 
-static struct bt_conn_tx *conn_tx_alloc(void)
-{
-    /* The TX context always get freed in the system workqueue,
-	 * so if we're in the same workqueue but there are no immediate
-	 * contexts available, there's no chance we'll get one by waiting.
-	 */
+static struct bt_conn_tx *conn_tx_alloc(void) {
+  /* The TX context always get freed in the system workqueue,
+   * so if we're in the same workqueue but there are no immediate
+   * contexts available, there's no chance we'll get one by waiting.
+   */
 #if !defined(BFLB_BLE)
-    if (k_current_get() == &k_sys_work_q.thread) {
-        return k_fifo_get(&free_tx, K_NO_WAIT);
-    }
+  if (k_current_get() == &k_sys_work_q.thread) {
+    return k_fifo_get(&free_tx, K_NO_WAIT);
+  }
 #endif
-    if (IS_ENABLED(CONFIG_BT_DEBUG_CONN)) {
-        struct bt_conn_tx *tx = k_fifo_get(&free_tx, K_NO_WAIT);
-
-        if (tx) {
-            return tx;
-        }
+  if (IS_ENABLED(CONFIG_BT_DEBUG_CONN)) {
+    struct bt_conn_tx *tx = k_fifo_get(&free_tx, K_NO_WAIT);
 
-        BT_WARN("Unable to get an immediate free conn_tx");
+    if (tx) {
+      return tx;
     }
 
-    return k_fifo_get(&free_tx, K_FOREVER);
+    BT_WARN("Unable to get an immediate free conn_tx");
+  }
+
+  return k_fifo_get(&free_tx, K_FOREVER);
 }
 
-int bt_conn_send_cb(struct bt_conn *conn, struct net_buf *buf,
-                    bt_conn_tx_cb_t cb, void *user_data)
-{
-    struct bt_conn_tx *tx;
+int bt_conn_send_cb(struct bt_conn *conn, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data) {
+  struct bt_conn_tx *tx;
+
+  BT_DBG("conn handle %u buf len %u cb %p user_data %p", conn->handle, buf->len, cb, user_data);
 
-    BT_DBG("conn handle %u buf len %u cb %p user_data %p", conn->handle,
-           buf->len, cb, user_data);
+  if (conn->state != BT_CONN_CONNECTED) {
+    BT_ERR("not connected!");
+    net_buf_unref(buf);
+    return -ENOTCONN;
+  }
 
+  if (cb) {
+    tx = conn_tx_alloc();
+    if (!tx) {
+      BT_ERR("Unable to allocate TX context");
+      net_buf_unref(buf);
+      return -ENOBUFS;
+    }
+
+    /* Verify that we're still connected after blocking */
     if (conn->state != BT_CONN_CONNECTED) {
-        BT_ERR("not connected!");
-        net_buf_unref(buf);
-        return -ENOTCONN;
-    }
-
-    if (cb) {
-        tx = conn_tx_alloc();
-        if (!tx) {
-            BT_ERR("Unable to allocate TX context");
-            net_buf_unref(buf);
-            return -ENOBUFS;
-        }
-
-        /* Verify that we're still connected after blocking */
-        if (conn->state != BT_CONN_CONNECTED) {
-            BT_WARN("Disconnected while allocating context");
-            net_buf_unref(buf);
-            tx_free(tx);
-            return -ENOTCONN;
-        }
-
-        tx->cb = cb;
-        tx->user_data = user_data;
-        tx->pending_no_cb = 0U;
-
-        tx_data(buf)->tx = tx;
-    } else {
-        tx_data(buf)->tx = NULL;
+      BT_WARN("Disconnected while allocating context");
+      net_buf_unref(buf);
+      tx_free(tx);
+      return -ENOTCONN;
     }
 
-    net_buf_put(&conn->tx_queue, buf);
+    tx->cb            = cb;
+    tx->user_data     = user_data;
+    tx->pending_no_cb = 0U;
+
+    tx_data(buf)->tx = tx;
+  } else {
+    tx_data(buf)->tx = NULL;
+  }
+
+  net_buf_put(&conn->tx_queue, buf);
 #if defined(BFLB_BLE)
-    k_sem_give(&g_poll_sem);
+  k_sem_give(&g_poll_sem);
 #endif
-    return 0;
+  return 0;
 }
 
-static bool send_frag(struct bt_conn *conn, struct net_buf *buf, u8_t flags,
-                      bool always_consume)
-{
-    struct bt_conn_tx *tx = tx_data(buf)->tx;
-    struct bt_hci_acl_hdr *hdr;
-    u32_t *pending_no_cb;
-    unsigned int key;
-    int err;
+static bool send_frag(struct bt_conn *conn, struct net_buf *buf, u8_t flags, bool always_consume) {
+  struct bt_conn_tx     *tx = tx_data(buf)->tx;
+  struct bt_hci_acl_hdr *hdr;
+  u32_t                 *pending_no_cb;
+  unsigned int           key;
+  int                    err;
 
-    BT_DBG("conn %p buf %p len %u flags 0x%02x", conn, buf, buf->len,
-           flags);
+  BT_DBG("conn %p buf %p len %u flags 0x%02x", conn, buf, buf->len, flags);
 
-    /* Wait until the controller can accept ACL packets */
-    k_sem_take(bt_conn_get_pkts(conn), K_FOREVER);
+  /* Wait until the controller can accept ACL packets */
+  k_sem_take(bt_conn_get_pkts(conn), K_FOREVER);
 
-    /* Check for disconnection while waiting for pkts_sem */
-    if (conn->state != BT_CONN_CONNECTED) {
-        goto fail;
+  /* Check for disconnection while waiting for pkts_sem */
+  if (conn->state != BT_CONN_CONNECTED) {
+    goto fail;
+  }
+
+  hdr         = net_buf_push(buf, sizeof(*hdr));
+  hdr->handle = sys_cpu_to_le16(bt_acl_handle_pack(conn->handle, flags));
+  hdr->len    = sys_cpu_to_le16(buf->len - sizeof(*hdr));
+
+  /* Add to pending, it must be done before bt_buf_set_type */
+  key = irq_lock();
+  if (tx) {
+    sys_slist_append(&conn->tx_pending, &tx->node);
+  } else {
+    struct bt_conn_tx *tail_tx;
+
+    tail_tx = (void *)sys_slist_peek_tail(&conn->tx_pending);
+    if (tail_tx) {
+      pending_no_cb = &tail_tx->pending_no_cb;
+    } else {
+      pending_no_cb = &conn->pending_no_cb;
     }
 
-    hdr = net_buf_push(buf, sizeof(*hdr));
-    hdr->handle = sys_cpu_to_le16(bt_acl_handle_pack(conn->handle, flags));
-    hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr));
+    (*pending_no_cb)++;
+  }
+  irq_unlock(key);
+
+  bt_buf_set_type(buf, BT_BUF_ACL_OUT);
 
-    /* Add to pending, it must be done before bt_buf_set_type */
+  err = bt_send(buf);
+  if (err) {
+    BT_ERR("Unable to send to driver (err %d)", err);
     key = irq_lock();
+    /* Roll back the pending TX info */
     if (tx) {
-        sys_slist_append(&conn->tx_pending, &tx->node);
+      sys_slist_find_and_remove(&conn->tx_pending, &tx->node);
     } else {
-        struct bt_conn_tx *tail_tx;
-
-        tail_tx = (void *)sys_slist_peek_tail(&conn->tx_pending);
-        if (tail_tx) {
-            pending_no_cb = &tail_tx->pending_no_cb;
-        } else {
-            pending_no_cb = &conn->pending_no_cb;
-        }
-
-        (*pending_no_cb)++;
+      __ASSERT_NO_MSG(*pending_no_cb > 0);
+      (*pending_no_cb)--;
     }
     irq_unlock(key);
+    goto fail;
+  }
 
-    bt_buf_set_type(buf, BT_BUF_ACL_OUT);
-
-    err = bt_send(buf);
-    if (err) {
-        BT_ERR("Unable to send to driver (err %d)", err);
-        key = irq_lock();
-        /* Roll back the pending TX info */
-        if (tx) {
-            sys_slist_find_and_remove(&conn->tx_pending, &tx->node);
-        } else {
-            __ASSERT_NO_MSG(*pending_no_cb > 0);
-            (*pending_no_cb)--;
-        }
-        irq_unlock(key);
-        goto fail;
-    }
-
-    return true;
+  return true;
 
 fail:
-    k_sem_give(bt_conn_get_pkts(conn));
-    if (tx) {
-        tx_free(tx);
-    }
+  k_sem_give(bt_conn_get_pkts(conn));
+  if (tx) {
+    tx_free(tx);
+  }
 
-    if (always_consume) {
-        net_buf_unref(buf);
-    }
-    return false;
+  if (always_consume) {
+    net_buf_unref(buf);
+  }
+  return false;
 }
 
-static inline u16_t conn_mtu(struct bt_conn *conn)
-{
+static inline u16_t conn_mtu(struct bt_conn *conn) {
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR || !bt_dev.le.mtu) {
-        return bt_dev.br.mtu;
-    }
+  if (conn->type == BT_CONN_TYPE_BR || !bt_dev.le.mtu) {
+    return bt_dev.br.mtu;
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    return bt_dev.le.mtu;
+  return bt_dev.le.mtu;
 }
 
-static struct net_buf *create_frag(struct bt_conn *conn, struct net_buf *buf)
-{
-    struct net_buf *frag;
-    u16_t frag_len;
+static struct net_buf *create_frag(struct bt_conn *conn, struct net_buf *buf) {
+  struct net_buf *frag;
+  u16_t           frag_len;
 
 #if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0
-    frag = bt_conn_create_pdu(&frag_pool, 0);
+  frag = bt_conn_create_pdu(&frag_pool, 0);
 #else
-    frag = bt_conn_create_pdu(NULL, 0);
+  frag = bt_conn_create_pdu(NULL, 0);
 #endif
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        net_buf_unref(frag);
-        return NULL;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    net_buf_unref(frag);
+    return NULL;
+  }
 
-    /* Fragments never have a TX completion callback */
-    tx_data(frag)->tx = NULL;
+  /* Fragments never have a TX completion callback */
+  tx_data(frag)->tx = NULL;
 
-    frag_len = MIN(conn_mtu(conn), net_buf_tailroom(frag));
+  frag_len = MIN(conn_mtu(conn), net_buf_tailroom(frag));
 
-    net_buf_add_mem(frag, buf->data, frag_len);
-    net_buf_pull(buf, frag_len);
+  net_buf_add_mem(frag, buf->data, frag_len);
+  net_buf_pull(buf, frag_len);
 
-    return frag;
+  return frag;
 }
 
-static bool send_buf(struct bt_conn *conn, struct net_buf *buf)
-{
-    struct net_buf *frag;
+static bool send_buf(struct bt_conn *conn, struct net_buf *buf) {
+  struct net_buf *frag;
 
-    BT_DBG("conn %p buf %p len %u", conn, buf, buf->len);
+  BT_DBG("conn %p buf %p len %u", conn, buf, buf->len);
 
-    /* Send directly if the packet fits the ACL MTU */
-    if (buf->len <= conn_mtu(conn)) {
-        return send_frag(conn, buf, BT_ACL_START_NO_FLUSH, false);
-    }
+  /* Send directly if the packet fits the ACL MTU */
+  if (buf->len <= conn_mtu(conn)) {
+    return send_frag(conn, buf, BT_ACL_START_NO_FLUSH, false);
+  }
+
+  /* Create & enqueue first fragment */
+  frag = create_frag(conn, buf);
+  if (!frag) {
+    return false;
+  }
 
-    /* Create & enqueue first fragment */
+  if (!send_frag(conn, frag, BT_ACL_START_NO_FLUSH, true)) {
+    return false;
+  }
+
+  /*
+   * Send the fragments. For the last one simply use the original
+   * buffer (which works since we've used net_buf_pull on it.
+   */
+  while (buf->len > conn_mtu(conn)) {
     frag = create_frag(conn, buf);
     if (!frag) {
-        return false;
-    }
-
-    if (!send_frag(conn, frag, BT_ACL_START_NO_FLUSH, true)) {
-        return false;
+      return false;
     }
 
-    /*
-	 * Send the fragments. For the last one simply use the original
-	 * buffer (which works since we've used net_buf_pull on it.
-	 */
-    while (buf->len > conn_mtu(conn)) {
-        frag = create_frag(conn, buf);
-        if (!frag) {
-            return false;
-        }
-
-        if (!send_frag(conn, frag, BT_ACL_CONT, true)) {
-            return false;
-        }
+    if (!send_frag(conn, frag, BT_ACL_CONT, true)) {
+      return false;
     }
+  }
 
-    return send_frag(conn, buf, BT_ACL_CONT, false);
+  return send_frag(conn, buf, BT_ACL_CONT, false);
 }
 
-static struct k_poll_signal conn_change =
-    K_POLL_SIGNAL_INITIALIZER(conn_change);
+static struct k_poll_signal conn_change = K_POLL_SIGNAL_INITIALIZER(conn_change);
 
-static void conn_cleanup(struct bt_conn *conn)
-{
-    struct net_buf *buf;
+static void conn_cleanup(struct bt_conn *conn) {
+  struct net_buf *buf;
 
-    /* Give back any allocated buffers */
-    while ((buf = net_buf_get(&conn->tx_queue, K_NO_WAIT))) {
-        if (tx_data(buf)->tx) {
-            tx_free(tx_data(buf)->tx);
-        }
-
-        net_buf_unref(buf);
+  /* Give back any allocated buffers */
+  while ((buf = net_buf_get(&conn->tx_queue, K_NO_WAIT))) {
+    if (tx_data(buf)->tx) {
+      tx_free(tx_data(buf)->tx);
     }
 
-    __ASSERT(sys_slist_is_empty(&conn->tx_pending), "Pending TX packets");
-    __ASSERT_NO_MSG(conn->pending_no_cb == 0);
+    net_buf_unref(buf);
+  }
 
-    bt_conn_reset_rx_state(conn);
+  __ASSERT(sys_slist_is_empty(&conn->tx_pending), "Pending TX packets");
+  __ASSERT_NO_MSG(conn->pending_no_cb == 0);
 
-    k_delayed_work_submit(&conn->update_work, K_NO_WAIT);
+  bt_conn_reset_rx_state(conn);
+
+  k_delayed_work_submit(&conn->update_work, K_NO_WAIT);
 
 #ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS
-    k_queue_free(&conn->tx_queue._queue);
-    // k_queue_free(&conn->tx_notify._queue);
-    conn->tx_queue._queue.hdl = NULL;
-    //conn->tx_notify._queue.hdl = NULL;
-    if (conn->update_work.timer.timer.hdl)
-        k_delayed_work_del_timer(&conn->update_work);
+  k_queue_free(&conn->tx_queue._queue);
+  // k_queue_free(&conn->tx_notify._queue);
+  conn->tx_queue._queue.hdl = NULL;
+  // conn->tx_notify._queue.hdl = NULL;
+  if (conn->update_work.timer.timer.hdl)
+    k_delayed_work_del_timer(&conn->update_work);
 #endif
 }
 
-int bt_conn_prepare_events(struct k_poll_event events[])
-{
-    int i, ev_count = 0;
+int bt_conn_prepare_events(struct k_poll_event events[]) {
+  int i, ev_count = 0;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    conn_change.signaled = 0U;
-    k_poll_event_init(&events[ev_count++], K_POLL_TYPE_SIGNAL,
-                      K_POLL_MODE_NOTIFY_ONLY, &conn_change);
+  conn_change.signaled = 0U;
+  k_poll_event_init(&events[ev_count++], K_POLL_TYPE_SIGNAL, K_POLL_MODE_NOTIFY_ONLY, &conn_change);
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        struct bt_conn *conn = &conns[i];
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    struct bt_conn *conn = &conns[i];
 
-        if (!atomic_get(&conn->ref)) {
-            continue;
-        }
+    if (!atomic_get(&conn->ref)) {
+      continue;
+    }
 
-        if (conn->state == BT_CONN_DISCONNECTED &&
-            atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) {
-            conn_cleanup(conn);
-            continue;
-        }
+    if (conn->state == BT_CONN_DISCONNECTED && atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) {
+      conn_cleanup(conn);
+      continue;
+    }
 
-        if (conn->state != BT_CONN_CONNECTED) {
-            continue;
-        }
+    if (conn->state != BT_CONN_CONNECTED) {
+      continue;
+    }
 
-        BT_DBG("Adding conn %p to poll list", conn);
+    BT_DBG("Adding conn %p to poll list", conn);
 
-        k_poll_event_init(&events[ev_count],
-                          K_POLL_TYPE_FIFO_DATA_AVAILABLE,
-                          K_POLL_MODE_NOTIFY_ONLY,
-                          &conn->tx_queue);
-        events[ev_count++].tag = BT_EVENT_CONN_TX_QUEUE;
-    }
+    k_poll_event_init(&events[ev_count], K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &conn->tx_queue);
+    events[ev_count++].tag = BT_EVENT_CONN_TX_QUEUE;
+  }
 
-    return ev_count;
+  return ev_count;
 }
 
-void bt_conn_process_tx(struct bt_conn *conn)
-{
-    struct net_buf *buf;
+void bt_conn_process_tx(struct bt_conn *conn) {
+  struct net_buf *buf;
 
-    BT_DBG("conn %p", conn);
+  BT_DBG("conn %p", conn);
 
-    if (conn->state == BT_CONN_DISCONNECTED &&
-        atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) {
-        BT_DBG("handle %u disconnected - cleaning up", conn->handle);
-        conn_cleanup(conn);
-        return;
-    }
+  if (conn->state == BT_CONN_DISCONNECTED && atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) {
+    BT_DBG("handle %u disconnected - cleaning up", conn->handle);
+    conn_cleanup(conn);
+    return;
+  }
 
-    /* Get next ACL packet for connection */
-    buf = net_buf_get(&conn->tx_queue, K_NO_WAIT);
-    BT_ASSERT(buf);
-    if (!send_buf(conn, buf)) {
-        net_buf_unref(buf);
-    }
+  /* Get next ACL packet for connection */
+  buf = net_buf_get(&conn->tx_queue, K_NO_WAIT);
+  BT_ASSERT(buf);
+  if (!send_buf(conn, buf)) {
+    net_buf_unref(buf);
+  }
 }
 
-struct bt_conn *bt_conn_add_le(u8_t id, const bt_addr_le_t *peer)
-{
-    struct bt_conn *conn = conn_new();
+struct bt_conn *bt_conn_add_le(u8_t id, const bt_addr_le_t *peer) {
+  struct bt_conn *conn = conn_new();
 
-    if (!conn) {
-        return NULL;
-    }
+  if (!conn) {
+    return NULL;
+  }
 
-    conn->id = id;
-    bt_addr_le_copy(&conn->le.dst, peer);
+  conn->id = id;
+  bt_addr_le_copy(&conn->le.dst, peer);
 #if defined(CONFIG_BT_SMP)
-    conn->sec_level = BT_SECURITY_L1;
-    conn->required_sec_level = BT_SECURITY_L1;
+  conn->sec_level          = BT_SECURITY_L1;
+  conn->required_sec_level = BT_SECURITY_L1;
 #endif /* CONFIG_BT_SMP */
-    conn->type = BT_CONN_TYPE_LE;
-    conn->le.interval_min = BT_GAP_INIT_CONN_INT_MIN;
-    conn->le.interval_max = BT_GAP_INIT_CONN_INT_MAX;
+  conn->type            = BT_CONN_TYPE_LE;
+  conn->le.interval_min = BT_GAP_INIT_CONN_INT_MIN;
+  conn->le.interval_max = BT_GAP_INIT_CONN_INT_MAX;
 
-    return conn;
+  return conn;
 }
 
-static void process_unack_tx(struct bt_conn *conn)
-{
-    /* Return any unacknowledged packets */
-    while (1) {
-        struct bt_conn_tx *tx;
-        sys_snode_t *node;
-        unsigned int key;
+static void process_unack_tx(struct bt_conn *conn) {
+  /* Return any unacknowledged packets */
+  while (1) {
+    struct bt_conn_tx *tx;
+    sys_snode_t       *node;
+    unsigned int       key;
 
-        key = irq_lock();
+    key = irq_lock();
 
-        if (conn->pending_no_cb) {
-            conn->pending_no_cb--;
-            irq_unlock(key);
-            k_sem_give(bt_conn_get_pkts(conn));
-            continue;
-        }
+    if (conn->pending_no_cb) {
+      conn->pending_no_cb--;
+      irq_unlock(key);
+      k_sem_give(bt_conn_get_pkts(conn));
+      continue;
+    }
 
-        node = sys_slist_get(&conn->tx_pending);
-        irq_unlock(key);
+    node = sys_slist_get(&conn->tx_pending);
+    irq_unlock(key);
 
-        if (!node) {
-            break;
-        }
+    if (!node) {
+      break;
+    }
 
-        tx = CONTAINER_OF(node, struct bt_conn_tx, node);
+    tx = CONTAINER_OF(node, struct bt_conn_tx, node);
 
-        key = irq_lock();
-        conn->pending_no_cb = tx->pending_no_cb;
-        tx->pending_no_cb = 0U;
-        irq_unlock(key);
+    key                 = irq_lock();
+    conn->pending_no_cb = tx->pending_no_cb;
+    tx->pending_no_cb   = 0U;
+    irq_unlock(key);
 
-        tx_free(tx);
+    tx_free(tx);
 
-        k_sem_give(bt_conn_get_pkts(conn));
+    k_sem_give(bt_conn_get_pkts(conn));
+  }
+}
+
+void bt_conn_set_state(struct bt_conn *conn, bt_conn_state_t state) {
+  bt_conn_state_t old_state;
+
+  BT_DBG("%s -> %s", state2str(conn->state), state2str(state));
+
+  if (conn->state == state) {
+    BT_WARN("no transition");
+    return;
+  }
+
+  old_state   = conn->state;
+  conn->state = state;
+
+  /* Actions needed for exiting the old state */
+  switch (old_state) {
+  case BT_CONN_DISCONNECTED:
+    /* Take a reference for the first state transition after
+     * bt_conn_add_le() and keep it until reaching DISCONNECTED
+     * again.
+     */
+    bt_conn_ref(conn);
+    break;
+  case BT_CONN_CONNECT:
+    if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->type == BT_CONN_TYPE_LE) {
+      k_delayed_work_cancel(&conn->update_work);
+    }
+    break;
+  default:
+    break;
+  }
+
+  /* Actions needed for entering the new state */
+  switch (conn->state) {
+  case BT_CONN_CONNECTED:
+    if (conn->type == BT_CONN_TYPE_SCO) {
+      /* TODO: Notify sco connected */
+      break;
+    }
+    k_fifo_init(&conn->tx_queue, 20);
+    k_poll_signal_raise(&conn_change, 0);
+
+    sys_slist_init(&conn->channels);
+
+    bt_l2cap_connected(conn);
+    notify_connected(conn);
+    break;
+  case BT_CONN_DISCONNECTED:
+    if (conn->type == BT_CONN_TYPE_SCO) {
+      /* TODO: Notify sco disconnected */
+      bt_conn_unref(conn);
+      break;
+    }
+    /* Notify disconnection and queue a dummy buffer to wake
+     * up and stop the tx thread for states where it was
+     * running.
+     */
+    if (old_state == BT_CONN_CONNECTED || old_state == BT_CONN_DISCONNECT) {
+      process_unack_tx(conn);
+      tx_notify(conn);
+
+      /* Cancel Connection Update if it is pending */
+      if (conn->type == BT_CONN_TYPE_LE) {
+        k_delayed_work_cancel(&conn->update_work);
+      }
+
+      atomic_set_bit(conn->flags, BT_CONN_CLEANUP);
+      k_poll_signal_raise(&conn_change, 0);
+      /* The last ref will be dropped during cleanup */
+    } else if (old_state == BT_CONN_CONNECT) {
+      /* conn->err will be set in this case */
+      notify_connected(conn);
+      bt_conn_unref(conn);
+    } else if (old_state == BT_CONN_CONNECT_SCAN) {
+      /* this indicate LE Create Connection failed */
+      if (conn->err) {
+        notify_connected(conn);
+      }
+
+      bt_conn_unref(conn);
+    } else if (old_state == BT_CONN_CONNECT_DIR_ADV) {
+      /* this indicate Directed advertising stopped */
+      if (conn->err) {
+        notify_connected(conn);
+      }
+
+      bt_conn_unref(conn);
+    }
+
+    break;
+  case BT_CONN_CONNECT_SCAN:
+    break;
+  case BT_CONN_CONNECT_DIR_ADV:
+    break;
+  case BT_CONN_CONNECT:
+    if (conn->type == BT_CONN_TYPE_SCO) {
+      break;
     }
-}
-
-void bt_conn_set_state(struct bt_conn *conn, bt_conn_state_t state)
-{
-    bt_conn_state_t old_state;
-
-    BT_DBG("%s -> %s", state2str(conn->state), state2str(state));
-
-    if (conn->state == state) {
-        BT_WARN("no transition");
-        return;
+    /*
+     * Timer is needed only for LE. For other link types controller
+     * will handle connection timeout.
+     */
+    if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->type == BT_CONN_TYPE_LE) {
+      k_delayed_work_submit(&conn->update_work, CONN_TIMEOUT);
     }
 
-    old_state = conn->state;
-    conn->state = state;
+    break;
+  case BT_CONN_DISCONNECT:
+    break;
+  default:
+    BT_WARN("no valid (%u) state was set", state);
 
-    /* Actions needed for exiting the old state */
-    switch (old_state) {
-        case BT_CONN_DISCONNECTED:
-            /* Take a reference for the first state transition after
-		 * bt_conn_add_le() and keep it until reaching DISCONNECTED
-		 * again.
-		 */
-            bt_conn_ref(conn);
-            break;
-        case BT_CONN_CONNECT:
-            if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
-                conn->type == BT_CONN_TYPE_LE) {
-                k_delayed_work_cancel(&conn->update_work);
-            }
-            break;
-        default:
-            break;
-    }
+    break;
+  }
+}
 
-    /* Actions needed for entering the new state */
-    switch (conn->state) {
-        case BT_CONN_CONNECTED:
-            if (conn->type == BT_CONN_TYPE_SCO) {
-                /* TODO: Notify sco connected */
-                break;
-            }
-            k_fifo_init(&conn->tx_queue, 20);
-            k_poll_signal_raise(&conn_change, 0);
-
-            sys_slist_init(&conn->channels);
-
-            bt_l2cap_connected(conn);
-            notify_connected(conn);
-            break;
-        case BT_CONN_DISCONNECTED:
-            if (conn->type == BT_CONN_TYPE_SCO) {
-                /* TODO: Notify sco disconnected */
-                bt_conn_unref(conn);
-                break;
-            }
-            /* Notify disconnection and queue a dummy buffer to wake
-		 * up and stop the tx thread for states where it was
-		 * running.
-		 */
-            if (old_state == BT_CONN_CONNECTED ||
-                old_state == BT_CONN_DISCONNECT) {
-                process_unack_tx(conn);
-                tx_notify(conn);
-
-                /* Cancel Connection Update if it is pending */
-                if (conn->type == BT_CONN_TYPE_LE) {
-                    k_delayed_work_cancel(&conn->update_work);
-                }
-
-                atomic_set_bit(conn->flags, BT_CONN_CLEANUP);
-                k_poll_signal_raise(&conn_change, 0);
-                /* The last ref will be dropped during cleanup */
-            } else if (old_state == BT_CONN_CONNECT) {
-                /* conn->err will be set in this case */
-                notify_connected(conn);
-                bt_conn_unref(conn);
-            } else if (old_state == BT_CONN_CONNECT_SCAN) {
-                /* this indicate LE Create Connection failed */
-                if (conn->err) {
-                    notify_connected(conn);
-                }
-
-                bt_conn_unref(conn);
-            } else if (old_state == BT_CONN_CONNECT_DIR_ADV) {
-                /* this indicate Directed advertising stopped */
-                if (conn->err) {
-                    notify_connected(conn);
-                }
-
-                bt_conn_unref(conn);
-            }
-
-            break;
-        case BT_CONN_CONNECT_SCAN:
-            break;
-        case BT_CONN_CONNECT_DIR_ADV:
-            break;
-        case BT_CONN_CONNECT:
-            if (conn->type == BT_CONN_TYPE_SCO) {
-                break;
-            }
-            /*
-		 * Timer is needed only for LE. For other link types controller
-		 * will handle connection timeout.
-		 */
-            if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
-                conn->type == BT_CONN_TYPE_LE) {
-                k_delayed_work_submit(&conn->update_work, CONN_TIMEOUT);
-            }
-
-            break;
-        case BT_CONN_DISCONNECT:
-            break;
-        default:
-            BT_WARN("no valid (%u) state was set", state);
-
-            break;
-    }
-}
-
-struct bt_conn *bt_conn_lookup_handle(u16_t handle)
-{
-    int i;
+struct bt_conn *bt_conn_lookup_handle(u16_t handle) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (!atomic_get(&conns[i].ref)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (!atomic_get(&conns[i].ref)) {
+      continue;
+    }
 
-        /* We only care about connections with a valid handle */
-        if (conns[i].state != BT_CONN_CONNECTED &&
-            conns[i].state != BT_CONN_DISCONNECT) {
-            continue;
-        }
+    /* We only care about connections with a valid handle */
+    if (conns[i].state != BT_CONN_CONNECTED && conns[i].state != BT_CONN_DISCONNECT) {
+      continue;
+    }
 
-        if (conns[i].handle == handle) {
-            return bt_conn_ref(&conns[i]);
-        }
+    if (conns[i].handle == handle) {
+      return bt_conn_ref(&conns[i]);
     }
+  }
 
 #if defined(CONFIG_BT_BREDR)
-    for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
-        if (!atomic_get(&sco_conns[i].ref)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
+    if (!atomic_get(&sco_conns[i].ref)) {
+      continue;
+    }
 
-        /* We only care about connections with a valid handle */
-        if (sco_conns[i].state != BT_CONN_CONNECTED &&
-            sco_conns[i].state != BT_CONN_DISCONNECT) {
-            continue;
-        }
+    /* We only care about connections with a valid handle */
+    if (sco_conns[i].state != BT_CONN_CONNECTED && sco_conns[i].state != BT_CONN_DISCONNECT) {
+      continue;
+    }
 
-        if (sco_conns[i].handle == handle) {
-            return bt_conn_ref(&sco_conns[i]);
-        }
+    if (sco_conns[i].handle == handle) {
+      return bt_conn_ref(&sco_conns[i]);
     }
+  }
 #endif
 
-    return NULL;
+  return NULL;
 }
 
-int bt_conn_addr_le_cmp(const struct bt_conn *conn, const bt_addr_le_t *peer)
-{
-    /* Check against conn dst address as it may be the identity address */
-    if (!bt_addr_le_cmp(peer, &conn->le.dst)) {
-        return 0;
-    }
+int bt_conn_addr_le_cmp(const struct bt_conn *conn, const bt_addr_le_t *peer) {
+  /* Check against conn dst address as it may be the identity address */
+  if (!bt_addr_le_cmp(peer, &conn->le.dst)) {
+    return 0;
+  }
 
-    /* Check against initial connection address */
-    if (conn->role == BT_HCI_ROLE_MASTER) {
-        return bt_addr_le_cmp(peer, &conn->le.resp_addr);
-    }
+  /* Check against initial connection address */
+  if (conn->role == BT_HCI_ROLE_MASTER) {
+    return bt_addr_le_cmp(peer, &conn->le.resp_addr);
+  }
 
-    return bt_addr_le_cmp(peer, &conn->le.init_addr);
+  return bt_addr_le_cmp(peer, &conn->le.init_addr);
 }
 
-struct bt_conn *bt_conn_lookup_addr_le(u8_t id, const bt_addr_le_t *peer)
-{
-    int i;
+struct bt_conn *bt_conn_lookup_addr_le(u8_t id, const bt_addr_le_t *peer) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (!atomic_get(&conns[i].ref)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (!atomic_get(&conns[i].ref)) {
+      continue;
+    }
 
-        if (conns[i].type != BT_CONN_TYPE_LE) {
-            continue;
-        }
+    if (conns[i].type != BT_CONN_TYPE_LE) {
+      continue;
+    }
 
-        if (conns[i].id == id &&
-            !bt_conn_addr_le_cmp(&conns[i], peer)) {
-            return bt_conn_ref(&conns[i]);
-        }
+    if (conns[i].id == id && !bt_conn_addr_le_cmp(&conns[i], peer)) {
+      return bt_conn_ref(&conns[i]);
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-struct bt_conn *bt_conn_lookup_state_le(const bt_addr_le_t *peer,
-                                        const bt_conn_state_t state)
-{
-    int i;
+struct bt_conn *bt_conn_lookup_state_le(const bt_addr_le_t *peer, const bt_conn_state_t state) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (!atomic_get(&conns[i].ref)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (!atomic_get(&conns[i].ref)) {
+      continue;
+    }
 
-        if (conns[i].type != BT_CONN_TYPE_LE) {
-            continue;
-        }
+    if (conns[i].type != BT_CONN_TYPE_LE) {
+      continue;
+    }
 
-        if (peer && bt_conn_addr_le_cmp(&conns[i], peer)) {
-            continue;
-        }
+    if (peer && bt_conn_addr_le_cmp(&conns[i], peer)) {
+      continue;
+    }
 
-        if (conns[i].state == state) {
-            return bt_conn_ref(&conns[i]);
-        }
+    if (conns[i].state == state) {
+      return bt_conn_ref(&conns[i]);
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-void bt_conn_foreach(int type, void (*func)(struct bt_conn *conn, void *data),
-                     void *data)
-{
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (!atomic_get(&conns[i].ref)) {
-            continue;
-        }
+void bt_conn_foreach(int type, void (*func)(struct bt_conn *conn, void *data), void *data) {
+  int i;
 
-        if (!(conns[i].type & type)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (!atomic_get(&conns[i].ref)) {
+      continue;
+    }
 
-        func(&conns[i], data);
+    if (!(conns[i].type & type)) {
+      continue;
     }
+
+    func(&conns[i], data);
+  }
 #if defined(CONFIG_BT_BREDR)
-    if (type & BT_CONN_TYPE_SCO) {
-        for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
-            if (!atomic_get(&sco_conns[i].ref)) {
-                continue;
-            }
+  if (type & BT_CONN_TYPE_SCO) {
+    for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
+      if (!atomic_get(&sco_conns[i].ref)) {
+        continue;
+      }
 
-            func(&sco_conns[i], data);
-        }
+      func(&sco_conns[i], data);
     }
+  }
 #endif /* defined(CONFIG_BT_BREDR) */
 }
 
-static void disconnect_all(struct bt_conn *conn, void *data)
-{
-    u8_t *id = (u8_t *)data;
+static void disconnect_all(struct bt_conn *conn, void *data) {
+  u8_t *id = (u8_t *)data;
 
-    if (conn->id == *id && conn->state == BT_CONN_CONNECTED) {
-        bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
-    }
+  if (conn->id == *id && conn->state == BT_CONN_CONNECTED) {
+    bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
+  }
 }
 
-void bt_conn_disconnect_all(u8_t id)
-{
-    bt_conn_foreach(BT_CONN_TYPE_ALL, disconnect_all, &id);
-}
+void bt_conn_disconnect_all(u8_t id) { bt_conn_foreach(BT_CONN_TYPE_ALL, disconnect_all, &id); }
 
-struct bt_conn *bt_conn_ref(struct bt_conn *conn)
-{
-    atomic_inc(&conn->ref);
+struct bt_conn *bt_conn_ref(struct bt_conn *conn) {
+  atomic_inc(&conn->ref);
 
-    BT_DBG("handle %u ref %u", conn->handle, atomic_get(&conn->ref));
+  BT_DBG("handle %u ref %u", conn->handle, atomic_get(&conn->ref));
 
-    return conn;
+  return conn;
 }
 
-void bt_conn_unref(struct bt_conn *conn)
-{
-    atomic_dec(&conn->ref);
+void bt_conn_unref(struct bt_conn *conn) {
+  atomic_dec(&conn->ref);
 
-    BT_DBG("handle %u ref %u", conn->handle, atomic_get(&conn->ref));
+  BT_DBG("handle %u ref %u", conn->handle, atomic_get(&conn->ref));
 }
 
-const bt_addr_le_t *bt_conn_get_dst(const struct bt_conn *conn)
-{
-    return &conn->le.dst;
-}
+const bt_addr_le_t *bt_conn_get_dst(const struct bt_conn *conn) { return &conn->le.dst; }
 
-int bt_conn_get_info(const struct bt_conn *conn, struct bt_conn_info *info)
-{
-    info->type = conn->type;
-    info->role = conn->role;
-    info->id = conn->id;
+int bt_conn_get_info(const struct bt_conn *conn, struct bt_conn_info *info) {
+  info->type = conn->type;
+  info->role = conn->role;
+  info->id   = conn->id;
 
-    switch (conn->type) {
-        case BT_CONN_TYPE_LE:
-            info->le.dst = &conn->le.dst;
-            info->le.src = &bt_dev.id_addr[conn->id];
-            if (conn->role == BT_HCI_ROLE_MASTER) {
-                info->le.local = &conn->le.init_addr;
-                info->le.remote = &conn->le.resp_addr;
-            } else {
-                info->le.local = &conn->le.resp_addr;
-                info->le.remote = &conn->le.init_addr;
-            }
-            info->le.interval = conn->le.interval;
-            info->le.latency = conn->le.latency;
-            info->le.timeout = conn->le.timeout;
-            return 0;
+  switch (conn->type) {
+  case BT_CONN_TYPE_LE:
+    info->le.dst = &conn->le.dst;
+    info->le.src = &bt_dev.id_addr[conn->id];
+    if (conn->role == BT_HCI_ROLE_MASTER) {
+      info->le.local  = &conn->le.init_addr;
+      info->le.remote = &conn->le.resp_addr;
+    } else {
+      info->le.local  = &conn->le.resp_addr;
+      info->le.remote = &conn->le.init_addr;
+    }
+    info->le.interval = conn->le.interval;
+    info->le.latency  = conn->le.latency;
+    info->le.timeout  = conn->le.timeout;
+    return 0;
 #if defined(CONFIG_BT_BREDR)
-        case BT_CONN_TYPE_BR:
-            info->br.dst = &conn->br.dst;
-            return 0;
+  case BT_CONN_TYPE_BR:
+    info->br.dst = &conn->br.dst;
+    return 0;
 #endif
-    }
+  }
 
-    return -EINVAL;
+  return -EINVAL;
 }
 
-int bt_conn_get_remote_dev_info(struct bt_conn_info *info)
-{
-    int link_num = 0;
+int bt_conn_get_remote_dev_info(struct bt_conn_info *info) {
+  int link_num = 0;
 
-    for (int i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (!atomic_get(&conns[i].ref)) {
-            continue;
-        }
-        bt_conn_get_info(&conns[i], &info[link_num]);
-        link_num++;
+  for (int i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (!atomic_get(&conns[i].ref)) {
+      continue;
     }
+    bt_conn_get_info(&conns[i], &info[link_num]);
+    link_num++;
+  }
 
-    return link_num;
+  return link_num;
 }
 
-static int bt_hci_disconnect(struct bt_conn *conn, u8_t reason)
-{
-    struct net_buf *buf;
-    struct bt_hci_cp_disconnect *disconn;
-    int err;
+static int bt_hci_disconnect(struct bt_conn *conn, u8_t reason) {
+  struct net_buf              *buf;
+  struct bt_hci_cp_disconnect *disconn;
+  int                          err;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_DISCONNECT, sizeof(*disconn));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_DISCONNECT, sizeof(*disconn));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    disconn = net_buf_add(buf, sizeof(*disconn));
-    disconn->handle = sys_cpu_to_le16(conn->handle);
-    disconn->reason = reason;
+  disconn         = net_buf_add(buf, sizeof(*disconn));
+  disconn->handle = sys_cpu_to_le16(conn->handle);
+  disconn->reason = reason;
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_DISCONNECT, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_DISCONNECT, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    bt_conn_set_state(conn, BT_CONN_DISCONNECT);
+  bt_conn_set_state(conn, BT_CONN_DISCONNECT);
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_STACK_PTS)
-int pts_bt_conn_le_param_update(struct bt_conn *conn,
-                                const struct bt_le_conn_param *param)
-{
-    BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn,
-           conn->le.features[0], param->interval_min,
-           param->interval_max, param->latency, param->timeout);
+int pts_bt_conn_le_param_update(struct bt_conn *conn, const struct bt_le_conn_param *param) {
+  BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, conn->le.features[0], param->interval_min, param->interval_max, param->latency, param->timeout);
 
-    /* Check if there's a need to update conn params */
-    if (conn->le.interval >= param->interval_min &&
-        conn->le.interval <= param->interval_max &&
-        conn->le.latency == param->latency &&
-        conn->le.timeout == param->timeout) {
-        return -EALREADY;
-    }
+  /* Check if there's a need to update conn params */
+  if (conn->le.interval >= param->interval_min && conn->le.interval <= param->interval_max && conn->le.latency == param->latency && conn->le.timeout == param->timeout) {
+    return -EALREADY;
+  }
 
-    /* Cancel any pending update */
-    k_delayed_work_cancel(&conn->update_work);
+  /* Cancel any pending update */
+  k_delayed_work_cancel(&conn->update_work);
 
-    return bt_l2cap_update_conn_param(conn, param);
+  return bt_l2cap_update_conn_param(conn, param);
 }
 #endif
-int bt_conn_le_param_update(struct bt_conn *conn,
-                            const struct bt_le_conn_param *param)
-{
-    BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn,
-           conn->le.features[0], param->interval_min,
-           param->interval_max, param->latency, param->timeout);
-
-    /* Check if there's a need to update conn params */
-    if (conn->le.interval >= param->interval_min &&
-        conn->le.interval <= param->interval_max &&
-        conn->le.latency == param->latency &&
-        conn->le.timeout == param->timeout) {
-        atomic_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET);
-        return -EALREADY;
-    }
+int bt_conn_le_param_update(struct bt_conn *conn, const struct bt_le_conn_param *param) {
+  BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, conn->le.features[0], param->interval_min, param->interval_max, param->latency, param->timeout);
+
+  /* Check if there's a need to update conn params */
+  if (conn->le.interval >= param->interval_min && conn->le.interval <= param->interval_max && conn->le.latency == param->latency && conn->le.timeout == param->timeout) {
+    atomic_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET);
+    return -EALREADY;
+  }
+
+  if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_CONN_ROLE_MASTER) {
+    return send_conn_le_param_update(conn, param);
+  }
+
+  if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
+    /* if slave conn param update timer expired just send request */
+    if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE)) {
+      return send_conn_le_param_update(conn, param);
+    }
+
+    /* store new conn params to be used by update timer */
+    conn->le.interval_min    = param->interval_min;
+    conn->le.interval_max    = param->interval_max;
+    conn->le.pending_latency = param->latency;
+    conn->le.pending_timeout = param->timeout;
+    atomic_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET);
+  }
+
+  return 0;
+}
+
+int bt_conn_disconnect(struct bt_conn *conn, u8_t reason) {
+  /* Disconnection is initiated by us, so auto connection shall
+   * be disabled. Otherwise the passive scan would be enabled
+   * and we could send LE Create Connection as soon as the remote
+   * starts advertising.
+   */
+#if !defined(CONFIG_BT_WHITELIST)
+  if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->type == BT_CONN_TYPE_LE) {
+    bt_le_set_auto_conn(&conn->le.dst, NULL);
+  }
+#endif /* !defined(CONFIG_BT_WHITELIST) */
 
-    if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
-        conn->role == BT_CONN_ROLE_MASTER) {
-        return send_conn_le_param_update(conn, param);
+  switch (conn->state) {
+  case BT_CONN_CONNECT_SCAN:
+    conn->err = reason;
+    bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
+    if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
+      bt_le_scan_update(false);
     }
-
+    return 0;
+  case BT_CONN_CONNECT_DIR_ADV:
+    conn->err = reason;
+    bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
     if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
-        /* if slave conn param update timer expired just send request */
-        if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE)) {
-            return send_conn_le_param_update(conn, param);
-        }
-
-        /* store new conn params to be used by update timer */
-        conn->le.interval_min = param->interval_min;
-        conn->le.interval_max = param->interval_max;
-        conn->le.pending_latency = param->latency;
-        conn->le.pending_timeout = param->timeout;
-        atomic_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET);
+      /* User should unref connection object when receiving
+       * error in connection callback.
+       */
+      return bt_le_adv_stop();
     }
-
     return 0;
-}
-
-int bt_conn_disconnect(struct bt_conn *conn, u8_t reason)
-{
-    /* Disconnection is initiated by us, so auto connection shall
-	 * be disabled. Otherwise the passive scan would be enabled
-	 * and we could send LE Create Connection as soon as the remote
-	 * starts advertising.
-	 */
-#if !defined(CONFIG_BT_WHITELIST)
-    if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
-        conn->type == BT_CONN_TYPE_LE) {
-        bt_le_set_auto_conn(&conn->le.dst, NULL);
-    }
-#endif /* !defined(CONFIG_BT_WHITELIST) */
-
-    switch (conn->state) {
-        case BT_CONN_CONNECT_SCAN:
-            conn->err = reason;
-            bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
-            if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
-                bt_le_scan_update(false);
-            }
-            return 0;
-        case BT_CONN_CONNECT_DIR_ADV:
-            conn->err = reason;
-            bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
-            if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
-                /* User should unref connection object when receiving
-			 * error in connection callback.
-			 */
-                return bt_le_adv_stop();
-            }
-            return 0;
-        case BT_CONN_CONNECT:
+  case BT_CONN_CONNECT:
 #if defined(CONFIG_BT_BREDR)
-            if (conn->type == BT_CONN_TYPE_BR) {
-                return bt_hci_connect_br_cancel(conn);
-            }
+    if (conn->type == BT_CONN_TYPE_BR) {
+      return bt_hci_connect_br_cancel(conn);
+    }
 #endif /* CONFIG_BT_BREDR */
 
-            if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
-                k_delayed_work_cancel(&conn->update_work);
-                return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN_CANCEL,
-                                            NULL, NULL);
-            }
-
-            return 0;
-        case BT_CONN_CONNECTED:
-            return bt_hci_disconnect(conn, reason);
-        case BT_CONN_DISCONNECT:
-            return 0;
-        case BT_CONN_DISCONNECTED:
-        default:
-            return -ENOTCONN;
+    if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
+      k_delayed_work_cancel(&conn->update_work);
+      return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN_CANCEL, NULL, NULL);
     }
+
+    return 0;
+  case BT_CONN_CONNECTED:
+    return bt_hci_disconnect(conn, reason);
+  case BT_CONN_DISCONNECT:
+    return 0;
+  case BT_CONN_DISCONNECTED:
+  default:
+    return -ENOTCONN;
+  }
 }
 
 #if defined(CONFIG_BT_CENTRAL)
-static void bt_conn_set_param_le(struct bt_conn *conn,
-                                 const struct bt_le_conn_param *param)
-{
-    conn->le.interval_min = param->interval_min;
-    conn->le.interval_max = param->interval_max;
-    conn->le.latency = param->latency;
-    conn->le.timeout = param->timeout;
+static void bt_conn_set_param_le(struct bt_conn *conn, const struct bt_le_conn_param *param) {
+  conn->le.interval_min = param->interval_min;
+  conn->le.interval_max = param->interval_max;
+  conn->le.latency      = param->latency;
+  conn->le.timeout      = param->timeout;
 
 #if defined(CONFIG_BT_STACK_PTS)
-    conn->le.own_adder_type = param->own_address_type;
+  conn->le.own_adder_type = param->own_address_type;
 #endif
 }
 
 #if defined(CONFIG_BT_WHITELIST)
-int bt_conn_create_auto_le(const struct bt_le_conn_param *param)
-{
-    struct bt_conn *conn;
-    int err;
+int bt_conn_create_auto_le(const struct bt_le_conn_param *param) {
+  struct bt_conn *conn;
+  int             err;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        return -EINVAL;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    return -EINVAL;
+  }
 
-    if (!bt_le_conn_params_valid(param)) {
-        return -EINVAL;
-    }
+  if (!bt_le_conn_params_valid(param)) {
+    return -EINVAL;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
-        return -EINVAL;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
+    return -EINVAL;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
-        return -EALREADY;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
+    return -EALREADY;
+  }
 
-    if (!bt_dev.le.wl_entries) {
-        return -EINVAL;
-    }
+  if (!bt_dev.le.wl_entries) {
+    return -EINVAL;
+  }
 
-    /* Don't start initiator if we have general discovery procedure. */
-    conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT_SCAN);
-    if (conn) {
-        bt_conn_unref(conn);
-        return -EINVAL;
-    }
+  /* Don't start initiator if we have general discovery procedure. */
+  conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT_SCAN);
+  if (conn) {
+    bt_conn_unref(conn);
+    return -EINVAL;
+  }
 
-    /* Don't start initiator if we have direct discovery procedure. */
-    conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
-    if (conn) {
-        bt_conn_unref(conn);
-        return -EINVAL;
-    }
+  /* Don't start initiator if we have direct discovery procedure. */
+  conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
+  if (conn) {
+    bt_conn_unref(conn);
+    return -EINVAL;
+  }
 
-    err = bt_le_auto_conn(param);
-    if (err) {
-        BT_ERR("Failed to start whitelist scan");
-        return err;
-    }
+  err = bt_le_auto_conn(param);
+  if (err) {
+    BT_ERR("Failed to start whitelist scan");
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-int bt_conn_create_auto_stop(void)
-{
-    int err;
+int bt_conn_create_auto_stop(void) {
+  int err;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        return -EINVAL;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    return -EINVAL;
+  }
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
-        return -EINVAL;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
+    return -EINVAL;
+  }
 
-    err = bt_le_auto_conn_cancel();
-    if (err) {
-        BT_ERR("Failed to stop initiator");
-        return err;
-    }
+  err = bt_le_auto_conn_cancel();
+  if (err) {
+    BT_ERR("Failed to stop initiator");
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 #endif /* defined(CONFIG_BT_WHITELIST) */
 
-struct bt_conn *bt_conn_create_le(const bt_addr_le_t *peer,
-                                  const struct bt_le_conn_param *param)
-{
-    struct bt_conn *conn;
-    bt_addr_le_t dst;
+struct bt_conn *bt_conn_create_le(const bt_addr_le_t *peer, const struct bt_le_conn_param *param) {
+  struct bt_conn *conn;
+  bt_addr_le_t    dst;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        return NULL;
-    }
-
-    if (!bt_le_conn_params_valid(param)) {
-        return NULL;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    return NULL;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
-        return NULL;
-    }
+  if (!bt_le_conn_params_valid(param)) {
+    return NULL;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_WHITELIST) &&
-        atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
-        return NULL;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
+    return NULL;
+  }
 
-    conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, peer);
-    if (conn) {
-        switch (conn->state) {
-            case BT_CONN_CONNECT_SCAN:
-                bt_conn_set_param_le(conn, param);
-                return conn;
-            case BT_CONN_CONNECT:
-            case BT_CONN_CONNECTED:
-                return conn;
-            case BT_CONN_DISCONNECTED:
-                BT_WARN("Found valid but disconnected conn object");
-                goto start_scan;
-            default:
-                bt_conn_unref(conn);
-                return NULL;
-        }
-    }
-
-    if (peer->type == BT_ADDR_LE_PUBLIC_ID ||
-        peer->type == BT_ADDR_LE_RANDOM_ID) {
-        bt_addr_le_copy(&dst, peer);
-        dst.type -= BT_ADDR_LE_PUBLIC_ID;
-    } else {
-        bt_addr_le_copy(&dst, bt_lookup_id_addr(BT_ID_DEFAULT, peer));
-    }
+  if (IS_ENABLED(CONFIG_BT_WHITELIST) && atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
+    return NULL;
+  }
 
-    /* Only default identity supported for now */
-    conn = bt_conn_add_le(BT_ID_DEFAULT, &dst);
-    if (!conn) {
-        return NULL;
-    }
+  conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, peer);
+  if (conn) {
+    switch (conn->state) {
+    case BT_CONN_CONNECT_SCAN:
+      bt_conn_set_param_le(conn, param);
+      return conn;
+    case BT_CONN_CONNECT:
+    case BT_CONN_CONNECTED:
+      return conn;
+    case BT_CONN_DISCONNECTED:
+      BT_WARN("Found valid but disconnected conn object");
+      goto start_scan;
+    default:
+      bt_conn_unref(conn);
+      return NULL;
+    }
+  }
+
+  if (peer->type == BT_ADDR_LE_PUBLIC_ID || peer->type == BT_ADDR_LE_RANDOM_ID) {
+    bt_addr_le_copy(&dst, peer);
+    dst.type -= BT_ADDR_LE_PUBLIC_ID;
+  } else {
+    bt_addr_le_copy(&dst, bt_lookup_id_addr(BT_ID_DEFAULT, peer));
+  }
+
+  /* Only default identity supported for now */
+  conn = bt_conn_add_le(BT_ID_DEFAULT, &dst);
+  if (!conn) {
+    return NULL;
+  }
 
 start_scan:
-    bt_conn_set_param_le(conn, param);
+  bt_conn_set_param_le(conn, param);
 
-    bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
+  bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
 
-    bt_le_scan_update(true);
+  bt_le_scan_update(true);
 
-    return conn;
+  return conn;
 }
 
 #if !defined(CONFIG_BT_WHITELIST)
-int bt_le_set_auto_conn(const bt_addr_le_t *addr,
-                        const struct bt_le_conn_param *param)
-{
-    struct bt_conn *conn;
+int bt_le_set_auto_conn(const bt_addr_le_t *addr, const struct bt_le_conn_param *param) {
+  struct bt_conn *conn;
 
-    if (param && !bt_le_conn_params_valid(param)) {
-        return -EINVAL;
-    }
+  if (param && !bt_le_conn_params_valid(param)) {
+    return -EINVAL;
+  }
 
-    /* Only default identity is supported */
-    conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, addr);
+  /* Only default identity is supported */
+  conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, addr);
+  if (!conn) {
+    conn = bt_conn_add_le(BT_ID_DEFAULT, addr);
     if (!conn) {
-        conn = bt_conn_add_le(BT_ID_DEFAULT, addr);
-        if (!conn) {
-            return -ENOMEM;
-        }
+      return -ENOMEM;
     }
+  }
 
-    if (param) {
-        bt_conn_set_param_le(conn, param);
+  if (param) {
+    bt_conn_set_param_le(conn, param);
 
-        if (!atomic_test_and_set_bit(conn->flags,
-                                     BT_CONN_AUTO_CONNECT)) {
-            bt_conn_ref(conn);
-        }
-    } else {
-        if (atomic_test_and_clear_bit(conn->flags,
-                                      BT_CONN_AUTO_CONNECT)) {
-            bt_conn_unref(conn);
-            if (conn->state == BT_CONN_CONNECT_SCAN) {
-                bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
-            }
-        }
+    if (!atomic_test_and_set_bit(conn->flags, BT_CONN_AUTO_CONNECT)) {
+      bt_conn_ref(conn);
     }
+  } else {
+    if (atomic_test_and_clear_bit(conn->flags, BT_CONN_AUTO_CONNECT)) {
+      bt_conn_unref(conn);
+      if (conn->state == BT_CONN_CONNECT_SCAN) {
+        bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
+      }
+    }
+  }
 
-    if (conn->state == BT_CONN_DISCONNECTED &&
-        atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        if (param) {
-            bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
-        }
-        bt_le_scan_update(false);
+  if (conn->state == BT_CONN_DISCONNECTED && atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    if (param) {
+      bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
     }
+    bt_le_scan_update(false);
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 
-    return 0;
+  return 0;
 }
 #endif /* !defined(CONFIG_BT_WHITELIST) */
 #endif /* CONFIG_BT_CENTRAL */
 
 #if defined(CONFIG_BT_PERIPHERAL)
-struct bt_conn *bt_conn_create_slave_le(const bt_addr_le_t *peer,
-                                        const struct bt_le_adv_param *param)
-{
-    int err;
-    struct bt_conn *conn;
-    struct bt_le_adv_param param_int;
-
-    memcpy(¶m_int, param, sizeof(param_int));
-    param_int.options |= (BT_LE_ADV_OPT_CONNECTABLE |
-                          BT_LE_ADV_OPT_ONE_TIME);
-
-    conn = bt_conn_lookup_addr_le(param->id, peer);
-    if (conn) {
-        switch (conn->state) {
-            case BT_CONN_CONNECT_DIR_ADV:
-                /* Handle the case when advertising is stopped with
-			 * bt_le_adv_stop function
-			 */
-                err = bt_le_adv_start_internal(¶m_int, NULL, 0,
-                                               NULL, 0, peer);
-                if (err && (err != -EALREADY)) {
-                    BT_WARN("Directed advertising could not be"
-                            " started: %d",
-                            err);
-                    bt_conn_unref(conn);
-                    return NULL;
-                }
-                __attribute__((fallthrough));
-            case BT_CONN_CONNECT:
-            case BT_CONN_CONNECTED:
-                return conn;
-            case BT_CONN_DISCONNECTED:
-                BT_WARN("Found valid but disconnected conn object");
-                goto start_adv;
-            default:
-                bt_conn_unref(conn);
-                return NULL;
-        }
-    }
-
-    conn = bt_conn_add_le(param->id, peer);
-    if (!conn) {
+struct bt_conn *bt_conn_create_slave_le(const bt_addr_le_t *peer, const struct bt_le_adv_param *param) {
+  int                    err;
+  struct bt_conn        *conn;
+  struct bt_le_adv_param param_int;
+
+  memcpy(¶m_int, param, sizeof(param_int));
+  param_int.options |= (BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME);
+
+  conn = bt_conn_lookup_addr_le(param->id, peer);
+  if (conn) {
+    switch (conn->state) {
+    case BT_CONN_CONNECT_DIR_ADV:
+      /* Handle the case when advertising is stopped with
+       * bt_le_adv_stop function
+       */
+      err = bt_le_adv_start_internal(¶m_int, NULL, 0, NULL, 0, peer);
+      if (err && (err != -EALREADY)) {
+        BT_WARN("Directed advertising could not be"
+                " started: %d",
+                err);
+        bt_conn_unref(conn);
         return NULL;
-    }
+      }
+      __attribute__((fallthrough));
+    case BT_CONN_CONNECT:
+    case BT_CONN_CONNECTED:
+      return conn;
+    case BT_CONN_DISCONNECTED:
+      BT_WARN("Found valid but disconnected conn object");
+      goto start_adv;
+    default:
+      bt_conn_unref(conn);
+      return NULL;
+    }
+  }
+
+  conn = bt_conn_add_le(param->id, peer);
+  if (!conn) {
+    return NULL;
+  }
 
 start_adv:
-    bt_conn_set_state(conn, BT_CONN_CONNECT_DIR_ADV);
+  bt_conn_set_state(conn, BT_CONN_CONNECT_DIR_ADV);
 
-    err = bt_le_adv_start_internal(¶m_int, NULL, 0, NULL, 0, peer);
-    if (err) {
-        BT_WARN("Directed advertising could not be started: %d", err);
+  err = bt_le_adv_start_internal(¶m_int, NULL, 0, NULL, 0, peer);
+  if (err) {
+    BT_WARN("Directed advertising could not be started: %d", err);
 
-        bt_conn_unref(conn);
-        return NULL;
-    }
+    bt_conn_unref(conn);
+    return NULL;
+  }
 
-    return conn;
+  return conn;
 }
 #endif /* CONFIG_BT_PERIPHERAL */
 
-int bt_conn_le_conn_update(struct bt_conn *conn,
-                           const struct bt_le_conn_param *param)
-{
-    struct hci_cp_le_conn_update *conn_update;
-    struct net_buf *buf;
+int bt_conn_le_conn_update(struct bt_conn *conn, const struct bt_le_conn_param *param) {
+  struct hci_cp_le_conn_update *conn_update;
+  struct net_buf               *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_UPDATE,
-                            sizeof(*conn_update));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_UPDATE, sizeof(*conn_update));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    conn_update = net_buf_add(buf, sizeof(*conn_update));
-    (void)memset(conn_update, 0, sizeof(*conn_update));
-    conn_update->handle = sys_cpu_to_le16(conn->handle);
-    conn_update->conn_interval_min = sys_cpu_to_le16(param->interval_min);
-    conn_update->conn_interval_max = sys_cpu_to_le16(param->interval_max);
-    conn_update->conn_latency = sys_cpu_to_le16(param->latency);
-    conn_update->supervision_timeout = sys_cpu_to_le16(param->timeout);
+  conn_update = net_buf_add(buf, sizeof(*conn_update));
+  (void)memset(conn_update, 0, sizeof(*conn_update));
+  conn_update->handle              = sys_cpu_to_le16(conn->handle);
+  conn_update->conn_interval_min   = sys_cpu_to_le16(param->interval_min);
+  conn_update->conn_interval_max   = sys_cpu_to_le16(param->interval_max);
+  conn_update->conn_latency        = sys_cpu_to_le16(param->latency);
+  conn_update->supervision_timeout = sys_cpu_to_le16(param->timeout);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CONN_UPDATE, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CONN_UPDATE, buf, NULL);
 }
 
-struct net_buf *bt_conn_create_pdu_timeout(struct net_buf_pool *pool,
-                                           size_t reserve, s32_t timeout)
-{
-    struct net_buf *buf;
-
-    /*
-	 * PDU must not be allocated from ISR as we block with 'K_FOREVER'
-	 * during the allocation
-	 */
-    __ASSERT_NO_MSG(!k_is_in_isr());
+struct net_buf *bt_conn_create_pdu_timeout(struct net_buf_pool *pool, size_t reserve, s32_t timeout) {
+  struct net_buf *buf;
 
-    if (!pool) {
-        pool = &acl_tx_pool;
-    }
+  /*
+   * PDU must not be allocated from ISR as we block with 'K_FOREVER'
+   * during the allocation
+   */
+  __ASSERT_NO_MSG(!k_is_in_isr());
 
-    if (IS_ENABLED(CONFIG_BT_DEBUG_CONN)) {
-        buf = net_buf_alloc(pool, K_NO_WAIT);
-        if (!buf) {
-            BT_WARN("Unable to allocate buffer with K_NO_WAIT");
-            buf = net_buf_alloc(pool, timeout);
-        }
-    } else {
-        buf = net_buf_alloc(pool, timeout);
-    }
+  if (!pool) {
+    pool = &acl_tx_pool;
+  }
 
+  if (IS_ENABLED(CONFIG_BT_DEBUG_CONN)) {
+    buf = net_buf_alloc(pool, K_NO_WAIT);
     if (!buf) {
-        BT_WARN("Unable to allocate buffer: timeout %d", timeout);
-        return NULL;
+      BT_WARN("Unable to allocate buffer with K_NO_WAIT");
+      buf = net_buf_alloc(pool, timeout);
     }
+  } else {
+    buf = net_buf_alloc(pool, timeout);
+  }
+
+  if (!buf) {
+    BT_WARN("Unable to allocate buffer: timeout %d", timeout);
+    return NULL;
+  }
 
-    reserve += sizeof(struct bt_hci_acl_hdr) + BT_BUF_RESERVE;
-    net_buf_reserve(buf, reserve);
+  reserve += sizeof(struct bt_hci_acl_hdr) + BT_BUF_RESERVE;
+  net_buf_reserve(buf, reserve);
 
-    return buf;
+  return buf;
 }
 
 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
-int bt_conn_auth_cb_register(const struct bt_conn_auth_cb *cb)
-{
-    if (!cb) {
-        bt_auth = NULL;
-        return 0;
-    }
+int bt_conn_auth_cb_register(const struct bt_conn_auth_cb *cb) {
+  if (!cb) {
+    bt_auth = NULL;
+    return 0;
+  }
 
-    if (bt_auth) {
-        return -EALREADY;
-    }
+  if (bt_auth) {
+    return -EALREADY;
+  }
 
-    /* The cancel callback must always be provided if the app provides
-	 * interactive callbacks.
-	 */
-    if (!cb->cancel &&
-        (cb->passkey_display || cb->passkey_entry || cb->passkey_confirm ||
+  /* The cancel callback must always be provided if the app provides
+   * interactive callbacks.
+   */
+  if (!cb->cancel
+      && (cb->passkey_display || cb->passkey_entry || cb->passkey_confirm ||
 #if defined(CONFIG_BT_BREDR)
-         cb->pincode_entry ||
+          cb->pincode_entry ||
 #endif
-         cb->pairing_confirm)) {
-        return -EINVAL;
-    }
+          cb->pairing_confirm)) {
+    return -EINVAL;
+  }
 
-    bt_auth = cb;
-    return 0;
+  bt_auth = cb;
+  return 0;
 }
 
-int bt_conn_auth_passkey_entry(struct bt_conn *conn, unsigned int passkey)
-{
-    if (!bt_auth) {
-        return -EINVAL;
-    }
+int bt_conn_auth_passkey_entry(struct bt_conn *conn, unsigned int passkey) {
+  if (!bt_auth) {
+    return -EINVAL;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) {
-        bt_smp_auth_passkey_entry(conn, passkey);
-        return 0;
-    }
+  if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) {
+    bt_smp_auth_passkey_entry(conn, passkey);
+    return 0;
+  }
 
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        /* User entered passkey, reset user state. */
-        if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
-            return -EPERM;
-        }
+  if (conn->type == BT_CONN_TYPE_BR) {
+    /* User entered passkey, reset user state. */
+    if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
+      return -EPERM;
+    }
 
-        if (conn->br.pairing_method == PASSKEY_INPUT) {
-            return ssp_passkey_reply(conn, passkey);
-        }
+    if (conn->br.pairing_method == PASSKEY_INPUT) {
+      return ssp_passkey_reply(conn, passkey);
     }
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    return -EINVAL;
+  return -EINVAL;
 }
 
-int bt_conn_auth_passkey_confirm(struct bt_conn *conn)
-{
-    if (!bt_auth) {
-        return -EINVAL;
-    }
+int bt_conn_auth_passkey_confirm(struct bt_conn *conn) {
+  if (!bt_auth) {
+    return -EINVAL;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SMP) &&
-        conn->type == BT_CONN_TYPE_LE) {
-        return bt_smp_auth_passkey_confirm(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) {
+    return bt_smp_auth_passkey_confirm(conn);
+  }
 
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        /* Allow user confirm passkey value, then reset user state. */
-        if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
-            return -EPERM;
-        }
-
-        return ssp_confirm_reply(conn);
+  if (conn->type == BT_CONN_TYPE_BR) {
+    /* Allow user confirm passkey value, then reset user state. */
+    if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
+      return -EPERM;
     }
+
+    return ssp_confirm_reply(conn);
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    return -EINVAL;
+  return -EINVAL;
 }
 
-int bt_conn_auth_cancel(struct bt_conn *conn)
-{
-    if (!bt_auth) {
-        return -EINVAL;
-    }
+int bt_conn_auth_cancel(struct bt_conn *conn) {
+  if (!bt_auth) {
+    return -EINVAL;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) {
-        return bt_smp_auth_cancel(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) {
+    return bt_smp_auth_cancel(conn);
+  }
 
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        /* Allow user cancel authentication, then reset user state. */
-        if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
-            return -EPERM;
-        }
-
-        switch (conn->br.pairing_method) {
-            case JUST_WORKS:
-            case PASSKEY_CONFIRM:
-                return ssp_confirm_neg_reply(conn);
-            case PASSKEY_INPUT:
-                return ssp_passkey_neg_reply(conn);
-            case PASSKEY_DISPLAY:
-                return bt_conn_disconnect(conn,
-                                          BT_HCI_ERR_AUTH_FAIL);
-            case LEGACY:
-                return pin_code_neg_reply(&conn->br.dst);
-            default:
-                break;
-        }
+  if (conn->type == BT_CONN_TYPE_BR) {
+    /* Allow user cancel authentication, then reset user state. */
+    if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
+      return -EPERM;
     }
+
+    switch (conn->br.pairing_method) {
+    case JUST_WORKS:
+    case PASSKEY_CONFIRM:
+      return ssp_confirm_neg_reply(conn);
+    case PASSKEY_INPUT:
+      return ssp_passkey_neg_reply(conn);
+    case PASSKEY_DISPLAY:
+      return bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
+    case LEGACY:
+      return pin_code_neg_reply(&conn->br.dst);
+    default:
+      break;
+    }
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    return -EINVAL;
+  return -EINVAL;
 }
 
-int bt_conn_auth_pairing_confirm(struct bt_conn *conn)
-{
-    if (!bt_auth) {
-        return -EINVAL;
-    }
+int bt_conn_auth_pairing_confirm(struct bt_conn *conn) {
+  if (!bt_auth) {
+    return -EINVAL;
+  }
 
-    switch (conn->type) {
+  switch (conn->type) {
 #if defined(CONFIG_BT_SMP)
-        case BT_CONN_TYPE_LE:
-            return bt_smp_auth_pairing_confirm(conn);
+  case BT_CONN_TYPE_LE:
+    return bt_smp_auth_pairing_confirm(conn);
 #endif /* CONFIG_BT_SMP */
 #if defined(CONFIG_BT_BREDR)
-        case BT_CONN_TYPE_BR:
-            return ssp_confirm_reply(conn);
+  case BT_CONN_TYPE_BR:
+    return ssp_confirm_reply(conn);
 #endif /* CONFIG_BT_BREDR */
-        default:
-            return -EINVAL;
-    }
+  default:
+    return -EINVAL;
+  }
 }
 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
 
-u8_t bt_conn_index(struct bt_conn *conn)
-{
-    u8_t index = conn - conns;
+u8_t bt_conn_index(struct bt_conn *conn) {
+  u8_t index = conn - conns;
 
-    __ASSERT(index < CONFIG_BT_MAX_CONN, "Invalid bt_conn pointer");
-    return index;
+  __ASSERT(index < CONFIG_BT_MAX_CONN, "Invalid bt_conn pointer");
+  return index;
 }
 
-struct bt_conn *bt_conn_lookup_id(u8_t id)
-{
-    struct bt_conn *conn;
+struct bt_conn *bt_conn_lookup_id(u8_t id) {
+  struct bt_conn *conn;
 
-    if (id >= ARRAY_SIZE(conns)) {
-        return NULL;
-    }
+  if (id >= ARRAY_SIZE(conns)) {
+    return NULL;
+  }
 
-    conn = &conns[id];
+  conn = &conns[id];
 
-    if (!atomic_get(&conn->ref)) {
-        return NULL;
-    }
+  if (!atomic_get(&conn->ref)) {
+    return NULL;
+  }
 
-    return bt_conn_ref(conn);
+  return bt_conn_ref(conn);
 }
 
-int bt_conn_init(void)
-{
+int bt_conn_init(void) {
 #if defined(CONFIG_BT_SMP)
-    int err;
+  int err;
 #endif
-    int i;
+  int i;
 
 #if defined(BFLB_BLE)
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    net_buf_init(&acl_tx_pool, CONFIG_BT_L2CAP_TX_BUF_COUNT, BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU), NULL);
+  net_buf_init(&acl_tx_pool, CONFIG_BT_L2CAP_TX_BUF_COUNT, BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU), NULL);
 #if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0
-    net_buf_init(&frag_pool, CONFIG_BT_L2CAP_TX_FRAG_COUNT, FRAG_SIZE, NULL);
+  net_buf_init(&frag_pool, CONFIG_BT_L2CAP_TX_FRAG_COUNT, FRAG_SIZE, NULL);
 #endif
-#else //BFLB_DYNAMIC_ALLOC_MEM
-    struct net_buf_pool num_complete_pool;
-    struct net_buf_pool acl_tx_pool;
+#else // BFLB_DYNAMIC_ALLOC_MEM
+  struct net_buf_pool num_complete_pool;
+  struct net_buf_pool acl_tx_pool;
 #if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0
-    struct net_buf_pool frag_pool;
+  struct net_buf_pool frag_pool;
 #endif
-#endif //BFLB_DYNAMIC_ALLOC_MEM
-    k_fifo_init(&free_tx, 20);
+#endif // BFLB_DYNAMIC_ALLOC_MEM
+  k_fifo_init(&free_tx, 20);
 #endif
-    for (i = 0; i < ARRAY_SIZE(conn_tx); i++) {
-        k_fifo_put(&free_tx, &conn_tx[i]);
-    }
+  for (i = 0; i < ARRAY_SIZE(conn_tx); i++) {
+    k_fifo_put(&free_tx, &conn_tx[i]);
+  }
 
-    bt_att_init();
+  bt_att_init();
 
 #if defined(CONFIG_BT_SMP)
-    err = bt_smp_init();
-    if (err) {
-        return err;
-    }
+  err = bt_smp_init();
+  if (err) {
+    return err;
+  }
 #endif
 
-    bt_l2cap_init();
+  bt_l2cap_init();
 
-    /* Initialize background scan */
-    if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
-        for (i = 0; i < ARRAY_SIZE(conns); i++) {
-            struct bt_conn *conn = &conns[i];
+  /* Initialize background scan */
+  if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
+    for (i = 0; i < ARRAY_SIZE(conns); i++) {
+      struct bt_conn *conn = &conns[i];
 
-            if (!atomic_get(&conn->ref)) {
-                continue;
-            }
+      if (!atomic_get(&conn->ref)) {
+        continue;
+      }
 
-            if (atomic_test_bit(conn->flags,
-                                BT_CONN_AUTO_CONNECT)) {
-                /* Only the default identity is supported */
-                conn->id = BT_ID_DEFAULT;
-                bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
-            }
-        }
+      if (atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT)) {
+        /* Only the default identity is supported */
+        conn->id = BT_ID_DEFAULT;
+        bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
+      }
     }
+  }
 
-    return 0;
+  return 0;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/crypto.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/crypto.c
index b1eeb8390e..5bcf4b2e85 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/crypto.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/crypto.c
@@ -5,19 +5,19 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
 #include 
+#include 
 
-#include 
 #include 
+#include 
 
 #include 
-#include 
 #include 
+#include 
 
+#include 
 #include 
 #include 
-#include 
 #include 
 
 #define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_HCI_CORE)
@@ -28,140 +28,132 @@
 
 static struct tc_hmac_prng_struct prng;
 
-static int prng_reseed(struct tc_hmac_prng_struct *h)
-{
-    u8_t seed[32];
-    s64_t extra;
-    int ret, i;
+static int prng_reseed(struct tc_hmac_prng_struct *h) {
+  u8_t  seed[32];
+  s64_t extra;
+  int   ret, i;
 
-    for (i = 0; i < (sizeof(seed) / 8); i++) {
-        struct bt_hci_rp_le_rand *rp;
-        struct net_buf *rsp;
+  for (i = 0; i < (sizeof(seed) / 8); i++) {
+    struct bt_hci_rp_le_rand *rp;
+    struct net_buf           *rsp;
 
-        ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp);
-        if (ret) {
-            return ret;
-        }
+    ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp);
+    if (ret) {
+      return ret;
+    }
 
-        rp = (void *)rsp->data;
-        memcpy(&seed[i * 8], rp->rand, 8);
+    rp = (void *)rsp->data;
+    memcpy(&seed[i * 8], rp->rand, 8);
 
-        net_buf_unref(rsp);
-    }
+    net_buf_unref(rsp);
+  }
 
-    extra = k_uptime_get();
+  extra = k_uptime_get();
 
-    ret = tc_hmac_prng_reseed(h, seed, sizeof(seed), (u8_t *)&extra,
-                              sizeof(extra));
-    if (ret == TC_CRYPTO_FAIL) {
-        BT_ERR("Failed to re-seed PRNG");
-        return -EIO;
-    }
+  ret = tc_hmac_prng_reseed(h, seed, sizeof(seed), (u8_t *)&extra, sizeof(extra));
+  if (ret == TC_CRYPTO_FAIL) {
+    BT_ERR("Failed to re-seed PRNG");
+    return -EIO;
+  }
 
-    return 0;
+  return 0;
 }
 
-int prng_init(void)
-{
-    struct bt_hci_rp_le_rand *rp;
-    struct net_buf *rsp;
-    int ret;
+int prng_init(void) {
+  struct bt_hci_rp_le_rand *rp;
+  struct net_buf           *rsp;
+  int                       ret;
 
-    /* Check first that HCI_LE_Rand is supported */
-    if (!BT_CMD_TEST(bt_dev.supported_commands, 27, 7)) {
-        return -ENOTSUP;
-    }
+  /* Check first that HCI_LE_Rand is supported */
+  if (!BT_CMD_TEST(bt_dev.supported_commands, 27, 7)) {
+    return -ENOTSUP;
+  }
 
-    ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp);
-    if (ret) {
-        return ret;
-    }
+  ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp);
+  if (ret) {
+    return ret;
+  }
 
-    rp = (void *)rsp->data;
+  rp = (void *)rsp->data;
 
-    ret = tc_hmac_prng_init(&prng, rp->rand, sizeof(rp->rand));
+  ret = tc_hmac_prng_init(&prng, rp->rand, sizeof(rp->rand));
 
-    net_buf_unref(rsp);
+  net_buf_unref(rsp);
 
-    if (ret == TC_CRYPTO_FAIL) {
-        BT_ERR("Failed to initialize PRNG");
-        return -EIO;
-    }
+  if (ret == TC_CRYPTO_FAIL) {
+    BT_ERR("Failed to initialize PRNG");
+    return -EIO;
+  }
 
-    /* re-seed is needed after init */
-    return prng_reseed(&prng);
+  /* re-seed is needed after init */
+  return prng_reseed(&prng);
 }
 
-int bt_rand(void *buf, size_t len)
-{
+int bt_rand(void *buf, size_t len) {
 #if !defined(CONFIG_BT_GEN_RANDOM_BY_SW)
-    k_get_random_byte_array(buf, len);
-    return 0;
+  k_get_random_byte_array(buf, len);
+  return 0;
 #else
-    int ret;
-    ret = tc_hmac_prng_generate(buf, len, &prng);
-    if (ret == TC_HMAC_PRNG_RESEED_REQ) {
-        ret = prng_reseed(&prng);
-        if (ret) {
-            return ret;
-        }
-
-        ret = tc_hmac_prng_generate(buf, len, &prng);
+  int ret;
+  ret = tc_hmac_prng_generate(buf, len, &prng);
+  if (ret == TC_HMAC_PRNG_RESEED_REQ) {
+    ret = prng_reseed(&prng);
+    if (ret) {
+      return ret;
     }
 
-    if (ret == TC_CRYPTO_SUCCESS) {
-        return 0;
-    }
+    ret = tc_hmac_prng_generate(buf, len, &prng);
+  }
 
-    return -EIO;
+  if (ret == TC_CRYPTO_SUCCESS) {
+    return 0;
+  }
+
+  return -EIO;
 #endif
 }
 
-int bt_encrypt_le(const u8_t key[16], const u8_t plaintext[16],
-                  u8_t enc_data[16])
-{
-    struct tc_aes_key_sched_struct s;
-    u8_t tmp[16];
+int bt_encrypt_le(const u8_t key[16], const u8_t plaintext[16], u8_t enc_data[16]) {
+  struct tc_aes_key_sched_struct s;
+  u8_t                           tmp[16];
 
-    BT_DBG("key %s", bt_hex(key, 16));
-    BT_DBG("plaintext %s", bt_hex(plaintext, 16));
+  BT_DBG("key %s", bt_hex(key, 16));
+  BT_DBG("plaintext %s", bt_hex(plaintext, 16));
 
-    sys_memcpy_swap(tmp, key, 16);
+  sys_memcpy_swap(tmp, key, 16);
 
-    if (tc_aes128_set_encrypt_key(&s, tmp) == TC_CRYPTO_FAIL) {
-        return -EINVAL;
-    }
+  if (tc_aes128_set_encrypt_key(&s, tmp) == TC_CRYPTO_FAIL) {
+    return -EINVAL;
+  }
 
-    sys_memcpy_swap(tmp, plaintext, 16);
+  sys_memcpy_swap(tmp, plaintext, 16);
 
-    if (tc_aes_encrypt(enc_data, tmp, &s) == TC_CRYPTO_FAIL) {
-        return -EINVAL;
-    }
+  if (tc_aes_encrypt(enc_data, tmp, &s) == TC_CRYPTO_FAIL) {
+    return -EINVAL;
+  }
 
-    sys_mem_swap(enc_data, 16);
+  sys_mem_swap(enc_data, 16);
 
-    BT_DBG("enc_data %s", bt_hex(enc_data, 16));
+  BT_DBG("enc_data %s", bt_hex(enc_data, 16));
 
-    return 0;
+  return 0;
 }
 
-int bt_encrypt_be(const u8_t key[16], const u8_t plaintext[16],
-                  u8_t enc_data[16])
-{
-    struct tc_aes_key_sched_struct s;
+int bt_encrypt_be(const u8_t key[16], const u8_t plaintext[16], u8_t enc_data[16]) {
+  struct tc_aes_key_sched_struct s;
 
-    BT_DBG("key %s", bt_hex(key, 16));
-    BT_DBG("plaintext %s", bt_hex(plaintext, 16));
+  BT_DBG("key %s", bt_hex(key, 16));
+  BT_DBG("plaintext %s", bt_hex(plaintext, 16));
 
-    if (tc_aes128_set_encrypt_key(&s, key) == TC_CRYPTO_FAIL) {
-        return -EINVAL;
-    }
+  if (tc_aes128_set_encrypt_key(&s, key) == TC_CRYPTO_FAIL) {
+    return -EINVAL;
+  }
 
-    if (tc_aes_encrypt(enc_data, plaintext, &s) == TC_CRYPTO_FAIL) {
-        return -EINVAL;
-    }
+  if (tc_aes_encrypt(enc_data, plaintext, &s) == TC_CRYPTO_FAIL) {
+    return -EINVAL;
+  }
 
-    BT_DBG("enc_data %s", bt_hex(enc_data, 16));
+  BT_DBG("enc_data %s", bt_hex(enc_data, 16));
 
-    return 0;
+  return 0;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c
index e6ed08ae45..2254d31a3f 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c
@@ -6,29 +6,29 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
-#include 
-#include 
-#include 
 #include 
+#include 
 #include 
 #include 
+#include 
+#include 
+#include 
+#include 
 
 #include 
 
 #if defined(CONFIG_BT_GATT_CACHING)
-#include 
-#include 
 #include 
-#include 
 #include 
+#include 
+#include 
+#include 
 #endif /* CONFIG_BT_GATT_CACHING */
-#include 
 #include 
-#include 
 #include 
 #include 
+#include 
+#include 
 #if defined(BFLB_BLE)
 #include "ble_config.h"
 #include 
@@ -48,14 +48,14 @@ extern u8_t event_flag;
 #define LOG_MODULE_NAME bt_gatt
 #include "log.h"
 
-#include "hci_core.h"
+#include "att_internal.h"
 #include "conn_internal.h"
+#include "gatt_internal.h"
+#include "hci_core.h"
 #include "keys.h"
 #include "l2cap_internal.h"
-#include "att_internal.h"
-#include "smp.h"
 #include "settings.h"
-#include "gatt_internal.h"
+#include "smp.h"
 
 #define SC_TIMEOUT      K_MSEC(10)
 #define CCC_STORE_DELAY K_SECONDS(1)
@@ -66,8 +66,8 @@ static u16_t last_static_handle;
 
 /* Persistent storage format for GATT CCC */
 struct ccc_store {
-    u16_t handle;
-    u16_t value;
+  u16_t handle;
+  u16_t value;
 };
 
 #if defined(CONFIG_BT_GATT_CLIENT)
@@ -86,91 +86,69 @@ static atomic_t init;
 bt_gatt_mtu_changed_cb_t gatt_mtu_changed_cb;
 #endif
 
-static ssize_t read_name(struct bt_conn *conn, const struct bt_gatt_attr *attr,
-                         void *buf, u16_t len, u16_t offset)
-{
-    const char *name = bt_get_name();
+static ssize_t read_name(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  const char *name = bt_get_name();
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, name,
-                             strlen(name));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, name, strlen(name));
 }
 
 #if defined(CONFIG_BT_DEVICE_NAME_GATT_WRITABLE)
 
-static ssize_t write_name(struct bt_conn *conn, const struct bt_gatt_attr *attr,
-                          const void *buf, u16_t len, u16_t offset,
-                          u8_t flags)
-{
-    char value[CONFIG_BT_DEVICE_NAME_MAX] = {};
+static ssize_t write_name(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len, u16_t offset, u8_t flags) {
+  char value[CONFIG_BT_DEVICE_NAME_MAX] = {};
 
-    if (offset) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
-    }
+  if (offset) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
+  }
 
-    if (len >= sizeof(value)) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
-    }
+  if (len >= sizeof(value)) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
+  }
 
-    memcpy(value, buf, len);
+  memcpy(value, buf, len);
 
-    bt_set_name(value);
+  bt_set_name(value);
 
-    return len;
+  return len;
 }
 
 #endif /* CONFIG_BT_DEVICE_NAME_GATT_WRITABLE */
 
-static ssize_t read_appearance(struct bt_conn *conn,
-                               const struct bt_gatt_attr *attr, void *buf,
-                               u16_t len, u16_t offset)
-{
-    u16_t appearance = sys_cpu_to_le16(gap_appearance);
+static ssize_t read_appearance(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  u16_t appearance = sys_cpu_to_le16(gap_appearance);
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &appearance,
-                             sizeof(appearance));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &appearance, sizeof(appearance));
 }
 
 #if defined(CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS)
 /* This checks if the range entered is valid */
-BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_MIN_INT > 3200 &&
-               CONFIG_BT_PERIPHERAL_PREF_MIN_INT < 0xffff));
-BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_MAX_INT > 3200 &&
-               CONFIG_BT_PERIPHERAL_PREF_MAX_INT < 0xffff));
-BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_TIMEOUT > 3200 &&
-               CONFIG_BT_PERIPHERAL_PREF_TIMEOUT < 0xffff));
-BUILD_ASSERT((CONFIG_BT_PERIPHERAL_PREF_MIN_INT == 0xffff) ||
-             (CONFIG_BT_PERIPHERAL_PREF_MIN_INT <=
-              CONFIG_BT_PERIPHERAL_PREF_MAX_INT));
-
-static ssize_t read_ppcp(struct bt_conn *conn, const struct bt_gatt_attr *attr,
-                         void *buf, u16_t len, u16_t offset)
-{
-    struct __packed {
-        u16_t min_int;
-        u16_t max_int;
-        u16_t latency;
-        u16_t timeout;
-    } ppcp;
-
-    ppcp.min_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MIN_INT);
-    ppcp.max_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MAX_INT);
-    ppcp.latency = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY);
-    ppcp.timeout = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_TIMEOUT);
-
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &ppcp,
-                             sizeof(ppcp));
+BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_MIN_INT > 3200 && CONFIG_BT_PERIPHERAL_PREF_MIN_INT < 0xffff));
+BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_MAX_INT > 3200 && CONFIG_BT_PERIPHERAL_PREF_MAX_INT < 0xffff));
+BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_TIMEOUT > 3200 && CONFIG_BT_PERIPHERAL_PREF_TIMEOUT < 0xffff));
+BUILD_ASSERT((CONFIG_BT_PERIPHERAL_PREF_MIN_INT == 0xffff) || (CONFIG_BT_PERIPHERAL_PREF_MIN_INT <= CONFIG_BT_PERIPHERAL_PREF_MAX_INT));
+
+static ssize_t read_ppcp(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  struct __packed {
+    u16_t min_int;
+    u16_t max_int;
+    u16_t latency;
+    u16_t timeout;
+  } ppcp;
+
+  ppcp.min_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MIN_INT);
+  ppcp.max_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MAX_INT);
+  ppcp.latency = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY);
+  ppcp.timeout = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_TIMEOUT);
+
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &ppcp, sizeof(ppcp));
 }
 #endif
 
 #if defined(CONFIG_BT_CENTRAL) && defined(CONFIG_BT_PRIVACY)
-static ssize_t read_central_addr_res(struct bt_conn *conn,
-                                     const struct bt_gatt_attr *attr, void *buf,
-                                     u16_t len, u16_t offset)
-{
-    u8_t central_addr_res = BT_GATT_CENTRAL_ADDR_RES_SUPP;
+static ssize_t read_central_addr_res(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  u8_t central_addr_res = BT_GATT_CENTRAL_ADDR_RES_SUPP;
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset,
-                             ¢ral_addr_res, sizeof(central_addr_res));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, ¢ral_addr_res, sizeof(central_addr_res));
 }
 #endif /* CONFIG_BT_CENTRAL && CONFIG_BT_PRIVACY */
 
@@ -183,24 +161,16 @@ BT_GATT_SERVICE_DEFINE(_2_gap_svc,
 
 #if defined(CONFIG_BT_DEVICE_NAME_GATT_WRITABLE)
     /* Require pairing for writes to device name */
-    BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME,
-                           BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
-                           BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
-                           read_name, write_name, bt_dev.name),
+    BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME, BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, read_name, write_name, bt_dev.name),
 #else
-                       BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME, BT_GATT_CHRC_READ,
-                                              BT_GATT_PERM_READ, read_name, NULL, NULL),
+                       BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_name, NULL, NULL),
 #endif /* CONFIG_BT_DEVICE_NAME_GATT_WRITABLE */
-    BT_GATT_CHARACTERISTIC(BT_UUID_GAP_APPEARANCE, BT_GATT_CHRC_READ,
-                           BT_GATT_PERM_READ, read_appearance, NULL, NULL),
+    BT_GATT_CHARACTERISTIC(BT_UUID_GAP_APPEARANCE, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_appearance, NULL, NULL),
 #if defined(CONFIG_BT_CENTRAL) && defined(CONFIG_BT_PRIVACY)
-    BT_GATT_CHARACTERISTIC(BT_UUID_CENTRAL_ADDR_RES,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_central_addr_res, NULL, NULL),
+    BT_GATT_CHARACTERISTIC(BT_UUID_CENTRAL_ADDR_RES, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_central_addr_res, NULL, NULL),
 #endif /* CONFIG_BT_CENTRAL && CONFIG_BT_PRIVACY */
 #if defined(CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS)
-    BT_GATT_CHARACTERISTIC(BT_UUID_GAP_PPCP, BT_GATT_CHRC_READ,
-                           BT_GATT_PERM_READ, read_ppcp, NULL, NULL),
+    BT_GATT_CHARACTERISTIC(BT_UUID_GAP_PPCP, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_ppcp, NULL, NULL),
 #endif
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
 };
@@ -213,508 +183,458 @@ static struct bt_gatt_service gap_svc = BT_GATT_SERVICE(gap_attrs);
 #endif
 
 struct sc_data {
-    u16_t start;
-    u16_t end;
+  u16_t start;
+  u16_t end;
 } __packed;
 
 struct gatt_sc_cfg {
-    u8_t id;
-    bt_addr_le_t peer;
-    struct {
-        u16_t start;
-        u16_t end;
-    } data;
+  u8_t         id;
+  bt_addr_le_t peer;
+  struct {
+    u16_t start;
+    u16_t end;
+  } data;
 };
 
 #define SC_CFG_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN)
 static struct gatt_sc_cfg sc_cfg[SC_CFG_MAX];
 BUILD_ASSERT(sizeof(struct sc_data) == sizeof(sc_cfg[0].data));
 
-static struct gatt_sc_cfg *find_sc_cfg(u8_t id, bt_addr_le_t *addr)
-{
-    BT_DBG("id: %u, addr: %s", id, bt_addr_le_str(addr));
+static struct gatt_sc_cfg *find_sc_cfg(u8_t id, bt_addr_le_t *addr) {
+  BT_DBG("id: %u, addr: %s", id, bt_addr_le_str(addr));
 
-    for (size_t i = 0; i < ARRAY_SIZE(sc_cfg); i++) {
-        if (id == sc_cfg[i].id &&
-            !bt_addr_le_cmp(&sc_cfg[i].peer, addr)) {
-            return &sc_cfg[i];
-        }
+  for (size_t i = 0; i < ARRAY_SIZE(sc_cfg); i++) {
+    if (id == sc_cfg[i].id && !bt_addr_le_cmp(&sc_cfg[i].peer, addr)) {
+      return &sc_cfg[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-static void sc_store(struct gatt_sc_cfg *cfg)
-{
-    char key[BT_SETTINGS_KEY_MAX];
-    int err;
+static void sc_store(struct gatt_sc_cfg *cfg) {
+  char key[BT_SETTINGS_KEY_MAX];
+  int  err;
 
-    if (cfg->id) {
-        char id_str[4];
+  if (cfg->id) {
+    char id_str[4];
 
-        u8_to_dec(id_str, sizeof(id_str), cfg->id);
-        bt_settings_encode_key(key, sizeof(key), "sc",
-                               &cfg->peer, id_str);
-    } else {
-        bt_settings_encode_key(key, sizeof(key), "sc",
-                               &cfg->peer, NULL);
-    }
+    u8_to_dec(id_str, sizeof(id_str), cfg->id);
+    bt_settings_encode_key(key, sizeof(key), "sc", &cfg->peer, id_str);
+  } else {
+    bt_settings_encode_key(key, sizeof(key), "sc", &cfg->peer, NULL);
+  }
 
-    err = settings_save_one(key, (u8_t *)&cfg->data, sizeof(cfg->data));
-    if (err) {
-        BT_ERR("failed to store SC (err %d)", err);
-        return;
-    }
+  err = settings_save_one(key, (u8_t *)&cfg->data, sizeof(cfg->data));
+  if (err) {
+    BT_ERR("failed to store SC (err %d)", err);
+    return;
+  }
 
-    BT_DBG("stored SC for %s (%s, 0x%04x-0x%04x)",
-           bt_addr_le_str(&cfg->peer), log_strdup(key), cfg->data.start,
-           cfg->data.end);
+  BT_DBG("stored SC for %s (%s, 0x%04x-0x%04x)", bt_addr_le_str(&cfg->peer), log_strdup(key), cfg->data.start, cfg->data.end);
 }
 
-static void sc_clear(struct gatt_sc_cfg *cfg)
-{
-    BT_DBG("peer %s", bt_addr_le_str(&cfg->peer));
+static void sc_clear(struct gatt_sc_cfg *cfg) {
+  BT_DBG("peer %s", bt_addr_le_str(&cfg->peer));
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        bool modified = false;
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    bool modified = false;
 
-        if (cfg->data.start || cfg->data.end) {
-            modified = true;
-        }
+    if (cfg->data.start || cfg->data.end) {
+      modified = true;
+    }
 
-        if (modified && bt_addr_le_is_bonded(cfg->id, &cfg->peer)) {
-            char key[BT_SETTINGS_KEY_MAX];
-            int err;
-
-            if (cfg->id) {
-                char id_str[4];
-
-                u8_to_dec(id_str, sizeof(id_str), cfg->id);
-                bt_settings_encode_key(key, sizeof(key), "sc",
-                                       &cfg->peer, id_str);
-            } else {
-                bt_settings_encode_key(key, sizeof(key), "sc",
-                                       &cfg->peer, NULL);
-            }
-
-            err = settings_delete(key);
-            if (err) {
-                BT_ERR("failed to delete SC (err %d)", err);
-            } else {
-                BT_DBG("deleted SC for %s (%s)",
-                       bt_addr_le_str(&cfg->peer),
-                       log_strdup(key));
-            }
-        }
+    if (modified && bt_addr_le_is_bonded(cfg->id, &cfg->peer)) {
+      char key[BT_SETTINGS_KEY_MAX];
+      int  err;
+
+      if (cfg->id) {
+        char id_str[4];
+
+        u8_to_dec(id_str, sizeof(id_str), cfg->id);
+        bt_settings_encode_key(key, sizeof(key), "sc", &cfg->peer, id_str);
+      } else {
+        bt_settings_encode_key(key, sizeof(key), "sc", &cfg->peer, NULL);
+      }
+
+      err = settings_delete(key);
+      if (err) {
+        BT_ERR("failed to delete SC (err %d)", err);
+      } else {
+        BT_DBG("deleted SC for %s (%s)", bt_addr_le_str(&cfg->peer), log_strdup(key));
+      }
     }
+  }
 
-    memset(cfg, 0, sizeof(*cfg));
+  memset(cfg, 0, sizeof(*cfg));
 }
 
-static void sc_reset(struct gatt_sc_cfg *cfg)
-{
-    BT_DBG("peer %s", bt_addr_le_str(&cfg->peer));
+static void sc_reset(struct gatt_sc_cfg *cfg) {
+  BT_DBG("peer %s", bt_addr_le_str(&cfg->peer));
 
-    memset(&cfg->data, 0, sizeof(cfg->data));
+  memset(&cfg->data, 0, sizeof(cfg->data));
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        sc_store(cfg);
-    }
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    sc_store(cfg);
+  }
 }
 
-static bool update_range(u16_t *start, u16_t *end, u16_t new_start,
-                         u16_t new_end)
-{
-    BT_DBG("start 0x%04x end 0x%04x new_start 0x%04x new_end 0x%04x",
-           *start, *end, new_start, new_end);
+static bool update_range(u16_t *start, u16_t *end, u16_t new_start, u16_t new_end) {
+  BT_DBG("start 0x%04x end 0x%04x new_start 0x%04x new_end 0x%04x", *start, *end, new_start, new_end);
 
-    /* Check if inside existing range */
-    if (new_start >= *start && new_end <= *end) {
-        return false;
-    }
+  /* Check if inside existing range */
+  if (new_start >= *start && new_end <= *end) {
+    return false;
+  }
 
-    /* Update range */
-    if (*start > new_start) {
-        *start = new_start;
-    }
+  /* Update range */
+  if (*start > new_start) {
+    *start = new_start;
+  }
 
-    if (*end < new_end) {
-        *end = new_end;
-    }
+  if (*end < new_end) {
+    *end = new_end;
+  }
 
-    return true;
+  return true;
 }
 
-static void sc_save(u8_t id, bt_addr_le_t *peer, u16_t start, u16_t end)
-{
-    struct gatt_sc_cfg *cfg;
-    bool modified = false;
+static void sc_save(u8_t id, bt_addr_le_t *peer, u16_t start, u16_t end) {
+  struct gatt_sc_cfg *cfg;
+  bool                modified = false;
 
-    BT_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(peer), start,
-           end);
+  BT_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(peer), start, end);
 
-    cfg = find_sc_cfg(id, peer);
+  cfg = find_sc_cfg(id, peer);
+  if (!cfg) {
+    /* Find and initialize a free sc_cfg entry */
+    cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY);
     if (!cfg) {
-        /* Find and initialize a free sc_cfg entry */
-        cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY);
-        if (!cfg) {
-            BT_ERR("unable to save SC: no cfg left");
-            return;
-        }
-
-        cfg->id = id;
-        bt_addr_le_copy(&cfg->peer, peer);
+      BT_ERR("unable to save SC: no cfg left");
+      return;
     }
 
-    /* Check if there is any change stored */
-    if (!(cfg->data.start || cfg->data.end)) {
-        cfg->data.start = start;
-        cfg->data.end = end;
-        modified = true;
-        goto done;
-    }
+    cfg->id = id;
+    bt_addr_le_copy(&cfg->peer, peer);
+  }
+
+  /* Check if there is any change stored */
+  if (!(cfg->data.start || cfg->data.end)) {
+    cfg->data.start = start;
+    cfg->data.end   = end;
+    modified        = true;
+    goto done;
+  }
 
-    modified = update_range(&cfg->data.start, &cfg->data.end, start, end);
+  modified = update_range(&cfg->data.start, &cfg->data.end, start, end);
 
 done:
-    if (IS_ENABLED(CONFIG_BT_SETTINGS) &&
-        modified && bt_addr_le_is_bonded(cfg->id, &cfg->peer)) {
-        sc_store(cfg);
-    }
+  if (IS_ENABLED(CONFIG_BT_SETTINGS) && modified && bt_addr_le_is_bonded(cfg->id, &cfg->peer)) {
+    sc_store(cfg);
+  }
 }
 
-static bool sc_ccc_cfg_write(struct bt_conn *conn,
-                             const struct bt_gatt_attr *attr,
-                             u16_t value)
-{
-    BT_DBG("value 0x%04x", value);
+static bool sc_ccc_cfg_write(struct bt_conn *conn, const struct bt_gatt_attr *attr, u16_t value) {
+  BT_DBG("value 0x%04x", value);
 
-    if (value == BT_GATT_CCC_INDICATE) {
-        /* Create a new SC configuration entry if subscribed */
-        sc_save(conn->id, &conn->le.dst, 0, 0);
-    } else {
-        struct gatt_sc_cfg *cfg;
+  if (value == BT_GATT_CCC_INDICATE) {
+    /* Create a new SC configuration entry if subscribed */
+    sc_save(conn->id, &conn->le.dst, 0, 0);
+  } else {
+    struct gatt_sc_cfg *cfg;
 
-        /* Clear SC configuration if unsubscribed */
-        cfg = find_sc_cfg(conn->id, &conn->le.dst);
-        if (cfg) {
-            sc_clear(cfg);
-        }
+    /* Clear SC configuration if unsubscribed */
+    cfg = find_sc_cfg(conn->id, &conn->le.dst);
+    if (cfg) {
+      sc_clear(cfg);
     }
+  }
 
-    return true;
+  return true;
 }
 
-static struct _bt_gatt_ccc sc_ccc = BT_GATT_CCC_INITIALIZER(NULL,
-                                                            sc_ccc_cfg_write,
-                                                            NULL);
+static struct _bt_gatt_ccc sc_ccc = BT_GATT_CCC_INITIALIZER(NULL, sc_ccc_cfg_write, NULL);
 
 #if defined(CONFIG_BT_GATT_CACHING)
 enum {
-    CF_CHANGE_AWARE, /* Client is changed aware */
-    CF_OUT_OF_SYNC,  /* Client is out of sync */
+  CF_CHANGE_AWARE, /* Client is changed aware */
+  CF_OUT_OF_SYNC,  /* Client is out of sync */
 
-    /* Total number of flags - must be at the end of the enum */
-    CF_NUM_FLAGS,
+  /* Total number of flags - must be at the end of the enum */
+  CF_NUM_FLAGS,
 };
 
 #define CF_ROBUST_CACHING(_cfg) (_cfg->data[0] & BIT(0))
 
 struct gatt_cf_cfg {
-    u8_t id;
-    bt_addr_le_t peer;
-    u8_t data[1];
-    ATOMIC_DEFINE(flags, CF_NUM_FLAGS);
+  u8_t         id;
+  bt_addr_le_t peer;
+  u8_t         data[1];
+  ATOMIC_DEFINE(flags, CF_NUM_FLAGS);
 };
 
 #define CF_CFG_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN)
 static struct gatt_cf_cfg cf_cfg[CF_CFG_MAX] = {};
 
-static struct gatt_cf_cfg *find_cf_cfg(struct bt_conn *conn)
-{
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
-        if (!conn) {
-            if (!bt_addr_le_cmp(&cf_cfg[i].peer, BT_ADDR_LE_ANY)) {
-                return &cf_cfg[i];
-            }
-        } else if (!bt_conn_addr_le_cmp(conn, &cf_cfg[i].peer)) {
-            return &cf_cfg[i];
-        }
+static struct gatt_cf_cfg *find_cf_cfg(struct bt_conn *conn) {
+  int i;
+
+  for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
+    if (!conn) {
+      if (!bt_addr_le_cmp(&cf_cfg[i].peer, BT_ADDR_LE_ANY)) {
+        return &cf_cfg[i];
+      }
+    } else if (!bt_conn_addr_le_cmp(conn, &cf_cfg[i].peer)) {
+      return &cf_cfg[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-static ssize_t cf_read(struct bt_conn *conn, const struct bt_gatt_attr *attr,
-                       void *buf, u16_t len, u16_t offset)
-{
-    struct gatt_cf_cfg *cfg;
-    u8_t data[1] = {};
+static ssize_t cf_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  struct gatt_cf_cfg *cfg;
+  u8_t                data[1] = {};
 
-    cfg = find_cf_cfg(conn);
-    if (cfg) {
-        memcpy(data, cfg->data, sizeof(data));
-    }
+  cfg = find_cf_cfg(conn);
+  if (cfg) {
+    memcpy(data, cfg->data, sizeof(data));
+  }
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, data,
-                             sizeof(data));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, data, sizeof(data));
 }
 
-static bool cf_set_value(struct gatt_cf_cfg *cfg, const u8_t *value, u16_t len)
-{
-    u16_t i;
-    u8_t last_byte = 1U;
-    u8_t last_bit = 1U;
-
-    /* Validate the bits */
-    for (i = 0U; i < len && i < last_byte; i++) {
-        u8_t chg_bits = value[i] ^ cfg->data[i];
-        u8_t bit;
-
-        for (bit = 0U; bit < last_bit; bit++) {
-            /* A client shall never clear a bit it has set */
-            if ((BIT(bit) & chg_bits) &&
-                (BIT(bit) & cfg->data[i])) {
-                return false;
-            }
-        }
-    }
+static bool cf_set_value(struct gatt_cf_cfg *cfg, const u8_t *value, u16_t len) {
+  u16_t i;
+  u8_t  last_byte = 1U;
+  u8_t  last_bit  = 1U;
+
+  /* Validate the bits */
+  for (i = 0U; i < len && i < last_byte; i++) {
+    u8_t chg_bits = value[i] ^ cfg->data[i];
+    u8_t bit;
 
-    /* Set the bits for each octect */
-    for (i = 0U; i < len && i < last_byte; i++) {
-        cfg->data[i] |= value[i] & ((1 << last_bit) - 1);
-        BT_DBG("byte %u: data 0x%02x value 0x%02x", i, cfg->data[i],
-               value[i]);
+    for (bit = 0U; bit < last_bit; bit++) {
+      /* A client shall never clear a bit it has set */
+      if ((BIT(bit) & chg_bits) && (BIT(bit) & cfg->data[i])) {
+        return false;
+      }
     }
+  }
 
-    return true;
+  /* Set the bits for each octect */
+  for (i = 0U; i < len && i < last_byte; i++) {
+    cfg->data[i] |= value[i] & ((1 << last_bit) - 1);
+    BT_DBG("byte %u: data 0x%02x value 0x%02x", i, cfg->data[i], value[i]);
+  }
+
+  return true;
 }
 
-static ssize_t cf_write(struct bt_conn *conn, const struct bt_gatt_attr *attr,
-                        const void *buf, u16_t len, u16_t offset, u8_t flags)
-{
-    struct gatt_cf_cfg *cfg;
-    const u8_t *value = buf;
+static ssize_t cf_write(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len, u16_t offset, u8_t flags) {
+  struct gatt_cf_cfg *cfg;
+  const u8_t         *value = buf;
 
-    if (offset > sizeof(cfg->data)) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
-    }
+  if (offset > sizeof(cfg->data)) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
+  }
 
-    if (offset + len > sizeof(cfg->data)) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
-    }
+  if (offset + len > sizeof(cfg->data)) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
+  }
 
-    cfg = find_cf_cfg(conn);
-    if (!cfg) {
-        cfg = find_cf_cfg(NULL);
-    }
+  cfg = find_cf_cfg(conn);
+  if (!cfg) {
+    cfg = find_cf_cfg(NULL);
+  }
 
-    if (!cfg) {
-        BT_WARN("No space to store Client Supported Features");
-        return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
-    }
+  if (!cfg) {
+    BT_WARN("No space to store Client Supported Features");
+    return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
+  }
 
-    BT_DBG("handle 0x%04x len %u", attr->handle, len);
+  BT_DBG("handle 0x%04x len %u", attr->handle, len);
 
-    if (!cf_set_value(cfg, value, len)) {
-        return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
-    }
+  if (!cf_set_value(cfg, value, len)) {
+    return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
+  }
 
-    bt_addr_le_copy(&cfg->peer, &conn->le.dst);
-    atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
+  bt_addr_le_copy(&cfg->peer, &conn->le.dst);
+  atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
 
-    return len;
+  return len;
 }
 
-static u8_t db_hash[16];
+static u8_t           db_hash[16];
 struct k_delayed_work db_hash_work;
 
 struct gen_hash_state {
-    struct tc_cmac_struct state;
-    int err;
+  struct tc_cmac_struct state;
+  int                   err;
 };
 
-static u8_t gen_hash_m(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct gen_hash_state *state = user_data;
-    struct bt_uuid_16 *u16;
-    u8_t data[16];
-    ssize_t len;
-    u16_t value;
-
-    if (attr->uuid->type != BT_UUID_TYPE_16)
-        return BT_GATT_ITER_CONTINUE;
-
-    u16 = (struct bt_uuid_16 *)attr->uuid;
-
-    switch (u16->val) {
-        /* Attributes to hash: handle + UUID + value */
-        case 0x2800: /* GATT Primary Service */
-        case 0x2801: /* GATT Secondary Service */
-        case 0x2802: /* GATT Include Service */
-        case 0x2803: /* GATT Characteristic */
-        case 0x2900: /* GATT Characteristic Extended Properties */
-            value = sys_cpu_to_le16(attr->handle);
-            if (tc_cmac_update(&state->state, (uint8_t *)&value,
-                               sizeof(attr->handle)) == TC_CRYPTO_FAIL) {
-                state->err = -EINVAL;
-                return BT_GATT_ITER_STOP;
-            }
-
-            value = sys_cpu_to_le16(u16->val);
-            if (tc_cmac_update(&state->state, (uint8_t *)&value,
-                               sizeof(u16->val)) == TC_CRYPTO_FAIL) {
-                state->err = -EINVAL;
-                return BT_GATT_ITER_STOP;
-            }
-
-            len = attr->read(NULL, attr, data, sizeof(data), 0);
-            if (len < 0) {
-                state->err = len;
-                return BT_GATT_ITER_STOP;
-            }
-
-            if (tc_cmac_update(&state->state, data, len) ==
-                TC_CRYPTO_FAIL) {
-                state->err = -EINVAL;
-                return BT_GATT_ITER_STOP;
-            }
-
-            break;
-        /* Attributes to hash: handle + UUID */
-        case 0x2901: /* GATT Characteristic User Descriptor */
-        case 0x2902: /* GATT Client Characteristic Configuration */
-        case 0x2903: /* GATT Server Characteristic Configuration */
-        case 0x2904: /* GATT Characteristic Presentation Format */
-        case 0x2905: /* GATT Characteristic Aggregated Format */
-            value = sys_cpu_to_le16(attr->handle);
-            if (tc_cmac_update(&state->state, (uint8_t *)&value,
-                               sizeof(attr->handle)) == TC_CRYPTO_FAIL) {
-                state->err = -EINVAL;
-                return BT_GATT_ITER_STOP;
-            }
-
-            value = sys_cpu_to_le16(u16->val);
-            if (tc_cmac_update(&state->state, (uint8_t *)&value,
-                               sizeof(u16->val)) == TC_CRYPTO_FAIL) {
-                state->err = -EINVAL;
-                return BT_GATT_ITER_STOP;
-            }
-            break;
-        default:
-            return BT_GATT_ITER_CONTINUE;
-    }
+static u8_t gen_hash_m(const struct bt_gatt_attr *attr, void *user_data) {
+  struct gen_hash_state *state = user_data;
+  struct bt_uuid_16     *u16;
+  u8_t                   data[16];
+  ssize_t                len;
+  u16_t                  value;
 
+  if (attr->uuid->type != BT_UUID_TYPE_16)
     return BT_GATT_ITER_CONTINUE;
-}
 
-static void db_hash_store(void)
-{
-    int err;
+  u16 = (struct bt_uuid_16 *)attr->uuid;
 
-    err = settings_save_one("bt/hash", &db_hash, sizeof(db_hash));
-    if (err) {
-        BT_ERR("Failed to save Database Hash (err %d)", err);
+  switch (u16->val) {
+  /* Attributes to hash: handle + UUID + value */
+  case 0x2800: /* GATT Primary Service */
+  case 0x2801: /* GATT Secondary Service */
+  case 0x2802: /* GATT Include Service */
+  case 0x2803: /* GATT Characteristic */
+  case 0x2900: /* GATT Characteristic Extended Properties */
+    value = sys_cpu_to_le16(attr->handle);
+    if (tc_cmac_update(&state->state, (uint8_t *)&value, sizeof(attr->handle)) == TC_CRYPTO_FAIL) {
+      state->err = -EINVAL;
+      return BT_GATT_ITER_STOP;
     }
 
-    BT_DBG("Database Hash stored");
-}
+    value = sys_cpu_to_le16(u16->val);
+    if (tc_cmac_update(&state->state, (uint8_t *)&value, sizeof(u16->val)) == TC_CRYPTO_FAIL) {
+      state->err = -EINVAL;
+      return BT_GATT_ITER_STOP;
+    }
 
-static void db_hash_gen(bool store)
-{
-    u8_t key[16] = {};
-    struct tc_aes_key_sched_struct sched;
-    struct gen_hash_state state;
+    len = attr->read(NULL, attr, data, sizeof(data), 0);
+    if (len < 0) {
+      state->err = len;
+      return BT_GATT_ITER_STOP;
+    }
 
-    if (tc_cmac_setup(&state.state, key, &sched) == TC_CRYPTO_FAIL) {
-        BT_ERR("Unable to setup AES CMAC");
-        return;
+    if (tc_cmac_update(&state->state, data, len) == TC_CRYPTO_FAIL) {
+      state->err = -EINVAL;
+      return BT_GATT_ITER_STOP;
     }
 
-    bt_gatt_foreach_attr(0x0001, 0xffff, gen_hash_m, &state);
+    break;
+  /* Attributes to hash: handle + UUID */
+  case 0x2901: /* GATT Characteristic User Descriptor */
+  case 0x2902: /* GATT Client Characteristic Configuration */
+  case 0x2903: /* GATT Server Characteristic Configuration */
+  case 0x2904: /* GATT Characteristic Presentation Format */
+  case 0x2905: /* GATT Characteristic Aggregated Format */
+    value = sys_cpu_to_le16(attr->handle);
+    if (tc_cmac_update(&state->state, (uint8_t *)&value, sizeof(attr->handle)) == TC_CRYPTO_FAIL) {
+      state->err = -EINVAL;
+      return BT_GATT_ITER_STOP;
+    }
 
-    if (tc_cmac_final(db_hash, &state.state) == TC_CRYPTO_FAIL) {
-        BT_ERR("Unable to calculate hash");
-        return;
+    value = sys_cpu_to_le16(u16->val);
+    if (tc_cmac_update(&state->state, (uint8_t *)&value, sizeof(u16->val)) == TC_CRYPTO_FAIL) {
+      state->err = -EINVAL;
+      return BT_GATT_ITER_STOP;
     }
+    break;
+  default:
+    return BT_GATT_ITER_CONTINUE;
+  }
+
+  return BT_GATT_ITER_CONTINUE;
+}
+
+static void db_hash_store(void) {
+  int err;
+
+  err = settings_save_one("bt/hash", &db_hash, sizeof(db_hash));
+  if (err) {
+    BT_ERR("Failed to save Database Hash (err %d)", err);
+  }
+
+  BT_DBG("Database Hash stored");
+}
+
+static void db_hash_gen(bool store) {
+  u8_t                           key[16] = {};
+  struct tc_aes_key_sched_struct sched;
+  struct gen_hash_state          state;
+
+  if (tc_cmac_setup(&state.state, key, &sched) == TC_CRYPTO_FAIL) {
+    BT_ERR("Unable to setup AES CMAC");
+    return;
+  }
+
+  bt_gatt_foreach_attr(0x0001, 0xffff, gen_hash_m, &state);
+
+  if (tc_cmac_final(db_hash, &state.state) == TC_CRYPTO_FAIL) {
+    BT_ERR("Unable to calculate hash");
+    return;
+  }
 
-    /**
-	 * Core 5.1 does not state the endianess of the hash.
-	 * However Vol 3, Part F, 3.3.1 says that multi-octet Characteristic
-	 * Values shall be LE unless otherwise defined. PTS expects hash to be
-	 * in little endianess as well. bt_smp_aes_cmac calculates the hash in
-	 * big endianess so we have to swap.
-	 */
-    sys_mem_swap(db_hash, sizeof(db_hash));
+  /**
+   * Core 5.1 does not state the endianess of the hash.
+   * However Vol 3, Part F, 3.3.1 says that multi-octet Characteristic
+   * Values shall be LE unless otherwise defined. PTS expects hash to be
+   * in little endianess as well. bt_smp_aes_cmac calculates the hash in
+   * big endianess so we have to swap.
+   */
+  sys_mem_swap(db_hash, sizeof(db_hash));
 
 #if !defined(BFLB_BLE)
-    BT_HEXDUMP_DBG(db_hash, sizeof(db_hash), "Hash: ");
+  BT_HEXDUMP_DBG(db_hash, sizeof(db_hash), "Hash: ");
 #endif
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) {
-        db_hash_store();
-    }
+  if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) {
+    db_hash_store();
+  }
 }
 
-static void db_hash_process(struct k_work *work)
-{
-    db_hash_gen(true);
-}
+static void db_hash_process(struct k_work *work) { db_hash_gen(true); }
 
-static ssize_t db_hash_read(struct bt_conn *conn,
-                            const struct bt_gatt_attr *attr,
-                            void *buf, u16_t len, u16_t offset)
-{
-    /* Check if db_hash is already pending in which case it shall be
-	 * generated immediately instead of waiting the work to complete.
-	 */
-    if (k_delayed_work_remaining_get(&db_hash_work)) {
-        k_delayed_work_cancel(&db_hash_work);
-        db_hash_gen(true);
-    }
+static ssize_t db_hash_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  /* Check if db_hash is already pending in which case it shall be
+   * generated immediately instead of waiting the work to complete.
+   */
+  if (k_delayed_work_remaining_get(&db_hash_work)) {
+    k_delayed_work_cancel(&db_hash_work);
+    db_hash_gen(true);
+  }
 
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
-	 * 2.5.2.1 Robust Caching
-	 * A connected client becomes change-aware when...
-	 * The client reads the Database Hash characteristic and then the server
-	 * receives another ATT request from the client.
-	 */
-    bt_gatt_change_aware(conn, true);
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
+   * 2.5.2.1 Robust Caching
+   * A connected client becomes change-aware when...
+   * The client reads the Database Hash characteristic and then the server
+   * receives another ATT request from the client.
+   */
+  bt_gatt_change_aware(conn, true);
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, db_hash,
-                             sizeof(db_hash));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, db_hash, sizeof(db_hash));
 }
 
-static void clear_cf_cfg(struct gatt_cf_cfg *cfg)
-{
-    bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY);
-    memset(cfg->data, 0, sizeof(cfg->data));
-    atomic_set(cfg->flags, 0);
+static void clear_cf_cfg(struct gatt_cf_cfg *cfg) {
+  bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY);
+  memset(cfg->data, 0, sizeof(cfg->data));
+  atomic_set(cfg->flags, 0);
 }
 
-static void remove_cf_cfg(struct bt_conn *conn)
-{
-    struct gatt_cf_cfg *cfg;
-
-    cfg = find_cf_cfg(conn);
-    if (!cfg) {
-        return;
-    }
+static void remove_cf_cfg(struct bt_conn *conn) {
+  struct gatt_cf_cfg *cfg;
 
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2405:
-	 * For clients with a trusted relationship, the characteristic value
-	 * shall be persistent across connections. For clients without a
-	 * trusted relationship the characteristic value shall be set to the
-	 * default value at each connection.
-	 */
-    if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
-        clear_cf_cfg(cfg);
-    } else {
-        /* Update address in case it has changed */
-        bt_addr_le_copy(&cfg->peer, &conn->le.dst);
-    }
+  cfg = find_cf_cfg(conn);
+  if (!cfg) {
+    return;
+  }
+
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2405:
+   * For clients with a trusted relationship, the characteristic value
+   * shall be persistent across connections. For clients without a
+   * trusted relationship the characteristic value shall be set to the
+   * default value at each connection.
+   */
+  if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
+    clear_cf_cfg(cfg);
+  } else {
+    /* Update address in case it has changed */
+    bt_addr_le_copy(&cfg->peer, &conn->le.dst);
+  }
 }
 #endif /* CONFIG_BT_GATT_CACHING */
 
@@ -727,23 +647,17 @@ BT_GATT_SERVICE_DEFINE(_1_gatt_svc,
 
 #if defined(CONFIG_BT_GATT_SERVICE_CHANGED)
     /* Bluetooth 5.0, Vol3 Part G:
-	 * The Service Changed characteristic Attribute Handle on the server
-	 * shall not change if the server has a trusted relationship with any
-	 * client.
-	 */
-    BT_GATT_CHARACTERISTIC(BT_UUID_GATT_SC, BT_GATT_CHRC_INDICATE,
-                           BT_GATT_PERM_NONE, NULL, NULL, NULL),
+     * The Service Changed characteristic Attribute Handle on the server
+     * shall not change if the server has a trusted relationship with any
+     * client.
+     */
+    BT_GATT_CHARACTERISTIC(BT_UUID_GATT_SC, BT_GATT_CHRC_INDICATE, BT_GATT_PERM_NONE, NULL, NULL, NULL),
 
     BT_GATT_CCC_MANAGED(&sc_ccc, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),
 
 #if defined(CONFIG_BT_GATT_CACHING)
-    BT_GATT_CHARACTERISTIC(BT_UUID_GATT_CLIENT_FEATURES,
-                           BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
-                           BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
-                           cf_read, cf_write, NULL),
-    BT_GATT_CHARACTERISTIC(BT_UUID_GATT_DB_HASH,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           db_hash_read, NULL, NULL),
+    BT_GATT_CHARACTERISTIC(BT_UUID_GATT_CLIENT_FEATURES, BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, cf_read, cf_write, NULL),
+    BT_GATT_CHARACTERISTIC(BT_UUID_GATT_DB_HASH, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, db_hash_read, NULL, NULL),
 #endif /* CONFIG_BT_GATT_CACHING */
 #endif /* CONFIG_BT_GATT_SERVICE_CHANGED */
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
@@ -757,3233 +671,2902 @@ static struct bt_gatt_service gatt_svc = BT_GATT_SERVICE(gatt_attrs);
 #endif
 
 #if defined(CONFIG_BT_GATT_DYNAMIC_DB)
-static u8_t found_attr(const struct bt_gatt_attr *attr, void *user_data)
-{
-    const struct bt_gatt_attr **found = user_data;
+static u8_t found_attr(const struct bt_gatt_attr *attr, void *user_data) {
+  const struct bt_gatt_attr **found = user_data;
 
-    *found = attr;
+  *found = attr;
 
-    return BT_GATT_ITER_STOP;
+  return BT_GATT_ITER_STOP;
 }
 
-static const struct bt_gatt_attr *find_attr(uint16_t handle)
-{
-    const struct bt_gatt_attr *attr = NULL;
+static const struct bt_gatt_attr *find_attr(uint16_t handle) {
+  const struct bt_gatt_attr *attr = NULL;
 
-    bt_gatt_foreach_attr(handle, handle, found_attr, &attr);
+  bt_gatt_foreach_attr(handle, handle, found_attr, &attr);
 
-    return attr;
+  return attr;
 }
 
-static void gatt_insert(struct bt_gatt_service *svc, u16_t last_handle)
-{
-    struct bt_gatt_service *tmp, *prev = NULL;
-
-    if (last_handle == 0 || svc->attrs[0].handle > last_handle) {
-        sys_slist_append(&db, &svc->node);
-        return;
-    }
+static void gatt_insert(struct bt_gatt_service *svc, u16_t last_handle) {
+  struct bt_gatt_service *tmp, *prev = NULL;
 
-    /* DB shall always have its service in ascending order */
-    SYS_SLIST_FOR_EACH_CONTAINER(&db, tmp, node)
-    {
-        if (tmp->attrs[0].handle > svc->attrs[0].handle) {
-            if (prev) {
-                sys_slist_insert(&db, &prev->node, &svc->node);
-            } else {
-                sys_slist_prepend(&db, &svc->node);
-            }
-            return;
-        }
+  if (last_handle == 0 || svc->attrs[0].handle > last_handle) {
+    sys_slist_append(&db, &svc->node);
+    return;
+  }
 
-        prev = tmp;
+  /* DB shall always have its service in ascending order */
+  SYS_SLIST_FOR_EACH_CONTAINER(&db, tmp, node) {
+    if (tmp->attrs[0].handle > svc->attrs[0].handle) {
+      if (prev) {
+        sys_slist_insert(&db, &prev->node, &svc->node);
+      } else {
+        sys_slist_prepend(&db, &svc->node);
+      }
+      return;
     }
+
+    prev = tmp;
+  }
 }
 
-static int gatt_register(struct bt_gatt_service *svc)
-{
-    struct bt_gatt_service *last;
-    u16_t handle, last_handle;
-    struct bt_gatt_attr *attrs = svc->attrs;
-    u16_t count = svc->attr_count;
-
-    if (sys_slist_is_empty(&db)) {
-        handle = last_static_handle;
-        last_handle = 0;
-        goto populate;
-    }
+static int gatt_register(struct bt_gatt_service *svc) {
+  struct bt_gatt_service *last;
+  u16_t                   handle, last_handle;
+  struct bt_gatt_attr    *attrs = svc->attrs;
+  u16_t                   count = svc->attr_count;
 
-    last = SYS_SLIST_PEEK_TAIL_CONTAINER(&db, last, node);
-    handle = last->attrs[last->attr_count - 1].handle;
-    last_handle = handle;
+  if (sys_slist_is_empty(&db)) {
+    handle      = last_static_handle;
+    last_handle = 0;
+    goto populate;
+  }
 
-populate:
-    /* Populate the handles and append them to the list */
-    for (; attrs && count; attrs++, count--) {
-        if (!attrs->handle) {
-            /* Allocate handle if not set already */
-            attrs->handle = ++handle;
-        } else if (attrs->handle > handle) {
-            /* Use existing handle if valid */
-            handle = attrs->handle;
-        } else if (find_attr(attrs->handle)) {
-            /* Service has conflicting handles */
-            BT_ERR("Unable to register handle 0x%04x",
-                   attrs->handle);
-            return -EINVAL;
-        }
+  last        = SYS_SLIST_PEEK_TAIL_CONTAINER(&db, last, node);
+  handle      = last->attrs[last->attr_count - 1].handle;
+  last_handle = handle;
 
-        BT_DBG("attr %p handle 0x%04x uuid %s perm 0x%02x",
-               attrs, attrs->handle, bt_uuid_str(attrs->uuid),
-               attrs->perm);
+populate:
+  /* Populate the handles and append them to the list */
+  for (; attrs && count; attrs++, count--) {
+    if (!attrs->handle) {
+      /* Allocate handle if not set already */
+      attrs->handle = ++handle;
+    } else if (attrs->handle > handle) {
+      /* Use existing handle if valid */
+      handle = attrs->handle;
+    } else if (find_attr(attrs->handle)) {
+      /* Service has conflicting handles */
+      BT_ERR("Unable to register handle 0x%04x", attrs->handle);
+      return -EINVAL;
     }
 
-    gatt_insert(svc, last_handle);
+    BT_DBG("attr %p handle 0x%04x uuid %s perm 0x%02x", attrs, attrs->handle, bt_uuid_str(attrs->uuid), attrs->perm);
+  }
 
-    return 0;
+  gatt_insert(svc, last_handle);
+
+  return 0;
 }
 #endif /* CONFIG_BT_GATT_DYNAMIC_DB */
 
 enum {
-    SC_RANGE_CHANGED,    /* SC range changed */
-    SC_INDICATE_PENDING, /* SC indicate pending */
+  SC_RANGE_CHANGED,    /* SC range changed */
+  SC_INDICATE_PENDING, /* SC indicate pending */
 
-    /* Total number of flags - must be at the end of the enum */
-    SC_NUM_FLAGS,
+  /* Total number of flags - must be at the end of the enum */
+  SC_NUM_FLAGS,
 };
 
 static struct gatt_sc {
-    struct bt_gatt_indicate_params params;
-    u16_t start;
-    u16_t end;
-    struct k_delayed_work work;
-    ATOMIC_DEFINE(flags, SC_NUM_FLAGS);
+  struct bt_gatt_indicate_params params;
+  u16_t                          start;
+  u16_t                          end;
+  struct k_delayed_work          work;
+  ATOMIC_DEFINE(flags, SC_NUM_FLAGS);
 } gatt_sc;
 
-static void sc_indicate_rsp(struct bt_conn *conn,
-                            const struct bt_gatt_attr *attr, u8_t err)
-{
+static void sc_indicate_rsp(struct bt_conn *conn, const struct bt_gatt_attr *attr, u8_t err) {
 #if defined(CONFIG_BT_GATT_CACHING)
-    struct gatt_cf_cfg *cfg;
+  struct gatt_cf_cfg *cfg;
 #endif
 
-    BT_DBG("err 0x%02x", err);
+  BT_DBG("err 0x%02x", err);
 
-    atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING);
+  atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING);
 
-    /* Check if there is new change in the meantime */
-    if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) {
-        /* Reschedule without any delay since it is waiting already */
-        k_delayed_work_submit(&gatt_sc.work, K_NO_WAIT);
-    }
+  /* Check if there is new change in the meantime */
+  if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) {
+    /* Reschedule without any delay since it is waiting already */
+    k_delayed_work_submit(&gatt_sc.work, K_NO_WAIT);
+  }
 
 #if defined(CONFIG_BT_GATT_CACHING)
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
-	 * 2.5.2.1 Robust Caching
-	 * A connected client becomes change-aware when...
-	 * The client receives and confirms a Service Changed indication.
-	 */
-    cfg = find_cf_cfg(conn);
-    if (cfg && CF_ROBUST_CACHING(cfg)) {
-        atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
-        BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer));
-    }
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
+   * 2.5.2.1 Robust Caching
+   * A connected client becomes change-aware when...
+   * The client receives and confirms a Service Changed indication.
+   */
+  cfg = find_cf_cfg(conn);
+  if (cfg && CF_ROBUST_CACHING(cfg)) {
+    atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
+    BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer));
+  }
 #endif
 }
 
-static void sc_process(struct k_work *work)
-{
-    struct gatt_sc *sc = CONTAINER_OF(work, struct gatt_sc, work);
-    u16_t sc_range[2];
+static void sc_process(struct k_work *work) {
+  struct gatt_sc *sc = CONTAINER_OF(work, struct gatt_sc, work);
+  u16_t           sc_range[2];
 
-    __ASSERT(!atomic_test_bit(sc->flags, SC_INDICATE_PENDING),
-             "Indicate already pending");
+  __ASSERT(!atomic_test_bit(sc->flags, SC_INDICATE_PENDING), "Indicate already pending");
 
-    BT_DBG("start 0x%04x end 0x%04x", sc->start, sc->end);
+  BT_DBG("start 0x%04x end 0x%04x", sc->start, sc->end);
 
-    sc_range[0] = sys_cpu_to_le16(sc->start);
-    sc_range[1] = sys_cpu_to_le16(sc->end);
+  sc_range[0] = sys_cpu_to_le16(sc->start);
+  sc_range[1] = sys_cpu_to_le16(sc->end);
 
-    atomic_clear_bit(sc->flags, SC_RANGE_CHANGED);
-    sc->start = 0U;
-    sc->end = 0U;
+  atomic_clear_bit(sc->flags, SC_RANGE_CHANGED);
+  sc->start = 0U;
+  sc->end   = 0U;
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-    sc->params.attr = &gatt_attrs[2];
+  sc->params.attr = &gatt_attrs[2];
 #else
-    sc->params.attr = &_1_gatt_svc.attrs[2];
+  sc->params.attr = &_1_gatt_svc.attrs[2];
 #endif
-    sc->params.func = sc_indicate_rsp;
-    sc->params.data = &sc_range[0];
-    sc->params.len = sizeof(sc_range);
+  sc->params.func = sc_indicate_rsp;
+  sc->params.data = &sc_range[0];
+  sc->params.len  = sizeof(sc_range);
 
-    if (bt_gatt_indicate(NULL, &sc->params)) {
-        /* No connections to indicate */
-        return;
-    }
+  if (bt_gatt_indicate(NULL, &sc->params)) {
+    /* No connections to indicate */
+    return;
+  }
 
-    atomic_set_bit(sc->flags, SC_INDICATE_PENDING);
+  atomic_set_bit(sc->flags, SC_INDICATE_PENDING);
 }
 
 #if defined(CONFIG_BT_STACK_PTS)
-int service_change_test(struct bt_gatt_indicate_params *params, const struct bt_conn *con)
-{
-    u16_t sc_range[2];
+int service_change_test(struct bt_gatt_indicate_params *params, const struct bt_conn *con) {
+  u16_t sc_range[2];
 
-    if (!params->attr) {
+  if (!params->attr) {
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-        params->attr = &gatt_attrs[2];
+    params->attr = &gatt_attrs[2];
 #else
-        params->attr = &_1_gatt_svc.attrs[2];
+    params->attr = &_1_gatt_svc.attrs[2];
 #endif
-    }
-    sc_range[0] = 0x000e;
-    sc_range[1] = 0x001e;
+  }
+  sc_range[0] = 0x000e;
+  sc_range[1] = 0x001e;
 
-    params->data = &sc_range[0];
-    params->len = sizeof(sc_range);
+  params->data = &sc_range[0];
+  params->len  = sizeof(sc_range);
 
-    if (bt_gatt_indicate(con, params)) {
-        /* No connections to indicate */
-        return;
-    }
+  if (bt_gatt_indicate(con, params)) {
+    /* No connections to indicate */
+    return;
+  }
 }
 #endif
 
 #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE)
 static struct gatt_ccc_store {
-    struct bt_conn *conn_list[CONFIG_BT_MAX_CONN];
-    struct k_delayed_work work;
+  struct bt_conn       *conn_list[CONFIG_BT_MAX_CONN];
+  struct k_delayed_work work;
 } gatt_ccc_store;
 
-static bool gatt_ccc_conn_is_queued(struct bt_conn *conn)
-{
-    return (conn == gatt_ccc_store.conn_list[bt_conn_index(conn)]);
-}
+static bool gatt_ccc_conn_is_queued(struct bt_conn *conn) { return (conn == gatt_ccc_store.conn_list[bt_conn_index(conn)]); }
 
-static void gatt_ccc_conn_unqueue(struct bt_conn *conn)
-{
-    u8_t index = bt_conn_index(conn);
+static void gatt_ccc_conn_unqueue(struct bt_conn *conn) {
+  u8_t index = bt_conn_index(conn);
 
-    if (gatt_ccc_store.conn_list[index] != NULL) {
-        bt_conn_unref(gatt_ccc_store.conn_list[index]);
-        gatt_ccc_store.conn_list[index] = NULL;
-    }
+  if (gatt_ccc_store.conn_list[index] != NULL) {
+    bt_conn_unref(gatt_ccc_store.conn_list[index]);
+    gatt_ccc_store.conn_list[index] = NULL;
+  }
 }
 
-static bool gatt_ccc_conn_queue_is_empty(void)
-{
-    for (size_t i = 0; i < CONFIG_BT_MAX_CONN; i++) {
-        if (gatt_ccc_store.conn_list[i]) {
-            return false;
-        }
+static bool gatt_ccc_conn_queue_is_empty(void) {
+  for (size_t i = 0; i < CONFIG_BT_MAX_CONN; i++) {
+    if (gatt_ccc_store.conn_list[i]) {
+      return false;
     }
+  }
 
-    return true;
+  return true;
 }
 
-static void ccc_delayed_store(struct k_work *work)
-{
-    struct gatt_ccc_store *ccc_store =
-        CONTAINER_OF(work, struct gatt_ccc_store, work);
+static void ccc_delayed_store(struct k_work *work) {
+  struct gatt_ccc_store *ccc_store = CONTAINER_OF(work, struct gatt_ccc_store, work);
 
-    for (size_t i = 0; i < CONFIG_BT_MAX_CONN; i++) {
-        struct bt_conn *conn = ccc_store->conn_list[i];
+  for (size_t i = 0; i < CONFIG_BT_MAX_CONN; i++) {
+    struct bt_conn *conn = ccc_store->conn_list[i];
 
-        if (!conn) {
-            continue;
-        }
+    if (!conn) {
+      continue;
+    }
 
-        if (bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
-            bt_gatt_store_ccc(conn->id, &conn->le.dst);
-            bt_conn_unref(conn);
-            ccc_store->conn_list[i] = NULL;
-        }
+    if (bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
+      bt_gatt_store_ccc(conn->id, &conn->le.dst);
+      bt_conn_unref(conn);
+      ccc_store->conn_list[i] = NULL;
     }
+  }
 }
 #endif
 
-void bt_gatt_init(void)
-{
-    if (!atomic_cas(&init, 0, 1)) {
-        return;
-    }
+void bt_gatt_init(void) {
+  if (!atomic_cas(&init, 0, 1)) {
+    return;
+  }
 
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-    /* Register mandatory services */
-    gatt_register(&gap_svc);
-    gatt_register(&gatt_svc);
+  /* Register mandatory services */
+  gatt_register(&gap_svc);
+  gatt_register(&gatt_svc);
 
 #else
-    Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, svc)
-    {
-        last_static_handle += svc->attr_count;
-    }
+  Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, svc) { last_static_handle += svc->attr_count; }
 #endif
 
 #if defined(CONFIG_BT_GATT_CACHING)
-    k_delayed_work_init(&db_hash_work, db_hash_process);
+  k_delayed_work_init(&db_hash_work, db_hash_process);
 
-    /* Submit work to Generate initial hash as there could be static
-	 * services already in the database.
-	 */
-    k_delayed_work_submit(&db_hash_work, DB_HASH_TIMEOUT);
+  /* Submit work to Generate initial hash as there could be static
+   * services already in the database.
+   */
+  k_delayed_work_submit(&db_hash_work, DB_HASH_TIMEOUT);
 #endif /* CONFIG_BT_GATT_CACHING */
 
-    if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) {
-        k_delayed_work_init(&gatt_sc.work, sc_process);
-        if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-            /* Make sure to not send SC indications until SC
-			 * settings are loaded
-			 */
-            atomic_set_bit(gatt_sc.flags, SC_INDICATE_PENDING);
-        }
+  if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) {
+    k_delayed_work_init(&gatt_sc.work, sc_process);
+    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+      /* Make sure to not send SC indications until SC
+       * settings are loaded
+       */
+      atomic_set_bit(gatt_sc.flags, SC_INDICATE_PENDING);
     }
+  }
 
 #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE)
-    k_delayed_work_init(&gatt_ccc_store.work, ccc_delayed_store);
+  k_delayed_work_init(&gatt_ccc_store.work, ccc_delayed_store);
 #endif
 }
 
 #if defined(BFLB_BLE)
-void bt_gatt_deinit(void)
-{
+void bt_gatt_deinit(void) {
 #if defined(CONFIG_BT_GATT_CACHING)
-    k_delayed_work_del_timer(&db_hash_work);
+  k_delayed_work_del_timer(&db_hash_work);
 #endif
 
-    if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) {
-        k_delayed_work_del_timer(&gatt_sc.work);
-    }
+  if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) {
+    k_delayed_work_del_timer(&gatt_sc.work);
+  }
 
 #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE)
-    k_delayed_work_del_timer(&gatt_ccc_store.work);
+  k_delayed_work_del_timer(&gatt_ccc_store.work);
 #endif
 }
 #endif
 
-#if defined(CONFIG_BT_GATT_DYNAMIC_DB) || \
-    (defined(CONFIG_BT_GATT_CACHING) && defined(CONFIG_BT_SETTINGS))
-static void sc_indicate(u16_t start, u16_t end)
-{
-    BT_DBG("start 0x%04x end 0x%04x", start, end);
+#if defined(CONFIG_BT_GATT_DYNAMIC_DB) || (defined(CONFIG_BT_GATT_CACHING) && defined(CONFIG_BT_SETTINGS))
+static void sc_indicate(u16_t start, u16_t end) {
+  BT_DBG("start 0x%04x end 0x%04x", start, end);
 
 #if defined(BFLB_BLE_PATCH_SET_SCRANGE_CHAGD_ONLY_IN_CONNECTED_STATE)
-    struct bt_conn *conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECTED);
-    if (conn) {
+  struct bt_conn *conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECTED);
+  if (conn) {
 #endif
-        if (!atomic_test_and_set_bit(gatt_sc.flags, SC_RANGE_CHANGED)) {
-            gatt_sc.start = start;
-            gatt_sc.end = end;
-            goto submit;
-        }
-#if defined(BFLB_BLE_PATCH_SET_SCRANGE_CHAGD_ONLY_IN_CONNECTED_STATE)
+    if (!atomic_test_and_set_bit(gatt_sc.flags, SC_RANGE_CHANGED)) {
+      gatt_sc.start = start;
+      gatt_sc.end   = end;
+      goto submit;
     }
+#if defined(BFLB_BLE_PATCH_SET_SCRANGE_CHAGD_ONLY_IN_CONNECTED_STATE)
+  }
 #endif
 
-    if (!update_range(&gatt_sc.start, &gatt_sc.end, start, end)) {
-        return;
-    }
+  if (!update_range(&gatt_sc.start, &gatt_sc.end, start, end)) {
+    return;
+  }
 
 submit:
-    if (atomic_test_bit(gatt_sc.flags, SC_INDICATE_PENDING)) {
-        BT_DBG("indicate pending, waiting until complete...");
-        return;
-    }
+  if (atomic_test_bit(gatt_sc.flags, SC_INDICATE_PENDING)) {
+    BT_DBG("indicate pending, waiting until complete...");
+    return;
+  }
 
 #if defined(BFLB_BLE_PATCH_SET_SCRANGE_CHAGD_ONLY_IN_CONNECTED_STATE)
-    if (conn) {
+  if (conn) {
 #endif
-        /* Reschedule since the range has changed */
-        k_delayed_work_submit(&gatt_sc.work, SC_TIMEOUT);
+    /* Reschedule since the range has changed */
+    k_delayed_work_submit(&gatt_sc.work, SC_TIMEOUT);
 #if defined(BFLB_BLE_PATCH_SET_SCRANGE_CHAGD_ONLY_IN_CONNECTED_STATE)
-        bt_conn_unref(conn);
-    }
+    bt_conn_unref(conn);
+  }
 #endif
 }
 #endif /* BT_GATT_DYNAMIC_DB || (BT_GATT_CACHING && BT_SETTINGS) */
 
 #if defined(CONFIG_BT_GATT_DYNAMIC_DB)
-static void db_changed(void)
-{
+static void db_changed(void) {
 #if defined(CONFIG_BT_GATT_CACHING)
-    int i;
+  int i;
 
-    k_delayed_work_submit(&db_hash_work, DB_HASH_TIMEOUT);
+  k_delayed_work_submit(&db_hash_work, DB_HASH_TIMEOUT);
 
-    for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
-        struct gatt_cf_cfg *cfg = &cf_cfg[i];
+  for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
+    struct gatt_cf_cfg *cfg = &cf_cfg[i];
 
-        if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) {
-            continue;
-        }
+    if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) {
+      continue;
+    }
 
-        if (CF_ROBUST_CACHING(cfg)) {
-            /* Core Spec 5.1 | Vol 3, Part G, 2.5.2.1 Robust Caching
-			 *... the database changes again before the client
-			 * becomes change-aware in which case the error response
-			 * shall be sent again.
-			 */
-            atomic_clear_bit(cfg->flags, CF_OUT_OF_SYNC);
-            if (atomic_test_and_clear_bit(cfg->flags,
-                                          CF_CHANGE_AWARE)) {
-                BT_DBG("%s change-unaware",
-                       bt_addr_le_str(&cfg->peer));
-            }
-        }
+    if (CF_ROBUST_CACHING(cfg)) {
+      /* Core Spec 5.1 | Vol 3, Part G, 2.5.2.1 Robust Caching
+       *... the database changes again before the client
+       * becomes change-aware in which case the error response
+       * shall be sent again.
+       */
+      atomic_clear_bit(cfg->flags, CF_OUT_OF_SYNC);
+      if (atomic_test_and_clear_bit(cfg->flags, CF_CHANGE_AWARE)) {
+        BT_DBG("%s change-unaware", bt_addr_le_str(&cfg->peer));
+      }
     }
+  }
 #endif
 }
 
-int bt_gatt_service_register(struct bt_gatt_service *svc)
-{
-    int err;
+int bt_gatt_service_register(struct bt_gatt_service *svc) {
+  int err;
 
-    __ASSERT(svc, "invalid parameters\n");
-    __ASSERT(svc->attrs, "invalid parameters\n");
-    __ASSERT(svc->attr_count, "invalid parameters\n");
+  __ASSERT(svc, "invalid parameters\n");
+  __ASSERT(svc->attrs, "invalid parameters\n");
+  __ASSERT(svc->attr_count, "invalid parameters\n");
 
-    /* Init GATT core services */
-    bt_gatt_init();
+  /* Init GATT core services */
+  bt_gatt_init();
 
-    /* Do no allow to register mandatory services twice */
-    if (!bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GAP) ||
-        !bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GATT)) {
-        return -EALREADY;
-    }
+  /* Do no allow to register mandatory services twice */
+  if (!bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GAP) || !bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GATT)) {
+    return -EALREADY;
+  }
 
-    err = gatt_register(svc);
-    if (err < 0) {
-        return err;
-    }
+  err = gatt_register(svc);
+  if (err < 0) {
+    return err;
+  }
 
-    sc_indicate(svc->attrs[0].handle,
-                svc->attrs[svc->attr_count - 1].handle);
+  sc_indicate(svc->attrs[0].handle, svc->attrs[svc->attr_count - 1].handle);
 
-    db_changed();
+  db_changed();
 
-    return 0;
+  return 0;
 }
 
-int bt_gatt_service_unregister(struct bt_gatt_service *svc)
-{
-    __ASSERT(svc, "invalid parameters\n");
+int bt_gatt_service_unregister(struct bt_gatt_service *svc) {
+  __ASSERT(svc, "invalid parameters\n");
 
-    if (!sys_slist_find_and_remove(&db, &svc->node)) {
-        return -ENOENT;
-    }
+  if (!sys_slist_find_and_remove(&db, &svc->node)) {
+    return -ENOENT;
+  }
 
-    sc_indicate(svc->attrs[0].handle,
-                svc->attrs[svc->attr_count - 1].handle);
+  sc_indicate(svc->attrs[0].handle, svc->attrs[svc->attr_count - 1].handle);
 
-    db_changed();
+  db_changed();
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_BT_GATT_DYNAMIC_DB */
 
-ssize_t bt_gatt_attr_read(struct bt_conn *conn, const struct bt_gatt_attr *attr,
-                          void *buf, u16_t buf_len, u16_t offset,
-                          const void *value, u16_t value_len)
-{
-    u16_t len;
+ssize_t bt_gatt_attr_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t buf_len, u16_t offset, const void *value, u16_t value_len) {
+  u16_t len;
 #if defined(CONFIG_BT_STACK_PTS)
-    u8_t *data = NULL;
-    u8_t i = 0;
+  u8_t *data = NULL;
+  u8_t  i    = 0;
 #endif
 
-    if (offset > value_len) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
-    }
+  if (offset > value_len) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
+  }
 
-    len = MIN(buf_len, value_len - offset);
+  len = MIN(buf_len, value_len - offset);
 
-    BT_DBG("handle 0x%04x offset %u length %u", attr->handle, offset,
-           len);
+  BT_DBG("handle 0x%04x offset %u length %u", attr->handle, offset, len);
 
-    memcpy(buf, (u8_t *)value + offset, len);
+  memcpy(buf, (u8_t *)value + offset, len);
 
 #if defined(CONFIG_BT_STACK_PTS)
-    /* PTS sends a request to iut read all primary services it contains.
-	 * Set event flags to avoid comflicts when other test cases need to add reference codes. 
-	 */
-    if (event_flag == att_read_by_group_type_ind) {
-        data = (u8_t *)buf;
-        for (i = 0; i < len; i++) {
-            BT_PTS("%s:handle = [0x%04x], data[%d] = [0x%x]\r\n", __func__,
-                   attr->handle, i, data[i]);
-        }
-    }
+  /* PTS sends a request to iut read all primary services it contains.
+   * Set event flags to avoid comflicts when other test cases need to add reference codes.
+   */
+  if (event_flag == att_read_by_group_type_ind) {
+    data = (u8_t *)buf;
+    for (i = 0; i < len; i++) {
+      BT_PTS("%s:handle = [0x%04x], data[%d] = [0x%x]\r\n", __func__, attr->handle, i, data[i]);
+    }
+  }
 #endif
 
-    return len;
+  return len;
 }
 
-ssize_t bt_gatt_attr_read_service(struct bt_conn *conn,
-                                  const struct bt_gatt_attr *attr,
-                                  void *buf, u16_t len, u16_t offset)
-{
-    struct bt_uuid *uuid = attr->user_data;
+ssize_t bt_gatt_attr_read_service(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  struct bt_uuid *uuid = attr->user_data;
 
-    if (uuid->type == BT_UUID_TYPE_16) {
-        u16_t uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
+  if (uuid->type == BT_UUID_TYPE_16) {
+    u16_t uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
 
-        return bt_gatt_attr_read(conn, attr, buf, len, offset,
-                                 &uuid16, 2);
-    }
+    return bt_gatt_attr_read(conn, attr, buf, len, offset, &uuid16, 2);
+  }
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset,
-                             BT_UUID_128(uuid)->val, 16);
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, BT_UUID_128(uuid)->val, 16);
 }
 
 struct gatt_incl {
-    u16_t start_handle;
-    u16_t end_handle;
-    u16_t uuid16;
+  u16_t start_handle;
+  u16_t end_handle;
+  u16_t uuid16;
 } __packed;
 
-static u8_t get_service_handles(const struct bt_gatt_attr *attr,
-                                void *user_data)
-{
-    struct gatt_incl *include = user_data;
+static u8_t get_service_handles(const struct bt_gatt_attr *attr, void *user_data) {
+  struct gatt_incl *include = user_data;
 
-    /* Stop if attribute is a service */
-    if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) ||
-        !bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) {
-        return BT_GATT_ITER_STOP;
-    }
+  /* Stop if attribute is a service */
+  if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) || !bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    include->end_handle = attr->handle;
+  include->end_handle = attr->handle;
 
-    return BT_GATT_ITER_CONTINUE;
+  return BT_GATT_ITER_CONTINUE;
 }
 
 #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-static u16_t find_static_attr(const struct bt_gatt_attr *attr)
-{
-    u16_t handle = 1;
+static u16_t find_static_attr(const struct bt_gatt_attr *attr) {
+  u16_t handle = 1;
 
-    Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc)
-    {
-        for (int i = 0; i < static_svc->attr_count; i++, handle++) {
-            if (attr == &static_svc->attrs[i]) {
-                return handle;
-            }
-        }
+  Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc) {
+    for (int i = 0; i < static_svc->attr_count; i++, handle++) {
+      if (attr == &static_svc->attrs[i]) {
+        return handle;
+      }
     }
+  }
 
-    return 0;
+  return 0;
 }
 #endif
 
-ssize_t bt_gatt_attr_read_included(struct bt_conn *conn,
-                                   const struct bt_gatt_attr *attr,
-                                   void *buf, u16_t len, u16_t offset)
-{
-    struct bt_gatt_attr *incl = attr->user_data;
+ssize_t bt_gatt_attr_read_included(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  struct bt_gatt_attr *incl = attr->user_data;
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-    u16_t handle = incl->handle;
+  u16_t handle = incl->handle;
 #else
-    u16_t handle = incl->handle ?: find_static_attr(incl);
+  u16_t handle = incl->handle ?: find_static_attr(incl);
 #endif
-    struct bt_uuid *uuid = incl->user_data;
-    struct gatt_incl pdu;
-    u8_t value_len;
-
-    /* first attr points to the start handle */
-    pdu.start_handle = sys_cpu_to_le16(handle);
-    value_len = sizeof(pdu.start_handle) + sizeof(pdu.end_handle);
-
-    /*
-	 * Core 4.2, Vol 3, Part G, 3.2,
-	 * The Service UUID shall only be present when the UUID is a
-	 * 16-bit Bluetooth UUID.
-	 */
-    if (uuid->type == BT_UUID_TYPE_16) {
-        pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
-        value_len += sizeof(pdu.uuid16);
-    }
+  struct bt_uuid  *uuid = incl->user_data;
+  struct gatt_incl pdu;
+  u8_t             value_len;
+
+  /* first attr points to the start handle */
+  pdu.start_handle = sys_cpu_to_le16(handle);
+  value_len        = sizeof(pdu.start_handle) + sizeof(pdu.end_handle);
+
+  /*
+   * Core 4.2, Vol 3, Part G, 3.2,
+   * The Service UUID shall only be present when the UUID is a
+   * 16-bit Bluetooth UUID.
+   */
+  if (uuid->type == BT_UUID_TYPE_16) {
+    pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
+    value_len += sizeof(pdu.uuid16);
+  }
 
-    /* Lookup for service end handle */
-    bt_gatt_foreach_attr(handle + 1, 0xffff, get_service_handles, &pdu);
+  /* Lookup for service end handle */
+  bt_gatt_foreach_attr(handle + 1, 0xffff, get_service_handles, &pdu);
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len);
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len);
 }
 
 struct gatt_chrc {
-    u8_t properties;
-    u16_t value_handle;
-    union {
-        u16_t uuid16;
-        u8_t uuid[16];
-    };
+  u8_t  properties;
+  u16_t value_handle;
+  union {
+    u16_t uuid16;
+    u8_t  uuid[16];
+  };
 } __packed;
 
-uint16_t bt_gatt_attr_value_handle(const struct bt_gatt_attr *attr)
-{
-    u16_t handle = 0;
+uint16_t bt_gatt_attr_value_handle(const struct bt_gatt_attr *attr) {
+  u16_t handle = 0;
 
-    if ((attr != NULL) && (attr->read == bt_gatt_attr_read_chrc)) {
-        struct bt_gatt_chrc *chrc = attr->user_data;
+  if ((attr != NULL) && (attr->read == bt_gatt_attr_read_chrc)) {
+    struct bt_gatt_chrc *chrc = attr->user_data;
 
-        handle = chrc->value_handle;
+    handle = chrc->value_handle;
 #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-        if (handle == 0) {
-            /* Fall back to Zephyr value handle policy */
-            handle = (attr->handle ?: find_static_attr(attr)) + 1U;
-        }
-#endif
+    if (handle == 0) {
+      /* Fall back to Zephyr value handle policy */
+      handle = (attr->handle ?: find_static_attr(attr)) + 1U;
     }
+#endif
+  }
 
-    return handle;
+  return handle;
 }
 
-ssize_t bt_gatt_attr_read_chrc(struct bt_conn *conn,
-                               const struct bt_gatt_attr *attr, void *buf,
-                               u16_t len, u16_t offset)
-{
-    struct bt_gatt_chrc *chrc = attr->user_data;
-    struct gatt_chrc pdu;
-    u8_t value_len;
-
-    pdu.properties = chrc->properties;
-    /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 534:
-	 * 3.3.2 Characteristic Value Declaration
-	 * The Characteristic Value declaration contains the value of the
-	 * characteristic. It is the first Attribute after the characteristic
-	 * declaration. All characteristic definitions shall have a
-	 * Characteristic Value declaration.
-	 */
-    pdu.value_handle = sys_cpu_to_le16(bt_gatt_attr_value_handle(attr));
-
-    value_len = sizeof(pdu.properties) + sizeof(pdu.value_handle);
-
-    if (chrc->uuid->type == BT_UUID_TYPE_16) {
-        pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(chrc->uuid)->val);
-        value_len += 2U;
-    } else {
-        memcpy(pdu.uuid, BT_UUID_128(chrc->uuid)->val, 16);
-        value_len += 16U;
-    }
+ssize_t bt_gatt_attr_read_chrc(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  struct bt_gatt_chrc *chrc = attr->user_data;
+  struct gatt_chrc     pdu;
+  u8_t                 value_len;
+
+  pdu.properties = chrc->properties;
+  /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 534:
+   * 3.3.2 Characteristic Value Declaration
+   * The Characteristic Value declaration contains the value of the
+   * characteristic. It is the first Attribute after the characteristic
+   * declaration. All characteristic definitions shall have a
+   * Characteristic Value declaration.
+   */
+  pdu.value_handle = sys_cpu_to_le16(bt_gatt_attr_value_handle(attr));
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len);
+  value_len = sizeof(pdu.properties) + sizeof(pdu.value_handle);
+
+  if (chrc->uuid->type == BT_UUID_TYPE_16) {
+    pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(chrc->uuid)->val);
+    value_len += 2U;
+  } else {
+    memcpy(pdu.uuid, BT_UUID_128(chrc->uuid)->val, 16);
+    value_len += 16U;
+  }
+
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len);
 }
 
-static u8_t gatt_foreach_iter(const struct bt_gatt_attr *attr,
-                              u16_t start_handle, u16_t end_handle,
-                              const struct bt_uuid *uuid,
-                              const void *attr_data, uint16_t *num_matches,
-                              bt_gatt_attr_func_t func, void *user_data)
-{
-    u8_t result;
+static u8_t gatt_foreach_iter(const struct bt_gatt_attr *attr, u16_t start_handle, u16_t end_handle, const struct bt_uuid *uuid, const void *attr_data, uint16_t *num_matches, bt_gatt_attr_func_t func,
+                              void *user_data) {
+  u8_t result;
 
-    /* Stop if over the requested range */
-    if (attr->handle > end_handle) {
-        return BT_GATT_ITER_STOP;
-    }
+  /* Stop if over the requested range */
+  if (attr->handle > end_handle) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    /* Check if attribute handle is within range */
-    if (attr->handle < start_handle) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  /* Check if attribute handle is within range */
+  if (attr->handle < start_handle) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    /* Match attribute UUID if set */
-    if (uuid && bt_uuid_cmp(uuid, attr->uuid)) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  /* Match attribute UUID if set */
+  if (uuid && bt_uuid_cmp(uuid, attr->uuid)) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    /* Match attribute user_data if set */
-    if (attr_data && attr_data != attr->user_data) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  /* Match attribute user_data if set */
+  if (attr_data && attr_data != attr->user_data) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    *num_matches -= 1;
+  *num_matches -= 1;
 
-    result = func(attr, user_data);
+  result = func(attr, user_data);
 
-    if (!*num_matches) {
-        return BT_GATT_ITER_STOP;
-    }
+  if (!*num_matches) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    return result;
+  return result;
 }
 
-static void foreach_attr_type_dyndb(u16_t start_handle, u16_t end_handle,
-                                    const struct bt_uuid *uuid,
-                                    const void *attr_data, uint16_t num_matches,
-                                    bt_gatt_attr_func_t func, void *user_data)
-{
+static void foreach_attr_type_dyndb(u16_t start_handle, u16_t end_handle, const struct bt_uuid *uuid, const void *attr_data, uint16_t num_matches, bt_gatt_attr_func_t func, void *user_data) {
 #if defined(CONFIG_BT_GATT_DYNAMIC_DB)
-    int i;
+  int i;
 
-    struct bt_gatt_service *svc;
+  struct bt_gatt_service *svc;
 
-    SYS_SLIST_FOR_EACH_CONTAINER(&db, svc, node)
-    {
-        struct bt_gatt_service *next;
+  SYS_SLIST_FOR_EACH_CONTAINER(&db, svc, node) {
+    struct bt_gatt_service *next;
 
-        next = SYS_SLIST_PEEK_NEXT_CONTAINER(svc, node);
-        if (next) {
-            /* Skip ahead if start is not within service handles */
-            if (next->attrs[0].handle <= start_handle) {
-                continue;
-            }
-        }
+    next = SYS_SLIST_PEEK_NEXT_CONTAINER(svc, node);
+    if (next) {
+      /* Skip ahead if start is not within service handles */
+      if (next->attrs[0].handle <= start_handle) {
+        continue;
+      }
+    }
 
-        for (i = 0; i < svc->attr_count; i++) {
-            struct bt_gatt_attr *attr = &svc->attrs[i];
-
-            if (gatt_foreach_iter(attr,
-                                  start_handle,
-                                  end_handle,
-                                  uuid, attr_data,
-                                  &num_matches,
-                                  func, user_data) ==
-                BT_GATT_ITER_STOP) {
-                return;
-            }
-        }
+    for (i = 0; i < svc->attr_count; i++) {
+      struct bt_gatt_attr *attr = &svc->attrs[i];
+
+      if (gatt_foreach_iter(attr, start_handle, end_handle, uuid, attr_data, &num_matches, func, user_data) == BT_GATT_ITER_STOP) {
+        return;
+      }
     }
+  }
 #endif /* CONFIG_BT_GATT_DYNAMIC_DB */
 }
 
-void bt_gatt_foreach_attr_type(u16_t start_handle, u16_t end_handle,
-                               const struct bt_uuid *uuid,
-                               const void *attr_data, uint16_t num_matches,
-                               bt_gatt_attr_func_t func, void *user_data)
-{
-    int i;
+void bt_gatt_foreach_attr_type(u16_t start_handle, u16_t end_handle, const struct bt_uuid *uuid, const void *attr_data, uint16_t num_matches, bt_gatt_attr_func_t func, void *user_data) {
+  int i;
 
-    if (!num_matches) {
-        num_matches = UINT16_MAX;
-    }
+  if (!num_matches) {
+    num_matches = UINT16_MAX;
+  }
 #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-    if (start_handle <= last_static_handle) {
-        u16_t handle = 1;
-
-        Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc)
-        {
-            /* Skip ahead if start is not within service handles */
-            if (handle + static_svc->attr_count < start_handle) {
-                handle += static_svc->attr_count;
-                continue;
-            }
-
-            for (i = 0; i < static_svc->attr_count; i++, handle++) {
-                struct bt_gatt_attr attr;
-
-                memcpy(&attr, &static_svc->attrs[i],
-                       sizeof(attr));
-
-                attr.handle = handle;
-
-                if (gatt_foreach_iter(&attr, start_handle,
-                                      end_handle, uuid,
-                                      attr_data, &num_matches,
-                                      func, user_data) ==
-                    BT_GATT_ITER_STOP) {
-                    return;
-                }
-            }
+  if (start_handle <= last_static_handle) {
+    u16_t handle = 1;
+
+    Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc) {
+      /* Skip ahead if start is not within service handles */
+      if (handle + static_svc->attr_count < start_handle) {
+        handle += static_svc->attr_count;
+        continue;
+      }
+
+      for (i = 0; i < static_svc->attr_count; i++, handle++) {
+        struct bt_gatt_attr attr;
+
+        memcpy(&attr, &static_svc->attrs[i], sizeof(attr));
+
+        attr.handle = handle;
+
+        if (gatt_foreach_iter(&attr, start_handle, end_handle, uuid, attr_data, &num_matches, func, user_data) == BT_GATT_ITER_STOP) {
+          return;
         }
+      }
     }
+  }
 #endif
-    /* Iterate over dynamic db */
-    foreach_attr_type_dyndb(start_handle, end_handle, uuid, attr_data,
-                            num_matches, func, user_data);
+  /* Iterate over dynamic db */
+  foreach_attr_type_dyndb(start_handle, end_handle, uuid, attr_data, num_matches, func, user_data);
 }
 
-static u8_t find_next(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct bt_gatt_attr **next = user_data;
+static u8_t find_next(const struct bt_gatt_attr *attr, void *user_data) {
+  struct bt_gatt_attr **next = user_data;
 
-    *next = (struct bt_gatt_attr *)attr;
+  *next = (struct bt_gatt_attr *)attr;
 
-    return BT_GATT_ITER_STOP;
+  return BT_GATT_ITER_STOP;
 }
 
-struct bt_gatt_attr *bt_gatt_attr_next(const struct bt_gatt_attr *attr)
-{
-    struct bt_gatt_attr *next = NULL;
+struct bt_gatt_attr *bt_gatt_attr_next(const struct bt_gatt_attr *attr) {
+  struct bt_gatt_attr *next = NULL;
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-    u16_t handle = attr->handle;
+  u16_t handle = attr->handle;
 #else
-    u16_t handle = attr->handle ?: find_static_attr(attr);
+  u16_t handle = attr->handle ?: find_static_attr(attr);
 #endif
-    bt_gatt_foreach_attr(handle + 1, handle + 1, find_next, &next);
+  bt_gatt_foreach_attr(handle + 1, handle + 1, find_next, &next);
 
-    return next;
+  return next;
 }
 
-static void clear_ccc_cfg(struct bt_gatt_ccc_cfg *cfg)
-{
-    bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY);
-    cfg->id = 0U;
-    cfg->value = 0U;
+static void clear_ccc_cfg(struct bt_gatt_ccc_cfg *cfg) {
+  bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY);
+  cfg->id    = 0U;
+  cfg->value = 0U;
 }
 
-static struct bt_gatt_ccc_cfg *find_ccc_cfg(const struct bt_conn *conn,
-                                            struct _bt_gatt_ccc *ccc)
-{
-    for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
-        if (conn) {
-            if (conn->id == ccc->cfg[i].id &&
-                !bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer)) {
-                return &ccc->cfg[i];
-            }
-        } else if (!bt_addr_le_cmp(&ccc->cfg[i].peer, BT_ADDR_LE_ANY)) {
-            return &ccc->cfg[i];
-        }
+static struct bt_gatt_ccc_cfg *find_ccc_cfg(const struct bt_conn *conn, struct _bt_gatt_ccc *ccc) {
+  for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
+    if (conn) {
+      if (conn->id == ccc->cfg[i].id && !bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer)) {
+        return &ccc->cfg[i];
+      }
+    } else if (!bt_addr_le_cmp(&ccc->cfg[i].peer, BT_ADDR_LE_ANY)) {
+      return &ccc->cfg[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-ssize_t bt_gatt_attr_read_ccc(struct bt_conn *conn,
-                              const struct bt_gatt_attr *attr, void *buf,
-                              u16_t len, u16_t offset)
-{
-    struct _bt_gatt_ccc *ccc = attr->user_data;
-    const struct bt_gatt_ccc_cfg *cfg;
-    u16_t value;
+ssize_t bt_gatt_attr_read_ccc(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  struct _bt_gatt_ccc          *ccc = attr->user_data;
+  const struct bt_gatt_ccc_cfg *cfg;
+  u16_t                         value;
 
-    cfg = find_ccc_cfg(conn, ccc);
-    if (cfg) {
-        value = sys_cpu_to_le16(cfg->value);
-    } else {
-        /* Default to disable if there is no cfg for the peer */
-        value = 0x0000;
-    }
+  cfg = find_ccc_cfg(conn, ccc);
+  if (cfg) {
+    value = sys_cpu_to_le16(cfg->value);
+  } else {
+    /* Default to disable if there is no cfg for the peer */
+    value = 0x0000;
+  }
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &value,
-                             sizeof(value));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &value, sizeof(value));
 }
 
-static void gatt_ccc_changed(const struct bt_gatt_attr *attr,
-                             struct _bt_gatt_ccc *ccc)
-{
-    int i;
-    u16_t value = 0x0000;
+static void gatt_ccc_changed(const struct bt_gatt_attr *attr, struct _bt_gatt_ccc *ccc) {
+  int   i;
+  u16_t value = 0x0000;
 
-    for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
-        if (ccc->cfg[i].value > value) {
-            value = ccc->cfg[i].value;
-        }
+  for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
+    if (ccc->cfg[i].value > value) {
+      value = ccc->cfg[i].value;
     }
+  }
 
-    BT_DBG("ccc %p value 0x%04x", ccc, value);
+  BT_DBG("ccc %p value 0x%04x", ccc, value);
 
-    if (value != ccc->value) {
-        ccc->value = value;
-        if (ccc->cfg_changed) {
-            ccc->cfg_changed(attr, value);
-        }
+  if (value != ccc->value) {
+    ccc->value = value;
+    if (ccc->cfg_changed) {
+      ccc->cfg_changed(attr, value);
     }
+  }
 }
 
-ssize_t bt_gatt_attr_write_ccc(struct bt_conn *conn,
-                               const struct bt_gatt_attr *attr, const void *buf,
-                               u16_t len, u16_t offset, u8_t flags)
-{
-    struct _bt_gatt_ccc *ccc = attr->user_data;
-    struct bt_gatt_ccc_cfg *cfg;
-    u16_t value;
+ssize_t bt_gatt_attr_write_ccc(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len, u16_t offset, u8_t flags) {
+  struct _bt_gatt_ccc    *ccc = attr->user_data;
+  struct bt_gatt_ccc_cfg *cfg;
+  u16_t                   value;
 
-    if (offset) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
-    }
+  if (offset) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
+  }
 
-    if (!len || len > sizeof(u16_t)) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
-    }
+  if (!len || len > sizeof(u16_t)) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
+  }
 
-    if (len < sizeof(u16_t)) {
-        value = *(u8_t *)buf;
-    } else {
-        value = sys_get_le16(buf);
+  if (len < sizeof(u16_t)) {
+    value = *(u8_t *)buf;
+  } else {
+    value = sys_get_le16(buf);
+  }
+
+  cfg = find_ccc_cfg(conn, ccc);
+  if (!cfg) {
+    /* If there's no existing entry, but the new value is zero,
+     * we don't need to do anything, since a disabled CCC is
+     * behavioraly the same as no written CCC.
+     */
+    if (!value) {
+      return len;
     }
 
-    cfg = find_ccc_cfg(conn, ccc);
+    cfg = find_ccc_cfg(NULL, ccc);
     if (!cfg) {
-        /* If there's no existing entry, but the new value is zero,
-		 * we don't need to do anything, since a disabled CCC is
-		 * behavioraly the same as no written CCC.
-		 */
-        if (!value) {
-            return len;
-        }
-
-        cfg = find_ccc_cfg(NULL, ccc);
-        if (!cfg) {
-            BT_WARN("No space to store CCC cfg");
-            return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
-        }
-
-        bt_addr_le_copy(&cfg->peer, &conn->le.dst);
-        cfg->id = conn->id;
+      BT_WARN("No space to store CCC cfg");
+      return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
     }
 
-    /* Confirm write if cfg is managed by application */
-    if (ccc->cfg_write && !ccc->cfg_write(conn, attr, value)) {
-        return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
-    }
+    bt_addr_le_copy(&cfg->peer, &conn->le.dst);
+    cfg->id = conn->id;
+  }
 
-    cfg->value = value;
+  /* Confirm write if cfg is managed by application */
+  if (ccc->cfg_write && !ccc->cfg_write(conn, attr, value)) {
+    return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
+  }
 
-    BT_DBG("handle 0x%04x value %u", attr->handle, cfg->value);
+  cfg->value = value;
 
-    /* Update cfg if don't match */
-    if (cfg->value != ccc->value) {
-        gatt_ccc_changed(attr, ccc);
+  BT_DBG("handle 0x%04x value %u", attr->handle, cfg->value);
+
+  /* Update cfg if don't match */
+  if (cfg->value != ccc->value) {
+    gatt_ccc_changed(attr, ccc);
 
 #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE)
-        if ((!gatt_ccc_conn_is_queued(conn)) &&
-            bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
-            /* Store the connection with the same index it has in
-			 * the conns array
-			 */
-            gatt_ccc_store.conn_list[bt_conn_index(conn)] =
-                bt_conn_ref(conn);
-            k_delayed_work_submit(&gatt_ccc_store.work,
-                                  CCC_STORE_DELAY);
-        }
-#endif
+    if ((!gatt_ccc_conn_is_queued(conn)) && bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
+      /* Store the connection with the same index it has in
+       * the conns array
+       */
+      gatt_ccc_store.conn_list[bt_conn_index(conn)] = bt_conn_ref(conn);
+      k_delayed_work_submit(&gatt_ccc_store.work, CCC_STORE_DELAY);
     }
+#endif
+  }
 
-    /* Disabled CCC is the same as no configured CCC, so clear the entry */
-    if (!value) {
-        clear_ccc_cfg(cfg);
-    }
+  /* Disabled CCC is the same as no configured CCC, so clear the entry */
+  if (!value) {
+    clear_ccc_cfg(cfg);
+  }
 
-    return len;
+  return len;
 }
 
-ssize_t bt_gatt_attr_read_cep(struct bt_conn *conn,
-                              const struct bt_gatt_attr *attr, void *buf,
-                              u16_t len, u16_t offset)
-{
-    const struct bt_gatt_cep *value = attr->user_data;
-    u16_t props = sys_cpu_to_le16(value->properties);
+ssize_t bt_gatt_attr_read_cep(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  const struct bt_gatt_cep *value = attr->user_data;
+  u16_t                     props = sys_cpu_to_le16(value->properties);
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &props,
-                             sizeof(props));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &props, sizeof(props));
 }
 
-ssize_t bt_gatt_attr_read_cud(struct bt_conn *conn,
-                              const struct bt_gatt_attr *attr, void *buf,
-                              u16_t len, u16_t offset)
-{
-    const char *value = attr->user_data;
+ssize_t bt_gatt_attr_read_cud(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  const char *value = attr->user_data;
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
-                             strlen(value));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, value, strlen(value));
 }
 
-ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn,
-                              const struct bt_gatt_attr *attr, void *buf,
-                              u16_t len, u16_t offset)
-{
-    const struct bt_gatt_cpf *value = attr->user_data;
+ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  const struct bt_gatt_cpf *value = attr->user_data;
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
-                             sizeof(*value));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, value, sizeof(*value));
 }
 
 struct notify_data {
-    int err;
-    u16_t type;
-    union {
-        struct bt_gatt_notify_params *nfy_params;
-        struct bt_gatt_indicate_params *ind_params;
-    };
+  int   err;
+  u16_t type;
+  union {
+    struct bt_gatt_notify_params   *nfy_params;
+    struct bt_gatt_indicate_params *ind_params;
+  };
 };
 
-static int gatt_notify(struct bt_conn *conn, u16_t handle,
-                       struct bt_gatt_notify_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_notify *nfy;
+static int gatt_notify(struct bt_conn *conn, u16_t handle, struct bt_gatt_notify_params *params) {
+  struct net_buf       *buf;
+  struct bt_att_notify *nfy;
 
 #if defined(CONFIG_BT_GATT_ENFORCE_CHANGE_UNAWARE)
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350:
-	 * Except for the Handle Value indication, the  server shall not send
-	 * notifications and indications to such a client until it becomes
-	 * change-aware.
-	 */
-    if (!bt_gatt_change_aware(conn, false)) {
-        return -EAGAIN;
-    }
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350:
+   * Except for the Handle Value indication, the  server shall not send
+   * notifications and indications to such a client until it becomes
+   * change-aware.
+   */
+  if (!bt_gatt_change_aware(conn, false)) {
+    return -EAGAIN;
+  }
 #endif
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_NOTIFY,
-                            sizeof(*nfy) + params->len);
-    if (!buf) {
-        BT_WARN("No buffer available to send notification");
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_NOTIFY, sizeof(*nfy) + params->len);
+  if (!buf) {
+    BT_WARN("No buffer available to send notification");
+    return -ENOMEM;
+  }
 
-    BT_DBG("conn %p handle 0x%04x", conn, handle);
+  BT_DBG("conn %p handle 0x%04x", conn, handle);
 
-    nfy = net_buf_add(buf, sizeof(*nfy));
-    nfy->handle = sys_cpu_to_le16(handle);
+  nfy         = net_buf_add(buf, sizeof(*nfy));
+  nfy->handle = sys_cpu_to_le16(handle);
 
-    net_buf_add(buf, params->len);
-    memcpy(nfy->value, params->data, params->len);
+  net_buf_add(buf, params->len);
+  memcpy(nfy->value, params->data, params->len);
 
-    return bt_att_send(conn, buf, params->func, params->user_data);
+  return bt_att_send(conn, buf, params->func, params->user_data);
 }
 
-static void gatt_indicate_rsp(struct bt_conn *conn, u8_t err,
-                              const void *pdu, u16_t length, void *user_data)
-{
-    struct bt_gatt_indicate_params *params = user_data;
+static void gatt_indicate_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_indicate_params *params = user_data;
 
-    params->func(conn, params->attr, err);
+  params->func(conn, params->attr, err);
 }
 
-static int gatt_send(struct bt_conn *conn, struct net_buf *buf,
-                     bt_att_func_t func, void *params,
-                     bt_att_destroy_t destroy)
-{
-    int err;
+static int gatt_send(struct bt_conn *conn, struct net_buf *buf, bt_att_func_t func, void *params, bt_att_destroy_t destroy) {
+  int err;
 
-    if (params) {
-        struct bt_att_req *req = params;
-        req->buf = buf;
-        req->func = func;
-        req->destroy = destroy;
+  if (params) {
+    struct bt_att_req *req = params;
+    req->buf               = buf;
+    req->func              = func;
+    req->destroy           = destroy;
 
-        err = bt_att_req_send(conn, req);
-    } else {
-        err = bt_att_send(conn, buf, NULL, NULL);
-    }
+    err = bt_att_req_send(conn, req);
+  } else {
+    err = bt_att_send(conn, buf, NULL, NULL);
+  }
 
-    if (err) {
-        BT_ERR("Error sending ATT PDU: %d", err);
-    }
+  if (err) {
+    BT_ERR("Error sending ATT PDU: %d", err);
+  }
 
-    return err;
+  return err;
 }
 
-static int gatt_indicate(struct bt_conn *conn, u16_t handle,
-                         struct bt_gatt_indicate_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_indicate *ind;
+static int gatt_indicate(struct bt_conn *conn, u16_t handle, struct bt_gatt_indicate_params *params) {
+  struct net_buf         *buf;
+  struct bt_att_indicate *ind;
 
 #if defined(CONFIG_BT_GATT_ENFORCE_CHANGE_UNAWARE)
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350:
-	 * Except for the Handle Value indication, the  server shall not send
-	 * notifications and indications to such a client until it becomes
-	 * change-aware.
-	 */
-    if (!(params->func && (params->func == sc_indicate_rsp ||
-                           params->func == sc_restore_rsp)) &&
-        !bt_gatt_change_aware(conn, false)) {
-        return -EAGAIN;
-    }
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350:
+   * Except for the Handle Value indication, the  server shall not send
+   * notifications and indications to such a client until it becomes
+   * change-aware.
+   */
+  if (!(params->func && (params->func == sc_indicate_rsp || params->func == sc_restore_rsp)) && !bt_gatt_change_aware(conn, false)) {
+    return -EAGAIN;
+  }
 #endif
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_INDICATE,
-                            sizeof(*ind) + params->len);
-    if (!buf) {
-        BT_WARN("No buffer available to send indication");
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_INDICATE, sizeof(*ind) + params->len);
+  if (!buf) {
+    BT_WARN("No buffer available to send indication");
+    return -ENOMEM;
+  }
 
-    BT_DBG("conn %p handle 0x%04x", conn, handle);
+  BT_DBG("conn %p handle 0x%04x", conn, handle);
 
-    ind = net_buf_add(buf, sizeof(*ind));
-    ind->handle = sys_cpu_to_le16(handle);
+  ind         = net_buf_add(buf, sizeof(*ind));
+  ind->handle = sys_cpu_to_le16(handle);
 
-    net_buf_add(buf, params->len);
-    memcpy(ind->value, params->data, params->len);
+  net_buf_add(buf, params->len);
+  memcpy(ind->value, params->data, params->len);
 
-    if (!params->func) {
-        return gatt_send(conn, buf, NULL, NULL, NULL);
-    }
+  if (!params->func) {
+    return gatt_send(conn, buf, NULL, NULL, NULL);
+  }
 
-    return gatt_send(conn, buf, gatt_indicate_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_indicate_rsp, params, NULL);
 }
 
-static u8_t notify_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct notify_data *data = user_data;
-    struct _bt_gatt_ccc *ccc;
-    size_t i;
+static u8_t notify_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct notify_data  *data = user_data;
+  struct _bt_gatt_ccc *ccc;
+  size_t               i;
 
-    /* Check attribute user_data must be of type struct _bt_gatt_ccc */
-    if (attr->write != bt_gatt_attr_write_ccc) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  /* Check attribute user_data must be of type struct _bt_gatt_ccc */
+  if (attr->write != bt_gatt_attr_write_ccc) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    ccc = attr->user_data;
-
-    /* Save Service Changed data if peer is not connected */
-    if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) && ccc == &sc_ccc) {
-        for (i = 0; i < ARRAY_SIZE(sc_cfg); i++) {
-            struct gatt_sc_cfg *cfg = &sc_cfg[i];
-            struct bt_conn *conn;
-
-            if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) {
-                continue;
-            }
-
-            conn = bt_conn_lookup_state_le(&cfg->peer,
-                                           BT_CONN_CONNECTED);
-            if (!conn) {
-                struct sc_data *sc;
-
-                sc = (struct sc_data *)data->ind_params->data;
-                sc_save(cfg->id, &cfg->peer,
-                        sys_le16_to_cpu(sc->start),
-                        sys_le16_to_cpu(sc->end));
-                continue;
-            }
-            bt_conn_unref(conn);
-        }
+  ccc = attr->user_data;
+
+  /* Save Service Changed data if peer is not connected */
+  if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) && ccc == &sc_ccc) {
+    for (i = 0; i < ARRAY_SIZE(sc_cfg); i++) {
+      struct gatt_sc_cfg *cfg = &sc_cfg[i];
+      struct bt_conn     *conn;
+
+      if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) {
+        continue;
+      }
+
+      conn = bt_conn_lookup_state_le(&cfg->peer, BT_CONN_CONNECTED);
+      if (!conn) {
+        struct sc_data *sc;
+
+        sc = (struct sc_data *)data->ind_params->data;
+        sc_save(cfg->id, &cfg->peer, sys_le16_to_cpu(sc->start), sys_le16_to_cpu(sc->end));
+        continue;
+      }
+      bt_conn_unref(conn);
     }
+  }
 
-    /* Notify all peers configured */
-    for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
-        struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
-        struct bt_conn *conn;
-        int err;
-
-        /* Check if config value matches data type since consolidated
-		 * value may be for a different peer.
-		 */
-        if (cfg->value != data->type) {
-            continue;
-        }
+  /* Notify all peers configured */
+  for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
+    struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
+    struct bt_conn         *conn;
+    int                     err;
 
-        conn = bt_conn_lookup_addr_le(cfg->id, &cfg->peer);
-        if (!conn) {
-            continue;
-        }
+    /* Check if config value matches data type since consolidated
+     * value may be for a different peer.
+     */
+    if (cfg->value != data->type) {
+      continue;
+    }
 
-        if (conn->state != BT_CONN_CONNECTED) {
-            bt_conn_unref(conn);
-            continue;
-        }
+    conn = bt_conn_lookup_addr_le(cfg->id, &cfg->peer);
+    if (!conn) {
+      continue;
+    }
 
-        /* Confirm match if cfg is managed by application */
-        if (ccc->cfg_match && !ccc->cfg_match(conn, attr)) {
-            bt_conn_unref(conn);
-            continue;
-        }
+    if (conn->state != BT_CONN_CONNECTED) {
+      bt_conn_unref(conn);
+      continue;
+    }
 
-        if (data->type == BT_GATT_CCC_INDICATE) {
-            err = gatt_indicate(conn, attr->handle - 1,
-                                data->ind_params);
-        } else {
-            err = gatt_notify(conn, attr->handle - 1,
-                              data->nfy_params);
-        }
+    /* Confirm match if cfg is managed by application */
+    if (ccc->cfg_match && !ccc->cfg_match(conn, attr)) {
+      bt_conn_unref(conn);
+      continue;
+    }
 
-        bt_conn_unref(conn);
+    if (data->type == BT_GATT_CCC_INDICATE) {
+      err = gatt_indicate(conn, attr->handle - 1, data->ind_params);
+    } else {
+      err = gatt_notify(conn, attr->handle - 1, data->nfy_params);
+    }
 
-        if (err < 0) {
-            return BT_GATT_ITER_STOP;
-        }
+    bt_conn_unref(conn);
 
-        data->err = 0;
+    if (err < 0) {
+      return BT_GATT_ITER_STOP;
     }
 
-    return BT_GATT_ITER_CONTINUE;
+    data->err = 0;
+  }
+
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static u8_t match_uuid(const struct bt_gatt_attr *attr, void *user_data)
-{
-    const struct bt_gatt_attr **found = user_data;
+static u8_t match_uuid(const struct bt_gatt_attr *attr, void *user_data) {
+  const struct bt_gatt_attr **found = user_data;
 
-    *found = attr;
+  *found = attr;
 
-    return BT_GATT_ITER_STOP;
+  return BT_GATT_ITER_STOP;
 }
 
-int bt_gatt_notify_cb(struct bt_conn *conn,
-                      struct bt_gatt_notify_params *params)
-{
-    struct notify_data data;
-    const struct bt_gatt_attr *attr;
-    u16_t handle;
+int bt_gatt_notify_cb(struct bt_conn *conn, struct bt_gatt_notify_params *params) {
+  struct notify_data         data;
+  const struct bt_gatt_attr *attr;
+  u16_t                      handle;
+
+  __ASSERT(params, "invalid parameters\n");
+  __ASSERT(params->attr, "invalid parameters\n");
 
-    __ASSERT(params, "invalid parameters\n");
-    __ASSERT(params->attr, "invalid parameters\n");
+  attr = params->attr;
+
+  if (conn && conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
+#if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
+  handle = attr->handle ?: find_static_attr(attr);
+#endif
+  if (!handle) {
+    return -ENOENT;
+  }
 
-    attr = params->attr;
+  /* Lookup UUID if it was given */
+  if (params->uuid) {
+    attr = NULL;
 
-    if (conn && conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
+    bt_gatt_foreach_attr_type(handle, 0xffff, params->uuid, NULL, 1, match_uuid, &attr);
+    if (!attr) {
+      return -ENOENT;
     }
 #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
     handle = attr->handle ?: find_static_attr(attr);
 #endif
     if (!handle) {
-        return -ENOENT;
+      return -ENOENT;
     }
+  }
 
-    /* Lookup UUID if it was given */
-    if (params->uuid) {
-        attr = NULL;
+  /* Check if attribute is a characteristic then adjust the handle */
+  if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) {
+    struct bt_gatt_chrc *chrc = attr->user_data;
 
-        bt_gatt_foreach_attr_type(handle, 0xffff, params->uuid,
-                                  NULL, 1, match_uuid, &attr);
-        if (!attr) {
-            return -ENOENT;
-        }
-#if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-        handle = attr->handle ?: find_static_attr(attr);
-#endif
-        if (!handle) {
-            return -ENOENT;
-        }
+    if (!(chrc->properties & BT_GATT_CHRC_NOTIFY)) {
+      return -EINVAL;
     }
 
-    /* Check if attribute is a characteristic then adjust the handle */
-    if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) {
-        struct bt_gatt_chrc *chrc = attr->user_data;
+    handle = bt_gatt_attr_value_handle(attr);
+  }
 
-        if (!(chrc->properties & BT_GATT_CHRC_NOTIFY)) {
-            return -EINVAL;
-        }
+  if (conn) {
+    return gatt_notify(conn, handle, params);
+  }
 
-        handle = bt_gatt_attr_value_handle(attr);
-    }
+  data.err        = -ENOTCONN;
+  data.type       = BT_GATT_CCC_NOTIFY;
+  data.nfy_params = params;
 
-    if (conn) {
-        return gatt_notify(conn, handle, params);
-    }
+  bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1, notify_cb, &data);
 
-    data.err = -ENOTCONN;
-    data.type = BT_GATT_CCC_NOTIFY;
-    data.nfy_params = params;
+  return data.err;
+}
 
-    bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1,
-                              notify_cb, &data);
+int bt_gatt_indicate(struct bt_conn *conn, struct bt_gatt_indicate_params *params) {
+  struct notify_data         data;
+  const struct bt_gatt_attr *attr;
+  u16_t                      handle;
 
-    return data.err;
-}
+  __ASSERT(params, "invalid parameters\n");
+  __ASSERT(params->attr, "invalid parameters\n");
 
-int bt_gatt_indicate(struct bt_conn *conn,
-                     struct bt_gatt_indicate_params *params)
-{
-    struct notify_data data;
-    const struct bt_gatt_attr *attr;
-    u16_t handle;
+  attr = params->attr;
 
-    __ASSERT(params, "invalid parameters\n");
-    __ASSERT(params->attr, "invalid parameters\n");
+  if (conn && conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
+#if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
+  handle = attr->handle ?: find_static_attr(attr);
+#endif
+  if (!handle) {
+    return -ENOENT;
+  }
 
-    attr = params->attr;
+  /* Lookup UUID if it was given */
+  if (params->uuid) {
+    attr = NULL;
 
-    if (conn && conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
+    bt_gatt_foreach_attr_type(handle, 0xffff, params->uuid, NULL, 1, match_uuid, &attr);
+    if (!attr) {
+      return -ENOENT;
     }
 #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
     handle = attr->handle ?: find_static_attr(attr);
 #endif
     if (!handle) {
-        return -ENOENT;
+      return -ENOENT;
     }
+  }
 
-    /* Lookup UUID if it was given */
-    if (params->uuid) {
-        attr = NULL;
+  /* Check if attribute is a characteristic then adjust the handle */
+  if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) {
+    struct bt_gatt_chrc *chrc = params->attr->user_data;
 
-        bt_gatt_foreach_attr_type(handle, 0xffff, params->uuid,
-                                  NULL, 1, match_uuid, &attr);
-        if (!attr) {
-            return -ENOENT;
-        }
-#if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-        handle = attr->handle ?: find_static_attr(attr);
-#endif
-        if (!handle) {
-            return -ENOENT;
-        }
+    if (!(chrc->properties & BT_GATT_CHRC_INDICATE)) {
+      return -EINVAL;
     }
 
-    /* Check if attribute is a characteristic then adjust the handle */
-    if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) {
-        struct bt_gatt_chrc *chrc = params->attr->user_data;
-
-        if (!(chrc->properties & BT_GATT_CHRC_INDICATE)) {
-            return -EINVAL;
-        }
-
-        handle = bt_gatt_attr_value_handle(params->attr);
-    }
+    handle = bt_gatt_attr_value_handle(params->attr);
+  }
 
-    if (conn) {
-        return gatt_indicate(conn, handle, params);
-    }
+  if (conn) {
+    return gatt_indicate(conn, handle, params);
+  }
 
-    data.err = -ENOTCONN;
-    data.type = BT_GATT_CCC_INDICATE;
-    data.ind_params = params;
+  data.err        = -ENOTCONN;
+  data.type       = BT_GATT_CCC_INDICATE;
+  data.ind_params = params;
 
-    bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1,
-                              notify_cb, &data);
+  bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1, notify_cb, &data);
 
-    return data.err;
+  return data.err;
 }
 
-u16_t bt_gatt_get_mtu(struct bt_conn *conn)
-{
-    return bt_att_get_mtu(conn);
-}
+u16_t bt_gatt_get_mtu(struct bt_conn *conn) { return bt_att_get_mtu(conn); }
 
-u8_t bt_gatt_check_perm(struct bt_conn *conn, const struct bt_gatt_attr *attr,
-                        u8_t mask)
-{
-    if ((mask & BT_GATT_PERM_READ) &&
-        (!(attr->perm & BT_GATT_PERM_READ_MASK) || !attr->read)) {
-        return BT_ATT_ERR_READ_NOT_PERMITTED;
-    }
+u8_t bt_gatt_check_perm(struct bt_conn *conn, const struct bt_gatt_attr *attr, u8_t mask) {
+  if ((mask & BT_GATT_PERM_READ) && (!(attr->perm & BT_GATT_PERM_READ_MASK) || !attr->read)) {
+    return BT_ATT_ERR_READ_NOT_PERMITTED;
+  }
 
-    if ((mask & BT_GATT_PERM_WRITE) &&
-        (!(attr->perm & BT_GATT_PERM_WRITE_MASK) || !attr->write)) {
-        return BT_ATT_ERR_WRITE_NOT_PERMITTED;
-    }
+  if ((mask & BT_GATT_PERM_WRITE) && (!(attr->perm & BT_GATT_PERM_WRITE_MASK) || !attr->write)) {
+    return BT_ATT_ERR_WRITE_NOT_PERMITTED;
+  }
 
-    mask &= attr->perm;
-    if (mask & BT_GATT_PERM_AUTHEN_MASK) {
-        if (bt_conn_get_security(conn) < BT_SECURITY_L3) {
-            return BT_ATT_ERR_AUTHENTICATION;
-        }
+  mask &= attr->perm;
+  if (mask & BT_GATT_PERM_AUTHEN_MASK) {
+    if (bt_conn_get_security(conn) < BT_SECURITY_L3) {
+      return BT_ATT_ERR_AUTHENTICATION;
     }
+  }
 
-    if ((mask & BT_GATT_PERM_ENCRYPT_MASK)) {
+  if ((mask & BT_GATT_PERM_ENCRYPT_MASK)) {
 #if defined(CONFIG_BT_SMP)
-        if (!conn->encrypt) {
-            return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION;
-        }
+    if (!conn->encrypt) {
+      return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION;
+    }
 #else
-        return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION;
+    return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION;
 #endif /* CONFIG_BT_SMP */
-    }
+  }
 
-    return 0;
+  return 0;
 }
 
-static void sc_restore_rsp(struct bt_conn *conn,
-                           const struct bt_gatt_attr *attr, u8_t err)
-{
+static void sc_restore_rsp(struct bt_conn *conn, const struct bt_gatt_attr *attr, u8_t err) {
 #if defined(CONFIG_BT_GATT_CACHING)
-    struct gatt_cf_cfg *cfg;
+  struct gatt_cf_cfg *cfg;
 #endif
 
-    BT_DBG("err 0x%02x", err);
+  BT_DBG("err 0x%02x", err);
 
 #if defined(CONFIG_BT_GATT_CACHING)
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
-	 * 2.5.2.1 Robust Caching
-	 * A connected client becomes change-aware when...
-	 * The client receives and confirms a Service Changed indication.
-	 */
-    cfg = find_cf_cfg(conn);
-    if (cfg && CF_ROBUST_CACHING(cfg)) {
-        atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
-        BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer));
-    }
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
+   * 2.5.2.1 Robust Caching
+   * A connected client becomes change-aware when...
+   * The client receives and confirms a Service Changed indication.
+   */
+  cfg = find_cf_cfg(conn);
+  if (cfg && CF_ROBUST_CACHING(cfg)) {
+    atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
+    BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer));
+  }
 #endif
 }
 
 static struct bt_gatt_indicate_params sc_restore_params[CONFIG_BT_MAX_CONN];
 
-static void sc_restore(struct bt_conn *conn)
-{
-    struct gatt_sc_cfg *cfg;
-    u16_t sc_range[2];
-    u8_t index;
+static void sc_restore(struct bt_conn *conn) {
+  struct gatt_sc_cfg *cfg;
+  u16_t               sc_range[2];
+  u8_t                index;
 
-    cfg = find_sc_cfg(conn->id, &conn->le.dst);
-    if (!cfg) {
-        BT_DBG("no SC data found");
-        return;
-    }
+  cfg = find_sc_cfg(conn->id, &conn->le.dst);
+  if (!cfg) {
+    BT_DBG("no SC data found");
+    return;
+  }
 
-    if (!(cfg->data.start || cfg->data.end)) {
-        return;
-    }
+  if (!(cfg->data.start || cfg->data.end)) {
+    return;
+  }
 
-    BT_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(&cfg->peer),
-           cfg->data.start, cfg->data.end);
+  BT_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(&cfg->peer), cfg->data.start, cfg->data.end);
 
-    sc_range[0] = sys_cpu_to_le16(cfg->data.start);
-    sc_range[1] = sys_cpu_to_le16(cfg->data.end);
+  sc_range[0] = sys_cpu_to_le16(cfg->data.start);
+  sc_range[1] = sys_cpu_to_le16(cfg->data.end);
 
-    index = bt_conn_index(conn);
+  index = bt_conn_index(conn);
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-    sc_restore_params[index].attr = &gatt_attrs[2];
+  sc_restore_params[index].attr = &gatt_attrs[2];
 #else
-    sc_restore_params[index].attr = &_1_gatt_svc.attrs[2];
+  sc_restore_params[index].attr = &_1_gatt_svc.attrs[2];
 #endif
-    sc_restore_params[index].func = sc_restore_rsp;
-    sc_restore_params[index].data = &sc_range[0];
-    sc_restore_params[index].len = sizeof(sc_range);
+  sc_restore_params[index].func = sc_restore_rsp;
+  sc_restore_params[index].data = &sc_range[0];
+  sc_restore_params[index].len  = sizeof(sc_range);
 
-    if (bt_gatt_indicate(conn, &sc_restore_params[index])) {
-        BT_ERR("SC restore indication failed");
-    }
+  if (bt_gatt_indicate(conn, &sc_restore_params[index])) {
+    BT_ERR("SC restore indication failed");
+  }
 
-    /* Reset config data */
-    sc_reset(cfg);
+  /* Reset config data */
+  sc_reset(cfg);
 }
 
 struct conn_data {
-    struct bt_conn *conn;
-    bt_security_t sec;
+  struct bt_conn *conn;
+  bt_security_t   sec;
 };
 
-static u8_t update_ccc(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct conn_data *data = user_data;
-    struct bt_conn *conn = data->conn;
-    struct _bt_gatt_ccc *ccc;
-    size_t i;
-    u8_t err;
-
-    /* Check attribute user_data must be of type struct _bt_gatt_ccc */
-    if (attr->write != bt_gatt_attr_write_ccc) {
-        return BT_GATT_ITER_CONTINUE;
+static u8_t update_ccc(const struct bt_gatt_attr *attr, void *user_data) {
+  struct conn_data    *data = user_data;
+  struct bt_conn      *conn = data->conn;
+  struct _bt_gatt_ccc *ccc;
+  size_t               i;
+  u8_t                 err;
+
+  /* Check attribute user_data must be of type struct _bt_gatt_ccc */
+  if (attr->write != bt_gatt_attr_write_ccc) {
+    return BT_GATT_ITER_CONTINUE;
+  }
+
+  ccc = attr->user_data;
+
+  for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
+    /* Ignore configuration for different peer */
+    if (bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer)) {
+      continue;
     }
 
-    ccc = attr->user_data;
+    /* Check if attribute requires encryption/authentication */
+    err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_WRITE_MASK);
+    if (err) {
+      bt_security_t sec;
 
-    for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
-        /* Ignore configuration for different peer */
-        if (bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer)) {
-            continue;
-        }
+      if (err == BT_ATT_ERR_WRITE_NOT_PERMITTED) {
+        BT_WARN("CCC %p not writable", attr);
+        continue;
+      }
 
-        /* Check if attribute requires encryption/authentication */
-        err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_WRITE_MASK);
-        if (err) {
-            bt_security_t sec;
-
-            if (err == BT_ATT_ERR_WRITE_NOT_PERMITTED) {
-                BT_WARN("CCC %p not writable", attr);
-                continue;
-            }
-
-            sec = BT_SECURITY_L2;
-
-            if (err == BT_ATT_ERR_AUTHENTICATION) {
-                sec = BT_SECURITY_L3;
-            }
-
-            /* Check if current security is enough */
-            if (IS_ENABLED(CONFIG_BT_SMP) &&
-                bt_conn_get_security(conn) < sec) {
-                if (data->sec < sec) {
-                    data->sec = sec;
-                }
-                continue;
-            }
-        }
+      sec = BT_SECURITY_L2;
+
+      if (err == BT_ATT_ERR_AUTHENTICATION) {
+        sec = BT_SECURITY_L3;
+      }
 
-        if (ccc->cfg[i].value) {
-            gatt_ccc_changed(attr, ccc);
-            if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) &&
-                ccc == &sc_ccc) {
-                sc_restore(conn);
-            }
-            return BT_GATT_ITER_CONTINUE;
+      /* Check if current security is enough */
+      if (IS_ENABLED(CONFIG_BT_SMP) && bt_conn_get_security(conn) < sec) {
+        if (data->sec < sec) {
+          data->sec = sec;
         }
+        continue;
+      }
     }
 
-    return BT_GATT_ITER_CONTINUE;
+    if (ccc->cfg[i].value) {
+      gatt_ccc_changed(attr, ccc);
+      if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) && ccc == &sc_ccc) {
+        sc_restore(conn);
+      }
+      return BT_GATT_ITER_CONTINUE;
+    }
+  }
+
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static u8_t disconnected_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct bt_conn *conn = user_data;
-    struct _bt_gatt_ccc *ccc;
-    bool value_used;
-    size_t i;
-
-    /* Check attribute user_data must be of type struct _bt_gatt_ccc */
-    if (attr->write != bt_gatt_attr_write_ccc) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+static u8_t disconnected_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct bt_conn      *conn = user_data;
+  struct _bt_gatt_ccc *ccc;
+  bool                 value_used;
+  size_t               i;
 
-    ccc = attr->user_data;
+  /* Check attribute user_data must be of type struct _bt_gatt_ccc */
+  if (attr->write != bt_gatt_attr_write_ccc) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    /* If already disabled skip */
-    if (!ccc->value) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  ccc = attr->user_data;
 
-    /* Checking if all values are disabled */
-    value_used = false;
+  /* If already disabled skip */
+  if (!ccc->value) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
-        struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
+  /* Checking if all values are disabled */
+  value_used = false;
 
-        /* Ignore configurations with disabled value */
-        if (!cfg->value) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
+    struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
 
-        if (conn->id != cfg->id ||
-            bt_conn_addr_le_cmp(conn, &cfg->peer)) {
-            struct bt_conn *tmp;
-
-            /* Skip if there is another peer connected */
-            tmp = bt_conn_lookup_addr_le(cfg->id, &cfg->peer);
-            if (tmp) {
-                if (tmp->state == BT_CONN_CONNECTED) {
-                    value_used = true;
-                }
-
-                bt_conn_unref(tmp);
-            }
-        } else {
-            /* Clear value if not paired */
-            if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
-                clear_ccc_cfg(cfg);
-            } else {
-                /* Update address in case it has changed */
-                bt_addr_le_copy(&cfg->peer, &conn->le.dst);
-            }
-        }
+    /* Ignore configurations with disabled value */
+    if (!cfg->value) {
+      continue;
     }
 
-    /* If all values are now disabled, reset value while disconnected */
-    if (!value_used) {
-        ccc->value = 0U;
-        if (ccc->cfg_changed) {
-            ccc->cfg_changed(attr, ccc->value);
+    if (conn->id != cfg->id || bt_conn_addr_le_cmp(conn, &cfg->peer)) {
+      struct bt_conn *tmp;
+
+      /* Skip if there is another peer connected */
+      tmp = bt_conn_lookup_addr_le(cfg->id, &cfg->peer);
+      if (tmp) {
+        if (tmp->state == BT_CONN_CONNECTED) {
+          value_used = true;
         }
 
-        BT_DBG("ccc %p reseted", ccc);
+        bt_conn_unref(tmp);
+      }
+    } else {
+      /* Clear value if not paired */
+      if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
+        clear_ccc_cfg(cfg);
+      } else {
+        /* Update address in case it has changed */
+        bt_addr_le_copy(&cfg->peer, &conn->le.dst);
+      }
     }
+  }
 
-    return BT_GATT_ITER_CONTINUE;
-}
+  /* If all values are now disabled, reset value while disconnected */
+  if (!value_used) {
+    ccc->value = 0U;
+    if (ccc->cfg_changed) {
+      ccc->cfg_changed(attr, ccc->value);
+    }
 
-bool bt_gatt_is_subscribed(struct bt_conn *conn,
-                           const struct bt_gatt_attr *attr, u16_t ccc_value)
-{
-    const struct _bt_gatt_ccc *ccc;
+    BT_DBG("ccc %p reseted", ccc);
+  }
 
-    __ASSERT(conn, "invalid parameter\n");
-    __ASSERT(attr, "invalid parameter\n");
+  return BT_GATT_ITER_CONTINUE;
+}
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return false;
-    }
+bool bt_gatt_is_subscribed(struct bt_conn *conn, const struct bt_gatt_attr *attr, u16_t ccc_value) {
+  const struct _bt_gatt_ccc *ccc;
 
-    /* Check if attribute is a characteristic declaration */
-    if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) {
-        struct bt_gatt_chrc *chrc = attr->user_data;
+  __ASSERT(conn, "invalid parameter\n");
+  __ASSERT(attr, "invalid parameter\n");
 
-        if (!(chrc->properties &
-              (BT_GATT_CHRC_NOTIFY | BT_GATT_CHRC_INDICATE))) {
-            /* Characteristic doesn't support subscription */
-            return false;
-        }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return false;
+  }
 
-        attr = bt_gatt_attr_next(attr);
-    }
+  /* Check if attribute is a characteristic declaration */
+  if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) {
+    struct bt_gatt_chrc *chrc = attr->user_data;
 
-    /* Check if attribute is a characteristic value */
-    if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) {
-        attr = bt_gatt_attr_next(attr);
+    if (!(chrc->properties & (BT_GATT_CHRC_NOTIFY | BT_GATT_CHRC_INDICATE))) {
+      /* Characteristic doesn't support subscription */
+      return false;
     }
 
-    /* Check if the attribute is the CCC Descriptor */
-    if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) {
-        return false;
-    }
+    attr = bt_gatt_attr_next(attr);
+  }
 
-    ccc = attr->user_data;
+  /* Check if attribute is a characteristic value */
+  if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) {
+    attr = bt_gatt_attr_next(attr);
+  }
 
-    /* Check if the connection is subscribed */
-    for (size_t i = 0; i < BT_GATT_CCC_MAX; i++) {
-        if (conn->id == ccc->cfg[i].id &&
-            !bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer) &&
-            (ccc_value & ccc->cfg[i].value)) {
-            return true;
-        }
+  /* Check if the attribute is the CCC Descriptor */
+  if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) {
+    return false;
+  }
+
+  ccc = attr->user_data;
+
+  /* Check if the connection is subscribed */
+  for (size_t i = 0; i < BT_GATT_CCC_MAX; i++) {
+    if (conn->id == ccc->cfg[i].id && !bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer) && (ccc_value & ccc->cfg[i].value)) {
+      return true;
     }
+  }
 
-    return false;
+  return false;
 }
 
 #if defined(CONFIG_BT_GATT_CLIENT)
-void bt_gatt_notification(struct bt_conn *conn, u16_t handle,
-                          const void *data, u16_t length)
-{
-    struct bt_gatt_subscribe_params *params, *tmp;
+void bt_gatt_notification(struct bt_conn *conn, u16_t handle, const void *data, u16_t length) {
+  struct bt_gatt_subscribe_params *params, *tmp;
 
-    BT_DBG("handle 0x%04x length %u", handle, length);
+  BT_DBG("handle 0x%04x length %u", handle, length);
 
-    SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node)
-    {
-        if (bt_conn_addr_le_cmp(conn, ¶ms->_peer) ||
-            handle != params->value_handle) {
-            continue;
-        }
+  SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node) {
+    if (bt_conn_addr_le_cmp(conn, ¶ms->_peer) || handle != params->value_handle) {
+      continue;
+    }
 
-        if (params->notify(conn, params, data, length) ==
-            BT_GATT_ITER_STOP) {
-            bt_gatt_unsubscribe(conn, params);
-        }
+    if (params->notify(conn, params, data, length) == BT_GATT_ITER_STOP) {
+      bt_gatt_unsubscribe(conn, params);
     }
+  }
 }
 
-static void update_subscription(struct bt_conn *conn,
-                                struct bt_gatt_subscribe_params *params)
-{
-    if (params->_peer.type == BT_ADDR_LE_PUBLIC) {
-        return;
-    }
+static void update_subscription(struct bt_conn *conn, struct bt_gatt_subscribe_params *params) {
+  if (params->_peer.type == BT_ADDR_LE_PUBLIC) {
+    return;
+  }
 
-    /* Update address */
-    bt_addr_le_copy(¶ms->_peer, &conn->le.dst);
+  /* Update address */
+  bt_addr_le_copy(¶ms->_peer, &conn->le.dst);
 }
 
-static void gatt_subscription_remove(struct bt_conn *conn, sys_snode_t *prev,
-                                     struct bt_gatt_subscribe_params *params)
-{
-    /* Remove subscription from the list*/
-    sys_slist_remove(&subscriptions, prev, ¶ms->node);
+static void gatt_subscription_remove(struct bt_conn *conn, sys_snode_t *prev, struct bt_gatt_subscribe_params *params) {
+  /* Remove subscription from the list*/
+  sys_slist_remove(&subscriptions, prev, ¶ms->node);
 
-    params->notify(conn, params, NULL, 0);
+  params->notify(conn, params, NULL, 0);
 }
 
-static void remove_subscriptions(struct bt_conn *conn)
-{
-    struct bt_gatt_subscribe_params *params, *tmp;
-    sys_snode_t *prev = NULL;
-
-    /* Lookup existing subscriptions */
-    SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node)
-    {
-        if (bt_conn_addr_le_cmp(conn, ¶ms->_peer)) {
-            prev = ¶ms->node;
-            continue;
-        }
+static void remove_subscriptions(struct bt_conn *conn) {
+  struct bt_gatt_subscribe_params *params, *tmp;
+  sys_snode_t                     *prev = NULL;
 
-        if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst) ||
-            (atomic_test_bit(params->flags,
-                             BT_GATT_SUBSCRIBE_FLAG_VOLATILE))) {
-            /* Remove subscription */
-            params->value = 0U;
-            gatt_subscription_remove(conn, prev, params);
-        } else {
-            update_subscription(conn, params);
-            prev = ¶ms->node;
-        }
+  /* Lookup existing subscriptions */
+  SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node) {
+    if (bt_conn_addr_le_cmp(conn, ¶ms->_peer)) {
+      prev = ¶ms->node;
+      continue;
+    }
+
+    if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst) || (atomic_test_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_VOLATILE))) {
+      /* Remove subscription */
+      params->value = 0U;
+      gatt_subscription_remove(conn, prev, params);
+    } else {
+      update_subscription(conn, params);
+      prev = ¶ms->node;
     }
+  }
 }
 
-static void gatt_mtu_rsp(struct bt_conn *conn, u8_t err, const void *pdu,
-                         u16_t length, void *user_data)
-{
-    struct bt_gatt_exchange_params *params = user_data;
+static void gatt_mtu_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_exchange_params *params = user_data;
 
-    params->func(conn, err, params);
+  params->func(conn, err, params);
 }
 #if defined(CONFIG_BLE_AT_CMD)
-int bt_at_gatt_exchange_mtu(struct bt_conn *conn, struct bt_gatt_exchange_params *params, u16_t mtu_size)
-{
-    struct bt_att_exchange_mtu_req *req;
-    struct net_buf *buf;
-    u16_t mtu;
+int bt_at_gatt_exchange_mtu(struct bt_conn *conn, struct bt_gatt_exchange_params *params, u16_t mtu_size) {
+  struct bt_att_exchange_mtu_req *req;
+  struct net_buf                 *buf;
+  u16_t                           mtu;
 
-    __ASSERT(conn, "invalid parameter\n");
-    __ASSERT(params && params->func, "invalid parameters\n");
+  __ASSERT(conn, "invalid parameter\n");
+  __ASSERT(params && params->func, "invalid parameters\n");
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_MTU_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_MTU_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    mtu = mtu_size;
+  mtu = mtu_size;
 
 #if defined(CONFIG_BLE_AT_CMD)
-    set_mtu_size(mtu);
+  set_mtu_size(mtu);
 #endif
 
-    BT_DBG("Client MTU %u", mtu);
+  BT_DBG("Client MTU %u", mtu);
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->mtu = sys_cpu_to_le16(mtu);
+  req      = net_buf_add(buf, sizeof(*req));
+  req->mtu = sys_cpu_to_le16(mtu);
 
-    return gatt_send(conn, buf, gatt_mtu_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_mtu_rsp, params, NULL);
 }
 #endif
 
-int bt_gatt_exchange_mtu(struct bt_conn *conn,
-                         struct bt_gatt_exchange_params *params)
-{
-    struct bt_att_exchange_mtu_req *req;
-    struct net_buf *buf;
-    u16_t mtu;
+int bt_gatt_exchange_mtu(struct bt_conn *conn, struct bt_gatt_exchange_params *params) {
+  struct bt_att_exchange_mtu_req *req;
+  struct net_buf                 *buf;
+  u16_t                           mtu;
 
-    __ASSERT(conn, "invalid parameter\n");
-    __ASSERT(params && params->func, "invalid parameters\n");
+  __ASSERT(conn, "invalid parameter\n");
+  __ASSERT(params && params->func, "invalid parameters\n");
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_MTU_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_MTU_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    mtu = BT_ATT_MTU;
+  mtu = BT_ATT_MTU;
 
-    BT_DBG("Client MTU %u", mtu);
+  BT_DBG("Client MTU %u", mtu);
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->mtu = sys_cpu_to_le16(mtu);
+  req      = net_buf_add(buf, sizeof(*req));
+  req->mtu = sys_cpu_to_le16(mtu);
 
-    return gatt_send(conn, buf, gatt_mtu_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_mtu_rsp, params, NULL);
 }
 
-static void gatt_discover_next(struct bt_conn *conn, u16_t last_handle,
-                               struct bt_gatt_discover_params *params)
-{
-    /* Skip if last_handle is not set */
-    if (!last_handle)
-        goto discover;
-
-    /* Continue from the last found handle */
-    params->start_handle = last_handle;
-    if (params->start_handle < UINT16_MAX) {
-        params->start_handle++;
-    } else {
-        goto done;
-    }
+static void gatt_discover_next(struct bt_conn *conn, u16_t last_handle, struct bt_gatt_discover_params *params) {
+  /* Skip if last_handle is not set */
+  if (!last_handle)
+    goto discover;
 
-    /* Stop if over the range or the requests */
-    if (params->start_handle > params->end_handle) {
-        goto done;
-    }
+  /* Continue from the last found handle */
+  params->start_handle = last_handle;
+  if (params->start_handle < UINT16_MAX) {
+    params->start_handle++;
+  } else {
+    goto done;
+  }
+
+  /* Stop if over the range or the requests */
+  if (params->start_handle > params->end_handle) {
+    goto done;
+  }
 
 discover:
-    /* Discover next range */
-    if (!bt_gatt_discover(conn, params)) {
-        return;
-    }
+  /* Discover next range */
+  if (!bt_gatt_discover(conn, params)) {
+    return;
+  }
 
 done:
-    params->func(conn, NULL, params);
+  params->func(conn, NULL, params);
 }
 
-static void gatt_find_type_rsp(struct bt_conn *conn, u8_t err,
-                               const void *pdu, u16_t length,
-                               void *user_data)
-{
-    const struct bt_att_find_type_rsp *rsp = pdu;
-    struct bt_gatt_discover_params *params = user_data;
-    u8_t i;
-    u16_t end_handle = 0U, start_handle;
+static void gatt_find_type_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  const struct bt_att_find_type_rsp *rsp    = pdu;
+  struct bt_gatt_discover_params    *params = user_data;
+  u8_t                               i;
+  u16_t                              end_handle = 0U, start_handle;
 
-    BT_DBG("err 0x%02x", err);
+  BT_DBG("err 0x%02x", err);
 
-    if (err) {
-        goto done;
-    }
+  if (err) {
+    goto done;
+  }
 
-    /* Parse attributes found */
-    for (i = 0U; length >= sizeof(rsp->list[i]);
-         i++, length -= sizeof(rsp->list[i])) {
-        struct bt_gatt_attr attr = {};
-        struct bt_gatt_service_val value;
+  /* Parse attributes found */
+  for (i = 0U; length >= sizeof(rsp->list[i]); i++, length -= sizeof(rsp->list[i])) {
+    struct bt_gatt_attr        attr = {};
+    struct bt_gatt_service_val value;
 
-        start_handle = sys_le16_to_cpu(rsp->list[i].start_handle);
-        end_handle = sys_le16_to_cpu(rsp->list[i].end_handle);
+    start_handle = sys_le16_to_cpu(rsp->list[i].start_handle);
+    end_handle   = sys_le16_to_cpu(rsp->list[i].end_handle);
 
-        BT_DBG("start_handle 0x%04x end_handle 0x%04x", start_handle,
-               end_handle);
+    BT_DBG("start_handle 0x%04x end_handle 0x%04x", start_handle, end_handle);
 
-        if (params->type == BT_GATT_DISCOVER_PRIMARY) {
-            attr.uuid = BT_UUID_GATT_PRIMARY;
-        } else {
-            attr.uuid = BT_UUID_GATT_SECONDARY;
-        }
+    if (params->type == BT_GATT_DISCOVER_PRIMARY) {
+      attr.uuid = BT_UUID_GATT_PRIMARY;
+    } else {
+      attr.uuid = BT_UUID_GATT_SECONDARY;
+    }
 
-        value.end_handle = end_handle;
-        value.uuid = params->uuid;
+    value.end_handle = end_handle;
+    value.uuid       = params->uuid;
 
-        attr.handle = start_handle;
-        attr.user_data = &value;
+    attr.handle    = start_handle;
+    attr.user_data = &value;
 
-        if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
-            return;
-        }
+    if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
+      return;
     }
+  }
 
-    /* Stop if could not parse the whole PDU */
-    if (length > 0) {
-        goto done;
-    }
+  /* Stop if could not parse the whole PDU */
+  if (length > 0) {
+    goto done;
+  }
 
-    gatt_discover_next(conn, end_handle, params);
+  gatt_discover_next(conn, end_handle, params);
 
-    return;
+  return;
 done:
-    params->func(conn, NULL, params);
-}
-
-static int gatt_find_type(struct bt_conn *conn,
-                          struct bt_gatt_discover_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_find_type_req *req;
-    struct bt_uuid *uuid;
+  params->func(conn, NULL, params);
+}
+
+static int gatt_find_type(struct bt_conn *conn, struct bt_gatt_discover_params *params) {
+  struct net_buf              *buf;
+  struct bt_att_find_type_req *req;
+  struct bt_uuid              *uuid;
+
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_TYPE_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
+
+  req               = net_buf_add(buf, sizeof(*req));
+  req->start_handle = sys_cpu_to_le16(params->start_handle);
+  req->end_handle   = sys_cpu_to_le16(params->end_handle);
+
+  if (params->type == BT_GATT_DISCOVER_PRIMARY) {
+    uuid = BT_UUID_GATT_PRIMARY;
+  } else {
+    uuid = BT_UUID_GATT_SECONDARY;
+  }
+
+  req->type = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
+
+  BT_DBG("uuid %s start_handle 0x%04x end_handle 0x%04x", bt_uuid_str(params->uuid), params->start_handle, params->end_handle);
+
+  switch (params->uuid->type) {
+  case BT_UUID_TYPE_16:
+    net_buf_add_le16(buf, BT_UUID_16(params->uuid)->val);
+    break;
+  case BT_UUID_TYPE_128:
+    net_buf_add_mem(buf, BT_UUID_128(params->uuid)->val, 16);
+    break;
+  default:
+    BT_ERR("Unknown UUID type %u", params->uuid->type);
+    net_buf_unref(buf);
+    return -EINVAL;
+  }
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_TYPE_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  return gatt_send(conn, buf, gatt_find_type_rsp, params, NULL);
+}
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->start_handle = sys_cpu_to_le16(params->start_handle);
-    req->end_handle = sys_cpu_to_le16(params->end_handle);
+static void read_included_uuid_cb(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_discover_params *params = user_data;
+  struct bt_gatt_include          value;
+  struct bt_gatt_attr            *attr;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_128 u128;
+  } u;
 
-    if (params->type == BT_GATT_DISCOVER_PRIMARY) {
-        uuid = BT_UUID_GATT_PRIMARY;
-    } else {
-        uuid = BT_UUID_GATT_SECONDARY;
-    }
-
-    req->type = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
-
-    BT_DBG("uuid %s start_handle 0x%04x end_handle 0x%04x",
-           bt_uuid_str(params->uuid), params->start_handle,
-           params->end_handle);
-
-    switch (params->uuid->type) {
-        case BT_UUID_TYPE_16:
-            net_buf_add_le16(buf, BT_UUID_16(params->uuid)->val);
-            break;
-        case BT_UUID_TYPE_128:
-            net_buf_add_mem(buf, BT_UUID_128(params->uuid)->val, 16);
-            break;
-        default:
-            BT_ERR("Unknown UUID type %u", params->uuid->type);
-            net_buf_unref(buf);
-            return -EINVAL;
-    }
+  if (length != 16U) {
+    BT_ERR("Invalid data len %u", length);
+    params->func(conn, NULL, params);
+    return;
+  }
+
+  value.start_handle = params->_included.start_handle;
+  value.end_handle   = params->_included.end_handle;
+  value.uuid         = &u.uuid;
+  u.uuid.type        = BT_UUID_TYPE_128;
+  memcpy(u.u128.val, pdu, length);
+
+  BT_DBG("handle 0x%04x uuid %s start_handle 0x%04x "
+         "end_handle 0x%04x\n",
+         params->_included.attr_handle, bt_uuid_str(&u.uuid), value.start_handle, value.end_handle);
+
+  /* Skip if UUID is set but doesn't match */
+  if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
+    goto next;
+  }
+
+  attr         = (&(struct bt_gatt_attr){
+              .uuid      = BT_UUID_GATT_INCLUDE,
+              .user_data = &value,
+  });
+  attr->handle = params->_included.attr_handle;
+
+  if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
+    return;
+  }
+next:
+  gatt_discover_next(conn, params->start_handle, params);
 
-    return gatt_send(conn, buf, gatt_find_type_rsp, params, NULL);
+  return;
 }
 
-static void read_included_uuid_cb(struct bt_conn *conn, u8_t err,
-                                  const void *pdu, u16_t length,
-                                  void *user_data)
-{
-    struct bt_gatt_discover_params *params = user_data;
-    struct bt_gatt_include value;
-    struct bt_gatt_attr *attr;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_128 u128;
-    } u;
-
-    if (length != 16U) {
-        BT_ERR("Invalid data len %u", length);
-        params->func(conn, NULL, params);
-        return;
-    }
-
-    value.start_handle = params->_included.start_handle;
-    value.end_handle = params->_included.end_handle;
-    value.uuid = &u.uuid;
-    u.uuid.type = BT_UUID_TYPE_128;
-    memcpy(u.u128.val, pdu, length);
+static int read_included_uuid(struct bt_conn *conn, struct bt_gatt_discover_params *params) {
+  struct net_buf         *buf;
+  struct bt_att_read_req *req;
 
-    BT_DBG("handle 0x%04x uuid %s start_handle 0x%04x "
-           "end_handle 0x%04x\n",
-           params->_included.attr_handle,
-           bt_uuid_str(&u.uuid), value.start_handle, value.end_handle);
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    /* Skip if UUID is set but doesn't match */
-    if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
-        goto next;
-    }
-
-    attr = (&(struct bt_gatt_attr){
-        .uuid = BT_UUID_GATT_INCLUDE,
-        .user_data = &value,
-    });
-    attr->handle = params->_included.attr_handle;
+  req         = net_buf_add(buf, sizeof(*req));
+  req->handle = sys_cpu_to_le16(params->_included.start_handle);
 
-    if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
-        return;
-    }
-next:
-    gatt_discover_next(conn, params->start_handle, params);
+  BT_DBG("handle 0x%04x", params->_included.start_handle);
 
-    return;
+  return gatt_send(conn, buf, read_included_uuid_cb, params, NULL);
 }
 
-static int read_included_uuid(struct bt_conn *conn,
-                              struct bt_gatt_discover_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_read_req *req;
+static u16_t parse_include(struct bt_conn *conn, const void *pdu, struct bt_gatt_discover_params *params, u16_t length) {
+  const struct bt_att_read_type_rsp *rsp    = pdu;
+  u16_t                              handle = 0U;
+  struct bt_gatt_include             value;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_128 u128;
+  } u;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
+  /* Data can be either in UUID16 or UUID128 */
+  switch (rsp->len) {
+  case 8: /* UUID16 */
+    u.uuid.type = BT_UUID_TYPE_16;
+    break;
+  case 6: /* UUID128 */
+    /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 550
+     * To get the included service UUID when the included service
+     * uses a 128-bit UUID, the Read Request is used.
+     */
+    u.uuid.type = BT_UUID_TYPE_128;
+    break;
+  default:
+    BT_ERR("Invalid data len %u", rsp->len);
+    goto done;
+  }
+
+  /* Parse include found */
+  for (length--, pdu = rsp->data; length >= rsp->len; length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
+    struct bt_gatt_attr      *attr;
+    const struct bt_att_data *data = pdu;
+    struct gatt_incl         *incl = (void *)data->value;
+
+    handle = sys_le16_to_cpu(data->handle);
+    /* Handle 0 is invalid */
+    if (!handle) {
+      goto done;
     }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->handle = sys_cpu_to_le16(params->_included.start_handle);
+    /* Convert include data, bt_gatt_incl and gatt_incl
+     * have different formats so the conversion have to be done
+     * field by field.
+     */
+    value.start_handle = sys_le16_to_cpu(incl->start_handle);
+    value.end_handle   = sys_le16_to_cpu(incl->end_handle);
 
-    BT_DBG("handle 0x%04x", params->_included.start_handle);
-
-    return gatt_send(conn, buf, read_included_uuid_cb, params, NULL);
-}
+    switch (u.uuid.type) {
+    case BT_UUID_TYPE_16:
+      value.uuid = &u.uuid;
+      u.u16.val  = sys_le16_to_cpu(incl->uuid16);
+      break;
+    case BT_UUID_TYPE_128:
+      params->_included.attr_handle  = handle;
+      params->_included.start_handle = value.start_handle;
+      params->_included.end_handle   = value.end_handle;
 
-static u16_t parse_include(struct bt_conn *conn, const void *pdu,
-                           struct bt_gatt_discover_params *params,
-                           u16_t length)
-{
-    const struct bt_att_read_type_rsp *rsp = pdu;
-    u16_t handle = 0U;
-    struct bt_gatt_include value;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_128 u128;
-    } u;
-
-    /* Data can be either in UUID16 or UUID128 */
-    switch (rsp->len) {
-        case 8: /* UUID16 */
-            u.uuid.type = BT_UUID_TYPE_16;
-            break;
-        case 6: /* UUID128 */
-            /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 550
-		 * To get the included service UUID when the included service
-		 * uses a 128-bit UUID, the Read Request is used.
-		 */
-            u.uuid.type = BT_UUID_TYPE_128;
-            break;
-        default:
-            BT_ERR("Invalid data len %u", rsp->len);
-            goto done;
+      return read_included_uuid(conn, params);
     }
 
-    /* Parse include found */
-    for (length--, pdu = rsp->data; length >= rsp->len;
-         length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
-        struct bt_gatt_attr *attr;
-        const struct bt_att_data *data = pdu;
-        struct gatt_incl *incl = (void *)data->value;
-
-        handle = sys_le16_to_cpu(data->handle);
-        /* Handle 0 is invalid */
-        if (!handle) {
-            goto done;
-        }
-
-        /* Convert include data, bt_gatt_incl and gatt_incl
-		 * have different formats so the conversion have to be done
-		 * field by field.
-		 */
-        value.start_handle = sys_le16_to_cpu(incl->start_handle);
-        value.end_handle = sys_le16_to_cpu(incl->end_handle);
-
-        switch (u.uuid.type) {
-            case BT_UUID_TYPE_16:
-                value.uuid = &u.uuid;
-                u.u16.val = sys_le16_to_cpu(incl->uuid16);
-                break;
-            case BT_UUID_TYPE_128:
-                params->_included.attr_handle = handle;
-                params->_included.start_handle = value.start_handle;
-                params->_included.end_handle = value.end_handle;
-
-                return read_included_uuid(conn, params);
-        }
-
-        BT_DBG("handle 0x%04x uuid %s start_handle 0x%04x "
-               "end_handle 0x%04x\n",
-               handle, bt_uuid_str(&u.uuid),
-               value.start_handle, value.end_handle);
+    BT_DBG("handle 0x%04x uuid %s start_handle 0x%04x "
+           "end_handle 0x%04x\n",
+           handle, bt_uuid_str(&u.uuid), value.start_handle, value.end_handle);
 
-        /* Skip if UUID is set but doesn't match */
-        if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
-            continue;
-        }
+    /* Skip if UUID is set but doesn't match */
+    if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
+      continue;
+    }
 
-        attr = (&(struct bt_gatt_attr){
-            .uuid = BT_UUID_GATT_INCLUDE,
-            .user_data = &value,
-        });
-        attr->handle = handle;
+    attr         = (&(struct bt_gatt_attr){
+                .uuid      = BT_UUID_GATT_INCLUDE,
+                .user_data = &value,
+    });
+    attr->handle = handle;
 
-        if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
-            return 0;
-        }
+    if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
+      return 0;
     }
+  }
 
-    /* Whole PDU read without error */
-    if (length == 0U && handle) {
-        return handle;
-    }
+  /* Whole PDU read without error */
+  if (length == 0U && handle) {
+    return handle;
+  }
 
 done:
-    params->func(conn, NULL, params);
-    return 0;
-}
-
-#define BT_GATT_CHRC(_uuid, _handle, _props)                \
-    BT_GATT_ATTRIBUTE(BT_UUID_GATT_CHRC, BT_GATT_PERM_READ, \
-                      bt_gatt_attr_read_chrc, NULL,         \
-                      (&(struct bt_gatt_chrc){              \
-                          .uuid = _uuid,                    \
-                          .value_handle = _handle,          \
-                          .properties = _props,             \
-                      }))
-
-static u16_t parse_characteristic(struct bt_conn *conn, const void *pdu,
-                                  struct bt_gatt_discover_params *params,
-                                  u16_t length)
-{
-    const struct bt_att_read_type_rsp *rsp = pdu;
-    u16_t handle = 0U;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_128 u128;
-    } u;
-
-    /* Data can be either in UUID16 or UUID128 */
-    switch (rsp->len) {
-        case 7: /* UUID16 */
-            u.uuid.type = BT_UUID_TYPE_16;
-            break;
-        case 21: /* UUID128 */
-            u.uuid.type = BT_UUID_TYPE_128;
-            break;
-        default:
-            BT_ERR("Invalid data len %u", rsp->len);
-            goto done;
+  params->func(conn, NULL, params);
+  return 0;
+}
+
+#define BT_GATT_CHRC(_uuid, _handle, _props)                                            \
+  BT_GATT_ATTRIBUTE(BT_UUID_GATT_CHRC, BT_GATT_PERM_READ, bt_gatt_attr_read_chrc, NULL, \
+                    (&(struct bt_gatt_chrc){                                            \
+                        .uuid         = _uuid,                                          \
+                        .value_handle = _handle,                                        \
+                        .properties   = _props,                                         \
+                    }))
+
+static u16_t parse_characteristic(struct bt_conn *conn, const void *pdu, struct bt_gatt_discover_params *params, u16_t length) {
+  const struct bt_att_read_type_rsp *rsp    = pdu;
+  u16_t                              handle = 0U;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_128 u128;
+  } u;
+
+  /* Data can be either in UUID16 or UUID128 */
+  switch (rsp->len) {
+  case 7: /* UUID16 */
+    u.uuid.type = BT_UUID_TYPE_16;
+    break;
+  case 21: /* UUID128 */
+    u.uuid.type = BT_UUID_TYPE_128;
+    break;
+  default:
+    BT_ERR("Invalid data len %u", rsp->len);
+    goto done;
+  }
+
+  /* Parse characteristics found */
+  for (length--, pdu = rsp->data; length >= rsp->len; length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
+    struct bt_gatt_attr      *attr;
+    const struct bt_att_data *data = pdu;
+    struct gatt_chrc         *chrc = (void *)data->value;
+
+    handle = sys_le16_to_cpu(data->handle);
+    /* Handle 0 is invalid */
+    if (!handle) {
+      goto done;
     }
 
-    /* Parse characteristics found */
-    for (length--, pdu = rsp->data; length >= rsp->len;
-         length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
-        struct bt_gatt_attr *attr;
-        const struct bt_att_data *data = pdu;
-        struct gatt_chrc *chrc = (void *)data->value;
-
-        handle = sys_le16_to_cpu(data->handle);
-        /* Handle 0 is invalid */
-        if (!handle) {
-            goto done;
-        }
-
-        switch (u.uuid.type) {
-            case BT_UUID_TYPE_16:
-                u.u16.val = sys_le16_to_cpu(chrc->uuid16);
-                break;
-            case BT_UUID_TYPE_128:
-                memcpy(u.u128.val, chrc->uuid, sizeof(chrc->uuid));
-                break;
-        }
+    switch (u.uuid.type) {
+    case BT_UUID_TYPE_16:
+      u.u16.val = sys_le16_to_cpu(chrc->uuid16);
+      break;
+    case BT_UUID_TYPE_128:
+      memcpy(u.u128.val, chrc->uuid, sizeof(chrc->uuid));
+      break;
+    }
 
-        BT_DBG("handle 0x%04x uuid %s properties 0x%02x", handle,
-               bt_uuid_str(&u.uuid), chrc->properties);
+    BT_DBG("handle 0x%04x uuid %s properties 0x%02x", handle, bt_uuid_str(&u.uuid), chrc->properties);
 
 #if defined(CONFIG_BT_STACK_PTS)
-        if (event_flag != gatt_discover_chara) {
-            /* Skip if UUID is set but doesn't match */
-            if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid))
-                continue;
-        }
+    if (event_flag != gatt_discover_chara) {
+      /* Skip if UUID is set but doesn't match */
+      if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid))
+        continue;
+    }
 #else
-        /* Skip if UUID is set but doesn't match */
-        if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
-            continue;
-        }
+    /* Skip if UUID is set but doesn't match */
+    if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
+      continue;
+    }
 #endif
 
-        attr = (&(struct bt_gatt_attr)BT_GATT_CHRC(&u.uuid,
-                                                   chrc->value_handle,
-                                                   chrc->properties));
-        attr->handle = handle;
+    attr         = (&(struct bt_gatt_attr)BT_GATT_CHRC(&u.uuid, chrc->value_handle, chrc->properties));
+    attr->handle = handle;
 
-        if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
-            return 0;
-        }
+    if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
+      return 0;
     }
+  }
 
-    /* Whole PDU read without error */
-    if (length == 0U && handle) {
-        return handle;
-    }
+  /* Whole PDU read without error */
+  if (length == 0U && handle) {
+    return handle;
+  }
 
 done:
-    params->func(conn, NULL, params);
-    return 0;
+  params->func(conn, NULL, params);
+  return 0;
 }
 
-static void gatt_read_type_rsp(struct bt_conn *conn, u8_t err,
-                               const void *pdu, u16_t length,
-                               void *user_data)
-{
-    struct bt_gatt_discover_params *params = user_data;
-    u16_t handle;
+static void gatt_read_type_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_discover_params *params = user_data;
+  u16_t                           handle;
 
-    BT_DBG("err 0x%02x", err);
+  BT_DBG("err 0x%02x", err);
 
-    if (err) {
-        params->func(conn, NULL, params);
-        return;
-    }
+  if (err) {
+    params->func(conn, NULL, params);
+    return;
+  }
 
-    if (params->type == BT_GATT_DISCOVER_INCLUDE) {
-        handle = parse_include(conn, pdu, params, length);
-    } else {
-        handle = parse_characteristic(conn, pdu, params, length);
-    }
+  if (params->type == BT_GATT_DISCOVER_INCLUDE) {
+    handle = parse_include(conn, pdu, params, length);
+  } else {
+    handle = parse_characteristic(conn, pdu, params, length);
+  }
 
-    if (!handle) {
-        return;
-    }
+  if (!handle) {
+    return;
+  }
 
-    gatt_discover_next(conn, handle, params);
+  gatt_discover_next(conn, handle, params);
 }
 
-static int gatt_read_type(struct bt_conn *conn,
-                          struct bt_gatt_discover_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_read_type_req *req;
+static int gatt_read_type(struct bt_conn *conn, struct bt_gatt_discover_params *params) {
+  struct net_buf              *buf;
+  struct bt_att_read_type_req *req;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->start_handle = sys_cpu_to_le16(params->start_handle);
-    req->end_handle = sys_cpu_to_le16(params->end_handle);
+  req               = net_buf_add(buf, sizeof(*req));
+  req->start_handle = sys_cpu_to_le16(params->start_handle);
+  req->end_handle   = sys_cpu_to_le16(params->end_handle);
 
-    if (params->type == BT_GATT_DISCOVER_INCLUDE) {
-        net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_INCLUDE)->val);
-    } else {
-        net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_CHRC)->val);
-    }
+  if (params->type == BT_GATT_DISCOVER_INCLUDE) {
+    net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_INCLUDE)->val);
+  } else {
+    net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_CHRC)->val);
+  }
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle,
-           params->end_handle);
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, params->end_handle);
 
-    return gatt_send(conn, buf, gatt_read_type_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_read_type_rsp, params, NULL);
 }
 
-static u16_t parse_service(struct bt_conn *conn, const void *pdu,
-                           struct bt_gatt_discover_params *params,
-                           u16_t length)
-{
-    const struct bt_att_read_group_rsp *rsp = pdu;
-    u16_t start_handle, end_handle = 0U;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_128 u128;
-    } u;
-
-    /* Data can be either in UUID16 or UUID128 */
-    switch (rsp->len) {
-        case 6: /* UUID16 */
-            u.uuid.type = BT_UUID_TYPE_16;
-            break;
-        case 20: /* UUID128 */
-            u.uuid.type = BT_UUID_TYPE_128;
-            break;
-        default:
-            BT_ERR("Invalid data len %u", rsp->len);
-            goto done;
-    }
-
-    /* Parse services found */
-    for (length--, pdu = rsp->data; length >= rsp->len;
-         length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
-        struct bt_gatt_attr attr = {};
-        struct bt_gatt_service_val value;
-        const struct bt_att_group_data *data = pdu;
-
-        start_handle = sys_le16_to_cpu(data->start_handle);
-        if (!start_handle) {
-            goto done;
-        }
-
-        end_handle = sys_le16_to_cpu(data->end_handle);
-        if (!end_handle || end_handle < start_handle) {
-            goto done;
-        }
-
-        switch (u.uuid.type) {
-            case BT_UUID_TYPE_16:
-                memcpy(&u.u16.val, data->value, sizeof(u.u16.val));
-                u.u16.val = sys_le16_to_cpu(u.u16.val);
-                break;
-            case BT_UUID_TYPE_128:
-                memcpy(u.u128.val, data->value, sizeof(u.u128.val));
-                break;
-        }
-
-        BT_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s",
-               start_handle, end_handle, bt_uuid_str(&u.uuid));
+static u16_t parse_service(struct bt_conn *conn, const void *pdu, struct bt_gatt_discover_params *params, u16_t length) {
+  const struct bt_att_read_group_rsp *rsp = pdu;
+  u16_t                               start_handle, end_handle = 0U;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_128 u128;
+  } u;
 
-        if (params->type == BT_GATT_DISCOVER_PRIMARY) {
-            attr.uuid = BT_UUID_GATT_PRIMARY;
-        } else {
-            attr.uuid = BT_UUID_GATT_SECONDARY;
-        }
+  /* Data can be either in UUID16 or UUID128 */
+  switch (rsp->len) {
+  case 6: /* UUID16 */
+    u.uuid.type = BT_UUID_TYPE_16;
+    break;
+  case 20: /* UUID128 */
+    u.uuid.type = BT_UUID_TYPE_128;
+    break;
+  default:
+    BT_ERR("Invalid data len %u", rsp->len);
+    goto done;
+  }
 
-        value.end_handle = end_handle;
-        value.uuid = &u.uuid;
+  /* Parse services found */
+  for (length--, pdu = rsp->data; length >= rsp->len; length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
+    struct bt_gatt_attr             attr = {};
+    struct bt_gatt_service_val      value;
+    const struct bt_att_group_data *data = pdu;
 
-        attr.handle = start_handle;
-        attr.user_data = &value;
+    start_handle = sys_le16_to_cpu(data->start_handle);
+    if (!start_handle) {
+      goto done;
+    }
 
-        if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
-            return 0;
-        }
+    end_handle = sys_le16_to_cpu(data->end_handle);
+    if (!end_handle || end_handle < start_handle) {
+      goto done;
     }
 
-    /* Whole PDU read without error */
-    if (length == 0U && end_handle) {
-        return end_handle;
+    switch (u.uuid.type) {
+    case BT_UUID_TYPE_16:
+      memcpy(&u.u16.val, data->value, sizeof(u.u16.val));
+      u.u16.val = sys_le16_to_cpu(u.u16.val);
+      break;
+    case BT_UUID_TYPE_128:
+      memcpy(u.u128.val, data->value, sizeof(u.u128.val));
+      break;
     }
 
-done:
-    params->func(conn, NULL, params);
-    return 0;
-}
+    BT_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s", start_handle, end_handle, bt_uuid_str(&u.uuid));
 
-static void gatt_read_group_rsp(struct bt_conn *conn, u8_t err,
-                                const void *pdu, u16_t length,
-                                void *user_data)
-{
-    struct bt_gatt_discover_params *params = user_data;
-    u16_t handle;
+    if (params->type == BT_GATT_DISCOVER_PRIMARY) {
+      attr.uuid = BT_UUID_GATT_PRIMARY;
+    } else {
+      attr.uuid = BT_UUID_GATT_SECONDARY;
+    }
 
-    BT_DBG("err 0x%02x", err);
+    value.end_handle = end_handle;
+    value.uuid       = &u.uuid;
 
-    if (err) {
-        params->func(conn, NULL, params);
-        return;
-    }
+    attr.handle    = start_handle;
+    attr.user_data = &value;
 
-    handle = parse_service(conn, pdu, params, length);
-    if (!handle) {
-        return;
+    if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
+      return 0;
     }
+  }
 
-    gatt_discover_next(conn, handle, params);
-}
-
-static int gatt_read_group(struct bt_conn *conn,
-                           struct bt_gatt_discover_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_read_group_req *req;
+  /* Whole PDU read without error */
+  if (length == 0U && end_handle) {
+    return end_handle;
+  }
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_GROUP_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+done:
+  params->func(conn, NULL, params);
+  return 0;
+}
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->start_handle = sys_cpu_to_le16(params->start_handle);
-    req->end_handle = sys_cpu_to_le16(params->end_handle);
+static void gatt_read_group_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_discover_params *params = user_data;
+  u16_t                           handle;
 
-    if (params->type == BT_GATT_DISCOVER_PRIMARY) {
-        net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_PRIMARY)->val);
-    } else {
-        net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_SECONDARY)->val);
-    }
+  BT_DBG("err 0x%02x", err);
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle,
-           params->end_handle);
+  if (err) {
+    params->func(conn, NULL, params);
+    return;
+  }
 
-    return gatt_send(conn, buf, gatt_read_group_rsp, params, NULL);
-}
+  handle = parse_service(conn, pdu, params, length);
+  if (!handle) {
+    return;
+  }
+
+  gatt_discover_next(conn, handle, params);
+}
+
+static int gatt_read_group(struct bt_conn *conn, struct bt_gatt_discover_params *params) {
+  struct net_buf               *buf;
+  struct bt_att_read_group_req *req;
+
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_GROUP_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
+
+  req               = net_buf_add(buf, sizeof(*req));
+  req->start_handle = sys_cpu_to_le16(params->start_handle);
+  req->end_handle   = sys_cpu_to_le16(params->end_handle);
+
+  if (params->type == BT_GATT_DISCOVER_PRIMARY) {
+    net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_PRIMARY)->val);
+  } else {
+    net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_SECONDARY)->val);
+  }
+
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, params->end_handle);
+
+  return gatt_send(conn, buf, gatt_read_group_rsp, params, NULL);
+}
+
+static void gatt_find_info_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  const struct bt_att_find_info_rsp *rsp    = pdu;
+  struct bt_gatt_discover_params    *params = user_data;
+  u16_t                              handle = 0U;
+  u16_t                              len;
+  union {
+    const struct bt_att_info_16  *i16;
+    const struct bt_att_info_128 *i128;
+  } info;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_128 u128;
+  } u;
+  int  i;
+  bool skip = false;
+
+  BT_DBG("err 0x%02x", err);
+
+  if (err) {
+    goto done;
+  }
+
+  /* Data can be either in UUID16 or UUID128 */
+  switch (rsp->format) {
+  case BT_ATT_INFO_16:
+    u.uuid.type = BT_UUID_TYPE_16;
+    len         = sizeof(*info.i16);
+    break;
+  case BT_ATT_INFO_128:
+    u.uuid.type = BT_UUID_TYPE_128;
+    len         = sizeof(*info.i128);
+    break;
+  default:
+    BT_ERR("Invalid format %u", rsp->format);
+    goto done;
+  }
+
+  length--;
+
+  /* Check if there is a least one descriptor in the response */
+  if (length < len) {
+    goto done;
+  }
+
+  /* Parse descriptors found */
+  for (i = length / len, pdu = rsp->info; i != 0; i--, pdu = (const u8_t *)pdu + len) {
+    struct bt_gatt_attr *attr;
 
-static void gatt_find_info_rsp(struct bt_conn *conn, u8_t err,
-                               const void *pdu, u16_t length,
-                               void *user_data)
-{
-    const struct bt_att_find_info_rsp *rsp = pdu;
-    struct bt_gatt_discover_params *params = user_data;
-    u16_t handle = 0U;
-    u16_t len;
-    union {
-        const struct bt_att_info_16 *i16;
-        const struct bt_att_info_128 *i128;
-    } info;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_128 u128;
-    } u;
-    int i;
-    bool skip = false;
-
-    BT_DBG("err 0x%02x", err);
+    info.i16 = pdu;
+    handle   = sys_le16_to_cpu(info.i16->handle);
 
-    if (err) {
-        goto done;
+    if (skip) {
+      skip = false;
+      continue;
     }
 
-    /* Data can be either in UUID16 or UUID128 */
-    switch (rsp->format) {
-        case BT_ATT_INFO_16:
-            u.uuid.type = BT_UUID_TYPE_16;
-            len = sizeof(*info.i16);
-            break;
-        case BT_ATT_INFO_128:
-            u.uuid.type = BT_UUID_TYPE_128;
-            len = sizeof(*info.i128);
-            break;
-        default:
-            BT_ERR("Invalid format %u", rsp->format);
-            goto done;
+    switch (u.uuid.type) {
+    case BT_UUID_TYPE_16:
+      u.u16.val = sys_le16_to_cpu(info.i16->uuid);
+      break;
+    case BT_UUID_TYPE_128:
+      memcpy(u.u128.val, info.i128->uuid, 16);
+      break;
     }
 
-    length--;
+    BT_DBG("handle 0x%04x uuid %s", handle, bt_uuid_str(&u.uuid));
 
-    /* Check if there is a least one descriptor in the response */
-    if (length < len) {
-        goto done;
+    /* Skip if UUID is set but doesn't match */
+    if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
+      continue;
     }
 
-    /* Parse descriptors found */
-    for (i = length / len, pdu = rsp->info; i != 0;
-         i--, pdu = (const u8_t *)pdu + len) {
-        struct bt_gatt_attr *attr;
-
-        info.i16 = pdu;
-        handle = sys_le16_to_cpu(info.i16->handle);
-
-        if (skip) {
-            skip = false;
-            continue;
-        }
-
-        switch (u.uuid.type) {
-            case BT_UUID_TYPE_16:
-                u.u16.val = sys_le16_to_cpu(info.i16->uuid);
-                break;
-            case BT_UUID_TYPE_128:
-                memcpy(u.u128.val, info.i128->uuid, 16);
-                break;
-        }
-
-        BT_DBG("handle 0x%04x uuid %s", handle, bt_uuid_str(&u.uuid));
-
-        /* Skip if UUID is set but doesn't match */
-        if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
-            continue;
-        }
+    if (params->type == BT_GATT_DISCOVER_DESCRIPTOR) {
+      /* Skip attributes that are not considered
+       * descriptors.
+       */
+      if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_PRIMARY) || !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_SECONDARY) || !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_INCLUDE)) {
+        continue;
+      }
 
-        if (params->type == BT_GATT_DISCOVER_DESCRIPTOR) {
-            /* Skip attributes that are not considered
-			 * descriptors.
-			 */
-            if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_PRIMARY) ||
-                !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_SECONDARY) ||
-                !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_INCLUDE)) {
-                continue;
-            }
-
-            /* If Characteristic Declaration skip ahead as the next
-			 * entry must be its value.
-			 */
-            if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_CHRC)) {
-                skip = true;
-                continue;
-            }
-        }
+      /* If Characteristic Declaration skip ahead as the next
+       * entry must be its value.
+       */
+      if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_CHRC)) {
+        skip = true;
+        continue;
+      }
+    }
 
-        attr = (&(struct bt_gatt_attr)
-                    BT_GATT_DESCRIPTOR(&u.uuid, 0, NULL, NULL, NULL));
-        attr->handle = handle;
+    attr         = (&(struct bt_gatt_attr)BT_GATT_DESCRIPTOR(&u.uuid, 0, NULL, NULL, NULL));
+    attr->handle = handle;
 
-        if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
-            return;
-        }
+    if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
+      return;
     }
+  }
 
-    gatt_discover_next(conn, handle, params);
+  gatt_discover_next(conn, handle, params);
 
-    return;
+  return;
 
 done:
-    params->func(conn, NULL, params);
+  params->func(conn, NULL, params);
 }
 
-static int gatt_find_info(struct bt_conn *conn,
-                          struct bt_gatt_discover_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_find_info_req *req;
+static int gatt_find_info(struct bt_conn *conn, struct bt_gatt_discover_params *params) {
+  struct net_buf              *buf;
+  struct bt_att_find_info_req *req;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_INFO_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_INFO_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->start_handle = sys_cpu_to_le16(params->start_handle);
-    req->end_handle = sys_cpu_to_le16(params->end_handle);
+  req               = net_buf_add(buf, sizeof(*req));
+  req->start_handle = sys_cpu_to_le16(params->start_handle);
+  req->end_handle   = sys_cpu_to_le16(params->end_handle);
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle,
-           params->end_handle);
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, params->end_handle);
 
-    return gatt_send(conn, buf, gatt_find_info_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_find_info_rsp, params, NULL);
 }
 
-int bt_gatt_discover(struct bt_conn *conn,
-                     struct bt_gatt_discover_params *params)
-{
-    __ASSERT(conn, "invalid parameters\n");
-    __ASSERT(params && params->func, "invalid parameters\n");
-    __ASSERT((params->start_handle && params->end_handle),
-             "invalid parameters\n");
-    __ASSERT((params->start_handle <= params->end_handle),
-             "invalid parameters\n");
+int bt_gatt_discover(struct bt_conn *conn, struct bt_gatt_discover_params *params) {
+  __ASSERT(conn, "invalid parameters\n");
+  __ASSERT(params && params->func, "invalid parameters\n");
+  __ASSERT((params->start_handle && params->end_handle), "invalid parameters\n");
+  __ASSERT((params->start_handle <= params->end_handle), "invalid parameters\n");
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    switch (params->type) {
-        case BT_GATT_DISCOVER_PRIMARY:
-        case BT_GATT_DISCOVER_SECONDARY:
-            if (params->uuid) {
-                return gatt_find_type(conn, params);
-            }
-            return gatt_read_group(conn, params);
-        case BT_GATT_DISCOVER_INCLUDE:
-        case BT_GATT_DISCOVER_CHARACTERISTIC:
-            return gatt_read_type(conn, params);
-        case BT_GATT_DISCOVER_DESCRIPTOR:
-            /* Only descriptors can be filtered */
-            if (params->uuid &&
-                (!bt_uuid_cmp(params->uuid, BT_UUID_GATT_PRIMARY) ||
-                 !bt_uuid_cmp(params->uuid, BT_UUID_GATT_SECONDARY) ||
-                 !bt_uuid_cmp(params->uuid, BT_UUID_GATT_INCLUDE) ||
-                 !bt_uuid_cmp(params->uuid, BT_UUID_GATT_CHRC))) {
-                return -EINVAL;
-            }
+  switch (params->type) {
+  case BT_GATT_DISCOVER_PRIMARY:
+  case BT_GATT_DISCOVER_SECONDARY:
+    if (params->uuid) {
+      return gatt_find_type(conn, params);
+    }
+    return gatt_read_group(conn, params);
+  case BT_GATT_DISCOVER_INCLUDE:
+  case BT_GATT_DISCOVER_CHARACTERISTIC:
+    return gatt_read_type(conn, params);
+  case BT_GATT_DISCOVER_DESCRIPTOR:
+    /* Only descriptors can be filtered */
+    if (params->uuid
+        && (!bt_uuid_cmp(params->uuid, BT_UUID_GATT_PRIMARY) || !bt_uuid_cmp(params->uuid, BT_UUID_GATT_SECONDARY) || !bt_uuid_cmp(params->uuid, BT_UUID_GATT_INCLUDE)
+            || !bt_uuid_cmp(params->uuid, BT_UUID_GATT_CHRC))) {
+      return -EINVAL;
+    }
 
 #if defined(BFLB_BLE)
-            __attribute__((fallthrough));
+    __attribute__((fallthrough));
 #endif
 
-            /* Fallthrough. */
-        case BT_GATT_DISCOVER_ATTRIBUTE:
-            return gatt_find_info(conn, params);
-        default:
-            BT_ERR("Invalid discovery type: %u", params->type);
-    }
+    /* Fallthrough. */
+  case BT_GATT_DISCOVER_ATTRIBUTE:
+    return gatt_find_info(conn, params);
+  default:
+    BT_ERR("Invalid discovery type: %u", params->type);
+  }
 
-    return -EINVAL;
+  return -EINVAL;
 }
 
-static void parse_read_by_uuid(struct bt_conn *conn,
-                               struct bt_gatt_read_params *params,
-                               const void *pdu, u16_t length)
-{
-    const struct bt_att_read_type_rsp *rsp = pdu;
+static void parse_read_by_uuid(struct bt_conn *conn, struct bt_gatt_read_params *params, const void *pdu, u16_t length) {
+  const struct bt_att_read_type_rsp *rsp = pdu;
 
-    /* Parse values found */
-    for (length--, pdu = rsp->data; length;
-         length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
-        const struct bt_att_data *data = pdu;
-        u16_t handle;
-        u16_t len;
+  /* Parse values found */
+  for (length--, pdu = rsp->data; length; length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
+    const struct bt_att_data *data = pdu;
+    u16_t                     handle;
+    u16_t                     len;
 
-        handle = sys_le16_to_cpu(data->handle);
+    handle = sys_le16_to_cpu(data->handle);
 
-        /* Handle 0 is invalid */
-        if (!handle) {
-            BT_ERR("Invalid handle");
-            return;
-        }
-
-        len = rsp->len > length ? length - 2 : rsp->len - 2;
-
-        BT_DBG("handle 0x%04x len %u value %u", handle, rsp->len, len);
+    /* Handle 0 is invalid */
+    if (!handle) {
+      BT_ERR("Invalid handle");
+      return;
+    }
 
-        /* Update start_handle */
-        params->by_uuid.start_handle = handle;
+    len = rsp->len > length ? length - 2 : rsp->len - 2;
 
-        if (params->func(conn, 0, params, data->value, len) ==
-            BT_GATT_ITER_STOP) {
-            return;
-        }
+    BT_DBG("handle 0x%04x len %u value %u", handle, rsp->len, len);
 
-        /* Check if long attribute */
-        if (rsp->len > length) {
-            break;
-        }
+    /* Update start_handle */
+    params->by_uuid.start_handle = handle;
 
-        /* Stop if it's the last handle to be read */
-        if (params->by_uuid.start_handle == params->by_uuid.end_handle) {
-            params->func(conn, 0, params, NULL, 0);
-            return;
-        }
+    if (params->func(conn, 0, params, data->value, len) == BT_GATT_ITER_STOP) {
+      return;
+    }
 
-        params->by_uuid.start_handle++;
+    /* Check if long attribute */
+    if (rsp->len > length) {
+      break;
     }
 
-    /* Continue reading the attributes */
-    if (bt_gatt_read(conn, params) < 0) {
-        params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0);
+    /* Stop if it's the last handle to be read */
+    if (params->by_uuid.start_handle == params->by_uuid.end_handle) {
+      params->func(conn, 0, params, NULL, 0);
+      return;
     }
-}
 
-static void gatt_read_rsp(struct bt_conn *conn, u8_t err, const void *pdu,
-                          u16_t length, void *user_data)
-{
-    struct bt_gatt_read_params *params = user_data;
+    params->by_uuid.start_handle++;
+  }
 
-    BT_DBG("err 0x%02x", err);
+  /* Continue reading the attributes */
+  if (bt_gatt_read(conn, params) < 0) {
+    params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0);
+  }
+}
 
-    if (err || !length) {
-        params->func(conn, err, params, NULL, 0);
-        return;
-    }
+static void gatt_read_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_read_params *params = user_data;
 
-    if (!params->handle_count) {
-        parse_read_by_uuid(conn, params, pdu, length);
-        return;
-    }
+  BT_DBG("err 0x%02x", err);
 
-    if (params->func(conn, 0, params, pdu, length) == BT_GATT_ITER_STOP) {
-        return;
-    }
+  if (err || !length) {
+    params->func(conn, err, params, NULL, 0);
+    return;
+  }
 
-    /*
-	 * Core Spec 4.2, Vol. 3, Part G, 4.8.1
-	 * If the Characteristic Value is greater than (ATT_MTU - 1) octets
-	 * in length, the Read Long Characteristic Value procedure may be used
-	 * if the rest of the Characteristic Value is required.
-	 */
-    if (length < (bt_att_get_mtu(conn) - 1)) {
-        params->func(conn, 0, params, NULL, 0);
-        return;
-    }
+  if (!params->handle_count) {
+    parse_read_by_uuid(conn, params, pdu, length);
+    return;
+  }
+
+  if (params->func(conn, 0, params, pdu, length) == BT_GATT_ITER_STOP) {
+    return;
+  }
+
+  /*
+   * Core Spec 4.2, Vol. 3, Part G, 4.8.1
+   * If the Characteristic Value is greater than (ATT_MTU - 1) octets
+   * in length, the Read Long Characteristic Value procedure may be used
+   * if the rest of the Characteristic Value is required.
+   */
+  if (length < (bt_att_get_mtu(conn) - 1)) {
+    params->func(conn, 0, params, NULL, 0);
+    return;
+  }
 
-    params->single.offset += length;
+  params->single.offset += length;
 
-    /* Continue reading the attribute */
-    if (bt_gatt_read(conn, params) < 0) {
-        params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0);
-    }
+  /* Continue reading the attribute */
+  if (bt_gatt_read(conn, params) < 0) {
+    params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0);
+  }
 }
 
-static int gatt_read_blob(struct bt_conn *conn,
-                          struct bt_gatt_read_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_read_blob_req *req;
+static int gatt_read_blob(struct bt_conn *conn, struct bt_gatt_read_params *params) {
+  struct net_buf              *buf;
+  struct bt_att_read_blob_req *req;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_BLOB_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_BLOB_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->handle = sys_cpu_to_le16(params->single.handle);
-    req->offset = sys_cpu_to_le16(params->single.offset);
+  req         = net_buf_add(buf, sizeof(*req));
+  req->handle = sys_cpu_to_le16(params->single.handle);
+  req->offset = sys_cpu_to_le16(params->single.offset);
 
-    BT_DBG("handle 0x%04x offset 0x%04x", params->single.handle,
-           params->single.offset);
+  BT_DBG("handle 0x%04x offset 0x%04x", params->single.handle, params->single.offset);
 
-    return gatt_send(conn, buf, gatt_read_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_read_rsp, params, NULL);
 }
 
-static int gatt_read_uuid(struct bt_conn *conn,
-                          struct bt_gatt_read_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_read_type_req *req;
+static int gatt_read_uuid(struct bt_conn *conn, struct bt_gatt_read_params *params) {
+  struct net_buf              *buf;
+  struct bt_att_read_type_req *req;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->start_handle = sys_cpu_to_le16(params->by_uuid.start_handle);
-    req->end_handle = sys_cpu_to_le16(params->by_uuid.end_handle);
+  req               = net_buf_add(buf, sizeof(*req));
+  req->start_handle = sys_cpu_to_le16(params->by_uuid.start_handle);
+  req->end_handle   = sys_cpu_to_le16(params->by_uuid.end_handle);
 
-    if (params->by_uuid.uuid->type == BT_UUID_TYPE_16) {
-        net_buf_add_le16(buf, BT_UUID_16(params->by_uuid.uuid)->val);
-    } else {
-        net_buf_add_mem(buf, BT_UUID_128(params->by_uuid.uuid)->val, 16);
-    }
+  if (params->by_uuid.uuid->type == BT_UUID_TYPE_16) {
+    net_buf_add_le16(buf, BT_UUID_16(params->by_uuid.uuid)->val);
+  } else {
+    net_buf_add_mem(buf, BT_UUID_128(params->by_uuid.uuid)->val, 16);
+  }
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s",
-           params->by_uuid.start_handle, params->by_uuid.end_handle,
-           bt_uuid_str(params->by_uuid.uuid));
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s", params->by_uuid.start_handle, params->by_uuid.end_handle, bt_uuid_str(params->by_uuid.uuid));
 
-    return gatt_send(conn, buf, gatt_read_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_read_rsp, params, NULL);
 }
 
 #if defined(CONFIG_BT_GATT_READ_MULTIPLE)
-static void gatt_read_multiple_rsp(struct bt_conn *conn, u8_t err,
-                                   const void *pdu, u16_t length,
-                                   void *user_data)
-{
-    struct bt_gatt_read_params *params = user_data;
+static void gatt_read_multiple_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_read_params *params = user_data;
 
-    BT_DBG("err 0x%02x", err);
+  BT_DBG("err 0x%02x", err);
 
-    if (err || !length) {
-        params->func(conn, err, params, NULL, 0);
-        return;
-    }
+  if (err || !length) {
+    params->func(conn, err, params, NULL, 0);
+    return;
+  }
 
-    params->func(conn, 0, params, pdu, length);
+  params->func(conn, 0, params, pdu, length);
 
-    /* mark read as complete since read multiple is single response */
-    params->func(conn, 0, params, NULL, 0);
+  /* mark read as complete since read multiple is single response */
+  params->func(conn, 0, params, NULL, 0);
 }
 
-static int gatt_read_multiple(struct bt_conn *conn,
-                              struct bt_gatt_read_params *params)
-{
-    struct net_buf *buf;
-    u8_t i;
+static int gatt_read_multiple(struct bt_conn *conn, struct bt_gatt_read_params *params) {
+  struct net_buf *buf;
+  u8_t            i;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_REQ,
-                            params->handle_count * sizeof(u16_t));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_REQ, params->handle_count * sizeof(u16_t));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    for (i = 0U; i < params->handle_count; i++) {
-        net_buf_add_le16(buf, params->handles[i]);
-    }
+  for (i = 0U; i < params->handle_count; i++) {
+    net_buf_add_le16(buf, params->handles[i]);
+  }
 
-    return gatt_send(conn, buf, gatt_read_multiple_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_read_multiple_rsp, params, NULL);
 }
 #else
-static int gatt_read_multiple(struct bt_conn *conn,
-                              struct bt_gatt_read_params *params)
-{
-    return -ENOTSUP;
-}
+static int gatt_read_multiple(struct bt_conn *conn, struct bt_gatt_read_params *params) { return -ENOTSUP; }
 #endif /* CONFIG_BT_GATT_READ_MULTIPLE */
 
-int bt_gatt_read(struct bt_conn *conn, struct bt_gatt_read_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_read_req *req;
+int bt_gatt_read(struct bt_conn *conn, struct bt_gatt_read_params *params) {
+  struct net_buf         *buf;
+  struct bt_att_read_req *req;
 
-    __ASSERT(conn, "invalid parameters\n");
-    __ASSERT(params && params->func, "invalid parameters\n");
+  __ASSERT(conn, "invalid parameters\n");
+  __ASSERT(params && params->func, "invalid parameters\n");
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    if (params->handle_count == 0) {
-        return gatt_read_uuid(conn, params);
-    }
+  if (params->handle_count == 0) {
+    return gatt_read_uuid(conn, params);
+  }
 
-    if (params->handle_count > 1) {
-        return gatt_read_multiple(conn, params);
-    }
+  if (params->handle_count > 1) {
+    return gatt_read_multiple(conn, params);
+  }
 
-    if (params->single.offset) {
-        return gatt_read_blob(conn, params);
-    }
+  if (params->single.offset) {
+    return gatt_read_blob(conn, params);
+  }
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->handle = sys_cpu_to_le16(params->single.handle);
+  req         = net_buf_add(buf, sizeof(*req));
+  req->handle = sys_cpu_to_le16(params->single.handle);
 
-    BT_DBG("handle 0x%04x", params->single.handle);
+  BT_DBG("handle 0x%04x", params->single.handle);
 
-    return gatt_send(conn, buf, gatt_read_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_read_rsp, params, NULL);
 }
 
-static void gatt_write_rsp(struct bt_conn *conn, u8_t err, const void *pdu,
-                           u16_t length, void *user_data)
-{
-    struct bt_gatt_write_params *params = user_data;
+static void gatt_write_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_write_params *params = user_data;
 
-    BT_DBG("err 0x%02x", err);
+  BT_DBG("err 0x%02x", err);
 
-    params->func(conn, err, params);
+  params->func(conn, err, params);
 }
 
-int bt_gatt_write_without_response_cb(struct bt_conn *conn, u16_t handle,
-                                      const void *data, u16_t length, bool sign,
-                                      bt_gatt_complete_func_t func,
-                                      void *user_data)
-{
-    struct net_buf *buf;
-    struct bt_att_write_cmd *cmd;
+int bt_gatt_write_without_response_cb(struct bt_conn *conn, u16_t handle, const void *data, u16_t length, bool sign, bt_gatt_complete_func_t func, void *user_data) {
+  struct net_buf          *buf;
+  struct bt_att_write_cmd *cmd;
 
-    __ASSERT(conn, "invalid parameters\n");
-    __ASSERT(handle, "invalid parameters\n");
+  __ASSERT(conn, "invalid parameters\n");
+  __ASSERT(handle, "invalid parameters\n");
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
 #if defined(CONFIG_BT_SMP)
-    if (conn->encrypt) {
-        /* Don't need to sign if already encrypted */
-        sign = false;
-    }
+  if (conn->encrypt) {
+    /* Don't need to sign if already encrypted */
+    sign = false;
+  }
 #endif
 
-    if (sign) {
-        buf = bt_att_create_pdu(conn, BT_ATT_OP_SIGNED_WRITE_CMD,
-                                sizeof(*cmd) + length + 12);
-    } else {
-        buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_CMD,
-                                sizeof(*cmd) + length);
-    }
-    if (!buf) {
-        return -ENOMEM;
-    }
+  if (sign) {
+    buf = bt_att_create_pdu(conn, BT_ATT_OP_SIGNED_WRITE_CMD, sizeof(*cmd) + length + 12);
+  } else {
+    buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_CMD, sizeof(*cmd) + length);
+  }
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    cmd = net_buf_add(buf, sizeof(*cmd));
-    cmd->handle = sys_cpu_to_le16(handle);
-    memcpy(cmd->value, data, length);
-    net_buf_add(buf, length);
+  cmd         = net_buf_add(buf, sizeof(*cmd));
+  cmd->handle = sys_cpu_to_le16(handle);
+  memcpy(cmd->value, data, length);
+  net_buf_add(buf, length);
 
-    BT_DBG("handle 0x%04x length %u", handle, length);
+  BT_DBG("handle 0x%04x length %u", handle, length);
 
-    return bt_att_send(conn, buf, func, user_data);
+  return bt_att_send(conn, buf, func, user_data);
 }
 
-static int gatt_exec_write(struct bt_conn *conn,
-                           struct bt_gatt_write_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_exec_write_req *req;
+static int gatt_exec_write(struct bt_conn *conn, struct bt_gatt_write_params *params) {
+  struct net_buf               *buf;
+  struct bt_att_exec_write_req *req;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_EXEC_WRITE_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_EXEC_WRITE_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
+  req = net_buf_add(buf, sizeof(*req));
 #if defined(CONFIG_BT_STACK_PTS)
-    if (event_flag == gatt_cancel_write_req)
-        req->flags = BT_ATT_FLAG_CANCEL;
-    else
-        req->flags = BT_ATT_FLAG_EXEC;
-#else
+  if (event_flag == gatt_cancel_write_req)
+    req->flags = BT_ATT_FLAG_CANCEL;
+  else
     req->flags = BT_ATT_FLAG_EXEC;
+#else
+  req->flags = BT_ATT_FLAG_EXEC;
 #endif
 
-    BT_DBG("");
+  BT_DBG("");
 
-    return gatt_send(conn, buf, gatt_write_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_write_rsp, params, NULL);
 }
 
-static void gatt_prepare_write_rsp(struct bt_conn *conn, u8_t err,
-                                   const void *pdu, u16_t length,
-                                   void *user_data)
-{
-    struct bt_gatt_write_params *params = user_data;
+static void gatt_prepare_write_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_write_params *params = user_data;
 
-    BT_DBG("err 0x%02x", err);
+  BT_DBG("err 0x%02x", err);
 
-    /* Don't continue in case of error */
-    if (err) {
-        params->func(conn, err, params);
-        return;
-    }
-    /* If there is no more data execute */
-    if (!params->length) {
-        gatt_exec_write(conn, params);
-        return;
-    }
+  /* Don't continue in case of error */
+  if (err) {
+    params->func(conn, err, params);
+    return;
+  }
+  /* If there is no more data execute */
+  if (!params->length) {
+    gatt_exec_write(conn, params);
+    return;
+  }
 
-    /* Write next chunk */
-    bt_gatt_write(conn, params);
+  /* Write next chunk */
+  bt_gatt_write(conn, params);
 }
 
-static int gatt_prepare_write(struct bt_conn *conn,
-                              struct bt_gatt_write_params *params)
+static int gatt_prepare_write(struct bt_conn *conn, struct bt_gatt_write_params *params)
 
 {
-    struct net_buf *buf;
-    struct bt_att_prepare_write_req *req;
-    u16_t len;
+  struct net_buf                  *buf;
+  struct bt_att_prepare_write_req *req;
+  u16_t                            len;
 
-    len = MIN(params->length, bt_att_get_mtu(conn) - sizeof(*req) - 1);
+  len = MIN(params->length, bt_att_get_mtu(conn) - sizeof(*req) - 1);
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_PREPARE_WRITE_REQ,
-                            sizeof(*req) + len);
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_PREPARE_WRITE_REQ, sizeof(*req) + len);
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->handle = sys_cpu_to_le16(params->handle);
-    req->offset = sys_cpu_to_le16(params->offset);
-    memcpy(req->value, params->data, len);
-    net_buf_add(buf, len);
+  req         = net_buf_add(buf, sizeof(*req));
+  req->handle = sys_cpu_to_le16(params->handle);
+  req->offset = sys_cpu_to_le16(params->offset);
+  memcpy(req->value, params->data, len);
+  net_buf_add(buf, len);
 
-    /* Update params */
-    params->offset += len;
-    params->data = (const u8_t *)params->data + len;
-    params->length -= len;
+  /* Update params */
+  params->offset += len;
+  params->data = (const u8_t *)params->data + len;
+  params->length -= len;
 
-    BT_DBG("handle 0x%04x offset %u len %u", params->handle, params->offset,
-           params->length);
+  BT_DBG("handle 0x%04x offset %u len %u", params->handle, params->offset, params->length);
 
-    return gatt_send(conn, buf, gatt_prepare_write_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_prepare_write_rsp, params, NULL);
 }
 
 #if defined(CONFIG_BT_STACK_PTS)
-int bt_gatt_prepare_write(struct bt_conn *conn,
-                          struct bt_gatt_write_params *params)
-{
-    return gatt_prepare_write(conn, params);
-}
+int bt_gatt_prepare_write(struct bt_conn *conn, struct bt_gatt_write_params *params) { return gatt_prepare_write(conn, params); }
 #endif
 
-int bt_gatt_write(struct bt_conn *conn, struct bt_gatt_write_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_write_req *req;
-
-    __ASSERT(conn, "invalid parameters\n");
-    __ASSERT(params && params->func, "invalid parameters\n");
-    __ASSERT(params->handle, "invalid parameters\n");
+int bt_gatt_write(struct bt_conn *conn, struct bt_gatt_write_params *params) {
+  struct net_buf          *buf;
+  struct bt_att_write_req *req;
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  __ASSERT(conn, "invalid parameters\n");
+  __ASSERT(params && params->func, "invalid parameters\n");
+  __ASSERT(params->handle, "invalid parameters\n");
 
-    /* Use Prepare Write if offset is set or Long Write is required */
-    if (params->offset ||
-        params->length > (bt_att_get_mtu(conn) - sizeof(*req) - 1)) {
-        return gatt_prepare_write(conn, params);
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_REQ,
-                            sizeof(*req) + params->length);
-    if (!buf) {
-        return -ENOMEM;
-    }
-
-    req = net_buf_add(buf, sizeof(*req));
-    req->handle = sys_cpu_to_le16(params->handle);
-    memcpy(req->value, params->data, params->length);
-    net_buf_add(buf, params->length);
-
-    BT_DBG("handle 0x%04x length %u", params->handle, params->length);
-
-    return gatt_send(conn, buf, gatt_write_rsp, params, NULL);
-}
-
-static void gatt_subscription_add(struct bt_conn *conn,
-                                  struct bt_gatt_subscribe_params *params)
-{
-    bt_addr_le_copy(¶ms->_peer, &conn->le.dst);
-
-    /* Prepend subscription */
-    sys_slist_prepend(&subscriptions, ¶ms->node);
-}
-
-static void gatt_write_ccc_rsp(struct bt_conn *conn, u8_t err,
-                               const void *pdu, u16_t length,
-                               void *user_data)
-{
-    struct bt_gatt_subscribe_params *params = user_data;
-
-    BT_DBG("err 0x%02x", err);
+  /* Use Prepare Write if offset is set or Long Write is required */
+  if (params->offset || params->length > (bt_att_get_mtu(conn) - sizeof(*req) - 1)) {
+    return gatt_prepare_write(conn, params);
+  }
 
-    atomic_clear_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING);
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_REQ, sizeof(*req) + params->length);
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    /* if write to CCC failed we remove subscription and notify app */
-    if (err) {
-        sys_snode_t *node, *tmp, *prev = NULL;
-        UNUSED(prev);
+  req         = net_buf_add(buf, sizeof(*req));
+  req->handle = sys_cpu_to_le16(params->handle);
+  memcpy(req->value, params->data, params->length);
+  net_buf_add(buf, params->length);
 
-        SYS_SLIST_FOR_EACH_NODE_SAFE(&subscriptions, node, tmp)
-        {
-            if (node == ¶ms->node) {
-                gatt_subscription_remove(conn, tmp, params);
-                break;
-            }
+  BT_DBG("handle 0x%04x length %u", params->handle, params->length);
 
-            prev = node;
-        }
-    } else if (!params->value) {
-        /* Notify with NULL data to complete unsubscribe */
-        params->notify(conn, params, NULL, 0);
-    }
-#if defined(BFLB_BLE_PATCH_NOTIFY_WRITE_CCC_RSP)
-    else {
-        params->notify(conn, params, NULL, 0);
-    }
-#endif
+  return gatt_send(conn, buf, gatt_write_rsp, params, NULL);
 }
 
-static int gatt_write_ccc(struct bt_conn *conn, u16_t handle, u16_t value,
-                          bt_att_func_t func,
-                          struct bt_gatt_subscribe_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_write_req *req;
-
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_REQ,
-                            sizeof(*req) + sizeof(u16_t));
-    if (!buf) {
-        return -ENOMEM;
-    }
+static void gatt_subscription_add(struct bt_conn *conn, struct bt_gatt_subscribe_params *params) {
+  bt_addr_le_copy(¶ms->_peer, &conn->le.dst);
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->handle = sys_cpu_to_le16(handle);
-    net_buf_add_le16(buf, value);
+  /* Prepend subscription */
+  sys_slist_prepend(&subscriptions, ¶ms->node);
+}
 
-    BT_DBG("handle 0x%04x value 0x%04x", handle, value);
+static void gatt_write_ccc_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_subscribe_params *params = user_data;
 
-    atomic_set_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING);
+  BT_DBG("err 0x%02x", err);
 
-    return gatt_send(conn, buf, func, params, NULL);
-}
+  atomic_clear_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING);
 
-int bt_gatt_subscribe(struct bt_conn *conn,
-                      struct bt_gatt_subscribe_params *params)
-{
-    struct bt_gatt_subscribe_params *tmp;
-    bool has_subscription = false;
+  /* if write to CCC failed we remove subscription and notify app */
+  if (err) {
+    sys_snode_t *node, *tmp, *prev = NULL;
+    UNUSED(prev);
 
-    __ASSERT(conn, "invalid parameters\n");
-    __ASSERT(params && params->notify, "invalid parameters\n");
-    __ASSERT(params->value, "invalid parameters\n");
-    __ASSERT(params->ccc_handle, "invalid parameters\n");
+    SYS_SLIST_FOR_EACH_NODE_SAFE(&subscriptions, node, tmp) {
+      if (node == ¶ms->node) {
+        gatt_subscription_remove(conn, tmp, params);
+        break;
+      }
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
+      prev = node;
     }
+  } else if (!params->value) {
+    /* Notify with NULL data to complete unsubscribe */
+    params->notify(conn, params, NULL, 0);
+  }
+#if defined(BFLB_BLE_PATCH_NOTIFY_WRITE_CCC_RSP)
+  else {
+    params->notify(conn, params, NULL, 0);
+  }
+#endif
+}
 
-    /* Lookup existing subscriptions */
-    SYS_SLIST_FOR_EACH_CONTAINER(&subscriptions, tmp, node)
-    {
-        /* Fail if entry already exists */
-        if (tmp == params) {
-            return -EALREADY;
-        }
+static int gatt_write_ccc(struct bt_conn *conn, u16_t handle, u16_t value, bt_att_func_t func, struct bt_gatt_subscribe_params *params) {
+  struct net_buf          *buf;
+  struct bt_att_write_req *req;
 
-        /* Check if another subscription exists */
-        if (!bt_conn_addr_le_cmp(conn, &tmp->_peer) &&
-            tmp->value_handle == params->value_handle &&
-            tmp->value >= params->value) {
-            has_subscription = true;
-        }
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_REQ, sizeof(*req) + sizeof(u16_t));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    /* Skip write if already subscribed */
-    if (!has_subscription) {
-        int err;
+  req         = net_buf_add(buf, sizeof(*req));
+  req->handle = sys_cpu_to_le16(handle);
+  net_buf_add_le16(buf, value);
 
-        err = gatt_write_ccc(conn, params->ccc_handle, params->value,
-                             gatt_write_ccc_rsp, params);
-        if (err) {
-            return err;
-        }
-    }
+  BT_DBG("handle 0x%04x value 0x%04x", handle, value);
 
-    /*
-	 * Add subscription before write complete as some implementation were
-	 * reported to send notification before reply to CCC write.
-	 */
-    gatt_subscription_add(conn, params);
+  atomic_set_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING);
 
-    return 0;
+  return gatt_send(conn, buf, func, params, NULL);
 }
 
-int bt_gatt_unsubscribe(struct bt_conn *conn,
-                        struct bt_gatt_subscribe_params *params)
-{
-    struct bt_gatt_subscribe_params *tmp, *next;
-    bool has_subscription = false, found = false;
-    sys_snode_t *prev = NULL;
+int bt_gatt_subscribe(struct bt_conn *conn, struct bt_gatt_subscribe_params *params) {
+  struct bt_gatt_subscribe_params *tmp;
+  bool                             has_subscription = false;
 
-    __ASSERT(conn, "invalid parameters\n");
-    __ASSERT(params, "invalid parameters\n");
+  __ASSERT(conn, "invalid parameters\n");
+  __ASSERT(params && params->notify, "invalid parameters\n");
+  __ASSERT(params->value, "invalid parameters\n");
+  __ASSERT(params->ccc_handle, "invalid parameters\n");
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    /* Lookup existing subscriptions */
-    SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, tmp, next, node)
-    {
-        /* Remove subscription */
-        if (params == tmp) {
-            found = true;
-            sys_slist_remove(&subscriptions, prev, &tmp->node);
-            /* Attempt to cancel if write is pending */
-            if (atomic_test_bit(params->flags,
-                                BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING)) {
-                bt_gatt_cancel(conn, params);
-            }
-            continue;
-        } else {
-            prev = &tmp->node;
-        }
+  /* Lookup existing subscriptions */
+  SYS_SLIST_FOR_EACH_CONTAINER(&subscriptions, tmp, node) {
+    /* Fail if entry already exists */
+    if (tmp == params) {
+      return -EALREADY;
+    }
 
-        /* Check if there still remains any other subscription */
-        if (!bt_conn_addr_le_cmp(conn, &tmp->_peer) &&
-            tmp->value_handle == params->value_handle) {
-            has_subscription = true;
-        }
+    /* Check if another subscription exists */
+    if (!bt_conn_addr_le_cmp(conn, &tmp->_peer) && tmp->value_handle == params->value_handle && tmp->value >= params->value) {
+      has_subscription = true;
     }
+  }
+
+  /* Skip write if already subscribed */
+  if (!has_subscription) {
+    int err;
 
-    if (!found) {
-        return -EINVAL;
+    err = gatt_write_ccc(conn, params->ccc_handle, params->value, gatt_write_ccc_rsp, params);
+    if (err) {
+      return err;
+    }
+  }
+
+  /*
+   * Add subscription before write complete as some implementation were
+   * reported to send notification before reply to CCC write.
+   */
+  gatt_subscription_add(conn, params);
+
+  return 0;
+}
+
+int bt_gatt_unsubscribe(struct bt_conn *conn, struct bt_gatt_subscribe_params *params) {
+  struct bt_gatt_subscribe_params *tmp, *next;
+  bool                             has_subscription = false, found = false;
+  sys_snode_t                     *prev = NULL;
+
+  __ASSERT(conn, "invalid parameters\n");
+  __ASSERT(params, "invalid parameters\n");
+
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
+
+  /* Lookup existing subscriptions */
+  SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, tmp, next, node) {
+    /* Remove subscription */
+    if (params == tmp) {
+      found = true;
+      sys_slist_remove(&subscriptions, prev, &tmp->node);
+      /* Attempt to cancel if write is pending */
+      if (atomic_test_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING)) {
+        bt_gatt_cancel(conn, params);
+      }
+      continue;
+    } else {
+      prev = &tmp->node;
     }
 
-    if (has_subscription) {
-        /* Notify with NULL data to complete unsubscribe */
-        params->notify(conn, params, NULL, 0);
-        return 0;
+    /* Check if there still remains any other subscription */
+    if (!bt_conn_addr_le_cmp(conn, &tmp->_peer) && tmp->value_handle == params->value_handle) {
+      has_subscription = true;
     }
+  }
 
-    params->value = 0x0000;
+  if (!found) {
+    return -EINVAL;
+  }
 
-    return gatt_write_ccc(conn, params->ccc_handle, params->value,
-                          gatt_write_ccc_rsp, params);
-}
+  if (has_subscription) {
+    /* Notify with NULL data to complete unsubscribe */
+    params->notify(conn, params, NULL, 0);
+    return 0;
+  }
 
-void bt_gatt_cancel(struct bt_conn *conn, void *params)
-{
-    bt_att_req_cancel(conn, params);
+  params->value = 0x0000;
+
+  return gatt_write_ccc(conn, params->ccc_handle, params->value, gatt_write_ccc_rsp, params);
 }
 
-static void add_subscriptions(struct bt_conn *conn)
-{
-    struct bt_gatt_subscribe_params *params;
+void bt_gatt_cancel(struct bt_conn *conn, void *params) { bt_att_req_cancel(conn, params); }
 
-    /* Lookup existing subscriptions */
-    SYS_SLIST_FOR_EACH_CONTAINER(&subscriptions, params, node)
-    {
-        if (bt_conn_addr_le_cmp(conn, ¶ms->_peer)) {
-            continue;
-        }
+static void add_subscriptions(struct bt_conn *conn) {
+  struct bt_gatt_subscribe_params *params;
 
-        /* Force write to CCC to workaround devices that don't track
-		 * it properly.
-		 */
-        gatt_write_ccc(conn, params->ccc_handle, params->value,
-                       gatt_write_ccc_rsp, params);
+  /* Lookup existing subscriptions */
+  SYS_SLIST_FOR_EACH_CONTAINER(&subscriptions, params, node) {
+    if (bt_conn_addr_le_cmp(conn, ¶ms->_peer)) {
+      continue;
     }
+
+    /* Force write to CCC to workaround devices that don't track
+     * it properly.
+     */
+    gatt_write_ccc(conn, params->ccc_handle, params->value, gatt_write_ccc_rsp, params);
+  }
 }
 
 #endif /* CONFIG_BT_GATT_CLIENT */
 
 #define CCC_STORE_MAX 48
 
-static struct bt_gatt_ccc_cfg *ccc_find_cfg(struct _bt_gatt_ccc *ccc,
-                                            const bt_addr_le_t *addr,
-                                            u8_t id)
-{
-    for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
-        if (id == ccc->cfg[i].id &&
-            !bt_addr_le_cmp(&ccc->cfg[i].peer, addr)) {
-            return &ccc->cfg[i];
-        }
+static struct bt_gatt_ccc_cfg *ccc_find_cfg(struct _bt_gatt_ccc *ccc, const bt_addr_le_t *addr, u8_t id) {
+  for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
+    if (id == ccc->cfg[i].id && !bt_addr_le_cmp(&ccc->cfg[i].peer, addr)) {
+      return &ccc->cfg[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
 struct addr_with_id {
-    const bt_addr_le_t *addr;
-    u8_t id;
+  const bt_addr_le_t *addr;
+  u8_t                id;
 };
 
 struct ccc_load {
-    struct addr_with_id addr_with_id;
-    struct ccc_store *entry;
-    size_t count;
+  struct addr_with_id addr_with_id;
+  struct ccc_store   *entry;
+  size_t              count;
 };
 
-static void ccc_clear(struct _bt_gatt_ccc *ccc,
-                      const bt_addr_le_t *addr,
-                      u8_t id)
-{
-    struct bt_gatt_ccc_cfg *cfg;
+static void ccc_clear(struct _bt_gatt_ccc *ccc, const bt_addr_le_t *addr, u8_t id) {
+  struct bt_gatt_ccc_cfg *cfg;
 
-    cfg = ccc_find_cfg(ccc, addr, id);
-    if (!cfg) {
-        BT_DBG("Unable to clear CCC: cfg not found");
-        return;
-    }
+  cfg = ccc_find_cfg(ccc, addr, id);
+  if (!cfg) {
+    BT_DBG("Unable to clear CCC: cfg not found");
+    return;
+  }
 
-    clear_ccc_cfg(cfg);
+  clear_ccc_cfg(cfg);
 }
 
-static u8_t ccc_load(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct ccc_load *load = user_data;
-    struct _bt_gatt_ccc *ccc;
-    struct bt_gatt_ccc_cfg *cfg;
-
-    /* Check if attribute is a CCC */
-    if (attr->write != bt_gatt_attr_write_ccc) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+static u8_t ccc_load(const struct bt_gatt_attr *attr, void *user_data) {
+  struct ccc_load        *load = user_data;
+  struct _bt_gatt_ccc    *ccc;
+  struct bt_gatt_ccc_cfg *cfg;
 
-    ccc = attr->user_data;
+  /* Check if attribute is a CCC */
+  if (attr->write != bt_gatt_attr_write_ccc) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    /* Clear if value was invalidated */
-    if (!load->entry) {
-        ccc_clear(ccc, load->addr_with_id.addr, load->addr_with_id.id);
-        return BT_GATT_ITER_CONTINUE;
-    } else if (!load->count) {
-        return BT_GATT_ITER_STOP;
-    }
+  ccc = attr->user_data;
 
-    /* Skip if value is not for the given attribute */
-    if (load->entry->handle != attr->handle) {
-        /* If attribute handle is bigger then it means
-		 * the attribute no longer exists and cannot
-		 * be restored.
-		 */
-        if (load->entry->handle < attr->handle) {
-            BT_DBG("Unable to restore CCC: handle 0x%04x cannot be"
-                   " found",
-                   load->entry->handle);
-            goto next;
-        }
-        return BT_GATT_ITER_CONTINUE;
+  /* Clear if value was invalidated */
+  if (!load->entry) {
+    ccc_clear(ccc, load->addr_with_id.addr, load->addr_with_id.id);
+    return BT_GATT_ITER_CONTINUE;
+  } else if (!load->count) {
+    return BT_GATT_ITER_STOP;
+  }
+
+  /* Skip if value is not for the given attribute */
+  if (load->entry->handle != attr->handle) {
+    /* If attribute handle is bigger then it means
+     * the attribute no longer exists and cannot
+     * be restored.
+     */
+    if (load->entry->handle < attr->handle) {
+      BT_DBG("Unable to restore CCC: handle 0x%04x cannot be"
+             " found",
+             load->entry->handle);
+      goto next;
     }
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    BT_DBG("Restoring CCC: handle 0x%04x value 0x%04x", load->entry->handle,
-           load->entry->value);
+  BT_DBG("Restoring CCC: handle 0x%04x value 0x%04x", load->entry->handle, load->entry->value);
 
-    cfg = ccc_find_cfg(ccc, load->addr_with_id.addr, load->addr_with_id.id);
+  cfg = ccc_find_cfg(ccc, load->addr_with_id.addr, load->addr_with_id.id);
+  if (!cfg) {
+    cfg = ccc_find_cfg(ccc, BT_ADDR_LE_ANY, 0);
     if (!cfg) {
-        cfg = ccc_find_cfg(ccc, BT_ADDR_LE_ANY, 0);
-        if (!cfg) {
-            BT_DBG("Unable to restore CCC: no cfg left");
-            goto next;
-        }
-        bt_addr_le_copy(&cfg->peer, load->addr_with_id.addr);
-        cfg->id = load->addr_with_id.id;
+      BT_DBG("Unable to restore CCC: no cfg left");
+      goto next;
     }
+    bt_addr_le_copy(&cfg->peer, load->addr_with_id.addr);
+    cfg->id = load->addr_with_id.id;
+  }
 
-    cfg->value = load->entry->value;
+  cfg->value = load->entry->value;
 
 next:
-    load->entry++;
-    load->count--;
+  load->entry++;
+  load->count--;
 
-    return load->count ? BT_GATT_ITER_CONTINUE : BT_GATT_ITER_STOP;
+  return load->count ? BT_GATT_ITER_CONTINUE : BT_GATT_ITER_STOP;
 }
 
 #if defined(BFLB_BLE)
 static int ccc_set(const char *key, u8_t id, bt_addr_le_t *addr)
 #else
-static int ccc_set(const char *name, size_t len_rd, settings_read_cb read_cb,
-                   void *cb_arg)
+static int ccc_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
 #endif
 {
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        struct ccc_store ccc_store[CCC_STORE_MAX];
-        struct ccc_load load;
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    struct ccc_store ccc_store[CCC_STORE_MAX];
+    struct ccc_load  load;
 #if defined(BFLB_BLE)
-        size_t len;
-        int err;
+    size_t len;
+    int    err;
 #else
-        bt_addr_le_t addr;
-        const char *next;
-        int len, err;
+    bt_addr_le_t addr;
+    const char  *next;
+    int          len, err;
 #endif
 
 #if defined(BFLB_BLE)
-        err = bt_settings_get_bin(key, (u8_t *)ccc_store, CCC_STORE_MAX, &len);
-        if (err)
-            return err;
-
-        load.addr_with_id.id = id;
-        load.addr_with_id.addr = addr;
-        load.entry = ccc_store;
-        load.count = len / sizeof(*ccc_store);
+    err = bt_settings_get_bin(key, (u8_t *)ccc_store, CCC_STORE_MAX, &len);
+    if (err)
+      return err;
+
+    load.addr_with_id.id   = id;
+    load.addr_with_id.addr = addr;
+    load.entry             = ccc_store;
+    load.count             = len / sizeof(*ccc_store);
 #else
-        settings_name_next(name, &next);
-
-        if (!name) {
-            BT_ERR("Insufficient number of arguments");
-            return -EINVAL;
-        } else if (!next) {
-            load.addr_with_id.id = BT_ID_DEFAULT;
-        } else {
-            load.addr_with_id.id = strtol(next, NULL, 10);
-        }
+    settings_name_next(name, &next);
 
-        err = bt_settings_decode_key(name, &addr);
-        if (err) {
-            BT_ERR("Unable to decode address %s", log_strdup(name));
-            return -EINVAL;
-        }
+    if (!name) {
+      BT_ERR("Insufficient number of arguments");
+      return -EINVAL;
+    } else if (!next) {
+      load.addr_with_id.id = BT_ID_DEFAULT;
+    } else {
+      load.addr_with_id.id = strtol(next, NULL, 10);
+    }
+
+    err = bt_settings_decode_key(name, &addr);
+    if (err) {
+      BT_ERR("Unable to decode address %s", log_strdup(name));
+      return -EINVAL;
+    }
 
-        load.addr_with_id.addr = &addr;
+    load.addr_with_id.addr = &addr;
 
-        if (len_rd) {
-            len = read_cb(cb_arg, ccc_store, sizeof(ccc_store));
+    if (len_rd) {
+      len = read_cb(cb_arg, ccc_store, sizeof(ccc_store));
 
-            if (len < 0) {
-                BT_ERR("Failed to decode value (err %d)", len);
-                return len;
-            }
+      if (len < 0) {
+        BT_ERR("Failed to decode value (err %d)", len);
+        return len;
+      }
 
-            load.entry = ccc_store;
-            load.count = len / sizeof(*ccc_store);
+      load.entry = ccc_store;
+      load.count = len / sizeof(*ccc_store);
 
-            for (int i = 0; i < load.count; i++) {
-                BT_DBG("Read CCC: handle 0x%04x value 0x%04x",
-                       ccc_store[i].handle, ccc_store[i].value);
-            }
-        } else {
-            load.entry = NULL;
-            load.count = 0;
-        }
+      for (int i = 0; i < load.count; i++) {
+        BT_DBG("Read CCC: handle 0x%04x value 0x%04x", ccc_store[i].handle, ccc_store[i].value);
+      }
+    } else {
+      load.entry = NULL;
+      load.count = 0;
+    }
 #endif
 
-        bt_gatt_foreach_attr(0x0001, 0xffff, ccc_load, &load);
+    bt_gatt_foreach_attr(0x0001, 0xffff, ccc_load, &load);
 
-        BT_DBG("Restored CCC for id:%x"
-               "PRIu8"
-               " addr:%s",
-               load.addr_with_id.id,
-               bt_addr_le_str(load.addr_with_id.addr));
-    }
+    BT_DBG("Restored CCC for id:%x"
+           "PRIu8"
+           " addr:%s",
+           load.addr_with_id.id, bt_addr_le_str(load.addr_with_id.addr));
+  }
 
-    return 0;
+  return 0;
 }
 
 #if !defined(BFLB_BLE)
@@ -3994,23 +3577,21 @@ SETTINGS_STATIC_HANDLER_DEFINE(bt_ccc, "bt/ccc", NULL, ccc_set, NULL, NULL);
 #endif
 
 #if !defined(BFLB_BLE)
-static int ccc_set_direct(const char *key, size_t len, settings_read_cb read_cb,
-                          void *cb_arg, void *param)
-{
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        const char *name;
-
-        BT_DBG("key: %s", log_strdup((const char *)param));
+static int ccc_set_direct(const char *key, size_t len, settings_read_cb read_cb, void *cb_arg, void *param) {
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    const char *name;
 
-        /* Only "bt/ccc" settings should ever come here */
-        if (!settings_name_steq((const char *)param, "bt/ccc", &name)) {
-            BT_ERR("Invalid key");
-            return -EINVAL;
-        }
+    BT_DBG("key: %s", log_strdup((const char *)param));
 
-        return ccc_set(name, len, read_cb, cb_arg);
+    /* Only "bt/ccc" settings should ever come here */
+    if (!settings_name_steq((const char *)param, "bt/ccc", &name)) {
+      BT_ERR("Invalid key");
+      return -EINVAL;
     }
-    return 0;
+
+    return ccc_set(name, len, read_cb, cb_arg);
+  }
+  return 0;
 }
 #endif
 
@@ -4022,566 +3603,525 @@ static int sc_commit(void);
 #endif
 #endif
 #endif
-void bt_gatt_connected(struct bt_conn *conn)
-{
-    struct conn_data data;
+void bt_gatt_connected(struct bt_conn *conn) {
+  struct conn_data data;
 
-    BT_DBG("conn %p", conn);
+  BT_DBG("conn %p", conn);
 
-    data.conn = conn;
-    data.sec = BT_SECURITY_L1;
+  data.conn = conn;
+  data.sec  = BT_SECURITY_L1;
 
-    /* Load CCC settings from backend if bonded */
-    if (IS_ENABLED(CONFIG_BT_SETTINGS_CCC_LAZY_LOADING) &&
-        bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
-        char key[BT_SETTINGS_KEY_MAX];
+  /* Load CCC settings from backend if bonded */
+  if (IS_ENABLED(CONFIG_BT_SETTINGS_CCC_LAZY_LOADING) && bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
+    char key[BT_SETTINGS_KEY_MAX];
 
-        if (conn->id) {
-            char id_str[4];
+    if (conn->id) {
+      char id_str[4];
 
-            u8_to_dec(id_str, sizeof(id_str), conn->id);
-            bt_settings_encode_key(key, sizeof(key), "ccc",
-                                   &conn->le.dst, id_str);
-        } else {
-            bt_settings_encode_key(key, sizeof(key), "ccc",
-                                   &conn->le.dst, NULL);
-        }
+      u8_to_dec(id_str, sizeof(id_str), conn->id);
+      bt_settings_encode_key(key, sizeof(key), "ccc", &conn->le.dst, id_str);
+    } else {
+      bt_settings_encode_key(key, sizeof(key), "ccc", &conn->le.dst, NULL);
+    }
 #if defined(BFLB_BLE)
-        ccc_set(key, conn->id, &conn->le.dst);
+    ccc_set(key, conn->id, &conn->le.dst);
 #else
-        settings_load_subtree_direct(key, ccc_set_direct, (void *)key);
+    settings_load_subtree_direct(key, ccc_set_direct, (void *)key);
 #endif
-    }
-
-    bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data);
-
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part C page 2192:
-	 *
-	 * 10.3.1.1 Handling of GATT indications and notifications
-	 *
-	 * A client requests a server to send indications and notifications
-	 * by appropriately configuring the server via a Client Characteristic
-	 * Configuration Descriptor. Since the configuration is persistent
-	 * across a disconnection and reconnection, security requirements must
-	 * be checked against the configuration upon a reconnection before
-	 * sending indications or notifications. When a server reconnects to a
-	 * client to send an indication or notification for which security is
-	 * required, the server shall initiate or request encryption with the
-	 * client prior to sending an indication or notification. If the client
-	 * does not have an LTK indicating that the client has lost the bond,
-	 * enabling encryption will fail.
-	 */
-    if (IS_ENABLED(CONFIG_BT_SMP) &&
-        bt_conn_get_security(conn) < data.sec) {
-        bt_conn_set_security(conn, data.sec);
-    }
+  }
+
+  bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data);
+
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part C page 2192:
+   *
+   * 10.3.1.1 Handling of GATT indications and notifications
+   *
+   * A client requests a server to send indications and notifications
+   * by appropriately configuring the server via a Client Characteristic
+   * Configuration Descriptor. Since the configuration is persistent
+   * across a disconnection and reconnection, security requirements must
+   * be checked against the configuration upon a reconnection before
+   * sending indications or notifications. When a server reconnects to a
+   * client to send an indication or notification for which security is
+   * required, the server shall initiate or request encryption with the
+   * client prior to sending an indication or notification. If the client
+   * does not have an LTK indicating that the client has lost the bond,
+   * enabling encryption will fail.
+   */
+  if (IS_ENABLED(CONFIG_BT_SMP) && bt_conn_get_security(conn) < data.sec) {
+    bt_conn_set_security(conn, data.sec);
+  }
 
 #if defined(CONFIG_BT_GATT_CLIENT)
-    add_subscriptions(conn);
+  add_subscriptions(conn);
 #endif /* CONFIG_BT_GATT_CLIENT */
 
 #if defined(BFLB_BLE)
 #if defined(CONFIG_BT_GATT_SERVICE_CHANGED)
 #if defined(CONFIG_BT_SETTINGS)
-    sc_set(conn->id, &conn->le.dst);
-    sc_commit();
+  sc_set(conn->id, &conn->le.dst);
+  sc_commit();
 #endif
 #endif
 #endif
 }
 
-void bt_gatt_encrypt_change(struct bt_conn *conn)
-{
-    struct conn_data data;
+void bt_gatt_encrypt_change(struct bt_conn *conn) {
+  struct conn_data data;
 
-    BT_DBG("conn %p", conn);
+  BT_DBG("conn %p", conn);
 
-    data.conn = conn;
-    data.sec = BT_SECURITY_L1;
+  data.conn = conn;
+  data.sec  = BT_SECURITY_L1;
 
-    bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data);
+  bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data);
 }
 
-bool bt_gatt_change_aware(struct bt_conn *conn, bool req)
-{
+bool bt_gatt_change_aware(struct bt_conn *conn, bool req) {
 #if defined(CONFIG_BT_GATT_CACHING)
-    struct gatt_cf_cfg *cfg;
-
-    cfg = find_cf_cfg(conn);
-    if (!cfg || !CF_ROBUST_CACHING(cfg)) {
-        return true;
-    }
+  struct gatt_cf_cfg *cfg;
 
-    if (atomic_test_bit(cfg->flags, CF_CHANGE_AWARE)) {
-        return true;
-    }
+  cfg = find_cf_cfg(conn);
+  if (!cfg || !CF_ROBUST_CACHING(cfg)) {
+    return true;
+  }
 
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350:
-	 * If a change-unaware client sends an ATT command, the server shall
-	 * ignore it.
-	 */
-    if (!req) {
-        return false;
-    }
+  if (atomic_test_bit(cfg->flags, CF_CHANGE_AWARE)) {
+    return true;
+  }
 
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
-	 * 2.5.2.1 Robust Caching
-	 * A connected client becomes change-aware when...
-	 * The server sends the client a response with the error code set to
-	 * Database Out Of Sync and then the server receives another ATT
-	 * request from the client.
-	 */
-    if (atomic_test_bit(cfg->flags, CF_OUT_OF_SYNC)) {
-        atomic_clear_bit(cfg->flags, CF_OUT_OF_SYNC);
-        atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
-        BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer));
-        return true;
-    }
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350:
+   * If a change-unaware client sends an ATT command, the server shall
+   * ignore it.
+   */
+  if (!req) {
+    return false;
+  }
+
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
+   * 2.5.2.1 Robust Caching
+   * A connected client becomes change-aware when...
+   * The server sends the client a response with the error code set to
+   * Database Out Of Sync and then the server receives another ATT
+   * request from the client.
+   */
+  if (atomic_test_bit(cfg->flags, CF_OUT_OF_SYNC)) {
+    atomic_clear_bit(cfg->flags, CF_OUT_OF_SYNC);
+    atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
+    BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer));
+    return true;
+  }
 
-    atomic_set_bit(cfg->flags, CF_OUT_OF_SYNC);
+  atomic_set_bit(cfg->flags, CF_OUT_OF_SYNC);
 
-    return false;
+  return false;
 #else
-    return true;
+  return true;
 #endif
 }
 
-static int bt_gatt_store_cf(struct bt_conn *conn)
-{
+static int bt_gatt_store_cf(struct bt_conn *conn) {
 #if defined(CONFIG_BT_GATT_CACHING)
-    struct gatt_cf_cfg *cfg;
-    char key[BT_SETTINGS_KEY_MAX];
-    char *str;
-    size_t len;
-    int err;
-
-    cfg = find_cf_cfg(conn);
-    if (!cfg) {
-        /* No cfg found, just clear it */
-        BT_DBG("No config for CF");
-        str = NULL;
-        len = 0;
-    } else {
-        str = (char *)cfg->data;
-        len = sizeof(cfg->data);
-
-        if (conn->id) {
-            char id_str[4];
-
-            u8_to_dec(id_str, sizeof(id_str), conn->id);
-            bt_settings_encode_key(key, sizeof(key), "cf",
-                                   &conn->le.dst, id_str);
-        }
-    }
-
-    if (!cfg || !conn->id) {
-        bt_settings_encode_key(key, sizeof(key), "cf",
-                               &conn->le.dst, NULL);
-    }
+  struct gatt_cf_cfg *cfg;
+  char                key[BT_SETTINGS_KEY_MAX];
+  char               *str;
+  size_t              len;
+  int                 err;
+
+  cfg = find_cf_cfg(conn);
+  if (!cfg) {
+    /* No cfg found, just clear it */
+    BT_DBG("No config for CF");
+    str = NULL;
+    len = 0;
+  } else {
+    str = (char *)cfg->data;
+    len = sizeof(cfg->data);
+
+    if (conn->id) {
+      char id_str[4];
+
+      u8_to_dec(id_str, sizeof(id_str), conn->id);
+      bt_settings_encode_key(key, sizeof(key), "cf", &conn->le.dst, id_str);
+    }
+  }
+
+  if (!cfg || !conn->id) {
+    bt_settings_encode_key(key, sizeof(key), "cf", &conn->le.dst, NULL);
+  }
 
 #if defined(BFLB_BLE)
-    err = settings_save_one(key, (u8_t *)str, len);
+  err = settings_save_one(key, (u8_t *)str, len);
 #else
-    err = settings_save_one(key, str, len);
+  err = settings_save_one(key, str, len);
 #endif
-    if (err) {
-        BT_ERR("Failed to store Client Features (err %d)", err);
-        return err;
-    }
+  if (err) {
+    BT_ERR("Failed to store Client Features (err %d)", err);
+    return err;
+  }
 
-    BT_DBG("Stored CF for %s (%s)", bt_addr_le_str(&conn->le.dst), log_strdup(key));
+  BT_DBG("Stored CF for %s (%s)", bt_addr_le_str(&conn->le.dst), log_strdup(key));
 #endif /* CONFIG_BT_GATT_CACHING */
-    return 0;
+  return 0;
 }
 
-void bt_gatt_disconnected(struct bt_conn *conn)
-{
-    BT_DBG("conn %p", conn);
-    bt_gatt_foreach_attr(0x0001, 0xffff, disconnected_cb, conn);
+void bt_gatt_disconnected(struct bt_conn *conn) {
+  BT_DBG("conn %p", conn);
+  bt_gatt_foreach_attr(0x0001, 0xffff, disconnected_cb, conn);
 
 #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE)
-    gatt_ccc_conn_unqueue(conn);
+  gatt_ccc_conn_unqueue(conn);
 
-    if (gatt_ccc_conn_queue_is_empty()) {
-        k_delayed_work_cancel(&gatt_ccc_store.work);
-    }
+  if (gatt_ccc_conn_queue_is_empty()) {
+    k_delayed_work_cancel(&gatt_ccc_store.work);
+  }
 #endif
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS) &&
-        bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
-        bt_gatt_store_ccc(conn->id, &conn->le.dst);
-        bt_gatt_store_cf(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_SETTINGS) && bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
+    bt_gatt_store_ccc(conn->id, &conn->le.dst);
+    bt_gatt_store_cf(conn);
+  }
 
 #if defined(CONFIG_BT_GATT_CLIENT)
-    remove_subscriptions(conn);
+  remove_subscriptions(conn);
 #endif /* CONFIG_BT_GATT_CLIENT */
 
 #if defined(CONFIG_BT_GATT_CACHING)
-    remove_cf_cfg(conn);
+  remove_cf_cfg(conn);
 #endif
 }
 
 #if defined(BFLB_BLE_MTU_CHANGE_CB)
-void bt_gatt_mtu_changed(struct bt_conn *conn, u16_t mtu)
-{
-    if (gatt_mtu_changed_cb)
-        gatt_mtu_changed_cb(conn, (int)mtu);
+void bt_gatt_mtu_changed(struct bt_conn *conn, u16_t mtu) {
+  if (gatt_mtu_changed_cb)
+    gatt_mtu_changed_cb(conn, (int)mtu);
 }
 
-void bt_gatt_register_mtu_callback(bt_gatt_mtu_changed_cb_t cb)
-{
-    gatt_mtu_changed_cb = cb;
-}
+void bt_gatt_register_mtu_callback(bt_gatt_mtu_changed_cb_t cb) { gatt_mtu_changed_cb = cb; }
 #endif
 
 #if defined(CONFIG_BT_SETTINGS)
 
 struct ccc_save {
-    struct addr_with_id addr_with_id;
-    struct ccc_store store[CCC_STORE_MAX];
-    size_t count;
+  struct addr_with_id addr_with_id;
+  struct ccc_store    store[CCC_STORE_MAX];
+  size_t              count;
 };
 
-static u8_t ccc_save(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct ccc_save *save = user_data;
-    struct _bt_gatt_ccc *ccc;
-    struct bt_gatt_ccc_cfg *cfg;
+static u8_t ccc_save(const struct bt_gatt_attr *attr, void *user_data) {
+  struct ccc_save        *save = user_data;
+  struct _bt_gatt_ccc    *ccc;
+  struct bt_gatt_ccc_cfg *cfg;
 
-    /* Check if attribute is a CCC */
-    if (attr->write != bt_gatt_attr_write_ccc) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  /* Check if attribute is a CCC */
+  if (attr->write != bt_gatt_attr_write_ccc) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    ccc = attr->user_data;
+  ccc = attr->user_data;
 
-    /* Check if there is a cfg for the peer */
-    cfg = ccc_find_cfg(ccc, save->addr_with_id.addr, save->addr_with_id.id);
-    if (!cfg) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  /* Check if there is a cfg for the peer */
+  cfg = ccc_find_cfg(ccc, save->addr_with_id.addr, save->addr_with_id.id);
+  if (!cfg) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    BT_DBG("Storing CCCs handle 0x%04x value 0x%04x", attr->handle,
-           cfg->value);
+  BT_DBG("Storing CCCs handle 0x%04x value 0x%04x", attr->handle, cfg->value);
 
-    save->store[save->count].handle = attr->handle;
-    save->store[save->count].value = cfg->value;
-    save->count++;
+  save->store[save->count].handle = attr->handle;
+  save->store[save->count].value  = cfg->value;
+  save->count++;
 
-    return BT_GATT_ITER_CONTINUE;
+  return BT_GATT_ITER_CONTINUE;
 }
 
-int bt_gatt_store_ccc(u8_t id, const bt_addr_le_t *addr)
-{
-    struct ccc_save save;
-    char key[BT_SETTINGS_KEY_MAX];
-    size_t len;
-    char *str;
-    int err;
+int bt_gatt_store_ccc(u8_t id, const bt_addr_le_t *addr) {
+  struct ccc_save save;
+  char            key[BT_SETTINGS_KEY_MAX];
+  size_t          len;
+  char           *str;
+  int             err;
 
-    save.addr_with_id.addr = addr;
-    save.addr_with_id.id = id;
-    save.count = 0;
+  save.addr_with_id.addr = addr;
+  save.addr_with_id.id   = id;
+  save.count             = 0;
 
-    bt_gatt_foreach_attr(0x0001, 0xffff, ccc_save, &save);
+  bt_gatt_foreach_attr(0x0001, 0xffff, ccc_save, &save);
 
-    if (id) {
-        char id_str[4];
+  if (id) {
+    char id_str[4];
 
-        u8_to_dec(id_str, sizeof(id_str), id);
-        bt_settings_encode_key(key, sizeof(key), "ccc",
-                               (bt_addr_le_t *)addr, id_str);
-    } else {
-        bt_settings_encode_key(key, sizeof(key), "ccc",
-                               (bt_addr_le_t *)addr, NULL);
-    }
+    u8_to_dec(id_str, sizeof(id_str), id);
+    bt_settings_encode_key(key, sizeof(key), "ccc", (bt_addr_le_t *)addr, id_str);
+  } else {
+    bt_settings_encode_key(key, sizeof(key), "ccc", (bt_addr_le_t *)addr, NULL);
+  }
 
-    if (save.count) {
-        str = (char *)save.store;
-        len = save.count * sizeof(*save.store);
-    } else {
-        /* No entries to encode, just clear */
-        str = NULL;
-        len = 0;
-    }
+  if (save.count) {
+    str = (char *)save.store;
+    len = save.count * sizeof(*save.store);
+  } else {
+    /* No entries to encode, just clear */
+    str = NULL;
+    len = 0;
+  }
 
-    err = settings_save_one(key, (const u8_t *)str, len);
-    if (err) {
-        BT_ERR("Failed to store CCCs (err %d)", err);
-        return err;
-    }
+  err = settings_save_one(key, (const u8_t *)str, len);
+  if (err) {
+    BT_ERR("Failed to store CCCs (err %d)", err);
+    return err;
+  }
 
-    BT_DBG("Stored CCCs for %s (%s)", bt_addr_le_str(addr),
-           log_strdup(key));
-    if (len) {
-        for (int i = 0; i < save.count; i++) {
-            BT_DBG("  CCC: handle 0x%04x value 0x%04x",
-                   save.store[i].handle, save.store[i].value);
-        }
-    } else {
-        BT_DBG("  CCC: NULL");
+  BT_DBG("Stored CCCs for %s (%s)", bt_addr_le_str(addr), log_strdup(key));
+  if (len) {
+    for (int i = 0; i < save.count; i++) {
+      BT_DBG("  CCC: handle 0x%04x value 0x%04x", save.store[i].handle, save.store[i].value);
     }
+  } else {
+    BT_DBG("  CCC: NULL");
+  }
 
-    return 0;
+  return 0;
 }
 
-static u8_t remove_peer_from_attr(const struct bt_gatt_attr *attr,
-                                  void *user_data)
-{
-    const struct addr_with_id *addr_with_id = user_data;
-    struct _bt_gatt_ccc *ccc;
-    struct bt_gatt_ccc_cfg *cfg;
+static u8_t remove_peer_from_attr(const struct bt_gatt_attr *attr, void *user_data) {
+  const struct addr_with_id *addr_with_id = user_data;
+  struct _bt_gatt_ccc       *ccc;
+  struct bt_gatt_ccc_cfg    *cfg;
 
-    /* Check if attribute is a CCC */
-    if (attr->write != bt_gatt_attr_write_ccc) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  /* Check if attribute is a CCC */
+  if (attr->write != bt_gatt_attr_write_ccc) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    ccc = attr->user_data;
+  ccc = attr->user_data;
 
-    /* Check if there is a cfg for the peer */
-    cfg = ccc_find_cfg(ccc, addr_with_id->addr, addr_with_id->id);
-    if (cfg) {
-        memset(cfg, 0, sizeof(*cfg));
-    }
+  /* Check if there is a cfg for the peer */
+  cfg = ccc_find_cfg(ccc, addr_with_id->addr, addr_with_id->id);
+  if (cfg) {
+    memset(cfg, 0, sizeof(*cfg));
+  }
 
-    return BT_GATT_ITER_CONTINUE;
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static int bt_gatt_clear_ccc(u8_t id, const bt_addr_le_t *addr)
-{
-    char key[BT_SETTINGS_KEY_MAX];
-    struct addr_with_id addr_with_id = {
-        .addr = addr,
-        .id = id,
-    };
+static int bt_gatt_clear_ccc(u8_t id, const bt_addr_le_t *addr) {
+  char                key[BT_SETTINGS_KEY_MAX];
+  struct addr_with_id addr_with_id = {
+      .addr = addr,
+      .id   = id,
+  };
 
-    if (id) {
-        char id_str[4];
+  if (id) {
+    char id_str[4];
 
-        u8_to_dec(id_str, sizeof(id_str), id);
-        bt_settings_encode_key(key, sizeof(key), "ccc",
-                               (bt_addr_le_t *)addr, id_str);
-    } else {
-        bt_settings_encode_key(key, sizeof(key), "ccc",
-                               (bt_addr_le_t *)addr, NULL);
-    }
+    u8_to_dec(id_str, sizeof(id_str), id);
+    bt_settings_encode_key(key, sizeof(key), "ccc", (bt_addr_le_t *)addr, id_str);
+  } else {
+    bt_settings_encode_key(key, sizeof(key), "ccc", (bt_addr_le_t *)addr, NULL);
+  }
 
-    bt_gatt_foreach_attr(0x0001, 0xffff, remove_peer_from_attr,
-                         &addr_with_id);
+  bt_gatt_foreach_attr(0x0001, 0xffff, remove_peer_from_attr, &addr_with_id);
 
-    return settings_delete(key);
+  return settings_delete(key);
 }
 
 #if defined(CONFIG_BT_GATT_CACHING)
-static struct gatt_cf_cfg *find_cf_cfg_by_addr(const bt_addr_le_t *addr)
-{
-    int i;
+static struct gatt_cf_cfg *find_cf_cfg_by_addr(const bt_addr_le_t *addr) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
-        if (!bt_addr_le_cmp(addr, &cf_cfg[i].peer)) {
-            return &cf_cfg[i];
-        }
+  for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
+    if (!bt_addr_le_cmp(addr, &cf_cfg[i].peer)) {
+      return &cf_cfg[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 #endif /* CONFIG_BT_GATT_CACHING */
 
-static int bt_gatt_clear_cf(u8_t id, const bt_addr_le_t *addr)
-{
+static int bt_gatt_clear_cf(u8_t id, const bt_addr_le_t *addr) {
 #if defined(CONFIG_BT_GATT_CACHING)
-    char key[BT_SETTINGS_KEY_MAX];
-    struct gatt_cf_cfg *cfg;
+  char                key[BT_SETTINGS_KEY_MAX];
+  struct gatt_cf_cfg *cfg;
 
-    if (id) {
-        char id_str[4];
+  if (id) {
+    char id_str[4];
 
-        u8_to_dec(id_str, sizeof(id_str), id);
-        bt_settings_encode_key(key, sizeof(key), "cf",
-                               (bt_addr_le_t *)addr, id_str);
-    } else {
-        bt_settings_encode_key(key, sizeof(key), "cf",
-                               (bt_addr_le_t *)addr, NULL);
-    }
+    u8_to_dec(id_str, sizeof(id_str), id);
+    bt_settings_encode_key(key, sizeof(key), "cf", (bt_addr_le_t *)addr, id_str);
+  } else {
+    bt_settings_encode_key(key, sizeof(key), "cf", (bt_addr_le_t *)addr, NULL);
+  }
 
-    cfg = find_cf_cfg_by_addr(addr);
-    if (cfg) {
-        clear_cf_cfg(cfg);
-    }
+  cfg = find_cf_cfg_by_addr(addr);
+  if (cfg) {
+    clear_cf_cfg(cfg);
+  }
 
-    return settings_delete(key);
+  return settings_delete(key);
 #endif /* CONFIG_BT_GATT_CACHING */
-    return 0;
+  return 0;
 }
 
-static int sc_clear_by_addr(u8_t id, const bt_addr_le_t *addr)
-{
-    if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) {
-        struct gatt_sc_cfg *cfg;
+static int sc_clear_by_addr(u8_t id, const bt_addr_le_t *addr) {
+  if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) {
+    struct gatt_sc_cfg *cfg;
 
-        cfg = find_sc_cfg(id, (bt_addr_le_t *)addr);
-        if (cfg) {
-            sc_clear(cfg);
-        }
+    cfg = find_sc_cfg(id, (bt_addr_le_t *)addr);
+    if (cfg) {
+      sc_clear(cfg);
     }
-    return 0;
+  }
+  return 0;
 }
 
-static void bt_gatt_clear_subscriptions(const bt_addr_le_t *addr)
-{
+static void bt_gatt_clear_subscriptions(const bt_addr_le_t *addr) {
 #if defined(CONFIG_BT_GATT_CLIENT)
-    struct bt_gatt_subscribe_params *params, *tmp;
-    sys_snode_t *prev = NULL;
-
-    SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node)
-    {
-        if (bt_addr_le_cmp(addr, ¶ms->_peer)) {
-            prev = ¶ms->node;
-            continue;
-        }
-        params->value = 0U;
-        gatt_subscription_remove(NULL, prev, params);
+  struct bt_gatt_subscribe_params *params, *tmp;
+  sys_snode_t                     *prev = NULL;
+
+  SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node) {
+    if (bt_addr_le_cmp(addr, ¶ms->_peer)) {
+      prev = ¶ms->node;
+      continue;
     }
+    params->value = 0U;
+    gatt_subscription_remove(NULL, prev, params);
+  }
 #endif /* CONFIG_BT_GATT_CLIENT */
 }
 
-int bt_gatt_clear(u8_t id, const bt_addr_le_t *addr)
-{
-    int err;
+int bt_gatt_clear(u8_t id, const bt_addr_le_t *addr) {
+  int err;
 
-    err = bt_gatt_clear_ccc(id, addr);
-    if (err < 0) {
-        return err;
-    }
+  err = bt_gatt_clear_ccc(id, addr);
+  if (err < 0) {
+    return err;
+  }
 
-    err = sc_clear_by_addr(id, addr);
-    if (err < 0) {
-        return err;
-    }
+  err = sc_clear_by_addr(id, addr);
+  if (err < 0) {
+    return err;
+  }
 
-    err = bt_gatt_clear_cf(id, addr);
-    if (err < 0) {
-        return err;
-    }
+  err = bt_gatt_clear_cf(id, addr);
+  if (err < 0) {
+    return err;
+  }
 
-    bt_gatt_clear_subscriptions(addr);
+  bt_gatt_clear_subscriptions(addr);
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_GATT_SERVICE_CHANGED)
 #if defined(BFLB_BLE)
 static int sc_set(u8_t id, bt_addr_le_t *addr)
 #else
-static int sc_set(const char *name, size_t len_rd, settings_read_cb read_cb,
-                  void *cb_arg)
+static int sc_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
 #endif
 {
-    struct gatt_sc_cfg *cfg;
+  struct gatt_sc_cfg *cfg;
 #if !defined(BFLB_BLE)
-    u8_t id;
-    bt_addr_le_t addr;
-    int len, err;
-    const char *next;
+  u8_t         id;
+  bt_addr_le_t addr;
+  int          len, err;
+  const char  *next;
 #endif
 
 #if defined(BFLB_BLE)
-    int err;
-    char key[BT_SETTINGS_KEY_MAX];
+  int  err;
+  char key[BT_SETTINGS_KEY_MAX];
 
-    cfg = find_sc_cfg(id, addr);
+  cfg = find_sc_cfg(id, addr);
+  if (!cfg) {
+    /* Find and initialize a free sc_cfg entry */
+    cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY);
     if (!cfg) {
-        /* Find and initialize a free sc_cfg entry */
-        cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY);
-        if (!cfg) {
-            BT_ERR("Unable to restore SC: no cfg left");
-            return -ENOMEM;
-        }
-
-        cfg->id = id;
-        bt_addr_le_copy(&cfg->peer, addr);
+      BT_ERR("Unable to restore SC: no cfg left");
+      return -ENOMEM;
     }
 
-    if (id) {
-        char id_str[4];
+    cfg->id = id;
+    bt_addr_le_copy(&cfg->peer, addr);
+  }
 
-        u8_to_dec(id_str, sizeof(id_str), id);
-        bt_settings_encode_key(key, sizeof(key), "sc",
-                               addr, id_str);
-    } else {
-        bt_settings_encode_key(key, sizeof(key), "sc",
-                               addr, NULL);
-    }
+  if (id) {
+    char id_str[4];
 
-    err = bt_settings_get_bin(key, (u8_t *)cfg, sizeof(*cfg), NULL);
-    if (err)
-        memset(cfg, 0, sizeof(*cfg));
-    return err;
+    u8_to_dec(id_str, sizeof(id_str), id);
+    bt_settings_encode_key(key, sizeof(key), "sc", addr, id_str);
+  } else {
+    bt_settings_encode_key(key, sizeof(key), "sc", addr, NULL);
+  }
+
+  err = bt_settings_get_bin(key, (u8_t *)cfg, sizeof(*cfg), NULL);
+  if (err)
+    memset(cfg, 0, sizeof(*cfg));
+  return err;
 #else
-    if (!name) {
-        BT_ERR("Insufficient number of arguments");
-        return -EINVAL;
-    }
+  if (!name) {
+    BT_ERR("Insufficient number of arguments");
+    return -EINVAL;
+  }
 
-    err = bt_settings_decode_key(name, &addr);
-    if (err) {
-        BT_ERR("Unable to decode address %s", log_strdup(name));
-        return -EINVAL;
-    }
+  err = bt_settings_decode_key(name, &addr);
+  if (err) {
+    BT_ERR("Unable to decode address %s", log_strdup(name));
+    return -EINVAL;
+  }
 
-    settings_name_next(name, &next);
+  settings_name_next(name, &next);
 
-    if (!next) {
-        id = BT_ID_DEFAULT;
-    } else {
-        id = strtol(next, NULL, 10);
+  if (!next) {
+    id = BT_ID_DEFAULT;
+  } else {
+    id = strtol(next, NULL, 10);
+  }
+
+  cfg = find_sc_cfg(id, &addr);
+  if (!cfg && len_rd) {
+    /* Find and initialize a free sc_cfg entry */
+    cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY);
+    if (!cfg) {
+      BT_ERR("Unable to restore SC: no cfg left");
+      return -ENOMEM;
     }
 
-    cfg = find_sc_cfg(id, &addr);
-    if (!cfg && len_rd) {
-        /* Find and initialize a free sc_cfg entry */
-        cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY);
-        if (!cfg) {
-            BT_ERR("Unable to restore SC: no cfg left");
-            return -ENOMEM;
-        }
+    cfg->id = id;
+    bt_addr_le_copy(&cfg->peer, &addr);
+  }
 
-        cfg->id = id;
-        bt_addr_le_copy(&cfg->peer, &addr);
+  if (len_rd) {
+    len = read_cb(cb_arg, &cfg->data, sizeof(cfg->data));
+    if (len < 0) {
+      BT_ERR("Failed to decode value (err %d)", len);
+      return len;
     }
+    BT_DBG("Read SC: len %d", len);
 
-    if (len_rd) {
-        len = read_cb(cb_arg, &cfg->data, sizeof(cfg->data));
-        if (len < 0) {
-            BT_ERR("Failed to decode value (err %d)", len);
-            return len;
-        }
-        BT_DBG("Read SC: len %d", len);
-
-        BT_DBG("Restored SC for %s", bt_addr_le_str(&addr));
-    } else if (cfg) {
-        /* Clear configuration */
-        memset(cfg, 0, sizeof(*cfg));
+    BT_DBG("Restored SC for %s", bt_addr_le_str(&addr));
+  } else if (cfg) {
+    /* Clear configuration */
+    memset(cfg, 0, sizeof(*cfg));
 
-        BT_DBG("Removed SC for %s", bt_addr_le_str(&addr));
-    }
+    BT_DBG("Removed SC for %s", bt_addr_le_str(&addr));
+  }
 
-    return 0;
+  return 0;
 #endif
 }
 
-static int sc_commit(void)
-{
-    atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING);
+static int sc_commit(void) {
+  atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING);
 
-    if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) {
-        /* Schedule SC indication since the range has changed */
-        k_delayed_work_submit(&gatt_sc.work, SC_TIMEOUT);
-    }
+  if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) {
+    /* Schedule SC indication since the range has changed */
+    k_delayed_work_submit(&gatt_sc.work, SC_TIMEOUT);
+  }
 
-    return 0;
+  return 0;
 }
 
 #if !defined(BFLB_BLE)
@@ -4590,103 +4130,97 @@ SETTINGS_STATIC_HANDLER_DEFINE(bt_sc, "bt/sc", NULL, sc_set, sc_commit, NULL);
 #endif /* CONFIG_BT_GATT_SERVICE_CHANGED */
 
 #if defined(CONFIG_BT_GATT_CACHING)
-static int cf_set(const char *name, size_t len_rd, settings_read_cb read_cb,
-                  void *cb_arg)
-{
-    struct gatt_cf_cfg *cfg;
-    bt_addr_le_t addr;
-    int len, err;
+static int cf_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) {
+  struct gatt_cf_cfg *cfg;
+  bt_addr_le_t        addr;
+  int                 len, err;
 
-    if (!name) {
-        BT_ERR("Insufficient number of arguments");
-        return -EINVAL;
-    }
+  if (!name) {
+    BT_ERR("Insufficient number of arguments");
+    return -EINVAL;
+  }
 
-    err = bt_settings_decode_key(name, &addr);
-    if (err) {
-        BT_ERR("Unable to decode address %s", log_strdup(name));
-        return -EINVAL;
-    }
+  err = bt_settings_decode_key(name, &addr);
+  if (err) {
+    BT_ERR("Unable to decode address %s", log_strdup(name));
+    return -EINVAL;
+  }
 
-    cfg = find_cf_cfg_by_addr(&addr);
+  cfg = find_cf_cfg_by_addr(&addr);
+  if (!cfg) {
+    cfg = find_cf_cfg(NULL);
     if (!cfg) {
-        cfg = find_cf_cfg(NULL);
-        if (!cfg) {
-            BT_ERR("Unable to restore CF: no cfg left");
-            return 0;
-        }
+      BT_ERR("Unable to restore CF: no cfg left");
+      return 0;
     }
+  }
 
-    if (len_rd) {
-        len = read_cb(cb_arg, cfg->data, sizeof(cfg->data));
-        if (len < 0) {
-            BT_ERR("Failed to decode value (err %d)", len);
-            return len;
-        }
-
-        BT_DBG("Read CF: len %d", len);
-    } else {
-        clear_cf_cfg(cfg);
+  if (len_rd) {
+    len = read_cb(cb_arg, cfg->data, sizeof(cfg->data));
+    if (len < 0) {
+      BT_ERR("Failed to decode value (err %d)", len);
+      return len;
     }
 
-    BT_DBG("Restored CF for %s", bt_addr_le_str(&addr));
+    BT_DBG("Read CF: len %d", len);
+  } else {
+    clear_cf_cfg(cfg);
+  }
 
-    return 0;
+  BT_DBG("Restored CF for %s", bt_addr_le_str(&addr));
+
+  return 0;
 }
 
 SETTINGS_STATIC_HANDLER_DEFINE(bt_cf, "bt/cf", NULL, cf_set, NULL, NULL);
 
 static u8_t stored_hash[16];
 
-static int db_hash_set(const char *name, size_t len_rd,
-                       settings_read_cb read_cb, void *cb_arg)
-{
-    int len;
+static int db_hash_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) {
+  int len;
 
-    len = read_cb(cb_arg, stored_hash, sizeof(stored_hash));
-    if (len < 0) {
-        BT_ERR("Failed to decode value (err %d)", len);
-        return len;
-    }
+  len = read_cb(cb_arg, stored_hash, sizeof(stored_hash));
+  if (len < 0) {
+    BT_ERR("Failed to decode value (err %d)", len);
+    return len;
+  }
 
-    BT_HEXDUMP_DBG(stored_hash, sizeof(stored_hash), "Stored Hash: ");
+  BT_HEXDUMP_DBG(stored_hash, sizeof(stored_hash), "Stored Hash: ");
 
-    return 0;
+  return 0;
 }
 
-static int db_hash_commit(void)
-{
-    /* Stop work and generate the hash */
-    if (k_delayed_work_remaining_get(&db_hash_work)) {
-        k_delayed_work_cancel(&db_hash_work);
-        db_hash_gen(false);
-    }
+static int db_hash_commit(void) {
+  /* Stop work and generate the hash */
+  if (k_delayed_work_remaining_get(&db_hash_work)) {
+    k_delayed_work_cancel(&db_hash_work);
+    db_hash_gen(false);
+  }
 
-    /* Check if hash matches then skip SC update */
-    if (!memcmp(stored_hash, db_hash, sizeof(stored_hash))) {
-        BT_DBG("Database Hash matches");
-        k_delayed_work_cancel(&gatt_sc.work);
-        return 0;
-    }
+  /* Check if hash matches then skip SC update */
+  if (!memcmp(stored_hash, db_hash, sizeof(stored_hash))) {
+    BT_DBG("Database Hash matches");
+    k_delayed_work_cancel(&gatt_sc.work);
+    return 0;
+  }
 
-    BT_HEXDUMP_DBG(db_hash, sizeof(db_hash), "New Hash: ");
+  BT_HEXDUMP_DBG(db_hash, sizeof(db_hash), "New Hash: ");
 
-    /**
-	 * GATT database has been modified since last boot, likely due to
-	 * a firmware update or a dynamic service that was not re-registered on
-	 * boot. Indicate Service Changed to all bonded devices for the full
-	 * database range to invalidate client-side cache and force discovery on
-	 * reconnect.
-	 */
-    sc_indicate(0x0001, 0xffff);
+  /**
+   * GATT database has been modified since last boot, likely due to
+   * a firmware update or a dynamic service that was not re-registered on
+   * boot. Indicate Service Changed to all bonded devices for the full
+   * database range to invalidate client-side cache and force discovery on
+   * reconnect.
+   */
+  sc_indicate(0x0001, 0xffff);
 
-    /* Hash did not match overwrite with current hash */
-    db_hash_store();
+  /* Hash did not match overwrite with current hash */
+  db_hash_store();
 
-    return 0;
+  return 0;
 }
 
-SETTINGS_STATIC_HANDLER_DEFINE(bt_hash, "bt/hash", NULL, db_hash_set,
-                               db_hash_commit, NULL);
+SETTINGS_STATIC_HANDLER_DEFINE(bt_hash, "bt/hash", NULL, db_hash_set, db_hash_commit, NULL);
 #endif /*CONFIG_BT_GATT_CACHING */
 #endif /* CONFIG_BT_SETTINGS */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c
index f6bbf28ae1..908f260f8e 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c
@@ -7,42 +7,42 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
-#include 
-#include 
 #include 
-#include 
-#include 
+#include 
+#include 
 #include 
+#include 
 #include 
-#include 
-//#include 
+#include 
+#include 
+#include 
+#include 
+// #include 
 
 #include 
 #include 
-#include 
+#include 
 #include 
 #include 
-#include 
+#include 
 
 #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_HCI_CORE)
 #include "log.h"
 
-#include "rpa.h"
-#include "keys.h"
-#include "monitor.h"
+#include "ecc.h"
 #include "hci_core.h"
 #include "hci_ecc.h"
-#include "ecc.h"
+#include "keys.h"
+#include "monitor.h"
+#include "rpa.h"
 
+#include "../include/bluetooth/crypto.h"
 #include "conn_internal.h"
-#include "l2cap_internal.h"
-#include "gatt_internal.h"
-#include "smp.h"
 #include "crypto.h"
-#include "../include/bluetooth/crypto.h"
+#include "gatt_internal.h"
+#include "l2cap_internal.h"
 #include "settings.h"
+#include "smp.h"
 #if defined(BFLB_BLE)
 #include "bl_hci_wrapper.h"
 #if defined(BL602)
@@ -81,9 +81,9 @@ static void init_work(struct k_work *work);
 struct bt_dev bt_dev = {
     .init = _K_WORK_INITIALIZER(init_work),
 /* Give cmd_sem allowing to send first HCI_Reset cmd, the only
-	 * exception is if the controller requests to wait for an
-	 * initial Command Complete for NOP.
-	 */
+ * exception is if the controller requests to wait for an
+ * initial Command Complete for NOP.
+ */
 #if defined(BFLB_BLE)
 #if !defined(CONFIG_BT_WAIT_NOP)
     .ncmd_sem = _K_SEM_INITIALIZER(bt_dev.ncmd_sem, 1, 1),
@@ -94,7 +94,7 @@ struct bt_dev bt_dev = {
 #if !defined(CONFIG_BT_RECV_IS_RX_THREAD)
     .rx_queue = Z_FIFO_INITIALIZER(bt_dev.rx_queue),
 #endif
-#else //BFLB_BLE
+#else // BFLB_BLE
 #if !defined(CONFIG_BT_WAIT_NOP)
     .ncmd_sem = Z_SEM_INITIALIZER(bt_dev.ncmd_sem, 1, 1),
 #else
@@ -118,20 +118,20 @@ static bt_hci_vnd_evt_cb_t *hci_vnd_evt_cb;
 #endif /* CONFIG_BT_HCI_VS_EVT_USER */
 
 #if defined(CONFIG_BT_ECC)
-static u8_t pub_key[64];
+static u8_t                  pub_key[64];
 static struct bt_pub_key_cb *pub_key_cb;
-static bt_dh_key_cb_t dh_key_cb;
+static bt_dh_key_cb_t        dh_key_cb;
 #endif /* CONFIG_BT_ECC */
 
 #if defined(CONFIG_BT_BREDR)
-static bt_br_discovery_cb_t *discovery_cb;
+static bt_br_discovery_cb_t   *discovery_cb;
 struct bt_br_discovery_result *discovery_results;
-static size_t discovery_results_size;
-static size_t discovery_results_count;
+static size_t                  discovery_results_size;
+static size_t                  discovery_results_count;
 #endif /* CONFIG_BT_BREDR */
 
 #if defined(CONFIG_BT_STACK_PTS)
-bt_addr_le_t pts_addr;
+bt_addr_le_t  pts_addr;
 volatile u8_t event_flag = 0;
 #endif
 
@@ -140,46 +140,44 @@ struct blhast_cb *host_assist_cb;
 #endif
 
 struct cmd_state_set {
-    atomic_t *target;
-    int bit;
-    bool val;
+  atomic_t *target;
+  int       bit;
+  bool      val;
 };
 
 #if defined(BFLB_RELEASE_CMD_SEM_IF_CONN_DISC)
 void hci_release_conn_related_cmd(void);
 #endif
 
-void cmd_state_set_init(struct cmd_state_set *state, atomic_t *target, int bit,
-                        bool val)
-{
-    state->target = target;
-    state->bit = bit;
-    state->val = val;
+void cmd_state_set_init(struct cmd_state_set *state, atomic_t *target, int bit, bool val) {
+  state->target = target;
+  state->bit    = bit;
+  state->val    = val;
 }
 
 struct cmd_data {
-    /** HCI status of the command completion */
-    u8_t status;
+  /** HCI status of the command completion */
+  u8_t status;
 
-    /** The command OpCode that the buffer contains */
-    u16_t opcode;
+  /** The command OpCode that the buffer contains */
+  u16_t opcode;
 
-    /** The state to update when command completes with success. */
-    struct cmd_state_set *state;
+  /** The state to update when command completes with success. */
+  struct cmd_state_set *state;
 
-    /** Used by bt_hci_cmd_send_sync. */
-    struct k_sem *sync;
+  /** Used by bt_hci_cmd_send_sync. */
+  struct k_sem *sync;
 };
 
 struct acl_data {
-    /** BT_BUF_ACL_IN */
-    u8_t type;
+  /** BT_BUF_ACL_IN */
+  u8_t type;
 
-    /* Index into the bt_conn storage array */
-    u8_t id;
+  /* Index into the bt_conn storage array */
+  u8_t id;
 
-    /** ACL connection handle */
-    u16_t handle;
+  /** ACL connection handle */
+  u16_t handle;
 };
 
 #if defined(BFLB_BLE)
@@ -196,11 +194,9 @@ static struct cmd_data cmd_data[CONFIG_BT_HCI_CMD_COUNT];
  */
 #define CMD_BUF_SIZE BT_BUF_RX_SIZE
 #if !defined(BFLB_DYNAMIC_ALLOC_MEM)
-NET_BUF_POOL_FIXED_DEFINE(hci_cmd_pool, CONFIG_BT_HCI_CMD_COUNT,
-                          CMD_BUF_SIZE, NULL);
+NET_BUF_POOL_FIXED_DEFINE(hci_cmd_pool, CONFIG_BT_HCI_CMD_COUNT, CMD_BUF_SIZE, NULL);
 
-NET_BUF_POOL_FIXED_DEFINE(hci_rx_pool, CONFIG_BT_RX_BUF_COUNT,
-                          BT_BUF_RX_SIZE, NULL);
+NET_BUF_POOL_FIXED_DEFINE(hci_rx_pool, CONFIG_BT_RX_BUF_COUNT, BT_BUF_RX_SIZE, NULL);
 #if defined(CONFIG_BT_CONN)
 /* Dedicated pool for HCI_Number_of_Completed_Packets. This event is always
  * consumed synchronously by bt_recv_prio() so a single buffer is enough.
@@ -211,8 +207,7 @@ NET_BUF_POOL_FIXED_DEFINE(num_complete_pool, 1, BT_BUF_RX_SIZE, NULL);
 #endif /* CONFIG_BT_CONN */
 
 #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT)
-NET_BUF_POOL_FIXED_DEFINE(discardable_pool, CONFIG_BT_DISCARDABLE_BUF_COUNT,
-                          BT_BUF_RX_SIZE, NULL);
+NET_BUF_POOL_FIXED_DEFINE(discardable_pool, CONFIG_BT_DISCARDABLE_BUF_COUNT, BT_BUF_RX_SIZE, NULL);
 #endif /* CONFIG_BT_DISCARDABLE_BUF_COUNT */
 #else
 struct net_buf_pool hci_cmd_pool;
@@ -228,2938 +223,2769 @@ struct net_buf_pool discardable_pool;
 extern bool hfp_codec_msbc;
 
 struct event_handler {
-    u8_t event;
-    u8_t min_len;
-    void (*handler)(struct net_buf *buf);
+  u8_t event;
+  u8_t min_len;
+  void (*handler)(struct net_buf *buf);
 };
 
 #define EVENT_HANDLER(_evt, _handler, _min_len) \
-    {                                           \
-        .event = _evt,                          \
-        .handler = _handler,                    \
-        .min_len = _min_len,                    \
-    }
-
-static inline void handle_event(u8_t event, struct net_buf *buf,
-                                const struct event_handler *handlers,
-                                size_t num_handlers)
-{
-    size_t i;
+  { .event = _evt, .handler = _handler, .min_len = _min_len, }
 
-    for (i = 0; i < num_handlers; i++) {
-        const struct event_handler *handler = &handlers[i];
+static inline void handle_event(u8_t event, struct net_buf *buf, const struct event_handler *handlers, size_t num_handlers) {
+  size_t i;
 
-        if (handler->event != event) {
-            continue;
-        }
+  for (i = 0; i < num_handlers; i++) {
+    const struct event_handler *handler = &handlers[i];
 
-        if (buf->len < handler->min_len) {
-            BT_ERR("Too small (%u bytes) event 0x%02x",
-                   buf->len, event);
-            return;
-        }
+    if (handler->event != event) {
+      continue;
+    }
 
-        handler->handler(buf);
-        return;
+    if (buf->len < handler->min_len) {
+      BT_ERR("Too small (%u bytes) event 0x%02x", buf->len, event);
+      return;
     }
 
-    BT_WARN("Unhandled event 0x%02x len %u: %s", event,
-            buf->len, bt_hex(buf->data, buf->len));
+    handler->handler(buf);
+    return;
+  }
+
+  BT_WARN("Unhandled event 0x%02x len %u: %s", event, buf->len, bt_hex(buf->data, buf->len));
 }
 
-static inline bool is_wl_empty(void)
-{
+static inline bool is_wl_empty(void) {
 #if defined(CONFIG_BT_WHITELIST)
-    return !bt_dev.le.wl_entries;
+  return !bt_dev.le.wl_entries;
 #else
-    return true;
+  return true;
 #endif /* defined(CONFIG_BT_WHITELIST) */
 }
 
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-static void report_completed_packet(struct net_buf *buf)
-{
-    struct bt_hci_cp_host_num_completed_packets *cp;
-    u16_t handle = acl(buf)->handle;
-    struct bt_hci_handle_count *hc;
-    struct bt_conn *conn;
+static void report_completed_packet(struct net_buf *buf) {
+  struct bt_hci_cp_host_num_completed_packets *cp;
+  u16_t                                        handle = acl(buf)->handle;
+  struct bt_hci_handle_count                  *hc;
+  struct bt_conn                              *conn;
 
-    net_buf_destroy(buf);
+  net_buf_destroy(buf);
 
-    /* Do nothing if controller to host flow control is not supported */
-    if (!BT_CMD_TEST(bt_dev.supported_commands, 10, 5)) {
-        return;
-    }
-
-    conn = bt_conn_lookup_id(acl(buf)->id);
-    if (!conn) {
-        BT_WARN("Unable to look up conn with id 0x%02x", acl(buf)->id);
-        return;
-    }
+  /* Do nothing if controller to host flow control is not supported */
+  if (!BT_CMD_TEST(bt_dev.supported_commands, 10, 5)) {
+    return;
+  }
 
-    if (conn->state != BT_CONN_CONNECTED &&
-        conn->state != BT_CONN_DISCONNECT) {
-        BT_WARN("Not reporting packet for non-connected conn");
-        bt_conn_unref(conn);
-        return;
-    }
+  conn = bt_conn_lookup_id(acl(buf)->id);
+  if (!conn) {
+    BT_WARN("Unable to look up conn with id 0x%02x", acl(buf)->id);
+    return;
+  }
 
+  if (conn->state != BT_CONN_CONNECTED && conn->state != BT_CONN_DISCONNECT) {
+    BT_WARN("Not reporting packet for non-connected conn");
     bt_conn_unref(conn);
+    return;
+  }
 
-    BT_DBG("Reporting completed packet for handle %u", handle);
+  bt_conn_unref(conn);
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS,
-                            sizeof(*cp) + sizeof(*hc));
-    if (!buf) {
-        BT_ERR("Unable to allocate new HCI command");
-        return;
-    }
+  BT_DBG("Reporting completed packet for handle %u", handle);
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->num_handles = sys_cpu_to_le16(1);
+  buf = bt_hci_cmd_create(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS, sizeof(*cp) + sizeof(*hc));
+  if (!buf) {
+    BT_ERR("Unable to allocate new HCI command");
+    return;
+  }
 
-    hc = net_buf_add(buf, sizeof(*hc));
-    hc->handle = sys_cpu_to_le16(handle);
-    hc->count = sys_cpu_to_le16(1);
+  cp              = net_buf_add(buf, sizeof(*cp));
+  cp->num_handles = sys_cpu_to_le16(1);
 
-    bt_hci_cmd_send(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS, buf);
+  hc         = net_buf_add(buf, sizeof(*hc));
+  hc->handle = sys_cpu_to_le16(handle);
+  hc->count  = sys_cpu_to_le16(1);
+
+  bt_hci_cmd_send(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS, buf);
 }
 
 #define ACL_IN_SIZE BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_RX_MTU)
 #if !defined(BFLB_DYNAMIC_ALLOC_MEM)
-NET_BUF_POOL_DEFINE(acl_in_pool, CONFIG_BT_ACL_RX_COUNT, ACL_IN_SIZE,
-                    sizeof(struct acl_data), report_completed_packet);
+NET_BUF_POOL_DEFINE(acl_in_pool, CONFIG_BT_ACL_RX_COUNT, ACL_IN_SIZE, sizeof(struct acl_data), report_completed_packet);
 #else
 struct net_buf_pool acl_in_pool;
 #endif
 #endif /* CONFIG_BT_HCI_ACL_FLOW_CONTROL */
 
-struct net_buf *bt_hci_cmd_create(u16_t opcode, u8_t param_len)
-{
-    struct bt_hci_cmd_hdr *hdr;
-    struct net_buf *buf;
+struct net_buf *bt_hci_cmd_create(u16_t opcode, u8_t param_len) {
+  struct bt_hci_cmd_hdr *hdr;
+  struct net_buf        *buf;
 
-    BT_DBG("opcode 0x%04x param_len %u", opcode, param_len);
+  BT_DBG("opcode 0x%04x param_len %u", opcode, param_len);
 
-    buf = net_buf_alloc(&hci_cmd_pool, K_FOREVER);
-    __ASSERT_NO_MSG(buf);
+  buf = net_buf_alloc(&hci_cmd_pool, K_FOREVER);
+  __ASSERT_NO_MSG(buf);
 
-    BT_DBG("buf %p", buf);
+  BT_DBG("buf %p", buf);
 
-    net_buf_reserve(buf, BT_BUF_RESERVE);
+  net_buf_reserve(buf, BT_BUF_RESERVE);
 
-    bt_buf_set_type(buf, BT_BUF_CMD);
+  bt_buf_set_type(buf, BT_BUF_CMD);
 
-    cmd(buf)->opcode = opcode;
-    cmd(buf)->sync = NULL;
-    cmd(buf)->state = NULL;
+  cmd(buf)->opcode = opcode;
+  cmd(buf)->sync   = NULL;
+  cmd(buf)->state  = NULL;
 
-    hdr = net_buf_add(buf, sizeof(*hdr));
-    hdr->opcode = sys_cpu_to_le16(opcode);
-    hdr->param_len = param_len;
+  hdr            = net_buf_add(buf, sizeof(*hdr));
+  hdr->opcode    = sys_cpu_to_le16(opcode);
+  hdr->param_len = param_len;
 
-    return buf;
+  return buf;
 }
 
-int bt_hci_cmd_send(u16_t opcode, struct net_buf *buf)
-{
+int bt_hci_cmd_send(u16_t opcode, struct net_buf *buf) {
+  if (!buf) {
+    buf = bt_hci_cmd_create(opcode, 0);
     if (!buf) {
-        buf = bt_hci_cmd_create(opcode, 0);
-        if (!buf) {
-            return -ENOBUFS;
-        }
+      return -ENOBUFS;
     }
+  }
 
-    BT_DBG("opcode 0x%04x len %u", opcode, buf->len);
-
-    /* Host Number of Completed Packets can ignore the ncmd value
-	 * and does not generate any cmd complete/status events.
-	 */
-    if (opcode == BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS) {
-        int err;
+  BT_DBG("opcode 0x%04x len %u", opcode, buf->len);
 
-        err = bt_send(buf);
-        if (err) {
-            BT_ERR("Unable to send to driver (err %d)", err);
-            net_buf_unref(buf);
-        }
+  /* Host Number of Completed Packets can ignore the ncmd value
+   * and does not generate any cmd complete/status events.
+   */
+  if (opcode == BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS) {
+    int err;
 
-        return err;
+    err = bt_send(buf);
+    if (err) {
+      BT_ERR("Unable to send to driver (err %d)", err);
+      net_buf_unref(buf);
     }
 
-    net_buf_put(&bt_dev.cmd_tx_queue, buf);
+    return err;
+  }
+
+  net_buf_put(&bt_dev.cmd_tx_queue, buf);
 #if defined(BFLB_BLE)
-    k_sem_give(&g_poll_sem);
+  k_sem_give(&g_poll_sem);
 #endif
-    return 0;
+  return 0;
 }
 
 #if defined(BFLB_HOST_ASSISTANT)
 extern void blhast_bt_reset(void);
-uint16_t hci_cmd_to_cnt = 0;
+uint16_t    hci_cmd_to_cnt = 0;
 #endif
-int bt_hci_cmd_send_sync(u16_t opcode, struct net_buf *buf,
-                         struct net_buf **rsp)
-{
-    struct k_sem sync_sem;
-    int err;
+int bt_hci_cmd_send_sync(u16_t opcode, struct net_buf *buf, struct net_buf **rsp) {
+  struct k_sem sync_sem;
+  int          err;
 
+  if (!buf) {
+    buf = bt_hci_cmd_create(opcode, 0);
     if (!buf) {
-        buf = bt_hci_cmd_create(opcode, 0);
-        if (!buf) {
-            return -ENOBUFS;
-        }
+      return -ENOBUFS;
     }
+  }
 
-    BT_DBG("buf %p opcode 0x%04x len %u", buf, opcode, buf->len);
+  BT_DBG("buf %p opcode 0x%04x len %u", buf, opcode, buf->len);
 
-    k_sem_init(&sync_sem, 0, 1);
-    cmd(buf)->sync = &sync_sem;
+  k_sem_init(&sync_sem, 0, 1);
+  cmd(buf)->sync = &sync_sem;
 
 #if defined(BFLB_BLE)
-    /*Assign a initial value to status in order to check if hci cmd timeout*/
-    cmd(buf)->status = 0xff;
+  /*Assign a initial value to status in order to check if hci cmd timeout*/
+  cmd(buf)->status = 0xff;
 #endif
 
-    /* Make sure the buffer stays around until the command completes */
-    net_buf_ref(buf);
+  /* Make sure the buffer stays around until the command completes */
+  net_buf_ref(buf);
 
-    net_buf_put(&bt_dev.cmd_tx_queue, buf);
+  net_buf_put(&bt_dev.cmd_tx_queue, buf);
 #if defined(BFLB_BLE)
-    k_sem_give(&g_poll_sem);
+  k_sem_give(&g_poll_sem);
 #endif
-    err = k_sem_take(&sync_sem, HCI_CMD_TIMEOUT);
+  err = k_sem_take(&sync_sem, HCI_CMD_TIMEOUT);
 #ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS
-    k_sem_delete(&sync_sem);
+  k_sem_delete(&sync_sem);
 #endif
-    __ASSERT(err == 0, "k_sem_take failed with err %d", err);
+  __ASSERT(err == 0, "k_sem_take failed with err %d", err);
 
-    BT_DBG("opcode 0x%04x status 0x%02x", opcode, cmd(buf)->status);
+  BT_DBG("opcode 0x%04x status 0x%02x", opcode, cmd(buf)->status);
 
-    if (cmd(buf)->status) {
-        switch (cmd(buf)->status) {
-            case BT_HCI_ERR_CONN_LIMIT_EXCEEDED:
-                err = -ECONNREFUSED;
-                break;
+  if (cmd(buf)->status) {
+    switch (cmd(buf)->status) {
+    case BT_HCI_ERR_CONN_LIMIT_EXCEEDED:
+      err = -ECONNREFUSED;
+      break;
 #if defined(BFLB_BLE)
-            case 0xff:
-                err = -ETIME;
-                BT_ERR("k_sem_take timeout with opcode 0x%04x", opcode);
+    case 0xff:
+      err = -ETIME;
+      BT_ERR("k_sem_take timeout with opcode 0x%04x", opcode);
 #if (defined(BL602) || defined(BL702)) && defined(BFLB_HOST_ASSISTANT)
-                BT_ERR("Restart and restore bt");
-                hci_cmd_to_cnt++;
-                if (cmd(buf)->state) {
-                    struct cmd_state_set *update = cmd(buf)->state;
-                    atomic_set_bit_to(update->target, update->bit, update->val);
-                }
-                blhast_bt_reset();
+      BT_ERR("Restart and restore bt");
+      hci_cmd_to_cnt++;
+      if (cmd(buf)->state) {
+        struct cmd_state_set *update = cmd(buf)->state;
+        atomic_set_bit_to(update->target, update->bit, update->val);
+      }
+      blhast_bt_reset();
 #else
-                BT_ASSERT(err == 0);
+      BT_ASSERT(err == 0);
 #endif
-                break;
+      break;
 #endif
-            default:
-                err = -EIO;
-                break;
-        }
+    default:
+      err = -EIO;
+      break;
+    }
 
-        net_buf_unref(buf);
+    net_buf_unref(buf);
+  } else {
+    err = 0;
+    if (rsp) {
+      *rsp = buf;
     } else {
-        err = 0;
-        if (rsp) {
-            *rsp = buf;
-        } else {
-            net_buf_unref(buf);
-        }
+      net_buf_unref(buf);
     }
+  }
 
-    return err;
+  return err;
 }
 
 #if defined(CONFIG_BT_OBSERVER) || defined(CONFIG_BT_CONN)
-const bt_addr_le_t *bt_lookup_id_addr(u8_t id, const bt_addr_le_t *addr)
-{
-    if (IS_ENABLED(CONFIG_BT_SMP)) {
-        struct bt_keys *keys;
-
-        keys = bt_keys_find_irk(id, addr);
-        if (keys) {
-            BT_DBG("Identity %s matched RPA %s",
-                   bt_addr_le_str(&keys->addr),
-                   bt_addr_le_str(addr));
-            return &keys->addr;
-        }
+const bt_addr_le_t *bt_lookup_id_addr(u8_t id, const bt_addr_le_t *addr) {
+  if (IS_ENABLED(CONFIG_BT_SMP)) {
+    struct bt_keys *keys;
+
+    keys = bt_keys_find_irk(id, addr);
+    if (keys) {
+      BT_DBG("Identity %s matched RPA %s", bt_addr_le_str(&keys->addr), bt_addr_le_str(addr));
+      return &keys->addr;
     }
+  }
 
-    return addr;
+  return addr;
 }
 #endif /* CONFIG_BT_OBSERVER || CONFIG_BT_CONN */
 
-static int set_advertise_enable(bool enable)
-{
-    struct net_buf *buf;
-    struct cmd_state_set state;
-    int err;
+static int set_advertise_enable(bool enable) {
+  struct net_buf      *buf;
+  struct cmd_state_set state;
+  int                  err;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_ENABLE, 1);
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_ENABLE, 1);
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    if (enable) {
-        net_buf_add_u8(buf, BT_HCI_LE_ADV_ENABLE);
-    } else {
-        net_buf_add_u8(buf, BT_HCI_LE_ADV_DISABLE);
-    }
+  if (enable) {
+    net_buf_add_u8(buf, BT_HCI_LE_ADV_ENABLE);
+  } else {
+    net_buf_add_u8(buf, BT_HCI_LE_ADV_DISABLE);
+  }
 
-    cmd_state_set_init(&state, bt_dev.flags, BT_DEV_ADVERTISING, enable);
-    cmd(buf)->state = &state;
+  cmd_state_set_init(&state, bt_dev.flags, BT_DEV_ADVERTISING, enable);
+  cmd(buf)->state = &state;
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_ENABLE, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_ENABLE, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-static int set_random_address(const bt_addr_t *addr)
-{
-    struct net_buf *buf;
-    int err;
+static int set_random_address(const bt_addr_t *addr) {
+  struct net_buf *buf;
+  int             err;
 
 #if defined(CONFIG_BT_STACK_PTS)
-    BT_PTS("set random address %s", bt_addr_str(addr));
+  BT_PTS("set random address %s", bt_addr_str(addr));
 #else
-    BT_DBG("%s", bt_addr_str(addr));
+  BT_DBG("%s", bt_addr_str(addr));
 #endif
 
-    /* Do nothing if we already have the right address */
-    if (!bt_addr_cmp(addr, &bt_dev.random_addr.a)) {
-        return 0;
-    }
+  /* Do nothing if we already have the right address */
+  if (!bt_addr_cmp(addr, &bt_dev.random_addr.a)) {
+    return 0;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, sizeof(*addr));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, sizeof(*addr));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    net_buf_add_mem(buf, addr, sizeof(*addr));
+  net_buf_add_mem(buf, addr, sizeof(*addr));
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    bt_addr_copy(&bt_dev.random_addr.a, addr);
-    bt_dev.random_addr.type = BT_ADDR_LE_RANDOM;
+  bt_addr_copy(&bt_dev.random_addr.a, addr);
+  bt_dev.random_addr.type = BT_ADDR_LE_RANDOM;
 
-    return 0;
+  return 0;
 }
 
-int bt_addr_from_str(const char *str, bt_addr_t *addr)
-{
-    int i, j;
-    u8_t tmp;
-
-    if (strlen(str) != 17U) {
-        return -EINVAL;
-    }
+int bt_addr_from_str(const char *str, bt_addr_t *addr) {
+  int  i, j;
+  u8_t tmp;
 
-    for (i = 5, j = 1; *str != '\0'; str++, j++) {
-        if (!(j % 3) && (*str != ':')) {
-            return -EINVAL;
-        } else if (*str == ':') {
-            i--;
-            continue;
-        }
+  if (strlen(str) != 17U) {
+    return -EINVAL;
+  }
 
-        addr->val[i] = addr->val[i] << 4;
+  for (i = 5, j = 1; *str != '\0'; str++, j++) {
+    if (!(j % 3) && (*str != ':')) {
+      return -EINVAL;
+    } else if (*str == ':') {
+      i--;
+      continue;
+    }
 
-        if (char2hex(*str, &tmp) < 0) {
-            return -EINVAL;
-        }
+    addr->val[i] = addr->val[i] << 4;
 
-        addr->val[i] |= tmp;
+    if (char2hex(*str, &tmp) < 0) {
+      return -EINVAL;
     }
 
-    return 0;
+    addr->val[i] |= tmp;
+  }
+
+  return 0;
 }
 
-int bt_addr_le_from_str(const char *str, const char *type, bt_addr_le_t *addr)
-{
-    int err;
+int bt_addr_le_from_str(const char *str, const char *type, bt_addr_le_t *addr) {
+  int err;
 
-    err = bt_addr_from_str(str, &addr->a);
-    if (err < 0) {
-        return err;
-    }
+  err = bt_addr_from_str(str, &addr->a);
+  if (err < 0) {
+    return err;
+  }
 
-    if (!strcmp(type, "public") || !strcmp(type, "(public)")) {
-        addr->type = BT_ADDR_LE_PUBLIC;
-    } else if (!strcmp(type, "random") || !strcmp(type, "(random)")) {
-        addr->type = BT_ADDR_LE_RANDOM;
-    } else if (!strcmp(type, "public-id") || !strcmp(type, "(public-id)")) {
-        addr->type = BT_ADDR_LE_PUBLIC_ID;
-    } else if (!strcmp(type, "random-id") || !strcmp(type, "(random-id)")) {
-        addr->type = BT_ADDR_LE_RANDOM_ID;
-    } else {
-        return -EINVAL;
-    }
+  if (!strcmp(type, "public") || !strcmp(type, "(public)")) {
+    addr->type = BT_ADDR_LE_PUBLIC;
+  } else if (!strcmp(type, "random") || !strcmp(type, "(random)")) {
+    addr->type = BT_ADDR_LE_RANDOM;
+  } else if (!strcmp(type, "public-id") || !strcmp(type, "(public-id)")) {
+    addr->type = BT_ADDR_LE_PUBLIC_ID;
+  } else if (!strcmp(type, "random-id") || !strcmp(type, "(random-id)")) {
+    addr->type = BT_ADDR_LE_RANDOM_ID;
+  } else {
+    return -EINVAL;
+  }
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_PRIVACY)
 /* this function sets new RPA only if current one is no longer valid */
-static int le_set_private_addr(u8_t id)
-{
-    bt_addr_t rpa;
-    int err;
+static int le_set_private_addr(u8_t id) {
+  bt_addr_t rpa;
+  int       err;
 
-    /* check if RPA is valid */
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_RPA_VALID)) {
-        return 0;
-    }
+  /* check if RPA is valid */
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_RPA_VALID)) {
+    return 0;
+  }
 
-    err = bt_rpa_create(bt_dev.irk[id], &rpa);
+  err = bt_rpa_create(bt_dev.irk[id], &rpa);
+  if (!err) {
+    err = set_random_address(&rpa);
     if (!err) {
-        err = set_random_address(&rpa);
-        if (!err) {
-            atomic_set_bit(bt_dev.flags, BT_DEV_RPA_VALID);
-        }
+      atomic_set_bit(bt_dev.flags, BT_DEV_RPA_VALID);
     }
+  }
 
-    /* restart timer even if failed to set new RPA */
-    k_delayed_work_submit(&bt_dev.rpa_update, RPA_TIMEOUT);
+  /* restart timer even if failed to set new RPA */
+  k_delayed_work_submit(&bt_dev.rpa_update, RPA_TIMEOUT);
 
-    return err;
+  return err;
 }
 
-static void rpa_timeout(struct k_work *work)
-{
-    int err_adv = 0, err_scan = 0;
+static void rpa_timeout(struct k_work *work) {
+  int err_adv = 0, err_scan = 0;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    /* Invalidate RPA */
-    atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
+  /* Invalidate RPA */
+  atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
 
-    /*
-	 * we need to update rpa only if advertising is ongoing, with
-	 * BT_DEV_KEEP_ADVERTISING flag is handled in disconnected event
-	 */
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        /* make sure new address is used */
-        set_advertise_enable(false);
-        err_adv = le_set_private_addr(bt_dev.adv_id);
-        set_advertise_enable(true);
-    }
+  /*
+   * we need to update rpa only if advertising is ongoing, with
+   * BT_DEV_KEEP_ADVERTISING flag is handled in disconnected event
+   */
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    /* make sure new address is used */
+    set_advertise_enable(false);
+    err_adv = le_set_private_addr(bt_dev.adv_id);
+    set_advertise_enable(true);
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_ACTIVE_SCAN)) {
-        /* TODO do we need to toggle scan? */
-        err_scan = le_set_private_addr(BT_ID_DEFAULT);
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_ACTIVE_SCAN)) {
+    /* TODO do we need to toggle scan? */
+    err_scan = le_set_private_addr(BT_ID_DEFAULT);
+  }
 
-    /* If both advertising and scanning is active, le_set_private_addr
-	 * will fail. In this case, set back RPA_VALID so that if either of
-	 * advertising or scanning was restarted by application then
-	 * le_set_private_addr in the public API call path will not retry
-	 * set_random_address. This is needed so as to be able to stop and
-	 * restart either of the role by the application after rpa_timeout.
-	 */
-    if (err_adv || err_scan) {
-        atomic_set_bit(bt_dev.flags, BT_DEV_RPA_VALID);
-    }
+  /* If both advertising and scanning is active, le_set_private_addr
+   * will fail. In this case, set back RPA_VALID so that if either of
+   * advertising or scanning was restarted by application then
+   * le_set_private_addr in the public API call path will not retry
+   * set_random_address. This is needed so as to be able to stop and
+   * restart either of the role by the application after rpa_timeout.
+   */
+  if (err_adv || err_scan) {
+    atomic_set_bit(bt_dev.flags, BT_DEV_RPA_VALID);
+  }
 }
 
 #if defined(CONFIG_BT_STACK_PTS) || defined(CONFIG_AUTO_PTS)
-static int le_set_non_resolv_private_addr(u8_t id)
-{
-    bt_addr_t nrpa;
-    int err;
+static int le_set_non_resolv_private_addr(u8_t id) {
+  bt_addr_t nrpa;
+  int       err;
 
-    err = bt_rand(nrpa.val, sizeof(nrpa.val));
-    if (err) {
-        return err;
-    }
+  err = bt_rand(nrpa.val, sizeof(nrpa.val));
+  if (err) {
+    return err;
+  }
 
-    nrpa.val[5] &= 0x3f;
-    atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
-    return set_random_address(&nrpa);
+  nrpa.val[5] &= 0x3f;
+  atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
+  return set_random_address(&nrpa);
 }
 
 #endif
 
 #else
-static int le_set_private_addr(u8_t id)
-{
-    bt_addr_t nrpa;
-    int err;
+static int le_set_private_addr(u8_t id) {
+  bt_addr_t nrpa;
+  int       err;
 
-    err = bt_rand(nrpa.val, sizeof(nrpa.val));
-    if (err) {
-        return err;
-    }
+  err = bt_rand(nrpa.val, sizeof(nrpa.val));
+  if (err) {
+    return err;
+  }
 
-    nrpa.val[5] &= 0x3f;
+  nrpa.val[5] &= 0x3f;
 
-    return set_random_address(&nrpa);
+  return set_random_address(&nrpa);
 }
 #endif
 
 #if defined(CONFIG_BT_OBSERVER)
-static int set_le_scan_enable(u8_t enable)
-{
-    struct bt_hci_cp_le_set_scan_enable *cp;
-    struct net_buf *buf;
-    struct cmd_state_set state;
-    int err;
+static int set_le_scan_enable(u8_t enable) {
+  struct bt_hci_cp_le_set_scan_enable *cp;
+  struct net_buf                      *buf;
+  struct cmd_state_set                 state;
+  int                                  err;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_ENABLE, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_ENABLE, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
 
-    if (enable == BT_HCI_LE_SCAN_ENABLE) {
-        cp->filter_dup = atomic_test_bit(bt_dev.flags,
-                                         BT_DEV_SCAN_FILTER_DUP);
-    } else {
-        cp->filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE;
-    }
+  if (enable == BT_HCI_LE_SCAN_ENABLE) {
+    cp->filter_dup = atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP);
+  } else {
+    cp->filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE;
+  }
 
-    cp->enable = enable;
+  cp->enable = enable;
 
-    cmd_state_set_init(&state, bt_dev.flags, BT_DEV_SCANNING,
-                       enable == BT_HCI_LE_SCAN_ENABLE);
-    cmd(buf)->state = &state;
+  cmd_state_set_init(&state, bt_dev.flags, BT_DEV_SCANNING, enable == BT_HCI_LE_SCAN_ENABLE);
+  cmd(buf)->state = &state;
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_ENABLE, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_ENABLE, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_BT_OBSERVER */
 
 #if defined(CONFIG_BT_CONN)
-static void hci_acl(struct net_buf *buf)
-{
-    struct bt_hci_acl_hdr *hdr;
-    u16_t handle, len;
-    struct bt_conn *conn;
-    u8_t flags;
+static void hci_acl(struct net_buf *buf) {
+  struct bt_hci_acl_hdr *hdr;
+  u16_t                  handle, len;
+  struct bt_conn        *conn;
+  u8_t                   flags;
 
-    BT_DBG("buf %p", buf);
+  BT_DBG("buf %p", buf);
 
-    BT_ASSERT(buf->len >= sizeof(*hdr));
+  BT_ASSERT(buf->len >= sizeof(*hdr));
 
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    len = sys_le16_to_cpu(hdr->len);
-    handle = sys_le16_to_cpu(hdr->handle);
-    flags = bt_acl_flags(handle);
+  hdr    = net_buf_pull_mem(buf, sizeof(*hdr));
+  len    = sys_le16_to_cpu(hdr->len);
+  handle = sys_le16_to_cpu(hdr->handle);
+  flags  = bt_acl_flags(handle);
 
-    acl(buf)->handle = bt_acl_handle(handle);
-    acl(buf)->id = BT_CONN_ID_INVALID;
+  acl(buf)->handle = bt_acl_handle(handle);
+  acl(buf)->id     = BT_CONN_ID_INVALID;
 
-    BT_DBG("handle %u len %u flags %u", acl(buf)->handle, len, flags);
+  BT_DBG("handle %u len %u flags %u", acl(buf)->handle, len, flags);
 
-    if (buf->len != len) {
-        BT_ERR("ACL data length mismatch (%u != %u)", buf->len, len);
-        net_buf_unref(buf);
-        return;
-    }
+  if (buf->len != len) {
+    BT_ERR("ACL data length mismatch (%u != %u)", buf->len, len);
+    net_buf_unref(buf);
+    return;
+  }
 
-    conn = bt_conn_lookup_handle(acl(buf)->handle);
-    if (!conn) {
-        BT_ERR("Unable to find conn for handle %u", acl(buf)->handle);
-        net_buf_unref(buf);
-        return;
-    }
+  conn = bt_conn_lookup_handle(acl(buf)->handle);
+  if (!conn) {
+    BT_ERR("Unable to find conn for handle %u", acl(buf)->handle);
+    net_buf_unref(buf);
+    return;
+  }
 
-    acl(buf)->id = bt_conn_index(conn);
+  acl(buf)->id = bt_conn_index(conn);
 
-    bt_conn_recv(conn, buf, flags);
-    bt_conn_unref(conn);
+  bt_conn_recv(conn, buf, flags);
+  bt_conn_unref(conn);
 }
 
-static void hci_data_buf_overflow(struct net_buf *buf)
-{
-    struct bt_hci_evt_data_buf_overflow *evt = (void *)buf->data;
+static void hci_data_buf_overflow(struct net_buf *buf) {
+  struct bt_hci_evt_data_buf_overflow *evt = (void *)buf->data;
 
-    BT_WARN("Data buffer overflow (link type 0x%02x)", evt->link_type);
-    // avoid compiler warning if BT_WARN is empty
-    (void)evt;
+  BT_WARN("Data buffer overflow (link type 0x%02x)", evt->link_type);
+  // avoid compiler warning if BT_WARN is empty
+  (void)evt;
 }
 
-static void hci_num_completed_packets(struct net_buf *buf)
-{
-    struct bt_hci_evt_num_completed_packets *evt = (void *)buf->data;
-    int i;
+static void hci_num_completed_packets(struct net_buf *buf) {
+  struct bt_hci_evt_num_completed_packets *evt = (void *)buf->data;
+  int                                      i;
 
-    BT_DBG("num_handles %u", evt->num_handles);
+  BT_DBG("num_handles %u", evt->num_handles);
 
-    for (i = 0; i < evt->num_handles; i++) {
-        u16_t handle, count;
-        struct bt_conn *conn;
-        unsigned int key;
+  for (i = 0; i < evt->num_handles; i++) {
+    u16_t           handle, count;
+    struct bt_conn *conn;
+    unsigned int    key;
 
-        handle = sys_le16_to_cpu(evt->h[i].handle);
-        count = sys_le16_to_cpu(evt->h[i].count);
+    handle = sys_le16_to_cpu(evt->h[i].handle);
+    count  = sys_le16_to_cpu(evt->h[i].count);
 
-        BT_DBG("handle %u count %u", handle, count);
+    BT_DBG("handle %u count %u", handle, count);
 
-        key = irq_lock();
+    key = irq_lock();
 
-        conn = bt_conn_lookup_handle(handle);
-        if (!conn) {
-            irq_unlock(key);
-            BT_ERR("No connection for handle %u", handle);
-            continue;
-        }
+    conn = bt_conn_lookup_handle(handle);
+    if (!conn) {
+      irq_unlock(key);
+      BT_ERR("No connection for handle %u", handle);
+      continue;
+    }
 
-        irq_unlock(key);
+    irq_unlock(key);
 
-        while (count--) {
-            struct bt_conn_tx *tx;
-            sys_snode_t *node;
+    while (count--) {
+      struct bt_conn_tx *tx;
+      sys_snode_t       *node;
 
-            key = irq_lock();
+      key = irq_lock();
 
-            if (conn->pending_no_cb) {
-                conn->pending_no_cb--;
-                irq_unlock(key);
-                k_sem_give(bt_conn_get_pkts(conn));
-                continue;
-            }
+      if (conn->pending_no_cb) {
+        conn->pending_no_cb--;
+        irq_unlock(key);
+        k_sem_give(bt_conn_get_pkts(conn));
+        continue;
+      }
 
-            node = sys_slist_get(&conn->tx_pending);
-            irq_unlock(key);
+      node = sys_slist_get(&conn->tx_pending);
+      irq_unlock(key);
 
-            if (!node) {
-                BT_ERR("packets count mismatch");
-                break;
-            }
+      if (!node) {
+        BT_ERR("packets count mismatch");
+        break;
+      }
 
-            tx = CONTAINER_OF(node, struct bt_conn_tx, node);
+      tx = CONTAINER_OF(node, struct bt_conn_tx, node);
 
-            key = irq_lock();
-            conn->pending_no_cb = tx->pending_no_cb;
-            tx->pending_no_cb = 0U;
-            sys_slist_append(&conn->tx_complete, &tx->node);
-            irq_unlock(key);
+      key                 = irq_lock();
+      conn->pending_no_cb = tx->pending_no_cb;
+      tx->pending_no_cb   = 0U;
+      sys_slist_append(&conn->tx_complete, &tx->node);
+      irq_unlock(key);
 
-            k_work_submit(&conn->tx_complete_work);
-            k_sem_give(bt_conn_get_pkts(conn));
+      k_work_submit(&conn->tx_complete_work);
+      k_sem_give(bt_conn_get_pkts(conn));
 #if defined(BFLB_BLE)
-            k_sem_give(&g_poll_sem);
+      k_sem_give(&g_poll_sem);
 #endif
-        }
-
-        bt_conn_unref(conn);
     }
+
+    bt_conn_unref(conn);
+  }
 }
 
 #if defined(CONFIG_BT_CENTRAL)
 #if defined(CONFIG_BT_WHITELIST)
-int bt_le_auto_conn(const struct bt_le_conn_param *conn_param)
-{
-    struct net_buf *buf;
-    struct cmd_state_set state;
-    struct bt_hci_cp_le_create_conn *cp;
-    u8_t own_addr_type;
-    int err;
-
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
-        err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
-        if (err) {
-            return err;
-        }
+int bt_le_auto_conn(const struct bt_le_conn_param *conn_param) {
+  struct net_buf                  *buf;
+  struct cmd_state_set             state;
+  struct bt_hci_cp_le_create_conn *cp;
+  u8_t                             own_addr_type;
+  int                              err;
+
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
+    err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
+    if (err) {
+      return err;
     }
+  }
 
 #if defined(CONFIG_BT_STACK_PTS)
-    if (conn_param->own_address_type != BT_ADDR_LE_PUBLIC) {
-#endif
-
-        if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-            err = le_set_private_addr(BT_ID_DEFAULT);
-            if (err) {
-                return err;
-            }
-            if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
-                own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-            } else {
-                own_addr_type = BT_ADDR_LE_RANDOM;
-            }
-        } else {
-            const bt_addr_le_t *addr = &bt_dev.id_addr[BT_ID_DEFAULT];
-
-            /* If Static Random address is used as Identity address we
-			 * need to restore it before creating connection. Otherwise
-			 * NRPA used for active scan could be used for connection.
-			 */
-            if (addr->type == BT_ADDR_LE_RANDOM) {
-                err = set_random_address(&addr->a);
-                if (err) {
-                    return err;
-                }
-            }
-
-            own_addr_type = addr->type;
-        }
+  if (conn_param->own_address_type != BT_ADDR_LE_PUBLIC) {
+#endif
 
-#if defined(CONFIG_BT_STACK_PTS)
+    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+      err = le_set_private_addr(BT_ID_DEFAULT);
+      if (err) {
+        return err;
+      }
+      if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+        own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+      } else {
+        own_addr_type = BT_ADDR_LE_RANDOM;
+      }
     } else {
-        own_addr_type = conn_param->own_address_type;
+      const bt_addr_le_t *addr = &bt_dev.id_addr[BT_ID_DEFAULT];
+
+      /* If Static Random address is used as Identity address we
+       * need to restore it before creating connection. Otherwise
+       * NRPA used for active scan could be used for connection.
+       */
+      if (addr->type == BT_ADDR_LE_RANDOM) {
+        err = set_random_address(&addr->a);
+        if (err) {
+          return err;
+        }
+      }
+
+      own_addr_type = addr->type;
     }
+
+#if defined(CONFIG_BT_STACK_PTS)
+  } else {
+    own_addr_type = conn_param->own_address_type;
+  }
 #endif
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    (void)memset(cp, 0, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
+  (void)memset(cp, 0, sizeof(*cp));
 
-    cp->filter_policy = BT_HCI_LE_CREATE_CONN_FP_WHITELIST;
-    cp->own_addr_type = own_addr_type;
+  cp->filter_policy = BT_HCI_LE_CREATE_CONN_FP_WHITELIST;
+  cp->own_addr_type = own_addr_type;
 
-    /* User Initiated procedure use fast scan parameters. */
-    cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL);
-    cp->scan_window = sys_cpu_to_le16(BT_GAP_SCAN_FAST_WINDOW);
+  /* User Initiated procedure use fast scan parameters. */
+  cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL);
+  cp->scan_window   = sys_cpu_to_le16(BT_GAP_SCAN_FAST_WINDOW);
 
-    cp->conn_interval_min = sys_cpu_to_le16(conn_param->interval_min);
-    cp->conn_interval_max = sys_cpu_to_le16(conn_param->interval_max);
-    cp->conn_latency = sys_cpu_to_le16(conn_param->latency);
-    cp->supervision_timeout = sys_cpu_to_le16(conn_param->timeout);
+  cp->conn_interval_min   = sys_cpu_to_le16(conn_param->interval_min);
+  cp->conn_interval_max   = sys_cpu_to_le16(conn_param->interval_max);
+  cp->conn_latency        = sys_cpu_to_le16(conn_param->latency);
+  cp->supervision_timeout = sys_cpu_to_le16(conn_param->timeout);
 
-    cmd_state_set_init(&state, bt_dev.flags, BT_DEV_AUTO_CONN, true);
-    cmd(buf)->state = &state;
+  cmd_state_set_init(&state, bt_dev.flags, BT_DEV_AUTO_CONN, true);
+  cmd(buf)->state = &state;
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN, buf, NULL);
 }
 
-int bt_le_auto_conn_cancel(void)
-{
-    struct net_buf *buf;
-    struct cmd_state_set state;
+int bt_le_auto_conn_cancel(void) {
+  struct net_buf      *buf;
+  struct cmd_state_set state;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN_CANCEL, 0);
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN_CANCEL, 0);
 
-    cmd_state_set_init(&state, bt_dev.flags, BT_DEV_AUTO_CONN, false);
-    cmd(buf)->state = &state;
+  cmd_state_set_init(&state, bt_dev.flags, BT_DEV_AUTO_CONN, false);
+  cmd(buf)->state = &state;
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN_CANCEL, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN_CANCEL, buf, NULL);
 }
 #endif /* defined(CONFIG_BT_WHITELIST) */
 
-static int hci_le_create_conn(const struct bt_conn *conn)
-{
-    struct net_buf *buf;
-    struct bt_hci_cp_le_create_conn *cp;
-    u8_t own_addr_type;
-    const bt_addr_le_t *peer_addr;
-    int err;
+static int hci_le_create_conn(const struct bt_conn *conn) {
+  struct net_buf                  *buf;
+  struct bt_hci_cp_le_create_conn *cp;
+  u8_t                             own_addr_type;
+  const bt_addr_le_t              *peer_addr;
+  int                              err;
 
 #if defined(CONFIG_BT_STACK_PTS)
-    if (conn->le.own_adder_type == BT_ADDR_LE_PUBLIC || conn->le.own_adder_type == BT_ADDR_LE_PUBLIC_ID) {
-        own_addr_type = conn->le.own_adder_type;
-        goto start_connect;
-    }
+  if (conn->le.own_adder_type == BT_ADDR_LE_PUBLIC || conn->le.own_adder_type == BT_ADDR_LE_PUBLIC_ID) {
+    own_addr_type = conn->le.own_adder_type;
+    goto start_connect;
+  }
 
 #endif
 
-    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-        err = le_set_private_addr(conn->id);
-        if (err) {
-            return err;
-        }
+  if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    err = le_set_private_addr(conn->id);
+    if (err) {
+      return err;
+    }
 #if defined(BFLB_BLE)
-        /*Use random type at the first time*/
-        own_addr_type = BT_ADDR_LE_RANDOM;
+    /*Use random type at the first time*/
+    own_addr_type = BT_ADDR_LE_RANDOM;
 #if defined(CONFIG_BT_STACK_PTS)
-        if (conn->le.own_adder_type == BT_ADDR_LE_RANDOM_ID) {
-            own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-        }
+    if (conn->le.own_adder_type == BT_ADDR_LE_RANDOM_ID) {
+      own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+    }
 #endif
 #else
-        if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
-            own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-        } else {
-            own_addr_type = BT_ADDR_LE_RANDOM;
-        }
-#endif
+    if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+      own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
     } else {
-        /* If Static Random address is used as Identity address we
-		 * need to restore it before creating connection. Otherwise
-		 * NRPA used for active scan could be used for connection.
-		 */
-        const bt_addr_le_t *own_addr = &bt_dev.id_addr[conn->id];
-
-        if (own_addr->type == BT_ADDR_LE_RANDOM) {
-            err = set_random_address(&own_addr->a);
-            if (err) {
-                return err;
-            }
-        }
+      own_addr_type = BT_ADDR_LE_RANDOM;
+    }
+#endif
+  } else {
+    /* If Static Random address is used as Identity address we
+     * need to restore it before creating connection. Otherwise
+     * NRPA used for active scan could be used for connection.
+     */
+    const bt_addr_le_t *own_addr = &bt_dev.id_addr[conn->id];
 
-        own_addr_type = own_addr->type;
+    if (own_addr->type == BT_ADDR_LE_RANDOM) {
+      err = set_random_address(&own_addr->a);
+      if (err) {
+        return err;
+      }
     }
 
+    own_addr_type = own_addr->type;
+  }
+
 #if defined(CONFIG_BT_STACK_PTS)
 start_connect:
 #endif
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    (void)memset(cp, 0, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
+  (void)memset(cp, 0, sizeof(*cp));
 
-    /* Interval == window for continuous scanning */
-    cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL);
-    cp->scan_window = cp->scan_interval;
+  /* Interval == window for continuous scanning */
+  cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL);
+  cp->scan_window   = cp->scan_interval;
 
-    peer_addr = &conn->le.dst;
+  peer_addr = &conn->le.dst;
 
 #if defined(CONFIG_BT_SMP)
-    if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) {
-        /* Host resolving is used, use the RPA directly. */
-        peer_addr = &conn->le.resp_addr;
-    }
+  if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) {
+    /* Host resolving is used, use the RPA directly. */
+    peer_addr = &conn->le.resp_addr;
+  }
 #endif
 
-    bt_addr_le_copy(&cp->peer_addr, peer_addr);
-    cp->own_addr_type = own_addr_type;
-    cp->conn_interval_min = sys_cpu_to_le16(conn->le.interval_min);
-    cp->conn_interval_max = sys_cpu_to_le16(conn->le.interval_max);
-    cp->conn_latency = sys_cpu_to_le16(conn->le.latency);
-    cp->supervision_timeout = sys_cpu_to_le16(conn->le.timeout);
+  bt_addr_le_copy(&cp->peer_addr, peer_addr);
+  cp->own_addr_type       = own_addr_type;
+  cp->conn_interval_min   = sys_cpu_to_le16(conn->le.interval_min);
+  cp->conn_interval_max   = sys_cpu_to_le16(conn->le.interval_max);
+  cp->conn_latency        = sys_cpu_to_le16(conn->le.latency);
+  cp->supervision_timeout = sys_cpu_to_le16(conn->le.timeout);
 
 #if defined(CONFIG_BT_STACK_PTS)
-    if (event_flag == dir_connect_req) {
-        bt_addr_le_copy(&cp->peer_addr, &pts_addr);
+  if (event_flag == dir_connect_req) {
+    bt_addr_le_copy(&cp->peer_addr, &pts_addr);
 
-        cp->filter_policy = 0;
-        cp->own_addr_type = BT_ADDR_LE_PUBLIC;
+    cp->filter_policy = 0;
+    cp->own_addr_type = BT_ADDR_LE_PUBLIC;
 
-        /* User Initiated procedure use fast scan parameters. */
-        cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL);
-        cp->scan_window = sys_cpu_to_le16(BT_GAP_SCAN_FAST_WINDOW);
-    }
+    /* User Initiated procedure use fast scan parameters. */
+    cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL);
+    cp->scan_window   = sys_cpu_to_le16(BT_GAP_SCAN_FAST_WINDOW);
+  }
 #endif
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN, buf, NULL);
 }
 #endif /* CONFIG_BT_CENTRAL */
 
-static void hci_disconn_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_disconn_complete *evt = (void *)buf->data;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    struct bt_conn *conn;
+static void hci_disconn_complete(struct net_buf *buf) {
+  struct bt_hci_evt_disconn_complete *evt    = (void *)buf->data;
+  u16_t                               handle = sys_le16_to_cpu(evt->handle);
+  struct bt_conn                     *conn;
 
-    BT_DBG("status 0x%02x handle %u reason 0x%02x", evt->status, handle,
-           evt->reason);
+  BT_DBG("status 0x%02x handle %u reason 0x%02x", evt->status, handle, evt->reason);
 
-    if (evt->status) {
-        return;
-    }
+  if (evt->status) {
+    return;
+  }
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to look up conn with handle %u", handle);
-        goto advertise;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to look up conn with handle %u", handle);
+    goto advertise;
+  }
 
-    conn->err = evt->reason;
+  conn->err = evt->reason;
 
-    /* Check stacks usage */
+  /* Check stacks usage */
 #if !defined(CONFIG_BT_RECV_IS_RX_THREAD)
-    STACK_ANALYZE("rx stack", rx_thread_stack);
+  STACK_ANALYZE("rx stack", rx_thread_stack);
 #endif
 #if !defined(BFLB_BLE)
-    STACK_ANALYZE("tx stack", tx_thread_stack);
+  STACK_ANALYZE("tx stack", tx_thread_stack);
 #endif
 
-    bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
-    conn->handle = 0U;
+  bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
+  conn->handle = 0U;
 
-    if (conn->type != BT_CONN_TYPE_LE) {
+  if (conn->type != BT_CONN_TYPE_LE) {
 #if defined(CONFIG_BT_BREDR)
-        if (conn->type == BT_CONN_TYPE_SCO) {
-            bt_sco_cleanup(conn);
-            return;
-        }
-        /*
-		 * If only for one connection session bond was set, clear keys
-		 * database row for this connection.
-		 */
-        if (conn->type == BT_CONN_TYPE_BR &&
-            atomic_test_and_clear_bit(conn->flags, BT_CONN_BR_NOBOND)) {
-            bt_keys_link_key_clear(conn->br.link_key);
-        }
-#endif
-        bt_conn_unref(conn);
-        return;
+    if (conn->type == BT_CONN_TYPE_SCO) {
+      bt_sco_cleanup(conn);
+      return;
     }
+    /*
+     * If only for one connection session bond was set, clear keys
+     * database row for this connection.
+     */
+    if (conn->type == BT_CONN_TYPE_BR && atomic_test_and_clear_bit(conn->flags, BT_CONN_BR_NOBOND)) {
+      bt_keys_link_key_clear(conn->br.link_key);
+    }
+#endif
+    bt_conn_unref(conn);
+    return;
+  }
 
 #if defined(CONFIG_BT_CENTRAL) && !defined(CONFIG_BT_WHITELIST)
-    if (atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT)) {
-        bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
-        bt_le_scan_update(false);
-    }
+  if (atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT)) {
+    bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
+    bt_le_scan_update(false);
+  }
 #endif /* defined(CONFIG_BT_CENTRAL) && !defined(CONFIG_BT_WHITELIST) */
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 
 #if defined(BFLB_BLE_PATCH_CLEAN_UP_CONNECT_REF)
-    atomic_clear(&conn->ref);
+  atomic_clear(&conn->ref);
 #endif
 
 #if defined(BFLB_RELEASE_CMD_SEM_IF_CONN_DISC)
-    hci_release_conn_related_cmd();
+  hci_release_conn_related_cmd();
 #endif
 
 #if defined(CONFIG_BLE_RECONNECT_TEST)
-    if (conn->role == BT_CONN_ROLE_MASTER) {
-        struct bt_le_conn_param param = {
-            .interval_min = BT_GAP_INIT_CONN_INT_MIN,
-            .interval_max = BT_GAP_INIT_CONN_INT_MAX,
-            .latency = 0,
-            .timeout = 400,
-        };
-
-        if (bt_conn_create_le(&conn->le.dst, ¶m)) {
-            printf("Reconnecting. \n");
-        } else {
-            printf("Reconnect fail. \n");
-        }
+  if (conn->role == BT_CONN_ROLE_MASTER) {
+    struct bt_le_conn_param param = {
+        .interval_min = BT_GAP_INIT_CONN_INT_MIN,
+        .interval_max = BT_GAP_INIT_CONN_INT_MAX,
+        .latency      = 0,
+        .timeout      = 400,
+    };
+
+    if (bt_conn_create_le(&conn->le.dst, ¶m)) {
+      printf("Reconnecting. \n");
+    } else {
+      printf("Reconnect fail. \n");
     }
+  }
 #endif
 
 advertise:
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING) &&
-        !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-            le_set_private_addr(bt_dev.adv_id);
-        }
-
-        set_advertise_enable(true);
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING) && !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+      le_set_private_addr(bt_dev.adv_id);
     }
+
+    set_advertise_enable(true);
+  }
 }
 
-static int hci_le_read_remote_features(struct bt_conn *conn)
-{
-    struct bt_hci_cp_le_read_remote_features *cp;
-    struct net_buf *buf;
+static int hci_le_read_remote_features(struct bt_conn *conn) {
+  struct bt_hci_cp_le_read_remote_features *cp;
+  struct net_buf                           *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_READ_REMOTE_FEATURES,
-                            sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_READ_REMOTE_FEATURES, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(conn->handle);
-    bt_hci_cmd_send(BT_HCI_OP_LE_READ_REMOTE_FEATURES, buf);
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = sys_cpu_to_le16(conn->handle);
+  bt_hci_cmd_send(BT_HCI_OP_LE_READ_REMOTE_FEATURES, buf);
 
-    return 0;
+  return 0;
 }
 
 /* LE Data Length Change Event is optional so this function just ignore
  * error and stack will continue to use default values.
  */
-static void hci_le_set_data_len(struct bt_conn *conn)
-{
-    struct bt_hci_rp_le_read_max_data_len *rp;
-    struct bt_hci_cp_le_set_data_len *cp;
-    struct net_buf *buf, *rsp;
-    u16_t tx_octets, tx_time;
-    int err;
-
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_MAX_DATA_LEN, NULL, &rsp);
-    if (err) {
-        BT_ERR("Failed to read DLE max data len");
-        return;
-    }
+static void hci_le_set_data_len(struct bt_conn *conn) {
+  struct bt_hci_rp_le_read_max_data_len *rp;
+  struct bt_hci_cp_le_set_data_len      *cp;
+  struct net_buf                        *buf, *rsp;
+  u16_t                                  tx_octets, tx_time;
+  int                                    err;
+
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_MAX_DATA_LEN, NULL, &rsp);
+  if (err) {
+    BT_ERR("Failed to read DLE max data len");
+    return;
+  }
 
-    rp = (void *)rsp->data;
-    tx_octets = sys_le16_to_cpu(rp->max_tx_octets);
-    tx_time = sys_le16_to_cpu(rp->max_tx_time);
-    net_buf_unref(rsp);
+  rp        = (void *)rsp->data;
+  tx_octets = sys_le16_to_cpu(rp->max_tx_octets);
+  tx_time   = sys_le16_to_cpu(rp->max_tx_time);
+  net_buf_unref(rsp);
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DATA_LEN, sizeof(*cp));
-    if (!buf) {
-        BT_ERR("Failed to create LE Set Data Length Command");
-        return;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DATA_LEN, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("Failed to create LE Set Data Length Command");
+    return;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(conn->handle);
-    cp->tx_octets = sys_cpu_to_le16(tx_octets);
-    cp->tx_time = sys_cpu_to_le16(tx_time);
-    err = bt_hci_cmd_send(BT_HCI_OP_LE_SET_DATA_LEN, buf);
-    if (err) {
-        BT_ERR("Failed to send LE Set Data Length Command");
-    }
+  cp            = net_buf_add(buf, sizeof(*cp));
+  cp->handle    = sys_cpu_to_le16(conn->handle);
+  cp->tx_octets = sys_cpu_to_le16(tx_octets);
+  cp->tx_time   = sys_cpu_to_le16(tx_time);
+  err           = bt_hci_cmd_send(BT_HCI_OP_LE_SET_DATA_LEN, buf);
+  if (err) {
+    BT_ERR("Failed to send LE Set Data Length Command");
+  }
 }
 
-int bt_le_set_data_len(struct bt_conn *conn, u16_t tx_octets, u16_t tx_time)
-{
-    struct bt_hci_cp_le_set_data_len *cp;
-    struct net_buf *buf;
+int bt_le_set_data_len(struct bt_conn *conn, u16_t tx_octets, u16_t tx_time) {
+  struct bt_hci_cp_le_set_data_len *cp;
+  struct net_buf                   *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DATA_LEN, sizeof(*cp));
-    if (!buf) {
-        BT_ERR("bt_le_set_data_len, Failed to create LE Set Data Length Command");
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DATA_LEN, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("bt_le_set_data_len, Failed to create LE Set Data Length Command");
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(conn->handle);
-    cp->tx_octets = sys_cpu_to_le16(tx_octets);
-    cp->tx_time = sys_cpu_to_le16(tx_time);
+  cp            = net_buf_add(buf, sizeof(*cp));
+  cp->handle    = sys_cpu_to_le16(conn->handle);
+  cp->tx_octets = sys_cpu_to_le16(tx_octets);
+  cp->tx_time   = sys_cpu_to_le16(tx_time);
 
-    return bt_hci_cmd_send(BT_HCI_OP_LE_SET_DATA_LEN, buf);
+  return bt_hci_cmd_send(BT_HCI_OP_LE_SET_DATA_LEN, buf);
 }
 
-int hci_le_set_phy(struct bt_conn *conn)
-{
-    struct bt_hci_cp_le_set_phy *cp;
-    struct net_buf *buf;
+int hci_le_set_phy(struct bt_conn *conn) {
+  struct bt_hci_cp_le_set_phy *cp;
+  struct net_buf              *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PHY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PHY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(conn->handle);
-    cp->all_phys = 0U;
-    cp->tx_phys = BT_HCI_LE_PHY_PREFER_2M;
-    cp->rx_phys = BT_HCI_LE_PHY_PREFER_2M;
-    cp->phy_opts = BT_HCI_LE_PHY_CODED_ANY;
-    bt_hci_cmd_send(BT_HCI_OP_LE_SET_PHY, buf);
+  cp           = net_buf_add(buf, sizeof(*cp));
+  cp->handle   = sys_cpu_to_le16(conn->handle);
+  cp->all_phys = 0U;
+  cp->tx_phys  = BT_HCI_LE_PHY_PREFER_2M;
+  cp->rx_phys  = BT_HCI_LE_PHY_PREFER_2M;
+  cp->phy_opts = BT_HCI_LE_PHY_CODED_ANY;
+  bt_hci_cmd_send(BT_HCI_OP_LE_SET_PHY, buf);
 
-    return 0;
+  return 0;
 }
 
-int hci_le_set_default_phy(struct bt_conn *conn, u8_t default_phy)
-{
-    struct bt_hci_cp_le_set_default_phy *cp;
-    struct net_buf *buf;
+int hci_le_set_default_phy(struct bt_conn *conn, u8_t default_phy) {
+  struct bt_hci_cp_le_set_default_phy *cp;
+  struct net_buf                      *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DEFAULT_PHY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DEFAULT_PHY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->all_phys = 0U;
-    cp->tx_phys = default_phy;
-    cp->rx_phys = default_phy;
-    bt_hci_cmd_send(BT_HCI_OP_LE_SET_DEFAULT_PHY, buf);
+  cp           = net_buf_add(buf, sizeof(*cp));
+  cp->all_phys = 0U;
+  cp->tx_phys  = default_phy;
+  cp->rx_phys  = default_phy;
+  bt_hci_cmd_send(BT_HCI_OP_LE_SET_DEFAULT_PHY, buf);
 
-    return 0;
+  return 0;
 }
 
-static void slave_update_conn_param(struct bt_conn *conn)
-{
-    if (!IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
-        return;
-    }
+static void slave_update_conn_param(struct bt_conn *conn) {
+  if (!IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
+    return;
+  }
 
-    /* don't start timer again on PHY update etc */
-    if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE)) {
-        return;
-    }
+  /* don't start timer again on PHY update etc */
+  if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE)) {
+    return;
+  }
 
-    /*
-	 * Core 4.2 Vol 3, Part C, 9.3.12.2
-	 * The Peripheral device should not perform a Connection Parameter
-	 * Update procedure within 5 s after establishing a connection.
-	 */
-    k_delayed_work_submit(&conn->update_work, CONN_UPDATE_TIMEOUT);
+  /*
+   * Core 4.2 Vol 3, Part C, 9.3.12.2
+   * The Peripheral device should not perform a Connection Parameter
+   * Update procedure within 5 s after establishing a connection.
+   */
+  k_delayed_work_submit(&conn->update_work, CONN_UPDATE_TIMEOUT);
 }
 
 #if defined(CONFIG_BT_SMP)
-static void update_pending_id(struct bt_keys *keys, void *data)
-{
-    if (keys->flags & BT_KEYS_ID_PENDING_ADD) {
-        keys->flags &= ~BT_KEYS_ID_PENDING_ADD;
-        bt_id_add(keys);
-        return;
-    }
+static void update_pending_id(struct bt_keys *keys, void *data) {
+  if (keys->flags & BT_KEYS_ID_PENDING_ADD) {
+    keys->flags &= ~BT_KEYS_ID_PENDING_ADD;
+    bt_id_add(keys);
+    return;
+  }
 
-    if (keys->flags & BT_KEYS_ID_PENDING_DEL) {
-        keys->flags &= ~BT_KEYS_ID_PENDING_DEL;
-        bt_id_del(keys);
-        return;
-    }
+  if (keys->flags & BT_KEYS_ID_PENDING_DEL) {
+    keys->flags &= ~BT_KEYS_ID_PENDING_DEL;
+    bt_id_del(keys);
+    return;
+  }
 }
 #endif
 
-static struct bt_conn *find_pending_connect(bt_addr_le_t *peer_addr)
-{
-    struct bt_conn *conn;
+static struct bt_conn *find_pending_connect(bt_addr_le_t *peer_addr) {
+  struct bt_conn *conn;
 
-    /*
-	 * Make lookup to check if there's a connection object in
-	 * CONNECT or DIR_ADV state associated with passed peer LE address.
-	 */
-    conn = bt_conn_lookup_state_le(peer_addr, BT_CONN_CONNECT);
-    if (conn) {
-        return conn;
-    }
+  /*
+   * Make lookup to check if there's a connection object in
+   * CONNECT or DIR_ADV state associated with passed peer LE address.
+   */
+  conn = bt_conn_lookup_state_le(peer_addr, BT_CONN_CONNECT);
+  if (conn) {
+    return conn;
+  }
 
-    return bt_conn_lookup_state_le(peer_addr, BT_CONN_CONNECT_DIR_ADV);
+  return bt_conn_lookup_state_le(peer_addr, BT_CONN_CONNECT_DIR_ADV);
 }
 
-static void enh_conn_complete(struct bt_hci_evt_le_enh_conn_complete *evt)
-{
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    bt_addr_le_t peer_addr, id_addr;
-    struct bt_conn *conn;
-    int err;
+static void enh_conn_complete(struct bt_hci_evt_le_enh_conn_complete *evt) {
+  u16_t           handle = sys_le16_to_cpu(evt->handle);
+  bt_addr_le_t    peer_addr, id_addr;
+  struct bt_conn *conn;
+  int             err;
 
-    BT_DBG("status 0x%02x handle %u role %u %s", evt->status, handle,
-           evt->role, bt_addr_le_str(&evt->peer_addr));
+  BT_DBG("status 0x%02x handle %u role %u %s", evt->status, handle, evt->role, bt_addr_le_str(&evt->peer_addr));
 
 #if defined(CONFIG_BT_SMP)
-    if (atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_ID_PENDING)) {
-        bt_keys_foreach(BT_KEYS_IRK, update_pending_id, NULL);
-    }
-#endif
-
-    if (evt->status) {
-        /*
-		 * If there was an error we are only interested in pending
-		 * connection. There is no need to check ID address as
-		 * only one connection can be in that state.
-		 *
-		 * Depending on error code address might not be valid anyway.
-		 */
-        conn = find_pending_connect(NULL);
-        if (!conn) {
-            return;
-        }
+  if (atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_ID_PENDING)) {
+    bt_keys_foreach(BT_KEYS_IRK, update_pending_id, NULL);
+  }
+#endif
 
-        conn->err = evt->status;
+  if (evt->status) {
+    /*
+     * If there was an error we are only interested in pending
+     * connection. There is no need to check ID address as
+     * only one connection can be in that state.
+     *
+     * Depending on error code address might not be valid anyway.
+     */
+    conn = find_pending_connect(NULL);
+    if (!conn) {
+      return;
+    }
 
-        if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
-            /*
-			 * Handle advertising timeout after high duty directed
-			 * advertising.
-			 */
-            if (conn->err == BT_HCI_ERR_ADV_TIMEOUT) {
-                atomic_clear_bit(bt_dev.flags,
-                                 BT_DEV_ADVERTISING);
-                bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
+    conn->err = evt->status;
 
-                goto done;
-            }
-        }
+    if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
+      /*
+       * Handle advertising timeout after high duty directed
+       * advertising.
+       */
+      if (conn->err == BT_HCI_ERR_ADV_TIMEOUT) {
+        atomic_clear_bit(bt_dev.flags, BT_DEV_ADVERTISING);
+        bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
+
+        goto done;
+      }
+    }
 
-        if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
-            /*
-			 * Handle cancellation of outgoing connection attempt.
-			 */
-            if (conn->err == BT_HCI_ERR_UNKNOWN_CONN_ID) {
-                /* We notify before checking autoconnect flag
-				 * as application may choose to change it from
-				 * callback.
-				 */
-                bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
+    if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
+      /*
+       * Handle cancellation of outgoing connection attempt.
+       */
+      if (conn->err == BT_HCI_ERR_UNKNOWN_CONN_ID) {
+        /* We notify before checking autoconnect flag
+         * as application may choose to change it from
+         * callback.
+         */
+        bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
 
 #if !defined(CONFIG_BT_WHITELIST)
-                /* Check if device is marked for autoconnect. */
-                if (atomic_test_bit(conn->flags,
-                                    BT_CONN_AUTO_CONNECT)) {
-                    bt_conn_set_state(conn,
-                                      BT_CONN_CONNECT_SCAN);
-                }
-#endif /* !defined(CONFIG_BT_WHITELIST) */
-                goto done;
-            }
+        /* Check if device is marked for autoconnect. */
+        if (atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT)) {
+          bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
         }
+#endif /* !defined(CONFIG_BT_WHITELIST) */
+        goto done;
+      }
+    }
 
-        BT_WARN("Unexpected status 0x%02x", evt->status);
-
-        bt_conn_unref(conn);
+    BT_WARN("Unexpected status 0x%02x", evt->status);
 
-        return;
-    }
+    bt_conn_unref(conn);
 
-    bt_addr_le_copy(&id_addr, &evt->peer_addr);
+    return;
+  }
 
-    /* Translate "enhanced" identity address type to normal one */
-    if (id_addr.type == BT_ADDR_LE_PUBLIC_ID ||
-        id_addr.type == BT_ADDR_LE_RANDOM_ID) {
-        id_addr.type -= BT_ADDR_LE_PUBLIC_ID;
-        bt_addr_copy(&peer_addr.a, &evt->peer_rpa);
-        peer_addr.type = BT_ADDR_LE_RANDOM;
-    } else {
-        bt_addr_le_copy(&peer_addr, &evt->peer_addr);
-    }
+  bt_addr_le_copy(&id_addr, &evt->peer_addr);
 
-    conn = find_pending_connect(&id_addr);
+  /* Translate "enhanced" identity address type to normal one */
+  if (id_addr.type == BT_ADDR_LE_PUBLIC_ID || id_addr.type == BT_ADDR_LE_RANDOM_ID) {
+    id_addr.type -= BT_ADDR_LE_PUBLIC_ID;
+    bt_addr_copy(&peer_addr.a, &evt->peer_rpa);
+    peer_addr.type = BT_ADDR_LE_RANDOM;
+  } else {
+    bt_addr_le_copy(&peer_addr, &evt->peer_addr);
+  }
 
-    if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
-        evt->role == BT_HCI_ROLE_SLAVE) {
-        /*
-		 * clear advertising even if we are not able to add connection
-		 * object to keep host in sync with controller state
-		 */
-        atomic_clear_bit(bt_dev.flags, BT_DEV_ADVERTISING);
+  conn = find_pending_connect(&id_addr);
 
-        /* for slave we may need to add new connection */
-        if (!conn) {
-            conn = bt_conn_add_le(bt_dev.adv_id, &id_addr);
-        }
-    }
+  if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && evt->role == BT_HCI_ROLE_SLAVE) {
+    /*
+     * clear advertising even if we are not able to add connection
+     * object to keep host in sync with controller state
+     */
+    atomic_clear_bit(bt_dev.flags, BT_DEV_ADVERTISING);
 
-    if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
-        IS_ENABLED(CONFIG_BT_WHITELIST) &&
-        evt->role == BT_HCI_ROLE_MASTER) {
-        /* for whitelist initiator me may need to add new connection. */
-        if (!conn) {
-            conn = bt_conn_add_le(BT_ID_DEFAULT, &id_addr);
-        }
+    /* for slave we may need to add new connection */
+    if (!conn) {
+      conn = bt_conn_add_le(bt_dev.adv_id, &id_addr);
     }
+  }
 
+  if (IS_ENABLED(CONFIG_BT_CENTRAL) && IS_ENABLED(CONFIG_BT_WHITELIST) && evt->role == BT_HCI_ROLE_MASTER) {
+    /* for whitelist initiator me may need to add new connection. */
     if (!conn) {
-        BT_ERR("Unable to add new conn for handle %u", handle);
-        return;
+      conn = bt_conn_add_le(BT_ID_DEFAULT, &id_addr);
     }
+  }
 
-    conn->handle = handle;
-    bt_addr_le_copy(&conn->le.dst, &id_addr);
-    conn->le.interval = sys_le16_to_cpu(evt->interval);
-    conn->le.latency = sys_le16_to_cpu(evt->latency);
-    conn->le.timeout = sys_le16_to_cpu(evt->supv_timeout);
-    conn->role = evt->role;
-    conn->err = 0U;
+  if (!conn) {
+    BT_ERR("Unable to add new conn for handle %u", handle);
+    return;
+  }
+
+  conn->handle = handle;
+  bt_addr_le_copy(&conn->le.dst, &id_addr);
+  conn->le.interval = sys_le16_to_cpu(evt->interval);
+  conn->le.latency  = sys_le16_to_cpu(evt->latency);
+  conn->le.timeout  = sys_le16_to_cpu(evt->supv_timeout);
+  conn->role        = evt->role;
+  conn->err         = 0U;
+
+  /*
+   * Use connection address (instead of identity address) as initiator
+   * or responder address. Only slave needs to be updated. For master all
+   * was set during outgoing connection creation.
+   */
+  if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn->role == BT_HCI_ROLE_SLAVE) {
+    bt_addr_le_copy(&conn->le.init_addr, &peer_addr);
 
-    /*
-	 * Use connection address (instead of identity address) as initiator
-	 * or responder address. Only slave needs to be updated. For master all
-	 * was set during outgoing connection creation.
-	 */
-    if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
-        conn->role == BT_HCI_ROLE_SLAVE) {
-        bt_addr_le_copy(&conn->le.init_addr, &peer_addr);
-
-        if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
 #if defined(BFLB_BLE_PATCH_DHKEY_CHECK_FAILED)
-            if (memcmp(&evt->local_rpa, BT_ADDR_ANY, sizeof(bt_addr_t)))
-                bt_addr_copy(&conn->le.resp_addr.a, &evt->local_rpa);
-            else
-                bt_addr_copy(&conn->le.resp_addr.a, &bt_dev.random_addr.a);
+      if (memcmp(&evt->local_rpa, BT_ADDR_ANY, sizeof(bt_addr_t)))
+        bt_addr_copy(&conn->le.resp_addr.a, &evt->local_rpa);
+      else
+        bt_addr_copy(&conn->le.resp_addr.a, &bt_dev.random_addr.a);
 #else
-            bt_addr_copy(&conn->le.resp_addr.a, &evt->local_rpa);
+      bt_addr_copy(&conn->le.resp_addr.a, &evt->local_rpa);
 #endif
-            conn->le.resp_addr.type = BT_ADDR_LE_RANDOM;
-        } else {
-            bt_addr_le_copy(&conn->le.resp_addr,
-                            &bt_dev.id_addr[conn->id]);
-        }
+      conn->le.resp_addr.type = BT_ADDR_LE_RANDOM;
+    } else {
+      bt_addr_le_copy(&conn->le.resp_addr, &bt_dev.id_addr[conn->id]);
+    }
 
 #if defined(CONFIG_BT_STACK_PTS)
-        if (atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_ADV_ADDRESS_IS_PUBLIC)) {
-            bt_addr_le_copy(&conn->le.resp_addr, &bt_dev.id_addr[conn->id]);
-        }
+    if (atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_ADV_ADDRESS_IS_PUBLIC)) {
+      bt_addr_le_copy(&conn->le.resp_addr, &bt_dev.id_addr[conn->id]);
+    }
 #endif
 
-        /* if the controller supports, lets advertise for another
-		 * slave connection.
-		 * check for connectable advertising state is sufficient as
-		 * this is how this le connection complete for slave occurred.
-		 */
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING) &&
-            BT_LE_STATES_SLAVE_CONN_ADV(bt_dev.le.states)) {
-            if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-                le_set_private_addr(bt_dev.adv_id);
-            }
+    /* if the controller supports, lets advertise for another
+     * slave connection.
+     * check for connectable advertising state is sufficient as
+     * this is how this le connection complete for slave occurred.
+     */
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING) && BT_LE_STATES_SLAVE_CONN_ADV(bt_dev.le.states)) {
+      if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+        le_set_private_addr(bt_dev.adv_id);
+      }
 
-            set_advertise_enable(true);
-        }
+      set_advertise_enable(true);
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
-        conn->role == BT_HCI_ROLE_MASTER) {
-        if (IS_ENABLED(CONFIG_BT_WHITELIST) &&
-            atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
-            conn->id = BT_ID_DEFAULT;
-            atomic_clear_bit(bt_dev.flags, BT_DEV_AUTO_CONN);
-        }
+  if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_HCI_ROLE_MASTER) {
+    if (IS_ENABLED(CONFIG_BT_WHITELIST) && atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
+      conn->id = BT_ID_DEFAULT;
+      atomic_clear_bit(bt_dev.flags, BT_DEV_AUTO_CONN);
+    }
 
-        bt_addr_le_copy(&conn->le.resp_addr, &peer_addr);
+    bt_addr_le_copy(&conn->le.resp_addr, &peer_addr);
 
-        if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
 #if defined(BFLB_BLE_PATCH_DHKEY_CHECK_FAILED)
-            if (memcmp(&evt->local_rpa, BT_ADDR_ANY, sizeof(bt_addr_t)))
-                bt_addr_copy(&conn->le.init_addr.a, &evt->local_rpa);
-            else
-                bt_addr_copy(&conn->le.init_addr.a, &bt_dev.random_addr.a);
+      if (memcmp(&evt->local_rpa, BT_ADDR_ANY, sizeof(bt_addr_t)))
+        bt_addr_copy(&conn->le.init_addr.a, &evt->local_rpa);
+      else
+        bt_addr_copy(&conn->le.init_addr.a, &bt_dev.random_addr.a);
 #else
-            bt_addr_copy(&conn->le.init_addr.a, &evt->local_rpa);
+      bt_addr_copy(&conn->le.init_addr.a, &evt->local_rpa);
 #endif
-            conn->le.init_addr.type = BT_ADDR_LE_RANDOM;
-        } else {
-            bt_addr_le_copy(&conn->le.init_addr,
-                            &bt_dev.id_addr[conn->id]);
-        }
+      conn->le.init_addr.type = BT_ADDR_LE_RANDOM;
+    } else {
+      bt_addr_le_copy(&conn->le.init_addr, &bt_dev.id_addr[conn->id]);
+    }
 
 #if defined(CONFIG_BT_STACK_PTS)
-        if (conn->le.own_adder_type == BT_ADDR_LE_PUBLIC_ID) {
-            bt_addr_le_copy(&conn->le.init_addr, &bt_dev.id_addr[conn->id]);
-        }
-#endif
+    if (conn->le.own_adder_type == BT_ADDR_LE_PUBLIC_ID) {
+      bt_addr_le_copy(&conn->le.init_addr, &bt_dev.id_addr[conn->id]);
     }
+#endif
+  }
 
-    bt_conn_set_state(conn, BT_CONN_CONNECTED);
+  bt_conn_set_state(conn, BT_CONN_CONNECTED);
 
-    /*
-	 * it is possible that connection was disconnected directly from
-	 * connected callback so we must check state before doing connection
-	 * parameters update
-	 */
-    if (conn->state != BT_CONN_CONNECTED) {
-        goto done;
-    }
+  /*
+   * it is possible that connection was disconnected directly from
+   * connected callback so we must check state before doing connection
+   * parameters update
+   */
+  if (conn->state != BT_CONN_CONNECTED) {
+    goto done;
+  }
 
-    if ((evt->role == BT_HCI_ROLE_MASTER) ||
-        BT_FEAT_LE_SLAVE_FEATURE_XCHG(bt_dev.le.features)) {
-        err = hci_le_read_remote_features(conn);
-        if (!err) {
-            goto done;
-        }
+  if ((evt->role == BT_HCI_ROLE_MASTER) || BT_FEAT_LE_SLAVE_FEATURE_XCHG(bt_dev.le.features)) {
+    err = hci_le_read_remote_features(conn);
+    if (!err) {
+      goto done;
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) &&
-        BT_FEAT_LE_PHY_2M(bt_dev.le.features)) {
-        err = hci_le_set_phy(conn);
-        if (!err) {
-            atomic_set_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE);
-            goto done;
-        }
+  if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) && BT_FEAT_LE_PHY_2M(bt_dev.le.features)) {
+    err = hci_le_set_phy(conn);
+    if (!err) {
+      atomic_set_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE);
+      goto done;
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) &&
-        BT_FEAT_LE_DLE(bt_dev.le.features)) {
-        hci_le_set_data_len(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && BT_FEAT_LE_DLE(bt_dev.le.features)) {
+    hci_le_set_data_len(conn);
+  }
 
-    if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
-        conn->role == BT_CONN_ROLE_SLAVE) {
-        slave_update_conn_param(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn->role == BT_CONN_ROLE_SLAVE) {
+    slave_update_conn_param(conn);
+  }
 
 done:
-    bt_conn_unref(conn);
-    if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
-        bt_le_scan_update(false);
-    }
+  bt_conn_unref(conn);
+  if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
+    bt_le_scan_update(false);
+  }
 }
 
-static void le_enh_conn_complete(struct net_buf *buf)
-{
-    enh_conn_complete((void *)buf->data);
-}
+static void le_enh_conn_complete(struct net_buf *buf) { enh_conn_complete((void *)buf->data); }
 
-static void le_legacy_conn_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_conn_complete *evt = (void *)buf->data;
-    struct bt_hci_evt_le_enh_conn_complete enh;
-    const bt_addr_le_t *id_addr;
+static void le_legacy_conn_complete(struct net_buf *buf) {
+  struct bt_hci_evt_le_conn_complete    *evt = (void *)buf->data;
+  struct bt_hci_evt_le_enh_conn_complete enh;
+  const bt_addr_le_t                    *id_addr;
 
-    BT_DBG("status 0x%02x role %u %s", evt->status, evt->role,
-           bt_addr_le_str(&evt->peer_addr));
+  BT_DBG("status 0x%02x role %u %s", evt->status, evt->role, bt_addr_le_str(&evt->peer_addr));
 
-    enh.status = evt->status;
-    enh.handle = evt->handle;
-    enh.role = evt->role;
-    enh.interval = evt->interval;
-    enh.latency = evt->latency;
-    enh.supv_timeout = evt->supv_timeout;
-    enh.clock_accuracy = evt->clock_accuracy;
+  enh.status         = evt->status;
+  enh.handle         = evt->handle;
+  enh.role           = evt->role;
+  enh.interval       = evt->interval;
+  enh.latency        = evt->latency;
+  enh.supv_timeout   = evt->supv_timeout;
+  enh.clock_accuracy = evt->clock_accuracy;
 
-    bt_addr_le_copy(&enh.peer_addr, &evt->peer_addr);
+  bt_addr_le_copy(&enh.peer_addr, &evt->peer_addr);
 
-    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-        bt_addr_copy(&enh.local_rpa, &bt_dev.random_addr.a);
-    } else {
-        bt_addr_copy(&enh.local_rpa, BT_ADDR_ANY);
-    }
+  if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    bt_addr_copy(&enh.local_rpa, &bt_dev.random_addr.a);
+  } else {
+    bt_addr_copy(&enh.local_rpa, BT_ADDR_ANY);
+  }
 
-    if (evt->role == BT_HCI_ROLE_SLAVE) {
-        id_addr = bt_lookup_id_addr(bt_dev.adv_id, &enh.peer_addr);
-    } else {
-        id_addr = bt_lookup_id_addr(BT_ID_DEFAULT, &enh.peer_addr);
-    }
+  if (evt->role == BT_HCI_ROLE_SLAVE) {
+    id_addr = bt_lookup_id_addr(bt_dev.adv_id, &enh.peer_addr);
+  } else {
+    id_addr = bt_lookup_id_addr(BT_ID_DEFAULT, &enh.peer_addr);
+  }
 
-    if (id_addr != &enh.peer_addr) {
-        bt_addr_copy(&enh.peer_rpa, &enh.peer_addr.a);
-        bt_addr_le_copy(&enh.peer_addr, id_addr);
-        enh.peer_addr.type += BT_ADDR_LE_PUBLIC_ID;
-    } else {
-        bt_addr_copy(&enh.peer_rpa, BT_ADDR_ANY);
-    }
+  if (id_addr != &enh.peer_addr) {
+    bt_addr_copy(&enh.peer_rpa, &enh.peer_addr.a);
+    bt_addr_le_copy(&enh.peer_addr, id_addr);
+    enh.peer_addr.type += BT_ADDR_LE_PUBLIC_ID;
+  } else {
+    bt_addr_copy(&enh.peer_rpa, BT_ADDR_ANY);
+  }
 
-    enh_conn_complete(&enh);
+  enh_conn_complete(&enh);
 }
 
-static void le_remote_feat_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_remote_feat_complete *evt = (void *)buf->data;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    struct bt_conn *conn;
+static void le_remote_feat_complete(struct net_buf *buf) {
+  struct bt_hci_evt_le_remote_feat_complete *evt    = (void *)buf->data;
+  u16_t                                      handle = sys_le16_to_cpu(evt->handle);
+  struct bt_conn                            *conn;
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to lookup conn for handle %u", handle);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to lookup conn for handle %u", handle);
+    return;
+  }
 
-    if (!evt->status) {
-        memcpy(conn->le.features, evt->features,
-               sizeof(conn->le.features));
-    }
+  if (!evt->status) {
+    memcpy(conn->le.features, evt->features, sizeof(conn->le.features));
+  }
 
-    if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) &&
-        BT_FEAT_LE_PHY_2M(bt_dev.le.features) &&
-        BT_FEAT_LE_PHY_2M(conn->le.features)) {
-        int err;
+  if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) && BT_FEAT_LE_PHY_2M(bt_dev.le.features) && BT_FEAT_LE_PHY_2M(conn->le.features)) {
+    int err;
 
-        err = hci_le_set_phy(conn);
-        if (!err) {
-            atomic_set_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE);
-            goto done;
-        }
+    err = hci_le_set_phy(conn);
+    if (!err) {
+      atomic_set_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE);
+      goto done;
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) &&
-        BT_FEAT_LE_DLE(bt_dev.le.features) &&
-        BT_FEAT_LE_DLE(conn->le.features)) {
-        hci_le_set_data_len(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && BT_FEAT_LE_DLE(bt_dev.le.features) && BT_FEAT_LE_DLE(conn->le.features)) {
+    hci_le_set_data_len(conn);
+  }
 
 #if !defined(CONFIG_BT_STACK_PTS)
-    if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
-        conn->role == BT_CONN_ROLE_SLAVE) {
-        slave_update_conn_param(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn->role == BT_CONN_ROLE_SLAVE) {
+    slave_update_conn_param(conn);
+  }
 #endif
 done:
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
 #if defined(CONFIG_BT_DATA_LEN_UPDATE)
-static void le_data_len_change(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_data_len_change *evt = (void *)buf->data;
-    u16_t max_tx_octets = sys_le16_to_cpu(evt->max_tx_octets);
-    u16_t max_rx_octets = sys_le16_to_cpu(evt->max_rx_octets);
-    u16_t max_tx_time = sys_le16_to_cpu(evt->max_tx_time);
-    u16_t max_rx_time = sys_le16_to_cpu(evt->max_rx_time);
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    struct bt_conn *conn;
-
-    UNUSED(max_tx_octets);
-    UNUSED(max_rx_octets);
-    UNUSED(max_tx_time);
-    UNUSED(max_rx_time);
-
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to lookup conn for handle %u", handle);
-        return;
-    }
+static void le_data_len_change(struct net_buf *buf) {
+  struct bt_hci_evt_le_data_len_change *evt           = (void *)buf->data;
+  u16_t                                 max_tx_octets = sys_le16_to_cpu(evt->max_tx_octets);
+  u16_t                                 max_rx_octets = sys_le16_to_cpu(evt->max_rx_octets);
+  u16_t                                 max_tx_time   = sys_le16_to_cpu(evt->max_tx_time);
+  u16_t                                 max_rx_time   = sys_le16_to_cpu(evt->max_rx_time);
+  u16_t                                 handle        = sys_le16_to_cpu(evt->handle);
+  struct bt_conn                       *conn;
+
+  UNUSED(max_tx_octets);
+  UNUSED(max_rx_octets);
+  UNUSED(max_tx_time);
+  UNUSED(max_rx_time);
+
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to lookup conn for handle %u", handle);
+    return;
+  }
 
-    BT_DBG("max. tx: %u (%uus), max. rx: %u (%uus)", max_tx_octets,
-           max_tx_time, max_rx_octets, max_rx_time);
+  BT_DBG("max. tx: %u (%uus), max. rx: %u (%uus)", max_tx_octets, max_tx_time, max_rx_octets, max_rx_time);
 
-    /* TODO use those */
+  /* TODO use those */
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 #endif /* CONFIG_BT_DATA_LEN_UPDATE */
 
 #if defined(CONFIG_BT_PHY_UPDATE)
-static void le_phy_update_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_phy_update_complete *evt = (void *)buf->data;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    struct bt_conn *conn;
-
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to lookup conn for handle %u", handle);
-        return;
-    }
+static void le_phy_update_complete(struct net_buf *buf) {
+  struct bt_hci_evt_le_phy_update_complete *evt    = (void *)buf->data;
+  u16_t                                     handle = sys_le16_to_cpu(evt->handle);
+  struct bt_conn                           *conn;
+
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to lookup conn for handle %u", handle);
+    return;
+  }
 
-    BT_DBG("PHY updated: status: 0x%02x, tx: %u, rx: %u",
-           evt->status, evt->tx_phy, evt->rx_phy);
+  BT_DBG("PHY updated: status: 0x%02x, tx: %u, rx: %u", evt->status, evt->tx_phy, evt->rx_phy);
 
-    if (!IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) ||
-        !atomic_test_and_clear_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE)) {
-        goto done;
-    }
+  if (!IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) || !atomic_test_and_clear_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE)) {
+    goto done;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) &&
-        BT_FEAT_LE_DLE(bt_dev.le.features) &&
-        BT_FEAT_LE_DLE(conn->le.features)) {
-        hci_le_set_data_len(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && BT_FEAT_LE_DLE(bt_dev.le.features) && BT_FEAT_LE_DLE(conn->le.features)) {
+    hci_le_set_data_len(conn);
+  }
 
-    if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
-        conn->role == BT_CONN_ROLE_SLAVE) {
-        slave_update_conn_param(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn->role == BT_CONN_ROLE_SLAVE) {
+    slave_update_conn_param(conn);
+  }
 
 done:
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 #endif /* CONFIG_BT_PHY_UPDATE */
 
-bool bt_le_conn_params_valid(const struct bt_le_conn_param *param)
-{
-    /* All limits according to BT Core spec 5.0 [Vol 2, Part E, 7.8.12] */
+bool bt_le_conn_params_valid(const struct bt_le_conn_param *param) {
+  /* All limits according to BT Core spec 5.0 [Vol 2, Part E, 7.8.12] */
 
-    if (param->interval_min > param->interval_max ||
-        param->interval_min < 6 || param->interval_max > 3200) {
-        return false;
-    }
+  if (param->interval_min > param->interval_max || param->interval_min < 6 || param->interval_max > 3200) {
+    return false;
+  }
 
-    if (param->latency > 499) {
-        return false;
-    }
+  if (param->latency > 499) {
+    return false;
+  }
 
-    if (param->timeout < 10 || param->timeout > 3200 ||
-        ((param->timeout * 4U) <=
-         ((1 + param->latency) * param->interval_max))) {
-        return false;
-    }
+  if (param->timeout < 10 || param->timeout > 3200 || ((param->timeout * 4U) <= ((1 + param->latency) * param->interval_max))) {
+    return false;
+  }
 
-    return true;
+  return true;
 }
 
-static void le_conn_param_neg_reply(u16_t handle, u8_t reason)
-{
-    struct bt_hci_cp_le_conn_param_req_neg_reply *cp;
-    struct net_buf *buf;
+static void le_conn_param_neg_reply(u16_t handle, u8_t reason) {
+  struct bt_hci_cp_le_conn_param_req_neg_reply *cp;
+  struct net_buf                               *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY,
-                            sizeof(*cp));
-    if (!buf) {
-        BT_ERR("Unable to allocate buffer");
-        return;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("Unable to allocate buffer");
+    return;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(handle);
-    cp->reason = sys_cpu_to_le16(reason);
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = sys_cpu_to_le16(handle);
+  cp->reason = sys_cpu_to_le16(reason);
 
-    bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY, buf);
+  bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY, buf);
 }
 
-static int le_conn_param_req_reply(u16_t handle,
-                                   const struct bt_le_conn_param *param)
-{
-    struct bt_hci_cp_le_conn_param_req_reply *cp;
-    struct net_buf *buf;
+static int le_conn_param_req_reply(u16_t handle, const struct bt_le_conn_param *param) {
+  struct bt_hci_cp_le_conn_param_req_reply *cp;
+  struct net_buf                           *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    (void)memset(cp, 0, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
+  (void)memset(cp, 0, sizeof(*cp));
 
-    cp->handle = sys_cpu_to_le16(handle);
-    cp->interval_min = sys_cpu_to_le16(param->interval_min);
-    cp->interval_max = sys_cpu_to_le16(param->interval_max);
-    cp->latency = sys_cpu_to_le16(param->latency);
-    cp->timeout = sys_cpu_to_le16(param->timeout);
+  cp->handle       = sys_cpu_to_le16(handle);
+  cp->interval_min = sys_cpu_to_le16(param->interval_min);
+  cp->interval_max = sys_cpu_to_le16(param->interval_max);
+  cp->latency      = sys_cpu_to_le16(param->latency);
+  cp->timeout      = sys_cpu_to_le16(param->timeout);
 
-    return bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, buf);
+  return bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, buf);
 }
 
-static void le_conn_param_req(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_conn_param_req *evt = (void *)buf->data;
-    struct bt_le_conn_param param;
-    struct bt_conn *conn;
-    u16_t handle;
+static void le_conn_param_req(struct net_buf *buf) {
+  struct bt_hci_evt_le_conn_param_req *evt = (void *)buf->data;
+  struct bt_le_conn_param              param;
+  struct bt_conn                      *conn;
+  u16_t                                handle;
 
-    handle = sys_le16_to_cpu(evt->handle);
-    param.interval_min = sys_le16_to_cpu(evt->interval_min);
-    param.interval_max = sys_le16_to_cpu(evt->interval_max);
-    param.latency = sys_le16_to_cpu(evt->latency);
-    param.timeout = sys_le16_to_cpu(evt->timeout);
+  handle             = sys_le16_to_cpu(evt->handle);
+  param.interval_min = sys_le16_to_cpu(evt->interval_min);
+  param.interval_max = sys_le16_to_cpu(evt->interval_max);
+  param.latency      = sys_le16_to_cpu(evt->latency);
+  param.timeout      = sys_le16_to_cpu(evt->timeout);
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to lookup conn for handle %u", handle);
-        le_conn_param_neg_reply(handle, BT_HCI_ERR_UNKNOWN_CONN_ID);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to lookup conn for handle %u", handle);
+    le_conn_param_neg_reply(handle, BT_HCI_ERR_UNKNOWN_CONN_ID);
+    return;
+  }
 
-    if (!le_param_req(conn, ¶m)) {
-        le_conn_param_neg_reply(handle, BT_HCI_ERR_INVALID_LL_PARAM);
-    } else {
-        le_conn_param_req_reply(handle, ¶m);
-    }
+  if (!le_param_req(conn, ¶m)) {
+    le_conn_param_neg_reply(handle, BT_HCI_ERR_INVALID_LL_PARAM);
+  } else {
+    le_conn_param_req_reply(handle, ¶m);
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
-static void le_conn_update_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_conn_update_complete *evt = (void *)buf->data;
-    struct bt_conn *conn;
-    u16_t handle;
+static void le_conn_update_complete(struct net_buf *buf) {
+  struct bt_hci_evt_le_conn_update_complete *evt = (void *)buf->data;
+  struct bt_conn                            *conn;
+  u16_t                                      handle;
 
-    handle = sys_le16_to_cpu(evt->handle);
+  handle = sys_le16_to_cpu(evt->handle);
 
-    BT_DBG("status 0x%02x, handle %u", evt->status, handle);
+  BT_DBG("status 0x%02x, handle %u", evt->status, handle);
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to lookup conn for handle %u", handle);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to lookup conn for handle %u", handle);
+    return;
+  }
 
-    if (!evt->status) {
-        conn->le.interval = sys_le16_to_cpu(evt->interval);
-        conn->le.latency = sys_le16_to_cpu(evt->latency);
-        conn->le.timeout = sys_le16_to_cpu(evt->supv_timeout);
-        notify_le_param_updated(conn);
-    } else if (evt->status == BT_HCI_ERR_UNSUPP_REMOTE_FEATURE &&
-               conn->role == BT_HCI_ROLE_SLAVE &&
-               !atomic_test_and_set_bit(conn->flags,
-                                        BT_CONN_SLAVE_PARAM_L2CAP)) {
-        /* CPR not supported, let's try L2CAP CPUP instead */
-        struct bt_le_conn_param param;
+  if (!evt->status) {
+    conn->le.interval = sys_le16_to_cpu(evt->interval);
+    conn->le.latency  = sys_le16_to_cpu(evt->latency);
+    conn->le.timeout  = sys_le16_to_cpu(evt->supv_timeout);
+    notify_le_param_updated(conn);
+  } else if (evt->status == BT_HCI_ERR_UNSUPP_REMOTE_FEATURE && conn->role == BT_HCI_ROLE_SLAVE && !atomic_test_and_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_L2CAP)) {
+    /* CPR not supported, let's try L2CAP CPUP instead */
+    struct bt_le_conn_param param;
 
-        param.interval_min = conn->le.interval_min;
-        param.interval_max = conn->le.interval_max;
-        param.latency = conn->le.pending_latency;
-        param.timeout = conn->le.pending_timeout;
+    param.interval_min = conn->le.interval_min;
+    param.interval_max = conn->le.interval_max;
+    param.latency      = conn->le.pending_latency;
+    param.timeout      = conn->le.pending_timeout;
 
-        bt_l2cap_update_conn_param(conn, ¶m);
-    }
+    bt_l2cap_update_conn_param(conn, ¶m);
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
 #if defined(CONFIG_BT_CENTRAL)
-static void check_pending_conn(const bt_addr_le_t *id_addr,
-                               const bt_addr_le_t *addr, u8_t evtype)
-{
-    struct bt_conn *conn;
+static void check_pending_conn(const bt_addr_le_t *id_addr, const bt_addr_le_t *addr, u8_t evtype) {
+  struct bt_conn *conn;
 
-    /* No connections are allowed during explicit scanning */
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
-        return;
-    }
+  /* No connections are allowed during explicit scanning */
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
+    return;
+  }
 
-    /* Return if event is not connectable */
-    if (evtype != BT_LE_ADV_IND && evtype != BT_LE_ADV_DIRECT_IND) {
-        return;
-    }
+  /* Return if event is not connectable */
+  if (evtype != BT_LE_ADV_IND && evtype != BT_LE_ADV_DIRECT_IND) {
+    return;
+  }
 
-    conn = bt_conn_lookup_state_le(id_addr, BT_CONN_CONNECT_SCAN);
-    if (!conn) {
-        return;
-    }
+  conn = bt_conn_lookup_state_le(id_addr, BT_CONN_CONNECT_SCAN);
+  if (!conn) {
+    return;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) &&
-        set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE)) {
-        goto failed;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) && set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE)) {
+    goto failed;
+  }
 
-    bt_addr_le_copy(&conn->le.resp_addr, addr);
-    if (hci_le_create_conn(conn)) {
-        goto failed;
-    }
+  bt_addr_le_copy(&conn->le.resp_addr, addr);
+  if (hci_le_create_conn(conn)) {
+    goto failed;
+  }
 
-    bt_conn_set_state(conn, BT_CONN_CONNECT);
-    bt_conn_unref(conn);
-    return;
+  bt_conn_set_state(conn, BT_CONN_CONNECT);
+  bt_conn_unref(conn);
+  return;
 
 failed:
-    conn->err = BT_HCI_ERR_UNSPECIFIED;
-    bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
-    bt_conn_unref(conn);
-    bt_le_scan_update(false);
+  conn->err = BT_HCI_ERR_UNSPECIFIED;
+  bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
+  bt_conn_unref(conn);
+  bt_le_scan_update(false);
 }
 #endif /* CONFIG_BT_CENTRAL */
 
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-static int set_flow_control(void)
-{
-    struct bt_hci_cp_host_buffer_size *hbs;
-    struct net_buf *buf;
-    int err;
-
-    /* Check if host flow control is actually supported */
-    if (!BT_CMD_TEST(bt_dev.supported_commands, 10, 5)) {
-        BT_WARN("Controller to host flow control not supported");
-        return 0;
-    }
+static int set_flow_control(void) {
+  struct bt_hci_cp_host_buffer_size *hbs;
+  struct net_buf                    *buf;
+  int                                err;
+
+  /* Check if host flow control is actually supported */
+  if (!BT_CMD_TEST(bt_dev.supported_commands, 10, 5)) {
+    BT_WARN("Controller to host flow control not supported");
+    return 0;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_HOST_BUFFER_SIZE,
-                            sizeof(*hbs));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_HOST_BUFFER_SIZE, sizeof(*hbs));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    hbs = net_buf_add(buf, sizeof(*hbs));
-    (void)memset(hbs, 0, sizeof(*hbs));
-    hbs->acl_mtu = sys_cpu_to_le16(CONFIG_BT_L2CAP_RX_MTU +
-                                   sizeof(struct bt_l2cap_hdr));
-    hbs->acl_pkts = sys_cpu_to_le16(CONFIG_BT_ACL_RX_COUNT);
+  hbs = net_buf_add(buf, sizeof(*hbs));
+  (void)memset(hbs, 0, sizeof(*hbs));
+  hbs->acl_mtu  = sys_cpu_to_le16(CONFIG_BT_L2CAP_RX_MTU + sizeof(struct bt_l2cap_hdr));
+  hbs->acl_pkts = sys_cpu_to_le16(CONFIG_BT_ACL_RX_COUNT);
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_HOST_BUFFER_SIZE, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_HOST_BUFFER_SIZE, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, 1);
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, 1);
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    net_buf_add_u8(buf, BT_HCI_CTL_TO_HOST_FLOW_ENABLE);
-    return bt_hci_cmd_send_sync(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, buf, NULL);
+  net_buf_add_u8(buf, BT_HCI_CTL_TO_HOST_FLOW_ENABLE);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, buf, NULL);
 }
 #endif /* CONFIG_BT_HCI_ACL_FLOW_CONTROL */
 
-static int bt_clear_all_pairings(u8_t id)
-{
-    bt_conn_disconnect_all(id);
+static int bt_clear_all_pairings(u8_t id) {
+  bt_conn_disconnect_all(id);
 
-    if (IS_ENABLED(CONFIG_BT_SMP)) {
-        bt_keys_clear_all(id);
-    }
+  if (IS_ENABLED(CONFIG_BT_SMP)) {
+    bt_keys_clear_all(id);
+  }
 
-    if (IS_ENABLED(CONFIG_BT_BREDR)) {
-        bt_keys_link_key_clear_addr(NULL);
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR)) {
+    bt_keys_link_key_clear_addr(NULL);
+  }
 
-    return 0;
+  return 0;
 }
 
-int bt_unpair(u8_t id, const bt_addr_le_t *addr)
-{
-    struct bt_keys *keys = NULL;
-    struct bt_conn *conn;
+int bt_unpair(u8_t id, const bt_addr_le_t *addr) {
+  struct bt_keys *keys = NULL;
+  struct bt_conn *conn;
 
-    if (id >= CONFIG_BT_ID_MAX) {
-        return -EINVAL;
-    }
+  if (id >= CONFIG_BT_ID_MAX) {
+    return -EINVAL;
+  }
+
+  if (!addr || !bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
+    return bt_clear_all_pairings(id);
+  }
 
-    if (!addr || !bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
-        return bt_clear_all_pairings(id);
+  conn = bt_conn_lookup_addr_le(id, addr);
+  if (conn) {
+    /* Clear the conn->le.keys pointer since we'll invalidate it,
+     * and don't want any subsequent code (like disconnected
+     * callbacks) accessing it.
+     */
+    if (conn->type == BT_CONN_TYPE_LE) {
+      keys          = conn->le.keys;
+      conn->le.keys = NULL;
     }
 
-    conn = bt_conn_lookup_addr_le(id, addr);
-    if (conn) {
-        /* Clear the conn->le.keys pointer since we'll invalidate it,
-		 * and don't want any subsequent code (like disconnected
-		 * callbacks) accessing it.
-		 */
-        if (conn->type == BT_CONN_TYPE_LE) {
-            keys = conn->le.keys;
-            conn->le.keys = NULL;
-        }
+    bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
+    bt_conn_unref(conn);
+  }
 
-        bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
-        bt_conn_unref(conn);
+  if (IS_ENABLED(CONFIG_BT_BREDR)) {
+    /* LE Public may indicate BR/EDR as well */
+    if (addr->type == BT_ADDR_LE_PUBLIC) {
+      bt_keys_link_key_clear_addr(&addr->a);
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_BREDR)) {
-        /* LE Public may indicate BR/EDR as well */
-        if (addr->type == BT_ADDR_LE_PUBLIC) {
-            bt_keys_link_key_clear_addr(&addr->a);
-        }
+  if (IS_ENABLED(CONFIG_BT_SMP)) {
+    if (!keys) {
+      keys = bt_keys_find_addr(id, addr);
     }
 
-    if (IS_ENABLED(CONFIG_BT_SMP)) {
-        if (!keys) {
-            keys = bt_keys_find_addr(id, addr);
-        }
-
-        if (keys) {
-            bt_keys_clear(keys);
-        }
+    if (keys) {
+      bt_keys_clear(keys);
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        bt_gatt_clear(id, addr);
-    }
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    bt_gatt_clear(id, addr);
+  }
 
-    return 0;
+  return 0;
 }
 
 #endif /* CONFIG_BT_CONN */
 
 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
-static enum bt_security_err security_err_get(u8_t hci_err)
-{
-    switch (hci_err) {
-        case BT_HCI_ERR_SUCCESS:
-            return BT_SECURITY_ERR_SUCCESS;
-        case BT_HCI_ERR_AUTH_FAIL:
-            return BT_SECURITY_ERR_AUTH_FAIL;
-        case BT_HCI_ERR_PIN_OR_KEY_MISSING:
-            return BT_SECURITY_ERR_PIN_OR_KEY_MISSING;
-        case BT_HCI_ERR_PAIRING_NOT_SUPPORTED:
-            return BT_SECURITY_ERR_PAIR_NOT_SUPPORTED;
-        case BT_HCI_ERR_PAIRING_NOT_ALLOWED:
-            return BT_SECURITY_ERR_PAIR_NOT_ALLOWED;
-        case BT_HCI_ERR_INVALID_PARAM:
-            return BT_SECURITY_ERR_INVALID_PARAM;
-        default:
-            return BT_SECURITY_ERR_UNSPECIFIED;
-    }
-}
-
-static void reset_pairing(struct bt_conn *conn)
-{
+static enum bt_security_err security_err_get(u8_t hci_err) {
+  switch (hci_err) {
+  case BT_HCI_ERR_SUCCESS:
+    return BT_SECURITY_ERR_SUCCESS;
+  case BT_HCI_ERR_AUTH_FAIL:
+    return BT_SECURITY_ERR_AUTH_FAIL;
+  case BT_HCI_ERR_PIN_OR_KEY_MISSING:
+    return BT_SECURITY_ERR_PIN_OR_KEY_MISSING;
+  case BT_HCI_ERR_PAIRING_NOT_SUPPORTED:
+    return BT_SECURITY_ERR_PAIR_NOT_SUPPORTED;
+  case BT_HCI_ERR_PAIRING_NOT_ALLOWED:
+    return BT_SECURITY_ERR_PAIR_NOT_ALLOWED;
+  case BT_HCI_ERR_INVALID_PARAM:
+    return BT_SECURITY_ERR_INVALID_PARAM;
+  default:
+    return BT_SECURITY_ERR_UNSPECIFIED;
+  }
+}
+
+static void reset_pairing(struct bt_conn *conn) {
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING);
-        atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR);
-        atomic_clear_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE);
-    }
+  if (conn->type == BT_CONN_TYPE_BR) {
+    atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING);
+    atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR);
+    atomic_clear_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE);
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    /* Reset required security level to current operational */
-    conn->required_sec_level = conn->sec_level;
+  /* Reset required security level to current operational */
+  conn->required_sec_level = conn->sec_level;
 }
 #endif /* defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) */
 
 #if defined(CONFIG_BT_BREDR)
-static int reject_conn(const bt_addr_t *bdaddr, u8_t reason)
-{
-    struct bt_hci_cp_reject_conn_req *cp;
-    struct net_buf *buf;
-    int err;
-
-    buf = bt_hci_cmd_create(BT_HCI_OP_REJECT_CONN_REQ, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
-
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, bdaddr);
-    cp->reason = reason;
-
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_REJECT_CONN_REQ, buf, NULL);
-    if (err) {
-        return err;
-    }
-
-    return 0;
-}
-
-static int accept_sco_conn(const bt_addr_t *bdaddr, struct bt_conn *sco_conn)
-{
-    struct bt_hci_cp_accept_sync_conn_req *cp;
-    struct net_buf *buf;
-    int err;
-
-    buf = bt_hci_cmd_create(BT_HCI_OP_ACCEPT_SYNC_CONN_REQ, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
-
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, bdaddr);
-    cp->pkt_type = sco_conn->sco.pkt_type;
-
-    cp->tx_bandwidth = 0x00001f40;
-    cp->rx_bandwidth = 0x00001f40;
-    if (!hfp_codec_msbc) {
-        cp->max_latency = 0x0007;
-        cp->retrans_effort = 0x01;
-        cp->content_format = BT_VOICE_CVSD_16BIT;
-        BT_DBG("eSCO air coding CVSD!");
-    } else {
-        cp->max_latency = 0x000d;
-        cp->retrans_effort = 0x02;
-        cp->content_format = BT_VOICE_MSBC_16BIT;
-        BT_DBG("eSCO air coding mSBC!");
-    }
-
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_ACCEPT_SYNC_CONN_REQ, buf, NULL);
-    if (err) {
-        return err;
-    }
+static int reject_conn(const bt_addr_t *bdaddr, u8_t reason) {
+  struct bt_hci_cp_reject_conn_req *cp;
+  struct net_buf                   *buf;
+  int                               err;
+
+  buf = bt_hci_cmd_create(BT_HCI_OP_REJECT_CONN_REQ, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
+
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, bdaddr);
+  cp->reason = reason;
+
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_REJECT_CONN_REQ, buf, NULL);
+  if (err) {
+    return err;
+  }
+
+  return 0;
+}
+
+static int accept_sco_conn(const bt_addr_t *bdaddr, struct bt_conn *sco_conn) {
+  struct bt_hci_cp_accept_sync_conn_req *cp;
+  struct net_buf                        *buf;
+  int                                    err;
+
+  buf = bt_hci_cmd_create(BT_HCI_OP_ACCEPT_SYNC_CONN_REQ, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
+
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, bdaddr);
+  cp->pkt_type = sco_conn->sco.pkt_type;
+
+  cp->tx_bandwidth = 0x00001f40;
+  cp->rx_bandwidth = 0x00001f40;
+  if (!hfp_codec_msbc) {
+    cp->max_latency    = 0x0007;
+    cp->retrans_effort = 0x01;
+    cp->content_format = BT_VOICE_CVSD_16BIT;
+    BT_DBG("eSCO air coding CVSD!");
+  } else {
+    cp->max_latency    = 0x000d;
+    cp->retrans_effort = 0x02;
+    cp->content_format = BT_VOICE_MSBC_16BIT;
+    BT_DBG("eSCO air coding mSBC!");
+  }
+
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_ACCEPT_SYNC_CONN_REQ, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-static int accept_conn(const bt_addr_t *bdaddr)
-{
-    struct bt_hci_cp_accept_conn_req *cp;
-    struct net_buf *buf;
-    int err;
+static int accept_conn(const bt_addr_t *bdaddr) {
+  struct bt_hci_cp_accept_conn_req *cp;
+  struct net_buf                   *buf;
+  int                               err;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_ACCEPT_CONN_REQ, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_ACCEPT_CONN_REQ, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, bdaddr);
-    cp->role = BT_HCI_ROLE_SLAVE;
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, bdaddr);
+  cp->role = BT_HCI_ROLE_SLAVE;
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_ACCEPT_CONN_REQ, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_ACCEPT_CONN_REQ, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-static void bt_esco_conn_req(struct bt_hci_evt_conn_request *evt)
-{
-    struct bt_conn *sco_conn;
+static void bt_esco_conn_req(struct bt_hci_evt_conn_request *evt) {
+  struct bt_conn *sco_conn;
 
-    sco_conn = bt_conn_add_sco(&evt->bdaddr, evt->link_type);
-    if (!sco_conn) {
-        reject_conn(&evt->bdaddr, BT_HCI_ERR_INSUFFICIENT_RESOURCES);
-        return;
-    }
+  sco_conn = bt_conn_add_sco(&evt->bdaddr, evt->link_type);
+  if (!sco_conn) {
+    reject_conn(&evt->bdaddr, BT_HCI_ERR_INSUFFICIENT_RESOURCES);
+    return;
+  }
 
-    if (accept_sco_conn(&evt->bdaddr, sco_conn)) {
-        BT_ERR("Error accepting connection from %s",
-               bt_addr_str(&evt->bdaddr));
-        reject_conn(&evt->bdaddr, BT_HCI_ERR_UNSPECIFIED);
-        bt_sco_cleanup(sco_conn);
-        return;
-    }
+  if (accept_sco_conn(&evt->bdaddr, sco_conn)) {
+    BT_ERR("Error accepting connection from %s", bt_addr_str(&evt->bdaddr));
+    reject_conn(&evt->bdaddr, BT_HCI_ERR_UNSPECIFIED);
+    bt_sco_cleanup(sco_conn);
+    return;
+  }
 
-    sco_conn->role = BT_HCI_ROLE_SLAVE;
-    bt_conn_set_state(sco_conn, BT_CONN_CONNECT);
-    bt_conn_unref(sco_conn);
+  sco_conn->role = BT_HCI_ROLE_SLAVE;
+  bt_conn_set_state(sco_conn, BT_CONN_CONNECT);
+  bt_conn_unref(sco_conn);
 }
 
-static void conn_req(struct net_buf *buf)
-{
-    struct bt_hci_evt_conn_request *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void conn_req(struct net_buf *buf) {
+  struct bt_hci_evt_conn_request *evt = (void *)buf->data;
+  struct bt_conn                 *conn;
 
-    BT_DBG("conn req from %s, type 0x%02x", bt_addr_str(&evt->bdaddr),
-           evt->link_type);
+  BT_DBG("conn req from %s, type 0x%02x", bt_addr_str(&evt->bdaddr), evt->link_type);
 
-    if (evt->link_type != BT_HCI_ACL) {
-        bt_esco_conn_req(evt);
-        return;
-    }
+  if (evt->link_type != BT_HCI_ACL) {
+    bt_esco_conn_req(evt);
+    return;
+  }
 
-    conn = bt_conn_add_br(&evt->bdaddr);
-    if (!conn) {
-        reject_conn(&evt->bdaddr, BT_HCI_ERR_INSUFFICIENT_RESOURCES);
-        return;
-    }
+  conn = bt_conn_add_br(&evt->bdaddr);
+  if (!conn) {
+    reject_conn(&evt->bdaddr, BT_HCI_ERR_INSUFFICIENT_RESOURCES);
+    return;
+  }
 
-    accept_conn(&evt->bdaddr);
-    conn->role = BT_HCI_ROLE_SLAVE;
-    bt_conn_set_state(conn, BT_CONN_CONNECT);
-    bt_conn_unref(conn);
+  accept_conn(&evt->bdaddr);
+  conn->role = BT_HCI_ROLE_SLAVE;
+  bt_conn_set_state(conn, BT_CONN_CONNECT);
+  bt_conn_unref(conn);
 }
 
-static bool br_sufficient_key_size(struct bt_conn *conn)
-{
-    struct bt_hci_cp_read_encryption_key_size *cp;
-    struct bt_hci_rp_read_encryption_key_size *rp;
-    struct net_buf *buf, *rsp;
-    u8_t key_size;
-    int err;
-
-    buf = bt_hci_cmd_create(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE,
-                            sizeof(*cp));
-    if (!buf) {
-        BT_ERR("Failed to allocate command buffer");
-        return false;
-    }
+static bool br_sufficient_key_size(struct bt_conn *conn) {
+  struct bt_hci_cp_read_encryption_key_size *cp;
+  struct bt_hci_rp_read_encryption_key_size *rp;
+  struct net_buf                            *buf, *rsp;
+  u8_t                                       key_size;
+  int                                        err;
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(conn->handle);
+  buf = bt_hci_cmd_create(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("Failed to allocate command buffer");
+    return false;
+  }
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE,
-                               buf, &rsp);
-    if (err) {
-        BT_ERR("Failed to read encryption key size (err %d)", err);
-        return false;
-    }
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = sys_cpu_to_le16(conn->handle);
 
-    if (rsp->len < sizeof(*rp)) {
-        BT_ERR("Too small command complete for encryption key size");
-        net_buf_unref(rsp);
-        return false;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, buf, &rsp);
+  if (err) {
+    BT_ERR("Failed to read encryption key size (err %d)", err);
+    return false;
+  }
 
-    rp = (void *)rsp->data;
-    key_size = rp->key_size;
+  if (rsp->len < sizeof(*rp)) {
+    BT_ERR("Too small command complete for encryption key size");
     net_buf_unref(rsp);
+    return false;
+  }
 
-    BT_DBG("Encryption key size is %u", key_size);
+  rp       = (void *)rsp->data;
+  key_size = rp->key_size;
+  net_buf_unref(rsp);
 
-    if (conn->sec_level == BT_SECURITY_L4) {
-        return key_size == BT_HCI_ENCRYPTION_KEY_SIZE_MAX;
-    }
+  BT_DBG("Encryption key size is %u", key_size);
 
-    return key_size >= BT_HCI_ENCRYPTION_KEY_SIZE_MIN;
-}
+  if (conn->sec_level == BT_SECURITY_L4) {
+    return key_size == BT_HCI_ENCRYPTION_KEY_SIZE_MAX;
+  }
 
-static bool update_sec_level_br(struct bt_conn *conn)
-{
-    if (!conn->encrypt) {
-        conn->sec_level = BT_SECURITY_L1;
-        return true;
-    }
+  return key_size >= BT_HCI_ENCRYPTION_KEY_SIZE_MIN;
+}
 
-    if (conn->br.link_key) {
-        if (conn->br.link_key->flags & BT_LINK_KEY_AUTHENTICATED) {
-            if (conn->encrypt == 0x02) {
-                conn->sec_level = BT_SECURITY_L4;
-            } else {
-                conn->sec_level = BT_SECURITY_L3;
-            }
-        } else {
-            conn->sec_level = BT_SECURITY_L2;
-        }
+static bool update_sec_level_br(struct bt_conn *conn) {
+  if (!conn->encrypt) {
+    conn->sec_level = BT_SECURITY_L1;
+    return true;
+  }
+
+  if (conn->br.link_key) {
+    if (conn->br.link_key->flags & BT_LINK_KEY_AUTHENTICATED) {
+      if (conn->encrypt == 0x02) {
+        conn->sec_level = BT_SECURITY_L4;
+      } else {
+        conn->sec_level = BT_SECURITY_L3;
+      }
     } else {
-        BT_WARN("No BR/EDR link key found");
-        conn->sec_level = BT_SECURITY_L2;
+      conn->sec_level = BT_SECURITY_L2;
     }
+  } else {
+    BT_WARN("No BR/EDR link key found");
+    conn->sec_level = BT_SECURITY_L2;
+  }
 
-    if (!br_sufficient_key_size(conn)) {
-        BT_ERR("Encryption key size is not sufficient");
-        bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
-        return false;
-    }
+  if (!br_sufficient_key_size(conn)) {
+    BT_ERR("Encryption key size is not sufficient");
+    bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
+    return false;
+  }
 
-    if (conn->required_sec_level > conn->sec_level) {
-        BT_ERR("Failed to set required security level");
-        bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
-        return false;
-    }
+  if (conn->required_sec_level > conn->sec_level) {
+    BT_ERR("Failed to set required security level");
+    bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
+    return false;
+  }
 
-    return true;
+  return true;
 }
 
-static void synchronous_conn_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_sync_conn_complete *evt = (void *)buf->data;
-    struct bt_conn *sco_conn;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-
-    BT_DBG("status 0x%02x, handle %u, type 0x%02x", evt->status, handle,
-           evt->link_type);
+static void synchronous_conn_complete(struct net_buf *buf) {
+  struct bt_hci_evt_sync_conn_complete *evt = (void *)buf->data;
+  struct bt_conn                       *sco_conn;
+  u16_t                                 handle = sys_le16_to_cpu(evt->handle);
 
-    sco_conn = bt_conn_lookup_addr_sco(&evt->bdaddr);
-    if (!sco_conn) {
-        BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  BT_DBG("status 0x%02x, handle %u, type 0x%02x", evt->status, handle, evt->link_type);
 
-    if (evt->status) {
-        sco_conn->err = evt->status;
-        bt_conn_set_state(sco_conn, BT_CONN_DISCONNECTED);
-        bt_conn_unref(sco_conn);
-        return;
-    }
+  sco_conn = bt_conn_lookup_addr_sco(&evt->bdaddr);
+  if (!sco_conn) {
+    BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    sco_conn->handle = handle;
-    bt_conn_set_state(sco_conn, BT_CONN_CONNECTED);
+  if (evt->status) {
+    sco_conn->err = evt->status;
+    bt_conn_set_state(sco_conn, BT_CONN_DISCONNECTED);
     bt_conn_unref(sco_conn);
-}
+    return;
+  }
 
-static void conn_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_conn_complete *evt = (void *)buf->data;
-    struct bt_conn *conn;
-    struct bt_hci_cp_read_remote_features *cp;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
+  sco_conn->handle = handle;
+  bt_conn_set_state(sco_conn, BT_CONN_CONNECTED);
+  bt_conn_unref(sco_conn);
+}
 
-    BT_DBG("status 0x%02x, handle %u, type 0x%02x", evt->status, handle,
-           evt->link_type);
+static void conn_complete(struct net_buf *buf) {
+  struct bt_hci_evt_conn_complete       *evt = (void *)buf->data;
+  struct bt_conn                        *conn;
+  struct bt_hci_cp_read_remote_features *cp;
+  u16_t                                  handle = sys_le16_to_cpu(evt->handle);
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  BT_DBG("status 0x%02x, handle %u, type 0x%02x", evt->status, handle, evt->link_type);
 
-    if (evt->status) {
-        conn->err = evt->status;
-        bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
-        bt_conn_unref(conn);
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    conn->handle = handle;
-    conn->err = 0U;
-    conn->encrypt = evt->encr_enabled;
+  if (evt->status) {
+    conn->err = evt->status;
+    bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
+    bt_conn_unref(conn);
+    return;
+  }
 
-    if (!update_sec_level_br(conn)) {
-        bt_conn_unref(conn);
-        return;
-    }
+  conn->handle  = handle;
+  conn->err     = 0U;
+  conn->encrypt = evt->encr_enabled;
 
-    bt_conn_set_state(conn, BT_CONN_CONNECTED);
+  if (!update_sec_level_br(conn)) {
     bt_conn_unref(conn);
+    return;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_FEATURES, sizeof(*cp));
-    if (!buf) {
-        return;
-    }
+  bt_conn_set_state(conn, BT_CONN_CONNECTED);
+  bt_conn_unref(conn);
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = evt->handle;
+  buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_FEATURES, sizeof(*cp));
+  if (!buf) {
+    return;
+  }
+
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = evt->handle;
 
-    bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_FEATURES, buf, NULL);
+  bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_FEATURES, buf, NULL);
 }
 
-static void pin_code_req(struct net_buf *buf)
-{
-    struct bt_hci_evt_pin_code_req *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void pin_code_req(struct net_buf *buf) {
+  struct bt_hci_evt_pin_code_req *evt = (void *)buf->data;
+  struct bt_conn                 *conn;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    bt_conn_pin_code_req(conn);
-    bt_conn_unref(conn);
+  bt_conn_pin_code_req(conn);
+  bt_conn_unref(conn);
 }
 
-static void link_key_notify(struct net_buf *buf)
-{
-    struct bt_hci_evt_link_key_notify *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void link_key_notify(struct net_buf *buf) {
+  struct bt_hci_evt_link_key_notify *evt = (void *)buf->data;
+  struct bt_conn                    *conn;
 
-    printf("bredr link key: ");
-    for (int i = 0; i < 16; i++) {
-        printf("0x%02x ", evt->link_key[i]);
-    }
-    printf("\n");
+  printf("bredr link key: ");
+  for (int i = 0; i < 16; i++) {
+    printf("0x%02x ", evt->link_key[i]);
+  }
+  printf("\n");
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
-
-    BT_DBG("%s, link type 0x%02x", bt_addr_str(&evt->bdaddr), evt->key_type);
-
-    if (!conn->br.link_key) {
-        conn->br.link_key = bt_keys_get_link_key(&evt->bdaddr);
-    }
-    if (!conn->br.link_key) {
-        BT_ERR("Can't update keys for %s", bt_addr_str(&evt->bdaddr));
-        bt_conn_unref(conn);
-        return;
-    }
-
-    /* clear any old Link Key flags */
-    conn->br.link_key->flags = 0U;
-
-    switch (evt->key_type) {
-        case BT_LK_COMBINATION:
-            /*
-		 * Setting Combination Link Key as AUTHENTICATED means it was
-		 * successfully generated by 16 digits wide PIN code.
-		 */
-            if (atomic_test_and_clear_bit(conn->flags,
-                                          BT_CONN_BR_LEGACY_SECURE)) {
-                conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED;
-            }
-            memcpy(conn->br.link_key->val, evt->link_key, 16);
-            break;
-        case BT_LK_AUTH_COMBINATION_P192:
-            conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED;
-            /* fall through */
-            __attribute__((fallthrough));
-        case BT_LK_UNAUTH_COMBINATION_P192:
-            /* Mark no-bond so that link-key is removed on disconnection */
-            if (bt_conn_ssp_get_auth(conn) < BT_HCI_DEDICATED_BONDING) {
-                atomic_set_bit(conn->flags, BT_CONN_BR_NOBOND);
-            }
-
-            memcpy(conn->br.link_key->val, evt->link_key, 16);
-            break;
-        case BT_LK_AUTH_COMBINATION_P256:
-            conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED;
-            /* fall through */
-            __attribute__((fallthrough));
-        case BT_LK_UNAUTH_COMBINATION_P256:
-            conn->br.link_key->flags |= BT_LINK_KEY_SC;
-
-            /* Mark no-bond so that link-key is removed on disconnection */
-            if (bt_conn_ssp_get_auth(conn) < BT_HCI_DEDICATED_BONDING) {
-                atomic_set_bit(conn->flags, BT_CONN_BR_NOBOND);
-            }
-
-            memcpy(conn->br.link_key->val, evt->link_key, 16);
-            break;
-        default:
-            BT_WARN("Unsupported Link Key type %u", evt->key_type);
-            (void)memset(conn->br.link_key->val, 0,
-                         sizeof(conn->br.link_key->val));
-            break;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    bt_conn_unref(conn);
-}
+  BT_DBG("%s, link type 0x%02x", bt_addr_str(&evt->bdaddr), evt->key_type);
 
-static void link_key_neg_reply(const bt_addr_t *bdaddr)
-{
-    struct bt_hci_cp_link_key_neg_reply *cp;
-    struct net_buf *buf;
+  if (!conn->br.link_key) {
+    conn->br.link_key = bt_keys_get_link_key(&evt->bdaddr);
+  }
+  if (!conn->br.link_key) {
+    BT_ERR("Can't update keys for %s", bt_addr_str(&evt->bdaddr));
+    bt_conn_unref(conn);
+    return;
+  }
 
-    BT_DBG("");
+  /* clear any old Link Key flags */
+  conn->br.link_key->flags = 0U;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LINK_KEY_NEG_REPLY, sizeof(*cp));
-    if (!buf) {
-        BT_ERR("Out of command buffers");
-        return;
-    }
+  switch (evt->key_type) {
+  case BT_LK_COMBINATION:
+    /*
+     * Setting Combination Link Key as AUTHENTICATED means it was
+     * successfully generated by 16 digits wide PIN code.
+     */
+    if (atomic_test_and_clear_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE)) {
+      conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED;
+    }
+    memcpy(conn->br.link_key->val, evt->link_key, 16);
+    break;
+  case BT_LK_AUTH_COMBINATION_P192:
+    conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED;
+    /* fall through */
+    __attribute__((fallthrough));
+  case BT_LK_UNAUTH_COMBINATION_P192:
+    /* Mark no-bond so that link-key is removed on disconnection */
+    if (bt_conn_ssp_get_auth(conn) < BT_HCI_DEDICATED_BONDING) {
+      atomic_set_bit(conn->flags, BT_CONN_BR_NOBOND);
+    }
+
+    memcpy(conn->br.link_key->val, evt->link_key, 16);
+    break;
+  case BT_LK_AUTH_COMBINATION_P256:
+    conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED;
+    /* fall through */
+    __attribute__((fallthrough));
+  case BT_LK_UNAUTH_COMBINATION_P256:
+    conn->br.link_key->flags |= BT_LINK_KEY_SC;
+
+    /* Mark no-bond so that link-key is removed on disconnection */
+    if (bt_conn_ssp_get_auth(conn) < BT_HCI_DEDICATED_BONDING) {
+      atomic_set_bit(conn->flags, BT_CONN_BR_NOBOND);
+    }
+
+    memcpy(conn->br.link_key->val, evt->link_key, 16);
+    break;
+  default:
+    BT_WARN("Unsupported Link Key type %u", evt->key_type);
+    (void)memset(conn->br.link_key->val, 0, sizeof(conn->br.link_key->val));
+    break;
+  }
+
+  bt_conn_unref(conn);
+}
+
+static void link_key_neg_reply(const bt_addr_t *bdaddr) {
+  struct bt_hci_cp_link_key_neg_reply *cp;
+  struct net_buf                      *buf;
+
+  BT_DBG("");
+
+  buf = bt_hci_cmd_create(BT_HCI_OP_LINK_KEY_NEG_REPLY, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("Out of command buffers");
+    return;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, bdaddr);
-    bt_hci_cmd_send_sync(BT_HCI_OP_LINK_KEY_NEG_REPLY, buf, NULL);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, bdaddr);
+  bt_hci_cmd_send_sync(BT_HCI_OP_LINK_KEY_NEG_REPLY, buf, NULL);
 }
 
-static void link_key_reply(const bt_addr_t *bdaddr, const u8_t *lk)
-{
-    struct bt_hci_cp_link_key_reply *cp;
-    struct net_buf *buf;
+static void link_key_reply(const bt_addr_t *bdaddr, const u8_t *lk) {
+  struct bt_hci_cp_link_key_reply *cp;
+  struct net_buf                  *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LINK_KEY_REPLY, sizeof(*cp));
-    if (!buf) {
-        BT_ERR("Out of command buffers");
-        return;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LINK_KEY_REPLY, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("Out of command buffers");
+    return;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, bdaddr);
-    memcpy(cp->link_key, lk, 16);
-    bt_hci_cmd_send_sync(BT_HCI_OP_LINK_KEY_REPLY, buf, NULL);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, bdaddr);
+  memcpy(cp->link_key, lk, 16);
+  bt_hci_cmd_send_sync(BT_HCI_OP_LINK_KEY_REPLY, buf, NULL);
 }
 
-static void link_key_req(struct net_buf *buf)
-{
-    struct bt_hci_evt_link_key_req *evt = (void *)buf->data;
-    struct bt_conn *conn;
-
-    BT_DBG("%s", bt_addr_str(&evt->bdaddr));
-
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        link_key_neg_reply(&evt->bdaddr);
-        return;
-    }
+static void link_key_req(struct net_buf *buf) {
+  struct bt_hci_evt_link_key_req *evt = (void *)buf->data;
+  struct bt_conn                 *conn;
 
-    if (!conn->br.link_key) {
-        conn->br.link_key = bt_keys_find_link_key(&evt->bdaddr);
-    }
+  BT_DBG("%s", bt_addr_str(&evt->bdaddr));
 
-    if (!conn->br.link_key) {
-        link_key_neg_reply(&evt->bdaddr);
-        bt_conn_unref(conn);
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    link_key_neg_reply(&evt->bdaddr);
+    return;
+  }
 
-    /*
-	 * Enforce regenerate by controller stronger link key since found one
-	 * in database not covers requested security level.
-	 */
-    if (!(conn->br.link_key->flags & BT_LINK_KEY_AUTHENTICATED) &&
-        conn->required_sec_level > BT_SECURITY_L2) {
-        link_key_neg_reply(&evt->bdaddr);
-        bt_conn_unref(conn);
-        return;
-    }
+  if (!conn->br.link_key) {
+    conn->br.link_key = bt_keys_find_link_key(&evt->bdaddr);
+  }
 
-    link_key_reply(&evt->bdaddr, conn->br.link_key->val);
+  if (!conn->br.link_key) {
+    link_key_neg_reply(&evt->bdaddr);
+    bt_conn_unref(conn);
+    return;
+  }
+
+  /*
+   * Enforce regenerate by controller stronger link key since found one
+   * in database not covers requested security level.
+   */
+  if (!(conn->br.link_key->flags & BT_LINK_KEY_AUTHENTICATED) && conn->required_sec_level > BT_SECURITY_L2) {
+    link_key_neg_reply(&evt->bdaddr);
     bt_conn_unref(conn);
+    return;
+  }
+
+  link_key_reply(&evt->bdaddr, conn->br.link_key->val);
+  bt_conn_unref(conn);
 }
 
-static void io_capa_neg_reply(const bt_addr_t *bdaddr, const u8_t reason)
-{
-    struct bt_hci_cp_io_capability_neg_reply *cp;
-    struct net_buf *resp_buf;
+static void io_capa_neg_reply(const bt_addr_t *bdaddr, const u8_t reason) {
+  struct bt_hci_cp_io_capability_neg_reply *cp;
+  struct net_buf                           *resp_buf;
 
-    resp_buf = bt_hci_cmd_create(BT_HCI_OP_IO_CAPABILITY_NEG_REPLY,
-                                 sizeof(*cp));
-    if (!resp_buf) {
-        BT_ERR("Out of command buffers");
-        return;
-    }
+  resp_buf = bt_hci_cmd_create(BT_HCI_OP_IO_CAPABILITY_NEG_REPLY, sizeof(*cp));
+  if (!resp_buf) {
+    BT_ERR("Out of command buffers");
+    return;
+  }
 
-    cp = net_buf_add(resp_buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, bdaddr);
-    cp->reason = reason;
-    bt_hci_cmd_send_sync(BT_HCI_OP_IO_CAPABILITY_NEG_REPLY, resp_buf, NULL);
+  cp = net_buf_add(resp_buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, bdaddr);
+  cp->reason = reason;
+  bt_hci_cmd_send_sync(BT_HCI_OP_IO_CAPABILITY_NEG_REPLY, resp_buf, NULL);
 }
 
-static void io_capa_resp(struct net_buf *buf)
-{
-    struct bt_hci_evt_io_capa_resp *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void io_capa_resp(struct net_buf *buf) {
+  struct bt_hci_evt_io_capa_resp *evt = (void *)buf->data;
+  struct bt_conn                 *conn;
 
-    BT_DBG("remote %s, IOcapa 0x%02x, auth 0x%02x",
-           bt_addr_str(&evt->bdaddr), evt->capability, evt->authentication);
+  BT_DBG("remote %s, IOcapa 0x%02x, auth 0x%02x", bt_addr_str(&evt->bdaddr), evt->capability, evt->authentication);
 
-    if (evt->authentication > BT_HCI_GENERAL_BONDING_MITM) {
-        BT_ERR("Invalid remote authentication requirements");
-        io_capa_neg_reply(&evt->bdaddr,
-                          BT_HCI_ERR_UNSUPP_FEATURE_PARAM_VAL);
-        return;
-    }
+  if (evt->authentication > BT_HCI_GENERAL_BONDING_MITM) {
+    BT_ERR("Invalid remote authentication requirements");
+    io_capa_neg_reply(&evt->bdaddr, BT_HCI_ERR_UNSUPP_FEATURE_PARAM_VAL);
+    return;
+  }
 
-    if (evt->capability > BT_IO_NO_INPUT_OUTPUT) {
-        BT_ERR("Invalid remote io capability requirements");
-        io_capa_neg_reply(&evt->bdaddr,
-                          BT_HCI_ERR_UNSUPP_FEATURE_PARAM_VAL);
-        return;
-    }
+  if (evt->capability > BT_IO_NO_INPUT_OUTPUT) {
+    BT_ERR("Invalid remote io capability requirements");
+    io_capa_neg_reply(&evt->bdaddr, BT_HCI_ERR_UNSUPP_FEATURE_PARAM_VAL);
+    return;
+  }
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    conn->br.remote_io_capa = evt->capability;
-    conn->br.remote_auth = evt->authentication;
-    atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING);
-    bt_conn_unref(conn);
+  conn->br.remote_io_capa = evt->capability;
+  conn->br.remote_auth    = evt->authentication;
+  atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING);
+  bt_conn_unref(conn);
 }
 
-static void io_capa_req(struct net_buf *buf)
-{
-    struct bt_hci_evt_io_capa_req *evt = (void *)buf->data;
-    struct net_buf *resp_buf;
-    struct bt_conn *conn;
-    struct bt_hci_cp_io_capability_reply *cp;
-    u8_t auth;
-
-    BT_DBG("");
+static void io_capa_req(struct net_buf *buf) {
+  struct bt_hci_evt_io_capa_req        *evt = (void *)buf->data;
+  struct net_buf                       *resp_buf;
+  struct bt_conn                       *conn;
+  struct bt_hci_cp_io_capability_reply *cp;
+  u8_t                                  auth;
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  BT_DBG("");
 
-    resp_buf = bt_hci_cmd_create(BT_HCI_OP_IO_CAPABILITY_REPLY,
-                                 sizeof(*cp));
-    if (!resp_buf) {
-        BT_ERR("Out of command buffers");
-        bt_conn_unref(conn);
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    /*
-	 * Set authentication requirements when acting as pairing initiator to
-	 * 'dedicated bond' with MITM protection set if local IO capa
-	 * potentially allows it, and for acceptor, based on local IO capa and
-	 * remote's authentication set.
-	 */
-    if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR)) {
-        if (bt_conn_get_io_capa() != BT_IO_NO_INPUT_OUTPUT) {
-            auth = BT_HCI_DEDICATED_BONDING_MITM;
-        } else {
-            auth = BT_HCI_DEDICATED_BONDING;
-        }
+  resp_buf = bt_hci_cmd_create(BT_HCI_OP_IO_CAPABILITY_REPLY, sizeof(*cp));
+  if (!resp_buf) {
+    BT_ERR("Out of command buffers");
+    bt_conn_unref(conn);
+    return;
+  }
+
+  /*
+   * Set authentication requirements when acting as pairing initiator to
+   * 'dedicated bond' with MITM protection set if local IO capa
+   * potentially allows it, and for acceptor, based on local IO capa and
+   * remote's authentication set.
+   */
+  if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR)) {
+    if (bt_conn_get_io_capa() != BT_IO_NO_INPUT_OUTPUT) {
+      auth = BT_HCI_DEDICATED_BONDING_MITM;
     } else {
-        auth = bt_conn_ssp_get_auth(conn);
+      auth = BT_HCI_DEDICATED_BONDING;
     }
+  } else {
+    auth = bt_conn_ssp_get_auth(conn);
+  }
 
-    cp = net_buf_add(resp_buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, &evt->bdaddr);
-    cp->capability = bt_conn_get_io_capa();
-    cp->authentication = auth;
-    cp->oob_data = 0U;
-    bt_hci_cmd_send_sync(BT_HCI_OP_IO_CAPABILITY_REPLY, resp_buf, NULL);
-    bt_conn_unref(conn);
+  cp = net_buf_add(resp_buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, &evt->bdaddr);
+  cp->capability     = bt_conn_get_io_capa();
+  cp->authentication = auth;
+  cp->oob_data       = 0U;
+  bt_hci_cmd_send_sync(BT_HCI_OP_IO_CAPABILITY_REPLY, resp_buf, NULL);
+  bt_conn_unref(conn);
 }
 
-static void ssp_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_ssp_complete *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void ssp_complete(struct net_buf *buf) {
+  struct bt_hci_evt_ssp_complete *evt = (void *)buf->data;
+  struct bt_conn                 *conn;
 
-    BT_DBG("status 0x%02x", evt->status);
+  BT_DBG("status 0x%02x", evt->status);
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    bt_conn_ssp_auth_complete(conn, security_err_get(evt->status));
-    if (evt->status) {
-        bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
-    }
+  bt_conn_ssp_auth_complete(conn, security_err_get(evt->status));
+  if (evt->status) {
+    bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
-static void user_confirm_req(struct net_buf *buf)
-{
-    struct bt_hci_evt_user_confirm_req *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void user_confirm_req(struct net_buf *buf) {
+  struct bt_hci_evt_user_confirm_req *evt = (void *)buf->data;
+  struct bt_conn                     *conn;
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    bt_conn_ssp_auth(conn, sys_le32_to_cpu(evt->passkey));
-    bt_conn_unref(conn);
+  bt_conn_ssp_auth(conn, sys_le32_to_cpu(evt->passkey));
+  bt_conn_unref(conn);
 }
 
-static void user_passkey_notify(struct net_buf *buf)
-{
-    struct bt_hci_evt_user_passkey_notify *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void user_passkey_notify(struct net_buf *buf) {
+  struct bt_hci_evt_user_passkey_notify *evt = (void *)buf->data;
+  struct bt_conn                        *conn;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    bt_conn_ssp_auth(conn, sys_le32_to_cpu(evt->passkey));
-    bt_conn_unref(conn);
+  bt_conn_ssp_auth(conn, sys_le32_to_cpu(evt->passkey));
+  bt_conn_unref(conn);
 }
 
-static void user_passkey_req(struct net_buf *buf)
-{
-    struct bt_hci_evt_user_passkey_req *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void user_passkey_req(struct net_buf *buf) {
+  struct bt_hci_evt_user_passkey_req *evt = (void *)buf->data;
+  struct bt_conn                     *conn;
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    bt_conn_ssp_auth(conn, 0);
-    bt_conn_unref(conn);
+  bt_conn_ssp_auth(conn, 0);
+  bt_conn_unref(conn);
 }
 
 struct discovery_priv {
-    u16_t clock_offset;
-    u8_t pscan_rep_mode;
-    u8_t resolving;
+  u16_t clock_offset;
+  u8_t  pscan_rep_mode;
+  u8_t  resolving;
 } __packed;
 
-static int request_name(const bt_addr_t *addr, u8_t pscan, u16_t offset)
-{
-    struct bt_hci_cp_remote_name_request *cp;
-    struct net_buf *buf;
+static int request_name(const bt_addr_t *addr, u8_t pscan, u16_t offset) {
+  struct bt_hci_cp_remote_name_request *cp;
+  struct net_buf                       *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_REMOTE_NAME_REQUEST, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_REMOTE_NAME_REQUEST, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
 
-    bt_addr_copy(&cp->bdaddr, addr);
-    cp->pscan_rep_mode = pscan;
-    cp->reserved = 0x00; /* reserver, should be set to 0x00 */
-    cp->clock_offset = offset;
+  bt_addr_copy(&cp->bdaddr, addr);
+  cp->pscan_rep_mode = pscan;
+  cp->reserved       = 0x00; /* reserver, should be set to 0x00 */
+  cp->clock_offset   = offset;
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_REMOTE_NAME_REQUEST, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_REMOTE_NAME_REQUEST, buf, NULL);
 }
 
 #define EIR_SHORT_NAME    0x08
 #define EIR_COMPLETE_NAME 0x09
 
-static bool eir_has_name(const u8_t *eir)
-{
-    int len = 240;
+static bool eir_has_name(const u8_t *eir) {
+  int len = 240;
 
-    while (len) {
-        if (len < 2) {
-            break;
-        };
-
-        /* Look for early termination */
-        if (!eir[0]) {
-            break;
-        }
-
-        /* Check if field length is correct */
-        if (eir[0] > len - 1) {
-            break;
-        }
+  while (len) {
+    if (len < 2) {
+      break;
+    };
 
-        switch (eir[1]) {
-            case EIR_SHORT_NAME:
-            case EIR_COMPLETE_NAME:
-                if (eir[0] > 1) {
-                    return true;
-                }
-                break;
-            default:
-                break;
-        }
+    /* Look for early termination */
+    if (!eir[0]) {
+      break;
+    }
 
-        /* Parse next AD Structure */
-        len -= eir[0] + 1;
-        eir += eir[0] + 1;
+    /* Check if field length is correct */
+    if (eir[0] > len - 1) {
+      break;
     }
 
-    return false;
-}
+    switch (eir[1]) {
+    case EIR_SHORT_NAME:
+    case EIR_COMPLETE_NAME:
+      if (eir[0] > 1) {
+        return true;
+      }
+      break;
+    default:
+      break;
+    }
 
-static void report_discovery_results(void)
-{
-    bool resolving_names = false;
-    int i;
+    /* Parse next AD Structure */
+    len -= eir[0] + 1;
+    eir += eir[0] + 1;
+  }
 
-    for (i = 0; i < discovery_results_count; i++) {
-        struct discovery_priv *priv;
+  return false;
+}
 
-        priv = (struct discovery_priv *)&discovery_results[i]._priv;
+static void report_discovery_results(void) {
+  bool resolving_names = false;
+  int  i;
 
-        if (eir_has_name(discovery_results[i].eir)) {
-            continue;
-        }
+  for (i = 0; i < discovery_results_count; i++) {
+    struct discovery_priv *priv;
 
-        if (request_name(&discovery_results[i].addr,
-                         priv->pscan_rep_mode, priv->clock_offset)) {
-            continue;
-        }
+    priv = (struct discovery_priv *)&discovery_results[i]._priv;
 
-        priv->resolving = 1U;
-        resolving_names = true;
+    if (eir_has_name(discovery_results[i].eir)) {
+      continue;
     }
 
-    if (resolving_names) {
-        return;
+    if (request_name(&discovery_results[i].addr, priv->pscan_rep_mode, priv->clock_offset)) {
+      continue;
     }
 
-    atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY);
-
-    discovery_cb(discovery_results, discovery_results_count);
+    priv->resolving = 1U;
+    resolving_names = true;
+  }
 
-    discovery_cb = NULL;
-    discovery_results = NULL;
-    discovery_results_size = 0;
-    discovery_results_count = 0;
-}
+  if (resolving_names) {
+    return;
+  }
 
-static void inquiry_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_inquiry_complete *evt = (void *)buf->data;
+  atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY);
 
-    if (evt->status) {
-        BT_ERR("Failed to complete inquiry");
-    }
+  discovery_cb(discovery_results, discovery_results_count);
 
-    report_discovery_results();
+  discovery_cb            = NULL;
+  discovery_results       = NULL;
+  discovery_results_size  = 0;
+  discovery_results_count = 0;
 }
 
-static struct bt_br_discovery_result *get_result_slot(const bt_addr_t *addr,
-                                                      s8_t rssi)
-{
-    struct bt_br_discovery_result *result = NULL;
-    size_t i;
+static void inquiry_complete(struct net_buf *buf) {
+  struct bt_hci_evt_inquiry_complete *evt = (void *)buf->data;
 
-    /* check if already present in results */
-    for (i = 0; i < discovery_results_count; i++) {
-        if (!bt_addr_cmp(addr, &discovery_results[i].addr)) {
-            return &discovery_results[i];
-        }
-    }
-
-    /* Pick a new slot (if available) */
-    if (discovery_results_count < discovery_results_size) {
-        bt_addr_copy(&discovery_results[discovery_results_count].addr,
-                     addr);
-        return &discovery_results[discovery_results_count++];
-    }
-
-    /* ignore if invalid RSSI */
-    if (rssi == 0xff) {
-        return NULL;
-    }
-
-    /*
-	 * Pick slot with smallest RSSI that is smaller then passed RSSI
-	 * TODO handle TX if present
-	 */
-    for (i = 0; i < discovery_results_size; i++) {
-        if (discovery_results[i].rssi > rssi) {
-            continue;
-        }
+  if (evt->status) {
+    BT_ERR("Failed to complete inquiry");
+  }
 
-        if (!result || result->rssi > discovery_results[i].rssi) {
-            result = &discovery_results[i];
-        }
-    }
+  report_discovery_results();
+}
 
-    if (result) {
-        BT_DBG("Reusing slot (old %s rssi %d dBm)",
-               bt_addr_str(&result->addr), result->rssi);
+static struct bt_br_discovery_result *get_result_slot(const bt_addr_t *addr, s8_t rssi) {
+  struct bt_br_discovery_result *result = NULL;
+  size_t                         i;
 
-        bt_addr_copy(&result->addr, addr);
+  /* check if already present in results */
+  for (i = 0; i < discovery_results_count; i++) {
+    if (!bt_addr_cmp(addr, &discovery_results[i].addr)) {
+      return &discovery_results[i];
     }
+  }
 
-    return result;
-}
+  /* Pick a new slot (if available) */
+  if (discovery_results_count < discovery_results_size) {
+    bt_addr_copy(&discovery_results[discovery_results_count].addr, addr);
+    return &discovery_results[discovery_results_count++];
+  }
 
-static void inquiry_result_with_rssi(struct net_buf *buf)
-{
-    u8_t num_reports = net_buf_pull_u8(buf);
+  /* ignore if invalid RSSI */
+  if (rssi == 0xff) {
+    return NULL;
+  }
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
-        return;
+  /*
+   * Pick slot with smallest RSSI that is smaller then passed RSSI
+   * TODO handle TX if present
+   */
+  for (i = 0; i < discovery_results_size; i++) {
+    if (discovery_results[i].rssi > rssi) {
+      continue;
     }
 
-    BT_DBG("number of results: %u", num_reports);
-
-    while (num_reports--) {
-        struct bt_hci_evt_inquiry_result_with_rssi *evt;
-        struct bt_br_discovery_result *result;
-        struct discovery_priv *priv;
+    if (!result || result->rssi > discovery_results[i].rssi) {
+      result = &discovery_results[i];
+    }
+  }
 
-        if (buf->len < sizeof(*evt)) {
-            BT_ERR("Unexpected end to buffer");
-            return;
-        }
+  if (result) {
+    BT_DBG("Reusing slot (old %s rssi %d dBm)", bt_addr_str(&result->addr), result->rssi);
 
-        evt = net_buf_pull_mem(buf, sizeof(*evt));
-        BT_DBG("%s rssi %d dBm", bt_addr_str(&evt->addr), evt->rssi);
+    bt_addr_copy(&result->addr, addr);
+  }
 
-        result = get_result_slot(&evt->addr, evt->rssi);
-        if (!result) {
-            return;
-        }
+  return result;
+}
 
-        priv = (struct discovery_priv *)&result->_priv;
-        priv->pscan_rep_mode = evt->pscan_rep_mode;
-        priv->clock_offset = evt->clock_offset;
+static void inquiry_result_with_rssi(struct net_buf *buf) {
+  u8_t num_reports = net_buf_pull_u8(buf);
 
-        memcpy(result->cod, evt->cod, 3);
-        result->rssi = evt->rssi;
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
+    return;
+  }
 
-        /* we could reuse slot so make sure EIR is cleared */
-        (void)memset(result->eir, 0, sizeof(result->eir));
-    }
-}
+  BT_DBG("number of results: %u", num_reports);
 
-static void extended_inquiry_result(struct net_buf *buf)
-{
-    struct bt_hci_evt_extended_inquiry_result *evt = (void *)buf->data;
-    struct bt_br_discovery_result *result;
-    struct discovery_priv *priv;
+  while (num_reports--) {
+    struct bt_hci_evt_inquiry_result_with_rssi *evt;
+    struct bt_br_discovery_result              *result;
+    struct discovery_priv                      *priv;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
-        return;
+    if (buf->len < sizeof(*evt)) {
+      BT_ERR("Unexpected end to buffer");
+      return;
     }
 
+    evt = net_buf_pull_mem(buf, sizeof(*evt));
     BT_DBG("%s rssi %d dBm", bt_addr_str(&evt->addr), evt->rssi);
 
     result = get_result_slot(&evt->addr, evt->rssi);
     if (!result) {
-        return;
+      return;
     }
 
-    priv = (struct discovery_priv *)&result->_priv;
+    priv                 = (struct discovery_priv *)&result->_priv;
     priv->pscan_rep_mode = evt->pscan_rep_mode;
-    priv->clock_offset = evt->clock_offset;
+    priv->clock_offset   = evt->clock_offset;
 
-    result->rssi = evt->rssi;
     memcpy(result->cod, evt->cod, 3);
-    memcpy(result->eir, evt->eir, sizeof(result->eir));
+    result->rssi = evt->rssi;
+
+    /* we could reuse slot so make sure EIR is cleared */
+    (void)memset(result->eir, 0, sizeof(result->eir));
+  }
 }
 
-static void remote_name_request_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_remote_name_req_complete *evt = (void *)buf->data;
-    struct bt_br_discovery_result *result;
-    struct discovery_priv *priv;
-    int eir_len = 240;
-    u8_t *eir;
-    int i;
+static void extended_inquiry_result(struct net_buf *buf) {
+  struct bt_hci_evt_extended_inquiry_result *evt = (void *)buf->data;
+  struct bt_br_discovery_result             *result;
+  struct discovery_priv                     *priv;
 
-    result = get_result_slot(&evt->bdaddr, 0xff);
-    if (!result) {
-        return;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
+    return;
+  }
 
-    priv = (struct discovery_priv *)&result->_priv;
-    priv->resolving = 0U;
+  BT_DBG("%s rssi %d dBm", bt_addr_str(&evt->addr), evt->rssi);
 
-    if (evt->status) {
-        goto check_names;
-    }
+  result = get_result_slot(&evt->addr, evt->rssi);
+  if (!result) {
+    return;
+  }
 
-    eir = result->eir;
+  priv                 = (struct discovery_priv *)&result->_priv;
+  priv->pscan_rep_mode = evt->pscan_rep_mode;
+  priv->clock_offset   = evt->clock_offset;
 
-    while (eir_len) {
-        if (eir_len < 2) {
-            break;
-        };
+  result->rssi = evt->rssi;
+  memcpy(result->cod, evt->cod, 3);
+  memcpy(result->eir, evt->eir, sizeof(result->eir));
+}
 
-        /* Look for early termination */
-        if (!eir[0]) {
-            size_t name_len;
+static void remote_name_request_complete(struct net_buf *buf) {
+  struct bt_hci_evt_remote_name_req_complete *evt = (void *)buf->data;
+  struct bt_br_discovery_result              *result;
+  struct discovery_priv                      *priv;
+  int                                         eir_len = 240;
+  u8_t                                       *eir;
+  int                                         i;
 
-            eir_len -= 2;
+  result = get_result_slot(&evt->bdaddr, 0xff);
+  if (!result) {
+    return;
+  }
 
-            /* name is null terminated */
-            name_len = strlen((const char *)evt->name);
+  priv            = (struct discovery_priv *)&result->_priv;
+  priv->resolving = 0U;
 
-            if (name_len > eir_len) {
-                eir[0] = eir_len + 1;
-                eir[1] = EIR_SHORT_NAME;
-            } else {
-                eir[0] = name_len + 1;
-                eir[1] = EIR_SHORT_NAME;
-            }
+  if (evt->status) {
+    goto check_names;
+  }
 
-            memcpy(&eir[2], evt->name, eir[0] - 1);
+  eir = result->eir;
 
-            break;
-        }
+  while (eir_len) {
+    if (eir_len < 2) {
+      break;
+    };
 
-        /* Check if field length is correct */
-        if (eir[0] > eir_len - 1) {
-            break;
-        }
+    /* Look for early termination */
+    if (!eir[0]) {
+      size_t name_len;
+
+      eir_len -= 2;
+
+      /* name is null terminated */
+      name_len = strlen((const char *)evt->name);
 
-        /* next EIR Structure */
-        eir_len -= eir[0] + 1;
-        eir += eir[0] + 1;
+      if (name_len > eir_len) {
+        eir[0] = eir_len + 1;
+        eir[1] = EIR_SHORT_NAME;
+      } else {
+        eir[0] = name_len + 1;
+        eir[1] = EIR_SHORT_NAME;
+      }
+
+      memcpy(&eir[2], evt->name, eir[0] - 1);
+
+      break;
     }
 
+    /* Check if field length is correct */
+    if (eir[0] > eir_len - 1) {
+      break;
+    }
+
+    /* next EIR Structure */
+    eir_len -= eir[0] + 1;
+    eir += eir[0] + 1;
+  }
+
 check_names:
-    /* if still waiting for names */
-    for (i = 0; i < discovery_results_count; i++) {
-        struct discovery_priv *priv;
+  /* if still waiting for names */
+  for (i = 0; i < discovery_results_count; i++) {
+    struct discovery_priv *priv;
 
-        priv = (struct discovery_priv *)&discovery_results[i]._priv;
+    priv = (struct discovery_priv *)&discovery_results[i]._priv;
 
-        if (priv->resolving) {
-            return;
-        }
+    if (priv->resolving) {
+      return;
     }
+  }
 
-    /* all names resolved, report discovery results */
-    atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY);
+  /* all names resolved, report discovery results */
+  atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY);
 
-    discovery_cb(discovery_results, discovery_results_count);
+  discovery_cb(discovery_results, discovery_results_count);
 
-    discovery_cb = NULL;
-    discovery_results = NULL;
-    discovery_results_size = 0;
-    discovery_results_count = 0;
+  discovery_cb            = NULL;
+  discovery_results       = NULL;
+  discovery_results_size  = 0;
+  discovery_results_count = 0;
 }
 
-static void link_encr(const u16_t handle)
-{
-    struct bt_hci_cp_set_conn_encrypt *encr;
-    struct net_buf *buf;
+static void link_encr(const u16_t handle) {
+  struct bt_hci_cp_set_conn_encrypt *encr;
+  struct net_buf                    *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_SET_CONN_ENCRYPT, sizeof(*encr));
-    if (!buf) {
-        BT_ERR("Out of command buffers");
-        return;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_SET_CONN_ENCRYPT, sizeof(*encr));
+  if (!buf) {
+    BT_ERR("Out of command buffers");
+    return;
+  }
 
-    encr = net_buf_add(buf, sizeof(*encr));
-    encr->handle = sys_cpu_to_le16(handle);
-    encr->encrypt = 0x01;
+  encr          = net_buf_add(buf, sizeof(*encr));
+  encr->handle  = sys_cpu_to_le16(handle);
+  encr->encrypt = 0x01;
 
-    bt_hci_cmd_send_sync(BT_HCI_OP_SET_CONN_ENCRYPT, buf, NULL);
+  bt_hci_cmd_send_sync(BT_HCI_OP_SET_CONN_ENCRYPT, buf, NULL);
 }
 
-static void auth_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_auth_complete *evt = (void *)buf->data;
-    struct bt_conn *conn;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
+static void auth_complete(struct net_buf *buf) {
+  struct bt_hci_evt_auth_complete *evt = (void *)buf->data;
+  struct bt_conn                  *conn;
+  u16_t                            handle = sys_le16_to_cpu(evt->handle);
 
-    BT_DBG("status 0x%02x, handle %u", evt->status, handle);
+  BT_DBG("status 0x%02x, handle %u", evt->status, handle);
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Can't find conn for handle %u", handle);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Can't find conn for handle %u", handle);
+    return;
+  }
 
-    if (evt->status) {
-        if (conn->state == BT_CONN_CONNECTED) {
-            /*
-			 * Inform layers above HCI about non-zero authentication
-			 * status to make them able cleanup pending jobs.
-			 */
-            bt_l2cap_encrypt_change(conn, evt->status);
-        }
-        reset_pairing(conn);
-    } else {
-        link_encr(handle);
+  if (evt->status) {
+    if (conn->state == BT_CONN_CONNECTED) {
+      /*
+       * Inform layers above HCI about non-zero authentication
+       * status to make them able cleanup pending jobs.
+       */
+      bt_l2cap_encrypt_change(conn, evt->status);
     }
+    reset_pairing(conn);
+  } else {
+    link_encr(handle);
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
-static void read_remote_features_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_remote_features *evt = (void *)buf->data;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    struct bt_hci_cp_read_remote_ext_features *cp;
-    struct bt_conn *conn;
+static void read_remote_features_complete(struct net_buf *buf) {
+  struct bt_hci_evt_remote_features         *evt    = (void *)buf->data;
+  u16_t                                      handle = sys_le16_to_cpu(evt->handle);
+  struct bt_hci_cp_read_remote_ext_features *cp;
+  struct bt_conn                            *conn;
 
-    BT_DBG("status 0x%02x handle %u", evt->status, handle);
+  BT_DBG("status 0x%02x handle %u", evt->status, handle);
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Can't find conn for handle %u", handle);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Can't find conn for handle %u", handle);
+    return;
+  }
 
-    if (evt->status) {
-        goto done;
-    }
+  if (evt->status) {
+    goto done;
+  }
 
-    memcpy(conn->br.features[0], evt->features, sizeof(evt->features));
+  memcpy(conn->br.features[0], evt->features, sizeof(evt->features));
 
-    if (!BT_FEAT_EXT_FEATURES(conn->br.features)) {
-        goto done;
-    }
+  if (!BT_FEAT_EXT_FEATURES(conn->br.features)) {
+    goto done;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_EXT_FEATURES,
-                            sizeof(*cp));
-    if (!buf) {
-        goto done;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_EXT_FEATURES, sizeof(*cp));
+  if (!buf) {
+    goto done;
+  }
 
-    /* Read remote host features (page 1) */
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = evt->handle;
-    cp->page = 0x01;
+  /* Read remote host features (page 1) */
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = evt->handle;
+  cp->page   = 0x01;
 
-    bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_EXT_FEATURES, buf, NULL);
+  bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_EXT_FEATURES, buf, NULL);
 
 done:
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
-static void read_remote_ext_features_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_remote_ext_features *evt = (void *)buf->data;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    struct bt_conn *conn;
+static void read_remote_ext_features_complete(struct net_buf *buf) {
+  struct bt_hci_evt_remote_ext_features *evt    = (void *)buf->data;
+  u16_t                                  handle = sys_le16_to_cpu(evt->handle);
+  struct bt_conn                        *conn;
 
-    BT_DBG("status 0x%02x handle %u", evt->status, handle);
+  BT_DBG("status 0x%02x handle %u", evt->status, handle);
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Can't find conn for handle %u", handle);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Can't find conn for handle %u", handle);
+    return;
+  }
 
-    if (!evt->status && evt->page == 0x01) {
-        memcpy(conn->br.features[1], evt->features,
-               sizeof(conn->br.features[1]));
-    }
+  if (!evt->status && evt->page == 0x01) {
+    memcpy(conn->br.features[1], evt->features, sizeof(conn->br.features[1]));
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
-static void role_change(struct net_buf *buf)
-{
-    struct bt_hci_evt_role_change *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void role_change(struct net_buf *buf) {
+  struct bt_hci_evt_role_change *evt = (void *)buf->data;
+  struct bt_conn                *conn;
 
-    BT_DBG("status 0x%02x role %u addr %s", evt->status, evt->role,
-           bt_addr_str(&evt->bdaddr));
+  BT_DBG("status 0x%02x role %u addr %s", evt->status, evt->role, bt_addr_str(&evt->bdaddr));
 
-    if (evt->status) {
-        return;
-    }
+  if (evt->status) {
+    return;
+  }
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    if (evt->role) {
-        conn->role = BT_CONN_ROLE_SLAVE;
-    } else {
-        conn->role = BT_CONN_ROLE_MASTER;
-    }
+  if (evt->role) {
+    conn->role = BT_CONN_ROLE_SLAVE;
+  } else {
+    conn->role = BT_CONN_ROLE_MASTER;
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 #endif /* CONFIG_BT_BREDR */
 
 #if defined(CONFIG_BT_SMP)
-static int le_set_privacy_mode(const bt_addr_le_t *addr, u8_t mode)
-{
-    struct bt_hci_cp_le_set_privacy_mode cp;
-    struct net_buf *buf;
-    int err;
-
-    /* Check if set privacy mode command is supported */
-    if (!BT_CMD_TEST(bt_dev.supported_commands, 39, 2)) {
-        BT_WARN("Set privacy mode command is not supported");
-        return 0;
-    }
+static int le_set_privacy_mode(const bt_addr_le_t *addr, u8_t mode) {
+  struct bt_hci_cp_le_set_privacy_mode cp;
+  struct net_buf                      *buf;
+  int                                  err;
+
+  /* Check if set privacy mode command is supported */
+  if (!BT_CMD_TEST(bt_dev.supported_commands, 39, 2)) {
+    BT_WARN("Set privacy mode command is not supported");
+    return 0;
+  }
 
-    BT_DBG("addr %s mode 0x%02x", bt_addr_le_str(addr), mode);
+  BT_DBG("addr %s mode 0x%02x", bt_addr_le_str(addr), mode);
 
-    bt_addr_le_copy(&cp.id_addr, addr);
-    cp.mode = mode;
+  bt_addr_le_copy(&cp.id_addr, addr);
+  cp.mode = mode;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PRIVACY_MODE, sizeof(cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PRIVACY_MODE, sizeof(cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    net_buf_add_mem(buf, &cp, sizeof(cp));
+  net_buf_add_mem(buf, &cp, sizeof(cp));
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_PRIVACY_MODE, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_PRIVACY_MODE, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 #if defined(CONFIG_BT_STACK_PTS)
 int addr_res_enable(u8_t enable)
@@ -3167,19 +2993,18 @@ int addr_res_enable(u8_t enable)
 static int addr_res_enable(u8_t enable)
 #endif
 {
-    struct net_buf *buf;
+  struct net_buf *buf;
 
-    BT_DBG("%s", enable ? "enabled" : "disabled");
+  BT_DBG("%s", enable ? "enabled" : "disabled");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE, 1);
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE, 1);
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    net_buf_add_u8(buf, enable);
+  net_buf_add_u8(buf, enable);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE,
-                                buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE, buf, NULL);
 }
 
 #if defined(CONFIG_BT_STACK_PTS)
@@ -3188,1093 +3013,992 @@ int hci_id_add(const bt_addr_le_t *addr, u8_t val[16])
 static int hci_id_add(const bt_addr_le_t *addr, u8_t val[16])
 #endif
 {
-    struct bt_hci_cp_le_add_dev_to_rl *cp;
-    struct net_buf *buf;
+  struct bt_hci_cp_le_add_dev_to_rl *cp;
+  struct net_buf                    *buf;
 
-    BT_DBG("addr %s", bt_addr_le_str(addr));
+  BT_DBG("addr %s", bt_addr_le_str(addr));
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_RL, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_RL, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_le_copy(&cp->peer_id_addr, addr);
-    memcpy(cp->peer_irk, val, 16);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_le_copy(&cp->peer_id_addr, addr);
+  memcpy(cp->peer_irk, val, 16);
 
 #if defined(CONFIG_BT_PRIVACY)
-    memcpy(cp->local_irk, bt_dev.irk, 16);
+  memcpy(cp->local_irk, bt_dev.irk, 16);
 #else
-    (void)memset(cp->local_irk, 0, 16);
+  (void)memset(cp->local_irk, 0, 16);
 #endif
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_RL, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_RL, buf, NULL);
 }
 
-void bt_id_add(struct bt_keys *keys)
-{
-    bool adv_enabled;
+void bt_id_add(struct bt_keys *keys) {
+  bool adv_enabled;
 #if defined(CONFIG_BT_OBSERVER)
-    bool scan_enabled;
+  bool scan_enabled;
 #endif /* CONFIG_BT_OBSERVER */
-    struct bt_conn *conn;
-    int err;
+  struct bt_conn *conn;
+  int             err;
 
-    BT_DBG("addr %s", bt_addr_le_str(&keys->addr));
+  BT_DBG("addr %s", bt_addr_le_str(&keys->addr));
 
-    /* Nothing to be done if host-side resolving is used */
-    if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) {
-        bt_dev.le.rl_entries++;
-        return;
-    }
+  /* Nothing to be done if host-side resolving is used */
+  if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) {
+    bt_dev.le.rl_entries++;
+    return;
+  }
 
-    conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
-    if (conn) {
-        atomic_set_bit(bt_dev.flags, BT_DEV_ID_PENDING);
-        keys->flags |= BT_KEYS_ID_PENDING_ADD;
-        bt_conn_unref(conn);
-        return;
-    }
+  conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
+  if (conn) {
+    atomic_set_bit(bt_dev.flags, BT_DEV_ID_PENDING);
+    keys->flags |= BT_KEYS_ID_PENDING_ADD;
+    bt_conn_unref(conn);
+    return;
+  }
 
-    adv_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING);
-    if (adv_enabled) {
-        set_advertise_enable(false);
-    }
+  adv_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING);
+  if (adv_enabled) {
+    set_advertise_enable(false);
+  }
 
 #if defined(CONFIG_BT_OBSERVER)
-    scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING);
-    if (scan_enabled) {
-        set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
-    }
+  scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING);
+  if (scan_enabled) {
+    set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
+  }
 #endif /* CONFIG_BT_OBSERVER */
 
-    /* If there are any existing entries address resolution will be on */
-    if (bt_dev.le.rl_entries) {
-        err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE);
-        if (err) {
-            BT_WARN("Failed to disable address resolution");
-            goto done;
-        }
+  /* If there are any existing entries address resolution will be on */
+  if (bt_dev.le.rl_entries) {
+    err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE);
+    if (err) {
+      BT_WARN("Failed to disable address resolution");
+      goto done;
     }
+  }
 
-    if (bt_dev.le.rl_entries == bt_dev.le.rl_size) {
-        BT_WARN("Resolving list size exceeded. Switching to host.");
-
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_RL, NULL, NULL);
-        if (err) {
-            BT_ERR("Failed to clear resolution list");
-            goto done;
-        }
-
-        bt_dev.le.rl_entries++;
-
-        goto done;
-    }
+  if (bt_dev.le.rl_entries == bt_dev.le.rl_size) {
+    BT_WARN("Resolving list size exceeded. Switching to host.");
 
-    err = hci_id_add(&keys->addr, keys->irk.val);
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_RL, NULL, NULL);
     if (err) {
-        BT_ERR("Failed to add IRK to controller");
-        goto done;
+      BT_ERR("Failed to clear resolution list");
+      goto done;
     }
 
     bt_dev.le.rl_entries++;
 
-    /*
-	 * According to Core Spec. 5.0 Vol 1, Part A 5.4.5 Privacy Feature
-	 *
-	 * By default, network privacy mode is used when private addresses are
-	 * resolved and generated by the Controller, so advertising packets from
-	 * peer devices that contain private addresses will only be accepted.
-	 * By changing to the device privacy mode device is only concerned about
-	 * its privacy and will accept advertising packets from peer devices
-	 * that contain their identity address as well as ones that contain
-	 * a private address, even if the peer device has distributed its IRK in
-	 * the past.
-	 */
-    err = le_set_privacy_mode(&keys->addr, BT_HCI_LE_PRIVACY_MODE_DEVICE);
-    if (err) {
-        BT_ERR("Failed to set privacy mode");
-        goto done;
-    }
+    goto done;
+  }
+
+  err = hci_id_add(&keys->addr, keys->irk.val);
+  if (err) {
+    BT_ERR("Failed to add IRK to controller");
+    goto done;
+  }
+
+  bt_dev.le.rl_entries++;
+
+  /*
+   * According to Core Spec. 5.0 Vol 1, Part A 5.4.5 Privacy Feature
+   *
+   * By default, network privacy mode is used when private addresses are
+   * resolved and generated by the Controller, so advertising packets from
+   * peer devices that contain private addresses will only be accepted.
+   * By changing to the device privacy mode device is only concerned about
+   * its privacy and will accept advertising packets from peer devices
+   * that contain their identity address as well as ones that contain
+   * a private address, even if the peer device has distributed its IRK in
+   * the past.
+   */
+  err = le_set_privacy_mode(&keys->addr, BT_HCI_LE_PRIVACY_MODE_DEVICE);
+  if (err) {
+    BT_ERR("Failed to set privacy mode");
+    goto done;
+  }
 
 done:
-    addr_res_enable(BT_HCI_ADDR_RES_ENABLE);
+  addr_res_enable(BT_HCI_ADDR_RES_ENABLE);
 
 #if defined(CONFIG_BT_OBSERVER)
-    if (scan_enabled) {
-        set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
-    }
+  if (scan_enabled) {
+    set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
+  }
 #endif /* CONFIG_BT_OBSERVER */
 
-    if (adv_enabled) {
-        set_advertise_enable(true);
-    }
+  if (adv_enabled) {
+    set_advertise_enable(true);
+  }
 }
 
-static void keys_add_id(struct bt_keys *keys, void *data)
-{
-    hci_id_add(&keys->addr, keys->irk.val);
-}
+static void keys_add_id(struct bt_keys *keys, void *data) { hci_id_add(&keys->addr, keys->irk.val); }
 
-void bt_id_del(struct bt_keys *keys)
-{
-    struct bt_hci_cp_le_rem_dev_from_rl *cp;
-    bool adv_enabled;
+void bt_id_del(struct bt_keys *keys) {
+  struct bt_hci_cp_le_rem_dev_from_rl *cp;
+  bool                                 adv_enabled;
 #if defined(CONFIG_BT_OBSERVER)
-    bool scan_enabled;
+  bool scan_enabled;
 #endif /* CONFIG_BT_OBSERVER */
-    struct bt_conn *conn;
-    struct net_buf *buf;
-    int err;
+  struct bt_conn *conn;
+  struct net_buf *buf;
+  int             err;
 
-    BT_DBG("addr %s", bt_addr_le_str(&keys->addr));
+  BT_DBG("addr %s", bt_addr_le_str(&keys->addr));
 
-    if (!bt_dev.le.rl_size ||
-        bt_dev.le.rl_entries > bt_dev.le.rl_size + 1) {
-        bt_dev.le.rl_entries--;
-        return;
-    }
+  if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size + 1) {
+    bt_dev.le.rl_entries--;
+    return;
+  }
 
-    conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
-    if (conn) {
-        atomic_set_bit(bt_dev.flags, BT_DEV_ID_PENDING);
-        keys->flags |= BT_KEYS_ID_PENDING_DEL;
-        bt_conn_unref(conn);
-        return;
-    }
+  conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
+  if (conn) {
+    atomic_set_bit(bt_dev.flags, BT_DEV_ID_PENDING);
+    keys->flags |= BT_KEYS_ID_PENDING_DEL;
+    bt_conn_unref(conn);
+    return;
+  }
 
-    adv_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING);
-    if (adv_enabled) {
-        set_advertise_enable(false);
-    }
+  adv_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING);
+  if (adv_enabled) {
+    set_advertise_enable(false);
+  }
 
 #if defined(CONFIG_BT_OBSERVER)
-    scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING);
-    if (scan_enabled) {
-        set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
-    }
+  scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING);
+  if (scan_enabled) {
+    set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
+  }
 #endif /* CONFIG_BT_OBSERVER */
 
-    err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE);
-    if (err) {
-        BT_ERR("Disabling address resolution failed (err %d)", err);
-        goto done;
-    }
+  err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE);
+  if (err) {
+    BT_ERR("Disabling address resolution failed (err %d)", err);
+    goto done;
+  }
 
-    /* We checked size + 1 earlier, so here we know we can fit again */
-    if (bt_dev.le.rl_entries > bt_dev.le.rl_size) {
-        bt_dev.le.rl_entries--;
-        keys->keys &= ~BT_KEYS_IRK;
-        bt_keys_foreach(BT_KEYS_IRK, keys_add_id, NULL);
-        goto done;
-    }
+  /* We checked size + 1 earlier, so here we know we can fit again */
+  if (bt_dev.le.rl_entries > bt_dev.le.rl_size) {
+    bt_dev.le.rl_entries--;
+    keys->keys &= ~BT_KEYS_IRK;
+    bt_keys_foreach(BT_KEYS_IRK, keys_add_id, NULL);
+    goto done;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_RL, sizeof(*cp));
-    if (!buf) {
-        goto done;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_RL, sizeof(*cp));
+  if (!buf) {
+    goto done;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_le_copy(&cp->peer_id_addr, &keys->addr);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_le_copy(&cp->peer_id_addr, &keys->addr);
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_RL, buf, NULL);
-    if (err) {
-        BT_ERR("Failed to remove IRK from controller");
-        goto done;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_RL, buf, NULL);
+  if (err) {
+    BT_ERR("Failed to remove IRK from controller");
+    goto done;
+  }
 
-    bt_dev.le.rl_entries--;
+  bt_dev.le.rl_entries--;
 
 done:
-    /* Only re-enable if there are entries to do resolving with */
-    if (bt_dev.le.rl_entries) {
-        addr_res_enable(BT_HCI_ADDR_RES_ENABLE);
-    }
+  /* Only re-enable if there are entries to do resolving with */
+  if (bt_dev.le.rl_entries) {
+    addr_res_enable(BT_HCI_ADDR_RES_ENABLE);
+  }
 
 #if defined(CONFIG_BT_OBSERVER)
-    if (scan_enabled) {
-        set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
-    }
+  if (scan_enabled) {
+    set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
+  }
 #endif /* CONFIG_BT_OBSERVER */
 
-    if (adv_enabled) {
-        set_advertise_enable(true);
-    }
+  if (adv_enabled) {
+    set_advertise_enable(true);
+  }
 }
 
-static void update_sec_level(struct bt_conn *conn)
-{
-    if (!conn->encrypt) {
-        conn->sec_level = BT_SECURITY_L1;
-        return;
-    }
+static void update_sec_level(struct bt_conn *conn) {
+  if (!conn->encrypt) {
+    conn->sec_level = BT_SECURITY_L1;
+    return;
+  }
 
-    if (conn->le.keys && (conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) {
-        if (conn->le.keys->flags & BT_KEYS_SC &&
-            conn->le.keys->enc_size == BT_SMP_MAX_ENC_KEY_SIZE) {
-            conn->sec_level = BT_SECURITY_L4;
-        } else {
-            conn->sec_level = BT_SECURITY_L3;
-        }
+  if (conn->le.keys && (conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) {
+    if (conn->le.keys->flags & BT_KEYS_SC && conn->le.keys->enc_size == BT_SMP_MAX_ENC_KEY_SIZE) {
+      conn->sec_level = BT_SECURITY_L4;
     } else {
-        conn->sec_level = BT_SECURITY_L2;
+      conn->sec_level = BT_SECURITY_L3;
     }
+  } else {
+    conn->sec_level = BT_SECURITY_L2;
+  }
 
-    if (conn->required_sec_level > conn->sec_level) {
-        BT_ERR("Failed to set required security level");
-        bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
-    }
+  if (conn->required_sec_level > conn->sec_level) {
+    BT_ERR("Failed to set required security level");
+    bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
+  }
 }
 #endif /* CONFIG_BT_SMP */
 
 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
-static void hci_encrypt_change(struct net_buf *buf)
-{
-    struct bt_hci_evt_encrypt_change *evt = (void *)buf->data;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    struct bt_conn *conn;
+static void hci_encrypt_change(struct net_buf *buf) {
+  struct bt_hci_evt_encrypt_change *evt    = (void *)buf->data;
+  u16_t                             handle = sys_le16_to_cpu(evt->handle);
+  struct bt_conn                   *conn;
 
-    BT_DBG("status 0x%02x handle %u encrypt 0x%02x", evt->status, handle,
-           evt->encrypt);
+  BT_DBG("status 0x%02x handle %u encrypt 0x%02x", evt->status, handle, evt->encrypt);
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to look up conn with handle %u", handle);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to look up conn with handle %u", handle);
+    return;
+  }
 
-    if (evt->status) {
-        reset_pairing(conn);
-        bt_l2cap_encrypt_change(conn, evt->status);
-        bt_conn_security_changed(conn, security_err_get(evt->status));
-        bt_conn_unref(conn);
-        return;
-    }
+  if (evt->status) {
+    reset_pairing(conn);
+    bt_l2cap_encrypt_change(conn, evt->status);
+    bt_conn_security_changed(conn, security_err_get(evt->status));
+    bt_conn_unref(conn);
+    return;
+  }
 
-    conn->encrypt = evt->encrypt;
+  conn->encrypt = evt->encrypt;
 
 #if defined(CONFIG_BT_SMP)
-    if (conn->type == BT_CONN_TYPE_LE) {
-        /*
-		 * we update keys properties only on successful encryption to
-		 * avoid losing valid keys if encryption was not successful.
-		 *
-		 * Update keys with last pairing info for proper sec level
-		 * update. This is done only for LE transport, for BR/EDR keys
-		 * are updated on HCI 'Link Key Notification Event'
-		 */
-        if (conn->encrypt) {
-            bt_smp_update_keys(conn);
-        }
-        update_sec_level(conn);
+  if (conn->type == BT_CONN_TYPE_LE) {
+    /*
+     * we update keys properties only on successful encryption to
+     * avoid losing valid keys if encryption was not successful.
+     *
+     * Update keys with last pairing info for proper sec level
+     * update. This is done only for LE transport, for BR/EDR keys
+     * are updated on HCI 'Link Key Notification Event'
+     */
+    if (conn->encrypt) {
+      bt_smp_update_keys(conn);
     }
+    update_sec_level(conn);
+  }
 #endif /* CONFIG_BT_SMP */
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        if (!update_sec_level_br(conn)) {
-            bt_conn_unref(conn);
-            return;
-        }
-
-        if (IS_ENABLED(CONFIG_BT_SMP)) {
-            /*
-			 * Start SMP over BR/EDR if we are pairing and are
-			 * master on the link
-			 */
-            if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING) &&
-                conn->role == BT_CONN_ROLE_MASTER) {
-                bt_smp_br_send_pairing_req(conn);
-            }
-        }
+  if (conn->type == BT_CONN_TYPE_BR) {
+    if (!update_sec_level_br(conn)) {
+      bt_conn_unref(conn);
+      return;
     }
+
+    if (IS_ENABLED(CONFIG_BT_SMP)) {
+      /*
+       * Start SMP over BR/EDR if we are pairing and are
+       * master on the link
+       */
+      if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING) && conn->role == BT_CONN_ROLE_MASTER) {
+        bt_smp_br_send_pairing_req(conn);
+      }
+    }
+  }
 #endif /* CONFIG_BT_BREDR */
-    reset_pairing(conn);
+  reset_pairing(conn);
 
-    bt_l2cap_encrypt_change(conn, evt->status);
-    bt_conn_security_changed(conn, BT_SECURITY_ERR_SUCCESS);
+  bt_l2cap_encrypt_change(conn, evt->status);
+  bt_conn_security_changed(conn, BT_SECURITY_ERR_SUCCESS);
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
-static void hci_encrypt_key_refresh_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_encrypt_key_refresh_complete *evt = (void *)buf->data;
-    struct bt_conn *conn;
-    u16_t handle;
-
-    handle = sys_le16_to_cpu(evt->handle);
+static void hci_encrypt_key_refresh_complete(struct net_buf *buf) {
+  struct bt_hci_evt_encrypt_key_refresh_complete *evt = (void *)buf->data;
+  struct bt_conn                                 *conn;
+  u16_t                                           handle;
 
-    BT_DBG("status 0x%02x handle %u", evt->status, handle);
+  handle = sys_le16_to_cpu(evt->handle);
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to look up conn with handle %u", handle);
-        return;
-    }
+  BT_DBG("status 0x%02x handle %u", evt->status, handle);
 
-    if (evt->status) {
-        reset_pairing(conn);
-        bt_l2cap_encrypt_change(conn, evt->status);
-        bt_conn_security_changed(conn, security_err_get(evt->status));
-        bt_conn_unref(conn);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to look up conn with handle %u", handle);
+    return;
+  }
 
-    /*
-	 * Update keys with last pairing info for proper sec level update.
-	 * This is done only for LE transport. For BR/EDR transport keys are
-	 * updated on HCI 'Link Key Notification Event', therefore update here
-	 * only security level based on available keys and encryption state.
-	 */
+  if (evt->status) {
+    reset_pairing(conn);
+    bt_l2cap_encrypt_change(conn, evt->status);
+    bt_conn_security_changed(conn, security_err_get(evt->status));
+    bt_conn_unref(conn);
+    return;
+  }
+
+  /*
+   * Update keys with last pairing info for proper sec level update.
+   * This is done only for LE transport. For BR/EDR transport keys are
+   * updated on HCI 'Link Key Notification Event', therefore update here
+   * only security level based on available keys and encryption state.
+   */
 #if defined(CONFIG_BT_SMP)
-    if (conn->type == BT_CONN_TYPE_LE) {
-        bt_smp_update_keys(conn);
-        update_sec_level(conn);
-    }
+  if (conn->type == BT_CONN_TYPE_LE) {
+    bt_smp_update_keys(conn);
+    update_sec_level(conn);
+  }
 #endif /* CONFIG_BT_SMP */
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        if (!update_sec_level_br(conn)) {
-            bt_conn_unref(conn);
-            return;
-        }
+  if (conn->type == BT_CONN_TYPE_BR) {
+    if (!update_sec_level_br(conn)) {
+      bt_conn_unref(conn);
+      return;
     }
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    reset_pairing(conn);
-    bt_l2cap_encrypt_change(conn, evt->status);
-    bt_conn_security_changed(conn, BT_SECURITY_ERR_SUCCESS);
-    bt_conn_unref(conn);
+  reset_pairing(conn);
+  bt_l2cap_encrypt_change(conn, evt->status);
+  bt_conn_security_changed(conn, BT_SECURITY_ERR_SUCCESS);
+  bt_conn_unref(conn);
 }
 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
 
 #if defined(CONFIG_BT_SMP)
-static void le_ltk_neg_reply(u16_t handle)
-{
-    struct bt_hci_cp_le_ltk_req_neg_reply *cp;
-    struct net_buf *buf;
+static void le_ltk_neg_reply(u16_t handle) {
+  struct bt_hci_cp_le_ltk_req_neg_reply *cp;
+  struct net_buf                        *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, sizeof(*cp));
-    if (!buf) {
-        BT_ERR("Out of command buffers");
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("Out of command buffers");
 
-        return;
-    }
+    return;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(handle);
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = sys_cpu_to_le16(handle);
 
-    bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, buf);
+  bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, buf);
 }
 
-static void le_ltk_reply(u16_t handle, u8_t *ltk)
-{
-    struct bt_hci_cp_le_ltk_req_reply *cp;
-    struct net_buf *buf;
+static void le_ltk_reply(u16_t handle, u8_t *ltk) {
+  struct bt_hci_cp_le_ltk_req_reply *cp;
+  struct net_buf                    *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_REPLY,
-                            sizeof(*cp));
-    if (!buf) {
-        BT_ERR("Out of command buffers");
-        return;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_REPLY, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("Out of command buffers");
+    return;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(handle);
-    memcpy(cp->ltk, ltk, sizeof(cp->ltk));
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = sys_cpu_to_le16(handle);
+  memcpy(cp->ltk, ltk, sizeof(cp->ltk));
 
-    bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_REPLY, buf);
+  bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_REPLY, buf);
 }
 
-static void le_ltk_request(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_ltk_request *evt = (void *)buf->data;
-    struct bt_conn *conn;
-    u16_t handle;
-    u8_t ltk[16];
+static void le_ltk_request(struct net_buf *buf) {
+  struct bt_hci_evt_le_ltk_request *evt = (void *)buf->data;
+  struct bt_conn                   *conn;
+  u16_t                             handle;
+  u8_t                              ltk[16];
 
-    handle = sys_le16_to_cpu(evt->handle);
+  handle = sys_le16_to_cpu(evt->handle);
 
-    BT_DBG("handle %u", handle);
+  BT_DBG("handle %u", handle);
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to lookup conn for handle %u", handle);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to lookup conn for handle %u", handle);
+    return;
+  }
 
-    if (bt_smp_request_ltk(conn, evt->rand, evt->ediv, ltk)) {
-        le_ltk_reply(handle, ltk);
-    } else {
-        le_ltk_neg_reply(handle);
-    }
+  if (bt_smp_request_ltk(conn, evt->rand, evt->ediv, ltk)) {
+    le_ltk_reply(handle, ltk);
+  } else {
+    le_ltk_neg_reply(handle);
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 #endif /* CONFIG_BT_SMP */
 
 #if defined(CONFIG_BT_ECC)
-static void le_pkey_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_p256_public_key_complete *evt = (void *)buf->data;
-    struct bt_pub_key_cb *cb;
+static void le_pkey_complete(struct net_buf *buf) {
+  struct bt_hci_evt_le_p256_public_key_complete *evt = (void *)buf->data;
+  struct bt_pub_key_cb                          *cb;
 
-    BT_DBG("status: 0x%02x", evt->status);
+  BT_DBG("status: 0x%02x", evt->status);
 
-    atomic_clear_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY);
+  atomic_clear_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY);
 
-    if (!evt->status) {
-        memcpy(pub_key, evt->key, 64);
-        atomic_set_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY);
-    }
+  if (!evt->status) {
+    memcpy(pub_key, evt->key, 64);
+    atomic_set_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY);
+  }
 
-    for (cb = pub_key_cb; cb; cb = cb->_next) {
-        cb->func(evt->status ? NULL : pub_key);
-    }
+  for (cb = pub_key_cb; cb; cb = cb->_next) {
+    cb->func(evt->status ? NULL : pub_key);
+  }
 
-    pub_key_cb = NULL;
+  pub_key_cb = NULL;
 }
 
-static void le_dhkey_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_generate_dhkey_complete *evt = (void *)buf->data;
+static void le_dhkey_complete(struct net_buf *buf) {
+  struct bt_hci_evt_le_generate_dhkey_complete *evt = (void *)buf->data;
 
-    BT_DBG("status: 0x%02x", evt->status);
+  BT_DBG("status: 0x%02x", evt->status);
 
-    if (dh_key_cb) {
-        dh_key_cb(evt->status ? NULL : evt->dhkey);
-        dh_key_cb = NULL;
-    }
+  if (dh_key_cb) {
+    dh_key_cb(evt->status ? NULL : evt->dhkey);
+    dh_key_cb = NULL;
+  }
 }
 #endif /* CONFIG_BT_ECC */
 
-static void hci_reset_complete(struct net_buf *buf)
-{
-    u8_t status = buf->data[0];
-    atomic_t flags;
+static void hci_reset_complete(struct net_buf *buf) {
+  u8_t     status = buf->data[0];
+  atomic_t flags;
 
-    BT_DBG("status 0x%02x", status);
+  BT_DBG("status 0x%02x", status);
 
-    if (status) {
-        return;
-    }
+  if (status) {
+    return;
+  }
 
-    scan_dev_found_cb = NULL;
+  scan_dev_found_cb = NULL;
 #if defined(CONFIG_BT_BREDR)
-    discovery_cb = NULL;
-    discovery_results = NULL;
-    discovery_results_size = 0;
-    discovery_results_count = 0;
+  discovery_cb            = NULL;
+  discovery_results       = NULL;
+  discovery_results_size  = 0;
+  discovery_results_count = 0;
 #endif /* CONFIG_BT_BREDR */
 
-    flags = (atomic_get(bt_dev.flags) & BT_DEV_PERSISTENT_FLAGS);
-    atomic_set(bt_dev.flags, flags);
+  flags = (atomic_get(bt_dev.flags) & BT_DEV_PERSISTENT_FLAGS);
+  atomic_set(bt_dev.flags, flags);
 }
 
-static void hci_cmd_done(u16_t opcode, u8_t status, struct net_buf *buf)
-{
-    BT_DBG("opcode 0x%04x status 0x%02x buf %p", opcode, status, buf);
+static void hci_cmd_done(u16_t opcode, u8_t status, struct net_buf *buf) {
+  BT_DBG("opcode 0x%04x status 0x%02x buf %p", opcode, status, buf);
 
-    if (net_buf_pool_get(buf->pool_id) != &hci_cmd_pool) {
-        BT_WARN("opcode 0x%04x pool id %u pool %p != &hci_cmd_pool %p",
-                opcode, buf->pool_id, net_buf_pool_get(buf->pool_id),
-                &hci_cmd_pool);
-        return;
-    }
+  if (net_buf_pool_get(buf->pool_id) != &hci_cmd_pool) {
+    BT_WARN("opcode 0x%04x pool id %u pool %p != &hci_cmd_pool %p", opcode, buf->pool_id, net_buf_pool_get(buf->pool_id), &hci_cmd_pool);
+    return;
+  }
 
-    if (cmd(buf)->opcode != opcode) {
-        BT_WARN("OpCode 0x%04x completed instead of expected 0x%04x",
-                opcode, cmd(buf)->opcode);
-    }
+  if (cmd(buf)->opcode != opcode) {
+    BT_WARN("OpCode 0x%04x completed instead of expected 0x%04x", opcode, cmd(buf)->opcode);
+  }
 
-    if (cmd(buf)->state && !status) {
-        struct cmd_state_set *update = cmd(buf)->state;
+  if (cmd(buf)->state && !status) {
+    struct cmd_state_set *update = cmd(buf)->state;
 
-        atomic_set_bit_to(update->target, update->bit, update->val);
-    }
+    atomic_set_bit_to(update->target, update->bit, update->val);
+  }
 
-    /* If the command was synchronous wake up bt_hci_cmd_send_sync() */
-    if (cmd(buf)->sync) {
-        cmd(buf)->status = status;
-        k_sem_give(cmd(buf)->sync);
-    }
+  /* If the command was synchronous wake up bt_hci_cmd_send_sync() */
+  if (cmd(buf)->sync) {
+    cmd(buf)->status = status;
+    k_sem_give(cmd(buf)->sync);
+  }
 }
 
-static void hci_cmd_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_cmd_complete *evt;
-    u8_t status, ncmd;
-    u16_t opcode;
+static void hci_cmd_complete(struct net_buf *buf) {
+  struct bt_hci_evt_cmd_complete *evt;
+  u8_t                            status, ncmd;
+  u16_t                           opcode;
 
-    evt = net_buf_pull_mem(buf, sizeof(*evt));
-    ncmd = evt->ncmd;
-    opcode = sys_le16_to_cpu(evt->opcode);
+  evt    = net_buf_pull_mem(buf, sizeof(*evt));
+  ncmd   = evt->ncmd;
+  opcode = sys_le16_to_cpu(evt->opcode);
 
-    BT_DBG("opcode 0x%04x", opcode);
+  BT_DBG("opcode 0x%04x", opcode);
 
-    /* All command return parameters have a 1-byte status in the
-	 * beginning, so we can safely make this generalization.
-	 */
-    status = buf->data[0];
+  /* All command return parameters have a 1-byte status in the
+   * beginning, so we can safely make this generalization.
+   */
+  status = buf->data[0];
 
-    hci_cmd_done(opcode, status, buf);
+  hci_cmd_done(opcode, status, buf);
 
-    /* Allow next command to be sent */
-    if (ncmd) {
-        k_sem_give(&bt_dev.ncmd_sem);
-    }
+  /* Allow next command to be sent */
+  if (ncmd) {
+    k_sem_give(&bt_dev.ncmd_sem);
+  }
 }
 
-static void hci_cmd_status(struct net_buf *buf)
-{
-    struct bt_hci_evt_cmd_status *evt;
-    u16_t opcode;
-    u8_t ncmd;
+static void hci_cmd_status(struct net_buf *buf) {
+  struct bt_hci_evt_cmd_status *evt;
+  u16_t                         opcode;
+  u8_t                          ncmd;
 
-    evt = net_buf_pull_mem(buf, sizeof(*evt));
-    opcode = sys_le16_to_cpu(evt->opcode);
-    ncmd = evt->ncmd;
+  evt    = net_buf_pull_mem(buf, sizeof(*evt));
+  opcode = sys_le16_to_cpu(evt->opcode);
+  ncmd   = evt->ncmd;
 
-    BT_DBG("opcode 0x%04x", opcode);
+  BT_DBG("opcode 0x%04x", opcode);
 
-    hci_cmd_done(opcode, evt->status, buf);
+  hci_cmd_done(opcode, evt->status, buf);
 
-    /* Allow next command to be sent */
-    if (ncmd) {
-        k_sem_give(&bt_dev.ncmd_sem);
-    }
+  /* Allow next command to be sent */
+  if (ncmd) {
+    k_sem_give(&bt_dev.ncmd_sem);
+  }
 }
 
 #if defined(CONFIG_BT_OBSERVER)
-static int start_le_scan(u8_t scan_type, u16_t interval, u16_t window)
-{
-    struct bt_hci_cp_le_set_scan_param set_param;
-    struct net_buf *buf;
-    int err;
-
-    (void)memset(&set_param, 0, sizeof(set_param));
+static int start_le_scan(u8_t scan_type, u16_t interval, u16_t window) {
+  struct bt_hci_cp_le_set_scan_param set_param;
+  struct net_buf                    *buf;
+  int                                err;
 
-    set_param.scan_type = scan_type;
+  (void)memset(&set_param, 0, sizeof(set_param));
 
-    /* for the rest parameters apply default values according to
-	 *  spec 4.2, vol2, part E, 7.8.10
-	 */
-    set_param.interval = sys_cpu_to_le16(interval);
-    set_param.window = sys_cpu_to_le16(window);
+  set_param.scan_type = scan_type;
 
-    if (IS_ENABLED(CONFIG_BT_WHITELIST) &&
-        atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_WL)) {
-        set_param.filter_policy = BT_HCI_LE_SCAN_FP_USE_WHITELIST;
-    } else {
-        set_param.filter_policy = BT_HCI_LE_SCAN_FP_NO_WHITELIST;
-    }
+  /* for the rest parameters apply default values according to
+   *  spec 4.2, vol2, part E, 7.8.10
+   */
+  set_param.interval = sys_cpu_to_le16(interval);
+  set_param.window   = sys_cpu_to_le16(window);
 
-    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-        err = le_set_private_addr(BT_ID_DEFAULT);
-        if (err) {
-            return err;
-        }
+  if (IS_ENABLED(CONFIG_BT_WHITELIST) && atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_WL)) {
+    set_param.filter_policy = BT_HCI_LE_SCAN_FP_USE_WHITELIST;
+  } else {
+    set_param.filter_policy = BT_HCI_LE_SCAN_FP_NO_WHITELIST;
+  }
 
-        if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
-            set_param.addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-        } else {
-            set_param.addr_type = BT_ADDR_LE_RANDOM;
-        }
-    } else {
-        set_param.addr_type = bt_dev.id_addr[0].type;
-
-        /* Use NRPA unless identity has been explicitly requested
-		 * (through Kconfig), or if there is no advertising ongoing.
-		 */
-        if (!IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) &&
-            scan_type == BT_HCI_LE_SCAN_ACTIVE &&
-            !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-            err = le_set_private_addr(BT_ID_DEFAULT);
-            if (err) {
-                return err;
-            }
-
-            set_param.addr_type = BT_ADDR_LE_RANDOM;
-        } else if (set_param.addr_type == BT_ADDR_LE_RANDOM) {
-            err = set_random_address(&bt_dev.id_addr[0].a);
-            if (err) {
-                return err;
-            }
-        }
+  if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    err = le_set_private_addr(BT_ID_DEFAULT);
+    if (err) {
+      return err;
     }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_PARAM, sizeof(set_param));
-    if (!buf) {
-        return -ENOBUFS;
+    if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+      set_param.addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+    } else {
+      set_param.addr_type = BT_ADDR_LE_RANDOM;
     }
+  } else {
+    set_param.addr_type = bt_dev.id_addr[0].type;
 
-    net_buf_add_mem(buf, &set_param, sizeof(set_param));
-
-    bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_PARAM, buf, NULL);
+    /* Use NRPA unless identity has been explicitly requested
+     * (through Kconfig), or if there is no advertising ongoing.
+     */
+    if (!IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) && scan_type == BT_HCI_LE_SCAN_ACTIVE && !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+      err = le_set_private_addr(BT_ID_DEFAULT);
+      if (err) {
+        return err;
+      }
 
-    err = set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
-    if (err) {
+      set_param.addr_type = BT_ADDR_LE_RANDOM;
+    } else if (set_param.addr_type == BT_ADDR_LE_RANDOM) {
+      err = set_random_address(&bt_dev.id_addr[0].a);
+      if (err) {
         return err;
+      }
     }
+  }
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_ACTIVE_SCAN,
-                      scan_type == BT_HCI_LE_SCAN_ACTIVE);
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_PARAM, sizeof(set_param));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    return 0;
-}
+  net_buf_add_mem(buf, &set_param, sizeof(set_param));
 
-#if defined(CONFIG_BT_STACK_PTS)
-static int start_le_scan_with_isrpa(u8_t scan_type, u16_t interval, u16_t window, u8_t addre_type)
-{
-    struct bt_hci_cp_le_set_scan_param set_param;
-    struct net_buf *buf;
-    int err = 0;
+  bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_PARAM, buf, NULL);
 
-    memset(&set_param, 0, sizeof(set_param));
+  err = set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
+  if (err) {
+    return err;
+  }
 
-    set_param.scan_type = scan_type;
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_ACTIVE_SCAN, scan_type == BT_HCI_LE_SCAN_ACTIVE);
 
-    /* for the rest parameters apply default values according to
-     *  spec 4.2, vol2, part E, 7.8.10
-     */
-    set_param.interval = sys_cpu_to_le16(interval);
-    set_param.window = sys_cpu_to_le16(window);
-    set_param.filter_policy = 0x00;
+  return 0;
+}
 
-    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-        if (addre_type == 1)
-            err = le_set_private_addr(BT_ID_DEFAULT);
-        else if (addre_type == 0)
-            err = le_set_non_resolv_private_addr(BT_ID_DEFAULT);
-        if (err) {
-            return err;
-        }
+#if defined(CONFIG_BT_STACK_PTS)
+static int start_le_scan_with_isrpa(u8_t scan_type, u16_t interval, u16_t window, u8_t addre_type) {
+  struct bt_hci_cp_le_set_scan_param set_param;
+  struct net_buf                    *buf;
+  int                                err = 0;
+
+  memset(&set_param, 0, sizeof(set_param));
+
+  set_param.scan_type = scan_type;
+
+  /* for the rest parameters apply default values according to
+   *  spec 4.2, vol2, part E, 7.8.10
+   */
+  set_param.interval      = sys_cpu_to_le16(interval);
+  set_param.window        = sys_cpu_to_le16(window);
+  set_param.filter_policy = 0x00;
+
+  if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    if (addre_type == 1)
+      err = le_set_private_addr(BT_ID_DEFAULT);
+    else if (addre_type == 0)
+      err = le_set_non_resolv_private_addr(BT_ID_DEFAULT);
+    if (err) {
+      return err;
+    }
 
-        if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
-            if (addre_type == 2)
-                set_param.addr_type = BT_ADDR_LE_PUBLIC;
-            if (addre_type == 1)
-                set_param.addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-            else if (addre_type == 0)
-                set_param.addr_type = BT_ADDR_LE_RANDOM;
-        } else {
-            set_param.addr_type = BT_ADDR_LE_RANDOM;
-        }
+    if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+      if (addre_type == 2)
+        set_param.addr_type = BT_ADDR_LE_PUBLIC;
+      if (addre_type == 1)
+        set_param.addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+      else if (addre_type == 0)
+        set_param.addr_type = BT_ADDR_LE_RANDOM;
     } else {
-        set_param.addr_type = bt_dev.id_addr[0].type;
-
-        /* Use NRPA unless identity has been explicitly requested
-         * (through Kconfig), or if there is no advertising ongoing.
-         */
-        if (!IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) &&
-            scan_type == BT_HCI_LE_SCAN_ACTIVE &&
-            !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-            err = le_set_private_addr(BT_ID_DEFAULT);
-            if (err) {
-                return err;
-            }
-
-            set_param.addr_type = BT_ADDR_LE_RANDOM;
-        }
+      set_param.addr_type = BT_ADDR_LE_RANDOM;
     }
+  } else {
+    set_param.addr_type = bt_dev.id_addr[0].type;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_PARAM, sizeof(set_param));
-    if (!buf) {
-        return -ENOBUFS;
+    /* Use NRPA unless identity has been explicitly requested
+     * (through Kconfig), or if there is no advertising ongoing.
+     */
+    if (!IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) && scan_type == BT_HCI_LE_SCAN_ACTIVE && !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+      err = le_set_private_addr(BT_ID_DEFAULT);
+      if (err) {
+        return err;
+      }
+
+      set_param.addr_type = BT_ADDR_LE_RANDOM;
     }
+  }
 
-    net_buf_add_mem(buf, &set_param, sizeof(set_param));
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_PARAM, sizeof(set_param));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_PARAM, buf, NULL);
+  net_buf_add_mem(buf, &set_param, sizeof(set_param));
 
-    err = set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
-    if (err) {
-        return err;
-    }
+  bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_PARAM, buf, NULL);
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_ACTIVE_SCAN,
-                      scan_type == BT_HCI_LE_SCAN_ACTIVE);
+  err = set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_ACTIVE_SCAN, scan_type == BT_HCI_LE_SCAN_ACTIVE);
+
+  return 0;
 }
 
 #endif
 
-int bt_le_scan_update(bool fast_scan)
-{
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
-        return 0;
-    }
+int bt_le_scan_update(bool fast_scan) {
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
+    return 0;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
-        int err;
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
+    int err;
 
-        err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
-        if (err) {
-            return err;
-        }
+    err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
+    if (err) {
+      return err;
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
-        u16_t interval, window;
-        struct bt_conn *conn;
-
-        /* don't restart scan if we have pending connection */
-        conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
-        if (conn) {
-            bt_conn_unref(conn);
-            return 0;
-        }
+  if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
+    u16_t           interval, window;
+    struct bt_conn *conn;
 
-        conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT_SCAN);
-        if (!conn) {
-            return 0;
-        }
+    /* don't restart scan if we have pending connection */
+    conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
+    if (conn) {
+      bt_conn_unref(conn);
+      return 0;
+    }
 
-        //atomic_set_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP);
-        atomic_clear_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP);
+    conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT_SCAN);
+    if (!conn) {
+      return 0;
+    }
 
-        bt_conn_unref(conn);
+    // atomic_set_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP);
+    atomic_clear_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP);
 
-        if (fast_scan) {
-            interval = BT_GAP_SCAN_FAST_INTERVAL;
-            window = BT_GAP_SCAN_FAST_WINDOW;
-        } else {
-            interval = CONFIG_BT_BACKGROUND_SCAN_INTERVAL;
-            window = CONFIG_BT_BACKGROUND_SCAN_WINDOW;
-        }
+    bt_conn_unref(conn);
 
-        return start_le_scan(BT_HCI_LE_SCAN_PASSIVE, interval, window);
+    if (fast_scan) {
+      interval = BT_GAP_SCAN_FAST_INTERVAL;
+      window   = BT_GAP_SCAN_FAST_WINDOW;
+    } else {
+      interval = CONFIG_BT_BACKGROUND_SCAN_INTERVAL;
+      window   = CONFIG_BT_BACKGROUND_SCAN_WINDOW;
     }
 
-    return 0;
+    return start_le_scan(BT_HCI_LE_SCAN_PASSIVE, interval, window);
+  }
+
+  return 0;
 }
 
-void bt_data_parse(struct net_buf_simple *ad,
-                   bool (*func)(struct bt_data *data, void *user_data),
-                   void *user_data)
-{
-    while (ad->len > 1) {
-        struct bt_data data;
-        u8_t len;
-
-        len = net_buf_simple_pull_u8(ad);
-        if (len == 0U) {
-            /* Early termination */
-            return;
-        }
+void bt_data_parse(struct net_buf_simple *ad, bool (*func)(struct bt_data *data, void *user_data), void *user_data) {
+  while (ad->len > 1) {
+    struct bt_data data;
+    u8_t           len;
 
-        if (len > ad->len) {
-            BT_WARN("Malformed data");
-            return;
-        }
+    len = net_buf_simple_pull_u8(ad);
+    if (len == 0U) {
+      /* Early termination */
+      return;
+    }
 
-        data.type = net_buf_simple_pull_u8(ad);
-        data.data_len = len - 1;
-        data.data = ad->data;
+    if (len > ad->len) {
+      BT_WARN("Malformed data");
+      return;
+    }
 
-        if (!func(&data, user_data)) {
-            return;
-        }
+    data.type     = net_buf_simple_pull_u8(ad);
+    data.data_len = len - 1;
+    data.data     = ad->data;
 
-        net_buf_simple_pull(ad, len - 1);
+    if (!func(&data, user_data)) {
+      return;
     }
+
+    net_buf_simple_pull(ad, len - 1);
+  }
 }
 
-static void le_adv_report(struct net_buf *buf)
-{
-    u8_t num_reports = net_buf_pull_u8(buf);
-    struct bt_hci_evt_le_advertising_info *info;
+static void le_adv_report(struct net_buf *buf) {
+  u8_t                                   num_reports = net_buf_pull_u8(buf);
+  struct bt_hci_evt_le_advertising_info *info;
 
-    BT_DBG("Adv number of reports %u", num_reports);
+  BT_DBG("Adv number of reports %u", num_reports);
 
-    while (num_reports--) {
-        bt_addr_le_t id_addr;
-        s8_t rssi;
+  while (num_reports--) {
+    bt_addr_le_t id_addr;
+    s8_t         rssi;
 
-        if (buf->len < sizeof(*info)) {
-            BT_ERR("Unexpected end of buffer");
-            break;
-        }
+    if (buf->len < sizeof(*info)) {
+      BT_ERR("Unexpected end of buffer");
+      break;
+    }
 
-        info = net_buf_pull_mem(buf, sizeof(*info));
-        rssi = info->data[info->length];
-
-        BT_DBG("%s event %u, len %u, rssi %d dBm",
-               bt_addr_le_str(&info->addr),
-               info->evt_type, info->length, rssi);
-
-        if (info->addr.type == BT_ADDR_LE_PUBLIC_ID ||
-            info->addr.type == BT_ADDR_LE_RANDOM_ID) {
-            bt_addr_le_copy(&id_addr, &info->addr);
-            id_addr.type -= BT_ADDR_LE_PUBLIC_ID;
-        } else {
-            bt_addr_le_copy(&id_addr,
-                            bt_lookup_id_addr(bt_dev.adv_id,
-                                              &info->addr));
-        }
+    info = net_buf_pull_mem(buf, sizeof(*info));
+    rssi = info->data[info->length];
+
+    BT_DBG("%s event %u, len %u, rssi %d dBm", bt_addr_le_str(&info->addr), info->evt_type, info->length, rssi);
+
+    if (info->addr.type == BT_ADDR_LE_PUBLIC_ID || info->addr.type == BT_ADDR_LE_RANDOM_ID) {
+      bt_addr_le_copy(&id_addr, &info->addr);
+      id_addr.type -= BT_ADDR_LE_PUBLIC_ID;
+    } else {
+      bt_addr_le_copy(&id_addr, bt_lookup_id_addr(bt_dev.adv_id, &info->addr));
+    }
 
-        if (scan_dev_found_cb) {
-            struct net_buf_simple_state state;
+    if (scan_dev_found_cb) {
+      struct net_buf_simple_state state;
 
-            net_buf_simple_save(&buf->b, &state);
+      net_buf_simple_save(&buf->b, &state);
 
-            buf->len = info->length;
-            scan_dev_found_cb(&id_addr, rssi, info->evt_type,
-                              &buf->b);
+      buf->len = info->length;
+      scan_dev_found_cb(&id_addr, rssi, info->evt_type, &buf->b);
 
-            net_buf_simple_restore(&buf->b, &state);
-        }
+      net_buf_simple_restore(&buf->b, &state);
+    }
 
 #if defined(CONFIG_BT_CENTRAL)
-        check_pending_conn(&id_addr, &info->addr, info->evt_type);
+    check_pending_conn(&id_addr, &info->addr, info->evt_type);
 #endif /* CONFIG_BT_CENTRAL */
 
-        net_buf_pull(buf, info->length + sizeof(rssi));
-    }
+    net_buf_pull(buf, info->length + sizeof(rssi));
+  }
 }
 #endif /* CONFIG_BT_OBSERVER */
 
-int bt_hci_get_conn_handle(const struct bt_conn *conn, u16_t *conn_handle)
-{
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+int bt_hci_get_conn_handle(const struct bt_conn *conn, u16_t *conn_handle) {
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    *conn_handle = conn->handle;
-    return 0;
+  *conn_handle = conn->handle;
+  return 0;
 }
 
 #if defined(CONFIG_BT_HCI_VS_EVT_USER)
-int bt_hci_register_vnd_evt_cb(bt_hci_vnd_evt_cb_t cb)
-{
-    hci_vnd_evt_cb = cb;
-    return 0;
+int bt_hci_register_vnd_evt_cb(bt_hci_vnd_evt_cb_t cb) {
+  hci_vnd_evt_cb = cb;
+  return 0;
 }
 #endif /* CONFIG_BT_HCI_VS_EVT_USER */
 
-static void hci_vendor_event(struct net_buf *buf)
-{
-    bool handled = false;
+static void hci_vendor_event(struct net_buf *buf) {
+  bool handled = false;
 
 #if defined(CONFIG_BT_HCI_VS_EVT_USER)
-    if (hci_vnd_evt_cb) {
-        struct net_buf_simple_state state;
+  if (hci_vnd_evt_cb) {
+    struct net_buf_simple_state state;
 
-        net_buf_simple_save(&buf->b, &state);
+    net_buf_simple_save(&buf->b, &state);
 
-        handled = (hci_vnd_evt_cb)(&buf->b);
+    handled = (hci_vnd_evt_cb)(&buf->b);
 
-        net_buf_simple_restore(&buf->b, &state);
-    }
+    net_buf_simple_restore(&buf->b, &state);
+  }
 #endif /* CONFIG_BT_HCI_VS_EVT_USER */
 
-    if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT) && !handled) {
-        /* do nothing at present time */
-        BT_WARN("Unhandled vendor-specific event: %s",
-                bt_hex(buf->data, buf->len));
-    }
+  if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT) && !handled) {
+    /* do nothing at present time */
+    BT_WARN("Unhandled vendor-specific event: %s", bt_hex(buf->data, buf->len));
+  }
 }
 
 static const struct event_handler meta_events[] = {
 #if defined(CONFIG_BT_OBSERVER)
-    EVENT_HANDLER(BT_HCI_EVT_LE_ADVERTISING_REPORT, le_adv_report,
-                  sizeof(struct bt_hci_evt_le_advertising_report)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_ADVERTISING_REPORT, le_adv_report, sizeof(struct bt_hci_evt_le_advertising_report)),
 #endif /* CONFIG_BT_OBSERVER */
 #if defined(CONFIG_BT_CONN)
-    EVENT_HANDLER(BT_HCI_EVT_LE_CONN_COMPLETE, le_legacy_conn_complete,
-                  sizeof(struct bt_hci_evt_le_conn_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_LE_ENH_CONN_COMPLETE, le_enh_conn_complete,
-                  sizeof(struct bt_hci_evt_le_enh_conn_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_LE_CONN_UPDATE_COMPLETE,
-                  le_conn_update_complete,
-                  sizeof(struct bt_hci_evt_le_conn_update_complete)),
-    EVENT_HANDLER(BT_HCI_EV_LE_REMOTE_FEAT_COMPLETE,
-                  le_remote_feat_complete,
-                  sizeof(struct bt_hci_evt_le_remote_feat_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_LE_CONN_PARAM_REQ, le_conn_param_req,
-                  sizeof(struct bt_hci_evt_le_conn_param_req)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_CONN_COMPLETE, le_legacy_conn_complete, sizeof(struct bt_hci_evt_le_conn_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_ENH_CONN_COMPLETE, le_enh_conn_complete, sizeof(struct bt_hci_evt_le_enh_conn_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_CONN_UPDATE_COMPLETE, le_conn_update_complete, sizeof(struct bt_hci_evt_le_conn_update_complete)),
+    EVENT_HANDLER(BT_HCI_EV_LE_REMOTE_FEAT_COMPLETE, le_remote_feat_complete, sizeof(struct bt_hci_evt_le_remote_feat_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_CONN_PARAM_REQ, le_conn_param_req, sizeof(struct bt_hci_evt_le_conn_param_req)),
 #if defined(CONFIG_BT_DATA_LEN_UPDATE)
-    EVENT_HANDLER(BT_HCI_EVT_LE_DATA_LEN_CHANGE, le_data_len_change,
-                  sizeof(struct bt_hci_evt_le_data_len_change)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_DATA_LEN_CHANGE, le_data_len_change, sizeof(struct bt_hci_evt_le_data_len_change)),
 #endif /* CONFIG_BT_DATA_LEN_UPDATE */
 #if defined(CONFIG_BT_PHY_UPDATE)
-    EVENT_HANDLER(BT_HCI_EVT_LE_PHY_UPDATE_COMPLETE,
-                  le_phy_update_complete,
-                  sizeof(struct bt_hci_evt_le_phy_update_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_PHY_UPDATE_COMPLETE, le_phy_update_complete, sizeof(struct bt_hci_evt_le_phy_update_complete)),
 #endif /* CONFIG_BT_PHY_UPDATE */
 #endif /* CONFIG_BT_CONN */
 #if defined(CONFIG_BT_SMP)
-    EVENT_HANDLER(BT_HCI_EVT_LE_LTK_REQUEST, le_ltk_request,
-                  sizeof(struct bt_hci_evt_le_ltk_request)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_LTK_REQUEST, le_ltk_request, sizeof(struct bt_hci_evt_le_ltk_request)),
 #endif /* CONFIG_BT_SMP */
 #if defined(CONFIG_BT_ECC)
-    EVENT_HANDLER(BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE, le_pkey_complete,
-                  sizeof(struct bt_hci_evt_le_p256_public_key_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE, le_dhkey_complete,
-                  sizeof(struct bt_hci_evt_le_generate_dhkey_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE, le_pkey_complete, sizeof(struct bt_hci_evt_le_p256_public_key_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE, le_dhkey_complete, sizeof(struct bt_hci_evt_le_generate_dhkey_complete)),
 #endif /* CONFIG_BT_SMP */
 };
 
-static void hci_le_meta_event(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_meta_event *evt;
+static void hci_le_meta_event(struct net_buf *buf) {
+  struct bt_hci_evt_le_meta_event *evt;
 
-    evt = net_buf_pull_mem(buf, sizeof(*evt));
+  evt = net_buf_pull_mem(buf, sizeof(*evt));
 
-    BT_DBG("subevent 0x%02x", evt->subevent);
+  BT_DBG("subevent 0x%02x", evt->subevent);
 
-    handle_event(evt->subevent, buf, meta_events, ARRAY_SIZE(meta_events));
+  handle_event(evt->subevent, buf, meta_events, ARRAY_SIZE(meta_events));
 }
 
 static const struct event_handler normal_events[] = {
-    EVENT_HANDLER(BT_HCI_EVT_VENDOR, hci_vendor_event,
-                  sizeof(struct bt_hci_evt_vs)),
-    EVENT_HANDLER(BT_HCI_EVT_LE_META_EVENT, hci_le_meta_event,
-                  sizeof(struct bt_hci_evt_le_meta_event)),
+    EVENT_HANDLER(BT_HCI_EVT_VENDOR, hci_vendor_event, sizeof(struct bt_hci_evt_vs)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_META_EVENT, hci_le_meta_event, sizeof(struct bt_hci_evt_le_meta_event)),
 #if defined(CONFIG_BT_BREDR)
-    EVENT_HANDLER(BT_HCI_EVT_CONN_REQUEST, conn_req,
-                  sizeof(struct bt_hci_evt_conn_request)),
-    EVENT_HANDLER(BT_HCI_EVT_CONN_COMPLETE, conn_complete,
-                  sizeof(struct bt_hci_evt_conn_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_PIN_CODE_REQ, pin_code_req,
-                  sizeof(struct bt_hci_evt_pin_code_req)),
-    EVENT_HANDLER(BT_HCI_EVT_LINK_KEY_NOTIFY, link_key_notify,
-                  sizeof(struct bt_hci_evt_link_key_notify)),
-    EVENT_HANDLER(BT_HCI_EVT_LINK_KEY_REQ, link_key_req,
-                  sizeof(struct bt_hci_evt_link_key_req)),
-    EVENT_HANDLER(BT_HCI_EVT_IO_CAPA_RESP, io_capa_resp,
-                  sizeof(struct bt_hci_evt_io_capa_resp)),
-    EVENT_HANDLER(BT_HCI_EVT_IO_CAPA_REQ, io_capa_req,
-                  sizeof(struct bt_hci_evt_io_capa_req)),
-    EVENT_HANDLER(BT_HCI_EVT_SSP_COMPLETE, ssp_complete,
-                  sizeof(struct bt_hci_evt_ssp_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_USER_CONFIRM_REQ, user_confirm_req,
-                  sizeof(struct bt_hci_evt_user_confirm_req)),
-    EVENT_HANDLER(BT_HCI_EVT_USER_PASSKEY_NOTIFY, user_passkey_notify,
-                  sizeof(struct bt_hci_evt_user_passkey_notify)),
-    EVENT_HANDLER(BT_HCI_EVT_USER_PASSKEY_REQ, user_passkey_req,
-                  sizeof(struct bt_hci_evt_user_passkey_req)),
-    EVENT_HANDLER(BT_HCI_EVT_INQUIRY_COMPLETE, inquiry_complete,
-                  sizeof(struct bt_hci_evt_inquiry_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_INQUIRY_RESULT_WITH_RSSI,
-                  inquiry_result_with_rssi,
-                  sizeof(struct bt_hci_evt_inquiry_result_with_rssi)),
-    EVENT_HANDLER(BT_HCI_EVT_EXTENDED_INQUIRY_RESULT,
-                  extended_inquiry_result,
-                  sizeof(struct bt_hci_evt_extended_inquiry_result)),
-    EVENT_HANDLER(BT_HCI_EVT_REMOTE_NAME_REQ_COMPLETE,
-                  remote_name_request_complete,
-                  sizeof(struct bt_hci_evt_remote_name_req_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_AUTH_COMPLETE, auth_complete,
-                  sizeof(struct bt_hci_evt_auth_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_REMOTE_FEATURES,
-                  read_remote_features_complete,
-                  sizeof(struct bt_hci_evt_remote_features)),
-    EVENT_HANDLER(BT_HCI_EVT_REMOTE_EXT_FEATURES,
-                  read_remote_ext_features_complete,
-                  sizeof(struct bt_hci_evt_remote_ext_features)),
-    EVENT_HANDLER(BT_HCI_EVT_ROLE_CHANGE, role_change,
-                  sizeof(struct bt_hci_evt_role_change)),
-    EVENT_HANDLER(BT_HCI_EVT_SYNC_CONN_COMPLETE, synchronous_conn_complete,
-                  sizeof(struct bt_hci_evt_sync_conn_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_CONN_REQUEST, conn_req, sizeof(struct bt_hci_evt_conn_request)),
+    EVENT_HANDLER(BT_HCI_EVT_CONN_COMPLETE, conn_complete, sizeof(struct bt_hci_evt_conn_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_PIN_CODE_REQ, pin_code_req, sizeof(struct bt_hci_evt_pin_code_req)),
+    EVENT_HANDLER(BT_HCI_EVT_LINK_KEY_NOTIFY, link_key_notify, sizeof(struct bt_hci_evt_link_key_notify)),
+    EVENT_HANDLER(BT_HCI_EVT_LINK_KEY_REQ, link_key_req, sizeof(struct bt_hci_evt_link_key_req)),
+    EVENT_HANDLER(BT_HCI_EVT_IO_CAPA_RESP, io_capa_resp, sizeof(struct bt_hci_evt_io_capa_resp)),
+    EVENT_HANDLER(BT_HCI_EVT_IO_CAPA_REQ, io_capa_req, sizeof(struct bt_hci_evt_io_capa_req)),
+    EVENT_HANDLER(BT_HCI_EVT_SSP_COMPLETE, ssp_complete, sizeof(struct bt_hci_evt_ssp_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_USER_CONFIRM_REQ, user_confirm_req, sizeof(struct bt_hci_evt_user_confirm_req)),
+    EVENT_HANDLER(BT_HCI_EVT_USER_PASSKEY_NOTIFY, user_passkey_notify, sizeof(struct bt_hci_evt_user_passkey_notify)),
+    EVENT_HANDLER(BT_HCI_EVT_USER_PASSKEY_REQ, user_passkey_req, sizeof(struct bt_hci_evt_user_passkey_req)),
+    EVENT_HANDLER(BT_HCI_EVT_INQUIRY_COMPLETE, inquiry_complete, sizeof(struct bt_hci_evt_inquiry_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_INQUIRY_RESULT_WITH_RSSI, inquiry_result_with_rssi, sizeof(struct bt_hci_evt_inquiry_result_with_rssi)),
+    EVENT_HANDLER(BT_HCI_EVT_EXTENDED_INQUIRY_RESULT, extended_inquiry_result, sizeof(struct bt_hci_evt_extended_inquiry_result)),
+    EVENT_HANDLER(BT_HCI_EVT_REMOTE_NAME_REQ_COMPLETE, remote_name_request_complete, sizeof(struct bt_hci_evt_remote_name_req_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_AUTH_COMPLETE, auth_complete, sizeof(struct bt_hci_evt_auth_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_REMOTE_FEATURES, read_remote_features_complete, sizeof(struct bt_hci_evt_remote_features)),
+    EVENT_HANDLER(BT_HCI_EVT_REMOTE_EXT_FEATURES, read_remote_ext_features_complete, sizeof(struct bt_hci_evt_remote_ext_features)),
+    EVENT_HANDLER(BT_HCI_EVT_ROLE_CHANGE, role_change, sizeof(struct bt_hci_evt_role_change)),
+    EVENT_HANDLER(BT_HCI_EVT_SYNC_CONN_COMPLETE, synchronous_conn_complete, sizeof(struct bt_hci_evt_sync_conn_complete)),
 #endif /* CONFIG_BT_BREDR */
 #if defined(CONFIG_BT_CONN)
-    EVENT_HANDLER(BT_HCI_EVT_DISCONN_COMPLETE, hci_disconn_complete,
-                  sizeof(struct bt_hci_evt_disconn_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_DISCONN_COMPLETE, hci_disconn_complete, sizeof(struct bt_hci_evt_disconn_complete)),
 #endif /* CONFIG_BT_CONN */
 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
-    EVENT_HANDLER(BT_HCI_EVT_ENCRYPT_CHANGE, hci_encrypt_change,
-                  sizeof(struct bt_hci_evt_encrypt_change)),
-    EVENT_HANDLER(BT_HCI_EVT_ENCRYPT_KEY_REFRESH_COMPLETE,
-                  hci_encrypt_key_refresh_complete,
-                  sizeof(struct bt_hci_evt_encrypt_key_refresh_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_ENCRYPT_CHANGE, hci_encrypt_change, sizeof(struct bt_hci_evt_encrypt_change)),
+    EVENT_HANDLER(BT_HCI_EVT_ENCRYPT_KEY_REFRESH_COMPLETE, hci_encrypt_key_refresh_complete, sizeof(struct bt_hci_evt_encrypt_key_refresh_complete)),
 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
 };
 
-static void hci_event(struct net_buf *buf)
-{
-    struct bt_hci_evt_hdr *hdr;
+static void hci_event(struct net_buf *buf) {
+  struct bt_hci_evt_hdr *hdr;
 
-    BT_ASSERT(buf->len >= sizeof(*hdr));
+  BT_ASSERT(buf->len >= sizeof(*hdr));
 
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    BT_DBG("event 0x%02x", hdr->evt);
-    BT_ASSERT(!bt_hci_evt_is_prio(hdr->evt));
+  hdr = net_buf_pull_mem(buf, sizeof(*hdr));
+  BT_DBG("event 0x%02x", hdr->evt);
+  BT_ASSERT(!bt_hci_evt_is_prio(hdr->evt));
 
-    handle_event(hdr->evt, buf, normal_events, ARRAY_SIZE(normal_events));
+  handle_event(hdr->evt, buf, normal_events, ARRAY_SIZE(normal_events));
 
-    net_buf_unref(buf);
+  net_buf_unref(buf);
 }
 
-static void send_cmd(void)
-{
-    struct net_buf *buf;
-    int err;
+static void send_cmd(void) {
+  struct net_buf *buf;
+  int             err;
 
-    /* Get next command */
-    BT_DBG("calling net_buf_get");
-    buf = net_buf_get(&bt_dev.cmd_tx_queue, K_NO_WAIT);
-    BT_ASSERT(buf);
+  /* Get next command */
+  BT_DBG("calling net_buf_get");
+  buf = net_buf_get(&bt_dev.cmd_tx_queue, K_NO_WAIT);
+  BT_ASSERT(buf);
 
-    /* Wait until ncmd > 0 */
-    BT_DBG("calling sem_take_wait");
-    k_sem_take(&bt_dev.ncmd_sem, K_FOREVER);
+  /* Wait until ncmd > 0 */
+  BT_DBG("calling sem_take_wait");
+  k_sem_take(&bt_dev.ncmd_sem, K_FOREVER);
 
-    /* Clear out any existing sent command */
-    if (bt_dev.sent_cmd) {
-        BT_ERR("Uncleared pending sent_cmd");
-        net_buf_unref(bt_dev.sent_cmd);
-        bt_dev.sent_cmd = NULL;
-    }
+  /* Clear out any existing sent command */
+  if (bt_dev.sent_cmd) {
+    BT_ERR("Uncleared pending sent_cmd");
+    net_buf_unref(bt_dev.sent_cmd);
+    bt_dev.sent_cmd = NULL;
+  }
 
-    bt_dev.sent_cmd = net_buf_ref(buf);
+  bt_dev.sent_cmd = net_buf_ref(buf);
 
-    BT_DBG("Sending command 0x%04x (buf %p) to driver",
-           cmd(buf)->opcode, buf);
+  BT_DBG("Sending command 0x%04x (buf %p) to driver", cmd(buf)->opcode, buf);
 
-    err = bt_send(buf);
-    if (err) {
-        BT_ERR("Unable to send to driver (err %d)", err);
-        k_sem_give(&bt_dev.ncmd_sem);
-        hci_cmd_done(cmd(buf)->opcode, BT_HCI_ERR_UNSPECIFIED, buf);
-        net_buf_unref(bt_dev.sent_cmd);
-        bt_dev.sent_cmd = NULL;
-        net_buf_unref(buf);
-    }
+  err = bt_send(buf);
+  if (err) {
+    BT_ERR("Unable to send to driver (err %d)", err);
+    k_sem_give(&bt_dev.ncmd_sem);
+    hci_cmd_done(cmd(buf)->opcode, BT_HCI_ERR_UNSPECIFIED, buf);
+    net_buf_unref(bt_dev.sent_cmd);
+    bt_dev.sent_cmd = NULL;
+    net_buf_unref(buf);
+  }
 }
 
-static void process_events(struct k_poll_event *ev, int count)
-{
-    BT_DBG("count %d", count);
-
-    for (; count; ev++, count--) {
-        BT_DBG("ev->state %u", ev->state);
-
-        switch (ev->state) {
-            case K_POLL_STATE_SIGNALED:
-                break;
-            case K_POLL_STATE_FIFO_DATA_AVAILABLE:
-                if (ev->tag == BT_EVENT_CMD_TX) {
-                    send_cmd();
-                } else if (IS_ENABLED(CONFIG_BT_CONN)) {
-                    struct bt_conn *conn;
-
-                    if (ev->tag == BT_EVENT_CONN_TX_QUEUE) {
-                        conn = CONTAINER_OF(ev->fifo,
-                                            struct bt_conn,
-                                            tx_queue);
-                        bt_conn_process_tx(conn);
-                    }
-                }
-                break;
-            case K_POLL_STATE_NOT_READY:
-                break;
-            default:
-                BT_WARN("Unexpected k_poll event state %u", ev->state);
-                break;
+static void process_events(struct k_poll_event *ev, int count) {
+  BT_DBG("count %d", count);
+
+  for (; count; ev++, count--) {
+    BT_DBG("ev->state %u", ev->state);
+
+    switch (ev->state) {
+    case K_POLL_STATE_SIGNALED:
+      break;
+    case K_POLL_STATE_FIFO_DATA_AVAILABLE:
+      if (ev->tag == BT_EVENT_CMD_TX) {
+        send_cmd();
+      } else if (IS_ENABLED(CONFIG_BT_CONN)) {
+        struct bt_conn *conn;
+
+        if (ev->tag == BT_EVENT_CONN_TX_QUEUE) {
+          conn = CONTAINER_OF(ev->fifo, struct bt_conn, tx_queue);
+          bt_conn_process_tx(conn);
         }
+      }
+      break;
+    case K_POLL_STATE_NOT_READY:
+      break;
+    default:
+      BT_WARN("Unexpected k_poll event state %u", ev->state);
+      break;
     }
+  }
 }
 
 #if defined(CONFIG_BT_CONN)
@@ -4287,27 +4011,23 @@ static void process_events(struct k_poll_event *ev, int count)
 
 #if defined(BFLB_BLE)
 #if (BFLB_BLE_CO_THREAD)
-void co_tx_thread()
-{
-    static struct k_poll_event events[EV_COUNT] = {
-        K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE,
-                                        K_POLL_MODE_NOTIFY_ONLY,
-                                        &bt_dev.cmd_tx_queue,
-                                        BT_EVENT_CMD_TX),
-    };
-
-    if (k_sem_count_get(&g_poll_sem) > 0) {
-        int ev_count, err;
-        events[0].state = K_POLL_STATE_NOT_READY;
-        ev_count = 1;
+void co_tx_thread() {
+  static struct k_poll_event events[EV_COUNT] = {
+      K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &bt_dev.cmd_tx_queue, BT_EVENT_CMD_TX),
+  };
 
-        if (IS_ENABLED(CONFIG_BT_CONN)) {
-            ev_count += bt_conn_prepare_events(&events[1]);
-        }
+  if (k_sem_count_get(&g_poll_sem) > 0) {
+    int ev_count, err;
+    events[0].state = K_POLL_STATE_NOT_READY;
+    ev_count        = 1;
 
-        err = k_poll(events, ev_count, K_NO_WAIT);
-        process_events(events, ev_count);
+    if (IS_ENABLED(CONFIG_BT_CONN)) {
+      ev_count += bt_conn_prepare_events(&events[1]);
     }
+
+    err = k_poll(events, ev_count, K_NO_WAIT);
+    process_events(events, ev_count);
+  }
 }
 #endif
 
@@ -4316,768 +4036,709 @@ static void hci_tx_thread(void *p1)
 static void hci_tx_thread(void *p1, void *p2, void *p3)
 #endif
 {
-    static struct k_poll_event events[EV_COUNT] = {
-        K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE,
-                                        K_POLL_MODE_NOTIFY_ONLY,
-                                        &bt_dev.cmd_tx_queue,
-                                        BT_EVENT_CMD_TX),
-    };
+  static struct k_poll_event events[EV_COUNT] = {
+      K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &bt_dev.cmd_tx_queue, BT_EVENT_CMD_TX),
+  };
 
-    BT_DBG("Started");
+  BT_DBG("Started");
 
-    while (1) {
-        int ev_count, err;
+  while (1) {
+    int ev_count, err;
 
-        events[0].state = K_POLL_STATE_NOT_READY;
-        ev_count = 1;
+    events[0].state = K_POLL_STATE_NOT_READY;
+    ev_count        = 1;
 
-        if (IS_ENABLED(CONFIG_BT_CONN)) {
-            ev_count += bt_conn_prepare_events(&events[1]);
-        }
+    if (IS_ENABLED(CONFIG_BT_CONN)) {
+      ev_count += bt_conn_prepare_events(&events[1]);
+    }
 
-        BT_DBG("Calling k_poll with %d events", ev_count);
+    BT_DBG("Calling k_poll with %d events", ev_count);
 
-        err = k_poll(events, ev_count, K_FOREVER);
-        BT_ASSERT(err == 0);
+    err = k_poll(events, ev_count, K_FOREVER);
+    BT_ASSERT(err == 0);
 
-        process_events(events, ev_count);
+    process_events(events, ev_count);
 
-        /* Make sure we don't hog the CPU if there's all the time
-		 * some ready events.
-		 */
-        k_yield();
-    }
+    /* Make sure we don't hog the CPU if there's all the time
+     * some ready events.
+     */
+    k_yield();
+  }
 }
 
-static void read_local_ver_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_read_local_version_info *rp = (void *)buf->data;
+static void read_local_ver_complete(struct net_buf *buf) {
+  struct bt_hci_rp_read_local_version_info *rp = (void *)buf->data;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    bt_dev.hci_version = rp->hci_version;
-    bt_dev.hci_revision = sys_le16_to_cpu(rp->hci_revision);
-    bt_dev.lmp_version = rp->lmp_version;
-    bt_dev.lmp_subversion = sys_le16_to_cpu(rp->lmp_subversion);
-    bt_dev.manufacturer = sys_le16_to_cpu(rp->manufacturer);
+  bt_dev.hci_version    = rp->hci_version;
+  bt_dev.hci_revision   = sys_le16_to_cpu(rp->hci_revision);
+  bt_dev.lmp_version    = rp->lmp_version;
+  bt_dev.lmp_subversion = sys_le16_to_cpu(rp->lmp_subversion);
+  bt_dev.manufacturer   = sys_le16_to_cpu(rp->manufacturer);
 }
 
-static void read_bdaddr_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_read_bd_addr *rp = (void *)buf->data;
+static void read_bdaddr_complete(struct net_buf *buf) {
+  struct bt_hci_rp_read_bd_addr *rp = (void *)buf->data;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    if (!bt_addr_cmp(&rp->bdaddr, BT_ADDR_ANY) ||
-        !bt_addr_cmp(&rp->bdaddr, BT_ADDR_NONE)) {
-        BT_DBG("Controller has no public address");
-        return;
-    }
+  if (!bt_addr_cmp(&rp->bdaddr, BT_ADDR_ANY) || !bt_addr_cmp(&rp->bdaddr, BT_ADDR_NONE)) {
+    BT_DBG("Controller has no public address");
+    return;
+  }
 
-    bt_addr_copy(&bt_dev.id_addr[0].a, &rp->bdaddr);
-    bt_dev.id_addr[0].type = BT_ADDR_LE_PUBLIC;
-    bt_dev.id_count = 1U;
+  bt_addr_copy(&bt_dev.id_addr[0].a, &rp->bdaddr);
+  bt_dev.id_addr[0].type = BT_ADDR_LE_PUBLIC;
+  bt_dev.id_count        = 1U;
 }
 
-static void read_le_features_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_le_read_local_features *rp = (void *)buf->data;
+static void read_le_features_complete(struct net_buf *buf) {
+  struct bt_hci_rp_le_read_local_features *rp = (void *)buf->data;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    memcpy(bt_dev.le.features, rp->features, sizeof(bt_dev.le.features));
+  memcpy(bt_dev.le.features, rp->features, sizeof(bt_dev.le.features));
 }
 
 #if defined(CONFIG_BT_BREDR)
-static void read_buffer_size_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_read_buffer_size *rp = (void *)buf->data;
-    u16_t pkts;
+static void read_buffer_size_complete(struct net_buf *buf) {
+  struct bt_hci_rp_read_buffer_size *rp = (void *)buf->data;
+  u16_t                              pkts;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    bt_dev.br.mtu = sys_le16_to_cpu(rp->acl_max_len);
-    pkts = sys_le16_to_cpu(rp->acl_max_num);
+  bt_dev.br.mtu = sys_le16_to_cpu(rp->acl_max_len);
+  pkts          = sys_le16_to_cpu(rp->acl_max_num);
 
-    BT_DBG("ACL BR/EDR buffers: pkts %u mtu %u", pkts, bt_dev.br.mtu);
+  BT_DBG("ACL BR/EDR buffers: pkts %u mtu %u", pkts, bt_dev.br.mtu);
 
-    k_sem_init(&bt_dev.br.pkts, pkts, pkts);
+  k_sem_init(&bt_dev.br.pkts, pkts, pkts);
 }
 #elif defined(CONFIG_BT_CONN)
-static void read_buffer_size_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_read_buffer_size *rp = (void *)buf->data;
-    u16_t pkts;
+static void read_buffer_size_complete(struct net_buf *buf) {
+  struct bt_hci_rp_read_buffer_size *rp = (void *)buf->data;
+  u16_t                              pkts;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    /* If LE-side has buffers we can ignore the BR/EDR values */
-    if (bt_dev.le.mtu) {
-        return;
-    }
+  /* If LE-side has buffers we can ignore the BR/EDR values */
+  if (bt_dev.le.mtu) {
+    return;
+  }
 
-    bt_dev.le.mtu = sys_le16_to_cpu(rp->acl_max_len);
-    pkts = sys_le16_to_cpu(rp->acl_max_num);
+  bt_dev.le.mtu = sys_le16_to_cpu(rp->acl_max_len);
+  pkts          = sys_le16_to_cpu(rp->acl_max_num);
 
-    BT_DBG("ACL BR/EDR buffers: pkts %u mtu %u", pkts, bt_dev.le.mtu);
+  BT_DBG("ACL BR/EDR buffers: pkts %u mtu %u", pkts, bt_dev.le.mtu);
 
-    k_sem_init(&bt_dev.le.pkts, pkts, pkts);
+  k_sem_init(&bt_dev.le.pkts, pkts, pkts);
 }
 #endif
 
 #if defined(CONFIG_BT_CONN)
-static void le_read_buffer_size_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_le_read_buffer_size *rp = (void *)buf->data;
+static void le_read_buffer_size_complete(struct net_buf *buf) {
+  struct bt_hci_rp_le_read_buffer_size *rp = (void *)buf->data;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    bt_dev.le.mtu = sys_le16_to_cpu(rp->le_max_len);
-    if (!bt_dev.le.mtu) {
-        return;
-    }
+  bt_dev.le.mtu = sys_le16_to_cpu(rp->le_max_len);
+  if (!bt_dev.le.mtu) {
+    return;
+  }
 
-    BT_DBG("ACL LE buffers: pkts %u mtu %u", rp->le_max_num, bt_dev.le.mtu);
+  BT_DBG("ACL LE buffers: pkts %u mtu %u", rp->le_max_num, bt_dev.le.mtu);
 
-    k_sem_init(&bt_dev.le.pkts, rp->le_max_num, rp->le_max_num);
+  k_sem_init(&bt_dev.le.pkts, rp->le_max_num, rp->le_max_num);
 }
 #endif
 
-static void read_supported_commands_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_read_supported_commands *rp = (void *)buf->data;
+static void read_supported_commands_complete(struct net_buf *buf) {
+  struct bt_hci_rp_read_supported_commands *rp = (void *)buf->data;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    memcpy(bt_dev.supported_commands, rp->commands,
-           sizeof(bt_dev.supported_commands));
+  memcpy(bt_dev.supported_commands, rp->commands, sizeof(bt_dev.supported_commands));
 
-    /*
-	 * Report "LE Read Local P-256 Public Key" and "LE Generate DH Key" as
-	 * supported if TinyCrypt ECC is used for emulation.
-	 */
-    if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) {
-        bt_dev.supported_commands[34] |= 0x02;
-        bt_dev.supported_commands[34] |= 0x04;
-    }
+  /*
+   * Report "LE Read Local P-256 Public Key" and "LE Generate DH Key" as
+   * supported if TinyCrypt ECC is used for emulation.
+   */
+  if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) {
+    bt_dev.supported_commands[34] |= 0x02;
+    bt_dev.supported_commands[34] |= 0x04;
+  }
 }
 
-static void read_local_features_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_read_local_features *rp = (void *)buf->data;
+static void read_local_features_complete(struct net_buf *buf) {
+  struct bt_hci_rp_read_local_features *rp = (void *)buf->data;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    memcpy(bt_dev.features[0], rp->features, sizeof(bt_dev.features[0]));
+  memcpy(bt_dev.features[0], rp->features, sizeof(bt_dev.features[0]));
 }
 
-static void le_read_supp_states_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_le_read_supp_states *rp = (void *)buf->data;
+static void le_read_supp_states_complete(struct net_buf *buf) {
+  struct bt_hci_rp_le_read_supp_states *rp = (void *)buf->data;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    bt_dev.le.states = sys_get_le64(rp->le_states);
+  bt_dev.le.states = sys_get_le64(rp->le_states);
 }
 
 #if defined(CONFIG_BT_SMP)
-static void le_read_resolving_list_size_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_le_read_rl_size *rp = (void *)buf->data;
+static void le_read_resolving_list_size_complete(struct net_buf *buf) {
+  struct bt_hci_rp_le_read_rl_size *rp = (void *)buf->data;
 
-    BT_DBG("Resolving List size %u", rp->rl_size);
+  BT_DBG("Resolving List size %u", rp->rl_size);
 
-    bt_dev.le.rl_size = rp->rl_size;
+  bt_dev.le.rl_size = rp->rl_size;
 }
 #endif /* defined(CONFIG_BT_SMP) */
 
 #if defined(CONFIG_BT_WHITELIST)
-static void le_read_wl_size_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_le_read_wl_size *rp =
-        (struct bt_hci_rp_le_read_wl_size *)buf->data;
+static void le_read_wl_size_complete(struct net_buf *buf) {
+  struct bt_hci_rp_le_read_wl_size *rp = (struct bt_hci_rp_le_read_wl_size *)buf->data;
 
-    BT_DBG("Whitelist size %u", rp->wl_size);
+  BT_DBG("Whitelist size %u", rp->wl_size);
 
-    bt_dev.le.wl_size = rp->wl_size;
+  bt_dev.le.wl_size = rp->wl_size;
 }
 #endif
 
-static int common_init(void)
-{
-    struct net_buf *rsp;
-    int err;
-
-    if (!(bt_dev.drv->quirks & BT_QUIRK_NO_RESET)) {
-        /* Send HCI_RESET */
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_RESET, NULL, &rsp);
-        if (err) {
-            return err;
-        }
-        hci_reset_complete(rsp);
-        net_buf_unref(rsp);
-    }
+static int common_init(void) {
+  struct net_buf *rsp;
+  int             err;
 
-    /* Read Local Supported Features */
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_FEATURES, NULL, &rsp);
+  if (!(bt_dev.drv->quirks & BT_QUIRK_NO_RESET)) {
+    /* Send HCI_RESET */
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_RESET, NULL, &rsp);
     if (err) {
-        return err;
+      return err;
     }
-    read_local_features_complete(rsp);
+    hci_reset_complete(rsp);
     net_buf_unref(rsp);
+  }
 
-    /* Read Local Version Information */
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_VERSION_INFO, NULL,
-                               &rsp);
-    if (err) {
-        return err;
-    }
-    read_local_ver_complete(rsp);
-    net_buf_unref(rsp);
+  /* Read Local Supported Features */
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_FEATURES, NULL, &rsp);
+  if (err) {
+    return err;
+  }
+  read_local_features_complete(rsp);
+  net_buf_unref(rsp);
 
-    /* Read Bluetooth Address */
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR)) {
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BD_ADDR, NULL, &rsp);
-        if (err) {
-            return err;
-        }
-        read_bdaddr_complete(rsp);
-        net_buf_unref(rsp);
-    }
+  /* Read Local Version Information */
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_VERSION_INFO, NULL, &rsp);
+  if (err) {
+    return err;
+  }
+  read_local_ver_complete(rsp);
+  net_buf_unref(rsp);
 
-    /* Read Local Supported Commands */
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_SUPPORTED_COMMANDS, NULL,
-                               &rsp);
+  /* Read Bluetooth Address */
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR)) {
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BD_ADDR, NULL, &rsp);
     if (err) {
-        return err;
+      return err;
     }
-    read_supported_commands_complete(rsp);
+    read_bdaddr_complete(rsp);
     net_buf_unref(rsp);
+  }
 
-    if (IS_ENABLED(CONFIG_BT_HOST_CRYPTO)) {
-        /* Initialize the PRNG so that it is safe to use it later
-		 * on in the initialization process.
-		 */
-        err = prng_init();
-        if (err) {
-            return err;
-        }
-    }
+  /* Read Local Supported Commands */
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_SUPPORTED_COMMANDS, NULL, &rsp);
+  if (err) {
+    return err;
+  }
+  read_supported_commands_complete(rsp);
+  net_buf_unref(rsp);
 
-#if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-    err = set_flow_control();
+  if (IS_ENABLED(CONFIG_BT_HOST_CRYPTO)) {
+    /* Initialize the PRNG so that it is safe to use it later
+     * on in the initialization process.
+     */
+    err = prng_init();
     if (err) {
-        return err;
+      return err;
     }
+  }
+
+#if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
+  err = set_flow_control();
+  if (err) {
+    return err;
+  }
 #endif /* CONFIG_BT_HCI_ACL_FLOW_CONTROL */
 
-    return 0;
+  return 0;
 }
 
-static int le_set_event_mask(void)
-{
-    struct bt_hci_cp_le_set_event_mask *cp_mask;
-    struct net_buf *buf;
-    u64_t mask = 0U;
-
-    /* Set LE event mask */
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EVENT_MASK, sizeof(*cp_mask));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+static int le_set_event_mask(void) {
+  struct bt_hci_cp_le_set_event_mask *cp_mask;
+  struct net_buf                     *buf;
+  u64_t                               mask = 0U;
 
-    cp_mask = net_buf_add(buf, sizeof(*cp_mask));
+  /* Set LE event mask */
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EVENT_MASK, sizeof(*cp_mask));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    mask |= BT_EVT_MASK_LE_ADVERTISING_REPORT;
-
-    if (IS_ENABLED(CONFIG_BT_CONN)) {
-        if (IS_ENABLED(CONFIG_BT_SMP) &&
-            BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
-            mask |= BT_EVT_MASK_LE_ENH_CONN_COMPLETE;
-        } else {
-            mask |= BT_EVT_MASK_LE_CONN_COMPLETE;
-        }
+  cp_mask = net_buf_add(buf, sizeof(*cp_mask));
 
-        mask |= BT_EVT_MASK_LE_CONN_UPDATE_COMPLETE;
-        mask |= BT_EVT_MASK_LE_REMOTE_FEAT_COMPLETE;
+  mask |= BT_EVT_MASK_LE_ADVERTISING_REPORT;
 
-        if (BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features)) {
-            mask |= BT_EVT_MASK_LE_CONN_PARAM_REQ;
-        }
+  if (IS_ENABLED(CONFIG_BT_CONN)) {
+    if (IS_ENABLED(CONFIG_BT_SMP) && BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+      mask |= BT_EVT_MASK_LE_ENH_CONN_COMPLETE;
+    } else {
+      mask |= BT_EVT_MASK_LE_CONN_COMPLETE;
+    }
 
-        if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) &&
-            BT_FEAT_LE_DLE(bt_dev.le.features)) {
-            mask |= BT_EVT_MASK_LE_DATA_LEN_CHANGE;
-        }
+    mask |= BT_EVT_MASK_LE_CONN_UPDATE_COMPLETE;
+    mask |= BT_EVT_MASK_LE_REMOTE_FEAT_COMPLETE;
 
-        if (IS_ENABLED(CONFIG_BT_PHY_UPDATE) &&
-            (BT_FEAT_LE_PHY_2M(bt_dev.le.features) ||
-             BT_FEAT_LE_PHY_CODED(bt_dev.le.features))) {
-            mask |= BT_EVT_MASK_LE_PHY_UPDATE_COMPLETE;
-        }
+    if (BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features)) {
+      mask |= BT_EVT_MASK_LE_CONN_PARAM_REQ;
     }
 
-    if (IS_ENABLED(CONFIG_BT_SMP) &&
-        BT_FEAT_LE_ENCR(bt_dev.le.features)) {
-        mask |= BT_EVT_MASK_LE_LTK_REQUEST;
+    if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && BT_FEAT_LE_DLE(bt_dev.le.features)) {
+      mask |= BT_EVT_MASK_LE_DATA_LEN_CHANGE;
     }
 
-    /*
-	 * If "LE Read Local P-256 Public Key" and "LE Generate DH Key" are
-	 * supported we need to enable events generated by those commands.
-	 */
-    if (IS_ENABLED(CONFIG_BT_ECC) &&
-        (BT_CMD_TEST(bt_dev.supported_commands, 34, 1)) &&
-        (BT_CMD_TEST(bt_dev.supported_commands, 34, 2))) {
-        mask |= BT_EVT_MASK_LE_P256_PUBLIC_KEY_COMPLETE;
-        mask |= BT_EVT_MASK_LE_GENERATE_DHKEY_COMPLETE;
+    if (IS_ENABLED(CONFIG_BT_PHY_UPDATE) && (BT_FEAT_LE_PHY_2M(bt_dev.le.features) || BT_FEAT_LE_PHY_CODED(bt_dev.le.features))) {
+      mask |= BT_EVT_MASK_LE_PHY_UPDATE_COMPLETE;
     }
+  }
+
+  if (IS_ENABLED(CONFIG_BT_SMP) && BT_FEAT_LE_ENCR(bt_dev.le.features)) {
+    mask |= BT_EVT_MASK_LE_LTK_REQUEST;
+  }
 
-    sys_put_le64(mask, cp_mask->events);
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EVENT_MASK, buf, NULL);
+  /*
+   * If "LE Read Local P-256 Public Key" and "LE Generate DH Key" are
+   * supported we need to enable events generated by those commands.
+   */
+  if (IS_ENABLED(CONFIG_BT_ECC) && (BT_CMD_TEST(bt_dev.supported_commands, 34, 1)) && (BT_CMD_TEST(bt_dev.supported_commands, 34, 2))) {
+    mask |= BT_EVT_MASK_LE_P256_PUBLIC_KEY_COMPLETE;
+    mask |= BT_EVT_MASK_LE_GENERATE_DHKEY_COMPLETE;
+  }
+
+  sys_put_le64(mask, cp_mask->events);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EVENT_MASK, buf, NULL);
 }
 
-static int le_init(void)
-{
-    struct bt_hci_cp_write_le_host_supp *cp_le;
-    struct net_buf *buf, *rsp;
-    int err;
+static int le_init(void) {
+  struct bt_hci_cp_write_le_host_supp *cp_le;
+  struct net_buf                      *buf, *rsp;
+  int                                  err;
 
-    /* For now we only support LE capable controllers */
-    if (!BT_FEAT_LE(bt_dev.features)) {
-        BT_ERR("Non-LE capable controller detected!");
-        return -ENODEV;
-    }
+  /* For now we only support LE capable controllers */
+  if (!BT_FEAT_LE(bt_dev.features)) {
+    BT_ERR("Non-LE capable controller detected!");
+    return -ENODEV;
+  }
 
-    /* Read Low Energy Supported Features */
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_LOCAL_FEATURES, NULL,
-                               &rsp);
-    if (err) {
-        return err;
-    }
-    read_le_features_complete(rsp);
-    net_buf_unref(rsp);
+  /* Read Low Energy Supported Features */
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_LOCAL_FEATURES, NULL, &rsp);
+  if (err) {
+    return err;
+  }
+  read_le_features_complete(rsp);
+  net_buf_unref(rsp);
 
 #if defined(CONFIG_BT_CONN)
-    /* Read LE Buffer Size */
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_BUFFER_SIZE,
-                               NULL, &rsp);
-    if (err) {
-        return err;
-    }
-    le_read_buffer_size_complete(rsp);
-    net_buf_unref(rsp);
+  /* Read LE Buffer Size */
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_BUFFER_SIZE, NULL, &rsp);
+  if (err) {
+    return err;
+  }
+  le_read_buffer_size_complete(rsp);
+  net_buf_unref(rsp);
 #endif
 
-    if (BT_FEAT_BREDR(bt_dev.features)) {
-        buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP,
-                                sizeof(*cp_le));
-        if (!buf) {
-            return -ENOBUFS;
-        }
+  if (BT_FEAT_BREDR(bt_dev.features)) {
+    buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP, sizeof(*cp_le));
+    if (!buf) {
+      return -ENOBUFS;
+    }
 
-        cp_le = net_buf_add(buf, sizeof(*cp_le));
+    cp_le = net_buf_add(buf, sizeof(*cp_le));
 
-        /* Explicitly enable LE for dual-mode controllers */
-        cp_le->le = 0x01;
-        cp_le->simul = 0x00;
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP, buf,
-                                   NULL);
-        if (err) {
-            return err;
-        }
+    /* Explicitly enable LE for dual-mode controllers */
+    cp_le->le    = 0x01;
+    cp_le->simul = 0x00;
+    err          = bt_hci_cmd_send_sync(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP, buf, NULL);
+    if (err) {
+      return err;
     }
+  }
 
-    /* Read LE Supported States */
-    if (BT_CMD_LE_STATES(bt_dev.supported_commands)) {
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_SUPP_STATES, NULL,
-                                   &rsp);
-        if (err) {
-            return err;
-        }
-        le_read_supp_states_complete(rsp);
-        net_buf_unref(rsp);
+  /* Read LE Supported States */
+  if (BT_CMD_LE_STATES(bt_dev.supported_commands)) {
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_SUPP_STATES, NULL, &rsp);
+    if (err) {
+      return err;
     }
+    le_read_supp_states_complete(rsp);
+    net_buf_unref(rsp);
+  }
 
-    if (IS_ENABLED(CONFIG_BT_CONN) &&
-        IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) &&
-        BT_FEAT_LE_DLE(bt_dev.le.features)) {
-        struct bt_hci_cp_le_write_default_data_len *cp;
-        struct bt_hci_rp_le_read_max_data_len *rp;
-        u16_t tx_octets, tx_time;
+  if (IS_ENABLED(CONFIG_BT_CONN) && IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && BT_FEAT_LE_DLE(bt_dev.le.features)) {
+    struct bt_hci_cp_le_write_default_data_len *cp;
+    struct bt_hci_rp_le_read_max_data_len      *rp;
+    u16_t                                       tx_octets, tx_time;
 
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_MAX_DATA_LEN, NULL,
-                                   &rsp);
-        if (err) {
-            return err;
-        }
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_MAX_DATA_LEN, NULL, &rsp);
+    if (err) {
+      return err;
+    }
 
-        rp = (void *)rsp->data;
-        tx_octets = sys_le16_to_cpu(rp->max_tx_octets);
-        tx_time = sys_le16_to_cpu(rp->max_tx_time);
-        net_buf_unref(rsp);
+    rp        = (void *)rsp->data;
+    tx_octets = sys_le16_to_cpu(rp->max_tx_octets);
+    tx_time   = sys_le16_to_cpu(rp->max_tx_time);
+    net_buf_unref(rsp);
 
-        buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN,
-                                sizeof(*cp));
-        if (!buf) {
-            return -ENOBUFS;
-        }
+    buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN, sizeof(*cp));
+    if (!buf) {
+      return -ENOBUFS;
+    }
 
-        cp = net_buf_add(buf, sizeof(*cp));
-        cp->max_tx_octets = sys_cpu_to_le16(tx_octets);
-        cp->max_tx_time = sys_cpu_to_le16(tx_time);
+    cp                = net_buf_add(buf, sizeof(*cp));
+    cp->max_tx_octets = sys_cpu_to_le16(tx_octets);
+    cp->max_tx_time   = sys_cpu_to_le16(tx_time);
 
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN,
-                                   buf, NULL);
-        if (err) {
-            return err;
-        }
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN, buf, NULL);
+    if (err) {
+      return err;
     }
+  }
 
 #if defined(CONFIG_BT_SMP)
-    if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+  if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
 #if defined(CONFIG_BT_PRIVACY)
-        struct bt_hci_cp_le_set_rpa_timeout *cp;
+    struct bt_hci_cp_le_set_rpa_timeout *cp;
 
-        buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RPA_TIMEOUT,
-                                sizeof(*cp));
-        if (!buf) {
-            return -ENOBUFS;
-        }
+    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RPA_TIMEOUT, sizeof(*cp));
+    if (!buf) {
+      return -ENOBUFS;
+    }
 
-        cp = net_buf_add(buf, sizeof(*cp));
-        cp->rpa_timeout = sys_cpu_to_le16(CONFIG_BT_RPA_TIMEOUT);
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RPA_TIMEOUT, buf,
-                                   NULL);
-        if (err) {
-            return err;
-        }
+    cp              = net_buf_add(buf, sizeof(*cp));
+    cp->rpa_timeout = sys_cpu_to_le16(CONFIG_BT_RPA_TIMEOUT);
+    err             = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RPA_TIMEOUT, buf, NULL);
+    if (err) {
+      return err;
+    }
 #endif /* defined(CONFIG_BT_PRIVACY) */
 
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_RL_SIZE, NULL,
-                                   &rsp);
-        if (err) {
-            return err;
-        }
-        le_read_resolving_list_size_complete(rsp);
-        net_buf_unref(rsp);
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_RL_SIZE, NULL, &rsp);
+    if (err) {
+      return err;
     }
+    le_read_resolving_list_size_complete(rsp);
+    net_buf_unref(rsp);
+  }
 #endif
 
 #if defined(CONFIG_BT_WHITELIST)
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_WL_SIZE, NULL,
-                               &rsp);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_WL_SIZE, NULL, &rsp);
+  if (err) {
+    return err;
+  }
 
-    le_read_wl_size_complete(rsp);
-    net_buf_unref(rsp);
+  le_read_wl_size_complete(rsp);
+  net_buf_unref(rsp);
 #endif /* defined(CONFIG_BT_WHITELIST) */
 
-    return le_set_event_mask();
+  return le_set_event_mask();
 }
 
 #if defined(CONFIG_BT_BREDR)
-static int read_ext_features(void)
-{
-    int i;
-
-    /* Read Local Supported Extended Features */
-    for (i = 1; i < LMP_FEAT_PAGES_COUNT; i++) {
-        struct bt_hci_cp_read_local_ext_features *cp;
-        struct bt_hci_rp_read_local_ext_features *rp;
-        struct net_buf *buf, *rsp;
-        int err;
-
-        buf = bt_hci_cmd_create(BT_HCI_OP_READ_LOCAL_EXT_FEATURES,
-                                sizeof(*cp));
-        if (!buf) {
-            return -ENOBUFS;
-        }
-
-        cp = net_buf_add(buf, sizeof(*cp));
-        cp->page = i;
-
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_EXT_FEATURES,
-                                   buf, &rsp);
-        if (err) {
-            return err;
-        }
-
-        rp = (void *)rsp->data;
-
-        memcpy(&bt_dev.features[i], rp->ext_features,
-               sizeof(bt_dev.features[i]));
-
-        if (rp->max_page <= i) {
-            net_buf_unref(rsp);
-            break;
-        }
+static int read_ext_features(void) {
+  int i;
 
-        net_buf_unref(rsp);
-    }
-
-    return 0;
-}
+  /* Read Local Supported Extended Features */
+  for (i = 1; i < LMP_FEAT_PAGES_COUNT; i++) {
+    struct bt_hci_cp_read_local_ext_features *cp;
+    struct bt_hci_rp_read_local_ext_features *rp;
+    struct net_buf                           *buf, *rsp;
+    int                                       err;
 
-void device_supported_pkt_type(void)
-{
-    /* Device supported features and sco packet types */
-    if (BT_FEAT_HV2_PKT(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_HV2);
+    buf = bt_hci_cmd_create(BT_HCI_OP_READ_LOCAL_EXT_FEATURES, sizeof(*cp));
+    if (!buf) {
+      return -ENOBUFS;
     }
 
-    if (BT_FEAT_HV3_PKT(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_HV3);
-    }
+    cp       = net_buf_add(buf, sizeof(*cp));
+    cp->page = i;
 
-    if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV3);
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_EXT_FEATURES, buf, &rsp);
+    if (err) {
+      return err;
     }
 
-    if (BT_FEAT_EV4_PKT(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV4);
-    }
+    rp = (void *)rsp->data;
 
-    if (BT_FEAT_EV5_PKT(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV5);
-    }
+    memcpy(&bt_dev.features[i], rp->ext_features, sizeof(bt_dev.features[i]));
 
-    if (BT_FEAT_2EV3_PKT(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_2EV3);
+    if (rp->max_page <= i) {
+      net_buf_unref(rsp);
+      break;
     }
 
-    if (BT_FEAT_3EV3_PKT(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_3EV3);
-    }
+    net_buf_unref(rsp);
+  }
 
-    if (BT_FEAT_3SLOT_PKT(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_2EV5 |
-                                    HCI_PKT_TYPE_ESCO_3EV5);
-    }
+  return 0;
 }
 
-static int br_init(void)
-{
-    struct net_buf *buf;
-    struct bt_hci_cp_write_ssp_mode *ssp_cp;
-    struct bt_hci_cp_write_inquiry_mode *inq_cp;
-    struct bt_hci_write_local_name *name_cp;
-    int err;
-
-    /* Read extended local features */
-    if (BT_FEAT_EXT_FEATURES(bt_dev.features)) {
-        err = read_ext_features();
-        if (err) {
-            return err;
-        }
-    }
-
-    /* Add local supported packet types to bt_dev */
-    device_supported_pkt_type();
+void device_supported_pkt_type(void) {
+  /* Device supported features and sco packet types */
+  if (BT_FEAT_HV2_PKT(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_HV2);
+  }
 
-    /* Get BR/EDR buffer size */
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BUFFER_SIZE, NULL, &buf);
-    if (err) {
-        return err;
-    }
+  if (BT_FEAT_HV3_PKT(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_HV3);
+  }
 
-    read_buffer_size_complete(buf);
-    net_buf_unref(buf);
+  if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV3);
+  }
 
-    /* Set SSP mode */
-    buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SSP_MODE, sizeof(*ssp_cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  if (BT_FEAT_EV4_PKT(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV4);
+  }
 
-    ssp_cp = net_buf_add(buf, sizeof(*ssp_cp));
-    ssp_cp->mode = 0x01;
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SSP_MODE, buf, NULL);
-    if (err) {
-        return err;
-    }
+  if (BT_FEAT_EV5_PKT(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV5);
+  }
 
-    /* Enable Inquiry results with RSSI or extended Inquiry */
-    buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_INQUIRY_MODE, sizeof(*inq_cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  if (BT_FEAT_2EV3_PKT(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_2EV3);
+  }
 
-    inq_cp = net_buf_add(buf, sizeof(*inq_cp));
-    inq_cp->mode = 0x02;
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_INQUIRY_MODE, buf, NULL);
-    if (err) {
-        return err;
-    }
+  if (BT_FEAT_3EV3_PKT(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_3EV3);
+  }
 
-    /* Set local name */
-    buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_LOCAL_NAME, sizeof(*name_cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  if (BT_FEAT_3SLOT_PKT(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_2EV5 | HCI_PKT_TYPE_ESCO_3EV5);
+  }
+}
 
-    name_cp = net_buf_add(buf, sizeof(*name_cp));
-    strncpy((char *)name_cp->local_name, CONFIG_BT_DEVICE_NAME,
-            sizeof(name_cp->local_name));
+static int br_init(void) {
+  struct net_buf                      *buf;
+  struct bt_hci_cp_write_ssp_mode     *ssp_cp;
+  struct bt_hci_cp_write_inquiry_mode *inq_cp;
+  struct bt_hci_write_local_name      *name_cp;
+  int                                  err;
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_LOCAL_NAME, buf, NULL);
+  /* Read extended local features */
+  if (BT_FEAT_EXT_FEATURES(bt_dev.features)) {
+    err = read_ext_features();
     if (err) {
-        return err;
-    }
-
-    /* Set page timeout*/
-    buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_PAGE_TIMEOUT, sizeof(u16_t));
-    if (!buf) {
-        return -ENOBUFS;
+      return err;
     }
+  }
 
-    net_buf_add_le16(buf, CONFIG_BT_PAGE_TIMEOUT);
-
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_PAGE_TIMEOUT, buf, NULL);
-    if (err) {
-        return err;
-    }
+  /* Add local supported packet types to bt_dev */
+  device_supported_pkt_type();
 
-    /* Enable BR/EDR SC if supported */
-    if (BT_FEAT_SC(bt_dev.features)) {
-        struct bt_hci_cp_write_sc_host_supp *sc_cp;
+  /* Get BR/EDR buffer size */
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BUFFER_SIZE, NULL, &buf);
+  if (err) {
+    return err;
+  }
 
-        buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SC_HOST_SUPP,
-                                sizeof(*sc_cp));
-        if (!buf) {
-            return -ENOBUFS;
-        }
+  read_buffer_size_complete(buf);
+  net_buf_unref(buf);
 
-        sc_cp = net_buf_add(buf, sizeof(*sc_cp));
-        sc_cp->sc_support = 0x01;
+  /* Set SSP mode */
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SSP_MODE, sizeof(*ssp_cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SC_HOST_SUPP, buf,
-                                   NULL);
-        if (err) {
-            return err;
-        }
-    }
+  ssp_cp       = net_buf_add(buf, sizeof(*ssp_cp));
+  ssp_cp->mode = 0x01;
+  err          = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SSP_MODE, buf, NULL);
+  if (err) {
+    return err;
+  }
+
+  /* Enable Inquiry results with RSSI or extended Inquiry */
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_INQUIRY_MODE, sizeof(*inq_cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
+
+  inq_cp       = net_buf_add(buf, sizeof(*inq_cp));
+  inq_cp->mode = 0x02;
+  err          = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_INQUIRY_MODE, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    return 0;
-}
-#else
-static int br_init(void)
-{
-#if defined(CONFIG_BT_CONN)
-    struct net_buf *rsp;
-    int err;
+  /* Set local name */
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_LOCAL_NAME, sizeof(*name_cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    if (bt_dev.le.mtu) {
-        return 0;
-    }
+  name_cp = net_buf_add(buf, sizeof(*name_cp));
+  strncpy((char *)name_cp->local_name, CONFIG_BT_DEVICE_NAME, sizeof(name_cp->local_name));
 
-    /* Use BR/EDR buffer size if LE reports zero buffers */
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BUFFER_SIZE, NULL, &rsp);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_LOCAL_NAME, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    read_buffer_size_complete(rsp);
-    net_buf_unref(rsp);
-#endif /* CONFIG_BT_CONN */
+  /* Set page timeout*/
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_PAGE_TIMEOUT, sizeof(u16_t));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    return 0;
-}
-#endif
+  net_buf_add_le16(buf, CONFIG_BT_PAGE_TIMEOUT);
 
-static int set_event_mask(void)
-{
-    struct bt_hci_cp_set_event_mask *ev;
-    struct net_buf *buf;
-    u64_t mask = 0U;
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_PAGE_TIMEOUT, buf, NULL);
+  if (err) {
+    return err;
+  }
+
+  /* Enable BR/EDR SC if supported */
+  if (BT_FEAT_SC(bt_dev.features)) {
+    struct bt_hci_cp_write_sc_host_supp *sc_cp;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_SET_EVENT_MASK, sizeof(*ev));
+    buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SC_HOST_SUPP, sizeof(*sc_cp));
     if (!buf) {
-        return -ENOBUFS;
+      return -ENOBUFS;
     }
 
-    ev = net_buf_add(buf, sizeof(*ev));
-
-    if (IS_ENABLED(CONFIG_BT_BREDR)) {
-        /* Since we require LE support, we can count on a
-		 * Bluetooth 4.0 feature set
-		 */
-        mask |= BT_EVT_MASK_INQUIRY_COMPLETE;
-        mask |= BT_EVT_MASK_CONN_COMPLETE;
-        mask |= BT_EVT_MASK_CONN_REQUEST;
-        mask |= BT_EVT_MASK_AUTH_COMPLETE;
-        mask |= BT_EVT_MASK_REMOTE_NAME_REQ_COMPLETE;
-        mask |= BT_EVT_MASK_REMOTE_FEATURES;
-        mask |= BT_EVT_MASK_ROLE_CHANGE;
-        mask |= BT_EVT_MASK_PIN_CODE_REQ;
-        mask |= BT_EVT_MASK_LINK_KEY_REQ;
-        mask |= BT_EVT_MASK_LINK_KEY_NOTIFY;
-        mask |= BT_EVT_MASK_INQUIRY_RESULT_WITH_RSSI;
-        mask |= BT_EVT_MASK_REMOTE_EXT_FEATURES;
-        mask |= BT_EVT_MASK_SYNC_CONN_COMPLETE;
-        mask |= BT_EVT_MASK_EXTENDED_INQUIRY_RESULT;
-        mask |= BT_EVT_MASK_IO_CAPA_REQ;
-        mask |= BT_EVT_MASK_IO_CAPA_RESP;
-        mask |= BT_EVT_MASK_USER_CONFIRM_REQ;
-        mask |= BT_EVT_MASK_USER_PASSKEY_REQ;
-        mask |= BT_EVT_MASK_SSP_COMPLETE;
-        mask |= BT_EVT_MASK_USER_PASSKEY_NOTIFY;
-    }
-
-    mask |= BT_EVT_MASK_HARDWARE_ERROR;
-    mask |= BT_EVT_MASK_DATA_BUFFER_OVERFLOW;
-    mask |= BT_EVT_MASK_LE_META_EVENT;
-
-    if (IS_ENABLED(CONFIG_BT_CONN)) {
-        mask |= BT_EVT_MASK_DISCONN_COMPLETE;
-        mask |= BT_EVT_MASK_REMOTE_VERSION_INFO;
-    }
+    sc_cp             = net_buf_add(buf, sizeof(*sc_cp));
+    sc_cp->sc_support = 0x01;
 
-    if (IS_ENABLED(CONFIG_BT_SMP) &&
-        BT_FEAT_LE_ENCR(bt_dev.le.features)) {
-        mask |= BT_EVT_MASK_ENCRYPT_CHANGE;
-        mask |= BT_EVT_MASK_ENCRYPT_KEY_REFRESH_COMPLETE;
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SC_HOST_SUPP, buf, NULL);
+    if (err) {
+      return err;
     }
+  }
 
-    sys_put_le64(mask, ev->events);
-    return bt_hci_cmd_send_sync(BT_HCI_OP_SET_EVENT_MASK, buf, NULL);
+  return 0;
 }
+#else
+static int br_init(void) {
+#if defined(CONFIG_BT_CONN)
+  struct net_buf *rsp;
+  int             err;
 
-static inline int create_random_addr(bt_addr_le_t *addr)
-{
-    addr->type = BT_ADDR_LE_RANDOM;
+  if (bt_dev.le.mtu) {
+    return 0;
+  }
 
-    return bt_rand(addr->a.val, 6);
+  /* Use BR/EDR buffer size if LE reports zero buffers */
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BUFFER_SIZE, NULL, &rsp);
+  if (err) {
+    return err;
+  }
+
+  read_buffer_size_complete(rsp);
+  net_buf_unref(rsp);
+#endif /* CONFIG_BT_CONN */
+
+  return 0;
 }
+#endif
 
-int bt_addr_le_create_nrpa(bt_addr_le_t *addr)
-{
-    int err;
+static int set_event_mask(void) {
+  struct bt_hci_cp_set_event_mask *ev;
+  struct net_buf                  *buf;
+  u64_t                            mask = 0U;
 
-    err = create_random_addr(addr);
-    if (err) {
-        return err;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_SET_EVENT_MASK, sizeof(*ev));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    BT_ADDR_SET_NRPA(&addr->a);
+  ev = net_buf_add(buf, sizeof(*ev));
 
-    return 0;
+  if (IS_ENABLED(CONFIG_BT_BREDR)) {
+    /* Since we require LE support, we can count on a
+     * Bluetooth 4.0 feature set
+     */
+    mask |= BT_EVT_MASK_INQUIRY_COMPLETE;
+    mask |= BT_EVT_MASK_CONN_COMPLETE;
+    mask |= BT_EVT_MASK_CONN_REQUEST;
+    mask |= BT_EVT_MASK_AUTH_COMPLETE;
+    mask |= BT_EVT_MASK_REMOTE_NAME_REQ_COMPLETE;
+    mask |= BT_EVT_MASK_REMOTE_FEATURES;
+    mask |= BT_EVT_MASK_ROLE_CHANGE;
+    mask |= BT_EVT_MASK_PIN_CODE_REQ;
+    mask |= BT_EVT_MASK_LINK_KEY_REQ;
+    mask |= BT_EVT_MASK_LINK_KEY_NOTIFY;
+    mask |= BT_EVT_MASK_INQUIRY_RESULT_WITH_RSSI;
+    mask |= BT_EVT_MASK_REMOTE_EXT_FEATURES;
+    mask |= BT_EVT_MASK_SYNC_CONN_COMPLETE;
+    mask |= BT_EVT_MASK_EXTENDED_INQUIRY_RESULT;
+    mask |= BT_EVT_MASK_IO_CAPA_REQ;
+    mask |= BT_EVT_MASK_IO_CAPA_RESP;
+    mask |= BT_EVT_MASK_USER_CONFIRM_REQ;
+    mask |= BT_EVT_MASK_USER_PASSKEY_REQ;
+    mask |= BT_EVT_MASK_SSP_COMPLETE;
+    mask |= BT_EVT_MASK_USER_PASSKEY_NOTIFY;
+  }
+
+  mask |= BT_EVT_MASK_HARDWARE_ERROR;
+  mask |= BT_EVT_MASK_DATA_BUFFER_OVERFLOW;
+  mask |= BT_EVT_MASK_LE_META_EVENT;
+
+  if (IS_ENABLED(CONFIG_BT_CONN)) {
+    mask |= BT_EVT_MASK_DISCONN_COMPLETE;
+    mask |= BT_EVT_MASK_REMOTE_VERSION_INFO;
+  }
+
+  if (IS_ENABLED(CONFIG_BT_SMP) && BT_FEAT_LE_ENCR(bt_dev.le.features)) {
+    mask |= BT_EVT_MASK_ENCRYPT_CHANGE;
+    mask |= BT_EVT_MASK_ENCRYPT_KEY_REFRESH_COMPLETE;
+  }
+
+  sys_put_le64(mask, ev->events);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_SET_EVENT_MASK, buf, NULL);
+}
+
+static inline int create_random_addr(bt_addr_le_t *addr) {
+  addr->type = BT_ADDR_LE_RANDOM;
+
+  return bt_rand(addr->a.val, 6);
+}
+
+int bt_addr_le_create_nrpa(bt_addr_le_t *addr) {
+  int err;
+
+  err = create_random_addr(addr);
+  if (err) {
+    return err;
+  }
+
+  BT_ADDR_SET_NRPA(&addr->a);
+
+  return 0;
 }
 
-int bt_addr_le_create_static(bt_addr_le_t *addr)
-{
-    int err;
+int bt_addr_le_create_static(bt_addr_le_t *addr) {
+  int err;
 
-    err = create_random_addr(addr);
-    if (err) {
-        return err;
-    }
+  err = create_random_addr(addr);
+  if (err) {
+    return err;
+  }
 
-    BT_ADDR_SET_STATIC(&addr->a);
+  BT_ADDR_SET_STATIC(&addr->a);
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_DEBUG)
@@ -5097,8 +4758,7 @@ static const char *ver_str(u8_t ver)
 }
 #endif
 
-static void bt_dev_show_info(void)
-{
+static void bt_dev_show_info(void) {
 #if 0
 	int i;
 
@@ -5119,600 +4779,540 @@ static void bt_dev_show_info(void)
 #endif
 }
 #else
-static inline void bt_dev_show_info(void)
-{
-}
+static inline void bt_dev_show_info(void) {}
 #endif /* CONFIG_BT_DEBUG */
 
 #if defined(CONFIG_BT_HCI_VS_EXT)
 #if defined(CONFIG_BT_DEBUG)
-static const char *vs_hw_platform(u16_t platform)
-{
-    static const char *const plat_str[] = {
-        "reserved", "Intel Corporation", "Nordic Semiconductor",
-        "NXP Semiconductors"
-    };
+static const char *vs_hw_platform(u16_t platform) {
+  static const char *const plat_str[] = {"reserved", "Intel Corporation", "Nordic Semiconductor", "NXP Semiconductors"};
 
-    if (platform < ARRAY_SIZE(plat_str)) {
-        return plat_str[platform];
-    }
+  if (platform < ARRAY_SIZE(plat_str)) {
+    return plat_str[platform];
+  }
 
-    return "unknown";
+  return "unknown";
 }
 
-static const char *vs_hw_variant(u16_t platform, u16_t variant)
-{
-    static const char *const nordic_str[] = {
-        "reserved", "nRF51x", "nRF52x", "nRF53x"
-    };
+static const char *vs_hw_variant(u16_t platform, u16_t variant) {
+  static const char *const nordic_str[] = {"reserved", "nRF51x", "nRF52x", "nRF53x"};
 
-    if (platform != BT_HCI_VS_HW_PLAT_NORDIC) {
-        return "unknown";
-    }
+  if (platform != BT_HCI_VS_HW_PLAT_NORDIC) {
+    return "unknown";
+  }
 
-    if (variant < ARRAY_SIZE(nordic_str)) {
-        return nordic_str[variant];
-    }
+  if (variant < ARRAY_SIZE(nordic_str)) {
+    return nordic_str[variant];
+  }
 
-    return "unknown";
+  return "unknown";
 }
 
-static const char *vs_fw_variant(u8_t variant)
-{
-    static const char *const var_str[] = {
-        "Standard Bluetooth controller",
-        "Vendor specific controller",
-        "Firmware loader",
-        "Rescue image",
-    };
+static const char *vs_fw_variant(u8_t variant) {
+  static const char *const var_str[] = {
+      "Standard Bluetooth controller",
+      "Vendor specific controller",
+      "Firmware loader",
+      "Rescue image",
+  };
 
-    if (variant < ARRAY_SIZE(var_str)) {
-        return var_str[variant];
-    }
+  if (variant < ARRAY_SIZE(var_str)) {
+    return var_str[variant];
+  }
 
-    return "unknown";
+  return "unknown";
 }
 #endif /* CONFIG_BT_DEBUG */
 
-static void hci_vs_init(void)
-{
-    union {
-        struct bt_hci_rp_vs_read_version_info *info;
-        struct bt_hci_rp_vs_read_supported_commands *cmds;
-        struct bt_hci_rp_vs_read_supported_features *feat;
-    } rp;
-    struct net_buf *rsp;
-    int err;
-
-    /* If heuristics is enabled, try to guess HCI VS support by looking
-	 * at the HCI version and identity address. We haven't tried to set
-	 * a static random address yet at this point, so the identity will
-	 * either be zeroes or a valid public address.
-	 */
-    if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) &&
-        (bt_dev.hci_version < BT_HCI_VERSION_5_0 ||
-         (!atomic_test_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR) &&
-          bt_addr_le_cmp(&bt_dev.id_addr[0], BT_ADDR_LE_ANY)))) {
-        BT_WARN("Controller doesn't seem to support Zephyr vendor HCI");
-        return;
-    }
+static void hci_vs_init(void) {
+  union {
+    struct bt_hci_rp_vs_read_version_info       *info;
+    struct bt_hci_rp_vs_read_supported_commands *cmds;
+    struct bt_hci_rp_vs_read_supported_features *feat;
+  } rp;
+  struct net_buf *rsp;
+  int             err;
+
+  /* If heuristics is enabled, try to guess HCI VS support by looking
+   * at the HCI version and identity address. We haven't tried to set
+   * a static random address yet at this point, so the identity will
+   * either be zeroes or a valid public address.
+   */
+  if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT)
+      && (bt_dev.hci_version < BT_HCI_VERSION_5_0 || (!atomic_test_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR) && bt_addr_le_cmp(&bt_dev.id_addr[0], BT_ADDR_LE_ANY)))) {
+    BT_WARN("Controller doesn't seem to support Zephyr vendor HCI");
+    return;
+  }
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_VERSION_INFO, NULL, &rsp);
-    if (err) {
-        BT_WARN("Vendor HCI extensions not available");
-        return;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_VERSION_INFO, NULL, &rsp);
+  if (err) {
+    BT_WARN("Vendor HCI extensions not available");
+    return;
+  }
 
 #if defined(CONFIG_BT_DEBUG)
-    rp.info = (void *)rsp->data;
-    BT_INFO("HW Platform: %s (0x%04x)",
-            vs_hw_platform(sys_le16_to_cpu(rp.info->hw_platform)),
-            sys_le16_to_cpu(rp.info->hw_platform));
-    BT_INFO("HW Variant: %s (0x%04x)",
-            vs_hw_variant(sys_le16_to_cpu(rp.info->hw_platform),
-                          sys_le16_to_cpu(rp.info->hw_variant)),
-            sys_le16_to_cpu(rp.info->hw_variant));
-    BT_INFO("Firmware: %s (0x%02x) Version %u.%u Build %u",
-            vs_fw_variant(rp.info->fw_variant), rp.info->fw_variant,
-            rp.info->fw_version, sys_le16_to_cpu(rp.info->fw_revision),
-            sys_le32_to_cpu(rp.info->fw_build));
+  rp.info = (void *)rsp->data;
+  BT_INFO("HW Platform: %s (0x%04x)", vs_hw_platform(sys_le16_to_cpu(rp.info->hw_platform)), sys_le16_to_cpu(rp.info->hw_platform));
+  BT_INFO("HW Variant: %s (0x%04x)", vs_hw_variant(sys_le16_to_cpu(rp.info->hw_platform), sys_le16_to_cpu(rp.info->hw_variant)), sys_le16_to_cpu(rp.info->hw_variant));
+  BT_INFO("Firmware: %s (0x%02x) Version %u.%u Build %u", vs_fw_variant(rp.info->fw_variant), rp.info->fw_variant, rp.info->fw_version, sys_le16_to_cpu(rp.info->fw_revision),
+          sys_le32_to_cpu(rp.info->fw_build));
 #endif /* CONFIG_BT_DEBUG */
 
-    net_buf_unref(rsp);
+  net_buf_unref(rsp);
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_COMMANDS,
-                               NULL, &rsp);
-    if (err) {
-        BT_WARN("Failed to read supported vendor features");
-        return;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_COMMANDS, NULL, &rsp);
+  if (err) {
+    BT_WARN("Failed to read supported vendor features");
+    return;
+  }
 
-    rp.cmds = (void *)rsp->data;
-    memcpy(bt_dev.vs_commands, rp.cmds->commands, BT_DEV_VS_CMDS_MAX);
-    net_buf_unref(rsp);
+  rp.cmds = (void *)rsp->data;
+  memcpy(bt_dev.vs_commands, rp.cmds->commands, BT_DEV_VS_CMDS_MAX);
+  net_buf_unref(rsp);
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_FEATURES,
-                               NULL, &rsp);
-    if (err) {
-        BT_WARN("Failed to read supported vendor commands");
-        return;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_FEATURES, NULL, &rsp);
+  if (err) {
+    BT_WARN("Failed to read supported vendor commands");
+    return;
+  }
 
-    rp.feat = (void *)rsp->data;
-    memcpy(bt_dev.vs_features, rp.feat->features, BT_DEV_VS_FEAT_MAX);
-    net_buf_unref(rsp);
+  rp.feat = (void *)rsp->data;
+  memcpy(bt_dev.vs_features, rp.feat->features, BT_DEV_VS_FEAT_MAX);
+  net_buf_unref(rsp);
 }
 #endif /* CONFIG_BT_HCI_VS_EXT */
 
-static int host_hci_init(void)
-{
-    int err;
-
-    err = common_init();
-    if (err) {
-        return err;
-    }
+static int host_hci_init(void) {
+  int err;
 
-    err = le_init();
-    if (err) {
-        return err;
-    }
+  err = common_init();
+  if (err) {
+    return err;
+  }
 
-    if (BT_FEAT_BREDR(bt_dev.features)) {
-        err = br_init();
-        if (err) {
-            return err;
-        }
-    } else if (IS_ENABLED(CONFIG_BT_BREDR)) {
-        BT_ERR("Non-BR/EDR controller detected");
-        return -EIO;
-    }
+  err = le_init();
+  if (err) {
+    return err;
+  }
 
-    err = set_event_mask();
+  if (BT_FEAT_BREDR(bt_dev.features)) {
+    err = br_init();
     if (err) {
-        return err;
+      return err;
     }
+  } else if (IS_ENABLED(CONFIG_BT_BREDR)) {
+    BT_ERR("Non-BR/EDR controller detected");
+    return -EIO;
+  }
+
+  err = set_event_mask();
+  if (err) {
+    return err;
+  }
 
 #if defined(CONFIG_BT_HCI_VS_EXT)
-    hci_vs_init();
+  hci_vs_init();
 #endif
 
-    if (!IS_ENABLED(CONFIG_BT_SETTINGS) && !bt_dev.id_count) {
-        BT_DBG("No public address. Trying to set static random.");
-        err = bt_setup_id_addr();
-        if (err) {
-            BT_ERR("Unable to set identity address");
-            return err;
-        }
+  if (!IS_ENABLED(CONFIG_BT_SETTINGS) && !bt_dev.id_count) {
+    BT_DBG("No public address. Trying to set static random.");
+    err = bt_setup_id_addr();
+    if (err) {
+      BT_ERR("Unable to set identity address");
+      return err;
     }
+  }
 
-    return 0;
+  return 0;
 }
 
-int bt_send(struct net_buf *buf)
-{
-    BT_DBG("buf %p len %u type %u", buf, buf->len, bt_buf_get_type(buf));
+int bt_send(struct net_buf *buf) {
+  BT_DBG("buf %p len %u type %u", buf, buf->len, bt_buf_get_type(buf));
 
-    bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len);
+  bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len);
 
-    if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) {
-        return bt_hci_ecc_send(buf);
-    }
+  if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) {
+    return bt_hci_ecc_send(buf);
+  }
 
-    return bt_dev.drv->send(buf);
+  return bt_dev.drv->send(buf);
 }
 
-int bt_recv(struct net_buf *buf)
-{
-    bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len);
+int bt_recv(struct net_buf *buf) {
+  bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len);
 
-    BT_DBG("buf %p len %u", buf, buf->len);
+  BT_DBG("buf %p len %u", buf, buf->len);
 
-    switch (bt_buf_get_type(buf)) {
+  switch (bt_buf_get_type(buf)) {
 #if defined(CONFIG_BT_CONN)
-        case BT_BUF_ACL_IN:
+  case BT_BUF_ACL_IN:
 #if defined(CONFIG_BT_RECV_IS_RX_THREAD)
-            hci_acl(buf);
+    hci_acl(buf);
 #else
-            net_buf_put(&bt_dev.rx_queue, buf);
+    net_buf_put(&bt_dev.rx_queue, buf);
 #endif
-            return 0;
+    return 0;
 #endif /* BT_CONN */
-        case BT_BUF_EVT:
+  case BT_BUF_EVT:
 #if defined(CONFIG_BT_RECV_IS_RX_THREAD)
-            hci_event(buf);
+    hci_event(buf);
 #else
-            net_buf_put(&bt_dev.rx_queue, buf);
+    net_buf_put(&bt_dev.rx_queue, buf);
 #endif
-            return 0;
-        default:
-            BT_ERR("Invalid buf type %u", bt_buf_get_type(buf));
-            net_buf_unref(buf);
-            return -EINVAL;
-    }
+    return 0;
+  default:
+    BT_ERR("Invalid buf type %u", bt_buf_get_type(buf));
+    net_buf_unref(buf);
+    return -EINVAL;
+  }
 }
 
 static const struct event_handler prio_events[] = {
-    EVENT_HANDLER(BT_HCI_EVT_CMD_COMPLETE, hci_cmd_complete,
-                  sizeof(struct bt_hci_evt_cmd_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_CMD_STATUS, hci_cmd_status,
-                  sizeof(struct bt_hci_evt_cmd_status)),
+    EVENT_HANDLER(BT_HCI_EVT_CMD_COMPLETE, hci_cmd_complete, sizeof(struct bt_hci_evt_cmd_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_CMD_STATUS, hci_cmd_status, sizeof(struct bt_hci_evt_cmd_status)),
 #if defined(CONFIG_BT_CONN)
-    EVENT_HANDLER(BT_HCI_EVT_DATA_BUF_OVERFLOW,
-                  hci_data_buf_overflow,
-                  sizeof(struct bt_hci_evt_data_buf_overflow)),
-    EVENT_HANDLER(BT_HCI_EVT_NUM_COMPLETED_PACKETS,
-                  hci_num_completed_packets,
-                  sizeof(struct bt_hci_evt_num_completed_packets)),
+    EVENT_HANDLER(BT_HCI_EVT_DATA_BUF_OVERFLOW, hci_data_buf_overflow, sizeof(struct bt_hci_evt_data_buf_overflow)),
+    EVENT_HANDLER(BT_HCI_EVT_NUM_COMPLETED_PACKETS, hci_num_completed_packets, sizeof(struct bt_hci_evt_num_completed_packets)),
 #endif /* CONFIG_BT_CONN */
 };
 
-int bt_recv_prio(struct net_buf *buf)
-{
-    struct bt_hci_evt_hdr *hdr;
+int bt_recv_prio(struct net_buf *buf) {
+  struct bt_hci_evt_hdr *hdr;
 
-    bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len);
+  bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len);
 
-    BT_ASSERT(bt_buf_get_type(buf) == BT_BUF_EVT);
-    BT_ASSERT(buf->len >= sizeof(*hdr));
+  BT_ASSERT(bt_buf_get_type(buf) == BT_BUF_EVT);
+  BT_ASSERT(buf->len >= sizeof(*hdr));
 
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    BT_ASSERT(bt_hci_evt_is_prio(hdr->evt));
+  hdr = net_buf_pull_mem(buf, sizeof(*hdr));
+  BT_ASSERT(bt_hci_evt_is_prio(hdr->evt));
 
-    handle_event(hdr->evt, buf, prio_events, ARRAY_SIZE(prio_events));
+  handle_event(hdr->evt, buf, prio_events, ARRAY_SIZE(prio_events));
 
-    net_buf_unref(buf);
+  net_buf_unref(buf);
 
-    return 0;
+  return 0;
 }
 
-int bt_hci_driver_register(const struct bt_hci_driver *drv)
-{
-    if (bt_dev.drv) {
-        return -EALREADY;
-    }
+int bt_hci_driver_register(const struct bt_hci_driver *drv) {
+  if (bt_dev.drv) {
+    return -EALREADY;
+  }
 
-    if (!drv->open || !drv->send) {
-        return -EINVAL;
-    }
+  if (!drv->open || !drv->send) {
+    return -EINVAL;
+  }
 
-    bt_dev.drv = drv;
+  bt_dev.drv = drv;
 
-    BT_DBG("Registered %s", drv->name ? drv->name : "");
+  BT_DBG("Registered %s", drv->name ? drv->name : "");
 
-    bt_monitor_new_index(BT_MONITOR_TYPE_PRIMARY, drv->bus,
-                         BT_ADDR_ANY, drv->name ? drv->name : "bt0");
+  bt_monitor_new_index(BT_MONITOR_TYPE_PRIMARY, drv->bus, BT_ADDR_ANY, drv->name ? drv->name : "bt0");
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_PRIVACY)
-static int irk_init(void)
-{
+static int irk_init(void) {
 #if (BFLB_FIXED_IRK)
-    //use fixed irk
-    memset(&bt_dev.irk[0], 0x11, 16);
-    return 0;
+  // use fixed irk
+  memset(&bt_dev.irk[0], 0x11, 16);
+  return 0;
 #endif
 #if defined(BFLB_BLE_PATCH_SETTINGS_LOAD)
-    u8_t empty_irk[16];
-    int err;
-    /*local irk has been loaded from flash in bt_enable, check if irk is null*/
-    memset(empty_irk, 0, 16);
-    if (memcmp(bt_dev.irk[0], empty_irk, 16) != 0)
-        return 0;
+  u8_t empty_irk[16];
+  int  err;
+  /*local irk has been loaded from flash in bt_enable, check if irk is null*/
+  memset(empty_irk, 0, 16);
+  if (memcmp(bt_dev.irk[0], empty_irk, 16) != 0)
+    return 0;
 
-    err = bt_rand(&bt_dev.irk[0], 16);
+  err = bt_rand(&bt_dev.irk[0], 16);
 
-    return err;
+  return err;
 #else
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        BT_DBG("Expecting settings to handle local IRK");
-    } else {
-        int err;
-
-        err = bt_rand(&bt_dev.irk[0], 16);
-        if (err) {
-            return err;
-        }
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    BT_DBG("Expecting settings to handle local IRK");
+  } else {
+    int err;
 
-        BT_WARN("Using temporary IRK");
+    err = bt_rand(&bt_dev.irk[0], 16);
+    if (err) {
+      return err;
     }
 
-    return 0;
+    BT_WARN("Using temporary IRK");
+  }
+
+  return 0;
 #endif
 }
 #endif /* CONFIG_BT_PRIVACY */
-void bt_finalize_init(void)
-{
-    atomic_set_bit(bt_dev.flags, BT_DEV_READY);
+void bt_finalize_init(void) {
+  atomic_set_bit(bt_dev.flags, BT_DEV_READY);
 
-    if (IS_ENABLED(CONFIG_BT_OBSERVER)) {
-        bt_le_scan_update(false);
-    }
+  if (IS_ENABLED(CONFIG_BT_OBSERVER)) {
+    bt_le_scan_update(false);
+  }
 
-    bt_dev_show_info();
+  bt_dev_show_info();
 }
 
 #if defined(BFLB_HOST_ASSISTANT)
 extern void blhast_init(struct blhast_cb *cb);
 #endif
-static int bt_init(void)
-{
-    int err;
+static int bt_init(void) {
+  int err;
 #if defined(CONFIG_BT_STACK_PTS)
-    u8_t dbg_irk[16];
+  u8_t dbg_irk[16];
 #endif
 /*Make sure that freertos is running when set info into flash, because Semaphore is used in ef_set_env*/
 #if defined(BFLB_BLE_PATCH_SETTINGS_LOAD)
-    char empty_name[CONFIG_BT_DEVICE_NAME_MAX];
-    memset(empty_name, 0, CONFIG_BT_DEVICE_NAME_MAX);
+  char empty_name[CONFIG_BT_DEVICE_NAME_MAX];
+  memset(empty_name, 0, CONFIG_BT_DEVICE_NAME_MAX);
 
-    if (!memcmp(bt_dev.name, empty_name, CONFIG_BT_DEVICE_NAME_MAX))
-        bt_set_name(CONFIG_BT_DEVICE_NAME);
+  if (!memcmp(bt_dev.name, empty_name, CONFIG_BT_DEVICE_NAME_MAX))
+    bt_set_name(CONFIG_BT_DEVICE_NAME);
 #endif
 
 #if defined(BFLB_BLE)
-    err = bl_onchiphci_interface_init();
-    if (err) {
-        return err;
-    }
+  err = bl_onchiphci_interface_init();
+  if (err) {
+    return err;
+  }
 #if defined(BFLB_HOST_ASSISTANT)
-    blhast_init(host_assist_cb);
+  blhast_init(host_assist_cb);
 #endif
 #endif
 
-    err = host_hci_init();
+  err = host_hci_init();
+  if (err) {
+    return err;
+  }
+  if (IS_ENABLED(CONFIG_BT_CONN)) {
+    err = bt_conn_init();
     if (err) {
-        return err;
-    }
-    if (IS_ENABLED(CONFIG_BT_CONN)) {
-        err = bt_conn_init();
-        if (err) {
-            return err;
-        }
+      return err;
     }
+  }
 
 #if defined(CONFIG_BT_PRIVACY)
-    err = irk_init();
-    if (err) {
-        return err;
-    }
+  err = irk_init();
+  if (err) {
+    return err;
+  }
 #if defined(CONFIG_BT_STACK_PTS)
-    reverse_bytearray(bt_dev.irk[0], dbg_irk, sizeof(dbg_irk));
-    BT_PTS("Local IRK %s public identity bdaddr %s",
-           bt_hex(dbg_irk, 16), bt_addr_str(&(bt_dev.id_addr[0].a)));
+  reverse_bytearray(bt_dev.irk[0], dbg_irk, sizeof(dbg_irk));
+  BT_PTS("Local IRK %s public identity bdaddr %s", bt_hex(dbg_irk, 16), bt_addr_str(&(bt_dev.id_addr[0].a)));
 #endif
 
-    k_delayed_work_init(&bt_dev.rpa_update, rpa_timeout);
+  k_delayed_work_init(&bt_dev.rpa_update, rpa_timeout);
 #endif
 
 #if defined(CONFIG_BT_SMP)
 #if defined(BFLB_BLE_PATCH_SETTINGS_LOAD)
 #if defined(CFG_SLEEP)
-    if (HBN_Get_Status_Flag() == 0)
+  if (HBN_Get_Status_Flag() == 0)
 #endif
-    {
-        if (!bt_keys_load())
-            keys_commit();
-    }
+  {
+    if (!bt_keys_load())
+      keys_commit();
+  }
 #endif
-#endif //CONFIG_BT_SMP
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        if (!bt_dev.id_count) {
-            BT_INFO("No ID address. App must call settings_load()");
-            return 0;
-        }
-
-        atomic_set_bit(bt_dev.flags, BT_DEV_PRESET_ID);
+#endif // CONFIG_BT_SMP
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    if (!bt_dev.id_count) {
+      BT_INFO("No ID address. App must call settings_load()");
+      return 0;
     }
 
-    bt_finalize_init();
-    return 0;
+    atomic_set_bit(bt_dev.flags, BT_DEV_PRESET_ID);
+  }
+
+  bt_finalize_init();
+  return 0;
 }
 
-static void init_work(struct k_work *work)
-{
-    int err;
+static void init_work(struct k_work *work) {
+  int err;
 
-    err = bt_init();
-    if (ready_cb) {
-        ready_cb(err);
-    }
+  err = bt_init();
+  if (ready_cb) {
+    ready_cb(err);
+  }
 }
 
 #if !defined(CONFIG_BT_RECV_IS_RX_THREAD)
-static void hci_rx_thread(void)
-{
-    struct net_buf *buf;
+static void hci_rx_thread(void) {
+  struct net_buf *buf;
 
-    BT_DBG("started");
+  BT_DBG("started");
 
-    while (1) {
-        BT_DBG("calling fifo_get_wait");
-        buf = net_buf_get(&bt_dev.rx_queue, K_FOREVER);
+  while (1) {
+    BT_DBG("calling fifo_get_wait");
+    buf = net_buf_get(&bt_dev.rx_queue, K_FOREVER);
 
-        BT_DBG("buf %p type %u len %u", buf, bt_buf_get_type(buf),
-               buf->len);
+    BT_DBG("buf %p type %u len %u", buf, bt_buf_get_type(buf), buf->len);
 
-        switch (bt_buf_get_type(buf)) {
+    switch (bt_buf_get_type(buf)) {
 #if defined(CONFIG_BT_CONN)
-            case BT_BUF_ACL_IN:
-                hci_acl(buf);
-                break;
+    case BT_BUF_ACL_IN:
+      hci_acl(buf);
+      break;
 #endif /* CONFIG_BT_CONN */
-            case BT_BUF_EVT:
-                hci_event(buf);
-                break;
-            default:
-                BT_ERR("Unknown buf type %u", bt_buf_get_type(buf));
-                net_buf_unref(buf);
-                break;
-        }
-
-        /* Make sure we don't hog the CPU if the rx_queue never
-		 * gets empty.
-		 */
-        k_yield();
+    case BT_BUF_EVT:
+      hci_event(buf);
+      break;
+    default:
+      BT_ERR("Unknown buf type %u", bt_buf_get_type(buf));
+      net_buf_unref(buf);
+      break;
     }
+
+    /* Make sure we don't hog the CPU if the rx_queue never
+     * gets empty.
+     */
+    k_yield();
+  }
 }
 #endif /* !CONFIG_BT_RECV_IS_RX_THREAD */
 
-int bt_enable(bt_ready_cb_t cb)
-{
-    int err;
+int bt_enable(bt_ready_cb_t cb) {
+  int err;
 
-    if (!bt_dev.drv) {
-        BT_ERR("No HCI driver registered");
-        return -ENODEV;
-    }
+  if (!bt_dev.drv) {
+    BT_ERR("No HCI driver registered");
+    return -ENODEV;
+  }
 
-    if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_ENABLE)) {
-        return -EALREADY;
-    }
+  if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_ENABLE)) {
+    return -EALREADY;
+  }
 
 #if defined(BFLB_BLE)
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    net_buf_init(&hci_cmd_pool, CONFIG_BT_HCI_CMD_COUNT, CMD_BUF_SIZE, NULL);
-    net_buf_init(&hci_rx_pool, CONFIG_BT_RX_BUF_COUNT, BT_BUF_RX_SIZE, NULL);
+  net_buf_init(&hci_cmd_pool, CONFIG_BT_HCI_CMD_COUNT, CMD_BUF_SIZE, NULL);
+  net_buf_init(&hci_rx_pool, CONFIG_BT_RX_BUF_COUNT, BT_BUF_RX_SIZE, NULL);
 #if defined(CONFIG_BT_CONN)
-    net_buf_init(&num_complete_pool, 1, BT_BUF_RX_SIZE, NULL);
+  net_buf_init(&num_complete_pool, 1, BT_BUF_RX_SIZE, NULL);
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-    net_buf_init(&acl_in_pool, CONFIG_BT_ACL_RX_COUNT, ACL_IN_SIZE, report_completed_packet);
-#endif //CONFIG_BT_HCI_ACL_FLOW_CONTROL
-#endif //CONFIG_BT_CONN
+  net_buf_init(&acl_in_pool, CONFIG_BT_ACL_RX_COUNT, ACL_IN_SIZE, report_completed_packet);
+#endif // CONFIG_BT_HCI_ACL_FLOW_CONTROL
+#endif // CONFIG_BT_CONN
 #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT)
-    net_buf_init(&discardable_pool, CONFIG_BT_DISCARDABLE_BUF_COUNT, BT_BUF_RX_SIZE, NULL);
+  net_buf_init(&discardable_pool, CONFIG_BT_DISCARDABLE_BUF_COUNT, BT_BUF_RX_SIZE, NULL);
 #endif
 #endif
 
-    k_work_init(&bt_dev.init, init_work);
-    k_work_q_start();
+  k_work_init(&bt_dev.init, init_work);
+  k_work_q_start();
 #if !defined(CONFIG_BT_WAIT_NOP)
-    k_sem_init(&bt_dev.ncmd_sem, 1, 1);
+  k_sem_init(&bt_dev.ncmd_sem, 1, 1);
 #else
-    k_sem_init(&bt_dev.ncmd_sem, 0, 1);
+  k_sem_init(&bt_dev.ncmd_sem, 0, 1);
 #endif
-    k_fifo_init(&bt_dev.cmd_tx_queue, 20);
+  k_fifo_init(&bt_dev.cmd_tx_queue, 20);
 #if !defined(CONFIG_BT_RECV_IS_RX_THREAD)
-    k_fifo_init(&bt_dev.rx_queue, 20);
+  k_fifo_init(&bt_dev.rx_queue, 20);
 #endif
 
-    k_sem_init(&g_poll_sem, 0, 1);
+  k_sem_init(&g_poll_sem, 0, 1);
 #endif
 
 #if defined(BFLB_BLE_PATCH_SETTINGS_LOAD)
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
 #if defined(CFG_SLEEP)
-/* When using eflash_loader upprade firmware and softreset, 
-         * HBN_Get_Status_Flag() is 0x594c440b. so comment this line. */
-//if( HBN_Get_Status_Flag() == 0)
+/* When using eflash_loader upprade firmware and softreset,
+ * HBN_Get_Status_Flag() is 0x594c440b. so comment this line. */
+// if( HBN_Get_Status_Flag() == 0)
 #endif
-        bt_local_info_load();
-    }
+    bt_local_info_load();
+  }
 #else
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        err = bt_settings_init();
-        if (err) {
-            return err;
-        }
-    } else {
-        bt_set_name(CONFIG_BT_DEVICE_NAME);
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    err = bt_settings_init();
+    if (err) {
+      return err;
     }
+  } else {
+    bt_set_name(CONFIG_BT_DEVICE_NAME);
+  }
 #endif
 
-    ready_cb = cb;
+  ready_cb = cb;
 
-    /* TX thread */
+  /* TX thread */
 #if defined(BFLB_BLE)
 #if (!BFLB_BLE_CO_THREAD)
-    k_thread_create(&tx_thread_data, "hci_tx_thread",
-                    CONFIG_BT_HCI_TX_STACK_SIZE,
-                    hci_tx_thread,
-                    CONFIG_BT_HCI_TX_PRIO);
+  k_thread_create(&tx_thread_data, "hci_tx_thread", CONFIG_BT_HCI_TX_STACK_SIZE, hci_tx_thread, CONFIG_BT_HCI_TX_PRIO);
 #endif
 #else
-    k_thread_create(&tx_thread_data, tx_thread_stack,
-                    K_THREAD_STACK_SIZEOF(tx_thread_stack),
-                    hci_tx_thread, NULL, NULL, NULL,
-                    K_PRIO_COOP(CONFIG_BT_HCI_TX_PRIO),
-                    0, K_NO_WAIT);
-    k_thread_name_set(&tx_thread_data, "BT TX");
+  k_thread_create(&tx_thread_data, tx_thread_stack, K_THREAD_STACK_SIZEOF(tx_thread_stack), hci_tx_thread, NULL, NULL, NULL, K_PRIO_COOP(CONFIG_BT_HCI_TX_PRIO), 0, K_NO_WAIT);
+  k_thread_name_set(&tx_thread_data, "BT TX");
 #endif
 
 #if !defined(CONFIG_BT_RECV_IS_RX_THREAD)
-    /* RX thread */
+  /* RX thread */
 #if defined(BFLB_BLE)
-    k_thread_create(&rx_thread_data, "hci_rx_thread",
-                    CONFIG_BT_HCI_RX_STACK_SIZE /*K_THREAD_STACK_SIZEOF(rx_thread_stack)*/,
-                    (k_thread_entry_t)hci_rx_thread,
-                    CONFIG_BT_RX_PRIO);
+  k_thread_create(&rx_thread_data, "hci_rx_thread", CONFIG_BT_HCI_RX_STACK_SIZE /*K_THREAD_STACK_SIZEOF(rx_thread_stack)*/, (k_thread_entry_t)hci_rx_thread, CONFIG_BT_RX_PRIO);
 #else
-    k_thread_create(&rx_thread_data, rx_thread_stack,
-                    K_THREAD_STACK_SIZEOF(rx_thread_stack),
-                    (k_thread_entry_t)hci_rx_thread, NULL, NULL, NULL,
-                    K_PRIO_COOP(CONFIG_BT_RX_PRIO),
-                    0, K_NO_WAIT);
-    k_thread_name_set(&rx_thread_data, "BT RX");
-#endif //BFLB_BLE
+  k_thread_create(&rx_thread_data, rx_thread_stack, K_THREAD_STACK_SIZEOF(rx_thread_stack), (k_thread_entry_t)hci_rx_thread, NULL, NULL, NULL, K_PRIO_COOP(CONFIG_BT_RX_PRIO), 0, K_NO_WAIT);
+  k_thread_name_set(&rx_thread_data, "BT RX");
+#endif // BFLB_BLE
 #endif
 
-    if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) {
-        bt_hci_ecc_init();
-    }
+  if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) {
+    bt_hci_ecc_init();
+  }
 
-    err = bt_dev.drv->open();
-    if (err) {
-        BT_ERR("HCI driver open failed (%d)", err);
-        return err;
-    }
+  err = bt_dev.drv->open();
+  if (err) {
+    BT_ERR("HCI driver open failed (%d)", err);
+    return err;
+  }
 
 #if !defined(BFLB_BLE)
-    if (!cb) {
-        return bt_init();
-    }
+  if (!cb) {
+    return bt_init();
+  }
 #endif
 
 #if defined(CONFIG_BLE_MULTI_ADV)
-    bt_le_multi_adv_thread_init();
+  bt_le_multi_adv_thread_init();
 #endif
 
-    k_work_submit(&bt_dev.init);
-    return 0;
+  k_work_submit(&bt_dev.init);
+  return 0;
 }
 
 struct bt_ad {
-    const struct bt_data *data;
-    size_t len;
+  const struct bt_data *data;
+  size_t                len;
 };
 
 #if defined(BFLB_BLE)
-bool le_check_valid_scan(void)
-{
-    return atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
-}
+bool le_check_valid_scan(void) { return atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN); }
 #endif
 
 #if defined(BFLB_DISABLE_BT)
 extern struct k_thread recv_thread_data;
 extern struct k_thread work_q_thread;
-extern struct k_fifo recv_fifo;
-extern struct k_fifo free_tx;
+extern struct k_fifo   recv_fifo;
+extern struct k_fifo   free_tx;
 extern struct k_work_q g_work_queue_main;
 #if defined(CONFIG_BT_SMP)
 extern struct k_sem sc_local_pkey_ready;
 #endif
 
-void bt_delete_queue(struct k_fifo *queue_to_del)
-{
-    struct net_buf *buf = NULL;
+void bt_delete_queue(struct k_fifo *queue_to_del) {
+  struct net_buf *buf = NULL;
+  buf                 = net_buf_get(queue_to_del, K_NO_WAIT);
+  while (buf) {
+    net_buf_unref(buf);
     buf = net_buf_get(queue_to_del, K_NO_WAIT);
-    while (buf) {
-        net_buf_unref(buf);
-        buf = net_buf_get(queue_to_del, K_NO_WAIT);
-    }
+  }
 
-    k_queue_free(&(queue_to_del->_queue));
+  k_queue_free(&(queue_to_del->_queue));
 }
 
 #if defined(BFLB_DYNAMIC_ALLOC_MEM) && (CONFIG_BT_CONN)
@@ -5726,2037 +5326,1892 @@ extern struct net_buf_pool dummy_pool;
 #endif
 #endif
 
-int bt_disable_action(void)
-{
+int bt_disable_action(void) {
 #if defined(CONFIG_BT_PRIVACY)
-    k_delayed_work_del_timer(&bt_dev.rpa_update);
+  k_delayed_work_del_timer(&bt_dev.rpa_update);
 #endif
 
-    bt_gatt_deinit();
+  bt_gatt_deinit();
 
-    //delete task
-    k_thread_delete(&tx_thread_data);
-    k_thread_delete(&recv_thread_data);
-    k_thread_delete(&work_q_thread);
+  // delete task
+  k_thread_delete(&tx_thread_data);
+  k_thread_delete(&recv_thread_data);
+  k_thread_delete(&work_q_thread);
 
-    //delete queue, not delete hci_cmd_pool.free/hci_rx_pool.free/acl_tx_pool.free which store released buffers.
-    bt_delete_queue(&recv_fifo);
-    bt_delete_queue(&g_work_queue_main.fifo);
-    bt_delete_queue(&bt_dev.cmd_tx_queue);
+  // delete queue, not delete hci_cmd_pool.free/hci_rx_pool.free/acl_tx_pool.free which store released buffers.
+  bt_delete_queue(&recv_fifo);
+  bt_delete_queue(&g_work_queue_main.fifo);
+  bt_delete_queue(&bt_dev.cmd_tx_queue);
 
-    k_queue_free((struct k_queue *)&free_tx);
+  k_queue_free((struct k_queue *)&free_tx);
 
-    //delete sem
-    k_sem_delete(&bt_dev.ncmd_sem);
-    k_sem_delete(&g_poll_sem);
+  // delete sem
+  k_sem_delete(&bt_dev.ncmd_sem);
+  k_sem_delete(&g_poll_sem);
 #if defined(CONFIG_BT_SMP)
-    k_sem_delete(&sc_local_pkey_ready);
+  k_sem_delete(&sc_local_pkey_ready);
 #endif
-    k_sem_delete(&bt_dev.le.pkts);
+  k_sem_delete(&bt_dev.le.pkts);
 
-    atomic_clear_bit(bt_dev.flags, BT_DEV_ENABLE);
+  atomic_clear_bit(bt_dev.flags, BT_DEV_ENABLE);
 
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    net_buf_deinit(&hci_cmd_pool);
-    net_buf_deinit(&hci_rx_pool);
+  net_buf_deinit(&hci_cmd_pool);
+  net_buf_deinit(&hci_rx_pool);
 #if defined(CONFIG_BT_CONN)
-    net_buf_deinit(&acl_tx_pool);
-    net_buf_deinit(&num_complete_pool);
+  net_buf_deinit(&acl_tx_pool);
+  net_buf_deinit(&num_complete_pool);
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
-    net_buf_deinit(&prep_pool);
+  net_buf_deinit(&prep_pool);
 #endif
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-    net_buf_deinit(&acl_in_pool);
+  net_buf_deinit(&acl_in_pool);
 #endif
 #if (CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0)
-    net_buf_deinit(&frag_pool);
+  net_buf_deinit(&frag_pool);
 #endif
 #if defined(CONFIG_BT_BREDR)
-    net_buf_deinit(&br_sig_pool);
-    net_buf_deinit(&sdp_pool);
-    net_buf_deinit(&hf_pool);
-    net_buf_deinit(&dummy_pool);
+  net_buf_deinit(&br_sig_pool);
+  net_buf_deinit(&sdp_pool);
+  net_buf_deinit(&hf_pool);
+  net_buf_deinit(&dummy_pool);
 #endif
-#endif //defined(CONFIG_BT_CONN)
+#endif // defined(CONFIG_BT_CONN)
 #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT)
-    net_buf_deinit(&discardable_pool);
+  net_buf_deinit(&discardable_pool);
 #endif
-#endif //defined(BFLB_DYNAMIC_ALLOC_MEM)
+#endif // defined(BFLB_DYNAMIC_ALLOC_MEM)
 
-    bl_onchiphci_interface_deinit();
+  bl_onchiphci_interface_deinit();
 
-    extern void ble_controller_deinit(void);
-    ble_controller_deinit();
+  extern void ble_controller_deinit(void);
+  ble_controller_deinit();
 
-    return 0;
+  return 0;
 }
 
-int bt_disable(void)
-{
-    if (le_check_valid_conn() || atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN) || atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        return -1;
-    } else
-        return bt_disable_action();
+int bt_disable(void) {
+  if (le_check_valid_conn() || atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN) || atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return -1;
+  } else
+    return bt_disable_action();
 }
 #endif
 
-static int set_ad(u16_t hci_op, const struct bt_ad *ad, size_t ad_len)
-{
-    struct bt_hci_cp_le_set_adv_data *set_data;
-    struct net_buf *buf;
-    int c, i;
+static int set_ad(u16_t hci_op, const struct bt_ad *ad, size_t ad_len) {
+  struct bt_hci_cp_le_set_adv_data *set_data;
+  struct net_buf                   *buf;
+  int                               c, i;
 
-    buf = bt_hci_cmd_create(hci_op, sizeof(*set_data));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(hci_op, sizeof(*set_data));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    set_data = net_buf_add(buf, sizeof(*set_data));
+  set_data = net_buf_add(buf, sizeof(*set_data));
 
-    (void)memset(set_data, 0, sizeof(*set_data));
+  (void)memset(set_data, 0, sizeof(*set_data));
 
-    for (c = 0; c < ad_len; c++) {
-        const struct bt_data *data = ad[c].data;
+  for (c = 0; c < ad_len; c++) {
+    const struct bt_data *data = ad[c].data;
 
-        for (i = 0; i < ad[c].len; i++) {
-            int len = data[i].data_len;
-            u8_t type = data[i].type;
+    for (i = 0; i < ad[c].len; i++) {
+      int  len  = data[i].data_len;
+      u8_t type = data[i].type;
 
-            /* Check if ad fit in the remaining buffer */
-            if (set_data->len + len + 2 > 31) {
-                len = 31 - (set_data->len + 2);
-                if (type != BT_DATA_NAME_COMPLETE || !len) {
-                    net_buf_unref(buf);
-                    BT_ERR("Too big advertising data");
-                    return -EINVAL;
-                }
-                type = BT_DATA_NAME_SHORTENED;
-            }
+      /* Check if ad fit in the remaining buffer */
+      if (set_data->len + len + 2 > 31) {
+        len = 31 - (set_data->len + 2);
+        if (type != BT_DATA_NAME_COMPLETE || !len) {
+          net_buf_unref(buf);
+          BT_ERR("Too big advertising data");
+          return -EINVAL;
+        }
+        type = BT_DATA_NAME_SHORTENED;
+      }
 
-            set_data->data[set_data->len++] = len + 1;
-            set_data->data[set_data->len++] = type;
+      set_data->data[set_data->len++] = len + 1;
+      set_data->data[set_data->len++] = type;
 
-            memcpy(&set_data->data[set_data->len], data[i].data,
-                   len);
-            set_data->len += len;
-        }
+      memcpy(&set_data->data[set_data->len], data[i].data, len);
+      set_data->len += len;
     }
+  }
 
-    return bt_hci_cmd_send_sync(hci_op, buf, NULL);
+  return bt_hci_cmd_send_sync(hci_op, buf, NULL);
 }
 
-int bt_set_name(const char *name)
-{
+int bt_set_name(const char *name) {
 #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC)
-    size_t len = strlen(name);
+  size_t len = strlen(name);
 #if !defined(BFLB_BLE)
-    int err;
+  int err;
 #endif
-    if (len >= sizeof(bt_dev.name)) {
-        return -ENOMEM;
-    }
+  if (len >= sizeof(bt_dev.name)) {
+    return -ENOMEM;
+  }
 
-    if (!strcmp(bt_dev.name, name)) {
-        return 0;
-    }
+  if (!strcmp(bt_dev.name, name)) {
+    return 0;
+  }
 
-    strncpy(bt_dev.name, name, sizeof(bt_dev.name));
+  strncpy(bt_dev.name, name, sizeof(bt_dev.name));
 
-    /* Update advertising name if in use */
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING_NAME)) {
-        struct bt_data data[] = { BT_DATA(BT_DATA_NAME_COMPLETE, name,
-                                          strlen(name)) };
-        struct bt_ad sd = { data, ARRAY_SIZE(data) };
+  /* Update advertising name if in use */
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING_NAME)) {
+    struct bt_data data[] = {BT_DATA(BT_DATA_NAME_COMPLETE, name, strlen(name))};
+    struct bt_ad   sd     = {data, ARRAY_SIZE(data)};
 
-        set_ad(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, &sd, 1);
+    set_ad(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, &sd, 1);
 
-        /* Make sure the new name is set */
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-            set_advertise_enable(false);
-            set_advertise_enable(true);
-        }
+    /* Make sure the new name is set */
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+      set_advertise_enable(false);
+      set_advertise_enable(true);
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
 #if defined(BFLB_BLE)
 #if defined(CFG_SLEEP)
-        if (HBN_Get_Status_Flag() == 0)
+    if (HBN_Get_Status_Flag() == 0)
 #endif
-            bt_settings_save_name();
+      bt_settings_save_name();
 #else
-        err = settings_save_one("bt/name", bt_dev.name, len);
-        if (err) {
-            BT_WARN("Unable to store name");
-        }
-#endif
+    err = settings_save_one("bt/name", bt_dev.name, len);
+    if (err) {
+      BT_WARN("Unable to store name");
     }
+#endif
+  }
 
-    return 0;
+  return 0;
 #else
-    return -ENOMEM;
+  return -ENOMEM;
 #endif
 }
 
-const char *bt_get_name(void)
-{
+const char *bt_get_name(void) {
 #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC)
-    return bt_dev.name;
+  return bt_dev.name;
 #else
-    return CONFIG_BT_DEVICE_NAME;
+  return CONFIG_BT_DEVICE_NAME;
 #endif
 }
 
-int bt_set_id_addr(const bt_addr_le_t *addr)
-{
-    bt_addr_le_t non_const_addr;
+int bt_set_id_addr(const bt_addr_le_t *addr) {
+  bt_addr_le_t non_const_addr;
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        BT_ERR("Setting identity not allowed after bt_enable()");
-        return -EBUSY;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    BT_ERR("Setting identity not allowed after bt_enable()");
+    return -EBUSY;
+  }
 
-    bt_addr_le_copy(&non_const_addr, addr);
+  bt_addr_le_copy(&non_const_addr, addr);
 
-    return bt_id_create(&non_const_addr, NULL);
+  return bt_id_create(&non_const_addr, NULL);
 }
 
-void bt_id_get(bt_addr_le_t *addrs, size_t *count)
-{
-    size_t to_copy = MIN(*count, bt_dev.id_count);
+void bt_id_get(bt_addr_le_t *addrs, size_t *count) {
+  size_t to_copy = MIN(*count, bt_dev.id_count);
 
-    memcpy(addrs, bt_dev.id_addr, to_copy * sizeof(bt_addr_le_t));
-    *count = to_copy;
+  memcpy(addrs, bt_dev.id_addr, to_copy * sizeof(bt_addr_le_t));
+  *count = to_copy;
 }
 
-static int id_find(const bt_addr_le_t *addr)
-{
-    u8_t id;
+static int id_find(const bt_addr_le_t *addr) {
+  u8_t id;
 
-    for (id = 0U; id < bt_dev.id_count; id++) {
-        if (!bt_addr_le_cmp(addr, &bt_dev.id_addr[id])) {
-            return id;
-        }
+  for (id = 0U; id < bt_dev.id_count; id++) {
+    if (!bt_addr_le_cmp(addr, &bt_dev.id_addr[id])) {
+      return id;
     }
+  }
 
-    return -ENOENT;
+  return -ENOENT;
 }
 
-static void id_create(u8_t id, bt_addr_le_t *addr, u8_t *irk)
-{
-    if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
-        bt_addr_le_copy(&bt_dev.id_addr[id], addr);
-    } else {
-        bt_addr_le_t new_addr;
+static void id_create(u8_t id, bt_addr_le_t *addr, u8_t *irk) {
+  if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
+    bt_addr_le_copy(&bt_dev.id_addr[id], addr);
+  } else {
+    bt_addr_le_t new_addr;
 
-        do {
-            bt_addr_le_create_static(&new_addr);
-            /* Make sure we didn't generate a duplicate */
-        } while (id_find(&new_addr) >= 0);
+    do {
+      bt_addr_le_create_static(&new_addr);
+      /* Make sure we didn't generate a duplicate */
+    } while (id_find(&new_addr) >= 0);
 
-        bt_addr_le_copy(&bt_dev.id_addr[id], &new_addr);
+    bt_addr_le_copy(&bt_dev.id_addr[id], &new_addr);
 
-        if (addr) {
-            bt_addr_le_copy(addr, &bt_dev.id_addr[id]);
-        }
+    if (addr) {
+      bt_addr_le_copy(addr, &bt_dev.id_addr[id]);
     }
+  }
 
 #if defined(CONFIG_BT_PRIVACY)
-    {
-        u8_t zero_irk[16] = { 0 };
-
-        if (irk && memcmp(irk, zero_irk, 16)) {
-            memcpy(&bt_dev.irk[id], irk, 16);
-        } else {
-            bt_rand(&bt_dev.irk[id], 16);
-            if (irk) {
-                memcpy(irk, &bt_dev.irk[id], 16);
-            }
-        }
+  {
+    u8_t zero_irk[16] = {0};
+
+    if (irk && memcmp(irk, zero_irk, 16)) {
+      memcpy(&bt_dev.irk[id], irk, 16);
+    } else {
+      bt_rand(&bt_dev.irk[id], 16);
+      if (irk) {
+        memcpy(irk, &bt_dev.irk[id], 16);
+      }
     }
+  }
 #endif
-    /* Only store if stack was already initialized. Before initialization
-	 * we don't know the flash content, so it's potentially harmful to
-	 * try to write anything there.
-	 */
-    if (IS_ENABLED(CONFIG_BT_SETTINGS) &&
-        atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        bt_settings_save_id();
-    }
+  /* Only store if stack was already initialized. Before initialization
+   * we don't know the flash content, so it's potentially harmful to
+   * try to write anything there.
+   */
+  if (IS_ENABLED(CONFIG_BT_SETTINGS) && atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    bt_settings_save_id();
+  }
 }
 
-int bt_id_create(bt_addr_le_t *addr, u8_t *irk)
-{
-    int new_id;
-
-    if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
-        if (addr->type != BT_ADDR_LE_RANDOM ||
-            !BT_ADDR_IS_STATIC(&addr->a)) {
-            BT_ERR("Only static random identity address supported");
-            return -EINVAL;
-        }
+int bt_id_create(bt_addr_le_t *addr, u8_t *irk) {
+  int new_id;
 
-        if (id_find(addr) >= 0) {
-            return -EALREADY;
-        }
+  if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
+    if (addr->type != BT_ADDR_LE_RANDOM || !BT_ADDR_IS_STATIC(&addr->a)) {
+      BT_ERR("Only static random identity address supported");
+      return -EINVAL;
     }
 
-    if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) {
-        return -EINVAL;
+    if (id_find(addr) >= 0) {
+      return -EALREADY;
     }
+  }
 
-    if (bt_dev.id_count == ARRAY_SIZE(bt_dev.id_addr)) {
-        return -ENOMEM;
-    }
+  if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) {
+    return -EINVAL;
+  }
 
-    new_id = bt_dev.id_count++;
-    if (new_id == BT_ID_DEFAULT &&
-        !atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        atomic_set_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR);
-    }
+  if (bt_dev.id_count == ARRAY_SIZE(bt_dev.id_addr)) {
+    return -ENOMEM;
+  }
 
-    id_create(new_id, addr, irk);
+  new_id = bt_dev.id_count++;
+  if (new_id == BT_ID_DEFAULT && !atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    atomic_set_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR);
+  }
 
-    return new_id;
-}
+  id_create(new_id, addr, irk);
 
-int bt_id_reset(u8_t id, bt_addr_le_t *addr, u8_t *irk)
-{
-    if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
-        if (addr->type != BT_ADDR_LE_RANDOM ||
-            !BT_ADDR_IS_STATIC(&addr->a)) {
-            BT_ERR("Only static random identity address supported");
-            return -EINVAL;
-        }
+  return new_id;
+}
 
-        if (id_find(addr) >= 0) {
-            return -EALREADY;
-        }
+int bt_id_reset(u8_t id, bt_addr_le_t *addr, u8_t *irk) {
+  if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
+    if (addr->type != BT_ADDR_LE_RANDOM || !BT_ADDR_IS_STATIC(&addr->a)) {
+      BT_ERR("Only static random identity address supported");
+      return -EINVAL;
     }
 
-    if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) {
-        return -EINVAL;
+    if (id_find(addr) >= 0) {
+      return -EALREADY;
     }
+  }
 
-    if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) {
-        return -EINVAL;
-    }
+  if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) {
+    return -EINVAL;
+  }
 
-    if (id == bt_dev.adv_id && atomic_test_bit(bt_dev.flags,
-                                               BT_DEV_ADVERTISING)) {
-        return -EBUSY;
-    }
+  if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) {
+    return -EINVAL;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_CONN) &&
-        bt_addr_le_cmp(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) {
-        int err;
+  if (id == bt_dev.adv_id && atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return -EBUSY;
+  }
 
-        err = bt_unpair(id, NULL);
-        if (err) {
-            return err;
-        }
-    }
+  if (IS_ENABLED(CONFIG_BT_CONN) && bt_addr_le_cmp(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) {
+    int err;
 
-    id_create(id, addr, irk);
+    err = bt_unpair(id, NULL);
+    if (err) {
+      return err;
+    }
+  }
 
-    return id;
-}
+  id_create(id, addr, irk);
 
-int bt_id_delete(u8_t id)
-{
-    if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) {
-        return -EINVAL;
-    }
+  return id;
+}
 
-    if (!bt_addr_le_cmp(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) {
-        return -EALREADY;
-    }
+int bt_id_delete(u8_t id) {
+  if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) {
+    return -EINVAL;
+  }
 
-    if (id == bt_dev.adv_id && atomic_test_bit(bt_dev.flags,
-                                               BT_DEV_ADVERTISING)) {
-        return -EBUSY;
-    }
+  if (!bt_addr_le_cmp(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) {
+    return -EALREADY;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_CONN)) {
-        int err;
+  if (id == bt_dev.adv_id && atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return -EBUSY;
+  }
 
-        err = bt_unpair(id, NULL);
-        if (err) {
-            return err;
-        }
+  if (IS_ENABLED(CONFIG_BT_CONN)) {
+    int err;
+
+    err = bt_unpair(id, NULL);
+    if (err) {
+      return err;
     }
+  }
 
 #if defined(CONFIG_BT_PRIVACY)
-    (void)memset(bt_dev.irk[id], 0, 16);
+  (void)memset(bt_dev.irk[id], 0, 16);
 #endif
-    bt_addr_le_copy(&bt_dev.id_addr[id], BT_ADDR_LE_ANY);
+  bt_addr_le_copy(&bt_dev.id_addr[id], BT_ADDR_LE_ANY);
 
-    if (id == bt_dev.id_count - 1) {
-        bt_dev.id_count--;
-    }
+  if (id == bt_dev.id_count - 1) {
+    bt_dev.id_count--;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS) &&
-        atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        bt_settings_save_id();
-    }
+  if (IS_ENABLED(CONFIG_BT_SETTINGS) && atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    bt_settings_save_id();
+  }
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_HCI_VS_EXT)
-static uint8_t bt_read_static_addr(bt_addr_le_t *addr)
-{
-    struct bt_hci_rp_vs_read_static_addrs *rp;
-    struct net_buf *rsp;
-    int err, i;
-    u8_t cnt;
-    if (!(bt_dev.vs_commands[1] & BIT(0))) {
-        BT_WARN("Read Static Addresses command not available");
-        return 0;
-    }
-
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_STATIC_ADDRS, NULL, &rsp);
-    if (err) {
-        BT_WARN("Failed to read static addresses");
-        return 0;
-    }
-    rp = (void *)rsp->data;
-    cnt = MIN(rp->num_addrs, CONFIG_BT_ID_MAX);
+static uint8_t bt_read_static_addr(bt_addr_le_t *addr) {
+  struct bt_hci_rp_vs_read_static_addrs *rp;
+  struct net_buf                        *rsp;
+  int                                    err, i;
+  u8_t                                   cnt;
+  if (!(bt_dev.vs_commands[1] & BIT(0))) {
+    BT_WARN("Read Static Addresses command not available");
+    return 0;
+  }
 
-    for (i = 0; i < cnt; i++) {
-        addr[i].type = BT_ADDR_LE_RANDOM;
-        bt_addr_copy(&addr[i].a, &rp->a[i].bdaddr);
-    }
-    net_buf_unref(rsp);
-    if (!cnt) {
-        BT_WARN("No static addresses stored in controller");
-    }
-    return cnt;
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_STATIC_ADDRS, NULL, &rsp);
+  if (err) {
+    BT_WARN("Failed to read static addresses");
+    return 0;
+  }
+  rp  = (void *)rsp->data;
+  cnt = MIN(rp->num_addrs, CONFIG_BT_ID_MAX);
+
+  for (i = 0; i < cnt; i++) {
+    addr[i].type = BT_ADDR_LE_RANDOM;
+    bt_addr_copy(&addr[i].a, &rp->a[i].bdaddr);
+  }
+  net_buf_unref(rsp);
+  if (!cnt) {
+    BT_WARN("No static addresses stored in controller");
+  }
+  return cnt;
 }
 #elif defined(CONFIG_BT_CTLR)
 uint8_t bt_read_static_addr(bt_addr_le_t *addr);
 #endif /* CONFIG_BT_HCI_VS_EXT */
 
-int bt_setup_id_addr(void)
-{
+int bt_setup_id_addr(void) {
 #if defined(CONFIG_BT_HCI_VS_EXT) || defined(CONFIG_BT_CTLR)
-    /* Only read the addresses if the user has not already configured one or
-	 * more identities (!bt_dev.id_count).
-	 */
-    if (!bt_dev.id_count) {
-        bt_addr_le_t addrs[CONFIG_BT_ID_MAX];
+  /* Only read the addresses if the user has not already configured one or
+   * more identities (!bt_dev.id_count).
+   */
+  if (!bt_dev.id_count) {
+    bt_addr_le_t addrs[CONFIG_BT_ID_MAX];
 
-        bt_dev.id_count = bt_read_static_addr(addrs);
-        if (bt_dev.id_count) {
-            int i;
+    bt_dev.id_count = bt_read_static_addr(addrs);
+    if (bt_dev.id_count) {
+      int i;
 
-            for (i = 0; i < bt_dev.id_count; i++) {
-                id_create(i, &addrs[i], NULL);
-            }
+      for (i = 0; i < bt_dev.id_count; i++) {
+        id_create(i, &addrs[i], NULL);
+      }
 
-            return set_random_address(&bt_dev.id_addr[0].a);
-        }
+      return set_random_address(&bt_dev.id_addr[0].a);
     }
+  }
 #endif
-    return bt_id_create(NULL, NULL);
+  return bt_id_create(NULL, NULL);
 }
 
-bool bt_addr_le_is_bonded(u8_t id, const bt_addr_le_t *addr)
-{
-    if (IS_ENABLED(CONFIG_BT_SMP)) {
-        struct bt_keys *keys = bt_keys_find_addr(id, addr);
+bool bt_addr_le_is_bonded(u8_t id, const bt_addr_le_t *addr) {
+  if (IS_ENABLED(CONFIG_BT_SMP)) {
+    struct bt_keys *keys = bt_keys_find_addr(id, addr);
 
-        /* if there are any keys stored then device is bonded */
-        return keys && keys->keys;
-    } else {
-        return false;
-    }
+    /* if there are any keys stored then device is bonded */
+    return keys && keys->keys;
+  } else {
+    return false;
+  }
 }
 
-static bool valid_adv_param(const struct bt_le_adv_param *param, bool dir_adv)
-{
-    if (param->id >= bt_dev.id_count ||
-        !bt_addr_le_cmp(&bt_dev.id_addr[param->id], BT_ADDR_LE_ANY)) {
-        return false;
-    }
+static bool valid_adv_param(const struct bt_le_adv_param *param, bool dir_adv) {
+  if (param->id >= bt_dev.id_count || !bt_addr_le_cmp(&bt_dev.id_addr[param->id], BT_ADDR_LE_ANY)) {
+    return false;
+  }
 
 #if !defined(BFLB_BLE)
-    if (!(param->options & BT_LE_ADV_OPT_CONNECTABLE)) {
-        /*
-		 * BT Core 4.2 [Vol 2, Part E, 7.8.5]
-		 * The Advertising_Interval_Min and Advertising_Interval_Max
-		 * shall not be set to less than 0x00A0 (100 ms) if the
-		 * Advertising_Type is set to ADV_SCAN_IND or ADV_NONCONN_IND.
-		 */
-        if (bt_dev.hci_version < BT_HCI_VERSION_5_0 &&
-            param->interval_min < 0x00a0) {
-            return false;
-        }
+  if (!(param->options & BT_LE_ADV_OPT_CONNECTABLE)) {
+    /*
+     * BT Core 4.2 [Vol 2, Part E, 7.8.5]
+     * The Advertising_Interval_Min and Advertising_Interval_Max
+     * shall not be set to less than 0x00A0 (100 ms) if the
+     * Advertising_Type is set to ADV_SCAN_IND or ADV_NONCONN_IND.
+     */
+    if (bt_dev.hci_version < BT_HCI_VERSION_5_0 && param->interval_min < 0x00a0) {
+      return false;
     }
+  }
 #endif
 
-    if (is_wl_empty() &&
-        ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) ||
-         (param->options & BT_LE_ADV_OPT_FILTER_CONN))) {
-        return false;
-    }
+  if (is_wl_empty() && ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) || (param->options & BT_LE_ADV_OPT_FILTER_CONN))) {
+    return false;
+  }
 
-    if ((param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) || !dir_adv) {
-        if (param->interval_min > param->interval_max ||
+  if ((param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) || !dir_adv) {
+    if (param->interval_min > param->interval_max ||
 #if !defined(BFLB_BLE)
-            param->interval_min < 0x0020 ||
+        param->interval_min < 0x0020 ||
 #endif
-            param->interval_max > 0x4000) {
-            return false;
-        }
+        param->interval_max > 0x4000) {
+      return false;
     }
+  }
 
-    return true;
+  return true;
 }
 
-static inline bool ad_has_name(const struct bt_data *ad, size_t ad_len)
-{
-    int i;
+static inline bool ad_has_name(const struct bt_data *ad, size_t ad_len) {
+  int i;
 
-    for (i = 0; i < ad_len; i++) {
-        if (ad[i].type == BT_DATA_NAME_COMPLETE ||
-            ad[i].type == BT_DATA_NAME_SHORTENED) {
-            return true;
-        }
+  for (i = 0; i < ad_len; i++) {
+    if (ad[i].type == BT_DATA_NAME_COMPLETE || ad[i].type == BT_DATA_NAME_SHORTENED) {
+      return true;
     }
+  }
 
-    return false;
+  return false;
 }
 
-static int le_adv_update(const struct bt_data *ad, size_t ad_len,
-                         const struct bt_data *sd, size_t sd_len,
-                         bool connectable, bool use_name)
-{
-    struct bt_ad d[2] = {};
-    struct bt_data data;
-    int err;
-
-    d[0].data = ad;
-    d[0].len = ad_len;
-
-    err = set_ad(BT_HCI_OP_LE_SET_ADV_DATA, d, 1);
-    if (err) {
-        return err;
-    }
-
-    d[0].data = sd;
-    d[0].len = sd_len;
+static int le_adv_update(const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len, bool connectable, bool use_name) {
+  struct bt_ad   d[2] = {};
+  struct bt_data data;
+  int            err;
 
-    if (use_name) {
-        const char *name;
+  d[0].data = ad;
+  d[0].len  = ad_len;
 
-        if (sd) {
-            /* Cannot use name if name is already set */
-            if (ad_has_name(sd, sd_len)) {
-                return -EINVAL;
-            }
-        }
+  err = set_ad(BT_HCI_OP_LE_SET_ADV_DATA, d, 1);
+  if (err) {
+    return err;
+  }
 
-        name = bt_get_name();
-        data = (struct bt_data)BT_DATA(
-            BT_DATA_NAME_COMPLETE,
-            name, strlen(name));
+  d[0].data = sd;
+  d[0].len  = sd_len;
 
-        d[1].data = &data;
-        d[1].len = 1;
-    }
+  if (use_name) {
+    const char *name;
 
-    /*
-	 * We need to set SCAN_RSP when enabling advertising type that
-	 * allows for Scan Requests.
-	 *
-	 * If any data was not provided but we enable connectable
-	 * undirected advertising sd needs to be cleared from values set
-	 * by previous calls.
-	 * Clearing sd is done by calling set_ad() with NULL data and
-	 * zero len.
-	 * So following condition check is unusual but correct.
-	 */
-    if (d[0].data || d[1].data || connectable) {
-        err = set_ad(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, d, 2);
-        if (err) {
-            return err;
-        }
+    if (sd) {
+      /* Cannot use name if name is already set */
+      if (ad_has_name(sd, sd_len)) {
+        return -EINVAL;
+      }
+    }
+
+    name = bt_get_name();
+    data = (struct bt_data)BT_DATA(BT_DATA_NAME_COMPLETE, name, strlen(name));
+
+    d[1].data = &data;
+    d[1].len  = 1;
+  }
+
+  /*
+   * We need to set SCAN_RSP when enabling advertising type that
+   * allows for Scan Requests.
+   *
+   * If any data was not provided but we enable connectable
+   * undirected advertising sd needs to be cleared from values set
+   * by previous calls.
+   * Clearing sd is done by calling set_ad() with NULL data and
+   * zero len.
+   * So following condition check is unusual but correct.
+   */
+  if (d[0].data || d[1].data || connectable) {
+    err = set_ad(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, d, 2);
+    if (err) {
+      return err;
     }
+  }
 
-    return 0;
+  return 0;
 }
 
-int bt_le_adv_update_data(const struct bt_data *ad, size_t ad_len,
-                          const struct bt_data *sd, size_t sd_len)
-{
-    bool connectable, use_name;
+int bt_le_adv_update_data(const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len) {
+  bool connectable, use_name;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        return -EAGAIN;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return -EAGAIN;
+  }
 
-    connectable = atomic_test_bit(bt_dev.flags,
-                                  BT_DEV_ADVERTISING_CONNECTABLE);
-    use_name = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING_NAME);
+  connectable = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING_CONNECTABLE);
+  use_name    = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING_NAME);
 
-    return le_adv_update(ad, ad_len, sd, sd_len, connectable, use_name);
+  return le_adv_update(ad, ad_len, sd, sd_len, connectable, use_name);
 }
 
-int bt_le_adv_start_internal(const struct bt_le_adv_param *param,
-                             const struct bt_data *ad, size_t ad_len,
-                             const struct bt_data *sd, size_t sd_len,
-                             const bt_addr_le_t *peer)
-{
-    struct bt_hci_cp_le_set_adv_param set_param;
-    const bt_addr_le_t *id_addr;
-    struct net_buf *buf;
-    bool dir_adv = (peer != NULL);
-    int err = 0;
+int bt_le_adv_start_internal(const struct bt_le_adv_param *param, const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len, const bt_addr_le_t *peer) {
+  struct bt_hci_cp_le_set_adv_param set_param;
+  const bt_addr_le_t               *id_addr;
+  struct net_buf                   *buf;
+  bool                              dir_adv = (peer != NULL);
+  int                               err     = 0;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        return -EAGAIN;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    return -EAGAIN;
+  }
 
-    if (!valid_adv_param(param, dir_adv)) {
-        return -EINVAL;
-    }
+  if (!valid_adv_param(param, dir_adv)) {
+    return -EINVAL;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        return -EALREADY;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return -EALREADY;
+  }
 
-    (void)memset(&set_param, 0, sizeof(set_param));
+  (void)memset(&set_param, 0, sizeof(set_param));
 
-    set_param.min_interval = sys_cpu_to_le16(param->interval_min);
-    set_param.max_interval = sys_cpu_to_le16(param->interval_max);
-    set_param.channel_map = adv_ch_map;
+  set_param.min_interval = sys_cpu_to_le16(param->interval_min);
+  set_param.max_interval = sys_cpu_to_le16(param->interval_max);
+  set_param.channel_map  = adv_ch_map;
 
-    if (bt_dev.adv_id != param->id) {
-        atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
-    }
+  if (bt_dev.adv_id != param->id) {
+    atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
+  }
 
 #if defined(CONFIG_BT_WHITELIST)
-    if ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) &&
-        (param->options & BT_LE_ADV_OPT_FILTER_CONN)) {
-        set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_BOTH;
-    } else if (param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) {
-        set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_SCAN_REQ;
-    } else if (param->options & BT_LE_ADV_OPT_FILTER_CONN) {
-        set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_CONN_IND;
-    } else {
+  if ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) && (param->options & BT_LE_ADV_OPT_FILTER_CONN)) {
+    set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_BOTH;
+  } else if (param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) {
+    set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_SCAN_REQ;
+  } else if (param->options & BT_LE_ADV_OPT_FILTER_CONN) {
+    set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_CONN_IND;
+  } else {
 #else
-    {
+  {
 #endif /* defined(CONFIG_BT_WHITELIST) */
-        set_param.filter_policy = BT_LE_ADV_FP_NO_WHITELIST;
-    }
+    set_param.filter_policy = BT_LE_ADV_FP_NO_WHITELIST;
+  }
 
-    /* Set which local identity address we're advertising with */
-    bt_dev.adv_id = param->id;
-    id_addr = &bt_dev.id_addr[param->id];
+  /* Set which local identity address we're advertising with */
+  bt_dev.adv_id = param->id;
+  id_addr       = &bt_dev.id_addr[param->id];
 
-    if (param->options & BT_LE_ADV_OPT_CONNECTABLE) {
-        if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
-            !(param->options & BT_LE_ADV_OPT_USE_IDENTITY)) {
+  if (param->options & BT_LE_ADV_OPT_CONNECTABLE) {
+    if (IS_ENABLED(CONFIG_BT_PRIVACY) && !(param->options & BT_LE_ADV_OPT_USE_IDENTITY)) {
 #if defined(CONFIG_BT_STACK_PTS)
-            if (param->addr_type == BT_ADDR_TYPE_RPA)
-                err = le_set_private_addr(param->id);
-            else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
-                err = le_set_non_resolv_private_addr(param->id);
+      if (param->addr_type == BT_ADDR_TYPE_RPA)
+        err = le_set_private_addr(param->id);
+      else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
+        err = le_set_non_resolv_private_addr(param->id);
 #else
-            err = le_set_private_addr(param->id);
+      err = le_set_private_addr(param->id);
 #endif
-            if (err) {
-                return err;
-            }
+      if (err) {
+        return err;
+      }
 
-            if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+      if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
 #if defined(CONFIG_BT_STACK_PTS)
-                if (param->addr_type == BT_ADDR_LE_PUBLIC)
-                    set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
-                if (param->addr_type == BT_ADDR_TYPE_RPA)
-                    set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-                else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
-                    set_param.own_addr_type = BT_ADDR_LE_RANDOM;
+        if (param->addr_type == BT_ADDR_LE_PUBLIC)
+          set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
+        if (param->addr_type == BT_ADDR_TYPE_RPA)
+          set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+        else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
+          set_param.own_addr_type = BT_ADDR_LE_RANDOM;
 #else
-                set_param.own_addr_type =
-                    BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-#endif
-            } else {
-                set_param.own_addr_type = BT_ADDR_LE_RANDOM;
-            }
-        } else {
-            /*
-			 * If Static Random address is used as Identity
-			 * address we need to restore it before advertising
-			 * is enabled. Otherwise NRPA used for active scan
-			 * could be used for advertising.
-			 */
-            if (id_addr->type == BT_ADDR_LE_RANDOM) {
-                err = set_random_address(&id_addr->a);
-                if (err) {
-                    return err;
-                }
-            }
-
-            set_param.own_addr_type = id_addr->type;
+        set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+#endif
+      } else {
+        set_param.own_addr_type = BT_ADDR_LE_RANDOM;
+      }
+    } else {
+      /*
+       * If Static Random address is used as Identity
+       * address we need to restore it before advertising
+       * is enabled. Otherwise NRPA used for active scan
+       * could be used for advertising.
+       */
+      if (id_addr->type == BT_ADDR_LE_RANDOM) {
+        err = set_random_address(&id_addr->a);
+        if (err) {
+          return err;
         }
+      }
 
-        if (dir_adv) {
-            if (param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) {
-                set_param.type = BT_LE_ADV_DIRECT_IND_LOW_DUTY;
-            } else {
-                set_param.type = BT_LE_ADV_DIRECT_IND;
-            }
-
-            bt_addr_le_copy(&set_param.direct_addr, peer);
-
-            if (IS_ENABLED(CONFIG_BT_SMP) &&
-                !IS_ENABLED(CONFIG_BT_PRIVACY) &&
-                BT_FEAT_LE_PRIVACY(bt_dev.le.features) &&
-                (param->options & BT_LE_ADV_OPT_DIR_ADDR_RPA)) {
-                /* This will not use RPA for our own address
-				 * since we have set zeroed out the local IRK.
-				 */
-                set_param.own_addr_type |=
-                    BT_HCI_OWN_ADDR_RPA_MASK;
-            }
-        } else {
-            set_param.type = BT_LE_ADV_IND;
-        }
+      set_param.own_addr_type = id_addr->type;
+    }
+
+    if (dir_adv) {
+      if (param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) {
+        set_param.type = BT_LE_ADV_DIRECT_IND_LOW_DUTY;
+      } else {
+        set_param.type = BT_LE_ADV_DIRECT_IND;
+      }
+
+      bt_addr_le_copy(&set_param.direct_addr, peer);
+
+      if (IS_ENABLED(CONFIG_BT_SMP) && !IS_ENABLED(CONFIG_BT_PRIVACY) && BT_FEAT_LE_PRIVACY(bt_dev.le.features) && (param->options & BT_LE_ADV_OPT_DIR_ADDR_RPA)) {
+        /* This will not use RPA for our own address
+         * since we have set zeroed out the local IRK.
+         */
+        set_param.own_addr_type |= BT_HCI_OWN_ADDR_RPA_MASK;
+      }
     } else {
-        if (param->options & BT_LE_ADV_OPT_USE_IDENTITY) {
-            if (id_addr->type == BT_ADDR_LE_RANDOM) {
-                err = set_random_address(&id_addr->a);
-            }
+      set_param.type = BT_LE_ADV_IND;
+    }
+  } else {
+    if (param->options & BT_LE_ADV_OPT_USE_IDENTITY) {
+      if (id_addr->type == BT_ADDR_LE_RANDOM) {
+        err = set_random_address(&id_addr->a);
+      }
 
-            set_param.own_addr_type = id_addr->type;
-        } else {
+      set_param.own_addr_type = id_addr->type;
+    } else {
 #if defined(BFLB_BLE) && !defined(CONFIG_BT_MESH)
 #if defined(CONFIG_BT_STACK_PTS)
-            if (param->addr_type == BT_ADDR_TYPE_RPA)
-                err = le_set_private_addr(param->id);
-            else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
-                err = le_set_non_resolv_private_addr(param->id);
+      if (param->addr_type == BT_ADDR_TYPE_RPA)
+        err = le_set_private_addr(param->id);
+      else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
+        err = le_set_non_resolv_private_addr(param->id);
 #else
-//#if !defined(CONFIG_BT_ADV_WITH_PUBLIC_ADDR)
-//err = le_set_private_addr(param->id);
-//#endif
-#endif //CONFIG_BT_STACK_PTS
+// #if !defined(CONFIG_BT_ADV_WITH_PUBLIC_ADDR)
+// err = le_set_private_addr(param->id);
+// #endif
+#endif // CONFIG_BT_STACK_PTS
 #if defined(CONFIG_BT_STACK_PTS)
-            if (param->addr_type == BT_ADDR_LE_PUBLIC)
-                set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
-            else
+      if (param->addr_type == BT_ADDR_LE_PUBLIC)
+        set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
+      else
 #endif
-                //set_param.own_addr_type = BT_ADDR_LE_RANDOM;
-                //#if defined(CONFIG_BT_ADV_WITH_PUBLIC_ADDR)
-                set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
-                //#endif
+        // set_param.own_addr_type = BT_ADDR_LE_RANDOM;
+        // #if defined(CONFIG_BT_ADV_WITH_PUBLIC_ADDR)
+        set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
+        // #endif
 #endif
-        }
+    }
 
-        if (err) {
-            return err;
-        }
+    if (err) {
+      return err;
+    }
 
-        if (sd) {
-            set_param.type = BT_LE_ADV_SCAN_IND;
-        } else {
-            set_param.type = BT_LE_ADV_NONCONN_IND;
-        }
+    if (sd) {
+      set_param.type = BT_LE_ADV_SCAN_IND;
+    } else {
+      set_param.type = BT_LE_ADV_NONCONN_IND;
     }
+  }
 
 #if defined(CONFIG_BT_STACK_PTS)
-    if (set_param.own_addr_type == BT_ADDR_LE_PUBLIC) {
-        atomic_set_bit(bt_dev.flags, BT_DEV_ADV_ADDRESS_IS_PUBLIC);
-    }
+  if (set_param.own_addr_type == BT_ADDR_LE_PUBLIC) {
+    atomic_set_bit(bt_dev.flags, BT_DEV_ADV_ADDRESS_IS_PUBLIC);
+  }
 #endif
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param));
-    if (!buf) {
-        return -ENOBUFS;
-    }
-
-    net_buf_add_mem(buf, &set_param, sizeof(set_param));
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL);
-    if (err) {
-        return err;
-    }
+  net_buf_add_mem(buf, &set_param, sizeof(set_param));
 
-    if (!dir_adv) {
-        err = le_adv_update(ad, ad_len, sd, sd_len,
-                            param->options & BT_LE_ADV_OPT_CONNECTABLE,
-                            param->options & BT_LE_ADV_OPT_USE_NAME);
-        if (err) {
-            return err;
-        }
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    err = set_advertise_enable(true);
+  if (!dir_adv) {
+    err = le_adv_update(ad, ad_len, sd, sd_len, param->options & BT_LE_ADV_OPT_CONNECTABLE, param->options & BT_LE_ADV_OPT_USE_NAME);
     if (err) {
-        return err;
+      return err;
     }
+  }
+
+  err = set_advertise_enable(true);
+  if (err) {
+    return err;
+  }
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_KEEP_ADVERTISING,
-                      !(param->options & BT_LE_ADV_OPT_ONE_TIME));
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_KEEP_ADVERTISING, !(param->options & BT_LE_ADV_OPT_ONE_TIME));
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_NAME,
-                      param->options & BT_LE_ADV_OPT_USE_NAME);
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_NAME, param->options & BT_LE_ADV_OPT_USE_NAME);
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_CONNECTABLE,
-                      param->options & BT_LE_ADV_OPT_CONNECTABLE);
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_CONNECTABLE, param->options & BT_LE_ADV_OPT_CONNECTABLE);
 
 #if defined(BFLB_HOST_ASSISTANT)
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_ASSIST_RUN) && host_assist_cb && host_assist_cb->le_adv_cb)
-        host_assist_cb->le_adv_cb(param, ad, ad_len, sd, sd_len);
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_ASSIST_RUN) && host_assist_cb && host_assist_cb->le_adv_cb)
+    host_assist_cb->le_adv_cb(param, ad, ad_len, sd, sd_len);
 #endif
 
-    return 0;
+  return 0;
 }
 #if defined(BFLB_BLE)
-int bt_le_read_rssi(u16_t handle, int8_t *rssi)
-{
-    struct bt_hci_cp_read_rssi *le_rssi;
-    struct bt_hci_rp_read_rssi *rsp_rssi;
-    struct net_buf *buf;
-    struct net_buf *rsp;
-    int ret;
+int bt_le_read_rssi(u16_t handle, int8_t *rssi) {
+  struct bt_hci_cp_read_rssi *le_rssi;
+  struct bt_hci_rp_read_rssi *rsp_rssi;
+  struct net_buf             *buf;
+  struct net_buf             *rsp;
+  int                         ret;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_READ_RSSI, sizeof(*le_rssi));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_READ_RSSI, sizeof(*le_rssi));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    le_rssi = net_buf_add(buf, sizeof(*le_rssi));
-    memset(le_rssi, 0, sizeof(*le_rssi));
+  le_rssi = net_buf_add(buf, sizeof(*le_rssi));
+  memset(le_rssi, 0, sizeof(*le_rssi));
 
-    le_rssi->handle = handle;
+  le_rssi->handle = handle;
 
-    ret = bt_hci_cmd_send_sync(BT_HCI_OP_READ_RSSI, buf, &rsp);
+  ret = bt_hci_cmd_send_sync(BT_HCI_OP_READ_RSSI, buf, &rsp);
 
-    if (ret) {
-        return ret;
-    }
+  if (ret) {
+    return ret;
+  }
 
-    rsp_rssi = (struct bt_hci_rp_read_rssi *)rsp->data;
-    *rssi = rsp_rssi->rssi;
+  rsp_rssi = (struct bt_hci_rp_read_rssi *)rsp->data;
+  *rssi    = rsp_rssi->rssi;
 
-    net_buf_unref(rsp);
+  net_buf_unref(rsp);
 
-    return ret;
+  return ret;
 }
 
-int set_adv_enable(bool enable)
-{
-    int err;
-    err = set_advertise_enable(enable);
-    if (err) {
-        return err;
-    }
+int set_adv_enable(bool enable) {
+  int err;
+  err = set_advertise_enable(enable);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-int set_adv_param(const struct bt_le_adv_param *param)
-{
-    struct bt_hci_cp_le_set_adv_param set_param;
-    const bt_addr_le_t *id_addr;
-    struct net_buf *buf;
-    int err = 0;
+int set_adv_param(const struct bt_le_adv_param *param) {
+  struct bt_hci_cp_le_set_adv_param set_param;
+  const bt_addr_le_t               *id_addr;
+  struct net_buf                   *buf;
+  int                               err = 0;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        return -EAGAIN;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    return -EAGAIN;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        return -EALREADY;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return -EALREADY;
+  }
 
-    (void)memset(&set_param, 0, sizeof(set_param));
+  (void)memset(&set_param, 0, sizeof(set_param));
 
-    set_param.min_interval = sys_cpu_to_le16(param->interval_min);
-    set_param.max_interval = sys_cpu_to_le16(param->interval_max);
-    set_param.channel_map = 0x07;
+  set_param.min_interval = sys_cpu_to_le16(param->interval_min);
+  set_param.max_interval = sys_cpu_to_le16(param->interval_max);
+  set_param.channel_map  = 0x07;
 
-    if (bt_dev.adv_id != param->id) {
-        atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
-    }
+  if (bt_dev.adv_id != param->id) {
+    atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
+  }
 
 #if defined(CONFIG_BT_WHITELIST)
-    if ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) &&
-        (param->options & BT_LE_ADV_OPT_FILTER_CONN)) {
-        set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_BOTH;
-    } else if (param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) {
-        set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_SCAN_REQ;
-    } else if (param->options & BT_LE_ADV_OPT_FILTER_CONN) {
-        set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_CONN_IND;
-    } else {
+  if ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) && (param->options & BT_LE_ADV_OPT_FILTER_CONN)) {
+    set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_BOTH;
+  } else if (param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) {
+    set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_SCAN_REQ;
+  } else if (param->options & BT_LE_ADV_OPT_FILTER_CONN) {
+    set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_CONN_IND;
+  } else {
 #else
-    {
+  {
 #endif /* defined(CONFIG_BT_WHITELIST) */
-        set_param.filter_policy = BT_LE_ADV_FP_NO_WHITELIST;
-    }
+    set_param.filter_policy = BT_LE_ADV_FP_NO_WHITELIST;
+  }
 
-    /* Set which local identity address we're advertising with */
-    bt_dev.adv_id = param->id;
-    id_addr = &bt_dev.id_addr[param->id];
+  /* Set which local identity address we're advertising with */
+  bt_dev.adv_id = param->id;
+  id_addr       = &bt_dev.id_addr[param->id];
 
-    if (param->options & BT_LE_ADV_OPT_CONNECTABLE) {
-        if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
-            !(param->options & BT_LE_ADV_OPT_USE_IDENTITY)) {
+  if (param->options & BT_LE_ADV_OPT_CONNECTABLE) {
+    if (IS_ENABLED(CONFIG_BT_PRIVACY) && !(param->options & BT_LE_ADV_OPT_USE_IDENTITY)) {
 #if defined(CONFIG_BT_STACK_PTS)
-            if (param->addr_type == BT_ADDR_TYPE_RPA)
-                err = le_set_private_addr(param->id);
-            else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
-                err = le_set_non_resolv_private_addr(param->id);
+      if (param->addr_type == BT_ADDR_TYPE_RPA)
+        err = le_set_private_addr(param->id);
+      else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
+        err = le_set_non_resolv_private_addr(param->id);
 #else
-            err = le_set_private_addr(param->id);
+      err = le_set_private_addr(param->id);
 #endif
-            if (err) {
-                return err;
-            }
+      if (err) {
+        return err;
+      }
 
-            if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+      if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
 #if defined(CONFIG_BT_STACK_PTS)
-                if (param->addr_type == BT_ADDR_LE_PUBLIC)
-                    set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
-                if (param->addr_type == BT_ADDR_TYPE_RPA)
-                    set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-                else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
-                    set_param.own_addr_type = BT_ADDR_LE_RANDOM;
+        if (param->addr_type == BT_ADDR_LE_PUBLIC)
+          set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
+        if (param->addr_type == BT_ADDR_TYPE_RPA)
+          set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+        else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
+          set_param.own_addr_type = BT_ADDR_LE_RANDOM;
 #else
-                set_param.own_addr_type =
-                    BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-#endif
-            } else {
-                set_param.own_addr_type = BT_ADDR_LE_RANDOM;
-            }
-        } else {
-            /*
-			 * If Static Random address is used as Identity
-			 * address we need to restore it before advertising
-			 * is enabled. Otherwise NRPA used for active scan
-			 * could be used for advertising.
-			 */
-            if (id_addr->type == BT_ADDR_LE_RANDOM) {
-                err = set_random_address(&id_addr->a);
-                if (err) {
-                    return err;
-                }
-            }
-
-            set_param.own_addr_type = id_addr->type;
+        set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+#endif
+      } else {
+        set_param.own_addr_type = BT_ADDR_LE_RANDOM;
+      }
+    } else {
+      /*
+       * If Static Random address is used as Identity
+       * address we need to restore it before advertising
+       * is enabled. Otherwise NRPA used for active scan
+       * could be used for advertising.
+       */
+      if (id_addr->type == BT_ADDR_LE_RANDOM) {
+        err = set_random_address(&id_addr->a);
+        if (err) {
+          return err;
         }
+      }
+
+      set_param.own_addr_type = id_addr->type;
+    }
 
-        set_param.type = BT_LE_ADV_IND;
+    set_param.type = BT_LE_ADV_IND;
 
-    } else {
-        if (param->options & BT_LE_ADV_OPT_USE_IDENTITY) {
-            if (id_addr->type == BT_ADDR_LE_RANDOM) {
-                err = set_random_address(&id_addr->a);
-            }
+  } else {
+    if (param->options & BT_LE_ADV_OPT_USE_IDENTITY) {
+      if (id_addr->type == BT_ADDR_LE_RANDOM) {
+        err = set_random_address(&id_addr->a);
+      }
 
-            set_param.own_addr_type = id_addr->type;
-        } else {
+      set_param.own_addr_type = id_addr->type;
+    } else {
 #if defined(BFLB_BLE) && !defined(CONFIG_BT_MESH)
 #if defined(CONFIG_BT_STACK_PTS)
-            if (param->addr_type == BT_ADDR_TYPE_RPA)
-                err = le_set_private_addr(param->id);
-            else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
-                err = le_set_non_resolv_private_addr(param->id);
+      if (param->addr_type == BT_ADDR_TYPE_RPA)
+        err = le_set_private_addr(param->id);
+      else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
+        err = le_set_non_resolv_private_addr(param->id);
 #else
-            err = le_set_private_addr(param->id);
-#endif //CONFIG_BT_STACK_PTS
+      err = le_set_private_addr(param->id);
+#endif // CONFIG_BT_STACK_PTS
 #if defined(CONFIG_BT_STACK_PTS)
-            if (param->addr_type == BT_ADDR_LE_PUBLIC)
-                set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
-            else
+      if (param->addr_type == BT_ADDR_LE_PUBLIC)
+        set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
+      else
 #endif
-                set_param.own_addr_type = BT_ADDR_LE_RANDOM;
+        set_param.own_addr_type = BT_ADDR_LE_RANDOM;
 #endif
-        }
-
-        if (err) {
-            return err;
-        }
-
-        set_param.type = BT_LE_ADV_NONCONN_IND;
     }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param));
-    if (!buf) {
-        return -ENOBUFS;
+    if (err) {
+      return err;
     }
 
-    net_buf_add_mem(buf, &set_param, sizeof(set_param));
+    set_param.type = BT_LE_ADV_NONCONN_IND;
+  }
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL);
-    if (err) {
-        return err;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_KEEP_ADVERTISING,
-                      !(param->options & BT_LE_ADV_OPT_ONE_TIME));
+  net_buf_add_mem(buf, &set_param, sizeof(set_param));
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_NAME,
-                      param->options & BT_LE_ADV_OPT_USE_NAME);
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_CONNECTABLE,
-                      param->options & BT_LE_ADV_OPT_CONNECTABLE);
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_KEEP_ADVERTISING, !(param->options & BT_LE_ADV_OPT_ONE_TIME));
 
-    return 0;
-}
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_NAME, param->options & BT_LE_ADV_OPT_USE_NAME);
 
-int set_ad_and_rsp_d(u16_t hci_op, u8_t *data, u32_t ad_len)
-{
-    struct net_buf *buf;
-    u32_t len;
-    u8_t size;
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_CONNECTABLE, param->options & BT_LE_ADV_OPT_CONNECTABLE);
 
-    if (BT_HCI_OP_LE_SET_ADV_DATA == hci_op) {
-        size = sizeof(struct bt_hci_cp_le_set_adv_data);
+  return 0;
+}
 
-    } else if (BT_HCI_OP_LE_SET_SCAN_RSP_DATA == hci_op) {
-        size = sizeof(struct bt_hci_cp_le_set_scan_rsp_data);
+int set_ad_and_rsp_d(u16_t hci_op, u8_t *data, u32_t ad_len) {
+  struct net_buf *buf;
+  u32_t           len;
+  u8_t            size;
 
-    } else
-        return -ENOTSUP;
+  if (BT_HCI_OP_LE_SET_ADV_DATA == hci_op) {
+    size = sizeof(struct bt_hci_cp_le_set_adv_data);
 
-    buf = bt_hci_cmd_create(hci_op, size);
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  } else if (BT_HCI_OP_LE_SET_SCAN_RSP_DATA == hci_op) {
+    size = sizeof(struct bt_hci_cp_le_set_scan_rsp_data);
 
-    if (BT_HCI_OP_LE_SET_ADV_DATA == hci_op) {
-        struct bt_hci_cp_le_set_adv_data *set_data = net_buf_add(buf, size);
-        memset(set_data, 0, size);
-        set_data->len = ad_len;
+  } else
+    return -ENOTSUP;
 
-        if (set_data->len > 30) {
-            len = 30 - (set_data->len);
-            if (!len) {
-                net_buf_unref(buf);
-                return -ENOBUFS;
-            }
-        }
+  buf = bt_hci_cmd_create(hci_op, size);
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-        memcpy(set_data->data, data, set_data->len);
+  if (BT_HCI_OP_LE_SET_ADV_DATA == hci_op) {
+    struct bt_hci_cp_le_set_adv_data *set_data = net_buf_add(buf, size);
+    memset(set_data, 0, size);
+    set_data->len = ad_len;
 
-    } else if (BT_HCI_OP_LE_SET_SCAN_RSP_DATA == hci_op) {
-        struct bt_hci_cp_le_set_scan_rsp_data *set_data = net_buf_add(buf, size);
-        memset(set_data, 0, size);
+    if (set_data->len > 30) {
+      len = 30 - (set_data->len);
+      if (!len) {
+        net_buf_unref(buf);
+        return -ENOBUFS;
+      }
+    }
 
-        set_data->len = ad_len;
+    memcpy(set_data->data, data, set_data->len);
 
-        if (set_data->len > 30) {
-            len = 30 - (set_data->len);
-            if (!len) {
-                net_buf_unref(buf);
-                return -ENOBUFS;
-            }
-        }
+  } else if (BT_HCI_OP_LE_SET_SCAN_RSP_DATA == hci_op) {
+    struct bt_hci_cp_le_set_scan_rsp_data *set_data = net_buf_add(buf, size);
+    memset(set_data, 0, size);
 
-        memcpy(set_data->data, data, set_data->len);
+    set_data->len = ad_len;
 
-    } else
+    if (set_data->len > 30) {
+      len = 30 - (set_data->len);
+      if (!len) {
+        net_buf_unref(buf);
         return -ENOBUFS;
+      }
+    }
+
+    memcpy(set_data->data, data, set_data->len);
+
+  } else
+    return -ENOBUFS;
 
-    return bt_hci_cmd_send_sync(hci_op, buf, NULL);
+  return bt_hci_cmd_send_sync(hci_op, buf, NULL);
 }
 
-int set_adv_channel_map(u8_t channel)
-{
-    int err = 0;
+int set_adv_channel_map(u8_t channel) {
+  int err = 0;
 
-    if (channel >= 1 && channel <= 7) {
-        adv_ch_map = channel;
-    } else {
-        err = -1;
-    }
+  if (channel >= 1 && channel <= 7) {
+    adv_ch_map = channel;
+  } else {
+    err = -1;
+  }
 
-    return err;
+  return err;
 }
 
-int bt_get_local_public_address(bt_addr_le_t *adv_addr)
-{
-    int err = 0;
+int bt_get_local_public_address(bt_addr_le_t *adv_addr) {
+  int err = 0;
 
-    bt_addr_le_copy(adv_addr, bt_dev.id_addr);
-    return err;
+  bt_addr_le_copy(adv_addr, bt_dev.id_addr);
+  return err;
 }
 
-int bt_get_local_ramdon_address(bt_addr_le_t *adv_addr)
-{
-    int err = 0;
+int bt_get_local_ramdon_address(bt_addr_le_t *adv_addr) {
+  int err = 0;
 
-    bt_addr_le_copy(adv_addr, &bt_dev.random_addr);
-    return err;
+  bt_addr_le_copy(adv_addr, &bt_dev.random_addr);
+  return err;
 }
 #endif
 
-int bt_le_adv_start(const struct bt_le_adv_param *param,
-                    const struct bt_data *ad, size_t ad_len,
-                    const struct bt_data *sd, size_t sd_len)
-{
-    if (param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) {
-        return -EINVAL;
-    }
+int bt_le_adv_start(const struct bt_le_adv_param *param, const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len) {
+  if (param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) {
+    return -EINVAL;
+  }
 
-    return bt_le_adv_start_internal(param, ad, ad_len, sd, sd_len, NULL);
+  return bt_le_adv_start_internal(param, ad, ad_len, sd, sd_len, NULL);
 }
 
-int bt_le_adv_stop(void)
-{
-    int err;
+int bt_le_adv_stop(void) {
+  int err;
 
-    /* Make sure advertising is not re-enabled later even if it's not
-	 * currently enabled (i.e. BT_DEV_ADVERTISING is not set).
-	 */
-    atomic_clear_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING);
+  /* Make sure advertising is not re-enabled later even if it's not
+   * currently enabled (i.e. BT_DEV_ADVERTISING is not set).
+   */
+  atomic_clear_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING);
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        return 0;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return 0;
+  }
 
-    err = set_advertise_enable(false);
-    if (err) {
-        return err;
-    }
+  err = set_advertise_enable(false);
+  if (err) {
+    return err;
+  }
 
-    if (!IS_ENABLED(CONFIG_BT_PRIVACY)) {
-        /* If active scan is ongoing set NRPA */
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) &&
-            atomic_test_bit(bt_dev.flags, BT_DEV_ACTIVE_SCAN)) {
-            le_set_private_addr(bt_dev.adv_id);
-        }
+  if (!IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    /* If active scan is ongoing set NRPA */
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) && atomic_test_bit(bt_dev.flags, BT_DEV_ACTIVE_SCAN)) {
+      le_set_private_addr(bt_dev.adv_id);
     }
+  }
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BLE_MULTI_ADV)
-static int set_ad_data(u16_t hci_op, const uint8_t *ad_data, int ad_len)
-{
-    struct bt_hci_cp_le_set_adv_data *set_data;
-    struct net_buf *buf;
+static int set_ad_data(u16_t hci_op, const uint8_t *ad_data, int ad_len) {
+  struct bt_hci_cp_le_set_adv_data *set_data;
+  struct net_buf                   *buf;
 
-    buf = bt_hci_cmd_create(hci_op, sizeof(*set_data));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(hci_op, sizeof(*set_data));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    if (ad_len > 31)
-        return -EINVAL;
+  if (ad_len > 31)
+    return -EINVAL;
 
-    set_data = net_buf_add(buf, sizeof(*set_data));
+  set_data = net_buf_add(buf, sizeof(*set_data));
 
-    memset(set_data, 0, sizeof(*set_data));
-    memcpy(set_data->data, ad_data, ad_len);
-    set_data->len = ad_len;
+  memset(set_data, 0, sizeof(*set_data));
+  memcpy(set_data->data, ad_data, ad_len);
+  set_data->len = ad_len;
 
-    return bt_hci_cmd_send_sync(hci_op, buf, NULL);
+  return bt_hci_cmd_send_sync(hci_op, buf, NULL);
 }
 
-int bt_le_adv_start_instant(const struct bt_le_adv_param *param,
-                            const uint8_t *ad_data, size_t ad_len,
-                            const uint8_t *sd_data, size_t sd_len)
-{
-    struct bt_hci_cp_le_set_adv_param set_param;
-    struct net_buf *buf;
-    const bt_addr_le_t *id_addr;
-    int err;
+int bt_le_adv_start_instant(const struct bt_le_adv_param *param, const uint8_t *ad_data, size_t ad_len, const uint8_t *sd_data, size_t sd_len) {
+  struct bt_hci_cp_le_set_adv_param set_param;
+  struct net_buf                   *buf;
+  const bt_addr_le_t               *id_addr;
+  int                               err;
 
-    bt_le_adv_stop();
+  bt_le_adv_stop();
 
-    if (!valid_adv_param(param, false)) {
-        return -EINVAL;
-    }
+  if (!valid_adv_param(param, false)) {
+    return -EINVAL;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        return -EALREADY;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return -EALREADY;
+  }
 
-    err = set_ad_data(BT_HCI_OP_LE_SET_ADV_DATA, ad_data, ad_len);
+  err = set_ad_data(BT_HCI_OP_LE_SET_ADV_DATA, ad_data, ad_len);
+  if (err) {
+    return err;
+  }
+
+  /*
+   * We need to set SCAN_RSP when enabling advertising type that allows
+   * for Scan Requests.
+   *
+   * If sd was not provided but we enable connectable undirected
+   * advertising sd needs to be cleared from values set by previous calls.
+   * Clearing sd is done by calling set_ad() with NULL data and zero len.
+   * So following condition check is unusual but correct.
+   */
+  if (sd_len || (param->options & BT_LE_ADV_OPT_CONNECTABLE)) {
+    err = set_ad_data(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, sd_data, sd_len);
     if (err) {
-        return err;
+      return err;
     }
+  }
 
-    /*
-     * We need to set SCAN_RSP when enabling advertising type that allows
-     * for Scan Requests.
-     *
-     * If sd was not provided but we enable connectable undirected
-     * advertising sd needs to be cleared from values set by previous calls.
-     * Clearing sd is done by calling set_ad() with NULL data and zero len.
-     * So following condition check is unusual but correct.
-     */
-    if (sd_len || (param->options & BT_LE_ADV_OPT_CONNECTABLE)) {
-        err = set_ad_data(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, sd_data, sd_len);
-        if (err) {
-            return err;
-        }
-    }
+  memset(&set_param, 0, sizeof(set_param));
 
-    memset(&set_param, 0, sizeof(set_param));
-
-    set_param.min_interval = sys_cpu_to_le16(param->interval_min);
-    set_param.max_interval = sys_cpu_to_le16(param->interval_max);
-    set_param.channel_map = 0x07;
-
-    bt_dev.adv_id = param->id;
-    id_addr = &bt_dev.id_addr[param->id];
-
-    if (param->options & BT_LE_ADV_OPT_CONNECTABLE) {
-        if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-            err = le_set_private_addr(bt_dev.adv_id);
-            if (err) {
-                return err;
-            }
-
-            if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
-                set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-            } else {
-                set_param.own_addr_type = BT_ADDR_LE_RANDOM;
-            }
-        } else {
-            /*
-             * If Static Random address is used as Identity
-             * address we need to restore it before advertising
-             * is enabled. Otherwise NRPA used for active scan
-             * could be used for advertising.
-             */
-            if (id_addr->type == BT_ADDR_LE_RANDOM) {
-                err = set_random_address(&id_addr->a);
-                if (err) {
-                    return err;
-                }
-            }
-            set_param.own_addr_type = id_addr->type;
-        }
+  set_param.min_interval = sys_cpu_to_le16(param->interval_min);
+  set_param.max_interval = sys_cpu_to_le16(param->interval_max);
+  set_param.channel_map  = 0x07;
+
+  bt_dev.adv_id = param->id;
+  id_addr       = &bt_dev.id_addr[param->id];
+
+  if (param->options & BT_LE_ADV_OPT_CONNECTABLE) {
+    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+      err = le_set_private_addr(bt_dev.adv_id);
+      if (err) {
+        return err;
+      }
 
-        set_param.type = BT_LE_ADV_IND;
+      if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+        set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+      } else {
+        set_param.own_addr_type = BT_ADDR_LE_RANDOM;
+      }
     } else {
-        if (sd_len) {
-            set_param.type = BT_LE_ADV_SCAN_IND;
-        } else {
-            set_param.type = BT_LE_ADV_NONCONN_IND;
+      /*
+       * If Static Random address is used as Identity
+       * address we need to restore it before advertising
+       * is enabled. Otherwise NRPA used for active scan
+       * could be used for advertising.
+       */
+      if (id_addr->type == BT_ADDR_LE_RANDOM) {
+        err = set_random_address(&id_addr->a);
+        if (err) {
+          return err;
         }
+      }
+      set_param.own_addr_type = id_addr->type;
     }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param));
-    if (!buf) {
-        return -ENOBUFS;
+    set_param.type = BT_LE_ADV_IND;
+  } else {
+    if (sd_len) {
+      set_param.type = BT_LE_ADV_SCAN_IND;
+    } else {
+      set_param.type = BT_LE_ADV_NONCONN_IND;
     }
+  }
 
-    net_buf_add_mem(buf, &set_param, sizeof(set_param));
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL);
-    if (err) {
-        return err;
-    }
+  net_buf_add_mem(buf, &set_param, sizeof(set_param));
 
-    err = set_advertise_enable(true);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    if (!(param->options & BT_LE_ADV_OPT_ONE_TIME)) {
-        atomic_set_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING);
-    }
+  err = set_advertise_enable(true);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  if (!(param->options & BT_LE_ADV_OPT_ONE_TIME)) {
+    atomic_set_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING);
+  }
+
+  return 0;
 }
-#endif //CONFIG_BLE_MULTI_ADV
+#endif // CONFIG_BLE_MULTI_ADV
 
 #if defined(CONFIG_BT_OBSERVER)
-static bool valid_le_scan_param(const struct bt_le_scan_param *param)
-{
-    if (param->type != BT_HCI_LE_SCAN_PASSIVE &&
-        param->type != BT_HCI_LE_SCAN_ACTIVE) {
-        return false;
-    }
+static bool valid_le_scan_param(const struct bt_le_scan_param *param) {
+  if (param->type != BT_HCI_LE_SCAN_PASSIVE && param->type != BT_HCI_LE_SCAN_ACTIVE) {
+    return false;
+  }
 
-    if (param->filter_dup &
-        ~(BT_LE_SCAN_FILTER_DUPLICATE | BT_LE_SCAN_FILTER_WHITELIST)) {
-        return false;
-    }
+  if (param->filter_dup & ~(BT_LE_SCAN_FILTER_DUPLICATE | BT_LE_SCAN_FILTER_WHITELIST)) {
+    return false;
+  }
 
-    if (is_wl_empty() &&
-        param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST) {
-        return false;
-    }
+  if (is_wl_empty() && param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST) {
+    return false;
+  }
 
-    if (param->interval < 0x0004 || param->interval > 0x4000) {
-        return false;
-    }
+  if (param->interval < 0x0004 || param->interval > 0x4000) {
+    return false;
+  }
 
-    if (param->window < 0x0004 || param->window > 0x4000) {
-        return false;
-    }
+  if (param->window < 0x0004 || param->window > 0x4000) {
+    return false;
+  }
 
-    if (param->window > param->interval) {
-        return false;
-    }
+  if (param->window > param->interval) {
+    return false;
+  }
 
-    return true;
+  return true;
 }
 
-#if defined(CONFIG_BT_STACK_PTS)
-int bt_le_pts_scan_start(const struct bt_le_scan_param *param, bt_le_scan_cb_t cb, u8_t addre_type)
-{
-    int err;
+#if defined(CONFIG_BT_STACK_PTS)
+int bt_le_pts_scan_start(const struct bt_le_scan_param *param, bt_le_scan_cb_t cb, u8_t addre_type) {
+  int err;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        return -EAGAIN;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    return -EAGAIN;
+  }
 
-    /* Check that the parameters have valid values */
-    if (!valid_le_scan_param(param)) {
-        return -EINVAL;
-    }
+  /* Check that the parameters have valid values */
+  if (!valid_le_scan_param(param)) {
+    return -EINVAL;
+  }
 
-    /* Return if active scan is already enabled */
-    if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
-        return -EALREADY;
-    }
+  /* Return if active scan is already enabled */
+  if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
+    return -EALREADY;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
-        err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
-        if (err) {
-            atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
-            return err;
-        }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
+    err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
+    if (err) {
+      atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
+      return err;
     }
+  }
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP,
-                      param->filter_dup & BT_LE_SCAN_FILTER_DUPLICATE);
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP, param->filter_dup & BT_LE_SCAN_FILTER_DUPLICATE);
 
 #if defined(CONFIG_BT_WHITELIST)
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_WL,
-                      param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST);
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_WL, param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST);
 #endif /* defined(CONFIG_BT_WHITELIST) */
 
-    err = start_le_scan_with_isrpa(param->type, param->interval, param->window, addre_type);
+  err = start_le_scan_with_isrpa(param->type, param->interval, param->window, addre_type);
 
-    if (err) {
-        atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
-        return err;
-    }
+  if (err) {
+    atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
+    return err;
+  }
 
-    scan_dev_found_cb = cb;
+  scan_dev_found_cb = cb;
 
-    return 0;
+  return 0;
 }
 #endif
 int bt_le_scan_start(const struct bt_le_scan_param *param, bt_le_scan_cb_t cb)
 
 {
-    int err;
+  int err;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        return -EAGAIN;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    return -EAGAIN;
+  }
 
-    /* Check that the parameters have valid values */
-    if (!valid_le_scan_param(param)) {
-        return -EINVAL;
-    }
+  /* Check that the parameters have valid values */
+  if (!valid_le_scan_param(param)) {
+    return -EINVAL;
+  }
 
-    /* Return if active scan is already enabled */
-    if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
-        return -EALREADY;
-    }
+  /* Return if active scan is already enabled */
+  if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
+    return -EALREADY;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
-        err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
-        if (err) {
-            atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
-            return err;
-        }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
+    err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
+    if (err) {
+      atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
+      return err;
     }
+  }
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP,
-                      param->filter_dup & BT_LE_SCAN_FILTER_DUPLICATE);
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP, param->filter_dup & BT_LE_SCAN_FILTER_DUPLICATE);
 
 #if defined(CONFIG_BT_WHITELIST)
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_WL,
-                      param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST);
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_WL, param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST);
 #endif /* defined(CONFIG_BT_WHITELIST) */
 
-    err = start_le_scan(param->type, param->interval, param->window);
-    if (err) {
-        atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
-        return err;
-    }
+  err = start_le_scan(param->type, param->interval, param->window);
+  if (err) {
+    atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
+    return err;
+  }
 
-    scan_dev_found_cb = cb;
+  scan_dev_found_cb = cb;
 
 #if defined(BFLB_HOST_ASSISTANT)
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_ASSIST_RUN) && host_assist_cb && host_assist_cb->le_scan_cb)
-        host_assist_cb->le_scan_cb(param, cb);
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_ASSIST_RUN) && host_assist_cb && host_assist_cb->le_scan_cb)
+    host_assist_cb->le_scan_cb(param, cb);
 #endif
 
-    return 0;
+  return 0;
 }
 
-int bt_le_scan_stop(void)
-{
-    /* Return if active scanning is already disabled */
-    if (!atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
-        return -EALREADY;
-    }
+int bt_le_scan_stop(void) {
+  /* Return if active scanning is already disabled */
+  if (!atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
+    return -EALREADY;
+  }
 
-    scan_dev_found_cb = NULL;
+  scan_dev_found_cb = NULL;
 
-    return bt_le_scan_update(false);
+  return bt_le_scan_update(false);
 }
 #endif /* CONFIG_BT_OBSERVER */
 
 #if defined(CONFIG_BT_WHITELIST)
-int bt_le_whitelist_add(const bt_addr_le_t *addr)
-{
-    struct bt_hci_cp_le_add_dev_to_wl *cp;
-    struct net_buf *buf;
-    int err;
+int bt_le_whitelist_add(const bt_addr_le_t *addr) {
+  struct bt_hci_cp_le_add_dev_to_wl *cp;
+  struct net_buf                    *buf;
+  int                                err;
 
-    if (!(bt_dev.le.wl_entries < bt_dev.le.wl_size)) {
-        return -ENOMEM;
-    }
+  if (!(bt_dev.le.wl_entries < bt_dev.le.wl_size)) {
+    return -ENOMEM;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_WL, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_WL, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_le_copy(&cp->addr, addr);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_le_copy(&cp->addr, addr);
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_WL, buf, NULL);
-    if (err) {
-        BT_ERR("Failed to add device to whitelist");
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_WL, buf, NULL);
+  if (err) {
+    BT_ERR("Failed to add device to whitelist");
 
-        return err;
-    }
+    return err;
+  }
 
-    bt_dev.le.wl_entries++;
+  bt_dev.le.wl_entries++;
 
-    return 0;
+  return 0;
 }
 
-int bt_le_whitelist_rem(const bt_addr_le_t *addr)
-{
-    struct bt_hci_cp_le_rem_dev_from_wl *cp;
-    struct net_buf *buf;
-    int err;
+int bt_le_whitelist_rem(const bt_addr_le_t *addr) {
+  struct bt_hci_cp_le_rem_dev_from_wl *cp;
+  struct net_buf                      *buf;
+  int                                  err;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_WL, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_WL, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_le_copy(&cp->addr, addr);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_le_copy(&cp->addr, addr);
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_WL, buf, NULL);
-    if (err) {
-        BT_ERR("Failed to remove device from whitelist");
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_WL, buf, NULL);
+  if (err) {
+    BT_ERR("Failed to remove device from whitelist");
+    return err;
+  }
 
-    bt_dev.le.wl_entries--;
-    return 0;
+  bt_dev.le.wl_entries--;
+  return 0;
 }
 
-int bt_le_whitelist_clear(void)
-{
-    int err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_WL, NULL, NULL);
+int bt_le_whitelist_clear(void) {
+  int err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_WL, NULL, NULL);
 
-    if (err) {
-        BT_ERR("Failed to clear whitelist");
-        return err;
-    }
+  if (err) {
+    BT_ERR("Failed to clear whitelist");
+    return err;
+  }
 
-    bt_dev.le.wl_entries = 0;
-    return 0;
+  bt_dev.le.wl_entries = 0;
+  return 0;
 }
 #endif /* defined(CONFIG_BT_WHITELIST) */
 
-int bt_le_set_chan_map(u8_t chan_map[5])
-{
-    struct bt_hci_cp_le_set_host_chan_classif *cp;
-    struct net_buf *buf;
+int bt_le_set_chan_map(u8_t chan_map[5]) {
+  struct bt_hci_cp_le_set_host_chan_classif *cp;
+  struct net_buf                            *buf;
 
-    if (!IS_ENABLED(CONFIG_BT_CENTRAL)) {
-        return -ENOTSUP;
-    }
+  if (!IS_ENABLED(CONFIG_BT_CENTRAL)) {
+    return -ENOTSUP;
+  }
 
-    if (!BT_CMD_TEST(bt_dev.supported_commands, 27, 3)) {
-        BT_WARN("Set Host Channel Classification command is "
-                "not supported");
-        return -ENOTSUP;
-    }
+  if (!BT_CMD_TEST(bt_dev.supported_commands, 27, 3)) {
+    BT_WARN("Set Host Channel Classification command is "
+            "not supported");
+    return -ENOTSUP;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF,
-                            sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
 
-    memcpy(&cp->ch_map[0], &chan_map[0], 4);
-    cp->ch_map[4] = chan_map[4] & BIT_MASK(5);
+  memcpy(&cp->ch_map[0], &chan_map[0], 4);
+  cp->ch_map[4] = chan_map[4] & BIT_MASK(5);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF,
-                                buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF, buf, NULL);
 }
 #if defined(CONFIG_SET_TX_PWR)
-int bt_set_tx_pwr(int8_t power)
-{
-    struct bt_hci_cp_vs_set_tx_pwr set_param;
-    struct net_buf *buf;
-    int err;
+int bt_set_tx_pwr(int8_t power) {
+  struct bt_hci_cp_vs_set_tx_pwr set_param;
+  struct net_buf                *buf;
+  int                            err;
 
-    if (power < 0 || power > 20)
-        return BT_HCI_ERR_INVALID_PARAM;
+  if (power < 0 || power > 20)
+    return BT_HCI_ERR_INVALID_PARAM;
 
-    memset(&set_param, 0, sizeof(set_param));
+  memset(&set_param, 0, sizeof(set_param));
 
-    set_param.power = power;
+  set_param.power = power;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_VS_SET_TX_PWR, sizeof(set_param));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_VS_SET_TX_PWR, sizeof(set_param));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    net_buf_add_mem(buf, &set_param, sizeof(set_param));
+  net_buf_add_mem(buf, &set_param, sizeof(set_param));
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_SET_TX_PWR, buf, NULL);
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_SET_TX_PWR, buf, NULL);
 
-    if (err) {
-        return err;
-    }
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 #endif
 
-int bt_buf_get_rx_avail_cnt(void)
-{
-    return (k_queue_get_cnt(&hci_rx_pool.free._queue) + hci_rx_pool.uninit_count);
-}
+int bt_buf_get_rx_avail_cnt(void) { return (k_queue_get_cnt(&hci_rx_pool.free._queue) + hci_rx_pool.uninit_count); }
 
-struct net_buf *bt_buf_get_rx(enum bt_buf_type type, s32_t timeout)
-{
-    struct net_buf *buf;
+struct net_buf *bt_buf_get_rx(enum bt_buf_type type, s32_t timeout) {
+  struct net_buf *buf;
 
-    __ASSERT(type == BT_BUF_EVT || type == BT_BUF_ACL_IN,
-             "Invalid buffer type requested");
+  __ASSERT(type == BT_BUF_EVT || type == BT_BUF_ACL_IN, "Invalid buffer type requested");
 
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-    if (type == BT_BUF_EVT) {
-        buf = net_buf_alloc(&hci_rx_pool, timeout);
-    } else {
-        buf = net_buf_alloc(&acl_in_pool, timeout);
-    }
-#else
+  if (type == BT_BUF_EVT) {
     buf = net_buf_alloc(&hci_rx_pool, timeout);
+  } else {
+    buf = net_buf_alloc(&acl_in_pool, timeout);
+  }
+#else
+  buf = net_buf_alloc(&hci_rx_pool, timeout);
 #endif
 
-    if (buf) {
-        net_buf_reserve(buf, BT_BUF_RESERVE);
-        bt_buf_set_type(buf, type);
-    }
+  if (buf) {
+    net_buf_reserve(buf, BT_BUF_RESERVE);
+    bt_buf_set_type(buf, type);
+  }
 
-    return buf;
+  return buf;
 }
 
-struct net_buf *bt_buf_get_cmd_complete(s32_t timeout)
-{
-    struct net_buf *buf;
-    unsigned int key;
+struct net_buf *bt_buf_get_cmd_complete(s32_t timeout) {
+  struct net_buf *buf;
+  unsigned int    key;
 
-    key = irq_lock();
-    buf = bt_dev.sent_cmd;
-    bt_dev.sent_cmd = NULL;
-    irq_unlock(key);
+  key             = irq_lock();
+  buf             = bt_dev.sent_cmd;
+  bt_dev.sent_cmd = NULL;
+  irq_unlock(key);
 
-    BT_DBG("sent_cmd %p", buf);
+  BT_DBG("sent_cmd %p", buf);
 
-    if (buf) {
-        bt_buf_set_type(buf, BT_BUF_EVT);
-        buf->len = 0U;
-        net_buf_reserve(buf, BT_BUF_RESERVE);
+  if (buf) {
+    bt_buf_set_type(buf, BT_BUF_EVT);
+    buf->len = 0U;
+    net_buf_reserve(buf, BT_BUF_RESERVE);
 
-        return buf;
-    }
+    return buf;
+  }
 
-    return bt_buf_get_rx(BT_BUF_EVT, timeout);
+  return bt_buf_get_rx(BT_BUF_EVT, timeout);
 }
 
-struct net_buf *bt_buf_get_evt(u8_t evt, bool discardable, s32_t timeout)
-{
-    switch (evt) {
+struct net_buf *bt_buf_get_evt(u8_t evt, bool discardable, s32_t timeout) {
+  switch (evt) {
 #if defined(CONFIG_BT_CONN)
-        case BT_HCI_EVT_NUM_COMPLETED_PACKETS: {
-            struct net_buf *buf;
+  case BT_HCI_EVT_NUM_COMPLETED_PACKETS: {
+    struct net_buf *buf;
 
-            buf = net_buf_alloc(&num_complete_pool, timeout);
-            if (buf) {
-                net_buf_reserve(buf, BT_BUF_RESERVE);
-                bt_buf_set_type(buf, BT_BUF_EVT);
-            }
+    buf = net_buf_alloc(&num_complete_pool, timeout);
+    if (buf) {
+      net_buf_reserve(buf, BT_BUF_RESERVE);
+      bt_buf_set_type(buf, BT_BUF_EVT);
+    }
 
-            return buf;
-        }
+    return buf;
+  }
 #endif /* CONFIG_BT_CONN */
-        case BT_HCI_EVT_CMD_COMPLETE:
-        case BT_HCI_EVT_CMD_STATUS:
-            return bt_buf_get_cmd_complete(timeout);
-        default:
+  case BT_HCI_EVT_CMD_COMPLETE:
+  case BT_HCI_EVT_CMD_STATUS:
+    return bt_buf_get_cmd_complete(timeout);
+  default:
 #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT)
-            if (discardable) {
-                struct net_buf *buf;
+    if (discardable) {
+      struct net_buf *buf;
 
-                buf = net_buf_alloc(&discardable_pool, timeout);
-                if (buf) {
-                    net_buf_reserve(buf, BT_BUF_RESERVE);
-                    bt_buf_set_type(buf, BT_BUF_EVT);
-                }
+      buf = net_buf_alloc(&discardable_pool, timeout);
+      if (buf) {
+        net_buf_reserve(buf, BT_BUF_RESERVE);
+        bt_buf_set_type(buf, BT_BUF_EVT);
+      }
 
-                return buf;
-            }
+      return buf;
+    }
 #endif /* CONFIG_BT_DISCARDABLE_BUF_COUNT */
 
-            return bt_buf_get_rx(BT_BUF_EVT, timeout);
-    }
+    return bt_buf_get_rx(BT_BUF_EVT, timeout);
+  }
 }
 
 #if defined(CONFIG_BT_BREDR)
-static int br_start_inquiry(const struct bt_br_discovery_param *param)
-{
-    const u8_t iac[3] = { 0x33, 0x8b, 0x9e };
-    struct bt_hci_op_inquiry *cp;
-    struct net_buf *buf;
+static int br_start_inquiry(const struct bt_br_discovery_param *param) {
+  const u8_t                iac[3] = {0x33, 0x8b, 0x9e};
+  struct bt_hci_op_inquiry *cp;
+  struct net_buf           *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_INQUIRY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_INQUIRY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
 
-    cp->length = param->length;
-    cp->num_rsp = 0xff; /* we limit discovery only by time */
+  cp->length  = param->length;
+  cp->num_rsp = 0xff; /* we limit discovery only by time */
 
-    memcpy(cp->lap, iac, 3);
-    if (param->limited) {
-        cp->lap[0] = 0x00;
-    }
+  memcpy(cp->lap, iac, 3);
+  if (param->limited) {
+    cp->lap[0] = 0x00;
+  }
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_INQUIRY, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_INQUIRY, buf, NULL);
 }
 
-static bool valid_br_discov_param(const struct bt_br_discovery_param *param,
-                                  size_t num_results)
-{
-    if (!num_results || num_results > 255) {
-        return false;
-    }
+static bool valid_br_discov_param(const struct bt_br_discovery_param *param, size_t num_results) {
+  if (!num_results || num_results > 255) {
+    return false;
+  }
 
-    if (!param->length || param->length > 0x30) {
-        return false;
-    }
+  if (!param->length || param->length > 0x30) {
+    return false;
+  }
 
-    return true;
+  return true;
 }
 
-int bt_br_discovery_start(const struct bt_br_discovery_param *param,
-                          struct bt_br_discovery_result *results, size_t cnt,
-                          bt_br_discovery_cb_t cb)
-{
-    int err;
+int bt_br_discovery_start(const struct bt_br_discovery_param *param, struct bt_br_discovery_result *results, size_t cnt, bt_br_discovery_cb_t cb) {
+  int err;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    if (!valid_br_discov_param(param, cnt)) {
-        return -EINVAL;
-    }
+  if (!valid_br_discov_param(param, cnt)) {
+    return -EINVAL;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
-        return -EALREADY;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
+    return -EALREADY;
+  }
 
-    err = br_start_inquiry(param);
-    if (err) {
-        return err;
-    }
+  err = br_start_inquiry(param);
+  if (err) {
+    return err;
+  }
 
-    atomic_set_bit(bt_dev.flags, BT_DEV_INQUIRY);
+  atomic_set_bit(bt_dev.flags, BT_DEV_INQUIRY);
 
-    (void)memset(results, 0, sizeof(*results) * cnt);
+  (void)memset(results, 0, sizeof(*results) * cnt);
 
-    discovery_cb = cb;
-    discovery_results = results;
-    discovery_results_size = cnt;
-    discovery_results_count = 0;
+  discovery_cb            = cb;
+  discovery_results       = results;
+  discovery_results_size  = cnt;
+  discovery_results_count = 0;
 
-    return 0;
+  return 0;
 }
 
-int bt_br_discovery_stop(void)
-{
-    int err;
-    int i;
+int bt_br_discovery_stop(void) {
+  int err;
+  int i;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
-        return -EALREADY;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
+    return -EALREADY;
+  }
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_INQUIRY_CANCEL, NULL, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_INQUIRY_CANCEL, NULL, NULL);
+  if (err) {
+    return err;
+  }
 
-    for (i = 0; i < discovery_results_count; i++) {
-        struct discovery_priv *priv;
-        struct bt_hci_cp_remote_name_cancel *cp;
-        struct net_buf *buf;
+  for (i = 0; i < discovery_results_count; i++) {
+    struct discovery_priv               *priv;
+    struct bt_hci_cp_remote_name_cancel *cp;
+    struct net_buf                      *buf;
 
-        priv = (struct discovery_priv *)&discovery_results[i]._priv;
+    priv = (struct discovery_priv *)&discovery_results[i]._priv;
 
-        if (!priv->resolving) {
-            continue;
-        }
+    if (!priv->resolving) {
+      continue;
+    }
 
-        buf = bt_hci_cmd_create(BT_HCI_OP_REMOTE_NAME_CANCEL,
-                                sizeof(*cp));
-        if (!buf) {
-            continue;
-        }
+    buf = bt_hci_cmd_create(BT_HCI_OP_REMOTE_NAME_CANCEL, sizeof(*cp));
+    if (!buf) {
+      continue;
+    }
 
-        cp = net_buf_add(buf, sizeof(*cp));
-        bt_addr_copy(&cp->bdaddr, &discovery_results[i].addr);
+    cp = net_buf_add(buf, sizeof(*cp));
+    bt_addr_copy(&cp->bdaddr, &discovery_results[i].addr);
 
-        bt_hci_cmd_send_sync(BT_HCI_OP_REMOTE_NAME_CANCEL, buf, NULL);
-    }
+    bt_hci_cmd_send_sync(BT_HCI_OP_REMOTE_NAME_CANCEL, buf, NULL);
+  }
 
-    atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY);
+  atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY);
 
-    discovery_cb = NULL;
-    discovery_results = NULL;
-    discovery_results_size = 0;
-    discovery_results_count = 0;
+  discovery_cb            = NULL;
+  discovery_results       = NULL;
+  discovery_results_size  = 0;
+  discovery_results_count = 0;
 
-    return 0;
+  return 0;
 }
 
-static int write_scan_enable(u8_t scan)
-{
-    struct net_buf *buf;
-    int err;
+static int write_scan_enable(u8_t scan) {
+  struct net_buf *buf;
+  int             err;
 
-    BT_DBG("type %u", scan);
+  BT_DBG("type %u", scan);
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SCAN_ENABLE, 1);
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SCAN_ENABLE, 1);
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    net_buf_add_u8(buf, scan);
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SCAN_ENABLE, buf, NULL);
-    if (err) {
-        return err;
-    }
+  net_buf_add_u8(buf, scan);
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SCAN_ENABLE, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_ISCAN,
-                      (scan & BT_BREDR_SCAN_INQUIRY));
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_PSCAN,
-                      (scan & BT_BREDR_SCAN_PAGE));
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_ISCAN, (scan & BT_BREDR_SCAN_INQUIRY));
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_PSCAN, (scan & BT_BREDR_SCAN_PAGE));
 
-    return 0;
+  return 0;
 }
 
-int bt_br_set_connectable(bool enable)
-{
-    if (enable) {
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
-            return -EALREADY;
-        } else {
-            return write_scan_enable(BT_BREDR_SCAN_PAGE);
-        }
+int bt_br_set_connectable(bool enable) {
+  if (enable) {
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
+      return -EALREADY;
     } else {
-        if (!atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
-            return -EALREADY;
-        } else {
-            return write_scan_enable(BT_BREDR_SCAN_DISABLED);
-        }
+      return write_scan_enable(BT_BREDR_SCAN_PAGE);
+    }
+  } else {
+    if (!atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
+      return -EALREADY;
+    } else {
+      return write_scan_enable(BT_BREDR_SCAN_DISABLED);
     }
+  }
 }
 
-int bt_br_set_discoverable(bool enable)
-{
-    if (enable) {
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
-            return -EALREADY;
-        }
-
-        if (!atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
-            return -EPERM;
-        }
+int bt_br_set_discoverable(bool enable) {
+  if (enable) {
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
+      return -EALREADY;
+    }
 
-        return write_scan_enable(BT_BREDR_SCAN_INQUIRY |
-                                 BT_BREDR_SCAN_PAGE);
-    } else {
-        if (!atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
-            return -EALREADY;
-        }
+    if (!atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
+      return -EPERM;
+    }
 
-        return write_scan_enable(BT_BREDR_SCAN_PAGE);
+    return write_scan_enable(BT_BREDR_SCAN_INQUIRY | BT_BREDR_SCAN_PAGE);
+  } else {
+    if (!atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
+      return -EALREADY;
     }
+
+    return write_scan_enable(BT_BREDR_SCAN_PAGE);
+  }
 }
 
-int bt_br_write_eir(u8_t rec, u8_t *data)
-{
-    struct bt_hci_cp_write_ext_inquiry_resp *ext_ir;
-    struct net_buf *buf;
+int bt_br_write_eir(u8_t rec, u8_t *data) {
+  struct bt_hci_cp_write_ext_inquiry_resp *ext_ir;
+  struct net_buf                          *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_EXT_INQUIRY_RESP, sizeof(*ext_ir));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_EXT_INQUIRY_RESP, sizeof(*ext_ir));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    ext_ir = net_buf_add(buf, sizeof(*ext_ir));
-    memset(ext_ir, 0, sizeof(*ext_ir));
+  ext_ir = net_buf_add(buf, sizeof(*ext_ir));
+  memset(ext_ir, 0, sizeof(*ext_ir));
 
-    ext_ir->rec = rec;
-    memcpy(ext_ir->eir, data, strlen((char *)data));
+  ext_ir->rec = rec;
+  memcpy(ext_ir->eir, data, strlen((char *)data));
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_EXT_INQUIRY_RESP, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_EXT_INQUIRY_RESP, buf, NULL);
 }
 
 #endif /* CONFIG_BT_BREDR */
 
 #if defined(CONFIG_BT_ECC)
-int bt_pub_key_gen(struct bt_pub_key_cb *new_cb)
-{
-    int err;
-
-    /*
-	 * We check for both "LE Read Local P-256 Public Key" and
-	 * "LE Generate DH Key" support here since both commands are needed for
-	 * ECC support. If "LE Generate DH Key" is not supported then there
-	 * is no point in reading local public key.
-	 */
-    if (!BT_CMD_TEST(bt_dev.supported_commands, 34, 1) ||
-        !BT_CMD_TEST(bt_dev.supported_commands, 34, 2)) {
-        BT_WARN("ECC HCI commands not available");
-        return -ENOTSUP;
-    }
+int bt_pub_key_gen(struct bt_pub_key_cb *new_cb) {
+  int err;
+
+  /*
+   * We check for both "LE Read Local P-256 Public Key" and
+   * "LE Generate DH Key" support here since both commands are needed for
+   * ECC support. If "LE Generate DH Key" is not supported then there
+   * is no point in reading local public key.
+   */
+  if (!BT_CMD_TEST(bt_dev.supported_commands, 34, 1) || !BT_CMD_TEST(bt_dev.supported_commands, 34, 2)) {
+    BT_WARN("ECC HCI commands not available");
+    return -ENOTSUP;
+  }
 
 #if defined(BFLB_BLE_PATCH_AVOID_DUPLI_PUBKEY_CB)
-    struct bt_pub_key_cb *cb;
-    struct bt_pub_key_cb *valid_cb;
-    bool existed = false;
-
-    if (pub_key_cb) {
-        cb = pub_key_cb;
-        valid_cb = cb;
-        while (cb) {
-            if (new_cb->func == cb->func) {
-                existed = true;
-                break;
-            }
-
-            valid_cb = cb;
-            cb = cb->_next;
-        }
+  struct bt_pub_key_cb *cb;
+  struct bt_pub_key_cb *valid_cb;
+  bool                  existed = false;
 
-        if (!existed) {
-            valid_cb->_next = new_cb;
-        }
-    } else {
-        pub_key_cb = new_cb;
+  if (pub_key_cb) {
+    cb       = pub_key_cb;
+    valid_cb = cb;
+    while (cb) {
+      if (new_cb->func == cb->func) {
+        existed = true;
+        break;
+      }
+
+      valid_cb = cb;
+      cb       = cb->_next;
     }
-#else
-    new_cb->_next = pub_key_cb;
+
+    if (!existed) {
+      valid_cb->_next = new_cb;
+    }
+  } else {
     pub_key_cb = new_cb;
+  }
+#else
+  new_cb->_next = pub_key_cb;
+  pub_key_cb    = new_cb;
 #endif
 
-    if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY)) {
-        return 0;
-    }
+  if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY)) {
+    return 0;
+  }
 
-    atomic_clear_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY);
+  atomic_clear_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY);
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_P256_PUBLIC_KEY, NULL, NULL);
-    if (err) {
-        BT_ERR("Sending LE P256 Public Key command failed");
-        atomic_clear_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY);
-        pub_key_cb = NULL;
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_P256_PUBLIC_KEY, NULL, NULL);
+  if (err) {
+    BT_ERR("Sending LE P256 Public Key command failed");
+    atomic_clear_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY);
+    pub_key_cb = NULL;
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-const u8_t *bt_pub_key_get(void)
-{
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY)) {
-        return pub_key;
-    }
+const u8_t *bt_pub_key_get(void) {
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY)) {
+    return pub_key;
+  }
 
-    return NULL;
+  return NULL;
 }
 
-int bt_dh_key_gen(const u8_t remote_pk[64], bt_dh_key_cb_t cb)
-{
-    struct bt_hci_cp_le_generate_dhkey *cp;
-    struct net_buf *buf;
-    int err;
+int bt_dh_key_gen(const u8_t remote_pk[64], bt_dh_key_cb_t cb) {
+  struct bt_hci_cp_le_generate_dhkey *cp;
+  struct net_buf                     *buf;
+  int                                 err;
 
-    if (dh_key_cb || atomic_test_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY)) {
-        return -EBUSY;
-    }
+  if (dh_key_cb || atomic_test_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY)) {
+    return -EBUSY;
+  }
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY)) {
-        return -EADDRNOTAVAIL;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY)) {
+    return -EADDRNOTAVAIL;
+  }
 
-    dh_key_cb = cb;
+  dh_key_cb = cb;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_GENERATE_DHKEY, sizeof(*cp));
-    if (!buf) {
-        dh_key_cb = NULL;
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_GENERATE_DHKEY, sizeof(*cp));
+  if (!buf) {
+    dh_key_cb = NULL;
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    memcpy(cp->key, remote_pk, sizeof(cp->key));
+  cp = net_buf_add(buf, sizeof(*cp));
+  memcpy(cp->key, remote_pk, sizeof(cp->key));
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_GENERATE_DHKEY, buf, NULL);
-    if (err) {
-        dh_key_cb = NULL;
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_GENERATE_DHKEY, buf, NULL);
+  if (err) {
+    dh_key_cb = NULL;
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_BT_ECC */
 
 #if defined(CONFIG_BT_BREDR)
-int bt_br_oob_get_local(struct bt_br_oob *oob)
-{
-    bt_addr_copy(&oob->addr, &bt_dev.id_addr[0].a);
+int bt_br_oob_get_local(struct bt_br_oob *oob) {
+  bt_addr_copy(&oob->addr, &bt_dev.id_addr[0].a);
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_BT_BREDR */
 
-int bt_le_oob_get_local(u8_t id, struct bt_le_oob *oob)
-{
-    int err;
-
-    if (id >= CONFIG_BT_ID_MAX) {
-        return -EINVAL;
-    }
+int bt_le_oob_get_local(u8_t id, struct bt_le_oob *oob) {
+  int err;
 
-    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-        /* Invalidate RPA so a new one is generated */
-        atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
+  if (id >= CONFIG_BT_ID_MAX) {
+    return -EINVAL;
+  }
 
-        err = le_set_private_addr(id);
-        if (err) {
-            return err;
-        }
+  if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    /* Invalidate RPA so a new one is generated */
+    atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
 
-        bt_addr_le_copy(&oob->addr, &bt_dev.random_addr);
-    } else {
-        bt_addr_le_copy(&oob->addr, &bt_dev.id_addr[id]);
+    err = le_set_private_addr(id);
+    if (err) {
+      return err;
     }
 
-    if (IS_ENABLED(CONFIG_BT_SMP)) {
-        err = bt_smp_le_oob_generate_sc_data(&oob->le_sc_data);
-        if (err) {
-            return err;
-        }
+    bt_addr_le_copy(&oob->addr, &bt_dev.random_addr);
+  } else {
+    bt_addr_le_copy(&oob->addr, &bt_dev.id_addr[id]);
+  }
+
+  if (IS_ENABLED(CONFIG_BT_SMP)) {
+    err = bt_smp_le_oob_generate_sc_data(&oob->le_sc_data);
+    if (err) {
+      return err;
     }
+  }
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_SMP)
-int bt_le_oob_set_sc_data(struct bt_conn *conn,
-                          const struct bt_le_oob_sc_data *oobd_local,
-                          const struct bt_le_oob_sc_data *oobd_remote)
-{
-    return bt_smp_le_oob_set_sc_data(conn, oobd_local, oobd_remote);
+int bt_le_oob_set_sc_data(struct bt_conn *conn, const struct bt_le_oob_sc_data *oobd_local, const struct bt_le_oob_sc_data *oobd_remote) {
+  return bt_smp_le_oob_set_sc_data(conn, oobd_local, oobd_remote);
 }
 
-int bt_le_oob_get_sc_data(struct bt_conn *conn,
-                          const struct bt_le_oob_sc_data **oobd_local,
-                          const struct bt_le_oob_sc_data **oobd_remote)
-{
-    return bt_smp_le_oob_get_sc_data(conn, oobd_local, oobd_remote);
+int bt_le_oob_get_sc_data(struct bt_conn *conn, const struct bt_le_oob_sc_data **oobd_local, const struct bt_le_oob_sc_data **oobd_remote) {
+  return bt_smp_le_oob_get_sc_data(conn, oobd_local, oobd_remote);
 }
 #endif
 
 #if defined(BFLB_RELEASE_CMD_SEM_IF_CONN_DISC)
-void hci_release_conn_related_cmd(void)
-{
-    u16_t opcode;
-
-    (void)opcode;
-
-    if (bt_dev.sent_cmd) {
-        opcode = cmd(bt_dev.sent_cmd)->opcode;
-        switch (opcode) {
-            case BT_HCI_OP_LE_SET_DATA_LEN:
-            case BT_HCI_OP_LE_READ_REMOTE_FEATURES:
-            case BT_HCI_OP_LE_SET_DEFAULT_PHY:
-            case BT_HCI_OP_LE_SET_PHY:
-            case BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY:
-            case BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY:
-            case BT_HCI_OP_LE_LTK_REQ_NEG_REPLY:
-            case BT_HCI_OP_LE_LTK_REQ_REPLY: {
-                k_sem_give(&bt_dev.ncmd_sem);
-                hci_cmd_done(opcode, BT_HCI_ERR_UNSPECIFIED, bt_dev.sent_cmd);
-                net_buf_unref(bt_dev.sent_cmd);
-                bt_dev.sent_cmd = NULL;
-            } break;
-            default:
-                break;
-        }
-    }
+void hci_release_conn_related_cmd(void) {
+  u16_t opcode;
+
+  (void)opcode;
+
+  if (bt_dev.sent_cmd) {
+    opcode = cmd(bt_dev.sent_cmd)->opcode;
+    switch (opcode) {
+    case BT_HCI_OP_LE_SET_DATA_LEN:
+    case BT_HCI_OP_LE_READ_REMOTE_FEATURES:
+    case BT_HCI_OP_LE_SET_DEFAULT_PHY:
+    case BT_HCI_OP_LE_SET_PHY:
+    case BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY:
+    case BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY:
+    case BT_HCI_OP_LE_LTK_REQ_NEG_REPLY:
+    case BT_HCI_OP_LE_LTK_REQ_REPLY: {
+      k_sem_give(&bt_dev.ncmd_sem);
+      hci_cmd_done(opcode, BT_HCI_ERR_UNSPECIFIED, bt_dev.sent_cmd);
+      net_buf_unref(bt_dev.sent_cmd);
+      bt_dev.sent_cmd = NULL;
+    } break;
+    default:
+      break;
+    }
+  }
 }
 #endif
 
 #if defined(BFLB_HOST_ASSISTANT)
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-int bt_set_flow_control(void)
-{
-    return set_flow_control();
-}
+int bt_set_flow_control(void) { return set_flow_control(); }
 #endif
-int bt_set_event_mask(void)
-{
-    return set_event_mask();
-}
+int bt_set_event_mask(void) { return set_event_mask(); }
 
-int bt_le_set_event_mask(void)
-{
-    return le_set_event_mask();
-}
+int bt_le_set_event_mask(void) { return le_set_event_mask(); }
 
-void bt_hci_reset_complete(struct net_buf *buf)
-{
-    hci_reset_complete(buf);
-}
+void bt_hci_reset_complete(struct net_buf *buf) { hci_reset_complete(buf); }
 
-void bt_register_host_assist_cb(struct blhast_cb *cb)
-{
-    host_assist_cb = cb;
-}
+void bt_register_host_assist_cb(struct blhast_cb *cb) { host_assist_cb = cb; }
 #endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_ecc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_ecc.c
index e9170a8c98..36e6ac21d6 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_ecc.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_ecc.c
@@ -9,28 +9,28 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
 #include 
-#include 
-#include 
 #include 
-#include 
 #include 
 #include 
+#include 
+#include 
+#include 
+#include 
 
+#include <../include/bluetooth/crypto.h>
 #include 
 #include 
-#include 
 #include 
-#include <../include/bluetooth/crypto.h>
+#include 
 
 #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_HCI_CORE)
 #include "log.h"
 
 #include "hci_ecc.h"
 #ifdef CONFIG_BT_HCI_RAW
-#include 
 #include "hci_raw_internal.h"
+#include 
 #else
 #include "hci_core.h"
 #endif
@@ -41,28 +41,20 @@ static BT_STACK_NOINIT(ecc_thread_stack, 1024);
 #endif
 
 /* based on Core Specification 4.2 Vol 3. Part H 2.3.5.6.1 */
-static const u32_t debug_private_key[8] = {
-    0xcd3c1abd, 0x5899b8a6, 0xeb40b799, 0x4aff607b, 0xd2103f50, 0x74c9b3e3,
-    0xa3c55f38, 0x3f49f6d4
-};
+static const u32_t debug_private_key[8] = {0xcd3c1abd, 0x5899b8a6, 0xeb40b799, 0x4aff607b, 0xd2103f50, 0x74c9b3e3, 0xa3c55f38, 0x3f49f6d4};
 
 #if defined(CONFIG_BT_USE_DEBUG_KEYS)
-static const u8_t debug_public_key[64] = {
-    0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, 0xdb, 0xfd, 0xf4, 0xac,
-    0x11, 0x91, 0xf4, 0xef, 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
-    0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20, 0x8b, 0xd2, 0x89, 0x15,
-    0xd0, 0x8e, 0x1c, 0x74, 0x24, 0x30, 0xed, 0x8f, 0xc2, 0x45, 0x63, 0x76,
-    0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63, 0x6d, 0xeb, 0x2a, 0x65,
-    0x49, 0x9c, 0x80, 0xdc
-};
+static const u8_t debug_public_key[64]
+    = {0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, 0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef, 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e, 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20,
+       0x8b, 0xd2, 0x89, 0x15, 0xd0, 0x8e, 0x1c, 0x74, 0x24, 0x30, 0xed, 0x8f, 0xc2, 0x45, 0x63, 0x76, 0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63, 0x6d, 0xeb, 0x2a, 0x65, 0x49, 0x9c, 0x80, 0xdc};
 #endif
 
 enum {
-    PENDING_PUB_KEY,
-    PENDING_DHKEY,
+  PENDING_PUB_KEY,
+  PENDING_DHKEY,
 
-    /* Total number of flags - must be at the end of the enum */
-    NUM_FLAGS,
+  /* Total number of flags - must be at the end of the enum */
+  NUM_FLAGS,
 };
 
 static ATOMIC_DEFINE(flags, NUM_FLAGS);
@@ -70,140 +62,135 @@ static ATOMIC_DEFINE(flags, NUM_FLAGS);
 static K_SEM_DEFINE(cmd_sem, 0, 1);
 
 static struct {
-    u8_t private_key[32];
+  u8_t private_key[32];
 
-    union {
-        u8_t pk[64];
-        u8_t dhkey[32];
-    };
+  union {
+    u8_t pk[64];
+    u8_t dhkey[32];
+  };
 } ecc;
 
-static void send_cmd_status(u16_t opcode, u8_t status)
-{
-    struct bt_hci_evt_cmd_status *evt;
-    struct bt_hci_evt_hdr *hdr;
-    struct net_buf *buf;
+static void send_cmd_status(u16_t opcode, u8_t status) {
+  struct bt_hci_evt_cmd_status *evt;
+  struct bt_hci_evt_hdr        *hdr;
+  struct net_buf               *buf;
 
-    BT_DBG("opcode %x status %x", opcode, status);
+  BT_DBG("opcode %x status %x", opcode, status);
 
-    buf = bt_buf_get_evt(BT_HCI_EVT_CMD_STATUS, false, K_FOREVER);
-    bt_buf_set_type(buf, BT_BUF_EVT);
+  buf = bt_buf_get_evt(BT_HCI_EVT_CMD_STATUS, false, K_FOREVER);
+  bt_buf_set_type(buf, BT_BUF_EVT);
 
-    hdr = net_buf_add(buf, sizeof(*hdr));
-    hdr->evt = BT_HCI_EVT_CMD_STATUS;
-    hdr->len = sizeof(*evt);
+  hdr      = net_buf_add(buf, sizeof(*hdr));
+  hdr->evt = BT_HCI_EVT_CMD_STATUS;
+  hdr->len = sizeof(*evt);
 
-    evt = net_buf_add(buf, sizeof(*evt));
-    evt->ncmd = 1U;
-    evt->opcode = sys_cpu_to_le16(opcode);
-    evt->status = status;
+  evt         = net_buf_add(buf, sizeof(*evt));
+  evt->ncmd   = 1U;
+  evt->opcode = sys_cpu_to_le16(opcode);
+  evt->status = status;
 
-    bt_recv_prio(buf);
+  bt_recv_prio(buf);
 }
 
-static u8_t generate_keys(void)
-{
+static u8_t generate_keys(void) {
 #if !defined(CONFIG_BT_USE_DEBUG_KEYS)
-    do {
-        int rc;
+  do {
+    int rc;
 
-        rc = uECC_make_key(ecc.pk, ecc.private_key, &curve_secp256r1);
-        if (rc == TC_CRYPTO_FAIL) {
-            BT_ERR("Failed to create ECC public/private pair");
-            return BT_HCI_ERR_UNSPECIFIED;
-        }
+    rc = uECC_make_key(ecc.pk, ecc.private_key, &curve_secp256r1);
+    if (rc == TC_CRYPTO_FAIL) {
+      BT_ERR("Failed to create ECC public/private pair");
+      return BT_HCI_ERR_UNSPECIFIED;
+    }
 
-        /* make sure generated key isn't debug key */
-    } while (memcmp(ecc.private_key, debug_private_key, 32) == 0);
+    /* make sure generated key isn't debug key */
+  } while (memcmp(ecc.private_key, debug_private_key, 32) == 0);
 #else
-    sys_memcpy_swap(&ecc.pk, debug_public_key, 32);
-    sys_memcpy_swap(&ecc.pk[32], &debug_public_key[32], 32);
-    sys_memcpy_swap(ecc.private_key, debug_private_key, 32);
+  sys_memcpy_swap(&ecc.pk, debug_public_key, 32);
+  sys_memcpy_swap(&ecc.pk[32], &debug_public_key[32], 32);
+  sys_memcpy_swap(ecc.private_key, debug_private_key, 32);
 #endif
-    return 0;
+  return 0;
 }
 
-static void emulate_le_p256_public_key_cmd(void)
-{
-    struct bt_hci_evt_le_p256_public_key_complete *evt;
-    struct bt_hci_evt_le_meta_event *meta;
-    struct bt_hci_evt_hdr *hdr;
-    struct net_buf *buf;
-    u8_t status;
+static void emulate_le_p256_public_key_cmd(void) {
+  struct bt_hci_evt_le_p256_public_key_complete *evt;
+  struct bt_hci_evt_le_meta_event               *meta;
+  struct bt_hci_evt_hdr                         *hdr;
+  struct net_buf                                *buf;
+  u8_t                                           status;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    status = generate_keys();
+  status = generate_keys();
 
-    buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
+  buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
 
-    hdr = net_buf_add(buf, sizeof(*hdr));
-    hdr->evt = BT_HCI_EVT_LE_META_EVENT;
-    hdr->len = sizeof(*meta) + sizeof(*evt);
+  hdr      = net_buf_add(buf, sizeof(*hdr));
+  hdr->evt = BT_HCI_EVT_LE_META_EVENT;
+  hdr->len = sizeof(*meta) + sizeof(*evt);
 
-    meta = net_buf_add(buf, sizeof(*meta));
-    meta->subevent = BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE;
+  meta           = net_buf_add(buf, sizeof(*meta));
+  meta->subevent = BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE;
 
-    evt = net_buf_add(buf, sizeof(*evt));
-    evt->status = status;
+  evt         = net_buf_add(buf, sizeof(*evt));
+  evt->status = status;
 
-    if (status) {
-        (void)memset(evt->key, 0, sizeof(evt->key));
-    } else {
-        /* Convert X and Y coordinates from big-endian (provided
-		 * by crypto API) to little endian HCI.
-		 */
-        sys_memcpy_swap(evt->key, ecc.pk, 32);
-        sys_memcpy_swap(&evt->key[32], &ecc.pk[32], 32);
-    }
+  if (status) {
+    (void)memset(evt->key, 0, sizeof(evt->key));
+  } else {
+    /* Convert X and Y coordinates from big-endian (provided
+     * by crypto API) to little endian HCI.
+     */
+    sys_memcpy_swap(evt->key, ecc.pk, 32);
+    sys_memcpy_swap(&evt->key[32], &ecc.pk[32], 32);
+  }
 
-    atomic_clear_bit(flags, PENDING_PUB_KEY);
+  atomic_clear_bit(flags, PENDING_PUB_KEY);
 
-    bt_recv(buf);
+  bt_recv(buf);
 }
 
-static void emulate_le_generate_dhkey(void)
-{
-    struct bt_hci_evt_le_generate_dhkey_complete *evt;
-    struct bt_hci_evt_le_meta_event *meta;
-    struct bt_hci_evt_hdr *hdr;
-    struct net_buf *buf;
-    int ret;
-
-    ret = uECC_valid_public_key(ecc.pk, &curve_secp256r1);
-    if (ret < 0) {
-        BT_ERR("public key is not valid (ret %d)", ret);
-        ret = TC_CRYPTO_FAIL;
-    } else {
-        ret = uECC_shared_secret(ecc.pk, ecc.private_key, ecc.dhkey,
-                                 &curve_secp256r1);
-    }
-
-    buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
-
-    hdr = net_buf_add(buf, sizeof(*hdr));
-    hdr->evt = BT_HCI_EVT_LE_META_EVENT;
-    hdr->len = sizeof(*meta) + sizeof(*evt);
-
-    meta = net_buf_add(buf, sizeof(*meta));
-    meta->subevent = BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE;
-
-    evt = net_buf_add(buf, sizeof(*evt));
-
-    if (ret == TC_CRYPTO_FAIL) {
-        evt->status = BT_HCI_ERR_UNSPECIFIED;
-        (void)memset(evt->dhkey, 0, sizeof(evt->dhkey));
-    } else {
-        evt->status = 0U;
-        /* Convert from big-endian (provided by crypto API) to
-		 * little-endian HCI.
-		 */
-        sys_memcpy_swap(evt->dhkey, ecc.dhkey, sizeof(ecc.dhkey));
-    }
-
-    atomic_clear_bit(flags, PENDING_DHKEY);
-
-    bt_recv(buf);
+static void emulate_le_generate_dhkey(void) {
+  struct bt_hci_evt_le_generate_dhkey_complete *evt;
+  struct bt_hci_evt_le_meta_event              *meta;
+  struct bt_hci_evt_hdr                        *hdr;
+  struct net_buf                               *buf;
+  int                                           ret;
+
+  ret = uECC_valid_public_key(ecc.pk, &curve_secp256r1);
+  if (ret < 0) {
+    BT_ERR("public key is not valid (ret %d)", ret);
+    ret = TC_CRYPTO_FAIL;
+  } else {
+    ret = uECC_shared_secret(ecc.pk, ecc.private_key, ecc.dhkey, &curve_secp256r1);
+  }
+
+  buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
+
+  hdr      = net_buf_add(buf, sizeof(*hdr));
+  hdr->evt = BT_HCI_EVT_LE_META_EVENT;
+  hdr->len = sizeof(*meta) + sizeof(*evt);
+
+  meta           = net_buf_add(buf, sizeof(*meta));
+  meta->subevent = BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE;
+
+  evt = net_buf_add(buf, sizeof(*evt));
+
+  if (ret == TC_CRYPTO_FAIL) {
+    evt->status = BT_HCI_ERR_UNSPECIFIED;
+    (void)memset(evt->dhkey, 0, sizeof(evt->dhkey));
+  } else {
+    evt->status = 0U;
+    /* Convert from big-endian (provided by crypto API) to
+     * little-endian HCI.
+     */
+    sys_memcpy_swap(evt->dhkey, ecc.dhkey, sizeof(ecc.dhkey));
+  }
+
+  atomic_clear_bit(flags, PENDING_DHKEY);
+
+  bt_recv(buf);
 }
 
 #if defined(BFLB_BLE)
@@ -212,129 +199,117 @@ static void ecc_thread(void *p1)
 static void ecc_thread(void *p1, void *p2, void *p3)
 #endif
 {
-    while (true) {
-        k_sem_take(&cmd_sem, K_FOREVER);
-
-        if (atomic_test_bit(flags, PENDING_PUB_KEY)) {
-            emulate_le_p256_public_key_cmd();
-        } else if (atomic_test_bit(flags, PENDING_DHKEY)) {
-            emulate_le_generate_dhkey();
-        } else {
-            __ASSERT(0, "Unhandled ECC command");
-        }
+  while (true) {
+    k_sem_take(&cmd_sem, K_FOREVER);
+
+    if (atomic_test_bit(flags, PENDING_PUB_KEY)) {
+      emulate_le_p256_public_key_cmd();
+    } else if (atomic_test_bit(flags, PENDING_DHKEY)) {
+      emulate_le_generate_dhkey();
+    } else {
+      __ASSERT(0, "Unhandled ECC command");
+    }
 #if !defined(BFLB_BLE)
-        STACK_ANALYZE("ecc stack", ecc_thread_stack);
+    STACK_ANALYZE("ecc stack", ecc_thread_stack);
 #endif
-    }
+  }
 }
 
-static void clear_ecc_events(struct net_buf *buf)
-{
-    struct bt_hci_cp_le_set_event_mask *cmd;
+static void clear_ecc_events(struct net_buf *buf) {
+  struct bt_hci_cp_le_set_event_mask *cmd;
 
-    cmd = (void *)(buf->data + sizeof(struct bt_hci_cmd_hdr));
+  cmd = (void *)(buf->data + sizeof(struct bt_hci_cmd_hdr));
 
-    /*
-	 * don't enable controller ECC events as those will be generated from
-	 * emulation code
-	 */
-    cmd->events[0] &= ~0x80; /* LE Read Local P-256 PKey Compl */
-    cmd->events[1] &= ~0x01; /* LE Generate DHKey Compl Event */
+  /*
+   * don't enable controller ECC events as those will be generated from
+   * emulation code
+   */
+  cmd->events[0] &= ~0x80; /* LE Read Local P-256 PKey Compl */
+  cmd->events[1] &= ~0x01; /* LE Generate DHKey Compl Event */
 }
 
-static void le_gen_dhkey(struct net_buf *buf)
-{
-    struct bt_hci_cp_le_generate_dhkey *cmd;
-    u8_t status;
-
-    if (atomic_test_bit(flags, PENDING_PUB_KEY)) {
-        status = BT_HCI_ERR_CMD_DISALLOWED;
-        goto send_status;
-    }
-
-    if (buf->len < sizeof(struct bt_hci_cp_le_generate_dhkey)) {
-        status = BT_HCI_ERR_INVALID_PARAM;
-        goto send_status;
-    }
-
-    if (atomic_test_and_set_bit(flags, PENDING_DHKEY)) {
-        status = BT_HCI_ERR_CMD_DISALLOWED;
-        goto send_status;
-    }
-
-    cmd = (void *)buf->data;
-    /* Convert X and Y coordinates from little-endian HCI to
-	 * big-endian (expected by the crypto API).
-	 */
-    sys_memcpy_swap(ecc.pk, cmd->key, 32);
-    sys_memcpy_swap(&ecc.pk[32], &cmd->key[32], 32);
-    k_sem_give(&cmd_sem);
-    status = BT_HCI_ERR_SUCCESS;
+static void le_gen_dhkey(struct net_buf *buf) {
+  struct bt_hci_cp_le_generate_dhkey *cmd;
+  u8_t                                status;
+
+  if (atomic_test_bit(flags, PENDING_PUB_KEY)) {
+    status = BT_HCI_ERR_CMD_DISALLOWED;
+    goto send_status;
+  }
+
+  if (buf->len < sizeof(struct bt_hci_cp_le_generate_dhkey)) {
+    status = BT_HCI_ERR_INVALID_PARAM;
+    goto send_status;
+  }
+
+  if (atomic_test_and_set_bit(flags, PENDING_DHKEY)) {
+    status = BT_HCI_ERR_CMD_DISALLOWED;
+    goto send_status;
+  }
+
+  cmd = (void *)buf->data;
+  /* Convert X and Y coordinates from little-endian HCI to
+   * big-endian (expected by the crypto API).
+   */
+  sys_memcpy_swap(ecc.pk, cmd->key, 32);
+  sys_memcpy_swap(&ecc.pk[32], &cmd->key[32], 32);
+  k_sem_give(&cmd_sem);
+  status = BT_HCI_ERR_SUCCESS;
 
 send_status:
-    net_buf_unref(buf);
-    send_cmd_status(BT_HCI_OP_LE_GENERATE_DHKEY, status);
+  net_buf_unref(buf);
+  send_cmd_status(BT_HCI_OP_LE_GENERATE_DHKEY, status);
 }
 
-static void le_p256_pub_key(struct net_buf *buf)
-{
-    u8_t status;
+static void le_p256_pub_key(struct net_buf *buf) {
+  u8_t status;
 
-    net_buf_unref(buf);
+  net_buf_unref(buf);
 
-    if (atomic_test_bit(flags, PENDING_DHKEY)) {
-        status = BT_HCI_ERR_CMD_DISALLOWED;
-    } else if (atomic_test_and_set_bit(flags, PENDING_PUB_KEY)) {
-        status = BT_HCI_ERR_CMD_DISALLOWED;
-    } else {
-        k_sem_give(&cmd_sem);
-        status = BT_HCI_ERR_SUCCESS;
-    }
+  if (atomic_test_bit(flags, PENDING_DHKEY)) {
+    status = BT_HCI_ERR_CMD_DISALLOWED;
+  } else if (atomic_test_and_set_bit(flags, PENDING_PUB_KEY)) {
+    status = BT_HCI_ERR_CMD_DISALLOWED;
+  } else {
+    k_sem_give(&cmd_sem);
+    status = BT_HCI_ERR_SUCCESS;
+  }
 
-    send_cmd_status(BT_HCI_OP_LE_P256_PUBLIC_KEY, status);
+  send_cmd_status(BT_HCI_OP_LE_P256_PUBLIC_KEY, status);
 }
 
-int bt_hci_ecc_send(struct net_buf *buf)
-{
-    if (bt_buf_get_type(buf) == BT_BUF_CMD) {
-        struct bt_hci_cmd_hdr *chdr = (void *)buf->data;
-
-        switch (sys_le16_to_cpu(chdr->opcode)) {
-            case BT_HCI_OP_LE_P256_PUBLIC_KEY:
-                net_buf_pull(buf, sizeof(*chdr));
-                le_p256_pub_key(buf);
-                return 0;
-            case BT_HCI_OP_LE_GENERATE_DHKEY:
-                net_buf_pull(buf, sizeof(*chdr));
-                le_gen_dhkey(buf);
-                return 0;
-            case BT_HCI_OP_LE_SET_EVENT_MASK:
-                clear_ecc_events(buf);
-                break;
-            default:
-                break;
-        }
+int bt_hci_ecc_send(struct net_buf *buf) {
+  if (bt_buf_get_type(buf) == BT_BUF_CMD) {
+    struct bt_hci_cmd_hdr *chdr = (void *)buf->data;
+
+    switch (sys_le16_to_cpu(chdr->opcode)) {
+    case BT_HCI_OP_LE_P256_PUBLIC_KEY:
+      net_buf_pull(buf, sizeof(*chdr));
+      le_p256_pub_key(buf);
+      return 0;
+    case BT_HCI_OP_LE_GENERATE_DHKEY:
+      net_buf_pull(buf, sizeof(*chdr));
+      le_gen_dhkey(buf);
+      return 0;
+    case BT_HCI_OP_LE_SET_EVENT_MASK:
+      clear_ecc_events(buf);
+      break;
+    default:
+      break;
     }
+  }
 
-    return bt_dev.drv->send(buf);
+  return bt_dev.drv->send(buf);
 }
 
-int default_CSPRNG(u8_t *dst, unsigned int len)
-{
-    return !bt_rand(dst, len);
-}
+int default_CSPRNG(u8_t *dst, unsigned int len) { return !bt_rand(dst, len); }
 
-void bt_hci_ecc_init(void)
-{
+void bt_hci_ecc_init(void) {
 #if defined(BFLB_BLE)
-    k_sem_init(&cmd_sem, 0, 1);
-    k_thread_create(&ecc_thread_data, "ecc_thread",
-                    CONFIG_BT_HCI_ECC_STACK_SIZE, ecc_thread,
-                    CONFIG_BT_WORK_QUEUE_PRIO);
+  k_sem_init(&cmd_sem, 0, 1);
+  k_thread_create(&ecc_thread_data, "ecc_thread", CONFIG_BT_HCI_ECC_STACK_SIZE, ecc_thread, CONFIG_BT_WORK_QUEUE_PRIO);
 #else
-    k_thread_create(&ecc_thread_data, ecc_thread_stack,
-                    K_THREAD_STACK_SIZEOF(ecc_thread_stack), ecc_thread,
-                    NULL, NULL, NULL, K_PRIO_PREEMPT(10), 0, K_NO_WAIT);
-    k_thread_name_set(&ecc_thread_data, "BT ECC");
+  k_thread_create(&ecc_thread_data, ecc_thread_stack, K_THREAD_STACK_SIZEOF(ecc_thread_stack), ecc_thread, NULL, NULL, NULL, K_PRIO_PREEMPT(10), 0, K_NO_WAIT);
+  k_thread_name_set(&ecc_thread_data, "BT ECC");
 #endif
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hfp_hf.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hfp_hf.c
index a8c715a12c..ccd8ef8554 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hfp_hf.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hfp_hf.c
@@ -5,12 +5,12 @@
  *
  * SPDX-License-Identifier: Apache-2.0
  */
-#include 
-#include 
 #include 
 #include 
-#include 
+#include 
 #include 
+#include 
+#include 
 
 #include 
 
@@ -18,25 +18,24 @@
 #define LOG_MODULE_NAME bt_hfp_hf
 #include "log.h"
 
-#include 
 #include 
+#include 
 #include 
 
-#include "hci_core.h"
+#include "at.h"
 #include "conn_internal.h"
+#include "hci_core.h"
+#include "hfp_internal.h"
 #include "l2cap_internal.h"
 #include "rfcomm_internal.h"
-#include "at.h"
-#include "hfp_internal.h"
 
 #define MAX_IND_STR_LEN 17
 
 struct bt_hfp_hf_cb *bt_hf;
-bool hfp_codec_msbc = 0;
+bool                 hfp_codec_msbc = 0;
 
 #if !defined(BFLB_DYNAMIC_ALLOC_MEM)
-NET_BUF_POOL_FIXED_DEFINE(hf_pool, CONFIG_BT_MAX_CONN + 1,
-                          BT_RFCOMM_BUF_SIZE(BT_HF_CLIENT_MAX_PDU), NULL);
+NET_BUF_POOL_FIXED_DEFINE(hf_pool, CONFIG_BT_MAX_CONN + 1, BT_RFCOMM_BUF_SIZE(BT_HF_CLIENT_MAX_PDU), NULL);
 #else
 struct net_buf_pool hf_pool;
 #endif
@@ -45,54 +44,28 @@ static struct bt_hfp_hf bt_hfp_hf_pool[CONFIG_BT_MAX_CONN];
 
 static struct bt_sdp_attribute hfp_attrs[] = {
     BT_SDP_NEW_SERVICE,
-    BT_SDP_LIST(
-        BT_SDP_ATTR_SVCLASS_ID_LIST,
-        BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 10),
-        BT_SDP_DATA_ELEM_LIST(
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_SDP_HANDSFREE_SVCLASS) }, ) },
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_SDP_GENERIC_AUDIO_SVCLASS) }, ) }, )),
-    BT_SDP_LIST(
-        BT_SDP_ATTR_PROTO_DESC_LIST,
-        BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 12),
-        BT_SDP_DATA_ELEM_LIST(
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_SDP_PROTO_L2CAP) }, ) },
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 5),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_SDP_PROTO_RFCOMM) },
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UINT8),
-                    BT_SDP_ARRAY_16(BT_RFCOMM_CHAN_HFP_HF) }) }, )),
-    BT_SDP_LIST(
-        BT_SDP_ATTR_PROFILE_DESC_LIST,
-        BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 8),
-        BT_SDP_DATA_ELEM_LIST(
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 6),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_SDP_HANDSFREE_SVCLASS) },
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UINT16),
-                    BT_SDP_ARRAY_16(0x0107) }, ) }, )),
+    BT_SDP_LIST(BT_SDP_ATTR_SVCLASS_ID_LIST, BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 10),
+                BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3), BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE(BT_SDP_UUID16), BT_SDP_ARRAY_16(BT_SDP_HANDSFREE_SVCLASS)}, )},
+                                      {BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3), BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE(BT_SDP_UUID16), BT_SDP_ARRAY_16(BT_SDP_GENERIC_AUDIO_SVCLASS)}, )}, )),
+    BT_SDP_LIST(BT_SDP_ATTR_PROTO_DESC_LIST, BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 12),
+                BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3), BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE(BT_SDP_UUID16), BT_SDP_ARRAY_16(BT_SDP_PROTO_L2CAP)}, )},
+                                      {BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 5), BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE(BT_SDP_UUID16), BT_SDP_ARRAY_16(BT_SDP_PROTO_RFCOMM)},
+                                                                                                   {BT_SDP_TYPE_SIZE(BT_SDP_UINT8), BT_SDP_ARRAY_16(BT_RFCOMM_CHAN_HFP_HF)})}, )),
+    BT_SDP_LIST(BT_SDP_ATTR_PROFILE_DESC_LIST, BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 8),
+                BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 6), BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE(BT_SDP_UUID16), BT_SDP_ARRAY_16(BT_SDP_HANDSFREE_SVCLASS)},
+                                                                                                   {BT_SDP_TYPE_SIZE(BT_SDP_UINT16), BT_SDP_ARRAY_16(0x0107)}, )}, )),
     BT_SDP_SERVICE_NAME("hands-free"),
     /*
-	"SupportedFeatures" attribute bit mapping for the HF
-	bit 0: EC and/or NR function
-	bit 1: Call waiting or three-way calling
-	bit 2: CLI presentation capability
-	bit 3: Voice recognition activation
-	bit 4: Remote volume control
-	bit 5: Wide band speech
-	bit 6: Enhanced Voice Recognition Status
-	bit 7: Voice Recognition Text
-	*/
+        "SupportedFeatures" attribute bit mapping for the HF
+        bit 0: EC and/or NR function
+        bit 1: Call waiting or three-way calling
+        bit 2: CLI presentation capability
+        bit 3: Voice recognition activation
+        bit 4: Remote volume control
+        bit 5: Wide band speech
+        bit 6: Enhanced Voice Recognition Status
+        bit 7: Voice Recognition Text
+        */
     BT_SDP_SUPPORTED_FEATURES(0x0035),
 };
 
@@ -100,788 +73,704 @@ static struct bt_sdp_record hfp_rec = BT_SDP_RECORD(hfp_attrs);
 
 /* The order should follow the enum hfp_hf_ag_indicators */
 static const struct {
-    char *name;
-    uint32_t min;
-    uint32_t max;
+  char    *name;
+  uint32_t min;
+  uint32_t max;
 } ag_ind[] = {
-    { "service", 0, 1 },   /* HF_SERVICE_IND */
-    { "call", 0, 1 },      /* HF_CALL_IND */
-    { "callsetup", 0, 3 }, /* HF_CALL_SETUP_IND */
-    { "callheld", 0, 2 },  /* HF_CALL_HELD_IND */
-    { "signal", 0, 5 },    /* HF_SINGNAL_IND */
-    { "roam", 0, 1 },      /* HF_ROAM_IND */
-    { "battchg", 0, 5 }    /* HF_BATTERY_IND */
+    {"service", 0, 1},   /* HF_SERVICE_IND */
+    {"call", 0, 1},      /* HF_CALL_IND */
+    {"callsetup", 0, 3}, /* HF_CALL_SETUP_IND */
+    {"callheld", 0, 2},  /* HF_CALL_HELD_IND */
+    {"signal", 0, 5},    /* HF_SINGNAL_IND */
+    {"roam", 0, 1},      /* HF_ROAM_IND */
+    {"battchg", 0, 5}    /* HF_BATTERY_IND */
 };
 
-static void connected(struct bt_conn *conn)
-{
-    BT_DBG("HFP HF Connected!");
-}
+static void connected(struct bt_conn *conn) { BT_DBG("HFP HF Connected!"); }
 
-static void disconnected(struct bt_conn *conn)
-{
-    BT_DBG("HFP HF Disconnected!");
-}
+static void disconnected(struct bt_conn *conn) { BT_DBG("HFP HF Disconnected!"); }
 
-static void service(struct bt_conn *conn, uint32_t value)
-{
-    BT_DBG("Service indicator value: %u", value);
-}
+static void service(struct bt_conn *conn, uint32_t value) { BT_DBG("Service indicator value: %u", value); }
 
-static void call(struct bt_conn *conn, uint32_t value)
-{
-    BT_DBG("Call indicator value: %u", value);
-}
+static void call(struct bt_conn *conn, uint32_t value) { BT_DBG("Call indicator value: %u", value); }
 
-static void call_setup(struct bt_conn *conn, uint32_t value)
-{
-    BT_DBG("Call Setup indicator value: %u", value);
-}
+static void call_setup(struct bt_conn *conn, uint32_t value) { BT_DBG("Call Setup indicator value: %u", value); }
 
-static void call_held(struct bt_conn *conn, uint32_t value)
-{
-    BT_DBG("Call Held indicator value: %u", value);
-}
+static void call_held(struct bt_conn *conn, uint32_t value) { BT_DBG("Call Held indicator value: %u", value); }
 
-static void signal(struct bt_conn *conn, uint32_t value)
-{
-    BT_DBG("Signal indicator value: %u", value);
-}
+static void signal(struct bt_conn *conn, uint32_t value) { BT_DBG("Signal indicator value: %u", value); }
 
-static void roam(struct bt_conn *conn, uint32_t value)
-{
-    BT_DBG("Roaming indicator value: %u", value);
-}
+static void roam(struct bt_conn *conn, uint32_t value) { BT_DBG("Roaming indicator value: %u", value); }
 
-static void battery(struct bt_conn *conn, uint32_t value)
-{
-    BT_DBG("Battery indicator value: %u", value);
-}
+static void battery(struct bt_conn *conn, uint32_t value) { BT_DBG("Battery indicator value: %u", value); }
 
-static void ring_cb(struct bt_conn *conn)
-{
-    BT_DBG("Incoming Call...");
-}
+static void ring_cb(struct bt_conn *conn) { BT_DBG("Incoming Call..."); }
 
 static struct bt_hfp_hf_cb hf_cb = {
-    .connected = connected,
-    .disconnected = disconnected,
-    .service = service,
-    .call = call,
-    .call_setup = call_setup,
-    .call_held = call_held,
-    .signal = signal,
-    .roam = roam,
-    .battery = battery,
+    .connected       = connected,
+    .disconnected    = disconnected,
+    .service         = service,
+    .call            = call,
+    .call_setup      = call_setup,
+    .call_held       = call_held,
+    .signal          = signal,
+    .roam            = roam,
+    .battery         = battery,
     .ring_indication = ring_cb,
 };
 
-void hf_slc_error(struct at_client *hf_at)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    int err;
+void hf_slc_error(struct at_client *hf_at) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  int               err;
 
-    BT_ERR("SLC error: disconnecting");
-    err = bt_rfcomm_dlc_disconnect(&hf->rfcomm_dlc);
-    if (err) {
-        BT_ERR("Rfcomm: Unable to disconnect :%d", -err);
-    }
+  BT_ERR("SLC error: disconnecting");
+  err = bt_rfcomm_dlc_disconnect(&hf->rfcomm_dlc);
+  if (err) {
+    BT_ERR("Rfcomm: Unable to disconnect :%d", -err);
+  }
 }
 
-int hfp_hf_send_cmd(struct bt_hfp_hf *hf, at_resp_cb_t resp,
-                    at_finish_cb_t finish, const char *format, ...)
-{
-    struct net_buf *buf;
-    va_list vargs;
-    int ret;
+int hfp_hf_send_cmd(struct bt_hfp_hf *hf, at_resp_cb_t resp, at_finish_cb_t finish, const char *format, ...) {
+  struct net_buf *buf;
+  va_list         vargs;
+  int             ret;
 
-    /* register the callbacks */
-    at_register(&hf->at, resp, finish);
+  /* register the callbacks */
+  at_register(&hf->at, resp, finish);
 
-    buf = bt_rfcomm_create_pdu(&hf_pool);
-    if (!buf) {
-        BT_ERR("No Buffers!");
-        return -ENOMEM;
-    }
+  buf = bt_rfcomm_create_pdu(&hf_pool);
+  if (!buf) {
+    BT_ERR("No Buffers!");
+    return -ENOMEM;
+  }
 
-    va_start(vargs, format);
-    ret = vsnprintf((char *)buf->data, (net_buf_tailroom(buf) - 1), format, vargs);
-    if (ret < 0) {
-        BT_ERR("Unable to format variable arguments");
-        return ret;
-    }
-    va_end(vargs);
+  va_start(vargs, format);
+  ret = vsnprintf((char *)buf->data, (net_buf_tailroom(buf) - 1), format, vargs);
+  if (ret < 0) {
+    BT_ERR("Unable to format variable arguments");
+    return ret;
+  }
+  va_end(vargs);
 
-    net_buf_add(buf, ret);
-    net_buf_add_u8(buf, '\r');
+  net_buf_add(buf, ret);
+  net_buf_add_u8(buf, '\r');
 
-    ret = bt_rfcomm_dlc_send(&hf->rfcomm_dlc, buf);
-    if (ret < 0) {
-        BT_ERR("Rfcomm send error :(%d)", ret);
-        return ret;
-    }
+  ret = bt_rfcomm_dlc_send(&hf->rfcomm_dlc, buf);
+  if (ret < 0) {
+    BT_ERR("Rfcomm send error :(%d)", ret);
+    return ret;
+  }
 
-    return 0;
+  return 0;
 }
 
-int brsf_handle(struct at_client *hf_at)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    uint32_t val;
-    int ret;
+int brsf_handle(struct at_client *hf_at) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  uint32_t          val;
+  int               ret;
 
-    ret = at_get_number(hf_at, &val);
-    if (ret < 0) {
-        BT_ERR("Error getting value");
-        return ret;
-    }
+  ret = at_get_number(hf_at, &val);
+  if (ret < 0) {
+    BT_ERR("Error getting value");
+    return ret;
+  }
 
-    hf->ag_features = val;
+  hf->ag_features = val;
 
-    return 0;
+  return 0;
 }
 
-int brsf_resp(struct at_client *hf_at, struct net_buf *buf)
-{
-    int err;
+int brsf_resp(struct at_client *hf_at, struct net_buf *buf) {
+  int err;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    err = at_parse_cmd_input(hf_at, buf, "BRSF", brsf_handle,
-                             AT_CMD_TYPE_NORMAL);
-    if (err < 0) {
-        /* Returning negative value is avoided before SLC connection
-		 * established.
-		 */
-        BT_ERR("Error parsing CMD input");
-        hf_slc_error(hf_at);
-    }
+  err = at_parse_cmd_input(hf_at, buf, "BRSF", brsf_handle, AT_CMD_TYPE_NORMAL);
+  if (err < 0) {
+    /* Returning negative value is avoided before SLC connection
+     * established.
+     */
+    BT_ERR("Error parsing CMD input");
+    hf_slc_error(hf_at);
+  }
 
-    return 0;
+  return 0;
 }
 
-static void cind_handle_values(struct at_client *hf_at, uint32_t index,
-                               char *name, uint32_t min, uint32_t max)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    int i;
-
-    BT_DBG("index: %u, name: %s, min: %u, max:%u", index, name, min, max);
+static void cind_handle_values(struct at_client *hf_at, uint32_t index, char *name, uint32_t min, uint32_t max) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  int               i;
 
-    for (i = 0; i < ARRAY_SIZE(ag_ind); i++) {
-        if (strcmp(name, ag_ind[i].name) != 0) {
-            continue;
-        }
-        if (min != ag_ind[i].min || max != ag_ind[i].max) {
-            BT_ERR("%s indicator min/max value not matching", name);
-        }
+  BT_DBG("index: %u, name: %s, min: %u, max:%u", index, name, min, max);
 
-        hf->ind_table[index] = i;
-        break;
+  for (i = 0; i < ARRAY_SIZE(ag_ind); i++) {
+    if (strcmp(name, ag_ind[i].name) != 0) {
+      continue;
     }
-}
-
-int cind_handle(struct at_client *hf_at)
-{
-    uint32_t index = 0U;
-
-    /* Parsing Example: CIND: ("call",(0,1)) etc.. */
-    while (at_has_next_list(hf_at)) {
-        char name[MAX_IND_STR_LEN];
-        uint32_t min, max;
-
-        if (at_open_list(hf_at) < 0) {
-            BT_ERR("Could not get open list");
-            goto error;
-        }
-
-        if (at_list_get_string(hf_at, name, sizeof(name)) < 0) {
-            BT_ERR("Could not get string");
-            goto error;
-        }
-
-        if (at_open_list(hf_at) < 0) {
-            BT_ERR("Could not get open list");
-            goto error;
-        }
-
-        if (at_list_get_range(hf_at, &min, &max) < 0) {
-            BT_ERR("Could not get range");
-            goto error;
-        }
-
-        if (at_close_list(hf_at) < 0) {
-            BT_ERR("Could not get close list");
-            goto error;
-        }
-
-        if (at_close_list(hf_at) < 0) {
-            BT_ERR("Could not get close list");
-            goto error;
-        }
-
-        cind_handle_values(hf_at, index, name, min, max);
-        index++;
+    if (min != ag_ind[i].min || max != ag_ind[i].max) {
+      BT_ERR("%s indicator min/max value not matching", name);
     }
 
-    return 0;
-error:
-    BT_ERR("Error on CIND response");
-    hf_slc_error(hf_at);
-    return -EINVAL;
+    hf->ind_table[index] = i;
+    break;
+  }
 }
 
-int cind_resp(struct at_client *hf_at, struct net_buf *buf)
-{
-    int err;
+int cind_handle(struct at_client *hf_at) {
+  uint32_t index = 0U;
 
-    err = at_parse_cmd_input(hf_at, buf, "CIND", cind_handle,
-                             AT_CMD_TYPE_NORMAL);
-    if (err < 0) {
-        BT_ERR("Error parsing CMD input");
-        hf_slc_error(hf_at);
-    }
+  /* Parsing Example: CIND: ("call",(0,1)) etc.. */
+  while (at_has_next_list(hf_at)) {
+    char     name[MAX_IND_STR_LEN];
+    uint32_t min, max;
 
-    return 0;
-}
-
-void ag_indicator_handle_values(struct at_client *hf_at, uint32_t index,
-                                uint32_t value)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    struct bt_conn *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
+    if (at_open_list(hf_at) < 0) {
+      BT_ERR("Could not get open list");
+      goto error;
+    }
 
-    BT_DBG("Index :%u, Value :%u", index, value);
+    if (at_list_get_string(hf_at, name, sizeof(name)) < 0) {
+      BT_ERR("Could not get string");
+      goto error;
+    }
 
-    if (index >= ARRAY_SIZE(ag_ind)) {
-        BT_ERR("Max only %lu indicators are supported",
-               ARRAY_SIZE(ag_ind));
-        return;
+    if (at_open_list(hf_at) < 0) {
+      BT_ERR("Could not get open list");
+      goto error;
     }
 
-    if (value > ag_ind[hf->ind_table[index]].max ||
-        value < ag_ind[hf->ind_table[index]].min) {
-        BT_ERR("Indicators out of range - value: %u", value);
-        return;
+    if (at_list_get_range(hf_at, &min, &max) < 0) {
+      BT_ERR("Could not get range");
+      goto error;
     }
 
-    switch (hf->ind_table[index]) {
-        case HF_SERVICE_IND:
-            if (bt_hf->service) {
-                bt_hf->service(conn, value);
-            }
-            break;
-        case HF_CALL_IND:
-            if (bt_hf->call) {
-                bt_hf->call(conn, value);
-            }
-            break;
-        case HF_CALL_SETUP_IND:
-            if (bt_hf->call_setup) {
-                bt_hf->call_setup(conn, value);
-            }
-            break;
-        case HF_CALL_HELD_IND:
-            if (bt_hf->call_held) {
-                bt_hf->call_held(conn, value);
-            }
-            break;
-        case HF_SINGNAL_IND:
-            if (bt_hf->signal) {
-                bt_hf->signal(conn, value);
-            }
-            break;
-        case HF_ROAM_IND:
-            if (bt_hf->roam) {
-                bt_hf->roam(conn, value);
-            }
-            break;
-        case HF_BATTERY_IND:
-            if (bt_hf->battery) {
-                bt_hf->battery(conn, value);
-            }
-            break;
-        default:
-            BT_ERR("Unknown AG indicator");
-            break;
+    if (at_close_list(hf_at) < 0) {
+      BT_ERR("Could not get close list");
+      goto error;
     }
-}
 
-int cind_status_handle(struct at_client *hf_at)
-{
-    uint32_t index = 0U;
+    if (at_close_list(hf_at) < 0) {
+      BT_ERR("Could not get close list");
+      goto error;
+    }
 
-    while (at_has_next_list(hf_at)) {
-        uint32_t value;
-        int ret;
+    cind_handle_values(hf_at, index, name, min, max);
+    index++;
+  }
 
-        ret = at_get_number(hf_at, &value);
-        if (ret < 0) {
-            BT_ERR("could not get the value");
-            return ret;
-        }
+  return 0;
+error:
+  BT_ERR("Error on CIND response");
+  hf_slc_error(hf_at);
+  return -EINVAL;
+}
 
-        ag_indicator_handle_values(hf_at, index, value);
+int cind_resp(struct at_client *hf_at, struct net_buf *buf) {
+  int err;
 
-        index++;
-    }
+  err = at_parse_cmd_input(hf_at, buf, "CIND", cind_handle, AT_CMD_TYPE_NORMAL);
+  if (err < 0) {
+    BT_ERR("Error parsing CMD input");
+    hf_slc_error(hf_at);
+  }
 
-    return 0;
+  return 0;
 }
 
-int cind_status_resp(struct at_client *hf_at, struct net_buf *buf)
-{
-    int err;
+void ag_indicator_handle_values(struct at_client *hf_at, uint32_t index, uint32_t value) {
+  struct bt_hfp_hf *hf   = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  struct bt_conn   *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
 
-    err = at_parse_cmd_input(hf_at, buf, "CIND", cind_status_handle,
-                             AT_CMD_TYPE_NORMAL);
-    if (err < 0) {
-        BT_ERR("Error parsing CMD input");
-        hf_slc_error(hf_at);
-    }
+  BT_DBG("Index :%u, Value :%u", index, value);
 
-    return 0;
-}
+  if (index >= ARRAY_SIZE(ag_ind)) {
+    BT_ERR("Max only %lu indicators are supported", ARRAY_SIZE(ag_ind));
+    return;
+  }
 
-int ciev_handle(struct at_client *hf_at)
-{
-    uint32_t index, value;
-    int ret;
+  if (value > ag_ind[hf->ind_table[index]].max || value < ag_ind[hf->ind_table[index]].min) {
+    BT_ERR("Indicators out of range - value: %u", value);
+    return;
+  }
 
-    ret = at_get_number(hf_at, &index);
-    if (ret < 0) {
-        BT_ERR("could not get the Index");
-        return ret;
+  switch (hf->ind_table[index]) {
+  case HF_SERVICE_IND:
+    if (bt_hf->service) {
+      bt_hf->service(conn, value);
+    }
+    break;
+  case HF_CALL_IND:
+    if (bt_hf->call) {
+      bt_hf->call(conn, value);
+    }
+    break;
+  case HF_CALL_SETUP_IND:
+    if (bt_hf->call_setup) {
+      bt_hf->call_setup(conn, value);
+    }
+    break;
+  case HF_CALL_HELD_IND:
+    if (bt_hf->call_held) {
+      bt_hf->call_held(conn, value);
     }
-    /* The first element of the list shall have 1 */
-    if (!index) {
-        BT_ERR("Invalid index value '0'");
-        return 0;
+    break;
+  case HF_SINGNAL_IND:
+    if (bt_hf->signal) {
+      bt_hf->signal(conn, value);
     }
+    break;
+  case HF_ROAM_IND:
+    if (bt_hf->roam) {
+      bt_hf->roam(conn, value);
+    }
+    break;
+  case HF_BATTERY_IND:
+    if (bt_hf->battery) {
+      bt_hf->battery(conn, value);
+    }
+    break;
+  default:
+    BT_ERR("Unknown AG indicator");
+    break;
+  }
+}
+
+int cind_status_handle(struct at_client *hf_at) {
+  uint32_t index = 0U;
+
+  while (at_has_next_list(hf_at)) {
+    uint32_t value;
+    int      ret;
 
     ret = at_get_number(hf_at, &value);
     if (ret < 0) {
-        BT_ERR("could not get the value");
-        return ret;
+      BT_ERR("could not get the value");
+      return ret;
     }
 
-    ag_indicator_handle_values(hf_at, (index - 1), value);
+    ag_indicator_handle_values(hf_at, index, value);
 
-    return 0;
+    index++;
+  }
+
+  return 0;
 }
 
-int ring_handle(struct at_client *hf_at)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    struct bt_conn *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
+int cind_status_resp(struct at_client *hf_at, struct net_buf *buf) {
+  int err;
 
-    if (bt_hf->ring_indication) {
-        bt_hf->ring_indication(conn);
-    }
+  err = at_parse_cmd_input(hf_at, buf, "CIND", cind_status_handle, AT_CMD_TYPE_NORMAL);
+  if (err < 0) {
+    BT_ERR("Error parsing CMD input");
+    hf_slc_error(hf_at);
+  }
 
+  return 0;
+}
+
+int ciev_handle(struct at_client *hf_at) {
+  uint32_t index, value;
+  int      ret;
+
+  ret = at_get_number(hf_at, &index);
+  if (ret < 0) {
+    BT_ERR("could not get the Index");
+    return ret;
+  }
+  /* The first element of the list shall have 1 */
+  if (!index) {
+    BT_ERR("Invalid index value '0'");
     return 0;
+  }
+
+  ret = at_get_number(hf_at, &value);
+  if (ret < 0) {
+    BT_ERR("could not get the value");
+    return ret;
+  }
+
+  ag_indicator_handle_values(hf_at, (index - 1), value);
+
+  return 0;
 }
 
-int bcs_handle(struct at_client *hf_at)
-{
-    uint32_t value;
-    int ret;
+int ring_handle(struct at_client *hf_at) {
+  struct bt_hfp_hf *hf   = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  struct bt_conn   *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
 
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  if (bt_hf->ring_indication) {
+    bt_hf->ring_indication(conn);
+  }
 
-    ret = at_get_number(hf_at, &value);
-    if (ret < 0) {
-        BT_ERR("could not get the value");
-        return ret;
+  return 0;
+}
+
+int bcs_handle(struct at_client *hf_at) {
+  uint32_t value;
+  int      ret;
+
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+
+  ret = at_get_number(hf_at, &value);
+  if (ret < 0) {
+    BT_ERR("could not get the value");
+    return ret;
+  }
+  if (value == 1) {
+    if (hfp_hf_send_cmd(hf, NULL, NULL, "AT+BCS=1") < 0) {
+      BT_ERR("Error Sending AT+BCS=1");
     }
-    if (value == 1) {
-        if (hfp_hf_send_cmd(hf, NULL, NULL, "AT+BCS=1") < 0) {
-            BT_ERR("Error Sending AT+BCS=1");
-        }
-    } else if (value == 2) {
-        if (hfp_hf_send_cmd(hf, NULL, NULL, "AT+BCS=2") < 0) {
-            BT_ERR("Error Sending AT+BCS=2");
-        } else {
-            hfp_codec_msbc = 1;
-        }
+  } else if (value == 2) {
+    if (hfp_hf_send_cmd(hf, NULL, NULL, "AT+BCS=2") < 0) {
+      BT_ERR("Error Sending AT+BCS=2");
     } else {
-        BT_WARN("Invail BCS value !");
+      hfp_codec_msbc = 1;
     }
+  } else {
+    BT_WARN("Invail BCS value !");
+  }
 
-    return 0;
+  return 0;
 }
 
 static const struct unsolicited {
-    const char *cmd;
-    enum at_cmd_type type;
-    int (*func)(struct at_client *hf_at);
-} handlers[] = {
-    { "CIEV", AT_CMD_TYPE_UNSOLICITED, ciev_handle },
-    { "RING", AT_CMD_TYPE_OTHER, ring_handle },
-    { "BCS", AT_CMD_TYPE_UNSOLICITED, bcs_handle }
-};
+  const char      *cmd;
+  enum at_cmd_type type;
+  int (*func)(struct at_client *hf_at);
+} handlers[] = {{"CIEV", AT_CMD_TYPE_UNSOLICITED, ciev_handle}, {"RING", AT_CMD_TYPE_OTHER, ring_handle}, {"BCS", AT_CMD_TYPE_UNSOLICITED, bcs_handle}};
 
-static const struct unsolicited *hfp_hf_unsol_lookup(struct at_client *hf_at)
-{
-    int i;
+static const struct unsolicited *hfp_hf_unsol_lookup(struct at_client *hf_at) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(handlers); i++) {
-        if (!strncmp(hf_at->buf, handlers[i].cmd,
-                     strlen(handlers[i].cmd))) {
-            return &handlers[i];
-        }
+  for (i = 0; i < ARRAY_SIZE(handlers); i++) {
+    if (!strncmp(hf_at->buf, handlers[i].cmd, strlen(handlers[i].cmd))) {
+      return &handlers[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-int unsolicited_cb(struct at_client *hf_at, struct net_buf *buf)
-{
-    const struct unsolicited *handler;
+int unsolicited_cb(struct at_client *hf_at, struct net_buf *buf) {
+  const struct unsolicited *handler;
 
-    handler = hfp_hf_unsol_lookup(hf_at);
-    if (!handler) {
-        BT_ERR("Unhandled unsolicited response");
-        return -ENOMSG;
-    }
+  handler = hfp_hf_unsol_lookup(hf_at);
+  if (!handler) {
+    BT_ERR("Unhandled unsolicited response");
+    return -ENOMSG;
+  }
 
-    if (!at_parse_cmd_input(hf_at, buf, handler->cmd, handler->func,
-                            handler->type)) {
-        return 0;
-    }
+  if (!at_parse_cmd_input(hf_at, buf, handler->cmd, handler->func, handler->type)) {
+    return 0;
+  }
 
-    return -ENOMSG;
+  return -ENOMSG;
 }
 
-int cmd_complete(struct at_client *hf_at, enum at_result result,
-                 enum at_cme cme_err)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    struct bt_conn *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
-    struct bt_hfp_hf_cmd_complete cmd = { 0 };
-
-    BT_DBG("");
-
-    switch (result) {
-        case AT_RESULT_OK:
-            cmd.type = HFP_HF_CMD_OK;
-            break;
-        case AT_RESULT_ERROR:
-            cmd.type = HFP_HF_CMD_ERROR;
-            break;
-        case AT_RESULT_CME_ERROR:
-            cmd.type = HFP_HF_CMD_CME_ERROR;
-            cmd.cme = cme_err;
-            break;
-        default:
-            BT_ERR("Unknown error code");
-            cmd.type = HFP_HF_CMD_UNKNOWN_ERROR;
-            break;
-    }
+int cmd_complete(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) {
+  struct bt_hfp_hf             *hf   = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  struct bt_conn               *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
+  struct bt_hfp_hf_cmd_complete cmd  = {0};
 
-    if (bt_hf->cmd_complete_cb) {
-        bt_hf->cmd_complete_cb(conn, &cmd);
-    }
+  BT_DBG("");
 
-    return 0;
+  switch (result) {
+  case AT_RESULT_OK:
+    cmd.type = HFP_HF_CMD_OK;
+    break;
+  case AT_RESULT_ERROR:
+    cmd.type = HFP_HF_CMD_ERROR;
+    break;
+  case AT_RESULT_CME_ERROR:
+    cmd.type = HFP_HF_CMD_CME_ERROR;
+    cmd.cme  = cme_err;
+    break;
+  default:
+    BT_ERR("Unknown error code");
+    cmd.type = HFP_HF_CMD_UNKNOWN_ERROR;
+    break;
+  }
+
+  if (bt_hf->cmd_complete_cb) {
+    bt_hf->cmd_complete_cb(conn, &cmd);
+  }
+
+  return 0;
 }
 
-int cmee_finish(struct at_client *hf_at, enum at_result result,
-                enum at_cme cme_err)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+int cmee_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
 
-    if (result != AT_RESULT_OK) {
-        BT_ERR("SLC Connection ERROR in response");
-        return -EINVAL;
-    }
+  if (result != AT_RESULT_OK) {
+    BT_ERR("SLC Connection ERROR in response");
+    return -EINVAL;
+  }
 
-    if (hfp_hf_send_cmd(hf, NULL, NULL, "AT+NREC=0") < 0) {
-        BT_ERR("Error Sending AT+NREC");
-    }
+  if (hfp_hf_send_cmd(hf, NULL, NULL, "AT+NREC=0") < 0) {
+    BT_ERR("Error Sending AT+NREC");
+  }
 
-    return 0;
+  return 0;
 }
 
-static void slc_completed(struct at_client *hf_at)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    struct bt_conn *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
+static void slc_completed(struct at_client *hf_at) {
+  struct bt_hfp_hf *hf   = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  struct bt_conn   *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
 
-    if (bt_hf->connected) {
-        bt_hf->connected(conn);
-    }
+  if (bt_hf->connected) {
+    bt_hf->connected(conn);
+  }
 
-    if (hfp_hf_send_cmd(hf, NULL, cmee_finish, "AT+CMEE=1") < 0) {
-        BT_ERR("Error Sending AT+CMEE");
-    }
+  if (hfp_hf_send_cmd(hf, NULL, cmee_finish, "AT+CMEE=1") < 0) {
+    BT_ERR("Error Sending AT+CMEE");
+  }
 }
 
-int cmer_finish(struct at_client *hf_at, enum at_result result,
-                enum at_cme cme_err)
-{
-    if (result != AT_RESULT_OK) {
-        BT_ERR("SLC Connection ERROR in response");
-        hf_slc_error(hf_at);
-        return -EINVAL;
-    }
+int cmer_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) {
+  if (result != AT_RESULT_OK) {
+    BT_ERR("SLC Connection ERROR in response");
+    hf_slc_error(hf_at);
+    return -EINVAL;
+  }
 
-    slc_completed(hf_at);
+  slc_completed(hf_at);
 
-    return 0;
+  return 0;
 }
 
-int cind_status_finish(struct at_client *hf_at, enum at_result result,
-                       enum at_cme cme_err)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    int err;
+int cind_status_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  int               err;
 
-    if (result != AT_RESULT_OK) {
-        BT_ERR("SLC Connection ERROR in response");
-        hf_slc_error(hf_at);
-        return -EINVAL;
-    }
+  if (result != AT_RESULT_OK) {
+    BT_ERR("SLC Connection ERROR in response");
+    hf_slc_error(hf_at);
+    return -EINVAL;
+  }
 
-    at_register_unsolicited(hf_at, unsolicited_cb);
-    err = hfp_hf_send_cmd(hf, NULL, cmer_finish, "AT+CMER=3,0,0,1");
-    if (err < 0) {
-        hf_slc_error(hf_at);
-        return err;
-    }
+  at_register_unsolicited(hf_at, unsolicited_cb);
+  err = hfp_hf_send_cmd(hf, NULL, cmer_finish, "AT+CMER=3,0,0,1");
+  if (err < 0) {
+    hf_slc_error(hf_at);
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-int cind_finish(struct at_client *hf_at, enum at_result result,
-                enum at_cme cme_err)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    int err;
+int cind_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  int               err;
 
-    if (result != AT_RESULT_OK) {
-        BT_ERR("SLC Connection ERROR in response");
-        hf_slc_error(hf_at);
-        return -EINVAL;
-    }
+  if (result != AT_RESULT_OK) {
+    BT_ERR("SLC Connection ERROR in response");
+    hf_slc_error(hf_at);
+    return -EINVAL;
+  }
 
-    err = hfp_hf_send_cmd(hf, cind_status_resp, cind_status_finish,
-                          "AT+CIND?");
-    if (err < 0) {
-        hf_slc_error(hf_at);
-        return err;
-    }
+  err = hfp_hf_send_cmd(hf, cind_status_resp, cind_status_finish, "AT+CIND?");
+  if (err < 0) {
+    hf_slc_error(hf_at);
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-int bac_finish(struct at_client *hf_at, enum at_result result,
-               enum at_cme cme_err)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    int err;
+int bac_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  int               err;
 
-    if (result != AT_RESULT_OK) {
-        BT_ERR("SLC Connection ERROR in response");
-        hf_slc_error(hf_at);
-        return -EINVAL;
-    }
+  if (result != AT_RESULT_OK) {
+    BT_ERR("SLC Connection ERROR in response");
+    hf_slc_error(hf_at);
+    return -EINVAL;
+  }
 
-    err = hfp_hf_send_cmd(hf, cind_resp, cind_finish, "AT+CIND=?");
-    if (err < 0) {
-        hf_slc_error(hf_at);
-        return err;
-    }
+  err = hfp_hf_send_cmd(hf, cind_resp, cind_finish, "AT+CIND=?");
+  if (err < 0) {
+    hf_slc_error(hf_at);
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-int brsf_finish(struct at_client *hf_at, enum at_result result,
-                enum at_cme cme_err)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    int err;
+int brsf_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  int               err;
 
-    if (result != AT_RESULT_OK) {
-        BT_ERR("SLC Connection ERROR in response");
-        hf_slc_error(hf_at);
-        return -EINVAL;
-    }
+  if (result != AT_RESULT_OK) {
+    BT_ERR("SLC Connection ERROR in response");
+    hf_slc_error(hf_at);
+    return -EINVAL;
+  }
 
-    err = hfp_hf_send_cmd(hf, NULL, bac_finish, "AT+BAC=1,2");
-    if (err < 0) {
-        hf_slc_error(hf_at);
-        return err;
-    }
+  err = hfp_hf_send_cmd(hf, NULL, bac_finish, "AT+BAC=1,2");
+  if (err < 0) {
+    hf_slc_error(hf_at);
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-int hf_slc_establish(struct bt_hfp_hf *hf)
-{
-    int err;
+int hf_slc_establish(struct bt_hfp_hf *hf) {
+  int err;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    err = hfp_hf_send_cmd(hf, brsf_resp, brsf_finish, "AT+BRSF=%u",
-                          hf->hf_features);
-    if (err < 0) {
-        hf_slc_error(&hf->at);
-        return err;
-    }
+  err = hfp_hf_send_cmd(hf, brsf_resp, brsf_finish, "AT+BRSF=%u", hf->hf_features);
+  if (err < 0) {
+    hf_slc_error(&hf->at);
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-static struct bt_hfp_hf *bt_hfp_hf_lookup_bt_conn(struct bt_conn *conn)
-{
-    int i;
+static struct bt_hfp_hf *bt_hfp_hf_lookup_bt_conn(struct bt_conn *conn) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(bt_hfp_hf_pool); i++) {
-        struct bt_hfp_hf *hf = &bt_hfp_hf_pool[i];
+  for (i = 0; i < ARRAY_SIZE(bt_hfp_hf_pool); i++) {
+    struct bt_hfp_hf *hf = &bt_hfp_hf_pool[i];
 
-        if (hf->rfcomm_dlc.session->br_chan.chan.conn == conn) {
-            return hf;
-        }
+    if (hf->rfcomm_dlc.session->br_chan.chan.conn == conn) {
+      return hf;
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-int bt_hfp_hf_send_cmd(struct bt_conn *conn, enum bt_hfp_hf_at_cmd cmd)
-{
-    struct bt_hfp_hf *hf;
-    int err;
+int bt_hfp_hf_send_cmd(struct bt_conn *conn, enum bt_hfp_hf_at_cmd cmd) {
+  struct bt_hfp_hf *hf;
+  int               err;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    if (!conn) {
-        BT_ERR("Invalid connection");
-        return -ENOTCONN;
-    }
+  if (!conn) {
+    BT_ERR("Invalid connection");
+    return -ENOTCONN;
+  }
 
-    hf = bt_hfp_hf_lookup_bt_conn(conn);
-    if (!hf) {
-        BT_ERR("No HF connection found");
-        return -ENOTCONN;
-    }
+  hf = bt_hfp_hf_lookup_bt_conn(conn);
+  if (!hf) {
+    BT_ERR("No HF connection found");
+    return -ENOTCONN;
+  }
 
-    switch (cmd) {
-        case BT_HFP_HF_ATA:
-            err = hfp_hf_send_cmd(hf, NULL, cmd_complete, "ATA");
-            if (err < 0) {
-                BT_ERR("Failed ATA");
-                return err;
-            }
-            break;
-        case BT_HFP_HF_AT_CHUP:
-            err = hfp_hf_send_cmd(hf, NULL, cmd_complete, "AT+CHUP");
-            if (err < 0) {
-                BT_ERR("Failed AT+CHUP");
-                return err;
-            }
-            break;
-        default:
-            BT_ERR("Invalid AT Command");
-            return -EINVAL;
+  switch (cmd) {
+  case BT_HFP_HF_ATA:
+    err = hfp_hf_send_cmd(hf, NULL, cmd_complete, "ATA");
+    if (err < 0) {
+      BT_ERR("Failed ATA");
+      return err;
+    }
+    break;
+  case BT_HFP_HF_AT_CHUP:
+    err = hfp_hf_send_cmd(hf, NULL, cmd_complete, "AT+CHUP");
+    if (err < 0) {
+      BT_ERR("Failed AT+CHUP");
+      return err;
     }
+    break;
+  default:
+    BT_ERR("Invalid AT Command");
+    return -EINVAL;
+  }
 
-    return 0;
+  return 0;
 }
 
-static void hfp_hf_connected(struct bt_rfcomm_dlc *dlc)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(dlc, struct bt_hfp_hf, rfcomm_dlc);
+static void hfp_hf_connected(struct bt_rfcomm_dlc *dlc) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(dlc, struct bt_hfp_hf, rfcomm_dlc);
 
-    BT_DBG("hf connected");
+  BT_DBG("hf connected");
 
-    BT_ASSERT(hf);
-    hf_slc_establish(hf);
+  BT_ASSERT(hf);
+  hf_slc_establish(hf);
 }
 
-static void hfp_hf_disconnected(struct bt_rfcomm_dlc *dlc)
-{
-    struct bt_conn *conn = dlc->session->br_chan.chan.conn;
+static void hfp_hf_disconnected(struct bt_rfcomm_dlc *dlc) {
+  struct bt_conn *conn = dlc->session->br_chan.chan.conn;
 
-    BT_DBG("hf disconnected!");
-    if (bt_hf->disconnected) {
-        bt_hf->disconnected(conn);
-    }
+  BT_DBG("hf disconnected!");
+  if (bt_hf->disconnected) {
+    bt_hf->disconnected(conn);
+  }
 }
 
-static void hfp_hf_recv(struct bt_rfcomm_dlc *dlc, struct net_buf *buf)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(dlc, struct bt_hfp_hf, rfcomm_dlc);
+static void hfp_hf_recv(struct bt_rfcomm_dlc *dlc, struct net_buf *buf) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(dlc, struct bt_hfp_hf, rfcomm_dlc);
 
-    if (at_parse_input(&hf->at, buf) < 0) {
-        BT_ERR("Parsing failed");
-    }
+  if (at_parse_input(&hf->at, buf) < 0) {
+    BT_ERR("Parsing failed");
+  }
 }
 
-static int bt_hfp_hf_accept(struct bt_conn *conn, struct bt_rfcomm_dlc **dlc)
-{
-    int i;
-    static struct bt_rfcomm_dlc_ops ops = {
-        .connected = hfp_hf_connected,
-        .disconnected = hfp_hf_disconnected,
-        .recv = hfp_hf_recv,
-    };
-
-    BT_DBG("conn %p", conn);
+static int bt_hfp_hf_accept(struct bt_conn *conn, struct bt_rfcomm_dlc **dlc) {
+  int                             i;
+  static struct bt_rfcomm_dlc_ops ops = {
+      .connected    = hfp_hf_connected,
+      .disconnected = hfp_hf_disconnected,
+      .recv         = hfp_hf_recv,
+  };
 
-    for (i = 0; i < ARRAY_SIZE(bt_hfp_hf_pool); i++) {
-        struct bt_hfp_hf *hf = &bt_hfp_hf_pool[i];
-        int j;
+  BT_DBG("conn %p", conn);
 
-        if (hf->rfcomm_dlc.session) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(bt_hfp_hf_pool); i++) {
+    struct bt_hfp_hf *hf = &bt_hfp_hf_pool[i];
+    int               j;
 
-        hf->at.buf = hf->hf_buffer;
-        hf->at.buf_max_len = HF_MAX_BUF_LEN;
+    if (hf->rfcomm_dlc.session) {
+      continue;
+    }
 
-        hf->rfcomm_dlc.ops = &ops;
-        hf->rfcomm_dlc.mtu = BT_HFP_MAX_MTU;
+    hf->at.buf         = hf->hf_buffer;
+    hf->at.buf_max_len = HF_MAX_BUF_LEN;
 
-        *dlc = &hf->rfcomm_dlc;
+    hf->rfcomm_dlc.ops = &ops;
+    hf->rfcomm_dlc.mtu = BT_HFP_MAX_MTU;
 
-        /* Set the supported features*/
-        hf->hf_features = BT_HFP_HF_SUPPORTED_FEATURES;
+    *dlc = &hf->rfcomm_dlc;
 
-        for (j = 0; j < HF_MAX_AG_INDICATORS; j++) {
-            hf->ind_table[j] = -1;
-        }
+    /* Set the supported features*/
+    hf->hf_features = BT_HFP_HF_SUPPORTED_FEATURES;
 
-        return 0;
+    for (j = 0; j < HF_MAX_AG_INDICATORS; j++) {
+      hf->ind_table[j] = -1;
     }
 
-    BT_ERR("Unable to establish HF connection (%p)", conn);
+    return 0;
+  }
+
+  BT_ERR("Unable to establish HF connection (%p)", conn);
 
-    return -ENOMEM;
+  return -ENOMEM;
 }
 
-int bt_hfp_hf_init(void)
-{
-    int err;
+int bt_hfp_hf_init(void) {
+  int err;
 
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    net_buf_init(&hf_pool, CONFIG_BT_MAX_CONN + 1, BT_RFCOMM_BUF_SIZE(BT_HF_CLIENT_MAX_PDU), NULL);
+  net_buf_init(&hf_pool, CONFIG_BT_MAX_CONN + 1, BT_RFCOMM_BUF_SIZE(BT_HF_CLIENT_MAX_PDU), NULL);
 #endif
 
-    bt_hf = &hf_cb;
+  bt_hf = &hf_cb;
 
-    static struct bt_rfcomm_server chan = {
-        .channel = BT_RFCOMM_CHAN_HFP_HF,
-        .accept = bt_hfp_hf_accept,
-    };
+  static struct bt_rfcomm_server chan = {
+      .channel = BT_RFCOMM_CHAN_HFP_HF,
+      .accept  = bt_hfp_hf_accept,
+  };
 
-    bt_rfcomm_server_register(&chan);
+  bt_rfcomm_server_register(&chan);
 
-    /* Register SDP record */
-    err = bt_sdp_register_service(&hfp_rec);
-    if (err < 0) {
-        BT_ERR("HFP regist sdp record failed");
-    }
-    BT_DBG("HFP initialized successfully.");
-    return err;
+  /* Register SDP record */
+  err = bt_sdp_register_service(&hfp_rec);
+  if (err < 0) {
+    BT_ERR("HFP regist sdp record failed");
+  }
+  BT_DBG("HFP initialized successfully.");
+  return err;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys.c
index 1988d7aa02..7f1b9864d7 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys.c
@@ -6,11 +6,11 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
-#include 
 #include 
 #include 
+#include 
+#include 
+#include 
 
 #include 
 #include 
@@ -19,12 +19,12 @@
 #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_KEYS)
 #include "log.h"
 
-#include "rpa.h"
 #include "gatt_internal.h"
 #include "hci_core.h"
-#include "smp.h"
-#include "settings.h"
 #include "keys.h"
+#include "rpa.h"
+#include "settings.h"
+#include "smp.h"
 #if defined(BFLB_BLE)
 #if defined(CONFIG_BT_SETTINGS)
 #include "easyflash.h"
@@ -36,419 +36,375 @@ static struct bt_keys key_pool[CONFIG_BT_MAX_PAIRED];
 #define BT_KEYS_STORAGE_LEN_COMPAT (BT_KEYS_STORAGE_LEN - sizeof(uint32_t))
 
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-static u32_t aging_counter_val;
+static u32_t           aging_counter_val;
 static struct bt_keys *last_keys_updated;
 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
 
-struct bt_keys *bt_keys_get_addr(u8_t id, const bt_addr_le_t *addr)
-{
-    struct bt_keys *keys;
-    int i;
-    size_t first_free_slot = ARRAY_SIZE(key_pool);
+struct bt_keys *bt_keys_get_addr(u8_t id, const bt_addr_le_t *addr) {
+  struct bt_keys *keys;
+  int             i;
+  size_t          first_free_slot = ARRAY_SIZE(key_pool);
 
-    BT_DBG("%s", bt_addr_le_str(addr));
+  BT_DBG("%s", bt_addr_le_str(addr));
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        keys = &key_pool[i];
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    keys = &key_pool[i];
 
-        if (keys->id == id && !bt_addr_le_cmp(&keys->addr, addr)) {
-            return keys;
-        }
+    if (keys->id == id && !bt_addr_le_cmp(&keys->addr, addr)) {
+      return keys;
+    }
 
-        if (first_free_slot == ARRAY_SIZE(key_pool) &&
-            (!bt_addr_le_cmp(&keys->addr, BT_ADDR_LE_ANY) ||
-             !keys->enc_size)) {
-            first_free_slot = i;
-        }
+    if (first_free_slot == ARRAY_SIZE(key_pool) && (!bt_addr_le_cmp(&keys->addr, BT_ADDR_LE_ANY) || !keys->enc_size)) {
+      first_free_slot = i;
     }
+  }
 
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-    if (first_free_slot == ARRAY_SIZE(key_pool)) {
-        struct bt_keys *oldest = &key_pool[0];
+  if (first_free_slot == ARRAY_SIZE(key_pool)) {
+    struct bt_keys *oldest = &key_pool[0];
 
-        for (i = 1; i < ARRAY_SIZE(key_pool); i++) {
-            struct bt_keys *current = &key_pool[i];
+    for (i = 1; i < ARRAY_SIZE(key_pool); i++) {
+      struct bt_keys *current = &key_pool[i];
 
-            if (current->aging_counter < oldest->aging_counter) {
-                oldest = current;
-            }
-        }
+      if (current->aging_counter < oldest->aging_counter) {
+        oldest = current;
+      }
+    }
 
-        bt_unpair(oldest->id, &oldest->addr);
-        if (!bt_addr_le_cmp(&oldest->addr, BT_ADDR_LE_ANY)) {
-            first_free_slot = oldest - &key_pool[0];
-        }
+    bt_unpair(oldest->id, &oldest->addr);
+    if (!bt_addr_le_cmp(&oldest->addr, BT_ADDR_LE_ANY)) {
+      first_free_slot = oldest - &key_pool[0];
     }
+  }
 
 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
-    if (first_free_slot < ARRAY_SIZE(key_pool)) {
-        keys = &key_pool[first_free_slot];
-        keys->id = id;
-        bt_addr_le_copy(&keys->addr, addr);
+  if (first_free_slot < ARRAY_SIZE(key_pool)) {
+    keys     = &key_pool[first_free_slot];
+    keys->id = id;
+    bt_addr_le_copy(&keys->addr, addr);
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-        keys->aging_counter = ++aging_counter_val;
-        last_keys_updated = keys;
+    keys->aging_counter = ++aging_counter_val;
+    last_keys_updated   = keys;
 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
-        BT_DBG("created %p for %s", keys, bt_addr_le_str(addr));
-        return keys;
-    }
+    BT_DBG("created %p for %s", keys, bt_addr_le_str(addr));
+    return keys;
+  }
 
-    BT_DBG("unable to create keys for %s", bt_addr_le_str(addr));
+  BT_DBG("unable to create keys for %s", bt_addr_le_str(addr));
 
-    return NULL;
+  return NULL;
 }
 
-void bt_foreach_bond(u8_t id, void (*func)(const struct bt_bond_info *info, void *user_data),
-                     void *user_data)
-{
-    int i;
+void bt_foreach_bond(u8_t id, void (*func)(const struct bt_bond_info *info, void *user_data), void *user_data) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        struct bt_keys *keys = &key_pool[i];
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    struct bt_keys *keys = &key_pool[i];
 
-        if (keys->keys && keys->id == id) {
-            struct bt_bond_info info;
+    if (keys->keys && keys->id == id) {
+      struct bt_bond_info info;
 
-            bt_addr_le_copy(&info.addr, &keys->addr);
-            func(&info, user_data);
-        }
+      bt_addr_le_copy(&info.addr, &keys->addr);
+      func(&info, user_data);
     }
+  }
 }
 
-void bt_keys_foreach(int type, void (*func)(struct bt_keys *keys, void *data),
-                     void *data)
-{
-    int i;
+void bt_keys_foreach(int type, void (*func)(struct bt_keys *keys, void *data), void *data) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        if ((key_pool[i].keys & type)) {
-            func(&key_pool[i], data);
-        }
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    if ((key_pool[i].keys & type)) {
+      func(&key_pool[i], data);
     }
+  }
 }
 
-struct bt_keys *bt_keys_find(int type, u8_t id, const bt_addr_le_t *addr)
-{
-    int i;
+struct bt_keys *bt_keys_find(int type, u8_t id, const bt_addr_le_t *addr) {
+  int i;
 
-    BT_DBG("type %d %s", type, bt_addr_le_str(addr));
+  BT_DBG("type %d %s", type, bt_addr_le_str(addr));
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        if ((key_pool[i].keys & type) && key_pool[i].id == id &&
-            !bt_addr_le_cmp(&key_pool[i].addr, addr)) {
-            return &key_pool[i];
-        }
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    if ((key_pool[i].keys & type) && key_pool[i].id == id && !bt_addr_le_cmp(&key_pool[i].addr, addr)) {
+      return &key_pool[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-struct bt_keys *bt_keys_get_type(int type, u8_t id, const bt_addr_le_t *addr)
-{
-    struct bt_keys *keys;
+struct bt_keys *bt_keys_get_type(int type, u8_t id, const bt_addr_le_t *addr) {
+  struct bt_keys *keys;
 
-    BT_DBG("type %d %s", type, bt_addr_le_str(addr));
+  BT_DBG("type %d %s", type, bt_addr_le_str(addr));
 
-    keys = bt_keys_find(type, id, addr);
-    if (keys) {
-        return keys;
-    }
+  keys = bt_keys_find(type, id, addr);
+  if (keys) {
+    return keys;
+  }
 
-    keys = bt_keys_get_addr(id, addr);
-    if (!keys) {
-        return NULL;
-    }
+  keys = bt_keys_get_addr(id, addr);
+  if (!keys) {
+    return NULL;
+  }
 
-    bt_keys_add_type(keys, type);
+  bt_keys_add_type(keys, type);
 
-    return keys;
+  return keys;
 }
 
-struct bt_keys *bt_keys_find_irk(u8_t id, const bt_addr_le_t *addr)
-{
-    int i;
+struct bt_keys *bt_keys_find_irk(u8_t id, const bt_addr_le_t *addr) {
+  int i;
+
+  BT_DBG("%s", bt_addr_le_str(addr));
 
-    BT_DBG("%s", bt_addr_le_str(addr));
+  if (!bt_addr_le_is_rpa(addr)) {
+    return NULL;
+  }
 
-    if (!bt_addr_le_is_rpa(addr)) {
-        return NULL;
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    if (!(key_pool[i].keys & BT_KEYS_IRK)) {
+      continue;
     }
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        if (!(key_pool[i].keys & BT_KEYS_IRK)) {
-            continue;
-        }
-
-        if (key_pool[i].id == id &&
-            !bt_addr_cmp(&addr->a, &key_pool[i].irk.rpa)) {
-            BT_DBG("cached RPA %s for %s",
-                   bt_addr_str(&key_pool[i].irk.rpa),
-                   bt_addr_le_str(&key_pool[i].addr));
-            return &key_pool[i];
-        }
+    if (key_pool[i].id == id && !bt_addr_cmp(&addr->a, &key_pool[i].irk.rpa)) {
+      BT_DBG("cached RPA %s for %s", bt_addr_str(&key_pool[i].irk.rpa), bt_addr_le_str(&key_pool[i].addr));
+      return &key_pool[i];
     }
+  }
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        if (!(key_pool[i].keys & BT_KEYS_IRK)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    if (!(key_pool[i].keys & BT_KEYS_IRK)) {
+      continue;
+    }
 
-        if (key_pool[i].id != id) {
-            continue;
-        }
+    if (key_pool[i].id != id) {
+      continue;
+    }
 
-        if (bt_rpa_irk_matches(key_pool[i].irk.val, &addr->a)) {
-            BT_DBG("RPA %s matches %s",
-                   bt_addr_str(&key_pool[i].irk.rpa),
-                   bt_addr_le_str(&key_pool[i].addr));
+    if (bt_rpa_irk_matches(key_pool[i].irk.val, &addr->a)) {
+      BT_DBG("RPA %s matches %s", bt_addr_str(&key_pool[i].irk.rpa), bt_addr_le_str(&key_pool[i].addr));
 
-            bt_addr_copy(&key_pool[i].irk.rpa, &addr->a);
+      bt_addr_copy(&key_pool[i].irk.rpa, &addr->a);
 
-            return &key_pool[i];
-        }
+      return &key_pool[i];
     }
+  }
 
-    BT_DBG("No IRK for %s", bt_addr_le_str(addr));
+  BT_DBG("No IRK for %s", bt_addr_le_str(addr));
 
-    return NULL;
+  return NULL;
 }
 
-struct bt_keys *bt_keys_find_addr(u8_t id, const bt_addr_le_t *addr)
-{
-    int i;
+struct bt_keys *bt_keys_find_addr(u8_t id, const bt_addr_le_t *addr) {
+  int i;
 
-    BT_DBG("%s", bt_addr_le_str(addr));
+  BT_DBG("%s", bt_addr_le_str(addr));
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        if (key_pool[i].id == id &&
-            !bt_addr_le_cmp(&key_pool[i].addr, addr)) {
-            return &key_pool[i];
-        }
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    if (key_pool[i].id == id && !bt_addr_le_cmp(&key_pool[i].addr, addr)) {
+      return &key_pool[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
 #if defined(CONFIG_BLE_AT_CMD)
-bt_addr_le_t *bt_get_keys_address(u8_t id)
-{
-    bt_addr_le_t addr;
+bt_addr_le_t *bt_get_keys_address(u8_t id) {
+  bt_addr_le_t addr;
 
-    memset(&addr, 0, sizeof(bt_addr_le_t));
-    if (id < ARRAY_SIZE(key_pool)) {
-        if (bt_addr_le_cmp(&key_pool[id].addr, &addr)) {
-            return &key_pool[id].addr;
-        }
+  memset(&addr, 0, sizeof(bt_addr_le_t));
+  if (id < ARRAY_SIZE(key_pool)) {
+    if (bt_addr_le_cmp(&key_pool[id].addr, &addr)) {
+      return &key_pool[id].addr;
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 #endif
 
-void bt_keys_add_type(struct bt_keys *keys, int type)
-{
-    keys->keys |= type;
-}
+void bt_keys_add_type(struct bt_keys *keys, int type) { keys->keys |= type; }
 
-void bt_keys_clear(struct bt_keys *keys)
-{
+void bt_keys_clear(struct bt_keys *keys) {
 #if defined(BFLB_BLE)
-    if (keys->keys & BT_KEYS_IRK) {
-        bt_id_del(keys);
-    }
+  if (keys->keys & BT_KEYS_IRK) {
+    bt_id_del(keys);
+  }
 
-    memset(keys, 0, sizeof(*keys));
+  memset(keys, 0, sizeof(*keys));
 
 #if defined(CONFIG_BT_SETTINGS)
-    ef_del_env(NV_KEY_POOL);
+  ef_del_env(NV_KEY_POOL);
 #endif
 #else
-    BT_DBG("%s (keys 0x%04x)", bt_addr_le_str(&keys->addr), keys->keys);
+  BT_DBG("%s (keys 0x%04x)", bt_addr_le_str(&keys->addr), keys->keys);
 
-    if (keys->keys & BT_KEYS_IRK) {
-        bt_id_del(keys);
-    }
+  if (keys->keys & BT_KEYS_IRK) {
+    bt_id_del(keys);
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        char key[BT_SETTINGS_KEY_MAX];
-
-        /* Delete stored keys from flash */
-        if (keys->id) {
-            char id[4];
-
-            u8_to_dec(id, sizeof(id), keys->id);
-            bt_settings_encode_key(key, sizeof(key), "keys",
-                                   &keys->addr, id);
-        } else {
-            bt_settings_encode_key(key, sizeof(key), "keys",
-                                   &keys->addr, NULL);
-        }
-
-        BT_DBG("Deleting key %s", log_strdup(key));
-        settings_delete(key);
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    char key[BT_SETTINGS_KEY_MAX];
+
+    /* Delete stored keys from flash */
+    if (keys->id) {
+      char id[4];
+
+      u8_to_dec(id, sizeof(id), keys->id);
+      bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, id);
+    } else {
+      bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, NULL);
     }
 
-    (void)memset(keys, 0, sizeof(*keys));
+    BT_DBG("Deleting key %s", log_strdup(key));
+    settings_delete(key);
+  }
+
+  (void)memset(keys, 0, sizeof(*keys));
 #endif
 }
 
-static void keys_clear_id(struct bt_keys *keys, void *data)
-{
-    u8_t *id = data;
-
-    if (*id == keys->id) {
-        if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-            bt_gatt_clear(*id, &keys->addr);
-        }
+static void keys_clear_id(struct bt_keys *keys, void *data) {
+  u8_t *id = data;
 
-        bt_keys_clear(keys);
+  if (*id == keys->id) {
+    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+      bt_gatt_clear(*id, &keys->addr);
     }
-}
 
-void bt_keys_clear_all(u8_t id)
-{
-    bt_keys_foreach(BT_KEYS_ALL, keys_clear_id, &id);
+    bt_keys_clear(keys);
+  }
 }
 
+void bt_keys_clear_all(u8_t id) { bt_keys_foreach(BT_KEYS_ALL, keys_clear_id, &id); }
+
 #if defined(CONFIG_BT_SETTINGS)
-int bt_keys_store(struct bt_keys *keys)
-{
+int bt_keys_store(struct bt_keys *keys) {
 #if defined(BFLB_BLE)
-    int err;
-    err = bt_settings_set_bin(NV_KEY_POOL, (const u8_t *)&key_pool[0], sizeof(key_pool));
-    return err;
+  int err;
+  err = bt_settings_set_bin(NV_KEY_POOL, (const u8_t *)&key_pool[0], sizeof(key_pool));
+  return err;
 #else
-    char val[BT_SETTINGS_SIZE(BT_KEYS_STORAGE_LEN)];
-    char key[BT_SETTINGS_KEY_MAX];
-    char *str;
-    int err;
-
-    str = settings_str_from_bytes(keys->storage_start, BT_KEYS_STORAGE_LEN,
-                                  val, sizeof(val));
-    if (!str) {
-        BT_ERR("Unable to encode bt_keys as value");
-        return -EINVAL;
-    }
-
-    if (keys->id) {
-        char id[4];
-
-        u8_to_dec(id, sizeof(id), keys->id);
-        bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr,
-                               id);
-    } else {
-        bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr,
-                               NULL);
-    }
-
-    err = settings_save_one(key, keys->storage_start, BT_KEYS_STORAGE_LEN);
-    if (err) {
-        BT_ERR("Failed to save keys (err %d)", err);
-        return err;
-    }
+  char  val[BT_SETTINGS_SIZE(BT_KEYS_STORAGE_LEN)];
+  char  key[BT_SETTINGS_KEY_MAX];
+  char *str;
+  int   err;
+
+  str = settings_str_from_bytes(keys->storage_start, BT_KEYS_STORAGE_LEN, val, sizeof(val));
+  if (!str) {
+    BT_ERR("Unable to encode bt_keys as value");
+    return -EINVAL;
+  }
+
+  if (keys->id) {
+    char id[4];
+
+    u8_to_dec(id, sizeof(id), keys->id);
+    bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, id);
+  } else {
+    bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, NULL);
+  }
+
+  err = settings_save_one(key, keys->storage_start, BT_KEYS_STORAGE_LEN);
+  if (err) {
+    BT_ERR("Failed to save keys (err %d)", err);
+    return err;
+  }
 
-    BT_DBG("Stored keys for %s (%s)", bt_addr_le_str(&keys->addr),
-           log_strdup(key));
+  BT_DBG("Stored keys for %s (%s)", bt_addr_le_str(&keys->addr), log_strdup(key));
 
-    return 0;
-#endif //BFLB_BLE
+  return 0;
+#endif // BFLB_BLE
 }
 
 #if !defined(BFLB_BLE)
-static int keys_set(const char *name, size_t len_rd, settings_read_cb read_cb,
-                    void *cb_arg)
-{
-    struct bt_keys *keys;
-    bt_addr_le_t addr;
-    u8_t id;
-    size_t len;
-    int err;
-    char val[BT_KEYS_STORAGE_LEN];
-    const char *next;
-
-    if (!name) {
-        BT_ERR("Insufficient number of arguments");
-        return -EINVAL;
-    }
-
-    len = read_cb(cb_arg, val, sizeof(val));
-    if (len < 0) {
-        BT_ERR("Failed to read value (err %zu)", len);
-        return -EINVAL;
-    }
-
-    BT_DBG("name %s val %s", log_strdup(name),
-           (len) ? bt_hex(val, sizeof(val)) : "(null)");
-
-    err = bt_settings_decode_key(name, &addr);
-    if (err) {
-        BT_ERR("Unable to decode address %s", name);
-        return -EINVAL;
-    }
-
-    settings_name_next(name, &next);
-
-    if (!next) {
-        id = BT_ID_DEFAULT;
+static int keys_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) {
+  struct bt_keys *keys;
+  bt_addr_le_t    addr;
+  u8_t            id;
+  size_t          len;
+  int             err;
+  char            val[BT_KEYS_STORAGE_LEN];
+  const char     *next;
+
+  if (!name) {
+    BT_ERR("Insufficient number of arguments");
+    return -EINVAL;
+  }
+
+  len = read_cb(cb_arg, val, sizeof(val));
+  if (len < 0) {
+    BT_ERR("Failed to read value (err %zu)", len);
+    return -EINVAL;
+  }
+
+  BT_DBG("name %s val %s", log_strdup(name), (len) ? bt_hex(val, sizeof(val)) : "(null)");
+
+  err = bt_settings_decode_key(name, &addr);
+  if (err) {
+    BT_ERR("Unable to decode address %s", name);
+    return -EINVAL;
+  }
+
+  settings_name_next(name, &next);
+
+  if (!next) {
+    id = BT_ID_DEFAULT;
+  } else {
+    id = strtol(next, NULL, 10);
+  }
+
+  if (!len) {
+    keys = bt_keys_find(BT_KEYS_ALL, id, &addr);
+    if (keys) {
+      (void)memset(keys, 0, sizeof(*keys));
+      BT_DBG("Cleared keys for %s", bt_addr_le_str(&addr));
     } else {
-        id = strtol(next, NULL, 10);
-    }
-
-    if (!len) {
-        keys = bt_keys_find(BT_KEYS_ALL, id, &addr);
-        if (keys) {
-            (void)memset(keys, 0, sizeof(*keys));
-            BT_DBG("Cleared keys for %s", bt_addr_le_str(&addr));
-        } else {
-            BT_WARN("Unable to find deleted keys for %s",
-                    bt_addr_le_str(&addr));
-        }
-
-        return 0;
+      BT_WARN("Unable to find deleted keys for %s", bt_addr_le_str(&addr));
     }
 
-    keys = bt_keys_get_addr(id, &addr);
-    if (!keys) {
-        BT_ERR("Failed to allocate keys for %s", bt_addr_le_str(&addr));
-        return -ENOMEM;
-    }
-    if (len != BT_KEYS_STORAGE_LEN) {
-        do {
-            /* Load shorter structure for compatibility with old
-			 * records format with no counter.
-			 */
-            if (IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) &&
-                len == BT_KEYS_STORAGE_LEN_COMPAT) {
-                BT_WARN("Keys for %s have no aging counter",
-                        bt_addr_le_str(&addr));
-                memcpy(keys->storage_start, val, len);
-                continue;
-            }
-
-            BT_ERR("Invalid key length %zu != %zu", len,
-                   BT_KEYS_STORAGE_LEN);
-            bt_keys_clear(keys);
-
-            return -EINVAL;
-        } while (0);
-    } else {
+    return 0;
+  }
+
+  keys = bt_keys_get_addr(id, &addr);
+  if (!keys) {
+    BT_ERR("Failed to allocate keys for %s", bt_addr_le_str(&addr));
+    return -ENOMEM;
+  }
+  if (len != BT_KEYS_STORAGE_LEN) {
+    do {
+      /* Load shorter structure for compatibility with old
+       * records format with no counter.
+       */
+      if (IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) && len == BT_KEYS_STORAGE_LEN_COMPAT) {
+        BT_WARN("Keys for %s have no aging counter", bt_addr_le_str(&addr));
         memcpy(keys->storage_start, val, len);
-    }
+        continue;
+      }
+
+      BT_ERR("Invalid key length %zu != %zu", len, BT_KEYS_STORAGE_LEN);
+      bt_keys_clear(keys);
+
+      return -EINVAL;
+    } while (0);
+  } else {
+    memcpy(keys->storage_start, val, len);
+  }
 
-    BT_DBG("Successfully restored keys for %s", bt_addr_le_str(&addr));
+  BT_DBG("Successfully restored keys for %s", bt_addr_le_str(&addr));
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-    if (aging_counter_val < keys->aging_counter) {
-        aging_counter_val = keys->aging_counter;
-    }
+  if (aging_counter_val < keys->aging_counter) {
+    aging_counter_val = keys->aging_counter;
+  }
 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
-    return 0;
+  return 0;
 }
 #endif //!(BFLB_BLE)
 
-static void id_add(struct bt_keys *keys, void *user_data)
-{
-    bt_id_add(keys);
-}
+static void id_add(struct bt_keys *keys, void *user_data) { bt_id_add(keys); }
 
 #if defined(BFLB_BLE)
 int keys_commit(void)
@@ -456,51 +412,46 @@ int keys_commit(void)
 static int keys_commit(void)
 #endif
 {
-    BT_DBG("");
+  BT_DBG("");
 
-    /* We do this in commit() rather than add() since add() may get
-	 * called multiple times for the same address, especially if
-	 * the keys were already removed.
-	 */
-    bt_keys_foreach(BT_KEYS_IRK, id_add, NULL);
+  /* We do this in commit() rather than add() since add() may get
+   * called multiple times for the same address, especially if
+   * the keys were already removed.
+   */
+  bt_keys_foreach(BT_KEYS_IRK, id_add, NULL);
 
-    return 0;
+  return 0;
 }
 
-//SETTINGS_STATIC_HANDLER_DEFINE(bt_keys, "bt/keys", NULL, keys_set, keys_commit,
+// SETTINGS_STATIC_HANDLER_DEFINE(bt_keys, "bt/keys", NULL, keys_set, keys_commit,
 //			       NULL);
 
 #if defined(BFLB_BLE)
-int bt_keys_load(void)
-{
-    return bt_settings_get_bin(NV_KEY_POOL, (u8_t *)&key_pool[0], sizeof(key_pool), NULL);
-}
+int bt_keys_load(void) { return bt_settings_get_bin(NV_KEY_POOL, (u8_t *)&key_pool[0], sizeof(key_pool), NULL); }
 #endif
 
 #endif /* CONFIG_BT_SETTINGS */
 
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-void bt_keys_update_usage(u8_t id, const bt_addr_le_t *addr)
-{
-    struct bt_keys *keys = bt_keys_find_addr(id, addr);
+void bt_keys_update_usage(u8_t id, const bt_addr_le_t *addr) {
+  struct bt_keys *keys = bt_keys_find_addr(id, addr);
 
-    if (!keys) {
-        return;
-    }
+  if (!keys) {
+    return;
+  }
 
-    if (last_keys_updated == keys) {
-        return;
-    }
+  if (last_keys_updated == keys) {
+    return;
+  }
 
-    keys->aging_counter = ++aging_counter_val;
-    last_keys_updated = keys;
+  keys->aging_counter = ++aging_counter_val;
+  last_keys_updated   = keys;
 
-    BT_DBG("Aging counter for %s is set to %u", bt_addr_le_str(addr),
-           keys->aging_counter);
+  BT_DBG("Aging counter for %s is set to %u", bt_addr_le_str(addr), keys->aging_counter);
 
-    if (IS_ENABLED(CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING)) {
-        bt_keys_store(keys);
-    }
+  if (IS_ENABLED(CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING)) {
+    bt_keys_store(keys);
+  }
 }
 
 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys_br.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys_br.c
index f5cd4e19ed..9949dea15c 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys_br.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys_br.c
@@ -6,10 +6,10 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
 #include 
+#include 
 #include 
+#include 
 
 #include 
 #include 
@@ -21,45 +21,43 @@
 #include "log.h"
 
 #include "hci_core.h"
-#include "settings.h"
 #include "keys.h"
+#include "settings.h"
 
 static struct bt_keys_link_key key_pool[CONFIG_BT_MAX_PAIRED];
 
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-static uint32_t aging_counter_val;
+static uint32_t                 aging_counter_val;
 static struct bt_keys_link_key *last_keys_updated;
 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
 
-struct bt_keys_link_key *bt_keys_find_link_key(const bt_addr_t *addr)
-{
-    struct bt_keys_link_key *key;
-    int i;
+struct bt_keys_link_key *bt_keys_find_link_key(const bt_addr_t *addr) {
+  struct bt_keys_link_key *key;
+  int                      i;
 
-    BT_DBG("%s", bt_addr_str(addr));
+  BT_DBG("%s", bt_addr_str(addr));
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        key = &key_pool[i];
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    key = &key_pool[i];
 
-        if (!bt_addr_cmp(&key->addr, addr)) {
-            return key;
-        }
+    if (!bt_addr_cmp(&key->addr, addr)) {
+      return key;
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-struct bt_keys_link_key *bt_keys_get_link_key(const bt_addr_t *addr)
-{
-    struct bt_keys_link_key *key;
+struct bt_keys_link_key *bt_keys_get_link_key(const bt_addr_t *addr) {
+  struct bt_keys_link_key *key;
 
-    key = bt_keys_find_link_key(addr);
-    if (key) {
-        return key;
-    }
+  key = bt_keys_find_link_key(addr);
+  if (key) {
+    return key;
+  }
 
-    key = bt_keys_find_link_key(BT_ADDR_ANY);
-#if 0 //IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) //MBHJ
+  key = bt_keys_find_link_key(BT_ADDR_ANY);
+#if 0 // IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) //MBHJ
 	if (!key) {
 		int i;
 
@@ -78,60 +76,56 @@ struct bt_keys_link_key *bt_keys_get_link_key(const bt_addr_t *addr)
 	}
 #endif
 
-    if (key) {
-        bt_addr_copy(&key->addr, addr);
-#if 0 //IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) //MBHJ
+  if (key) {
+    bt_addr_copy(&key->addr, addr);
+#if 0 // IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) //MBHJ
 		key->aging_counter = ++aging_counter_val;
 		last_keys_updated = key;
 #endif
-        BT_DBG("created %p for %s", key, bt_addr_str(addr));
-        return key;
-    }
+    BT_DBG("created %p for %s", key, bt_addr_str(addr));
+    return key;
+  }
 
-    BT_DBG("unable to create keys for %s", bt_addr_str(addr));
+  BT_DBG("unable to create keys for %s", bt_addr_str(addr));
 
-    return NULL;
+  return NULL;
 }
 
-void bt_keys_link_key_clear(struct bt_keys_link_key *link_key)
-{
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        char key[BT_SETTINGS_KEY_MAX];
-        bt_addr_le_t le_addr;
-
-        le_addr.type = BT_ADDR_LE_PUBLIC;
-        bt_addr_copy(&le_addr.a, &link_key->addr);
-        bt_settings_encode_key(key, sizeof(key), "link_key",
-                               &le_addr, NULL);
-        settings_delete(key);
-    }
+void bt_keys_link_key_clear(struct bt_keys_link_key *link_key) {
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    char         key[BT_SETTINGS_KEY_MAX];
+    bt_addr_le_t le_addr;
+
+    le_addr.type = BT_ADDR_LE_PUBLIC;
+    bt_addr_copy(&le_addr.a, &link_key->addr);
+    bt_settings_encode_key(key, sizeof(key), "link_key", &le_addr, NULL);
+    settings_delete(key);
+  }
 
-    BT_DBG("%s", bt_addr_str(&link_key->addr));
-    (void)memset(link_key, 0, sizeof(*link_key));
+  BT_DBG("%s", bt_addr_str(&link_key->addr));
+  (void)memset(link_key, 0, sizeof(*link_key));
 }
 
-void bt_keys_link_key_clear_addr(const bt_addr_t *addr)
-{
-    int i;
-    struct bt_keys_link_key *key;
-
-    if (!addr) {
-        for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-            key = &key_pool[i];
-            bt_keys_link_key_clear(key);
-        }
-        return;
-    }
+void bt_keys_link_key_clear_addr(const bt_addr_t *addr) {
+  int                      i;
+  struct bt_keys_link_key *key;
 
-    key = bt_keys_find_link_key(addr);
-    if (key) {
-        bt_keys_link_key_clear(key);
+  if (!addr) {
+    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+      key = &key_pool[i];
+      bt_keys_link_key_clear(key);
     }
+    return;
+  }
+
+  key = bt_keys_find_link_key(addr);
+  if (key) {
+    bt_keys_link_key_clear(key);
+  }
 }
 
-void bt_keys_link_key_store(struct bt_keys_link_key *link_key)
-{
-#if 0 //MBHJ
+void bt_keys_link_key_store(struct bt_keys_link_key *link_key) {
+#if 0 // MBHJ
 	if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
 		int err;
 		char key[BT_SETTINGS_KEY_MAX];
@@ -153,89 +147,78 @@ void bt_keys_link_key_store(struct bt_keys_link_key *link_key)
 
 #if defined(CONFIG_BT_SETTINGS)
 
-static int link_key_set(const char *name, size_t len_rd,
-                        settings_read_cb read_cb, void *cb_arg)
-{
-    int err;
-    ssize_t len;
-    bt_addr_le_t le_addr;
-    struct bt_keys_link_key *link_key;
-    char val[BT_KEYS_LINK_KEY_STORAGE_LEN];
-
-    if (!name) {
-        BT_ERR("Insufficient number of arguments");
-        return -EINVAL;
-    }
-
-    len = read_cb(cb_arg, val, sizeof(val));
-    if (len < 0) {
-        BT_ERR("Failed to read value (err %zu)", len);
-        return -EINVAL;
-    }
-
-    BT_DBG("name %s val %s", log_strdup(name),
-           len ? bt_hex(val, sizeof(val)) : "(null)");
-
-    err = bt_settings_decode_key(name, &le_addr);
-    if (err) {
-        BT_ERR("Unable to decode address %s", name);
-        return -EINVAL;
+static int link_key_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) {
+  int                      err;
+  ssize_t                  len;
+  bt_addr_le_t             le_addr;
+  struct bt_keys_link_key *link_key;
+  char                     val[BT_KEYS_LINK_KEY_STORAGE_LEN];
+
+  if (!name) {
+    BT_ERR("Insufficient number of arguments");
+    return -EINVAL;
+  }
+
+  len = read_cb(cb_arg, val, sizeof(val));
+  if (len < 0) {
+    BT_ERR("Failed to read value (err %zu)", len);
+    return -EINVAL;
+  }
+
+  BT_DBG("name %s val %s", log_strdup(name), len ? bt_hex(val, sizeof(val)) : "(null)");
+
+  err = bt_settings_decode_key(name, &le_addr);
+  if (err) {
+    BT_ERR("Unable to decode address %s", name);
+    return -EINVAL;
+  }
+
+  link_key = bt_keys_get_link_key(&le_addr.a);
+  if (len != BT_KEYS_LINK_KEY_STORAGE_LEN) {
+    if (link_key) {
+      bt_keys_link_key_clear(link_key);
+      BT_DBG("Clear keys for %s", bt_addr_le_str(&le_addr));
+    } else {
+      BT_WARN("Unable to find deleted keys for %s", bt_addr_le_str(&le_addr));
     }
 
-    link_key = bt_keys_get_link_key(&le_addr.a);
-    if (len != BT_KEYS_LINK_KEY_STORAGE_LEN) {
-        if (link_key) {
-            bt_keys_link_key_clear(link_key);
-            BT_DBG("Clear keys for %s", bt_addr_le_str(&le_addr));
-        } else {
-            BT_WARN("Unable to find deleted keys for %s",
-                    bt_addr_le_str(&le_addr));
-        }
-
-        return 0;
-    }
+    return 0;
+  }
 
-    memcpy(link_key->storage_start, val, len);
-    BT_DBG("Successfully restored link key for %s",
-           bt_addr_le_str(&le_addr));
+  memcpy(link_key->storage_start, val, len);
+  BT_DBG("Successfully restored link key for %s", bt_addr_le_str(&le_addr));
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-    if (aging_counter_val < link_key->aging_counter) {
-        aging_counter_val = link_key->aging_counter;
-    }
+  if (aging_counter_val < link_key->aging_counter) {
+    aging_counter_val = link_key->aging_counter;
+  }
 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
 
-    return 0;
+  return 0;
 }
 
-static int link_key_commit(void)
-{
-    return 0;
-}
+static int link_key_commit(void) { return 0; }
 
-SETTINGS_STATIC_HANDLER_DEFINE(bt_link_key, "bt/link_key", NULL, link_key_set,
-                               link_key_commit, NULL);
+SETTINGS_STATIC_HANDLER_DEFINE(bt_link_key, "bt/link_key", NULL, link_key_set, link_key_commit, NULL);
 
-void bt_keys_link_key_update_usage(const bt_addr_t *addr)
-{
-    struct bt_keys_link_key *link_key = bt_keys_find_link_key(addr);
+void bt_keys_link_key_update_usage(const bt_addr_t *addr) {
+  struct bt_keys_link_key *link_key = bt_keys_find_link_key(addr);
 
-    if (!link_key) {
-        return;
-    }
+  if (!link_key) {
+    return;
+  }
 
-    if (last_keys_updated == link_key) {
-        return;
-    }
+  if (last_keys_updated == link_key) {
+    return;
+  }
 
-    link_key->aging_counter = ++aging_counter_val;
-    last_keys_updated = link_key;
+  link_key->aging_counter = ++aging_counter_val;
+  last_keys_updated       = link_key;
 
-    BT_DBG("Aging counter for %s is set to %u", bt_addr_str(addr),
-           link_key->aging_counter);
+  BT_DBG("Aging counter for %s is set to %u", bt_addr_str(addr), link_key->aging_counter);
 
-    if (IS_ENABLED(CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING)) {
-        bt_keys_link_key_store(link_key);
-    }
+  if (IS_ENABLED(CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING)) {
+    bt_keys_link_key_store(link_key);
+  }
 }
 
 #endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/l2cap.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/l2cap.c
index 988365722d..9137ee43d6 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/l2cap.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/l2cap.c
@@ -6,24 +6,24 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
-#include 
 #include 
+#include 
 #include 
 #include 
+#include 
+#include 
 
-#include 
 #include 
 #include 
 #include 
+#include 
 
 #define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_L2CAP)
 #define LOG_MODULE_NAME bt_l2cap
 #include "log.h"
 
-#include "hci_core.h"
 #include "conn_internal.h"
+#include "hci_core.h"
 #include "l2cap_internal.h"
 
 #include "ble_config.h"
@@ -39,10 +39,9 @@
 #define L2CAP_LE_MAX_CREDITS (CONFIG_BT_RX_BUF_COUNT - 1)
 #endif
 
-#define L2CAP_LE_CID_DYN_START 0x0040
-#define L2CAP_LE_CID_DYN_END   0x007f
-#define L2CAP_LE_CID_IS_DYN(_cid) \
-    (_cid >= L2CAP_LE_CID_DYN_START && _cid <= L2CAP_LE_CID_DYN_END)
+#define L2CAP_LE_CID_DYN_START    0x0040
+#define L2CAP_LE_CID_DYN_END      0x007f
+#define L2CAP_LE_CID_IS_DYN(_cid) (_cid >= L2CAP_LE_CID_DYN_START && _cid <= L2CAP_LE_CID_DYN_END)
 
 #define L2CAP_LE_PSM_FIXED_START 0x0001
 #define L2CAP_LE_PSM_FIXED_END   0x007f
@@ -73,1894 +72,1716 @@ static sys_slist_t servers;
 
 /* L2CAP signalling channel specific context */
 struct bt_l2cap {
-    /* The channel this context is associated with */
-    struct bt_l2cap_le_chan chan;
+  /* The channel this context is associated with */
+  struct bt_l2cap_le_chan chan;
 };
 
 static struct bt_l2cap bt_l2cap_pool[CONFIG_BT_MAX_CONN];
 
-static u8_t get_ident(void)
-{
-    static u8_t ident;
+static u8_t get_ident(void) {
+  static u8_t ident;
 
+  ident++;
+  /* handle integer overflow (0 is not valid) */
+  if (!ident) {
     ident++;
-    /* handle integer overflow (0 is not valid) */
-    if (!ident) {
-        ident++;
-    }
+  }
 
-    return ident;
+  return ident;
 }
 
 #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL)
-void bt_l2cap_le_fixed_chan_register(struct bt_l2cap_fixed_chan *chan)
-{
-    BT_DBG("CID 0x%04x", chan->cid);
+void bt_l2cap_le_fixed_chan_register(struct bt_l2cap_fixed_chan *chan) {
+  BT_DBG("CID 0x%04x", chan->cid);
 
-    sys_slist_append(&le_channels, &chan->node);
+  sys_slist_append(&le_channels, &chan->node);
 }
 #endif
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-static struct bt_l2cap_le_chan *l2cap_chan_alloc_cid(struct bt_conn *conn,
-                                                     struct bt_l2cap_chan *chan)
-{
-    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
-    u16_t cid;
-
-    /*
-	 * No action needed if there's already a CID allocated, e.g. in
-	 * the case of a fixed channel.
-	 */
-    if (ch && ch->rx.cid > 0) {
-        return ch;
-    }
+static struct bt_l2cap_le_chan *l2cap_chan_alloc_cid(struct bt_conn *conn, struct bt_l2cap_chan *chan) {
+  struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
+  u16_t                    cid;
+
+  /*
+   * No action needed if there's already a CID allocated, e.g. in
+   * the case of a fixed channel.
+   */
+  if (ch && ch->rx.cid > 0) {
+    return ch;
+  }
 
-    for (cid = L2CAP_LE_CID_DYN_START; cid <= L2CAP_LE_CID_DYN_END; cid++) {
-        if (ch && !bt_l2cap_le_lookup_rx_cid(conn, cid)) {
-            ch->rx.cid = cid;
-            return ch;
-        }
+  for (cid = L2CAP_LE_CID_DYN_START; cid <= L2CAP_LE_CID_DYN_END; cid++) {
+    if (ch && !bt_l2cap_le_lookup_rx_cid(conn, cid)) {
+      ch->rx.cid = cid;
+      return ch;
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-static struct bt_l2cap_le_chan *
-__l2cap_lookup_ident(struct bt_conn *conn, u16_t ident, bool remove)
-{
-    struct bt_l2cap_chan *chan;
-    sys_snode_t *prev = NULL;
+static struct bt_l2cap_le_chan *__l2cap_lookup_ident(struct bt_conn *conn, u16_t ident, bool remove) {
+  struct bt_l2cap_chan *chan;
+  sys_snode_t          *prev = NULL;
 
-    SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node)
-    {
-        if (chan->ident == ident) {
-            if (remove) {
-                sys_slist_remove(&conn->channels, prev,
-                                 &chan->node);
-            }
-            return BT_L2CAP_LE_CHAN(chan);
-        }
-
-        prev = &chan->node;
+  SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) {
+    if (chan->ident == ident) {
+      if (remove) {
+        sys_slist_remove(&conn->channels, prev, &chan->node);
+      }
+      return BT_L2CAP_LE_CHAN(chan);
     }
 
-    return NULL;
+    prev = &chan->node;
+  }
+
+  return NULL;
 }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-void bt_l2cap_chan_remove(struct bt_conn *conn, struct bt_l2cap_chan *ch)
-{
-    struct bt_l2cap_chan *chan;
-    sys_snode_t *prev = NULL;
-
-    SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node)
-    {
-        if (chan == ch) {
-            sys_slist_remove(&conn->channels, prev, &chan->node);
-            return;
-        }
+void bt_l2cap_chan_remove(struct bt_conn *conn, struct bt_l2cap_chan *ch) {
+  struct bt_l2cap_chan *chan;
+  sys_snode_t          *prev = NULL;
 
-        prev = &chan->node;
+  SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) {
+    if (chan == ch) {
+      sys_slist_remove(&conn->channels, prev, &chan->node);
+      return;
     }
+
+    prev = &chan->node;
+  }
 }
 
-const char *bt_l2cap_chan_state_str(bt_l2cap_chan_state_t state)
-{
-    switch (state) {
-        case BT_L2CAP_DISCONNECTED:
-            return "disconnected";
-        case BT_L2CAP_CONNECT:
-            return "connect";
-        case BT_L2CAP_CONFIG:
-            return "config";
-        case BT_L2CAP_CONNECTED:
-            return "connected";
-        case BT_L2CAP_DISCONNECT:
-            return "disconnect";
-        default:
-            return "unknown";
-    }
+const char *bt_l2cap_chan_state_str(bt_l2cap_chan_state_t state) {
+  switch (state) {
+  case BT_L2CAP_DISCONNECTED:
+    return "disconnected";
+  case BT_L2CAP_CONNECT:
+    return "connect";
+  case BT_L2CAP_CONFIG:
+    return "config";
+  case BT_L2CAP_CONNECTED:
+    return "connected";
+  case BT_L2CAP_DISCONNECT:
+    return "disconnect";
+  default:
+    return "unknown";
+  }
 }
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
 #if defined(CONFIG_BT_DEBUG_L2CAP)
-void bt_l2cap_chan_set_state_debug(struct bt_l2cap_chan *chan,
-                                   bt_l2cap_chan_state_t state,
-                                   const char *func, int line)
-{
-    BT_DBG("chan %p psm 0x%04x %s -> %s", chan, chan->psm,
-           bt_l2cap_chan_state_str(chan->state),
-           bt_l2cap_chan_state_str(state));
-
-    /* check transitions validness */
-    switch (state) {
-        case BT_L2CAP_DISCONNECTED:
-            /* regardless of old state always allows this state */
-            break;
-        case BT_L2CAP_CONNECT:
-            if (chan->state != BT_L2CAP_DISCONNECTED) {
-                BT_WARN("%s()%d: invalid transition", func, line);
-            }
-            break;
-        case BT_L2CAP_CONFIG:
-            if (chan->state != BT_L2CAP_CONNECT) {
-                BT_WARN("%s()%d: invalid transition", func, line);
-            }
-            break;
-        case BT_L2CAP_CONNECTED:
-            if (chan->state != BT_L2CAP_CONFIG &&
-                chan->state != BT_L2CAP_CONNECT) {
-                BT_WARN("%s()%d: invalid transition", func, line);
-            }
-            break;
-        case BT_L2CAP_DISCONNECT:
-            if (chan->state != BT_L2CAP_CONFIG &&
-                chan->state != BT_L2CAP_CONNECTED) {
-                BT_WARN("%s()%d: invalid transition", func, line);
-            }
-            break;
-        default:
-            BT_ERR("%s()%d: unknown (%u) state was set", func, line, state);
-            return;
-    }
-
-    chan->state = state;
+void bt_l2cap_chan_set_state_debug(struct bt_l2cap_chan *chan, bt_l2cap_chan_state_t state, const char *func, int line) {
+  BT_DBG("chan %p psm 0x%04x %s -> %s", chan, chan->psm, bt_l2cap_chan_state_str(chan->state), bt_l2cap_chan_state_str(state));
+
+  /* check transitions validness */
+  switch (state) {
+  case BT_L2CAP_DISCONNECTED:
+    /* regardless of old state always allows this state */
+    break;
+  case BT_L2CAP_CONNECT:
+    if (chan->state != BT_L2CAP_DISCONNECTED) {
+      BT_WARN("%s()%d: invalid transition", func, line);
+    }
+    break;
+  case BT_L2CAP_CONFIG:
+    if (chan->state != BT_L2CAP_CONNECT) {
+      BT_WARN("%s()%d: invalid transition", func, line);
+    }
+    break;
+  case BT_L2CAP_CONNECTED:
+    if (chan->state != BT_L2CAP_CONFIG && chan->state != BT_L2CAP_CONNECT) {
+      BT_WARN("%s()%d: invalid transition", func, line);
+    }
+    break;
+  case BT_L2CAP_DISCONNECT:
+    if (chan->state != BT_L2CAP_CONFIG && chan->state != BT_L2CAP_CONNECTED) {
+      BT_WARN("%s()%d: invalid transition", func, line);
+    }
+    break;
+  default:
+    BT_ERR("%s()%d: unknown (%u) state was set", func, line, state);
+    return;
+  }
+
+  chan->state = state;
 }
 #else
-void bt_l2cap_chan_set_state(struct bt_l2cap_chan *chan,
-                             bt_l2cap_chan_state_t state)
-{
-    chan->state = state;
-}
+void bt_l2cap_chan_set_state(struct bt_l2cap_chan *chan, bt_l2cap_chan_state_t state) { chan->state = state; }
 #endif /* CONFIG_BT_DEBUG_L2CAP */
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-void bt_l2cap_chan_del(struct bt_l2cap_chan *chan)
-{
-    BT_DBG("conn %p chan %p", chan->conn, chan);
+void bt_l2cap_chan_del(struct bt_l2cap_chan *chan) {
+  BT_DBG("conn %p chan %p", chan->conn, chan);
 
-    if (!chan->conn) {
-        goto destroy;
-    }
+  if (!chan->conn) {
+    goto destroy;
+  }
 
-    if (chan->ops->disconnected) {
-        chan->ops->disconnected(chan);
-    }
+  if (chan->ops->disconnected) {
+    chan->ops->disconnected(chan);
+  }
 
-    chan->conn = NULL;
+  chan->conn = NULL;
 
 destroy:
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-    /* Reset internal members of common channel */
-    bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECTED);
-    chan->psm = 0U;
+  /* Reset internal members of common channel */
+  bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECTED);
+  chan->psm = 0U;
 #endif
 
-    if (chan->destroy) {
-        chan->destroy(chan);
-    }
+  if (chan->destroy) {
+    chan->destroy(chan);
+  }
 
 #ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS
-    if (chan->rtx_work.timer.timer.hdl)
-        k_delayed_work_del_timer(&chan->rtx_work);
+  if (chan->rtx_work.timer.timer.hdl)
+    k_delayed_work_del_timer(&chan->rtx_work);
 #endif
 }
 
-static void l2cap_rtx_timeout(struct k_work *work)
-{
-    struct bt_l2cap_le_chan *chan = LE_CHAN_RTX(work);
+static void l2cap_rtx_timeout(struct k_work *work) {
+  struct bt_l2cap_le_chan *chan = LE_CHAN_RTX(work);
 
-    BT_ERR("chan %p timeout", chan);
+  BT_ERR("chan %p timeout", chan);
 
-    bt_l2cap_chan_remove(chan->chan.conn, &chan->chan);
-    bt_l2cap_chan_del(&chan->chan);
+  bt_l2cap_chan_remove(chan->chan.conn, &chan->chan);
+  bt_l2cap_chan_del(&chan->chan);
 }
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-static void l2cap_chan_le_recv(struct bt_l2cap_le_chan *chan,
-                               struct net_buf *buf);
-
-static void l2cap_rx_process(struct k_work *work)
-{
-    struct bt_l2cap_le_chan *ch = CHAN_RX(work);
-    struct net_buf *buf;
-
-    while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) {
-        BT_DBG("ch %p buf %p", ch, buf);
-        l2cap_chan_le_recv(ch, buf);
-        net_buf_unref(buf);
-    }
+static void l2cap_chan_le_recv(struct bt_l2cap_le_chan *chan, struct net_buf *buf);
+
+static void l2cap_rx_process(struct k_work *work) {
+  struct bt_l2cap_le_chan *ch = CHAN_RX(work);
+  struct net_buf          *buf;
+
+  while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) {
+    BT_DBG("ch %p buf %p", ch, buf);
+    l2cap_chan_le_recv(ch, buf);
+    net_buf_unref(buf);
+  }
 }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-void bt_l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan,
-                       bt_l2cap_chan_destroy_t destroy)
-{
-    /* Attach channel to the connection */
-    sys_slist_append(&conn->channels, &chan->node);
-    chan->conn = conn;
-    chan->destroy = destroy;
+void bt_l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan, bt_l2cap_chan_destroy_t destroy) {
+  /* Attach channel to the connection */
+  sys_slist_append(&conn->channels, &chan->node);
+  chan->conn    = conn;
+  chan->destroy = destroy;
 
-    BT_DBG("conn %p chan %p", conn, chan);
+  BT_DBG("conn %p chan %p", conn, chan);
 }
 
-static bool l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan,
-                           bt_l2cap_chan_destroy_t destroy)
-{
-    struct bt_l2cap_le_chan *ch;
+static bool l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan, bt_l2cap_chan_destroy_t destroy) {
+  struct bt_l2cap_le_chan *ch;
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-    ch = l2cap_chan_alloc_cid(conn, chan);
+  ch = l2cap_chan_alloc_cid(conn, chan);
 #else
-    ch = BT_L2CAP_LE_CHAN(chan);
+  ch = BT_L2CAP_LE_CHAN(chan);
 #endif
 
-    if (!ch) {
-        BT_ERR("Unable to allocate L2CAP CID");
-        return false;
-    }
+  if (!ch) {
+    BT_ERR("Unable to allocate L2CAP CID");
+    return false;
+  }
 
-    k_delayed_work_init(&chan->rtx_work, l2cap_rtx_timeout);
+  k_delayed_work_init(&chan->rtx_work, l2cap_rtx_timeout);
 
-    bt_l2cap_chan_add(conn, chan, destroy);
+  bt_l2cap_chan_add(conn, chan, destroy);
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-    if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) {
-        k_work_init(&ch->rx_work, l2cap_rx_process);
-        k_fifo_init(&ch->rx_queue, 20);
-        bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECT);
-    }
+  if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) {
+    k_work_init(&ch->rx_work, l2cap_rx_process);
+    k_fifo_init(&ch->rx_queue, 20);
+    bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECT);
+  }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-    return true;
+  return true;
 }
 
-void bt_l2cap_connected(struct bt_conn *conn)
-{
+void bt_l2cap_connected(struct bt_conn *conn) {
 #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL)
-    struct bt_l2cap_fixed_chan *fchan;
+  struct bt_l2cap_fixed_chan *fchan;
 #endif
-    struct bt_l2cap_chan *chan;
+  struct bt_l2cap_chan *chan;
 
-    if (IS_ENABLED(CONFIG_BT_BREDR) &&
-        conn->type == BT_CONN_TYPE_BR) {
-        bt_l2cap_br_connected(conn);
-        return;
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
+    bt_l2cap_br_connected(conn);
+    return;
+  }
 
 #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL)
-    SYS_SLIST_FOR_EACH_CONTAINER(&le_channels, fchan, node)
-    {
+  SYS_SLIST_FOR_EACH_CONTAINER(&le_channels, fchan, node) {
 #else
-    Z_STRUCT_SECTION_FOREACH(bt_l2cap_fixed_chan, fchan)
-    {
+  Z_STRUCT_SECTION_FOREACH(bt_l2cap_fixed_chan, fchan) {
 #endif
-        struct bt_l2cap_le_chan *ch;
+    struct bt_l2cap_le_chan *ch;
 
-        if (fchan->accept(conn, &chan) < 0) {
-            continue;
-        }
+    if (fchan->accept(conn, &chan) < 0) {
+      continue;
+    }
 
-        ch = BT_L2CAP_LE_CHAN(chan);
+    ch = BT_L2CAP_LE_CHAN(chan);
 
-        /* Fill up remaining fixed channel context attached in
-		 * fchan->accept()
-		 */
-        ch->rx.cid = fchan->cid;
-        ch->tx.cid = fchan->cid;
+    /* Fill up remaining fixed channel context attached in
+     * fchan->accept()
+     */
+    ch->rx.cid = fchan->cid;
+    ch->tx.cid = fchan->cid;
 
-        if (!l2cap_chan_add(conn, chan, NULL)) {
-            return;
-        }
+    if (!l2cap_chan_add(conn, chan, NULL)) {
+      return;
+    }
 
-        if (chan->ops->connected) {
-            chan->ops->connected(chan);
-        }
+    if (chan->ops->connected) {
+      chan->ops->connected(chan);
+    }
 
-        /* Always set output status to fixed channels */
-        atomic_set_bit(chan->status, BT_L2CAP_STATUS_OUT);
+    /* Always set output status to fixed channels */
+    atomic_set_bit(chan->status, BT_L2CAP_STATUS_OUT);
 
-        if (chan->ops->status) {
-            chan->ops->status(chan, chan->status);
-        }
+    if (chan->ops->status) {
+      chan->ops->status(chan, chan->status);
     }
+  }
 }
 
-void bt_l2cap_disconnected(struct bt_conn *conn)
-{
-    struct bt_l2cap_chan *chan, *next;
+void bt_l2cap_disconnected(struct bt_conn *conn) {
+  struct bt_l2cap_chan *chan, *next;
 
-    SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&conn->channels, chan, next, node)
-    {
-        bt_l2cap_chan_del(chan);
-    }
+  SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&conn->channels, chan, next, node) { bt_l2cap_chan_del(chan); }
 }
 
-static struct net_buf *l2cap_create_le_sig_pdu(struct net_buf *buf,
-                                               u8_t code, u8_t ident,
-                                               u16_t len)
-{
-    struct bt_l2cap_sig_hdr *hdr;
-
-    /* Don't wait more than the minimum RTX timeout of 2 seconds */
-    buf = bt_l2cap_create_pdu_timeout(NULL, 0, K_SECONDS(2));
-    if (!buf) {
-        /* If it was not possible to allocate a buffer within the
-		 * timeout return NULL.
-		 */
-        BT_ERR("Unable to allocate buffer for op 0x%02x", code);
-        return NULL;
-    }
+static struct net_buf *l2cap_create_le_sig_pdu(struct net_buf *buf, u8_t code, u8_t ident, u16_t len) {
+  struct bt_l2cap_sig_hdr *hdr;
+
+  /* Don't wait more than the minimum RTX timeout of 2 seconds */
+  buf = bt_l2cap_create_pdu_timeout(NULL, 0, K_SECONDS(2));
+  if (!buf) {
+    /* If it was not possible to allocate a buffer within the
+     * timeout return NULL.
+     */
+    BT_ERR("Unable to allocate buffer for op 0x%02x", code);
+    return NULL;
+  }
 
-    hdr = net_buf_add(buf, sizeof(*hdr));
-    hdr->code = code;
-    hdr->ident = ident;
-    hdr->len = sys_cpu_to_le16(len);
+  hdr        = net_buf_add(buf, sizeof(*hdr));
+  hdr->code  = code;
+  hdr->ident = ident;
+  hdr->len   = sys_cpu_to_le16(len);
 
-    return buf;
+  return buf;
 }
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-static void l2cap_chan_send_req(struct bt_l2cap_le_chan *chan,
-                                struct net_buf *buf, s32_t timeout)
-{
-    /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part A] page 126:
-	 *
-	 * The value of this timer is implementation-dependent but the minimum
-	 * initial value is 1 second and the maximum initial value is 60
-	 * seconds. One RTX timer shall exist for each outstanding signaling
-	 * request, including each Echo Request. The timer disappears on the
-	 * final expiration, when the response is received, or the physical
-	 * link is lost.
-	 */
-    if (timeout) {
-        k_delayed_work_submit(&chan->chan.rtx_work, timeout);
-    } else {
-        k_delayed_work_cancel(&chan->chan.rtx_work);
-    }
+static void l2cap_chan_send_req(struct bt_l2cap_le_chan *chan, struct net_buf *buf, s32_t timeout) {
+  /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part A] page 126:
+   *
+   * The value of this timer is implementation-dependent but the minimum
+   * initial value is 1 second and the maximum initial value is 60
+   * seconds. One RTX timer shall exist for each outstanding signaling
+   * request, including each Echo Request. The timer disappears on the
+   * final expiration, when the response is received, or the physical
+   * link is lost.
+   */
+  if (timeout) {
+    k_delayed_work_submit(&chan->chan.rtx_work, timeout);
+  } else {
+    k_delayed_work_cancel(&chan->chan.rtx_work);
+  }
 
-    bt_l2cap_send(chan->chan.conn, BT_L2CAP_CID_LE_SIG, buf);
+  bt_l2cap_send(chan->chan.conn, BT_L2CAP_CID_LE_SIG, buf);
 }
 
-static int l2cap_le_conn_req(struct bt_l2cap_le_chan *ch)
-{
-    struct net_buf *buf;
-    struct bt_l2cap_le_conn_req *req;
+static int l2cap_le_conn_req(struct bt_l2cap_le_chan *ch) {
+  struct net_buf              *buf;
+  struct bt_l2cap_le_conn_req *req;
 
-    ch->chan.ident = get_ident();
+  ch->chan.ident = get_ident();
 
-    buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_LE_CONN_REQ,
-                                  ch->chan.ident, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_LE_CONN_REQ, ch->chan.ident, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->psm = sys_cpu_to_le16(ch->chan.psm);
-    req->scid = sys_cpu_to_le16(ch->rx.cid);
-    req->mtu = sys_cpu_to_le16(ch->rx.mtu);
-    req->mps = sys_cpu_to_le16(ch->rx.mps);
-    req->credits = sys_cpu_to_le16(ch->rx.init_credits);
+  req          = net_buf_add(buf, sizeof(*req));
+  req->psm     = sys_cpu_to_le16(ch->chan.psm);
+  req->scid    = sys_cpu_to_le16(ch->rx.cid);
+  req->mtu     = sys_cpu_to_le16(ch->rx.mtu);
+  req->mps     = sys_cpu_to_le16(ch->rx.mps);
+  req->credits = sys_cpu_to_le16(ch->rx.init_credits);
 
-    l2cap_chan_send_req(ch, buf, L2CAP_CONN_TIMEOUT);
+  l2cap_chan_send_req(ch, buf, L2CAP_CONN_TIMEOUT);
 
-    return 0;
+  return 0;
 }
 
-static void l2cap_le_encrypt_change(struct bt_l2cap_chan *chan, u8_t status)
-{
-    /* Skip channels already connected or with a pending request */
-    if (chan->state != BT_L2CAP_CONNECT || chan->ident) {
-        return;
-    }
+static void l2cap_le_encrypt_change(struct bt_l2cap_chan *chan, u8_t status) {
+  /* Skip channels already connected or with a pending request */
+  if (chan->state != BT_L2CAP_CONNECT || chan->ident) {
+    return;
+  }
 
-    if (status) {
-        bt_l2cap_chan_remove(chan->conn, chan);
-        bt_l2cap_chan_del(chan);
-        return;
-    }
+  if (status) {
+    bt_l2cap_chan_remove(chan->conn, chan);
+    bt_l2cap_chan_del(chan);
+    return;
+  }
 
-    /* Retry to connect */
-    l2cap_le_conn_req(BT_L2CAP_LE_CHAN(chan));
+  /* Retry to connect */
+  l2cap_le_conn_req(BT_L2CAP_LE_CHAN(chan));
 }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-void bt_l2cap_encrypt_change(struct bt_conn *conn, u8_t hci_status)
-{
-    struct bt_l2cap_chan *chan;
+void bt_l2cap_encrypt_change(struct bt_conn *conn, u8_t hci_status) {
+  struct bt_l2cap_chan *chan;
 
-    if (IS_ENABLED(CONFIG_BT_BREDR) &&
-        conn->type == BT_CONN_TYPE_BR) {
-        l2cap_br_encrypt_change(conn, hci_status);
-        return;
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
+    l2cap_br_encrypt_change(conn, hci_status);
+    return;
+  }
 
-    SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node)
-    {
+  SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) {
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-        l2cap_le_encrypt_change(chan, hci_status);
+    l2cap_le_encrypt_change(chan, hci_status);
 #endif
 
-        if (chan->ops->encrypt_change) {
-            chan->ops->encrypt_change(chan, hci_status);
-        }
+    if (chan->ops->encrypt_change) {
+      chan->ops->encrypt_change(chan, hci_status);
     }
+  }
 }
 
-struct net_buf *bt_l2cap_create_pdu_timeout(struct net_buf_pool *pool,
-                                            size_t reserve, s32_t timeout)
-{
-    return bt_conn_create_pdu_timeout(pool,
-                                      sizeof(struct bt_l2cap_hdr) + reserve,
-                                      timeout);
-}
+struct net_buf *bt_l2cap_create_pdu_timeout(struct net_buf_pool *pool, size_t reserve, s32_t timeout) { return bt_conn_create_pdu_timeout(pool, sizeof(struct bt_l2cap_hdr) + reserve, timeout); }
 
-int bt_l2cap_send_cb(struct bt_conn *conn, u16_t cid, struct net_buf *buf,
-                     bt_conn_tx_cb_t cb, void *user_data)
-{
-    struct bt_l2cap_hdr *hdr;
+int bt_l2cap_send_cb(struct bt_conn *conn, u16_t cid, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data) {
+  struct bt_l2cap_hdr *hdr;
 
-    BT_DBG("conn %p cid %u len %zu", conn, cid, net_buf_frags_len(buf));
+  BT_DBG("conn %p cid %u len %zu", conn, cid, net_buf_frags_len(buf));
 
-    hdr = net_buf_push(buf, sizeof(*hdr));
-    hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr));
-    hdr->cid = sys_cpu_to_le16(cid);
+  hdr      = net_buf_push(buf, sizeof(*hdr));
+  hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr));
+  hdr->cid = sys_cpu_to_le16(cid);
 
-    return bt_conn_send_cb(conn, buf, cb, user_data);
+  return bt_conn_send_cb(conn, buf, cb, user_data);
 }
 
-static void l2cap_send_reject(struct bt_conn *conn, u8_t ident,
-                              u16_t reason, void *data, u8_t data_len)
-{
-    struct bt_l2cap_cmd_reject *rej;
-    struct net_buf *buf;
+static void l2cap_send_reject(struct bt_conn *conn, u8_t ident, u16_t reason, void *data, u8_t data_len) {
+  struct bt_l2cap_cmd_reject *rej;
+  struct net_buf             *buf;
 
-    buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CMD_REJECT, ident,
-                                  sizeof(*rej) + data_len);
-    if (!buf) {
-        return;
-    }
+  buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CMD_REJECT, ident, sizeof(*rej) + data_len);
+  if (!buf) {
+    return;
+  }
 
-    rej = net_buf_add(buf, sizeof(*rej));
-    rej->reason = sys_cpu_to_le16(reason);
+  rej         = net_buf_add(buf, sizeof(*rej));
+  rej->reason = sys_cpu_to_le16(reason);
 
-    if (data) {
-        net_buf_add_mem(buf, data, data_len);
-    }
+  if (data) {
+    net_buf_add_mem(buf, data, data_len);
+  }
 
-    bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
+  bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
 }
 
-static void le_conn_param_rsp(struct bt_l2cap *l2cap, struct net_buf *buf)
-{
-    struct bt_l2cap_conn_param_rsp *rsp = (void *)buf->data;
+static void le_conn_param_rsp(struct bt_l2cap *l2cap, struct net_buf *buf) {
+  struct bt_l2cap_conn_param_rsp *rsp = (void *)buf->data;
 
-    if (buf->len < sizeof(*rsp)) {
-        BT_ERR("Too small LE conn param rsp");
-        return;
-    }
+  if (buf->len < sizeof(*rsp)) {
+    BT_ERR("Too small LE conn param rsp");
+    return;
+  }
 
-    BT_DBG("LE conn param rsp result %u", sys_le16_to_cpu(rsp->result));
+  BT_DBG("LE conn param rsp result %u", sys_le16_to_cpu(rsp->result));
 }
 
-static void le_conn_param_update_req(struct bt_l2cap *l2cap, u8_t ident,
-                                     struct net_buf *buf)
-{
-    struct bt_conn *conn = l2cap->chan.chan.conn;
-    struct bt_le_conn_param param;
-    struct bt_l2cap_conn_param_rsp *rsp;
-    struct bt_l2cap_conn_param_req *req = (void *)buf->data;
-    bool accepted;
+static void le_conn_param_update_req(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) {
+  struct bt_conn                 *conn = l2cap->chan.chan.conn;
+  struct bt_le_conn_param         param;
+  struct bt_l2cap_conn_param_rsp *rsp;
+  struct bt_l2cap_conn_param_req *req = (void *)buf->data;
+  bool                            accepted;
 
-    if (buf->len < sizeof(*req)) {
-        BT_ERR("Too small LE conn update param req");
-        return;
-    }
+  if (buf->len < sizeof(*req)) {
+    BT_ERR("Too small LE conn update param req");
+    return;
+  }
 
-    if (conn->role != BT_HCI_ROLE_MASTER) {
-        l2cap_send_reject(conn, ident, BT_L2CAP_REJ_NOT_UNDERSTOOD,
-                          NULL, 0);
-        return;
-    }
+  if (conn->role != BT_HCI_ROLE_MASTER) {
+    l2cap_send_reject(conn, ident, BT_L2CAP_REJ_NOT_UNDERSTOOD, NULL, 0);
+    return;
+  }
 
-    param.interval_min = sys_le16_to_cpu(req->min_interval);
-    param.interval_max = sys_le16_to_cpu(req->max_interval);
-    param.latency = sys_le16_to_cpu(req->latency);
-    param.timeout = sys_le16_to_cpu(req->timeout);
+  param.interval_min = sys_le16_to_cpu(req->min_interval);
+  param.interval_max = sys_le16_to_cpu(req->max_interval);
+  param.latency      = sys_le16_to_cpu(req->latency);
+  param.timeout      = sys_le16_to_cpu(req->timeout);
 
-    BT_DBG("min 0x%04x max 0x%04x latency: 0x%04x timeout: 0x%04x",
-           param.interval_min, param.interval_max, param.latency,
-           param.timeout);
+  BT_DBG("min 0x%04x max 0x%04x latency: 0x%04x timeout: 0x%04x", param.interval_min, param.interval_max, param.latency, param.timeout);
 
-    buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_CONN_PARAM_RSP, ident,
-                                  sizeof(*rsp));
-    if (!buf) {
-        return;
-    }
+  buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_CONN_PARAM_RSP, ident, sizeof(*rsp));
+  if (!buf) {
+    return;
+  }
 
-    accepted = le_param_req(conn, ¶m);
+  accepted = le_param_req(conn, ¶m);
 
-    rsp = net_buf_add(buf, sizeof(*rsp));
-    if (accepted) {
-        rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_ACCEPTED);
-    } else {
-        rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_REJECTED);
-    }
+  rsp = net_buf_add(buf, sizeof(*rsp));
+  if (accepted) {
+    rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_ACCEPTED);
+  } else {
+    rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_REJECTED);
+  }
 
-    bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
+  bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
 
-    if (accepted) {
-        bt_conn_le_conn_update(conn, ¶m);
-    }
+  if (accepted) {
+    bt_conn_le_conn_update(conn, ¶m);
+  }
 }
 
-struct bt_l2cap_chan *bt_l2cap_le_lookup_tx_cid(struct bt_conn *conn,
-                                                u16_t cid)
-{
-    struct bt_l2cap_chan *chan;
+struct bt_l2cap_chan *bt_l2cap_le_lookup_tx_cid(struct bt_conn *conn, u16_t cid) {
+  struct bt_l2cap_chan *chan;
 
-    SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node)
-    {
-        if (BT_L2CAP_LE_CHAN(chan)->tx.cid == cid) {
-            return chan;
-        }
+  SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) {
+    if (BT_L2CAP_LE_CHAN(chan)->tx.cid == cid) {
+      return chan;
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-struct bt_l2cap_chan *bt_l2cap_le_lookup_rx_cid(struct bt_conn *conn,
-                                                u16_t cid)
-{
-    struct bt_l2cap_chan *chan;
+struct bt_l2cap_chan *bt_l2cap_le_lookup_rx_cid(struct bt_conn *conn, u16_t cid) {
+  struct bt_l2cap_chan *chan;
 
-    SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node)
-    {
-        if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) {
-            return chan;
-        }
+  SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) {
+    if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) {
+      return chan;
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-static struct bt_l2cap_server *l2cap_server_lookup_psm(u16_t psm)
-{
-    struct bt_l2cap_server *server;
-
-    SYS_SLIST_FOR_EACH_CONTAINER(&servers, server, node)
-    {
-        if (server->psm == psm) {
-            return server;
-        }
+static struct bt_l2cap_server *l2cap_server_lookup_psm(u16_t psm) {
+  struct bt_l2cap_server *server;
+
+  SYS_SLIST_FOR_EACH_CONTAINER(&servers, server, node) {
+    if (server->psm == psm) {
+      return server;
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-int bt_l2cap_server_register(struct bt_l2cap_server *server)
-{
-    if (!server->accept) {
-        return -EINVAL;
-    }
+int bt_l2cap_server_register(struct bt_l2cap_server *server) {
+  if (!server->accept) {
+    return -EINVAL;
+  }
 
-    if (server->psm) {
-        if (server->psm < L2CAP_LE_PSM_FIXED_START ||
-            server->psm > L2CAP_LE_PSM_DYN_END) {
-            return -EINVAL;
-        }
-
-        /* Check if given PSM is already in use */
-        if (l2cap_server_lookup_psm(server->psm)) {
-            BT_DBG("PSM already registered");
-            return -EADDRINUSE;
-        }
-    } else {
-        u16_t psm;
-
-        for (psm = L2CAP_LE_PSM_DYN_START;
-             psm <= L2CAP_LE_PSM_DYN_END; psm++) {
-            if (!l2cap_server_lookup_psm(psm)) {
-                break;
-            }
-        }
-
-        if (psm > L2CAP_LE_PSM_DYN_END) {
-            BT_WARN("No free dynamic PSMs available");
-            return -EADDRNOTAVAIL;
-        }
-
-        BT_DBG("Allocated PSM 0x%04x for new server", psm);
-        server->psm = psm;
+  if (server->psm) {
+    if (server->psm < L2CAP_LE_PSM_FIXED_START || server->psm > L2CAP_LE_PSM_DYN_END) {
+      return -EINVAL;
     }
 
-    if (server->sec_level > BT_SECURITY_L4) {
-        return -EINVAL;
-    } else if (server->sec_level < BT_SECURITY_L1) {
-        /* Level 0 is only applicable for BR/EDR */
-        server->sec_level = BT_SECURITY_L1;
+    /* Check if given PSM is already in use */
+    if (l2cap_server_lookup_psm(server->psm)) {
+      BT_DBG("PSM already registered");
+      return -EADDRINUSE;
     }
+  } else {
+    u16_t psm;
 
-    BT_DBG("PSM 0x%04x", server->psm);
-
-    sys_slist_append(&servers, &server->node);
-
-    return 0;
-}
-
-static void l2cap_chan_rx_init(struct bt_l2cap_le_chan *chan)
-{
-    BT_DBG("chan %p", chan);
-
-    /* Use existing MTU if defined */
-    if (!chan->rx.mtu) {
-        chan->rx.mtu = L2CAP_MAX_LE_MTU;
+    for (psm = L2CAP_LE_PSM_DYN_START; psm <= L2CAP_LE_PSM_DYN_END; psm++) {
+      if (!l2cap_server_lookup_psm(psm)) {
+        break;
+      }
     }
 
-    /* Use existing credits if defined */
-    if (!chan->rx.init_credits) {
-        if (chan->chan.ops->alloc_buf) {
-            /* Auto tune credits to receive a full packet */
-            chan->rx.init_credits = (chan->rx.mtu +
-                                     (L2CAP_MAX_LE_MPS - 1)) /
-                                    L2CAP_MAX_LE_MPS;
-        } else {
-            chan->rx.init_credits = L2CAP_LE_MAX_CREDITS;
-        }
+    if (psm > L2CAP_LE_PSM_DYN_END) {
+      BT_WARN("No free dynamic PSMs available");
+      return -EADDRNOTAVAIL;
     }
 
-    /* MPS shall not be bigger than MTU + 2 as the remaining bytes cannot
-	 * be used.
-	 */
-    chan->rx.mps = MIN(chan->rx.mtu + 2, L2CAP_MAX_LE_MPS);
-    k_sem_init(&chan->rx.credits, 0, BT_UINT_MAX);
+    BT_DBG("Allocated PSM 0x%04x for new server", psm);
+    server->psm = psm;
+  }
 
-    if (BT_DBG_ENABLED &&
-        chan->rx.init_credits * chan->rx.mps < chan->rx.mtu + 2) {
-        BT_WARN("Not enough credits for a full packet");
-    }
-}
+  if (server->sec_level > BT_SECURITY_L4) {
+    return -EINVAL;
+  } else if (server->sec_level < BT_SECURITY_L1) {
+    /* Level 0 is only applicable for BR/EDR */
+    server->sec_level = BT_SECURITY_L1;
+  }
+
+  BT_DBG("PSM 0x%04x", server->psm);
 
-static void l2cap_chan_tx_init(struct bt_l2cap_le_chan *chan)
-{
-    BT_DBG("chan %p", chan);
+  sys_slist_append(&servers, &server->node);
 
-    (void)memset(&chan->tx, 0, sizeof(chan->tx));
-    k_sem_init(&chan->tx.credits, 0, BT_UINT_MAX);
-    k_fifo_init(&chan->tx_queue, 20);
+  return 0;
 }
 
-static void l2cap_chan_tx_give_credits(struct bt_l2cap_le_chan *chan,
-                                       u16_t credits)
-{
-    BT_DBG("chan %p credits %u", chan, credits);
+static void l2cap_chan_rx_init(struct bt_l2cap_le_chan *chan) {
+  BT_DBG("chan %p", chan);
 
-    while (credits--) {
-        k_sem_give(&chan->tx.credits);
-    }
+  /* Use existing MTU if defined */
+  if (!chan->rx.mtu) {
+    chan->rx.mtu = L2CAP_MAX_LE_MTU;
+  }
 
-    if (atomic_test_and_set_bit(chan->chan.status, BT_L2CAP_STATUS_OUT) &&
-        chan->chan.ops->status) {
-        chan->chan.ops->status(&chan->chan, chan->chan.status);
+  /* Use existing credits if defined */
+  if (!chan->rx.init_credits) {
+    if (chan->chan.ops->alloc_buf) {
+      /* Auto tune credits to receive a full packet */
+      chan->rx.init_credits = (chan->rx.mtu + (L2CAP_MAX_LE_MPS - 1)) / L2CAP_MAX_LE_MPS;
+    } else {
+      chan->rx.init_credits = L2CAP_LE_MAX_CREDITS;
     }
-}
+  }
 
-static void l2cap_chan_rx_give_credits(struct bt_l2cap_le_chan *chan,
-                                       u16_t credits)
-{
-    BT_DBG("chan %p credits %u", chan, credits);
+  /* MPS shall not be bigger than MTU + 2 as the remaining bytes cannot
+   * be used.
+   */
+  chan->rx.mps = MIN(chan->rx.mtu + 2, L2CAP_MAX_LE_MPS);
+  k_sem_init(&chan->rx.credits, 0, BT_UINT_MAX);
 
-    while (credits--) {
-        k_sem_give(&chan->rx.credits);
-    }
+  if (BT_DBG_ENABLED && chan->rx.init_credits * chan->rx.mps < chan->rx.mtu + 2) {
+    BT_WARN("Not enough credits for a full packet");
+  }
 }
 
-static void l2cap_chan_destroy(struct bt_l2cap_chan *chan)
-{
-    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
-    struct net_buf *buf;
+static void l2cap_chan_tx_init(struct bt_l2cap_le_chan *chan) {
+  BT_DBG("chan %p", chan);
 
-    BT_DBG("chan %p cid 0x%04x", ch, ch->rx.cid);
-
-    /* Cancel ongoing work */
-    k_delayed_work_cancel(&chan->rtx_work);
-
-    if (ch->tx_buf) {
-        net_buf_unref(ch->tx_buf);
-        ch->tx_buf = NULL;
-    }
+  (void)memset(&chan->tx, 0, sizeof(chan->tx));
+  k_sem_init(&chan->tx.credits, 0, BT_UINT_MAX);
+  k_fifo_init(&chan->tx_queue, 20);
+}
 
-    /* Remove buffers on the TX queue */
-    while ((buf = net_buf_get(&ch->tx_queue, K_NO_WAIT))) {
-        net_buf_unref(buf);
-    }
+static void l2cap_chan_tx_give_credits(struct bt_l2cap_le_chan *chan, u16_t credits) {
+  BT_DBG("chan %p credits %u", chan, credits);
 
-    /* Remove buffers on the RX queue */
-    while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) {
-        net_buf_unref(buf);
-    }
+  while (credits--) {
+    k_sem_give(&chan->tx.credits);
+  }
 
-    /* Destroy segmented SDU if it exists */
-    if (ch->_sdu) {
-        net_buf_unref(ch->_sdu);
-        ch->_sdu = NULL;
-        ch->_sdu_len = 0U;
-    }
+  if (atomic_test_and_set_bit(chan->chan.status, BT_L2CAP_STATUS_OUT) && chan->chan.ops->status) {
+    chan->chan.ops->status(&chan->chan, chan->chan.status);
+  }
 }
 
-static u16_t le_err_to_result(int err)
-{
-    switch (err) {
-        case -ENOMEM:
-            return BT_L2CAP_LE_ERR_NO_RESOURCES;
-        case -EACCES:
-            return BT_L2CAP_LE_ERR_AUTHORIZATION;
-        case -EPERM:
-            return BT_L2CAP_LE_ERR_KEY_SIZE;
-        case -ENOTSUP:
-            /* This handle the cases where a fixed channel is registered but
-		 * for some reason (e.g. controller not suporting a feature)
-		 * cannot be used.
-		 */
-            return BT_L2CAP_LE_ERR_PSM_NOT_SUPP;
-        default:
-            return BT_L2CAP_LE_ERR_UNACCEPT_PARAMS;
-    }
+static void l2cap_chan_rx_give_credits(struct bt_l2cap_le_chan *chan, u16_t credits) {
+  BT_DBG("chan %p credits %u", chan, credits);
+
+  while (credits--) {
+    k_sem_give(&chan->rx.credits);
+  }
 }
 
-static void le_conn_req(struct bt_l2cap *l2cap, u8_t ident,
-                        struct net_buf *buf)
-{
-    struct bt_conn *conn = l2cap->chan.chan.conn;
-    struct bt_l2cap_chan *chan;
-    struct bt_l2cap_server *server;
-    struct bt_l2cap_le_conn_req *req = (void *)buf->data;
-    struct bt_l2cap_le_conn_rsp *rsp;
-    u16_t psm, scid, mtu, mps, credits;
-    int err;
-
-    if (buf->len < sizeof(*req)) {
-        BT_ERR("Too small LE conn req packet size");
-        return;
-    }
+static void l2cap_chan_destroy(struct bt_l2cap_chan *chan) {
+  struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
+  struct net_buf          *buf;
 
-    psm = sys_le16_to_cpu(req->psm);
-    scid = sys_le16_to_cpu(req->scid);
-    mtu = sys_le16_to_cpu(req->mtu);
-    mps = sys_le16_to_cpu(req->mps);
-    credits = sys_le16_to_cpu(req->credits);
+  BT_DBG("chan %p cid 0x%04x", ch, ch->rx.cid);
 
-    BT_DBG("psm 0x%02x scid 0x%04x mtu %u mps %u credits %u", psm, scid,
-           mtu, mps, credits);
+  /* Cancel ongoing work */
+  k_delayed_work_cancel(&chan->rtx_work);
 
-    if (mtu < L2CAP_LE_MIN_MTU || mps < L2CAP_LE_MIN_MTU) {
-        BT_ERR("Invalid LE-Conn Req params");
-        return;
-    }
+  if (ch->tx_buf) {
+    net_buf_unref(ch->tx_buf);
+    ch->tx_buf = NULL;
+  }
 
-    buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CONN_RSP, ident,
-                                  sizeof(*rsp));
-    if (!buf) {
-        return;
-    }
-
-    rsp = net_buf_add(buf, sizeof(*rsp));
-    (void)memset(rsp, 0, sizeof(*rsp));
+  /* Remove buffers on the TX queue */
+  while ((buf = net_buf_get(&ch->tx_queue, K_NO_WAIT))) {
+    net_buf_unref(buf);
+  }
 
-    /* Check if there is a server registered */
-    server = l2cap_server_lookup_psm(psm);
-    if (!server) {
-        rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_PSM_NOT_SUPP);
-        goto rsp;
-    }
+  /* Remove buffers on the RX queue */
+  while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) {
+    net_buf_unref(buf);
+  }
+
+  /* Destroy segmented SDU if it exists */
+  if (ch->_sdu) {
+    net_buf_unref(ch->_sdu);
+    ch->_sdu     = NULL;
+    ch->_sdu_len = 0U;
+  }
+}
+
+static u16_t le_err_to_result(int err) {
+  switch (err) {
+  case -ENOMEM:
+    return BT_L2CAP_LE_ERR_NO_RESOURCES;
+  case -EACCES:
+    return BT_L2CAP_LE_ERR_AUTHORIZATION;
+  case -EPERM:
+    return BT_L2CAP_LE_ERR_KEY_SIZE;
+  case -ENOTSUP:
+    /* This handle the cases where a fixed channel is registered but
+     * for some reason (e.g. controller not suporting a feature)
+     * cannot be used.
+     */
+    return BT_L2CAP_LE_ERR_PSM_NOT_SUPP;
+  default:
+    return BT_L2CAP_LE_ERR_UNACCEPT_PARAMS;
+  }
+}
+
+static void le_conn_req(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) {
+  struct bt_conn              *conn = l2cap->chan.chan.conn;
+  struct bt_l2cap_chan        *chan;
+  struct bt_l2cap_server      *server;
+  struct bt_l2cap_le_conn_req *req = (void *)buf->data;
+  struct bt_l2cap_le_conn_rsp *rsp;
+  u16_t                        psm, scid, mtu, mps, credits;
+  int                          err;
+
+  if (buf->len < sizeof(*req)) {
+    BT_ERR("Too small LE conn req packet size");
+    return;
+  }
+
+  psm     = sys_le16_to_cpu(req->psm);
+  scid    = sys_le16_to_cpu(req->scid);
+  mtu     = sys_le16_to_cpu(req->mtu);
+  mps     = sys_le16_to_cpu(req->mps);
+  credits = sys_le16_to_cpu(req->credits);
+
+  BT_DBG("psm 0x%02x scid 0x%04x mtu %u mps %u credits %u", psm, scid, mtu, mps, credits);
+
+  if (mtu < L2CAP_LE_MIN_MTU || mps < L2CAP_LE_MIN_MTU) {
+    BT_ERR("Invalid LE-Conn Req params");
+    return;
+  }
+
+  buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CONN_RSP, ident, sizeof(*rsp));
+  if (!buf) {
+    return;
+  }
+
+  rsp = net_buf_add(buf, sizeof(*rsp));
+  (void)memset(rsp, 0, sizeof(*rsp));
+
+  /* Check if there is a server registered */
+  server = l2cap_server_lookup_psm(psm);
+  if (!server) {
+    rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_PSM_NOT_SUPP);
+    goto rsp;
+  }
 
 /* Check if connection has minimum required security level */
 #if defined(CONFIG_BT_SMP)
-    if (conn->sec_level < server->sec_level) {
-        rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_AUTHENTICATION);
-        goto rsp;
-    }
+  if (conn->sec_level < server->sec_level) {
+    rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_AUTHENTICATION);
+    goto rsp;
+  }
 #endif
 
-    if (!L2CAP_LE_CID_IS_DYN(scid)) {
-        rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_INVALID_SCID);
-        goto rsp;
-    }
-
-    chan = bt_l2cap_le_lookup_tx_cid(conn, scid);
-    if (chan) {
-        rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_SCID_IN_USE);
-        goto rsp;
-    }
-
-    /* Request server to accept the new connection and allocate the
-	 * channel.
-	 */
-    err = server->accept(conn, &chan);
-    if (err < 0) {
-        rsp->result = sys_cpu_to_le16(le_err_to_result(err));
-        goto rsp;
-    }
-
-    chan->required_sec_level = server->sec_level;
-
-    if (l2cap_chan_add(conn, chan, l2cap_chan_destroy)) {
-        struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
-
-        /* Init TX parameters */
-        l2cap_chan_tx_init(ch);
-        ch->tx.cid = scid;
-        ch->tx.mps = mps;
-        ch->tx.mtu = mtu;
-        ch->tx.init_credits = credits;
-        l2cap_chan_tx_give_credits(ch, credits);
+  if (!L2CAP_LE_CID_IS_DYN(scid)) {
+    rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_INVALID_SCID);
+    goto rsp;
+  }
+
+  chan = bt_l2cap_le_lookup_tx_cid(conn, scid);
+  if (chan) {
+    rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_SCID_IN_USE);
+    goto rsp;
+  }
+
+  /* Request server to accept the new connection and allocate the
+   * channel.
+   */
+  err = server->accept(conn, &chan);
+  if (err < 0) {
+    rsp->result = sys_cpu_to_le16(le_err_to_result(err));
+    goto rsp;
+  }
+
+  chan->required_sec_level = server->sec_level;
+
+  if (l2cap_chan_add(conn, chan, l2cap_chan_destroy)) {
+    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
 
-        /* Init RX parameters */
-        l2cap_chan_rx_init(ch);
-        l2cap_chan_rx_give_credits(ch, ch->rx.init_credits);
+    /* Init TX parameters */
+    l2cap_chan_tx_init(ch);
+    ch->tx.cid          = scid;
+    ch->tx.mps          = mps;
+    ch->tx.mtu          = mtu;
+    ch->tx.init_credits = credits;
+    l2cap_chan_tx_give_credits(ch, credits);
 
-        /* Set channel PSM */
-        chan->psm = server->psm;
+    /* Init RX parameters */
+    l2cap_chan_rx_init(ch);
+    l2cap_chan_rx_give_credits(ch, ch->rx.init_credits);
 
-        /* Update state */
-        bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECTED);
+    /* Set channel PSM */
+    chan->psm = server->psm;
 
-        if (chan->ops->connected) {
-            chan->ops->connected(chan);
-        }
+    /* Update state */
+    bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECTED);
 
-        /* Prepare response protocol data */
-        rsp->dcid = sys_cpu_to_le16(ch->rx.cid);
-        rsp->mps = sys_cpu_to_le16(ch->rx.mps);
-        rsp->mtu = sys_cpu_to_le16(ch->rx.mtu);
-        rsp->credits = sys_cpu_to_le16(ch->rx.init_credits);
-        rsp->result = BT_L2CAP_LE_SUCCESS;
-    } else {
-        rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_NO_RESOURCES);
+    if (chan->ops->connected) {
+      chan->ops->connected(chan);
     }
+
+    /* Prepare response protocol data */
+    rsp->dcid    = sys_cpu_to_le16(ch->rx.cid);
+    rsp->mps     = sys_cpu_to_le16(ch->rx.mps);
+    rsp->mtu     = sys_cpu_to_le16(ch->rx.mtu);
+    rsp->credits = sys_cpu_to_le16(ch->rx.init_credits);
+    rsp->result  = BT_L2CAP_LE_SUCCESS;
+  } else {
+    rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_NO_RESOURCES);
+  }
 rsp:
-    bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
+  bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
 }
 
-static struct bt_l2cap_le_chan *l2cap_remove_rx_cid(struct bt_conn *conn,
-                                                    u16_t cid)
-{
-    struct bt_l2cap_chan *chan;
-    sys_snode_t *prev = NULL;
-
-    /* Protect fixed channels against accidental removal */
-    if (!L2CAP_LE_CID_IS_DYN(cid)) {
-        return NULL;
-    }
+static struct bt_l2cap_le_chan *l2cap_remove_rx_cid(struct bt_conn *conn, u16_t cid) {
+  struct bt_l2cap_chan *chan;
+  sys_snode_t          *prev = NULL;
 
-    SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node)
-    {
-        if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) {
-            sys_slist_remove(&conn->channels, prev, &chan->node);
-            return BT_L2CAP_LE_CHAN(chan);
-        }
+  /* Protect fixed channels against accidental removal */
+  if (!L2CAP_LE_CID_IS_DYN(cid)) {
+    return NULL;
+  }
 
-        prev = &chan->node;
+  SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) {
+    if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) {
+      sys_slist_remove(&conn->channels, prev, &chan->node);
+      return BT_L2CAP_LE_CHAN(chan);
     }
 
-    return NULL;
+    prev = &chan->node;
+  }
+
+  return NULL;
 }
 
-static void le_disconn_req(struct bt_l2cap *l2cap, u8_t ident,
-                           struct net_buf *buf)
-{
-    struct bt_conn *conn = l2cap->chan.chan.conn;
-    struct bt_l2cap_le_chan *chan;
-    struct bt_l2cap_disconn_req *req = (void *)buf->data;
-    struct bt_l2cap_disconn_rsp *rsp;
-    u16_t dcid;
+static void le_disconn_req(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) {
+  struct bt_conn              *conn = l2cap->chan.chan.conn;
+  struct bt_l2cap_le_chan     *chan;
+  struct bt_l2cap_disconn_req *req = (void *)buf->data;
+  struct bt_l2cap_disconn_rsp *rsp;
+  u16_t                        dcid;
 
-    if (buf->len < sizeof(*req)) {
-        BT_ERR("Too small LE conn req packet size");
-        return;
-    }
+  if (buf->len < sizeof(*req)) {
+    BT_ERR("Too small LE conn req packet size");
+    return;
+  }
 
-    dcid = sys_le16_to_cpu(req->dcid);
+  dcid = sys_le16_to_cpu(req->dcid);
 
-    BT_DBG("dcid 0x%04x scid 0x%04x", dcid, sys_le16_to_cpu(req->scid));
+  BT_DBG("dcid 0x%04x scid 0x%04x", dcid, sys_le16_to_cpu(req->scid));
 
-    chan = l2cap_remove_rx_cid(conn, dcid);
-    if (!chan) {
-        struct bt_l2cap_cmd_reject_cid_data data;
+  chan = l2cap_remove_rx_cid(conn, dcid);
+  if (!chan) {
+    struct bt_l2cap_cmd_reject_cid_data data;
 
-        data.scid = req->scid;
-        data.dcid = req->dcid;
+    data.scid = req->scid;
+    data.dcid = req->dcid;
 
-        l2cap_send_reject(conn, ident, BT_L2CAP_REJ_INVALID_CID, &data,
-                          sizeof(data));
-        return;
-    }
+    l2cap_send_reject(conn, ident, BT_L2CAP_REJ_INVALID_CID, &data, sizeof(data));
+    return;
+  }
 
-    buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_DISCONN_RSP, ident,
-                                  sizeof(*rsp));
-    if (!buf) {
-        return;
-    }
+  buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_DISCONN_RSP, ident, sizeof(*rsp));
+  if (!buf) {
+    return;
+  }
 
-    rsp = net_buf_add(buf, sizeof(*rsp));
-    rsp->dcid = sys_cpu_to_le16(chan->rx.cid);
-    rsp->scid = sys_cpu_to_le16(chan->tx.cid);
+  rsp       = net_buf_add(buf, sizeof(*rsp));
+  rsp->dcid = sys_cpu_to_le16(chan->rx.cid);
+  rsp->scid = sys_cpu_to_le16(chan->tx.cid);
 
-    bt_l2cap_chan_del(&chan->chan);
+  bt_l2cap_chan_del(&chan->chan);
 
-    bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
+  bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
 }
 
 #if defined(CONFIG_BT_SMP)
-static int l2cap_change_security(struct bt_l2cap_le_chan *chan, u16_t err)
-{
-    switch (err) {
-        case BT_L2CAP_LE_ERR_ENCRYPTION:
-            if (chan->chan.required_sec_level >= BT_SECURITY_L2) {
-                return -EALREADY;
-            }
-            chan->chan.required_sec_level = BT_SECURITY_L2;
-            break;
-        case BT_L2CAP_LE_ERR_AUTHENTICATION:
-            if (chan->chan.required_sec_level < BT_SECURITY_L2) {
-                chan->chan.required_sec_level = BT_SECURITY_L2;
-            } else if (chan->chan.required_sec_level < BT_SECURITY_L3) {
-                chan->chan.required_sec_level = BT_SECURITY_L3;
-            } else if (chan->chan.required_sec_level < BT_SECURITY_L4) {
-                chan->chan.required_sec_level = BT_SECURITY_L4;
-            } else {
-                return -EALREADY;
-            }
-            break;
-        default:
-            return -EINVAL;
+static int l2cap_change_security(struct bt_l2cap_le_chan *chan, u16_t err) {
+  switch (err) {
+  case BT_L2CAP_LE_ERR_ENCRYPTION:
+    if (chan->chan.required_sec_level >= BT_SECURITY_L2) {
+      return -EALREADY;
+    }
+    chan->chan.required_sec_level = BT_SECURITY_L2;
+    break;
+  case BT_L2CAP_LE_ERR_AUTHENTICATION:
+    if (chan->chan.required_sec_level < BT_SECURITY_L2) {
+      chan->chan.required_sec_level = BT_SECURITY_L2;
+    } else if (chan->chan.required_sec_level < BT_SECURITY_L3) {
+      chan->chan.required_sec_level = BT_SECURITY_L3;
+    } else if (chan->chan.required_sec_level < BT_SECURITY_L4) {
+      chan->chan.required_sec_level = BT_SECURITY_L4;
+    } else {
+      return -EALREADY;
     }
+    break;
+  default:
+    return -EINVAL;
+  }
 
-    return bt_conn_set_security(chan->chan.conn,
-                                chan->chan.required_sec_level);
+  return bt_conn_set_security(chan->chan.conn, chan->chan.required_sec_level);
 }
-#endif //CONFIG_BT_SMP
+#endif // CONFIG_BT_SMP
 
-static void le_conn_rsp(struct bt_l2cap *l2cap, u8_t ident,
-                        struct net_buf *buf)
-{
-    struct bt_conn *conn = l2cap->chan.chan.conn;
-    struct bt_l2cap_le_chan *chan;
-    struct bt_l2cap_le_conn_rsp *rsp = (void *)buf->data;
-    u16_t dcid, mtu, mps, credits, result;
+static void le_conn_rsp(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) {
+  struct bt_conn              *conn = l2cap->chan.chan.conn;
+  struct bt_l2cap_le_chan     *chan;
+  struct bt_l2cap_le_conn_rsp *rsp = (void *)buf->data;
+  u16_t                        dcid, mtu, mps, credits, result;
 
-    if (buf->len < sizeof(*rsp)) {
-        BT_ERR("Too small LE conn rsp packet size");
-        return;
-    }
+  if (buf->len < sizeof(*rsp)) {
+    BT_ERR("Too small LE conn rsp packet size");
+    return;
+  }
 
-    dcid = sys_le16_to_cpu(rsp->dcid);
-    mtu = sys_le16_to_cpu(rsp->mtu);
-    mps = sys_le16_to_cpu(rsp->mps);
-    credits = sys_le16_to_cpu(rsp->credits);
-    result = sys_le16_to_cpu(rsp->result);
+  dcid    = sys_le16_to_cpu(rsp->dcid);
+  mtu     = sys_le16_to_cpu(rsp->mtu);
+  mps     = sys_le16_to_cpu(rsp->mps);
+  credits = sys_le16_to_cpu(rsp->credits);
+  result  = sys_le16_to_cpu(rsp->result);
 
-    BT_DBG("dcid 0x%04x mtu %u mps %u credits %u result 0x%04x", dcid,
-           mtu, mps, credits, result);
+  BT_DBG("dcid 0x%04x mtu %u mps %u credits %u result 0x%04x", dcid, mtu, mps, credits, result);
 
-    /* Keep the channel in case of security errors */
-    if (result == BT_L2CAP_LE_SUCCESS ||
-        result == BT_L2CAP_LE_ERR_AUTHENTICATION ||
-        result == BT_L2CAP_LE_ERR_ENCRYPTION) {
-        chan = l2cap_lookup_ident(conn, ident);
-    } else {
-        chan = l2cap_remove_ident(conn, ident);
-    }
+  /* Keep the channel in case of security errors */
+  if (result == BT_L2CAP_LE_SUCCESS || result == BT_L2CAP_LE_ERR_AUTHENTICATION || result == BT_L2CAP_LE_ERR_ENCRYPTION) {
+    chan = l2cap_lookup_ident(conn, ident);
+  } else {
+    chan = l2cap_remove_ident(conn, ident);
+  }
 
-    if (!chan) {
-        BT_ERR("Cannot find channel for ident %u", ident);
-        return;
-    }
+  if (!chan) {
+    BT_ERR("Cannot find channel for ident %u", ident);
+    return;
+  }
 
-    /* Cancel RTX work */
-    k_delayed_work_cancel(&chan->chan.rtx_work);
+  /* Cancel RTX work */
+  k_delayed_work_cancel(&chan->chan.rtx_work);
 
-    /* Reset ident since it got a response */
-    chan->chan.ident = 0U;
+  /* Reset ident since it got a response */
+  chan->chan.ident = 0U;
 
-    switch (result) {
-        case BT_L2CAP_LE_SUCCESS:
-            chan->tx.cid = dcid;
-            chan->tx.mtu = mtu;
-            chan->tx.mps = mps;
+  switch (result) {
+  case BT_L2CAP_LE_SUCCESS:
+    chan->tx.cid = dcid;
+    chan->tx.mtu = mtu;
+    chan->tx.mps = mps;
 
-            /* Update state */
-            bt_l2cap_chan_set_state(&chan->chan, BT_L2CAP_CONNECTED);
+    /* Update state */
+    bt_l2cap_chan_set_state(&chan->chan, BT_L2CAP_CONNECTED);
 
-            if (chan->chan.ops->connected) {
-                chan->chan.ops->connected(&chan->chan);
-            }
+    if (chan->chan.ops->connected) {
+      chan->chan.ops->connected(&chan->chan);
+    }
 
-            /* Give credits */
-            l2cap_chan_tx_give_credits(chan, credits);
-            l2cap_chan_rx_give_credits(chan, chan->rx.init_credits);
+    /* Give credits */
+    l2cap_chan_tx_give_credits(chan, credits);
+    l2cap_chan_rx_give_credits(chan, chan->rx.init_credits);
 
-            break;
-        case BT_L2CAP_LE_ERR_AUTHENTICATION:
-        case BT_L2CAP_LE_ERR_ENCRYPTION:
+    break;
+  case BT_L2CAP_LE_ERR_AUTHENTICATION:
+  case BT_L2CAP_LE_ERR_ENCRYPTION:
 #if defined(CONFIG_BT_SMP)
-            /* If security needs changing wait it to be completed */
-            if (l2cap_change_security(chan, result) == 0) {
-                return;
-            }
-#endif
-            bt_l2cap_chan_remove(conn, &chan->chan);
-            __attribute__((fallthrough));
-        default:
-            bt_l2cap_chan_del(&chan->chan);
+    /* If security needs changing wait it to be completed */
+    if (l2cap_change_security(chan, result) == 0) {
+      return;
     }
+#endif
+    bt_l2cap_chan_remove(conn, &chan->chan);
+    __attribute__((fallthrough));
+  default:
+    bt_l2cap_chan_del(&chan->chan);
+  }
 }
 
-static void le_disconn_rsp(struct bt_l2cap *l2cap, u8_t ident,
-                           struct net_buf *buf)
-{
-    struct bt_conn *conn = l2cap->chan.chan.conn;
-    struct bt_l2cap_le_chan *chan;
-    struct bt_l2cap_disconn_rsp *rsp = (void *)buf->data;
-    u16_t scid;
+static void le_disconn_rsp(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) {
+  struct bt_conn              *conn = l2cap->chan.chan.conn;
+  struct bt_l2cap_le_chan     *chan;
+  struct bt_l2cap_disconn_rsp *rsp = (void *)buf->data;
+  u16_t                        scid;
 
-    if (buf->len < sizeof(*rsp)) {
-        BT_ERR("Too small LE disconn rsp packet size");
-        return;
-    }
+  if (buf->len < sizeof(*rsp)) {
+    BT_ERR("Too small LE disconn rsp packet size");
+    return;
+  }
 
-    scid = sys_le16_to_cpu(rsp->scid);
+  scid = sys_le16_to_cpu(rsp->scid);
 
-    BT_DBG("dcid 0x%04x scid 0x%04x", sys_le16_to_cpu(rsp->dcid), scid);
+  BT_DBG("dcid 0x%04x scid 0x%04x", sys_le16_to_cpu(rsp->dcid), scid);
 
-    chan = l2cap_remove_rx_cid(conn, scid);
-    if (!chan) {
-        return;
-    }
+  chan = l2cap_remove_rx_cid(conn, scid);
+  if (!chan) {
+    return;
+  }
 
-    bt_l2cap_chan_del(&chan->chan);
+  bt_l2cap_chan_del(&chan->chan);
 }
 
-static inline struct net_buf *l2cap_alloc_seg(struct net_buf *buf)
-{
-    struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
-    struct net_buf *seg;
+static inline struct net_buf *l2cap_alloc_seg(struct net_buf *buf) {
+  struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
+  struct net_buf      *seg;
 
-    /* Try to use original pool if possible */
-    seg = net_buf_alloc(pool, K_NO_WAIT);
-    if (seg) {
-        net_buf_reserve(seg, BT_L2CAP_CHAN_SEND_RESERVE);
-        return seg;
-    }
+  /* Try to use original pool if possible */
+  seg = net_buf_alloc(pool, K_NO_WAIT);
+  if (seg) {
+    net_buf_reserve(seg, BT_L2CAP_CHAN_SEND_RESERVE);
+    return seg;
+  }
 
-    /* Fallback to using global connection tx pool */
-    return bt_l2cap_create_pdu(NULL, 0);
+  /* Fallback to using global connection tx pool */
+  return bt_l2cap_create_pdu(NULL, 0);
 }
 
-static struct net_buf *l2cap_chan_create_seg(struct bt_l2cap_le_chan *ch,
-                                             struct net_buf *buf,
-                                             size_t sdu_hdr_len)
-{
-    struct net_buf *seg;
-    u16_t headroom;
-    u16_t len;
+static struct net_buf *l2cap_chan_create_seg(struct bt_l2cap_le_chan *ch, struct net_buf *buf, size_t sdu_hdr_len) {
+  struct net_buf *seg;
+  u16_t           headroom;
+  u16_t           len;
 
-    /* Segment if data (+ data headroom) is bigger than MPS */
-    if (buf->len + sdu_hdr_len > ch->tx.mps) {
-        goto segment;
-    }
+  /* Segment if data (+ data headroom) is bigger than MPS */
+  if (buf->len + sdu_hdr_len > ch->tx.mps) {
+    goto segment;
+  }
+
+  headroom = BT_L2CAP_CHAN_SEND_RESERVE + sdu_hdr_len;
 
-    headroom = BT_L2CAP_CHAN_SEND_RESERVE + sdu_hdr_len;
-
-    /* Check if original buffer has enough headroom and don't have any
-	 * fragments.
-	 */
-    if (net_buf_headroom(buf) >= headroom && !buf->frags) {
-        if (sdu_hdr_len) {
-            /* Push SDU length if set */
-            net_buf_push_le16(buf, net_buf_frags_len(buf));
-        }
-        return net_buf_ref(buf);
+  /* Check if original buffer has enough headroom and don't have any
+   * fragments.
+   */
+  if (net_buf_headroom(buf) >= headroom && !buf->frags) {
+    if (sdu_hdr_len) {
+      /* Push SDU length if set */
+      net_buf_push_le16(buf, net_buf_frags_len(buf));
     }
+    return net_buf_ref(buf);
+  }
 
 segment:
-    seg = l2cap_alloc_seg(buf);
-    if (!seg) {
-        return NULL;
-    }
+  seg = l2cap_alloc_seg(buf);
+  if (!seg) {
+    return NULL;
+  }
 
-    if (sdu_hdr_len) {
-        net_buf_add_le16(seg, net_buf_frags_len(buf));
-    }
+  if (sdu_hdr_len) {
+    net_buf_add_le16(seg, net_buf_frags_len(buf));
+  }
 
-    /* Don't send more that TX MPS including SDU length */
-    len = MIN(net_buf_tailroom(seg), ch->tx.mps - sdu_hdr_len);
-    /* Limit if original buffer is smaller than the segment */
-    len = MIN(buf->len, len);
-    net_buf_add_mem(seg, buf->data, len);
-    net_buf_pull(buf, len);
+  /* Don't send more that TX MPS including SDU length */
+  len = MIN(net_buf_tailroom(seg), ch->tx.mps - sdu_hdr_len);
+  /* Limit if original buffer is smaller than the segment */
+  len = MIN(buf->len, len);
+  net_buf_add_mem(seg, buf->data, len);
+  net_buf_pull(buf, len);
 
-    BT_DBG("ch %p seg %p len %u", ch, seg, seg->len);
+  BT_DBG("ch %p seg %p len %u", ch, seg, seg->len);
 
-    return seg;
+  return seg;
 }
 
-void l2cap_chan_sdu_sent(struct bt_conn *conn, void *user_data)
-{
-    struct bt_l2cap_chan *chan = user_data;
+void l2cap_chan_sdu_sent(struct bt_conn *conn, void *user_data) {
+  struct bt_l2cap_chan *chan = user_data;
 
-    BT_DBG("conn %p chan %p", conn, chan);
+  BT_DBG("conn %p chan %p", conn, chan);
 
-    if (chan->ops->sent) {
-        chan->ops->sent(chan);
-    }
+  if (chan->ops->sent) {
+    chan->ops->sent(chan);
+  }
 }
 
-static int l2cap_chan_le_send(struct bt_l2cap_le_chan *ch, struct net_buf *buf,
-                              u16_t sdu_hdr_len)
-{
-    struct net_buf *seg;
-    int len;
+static int l2cap_chan_le_send(struct bt_l2cap_le_chan *ch, struct net_buf *buf, u16_t sdu_hdr_len) {
+  struct net_buf *seg;
+  int             len;
 
-    /* Wait for credits */
-    if (k_sem_take(&ch->tx.credits, K_NO_WAIT)) {
-        BT_DBG("No credits to transmit packet");
-        return -EAGAIN;
-    }
+  /* Wait for credits */
+  if (k_sem_take(&ch->tx.credits, K_NO_WAIT)) {
+    BT_DBG("No credits to transmit packet");
+    return -EAGAIN;
+  }
 
-    seg = l2cap_chan_create_seg(ch, buf, sdu_hdr_len);
-    if (!seg) {
-        return -ENOMEM;
-    }
+  seg = l2cap_chan_create_seg(ch, buf, sdu_hdr_len);
+  if (!seg) {
+    return -ENOMEM;
+  }
 
-    /* Channel may have been disconnected while waiting for a buffer */
-    if (!ch->chan.conn) {
-        net_buf_unref(buf);
-        return -ECONNRESET;
-    }
+  /* Channel may have been disconnected while waiting for a buffer */
+  if (!ch->chan.conn) {
+    net_buf_unref(buf);
+    return -ECONNRESET;
+  }
 
-    BT_DBG("ch %p cid 0x%04x len %u credits %u", ch, ch->tx.cid,
-           seg->len, k_sem_count_get(&ch->tx.credits));
+  BT_DBG("ch %p cid 0x%04x len %u credits %u", ch, ch->tx.cid, seg->len, k_sem_count_get(&ch->tx.credits));
 
-    len = seg->len - sdu_hdr_len;
+  len = seg->len - sdu_hdr_len;
 
-    /* Set a callback if there is no data left in the buffer and sent
-	 * callback has been set.
-	 */
-    if ((buf == seg || !buf->len) && ch->chan.ops->sent) {
-        bt_l2cap_send_cb(ch->chan.conn, ch->tx.cid, seg,
-                         l2cap_chan_sdu_sent, &ch->chan);
-    } else {
-        bt_l2cap_send(ch->chan.conn, ch->tx.cid, seg);
-    }
+  /* Set a callback if there is no data left in the buffer and sent
+   * callback has been set.
+   */
+  if ((buf == seg || !buf->len) && ch->chan.ops->sent) {
+    bt_l2cap_send_cb(ch->chan.conn, ch->tx.cid, seg, l2cap_chan_sdu_sent, &ch->chan);
+  } else {
+    bt_l2cap_send(ch->chan.conn, ch->tx.cid, seg);
+  }
 
-    /* Check if there is no credits left clear output status and notify its
-	 * change.
-	 */
-    if (!k_sem_count_get(&ch->tx.credits)) {
-        atomic_clear_bit(ch->chan.status, BT_L2CAP_STATUS_OUT);
-        if (ch->chan.ops->status) {
-            ch->chan.ops->status(&ch->chan, ch->chan.status);
-        }
+  /* Check if there is no credits left clear output status and notify its
+   * change.
+   */
+  if (!k_sem_count_get(&ch->tx.credits)) {
+    atomic_clear_bit(ch->chan.status, BT_L2CAP_STATUS_OUT);
+    if (ch->chan.ops->status) {
+      ch->chan.ops->status(&ch->chan, ch->chan.status);
     }
+  }
 
-    return len;
+  return len;
 }
 
-static int l2cap_chan_le_send_sdu(struct bt_l2cap_le_chan *ch,
-                                  struct net_buf **buf, u16_t sent)
-{
-    int ret, total_len;
-    struct net_buf *frag;
+static int l2cap_chan_le_send_sdu(struct bt_l2cap_le_chan *ch, struct net_buf **buf, u16_t sent) {
+  int             ret, total_len;
+  struct net_buf *frag;
 
-    total_len = net_buf_frags_len(*buf) + sent;
+  total_len = net_buf_frags_len(*buf) + sent;
 
-    if (total_len > ch->tx.mtu) {
-        return -EMSGSIZE;
-    }
+  if (total_len > ch->tx.mtu) {
+    return -EMSGSIZE;
+  }
 
-    frag = *buf;
-    if (!frag->len && frag->frags) {
-        frag = frag->frags;
+  frag = *buf;
+  if (!frag->len && frag->frags) {
+    frag = frag->frags;
+  }
+
+  if (!sent) {
+    /* Add SDU length for the first segment */
+    ret = l2cap_chan_le_send(ch, frag, BT_L2CAP_SDU_HDR_LEN);
+    if (ret < 0) {
+      if (ret == -EAGAIN) {
+        /* Store sent data into user_data */
+        memcpy(net_buf_user_data(frag), &sent, sizeof(sent));
+      }
+      *buf = frag;
+      return ret;
     }
+    sent = ret;
+  }
 
-    if (!sent) {
-        /* Add SDU length for the first segment */
-        ret = l2cap_chan_le_send(ch, frag, BT_L2CAP_SDU_HDR_LEN);
-        if (ret < 0) {
-            if (ret == -EAGAIN) {
-                /* Store sent data into user_data */
-                memcpy(net_buf_user_data(frag), &sent,
-                       sizeof(sent));
-            }
-            *buf = frag;
-            return ret;
-        }
-        sent = ret;
+  /* Send remaining segments */
+  for (ret = 0; sent < total_len; sent += ret) {
+    /* Proceed to next fragment */
+    if (!frag->len) {
+      frag = net_buf_frag_del(NULL, frag);
     }
 
-    /* Send remaining segments */
-    for (ret = 0; sent < total_len; sent += ret) {
-        /* Proceed to next fragment */
-        if (!frag->len) {
-            frag = net_buf_frag_del(NULL, frag);
-        }
-
-        ret = l2cap_chan_le_send(ch, frag, 0);
-        if (ret < 0) {
-            if (ret == -EAGAIN) {
-                /* Store sent data into user_data */
-                memcpy(net_buf_user_data(frag), &sent,
-                       sizeof(sent));
-            }
-            *buf = frag;
-            return ret;
-        }
+    ret = l2cap_chan_le_send(ch, frag, 0);
+    if (ret < 0) {
+      if (ret == -EAGAIN) {
+        /* Store sent data into user_data */
+        memcpy(net_buf_user_data(frag), &sent, sizeof(sent));
+      }
+      *buf = frag;
+      return ret;
     }
+  }
 
-    BT_DBG("ch %p cid 0x%04x sent %u total_len %u", ch, ch->tx.cid, sent,
-           total_len);
+  BT_DBG("ch %p cid 0x%04x sent %u total_len %u", ch, ch->tx.cid, sent, total_len);
 
-    net_buf_unref(frag);
+  net_buf_unref(frag);
 
-    return ret;
+  return ret;
 }
 
-static struct net_buf *l2cap_chan_le_get_tx_buf(struct bt_l2cap_le_chan *ch)
-{
-    struct net_buf *buf;
+static struct net_buf *l2cap_chan_le_get_tx_buf(struct bt_l2cap_le_chan *ch) {
+  struct net_buf *buf;
 
-    /* Return current buffer */
-    if (ch->tx_buf) {
-        buf = ch->tx_buf;
-        ch->tx_buf = NULL;
-        return buf;
-    }
+  /* Return current buffer */
+  if (ch->tx_buf) {
+    buf        = ch->tx_buf;
+    ch->tx_buf = NULL;
+    return buf;
+  }
 
-    return net_buf_get(&ch->tx_queue, K_NO_WAIT);
+  return net_buf_get(&ch->tx_queue, K_NO_WAIT);
 }
 
-static void l2cap_chan_le_send_resume(struct bt_l2cap_le_chan *ch)
-{
-    struct net_buf *buf;
+static void l2cap_chan_le_send_resume(struct bt_l2cap_le_chan *ch) {
+  struct net_buf *buf;
 
-    /* Resume tx in case there are buffers in the queue */
-    while ((buf = l2cap_chan_le_get_tx_buf(ch))) {
+  /* Resume tx in case there are buffers in the queue */
+  while ((buf = l2cap_chan_le_get_tx_buf(ch))) {
 #if defined(BFLB_BLE)
-        int sent = *((int *)net_buf_user_data(buf));
+    int sent = *((int *)net_buf_user_data(buf));
 #else
-        u16_t sent = *((u16_t *)net_buf_user_data(buf));
+    u16_t sent = *((u16_t *)net_buf_user_data(buf));
 #endif
 
-        BT_DBG("buf %p sent %u", buf, sent);
+    BT_DBG("buf %p sent %u", buf, sent);
 
-        sent = l2cap_chan_le_send_sdu(ch, &buf, sent);
-        if (sent < 0) {
-            if (sent == -EAGAIN) {
-                ch->tx_buf = buf;
-            }
-            break;
-        }
+    sent = l2cap_chan_le_send_sdu(ch, &buf, sent);
+    if (sent < 0) {
+      if (sent == -EAGAIN) {
+        ch->tx_buf = buf;
+      }
+      break;
     }
+  }
 }
 
-static void le_credits(struct bt_l2cap *l2cap, u8_t ident,
-                       struct net_buf *buf)
-{
-    struct bt_conn *conn = l2cap->chan.chan.conn;
-    struct bt_l2cap_chan *chan;
-    struct bt_l2cap_le_credits *ev = (void *)buf->data;
-    struct bt_l2cap_le_chan *ch;
-    u16_t credits, cid;
+static void le_credits(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) {
+  struct bt_conn             *conn = l2cap->chan.chan.conn;
+  struct bt_l2cap_chan       *chan;
+  struct bt_l2cap_le_credits *ev = (void *)buf->data;
+  struct bt_l2cap_le_chan    *ch;
+  u16_t                       credits, cid;
 
-    if (buf->len < sizeof(*ev)) {
-        BT_ERR("Too small LE Credits packet size");
-        return;
-    }
+  if (buf->len < sizeof(*ev)) {
+    BT_ERR("Too small LE Credits packet size");
+    return;
+  }
 
-    cid = sys_le16_to_cpu(ev->cid);
-    credits = sys_le16_to_cpu(ev->credits);
+  cid     = sys_le16_to_cpu(ev->cid);
+  credits = sys_le16_to_cpu(ev->credits);
 
-    BT_DBG("cid 0x%04x credits %u", cid, credits);
+  BT_DBG("cid 0x%04x credits %u", cid, credits);
 
-    chan = bt_l2cap_le_lookup_tx_cid(conn, cid);
-    if (!chan) {
-        BT_ERR("Unable to find channel of LE Credits packet");
-        return;
-    }
+  chan = bt_l2cap_le_lookup_tx_cid(conn, cid);
+  if (!chan) {
+    BT_ERR("Unable to find channel of LE Credits packet");
+    return;
+  }
 
-    ch = BT_L2CAP_LE_CHAN(chan);
+  ch = BT_L2CAP_LE_CHAN(chan);
 
-    if (k_sem_count_get(&ch->tx.credits) + credits > UINT16_MAX) {
-        BT_ERR("Credits overflow");
-        bt_l2cap_chan_disconnect(chan);
-        return;
-    }
+  if (k_sem_count_get(&ch->tx.credits) + credits > UINT16_MAX) {
+    BT_ERR("Credits overflow");
+    bt_l2cap_chan_disconnect(chan);
+    return;
+  }
 
-    l2cap_chan_tx_give_credits(ch, credits);
+  l2cap_chan_tx_give_credits(ch, credits);
 
-    BT_DBG("chan %p total credits %u", ch,
-           k_sem_count_get(&ch->tx.credits));
+  BT_DBG("chan %p total credits %u", ch, k_sem_count_get(&ch->tx.credits));
 
-    l2cap_chan_le_send_resume(ch);
+  l2cap_chan_le_send_resume(ch);
 }
 
-static void reject_cmd(struct bt_l2cap *l2cap, u8_t ident,
-                       struct net_buf *buf)
-{
-    struct bt_conn *conn = l2cap->chan.chan.conn;
-    struct bt_l2cap_le_chan *chan;
+static void reject_cmd(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) {
+  struct bt_conn          *conn = l2cap->chan.chan.conn;
+  struct bt_l2cap_le_chan *chan;
 
-    /* Check if there is a outstanding channel */
-    chan = l2cap_remove_ident(conn, ident);
-    if (!chan) {
-        return;
-    }
+  /* Check if there is a outstanding channel */
+  chan = l2cap_remove_ident(conn, ident);
+  if (!chan) {
+    return;
+  }
 
-    bt_l2cap_chan_del(&chan->chan);
+  bt_l2cap_chan_del(&chan->chan);
 }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-static int l2cap_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
-    struct bt_l2cap *l2cap = CONTAINER_OF(chan, struct bt_l2cap, chan);
-    struct bt_l2cap_sig_hdr *hdr;
-    u16_t len;
+static int l2cap_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) {
+  struct bt_l2cap         *l2cap = CONTAINER_OF(chan, struct bt_l2cap, chan);
+  struct bt_l2cap_sig_hdr *hdr;
+  u16_t                    len;
 
-    if (buf->len < sizeof(*hdr)) {
-        BT_ERR("Too small L2CAP signaling PDU");
-        return 0;
-    }
+  if (buf->len < sizeof(*hdr)) {
+    BT_ERR("Too small L2CAP signaling PDU");
+    return 0;
+  }
 
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    len = sys_le16_to_cpu(hdr->len);
+  hdr = net_buf_pull_mem(buf, sizeof(*hdr));
+  len = sys_le16_to_cpu(hdr->len);
 
-    BT_DBG("Signaling code 0x%02x ident %u len %u", hdr->code,
-           hdr->ident, len);
+  BT_DBG("Signaling code 0x%02x ident %u len %u", hdr->code, hdr->ident, len);
 
-    if (buf->len != len) {
-        BT_ERR("L2CAP length mismatch (%u != %u)", buf->len, len);
-        return 0;
-    }
+  if (buf->len != len) {
+    BT_ERR("L2CAP length mismatch (%u != %u)", buf->len, len);
+    return 0;
+  }
 
-    if (!hdr->ident) {
-        BT_ERR("Invalid ident value in L2CAP PDU");
-        return 0;
-    }
+  if (!hdr->ident) {
+    BT_ERR("Invalid ident value in L2CAP PDU");
+    return 0;
+  }
 
-    switch (hdr->code) {
-        case BT_L2CAP_CONN_PARAM_RSP:
-            le_conn_param_rsp(l2cap, buf);
-            break;
+  switch (hdr->code) {
+  case BT_L2CAP_CONN_PARAM_RSP:
+    le_conn_param_rsp(l2cap, buf);
+    break;
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-        case BT_L2CAP_LE_CONN_REQ:
-            le_conn_req(l2cap, hdr->ident, buf);
-            break;
-        case BT_L2CAP_LE_CONN_RSP:
-            le_conn_rsp(l2cap, hdr->ident, buf);
-            break;
-        case BT_L2CAP_DISCONN_REQ:
-            le_disconn_req(l2cap, hdr->ident, buf);
-            break;
-        case BT_L2CAP_DISCONN_RSP:
-            le_disconn_rsp(l2cap, hdr->ident, buf);
-            break;
-        case BT_L2CAP_LE_CREDITS:
-            le_credits(l2cap, hdr->ident, buf);
-            break;
-        case BT_L2CAP_CMD_REJECT:
-            reject_cmd(l2cap, hdr->ident, buf);
-            break;
+  case BT_L2CAP_LE_CONN_REQ:
+    le_conn_req(l2cap, hdr->ident, buf);
+    break;
+  case BT_L2CAP_LE_CONN_RSP:
+    le_conn_rsp(l2cap, hdr->ident, buf);
+    break;
+  case BT_L2CAP_DISCONN_REQ:
+    le_disconn_req(l2cap, hdr->ident, buf);
+    break;
+  case BT_L2CAP_DISCONN_RSP:
+    le_disconn_rsp(l2cap, hdr->ident, buf);
+    break;
+  case BT_L2CAP_LE_CREDITS:
+    le_credits(l2cap, hdr->ident, buf);
+    break;
+  case BT_L2CAP_CMD_REJECT:
+    reject_cmd(l2cap, hdr->ident, buf);
+    break;
 #else
-        case BT_L2CAP_CMD_REJECT:
-            /* Ignored */
-            break;
+  case BT_L2CAP_CMD_REJECT:
+    /* Ignored */
+    break;
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
-        case BT_L2CAP_CONN_PARAM_REQ:
-            if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
-                le_conn_param_update_req(l2cap, hdr->ident, buf);
-                break;
-            }
+  case BT_L2CAP_CONN_PARAM_REQ:
+    if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
+      le_conn_param_update_req(l2cap, hdr->ident, buf);
+      break;
+    }
 #if defined(BFLB_BLE)
-            __attribute__((fallthrough));
+    __attribute__((fallthrough));
 #endif
 
-        /* Fall-through */
-        default:
-            BT_WARN("Unknown L2CAP PDU code 0x%02x", hdr->code);
-            l2cap_send_reject(chan->conn, hdr->ident,
-                              BT_L2CAP_REJ_NOT_UNDERSTOOD, NULL, 0);
-            break;
-    }
+  /* Fall-through */
+  default:
+    BT_WARN("Unknown L2CAP PDU code 0x%02x", hdr->code);
+    l2cap_send_reject(chan->conn, hdr->ident, BT_L2CAP_REJ_NOT_UNDERSTOOD, NULL, 0);
+    break;
+  }
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-static void l2cap_chan_send_credits(struct bt_l2cap_le_chan *chan,
-                                    struct net_buf *buf, u16_t credits)
-{
-    struct bt_l2cap_le_credits *ev;
-
-    /* Cap the number of credits given */
-    if (credits > chan->rx.init_credits) {
-        credits = chan->rx.init_credits;
-    }
+static void l2cap_chan_send_credits(struct bt_l2cap_le_chan *chan, struct net_buf *buf, u16_t credits) {
+  struct bt_l2cap_le_credits *ev;
 
-    l2cap_chan_rx_give_credits(chan, credits);
+  /* Cap the number of credits given */
+  if (credits > chan->rx.init_credits) {
+    credits = chan->rx.init_credits;
+  }
 
-    buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CREDITS, get_ident(),
-                                  sizeof(*ev));
-    if (!buf) {
-        return;
-    }
+  l2cap_chan_rx_give_credits(chan, credits);
+
+  buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CREDITS, get_ident(), sizeof(*ev));
+  if (!buf) {
+    return;
+  }
 
-    ev = net_buf_add(buf, sizeof(*ev));
-    ev->cid = sys_cpu_to_le16(chan->rx.cid);
-    ev->credits = sys_cpu_to_le16(credits);
+  ev          = net_buf_add(buf, sizeof(*ev));
+  ev->cid     = sys_cpu_to_le16(chan->rx.cid);
+  ev->credits = sys_cpu_to_le16(credits);
 
-    bt_l2cap_send(chan->chan.conn, BT_L2CAP_CID_LE_SIG, buf);
+  bt_l2cap_send(chan->chan.conn, BT_L2CAP_CID_LE_SIG, buf);
 
-    BT_DBG("chan %p credits %u", chan, k_sem_count_get(&chan->rx.credits));
+  BT_DBG("chan %p credits %u", chan, k_sem_count_get(&chan->rx.credits));
 }
 
-static void l2cap_chan_update_credits(struct bt_l2cap_le_chan *chan,
-                                      struct net_buf *buf)
-{
-    s16_t credits;
+static void l2cap_chan_update_credits(struct bt_l2cap_le_chan *chan, struct net_buf *buf) {
+  s16_t credits;
 
-    /* Restore enough credits to complete the sdu */
-    credits = ((chan->_sdu_len - net_buf_frags_len(buf)) +
-               (chan->rx.mps - 1)) /
-              chan->rx.mps;
-    credits -= k_sem_count_get(&chan->rx.credits);
-    if (credits <= 0) {
-        return;
-    }
+  /* Restore enough credits to complete the sdu */
+  credits = ((chan->_sdu_len - net_buf_frags_len(buf)) + (chan->rx.mps - 1)) / chan->rx.mps;
+  credits -= k_sem_count_get(&chan->rx.credits);
+  if (credits <= 0) {
+    return;
+  }
 
-    l2cap_chan_send_credits(chan, buf, credits);
+  l2cap_chan_send_credits(chan, buf, credits);
 }
 
-int bt_l2cap_chan_recv_complete(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
-    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
-    struct bt_conn *conn = chan->conn;
-    u16_t credits;
+int bt_l2cap_chan_recv_complete(struct bt_l2cap_chan *chan, struct net_buf *buf) {
+  struct bt_l2cap_le_chan *ch   = BT_L2CAP_LE_CHAN(chan);
+  struct bt_conn          *conn = chan->conn;
+  u16_t                    credits;
 
-    __ASSERT_NO_MSG(chan);
-    __ASSERT_NO_MSG(buf);
+  __ASSERT_NO_MSG(chan);
+  __ASSERT_NO_MSG(buf);
 
-    if (!conn) {
-        return -ENOTCONN;
-    }
+  if (!conn) {
+    return -ENOTCONN;
+  }
 
-    if (conn->type != BT_CONN_TYPE_LE) {
-        return -ENOTSUP;
-    }
+  if (conn->type != BT_CONN_TYPE_LE) {
+    return -ENOTSUP;
+  }
 
-    BT_DBG("chan %p buf %p", chan, buf);
+  BT_DBG("chan %p buf %p", chan, buf);
 
-    /* Restore credits used by packet */
-    memcpy(&credits, net_buf_user_data(buf), sizeof(credits));
+  /* Restore credits used by packet */
+  memcpy(&credits, net_buf_user_data(buf), sizeof(credits));
 
-    l2cap_chan_send_credits(ch, buf, credits);
+  l2cap_chan_send_credits(ch, buf, credits);
 
-    net_buf_unref(buf);
+  net_buf_unref(buf);
 
-    return 0;
+  return 0;
 }
 
-static struct net_buf *l2cap_alloc_frag(s32_t timeout, void *user_data)
-{
-    struct bt_l2cap_le_chan *chan = user_data;
-    struct net_buf *frag = NULL;
+static struct net_buf *l2cap_alloc_frag(s32_t timeout, void *user_data) {
+  struct bt_l2cap_le_chan *chan = user_data;
+  struct net_buf          *frag = NULL;
 
-    frag = chan->chan.ops->alloc_buf(&chan->chan);
-    if (!frag) {
-        return NULL;
-    }
+  frag = chan->chan.ops->alloc_buf(&chan->chan);
+  if (!frag) {
+    return NULL;
+  }
 
-    BT_DBG("frag %p tailroom %zu", frag, net_buf_tailroom(frag));
+  BT_DBG("frag %p tailroom %zu", frag, net_buf_tailroom(frag));
 
-    return frag;
+  return frag;
 }
 
-static void l2cap_chan_le_recv_sdu(struct bt_l2cap_le_chan *chan,
-                                   struct net_buf *buf, u16_t seg)
-{
-    int err;
+static void l2cap_chan_le_recv_sdu(struct bt_l2cap_le_chan *chan, struct net_buf *buf, u16_t seg) {
+  int err;
 
-    BT_DBG("chan %p len %zu", chan, net_buf_frags_len(buf));
+  BT_DBG("chan %p len %zu", chan, net_buf_frags_len(buf));
 
-    /* Receiving complete SDU, notify channel and reset SDU buf */
-    err = chan->chan.ops->recv(&chan->chan, buf);
-    if (err < 0) {
-        if (err != -EINPROGRESS) {
-            BT_ERR("err %d", err);
-            bt_l2cap_chan_disconnect(&chan->chan);
-            net_buf_unref(buf);
-        }
-        return;
+  /* Receiving complete SDU, notify channel and reset SDU buf */
+  err = chan->chan.ops->recv(&chan->chan, buf);
+  if (err < 0) {
+    if (err != -EINPROGRESS) {
+      BT_ERR("err %d", err);
+      bt_l2cap_chan_disconnect(&chan->chan);
+      net_buf_unref(buf);
     }
+    return;
+  }
 
-    l2cap_chan_send_credits(chan, buf, seg);
-    net_buf_unref(buf);
+  l2cap_chan_send_credits(chan, buf, seg);
+  net_buf_unref(buf);
 }
 
-static void l2cap_chan_le_recv_seg(struct bt_l2cap_le_chan *chan,
-                                   struct net_buf *buf)
-{
-    u16_t len;
-    u16_t seg = 0U;
+static void l2cap_chan_le_recv_seg(struct bt_l2cap_le_chan *chan, struct net_buf *buf) {
+  u16_t len;
+  u16_t seg = 0U;
 
-    len = net_buf_frags_len(chan->_sdu);
-    if (len) {
-        memcpy(&seg, net_buf_user_data(chan->_sdu), sizeof(seg));
-    }
+  len = net_buf_frags_len(chan->_sdu);
+  if (len) {
+    memcpy(&seg, net_buf_user_data(chan->_sdu), sizeof(seg));
+  }
 
-    if (len + buf->len > chan->_sdu_len) {
-        BT_ERR("SDU length mismatch");
-        bt_l2cap_chan_disconnect(&chan->chan);
-        return;
-    }
+  if (len + buf->len > chan->_sdu_len) {
+    BT_ERR("SDU length mismatch");
+    bt_l2cap_chan_disconnect(&chan->chan);
+    return;
+  }
 
-    seg++;
-    /* Store received segments in user_data */
-    memcpy(net_buf_user_data(chan->_sdu), &seg, sizeof(seg));
+  seg++;
+  /* Store received segments in user_data */
+  memcpy(net_buf_user_data(chan->_sdu), &seg, sizeof(seg));
 
-    BT_DBG("chan %p seg %d len %zu", chan, seg, net_buf_frags_len(buf));
+  BT_DBG("chan %p seg %d len %zu", chan, seg, net_buf_frags_len(buf));
 
-    /* Append received segment to SDU */
-    len = net_buf_append_bytes(chan->_sdu, buf->len, buf->data, K_NO_WAIT,
-                               l2cap_alloc_frag, chan);
-    if (len != buf->len) {
-        BT_ERR("Unable to store SDU");
-        bt_l2cap_chan_disconnect(&chan->chan);
-        return;
-    }
+  /* Append received segment to SDU */
+  len = net_buf_append_bytes(chan->_sdu, buf->len, buf->data, K_NO_WAIT, l2cap_alloc_frag, chan);
+  if (len != buf->len) {
+    BT_ERR("Unable to store SDU");
+    bt_l2cap_chan_disconnect(&chan->chan);
+    return;
+  }
 
-    if (net_buf_frags_len(chan->_sdu) < chan->_sdu_len) {
-        /* Give more credits if remote has run out of them, this
-		 * should only happen if the remote cannot fully utilize the
-		 * MPS for some reason.
-		 */
-        if (!k_sem_count_get(&chan->rx.credits) &&
-            seg == chan->rx.init_credits) {
-            l2cap_chan_update_credits(chan, buf);
-        }
-        return;
+  if (net_buf_frags_len(chan->_sdu) < chan->_sdu_len) {
+    /* Give more credits if remote has run out of them, this
+     * should only happen if the remote cannot fully utilize the
+     * MPS for some reason.
+     */
+    if (!k_sem_count_get(&chan->rx.credits) && seg == chan->rx.init_credits) {
+      l2cap_chan_update_credits(chan, buf);
     }
+    return;
+  }
 
-    buf = chan->_sdu;
-    chan->_sdu = NULL;
-    chan->_sdu_len = 0U;
+  buf            = chan->_sdu;
+  chan->_sdu     = NULL;
+  chan->_sdu_len = 0U;
 
-    l2cap_chan_le_recv_sdu(chan, buf, seg);
+  l2cap_chan_le_recv_sdu(chan, buf, seg);
 }
 
-static void l2cap_chan_le_recv(struct bt_l2cap_le_chan *chan,
-                               struct net_buf *buf)
-{
-    u16_t sdu_len;
-    int err;
-
-    if (k_sem_take(&chan->rx.credits, K_NO_WAIT)) {
-        BT_ERR("No credits to receive packet");
-        bt_l2cap_chan_disconnect(&chan->chan);
-        return;
-    }
+static void l2cap_chan_le_recv(struct bt_l2cap_le_chan *chan, struct net_buf *buf) {
+  u16_t sdu_len;
+  int   err;
 
-    /* Check if segments already exist */
-    if (chan->_sdu) {
-        l2cap_chan_le_recv_seg(chan, buf);
-        return;
-    }
+  if (k_sem_take(&chan->rx.credits, K_NO_WAIT)) {
+    BT_ERR("No credits to receive packet");
+    bt_l2cap_chan_disconnect(&chan->chan);
+    return;
+  }
 
-    sdu_len = net_buf_pull_le16(buf);
+  /* Check if segments already exist */
+  if (chan->_sdu) {
+    l2cap_chan_le_recv_seg(chan, buf);
+    return;
+  }
 
-    BT_DBG("chan %p len %u sdu_len %u", chan, buf->len, sdu_len);
+  sdu_len = net_buf_pull_le16(buf);
 
-    if (sdu_len > chan->rx.mtu) {
-        BT_ERR("Invalid SDU length");
-        bt_l2cap_chan_disconnect(&chan->chan);
-        return;
-    }
+  BT_DBG("chan %p len %u sdu_len %u", chan, buf->len, sdu_len);
 
-    /* Always allocate buffer from the channel if supported. */
-    if (chan->chan.ops->alloc_buf) {
-        chan->_sdu = chan->chan.ops->alloc_buf(&chan->chan);
-        if (!chan->_sdu) {
-            BT_ERR("Unable to allocate buffer for SDU");
-            bt_l2cap_chan_disconnect(&chan->chan);
-            return;
-        }
-        chan->_sdu_len = sdu_len;
-        l2cap_chan_le_recv_seg(chan, buf);
-        return;
-    }
+  if (sdu_len > chan->rx.mtu) {
+    BT_ERR("Invalid SDU length");
+    bt_l2cap_chan_disconnect(&chan->chan);
+    return;
+  }
 
-    err = chan->chan.ops->recv(&chan->chan, buf);
-    if (err) {
-        if (err != -EINPROGRESS) {
-            BT_ERR("err %d", err);
-            bt_l2cap_chan_disconnect(&chan->chan);
-        }
-        return;
+  /* Always allocate buffer from the channel if supported. */
+  if (chan->chan.ops->alloc_buf) {
+    chan->_sdu = chan->chan.ops->alloc_buf(&chan->chan);
+    if (!chan->_sdu) {
+      BT_ERR("Unable to allocate buffer for SDU");
+      bt_l2cap_chan_disconnect(&chan->chan);
+      return;
+    }
+    chan->_sdu_len = sdu_len;
+    l2cap_chan_le_recv_seg(chan, buf);
+    return;
+  }
+
+  err = chan->chan.ops->recv(&chan->chan, buf);
+  if (err) {
+    if (err != -EINPROGRESS) {
+      BT_ERR("err %d", err);
+      bt_l2cap_chan_disconnect(&chan->chan);
     }
+    return;
+  }
 
-    l2cap_chan_send_credits(chan, buf, 1);
+  l2cap_chan_send_credits(chan, buf, 1);
 }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-static void l2cap_chan_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
+static void l2cap_chan_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) {
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
+  struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
 
-    if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) {
-        net_buf_put(&ch->rx_queue, net_buf_ref(buf));
-        k_work_submit(&ch->rx_work);
-        return;
-    }
+  if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) {
+    net_buf_put(&ch->rx_queue, net_buf_ref(buf));
+    k_work_submit(&ch->rx_work);
+    return;
+  }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-    BT_DBG("chan %p len %u", chan, buf->len);
+  BT_DBG("chan %p len %u", chan, buf->len);
 
-    chan->ops->recv(chan, buf);
-    net_buf_unref(buf);
+  chan->ops->recv(chan, buf);
+  net_buf_unref(buf);
 }
 
-void bt_l2cap_recv(struct bt_conn *conn, struct net_buf *buf)
-{
-    struct bt_l2cap_hdr *hdr;
-    struct bt_l2cap_chan *chan;
-    u16_t cid;
+void bt_l2cap_recv(struct bt_conn *conn, struct net_buf *buf) {
+  struct bt_l2cap_hdr  *hdr;
+  struct bt_l2cap_chan *chan;
+  u16_t                 cid;
 
-    if (IS_ENABLED(CONFIG_BT_BREDR) &&
-        conn->type == BT_CONN_TYPE_BR) {
-        bt_l2cap_br_recv(conn, buf);
-        return;
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
+    bt_l2cap_br_recv(conn, buf);
+    return;
+  }
 
-    if (buf->len < sizeof(*hdr)) {
-        BT_ERR("Too small L2CAP PDU received");
-        net_buf_unref(buf);
-        return;
-    }
+  if (buf->len < sizeof(*hdr)) {
+    BT_ERR("Too small L2CAP PDU received");
+    net_buf_unref(buf);
+    return;
+  }
 
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    cid = sys_le16_to_cpu(hdr->cid);
+  hdr = net_buf_pull_mem(buf, sizeof(*hdr));
+  cid = sys_le16_to_cpu(hdr->cid);
 
-    BT_DBG("Packet for CID %u len %u", cid, buf->len);
+  BT_DBG("Packet for CID %u len %u", cid, buf->len);
 
-    chan = bt_l2cap_le_lookup_rx_cid(conn, cid);
-    if (!chan) {
-        BT_WARN("Ignoring data for unknown CID 0x%04x", cid);
-        net_buf_unref(buf);
-        return;
-    }
+  chan = bt_l2cap_le_lookup_rx_cid(conn, cid);
+  if (!chan) {
+    BT_WARN("Ignoring data for unknown CID 0x%04x", cid);
+    net_buf_unref(buf);
+    return;
+  }
 
-    l2cap_chan_recv(chan, buf);
+  l2cap_chan_recv(chan, buf);
 }
 
-int bt_l2cap_update_conn_param(struct bt_conn *conn,
-                               const struct bt_le_conn_param *param)
-{
-    struct bt_l2cap_conn_param_req *req;
-    struct net_buf *buf;
+int bt_l2cap_update_conn_param(struct bt_conn *conn, const struct bt_le_conn_param *param) {
+  struct bt_l2cap_conn_param_req *req;
+  struct net_buf                 *buf;
 
-    buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CONN_PARAM_REQ,
-                                  get_ident(), sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CONN_PARAM_REQ, get_ident(), sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->min_interval = sys_cpu_to_le16(param->interval_min);
-    req->max_interval = sys_cpu_to_le16(param->interval_max);
-    req->latency = sys_cpu_to_le16(param->latency);
-    req->timeout = sys_cpu_to_le16(param->timeout);
+  req               = net_buf_add(buf, sizeof(*req));
+  req->min_interval = sys_cpu_to_le16(param->interval_min);
+  req->max_interval = sys_cpu_to_le16(param->interval_max);
+  req->latency      = sys_cpu_to_le16(param->latency);
+  req->timeout      = sys_cpu_to_le16(param->timeout);
 
-    bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
+  bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
 
-    return 0;
+  return 0;
 }
 
-static void l2cap_connected(struct bt_l2cap_chan *chan)
-{
-    BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan),
-           BT_L2CAP_LE_CHAN(chan)->rx.cid);
-}
+static void l2cap_connected(struct bt_l2cap_chan *chan) { BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan), BT_L2CAP_LE_CHAN(chan)->rx.cid); }
 
-static void l2cap_disconnected(struct bt_l2cap_chan *chan)
-{
-    BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan),
-           BT_L2CAP_LE_CHAN(chan)->rx.cid);
-}
+static void l2cap_disconnected(struct bt_l2cap_chan *chan) { BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan), BT_L2CAP_LE_CHAN(chan)->rx.cid); }
 
-static int l2cap_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan)
-{
-    int i;
-    static struct bt_l2cap_chan_ops ops = {
-        .connected = l2cap_connected,
-        .disconnected = l2cap_disconnected,
-        .recv = l2cap_recv,
-    };
+static int l2cap_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) {
+  int                             i;
+  static struct bt_l2cap_chan_ops ops = {
+      .connected    = l2cap_connected,
+      .disconnected = l2cap_disconnected,
+      .recv         = l2cap_recv,
+  };
 
-    BT_DBG("conn %p handle %u", conn, conn->handle);
+  BT_DBG("conn %p handle %u", conn, conn->handle);
 
-    for (i = 0; i < ARRAY_SIZE(bt_l2cap_pool); i++) {
-        struct bt_l2cap *l2cap = &bt_l2cap_pool[i];
+  for (i = 0; i < ARRAY_SIZE(bt_l2cap_pool); i++) {
+    struct bt_l2cap *l2cap = &bt_l2cap_pool[i];
 
-        if (l2cap->chan.chan.conn) {
-            continue;
-        }
+    if (l2cap->chan.chan.conn) {
+      continue;
+    }
 
-        l2cap->chan.chan.ops = &ops;
-        *chan = &l2cap->chan.chan;
+    l2cap->chan.chan.ops = &ops;
+    *chan                = &l2cap->chan.chan;
 
-        return 0;
-    }
+    return 0;
+  }
 
-    BT_ERR("No available L2CAP context for conn %p", conn);
+  BT_ERR("No available L2CAP context for conn %p", conn);
 
-    return -ENOMEM;
+  return -ENOMEM;
 }
 
 BT_L2CAP_CHANNEL_DEFINE(le_fixed_chan, BT_L2CAP_CID_LE_SIG, l2cap_accept);
 
-void bt_l2cap_init(void)
-{
+void bt_l2cap_init(void) {
 #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL)
-    static struct bt_l2cap_fixed_chan chan = {
-        .cid = BT_L2CAP_CID_LE_SIG,
-        .accept = l2cap_accept,
-    };
+  static struct bt_l2cap_fixed_chan chan = {
+      .cid    = BT_L2CAP_CID_LE_SIG,
+      .accept = l2cap_accept,
+  };
 
-    bt_l2cap_le_fixed_chan_register(&chan);
+  bt_l2cap_le_fixed_chan_register(&chan);
 #endif
-    if (IS_ENABLED(CONFIG_BT_BREDR)) {
-        bt_l2cap_br_init();
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR)) {
+    bt_l2cap_br_init();
+  }
 }
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-static int l2cap_le_connect(struct bt_conn *conn, struct bt_l2cap_le_chan *ch,
-                            u16_t psm)
-{
-    if (psm < L2CAP_LE_PSM_FIXED_START || psm > L2CAP_LE_PSM_DYN_END) {
-        return -EINVAL;
-    }
+static int l2cap_le_connect(struct bt_conn *conn, struct bt_l2cap_le_chan *ch, u16_t psm) {
+  if (psm < L2CAP_LE_PSM_FIXED_START || psm > L2CAP_LE_PSM_DYN_END) {
+    return -EINVAL;
+  }
 
-    l2cap_chan_tx_init(ch);
-    l2cap_chan_rx_init(ch);
+  l2cap_chan_tx_init(ch);
+  l2cap_chan_rx_init(ch);
 
-    if (!l2cap_chan_add(conn, &ch->chan, l2cap_chan_destroy)) {
-        return -ENOMEM;
-    }
+  if (!l2cap_chan_add(conn, &ch->chan, l2cap_chan_destroy)) {
+    return -ENOMEM;
+  }
 
-    ch->chan.psm = psm;
+  ch->chan.psm = psm;
 
-    return l2cap_le_conn_req(ch);
+  return l2cap_le_conn_req(ch);
 }
 
-int bt_l2cap_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan *chan,
-                          u16_t psm)
-{
-    BT_DBG("conn %p chan %p psm 0x%04x", conn, chan, psm);
+int bt_l2cap_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan *chan, u16_t psm) {
+  BT_DBG("conn %p chan %p psm 0x%04x", conn, chan, psm);
 
-    if (!conn || conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (!conn || conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    if (!chan) {
-        return -EINVAL;
-    }
+  if (!chan) {
+    return -EINVAL;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_BREDR) &&
-        conn->type == BT_CONN_TYPE_BR) {
-        return bt_l2cap_br_chan_connect(conn, chan, psm);
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
+    return bt_l2cap_br_chan_connect(conn, chan, psm);
+  }
 
-    if (chan->required_sec_level > BT_SECURITY_L4) {
-        return -EINVAL;
-    } else if (chan->required_sec_level == BT_SECURITY_L0) {
-        chan->required_sec_level = BT_SECURITY_L1;
-    }
+  if (chan->required_sec_level > BT_SECURITY_L4) {
+    return -EINVAL;
+  } else if (chan->required_sec_level == BT_SECURITY_L0) {
+    chan->required_sec_level = BT_SECURITY_L1;
+  }
 
-    return l2cap_le_connect(conn, BT_L2CAP_LE_CHAN(chan), psm);
+  return l2cap_le_connect(conn, BT_L2CAP_LE_CHAN(chan), psm);
 }
 
-int bt_l2cap_chan_disconnect(struct bt_l2cap_chan *chan)
-{
-    struct bt_conn *conn = chan->conn;
-    struct net_buf *buf;
-    struct bt_l2cap_disconn_req *req;
-    struct bt_l2cap_le_chan *ch;
+int bt_l2cap_chan_disconnect(struct bt_l2cap_chan *chan) {
+  struct bt_conn              *conn = chan->conn;
+  struct net_buf              *buf;
+  struct bt_l2cap_disconn_req *req;
+  struct bt_l2cap_le_chan     *ch;
 
-    if (!conn) {
-        return -ENOTCONN;
-    }
+  if (!conn) {
+    return -ENOTCONN;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_BREDR) &&
-        conn->type == BT_CONN_TYPE_BR) {
-        return bt_l2cap_br_chan_disconnect(chan);
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
+    return bt_l2cap_br_chan_disconnect(chan);
+  }
 
-    ch = BT_L2CAP_LE_CHAN(chan);
+  ch = BT_L2CAP_LE_CHAN(chan);
 
-    BT_DBG("chan %p scid 0x%04x dcid 0x%04x", chan, ch->rx.cid,
-           ch->tx.cid);
+  BT_DBG("chan %p scid 0x%04x dcid 0x%04x", chan, ch->rx.cid, ch->tx.cid);
 
-    ch->chan.ident = get_ident();
+  ch->chan.ident = get_ident();
 
-    buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_DISCONN_REQ,
-                                  ch->chan.ident, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_DISCONN_REQ, ch->chan.ident, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->dcid = sys_cpu_to_le16(ch->rx.cid);
-    req->scid = sys_cpu_to_le16(ch->tx.cid);
+  req       = net_buf_add(buf, sizeof(*req));
+  req->dcid = sys_cpu_to_le16(ch->rx.cid);
+  req->scid = sys_cpu_to_le16(ch->tx.cid);
 
-    l2cap_chan_send_req(ch, buf, L2CAP_DISC_TIMEOUT);
-    bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECT);
+  l2cap_chan_send_req(ch, buf, L2CAP_DISC_TIMEOUT);
+  bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECT);
 
-    return 0;
+  return 0;
 }
 
-int bt_l2cap_chan_send(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
-    int err;
+int bt_l2cap_chan_send(struct bt_l2cap_chan *chan, struct net_buf *buf) {
+  int err;
 
-    if (!buf) {
-        return -EINVAL;
-    }
+  if (!buf) {
+    return -EINVAL;
+  }
 
-    BT_DBG("chan %p buf %p len %zu", chan, buf, net_buf_frags_len(buf));
+  BT_DBG("chan %p buf %p len %zu", chan, buf, net_buf_frags_len(buf));
 
-    if (!chan->conn || chan->conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (!chan->conn || chan->conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_BREDR) &&
-        chan->conn->type == BT_CONN_TYPE_BR) {
-        return bt_l2cap_br_chan_send(chan, buf);
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR) && chan->conn->type == BT_CONN_TYPE_BR) {
+    return bt_l2cap_br_chan_send(chan, buf);
+  }
 
-    err = l2cap_chan_le_send_sdu(BT_L2CAP_LE_CHAN(chan), &buf, 0);
-    if (err < 0) {
-        if (err == -EAGAIN) {
-            /* Queue buffer to be sent later */
-            net_buf_put(&(BT_L2CAP_LE_CHAN(chan))->tx_queue, buf);
-            return *((u16_t *)net_buf_user_data(buf));
-        }
-        BT_ERR("failed to send message %d", err);
+  err = l2cap_chan_le_send_sdu(BT_L2CAP_LE_CHAN(chan), &buf, 0);
+  if (err < 0) {
+    if (err == -EAGAIN) {
+      /* Queue buffer to be sent later */
+      net_buf_put(&(BT_L2CAP_LE_CHAN(chan))->tx_queue, buf);
+      return *((u16_t *)net_buf_user_data(buf));
     }
+    BT_ERR("failed to send message %d", err);
+  }
 
-    return err;
+  return err;
 }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/monitor.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/monitor.c
index af4ee9c2d3..c6b27c372b 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/monitor.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/monitor.c
@@ -9,20 +9,16 @@
  */
 #if defined(CONFIG_BT_DEBUG_MONITOR)
 
-#include 
-#include 
 #include "monitor.h"
 #include "log.h"
+#include 
+#include 
 
-void bt_monitor_send(uint16_t opcode, const void *data, size_t len)
-{
-    const uint8_t *buf = data;
+void bt_monitor_send(uint16_t opcode, const void *data, size_t len) {
+  const uint8_t *buf = data;
 
-    BT_WARN("[Hci]:pkt_type:[0x%x],pkt_data:[%s]\r\n", opcode, bt_hex(buf, len));
+  BT_WARN("[Hci]:pkt_type:[0x%x],pkt_data:[%s]\r\n", opcode, bt_hex(buf, len));
 }
 
-void bt_monitor_new_index(uint8_t type, uint8_t bus, bt_addr_t *addr,
-                          const char *name)
-{
-}
+void bt_monitor_new_index(uint8_t type, uint8_t bus, bt_addr_t *addr, const char *name) {}
 #endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/multi_adv.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/multi_adv.c
index 4a1418789f..6f885a2e52 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/multi_adv.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/multi_adv.c
@@ -2,513 +2,485 @@
  * xx
  */
 
-#include 
 #include 
+#include 
 
-//#include 
+// #include 
 #include 
 #include 
 
 #include "multi_adv.h"
 #include "work_q.h"
 
-static struct multi_adv_instant g_multi_adv_list[MAX_MULTI_ADV_INSTANT];
+static struct multi_adv_instant   g_multi_adv_list[MAX_MULTI_ADV_INSTANT];
 static struct multi_adv_scheduler g_multi_adv_scheduler;
-static struct k_delayed_work g_multi_adv_timer;
+static struct k_delayed_work      g_multi_adv_timer;
 
 void multi_adv_schedule_timeslot(struct multi_adv_scheduler *adv_scheduler);
-int multi_adv_schedule_timer_stop(void);
+int  multi_adv_schedule_timer_stop(void);
 
-int multi_adv_get_instant_num(void)
-{
-    int i, num = 0;
-    struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
+int multi_adv_get_instant_num(void) {
+  int                       i, num = 0;
+  struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
 
-    for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
-        if (inst[i].inuse_flag)
-            num++;
-    }
-    return num;
+  for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
+    if (inst[i].inuse_flag)
+      num++;
+  }
+  return num;
 }
 
-struct multi_adv_instant *multi_adv_alloc_unused_instant(void)
-{
-    int i;
-    struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
+struct multi_adv_instant *multi_adv_alloc_unused_instant(void) {
+  int                       i;
+  struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
 
-    for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
-        if (inst[i].inuse_flag == 0) {
-            inst[i].inuse_flag = 1;
-            inst[i].instant_id = i + 1;
-            return &(inst[i]);
-        }
+  for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
+    if (inst[i].inuse_flag == 0) {
+      inst[i].inuse_flag = 1;
+      inst[i].instant_id = i + 1;
+      return &(inst[i]);
     }
-    return 0;
+  }
+  return 0;
 }
 
-int multi_adv_delete_instant_by_id(int instant_id)
-{
-    int i;
-    struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
+int multi_adv_delete_instant_by_id(int instant_id) {
+  int                       i;
+  struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
 
-    for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
-        if ((inst[i].inuse_flag) && (instant_id == (inst[i].instant_id))) {
-            inst[i].inuse_flag = 0;
-            return 0;
-        }
+  for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
+    if ((inst[i].inuse_flag) && (instant_id == (inst[i].instant_id))) {
+      inst[i].inuse_flag = 0;
+      return 0;
     }
-    return -1;
+  }
+  return -1;
 }
 
-struct multi_adv_instant *multi_adv_find_instant_by_id(int instant_id)
-{
-    int i;
-    struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
+struct multi_adv_instant *multi_adv_find_instant_by_id(int instant_id) {
+  int                       i;
+  struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
 
-    for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
-        if ((inst[i].inuse_flag) && (instant_id == (inst[i].instant_id))) {
-            return &(inst[i]);
-        }
+  for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
+    if ((inst[i].inuse_flag) && (instant_id == (inst[i].instant_id))) {
+      return &(inst[i]);
     }
-    return 0;
+  }
+  return 0;
 }
 
-struct multi_adv_instant *multi_adv_find_instant_by_order(int order)
-{
-    struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
+struct multi_adv_instant *multi_adv_find_instant_by_order(int order) {
+  struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
 
-    if (inst[order].inuse_flag) {
-        return &(inst[order]);
-    }
-    return 0;
+  if (inst[order].inuse_flag) {
+    return &(inst[order]);
+  }
+  return 0;
 }
 
-int multi_adv_set_ad_data(uint8_t *ad_data, const struct bt_data *ad, size_t ad_len)
-{
-    int i, len;
+int multi_adv_set_ad_data(uint8_t *ad_data, const struct bt_data *ad, size_t ad_len) {
+  int i, len;
 
-    memset(ad_data, 0, MAX_AD_DATA_LEN);
-    len = 0;
-    for (i = 0; i < ad_len; i++) {
-        /* Check if ad fit in the remaining buffer */
-        if (len + ad[i].data_len + 2 > MAX_AD_DATA_LEN) {
-            break;
-        }
+  memset(ad_data, 0, MAX_AD_DATA_LEN);
+  len = 0;
+  for (i = 0; i < ad_len; i++) {
+    /* Check if ad fit in the remaining buffer */
+    if (len + ad[i].data_len + 2 > MAX_AD_DATA_LEN) {
+      break;
+    }
 
-        ad_data[len++] = ad[i].data_len + 1;
-        ad_data[len++] = ad[i].type;
+    ad_data[len++] = ad[i].data_len + 1;
+    ad_data[len++] = ad[i].type;
 
-        memcpy(&ad_data[len], ad[i].data, ad[i].data_len);
-        len += ad[i].data_len;
-    }
+    memcpy(&ad_data[len], ad[i].data, ad[i].data_len);
+    len += ad[i].data_len;
+  }
 
-    return len;
+  return len;
 }
 
-int change_to_tick(int min_interval, int max_interval)
-{
-    int tick;
+int change_to_tick(int min_interval, int max_interval) {
+  int tick;
 
-    if (max_interval / SLOT_PER_PERIOD != min_interval / SLOT_PER_PERIOD) {
-        tick = min_interval / SLOT_PER_PERIOD;
-        if (min_interval % SLOT_PER_PERIOD)
-            tick++;
-    } else {
-        tick = min_interval / SLOT_PER_PERIOD;
-    }
-    if (tick <= 1)
-        tick = 1;
+  if (max_interval / SLOT_PER_PERIOD != min_interval / SLOT_PER_PERIOD) {
+    tick = min_interval / SLOT_PER_PERIOD;
+    if (min_interval % SLOT_PER_PERIOD)
+      tick++;
+  } else {
+    tick = min_interval / SLOT_PER_PERIOD;
+  }
+  if (tick <= 1)
+    tick = 1;
 
-    return tick;
+  return tick;
 }
 
-int calculate_min_multi(int a, int b)
-{
-    int x = a, y = b, z;
+int calculate_min_multi(int a, int b) {
+  int x = a, y = b, z;
 
-    while (y != 0) {
-        z = x % y;
-        x = y;
-        y = z;
-    }
+  while (y != 0) {
+    z = x % y;
+    x = y;
+    y = z;
+  }
 
-    return a * b / x;
+  return a * b / x;
 }
 
-void multi_adv_reorder(int inst_num, uint16_t inst_interval[], uint8_t inst_order[])
-{
-    int i, j;
+void multi_adv_reorder(int inst_num, uint16_t inst_interval[], uint8_t inst_order[]) {
+  int i, j;
 
-    for (i = 0; i < inst_num; i++) {
-        int max = inst_interval[0];
-        int max_idx = 0;
-        int temp;
+  for (i = 0; i < inst_num; i++) {
+    int max     = inst_interval[0];
+    int max_idx = 0;
+    int temp;
 
-        for (j = 1; j < inst_num - i; j++) {
-            if (max < inst_interval[j]) {
-                max = inst_interval[j];
-                max_idx = j;
-            }
-        }
+    for (j = 1; j < inst_num - i; j++) {
+      if (max < inst_interval[j]) {
+        max     = inst_interval[j];
+        max_idx = j;
+      }
+    }
 
-        temp = inst_interval[inst_num - i - 1];
-        inst_interval[inst_num - i - 1] = inst_interval[max_idx];
-        inst_interval[max_idx] = temp;
+    temp                            = inst_interval[inst_num - i - 1];
+    inst_interval[inst_num - i - 1] = inst_interval[max_idx];
+    inst_interval[max_idx]          = temp;
 
-        temp = inst_order[inst_num - i - 1];
-        inst_order[inst_num - i - 1] = inst_order[max_idx];
-        inst_order[max_idx] = temp;
-    }
+    temp                         = inst_order[inst_num - i - 1];
+    inst_order[inst_num - i - 1] = inst_order[max_idx];
+    inst_order[max_idx]          = temp;
+  }
 }
 
-int calculate_offset(uint16_t interval[], uint16_t offset[], int num, int duration)
-{
-    int i, j, k, curr_offset = 0;
-    int curr_max_instants, min_max_instants, instants;
-    int offset_range;
-
-    offset_range = interval[num];
-    if (offset_range > duration)
-        offset_range = duration;
-
-    if (num == 0)
-        return 0;
-
-    min_max_instants = 0x7fffffff;
-    /* using 0-interval-1 as offset */
-    for (i = 0; i < offset_range; i++) {
-        curr_max_instants = 0;
-        /* search slot form 0 - duration to get the max instants number */
-        for (j = 0; j < duration; j++) {
-            /* get instant number in each slot */
-            instants = 0;
-            for (k = 0; k < num; k++) {
-                if (j % interval[k] == offset[k]) {
-                    instants++;
-                }
-            }
-            if (j % interval[num] == i)
-                instants++;
-            if (curr_max_instants < instants) {
-                curr_max_instants = instants;
-            }
-        }
+int calculate_offset(uint16_t interval[], uint16_t offset[], int num, int duration) {
+  int i, j, k, curr_offset = 0;
+  int curr_max_instants, min_max_instants, instants;
+  int offset_range;
 
-        /* check if min max instants */
-        if (min_max_instants > curr_max_instants) {
-            min_max_instants = curr_max_instants;
-            curr_offset = i;
-        }
-    }
-    return curr_offset;
-}
+  offset_range = interval[num];
+  if (offset_range > duration)
+    offset_range = duration;
+
+  if (num == 0)
+    return 0;
 
-void multi_adv_schedule_table(int inst_num, uint16_t inst_interval[], uint16_t inst_offset[])
-{
-    int i, min_multi, last_min_multi;
-    /* calculate min multi */
-    last_min_multi = min_multi = inst_interval[0];
-    for (i = 1; i < inst_num; i++) {
-        min_multi = calculate_min_multi(min_multi, inst_interval[i]);
-        if (min_multi > MAX_MIN_MULTI) {
-            min_multi = last_min_multi;
-            break;
+  min_max_instants = 0x7fffffff;
+  /* using 0-interval-1 as offset */
+  for (i = 0; i < offset_range; i++) {
+    curr_max_instants = 0;
+    /* search slot form 0 - duration to get the max instants number */
+    for (j = 0; j < duration; j++) {
+      /* get instant number in each slot */
+      instants = 0;
+      for (k = 0; k < num; k++) {
+        if (j % interval[k] == offset[k]) {
+          instants++;
         }
-        last_min_multi = min_multi;
+      }
+      if (j % interval[num] == i)
+        instants++;
+      if (curr_max_instants < instants) {
+        curr_max_instants = instants;
+      }
     }
 
-    /* offset calcute for schedule just for small interval range */
-    for (i = 0; i < inst_num; i++) {
-        inst_offset[i] = calculate_offset(inst_interval, inst_offset, i, min_multi);
+    /* check if min max instants */
+    if (min_max_instants > curr_max_instants) {
+      min_max_instants = curr_max_instants;
+      curr_offset      = i;
     }
+  }
+  return curr_offset;
 }
 
-int multi_adv_start_adv_instant(struct multi_adv_instant *adv_instant)
-{
-    int ret;
-
-    ret = bt_le_adv_start_instant(&adv_instant->param,
-                                  adv_instant->ad, adv_instant->ad_len,
-                                  adv_instant->sd, adv_instant->sd_len);
-    if (ret) {
-        BT_WARN("adv start instant failed: inst_id %d, err %d\r\n", adv_instant->instant_id, ret);
+void multi_adv_schedule_table(int inst_num, uint16_t inst_interval[], uint16_t inst_offset[]) {
+  int i, min_multi, last_min_multi;
+  /* calculate min multi */
+  last_min_multi = min_multi = inst_interval[0];
+  for (i = 1; i < inst_num; i++) {
+    min_multi = calculate_min_multi(min_multi, inst_interval[i]);
+    if (min_multi > MAX_MIN_MULTI) {
+      min_multi = last_min_multi;
+      break;
     }
-    return ret;
+    last_min_multi = min_multi;
+  }
+
+  /* offset calcute for schedule just for small interval range */
+  for (i = 0; i < inst_num; i++) {
+    inst_offset[i] = calculate_offset(inst_interval, inst_offset, i, min_multi);
+  }
 }
 
-void multi_adv_schedule_timer_handle(void)
-{
-    struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
+int multi_adv_start_adv_instant(struct multi_adv_instant *adv_instant) {
+  int ret;
 
-    multi_adv_schedule_timer_stop();
-    if (adv_scheduler->schedule_state == SCHEDULE_STOP)
-        return;
+  ret = bt_le_adv_start_instant(&adv_instant->param, adv_instant->ad, adv_instant->ad_len, adv_instant->sd, adv_instant->sd_len);
+  if (ret) {
+    BT_WARN("adv start instant failed: inst_id %d, err %d\r\n", adv_instant->instant_id, ret);
+  }
+  return ret;
+}
 
-    adv_scheduler->slot_clock = adv_scheduler->next_slot_clock;
-    adv_scheduler->slot_offset = adv_scheduler->next_slot_offset;
+void multi_adv_schedule_timer_handle(void) {
+  struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
 
-    multi_adv_schedule_timeslot(adv_scheduler);
+  multi_adv_schedule_timer_stop();
+  if (adv_scheduler->schedule_state == SCHEDULE_STOP)
     return;
+
+  adv_scheduler->slot_clock  = adv_scheduler->next_slot_clock;
+  adv_scheduler->slot_offset = adv_scheduler->next_slot_offset;
+
+  multi_adv_schedule_timeslot(adv_scheduler);
+  return;
 }
 
-void multi_adv_schedule_timer_callback(struct k_work *timer)
-{
-    multi_adv_schedule_timer_handle();
-    return;
+void multi_adv_schedule_timer_callback(struct k_work *timer) {
+  multi_adv_schedule_timer_handle();
+  return;
 }
 
-int multi_adv_schedule_timer_start(int timeout)
-{
-    struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
-    multi_adv_schedule_timer_stop();
+int multi_adv_schedule_timer_start(int timeout) {
+  struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
+  multi_adv_schedule_timer_stop();
 
-    k_delayed_work_submit(&g_multi_adv_timer, timeout);
-    adv_scheduler->schedule_timer_active = 1;
+  k_delayed_work_submit(&g_multi_adv_timer, timeout);
+  adv_scheduler->schedule_timer_active = 1;
 
-    return 1;
+  return 1;
 }
 
-int multi_adv_schedule_timer_stop(void)
-{
-    struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
+int multi_adv_schedule_timer_stop(void) {
+  struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
 
-    if (adv_scheduler->schedule_timer_active) {
-        k_delayed_work_cancel(&g_multi_adv_timer);
-        adv_scheduler->schedule_timer_active = 0;
-    }
-    return 0;
+  if (adv_scheduler->schedule_timer_active) {
+    k_delayed_work_cancel(&g_multi_adv_timer);
+    adv_scheduler->schedule_timer_active = 0;
+  }
+  return 0;
 }
 
-void multi_adv_schedule_timeslot(struct multi_adv_scheduler *adv_scheduler)
-{
-    int i, inst_num;
-    int inst_clk, inst_off, match, insts = 0, next_slot, min_next_slot;
-    struct multi_adv_instant *adv_instant;
-    uint16_t inst_interval[MAX_MULTI_ADV_INSTANT];
-    uint16_t inst_offset[MAX_MULTI_ADV_INSTANT];
-    uint8_t inst_order[MAX_MULTI_ADV_INSTANT];
-    uint8_t match_order[MAX_MULTI_ADV_INSTANT];
-
-    inst_num = 0;
-    for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
-        adv_instant = multi_adv_find_instant_by_order(i);
-        if (adv_instant) {
-            inst_interval[inst_num] = adv_instant->instant_interval;
-            inst_offset[inst_num] = adv_instant->instant_offset;
-            inst_order[inst_num] = i;
-            inst_num++;
-        }
+void multi_adv_schedule_timeslot(struct multi_adv_scheduler *adv_scheduler) {
+  int                       i, inst_num;
+  int                       inst_clk, inst_off, match, insts = 0, next_slot, min_next_slot;
+  struct multi_adv_instant *adv_instant;
+  uint16_t                  inst_interval[MAX_MULTI_ADV_INSTANT];
+  uint16_t                  inst_offset[MAX_MULTI_ADV_INSTANT];
+  uint8_t                   inst_order[MAX_MULTI_ADV_INSTANT];
+  uint8_t                   match_order[MAX_MULTI_ADV_INSTANT];
+
+  inst_num = 0;
+  for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
+    adv_instant = multi_adv_find_instant_by_order(i);
+    if (adv_instant) {
+      inst_interval[inst_num] = adv_instant->instant_interval;
+      inst_offset[inst_num]   = adv_instant->instant_offset;
+      inst_order[inst_num]    = i;
+      inst_num++;
     }
-
-    inst_clk = adv_scheduler->slot_clock;
-    inst_off = adv_scheduler->slot_offset;
-    match = 0;
-    for (i = 0; i < inst_num; i++) {
-        if ((inst_clk % inst_interval[i]) == inst_offset[i]) {
-            match_order[match] = i;
-            match++;
-        }
+  }
+
+  inst_clk = adv_scheduler->slot_clock;
+  inst_off = adv_scheduler->slot_offset;
+  match    = 0;
+  for (i = 0; i < inst_num; i++) {
+    if ((inst_clk % inst_interval[i]) == inst_offset[i]) {
+      match_order[match] = i;
+      match++;
     }
+  }
 
-    //    BT_DBG("multi_adv_schedule_timeslot, num = %d, match = %d", inst_num, match);
-    if (match) {
-        int offset_per_instant, diff;
-        offset_per_instant = TIME_PRIOD_MS / match;
-        diff = inst_off - (inst_off + offset_per_instant / 2) / offset_per_instant * offset_per_instant; //TODO may be error
+  //    BT_DBG("multi_adv_schedule_timeslot, num = %d, match = %d", inst_num, match);
+  if (match) {
+    int offset_per_instant, diff;
+    offset_per_instant = TIME_PRIOD_MS / match;
+    diff               = inst_off - (inst_off + offset_per_instant / 2) / offset_per_instant * offset_per_instant; // TODO may be error
 
-        /* means this is the time to start */
-        if (diff <= 2) {
-            insts = (inst_off + offset_per_instant / 2) / offset_per_instant;
+    /* means this is the time to start */
+    if (diff <= 2) {
+      insts = (inst_off + offset_per_instant / 2) / offset_per_instant;
 
-            /* start instant */
-            adv_instant = multi_adv_find_instant_by_order(inst_order[match_order[insts]]);
-            if (adv_instant)
-                multi_adv_start_adv_instant(adv_instant);
-        }
+      /* start instant */
+      adv_instant = multi_adv_find_instant_by_order(inst_order[match_order[insts]]);
+      if (adv_instant)
+        multi_adv_start_adv_instant(adv_instant);
+    }
 
-        /* next instant in the same slot */
-        if (match - insts > 1) {
-            adv_scheduler->next_slot_offset = adv_scheduler->slot_offset + offset_per_instant;
-            adv_scheduler->next_slot_clock = adv_scheduler->slot_clock;
-
-            if ((adv_scheduler->next_slot_offset >= (TIME_PRIOD_MS - 2)) && (adv_scheduler->slot_offset <= (TIME_PRIOD_MS + 2))) {
-                adv_scheduler->next_slot_clock++;
-                adv_scheduler->next_slot_offset = 0;
-            }
-            multi_adv_schedule_timer_start(offset_per_instant);
-            return;
-        }
+    /* next instant in the same slot */
+    if (match - insts > 1) {
+      adv_scheduler->next_slot_offset = adv_scheduler->slot_offset + offset_per_instant;
+      adv_scheduler->next_slot_clock  = adv_scheduler->slot_clock;
+
+      if ((adv_scheduler->next_slot_offset >= (TIME_PRIOD_MS - 2)) && (adv_scheduler->slot_offset <= (TIME_PRIOD_MS + 2))) {
+        adv_scheduler->next_slot_clock++;
+        adv_scheduler->next_slot_offset = 0;
+      }
+      multi_adv_schedule_timer_start(offset_per_instant);
+      return;
     }
+  }
 
-    /* next instant not in the same slot */
-    min_next_slot = 0x7fffffff;
-    for (i = 0; i < inst_num; i++) {
-        if (inst_clk - inst_offset[i] < 0) {
-            match = 0;
-        } else {
-            match = (inst_clk - inst_offset[i]) / inst_interval[i] + 1;
-        }
-        next_slot = match * inst_interval[i] + inst_offset[i];
-        if (next_slot < min_next_slot) {
-            min_next_slot = next_slot;
-        }
+  /* next instant not in the same slot */
+  min_next_slot = 0x7fffffff;
+  for (i = 0; i < inst_num; i++) {
+    if (inst_clk - inst_offset[i] < 0) {
+      match = 0;
+    } else {
+      match = (inst_clk - inst_offset[i]) / inst_interval[i] + 1;
+    }
+    next_slot = match * inst_interval[i] + inst_offset[i];
+    if (next_slot < min_next_slot) {
+      min_next_slot = next_slot;
     }
-    adv_scheduler->next_slot_offset = 0;
-    adv_scheduler->next_slot_clock = min_next_slot;
+  }
+  adv_scheduler->next_slot_offset = 0;
+  adv_scheduler->next_slot_clock  = min_next_slot;
 
-    next_slot = (adv_scheduler->next_slot_clock - adv_scheduler->slot_clock) * TIME_PRIOD_MS + (adv_scheduler->next_slot_offset - adv_scheduler->slot_offset);
-    multi_adv_schedule_timer_start(next_slot);
-    return;
+  next_slot = (adv_scheduler->next_slot_clock - adv_scheduler->slot_clock) * TIME_PRIOD_MS + (adv_scheduler->next_slot_offset - adv_scheduler->slot_offset);
+  multi_adv_schedule_timer_start(next_slot);
+  return;
 }
 
-void multi_adv_schedule_stop(void)
-{
-    struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
+void multi_adv_schedule_stop(void) {
+  struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
 
-    multi_adv_schedule_timer_stop();
-    adv_scheduler->schedule_state = SCHEDULE_STOP;
+  multi_adv_schedule_timer_stop();
+  adv_scheduler->schedule_state = SCHEDULE_STOP;
 }
 
-void multi_adv_schedule_start(void)
-{
-    struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
+void multi_adv_schedule_start(void) {
+  struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
 
-    /* get all instant and calculate ticks and */
-    if (adv_scheduler->schedule_state == SCHEDULE_START) {
-        multi_adv_schedule_stop();
-    }
+  /* get all instant and calculate ticks and */
+  if (adv_scheduler->schedule_state == SCHEDULE_START) {
+    multi_adv_schedule_stop();
+  }
 
-    /* reinit scheduler */
-    adv_scheduler->slot_clock = 0;
-    adv_scheduler->slot_offset = 0;
-    adv_scheduler->schedule_state = SCHEDULE_START;
-    multi_adv_schedule_timeslot(adv_scheduler);
+  /* reinit scheduler */
+  adv_scheduler->slot_clock     = 0;
+  adv_scheduler->slot_offset    = 0;
+  adv_scheduler->schedule_state = SCHEDULE_START;
+  multi_adv_schedule_timeslot(adv_scheduler);
 }
 
-void multi_adv_new_schedule(void)
-{
-    int i;
-    struct multi_adv_instant *adv_instant, *high_duty_instant;
-    struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
-    uint16_t inst_offset[MAX_MULTI_ADV_INSTANT];
-    uint16_t inst_interval[MAX_MULTI_ADV_INSTANT];
-    uint8_t inst_order[MAX_MULTI_ADV_INSTANT];
-    int inst_num = 0;
-
-    if (adv_scheduler->schedule_state == SCHEDULE_START) {
-        multi_adv_schedule_stop();
-    }
-    /* get all instant and calculate ticks and */
-    high_duty_instant = 0;
-    for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
-        adv_instant = multi_adv_find_instant_by_order(i);
-        if (adv_instant) {
-            /* if high duty cycle adv found */
-            if (adv_instant->param.interval_min < HIGH_DUTY_CYCLE_INTERVAL) {
-                high_duty_instant = adv_instant;
-                break;
-            }
-
-            inst_interval[inst_num] = change_to_tick(adv_instant->param.interval_min, adv_instant->param.interval_max);
-            inst_order[inst_num] = i;
-            inst_num++;
-        }
+void multi_adv_new_schedule(void) {
+  int                         i;
+  struct multi_adv_instant   *adv_instant, *high_duty_instant;
+  struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
+  uint16_t                    inst_offset[MAX_MULTI_ADV_INSTANT];
+  uint16_t                    inst_interval[MAX_MULTI_ADV_INSTANT];
+  uint8_t                     inst_order[MAX_MULTI_ADV_INSTANT];
+  int                         inst_num = 0;
+
+  if (adv_scheduler->schedule_state == SCHEDULE_START) {
+    multi_adv_schedule_stop();
+  }
+  /* get all instant and calculate ticks and */
+  high_duty_instant = 0;
+  for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
+    adv_instant = multi_adv_find_instant_by_order(i);
+    if (adv_instant) {
+      /* if high duty cycle adv found */
+      if (adv_instant->param.interval_min < HIGH_DUTY_CYCLE_INTERVAL) {
+        high_duty_instant = adv_instant;
+        break;
+      }
+
+      inst_interval[inst_num] = change_to_tick(adv_instant->param.interval_min, adv_instant->param.interval_max);
+      inst_order[inst_num]    = i;
+      inst_num++;
     }
+  }
 
-    if (high_duty_instant) {
-        //BT_WARN("High Duty Cycle Instants, id = %d, interval = %d\n", adv_instant->instant_id, adv_instant->param.interval_min);
-        multi_adv_start_adv_instant(adv_instant);
-        return;
-    }
-
-    /* instant number equal 0 and 1 */
-    if (inst_num == 0) {
-        bt_le_adv_stop();
-        return;
-    }
-    if (inst_num == 1) {
-        adv_instant = multi_adv_find_instant_by_order(inst_order[0]);
-        if (!adv_instant)
-            return;
-        multi_adv_start_adv_instant(adv_instant);
-        return;
-    }
+  if (high_duty_instant) {
+    // BT_WARN("High Duty Cycle Instants, id = %d, interval = %d\n", adv_instant->instant_id, adv_instant->param.interval_min);
+    multi_adv_start_adv_instant(adv_instant);
+    return;
+  }
 
-    /* reorder by inst_interval */
-    multi_adv_reorder(inst_num, inst_interval, inst_order);
+  /* instant number equal 0 and 1 */
+  if (inst_num == 0) {
+    bt_le_adv_stop();
+    return;
+  }
+  if (inst_num == 1) {
+    adv_instant = multi_adv_find_instant_by_order(inst_order[0]);
+    if (!adv_instant)
+      return;
+    multi_adv_start_adv_instant(adv_instant);
+    return;
+  }
 
-    /* calcuate schedule table */
-    multi_adv_schedule_table(inst_num, inst_interval, inst_offset);
+  /* reorder by inst_interval */
+  multi_adv_reorder(inst_num, inst_interval, inst_order);
 
-    /* set interval and offset to instant */
-    for (i = 0; i < inst_num; i++) {
-        adv_instant = multi_adv_find_instant_by_order(inst_order[i]);
-        if (!adv_instant) {
-            continue;
-        }
-        adv_instant->instant_interval = inst_interval[i];
-        adv_instant->instant_offset = inst_offset[i];
+  /* calcuate schedule table */
+  multi_adv_schedule_table(inst_num, inst_interval, inst_offset);
 
-        //BT_WARN("adv_instant id = %d, interval = %d, offset = %d\n", adv_instant->instant_id, adv_instant->instant_interval, adv_instant->instant_offset);
+  /* set interval and offset to instant */
+  for (i = 0; i < inst_num; i++) {
+    adv_instant = multi_adv_find_instant_by_order(inst_order[i]);
+    if (!adv_instant) {
+      continue;
     }
+    adv_instant->instant_interval = inst_interval[i];
+    adv_instant->instant_offset   = inst_offset[i];
 
-    multi_adv_schedule_start();
+    // BT_WARN("adv_instant id = %d, interval = %d, offset = %d\n", adv_instant->instant_id, adv_instant->instant_interval, adv_instant->instant_offset);
+  }
+
+  multi_adv_schedule_start();
 }
 
-int bt_le_multi_adv_thread_init(void)
-{
-    /* timer and event init */
-    k_delayed_work_init(&g_multi_adv_timer, multi_adv_schedule_timer_callback);
-    return 0;
+int bt_le_multi_adv_thread_init(void) {
+  /* timer and event init */
+  k_delayed_work_init(&g_multi_adv_timer, multi_adv_schedule_timer_callback);
+  return 0;
 }
 
-int bt_le_multi_adv_start(const struct bt_le_adv_param *param,
-                          const struct bt_data *ad, size_t ad_len,
-                          const struct bt_data *sd, size_t sd_len, int *instant_id)
-{
-    int instant_num;
-    struct multi_adv_instant *adv_instant;
+int bt_le_multi_adv_start(const struct bt_le_adv_param *param, const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len, int *instant_id) {
+  int                       instant_num;
+  struct multi_adv_instant *adv_instant;
 
-    instant_num = multi_adv_get_instant_num();
-    if (instant_num >= MAX_MULTI_ADV_INSTANT)
-        return -1;
+  instant_num = multi_adv_get_instant_num();
+  if (instant_num >= MAX_MULTI_ADV_INSTANT)
+    return -1;
 
-    adv_instant = multi_adv_alloc_unused_instant();
-    if (adv_instant == 0)
-        return -1;
+  adv_instant = multi_adv_alloc_unused_instant();
+  if (adv_instant == 0)
+    return -1;
 
-    memcpy(&(adv_instant->param), param, sizeof(struct bt_le_adv_param));
+  memcpy(&(adv_instant->param), param, sizeof(struct bt_le_adv_param));
 
-    adv_instant->ad_len = multi_adv_set_ad_data(adv_instant->ad, ad, ad_len);
-    adv_instant->sd_len = multi_adv_set_ad_data(adv_instant->sd, sd, sd_len);
+  adv_instant->ad_len = multi_adv_set_ad_data(adv_instant->ad, ad, ad_len);
+  adv_instant->sd_len = multi_adv_set_ad_data(adv_instant->sd, sd, sd_len);
 
-    multi_adv_new_schedule();
+  multi_adv_new_schedule();
 
-    *instant_id = adv_instant->instant_id;
-    return 0;
+  *instant_id = adv_instant->instant_id;
+  return 0;
 }
 
-int bt_le_multi_adv_stop(int instant_id)
-{
-    if (multi_adv_find_instant_by_id(instant_id) == 0)
-        return -1;
+int bt_le_multi_adv_stop(int instant_id) {
+  if (multi_adv_find_instant_by_id(instant_id) == 0)
+    return -1;
 
-    //BT_WARN("%s id[%d]\n", __func__, instant_id);
-    multi_adv_delete_instant_by_id(instant_id);
-    multi_adv_new_schedule();
+  // BT_WARN("%s id[%d]\n", __func__, instant_id);
+  multi_adv_delete_instant_by_id(instant_id);
+  multi_adv_new_schedule();
 
-    return 0;
+  return 0;
 }
 
-bool bt_le_multi_adv_id_is_vaild(int instant_id)
-{
-    int i;
-    struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
+bool bt_le_multi_adv_id_is_vaild(int instant_id) {
+  int                       i;
+  struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
 
-    for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
-        if ((inst[i].inuse_flag) && (instant_id == (inst[i].instant_id))) {
-            return true;
-        }
+  for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
+    if ((inst[i].inuse_flag) && (instant_id == (inst[i].instant_id))) {
+      return true;
     }
-    return false;
+  }
+  return false;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/sdp.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/sdp.c
index 4cebb5bcc2..a757f6cb39 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/sdp.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/sdp.c
@@ -9,9 +9,9 @@
  */
 
 #include 
-#include 
-#include 
 #include 
+#include 
+#include 
 
 #include <../bluetooth/buf.h>
 #include <../bluetooth/sdp.h>
@@ -20,8 +20,8 @@
 #define LOG_MODULE_NAME bt_sdp
 #include "log.h"
 
-#include "hci_core.h"
 #include "conn_internal.h"
+#include "hci_core.h"
 #include "l2cap_internal.h"
 #include "sdp_internal.h"
 
@@ -58,20 +58,19 @@
 #define SDP_INVALID 0xff
 
 struct bt_sdp {
-    struct bt_l2cap_br_chan chan;
-    struct k_fifo partial_resp_queue;
-    /* TODO: Allow more than one pending request */
+  struct bt_l2cap_br_chan chan;
+  struct k_fifo           partial_resp_queue;
+  /* TODO: Allow more than one pending request */
 };
 
 static struct bt_sdp_record *db;
-static uint8_t num_services;
+static uint8_t               num_services;
 
 static struct bt_sdp bt_sdp_pool[CONFIG_BT_MAX_CONN];
 
 /* Pool for outgoing SDP packets */
 #if !defined(BFLB_DYNAMIC_ALLOC_MEM)
-NET_BUF_POOL_FIXED_DEFINE(sdp_pool, CONFIG_BT_MAX_CONN,
-                          BT_L2CAP_BUF_SIZE(SDP_MTU), NULL);
+NET_BUF_POOL_FIXED_DEFINE(sdp_pool, CONFIG_BT_MAX_CONN, BT_L2CAP_BUF_SIZE(SDP_MTU), NULL);
 #else
 struct net_buf_pool sdp_pool;
 #endif
@@ -81,45 +80,45 @@ struct net_buf_pool sdp_pool;
 #define SDP_CLIENT_MTU 64
 
 struct bt_sdp_client {
-    struct bt_l2cap_br_chan chan;
-    /* list of waiting to be resolved UUID params */
-    sys_slist_t reqs;
-    /* required SDP transaction ID */
-    uint16_t tid;
-    /* UUID params holder being now resolved */
-    const struct bt_sdp_discover_params *param;
-    /* PDU continuation state object */
-    struct bt_sdp_pdu_cstate cstate;
-    /* buffer for collecting record data */
-    struct net_buf *rec_buf;
+  struct bt_l2cap_br_chan chan;
+  /* list of waiting to be resolved UUID params */
+  sys_slist_t reqs;
+  /* required SDP transaction ID */
+  uint16_t tid;
+  /* UUID params holder being now resolved */
+  const struct bt_sdp_discover_params *param;
+  /* PDU continuation state object */
+  struct bt_sdp_pdu_cstate cstate;
+  /* buffer for collecting record data */
+  struct net_buf *rec_buf;
 };
 
 static struct bt_sdp_client bt_sdp_client_pool[CONFIG_BT_MAX_CONN];
 
 enum {
-    BT_SDP_ITER_STOP,
-    BT_SDP_ITER_CONTINUE,
+  BT_SDP_ITER_STOP,
+  BT_SDP_ITER_CONTINUE,
 };
 
 struct search_state {
-    uint16_t att_list_size;
-    uint8_t current_svc;
-    uint8_t last_att;
-    bool pkt_full;
+  uint16_t att_list_size;
+  uint8_t  current_svc;
+  uint8_t  last_att;
+  bool     pkt_full;
 };
 
 struct select_attrs_data {
-    struct bt_sdp_record *rec;
-    struct net_buf *rsp_buf;
-    struct bt_sdp *sdp;
-    struct bt_sdp_data_elem_seq *seq;
-    struct search_state *state;
-    uint32_t *filter;
-    uint16_t max_att_len;
-    uint16_t att_list_len;
-    uint8_t cont_state_size;
-    uint8_t num_filters;
-    bool new_service;
+  struct bt_sdp_record        *rec;
+  struct net_buf              *rsp_buf;
+  struct bt_sdp               *sdp;
+  struct bt_sdp_data_elem_seq *seq;
+  struct search_state         *state;
+  uint32_t                    *filter;
+  uint16_t                     max_att_len;
+  uint16_t                     att_list_len;
+  uint8_t                      cont_state_size;
+  uint8_t                      num_filters;
+  bool                         new_service;
 };
 
 /* @typedef bt_sdp_attr_func_t
@@ -132,8 +131,7 @@ struct select_attrs_data {
  *  @return BT_SDP_ITER_CONTINUE if should continue to the next attribute
  *  or BT_SDP_ITER_STOP to stop.
  */
-typedef uint8_t (*bt_sdp_attr_func_t)(struct bt_sdp_attribute *attr,
-                                      uint8_t att_idx, void *user_data);
+typedef uint8_t (*bt_sdp_attr_func_t)(struct bt_sdp_attribute *attr, uint8_t att_idx, void *user_data);
 
 /* @typedef bt_sdp_svc_func_t
  * @brief SDP service record iterator callback.
@@ -144,8 +142,7 @@ typedef uint8_t (*bt_sdp_attr_func_t)(struct bt_sdp_attribute *attr,
  * @return BT_SDP_ITER_CONTINUE if should continue to the next service record
  *  or BT_SDP_ITER_STOP to stop.
  */
-typedef uint8_t (*bt_sdp_svc_func_t)(struct bt_sdp_record *rec,
-                                     void *user_data);
+typedef uint8_t (*bt_sdp_svc_func_t)(struct bt_sdp_record *rec, void *user_data);
 
 /* @brief Callback for SDP connection
  *
@@ -155,17 +152,14 @@ typedef uint8_t (*bt_sdp_svc_func_t)(struct bt_sdp_record *rec,
  *
  *  @return None
  */
-static void bt_sdp_connected(struct bt_l2cap_chan *chan)
-{
-    struct bt_l2cap_br_chan *ch = CONTAINER_OF(chan,
-                                               struct bt_l2cap_br_chan,
-                                               chan);
+static void bt_sdp_connected(struct bt_l2cap_chan *chan) {
+  struct bt_l2cap_br_chan *ch = CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan);
 
-    struct bt_sdp *sdp = CONTAINER_OF(ch, struct bt_sdp, chan);
+  struct bt_sdp *sdp = CONTAINER_OF(ch, struct bt_sdp, chan);
 
-    BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
+  BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
 
-    k_fifo_init(&sdp->partial_resp_queue, 20); //MBHJ
+  k_fifo_init(&sdp->partial_resp_queue, 20); // MBHJ
 }
 
 /** @brief Callback for SDP disconnection
@@ -176,17 +170,14 @@ static void bt_sdp_connected(struct bt_l2cap_chan *chan)
  *
  *  @return None
  */
-static void bt_sdp_disconnected(struct bt_l2cap_chan *chan)
-{
-    struct bt_l2cap_br_chan *ch = CONTAINER_OF(chan,
-                                               struct bt_l2cap_br_chan,
-                                               chan);
+static void bt_sdp_disconnected(struct bt_l2cap_chan *chan) {
+  struct bt_l2cap_br_chan *ch = CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan);
 
-    struct bt_sdp *sdp = CONTAINER_OF(ch, struct bt_sdp, chan);
+  struct bt_sdp *sdp = CONTAINER_OF(ch, struct bt_sdp, chan);
 
-    BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
+  BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
 
-    (void)memset(sdp, 0, sizeof(*sdp));
+  (void)memset(sdp, 0, sizeof(*sdp));
 }
 
 /* @brief Creates an SDP PDU
@@ -197,10 +188,7 @@ static void bt_sdp_disconnected(struct bt_l2cap_chan *chan)
  *
  *  @return Pointer to the net_buf buffer
  */
-static struct net_buf *bt_sdp_create_pdu(void)
-{
-    return bt_l2cap_create_pdu(&sdp_pool, sizeof(struct bt_sdp_hdr));
-}
+static struct net_buf *bt_sdp_create_pdu(void) { return bt_l2cap_create_pdu(&sdp_pool, sizeof(struct bt_sdp_hdr)); }
 
 /* @brief Sends out an SDP PDU
  *
@@ -213,18 +201,16 @@ static struct net_buf *bt_sdp_create_pdu(void)
  *
  *  @return None
  */
-static void bt_sdp_send(struct bt_l2cap_chan *chan, struct net_buf *buf,
-                        uint8_t op, uint16_t tid)
-{
-    struct bt_sdp_hdr *hdr;
-    uint16_t param_len = buf->len;
-
-    hdr = net_buf_push(buf, sizeof(struct bt_sdp_hdr));
-    hdr->op_code = op;
-    hdr->tid = tid;
-    hdr->param_len = sys_cpu_to_be16(param_len);
-
-    bt_l2cap_chan_send(chan, buf);
+static void bt_sdp_send(struct bt_l2cap_chan *chan, struct net_buf *buf, uint8_t op, uint16_t tid) {
+  struct bt_sdp_hdr *hdr;
+  uint16_t           param_len = buf->len;
+
+  hdr            = net_buf_push(buf, sizeof(struct bt_sdp_hdr));
+  hdr->op_code   = op;
+  hdr->tid       = tid;
+  hdr->param_len = sys_cpu_to_be16(param_len);
+
+  bt_l2cap_chan_send(chan, buf);
 }
 
 /* @brief Sends an error response PDU
@@ -237,18 +223,16 @@ static void bt_sdp_send(struct bt_l2cap_chan *chan, struct net_buf *buf,
  *
  *  @return None
  */
-static void send_err_rsp(struct bt_l2cap_chan *chan, uint16_t err,
-                         uint16_t tid)
-{
-    struct net_buf *buf;
+static void send_err_rsp(struct bt_l2cap_chan *chan, uint16_t err, uint16_t tid) {
+  struct net_buf *buf;
 
-    BT_DBG("tid %u, error %u", tid, err);
+  BT_DBG("tid %u, error %u", tid, err);
 
-    buf = bt_sdp_create_pdu();
+  buf = bt_sdp_create_pdu();
 
-    net_buf_add_be16(buf, err);
+  net_buf_add_be16(buf, err);
 
-    bt_sdp_send(chan, buf, BT_SDP_ERROR_RSP, tid);
+  bt_sdp_send(chan, buf, BT_SDP_ERROR_RSP, tid);
 }
 
 /* @brief Parses data elements from a net_buf
@@ -262,65 +246,61 @@ static void send_err_rsp(struct bt_l2cap_chan *chan, uint16_t err,
  *
  * @return 0 for success, or relevant error code
  */
-static uint16_t parse_data_elem(struct net_buf *buf,
-                                struct bt_sdp_data_elem *data_elem)
-{
-    uint8_t size_field_len = 0U; /* Space used to accommodate the size */
-
-    if (buf->len < 1) {
-        BT_WARN("Malformed packet");
-        return BT_SDP_INVALID_SYNTAX;
-    }
-
-    data_elem->type = net_buf_pull_u8(buf);
-
-    switch (data_elem->type & BT_SDP_TYPE_DESC_MASK) {
-        case BT_SDP_UINT8:
-        case BT_SDP_INT8:
-        case BT_SDP_UUID_UNSPEC:
-        case BT_SDP_BOOL:
-            data_elem->data_size = BIT(data_elem->type &
-                                       BT_SDP_SIZE_DESC_MASK);
-            break;
-        case BT_SDP_TEXT_STR_UNSPEC:
-        case BT_SDP_SEQ_UNSPEC:
-        case BT_SDP_ALT_UNSPEC:
-        case BT_SDP_URL_STR_UNSPEC:
-            size_field_len = BIT((data_elem->type & BT_SDP_SIZE_DESC_MASK) -
-                                 BT_SDP_SIZE_INDEX_OFFSET);
-            if (buf->len < size_field_len) {
-                BT_WARN("Malformed packet");
-                return BT_SDP_INVALID_SYNTAX;
-            }
-            switch (size_field_len) {
-                case 1:
-                    data_elem->data_size = net_buf_pull_u8(buf);
-                    break;
-                case 2:
-                    data_elem->data_size = net_buf_pull_be16(buf);
-                    break;
-                case 4:
-                    data_elem->data_size = net_buf_pull_be32(buf);
-                    break;
-                default:
-                    BT_WARN("Invalid size in remote request");
-                    return BT_SDP_INVALID_SYNTAX;
-            }
-            break;
-        default:
-            BT_WARN("Invalid type in remote request");
-            return BT_SDP_INVALID_SYNTAX;
-    }
-
-    if (buf->len < data_elem->data_size) {
-        BT_WARN("Malformed packet");
-        return BT_SDP_INVALID_SYNTAX;
-    }
-
-    data_elem->total_size = data_elem->data_size + size_field_len + 1;
-    data_elem->data = buf->data;
-
-    return 0;
+static uint16_t parse_data_elem(struct net_buf *buf, struct bt_sdp_data_elem *data_elem) {
+  uint8_t size_field_len = 0U; /* Space used to accommodate the size */
+
+  if (buf->len < 1) {
+    BT_WARN("Malformed packet");
+    return BT_SDP_INVALID_SYNTAX;
+  }
+
+  data_elem->type = net_buf_pull_u8(buf);
+
+  switch (data_elem->type & BT_SDP_TYPE_DESC_MASK) {
+  case BT_SDP_UINT8:
+  case BT_SDP_INT8:
+  case BT_SDP_UUID_UNSPEC:
+  case BT_SDP_BOOL:
+    data_elem->data_size = BIT(data_elem->type & BT_SDP_SIZE_DESC_MASK);
+    break;
+  case BT_SDP_TEXT_STR_UNSPEC:
+  case BT_SDP_SEQ_UNSPEC:
+  case BT_SDP_ALT_UNSPEC:
+  case BT_SDP_URL_STR_UNSPEC:
+    size_field_len = BIT((data_elem->type & BT_SDP_SIZE_DESC_MASK) - BT_SDP_SIZE_INDEX_OFFSET);
+    if (buf->len < size_field_len) {
+      BT_WARN("Malformed packet");
+      return BT_SDP_INVALID_SYNTAX;
+    }
+    switch (size_field_len) {
+    case 1:
+      data_elem->data_size = net_buf_pull_u8(buf);
+      break;
+    case 2:
+      data_elem->data_size = net_buf_pull_be16(buf);
+      break;
+    case 4:
+      data_elem->data_size = net_buf_pull_be32(buf);
+      break;
+    default:
+      BT_WARN("Invalid size in remote request");
+      return BT_SDP_INVALID_SYNTAX;
+    }
+    break;
+  default:
+    BT_WARN("Invalid type in remote request");
+    return BT_SDP_INVALID_SYNTAX;
+  }
+
+  if (buf->len < data_elem->data_size) {
+    BT_WARN("Malformed packet");
+    return BT_SDP_INVALID_SYNTAX;
+  }
+
+  data_elem->total_size = data_elem->data_size + size_field_len + 1;
+  data_elem->data       = buf->data;
+
+  return 0;
 }
 
 /* @brief Searches for an UUID within an attribute
@@ -338,70 +318,66 @@ static uint16_t parse_data_elem(struct net_buf *buf,
  * @return Size of the last data element that has been searched
  *  (used in recursion)
  */
-static uint32_t search_uuid(struct bt_sdp_data_elem *elem, struct bt_uuid *uuid,
-                            bool *found, uint8_t nest_level)
-{
-    const uint8_t *cur_elem;
-    uint32_t seq_size, size;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_32 u32;
-        struct bt_uuid_128 u128;
-    } u;
-
-    if (*found) {
-        return 0;
-    }
-
-    /* Limit recursion depth to avoid stack overflows */
-    if (nest_level == SDP_DATA_ELEM_NEST_LEVEL_MAX) {
-        return 0;
-    }
+static uint32_t search_uuid(struct bt_sdp_data_elem *elem, struct bt_uuid *uuid, bool *found, uint8_t nest_level) {
+  const uint8_t *cur_elem;
+  uint32_t       seq_size, size;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_32  u32;
+    struct bt_uuid_128 u128;
+  } u;
+
+  if (*found) {
+    return 0;
+  }
 
-    seq_size = elem->data_size;
-    cur_elem = elem->data;
-
-    if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_UUID_UNSPEC) {
-        if (seq_size == 2U) {
-            u.uuid.type = BT_UUID_TYPE_16;
-            u.u16.val = *((uint16_t *)cur_elem);
-            if (!bt_uuid_cmp(&u.uuid, uuid)) {
-                *found = true;
-            }
-        } else if (seq_size == 4U) {
-            u.uuid.type = BT_UUID_TYPE_32;
-            u.u32.val = *((uint32_t *)cur_elem);
-            if (!bt_uuid_cmp(&u.uuid, uuid)) {
-                *found = true;
-            }
-        } else if (seq_size == 16U) {
-            u.uuid.type = BT_UUID_TYPE_128;
-            memcpy(u.u128.val, cur_elem, seq_size);
-            if (!bt_uuid_cmp(&u.uuid, uuid)) {
-                *found = true;
-            }
-        } else {
-            BT_WARN("Invalid UUID size in local database");
-            BT_ASSERT(0);
-        }
+  /* Limit recursion depth to avoid stack overflows */
+  if (nest_level == SDP_DATA_ELEM_NEST_LEVEL_MAX) {
+    return 0;
+  }
+
+  seq_size = elem->data_size;
+  cur_elem = elem->data;
+
+  if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_UUID_UNSPEC) {
+    if (seq_size == 2U) {
+      u.uuid.type = BT_UUID_TYPE_16;
+      u.u16.val   = *((uint16_t *)cur_elem);
+      if (!bt_uuid_cmp(&u.uuid, uuid)) {
+        *found = true;
+      }
+    } else if (seq_size == 4U) {
+      u.uuid.type = BT_UUID_TYPE_32;
+      u.u32.val   = *((uint32_t *)cur_elem);
+      if (!bt_uuid_cmp(&u.uuid, uuid)) {
+        *found = true;
+      }
+    } else if (seq_size == 16U) {
+      u.uuid.type = BT_UUID_TYPE_128;
+      memcpy(u.u128.val, cur_elem, seq_size);
+      if (!bt_uuid_cmp(&u.uuid, uuid)) {
+        *found = true;
+      }
+    } else {
+      BT_WARN("Invalid UUID size in local database");
+      BT_ASSERT(0);
     }
+  }
 
-    if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_SEQ_UNSPEC ||
-        (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_ALT_UNSPEC) {
-        do {
-            /* Recursively parse data elements */
-            size = search_uuid((struct bt_sdp_data_elem *)cur_elem,
-                               uuid, found, nest_level + 1);
-            if (*found) {
-                return 0;
-            }
-            cur_elem += sizeof(struct bt_sdp_data_elem);
-            seq_size -= size;
-        } while (seq_size);
-    }
+  if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_SEQ_UNSPEC || (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_ALT_UNSPEC) {
+    do {
+      /* Recursively parse data elements */
+      size = search_uuid((struct bt_sdp_data_elem *)cur_elem, uuid, found, nest_level + 1);
+      if (*found) {
+        return 0;
+      }
+      cur_elem += sizeof(struct bt_sdp_data_elem);
+      seq_size -= size;
+    } while (seq_size);
+  }
 
-    return elem->total_size;
+  return elem->total_size;
 }
 
 /* @brief SDP service record iterator.
@@ -414,19 +390,17 @@ static uint32_t search_uuid(struct bt_sdp_data_elem *elem, struct bt_uuid *uuid,
  * @return Pointer to the record where the iterator stopped, or NULL if all
  *  records are covered
  */
-static struct bt_sdp_record *bt_sdp_foreach_svc(bt_sdp_svc_func_t func,
-                                                void *user_data)
-{
-    struct bt_sdp_record *rec = db;
-
-    while (rec) {
-        if (func(rec, user_data) == BT_SDP_ITER_STOP) {
-            break;
-        }
+static struct bt_sdp_record *bt_sdp_foreach_svc(bt_sdp_svc_func_t func, void *user_data) {
+  struct bt_sdp_record *rec = db;
 
-        rec = rec->next;
+  while (rec) {
+    if (func(rec, user_data) == BT_SDP_ITER_STOP) {
+      break;
     }
-    return rec;
+
+    rec = rec->next;
+  }
+  return rec;
 }
 
 /* @brief Inserts a service record into a record pointer list
@@ -438,13 +412,12 @@ static struct bt_sdp_record *bt_sdp_foreach_svc(bt_sdp_svc_func_t func,
  *
  * @return BT_SDP_ITER_CONTINUE to move on to the next record.
  */
-static uint8_t insert_record(struct bt_sdp_record *rec, void *user_data)
-{
-    struct bt_sdp_record **rec_list = user_data;
+static uint8_t insert_record(struct bt_sdp_record *rec, void *user_data) {
+  struct bt_sdp_record **rec_list = user_data;
 
-    rec_list[rec->index] = rec;
+  rec_list[rec->index] = rec;
 
-    return BT_SDP_ITER_CONTINUE;
+  return BT_SDP_ITER_CONTINUE;
 }
 
 /* @brief Looks for matching UUIDs in a list of service records
@@ -460,108 +433,98 @@ static uint8_t insert_record(struct bt_sdp_record *rec, void *user_data)
  *
  * @return 0 for success, or relevant error code
  */
-static uint16_t find_services(struct net_buf *buf,
-                              struct bt_sdp_record **matching_recs)
-{
-    struct bt_sdp_data_elem data_elem;
-    struct bt_sdp_record *record;
-    uint32_t uuid_list_size;
-    uint16_t res;
-    uint8_t att_idx, rec_idx = 0U;
-    bool found;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_32 u32;
-        struct bt_uuid_128 u128;
-    } u;
-
+static uint16_t find_services(struct net_buf *buf, struct bt_sdp_record **matching_recs) {
+  struct bt_sdp_data_elem data_elem;
+  struct bt_sdp_record   *record;
+  uint32_t                uuid_list_size;
+  uint16_t                res;
+  uint8_t                 att_idx, rec_idx = 0U;
+  bool                    found;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_32  u32;
+    struct bt_uuid_128 u128;
+  } u;
+
+  res = parse_data_elem(buf, &data_elem);
+  if (res) {
+    return res;
+  }
+
+  if (((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_SEQ_UNSPEC) && ((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_ALT_UNSPEC)) {
+    BT_WARN("Invalid type %x in service search pattern", data_elem.type);
+    return BT_SDP_INVALID_SYNTAX;
+  }
+
+  uuid_list_size = data_elem.data_size;
+
+  bt_sdp_foreach_svc(insert_record, matching_recs);
+
+  /* Go over the sequence of UUIDs, and match one UUID at a time */
+  while (uuid_list_size) {
     res = parse_data_elem(buf, &data_elem);
     if (res) {
-        return res;
+      return res;
     }
 
-    if (((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_SEQ_UNSPEC) &&
-        ((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_ALT_UNSPEC)) {
-        BT_WARN("Invalid type %x in service search pattern",
-                data_elem.type);
-        return BT_SDP_INVALID_SYNTAX;
+    if ((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_UUID_UNSPEC) {
+      BT_WARN("Invalid type %u in service search pattern", data_elem.type);
+      return BT_SDP_INVALID_SYNTAX;
     }
 
-    uuid_list_size = data_elem.data_size;
+    if (buf->len < data_elem.data_size) {
+      BT_WARN("Malformed packet");
+      return BT_SDP_INVALID_SYNTAX;
+    }
 
-    bt_sdp_foreach_svc(insert_record, matching_recs);
+    if (data_elem.data_size == 2U) {
+      u.uuid.type = BT_UUID_TYPE_16;
+      u.u16.val   = net_buf_pull_be16(buf);
+    } else if (data_elem.data_size == 4U) {
+      u.uuid.type = BT_UUID_TYPE_32;
+      u.u32.val   = net_buf_pull_be32(buf);
+    } else if (data_elem.data_size == 16U) {
+      u.uuid.type = BT_UUID_TYPE_128;
+      sys_memcpy_swap(u.u128.val, buf->data, data_elem.data_size);
+      net_buf_pull(buf, data_elem.data_size);
+    } else {
+      BT_WARN("Invalid UUID len %u in service search pattern", data_elem.data_size);
+      net_buf_pull(buf, data_elem.data_size);
+    }
 
-    /* Go over the sequence of UUIDs, and match one UUID at a time */
-    while (uuid_list_size) {
-        res = parse_data_elem(buf, &data_elem);
-        if (res) {
-            return res;
-        }
+    uuid_list_size -= data_elem.total_size;
 
-        if ((data_elem.type & BT_SDP_TYPE_DESC_MASK) !=
-            BT_SDP_UUID_UNSPEC) {
-            BT_WARN("Invalid type %u in service search pattern",
-                    data_elem.type);
-            return BT_SDP_INVALID_SYNTAX;
-        }
+    /* Go over the list of services, and look for a service which
+     * doesn't have this UUID
+     */
+    for (rec_idx = 0U; rec_idx < num_services; rec_idx++) {
+      record = matching_recs[rec_idx];
 
-        if (buf->len < data_elem.data_size) {
-            BT_WARN("Malformed packet");
-            return BT_SDP_INVALID_SYNTAX;
-        }
+      if (!record) {
+        continue;
+      }
 
-        if (data_elem.data_size == 2U) {
-            u.uuid.type = BT_UUID_TYPE_16;
-            u.u16.val = net_buf_pull_be16(buf);
-        } else if (data_elem.data_size == 4U) {
-            u.uuid.type = BT_UUID_TYPE_32;
-            u.u32.val = net_buf_pull_be32(buf);
-        } else if (data_elem.data_size == 16U) {
-            u.uuid.type = BT_UUID_TYPE_128;
-            sys_memcpy_swap(u.u128.val, buf->data,
-                            data_elem.data_size);
-            net_buf_pull(buf, data_elem.data_size);
-        } else {
-            BT_WARN("Invalid UUID len %u in service search pattern",
-                    data_elem.data_size);
-            net_buf_pull(buf, data_elem.data_size);
-        }
+      found = false;
 
-        uuid_list_size -= data_elem.total_size;
-
-        /* Go over the list of services, and look for a service which
-		 * doesn't have this UUID
-		 */
-        for (rec_idx = 0U; rec_idx < num_services; rec_idx++) {
-            record = matching_recs[rec_idx];
-
-            if (!record) {
-                continue;
-            }
-
-            found = false;
-
-            /* Search for the UUID in all the attrs of the svc */
-            for (att_idx = 0U; att_idx < record->attr_count;
-                 att_idx++) {
-                search_uuid(&record->attrs[att_idx].val,
-                            &u.uuid, &found, 1);
-                if (found) {
-                    break;
-                }
-            }
-
-            /* Remove the record from the list if it doesn't have
-			 * the UUID
-			 */
-            if (!found) {
-                matching_recs[rec_idx] = NULL;
-            }
+      /* Search for the UUID in all the attrs of the svc */
+      for (att_idx = 0U; att_idx < record->attr_count; att_idx++) {
+        search_uuid(&record->attrs[att_idx].val, &u.uuid, &found, 1);
+        if (found) {
+          break;
         }
+      }
+
+      /* Remove the record from the list if it doesn't have
+       * the UUID
+       */
+      if (!found) {
+        matching_recs[rec_idx] = NULL;
+      }
     }
+  }
 
-    return 0;
+  return 0;
 }
 
 /* @brief Handler for Service Search Request
@@ -574,129 +537,125 @@ static uint16_t find_services(struct net_buf *buf,
  *
  * @return 0 for success, or relevant error code
  */
-static uint16_t sdp_svc_search_req(struct bt_sdp *sdp, struct net_buf *buf,
-                                   uint16_t tid)
-{
-    struct bt_sdp_svc_rsp *rsp;
-    struct net_buf *resp_buf;
-    struct bt_sdp_record *record;
-    struct bt_sdp_record *matching_recs[BT_SDP_MAX_SERVICES];
-    uint16_t max_rec_count, total_recs = 0U, current_recs = 0U, res;
-    uint8_t cont_state_size, cont_state = 0U, idx = 0U, count = 0U;
-    bool pkt_full = false;
-
-    res = find_services(buf, matching_recs);
-    if (res) {
-        /* Error in parsing */
-        return res;
-    }
+static uint16_t sdp_svc_search_req(struct bt_sdp *sdp, struct net_buf *buf, uint16_t tid) {
+  struct bt_sdp_svc_rsp *rsp;
+  struct net_buf        *resp_buf;
+  struct bt_sdp_record  *record;
+  struct bt_sdp_record  *matching_recs[BT_SDP_MAX_SERVICES];
+  uint16_t               max_rec_count, total_recs = 0U, current_recs = 0U, res;
+  uint8_t                cont_state_size, cont_state = 0U, idx = 0U, count = 0U;
+  bool                   pkt_full = false;
 
-    if (buf->len < 3) {
-        BT_WARN("Malformed packet");
-        return BT_SDP_INVALID_SYNTAX;
-    }
+  res = find_services(buf, matching_recs);
+  if (res) {
+    /* Error in parsing */
+    return res;
+  }
 
-    max_rec_count = net_buf_pull_be16(buf);
-    cont_state_size = net_buf_pull_u8(buf);
+  if (buf->len < 3) {
+    BT_WARN("Malformed packet");
+    return BT_SDP_INVALID_SYNTAX;
+  }
 
-    /* Zero out the matching services beyond max_rec_count */
-    for (idx = 0U; idx < num_services; idx++) {
-        if (count == max_rec_count) {
-            matching_recs[idx] = NULL;
-            continue;
-        }
+  max_rec_count   = net_buf_pull_be16(buf);
+  cont_state_size = net_buf_pull_u8(buf);
 
-        if (matching_recs[idx]) {
-            count++;
-        }
+  /* Zero out the matching services beyond max_rec_count */
+  for (idx = 0U; idx < num_services; idx++) {
+    if (count == max_rec_count) {
+      matching_recs[idx] = NULL;
+      continue;
     }
 
-    /* We send out only SDP_SS_CONT_STATE_SIZE bytes continuation state in
-	 * responses, so expect only SDP_SS_CONT_STATE_SIZE bytes in requests
-	 */
-    if (cont_state_size) {
-        if (cont_state_size != SDP_SS_CONT_STATE_SIZE) {
-            BT_WARN("Invalid cont state size %u", cont_state_size);
-            return BT_SDP_INVALID_CSTATE;
-        }
-
-        if (buf->len < cont_state_size) {
-            BT_WARN("Malformed packet");
-            return BT_SDP_INVALID_SYNTAX;
-        }
+    if (matching_recs[idx]) {
+      count++;
+    }
+  }
 
-        cont_state = net_buf_pull_u8(buf);
-        /* We include total_recs in the continuation state. We calculate
-		 * it once and preserve it across all the partial responses
-		 */
-        total_recs = net_buf_pull_be16(buf);
+  /* We send out only SDP_SS_CONT_STATE_SIZE bytes continuation state in
+   * responses, so expect only SDP_SS_CONT_STATE_SIZE bytes in requests
+   */
+  if (cont_state_size) {
+    if (cont_state_size != SDP_SS_CONT_STATE_SIZE) {
+      BT_WARN("Invalid cont state size %u", cont_state_size);
+      return BT_SDP_INVALID_CSTATE;
     }
 
-    BT_DBG("max_rec_count %u, cont_state %u", max_rec_count, cont_state);
+    if (buf->len < cont_state_size) {
+      BT_WARN("Malformed packet");
+      return BT_SDP_INVALID_SYNTAX;
+    }
 
-    resp_buf = bt_sdp_create_pdu();
-    rsp = net_buf_add(resp_buf, sizeof(*rsp));
+    cont_state = net_buf_pull_u8(buf);
+    /* We include total_recs in the continuation state. We calculate
+     * it once and preserve it across all the partial responses
+     */
+    total_recs = net_buf_pull_be16(buf);
+  }
 
-    for (; cont_state < num_services; cont_state++) {
-        record = matching_recs[cont_state];
+  BT_DBG("max_rec_count %u, cont_state %u", max_rec_count, cont_state);
 
-        if (!record) {
-            continue;
-        }
+  resp_buf = bt_sdp_create_pdu();
+  rsp      = net_buf_add(resp_buf, sizeof(*rsp));
 
-        /* Calculate total recs only if it is first packet */
-        if (!cont_state_size) {
-            total_recs++;
-        }
+  for (; cont_state < num_services; cont_state++) {
+    record = matching_recs[cont_state];
 
-        if (pkt_full) {
-            continue;
-        }
+    if (!record) {
+      continue;
+    }
 
-        /* 4 bytes per Service Record Handle */
-        /* 4 bytes for ContinuationState */
-        if ((MIN(SDP_MTU, sdp->chan.tx.mtu) - resp_buf->len) <
-            (4 + 4 + sizeof(struct bt_sdp_hdr))) {
-            pkt_full = true;
-        }
+    /* Calculate total recs only if it is first packet */
+    if (!cont_state_size) {
+      total_recs++;
+    }
 
-        if (pkt_full) {
-            /* Packet exhausted: Add continuation state and break */
-            BT_DBG("Packet full, num_services_covered %u",
-                   cont_state);
-            net_buf_add_u8(resp_buf, SDP_SS_CONT_STATE_SIZE);
-            net_buf_add_u8(resp_buf, cont_state);
-
-            /* If it is the first packet of a partial response,
-			 * continue dry-running to calculate total_recs.
-			 * Else break
-			 */
-            if (cont_state_size) {
-                break;
-            }
-
-            continue;
-        }
+    if (pkt_full) {
+      continue;
+    }
 
-        /* Add the service record handle to the packet */
-        net_buf_add_be32(resp_buf, record->handle);
-        current_recs++;
+    /* 4 bytes per Service Record Handle */
+    /* 4 bytes for ContinuationState */
+    if ((MIN(SDP_MTU, sdp->chan.tx.mtu) - resp_buf->len) < (4 + 4 + sizeof(struct bt_sdp_hdr))) {
+      pkt_full = true;
     }
 
-    /* Add 0 continuation state if packet is exhausted */
-    if (!pkt_full) {
-        net_buf_add_u8(resp_buf, 0);
-    } else {
-        net_buf_add_be16(resp_buf, total_recs);
+    if (pkt_full) {
+      /* Packet exhausted: Add continuation state and break */
+      BT_DBG("Packet full, num_services_covered %u", cont_state);
+      net_buf_add_u8(resp_buf, SDP_SS_CONT_STATE_SIZE);
+      net_buf_add_u8(resp_buf, cont_state);
+
+      /* If it is the first packet of a partial response,
+       * continue dry-running to calculate total_recs.
+       * Else break
+       */
+      if (cont_state_size) {
+        break;
+      }
+
+      continue;
     }
 
-    rsp->total_recs = sys_cpu_to_be16(total_recs);
-    rsp->current_recs = sys_cpu_to_be16(current_recs);
+    /* Add the service record handle to the packet */
+    net_buf_add_be32(resp_buf, record->handle);
+    current_recs++;
+  }
 
-    BT_DBG("Sending response, len %u", resp_buf->len);
-    bt_sdp_send(&sdp->chan.chan, resp_buf, BT_SDP_SVC_SEARCH_RSP, tid);
+  /* Add 0 continuation state if packet is exhausted */
+  if (!pkt_full) {
+    net_buf_add_u8(resp_buf, 0);
+  } else {
+    net_buf_add_be16(resp_buf, total_recs);
+  }
 
-    return 0;
+  rsp->total_recs   = sys_cpu_to_be16(total_recs);
+  rsp->current_recs = sys_cpu_to_be16(current_recs);
+
+  BT_DBG("Sending response, len %u", resp_buf->len);
+  bt_sdp_send(&sdp->chan.chan, resp_buf, BT_SDP_SVC_SEARCH_RSP, tid);
+
+  return 0;
 }
 
 /* @brief Copies an attribute into an outgoing buffer
@@ -710,66 +669,59 @@ static uint16_t sdp_svc_search_req(struct bt_sdp *sdp, struct net_buf *buf,
  *  @return Size of the last data element that has been searched
  *  (used in recursion)
  */
-static uint32_t copy_attribute(struct bt_sdp_data_elem *elem,
-                               struct net_buf *buf, uint8_t nest_level)
-{
-    const uint8_t *cur_elem;
-    uint32_t size, seq_size, total_size;
-
-    /* Limit recursion depth to avoid stack overflows */
-    if (nest_level == SDP_DATA_ELEM_NEST_LEVEL_MAX) {
-        return 0;
-    }
+static uint32_t copy_attribute(struct bt_sdp_data_elem *elem, struct net_buf *buf, uint8_t nest_level) {
+  const uint8_t *cur_elem;
+  uint32_t       size, seq_size, total_size;
 
-    seq_size = elem->data_size;
-    total_size = elem->total_size;
-    cur_elem = elem->data;
-
-    /* Copy the header */
-    net_buf_add_u8(buf, elem->type);
-
-    switch (total_size - (seq_size + 1U)) {
-        case 1:
-            net_buf_add_u8(buf, elem->data_size);
-            break;
-        case 2:
-            net_buf_add_be16(buf, elem->data_size);
-            break;
-        case 4:
-            net_buf_add_be32(buf, elem->data_size);
-            break;
-    }
-
-    /* Recursively parse (till the last element is not another data element)
-	 * and then fill the elements
-	 */
-    if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_SEQ_UNSPEC ||
-        (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_ALT_UNSPEC) {
-        do {
-            size = copy_attribute((struct bt_sdp_data_elem *)
-                                      cur_elem,
-                                  buf, nest_level + 1);
-            cur_elem += sizeof(struct bt_sdp_data_elem);
-            seq_size -= size;
-        } while (seq_size);
-    } else if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_UINT8 ||
-               (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_INT8 ||
-               (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_UUID_UNSPEC) {
-        if (seq_size == 1U) {
-            net_buf_add_u8(buf, *((uint8_t *)elem->data));
-        } else if (seq_size == 2U) {
-            net_buf_add_be16(buf, *((uint16_t *)elem->data));
-        } else if (seq_size == 4U) {
-            net_buf_add_be32(buf, *((uint32_t *)elem->data));
-        } else {
-            /* TODO: Convert 32bit and 128bit values to big-endian*/
-            net_buf_add_mem(buf, elem->data, seq_size);
-        }
+  /* Limit recursion depth to avoid stack overflows */
+  if (nest_level == SDP_DATA_ELEM_NEST_LEVEL_MAX) {
+    return 0;
+  }
+
+  seq_size   = elem->data_size;
+  total_size = elem->total_size;
+  cur_elem   = elem->data;
+
+  /* Copy the header */
+  net_buf_add_u8(buf, elem->type);
+
+  switch (total_size - (seq_size + 1U)) {
+  case 1:
+    net_buf_add_u8(buf, elem->data_size);
+    break;
+  case 2:
+    net_buf_add_be16(buf, elem->data_size);
+    break;
+  case 4:
+    net_buf_add_be32(buf, elem->data_size);
+    break;
+  }
+
+  /* Recursively parse (till the last element is not another data element)
+   * and then fill the elements
+   */
+  if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_SEQ_UNSPEC || (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_ALT_UNSPEC) {
+    do {
+      size = copy_attribute((struct bt_sdp_data_elem *)cur_elem, buf, nest_level + 1);
+      cur_elem += sizeof(struct bt_sdp_data_elem);
+      seq_size -= size;
+    } while (seq_size);
+  } else if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_UINT8 || (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_INT8 || (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_UUID_UNSPEC) {
+    if (seq_size == 1U) {
+      net_buf_add_u8(buf, *((uint8_t *)elem->data));
+    } else if (seq_size == 2U) {
+      net_buf_add_be16(buf, *((uint16_t *)elem->data));
+    } else if (seq_size == 4U) {
+      net_buf_add_be32(buf, *((uint32_t *)elem->data));
     } else {
-        net_buf_add_mem(buf, elem->data, seq_size);
+      /* TODO: Convert 32bit and 128bit values to big-endian*/
+      net_buf_add_mem(buf, elem->data, seq_size);
     }
+  } else {
+    net_buf_add_mem(buf, elem->data, seq_size);
+  }
 
-    return total_size;
+  return total_size;
 }
 
 /* @brief SDP attribute iterator.
@@ -783,17 +735,14 @@ static uint32_t copy_attribute(struct bt_sdp_data_elem *elem,
  *
  *  @return Index of the attribute where the iterator stopped
  */
-static uint8_t bt_sdp_foreach_attr(struct bt_sdp_record *record, uint8_t idx,
-                                   bt_sdp_attr_func_t func, void *user_data)
-{
-    for (; idx < record->attr_count; idx++) {
-        if (func(&record->attrs[idx], idx, user_data) ==
-            BT_SDP_ITER_STOP) {
-            break;
-        }
+static uint8_t bt_sdp_foreach_attr(struct bt_sdp_record *record, uint8_t idx, bt_sdp_attr_func_t func, void *user_data) {
+  for (; idx < record->attr_count; idx++) {
+    if (func(&record->attrs[idx], idx, user_data) == BT_SDP_ITER_STOP) {
+      break;
     }
+  }
 
-    return idx;
+  return idx;
 }
 
 /* @brief Check if an attribute matches a range, and include it in the response
@@ -809,114 +758,105 @@ static uint8_t bt_sdp_foreach_attr(struct bt_sdp_record *record, uint8_t idx,
  *  @return BT_SDP_ITER_CONTINUE if should continue to the next attribute
  *   or BT_SDP_ITER_STOP to stop.
  */
-static uint8_t select_attrs(struct bt_sdp_attribute *attr, uint8_t att_idx,
-                            void *user_data)
-{
-    struct select_attrs_data *sad = user_data;
-    uint16_t att_id_lower, att_id_upper, att_id_cur, space;
-    uint32_t attr_size, seq_size;
-    uint8_t idx_filter;
-
-    for (idx_filter = 0U; idx_filter < sad->num_filters; idx_filter++) {
-        att_id_lower = (sad->filter[idx_filter] >> 16);
-        att_id_upper = (sad->filter[idx_filter]);
-        att_id_cur = attr->id;
-
-        /* Check for range values */
-        if (att_id_lower != 0xffff &&
-            (!IN_RANGE(att_id_cur, att_id_lower, att_id_upper))) {
-            continue;
-        }
+static uint8_t select_attrs(struct bt_sdp_attribute *attr, uint8_t att_idx, void *user_data) {
+  struct select_attrs_data *sad = user_data;
+  uint16_t                  att_id_lower, att_id_upper, att_id_cur, space;
+  uint32_t                  attr_size, seq_size;
+  uint8_t                   idx_filter;
 
-        /* Check for match values */
-        if (att_id_lower == 0xffff && att_id_cur != att_id_upper) {
-            continue;
-        }
+  for (idx_filter = 0U; idx_filter < sad->num_filters; idx_filter++) {
+    att_id_lower = (sad->filter[idx_filter] >> 16);
+    att_id_upper = (sad->filter[idx_filter]);
+    att_id_cur   = attr->id;
 
-        /* Attribute ID matches */
-
-        /* 3 bytes for Attribute ID */
-        attr_size = 3 + attr->val.total_size;
-
-        /* If this is the first attribute of the service, then we need
-		 * to account for the space required to add the per-service
-		 * data element sequence header as well.
-		 */
-        if ((sad->state->current_svc != sad->rec->index) &&
-            sad->new_service) {
-            /* 3 bytes for Per-Service Data Elem Seq declaration */
-            seq_size = attr_size + 3;
-        } else {
-            seq_size = attr_size;
-        }
+    /* Check for range values */
+    if (att_id_lower != 0xffff && (!IN_RANGE(att_id_cur, att_id_lower, att_id_upper))) {
+      continue;
+    }
 
-        if (sad->rsp_buf) {
-            space = MIN(SDP_MTU, sad->sdp->chan.tx.mtu) -
-                    sad->rsp_buf->len - sizeof(struct bt_sdp_hdr);
+    /* Check for match values */
+    if (att_id_lower == 0xffff && att_id_cur != att_id_upper) {
+      continue;
+    }
 
-            if ((!sad->state->pkt_full) &&
-                ((seq_size > sad->max_att_len) ||
-                 (space < seq_size + sad->cont_state_size))) {
-                /* Packet exhausted */
-                sad->state->pkt_full = true;
-            }
-        }
+    /* Attribute ID matches */
 
-        /* Keep filling data only if packet is not exhausted */
-        if (!sad->state->pkt_full && sad->rsp_buf) {
-            /* Add Per-Service Data Element Seq declaration once
-			 * only when we are starting from the first attribute
-			 */
-            if (!sad->seq &&
-                (sad->state->current_svc != sad->rec->index)) {
-                sad->seq = net_buf_add(sad->rsp_buf,
-                                       sizeof(*sad->seq));
-                sad->seq->type = BT_SDP_SEQ16;
-                sad->seq->size = 0U;
-            }
-
-            /* Add attribute ID */
-            net_buf_add_u8(sad->rsp_buf, BT_SDP_UINT16);
-            net_buf_add_be16(sad->rsp_buf, att_id_cur);
-
-            /* Add attribute value */
-            copy_attribute(&attr->val, sad->rsp_buf, 1);
-
-            sad->max_att_len -= seq_size;
-            sad->att_list_len += seq_size;
-            sad->state->last_att = att_idx;
-            sad->state->current_svc = sad->rec->index;
-        }
+    /* 3 bytes for Attribute ID */
+    attr_size = 3 + attr->val.total_size;
 
-        if (sad->seq) {
-            /* Keep adding the sequence size if this packet contains
-			 * the Per-Service Data Element Seq declaration header
-			 */
-            sad->seq->size += attr_size;
-            sad->state->att_list_size += seq_size;
-        } else {
-            /* Keep adding the total attr lists size if:
-			 * It's a dry-run, calculating the total attr lists size
-			 */
-            sad->state->att_list_size += seq_size;
-        }
+    /* If this is the first attribute of the service, then we need
+     * to account for the space required to add the per-service
+     * data element sequence header as well.
+     */
+    if ((sad->state->current_svc != sad->rec->index) && sad->new_service) {
+      /* 3 bytes for Per-Service Data Elem Seq declaration */
+      seq_size = attr_size + 3;
+    } else {
+      seq_size = attr_size;
+    }
 
-        sad->new_service = false;
-        break;
+    if (sad->rsp_buf) {
+      space = MIN(SDP_MTU, sad->sdp->chan.tx.mtu) - sad->rsp_buf->len - sizeof(struct bt_sdp_hdr);
+
+      if ((!sad->state->pkt_full) && ((seq_size > sad->max_att_len) || (space < seq_size + sad->cont_state_size))) {
+        /* Packet exhausted */
+        sad->state->pkt_full = true;
+      }
     }
 
-    /* End the search if:
-	 * 1. We have exhausted the packet
-	 * AND
-	 * 2. This packet doesn't contain the service element declaration header
-	 * AND
-	 * 3. This is not a dry-run (then we look for other attrs that match)
-	 */
-    if (sad->state->pkt_full && !sad->seq && sad->rsp_buf) {
-        return BT_SDP_ITER_STOP;
+    /* Keep filling data only if packet is not exhausted */
+    if (!sad->state->pkt_full && sad->rsp_buf) {
+      /* Add Per-Service Data Element Seq declaration once
+       * only when we are starting from the first attribute
+       */
+      if (!sad->seq && (sad->state->current_svc != sad->rec->index)) {
+        sad->seq       = net_buf_add(sad->rsp_buf, sizeof(*sad->seq));
+        sad->seq->type = BT_SDP_SEQ16;
+        sad->seq->size = 0U;
+      }
+
+      /* Add attribute ID */
+      net_buf_add_u8(sad->rsp_buf, BT_SDP_UINT16);
+      net_buf_add_be16(sad->rsp_buf, att_id_cur);
+
+      /* Add attribute value */
+      copy_attribute(&attr->val, sad->rsp_buf, 1);
+
+      sad->max_att_len -= seq_size;
+      sad->att_list_len += seq_size;
+      sad->state->last_att    = att_idx;
+      sad->state->current_svc = sad->rec->index;
     }
 
-    return BT_SDP_ITER_CONTINUE;
+    if (sad->seq) {
+      /* Keep adding the sequence size if this packet contains
+       * the Per-Service Data Element Seq declaration header
+       */
+      sad->seq->size += attr_size;
+      sad->state->att_list_size += seq_size;
+    } else {
+      /* Keep adding the total attr lists size if:
+       * It's a dry-run, calculating the total attr lists size
+       */
+      sad->state->att_list_size += seq_size;
+    }
+
+    sad->new_service = false;
+    break;
+  }
+
+  /* End the search if:
+   * 1. We have exhausted the packet
+   * AND
+   * 2. This packet doesn't contain the service element declaration header
+   * AND
+   * 3. This is not a dry-run (then we look for other attrs that match)
+   */
+  if (sad->state->pkt_full && !sad->seq && sad->rsp_buf) {
+    return BT_SDP_ITER_STOP;
+  }
+
+  return BT_SDP_ITER_CONTINUE;
 }
 
 /* @brief Creates attribute list in the given buffer
@@ -938,34 +878,30 @@ static uint8_t select_attrs(struct bt_sdp_attribute *attr, uint8_t att_idx,
  *
  *  @return len Length of the attribute list created
  */
-static uint16_t create_attr_list(struct bt_sdp *sdp, struct bt_sdp_record *record,
-                                 uint32_t *filter, uint8_t num_filters,
-                                 uint16_t max_att_len, uint8_t cont_state_size,
-                                 uint8_t next_att, struct search_state *state,
-                                 struct net_buf *rsp_buf)
-{
-    struct select_attrs_data sad;
-    uint8_t idx_att;
-
-    sad.num_filters = num_filters;
-    sad.rec = record;
-    sad.rsp_buf = rsp_buf;
-    sad.sdp = sdp;
-    sad.max_att_len = max_att_len;
-    sad.cont_state_size = cont_state_size;
-    sad.seq = NULL;
-    sad.filter = filter;
-    sad.state = state;
-    sad.att_list_len = 0U;
-    sad.new_service = true;
-
-    idx_att = bt_sdp_foreach_attr(sad.rec, next_att, select_attrs, &sad);
-
-    if (sad.seq) {
-        sad.seq->size = sys_cpu_to_be16(sad.seq->size);
-    }
-
-    return sad.att_list_len;
+static uint16_t create_attr_list(struct bt_sdp *sdp, struct bt_sdp_record *record, uint32_t *filter, uint8_t num_filters, uint16_t max_att_len, uint8_t cont_state_size, uint8_t next_att,
+                                 struct search_state *state, struct net_buf *rsp_buf) {
+  struct select_attrs_data sad;
+  uint8_t                  idx_att;
+
+  sad.num_filters     = num_filters;
+  sad.rec             = record;
+  sad.rsp_buf         = rsp_buf;
+  sad.sdp             = sdp;
+  sad.max_att_len     = max_att_len;
+  sad.cont_state_size = cont_state_size;
+  sad.seq             = NULL;
+  sad.filter          = filter;
+  sad.state           = state;
+  sad.att_list_len    = 0U;
+  sad.new_service     = true;
+
+  idx_att = bt_sdp_foreach_attr(sad.rec, next_att, select_attrs, &sad);
+
+  if (sad.seq) {
+    sad.seq->size = sys_cpu_to_be16(sad.seq->size);
+  }
+
+  return sad.att_list_len;
 }
 
 /* @brief Extracts the attribute search list from a buffer
@@ -982,53 +918,49 @@ static uint16_t create_attr_list(struct bt_sdp *sdp, struct bt_sdp_record *recor
  *
  *  @return 0 for success, or relevant error code
  */
-static uint16_t get_att_search_list(struct net_buf *buf, uint32_t *filter,
-                                    uint8_t *num_filters)
-{
-    struct bt_sdp_data_elem data_elem;
-    uint16_t res;
-    uint32_t size;
-
-    *num_filters = 0U;
-    res = parse_data_elem(buf, &data_elem);
-    if (res) {
-        return res;
-    }
+static uint16_t get_att_search_list(struct net_buf *buf, uint32_t *filter, uint8_t *num_filters) {
+  struct bt_sdp_data_elem data_elem;
+  uint16_t                res;
+  uint32_t                size;
 
-    size = data_elem.data_size;
+  *num_filters = 0U;
+  res          = parse_data_elem(buf, &data_elem);
+  if (res) {
+    return res;
+  }
 
-    while (size) {
-        res = parse_data_elem(buf, &data_elem);
-        if (res) {
-            return res;
-        }
+  size = data_elem.data_size;
 
-        if ((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_UINT8) {
-            BT_WARN("Invalid type %u in attribute ID list",
-                    data_elem.type);
-            return BT_SDP_INVALID_SYNTAX;
-        }
+  while (size) {
+    res = parse_data_elem(buf, &data_elem);
+    if (res) {
+      return res;
+    }
 
-        if (buf->len < data_elem.data_size) {
-            BT_WARN("Malformed packet");
-            return BT_SDP_INVALID_SYNTAX;
-        }
+    if ((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_UINT8) {
+      BT_WARN("Invalid type %u in attribute ID list", data_elem.type);
+      return BT_SDP_INVALID_SYNTAX;
+    }
 
-        /* This is an attribute ID */
-        if (data_elem.data_size == 2U) {
-            filter[(*num_filters)++] = 0xffff0000 |
-                                       net_buf_pull_be16(buf);
-        }
+    if (buf->len < data_elem.data_size) {
+      BT_WARN("Malformed packet");
+      return BT_SDP_INVALID_SYNTAX;
+    }
 
-        /* This is an attribute ID range */
-        if (data_elem.data_size == 4U) {
-            filter[(*num_filters)++] = net_buf_pull_be32(buf);
-        }
+    /* This is an attribute ID */
+    if (data_elem.data_size == 2U) {
+      filter[(*num_filters)++] = 0xffff0000 | net_buf_pull_be16(buf);
+    }
 
-        size -= data_elem.total_size;
+    /* This is an attribute ID range */
+    if (data_elem.data_size == 4U) {
+      filter[(*num_filters)++] = net_buf_pull_be32(buf);
     }
 
-    return 0;
+    size -= data_elem.total_size;
+  }
+
+  return 0;
 }
 
 /* @brief Check if a given handle matches that of the current service
@@ -1041,15 +973,14 @@ static uint16_t get_att_search_list(struct net_buf *buf, uint32_t *filter,
  *  @return BT_SDP_ITER_CONTINUE if should continue to the next record
  *   or BT_SDP_ITER_STOP to stop.
  */
-static uint8_t find_handle(struct bt_sdp_record *rec, void *user_data)
-{
-    uint32_t *svc_rec_hdl = user_data;
+static uint8_t find_handle(struct bt_sdp_record *rec, void *user_data) {
+  uint32_t *svc_rec_hdl = user_data;
 
-    if (rec->handle == *svc_rec_hdl) {
-        return BT_SDP_ITER_STOP;
-    }
+  if (rec->handle == *svc_rec_hdl) {
+    return BT_SDP_ITER_STOP;
+  }
 
-    return BT_SDP_ITER_CONTINUE;
+  return BT_SDP_ITER_CONTINUE;
 }
 
 /* @brief Handler for Service Attribute Request
@@ -1062,108 +993,99 @@ static uint8_t find_handle(struct bt_sdp_record *rec, void *user_data)
  *
  *  @return 0 for success, or relevant error code
  */
-static uint16_t sdp_svc_att_req(struct bt_sdp *sdp, struct net_buf *buf,
-                                uint16_t tid)
-{
-    uint32_t filter[MAX_NUM_ATT_ID_FILTER];
-    struct search_state state = {
-        .current_svc = SDP_INVALID,
-        .last_att = SDP_INVALID,
-        .pkt_full = false
-    };
-    struct bt_sdp_record *record;
-    struct bt_sdp_att_rsp *rsp;
-    struct net_buf *rsp_buf;
-    uint32_t svc_rec_hdl;
-    uint16_t max_att_len, res, att_list_len;
-    uint8_t num_filters, cont_state_size, next_att = 0U;
-
-    if (buf->len < 6) {
-        BT_WARN("Malformed packet");
-        return BT_SDP_INVALID_SYNTAX;
-    }
-
-    svc_rec_hdl = net_buf_pull_be32(buf);
-    max_att_len = net_buf_pull_be16(buf);
-
-    /* Set up the filters */
-    res = get_att_search_list(buf, filter, &num_filters);
-    if (res) {
-        /* Error in parsing */
-        return res;
-    }
-
-    if (buf->len < 1) {
-        BT_WARN("Malformed packet");
-        return BT_SDP_INVALID_SYNTAX;
-    }
-
-    cont_state_size = net_buf_pull_u8(buf);
-
-    /* We only send out 1 byte continuation state in responses,
-	 * so expect only 1 byte in requests
-	 */
-    if (cont_state_size) {
-        if (cont_state_size != SDP_SA_CONT_STATE_SIZE) {
-            BT_WARN("Invalid cont state size %u", cont_state_size);
-            return BT_SDP_INVALID_CSTATE;
-        }
-
-        if (buf->len < cont_state_size) {
-            BT_WARN("Malformed packet");
-            return BT_SDP_INVALID_SYNTAX;
-        }
-
-        state.last_att = net_buf_pull_u8(buf) + 1;
-        next_att = state.last_att;
-    }
-
-    BT_DBG("svc_rec_hdl %u, max_att_len 0x%04x, cont_state %u", svc_rec_hdl,
-           max_att_len, next_att);
-
-    /* Find the service */
-    record = bt_sdp_foreach_svc(find_handle, &svc_rec_hdl);
-
-    if (!record) {
-        BT_WARN("Handle %u not found", svc_rec_hdl);
-        return BT_SDP_INVALID_RECORD_HANDLE;
-    }
-
-    /* For partial responses, restore the search state */
-    if (cont_state_size) {
-        state.current_svc = record->index;
-    }
-
-    rsp_buf = bt_sdp_create_pdu();
-    rsp = net_buf_add(rsp_buf, sizeof(*rsp));
-
-    /* cont_state_size should include 1 byte header */
-    att_list_len = create_attr_list(sdp, record, filter, num_filters,
-                                    max_att_len, SDP_SA_CONT_STATE_SIZE + 1,
-                                    next_att, &state, rsp_buf);
-
-    if (!att_list_len) {
-        /* For empty responses, add an empty data element sequence */
-        net_buf_add_u8(rsp_buf, BT_SDP_SEQ8);
-        net_buf_add_u8(rsp_buf, 0);
-        att_list_len = 2U;
-    }
-
-    /* Add continuation state */
-    if (state.pkt_full) {
-        BT_DBG("Packet full, state.last_att %u", state.last_att);
-        net_buf_add_u8(rsp_buf, 1);
-        net_buf_add_u8(rsp_buf, state.last_att);
-    } else {
-        net_buf_add_u8(rsp_buf, 0);
-    }
-
-    rsp->att_list_len = sys_cpu_to_be16(att_list_len);
-
-    BT_DBG("Sending response, len %u", rsp_buf->len);
-    bt_sdp_send(&sdp->chan.chan, rsp_buf, BT_SDP_SVC_ATTR_RSP, tid);
-
-    return 0;
+static uint16_t sdp_svc_att_req(struct bt_sdp *sdp, struct net_buf *buf, uint16_t tid) {
+  uint32_t               filter[MAX_NUM_ATT_ID_FILTER];
+  struct search_state    state = {.current_svc = SDP_INVALID, .last_att = SDP_INVALID, .pkt_full = false};
+  struct bt_sdp_record  *record;
+  struct bt_sdp_att_rsp *rsp;
+  struct net_buf        *rsp_buf;
+  uint32_t               svc_rec_hdl;
+  uint16_t               max_att_len, res, att_list_len;
+  uint8_t                num_filters, cont_state_size, next_att = 0U;
+
+  if (buf->len < 6) {
+    BT_WARN("Malformed packet");
+    return BT_SDP_INVALID_SYNTAX;
+  }
+
+  svc_rec_hdl = net_buf_pull_be32(buf);
+  max_att_len = net_buf_pull_be16(buf);
+
+  /* Set up the filters */
+  res = get_att_search_list(buf, filter, &num_filters);
+  if (res) {
+    /* Error in parsing */
+    return res;
+  }
+
+  if (buf->len < 1) {
+    BT_WARN("Malformed packet");
+    return BT_SDP_INVALID_SYNTAX;
+  }
+
+  cont_state_size = net_buf_pull_u8(buf);
+
+  /* We only send out 1 byte continuation state in responses,
+   * so expect only 1 byte in requests
+   */
+  if (cont_state_size) {
+    if (cont_state_size != SDP_SA_CONT_STATE_SIZE) {
+      BT_WARN("Invalid cont state size %u", cont_state_size);
+      return BT_SDP_INVALID_CSTATE;
+    }
+
+    if (buf->len < cont_state_size) {
+      BT_WARN("Malformed packet");
+      return BT_SDP_INVALID_SYNTAX;
+    }
+
+    state.last_att = net_buf_pull_u8(buf) + 1;
+    next_att       = state.last_att;
+  }
+
+  BT_DBG("svc_rec_hdl %u, max_att_len 0x%04x, cont_state %u", svc_rec_hdl, max_att_len, next_att);
+
+  /* Find the service */
+  record = bt_sdp_foreach_svc(find_handle, &svc_rec_hdl);
+
+  if (!record) {
+    BT_WARN("Handle %u not found", svc_rec_hdl);
+    return BT_SDP_INVALID_RECORD_HANDLE;
+  }
+
+  /* For partial responses, restore the search state */
+  if (cont_state_size) {
+    state.current_svc = record->index;
+  }
+
+  rsp_buf = bt_sdp_create_pdu();
+  rsp     = net_buf_add(rsp_buf, sizeof(*rsp));
+
+  /* cont_state_size should include 1 byte header */
+  att_list_len = create_attr_list(sdp, record, filter, num_filters, max_att_len, SDP_SA_CONT_STATE_SIZE + 1, next_att, &state, rsp_buf);
+
+  if (!att_list_len) {
+    /* For empty responses, add an empty data element sequence */
+    net_buf_add_u8(rsp_buf, BT_SDP_SEQ8);
+    net_buf_add_u8(rsp_buf, 0);
+    att_list_len = 2U;
+  }
+
+  /* Add continuation state */
+  if (state.pkt_full) {
+    BT_DBG("Packet full, state.last_att %u", state.last_att);
+    net_buf_add_u8(rsp_buf, 1);
+    net_buf_add_u8(rsp_buf, state.last_att);
+  } else {
+    net_buf_add_u8(rsp_buf, 0);
+  }
+
+  rsp->att_list_len = sys_cpu_to_be16(att_list_len);
+
+  BT_DBG("Sending response, len %u", rsp_buf->len);
+  bt_sdp_send(&sdp->chan.chan, rsp_buf, BT_SDP_SVC_ATTR_RSP, tid);
+
+  return 0;
 }
 
 /* @brief Handler for Service Search Attribute Request
@@ -1176,157 +1098,144 @@ static uint16_t sdp_svc_att_req(struct bt_sdp *sdp, struct net_buf *buf,
  *
  *  @return 0 for success, or relevant error code
  */
-static uint16_t sdp_svc_search_att_req(struct bt_sdp *sdp, struct net_buf *buf,
-                                       uint16_t tid)
-{
-    uint32_t filter[MAX_NUM_ATT_ID_FILTER];
-    struct bt_sdp_record *matching_recs[BT_SDP_MAX_SERVICES];
-    struct search_state state = {
-        .att_list_size = 0,
-        .current_svc = SDP_INVALID,
-        .last_att = SDP_INVALID,
-        .pkt_full = false
-    };
-    struct net_buf *rsp_buf, *rsp_buf_cpy;
-    struct bt_sdp_record *record;
-    struct bt_sdp_att_rsp *rsp;
-    struct bt_sdp_data_elem_seq *seq = NULL;
-    uint16_t max_att_len, res, att_list_len = 0U;
-    uint8_t num_filters, cont_state_size, next_svc = 0U, next_att = 0U;
-    bool dry_run = false;
-
-    res = find_services(buf, matching_recs);
-    if (res) {
-        return res;
-    }
+static uint16_t sdp_svc_search_att_req(struct bt_sdp *sdp, struct net_buf *buf, uint16_t tid) {
+  uint32_t                     filter[MAX_NUM_ATT_ID_FILTER];
+  struct bt_sdp_record        *matching_recs[BT_SDP_MAX_SERVICES];
+  struct search_state          state = {.att_list_size = 0, .current_svc = SDP_INVALID, .last_att = SDP_INVALID, .pkt_full = false};
+  struct net_buf              *rsp_buf, *rsp_buf_cpy;
+  struct bt_sdp_record        *record;
+  struct bt_sdp_att_rsp       *rsp;
+  struct bt_sdp_data_elem_seq *seq = NULL;
+  uint16_t                     max_att_len, res, att_list_len         = 0U;
+  uint8_t                      num_filters, cont_state_size, next_svc = 0U, next_att = 0U;
+  bool                         dry_run = false;
 
-    if (buf->len < 2) {
-        BT_WARN("Malformed packet");
-        return BT_SDP_INVALID_SYNTAX;
-    }
+  res = find_services(buf, matching_recs);
+  if (res) {
+    return res;
+  }
 
-    max_att_len = net_buf_pull_be16(buf);
+  if (buf->len < 2) {
+    BT_WARN("Malformed packet");
+    return BT_SDP_INVALID_SYNTAX;
+  }
 
-    /* Set up the filters */
-    res = get_att_search_list(buf, filter, &num_filters);
+  max_att_len = net_buf_pull_be16(buf);
 
-    if (res) {
-        /* Error in parsing */
-        return res;
+  /* Set up the filters */
+  res = get_att_search_list(buf, filter, &num_filters);
+
+  if (res) {
+    /* Error in parsing */
+    return res;
+  }
+
+  if (buf->len < 1) {
+    BT_WARN("Malformed packet");
+    return BT_SDP_INVALID_SYNTAX;
+  }
+
+  cont_state_size = net_buf_pull_u8(buf);
+
+  /* We only send out 2 bytes continuation state in responses,
+   * so expect only 2 bytes in requests
+   */
+  if (cont_state_size) {
+    if (cont_state_size != SDP_SSA_CONT_STATE_SIZE) {
+      BT_WARN("Invalid cont state size %u", cont_state_size);
+      return BT_SDP_INVALID_CSTATE;
     }
 
-    if (buf->len < 1) {
-        BT_WARN("Malformed packet");
-        return BT_SDP_INVALID_SYNTAX;
+    if (buf->len < cont_state_size) {
+      BT_WARN("Malformed packet");
+      return BT_SDP_INVALID_SYNTAX;
     }
 
-    cont_state_size = net_buf_pull_u8(buf);
+    state.current_svc = net_buf_pull_u8(buf);
+    state.last_att    = net_buf_pull_u8(buf) + 1;
+    next_svc          = state.current_svc;
+    next_att          = state.last_att;
+  }
 
-    /* We only send out 2 bytes continuation state in responses,
-	 * so expect only 2 bytes in requests
-	 */
-    if (cont_state_size) {
-        if (cont_state_size != SDP_SSA_CONT_STATE_SIZE) {
-            BT_WARN("Invalid cont state size %u", cont_state_size);
-            return BT_SDP_INVALID_CSTATE;
-        }
+  BT_DBG("max_att_len 0x%04x, state.current_svc %u, state.last_att %u", max_att_len, state.current_svc, state.last_att);
 
-        if (buf->len < cont_state_size) {
-            BT_WARN("Malformed packet");
-            return BT_SDP_INVALID_SYNTAX;
-        }
+  rsp_buf = bt_sdp_create_pdu();
 
-        state.current_svc = net_buf_pull_u8(buf);
-        state.last_att = net_buf_pull_u8(buf) + 1;
-        next_svc = state.current_svc;
-        next_att = state.last_att;
-    }
+  rsp = net_buf_add(rsp_buf, sizeof(*rsp));
 
-    BT_DBG("max_att_len 0x%04x, state.current_svc %u, state.last_att %u",
-           max_att_len, state.current_svc, state.last_att);
+  /* Add headers only if this is not a partial response */
+  if (!cont_state_size) {
+    seq       = net_buf_add(rsp_buf, sizeof(*seq));
+    seq->type = BT_SDP_SEQ16;
+    seq->size = 0U;
 
-    rsp_buf = bt_sdp_create_pdu();
+    /* 3 bytes for Outer Data Element Sequence declaration */
+    att_list_len = 3U;
+  }
 
-    rsp = net_buf_add(rsp_buf, sizeof(*rsp));
+  rsp_buf_cpy = rsp_buf;
 
-    /* Add headers only if this is not a partial response */
-    if (!cont_state_size) {
-        seq = net_buf_add(rsp_buf, sizeof(*seq));
-        seq->type = BT_SDP_SEQ16;
-        seq->size = 0U;
+  for (; next_svc < num_services; next_svc++) {
+    record = matching_recs[next_svc];
 
-        /* 3 bytes for Outer Data Element Sequence declaration */
-        att_list_len = 3U;
+    if (!record) {
+      continue;
     }
 
-    rsp_buf_cpy = rsp_buf;
+    att_list_len += create_attr_list(sdp, record, filter, num_filters, max_att_len, SDP_SSA_CONT_STATE_SIZE + 1, next_att, &state, rsp_buf_cpy);
 
-    for (; next_svc < num_services; next_svc++) {
-        record = matching_recs[next_svc];
+    /* Check if packet is full and not dry run */
+    if (state.pkt_full && !dry_run) {
+      BT_DBG("Packet full, state.last_att %u", state.last_att);
+      dry_run = true;
 
-        if (!record) {
-            continue;
-        }
+      /* Add continuation state */
+      net_buf_add_u8(rsp_buf, 2);
+      net_buf_add_u8(rsp_buf, state.current_svc);
+      net_buf_add_u8(rsp_buf, state.last_att);
 
-        att_list_len += create_attr_list(sdp, record, filter,
-                                         num_filters, max_att_len,
-                                         SDP_SSA_CONT_STATE_SIZE + 1,
-                                         next_att, &state, rsp_buf_cpy);
-
-        /* Check if packet is full and not dry run */
-        if (state.pkt_full && !dry_run) {
-            BT_DBG("Packet full, state.last_att %u",
-                   state.last_att);
-            dry_run = true;
-
-            /* Add continuation state */
-            net_buf_add_u8(rsp_buf, 2);
-            net_buf_add_u8(rsp_buf, state.current_svc);
-            net_buf_add_u8(rsp_buf, state.last_att);
-
-            /* Break if it's not a partial response, else dry-run
-			 * Dry run: Look for other services that match
-			 */
-            if (cont_state_size) {
-                break;
-            }
-
-            rsp_buf_cpy = NULL;
-        }
+      /* Break if it's not a partial response, else dry-run
+       * Dry run: Look for other services that match
+       */
+      if (cont_state_size) {
+        break;
+      }
 
-        next_att = 0U;
+      rsp_buf_cpy = NULL;
     }
 
-    if (!dry_run) {
-        if (!att_list_len) {
-            /* For empty responses, add an empty data elem seq */
-            net_buf_add_u8(rsp_buf, BT_SDP_SEQ8);
-            net_buf_add_u8(rsp_buf, 0);
-            att_list_len = 2U;
-        }
-        /* Search exhausted */
-        net_buf_add_u8(rsp_buf, 0);
-    }
+    next_att = 0U;
+  }
 
-    rsp->att_list_len = sys_cpu_to_be16(att_list_len);
-    if (seq) {
-        seq->size = sys_cpu_to_be16(state.att_list_size);
+  if (!dry_run) {
+    if (!att_list_len) {
+      /* For empty responses, add an empty data elem seq */
+      net_buf_add_u8(rsp_buf, BT_SDP_SEQ8);
+      net_buf_add_u8(rsp_buf, 0);
+      att_list_len = 2U;
     }
+    /* Search exhausted */
+    net_buf_add_u8(rsp_buf, 0);
+  }
 
-    BT_DBG("Sending response, len %u", rsp_buf->len);
-    bt_sdp_send(&sdp->chan.chan, rsp_buf, BT_SDP_SVC_SEARCH_ATTR_RSP,
-                tid);
+  rsp->att_list_len = sys_cpu_to_be16(att_list_len);
+  if (seq) {
+    seq->size = sys_cpu_to_be16(state.att_list_size);
+  }
 
-    return 0;
+  BT_DBG("Sending response, len %u", rsp_buf->len);
+  bt_sdp_send(&sdp->chan.chan, rsp_buf, BT_SDP_SVC_SEARCH_ATTR_RSP, tid);
+
+  return 0;
 }
 
 static const struct {
-    uint8_t op_code;
-    uint16_t (*func)(struct bt_sdp *sdp, struct net_buf *buf, uint16_t tid);
+  uint8_t op_code;
+  uint16_t (*func)(struct bt_sdp *sdp, struct net_buf *buf, uint16_t tid);
 } handlers[] = {
-    { BT_SDP_SVC_SEARCH_REQ, sdp_svc_search_req },
-    { BT_SDP_SVC_ATTR_REQ, sdp_svc_att_req },
-    { BT_SDP_SVC_SEARCH_ATTR_REQ, sdp_svc_search_att_req },
+    {BT_SDP_SVC_SEARCH_REQ, sdp_svc_search_req},
+    {BT_SDP_SVC_ATTR_REQ, sdp_svc_att_req},
+    {BT_SDP_SVC_SEARCH_ATTR_REQ, sdp_svc_search_att_req},
 };
 
 /* @brief Callback for SDP data receive
@@ -1339,46 +1248,44 @@ static const struct {
  *
  *  @return None
  */
-static int bt_sdp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
-    struct bt_l2cap_br_chan *ch = CONTAINER_OF(chan,
-                                               struct bt_l2cap_br_chan, chan);
-    struct bt_sdp *sdp = CONTAINER_OF(ch, struct bt_sdp, chan);
-    struct bt_sdp_hdr *hdr;
-    uint16_t err = BT_SDP_INVALID_SYNTAX;
-    size_t i;
+static int bt_sdp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) {
+  struct bt_l2cap_br_chan *ch  = CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan);
+  struct bt_sdp           *sdp = CONTAINER_OF(ch, struct bt_sdp, chan);
+  struct bt_sdp_hdr       *hdr;
+  uint16_t                 err = BT_SDP_INVALID_SYNTAX;
+  size_t                   i;
 
-    BT_DBG("chan %p, ch %p, cid 0x%04x", chan, ch, ch->tx.cid);
+  BT_DBG("chan %p, ch %p, cid 0x%04x", chan, ch, ch->tx.cid);
 
-    BT_ASSERT(sdp);
+  BT_ASSERT(sdp);
 
-    if (buf->len < sizeof(*hdr)) {
-        BT_ERR("Too small SDP PDU received");
-        return 0;
-    }
+  if (buf->len < sizeof(*hdr)) {
+    BT_ERR("Too small SDP PDU received");
+    return 0;
+  }
 
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    BT_DBG("Received SDP code 0x%02x len %u", hdr->op_code, buf->len);
+  hdr = net_buf_pull_mem(buf, sizeof(*hdr));
+  BT_DBG("Received SDP code 0x%02x len %u", hdr->op_code, buf->len);
 
-    if (sys_cpu_to_be16(hdr->param_len) != buf->len) {
-        err = BT_SDP_INVALID_PDU_SIZE;
-    } else {
-        for (i = 0; i < ARRAY_SIZE(handlers); i++) {
-            if (hdr->op_code != handlers[i].op_code) {
-                continue;
-            }
+  if (sys_cpu_to_be16(hdr->param_len) != buf->len) {
+    err = BT_SDP_INVALID_PDU_SIZE;
+  } else {
+    for (i = 0; i < ARRAY_SIZE(handlers); i++) {
+      if (hdr->op_code != handlers[i].op_code) {
+        continue;
+      }
 
-            err = handlers[i].func(sdp, buf, hdr->tid);
-            break;
-        }
+      err = handlers[i].func(sdp, buf, hdr->tid);
+      break;
     }
+  }
 
-    if (err) {
-        BT_WARN("SDP error 0x%02x", err);
-        send_err_rsp(chan, err, hdr->tid);
-    }
+  if (err) {
+    BT_WARN("SDP error 0x%02x", err);
+    send_err_rsp(chan, err, hdr->tid);
+  }
 
-    return 0;
+  return 0;
 }
 
 /* @brief Callback for SDP connection accept
@@ -1391,1155 +1298,1095 @@ static int bt_sdp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
  *
  *  @return 0 for success, or relevant error code
  */
-static int bt_sdp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan)
-{
-    static const struct bt_l2cap_chan_ops ops = {
-        .connected = bt_sdp_connected,
-        .disconnected = bt_sdp_disconnected,
-        .recv = bt_sdp_recv,
-    };
-    int i;
-
-    BT_DBG("conn %p", conn);
-
-    for (i = 0; i < ARRAY_SIZE(bt_sdp_pool); i++) {
-        struct bt_sdp *sdp = &bt_sdp_pool[i];
-
-        if (sdp->chan.chan.conn) {
-            continue;
-        }
+static int bt_sdp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) {
+  static const struct bt_l2cap_chan_ops ops = {
+      .connected    = bt_sdp_connected,
+      .disconnected = bt_sdp_disconnected,
+      .recv         = bt_sdp_recv,
+  };
+  int i;
 
-        sdp->chan.chan.ops = &ops;
-        sdp->chan.rx.mtu = SDP_MTU;
+  BT_DBG("conn %p", conn);
 
-        *chan = &sdp->chan.chan;
+  for (i = 0; i < ARRAY_SIZE(bt_sdp_pool); i++) {
+    struct bt_sdp *sdp = &bt_sdp_pool[i];
 
-        return 0;
+    if (sdp->chan.chan.conn) {
+      continue;
     }
 
-    BT_ERR("No available SDP context for conn %p", conn);
+    sdp->chan.chan.ops = &ops;
+    sdp->chan.rx.mtu   = SDP_MTU;
 
-    return -ENOMEM;
+    *chan = &sdp->chan.chan;
+
+    return 0;
+  }
+
+  BT_ERR("No available SDP context for conn %p", conn);
+
+  return -ENOMEM;
 }
 
-void bt_sdp_init(void)
-{
+void bt_sdp_init(void) {
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    net_buf_init(&sdp_pool, CONFIG_BT_MAX_CONN, BT_L2CAP_BUF_SIZE(SDP_MTU), NULL);
+  net_buf_init(&sdp_pool, CONFIG_BT_MAX_CONN, BT_L2CAP_BUF_SIZE(SDP_MTU), NULL);
 #endif
-    static struct bt_l2cap_server server = {
-        .psm = SDP_PSM,
-        .accept = bt_sdp_accept,
-        .sec_level = BT_SECURITY_L0,
-    };
-    int res;
-
-    res = bt_l2cap_br_server_register(&server);
-    if (res) {
-        BT_ERR("L2CAP server registration failed with error %d", res);
-    }
+  static struct bt_l2cap_server server = {
+      .psm       = SDP_PSM,
+      .accept    = bt_sdp_accept,
+      .sec_level = BT_SECURITY_L0,
+  };
+  int res;
+
+  res = bt_l2cap_br_server_register(&server);
+  if (res) {
+    BT_ERR("L2CAP server registration failed with error %d", res);
+  }
 }
 
-int bt_sdp_register_service(struct bt_sdp_record *service)
-{
-    uint32_t handle = SDP_SERVICE_HANDLE_BASE;
+int bt_sdp_register_service(struct bt_sdp_record *service) {
+  uint32_t handle = SDP_SERVICE_HANDLE_BASE;
 
-    if (!service) {
-        BT_ERR("No service record specified");
-        return 0;
-    }
+  if (!service) {
+    BT_ERR("No service record specified");
+    return 0;
+  }
 
-    if (num_services == BT_SDP_MAX_SERVICES) {
-        BT_ERR("Reached max allowed registrations");
-        return -ENOMEM;
-    }
+  if (num_services == BT_SDP_MAX_SERVICES) {
+    BT_ERR("Reached max allowed registrations");
+    return -ENOMEM;
+  }
 
-    if (db) {
-        handle = db->handle + 1;
-    }
+  if (db) {
+    handle = db->handle + 1;
+  }
 
-    service->next = db;
-    service->index = num_services++;
-    service->handle = handle;
-    *((uint32_t *)(service->attrs[0].val.data)) = handle;
-    db = service;
+  service->next                               = db;
+  service->index                              = num_services++;
+  service->handle                             = handle;
+  *((uint32_t *)(service->attrs[0].val.data)) = handle;
+  db                                          = service;
 
-    BT_DBG("Service registered at %u", handle);
+  BT_DBG("Service registered at %u", handle);
 
-    return 0;
+  return 0;
 }
 
-#define GET_PARAM(__node) \
-    CONTAINER_OF(__node, struct bt_sdp_discover_params, _node)
+#define GET_PARAM(__node) CONTAINER_OF(__node, struct bt_sdp_discover_params, _node)
 
 /* ServiceSearchAttribute PDU, ref to BT Core 4.2, Vol 3, part B, 4.7.1 */
-static int sdp_client_ssa_search(struct bt_sdp_client *session)
-{
-    const struct bt_sdp_discover_params *param;
-    struct bt_sdp_hdr *hdr;
-    struct net_buf *buf;
-
-    /*
-	 * Select proper user params, if session->param is invalid it means
-	 * getting new UUID from top of to be resolved params list. Otherwise
-	 * the context is in a middle of partial SDP PDU responses and cached
-	 * value from context can be used.
-	 */
-    if (!session->param) {
-        param = GET_PARAM(sys_slist_peek_head(&session->reqs));
-    } else {
-        param = session->param;
-    }
-
-    if (!param) {
-        BT_WARN("No UUIDs to be resolved on remote");
-        return -EINVAL;
-    }
-
-    buf = bt_l2cap_create_pdu(&sdp_pool, 0);
-
-    hdr = net_buf_add(buf, sizeof(*hdr));
-
-    hdr->op_code = BT_SDP_SVC_SEARCH_ATTR_REQ;
-    /* BT_SDP_SEQ8 means length of sequence is on additional next byte */
-    net_buf_add_u8(buf, BT_SDP_SEQ8);
-
-    switch (param->uuid->type) {
-        case BT_UUID_TYPE_16:
-            /* Seq length */
-            net_buf_add_u8(buf, 0x03);
-            /* Seq type */
-            net_buf_add_u8(buf, BT_SDP_UUID16);
-            /* Seq value */
-            net_buf_add_be16(buf, BT_UUID_16(param->uuid)->val);
-            break;
-        case BT_UUID_TYPE_32:
-            net_buf_add_u8(buf, 0x05);
-            net_buf_add_u8(buf, BT_SDP_UUID32);
-            net_buf_add_be32(buf, BT_UUID_32(param->uuid)->val);
-            break;
-        case BT_UUID_TYPE_128:
-            net_buf_add_u8(buf, 0x11);
-            net_buf_add_u8(buf, BT_SDP_UUID128);
-            net_buf_add_mem(buf, BT_UUID_128(param->uuid)->val,
-                            ARRAY_SIZE(BT_UUID_128(param->uuid)->val));
-            break;
-        default:
-            BT_ERR("Unknown UUID type %u", param->uuid->type);
-            return -EINVAL;
-    }
-
-    /* Set attribute max bytes count to be returned from server */
-    net_buf_add_be16(buf, BT_SDP_MAX_ATTR_LEN);
-    /*
-	 * Sequence definition where data is sequence of elements and where
-	 * additional next byte points the size of elements within
-	 */
-    net_buf_add_u8(buf, BT_SDP_SEQ8);
+static int sdp_client_ssa_search(struct bt_sdp_client *session) {
+  const struct bt_sdp_discover_params *param;
+  struct bt_sdp_hdr                   *hdr;
+  struct net_buf                      *buf;
+
+  /*
+   * Select proper user params, if session->param is invalid it means
+   * getting new UUID from top of to be resolved params list. Otherwise
+   * the context is in a middle of partial SDP PDU responses and cached
+   * value from context can be used.
+   */
+  if (!session->param) {
+    param = GET_PARAM(sys_slist_peek_head(&session->reqs));
+  } else {
+    param = session->param;
+  }
+
+  if (!param) {
+    BT_WARN("No UUIDs to be resolved on remote");
+    return -EINVAL;
+  }
+
+  buf = bt_l2cap_create_pdu(&sdp_pool, 0);
+
+  hdr = net_buf_add(buf, sizeof(*hdr));
+
+  hdr->op_code = BT_SDP_SVC_SEARCH_ATTR_REQ;
+  /* BT_SDP_SEQ8 means length of sequence is on additional next byte */
+  net_buf_add_u8(buf, BT_SDP_SEQ8);
+
+  switch (param->uuid->type) {
+  case BT_UUID_TYPE_16:
+    /* Seq length */
+    net_buf_add_u8(buf, 0x03);
+    /* Seq type */
+    net_buf_add_u8(buf, BT_SDP_UUID16);
+    /* Seq value */
+    net_buf_add_be16(buf, BT_UUID_16(param->uuid)->val);
+    break;
+  case BT_UUID_TYPE_32:
     net_buf_add_u8(buf, 0x05);
-    /* Data element definition for two following 16bits range elements */
-    net_buf_add_u8(buf, BT_SDP_UINT32);
-    /* Get all attributes. It enables filter out wanted only attributes */
-    net_buf_add_be16(buf, 0x0000);
-    net_buf_add_be16(buf, 0xffff);
+    net_buf_add_u8(buf, BT_SDP_UUID32);
+    net_buf_add_be32(buf, BT_UUID_32(param->uuid)->val);
+    break;
+  case BT_UUID_TYPE_128:
+    net_buf_add_u8(buf, 0x11);
+    net_buf_add_u8(buf, BT_SDP_UUID128);
+    net_buf_add_mem(buf, BT_UUID_128(param->uuid)->val, ARRAY_SIZE(BT_UUID_128(param->uuid)->val));
+    break;
+  default:
+    BT_ERR("Unknown UUID type %u", param->uuid->type);
+    return -EINVAL;
+  }
+
+  /* Set attribute max bytes count to be returned from server */
+  net_buf_add_be16(buf, BT_SDP_MAX_ATTR_LEN);
+  /*
+   * Sequence definition where data is sequence of elements and where
+   * additional next byte points the size of elements within
+   */
+  net_buf_add_u8(buf, BT_SDP_SEQ8);
+  net_buf_add_u8(buf, 0x05);
+  /* Data element definition for two following 16bits range elements */
+  net_buf_add_u8(buf, BT_SDP_UINT32);
+  /* Get all attributes. It enables filter out wanted only attributes */
+  net_buf_add_be16(buf, 0x0000);
+  net_buf_add_be16(buf, 0xffff);
+
+  /*
+   * Update and validate PDU ContinuationState. Initial SSA Request has
+   * zero length continuation state since no interaction has place with
+   * server so far, otherwise use the original state taken from remote's
+   * last response PDU that is cached by SDP client context.
+   */
+  if (session->cstate.length == 0U) {
+    net_buf_add_u8(buf, 0x00);
+  } else {
+    net_buf_add_u8(buf, session->cstate.length);
+    net_buf_add_mem(buf, session->cstate.data, session->cstate.length);
+  }
+
+  /* set overall PDU length */
+  hdr->param_len = sys_cpu_to_be16(buf->len - sizeof(*hdr));
+
+  /* Update context param to the one being resolving now */
+  session->param = param;
+  session->tid++;
+  hdr->tid = sys_cpu_to_be16(session->tid);
+
+  return bt_l2cap_chan_send(&session->chan.chan, buf);
+}
 
-    /*
-	 * Update and validate PDU ContinuationState. Initial SSA Request has
-	 * zero length continuation state since no interaction has place with
-	 * server so far, otherwise use the original state taken from remote's
-	 * last response PDU that is cached by SDP client context.
-	 */
-    if (session->cstate.length == 0U) {
-        net_buf_add_u8(buf, 0x00);
-    } else {
-        net_buf_add_u8(buf, session->cstate.length);
-        net_buf_add_mem(buf, session->cstate.data,
-                        session->cstate.length);
+static void sdp_client_params_iterator(struct bt_sdp_client *session) {
+  struct bt_l2cap_chan          *chan = &session->chan.chan;
+  struct bt_sdp_discover_params *param, *tmp;
+
+  SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&session->reqs, param, tmp, _node) {
+    if (param != session->param) {
+      continue;
     }
 
-    /* set overall PDU length */
-    hdr->param_len = sys_cpu_to_be16(buf->len - sizeof(*hdr));
+    BT_DBG("");
 
-    /* Update context param to the one being resolving now */
-    session->param = param;
-    session->tid++;
-    hdr->tid = sys_cpu_to_be16(session->tid);
+    /* Remove already checked UUID node */
+    sys_slist_remove(&session->reqs, NULL, ¶m->_node);
+    /* Invalidate cached param in context */
+    session->param = NULL;
+    /* Reset continuation state in current context */
+    (void)memset(&session->cstate, 0, sizeof(session->cstate));
+
+    /* Check if there's valid next UUID */
+    if (!sys_slist_is_empty(&session->reqs)) {
+      sdp_client_ssa_search(session);
+      return;
+    }
 
-    return bt_l2cap_chan_send(&session->chan.chan, buf);
+    /* No UUID items, disconnect channel */
+    bt_l2cap_chan_disconnect(chan);
+    break;
+  }
 }
 
-static void sdp_client_params_iterator(struct bt_sdp_client *session)
-{
-    struct bt_l2cap_chan *chan = &session->chan.chan;
-    struct bt_sdp_discover_params *param, *tmp;
+static uint16_t sdp_client_get_total(struct bt_sdp_client *session, struct net_buf *buf, uint16_t *total) {
+  uint16_t pulled;
+  uint8_t  seq;
+
+  /*
+   * Pull value of total octets of all attributes available to be
+   * collected when response gets completed for given UUID. Such info can
+   * be get from the very first response frame after initial SSA request
+   * was sent. For subsequent calls related to the same SSA request input
+   * buf and in/out function parameters stays neutral.
+   */
+  if (session->cstate.length == 0U) {
+    seq    = net_buf_pull_u8(buf);
+    pulled = 1U;
+    switch (seq) {
+    case BT_SDP_SEQ8:
+      *total = net_buf_pull_u8(buf);
+      pulled += 1U;
+      break;
+    case BT_SDP_SEQ16:
+      *total = net_buf_pull_be16(buf);
+      pulled += 2U;
+      break;
+    default:
+      BT_WARN("Sequence type 0x%02x not handled", seq);
+      *total = 0U;
+      break;
+    }
+
+    BT_DBG("Total %u octets of all attributes", *total);
+  } else {
+    pulled = 0U;
+    *total = 0U;
+  }
+
+  return pulled;
+}
 
-    SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&session->reqs, param, tmp, _node)
-    {
-        if (param != session->param) {
-            continue;
-        }
+static uint16_t get_record_len(struct net_buf *buf) {
+  uint16_t len;
+  uint8_t  seq;
 
-        BT_DBG("");
+  seq = net_buf_pull_u8(buf);
 
-        /* Remove already checked UUID node */
-        sys_slist_remove(&session->reqs, NULL, ¶m->_node);
-        /* Invalidate cached param in context */
-        session->param = NULL;
-        /* Reset continuation state in current context */
-        (void)memset(&session->cstate, 0, sizeof(session->cstate));
+  switch (seq) {
+  case BT_SDP_SEQ8:
+    len = net_buf_pull_u8(buf);
+    break;
+  case BT_SDP_SEQ16:
+    len = net_buf_pull_be16(buf);
+    break;
+  default:
+    BT_WARN("Sequence type 0x%02x not handled", seq);
+    len = 0U;
+    break;
+  }
 
-        /* Check if there's valid next UUID */
-        if (!sys_slist_is_empty(&session->reqs)) {
-            sdp_client_ssa_search(session);
-            return;
-        }
+  BT_DBG("Record len %u", len);
 
-        /* No UUID items, disconnect channel */
-        bt_l2cap_chan_disconnect(chan);
-        break;
-    }
+  return len;
 }
 
-static uint16_t sdp_client_get_total(struct bt_sdp_client *session,
-                                     struct net_buf *buf, uint16_t *total)
-{
-    uint16_t pulled;
-    uint8_t seq;
+enum uuid_state {
+  UUID_NOT_RESOLVED,
+  UUID_RESOLVED,
+};
 
-    /*
-	 * Pull value of total octets of all attributes available to be
-	 * collected when response gets completed for given UUID. Such info can
-	 * be get from the very first response frame after initial SSA request
-	 * was sent. For subsequent calls related to the same SSA request input
-	 * buf and in/out function parameters stays neutral.
-	 */
-    if (session->cstate.length == 0U) {
-        seq = net_buf_pull_u8(buf);
-        pulled = 1U;
-        switch (seq) {
-            case BT_SDP_SEQ8:
-                *total = net_buf_pull_u8(buf);
-                pulled += 1U;
-                break;
-            case BT_SDP_SEQ16:
-                *total = net_buf_pull_be16(buf);
-                pulled += 2U;
-                break;
-            default:
-                BT_WARN("Sequence type 0x%02x not handled", seq);
-                *total = 0U;
-                break;
-        }
+static void sdp_client_notify_result(struct bt_sdp_client *session, enum uuid_state state) {
+  struct bt_conn             *conn = session->chan.chan.conn;
+  struct bt_sdp_client_result result;
+  uint16_t                    rec_len;
+  uint8_t                     user_ret;
 
-        BT_DBG("Total %u octets of all attributes", *total);
-    } else {
-        pulled = 0U;
-        *total = 0U;
-    }
-
-    return pulled;
-}
+  result.uuid = session->param->uuid;
 
-static uint16_t get_record_len(struct net_buf *buf)
-{
-    uint16_t len;
-    uint8_t seq;
+  if (state == UUID_NOT_RESOLVED) {
+    result.resp_buf         = NULL;
+    result.next_record_hint = false;
+    session->param->func(conn, &result);
+    return;
+  }
 
-    seq = net_buf_pull_u8(buf);
+  while (session->rec_buf->len) {
+    struct net_buf_simple_state buf_state;
 
-    switch (seq) {
-        case BT_SDP_SEQ8:
-            len = net_buf_pull_u8(buf);
-            break;
-        case BT_SDP_SEQ16:
-            len = net_buf_pull_be16(buf);
-            break;
-        default:
-            BT_WARN("Sequence type 0x%02x not handled", seq);
-            len = 0U;
-            break;
+    rec_len = get_record_len(session->rec_buf);
+    /* tell the user about multi record resolution */
+    if (session->rec_buf->len > rec_len) {
+      result.next_record_hint = true;
+    } else {
+      result.next_record_hint = false;
     }
 
-    BT_DBG("Record len %u", len);
+    /* save the original session buffer */
+    net_buf_simple_save(&session->rec_buf->b, &buf_state);
+    /* initialize internal result buffer instead of memcpy */
+    result.resp_buf = session->rec_buf;
+    /*
+     * Set user internal result buffer length as same as record
+     * length to fake user. User will see the individual record
+     * length as rec_len insted of whole session rec_buf length.
+     */
+    result.resp_buf->len = rec_len;
 
-    return len;
-}
+    user_ret = session->param->func(conn, &result);
 
-enum uuid_state {
-    UUID_NOT_RESOLVED,
-    UUID_RESOLVED,
-};
+    /* restore original session buffer */
+    net_buf_simple_restore(&session->rec_buf->b, &buf_state);
+    /*
+     * sync session buffer data length with next record chunk not
+     * send to user so far
+     */
+    net_buf_pull(session->rec_buf, rec_len);
+    if (user_ret == BT_SDP_DISCOVER_UUID_STOP) {
+      break;
+    }
+  }
+}
 
-static void sdp_client_notify_result(struct bt_sdp_client *session,
-                                     enum uuid_state state)
-{
-    struct bt_conn *conn = session->chan.chan.conn;
-    struct bt_sdp_client_result result;
-    uint16_t rec_len;
-    uint8_t user_ret;
+static int sdp_client_receive(struct bt_l2cap_chan *chan, struct net_buf *buf) {
+  struct bt_sdp_client     *session = SDP_CLIENT_CHAN(chan);
+  struct bt_sdp_hdr        *hdr;
+  struct bt_sdp_pdu_cstate *cstate;
+  uint16_t                  len, tid, frame_len;
+  uint16_t                  total;
 
-    result.uuid = session->param->uuid;
+  BT_DBG("session %p buf %p", session, buf);
 
-    if (state == UUID_NOT_RESOLVED) {
-        result.resp_buf = NULL;
-        result.next_record_hint = false;
-        session->param->func(conn, &result);
-        return;
-    }
+  if (buf->len < sizeof(*hdr)) {
+    BT_ERR("Too small SDP PDU");
+    return 0;
+  }
 
-    while (session->rec_buf->len) {
-        struct net_buf_simple_state buf_state;
+  hdr = net_buf_pull_mem(buf, sizeof(*hdr));
+  if (hdr->op_code == BT_SDP_ERROR_RSP) {
+    BT_INFO("Error SDP PDU response");
+    return 0;
+  }
 
-        rec_len = get_record_len(session->rec_buf);
-        /* tell the user about multi record resolution */
-        if (session->rec_buf->len > rec_len) {
-            result.next_record_hint = true;
-        } else {
-            result.next_record_hint = false;
-        }
+  len = sys_be16_to_cpu(hdr->param_len);
+  tid = sys_be16_to_cpu(hdr->tid);
 
-        /* save the original session buffer */
-        net_buf_simple_save(&session->rec_buf->b, &buf_state);
-        /* initialize internal result buffer instead of memcpy */
-        result.resp_buf = session->rec_buf;
-        /*
-		 * Set user internal result buffer length as same as record
-		 * length to fake user. User will see the individual record
-		 * length as rec_len insted of whole session rec_buf length.
-		 */
-        result.resp_buf->len = rec_len;
-
-        user_ret = session->param->func(conn, &result);
-
-        /* restore original session buffer */
-        net_buf_simple_restore(&session->rec_buf->b, &buf_state);
-        /*
-		 * sync session buffer data length with next record chunk not
-		 * send to user so far
-		 */
-        net_buf_pull(session->rec_buf, rec_len);
-        if (user_ret == BT_SDP_DISCOVER_UUID_STOP) {
-            break;
-        }
-    }
-}
+  BT_DBG("SDP PDU tid %u len %u", tid, len);
 
-static int sdp_client_receive(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
-    struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan);
-    struct bt_sdp_hdr *hdr;
-    struct bt_sdp_pdu_cstate *cstate;
-    uint16_t len, tid, frame_len;
-    uint16_t total;
+  if (buf->len != len) {
+    BT_ERR("SDP PDU length mismatch (%u != %u)", buf->len, len);
+    return 0;
+  }
 
-    BT_DBG("session %p buf %p", session, buf);
+  if (tid != session->tid) {
+    BT_ERR("Mismatch transaction ID value in SDP PDU");
+    return 0;
+  }
 
-    if (buf->len < sizeof(*hdr)) {
-        BT_ERR("Too small SDP PDU");
-        return 0;
+  switch (hdr->op_code) {
+  case BT_SDP_SVC_SEARCH_ATTR_RSP:
+    /* Get number of attributes in this frame. */
+    frame_len = net_buf_pull_be16(buf);
+    /* Check valid buf len for attribute list and cont state */
+    if (buf->len < frame_len + SDP_CONT_STATE_LEN_SIZE) {
+      BT_ERR("Invalid frame payload length");
+      return 0;
     }
-
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    if (hdr->op_code == BT_SDP_ERROR_RSP) {
-        BT_INFO("Error SDP PDU response");
-        return 0;
+    /* Check valid range of attributes length */
+    if (frame_len < 2) {
+      BT_ERR("Invalid attributes data length");
+      return 0;
     }
 
-    len = sys_be16_to_cpu(hdr->param_len);
-    tid = sys_be16_to_cpu(hdr->tid);
+    /* Get PDU continuation state */
+    cstate = (struct bt_sdp_pdu_cstate *)(buf->data + frame_len);
 
-    BT_DBG("SDP PDU tid %u len %u", tid, len);
+    if (cstate->length > BT_SDP_MAX_PDU_CSTATE_LEN) {
+      BT_ERR("Invalid SDP PDU Continuation State length %u", cstate->length);
+      return 0;
+    }
 
-    if (buf->len != len) {
-        BT_ERR("SDP PDU length mismatch (%u != %u)", buf->len, len);
-        return 0;
+    if ((frame_len + SDP_CONT_STATE_LEN_SIZE + cstate->length) > buf->len) {
+      BT_ERR("Invalid frame payload length");
+      return 0;
     }
 
-    if (tid != session->tid) {
-        BT_ERR("Mismatch transaction ID value in SDP PDU");
-        return 0;
+    /*
+     * No record found for given UUID. The check catches case when
+     * current response frame has Continuation State shortest and
+     * valid and this is the first response frame as well.
+     */
+    if (frame_len == 2U && cstate->length == 0U && session->cstate.length == 0U) {
+      BT_DBG("record for UUID 0x%s not found", bt_uuid_str(session->param->uuid));
+      /* Call user UUID handler */
+      sdp_client_notify_result(session, UUID_NOT_RESOLVED);
+      net_buf_pull(buf, frame_len + sizeof(cstate->length));
+      goto iterate;
     }
 
-    switch (hdr->op_code) {
-        case BT_SDP_SVC_SEARCH_ATTR_RSP:
-            /* Get number of attributes in this frame. */
-            frame_len = net_buf_pull_be16(buf);
-            /* Check valid buf len for attribute list and cont state */
-            if (buf->len < frame_len + SDP_CONT_STATE_LEN_SIZE) {
-                BT_ERR("Invalid frame payload length");
-                return 0;
-            }
-            /* Check valid range of attributes length */
-            if (frame_len < 2) {
-                BT_ERR("Invalid attributes data length");
-                return 0;
-            }
-
-            /* Get PDU continuation state */
-            cstate = (struct bt_sdp_pdu_cstate *)(buf->data + frame_len);
-
-            if (cstate->length > BT_SDP_MAX_PDU_CSTATE_LEN) {
-                BT_ERR("Invalid SDP PDU Continuation State length %u",
-                       cstate->length);
-                return 0;
-            }
-
-            if ((frame_len + SDP_CONT_STATE_LEN_SIZE + cstate->length) >
-                buf->len) {
-                BT_ERR("Invalid frame payload length");
-                return 0;
-            }
-
-            /*
-		 * No record found for given UUID. The check catches case when
-		 * current response frame has Continuation State shortest and
-		 * valid and this is the first response frame as well.
-		 */
-            if (frame_len == 2U && cstate->length == 0U &&
-                session->cstate.length == 0U) {
-                BT_DBG("record for UUID 0x%s not found",
-                       bt_uuid_str(session->param->uuid));
-                /* Call user UUID handler */
-                sdp_client_notify_result(session, UUID_NOT_RESOLVED);
-                net_buf_pull(buf, frame_len + sizeof(cstate->length));
-                goto iterate;
-            }
-
-            /* Get total value of all attributes to be collected */
-            frame_len -= sdp_client_get_total(session, buf, &total);
-
-            if (total > net_buf_tailroom(session->rec_buf)) {
-                BT_WARN("Not enough room for getting records data");
-                goto iterate;
-            }
-
-            net_buf_add_mem(session->rec_buf, buf->data, frame_len);
-            net_buf_pull(buf, frame_len);
-
-            /*
-		 * check if current response says there's next portion to be
-		 * fetched
-		 */
-            if (cstate->length) {
-                /* Cache original Continuation State in context */
-                memcpy(&session->cstate, cstate,
-                       sizeof(struct bt_sdp_pdu_cstate));
-
-                net_buf_pull(buf, cstate->length +
-                                      sizeof(cstate->length));
-
-                /* Request for next portion of attributes data */
-                sdp_client_ssa_search(session);
-                break;
-            }
-
-            net_buf_pull(buf, sizeof(cstate->length));
-
-            BT_DBG("UUID 0x%s resolved", bt_uuid_str(session->param->uuid));
-            sdp_client_notify_result(session, UUID_RESOLVED);
-        iterate:
-            /* Get next UUID and start resolving it */
-            sdp_client_params_iterator(session);
-            break;
-        default:
-            BT_DBG("PDU 0x%0x response not handled", hdr->op_code);
-            break;
+    /* Get total value of all attributes to be collected */
+    frame_len -= sdp_client_get_total(session, buf, &total);
+
+    if (total > net_buf_tailroom(session->rec_buf)) {
+      BT_WARN("Not enough room for getting records data");
+      goto iterate;
     }
 
-    return 0;
-}
+    net_buf_add_mem(session->rec_buf, buf->data, frame_len);
+    net_buf_pull(buf, frame_len);
 
-static int sdp_client_chan_connect(struct bt_sdp_client *session)
-{
-    return bt_l2cap_br_chan_connect(session->chan.chan.conn,
-                                    &session->chan.chan, SDP_PSM);
+    /*
+     * check if current response says there's next portion to be
+     * fetched
+     */
+    if (cstate->length) {
+      /* Cache original Continuation State in context */
+      memcpy(&session->cstate, cstate, sizeof(struct bt_sdp_pdu_cstate));
+
+      net_buf_pull(buf, cstate->length + sizeof(cstate->length));
+
+      /* Request for next portion of attributes data */
+      sdp_client_ssa_search(session);
+      break;
+    }
+
+    net_buf_pull(buf, sizeof(cstate->length));
+
+    BT_DBG("UUID 0x%s resolved", bt_uuid_str(session->param->uuid));
+    sdp_client_notify_result(session, UUID_RESOLVED);
+  iterate:
+    /* Get next UUID and start resolving it */
+    sdp_client_params_iterator(session);
+    break;
+  default:
+    BT_DBG("PDU 0x%0x response not handled", hdr->op_code);
+    break;
+  }
+
+  return 0;
 }
 
-static struct net_buf *sdp_client_alloc_buf(struct bt_l2cap_chan *chan)
-{
-    struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan);
-    struct net_buf *buf;
+static int sdp_client_chan_connect(struct bt_sdp_client *session) { return bt_l2cap_br_chan_connect(session->chan.chan.conn, &session->chan.chan, SDP_PSM); }
 
-    BT_DBG("session %p chan %p", session, chan);
+static struct net_buf *sdp_client_alloc_buf(struct bt_l2cap_chan *chan) {
+  struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan);
+  struct net_buf       *buf;
 
-    session->param = GET_PARAM(sys_slist_peek_head(&session->reqs));
+  BT_DBG("session %p chan %p", session, chan);
 
-    buf = net_buf_alloc(session->param->pool, K_FOREVER);
-    __ASSERT_NO_MSG(buf);
+  session->param = GET_PARAM(sys_slist_peek_head(&session->reqs));
 
-    return buf;
+  buf = net_buf_alloc(session->param->pool, K_FOREVER);
+  __ASSERT_NO_MSG(buf);
+
+  return buf;
 }
 
-static void sdp_client_connected(struct bt_l2cap_chan *chan)
-{
-    struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan);
+static void sdp_client_connected(struct bt_l2cap_chan *chan) {
+  struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan);
 
-    BT_DBG("session %p chan %p connected", session, chan);
+  BT_DBG("session %p chan %p connected", session, chan);
 
-    session->rec_buf = chan->ops->alloc_buf(chan);
+  session->rec_buf = chan->ops->alloc_buf(chan);
 
-    sdp_client_ssa_search(session);
+  sdp_client_ssa_search(session);
 }
 
-static void sdp_client_disconnected(struct bt_l2cap_chan *chan)
-{
-    struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan);
+static void sdp_client_disconnected(struct bt_l2cap_chan *chan) {
+  struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan);
 
-    BT_DBG("session %p chan %p disconnected", session, chan);
+  BT_DBG("session %p chan %p disconnected", session, chan);
 
-    net_buf_unref(session->rec_buf);
+  net_buf_unref(session->rec_buf);
 
-    /*
-	 * Reset session excluding L2CAP channel member. Let's the channel
-	 * resets autonomous.
-	 */
-    (void)memset(&session->reqs, 0,
-                 sizeof(*session) - sizeof(session->chan));
+  /*
+   * Reset session excluding L2CAP channel member. Let's the channel
+   * resets autonomous.
+   */
+  (void)memset(&session->reqs, 0, sizeof(*session) - sizeof(session->chan));
 }
 
 static const struct bt_l2cap_chan_ops sdp_client_chan_ops = {
-    .connected = sdp_client_connected,
+    .connected    = sdp_client_connected,
     .disconnected = sdp_client_disconnected,
-    .recv = sdp_client_receive,
-    .alloc_buf = sdp_client_alloc_buf,
+    .recv         = sdp_client_receive,
+    .alloc_buf    = sdp_client_alloc_buf,
 };
 
-static struct bt_sdp_client *sdp_client_new_session(struct bt_conn *conn)
-{
-    int i;
+static struct bt_sdp_client *sdp_client_new_session(struct bt_conn *conn) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(bt_sdp_client_pool); i++) {
-        struct bt_sdp_client *session = &bt_sdp_client_pool[i];
-        int err;
+  for (i = 0; i < ARRAY_SIZE(bt_sdp_client_pool); i++) {
+    struct bt_sdp_client *session = &bt_sdp_client_pool[i];
+    int                   err;
 
-        if (session->chan.chan.conn) {
-            continue;
-        }
-
-        sys_slist_init(&session->reqs);
+    if (session->chan.chan.conn) {
+      continue;
+    }
 
-        session->chan.chan.ops = &sdp_client_chan_ops;
-        session->chan.chan.conn = conn;
-        session->chan.rx.mtu = SDP_CLIENT_MTU;
+    sys_slist_init(&session->reqs);
 
-        err = sdp_client_chan_connect(session);
-        if (err) {
-            (void)memset(session, 0, sizeof(*session));
-            BT_ERR("Cannot connect %d", err);
-            return NULL;
-        }
+    session->chan.chan.ops  = &sdp_client_chan_ops;
+    session->chan.chan.conn = conn;
+    session->chan.rx.mtu    = SDP_CLIENT_MTU;
 
-        return session;
+    err = sdp_client_chan_connect(session);
+    if (err) {
+      (void)memset(session, 0, sizeof(*session));
+      BT_ERR("Cannot connect %d", err);
+      return NULL;
     }
 
-    BT_ERR("No available SDP client context");
+    return session;
+  }
+
+  BT_ERR("No available SDP client context");
 
-    return NULL;
+  return NULL;
 }
 
-static struct bt_sdp_client *sdp_client_get_session(struct bt_conn *conn)
-{
-    int i;
+static struct bt_sdp_client *sdp_client_get_session(struct bt_conn *conn) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(bt_sdp_client_pool); i++) {
-        if (bt_sdp_client_pool[i].chan.chan.conn == conn) {
-            return &bt_sdp_client_pool[i];
-        }
+  for (i = 0; i < ARRAY_SIZE(bt_sdp_client_pool); i++) {
+    if (bt_sdp_client_pool[i].chan.chan.conn == conn) {
+      return &bt_sdp_client_pool[i];
     }
+  }
 
-    /*
-	 * Try to allocate session context since not found in pool and attempt
-	 * connect to remote SDP endpoint.
-	 */
-    return sdp_client_new_session(conn);
+  /*
+   * Try to allocate session context since not found in pool and attempt
+   * connect to remote SDP endpoint.
+   */
+  return sdp_client_new_session(conn);
 }
 
-int bt_sdp_discover(struct bt_conn *conn,
-                    const struct bt_sdp_discover_params *params)
-{
-    struct bt_sdp_client *session;
+int bt_sdp_discover(struct bt_conn *conn, const struct bt_sdp_discover_params *params) {
+  struct bt_sdp_client *session;
 
-    if (!params || !params->uuid || !params->func || !params->pool) {
-        BT_WARN("Invalid user params");
-        return -EINVAL;
-    }
+  if (!params || !params->uuid || !params->func || !params->pool) {
+    BT_WARN("Invalid user params");
+    return -EINVAL;
+  }
 
-    session = sdp_client_get_session(conn);
-    if (!session) {
-        return -ENOMEM;
-    }
+  session = sdp_client_get_session(conn);
+  if (!session) {
+    return -ENOMEM;
+  }
 
-    sys_slist_append(&session->reqs, (sys_snode_t *)¶ms->_node);
+  sys_slist_append(&session->reqs, (sys_snode_t *)¶ms->_node);
 
-    return 0;
+  return 0;
 }
 
 /* Helper getting length of data determined by DTD for integers */
-static inline ssize_t sdp_get_int_len(const uint8_t *data, size_t len)
-{
-    BT_ASSERT(data);
-
-    switch (data[0]) {
-        case BT_SDP_DATA_NIL:
-            return 1;
-        case BT_SDP_BOOL:
-        case BT_SDP_INT8:
-        case BT_SDP_UINT8:
-            if (len < 2) {
-                break;
-            }
-
-            return 2;
-        case BT_SDP_INT16:
-        case BT_SDP_UINT16:
-            if (len < 3) {
-                break;
-            }
-
-            return 3;
-        case BT_SDP_INT32:
-        case BT_SDP_UINT32:
-            if (len < 5) {
-                break;
-            }
-
-            return 5;
-        case BT_SDP_INT64:
-        case BT_SDP_UINT64:
-            if (len < 9) {
-                break;
-            }
-
-            return 9;
-        case BT_SDP_INT128:
-        case BT_SDP_UINT128:
-        default:
-            BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
-            return -EINVAL;
-    }
-
-    BT_ERR("Too short buffer length %zu", len);
-    return -EMSGSIZE;
+static inline ssize_t sdp_get_int_len(const uint8_t *data, size_t len) {
+  BT_ASSERT(data);
+
+  switch (data[0]) {
+  case BT_SDP_DATA_NIL:
+    return 1;
+  case BT_SDP_BOOL:
+  case BT_SDP_INT8:
+  case BT_SDP_UINT8:
+    if (len < 2) {
+      break;
+    }
+
+    return 2;
+  case BT_SDP_INT16:
+  case BT_SDP_UINT16:
+    if (len < 3) {
+      break;
+    }
+
+    return 3;
+  case BT_SDP_INT32:
+  case BT_SDP_UINT32:
+    if (len < 5) {
+      break;
+    }
+
+    return 5;
+  case BT_SDP_INT64:
+  case BT_SDP_UINT64:
+    if (len < 9) {
+      break;
+    }
+
+    return 9;
+  case BT_SDP_INT128:
+  case BT_SDP_UINT128:
+  default:
+    BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
+    return -EINVAL;
+  }
+
+  BT_ERR("Too short buffer length %zu", len);
+  return -EMSGSIZE;
 }
 
 /* Helper getting length of data determined by DTD for UUID */
-static inline ssize_t sdp_get_uuid_len(const uint8_t *data, size_t len)
-{
-    BT_ASSERT(data);
-
-    switch (data[0]) {
-        case BT_SDP_UUID16:
-            if (len < 3) {
-                break;
-            }
-
-            return 3;
-        case BT_SDP_UUID32:
-            if (len < 5) {
-                break;
-            }
-
-            return 5;
-        case BT_SDP_UUID128:
-        default:
-            BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
-            return -EINVAL;
-    }
-
-    BT_ERR("Too short buffer length %zu", len);
-    return -EMSGSIZE;
+static inline ssize_t sdp_get_uuid_len(const uint8_t *data, size_t len) {
+  BT_ASSERT(data);
+
+  switch (data[0]) {
+  case BT_SDP_UUID16:
+    if (len < 3) {
+      break;
+    }
+
+    return 3;
+  case BT_SDP_UUID32:
+    if (len < 5) {
+      break;
+    }
+
+    return 5;
+  case BT_SDP_UUID128:
+  default:
+    BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
+    return -EINVAL;
+  }
+
+  BT_ERR("Too short buffer length %zu", len);
+  return -EMSGSIZE;
 }
 
 /* Helper getting length of data determined by DTD for strings */
-static inline ssize_t sdp_get_str_len(const uint8_t *data, size_t len)
-{
-    const uint8_t *pnext;
+static inline ssize_t sdp_get_str_len(const uint8_t *data, size_t len) {
+  const uint8_t *pnext;
 
-    BT_ASSERT(data);
+  BT_ASSERT(data);
 
-    /* validate len for pnext safe use to read next 8bit value */
-    if (len < 2) {
-        goto err;
-    }
-
-    pnext = data + sizeof(uint8_t);
+  /* validate len for pnext safe use to read next 8bit value */
+  if (len < 2) {
+    goto err;
+  }
 
-    switch (data[0]) {
-        case BT_SDP_TEXT_STR8:
-        case BT_SDP_URL_STR8:
-            if (len < (2 + pnext[0])) {
-                break;
-            }
+  pnext = data + sizeof(uint8_t);
 
-            return 2 + pnext[0];
-        case BT_SDP_TEXT_STR16:
-        case BT_SDP_URL_STR16:
-            /* validate len for pnext safe use to read 16bit value */
-            if (len < 3) {
-                break;
-            }
+  switch (data[0]) {
+  case BT_SDP_TEXT_STR8:
+  case BT_SDP_URL_STR8:
+    if (len < (2 + pnext[0])) {
+      break;
+    }
 
-            if (len < (3 + sys_get_be16(pnext))) {
-                break;
-            }
+    return 2 + pnext[0];
+  case BT_SDP_TEXT_STR16:
+  case BT_SDP_URL_STR16:
+    /* validate len for pnext safe use to read 16bit value */
+    if (len < 3) {
+      break;
+    }
 
-            return 3 + sys_get_be16(pnext);
-        case BT_SDP_TEXT_STR32:
-        case BT_SDP_URL_STR32:
-        default:
-            BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
-            return -EINVAL;
+    if (len < (3 + sys_get_be16(pnext))) {
+      break;
     }
+
+    return 3 + sys_get_be16(pnext);
+  case BT_SDP_TEXT_STR32:
+  case BT_SDP_URL_STR32:
+  default:
+    BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
+    return -EINVAL;
+  }
 err:
-    BT_ERR("Too short buffer length %zu", len);
-    return -EMSGSIZE;
+  BT_ERR("Too short buffer length %zu", len);
+  return -EMSGSIZE;
 }
 
 /* Helper getting length of data determined by DTD for sequences */
-static inline ssize_t sdp_get_seq_len(const uint8_t *data, size_t len)
-{
-    const uint8_t *pnext;
-
-    BT_ASSERT(data);
+static inline ssize_t sdp_get_seq_len(const uint8_t *data, size_t len) {
+  const uint8_t *pnext;
 
-    /* validate len for pnext safe use to read 8bit bit value */
-    if (len < 2) {
-        goto err;
-    }
+  BT_ASSERT(data);
 
-    pnext = data + sizeof(uint8_t);
+  /* validate len for pnext safe use to read 8bit bit value */
+  if (len < 2) {
+    goto err;
+  }
 
-    switch (data[0]) {
-        case BT_SDP_SEQ8:
-        case BT_SDP_ALT8:
-            if (len < (2 + pnext[0])) {
-                break;
-            }
+  pnext = data + sizeof(uint8_t);
 
-            return 2 + pnext[0];
-        case BT_SDP_SEQ16:
-        case BT_SDP_ALT16:
-            /* validate len for pnext safe use to read 16bit value */
-            if (len < 3) {
-                break;
-            }
+  switch (data[0]) {
+  case BT_SDP_SEQ8:
+  case BT_SDP_ALT8:
+    if (len < (2 + pnext[0])) {
+      break;
+    }
 
-            if (len < (3 + sys_get_be16(pnext))) {
-                break;
-            }
+    return 2 + pnext[0];
+  case BT_SDP_SEQ16:
+  case BT_SDP_ALT16:
+    /* validate len for pnext safe use to read 16bit value */
+    if (len < 3) {
+      break;
+    }
 
-            return 3 + sys_get_be16(pnext);
-        case BT_SDP_SEQ32:
-        case BT_SDP_ALT32:
-        default:
-            BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
-            return -EINVAL;
+    if (len < (3 + sys_get_be16(pnext))) {
+      break;
     }
+
+    return 3 + sys_get_be16(pnext);
+  case BT_SDP_SEQ32:
+  case BT_SDP_ALT32:
+  default:
+    BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
+    return -EINVAL;
+  }
 err:
-    BT_ERR("Too short buffer length %zu", len);
-    return -EMSGSIZE;
+  BT_ERR("Too short buffer length %zu", len);
+  return -EMSGSIZE;
 }
 
 /* Helper getting length of attribute value data */
-static ssize_t sdp_get_attr_value_len(const uint8_t *data, size_t len)
-{
-    BT_ASSERT(data);
-
-    BT_DBG("Attr val DTD 0x%02x", data[0]);
-
-    switch (data[0]) {
-        case BT_SDP_DATA_NIL:
-        case BT_SDP_BOOL:
-        case BT_SDP_UINT8:
-        case BT_SDP_UINT16:
-        case BT_SDP_UINT32:
-        case BT_SDP_UINT64:
-        case BT_SDP_UINT128:
-        case BT_SDP_INT8:
-        case BT_SDP_INT16:
-        case BT_SDP_INT32:
-        case BT_SDP_INT64:
-        case BT_SDP_INT128:
-            return sdp_get_int_len(data, len);
-        case BT_SDP_UUID16:
-        case BT_SDP_UUID32:
-        case BT_SDP_UUID128:
-            return sdp_get_uuid_len(data, len);
-        case BT_SDP_TEXT_STR8:
-        case BT_SDP_TEXT_STR16:
-        case BT_SDP_TEXT_STR32:
-        case BT_SDP_URL_STR8:
-        case BT_SDP_URL_STR16:
-        case BT_SDP_URL_STR32:
-            return sdp_get_str_len(data, len);
-        case BT_SDP_SEQ8:
-        case BT_SDP_SEQ16:
-        case BT_SDP_SEQ32:
-        case BT_SDP_ALT8:
-        case BT_SDP_ALT16:
-        case BT_SDP_ALT32:
-            return sdp_get_seq_len(data, len);
-        default:
-            BT_ERR("Unknown DTD 0x%02x", data[0]);
-            return -EINVAL;
-    }
+static ssize_t sdp_get_attr_value_len(const uint8_t *data, size_t len) {
+  BT_ASSERT(data);
+
+  BT_DBG("Attr val DTD 0x%02x", data[0]);
+
+  switch (data[0]) {
+  case BT_SDP_DATA_NIL:
+  case BT_SDP_BOOL:
+  case BT_SDP_UINT8:
+  case BT_SDP_UINT16:
+  case BT_SDP_UINT32:
+  case BT_SDP_UINT64:
+  case BT_SDP_UINT128:
+  case BT_SDP_INT8:
+  case BT_SDP_INT16:
+  case BT_SDP_INT32:
+  case BT_SDP_INT64:
+  case BT_SDP_INT128:
+    return sdp_get_int_len(data, len);
+  case BT_SDP_UUID16:
+  case BT_SDP_UUID32:
+  case BT_SDP_UUID128:
+    return sdp_get_uuid_len(data, len);
+  case BT_SDP_TEXT_STR8:
+  case BT_SDP_TEXT_STR16:
+  case BT_SDP_TEXT_STR32:
+  case BT_SDP_URL_STR8:
+  case BT_SDP_URL_STR16:
+  case BT_SDP_URL_STR32:
+    return sdp_get_str_len(data, len);
+  case BT_SDP_SEQ8:
+  case BT_SDP_SEQ16:
+  case BT_SDP_SEQ32:
+  case BT_SDP_ALT8:
+  case BT_SDP_ALT16:
+  case BT_SDP_ALT32:
+    return sdp_get_seq_len(data, len);
+  default:
+    BT_ERR("Unknown DTD 0x%02x", data[0]);
+    return -EINVAL;
+  }
 }
 
 /* Type holding UUID item and related to it specific information. */
 struct bt_sdp_uuid_desc {
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 uuid16;
-        struct bt_uuid_32 uuid32;
-    };
-    uint16_t attr_id;
-    uint8_t *params;
-    uint16_t params_len;
+  union {
+    struct bt_uuid    uuid;
+    struct bt_uuid_16 uuid16;
+    struct bt_uuid_32 uuid32;
+  };
+  uint16_t attr_id;
+  uint8_t *params;
+  uint16_t params_len;
 };
 
 /* Generic attribute item collector. */
 struct bt_sdp_attr_item {
-    /*  Attribute identifier. */
-    uint16_t attr_id;
-    /*  Address of beginning attribute value taken from original buffer
-	 *  holding response from server.
-	 */
-    uint8_t *val;
-    /*  Says about the length of attribute value. */
-    uint16_t len;
+  /*  Attribute identifier. */
+  uint16_t attr_id;
+  /*  Address of beginning attribute value taken from original buffer
+   *  holding response from server.
+   */
+  uint8_t *val;
+  /*  Says about the length of attribute value. */
+  uint16_t len;
 };
 
-static int bt_sdp_get_attr(const struct net_buf *buf,
-                           struct bt_sdp_attr_item *attr, uint16_t attr_id)
-{
-    uint8_t *data;
-    uint16_t id;
+static int bt_sdp_get_attr(const struct net_buf *buf, struct bt_sdp_attr_item *attr, uint16_t attr_id) {
+  uint8_t *data;
+  uint16_t id;
 
-    data = buf->data;
-    while (data - buf->data < buf->len) {
-        ssize_t dlen;
+  data = buf->data;
+  while (data - buf->data < buf->len) {
+    ssize_t dlen;
 
-        /* data need to point to attribute id descriptor field (DTD)*/
-        if (data[0] != BT_SDP_UINT16) {
-            BT_ERR("Invalid descriptor 0x%02x", data[0]);
-            return -EINVAL;
-        }
-
-        data += sizeof(uint8_t);
-        id = sys_get_be16(data);
-        BT_DBG("Attribute ID 0x%04x", id);
-        data += sizeof(uint16_t);
+    /* data need to point to attribute id descriptor field (DTD)*/
+    if (data[0] != BT_SDP_UINT16) {
+      BT_ERR("Invalid descriptor 0x%02x", data[0]);
+      return -EINVAL;
+    }
 
-        dlen = sdp_get_attr_value_len(data,
-                                      buf->len - (data - buf->data));
-        if (dlen < 0) {
-            BT_ERR("Invalid attribute value data");
-            return -EINVAL;
-        }
+    data += sizeof(uint8_t);
+    id = sys_get_be16(data);
+    BT_DBG("Attribute ID 0x%04x", id);
+    data += sizeof(uint16_t);
 
-        if (id == attr_id) {
-            BT_DBG("Attribute ID 0x%04x Value found", id);
-            /*
-			 * Initialize attribute value buffer data using selected
-			 * data slice from original buffer.
-			 */
-            attr->val = data;
-            attr->len = dlen;
-            attr->attr_id = id;
-            return 0;
-        }
+    dlen = sdp_get_attr_value_len(data, buf->len - (data - buf->data));
+    if (dlen < 0) {
+      BT_ERR("Invalid attribute value data");
+      return -EINVAL;
+    }
 
-        data += dlen;
+    if (id == attr_id) {
+      BT_DBG("Attribute ID 0x%04x Value found", id);
+      /*
+       * Initialize attribute value buffer data using selected
+       * data slice from original buffer.
+       */
+      attr->val     = data;
+      attr->len     = dlen;
+      attr->attr_id = id;
+      return 0;
     }
 
-    return -ENOENT;
+    data += dlen;
+  }
+
+  return -ENOENT;
 }
 
 /* reads SEQ item length, moves input buffer data reader forward */
-static ssize_t sdp_get_seq_len_item(uint8_t **data, size_t len)
-{
-    const uint8_t *pnext;
+static ssize_t sdp_get_seq_len_item(uint8_t **data, size_t len) {
+  const uint8_t *pnext;
 
-    BT_ASSERT(data);
-    BT_ASSERT(*data);
+  BT_ASSERT(data);
+  BT_ASSERT(*data);
 
-    /* validate len for pnext safe use to read 8bit bit value */
-    if (len < 2) {
-        goto err;
-    }
-
-    pnext = *data + sizeof(uint8_t);
-
-    switch (*data[0]) {
-        case BT_SDP_SEQ8:
-            if (len < (2 + pnext[0])) {
-                break;
-            }
-
-            *data += 2;
-            return pnext[0];
-        case BT_SDP_SEQ16:
-            /* validate len for pnext safe use to read 16bit value */
-            if (len < 3) {
-                break;
-            }
-
-            if (len < (3 + sys_get_be16(pnext))) {
-                break;
-            }
-
-            *data += 3;
-            return sys_get_be16(pnext);
-        case BT_SDP_SEQ32:
-            /* validate len for pnext safe use to read 32bit value */
-            if (len < 5) {
-                break;
-            }
-
-            if (len < (5 + sys_get_be32(pnext))) {
-                break;
-            }
-
-            *data += 5;
-            return sys_get_be32(pnext);
-        default:
-            BT_ERR("Invalid/unhandled DTD 0x%02x", *data[0]);
-            return -EINVAL;
-    }
-err:
-    BT_ERR("Too short buffer length %zu", len);
-    return -EMSGSIZE;
-}
+  /* validate len for pnext safe use to read 8bit bit value */
+  if (len < 2) {
+    goto err;
+  }
 
-static int sdp_get_uuid_data(const struct bt_sdp_attr_item *attr,
-                             struct bt_sdp_uuid_desc *pd,
-                             uint16_t proto_profile)
-{
-    /* get start address of attribute value */
-    uint8_t *p = attr->val;
-    ssize_t slen;
+  pnext = *data + sizeof(uint8_t);
 
-    BT_ASSERT(p);
+  switch (*data[0]) {
+  case BT_SDP_SEQ8:
+    if (len < (2 + pnext[0])) {
+      break;
+    }
 
-    /* Attribute value is a SEQ, get length of parent SEQ frame */
-    slen = sdp_get_seq_len_item(&p, attr->len);
-    if (slen < 0) {
-        return slen;
+    *data += 2;
+    return pnext[0];
+  case BT_SDP_SEQ16:
+    /* validate len for pnext safe use to read 16bit value */
+    if (len < 3) {
+      break;
     }
 
-    /* start reading stacked UUIDs in analyzed sequences tree */
-    while (p - attr->val < attr->len) {
-        size_t to_end, left = 0;
+    if (len < (3 + sys_get_be16(pnext))) {
+      break;
+    }
 
-        /* to_end tells how far to the end of input buffer */
-        to_end = attr->len - (p - attr->val);
-        /* how long is current UUID's item data associated to */
-        slen = sdp_get_seq_len_item(&p, to_end);
-        if (slen < 0) {
-            return slen;
-        }
+    *data += 3;
+    return sys_get_be16(pnext);
+  case BT_SDP_SEQ32:
+    /* validate len for pnext safe use to read 32bit value */
+    if (len < 5) {
+      break;
+    }
 
-        /* left tells how far is to the end of current UUID */
-        left = slen;
+    if (len < (5 + sys_get_be32(pnext))) {
+      break;
+    }
 
-        /* check if at least DTD + UUID16 can be read safely */
-        if (left < 3) {
-            return -EMSGSIZE;
-        }
+    *data += 5;
+    return sys_get_be32(pnext);
+  default:
+    BT_ERR("Invalid/unhandled DTD 0x%02x", *data[0]);
+    return -EINVAL;
+  }
+err:
+  BT_ERR("Too short buffer length %zu", len);
+  return -EMSGSIZE;
+}
 
-        /* check DTD and get stacked UUID value */
-        switch (p[0]) {
-            case BT_SDP_UUID16:
-                memcpy(&pd->uuid16,
-                       BT_UUID_DECLARE_16(sys_get_be16(++p)),
-                       sizeof(struct bt_uuid_16));
-                p += sizeof(uint16_t);
-                left -= sizeof(uint16_t);
-                break;
-            case BT_SDP_UUID32:
-                /* check if valid UUID32 can be read safely */
-                if (left < 5) {
-                    return -EMSGSIZE;
-                }
-
-                memcpy(&pd->uuid32,
-                       BT_UUID_DECLARE_32(sys_get_be32(++p)),
-                       sizeof(struct bt_uuid_32));
-                p += sizeof(uint32_t);
-                left -= sizeof(uint32_t);
-                break;
-            default:
-                BT_ERR("Invalid/unhandled DTD 0x%02x\n", p[0]);
-                return -EINVAL;
-        }
+static int sdp_get_uuid_data(const struct bt_sdp_attr_item *attr, struct bt_sdp_uuid_desc *pd, uint16_t proto_profile) {
+  /* get start address of attribute value */
+  uint8_t *p = attr->val;
+  ssize_t  slen;
 
-        /* include last DTD in p[0] size itself updating left */
-        left -= sizeof(p[0]);
+  BT_ASSERT(p);
 
-        /*
-		 * Check if current UUID value matches input one given by user.
-		 * If found save it's location and length and return.
-		 */
-        if ((proto_profile == BT_UUID_16(&pd->uuid)->val) ||
-            (proto_profile == BT_UUID_32(&pd->uuid)->val)) {
-            pd->params = p;
-            pd->params_len = left;
+  /* Attribute value is a SEQ, get length of parent SEQ frame */
+  slen = sdp_get_seq_len_item(&p, attr->len);
+  if (slen < 0) {
+    return slen;
+  }
 
-            BT_DBG("UUID 0x%s found", bt_uuid_str(&pd->uuid));
-            return 0;
-        }
+  /* start reading stacked UUIDs in analyzed sequences tree */
+  while (p - attr->val < attr->len) {
+    size_t to_end, left = 0;
 
-        /* skip left octets to point beginning of next UUID in tree */
-        p += left;
+    /* to_end tells how far to the end of input buffer */
+    to_end = attr->len - (p - attr->val);
+    /* how long is current UUID's item data associated to */
+    slen = sdp_get_seq_len_item(&p, to_end);
+    if (slen < 0) {
+      return slen;
     }
 
-    BT_DBG("Value 0x%04x not found", proto_profile);
-    return -ENOENT;
-}
+    /* left tells how far is to the end of current UUID */
+    left = slen;
 
-/*
- * Helper extracting specific parameters associated with UUID node given in
- * protocol descriptor list or profile descriptor list.
- */
-static int sdp_get_param_item(struct bt_sdp_uuid_desc *pd_item, uint16_t *param)
-{
-    const uint8_t *p = pd_item->params;
-    bool len_err = false;
-
-    BT_ASSERT(p);
-
-    BT_DBG("Getting UUID's 0x%s params", bt_uuid_str(&pd_item->uuid));
+    /* check if at least DTD + UUID16 can be read safely */
+    if (left < 3) {
+      return -EMSGSIZE;
+    }
 
+    /* check DTD and get stacked UUID value */
     switch (p[0]) {
-        case BT_SDP_UINT8:
-            /* check if 8bits value can be read safely */
-            if (pd_item->params_len < 2) {
-                len_err = true;
-                break;
-            }
-            *param = (++p)[0];
-            p += sizeof(uint8_t);
-            break;
-        case BT_SDP_UINT16:
-            /* check if 16bits value can be read safely */
-            if (pd_item->params_len < 3) {
-                len_err = true;
-                break;
-            }
-            *param = sys_get_be16(++p);
-            p += sizeof(uint16_t);
-            break;
-        case BT_SDP_UINT32:
-            /* check if 32bits value can be read safely */
-            if (pd_item->params_len < 5) {
-                len_err = true;
-                break;
-            }
-            *param = sys_get_be32(++p);
-            p += sizeof(uint32_t);
-            break;
-        default:
-            BT_ERR("Invalid/unhandled DTD 0x%02x\n", p[0]);
-            return -EINVAL;
-    }
-    /*
-	 * Check if no more data than already read is associated with UUID. In
-	 * valid case after getting parameter we should reach data buf end.
-	 */
-    if (p - pd_item->params != pd_item->params_len || len_err) {
-        BT_DBG("Invalid param buffer length");
+    case BT_SDP_UUID16:
+      memcpy(&pd->uuid16, BT_UUID_DECLARE_16(sys_get_be16(++p)), sizeof(struct bt_uuid_16));
+      p += sizeof(uint16_t);
+      left -= sizeof(uint16_t);
+      break;
+    case BT_SDP_UUID32:
+      /* check if valid UUID32 can be read safely */
+      if (left < 5) {
         return -EMSGSIZE;
+      }
+
+      memcpy(&pd->uuid32, BT_UUID_DECLARE_32(sys_get_be32(++p)), sizeof(struct bt_uuid_32));
+      p += sizeof(uint32_t);
+      left -= sizeof(uint32_t);
+      break;
+    default:
+      BT_ERR("Invalid/unhandled DTD 0x%02x\n", p[0]);
+      return -EINVAL;
     }
 
-    return 0;
-}
+    /* include last DTD in p[0] size itself updating left */
+    left -= sizeof(p[0]);
 
-int bt_sdp_get_proto_param(const struct net_buf *buf, enum bt_sdp_proto proto,
-                           uint16_t *param)
-{
-    struct bt_sdp_attr_item attr;
-    struct bt_sdp_uuid_desc pd;
-    int res;
+    /*
+     * Check if current UUID value matches input one given by user.
+     * If found save it's location and length and return.
+     */
+    if ((proto_profile == BT_UUID_16(&pd->uuid)->val) || (proto_profile == BT_UUID_32(&pd->uuid)->val)) {
+      pd->params     = p;
+      pd->params_len = left;
 
-    if (proto != BT_SDP_PROTO_RFCOMM && proto != BT_SDP_PROTO_L2CAP) {
-        BT_ERR("Invalid protocol specifier");
-        return -EINVAL;
+      BT_DBG("UUID 0x%s found", bt_uuid_str(&pd->uuid));
+      return 0;
     }
 
-    res = bt_sdp_get_attr(buf, &attr, BT_SDP_ATTR_PROTO_DESC_LIST);
-    if (res < 0) {
-        BT_WARN("Attribute 0x%04x not found, err %d",
-                BT_SDP_ATTR_PROTO_DESC_LIST, res);
-        return res;
-    }
+    /* skip left octets to point beginning of next UUID in tree */
+    p += left;
+  }
 
-    res = sdp_get_uuid_data(&attr, &pd, proto);
-    if (res < 0) {
-        BT_WARN("Protocol specifier 0x%04x not found, err %d", proto,
-                res);
-        return res;
-    }
+  BT_DBG("Value 0x%04x not found", proto_profile);
+  return -ENOENT;
+}
 
-    return sdp_get_param_item(&pd, param);
+/*
+ * Helper extracting specific parameters associated with UUID node given in
+ * protocol descriptor list or profile descriptor list.
+ */
+static int sdp_get_param_item(struct bt_sdp_uuid_desc *pd_item, uint16_t *param) {
+  const uint8_t *p       = pd_item->params;
+  bool           len_err = false;
+
+  BT_ASSERT(p);
+
+  BT_DBG("Getting UUID's 0x%s params", bt_uuid_str(&pd_item->uuid));
+
+  switch (p[0]) {
+  case BT_SDP_UINT8:
+    /* check if 8bits value can be read safely */
+    if (pd_item->params_len < 2) {
+      len_err = true;
+      break;
+    }
+    *param = (++p)[0];
+    p += sizeof(uint8_t);
+    break;
+  case BT_SDP_UINT16:
+    /* check if 16bits value can be read safely */
+    if (pd_item->params_len < 3) {
+      len_err = true;
+      break;
+    }
+    *param = sys_get_be16(++p);
+    p += sizeof(uint16_t);
+    break;
+  case BT_SDP_UINT32:
+    /* check if 32bits value can be read safely */
+    if (pd_item->params_len < 5) {
+      len_err = true;
+      break;
+    }
+    *param = sys_get_be32(++p);
+    p += sizeof(uint32_t);
+    break;
+  default:
+    BT_ERR("Invalid/unhandled DTD 0x%02x\n", p[0]);
+    return -EINVAL;
+  }
+  /*
+   * Check if no more data than already read is associated with UUID. In
+   * valid case after getting parameter we should reach data buf end.
+   */
+  if (p - pd_item->params != pd_item->params_len || len_err) {
+    BT_DBG("Invalid param buffer length");
+    return -EMSGSIZE;
+  }
+
+  return 0;
 }
 
-int bt_sdp_get_profile_version(const struct net_buf *buf, uint16_t profile,
-                               uint16_t *version)
-{
-    struct bt_sdp_attr_item attr;
-    struct bt_sdp_uuid_desc pd;
-    int res;
+int bt_sdp_get_proto_param(const struct net_buf *buf, enum bt_sdp_proto proto, uint16_t *param) {
+  struct bt_sdp_attr_item attr;
+  struct bt_sdp_uuid_desc pd;
+  int                     res;
+
+  if (proto != BT_SDP_PROTO_RFCOMM && proto != BT_SDP_PROTO_L2CAP) {
+    BT_ERR("Invalid protocol specifier");
+    return -EINVAL;
+  }
+
+  res = bt_sdp_get_attr(buf, &attr, BT_SDP_ATTR_PROTO_DESC_LIST);
+  if (res < 0) {
+    BT_WARN("Attribute 0x%04x not found, err %d", BT_SDP_ATTR_PROTO_DESC_LIST, res);
+    return res;
+  }
+
+  res = sdp_get_uuid_data(&attr, &pd, proto);
+  if (res < 0) {
+    BT_WARN("Protocol specifier 0x%04x not found, err %d", proto, res);
+    return res;
+  }
+
+  return sdp_get_param_item(&pd, param);
+}
 
-    res = bt_sdp_get_attr(buf, &attr, BT_SDP_ATTR_PROFILE_DESC_LIST);
-    if (res < 0) {
-        BT_WARN("Attribute 0x%04x not found, err %d",
-                BT_SDP_ATTR_PROFILE_DESC_LIST, res);
-        return res;
-    }
+int bt_sdp_get_profile_version(const struct net_buf *buf, uint16_t profile, uint16_t *version) {
+  struct bt_sdp_attr_item attr;
+  struct bt_sdp_uuid_desc pd;
+  int                     res;
 
-    res = sdp_get_uuid_data(&attr, &pd, profile);
-    if (res < 0) {
-        BT_WARN("Profile 0x%04x not found, err %d", profile, res);
-        return res;
-    }
+  res = bt_sdp_get_attr(buf, &attr, BT_SDP_ATTR_PROFILE_DESC_LIST);
+  if (res < 0) {
+    BT_WARN("Attribute 0x%04x not found, err %d", BT_SDP_ATTR_PROFILE_DESC_LIST, res);
+    return res;
+  }
+
+  res = sdp_get_uuid_data(&attr, &pd, profile);
+  if (res < 0) {
+    BT_WARN("Profile 0x%04x not found, err %d", profile, res);
+    return res;
+  }
 
-    return sdp_get_param_item(&pd, version);
+  return sdp_get_param_item(&pd, version);
 }
 
-int bt_sdp_get_features(const struct net_buf *buf, uint16_t *features)
-{
-    struct bt_sdp_attr_item attr;
-    const uint8_t *p;
-    int res;
+int bt_sdp_get_features(const struct net_buf *buf, uint16_t *features) {
+  struct bt_sdp_attr_item attr;
+  const uint8_t          *p;
+  int                     res;
 
-    res = bt_sdp_get_attr(buf, &attr, BT_SDP_ATTR_SUPPORTED_FEATURES);
-    if (res < 0) {
-        BT_WARN("Attribute 0x%04x not found, err %d",
-                BT_SDP_ATTR_SUPPORTED_FEATURES, res);
-        return res;
-    }
+  res = bt_sdp_get_attr(buf, &attr, BT_SDP_ATTR_SUPPORTED_FEATURES);
+  if (res < 0) {
+    BT_WARN("Attribute 0x%04x not found, err %d", BT_SDP_ATTR_SUPPORTED_FEATURES, res);
+    return res;
+  }
 
-    p = attr.val;
-    BT_ASSERT(p);
+  p = attr.val;
+  BT_ASSERT(p);
 
-    if (p[0] != BT_SDP_UINT16) {
-        BT_ERR("Invalid DTD 0x%02x", p[0]);
-        return -EINVAL;
-    }
+  if (p[0] != BT_SDP_UINT16) {
+    BT_ERR("Invalid DTD 0x%02x", p[0]);
+    return -EINVAL;
+  }
 
-    /* assert 16bit can be read safely */
-    if (attr.len < 3) {
-        BT_ERR("Data length too short %u", attr.len);
-        return -EMSGSIZE;
-    }
+  /* assert 16bit can be read safely */
+  if (attr.len < 3) {
+    BT_ERR("Data length too short %u", attr.len);
+    return -EMSGSIZE;
+  }
 
-    *features = sys_get_be16(++p);
-    p += sizeof(uint16_t);
+  *features = sys_get_be16(++p);
+  p += sizeof(uint16_t);
 
-    if (p - attr.val != attr.len) {
-        BT_ERR("Invalid data length %u", attr.len);
-        return -EMSGSIZE;
-    }
+  if (p - attr.val != attr.len) {
+    BT_ERR("Invalid data length %u", attr.len);
+    return -EMSGSIZE;
+  }
 
-    return 0;
+  return 0;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/settings.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/settings.c
index 1eaffca7b7..d5a2716191 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/settings.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/settings.c
@@ -4,425 +4,389 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
 #include 
 #include 
+#include 
+#include 
 
 #define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_SETTINGS)
 #define LOG_MODULE_NAME bt_settings
 #include "log.h"
 
+#include "gatt.h"
 #include "hci_core.h"
-#include "settings.h"
 #include "keys.h"
-#include "gatt.h"
+#include "settings.h"
 #if defined(BFLB_BLE)
 #include 
 #if defined(CONFIG_BT_SETTINGS)
 #include "easyflash.h"
 #endif
-#include 
 #include "portable.h"
+#include 
 #endif
 
 #if defined(CONFIG_BT_SETTINGS_USE_PRINTK)
-void bt_settings_encode_key(char *path, size_t path_size, const char *subsys,
-                            bt_addr_le_t *addr, const char *key)
-{
-    if (key) {
-        snprintk(path, path_size,
-                 "bt/%s/%02x%02x%02x%02x%02x%02x%u/%s", subsys,
-                 addr->a.val[5], addr->a.val[4], addr->a.val[3],
-                 addr->a.val[2], addr->a.val[1], addr->a.val[0],
-                 addr->type, key);
-    } else {
-        snprintk(path, path_size,
-                 "bt/%s/%02x%02x%02x%02x%02x%02x%u", subsys,
-                 addr->a.val[5], addr->a.val[4], addr->a.val[3],
-                 addr->a.val[2], addr->a.val[1], addr->a.val[0],
-                 addr->type);
-    }
-
-    BT_DBG("Encoded path %s", log_strdup(path));
+void bt_settings_encode_key(char *path, size_t path_size, const char *subsys, bt_addr_le_t *addr, const char *key) {
+  if (key) {
+    snprintk(path, path_size, "bt/%s/%02x%02x%02x%02x%02x%02x%u/%s", subsys, addr->a.val[5], addr->a.val[4], addr->a.val[3], addr->a.val[2], addr->a.val[1], addr->a.val[0], addr->type, key);
+  } else {
+    snprintk(path, path_size, "bt/%s/%02x%02x%02x%02x%02x%02x%u", subsys, addr->a.val[5], addr->a.val[4], addr->a.val[3], addr->a.val[2], addr->a.val[1], addr->a.val[0], addr->type);
+  }
+
+  BT_DBG("Encoded path %s", log_strdup(path));
 }
 #else
-void bt_settings_encode_key(char *path, size_t path_size, const char *subsys,
-                            bt_addr_le_t *addr, const char *key)
-{
-    size_t len = 3;
-
-    /* Skip if path_size is less than 3; strlen("bt/") */
+void bt_settings_encode_key(char *path, size_t path_size, const char *subsys, bt_addr_le_t *addr, const char *key) {
+  size_t len = 3;
+
+  /* Skip if path_size is less than 3; strlen("bt/") */
+  if (len < path_size) {
+    /* Key format:
+     *  "bt///", "/" is optional
+     */
+    strcpy(path, "bt/");
+    strncpy(&path[len], subsys, path_size - len);
+    len = strlen(path);
     if (len < path_size) {
-        /* Key format:
-		 *  "bt///", "/" is optional
-		 */
-        strcpy(path, "bt/");
-        strncpy(&path[len], subsys, path_size - len);
-        len = strlen(path);
-        if (len < path_size) {
-            path[len] = '/';
-            len++;
-        }
-
-        for (s8_t i = 5; i >= 0 && len < path_size; i--) {
-            len += bin2hex(&addr->a.val[i], 1, &path[len],
-                           path_size - len);
-        }
-
-        if (len < path_size) {
-            /* Type can be either BT_ADDR_LE_PUBLIC or
-			 * BT_ADDR_LE_RANDOM (value 0 or 1)
-			 */
-            path[len] = '0' + addr->type;
-            len++;
-        }
-
-        if (key && len < path_size) {
-            path[len] = '/';
-            len++;
-            strncpy(&path[len], key, path_size - len);
-            len += strlen(&path[len]);
-        }
-
-        if (len >= path_size) {
-            /* Truncate string */
-            path[path_size - 1] = '\0';
-        }
-    } else if (path_size > 0) {
-        *path = '\0';
+      path[len] = '/';
+      len++;
     }
 
-    BT_DBG("Encoded path %s", log_strdup(path));
-}
-#endif
+    for (s8_t i = 5; i >= 0 && len < path_size; i--) {
+      len += bin2hex(&addr->a.val[i], 1, &path[len], path_size - len);
+    }
 
-#if !defined(BFLB_BLE)
-int bt_settings_decode_key(const char *key, bt_addr_le_t *addr)
-{
-    if (settings_name_next(key, NULL) != 13) {
-        return -EINVAL;
+    if (len < path_size) {
+      /* Type can be either BT_ADDR_LE_PUBLIC or
+       * BT_ADDR_LE_RANDOM (value 0 or 1)
+       */
+      path[len] = '0' + addr->type;
+      len++;
     }
 
-    if (key[12] == '0') {
-        addr->type = BT_ADDR_LE_PUBLIC;
-    } else if (key[12] == '1') {
-        addr->type = BT_ADDR_LE_RANDOM;
-    } else {
-        return -EINVAL;
+    if (key && len < path_size) {
+      path[len] = '/';
+      len++;
+      strncpy(&path[len], key, path_size - len);
+      len += strlen(&path[len]);
     }
 
-    for (u8_t i = 0; i < 6; i++) {
-        hex2bin(&key[i * 2], 2, &addr->a.val[5 - i], 1);
+    if (len >= path_size) {
+      /* Truncate string */
+      path[path_size - 1] = '\0';
     }
+  } else if (path_size > 0) {
+    *path = '\0';
+  }
 
-    BT_DBG("Decoded %s as %s", log_strdup(key), bt_addr_le_str(addr));
+  BT_DBG("Encoded path %s", log_strdup(path));
+}
+#endif
 
-    return 0;
+#if !defined(BFLB_BLE)
+int bt_settings_decode_key(const char *key, bt_addr_le_t *addr) {
+  if (settings_name_next(key, NULL) != 13) {
+    return -EINVAL;
+  }
+
+  if (key[12] == '0') {
+    addr->type = BT_ADDR_LE_PUBLIC;
+  } else if (key[12] == '1') {
+    addr->type = BT_ADDR_LE_RANDOM;
+  } else {
+    return -EINVAL;
+  }
+
+  for (u8_t i = 0; i < 6; i++) {
+    hex2bin(&key[i * 2], 2, &addr->a.val[5 - i], 1);
+  }
+
+  BT_DBG("Decoded %s as %s", log_strdup(key), bt_addr_le_str(addr));
+
+  return 0;
 }
 
-static int set(const char *name, size_t len_rd, settings_read_cb read_cb,
-               void *cb_arg)
-{
-    ssize_t len;
-    const char *next;
+static int set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) {
+  ssize_t     len;
+  const char *next;
 
-    if (!name) {
-        BT_ERR("Insufficient number of arguments");
-        return -ENOENT;
+  if (!name) {
+    BT_ERR("Insufficient number of arguments");
+    return -ENOENT;
+  }
+
+  len = settings_name_next(name, &next);
+
+  if (!strncmp(name, "id", len)) {
+    /* Any previously provided identities supersede flash */
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_PRESET_ID)) {
+      BT_WARN("Ignoring identities stored in flash");
+      return 0;
     }
 
-    len = settings_name_next(name, &next);
-
-    if (!strncmp(name, "id", len)) {
-        /* Any previously provided identities supersede flash */
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_PRESET_ID)) {
-            BT_WARN("Ignoring identities stored in flash");
-            return 0;
-        }
-
-        len = read_cb(cb_arg, &bt_dev.id_addr, sizeof(bt_dev.id_addr));
-        if (len < sizeof(bt_dev.id_addr[0])) {
-            if (len < 0) {
-                BT_ERR("Failed to read ID address from storage"
-                       " (err %zu)",
-                       len);
-            } else {
-                BT_ERR("Invalid length ID address in storage");
-                BT_HEXDUMP_DBG(&bt_dev.id_addr, len,
-                               "data read");
-            }
-            (void)memset(bt_dev.id_addr, 0,
-                         sizeof(bt_dev.id_addr));
-            bt_dev.id_count = 0U;
-        } else {
-            int i;
-
-            bt_dev.id_count = len / sizeof(bt_dev.id_addr[0]);
-            for (i = 0; i < bt_dev.id_count; i++) {
-                BT_DBG("ID[%d] %s", i,
-                       bt_addr_le_str(&bt_dev.id_addr[i]));
-            }
-        }
-
-        return 0;
+    len = read_cb(cb_arg, &bt_dev.id_addr, sizeof(bt_dev.id_addr));
+    if (len < sizeof(bt_dev.id_addr[0])) {
+      if (len < 0) {
+        BT_ERR("Failed to read ID address from storage"
+               " (err %zu)",
+               len);
+      } else {
+        BT_ERR("Invalid length ID address in storage");
+        BT_HEXDUMP_DBG(&bt_dev.id_addr, len, "data read");
+      }
+      (void)memset(bt_dev.id_addr, 0, sizeof(bt_dev.id_addr));
+      bt_dev.id_count = 0U;
+    } else {
+      int i;
+
+      bt_dev.id_count = len / sizeof(bt_dev.id_addr[0]);
+      for (i = 0; i < bt_dev.id_count; i++) {
+        BT_DBG("ID[%d] %s", i, bt_addr_le_str(&bt_dev.id_addr[i]));
+      }
     }
 
+    return 0;
+  }
+
 #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC)
-    if (!strncmp(name, "name", len)) {
-        len = read_cb(cb_arg, &bt_dev.name, sizeof(bt_dev.name) - 1);
-        if (len < 0) {
-            BT_ERR("Failed to read device name from storage"
-                   " (err %zu)",
-                   len);
-        } else {
-            bt_dev.name[len] = '\0';
-
-            BT_DBG("Name set to %s", log_strdup(bt_dev.name));
-        }
-        return 0;
+  if (!strncmp(name, "name", len)) {
+    len = read_cb(cb_arg, &bt_dev.name, sizeof(bt_dev.name) - 1);
+    if (len < 0) {
+      BT_ERR("Failed to read device name from storage"
+             " (err %zu)",
+             len);
+    } else {
+      bt_dev.name[len] = '\0';
+
+      BT_DBG("Name set to %s", log_strdup(bt_dev.name));
     }
+    return 0;
+  }
 #endif
 
 #if defined(CONFIG_BT_PRIVACY)
-    if (!strncmp(name, "irk", len)) {
-        len = read_cb(cb_arg, bt_dev.irk, sizeof(bt_dev.irk));
-        if (len < sizeof(bt_dev.irk[0])) {
-            if (len < 0) {
-                BT_ERR("Failed to read IRK from storage"
-                       " (err %zu)",
-                       len);
-            } else {
-                BT_ERR("Invalid length IRK in storage");
-                (void)memset(bt_dev.irk, 0, sizeof(bt_dev.irk));
-            }
-        } else {
-            int i, count;
-
-            count = len / sizeof(bt_dev.irk[0]);
-            for (i = 0; i < count; i++) {
-                BT_DBG("IRK[%d] %s", i,
-                       bt_hex(bt_dev.irk[i], 16));
-            }
-        }
-
-        return 0;
+  if (!strncmp(name, "irk", len)) {
+    len = read_cb(cb_arg, bt_dev.irk, sizeof(bt_dev.irk));
+    if (len < sizeof(bt_dev.irk[0])) {
+      if (len < 0) {
+        BT_ERR("Failed to read IRK from storage"
+               " (err %zu)",
+               len);
+      } else {
+        BT_ERR("Invalid length IRK in storage");
+        (void)memset(bt_dev.irk, 0, sizeof(bt_dev.irk));
+      }
+    } else {
+      int i, count;
+
+      count = len / sizeof(bt_dev.irk[0]);
+      for (i = 0; i < count; i++) {
+        BT_DBG("IRK[%d] %s", i, bt_hex(bt_dev.irk[i], 16));
+      }
     }
+
+    return 0;
+  }
 #endif /* CONFIG_BT_PRIVACY */
 
-    return -ENOENT;
+  return -ENOENT;
 }
 
 #define ID_DATA_LEN(array) (bt_dev.id_count * sizeof(array[0]))
 
-static void save_id(struct k_work *work)
-{
-    int err;
-    BT_INFO("Saving ID");
-    err = settings_save_one("bt/id", &bt_dev.id_addr,
-                            ID_DATA_LEN(bt_dev.id_addr));
-    if (err) {
-        BT_ERR("Failed to save ID (err %d)", err);
-    }
+static void save_id(struct k_work *work) {
+  int err;
+  BT_INFO("Saving ID");
+  err = settings_save_one("bt/id", &bt_dev.id_addr, ID_DATA_LEN(bt_dev.id_addr));
+  if (err) {
+    BT_ERR("Failed to save ID (err %d)", err);
+  }
 
 #if defined(CONFIG_BT_PRIVACY)
-    err = settings_save_one("bt/irk", bt_dev.irk, ID_DATA_LEN(bt_dev.irk));
-    if (err) {
-        BT_ERR("Failed to save IRK (err %d)", err);
-    }
+  err = settings_save_one("bt/irk", bt_dev.irk, ID_DATA_LEN(bt_dev.irk));
+  if (err) {
+    BT_ERR("Failed to save IRK (err %d)", err);
+  }
 #endif
 }
 
 K_WORK_DEFINE(save_id_work, save_id);
-#endif //!BFLB_BLE
+#endif //! BFLB_BLE
 #if defined(BFLB_BLE)
 #if defined(CONFIG_BT_SETTINGS)
 bool ef_ready_flag = false;
-int bt_check_if_ef_ready()
-{
-    int err = 0;
-
-    if (!ef_ready_flag) {
-        err = easyflash_init();
-        if (!err)
-            ef_ready_flag = true;
-    }
+int  bt_check_if_ef_ready() {
+  int err = 0;
 
-    return err;
+  if (!ef_ready_flag) {
+    err = easyflash_init();
+    if (!err)
+      ef_ready_flag = true;
+  }
+
+  return err;
 }
 
-int bt_settings_set_bin(const char *key, const uint8_t *value, size_t length)
-{
-    const char *lookup = "0123456789abcdef";
-    char *str_value;
-    int err;
+int bt_settings_set_bin(const char *key, const uint8_t *value, size_t length) {
+  const char *lookup = "0123456789abcdef";
+  char       *str_value;
+  int         err;
 
-    err = bt_check_if_ef_ready();
-    if (err)
-        return err;
+  err = bt_check_if_ef_ready();
+  if (err)
+    return err;
 
-    str_value = pvPortMalloc(length * 2 + 1);
+  str_value = pvPortMalloc(length * 2 + 1);
 
-    BT_ASSERT(str_value != NULL);
+  BT_ASSERT(str_value != NULL);
 
-    for (size_t i = 0; i < length; i++) {
-        str_value[(i * 2) + 0] = lookup[(value[i] >> 4) & 0x0F];
-        str_value[(i * 2) + 1] = lookup[value[i] & 0x0F];
-    }
-    str_value[length * 2] = '\0';
+  for (size_t i = 0; i < length; i++) {
+    str_value[(i * 2) + 0] = lookup[(value[i] >> 4) & 0x0F];
+    str_value[(i * 2) + 1] = lookup[value[i] & 0x0F];
+  }
+  str_value[length * 2] = '\0';
 
-    err = ef_set_env(key, (const char *)str_value);
+  err = ef_set_env(key, (const char *)str_value);
 
-    vPortFree(str_value);
+  vPortFree(str_value);
 
-    return err;
+  return err;
 }
 
-int bt_settings_get_bin(const char *key, u8_t *value, size_t exp_len, size_t *real_len)
-{
-    char *str_value;
-    size_t str_value_len;
-    char rand[3];
-    int err;
+int bt_settings_get_bin(const char *key, u8_t *value, size_t exp_len, size_t *real_len) {
+  char  *str_value;
+  size_t str_value_len;
+  char   rand[3];
+  int    err;
 
-    err = bt_check_if_ef_ready();
-    if (err)
-        return err;
+  err = bt_check_if_ef_ready();
+  if (err)
+    return err;
 
-    str_value = ef_get_env(key);
-    if (str_value == NULL) {
-        return -1;
-    }
+  str_value = ef_get_env(key);
+  if (str_value == NULL) {
+    return -1;
+  }
 
-    str_value_len = strlen(str_value);
+  str_value_len = strlen(str_value);
 
-    if ((str_value_len % 2) != 0 || (exp_len > 0 && str_value_len > exp_len * 2)) {
-        return -1;
-    }
+  if ((str_value_len % 2) != 0 || (exp_len > 0 && str_value_len > exp_len * 2)) {
+    return -1;
+  }
 
-    if (real_len)
-        *real_len = str_value_len / 2;
+  if (real_len)
+    *real_len = str_value_len / 2;
 
-    for (size_t i = 0; i < str_value_len / 2; i++) {
-        strncpy(rand, str_value + 2 * i, 2);
-        rand[2] = '\0';
-        value[i] = strtol(rand, NULL, 16);
-    }
+  for (size_t i = 0; i < str_value_len / 2; i++) {
+    strncpy(rand, str_value + 2 * i, 2);
+    rand[2]  = '\0';
+    value[i] = strtol(rand, NULL, 16);
+  }
 
-    return 0;
+  return 0;
 }
 
-int settings_delete(const char *key)
-{
-    return ef_del_env(key);
-}
+int settings_delete(const char *key) { return ef_del_env(key); }
 
-int settings_save_one(const char *key, const u8_t *value, size_t length)
-{
-    return bt_settings_set_bin(key, value, length);
-}
-#endif //CONFIG_BT_SETTINGS
+int settings_save_one(const char *key, const u8_t *value, size_t length) { return bt_settings_set_bin(key, value, length); }
+#endif // CONFIG_BT_SETTINGS
 #endif
 
-void bt_settings_save_id(void)
-{
+void bt_settings_save_id(void) {
 #if defined(BFLB_BLE)
 #if defined(CONFIG_BT_SETTINGS)
-    if (bt_check_if_ef_ready())
-        return;
-    bt_settings_set_bin(NV_LOCAL_ID_ADDR, (const u8_t *)&bt_dev.id_addr[0], sizeof(bt_addr_le_t) * CONFIG_BT_ID_MAX);
+  if (bt_check_if_ef_ready())
+    return;
+  bt_settings_set_bin(NV_LOCAL_ID_ADDR, (const u8_t *)&bt_dev.id_addr[0], sizeof(bt_addr_le_t) * CONFIG_BT_ID_MAX);
 #if defined(CONFIG_BT_PRIVACY)
-    bt_settings_set_bin(NV_LOCAL_IRK, (const u8_t *)&bt_dev.irk[0], 16 * CONFIG_BT_ID_MAX);
-#endif //CONFIG_BT_PRIVACY
-#endif //CONFIG_BT_SETTINGS
+  bt_settings_set_bin(NV_LOCAL_IRK, (const u8_t *)&bt_dev.irk[0], 16 * CONFIG_BT_ID_MAX);
+#endif // CONFIG_BT_PRIVACY
+#endif // CONFIG_BT_SETTINGS
 #else
-    k_work_submit(&save_id_work);
+  k_work_submit(&save_id_work);
 #endif
 }
 
 #if defined(BFLB_BLE)
 #if defined(CONFIG_BT_SETTINGS)
-void bt_settings_save_name(void)
-{
-    if (bt_check_if_ef_ready())
-        return;
+void bt_settings_save_name(void) {
+  if (bt_check_if_ef_ready())
+    return;
 
-    ef_set_env(NV_LOCAL_NAME, bt_dev.name);
+  ef_set_env(NV_LOCAL_NAME, bt_dev.name);
 }
 
-void bt_local_info_load(void)
-{
-    if (bt_check_if_ef_ready())
-        return;
+void bt_local_info_load(void) {
+  if (bt_check_if_ef_ready())
+    return;
 #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC)
-    char *dev_name;
-    uint8_t len;
-    dev_name = ef_get_env(NV_LOCAL_NAME);
-    if (dev_name != NULL) {
-        len = ((strlen(dev_name) + 1) < CONFIG_BT_DEVICE_NAME_MAX) ? (strlen(dev_name) + 1) : CONFIG_BT_DEVICE_NAME_MAX;
-        memcpy(bt_dev.name, dev_name, len);
-    }
+  char   *dev_name;
+  uint8_t len;
+  dev_name = ef_get_env(NV_LOCAL_NAME);
+  if (dev_name != NULL) {
+    len = ((strlen(dev_name) + 1) < CONFIG_BT_DEVICE_NAME_MAX) ? (strlen(dev_name) + 1) : CONFIG_BT_DEVICE_NAME_MAX;
+    memcpy(bt_dev.name, dev_name, len);
+  }
 #endif
-    bt_settings_get_bin(NV_LOCAL_ID_ADDR, (u8_t *)&bt_dev.id_addr[0], sizeof(bt_addr_le_t) * CONFIG_BT_ID_MAX, NULL);
+  bt_settings_get_bin(NV_LOCAL_ID_ADDR, (u8_t *)&bt_dev.id_addr[0], sizeof(bt_addr_le_t) * CONFIG_BT_ID_MAX, NULL);
 #if defined(CONFIG_BT_PRIVACY)
-    bt_settings_get_bin(NV_LOCAL_IRK, (u8_t *)&bt_dev.irk[0][0], 16 * CONFIG_BT_ID_MAX, NULL);
+  bt_settings_get_bin(NV_LOCAL_IRK, (u8_t *)&bt_dev.irk[0][0], 16 * CONFIG_BT_ID_MAX, NULL);
 #endif
 }
-#endif //CONFIG_BT_SETTINGS
+#endif // CONFIG_BT_SETTINGS
 #endif
 
 #if !defined(BFLB_BLE)
-static int commit(void)
-{
-    BT_DBG("");
+static int commit(void) {
+  BT_DBG("");
 
 #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC)
-    if (bt_dev.name[0] == '\0') {
-        bt_set_name(CONFIG_BT_DEVICE_NAME);
-    }
+  if (bt_dev.name[0] == '\0') {
+    bt_set_name(CONFIG_BT_DEVICE_NAME);
+  }
 #endif
-    if (!bt_dev.id_count) {
-        int err;
-
-        err = bt_setup_id_addr();
-        if (err) {
-            BT_ERR("Unable to setup an identity address");
-            return err;
-        }
-    }
+  if (!bt_dev.id_count) {
+    int err;
 
-    /* Make sure that the identities created by bt_id_create after
-	 * bt_enable is saved to persistent storage. */
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_PRESET_ID)) {
-        bt_settings_save_id();
+    err = bt_setup_id_addr();
+    if (err) {
+      BT_ERR("Unable to setup an identity address");
+      return err;
     }
+  }
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        bt_finalize_init();
-    }
+  /* Make sure that the identities created by bt_id_create after
+   * bt_enable is saved to persistent storage. */
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_PRESET_ID)) {
+    bt_settings_save_id();
+  }
 
-    return 0;
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    bt_finalize_init();
+  }
+
+  return 0;
 }
 
 SETTINGS_STATIC_HANDLER_DEFINE(bt, "bt", NULL, set, commit, NULL);
 
-#endif //!BFLB_BLE
+#endif //! BFLB_BLE
 
-int bt_settings_init(void)
-{
+int bt_settings_init(void) {
 #if defined(BFLB_BLE)
-    return 0;
+  return 0;
 #else
-    int err;
+  int err;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    err = settings_subsys_init();
-    if (err) {
-        BT_ERR("settings_subsys_init failed (err %d)", err);
-        return err;
-    }
+  err = settings_subsys_init();
+  if (err) {
+    BT_ERR("settings_subsys_init failed (err %d)", err);
+    return err;
+  }
 
-    return 0;
+  return 0;
 #endif
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/smp_null.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/smp_null.c
index e0b2f74bda..24bcfdbf9f 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/smp_null.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/smp_null.c
@@ -9,93 +9,82 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
 #include 
+#include 
 #include 
+#include 
 
+#include <../include/bluetooth/buf.h>
 #include 
 #include 
-#include <../include/bluetooth/buf.h>
 
 #define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_HCI_CORE)
 #define LOG_MODULE_NAME bt_smp
 #include "log.h"
 
-#include "hci_core.h"
 #include "conn_internal.h"
+#include "hci_core.h"
 #include "l2cap_internal.h"
 #include "smp.h"
 
 static struct bt_l2cap_le_chan bt_smp_pool[CONFIG_BT_MAX_CONN];
 
-int bt_smp_sign_verify(struct bt_conn *conn, struct net_buf *buf)
-{
-    return -ENOTSUP;
-}
+int bt_smp_sign_verify(struct bt_conn *conn, struct net_buf *buf) { return -ENOTSUP; }
 
-int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf)
-{
-    return -ENOTSUP;
-}
+int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf) { return -ENOTSUP; }
 
-static int bt_smp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
-    struct bt_conn *conn = chan->conn;
-    struct bt_smp_pairing_fail *rsp;
-    struct bt_smp_hdr *hdr;
+static int bt_smp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) {
+  struct bt_conn             *conn = chan->conn;
+  struct bt_smp_pairing_fail *rsp;
+  struct bt_smp_hdr          *hdr;
 
-    /* If a device does not support pairing then it shall respond with
-	 * a Pairing Failed command with the reason set to "Pairing Not
-	 * Supported" when any command is received.
-	 * Core Specification Vol. 3, Part H, 3.3
-	 */
+  /* If a device does not support pairing then it shall respond with
+   * a Pairing Failed command with the reason set to "Pairing Not
+   * Supported" when any command is received.
+   * Core Specification Vol. 3, Part H, 3.3
+   */
 
-    buf = bt_l2cap_create_pdu(NULL, 0);
-    /* NULL is not a possible return due to K_FOREVER */
+  buf = bt_l2cap_create_pdu(NULL, 0);
+  /* NULL is not a possible return due to K_FOREVER */
 
-    hdr = net_buf_add(buf, sizeof(*hdr));
-    hdr->code = BT_SMP_CMD_PAIRING_FAIL;
+  hdr       = net_buf_add(buf, sizeof(*hdr));
+  hdr->code = BT_SMP_CMD_PAIRING_FAIL;
 
-    rsp = net_buf_add(buf, sizeof(*rsp));
-    rsp->reason = BT_SMP_ERR_PAIRING_NOTSUPP;
+  rsp         = net_buf_add(buf, sizeof(*rsp));
+  rsp->reason = BT_SMP_ERR_PAIRING_NOTSUPP;
 
-    bt_l2cap_send(conn, BT_L2CAP_CID_SMP, buf);
+  bt_l2cap_send(conn, BT_L2CAP_CID_SMP, buf);
 
-    return 0;
+  return 0;
 }
 
-static int bt_smp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan)
-{
-    int i;
-    static struct bt_l2cap_chan_ops ops = {
-        .recv = bt_smp_recv,
-    };
+static int bt_smp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) {
+  int                             i;
+  static struct bt_l2cap_chan_ops ops = {
+      .recv = bt_smp_recv,
+  };
 
-    BT_DBG("conn %p handle %u", conn, conn->handle);
+  BT_DBG("conn %p handle %u", conn, conn->handle);
 
-    for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) {
-        struct bt_l2cap_le_chan *smp = &bt_smp_pool[i];
+  for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) {
+    struct bt_l2cap_le_chan *smp = &bt_smp_pool[i];
 
-        if (smp->chan.conn) {
-            continue;
-        }
+    if (smp->chan.conn) {
+      continue;
+    }
 
-        smp->chan.ops = &ops;
+    smp->chan.ops = &ops;
 
-        *chan = &smp->chan;
+    *chan = &smp->chan;
 
-        return 0;
-    }
+    return 0;
+  }
 
-    BT_ERR("No available SMP context for conn %p", conn);
+  BT_ERR("No available SMP context for conn %p", conn);
 
-    return -ENOMEM;
+  return -ENOMEM;
 }
 
 BT_L2CAP_CHANNEL_DEFINE(smp_fixed_chan, BT_L2CAP_CID_SMP, bt_smp_accept);
 
-int bt_smp_init(void)
-{
-    return 0;
-}
+int bt_smp_init(void) { return 0; }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/uuid.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/uuid.c
index dee1350438..d0cca15338 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/uuid.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/uuid.c
@@ -6,10 +6,10 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
 #include 
 #include 
 #include 
+#include 
 
 #include 
 
@@ -22,118 +22,105 @@
  *  little endian 0x2800 : [00 28] -> no swapping required
  *  big endian 0x2800    : [28 00] -> swapping required
  */
-static const struct bt_uuid_128 uuid128_base = {
-    .uuid = { BT_UUID_TYPE_128 },
-    .val = { BT_UUID_128_ENCODE(
-        0x00000000, 0x0000, 0x1000, 0x8000, 0x00805F9B34FB) }
-};
-
-static void uuid_to_uuid128(const struct bt_uuid *src, struct bt_uuid_128 *dst)
-{
-    switch (src->type) {
-        case BT_UUID_TYPE_16:
-            *dst = uuid128_base;
-            sys_put_le16(BT_UUID_16(src)->val,
-                         &dst->val[UUID_16_BASE_OFFSET]);
-            return;
-        case BT_UUID_TYPE_32:
-            *dst = uuid128_base;
-            sys_put_le32(BT_UUID_32(src)->val,
-                         &dst->val[UUID_16_BASE_OFFSET]);
-            return;
-        case BT_UUID_TYPE_128:
-            memcpy(dst, src, sizeof(*dst));
-            return;
-    }
+static const struct bt_uuid_128 uuid128_base = {.uuid = {BT_UUID_TYPE_128}, .val = {BT_UUID_128_ENCODE(0x00000000, 0x0000, 0x1000, 0x8000, 0x00805F9B34FB)}};
+
+static void uuid_to_uuid128(const struct bt_uuid *src, struct bt_uuid_128 *dst) {
+  switch (src->type) {
+  case BT_UUID_TYPE_16:
+    *dst = uuid128_base;
+    sys_put_le16(BT_UUID_16(src)->val, &dst->val[UUID_16_BASE_OFFSET]);
+    return;
+  case BT_UUID_TYPE_32:
+    *dst = uuid128_base;
+    sys_put_le32(BT_UUID_32(src)->val, &dst->val[UUID_16_BASE_OFFSET]);
+    return;
+  case BT_UUID_TYPE_128:
+    memcpy(dst, src, sizeof(*dst));
+    return;
+  }
 }
 
-static int uuid128_cmp(const struct bt_uuid *u1, const struct bt_uuid *u2)
-{
-    struct bt_uuid_128 uuid1, uuid2;
+static int uuid128_cmp(const struct bt_uuid *u1, const struct bt_uuid *u2) {
+  struct bt_uuid_128 uuid1, uuid2;
 
-    uuid_to_uuid128(u1, &uuid1);
-    uuid_to_uuid128(u2, &uuid2);
+  uuid_to_uuid128(u1, &uuid1);
+  uuid_to_uuid128(u2, &uuid2);
 
-    return memcmp(uuid1.val, uuid2.val, 16);
+  return memcmp(uuid1.val, uuid2.val, 16);
 }
 
-int bt_uuid_cmp(const struct bt_uuid *u1, const struct bt_uuid *u2)
-{
-    /* Convert to 128 bit if types don't match */
-    if (u1->type != u2->type) {
-        return uuid128_cmp(u1, u2);
-    }
-
-    switch (u1->type) {
-        case BT_UUID_TYPE_16:
-            return (int)BT_UUID_16(u1)->val - (int)BT_UUID_16(u2)->val;
-        case BT_UUID_TYPE_32:
-            return (int)BT_UUID_32(u1)->val - (int)BT_UUID_32(u2)->val;
-        case BT_UUID_TYPE_128:
-            return memcmp(BT_UUID_128(u1)->val, BT_UUID_128(u2)->val, 16);
-    }
-
-    return -EINVAL;
+int bt_uuid_cmp(const struct bt_uuid *u1, const struct bt_uuid *u2) {
+  /* Convert to 128 bit if types don't match */
+  if (u1->type != u2->type) {
+    return uuid128_cmp(u1, u2);
+  }
+
+  switch (u1->type) {
+  case BT_UUID_TYPE_16:
+    return (int)BT_UUID_16(u1)->val - (int)BT_UUID_16(u2)->val;
+  case BT_UUID_TYPE_32:
+    return (int)BT_UUID_32(u1)->val - (int)BT_UUID_32(u2)->val;
+  case BT_UUID_TYPE_128:
+    return memcmp(BT_UUID_128(u1)->val, BT_UUID_128(u2)->val, 16);
+  }
+
+  return -EINVAL;
 }
 
-bool bt_uuid_create(struct bt_uuid *uuid, const u8_t *data, u8_t data_len)
-{
-    /* Copy UUID from packet data/internal variable to internal bt_uuid */
-    switch (data_len) {
-        case 2:
-            uuid->type = BT_UUID_TYPE_16;
-            BT_UUID_16(uuid)->val = sys_get_le16(data);
-            break;
-        case 4:
-            uuid->type = BT_UUID_TYPE_32;
-            BT_UUID_32(uuid)->val = sys_get_le32(data);
-            break;
-        case 16:
-            uuid->type = BT_UUID_TYPE_128;
-            memcpy(&BT_UUID_128(uuid)->val, data, 16);
-            break;
-        default:
-            return false;
-    }
-    return true;
+bool bt_uuid_create(struct bt_uuid *uuid, const u8_t *data, u8_t data_len) {
+  /* Copy UUID from packet data/internal variable to internal bt_uuid */
+  switch (data_len) {
+  case 2:
+    uuid->type            = BT_UUID_TYPE_16;
+    BT_UUID_16(uuid)->val = sys_get_le16(data);
+    break;
+  case 4:
+    uuid->type            = BT_UUID_TYPE_32;
+    BT_UUID_32(uuid)->val = sys_get_le32(data);
+    break;
+  case 16:
+    uuid->type = BT_UUID_TYPE_128;
+    memcpy(&BT_UUID_128(uuid)->val, data, 16);
+    break;
+  default:
+    return false;
+  }
+  return true;
 }
 
 #if defined(CONFIG_BT_DEBUG)
-void bt_uuid_to_str(const struct bt_uuid *uuid, char *str, size_t len)
-{
-    u32_t tmp1, tmp5;
-    u16_t tmp0, tmp2, tmp3, tmp4;
-
-    switch (uuid->type) {
-        case BT_UUID_TYPE_16:
-            snprintk(str, len, "%04x", BT_UUID_16(uuid)->val);
-            break;
-        case BT_UUID_TYPE_32:
-            snprintk(str, len, "%04x", BT_UUID_32(uuid)->val);
-            break;
-        case BT_UUID_TYPE_128:
-            memcpy(&tmp0, &BT_UUID_128(uuid)->val[0], sizeof(tmp0));
-            memcpy(&tmp1, &BT_UUID_128(uuid)->val[2], sizeof(tmp1));
-            memcpy(&tmp2, &BT_UUID_128(uuid)->val[6], sizeof(tmp2));
-            memcpy(&tmp3, &BT_UUID_128(uuid)->val[8], sizeof(tmp3));
-            memcpy(&tmp4, &BT_UUID_128(uuid)->val[10], sizeof(tmp4));
-            memcpy(&tmp5, &BT_UUID_128(uuid)->val[12], sizeof(tmp5));
-
-            snprintk(str, len, "%08x-%04x-%04x-%04x-%08x%04x",
-                     tmp5, tmp4, tmp3, tmp2, tmp1, tmp0);
-            break;
-        default:
-            (void)memset(str, 0, len);
-            return;
-    }
+void bt_uuid_to_str(const struct bt_uuid *uuid, char *str, size_t len) {
+  u32_t tmp1, tmp5;
+  u16_t tmp0, tmp2, tmp3, tmp4;
+
+  switch (uuid->type) {
+  case BT_UUID_TYPE_16:
+    snprintk(str, len, "%04x", BT_UUID_16(uuid)->val);
+    break;
+  case BT_UUID_TYPE_32:
+    snprintk(str, len, "%04x", BT_UUID_32(uuid)->val);
+    break;
+  case BT_UUID_TYPE_128:
+    memcpy(&tmp0, &BT_UUID_128(uuid)->val[0], sizeof(tmp0));
+    memcpy(&tmp1, &BT_UUID_128(uuid)->val[2], sizeof(tmp1));
+    memcpy(&tmp2, &BT_UUID_128(uuid)->val[6], sizeof(tmp2));
+    memcpy(&tmp3, &BT_UUID_128(uuid)->val[8], sizeof(tmp3));
+    memcpy(&tmp4, &BT_UUID_128(uuid)->val[10], sizeof(tmp4));
+    memcpy(&tmp5, &BT_UUID_128(uuid)->val[12], sizeof(tmp5));
+
+    snprintk(str, len, "%08x-%04x-%04x-%04x-%08x%04x", tmp5, tmp4, tmp3, tmp2, tmp1, tmp0);
+    break;
+  default:
+    (void)memset(str, 0, len);
+    return;
+  }
 }
 
-const char *bt_uuid_str_real(const struct bt_uuid *uuid)
-{
-    static char str[37];
+const char *bt_uuid_str_real(const struct bt_uuid *uuid) {
+  static char str[37];
 
-    bt_uuid_to_str(uuid, str, sizeof(str));
+  bt_uuid_to_str(uuid, str, sizeof(str));
 
-    return str;
+  return str;
 }
 #endif /* CONFIG_BT_DEBUG */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/gatt.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/gatt.h
index 709e8bc21e..26c43f173b 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/gatt.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/gatt.h
@@ -26,6 +26,7 @@
 #ifdef __cplusplus
 extern "C" {
 #endif
+#include "conn_internal.h"
 
 /* GATT attribute permission bit field values */
 enum {
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/bl_port.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/bl_port.c
index ccc1568d0f..05687274e1 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/bl_port.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/bl_port.c
@@ -1,384 +1,318 @@
-#include 
-#include 
 #include 
+#include 
+#include 
 
 #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BLUETOOTH_DEBUG_CORE)
 
+#include "atomic.h"
 #include 
 #include 
 #include 
 #include 
-#include "atomic.h"
 
 #include "errno.h"
 #include 
-#include 
 #include 
-#include 
 #include 
+#include 
+#include 
 
 #if defined(BL_MCU_SDK)
 #define TRNG_LOOP_COUNTER (17)
 extern BL_Err_Type Sec_Eng_Trng_Get_Random(uint8_t *data, uint32_t len);
 extern BL_Err_Type Sec_Eng_Trng_Enable(void);
-int bl_rand();
+int                bl_rand();
 #else
 extern int bl_rand();
 #endif
 
-int ble_rand()
-{
+int ble_rand() {
 #if defined(CONFIG_HW_SEC_ENG_DISABLE)
-    extern long random(void);
-    return random();
+  extern long random(void);
+  return random();
 #else
-    return bl_rand();
+  return bl_rand();
 #endif
 }
 
 #if defined(BL_MCU_SDK)
-int bl_rand()
-{
-    unsigned int val;
-    int counter = 0;
-    int32_t ret = 0;
-    do {
-        ret = Sec_Eng_Trng_Get_Random((uint8_t *)&val, 4);
-        if (ret < -1) {
-            return -1;
-        }
-        if ((counter++) > TRNG_LOOP_COUNTER) {
-            break;
-        }
-    } while (0 == val);
-    val >>= 1; //leave signe bit alone
-    return val;
+int bl_rand() {
+  unsigned int val;
+  int          counter = 0;
+  int32_t      ret     = 0;
+  do {
+    ret = Sec_Eng_Trng_Get_Random((uint8_t *)&val, 4);
+    if (ret < -1) {
+      return -1;
+    }
+    if ((counter++) > TRNG_LOOP_COUNTER) {
+      break;
+    }
+  } while (0 == val);
+  val >>= 1; // leave signe bit alone
+  return val;
 }
 #endif
 
-void k_queue_init(struct k_queue *queue, int size)
-{
-    //int size = 20;
-    uint8_t blk_size = sizeof(void *) + 1;
+void k_queue_init(struct k_queue *queue, int size) {
+  // int size = 20;
+  uint8_t blk_size = sizeof(void *) + 1;
 
-    queue->hdl = xQueueCreate(size, blk_size);
-    BT_ASSERT(queue->hdl != NULL);
+  queue->hdl = xQueueCreate(size, blk_size);
+  BT_ASSERT(queue->hdl != NULL);
 
-    sys_dlist_init(&queue->poll_events);
+  sys_dlist_init(&queue->poll_events);
 }
 
-void k_queue_insert(struct k_queue *queue, void *prev, void *data)
-{
-    BaseType_t ret;
-    (void)ret;
-
-    ret = xQueueSend(queue->hdl, &data, portMAX_DELAY);
-    BT_ASSERT(ret == pdPASS);
-}
+void k_queue_insert(struct k_queue *queue, void *prev, void *data) {
+  BaseType_t ret;
+  (void)ret;
 
-void k_queue_append(struct k_queue *queue, void *data)
-{
-    k_queue_insert(queue, NULL, data);
+  ret = xQueueSend(queue->hdl, &data, portMAX_DELAY);
+  BT_ASSERT(ret == pdPASS);
 }
 
-void k_queue_insert_from_isr(struct k_queue *queue, void *prev, void *data)
-{
-    BaseType_t xHigherPriorityTaskWoken;
+void k_queue_append(struct k_queue *queue, void *data) { k_queue_insert(queue, NULL, data); }
 
-    xQueueSendFromISR(queue->hdl, &data, &xHigherPriorityTaskWoken);
-    if (xHigherPriorityTaskWoken == pdTRUE) {
-        portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
-    }
-}
+void k_queue_insert_from_isr(struct k_queue *queue, void *prev, void *data) {
+  BaseType_t xHigherPriorityTaskWoken;
 
-void k_queue_append_from_isr(struct k_queue *queue, void *data)
-{
-    k_queue_insert_from_isr(queue, NULL, data);
+  xQueueSendFromISR(queue->hdl, &data, &xHigherPriorityTaskWoken);
+  if (xHigherPriorityTaskWoken == pdTRUE) {
+    portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
+  }
 }
 
-void k_queue_free(struct k_queue *queue)
-{
-    if (NULL == queue || NULL == queue->hdl) {
-        BT_ERR("Queue is NULL\n");
-        return;
-    }
+void k_queue_append_from_isr(struct k_queue *queue, void *data) { k_queue_insert_from_isr(queue, NULL, data); }
 
-    vQueueDelete(queue->hdl);
-    queue->hdl = NULL;
+void k_queue_free(struct k_queue *queue) {
+  if (NULL == queue || NULL == queue->hdl) {
+    BT_ERR("Queue is NULL\n");
     return;
-}
+  }
 
-void k_queue_prepend(struct k_queue *queue, void *data)
-{
-    k_queue_insert(queue, NULL, data);
+  vQueueDelete(queue->hdl);
+  queue->hdl = NULL;
+  return;
 }
 
-void k_queue_append_list(struct k_queue *queue, void *head, void *tail)
-{
-    struct net_buf *buf_tail = (struct net_buf *)head;
+void k_queue_prepend(struct k_queue *queue, void *data) { k_queue_insert(queue, NULL, data); }
 
-    for (buf_tail = (struct net_buf *)head; buf_tail; buf_tail = buf_tail->frags) {
-        k_queue_append(queue, buf_tail);
-    }
+void k_queue_append_list(struct k_queue *queue, void *head, void *tail) {
+  struct net_buf *buf_tail = (struct net_buf *)head;
+
+  for (buf_tail = (struct net_buf *)head; buf_tail; buf_tail = buf_tail->frags) {
+    k_queue_append(queue, buf_tail);
+  }
 }
 
-void *k_queue_get(struct k_queue *queue, s32_t timeout)
-{
-    void *msg = NULL;
-    unsigned int t = timeout;
-    BaseType_t ret;
+void *k_queue_get(struct k_queue *queue, s32_t timeout) {
+  void        *msg = NULL;
+  unsigned int t   = timeout;
+  BaseType_t   ret;
 
-    (void)ret;
+  (void)ret;
 
-    if (timeout == K_FOREVER) {
-        t = BL_WAIT_FOREVER;
-    } else if (timeout == K_NO_WAIT) {
-        t = BL_NO_WAIT;
-    }
+  if (timeout == K_FOREVER) {
+    t = BL_WAIT_FOREVER;
+  } else if (timeout == K_NO_WAIT) {
+    t = BL_NO_WAIT;
+  }
 
-    ret = xQueueReceive(queue->hdl, &msg, t == BL_WAIT_FOREVER ? portMAX_DELAY : ms2tick(t));
-    if (ret == pdPASS) {
-        return msg;
-    } else {
-        return NULL;
-    }
+  ret = xQueueReceive(queue->hdl, &msg, t == BL_WAIT_FOREVER ? portMAX_DELAY : ms2tick(t));
+  if (ret == pdPASS) {
+    return msg;
+  } else {
+    return NULL;
+  }
 }
 
-int k_queue_is_empty(struct k_queue *queue)
-{
-    return uxQueueMessagesWaiting(queue->hdl) ? 0 : 1;
-}
+int k_queue_is_empty(struct k_queue *queue) { return uxQueueMessagesWaiting(queue->hdl) ? 0 : 1; }
 
-int k_queue_get_cnt(struct k_queue *queue)
-{
-    return uxQueueMessagesWaiting(queue->hdl);
-}
+int k_queue_get_cnt(struct k_queue *queue) { return uxQueueMessagesWaiting(queue->hdl); }
 
-int k_sem_init(struct k_sem *sem, unsigned int initial_count, unsigned int limit)
-{
-    if (NULL == sem) {
-        BT_ERR("sem is NULL\n");
-        return -EINVAL;
-    }
+int k_sem_init(struct k_sem *sem, unsigned int initial_count, unsigned int limit) {
+  if (NULL == sem) {
+    BT_ERR("sem is NULL\n");
+    return -EINVAL;
+  }
 
-    sem->sem.hdl = xSemaphoreCreateCounting(limit, initial_count);
-    sys_dlist_init(&sem->poll_events);
-    return 0;
+  sem->sem.hdl = xSemaphoreCreateCounting(limit, initial_count);
+  sys_dlist_init(&sem->poll_events);
+  return 0;
 }
 
-int k_sem_take(struct k_sem *sem, uint32_t timeout)
-{
-    BaseType_t ret;
-    unsigned int t = timeout;
+int k_sem_take(struct k_sem *sem, uint32_t timeout) {
+  BaseType_t   ret;
+  unsigned int t = timeout;
 
-    (void)ret;
-    if (timeout == K_FOREVER) {
-        t = BL_WAIT_FOREVER;
-    } else if (timeout == K_NO_WAIT) {
-        t = BL_NO_WAIT;
-    }
+  (void)ret;
+  if (timeout == K_FOREVER) {
+    t = BL_WAIT_FOREVER;
+  } else if (timeout == K_NO_WAIT) {
+    t = BL_NO_WAIT;
+  }
 
-    if (NULL == sem) {
-        return -1;
-    }
+  if (NULL == sem) {
+    return -1;
+  }
 
-    ret = xSemaphoreTake(sem->sem.hdl, t == BL_WAIT_FOREVER ? portMAX_DELAY : ms2tick(t));
-    return ret == pdPASS ? 0 : -1;
+  ret = xSemaphoreTake(sem->sem.hdl, t == BL_WAIT_FOREVER ? portMAX_DELAY : ms2tick(t));
+  return ret == pdPASS ? 0 : -1;
 }
 
-int k_sem_give(struct k_sem *sem)
-{
-    BaseType_t ret;
-    (void)ret;
+int k_sem_give(struct k_sem *sem) {
+  BaseType_t ret;
+  (void)ret;
 
-    if (NULL == sem) {
-        BT_ERR("sem is NULL\n");
-        return -EINVAL;
-    }
+  if (NULL == sem) {
+    BT_ERR("sem is NULL\n");
+    return -EINVAL;
+  }
 
-    ret = xSemaphoreGive(sem->sem.hdl);
-    return ret == pdPASS ? 0 : -1;
+  ret = xSemaphoreGive(sem->sem.hdl);
+  return ret == pdPASS ? 0 : -1;
 }
 
-int k_sem_delete(struct k_sem *sem)
-{
-    if (NULL == sem || NULL == sem->sem.hdl) {
-        BT_ERR("sem is NULL\n");
-        return -EINVAL;
-    }
+int k_sem_delete(struct k_sem *sem) {
+  if (NULL == sem || NULL == sem->sem.hdl) {
+    BT_ERR("sem is NULL\n");
+    return -EINVAL;
+  }
 
-    vSemaphoreDelete(sem->sem.hdl);
-    sem->sem.hdl = NULL;
-    return 0;
+  vSemaphoreDelete(sem->sem.hdl);
+  sem->sem.hdl = NULL;
+  return 0;
 }
 
-unsigned int k_sem_count_get(struct k_sem *sem)
-{
-    return uxQueueMessagesWaiting(sem->sem.hdl);
-}
+unsigned int k_sem_count_get(struct k_sem *sem) { return uxQueueMessagesWaiting(sem->sem.hdl); }
 
-void k_mutex_init(struct k_mutex *mutex)
-{
-    if (NULL == mutex) {
-        BT_ERR("mutex is NULL\n");
-        return;
-    }
+void k_mutex_init(struct k_mutex *mutex) {
+  if (NULL == mutex) {
+    BT_ERR("mutex is NULL\n");
+    return;
+  }
 
-    mutex->mutex.hdl = xSemaphoreCreateMutex();
-    BT_ASSERT(mutex->mutex.hdl != NULL);
-    sys_dlist_init(&mutex->poll_events);
+  mutex->mutex.hdl = xSemaphoreCreateMutex();
+  BT_ASSERT(mutex->mutex.hdl != NULL);
+  sys_dlist_init(&mutex->poll_events);
 }
 
-int64_t k_uptime_get()
-{
-    return k_now_ms();
-}
+int64_t k_uptime_get() { return k_now_ms(); }
 
-u32_t k_uptime_get_32(void)
-{
-    return (u32_t)k_now_ms();
-}
+u32_t k_uptime_get_32(void) { return (u32_t)k_now_ms(); }
 
-int k_thread_create(struct k_thread *new_thread, const char *name,
-                    size_t stack_size, k_thread_entry_t entry,
-                    int prio)
-{
-    stack_size /= sizeof(StackType_t);
-    xTaskCreate(entry, name, stack_size, NULL, prio, (void *)(&new_thread->task));
+int k_thread_create(struct k_thread *new_thread, const char *name, size_t stack_size, k_thread_entry_t entry, int prio) {
+  stack_size /= sizeof(StackType_t);
+  xTaskCreate(entry, name, stack_size, NULL, prio, (void *)(&new_thread->task));
 
-    return new_thread->task ? 0 : -1;
+  return new_thread->task ? 0 : -1;
 }
 
-void k_thread_delete(struct k_thread *new_thread)
-{
-    if (NULL == new_thread || 0 == new_thread->task) {
-        BT_ERR("task is NULL\n");
-        return;
-    }
-
-    vTaskDelete((void *)(new_thread->task));
-    new_thread->task = 0;
+void k_thread_delete(struct k_thread *new_thread) {
+  if (NULL == new_thread || 0 == new_thread->task) {
+    BT_ERR("task is NULL\n");
     return;
-}
+  }
 
-int k_yield(void)
-{
-    taskYIELD();
-    return 0;
+  vTaskDelete((void *)(new_thread->task));
+  new_thread->task = 0;
+  return;
 }
 
-void k_sleep(s32_t dur_ms)
-{
-    TickType_t ticks;
-    ticks = pdMS_TO_TICKS(dur_ms);
-    vTaskDelay(ticks);
+int k_yield(void) {
+  taskYIELD();
+  return 0;
 }
 
-unsigned int irq_lock(void)
-{
-    taskENTER_CRITICAL();
-    return 1;
+void k_sleep(s32_t dur_ms) {
+  TickType_t ticks;
+  ticks = pdMS_TO_TICKS(dur_ms);
+  vTaskDelay(ticks);
 }
 
-void irq_unlock(unsigned int key)
-{
-    taskEXIT_CRITICAL();
+unsigned int irq_lock(void) {
+  taskENTER_CRITICAL();
+  return 1;
 }
 
-int k_is_in_isr(void)
-{
+void irq_unlock(unsigned int key) { taskEXIT_CRITICAL(); }
+
+int k_is_in_isr(void) {
 #if defined(ARCH_RISCV)
-    return (xPortIsInsideInterrupt());
+  return (xPortIsInsideInterrupt());
 #else
-    /* IRQs + PendSV (14) + SYSTICK (15) are interrupts. */
-    return (__get_IPSR() > 13);
+  /* IRQs + PendSV (14) + SYSTICK (15) are interrupts. */
+  return (__get_IPSR() > 13);
 #endif
 
-    return 0;
+  return 0;
 }
 
-void k_timer_init(k_timer_t *timer, k_timer_handler_t handle, void *args)
-{
-    BT_ASSERT(timer != NULL);
-    timer->handler = handle;
-    timer->args = args;
-    /* Set args as timer id */
-    timer->timer.hdl = xTimerCreate("Timer", pdMS_TO_TICKS(1000), 0, args, (TimerCallbackFunction_t)(timer->handler));
-    BT_ASSERT(timer->timer.hdl != NULL);
+void k_timer_init(k_timer_t *timer, k_timer_handler_t handle, void *args) {
+  BT_ASSERT(timer != NULL);
+  timer->handler = handle;
+  timer->args    = args;
+  /* Set args as timer id */
+  timer->timer.hdl = xTimerCreate("Timer", pdMS_TO_TICKS(1000), 0, args, (TimerCallbackFunction_t)(timer->handler));
+  BT_ASSERT(timer->timer.hdl != NULL);
 }
 
-void *k_timer_get_id(void *hdl)
-{
-    return pvTimerGetTimerID((TimerHandle_t)hdl);
-}
+void *k_timer_get_id(void *hdl) { return pvTimerGetTimerID((TimerHandle_t)hdl); }
 
-void k_timer_start(k_timer_t *timer, uint32_t timeout)
-{
-    BaseType_t ret;
-    (void)ret;
+void k_timer_start(k_timer_t *timer, uint32_t timeout) {
+  BaseType_t ret;
+  (void)ret;
 
-    BT_ASSERT(timer != NULL);
-    timer->timeout = timeout;
-    timer->start_ms = k_now_ms();
+  BT_ASSERT(timer != NULL);
+  timer->timeout  = timeout;
+  timer->start_ms = k_now_ms();
 
-    ret = xTimerChangePeriod(timer->timer.hdl, pdMS_TO_TICKS(timeout), 0);
-    BT_ASSERT(ret == pdPASS);
-    ret = xTimerStart(timer->timer.hdl, 0);
-    BT_ASSERT(ret == pdPASS);
+  ret = xTimerChangePeriod(timer->timer.hdl, pdMS_TO_TICKS(timeout), 0);
+  BT_ASSERT(ret == pdPASS);
+  ret = xTimerStart(timer->timer.hdl, 0);
+  BT_ASSERT(ret == pdPASS);
 }
 
-void k_timer_reset(k_timer_t *timer)
-{
-    BaseType_t ret;
+void k_timer_reset(k_timer_t *timer) {
+  BaseType_t ret;
 
-    (void)ret;
-    BT_ASSERT(timer != NULL);
+  (void)ret;
+  BT_ASSERT(timer != NULL);
 
-    ret = xTimerReset(timer->timer.hdl, 0);
-    BT_ASSERT(ret == pdPASS);
+  ret = xTimerReset(timer->timer.hdl, 0);
+  BT_ASSERT(ret == pdPASS);
 }
 
-void k_timer_stop(k_timer_t *timer)
-{
-    BaseType_t ret;
+void k_timer_stop(k_timer_t *timer) {
+  BaseType_t ret;
 
-    (void)ret;
-    BT_ASSERT(timer != NULL);
+  (void)ret;
+  BT_ASSERT(timer != NULL);
 
-    ret = xTimerStop(timer->timer.hdl, 0);
-    BT_ASSERT(ret == pdPASS);
+  ret = xTimerStop(timer->timer.hdl, 0);
+  BT_ASSERT(ret == pdPASS);
 }
 
-void k_timer_delete(k_timer_t *timer)
-{
-    BaseType_t ret;
-    (void)ret;
+void k_timer_delete(k_timer_t *timer) {
+  BaseType_t ret;
+  (void)ret;
 
-    BT_ASSERT(timer != NULL);
+  BT_ASSERT(timer != NULL);
 
-    ret = xTimerDelete(timer->timer.hdl, 0);
-    BT_ASSERT(ret == pdPASS);
+  ret = xTimerDelete(timer->timer.hdl, 0);
+  BT_ASSERT(ret == pdPASS);
 }
 
-long long k_now_ms(void)
-{
-    return (long long)(xTaskGetTickCount() * 1000) / configTICK_RATE_HZ;
-}
+long long k_now_ms(void) { return (long long)(xTaskGetTickCount() * 1000) / configTICK_RATE_HZ; }
 
-void k_get_random_byte_array(uint8_t *buf, size_t len)
-{
-    // bl_rand() return a word, but *buf may not be word-aligned
-    for (int i = 0; i < len; i++) {
-        *(buf + i) = (uint8_t)(ble_rand() & 0xFF);
-    }
+void k_get_random_byte_array(uint8_t *buf, size_t len) {
+  // bl_rand() return a word, but *buf may not be word-aligned
+  for (int i = 0; i < len; i++) {
+    *(buf + i) = (uint8_t)(ble_rand() & 0xFF);
+  }
 }
 
-void *k_malloc(size_t size)
-{
-    return pvPortMalloc(size);
-}
+void *k_malloc(size_t size) { return pvPortMalloc(size); }
 
-void k_free(void *buf)
-{
-    return vPortFree(buf);
-}
+void k_free(void *buf) { return vPortFree(buf); }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/alloc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/alloc.c
index 8e59674b0c..b9c5450721 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/alloc.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/alloc.c
@@ -17,8 +17,8 @@
  *
  ******************************************************************************/
 
-#include 
 #include 
+#include 
 
 #if defined(SBC_DEC_INCLUDED)
 
@@ -26,57 +26,52 @@
   $Revision: #1 $
 ***********************************************************************************/
 
-PRIVATE OI_STATUS OI_CODEC_SBC_Alloc(OI_CODEC_SBC_COMMON_CONTEXT *common,
-                                     OI_UINT32 *codecDataAligned,
-                                     OI_UINT32 codecDataBytes,
-                                     OI_UINT8 maxChannels,
-                                     OI_UINT8 pcmStride)
-{
-    int i;
-    size_t filterBufferCount;
-    size_t subdataSize;
-    OI_BYTE *codecData = (OI_BYTE *)codecDataAligned;
+PRIVATE OI_STATUS OI_CODEC_SBC_Alloc(OI_CODEC_SBC_COMMON_CONTEXT *common, OI_UINT32 *codecDataAligned, OI_UINT32 codecDataBytes, OI_UINT8 maxChannels, OI_UINT8 pcmStride) {
+  int      i;
+  size_t   filterBufferCount;
+  size_t   subdataSize;
+  OI_BYTE *codecData = (OI_BYTE *)codecDataAligned;
 
-    if (maxChannels < 1 || maxChannels > 2) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
+  if (maxChannels < 1 || maxChannels > 2) {
+    return OI_STATUS_INVALID_PARAMETERS;
+  }
 
-    if (pcmStride < 1 || pcmStride > maxChannels) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
+  if (pcmStride < 1 || pcmStride > maxChannels) {
+    return OI_STATUS_INVALID_PARAMETERS;
+  }
 
-    common->maxChannels = maxChannels;
-    common->pcmStride = pcmStride;
+  common->maxChannels = maxChannels;
+  common->pcmStride   = pcmStride;
 
-    /* Compute sizes needed for the memory regions, and bail if we don't have
-     * enough memory for them. */
-    subdataSize = maxChannels * sizeof(common->subdata[0]) * SBC_MAX_BANDS * SBC_MAX_BLOCKS;
-    if (subdataSize > codecDataBytes) {
-        return OI_STATUS_OUT_OF_MEMORY;
-    }
+  /* Compute sizes needed for the memory regions, and bail if we don't have
+   * enough memory for them. */
+  subdataSize = maxChannels * sizeof(common->subdata[0]) * SBC_MAX_BANDS * SBC_MAX_BLOCKS;
+  if (subdataSize > codecDataBytes) {
+    return OI_STATUS_OUT_OF_MEMORY;
+  }
 
-    filterBufferCount = (codecDataBytes - subdataSize) / (sizeof(common->filterBuffer[0][0]) * SBC_MAX_BANDS * maxChannels);
-    if (filterBufferCount < SBC_CODEC_MIN_FILTER_BUFFERS) {
-        return OI_STATUS_OUT_OF_MEMORY;
-    }
-    common->filterBufferLen = filterBufferCount * SBC_MAX_BANDS;
+  filterBufferCount = (codecDataBytes - subdataSize) / (sizeof(common->filterBuffer[0][0]) * SBC_MAX_BANDS * maxChannels);
+  if (filterBufferCount < SBC_CODEC_MIN_FILTER_BUFFERS) {
+    return OI_STATUS_OUT_OF_MEMORY;
+  }
+  common->filterBufferLen = filterBufferCount * SBC_MAX_BANDS;
 
-    /* Allocate memory for the subband data */
-    common->subdata = (OI_INT32 *)codecData;
-    codecData += subdataSize;
-    OI_ASSERT(codecDataBytes >= subdataSize);
-    codecDataBytes -= subdataSize;
+  /* Allocate memory for the subband data */
+  common->subdata = (OI_INT32 *)codecData;
+  codecData += subdataSize;
+  OI_ASSERT(codecDataBytes >= subdataSize);
+  codecDataBytes -= subdataSize;
 
-    /* Allocate memory for the synthesis buffers */
-    for (i = 0; i < maxChannels; ++i) {
-        size_t allocSize = common->filterBufferLen * sizeof(common->filterBuffer[0][0]);
-        common->filterBuffer[i] = (SBC_BUFFER_T *)codecData;
-        OI_ASSERT(codecDataBytes >= allocSize);
-        codecData += allocSize;
-        codecDataBytes -= allocSize;
-    }
+  /* Allocate memory for the synthesis buffers */
+  for (i = 0; i < maxChannels; ++i) {
+    size_t allocSize        = common->filterBufferLen * sizeof(common->filterBuffer[0][0]);
+    common->filterBuffer[i] = (SBC_BUFFER_T *)codecData;
+    OI_ASSERT(codecDataBytes >= allocSize);
+    codecData += allocSize;
+    codecDataBytes -= allocSize;
+  }
 
-    return OI_OK;
+  return OI_OK;
 }
 
 #endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc-sbc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc-sbc.c
index 6eedd26b59..f903dc8a94 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc-sbc.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc-sbc.c
@@ -31,61 +31,59 @@
 
 #if defined(SBC_DEC_INCLUDED)
 
-static void dualBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common)
-{
-    OI_UINT bitcountL;
-    OI_UINT bitcountR;
-    OI_UINT bitpoolPreferenceL = 0;
-    OI_UINT bitpoolPreferenceR = 0;
-    BITNEED_UNION1 bitneedsL;
-    BITNEED_UNION1 bitneedsR;
-
-    bitcountL = computeBitneed(common, bitneedsL.uint8, 0, &bitpoolPreferenceL);
-    bitcountR = computeBitneed(common, bitneedsR.uint8, 1, &bitpoolPreferenceR);
-
-    oneChannelBitAllocation(common, &bitneedsL, 0, bitcountL);
-    oneChannelBitAllocation(common, &bitneedsR, 1, bitcountR);
+static void dualBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common) {
+  OI_UINT        bitcountL;
+  OI_UINT        bitcountR;
+  OI_UINT        bitpoolPreferenceL = 0;
+  OI_UINT        bitpoolPreferenceR = 0;
+  BITNEED_UNION1 bitneedsL;
+  BITNEED_UNION1 bitneedsR;
+
+  bitcountL = computeBitneed(common, bitneedsL.uint8, 0, &bitpoolPreferenceL);
+  bitcountR = computeBitneed(common, bitneedsR.uint8, 1, &bitpoolPreferenceR);
+
+  oneChannelBitAllocation(common, &bitneedsL, 0, bitcountL);
+  oneChannelBitAllocation(common, &bitneedsR, 1, bitcountR);
 }
 
-static void stereoBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common)
-{
-    const OI_UINT nrof_subbands = common->frameInfo.nrof_subbands;
-    BITNEED_UNION2 bitneeds;
-    OI_UINT excess;
-    OI_INT bitadjust;
-    OI_UINT bitcount;
-    OI_UINT sbL;
-    OI_UINT sbR;
-    OI_UINT bitpoolPreference = 0;
-
-    bitcount = computeBitneed(common, &bitneeds.uint8[0], 0, &bitpoolPreference);
-    bitcount += computeBitneed(common, &bitneeds.uint8[nrof_subbands], 1, &bitpoolPreference);
-
-    {
-        OI_UINT ex;
-        bitadjust = adjustToFitBitpool(common->frameInfo.bitpool, bitneeds.uint32, 2 * nrof_subbands, bitcount, &ex);
-        /* We want the compiler to put excess into a register */
-        excess = ex;
-    }
-    sbL = 0;
-    sbR = nrof_subbands;
-    while (sbL < nrof_subbands) {
-        excess = allocAdjustedBits(&common->bits.uint8[sbL], bitneeds.uint8[sbL] + bitadjust, excess);
-        ++sbL;
-        excess = allocAdjustedBits(&common->bits.uint8[sbR], bitneeds.uint8[sbR] + bitadjust, excess);
-        ++sbR;
-    }
-    sbL = 0;
-    sbR = nrof_subbands;
-    while (excess) {
-        excess = allocExcessBits(&common->bits.uint8[sbL], excess);
-        ++sbL;
-        if (!excess) {
-            break;
-        }
-        excess = allocExcessBits(&common->bits.uint8[sbR], excess);
-        ++sbR;
+static void stereoBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common) {
+  const OI_UINT  nrof_subbands = common->frameInfo.nrof_subbands;
+  BITNEED_UNION2 bitneeds;
+  OI_UINT        excess;
+  OI_INT         bitadjust;
+  OI_UINT        bitcount;
+  OI_UINT        sbL;
+  OI_UINT        sbR;
+  OI_UINT        bitpoolPreference = 0;
+
+  bitcount = computeBitneed(common, &bitneeds.uint8[0], 0, &bitpoolPreference);
+  bitcount += computeBitneed(common, &bitneeds.uint8[nrof_subbands], 1, &bitpoolPreference);
+
+  {
+    OI_UINT ex;
+    bitadjust = adjustToFitBitpool(common->frameInfo.bitpool, bitneeds.uint32, 2 * nrof_subbands, bitcount, &ex);
+    /* We want the compiler to put excess into a register */
+    excess = ex;
+  }
+  sbL = 0;
+  sbR = nrof_subbands;
+  while (sbL < nrof_subbands) {
+    excess = allocAdjustedBits(&common->bits.uint8[sbL], bitneeds.uint8[sbL] + bitadjust, excess);
+    ++sbL;
+    excess = allocAdjustedBits(&common->bits.uint8[sbR], bitneeds.uint8[sbR] + bitadjust, excess);
+    ++sbR;
+  }
+  sbL = 0;
+  sbR = nrof_subbands;
+  while (excess) {
+    excess = allocExcessBits(&common->bits.uint8[sbL], excess);
+    ++sbL;
+    if (!excess) {
+      break;
     }
+    excess = allocExcessBits(&common->bits.uint8[sbR], excess);
+    ++sbR;
+  }
 }
 
 static const BIT_ALLOC balloc[] = {
@@ -95,70 +93,57 @@ static const BIT_ALLOC balloc[] = {
     stereoBitAllocation  /* SBC_JOINT_STEREO */
 };
 
-PRIVATE void OI_SBC_ComputeBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common)
-{
-    OI_ASSERT(common->frameInfo.bitpool <= OI_SBC_MaxBitpool(&common->frameInfo));
-    OI_ASSERT(common->frameInfo.mode < OI_ARRAYSIZE(balloc));
+PRIVATE void OI_SBC_ComputeBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common) {
+  OI_ASSERT(common->frameInfo.bitpool <= OI_SBC_MaxBitpool(&common->frameInfo));
+  OI_ASSERT(common->frameInfo.mode < OI_ARRAYSIZE(balloc));
 
-    /*
-     * Using an array of function pointers prevents the compiler from creating a suboptimal
-     * monolithic inlined bit allocation function.
-     */
-    balloc[common->frameInfo.mode](common);
+  /*
+   * Using an array of function pointers prevents the compiler from creating a suboptimal
+   * monolithic inlined bit allocation function.
+   */
+  balloc[common->frameInfo.mode](common);
 }
 
-OI_UINT32 OI_CODEC_SBC_CalculateBitrate(OI_CODEC_SBC_FRAME_INFO *frame)
-{
-    return internal_CalculateBitrate(frame);
-}
+OI_UINT32 OI_CODEC_SBC_CalculateBitrate(OI_CODEC_SBC_FRAME_INFO *frame) { return internal_CalculateBitrate(frame); }
 
 /*
  * Return the current maximum bitneed and clear it.
  */
-OI_UINT8 OI_CODEC_SBC_GetMaxBitneed(OI_CODEC_SBC_COMMON_CONTEXT *common)
-{
-    OI_UINT8 max = common->maxBitneed;
+OI_UINT8 OI_CODEC_SBC_GetMaxBitneed(OI_CODEC_SBC_COMMON_CONTEXT *common) {
+  OI_UINT8 max = common->maxBitneed;
 
-    common->maxBitneed = 0;
-    return max;
+  common->maxBitneed = 0;
+  return max;
 }
 
 /*
  * Calculates the bitpool size for a given frame length
  */
-OI_UINT16 OI_CODEC_SBC_CalculateBitpool(OI_CODEC_SBC_FRAME_INFO *frame,
-                                        OI_UINT16 frameLen)
-{
-    OI_UINT16 nrof_subbands = frame->nrof_subbands;
-    OI_UINT16 nrof_blocks = frame->nrof_blocks;
-    OI_UINT16 hdr;
-    OI_UINT16 bits;
-
-    if (frame->mode == SBC_JOINT_STEREO) {
-        hdr = 9 * nrof_subbands;
+OI_UINT16 OI_CODEC_SBC_CalculateBitpool(OI_CODEC_SBC_FRAME_INFO *frame, OI_UINT16 frameLen) {
+  OI_UINT16 nrof_subbands = frame->nrof_subbands;
+  OI_UINT16 nrof_blocks   = frame->nrof_blocks;
+  OI_UINT16 hdr;
+  OI_UINT16 bits;
+
+  if (frame->mode == SBC_JOINT_STEREO) {
+    hdr = 9 * nrof_subbands;
+  } else {
+    if (frame->mode == SBC_MONO) {
+      hdr = 4 * nrof_subbands;
     } else {
-        if (frame->mode == SBC_MONO) {
-            hdr = 4 * nrof_subbands;
-        } else {
-            hdr = 8 * nrof_subbands;
-        }
-        if (frame->mode == SBC_DUAL_CHANNEL) {
-            nrof_blocks *= 2;
-        }
+      hdr = 8 * nrof_subbands;
     }
-    bits = 8 * (frameLen - SBC_HEADER_LEN) - hdr;
-    return DIVIDE(bits, nrof_blocks);
+    if (frame->mode == SBC_DUAL_CHANNEL) {
+      nrof_blocks *= 2;
+    }
+  }
+  bits = 8 * (frameLen - SBC_HEADER_LEN) - hdr;
+  return DIVIDE(bits, nrof_blocks);
 }
 
-OI_UINT16 OI_CODEC_SBC_CalculatePcmBytes(OI_CODEC_SBC_COMMON_CONTEXT *common)
-{
-    return sizeof(OI_INT16) * common->pcmStride * common->frameInfo.nrof_subbands * common->frameInfo.nrof_blocks;
-}
+OI_UINT16 OI_CODEC_SBC_CalculatePcmBytes(OI_CODEC_SBC_COMMON_CONTEXT *common) { return sizeof(OI_INT16) * common->pcmStride * common->frameInfo.nrof_subbands * common->frameInfo.nrof_blocks; }
 
-OI_UINT16 OI_CODEC_SBC_CalculateFramelen(OI_CODEC_SBC_FRAME_INFO *frame)
-{
-    return internal_CalculateFramelen(frame);
-}
+OI_UINT16 OI_CODEC_SBC_CalculateFramelen(OI_CODEC_SBC_FRAME_INFO *frame) { return internal_CalculateFramelen(frame); }
 
 /**@}*/
 #endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc.c
index 7b8b4586f5..e3e20ddce5 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc.c
@@ -41,61 +41,57 @@ frame length and bitrate.
 
 #if defined(SBC_DEC_INCLUDED)
 
-OI_UINT32 OI_SBC_MaxBitpool(OI_CODEC_SBC_FRAME_INFO *frame)
-{
-    switch (frame->mode) {
-        case SBC_MONO:
-        case SBC_DUAL_CHANNEL:
-            return 16 * frame->nrof_subbands;
-        case SBC_STEREO:
-        case SBC_JOINT_STEREO:
-            return 32 * frame->nrof_subbands;
-    }
-
-    ERROR(("Invalid frame mode %d", frame->mode));
-    OI_ASSERT(FALSE);
-    return 0; /* Should never be reached */
+OI_UINT32 OI_SBC_MaxBitpool(OI_CODEC_SBC_FRAME_INFO *frame) {
+  switch (frame->mode) {
+  case SBC_MONO:
+  case SBC_DUAL_CHANNEL:
+    return 16 * frame->nrof_subbands;
+  case SBC_STEREO:
+  case SBC_JOINT_STEREO:
+    return 32 * frame->nrof_subbands;
+  }
+
+  ERROR(("Invalid frame mode %d", frame->mode));
+  OI_ASSERT(FALSE);
+  return 0; /* Should never be reached */
 }
 
-PRIVATE OI_UINT16 internal_CalculateFramelen(OI_CODEC_SBC_FRAME_INFO *frame)
-{
-    OI_UINT16 nbits = frame->nrof_blocks * frame->bitpool;
-    OI_UINT16 nrof_subbands = frame->nrof_subbands;
-    OI_UINT16 result = nbits;
+PRIVATE OI_UINT16 internal_CalculateFramelen(OI_CODEC_SBC_FRAME_INFO *frame) {
+  OI_UINT16 nbits         = frame->nrof_blocks * frame->bitpool;
+  OI_UINT16 nrof_subbands = frame->nrof_subbands;
+  OI_UINT16 result        = nbits;
 
-    if (frame->mode == SBC_JOINT_STEREO) {
-        result += nrof_subbands + (8 * nrof_subbands);
+  if (frame->mode == SBC_JOINT_STEREO) {
+    result += nrof_subbands + (8 * nrof_subbands);
+  } else {
+    if (frame->mode == SBC_DUAL_CHANNEL) {
+      result += nbits;
+    }
+    if (frame->mode == SBC_MONO) {
+      result += 4 * nrof_subbands;
     } else {
-        if (frame->mode == SBC_DUAL_CHANNEL) {
-            result += nbits;
-        }
-        if (frame->mode == SBC_MONO) {
-            result += 4 * nrof_subbands;
-        } else {
-            result += 8 * nrof_subbands;
-        }
+      result += 8 * nrof_subbands;
     }
-    return SBC_HEADER_LEN + (result + 7) / 8;
+  }
+  return SBC_HEADER_LEN + (result + 7) / 8;
 }
 
-PRIVATE OI_UINT32 internal_CalculateBitrate(OI_CODEC_SBC_FRAME_INFO *frame)
-{
-    OI_UINT blocksbands;
-    blocksbands = frame->nrof_subbands * frame->nrof_blocks;
+PRIVATE OI_UINT32 internal_CalculateBitrate(OI_CODEC_SBC_FRAME_INFO *frame) {
+  OI_UINT blocksbands;
+  blocksbands = frame->nrof_subbands * frame->nrof_blocks;
 
-    return DIVIDE(8 * internal_CalculateFramelen(frame) * frame->frequency, blocksbands);
+  return DIVIDE(8 * internal_CalculateFramelen(frame) * frame->frequency, blocksbands);
 }
 
-INLINE OI_UINT16 OI_SBC_CalculateFrameAndHeaderlen(OI_CODEC_SBC_FRAME_INFO *frame, OI_UINT *headerLen_)
-{
-    OI_UINT headerLen = SBC_HEADER_LEN + frame->nrof_subbands * frame->nrof_channels / 2;
+INLINE OI_UINT16 OI_SBC_CalculateFrameAndHeaderlen(OI_CODEC_SBC_FRAME_INFO *frame, OI_UINT *headerLen_) {
+  OI_UINT headerLen = SBC_HEADER_LEN + frame->nrof_subbands * frame->nrof_channels / 2;
 
-    if (frame->mode == SBC_JOINT_STEREO) {
-        headerLen++;
-    }
+  if (frame->mode == SBC_JOINT_STEREO) {
+    headerLen++;
+  }
 
-    *headerLen_ = headerLen;
-    return internal_CalculateFramelen(frame);
+  *headerLen_ = headerLen;
+  return internal_CalculateFramelen(frame);
 }
 
 #define MIN(x, y) ((x) < (y) ? (x) : (y))
@@ -120,71 +116,57 @@ INLINE OI_UINT16 OI_SBC_CalculateFrameAndHeaderlen(OI_CODEC_SBC_FRAME_INFO *fram
  * @return              The SBC bit need
  *
  */
-OI_UINT computeBitneed(OI_CODEC_SBC_COMMON_CONTEXT *common,
-                       OI_UINT8 *bitneeds,
-                       OI_UINT ch,
-                       OI_UINT *preferredBitpool)
-{
-    static const OI_INT8 offset4[4][4] = {
-        { -1, 0, 0, 0 },
-        { -2, 0, 0, 1 },
-        { -2, 0, 0, 1 },
-        { -2, 0, 0, 1 }
-    };
-
-    static const OI_INT8 offset8[4][8] = {
-        { -2, 0, 0, 0, 0, 0, 0, 1 },
-        { -3, 0, 0, 0, 0, 0, 1, 2 },
-        { -4, 0, 0, 0, 0, 0, 1, 2 },
-        { -4, 0, 0, 0, 0, 0, 1, 2 }
-    };
-
-    const OI_UINT nrof_subbands = common->frameInfo.nrof_subbands;
-    OI_UINT sb;
-    OI_INT8 *scale_factor = &common->scale_factor[ch ? nrof_subbands : 0];
-    OI_UINT bitcount = 0;
-    OI_UINT8 maxBits = 0;
-    OI_UINT8 prefBits = 0;
-
-    if (common->frameInfo.alloc == SBC_SNR) {
-        for (sb = 0; sb < nrof_subbands; sb++) {
-            OI_INT bits = scale_factor[sb];
-            if (bits > maxBits) {
-                maxBits = bits;
-            }
-            if ((bitneeds[sb] = bits) > 1) {
-                bitcount += bits;
-            }
-            prefBits += 2 + bits;
-        }
+OI_UINT computeBitneed(OI_CODEC_SBC_COMMON_CONTEXT *common, OI_UINT8 *bitneeds, OI_UINT ch, OI_UINT *preferredBitpool) {
+  static const OI_INT8 offset4[4][4] = {{-1, 0, 0, 0}, {-2, 0, 0, 1}, {-2, 0, 0, 1}, {-2, 0, 0, 1}};
+
+  static const OI_INT8 offset8[4][8] = {{-2, 0, 0, 0, 0, 0, 0, 1}, {-3, 0, 0, 0, 0, 0, 1, 2}, {-4, 0, 0, 0, 0, 0, 1, 2}, {-4, 0, 0, 0, 0, 0, 1, 2}};
+
+  const OI_UINT nrof_subbands = common->frameInfo.nrof_subbands;
+  OI_UINT       sb;
+  OI_INT8      *scale_factor = &common->scale_factor[ch ? nrof_subbands : 0];
+  OI_UINT       bitcount     = 0;
+  OI_UINT8      maxBits      = 0;
+  OI_UINT8      prefBits     = 0;
+
+  if (common->frameInfo.alloc == SBC_SNR) {
+    for (sb = 0; sb < nrof_subbands; sb++) {
+      OI_INT bits = scale_factor[sb];
+      if (bits > maxBits) {
+        maxBits = bits;
+      }
+      if ((bitneeds[sb] = bits) > 1) {
+        bitcount += bits;
+      }
+      prefBits += 2 + bits;
+    }
+  } else {
+    const OI_INT8 *offset;
+    if (nrof_subbands == 4) {
+      offset = offset4[common->frameInfo.freqIndex];
     } else {
-        const OI_INT8 *offset;
-        if (nrof_subbands == 4) {
-            offset = offset4[common->frameInfo.freqIndex];
-        } else {
-            offset = offset8[common->frameInfo.freqIndex];
-        }
-        for (sb = 0; sb < nrof_subbands; sb++) {
-            OI_INT bits = scale_factor[sb];
-            if (bits > maxBits) {
-                maxBits = bits;
-            }
-            prefBits += 2 + bits;
-            if (bits) {
-                bits -= offset[sb];
-                if (bits > 0) {
-                    bits /= 2;
-                }
-                bits += 5;
-            }
-            if ((bitneeds[sb] = bits) > 1) {
-                bitcount += bits;
-            }
+      offset = offset8[common->frameInfo.freqIndex];
+    }
+    for (sb = 0; sb < nrof_subbands; sb++) {
+      OI_INT bits = scale_factor[sb];
+      if (bits > maxBits) {
+        maxBits = bits;
+      }
+      prefBits += 2 + bits;
+      if (bits) {
+        bits -= offset[sb];
+        if (bits > 0) {
+          bits /= 2;
         }
+        bits += 5;
+      }
+      if ((bitneeds[sb] = bits) > 1) {
+        bitcount += bits;
+      }
     }
-    common->maxBitneed = OI_MAX(maxBits, common->maxBitneed);
-    *preferredBitpool += prefBits;
-    return bitcount;
+  }
+  common->maxBitneed = OI_MAX(maxBits, common->maxBitneed);
+  *preferredBitpool += prefBits;
+  return bitcount;
 }
 
 /*
@@ -246,144 +228,129 @@ OI_UINT computeBitneed(OI_CODEC_SBC_COMMON_CONTEXT *common,
  *
  * @return   The adjustment.
  */
-OI_INT adjustToFitBitpool(const OI_UINT bitpool,
-                          OI_UINT32 *bitneeds,
-                          const OI_UINT subbands,
-                          OI_UINT bitcount,
-                          OI_UINT *excess)
-{
-    OI_INT maxBitadjust = 0;
-    OI_INT bitadjust = (bitcount > bitpool) ? -8 : 8;
-    OI_INT chop = 8;
-
-    /*
-     * This is essentially a binary search for the optimal adjustment value.
-     */
-    while ((bitcount != bitpool) && chop) {
-        OI_UINT32 total = 0;
-        OI_UINT count;
-        OI_UINT32 adjust4;
-        OI_INT i;
-
-        adjust4 = bitadjust & 0x7F;
-        adjust4 |= (adjust4 << 8);
-        adjust4 |= (adjust4 << 16);
-
-        for (i = (subbands / 4 - 1); i >= 0; --i) {
-            OI_UINT32 mask;
-            OI_UINT32 n = bitneeds[i] + adjust4;
-            mask = 0x7F7F7F7F + ((n & 0x40404040) >> 6);
-            n &= mask;
-            mask = 0x0F0F0F0F + ((n & 0x10101010) >> 4);
-            n &= mask;
-            mask = (((n + 0x0E0E0E0E) >> 4) | 0x1E1E1E1E);
-            n &= mask;
-            total += n;
-        }
+OI_INT adjustToFitBitpool(const OI_UINT bitpool, OI_UINT32 *bitneeds, const OI_UINT subbands, OI_UINT bitcount, OI_UINT *excess) {
+  OI_INT maxBitadjust = 0;
+  OI_INT bitadjust    = (bitcount > bitpool) ? -8 : 8;
+  OI_INT chop         = 8;
+
+  /*
+   * This is essentially a binary search for the optimal adjustment value.
+   */
+  while ((bitcount != bitpool) && chop) {
+    OI_UINT32 total = 0;
+    OI_UINT   count;
+    OI_UINT32 adjust4;
+    OI_INT    i;
+
+    adjust4 = bitadjust & 0x7F;
+    adjust4 |= (adjust4 << 8);
+    adjust4 |= (adjust4 << 16);
+
+    for (i = (subbands / 4 - 1); i >= 0; --i) {
+      OI_UINT32 mask;
+      OI_UINT32 n = bitneeds[i] + adjust4;
+      mask        = 0x7F7F7F7F + ((n & 0x40404040) >> 6);
+      n &= mask;
+      mask = 0x0F0F0F0F + ((n & 0x10101010) >> 4);
+      n &= mask;
+      mask = (((n + 0x0E0E0E0E) >> 4) | 0x1E1E1E1E);
+      n &= mask;
+      total += n;
+    }
 
-        count = (total & 0xFFFF) + (total >> 16);
-        count = (count & 0xFF) + (count >> 8);
+    count = (total & 0xFFFF) + (total >> 16);
+    count = (count & 0xFF) + (count >> 8);
 
-        chop >>= 1;
-        if (count > bitpool) {
-            bitadjust -= chop;
-        } else {
-            maxBitadjust = bitadjust;
-            bitcount = count;
-            bitadjust += chop;
-        }
+    chop >>= 1;
+    if (count > bitpool) {
+      bitadjust -= chop;
+    } else {
+      maxBitadjust = bitadjust;
+      bitcount     = count;
+      bitadjust += chop;
     }
+  }
 
-    *excess = bitpool - bitcount;
+  *excess = bitpool - bitcount;
 
-    return maxBitadjust;
+  return maxBitadjust;
 }
 
 /*
  * The bit allocator trys to avoid single bit allocations except as a last resort. So in the case
  * where a bitneed of 1 was passed over during the adsjustment phase 2 bits are now allocated.
  */
-INLINE OI_INT allocAdjustedBits(OI_UINT8 *dest,
-                                OI_INT bits,
-                                OI_INT excess)
-{
-    if (bits < 16) {
-        if (bits > 1) {
-            if (excess) {
-                ++bits;
-                --excess;
-            }
-        } else if ((bits == 1) && (excess > 1)) {
-            bits = 2;
-            excess -= 2;
-        } else {
-            bits = 0;
-        }
+INLINE OI_INT allocAdjustedBits(OI_UINT8 *dest, OI_INT bits, OI_INT excess) {
+  if (bits < 16) {
+    if (bits > 1) {
+      if (excess) {
+        ++bits;
+        --excess;
+      }
+    } else if ((bits == 1) && (excess > 1)) {
+      bits = 2;
+      excess -= 2;
     } else {
-        bits = 16;
+      bits = 0;
     }
-    *dest = (OI_UINT8)bits;
-    return excess;
+  } else {
+    bits = 16;
+  }
+  *dest = (OI_UINT8)bits;
+  return excess;
 }
 
 /*
  * Excess bits not allocated by allocaAdjustedBits are allocated round-robin.
  */
-INLINE OI_INT allocExcessBits(OI_UINT8 *dest,
-                              OI_INT excess)
-{
-    if (*dest < 16) {
-        *dest += 1;
-        return excess - 1;
-    } else {
-        return excess;
-    }
+INLINE OI_INT allocExcessBits(OI_UINT8 *dest, OI_INT excess) {
+  if (*dest < 16) {
+    *dest += 1;
+    return excess - 1;
+  } else {
+    return excess;
+  }
 }
 
-void oneChannelBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common,
-                             BITNEED_UNION1 *bitneeds,
-                             OI_UINT ch,
-                             OI_UINT bitcount)
-{
-    const OI_UINT8 nrof_subbands = common->frameInfo.nrof_subbands;
-    OI_UINT excess;
-    OI_UINT sb;
-    OI_INT bitadjust;
-    OI_UINT8 RESTRICT *allocBits;
-
-    {
-        OI_UINT ex;
-        bitadjust = adjustToFitBitpool(common->frameInfo.bitpool, bitneeds->uint32, nrof_subbands, bitcount, &ex);
-        /* We want the compiler to put excess into a register */
-        excess = ex;
-    }
-
-    /*
-     * Allocate adjusted bits
-     */
-    allocBits = &common->bits.uint8[ch ? nrof_subbands : 0];
-
-    sb = 0;
-    while (sb < nrof_subbands) {
-        excess = allocAdjustedBits(&allocBits[sb], bitneeds->uint8[sb] + bitadjust, excess);
-        ++sb;
-    }
-    sb = 0;
-    while (excess) {
-        excess = allocExcessBits(&allocBits[sb], excess);
-        ++sb;
-    }
+void oneChannelBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common, BITNEED_UNION1 *bitneeds, OI_UINT ch, OI_UINT bitcount) {
+  const OI_UINT8     nrof_subbands = common->frameInfo.nrof_subbands;
+  OI_UINT            excess;
+  OI_UINT            sb;
+  OI_INT             bitadjust;
+  OI_UINT8 RESTRICT *allocBits;
+
+  {
+    OI_UINT ex;
+    bitadjust = adjustToFitBitpool(common->frameInfo.bitpool, bitneeds->uint32, nrof_subbands, bitcount, &ex);
+    /* We want the compiler to put excess into a register */
+    excess = ex;
+  }
+
+  /*
+   * Allocate adjusted bits
+   */
+  allocBits = &common->bits.uint8[ch ? nrof_subbands : 0];
+
+  sb = 0;
+  while (sb < nrof_subbands) {
+    excess = allocAdjustedBits(&allocBits[sb], bitneeds->uint8[sb] + bitadjust, excess);
+    ++sb;
+  }
+  sb = 0;
+  while (excess) {
+    excess = allocExcessBits(&allocBits[sb], excess);
+    ++sb;
+  }
 }
 
-void monoBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common)
-{
-    BITNEED_UNION1 bitneeds;
-    OI_UINT bitcount;
-    OI_UINT bitpoolPreference = 0;
+void monoBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common) {
+  BITNEED_UNION1 bitneeds;
+  OI_UINT        bitcount;
+  OI_UINT        bitpoolPreference = 0;
 
-    bitcount = computeBitneed(common, bitneeds.uint8, 0, &bitpoolPreference);
+  bitcount = computeBitneed(common, bitneeds.uint8, 0, &bitpoolPreference);
 
-    oneChannelBitAllocation(common, &bitneeds, 0, bitcount);
+  oneChannelBitAllocation(common, &bitneeds, 0, bitcount);
 }
 
 /**
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitstream-decode.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitstream-decode.c
index da20e31492..43d2e61e10 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitstream-decode.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitstream-decode.c
@@ -33,58 +33,53 @@ Functions for manipulating input bitstreams.
 @{
 */
 
-#include "oi_stddefs.h"
-#include "oi_bitstream.h"
 #include "oi_assert.h"
+#include "oi_bitstream.h"
+#include "oi_stddefs.h"
 
 #if defined(SBC_DEC_INCLUDED)
 
-PRIVATE void OI_BITSTREAM_ReadInit(OI_BITSTREAM *bs,
-                                   const OI_BYTE *buffer)
-{
-    bs->value = ((OI_INT32)buffer[0] << 16) | ((OI_INT32)buffer[1] << 8) | (buffer[2]);
-    bs->ptr.r = buffer + 3;
-    bs->bitPtr = 8;
+PRIVATE void OI_BITSTREAM_ReadInit(OI_BITSTREAM *bs, const OI_BYTE *buffer) {
+  bs->value  = ((OI_INT32)buffer[0] << 16) | ((OI_INT32)buffer[1] << 8) | (buffer[2]);
+  bs->ptr.r  = buffer + 3;
+  bs->bitPtr = 8;
 }
 
-PRIVATE OI_UINT32 OI_BITSTREAM_ReadUINT(OI_BITSTREAM *bs, OI_UINT bits)
-{
-    OI_UINT32 result;
+PRIVATE OI_UINT32 OI_BITSTREAM_ReadUINT(OI_BITSTREAM *bs, OI_UINT bits) {
+  OI_UINT32 result;
 
-    OI_BITSTREAM_READUINT(result, bits, bs->ptr.r, bs->value, bs->bitPtr);
+  OI_BITSTREAM_READUINT(result, bits, bs->ptr.r, bs->value, bs->bitPtr);
 
-    return result;
+  return result;
 }
 
-PRIVATE OI_UINT8 OI_BITSTREAM_ReadUINT4Aligned(OI_BITSTREAM *bs)
-{
-    OI_UINT32 result;
-
-    OI_ASSERT(bs->bitPtr < 16);
-    OI_ASSERT(bs->bitPtr % 4 == 0);
-
-    if (bs->bitPtr == 8) {
-        result = bs->value << 8;
-        bs->bitPtr = 12;
-    } else {
-        result = bs->value << 12;
-        bs->value = (bs->value << 8) | *bs->ptr.r++;
-        bs->bitPtr = 8;
-    }
-    result >>= 28;
-    OI_ASSERT(result < (1u << 4));
-    return (OI_UINT8)result;
+PRIVATE OI_UINT8 OI_BITSTREAM_ReadUINT4Aligned(OI_BITSTREAM *bs) {
+  OI_UINT32 result;
+
+  OI_ASSERT(bs->bitPtr < 16);
+  OI_ASSERT(bs->bitPtr % 4 == 0);
+
+  if (bs->bitPtr == 8) {
+    result     = bs->value << 8;
+    bs->bitPtr = 12;
+  } else {
+    result     = bs->value << 12;
+    bs->value  = (bs->value << 8) | *bs->ptr.r++;
+    bs->bitPtr = 8;
+  }
+  result >>= 28;
+  OI_ASSERT(result < (1u << 4));
+  return (OI_UINT8)result;
 }
 
-PRIVATE OI_UINT8 OI_BITSTREAM_ReadUINT8Aligned(OI_BITSTREAM *bs)
-{
-    OI_UINT32 result;
-    OI_ASSERT(bs->bitPtr == 8);
+PRIVATE OI_UINT8 OI_BITSTREAM_ReadUINT8Aligned(OI_BITSTREAM *bs) {
+  OI_UINT32 result;
+  OI_ASSERT(bs->bitPtr == 8);
 
-    result = bs->value >> 16;
-    bs->value = (bs->value << 8) | *bs->ptr.r++;
+  result    = bs->value >> 16;
+  bs->value = (bs->value << 8) | *bs->ptr.r++;
 
-    return (OI_UINT8)result;
+  return (OI_UINT8)result;
 }
 
 /**
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-oina.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-oina.c
index bc57ead003..78d6ab9029 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-oina.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-oina.c
@@ -37,97 +37,76 @@ This file exposes OINA-specific interfaces to decoder functions.
 
 #if defined(SBC_DEC_INCLUDED)
 
-OI_STATUS OI_CODEC_SBC_DecoderConfigureRaw(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                           OI_BOOL enhanced,
-                                           OI_UINT8 frequency,
-                                           OI_UINT8 mode,
-                                           OI_UINT8 subbands,
-                                           OI_UINT8 blocks,
-                                           OI_UINT8 alloc,
-                                           OI_UINT8 maxBitpool)
-{
-    if (frequency > SBC_FREQ_48000) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
+OI_STATUS OI_CODEC_SBC_DecoderConfigureRaw(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_BOOL enhanced, OI_UINT8 frequency, OI_UINT8 mode, OI_UINT8 subbands, OI_UINT8 blocks, OI_UINT8 alloc,
+                                           OI_UINT8 maxBitpool) {
+  if (frequency > SBC_FREQ_48000) {
+    return OI_STATUS_INVALID_PARAMETERS;
+  }
 
-    if (enhanced) {
+  if (enhanced) {
 #ifdef SBC_ENHANCED
-        if (subbands != SBC_SUBBANDS_8) {
-            return OI_STATUS_INVALID_PARAMETERS;
-        }
+    if (subbands != SBC_SUBBANDS_8) {
+      return OI_STATUS_INVALID_PARAMETERS;
+    }
 #else
-        return OI_STATUS_INVALID_PARAMETERS;
+    return OI_STATUS_INVALID_PARAMETERS;
 #endif
-    }
+  }
 
-    if (mode > SBC_JOINT_STEREO) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
+  if (mode > SBC_JOINT_STEREO) {
+    return OI_STATUS_INVALID_PARAMETERS;
+  }
 
-    if (subbands > SBC_SUBBANDS_8) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
+  if (subbands > SBC_SUBBANDS_8) {
+    return OI_STATUS_INVALID_PARAMETERS;
+  }
 
-    if (blocks > SBC_BLOCKS_16) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
+  if (blocks > SBC_BLOCKS_16) {
+    return OI_STATUS_INVALID_PARAMETERS;
+  }
 
-    if (alloc > SBC_SNR) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
+  if (alloc > SBC_SNR) {
+    return OI_STATUS_INVALID_PARAMETERS;
+  }
 
 #ifdef SBC_ENHANCED
-    context->common.frameInfo.enhanced = enhanced;
+  context->common.frameInfo.enhanced = enhanced;
 #else
-    context->common.frameInfo.enhanced = FALSE;
+  context->common.frameInfo.enhanced = FALSE;
 #endif
-    context->common.frameInfo.freqIndex = frequency;
-    context->common.frameInfo.mode = mode;
-    context->common.frameInfo.subbands = subbands;
-    context->common.frameInfo.blocks = blocks;
-    context->common.frameInfo.alloc = alloc;
-    context->common.frameInfo.bitpool = maxBitpool;
+  context->common.frameInfo.freqIndex = frequency;
+  context->common.frameInfo.mode      = mode;
+  context->common.frameInfo.subbands  = subbands;
+  context->common.frameInfo.blocks    = blocks;
+  context->common.frameInfo.alloc     = alloc;
+  context->common.frameInfo.bitpool   = maxBitpool;
 
-    OI_SBC_ExpandFrameFields(&context->common.frameInfo);
+  OI_SBC_ExpandFrameFields(&context->common.frameInfo);
 
-    if (context->common.frameInfo.nrof_channels >= context->common.pcmStride) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
+  if (context->common.frameInfo.nrof_channels >= context->common.pcmStride) {
+    return OI_STATUS_INVALID_PARAMETERS;
+  }
 
-    return OI_OK;
+  return OI_OK;
 }
 
-OI_STATUS OI_CODEC_SBC_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                 OI_UINT8 bitpool,
-                                 const OI_BYTE **frameData,
-                                 OI_UINT32 *frameBytes,
-                                 OI_INT16 *pcmData,
-                                 OI_UINT32 *pcmBytes)
-{
-    return internal_DecodeRaw(context,
-                              bitpool,
-                              frameData,
-                              frameBytes,
-                              pcmData,
-                              pcmBytes);
+OI_STATUS OI_CODEC_SBC_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_UINT8 bitpool, const OI_BYTE **frameData, OI_UINT32 *frameBytes, OI_INT16 *pcmData, OI_UINT32 *pcmBytes) {
+  return internal_DecodeRaw(context, bitpool, frameData, frameBytes, pcmData, pcmBytes);
 }
 
-OI_STATUS OI_CODEC_SBC_DecoderLimit(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                    OI_BOOL enhanced,
-                                    OI_UINT8 subbands)
-{
-    if (enhanced) {
+OI_STATUS OI_CODEC_SBC_DecoderLimit(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_BOOL enhanced, OI_UINT8 subbands) {
+  if (enhanced) {
 #ifdef SBC_ENHANCED
-        context->enhancedEnabled = TRUE;
+    context->enhancedEnabled = TRUE;
 #else
-        context->enhancedEnabled = FALSE;
+    context->enhancedEnabled = FALSE;
 #endif
-    } else {
-        context->enhancedEnabled = FALSE;
-    }
-    context->restrictSubbands = subbands;
-    context->limitFrameFormat = TRUE;
-    return OI_OK;
+  } else {
+    context->enhancedEnabled = FALSE;
+  }
+  context->restrictSubbands = subbands;
+  context->limitFrameFormat = TRUE;
+  return OI_OK;
 }
 
 /**
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-private.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-private.c
index 0c7ff1256e..41feeb3a9d 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-private.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-private.c
@@ -33,219 +33,208 @@ This file drives SBC decoding.
 @{
 */
 
-#include "oi_codec_sbc_private.h"
 #include "oi_bitstream.h"
+#include "oi_codec_sbc_private.h"
 #include 
 
 #if defined(SBC_DEC_INCLUDED)
 
 OI_CHAR *const OI_Codec_Copyright = "Copyright 2002-2007 Open Interface North America, Inc. All rights reserved";
 
-INLINE OI_STATUS internal_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                       OI_UINT32 *decoderData,
-                                       OI_UINT32 decoderDataBytes,
-                                       OI_BYTE maxChannels,
-                                       OI_BYTE pcmStride,
-                                       OI_BOOL enhanced,
-                                       OI_BOOL msbc_enable)
-{
-    OI_UINT i;
-    OI_STATUS status;
+INLINE OI_STATUS internal_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_UINT32 *decoderData, OI_UINT32 decoderDataBytes, OI_BYTE maxChannels, OI_BYTE pcmStride, OI_BOOL enhanced,
+                                       OI_BOOL msbc_enable) {
+  OI_UINT   i;
+  OI_STATUS status;
 
-    for (i = 0; i < sizeof(*context); i++) {
-        ((char *)context)[i] = 0;
-    }
+  for (i = 0; i < sizeof(*context); i++) {
+    ((char *)context)[i] = 0;
+  }
 
 #ifdef SBC_ENHANCED
-    context->enhancedEnabled = enhanced ? TRUE : FALSE;
+  context->enhancedEnabled = enhanced ? TRUE : FALSE;
 #else
-    context->enhancedEnabled = FALSE;
-    if (enhanced) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
+  context->enhancedEnabled = FALSE;
+  if (enhanced) {
+    return OI_STATUS_INVALID_PARAMETERS;
+  }
 #endif
 
-    if (msbc_enable) {
-        context->sbc_mode = OI_SBC_MODE_MSBC;
-    } else {
-        context->sbc_mode = OI_SBC_MODE_STD;
-    }
+  if (msbc_enable) {
+    context->sbc_mode = OI_SBC_MODE_MSBC;
+  } else {
+    context->sbc_mode = OI_SBC_MODE_STD;
+  }
 
-    status = OI_CODEC_SBC_Alloc(&context->common, decoderData, decoderDataBytes, maxChannels, pcmStride);
+  status = OI_CODEC_SBC_Alloc(&context->common, decoderData, decoderDataBytes, maxChannels, pcmStride);
 
-    if (!OI_SUCCESS(status)) {
-        return status;
-    }
+  if (!OI_SUCCESS(status)) {
+    return status;
+  }
 
-    context->common.codecInfo = OI_Codec_Copyright;
-    context->common.maxBitneed = 0;
-    context->limitFrameFormat = FALSE;
-    OI_SBC_ExpandFrameFields(&context->common.frameInfo);
+  context->common.codecInfo  = OI_Codec_Copyright;
+  context->common.maxBitneed = 0;
+  context->limitFrameFormat  = FALSE;
+  OI_SBC_ExpandFrameFields(&context->common.frameInfo);
 
-    /*PLATFORM_DECODER_RESET(context);*/
+  /*PLATFORM_DECODER_RESET(context);*/
 
-    return OI_OK;
+  return OI_OK;
 }
 
 /**
  * Read the SBC header up to but not including the joint stereo mask.  The syncword has already been
  * examined, and the enhanced mode flag set, by FindSyncword.
  */
-INLINE void OI_SBC_ReadHeader(OI_CODEC_SBC_COMMON_CONTEXT *common, const OI_BYTE *data)
-{
-    OI_CODEC_SBC_FRAME_INFO *frame = &common->frameInfo;
-    OI_UINT8 d1;
+INLINE void OI_SBC_ReadHeader(OI_CODEC_SBC_COMMON_CONTEXT *common, const OI_BYTE *data) {
+  OI_CODEC_SBC_FRAME_INFO *frame = &common->frameInfo;
+  OI_UINT8                 d1;
 
-    OI_ASSERT(data[0] == OI_SBC_SYNCWORD || data[0] == OI_SBC_ENHANCED_SYNCWORD || data[0] == OI_mSBC_SYNCWORD);
+  OI_ASSERT(data[0] == OI_SBC_SYNCWORD || data[0] == OI_SBC_ENHANCED_SYNCWORD || data[0] == OI_mSBC_SYNCWORD);
 
-    /**
-     * For mSBC, just set those parameters
-     */
-    if (data[0] == OI_mSBC_SYNCWORD) {
-        frame->freqIndex = 0;
-        frame->frequency = 16000;
+  /**
+   * For mSBC, just set those parameters
+   */
+  if (data[0] == OI_mSBC_SYNCWORD) {
+    frame->freqIndex = 0;
+    frame->frequency = 16000;
 
-        frame->blocks = 4;
-        frame->nrof_blocks = 15;
+    frame->blocks      = 4;
+    frame->nrof_blocks = 15;
 
-        frame->mode = 0;
-        frame->nrof_channels = 1;
+    frame->mode          = 0;
+    frame->nrof_channels = 1;
 
-        frame->alloc = SBC_LOUDNESS;
+    frame->alloc = SBC_LOUDNESS;
 
-        frame->subbands = 1;
-        frame->nrof_subbands = 8;
+    frame->subbands      = 1;
+    frame->nrof_subbands = 8;
 
-        frame->cachedInfo = 0;
+    frame->cachedInfo = 0;
 
-        frame->bitpool = 26;
-        frame->crc = data[3];
-        return;
-    }
+    frame->bitpool = 26;
+    frame->crc     = data[3];
+    return;
+  }
 
-    /* Avoid filling out all these strucutures if we already remember the values
-     * from last time. Just in case we get a stream corresponding to data[1] ==
-     * 0, DecoderReset is responsible for ensuring the lookup table entries have
-     * already been populated
-     */
-    d1 = data[1];
-    if (d1 != frame->cachedInfo) {
-        frame->freqIndex = (d1 & (BIT7 | BIT6)) >> 6;
-        frame->frequency = freq_values[frame->freqIndex];
+  /* Avoid filling out all these strucutures if we already remember the values
+   * from last time. Just in case we get a stream corresponding to data[1] ==
+   * 0, DecoderReset is responsible for ensuring the lookup table entries have
+   * already been populated
+   */
+  d1 = data[1];
+  if (d1 != frame->cachedInfo) {
+    frame->freqIndex = (d1 & (BIT7 | BIT6)) >> 6;
+    frame->frequency = freq_values[frame->freqIndex];
 
-        frame->blocks = (d1 & (BIT5 | BIT4)) >> 4;
-        frame->nrof_blocks = block_values[frame->blocks];
+    frame->blocks      = (d1 & (BIT5 | BIT4)) >> 4;
+    frame->nrof_blocks = block_values[frame->blocks];
 
-        frame->mode = (d1 & (BIT3 | BIT2)) >> 2;
-        frame->nrof_channels = channel_values[frame->mode];
+    frame->mode          = (d1 & (BIT3 | BIT2)) >> 2;
+    frame->nrof_channels = channel_values[frame->mode];
 
-        frame->alloc = (d1 & BIT1) >> 1;
+    frame->alloc = (d1 & BIT1) >> 1;
 
-        frame->subbands = (d1 & BIT0);
-        frame->nrof_subbands = band_values[frame->subbands];
+    frame->subbands      = (d1 & BIT0);
+    frame->nrof_subbands = band_values[frame->subbands];
 
-        frame->cachedInfo = d1;
-    }
-    /*
-     * For decode, the bit allocator needs to know the bitpool value
-     */
-    frame->bitpool = data[2];
-    frame->crc = data[3];
+    frame->cachedInfo = d1;
+  }
+  /*
+   * For decode, the bit allocator needs to know the bitpool value
+   */
+  frame->bitpool = data[2];
+  frame->crc     = data[3];
 }
 
-#define LOW(x)  ((x)&0xf)
+#define LOW(x)  ((x) & 0xf)
 #define HIGH(x) ((x) >> 4)
 
 /*
  * Read scalefactor values and prepare the bitstream for OI_SBC_ReadSamples
  */
-PRIVATE void OI_SBC_ReadScalefactors(OI_CODEC_SBC_COMMON_CONTEXT *common,
-                                     const OI_BYTE *b,
-                                     OI_BITSTREAM *bs)
-{
-    OI_UINT i = common->frameInfo.nrof_subbands * common->frameInfo.nrof_channels;
-    OI_INT8 *scale_factor = common->scale_factor;
-    OI_UINT f;
-
-    if (common->frameInfo.nrof_subbands == 8 || common->frameInfo.mode != SBC_JOINT_STEREO) {
-        if (common->frameInfo.mode == SBC_JOINT_STEREO) {
-            common->frameInfo.join = *b++;
-        } else {
-            common->frameInfo.join = 0;
-        }
-        i /= 2;
-        do {
-            *scale_factor++ = HIGH(f = *b++);
-            *scale_factor++ = LOW(f);
-        } while (--i);
-        /*
-         * In this case we know that the scale factors end on a byte boundary so all we need to do
-         * is initialize the bitstream.
-         */
-        OI_BITSTREAM_ReadInit(bs, b);
+PRIVATE void OI_SBC_ReadScalefactors(OI_CODEC_SBC_COMMON_CONTEXT *common, const OI_BYTE *b, OI_BITSTREAM *bs) {
+  OI_UINT  i            = common->frameInfo.nrof_subbands * common->frameInfo.nrof_channels;
+  OI_INT8 *scale_factor = common->scale_factor;
+  OI_UINT  f;
+
+  if (common->frameInfo.nrof_subbands == 8 || common->frameInfo.mode != SBC_JOINT_STEREO) {
+    if (common->frameInfo.mode == SBC_JOINT_STEREO) {
+      common->frameInfo.join = *b++;
     } else {
-        OI_ASSERT(common->frameInfo.nrof_subbands == 4 && common->frameInfo.mode == SBC_JOINT_STEREO);
-        common->frameInfo.join = HIGH(f = *b++);
-        i = (i - 1) / 2;
-        do {
-            *scale_factor++ = LOW(f);
-            *scale_factor++ = HIGH(f = *b++);
-        } while (--i);
-        *scale_factor++ = LOW(f);
-        /*
-         * In 4-subband joint stereo mode, the joint stereo information ends on a half-byte
-         * boundary, so it's necessary to use the bitstream abstraction to read it, since
-         * OI_SBC_ReadSamples will need to pick up in mid-byte.
-         */
-        OI_BITSTREAM_ReadInit(bs, b);
-        *scale_factor++ = OI_BITSTREAM_ReadUINT4Aligned(bs);
+      common->frameInfo.join = 0;
     }
+    i /= 2;
+    do {
+      *scale_factor++ = HIGH(f = *b++);
+      *scale_factor++ = LOW(f);
+    } while (--i);
+    /*
+     * In this case we know that the scale factors end on a byte boundary so all we need to do
+     * is initialize the bitstream.
+     */
+    OI_BITSTREAM_ReadInit(bs, b);
+  } else {
+    OI_ASSERT(common->frameInfo.nrof_subbands == 4 && common->frameInfo.mode == SBC_JOINT_STEREO);
+    common->frameInfo.join = HIGH(f = *b++);
+    i                      = (i - 1) / 2;
+    do {
+      *scale_factor++ = LOW(f);
+      *scale_factor++ = HIGH(f = *b++);
+    } while (--i);
+    *scale_factor++ = LOW(f);
+    /*
+     * In 4-subband joint stereo mode, the joint stereo information ends on a half-byte
+     * boundary, so it's necessary to use the bitstream abstraction to read it, since
+     * OI_SBC_ReadSamples will need to pick up in mid-byte.
+     */
+    OI_BITSTREAM_ReadInit(bs, b);
+    *scale_factor++ = OI_BITSTREAM_ReadUINT4Aligned(bs);
+  }
 }
 
 /** Read quantized subband samples from the input bitstream and expand them. */
-PRIVATE void OI_SBC_ReadSamples(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_BITSTREAM *global_bs)
-{
-    OI_CODEC_SBC_COMMON_CONTEXT *common = &context->common;
-    OI_UINT nrof_blocks = common->frameInfo.nrof_blocks;
-    OI_INT32 *RESTRICT s = common->subdata;
-    OI_UINT8 *ptr = global_bs->ptr.w;
-    OI_UINT32 value = global_bs->value;
-    OI_UINT bitPtr = global_bs->bitPtr;
-
-    const OI_UINT iter_count = common->frameInfo.nrof_channels * common->frameInfo.nrof_subbands / 4;
-    do {
-        OI_UINT i;
-        for (i = 0; i < iter_count; ++i) {
-            OI_UINT32 sf_by4 = ((OI_UINT32 *)common->scale_factor)[i];
-            OI_UINT32 bits_by4 = common->bits.uint32[i];
-            OI_UINT n;
-            for (n = 0; n < 4; ++n) {
-                OI_INT32 dequant;
-                OI_UINT bits;
-                OI_INT sf;
-
-                if (OI_CPU_BYTE_ORDER == OI_LITTLE_ENDIAN_BYTE_ORDER) {
-                    bits = bits_by4 & 0xFF;
-                    bits_by4 >>= 8;
-                    sf = sf_by4 & 0xFF;
-                    sf_by4 >>= 8;
-                } else {
-                    bits = (bits_by4 >> 24) & 0xFF;
-                    bits_by4 <<= 8;
-                    sf = (sf_by4 >> 24) & 0xFF;
-                    sf_by4 <<= 8;
-                }
-                if (bits) {
-                    OI_UINT32 raw;
-                    OI_BITSTREAM_READUINT(raw, bits, ptr, value, bitPtr);
-                    dequant = OI_SBC_Dequant(raw, sf, bits);
-                } else {
-                    dequant = 0;
-                }
-                *s++ = dequant;
-            }
+PRIVATE void OI_SBC_ReadSamples(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_BITSTREAM *global_bs) {
+  OI_CODEC_SBC_COMMON_CONTEXT *common      = &context->common;
+  OI_UINT                      nrof_blocks = common->frameInfo.nrof_blocks;
+  OI_INT32 *RESTRICT           s           = common->subdata;
+  OI_UINT8                    *ptr         = global_bs->ptr.w;
+  OI_UINT32                    value       = global_bs->value;
+  OI_UINT                      bitPtr      = global_bs->bitPtr;
+
+  const OI_UINT iter_count = common->frameInfo.nrof_channels * common->frameInfo.nrof_subbands / 4;
+  do {
+    OI_UINT i;
+    for (i = 0; i < iter_count; ++i) {
+      OI_UINT32 sf_by4   = ((OI_UINT32 *)common->scale_factor)[i];
+      OI_UINT32 bits_by4 = common->bits.uint32[i];
+      OI_UINT   n;
+      for (n = 0; n < 4; ++n) {
+        OI_INT32 dequant;
+        OI_UINT  bits;
+        OI_INT   sf;
+
+        if (OI_CPU_BYTE_ORDER == OI_LITTLE_ENDIAN_BYTE_ORDER) {
+          bits = bits_by4 & 0xFF;
+          bits_by4 >>= 8;
+          sf = sf_by4 & 0xFF;
+          sf_by4 >>= 8;
+        } else {
+          bits = (bits_by4 >> 24) & 0xFF;
+          bits_by4 <<= 8;
+          sf = (sf_by4 >> 24) & 0xFF;
+          sf_by4 <<= 8;
         }
-    } while (--nrof_blocks);
+        if (bits) {
+          OI_UINT32 raw;
+          OI_BITSTREAM_READUINT(raw, bits, ptr, value, bitPtr);
+          dequant = OI_SBC_Dequant(raw, sf, bits);
+        } else {
+          dequant = 0;
+        }
+        *s++ = dequant;
+      }
+    }
+  } while (--nrof_blocks);
 }
 
 /**
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-sbc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-sbc.c
index ee3c451312..01f7955979 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-sbc.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-sbc.c
@@ -28,8 +28,8 @@
 /**@addtogroup codec_internal */
 /**@{*/
 
-#include "oi_codec_sbc_private.h"
 #include "oi_bitstream.h"
+#include "oi_codec_sbc_private.h"
 
 #if defined(SBC_DEC_INCLUDED)
 
@@ -40,386 +40,356 @@
  * set for enhanced operation using OI_CODEC_SBC_DecoderReset(), it will search
  * for both a standard and an enhanced syncword.
  */
-PRIVATE OI_STATUS FindSyncword(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                               const OI_BYTE **frameData,
-                               OI_UINT32 *frameBytes)
-{
+PRIVATE OI_STATUS FindSyncword(OI_CODEC_SBC_DECODER_CONTEXT *context, const OI_BYTE **frameData, OI_UINT32 *frameBytes) {
 #ifdef SBC_ENHANCED
-    OI_BYTE search1 = OI_SBC_SYNCWORD;
-    OI_BYTE search2 = OI_SBC_ENHANCED_SYNCWORD;
+  OI_BYTE search1 = OI_SBC_SYNCWORD;
+  OI_BYTE search2 = OI_SBC_ENHANCED_SYNCWORD;
 #endif // SBC_ENHANCED
 
-    if (*frameBytes == 0) {
-        return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
-    }
+  if (*frameBytes == 0) {
+    return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
+  }
 
 #ifdef SBC_ENHANCED
-    if (context->limitFrameFormat && context->enhancedEnabled) {
-        /* If the context is restricted, only search for specified SYNCWORD */
-        search1 = search2;
-    } else if (context->enhancedEnabled == FALSE) {
-        /* If enhanced is not enabled, only search for classic SBC SYNCWORD*/
-        search2 = search1;
-    }
-    while (*frameBytes && (**frameData != search1) && (**frameData != search2)) {
-        (*frameBytes)--;
-        (*frameData)++;
-    }
-    if (*frameBytes) {
-        /* Syncword found, *frameData points to it, and *frameBytes correctly
-         * reflects the number of bytes available to read, including the
-         * syncword. */
-        context->common.frameInfo.enhanced = (**frameData == OI_SBC_ENHANCED_SYNCWORD);
-        return OI_OK;
-    } else {
-        /* No syncword was found anywhere in the provided input data.
-         * *frameData points past the end of the original input, and
-         * *frameBytes is 0. */
-        return OI_CODEC_SBC_NO_SYNCWORD;
-    }
+  if (context->limitFrameFormat && context->enhancedEnabled) {
+    /* If the context is restricted, only search for specified SYNCWORD */
+    search1 = search2;
+  } else if (context->enhancedEnabled == FALSE) {
+    /* If enhanced is not enabled, only search for classic SBC SYNCWORD*/
+    search2 = search1;
+  }
+  while (*frameBytes && (**frameData != search1) && (**frameData != search2)) {
+    (*frameBytes)--;
+    (*frameData)++;
+  }
+  if (*frameBytes) {
+    /* Syncword found, *frameData points to it, and *frameBytes correctly
+     * reflects the number of bytes available to read, including the
+     * syncword. */
+    context->common.frameInfo.enhanced = (**frameData == OI_SBC_ENHANCED_SYNCWORD);
+    return OI_OK;
+  } else {
+    /* No syncword was found anywhere in the provided input data.
+     * *frameData points past the end of the original input, and
+     * *frameBytes is 0. */
+    return OI_CODEC_SBC_NO_SYNCWORD;
+  }
 #else  // SBC_ENHANCED
-    while (*frameBytes && (!(context->sbc_mode == OI_SBC_MODE_STD && **frameData == OI_SBC_SYNCWORD)) && (!(context->sbc_mode == OI_SBC_MODE_MSBC && **frameData == OI_mSBC_SYNCWORD))) {
-        (*frameBytes)--;
-        (*frameData)++;
-    }
-    if (*frameBytes) {
-        /* Syncword found, *frameData points to it, and *frameBytes correctly
-         * reflects the number of bytes available to read, including the
-         * syncword. */
-        context->common.frameInfo.enhanced = FALSE;
-        return OI_OK;
-    } else {
-        /* No syncword was found anywhere in the provided input data.
-         * *frameData points past the end of the original input, and
-         * *frameBytes is 0. */
-        return OI_CODEC_SBC_NO_SYNCWORD;
-    }
+  while (*frameBytes && (!(context->sbc_mode == OI_SBC_MODE_STD && **frameData == OI_SBC_SYNCWORD)) && (!(context->sbc_mode == OI_SBC_MODE_MSBC && **frameData == OI_mSBC_SYNCWORD))) {
+    (*frameBytes)--;
+    (*frameData)++;
+  }
+  if (*frameBytes) {
+    /* Syncword found, *frameData points to it, and *frameBytes correctly
+     * reflects the number of bytes available to read, including the
+     * syncword. */
+    context->common.frameInfo.enhanced = FALSE;
+    return OI_OK;
+  } else {
+    /* No syncword was found anywhere in the provided input data.
+     * *frameData points past the end of the original input, and
+     * *frameBytes is 0. */
+    return OI_CODEC_SBC_NO_SYNCWORD;
+  }
 #endif // SBC_ENHANCED
 }
 
-static OI_STATUS DecodeBody(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                            const OI_BYTE *bodyData,
-                            OI_INT16 *pcmData,
-                            OI_UINT32 *pcmBytes,
-                            OI_BOOL allowPartial)
-{
-    OI_BITSTREAM bs;
-    OI_UINT frameSamples = context->common.frameInfo.nrof_blocks * context->common.frameInfo.nrof_subbands;
-    OI_UINT decode_block_count;
-
-    /*
-     * Based on the header data, make sure that there is enough room to write the output samples.
-     */
-    if (*pcmBytes < (sizeof(OI_INT16) * frameSamples * context->common.pcmStride) && !allowPartial) {
-        /* If we're not allowing partial decodes, we need room for the entire
-         * codec frame */
-        TRACE(("-OI_CODEC_SBC_Decode: OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA"));
-        return OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA;
-    } else if (*pcmBytes < sizeof(OI_INT16) * context->common.frameInfo.nrof_subbands * context->common.pcmStride) {
-        /* Even if we're allowing partials, we can still only decode on a frame
-         * boundary */
-        return OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA;
+static OI_STATUS DecodeBody(OI_CODEC_SBC_DECODER_CONTEXT *context, const OI_BYTE *bodyData, OI_INT16 *pcmData, OI_UINT32 *pcmBytes, OI_BOOL allowPartial) {
+  OI_BITSTREAM bs;
+  OI_UINT      frameSamples = context->common.frameInfo.nrof_blocks * context->common.frameInfo.nrof_subbands;
+  OI_UINT      decode_block_count;
+
+  /*
+   * Based on the header data, make sure that there is enough room to write the output samples.
+   */
+  if (*pcmBytes < (sizeof(OI_INT16) * frameSamples * context->common.pcmStride) && !allowPartial) {
+    /* If we're not allowing partial decodes, we need room for the entire
+     * codec frame */
+    TRACE(("-OI_CODEC_SBC_Decode: OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA"));
+    return OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA;
+  } else if (*pcmBytes < sizeof(OI_INT16) * context->common.frameInfo.nrof_subbands * context->common.pcmStride) {
+    /* Even if we're allowing partials, we can still only decode on a frame
+     * boundary */
+    return OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA;
+  }
+
+  if (context->bufferedBlocks == 0) {
+    TRACE(("Reading scalefactors"));
+    OI_SBC_ReadScalefactors(&context->common, bodyData, &bs);
+
+    TRACE(("Computing bit allocation"));
+    OI_SBC_ComputeBitAllocation(&context->common);
+
+    TRACE(("Reading samples"));
+    if (context->common.frameInfo.mode == SBC_JOINT_STEREO) {
+      OI_SBC_ReadSamplesJoint(context, &bs);
+    } else {
+      OI_SBC_ReadSamples(context, &bs);
     }
 
-    if (context->bufferedBlocks == 0) {
-        TRACE(("Reading scalefactors"));
-        OI_SBC_ReadScalefactors(&context->common, bodyData, &bs);
+    context->bufferedBlocks = context->common.frameInfo.nrof_blocks;
+  }
 
-        TRACE(("Computing bit allocation"));
-        OI_SBC_ComputeBitAllocation(&context->common);
+  if (allowPartial) {
+    decode_block_count = *pcmBytes / sizeof(OI_INT16) / context->common.pcmStride / context->common.frameInfo.nrof_subbands;
 
-        TRACE(("Reading samples"));
-        if (context->common.frameInfo.mode == SBC_JOINT_STEREO) {
-            OI_SBC_ReadSamplesJoint(context, &bs);
-        } else {
-            OI_SBC_ReadSamples(context, &bs);
-        }
-
-        context->bufferedBlocks = context->common.frameInfo.nrof_blocks;
+    if (decode_block_count > context->bufferedBlocks) {
+      decode_block_count = context->bufferedBlocks;
     }
 
-    if (allowPartial) {
-        decode_block_count = *pcmBytes / sizeof(OI_INT16) / context->common.pcmStride / context->common.frameInfo.nrof_subbands;
+  } else {
+    decode_block_count = context->common.frameInfo.nrof_blocks;
+  }
 
-        if (decode_block_count > context->bufferedBlocks) {
-            decode_block_count = context->bufferedBlocks;
-        }
+  TRACE(("Synthesizing frame"));
+  {
+    OI_UINT start_block = context->common.frameInfo.nrof_blocks - context->bufferedBlocks;
+    OI_SBC_SynthFrame(context, pcmData, start_block, decode_block_count);
+  }
 
-    } else {
-        decode_block_count = context->common.frameInfo.nrof_blocks;
-    }
+  OI_ASSERT(context->bufferedBlocks >= decode_block_count);
+  context->bufferedBlocks -= decode_block_count;
+
+  frameSamples = decode_block_count * context->common.frameInfo.nrof_subbands;
 
-    TRACE(("Synthesizing frame"));
-    {
-        OI_UINT start_block = context->common.frameInfo.nrof_blocks - context->bufferedBlocks;
-        OI_SBC_SynthFrame(context, pcmData, start_block, decode_block_count);
+  /*
+   * When decoding mono into a stride-2 array, copy pcm data to second channel
+   */
+  if (context->common.frameInfo.nrof_channels == 1 && context->common.pcmStride == 2) {
+    OI_UINT i;
+    for (i = 0; i < frameSamples; ++i) {
+      pcmData[2 * i + 1] = pcmData[2 * i];
     }
+  }
+
+  /*
+   * Return number of pcm bytes generated by the decode operation.
+   */
+  *pcmBytes = frameSamples * sizeof(OI_INT16) * context->common.pcmStride;
+  if (context->bufferedBlocks > 0) {
+    return OI_CODEC_SBC_PARTIAL_DECODE;
+  } else {
+    return OI_OK;
+  }
+}
 
-    OI_ASSERT(context->bufferedBlocks >= decode_block_count);
-    context->bufferedBlocks -= decode_block_count;
+PRIVATE OI_STATUS internal_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_UINT8 bitpool, const OI_BYTE **frameData, OI_UINT32 *frameBytes, OI_INT16 *pcmData, OI_UINT32 *pcmBytes) {
+  OI_STATUS status;
+  OI_UINT   bodyLen;
 
-    frameSamples = decode_block_count * context->common.frameInfo.nrof_subbands;
+  TRACE(("+OI_CODEC_SBC_DecodeRaw"));
 
+  if (context->bufferedBlocks == 0) {
     /*
-     * When decoding mono into a stride-2 array, copy pcm data to second channel
+     * The bitallocator needs to know the bitpool value.
      */
-    if (context->common.frameInfo.nrof_channels == 1 && context->common.pcmStride == 2) {
-        OI_UINT i;
-        for (i = 0; i < frameSamples; ++i) {
-            pcmData[2 * i + 1] = pcmData[2 * i];
-        }
-    }
-
-    /*
-     * Return number of pcm bytes generated by the decode operation.
-     */
-    *pcmBytes = frameSamples * sizeof(OI_INT16) * context->common.pcmStride;
-    if (context->bufferedBlocks > 0) {
-        return OI_CODEC_SBC_PARTIAL_DECODE;
-    } else {
-        return OI_OK;
-    }
-}
-
-PRIVATE OI_STATUS internal_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                     OI_UINT8 bitpool,
-                                     const OI_BYTE **frameData,
-                                     OI_UINT32 *frameBytes,
-                                     OI_INT16 *pcmData,
-                                     OI_UINT32 *pcmBytes)
-{
-    OI_STATUS status;
-    OI_UINT bodyLen;
-
-    TRACE(("+OI_CODEC_SBC_DecodeRaw"));
-
-    if (context->bufferedBlocks == 0) {
-        /*
-         * The bitallocator needs to know the bitpool value.
-         */
-        context->common.frameInfo.bitpool = bitpool;
-        /*
-         * Compute the frame length and check we have enough frame data to proceed
-         */
-        bodyLen = OI_CODEC_SBC_CalculateFramelen(&context->common.frameInfo) - SBC_HEADER_LEN;
-        if (*frameBytes < bodyLen) {
-            TRACE(("-OI_CODEC_SBC_Decode: OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA"));
-            return OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA;
-        }
-    } else {
-        bodyLen = 0;
-    }
+    context->common.frameInfo.bitpool = bitpool;
     /*
-     * Decode the SBC data. Pass TRUE to DecodeBody to allow partial decoding of
-     * tones.
+     * Compute the frame length and check we have enough frame data to proceed
      */
-    status = DecodeBody(context, *frameData, pcmData, pcmBytes, TRUE);
-    if (OI_SUCCESS(status) || status == OI_CODEC_SBC_PARTIAL_DECODE) {
-        *frameData += bodyLen;
-        *frameBytes -= bodyLen;
+    bodyLen = OI_CODEC_SBC_CalculateFramelen(&context->common.frameInfo) - SBC_HEADER_LEN;
+    if (*frameBytes < bodyLen) {
+      TRACE(("-OI_CODEC_SBC_Decode: OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA"));
+      return OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA;
     }
-    TRACE(("-OI_CODEC_SBC_DecodeRaw: %d", status));
-    return status;
+  } else {
+    bodyLen = 0;
+  }
+  /*
+   * Decode the SBC data. Pass TRUE to DecodeBody to allow partial decoding of
+   * tones.
+   */
+  status = DecodeBody(context, *frameData, pcmData, pcmBytes, TRUE);
+  if (OI_SUCCESS(status) || status == OI_CODEC_SBC_PARTIAL_DECODE) {
+    *frameData += bodyLen;
+    *frameBytes -= bodyLen;
+  }
+  TRACE(("-OI_CODEC_SBC_DecodeRaw: %d", status));
+  return status;
 }
 
-OI_STATUS OI_CODEC_SBC_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                    OI_UINT32 *decoderData,
-                                    OI_UINT32 decoderDataBytes,
-                                    OI_UINT8 maxChannels,
-                                    OI_UINT8 pcmStride,
-                                    OI_BOOL enhanced,
-                                    OI_BOOL msbc_enable)
-{
-    return internal_DecoderReset(context, decoderData, decoderDataBytes, maxChannels, pcmStride, enhanced, msbc_enable);
+OI_STATUS OI_CODEC_SBC_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_UINT32 *decoderData, OI_UINT32 decoderDataBytes, OI_UINT8 maxChannels, OI_UINT8 pcmStride, OI_BOOL enhanced,
+                                    OI_BOOL msbc_enable) {
+  return internal_DecoderReset(context, decoderData, decoderDataBytes, maxChannels, pcmStride, enhanced, msbc_enable);
 }
 
-OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                   const OI_BYTE **frameData,
-                                   OI_UINT32 *frameBytes,
-                                   OI_INT16 *pcmData,
-                                   OI_UINT32 *pcmBytes)
-{
-    OI_STATUS status;
-    OI_UINT framelen;
-    OI_UINT8 crc;
-
-    TRACE(("+OI_CODEC_SBC_DecodeFrame"));
-
-    TRACE(("Finding syncword"));
-    status = FindSyncword(context, frameData, frameBytes);
-    if (!OI_SUCCESS(status)) {
-        return status;
-    }
-
-    /* Make sure enough data remains to read the header. */
-    if (*frameBytes < SBC_HEADER_LEN) {
-        TRACE(("-OI_CODEC_SBC_DecodeFrame: OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA"));
-        return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
-    }
-
-    TRACE(("Reading Header"));
-    OI_SBC_ReadHeader(&context->common, *frameData);
-
-    /*
-     * Some implementations load the decoder into RAM and use overlays for 4 vs 8 subbands. We need
-     * to ensure that the SBC parameters for this frame are compatible with the restrictions imposed
-     * by the loaded overlays.
-     */
-    if (context->limitFrameFormat && (context->common.frameInfo.subbands != context->restrictSubbands)) {
-        ERROR(("SBC parameters incompatible with loaded overlay"));
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-
-    if (context->common.frameInfo.nrof_channels > context->common.maxChannels) {
-        ERROR(("SBC parameters incompatible with number of channels specified during reset"));
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-
-    if (context->common.pcmStride < 1 || context->common.pcmStride > 2) {
-        ERROR(("PCM stride not set correctly during reset"));
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-
-    /*
-     * At this point a header has been read. However, it's possible that we found a false syncword,
-     * so the header data might be invalid. Make sure we have enough bytes to read in the
-     * CRC-protected header, but don't require we have the whole frame. That way, if it turns out
-     * that we're acting on bogus header data, we don't stall the decoding process by waiting for
-     * data that we don't actually need.
-     */
-    framelen = OI_CODEC_SBC_CalculateFramelen(&context->common.frameInfo);
-    if (*frameBytes < framelen) {
-        TRACE(("-OI_CODEC_SBC_DecodeFrame: OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA"));
-        return OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA;
-    }
+OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT *context, const OI_BYTE **frameData, OI_UINT32 *frameBytes, OI_INT16 *pcmData, OI_UINT32 *pcmBytes) {
+  OI_STATUS status;
+  OI_UINT   framelen;
+  OI_UINT8  crc;
 
-    TRACE(("Calculating checksum"));
+  TRACE(("+OI_CODEC_SBC_DecodeFrame"));
 
-    crc = OI_SBC_CalculateChecksum(&context->common.frameInfo, *frameData);
-    if (crc != context->common.frameInfo.crc) {
-        TRACE(("CRC Mismatch:  calc=%02x read=%02x\n", crc, context->common.frameInfo.crc));
-        TRACE(("-OI_CODEC_SBC_DecodeFrame: OI_CODEC_SBC_CHECKSUM_MISMATCH"));
-        return OI_CODEC_SBC_CHECKSUM_MISMATCH;
-    }
+  TRACE(("Finding syncword"));
+  status = FindSyncword(context, frameData, frameBytes);
+  if (!OI_SUCCESS(status)) {
+    return status;
+  }
+
+  /* Make sure enough data remains to read the header. */
+  if (*frameBytes < SBC_HEADER_LEN) {
+    TRACE(("-OI_CODEC_SBC_DecodeFrame: OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA"));
+    return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
+  }
+
+  TRACE(("Reading Header"));
+  OI_SBC_ReadHeader(&context->common, *frameData);
+
+  /*
+   * Some implementations load the decoder into RAM and use overlays for 4 vs 8 subbands. We need
+   * to ensure that the SBC parameters for this frame are compatible with the restrictions imposed
+   * by the loaded overlays.
+   */
+  if (context->limitFrameFormat && (context->common.frameInfo.subbands != context->restrictSubbands)) {
+    ERROR(("SBC parameters incompatible with loaded overlay"));
+    return OI_STATUS_INVALID_PARAMETERS;
+  }
+
+  if (context->common.frameInfo.nrof_channels > context->common.maxChannels) {
+    ERROR(("SBC parameters incompatible with number of channels specified during reset"));
+    return OI_STATUS_INVALID_PARAMETERS;
+  }
+
+  if (context->common.pcmStride < 1 || context->common.pcmStride > 2) {
+    ERROR(("PCM stride not set correctly during reset"));
+    return OI_STATUS_INVALID_PARAMETERS;
+  }
+
+  /*
+   * At this point a header has been read. However, it's possible that we found a false syncword,
+   * so the header data might be invalid. Make sure we have enough bytes to read in the
+   * CRC-protected header, but don't require we have the whole frame. That way, if it turns out
+   * that we're acting on bogus header data, we don't stall the decoding process by waiting for
+   * data that we don't actually need.
+   */
+  framelen = OI_CODEC_SBC_CalculateFramelen(&context->common.frameInfo);
+  if (*frameBytes < framelen) {
+    TRACE(("-OI_CODEC_SBC_DecodeFrame: OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA"));
+    return OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA;
+  }
+
+  TRACE(("Calculating checksum"));
+
+  crc = OI_SBC_CalculateChecksum(&context->common.frameInfo, *frameData);
+  if (crc != context->common.frameInfo.crc) {
+    TRACE(("CRC Mismatch:  calc=%02x read=%02x\n", crc, context->common.frameInfo.crc));
+    TRACE(("-OI_CODEC_SBC_DecodeFrame: OI_CODEC_SBC_CHECKSUM_MISMATCH"));
+    return OI_CODEC_SBC_CHECKSUM_MISMATCH;
+  }
 
 #ifdef OI_DEBUG
-    /*
-     * Make sure the bitpool values are sane.
-     */
-    if ((context->common.frameInfo.bitpool < SBC_MIN_BITPOOL) && !context->common.frameInfo.enhanced) {
-        ERROR(("Bitpool too small: %d (must be >= 2)", context->common.frameInfo.bitpool));
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-    if (context->common.frameInfo.bitpool > OI_SBC_MaxBitpool(&context->common.frameInfo)) {
-        ERROR(("Bitpool too large: %d (must be <= %ld)", context->common.frameInfo.bitpool, OI_SBC_MaxBitpool(&context->common.frameInfo)));
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
+  /*
+   * Make sure the bitpool values are sane.
+   */
+  if ((context->common.frameInfo.bitpool < SBC_MIN_BITPOOL) && !context->common.frameInfo.enhanced) {
+    ERROR(("Bitpool too small: %d (must be >= 2)", context->common.frameInfo.bitpool));
+    return OI_STATUS_INVALID_PARAMETERS;
+  }
+  if (context->common.frameInfo.bitpool > OI_SBC_MaxBitpool(&context->common.frameInfo)) {
+    ERROR(("Bitpool too large: %d (must be <= %ld)", context->common.frameInfo.bitpool, OI_SBC_MaxBitpool(&context->common.frameInfo)));
+    return OI_STATUS_INVALID_PARAMETERS;
+  }
 #endif
 
-    /*
-     * Now decode the SBC data. Partial decode is not yet implemented for an SBC
-     * stream, so pass FALSE to decode body to have it enforce the old rule that
-     * you have to decode a whole packet at a time.
-     */
-    status = DecodeBody(context, *frameData + SBC_HEADER_LEN, pcmData, pcmBytes, FALSE);
-    if (OI_SUCCESS(status)) {
-        *frameData += framelen;
-        *frameBytes -= framelen;
-    }
-    TRACE(("-OI_CODEC_SBC_DecodeFrame: %d", status));
+  /*
+   * Now decode the SBC data. Partial decode is not yet implemented for an SBC
+   * stream, so pass FALSE to decode body to have it enforce the old rule that
+   * you have to decode a whole packet at a time.
+   */
+  status = DecodeBody(context, *frameData + SBC_HEADER_LEN, pcmData, pcmBytes, FALSE);
+  if (OI_SUCCESS(status)) {
+    *frameData += framelen;
+    *frameBytes -= framelen;
+  }
+  TRACE(("-OI_CODEC_SBC_DecodeFrame: %d", status));
+
+  return status;
+}
+
+OI_STATUS OI_CODEC_SBC_SkipFrame(OI_CODEC_SBC_DECODER_CONTEXT *context, const OI_BYTE **frameData, OI_UINT32 *frameBytes) {
+  OI_STATUS status;
+  OI_UINT   framelen;
+  OI_UINT   headerlen;
+  OI_UINT8  crc;
 
+  status = FindSyncword(context, frameData, frameBytes);
+  if (!OI_SUCCESS(status)) {
     return status;
+  }
+  if (*frameBytes < SBC_HEADER_LEN) {
+    return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
+  }
+  OI_SBC_ReadHeader(&context->common, *frameData);
+  framelen = OI_SBC_CalculateFrameAndHeaderlen(&context->common.frameInfo, &headerlen);
+  if (*frameBytes < headerlen) {
+    return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
+  }
+  crc = OI_SBC_CalculateChecksum(&context->common.frameInfo, *frameData);
+  if (crc != context->common.frameInfo.crc) {
+    return OI_CODEC_SBC_CHECKSUM_MISMATCH;
+  }
+  if (*frameBytes < framelen) {
+    return OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA;
+  }
+  context->bufferedBlocks = 0;
+  *frameData += framelen;
+  *frameBytes -= framelen;
+  return OI_OK;
 }
 
-OI_STATUS OI_CODEC_SBC_SkipFrame(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                 const OI_BYTE **frameData,
-                                 OI_UINT32 *frameBytes)
-{
-    OI_STATUS status;
-    OI_UINT framelen;
-    OI_UINT headerlen;
-    OI_UINT8 crc;
-
-    status = FindSyncword(context, frameData, frameBytes);
-    if (!OI_SUCCESS(status)) {
-        return status;
+OI_UINT8 OI_CODEC_SBC_FrameCount(OI_BYTE *frameData, OI_UINT32 frameBytes) {
+  OI_UINT8 mode;
+  OI_UINT8 blocks;
+  OI_UINT8 subbands;
+  OI_UINT8 frameCount = 0;
+  OI_UINT  frameLen;
+
+  while (frameBytes) {
+    while (frameBytes && ((frameData[0] & 0xFE) != 0x9C)) {
+      frameData++;
+      frameBytes--;
     }
-    if (*frameBytes < SBC_HEADER_LEN) {
-        return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
-    }
-    OI_SBC_ReadHeader(&context->common, *frameData);
-    framelen = OI_SBC_CalculateFrameAndHeaderlen(&context->common.frameInfo, &headerlen);
-    if (*frameBytes < headerlen) {
-        return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
-    }
-    crc = OI_SBC_CalculateChecksum(&context->common.frameInfo, *frameData);
-    if (crc != context->common.frameInfo.crc) {
-        return OI_CODEC_SBC_CHECKSUM_MISMATCH;
+
+    if (frameBytes < SBC_HEADER_LEN) {
+      return frameCount;
     }
-    if (*frameBytes < framelen) {
-        return OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA;
+
+    /* Extract and translate required fields from Header */
+    subbands = mode = blocks = frameData[1];
+    ;
+    mode     = (mode & (BIT3 | BIT2)) >> 2;
+    blocks   = block_values[(blocks & (BIT5 | BIT4)) >> 4];
+    subbands = band_values[(subbands & BIT0)];
+
+    /* Inline logic to avoid corrupting context */
+    frameLen = blocks * frameData[2];
+    switch (mode) {
+    case SBC_JOINT_STEREO:
+      frameLen += subbands + (8 * subbands);
+      break;
+
+    case SBC_DUAL_CHANNEL:
+      frameLen *= 2;
+      /* fall through */
+
+    default:
+      if (mode == SBC_MONO) {
+        frameLen += 4 * subbands;
+      } else {
+        frameLen += 8 * subbands;
+      }
     }
-    context->bufferedBlocks = 0;
-    *frameData += framelen;
-    *frameBytes -= framelen;
-    return OI_OK;
-}
 
-OI_UINT8 OI_CODEC_SBC_FrameCount(OI_BYTE *frameData,
-                                 OI_UINT32 frameBytes)
-{
-    OI_UINT8 mode;
-    OI_UINT8 blocks;
-    OI_UINT8 subbands;
-    OI_UINT8 frameCount = 0;
-    OI_UINT frameLen;
-
-    while (frameBytes) {
-        while (frameBytes && ((frameData[0] & 0xFE) != 0x9C)) {
-            frameData++;
-            frameBytes--;
-        }
-
-        if (frameBytes < SBC_HEADER_LEN) {
-            return frameCount;
-        }
-
-        /* Extract and translate required fields from Header */
-        subbands = mode = blocks = frameData[1];
-        ;
-        mode = (mode & (BIT3 | BIT2)) >> 2;
-        blocks = block_values[(blocks & (BIT5 | BIT4)) >> 4];
-        subbands = band_values[(subbands & BIT0)];
-
-        /* Inline logic to avoid corrupting context */
-        frameLen = blocks * frameData[2];
-        switch (mode) {
-            case SBC_JOINT_STEREO:
-                frameLen += subbands + (8 * subbands);
-                break;
-
-            case SBC_DUAL_CHANNEL:
-                frameLen *= 2;
-                /* fall through */
-
-            default:
-                if (mode == SBC_MONO) {
-                    frameLen += 4 * subbands;
-                } else {
-                    frameLen += 8 * subbands;
-                }
-        }
-
-        frameCount++;
-        frameLen = SBC_HEADER_LEN + (frameLen + 7) / 8;
-        if (frameBytes > frameLen) {
-            frameBytes -= frameLen;
-            frameData += frameLen;
-        } else {
-            frameBytes = 0;
-        }
+    frameCount++;
+    frameLen = SBC_HEADER_LEN + (frameLen + 7) / 8;
+    if (frameBytes > frameLen) {
+      frameBytes -= frameLen;
+      frameData += frameLen;
+    } else {
+      frameBytes = 0;
     }
-    return frameCount;
+  }
+  return frameCount;
 }
 
 /** Read quantized subband samples from the input bitstream and expand them. */
@@ -432,8 +402,7 @@ PRIVATE void OI_SBC_ReadSamplesJoint4(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_
 #undef NROF_SUBBANDS
 }
 
-PRIVATE void OI_SBC_ReadSamplesJoint8(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_BITSTREAM *global_bs)
-{
+PRIVATE void OI_SBC_ReadSamplesJoint8(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_BITSTREAM *global_bs) {
 #define NROF_SUBBANDS 8
 #include "readsamplesjoint.inc"
 #undef NROF_SUBBANDS
@@ -441,20 +410,16 @@ PRIVATE void OI_SBC_ReadSamplesJoint8(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_
 
 typedef void (*READ_SAMPLES)(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_BITSTREAM *global_bs);
 
-static const READ_SAMPLES SpecializedReadSamples[] = {
-    OI_SBC_ReadSamplesJoint4,
-    OI_SBC_ReadSamplesJoint8
-};
+static const READ_SAMPLES SpecializedReadSamples[] = {OI_SBC_ReadSamplesJoint4, OI_SBC_ReadSamplesJoint8};
 
 #endif /* SPECIALIZE_READ_SAMPLES_JOINT */
 
-PRIVATE void OI_SBC_ReadSamplesJoint(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_BITSTREAM *global_bs)
-{
-    OI_CODEC_SBC_COMMON_CONTEXT *common = &context->common;
-    OI_UINT nrof_subbands = common->frameInfo.nrof_subbands;
+PRIVATE void OI_SBC_ReadSamplesJoint(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_BITSTREAM *global_bs) {
+  OI_CODEC_SBC_COMMON_CONTEXT *common        = &context->common;
+  OI_UINT                      nrof_subbands = common->frameInfo.nrof_subbands;
 #ifdef SPECIALIZE_READ_SAMPLES_JOINT
-    OI_ASSERT((nrof_subbands >> 3u) <= 1u);
-    SpecializedReadSamples[nrof_subbands >> 3](context, global_bs);
+  OI_ASSERT((nrof_subbands >> 3u) <= 1u);
+  SpecializedReadSamples[nrof_subbands >> 3](context, global_bs);
 #else
 
 #define NROF_SUBBANDS nrof_subbands
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/dequant.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/dequant.c
index a134d45e77..8b4973ece1 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/dequant.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/dequant.c
@@ -124,54 +124,51 @@ const OI_UINT32 dequant_long_unscaled[17];
 
 #include 
 
-static INLINE float dequant_float(OI_UINT32 raw, OI_UINT scale_factor, OI_UINT bits)
-{
-    float result = (1 << (scale_factor + 1)) * ((raw * 2.0f + 1.0f) / ((1 << bits) - 1.0f) - 1.0f);
+static INLINE float dequant_float(OI_UINT32 raw, OI_UINT scale_factor, OI_UINT bits) {
+  float result = (1 << (scale_factor + 1)) * ((raw * 2.0f + 1.0f) / ((1 << bits) - 1.0f) - 1.0f);
 
-    result /= SBC_DEQUANT_SCALING_FACTOR;
+  result /= SBC_DEQUANT_SCALING_FACTOR;
 
-    /* Unless the encoder screwed up, all correct dequantized values should
-     * satisfy this inequality. Non-compliant encoders which generate quantized
-     * values with all 1-bits set can, theoretically, trigger this assert. This
-     * is unlikely, however, and only an issue in debug mode.
-     */
-    OI_ASSERT(fabs(result) < 32768 * 1.6);
+  /* Unless the encoder screwed up, all correct dequantized values should
+   * satisfy this inequality. Non-compliant encoders which generate quantized
+   * values with all 1-bits set can, theoretically, trigger this assert. This
+   * is unlikely, however, and only an issue in debug mode.
+   */
+  OI_ASSERT(fabs(result) < 32768 * 1.6);
 
-    return result;
+  return result;
 }
 
 #endif
 
-INLINE OI_INT32 OI_SBC_Dequant(OI_UINT32 raw, OI_UINT scale_factor, OI_UINT bits)
-{
-    OI_UINT32 d;
-    OI_INT32 result;
+INLINE OI_INT32 OI_SBC_Dequant(OI_UINT32 raw, OI_UINT scale_factor, OI_UINT bits) {
+  OI_UINT32 d;
+  OI_INT32  result;
 
-    OI_ASSERT(scale_factor <= 15);
-    OI_ASSERT(bits <= 16);
+  OI_ASSERT(scale_factor <= 15);
+  OI_ASSERT(bits <= 16);
 
-    if (bits <= 1) {
-        return 0;
-    }
+  if (bits <= 1) {
+    return 0;
+  }
 
-    d = (raw * 2) + 1;
-    d *= dequant_long_scaled[bits];
-    result = d - SBC_DEQUANT_LONG_SCALED_OFFSET;
+  d = (raw * 2) + 1;
+  d *= dequant_long_scaled[bits];
+  result = d - SBC_DEQUANT_LONG_SCALED_OFFSET;
 
 #ifdef DEBUG_DEQUANTIZATION
-    {
-        OI_INT32 integerized_float_result;
-        float float_result;
+  {
+    OI_INT32 integerized_float_result;
+    float    float_result;
 
-        float_result = dequant_float(raw, scale_factor, bits);
-        integerized_float_result = (OI_INT32)floor(0.5f + float_result * (1 << 15));
+    float_result             = dequant_float(raw, scale_factor, bits);
+    integerized_float_result = (OI_INT32)floor(0.5f + float_result * (1 << 15));
 
-        /* This detects overflow */
-        OI_ASSERT(((result >= 0) && (integerized_float_result >= 0)) ||
-                  ((result <= 0) && (integerized_float_result <= 0)));
-    }
+    /* This detects overflow */
+    OI_ASSERT(((result >= 0) && (integerized_float_result >= 0)) || ((result <= 0) && (integerized_float_result <= 0)));
+  }
 #endif
-    return result >> (15 - scale_factor);
+  return result >> (15 - scale_factor);
 }
 
 /* This version of Dequant does not incorporate the scaling factor of 1.38. It
@@ -181,27 +178,26 @@ INLINE OI_INT32 OI_SBC_Dequant(OI_UINT32 raw, OI_UINT scale_factor, OI_UINT bits
  * the encoder is conformant) the result will fit a 24 bit fixed point signed
  * value.*/
 
-INLINE OI_INT32 OI_SBC_Dequant_Unscaled(OI_UINT32 raw, OI_UINT scale_factor, OI_UINT bits)
-{
-    OI_UINT32 d;
-    OI_INT32 result;
+INLINE OI_INT32 OI_SBC_Dequant_Unscaled(OI_UINT32 raw, OI_UINT scale_factor, OI_UINT bits) {
+  OI_UINT32 d;
+  OI_INT32  result;
 
-    OI_ASSERT(scale_factor <= 15);
-    OI_ASSERT(bits <= 16);
+  OI_ASSERT(scale_factor <= 15);
+  OI_ASSERT(bits <= 16);
 
-    if (bits <= 1) {
-        return 0;
-    }
-    if (bits == 16) {
-        result = (raw << 16) + raw - 0x7fff7fff;
-        return SCALE(result, 24 - scale_factor);
-    }
+  if (bits <= 1) {
+    return 0;
+  }
+  if (bits == 16) {
+    result = (raw << 16) + raw - 0x7fff7fff;
+    return SCALE(result, 24 - scale_factor);
+  }
 
-    d = (raw * 2) + 1;
-    d *= dequant_long_unscaled[bits];
-    result = d - 0x80000000;
+  d = (raw * 2) + 1;
+  d *= dequant_long_unscaled[bits];
+  result = d - 0x80000000;
 
-    return SCALE(result, 24 - scale_factor);
+  return SCALE(result, 24 - scale_factor);
 }
 
 /**
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing-sbc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing-sbc.c
index ec94375534..cb4545d861 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing-sbc.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing-sbc.c
@@ -32,24 +32,23 @@
 
 #if defined(SBC_DEC_INCLUDED)
 
-const OI_CHAR *const OI_CODEC_SBC_FreqText[] = { "SBC_FREQ_16000", "SBC_FREQ_32000", "SBC_FREQ_44100", "SBC_FREQ_48000" };
-const OI_CHAR *const OI_CODEC_SBC_ModeText[] = { "SBC_MONO", "SBC_DUAL_CHANNEL", "SBC_STEREO", "SBC_JOINT_STEREO" };
-const OI_CHAR *const OI_CODEC_SBC_SubbandsText[] = { "SBC_SUBBANDS_4", "SBC_SUBBANDS_8" };
-const OI_CHAR *const OI_CODEC_SBC_BlocksText[] = { "SBC_BLOCKS_4", "SBC_BLOCKS_8", "SBC_BLOCKS_12", "SBC_BLOCKS_16" };
-const OI_CHAR *const OI_CODEC_SBC_AllocText[] = { "SBC_LOUDNESS", "SBC_SNR" };
+const OI_CHAR *const OI_CODEC_SBC_FreqText[]     = {"SBC_FREQ_16000", "SBC_FREQ_32000", "SBC_FREQ_44100", "SBC_FREQ_48000"};
+const OI_CHAR *const OI_CODEC_SBC_ModeText[]     = {"SBC_MONO", "SBC_DUAL_CHANNEL", "SBC_STEREO", "SBC_JOINT_STEREO"};
+const OI_CHAR *const OI_CODEC_SBC_SubbandsText[] = {"SBC_SUBBANDS_4", "SBC_SUBBANDS_8"};
+const OI_CHAR *const OI_CODEC_SBC_BlocksText[]   = {"SBC_BLOCKS_4", "SBC_BLOCKS_8", "SBC_BLOCKS_12", "SBC_BLOCKS_16"};
+const OI_CHAR *const OI_CODEC_SBC_AllocText[]    = {"SBC_LOUDNESS", "SBC_SNR"};
 
 #ifdef OI_DEBUG
-void OI_CODEC_SBC_DumpConfig(OI_CODEC_SBC_FRAME_INFO *frameInfo)
-{
-    BT_WARN("SBC configuration\n");
-    BT_WARN("  enhanced:  %s\n", frameInfo->enhanced ? "TRUE" : "FALSE");
-    BT_WARN("  frequency: %d\n", frameInfo->frequency);
-    BT_WARN("  subbands:  %d\n", frameInfo->nrof_subbands);
-    BT_WARN("  blocks:    %d\n", frameInfo->nrof_blocks);
-    BT_WARN("  channels:  %d\n", frameInfo->nrof_channels);
-    BT_WARN("  mode:      %s\n", OI_CODEC_SBC_ModeText[frameInfo->mode]);
-    BT_WARN("  alloc:     %s\n", OI_CODEC_SBC_AllocText[frameInfo->alloc]);
-    BT_WARN("  bitpool:   %d\n", frameInfo->bitpool);
+void OI_CODEC_SBC_DumpConfig(OI_CODEC_SBC_FRAME_INFO *frameInfo) {
+  BT_WARN("SBC configuration\n");
+  BT_WARN("  enhanced:  %s\n", frameInfo->enhanced ? "TRUE" : "FALSE");
+  BT_WARN("  frequency: %d\n", frameInfo->frequency);
+  BT_WARN("  subbands:  %d\n", frameInfo->nrof_subbands);
+  BT_WARN("  blocks:    %d\n", frameInfo->nrof_blocks);
+  BT_WARN("  channels:  %d\n", frameInfo->nrof_channels);
+  BT_WARN("  mode:      %s\n", OI_CODEC_SBC_ModeText[frameInfo->mode]);
+  BT_WARN("  alloc:     %s\n", OI_CODEC_SBC_AllocText[frameInfo->alloc]);
+  BT_WARN("  bitpool:   %d\n", frameInfo->bitpool);
 }
 #endif /* OI_DEBUG */
 
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing.c
index d962eaa05d..f68c0300ce 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing.c
@@ -33,8 +33,8 @@ Checksum and header-related functions.
 @{
 */
 
-#include "oi_codec_sbc_private.h"
 #include "oi_assert.h"
+#include "oi_codec_sbc_private.h"
 
 #if defined(SBC_DEC_INCLUDED)
 
@@ -52,182 +52,60 @@ Checksum and header-related functions.
 #ifdef USE_WIDE_CRC
 /* Save space if a char is 16 bits, such as on the C54x */
 const OI_BYTE crc8_wide[128] = {
-    0x001d,
-    0x3a27,
-    0x7469,
-    0x4e53,
-    0xe8f5,
-    0xd2cf,
-    0x9c81,
-    0xa6bb,
-    0xcdd0,
-    0xf7ea,
-    0xb9a4,
-    0x839e,
-    0x2538,
-    0x1f02,
-    0x514c,
-    0x6b76,
-    0x879a,
-    0xbda0,
-    0xf3ee,
-    0xc9d4,
-    0x6f72,
-    0x5548,
-    0x1b06,
-    0x213c,
-    0x4a57,
-    0x706d,
-    0x3e23,
-    0x0419,
-    0xa2bf,
-    0x9885,
-    0xd6cb,
-    0xecf1,
-    0x130e,
-    0x2934,
-    0x677a,
-    0x5d40,
-    0xfbe6,
-    0xc1dc,
-    0x8f92,
-    0xb5a8,
-    0xdec3,
-    0xe4f9,
-    0xaab7,
-    0x908d,
-    0x362b,
-    0x0c11,
-    0x425f,
-    0x7865,
-    0x9489,
-    0xaeb3,
-    0xe0fd,
-    0xdac7,
-    0x7c61,
-    0x465b,
-    0x0815,
-    0x322f,
-    0x5944,
-    0x637e,
-    0x2d30,
-    0x170a,
-    0xb1ac,
-    0x8b96,
-    0xc5d8,
-    0xffe2,
-    0x263b,
-    0x1c01,
-    0x524f,
-    0x6875,
-    0xced3,
-    0xf4e9,
-    0xbaa7,
-    0x809d,
-    0xebf6,
-    0xd1cc,
-    0x9f82,
-    0xa5b8,
-    0x031e,
-    0x3924,
-    0x776a,
-    0x4d50,
-    0xa1bc,
-    0x9b86,
-    0xd5c8,
-    0xeff2,
-    0x4954,
-    0x736e,
-    0x3d20,
-    0x071a,
-    0x6c71,
-    0x564b,
-    0x1805,
-    0x223f,
-    0x8499,
-    0xbea3,
-    0xf0ed,
-    0xcad7,
-    0x3528,
-    0x0f12,
-    0x415c,
-    0x7b66,
-    0xddc0,
-    0xe7fa,
-    0xa9b4,
-    0x938e,
-    0xf8e5,
-    0xc2df,
-    0x8c91,
-    0xb6ab,
-    0x100d,
-    0x2a37,
-    0x6479,
-    0x5e43,
-    0xb2af,
-    0x8895,
-    0xc6db,
-    0xfce1,
-    0x5a47,
-    0x607d,
-    0x2e33,
-    0x1409,
-    0x7f62,
-    0x4558,
-    0x0b16,
-    0x312c,
-    0x978a,
-    0xadb0,
-    0xe3fe,
-    0xd9c4,
+    0x001d, 0x3a27, 0x7469, 0x4e53, 0xe8f5, 0xd2cf, 0x9c81, 0xa6bb, 0xcdd0, 0xf7ea, 0xb9a4, 0x839e, 0x2538, 0x1f02, 0x514c, 0x6b76, 0x879a, 0xbda0, 0xf3ee, 0xc9d4, 0x6f72, 0x5548,
+    0x1b06, 0x213c, 0x4a57, 0x706d, 0x3e23, 0x0419, 0xa2bf, 0x9885, 0xd6cb, 0xecf1, 0x130e, 0x2934, 0x677a, 0x5d40, 0xfbe6, 0xc1dc, 0x8f92, 0xb5a8, 0xdec3, 0xe4f9, 0xaab7, 0x908d,
+    0x362b, 0x0c11, 0x425f, 0x7865, 0x9489, 0xaeb3, 0xe0fd, 0xdac7, 0x7c61, 0x465b, 0x0815, 0x322f, 0x5944, 0x637e, 0x2d30, 0x170a, 0xb1ac, 0x8b96, 0xc5d8, 0xffe2, 0x263b, 0x1c01,
+    0x524f, 0x6875, 0xced3, 0xf4e9, 0xbaa7, 0x809d, 0xebf6, 0xd1cc, 0x9f82, 0xa5b8, 0x031e, 0x3924, 0x776a, 0x4d50, 0xa1bc, 0x9b86, 0xd5c8, 0xeff2, 0x4954, 0x736e, 0x3d20, 0x071a,
+    0x6c71, 0x564b, 0x1805, 0x223f, 0x8499, 0xbea3, 0xf0ed, 0xcad7, 0x3528, 0x0f12, 0x415c, 0x7b66, 0xddc0, 0xe7fa, 0xa9b4, 0x938e, 0xf8e5, 0xc2df, 0x8c91, 0xb6ab, 0x100d, 0x2a37,
+    0x6479, 0x5e43, 0xb2af, 0x8895, 0xc6db, 0xfce1, 0x5a47, 0x607d, 0x2e33, 0x1409, 0x7f62, 0x4558, 0x0b16, 0x312c, 0x978a, 0xadb0, 0xe3fe, 0xd9c4,
 };
 #elif defined(USE_NIBBLEWISE_CRC)
-const OI_BYTE crc8_narrow[16] = {
-    0x00, 0x1d, 0x3a, 0x27, 0x74, 0x69, 0x4e, 0x53, 0xe8, 0xf5, 0xd2, 0xcf, 0x9c, 0x81, 0xa6, 0xbb
-};
+const OI_BYTE crc8_narrow[16] = {0x00, 0x1d, 0x3a, 0x27, 0x74, 0x69, 0x4e, 0x53, 0xe8, 0xf5, 0xd2, 0xcf, 0x9c, 0x81, 0xa6, 0xbb};
 #else
-const OI_BYTE crc8_narrow[256] = {
-    0x00, 0x1d, 0x3a, 0x27, 0x74, 0x69, 0x4e, 0x53, 0xe8, 0xf5, 0xd2, 0xcf, 0x9c, 0x81, 0xa6, 0xbb, 0xcd, 0xd0, 0xf7, 0xea, 0xb9, 0xa4, 0x83, 0x9e, 0x25, 0x38, 0x1f, 0x02, 0x51, 0x4c, 0x6b, 0x76, 0x87, 0x9a, 0xbd, 0xa0, 0xf3, 0xee, 0xc9, 0xd4, 0x6f, 0x72, 0x55, 0x48, 0x1b, 0x06, 0x21, 0x3c, 0x4a, 0x57, 0x70, 0x6d, 0x3e, 0x23, 0x04, 0x19, 0xa2, 0xbf, 0x98, 0x85, 0xd6, 0xcb, 0xec, 0xf1, 0x13, 0x0e, 0x29, 0x34, 0x67, 0x7a, 0x5d, 0x40, 0xfb, 0xe6, 0xc1, 0xdc, 0x8f, 0x92, 0xb5, 0xa8, 0xde, 0xc3, 0xe4, 0xf9, 0xaa, 0xb7, 0x90, 0x8d, 0x36, 0x2b, 0x0c, 0x11, 0x42, 0x5f, 0x78, 0x65, 0x94, 0x89, 0xae, 0xb3, 0xe0, 0xfd, 0xda, 0xc7, 0x7c, 0x61, 0x46, 0x5b, 0x08, 0x15, 0x32, 0x2f, 0x59, 0x44, 0x63, 0x7e, 0x2d, 0x30, 0x17, 0x0a, 0xb1, 0xac, 0x8b, 0x96, 0xc5, 0xd8, 0xff, 0xe2, 0x26, 0x3b, 0x1c, 0x01, 0x52, 0x4f, 0x68, 0x75, 0xce, 0xd3, 0xf4, 0xe9, 0xba, 0xa7, 0x80, 0x9d, 0xeb, 0xf6, 0xd1, 0xcc, 0x9f, 0x82, 0xa5, 0xb8, 0x03, 0x1e, 0x39, 0x24, 0x77, 0x6a, 0x4d, 0x50, 0xa1, 0xbc, 0x9b, 0x86, 0xd5, 0xc8, 0xef, 0xf2, 0x49, 0x54, 0x73, 0x6e, 0x3d, 0x20, 0x07, 0x1a, 0x6c, 0x71, 0x56, 0x4b, 0x18, 0x05, 0x22, 0x3f, 0x84, 0x99, 0xbe, 0xa3, 0xf0, 0xed, 0xca, 0xd7, 0x35, 0x28, 0x0f, 0x12, 0x41, 0x5c, 0x7b, 0x66, 0xdd, 0xc0, 0xe7, 0xfa, 0xa9, 0xb4, 0x93, 0x8e, 0xf8, 0xe5, 0xc2, 0xdf, 0x8c, 0x91, 0xb6, 0xab, 0x10, 0x0d, 0x2a, 0x37, 0x64, 0x79, 0x5e, 0x43, 0xb2, 0xaf, 0x88, 0x95, 0xc6, 0xdb, 0xfc, 0xe1, 0x5a, 0x47, 0x60, 0x7d, 0x2e, 0x33, 0x14, 0x09, 0x7f, 0x62, 0x45, 0x58, 0x0b, 0x16, 0x31, 0x2c, 0x97, 0x8a, 0xad, 0xb0, 0xe3, 0xfe, 0xd9, 0xc4
-};
+const OI_BYTE crc8_narrow[256]
+    = {0x00, 0x1d, 0x3a, 0x27, 0x74, 0x69, 0x4e, 0x53, 0xe8, 0xf5, 0xd2, 0xcf, 0x9c, 0x81, 0xa6, 0xbb, 0xcd, 0xd0, 0xf7, 0xea, 0xb9, 0xa4, 0x83, 0x9e, 0x25, 0x38, 0x1f, 0x02, 0x51, 0x4c, 0x6b, 0x76,
+       0x87, 0x9a, 0xbd, 0xa0, 0xf3, 0xee, 0xc9, 0xd4, 0x6f, 0x72, 0x55, 0x48, 0x1b, 0x06, 0x21, 0x3c, 0x4a, 0x57, 0x70, 0x6d, 0x3e, 0x23, 0x04, 0x19, 0xa2, 0xbf, 0x98, 0x85, 0xd6, 0xcb, 0xec, 0xf1,
+       0x13, 0x0e, 0x29, 0x34, 0x67, 0x7a, 0x5d, 0x40, 0xfb, 0xe6, 0xc1, 0xdc, 0x8f, 0x92, 0xb5, 0xa8, 0xde, 0xc3, 0xe4, 0xf9, 0xaa, 0xb7, 0x90, 0x8d, 0x36, 0x2b, 0x0c, 0x11, 0x42, 0x5f, 0x78, 0x65,
+       0x94, 0x89, 0xae, 0xb3, 0xe0, 0xfd, 0xda, 0xc7, 0x7c, 0x61, 0x46, 0x5b, 0x08, 0x15, 0x32, 0x2f, 0x59, 0x44, 0x63, 0x7e, 0x2d, 0x30, 0x17, 0x0a, 0xb1, 0xac, 0x8b, 0x96, 0xc5, 0xd8, 0xff, 0xe2,
+       0x26, 0x3b, 0x1c, 0x01, 0x52, 0x4f, 0x68, 0x75, 0xce, 0xd3, 0xf4, 0xe9, 0xba, 0xa7, 0x80, 0x9d, 0xeb, 0xf6, 0xd1, 0xcc, 0x9f, 0x82, 0xa5, 0xb8, 0x03, 0x1e, 0x39, 0x24, 0x77, 0x6a, 0x4d, 0x50,
+       0xa1, 0xbc, 0x9b, 0x86, 0xd5, 0xc8, 0xef, 0xf2, 0x49, 0x54, 0x73, 0x6e, 0x3d, 0x20, 0x07, 0x1a, 0x6c, 0x71, 0x56, 0x4b, 0x18, 0x05, 0x22, 0x3f, 0x84, 0x99, 0xbe, 0xa3, 0xf0, 0xed, 0xca, 0xd7,
+       0x35, 0x28, 0x0f, 0x12, 0x41, 0x5c, 0x7b, 0x66, 0xdd, 0xc0, 0xe7, 0xfa, 0xa9, 0xb4, 0x93, 0x8e, 0xf8, 0xe5, 0xc2, 0xdf, 0x8c, 0x91, 0xb6, 0xab, 0x10, 0x0d, 0x2a, 0x37, 0x64, 0x79, 0x5e, 0x43,
+       0xb2, 0xaf, 0x88, 0x95, 0xc6, 0xdb, 0xfc, 0xe1, 0x5a, 0x47, 0x60, 0x7d, 0x2e, 0x33, 0x14, 0x09, 0x7f, 0x62, 0x45, 0x58, 0x0b, 0x16, 0x31, 0x2c, 0x97, 0x8a, 0xad, 0xb0, 0xe3, 0xfe, 0xd9, 0xc4};
 #endif
 const OI_UINT32 dequant_long_scaled[17] = {
-    0,
-    0,
-    0x1ee9e116, /* bits=2  0.24151243  1/3      * (1/1.38019122262781) (0x00000008)*/
-    0x0d3fa99c, /* bits=3  0.10350533  1/7      * (1/1.38019122262781) (0x00000013)*/
-    0x062ec69e, /* bits=4  0.04830249  1/15     * (1/1.38019122262781) (0x00000029)*/
-    0x02fddbfa, /* bits=5  0.02337217  1/31     * (1/1.38019122262781) (0x00000055)*/
-    0x0178d9f5, /* bits=6  0.01150059  1/63     * (1/1.38019122262781) (0x000000ad)*/
-    0x00baf129, /* bits=7  0.00570502  1/127    * (1/1.38019122262781) (0x0000015e)*/
-    0x005d1abe, /* bits=8  0.00284132  1/255    * (1/1.38019122262781) (0x000002bf)*/
-    0x002e760d, /* bits=9  0.00141788  1/511    * (1/1.38019122262781) (0x00000582)*/
-    0x00173536, /* bits=10 0.00070825  1/1023   * (1/1.38019122262781) (0x00000b07)*/
-    0x000b9928, /* bits=11 0.00035395  1/2047   * (1/1.38019122262781) (0x00001612)*/
-    0x0005cc37, /* bits=12 0.00017693  1/4095   * (1/1.38019122262781) (0x00002c27)*/
-    0x0002e604, /* bits=13 0.00008846  1/8191   * (1/1.38019122262781) (0x00005852)*/
-    0x000172fc, /* bits=14 0.00004422  1/16383  * (1/1.38019122262781) (0x0000b0a7)*/
-    0x0000b97d, /* bits=15 0.00002211  1/32767  * (1/1.38019122262781) (0x00016150)*/
-    0x00005cbe, /* bits=16 0.00001106  1/65535  * (1/1.38019122262781) (0x0002c2a5)*/
+    0,          0, 0x1ee9e116, /* bits=2  0.24151243  1/3      * (1/1.38019122262781) (0x00000008)*/
+    0x0d3fa99c,                /* bits=3  0.10350533  1/7      * (1/1.38019122262781) (0x00000013)*/
+    0x062ec69e,                /* bits=4  0.04830249  1/15     * (1/1.38019122262781) (0x00000029)*/
+    0x02fddbfa,                /* bits=5  0.02337217  1/31     * (1/1.38019122262781) (0x00000055)*/
+    0x0178d9f5,                /* bits=6  0.01150059  1/63     * (1/1.38019122262781) (0x000000ad)*/
+    0x00baf129,                /* bits=7  0.00570502  1/127    * (1/1.38019122262781) (0x0000015e)*/
+    0x005d1abe,                /* bits=8  0.00284132  1/255    * (1/1.38019122262781) (0x000002bf)*/
+    0x002e760d,                /* bits=9  0.00141788  1/511    * (1/1.38019122262781) (0x00000582)*/
+    0x00173536,                /* bits=10 0.00070825  1/1023   * (1/1.38019122262781) (0x00000b07)*/
+    0x000b9928,                /* bits=11 0.00035395  1/2047   * (1/1.38019122262781) (0x00001612)*/
+    0x0005cc37,                /* bits=12 0.00017693  1/4095   * (1/1.38019122262781) (0x00002c27)*/
+    0x0002e604,                /* bits=13 0.00008846  1/8191   * (1/1.38019122262781) (0x00005852)*/
+    0x000172fc,                /* bits=14 0.00004422  1/16383  * (1/1.38019122262781) (0x0000b0a7)*/
+    0x0000b97d,                /* bits=15 0.00002211  1/32767  * (1/1.38019122262781) (0x00016150)*/
+    0x00005cbe,                /* bits=16 0.00001106  1/65535  * (1/1.38019122262781) (0x0002c2a5)*/
 };
 
 const OI_UINT32 dequant_long_unscaled[17] = {
-    0,
-    0,
-    0x2aaaaaab, /* bits=2  0.33333333  1/3      (0x00000005)*/
-    0x12492492, /* bits=3  0.14285714  1/7      (0x0000000e)*/
-    0x08888889, /* bits=4  0.06666667  1/15     (0x0000001d)*/
-    0x04210842, /* bits=5  0.03225806  1/31     (0x0000003e)*/
-    0x02082082, /* bits=6  0.01587302  1/63     (0x0000007e)*/
-    0x01020408, /* bits=7  0.00787402  1/127    (0x000000fe)*/
-    0x00808081, /* bits=8  0.00392157  1/255    (0x000001fd)*/
-    0x00402010, /* bits=9  0.00195695  1/511    (0x000003fe)*/
-    0x00200802, /* bits=10 0.00097752  1/1023   (0x000007fe)*/
-    0x00100200, /* bits=11 0.00048852  1/2047   (0x00000ffe)*/
-    0x00080080, /* bits=12 0.00024420  1/4095   (0x00001ffe)*/
-    0x00040020, /* bits=13 0.00012209  1/8191   (0x00003ffe)*/
-    0x00020008, /* bits=14 0.00006104  1/16383  (0x00007ffe)*/
-    0x00010002, /* bits=15 0.00003052  1/32767  (0x0000fffe)*/
-    0x00008001, /* bits=16 0.00001526  1/65535  (0x0001fffc)*/
+    0,          0, 0x2aaaaaab, /* bits=2  0.33333333  1/3      (0x00000005)*/
+    0x12492492,                /* bits=3  0.14285714  1/7      (0x0000000e)*/
+    0x08888889,                /* bits=4  0.06666667  1/15     (0x0000001d)*/
+    0x04210842,                /* bits=5  0.03225806  1/31     (0x0000003e)*/
+    0x02082082,                /* bits=6  0.01587302  1/63     (0x0000007e)*/
+    0x01020408,                /* bits=7  0.00787402  1/127    (0x000000fe)*/
+    0x00808081,                /* bits=8  0.00392157  1/255    (0x000001fd)*/
+    0x00402010,                /* bits=9  0.00195695  1/511    (0x000003fe)*/
+    0x00200802,                /* bits=10 0.00097752  1/1023   (0x000007fe)*/
+    0x00100200,                /* bits=11 0.00048852  1/2047   (0x00000ffe)*/
+    0x00080080,                /* bits=12 0.00024420  1/4095   (0x00001ffe)*/
+    0x00040020,                /* bits=13 0.00012209  1/8191   (0x00003ffe)*/
+    0x00020008,                /* bits=14 0.00006104  1/16383  (0x00007ffe)*/
+    0x00010002,                /* bits=15 0.00003052  1/32767  (0x0000fffe)*/
+    0x00008001,                /* bits=16 0.00001526  1/65535  (0x0001fffc)*/
 };
 
 #if defined(OI_DEBUG) || defined(PRINT_SAMPLES) || defined(PRINT_SCALEFACTORS)
@@ -235,138 +113,126 @@ const OI_UINT32 dequant_long_unscaled[17] = {
 #endif
 
 #ifdef USE_WIDE_CRC
-static INLINE OI_CHAR crc_iterate(OI_UINT8 oldcrc, OI_UINT8 next)
-{
-    OI_UINT crc;
-    OI_UINT idx;
-    idx = oldcrc ^ next;
-    crc = crc8_wide[idx >> 1];
-    if (idx % 2) {
-        crc &= 0xff;
-    } else {
-        crc >>= 8;
-    }
-
-    return crc;
+static INLINE OI_CHAR crc_iterate(OI_UINT8 oldcrc, OI_UINT8 next) {
+  OI_UINT crc;
+  OI_UINT idx;
+  idx = oldcrc ^ next;
+  crc = crc8_wide[idx >> 1];
+  if (idx % 2) {
+    crc &= 0xff;
+  } else {
+    crc >>= 8;
+  }
+
+  return crc;
 }
 
-static INLINE OI_CHAR crc_iterate_top4(OI_UINT8 oldcrc, OI_UINT8 next)
-{
-    OI_UINT crc;
-    OI_UINT idx;
-    idx = (oldcrc ^ next) >> 4;
-    crc = crc8_wide[idx >> 1];
-    if (idx % 2) {
-        crc &= 0xff;
-    } else {
-        crc >>= 8;
-    }
-
-    return (oldcrc << 4) ^ crc;
+static INLINE OI_CHAR crc_iterate_top4(OI_UINT8 oldcrc, OI_UINT8 next) {
+  OI_UINT crc;
+  OI_UINT idx;
+  idx = (oldcrc ^ next) >> 4;
+  crc = crc8_wide[idx >> 1];
+  if (idx % 2) {
+    crc &= 0xff;
+  } else {
+    crc >>= 8;
+  }
+
+  return (oldcrc << 4) ^ crc;
 }
 
 #else // USE_WIDE_CRC
 
-static INLINE OI_UINT8 crc_iterate_top4(OI_UINT8 oldcrc, OI_UINT8 next)
-{
-    return (oldcrc << 4) ^ crc8_narrow[(oldcrc ^ next) >> 4];
-}
+static INLINE OI_UINT8 crc_iterate_top4(OI_UINT8 oldcrc, OI_UINT8 next) { return (oldcrc << 4) ^ crc8_narrow[(oldcrc ^ next) >> 4]; }
 
 #ifdef USE_NIBBLEWISE_CRC
-static INLINE OI_UINT8 crc_iterate(OI_UINT8 crc, OI_UINT8 next)
-{
-    crc = (crc << 4) ^ crc8_narrow[(crc ^ next) >> 4];
-    crc = (crc << 4) ^ crc8_narrow[((crc >> 4) ^ next) & 0xf];
+static INLINE OI_UINT8 crc_iterate(OI_UINT8 crc, OI_UINT8 next) {
+  crc = (crc << 4) ^ crc8_narrow[(crc ^ next) >> 4];
+  crc = (crc << 4) ^ crc8_narrow[((crc >> 4) ^ next) & 0xf];
 
-    return crc;
+  return crc;
 }
 
 #else // USE_NIBBLEWISE_CRC
-static INLINE OI_UINT8 crc_iterate(OI_UINT8 crc, OI_UINT8 next)
-{
-    return crc8_narrow[crc ^ next];
-}
+static INLINE OI_UINT8 crc_iterate(OI_UINT8 crc, OI_UINT8 next) { return crc8_narrow[crc ^ next]; }
 
 #endif // USE_NIBBLEWISE_CRC
 
 #endif // USE_WIDE_CRC
 
-PRIVATE OI_UINT8 OI_SBC_CalculateChecksum(OI_CODEC_SBC_FRAME_INFO *frame, OI_BYTE const *data)
-{
-    OI_UINT i;
-    OI_UINT8 crc = 0x0f;
-    /* Count is the number of whole bytes subject to CRC. Actually, it's one
-     * more than this number, because data[3] is the CRC field itself, which is
-     * explicitly skipped. Since crc_iterate (should be) inlined, it's cheaper
-     * spacewise to include the check in the loop. This shouldn't be much of a
-     * bottleneck routine in the first place. */
-    OI_UINT count = (frame->nrof_subbands * frame->nrof_channels / 2u) + 4;
-
-    if (frame->mode == SBC_JOINT_STEREO && frame->nrof_subbands == 8) {
-        count++;
+PRIVATE OI_UINT8 OI_SBC_CalculateChecksum(OI_CODEC_SBC_FRAME_INFO *frame, OI_BYTE const *data) {
+  OI_UINT  i;
+  OI_UINT8 crc = 0x0f;
+  /* Count is the number of whole bytes subject to CRC. Actually, it's one
+   * more than this number, because data[3] is the CRC field itself, which is
+   * explicitly skipped. Since crc_iterate (should be) inlined, it's cheaper
+   * spacewise to include the check in the loop. This shouldn't be much of a
+   * bottleneck routine in the first place. */
+  OI_UINT count = (frame->nrof_subbands * frame->nrof_channels / 2u) + 4;
+
+  if (frame->mode == SBC_JOINT_STEREO && frame->nrof_subbands == 8) {
+    count++;
+  }
+
+  for (i = 1; i < count; i++) {
+    if (i != 3) {
+      crc = crc_iterate(crc, data[i]);
     }
+  }
 
-    for (i = 1; i < count; i++) {
-        if (i != 3) {
-            crc = crc_iterate(crc, data[i]);
-        }
-    }
-
-    if (frame->mode == SBC_JOINT_STEREO && frame->nrof_subbands == 4) {
-        crc = crc_iterate_top4(crc, data[i]);
-    }
+  if (frame->mode == SBC_JOINT_STEREO && frame->nrof_subbands == 4) {
+    crc = crc_iterate_top4(crc, data[i]);
+  }
 
-    return crc;
+  return crc;
 }
 
-void OI_SBC_ExpandFrameFields(OI_CODEC_SBC_FRAME_INFO *frame)
-{
-    frame->nrof_blocks = block_values[frame->blocks];
-    frame->nrof_subbands = band_values[frame->subbands];
+void OI_SBC_ExpandFrameFields(OI_CODEC_SBC_FRAME_INFO *frame) {
+  frame->nrof_blocks   = block_values[frame->blocks];
+  frame->nrof_subbands = band_values[frame->subbands];
 
-    frame->frequency = freq_values[frame->freqIndex];
-    frame->nrof_channels = channel_values[frame->mode];
+  frame->frequency     = freq_values[frame->freqIndex];
+  frame->nrof_channels = channel_values[frame->mode];
 }
 
 /**
  * Unrolled macro to copy 4 32-bit aligned 32-bit values backward in memory
  */
 #define COPY4WORDS_BACK(_dest, _src) \
-    do {                             \
-        OI_INT32 _a, _b, _c, _d;     \
-        _a = *--_src;                \
-        _b = *--_src;                \
-        _c = *--_src;                \
-        _d = *--_src;                \
-        *--_dest = _a;               \
-        *--_dest = _b;               \
-        *--_dest = _c;               \
-        *--_dest = _d;               \
-    } while (0)
+  do {                               \
+    OI_INT32 _a, _b, _c, _d;         \
+    _a       = *--_src;              \
+    _b       = *--_src;              \
+    _c       = *--_src;              \
+    _d       = *--_src;              \
+    *--_dest = _a;                   \
+    *--_dest = _b;                   \
+    *--_dest = _c;                   \
+    *--_dest = _d;                   \
+  } while (0)
 
 #if defined(USE_PLATFORM_MEMMOVE) || defined(USE_PLATFORM_MEMCPY)
 #include 
 #endif
-PRIVATE void shift_buffer(SBC_BUFFER_T *dest, SBC_BUFFER_T *src, OI_UINT wordCount)
-{
+PRIVATE void shift_buffer(SBC_BUFFER_T *dest, SBC_BUFFER_T *src, OI_UINT wordCount) {
 #ifdef USE_PLATFORM_MEMMOVE
-    memmove(dest, src, wordCount * sizeof(SBC_BUFFER_T));
+  memmove(dest, src, wordCount * sizeof(SBC_BUFFER_T));
 #elif defined(USE_PLATFORM_MEMCPY)
-    OI_ASSERT(((OI_CHAR *)(dest) - (OI_CHAR *)(src)) >= wordCount * sizeof(*dest));
-    memcpy(dest, src, wordCount * sizeof(SBC_BUFFER_T));
+  OI_ASSERT(((OI_CHAR *)(dest) - (OI_CHAR *)(src)) >= wordCount * sizeof(*dest));
+  memcpy(dest, src, wordCount * sizeof(SBC_BUFFER_T));
 #else
-    OI_UINT n;
-    OI_INT32 *d;
-    OI_INT32 *s;
-    n = wordCount / 4 / (sizeof(OI_INT32) / sizeof(*dest));
-    OI_ASSERT((n * 4 * (sizeof(OI_INT32) / sizeof(*dest))) == wordCount);
-
-    d = (void *)(dest + wordCount);
-    s = (void *)(src + wordCount);
-
-    do {
-        COPY4WORDS_BACK(d, s);
-    } while (--n);
+  OI_UINT   n;
+  OI_INT32 *d;
+  OI_INT32 *s;
+  n = wordCount / 4 / (sizeof(OI_INT32) / sizeof(*dest));
+  OI_ASSERT((n * 4 * (sizeof(OI_INT32) / sizeof(*dest))) == wordCount);
+
+  d = (void *)(dest + wordCount);
+  s = (void *)(src + wordCount);
+
+  do {
+    COPY4WORDS_BACK(d, s);
+  } while (--n);
 #endif
 }
 /**
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_codec_version.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_codec_version.c
index 697ef102fa..e033226f9d 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_codec_version.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_codec_version.c
@@ -33,8 +33,8 @@ version number of the eSBC codec
 /**********************************************************************************
   $Revision: #1 $
 ***********************************************************************************/
-#include "oi_stddefs.h"
 #include "oi_codec_sbc_private.h"
+#include "oi_stddefs.h"
 
 #if defined(SBC_DEC_INCLUDED)
 /** Version string for the BLUEmagic 3.0 protocol stack and profiles */
@@ -46,10 +46,7 @@ PRIVATE OI_CHAR *const codecVersion = "v1.5"
 
 /** This function returns the version string for the BLUEmagic 3.0 protocol stack
     and profiles */
-OI_CHAR *OI_CODEC_Version(void)
-{
-    return codecVersion;
-}
+OI_CHAR *OI_CODEC_Version(void) { return codecVersion; }
 
 /**********************************************************************************/
 
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-8-generated.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-8-generated.c
index 71ff6a9e08..cc603f7d7a 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-8-generated.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-8-generated.c
@@ -35,127 +35,126 @@
 #if defined(SBC_DEC_INCLUDED)
 
 #ifndef CLIP_INT16
-#define CLIP_INT16(x)                  \
-    do {                               \
-        if (x > OI_INT16_MAX) {        \
-            x = OI_INT16_MAX;          \
-        } else if (x < OI_INT16_MIN) { \
-            x = OI_INT16_MIN;          \
-        }                              \
-    } while (0)
+#define CLIP_INT16(x)              \
+  do {                             \
+    if (x > OI_INT16_MAX) {        \
+      x = OI_INT16_MAX;            \
+    } else if (x < OI_INT16_MIN) { \
+      x = OI_INT16_MIN;            \
+    }                              \
+  } while (0)
 #endif
 
 #define MUL_16S_16S(_x, _y) ((_x) * (_y))
 
-PRIVATE void SynthWindow80_generated(OI_INT16 *pcm, SBC_BUFFER_T const *RESTRICT buffer, OI_UINT strideShift)
-{
-    OI_INT32 pcm_a, pcm_b;
-    /* 1 - stage 0 */ pcm_b = 0;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(8235, buffer[12])) >> 3;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(-23167, buffer[20])) >> 3;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(26479, buffer[28])) >> 2;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(-17397, buffer[36])) << 1;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(9399, buffer[44])) << 3;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(17397, buffer[52])) << 1;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(26479, buffer[60])) >> 2;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(23167, buffer[68])) >> 3;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(8235, buffer[76])) >> 3;
-    /* 1 - stage 0 */ pcm_b /= 32768;
-    CLIP_INT16(pcm_b);
-    pcm[0 << strideShift] = (OI_INT16)pcm_b;
-    /* 1 - stage 1 */ pcm_a = 0;
-    /* 1 - stage 1 */ pcm_b = 0;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(-3263, buffer[5])) >> 5;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(9293, buffer[5])) >> 3;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(29293, buffer[11])) >> 5;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(-6087, buffer[11])) >> 2;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(-5229, buffer[21]));
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(1247, buffer[21])) << 3;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(30835, buffer[27])) >> 3;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(-2893, buffer[27])) << 3;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(-27021, buffer[37])) << 1;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(23671, buffer[37])) << 2;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(31633, buffer[43])) << 1;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(18055, buffer[43])) << 1;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(17319, buffer[53])) << 1;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(11537, buffer[53])) >> 1;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(26663, buffer[59])) >> 2;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(1747, buffer[59])) << 1;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(4555, buffer[69])) >> 1;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(685, buffer[69])) << 1;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(12419, buffer[75])) >> 4;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(8721, buffer[75])) >> 7;
-    /* 1 - stage 1 */ pcm_a /= 32768;
-    CLIP_INT16(pcm_a);
-    pcm[1 << strideShift] = (OI_INT16)pcm_a;
-    /* 1 - stage 1 */ pcm_b /= 32768;
-    CLIP_INT16(pcm_b);
-    pcm[7 << strideShift] = (OI_INT16)pcm_b;
-    /* 1 - stage 2 */ pcm_a = 0;
-    /* 1 - stage 2 */ pcm_b = 0;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(-10385, buffer[6])) >> 6;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(11167, buffer[6])) >> 4;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(24995, buffer[10])) >> 5;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(-10337, buffer[10])) >> 4;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(-309, buffer[22])) << 4;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(1917, buffer[22])) << 2;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(9161, buffer[26])) >> 3;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(-30605, buffer[26])) >> 1;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(-23063, buffer[38])) << 1;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(8317, buffer[38])) << 3;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(27561, buffer[42])) << 1;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(9553, buffer[42])) << 2;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(2309, buffer[54])) << 3;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(22117, buffer[54])) >> 4;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(12705, buffer[58])) >> 1;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(16383, buffer[58])) >> 2;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(6239, buffer[70])) >> 3;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(7543, buffer[70])) >> 3;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(9251, buffer[74])) >> 4;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(8603, buffer[74])) >> 6;
-    /* 1 - stage 2 */ pcm_a /= 32768;
-    CLIP_INT16(pcm_a);
-    pcm[2 << strideShift] = (OI_INT16)pcm_a;
-    /* 1 - stage 2 */ pcm_b /= 32768;
-    CLIP_INT16(pcm_b);
-    pcm[6 << strideShift] = (OI_INT16)pcm_b;
-    /* 1 - stage 3 */ pcm_a = 0;
-    /* 1 - stage 3 */ pcm_b = 0;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(-16457, buffer[7])) >> 6;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(16913, buffer[7])) >> 5;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(19083, buffer[9])) >> 5;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(-8443, buffer[9])) >> 7;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(-23641, buffer[23])) >> 2;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(3687, buffer[23])) << 1;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(-29015, buffer[25])) >> 4;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(-301, buffer[25])) << 5;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(-12889, buffer[39])) << 2;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(15447, buffer[39])) << 2;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(6145, buffer[41])) << 3;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(10255, buffer[41])) << 2;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(24211, buffer[55])) >> 1;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(-18233, buffer[55])) >> 3;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(23469, buffer[57])) >> 2;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(9405, buffer[57])) >> 1;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(21223, buffer[71])) >> 8;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(1499, buffer[71])) >> 1;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(26913, buffer[73])) >> 6;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(26189, buffer[73])) >> 7;
-    /* 1 - stage 3 */ pcm_a /= 32768;
-    CLIP_INT16(pcm_a);
-    pcm[3 << strideShift] = (OI_INT16)pcm_a;
-    /* 1 - stage 3 */ pcm_b /= 32768;
-    CLIP_INT16(pcm_b);
-    pcm[5 << strideShift] = (OI_INT16)pcm_b;
-    /* 1 - stage 4 */ pcm_a = 0;
-    /* 1 - stage 4 */ pcm_a += (MUL_16S_16S(10445, buffer[8])) >> 4;
-    /* 1 - stage 4 */ pcm_a += (MUL_16S_16S(-5297, buffer[24])) << 1;
-    /* 1 - stage 4 */ pcm_a += (MUL_16S_16S(22299, buffer[40])) << 2;
-    /* 1 - stage 4 */ pcm_a += (MUL_16S_16S(10603, buffer[56]));
-    /* 1 - stage 4 */ pcm_a += (MUL_16S_16S(9539, buffer[72])) >> 4;
-    /* 1 - stage 4 */ pcm_a /= 32768;
-    CLIP_INT16(pcm_a);
-    pcm[4 << strideShift] = (OI_INT16)pcm_a;
+PRIVATE void SynthWindow80_generated(OI_INT16 *pcm, SBC_BUFFER_T const *RESTRICT buffer, OI_UINT strideShift) {
+  OI_INT32 pcm_a, pcm_b;
+  /* 1 - stage 0 */ pcm_b = 0;
+  /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(8235, buffer[12])) >> 3;
+  /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(-23167, buffer[20])) >> 3;
+  /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(26479, buffer[28])) >> 2;
+  /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(-17397, buffer[36])) << 1;
+  /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(9399, buffer[44])) << 3;
+  /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(17397, buffer[52])) << 1;
+  /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(26479, buffer[60])) >> 2;
+  /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(23167, buffer[68])) >> 3;
+  /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(8235, buffer[76])) >> 3;
+  /* 1 - stage 0 */ pcm_b /= 32768;
+  CLIP_INT16(pcm_b);
+  pcm[0 << strideShift]   = (OI_INT16)pcm_b;
+  /* 1 - stage 1 */ pcm_a = 0;
+  /* 1 - stage 1 */ pcm_b = 0;
+  /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(-3263, buffer[5])) >> 5;
+  /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(9293, buffer[5])) >> 3;
+  /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(29293, buffer[11])) >> 5;
+  /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(-6087, buffer[11])) >> 2;
+  /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(-5229, buffer[21]));
+  /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(1247, buffer[21])) << 3;
+  /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(30835, buffer[27])) >> 3;
+  /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(-2893, buffer[27])) << 3;
+  /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(-27021, buffer[37])) << 1;
+  /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(23671, buffer[37])) << 2;
+  /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(31633, buffer[43])) << 1;
+  /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(18055, buffer[43])) << 1;
+  /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(17319, buffer[53])) << 1;
+  /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(11537, buffer[53])) >> 1;
+  /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(26663, buffer[59])) >> 2;
+  /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(1747, buffer[59])) << 1;
+  /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(4555, buffer[69])) >> 1;
+  /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(685, buffer[69])) << 1;
+  /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(12419, buffer[75])) >> 4;
+  /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(8721, buffer[75])) >> 7;
+  /* 1 - stage 1 */ pcm_a /= 32768;
+  CLIP_INT16(pcm_a);
+  pcm[1 << strideShift] = (OI_INT16)pcm_a;
+  /* 1 - stage 1 */ pcm_b /= 32768;
+  CLIP_INT16(pcm_b);
+  pcm[7 << strideShift]   = (OI_INT16)pcm_b;
+  /* 1 - stage 2 */ pcm_a = 0;
+  /* 1 - stage 2 */ pcm_b = 0;
+  /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(-10385, buffer[6])) >> 6;
+  /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(11167, buffer[6])) >> 4;
+  /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(24995, buffer[10])) >> 5;
+  /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(-10337, buffer[10])) >> 4;
+  /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(-309, buffer[22])) << 4;
+  /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(1917, buffer[22])) << 2;
+  /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(9161, buffer[26])) >> 3;
+  /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(-30605, buffer[26])) >> 1;
+  /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(-23063, buffer[38])) << 1;
+  /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(8317, buffer[38])) << 3;
+  /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(27561, buffer[42])) << 1;
+  /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(9553, buffer[42])) << 2;
+  /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(2309, buffer[54])) << 3;
+  /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(22117, buffer[54])) >> 4;
+  /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(12705, buffer[58])) >> 1;
+  /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(16383, buffer[58])) >> 2;
+  /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(6239, buffer[70])) >> 3;
+  /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(7543, buffer[70])) >> 3;
+  /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(9251, buffer[74])) >> 4;
+  /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(8603, buffer[74])) >> 6;
+  /* 1 - stage 2 */ pcm_a /= 32768;
+  CLIP_INT16(pcm_a);
+  pcm[2 << strideShift] = (OI_INT16)pcm_a;
+  /* 1 - stage 2 */ pcm_b /= 32768;
+  CLIP_INT16(pcm_b);
+  pcm[6 << strideShift]   = (OI_INT16)pcm_b;
+  /* 1 - stage 3 */ pcm_a = 0;
+  /* 1 - stage 3 */ pcm_b = 0;
+  /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(-16457, buffer[7])) >> 6;
+  /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(16913, buffer[7])) >> 5;
+  /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(19083, buffer[9])) >> 5;
+  /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(-8443, buffer[9])) >> 7;
+  /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(-23641, buffer[23])) >> 2;
+  /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(3687, buffer[23])) << 1;
+  /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(-29015, buffer[25])) >> 4;
+  /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(-301, buffer[25])) << 5;
+  /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(-12889, buffer[39])) << 2;
+  /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(15447, buffer[39])) << 2;
+  /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(6145, buffer[41])) << 3;
+  /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(10255, buffer[41])) << 2;
+  /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(24211, buffer[55])) >> 1;
+  /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(-18233, buffer[55])) >> 3;
+  /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(23469, buffer[57])) >> 2;
+  /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(9405, buffer[57])) >> 1;
+  /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(21223, buffer[71])) >> 8;
+  /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(1499, buffer[71])) >> 1;
+  /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(26913, buffer[73])) >> 6;
+  /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(26189, buffer[73])) >> 7;
+  /* 1 - stage 3 */ pcm_a /= 32768;
+  CLIP_INT16(pcm_a);
+  pcm[3 << strideShift] = (OI_INT16)pcm_a;
+  /* 1 - stage 3 */ pcm_b /= 32768;
+  CLIP_INT16(pcm_b);
+  pcm[5 << strideShift]   = (OI_INT16)pcm_b;
+  /* 1 - stage 4 */ pcm_a = 0;
+  /* 1 - stage 4 */ pcm_a += (MUL_16S_16S(10445, buffer[8])) >> 4;
+  /* 1 - stage 4 */ pcm_a += (MUL_16S_16S(-5297, buffer[24])) << 1;
+  /* 1 - stage 4 */ pcm_a += (MUL_16S_16S(22299, buffer[40])) << 2;
+  /* 1 - stage 4 */ pcm_a += (MUL_16S_16S(10603, buffer[56]));
+  /* 1 - stage 4 */ pcm_a += (MUL_16S_16S(9539, buffer[72])) >> 4;
+  /* 1 - stage 4 */ pcm_a /= 32768;
+  CLIP_INT16(pcm_a);
+  pcm[4 << strideShift] = (OI_INT16)pcm_a;
 }
 
 #endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-dct8.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-dct8.c
index aa70d3bc3c..d75b8ae7ae 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-dct8.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-dct8.c
@@ -61,143 +61,141 @@
  * @return  A signed 32-bit value corresponding to the 32 most significant bits
  * of the 64-bit product of u and v.
  */
-static INLINE OI_INT32 default_mul_32s_32s_hi(OI_INT32 u, OI_INT32 v)
-{
-    OI_UINT32 u0, v0;
-    OI_INT32 u1, v1, w1, w2, t;
-
-    u0 = u & 0xFFFF;
-    u1 = u >> 16;
-    v0 = v & 0xFFFF;
-    v1 = v >> 16;
-    t = u0 * v0;
-    t = u1 * v0 + ((OI_UINT32)t >> 16);
-    w1 = t & 0xFFFF;
-    w2 = t >> 16;
-    w1 = u0 * v1 + w1;
-    return u1 * v1 + w2 + (w1 >> 16);
+static INLINE OI_INT32 default_mul_32s_32s_hi(OI_INT32 u, OI_INT32 v) {
+  OI_UINT32 u0, v0;
+  OI_INT32  u1, v1, w1, w2, t;
+
+  u0 = u & 0xFFFF;
+  u1 = u >> 16;
+  v0 = v & 0xFFFF;
+  v1 = v >> 16;
+  t  = u0 * v0;
+  t  = u1 * v0 + ((OI_UINT32)t >> 16);
+  w1 = t & 0xFFFF;
+  w2 = t >> 16;
+  w1 = u0 * v1 + w1;
+  return u1 * v1 + w2 + (w1 >> 16);
 }
 
 #define MUL_32S_32S_HI(_x, _y) default_mul_32s_32s_hi(_x, _y)
 
 #ifdef DEBUG_DCT
-PRIVATE void float_dct2_8(float *RESTRICT out, OI_INT32 const *RESTRICT in)
-{
+PRIVATE void float_dct2_8(float *RESTRICT out, OI_INT32 const *RESTRICT in) {
 #define FIX(x, bits) (((int)floor(0.5f + ((x) * ((float)(1 << bits))))) / ((float)(1 << bits)))
-#define FLOAT_BUTTERFLY(x, y)  \
-    x += y;                    \
-    y = x - (y * 2);           \
-    OI_ASSERT(VALID_INT32(x)); \
-    OI_ASSERT(VALID_INT32(y));
+#define FLOAT_BUTTERFLY(x, y) \
+  x += y;                     \
+  y = x - (y * 2);            \
+  OI_ASSERT(VALID_INT32(x));  \
+  OI_ASSERT(VALID_INT32(y));
 #define FLOAT_MULT_DCT(K, sample) (FIX(K, 20) * sample)
 #define FLOAT_SCALE(x, y)         (((x) / (double)(1 << (y))))
 
-    double L00, L01, L02, L03, L04, L05, L06, L07;
-    double L25;
-
-    double in0, in1, in2, in3;
-    double in4, in5, in6, in7;
-
-    in0 = FLOAT_SCALE(in[0], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in0));
-    in1 = FLOAT_SCALE(in[1], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in1));
-    in2 = FLOAT_SCALE(in[2], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in2));
-    in3 = FLOAT_SCALE(in[3], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in3));
-    in4 = FLOAT_SCALE(in[4], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in4));
-    in5 = FLOAT_SCALE(in[5], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in5));
-    in6 = FLOAT_SCALE(in[6], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in6));
-    in7 = FLOAT_SCALE(in[7], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in7));
-
-    L00 = (in0 + in7);
-    OI_ASSERT(VALID_INT32(L00));
-    L01 = (in1 + in6);
-    OI_ASSERT(VALID_INT32(L01));
-    L02 = (in2 + in5);
-    OI_ASSERT(VALID_INT32(L02));
-    L03 = (in3 + in4);
-    OI_ASSERT(VALID_INT32(L03));
-
-    L04 = (in3 - in4);
-    OI_ASSERT(VALID_INT32(L04));
-    L05 = (in2 - in5);
-    OI_ASSERT(VALID_INT32(L05));
-    L06 = (in1 - in6);
-    OI_ASSERT(VALID_INT32(L06));
-    L07 = (in0 - in7);
-    OI_ASSERT(VALID_INT32(L07));
-
-    FLOAT_BUTTERFLY(L00, L03);
-    FLOAT_BUTTERFLY(L01, L02);
-
-    L02 += L03;
-    OI_ASSERT(VALID_INT32(L02));
-
-    L02 = FLOAT_MULT_DCT(AAN_C4_FLOAT, L02);
-    OI_ASSERT(VALID_INT32(L02));
-
-    FLOAT_BUTTERFLY(L00, L01);
-
-    out[0] = (float)FLOAT_SCALE(L00, DCTII_8_SHIFT_0);
-    OI_ASSERT(VALID_INT16(out[0]));
-    out[4] = (float)FLOAT_SCALE(L01, DCTII_8_SHIFT_4);
-    OI_ASSERT(VALID_INT16(out[4]));
-
-    FLOAT_BUTTERFLY(L03, L02);
-    out[6] = (float)FLOAT_SCALE(L02, DCTII_8_SHIFT_6);
-    OI_ASSERT(VALID_INT16(out[6]));
-    out[2] = (float)FLOAT_SCALE(L03, DCTII_8_SHIFT_2);
-    OI_ASSERT(VALID_INT16(out[2]));
-
-    L04 += L05;
-    OI_ASSERT(VALID_INT32(L04));
-    L05 += L06;
-    OI_ASSERT(VALID_INT32(L05));
-    L06 += L07;
-    OI_ASSERT(VALID_INT32(L06));
-
-    L04 /= 2;
-    L05 /= 2;
-    L06 /= 2;
-    L07 /= 2;
-
-    L05 = FLOAT_MULT_DCT(AAN_C4_FLOAT, L05);
-    OI_ASSERT(VALID_INT32(L05));
-
-    L25 = L06 - L04;
-    OI_ASSERT(VALID_INT32(L25));
-    L25 = FLOAT_MULT_DCT(AAN_C6_FLOAT, L25);
-    OI_ASSERT(VALID_INT32(L25));
-
-    L04 = FLOAT_MULT_DCT(AAN_Q0_FLOAT, L04);
-    OI_ASSERT(VALID_INT32(L04));
-    L04 -= L25;
-    OI_ASSERT(VALID_INT32(L04));
-
-    L06 = FLOAT_MULT_DCT(AAN_Q1_FLOAT, L06);
-    OI_ASSERT(VALID_INT32(L06));
-    L06 -= L25;
-    OI_ASSERT(VALID_INT32(L25));
-
-    FLOAT_BUTTERFLY(L07, L05);
-
-    FLOAT_BUTTERFLY(L05, L04);
-    out[3] = (float)(FLOAT_SCALE(L04, DCTII_8_SHIFT_3 - 1));
-    OI_ASSERT(VALID_INT16(out[3]));
-    out[5] = (float)(FLOAT_SCALE(L05, DCTII_8_SHIFT_5 - 1));
-    OI_ASSERT(VALID_INT16(out[5]));
-
-    FLOAT_BUTTERFLY(L07, L06);
-    out[7] = (float)(FLOAT_SCALE(L06, DCTII_8_SHIFT_7 - 1));
-    OI_ASSERT(VALID_INT16(out[7]));
-    out[1] = (float)(FLOAT_SCALE(L07, DCTII_8_SHIFT_1 - 1));
-    OI_ASSERT(VALID_INT16(out[1]));
+  double L00, L01, L02, L03, L04, L05, L06, L07;
+  double L25;
+
+  double in0, in1, in2, in3;
+  double in4, in5, in6, in7;
+
+  in0 = FLOAT_SCALE(in[0], DCTII_8_SHIFT_IN);
+  OI_ASSERT(VALID_INT32(in0));
+  in1 = FLOAT_SCALE(in[1], DCTII_8_SHIFT_IN);
+  OI_ASSERT(VALID_INT32(in1));
+  in2 = FLOAT_SCALE(in[2], DCTII_8_SHIFT_IN);
+  OI_ASSERT(VALID_INT32(in2));
+  in3 = FLOAT_SCALE(in[3], DCTII_8_SHIFT_IN);
+  OI_ASSERT(VALID_INT32(in3));
+  in4 = FLOAT_SCALE(in[4], DCTII_8_SHIFT_IN);
+  OI_ASSERT(VALID_INT32(in4));
+  in5 = FLOAT_SCALE(in[5], DCTII_8_SHIFT_IN);
+  OI_ASSERT(VALID_INT32(in5));
+  in6 = FLOAT_SCALE(in[6], DCTII_8_SHIFT_IN);
+  OI_ASSERT(VALID_INT32(in6));
+  in7 = FLOAT_SCALE(in[7], DCTII_8_SHIFT_IN);
+  OI_ASSERT(VALID_INT32(in7));
+
+  L00 = (in0 + in7);
+  OI_ASSERT(VALID_INT32(L00));
+  L01 = (in1 + in6);
+  OI_ASSERT(VALID_INT32(L01));
+  L02 = (in2 + in5);
+  OI_ASSERT(VALID_INT32(L02));
+  L03 = (in3 + in4);
+  OI_ASSERT(VALID_INT32(L03));
+
+  L04 = (in3 - in4);
+  OI_ASSERT(VALID_INT32(L04));
+  L05 = (in2 - in5);
+  OI_ASSERT(VALID_INT32(L05));
+  L06 = (in1 - in6);
+  OI_ASSERT(VALID_INT32(L06));
+  L07 = (in0 - in7);
+  OI_ASSERT(VALID_INT32(L07));
+
+  FLOAT_BUTTERFLY(L00, L03);
+  FLOAT_BUTTERFLY(L01, L02);
+
+  L02 += L03;
+  OI_ASSERT(VALID_INT32(L02));
+
+  L02 = FLOAT_MULT_DCT(AAN_C4_FLOAT, L02);
+  OI_ASSERT(VALID_INT32(L02));
+
+  FLOAT_BUTTERFLY(L00, L01);
+
+  out[0] = (float)FLOAT_SCALE(L00, DCTII_8_SHIFT_0);
+  OI_ASSERT(VALID_INT16(out[0]));
+  out[4] = (float)FLOAT_SCALE(L01, DCTII_8_SHIFT_4);
+  OI_ASSERT(VALID_INT16(out[4]));
+
+  FLOAT_BUTTERFLY(L03, L02);
+  out[6] = (float)FLOAT_SCALE(L02, DCTII_8_SHIFT_6);
+  OI_ASSERT(VALID_INT16(out[6]));
+  out[2] = (float)FLOAT_SCALE(L03, DCTII_8_SHIFT_2);
+  OI_ASSERT(VALID_INT16(out[2]));
+
+  L04 += L05;
+  OI_ASSERT(VALID_INT32(L04));
+  L05 += L06;
+  OI_ASSERT(VALID_INT32(L05));
+  L06 += L07;
+  OI_ASSERT(VALID_INT32(L06));
+
+  L04 /= 2;
+  L05 /= 2;
+  L06 /= 2;
+  L07 /= 2;
+
+  L05 = FLOAT_MULT_DCT(AAN_C4_FLOAT, L05);
+  OI_ASSERT(VALID_INT32(L05));
+
+  L25 = L06 - L04;
+  OI_ASSERT(VALID_INT32(L25));
+  L25 = FLOAT_MULT_DCT(AAN_C6_FLOAT, L25);
+  OI_ASSERT(VALID_INT32(L25));
+
+  L04 = FLOAT_MULT_DCT(AAN_Q0_FLOAT, L04);
+  OI_ASSERT(VALID_INT32(L04));
+  L04 -= L25;
+  OI_ASSERT(VALID_INT32(L04));
+
+  L06 = FLOAT_MULT_DCT(AAN_Q1_FLOAT, L06);
+  OI_ASSERT(VALID_INT32(L06));
+  L06 -= L25;
+  OI_ASSERT(VALID_INT32(L25));
+
+  FLOAT_BUTTERFLY(L07, L05);
+
+  FLOAT_BUTTERFLY(L05, L04);
+  out[3] = (float)(FLOAT_SCALE(L04, DCTII_8_SHIFT_3 - 1));
+  OI_ASSERT(VALID_INT16(out[3]));
+  out[5] = (float)(FLOAT_SCALE(L05, DCTII_8_SHIFT_5 - 1));
+  OI_ASSERT(VALID_INT16(out[5]));
+
+  FLOAT_BUTTERFLY(L07, L06);
+  out[7] = (float)(FLOAT_SCALE(L06, DCTII_8_SHIFT_7 - 1));
+  OI_ASSERT(VALID_INT16(out[7]));
+  out[1] = (float)(FLOAT_SCALE(L07, DCTII_8_SHIFT_1 - 1));
+  OI_ASSERT(VALID_INT16(out[1]));
 }
 #undef BUTTERFLY
 #endif
@@ -247,101 +245,100 @@ PRIVATE void float_dct2_8(float *RESTRICT out, OI_INT32 const *RESTRICT in)
  * [ 0  0  0  0  0  0  1  2 ]
  *
  */
-PRIVATE void dct2_8(SBC_BUFFER_T *RESTRICT out, OI_INT32 const *RESTRICT in)
-{
+PRIVATE void dct2_8(SBC_BUFFER_T *RESTRICT out, OI_INT32 const *RESTRICT in) {
 #define BUTTERFLY(x, y) \
-    x += y;             \
-    y = x - (y << 1);
+  x += y;               \
+  y = x - (y << 1);
 #define FIX_MULT_DCT(K, x) (MUL_32S_32S_HI(K, x) << 2)
 
-    OI_INT32 L00, L01, L02, L03, L04, L05, L06, L07;
-    OI_INT32 L25;
+  OI_INT32 L00, L01, L02, L03, L04, L05, L06, L07;
+  OI_INT32 L25;
 
-    OI_INT32 in0, in1, in2, in3;
-    OI_INT32 in4, in5, in6, in7;
+  OI_INT32 in0, in1, in2, in3;
+  OI_INT32 in4, in5, in6, in7;
 
 #if DCTII_8_SHIFT_IN != 0
-    in0 = SCALE(in[0], DCTII_8_SHIFT_IN);
-    in1 = SCALE(in[1], DCTII_8_SHIFT_IN);
-    in2 = SCALE(in[2], DCTII_8_SHIFT_IN);
-    in3 = SCALE(in[3], DCTII_8_SHIFT_IN);
-    in4 = SCALE(in[4], DCTII_8_SHIFT_IN);
-    in5 = SCALE(in[5], DCTII_8_SHIFT_IN);
-    in6 = SCALE(in[6], DCTII_8_SHIFT_IN);
-    in7 = SCALE(in[7], DCTII_8_SHIFT_IN);
+  in0 = SCALE(in[0], DCTII_8_SHIFT_IN);
+  in1 = SCALE(in[1], DCTII_8_SHIFT_IN);
+  in2 = SCALE(in[2], DCTII_8_SHIFT_IN);
+  in3 = SCALE(in[3], DCTII_8_SHIFT_IN);
+  in4 = SCALE(in[4], DCTII_8_SHIFT_IN);
+  in5 = SCALE(in[5], DCTII_8_SHIFT_IN);
+  in6 = SCALE(in[6], DCTII_8_SHIFT_IN);
+  in7 = SCALE(in[7], DCTII_8_SHIFT_IN);
 #else
-    in0 = in[0];
-    in1 = in[1];
-    in2 = in[2];
-    in3 = in[3];
-    in4 = in[4];
-    in5 = in[5];
-    in6 = in[6];
-    in7 = in[7];
+  in0 = in[0];
+  in1 = in[1];
+  in2 = in[2];
+  in3 = in[3];
+  in4 = in[4];
+  in5 = in[5];
+  in6 = in[6];
+  in7 = in[7];
 #endif
 
-    L00 = in0 + in7;
-    L01 = in1 + in6;
-    L02 = in2 + in5;
-    L03 = in3 + in4;
+  L00 = in0 + in7;
+  L01 = in1 + in6;
+  L02 = in2 + in5;
+  L03 = in3 + in4;
 
-    L04 = in3 - in4;
-    L05 = in2 - in5;
-    L06 = in1 - in6;
-    L07 = in0 - in7;
+  L04 = in3 - in4;
+  L05 = in2 - in5;
+  L06 = in1 - in6;
+  L07 = in0 - in7;
 
-    BUTTERFLY(L00, L03);
-    BUTTERFLY(L01, L02);
+  BUTTERFLY(L00, L03);
+  BUTTERFLY(L01, L02);
 
-    L02 += L03;
+  L02 += L03;
 
-    L02 = FIX_MULT_DCT(AAN_C4_FIX, L02);
+  L02 = FIX_MULT_DCT(AAN_C4_FIX, L02);
 
-    BUTTERFLY(L00, L01);
+  BUTTERFLY(L00, L01);
 
-    out[0] = (OI_INT16)SCALE(L00, DCTII_8_SHIFT_0);
-    out[4] = (OI_INT16)SCALE(L01, DCTII_8_SHIFT_4);
+  out[0] = (OI_INT16)SCALE(L00, DCTII_8_SHIFT_0);
+  out[4] = (OI_INT16)SCALE(L01, DCTII_8_SHIFT_4);
 
-    BUTTERFLY(L03, L02);
-    out[6] = (OI_INT16)SCALE(L02, DCTII_8_SHIFT_6);
-    out[2] = (OI_INT16)SCALE(L03, DCTII_8_SHIFT_2);
+  BUTTERFLY(L03, L02);
+  out[6] = (OI_INT16)SCALE(L02, DCTII_8_SHIFT_6);
+  out[2] = (OI_INT16)SCALE(L03, DCTII_8_SHIFT_2);
 
-    L04 += L05;
-    L05 += L06;
-    L06 += L07;
+  L04 += L05;
+  L05 += L06;
+  L06 += L07;
 
-    L04 /= 2;
-    L05 /= 2;
-    L06 /= 2;
-    L07 /= 2;
+  L04 /= 2;
+  L05 /= 2;
+  L06 /= 2;
+  L07 /= 2;
 
-    L05 = FIX_MULT_DCT(AAN_C4_FIX, L05);
+  L05 = FIX_MULT_DCT(AAN_C4_FIX, L05);
 
-    L25 = L06 - L04;
-    L25 = FIX_MULT_DCT(AAN_C6_FIX, L25);
+  L25 = L06 - L04;
+  L25 = FIX_MULT_DCT(AAN_C6_FIX, L25);
 
-    L04 = FIX_MULT_DCT(AAN_Q0_FIX, L04);
-    L04 -= L25;
+  L04 = FIX_MULT_DCT(AAN_Q0_FIX, L04);
+  L04 -= L25;
 
-    L06 = FIX_MULT_DCT(AAN_Q1_FIX, L06);
-    L06 -= L25;
+  L06 = FIX_MULT_DCT(AAN_Q1_FIX, L06);
+  L06 -= L25;
 
-    BUTTERFLY(L07, L05);
+  BUTTERFLY(L07, L05);
 
-    BUTTERFLY(L05, L04);
-    out[3] = (OI_INT16)SCALE(L04, DCTII_8_SHIFT_3 - 1);
-    out[5] = (OI_INT16)SCALE(L05, DCTII_8_SHIFT_5 - 1);
+  BUTTERFLY(L05, L04);
+  out[3] = (OI_INT16)SCALE(L04, DCTII_8_SHIFT_3 - 1);
+  out[5] = (OI_INT16)SCALE(L05, DCTII_8_SHIFT_5 - 1);
 
-    BUTTERFLY(L07, L06);
-    out[7] = (OI_INT16)SCALE(L06, DCTII_8_SHIFT_7 - 1);
-    out[1] = (OI_INT16)SCALE(L07, DCTII_8_SHIFT_1 - 1);
+  BUTTERFLY(L07, L06);
+  out[7] = (OI_INT16)SCALE(L06, DCTII_8_SHIFT_7 - 1);
+  out[1] = (OI_INT16)SCALE(L07, DCTII_8_SHIFT_1 - 1);
 #undef BUTTERFLY
 
 #ifdef DEBUG_DCT
-    {
-        float float_out[8];
-        float_dct2_8(float_out, in);
-    }
+  {
+    float float_out[8];
+    float_dct2_8(float_out, in);
+  }
 #endif
 }
 
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-sbc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-sbc.c
index e343cf3dbe..66cd17a1d6 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-sbc.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-sbc.c
@@ -201,14 +201,14 @@ const OI_INT32 dec_window_4[21] = {
 #endif
 
 #ifndef CLIP_INT16
-#define CLIP_INT16(x)                  \
-    do {                               \
-        if (x > OI_INT16_MAX) {        \
-            x = OI_INT16_MAX;          \
-        } else if (x < OI_INT16_MIN) { \
-            x = OI_INT16_MIN;          \
-        }                              \
-    } while (0)
+#define CLIP_INT16(x)              \
+  do {                             \
+    if (x > OI_INT16_MAX) {        \
+      x = OI_INT16_MAX;            \
+    } else if (x < OI_INT16_MIN) { \
+      x = OI_INT16_MIN;            \
+    }                              \
+  } while (0)
 #endif
 
 /**
@@ -221,20 +221,19 @@ const OI_INT32 dec_window_4[21] = {
  * @return  A signed 32-bit value corresponding to the 32 most significant bits
  * of the 48-bit product of u and v.
  */
-static INLINE OI_INT32 default_mul_16s_32s_hi(OI_INT16 u, OI_INT32 v)
-{
-    OI_UINT16 v0;
-    OI_INT16 v1;
+static INLINE OI_INT32 default_mul_16s_32s_hi(OI_INT16 u, OI_INT32 v) {
+  OI_UINT16 v0;
+  OI_INT16  v1;
 
-    OI_INT32 w, x;
+  OI_INT32 w, x;
 
-    v0 = (OI_UINT16)(v & 0xffff);
-    v1 = (OI_INT16)(v >> 16);
+  v0 = (OI_UINT16)(v & 0xffff);
+  v1 = (OI_INT16)(v >> 16);
 
-    w = v1 * u;
-    x = u * v0;
+  w = v1 * u;
+  x = u * v0;
 
-    return w + (x >> 16);
+  return w + (x >> 16);
 }
 
 #define MUL_16S_32S_HI(_x, _y) default_mul_16s_32s_hi(_x, _y)
@@ -249,9 +248,9 @@ typedef void (*SYNTH_FRAME)(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm
 
 #ifndef COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS
 #define COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(dest, src) \
-    do {                                                    \
-        shift_buffer(dest, src, 72);                        \
-    } while (0)
+  do {                                                      \
+    shift_buffer(dest, src, 72);                            \
+  } while (0)
 #endif
 
 #ifndef DCT2_8
@@ -266,99 +265,94 @@ typedef void (*SYNTH_FRAME)(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm
 #define SYNTH112 SynthWindow112_generated
 #endif
 
-PRIVATE void OI_SBC_SynthFrame_80(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT blkstart, OI_UINT blkcount)
-{
-    OI_UINT blk;
-    OI_UINT ch;
-    OI_UINT nrof_channels = context->common.frameInfo.nrof_channels;
-    OI_UINT pcmStrideShift = context->common.pcmStride == 1 ? 0 : 1;
-    OI_UINT offset = context->common.filterBufferOffset;
-    OI_INT32 *s = context->common.subdata + 8 * nrof_channels * blkstart;
-    OI_UINT blkstop = blkstart + blkcount;
-
-    for (blk = blkstart; blk < blkstop; blk++) {
-        if (offset == 0) {
-            COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(context->common.filterBuffer[0] + context->common.filterBufferLen - 72, context->common.filterBuffer[0]);
-            if (nrof_channels == 2) {
-                COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(context->common.filterBuffer[1] + context->common.filterBufferLen - 72, context->common.filterBuffer[1]);
-            }
-            offset = context->common.filterBufferLen - 80;
-        } else {
-            offset -= 1 * 8;
-        }
-
-        for (ch = 0; ch < nrof_channels; ch++) {
-            DCT2_8(context->common.filterBuffer[ch] + offset, s);
-            SYNTH80(pcm + ch, context->common.filterBuffer[ch] + offset, pcmStrideShift);
-            s += 8;
-        }
-        pcm += (8 << pcmStrideShift);
+PRIVATE void OI_SBC_SynthFrame_80(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT blkstart, OI_UINT blkcount) {
+  OI_UINT   blk;
+  OI_UINT   ch;
+  OI_UINT   nrof_channels  = context->common.frameInfo.nrof_channels;
+  OI_UINT   pcmStrideShift = context->common.pcmStride == 1 ? 0 : 1;
+  OI_UINT   offset         = context->common.filterBufferOffset;
+  OI_INT32 *s              = context->common.subdata + 8 * nrof_channels * blkstart;
+  OI_UINT   blkstop        = blkstart + blkcount;
+
+  for (blk = blkstart; blk < blkstop; blk++) {
+    if (offset == 0) {
+      COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(context->common.filterBuffer[0] + context->common.filterBufferLen - 72, context->common.filterBuffer[0]);
+      if (nrof_channels == 2) {
+        COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(context->common.filterBuffer[1] + context->common.filterBufferLen - 72, context->common.filterBuffer[1]);
+      }
+      offset = context->common.filterBufferLen - 80;
+    } else {
+      offset -= 1 * 8;
+    }
+
+    for (ch = 0; ch < nrof_channels; ch++) {
+      DCT2_8(context->common.filterBuffer[ch] + offset, s);
+      SYNTH80(pcm + ch, context->common.filterBuffer[ch] + offset, pcmStrideShift);
+      s += 8;
     }
-    context->common.filterBufferOffset = offset;
+    pcm += (8 << pcmStrideShift);
+  }
+  context->common.filterBufferOffset = offset;
 }
 
-PRIVATE void OI_SBC_SynthFrame_4SB(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT blkstart, OI_UINT blkcount)
-{
-    OI_UINT blk;
-    OI_UINT ch;
-    OI_UINT nrof_channels = context->common.frameInfo.nrof_channels;
-    OI_UINT pcmStrideShift = context->common.pcmStride == 1 ? 0 : 1;
-    OI_UINT offset = context->common.filterBufferOffset;
-    OI_INT32 *s = context->common.subdata + 8 * nrof_channels * blkstart;
-    OI_UINT blkstop = blkstart + blkcount;
-
-    for (blk = blkstart; blk < blkstop; blk++) {
-        if (offset == 0) {
-            COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(context->common.filterBuffer[0] + context->common.filterBufferLen - 72, context->common.filterBuffer[0]);
-            if (nrof_channels == 2) {
-                COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(context->common.filterBuffer[1] + context->common.filterBufferLen - 72, context->common.filterBuffer[1]);
-            }
-            offset = context->common.filterBufferLen - 80;
-        } else {
-            offset -= 8;
-        }
-        for (ch = 0; ch < nrof_channels; ch++) {
-            cosineModulateSynth4(context->common.filterBuffer[ch] + offset, s);
-            SynthWindow40_int32_int32_symmetry_with_sum(pcm + ch,
-                                                        context->common.filterBuffer[ch] + offset,
-                                                        pcmStrideShift);
-            s += 4;
-        }
-        pcm += (4 << pcmStrideShift);
+PRIVATE void OI_SBC_SynthFrame_4SB(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT blkstart, OI_UINT blkcount) {
+  OI_UINT   blk;
+  OI_UINT   ch;
+  OI_UINT   nrof_channels  = context->common.frameInfo.nrof_channels;
+  OI_UINT   pcmStrideShift = context->common.pcmStride == 1 ? 0 : 1;
+  OI_UINT   offset         = context->common.filterBufferOffset;
+  OI_INT32 *s              = context->common.subdata + 8 * nrof_channels * blkstart;
+  OI_UINT   blkstop        = blkstart + blkcount;
+
+  for (blk = blkstart; blk < blkstop; blk++) {
+    if (offset == 0) {
+      COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(context->common.filterBuffer[0] + context->common.filterBufferLen - 72, context->common.filterBuffer[0]);
+      if (nrof_channels == 2) {
+        COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(context->common.filterBuffer[1] + context->common.filterBufferLen - 72, context->common.filterBuffer[1]);
+      }
+      offset = context->common.filterBufferLen - 80;
+    } else {
+      offset -= 8;
+    }
+    for (ch = 0; ch < nrof_channels; ch++) {
+      cosineModulateSynth4(context->common.filterBuffer[ch] + offset, s);
+      SynthWindow40_int32_int32_symmetry_with_sum(pcm + ch, context->common.filterBuffer[ch] + offset, pcmStrideShift);
+      s += 4;
     }
-    context->common.filterBufferOffset = offset;
+    pcm += (4 << pcmStrideShift);
+  }
+  context->common.filterBufferOffset = offset;
 }
 
 #ifdef SBC_ENHANCED
 
-PRIVATE void OI_SBC_SynthFrame_Enhanced(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT blkstart, OI_UINT blkcount)
-{
-    OI_UINT blk;
-    OI_UINT ch;
-    OI_UINT nrof_channels = context->common.frameInfo.nrof_channels;
-    OI_UINT pcmStrideShift = context->common.pcmStride == 1 ? 0 : 1;
-    OI_UINT offset = context->common.filterBufferOffset;
-    OI_INT32 *s = context->common.subdata + 8 * nrof_channels * blkstart;
-    OI_UINT blkstop = blkstart + blkcount;
-
-    for (blk = blkstart; blk < blkstop; blk++) {
-        if (offset == 0) {
-            COPY_BACKWARD_32BIT_ALIGNED_104_HALFWORDS(context->common.filterBuffer[0] + context->common.filterBufferLen - 104, context->common.filterBuffer[0]);
-            if (nrof_channels == 2) {
-                COPY_BACKWARD_32BIT_ALIGNED_104_HALFWORDS(context->common.filterBuffer[1] + context->common.filterBufferLen - 104, context->common.filterBuffer[1]);
-            }
-            offset = context->common.filterBufferLen - 112;
-        } else {
-            offset -= 8;
-        }
-        for (ch = 0; ch < nrof_channels; ++ch) {
-            DCT2_8(context->common.filterBuffer[ch] + offset, s);
-            SYNTH112(pcm + ch, context->common.filterBuffer[ch] + offset, pcmStrideShift);
-            s += 8;
-        }
-        pcm += (8 << pcmStrideShift);
+PRIVATE void OI_SBC_SynthFrame_Enhanced(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT blkstart, OI_UINT blkcount) {
+  OI_UINT   blk;
+  OI_UINT   ch;
+  OI_UINT   nrof_channels  = context->common.frameInfo.nrof_channels;
+  OI_UINT   pcmStrideShift = context->common.pcmStride == 1 ? 0 : 1;
+  OI_UINT   offset         = context->common.filterBufferOffset;
+  OI_INT32 *s              = context->common.subdata + 8 * nrof_channels * blkstart;
+  OI_UINT   blkstop        = blkstart + blkcount;
+
+  for (blk = blkstart; blk < blkstop; blk++) {
+    if (offset == 0) {
+      COPY_BACKWARD_32BIT_ALIGNED_104_HALFWORDS(context->common.filterBuffer[0] + context->common.filterBufferLen - 104, context->common.filterBuffer[0]);
+      if (nrof_channels == 2) {
+        COPY_BACKWARD_32BIT_ALIGNED_104_HALFWORDS(context->common.filterBuffer[1] + context->common.filterBufferLen - 104, context->common.filterBuffer[1]);
+      }
+      offset = context->common.filterBufferLen - 112;
+    } else {
+      offset -= 8;
+    }
+    for (ch = 0; ch < nrof_channels; ++ch) {
+      DCT2_8(context->common.filterBuffer[ch] + offset, s);
+      SYNTH112(pcm + ch, context->common.filterBuffer[ch] + offset, pcmStrideShift);
+      s += 8;
     }
-    context->common.filterBufferOffset = offset;
+    pcm += (8 << pcmStrideShift);
+  }
+  context->common.filterBufferOffset = offset;
 }
 
 static const SYNTH_FRAME SynthFrameEnhanced[] = {
@@ -381,85 +375,83 @@ static const SYNTH_FRAME SynthFrame4SB[] = {
     OI_SBC_SynthFrame_4SB  /* stereo */
 };
 
-PRIVATE void OI_SBC_SynthFrame(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT start_block, OI_UINT nrof_blocks)
-{
-    OI_UINT nrof_subbands = context->common.frameInfo.nrof_subbands;
-    OI_UINT nrof_channels = context->common.frameInfo.nrof_channels;
+PRIVATE void OI_SBC_SynthFrame(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT start_block, OI_UINT nrof_blocks) {
+  OI_UINT nrof_subbands = context->common.frameInfo.nrof_subbands;
+  OI_UINT nrof_channels = context->common.frameInfo.nrof_channels;
 
-    OI_ASSERT(nrof_subbands == 4 || nrof_subbands == 8);
-    if (nrof_subbands == 4) {
-        SynthFrame4SB[nrof_channels](context, pcm, start_block, nrof_blocks);
+  OI_ASSERT(nrof_subbands == 4 || nrof_subbands == 8);
+  if (nrof_subbands == 4) {
+    SynthFrame4SB[nrof_channels](context, pcm, start_block, nrof_blocks);
 #ifdef SBC_ENHANCED
-    } else if (context->common.frameInfo.enhanced) {
-        SynthFrameEnhanced[nrof_channels](context, pcm, start_block, nrof_blocks);
+  } else if (context->common.frameInfo.enhanced) {
+    SynthFrameEnhanced[nrof_channels](context, pcm, start_block, nrof_blocks);
 #endif /* SBC_ENHANCED */
-    } else {
-        SynthFrame8SB[nrof_channels](context, pcm, start_block, nrof_blocks);
-    }
+  } else {
+    SynthFrame8SB[nrof_channels](context, pcm, start_block, nrof_blocks);
+  }
 }
 
-void SynthWindow40_int32_int32_symmetry_with_sum(OI_INT16 *pcm, SBC_BUFFER_T buffer[80], OI_UINT strideShift)
-{
-    OI_INT32 pa;
-    OI_INT32 pb;
-
-    /* These values should be zero, since out[2] of the 4-band cosine modulation
-     * is always zero. */
-    OI_ASSERT(buffer[2] == 0);
-    OI_ASSERT(buffer[10] == 0);
-    OI_ASSERT(buffer[18] == 0);
-    OI_ASSERT(buffer[26] == 0);
-    OI_ASSERT(buffer[34] == 0);
-    OI_ASSERT(buffer[42] == 0);
-    OI_ASSERT(buffer[50] == 0);
-    OI_ASSERT(buffer[58] == 0);
-    OI_ASSERT(buffer[66] == 0);
-    OI_ASSERT(buffer[74] == 0);
-
-    pa = dec_window_4[4] * (buffer[12] + buffer[76]);
-    pa += dec_window_4[8] * (buffer[16] - buffer[64]);
-    pa += dec_window_4[12] * (buffer[28] + buffer[60]);
-    pa += dec_window_4[16] * (buffer[32] - buffer[48]);
-    pa += dec_window_4[20] * buffer[44];
-    pa = SCALE(-pa, 15);
-    CLIP_INT16(pa);
-    pcm[0 << strideShift] = (OI_INT16)pa;
-
-    pa = dec_window_4[1] * buffer[1];
-    pb = dec_window_4[1] * buffer[79];
-    pb += dec_window_4[3] * buffer[3];
-    pa += dec_window_4[3] * buffer[77];
-    pa += dec_window_4[5] * buffer[13];
-    pb += dec_window_4[5] * buffer[67];
-    pb += dec_window_4[7] * buffer[15];
-    pa += dec_window_4[7] * buffer[65];
-    pa += dec_window_4[9] * buffer[17];
-    pb += dec_window_4[9] * buffer[63];
-    pb += dec_window_4[11] * buffer[19];
-    pa += dec_window_4[11] * buffer[61];
-    pa += dec_window_4[13] * buffer[29];
-    pb += dec_window_4[13] * buffer[51];
-    pb += dec_window_4[15] * buffer[31];
-    pa += dec_window_4[15] * buffer[49];
-    pa += dec_window_4[17] * buffer[33];
-    pb += dec_window_4[17] * buffer[47];
-    pb += dec_window_4[19] * buffer[35];
-    pa += dec_window_4[19] * buffer[45];
-    pa = SCALE(-pa, 15);
-    CLIP_INT16(pa);
-    pcm[1 << strideShift] = (OI_INT16)(pa);
-    pb = SCALE(-pb, 15);
-    CLIP_INT16(pb);
-    pcm[3 << strideShift] = (OI_INT16)(pb);
-
-    pa = dec_window_4[2] * (/*buffer[ 2] + */ buffer[78]);   /* buffer[ 2] is always zero */
-    pa += dec_window_4[6] * (buffer[14] /* + buffer[66]*/);  /* buffer[66] is always zero */
-    pa += dec_window_4[10] * (/*buffer[18] + */ buffer[62]); /* buffer[18] is always zero */
-    pa += dec_window_4[14] * (buffer[30] /* + buffer[50]*/); /* buffer[50] is always zero */
-    pa += dec_window_4[18] * (/*buffer[34] + */ buffer[46]); /* buffer[34] is always zero */
-    pa = SCALE(-pa, 15);
-    CLIP_INT16(pa);
-    pcm[2 << strideShift] = (OI_INT16)(pa);
+void SynthWindow40_int32_int32_symmetry_with_sum(OI_INT16 *pcm, SBC_BUFFER_T buffer[80], OI_UINT strideShift) {
+  OI_INT32 pa;
+  OI_INT32 pb;
+
+  /* These values should be zero, since out[2] of the 4-band cosine modulation
+   * is always zero. */
+  OI_ASSERT(buffer[2] == 0);
+  OI_ASSERT(buffer[10] == 0);
+  OI_ASSERT(buffer[18] == 0);
+  OI_ASSERT(buffer[26] == 0);
+  OI_ASSERT(buffer[34] == 0);
+  OI_ASSERT(buffer[42] == 0);
+  OI_ASSERT(buffer[50] == 0);
+  OI_ASSERT(buffer[58] == 0);
+  OI_ASSERT(buffer[66] == 0);
+  OI_ASSERT(buffer[74] == 0);
+
+  pa = dec_window_4[4] * (buffer[12] + buffer[76]);
+  pa += dec_window_4[8] * (buffer[16] - buffer[64]);
+  pa += dec_window_4[12] * (buffer[28] + buffer[60]);
+  pa += dec_window_4[16] * (buffer[32] - buffer[48]);
+  pa += dec_window_4[20] * buffer[44];
+  pa = SCALE(-pa, 15);
+  CLIP_INT16(pa);
+  pcm[0 << strideShift] = (OI_INT16)pa;
+
+  pa = dec_window_4[1] * buffer[1];
+  pb = dec_window_4[1] * buffer[79];
+  pb += dec_window_4[3] * buffer[3];
+  pa += dec_window_4[3] * buffer[77];
+  pa += dec_window_4[5] * buffer[13];
+  pb += dec_window_4[5] * buffer[67];
+  pb += dec_window_4[7] * buffer[15];
+  pa += dec_window_4[7] * buffer[65];
+  pa += dec_window_4[9] * buffer[17];
+  pb += dec_window_4[9] * buffer[63];
+  pb += dec_window_4[11] * buffer[19];
+  pa += dec_window_4[11] * buffer[61];
+  pa += dec_window_4[13] * buffer[29];
+  pb += dec_window_4[13] * buffer[51];
+  pb += dec_window_4[15] * buffer[31];
+  pa += dec_window_4[15] * buffer[49];
+  pa += dec_window_4[17] * buffer[33];
+  pb += dec_window_4[17] * buffer[47];
+  pb += dec_window_4[19] * buffer[35];
+  pa += dec_window_4[19] * buffer[45];
+  pa = SCALE(-pa, 15);
+  CLIP_INT16(pa);
+  pcm[1 << strideShift] = (OI_INT16)(pa);
+  pb                    = SCALE(-pb, 15);
+  CLIP_INT16(pb);
+  pcm[3 << strideShift] = (OI_INT16)(pb);
+
+  pa = dec_window_4[2] * (/*buffer[ 2] + */ buffer[78]);   /* buffer[ 2] is always zero */
+  pa += dec_window_4[6] * (buffer[14] /* + buffer[66]*/);  /* buffer[66] is always zero */
+  pa += dec_window_4[10] * (/*buffer[18] + */ buffer[62]); /* buffer[18] is always zero */
+  pa += dec_window_4[14] * (buffer[30] /* + buffer[50]*/); /* buffer[50] is always zero */
+  pa += dec_window_4[18] * (/*buffer[34] + */ buffer[46]); /* buffer[34] is always zero */
+  pa = SCALE(-pa, 15);
+  CLIP_INT16(pa);
+  pcm[2 << strideShift] = (OI_INT16)(pa);
 }
 
 /**
@@ -487,35 +479,34 @@ void SynthWindow40_int32_int32_symmetry_with_sum(OI_INT16 *pcm, SBC_BUFFER_T buf
   algebra system, manually converted to fixed-point arithmetic. S4 can be
   implemented using only assignment and negation.
   */
-PRIVATE void cosineModulateSynth4(SBC_BUFFER_T *RESTRICT out, OI_INT32 const *RESTRICT in)
-{
-    OI_INT32 f0, f1, f2, f3, f4, f7, f8, f9, f10;
-    OI_INT32 y0, y1, y2, y3;
-
-    f0 = (in[0] - in[3]);
-    f1 = (in[0] + in[3]);
-    f2 = (in[1] - in[2]);
-    f3 = (in[1] + in[2]);
-
-    f4 = f1 - f3;
-
-    y0 = -SCALE(f1 + f3, DCT_SHIFT);
-    y2 = -SCALE(LONG_MULT_DCT(DCTII_4_K06_FIX, f4), DCT_SHIFT);
-    f7 = f0 + f2;
-    f8 = LONG_MULT_DCT(DCTII_4_K08_FIX, f0);
-    f9 = LONG_MULT_DCT(DCTII_4_K09_FIX, f7);
-    f10 = LONG_MULT_DCT(DCTII_4_K10_FIX, f2);
-    y3 = -SCALE(f8 + f9, DCT_SHIFT);
-    y1 = -SCALE(f10 - f9, DCT_SHIFT);
-
-    out[0] = (OI_INT16)-y2;
-    out[1] = (OI_INT16)-y3;
-    out[2] = (OI_INT16)0;
-    out[3] = (OI_INT16)y3;
-    out[4] = (OI_INT16)y2;
-    out[5] = (OI_INT16)y1;
-    out[6] = (OI_INT16)y0;
-    out[7] = (OI_INT16)y1;
+PRIVATE void cosineModulateSynth4(SBC_BUFFER_T *RESTRICT out, OI_INT32 const *RESTRICT in) {
+  OI_INT32 f0, f1, f2, f3, f4, f7, f8, f9, f10;
+  OI_INT32 y0, y1, y2, y3;
+
+  f0 = (in[0] - in[3]);
+  f1 = (in[0] + in[3]);
+  f2 = (in[1] - in[2]);
+  f3 = (in[1] + in[2]);
+
+  f4 = f1 - f3;
+
+  y0  = -SCALE(f1 + f3, DCT_SHIFT);
+  y2  = -SCALE(LONG_MULT_DCT(DCTII_4_K06_FIX, f4), DCT_SHIFT);
+  f7  = f0 + f2;
+  f8  = LONG_MULT_DCT(DCTII_4_K08_FIX, f0);
+  f9  = LONG_MULT_DCT(DCTII_4_K09_FIX, f7);
+  f10 = LONG_MULT_DCT(DCTII_4_K10_FIX, f2);
+  y3  = -SCALE(f8 + f9, DCT_SHIFT);
+  y1  = -SCALE(f10 - f9, DCT_SHIFT);
+
+  out[0] = (OI_INT16)-y2;
+  out[1] = (OI_INT16)-y3;
+  out[2] = (OI_INT16)0;
+  out[3] = (OI_INT16)y3;
+  out[4] = (OI_INT16)y2;
+  out[5] = (OI_INT16)y1;
+  out[6] = (OI_INT16)y0;
+  out[7] = (OI_INT16)y1;
 }
 
 /**
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_analysis.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_analysis.c
index 0a548ab8b3..bc03d6900c 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_analysis.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_analysis.c
@@ -22,11 +22,11 @@
  *  stream.
  *
  ******************************************************************************/
+#include "sbc_enc_func_declare.h"
+#include "sbc_encoder.h"
 #include 
 #include 
-#include "sbc_encoder.h"
-#include "sbc_enc_func_declare.h"
-//#include "osi/allocator.h"
+// #include "osi/allocator.h"
 /*#include */
 #if defined(SBC_ENC_INCLUDED)
 
@@ -160,97 +160,96 @@
 #pragma arm section zidata = "sbc_s32_analysis_section"
 #endif
 #if BT_BLE_DYNAMIC_ENV_MEMORY == FALSE
-static SINT32 s32DCTY[16] = { 0 };
-static SINT32 s32X[ENC_VX_BUFFER_SIZE / 2];
+static SINT32  s32DCTY[16] = {0};
+static SINT32  s32X[ENC_VX_BUFFER_SIZE / 2];
 static SINT16 *s16X = (SINT16 *)s32X; /* s16X must be 32 bits aligned cf  SHIFTUP_X8_2*/
 #else
 static SINT32 *s32DCTY;
 static SINT32 *s32X;
 static SINT16 *s16X; /* s16X must be 32 bits aligned cf  SHIFTUP_X8_2*/
-#endif //BT_BLE_DYNAMIC_ENV_MEMORY == FALSE
+#endif // BT_BLE_DYNAMIC_ENV_MEMORY == FALSE
 
 #if (SBC_USE_ARM_PRAGMA == TRUE)
 #pragma arm section zidata
 #endif
 
 /* This macro is for 4 subbands */
-#define SHIFTUP_X4                                          \
-    {                                                       \
-        ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 38); \
-        for (i = 0; i < 9; i++) {                           \
-            *ps32X = *(ps32X - 2 - (ShiftCounter >> 1));    \
-            ps32X--;                                        \
-            *ps32X = *(ps32X - 2 - (ShiftCounter >> 1));    \
-            ps32X--;                                        \
-        }                                                   \
-    }
-#define SHIFTUP_X4_2                                                \
-    {                                                               \
-        ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 38);         \
-        ps32X2 = (SINT32 *)(s16X + (EncMaxShiftCounter << 1) + 78); \
-        for (i = 0; i < 9; i++) {                                   \
-            *ps32X = *(ps32X - 2 - (ShiftCounter >> 1));            \
-            *(ps32X2) = *(ps32X2 - 2 - (ShiftCounter >> 1));        \
-            ps32X--;                                                \
-            ps32X2--;                                               \
-            *ps32X = *(ps32X - 2 - (ShiftCounter >> 1));            \
-            *(ps32X2) = *(ps32X2 - 2 - (ShiftCounter >> 1));        \
-            ps32X--;                                                \
-            ps32X2--;                                               \
-        }                                                           \
-    }
+#define SHIFTUP_X4                                      \
+  {                                                     \
+    ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 38); \
+    for (i = 0; i < 9; i++) {                           \
+      *ps32X = *(ps32X - 2 - (ShiftCounter >> 1));      \
+      ps32X--;                                          \
+      *ps32X = *(ps32X - 2 - (ShiftCounter >> 1));      \
+      ps32X--;                                          \
+    }                                                   \
+  }
+#define SHIFTUP_X4_2                                            \
+  {                                                             \
+    ps32X  = (SINT32 *)(s16X + EncMaxShiftCounter + 38);        \
+    ps32X2 = (SINT32 *)(s16X + (EncMaxShiftCounter << 1) + 78); \
+    for (i = 0; i < 9; i++) {                                   \
+      *ps32X    = *(ps32X - 2 - (ShiftCounter >> 1));           \
+      *(ps32X2) = *(ps32X2 - 2 - (ShiftCounter >> 1));          \
+      ps32X--;                                                  \
+      ps32X2--;                                                 \
+      *ps32X    = *(ps32X - 2 - (ShiftCounter >> 1));           \
+      *(ps32X2) = *(ps32X2 - 2 - (ShiftCounter >> 1));          \
+      ps32X--;                                                  \
+      ps32X2--;                                                 \
+    }                                                           \
+  }
 
 /* This macro is for 8 subbands */
-#define SHIFTUP_X8                                          \
-    {                                                       \
-        ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 78); \
-        for (i = 0; i < 9; i++) {                           \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));    \
-            ps32X--;                                        \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));    \
-            ps32X--;                                        \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));    \
-            ps32X--;                                        \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));    \
-            ps32X--;                                        \
-        }                                                   \
-    }
-#define SHIFTUP_X8_2                                                 \
-    {                                                                \
-        ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 78);          \
-        ps32X2 = (SINT32 *)(s16X + (EncMaxShiftCounter << 1) + 158); \
-        for (i = 0; i < 9; i++) {                                    \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));             \
-            *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1));         \
-            ps32X--;                                                 \
-            ps32X2--;                                                \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));             \
-            *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1));         \
-            ps32X--;                                                 \
-            ps32X2--;                                                \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));             \
-            *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1));         \
-            ps32X--;                                                 \
-            ps32X2--;                                                \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));             \
-            *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1));         \
-            ps32X--;                                                 \
-            ps32X2--;                                                \
-        }                                                            \
-    }
+#define SHIFTUP_X8                                      \
+  {                                                     \
+    ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 78); \
+    for (i = 0; i < 9; i++) {                           \
+      *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));      \
+      ps32X--;                                          \
+      *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));      \
+      ps32X--;                                          \
+      *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));      \
+      ps32X--;                                          \
+      *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));      \
+      ps32X--;                                          \
+    }                                                   \
+  }
+#define SHIFTUP_X8_2                                             \
+  {                                                              \
+    ps32X  = (SINT32 *)(s16X + EncMaxShiftCounter + 78);         \
+    ps32X2 = (SINT32 *)(s16X + (EncMaxShiftCounter << 1) + 158); \
+    for (i = 0; i < 9; i++) {                                    \
+      *ps32X    = *(ps32X - 4 - (ShiftCounter >> 1));            \
+      *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1));           \
+      ps32X--;                                                   \
+      ps32X2--;                                                  \
+      *ps32X    = *(ps32X - 4 - (ShiftCounter >> 1));            \
+      *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1));           \
+      ps32X--;                                                   \
+      ps32X2--;                                                  \
+      *ps32X    = *(ps32X - 4 - (ShiftCounter >> 1));            \
+      *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1));           \
+      ps32X--;                                                   \
+      ps32X2--;                                                  \
+      *ps32X    = *(ps32X - 4 - (ShiftCounter >> 1));            \
+      *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1));           \
+      ps32X--;                                                   \
+      ps32X2--;                                                  \
+    }                                                            \
+  }
 
 #if (SBC_ARM_ASM_OPT == TRUE)
-#define WINDOW_ACCU_8_0 \
-    {                   \
-        __asm {\
+#define WINDOW_ACCU_8_0                                                                                                                                                             \
+  {                                                                                                                                                                                 \
+    __asm {\
         MUL s32Hi,WIND_8_SUBBANDS_0_1,(s16X[ChOffset+16]-s16X[ChOffset+64]);\
         MLA s32Hi,WIND_8_SUBBANDS_0_2,(s16X[ChOffset+32]-s16X[ChOffset+48]),s32Hi;\
-        MOV s32DCTY[0],s32Hi;        \
-        }               \
-    }
+        MOV s32DCTY[0],s32Hi; } \
+  }
 #define WINDOW_ACCU_8_1_15 \
-    {                      \
-        __asm {\
+  {                        \
+    __asm {\
         MUL s32Hi,WIND_8_SUBBANDS_1_0,s16X[ChOffset+1];\
         MUL s32Hi2,WIND_8_SUBBANDS_1_0,s16X[ChOffset+64+15];\
         MLA s32Hi,WIND_8_SUBBANDS_1_1,s16X[ChOffset+16+1],s32Hi;\
@@ -262,12 +261,12 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf  SHIFTUP_X8_2*/
         MLA s32Hi,WIND_8_SUBBANDS_1_4,s16X[ChOffset+64+1],s32Hi;\
         MLA s32Hi2,WIND_8_SUBBANDS_1_4,s16X[ChOffset+15],s32Hi2;\
         MOV s32DCTY[1],s32Hi;\
-        MOV s32DCTY[15],s32Hi2;           \
-        }                  \
-    }
+        MOV s32DCTY[15],s32Hi2;               \
+    }                      \
+  }
 #define WINDOW_ACCU_8_2_14 \
-    {                      \
-        __asm {\
+  {                        \
+    __asm {\
         MUL s32Hi,WIND_8_SUBBANDS_2_0,s16X[ChOffset+2];\
         MUL s32Hi2,WIND_8_SUBBANDS_2_0,s16X[ChOffset+64+14];\
         MLA s32Hi,WIND_8_SUBBANDS_2_1,s16X[ChOffset+16+2],s32Hi;\
@@ -279,12 +278,12 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf  SHIFTUP_X8_2*/
         MLA s32Hi,WIND_8_SUBBANDS_2_4,s16X[ChOffset+64+2],s32Hi;\
         MLA s32Hi2,WIND_8_SUBBANDS_2_4,s16X[ChOffset+14],s32Hi2;\
         MOV s32DCTY[2],s32Hi;\
-        MOV s32DCTY[14],s32Hi2;           \
-        }                  \
-    }
+        MOV s32DCTY[14],s32Hi2;               \
+    }                      \
+  }
 #define WINDOW_ACCU_8_3_13 \
-    {                      \
-        __asm {\
+  {                        \
+    __asm {\
         MUL s32Hi,WIND_8_SUBBANDS_3_0,s16X[ChOffset+3];\
         MUL s32Hi2,WIND_8_SUBBANDS_3_0,s16X[ChOffset+64+13];\
         MLA s32Hi,WIND_8_SUBBANDS_3_1,s16X[ChOffset+16+3],s32Hi;\
@@ -296,12 +295,12 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf  SHIFTUP_X8_2*/
         MLA s32Hi,WIND_8_SUBBANDS_3_4,s16X[ChOffset+64+3],s32Hi;\
         MLA s32Hi2,WIND_8_SUBBANDS_3_4,s16X[ChOffset+13],s32Hi2;\
         MOV s32DCTY[3],s32Hi;\
-        MOV s32DCTY[13],s32Hi2;           \
-        }                  \
-    }
+        MOV s32DCTY[13],s32Hi2;               \
+    }                      \
+  }
 #define WINDOW_ACCU_8_4_12 \
-    {                      \
-        __asm {\
+  {                        \
+    __asm {\
         MUL s32Hi,WIND_8_SUBBANDS_4_0,s16X[ChOffset+4];\
         MUL s32Hi2,WIND_8_SUBBANDS_4_0,s16X[ChOffset+64+12];\
         MLA s32Hi,WIND_8_SUBBANDS_4_1,s16X[ChOffset+16+4],s32Hi;\
@@ -313,12 +312,12 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf  SHIFTUP_X8_2*/
         MLA s32Hi,WIND_8_SUBBANDS_4_4,s16X[ChOffset+64+4],s32Hi;\
         MLA s32Hi2,WIND_8_SUBBANDS_4_4,s16X[ChOffset+12],s32Hi2;\
         MOV s32DCTY[4],s32Hi;\
-        MOV s32DCTY[12],s32Hi2;           \
-        }                  \
-    }
+        MOV s32DCTY[12],s32Hi2;               \
+    }                      \
+  }
 #define WINDOW_ACCU_8_5_11 \
-    {                      \
-        __asm {\
+  {                        \
+    __asm {\
         MUL s32Hi,WIND_8_SUBBANDS_5_0,s16X[ChOffset+5];\
         MUL s32Hi2,WIND_8_SUBBANDS_5_0,s16X[ChOffset+64+11];\
         MLA s32Hi,WIND_8_SUBBANDS_5_1,s16X[ChOffset+16+5],s32Hi;\
@@ -330,12 +329,12 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf  SHIFTUP_X8_2*/
         MLA s32Hi,WIND_8_SUBBANDS_5_4,s16X[ChOffset+64+5],s32Hi;\
         MLA s32Hi2,WIND_8_SUBBANDS_5_4,s16X[ChOffset+11],s32Hi2;\
         MOV s32DCTY[5],s32Hi;\
-        MOV s32DCTY[11],s32Hi2;           \
-        }                  \
-    }
+        MOV s32DCTY[11],s32Hi2;               \
+    }                      \
+  }
 #define WINDOW_ACCU_8_6_10 \
-    {                      \
-        __asm {\
+  {                        \
+    __asm {\
         MUL s32Hi,WIND_8_SUBBANDS_6_0,s16X[ChOffset+6];\
         MUL s32Hi2,WIND_8_SUBBANDS_6_0,s16X[ChOffset+64+10];\
         MLA s32Hi,WIND_8_SUBBANDS_6_1,s16X[ChOffset+16+6],s32Hi;\
@@ -347,12 +346,12 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf  SHIFTUP_X8_2*/
         MLA s32Hi,WIND_8_SUBBANDS_6_4,s16X[ChOffset+64+6],s32Hi;\
         MLA s32Hi2,WIND_8_SUBBANDS_6_4,s16X[ChOffset+10],s32Hi2;\
         MOV s32DCTY[6],s32Hi;\
-        MOV s32DCTY[10],s32Hi2;           \
-        }                  \
-    }
+        MOV s32DCTY[10],s32Hi2;               \
+    }                      \
+  }
 #define WINDOW_ACCU_8_7_9 \
-    {                     \
-        __asm {\
+  {                       \
+    __asm {\
         MUL s32Hi,WIND_8_SUBBANDS_7_0,s16X[ChOffset+7];\
         MUL s32Hi2,WIND_8_SUBBANDS_7_0,s16X[ChOffset+64+9];\
         MLA s32Hi,WIND_8_SUBBANDS_7_1,s16X[ChOffset+16+7],s32Hi;\
@@ -364,29 +363,28 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf  SHIFTUP_X8_2*/
         MLA s32Hi,WIND_8_SUBBANDS_7_4,s16X[ChOffset+64+7],s32Hi;\
         MLA s32Hi2,WIND_8_SUBBANDS_7_4,s16X[ChOffset+9],s32Hi2;\
         MOV s32DCTY[7],s32Hi;\
-        MOV s32DCTY[9],s32Hi2;          \
-        }                 \
-    }
+        MOV s32DCTY[9],s32Hi2;              \
+    }                     \
+  }
 #define WINDOW_ACCU_8_8 \
-    {                   \
-        __asm {\
+  {                     \
+    __asm {\
         MUL s32Hi,WIND_8_SUBBANDS_8_0,(s16X[ChOffset+8]+s16X[ChOffset+8+64]);\
         MLA s32Hi,WIND_8_SUBBANDS_8_1,(s16X[ChOffset+8+16]+s16X[ChOffset+8+64]),s32Hi;\
         MLA s32Hi,WIND_8_SUBBANDS_8_2,s16X[ChOffset+8+32],s32Hi;\
-        MOV s32DCTY[8],s32Hi;        \
-        }               \
-    }
-#define WINDOW_ACCU_4_0 \
-    {                   \
-        __asm {\
+        MOV s32DCTY[8],s32Hi;            \
+    }                   \
+  }
+#define WINDOW_ACCU_4_0                                                                                                                                                            \
+  {                                                                                                                                                                                \
+    __asm {\
         MUL s32Hi,WIND_4_SUBBANDS_0_1,(s16X[ChOffset+8]-s16X[ChOffset+32]);\
         MLA s32Hi,WIND_4_SUBBANDS_0_2,(s16X[ChOffset+16]-s16X[ChOffset+24]),s32Hi;\
-        MOV s32DCTY[0],s32Hi;        \
-        }               \
-    }
+        MOV s32DCTY[0],s32Hi; } \
+  }
 #define WINDOW_ACCU_4_1_7 \
-    {                     \
-        __asm {\
+  {                       \
+    __asm {\
         MUL s32Hi,WIND_4_SUBBANDS_1_0,s16X[ChOffset+1];\
         MUL s32Hi2,WIND_4_SUBBANDS_1_0,s16X[ChOffset+32+7];\
         MLA s32Hi,WIND_4_SUBBANDS_1_1,s16X[ChOffset+8+1],s32Hi;\
@@ -398,12 +396,12 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf  SHIFTUP_X8_2*/
         MLA s32Hi,WIND_4_SUBBANDS_1_4,s16X[ChOffset+32+1],s32Hi;\
         MLA s32Hi2,WIND_4_SUBBANDS_1_4,s16X[ChOffset+7],s32Hi2;\
         MOV s32DCTY[1],s32Hi;\
-        MOV s32DCTY[7],s32Hi2;          \
-        }                 \
-    }
+        MOV s32DCTY[7],s32Hi2;              \
+    }                     \
+  }
 #define WINDOW_ACCU_4_2_6 \
-    {                     \
-        __asm {\
+  {                       \
+    __asm {\
         MUL s32Hi,WIND_4_SUBBANDS_2_0,s16X[ChOffset+2];\
         MUL s32Hi2,WIND_4_SUBBANDS_2_0,s16X[ChOffset+32+6];\
         MLA s32Hi,WIND_4_SUBBANDS_2_1,s16X[ChOffset+8+2],s32Hi;\
@@ -415,12 +413,12 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf  SHIFTUP_X8_2*/
         MLA s32Hi,WIND_4_SUBBANDS_2_4,s16X[ChOffset+32+2],s32Hi;\
         MLA s32Hi2,WIND_4_SUBBANDS_2_4,s16X[ChOffset+6],s32Hi2;\
         MOV s32DCTY[2],s32Hi;\
-        MOV s32DCTY[6],s32Hi2;          \
-        }                 \
-    }
+        MOV s32DCTY[6],s32Hi2;              \
+    }                     \
+  }
 #define WINDOW_ACCU_4_3_5 \
-    {                     \
-        __asm {\
+  {                       \
+    __asm {\
         MUL s32Hi,WIND_4_SUBBANDS_3_0,s16X[ChOffset+3];\
         MUL s32Hi2,WIND_4_SUBBANDS_3_0,s16X[ChOffset+32+5];\
         MLA s32Hi,WIND_4_SUBBANDS_3_1,s16X[ChOffset+8+3],s32Hi;\
@@ -432,729 +430,726 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf  SHIFTUP_X8_2*/
         MLA s32Hi,WIND_4_SUBBANDS_3_4,s16X[ChOffset+32+3],s32Hi;\
         MLA s32Hi2,WIND_4_SUBBANDS_3_4,s16X[ChOffset+5],s32Hi2;\
         MOV s32DCTY[3],s32Hi;\
-        MOV s32DCTY[5],s32Hi2;          \
-        }                 \
-    }
+        MOV s32DCTY[5],s32Hi2;              \
+    }                     \
+  }
 #define WINDOW_ACCU_4_4 \
-    {                   \
-        __asm {\
+  {                     \
+    __asm {\
         MUL s32Hi,WIND_4_SUBBANDS_4_0,(s16X[ChOffset+4]+s16X[ChOffset+4+32]);\
         MLA s32Hi,WIND_4_SUBBANDS_4_1,(s16X[ChOffset+4+8]+s16X[ChOffset+4+24]),s32Hi;\
         MLA s32Hi,WIND_4_SUBBANDS_4_2,s16X[ChOffset+4+16],s32Hi;\
-        MOV s32DCTY[4],s32Hi;        \
-        }               \
-    }
+        MOV s32DCTY[4],s32Hi;            \
+    }                   \
+  }
 
-#define WINDOW_PARTIAL_4   \
-    {                      \
-        WINDOW_ACCU_4_0;   \
-        WINDOW_ACCU_4_1_7; \
-        WINDOW_ACCU_4_2_6; \
-        WINDOW_ACCU_4_3_5; \
-        WINDOW_ACCU_4_4;   \
-    }
+#define WINDOW_PARTIAL_4 \
+  {                      \
+    WINDOW_ACCU_4_0;     \
+    WINDOW_ACCU_4_1_7;   \
+    WINDOW_ACCU_4_2_6;   \
+    WINDOW_ACCU_4_3_5;   \
+    WINDOW_ACCU_4_4;     \
+  }
 
-#define WINDOW_PARTIAL_8    \
-    {                       \
-        WINDOW_ACCU_8_0;    \
-        WINDOW_ACCU_8_1_15; \
-        WINDOW_ACCU_8_2_14; \
-        WINDOW_ACCU_8_3_13; \
-        WINDOW_ACCU_8_4_12; \
-        WINDOW_ACCU_8_5_11; \
-        WINDOW_ACCU_8_6_10; \
-        WINDOW_ACCU_8_7_9;  \
-        WINDOW_ACCU_8_8;    \
-    }
+#define WINDOW_PARTIAL_8 \
+  {                      \
+    WINDOW_ACCU_8_0;     \
+    WINDOW_ACCU_8_1_15;  \
+    WINDOW_ACCU_8_2_14;  \
+    WINDOW_ACCU_8_3_13;  \
+    WINDOW_ACCU_8_4_12;  \
+    WINDOW_ACCU_8_5_11;  \
+    WINDOW_ACCU_8_6_10;  \
+    WINDOW_ACCU_8_7_9;   \
+    WINDOW_ACCU_8_8;     \
+  }
 
 #else
 #if (SBC_IPAQ_OPT == TRUE)
 
 #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE)
-#define WINDOW_ACCU_8_0                                                                               \
-    {                                                                                                 \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_0_1 * (SINT64)(s16X[ChOffset + 16] - s16X[ChOffset + 64]);  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_0_2 * (SINT64)(s16X[ChOffset + 32] - s16X[ChOffset + 48]); \
-        s32DCTY[0] = (SINT32)(s64Temp >> 16);                                                         \
-    }
-#define WINDOW_ACCU_8_1_15                                                          \
-    {                                                                               \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 1];         \
-        s64Temp2 = (SINT64)WIND_8_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 64 + 15];  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 16 + 1];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 48 + 15]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 32 + 1];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 32 + 15]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 48 + 1];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 16 + 15]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 64 + 1];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 15];      \
-        s32DCTY[1] = (SINT32)(s64Temp >> 16);                                       \
-        s32DCTY[15] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_8_2_14                                                          \
-    {                                                                               \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 2];         \
-        s64Temp2 = (SINT64)WIND_8_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 64 + 14];  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 16 + 2];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 48 + 14]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 32 + 2];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 32 + 14]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 48 + 2];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 16 + 14]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 64 + 2];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 14];      \
-        s32DCTY[2] = (SINT32)(s64Temp >> 16);                                       \
-        s32DCTY[14] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_8_3_13                                                          \
-    {                                                                               \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 3];         \
-        s64Temp2 = (SINT64)WIND_8_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 64 + 13];  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 16 + 3];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 48 + 13]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 32 + 3];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 32 + 13]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 48 + 3];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 16 + 13]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 64 + 3];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 13];      \
-        s32DCTY[3] = (SINT32)(s64Temp >> 16);                                       \
-        s32DCTY[13] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_8_4_12                                                          \
-    {                                                                               \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_4_0 * (SINT64)s16X[ChOffset + 4];         \
-        s64Temp2 = (SINT64)WIND_8_SUBBANDS_4_0 * (SINT64)s16X[ChOffset + 64 + 12];  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_4_1 * (SINT64)s16X[ChOffset + 16 + 4];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_1 * (SINT64)s16X[ChOffset + 48 + 12]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_4_2 * (SINT64)s16X[ChOffset + 32 + 4];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_2 * (SINT64)s16X[ChOffset + 32 + 12]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_4_3 * (SINT64)s16X[ChOffset + 48 + 4];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_3 * (SINT64)s16X[ChOffset + 16 + 12]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_4_4 * (SINT64)s16X[ChOffset + 64 + 4];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_4 * (SINT64)s16X[ChOffset + 12];      \
-        s32DCTY[4] = (SINT32)(s64Temp >> 16);                                       \
-        s32DCTY[12] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_8_5_11                                                          \
-    {                                                                               \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_5_0 * (SINT64)s16X[ChOffset + 5];         \
-        s64Temp2 = (SINT64)WIND_8_SUBBANDS_5_0 * (SINT64)s16X[ChOffset + 64 + 11];  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_5_1 * (SINT64)s16X[ChOffset + 16 + 5];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_1 * (SINT64)s16X[ChOffset + 48 + 11]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_5_2 * (SINT64)s16X[ChOffset + 32 + 5];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_2 * (SINT64)s16X[ChOffset + 32 + 11]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_5_3 * (SINT64)s16X[ChOffset + 48 + 5];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_3 * (SINT64)s16X[ChOffset + 16 + 11]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_5_4 * (SINT64)s16X[ChOffset + 64 + 5];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_4 * (SINT64)s16X[ChOffset + 11];      \
-        s32DCTY[5] = (SINT32)(s64Temp >> 16);                                       \
-        s32DCTY[11] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_8_6_10                                                          \
-    {                                                                               \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_6_0 * (SINT64)s16X[ChOffset + 6];         \
-        s64Temp2 = (SINT64)WIND_8_SUBBANDS_6_0 * (SINT64)s16X[ChOffset + 64 + 10];  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_6_1 * (SINT64)s16X[ChOffset + 16 + 6];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_1 * (SINT64)s16X[ChOffset + 48 + 10]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_6_2 * (SINT64)s16X[ChOffset + 32 + 6];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_2 * (SINT64)s16X[ChOffset + 32 + 10]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_6_3 * (SINT64)s16X[ChOffset + 48 + 6];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_3 * (SINT64)s16X[ChOffset + 16 + 10]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_6_4 * (SINT64)s16X[ChOffset + 64 + 6];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_4 * (SINT64)s16X[ChOffset + 10];      \
-        s32DCTY[6] = (SINT32)(s64Temp >> 16);                                       \
-        s32DCTY[10] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_8_7_9                                                          \
-    {                                                                              \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_7_0 * (SINT64)s16X[ChOffset + 7];        \
-        s64Temp2 = (SINT64)WIND_8_SUBBANDS_7_0 * (SINT64)s16X[ChOffset + 64 + 9];  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_7_1 * (SINT64)s16X[ChOffset + 16 + 7];  \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_1 * (SINT64)s16X[ChOffset + 48 + 9]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_7_2 * (SINT64)s16X[ChOffset + 32 + 7];  \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_2 * (SINT64)s16X[ChOffset + 32 + 9]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_7_3 * (SINT64)s16X[ChOffset + 48 + 7];  \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_3 * (SINT64)s16X[ChOffset + 16 + 9]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_7_4 * (SINT64)s16X[ChOffset + 64 + 7];  \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_4 * (SINT64)s16X[ChOffset + 9];      \
-        s32DCTY[7] = (SINT32)(s64Temp >> 16);                                      \
-        s32DCTY[9] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_8_8                                                                                       \
-    {                                                                                                         \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_8_0 * (SINT64)(s16X[ChOffset + 8] + s16X[ChOffset + 64 + 8]);       \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_8_1 * (SINT64)(s16X[ChOffset + 16 + 8] + s16X[ChOffset + 48 + 8]); \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_8_2 * (SINT64)s16X[ChOffset + 32 + 8];                             \
-        s32DCTY[8] = (SINT32)(s64Temp >> 16);                                                                 \
-    }
-#define WINDOW_ACCU_4_0                                                                               \
-    {                                                                                                 \
-        s64Temp = (SINT64)WIND_4_SUBBANDS_0_1 * (SINT64)(s16X[ChOffset + 8] - s16X[ChOffset + 32]);   \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_0_2 * (SINT64)(s16X[ChOffset + 16] - s16X[ChOffset + 24]); \
-        s32DCTY[0] = (SINT32)(s64Temp >> 16);                                                         \
-    }
-#define WINDOW_ACCU_4_1_7                                                          \
-    {                                                                              \
-        s64Temp = (SINT64)WIND_4_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 1];        \
-        s64Temp2 = (SINT64)WIND_4_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 32 + 7];  \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 8 + 1];   \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 24 + 7]; \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 16 + 1];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 16 + 7]; \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 24 + 1];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 8 + 7];  \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 32 + 1];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 7];      \
-        s32DCTY[1] = (SINT32)(s64Temp >> 16);                                      \
-        s32DCTY[7] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_4_2_6                                                          \
-    {                                                                              \
-        s64Temp = (SINT64)WIND_4_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 2];        \
-        s64Temp2 = (SINT64)WIND_4_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 32 + 6];  \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 8 + 2];   \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 24 + 6]; \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 16 + 2];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 16 + 6]; \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 24 + 2];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 8 + 6];  \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 32 + 2];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 6];      \
-        s32DCTY[2] = (SINT32)(s64Temp >> 16);                                      \
-        s32DCTY[6] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_4_3_5                                                          \
-    {                                                                              \
-        s64Temp = (SINT64)WIND_4_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 3];        \
-        s64Temp2 = (SINT64)WIND_4_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 32 + 5];  \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 8 + 3];   \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 24 + 5]; \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 16 + 3];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 16 + 5]; \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 24 + 3];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 8 + 5];  \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 32 + 3];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 5];      \
-        s32DCTY[3] = (SINT32)(s64Temp >> 16);                                      \
-        s32DCTY[5] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
+#define WINDOW_ACCU_8_0                                                                           \
+  {                                                                                               \
+    s64Temp = (SINT64)WIND_8_SUBBANDS_0_1 * (SINT64)(s16X[ChOffset + 16] - s16X[ChOffset + 64]);  \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_0_2 * (SINT64)(s16X[ChOffset + 32] - s16X[ChOffset + 48]); \
+    s32DCTY[0] = (SINT32)(s64Temp >> 16);                                                         \
+  }
+#define WINDOW_ACCU_8_1_15                                                      \
+  {                                                                             \
+    s64Temp  = (SINT64)WIND_8_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 1];        \
+    s64Temp2 = (SINT64)WIND_8_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 64 + 15];  \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 16 + 1];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 48 + 15]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 32 + 1];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 32 + 15]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 48 + 1];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 16 + 15]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 64 + 1];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 15];      \
+    s32DCTY[1]  = (SINT32)(s64Temp >> 16);                                      \
+    s32DCTY[15] = (SINT32)(s64Temp2 >> 16);                                     \
+  }
+#define WINDOW_ACCU_8_2_14                                                      \
+  {                                                                             \
+    s64Temp  = (SINT64)WIND_8_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 2];        \
+    s64Temp2 = (SINT64)WIND_8_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 64 + 14];  \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 16 + 2];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 48 + 14]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 32 + 2];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 32 + 14]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 48 + 2];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 16 + 14]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 64 + 2];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 14];      \
+    s32DCTY[2]  = (SINT32)(s64Temp >> 16);                                      \
+    s32DCTY[14] = (SINT32)(s64Temp2 >> 16);                                     \
+  }
+#define WINDOW_ACCU_8_3_13                                                      \
+  {                                                                             \
+    s64Temp  = (SINT64)WIND_8_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 3];        \
+    s64Temp2 = (SINT64)WIND_8_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 64 + 13];  \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 16 + 3];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 48 + 13]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 32 + 3];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 32 + 13]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 48 + 3];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 16 + 13]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 64 + 3];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 13];      \
+    s32DCTY[3]  = (SINT32)(s64Temp >> 16);                                      \
+    s32DCTY[13] = (SINT32)(s64Temp2 >> 16);                                     \
+  }
+#define WINDOW_ACCU_8_4_12                                                      \
+  {                                                                             \
+    s64Temp  = (SINT64)WIND_8_SUBBANDS_4_0 * (SINT64)s16X[ChOffset + 4];        \
+    s64Temp2 = (SINT64)WIND_8_SUBBANDS_4_0 * (SINT64)s16X[ChOffset + 64 + 12];  \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_4_1 * (SINT64)s16X[ChOffset + 16 + 4];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_1 * (SINT64)s16X[ChOffset + 48 + 12]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_4_2 * (SINT64)s16X[ChOffset + 32 + 4];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_2 * (SINT64)s16X[ChOffset + 32 + 12]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_4_3 * (SINT64)s16X[ChOffset + 48 + 4];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_3 * (SINT64)s16X[ChOffset + 16 + 12]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_4_4 * (SINT64)s16X[ChOffset + 64 + 4];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_4 * (SINT64)s16X[ChOffset + 12];      \
+    s32DCTY[4]  = (SINT32)(s64Temp >> 16);                                      \
+    s32DCTY[12] = (SINT32)(s64Temp2 >> 16);                                     \
+  }
+#define WINDOW_ACCU_8_5_11                                                      \
+  {                                                                             \
+    s64Temp  = (SINT64)WIND_8_SUBBANDS_5_0 * (SINT64)s16X[ChOffset + 5];        \
+    s64Temp2 = (SINT64)WIND_8_SUBBANDS_5_0 * (SINT64)s16X[ChOffset + 64 + 11];  \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_5_1 * (SINT64)s16X[ChOffset + 16 + 5];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_1 * (SINT64)s16X[ChOffset + 48 + 11]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_5_2 * (SINT64)s16X[ChOffset + 32 + 5];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_2 * (SINT64)s16X[ChOffset + 32 + 11]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_5_3 * (SINT64)s16X[ChOffset + 48 + 5];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_3 * (SINT64)s16X[ChOffset + 16 + 11]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_5_4 * (SINT64)s16X[ChOffset + 64 + 5];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_4 * (SINT64)s16X[ChOffset + 11];      \
+    s32DCTY[5]  = (SINT32)(s64Temp >> 16);                                      \
+    s32DCTY[11] = (SINT32)(s64Temp2 >> 16);                                     \
+  }
+#define WINDOW_ACCU_8_6_10                                                      \
+  {                                                                             \
+    s64Temp  = (SINT64)WIND_8_SUBBANDS_6_0 * (SINT64)s16X[ChOffset + 6];        \
+    s64Temp2 = (SINT64)WIND_8_SUBBANDS_6_0 * (SINT64)s16X[ChOffset + 64 + 10];  \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_6_1 * (SINT64)s16X[ChOffset + 16 + 6];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_1 * (SINT64)s16X[ChOffset + 48 + 10]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_6_2 * (SINT64)s16X[ChOffset + 32 + 6];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_2 * (SINT64)s16X[ChOffset + 32 + 10]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_6_3 * (SINT64)s16X[ChOffset + 48 + 6];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_3 * (SINT64)s16X[ChOffset + 16 + 10]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_6_4 * (SINT64)s16X[ChOffset + 64 + 6];   \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_4 * (SINT64)s16X[ChOffset + 10];      \
+    s32DCTY[6]  = (SINT32)(s64Temp >> 16);                                      \
+    s32DCTY[10] = (SINT32)(s64Temp2 >> 16);                                     \
+  }
+#define WINDOW_ACCU_8_7_9                                                      \
+  {                                                                            \
+    s64Temp  = (SINT64)WIND_8_SUBBANDS_7_0 * (SINT64)s16X[ChOffset + 7];       \
+    s64Temp2 = (SINT64)WIND_8_SUBBANDS_7_0 * (SINT64)s16X[ChOffset + 64 + 9];  \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_7_1 * (SINT64)s16X[ChOffset + 16 + 7];  \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_1 * (SINT64)s16X[ChOffset + 48 + 9]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_7_2 * (SINT64)s16X[ChOffset + 32 + 7];  \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_2 * (SINT64)s16X[ChOffset + 32 + 9]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_7_3 * (SINT64)s16X[ChOffset + 48 + 7];  \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_3 * (SINT64)s16X[ChOffset + 16 + 9]; \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_7_4 * (SINT64)s16X[ChOffset + 64 + 7];  \
+    s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_4 * (SINT64)s16X[ChOffset + 9];      \
+    s32DCTY[7] = (SINT32)(s64Temp >> 16);                                      \
+    s32DCTY[9] = (SINT32)(s64Temp2 >> 16);                                     \
+  }
+#define WINDOW_ACCU_8_8                                                                                   \
+  {                                                                                                       \
+    s64Temp = (SINT64)WIND_8_SUBBANDS_8_0 * (SINT64)(s16X[ChOffset + 8] + s16X[ChOffset + 64 + 8]);       \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_8_1 * (SINT64)(s16X[ChOffset + 16 + 8] + s16X[ChOffset + 48 + 8]); \
+    s64Temp += (SINT64)WIND_8_SUBBANDS_8_2 * (SINT64)s16X[ChOffset + 32 + 8];                             \
+    s32DCTY[8] = (SINT32)(s64Temp >> 16);                                                                 \
+  }
+#define WINDOW_ACCU_4_0                                                                           \
+  {                                                                                               \
+    s64Temp = (SINT64)WIND_4_SUBBANDS_0_1 * (SINT64)(s16X[ChOffset + 8] - s16X[ChOffset + 32]);   \
+    s64Temp += (SINT64)WIND_4_SUBBANDS_0_2 * (SINT64)(s16X[ChOffset + 16] - s16X[ChOffset + 24]); \
+    s32DCTY[0] = (SINT32)(s64Temp >> 16);                                                         \
+  }
+#define WINDOW_ACCU_4_1_7                                                      \
+  {                                                                            \
+    s64Temp  = (SINT64)WIND_4_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 1];       \
+    s64Temp2 = (SINT64)WIND_4_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 32 + 7];  \
+    s64Temp += (SINT64)WIND_4_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 8 + 1];   \
+    s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 24 + 7]; \
+    s64Temp += (SINT64)WIND_4_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 16 + 1];  \
+    s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 16 + 7]; \
+    s64Temp += (SINT64)WIND_4_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 24 + 1];  \
+    s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 8 + 7];  \
+    s64Temp += (SINT64)WIND_4_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 32 + 1];  \
+    s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 7];      \
+    s32DCTY[1] = (SINT32)(s64Temp >> 16);                                      \
+    s32DCTY[7] = (SINT32)(s64Temp2 >> 16);                                     \
+  }
+#define WINDOW_ACCU_4_2_6                                                      \
+  {                                                                            \
+    s64Temp  = (SINT64)WIND_4_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 2];       \
+    s64Temp2 = (SINT64)WIND_4_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 32 + 6];  \
+    s64Temp += (SINT64)WIND_4_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 8 + 2];   \
+    s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 24 + 6]; \
+    s64Temp += (SINT64)WIND_4_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 16 + 2];  \
+    s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 16 + 6]; \
+    s64Temp += (SINT64)WIND_4_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 24 + 2];  \
+    s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 8 + 6];  \
+    s64Temp += (SINT64)WIND_4_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 32 + 2];  \
+    s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 6];      \
+    s32DCTY[2] = (SINT32)(s64Temp >> 16);                                      \
+    s32DCTY[6] = (SINT32)(s64Temp2 >> 16);                                     \
+  }
+#define WINDOW_ACCU_4_3_5                                                      \
+  {                                                                            \
+    s64Temp  = (SINT64)WIND_4_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 3];       \
+    s64Temp2 = (SINT64)WIND_4_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 32 + 5];  \
+    s64Temp += (SINT64)WIND_4_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 8 + 3];   \
+    s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 24 + 5]; \
+    s64Temp += (SINT64)WIND_4_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 16 + 3];  \
+    s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 16 + 5]; \
+    s64Temp += (SINT64)WIND_4_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 24 + 3];  \
+    s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 8 + 5];  \
+    s64Temp += (SINT64)WIND_4_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 32 + 3];  \
+    s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 5];      \
+    s32DCTY[3] = (SINT32)(s64Temp >> 16);                                      \
+    s32DCTY[5] = (SINT32)(s64Temp2 >> 16);                                     \
+  }
 
-#define WINDOW_ACCU_4_4                                                                                      \
-    {                                                                                                        \
-        s64Temp = (SINT64)WIND_4_SUBBANDS_4_0 * (SINT64)(s16X[ChOffset + 4] + s16X[ChOffset + 4 + 32]);      \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_4_1 * (SINT64)(s16X[ChOffset + 4 + 8] + s16X[ChOffset + 4 + 24]); \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_4_2 * (SINT64)s16X[ChOffset + 4 + 16];                            \
-        s32DCTY[4] = (SINT32)(s64Temp >> 16);                                                                \
-    }
+#define WINDOW_ACCU_4_4                                                                                  \
+  {                                                                                                      \
+    s64Temp = (SINT64)WIND_4_SUBBANDS_4_0 * (SINT64)(s16X[ChOffset + 4] + s16X[ChOffset + 4 + 32]);      \
+    s64Temp += (SINT64)WIND_4_SUBBANDS_4_1 * (SINT64)(s16X[ChOffset + 4 + 8] + s16X[ChOffset + 4 + 24]); \
+    s64Temp += (SINT64)WIND_4_SUBBANDS_4_2 * (SINT64)s16X[ChOffset + 4 + 16];                            \
+    s32DCTY[4] = (SINT32)(s64Temp >> 16);                                                                \
+  }
 #else /* SBC_IS_64_MULT_IN_WINDOW_ACCU == FALSE */
-#define WINDOW_ACCU_8_0                                                                               \
-    {                                                                                                 \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_0_1 * (SINT32)(s16X[ChOffset + 16] - s16X[ChOffset + 64]);  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_0_2 * (SINT32)(s16X[ChOffset + 32] - s16X[ChOffset + 48]); \
-        s32DCTY[0] = (SINT32)s32Temp;                                                                 \
-    }
-#define WINDOW_ACCU_8_1_15                                                          \
-    {                                                                               \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 1];         \
-        s32Temp2 = (SINT32)WIND_8_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 64 + 15];  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 16 + 1];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 48 + 15]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 32 + 1];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 32 + 15]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 48 + 1];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 16 + 15]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 64 + 1];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 15];      \
-        s32DCTY[1] = (SINT32)s32Temp;                                               \
-        s32DCTY[15] = (SINT32)s32Temp2;                                             \
-    }
-#define WINDOW_ACCU_8_2_14                                                          \
-    {                                                                               \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 2];         \
-        s32Temp2 = (SINT32)WIND_8_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 64 + 14];  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 16 + 2];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 48 + 14]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 32 + 2];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 32 + 14]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 48 + 2];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 16 + 14]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 64 + 2];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 14];      \
-        s32DCTY[2] = (SINT32)s32Temp;                                               \
-        s32DCTY[14] = (SINT32)s32Temp2;                                             \
-    }
-#define WINDOW_ACCU_8_3_13                                                          \
-    {                                                                               \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 3];         \
-        s32Temp2 = (SINT32)WIND_8_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 64 + 13];  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 16 + 3];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 48 + 13]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 32 + 3];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 32 + 13]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 48 + 3];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 16 + 13]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 64 + 3];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 13];      \
-        s32DCTY[3] = (SINT32)s32Temp;                                               \
-        s32DCTY[13] = (SINT32)s32Temp2;                                             \
-    }
-#define WINDOW_ACCU_8_4_12                                                          \
-    {                                                                               \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_4_0 * (SINT32)s16X[ChOffset + 4];         \
-        s32Temp2 = (SINT32)WIND_8_SUBBANDS_4_0 * (SINT32)s16X[ChOffset + 64 + 12];  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_4_1 * (SINT32)s16X[ChOffset + 16 + 4];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_1 * (SINT32)s16X[ChOffset + 48 + 12]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_4_2 * (SINT32)s16X[ChOffset + 32 + 4];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_2 * (SINT32)s16X[ChOffset + 32 + 12]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_4_3 * (SINT32)s16X[ChOffset + 48 + 4];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_3 * (SINT32)s16X[ChOffset + 16 + 12]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_4_4 * (SINT32)s16X[ChOffset + 64 + 4];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_4 * (SINT32)s16X[ChOffset + 12];      \
-        s32DCTY[4] = (SINT32)s32Temp;                                               \
-        s32DCTY[12] = (SINT32)s32Temp2;                                             \
-    }
-#define WINDOW_ACCU_8_5_11                                                          \
-    {                                                                               \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_5_0 * (SINT32)s16X[ChOffset + 5];         \
-        s32Temp2 = (SINT32)WIND_8_SUBBANDS_5_0 * (SINT32)s16X[ChOffset + 64 + 11];  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_5_1 * (SINT32)s16X[ChOffset + 16 + 5];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_1 * (SINT32)s16X[ChOffset + 48 + 11]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_5_2 * (SINT32)s16X[ChOffset + 32 + 5];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_2 * (SINT32)s16X[ChOffset + 32 + 11]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_5_3 * (SINT32)s16X[ChOffset + 48 + 5];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_3 * (SINT32)s16X[ChOffset + 16 + 11]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_5_4 * (SINT32)s16X[ChOffset + 64 + 5];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_4 * (SINT32)s16X[ChOffset + 11];      \
-        s32DCTY[5] = (SINT32)s32Temp;                                               \
-        s32DCTY[11] = (SINT32)s32Temp2;                                             \
-    }
-#define WINDOW_ACCU_8_6_10                                                          \
-    {                                                                               \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_6_0 * (SINT32)s16X[ChOffset + 6];         \
-        s32Temp2 = (SINT32)WIND_8_SUBBANDS_6_0 * (SINT32)s16X[ChOffset + 64 + 10];  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_6_1 * (SINT32)s16X[ChOffset + 16 + 6];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_1 * (SINT32)s16X[ChOffset + 48 + 10]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_6_2 * (SINT32)s16X[ChOffset + 32 + 6];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_2 * (SINT32)s16X[ChOffset + 32 + 10]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_6_3 * (SINT32)s16X[ChOffset + 48 + 6];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_3 * (SINT32)s16X[ChOffset + 16 + 10]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_6_4 * (SINT32)s16X[ChOffset + 64 + 6];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_4 * (SINT32)s16X[ChOffset + 10];      \
-        s32DCTY[6] = (SINT32)s32Temp;                                               \
-        s32DCTY[10] = (SINT32)s32Temp2;                                             \
-    }
-#define WINDOW_ACCU_8_7_9                                                          \
-    {                                                                              \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_7_0 * (SINT32)s16X[ChOffset + 7];        \
-        s32Temp2 = (SINT32)WIND_8_SUBBANDS_7_0 * (SINT32)s16X[ChOffset + 64 + 9];  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_7_1 * (SINT32)s16X[ChOffset + 16 + 7];  \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_1 * (SINT32)s16X[ChOffset + 48 + 9]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_7_2 * (SINT32)s16X[ChOffset + 32 + 7];  \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_2 * (SINT32)s16X[ChOffset + 32 + 9]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_7_3 * (SINT32)s16X[ChOffset + 48 + 7];  \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_3 * (SINT32)s16X[ChOffset + 16 + 9]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_7_4 * (SINT32)s16X[ChOffset + 64 + 7];  \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_4 * (SINT32)s16X[ChOffset + 9];      \
-        s32DCTY[7] = (SINT32)s32Temp;                                              \
-        s32DCTY[9] = (SINT32)s32Temp2;                                             \
-    }
-#define WINDOW_ACCU_8_8                                                                                       \
-    {                                                                                                         \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_8_0 * (SINT32)(s16X[ChOffset + 8] + s16X[ChOffset + 64 + 8]);       \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_8_1 * (SINT32)(s16X[ChOffset + 16 + 8] + s16X[ChOffset + 48 + 8]); \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_8_2 * (SINT32)s16X[ChOffset + 32 + 8];                             \
-        s32DCTY[8] = (SINT32)s32Temp;                                                                         \
-    }
-#define WINDOW_ACCU_4_0                                                                               \
-    {                                                                                                 \
-        s32Temp = (SINT32)WIND_4_SUBBANDS_0_1 * (SINT32)(s16X[ChOffset + 8] - s16X[ChOffset + 32]);   \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_0_2 * (SINT32)(s16X[ChOffset + 16] - s16X[ChOffset + 24]); \
-        s32DCTY[0] = (SINT32)(s32Temp);                                                               \
-    }
-#define WINDOW_ACCU_4_1_7                                                          \
-    {                                                                              \
-        s32Temp = (SINT32)WIND_4_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 1];        \
-        s32Temp2 = (SINT32)WIND_4_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 32 + 7];  \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 8 + 1];   \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 24 + 7]; \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 16 + 1];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 16 + 7]; \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 24 + 1];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 8 + 7];  \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 32 + 1];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 7];      \
-        s32DCTY[1] = (SINT32)(s32Temp);                                            \
-        s32DCTY[7] = (SINT32)(s32Temp2);                                           \
-    }
-#define WINDOW_ACCU_4_2_6                                                          \
-    {                                                                              \
-        s32Temp = (SINT32)WIND_4_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 2];        \
-        s32Temp2 = (SINT32)WIND_4_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 32 + 6];  \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 8 + 2];   \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 24 + 6]; \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 16 + 2];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 16 + 6]; \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 24 + 2];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 8 + 6];  \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 32 + 2];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 6];      \
-        s32DCTY[2] = (SINT32)(s32Temp);                                            \
-        s32DCTY[6] = (SINT32)(s32Temp2);                                           \
-    }
-#define WINDOW_ACCU_4_3_5                                                          \
-    {                                                                              \
-        s32Temp = (SINT32)WIND_4_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 3];        \
-        s32Temp2 = (SINT32)WIND_4_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 32 + 5];  \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 8 + 3];   \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 24 + 5]; \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 16 + 3];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 16 + 5]; \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 24 + 3];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 8 + 5];  \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 32 + 3];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 5];      \
-        s32DCTY[3] = (SINT32)(s32Temp);                                            \
-        s32DCTY[5] = (SINT32)(s32Temp2);                                           \
-    }
+#define WINDOW_ACCU_8_0                                                                           \
+  {                                                                                               \
+    s32Temp = (SINT32)WIND_8_SUBBANDS_0_1 * (SINT32)(s16X[ChOffset + 16] - s16X[ChOffset + 64]);  \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_0_2 * (SINT32)(s16X[ChOffset + 32] - s16X[ChOffset + 48]); \
+    s32DCTY[0] = (SINT32)s32Temp;                                                                 \
+  }
+#define WINDOW_ACCU_8_1_15                                                      \
+  {                                                                             \
+    s32Temp  = (SINT32)WIND_8_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 1];        \
+    s32Temp2 = (SINT32)WIND_8_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 64 + 15];  \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 16 + 1];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 48 + 15]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 32 + 1];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 32 + 15]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 48 + 1];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 16 + 15]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 64 + 1];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 15];      \
+    s32DCTY[1]  = (SINT32)s32Temp;                                              \
+    s32DCTY[15] = (SINT32)s32Temp2;                                             \
+  }
+#define WINDOW_ACCU_8_2_14                                                      \
+  {                                                                             \
+    s32Temp  = (SINT32)WIND_8_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 2];        \
+    s32Temp2 = (SINT32)WIND_8_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 64 + 14];  \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 16 + 2];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 48 + 14]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 32 + 2];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 32 + 14]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 48 + 2];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 16 + 14]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 64 + 2];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 14];      \
+    s32DCTY[2]  = (SINT32)s32Temp;                                              \
+    s32DCTY[14] = (SINT32)s32Temp2;                                             \
+  }
+#define WINDOW_ACCU_8_3_13                                                      \
+  {                                                                             \
+    s32Temp  = (SINT32)WIND_8_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 3];        \
+    s32Temp2 = (SINT32)WIND_8_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 64 + 13];  \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 16 + 3];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 48 + 13]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 32 + 3];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 32 + 13]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 48 + 3];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 16 + 13]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 64 + 3];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 13];      \
+    s32DCTY[3]  = (SINT32)s32Temp;                                              \
+    s32DCTY[13] = (SINT32)s32Temp2;                                             \
+  }
+#define WINDOW_ACCU_8_4_12                                                      \
+  {                                                                             \
+    s32Temp  = (SINT32)WIND_8_SUBBANDS_4_0 * (SINT32)s16X[ChOffset + 4];        \
+    s32Temp2 = (SINT32)WIND_8_SUBBANDS_4_0 * (SINT32)s16X[ChOffset + 64 + 12];  \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_4_1 * (SINT32)s16X[ChOffset + 16 + 4];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_1 * (SINT32)s16X[ChOffset + 48 + 12]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_4_2 * (SINT32)s16X[ChOffset + 32 + 4];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_2 * (SINT32)s16X[ChOffset + 32 + 12]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_4_3 * (SINT32)s16X[ChOffset + 48 + 4];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_3 * (SINT32)s16X[ChOffset + 16 + 12]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_4_4 * (SINT32)s16X[ChOffset + 64 + 4];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_4 * (SINT32)s16X[ChOffset + 12];      \
+    s32DCTY[4]  = (SINT32)s32Temp;                                              \
+    s32DCTY[12] = (SINT32)s32Temp2;                                             \
+  }
+#define WINDOW_ACCU_8_5_11                                                      \
+  {                                                                             \
+    s32Temp  = (SINT32)WIND_8_SUBBANDS_5_0 * (SINT32)s16X[ChOffset + 5];        \
+    s32Temp2 = (SINT32)WIND_8_SUBBANDS_5_0 * (SINT32)s16X[ChOffset + 64 + 11];  \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_5_1 * (SINT32)s16X[ChOffset + 16 + 5];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_1 * (SINT32)s16X[ChOffset + 48 + 11]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_5_2 * (SINT32)s16X[ChOffset + 32 + 5];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_2 * (SINT32)s16X[ChOffset + 32 + 11]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_5_3 * (SINT32)s16X[ChOffset + 48 + 5];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_3 * (SINT32)s16X[ChOffset + 16 + 11]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_5_4 * (SINT32)s16X[ChOffset + 64 + 5];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_4 * (SINT32)s16X[ChOffset + 11];      \
+    s32DCTY[5]  = (SINT32)s32Temp;                                              \
+    s32DCTY[11] = (SINT32)s32Temp2;                                             \
+  }
+#define WINDOW_ACCU_8_6_10                                                      \
+  {                                                                             \
+    s32Temp  = (SINT32)WIND_8_SUBBANDS_6_0 * (SINT32)s16X[ChOffset + 6];        \
+    s32Temp2 = (SINT32)WIND_8_SUBBANDS_6_0 * (SINT32)s16X[ChOffset + 64 + 10];  \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_6_1 * (SINT32)s16X[ChOffset + 16 + 6];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_1 * (SINT32)s16X[ChOffset + 48 + 10]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_6_2 * (SINT32)s16X[ChOffset + 32 + 6];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_2 * (SINT32)s16X[ChOffset + 32 + 10]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_6_3 * (SINT32)s16X[ChOffset + 48 + 6];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_3 * (SINT32)s16X[ChOffset + 16 + 10]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_6_4 * (SINT32)s16X[ChOffset + 64 + 6];   \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_4 * (SINT32)s16X[ChOffset + 10];      \
+    s32DCTY[6]  = (SINT32)s32Temp;                                              \
+    s32DCTY[10] = (SINT32)s32Temp2;                                             \
+  }
+#define WINDOW_ACCU_8_7_9                                                      \
+  {                                                                            \
+    s32Temp  = (SINT32)WIND_8_SUBBANDS_7_0 * (SINT32)s16X[ChOffset + 7];       \
+    s32Temp2 = (SINT32)WIND_8_SUBBANDS_7_0 * (SINT32)s16X[ChOffset + 64 + 9];  \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_7_1 * (SINT32)s16X[ChOffset + 16 + 7];  \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_1 * (SINT32)s16X[ChOffset + 48 + 9]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_7_2 * (SINT32)s16X[ChOffset + 32 + 7];  \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_2 * (SINT32)s16X[ChOffset + 32 + 9]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_7_3 * (SINT32)s16X[ChOffset + 48 + 7];  \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_3 * (SINT32)s16X[ChOffset + 16 + 9]; \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_7_4 * (SINT32)s16X[ChOffset + 64 + 7];  \
+    s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_4 * (SINT32)s16X[ChOffset + 9];      \
+    s32DCTY[7] = (SINT32)s32Temp;                                              \
+    s32DCTY[9] = (SINT32)s32Temp2;                                             \
+  }
+#define WINDOW_ACCU_8_8                                                                                   \
+  {                                                                                                       \
+    s32Temp = (SINT32)WIND_8_SUBBANDS_8_0 * (SINT32)(s16X[ChOffset + 8] + s16X[ChOffset + 64 + 8]);       \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_8_1 * (SINT32)(s16X[ChOffset + 16 + 8] + s16X[ChOffset + 48 + 8]); \
+    s32Temp += (SINT32)WIND_8_SUBBANDS_8_2 * (SINT32)s16X[ChOffset + 32 + 8];                             \
+    s32DCTY[8] = (SINT32)s32Temp;                                                                         \
+  }
+#define WINDOW_ACCU_4_0                                                                           \
+  {                                                                                               \
+    s32Temp = (SINT32)WIND_4_SUBBANDS_0_1 * (SINT32)(s16X[ChOffset + 8] - s16X[ChOffset + 32]);   \
+    s32Temp += (SINT32)WIND_4_SUBBANDS_0_2 * (SINT32)(s16X[ChOffset + 16] - s16X[ChOffset + 24]); \
+    s32DCTY[0] = (SINT32)(s32Temp);                                                               \
+  }
+#define WINDOW_ACCU_4_1_7                                                      \
+  {                                                                            \
+    s32Temp  = (SINT32)WIND_4_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 1];       \
+    s32Temp2 = (SINT32)WIND_4_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 32 + 7];  \
+    s32Temp += (SINT32)WIND_4_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 8 + 1];   \
+    s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 24 + 7]; \
+    s32Temp += (SINT32)WIND_4_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 16 + 1];  \
+    s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 16 + 7]; \
+    s32Temp += (SINT32)WIND_4_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 24 + 1];  \
+    s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 8 + 7];  \
+    s32Temp += (SINT32)WIND_4_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 32 + 1];  \
+    s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 7];      \
+    s32DCTY[1] = (SINT32)(s32Temp);                                            \
+    s32DCTY[7] = (SINT32)(s32Temp2);                                           \
+  }
+#define WINDOW_ACCU_4_2_6                                                      \
+  {                                                                            \
+    s32Temp  = (SINT32)WIND_4_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 2];       \
+    s32Temp2 = (SINT32)WIND_4_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 32 + 6];  \
+    s32Temp += (SINT32)WIND_4_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 8 + 2];   \
+    s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 24 + 6]; \
+    s32Temp += (SINT32)WIND_4_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 16 + 2];  \
+    s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 16 + 6]; \
+    s32Temp += (SINT32)WIND_4_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 24 + 2];  \
+    s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 8 + 6];  \
+    s32Temp += (SINT32)WIND_4_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 32 + 2];  \
+    s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 6];      \
+    s32DCTY[2] = (SINT32)(s32Temp);                                            \
+    s32DCTY[6] = (SINT32)(s32Temp2);                                           \
+  }
+#define WINDOW_ACCU_4_3_5                                                      \
+  {                                                                            \
+    s32Temp  = (SINT32)WIND_4_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 3];       \
+    s32Temp2 = (SINT32)WIND_4_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 32 + 5];  \
+    s32Temp += (SINT32)WIND_4_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 8 + 3];   \
+    s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 24 + 5]; \
+    s32Temp += (SINT32)WIND_4_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 16 + 3];  \
+    s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 16 + 5]; \
+    s32Temp += (SINT32)WIND_4_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 24 + 3];  \
+    s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 8 + 5];  \
+    s32Temp += (SINT32)WIND_4_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 32 + 3];  \
+    s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 5];      \
+    s32DCTY[3] = (SINT32)(s32Temp);                                            \
+    s32DCTY[5] = (SINT32)(s32Temp2);                                           \
+  }
 
-#define WINDOW_ACCU_4_4                                                                                      \
-    {                                                                                                        \
-        s32Temp = (SINT32)WIND_4_SUBBANDS_4_0 * (SINT32)(s16X[ChOffset + 4] + s16X[ChOffset + 4 + 32]);      \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_4_1 * (SINT32)(s16X[ChOffset + 4 + 8] + s16X[ChOffset + 4 + 24]); \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_4_2 * (SINT32)s16X[ChOffset + 4 + 16];                            \
-        s32DCTY[4] = (SINT32)(s32Temp);                                                                      \
-    }
+#define WINDOW_ACCU_4_4                                                                                  \
+  {                                                                                                      \
+    s32Temp = (SINT32)WIND_4_SUBBANDS_4_0 * (SINT32)(s16X[ChOffset + 4] + s16X[ChOffset + 4 + 32]);      \
+    s32Temp += (SINT32)WIND_4_SUBBANDS_4_1 * (SINT32)(s16X[ChOffset + 4 + 8] + s16X[ChOffset + 4 + 24]); \
+    s32Temp += (SINT32)WIND_4_SUBBANDS_4_2 * (SINT32)s16X[ChOffset + 4 + 16];                            \
+    s32DCTY[4] = (SINT32)(s32Temp);                                                                      \
+  }
 #endif
-#define WINDOW_PARTIAL_4   \
-    {                      \
-        WINDOW_ACCU_4_0;   \
-        WINDOW_ACCU_4_1_7; \
-        WINDOW_ACCU_4_2_6; \
-        WINDOW_ACCU_4_3_5; \
-        WINDOW_ACCU_4_4;   \
-    }
+#define WINDOW_PARTIAL_4 \
+  {                      \
+    WINDOW_ACCU_4_0;     \
+    WINDOW_ACCU_4_1_7;   \
+    WINDOW_ACCU_4_2_6;   \
+    WINDOW_ACCU_4_3_5;   \
+    WINDOW_ACCU_4_4;     \
+  }
 
-#define WINDOW_PARTIAL_8    \
-    {                       \
-        WINDOW_ACCU_8_0;    \
-        WINDOW_ACCU_8_1_15; \
-        WINDOW_ACCU_8_2_14; \
-        WINDOW_ACCU_8_3_13; \
-        WINDOW_ACCU_8_4_12; \
-        WINDOW_ACCU_8_5_11; \
-        WINDOW_ACCU_8_6_10; \
-        WINDOW_ACCU_8_7_9;  \
-        WINDOW_ACCU_8_8;    \
-    }
+#define WINDOW_PARTIAL_8 \
+  {                      \
+    WINDOW_ACCU_8_0;     \
+    WINDOW_ACCU_8_1_15;  \
+    WINDOW_ACCU_8_2_14;  \
+    WINDOW_ACCU_8_3_13;  \
+    WINDOW_ACCU_8_4_12;  \
+    WINDOW_ACCU_8_5_11;  \
+    WINDOW_ACCU_8_6_10;  \
+    WINDOW_ACCU_8_7_9;   \
+    WINDOW_ACCU_8_8;     \
+  }
 #else
 #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE)
-#define WINDOW_ACCU_4(i)                                                                    \
-    {                                                                                       \
-        s64Temp = ((SINT64)gas32CoeffFor4SBs[i] * (SINT64)s16X[ChOffset + i]);              \
-        s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 8)] * (SINT64)s16X[ChOffset + i + 8]);   \
-        s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 16)] * (SINT64)s16X[ChOffset + i + 16]); \
-        s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 24)] * (SINT64)s16X[ChOffset + i + 24]); \
-        s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 32)] * (SINT64)s16X[ChOffset + i + 32]); \
-        s32DCTY[i] = (SINT32)(s64Temp >> 16);                                               \
-        /*BT_WARN("s32DCTY4: 0x%x \n", s32DCTY[i]);*/                                       \
-    }
+#define WINDOW_ACCU_4(i)                                                                \
+  {                                                                                     \
+    s64Temp = ((SINT64)gas32CoeffFor4SBs[i] * (SINT64)s16X[ChOffset + i]);              \
+    s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 8)] * (SINT64)s16X[ChOffset + i + 8]);   \
+    s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 16)] * (SINT64)s16X[ChOffset + i + 16]); \
+    s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 24)] * (SINT64)s16X[ChOffset + i + 24]); \
+    s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 32)] * (SINT64)s16X[ChOffset + i + 32]); \
+    s32DCTY[i] = (SINT32)(s64Temp >> 16);                                               \
+    /*BT_WARN("s32DCTY4: 0x%x \n", s32DCTY[i]);*/                                       \
+  }
 #else
-#define WINDOW_ACCU_4(i)                                                                                                                                                         \
-    {                                                                                                                                                                            \
-        s32DCTY[i] = (gas32CoeffFor4SBs[i * 2] * s16X[ChOffset + i]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[(i * 2) + 1]) * s16X[ChOffset + i]) >> 16);                          \
-        s32DCTY[i] += (gas32CoeffFor4SBs[(i + 8) * 2] * s16X[ChOffset + i + 8]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 8) * 2) + 1]) * s16X[ChOffset + i + 8]) >> 16);     \
-        s32DCTY[i] += (gas32CoeffFor4SBs[(i + 16) * 2] * s16X[ChOffset + i + 16]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 16) * 2) + 1]) * s16X[ChOffset + i + 16]) >> 16); \
-        s32DCTY[i] += (gas32CoeffFor4SBs[(i + 24) * 2] * s16X[ChOffset + i + 24]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 24) * 2) + 1]) * s16X[ChOffset + i + 24]) >> 16); \
-        s32DCTY[i] += (gas32CoeffFor4SBs[(i + 32) * 2] * s16X[ChOffset + i + 32]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 32) * 2) + 1]) * s16X[ChOffset + i + 32]) >> 16); \
-    }
+#define WINDOW_ACCU_4(i)                                                                                                                                                     \
+  {                                                                                                                                                                          \
+    s32DCTY[i] = (gas32CoeffFor4SBs[i * 2] * s16X[ChOffset + i]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[(i * 2) + 1]) * s16X[ChOffset + i]) >> 16);                          \
+    s32DCTY[i] += (gas32CoeffFor4SBs[(i + 8) * 2] * s16X[ChOffset + i + 8]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 8) * 2) + 1]) * s16X[ChOffset + i + 8]) >> 16);     \
+    s32DCTY[i] += (gas32CoeffFor4SBs[(i + 16) * 2] * s16X[ChOffset + i + 16]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 16) * 2) + 1]) * s16X[ChOffset + i + 16]) >> 16); \
+    s32DCTY[i] += (gas32CoeffFor4SBs[(i + 24) * 2] * s16X[ChOffset + i + 24]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 24) * 2) + 1]) * s16X[ChOffset + i + 24]) >> 16); \
+    s32DCTY[i] += (gas32CoeffFor4SBs[(i + 32) * 2] * s16X[ChOffset + i + 32]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 32) * 2) + 1]) * s16X[ChOffset + i + 32]) >> 16); \
+  }
 #endif
-#define WINDOW_PARTIAL_4  \
-    {                     \
-        WINDOW_ACCU_4(0); \
-        WINDOW_ACCU_4(1); \
-        WINDOW_ACCU_4(2); \
-        WINDOW_ACCU_4(3); \
-        WINDOW_ACCU_4(4); \
-        WINDOW_ACCU_4(5); \
-        WINDOW_ACCU_4(6); \
-        WINDOW_ACCU_4(7); \
-    }
+#define WINDOW_PARTIAL_4 \
+  {                      \
+    WINDOW_ACCU_4(0);    \
+    WINDOW_ACCU_4(1);    \
+    WINDOW_ACCU_4(2);    \
+    WINDOW_ACCU_4(3);    \
+    WINDOW_ACCU_4(4);    \
+    WINDOW_ACCU_4(5);    \
+    WINDOW_ACCU_4(6);    \
+    WINDOW_ACCU_4(7);    \
+  }
 
 #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE)
-#define WINDOW_ACCU_8(i)                                                                              \
-    {                                                                                                 \
-        s64Temp = ((((SINT64)gas32CoeffFor8SBs[i] * (SINT64)s16X[ChOffset + i])));                    \
-        s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 16)] * (SINT64)s16X[ChOffset + i + 16])));       \
-        s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 32)] * (SINT64)s16X[ChOffset + i + 32])));       \
-        s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 48)] * (SINT64)s16X[ChOffset + i + 48])));       \
-        s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 64)] * (SINT64)s16X[ChOffset + i + 64])));       \
-        /*BT_WARN("s32DCTY8: %d= 0x%x * %d\n", s32DCTY[i], gas32CoeffFor8SBs[i], s16X[ChOffset+i]);*/ \
-        s32DCTY[i] = (SINT32)(s64Temp >> 16);                                                         \
-    }
+#define WINDOW_ACCU_8(i)                                                                          \
+  {                                                                                               \
+    s64Temp = ((((SINT64)gas32CoeffFor8SBs[i] * (SINT64)s16X[ChOffset + i])));                    \
+    s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 16)] * (SINT64)s16X[ChOffset + i + 16])));       \
+    s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 32)] * (SINT64)s16X[ChOffset + i + 32])));       \
+    s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 48)] * (SINT64)s16X[ChOffset + i + 48])));       \
+    s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 64)] * (SINT64)s16X[ChOffset + i + 64])));       \
+    /*BT_WARN("s32DCTY8: %d= 0x%x * %d\n", s32DCTY[i], gas32CoeffFor8SBs[i], s16X[ChOffset+i]);*/ \
+    s32DCTY[i] = (SINT32)(s64Temp >> 16);                                                         \
+  }
 #else
-#define WINDOW_ACCU_8(i)                                                                                                                                                         \
-    {                                                                                                                                                                            \
-        s32DCTY[i] = (gas32CoeffFor8SBs[i * 2] * s16X[ChOffset + i]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[(i * 2) + 1]) * s16X[ChOffset + i]) >> 16);                          \
-        s32DCTY[i] += (gas32CoeffFor8SBs[(i + 16) * 2] * s16X[ChOffset + i + 16]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 16) * 2) + 1]) * s16X[ChOffset + i + 16]) >> 16); \
-        s32DCTY[i] += (gas32CoeffFor8SBs[(i + 32) * 2] * s16X[ChOffset + i + 32]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 32) * 2) + 1]) * s16X[ChOffset + i + 32]) >> 16); \
-        s32DCTY[i] += (gas32CoeffFor8SBs[(i + 48) * 2] * s16X[ChOffset + i + 48]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 48) * 2) + 1]) * s16X[ChOffset + i + 48]) >> 16); \
-        s32DCTY[i] += (gas32CoeffFor8SBs[(i + 64) * 2] * s16X[ChOffset + i + 64]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 64) * 2) + 1]) * s16X[ChOffset + i + 64]) >> 16); \
-        /*BT_WARN("s32DCTY8: %d = 0x%4x%4x * %d\n", s32DCTY[i], gas32CoeffFor8SBs[i * 2], (gas32CoeffFor8SBs[(i * 2) + 1]), s16X[ChOffset+i]);*/                                 \
-        /*s32DCTY[i]=(SINT32)(s64Temp>>16);*/                                                                                                                                    \
-    }
+#define WINDOW_ACCU_8(i)                                                                                                                                                     \
+  {                                                                                                                                                                          \
+    s32DCTY[i] = (gas32CoeffFor8SBs[i * 2] * s16X[ChOffset + i]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[(i * 2) + 1]) * s16X[ChOffset + i]) >> 16);                          \
+    s32DCTY[i] += (gas32CoeffFor8SBs[(i + 16) * 2] * s16X[ChOffset + i + 16]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 16) * 2) + 1]) * s16X[ChOffset + i + 16]) >> 16); \
+    s32DCTY[i] += (gas32CoeffFor8SBs[(i + 32) * 2] * s16X[ChOffset + i + 32]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 32) * 2) + 1]) * s16X[ChOffset + i + 32]) >> 16); \
+    s32DCTY[i] += (gas32CoeffFor8SBs[(i + 48) * 2] * s16X[ChOffset + i + 48]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 48) * 2) + 1]) * s16X[ChOffset + i + 48]) >> 16); \
+    s32DCTY[i] += (gas32CoeffFor8SBs[(i + 64) * 2] * s16X[ChOffset + i + 64]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 64) * 2) + 1]) * s16X[ChOffset + i + 64]) >> 16); \
+    /*BT_WARN("s32DCTY8: %d = 0x%4x%4x * %d\n", s32DCTY[i], gas32CoeffFor8SBs[i * 2], (gas32CoeffFor8SBs[(i * 2) + 1]), s16X[ChOffset+i]);*/                                 \
+    /*s32DCTY[i]=(SINT32)(s64Temp>>16);*/                                                                                                                                    \
+  }
 #endif
-#define WINDOW_PARTIAL_8   \
-    {                      \
-        WINDOW_ACCU_8(0);  \
-        WINDOW_ACCU_8(1);  \
-        WINDOW_ACCU_8(2);  \
-        WINDOW_ACCU_8(3);  \
-        WINDOW_ACCU_8(4);  \
-        WINDOW_ACCU_8(5);  \
-        WINDOW_ACCU_8(6);  \
-        WINDOW_ACCU_8(7);  \
-        WINDOW_ACCU_8(8);  \
-        WINDOW_ACCU_8(9);  \
-        WINDOW_ACCU_8(10); \
-        WINDOW_ACCU_8(11); \
-        WINDOW_ACCU_8(12); \
-        WINDOW_ACCU_8(13); \
-        WINDOW_ACCU_8(14); \
-        WINDOW_ACCU_8(15); \
-    }
+#define WINDOW_PARTIAL_8 \
+  {                      \
+    WINDOW_ACCU_8(0);    \
+    WINDOW_ACCU_8(1);    \
+    WINDOW_ACCU_8(2);    \
+    WINDOW_ACCU_8(3);    \
+    WINDOW_ACCU_8(4);    \
+    WINDOW_ACCU_8(5);    \
+    WINDOW_ACCU_8(6);    \
+    WINDOW_ACCU_8(7);    \
+    WINDOW_ACCU_8(8);    \
+    WINDOW_ACCU_8(9);    \
+    WINDOW_ACCU_8(10);   \
+    WINDOW_ACCU_8(11);   \
+    WINDOW_ACCU_8(12);   \
+    WINDOW_ACCU_8(13);   \
+    WINDOW_ACCU_8(14);   \
+    WINDOW_ACCU_8(15);   \
+  }
 #endif
 #endif
 
 static SINT16 ShiftCounter = 0;
 extern SINT16 EncMaxShiftCounter;
 /****************************************************************************
-* SbcAnalysisFilter - performs Analysis of the input audio stream
-*
-* RETURNS : N/A
-*/
-void SbcAnalysisFilter4(SBC_ENC_PARAMS *pstrEncParams)
-{
-    SINT16 *ps16PcmBuf;
-    SINT32 *ps32SbBuf;
-    SINT32 s32Blk, s32Ch;
-    SINT32 s32NumOfChannels, s32NumOfBlocks;
-    SINT32 i, *ps32X, *ps32X2;
-    SINT32 Offset, Offset2, ChOffset;
+ * SbcAnalysisFilter - performs Analysis of the input audio stream
+ *
+ * RETURNS : N/A
+ */
+void SbcAnalysisFilter4(SBC_ENC_PARAMS *pstrEncParams) {
+  SINT16 *ps16PcmBuf;
+  SINT32 *ps32SbBuf;
+  SINT32  s32Blk, s32Ch;
+  SINT32  s32NumOfChannels, s32NumOfBlocks;
+  SINT32  i, *ps32X, *ps32X2;
+  SINT32  Offset, Offset2, ChOffset;
 #if (SBC_ARM_ASM_OPT == TRUE)
-    register SINT32 s32Hi, s32Hi2;
+  register SINT32 s32Hi, s32Hi2;
 #else
 #if (SBC_IPAQ_OPT == TRUE)
 #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE)
-    register SINT64 s64Temp, s64Temp2;
+  register SINT64 s64Temp, s64Temp2;
 #else
-    register SINT32 s32Temp, s32Temp2;
+  register SINT32 s32Temp, s32Temp2;
 #endif
 #else
 
 #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE)
-    SINT64 s64Temp;
+  SINT64 s64Temp;
 #endif
 
 #endif
 #endif
 
-    s32NumOfChannels = pstrEncParams->s16NumOfChannels;
-    s32NumOfBlocks = pstrEncParams->s16NumOfBlocks;
+  s32NumOfChannels = pstrEncParams->s16NumOfChannels;
+  s32NumOfBlocks   = pstrEncParams->s16NumOfBlocks;
 
-    ps16PcmBuf = pstrEncParams->ps16NextPcmBuffer;
+  ps16PcmBuf = pstrEncParams->ps16NextPcmBuffer;
 
-    ps32SbBuf = pstrEncParams->s32SbBuffer;
-    Offset2 = (SINT32)(EncMaxShiftCounter + 40);
-    for (s32Blk = 0; s32Blk < s32NumOfBlocks; s32Blk++) {
-        Offset = (SINT32)(EncMaxShiftCounter - ShiftCounter);
-        /* Store new samples */
-        if (s32NumOfChannels == 1) {
-            s16X[3 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[2 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[1 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[0 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-        } else {
-            s16X[3 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 3 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[2 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 2 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[1 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 1 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[0 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 0 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-        }
-        for (s32Ch = 0; s32Ch < s32NumOfChannels; s32Ch++) {
-            ChOffset = s32Ch * Offset2 + Offset;
+  ps32SbBuf = pstrEncParams->s32SbBuffer;
+  Offset2   = (SINT32)(EncMaxShiftCounter + 40);
+  for (s32Blk = 0; s32Blk < s32NumOfBlocks; s32Blk++) {
+    Offset = (SINT32)(EncMaxShiftCounter - ShiftCounter);
+    /* Store new samples */
+    if (s32NumOfChannels == 1) {
+      s16X[3 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[2 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[1 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[0 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+    } else {
+      s16X[3 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[Offset2 + 3 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[2 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[Offset2 + 2 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[1 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[Offset2 + 1 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[0 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[Offset2 + 0 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+    }
+    for (s32Ch = 0; s32Ch < s32NumOfChannels; s32Ch++) {
+      ChOffset = s32Ch * Offset2 + Offset;
 
-            WINDOW_PARTIAL_4
+      WINDOW_PARTIAL_4
 
-            SBC_FastIDCT4(s32DCTY, ps32SbBuf);
+      SBC_FastIDCT4(s32DCTY, ps32SbBuf);
 
-            ps32SbBuf += SUB_BANDS_4;
-        }
-        if (s32NumOfChannels == 1) {
-            if (ShiftCounter >= EncMaxShiftCounter) {
-                SHIFTUP_X4;
-                ShiftCounter = 0;
-            } else {
-                ShiftCounter += SUB_BANDS_4;
-            }
-        } else {
-            if (ShiftCounter >= EncMaxShiftCounter) {
-                SHIFTUP_X4_2;
-                ShiftCounter = 0;
-            } else {
-                ShiftCounter += SUB_BANDS_4;
-            }
-        }
+      ps32SbBuf += SUB_BANDS_4;
     }
+    if (s32NumOfChannels == 1) {
+      if (ShiftCounter >= EncMaxShiftCounter) {
+        SHIFTUP_X4;
+        ShiftCounter = 0;
+      } else {
+        ShiftCounter += SUB_BANDS_4;
+      }
+    } else {
+      if (ShiftCounter >= EncMaxShiftCounter) {
+        SHIFTUP_X4_2;
+        ShiftCounter = 0;
+      } else {
+        ShiftCounter += SUB_BANDS_4;
+      }
+    }
+  }
 }
 
 /* //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// */
-void SbcAnalysisFilter8(SBC_ENC_PARAMS *pstrEncParams)
-{
-    SINT16 *ps16PcmBuf;
-    SINT32 *ps32SbBuf;
-    SINT32 s32Blk, s32Ch; /* counter for block*/
-    SINT32 Offset, Offset2;
-    SINT32 s32NumOfChannels, s32NumOfBlocks;
-    SINT32 i, *ps32X, *ps32X2;
-    SINT32 ChOffset;
+void SbcAnalysisFilter8(SBC_ENC_PARAMS *pstrEncParams) {
+  SINT16 *ps16PcmBuf;
+  SINT32 *ps32SbBuf;
+  SINT32  s32Blk, s32Ch; /* counter for block*/
+  SINT32  Offset, Offset2;
+  SINT32  s32NumOfChannels, s32NumOfBlocks;
+  SINT32  i, *ps32X, *ps32X2;
+  SINT32  ChOffset;
 #if (SBC_ARM_ASM_OPT == TRUE)
-    register SINT32 s32Hi, s32Hi2;
+  register SINT32 s32Hi, s32Hi2;
 #else
 #if (SBC_IPAQ_OPT == TRUE)
 #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE)
-    register SINT64 s64Temp, s64Temp2;
+  register SINT64 s64Temp, s64Temp2;
 #else
-    register SINT32 s32Temp, s32Temp2;
+  register SINT32 s32Temp, s32Temp2;
 #endif
 #else
 #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE)
-    SINT64 s64Temp;
+  SINT64 s64Temp;
 #endif
 #endif
 #endif
 
-    s32NumOfChannels = pstrEncParams->s16NumOfChannels;
-    s32NumOfBlocks = pstrEncParams->s16NumOfBlocks;
+  s32NumOfChannels = pstrEncParams->s16NumOfChannels;
+  s32NumOfBlocks   = pstrEncParams->s16NumOfBlocks;
 
-    ps16PcmBuf = pstrEncParams->ps16NextPcmBuffer;
+  ps16PcmBuf = pstrEncParams->ps16NextPcmBuffer;
 
-    ps32SbBuf = pstrEncParams->s32SbBuffer;
-    Offset2 = (SINT32)(EncMaxShiftCounter + 80);
-    for (s32Blk = 0; s32Blk < s32NumOfBlocks; s32Blk++) {
-        Offset = (SINT32)(EncMaxShiftCounter - ShiftCounter);
-        /* Store new samples */
-        if (s32NumOfChannels == 1) {
-            s16X[7 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[6 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[5 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[4 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[3 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[2 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[1 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[0 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-        } else {
-            s16X[7 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 7 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[6 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 6 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[5 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 5 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[4 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 4 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[3 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 3 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[2 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 2 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[1 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 1 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[0 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 0 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-        }
-        for (s32Ch = 0; s32Ch < s32NumOfChannels; s32Ch++) {
-            ChOffset = s32Ch * Offset2 + Offset;
+  ps32SbBuf = pstrEncParams->s32SbBuffer;
+  Offset2   = (SINT32)(EncMaxShiftCounter + 80);
+  for (s32Blk = 0; s32Blk < s32NumOfBlocks; s32Blk++) {
+    Offset = (SINT32)(EncMaxShiftCounter - ShiftCounter);
+    /* Store new samples */
+    if (s32NumOfChannels == 1) {
+      s16X[7 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[6 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[5 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[4 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[3 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[2 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[1 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[0 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+    } else {
+      s16X[7 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[Offset2 + 7 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[6 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[Offset2 + 6 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[5 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[Offset2 + 5 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[4 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[Offset2 + 4 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[3 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[Offset2 + 3 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[2 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[Offset2 + 2 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[1 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[Offset2 + 1 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[0 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+      s16X[Offset2 + 0 + Offset] = *ps16PcmBuf;
+      ps16PcmBuf++;
+    }
+    for (s32Ch = 0; s32Ch < s32NumOfChannels; s32Ch++) {
+      ChOffset = s32Ch * Offset2 + Offset;
 
-            WINDOW_PARTIAL_8
+      WINDOW_PARTIAL_8
 
-            SBC_FastIDCT8(s32DCTY, ps32SbBuf);
+      SBC_FastIDCT8(s32DCTY, ps32SbBuf);
 
-            ps32SbBuf += SUB_BANDS_8;
-        }
-        if (s32NumOfChannels == 1) {
-            if (ShiftCounter >= EncMaxShiftCounter) {
-                SHIFTUP_X8;
-                ShiftCounter = 0;
-            } else {
-                ShiftCounter += SUB_BANDS_8;
-            }
-        } else {
-            if (ShiftCounter >= EncMaxShiftCounter) {
-                SHIFTUP_X8_2;
-                ShiftCounter = 0;
-            } else {
-                ShiftCounter += SUB_BANDS_8;
-            }
-        }
+      ps32SbBuf += SUB_BANDS_8;
     }
+    if (s32NumOfChannels == 1) {
+      if (ShiftCounter >= EncMaxShiftCounter) {
+        SHIFTUP_X8;
+        ShiftCounter = 0;
+      } else {
+        ShiftCounter += SUB_BANDS_8;
+      }
+    } else {
+      if (ShiftCounter >= EncMaxShiftCounter) {
+        SHIFTUP_X8_2;
+        ShiftCounter = 0;
+      } else {
+        ShiftCounter += SUB_BANDS_8;
+      }
+    }
+  }
 }
 
-void SbcAnalysisInit(void)
-{
-    static bool loaded = false;
-    if (!loaded) {
-        loaded = true;
+void SbcAnalysisInit(void) {
+  static bool loaded = false;
+  if (!loaded) {
+    loaded = true;
 #if BT_BLE_DYNAMIC_ENV_MEMORY == TRUE
-        s32X = (SINT32 *)osi_malloc(sizeof(SINT32) * (ENC_VX_BUFFER_SIZE / 2));
-        s32DCTY = (SINT32 *)osi_malloc(sizeof(SINT32) * 16);
-        assert(s32X);
-        assert(s32DCTY);
-        memset(s32X, 0, sizeof(SINT16) * ENC_VX_BUFFER_SIZE);
-        memset(s32DCTY, 0, sizeof(SINT32) * 16);
-        s16X = (SINT16 *)s32X;
+    s32X    = (SINT32 *)osi_malloc(sizeof(SINT32) * (ENC_VX_BUFFER_SIZE / 2));
+    s32DCTY = (SINT32 *)osi_malloc(sizeof(SINT32) * 16);
+    assert(s32X);
+    assert(s32DCTY);
+    memset(s32X, 0, sizeof(SINT16) * ENC_VX_BUFFER_SIZE);
+    memset(s32DCTY, 0, sizeof(SINT32) * 16);
+    s16X = (SINT16 *)s32X;
 #endif
-    }
-    memset(s16X, 0, ENC_VX_BUFFER_SIZE * sizeof(SINT16));
-    ShiftCounter = 0;
+  }
+  memset(s16X, 0, ENC_VX_BUFFER_SIZE * sizeof(SINT16));
+  ShiftCounter = 0;
 }
 
 #endif /* #if defined(SBC_ENC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct.c
index a9b8baf776..22011a846f 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct.c
@@ -21,9 +21,9 @@
  *  source file for fast dct operations
  *
  ******************************************************************************/
-#include "sbc_encoder.h"
-#include "sbc_enc_func_declare.h"
 #include "sbc_dct.h"
+#include "sbc_enc_func_declare.h"
+#include "sbc_encoder.h"
 
 #if defined(SBC_ENC_INCLUDED)
 
@@ -64,113 +64,112 @@ extern const SINT16 gas16AnalDCTcoeff8[];
 extern const SINT16 gas16AnalDCTcoeff4[];
 #endif
 
-void SBC_FastIDCT8(SINT32 *pInVect, SINT32 *pOutVect)
-{
+void SBC_FastIDCT8(SINT32 *pInVect, SINT32 *pOutVect) {
 #if (SBC_FAST_DCT == TRUE)
 #if (SBC_ARM_ASM_OPT == TRUE)
 #else
 #if (SBC_IPAQ_OPT == TRUE)
 #if (SBC_IS_64_MULT_IN_IDCT == TRUE)
-    SINT64 s64Temp;
+  SINT64 s64Temp;
 #endif
 #else
 #if (SBC_IS_64_MULT_IN_IDCT == TRUE)
-    SINT32 s32HiTemp;
+  SINT32 s32HiTemp;
 #else
-    SINT32 s32In2Temp;
-    register SINT32 s32In1Temp;
+  SINT32          s32In2Temp;
+  register SINT32 s32In1Temp;
 #endif
 #endif
 #endif
 
-    register SINT32 x0, x1, x2, x3, x4, x5, x6, x7, temp;
-    SINT32 res_even[4], res_odd[4];
-    /*x0= (pInVect[4])/2 ;*/
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_4, pInVect[4], x0);
-    /*BT_WARN("x0 0x%x = %d = %d * %d\n", x0, x0, SBC_COS_PI_SUR_4, pInVect[4]);*/
-
-    x1 = (pInVect[3] + pInVect[5]) >> 1;
-    x2 = (pInVect[2] + pInVect[6]) >> 1;
-    x3 = (pInVect[1] + pInVect[7]) >> 1;
-    x4 = (pInVect[0] + pInVect[8]) >> 1;
-    x5 = (pInVect[9] - pInVect[15]) >> 1;
-    x6 = (pInVect[10] - pInVect[14]) >> 1;
-    x7 = (pInVect[11] - pInVect[13]) >> 1;
-
-    /* 2-point IDCT of x0 and x4 as in (11) */
-    temp = x0;
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_4, (x0 + x4), x0);   /*x0 = ( x0 + x4 ) * cos(1*pi/4) ; */
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_4, (temp - x4), x4); /*x4 = ( temp - x4 ) * cos(1*pi/4) ; */
-
-    /* rearrangement of x2 and x6 as in (15) */
-    x2 -= x6;
-    x6 <<= 1;
-
-    /* 2-point IDCT of x2 and x6 and post-multiplication as in (15) */
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_4, x6, x6); /*x6 = x6 * cos(1*pi/4) ; */
-    temp = x2;
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_8, (x2 + x6), x2);    /*x2 = ( x2 + x6 ) * cos(1*pi/8) ; */
-    SBC_IDCT_MULT(SBC_COS_3PI_SUR_8, (temp - x6), x6); /*x6 = ( temp - x6 ) * cos(3*pi/8) ;*/
-
-    /* 4-point IDCT of x0,x2,x4 and x6 as in (11) */
-    res_even[0] = x0 + x2;
-    res_even[1] = x4 + x6;
-    res_even[2] = x4 - x6;
-    res_even[3] = x0 - x2;
-
-    /* rearrangement of x1,x3,x5,x7 as in (15) */
-    x7 <<= 1;
-    x5 = (x5 << 1) - x7;
-    x3 = (x3 << 1) - x5;
-    x1 -= x3 >> 1;
-
-    /* two-dimensional IDCT of x1 and x5 */
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_4, x5, x5); /*x5 = x5 * cos(1*pi/4) ; */
-    temp = x1;
-    x1 = x1 + x5;
-    x5 = temp - x5;
-
-    /* rearrangement of x3 and x7 as in (15) */
-    x3 -= x7;
-    x7 <<= 1;
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_4, x7, x7); /*x7 = x7 * cos(1*pi/4) ; */
-
-    /* 2-point IDCT of x3 and x7 and post-multiplication as in (15) */
-    temp = x3;
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_8, (x3 + x7), x3);    /*x3 = ( x3 + x7 ) * cos(1*pi/8)  ; */
-    SBC_IDCT_MULT(SBC_COS_3PI_SUR_8, (temp - x7), x7); /*x7 = ( temp - x7 ) * cos(3*pi/8) ;*/
-
-    /* 4-point IDCT of x1,x3,x5 and x7 and post multiplication by diagonal matrix as in (14) */
-    SBC_IDCT_MULT((SBC_COS_PI_SUR_16), (x1 + x3), res_odd[0]);  /*res_odd[ 0 ] = ( x1 + x3 ) * cos(1*pi/16) ; */
-    SBC_IDCT_MULT((SBC_COS_3PI_SUR_16), (x5 + x7), res_odd[1]); /*res_odd[ 1 ] = ( x5 + x7 ) * cos(3*pi/16) ; */
-    SBC_IDCT_MULT((SBC_COS_5PI_SUR_16), (x5 - x7), res_odd[2]); /*res_odd[ 2 ] = ( x5 - x7 ) * cos(5*pi/16) ; */
-    SBC_IDCT_MULT((SBC_COS_7PI_SUR_16), (x1 - x3), res_odd[3]); /*res_odd[ 3 ] = ( x1 - x3 ) * cos(7*pi/16) ; */
-
-    /* additions and subtractions as in (9) */
-    pOutVect[0] = (res_even[0] + res_odd[0]);
-    pOutVect[1] = (res_even[1] + res_odd[1]);
-    pOutVect[2] = (res_even[2] + res_odd[2]);
-    pOutVect[3] = (res_even[3] + res_odd[3]);
-    pOutVect[7] = (res_even[0] - res_odd[0]);
-    pOutVect[6] = (res_even[1] - res_odd[1]);
-    pOutVect[5] = (res_even[2] - res_odd[2]);
-    pOutVect[4] = (res_even[3] - res_odd[3]);
+  register SINT32 x0, x1, x2, x3, x4, x5, x6, x7, temp;
+  SINT32          res_even[4], res_odd[4];
+  /*x0= (pInVect[4])/2 ;*/
+  SBC_IDCT_MULT(SBC_COS_PI_SUR_4, pInVect[4], x0);
+  /*BT_WARN("x0 0x%x = %d = %d * %d\n", x0, x0, SBC_COS_PI_SUR_4, pInVect[4]);*/
+
+  x1 = (pInVect[3] + pInVect[5]) >> 1;
+  x2 = (pInVect[2] + pInVect[6]) >> 1;
+  x3 = (pInVect[1] + pInVect[7]) >> 1;
+  x4 = (pInVect[0] + pInVect[8]) >> 1;
+  x5 = (pInVect[9] - pInVect[15]) >> 1;
+  x6 = (pInVect[10] - pInVect[14]) >> 1;
+  x7 = (pInVect[11] - pInVect[13]) >> 1;
+
+  /* 2-point IDCT of x0 and x4 as in (11) */
+  temp = x0;
+  SBC_IDCT_MULT(SBC_COS_PI_SUR_4, (x0 + x4), x0);   /*x0 = ( x0 + x4 ) * cos(1*pi/4) ; */
+  SBC_IDCT_MULT(SBC_COS_PI_SUR_4, (temp - x4), x4); /*x4 = ( temp - x4 ) * cos(1*pi/4) ; */
+
+  /* rearrangement of x2 and x6 as in (15) */
+  x2 -= x6;
+  x6 <<= 1;
+
+  /* 2-point IDCT of x2 and x6 and post-multiplication as in (15) */
+  SBC_IDCT_MULT(SBC_COS_PI_SUR_4, x6, x6); /*x6 = x6 * cos(1*pi/4) ; */
+  temp = x2;
+  SBC_IDCT_MULT(SBC_COS_PI_SUR_8, (x2 + x6), x2);    /*x2 = ( x2 + x6 ) * cos(1*pi/8) ; */
+  SBC_IDCT_MULT(SBC_COS_3PI_SUR_8, (temp - x6), x6); /*x6 = ( temp - x6 ) * cos(3*pi/8) ;*/
+
+  /* 4-point IDCT of x0,x2,x4 and x6 as in (11) */
+  res_even[0] = x0 + x2;
+  res_even[1] = x4 + x6;
+  res_even[2] = x4 - x6;
+  res_even[3] = x0 - x2;
+
+  /* rearrangement of x1,x3,x5,x7 as in (15) */
+  x7 <<= 1;
+  x5 = (x5 << 1) - x7;
+  x3 = (x3 << 1) - x5;
+  x1 -= x3 >> 1;
+
+  /* two-dimensional IDCT of x1 and x5 */
+  SBC_IDCT_MULT(SBC_COS_PI_SUR_4, x5, x5); /*x5 = x5 * cos(1*pi/4) ; */
+  temp = x1;
+  x1   = x1 + x5;
+  x5   = temp - x5;
+
+  /* rearrangement of x3 and x7 as in (15) */
+  x3 -= x7;
+  x7 <<= 1;
+  SBC_IDCT_MULT(SBC_COS_PI_SUR_4, x7, x7); /*x7 = x7 * cos(1*pi/4) ; */
+
+  /* 2-point IDCT of x3 and x7 and post-multiplication as in (15) */
+  temp = x3;
+  SBC_IDCT_MULT(SBC_COS_PI_SUR_8, (x3 + x7), x3);    /*x3 = ( x3 + x7 ) * cos(1*pi/8)  ; */
+  SBC_IDCT_MULT(SBC_COS_3PI_SUR_8, (temp - x7), x7); /*x7 = ( temp - x7 ) * cos(3*pi/8) ;*/
+
+  /* 4-point IDCT of x1,x3,x5 and x7 and post multiplication by diagonal matrix as in (14) */
+  SBC_IDCT_MULT((SBC_COS_PI_SUR_16), (x1 + x3), res_odd[0]);  /*res_odd[ 0 ] = ( x1 + x3 ) * cos(1*pi/16) ; */
+  SBC_IDCT_MULT((SBC_COS_3PI_SUR_16), (x5 + x7), res_odd[1]); /*res_odd[ 1 ] = ( x5 + x7 ) * cos(3*pi/16) ; */
+  SBC_IDCT_MULT((SBC_COS_5PI_SUR_16), (x5 - x7), res_odd[2]); /*res_odd[ 2 ] = ( x5 - x7 ) * cos(5*pi/16) ; */
+  SBC_IDCT_MULT((SBC_COS_7PI_SUR_16), (x1 - x3), res_odd[3]); /*res_odd[ 3 ] = ( x1 - x3 ) * cos(7*pi/16) ; */
+
+  /* additions and subtractions as in (9) */
+  pOutVect[0] = (res_even[0] + res_odd[0]);
+  pOutVect[1] = (res_even[1] + res_odd[1]);
+  pOutVect[2] = (res_even[2] + res_odd[2]);
+  pOutVect[3] = (res_even[3] + res_odd[3]);
+  pOutVect[7] = (res_even[0] - res_odd[0]);
+  pOutVect[6] = (res_even[1] - res_odd[1]);
+  pOutVect[5] = (res_even[2] - res_odd[2]);
+  pOutVect[4] = (res_even[3] - res_odd[3]);
 #else
-    UINT8 Index, k;
-    SINT32 temp;
-    /*Calculate 4 subband samples by matrixing*/
-    for (Index = 0; Index < 8; Index++) {
-        temp = 0;
-        for (k = 0; k < 16; k++) {
-            /*temp += (SINT32)(((SINT64)M[(Index*strEncParams->numOfSubBands*2)+k] * Y[k]) >> 16 );*/
-            temp += (gas16AnalDCTcoeff8[(Index * 8 * 2) + k] * (pInVect[k] >> 16));
-            temp += ((gas16AnalDCTcoeff8[(Index * 8 * 2) + k] * (pInVect[k] & 0xFFFF)) >> 16);
-        }
-        pOutVect[Index] = temp;
+  UINT8  Index, k;
+  SINT32 temp;
+  /*Calculate 4 subband samples by matrixing*/
+  for (Index = 0; Index < 8; Index++) {
+    temp = 0;
+    for (k = 0; k < 16; k++) {
+      /*temp += (SINT32)(((SINT64)M[(Index*strEncParams->numOfSubBands*2)+k] * Y[k]) >> 16 );*/
+      temp += (gas16AnalDCTcoeff8[(Index * 8 * 2) + k] * (pInVect[k] >> 16));
+      temp += ((gas16AnalDCTcoeff8[(Index * 8 * 2) + k] * (pInVect[k] & 0xFFFF)) >> 16);
     }
+    pOutVect[Index] = temp;
+  }
 #endif
-    /*    BT_WARN("pOutVect: 0x%x;0x%x;0x%x;0x%x;0x%x;0x%x;0x%x;0x%x\n",\
-            pOutVect[0],pOutVect[1],pOutVect[2],pOutVect[3],pOutVect[4],pOutVect[5],pOutVect[6],pOutVect[7]);*/
+  /*    BT_WARN("pOutVect: 0x%x;0x%x;0x%x;0x%x;0x%x;0x%x;0x%x;0x%x\n",\
+          pOutVect[0],pOutVect[1],pOutVect[2],pOutVect[3],pOutVect[4],pOutVect[5],pOutVect[6],pOutVect[7]);*/
 }
 
 /*******************************************************************************
@@ -184,57 +183,56 @@ void SBC_FastIDCT8(SINT32 *pInVect, SINT32 *pOutVect)
 **
 **
 *******************************************************************************/
-void SBC_FastIDCT4(SINT32 *pInVect, SINT32 *pOutVect)
-{
+void SBC_FastIDCT4(SINT32 *pInVect, SINT32 *pOutVect) {
 #if (SBC_FAST_DCT == TRUE)
 #if (SBC_ARM_ASM_OPT == TRUE)
 #else
 #if (SBC_IPAQ_OPT == TRUE)
 #if (SBC_IS_64_MULT_IN_IDCT == TRUE)
-    SINT64 s64Temp;
+  SINT64 s64Temp;
 #endif
 #else
 #if (SBC_IS_64_MULT_IN_IDCT == TRUE)
-    SINT32 s32HiTemp;
+  SINT32 s32HiTemp;
 #else
-    UINT16 s32In2Temp;
-    SINT32 s32In1Temp;
+  UINT16 s32In2Temp;
+  SINT32 s32In1Temp;
 #endif
 #endif
 #endif
-    SINT32 temp, x2;
-    SINT32 tmp[8];
-
-    x2 = pInVect[2] >> 1;
-    temp = (pInVect[0] + pInVect[4]);
-    SBC_IDCT_MULT((SBC_COS_PI_SUR_4 >> 1), temp, tmp[0]);
-    tmp[1] = x2 - tmp[0];
-    tmp[0] += x2;
-    temp = (pInVect[1] + pInVect[3]);
-    SBC_IDCT_MULT((SBC_COS_3PI_SUR_8 >> 1), temp, tmp[3]);
-    SBC_IDCT_MULT((SBC_COS_PI_SUR_8 >> 1), temp, tmp[2]);
-    temp = (pInVect[5] - pInVect[7]);
-    SBC_IDCT_MULT((SBC_COS_3PI_SUR_8 >> 1), temp, tmp[5]);
-    SBC_IDCT_MULT((SBC_COS_PI_SUR_8 >> 1), temp, tmp[4]);
-    tmp[6] = tmp[2] + tmp[5];
-    tmp[7] = tmp[3] - tmp[4];
-    pOutVect[0] = (tmp[0] + tmp[6]);
-    pOutVect[1] = (tmp[1] + tmp[7]);
-    pOutVect[2] = (tmp[1] - tmp[7]);
-    pOutVect[3] = (tmp[0] - tmp[6]);
+  SINT32 temp, x2;
+  SINT32 tmp[8];
+
+  x2   = pInVect[2] >> 1;
+  temp = (pInVect[0] + pInVect[4]);
+  SBC_IDCT_MULT((SBC_COS_PI_SUR_4 >> 1), temp, tmp[0]);
+  tmp[1] = x2 - tmp[0];
+  tmp[0] += x2;
+  temp = (pInVect[1] + pInVect[3]);
+  SBC_IDCT_MULT((SBC_COS_3PI_SUR_8 >> 1), temp, tmp[3]);
+  SBC_IDCT_MULT((SBC_COS_PI_SUR_8 >> 1), temp, tmp[2]);
+  temp = (pInVect[5] - pInVect[7]);
+  SBC_IDCT_MULT((SBC_COS_3PI_SUR_8 >> 1), temp, tmp[5]);
+  SBC_IDCT_MULT((SBC_COS_PI_SUR_8 >> 1), temp, tmp[4]);
+  tmp[6]      = tmp[2] + tmp[5];
+  tmp[7]      = tmp[3] - tmp[4];
+  pOutVect[0] = (tmp[0] + tmp[6]);
+  pOutVect[1] = (tmp[1] + tmp[7]);
+  pOutVect[2] = (tmp[1] - tmp[7]);
+  pOutVect[3] = (tmp[0] - tmp[6]);
 #else
-    UINT8 Index, k;
-    SINT32 temp;
-    /*Calculate 4 subband samples by matrixing*/
-    for (Index = 0; Index < 4; Index++) {
-        temp = 0;
-        for (k = 0; k < 8; k++) {
-            /*temp += (SINT32)(((SINT64)M[(Index*strEncParams->numOfSubBands*2)+k] * Y[k]) >> 16 ); */
-            temp += (gas16AnalDCTcoeff4[(Index * 4 * 2) + k] * (pInVect[k] >> 16));
-            temp += ((gas16AnalDCTcoeff4[(Index * 4 * 2) + k] * (pInVect[k] & 0xFFFF)) >> 16);
-        }
-        pOutVect[Index] = temp;
+  UINT8  Index, k;
+  SINT32 temp;
+  /*Calculate 4 subband samples by matrixing*/
+  for (Index = 0; Index < 4; Index++) {
+    temp = 0;
+    for (k = 0; k < 8; k++) {
+      /*temp += (SINT32)(((SINT64)M[(Index*strEncParams->numOfSubBands*2)+k] * Y[k]) >> 16 ); */
+      temp += (gas16AnalDCTcoeff4[(Index * 4 * 2) + k] * (pInVect[k] >> 16));
+      temp += ((gas16AnalDCTcoeff4[(Index * 4 * 2) + k] * (pInVect[k] & 0xFFFF)) >> 16);
     }
+    pOutVect[Index] = temp;
+  }
 #endif
 }
 
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct_coeffs.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct_coeffs.c
index 800a722a95..30894fca6d 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct_coeffs.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct_coeffs.c
@@ -29,175 +29,39 @@
 
 /*DCT coeff for 4 sub-band case.*/
 #if (SBC_FAST_DCT == FALSE)
-const SINT16 gas16AnalDCTcoeff4[] = {
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(0.0000 * 32768),
-    (SINT16)(-0.3827 * 32768),
+const SINT16 gas16AnalDCTcoeff4[] = {(SINT16)(0.7071 * 32768),  (SINT16)(0.9239 * 32768),  (SINT16)(1.0000 * 32767),  (SINT16)(0.9239 * 32768),
+                                     (SINT16)(0.7071 * 32768),  (SINT16)(0.3827 * 32768),  (SINT16)(0.0000 * 32768),  (SINT16)(-0.3827 * 32768),
 
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(-0.0000 * 32768),
-    (SINT16)(0.9239 * 32768),
+                                     (SINT16)(-0.7071 * 32768), (SINT16)(0.3827 * 32768),  (SINT16)(1.0000 * 32767),  (SINT16)(0.3827 * 32768),
+                                     (SINT16)(-0.7071 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(-0.0000 * 32768), (SINT16)(0.9239 * 32768),
 
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(0.0000 * 32768),
-    (SINT16)(-0.9239 * 32768),
+                                     (SINT16)(-0.7071 * 32768), (SINT16)(-0.3827 * 32768), (SINT16)(1.0000 * 32767),  (SINT16)(-0.3827 * 32768),
+                                     (SINT16)(-0.7071 * 32768), (SINT16)(0.9239 * 32768),  (SINT16)(0.0000 * 32768),  (SINT16)(-0.9239 * 32768),
 
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(-0.0000 * 32768),
-    (SINT16)(0.3827 * 32768)
-};
+                                     (SINT16)(0.7071 * 32768),  (SINT16)(-0.9239 * 32768), (SINT16)(1.0000 * 32767),  (SINT16)(-0.9239 * 32768),
+                                     (SINT16)(0.7071 * 32768),  (SINT16)(-0.3827 * 32768), (SINT16)(-0.0000 * 32768), (SINT16)(0.3827 * 32768)};
 
 /*DCT coeff for 8 sub-band case.*/
-const SINT16 gas16AnalDCTcoeff8[] = {
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(0.5556 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(0.0000 * 32768),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(-0.0000 * 32768),
-    (SINT16)(0.5556 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(0.5556 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(0.5556 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(0.0000 * 32768),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(-0.0000 * 32768),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(0.5556 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(0.5556 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(0.0000 * 32768),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(-0.0000 * 32768),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(0.5556 * 32768),
-    (SINT16)(-0.0000 * 32768),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(-0.0000 * 32768),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(0.5556 * 32768)
-};
+const SINT16 gas16AnalDCTcoeff8[]
+    = {(SINT16)(0.7071 * 32768),  (SINT16)(0.8315 * 32768),  (SINT16)(0.9239 * 32768),  (SINT16)(0.9808 * 32768),  (SINT16)(1.0000 * 32767),  (SINT16)(0.9808 * 32768),  (SINT16)(0.9239 * 32768),
+       (SINT16)(0.8315 * 32768),  (SINT16)(0.7071 * 32768),  (SINT16)(0.5556 * 32768),  (SINT16)(0.3827 * 32768),  (SINT16)(0.1951 * 32768),  (SINT16)(0.0000 * 32768),  (SINT16)(-0.1951 * 32768),
+       (SINT16)(-0.3827 * 32768), (SINT16)(-0.5556 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(0.3827 * 32768),  (SINT16)(0.8315 * 32768),  (SINT16)(1.0000 * 32767),
+       (SINT16)(0.8315 * 32768),  (SINT16)(0.3827 * 32768),  (SINT16)(-0.1951 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(-0.9808 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(-0.5556 * 32768),
+       (SINT16)(-0.0000 * 32768), (SINT16)(0.5556 * 32768),  (SINT16)(0.9239 * 32768),  (SINT16)(0.9808 * 32768),  (SINT16)(-0.7071 * 32768), (SINT16)(-0.9808 * 32768), (SINT16)(-0.3827 * 32768),
+       (SINT16)(0.5556 * 32768),  (SINT16)(1.0000 * 32767),  (SINT16)(0.5556 * 32768),  (SINT16)(-0.3827 * 32768), (SINT16)(-0.9808 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(0.1951 * 32768),
+       (SINT16)(0.9239 * 32768),  (SINT16)(0.8315 * 32768),  (SINT16)(0.0000 * 32768),  (SINT16)(-0.8315 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(0.7071 * 32768),
+       (SINT16)(-0.5556 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(0.1951 * 32768),  (SINT16)(1.0000 * 32767),  (SINT16)(0.1951 * 32768),  (SINT16)(-0.9239 * 32768), (SINT16)(-0.5556 * 32768),
+       (SINT16)(0.7071 * 32768),  (SINT16)(0.8315 * 32768),  (SINT16)(-0.3827 * 32768), (SINT16)(-0.9808 * 32768), (SINT16)(-0.0000 * 32768), (SINT16)(0.9808 * 32768),  (SINT16)(0.3827 * 32768),
+       (SINT16)(-0.8315 * 32768), (SINT16)(0.7071 * 32768),  (SINT16)(0.5556 * 32768),  (SINT16)(-0.9239 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(1.0000 * 32767),  (SINT16)(-0.1951 * 32768),
+       (SINT16)(-0.9239 * 32768), (SINT16)(0.5556 * 32768),  (SINT16)(0.7071 * 32768),  (SINT16)(-0.8315 * 32768), (SINT16)(-0.3827 * 32768), (SINT16)(0.9808 * 32768),  (SINT16)(0.0000 * 32768),
+       (SINT16)(-0.9808 * 32768), (SINT16)(0.3827 * 32768),  (SINT16)(0.8315 * 32768),  (SINT16)(-0.7071 * 32768), (SINT16)(0.9808 * 32768),  (SINT16)(-0.3827 * 32768), (SINT16)(-0.5556 * 32768),
+       (SINT16)(1.0000 * 32767),  (SINT16)(-0.5556 * 32768), (SINT16)(-0.3827 * 32768), (SINT16)(0.9808 * 32768),  (SINT16)(-0.7071 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(0.9239 * 32768),
+       (SINT16)(-0.8315 * 32768), (SINT16)(-0.0000 * 32768), (SINT16)(0.8315 * 32768),  (SINT16)(-0.9239 * 32768), (SINT16)(0.1951 * 32768),  (SINT16)(-0.7071 * 32768), (SINT16)(0.1951 * 32768),
+       (SINT16)(0.3827 * 32768),  (SINT16)(-0.8315 * 32768), (SINT16)(1.0000 * 32767),  (SINT16)(-0.8315 * 32768), (SINT16)(0.3827 * 32768),  (SINT16)(0.1951 * 32768),  (SINT16)(-0.7071 * 32768),
+       (SINT16)(0.9808 * 32768),  (SINT16)(-0.9239 * 32768), (SINT16)(0.5556 * 32768),  (SINT16)(-0.0000 * 32768), (SINT16)(-0.5556 * 32768), (SINT16)(0.9239 * 32768),  (SINT16)(-0.9808 * 32768),
+       (SINT16)(0.7071 * 32768),  (SINT16)(-0.8315 * 32768), (SINT16)(0.9239 * 32768),  (SINT16)(-0.9808 * 32768), (SINT16)(1.0000 * 32767),  (SINT16)(-0.9808 * 32768), (SINT16)(0.9239 * 32768),
+       (SINT16)(-0.8315 * 32768), (SINT16)(0.7071 * 32768),  (SINT16)(-0.5556 * 32768), (SINT16)(0.3827 * 32768),  (SINT16)(-0.1951 * 32768), (SINT16)(-0.0000 * 32768), (SINT16)(0.1951 * 32768),
+       (SINT16)(-0.3827 * 32768), (SINT16)(0.5556 * 32768)};
 #endif
 
 #endif /* #if defined(SBC_ENC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_mono.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_mono.c
index 06af17a400..25d3fb4a39 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_mono.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_mono.c
@@ -24,159 +24,149 @@
  ******************************************************************************/
 
 /*Includes*/
-#include "sbc_encoder.h"
 #include "sbc_enc_func_declare.h"
+#include "sbc_encoder.h"
 
 #if defined(SBC_ENC_INCLUDED)
 
 /*global arrays*/
-const SINT16 sbc_enc_as16Offset4[4][4] = { { -1, 0, 0, 0 }, { -2, 0, 0, 1 }, { -2, 0, 0, 1 }, { -2, 0, 0, 1 } };
-const SINT16 sbc_enc_as16Offset8[4][8] = { { -2, 0, 0, 0, 0, 0, 0, 1 },
-                                           { -3, 0, 0, 0, 0, 0, 1, 2 },
-                                           { -4, 0, 0, 0, 0, 0, 1, 2 },
-                                           { -4, 0, 0, 0, 0, 0, 1, 2 } };
+const SINT16 sbc_enc_as16Offset4[4][4] = {{-1, 0, 0, 0}, {-2, 0, 0, 1}, {-2, 0, 0, 1}, {-2, 0, 0, 1}};
+const SINT16 sbc_enc_as16Offset8[4][8] = {{-2, 0, 0, 0, 0, 0, 0, 1}, {-3, 0, 0, 0, 0, 0, 1, 2}, {-4, 0, 0, 0, 0, 0, 1, 2}, {-4, 0, 0, 0, 0, 0, 1, 2}};
 
 /****************************************************************************
-* BitAlloc - Calculates the required number of bits for the given scale factor
-* and the number of subbands.
-*
-* RETURNS : N/A
-*/
-
-void sbc_enc_bit_alloc_mono(SBC_ENC_PARAMS *pstrCodecParams)
-{
-    SINT32 s32MaxBitNeed; /*to store the max bits needed per sb*/
-    SINT32 s32BitCount;   /*the used number of bits*/
-    SINT32 s32SliceCount; /*to store hwo many slices can be put in bitpool*/
-    SINT32 s32BitSlice;   /*number of bitslices in bitpool*/
-    SINT32 s32Sb;         /*counter for sub-band*/
-    SINT32 s32Ch;         /*counter for channel*/
-    SINT16 *ps16BitNeed;  /*temp memory to store required number of bits*/
-    SINT32 s32Loudness;   /*used in Loudness calculation*/
-    SINT16 *ps16GenBufPtr;
-    SINT16 *ps16GenArrPtr;
-    SINT16 *ps16GenTabPtr;
-    SINT32 s32NumOfSubBands = pstrCodecParams->s16NumOfSubBands;
-
-    ps16BitNeed = pstrCodecParams->s16ScartchMemForBitAlloc;
-
-    for (s32Ch = 0; s32Ch < pstrCodecParams->s16NumOfChannels; s32Ch++) {
-        ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
-        ps16GenArrPtr = pstrCodecParams->as16Bits + s32Ch * SBC_MAX_NUM_OF_SUBBANDS;
-
-        /* bitneed values are derived from scale factor */
-        if (pstrCodecParams->s16AllocationMethod == SBC_SNR) {
-            ps16BitNeed = pstrCodecParams->as16ScaleFactor;
-            ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
+ * BitAlloc - Calculates the required number of bits for the given scale factor
+ * and the number of subbands.
+ *
+ * RETURNS : N/A
+ */
+
+void sbc_enc_bit_alloc_mono(SBC_ENC_PARAMS *pstrCodecParams) {
+  SINT32  s32MaxBitNeed; /*to store the max bits needed per sb*/
+  SINT32  s32BitCount;   /*the used number of bits*/
+  SINT32  s32SliceCount; /*to store hwo many slices can be put in bitpool*/
+  SINT32  s32BitSlice;   /*number of bitslices in bitpool*/
+  SINT32  s32Sb;         /*counter for sub-band*/
+  SINT32  s32Ch;         /*counter for channel*/
+  SINT16 *ps16BitNeed;   /*temp memory to store required number of bits*/
+  SINT32  s32Loudness;   /*used in Loudness calculation*/
+  SINT16 *ps16GenBufPtr;
+  SINT16 *ps16GenArrPtr;
+  SINT16 *ps16GenTabPtr;
+  SINT32  s32NumOfSubBands = pstrCodecParams->s16NumOfSubBands;
+
+  ps16BitNeed = pstrCodecParams->s16ScartchMemForBitAlloc;
+
+  for (s32Ch = 0; s32Ch < pstrCodecParams->s16NumOfChannels; s32Ch++) {
+    ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
+    ps16GenArrPtr = pstrCodecParams->as16Bits + s32Ch * SBC_MAX_NUM_OF_SUBBANDS;
+
+    /* bitneed values are derived from scale factor */
+    if (pstrCodecParams->s16AllocationMethod == SBC_SNR) {
+      ps16BitNeed   = pstrCodecParams->as16ScaleFactor;
+      ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
+    } else {
+      ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
+      if (s32NumOfSubBands == 4) {
+        ps16GenTabPtr = (SINT16 *)sbc_enc_as16Offset4[pstrCodecParams->s16SamplingFreq];
+      } else {
+        ps16GenTabPtr = (SINT16 *)sbc_enc_as16Offset8[pstrCodecParams->s16SamplingFreq];
+      }
+      for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
+        if (pstrCodecParams->as16ScaleFactor[s32Ch * s32NumOfSubBands + s32Sb] == 0) {
+          *(ps16GenBufPtr) = -5;
         } else {
-            ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
-            if (s32NumOfSubBands == 4) {
-                ps16GenTabPtr = (SINT16 *)
-                    sbc_enc_as16Offset4[pstrCodecParams->s16SamplingFreq];
-            } else {
-                ps16GenTabPtr = (SINT16 *)
-                    sbc_enc_as16Offset8[pstrCodecParams->s16SamplingFreq];
-            }
-            for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
-                if (pstrCodecParams->as16ScaleFactor[s32Ch * s32NumOfSubBands + s32Sb] == 0) {
-                    *(ps16GenBufPtr) = -5;
-                } else {
-                    s32Loudness =
-                        (SINT32)(pstrCodecParams->as16ScaleFactor[s32Ch * s32NumOfSubBands + s32Sb] - *ps16GenTabPtr);
-                    if (s32Loudness > 0) {
-                        *(ps16GenBufPtr) = (SINT16)(s32Loudness >> 1);
-                    } else {
-                        *(ps16GenBufPtr) = (SINT16)s32Loudness;
-                    }
-                }
-                ps16GenBufPtr++;
-                ps16GenTabPtr++;
-            }
+          s32Loudness = (SINT32)(pstrCodecParams->as16ScaleFactor[s32Ch * s32NumOfSubBands + s32Sb] - *ps16GenTabPtr);
+          if (s32Loudness > 0) {
+            *(ps16GenBufPtr) = (SINT16)(s32Loudness >> 1);
+          } else {
+            *(ps16GenBufPtr) = (SINT16)s32Loudness;
+          }
         }
+        ps16GenBufPtr++;
+        ps16GenTabPtr++;
+      }
+    }
 
-        /* max bitneed index is searched*/
-        s32MaxBitNeed = 0;
-        ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
-        for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
-            if (*(ps16GenBufPtr) > s32MaxBitNeed) {
-                s32MaxBitNeed = *(ps16GenBufPtr);
-            }
+    /* max bitneed index is searched*/
+    s32MaxBitNeed = 0;
+    ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
+    for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
+      if (*(ps16GenBufPtr) > s32MaxBitNeed) {
+        s32MaxBitNeed = *(ps16GenBufPtr);
+      }
 
-            ps16GenBufPtr++;
-        }
-        ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
-        /*iterative process to find hwo many bitslices fit into the bitpool*/
-        s32BitSlice = s32MaxBitNeed + 1;
-        s32BitCount = pstrCodecParams->s16BitPool;
-        s32SliceCount = 0;
-        do {
-            s32BitSlice--;
-            s32BitCount -= s32SliceCount;
-            s32SliceCount = 0;
-
-            for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
-                if ((((*ps16GenBufPtr - s32BitSlice) < 16) && (*ps16GenBufPtr - s32BitSlice) >= 1)) {
-                    if ((*ps16GenBufPtr - s32BitSlice) == 1) {
-                        s32SliceCount += 2;
-                    } else {
-                        s32SliceCount++;
-                    }
-                }
-                ps16GenBufPtr++;
-
-            } /*end of for*/
-            ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
-        } while (s32BitCount - s32SliceCount > 0);
-
-        if (s32BitCount == 0) {
-            s32BitCount -= s32SliceCount;
-            s32BitSlice--;
+      ps16GenBufPtr++;
+    }
+    ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
+    /*iterative process to find hwo many bitslices fit into the bitpool*/
+    s32BitSlice   = s32MaxBitNeed + 1;
+    s32BitCount   = pstrCodecParams->s16BitPool;
+    s32SliceCount = 0;
+    do {
+      s32BitSlice--;
+      s32BitCount -= s32SliceCount;
+      s32SliceCount = 0;
+
+      for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
+        if ((((*ps16GenBufPtr - s32BitSlice) < 16) && (*ps16GenBufPtr - s32BitSlice) >= 1)) {
+          if ((*ps16GenBufPtr - s32BitSlice) == 1) {
+            s32SliceCount += 2;
+          } else {
+            s32SliceCount++;
+          }
         }
+        ps16GenBufPtr++;
 
-        /*Bits are distributed until the last bitslice is reached*/
-        ps16GenArrPtr = pstrCodecParams->as16Bits + s32Ch * s32NumOfSubBands;
-        ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
-        for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
-            if (*(ps16GenBufPtr) < s32BitSlice + 2) {
-                *(ps16GenArrPtr) = 0;
-            } else {
-                *(ps16GenArrPtr) = ((*(ps16GenBufPtr)-s32BitSlice) < 16) ?
-                                       (SINT16)(*(ps16GenBufPtr)-s32BitSlice) :
-                                       16;
-            }
-
-            ps16GenBufPtr++;
-            ps16GenArrPtr++;
-        }
-        ps16GenArrPtr = pstrCodecParams->as16Bits + s32Ch * s32NumOfSubBands;
-        ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
-        /*the remaining bits are allocated starting at subband 0*/
-        s32Sb = 0;
-        while ((s32BitCount > 0) && (s32Sb < s32NumOfSubBands)) {
-            if ((*(ps16GenArrPtr) >= 2) && (*(ps16GenArrPtr) < 16)) {
-                (*(ps16GenArrPtr))++;
-                s32BitCount--;
-            } else if ((*(ps16GenBufPtr) == s32BitSlice + 1) &&
-                       (s32BitCount > 1)) {
-                *(ps16GenArrPtr) = 2;
-                s32BitCount -= 2;
-            }
-            s32Sb++;
-            ps16GenArrPtr++;
-            ps16GenBufPtr++;
-        }
-        ps16GenArrPtr = pstrCodecParams->as16Bits + s32Ch * s32NumOfSubBands;
-
-        s32Sb = 0;
-        while ((s32BitCount > 0) && (s32Sb < s32NumOfSubBands)) {
-            if (*(ps16GenArrPtr) < 16) {
-                (*(ps16GenArrPtr))++;
-                s32BitCount--;
-            }
-            s32Sb++;
-            ps16GenArrPtr++;
-        }
+      } /*end of for*/
+      ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
+    } while (s32BitCount - s32SliceCount > 0);
+
+    if (s32BitCount == 0) {
+      s32BitCount -= s32SliceCount;
+      s32BitSlice--;
+    }
+
+    /*Bits are distributed until the last bitslice is reached*/
+    ps16GenArrPtr = pstrCodecParams->as16Bits + s32Ch * s32NumOfSubBands;
+    ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
+    for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
+      if (*(ps16GenBufPtr) < s32BitSlice + 2) {
+        *(ps16GenArrPtr) = 0;
+      } else {
+        *(ps16GenArrPtr) = ((*(ps16GenBufPtr)-s32BitSlice) < 16) ? (SINT16)(*(ps16GenBufPtr)-s32BitSlice) : 16;
+      }
+
+      ps16GenBufPtr++;
+      ps16GenArrPtr++;
+    }
+    ps16GenArrPtr = pstrCodecParams->as16Bits + s32Ch * s32NumOfSubBands;
+    ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
+    /*the remaining bits are allocated starting at subband 0*/
+    s32Sb = 0;
+    while ((s32BitCount > 0) && (s32Sb < s32NumOfSubBands)) {
+      if ((*(ps16GenArrPtr) >= 2) && (*(ps16GenArrPtr) < 16)) {
+        (*(ps16GenArrPtr))++;
+        s32BitCount--;
+      } else if ((*(ps16GenBufPtr) == s32BitSlice + 1) && (s32BitCount > 1)) {
+        *(ps16GenArrPtr) = 2;
+        s32BitCount -= 2;
+      }
+      s32Sb++;
+      ps16GenArrPtr++;
+      ps16GenBufPtr++;
+    }
+    ps16GenArrPtr = pstrCodecParams->as16Bits + s32Ch * s32NumOfSubBands;
+
+    s32Sb = 0;
+    while ((s32BitCount > 0) && (s32Sb < s32NumOfSubBands)) {
+      if (*(ps16GenArrPtr) < 16) {
+        (*(ps16GenArrPtr))++;
+        s32BitCount--;
+      }
+      s32Sb++;
+      ps16GenArrPtr++;
     }
+  }
 }
 /*End of BitAlloc() function*/
 
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_ste.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_ste.c
index 5982461332..a59979232e 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_ste.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_ste.c
@@ -24,8 +24,8 @@
  ******************************************************************************/
 
 /*Includes*/
-#include "sbc_encoder.h"
 #include "sbc_enc_func_declare.h"
+#include "sbc_encoder.h"
 
 #if defined(SBC_ENC_INCLUDED)
 
@@ -34,158 +34,155 @@ extern const SINT16 sbc_enc_as16Offset4[4][4];
 extern const SINT16 sbc_enc_as16Offset8[4][8];
 
 /****************************************************************************
-* BitAlloc - Calculates the required number of bits for the given scale factor
-* and the number of subbands.
-*
-* RETURNS : N/A
-*/
-
-void sbc_enc_bit_alloc_ste(SBC_ENC_PARAMS *pstrCodecParams)
-{
-    /* CAUTIOM -> mips optim for arm 32 require to use SINT32 instead of SINT16 */
-    /* Do not change variable type or name */
-    SINT32 s32MaxBitNeed; /*to store the max bits needed per sb*/
-    SINT32 s32BitCount;   /*the used number of bits*/
-    SINT32 s32SliceCount; /*to store hwo many slices can be put in bitpool*/
-    SINT32 s32BitSlice;   /*number of bitslices in bitpool*/
-    SINT32 s32Sb;         /*counter for sub-band*/
-    SINT32 s32Ch;         /*counter for channel*/
-    SINT16 *ps16BitNeed;  /*temp memory to store required number of bits*/
-    SINT32 s32Loudness;   /*used in Loudness calculation*/
-    SINT16 *ps16GenBufPtr, *pas16ScaleFactor;
-    SINT16 *ps16GenArrPtr;
-    SINT16 *ps16GenTabPtr;
-    SINT32 s32NumOfSubBands = pstrCodecParams->s16NumOfSubBands;
-    SINT32 s32BitPool = pstrCodecParams->s16BitPool;
-
-    /* bitneed values are derived from scale factor */
-    if (pstrCodecParams->s16AllocationMethod == SBC_SNR) {
-        ps16BitNeed = pstrCodecParams->as16ScaleFactor;
-        s32MaxBitNeed = pstrCodecParams->s16MaxBitNeed;
-    } else {
-        ps16BitNeed = pstrCodecParams->s16ScartchMemForBitAlloc;
-        pas16ScaleFactor = pstrCodecParams->as16ScaleFactor;
-        s32MaxBitNeed = 0;
-        ps16GenBufPtr = ps16BitNeed;
-        for (s32Ch = 0; s32Ch < 2; s32Ch++) {
-            if (s32NumOfSubBands == 4) {
-                ps16GenTabPtr = (SINT16 *)sbc_enc_as16Offset4[pstrCodecParams->s16SamplingFreq];
-            } else {
-                ps16GenTabPtr = (SINT16 *)sbc_enc_as16Offset8[pstrCodecParams->s16SamplingFreq];
-            }
-
-            for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
-                if (*pas16ScaleFactor == 0) {
-                    *ps16GenBufPtr = -5;
-                } else {
-                    s32Loudness = (SINT32)(*pas16ScaleFactor - *ps16GenTabPtr);
-
-                    if (s32Loudness > 0) {
-                        *ps16GenBufPtr = (SINT16)(s32Loudness >> 1);
-                    } else {
-                        *ps16GenBufPtr = (SINT16)s32Loudness;
-                    }
-                }
-
-                if (*ps16GenBufPtr > s32MaxBitNeed) {
-                    s32MaxBitNeed = *ps16GenBufPtr;
-                }
-                pas16ScaleFactor++;
-                ps16GenBufPtr++;
-                ps16GenTabPtr++;
-            }
-        }
-    }
+ * BitAlloc - Calculates the required number of bits for the given scale factor
+ * and the number of subbands.
+ *
+ * RETURNS : N/A
+ */
+
+void sbc_enc_bit_alloc_ste(SBC_ENC_PARAMS *pstrCodecParams) {
+  /* CAUTIOM -> mips optim for arm 32 require to use SINT32 instead of SINT16 */
+  /* Do not change variable type or name */
+  SINT32  s32MaxBitNeed; /*to store the max bits needed per sb*/
+  SINT32  s32BitCount;   /*the used number of bits*/
+  SINT32  s32SliceCount; /*to store hwo many slices can be put in bitpool*/
+  SINT32  s32BitSlice;   /*number of bitslices in bitpool*/
+  SINT32  s32Sb;         /*counter for sub-band*/
+  SINT32  s32Ch;         /*counter for channel*/
+  SINT16 *ps16BitNeed;   /*temp memory to store required number of bits*/
+  SINT32  s32Loudness;   /*used in Loudness calculation*/
+  SINT16 *ps16GenBufPtr, *pas16ScaleFactor;
+  SINT16 *ps16GenArrPtr;
+  SINT16 *ps16GenTabPtr;
+  SINT32  s32NumOfSubBands = pstrCodecParams->s16NumOfSubBands;
+  SINT32  s32BitPool       = pstrCodecParams->s16BitPool;
+
+  /* bitneed values are derived from scale factor */
+  if (pstrCodecParams->s16AllocationMethod == SBC_SNR) {
+    ps16BitNeed   = pstrCodecParams->as16ScaleFactor;
+    s32MaxBitNeed = pstrCodecParams->s16MaxBitNeed;
+  } else {
+    ps16BitNeed      = pstrCodecParams->s16ScartchMemForBitAlloc;
+    pas16ScaleFactor = pstrCodecParams->as16ScaleFactor;
+    s32MaxBitNeed    = 0;
+    ps16GenBufPtr    = ps16BitNeed;
+    for (s32Ch = 0; s32Ch < 2; s32Ch++) {
+      if (s32NumOfSubBands == 4) {
+        ps16GenTabPtr = (SINT16 *)sbc_enc_as16Offset4[pstrCodecParams->s16SamplingFreq];
+      } else {
+        ps16GenTabPtr = (SINT16 *)sbc_enc_as16Offset8[pstrCodecParams->s16SamplingFreq];
+      }
+
+      for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
+        if (*pas16ScaleFactor == 0) {
+          *ps16GenBufPtr = -5;
+        } else {
+          s32Loudness = (SINT32)(*pas16ScaleFactor - *ps16GenTabPtr);
 
-    /* iterative process to find out hwo many bitslices fit into the bitpool */
-    s32BitSlice = s32MaxBitNeed + 1;
-    s32BitCount = s32BitPool;
-    s32SliceCount = 0;
-    do {
-        s32BitSlice--;
-        s32BitCount -= s32SliceCount;
-        s32SliceCount = 0;
-        ps16GenBufPtr = ps16BitNeed;
-
-        for (s32Sb = 0; s32Sb < 2 * s32NumOfSubBands; s32Sb++) {
-            if ((*ps16GenBufPtr >= s32BitSlice + 1) && (*ps16GenBufPtr < s32BitSlice + 16)) {
-                if (*(ps16GenBufPtr) == s32BitSlice + 1) {
-                    s32SliceCount += 2;
-                } else {
-                    s32SliceCount++;
-                }
-            }
-            ps16GenBufPtr++;
+          if (s32Loudness > 0) {
+            *ps16GenBufPtr = (SINT16)(s32Loudness >> 1);
+          } else {
+            *ps16GenBufPtr = (SINT16)s32Loudness;
+          }
         }
-    } while (s32BitCount - s32SliceCount > 0);
-
-    if (s32BitCount - s32SliceCount == 0) {
-        s32BitCount -= s32SliceCount;
-        s32BitSlice--;
-    }
 
-    /* Bits are distributed until the last bitslice is reached */
-    ps16GenBufPtr = ps16BitNeed;
-    ps16GenArrPtr = pstrCodecParams->as16Bits;
-    for (s32Ch = 0; s32Ch < 2; s32Ch++) {
-        for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
-            if (*ps16GenBufPtr < s32BitSlice + 2) {
-                *ps16GenArrPtr = 0;
-            } else {
-                *ps16GenArrPtr = ((*(ps16GenBufPtr)-s32BitSlice) < 16) ?
-                                     (SINT16)(*(ps16GenBufPtr)-s32BitSlice) :
-                                     16;
-            }
-            ps16GenBufPtr++;
-            ps16GenArrPtr++;
+        if (*ps16GenBufPtr > s32MaxBitNeed) {
+          s32MaxBitNeed = *ps16GenBufPtr;
         }
+        pas16ScaleFactor++;
+        ps16GenBufPtr++;
+        ps16GenTabPtr++;
+      }
     }
-
-    /* the remaining bits are allocated starting at subband 0 */
-    s32Ch = 0;
-    s32Sb = 0;
+  }
+
+  /* iterative process to find out hwo many bitslices fit into the bitpool */
+  s32BitSlice   = s32MaxBitNeed + 1;
+  s32BitCount   = s32BitPool;
+  s32SliceCount = 0;
+  do {
+    s32BitSlice--;
+    s32BitCount -= s32SliceCount;
+    s32SliceCount = 0;
     ps16GenBufPtr = ps16BitNeed;
-    ps16GenArrPtr -= 2 * s32NumOfSubBands;
-
-    while ((s32BitCount > 0) && (s32Sb < s32NumOfSubBands)) {
-        if ((*(ps16GenArrPtr) >= 2) && (*(ps16GenArrPtr) < 16)) {
-            (*(ps16GenArrPtr))++;
-            s32BitCount--;
-        } else if ((*ps16GenBufPtr == s32BitSlice + 1) && (s32BitCount > 1)) {
-            *(ps16GenArrPtr) = 2;
-            s32BitCount -= 2;
-        }
-        if (s32Ch == 1) {
-            s32Ch = 0;
-            s32Sb++;
-            ps16GenBufPtr = ps16BitNeed + s32Sb;
-            ps16GenArrPtr = pstrCodecParams->as16Bits + s32Sb;
 
+    for (s32Sb = 0; s32Sb < 2 * s32NumOfSubBands; s32Sb++) {
+      if ((*ps16GenBufPtr >= s32BitSlice + 1) && (*ps16GenBufPtr < s32BitSlice + 16)) {
+        if (*(ps16GenBufPtr) == s32BitSlice + 1) {
+          s32SliceCount += 2;
         } else {
-            s32Ch = 1;
-            ps16GenBufPtr = ps16BitNeed + s32NumOfSubBands + s32Sb;
-            ps16GenArrPtr = pstrCodecParams->as16Bits + s32NumOfSubBands + s32Sb;
+          s32SliceCount++;
         }
+      }
+      ps16GenBufPtr++;
+    }
+  } while (s32BitCount - s32SliceCount > 0);
+
+  if (s32BitCount - s32SliceCount == 0) {
+    s32BitCount -= s32SliceCount;
+    s32BitSlice--;
+  }
+
+  /* Bits are distributed until the last bitslice is reached */
+  ps16GenBufPtr = ps16BitNeed;
+  ps16GenArrPtr = pstrCodecParams->as16Bits;
+  for (s32Ch = 0; s32Ch < 2; s32Ch++) {
+    for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
+      if (*ps16GenBufPtr < s32BitSlice + 2) {
+        *ps16GenArrPtr = 0;
+      } else {
+        *ps16GenArrPtr = ((*(ps16GenBufPtr)-s32BitSlice) < 16) ? (SINT16)(*(ps16GenBufPtr)-s32BitSlice) : 16;
+      }
+      ps16GenBufPtr++;
+      ps16GenArrPtr++;
     }
+  }
+
+  /* the remaining bits are allocated starting at subband 0 */
+  s32Ch         = 0;
+  s32Sb         = 0;
+  ps16GenBufPtr = ps16BitNeed;
+  ps16GenArrPtr -= 2 * s32NumOfSubBands;
+
+  while ((s32BitCount > 0) && (s32Sb < s32NumOfSubBands)) {
+    if ((*(ps16GenArrPtr) >= 2) && (*(ps16GenArrPtr) < 16)) {
+      (*(ps16GenArrPtr))++;
+      s32BitCount--;
+    } else if ((*ps16GenBufPtr == s32BitSlice + 1) && (s32BitCount > 1)) {
+      *(ps16GenArrPtr) = 2;
+      s32BitCount -= 2;
+    }
+    if (s32Ch == 1) {
+      s32Ch = 0;
+      s32Sb++;
+      ps16GenBufPtr = ps16BitNeed + s32Sb;
+      ps16GenArrPtr = pstrCodecParams->as16Bits + s32Sb;
 
-    s32Ch = 0;
-    s32Sb = 0;
-    ps16GenArrPtr = pstrCodecParams->as16Bits;
+    } else {
+      s32Ch         = 1;
+      ps16GenBufPtr = ps16BitNeed + s32NumOfSubBands + s32Sb;
+      ps16GenArrPtr = pstrCodecParams->as16Bits + s32NumOfSubBands + s32Sb;
+    }
+  }
 
-    while ((s32BitCount > 0) && (s32Sb < s32NumOfSubBands)) {
-        if (*(ps16GenArrPtr) < 16) {
-            (*(ps16GenArrPtr))++;
-            s32BitCount--;
-        }
-        if (s32Ch == 1) {
-            s32Ch = 0;
-            s32Sb++;
-            ps16GenArrPtr = pstrCodecParams->as16Bits + s32Sb;
-        } else {
-            s32Ch = 1;
-            ps16GenArrPtr = pstrCodecParams->as16Bits + s32NumOfSubBands + s32Sb;
-        }
+  s32Ch         = 0;
+  s32Sb         = 0;
+  ps16GenArrPtr = pstrCodecParams->as16Bits;
+
+  while ((s32BitCount > 0) && (s32Sb < s32NumOfSubBands)) {
+    if (*(ps16GenArrPtr) < 16) {
+      (*(ps16GenArrPtr))++;
+      s32BitCount--;
+    }
+    if (s32Ch == 1) {
+      s32Ch = 0;
+      s32Sb++;
+      ps16GenArrPtr = pstrCodecParams->as16Bits + s32Sb;
+    } else {
+      s32Ch         = 1;
+      ps16GenArrPtr = pstrCodecParams->as16Bits + s32NumOfSubBands + s32Sb;
     }
+  }
 }
 
 /*End of BitAlloc() function*/
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_coeffs.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_coeffs.c
index 29dee97904..8600235a44 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_coeffs.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_coeffs.c
@@ -29,288 +29,120 @@
 #if (SBC_ARM_ASM_OPT == FALSE && SBC_IPAQ_OPT == FALSE)
 #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == FALSE)
 /*Window coeff for 4 sub band case*/
-const SINT16 gas32CoeffFor4SBs[] = {
-    (SINT16)((SINT32)0x00000000 >> 16), (SINT16)0x00000000,
-    (SINT16)((SINT32)0x001194E6 >> 16), (SINT16)0x001194E6,
-    (SINT16)((SINT32)0x0030E2D3 >> 16), (SINT16)0x0030E2D3,
-    (SINT16)((SINT32)0x00599403 >> 16), (SINT16)0x00599403,
-    (SINT16)((SINT32)0x007DBCC8 >> 16), (SINT16)0x007DBCC8,
-    (SINT16)((SINT32)0x007F88E4 >> 16), (SINT16)0x007F88E4,
-    (SINT16)((SINT32)0x003D239B >> 16), (SINT16)0x003D239B,
-    (SINT16)((SINT32)0xFF9BB9D5 >> 16), (SINT16)0xFF9BB9D5,
-
-    (SINT16)((SINT32)0x01659F45 >> 16), (SINT16)0x01659F45,
-    (SINT16)((SINT32)0x029DBAA3 >> 16), (SINT16)0x029DBAA3,
-    (SINT16)((SINT32)0x03B23341 >> 16), (SINT16)0x03B23341,
-    (SINT16)((SINT32)0x041EEE40 >> 16), (SINT16)0x041EEE40,
-    (SINT16)((SINT32)0x034FEE2C >> 16), (SINT16)0x034FEE2C,
-    (SINT16)((SINT32)0x00C8F2BC >> 16), (SINT16)0x00C8F2BC,
-    (SINT16)((SINT32)0xFC4F91D4 >> 16), (SINT16)0xFC4F91D4,
-    (SINT16)((SINT32)0xF60FAF37 >> 16), (SINT16)0xF60FAF37,
-
-    (SINT16)((SINT32)0x115B1ED2 >> 16), (SINT16)0x115B1ED2,
-    (SINT16)((SINT32)0x18F55C90 >> 16), (SINT16)0x18F55C90,
-    (SINT16)((SINT32)0x1F91CA46 >> 16), (SINT16)0x1F91CA46,
-    (SINT16)((SINT32)0x2412F251 >> 16), (SINT16)0x2412F251,
-    (SINT16)((SINT32)0x25AC1FF2 >> 16), (SINT16)0x25AC1FF2,
-    (SINT16)((SINT32)0x2412F251 >> 16), (SINT16)0x2412F251,
-    (SINT16)((SINT32)0x1F91CA46 >> 16), (SINT16)0x1F91CA46,
-    (SINT16)((SINT32)0x18F55C90 >> 16), (SINT16)0x18F55C90,
-
-    (SINT16)((SINT32)0xEEA4E12E >> 16), (SINT16)0xEEA4E12E,
-    (SINT16)((SINT32)0xF60FAF37 >> 16), (SINT16)0xF60FAF37,
-    (SINT16)((SINT32)0xFC4F91D4 >> 16), (SINT16)0xFC4F91D4,
-    (SINT16)((SINT32)0x00C8F2BC >> 16), (SINT16)0x00C8F2BC,
-    (SINT16)((SINT32)0x034FEE2C >> 16), (SINT16)0x034FEE2C,
-    (SINT16)((SINT32)0x041EEE40 >> 16), (SINT16)0x041EEE40,
-    (SINT16)((SINT32)0x03B23341 >> 16), (SINT16)0x03B23341,
-    (SINT16)((SINT32)0x029DBAA3 >> 16), (SINT16)0x029DBAA3,
-
-    (SINT16)((SINT32)0xFE9A60BB >> 16), (SINT16)0xFE9A60BB,
-    (SINT16)((SINT32)0xFF9BB9D5 >> 16), (SINT16)0xFF9BB9D5,
-    (SINT16)((SINT32)0x003D239B >> 16), (SINT16)0x003D239B,
-    (SINT16)((SINT32)0x007F88E4 >> 16), (SINT16)0x007F88E4,
-    (SINT16)((SINT32)0x007DBCC8 >> 16), (SINT16)0x007DBCC8,
-    (SINT16)((SINT32)0x00599403 >> 16), (SINT16)0x00599403,
-    (SINT16)((SINT32)0x0030E2D3 >> 16), (SINT16)0x0030E2D3,
-    (SINT16)((SINT32)0x001194E6 >> 16), (SINT16)0x001194E6
-};
+const SINT16 gas32CoeffFor4SBs[]
+    = {(SINT16)((SINT32)0x00000000 >> 16), (SINT16)0x00000000, (SINT16)((SINT32)0x001194E6 >> 16), (SINT16)0x001194E6, (SINT16)((SINT32)0x0030E2D3 >> 16), (SINT16)0x0030E2D3,
+       (SINT16)((SINT32)0x00599403 >> 16), (SINT16)0x00599403, (SINT16)((SINT32)0x007DBCC8 >> 16), (SINT16)0x007DBCC8, (SINT16)((SINT32)0x007F88E4 >> 16), (SINT16)0x007F88E4,
+       (SINT16)((SINT32)0x003D239B >> 16), (SINT16)0x003D239B, (SINT16)((SINT32)0xFF9BB9D5 >> 16), (SINT16)0xFF9BB9D5,
+
+       (SINT16)((SINT32)0x01659F45 >> 16), (SINT16)0x01659F45, (SINT16)((SINT32)0x029DBAA3 >> 16), (SINT16)0x029DBAA3, (SINT16)((SINT32)0x03B23341 >> 16), (SINT16)0x03B23341,
+       (SINT16)((SINT32)0x041EEE40 >> 16), (SINT16)0x041EEE40, (SINT16)((SINT32)0x034FEE2C >> 16), (SINT16)0x034FEE2C, (SINT16)((SINT32)0x00C8F2BC >> 16), (SINT16)0x00C8F2BC,
+       (SINT16)((SINT32)0xFC4F91D4 >> 16), (SINT16)0xFC4F91D4, (SINT16)((SINT32)0xF60FAF37 >> 16), (SINT16)0xF60FAF37,
+
+       (SINT16)((SINT32)0x115B1ED2 >> 16), (SINT16)0x115B1ED2, (SINT16)((SINT32)0x18F55C90 >> 16), (SINT16)0x18F55C90, (SINT16)((SINT32)0x1F91CA46 >> 16), (SINT16)0x1F91CA46,
+       (SINT16)((SINT32)0x2412F251 >> 16), (SINT16)0x2412F251, (SINT16)((SINT32)0x25AC1FF2 >> 16), (SINT16)0x25AC1FF2, (SINT16)((SINT32)0x2412F251 >> 16), (SINT16)0x2412F251,
+       (SINT16)((SINT32)0x1F91CA46 >> 16), (SINT16)0x1F91CA46, (SINT16)((SINT32)0x18F55C90 >> 16), (SINT16)0x18F55C90,
+
+       (SINT16)((SINT32)0xEEA4E12E >> 16), (SINT16)0xEEA4E12E, (SINT16)((SINT32)0xF60FAF37 >> 16), (SINT16)0xF60FAF37, (SINT16)((SINT32)0xFC4F91D4 >> 16), (SINT16)0xFC4F91D4,
+       (SINT16)((SINT32)0x00C8F2BC >> 16), (SINT16)0x00C8F2BC, (SINT16)((SINT32)0x034FEE2C >> 16), (SINT16)0x034FEE2C, (SINT16)((SINT32)0x041EEE40 >> 16), (SINT16)0x041EEE40,
+       (SINT16)((SINT32)0x03B23341 >> 16), (SINT16)0x03B23341, (SINT16)((SINT32)0x029DBAA3 >> 16), (SINT16)0x029DBAA3,
+
+       (SINT16)((SINT32)0xFE9A60BB >> 16), (SINT16)0xFE9A60BB, (SINT16)((SINT32)0xFF9BB9D5 >> 16), (SINT16)0xFF9BB9D5, (SINT16)((SINT32)0x003D239B >> 16), (SINT16)0x003D239B,
+       (SINT16)((SINT32)0x007F88E4 >> 16), (SINT16)0x007F88E4, (SINT16)((SINT32)0x007DBCC8 >> 16), (SINT16)0x007DBCC8, (SINT16)((SINT32)0x00599403 >> 16), (SINT16)0x00599403,
+       (SINT16)((SINT32)0x0030E2D3 >> 16), (SINT16)0x0030E2D3, (SINT16)((SINT32)0x001194E6 >> 16), (SINT16)0x001194E6};
 
 /*Window coeff for 8 sub band case*/
-const SINT16 gas32CoeffFor8SBs[] = {
-    (SINT16)((SINT32)0x00000000 >> 16), (SINT16)0x00000000,
-    (SINT16)((SINT32)0x00052173 >> 16), (SINT16)0x00052173,
-    (SINT16)((SINT32)0x000B3F71 >> 16), (SINT16)0x000B3F71,
-    (SINT16)((SINT32)0x00122C7D >> 16), (SINT16)0x00122C7D,
-    (SINT16)((SINT32)0x001AFF89 >> 16), (SINT16)0x001AFF89,
-    (SINT16)((SINT32)0x00255A62 >> 16), (SINT16)0x00255A62,
-    (SINT16)((SINT32)0x003060F4 >> 16), (SINT16)0x003060F4,
-    (SINT16)((SINT32)0x003A72E7 >> 16), (SINT16)0x003A72E7,
-
-    (SINT16)((SINT32)0x0041EC6A >> 16), (SINT16)0x0041EC6A, /* 8 */
-    (SINT16)((SINT32)0x0044EF48 >> 16), (SINT16)0x0044EF48,
-    (SINT16)((SINT32)0x00415B75 >> 16), (SINT16)0x00415B75,
-    (SINT16)((SINT32)0x0034F8B6 >> 16), (SINT16)0x0034F8B6,
-    (SINT16)((SINT32)0x001D8FD2 >> 16), (SINT16)0x001D8FD2,
-    (SINT16)((SINT32)0xFFFA2413 >> 16), (SINT16)0xFFFA2413,
-    (SINT16)((SINT32)0xFFC9F10E >> 16), (SINT16)0xFFC9F10E,
-    (SINT16)((SINT32)0xFF8D6793 >> 16), (SINT16)0xFF8D6793,
-
-    (SINT16)((SINT32)0x00B97348 >> 16), (SINT16)0x00B97348, /* 16 */
-    (SINT16)((SINT32)0x01071B96 >> 16), (SINT16)0x01071B96,
-    (SINT16)((SINT32)0x0156B3CA >> 16), (SINT16)0x0156B3CA,
-    (SINT16)((SINT32)0x01A1B38B >> 16), (SINT16)0x01A1B38B,
-    (SINT16)((SINT32)0x01E0224C >> 16), (SINT16)0x01E0224C,
-    (SINT16)((SINT32)0x0209291F >> 16), (SINT16)0x0209291F,
-    (SINT16)((SINT32)0x02138653 >> 16), (SINT16)0x02138653,
-    (SINT16)((SINT32)0x01F5F424 >> 16), (SINT16)0x01F5F424,
-
-    (SINT16)((SINT32)0x01A7ECEF >> 16), (SINT16)0x01A7ECEF, /* 24 */
-    (SINT16)((SINT32)0x01223EBA >> 16), (SINT16)0x01223EBA,
-    (SINT16)((SINT32)0x005FD0FF >> 16), (SINT16)0x005FD0FF,
-    (SINT16)((SINT32)0xFF5EEB73 >> 16), (SINT16)0xFF5EEB73,
-    (SINT16)((SINT32)0xFE20435D >> 16), (SINT16)0xFE20435D,
-    (SINT16)((SINT32)0xFCA86E7E >> 16), (SINT16)0xFCA86E7E,
-    (SINT16)((SINT32)0xFAFF95FC >> 16), (SINT16)0xFAFF95FC,
-    (SINT16)((SINT32)0xF9312891 >> 16), (SINT16)0xF9312891,
-
-    (SINT16)((SINT32)0x08B4307A >> 16), (SINT16)0x08B4307A, /* 32 */
-    (SINT16)((SINT32)0x0A9F3E9A >> 16), (SINT16)0x0A9F3E9A,
-    (SINT16)((SINT32)0x0C7D59B6 >> 16), (SINT16)0x0C7D59B6,
-    (SINT16)((SINT32)0x0E3BB16F >> 16), (SINT16)0x0E3BB16F,
-    (SINT16)((SINT32)0x0FC721F9 >> 16), (SINT16)0x0FC721F9,
-    (SINT16)((SINT32)0x110ECEF0 >> 16), (SINT16)0x110ECEF0,
-    (SINT16)((SINT32)0x120435FA >> 16), (SINT16)0x120435FA,
-    (SINT16)((SINT32)0x129C226F >> 16), (SINT16)0x129C226F,
-
-    (SINT16)((SINT32)0x12CF6C75 >> 16), (SINT16)0x12CF6C75, /* 40 */
-    (SINT16)((SINT32)0x129C226F >> 16), (SINT16)0x129C226F,
-    (SINT16)((SINT32)0x120435FA >> 16), (SINT16)0x120435FA,
-    (SINT16)((SINT32)0x110ECEF0 >> 16), (SINT16)0x110ECEF0,
-    (SINT16)((SINT32)0x0FC721F9 >> 16), (SINT16)0x0FC721F9,
-    (SINT16)((SINT32)0x0E3BB16F >> 16), (SINT16)0x0E3BB16F,
-    (SINT16)((SINT32)0x0C7D59B6 >> 16), (SINT16)0x0C7D59B6,
-    (SINT16)((SINT32)0x0A9F3E9A >> 16), (SINT16)0x0A9F3E9A,
-
-    (SINT16)((SINT32)0xF74BCF86 >> 16), (SINT16)0xF74BCF86, /* 48 */
-    (SINT16)((SINT32)0xF9312891 >> 16), (SINT16)0xF9312891,
-    (SINT16)((SINT32)0xFAFF95FC >> 16), (SINT16)0xFAFF95FC,
-    (SINT16)((SINT32)0xFCA86E7E >> 16), (SINT16)0xFCA86E7E,
-    (SINT16)((SINT32)0xFE20435D >> 16), (SINT16)0xFE20435D,
-    (SINT16)((SINT32)0xFF5EEB73 >> 16), (SINT16)0xFF5EEB73,
-    (SINT16)((SINT32)0x005FD0FF >> 16), (SINT16)0x005FD0FF,
-    (SINT16)((SINT32)0x01223EBA >> 16), (SINT16)0x01223EBA,
-
-    (SINT16)((SINT32)0x01A7ECEF >> 16), (SINT16)0x01A7ECEF, /* 56 */
-    (SINT16)((SINT32)0x01F5F424 >> 16), (SINT16)0x01F5F424,
-    (SINT16)((SINT32)0x02138653 >> 16), (SINT16)0x02138653,
-    (SINT16)((SINT32)0x0209291F >> 16), (SINT16)0x0209291F,
-    (SINT16)((SINT32)0x01E0224C >> 16), (SINT16)0x01E0224C,
-    (SINT16)((SINT32)0x01A1B38B >> 16), (SINT16)0x01A1B38B,
-    (SINT16)((SINT32)0x0156B3CA >> 16), (SINT16)0x0156B3CA,
-    (SINT16)((SINT32)0x01071B96 >> 16), (SINT16)0x01071B96,
-
-    (SINT16)((SINT32)0xFF468CB8 >> 16), (SINT16)0xFF468CB8, /* 64 */
-    (SINT16)((SINT32)0xFF8D6793 >> 16), (SINT16)0xFF8D6793,
-    (SINT16)((SINT32)0xFFC9F10E >> 16), (SINT16)0xFFC9F10E,
-    (SINT16)((SINT32)0xFFFA2413 >> 16), (SINT16)0xFFFA2413,
-    (SINT16)((SINT32)0x001D8FD2 >> 16), (SINT16)0x001D8FD2,
-    (SINT16)((SINT32)0x0034F8B6 >> 16), (SINT16)0x0034F8B6,
-    (SINT16)((SINT32)0x00415B75 >> 16), (SINT16)0x00415B75,
-    (SINT16)((SINT32)0x0044EF48 >> 16), (SINT16)0x0044EF48,
-
-    (SINT16)((SINT32)0x0041EC6A >> 16), (SINT16)0x0041EC6A, /* 72 */
-    (SINT16)((SINT32)0x003A72E7 >> 16), (SINT16)0x003A72E7,
-    (SINT16)((SINT32)0x003060F4 >> 16), (SINT16)0x003060F4,
-    (SINT16)((SINT32)0x00255A62 >> 16), (SINT16)0x00255A62,
-    (SINT16)((SINT32)0x001AFF89 >> 16), (SINT16)0x001AFF89,
-    (SINT16)((SINT32)0x00122C7D >> 16), (SINT16)0x00122C7D,
-    (SINT16)((SINT32)0x000B3F71 >> 16), (SINT16)0x000B3F71,
-    (SINT16)((SINT32)0x00052173 >> 16), (SINT16)0x00052173
-};
+const SINT16 gas32CoeffFor8SBs[]
+    = {(SINT16)((SINT32)0x00000000 >> 16), (SINT16)0x00000000, (SINT16)((SINT32)0x00052173 >> 16), (SINT16)0x00052173, (SINT16)((SINT32)0x000B3F71 >> 16), (SINT16)0x000B3F71,
+       (SINT16)((SINT32)0x00122C7D >> 16), (SINT16)0x00122C7D, (SINT16)((SINT32)0x001AFF89 >> 16), (SINT16)0x001AFF89, (SINT16)((SINT32)0x00255A62 >> 16), (SINT16)0x00255A62,
+       (SINT16)((SINT32)0x003060F4 >> 16), (SINT16)0x003060F4, (SINT16)((SINT32)0x003A72E7 >> 16), (SINT16)0x003A72E7,
+
+       (SINT16)((SINT32)0x0041EC6A >> 16), (SINT16)0x0041EC6A, /* 8 */
+       (SINT16)((SINT32)0x0044EF48 >> 16), (SINT16)0x0044EF48, (SINT16)((SINT32)0x00415B75 >> 16), (SINT16)0x00415B75, (SINT16)((SINT32)0x0034F8B6 >> 16), (SINT16)0x0034F8B6,
+       (SINT16)((SINT32)0x001D8FD2 >> 16), (SINT16)0x001D8FD2, (SINT16)((SINT32)0xFFFA2413 >> 16), (SINT16)0xFFFA2413, (SINT16)((SINT32)0xFFC9F10E >> 16), (SINT16)0xFFC9F10E,
+       (SINT16)((SINT32)0xFF8D6793 >> 16), (SINT16)0xFF8D6793,
+
+       (SINT16)((SINT32)0x00B97348 >> 16), (SINT16)0x00B97348, /* 16 */
+       (SINT16)((SINT32)0x01071B96 >> 16), (SINT16)0x01071B96, (SINT16)((SINT32)0x0156B3CA >> 16), (SINT16)0x0156B3CA, (SINT16)((SINT32)0x01A1B38B >> 16), (SINT16)0x01A1B38B,
+       (SINT16)((SINT32)0x01E0224C >> 16), (SINT16)0x01E0224C, (SINT16)((SINT32)0x0209291F >> 16), (SINT16)0x0209291F, (SINT16)((SINT32)0x02138653 >> 16), (SINT16)0x02138653,
+       (SINT16)((SINT32)0x01F5F424 >> 16), (SINT16)0x01F5F424,
+
+       (SINT16)((SINT32)0x01A7ECEF >> 16), (SINT16)0x01A7ECEF, /* 24 */
+       (SINT16)((SINT32)0x01223EBA >> 16), (SINT16)0x01223EBA, (SINT16)((SINT32)0x005FD0FF >> 16), (SINT16)0x005FD0FF, (SINT16)((SINT32)0xFF5EEB73 >> 16), (SINT16)0xFF5EEB73,
+       (SINT16)((SINT32)0xFE20435D >> 16), (SINT16)0xFE20435D, (SINT16)((SINT32)0xFCA86E7E >> 16), (SINT16)0xFCA86E7E, (SINT16)((SINT32)0xFAFF95FC >> 16), (SINT16)0xFAFF95FC,
+       (SINT16)((SINT32)0xF9312891 >> 16), (SINT16)0xF9312891,
+
+       (SINT16)((SINT32)0x08B4307A >> 16), (SINT16)0x08B4307A, /* 32 */
+       (SINT16)((SINT32)0x0A9F3E9A >> 16), (SINT16)0x0A9F3E9A, (SINT16)((SINT32)0x0C7D59B6 >> 16), (SINT16)0x0C7D59B6, (SINT16)((SINT32)0x0E3BB16F >> 16), (SINT16)0x0E3BB16F,
+       (SINT16)((SINT32)0x0FC721F9 >> 16), (SINT16)0x0FC721F9, (SINT16)((SINT32)0x110ECEF0 >> 16), (SINT16)0x110ECEF0, (SINT16)((SINT32)0x120435FA >> 16), (SINT16)0x120435FA,
+       (SINT16)((SINT32)0x129C226F >> 16), (SINT16)0x129C226F,
+
+       (SINT16)((SINT32)0x12CF6C75 >> 16), (SINT16)0x12CF6C75, /* 40 */
+       (SINT16)((SINT32)0x129C226F >> 16), (SINT16)0x129C226F, (SINT16)((SINT32)0x120435FA >> 16), (SINT16)0x120435FA, (SINT16)((SINT32)0x110ECEF0 >> 16), (SINT16)0x110ECEF0,
+       (SINT16)((SINT32)0x0FC721F9 >> 16), (SINT16)0x0FC721F9, (SINT16)((SINT32)0x0E3BB16F >> 16), (SINT16)0x0E3BB16F, (SINT16)((SINT32)0x0C7D59B6 >> 16), (SINT16)0x0C7D59B6,
+       (SINT16)((SINT32)0x0A9F3E9A >> 16), (SINT16)0x0A9F3E9A,
+
+       (SINT16)((SINT32)0xF74BCF86 >> 16), (SINT16)0xF74BCF86, /* 48 */
+       (SINT16)((SINT32)0xF9312891 >> 16), (SINT16)0xF9312891, (SINT16)((SINT32)0xFAFF95FC >> 16), (SINT16)0xFAFF95FC, (SINT16)((SINT32)0xFCA86E7E >> 16), (SINT16)0xFCA86E7E,
+       (SINT16)((SINT32)0xFE20435D >> 16), (SINT16)0xFE20435D, (SINT16)((SINT32)0xFF5EEB73 >> 16), (SINT16)0xFF5EEB73, (SINT16)((SINT32)0x005FD0FF >> 16), (SINT16)0x005FD0FF,
+       (SINT16)((SINT32)0x01223EBA >> 16), (SINT16)0x01223EBA,
+
+       (SINT16)((SINT32)0x01A7ECEF >> 16), (SINT16)0x01A7ECEF, /* 56 */
+       (SINT16)((SINT32)0x01F5F424 >> 16), (SINT16)0x01F5F424, (SINT16)((SINT32)0x02138653 >> 16), (SINT16)0x02138653, (SINT16)((SINT32)0x0209291F >> 16), (SINT16)0x0209291F,
+       (SINT16)((SINT32)0x01E0224C >> 16), (SINT16)0x01E0224C, (SINT16)((SINT32)0x01A1B38B >> 16), (SINT16)0x01A1B38B, (SINT16)((SINT32)0x0156B3CA >> 16), (SINT16)0x0156B3CA,
+       (SINT16)((SINT32)0x01071B96 >> 16), (SINT16)0x01071B96,
+
+       (SINT16)((SINT32)0xFF468CB8 >> 16), (SINT16)0xFF468CB8, /* 64 */
+       (SINT16)((SINT32)0xFF8D6793 >> 16), (SINT16)0xFF8D6793, (SINT16)((SINT32)0xFFC9F10E >> 16), (SINT16)0xFFC9F10E, (SINT16)((SINT32)0xFFFA2413 >> 16), (SINT16)0xFFFA2413,
+       (SINT16)((SINT32)0x001D8FD2 >> 16), (SINT16)0x001D8FD2, (SINT16)((SINT32)0x0034F8B6 >> 16), (SINT16)0x0034F8B6, (SINT16)((SINT32)0x00415B75 >> 16), (SINT16)0x00415B75,
+       (SINT16)((SINT32)0x0044EF48 >> 16), (SINT16)0x0044EF48,
+
+       (SINT16)((SINT32)0x0041EC6A >> 16), (SINT16)0x0041EC6A, /* 72 */
+       (SINT16)((SINT32)0x003A72E7 >> 16), (SINT16)0x003A72E7, (SINT16)((SINT32)0x003060F4 >> 16), (SINT16)0x003060F4, (SINT16)((SINT32)0x00255A62 >> 16), (SINT16)0x00255A62,
+       (SINT16)((SINT32)0x001AFF89 >> 16), (SINT16)0x001AFF89, (SINT16)((SINT32)0x00122C7D >> 16), (SINT16)0x00122C7D, (SINT16)((SINT32)0x000B3F71 >> 16), (SINT16)0x000B3F71,
+       (SINT16)((SINT32)0x00052173 >> 16), (SINT16)0x00052173};
 
 #else
 
 /*Window coeff for 4 sub band case*/
-const SINT32 gas32CoeffFor4SBs[] = {
-    (SINT32)0x00000000,
-    (SINT32)0x001194E6,
-    (SINT32)0x0030E2D3,
-    (SINT32)0x00599403,
-    (SINT32)0x007DBCC8,
-    (SINT32)0x007F88E4,
-    (SINT32)0x003D239B,
-    (SINT32)0xFF9BB9D5,
-
-    (SINT32)0x01659F45,
-    (SINT32)0x029DBAA3,
-    (SINT32)0x03B23341,
-    (SINT32)0x041EEE40,
-    (SINT32)0x034FEE2C,
-    (SINT32)0x00C8F2BC,
-    (SINT32)0xFC4F91D4,
-    (SINT32)0xF60FAF37,
-
-    (SINT32)0x115B1ED2,
-    (SINT32)0x18F55C90,
-    (SINT32)0x1F91CA46,
-    (SINT32)0x2412F251,
-    (SINT32)0x25AC1FF2,
-    (SINT32)0x2412F251,
-    (SINT32)0x1F91CA46,
-    (SINT32)0x18F55C90,
-
-    (SINT32)0xEEA4E12E,
-    (SINT32)0xF60FAF37,
-    (SINT32)0xFC4F91D4,
-    (SINT32)0x00C8F2BC,
-    (SINT32)0x034FEE2C,
-    (SINT32)0x041EEE40,
-    (SINT32)0x03B23341,
-    (SINT32)0x029DBAA3,
-
-    (SINT32)0xFE9A60BB,
-    (SINT32)0xFF9BB9D5,
-    (SINT32)0x003D239B,
-    (SINT32)0x007F88E4,
-    (SINT32)0x007DBCC8,
-    (SINT32)0x00599403,
-    (SINT32)0x0030E2D3,
-    (SINT32)0x001194E6
-};
+const SINT32 gas32CoeffFor4SBs[] = {(SINT32)0x00000000, (SINT32)0x001194E6, (SINT32)0x0030E2D3, (SINT32)0x00599403, (SINT32)0x007DBCC8, (SINT32)0x007F88E4, (SINT32)0x003D239B, (SINT32)0xFF9BB9D5,
+
+                                    (SINT32)0x01659F45, (SINT32)0x029DBAA3, (SINT32)0x03B23341, (SINT32)0x041EEE40, (SINT32)0x034FEE2C, (SINT32)0x00C8F2BC, (SINT32)0xFC4F91D4, (SINT32)0xF60FAF37,
+
+                                    (SINT32)0x115B1ED2, (SINT32)0x18F55C90, (SINT32)0x1F91CA46, (SINT32)0x2412F251, (SINT32)0x25AC1FF2, (SINT32)0x2412F251, (SINT32)0x1F91CA46, (SINT32)0x18F55C90,
+
+                                    (SINT32)0xEEA4E12E, (SINT32)0xF60FAF37, (SINT32)0xFC4F91D4, (SINT32)0x00C8F2BC, (SINT32)0x034FEE2C, (SINT32)0x041EEE40, (SINT32)0x03B23341, (SINT32)0x029DBAA3,
+
+                                    (SINT32)0xFE9A60BB, (SINT32)0xFF9BB9D5, (SINT32)0x003D239B, (SINT32)0x007F88E4, (SINT32)0x007DBCC8, (SINT32)0x00599403, (SINT32)0x0030E2D3, (SINT32)0x001194E6};
 
 /*Window coeff for 8 sub band case*/
-const SINT32 gas32CoeffFor8SBs[] = {
-    (SINT32)0x00000000,
-    (SINT32)0x00052173,
-    (SINT32)0x000B3F71,
-    (SINT32)0x00122C7D,
-    (SINT32)0x001AFF89,
-    (SINT32)0x00255A62,
-    (SINT32)0x003060F4,
-    (SINT32)0x003A72E7,
-
-    (SINT32)0x0041EC6A, /* 8 */
-    (SINT32)0x0044EF48,
-    (SINT32)0x00415B75,
-    (SINT32)0x0034F8B6,
-    (SINT32)0x001D8FD2,
-    (SINT32)0xFFFA2413,
-    (SINT32)0xFFC9F10E,
-    (SINT32)0xFF8D6793,
-
-    (SINT32)0x00B97348, /* 16 */
-    (SINT32)0x01071B96,
-    (SINT32)0x0156B3CA,
-    (SINT32)0x01A1B38B,
-    (SINT32)0x01E0224C,
-    (SINT32)0x0209291F,
-    (SINT32)0x02138653,
-    (SINT32)0x01F5F424,
-
-    (SINT32)0x01A7ECEF, /* 24 */
-    (SINT32)0x01223EBA,
-    (SINT32)0x005FD0FF,
-    (SINT32)0xFF5EEB73,
-    (SINT32)0xFE20435D,
-    (SINT32)0xFCA86E7E,
-    (SINT32)0xFAFF95FC,
-    (SINT32)0xF9312891,
-
-    (SINT32)0x08B4307A, /* 32 */
-    (SINT32)0x0A9F3E9A,
-    (SINT32)0x0C7D59B6,
-    (SINT32)0x0E3BB16F,
-    (SINT32)0x0FC721F9,
-    (SINT32)0x110ECEF0,
-    (SINT32)0x120435FA,
-    (SINT32)0x129C226F,
-
-    (SINT32)0x12CF6C75, /* 40 */
-    (SINT32)0x129C226F,
-    (SINT32)0x120435FA,
-    (SINT32)0x110ECEF0,
-    (SINT32)0x0FC721F9,
-    (SINT32)0x0E3BB16F,
-    (SINT32)0x0C7D59B6,
-    (SINT32)0x0A9F3E9A,
-
-    (SINT32)0xF74BCF86, /* 48 */
-    (SINT32)0xF9312891,
-    (SINT32)0xFAFF95FC,
-    (SINT32)0xFCA86E7E,
-    (SINT32)0xFE20435D,
-    (SINT32)0xFF5EEB73,
-    (SINT32)0x005FD0FF,
-    (SINT32)0x01223EBA,
-
-    (SINT32)0x01A7ECEF, /* 56 */
-    (SINT32)0x01F5F424,
-    (SINT32)0x02138653,
-    (SINT32)0x0209291F,
-    (SINT32)0x01E0224C,
-    (SINT32)0x01A1B38B,
-    (SINT32)0x0156B3CA,
-    (SINT32)0x01071B96,
-
-    (SINT32)0xFF468CB8, /* 64 */
-    (SINT32)0xFF8D6793,
-    (SINT32)0xFFC9F10E,
-    (SINT32)0xFFFA2413,
-    (SINT32)0x001D8FD2,
-    (SINT32)0x0034F8B6,
-    (SINT32)0x00415B75,
-    (SINT32)0x0044EF48,
-
-    (SINT32)0x0041EC6A, /* 72 */
-    (SINT32)0x003A72E7,
-    (SINT32)0x003060F4,
-    (SINT32)0x00255A62,
-    (SINT32)0x001AFF89,
-    (SINT32)0x00122C7D,
-    (SINT32)0x000B3F71,
-    (SINT32)0x00052173
-};
+const SINT32 gas32CoeffFor8SBs[] = {(SINT32)0x00000000, (SINT32)0x00052173, (SINT32)0x000B3F71, (SINT32)0x00122C7D, (SINT32)0x001AFF89, (SINT32)0x00255A62, (SINT32)0x003060F4, (SINT32)0x003A72E7,
+
+                                    (SINT32)0x0041EC6A, /* 8 */
+                                    (SINT32)0x0044EF48, (SINT32)0x00415B75, (SINT32)0x0034F8B6, (SINT32)0x001D8FD2, (SINT32)0xFFFA2413, (SINT32)0xFFC9F10E, (SINT32)0xFF8D6793,
+
+                                    (SINT32)0x00B97348, /* 16 */
+                                    (SINT32)0x01071B96, (SINT32)0x0156B3CA, (SINT32)0x01A1B38B, (SINT32)0x01E0224C, (SINT32)0x0209291F, (SINT32)0x02138653, (SINT32)0x01F5F424,
+
+                                    (SINT32)0x01A7ECEF, /* 24 */
+                                    (SINT32)0x01223EBA, (SINT32)0x005FD0FF, (SINT32)0xFF5EEB73, (SINT32)0xFE20435D, (SINT32)0xFCA86E7E, (SINT32)0xFAFF95FC, (SINT32)0xF9312891,
+
+                                    (SINT32)0x08B4307A, /* 32 */
+                                    (SINT32)0x0A9F3E9A, (SINT32)0x0C7D59B6, (SINT32)0x0E3BB16F, (SINT32)0x0FC721F9, (SINT32)0x110ECEF0, (SINT32)0x120435FA, (SINT32)0x129C226F,
+
+                                    (SINT32)0x12CF6C75, /* 40 */
+                                    (SINT32)0x129C226F, (SINT32)0x120435FA, (SINT32)0x110ECEF0, (SINT32)0x0FC721F9, (SINT32)0x0E3BB16F, (SINT32)0x0C7D59B6, (SINT32)0x0A9F3E9A,
+
+                                    (SINT32)0xF74BCF86, /* 48 */
+                                    (SINT32)0xF9312891, (SINT32)0xFAFF95FC, (SINT32)0xFCA86E7E, (SINT32)0xFE20435D, (SINT32)0xFF5EEB73, (SINT32)0x005FD0FF, (SINT32)0x01223EBA,
+
+                                    (SINT32)0x01A7ECEF, /* 56 */
+                                    (SINT32)0x01F5F424, (SINT32)0x02138653, (SINT32)0x0209291F, (SINT32)0x01E0224C, (SINT32)0x01A1B38B, (SINT32)0x0156B3CA, (SINT32)0x01071B96,
+
+                                    (SINT32)0xFF468CB8, /* 64 */
+                                    (SINT32)0xFF8D6793, (SINT32)0xFFC9F10E, (SINT32)0xFFFA2413, (SINT32)0x001D8FD2, (SINT32)0x0034F8B6, (SINT32)0x00415B75, (SINT32)0x0044EF48,
+
+                                    (SINT32)0x0041EC6A, /* 72 */
+                                    (SINT32)0x003A72E7, (SINT32)0x003060F4, (SINT32)0x00255A62, (SINT32)0x001AFF89, (SINT32)0x00122C7D, (SINT32)0x000B3F71, (SINT32)0x00052173};
 
 #endif
 #endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_encoder.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_encoder.c
index bcfdfa456a..adfd588b38 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_encoder.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_encoder.c
@@ -22,300 +22,291 @@
  *
  ******************************************************************************/
 
-#include 
-#include 
 #include "sbc_encoder.h"
 #include "sbc_enc_func_declare.h"
+#include 
+#include 
 
 #if defined(SBC_ENC_INCLUDED)
 
 SINT16 EncMaxShiftCounter;
 
 #if (SBC_JOINT_STE_INCLUDED == TRUE)
-SINT32 s32LRDiff[SBC_MAX_NUM_OF_BLOCKS] = { 0 };
-SINT32 s32LRSum[SBC_MAX_NUM_OF_BLOCKS] = { 0 };
+SINT32 s32LRDiff[SBC_MAX_NUM_OF_BLOCKS] = {0};
+SINT32 s32LRSum[SBC_MAX_NUM_OF_BLOCKS]  = {0};
 #endif
 
-void SBC_Encoder(SBC_ENC_PARAMS *pstrEncParams)
-{
-    SINT32 s32Ch;                /* counter for ch*/
-    SINT32 s32Sb;                /* counter for sub-band*/
-    UINT32 u32Count, maxBit = 0; /* loop count*/
-    SINT32 s32MaxValue;          /* temp variable to store max value */
-
-    SINT16 *ps16ScfL;
-    SINT32 *SbBuffer;
-    SINT32 s32Blk; /* counter for block*/
-    SINT32 s32NumOfBlocks = pstrEncParams->s16NumOfBlocks;
+void SBC_Encoder(SBC_ENC_PARAMS *pstrEncParams) {
+  SINT32 s32Ch;                /* counter for ch*/
+  SINT32 s32Sb;                /* counter for sub-band*/
+  UINT32 u32Count, maxBit = 0; /* loop count*/
+  SINT32 s32MaxValue;          /* temp variable to store max value */
+
+  SINT16 *ps16ScfL;
+  SINT32 *SbBuffer;
+  SINT32  s32Blk; /* counter for block*/
+  SINT32  s32NumOfBlocks = pstrEncParams->s16NumOfBlocks;
 #if (SBC_JOINT_STE_INCLUDED == TRUE)
-    SINT32 s32MaxValue2;
-    UINT32 u32CountSum, u32CountDiff;
-    SINT32 *pSum, *pDiff;
+  SINT32  s32MaxValue2;
+  UINT32  u32CountSum, u32CountDiff;
+  SINT32 *pSum, *pDiff;
 #endif
-    register SINT32 s32NumOfSubBands = pstrEncParams->s16NumOfSubBands;
+  register SINT32 s32NumOfSubBands = pstrEncParams->s16NumOfSubBands;
 
-    pstrEncParams->pu8NextPacket = pstrEncParams->pu8Packet;
+  pstrEncParams->pu8NextPacket = pstrEncParams->pu8Packet;
 
 #if (SBC_NO_PCM_CPY_OPTION == TRUE)
-    pstrEncParams->ps16NextPcmBuffer = pstrEncParams->ps16PcmBuffer;
+  pstrEncParams->ps16NextPcmBuffer = pstrEncParams->ps16PcmBuffer;
 #else
-    pstrEncParams->ps16NextPcmBuffer = pstrEncParams->as16PcmBuffer;
+  pstrEncParams->ps16NextPcmBuffer = pstrEncParams->as16PcmBuffer;
 #endif
-    do {
-        /* SBC ananlysis filter*/
-        if (s32NumOfSubBands == 4) {
-            SbcAnalysisFilter4(pstrEncParams);
-        } else {
-            SbcAnalysisFilter8(pstrEncParams);
+  do {
+    /* SBC ananlysis filter*/
+    if (s32NumOfSubBands == 4) {
+      SbcAnalysisFilter4(pstrEncParams);
+    } else {
+      SbcAnalysisFilter8(pstrEncParams);
+    }
+
+    /* compute the scale factor, and save the max */
+    ps16ScfL = pstrEncParams->as16ScaleFactor;
+    s32Ch    = pstrEncParams->s16NumOfChannels * s32NumOfSubBands;
+
+    pstrEncParams->ps16NextPcmBuffer += s32Ch * s32NumOfBlocks; /* in case of multible sbc frame to encode update the pcm pointer */
+
+    for (s32Sb = 0; s32Sb < s32Ch; s32Sb++) {
+      SbBuffer    = pstrEncParams->s32SbBuffer + s32Sb;
+      s32MaxValue = 0;
+      for (s32Blk = s32NumOfBlocks; s32Blk > 0; s32Blk--) {
+        if (s32MaxValue < abs32(*SbBuffer)) {
+          s32MaxValue = abs32(*SbBuffer);
         }
+        SbBuffer += s32Ch;
+      }
+
+      u32Count = (s32MaxValue > 0x800000) ? 9 : 0;
 
-        /* compute the scale factor, and save the max */
-        ps16ScfL = pstrEncParams->as16ScaleFactor;
-        s32Ch = pstrEncParams->s16NumOfChannels * s32NumOfSubBands;
-
-        pstrEncParams->ps16NextPcmBuffer += s32Ch * s32NumOfBlocks; /* in case of multible sbc frame to encode update the pcm pointer */
-
-        for (s32Sb = 0; s32Sb < s32Ch; s32Sb++) {
-            SbBuffer = pstrEncParams->s32SbBuffer + s32Sb;
-            s32MaxValue = 0;
-            for (s32Blk = s32NumOfBlocks; s32Blk > 0; s32Blk--) {
-                if (s32MaxValue < abs32(*SbBuffer)) {
-                    s32MaxValue = abs32(*SbBuffer);
-                }
-                SbBuffer += s32Ch;
-            }
-
-            u32Count = (s32MaxValue > 0x800000) ? 9 : 0;
-
-            for (; u32Count < 15; u32Count++) {
-                if (s32MaxValue <= (SINT32)(0x8000 << u32Count)) {
-                    break;
-                }
-            }
-            *ps16ScfL++ = (SINT16)u32Count;
-
-            if (u32Count > maxBit) {
-                maxBit = u32Count;
-            }
+      for (; u32Count < 15; u32Count++) {
+        if (s32MaxValue <= (SINT32)(0x8000 << u32Count)) {
+          break;
         }
-        /* In case of JS processing,check whether to use JS */
+      }
+      *ps16ScfL++ = (SINT16)u32Count;
+
+      if (u32Count > maxBit) {
+        maxBit = u32Count;
+      }
+    }
+    /* In case of JS processing,check whether to use JS */
 #if (SBC_JOINT_STE_INCLUDED == TRUE)
-        if (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) {
-            /* Calculate sum and differance  scale factors for making JS decision   */
-            ps16ScfL = pstrEncParams->as16ScaleFactor;
-            /* calculate the scale factor of Joint stereo max sum and diff */
-            for (s32Sb = 0; s32Sb < s32NumOfSubBands - 1; s32Sb++) {
-                SbBuffer = pstrEncParams->s32SbBuffer + s32Sb;
-                s32MaxValue2 = 0;
-                s32MaxValue = 0;
-                pSum = s32LRSum;
-                pDiff = s32LRDiff;
-                for (s32Blk = 0; s32Blk < s32NumOfBlocks; s32Blk++) {
-                    *pSum = (*SbBuffer + *(SbBuffer + s32NumOfSubBands)) >> 1;
-                    if (abs32(*pSum) > s32MaxValue) {
-                        s32MaxValue = abs32(*pSum);
-                    }
-                    pSum++;
-                    *pDiff = (*SbBuffer - *(SbBuffer + s32NumOfSubBands)) >> 1;
-                    if (abs32(*pDiff) > s32MaxValue2) {
-                        s32MaxValue2 = abs32(*pDiff);
-                    }
-                    pDiff++;
-                    SbBuffer += s32Ch;
-                }
-                u32Count = (s32MaxValue > 0x800000) ? 9 : 0;
-                for (; u32Count < 15; u32Count++) {
-                    if (s32MaxValue <= (SINT32)(0x8000 << u32Count)) {
-                        break;
-                    }
-                }
-                u32CountSum = u32Count;
-                u32Count = (s32MaxValue2 > 0x800000) ? 9 : 0;
-                for (; u32Count < 15; u32Count++) {
-                    if (s32MaxValue2 <= (SINT32)(0x8000 << u32Count)) {
-                        break;
-                    }
-                }
-                u32CountDiff = u32Count;
-                if ((*ps16ScfL + *(ps16ScfL + s32NumOfSubBands)) > (SINT16)(u32CountSum + u32CountDiff)) {
-                    if (u32CountSum > maxBit) {
-                        maxBit = u32CountSum;
-                    }
-
-                    if (u32CountDiff > maxBit) {
-                        maxBit = u32CountDiff;
-                    }
-
-                    *ps16ScfL = (SINT16)u32CountSum;
-                    *(ps16ScfL + s32NumOfSubBands) = (SINT16)u32CountDiff;
-
-                    SbBuffer = pstrEncParams->s32SbBuffer + s32Sb;
-                    pSum = s32LRSum;
-                    pDiff = s32LRDiff;
-
-                    for (s32Blk = 0; s32Blk < s32NumOfBlocks; s32Blk++) {
-                        *SbBuffer = *pSum;
-                        *(SbBuffer + s32NumOfSubBands) = *pDiff;
-
-                        SbBuffer += s32NumOfSubBands << 1;
-                        pSum++;
-                        pDiff++;
-                    }
-
-                    pstrEncParams->as16Join[s32Sb] = 1;
-                } else {
-                    pstrEncParams->as16Join[s32Sb] = 0;
-                }
-                ps16ScfL++;
-            }
-            pstrEncParams->as16Join[s32Sb] = 0;
+    if (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) {
+      /* Calculate sum and differance  scale factors for making JS decision   */
+      ps16ScfL = pstrEncParams->as16ScaleFactor;
+      /* calculate the scale factor of Joint stereo max sum and diff */
+      for (s32Sb = 0; s32Sb < s32NumOfSubBands - 1; s32Sb++) {
+        SbBuffer     = pstrEncParams->s32SbBuffer + s32Sb;
+        s32MaxValue2 = 0;
+        s32MaxValue  = 0;
+        pSum         = s32LRSum;
+        pDiff        = s32LRDiff;
+        for (s32Blk = 0; s32Blk < s32NumOfBlocks; s32Blk++) {
+          *pSum = (*SbBuffer + *(SbBuffer + s32NumOfSubBands)) >> 1;
+          if (abs32(*pSum) > s32MaxValue) {
+            s32MaxValue = abs32(*pSum);
+          }
+          pSum++;
+          *pDiff = (*SbBuffer - *(SbBuffer + s32NumOfSubBands)) >> 1;
+          if (abs32(*pDiff) > s32MaxValue2) {
+            s32MaxValue2 = abs32(*pDiff);
+          }
+          pDiff++;
+          SbBuffer += s32Ch;
         }
-#endif
+        u32Count = (s32MaxValue > 0x800000) ? 9 : 0;
+        for (; u32Count < 15; u32Count++) {
+          if (s32MaxValue <= (SINT32)(0x8000 << u32Count)) {
+            break;
+          }
+        }
+        u32CountSum = u32Count;
+        u32Count    = (s32MaxValue2 > 0x800000) ? 9 : 0;
+        for (; u32Count < 15; u32Count++) {
+          if (s32MaxValue2 <= (SINT32)(0x8000 << u32Count)) {
+            break;
+          }
+        }
+        u32CountDiff = u32Count;
+        if ((*ps16ScfL + *(ps16ScfL + s32NumOfSubBands)) > (SINT16)(u32CountSum + u32CountDiff)) {
+          if (u32CountSum > maxBit) {
+            maxBit = u32CountSum;
+          }
+
+          if (u32CountDiff > maxBit) {
+            maxBit = u32CountDiff;
+          }
+
+          *ps16ScfL                      = (SINT16)u32CountSum;
+          *(ps16ScfL + s32NumOfSubBands) = (SINT16)u32CountDiff;
+
+          SbBuffer = pstrEncParams->s32SbBuffer + s32Sb;
+          pSum     = s32LRSum;
+          pDiff    = s32LRDiff;
 
-        pstrEncParams->s16MaxBitNeed = (SINT16)maxBit;
+          for (s32Blk = 0; s32Blk < s32NumOfBlocks; s32Blk++) {
+            *SbBuffer                      = *pSum;
+            *(SbBuffer + s32NumOfSubBands) = *pDiff;
 
-        /* bit allocation */
-        if ((pstrEncParams->s16ChannelMode == SBC_STEREO) || (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO)) {
-            sbc_enc_bit_alloc_ste(pstrEncParams);
+            SbBuffer += s32NumOfSubBands << 1;
+            pSum++;
+            pDiff++;
+          }
+
+          pstrEncParams->as16Join[s32Sb] = 1;
         } else {
-            sbc_enc_bit_alloc_mono(pstrEncParams);
+          pstrEncParams->as16Join[s32Sb] = 0;
         }
+        ps16ScfL++;
+      }
+      pstrEncParams->as16Join[s32Sb] = 0;
+    }
+#endif
 
-        /* Quantize the encoded audio */
-        EncPacking(pstrEncParams);
-    } while (--(pstrEncParams->u8NumPacketToEncode));
+    pstrEncParams->s16MaxBitNeed = (SINT16)maxBit;
+
+    /* bit allocation */
+    if ((pstrEncParams->s16ChannelMode == SBC_STEREO) || (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO)) {
+      sbc_enc_bit_alloc_ste(pstrEncParams);
+    } else {
+      sbc_enc_bit_alloc_mono(pstrEncParams);
+    }
 
-    pstrEncParams->u8NumPacketToEncode = 1; /* default is one for retrocompatibility purpose */
+    /* Quantize the encoded audio */
+    EncPacking(pstrEncParams);
+  } while (--(pstrEncParams->u8NumPacketToEncode));
+
+  pstrEncParams->u8NumPacketToEncode = 1; /* default is one for retrocompatibility purpose */
 }
 
 /****************************************************************************
-* InitSbcAnalysisFilt - Initalizes the input data to 0
-*
-* RETURNS : N/A
-*/
-void SBC_Encoder_Init(SBC_ENC_PARAMS *pstrEncParams)
-{
-    UINT16 s16SamplingFreq; /*temp variable to store smpling freq*/
-    SINT16 s16Bitpool;      /*to store bit pool value*/
-    SINT16 s16BitRate;      /*to store bitrate*/
-    SINT16 s16FrameLen;     /*to store frame length*/
-    UINT16 HeaderParams;
-
-    pstrEncParams->u8NumPacketToEncode = 1; /* default is one for retrocompatibility purpose */
-
-    if (pstrEncParams->sbc_mode != SBC_MODE_MSBC) {
-        /* Required number of channels */
-        if (pstrEncParams->s16ChannelMode == SBC_MONO) {
-            pstrEncParams->s16NumOfChannels = 1;
-        } else {
-            pstrEncParams->s16NumOfChannels = 2;
-        }
+ * InitSbcAnalysisFilt - Initalizes the input data to 0
+ *
+ * RETURNS : N/A
+ */
+void SBC_Encoder_Init(SBC_ENC_PARAMS *pstrEncParams) {
+  UINT16 s16SamplingFreq; /*temp variable to store smpling freq*/
+  SINT16 s16Bitpool;      /*to store bit pool value*/
+  SINT16 s16BitRate;      /*to store bitrate*/
+  SINT16 s16FrameLen;     /*to store frame length*/
+  UINT16 HeaderParams;
+
+  pstrEncParams->u8NumPacketToEncode = 1; /* default is one for retrocompatibility purpose */
+
+  if (pstrEncParams->sbc_mode != SBC_MODE_MSBC) {
+    /* Required number of channels */
+    if (pstrEncParams->s16ChannelMode == SBC_MONO) {
+      pstrEncParams->s16NumOfChannels = 1;
+    } else {
+      pstrEncParams->s16NumOfChannels = 2;
+    }
 
-        /* Bit pool calculation */
-        if (pstrEncParams->s16SamplingFreq == SBC_sf16000) {
-            s16SamplingFreq = 16000;
-        } else if (pstrEncParams->s16SamplingFreq == SBC_sf32000) {
-            s16SamplingFreq = 32000;
-        } else if (pstrEncParams->s16SamplingFreq == SBC_sf44100) {
-            s16SamplingFreq = 44100;
-        } else {
-            s16SamplingFreq = 48000;
-        }
+    /* Bit pool calculation */
+    if (pstrEncParams->s16SamplingFreq == SBC_sf16000) {
+      s16SamplingFreq = 16000;
+    } else if (pstrEncParams->s16SamplingFreq == SBC_sf32000) {
+      s16SamplingFreq = 32000;
+    } else if (pstrEncParams->s16SamplingFreq == SBC_sf44100) {
+      s16SamplingFreq = 44100;
+    } else {
+      s16SamplingFreq = 48000;
+    }
 
-        if ((pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) || (pstrEncParams->s16ChannelMode == SBC_STEREO)) {
-            s16Bitpool = (SINT16)((pstrEncParams->u16BitRate *
-                                   pstrEncParams->s16NumOfSubBands * 1000 / s16SamplingFreq) -
-                                  ((32 + (4 * pstrEncParams->s16NumOfSubBands * pstrEncParams->s16NumOfChannels) + ((pstrEncParams->s16ChannelMode - 2) * pstrEncParams->s16NumOfSubBands)) / pstrEncParams->s16NumOfBlocks));
+    if ((pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) || (pstrEncParams->s16ChannelMode == SBC_STEREO)) {
+      s16Bitpool = (SINT16)((pstrEncParams->u16BitRate * pstrEncParams->s16NumOfSubBands * 1000 / s16SamplingFreq)
+                            - ((32 + (4 * pstrEncParams->s16NumOfSubBands * pstrEncParams->s16NumOfChannels) + ((pstrEncParams->s16ChannelMode - 2) * pstrEncParams->s16NumOfSubBands))
+                               / pstrEncParams->s16NumOfBlocks));
 
-            s16FrameLen = 4 + (4 * pstrEncParams->s16NumOfSubBands * pstrEncParams->s16NumOfChannels) / 8 + (((pstrEncParams->s16ChannelMode - 2) * pstrEncParams->s16NumOfSubBands) + (pstrEncParams->s16NumOfBlocks * s16Bitpool)) / 8;
+      s16FrameLen = 4 + (4 * pstrEncParams->s16NumOfSubBands * pstrEncParams->s16NumOfChannels) / 8
+                    + (((pstrEncParams->s16ChannelMode - 2) * pstrEncParams->s16NumOfSubBands) + (pstrEncParams->s16NumOfBlocks * s16Bitpool)) / 8;
 
-            s16BitRate = (8 * s16FrameLen * s16SamplingFreq) / (pstrEncParams->s16NumOfSubBands *
-                                                                pstrEncParams->s16NumOfBlocks * 1000);
+      s16BitRate = (8 * s16FrameLen * s16SamplingFreq) / (pstrEncParams->s16NumOfSubBands * pstrEncParams->s16NumOfBlocks * 1000);
 
-            if (s16BitRate > pstrEncParams->u16BitRate) {
-                s16Bitpool--;
-            }
+      if (s16BitRate > pstrEncParams->u16BitRate) {
+        s16Bitpool--;
+      }
 
-            if (pstrEncParams->s16NumOfSubBands == 8) {
-                pstrEncParams->s16BitPool = (s16Bitpool > 255) ? 255 : s16Bitpool;
-            } else {
-                pstrEncParams->s16BitPool = (s16Bitpool > 128) ? 128 : s16Bitpool;
-            }
-        } else {
-            s16Bitpool = (SINT16)(((pstrEncParams->s16NumOfSubBands *
-                                    pstrEncParams->u16BitRate * 1000) /
-                                   (s16SamplingFreq * pstrEncParams->s16NumOfChannels)) -
-                                  (((32 / pstrEncParams->s16NumOfChannels) +
-                                    (4 * pstrEncParams->s16NumOfSubBands)) /
-                                   pstrEncParams->s16NumOfBlocks));
-
-            pstrEncParams->s16BitPool = (s16Bitpool >
-                                         (16 * pstrEncParams->s16NumOfSubBands)) ?
-                                            (16 * pstrEncParams->s16NumOfSubBands) :
-                                            s16Bitpool;
-        }
+      if (pstrEncParams->s16NumOfSubBands == 8) {
+        pstrEncParams->s16BitPool = (s16Bitpool > 255) ? 255 : s16Bitpool;
+      } else {
+        pstrEncParams->s16BitPool = (s16Bitpool > 128) ? 128 : s16Bitpool;
+      }
+    } else {
+      s16Bitpool = (SINT16)(((pstrEncParams->s16NumOfSubBands * pstrEncParams->u16BitRate * 1000) / (s16SamplingFreq * pstrEncParams->s16NumOfChannels))
+                            - (((32 / pstrEncParams->s16NumOfChannels) + (4 * pstrEncParams->s16NumOfSubBands)) / pstrEncParams->s16NumOfBlocks));
 
-        if (pstrEncParams->s16BitPool < 0) {
-            pstrEncParams->s16BitPool = 0;
-        }
-        /* sampling freq */
-        HeaderParams = ((pstrEncParams->s16SamplingFreq & 3) << 6);
+      pstrEncParams->s16BitPool = (s16Bitpool > (16 * pstrEncParams->s16NumOfSubBands)) ? (16 * pstrEncParams->s16NumOfSubBands) : s16Bitpool;
+    }
 
-        /* number of blocks*/
-        HeaderParams |= (((pstrEncParams->s16NumOfBlocks - 4) & 12) << 2);
+    if (pstrEncParams->s16BitPool < 0) {
+      pstrEncParams->s16BitPool = 0;
+    }
+    /* sampling freq */
+    HeaderParams = ((pstrEncParams->s16SamplingFreq & 3) << 6);
 
-        /* channel mode: mono, dual...*/
-        HeaderParams |= ((pstrEncParams->s16ChannelMode & 3) << 2);
+    /* number of blocks*/
+    HeaderParams |= (((pstrEncParams->s16NumOfBlocks - 4) & 12) << 2);
 
-        /* Loudness or SNR */
-        HeaderParams |= ((pstrEncParams->s16AllocationMethod & 1) << 1);
-        HeaderParams |= ((pstrEncParams->s16NumOfSubBands >> 3) & 1); /*4 or 8*/
+    /* channel mode: mono, dual...*/
+    HeaderParams |= ((pstrEncParams->s16ChannelMode & 3) << 2);
 
-        pstrEncParams->FrameHeader = HeaderParams;
-    } else {
-        // mSBC
+    /* Loudness or SNR */
+    HeaderParams |= ((pstrEncParams->s16AllocationMethod & 1) << 1);
+    HeaderParams |= ((pstrEncParams->s16NumOfSubBands >> 3) & 1); /*4 or 8*/
 
-        // Use mSBC encoding parameters to reset the control field
-        /* Required number of channels: 1 */
-        pstrEncParams->s16ChannelMode = SBC_MONO;
-        pstrEncParams->s16NumOfChannels = 1;
+    pstrEncParams->FrameHeader = HeaderParams;
+  } else {
+    // mSBC
 
-        /* Required Sampling frequency : 16KHz */
-        pstrEncParams->s16SamplingFreq = SBC_sf16000;
+    // Use mSBC encoding parameters to reset the control field
+    /* Required number of channels: 1 */
+    pstrEncParams->s16ChannelMode   = SBC_MONO;
+    pstrEncParams->s16NumOfChannels = 1;
 
-        /* Bit pool value: 26 */
-        pstrEncParams->s16BitPool = 26;
+    /* Required Sampling frequency : 16KHz */
+    pstrEncParams->s16SamplingFreq = SBC_sf16000;
 
-        /* number of subbands: 8 */
-        pstrEncParams->s16NumOfSubBands = 8;
+    /* Bit pool value: 26 */
+    pstrEncParams->s16BitPool = 26;
 
-        /* number of blocks: 15 */
-        pstrEncParams->s16NumOfBlocks = 15;
+    /* number of subbands: 8 */
+    pstrEncParams->s16NumOfSubBands = 8;
 
-        /* allocation method: loudness */
-        pstrEncParams->s16AllocationMethod = SBC_LOUDNESS;
+    /* number of blocks: 15 */
+    pstrEncParams->s16NumOfBlocks = 15;
 
-        /* set the header paramers, unused for mSBC */
-        pstrEncParams->FrameHeader = 0;
-    }
+    /* allocation method: loudness */
+    pstrEncParams->s16AllocationMethod = SBC_LOUDNESS;
 
-    if (pstrEncParams->s16NumOfSubBands == 4) {
-        if (pstrEncParams->s16NumOfChannels == 1) {
-            EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 4 * 10) >> 2) << 2;
-        } else {
-            EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 4 * 10 * 2) >> 3) << 2;
-        }
+    /* set the header paramers, unused for mSBC */
+    pstrEncParams->FrameHeader = 0;
+  }
+
+  if (pstrEncParams->s16NumOfSubBands == 4) {
+    if (pstrEncParams->s16NumOfChannels == 1) {
+      EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 4 * 10) >> 2) << 2;
     } else {
-        if (pstrEncParams->s16NumOfChannels == 1) {
-            EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 8 * 10) >> 3) << 3;
-        } else {
-            EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 8 * 10 * 2) >> 4) << 3;
-        }
+      EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 4 * 10 * 2) >> 3) << 2;
+    }
+  } else {
+    if (pstrEncParams->s16NumOfChannels == 1) {
+      EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 8 * 10) >> 3) << 3;
+    } else {
+      EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 8 * 10 * 2) >> 4) << 3;
     }
+  }
 
-    BT_WARN("SBC_Encoder_Init : bitrate %d, bitpool %d\n", pstrEncParams->u16BitRate, pstrEncParams->s16BitPool);
+  BT_WARN("SBC_Encoder_Init : bitrate %d, bitpool %d\n", pstrEncParams->u16BitRate, pstrEncParams->s16BitPool);
 
-    SbcAnalysisInit();
+  SbcAnalysisInit();
 }
 
 #endif /* #if defined(SBC_ENC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_packing.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_packing.c
index 36adea7626..a83dcb9dd2 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_packing.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_packing.c
@@ -22,241 +22,236 @@
  *
  ******************************************************************************/
 
-#include "sbc_encoder.h"
 #include "sbc_enc_func_declare.h"
+#include "sbc_encoder.h"
 
 #if defined(SBC_ENC_INCLUDED)
 
 #if (SBC_ARM_ASM_OPT == TRUE)
-#define Mult32(s32In1, s32In2, s32OutLow)                                                            \
-    {                                                                                                \
-        __asm {                                                                                    \
-        MUL s32OutLow,s32In1,s32In2; \
-        }                                                                                            \
-    }
-#define Mult64(s32In1, s32In2, s32OutLow, s32OutHi)                                                 \
-    {                                                                                               \
-        __asm {                                                                                   \
-        SMULL s32OutLow,s32OutHi,s32In1,s32In2 \
-        }                                                                                           \
-    }
+#define Mult32(s32In1, s32In2, s32OutLow)  \
+  {                                        \
+    __asm {                                                                                    \
+        MUL s32OutLow,s32In1,s32In2; } \
+  }
+#define Mult64(s32In1, s32In2, s32OutLow, s32OutHi)  \
+  {                                                  \
+    __asm {                                                                                   \
+        SMULL s32OutLow,s32OutHi,s32In1,s32In2 } \
+  }
 #else
 #define Mult32(s32In1, s32In2, s32OutLow) s32OutLow = (SINT32)s32In1 * (SINT32)s32In2;
-#define Mult64(s32In1, s32In2, s32OutLow, s32OutHi)              \
-    {                                                            \
-        s32OutLow = ((SINT32)(UINT16)s32In1 * (UINT16)s32In2);   \
-        s32TempVal2 = (SINT32)((s32In1 >> 16) * (UINT16)s32In2); \
-        s32Carry = ((((UINT32)(s32OutLow) >> 16) & 0xFFFF) +     \
-                    +(s32TempVal2 & 0xFFFF)) >>                  \
-                   16;                                           \
-        s32OutLow += (s32TempVal2 << 16);                        \
-        s32OutHi = (s32TempVal2 >> 16) + s32Carry;               \
-    }
+#define Mult64(s32In1, s32In2, s32OutLow, s32OutHi)                                         \
+  {                                                                                         \
+    s32OutLow   = ((SINT32)(UINT16)s32In1 * (UINT16)s32In2);                                \
+    s32TempVal2 = (SINT32)((s32In1 >> 16) * (UINT16)s32In2);                                \
+    s32Carry    = ((((UINT32)(s32OutLow) >> 16) & 0xFFFF) + +(s32TempVal2 & 0xFFFF)) >> 16; \
+    s32OutLow += (s32TempVal2 << 16);                                                       \
+    s32OutHi = (s32TempVal2 >> 16) + s32Carry;                                              \
+  }
 #endif
 
-void EncPacking(SBC_ENC_PARAMS *pstrEncParams)
-{
-    UINT8 *pu8PacketPtr; /* packet ptr*/
-    UINT8 Temp;
-    SINT32 s32Blk;        /* counter for block*/
-    SINT32 s32Ch;         /* counter for channel*/
-    SINT32 s32Sb;         /* counter for sub-band*/
-    SINT32 s32PresentBit; /* represents bit to be stored*/
-    /*SINT32 s32LoopCountI;                       loop counter*/
-    SINT32 s32LoopCountJ;                             /* loop counter*/
-    UINT32 u32QuantizedSbValue, u32QuantizedSbValue0; /* temp variable to store quantized sb val*/
-    SINT32 s32LoopCount;                              /* loop counter*/
-    UINT8 u8XoredVal;                                 /* to store XORed value in CRC calculation*/
-    UINT8 u8CRC;                                      /* to store CRC value*/
-    SINT16 *ps16GenPtr;
-    SINT32 s32NumOfBlocks;
-    SINT32 s32NumOfSubBands = pstrEncParams->s16NumOfSubBands;
-    SINT32 s32NumOfChannels = pstrEncParams->s16NumOfChannels;
-    UINT32 u32SfRaisedToPow2; /*scale factor raised to power 2*/
-    SINT16 *ps16ScfPtr;
-    SINT32 *ps32SbPtr;
-    UINT16 u16Levels; /*to store levels*/
-    SINT32 s32Temp1;  /*used in 64-bit multiplication*/
-    SINT32 s32Low;    /*used in 64-bit multiplication*/
+void EncPacking(SBC_ENC_PARAMS *pstrEncParams) {
+  UINT8 *pu8PacketPtr; /* packet ptr*/
+  UINT8  Temp;
+  SINT32 s32Blk;        /* counter for block*/
+  SINT32 s32Ch;         /* counter for channel*/
+  SINT32 s32Sb;         /* counter for sub-band*/
+  SINT32 s32PresentBit; /* represents bit to be stored*/
+  /*SINT32 s32LoopCountI;                       loop counter*/
+  SINT32  s32LoopCountJ;                             /* loop counter*/
+  UINT32  u32QuantizedSbValue, u32QuantizedSbValue0; /* temp variable to store quantized sb val*/
+  SINT32  s32LoopCount;                              /* loop counter*/
+  UINT8   u8XoredVal;                                /* to store XORed value in CRC calculation*/
+  UINT8   u8CRC;                                     /* to store CRC value*/
+  SINT16 *ps16GenPtr;
+  SINT32  s32NumOfBlocks;
+  SINT32  s32NumOfSubBands = pstrEncParams->s16NumOfSubBands;
+  SINT32  s32NumOfChannels = pstrEncParams->s16NumOfChannels;
+  UINT32  u32SfRaisedToPow2; /*scale factor raised to power 2*/
+  SINT16 *ps16ScfPtr;
+  SINT32 *ps32SbPtr;
+  UINT16  u16Levels; /*to store levels*/
+  SINT32  s32Temp1;  /*used in 64-bit multiplication*/
+  SINT32  s32Low;    /*used in 64-bit multiplication*/
 #if (SBC_IS_64_MULT_IN_QUANTIZER == TRUE)
-    SINT32 s32Hi1, s32Low1, s32Carry, s32TempVal2, s32Hi, s32Temp2;
+  SINT32 s32Hi1, s32Low1, s32Carry, s32TempVal2, s32Hi, s32Temp2;
 #endif
 
-    pu8PacketPtr = pstrEncParams->pu8NextPacket; /*Initialize the ptr*/
-    if (pstrEncParams->sbc_mode != SBC_MODE_MSBC) {
-        *pu8PacketPtr++ = (UINT8)SBC_SYNC_WORD_STD; /*Sync word*/
-        *pu8PacketPtr++ = (UINT8)(pstrEncParams->FrameHeader);
+  pu8PacketPtr = pstrEncParams->pu8NextPacket; /*Initialize the ptr*/
+  if (pstrEncParams->sbc_mode != SBC_MODE_MSBC) {
+    *pu8PacketPtr++ = (UINT8)SBC_SYNC_WORD_STD; /*Sync word*/
+    *pu8PacketPtr++ = (UINT8)(pstrEncParams->FrameHeader);
 
-        *pu8PacketPtr = (UINT8)(pstrEncParams->s16BitPool & 0x00FF);
-    } else {
-        *pu8PacketPtr++ = (UINT8)SBC_SYNC_WORD_MSBC; /*Sync word*/
-        // two reserved bytes
-        *pu8PacketPtr++ = 0;
-        *pu8PacketPtr = 0;
-    }
-    pu8PacketPtr += 2; /*skip for CRC*/
+    *pu8PacketPtr = (UINT8)(pstrEncParams->s16BitPool & 0x00FF);
+  } else {
+    *pu8PacketPtr++ = (UINT8)SBC_SYNC_WORD_MSBC; /*Sync word*/
+    // two reserved bytes
+    *pu8PacketPtr++ = 0;
+    *pu8PacketPtr   = 0;
+  }
+  pu8PacketPtr += 2; /*skip for CRC*/
 
-    /*here it indicate if it is byte boundary or nibble boundary*/
-    s32PresentBit = 8;
-    Temp = 0;
+  /*here it indicate if it is byte boundary or nibble boundary*/
+  s32PresentBit = 8;
+  Temp          = 0;
 #if (SBC_JOINT_STE_INCLUDED == TRUE)
-    if (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) {
-        /* pack join stero parameters */
-        for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
-            Temp <<= 1;
-            Temp |= pstrEncParams->as16Join[s32Sb];
-        }
+  if (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) {
+    /* pack join stero parameters */
+    for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
+      Temp <<= 1;
+      Temp |= pstrEncParams->as16Join[s32Sb];
+    }
 
-        /* pack RFA */
-        if (s32NumOfSubBands == SUB_BANDS_4) {
-            s32PresentBit = 4;
-        } else {
-            *(pu8PacketPtr++) = Temp;
-            Temp = 0;
-        }
+    /* pack RFA */
+    if (s32NumOfSubBands == SUB_BANDS_4) {
+      s32PresentBit = 4;
+    } else {
+      *(pu8PacketPtr++) = Temp;
+      Temp              = 0;
     }
+  }
 #endif
 
-    /* Pack Scale factor */
-    ps16GenPtr = pstrEncParams->as16ScaleFactor;
-    s32Sb = s32NumOfChannels * s32NumOfSubBands;
-    /*Temp=*pu8PacketPtr;*/
-    for (s32Ch = s32Sb; s32Ch > 0; s32Ch--) {
-        Temp <<= 4;
-        Temp |= *ps16GenPtr++;
+  /* Pack Scale factor */
+  ps16GenPtr = pstrEncParams->as16ScaleFactor;
+  s32Sb      = s32NumOfChannels * s32NumOfSubBands;
+  /*Temp=*pu8PacketPtr;*/
+  for (s32Ch = s32Sb; s32Ch > 0; s32Ch--) {
+    Temp <<= 4;
+    Temp |= *ps16GenPtr++;
 
-        if (s32PresentBit == 4) {
-            s32PresentBit = 8;
-            *(pu8PacketPtr++) = Temp;
-            Temp = 0;
-        } else {
-            s32PresentBit = 4;
-        }
+    if (s32PresentBit == 4) {
+      s32PresentBit     = 8;
+      *(pu8PacketPtr++) = Temp;
+      Temp              = 0;
+    } else {
+      s32PresentBit = 4;
     }
+  }
 
-    /* Pack samples */
-    ps32SbPtr = pstrEncParams->s32SbBuffer;
-    /*Temp=*pu8PacketPtr;*/
-    s32NumOfBlocks = pstrEncParams->s16NumOfBlocks;
-    for (s32Blk = s32NumOfBlocks - 1; s32Blk >= 0; s32Blk--) {
-        ps16GenPtr = pstrEncParams->as16Bits;
-        ps16ScfPtr = pstrEncParams->as16ScaleFactor;
-        for (s32Ch = s32Sb - 1; s32Ch >= 0; s32Ch--) {
-            s32LoopCount = *ps16GenPtr++;
-            if (s32LoopCount != 0) {
+  /* Pack samples */
+  ps32SbPtr = pstrEncParams->s32SbBuffer;
+  /*Temp=*pu8PacketPtr;*/
+  s32NumOfBlocks = pstrEncParams->s16NumOfBlocks;
+  for (s32Blk = s32NumOfBlocks - 1; s32Blk >= 0; s32Blk--) {
+    ps16GenPtr = pstrEncParams->as16Bits;
+    ps16ScfPtr = pstrEncParams->as16ScaleFactor;
+    for (s32Ch = s32Sb - 1; s32Ch >= 0; s32Ch--) {
+      s32LoopCount = *ps16GenPtr++;
+      if (s32LoopCount != 0) {
 #if (SBC_IS_64_MULT_IN_QUANTIZER == TRUE)
-                /* finding level from reconstruction part of decoder */
-                u32SfRaisedToPow2 = ((UINT32)1 << ((*ps16ScfPtr) + 1));
-                u16Levels = (UINT16)(((UINT32)1 << s32LoopCount) - 1);
+        /* finding level from reconstruction part of decoder */
+        u32SfRaisedToPow2 = ((UINT32)1 << ((*ps16ScfPtr) + 1));
+        u16Levels         = (UINT16)(((UINT32)1 << s32LoopCount) - 1);
 
-                /* quantizer */
-                s32Temp1 = (*ps32SbPtr >> 2) + (u32SfRaisedToPow2 << 12);
-                s32Temp2 = u16Levels;
+        /* quantizer */
+        s32Temp1 = (*ps32SbPtr >> 2) + (u32SfRaisedToPow2 << 12);
+        s32Temp2 = u16Levels;
 
-                Mult64(s32Temp1, s32Temp2, s32Low, s32Hi);
+        Mult64(s32Temp1, s32Temp2, s32Low, s32Hi);
 
-                s32Low1 = s32Low >> ((*ps16ScfPtr) + 2);
-                s32Low1 &= ((UINT32)1 << (32 - ((*ps16ScfPtr) + 2))) - 1;
-                s32Hi1 = s32Hi << (32 - ((*ps16ScfPtr) + 2));
+        s32Low1 = s32Low >> ((*ps16ScfPtr) + 2);
+        s32Low1 &= ((UINT32)1 << (32 - ((*ps16ScfPtr) + 2))) - 1;
+        s32Hi1 = s32Hi << (32 - ((*ps16ScfPtr) + 2));
 
-                u32QuantizedSbValue0 = (UINT16)((s32Low1 | s32Hi1) >> 12);
+        u32QuantizedSbValue0 = (UINT16)((s32Low1 | s32Hi1) >> 12);
 #else
-                /* finding level from reconstruction part of decoder */
-                u32SfRaisedToPow2 = ((UINT32)1 << *ps16ScfPtr);
-                u16Levels = (UINT16)(((UINT32)1 << s32LoopCount) - 1);
+        /* finding level from reconstruction part of decoder */
+        u32SfRaisedToPow2 = ((UINT32)1 << *ps16ScfPtr);
+        u16Levels         = (UINT16)(((UINT32)1 << s32LoopCount) - 1);
 
-                /* quantizer */
-                s32Temp1 = (*ps32SbPtr >> 15) + u32SfRaisedToPow2;
-                Mult32(s32Temp1, u16Levels, s32Low);
-                s32Low >>= (*ps16ScfPtr + 1);
-                u32QuantizedSbValue0 = (UINT16)s32Low;
+        /* quantizer */
+        s32Temp1 = (*ps32SbPtr >> 15) + u32SfRaisedToPow2;
+        Mult32(s32Temp1, u16Levels, s32Low);
+        s32Low >>= (*ps16ScfPtr + 1);
+        u32QuantizedSbValue0 = (UINT16)s32Low;
 #endif
-                /*store the number of bits required and the quantized s32Sb
-                sample to ease the coding*/
-                u32QuantizedSbValue = u32QuantizedSbValue0;
+        /*store the number of bits required and the quantized s32Sb
+        sample to ease the coding*/
+        u32QuantizedSbValue = u32QuantizedSbValue0;
 
-                if (s32PresentBit >= s32LoopCount) {
-                    Temp <<= s32LoopCount;
-                    Temp |= u32QuantizedSbValue;
-                    s32PresentBit -= s32LoopCount;
-                } else {
-                    while (s32PresentBit < s32LoopCount) {
-                        s32LoopCount -= s32PresentBit;
-                        u32QuantizedSbValue >>= s32LoopCount;
+        if (s32PresentBit >= s32LoopCount) {
+          Temp <<= s32LoopCount;
+          Temp |= u32QuantizedSbValue;
+          s32PresentBit -= s32LoopCount;
+        } else {
+          while (s32PresentBit < s32LoopCount) {
+            s32LoopCount -= s32PresentBit;
+            u32QuantizedSbValue >>= s32LoopCount;
 
-                        /*remove the unwanted msbs*/
-                        /*u32QuantizedSbValue <<= 16 - s32PresentBit;
-                        u32QuantizedSbValue >>= 16 - s32PresentBit;*/
+            /*remove the unwanted msbs*/
+            /*u32QuantizedSbValue <<= 16 - s32PresentBit;
+            u32QuantizedSbValue >>= 16 - s32PresentBit;*/
 
-                        Temp <<= s32PresentBit;
+            Temp <<= s32PresentBit;
 
-                        Temp |= u32QuantizedSbValue;
-                        /*restore the original*/
-                        u32QuantizedSbValue = u32QuantizedSbValue0;
+            Temp |= u32QuantizedSbValue;
+            /*restore the original*/
+            u32QuantizedSbValue = u32QuantizedSbValue0;
 
-                        *(pu8PacketPtr++) = Temp;
-                        Temp = 0;
-                        s32PresentBit = 8;
-                    }
-                    Temp <<= s32LoopCount;
+            *(pu8PacketPtr++) = Temp;
+            Temp              = 0;
+            s32PresentBit     = 8;
+          }
+          Temp <<= s32LoopCount;
 
-                    /* remove the unwanted msbs */
-                    /*u32QuantizedSbValue <<= 16 - s32LoopCount;
-                    u32QuantizedSbValue >>= 16 - s32LoopCount;*/
+          /* remove the unwanted msbs */
+          /*u32QuantizedSbValue <<= 16 - s32LoopCount;
+          u32QuantizedSbValue >>= 16 - s32LoopCount;*/
 
-                    Temp |= u32QuantizedSbValue;
+          Temp |= u32QuantizedSbValue;
 
-                    s32PresentBit -= s32LoopCount;
-                }
-            }
-            ps16ScfPtr++;
-            ps32SbPtr++;
+          s32PresentBit -= s32LoopCount;
         }
+      }
+      ps16ScfPtr++;
+      ps32SbPtr++;
     }
+  }
 
-    Temp <<= s32PresentBit;
-    *pu8PacketPtr = Temp;
-    pstrEncParams->u16PacketLength = pu8PacketPtr - pstrEncParams->pu8NextPacket + 1;
-    /*find CRC*/
-    pu8PacketPtr = pstrEncParams->pu8NextPacket + 1; /*Initialize the ptr*/
-    u8CRC = 0x0F;
-    s32LoopCount = s32Sb >> 1;
+  Temp <<= s32PresentBit;
+  *pu8PacketPtr                  = Temp;
+  pstrEncParams->u16PacketLength = pu8PacketPtr - pstrEncParams->pu8NextPacket + 1;
+  /*find CRC*/
+  pu8PacketPtr = pstrEncParams->pu8NextPacket + 1; /*Initialize the ptr*/
+  u8CRC        = 0x0F;
+  s32LoopCount = s32Sb >> 1;
 
-    /*
-    The loops is run from the start of the packet till the scale factor
-    parameters. In case of JS, 'join' parameter is included in the packet
-    so that many more bytes are included in CRC calculation.
-    */
-    Temp = *pu8PacketPtr;
-    for (s32Ch = 1; s32Ch < (s32LoopCount + 4); s32Ch++) {
-        /* skip sync word and CRC bytes */
-        if (s32Ch != 3) {
-            for (s32LoopCountJ = 7; s32LoopCountJ >= 0; s32LoopCountJ--) {
-                u8XoredVal = ((u8CRC >> 7) & 0x01) ^ ((Temp >> s32LoopCountJ) & 0x01);
-                u8CRC <<= 1;
-                u8CRC ^= (u8XoredVal * 0x1D);
-                u8CRC &= 0xFF;
-            }
-        }
-        Temp = *(++pu8PacketPtr);
+  /*
+  The loops is run from the start of the packet till the scale factor
+  parameters. In case of JS, 'join' parameter is included in the packet
+  so that many more bytes are included in CRC calculation.
+  */
+  Temp = *pu8PacketPtr;
+  for (s32Ch = 1; s32Ch < (s32LoopCount + 4); s32Ch++) {
+    /* skip sync word and CRC bytes */
+    if (s32Ch != 3) {
+      for (s32LoopCountJ = 7; s32LoopCountJ >= 0; s32LoopCountJ--) {
+        u8XoredVal = ((u8CRC >> 7) & 0x01) ^ ((Temp >> s32LoopCountJ) & 0x01);
+        u8CRC <<= 1;
+        u8CRC ^= (u8XoredVal * 0x1D);
+        u8CRC &= 0xFF;
+      }
     }
+    Temp = *(++pu8PacketPtr);
+  }
 
-    if (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) {
-        for (s32LoopCountJ = 7; s32LoopCountJ >= (8 - s32NumOfSubBands); s32LoopCountJ--) {
-            u8XoredVal = ((u8CRC >> 7) & 0x01) ^ ((Temp >> s32LoopCountJ) & 0x01);
-            u8CRC <<= 1;
-            u8CRC ^= (u8XoredVal * 0x1D);
-            u8CRC &= 0xFF;
-        }
+  if (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) {
+    for (s32LoopCountJ = 7; s32LoopCountJ >= (8 - s32NumOfSubBands); s32LoopCountJ--) {
+      u8XoredVal = ((u8CRC >> 7) & 0x01) ^ ((Temp >> s32LoopCountJ) & 0x01);
+      u8CRC <<= 1;
+      u8CRC ^= (u8XoredVal * 0x1D);
+      u8CRC &= 0xFF;
     }
+  }
 
-    /* CRC calculation ends here */
+  /* CRC calculation ends here */
 
-    /* store CRC in packet */
-    pu8PacketPtr = pstrEncParams->pu8NextPacket; /*Initialize the ptr*/
-    pu8PacketPtr += 3;
-    *pu8PacketPtr = u8CRC;
-    pstrEncParams->pu8NextPacket += pstrEncParams->u16PacketLength; /* move the pointer to the end in case there is more than one frame to encode */
+  /* store CRC in packet */
+  pu8PacketPtr = pstrEncParams->pu8NextPacket; /*Initialize the ptr*/
+  pu8PacketPtr += 3;
+  *pu8PacketPtr = u8CRC;
+  pstrEncParams->pu8NextPacket += pstrEncParams->u16PacketLength; /* move the pointer to the end in case there is more than one frame to encode */
 }
 
 #endif /* #if defined(SBC_ENC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/bas.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/bas.c
index f4b34c022e..851b403247 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/bas.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/bas.c
@@ -13,11 +13,11 @@
 #include 
 #include 
 
+#include "bas.h"
 #include "bluetooth.h"
 #include "conn.h"
 #include "gatt.h"
 #include "uuid.h"
-#include "bas.h"
 
 #if !defined(BFLB_BLE)
 #define LOG_LEVEL CONFIG_BT_GATT_BAS_LOG_LEVEL
@@ -27,64 +27,47 @@ LOG_MODULE_REGISTER(bas);
 
 static u8_t battery_level = 100U;
 
-static void blvl_ccc_cfg_changed(const struct bt_gatt_attr *attr,
-                                 u16_t value)
-{
-    ARG_UNUSED(attr);
+static void blvl_ccc_cfg_changed(const struct bt_gatt_attr *attr, u16_t value) {
+  ARG_UNUSED(attr);
 
-    bool notif_enabled = (value == BT_GATT_CCC_NOTIFY);
+  bool notif_enabled = (value == BT_GATT_CCC_NOTIFY);
 
 #if !defined(BFLB_BLE)
-    LOG_INF("BAS Notifications %s", notif_enabled ? "enabled" : "disabled");
+  LOG_INF("BAS Notifications %s", notif_enabled ? "enabled" : "disabled");
 #endif
 }
 
-static ssize_t read_blvl(struct bt_conn *conn,
-                         const struct bt_gatt_attr *attr, void *buf,
-                         u16_t len, u16_t offset)
-{
-    u8_t lvl8 = battery_level;
+static ssize_t read_blvl(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  u8_t lvl8 = battery_level;
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &lvl8,
-                             sizeof(lvl8));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &lvl8, sizeof(lvl8));
 }
 
 static struct bt_gatt_attr attrs[] = {
     BT_GATT_PRIMARY_SERVICE(BT_UUID_BAS),
-    BT_GATT_CHARACTERISTIC(BT_UUID_BAS_BATTERY_LEVEL,
-                           BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY,
-                           BT_GATT_PERM_READ, read_blvl, NULL,
-                           &battery_level),
+    BT_GATT_CHARACTERISTIC(BT_UUID_BAS_BATTERY_LEVEL, BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY, BT_GATT_PERM_READ, read_blvl, NULL, &battery_level),
     BT_GATT_CCC(blvl_ccc_cfg_changed, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),
-    BT_GATT_DESCRIPTOR(BT_UUID_HIDS_REPORT_REF, BT_GATT_PERM_READ,
-                       NULL, NULL, NULL),
+    BT_GATT_DESCRIPTOR(BT_UUID_HIDS_REPORT_REF, BT_GATT_PERM_READ, NULL, NULL, NULL),
 };
 
 struct bt_gatt_service bas = BT_GATT_SERVICE(attrs);
 
-void bas_init(void)
-{
-    bt_gatt_service_register(&bas);
-}
+void bas_init(void) { bt_gatt_service_register(&bas); }
 
-u8_t bt_gatt_bas_get_battery_level(void)
-{
-    return battery_level;
-}
+u8_t bt_gatt_bas_get_battery_level(void) { return battery_level; }
 
-int bt_gatt_bas_set_battery_level(u8_t level)
-{
-    int rc;
+int bt_gatt_bas_set_battery_level(u8_t level) {
+  int rc;
 
-    if (level > 100U) {
-        return -EINVAL;
-    }
+  if (level > 100U) {
+    return -EINVAL;
+  }
 
-    battery_level = level;
+  battery_level = level;
 
-    rc = bt_gatt_notify(NULL, &bas.attrs[1], &level, sizeof(level));
+  rc = bt_gatt_notify(NULL, &bas.attrs[1], &level, sizeof(level));
 
-    return rc == -ENOTCONN ? 0 : rc;
+  return rc == -ENOTCONN ? 0 : rc;
 }
 
 #if !defined(BFLB_BLE)
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/dis.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/dis.c
index 3e6e990358..5212492010 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/dis.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/dis.c
@@ -10,20 +10,20 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
+#include 
 #include 
 #include 
-#include 
 #include 
+#include 
 
 #include "settings.h"
 
 #include "bluetooth.h"
-#include "hci_host.h"
 #include "conn.h"
-#include "uuid.h"
-#include "gatt.h"
 #include "dis.h"
+#include "gatt.h"
+#include "hci_host.h"
+#include "uuid.h"
 
 #if !defined(BFLB_BLE)
 #define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_SERVICE)
@@ -33,10 +33,10 @@
 
 #if CONFIG_BT_GATT_DIS_PNP
 struct dis_pnp {
-    u8_t pnp_vid_src;
-    u16_t pnp_vid;
-    u16_t pnp_pid;
-    u16_t pnp_ver;
+  u8_t  pnp_vid_src;
+  u16_t pnp_vid;
+  u16_t pnp_pid;
+  u16_t pnp_ver;
 } __packed;
 
 #if defined(BFLB_BLE)
@@ -61,9 +61,9 @@ struct dis_pnp {
 
 static struct dis_pnp dis_pnp_id = {
     .pnp_vid_src = DIS_PNP_VID_SRC,
-    .pnp_vid = CONFIG_BT_GATT_DIS_PNP_VID,
-    .pnp_pid = CONFIG_BT_GATT_DIS_PNP_PID,
-    .pnp_ver = CONFIG_BT_GATT_DIS_PNP_VER,
+    .pnp_vid     = CONFIG_BT_GATT_DIS_PNP_VID,
+    .pnp_pid     = CONFIG_BT_GATT_DIS_PNP_PID,
+    .pnp_ver     = CONFIG_BT_GATT_DIS_PNP_VER,
 };
 #endif
 
@@ -71,20 +71,16 @@ static struct dis_pnp dis_pnp_id = {
 static u8_t dis_model[CONFIG_BT_GATT_DIS_STR_MAX] = CONFIG_BT_GATT_DIS_MODEL;
 static u8_t dis_manuf[CONFIG_BT_GATT_DIS_STR_MAX] = CONFIG_BT_GATT_DIS_MANUF;
 #if defined(CONFIG_BT_GATT_DIS_SERIAL_NUMBER)
-static u8_t dis_serial_number[CONFIG_BT_GATT_DIS_STR_MAX] =
-    CONFIG_BT_GATT_DIS_SERIAL_NUMBER_STR;
+static u8_t dis_serial_number[CONFIG_BT_GATT_DIS_STR_MAX] = CONFIG_BT_GATT_DIS_SERIAL_NUMBER_STR;
 #endif
 #if defined(CONFIG_BT_GATT_DIS_FW_REV)
-static u8_t dis_fw_rev[CONFIG_BT_GATT_DIS_STR_MAX] =
-    CONFIG_BT_GATT_DIS_FW_REV_STR;
+static u8_t dis_fw_rev[CONFIG_BT_GATT_DIS_STR_MAX] = CONFIG_BT_GATT_DIS_FW_REV_STR;
 #endif
 #if defined(CONFIG_BT_GATT_DIS_HW_REV)
-static u8_t dis_hw_rev[CONFIG_BT_GATT_DIS_STR_MAX] =
-    CONFIG_BT_GATT_DIS_HW_REV_STR;
+static u8_t dis_hw_rev[CONFIG_BT_GATT_DIS_STR_MAX] = CONFIG_BT_GATT_DIS_HW_REV_STR;
 #endif
 #if defined(CONFIG_BT_GATT_DIS_SW_REV)
-static u8_t dis_sw_rev[CONFIG_BT_GATT_DIS_STR_MAX] =
-    CONFIG_BT_GATT_DIS_SW_REV_STR;
+static u8_t dis_sw_rev[CONFIG_BT_GATT_DIS_STR_MAX] = CONFIG_BT_GATT_DIS_SW_REV_STR;
 #endif
 
 #define BT_GATT_DIS_MODEL_REF             dis_model
@@ -105,21 +101,13 @@ static u8_t dis_sw_rev[CONFIG_BT_GATT_DIS_STR_MAX] =
 
 #endif /* CONFIG_BT_GATT_DIS_SETTINGS */
 
-static ssize_t read_str(struct bt_conn *conn,
-                        const struct bt_gatt_attr *attr, void *buf,
-                        u16_t len, u16_t offset)
-{
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, attr->user_data,
-                             strlen(attr->user_data));
+static ssize_t read_str(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, attr->user_data, strlen(attr->user_data));
 }
 
 #if CONFIG_BT_GATT_DIS_PNP
-static ssize_t read_pnp_id(struct bt_conn *conn,
-                           const struct bt_gatt_attr *attr, void *buf,
-                           u16_t len, u16_t offset)
-{
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &dis_pnp_id,
-                             sizeof(dis_pnp_id));
+static ssize_t read_pnp_id(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &dis_pnp_id, sizeof(dis_pnp_id));
 }
 #endif
 
@@ -128,149 +116,130 @@ static struct bt_gatt_attr attrs[] = {
 
     BT_GATT_PRIMARY_SERVICE(BT_UUID_DIS),
 
-    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_MODEL_NUMBER,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_str, NULL, BT_GATT_DIS_MODEL_REF),
-    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_MANUFACTURER_NAME,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_str, NULL, BT_GATT_DIS_MANUF_REF),
+    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_MODEL_NUMBER, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_str, NULL, BT_GATT_DIS_MODEL_REF),
+    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_MANUFACTURER_NAME, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_str, NULL, BT_GATT_DIS_MANUF_REF),
 #if CONFIG_BT_GATT_DIS_PNP
-    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_PNP_ID,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_pnp_id, NULL, &dis_pnp_id),
+    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_PNP_ID, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_pnp_id, NULL, &dis_pnp_id),
 #endif
 
 #if defined(CONFIG_BT_GATT_DIS_SERIAL_NUMBER)
-    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_SERIAL_NUMBER,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_str, NULL,
-                           BT_GATT_DIS_SERIAL_NUMBER_STR_REF),
+    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_SERIAL_NUMBER, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_str, NULL, BT_GATT_DIS_SERIAL_NUMBER_STR_REF),
 #endif
 #if defined(CONFIG_BT_GATT_DIS_FW_REV)
-    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_FIRMWARE_REVISION,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_str, NULL, BT_GATT_DIS_FW_REV_STR_REF),
+    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_FIRMWARE_REVISION, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_str, NULL, BT_GATT_DIS_FW_REV_STR_REF),
 #endif
 #if defined(CONFIG_BT_GATT_DIS_HW_REV)
-    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_HARDWARE_REVISION,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_str, NULL, BT_GATT_DIS_HW_REV_STR_REF),
+    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_HARDWARE_REVISION, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_str, NULL, BT_GATT_DIS_HW_REV_STR_REF),
 #endif
 #if defined(CONFIG_BT_GATT_DIS_SW_REV)
-    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_SOFTWARE_REVISION,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_str, NULL, BT_GATT_DIS_SW_REV_STR_REF),
+    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_SOFTWARE_REVISION, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_str, NULL, BT_GATT_DIS_SW_REV_STR_REF),
 #endif
 
 };
 
 static struct bt_gatt_service dis_svc = BT_GATT_SERVICE(attrs);
 
-void dis_init(u8_t vid_src, u16_t vid, u16_t pid, u16_t pid_ver)
-{
-    dis_pnp_id.pnp_vid_src = vid_src;
-    dis_pnp_id.pnp_vid = vid;
-    dis_pnp_id.pnp_pid = pid;
-    dis_pnp_id.pnp_ver = pid_ver;
-    bt_gatt_service_register(&dis_svc);
+void dis_init(u8_t vid_src, u16_t vid, u16_t pid, u16_t pid_ver) {
+  dis_pnp_id.pnp_vid_src = vid_src;
+  dis_pnp_id.pnp_vid     = vid;
+  dis_pnp_id.pnp_pid     = pid;
+  dis_pnp_id.pnp_ver     = pid_ver;
+  bt_gatt_service_register(&dis_svc);
 }
 
 #if defined(CONFIG_BT_SETTINGS) && defined(CONFIG_BT_GATT_DIS_SETTINGS)
-static int dis_set(const char *name, size_t len_rd,
-                   settings_read_cb read_cb, void *store)
-{
-    int len, nlen;
-    const char *next;
-
-    nlen = settings_name_next(name, &next);
-    if (!strncmp(name, "manuf", nlen)) {
-        len = read_cb(store, &dis_manuf, sizeof(dis_manuf) - 1);
-        if (len < 0) {
-            BT_ERR("Failed to read manufacturer from storage"
-                   " (err %d)",
-                   len);
-        } else {
-            dis_manuf[len] = '\0';
-
-            BT_DBG("Manufacturer set to %s", dis_manuf);
-        }
-        return 0;
+static int dis_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *store) {
+  int         len, nlen;
+  const char *next;
+
+  nlen = settings_name_next(name, &next);
+  if (!strncmp(name, "manuf", nlen)) {
+    len = read_cb(store, &dis_manuf, sizeof(dis_manuf) - 1);
+    if (len < 0) {
+      BT_ERR("Failed to read manufacturer from storage"
+             " (err %d)",
+             len);
+    } else {
+      dis_manuf[len] = '\0';
+
+      BT_DBG("Manufacturer set to %s", dis_manuf);
     }
-    if (!strncmp(name, "model", nlen)) {
-        len = read_cb(store, &dis_model, sizeof(dis_model) - 1);
-        if (len < 0) {
-            BT_ERR("Failed to read model from storage"
-                   " (err %d)",
-                   len);
-        } else {
-            dis_model[len] = '\0';
-
-            BT_DBG("Model set to %s", dis_model);
-        }
-        return 0;
+    return 0;
+  }
+  if (!strncmp(name, "model", nlen)) {
+    len = read_cb(store, &dis_model, sizeof(dis_model) - 1);
+    if (len < 0) {
+      BT_ERR("Failed to read model from storage"
+             " (err %d)",
+             len);
+    } else {
+      dis_model[len] = '\0';
+
+      BT_DBG("Model set to %s", dis_model);
     }
+    return 0;
+  }
 #if defined(CONFIG_BT_GATT_DIS_SERIAL_NUMBER)
-    if (!strncmp(name, "serial", nlen)) {
-        len = read_cb(store, &dis_serial_number,
-                      sizeof(dis_serial_number) - 1);
-        if (len < 0) {
-            BT_ERR("Failed to read serial number from storage"
-                   " (err %d)",
-                   len);
-        } else {
-            dis_serial_number[len] = '\0';
-
-            BT_DBG("Serial number set to %s", dis_serial_number);
-        }
-        return 0;
+  if (!strncmp(name, "serial", nlen)) {
+    len = read_cb(store, &dis_serial_number, sizeof(dis_serial_number) - 1);
+    if (len < 0) {
+      BT_ERR("Failed to read serial number from storage"
+             " (err %d)",
+             len);
+    } else {
+      dis_serial_number[len] = '\0';
+
+      BT_DBG("Serial number set to %s", dis_serial_number);
     }
+    return 0;
+  }
 #endif
 #if defined(CONFIG_BT_GATT_DIS_FW_REV)
-    if (!strncmp(name, "fw", nlen)) {
-        len = read_cb(store, &dis_fw_rev, sizeof(dis_fw_rev) - 1);
-        if (len < 0) {
-            BT_ERR("Failed to read firmware revision from storage"
-                   " (err %d)",
-                   len);
-        } else {
-            dis_fw_rev[len] = '\0';
-
-            BT_DBG("Firmware revision set to %s", dis_fw_rev);
-        }
-        return 0;
+  if (!strncmp(name, "fw", nlen)) {
+    len = read_cb(store, &dis_fw_rev, sizeof(dis_fw_rev) - 1);
+    if (len < 0) {
+      BT_ERR("Failed to read firmware revision from storage"
+             " (err %d)",
+             len);
+    } else {
+      dis_fw_rev[len] = '\0';
+
+      BT_DBG("Firmware revision set to %s", dis_fw_rev);
     }
+    return 0;
+  }
 #endif
 #if defined(CONFIG_BT_GATT_DIS_HW_REV)
-    if (!strncmp(name, "hw", nlen)) {
-        len = read_cb(store, &dis_hw_rev, sizeof(dis_hw_rev) - 1);
-        if (len < 0) {
-            BT_ERR("Failed to read hardware revision from storage"
-                   " (err %d)",
-                   len);
-        } else {
-            dis_hw_rev[len] = '\0';
-
-            BT_DBG("Hardware revision set to %s", dis_hw_rev);
-        }
-        return 0;
+  if (!strncmp(name, "hw", nlen)) {
+    len = read_cb(store, &dis_hw_rev, sizeof(dis_hw_rev) - 1);
+    if (len < 0) {
+      BT_ERR("Failed to read hardware revision from storage"
+             " (err %d)",
+             len);
+    } else {
+      dis_hw_rev[len] = '\0';
+
+      BT_DBG("Hardware revision set to %s", dis_hw_rev);
     }
+    return 0;
+  }
 #endif
 #if defined(CONFIG_BT_GATT_DIS_SW_REV)
-    if (!strncmp(name, "sw", nlen)) {
-        len = read_cb(store, &dis_sw_rev, sizeof(dis_sw_rev) - 1);
-        if (len < 0) {
-            BT_ERR("Failed to read software revision from storage"
-                   " (err %d)",
-                   len);
-        } else {
-            dis_sw_rev[len] = '\0';
-
-            BT_DBG("Software revision set to %s", dis_sw_rev);
-        }
-        return 0;
+  if (!strncmp(name, "sw", nlen)) {
+    len = read_cb(store, &dis_sw_rev, sizeof(dis_sw_rev) - 1);
+    if (len < 0) {
+      BT_ERR("Failed to read software revision from storage"
+             " (err %d)",
+             len);
+    } else {
+      dis_sw_rev[len] = '\0';
+
+      BT_DBG("Software revision set to %s", dis_sw_rev);
     }
-#endif
     return 0;
+  }
+#endif
+  return 0;
 }
 
 SETTINGS_STATIC_HANDLER_DEFINE(bt_dis, "bt/dis", NULL, dis_set, NULL, NULL);
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c
index 14f3c9729d..f9c971be46 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c
@@ -8,50 +8,50 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
+#include 
+#include 
 #include 
 #include 
-#include 
-#include 
 #include 
+#include 
 
+#include "hog.h"
+#include "log.h"
 #include 
 #include 
-#include 
 #include 
-#include "hog.h"
-#include "log.h"
+#include 
 
 enum {
-    HIDS_REMOTE_WAKE = BIT(0),
-    HIDS_NORMALLY_CONNECTABLE = BIT(1),
+  HIDS_REMOTE_WAKE          = BIT(0),
+  HIDS_NORMALLY_CONNECTABLE = BIT(1),
 };
 
 struct hids_info {
-    uint16_t version; /* version number of base USB HID Specification */
-    uint8_t code;     /* country HID Device hardware is localized for. */
-    uint8_t flags;
+  uint16_t version; /* version number of base USB HID Specification */
+  uint8_t  code;    /* country HID Device hardware is localized for. */
+  uint8_t  flags;
 } __packed;
 
 struct hids_report {
-    uint8_t id;   /* report id */
-    uint8_t type; /* report type */
+  uint8_t id;   /* report id */
+  uint8_t type; /* report type */
 } __packed;
 
 static struct hids_info info = {
     .version = 0x0000,
-    .code = 0x00,
-    .flags = HIDS_NORMALLY_CONNECTABLE,
+    .code    = 0x00,
+    .flags   = HIDS_NORMALLY_CONNECTABLE,
 };
 
 enum {
-    HIDS_INPUT = 0x01,
-    HIDS_OUTPUT = 0x02,
-    HIDS_FEATURE = 0x03,
+  HIDS_INPUT   = 0x01,
+  HIDS_OUTPUT  = 0x02,
+  HIDS_FEATURE = 0x03,
 };
 
 static struct hids_report input = {
-    .id = 0x01,
+    .id   = 0x01,
     .type = HIDS_INPUT,
 };
 
@@ -86,127 +86,91 @@ static uint8_t report_map[] = {
     0xC0,       /* End Collection */
 };
 
-static ssize_t read_info(struct bt_conn *conn,
-                         const struct bt_gatt_attr *attr, void *buf,
-                         uint16_t len, uint16_t offset)
-{
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, attr->user_data,
-                             sizeof(struct hids_info));
+static ssize_t read_info(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, uint16_t len, uint16_t offset) {
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, attr->user_data, sizeof(struct hids_info));
 }
 
-static ssize_t read_report_map(struct bt_conn *conn,
-                               const struct bt_gatt_attr *attr, void *buf,
-                               uint16_t len, uint16_t offset)
-{
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, report_map,
-                             sizeof(report_map));
+static ssize_t read_report_map(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, uint16_t len, uint16_t offset) {
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, report_map, sizeof(report_map));
 }
 
-static ssize_t read_report(struct bt_conn *conn,
-                           const struct bt_gatt_attr *attr, void *buf,
-                           uint16_t len, uint16_t offset)
-{
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, attr->user_data,
-                             sizeof(struct hids_report));
+static ssize_t read_report(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, uint16_t len, uint16_t offset) {
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, attr->user_data, sizeof(struct hids_report));
 }
 
-static void input_ccc_changed(const struct bt_gatt_attr *attr, uint16_t value)
-{
-    simulate_input = (value == BT_GATT_CCC_NOTIFY) ? 1 : 0;
-    BT_WARN("simulate_input = [%d]\r\n", simulate_input);
+static void input_ccc_changed(const struct bt_gatt_attr *attr, uint16_t value) {
+  simulate_input = (value == BT_GATT_CCC_NOTIFY) ? 1 : 0;
+  BT_WARN("simulate_input = [%d]\r\n", simulate_input);
 }
 
-static ssize_t read_input_report(struct bt_conn *conn,
-                                 const struct bt_gatt_attr *attr, void *buf,
-                                 uint16_t len, uint16_t offset)
-{
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, NULL, 0);
-}
+static ssize_t read_input_report(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, uint16_t len, uint16_t offset) { return bt_gatt_attr_read(conn, attr, buf, len, offset, NULL, 0); }
 
-static ssize_t write_ctrl_point(struct bt_conn *conn,
-                                const struct bt_gatt_attr *attr,
-                                const void *buf, uint16_t len, uint16_t offset,
-                                uint8_t flags)
-{
-    uint8_t *value = attr->user_data;
+static ssize_t write_ctrl_point(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, uint16_t len, uint16_t offset, uint8_t flags) {
+  uint8_t *value = attr->user_data;
 
-    if (offset + len > sizeof(ctrl_point)) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
-    }
+  if (offset + len > sizeof(ctrl_point)) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
+  }
 
-    memcpy(value + offset, buf, len);
+  memcpy(value + offset, buf, len);
 
-    return len;
+  return len;
 }
 
 /* HID Service Declaration */
 static struct bt_gatt_attr attrs[] = {
     BT_GATT_PRIMARY_SERVICE(BT_UUID_HIDS),
-    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_INFO, BT_GATT_CHRC_READ,
-                           BT_GATT_PERM_READ, read_info, NULL, &info),
-    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_REPORT_MAP, BT_GATT_CHRC_READ,
-                           BT_GATT_PERM_READ, read_report_map, NULL, NULL),
-    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_REPORT,
-                           BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY,
-                           BT_GATT_PERM_READ_AUTHEN,
-                           read_input_report, NULL, NULL),
-    BT_GATT_CCC(input_ccc_changed,
-                BT_GATT_PERM_READ_AUTHEN | BT_GATT_PERM_WRITE_AUTHEN),
-    BT_GATT_DESCRIPTOR(BT_UUID_HIDS_REPORT_REF, BT_GATT_PERM_READ,
-                       read_report, NULL, &input),
-    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_CTRL_POINT,
-                           BT_GATT_CHRC_WRITE_WITHOUT_RESP,
-                           BT_GATT_PERM_WRITE,
-                           NULL, write_ctrl_point, &ctrl_point),
+    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_INFO, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_info, NULL, &info),
+    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_REPORT_MAP, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_report_map, NULL, NULL),
+    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_REPORT, BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY, BT_GATT_PERM_READ_AUTHEN, read_input_report, NULL, NULL),
+    BT_GATT_CCC(input_ccc_changed, BT_GATT_PERM_READ_AUTHEN | BT_GATT_PERM_WRITE_AUTHEN),
+    BT_GATT_DESCRIPTOR(BT_UUID_HIDS_REPORT_REF, BT_GATT_PERM_READ, read_report, NULL, &input),
+    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_CTRL_POINT, BT_GATT_CHRC_WRITE_WITHOUT_RESP, BT_GATT_PERM_WRITE, NULL, write_ctrl_point, &ctrl_point),
 };
 
 struct hids_remote_key {
-    u8_t hid_page;
-    u16_t hid_usage;
+  u8_t  hid_page;
+  u16_t hid_usage;
 } __packed;
 
 static struct hids_remote_key remote_kbd_map_tab[] = {
-    { HID_PAGE_KBD, Key_a_or_A2 },
-    { HID_PAGE_KBD, Key_b_or_B },
-    { HID_PAGE_KBD, Key_c_or_C },
+    {HID_PAGE_KBD, Key_a_or_A2},
+    {HID_PAGE_KBD, Key_b_or_B},
+    {HID_PAGE_KBD, Key_c_or_C},
 };
 
-int hog_notify(struct bt_conn *conn, uint16_t hid_usage, uint8_t press)
-{
-    struct bt_gatt_attr *attr;
-    struct hids_remote_key *remote_key = NULL;
-    u8_t len = 4, data[4];
-
-    for (int i = 0; i < (sizeof(remote_kbd_map_tab) / sizeof(remote_kbd_map_tab[0])); i++) {
-        if (remote_kbd_map_tab[i].hid_usage == hid_usage) {
-            remote_key = &remote_kbd_map_tab[i];
-            break;
-        }
+int hog_notify(struct bt_conn *conn, uint16_t hid_usage, uint8_t press) {
+  struct bt_gatt_attr    *attr;
+  struct hids_remote_key *remote_key = NULL;
+  u8_t                    len        = 4, data[4];
+
+  for (int i = 0; i < (sizeof(remote_kbd_map_tab) / sizeof(remote_kbd_map_tab[0])); i++) {
+    if (remote_kbd_map_tab[i].hid_usage == hid_usage) {
+      remote_key = &remote_kbd_map_tab[i];
+      break;
     }
+  }
 
-    if (!remote_key)
-        return EINVAL;
+  if (!remote_key)
+    return EINVAL;
 
-    if (remote_key->hid_page == HID_PAGE_KBD) {
-        attr = &attrs[BT_CHAR_BLE_HID_REPORT_ATTR_VAL_INDEX];
-        len = 3;
-    } else
-        return EINVAL;
+  if (remote_key->hid_page == HID_PAGE_KBD) {
+    attr = &attrs[BT_CHAR_BLE_HID_REPORT_ATTR_VAL_INDEX];
+    len  = 3;
+  } else
+    return EINVAL;
 
-    sys_put_le16(hid_usage, data);
-    data[2] = 0;
-    data[3] = 0;
+  sys_put_le16(hid_usage, data);
+  data[2] = 0;
+  data[3] = 0;
 
-    if (!press) {
-        memset(data, 0, len);
-    }
+  if (!press) {
+    memset(data, 0, len);
+  }
 
-    return bt_gatt_notify(conn, attr, data, len);
+  return bt_gatt_notify(conn, attr, data, len);
 }
 
 struct bt_gatt_service hog_srv = BT_GATT_SERVICE(attrs);
 
-void hog_init(void)
-{
-    bt_gatt_service_register(&hog_srv);
-}
+void hog_init(void) { bt_gatt_service_register(&hog_srv); }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.c
index 67d4db3bcd..6bd0ed37e3 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.c
@@ -11,64 +11,55 @@
  *
  ****************************************************************************************
  */
+#include "scps.h"
 #include "bluetooth.h"
+#include "byteorder.h"
 #include "gatt.h"
 #include "uuid.h"
-#include "scps.h"
-#include "byteorder.h"
 
 struct scan_intvl_win {
-    u16_t scan_intvl;
-    u16_t scan_win;
+  u16_t scan_intvl;
+  u16_t scan_win;
 } __packed;
 
 static struct scan_intvl_win intvl_win = {
     .scan_intvl = BT_GAP_SCAN_FAST_INTERVAL,
-    .scan_win = BT_GAP_SCAN_FAST_WINDOW,
+    .scan_win   = BT_GAP_SCAN_FAST_WINDOW,
 };
 
-static ssize_t scan_intvl_win_write(struct bt_conn *conn,
-                                    const struct bt_gatt_attr *attr, const void *buf,
-                                    u16_t len, u16_t offset, u8_t flags)
-{
-    const u8_t *data = buf;
-    intvl_win.scan_intvl = sys_get_le16(data);
-    data += 2;
-    intvl_win.scan_win = sys_get_le16(data);
+static ssize_t scan_intvl_win_write(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len, u16_t offset, u8_t flags) {
+  const u8_t *data     = buf;
+  intvl_win.scan_intvl = sys_get_le16(data);
+  data += 2;
+  intvl_win.scan_win = sys_get_le16(data);
 
-    return len;
+  return len;
 }
 
-static struct bt_gatt_attr attrs[] = {
-    BT_GATT_PRIMARY_SERVICE(BT_UUID_SCPS),
-    BT_GATT_CHARACTERISTIC(BT_UUID_SCPS_SCAN_INTVL_WIN,
-                           BT_GATT_CHRC_WRITE_WITHOUT_RESP,
-                           BT_GATT_PERM_NONE, NULL, NULL,
-                           &intvl_win)
-};
+static struct bt_gatt_attr attrs[]
+    = {BT_GATT_PRIMARY_SERVICE(BT_UUID_SCPS), BT_GATT_CHARACTERISTIC(BT_UUID_SCPS_SCAN_INTVL_WIN, BT_GATT_CHRC_WRITE_WITHOUT_RESP, BT_GATT_PERM_NONE, NULL, NULL, &intvl_win)};
 
 static struct bt_gatt_service scps = BT_GATT_SERVICE(attrs);
 
-bool scps_init(u16_t scan_intvl, u16_t scan_win)
-{
-    int err;
+bool scps_init(u16_t scan_intvl, u16_t scan_win) {
+  int err;
 
-    if (scan_intvl < 0x0004 || scan_intvl > 0x4000) {
-        return false;
-    }
+  if (scan_intvl < 0x0004 || scan_intvl > 0x4000) {
+    return false;
+  }
 
-    if (scan_win < 0x0004 || scan_win > 0x4000) {
-        return false;
-    }
+  if (scan_win < 0x0004 || scan_win > 0x4000) {
+    return false;
+  }
 
-    if (scan_win > scan_intvl) {
-        return false;
-    }
+  if (scan_win > scan_intvl) {
+    return false;
+  }
 
-    intvl_win.scan_intvl = scan_intvl;
-    intvl_win.scan_win = scan_win;
+  intvl_win.scan_intvl = scan_intvl;
+  intvl_win.scan_win   = scan_win;
 
-    err = bt_gatt_service_register(&scps);
+  err = bt_gatt_service_register(&scps);
 
-    return err ? false : true;
+  return err ? false : true;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/freertos/portable/gcc/risc-v/bl702/port.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/freertos/portable/gcc/risc-v/bl702/port.c
index 36ec151443..7a70a0938b 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/freertos/portable/gcc/risc-v/bl702/port.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/freertos/portable/gcc/risc-v/bl702/port.c
@@ -31,8 +31,8 @@
 
 /* Scheduler includes. */
 #include "FreeRTOS.h"
-#include "task.h"
 #include "portmacro.h"
+#include "task.h"
 
 #ifndef configCLINT_BASE_ADDRESS
 #warning configCLINT_BASE_ADDRESS must be defined in FreeRTOSConfig.h.  If the target chip includes a Core Local Interrupter (CLINT) then set configCLINT_BASE_ADDRESS to the CLINT base address.  Otherwise set configCLINT_BASE_ADDRESS to 0.
@@ -55,11 +55,11 @@ of the stack used by main.  Using the linker script method will repurpose the
 stack that was used by main before the scheduler was started for use as the
 interrupt stack after the scheduler has started. */
 #ifdef configISR_STACK_SIZE_WORDS
-static __attribute__((aligned(16))) StackType_t xISRStack[configISR_STACK_SIZE_WORDS] = { 0 };
-const StackType_t xISRStackTop = (StackType_t) & (xISRStack[configISR_STACK_SIZE_WORDS & ~portBYTE_ALIGNMENT_MASK]);
+static __attribute__((aligned(16))) StackType_t xISRStack[configISR_STACK_SIZE_WORDS] = {0};
+const StackType_t                               xISRStackTop                          = (StackType_t) & (xISRStack[configISR_STACK_SIZE_WORDS & ~portBYTE_ALIGNMENT_MASK]);
 #else
 extern const uint32_t __freertos_irq_stack_top[];
-const StackType_t xISRStackTop = (StackType_t)__freertos_irq_stack_top;
+const StackType_t     xISRStackTop = (StackType_t)__freertos_irq_stack_top;
 #endif
 
 /*
@@ -72,13 +72,13 @@ void vPortSetupTimerInterrupt(void) __attribute__((weak));
 /*-----------------------------------------------------------*/
 
 /* Used to program the machine timer compare register. */
-uint64_t ullNextTime = 0ULL;
-const uint64_t *pullNextTime = &ullNextTime;
-const size_t uxTimerIncrementsForOneTick = (size_t)(configCPU_CLOCK_HZ / configTICK_RATE_HZ); /* Assumes increment won't go over 32-bits. */
+uint64_t                 ullNextTime                         = 0ULL;
+const uint64_t          *pullNextTime                        = &ullNextTime;
+const size_t             uxTimerIncrementsForOneTick         = (size_t)(configCPU_CLOCK_HZ / configTICK_RATE_HZ); /* Assumes increment won't go over 32-bits. */
 volatile uint64_t *const pullMachineTimerCompareRegisterBase = (volatile uint64_t *const)(configCLINT_BASE_ADDRESS + 0x4000);
-volatile uint64_t *pullMachineTimerCompareRegister = 0;
-BaseType_t TrapNetCounter = 0;
-const BaseType_t *pTrapNetCounter = &TrapNetCounter;
+volatile uint64_t       *pullMachineTimerCompareRegister     = 0;
+BaseType_t               TrapNetCounter                      = 0;
+const BaseType_t        *pTrapNetCounter                     = &TrapNetCounter;
 
 /* Set configCHECK_FOR_STACK_OVERFLOW to 3 to add ISR stack checking to task
 stack checking.  A problem in the ISR stack will trigger an assert, not call the
@@ -91,13 +91,10 @@ the task stacks, and so will legitimately appear in many positions within
 the ISR stack. */
 #define portISR_STACK_FILL_BYTE 0xee
 
-static const uint8_t ucExpectedStackBytes[] = {
-    portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,
-    portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,
-    portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,
-    portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,
-    portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE
-};
+static const uint8_t ucExpectedStackBytes[]
+    = {portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,
+       portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,
+       portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE};
 
 #define portCHECK_ISR_STACK() configASSERT((memcmp((void *)xISRStack, (void *)ucExpectedStackBytes, sizeof(ucExpectedStackBytes)) == 0))
 #else
@@ -109,87 +106,82 @@ static const uint8_t ucExpectedStackBytes[] = {
 
 #if (configCLINT_BASE_ADDRESS != 0)
 
-void vPortSetupTimerInterrupt(void)
-{
-    uint32_t ulCurrentTimeHigh, ulCurrentTimeLow;
-    volatile uint32_t *const pulTimeHigh = (volatile uint32_t *const)(configCLINT_BASE_ADDRESS + 0xBFFC);
-    volatile uint32_t *const pulTimeLow = (volatile uint32_t *const)(configCLINT_BASE_ADDRESS + 0xBFF8);
-    volatile uint32_t ulHartId = 0;
-
-    __asm volatile("csrr %0, mhartid"
-                   : "=r"(ulHartId));
-    pullMachineTimerCompareRegister = &(pullMachineTimerCompareRegisterBase[ulHartId]);
-
-    do {
-        ulCurrentTimeHigh = *pulTimeHigh;
-        ulCurrentTimeLow = *pulTimeLow;
-    } while (ulCurrentTimeHigh != *pulTimeHigh);
-
-    ullNextTime = (uint64_t)ulCurrentTimeHigh;
-    ullNextTime <<= 32ULL;
-    ullNextTime |= (uint64_t)ulCurrentTimeLow;
-    ullNextTime += (uint64_t)uxTimerIncrementsForOneTick;
-    *pullMachineTimerCompareRegister = ullNextTime;
-
-    /* Prepare the time to use after the next tick interrupt. */
-    ullNextTime += (uint64_t)uxTimerIncrementsForOneTick;
+void vPortSetupTimerInterrupt(void) {
+  uint32_t                 ulCurrentTimeHigh, ulCurrentTimeLow;
+  volatile uint32_t *const pulTimeHigh = (volatile uint32_t *const)(configCLINT_BASE_ADDRESS + 0xBFFC);
+  volatile uint32_t *const pulTimeLow  = (volatile uint32_t *const)(configCLINT_BASE_ADDRESS + 0xBFF8);
+  volatile uint32_t        ulHartId    = 0;
+
+  __asm volatile("csrr %0, mhartid" : "=r"(ulHartId));
+  pullMachineTimerCompareRegister = &(pullMachineTimerCompareRegisterBase[ulHartId]);
+
+  do {
+    ulCurrentTimeHigh = *pulTimeHigh;
+    ulCurrentTimeLow  = *pulTimeLow;
+  } while (ulCurrentTimeHigh != *pulTimeHigh);
+
+  ullNextTime = (uint64_t)ulCurrentTimeHigh;
+  ullNextTime <<= 32ULL;
+  ullNextTime |= (uint64_t)ulCurrentTimeLow;
+  ullNextTime += (uint64_t)uxTimerIncrementsForOneTick;
+  *pullMachineTimerCompareRegister = ullNextTime;
+
+  /* Prepare the time to use after the next tick interrupt. */
+  ullNextTime += (uint64_t)uxTimerIncrementsForOneTick;
 }
 
 #endif /* ( configCLINT_BASE_ADDRESS != 0 ) */
 /*-----------------------------------------------------------*/
 
-BaseType_t xPortStartScheduler(void)
-{
-    extern void xPortStartFirstTask(void);
+BaseType_t xPortStartScheduler(void) {
+  extern void xPortStartFirstTask(void);
 
 #if (configASSERT_DEFINED == 1)
-    {
-        volatile uint32_t mtvec = 0;
-
-        /* Check the least significant two bits of mtvec are 00 - indicating
-        single vector mode. */
-        __asm volatile("csrr %0, mtvec"
-                       : "=r"(mtvec));
-        //configASSERT( ( mtvec & 0x03UL ) == 0 );
-
-        /* Check alignment of the interrupt stack - which is the same as the
-        stack that was being used by main() prior to the scheduler being
-        started. */
-        configASSERT((xISRStackTop & portBYTE_ALIGNMENT_MASK) == 0);
-    }
+  {
+    volatile uint32_t mtvec = 0;
+
+    /* Check the least significant two bits of mtvec are 00 - indicating
+    single vector mode. */
+    __asm volatile("csrr %0, mtvec" : "=r"(mtvec));
+    // configASSERT( ( mtvec & 0x03UL ) == 0 );
+
+    /* Check alignment of the interrupt stack - which is the same as the
+    stack that was being used by main() prior to the scheduler being
+    started. */
+    configASSERT((xISRStackTop & portBYTE_ALIGNMENT_MASK) == 0);
+  }
 #endif /* configASSERT_DEFINED */
 
-    /* If there is a CLINT then it is ok to use the default implementation
-    in this file, otherwise vPortSetupTimerInterrupt() must be implemented to
-    configure whichever clock is to be used to generate the tick interrupt. */
-    vPortSetupTimerInterrupt();
+  /* If there is a CLINT then it is ok to use the default implementation
+  in this file, otherwise vPortSetupTimerInterrupt() must be implemented to
+  configure whichever clock is to be used to generate the tick interrupt. */
+  vPortSetupTimerInterrupt();
 
 #if (configCLINT_BASE_ADDRESS != 0)
-    {
-        /* Enable mtime and external interrupts.  1<<7 for timer interrupt, 1<<11
-        for external interrupt.  _RB_ What happens here when mtime is not present as
-        with pulpino? */
-        __asm volatile("csrs mie, %0" ::"r"(0x880));
-    }
+  {
+    /* Enable mtime and external interrupts.  1<<7 for timer interrupt, 1<<11
+    for external interrupt.  _RB_ What happens here when mtime is not present as
+    with pulpino? */
+    __asm volatile("csrs mie, %0" ::"r"(0x880));
+  }
 #else
-    {
-        /* Enable external interrupts. */
-        __asm volatile("csrs mie, %0" ::"r"(0x800));
-    }
+  {
+    /* Enable external interrupts. */
+    __asm volatile("csrs mie, %0" ::"r"(0x800));
+  }
 #endif /* configCLINT_BASE_ADDRESS */
 
-    *(uint8_t *)(0x02800400 + 7) = 1;
-    xPortStartFirstTask();
+  *(uint8_t *)(0x02800400 + 7) = 1;
+  xPortStartFirstTask();
 
-    /* Should not get here as after calling xPortStartFirstTask() only tasks
-    should be executing. */
-    return pdFAIL;
+  /* Should not get here as after calling xPortStartFirstTask() only tasks
+  should be executing. */
+  return pdFAIL;
 }
 /*-----------------------------------------------------------*/
 
-void vPortEndScheduler(void)
-{
-    /* Not implemented. */
-    for (;;)
-        ;
+void vPortEndScheduler(void) {
+  /* Not implemented. */
+  for (;;)
+    ;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.c
index 94d4311f9b..15c19a29f6 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.c
@@ -1,114 +1,109 @@
-#include "usbd_core.h"
 #include "usbd_audio.h"
+#include "usbd_core.h"
 
-struct usbd_audio_control_info audio_control_info = { 0xdb00, 0x0000, 0x0100, 0xf600, 0 };
-
-int audio_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("AUDIO Class request: "
-                 "bRequest 0x%02x\r\n",
-                 setup->bRequest);
-
-    switch (setup->bRequest) {
-        case AUDIO_REQUEST_SET_CUR:
-
-            if (setup->wValueL == 0x01) {
-                if (setup->wValueH == AUDIO_FU_CONTROL_MUTE) {
-                    memcpy(&audio_control_info.mute, *data, *len);
-                } else if (setup->wValueH == AUDIO_FU_CONTROL_VOLUME) {
-                    memcpy(&audio_control_info.vol_current, *data, *len);
-                    uint32_t vol;
-                    if (audio_control_info.vol_current == 0) {
-                        vol = 100;
-                    } else {
-                        vol = (audio_control_info.vol_current - 0xDB00 + 1) * 100 / (0xFFFF - 0xDB00);
-                    }
-                    usbd_audio_set_volume(vol);
-                    USBD_LOG_INFO("current audio volume:%d\r\n", vol);
-                }
-            }
-
-            break;
-
-        case AUDIO_REQUEST_GET_CUR:
-            if (setup->wValueH == AUDIO_FU_CONTROL_MUTE) {
-                *data = (uint8_t *)&audio_control_info.mute;
-                *len = 1;
-            } else if (setup->wValueH == AUDIO_FU_CONTROL_VOLUME) {
-                *data = (uint8_t *)&audio_control_info.vol_current;
-                *len = 2;
-            }
-
-            break;
-
-        case AUDIO_REQUEST_SET_RES:
-            break;
-
-        case AUDIO_REQUEST_SET_MEM:
-            break;
-
-        case AUDIO_REQUEST_GET_MIN:
-            *data = (uint8_t *)&audio_control_info.vol_min;
-            *len = 2;
-            break;
-
-        case AUDIO_REQUEST_GET_MAX:
-            *data = (uint8_t *)&audio_control_info.vol_max;
-            *len = 2;
-            break;
-
-        case AUDIO_REQUEST_GET_RES:
-            *data = (uint8_t *)&audio_control_info.vol_res;
-            *len = 2;
-            break;
-        case AUDIO_REQUEST_GET_MEM:
-            *data[0] = 0;
-            *len = 1;
-            break;
-
-        default:
-            USBD_LOG_WRN("Unhandled Audio Class bRequest 0x%02x\r\n", setup->bRequest);
-            return -1;
+struct usbd_audio_control_info audio_control_info = {0xdb00, 0x0000, 0x0100, 0xf600, 0};
+
+int audio_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) {
+  USBD_LOG_DBG("AUDIO Class request: "
+               "bRequest 0x%02x\r\n",
+               setup->bRequest);
+
+  switch (setup->bRequest) {
+  case AUDIO_REQUEST_SET_CUR:
+
+    if (setup->wValueL == 0x01) {
+      if (setup->wValueH == AUDIO_FU_CONTROL_MUTE) {
+        memcpy(&audio_control_info.mute, *data, *len);
+      } else if (setup->wValueH == AUDIO_FU_CONTROL_VOLUME) {
+        memcpy(&audio_control_info.vol_current, *data, *len);
+        uint32_t vol;
+        if (audio_control_info.vol_current == 0) {
+          vol = 100;
+        } else {
+          vol = (audio_control_info.vol_current - 0xDB00 + 1) * 100 / (0xFFFF - 0xDB00);
+        }
+        usbd_audio_set_volume(vol);
+        USBD_LOG_INFO("current audio volume:%d\r\n", vol);
+      }
     }
 
-    return 0;
-}
+    break;
+
+  case AUDIO_REQUEST_GET_CUR:
+    if (setup->wValueH == AUDIO_FU_CONTROL_MUTE) {
+      *data = (uint8_t *)&audio_control_info.mute;
+      *len  = 1;
+    } else if (setup->wValueH == AUDIO_FU_CONTROL_VOLUME) {
+      *data = (uint8_t *)&audio_control_info.vol_current;
+      *len  = 2;
+    }
 
-void audio_notify_handler(uint8_t event, void *arg)
-{
-    switch (event) {
-        case USB_EVENT_RESET:
+    break;
 
-            break;
+  case AUDIO_REQUEST_SET_RES:
+    break;
 
-        case USB_EVENT_SOF:
-            break;
+  case AUDIO_REQUEST_SET_MEM:
+    break;
 
-        case USB_EVENT_SET_INTERFACE:
-            usbd_audio_set_interface_callback(((uint8_t *)arg)[3]);
-            break;
+  case AUDIO_REQUEST_GET_MIN:
+    *data = (uint8_t *)&audio_control_info.vol_min;
+    *len  = 2;
+    break;
 
-        default:
-            break;
-    }
+  case AUDIO_REQUEST_GET_MAX:
+    *data = (uint8_t *)&audio_control_info.vol_max;
+    *len  = 2;
+    break;
+
+  case AUDIO_REQUEST_GET_RES:
+    *data = (uint8_t *)&audio_control_info.vol_res;
+    *len  = 2;
+    break;
+  case AUDIO_REQUEST_GET_MEM:
+    *data[0] = 0;
+    *len     = 1;
+    break;
+
+  default:
+    USBD_LOG_WRN("Unhandled Audio Class bRequest 0x%02x\r\n", setup->bRequest);
+    return -1;
+  }
+
+  return 0;
 }
 
-__weak void usbd_audio_set_volume(uint8_t vol)
-{
+void audio_notify_handler(uint8_t event, void *arg) {
+  switch (event) {
+  case USB_EVENT_RESET:
+
+    break;
+
+  case USB_EVENT_SOF:
+    break;
+
+  case USB_EVENT_SET_INTERFACE:
+    usbd_audio_set_interface_callback(((uint8_t *)arg)[3]);
+    break;
+
+  default:
+    break;
+  }
 }
 
-void usbd_audio_add_interface(usbd_class_t *class, usbd_interface_t *intf)
-{
-    static usbd_class_t *last_class = NULL;
+__weak void usbd_audio_set_volume(uint8_t vol) {}
 
-    if (last_class != class) {
-        last_class = class;
-        usbd_class_register(class);
-    }
+void usbd_audio_add_interface(usbd_class_t *class, usbd_interface_t *intf) {
+  static usbd_class_t *last_class = NULL;
+
+  if (last_class != class) {
+    last_class = class;
+    usbd_class_register(class);
+  }
 
-    intf->class_handler = audio_class_request_handler;
-    intf->custom_handler = NULL;
-    intf->vendor_handler = NULL;
-    intf->notify_handler = audio_notify_handler;
-    usbd_class_add_interface(class, intf);
+  intf->class_handler  = audio_class_request_handler;
+  intf->custom_handler = NULL;
+  intf->vendor_handler = NULL;
+  intf->notify_handler = audio_notify_handler;
+  usbd_class_add_interface(class, intf);
 }
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.c
index c48a74a8d0..81384d6f21 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.c
@@ -20,38 +20,37 @@
  * under the License.
  *
  */
-#include "usbd_core.h"
 #include "usbd_cdc.h"
+#include "usbd_core.h"
 
-const char *stop_name[] = { "1", "1.5", "2" };
-const char *parity_name[] = { "N", "O", "E", "M", "S" };
+const char *stop_name[]   = {"1", "1.5", "2"};
+const char *parity_name[] = {"N", "O", "E", "M", "S"};
 
 /* Device data structure */
 struct cdc_acm_cfg_private {
-    /* CDC ACM line coding properties. LE order */
-    struct cdc_line_coding line_coding;
-    /* CDC ACM line state bitmap, DTE side */
-    uint8_t line_state;
-    /* CDC ACM serial state bitmap, DCE side */
-    uint8_t serial_state;
-    /* CDC ACM notification sent status */
-    uint8_t notification_sent;
-    /* CDC ACM configured flag */
-    bool configured;
-    /* CDC ACM suspended flag */
-    bool suspended;
-    uint32_t uart_first_init_flag;
+  /* CDC ACM line coding properties. LE order */
+  struct cdc_line_coding line_coding;
+  /* CDC ACM line state bitmap, DTE side */
+  uint8_t line_state;
+  /* CDC ACM serial state bitmap, DCE side */
+  uint8_t serial_state;
+  /* CDC ACM notification sent status */
+  uint8_t notification_sent;
+  /* CDC ACM configured flag */
+  bool configured;
+  /* CDC ACM suspended flag */
+  bool     suspended;
+  uint32_t uart_first_init_flag;
 
 } usbd_cdc_acm_cfg;
 
-static void usbd_cdc_acm_reset(void)
-{
-    usbd_cdc_acm_cfg.line_coding.dwDTERate = 2000000;
-    usbd_cdc_acm_cfg.line_coding.bDataBits = 8;
-    usbd_cdc_acm_cfg.line_coding.bParityType = 0;
-    usbd_cdc_acm_cfg.line_coding.bCharFormat = 0;
-    usbd_cdc_acm_cfg.configured = false;
-    usbd_cdc_acm_cfg.uart_first_init_flag = 0;
+static void usbd_cdc_acm_reset(void) {
+  usbd_cdc_acm_cfg.line_coding.dwDTERate   = 2000000;
+  usbd_cdc_acm_cfg.line_coding.bDataBits   = 8;
+  usbd_cdc_acm_cfg.line_coding.bParityType = 0;
+  usbd_cdc_acm_cfg.line_coding.bCharFormat = 0;
+  usbd_cdc_acm_cfg.configured              = false;
+  usbd_cdc_acm_cfg.uart_first_init_flag    = 0;
 }
 
 /**
@@ -63,109 +62,92 @@ static void usbd_cdc_acm_reset(void)
  *
  * @return  0 on success, negative errno code on fail.
  */
-static int cdc_acm_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("CDC Class request: "
-                 "bRequest 0x%02x\r\n",
-                 setup->bRequest);
-
-    switch (setup->bRequest) {
-        case CDC_REQUEST_SET_LINE_CODING:
-
-            /*******************************************************************************/
-            /* Line Coding Structure                                                       */
-            /*-----------------------------------------------------------------------------*/
-            /* Offset | Field       | Size | Value  | Description                          */
-            /* 0      | dwDTERate   |   4  | Number |Data terminal rate, in bits per second*/
-            /* 4      | bCharFormat |   1  | Number | Stop bits                            */
-            /*                                        0 - 1 Stop bit                       */
-            /*                                        1 - 1.5 Stop bits                    */
-            /*                                        2 - 2 Stop bits                      */
-            /* 5      | bParityType |  1   | Number | Parity                               */
-            /*                                        0 - None                             */
-            /*                                        1 - Odd                              */
-            /*                                        2 - Even                             */
-            /*                                        3 - Mark                             */
-            /*                                        4 - Space                            */
-            /* 6      | bDataBits  |   1   | Number Data bits (5, 6, 7, 8 or 16).          */
-            /*******************************************************************************/
-            if (usbd_cdc_acm_cfg.uart_first_init_flag == 0) {
-                usbd_cdc_acm_cfg.uart_first_init_flag = 1;
-                return 0;
-            }
-
-            memcpy(&usbd_cdc_acm_cfg.line_coding, *data, sizeof(usbd_cdc_acm_cfg.line_coding));
-            USBD_LOG_DBG("CDC_SET_LINE_CODING <%d %d %s %s>\r\n",
-                         usbd_cdc_acm_cfg.line_coding.dwDTERate,
-                         usbd_cdc_acm_cfg.line_coding.bDataBits,
-                         parity_name[usbd_cdc_acm_cfg.line_coding.bParityType],
-                         stop_name[usbd_cdc_acm_cfg.line_coding.bCharFormat]);
-            usbd_cdc_acm_set_line_coding(usbd_cdc_acm_cfg.line_coding.dwDTERate, usbd_cdc_acm_cfg.line_coding.bDataBits,
-                                         usbd_cdc_acm_cfg.line_coding.bParityType, usbd_cdc_acm_cfg.line_coding.bCharFormat);
-            break;
-
-        case CDC_REQUEST_SET_CONTROL_LINE_STATE:
-            usbd_cdc_acm_cfg.line_state = (uint8_t)setup->wValue;
-            bool dtr = (setup->wValue & 0x01);
-            bool rts = (setup->wValue & 0x02);
-            USBD_LOG_DBG("DTR 0x%x,RTS 0x%x\r\n",
-                         dtr, rts);
-            usbd_cdc_acm_set_dtr(dtr);
-            usbd_cdc_acm_set_rts(rts);
-            break;
-
-        case CDC_REQUEST_GET_LINE_CODING:
-            *data = (uint8_t *)(&usbd_cdc_acm_cfg.line_coding);
-            *len = sizeof(usbd_cdc_acm_cfg.line_coding);
-            USBD_LOG_DBG("CDC_GET_LINE_CODING %d %d %d %d\r\n",
-                         usbd_cdc_acm_cfg.line_coding.dwDTERate,
-                         usbd_cdc_acm_cfg.line_coding.bCharFormat,
-                         usbd_cdc_acm_cfg.line_coding.bParityType,
-                         usbd_cdc_acm_cfg.line_coding.bDataBits);
-            break;
-
-        default:
-            USBD_LOG_WRN("Unhandled CDC Class bRequest 0x%02x\r\n", setup->bRequest);
-            return -1;
+static int cdc_acm_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) {
+  USBD_LOG_DBG("CDC Class request: "
+               "bRequest 0x%02x\r\n",
+               setup->bRequest);
+
+  switch (setup->bRequest) {
+  case CDC_REQUEST_SET_LINE_CODING:
+
+    /*******************************************************************************/
+    /* Line Coding Structure                                                       */
+    /*-----------------------------------------------------------------------------*/
+    /* Offset | Field       | Size | Value  | Description                          */
+    /* 0      | dwDTERate   |   4  | Number |Data terminal rate, in bits per second*/
+    /* 4      | bCharFormat |   1  | Number | Stop bits                            */
+    /*                                        0 - 1 Stop bit                       */
+    /*                                        1 - 1.5 Stop bits                    */
+    /*                                        2 - 2 Stop bits                      */
+    /* 5      | bParityType |  1   | Number | Parity                               */
+    /*                                        0 - None                             */
+    /*                                        1 - Odd                              */
+    /*                                        2 - Even                             */
+    /*                                        3 - Mark                             */
+    /*                                        4 - Space                            */
+    /* 6      | bDataBits  |   1   | Number Data bits (5, 6, 7, 8 or 16).          */
+    /*******************************************************************************/
+    if (usbd_cdc_acm_cfg.uart_first_init_flag == 0) {
+      usbd_cdc_acm_cfg.uart_first_init_flag = 1;
+      return 0;
     }
 
-    return 0;
+    memcpy(&usbd_cdc_acm_cfg.line_coding, *data, sizeof(usbd_cdc_acm_cfg.line_coding));
+    USBD_LOG_DBG("CDC_SET_LINE_CODING <%d %d %s %s>\r\n", usbd_cdc_acm_cfg.line_coding.dwDTERate, usbd_cdc_acm_cfg.line_coding.bDataBits, parity_name[usbd_cdc_acm_cfg.line_coding.bParityType],
+                 stop_name[usbd_cdc_acm_cfg.line_coding.bCharFormat]);
+    usbd_cdc_acm_set_line_coding(usbd_cdc_acm_cfg.line_coding.dwDTERate, usbd_cdc_acm_cfg.line_coding.bDataBits, usbd_cdc_acm_cfg.line_coding.bParityType, usbd_cdc_acm_cfg.line_coding.bCharFormat);
+    break;
+
+  case CDC_REQUEST_SET_CONTROL_LINE_STATE:
+    usbd_cdc_acm_cfg.line_state = (uint8_t)setup->wValue;
+    bool dtr                    = (setup->wValue & 0x01);
+    bool rts                    = (setup->wValue & 0x02);
+    USBD_LOG_DBG("DTR 0x%x,RTS 0x%x\r\n", dtr, rts);
+    usbd_cdc_acm_set_dtr(dtr);
+    usbd_cdc_acm_set_rts(rts);
+    break;
+
+  case CDC_REQUEST_GET_LINE_CODING:
+    *data = (uint8_t *)(&usbd_cdc_acm_cfg.line_coding);
+    *len  = sizeof(usbd_cdc_acm_cfg.line_coding);
+    USBD_LOG_DBG("CDC_GET_LINE_CODING %d %d %d %d\r\n", usbd_cdc_acm_cfg.line_coding.dwDTERate, usbd_cdc_acm_cfg.line_coding.bCharFormat, usbd_cdc_acm_cfg.line_coding.bParityType,
+                 usbd_cdc_acm_cfg.line_coding.bDataBits);
+    break;
+
+  default:
+    USBD_LOG_WRN("Unhandled CDC Class bRequest 0x%02x\r\n", setup->bRequest);
+    return -1;
+  }
+
+  return 0;
 }
 
-static void cdc_notify_handler(uint8_t event, void *arg)
-{
-    switch (event) {
-        case USB_EVENT_RESET:
-            usbd_cdc_acm_reset();
-            break;
+static void cdc_notify_handler(uint8_t event, void *arg) {
+  switch (event) {
+  case USB_EVENT_RESET:
+    usbd_cdc_acm_reset();
+    break;
 
-        default:
-            break;
-    }
+  default:
+    break;
+  }
 }
 
-__weak void usbd_cdc_acm_set_line_coding(uint32_t baudrate, uint8_t databits, uint8_t parity, uint8_t stopbits)
-{
-}
-__weak void usbd_cdc_acm_set_dtr(bool dtr)
-{
-}
-__weak void usbd_cdc_acm_set_rts(bool rts)
-{
-}
+__weak void usbd_cdc_acm_set_line_coding(uint32_t baudrate, uint8_t databits, uint8_t parity, uint8_t stopbits) {}
+__weak void usbd_cdc_acm_set_dtr(bool dtr) {}
+__weak void usbd_cdc_acm_set_rts(bool rts) {}
 
-void usbd_cdc_add_acm_interface(usbd_class_t *class, usbd_interface_t *intf)
-{
-    static usbd_class_t *last_class = NULL;
+void usbd_cdc_add_acm_interface(usbd_class_t *class, usbd_interface_t *intf) {
+  static usbd_class_t *last_class = NULL;
 
-    if (last_class != class) {
-        last_class = class;
-        usbd_class_register(class);
-    }
+  if (last_class != class) {
+    last_class = class;
+    usbd_class_register(class);
+  }
 
-    intf->class_handler = cdc_acm_class_request_handler;
-    intf->custom_handler = NULL;
-    intf->vendor_handler = NULL;
-    intf->notify_handler = cdc_notify_handler;
-    usbd_class_add_interface(class, intf);
+  intf->class_handler  = cdc_acm_class_request_handler;
+  intf->custom_handler = NULL;
+  intf->vendor_handler = NULL;
+  intf->notify_handler = cdc_notify_handler;
+  usbd_class_add_interface(class, intf);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.c
index 5e66d18b03..6ee9e3c891 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.c
@@ -20,217 +20,204 @@
  * under the License.
  *
  */
-#include "usbd_core.h"
 #include "usbd_hid.h"
+#include "usbd_core.h"
 
 #define HID_STATE_IDLE 0
 #define HID_STATE_BUSY 1
 
 struct usbd_hid_cfg_private {
-    const uint8_t *hid_descriptor;
-    const uint8_t *hid_report_descriptor;
-    uint32_t hid_report_descriptor_len;
-    uint8_t current_intf_num;
-    uint8_t hid_state;
-    uint8_t report;
-    uint8_t idle_state;
-    uint8_t protocol;
-
-    uint8_t (*get_report_callback)(uint8_t report_id, uint8_t report_type);
-    void (*set_report_callback)(uint8_t report_id, uint8_t report_type, uint8_t *report, uint8_t report_len);
-    uint8_t (*get_idle_callback)(uint8_t report_id);
-    void (*set_idle_callback)(uint8_t report_id, uint8_t duration);
-    void (*set_protocol_callback)(uint8_t protocol);
-    uint8_t (*get_protocol_callback)(void);
-
-    usb_slist_t list;
+  const uint8_t *hid_descriptor;
+  const uint8_t *hid_report_descriptor;
+  uint32_t       hid_report_descriptor_len;
+  uint8_t        current_intf_num;
+  uint8_t        hid_state;
+  uint8_t        report;
+  uint8_t        idle_state;
+  uint8_t        protocol;
+
+  uint8_t (*get_report_callback)(uint8_t report_id, uint8_t report_type);
+  void (*set_report_callback)(uint8_t report_id, uint8_t report_type, uint8_t *report, uint8_t report_len);
+  uint8_t (*get_idle_callback)(uint8_t report_id);
+  void (*set_idle_callback)(uint8_t report_id, uint8_t duration);
+  void (*set_protocol_callback)(uint8_t protocol);
+  uint8_t (*get_protocol_callback)(void);
+
+  usb_slist_t list;
 } usbd_hid_cfg[4];
 
 static usb_slist_t usbd_hid_class_head = USB_SLIST_OBJECT_INIT(usbd_hid_class_head);
 
-static void usbd_hid_reset(void)
-{
-    usb_slist_t *i;
-    usb_slist_for_each(i, &usbd_hid_class_head)
-    {
-        struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list);
-        hid_intf->hid_state = HID_STATE_IDLE;
-        hid_intf->report = 0;
-        hid_intf->idle_state = 0;
-        hid_intf->protocol = 0;
-    }
+static void usbd_hid_reset(void) {
+  usb_slist_t *i;
+  usb_slist_for_each(i, &usbd_hid_class_head) {
+    struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list);
+    hid_intf->hid_state                   = HID_STATE_IDLE;
+    hid_intf->report                      = 0;
+    hid_intf->idle_state                  = 0;
+    hid_intf->protocol                    = 0;
+  }
 }
 
-int hid_custom_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("HID Custom request: "
-                 "bRequest 0x%02x\r\n",
-                 setup->bRequest);
-
-    if (REQTYPE_GET_DIR(setup->bmRequestType) == USB_REQUEST_DEVICE_TO_HOST &&
-        setup->bRequest == USB_REQUEST_GET_DESCRIPTOR) {
-        uint8_t value = (uint8_t)(setup->wValue >> 8);
-        uint8_t intf_num = (uint8_t)setup->wIndex;
-
-        struct usbd_hid_cfg_private *current_hid_intf = NULL;
-        usb_slist_t *i;
-        usb_slist_for_each(i, &usbd_hid_class_head)
-        {
-            struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list);
-
-            if (hid_intf->current_intf_num == intf_num) {
-                current_hid_intf = hid_intf;
-                break;
-            }
-        }
-
-        if (current_hid_intf == NULL) {
-            return -2;
-        }
-
-        switch (value) {
-            case HID_DESCRIPTOR_TYPE_HID:
-                USBD_LOG_INFO("get HID Descriptor\r\n");
-                *data = (uint8_t *)current_hid_intf->hid_descriptor;
-                *len = current_hid_intf->hid_descriptor[0];
-                break;
-
-            case HID_DESCRIPTOR_TYPE_HID_REPORT:
-                USBD_LOG_INFO("get Report Descriptor\r\n");
-                *data = (uint8_t *)current_hid_intf->hid_report_descriptor;
-                *len = current_hid_intf->hid_report_descriptor_len;
-                break;
-
-            case HID_DESCRIPTOR_TYPE_HID_PHYSICAL:
-                USBD_LOG_INFO("get PHYSICAL Descriptor\r\n");
-
-                break;
-
-            default:
-                return -2;
-        }
-
-        return 0;
-    }
-
-    return -1;
-}
+int hid_custom_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) {
+  USBD_LOG_DBG("HID Custom request: "
+               "bRequest 0x%02x\r\n",
+               setup->bRequest);
 
-int hid_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("HID Class request: "
-                 "bRequest 0x%02x\r\n",
-                 setup->bRequest);
+  if (REQTYPE_GET_DIR(setup->bmRequestType) == USB_REQUEST_DEVICE_TO_HOST && setup->bRequest == USB_REQUEST_GET_DESCRIPTOR) {
+    uint8_t value    = (uint8_t)(setup->wValue >> 8);
+    uint8_t intf_num = (uint8_t)setup->wIndex;
 
     struct usbd_hid_cfg_private *current_hid_intf = NULL;
-    usb_slist_t *i;
-    usb_slist_for_each(i, &usbd_hid_class_head)
-    {
-        struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list);
-        uint8_t intf_num = (uint8_t)setup->wIndex;
-        if (hid_intf->current_intf_num == intf_num) {
-            current_hid_intf = hid_intf;
-            break;
-        }
+    usb_slist_t                 *i;
+    usb_slist_for_each(i, &usbd_hid_class_head) {
+      struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list);
+
+      if (hid_intf->current_intf_num == intf_num) {
+        current_hid_intf = hid_intf;
+        break;
+      }
     }
 
     if (current_hid_intf == NULL) {
-        return -2;
+      return -2;
     }
 
-    switch (setup->bRequest) {
-        case HID_REQUEST_GET_REPORT:
-            if (current_hid_intf->get_report_callback)
-                current_hid_intf->report = current_hid_intf->get_report_callback(setup->wValueL, setup->wValueH); /*report id ,report type*/
-
-            *data = (uint8_t *)¤t_hid_intf->report;
-            *len = 1;
-            break;
-        case HID_REQUEST_GET_IDLE:
-            if (current_hid_intf->get_idle_callback)
-                current_hid_intf->idle_state = current_hid_intf->get_idle_callback(setup->wValueL);
-
-            *data = (uint8_t *)¤t_hid_intf->idle_state;
-            *len = 1;
-            break;
-        case HID_REQUEST_GET_PROTOCOL:
-            if (current_hid_intf->get_protocol_callback)
-                current_hid_intf->protocol = current_hid_intf->get_protocol_callback();
-
-            *data = (uint8_t *)¤t_hid_intf->protocol;
-            *len = 1;
-            break;
-        case HID_REQUEST_SET_REPORT:
-            if (current_hid_intf->set_report_callback)
-                current_hid_intf->set_report_callback(setup->wValueL, setup->wValueH, *data, *len); /*report id ,report type,report,report len*/
-
-            current_hid_intf->report = **data;
-            break;
-        case HID_REQUEST_SET_IDLE:
-            if (current_hid_intf->set_idle_callback)
-                current_hid_intf->set_idle_callback(setup->wValueL, setup->wIndexH); /*report id ,duration*/
-
-            current_hid_intf->idle_state = setup->wIndexH;
-            break;
-        case HID_REQUEST_SET_PROTOCOL:
-            if (current_hid_intf->set_protocol_callback)
-                current_hid_intf->set_protocol_callback(setup->wValueL); /*protocol*/
-
-            current_hid_intf->protocol = setup->wValueL;
-            break;
-
-        default:
-            USBD_LOG_WRN("Unhandled HID Class bRequest 0x%02x\r\n", setup->bRequest);
-            return -1;
+    switch (value) {
+    case HID_DESCRIPTOR_TYPE_HID:
+      USBD_LOG_INFO("get HID Descriptor\r\n");
+      *data = (uint8_t *)current_hid_intf->hid_descriptor;
+      *len  = current_hid_intf->hid_descriptor[0];
+      break;
+
+    case HID_DESCRIPTOR_TYPE_HID_REPORT:
+      USBD_LOG_INFO("get Report Descriptor\r\n");
+      *data = (uint8_t *)current_hid_intf->hid_report_descriptor;
+      *len  = current_hid_intf->hid_report_descriptor_len;
+      break;
+
+    case HID_DESCRIPTOR_TYPE_HID_PHYSICAL:
+      USBD_LOG_INFO("get PHYSICAL Descriptor\r\n");
+
+      break;
+
+    default:
+      return -2;
     }
 
     return 0;
-}
+  }
 
-static void hid_notify_handler(uint8_t event, void *arg)
-{
-    switch (event) {
-        case USB_EVENT_RESET:
-            usbd_hid_reset();
-            break;
+  return -1;
+}
 
-        default:
-            break;
+int hid_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) {
+  USBD_LOG_DBG("HID Class request: "
+               "bRequest 0x%02x\r\n",
+               setup->bRequest);
+
+  struct usbd_hid_cfg_private *current_hid_intf = NULL;
+  usb_slist_t                 *i;
+  usb_slist_for_each(i, &usbd_hid_class_head) {
+    struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list);
+    uint8_t                      intf_num = (uint8_t)setup->wIndex;
+    if (hid_intf->current_intf_num == intf_num) {
+      current_hid_intf = hid_intf;
+      break;
     }
+  }
+
+  if (current_hid_intf == NULL) {
+    return -2;
+  }
+
+  switch (setup->bRequest) {
+  case HID_REQUEST_GET_REPORT:
+    if (current_hid_intf->get_report_callback)
+      current_hid_intf->report = current_hid_intf->get_report_callback(setup->wValueL, setup->wValueH); /*report id ,report type*/
+
+    *data = (uint8_t *)¤t_hid_intf->report;
+    *len  = 1;
+    break;
+  case HID_REQUEST_GET_IDLE:
+    if (current_hid_intf->get_idle_callback)
+      current_hid_intf->idle_state = current_hid_intf->get_idle_callback(setup->wValueL);
+
+    *data = (uint8_t *)¤t_hid_intf->idle_state;
+    *len  = 1;
+    break;
+  case HID_REQUEST_GET_PROTOCOL:
+    if (current_hid_intf->get_protocol_callback)
+      current_hid_intf->protocol = current_hid_intf->get_protocol_callback();
+
+    *data = (uint8_t *)¤t_hid_intf->protocol;
+    *len  = 1;
+    break;
+  case HID_REQUEST_SET_REPORT:
+    if (current_hid_intf->set_report_callback)
+      current_hid_intf->set_report_callback(setup->wValueL, setup->wValueH, *data, *len); /*report id ,report type,report,report len*/
+
+    current_hid_intf->report = **data;
+    break;
+  case HID_REQUEST_SET_IDLE:
+    if (current_hid_intf->set_idle_callback)
+      current_hid_intf->set_idle_callback(setup->wValueL, setup->wIndexH); /*report id ,duration*/
+
+    current_hid_intf->idle_state = setup->wIndexH;
+    break;
+  case HID_REQUEST_SET_PROTOCOL:
+    if (current_hid_intf->set_protocol_callback)
+      current_hid_intf->set_protocol_callback(setup->wValueL); /*protocol*/
+
+    current_hid_intf->protocol = setup->wValueL;
+    break;
+
+  default:
+    USBD_LOG_WRN("Unhandled HID Class bRequest 0x%02x\r\n", setup->bRequest);
+    return -1;
+  }
+
+  return 0;
 }
 
-void usbd_hid_reset_state(void)
-{
-    // usbd_hid_cfg.hid_state = HID_STATE_IDLE;
+static void hid_notify_handler(uint8_t event, void *arg) {
+  switch (event) {
+  case USB_EVENT_RESET:
+    usbd_hid_reset();
+    break;
+
+  default:
+    break;
+  }
 }
 
-void usbd_hid_send_report(uint8_t ep, uint8_t *data, uint8_t len)
-{
-    // if(usbd_hid_cfg.hid_state == HID_STATE_IDLE)
-    // {
-    //     usbd_hid_cfg.hid_state = HID_STATE_BUSY;
-    //     usbd_ep_write(ep, data, len, NULL);
-    // }
+void usbd_hid_reset_state(void) {
+  // usbd_hid_cfg.hid_state = HID_STATE_IDLE;
 }
 
-void usbd_hid_descriptor_register(uint8_t intf_num, const uint8_t *desc)
-{
-    // usbd_hid_cfg.hid_descriptor = desc;
+void usbd_hid_send_report(uint8_t ep, uint8_t *data, uint8_t len) {
+  // if(usbd_hid_cfg.hid_state == HID_STATE_IDLE)
+  // {
+  //     usbd_hid_cfg.hid_state = HID_STATE_BUSY;
+  //     usbd_ep_write(ep, data, len, NULL);
+  // }
 }
 
-void usbd_hid_report_descriptor_register(uint8_t intf_num, const uint8_t *desc, uint32_t desc_len)
-{
-    usb_slist_t *i;
-    usb_slist_for_each(i, &usbd_hid_class_head)
-    {
-        struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list);
-
-        if (hid_intf->current_intf_num == intf_num) {
-            hid_intf->hid_report_descriptor = desc;
-            hid_intf->hid_report_descriptor_len = desc_len;
-            return;
-        }
+void usbd_hid_descriptor_register(uint8_t intf_num, const uint8_t *desc) {
+  // usbd_hid_cfg.hid_descriptor = desc;
+}
+
+void usbd_hid_report_descriptor_register(uint8_t intf_num, const uint8_t *desc, uint32_t desc_len) {
+  usb_slist_t *i;
+  usb_slist_for_each(i, &usbd_hid_class_head) {
+    struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list);
+
+    if (hid_intf->current_intf_num == intf_num) {
+      hid_intf->hid_report_descriptor     = desc;
+      hid_intf->hid_report_descriptor_len = desc_len;
+      return;
     }
+  }
 }
 // clang-format off
 void usbd_hid_set_request_callback( uint8_t intf_num,
@@ -242,45 +229,43 @@ void usbd_hid_set_request_callback( uint8_t intf_num,
                                     uint8_t (*get_protocol_callback)(void))
 // clang-format on
 {
-    usb_slist_t *i;
-    usb_slist_for_each(i, &usbd_hid_class_head)
-    {
-        struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list);
-
-        if (hid_intf->current_intf_num == intf_num) {
-            if (get_report_callback)
-                hid_intf->get_report_callback = get_report_callback;
-            if (set_report_callback)
-                hid_intf->set_report_callback = set_report_callback;
-            if (get_idle_callback)
-                hid_intf->get_idle_callback = get_idle_callback;
-            if (set_idle_callback)
-                hid_intf->set_idle_callback = set_idle_callback;
-            if (set_protocol_callback)
-                hid_intf->set_protocol_callback = set_protocol_callback;
-            if (get_protocol_callback)
-                hid_intf->get_protocol_callback = get_protocol_callback;
-            return;
-        }
+  usb_slist_t *i;
+  usb_slist_for_each(i, &usbd_hid_class_head) {
+    struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list);
+
+    if (hid_intf->current_intf_num == intf_num) {
+      if (get_report_callback)
+        hid_intf->get_report_callback = get_report_callback;
+      if (set_report_callback)
+        hid_intf->set_report_callback = set_report_callback;
+      if (get_idle_callback)
+        hid_intf->get_idle_callback = get_idle_callback;
+      if (set_idle_callback)
+        hid_intf->set_idle_callback = set_idle_callback;
+      if (set_protocol_callback)
+        hid_intf->set_protocol_callback = set_protocol_callback;
+      if (get_protocol_callback)
+        hid_intf->get_protocol_callback = get_protocol_callback;
+      return;
     }
+  }
 }
 
-void usbd_hid_add_interface(usbd_class_t *class, usbd_interface_t *intf)
-{
-    static usbd_class_t *last_class = NULL;
-    static uint8_t hid_num = 0;
-    if (last_class != class) {
-        last_class = class;
-        usbd_class_register(class);
-    }
-
-    intf->class_handler = hid_class_request_handler;
-    intf->custom_handler = hid_custom_request_handler;
-    intf->vendor_handler = NULL;
-    intf->notify_handler = hid_notify_handler;
-    usbd_class_add_interface(class, intf);
-
-    usbd_hid_cfg[hid_num].current_intf_num = intf->intf_num;
-    usb_slist_add_tail(&usbd_hid_class_head, &usbd_hid_cfg[hid_num].list);
-    hid_num++;
+void usbd_hid_add_interface(usbd_class_t *class, usbd_interface_t *intf) {
+  static usbd_class_t *last_class = NULL;
+  static uint8_t       hid_num    = 0;
+  if (last_class != class) {
+    last_class = class;
+    usbd_class_register(class);
+  }
+
+  intf->class_handler  = hid_class_request_handler;
+  intf->custom_handler = hid_custom_request_handler;
+  intf->vendor_handler = NULL;
+  intf->notify_handler = hid_notify_handler;
+  usbd_class_add_interface(class, intf);
+
+  usbd_hid_cfg[hid_num].current_intf_num = intf->intf_num;
+  usb_slist_add_tail(&usbd_hid_class_head, &usbd_hid_cfg[hid_num].list);
+  hid_num++;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.c
index 262adbb111..90cca19c0d 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.c
@@ -20,9 +20,9 @@
  * under the License.
  *
  */
+#include "usbd_msc.h"
 #include "usbd_core.h"
 #include "usbd_scsi.h"
-#include "usbd_msc.h"
 
 /* max USB packet size */
 #ifndef CONFIG_USB_HS
@@ -39,75 +39,74 @@ static usbd_endpoint_t mass_ep_data[2];
 
 /* MSC Bulk-only Stage */
 enum Stage {
-    MSC_READ_CBW = 0, /* Command Block Wrapper */
-    MSC_DATA_OUT = 1, /* Data Out Phase */
-    MSC_DATA_IN = 2,  /* Data In Phase */
-    MSC_SEND_CSW = 3, /* Command Status Wrapper */
-    MSC_WAIT_CSW = 4, /* Command Status Wrapper */
+  MSC_READ_CBW = 0, /* Command Block Wrapper */
+  MSC_DATA_OUT = 1, /* Data Out Phase */
+  MSC_DATA_IN  = 2, /* Data In Phase */
+  MSC_SEND_CSW = 3, /* Command Status Wrapper */
+  MSC_WAIT_CSW = 4, /* Command Status Wrapper */
 };
 
 /** MSC Bulk-Only Command Block Wrapper (CBW) */
 struct CBW {
-    uint32_t dSignature;
-    uint32_t dTag;
-    uint32_t dDataLength;
-    uint8_t bmFlags;
-    uint8_t bLUN;
-    uint8_t bCBLength;
-    uint8_t CB[16];
+  uint32_t dSignature;
+  uint32_t dTag;
+  uint32_t dDataLength;
+  uint8_t  bmFlags;
+  uint8_t  bLUN;
+  uint8_t  bCBLength;
+  uint8_t  CB[16];
 } __packed;
 
 /** MSC Bulk-Only Command Status Wrapper (CSW) */
 struct CSW {
-    uint32_t dSignature;
-    uint32_t dTag;
-    uint32_t dDataResidue;
-    uint8_t bStatus;
+  uint32_t dSignature;
+  uint32_t dTag;
+  uint32_t dDataResidue;
+  uint8_t  bStatus;
 } __packed;
 
 /* Device data structure */
 struct usbd_msc_cfg_private {
-    /* state of the bulk-only state machine */
-    enum Stage stage;
-    struct CBW cbw;
-    struct CSW csw;
-
-    uint8_t sKey; /* Sense key */
-    uint8_t ASC;  /* Additional Sense Code */
-    uint8_t ASQ;  /* Additional Sense Qualifier */
-    uint8_t max_lun;
-    uint16_t scsi_blk_size;
-    uint32_t scsi_blk_nbr;
-
-    uint32_t scsi_blk_addr;
-    uint32_t scsi_blk_len;
-    uint8_t *block_buffer;
+  /* state of the bulk-only state machine */
+  enum Stage stage;
+  struct CBW cbw;
+  struct CSW csw;
+
+  uint8_t  sKey; /* Sense key */
+  uint8_t  ASC;  /* Additional Sense Code */
+  uint8_t  ASQ;  /* Additional Sense Qualifier */
+  uint8_t  max_lun;
+  uint16_t scsi_blk_size;
+  uint32_t scsi_blk_nbr;
+
+  uint32_t scsi_blk_addr;
+  uint32_t scsi_blk_len;
+  uint8_t *block_buffer;
 
 } usbd_msc_cfg;
 
 /*memory OK (after a usbd_msc_memory_verify)*/
 static bool memOK;
 
-static void usbd_msc_reset(void)
-{
-    usbd_msc_cfg.stage = MSC_READ_CBW;
-    usbd_msc_cfg.scsi_blk_addr = 0U;
-    usbd_msc_cfg.scsi_blk_len = 0U;
-    usbd_msc_cfg.max_lun = 0;
-    usbd_msc_cfg.sKey = 0;
-    usbd_msc_cfg.ASC = 0;
-    usbd_msc_cfg.ASQ = 0;
-
-    (void)memset((void *)&usbd_msc_cfg.cbw, 0, sizeof(struct CBW));
-    (void)memset((void *)&usbd_msc_cfg.csw, 0, sizeof(struct CSW));
-
-    usbd_msc_get_cap(0, &usbd_msc_cfg.scsi_blk_nbr, &usbd_msc_cfg.scsi_blk_size);
-
-    if (usbd_msc_cfg.block_buffer) {
-        free(usbd_msc_cfg.block_buffer);
-    }
-    usbd_msc_cfg.block_buffer = malloc(usbd_msc_cfg.scsi_blk_size * sizeof(uint8_t));
-    memset(usbd_msc_cfg.block_buffer, 0, usbd_msc_cfg.scsi_blk_size * sizeof(uint8_t));
+static void usbd_msc_reset(void) {
+  usbd_msc_cfg.stage         = MSC_READ_CBW;
+  usbd_msc_cfg.scsi_blk_addr = 0U;
+  usbd_msc_cfg.scsi_blk_len  = 0U;
+  usbd_msc_cfg.max_lun       = 0;
+  usbd_msc_cfg.sKey          = 0;
+  usbd_msc_cfg.ASC           = 0;
+  usbd_msc_cfg.ASQ           = 0;
+
+  (void)memset((void *)&usbd_msc_cfg.cbw, 0, sizeof(struct CBW));
+  (void)memset((void *)&usbd_msc_cfg.csw, 0, sizeof(struct CSW));
+
+  usbd_msc_get_cap(0, &usbd_msc_cfg.scsi_blk_nbr, &usbd_msc_cfg.scsi_blk_size);
+
+  if (usbd_msc_cfg.block_buffer) {
+    free(usbd_msc_cfg.block_buffer);
+  }
+  usbd_msc_cfg.block_buffer = malloc(usbd_msc_cfg.scsi_blk_size * sizeof(uint8_t));
+  memset(usbd_msc_cfg.block_buffer, 0, usbd_msc_cfg.scsi_blk_size * sizeof(uint8_t));
 }
 
 /**
@@ -119,83 +118,78 @@ static void usbd_msc_reset(void)
  *
  * @return  0 on success, negative errno code on fail.
  */
-static int msc_storage_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("MSC Class request: "
-                 "bRequest 0x%02x\r\n",
-                 setup->bRequest);
-
-    switch (setup->bRequest) {
-        case MSC_REQUEST_RESET:
-            USBD_LOG_DBG("MSC_REQUEST_RESET\r\n");
-
-            if (setup->wLength) {
-                USBD_LOG_WRN("Invalid length\r\n");
-                return -1;
-            }
-
-            usbd_msc_reset();
-            break;
-
-        case MSC_REQUEST_GET_MAX_LUN:
-            USBD_LOG_DBG("MSC_REQUEST_GET_MAX_LUN\r\n");
-
-            if (setup->wLength != 1) {
-                USBD_LOG_WRN("Invalid length\r\n");
-                return -1;
-            }
-
-            *data = (uint8_t *)(&usbd_msc_cfg.max_lun);
-            *len = 1;
-            break;
-
-        default:
-            USBD_LOG_WRN("Unhandled MSC Class bRequest 0x%02x\r\n", setup->bRequest);
-            return -1;
+static int msc_storage_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) {
+  USBD_LOG_DBG("MSC Class request: "
+               "bRequest 0x%02x\r\n",
+               setup->bRequest);
+
+  switch (setup->bRequest) {
+  case MSC_REQUEST_RESET:
+    USBD_LOG_DBG("MSC_REQUEST_RESET\r\n");
+
+    if (setup->wLength) {
+      USBD_LOG_WRN("Invalid length\r\n");
+      return -1;
     }
 
-    return 0;
-}
+    usbd_msc_reset();
+    break;
 
-static void usbd_msc_bot_abort(void)
-{
-    if ((usbd_msc_cfg.cbw.bmFlags == 0) && (usbd_msc_cfg.cbw.dDataLength != 0)) {
-        usbd_ep_set_stall(mass_ep_data[MSD_OUT_EP_IDX].ep_addr);
+  case MSC_REQUEST_GET_MAX_LUN:
+    USBD_LOG_DBG("MSC_REQUEST_GET_MAX_LUN\r\n");
+
+    if (setup->wLength != 1) {
+      USBD_LOG_WRN("Invalid length\r\n");
+      return -1;
     }
-    usbd_ep_set_stall(mass_ep_data[MSD_IN_EP_IDX].ep_addr);
+
+    *data = (uint8_t *)(&usbd_msc_cfg.max_lun);
+    *len  = 1;
+    break;
+
+  default:
+    USBD_LOG_WRN("Unhandled MSC Class bRequest 0x%02x\r\n", setup->bRequest);
+    return -1;
+  }
+
+  return 0;
 }
 
-static void sendCSW(uint8_t CSW_Status)
-{
-    usbd_msc_cfg.csw.dSignature = MSC_CSW_Signature;
-    usbd_msc_cfg.csw.bStatus = CSW_Status;
+static void usbd_msc_bot_abort(void) {
+  if ((usbd_msc_cfg.cbw.bmFlags == 0) && (usbd_msc_cfg.cbw.dDataLength != 0)) {
+    usbd_ep_set_stall(mass_ep_data[MSD_OUT_EP_IDX].ep_addr);
+  }
+  usbd_ep_set_stall(mass_ep_data[MSD_IN_EP_IDX].ep_addr);
+}
 
-    /* updating the State Machine , so that we wait CSW when this
-	 * transfer is complete, ie when we get a bulk in callback
-	 */
-    usbd_msc_cfg.stage = MSC_WAIT_CSW;
+static void sendCSW(uint8_t CSW_Status) {
+  usbd_msc_cfg.csw.dSignature = MSC_CSW_Signature;
+  usbd_msc_cfg.csw.bStatus    = CSW_Status;
 
-    if (usbd_ep_write(mass_ep_data[MSD_IN_EP_IDX].ep_addr, (uint8_t *)&usbd_msc_cfg.csw,
-                      sizeof(struct CSW), NULL) != 0) {
-        USBD_LOG_ERR("usb write failure\r\n");
-    }
+  /* updating the State Machine , so that we wait CSW when this
+   * transfer is complete, ie when we get a bulk in callback
+   */
+  usbd_msc_cfg.stage = MSC_WAIT_CSW;
+
+  if (usbd_ep_write(mass_ep_data[MSD_IN_EP_IDX].ep_addr, (uint8_t *)&usbd_msc_cfg.csw, sizeof(struct CSW), NULL) != 0) {
+    USBD_LOG_ERR("usb write failure\r\n");
+  }
 }
 
-static void sendLastData(uint8_t *buffer, uint8_t size)
-{
-    size = MIN(size, usbd_msc_cfg.cbw.dDataLength);
+static void sendLastData(uint8_t *buffer, uint8_t size) {
+  size = MIN(size, usbd_msc_cfg.cbw.dDataLength);
 
-    /* updating the State Machine , so that we send CSW when this
-	 * transfer is complete, ie when we get a bulk in callback
-	 */
-    usbd_msc_cfg.stage = MSC_SEND_CSW;
+  /* updating the State Machine , so that we send CSW when this
+   * transfer is complete, ie when we get a bulk in callback
+   */
+  usbd_msc_cfg.stage = MSC_SEND_CSW;
 
-    if (usbd_ep_write(mass_ep_data[MSD_IN_EP_IDX].ep_addr, buffer, size, NULL) != 0) {
-        USBD_LOG_ERR("USB write failed\r\n");
-    }
+  if (usbd_ep_write(mass_ep_data[MSD_IN_EP_IDX].ep_addr, buffer, size, NULL) != 0) {
+    USBD_LOG_ERR("USB write failed\r\n");
+  }
 
-    usbd_msc_cfg.csw.dDataResidue -= size;
-    usbd_msc_cfg.csw.bStatus = CSW_STATUS_CMD_PASSED;
+  usbd_msc_cfg.csw.dDataResidue -= size;
+  usbd_msc_cfg.csw.bStatus = CSW_STATUS_CMD_PASSED;
 }
 
 /**
@@ -224,235 +218,212 @@ static bool SCSI_verify10(uint8_t **data, uint32_t *len);
 * @retval none
 
 */
-static void SCSI_SenseCode(uint8_t sKey, uint8_t ASC)
-{
-    usbd_msc_cfg.sKey = sKey;
-    usbd_msc_cfg.ASC = ASC;
+static void SCSI_SenseCode(uint8_t sKey, uint8_t ASC) {
+  usbd_msc_cfg.sKey = sKey;
+  usbd_msc_cfg.ASC  = ASC;
 }
 
-static bool SCSI_processRead(void)
-{
-    uint32_t transfer_len;
+static bool SCSI_processRead(void) {
+  uint32_t transfer_len;
 
-    USBD_LOG_DBG("read addr:%d\r\n", usbd_msc_cfg.scsi_blk_addr);
+  USBD_LOG_DBG("read addr:%d\r\n", usbd_msc_cfg.scsi_blk_addr);
 
-    transfer_len = MIN(usbd_msc_cfg.scsi_blk_len, MASS_STORAGE_BULK_EP_MPS);
+  transfer_len = MIN(usbd_msc_cfg.scsi_blk_len, MASS_STORAGE_BULK_EP_MPS);
 
-    /* we read an entire block */
-    if (!(usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size)) {
-        if (usbd_msc_sector_read((usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size), usbd_msc_cfg.block_buffer, usbd_msc_cfg.scsi_blk_size) != 0) {
-            SCSI_SenseCode(SCSI_SENSE_HARDWARE_ERROR, SCSI_ASC_UNRECOVERED_READ_ERROR);
-            return false;
-        }
+  /* we read an entire block */
+  if (!(usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size)) {
+    if (usbd_msc_sector_read((usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size), usbd_msc_cfg.block_buffer, usbd_msc_cfg.scsi_blk_size) != 0) {
+      SCSI_SenseCode(SCSI_SENSE_HARDWARE_ERROR, SCSI_ASC_UNRECOVERED_READ_ERROR);
+      return false;
     }
+  }
 
-    usbd_ep_write(mass_ep_data[MSD_IN_EP_IDX].ep_addr,
-                  &usbd_msc_cfg.block_buffer[usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size], transfer_len, NULL);
+  usbd_ep_write(mass_ep_data[MSD_IN_EP_IDX].ep_addr, &usbd_msc_cfg.block_buffer[usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size], transfer_len, NULL);
 
-    usbd_msc_cfg.scsi_blk_addr += transfer_len;
-    usbd_msc_cfg.scsi_blk_len -= transfer_len;
-    usbd_msc_cfg.csw.dDataResidue -= transfer_len;
+  usbd_msc_cfg.scsi_blk_addr += transfer_len;
+  usbd_msc_cfg.scsi_blk_len -= transfer_len;
+  usbd_msc_cfg.csw.dDataResidue -= transfer_len;
 
-    if (usbd_msc_cfg.scsi_blk_len == 0) {
-        usbd_msc_cfg.stage = MSC_SEND_CSW;
-    }
+  if (usbd_msc_cfg.scsi_blk_len == 0) {
+    usbd_msc_cfg.stage = MSC_SEND_CSW;
+  }
 
-    return true;
+  return true;
 }
 
-static bool SCSI_processWrite(uint8_t *buf, uint16_t len)
-{
-    USBD_LOG_DBG("write addr:%d\r\n", usbd_msc_cfg.scsi_blk_addr);
+static bool SCSI_processWrite(uint8_t *buf, uint16_t len) {
+  USBD_LOG_DBG("write addr:%d\r\n", usbd_msc_cfg.scsi_blk_addr);
 
-    /* we fill an array in RAM of 1 block before writing it in memory */
-    for (int i = 0; i < len; i++) {
-        usbd_msc_cfg.block_buffer[usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size + i] = buf[i];
-    }
+  /* we fill an array in RAM of 1 block before writing it in memory */
+  for (int i = 0; i < len; i++) {
+    usbd_msc_cfg.block_buffer[usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size + i] = buf[i];
+  }
 
-    /* if the array is filled, write it in memory */
-    if ((usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size) + len >= usbd_msc_cfg.scsi_blk_size) {
-        if (usbd_msc_sector_write((usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size), usbd_msc_cfg.block_buffer, usbd_msc_cfg.scsi_blk_size) != 0) {
-            SCSI_SenseCode(SCSI_SENSE_HARDWARE_ERROR, SCSI_ASC_WRITE_FAULT);
-            return false;
-        }
+  /* if the array is filled, write it in memory */
+  if ((usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size) + len >= usbd_msc_cfg.scsi_blk_size) {
+    if (usbd_msc_sector_write((usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size), usbd_msc_cfg.block_buffer, usbd_msc_cfg.scsi_blk_size) != 0) {
+      SCSI_SenseCode(SCSI_SENSE_HARDWARE_ERROR, SCSI_ASC_WRITE_FAULT);
+      return false;
     }
+  }
 
-    usbd_msc_cfg.scsi_blk_addr += len;
-    usbd_msc_cfg.scsi_blk_len -= len;
-    usbd_msc_cfg.csw.dDataResidue -= len;
+  usbd_msc_cfg.scsi_blk_addr += len;
+  usbd_msc_cfg.scsi_blk_len -= len;
+  usbd_msc_cfg.csw.dDataResidue -= len;
 
-    if (usbd_msc_cfg.scsi_blk_len == 0) {
-        sendCSW(CSW_STATUS_CMD_PASSED);
-    }
+  if (usbd_msc_cfg.scsi_blk_len == 0) {
+    sendCSW(CSW_STATUS_CMD_PASSED);
+  }
 
-    return true;
+  return true;
 }
 
-static bool SCSI_processVerify(uint8_t *buf, uint16_t len)
-{
-    USBD_LOG_DBG("verify addr:%d\r\n", usbd_msc_cfg.scsi_blk_addr);
+static bool SCSI_processVerify(uint8_t *buf, uint16_t len) {
+  USBD_LOG_DBG("verify addr:%d\r\n", usbd_msc_cfg.scsi_blk_addr);
 
-    /* we read an entire block */
-    if (!(usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size)) {
-        if (usbd_msc_sector_read((usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size), usbd_msc_cfg.block_buffer, usbd_msc_cfg.scsi_blk_size) != 0) {
-            SCSI_SenseCode(SCSI_SENSE_HARDWARE_ERROR, SCSI_ASC_UNRECOVERED_READ_ERROR);
-            return false;
-        }
+  /* we read an entire block */
+  if (!(usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size)) {
+    if (usbd_msc_sector_read((usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size), usbd_msc_cfg.block_buffer, usbd_msc_cfg.scsi_blk_size) != 0) {
+      SCSI_SenseCode(SCSI_SENSE_HARDWARE_ERROR, SCSI_ASC_UNRECOVERED_READ_ERROR);
+      return false;
     }
+  }
 
-    /* info are in RAM -> no need to re-read memory */
-    for (uint16_t i = 0U; i < len; i++) {
-        if (usbd_msc_cfg.block_buffer[usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size + i] != buf[i]) {
-            USBD_LOG_DBG("Mismatch sector %d offset %d",
-                         usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size, i);
-            memOK = false;
-            break;
-        }
+  /* info are in RAM -> no need to re-read memory */
+  for (uint16_t i = 0U; i < len; i++) {
+    if (usbd_msc_cfg.block_buffer[usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size + i] != buf[i]) {
+      USBD_LOG_DBG("Mismatch sector %d offset %d", usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size, i);
+      memOK = false;
+      break;
     }
+  }
 
-    usbd_msc_cfg.scsi_blk_addr += len;
-    usbd_msc_cfg.scsi_blk_len -= len;
-    usbd_msc_cfg.csw.dDataResidue -= len;
+  usbd_msc_cfg.scsi_blk_addr += len;
+  usbd_msc_cfg.scsi_blk_len -= len;
+  usbd_msc_cfg.csw.dDataResidue -= len;
 
-    if (usbd_msc_cfg.scsi_blk_len == 0) {
-        sendCSW(CSW_STATUS_CMD_PASSED);
-    }
+  if (usbd_msc_cfg.scsi_blk_len == 0) {
+    sendCSW(CSW_STATUS_CMD_PASSED);
+  }
 
-    return true;
+  return true;
 }
 
-static bool SCSI_CBWDecode(uint8_t *buf, uint16_t size)
-{
-    uint8_t send_buffer[64];
-    uint8_t *buf2send = send_buffer;
-    uint32_t len2send = 0;
-    bool ret = false;
-
-    if (size != sizeof(struct CBW)) {
-        USBD_LOG_ERR("size != sizeof(cbw)\r\n");
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-
-    memcpy((uint8_t *)&usbd_msc_cfg.cbw, buf, size);
-
-    usbd_msc_cfg.csw.dTag = usbd_msc_cfg.cbw.dTag;
-    usbd_msc_cfg.csw.dDataResidue = usbd_msc_cfg.cbw.dDataLength;
-
-    if ((usbd_msc_cfg.cbw.bLUN > 1) || (usbd_msc_cfg.cbw.dSignature != MSC_CBW_Signature) || (usbd_msc_cfg.cbw.bCBLength < 1) || (usbd_msc_cfg.cbw.bCBLength > 16)) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    } else {
-        switch (usbd_msc_cfg.cbw.CB[0]) {
-            case SCSI_TEST_UNIT_READY:
-                ret = SCSI_testUnitReady(&buf2send, &len2send);
-                break;
-            case SCSI_REQUEST_SENSE:
-                ret = SCSI_requestSense(&buf2send, &len2send);
-                break;
-            case SCSI_INQUIRY:
-                ret = SCSI_inquiry(&buf2send, &len2send);
-                break;
-            case SCSI_START_STOP_UNIT:
-                ret = SCSI_startStopUnit(&buf2send, &len2send);
-                break;
-            case SCSI_PREVENT_ALLOW_MEDIA_REMOVAL:
-                ret = SCSI_preventAllowMediaRemoval(&buf2send, &len2send);
-                break;
-            case SCSI_MODE_SENSE6:
-                ret = SCSI_modeSense6(&buf2send, &len2send);
-                break;
-            case SCSI_MODE_SENSE10:
-                ret = SCSI_modeSense10(&buf2send, &len2send);
-                break;
-            case SCSI_READ_FORMAT_CAPACITIES:
-                ret = SCSI_readFormatCapacity(&buf2send, &len2send);
-                break;
-            case SCSI_READ_CAPACITY10:
-                ret = SCSI_readCapacity10(&buf2send, &len2send);
-                break;
-            case SCSI_READ10:
-                ret = SCSI_read10(NULL, 0);
-                break;
-            case SCSI_READ12:
-                ret = SCSI_read12(NULL, 0);
-                break;
-            case SCSI_WRITE10:
-                ret = SCSI_write10(NULL, 0);
-                break;
-            case SCSI_WRITE12:
-                ret = SCSI_write12(NULL, 0);
-                break;
-            case SCSI_VERIFY10:
-                ret = SCSI_verify10(NULL, 0);
-                break;
-
-            default:
-                SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-                USBD_LOG_WRN("unsupported cmd:0x%02x\r\n", usbd_msc_cfg.cbw.CB[0]);
-                ret = false;
-                break;
-        }
-    }
-    if (ret) {
-        if (usbd_msc_cfg.stage == MSC_READ_CBW) {
-            if (len2send) {
-                sendLastData(buf2send, len2send);
-            } else {
-                sendCSW(CSW_STATUS_CMD_PASSED);
-            }
-        }
+static bool SCSI_CBWDecode(uint8_t *buf, uint16_t size) {
+  uint8_t  send_buffer[64];
+  uint8_t *buf2send = send_buffer;
+  uint32_t len2send = 0;
+  bool     ret      = false;
+
+  if (size != sizeof(struct CBW)) {
+    USBD_LOG_ERR("size != sizeof(cbw)\r\n");
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  }
+
+  memcpy((uint8_t *)&usbd_msc_cfg.cbw, buf, size);
+
+  usbd_msc_cfg.csw.dTag         = usbd_msc_cfg.cbw.dTag;
+  usbd_msc_cfg.csw.dDataResidue = usbd_msc_cfg.cbw.dDataLength;
+
+  if ((usbd_msc_cfg.cbw.bLUN > 1) || (usbd_msc_cfg.cbw.dSignature != MSC_CBW_Signature) || (usbd_msc_cfg.cbw.bCBLength < 1) || (usbd_msc_cfg.cbw.bCBLength > 16)) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  } else {
+    switch (usbd_msc_cfg.cbw.CB[0]) {
+    case SCSI_TEST_UNIT_READY:
+      ret = SCSI_testUnitReady(&buf2send, &len2send);
+      break;
+    case SCSI_REQUEST_SENSE:
+      ret = SCSI_requestSense(&buf2send, &len2send);
+      break;
+    case SCSI_INQUIRY:
+      ret = SCSI_inquiry(&buf2send, &len2send);
+      break;
+    case SCSI_START_STOP_UNIT:
+      ret = SCSI_startStopUnit(&buf2send, &len2send);
+      break;
+    case SCSI_PREVENT_ALLOW_MEDIA_REMOVAL:
+      ret = SCSI_preventAllowMediaRemoval(&buf2send, &len2send);
+      break;
+    case SCSI_MODE_SENSE6:
+      ret = SCSI_modeSense6(&buf2send, &len2send);
+      break;
+    case SCSI_MODE_SENSE10:
+      ret = SCSI_modeSense10(&buf2send, &len2send);
+      break;
+    case SCSI_READ_FORMAT_CAPACITIES:
+      ret = SCSI_readFormatCapacity(&buf2send, &len2send);
+      break;
+    case SCSI_READ_CAPACITY10:
+      ret = SCSI_readCapacity10(&buf2send, &len2send);
+      break;
+    case SCSI_READ10:
+      ret = SCSI_read10(NULL, 0);
+      break;
+    case SCSI_READ12:
+      ret = SCSI_read12(NULL, 0);
+      break;
+    case SCSI_WRITE10:
+      ret = SCSI_write10(NULL, 0);
+      break;
+    case SCSI_WRITE12:
+      ret = SCSI_write12(NULL, 0);
+      break;
+    case SCSI_VERIFY10:
+      ret = SCSI_verify10(NULL, 0);
+      break;
+
+    default:
+      SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+      USBD_LOG_WRN("unsupported cmd:0x%02x\r\n", usbd_msc_cfg.cbw.CB[0]);
+      ret = false;
+      break;
+    }
+  }
+  if (ret) {
+    if (usbd_msc_cfg.stage == MSC_READ_CBW) {
+      if (len2send) {
+        sendLastData(buf2send, len2send);
+      } else {
+        sendCSW(CSW_STATUS_CMD_PASSED);
+      }
     }
-    return ret;
+  }
+  return ret;
 }
 
-static bool SCSI_testUnitReady(uint8_t **data, uint32_t *len)
-{
-    if (usbd_msc_cfg.cbw.dDataLength != 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-    *data = NULL;
-    *len = 0;
-    return true;
+static bool SCSI_testUnitReady(uint8_t **data, uint32_t *len) {
+  if (usbd_msc_cfg.cbw.dDataLength != 0U) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  }
+  *data = NULL;
+  *len  = 0;
+  return true;
 }
 
-static bool SCSI_requestSense(uint8_t **data, uint32_t *len)
-{
-    uint8_t data_len = REQUEST_SENSE_DATA_LEN;
-    if (usbd_msc_cfg.cbw.dDataLength == 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-
-    if (usbd_msc_cfg.cbw.CB[4] < REQUEST_SENSE_DATA_LEN) {
-        data_len = usbd_msc_cfg.cbw.CB[4];
-    }
-
-    uint8_t request_sense[REQUEST_SENSE_DATA_LEN] = {
-        0x70,
-        0x00,
-        0x00, /* Sense Key */
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        REQUEST_SENSE_DATA_LEN - 8,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00, /* Additional Sense Code */
-        0x00, /* Additional Sense Request */
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-    };
-
-    request_sense[2] = usbd_msc_cfg.sKey;
-    request_sense[12] = usbd_msc_cfg.ASC;
-    request_sense[13] = usbd_msc_cfg.ASQ;
+static bool SCSI_requestSense(uint8_t **data, uint32_t *len) {
+  uint8_t data_len = REQUEST_SENSE_DATA_LEN;
+  if (usbd_msc_cfg.cbw.dDataLength == 0U) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  }
+
+  if (usbd_msc_cfg.cbw.CB[4] < REQUEST_SENSE_DATA_LEN) {
+    data_len = usbd_msc_cfg.cbw.CB[4];
+  }
+
+  uint8_t request_sense[REQUEST_SENSE_DATA_LEN] = {
+      0x70, 0x00, 0x00,                                                                 /* Sense Key */
+      0x00, 0x00, 0x00, 0x00, REQUEST_SENSE_DATA_LEN - 8, 0x00, 0x00, 0x00, 0x00, 0x00, /* Additional Sense Code */
+      0x00,                                                                             /* Additional Sense Request */
+      0x00, 0x00, 0x00, 0x00,
+  };
+
+  request_sense[2]  = usbd_msc_cfg.sKey;
+  request_sense[12] = usbd_msc_cfg.ASC;
+  request_sense[13] = usbd_msc_cfg.ASQ;
 #if 0
     request_sense[ 2] = 0x06;           /* UNIT ATTENTION */
     request_sense[12] = 0x28;           /* Additional Sense Code: Not ready to ready transition */
@@ -474,455 +445,392 @@ static bool SCSI_requestSense(uint8_t **data, uint32_t *len)
     request_sense[13] = 0x00;         /* Additional Sense Code Qualifier */
 #endif
 
-    memcpy(*data, (uint8_t *)&request_sense, data_len);
-    *len = data_len;
-    return true;
+  memcpy(*data, (uint8_t *)&request_sense, data_len);
+  *len = data_len;
+  return true;
 }
 
-static bool SCSI_inquiry(uint8_t **data, uint32_t *len)
-{
-    uint8_t data_len = STANDARD_INQUIRY_DATA_LEN;
-
-    uint8_t inquiry00[6] = {
-        0x00,
-        0x00,
-        0x00,
-        (0x06 - 4U),
-        0x00,
-        0x80
-    };
-
-    /* USB Mass storage VPD Page 0x80 Inquiry Data for Unit Serial Number */
-    uint8_t inquiry80[8] = {
-        0x00,
-        0x80,
-        0x00,
-        0x08,
-        0x20, /* Put Product Serial number */
-        0x20,
-        0x20,
-        0x20
-    };
-
-    uint8_t inquiry[STANDARD_INQUIRY_DATA_LEN] = {
-        /* 36 */
-
-        /* LUN 0 */
-        0x00,
-        0x80,
-        0x02,
-        0x02,
-        (STANDARD_INQUIRY_DATA_LEN - 5),
-        0x00,
-        0x00,
-        0x00,
-        'B', 'o', 'u', 'f', 'f', 'a', 'l', 'o', /* Manufacturer : 8 bytes */
-        'P', 'r', 'o', 'd', 'u', 'c', 't', ' ', /* Product      : 16 Bytes */
-        ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
-        '0', '.', '0', '1' /* Version      : 4 Bytes */
-    };
-
-    if (usbd_msc_cfg.cbw.dDataLength == 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-
-    if ((usbd_msc_cfg.cbw.CB[1] & 0x01U) != 0U) { /* Evpd is set */
-        if (usbd_msc_cfg.cbw.CB[2] == 0U) {       /* Request for Supported Vital Product Data Pages*/
-            data_len = 0x06;
-            memcpy(*data, (uint8_t *)&inquiry00, data_len);
-        } else if (usbd_msc_cfg.cbw.CB[2] == 0x80U) { /* Request for VPD page 0x80 Unit Serial Number */
-            data_len = 0x08;
-            memcpy(*data, (uint8_t *)&inquiry80, data_len);
-        } else { /* Request Not supported */
-            SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_FIELED_IN_COMMAND);
-            return false;
-        }
-    } else {
-        if (usbd_msc_cfg.cbw.CB[4] < STANDARD_INQUIRY_DATA_LEN) {
-            data_len = usbd_msc_cfg.cbw.CB[4];
-        }
-        memcpy(*data, (uint8_t *)&inquiry, data_len);
-    }
-
-    *len = data_len;
-    return true;
+static bool SCSI_inquiry(uint8_t **data, uint32_t *len) {
+  uint8_t data_len = STANDARD_INQUIRY_DATA_LEN;
+
+  uint8_t inquiry00[6] = {0x00, 0x00, 0x00, (0x06 - 4U), 0x00, 0x80};
+
+  /* USB Mass storage VPD Page 0x80 Inquiry Data for Unit Serial Number */
+  uint8_t inquiry80[8] = {0x00, 0x80, 0x00, 0x08, 0x20, /* Put Product Serial number */
+                          0x20, 0x20, 0x20};
+
+  uint8_t inquiry[STANDARD_INQUIRY_DATA_LEN] = {
+      /* 36 */
+
+      /* LUN 0 */
+      0x00, 0x80, 0x02, 0x02, (STANDARD_INQUIRY_DATA_LEN - 5),
+      0x00, 0x00, 0x00, 'B',  'o',
+      'u',  'f',  'f',  'a',  'l',
+      'o', /* Manufacturer : 8 bytes */
+      'P',  'r',  'o',  'd',  'u',
+      'c',  't',  ' ', /* Product      : 16 Bytes */
+      ' ',  ' ',  ' ',  ' ',  ' ',
+      ' ',  ' ',  ' ',  '0',  '.',
+      '0',  '1' /* Version      : 4 Bytes */
+  };
+
+  if (usbd_msc_cfg.cbw.dDataLength == 0U) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  }
+
+  if ((usbd_msc_cfg.cbw.CB[1] & 0x01U) != 0U) { /* Evpd is set */
+    if (usbd_msc_cfg.cbw.CB[2] == 0U) {         /* Request for Supported Vital Product Data Pages*/
+      data_len = 0x06;
+      memcpy(*data, (uint8_t *)&inquiry00, data_len);
+    } else if (usbd_msc_cfg.cbw.CB[2] == 0x80U) { /* Request for VPD page 0x80 Unit Serial Number */
+      data_len = 0x08;
+      memcpy(*data, (uint8_t *)&inquiry80, data_len);
+    } else { /* Request Not supported */
+      SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_FIELED_IN_COMMAND);
+      return false;
+    }
+  } else {
+    if (usbd_msc_cfg.cbw.CB[4] < STANDARD_INQUIRY_DATA_LEN) {
+      data_len = usbd_msc_cfg.cbw.CB[4];
+    }
+    memcpy(*data, (uint8_t *)&inquiry, data_len);
+  }
+
+  *len = data_len;
+  return true;
 }
 
-static bool SCSI_startStopUnit(uint8_t **data, uint32_t *len)
-{
-    if (usbd_msc_cfg.cbw.dDataLength != 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-
-    if ((usbd_msc_cfg.cbw.CB[4] & 0x3U) == 0x1U) /* START=1 */
-    {
-        //SCSI_MEDIUM_UNLOCKED;
-    } else if ((usbd_msc_cfg.cbw.CB[4] & 0x3U) == 0x2U) /* START=0 and LOEJ Load Eject=1 */
-    {
-        //SCSI_MEDIUM_EJECTED;
-    } else if ((usbd_msc_cfg.cbw.CB[4] & 0x3U) == 0x3U) /* START=1 and LOEJ Load Eject=1 */
-    {
-        //SCSI_MEDIUM_UNLOCKED;
-    } else {
-    }
-
-    *data = NULL;
-    *len = 0;
-    return true;
+static bool SCSI_startStopUnit(uint8_t **data, uint32_t *len) {
+  if (usbd_msc_cfg.cbw.dDataLength != 0U) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  }
+
+  if ((usbd_msc_cfg.cbw.CB[4] & 0x3U) == 0x1U) /* START=1 */
+  {
+    // SCSI_MEDIUM_UNLOCKED;
+  } else if ((usbd_msc_cfg.cbw.CB[4] & 0x3U) == 0x2U) /* START=0 and LOEJ Load Eject=1 */
+  {
+    // SCSI_MEDIUM_EJECTED;
+  } else if ((usbd_msc_cfg.cbw.CB[4] & 0x3U) == 0x3U) /* START=1 and LOEJ Load Eject=1 */
+  {
+    // SCSI_MEDIUM_UNLOCKED;
+  } else {
+  }
+
+  *data = NULL;
+  *len  = 0;
+  return true;
 }
 
-static bool SCSI_preventAllowMediaRemoval(uint8_t **data, uint32_t *len)
-{
-    if (usbd_msc_cfg.cbw.dDataLength != 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-    if (usbd_msc_cfg.cbw.CB[4] == 0U) {
-        //SCSI_MEDIUM_UNLOCKED;
-    } else {
-        //SCSI_MEDIUM_LOCKED;
-    }
-    *data = NULL;
-    *len = 0;
-    return true;
+static bool SCSI_preventAllowMediaRemoval(uint8_t **data, uint32_t *len) {
+  if (usbd_msc_cfg.cbw.dDataLength != 0U) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  }
+  if (usbd_msc_cfg.cbw.CB[4] == 0U) {
+    // SCSI_MEDIUM_UNLOCKED;
+  } else {
+    // SCSI_MEDIUM_LOCKED;
+  }
+  *data = NULL;
+  *len  = 0;
+  return true;
 }
 
-static bool SCSI_modeSense6(uint8_t **data, uint32_t *len)
-{
-    uint8_t data_len = 4;
-    if (usbd_msc_cfg.cbw.dDataLength == 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-    if (usbd_msc_cfg.cbw.CB[4] < MODE_SENSE6_DATA_LEN) {
-        data_len = usbd_msc_cfg.cbw.CB[4];
-    }
-
-    uint8_t sense6[] = { 0x03, 0x00, 0x00, 0x00 };
-
-    memcpy(*data, (uint8_t *)&sense6, data_len);
-    *len = data_len;
-    return true;
+static bool SCSI_modeSense6(uint8_t **data, uint32_t *len) {
+  uint8_t data_len = 4;
+  if (usbd_msc_cfg.cbw.dDataLength == 0U) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  }
+  if (usbd_msc_cfg.cbw.CB[4] < MODE_SENSE6_DATA_LEN) {
+    data_len = usbd_msc_cfg.cbw.CB[4];
+  }
+
+  uint8_t sense6[] = {0x03, 0x00, 0x00, 0x00};
+
+  memcpy(*data, (uint8_t *)&sense6, data_len);
+  *len = data_len;
+  return true;
 }
 
-static bool SCSI_modeSense10(uint8_t **data, uint32_t *len)
-{
-    uint8_t data_len = MODE_SENSE10_DATA_LEN;
-    if (usbd_msc_cfg.cbw.dDataLength == 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-    if (usbd_msc_cfg.cbw.CB[8] < MODE_SENSE10_DATA_LEN) {
-        data_len = usbd_msc_cfg.cbw.CB[8];
-    }
-
-    uint8_t sense10[MODE_SENSE10_DATA_LEN] = {
-        0x00,
-        0x26,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x08,
-        0x12,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00
-    };
-    memcpy(*data, (uint8_t *)&sense10, data_len);
-    *len = data_len;
-    return true;
+static bool SCSI_modeSense10(uint8_t **data, uint32_t *len) {
+  uint8_t data_len = MODE_SENSE10_DATA_LEN;
+  if (usbd_msc_cfg.cbw.dDataLength == 0U) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  }
+  if (usbd_msc_cfg.cbw.CB[8] < MODE_SENSE10_DATA_LEN) {
+    data_len = usbd_msc_cfg.cbw.CB[8];
+  }
+
+  uint8_t sense10[MODE_SENSE10_DATA_LEN]
+      = {0x00, 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+  memcpy(*data, (uint8_t *)&sense10, data_len);
+  *len = data_len;
+  return true;
 }
 
-static bool SCSI_readFormatCapacity(uint8_t **data, uint32_t *len)
-{
-    if (usbd_msc_cfg.cbw.dDataLength == 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-    uint8_t capacity[READ_FORMAT_CAPACITY_DATA_LEN] = {
-        0x00,
-        0x00,
-        0x00,
-        0x08, /* Capacity List Length */
-        (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 24) & 0xff),
-        (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 16) & 0xff),
-        (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 8) & 0xff),
-        (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 0) & 0xff),
-
-        0x02, /* Descriptor Code: Formatted Media */
-        0x00,
-        (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 8) & 0xff),
-        (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 0) & 0xff),
-    };
-
-    memcpy(*data, (uint8_t *)&capacity, READ_FORMAT_CAPACITY_DATA_LEN);
-    *len = READ_FORMAT_CAPACITY_DATA_LEN;
-    return true;
+static bool SCSI_readFormatCapacity(uint8_t **data, uint32_t *len) {
+  if (usbd_msc_cfg.cbw.dDataLength == 0U) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  }
+  uint8_t capacity[READ_FORMAT_CAPACITY_DATA_LEN] = {
+      0x00,
+      0x00,
+      0x00,
+      0x08, /* Capacity List Length */
+      (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 24) & 0xff),
+      (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 16) & 0xff),
+      (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 8) & 0xff),
+      (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 0) & 0xff),
+
+      0x02, /* Descriptor Code: Formatted Media */
+      0x00,
+      (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 8) & 0xff),
+      (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 0) & 0xff),
+  };
+
+  memcpy(*data, (uint8_t *)&capacity, READ_FORMAT_CAPACITY_DATA_LEN);
+  *len = READ_FORMAT_CAPACITY_DATA_LEN;
+  return true;
 }
 
-static bool SCSI_readCapacity10(uint8_t **data, uint32_t *len)
-{
-    if (usbd_msc_cfg.cbw.dDataLength == 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
+static bool SCSI_readCapacity10(uint8_t **data, uint32_t *len) {
+  if (usbd_msc_cfg.cbw.dDataLength == 0U) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  }
 
-    uint8_t capacity[READ_CAPACITY10_DATA_LEN] = {
-        (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 24) & 0xff),
-        (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 16) & 0xff),
-        (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 8) & 0xff),
-        (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 0) & 0xff),
+  uint8_t capacity[READ_CAPACITY10_DATA_LEN] = {
+      (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 24) & 0xff), (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 16) & 0xff),
+      (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 8) & 0xff),  (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 0) & 0xff),
 
-        (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 24) & 0xff),
-        (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 16) & 0xff),
-        (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 8) & 0xff),
-        (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 0) & 0xff),
-    };
+      (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 24) & 0xff),      (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 16) & 0xff),
+      (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 8) & 0xff),       (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 0) & 0xff),
+  };
 
-    memcpy(*data, (uint8_t *)&capacity, READ_CAPACITY10_DATA_LEN);
-    *len = READ_CAPACITY10_DATA_LEN;
-    return true;
+  memcpy(*data, (uint8_t *)&capacity, READ_CAPACITY10_DATA_LEN);
+  *len = READ_CAPACITY10_DATA_LEN;
+  return true;
 }
 
-static bool SCSI_read10(uint8_t **data, uint32_t *len)
-{
-    /* Logical Block Address of First Block */
-    uint32_t lba = 0;
-    uint32_t blk_num = 0;
-    if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x80U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-
-    lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]);
-    USBD_LOG_DBG("lba: 0x%x\r\n", lba);
-
-    usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size;
-
-    /* Number of Blocks to transfer */
-    blk_num = GET_BE16(&usbd_msc_cfg.cbw.CB[7]);
-
-    USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num);
-    usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size;
-
-    if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) {
-        USBD_LOG_ERR("LBA out of range\r\n");
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ADDRESS_OUT_OF_RANGE);
-        return false;
-    }
-
-    if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) {
-        return false;
-    }
-    usbd_msc_cfg.stage = MSC_DATA_IN;
-    return SCSI_processRead();
+static bool SCSI_read10(uint8_t **data, uint32_t *len) {
+  /* Logical Block Address of First Block */
+  uint32_t lba     = 0;
+  uint32_t blk_num = 0;
+  if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x80U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  }
+
+  lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]);
+  USBD_LOG_DBG("lba: 0x%x\r\n", lba);
+
+  usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size;
+
+  /* Number of Blocks to transfer */
+  blk_num = GET_BE16(&usbd_msc_cfg.cbw.CB[7]);
+
+  USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num);
+  usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size;
+
+  if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) {
+    USBD_LOG_ERR("LBA out of range\r\n");
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ADDRESS_OUT_OF_RANGE);
+    return false;
+  }
+
+  if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) {
+    return false;
+  }
+  usbd_msc_cfg.stage = MSC_DATA_IN;
+  return SCSI_processRead();
 }
 
-static bool SCSI_read12(uint8_t **data, uint32_t *len)
-{
-    /* Logical Block Address of First Block */
-    uint32_t lba = 0;
-    uint32_t blk_num = 0;
-    if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x80U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
+static bool SCSI_read12(uint8_t **data, uint32_t *len) {
+  /* Logical Block Address of First Block */
+  uint32_t lba     = 0;
+  uint32_t blk_num = 0;
+  if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x80U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  }
 
-    lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]);
-    USBD_LOG_DBG("lba: 0x%x\r\n", lba);
+  lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]);
+  USBD_LOG_DBG("lba: 0x%x\r\n", lba);
 
-    usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size;
+  usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size;
 
-    /* Number of Blocks to transfer */
-    blk_num = GET_BE32(&usbd_msc_cfg.cbw.CB[6]);
+  /* Number of Blocks to transfer */
+  blk_num = GET_BE32(&usbd_msc_cfg.cbw.CB[6]);
 
-    USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num);
-    usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size;
+  USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num);
+  usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size;
 
-    if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) {
-        USBD_LOG_ERR("LBA out of range\r\n");
-        return false;
-    }
+  if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) {
+    USBD_LOG_ERR("LBA out of range\r\n");
+    return false;
+  }
 
-    if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) {
-        return false;
-    }
-    usbd_msc_cfg.stage = MSC_DATA_IN;
-    return SCSI_processRead();
+  if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) {
+    return false;
+  }
+  usbd_msc_cfg.stage = MSC_DATA_IN;
+  return SCSI_processRead();
 }
 
-static bool SCSI_write10(uint8_t **data, uint32_t *len)
-{
-    /* Logical Block Address of First Block */
-    uint32_t lba = 0;
-    uint32_t blk_num = 0;
-    if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x00U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
+static bool SCSI_write10(uint8_t **data, uint32_t *len) {
+  /* Logical Block Address of First Block */
+  uint32_t lba     = 0;
+  uint32_t blk_num = 0;
+  if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x00U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  }
 
-    lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]);
-    USBD_LOG_DBG("lba: 0x%x\r\n", lba);
+  lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]);
+  USBD_LOG_DBG("lba: 0x%x\r\n", lba);
 
-    usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size;
+  usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size;
 
-    /* Number of Blocks to transfer */
-    blk_num = GET_BE16(&usbd_msc_cfg.cbw.CB[7]);
+  /* Number of Blocks to transfer */
+  blk_num = GET_BE16(&usbd_msc_cfg.cbw.CB[7]);
 
-    USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num);
-    usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size;
+  USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num);
+  usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size;
 
-    if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) {
-        USBD_LOG_ERR("LBA out of range\r\n");
-        return false;
-    }
+  if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) {
+    USBD_LOG_ERR("LBA out of range\r\n");
+    return false;
+  }
 
-    if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) {
-        return false;
-    }
-    usbd_msc_cfg.stage = MSC_DATA_OUT;
-    return true;
+  if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) {
+    return false;
+  }
+  usbd_msc_cfg.stage = MSC_DATA_OUT;
+  return true;
 }
 
-static bool SCSI_write12(uint8_t **data, uint32_t *len)
-{
-    /* Logical Block Address of First Block */
-    uint32_t lba = 0;
-    uint32_t blk_num = 0;
-    if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x00U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
+static bool SCSI_write12(uint8_t **data, uint32_t *len) {
+  /* Logical Block Address of First Block */
+  uint32_t lba     = 0;
+  uint32_t blk_num = 0;
+  if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x00U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  }
 
-    lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]);
-    USBD_LOG_DBG("lba: 0x%x\r\n", lba);
+  lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]);
+  USBD_LOG_DBG("lba: 0x%x\r\n", lba);
 
-    usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size;
+  usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size;
 
-    /* Number of Blocks to transfer */
-    blk_num = GET_BE32(&usbd_msc_cfg.cbw.CB[6]);
+  /* Number of Blocks to transfer */
+  blk_num = GET_BE32(&usbd_msc_cfg.cbw.CB[6]);
 
-    USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num);
-    usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size;
+  USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num);
+  usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size;
 
-    if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) {
-        USBD_LOG_ERR("LBA out of range\r\n");
-        return false;
-    }
+  if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) {
+    USBD_LOG_ERR("LBA out of range\r\n");
+    return false;
+  }
 
-    if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) {
-        return false;
-    }
-    usbd_msc_cfg.stage = MSC_DATA_OUT;
-    return true;
+  if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) {
+    return false;
+  }
+  usbd_msc_cfg.stage = MSC_DATA_OUT;
+  return true;
 }
 
-static bool SCSI_verify10(uint8_t **data, uint32_t *len)
-{
-    /* Logical Block Address of First Block */
-    uint32_t lba = 0;
-    uint32_t blk_num = 0;
+static bool SCSI_verify10(uint8_t **data, uint32_t *len) {
+  /* Logical Block Address of First Block */
+  uint32_t lba     = 0;
+  uint32_t blk_num = 0;
 
-    if ((usbd_msc_cfg.cbw.CB[1] & 0x02U) == 0x00U) {
-        return true;
-    }
+  if ((usbd_msc_cfg.cbw.CB[1] & 0x02U) == 0x00U) {
+    return true;
+  }
 
-    if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x00U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
+  if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x00U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
+    return false;
+  }
 
-    if ((usbd_msc_cfg.cbw.CB[1] & 0x02U) == 0x02U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_FIELED_IN_COMMAND);
-        return false; /* Error, Verify Mode Not supported*/
-    }
+  if ((usbd_msc_cfg.cbw.CB[1] & 0x02U) == 0x02U) {
+    SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_FIELED_IN_COMMAND);
+    return false; /* Error, Verify Mode Not supported*/
+  }
 
-    lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]);
-    USBD_LOG_DBG("lba: 0x%x\r\n", lba);
+  lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]);
+  USBD_LOG_DBG("lba: 0x%x\r\n", lba);
 
-    usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size;
+  usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size;
 
-    /* Number of Blocks to transfer */
-    blk_num = GET_BE16(&usbd_msc_cfg.cbw.CB[7]);
+  /* Number of Blocks to transfer */
+  blk_num = GET_BE16(&usbd_msc_cfg.cbw.CB[7]);
 
-    USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num);
-    usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size;
+  USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num);
+  usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size;
 
-    if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) {
-        USBD_LOG_ERR("LBA out of range\r\n");
-        return false;
-    }
+  if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) {
+    USBD_LOG_ERR("LBA out of range\r\n");
+    return false;
+  }
 
-    if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) {
-        return false;
-    }
+  if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) {
+    return false;
+  }
 
-    memOK = true;
-    usbd_msc_cfg.stage = MSC_DATA_OUT;
-    return true;
+  memOK              = true;
+  usbd_msc_cfg.stage = MSC_DATA_OUT;
+  return true;
 }
 
-static void mass_storage_bulk_out(uint8_t ep)
-{
-    uint8_t out_buf[MASS_STORAGE_BULK_EP_MPS];
-    uint32_t bytes_read;
-
-    usbd_ep_read(ep, out_buf, MASS_STORAGE_BULK_EP_MPS,
-                 &bytes_read);
-
-    switch (usbd_msc_cfg.stage) {
-        case MSC_READ_CBW:
-            if (SCSI_CBWDecode(out_buf, bytes_read) == false) {
-                USBD_LOG_ERR("Command:0x%02x decode err\r\n", usbd_msc_cfg.cbw.CB[0]);
-                usbd_msc_bot_abort();
-                return;
-            }
-            break;
-        /* last command is write10 or write12,and has caculated blk_addr and blk_len,so the device start reading data from host*/
-        case MSC_DATA_OUT:
-            switch (usbd_msc_cfg.cbw.CB[0]) {
-                case SCSI_WRITE10:
-                case SCSI_WRITE12:
-                    if (SCSI_processWrite(out_buf, bytes_read) == false) {
-                        sendCSW(CSW_STATUS_CMD_FAILED); /* send fail status to host,and the host will retry*/
-                        //return;
-                    }
-                    break;
-                case SCSI_VERIFY10:
-                    if (SCSI_processVerify(out_buf, bytes_read) == false) {
-                        sendCSW(CSW_STATUS_CMD_FAILED); /* send fail status to host,and the host will retry*/
-                        //return;
-                    }
-                    break;
-                default:
-                    break;
-            }
-            break;
-        default:
-            break;
-    }
-
-    /*set ep ack to recv next data*/
-    usbd_ep_read(ep, NULL, 0, NULL);
+static void mass_storage_bulk_out(uint8_t ep) {
+  uint8_t  out_buf[MASS_STORAGE_BULK_EP_MPS];
+  uint32_t bytes_read;
+
+  usbd_ep_read(ep, out_buf, MASS_STORAGE_BULK_EP_MPS, &bytes_read);
+
+  switch (usbd_msc_cfg.stage) {
+  case MSC_READ_CBW:
+    if (SCSI_CBWDecode(out_buf, bytes_read) == false) {
+      USBD_LOG_ERR("Command:0x%02x decode err\r\n", usbd_msc_cfg.cbw.CB[0]);
+      usbd_msc_bot_abort();
+      return;
+    }
+    break;
+  /* last command is write10 or write12,and has caculated blk_addr and blk_len,so the device start reading data from host*/
+  case MSC_DATA_OUT:
+    switch (usbd_msc_cfg.cbw.CB[0]) {
+    case SCSI_WRITE10:
+    case SCSI_WRITE12:
+      if (SCSI_processWrite(out_buf, bytes_read) == false) {
+        sendCSW(CSW_STATUS_CMD_FAILED); /* send fail status to host,and the host will retry*/
+                                        // return;
+      }
+      break;
+    case SCSI_VERIFY10:
+      if (SCSI_processVerify(out_buf, bytes_read) == false) {
+        sendCSW(CSW_STATUS_CMD_FAILED); /* send fail status to host,and the host will retry*/
+                                        // return;
+      }
+      break;
+    default:
+      break;
+    }
+    break;
+  default:
+    break;
+  }
+
+  /*set ep ack to recv next data*/
+  usbd_ep_read(ep, NULL, 0, NULL);
 }
 
 /**
@@ -933,72 +841,69 @@ static void mass_storage_bulk_out(uint8_t ep)
  *
  * @return  N/A.
  */
-static void mass_storage_bulk_in(uint8_t ep)
-{
-    switch (usbd_msc_cfg.stage) {
-        /* last command is read10 or read12,and has caculated blk_addr and blk_len,so the device has to send remain data to host*/
-        case MSC_DATA_IN:
-            switch (usbd_msc_cfg.cbw.CB[0]) {
-                case SCSI_READ10:
-                case SCSI_READ12:
-                    if (SCSI_processRead() == false) {
-                        sendCSW(CSW_STATUS_CMD_FAILED); /* send fail status to host,and the host will retry*/
-                        return;
-                    }
-                    break;
-                default:
-                    break;
-            }
-
-            break;
-
-        /*the device has to send a CSW*/
-        case MSC_SEND_CSW:
-            sendCSW(CSW_STATUS_CMD_PASSED);
-            break;
-
-        /*the host has received the CSW*/
-        case MSC_WAIT_CSW:
-            usbd_msc_cfg.stage = MSC_READ_CBW;
-            break;
-
-        default:
-            break;
-    }
+static void mass_storage_bulk_in(uint8_t ep) {
+  switch (usbd_msc_cfg.stage) {
+  /* last command is read10 or read12,and has caculated blk_addr and blk_len,so the device has to send remain data to host*/
+  case MSC_DATA_IN:
+    switch (usbd_msc_cfg.cbw.CB[0]) {
+    case SCSI_READ10:
+    case SCSI_READ12:
+      if (SCSI_processRead() == false) {
+        sendCSW(CSW_STATUS_CMD_FAILED); /* send fail status to host,and the host will retry*/
+        return;
+      }
+      break;
+    default:
+      break;
+    }
+
+    break;
+
+  /*the device has to send a CSW*/
+  case MSC_SEND_CSW:
+    sendCSW(CSW_STATUS_CMD_PASSED);
+    break;
+
+  /*the host has received the CSW*/
+  case MSC_WAIT_CSW:
+    usbd_msc_cfg.stage = MSC_READ_CBW;
+    break;
+
+  default:
+    break;
+  }
 }
 
-void msc_storage_notify_handler(uint8_t event, void *arg)
-{
-    switch (event) {
-        case USB_EVENT_RESET:
-            usbd_msc_reset();
-            break;
+void msc_storage_notify_handler(uint8_t event, void *arg) {
+  switch (event) {
+  case USB_EVENT_RESET:
+    usbd_msc_reset();
+    break;
 
-        default:
-            break;
-    }
+  default:
+    break;
+  }
 }
 
 static usbd_class_t msc_class;
 
 static usbd_interface_t msc_intf = {
-    .class_handler = msc_storage_class_request_handler,
+    .class_handler  = msc_storage_class_request_handler,
     .vendor_handler = NULL,
     .notify_handler = msc_storage_notify_handler,
 };
 
-void usbd_msc_class_init(uint8_t out_ep, uint8_t in_ep)
-{
-    msc_class.name = "usbd_msc";
+void usbd_msc_class_init(uint8_t out_ep, uint8_t in_ep) {
+  msc_class.name = "usbd_msc";
 
-    usbd_class_register(&msc_class);
-    usbd_class_add_interface(&msc_class, &msc_intf);
+  usbd_class_register(&msc_class);
+  usbd_class_add_interface(&msc_class, &msc_intf);
 
-    mass_ep_data[0].ep_addr = out_ep;
-    mass_ep_data[0].ep_cb = mass_storage_bulk_out;
-    mass_ep_data[1].ep_addr = in_ep;
-    mass_ep_data[1].ep_cb = mass_storage_bulk_in;
+  mass_ep_data[0].ep_addr = out_ep;
+  mass_ep_data[0].ep_cb   = mass_storage_bulk_out;
+  mass_ep_data[1].ep_addr = in_ep;
+  mass_ep_data[1].ep_cb   = mass_storage_bulk_in;
 
-    usbd_interface_add_endpoint(&msc_intf, &mass_ep_data[0]);
-    usbd_interface_add_endpoint(&msc_intf, &mass_ep_data[1]);
+  usbd_interface_add_endpoint(&msc_intf, &mass_ep_data[0]);
+  usbd_interface_add_endpoint(&msc_intf, &mass_ep_data[1]);
 }
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.c
index 6eb2554ba5..7e09da0b52 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.c
@@ -19,116 +19,113 @@
  * under the License.
  *
  */
-#include "usbd_core.h"
 #include "usbd_video.h"
+#include "usbd_core.h"
 
 extern struct video_probe_and_commit_controls probe;
 extern struct video_probe_and_commit_controls commit;
 
-int video_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("Video Class request: "
-                 "bRequest 0x%02x\r\n",
-                 setup->bRequest);
-
-    switch (setup->bRequest) {
-        case VIDEO_REQUEST_SET_CUR:
-            if (setup->wValue == 256) {
-                memcpy((uint8_t *)&probe, *data, setup->wLength);
-            } else if (setup->wValue == 512) {
-                memcpy((uint8_t *)&commit, *data, setup->wLength);
-            }
+int video_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) {
+  USBD_LOG_DBG("Video Class request: "
+               "bRequest 0x%02x\r\n",
+               setup->bRequest);
+
+  switch (setup->bRequest) {
+  case VIDEO_REQUEST_SET_CUR:
+    if (setup->wValue == 256) {
+      memcpy((uint8_t *)&probe, *data, setup->wLength);
+    } else if (setup->wValue == 512) {
+      memcpy((uint8_t *)&commit, *data, setup->wLength);
+    }
 
-            break;
+    break;
 
-        case VIDEO_REQUEST_GET_CUR:
-            if (setup->wValue == 256) {
-                *data = (uint8_t *)&probe;
-            } else if (setup->wValue == 512) {
-                *data = (uint8_t *)&commit;
-            }
+  case VIDEO_REQUEST_GET_CUR:
+    if (setup->wValue == 256) {
+      *data = (uint8_t *)&probe;
+    } else if (setup->wValue == 512) {
+      *data = (uint8_t *)&commit;
+    }
 
-            break;
+    break;
 
-        case VIDEO_REQUEST_GET_MIN:
-            if (setup->wValue == 256) {
-                *data = (uint8_t *)&probe;
-            } else if (setup->wValue == 512) {
-                *data = (uint8_t *)&commit;
-            }
+  case VIDEO_REQUEST_GET_MIN:
+    if (setup->wValue == 256) {
+      *data = (uint8_t *)&probe;
+    } else if (setup->wValue == 512) {
+      *data = (uint8_t *)&commit;
+    }
 
-            break;
+    break;
 
-        case VIDEO_REQUEST_GET_MAX:
-            if (setup->wValue == 256) {
-                *data = (uint8_t *)&probe;
-            } else if (setup->wValue == 512) {
-                *data = (uint8_t *)&commit;
-            }
+  case VIDEO_REQUEST_GET_MAX:
+    if (setup->wValue == 256) {
+      *data = (uint8_t *)&probe;
+    } else if (setup->wValue == 512) {
+      *data = (uint8_t *)&commit;
+    }
 
-            break;
+    break;
 
-        case VIDEO_REQUEST_GET_RES:
+  case VIDEO_REQUEST_GET_RES:
 
-            break;
+    break;
 
-        case VIDEO_REQUEST_GET_LEN:
+  case VIDEO_REQUEST_GET_LEN:
 
-            break;
+    break;
 
-        case VIDEO_REQUEST_GET_INFO:
+  case VIDEO_REQUEST_GET_INFO:
 
-            break;
+    break;
 
-        case VIDEO_REQUEST_GET_DEF:
-            if (setup->wLength == 256) {
-                *data = (uint8_t *)&probe;
-            } else if (setup->wLength == 512) {
-                *data = (uint8_t *)&commit;
-            }
+  case VIDEO_REQUEST_GET_DEF:
+    if (setup->wLength == 256) {
+      *data = (uint8_t *)&probe;
+    } else if (setup->wLength == 512) {
+      *data = (uint8_t *)&commit;
+    }
 
-            break;
+    break;
 
-        default:
-            USBD_LOG_WRN("Unhandled Video Class bRequest 0x%02x\r\n", setup->bRequest);
-            return -1;
-    }
+  default:
+    USBD_LOG_WRN("Unhandled Video Class bRequest 0x%02x\r\n", setup->bRequest);
+    return -1;
+  }
 
-    return 0;
+  return 0;
 }
 
-void video_notify_handler(uint8_t event, void *arg)
-{
-    switch (event) {
-        case USB_EVENT_RESET:
+void video_notify_handler(uint8_t event, void *arg) {
+  switch (event) {
+  case USB_EVENT_RESET:
 
-            break;
+    break;
 
-        case USB_EVENT_SOF:
-            usbd_video_sof_callback();
-            break;
+  case USB_EVENT_SOF:
+    usbd_video_sof_callback();
+    break;
 
-        case USB_EVENT_SET_INTERFACE:
-            usbd_video_set_interface_callback(((uint8_t *)arg)[3]);
-            break;
+  case USB_EVENT_SET_INTERFACE:
+    usbd_video_set_interface_callback(((uint8_t *)arg)[3]);
+    break;
 
-        default:
-            break;
-    }
+  default:
+    break;
+  }
 }
 
-void usbd_video_add_interface(usbd_class_t *class, usbd_interface_t *intf)
-{
-    static usbd_class_t *last_class = NULL;
+void usbd_video_add_interface(usbd_class_t *class, usbd_interface_t *intf) {
+  static usbd_class_t *last_class = NULL;
 
-    if (last_class != class) {
-        last_class = class;
-        usbd_class_register(class);
-    }
+  if (last_class != class) {
+    last_class = class;
+    usbd_class_register(class);
+  }
 
-    intf->class_handler = video_class_request_handler;
-    intf->custom_handler = NULL;
-    intf->vendor_handler = NULL;
-    intf->notify_handler = video_notify_handler;
-    usbd_class_add_interface(class, intf);
+  intf->class_handler  = video_class_request_handler;
+  intf->custom_handler = NULL;
+  intf->vendor_handler = NULL;
+  intf->notify_handler = video_notify_handler;
+  usbd_class_add_interface(class, intf);
 }
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.c
index 47929088fd..99e0072b3c 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.c
@@ -45,40 +45,40 @@
 #define USB_EP_IN_NUM           8
 
 static struct usbd_core_cfg_priv {
-    /** Setup packet */
-    struct usb_setup_packet setup;
-    /** Pointer to data buffer */
-    uint8_t *ep0_data_buf;
-    /** Remaining bytes in buffer */
-    uint32_t ep0_data_buf_residue;
-    /** Total length of control transfer */
-    uint32_t ep0_data_buf_len;
-    /** Zero length packet flag of control transfer */
-    bool zlp_flag;
-    /** Pointer to registered descriptors */
-    const uint8_t *descriptors;
-    /* Buffer used for storing standard, class and vendor request data */
-    uint8_t req_data[USB_REQUEST_BUFFER_SIZE];
+  /** Setup packet */
+  struct usb_setup_packet setup;
+  /** Pointer to data buffer */
+  uint8_t *ep0_data_buf;
+  /** Remaining bytes in buffer */
+  uint32_t ep0_data_buf_residue;
+  /** Total length of control transfer */
+  uint32_t ep0_data_buf_len;
+  /** Zero length packet flag of control transfer */
+  bool zlp_flag;
+  /** Pointer to registered descriptors */
+  const uint8_t *descriptors;
+  /* Buffer used for storing standard, class and vendor request data */
+  uint8_t req_data[USB_REQUEST_BUFFER_SIZE];
 
 #if USBD_EP_CALLBACK_SEARCH_METHOD == 1
-    usbd_endpoint_callback in_ep_cb[USB_EP_IN_NUM];
-    usbd_endpoint_callback out_ep_cb[USB_EP_OUT_NUM];
+  usbd_endpoint_callback in_ep_cb[USB_EP_IN_NUM];
+  usbd_endpoint_callback out_ep_cb[USB_EP_OUT_NUM];
 #endif
-    /** Variable to check whether the usb has been enabled */
-    bool enabled;
-    /** Variable to check whether the usb has been configured */
-    bool configured;
-    /** Currently selected configuration */
-    uint8_t configuration;
-    /** Remote wakeup feature status */
-    uint16_t remote_wakeup;
-    uint8_t reserved;
+  /** Variable to check whether the usb has been enabled */
+  bool enabled;
+  /** Variable to check whether the usb has been configured */
+  bool configured;
+  /** Currently selected configuration */
+  uint8_t configuration;
+  /** Remote wakeup feature status */
+  uint16_t remote_wakeup;
+  uint8_t  reserved;
 } usbd_core_cfg;
 
-static usb_slist_t usbd_class_head = USB_SLIST_OBJECT_INIT(usbd_class_head);
+static usb_slist_t                   usbd_class_head = USB_SLIST_OBJECT_INIT(usbd_class_head);
 static struct usb_msosv1_descriptor *msosv1_desc;
 static struct usb_msosv2_descriptor *msosv2_desc;
-static struct usb_bos_descriptor *bos_desc;
+static struct usb_bos_descriptor    *bos_desc;
 
 /**
  * @brief print the contents of a setup packet
@@ -86,15 +86,10 @@ static struct usb_bos_descriptor *bos_desc;
  * @param [in] setup The setup packet
  *
  */
-static void usbd_print_setup(struct usb_setup_packet *setup)
-{
-    USBD_LOG_INFO("Setup: "
-                  "bmRequestType 0x%02x, bRequest 0x%02x, wValue 0x%04x, wIndex 0x%04x, wLength 0x%04x\r\n",
-                  setup->bmRequestType,
-                  setup->bRequest,
-                  setup->wValue,
-                  setup->wIndex,
-                  setup->wLength);
+static void usbd_print_setup(struct usb_setup_packet *setup) {
+  USBD_LOG_INFO("Setup: "
+                "bmRequestType 0x%02x, bRequest 0x%02x, wValue 0x%04x, wIndex 0x%04x, wLength 0x%04x\r\n",
+                setup->bmRequestType, setup->bRequest, setup->wValue, setup->wIndex, setup->wLength);
 }
 
 /**
@@ -102,10 +97,7 @@ static void usbd_print_setup(struct usb_setup_packet *setup)
  *
  * @return true if Configured, false otherwise.
  */
-static bool is_device_configured(void)
-{
-    return (usbd_core_cfg.configuration != 0);
-}
+static bool is_device_configured(void) { return (usbd_core_cfg.configuration != 0); }
 /**
  * @brief Check if the interface of given number is valid
  *
@@ -116,25 +108,24 @@ static bool is_device_configured(void)
  *
  * @return true if interface exists - valid
  */
-static bool is_interface_valid(uint8_t interface)
-{
-    const uint8_t *p = (uint8_t *)usbd_core_cfg.descriptors;
-    const struct usb_configuration_descriptor *cfg_descr;
-
-    /* Search through descriptor for matching interface */
-    while (p[DESC_bLength] != 0U) {
-        if (p[DESC_bDescriptorType] == USB_DESCRIPTOR_TYPE_CONFIGURATION) {
-            cfg_descr = (const struct usb_configuration_descriptor *)p;
-
-            if (interface < cfg_descr->bNumInterfaces) {
-                return true;
-            }
-        }
+static bool is_interface_valid(uint8_t interface) {
+  const uint8_t                             *p = (uint8_t *)usbd_core_cfg.descriptors;
+  const struct usb_configuration_descriptor *cfg_descr;
+
+  /* Search through descriptor for matching interface */
+  while (p[DESC_bLength] != 0U) {
+    if (p[DESC_bDescriptorType] == USB_DESCRIPTOR_TYPE_CONFIGURATION) {
+      cfg_descr = (const struct usb_configuration_descriptor *)p;
 
-        p += p[DESC_bLength];
+      if (interface < cfg_descr->bNumInterfaces) {
+        return true;
+      }
     }
 
-    return false;
+    p += p[DESC_bLength];
+  }
+
+  return false;
 }
 /**
  * @brief Check if the endpoint of given address is valid
@@ -147,41 +138,36 @@ static bool is_interface_valid(uint8_t interface)
  *
  * @return true if endpoint exists - valid
  */
-static bool is_ep_valid(uint8_t ep)
-{
-    /* Check if its Endpoint 0 */
-    if ((ep & 0x7f) == 0) {
-        return true;
-    }
-
+static bool is_ep_valid(uint8_t ep) {
+  /* Check if its Endpoint 0 */
+  if ((ep & 0x7f) == 0) {
     return true;
+  }
+
+  return true;
 }
 #if USBD_EP_CALLBACK_SEARCH_METHOD == 1
-static void usbd_ep_callback_register(void)
-{
-    usb_slist_t *i, *j, *k;
-    usb_slist_for_each(i, &usbd_class_head)
-    {
-        usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
-
-        usb_slist_for_each(j, &class->intf_list)
-        {
-            usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
-
-            usb_slist_for_each(k, &intf->ep_list)
-            {
-                usbd_endpoint_t *ept = usb_slist_entry(k, struct usbd_endpoint, list);
-
-                if (ept->ep_cb) {
-                    if (ept->ep_addr & 0x80) {
-                        usbd_core_cfg.in_ep_cb[ept->ep_addr & 0x7f] = ept->ep_cb;
-                    } else {
-                        usbd_core_cfg.out_ep_cb[ept->ep_addr & 0x7f] = ept->ep_cb;
-                    }
-                }
-            }
+static void usbd_ep_callback_register(void) {
+  usb_slist_t *i, *j, *k;
+  usb_slist_for_each(i, &usbd_class_head) {
+    usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
+
+    usb_slist_for_each(j, &class->intf_list) {
+      usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
+
+      usb_slist_for_each(k, &intf->ep_list) {
+        usbd_endpoint_t *ept = usb_slist_entry(k, struct usbd_endpoint, list);
+
+        if (ept->ep_cb) {
+          if (ept->ep_addr & 0x80) {
+            usbd_core_cfg.in_ep_cb[ept->ep_addr & 0x7f] = ept->ep_cb;
+          } else {
+            usbd_core_cfg.out_ep_cb[ept->ep_addr & 0x7f] = ept->ep_cb;
+          }
         }
+      }
     }
+  }
 }
 #endif
 /**
@@ -194,21 +180,19 @@ static void usbd_ep_callback_register(void)
  *
  * @return true if successfully configured and enabled
  */
-static bool usbd_set_endpoint(const struct usb_endpoint_descriptor *ep_desc)
-{
-    struct usbd_endpoint_cfg ep_cfg;
+static bool usbd_set_endpoint(const struct usb_endpoint_descriptor *ep_desc) {
+  struct usbd_endpoint_cfg ep_cfg;
 
-    ep_cfg.ep_addr = ep_desc->bEndpointAddress;
-    ep_cfg.ep_mps = ep_desc->wMaxPacketSize;
-    ep_cfg.ep_type = ep_desc->bmAttributes & USBD_EP_TYPE_MASK;
+  ep_cfg.ep_addr = ep_desc->bEndpointAddress;
+  ep_cfg.ep_mps  = ep_desc->wMaxPacketSize;
+  ep_cfg.ep_type = ep_desc->bmAttributes & USBD_EP_TYPE_MASK;
 
-    USBD_LOG_INFO("Open endpoint:0x%x type:%u mps:%u\r\n",
-                  ep_cfg.ep_addr, ep_cfg.ep_type, ep_cfg.ep_mps);
+  USBD_LOG_INFO("Open endpoint:0x%x type:%u mps:%u\r\n", ep_cfg.ep_addr, ep_cfg.ep_type, ep_cfg.ep_mps);
 
-    usbd_ep_open(&ep_cfg);
-    usbd_core_cfg.configured = true;
+  usbd_ep_open(&ep_cfg);
+  usbd_core_cfg.configured = true;
 
-    return true;
+  return true;
 }
 /**
  * @brief Disable endpoint for transferring data
@@ -220,20 +204,18 @@ static bool usbd_set_endpoint(const struct usb_endpoint_descriptor *ep_desc)
  *
  * @return true if successfully deconfigured and disabled
  */
-static bool usbd_reset_endpoint(const struct usb_endpoint_descriptor *ep_desc)
-{
-    struct usbd_endpoint_cfg ep_cfg;
+static bool usbd_reset_endpoint(const struct usb_endpoint_descriptor *ep_desc) {
+  struct usbd_endpoint_cfg ep_cfg;
 
-    ep_cfg.ep_addr = ep_desc->bEndpointAddress;
-    ep_cfg.ep_mps = ep_desc->wMaxPacketSize;
-    ep_cfg.ep_type = ep_desc->bmAttributes & USBD_EP_TYPE_MASK;
+  ep_cfg.ep_addr = ep_desc->bEndpointAddress;
+  ep_cfg.ep_mps  = ep_desc->wMaxPacketSize;
+  ep_cfg.ep_type = ep_desc->bmAttributes & USBD_EP_TYPE_MASK;
 
-    USBD_LOG_INFO("Close endpoint:0x%x type:%u\r\n",
-                  ep_cfg.ep_addr, ep_cfg.ep_type);
+  USBD_LOG_INFO("Close endpoint:0x%x type:%u\r\n", ep_cfg.ep_addr, ep_cfg.ep_type);
 
-    usbd_ep_close(ep_cfg.ep_addr);
+  usbd_ep_close(ep_cfg.ep_addr);
 
-    return true;
+  return true;
 }
 
 /**
@@ -249,92 +231,90 @@ static bool usbd_reset_endpoint(const struct usb_endpoint_descriptor *ep_desc)
  *
  * @return true if the descriptor was found, false otherwise
  */
-static bool usbd_get_descriptor(uint16_t type_index, uint8_t **data, uint32_t *len)
-{
-    uint8_t type = 0U;
-    uint8_t index = 0U;
-    uint8_t *p = NULL;
-    uint32_t cur_index = 0U;
-    bool found = false;
-
-    type = GET_DESC_TYPE(type_index);
-    index = GET_DESC_INDEX(type_index);
-
-    if ((type == USB_DESCRIPTOR_TYPE_STRING) && (index == USB_OSDESC_STRING_DESC_INDEX)) {
-        USBD_LOG_INFO("read MS OS 2.0 descriptor string\r\n");
-
-        if (!msosv1_desc) {
-            return false;
-        }
+static bool usbd_get_descriptor(uint16_t type_index, uint8_t **data, uint32_t *len) {
+  uint8_t  type      = 0U;
+  uint8_t  index     = 0U;
+  uint8_t *p         = NULL;
+  uint32_t cur_index = 0U;
+  bool     found     = false;
 
-        *data = (uint8_t *)msosv1_desc->string;
-        *len = msosv1_desc->string_len;
+  type  = GET_DESC_TYPE(type_index);
+  index = GET_DESC_INDEX(type_index);
 
-        return true;
-    } else if (type == USB_DESCRIPTOR_TYPE_BINARY_OBJECT_STORE) {
-        USBD_LOG_INFO("read BOS descriptor string\r\n");
+  if ((type == USB_DESCRIPTOR_TYPE_STRING) && (index == USB_OSDESC_STRING_DESC_INDEX)) {
+    USBD_LOG_INFO("read MS OS 2.0 descriptor string\r\n");
 
-        if (!bos_desc) {
-            return false;
-        }
+    if (!msosv1_desc) {
+      return false;
+    }
 
-        *data = bos_desc->string;
-        *len = bos_desc->string_len;
-        return true;
+    *data = (uint8_t *)msosv1_desc->string;
+    *len  = msosv1_desc->string_len;
+
+    return true;
+  } else if (type == USB_DESCRIPTOR_TYPE_BINARY_OBJECT_STORE) {
+    USBD_LOG_INFO("read BOS descriptor string\r\n");
+
+    if (!bos_desc) {
+      return false;
     }
-    /*
-     * Invalid types of descriptors,
-     * see USB Spec. Revision 2.0, 9.4.3 Get Descriptor
-     */
-    else if ((type == USB_DESCRIPTOR_TYPE_INTERFACE) || (type == USB_DESCRIPTOR_TYPE_ENDPOINT) ||
+
+    *data = bos_desc->string;
+    *len  = bos_desc->string_len;
+    return true;
+  }
+  /*
+   * Invalid types of descriptors,
+   * see USB Spec. Revision 2.0, 9.4.3 Get Descriptor
+   */
+  else if ((type == USB_DESCRIPTOR_TYPE_INTERFACE) || (type == USB_DESCRIPTOR_TYPE_ENDPOINT) ||
 #ifndef CONFIG_USB_HS
-             (type > USB_DESCRIPTOR_TYPE_ENDPOINT)) {
+           (type > USB_DESCRIPTOR_TYPE_ENDPOINT)) {
 #else
-             (type > USB_DESCRIPTOR_TYPE_OTHER_SPEED)) {
+           (type > USB_DESCRIPTOR_TYPE_OTHER_SPEED)) {
 #endif
-        return false;
-    }
+    return false;
+  }
 
-    p = (uint8_t *)usbd_core_cfg.descriptors;
+  p = (uint8_t *)usbd_core_cfg.descriptors;
 
-    cur_index = 0U;
+  cur_index = 0U;
 
-    while (p[DESC_bLength] != 0U) {
-        if (p[DESC_bDescriptorType] == type) {
-            if (cur_index == index) {
-                found = true;
-                break;
-            }
+  while (p[DESC_bLength] != 0U) {
+    if (p[DESC_bDescriptorType] == type) {
+      if (cur_index == index) {
+        found = true;
+        break;
+      }
 
-            cur_index++;
-        }
-
-        /* skip to next descriptor */
-        p += p[DESC_bLength];
+      cur_index++;
     }
 
-    if (found) {
-        /* set data pointer */
-        *data = p;
-
-        /* get length from structure */
-        if (type == USB_DESCRIPTOR_TYPE_CONFIGURATION) {
-            /* configuration descriptor is an
-             * exception, length is at offset
-             * 2 and 3
-             */
-            *len = (p[CONF_DESC_wTotalLength]) |
-                   (p[CONF_DESC_wTotalLength + 1] << 8);
-        } else {
-            /* normally length is at offset 0 */
-            *len = p[DESC_bLength];
-        }
+    /* skip to next descriptor */
+    p += p[DESC_bLength];
+  }
+
+  if (found) {
+    /* set data pointer */
+    *data = p;
+
+    /* get length from structure */
+    if (type == USB_DESCRIPTOR_TYPE_CONFIGURATION) {
+      /* configuration descriptor is an
+       * exception, length is at offset
+       * 2 and 3
+       */
+      *len = (p[CONF_DESC_wTotalLength]) | (p[CONF_DESC_wTotalLength + 1] << 8);
     } else {
-        /* nothing found */
-        USBD_LOG_ERR("descriptor  not found!\r\n", type, index);
+      /* normally length is at offset 0 */
+      *len = p[DESC_bLength];
     }
+  } else {
+    /* nothing found */
+    USBD_LOG_ERR("descriptor  not found!\r\n", type, index);
+  }
 
-    return found;
+  return found;
 }
 
 /**
@@ -349,56 +329,53 @@ static bool usbd_get_descriptor(uint16_t type_index, uint8_t **data, uint32_t *l
  *
  * @return true if successfully configured false if error or unconfigured
  */
-static bool usbd_set_configuration(uint8_t config_index, uint8_t alt_setting)
-{
-    uint8_t *p = (uint8_t *)usbd_core_cfg.descriptors;
-    uint8_t cur_alt_setting = 0xFF;
-    uint8_t cur_config = 0xFF;
-    bool found = false;
-
-    if (config_index == 0U) {
-        /* TODO: unconfigure device */
-        USBD_LOG_ERR("Device not configured - invalid configuration\r\n");
-        return true;
-    }
-
-    /* configure endpoints for this configuration/altsetting */
-    while (p[DESC_bLength] != 0U) {
-        switch (p[DESC_bDescriptorType]) {
-            case USB_DESCRIPTOR_TYPE_CONFIGURATION:
-                /* remember current configuration index */
-                cur_config = p[CONF_DESC_bConfigurationValue];
+static bool usbd_set_configuration(uint8_t config_index, uint8_t alt_setting) {
+  uint8_t *p               = (uint8_t *)usbd_core_cfg.descriptors;
+  uint8_t  cur_alt_setting = 0xFF;
+  uint8_t  cur_config      = 0xFF;
+  bool     found           = false;
+
+  if (config_index == 0U) {
+    /* TODO: unconfigure device */
+    USBD_LOG_ERR("Device not configured - invalid configuration\r\n");
+    return true;
+  }
 
-                if (cur_config == config_index) {
-                    found = true;
-                }
+  /* configure endpoints for this configuration/altsetting */
+  while (p[DESC_bLength] != 0U) {
+    switch (p[DESC_bDescriptorType]) {
+    case USB_DESCRIPTOR_TYPE_CONFIGURATION:
+      /* remember current configuration index */
+      cur_config = p[CONF_DESC_bConfigurationValue];
 
-                break;
+      if (cur_config == config_index) {
+        found = true;
+      }
 
-            case USB_DESCRIPTOR_TYPE_INTERFACE:
-                /* remember current alternate setting */
-                cur_alt_setting =
-                    p[INTF_DESC_bAlternateSetting];
-                break;
+      break;
 
-            case USB_DESCRIPTOR_TYPE_ENDPOINT:
-                if ((cur_config != config_index) ||
-                    (cur_alt_setting != alt_setting)) {
-                    break;
-                }
+    case USB_DESCRIPTOR_TYPE_INTERFACE:
+      /* remember current alternate setting */
+      cur_alt_setting = p[INTF_DESC_bAlternateSetting];
+      break;
 
-                found = usbd_set_endpoint((struct usb_endpoint_descriptor *)p);
-                break;
+    case USB_DESCRIPTOR_TYPE_ENDPOINT:
+      if ((cur_config != config_index) || (cur_alt_setting != alt_setting)) {
+        break;
+      }
 
-            default:
-                break;
-        }
+      found = usbd_set_endpoint((struct usb_endpoint_descriptor *)p);
+      break;
 
-        /* skip to next descriptor */
-        p += p[DESC_bLength];
+    default:
+      break;
     }
 
-    return found;
+    /* skip to next descriptor */
+    p += p[DESC_bLength];
+  }
+
+  return found;
 }
 
 /**
@@ -409,57 +386,54 @@ static bool usbd_set_configuration(uint8_t config_index, uint8_t alt_setting)
  *
  * @return true if successfully configured false if error or unconfigured
  */
-static bool usbd_set_interface(uint8_t iface, uint8_t alt_setting)
-{
-    const uint8_t *p = usbd_core_cfg.descriptors;
-    const uint8_t *if_desc = NULL;
-    struct usb_endpoint_descriptor *ep_desc;
-    uint8_t cur_alt_setting = 0xFF;
-    uint8_t cur_iface = 0xFF;
-    bool ret = false;
-
-    USBD_LOG_DBG("iface %u alt_setting %u\r\n", iface, alt_setting);
-
-    while (p[DESC_bLength] != 0U) {
-        switch (p[DESC_bDescriptorType]) {
-            case USB_DESCRIPTOR_TYPE_INTERFACE:
-                /* remember current alternate setting */
-                cur_alt_setting = p[INTF_DESC_bAlternateSetting];
-                cur_iface = p[INTF_DESC_bInterfaceNumber];
-
-                if (cur_iface == iface &&
-                    cur_alt_setting == alt_setting) {
-                    if_desc = (void *)p;
-                }
-
-                USBD_LOG_DBG("Current iface %u alt setting %u",
-                             cur_iface, cur_alt_setting);
-                break;
-
-            case USB_DESCRIPTOR_TYPE_ENDPOINT:
-                if (cur_iface == iface) {
-                    ep_desc = (struct usb_endpoint_descriptor *)p;
-
-                    if (cur_alt_setting != alt_setting) {
-                        ret = usbd_reset_endpoint(ep_desc);
-                    } else {
-                        ret = usbd_set_endpoint(ep_desc);
-                    }
-                }
-
-                break;
-
-            default:
-                break;
+static bool usbd_set_interface(uint8_t iface, uint8_t alt_setting) {
+  const uint8_t                  *p       = usbd_core_cfg.descriptors;
+  const uint8_t                  *if_desc = NULL;
+  struct usb_endpoint_descriptor *ep_desc;
+  uint8_t                         cur_alt_setting = 0xFF;
+  uint8_t                         cur_iface       = 0xFF;
+  bool                            ret             = false;
+
+  USBD_LOG_DBG("iface %u alt_setting %u\r\n", iface, alt_setting);
+
+  while (p[DESC_bLength] != 0U) {
+    switch (p[DESC_bDescriptorType]) {
+    case USB_DESCRIPTOR_TYPE_INTERFACE:
+      /* remember current alternate setting */
+      cur_alt_setting = p[INTF_DESC_bAlternateSetting];
+      cur_iface       = p[INTF_DESC_bInterfaceNumber];
+
+      if (cur_iface == iface && cur_alt_setting == alt_setting) {
+        if_desc = (void *)p;
+      }
+
+      USBD_LOG_DBG("Current iface %u alt setting %u", cur_iface, cur_alt_setting);
+      break;
+
+    case USB_DESCRIPTOR_TYPE_ENDPOINT:
+      if (cur_iface == iface) {
+        ep_desc = (struct usb_endpoint_descriptor *)p;
+
+        if (cur_alt_setting != alt_setting) {
+          ret = usbd_reset_endpoint(ep_desc);
+        } else {
+          ret = usbd_set_endpoint(ep_desc);
         }
+      }
 
-        /* skip to next descriptor */
-        p += p[DESC_bLength];
+      break;
+
+    default:
+      break;
     }
 
-    usbd_event_notify_handler(USB_EVENT_SET_INTERFACE, (void *)if_desc);
+    /* skip to next descriptor */
+    p += p[DESC_bLength];
+  }
+
+  usbd_event_notify_handler(USB_EVENT_SET_INTERFACE, (void *)if_desc);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -471,102 +445,101 @@ static bool usbd_set_interface(uint8_t iface, uint8_t alt_setting)
  *
  * @return true if the request was handled successfully
  */
-static bool usbd_std_device_req_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    uint16_t value = setup->wValue;
-    // uint16_t index = setup->wIndex;
-    bool ret = true;
-
-    switch (setup->bRequest) {
-        case USB_REQUEST_GET_STATUS:
-            USBD_LOG_DBG("REQ_GET_STATUS\r\n");
-            /* bit 0: self-powered */
-            /* bit 1: remote wakeup */
-            *data = (uint8_t *)&usbd_core_cfg.remote_wakeup;
-
-            *len = 2;
-            break;
-
-        case USB_REQUEST_CLEAR_FEATURE:
-            USBD_LOG_DBG("REQ_CLEAR_FEATURE\r\n");
-            ret = false;
-
-            if (value == USB_FEATURE_REMOTE_WAKEUP) {
-                usbd_core_cfg.remote_wakeup = 0;
-                usbd_event_notify_handler(USB_EVENT_CLEAR_REMOTE_WAKEUP, NULL);
-                ret = true;
-            }
-
-            break;
-
-        case USB_REQUEST_SET_FEATURE:
-            USBD_LOG_DBG("REQ_SET_FEATURE\r\n");
-            ret = false;
-
-            if (value == USB_FEATURE_REMOTE_WAKEUP) {
-                usbd_core_cfg.remote_wakeup = 1;
-                usbd_event_notify_handler(USB_EVENT_SET_REMOTE_WAKEUP, NULL);
-                ret = true;
-            }
-
-            if (value == USB_FEATURE_TEST_MODE) {
-                /* put TEST_MODE code here */
-            }
-
-            break;
-
-        case USB_REQUEST_SET_ADDRESS:
-            USBD_LOG_DBG("REQ_SET_ADDRESS, addr 0x%x\r\n", value);
-            usbd_set_address(value);
-            break;
-
-        case USB_REQUEST_GET_DESCRIPTOR:
-            USBD_LOG_DBG("REQ_GET_DESCRIPTOR\r\n");
-            ret = usbd_get_descriptor(value, data, len);
-            break;
-
-        case USB_REQUEST_SET_DESCRIPTOR:
-            USBD_LOG_DBG("Device req 0x%02x not implemented\r\n", setup->bRequest);
-            ret = false;
-            break;
-
-        case USB_REQUEST_GET_CONFIGURATION:
-            USBD_LOG_DBG("REQ_GET_CONFIGURATION\r\n");
-            /* indicate if we are configured */
-            *data = (uint8_t *)&usbd_core_cfg.configuration;
-            *len = 1;
-            break;
-
-        case USB_REQUEST_SET_CONFIGURATION:
-            value &= 0xFF;
-            USBD_LOG_DBG("REQ_SET_CONFIGURATION, conf 0x%x\r\n", value);
-
-            if (!usbd_set_configuration(value, 0)) {
-                USBD_LOG_DBG("USB Set Configuration failed\r\n");
-                ret = false;
-            } else {
-                /* configuration successful,
-                 * update current configuration
-                 */
-                usbd_core_cfg.configuration = value;
-                usbd_event_notify_handler(USB_EVENT_CONFIGURED, NULL);
-            }
-
-            break;
-
-        case USB_REQUEST_GET_INTERFACE:
-            break;
-
-        case USB_REQUEST_SET_INTERFACE:
-            break;
-
-        default:
-            USBD_LOG_ERR("Illegal device req 0x%02x\r\n", setup->bRequest);
-            ret = false;
-            break;
+static bool usbd_std_device_req_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) {
+  uint16_t value = setup->wValue;
+  // uint16_t index = setup->wIndex;
+  bool ret = true;
+
+  switch (setup->bRequest) {
+  case USB_REQUEST_GET_STATUS:
+    USBD_LOG_DBG("REQ_GET_STATUS\r\n");
+    /* bit 0: self-powered */
+    /* bit 1: remote wakeup */
+    *data = (uint8_t *)&usbd_core_cfg.remote_wakeup;
+
+    *len = 2;
+    break;
+
+  case USB_REQUEST_CLEAR_FEATURE:
+    USBD_LOG_DBG("REQ_CLEAR_FEATURE\r\n");
+    ret = false;
+
+    if (value == USB_FEATURE_REMOTE_WAKEUP) {
+      usbd_core_cfg.remote_wakeup = 0;
+      usbd_event_notify_handler(USB_EVENT_CLEAR_REMOTE_WAKEUP, NULL);
+      ret = true;
     }
 
-    return ret;
+    break;
+
+  case USB_REQUEST_SET_FEATURE:
+    USBD_LOG_DBG("REQ_SET_FEATURE\r\n");
+    ret = false;
+
+    if (value == USB_FEATURE_REMOTE_WAKEUP) {
+      usbd_core_cfg.remote_wakeup = 1;
+      usbd_event_notify_handler(USB_EVENT_SET_REMOTE_WAKEUP, NULL);
+      ret = true;
+    }
+
+    if (value == USB_FEATURE_TEST_MODE) {
+      /* put TEST_MODE code here */
+    }
+
+    break;
+
+  case USB_REQUEST_SET_ADDRESS:
+    USBD_LOG_DBG("REQ_SET_ADDRESS, addr 0x%x\r\n", value);
+    usbd_set_address(value);
+    break;
+
+  case USB_REQUEST_GET_DESCRIPTOR:
+    USBD_LOG_DBG("REQ_GET_DESCRIPTOR\r\n");
+    ret = usbd_get_descriptor(value, data, len);
+    break;
+
+  case USB_REQUEST_SET_DESCRIPTOR:
+    USBD_LOG_DBG("Device req 0x%02x not implemented\r\n", setup->bRequest);
+    ret = false;
+    break;
+
+  case USB_REQUEST_GET_CONFIGURATION:
+    USBD_LOG_DBG("REQ_GET_CONFIGURATION\r\n");
+    /* indicate if we are configured */
+    *data = (uint8_t *)&usbd_core_cfg.configuration;
+    *len  = 1;
+    break;
+
+  case USB_REQUEST_SET_CONFIGURATION:
+    value &= 0xFF;
+    USBD_LOG_DBG("REQ_SET_CONFIGURATION, conf 0x%x\r\n", value);
+
+    if (!usbd_set_configuration(value, 0)) {
+      USBD_LOG_DBG("USB Set Configuration failed\r\n");
+      ret = false;
+    } else {
+      /* configuration successful,
+       * update current configuration
+       */
+      usbd_core_cfg.configuration = value;
+      usbd_event_notify_handler(USB_EVENT_CONFIGURED, NULL);
+    }
+
+    break;
+
+  case USB_REQUEST_GET_INTERFACE:
+    break;
+
+  case USB_REQUEST_SET_INTERFACE:
+    break;
+
+  default:
+    USBD_LOG_ERR("Illegal device req 0x%02x\r\n", setup->bRequest);
+    ret = false;
+    break;
+  }
+
+  return ret;
 }
 
 /**
@@ -578,52 +551,49 @@ static bool usbd_std_device_req_handler(struct usb_setup_packet *setup, uint8_t
  *
  * @return true if the request was handled successfully
  */
-static bool usbd_std_interface_req_handler(struct usb_setup_packet *setup,
-                                           uint8_t **data, uint32_t *len)
-{
-    /** The device must be configured to accept standard interface
-     * requests and the addressed Interface must be valid.
+static bool usbd_std_interface_req_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) {
+  /** The device must be configured to accept standard interface
+   * requests and the addressed Interface must be valid.
+   */
+  if (!is_device_configured() || (!is_interface_valid((uint8_t)setup->wIndex))) {
+    return false;
+  }
+
+  switch (setup->bRequest) {
+  case USB_REQUEST_GET_STATUS:
+    /* no bits specified */
+    *data = (uint8_t *)&usbd_core_cfg.remote_wakeup;
+
+    *len = 2;
+    break;
+
+  case USB_REQUEST_CLEAR_FEATURE:
+  case USB_REQUEST_SET_FEATURE:
+    /* not defined for interface */
+    return false;
+
+  case USB_REQUEST_GET_INTERFACE:
+    /** This handler is called for classes that does not support
+     * alternate Interfaces so always return 0. Classes that
+     * support alternative interfaces handles GET_INTERFACE
+     * in custom_handler.
      */
-    if (!is_device_configured() ||
-        (!is_interface_valid((uint8_t)setup->wIndex))) {
-        return false;
-    }
+    *data = (uint8_t *)&usbd_core_cfg.reserved;
 
-    switch (setup->bRequest) {
-        case USB_REQUEST_GET_STATUS:
-            /* no bits specified */
-            *data = (uint8_t *)&usbd_core_cfg.remote_wakeup;
-
-            *len = 2;
-            break;
-
-        case USB_REQUEST_CLEAR_FEATURE:
-        case USB_REQUEST_SET_FEATURE:
-            /* not defined for interface */
-            return false;
-
-        case USB_REQUEST_GET_INTERFACE:
-            /** This handler is called for classes that does not support
-             * alternate Interfaces so always return 0. Classes that
-             * support alternative interfaces handles GET_INTERFACE
-             * in custom_handler.
-             */
-            *data = (uint8_t *)&usbd_core_cfg.reserved;
-
-            *len = 1;
-            break;
-
-        case USB_REQUEST_SET_INTERFACE:
-            USBD_LOG_DBG("REQ_SET_INTERFACE\r\n");
-            usbd_set_interface(setup->wIndex, setup->wValue);
-            break;
-
-        default:
-            USBD_LOG_ERR("Illegal interface req 0x%02x\r\n", setup->bRequest);
-            return false;
-    }
+    *len = 1;
+    break;
 
-    return true;
+  case USB_REQUEST_SET_INTERFACE:
+    USBD_LOG_DBG("REQ_SET_INTERFACE\r\n");
+    usbd_set_interface(setup->wIndex, setup->wValue);
+    break;
+
+  default:
+    USBD_LOG_ERR("Illegal interface req 0x%02x\r\n", setup->bRequest);
+    return false;
+  }
+
+  return true;
 }
 
 /**
@@ -635,93 +605,92 @@ static bool usbd_std_interface_req_handler(struct usb_setup_packet *setup,
  *
  * @return true if the request was handled successfully
  */
-static bool usbd_std_endpoint_req_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    uint8_t ep = (uint8_t)setup->wIndex;
+static bool usbd_std_endpoint_req_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) {
+  uint8_t ep = (uint8_t)setup->wIndex;
+
+  /* Check if request addresses valid Endpoint */
+  if (!is_ep_valid(ep)) {
+    return false;
+  }
+
+  switch (setup->bRequest) {
+  case USB_REQUEST_GET_STATUS:
+
+    /** This request is valid for Control Endpoints when
+     * the device is not yet configured. For other
+     * Endpoints the device must be configured.
+     * Firstly check if addressed ep is Control Endpoint.
+     * If no then the device must be in Configured state
+     * to accept the request.
+     */
+    if (((ep & 0x7f) == 0) || is_device_configured()) {
+      /* bit 0 - Endpoint halted or not */
+      usbd_ep_is_stalled(ep, (uint8_t *)&usbd_core_cfg.remote_wakeup);
+      *data = (uint8_t *)&usbd_core_cfg.remote_wakeup;
 
-    /* Check if request addresses valid Endpoint */
-    if (!is_ep_valid(ep)) {
-        return false;
+      *len = 2;
+      break;
     }
 
-    switch (setup->bRequest) {
-        case USB_REQUEST_GET_STATUS:
-
-            /** This request is valid for Control Endpoints when
-             * the device is not yet configured. For other
-             * Endpoints the device must be configured.
-             * Firstly check if addressed ep is Control Endpoint.
-             * If no then the device must be in Configured state
-             * to accept the request.
-             */
-            if (((ep & 0x7f) == 0) || is_device_configured()) {
-                /* bit 0 - Endpoint halted or not */
-                usbd_ep_is_stalled(ep, (uint8_t *)&usbd_core_cfg.remote_wakeup);
-                *data = (uint8_t *)&usbd_core_cfg.remote_wakeup;
-
-                *len = 2;
-                break;
-            }
-
-            return false;
-
-        case USB_REQUEST_CLEAR_FEATURE:
-            if (setup->wValue == USB_FEATURE_ENDPOINT_STALL) {
-                /** This request is valid for Control Endpoints when
-                 * the device is not yet configured. For other
-                 * Endpoints the device must be configured.
-                 * Firstly check if addressed ep is Control Endpoint.
-                 * If no then the device must be in Configured state
-                 * to accept the request.
-                 */
-                if (((ep & 0x7f) == 0) || is_device_configured()) {
-                    USBD_LOG_ERR("ep:%x clear halt\r\n", ep);
-                    usbd_ep_clear_stall(ep);
-                    usbd_event_notify_handler(USB_EVENT_CLEAR_HALT, NULL);
-                    break;
-                }
-            }
-
-            /* only ENDPOINT_HALT defined for endpoints */
-            return false;
-
-        case USB_REQUEST_SET_FEATURE:
-            if (setup->wValue == USB_FEATURE_ENDPOINT_STALL) {
-                /** This request is valid for Control Endpoints when
-                 * the device is not yet configured. For other
-                 * Endpoints the device must be configured.
-                 * Firstly check if addressed ep is Control Endpoint.
-                 * If no then the device must be in Configured state
-                 * to accept the request.
-                 */
-                if (((ep & 0x7f) == 0) || is_device_configured()) {
-                    /* set HALT by stalling */
-                    USBD_LOG_ERR("ep:%x set halt\r\n", ep);
-                    usbd_ep_set_stall(ep);
-                    usbd_event_notify_handler(USB_EVENT_SET_HALT, NULL);
-                    break;
-                }
-            }
-
-            /* only ENDPOINT_HALT defined for endpoints */
-            return false;
-
-        case USB_REQUEST_SYNCH_FRAME:
-
-            /* For Synch Frame request the device must be configured */
-            if (is_device_configured()) {
-                /* Not supported, return false anyway */
-                USBD_LOG_DBG("ep req 0x%02x not implemented\r\n", setup->bRequest);
-            }
-
-            return false;
-
-        default:
-            USBD_LOG_ERR("Illegal ep req 0x%02x\r\n", setup->bRequest);
-            return false;
+    return false;
+
+  case USB_REQUEST_CLEAR_FEATURE:
+    if (setup->wValue == USB_FEATURE_ENDPOINT_STALL) {
+      /** This request is valid for Control Endpoints when
+       * the device is not yet configured. For other
+       * Endpoints the device must be configured.
+       * Firstly check if addressed ep is Control Endpoint.
+       * If no then the device must be in Configured state
+       * to accept the request.
+       */
+      if (((ep & 0x7f) == 0) || is_device_configured()) {
+        USBD_LOG_ERR("ep:%x clear halt\r\n", ep);
+        usbd_ep_clear_stall(ep);
+        usbd_event_notify_handler(USB_EVENT_CLEAR_HALT, NULL);
+        break;
+      }
     }
 
-    return true;
+    /* only ENDPOINT_HALT defined for endpoints */
+    return false;
+
+  case USB_REQUEST_SET_FEATURE:
+    if (setup->wValue == USB_FEATURE_ENDPOINT_STALL) {
+      /** This request is valid for Control Endpoints when
+       * the device is not yet configured. For other
+       * Endpoints the device must be configured.
+       * Firstly check if addressed ep is Control Endpoint.
+       * If no then the device must be in Configured state
+       * to accept the request.
+       */
+      if (((ep & 0x7f) == 0) || is_device_configured()) {
+        /* set HALT by stalling */
+        USBD_LOG_ERR("ep:%x set halt\r\n", ep);
+        usbd_ep_set_stall(ep);
+        usbd_event_notify_handler(USB_EVENT_SET_HALT, NULL);
+        break;
+      }
+    }
+
+    /* only ENDPOINT_HALT defined for endpoints */
+    return false;
+
+  case USB_REQUEST_SYNCH_FRAME:
+
+    /* For Synch Frame request the device must be configured */
+    if (is_device_configured()) {
+      /* Not supported, return false anyway */
+      USBD_LOG_DBG("ep req 0x%02x not implemented\r\n", setup->bRequest);
+    }
+
+    return false;
+
+  default:
+    USBD_LOG_ERR("Illegal ep req 0x%02x\r\n", setup->bRequest);
+    return false;
+  }
+
+  return true;
 }
 
 /**
@@ -735,37 +704,36 @@ static bool usbd_std_endpoint_req_handler(struct usb_setup_packet *setup, uint8_
  *
  * @return true if the request was handled successfully
  */
-static int usbd_standard_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    int rc = 0;
+static int usbd_standard_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) {
+  int rc = 0;
 
-    switch (setup->bmRequestType_b.Recipient) {
-        case USB_REQUEST_TO_DEVICE:
-            if (usbd_std_device_req_handler(setup, data, len) == false) {
-                rc = -1;
-            }
+  switch (setup->bmRequestType_b.Recipient) {
+  case USB_REQUEST_TO_DEVICE:
+    if (usbd_std_device_req_handler(setup, data, len) == false) {
+      rc = -1;
+    }
 
-            break;
+    break;
 
-        case USB_REQUEST_TO_INTERFACE:
-            if (usbd_std_interface_req_handler(setup, data, len) == false) {
-                rc = -1;
-            }
+  case USB_REQUEST_TO_INTERFACE:
+    if (usbd_std_interface_req_handler(setup, data, len) == false) {
+      rc = -1;
+    }
 
-            break;
+    break;
 
-        case USB_REQUEST_TO_ENDPOINT:
-            if (usbd_std_endpoint_req_handler(setup, data, len) == false) {
-                rc = -1;
-            }
+  case USB_REQUEST_TO_ENDPOINT:
+    if (usbd_std_endpoint_req_handler(setup, data, len) == false) {
+      rc = -1;
+    }
 
-            break;
+    break;
 
-        default:
-            rc = -1;
-    }
+  default:
+    rc = -1;
+  }
 
-    return rc;
+  return rc;
 }
 
 /*
@@ -779,118 +747,109 @@ static int usbd_standard_request_handler(struct usb_setup_packet *setup, uint8_t
  * when legacy initialization throgh the usb_set_config() and
  * usb_enable() is no longer needed.
  */
-static int usbd_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("bRequest 0x%02x, wIndex 0x%04x\r\n", setup->bRequest, setup->wIndex);
+static int usbd_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) {
+  USBD_LOG_DBG("bRequest 0x%02x, wIndex 0x%04x\r\n", setup->bRequest, setup->wIndex);
 
-    if (setup->bmRequestType_b.Recipient != USB_REQUEST_TO_INTERFACE) {
-        return -1;
-    }
+  if (setup->bmRequestType_b.Recipient != USB_REQUEST_TO_INTERFACE) {
+    return -1;
+  }
 
-    usb_slist_t *i, *j;
-    usb_slist_for_each(i, &usbd_class_head)
-    {
-        usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
+  usb_slist_t *i, *j;
+  usb_slist_for_each(i, &usbd_class_head) {
+    usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
 
-        usb_slist_for_each(j, &class->intf_list)
-        {
-            usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
+    usb_slist_for_each(j, &class->intf_list) {
+      usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
 
-            if (intf->class_handler && (intf->intf_num == (setup->wIndex & 0xFF))) {
-                return intf->class_handler(setup, data, len);
-            }
-        }
+      if (intf->class_handler && (intf->intf_num == (setup->wIndex & 0xFF))) {
+        return intf->class_handler(setup, data, len);
+      }
     }
-    return -1;
+  }
+  return -1;
 }
 
-static int usbd_vendor_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("bRequest 0x%02x, wValue0x%04x, wIndex 0x%04x\r\n", setup->bRequest, setup->wValue, setup->wIndex);
-
-    // if(setup->bmRequestType_b.Recipient != USB_REQUEST_TO_DEVICE)
-    // {
-    //     return -1;
-    // }
-
-    if (msosv1_desc) {
-        if (setup->bRequest == msosv1_desc->vendor_code) {
-            switch (setup->wIndex) {
-                case 0x04:
-                    USBD_LOG_INFO("get Compat ID\r\n");
-                    *data = (uint8_t *)msosv1_desc->compat_id;
-                    *len = msosv1_desc->compat_id_len;
-
-                    return 0;
-                case 0x05:
-                    USBD_LOG_INFO("get Compat id properties\r\n");
-                    *data = (uint8_t *)msosv1_desc->comp_id_property;
-                    *len = msosv1_desc->comp_id_property_len;
-
-                    return 0;
-                default:
-                    USBD_LOG_ERR("unknown vendor code\r\n");
-                    return -1;
-            }
-        }
-    } else if (msosv2_desc) {
-        if (setup->bRequest == msosv2_desc->vendor_code) {
-            switch (setup->wIndex) {
-                case WINUSB_REQUEST_GET_DESCRIPTOR_SET:
-                    USBD_LOG_INFO("GET MS OS 2.0 Descriptor\r\n");
-                    *data = (uint8_t *)msosv2_desc->compat_id;
-                    *len = msosv2_desc->compat_id_len;
-                    return 0;
-                default:
-                    USBD_LOG_ERR("unknown vendor code\r\n");
-                    return -1;
-            }
-        }
+static int usbd_vendor_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) {
+  USBD_LOG_DBG("bRequest 0x%02x, wValue0x%04x, wIndex 0x%04x\r\n", setup->bRequest, setup->wValue, setup->wIndex);
+
+  // if(setup->bmRequestType_b.Recipient != USB_REQUEST_TO_DEVICE)
+  // {
+  //     return -1;
+  // }
+
+  if (msosv1_desc) {
+    if (setup->bRequest == msosv1_desc->vendor_code) {
+      switch (setup->wIndex) {
+      case 0x04:
+        USBD_LOG_INFO("get Compat ID\r\n");
+        *data = (uint8_t *)msosv1_desc->compat_id;
+        *len  = msosv1_desc->compat_id_len;
+
+        return 0;
+      case 0x05:
+        USBD_LOG_INFO("get Compat id properties\r\n");
+        *data = (uint8_t *)msosv1_desc->comp_id_property;
+        *len  = msosv1_desc->comp_id_property_len;
+
+        return 0;
+      default:
+        USBD_LOG_ERR("unknown vendor code\r\n");
+        return -1;
+      }
+    }
+  } else if (msosv2_desc) {
+    if (setup->bRequest == msosv2_desc->vendor_code) {
+      switch (setup->wIndex) {
+      case WINUSB_REQUEST_GET_DESCRIPTOR_SET:
+        USBD_LOG_INFO("GET MS OS 2.0 Descriptor\r\n");
+        *data = (uint8_t *)msosv2_desc->compat_id;
+        *len  = msosv2_desc->compat_id_len;
+        return 0;
+      default:
+        USBD_LOG_ERR("unknown vendor code\r\n");
+        return -1;
+      }
     }
+  }
 
-    usb_slist_t *i, *j;
+  usb_slist_t *i, *j;
 
-    usb_slist_for_each(i, &usbd_class_head)
-    {
-        usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
+  usb_slist_for_each(i, &usbd_class_head) {
+    usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
 
-        usb_slist_for_each(j, &class->intf_list)
-        {
-            usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
+    usb_slist_for_each(j, &class->intf_list) {
+      usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
 
-            if (intf->vendor_handler && !intf->vendor_handler(setup, data, len)) {
-                return 0;
-            }
-        }
+      if (intf->vendor_handler && !intf->vendor_handler(setup, data, len)) {
+        return 0;
+      }
     }
+  }
 
-    return -1;
+  return -1;
 }
 
-static int usbd_custom_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("bRequest 0x%02x, wIndex 0x%04x\r\n", setup->bRequest, setup->wIndex);
+static int usbd_custom_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) {
+  USBD_LOG_DBG("bRequest 0x%02x, wIndex 0x%04x\r\n", setup->bRequest, setup->wIndex);
 
-    if (setup->bmRequestType_b.Recipient != USB_REQUEST_TO_INTERFACE) {
-        return -1;
-    }
+  if (setup->bmRequestType_b.Recipient != USB_REQUEST_TO_INTERFACE) {
+    return -1;
+  }
 
-    usb_slist_t *i, *j;
-    usb_slist_for_each(i, &usbd_class_head)
-    {
-        usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
+  usb_slist_t *i, *j;
+  usb_slist_for_each(i, &usbd_class_head) {
+    usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
 
-        usb_slist_for_each(j, &class->intf_list)
-        {
-            usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
+    usb_slist_for_each(j, &class->intf_list) {
+      usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
 
-            if (intf->custom_handler && (intf->intf_num == (setup->wIndex & 0xFF))) {
-                return intf->custom_handler(setup, data, len);
-            }
-        }
+      if (intf->custom_handler && (intf->intf_num == (setup->wIndex & 0xFF))) {
+        return intf->custom_handler(setup, data, len);
+      }
     }
+  }
 
-    return -1;
+  return -1;
 }
 
 /**
@@ -907,363 +866,319 @@ static int usbd_custom_request_handler(struct usb_setup_packet *setup, uint8_t *
  *
  * @return true if the request was handles successfully
  */
-static bool usbd_setup_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    uint8_t type = setup->bmRequestType_b.Type;
+static bool usbd_setup_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) {
+  uint8_t type = setup->bmRequestType_b.Type;
 
-    if (type == USB_REQUEST_STANDARD) {
-        if (!usbd_custom_request_handler(setup, data, len)) {
-            return true;
-        }
+  if (type == USB_REQUEST_STANDARD) {
+    if (!usbd_custom_request_handler(setup, data, len)) {
+      return true;
+    }
 
-        if (usbd_standard_request_handler(setup, data, len) < 0) {
-            USBD_LOG_ERR("Handler Error %d\r\n", type);
-            usbd_print_setup(setup);
-            return false;
-        }
-    } else if (type == USB_REQUEST_CLASS) {
-        if (usbd_class_request_handler(setup, data, len) < 0) {
-            USBD_LOG_ERR("Handler Error %d\r\n", type);
-            usbd_print_setup(setup);
-            return false;
-        }
-    } else if (type == USB_REQUEST_VENDOR) {
-        if (usbd_vendor_request_handler(setup, data, len) < 0) {
-            USBD_LOG_ERR("Handler Error %d\r\n", type);
-            usbd_print_setup(setup);
-            return false;
-        }
-    } else {
-        return false;
+    if (usbd_standard_request_handler(setup, data, len) < 0) {
+      USBD_LOG_ERR("Handler Error %d\r\n", type);
+      usbd_print_setup(setup);
+      return false;
+    }
+  } else if (type == USB_REQUEST_CLASS) {
+    if (usbd_class_request_handler(setup, data, len) < 0) {
+      USBD_LOG_ERR("Handler Error %d\r\n", type);
+      usbd_print_setup(setup);
+      return false;
     }
+  } else if (type == USB_REQUEST_VENDOR) {
+    if (usbd_vendor_request_handler(setup, data, len) < 0) {
+      USBD_LOG_ERR("Handler Error %d\r\n", type);
+      usbd_print_setup(setup);
+      return false;
+    }
+  } else {
+    return false;
+  }
 
-    return true;
+  return true;
 }
 /**
  * @brief send data or status to host
  *
  * @return N/A
  */
-static void usbd_send_to_host(uint16_t len)
-{
-    uint32_t chunk = 0U;
-
-    if (usbd_core_cfg.zlp_flag == false) {
-        chunk = usbd_core_cfg.ep0_data_buf_residue;
+static void usbd_send_to_host(uint16_t len) {
+  uint32_t chunk = 0U;
 
-        if (usbd_ep_write(USB_CONTROL_IN_EP0, usbd_core_cfg.ep0_data_buf, usbd_core_cfg.ep0_data_buf_residue, &chunk) < 0) {
-            USBD_LOG_ERR("USB write data failed\r\n");
-            return;
-        }
+  if (usbd_core_cfg.zlp_flag == false) {
+    chunk = usbd_core_cfg.ep0_data_buf_residue;
 
-        usbd_core_cfg.ep0_data_buf += chunk;
-        usbd_core_cfg.ep0_data_buf_residue -= chunk;
-
-        /*
-         * Set ZLP flag when host asks for a bigger length and the
-         * last chunk is wMaxPacketSize long, to indicate the last
-         * packet.
-         */
-        if ((!usbd_core_cfg.ep0_data_buf_residue) && (usbd_core_cfg.ep0_data_buf_len >= USB_CTRL_EP_MPS) && !(usbd_core_cfg.ep0_data_buf_len % USB_CTRL_EP_MPS)) {
-            /* Transfers a zero-length packet next*/
-            usbd_core_cfg.zlp_flag = true;
-        }
-    } else {
-        usbd_core_cfg.zlp_flag = false;
-        USBD_LOG_DBG("send zlp\r\n");
-        if (usbd_ep_write(USB_CONTROL_IN_EP0, NULL, 0, NULL) < 0) {
-            USBD_LOG_ERR("USB write zlp failed\r\n");
-            return;
-        }
+    if (usbd_ep_write(USB_CONTROL_IN_EP0, usbd_core_cfg.ep0_data_buf, usbd_core_cfg.ep0_data_buf_residue, &chunk) < 0) {
+      USBD_LOG_ERR("USB write data failed\r\n");
+      return;
     }
-}
 
-static void usbd_ep0_setup_handler(void)
-{
-    struct usb_setup_packet *setup = &usbd_core_cfg.setup;
+    usbd_core_cfg.ep0_data_buf += chunk;
+    usbd_core_cfg.ep0_data_buf_residue -= chunk;
 
     /*
-    * OUT transfer, Setup packet,
-    * reset request message state machine
-    */
-    if (usbd_ep_read(USB_CONTROL_OUT_EP0, (uint8_t *)setup,
-                     sizeof(struct usb_setup_packet), NULL) < 0) {
-        USBD_LOG_ERR("Read Setup Packet failed\r\n");
-        usbd_ep_set_stall(USB_CONTROL_IN_EP0);
-        return;
-    }
-
-    //usbd_print_setup(setup);
-
-    if (setup->wLength > USB_REQUEST_BUFFER_SIZE) {
-        if (setup->bmRequestType_b.Dir != USB_REQUEST_DEVICE_TO_HOST) {
-            USBD_LOG_ERR("Request buffer too small\r\n");
-            usbd_ep_set_stall(USB_CONTROL_IN_EP0);
-            return;
-        }
+     * Set ZLP flag when host asks for a bigger length and the
+     * last chunk is wMaxPacketSize long, to indicate the last
+     * packet.
+     */
+    if ((!usbd_core_cfg.ep0_data_buf_residue) && (usbd_core_cfg.ep0_data_buf_len >= USB_CTRL_EP_MPS) && !(usbd_core_cfg.ep0_data_buf_len % USB_CTRL_EP_MPS)) {
+      /* Transfers a zero-length packet next*/
+      usbd_core_cfg.zlp_flag = true;
     }
-
-    // usbd_core_cfg.ep0_data_buf = usbd_core_cfg.req_data;
-    usbd_core_cfg.ep0_data_buf_residue = setup->wLength;
-    usbd_core_cfg.ep0_data_buf_len = setup->wLength;
+  } else {
     usbd_core_cfg.zlp_flag = false;
-
-    /* this maybe set code in class request code  */
-    if (setup->wLength &&
-        setup->bmRequestType_b.Dir == USB_REQUEST_HOST_TO_DEVICE) {
-        USBD_LOG_DBG("prepare to out data\r\n");
-        return;
+    USBD_LOG_DBG("send zlp\r\n");
+    if (usbd_ep_write(USB_CONTROL_IN_EP0, NULL, 0, NULL) < 0) {
+      USBD_LOG_ERR("USB write zlp failed\r\n");
+      return;
     }
+  }
+}
 
-    /* Ask installed handler to process request */
-    if (!usbd_setup_request_handler(setup, &usbd_core_cfg.ep0_data_buf, &usbd_core_cfg.ep0_data_buf_len)) {
-        USBD_LOG_ERR("usbd_setup_request_handler failed\r\n");
-        usbd_ep_set_stall(USB_CONTROL_IN_EP0);
-        return;
+static void usbd_ep0_setup_handler(void) {
+  struct usb_setup_packet *setup = &usbd_core_cfg.setup;
+
+  /*
+   * OUT transfer, Setup packet,
+   * reset request message state machine
+   */
+  if (usbd_ep_read(USB_CONTROL_OUT_EP0, (uint8_t *)setup, sizeof(struct usb_setup_packet), NULL) < 0) {
+    USBD_LOG_ERR("Read Setup Packet failed\r\n");
+    usbd_ep_set_stall(USB_CONTROL_IN_EP0);
+    return;
+  }
+
+  // usbd_print_setup(setup);
+
+  if (setup->wLength > USB_REQUEST_BUFFER_SIZE) {
+    if (setup->bmRequestType_b.Dir != USB_REQUEST_DEVICE_TO_HOST) {
+      USBD_LOG_ERR("Request buffer too small\r\n");
+      usbd_ep_set_stall(USB_CONTROL_IN_EP0);
+      return;
     }
-
-    /* Send smallest of requested and offered length */
-    usbd_core_cfg.ep0_data_buf_residue = MIN(usbd_core_cfg.ep0_data_buf_len,
-                                             setup->wLength);
-    /*Send data or status to host*/
-    usbd_send_to_host(setup->wLength);
+  }
+
+  // usbd_core_cfg.ep0_data_buf = usbd_core_cfg.req_data;
+  usbd_core_cfg.ep0_data_buf_residue = setup->wLength;
+  usbd_core_cfg.ep0_data_buf_len     = setup->wLength;
+  usbd_core_cfg.zlp_flag             = false;
+
+  /* this maybe set code in class request code  */
+  if (setup->wLength && setup->bmRequestType_b.Dir == USB_REQUEST_HOST_TO_DEVICE) {
+    USBD_LOG_DBG("prepare to out data\r\n");
+    return;
+  }
+
+  /* Ask installed handler to process request */
+  if (!usbd_setup_request_handler(setup, &usbd_core_cfg.ep0_data_buf, &usbd_core_cfg.ep0_data_buf_len)) {
+    USBD_LOG_ERR("usbd_setup_request_handler failed\r\n");
+    usbd_ep_set_stall(USB_CONTROL_IN_EP0);
+    return;
+  }
+
+  /* Send smallest of requested and offered length */
+  usbd_core_cfg.ep0_data_buf_residue = MIN(usbd_core_cfg.ep0_data_buf_len, setup->wLength);
+  /*Send data or status to host*/
+  usbd_send_to_host(setup->wLength);
 }
 
-static void usbd_ep0_out_handler(void)
-{
-    uint32_t chunk = 0U;
-    struct usb_setup_packet *setup = &usbd_core_cfg.setup;
-
-    /* OUT transfer, status packets */
-    if (usbd_core_cfg.ep0_data_buf_residue == 0) {
-        /* absorb zero-length status message */
-        USBD_LOG_DBG("recv status\r\n");
-
-        if (usbd_ep_read(USB_CONTROL_OUT_EP0,
-                         NULL,
-                         0, NULL) < 0) {
-            USBD_LOG_ERR("Read DATA Packet failed\r\n");
-            usbd_ep_set_stall(USB_CONTROL_IN_EP0);
-        }
+static void usbd_ep0_out_handler(void) {
+  uint32_t                 chunk = 0U;
+  struct usb_setup_packet *setup = &usbd_core_cfg.setup;
 
-        return;
+  /* OUT transfer, status packets */
+  if (usbd_core_cfg.ep0_data_buf_residue == 0) {
+    /* absorb zero-length status message */
+    USBD_LOG_DBG("recv status\r\n");
+
+    if (usbd_ep_read(USB_CONTROL_OUT_EP0, NULL, 0, NULL) < 0) {
+      USBD_LOG_ERR("Read DATA Packet failed\r\n");
+      usbd_ep_set_stall(USB_CONTROL_IN_EP0);
     }
 
-    usbd_core_cfg.ep0_data_buf = usbd_core_cfg.req_data;
+    return;
+  }
 
-    /* OUT transfer, data packets */
-    if (usbd_ep_read(USB_CONTROL_OUT_EP0,
-                     usbd_core_cfg.ep0_data_buf,
-                     usbd_core_cfg.ep0_data_buf_residue, &chunk) < 0) {
-        USBD_LOG_ERR("Read DATA Packet failed\r\n");
-        usbd_ep_set_stall(USB_CONTROL_IN_EP0);
-        return;
-    }
+  usbd_core_cfg.ep0_data_buf = usbd_core_cfg.req_data;
 
-    usbd_core_cfg.ep0_data_buf += chunk;
-    usbd_core_cfg.ep0_data_buf_residue -= chunk;
+  /* OUT transfer, data packets */
+  if (usbd_ep_read(USB_CONTROL_OUT_EP0, usbd_core_cfg.ep0_data_buf, usbd_core_cfg.ep0_data_buf_residue, &chunk) < 0) {
+    USBD_LOG_ERR("Read DATA Packet failed\r\n");
+    usbd_ep_set_stall(USB_CONTROL_IN_EP0);
+    return;
+  }
 
-    if (usbd_core_cfg.ep0_data_buf_residue == 0) {
-        /* Received all, send data to handler */
-        usbd_core_cfg.ep0_data_buf = usbd_core_cfg.req_data;
+  usbd_core_cfg.ep0_data_buf += chunk;
+  usbd_core_cfg.ep0_data_buf_residue -= chunk;
 
-        if (!usbd_setup_request_handler(setup, &usbd_core_cfg.ep0_data_buf, &usbd_core_cfg.ep0_data_buf_len)) {
-            USBD_LOG_ERR("usbd_setup_request_handler1 failed\r\n");
-            usbd_ep_set_stall(USB_CONTROL_IN_EP0);
-            return;
-        }
+  if (usbd_core_cfg.ep0_data_buf_residue == 0) {
+    /* Received all, send data to handler */
+    usbd_core_cfg.ep0_data_buf = usbd_core_cfg.req_data;
 
-        /*Send status to host*/
-        usbd_send_to_host(setup->wLength);
-    } else {
-        USBD_LOG_ERR("ep0_data_buf_residue is not zero\r\n");
+    if (!usbd_setup_request_handler(setup, &usbd_core_cfg.ep0_data_buf, &usbd_core_cfg.ep0_data_buf_len)) {
+      USBD_LOG_ERR("usbd_setup_request_handler1 failed\r\n");
+      usbd_ep_set_stall(USB_CONTROL_IN_EP0);
+      return;
     }
+
+    /*Send status to host*/
+    usbd_send_to_host(setup->wLength);
+  } else {
+    USBD_LOG_ERR("ep0_data_buf_residue is not zero\r\n");
+  }
 }
 
-static void usbd_ep0_in_handler(void)
-{
-    struct usb_setup_packet *setup = &usbd_core_cfg.setup;
+static void usbd_ep0_in_handler(void) {
+  struct usb_setup_packet *setup = &usbd_core_cfg.setup;
 
-    /* Send more data if available */
-    if (usbd_core_cfg.ep0_data_buf_residue != 0 || usbd_core_cfg.zlp_flag == true) {
-        usbd_send_to_host(setup->wLength);
-    } else {
-        /*ep0 tx has completed,and no data to send,so do nothing*/
-    }
+  /* Send more data if available */
+  if (usbd_core_cfg.ep0_data_buf_residue != 0 || usbd_core_cfg.zlp_flag == true) {
+    usbd_send_to_host(setup->wLength);
+  } else {
+    /*ep0 tx has completed,and no data to send,so do nothing*/
+  }
 }
 
-static void usbd_ep_out_handler(uint8_t ep)
-{
+static void usbd_ep_out_handler(uint8_t ep) {
 #if USBD_EP_CALLBACK_SEARCH_METHOD == 0
-    usb_slist_t *i, *j, *k;
-    usb_slist_for_each(i, &usbd_class_head)
-    {
-        usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
-
-        usb_slist_for_each(j, &class->intf_list)
-        {
-            usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
-
-            usb_slist_for_each(k, &intf->ep_list)
-            {
-                usbd_endpoint_t *ept = usb_slist_entry(k, struct usbd_endpoint, list);
-
-                if ((ept->ep_addr == ep) && ept->ep_cb) {
-                    ept->ep_cb(ep);
-                }
-            }
+  usb_slist_t *i, *j, *k;
+  usb_slist_for_each(i, &usbd_class_head) {
+    usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
+
+    usb_slist_for_each(j, &class->intf_list) {
+      usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
+
+      usb_slist_for_each(k, &intf->ep_list) {
+        usbd_endpoint_t *ept = usb_slist_entry(k, struct usbd_endpoint, list);
+
+        if ((ept->ep_addr == ep) && ept->ep_cb) {
+          ept->ep_cb(ep);
         }
+      }
     }
+  }
 #else
 
-    if (usbd_core_cfg.out_ep_cb[ep & 0x7f]) {
-        usbd_core_cfg.out_ep_cb[ep & 0x7f](ep);
-    }
+  if (usbd_core_cfg.out_ep_cb[ep & 0x7f]) {
+    usbd_core_cfg.out_ep_cb[ep & 0x7f](ep);
+  }
 
 #endif
 }
 
-static void usbd_ep_in_handler(uint8_t ep)
-{
+static void usbd_ep_in_handler(uint8_t ep) {
 #if USBD_EP_CALLBACK_SEARCH_METHOD == 0
-    usb_slist_t *i, *j, *k;
-    usb_slist_for_each(i, &usbd_class_head)
-    {
-        usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
-
-        usb_slist_for_each(j, &class->intf_list)
-        {
-            usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
-
-            usb_slist_for_each(k, &intf->ep_list)
-            {
-                usbd_endpoint_t *ept = usb_slist_entry(k, struct usbd_endpoint, list);
-
-                if ((ept->ep_addr == ep) && ept->ep_cb) {
-                    ept->ep_cb(ep);
-                }
-            }
+  usb_slist_t *i, *j, *k;
+  usb_slist_for_each(i, &usbd_class_head) {
+    usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
+
+    usb_slist_for_each(j, &class->intf_list) {
+      usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
+
+      usb_slist_for_each(k, &intf->ep_list) {
+        usbd_endpoint_t *ept = usb_slist_entry(k, struct usbd_endpoint, list);
+
+        if ((ept->ep_addr == ep) && ept->ep_cb) {
+          ept->ep_cb(ep);
         }
+      }
     }
+  }
 #else
 
-    if (usbd_core_cfg.in_ep_cb[ep & 0x7f]) {
-        usbd_core_cfg.in_ep_cb[ep & 0x7f](ep);
-    }
+  if (usbd_core_cfg.in_ep_cb[ep & 0x7f]) {
+    usbd_core_cfg.in_ep_cb[ep & 0x7f](ep);
+  }
 
 #endif
 }
 
-static void usbd_class_event_notify_handler(uint8_t event, void *arg)
-{
-    usb_slist_t *i, *j;
-    usb_slist_for_each(i, &usbd_class_head)
-    {
-        usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
+static void usbd_class_event_notify_handler(uint8_t event, void *arg) {
+  usb_slist_t *i, *j;
+  usb_slist_for_each(i, &usbd_class_head) {
+    usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
 
-        usb_slist_for_each(j, &class->intf_list)
-        {
-            usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
+    usb_slist_for_each(j, &class->intf_list) {
+      usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
 
-            if (intf->notify_handler) {
-                intf->notify_handler(event, arg);
-            }
-        }
+      if (intf->notify_handler) {
+        intf->notify_handler(event, arg);
+      }
     }
+  }
 }
 
-void usbd_event_notify_handler(uint8_t event, void *arg)
-{
-    switch (event) {
-        case USB_EVENT_RESET:
-            usbd_set_address(0);
+void usbd_event_notify_handler(uint8_t event, void *arg) {
+  switch (event) {
+  case USB_EVENT_RESET:
+    usbd_set_address(0);
 #if USBD_EP_CALLBACK_SEARCH_METHOD == 1
-            usbd_ep_callback_register();
+    usbd_ep_callback_register();
 #endif
 
-        case USB_EVENT_ERROR:
-        case USB_EVENT_SOF:
-        case USB_EVENT_CONNECTED:
-        case USB_EVENT_CONFIGURED:
-        case USB_EVENT_SUSPEND:
-        case USB_EVENT_DISCONNECTED:
-        case USB_EVENT_RESUME:
-        case USB_EVENT_SET_INTERFACE:
-        case USB_EVENT_SET_REMOTE_WAKEUP:
-        case USB_EVENT_CLEAR_REMOTE_WAKEUP:
-        case USB_EVENT_SET_HALT:
-        case USB_EVENT_CLEAR_HALT:
-            usbd_class_event_notify_handler(event, arg);
-            break;
-
-        case USB_EVENT_SETUP_NOTIFY:
-            usbd_ep0_setup_handler();
-            break;
-
-        case USB_EVENT_EP0_IN_NOTIFY:
-            usbd_ep0_in_handler();
-            break;
-
-        case USB_EVENT_EP0_OUT_NOTIFY:
-            usbd_ep0_out_handler();
-            break;
-
-        case USB_EVENT_EP_IN_NOTIFY:
-            usbd_ep_in_handler((uint32_t)arg);
-            break;
-
-        case USB_EVENT_EP_OUT_NOTIFY:
-            usbd_ep_out_handler((uint32_t)arg);
-            break;
-
-        default:
-            USBD_LOG_ERR("USB unknown event: %d\r\n", event);
-            break;
-    }
+  case USB_EVENT_ERROR:
+  case USB_EVENT_SOF:
+  case USB_EVENT_CONNECTED:
+  case USB_EVENT_CONFIGURED:
+  case USB_EVENT_SUSPEND:
+  case USB_EVENT_DISCONNECTED:
+  case USB_EVENT_RESUME:
+  case USB_EVENT_SET_INTERFACE:
+  case USB_EVENT_SET_REMOTE_WAKEUP:
+  case USB_EVENT_CLEAR_REMOTE_WAKEUP:
+  case USB_EVENT_SET_HALT:
+  case USB_EVENT_CLEAR_HALT:
+    usbd_class_event_notify_handler(event, arg);
+    break;
+
+  case USB_EVENT_SETUP_NOTIFY:
+    usbd_ep0_setup_handler();
+    break;
+
+  case USB_EVENT_EP0_IN_NOTIFY:
+    usbd_ep0_in_handler();
+    break;
+
+  case USB_EVENT_EP0_OUT_NOTIFY:
+    usbd_ep0_out_handler();
+    break;
+
+  case USB_EVENT_EP_IN_NOTIFY:
+    usbd_ep_in_handler((uint32_t)arg);
+    break;
+
+  case USB_EVENT_EP_OUT_NOTIFY:
+    usbd_ep_out_handler((uint32_t)arg);
+    break;
+
+  default:
+    USBD_LOG_ERR("USB unknown event: %d\r\n", event);
+    break;
+  }
 }
 
-void usbd_desc_register(const uint8_t *desc)
-{
-    usbd_core_cfg.descriptors = desc;
-}
+void usbd_desc_register(const uint8_t *desc) { usbd_core_cfg.descriptors = desc; }
 /* Register MS OS Descriptors version 1 */
-void usbd_msosv1_desc_register(struct usb_msosv1_descriptor *desc)
-{
-    msosv1_desc = desc;
-}
+void usbd_msosv1_desc_register(struct usb_msosv1_descriptor *desc) { msosv1_desc = desc; }
 
 /* Register MS OS Descriptors version 2 */
-void usbd_msosv2_desc_register(struct usb_msosv2_descriptor *desc)
-{
-    msosv2_desc = desc;
-}
+void usbd_msosv2_desc_register(struct usb_msosv2_descriptor *desc) { msosv2_desc = desc; }
 
-void usbd_bos_desc_register(struct usb_bos_descriptor *desc)
-{
-    bos_desc = desc;
-}
+void usbd_bos_desc_register(struct usb_bos_descriptor *desc) { bos_desc = desc; }
 
-void usbd_class_register(usbd_class_t *class)
-{
-    usb_slist_add_tail(&usbd_class_head, &class->list);
-    usb_slist_init(&class->intf_list);
+void usbd_class_register(usbd_class_t *class) {
+  usb_slist_add_tail(&usbd_class_head, &class->list);
+  usb_slist_init(&class->intf_list);
 }
 
-void usbd_class_add_interface(usbd_class_t *class, usbd_interface_t *intf)
-{
-    static uint8_t intf_offset = 0;
-    intf->intf_num = intf_offset;
-    usb_slist_add_tail(&class->intf_list, &intf->list);
-    usb_slist_init(&intf->ep_list);
-    intf_offset++;
+void usbd_class_add_interface(usbd_class_t *class, usbd_interface_t *intf) {
+  static uint8_t intf_offset = 0;
+  intf->intf_num             = intf_offset;
+  usb_slist_add_tail(&class->intf_list, &intf->list);
+  usb_slist_init(&intf->ep_list);
+  intf_offset++;
 }
 
-void usbd_interface_add_endpoint(usbd_interface_t *intf, usbd_endpoint_t *ep)
-{
-    usb_slist_add_tail(&intf->ep_list, &ep->list);
-}
+void usbd_interface_add_endpoint(usbd_interface_t *intf, usbd_endpoint_t *ep) { usb_slist_add_tail(&intf->ep_list, &ep->list); }
 
-bool usb_device_is_configured(void)
-{
-    return usbd_core_cfg.configured;
-}
+bool usb_device_is_configured(void) { return usbd_core_cfg.configured; }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_boot2.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_boot2.c
index 0767d52154..c906b6249b 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_boot2.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_boot2.c
@@ -1,13 +1,13 @@
 #include "hal_boot2.h"
-#include "hal_flash.h"
 #include "bl702_ef_ctrl.h"
-#include "bl702_hbn.h"
 #include "bl702_glb.h"
+#include "bl702_hbn.h"
 #include "bl702_xip_sflash.h"
-#include "tzc_sec_reg.h"
+#include "hal_flash.h"
 #include "hal_gpio.h"
-#include "softcrc.h"
 #include "hal_sec_hash.h"
+#include "softcrc.h"
+#include "tzc_sec_reg.h"
 
 /**
  * @brief boot2 custom
@@ -15,10 +15,7 @@
  * @param None
  * @return uint32
  */
-uint32_t hal_boot2_custom(void)
-{
-    return 0;
-}
+uint32_t hal_boot2_custom(void) { return 0; }
 
 /**
  * @brief get efuse Boot2 config
@@ -28,56 +25,49 @@ uint32_t hal_boot2_custom(void)
  * @param
  * @return None
  */
-void hal_boot2_get_efuse_cfg(boot2_efuse_hw_config *efuse_cfg)
-{
-    uint32_t tmp;
-    uint32_t rootClk;
-    uint8_t hdiv = 0, bdiv = 0;
-
-    /* save bclk fclk div and root clock sel */
-    bdiv = GLB_Get_BCLK_Div();
-    hdiv = GLB_Get_HCLK_Div();
-    rootClk = BL_RD_REG(HBN_BASE, HBN_GLB);
-
-    /* change root clock to rc32m for efuse operation */
-    HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_RC32M);
-
-    /* Get sign and aes type*/
-    EF_Ctrl_Read_Secure_Boot((EF_Ctrl_Sign_Type *)efuse_cfg->sign, (EF_Ctrl_SF_AES_Type *)efuse_cfg->encrypted);
-    /* Get hash:aes key slot 0 and slot1*/
-    EF_Ctrl_Read_AES_Key(0, (uint32_t *)efuse_cfg->pk_hash_cpu0, 8);
-    EF_Ctrl_Read_Chip_ID(efuse_cfg->chip_id);
-    /* Get HBN check sign config */
-    EF_Ctrl_Read_Sw_Usage(0, &tmp);
-    efuse_cfg->hbn_check_sign = (tmp >> 22) & 0x01;
-
-    /* restore bclk fclk div and root clock sel */
-    GLB_Set_System_CLK_Div(hdiv, bdiv);
-    BL_WR_REG(HBN_BASE, HBN_GLB, rootClk);
-    __NOP();
-    __NOP();
-    __NOP();
-    __NOP();
+void hal_boot2_get_efuse_cfg(boot2_efuse_hw_config *efuse_cfg) {
+  uint32_t tmp;
+  uint32_t rootClk;
+  uint8_t  hdiv = 0, bdiv = 0;
+
+  /* save bclk fclk div and root clock sel */
+  bdiv    = GLB_Get_BCLK_Div();
+  hdiv    = GLB_Get_HCLK_Div();
+  rootClk = BL_RD_REG(HBN_BASE, HBN_GLB);
+
+  /* change root clock to rc32m for efuse operation */
+  HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_RC32M);
+
+  /* Get sign and aes type*/
+  EF_Ctrl_Read_Secure_Boot((EF_Ctrl_Sign_Type *)efuse_cfg->sign, (EF_Ctrl_SF_AES_Type *)efuse_cfg->encrypted);
+  /* Get hash:aes key slot 0 and slot1*/
+  EF_Ctrl_Read_AES_Key(0, (uint32_t *)efuse_cfg->pk_hash_cpu0, 8);
+  EF_Ctrl_Read_Chip_ID(efuse_cfg->chip_id);
+  /* Get HBN check sign config */
+  EF_Ctrl_Read_Sw_Usage(0, &tmp);
+  efuse_cfg->hbn_check_sign = (tmp >> 22) & 0x01;
+
+  /* restore bclk fclk div and root clock sel */
+  GLB_Set_System_CLK_Div(hdiv, bdiv);
+  BL_WR_REG(HBN_BASE, HBN_GLB, rootClk);
+  __NOP();
+  __NOP();
+  __NOP();
+  __NOP();
 }
 /**
  * @brief reset sec eng clock
  *
  * @return
  */
-void hal_boot2_reset_sec_eng(void)
-{
-    GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_SEC);
-}
+void hal_boot2_reset_sec_eng(void) { GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_SEC); }
 
 /**
  * @brief system soft reset
  *
  * @return
  */
-void hal_boot2_sw_system_reset(void)
-{
-    GLB_SW_System_Reset();
-}
+void hal_boot2_sw_system_reset(void) { GLB_SW_System_Reset(); }
 
 /**
  * @brief
@@ -87,10 +77,7 @@ void hal_boot2_sw_system_reset(void)
  * @param
  * @return
  */
-void hal_boot2_set_psmode_status(uint32_t flag)
-{
-    HBN_Set_Status_Flag(flag);
-}
+void hal_boot2_set_psmode_status(uint32_t flag) { HBN_Set_Status_Flag(flag); }
 
 /**
  * @brief
@@ -100,10 +87,7 @@ void hal_boot2_set_psmode_status(uint32_t flag)
  * @param
  * @return flag
  */
-uint32_t hal_boot2_get_psmode_status(void)
-{
-    return HBN_Get_Status_Flag();
-}
+uint32_t hal_boot2_get_psmode_status(void) { return HBN_Get_Status_Flag(); }
 
 /**
  * @brief
@@ -113,10 +97,7 @@ uint32_t hal_boot2_get_psmode_status(void)
  * @param
  * @return user define flag
  */
-uint32_t hal_boot2_get_user_fw(void)
-{
-    return BL_RD_WORD(HBN_BASE + HBN_RSV0_OFFSET);
-}
+uint32_t hal_boot2_get_user_fw(void) { return BL_RD_WORD(HBN_BASE + HBN_RSV0_OFFSET); }
 
 /**
  * @brief clr user define flag
@@ -126,10 +107,9 @@ uint32_t hal_boot2_get_user_fw(void)
  * @param
  * @return
  */
-void hal_boot2_clr_user_fw(void)
-{
-    uint32_t *p = (uint32_t *)(HBN_BASE + HBN_RSV0_OFFSET);
-    *p = 0;
+void hal_boot2_clr_user_fw(void) {
+  uint32_t *p = (uint32_t *)(HBN_BASE + HBN_RSV0_OFFSET);
+  *p          = 0;
 }
 
 /**
@@ -137,15 +117,14 @@ void hal_boot2_clr_user_fw(void)
  *
  * @return
  */
-void ATTR_TCM_SECTION hal_boot2_sboot_finish(void)
-{
-    uint32_t tmp_val;
+void ATTR_TCM_SECTION hal_boot2_sboot_finish(void) {
+  uint32_t tmp_val;
 
-    tmp_val = BL_RD_REG(TZC_SEC_BASE, TZC_SEC_TZC_ROM_CTRL);
+  tmp_val = BL_RD_REG(TZC_SEC_BASE, TZC_SEC_TZC_ROM_CTRL);
 
-    tmp_val = BL_SET_REG_BITS_VAL(tmp_val, TZC_SEC_TZC_SBOOT_DONE, 0xf);
+  tmp_val = BL_SET_REG_BITS_VAL(tmp_val, TZC_SEC_TZC_SBOOT_DONE, 0xf);
 
-    BL_WR_REG(TZC_SEC_BASE, TZC_SEC_TZC_ROM_CTRL, tmp_val);
+  BL_WR_REG(TZC_SEC_BASE, TZC_SEC_TZC_ROM_CTRL, tmp_val);
 }
 
 /**
@@ -153,14 +132,13 @@ void ATTR_TCM_SECTION hal_boot2_sboot_finish(void)
  *
  * @return
  */
-void hal_boot2_uart_gpio_init(void)
-{
-    GLB_GPIO_Type gpios[] = { GPIO_PIN_14, GPIO_PIN_15 };
+void hal_boot2_uart_gpio_init(void) {
+  GLB_GPIO_Type gpios[] = {GPIO_PIN_14, GPIO_PIN_15};
 
-    GLB_GPIO_Func_Init(GPIO_FUN_UART, gpios, 2);
+  GLB_GPIO_Func_Init(GPIO_FUN_UART, gpios, 2);
 
-    GLB_UART_Fun_Sel((GPIO_PIN_14 % 8), GLB_UART_SIG_FUN_UART0_TXD); //  GPIO_FUN_UART1_TX
-    GLB_UART_Fun_Sel((GPIO_PIN_15 % 8), GLB_UART_SIG_FUN_UART0_RXD);
+  GLB_UART_Fun_Sel((GPIO_PIN_14 % 8), GLB_UART_SIG_FUN_UART0_TXD); //  GPIO_FUN_UART1_TX
+  GLB_UART_Fun_Sel((GPIO_PIN_15 % 8), GLB_UART_SIG_FUN_UART0_RXD);
 }
 
 /**
@@ -168,13 +146,12 @@ void hal_boot2_uart_gpio_init(void)
  *
  * @return
  */
-void hal_boot2_debug_uart_gpio_init(void)
-{
-    GLB_GPIO_Type gpios[] = { GPIO_PIN_17 };
+void hal_boot2_debug_uart_gpio_init(void) {
+  GLB_GPIO_Type gpios[] = {GPIO_PIN_17};
 
-    GLB_GPIO_Func_Init(GPIO_FUN_UART, gpios, 1);
+  GLB_GPIO_Func_Init(GPIO_FUN_UART, gpios, 1);
 
-    GLB_UART_Fun_Sel((GPIO_PIN_17 % 8), GLB_UART_SIG_FUN_UART1_TXD);
+  GLB_UART_Fun_Sel((GPIO_PIN_17 % 8), GLB_UART_SIG_FUN_UART1_TXD);
 }
 
 /**
@@ -183,14 +160,13 @@ void hal_boot2_debug_uart_gpio_init(void)
  * @return
  */
 #if HAL_BOOT2_SUPPORT_USB_IAP
-void hal_boot2_debug_usb_port_init(void)
-{
-    /* must do this , or usb can not be recognized */
-    cpu_global_irq_disable();
-    cpu_global_irq_enable();
-
-    GLB_GPIO_Type gpios[] = { GPIO_PIN_7, GPIO_PIN_8 };
-    GLB_GPIO_Func_Init(GPIO_FUN_ANALOG, gpios, 2);
+void hal_boot2_debug_usb_port_init(void) {
+  /* must do this , or usb can not be recognized */
+  cpu_global_irq_disable();
+  cpu_global_irq_enable();
+
+  GLB_GPIO_Type gpios[] = {GPIO_PIN_7, GPIO_PIN_8};
+  GLB_GPIO_Func_Init(GPIO_FUN_ANALOG, gpios, 2);
 }
 #endif
 
@@ -199,279 +175,244 @@ void hal_boot2_debug_usb_port_init(void)
  *
  * @return
  */
-void hal_boot2_debug_uart_gpio_deinit(void)
-{
-    GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART0);
-    GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART1);
-    GLB_UART_Sig_Swap_Set(UART_SIG_SWAP_NONE);
+void hal_boot2_debug_uart_gpio_deinit(void) {
+  GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART0);
+  GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART1);
+  GLB_UART_Sig_Swap_Set(UART_SIG_SWAP_NONE);
 }
 
-
 /****************************************************************************/ /**
- * @brief  Check bootheader crc
- *
- * @param  data: bootheader data pointer
- *
- * @return boot_error_code type
- *
-*******************************************************************************/
-static uint32_t hal_boot_check_bootheader(struct hal_bootheader_t *header)
-{
-    uint32_t crc_pass = 0;
-    uint32_t crc;
-
-    if (header->bootCfg.bval.crcIgnore == 1 && header->crc32 == HAL_BOOT2_DEADBEEF_VAL) {
-        //MSG("Crc ignored\r\n");
-        crc_pass = 1;
-    } else {
-        crc = BFLB_Soft_CRC32((uint8_t *)header, sizeof(struct hal_bootheader_t) - sizeof(header->crc32));
-
-        if (header->crc32 == crc) {
-            crc_pass = 1;
-        }
+                                                                                * @brief  Check bootheader crc
+                                                                                *
+                                                                                * @param  data: bootheader data pointer
+                                                                                *
+                                                                                * @return boot_error_code type
+                                                                                *
+                                                                                *******************************************************************************/
+static uint32_t hal_boot_check_bootheader(struct hal_bootheader_t *header) {
+  uint32_t crc_pass = 0;
+  uint32_t crc;
+
+  if (header->bootCfg.bval.crcIgnore == 1 && header->crc32 == HAL_BOOT2_DEADBEEF_VAL) {
+    // MSG("Crc ignored\r\n");
+    crc_pass = 1;
+  } else {
+    crc = BFLB_Soft_CRC32((uint8_t *)header, sizeof(struct hal_bootheader_t) - sizeof(header->crc32));
+
+    if (header->crc32 == crc) {
+      crc_pass = 1;
     }
-    return crc_pass;
+  }
+  return crc_pass;
 }
 
 /****************************************************************************/ /**
- * @brief  Check if the input public key is the same as  burned in the efuse
- *
- * @param  g_boot_img_cfg: Boot image config pointer
- * @param  data: Image data pointer
- *
- * @return boot_error_code type
- *
-*******************************************************************************/
-int32_t hal_boot_parse_bootheader(boot2_image_config *boot_img_cfg, uint8_t *data)
-{
-    struct  hal_bootheader_t *header = (struct  hal_bootheader_t *)data;
-    uint32_t crc_pass = 0;
-    uint32_t i = 0;
-    uint32_t *phash = (uint32_t *)header->hash;
-
-    crc_pass=hal_boot_check_bootheader(header);
-
-    if (!crc_pass) {
-        //MSG_ERR("bootheader crc error\r\n");
-        //blsp_dump_data((uint8_t *)&crc, 4);
-        return 0x0204;
-    }
-
-    if (header->bootCfg.bval.notLoadInBoot) {
-        return 0x0202;
+                                                                                * @brief  Check if the input public key is the same as  burned in the efuse
+                                                                                *
+                                                                                * @param  g_boot_img_cfg: Boot image config pointer
+                                                                                * @param  data: Image data pointer
+                                                                                *
+                                                                                * @return boot_error_code type
+                                                                                *
+                                                                                *******************************************************************************/
+int32_t hal_boot_parse_bootheader(boot2_image_config *boot_img_cfg, uint8_t *data) {
+  struct hal_bootheader_t *header   = (struct hal_bootheader_t *)data;
+  uint32_t                 crc_pass = 0;
+  uint32_t                 i        = 0;
+  uint32_t                *phash    = (uint32_t *)header->hash;
+
+  crc_pass = hal_boot_check_bootheader(header);
+
+  if (!crc_pass) {
+    // MSG_ERR("bootheader crc error\r\n");
+    // blsp_dump_data((uint8_t *)&crc, 4);
+    return 0x0204;
+  }
+
+  if (header->bootCfg.bval.notLoadInBoot) {
+    return 0x0202;
+  }
+
+  /* Get which CPU's img it is*/
+  for (i = 0; i < HAL_BOOT2_CPU_MAX; i++) {
+    if (0 == memcmp((void *)&header->magicCode, HAL_BOOT2_CPU0_MAGIC, sizeof(header->magicCode))) {
+      break;
+    } else if (0 == memcmp((void *)&header->magicCode, HAL_BOOT2_CPU1_MAGIC, sizeof(header->magicCode))) {
+      break;
     }
+  }
 
-    /* Get which CPU's img it is*/
-    for (i = 0; i < HAL_BOOT2_CPU_MAX; i++) {
-        if (0 == memcmp((void *)&header->magicCode, HAL_BOOT2_CPU0_MAGIC,
-                        sizeof(header->magicCode))) {
-            break;
-        } else if (0 == memcmp((void *)&header->magicCode, HAL_BOOT2_CPU1_MAGIC,
-                               sizeof(header->magicCode))) {
-            break;
-        }
-    }
+  if (i == HAL_BOOT2_CPU_MAX) {
+    /* No cpu img magic match */
+    // MSG_ERR("Magic code error\r\n");
+    return 0x0203;
+  }
 
-    if (i == HAL_BOOT2_CPU_MAX) {
-        /* No cpu img magic match */
-        //MSG_ERR("Magic code error\r\n");
-        return 0x0203;
-    }
-
-    if(boot_img_cfg==NULL){
-        return 0;
-    }
-    
-    boot_img_cfg->pk_src=i;    
-    boot_img_cfg->img_valid=0;
-
-    /* Deal with pll config */
-
-    /* Encrypt and sign */
-    boot_img_cfg->basic_cfg.encrypt_type = header->bootCfg.bval.encrypt_type;
-    boot_img_cfg->basic_cfg.sign_type = header->bootCfg.bval.sign;
-    boot_img_cfg->basic_cfg.key_sel = header->bootCfg.bval.key_sel;
-
-    /* Xip relative */
-    boot_img_cfg->basic_cfg.no_segment = header->bootCfg.bval.no_segment;
-    boot_img_cfg->cpu_cfg[0].cache_enable = header->bootCfg.bval.cache_enable;
-    boot_img_cfg->basic_cfg.aes_region_lock = header->bootCfg.bval.aes_region_lock;
-    //boot_img_cfg->cpu_cfg[1].halt_cpu = header->bootCfg.bval.halt_cpu1;
-    boot_img_cfg->cpu_cfg[0].cache_way_dis = header->bootCfg.bval.cache_way_disable;
-    boot_img_cfg->basic_cfg.hash_ignore = header->bootCfg.bval.hash_ignore;
-    /* Firmware len*/
-    boot_img_cfg->basic_cfg.img_len_cnt= header->img_segment_info.img_len;
-
-    /* Boot entry and flash offset */
-    boot_img_cfg->cpu_cfg[0].boot_entry = header->bootEntry;
-    boot_img_cfg->basic_cfg.group_image_offset = header->img_start.flash_offset;
-
-    boot_img_cfg->cpu_cfg[0].config_enable=1;
-    boot_img_cfg->cpu_cfg[0].halt_cpu =0;
-
-    //MSG("sign %d,encrypt:%d\r\n", boot_img_cfg->sign_type,boot_img_cfg->encrypt_type);
-
-    /* Check encrypt and sign match*/
-    if (g_efuse_cfg.encrypted[i] != 0) {
-        if (boot_img_cfg->basic_cfg.encrypt_type == 0) {
-            //MSG_ERR("Encrypt not fit\r\n");
-            return 0x0205;
-        }
+  if (boot_img_cfg == NULL) {
+    return 0;
+  }
+
+  boot_img_cfg->pk_src    = i;
+  boot_img_cfg->img_valid = 0;
+
+  /* Deal with pll config */
+
+  /* Encrypt and sign */
+  boot_img_cfg->basic_cfg.encrypt_type = header->bootCfg.bval.encrypt_type;
+  boot_img_cfg->basic_cfg.sign_type    = header->bootCfg.bval.sign;
+  boot_img_cfg->basic_cfg.key_sel      = header->bootCfg.bval.key_sel;
+
+  /* Xip relative */
+  boot_img_cfg->basic_cfg.no_segment      = header->bootCfg.bval.no_segment;
+  boot_img_cfg->cpu_cfg[0].cache_enable   = header->bootCfg.bval.cache_enable;
+  boot_img_cfg->basic_cfg.aes_region_lock = header->bootCfg.bval.aes_region_lock;
+  // boot_img_cfg->cpu_cfg[1].halt_cpu = header->bootCfg.bval.halt_cpu1;
+  boot_img_cfg->cpu_cfg[0].cache_way_dis = header->bootCfg.bval.cache_way_disable;
+  boot_img_cfg->basic_cfg.hash_ignore    = header->bootCfg.bval.hash_ignore;
+  /* Firmware len*/
+  boot_img_cfg->basic_cfg.img_len_cnt = header->img_segment_info.img_len;
+
+  /* Boot entry and flash offset */
+  boot_img_cfg->cpu_cfg[0].boot_entry        = header->bootEntry;
+  boot_img_cfg->basic_cfg.group_image_offset = header->img_start.flash_offset;
+
+  boot_img_cfg->cpu_cfg[0].config_enable = 1;
+  boot_img_cfg->cpu_cfg[0].halt_cpu      = 0;
+
+  // MSG("sign %d,encrypt:%d\r\n", boot_img_cfg->sign_type,boot_img_cfg->encrypt_type);
+
+  /* Check encrypt and sign match*/
+  if (g_efuse_cfg.encrypted[i] != 0) {
+    if (boot_img_cfg->basic_cfg.encrypt_type == 0) {
+      // MSG_ERR("Encrypt not fit\r\n");
+      return 0x0205;
     }
+  }
 
-    if (g_efuse_cfg.sign[i] !=boot_img_cfg->basic_cfg.sign_type) {
-        //MSG_ERR("sign not fit\r\n");
-        boot_img_cfg->basic_cfg.sign_type = g_efuse_cfg.sign[i];
-        return 0x0206;
-    }
+  if (g_efuse_cfg.sign[i] != boot_img_cfg->basic_cfg.sign_type) {
+    // MSG_ERR("sign not fit\r\n");
+    boot_img_cfg->basic_cfg.sign_type = g_efuse_cfg.sign[i];
+    return 0x0206;
+  }
 
-    if (g_ps_mode == 1 && (!g_efuse_cfg.hbn_check_sign)) {
-        /* In HBN Mode, if user select to ignore hash and sign*/
-        boot_img_cfg->basic_cfg.hash_ignore = 1;
-    } else if ((boot_img_cfg->basic_cfg.hash_ignore == 1 && *phash != HAL_BOOT2_DEADBEEF_VAL) ||
-                g_efuse_cfg.sign[i] != 0) {
-        /* If signed or user not really want to ignore, hash can't be ignored*/
-        boot_img_cfg->basic_cfg.hash_ignore = 0;
-    }
+  if (g_ps_mode == 1 && (!g_efuse_cfg.hbn_check_sign)) {
+    /* In HBN Mode, if user select to ignore hash and sign*/
+    boot_img_cfg->basic_cfg.hash_ignore = 1;
+  } else if ((boot_img_cfg->basic_cfg.hash_ignore == 1 && *phash != HAL_BOOT2_DEADBEEF_VAL) || g_efuse_cfg.sign[i] != 0) {
+    /* If signed or user not really want to ignore, hash can't be ignored*/
+    boot_img_cfg->basic_cfg.hash_ignore = 0;
+  }
 
-    if (g_user_hash_ignored) {
-        boot_img_cfg->basic_cfg.hash_ignore = 1;
-    }
+  if (g_user_hash_ignored) {
+    boot_img_cfg->basic_cfg.hash_ignore = 1;
+  }
 
-    ARCH_MemCpy_Fast(boot_img_cfg->basic_cfg.hash, header->hash, sizeof(header->hash));
+  ARCH_MemCpy_Fast(boot_img_cfg->basic_cfg.hash, header->hash, sizeof(header->hash));
 
-    if (boot_img_cfg->basic_cfg.img_len_cnt == 0) {
-        return 0x0207;
-    }
+  if (boot_img_cfg->basic_cfg.img_len_cnt == 0) {
+    return 0x0207;
+  }
 
-    return 0;
+  return 0;
 }
 
-void ATTR_TCM_SECTION hal_boot2_clean_cache(void)
-{
-    /* no need clean again since hal_boot2_set_cache will also clean
-      unused way,and bl702 no data cache except psram */
+void ATTR_TCM_SECTION hal_boot2_clean_cache(void) {
+  /* no need clean again since hal_boot2_set_cache will also clean
+    unused way,and bl702 no data cache except psram */
 }
 
-
-BL_Err_Type ATTR_TCM_SECTION hal_boot2_set_cache(uint8_t cont_read, boot2_image_config *boot_img_cfg)
-{
-    return flash_set_cache(cont_read, boot_img_cfg->cpu_cfg[0].cache_enable, 
-                    boot_img_cfg->cpu_cfg[0].cache_way_dis,
-                    boot_img_cfg->basic_cfg.group_image_offset);
-}
- 
-/****************************************************************************/ /**
- * @brief  get the ram image name and count
- *
- * @param  img_name: ram image name in partition
- * @param  ram_img_cnt: ram image count that support boot from flash
- *
- * @return None
- *
-*******************************************************************************/
-void hal_boot2_get_ram_img_cnt(char* img_name[],uint32_t *ram_img_cnt )
-{
-    *ram_img_cnt=0;
+BL_Err_Type ATTR_TCM_SECTION hal_boot2_set_cache(uint8_t cont_read, boot2_image_config *boot_img_cfg) {
+  return flash_set_cache(cont_read, boot_img_cfg->cpu_cfg[0].cache_enable, boot_img_cfg->cpu_cfg[0].cache_way_dis, boot_img_cfg->basic_cfg.group_image_offset);
 }
 
 /****************************************************************************/ /**
- * @brief  get the ram image info
- *
- * @param  data: bootheader information
- * @param  image_offset: ram image offset in flash(from of bootheader)
- * @param  img_len: ram image length
- * @param  hash: pointer to hash pointer
- *
- * @return None
- *
-*******************************************************************************/
-void hal_boot2_get_img_info(uint8_t *data, uint32_t *image_offset, uint32_t *img_len,uint8_t **hash)
-{
-    *img_len=0;
-}
+                                                                                * @brief  get the ram image name and count
+                                                                                *
+                                                                                * @param  img_name: ram image name in partition
+                                                                                * @param  ram_img_cnt: ram image count that support boot from flash
+                                                                                *
+                                                                                * @return None
+                                                                                *
+                                                                                *******************************************************************************/
+void hal_boot2_get_ram_img_cnt(char *img_name[], uint32_t *ram_img_cnt) { *ram_img_cnt = 0; }
 
 /****************************************************************************/ /**
- * @brief  release other cpu to boot up
- *
- * @param  core: core number
- * @param  boot_addr: boot address
- *
- * @return None
- *
-*******************************************************************************/
-void ATTR_TCM_SECTION hal_boot2_release_cpu(uint32_t core, uint32_t boot_addr)
-{
-
-}
+                                                                                * @brief  get the ram image info
+                                                                                *
+                                                                                * @param  data: bootheader information
+                                                                                * @param  image_offset: ram image offset in flash(from of bootheader)
+                                                                                * @param  img_len: ram image length
+                                                                                * @param  hash: pointer to hash pointer
+                                                                                *
+                                                                                * @return None
+                                                                                *
+                                                                                *******************************************************************************/
+void hal_boot2_get_img_info(uint8_t *data, uint32_t *image_offset, uint32_t *img_len, uint8_t **hash) { *img_len = 0; }
 
 /****************************************************************************/ /**
- * @brief  get xip address according to flash addr
- *
- * @param  flash_addr: flash address
- *
- * @return XIP Address
- *
-*******************************************************************************/
-uint32_t hal_boot2_get_xip_addr(uint32_t flash_addr)
-{
-    uint32_t img_offset= SF_Ctrl_Get_Flash_Image_Offset();
-    if(flash_addr>=img_offset){
-        return BL702_FLASH_XIP_BASE+(flash_addr-img_offset);
-    }else{
-        return 0;
-    }
-}
+                                                                                * @brief  release other cpu to boot up
+                                                                                *
+                                                                                * @param  core: core number
+                                                                                * @param  boot_addr: boot address
+                                                                                *
+                                                                                * @return None
+                                                                                *
+                                                                                *******************************************************************************/
+void ATTR_TCM_SECTION hal_boot2_release_cpu(uint32_t core, uint32_t boot_addr) {}
 
 /****************************************************************************/ /**
- * @brief  get multi-group count
- *
- * @param  None
- *
- * @return 1 for multi-group 0 for not
- *
-*******************************************************************************/
-uint32_t hal_boot2_get_grp_count(void)
-{
-    return 1;
+                                                                                * @brief  get xip address according to flash addr
+                                                                                *
+                                                                                * @param  flash_addr: flash address
+                                                                                *
+                                                                                * @return XIP Address
+                                                                                *
+                                                                                *******************************************************************************/
+uint32_t hal_boot2_get_xip_addr(uint32_t flash_addr) {
+  uint32_t img_offset = SF_Ctrl_Get_Flash_Image_Offset();
+  if (flash_addr >= img_offset) {
+    return BL702_FLASH_XIP_BASE + (flash_addr - img_offset);
+  } else {
+    return 0;
+  }
 }
 
 /****************************************************************************/ /**
- * @brief  get cpu count
- *
- * @param  None
- *
- * @return 1 for multi-group 0 for not
- *
-*******************************************************************************/
-uint32_t hal_boot2_get_cpu_count(void)
-{
-    return 1;
-}
+                                                                                * @brief  get multi-group count
+                                                                                *
+                                                                                * @param  None
+                                                                                *
+                                                                                * @return 1 for multi-group 0 for not
+                                                                                *
+                                                                                *******************************************************************************/
+uint32_t hal_boot2_get_grp_count(void) { return 1; }
 
 /****************************************************************************/ /**
- * @brief  get cpu count
- *
- * @param  None
- *
- * @return 1 for multi-group 0 for not
- *
-*******************************************************************************/
-uint32_t ATTR_TCM_SECTION hal_boot2_get_feature_flag(void)
-{
-    return HAL_BOOT2_SP_FLAG;
-}
+                                                                                * @brief  get cpu count
+                                                                                *
+                                                                                * @param  None
+                                                                                *
+                                                                                * @return 1 for multi-group 0 for not
+                                                                                *
+                                                                                *******************************************************************************/
+uint32_t hal_boot2_get_cpu_count(void) { return 1; }
 
 /****************************************************************************/ /**
- * @brief  get boot header offset
- *
- * @param  None
- *
- * @return bootheader offset
- *
-*******************************************************************************/
-uint32_t hal_boot2_get_bootheader_offset(void)
-{
-    return 0x00;
-}
+                                                                                * @brief  get cpu count
+                                                                                *
+                                                                                * @param  None
+                                                                                *
+                                                                                * @return 1 for multi-group 0 for not
+                                                                                *
+                                                                                *******************************************************************************/
+uint32_t ATTR_TCM_SECTION hal_boot2_get_feature_flag(void) { return HAL_BOOT2_SP_FLAG; }
 
+/****************************************************************************/ /**
+                                                                                * @brief  get boot header offset
+                                                                                *
+                                                                                * @param  None
+                                                                                *
+                                                                                * @return bootheader offset
+                                                                                *
+                                                                                *******************************************************************************/
+uint32_t hal_boot2_get_bootheader_offset(void) { return 0x00; }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_clock.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_clock.c
index 56a0037390..0a846dd88d 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_clock.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_clock.c
@@ -323,7 +323,7 @@ void peripheral_clock_init(void) {
 #if BSP_PWM_CLOCK_SOURCE == ROOT_CLOCK_SOURCE_32K_CLK
 
   for (int i = 0; i < 5; i++) {
-    PWMx    = PWM_BASE + PWM_CHANNEL_OFFSET + (i)*0x20;
+    PWMx    = PWM_BASE + PWM_CHANNEL_OFFSET + (i) * 0x20;
     tmp_pwm = BL_RD_REG(PWMx, PWM_CONFIG);
     BL_WR_REG(PWMx, PWM_CONFIG, BL_SET_REG_BIT(tmp_pwm, PWM_STOP_EN));
 
@@ -343,7 +343,7 @@ void peripheral_clock_init(void) {
 #elif BSP_PWM_CLOCK_SOURCE == ROOT_CLOCK_SOURCE_BCLK
 
   for (int i = 0; i < 5; i++) {
-    PWMx    = PWM_BASE + PWM_CHANNEL_OFFSET + (i)*0x20;
+    PWMx    = PWM_BASE + PWM_CHANNEL_OFFSET + (i) * 0x20;
     tmp_pwm = BL_RD_REG(PWMx, PWM_CONFIG);
     BL_WR_REG(PWMx, PWM_CONFIG, BL_SET_REG_BIT(tmp_pwm, PWM_STOP_EN));
 
@@ -363,7 +363,7 @@ void peripheral_clock_init(void) {
 #elif BSP_PWM_CLOCK_SOURCE == ROOT_CLOCK_SOURCE_XCLK
 
   for (int i = 0; i < 5; i++) {
-    PWMx    = PWM_BASE + PWM_CHANNEL_OFFSET + (i)*0x20;
+    PWMx    = PWM_BASE + PWM_CHANNEL_OFFSET + (i) * 0x20;
     tmp_pwm = BL_RD_REG(PWMx, PWM_CONFIG);
     BL_WR_REG(PWMx, PWM_CONFIG, BL_SET_REG_BIT(tmp_pwm, PWM_STOP_EN));
 
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_common.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_common.c
index 34fc9f01bc..84888bdb5c 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_common.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_common.c
@@ -22,83 +22,65 @@
  */
 #include "hal_common.h"
 #include "bl702_ef_ctrl.h"
+#include "bl702_l1c.h"
 #include "bl702_romdriver.h"
 #include "bl702_sec_eng.h"
-#include "bl702_l1c.h"
 #include "hbn_reg.h"
 
 volatile uint32_t nesting = 0;
 
-void ATTR_TCM_SECTION cpu_global_irq_enable(void)
-{
-    nesting--;
-    if (nesting == 0) {
-        __enable_irq();
-    }
+void ATTR_TCM_SECTION cpu_global_irq_enable(void) {
+  nesting--;
+  if (nesting == 0) {
+    __enable_irq();
+  }
 }
 
-void ATTR_TCM_SECTION cpu_global_irq_disable(void)
-{
-    __disable_irq();
-    nesting++;
+void ATTR_TCM_SECTION cpu_global_irq_disable(void) {
+  __disable_irq();
+  nesting++;
 }
 
-void hal_por_reset(void)
-{
-    RomDriver_GLB_SW_POR_Reset();
-}
+void hal_por_reset(void) { RomDriver_GLB_SW_POR_Reset(); }
 
-void hal_system_reset(void)
-{
-    RomDriver_GLB_SW_System_Reset();
-}
+void hal_system_reset(void) { RomDriver_GLB_SW_System_Reset(); }
 
-void hal_cpu_reset(void)
-{
-    RomDriver_GLB_SW_CPU_Reset();
-}
+void hal_cpu_reset(void) { RomDriver_GLB_SW_CPU_Reset(); }
 
-void hal_get_chip_id(uint8_t chip_id[8])
-{
-    EF_Ctrl_Read_MAC_Address(chip_id);
-}
+void hal_get_chip_id(uint8_t chip_id[8]) { EF_Ctrl_Read_MAC_Address(chip_id); }
 
-void hal_enter_usb_iap(void)
-{
-    BL_WR_WORD(HBN_BASE + HBN_RSV0_OFFSET, 0x00425355); //"\0BSU"
+void hal_enter_usb_iap(void) {
+  BL_WR_WORD(HBN_BASE + HBN_RSV0_OFFSET, 0x00425355); //"\0BSU"
 
-    arch_delay_ms(1000);
-    RomDriver_GLB_SW_POR_Reset();
+  arch_delay_ms(1000);
+  RomDriver_GLB_SW_POR_Reset();
 }
 
-void ATTR_TCM_SECTION hal_jump2app(uint32_t flash_offset)
-{
-    /*flash_offset from 48K to 3.98M*/
-    if ((flash_offset >= 0xc000) && (flash_offset < (0x400000 - 20 * 1024))) {
-        void (*app_main)(void) = (void (*)(void))0x23000000;
-        BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET, flash_offset);
-        L1C_Cache_Flush_Ext();
-        app_main();
-    } else {
-        while(1)
-        {}
-    }
+void ATTR_TCM_SECTION hal_jump2app(uint32_t flash_offset) {
+  /*flash_offset from 48K to 3.98M*/
+  if ((flash_offset >= 0xc000) && (flash_offset < (0x400000 - 20 * 1024))) {
+    void (*app_main)(void) = (void (*)(void))0x23000000;
+    BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET, flash_offset);
+    L1C_Cache_Flush_Ext();
+    app_main();
+  } else {
+    while (1) {}
+  }
 }
 
-int hal_get_trng_seed(void)
-{
-    uint32_t seed[8];
-    uint32_t tmpVal;
-    tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1);
-    tmpVal |= (1 << BL_AHB_SLAVE1_SEC);
-    BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal);
+int hal_get_trng_seed(void) {
+  uint32_t seed[8];
+  uint32_t tmpVal;
+  tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1);
+  tmpVal |= (1 << BL_AHB_SLAVE1_SEC);
+  BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal);
 
-    Sec_Eng_Trng_Enable();
-    Sec_Eng_Trng_Read((uint8_t *)seed);
-    Sec_Eng_Trng_Disable();
-    tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1);
-    tmpVal &= (~(1 << BL_AHB_SLAVE1_SEC));
-    BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal);
+  Sec_Eng_Trng_Enable();
+  Sec_Eng_Trng_Read((uint8_t *)seed);
+  Sec_Eng_Trng_Disable();
+  tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1);
+  tmpVal &= (~(1 << BL_AHB_SLAVE1_SEC));
+  BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal);
 
-    return seed[0];
+  return seed[0];
 }
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_dma.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_dma.c
index 0fbe57f8d2..ce242d6a1b 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_dma.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_dma.c
@@ -23,19 +23,18 @@
 #include "hal_dma.h"
 #include "bl702_dma.h"
 
-#define DMA_CHANNEL_BASE(id_base, ch) ((id_base) + DMA_CHANNEL_OFFSET + (ch)*0x100)
-
-static const uint32_t dma_channel_base[][8] = {
-    {
-        DMA_CHANNEL_BASE(DMA_BASE, 0),
-        DMA_CHANNEL_BASE(DMA_BASE, 1),
-        DMA_CHANNEL_BASE(DMA_BASE, 2),
-        DMA_CHANNEL_BASE(DMA_BASE, 3),
-        DMA_CHANNEL_BASE(DMA_BASE, 4),
-        DMA_CHANNEL_BASE(DMA_BASE, 5),
-        DMA_CHANNEL_BASE(DMA_BASE, 6),
-        DMA_CHANNEL_BASE(DMA_BASE, 7),
-    }
+#define DMA_CHANNEL_BASE(id_base, ch) ((id_base) + DMA_CHANNEL_OFFSET + (ch) * 0x100)
+
+static const uint32_t dma_channel_base[][8] = {{
+    DMA_CHANNEL_BASE(DMA_BASE, 0),
+    DMA_CHANNEL_BASE(DMA_BASE, 1),
+    DMA_CHANNEL_BASE(DMA_BASE, 2),
+    DMA_CHANNEL_BASE(DMA_BASE, 3),
+    DMA_CHANNEL_BASE(DMA_BASE, 4),
+    DMA_CHANNEL_BASE(DMA_BASE, 5),
+    DMA_CHANNEL_BASE(DMA_BASE, 6),
+    DMA_CHANNEL_BASE(DMA_BASE, 7),
+}
 
 };
 
@@ -74,38 +73,37 @@ static dma_device_t dmax_device[DMA_MAX_INDEX] = {
  * @param oflag
  * @return int
  */
-int dma_open(struct device *dev, uint16_t oflag)
-{
-    dma_device_t *dma_device = (dma_device_t *)dev;
-    DMA_Channel_Cfg_Type chCfg = { 0 };
-
-    /* Disable all interrupt */
-    DMA_IntMask(dma_device->ch, DMA_INT_ALL, MASK);
-    /* Enable uart interrupt*/
-    CPU_Interrupt_Disable(DMA_ALL_IRQn);
-
-    DMA_Disable();
-
-    DMA_Channel_Disable(dma_device->ch);
-
-    chCfg.ch = dma_device->ch;
-    chCfg.dir = dma_device->direction;
-    chCfg.srcPeriph = dma_device->src_req;
-    chCfg.dstPeriph = dma_device->dst_req;
-    chCfg.srcAddrInc = dma_device->src_addr_inc;
-    chCfg.destAddrInc = dma_device->dst_addr_inc;
-    chCfg.srcBurstSzie = dma_device->src_burst_size;
-    chCfg.dstBurstSzie = dma_device->dst_burst_size;
-    chCfg.srcTransfWidth = dma_device->src_width;
-    chCfg.dstTransfWidth = dma_device->dst_width;
-    DMA_Channel_Init(&chCfg);
-
-    DMA_Enable();
-
-    Interrupt_Handler_Register(DMA_ALL_IRQn, DMA0_IRQ);
-    /* Enable uart interrupt*/
-    CPU_Interrupt_Enable(DMA_ALL_IRQn);
-    return 0;
+int dma_open(struct device *dev, uint16_t oflag) {
+  dma_device_t        *dma_device = (dma_device_t *)dev;
+  DMA_Channel_Cfg_Type chCfg      = {0};
+
+  /* Disable all interrupt */
+  DMA_IntMask(dma_device->ch, DMA_INT_ALL, MASK);
+  /* Enable uart interrupt*/
+  CPU_Interrupt_Disable(DMA_ALL_IRQn);
+
+  DMA_Disable();
+
+  DMA_Channel_Disable(dma_device->ch);
+
+  chCfg.ch             = dma_device->ch;
+  chCfg.dir            = dma_device->direction;
+  chCfg.srcPeriph      = dma_device->src_req;
+  chCfg.dstPeriph      = dma_device->dst_req;
+  chCfg.srcAddrInc     = dma_device->src_addr_inc;
+  chCfg.destAddrInc    = dma_device->dst_addr_inc;
+  chCfg.srcBurstSzie   = dma_device->src_burst_size;
+  chCfg.dstBurstSzie   = dma_device->dst_burst_size;
+  chCfg.srcTransfWidth = dma_device->src_width;
+  chCfg.dstTransfWidth = dma_device->dst_width;
+  DMA_Channel_Init(&chCfg);
+
+  DMA_Enable();
+
+  Interrupt_Handler_Register(DMA_ALL_IRQn, DMA0_IRQ);
+  /* Enable uart interrupt*/
+  CPU_Interrupt_Enable(DMA_ALL_IRQn);
+  return 0;
 }
 /**
  * @brief
@@ -115,62 +113,61 @@ int dma_open(struct device *dev, uint16_t oflag)
  * @param args
  * @return int
  */
-int dma_control(struct device *dev, int cmd, void *args)
-{
-    dma_device_t *dma_device = (dma_device_t *)dev;
-
-    switch (cmd) {
-        case DEVICE_CTRL_SET_INT:
-            /* Dma interrupt configuration */
-            DMA_IntMask(dma_device->ch, DMA_INT_TCOMPLETED, UNMASK);
-            DMA_IntMask(dma_device->ch, DMA_INT_ERR, UNMASK);
-
-            break;
-
-        case DEVICE_CTRL_CLR_INT:
-            /* Dma interrupt configuration */
-            DMA_IntMask(dma_device->ch, DMA_INT_TCOMPLETED, MASK);
-            DMA_IntMask(dma_device->ch, DMA_INT_ERR, MASK);
-
-            break;
-
-        case DEVICE_CTRL_GET_INT:
-            break;
-
-        case DEVICE_CTRL_CONFIG:
-            break;
-
-        case DEVICE_CTRL_DMA_CHANNEL_UPDATE:
-            DMA_LLI_Update(dma_device->ch, (uint32_t)args);
-            break;
-
-        case DEVICE_CTRL_DMA_CHANNEL_GET_STATUS:
-            return DMA_Channel_Is_Busy(dma_device->ch);
-
-        case DEVICE_CTRL_DMA_CHANNEL_START:
-            DMA_Channel_Enable(dma_device->ch);
-            break;
-
-        case DEVICE_CTRL_DMA_CHANNEL_STOP:
-            DMA_Channel_Disable(dma_device->ch);
-            break;
-        case DEVICE_CTRL_DMA_CONFIG_SI: {
-            uint32_t tmpVal = BL_RD_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL);
-            tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SI, ((uint32_t)args) & 0x01);
-            BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL, tmpVal);
-
-        } break;
-        case DEVICE_CTRL_DMA_CONFIG_DI: {
-            uint32_t tmpVal = BL_RD_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL);
-            tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DI, ((uint32_t)args) & 0x01);
-            BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL, tmpVal);
-
-        } break;
-        default:
-            break;
-    }
+int dma_control(struct device *dev, int cmd, void *args) {
+  dma_device_t *dma_device = (dma_device_t *)dev;
 
-    return 0;
+  switch (cmd) {
+  case DEVICE_CTRL_SET_INT:
+    /* Dma interrupt configuration */
+    DMA_IntMask(dma_device->ch, DMA_INT_TCOMPLETED, UNMASK);
+    DMA_IntMask(dma_device->ch, DMA_INT_ERR, UNMASK);
+
+    break;
+
+  case DEVICE_CTRL_CLR_INT:
+    /* Dma interrupt configuration */
+    DMA_IntMask(dma_device->ch, DMA_INT_TCOMPLETED, MASK);
+    DMA_IntMask(dma_device->ch, DMA_INT_ERR, MASK);
+
+    break;
+
+  case DEVICE_CTRL_GET_INT:
+    break;
+
+  case DEVICE_CTRL_CONFIG:
+    break;
+
+  case DEVICE_CTRL_DMA_CHANNEL_UPDATE:
+    DMA_LLI_Update(dma_device->ch, (uint32_t)args);
+    break;
+
+  case DEVICE_CTRL_DMA_CHANNEL_GET_STATUS:
+    return DMA_Channel_Is_Busy(dma_device->ch);
+
+  case DEVICE_CTRL_DMA_CHANNEL_START:
+    DMA_Channel_Enable(dma_device->ch);
+    break;
+
+  case DEVICE_CTRL_DMA_CHANNEL_STOP:
+    DMA_Channel_Disable(dma_device->ch);
+    break;
+  case DEVICE_CTRL_DMA_CONFIG_SI: {
+    uint32_t tmpVal = BL_RD_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL);
+    tmpVal          = BL_SET_REG_BITS_VAL(tmpVal, DMA_SI, ((uint32_t)args) & 0x01);
+    BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL, tmpVal);
+
+  } break;
+  case DEVICE_CTRL_DMA_CONFIG_DI: {
+    uint32_t tmpVal = BL_RD_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL);
+    tmpVal          = BL_SET_REG_BITS_VAL(tmpVal, DMA_DI, ((uint32_t)args) & 0x01);
+    BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL, tmpVal);
+
+  } break;
+  default:
+    break;
+  }
+
+  return 0;
 }
 /**
  * @brief
@@ -178,95 +175,90 @@ int dma_control(struct device *dev, int cmd, void *args)
  * @param dev
  * @return int
  */
-int dma_close(struct device *dev)
-{
-    dma_device_t *dma_device = (dma_device_t *)dev;
-    DMA_Channel_Cfg_Type chCfg = { 0 };
+int dma_close(struct device *dev) {
+  dma_device_t        *dma_device = (dma_device_t *)dev;
+  DMA_Channel_Cfg_Type chCfg      = {0};
 
-    DMA_Channel_Disable(dma_device->ch);
-    DMA_Channel_Init(&chCfg);
-    return 0;
+  DMA_Channel_Disable(dma_device->ch);
+  DMA_Channel_Init(&chCfg);
+  return 0;
 }
 
-int dma_register(enum dma_index_type index, const char *name)
-{
-    struct device *dev;
+int dma_register(enum dma_index_type index, const char *name) {
+  struct device *dev;
 
-    if (DMA_MAX_INDEX == 0) {
-        return -DEVICE_EINVAL;
-    }
+  if (DMA_MAX_INDEX == 0) {
+    return -DEVICE_EINVAL;
+  }
 
-    dev = &(dmax_device[index].parent);
+  dev = &(dmax_device[index].parent);
 
-    dev->open = dma_open;
-    dev->close = dma_close;
-    dev->control = dma_control;
-    // dev->write = dma_write;
-    // dev->read = dma_read;
+  dev->open    = dma_open;
+  dev->close   = dma_close;
+  dev->control = dma_control;
+  // dev->write = dma_write;
+  // dev->read = dma_read;
 
-    dev->type = DEVICE_CLASS_DMA;
-    dev->handle = NULL;
+  dev->type   = DEVICE_CLASS_DMA;
+  dev->handle = NULL;
 
-    return device_register(dev, name);
+  return device_register(dev, name);
 }
 
-static BL_Err_Type dma_scan_unregister_device(uint8_t *allocate_index)
-{
-    struct device *dev;
-    dlist_t *node;
-    uint8_t dma_index = 0;
-    uint32_t dma_handle[DMA_MAX_INDEX];
+static BL_Err_Type dma_scan_unregister_device(uint8_t *allocate_index) {
+  struct device *dev;
+  dlist_t       *node;
+  uint8_t        dma_index = 0;
+  uint32_t       dma_handle[DMA_MAX_INDEX];
 
-    for (dma_index = 0; dma_index < DMA_MAX_INDEX; dma_index++) {
-        dma_handle[dma_index] = 0xff;
-    }
+  for (dma_index = 0; dma_index < DMA_MAX_INDEX; dma_index++) {
+    dma_handle[dma_index] = 0xff;
+  }
 
-    /* get registered dma handle list*/
-    dlist_for_each(node, device_get_list_header())
-    {
-        dev = dlist_entry(node, struct device, list);
+  /* get registered dma handle list*/
+  dlist_for_each(node, device_get_list_header()) {
+    dev = dlist_entry(node, struct device, list);
 
-        if (dev->type == DEVICE_CLASS_DMA) {
-            dma_handle[(((uint32_t)dev - (uint32_t)dmax_device) / sizeof(dma_device_t)) % DMA_MAX_INDEX] = SET;
-        }
+    if (dev->type == DEVICE_CLASS_DMA) {
+      dma_handle[(((uint32_t)dev - (uint32_t)dmax_device) / sizeof(dma_device_t)) % DMA_MAX_INDEX] = SET;
     }
+  }
 
-    for (dma_index = 0; dma_index < DMA_MAX_INDEX; dma_index++) {
-        if (dma_handle[dma_index] == 0xff) {
-            *allocate_index = dma_index;
-            return SUCCESS;
-        }
+  for (dma_index = 0; dma_index < DMA_MAX_INDEX; dma_index++) {
+    if (dma_handle[dma_index] == 0xff) {
+      *allocate_index = dma_index;
+      return SUCCESS;
     }
+  }
 
-    return ERROR;
+  return ERROR;
 }
 
-int dma_allocate_register(const char *name)
-{
-    struct device *dev;
-    uint8_t index;
+int dma_allocate_register(const char *name) {
+  struct device *dev;
+  uint8_t        index;
 
-    if (DMA_MAX_INDEX == 0) {
-        return -DEVICE_EINVAL;
-    }
+  if (DMA_MAX_INDEX == 0) {
+    return -DEVICE_EINVAL;
+  }
 
-    if (dma_scan_unregister_device(&index) == ERROR) {
-        return -DEVICE_ENOSPACE;
-    }
+  if (dma_scan_unregister_device(&index) == ERROR) {
+    return -DEVICE_ENOSPACE;
+  }
 
-    dev = &(dmax_device[index].parent);
+  dev = &(dmax_device[index].parent);
 
-    dev->open = dma_open;
-    dev->close = dma_close;
-    dev->control = dma_control;
-    // dev->write = dma_write;
-    // dev->read = dma_read;
+  dev->open    = dma_open;
+  dev->close   = dma_close;
+  dev->control = dma_control;
+  // dev->write = dma_write;
+  // dev->read = dma_read;
 
-    dev->status = DEVICE_UNREGISTER;
-    dev->type = DEVICE_CLASS_DMA;
-    dev->handle = NULL;
+  dev->status = DEVICE_UNREGISTER;
+  dev->type   = DEVICE_CLASS_DMA;
+  dev->handle = NULL;
 
-    return device_register(dev, name);
+  return device_register(dev, name);
 }
 
 /**
@@ -278,106 +270,105 @@ int dma_allocate_register(const char *name)
  * @param transfer_size
  * @return int
  */
-int dma_reload(struct device *dev, uint32_t src_addr, uint32_t dst_addr, uint32_t transfer_size)
-{
-#if defined(BSP_USING_DMA0_CH0) || defined(BSP_USING_DMA0_CH1) || defined(BSP_USING_DMA0_CH2) || defined(BSP_USING_DMA0_CH3) || \
-    defined(BSP_USING_DMA0_CH4) || defined(BSP_USING_DMA0_CH5) || defined(BSP_USING_DMA0_CH6) || defined(BSP_USING_DMA0_CH7)
+int dma_reload(struct device *dev, uint32_t src_addr, uint32_t dst_addr, uint32_t transfer_size) {
+#if defined(BSP_USING_DMA0_CH0) || defined(BSP_USING_DMA0_CH1) || defined(BSP_USING_DMA0_CH2) || defined(BSP_USING_DMA0_CH3) || defined(BSP_USING_DMA0_CH4) || defined(BSP_USING_DMA0_CH5) \
+    || defined(BSP_USING_DMA0_CH6) || defined(BSP_USING_DMA0_CH7)
 
-    uint32_t malloc_count;
-    uint32_t remain_len;
-    uint32_t actual_transfer_len = 0;
-    uint32_t actual_transfer_offset = 0;
-    dma_control_data_t dma_ctrl_cfg;
+  uint32_t           malloc_count;
+  uint32_t           remain_len;
+  uint32_t           actual_transfer_len    = 0;
+  uint32_t           actual_transfer_offset = 0;
+  dma_control_data_t dma_ctrl_cfg;
 
-    dma_device_t *dma_device = (dma_device_t *)dev;
+  dma_device_t *dma_device = (dma_device_t *)dev;
 
-    DMA_Channel_Disable(dma_device->ch);
+  DMA_Channel_Disable(dma_device->ch);
 
-    if (transfer_size == 0) {
-        return 0;
+  if (transfer_size == 0) {
+    return 0;
+  }
+
+  switch (dma_device->src_width) {
+  case DMA_TRANSFER_WIDTH_8BIT:
+    actual_transfer_offset = 4095;
+    actual_transfer_len    = transfer_size;
+    break;
+  case DMA_TRANSFER_WIDTH_16BIT:
+    if (transfer_size % 2) {
+      return -1;
     }
-
-    switch (dma_device->src_width) {
-        case DMA_TRANSFER_WIDTH_8BIT:
-            actual_transfer_offset = 4095;
-            actual_transfer_len = transfer_size;
-            break;
-        case DMA_TRANSFER_WIDTH_16BIT:
-            if (transfer_size % 2) {
-                return -1;
-            }
-            actual_transfer_offset = 4095 << 1;
-            actual_transfer_len = transfer_size >> 1;
-            break;
-        case DMA_TRANSFER_WIDTH_32BIT:
-            if (transfer_size % 4) {
-                return -1;
-            }
-
-            actual_transfer_offset = 4095 << 2;
-            actual_transfer_len = transfer_size >> 2;
-            break;
-
-        default:
-            return -3;
-            break;
+    actual_transfer_offset = 4095 << 1;
+    actual_transfer_len    = transfer_size >> 1;
+    break;
+  case DMA_TRANSFER_WIDTH_32BIT:
+    if (transfer_size % 4) {
+      return -1;
     }
 
-    dma_ctrl_cfg = (dma_control_data_t)(BL_RD_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL));
+    actual_transfer_offset = 4095 << 2;
+    actual_transfer_len    = transfer_size >> 2;
+    break;
 
-    malloc_count = actual_transfer_len / 4095;
-    remain_len = actual_transfer_len % 4095;
+  default:
+    return -3;
+    break;
+  }
 
-    if (remain_len) {
-        malloc_count++;
-    }
+  dma_ctrl_cfg = (dma_control_data_t)(BL_RD_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL));
 
-    dma_device->lli_cfg = (dma_lli_ctrl_t *)realloc(dma_device->lli_cfg, sizeof(dma_lli_ctrl_t) * malloc_count);
+  malloc_count = actual_transfer_len / 4095;
+  remain_len   = actual_transfer_len % 4095;
 
-    if (dma_device->lli_cfg) {
-        /*transfer_size will be integer multiple of 4095*n or 4095*2*n or 4095*4*n,(n>0) */
-        for (uint32_t i = 0; i < malloc_count; i++) {
-            dma_device->lli_cfg[i].src_addr = src_addr;
-            dma_device->lli_cfg[i].dst_addr = dst_addr;
-            dma_device->lli_cfg[i].nextlli = 0;
+  if (remain_len) {
+    malloc_count++;
+  }
 
-            dma_ctrl_cfg.bits.TransferSize = 4095;
-            dma_ctrl_cfg.bits.I = 0;
+  dma_device->lli_cfg = (dma_lli_ctrl_t *)realloc(dma_device->lli_cfg, sizeof(dma_lli_ctrl_t) * malloc_count);
 
-            if (dma_ctrl_cfg.bits.SI) {
-                src_addr += actual_transfer_offset;
-            }
+  if (dma_device->lli_cfg) {
+    /*transfer_size will be integer multiple of 4095*n or 4095*2*n or 4095*4*n,(n>0) */
+    for (uint32_t i = 0; i < malloc_count; i++) {
+      dma_device->lli_cfg[i].src_addr = src_addr;
+      dma_device->lli_cfg[i].dst_addr = dst_addr;
+      dma_device->lli_cfg[i].nextlli  = 0;
 
-            if (dma_ctrl_cfg.bits.DI) {
-                dst_addr += actual_transfer_offset;
-            }
+      dma_ctrl_cfg.bits.TransferSize = 4095;
+      dma_ctrl_cfg.bits.I            = 0;
 
-            if (i == malloc_count - 1) {
-                if (remain_len) {
-                    dma_ctrl_cfg.bits.TransferSize = remain_len;
-                }
-                dma_ctrl_cfg.bits.I = 1;
+      if (dma_ctrl_cfg.bits.SI) {
+        src_addr += actual_transfer_offset;
+      }
 
-                if (dma_device->transfer_mode == DMA_LLI_CYCLE_MODE) {
-                    dma_device->lli_cfg[i].nextlli = (uint32_t)&dma_device->lli_cfg[0];
-                }
-            }
+      if (dma_ctrl_cfg.bits.DI) {
+        dst_addr += actual_transfer_offset;
+      }
 
-            if (i) {
-                dma_device->lli_cfg[i - 1].nextlli = (uint32_t)&dma_device->lli_cfg[i];
-            }
+      if (i == malloc_count - 1) {
+        if (remain_len) {
+          dma_ctrl_cfg.bits.TransferSize = remain_len;
+        }
+        dma_ctrl_cfg.bits.I = 1;
 
-            dma_device->lli_cfg[i].cfg = dma_ctrl_cfg;
+        if (dma_device->transfer_mode == DMA_LLI_CYCLE_MODE) {
+          dma_device->lli_cfg[i].nextlli = (uint32_t)&dma_device->lli_cfg[0];
         }
-        BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_SRCADDR, dma_device->lli_cfg[0].src_addr);
-        BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_DSTADDR, dma_device->lli_cfg[0].dst_addr);
-        BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_LLI, dma_device->lli_cfg[0].nextlli);
-        BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL, dma_device->lli_cfg[0].cfg.WORD);
-    } else {
-        return -2;
+      }
+
+      if (i) {
+        dma_device->lli_cfg[i - 1].nextlli = (uint32_t)&dma_device->lli_cfg[i];
+      }
+
+      dma_device->lli_cfg[i].cfg = dma_ctrl_cfg;
     }
+    BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_SRCADDR, dma_device->lli_cfg[0].src_addr);
+    BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_DSTADDR, dma_device->lli_cfg[0].dst_addr);
+    BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_LLI, dma_device->lli_cfg[0].nextlli);
+    BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL, dma_device->lli_cfg[0].cfg.WORD);
+  } else {
+    return -2;
+  }
 #endif
-    return 0;
+  return 0;
 }
 
 /**
@@ -385,47 +376,45 @@ int dma_reload(struct device *dev, uint32_t src_addr, uint32_t dst_addr, uint32_
  *
  * @param handle
  */
-void dma_channel_isr(dma_device_t *handle)
-{
-    uint32_t tmpVal;
-    uint32_t intClr;
-
-    /* Get DMA register */
-    uint32_t DMAChs = DMA_BASE;
-
-    if (!handle->parent.callback) {
-        return;
-    }
-
-    tmpVal = BL_RD_REG(DMAChs, DMA_INTTCSTATUS);
-    if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCSTATUS) & (1 << handle->ch)) != 0) {
-        /* Clear interrupt */
-        tmpVal = BL_RD_REG(DMAChs, DMA_INTTCCLEAR);
-        intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR);
-        intClr |= (1 << handle->ch);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR, intClr);
-        BL_WR_REG(DMAChs, DMA_INTTCCLEAR, tmpVal);
-        handle->parent.callback(&handle->parent, NULL, 0, DMA_INT_TCOMPLETED);
-    }
-
-    tmpVal = BL_RD_REG(DMAChs, DMA_INTERRORSTATUS);
-    if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRORSTATUS) & (1 << handle->ch)) != 0) {
-        /*Clear interrupt */
-        tmpVal = BL_RD_REG(DMAChs, DMA_INTERRCLR);
-        intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR);
-        intClr |= (1 << handle->ch);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR, intClr);
-        BL_WR_REG(DMAChs, DMA_INTERRCLR, tmpVal);
-        handle->parent.callback(&handle->parent, NULL, 0, DMA_INT_ERR);
-    }
+void dma_channel_isr(dma_device_t *handle) {
+  uint32_t tmpVal;
+  uint32_t intClr;
+
+  /* Get DMA register */
+  uint32_t DMAChs = DMA_BASE;
+
+  if (!handle->parent.callback) {
+    return;
+  }
+
+  tmpVal = BL_RD_REG(DMAChs, DMA_INTTCSTATUS);
+  if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCSTATUS) & (1 << handle->ch)) != 0) {
+    /* Clear interrupt */
+    tmpVal = BL_RD_REG(DMAChs, DMA_INTTCCLEAR);
+    intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR);
+    intClr |= (1 << handle->ch);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR, intClr);
+    BL_WR_REG(DMAChs, DMA_INTTCCLEAR, tmpVal);
+    handle->parent.callback(&handle->parent, NULL, 0, DMA_INT_TCOMPLETED);
+  }
+
+  tmpVal = BL_RD_REG(DMAChs, DMA_INTERRORSTATUS);
+  if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRORSTATUS) & (1 << handle->ch)) != 0) {
+    /*Clear interrupt */
+    tmpVal = BL_RD_REG(DMAChs, DMA_INTERRCLR);
+    intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR);
+    intClr |= (1 << handle->ch);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR, intClr);
+    BL_WR_REG(DMAChs, DMA_INTERRCLR, tmpVal);
+    handle->parent.callback(&handle->parent, NULL, 0, DMA_INT_ERR);
+  }
 }
 /**
  * @brief
  *
  */
-void DMA0_IRQ(void)
-{
-    for (uint8_t i = 0; i < DMA_MAX_INDEX; i++) {
-        dma_channel_isr(&dmax_device[i]);
-    }
+void DMA0_IRQ(void) {
+  for (uint8_t i = 0; i < DMA_MAX_INDEX; i++) {
+    dma_channel_isr(&dmax_device[i]);
+  }
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_flash.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_flash.c
index dad0210ce5..a0d7f874df 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_flash.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_flash.c
@@ -20,14 +20,14 @@
  * under the License.
  *
  */
+#include "hal_flash.h"
 #include "bl702_glb.h"
-#include "bl702_xip_sflash.h"
-#include "bl702_xip_sflash_ext.h"
 #include "bl702_sf_cfg.h"
 #include "bl702_sf_cfg_ext.h"
-#include "hal_flash.h"
+#include "bl702_xip_sflash.h"
+#include "bl702_xip_sflash_ext.h"
 
-static uint32_t g_jedec_id = 0;
+static uint32_t           g_jedec_id = 0;
 static SPI_Flash_Cfg_Type g_flash_cfg;
 
 /**
@@ -35,12 +35,11 @@ static SPI_Flash_Cfg_Type g_flash_cfg;
  *
  * @return BL_Err_Type
  */
-uint32_t flash_get_jedecid(void)
-{
-    uint32_t jid = 0;
+uint32_t flash_get_jedecid(void) {
+  uint32_t jid = 0;
 
-    jid = ((g_jedec_id&0xff)<<16) + (g_jedec_id&0xff00) + ((g_jedec_id&0xff0000)>>16);
-    return jid;
+  jid = ((g_jedec_id & 0xff) << 16) + (g_jedec_id & 0xff00) + ((g_jedec_id & 0xff0000) >> 16);
+  return jid;
 }
 
 /**
@@ -48,12 +47,11 @@ uint32_t flash_get_jedecid(void)
  *
  * @return BL_Err_Type
  */
-BL_Err_Type flash_get_cfg(uint8_t **cfg_addr, uint32_t *len)
-{
-    *cfg_addr = (uint8_t *)&g_flash_cfg;
-    *len = sizeof(SPI_Flash_Cfg_Type);
+BL_Err_Type flash_get_cfg(uint8_t **cfg_addr, uint32_t *len) {
+  *cfg_addr = (uint8_t *)&g_flash_cfg;
+  *len      = sizeof(SPI_Flash_Cfg_Type);
 
-    return SUCCESS;
+  return SUCCESS;
 }
 
 /**
@@ -61,13 +59,12 @@ BL_Err_Type flash_get_cfg(uint8_t **cfg_addr, uint32_t *len)
  *
  * @return BL_Err_Type
  */
-static BL_Err_Type ATTR_TCM_SECTION flash_set_qspi_enable(SPI_Flash_Cfg_Type *p_flash_cfg)
-{
-    if ((p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QO_MODE || (p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QIO_MODE) {
-        SFlash_Qspi_Enable(p_flash_cfg);
-    }
+static BL_Err_Type ATTR_TCM_SECTION flash_set_qspi_enable(SPI_Flash_Cfg_Type *p_flash_cfg) {
+  if ((p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QO_MODE || (p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QIO_MODE) {
+    SFlash_Qspi_Enable(p_flash_cfg);
+  }
 
-    return SUCCESS;
+  return SUCCESS;
 }
 
 /**
@@ -75,18 +72,17 @@ static BL_Err_Type ATTR_TCM_SECTION flash_set_qspi_enable(SPI_Flash_Cfg_Type *p_
  *
  * @return BL_Err_Type
  */
-static BL_Err_Type ATTR_TCM_SECTION flash_set_l1c_wrap(SPI_Flash_Cfg_Type *p_flash_cfg)
-{
-    if (((p_flash_cfg->ioMode >> 4) & 0x01) == 1) {
-        L1C_Set_Wrap(DISABLE);
-    } else {
-        L1C_Set_Wrap(ENABLE);
-        if ((p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QO_MODE || (p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QIO_MODE) {
-            SFlash_SetBurstWrap(p_flash_cfg);
-        }
+static BL_Err_Type ATTR_TCM_SECTION flash_set_l1c_wrap(SPI_Flash_Cfg_Type *p_flash_cfg) {
+  if (((p_flash_cfg->ioMode >> 4) & 0x01) == 1) {
+    L1C_Set_Wrap(DISABLE);
+  } else {
+    L1C_Set_Wrap(ENABLE);
+    if ((p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QO_MODE || (p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QIO_MODE) {
+      SFlash_SetBurstWrap(p_flash_cfg);
     }
+  }
 
-    return SUCCESS;
+  return SUCCESS;
 }
 
 /**
@@ -94,32 +90,31 @@ static BL_Err_Type ATTR_TCM_SECTION flash_set_l1c_wrap(SPI_Flash_Cfg_Type *p_fla
  *
  * @return BL_Err_Type
  */
-static BL_Err_Type ATTR_TCM_SECTION flash_config_init(SPI_Flash_Cfg_Type *p_flash_cfg, uint8_t *jedec_id)
-{
-    BL_Err_Type ret = ERROR;
-    uint32_t jid = 0;
-    uint32_t offset = 0;
-
-    cpu_global_irq_disable();
-    XIP_SFlash_Opt_Enter();
-    XIP_SFlash_State_Save(p_flash_cfg, &offset);
-    SFlash_GetJedecId(p_flash_cfg, (uint8_t *)&jid);
-    arch_memcpy(jedec_id, (uint8_t *)&jid, 3);
-    jid &= 0xFFFFFF;
-    g_jedec_id = jid;
-    ret = SF_Cfg_Get_Flash_Cfg_Need_Lock_Ext(jid, p_flash_cfg);
-    if (ret == SUCCESS) {
-        p_flash_cfg->mid = (jid & 0xff);
-    }
-
-    /* Set flash controler from p_flash_cfg */
-    flash_set_qspi_enable(p_flash_cfg);
-    flash_set_l1c_wrap(p_flash_cfg);
-    XIP_SFlash_State_Restore(p_flash_cfg, p_flash_cfg->ioMode & 0x0f, offset);
-    XIP_SFlash_Opt_Exit();
-    cpu_global_irq_enable();
-
-    return ret;
+static BL_Err_Type ATTR_TCM_SECTION flash_config_init(SPI_Flash_Cfg_Type *p_flash_cfg, uint8_t *jedec_id) {
+  BL_Err_Type ret    = ERROR;
+  uint32_t    jid    = 0;
+  uint32_t    offset = 0;
+
+  cpu_global_irq_disable();
+  XIP_SFlash_Opt_Enter();
+  XIP_SFlash_State_Save(p_flash_cfg, &offset);
+  SFlash_GetJedecId(p_flash_cfg, (uint8_t *)&jid);
+  arch_memcpy(jedec_id, (uint8_t *)&jid, 3);
+  jid &= 0xFFFFFF;
+  g_jedec_id = jid;
+  ret        = SF_Cfg_Get_Flash_Cfg_Need_Lock_Ext(jid, p_flash_cfg);
+  if (ret == SUCCESS) {
+    p_flash_cfg->mid = (jid & 0xff);
+  }
+
+  /* Set flash controler from p_flash_cfg */
+  flash_set_qspi_enable(p_flash_cfg);
+  flash_set_l1c_wrap(p_flash_cfg);
+  XIP_SFlash_State_Restore(p_flash_cfg, p_flash_cfg->ioMode & 0x0f, offset);
+  XIP_SFlash_Opt_Exit();
+  cpu_global_irq_enable();
+
+  return ret;
 }
 
 /**
@@ -127,26 +122,25 @@ static BL_Err_Type ATTR_TCM_SECTION flash_config_init(SPI_Flash_Cfg_Type *p_flas
  *
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_init(void)
-{
-    BL_Err_Type ret = ERROR;
-    uint8_t clkDelay = 1;
-    uint8_t clkInvert = 1;
-    uint32_t jedec_id = 0;
-
-    cpu_global_irq_disable();
-    L1C_Cache_Flush_Ext();
-    SF_Cfg_Get_Flash_Cfg_Need_Lock_Ext(0, &g_flash_cfg);
-    L1C_Cache_Flush_Ext();
-    cpu_global_irq_enable();
-    if (g_flash_cfg.mid != 0xff) {
-        return SUCCESS;
-    }
-    clkDelay = g_flash_cfg.clkDelay;
-    clkInvert = g_flash_cfg.clkInvert;
-    g_flash_cfg.ioMode = g_flash_cfg.ioMode & 0x0f;
+BL_Err_Type ATTR_TCM_SECTION flash_init(void) {
+  BL_Err_Type ret       = ERROR;
+  uint8_t     clkDelay  = 1;
+  uint8_t     clkInvert = 1;
+  uint32_t    jedec_id  = 0;
+
+  cpu_global_irq_disable();
+  L1C_Cache_Flush_Ext();
+  SF_Cfg_Get_Flash_Cfg_Need_Lock_Ext(0, &g_flash_cfg);
+  L1C_Cache_Flush_Ext();
+  cpu_global_irq_enable();
+  if (g_flash_cfg.mid != 0xff) {
+    return SUCCESS;
+  }
+  clkDelay           = g_flash_cfg.clkDelay;
+  clkInvert          = g_flash_cfg.clkInvert;
+  g_flash_cfg.ioMode = g_flash_cfg.ioMode & 0x0f;
 
-    ret = flash_config_init(&g_flash_cfg, (uint8_t *)&jedec_id);
+  ret = flash_config_init(&g_flash_cfg, (uint8_t *)&jedec_id);
 #if 0
     MSG("flash ID = %08x\r\n", jedec_id);
     bflb_platform_dump((uint8_t *)&g_flash_cfg, sizeof(g_flash_cfg));
@@ -154,10 +148,10 @@ BL_Err_Type ATTR_TCM_SECTION flash_init(void)
         MSG("flash config init fail!\r\n");
     }
 #endif
-    g_flash_cfg.clkDelay = clkDelay;
-    g_flash_cfg.clkInvert = clkInvert;
+  g_flash_cfg.clkDelay  = clkDelay;
+  g_flash_cfg.clkInvert = clkInvert;
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -166,19 +160,18 @@ BL_Err_Type ATTR_TCM_SECTION flash_init(void)
  * @param data
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_read_jedec_id(uint8_t *data)
-{
-    uint32_t jid = 0;
-
-    cpu_global_irq_disable();
-    XIP_SFlash_Opt_Enter();
-    XIP_SFlash_GetJedecId_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, (uint8_t *)&jid);
-    XIP_SFlash_Opt_Exit();
-    cpu_global_irq_enable();
-    jid &= 0xFFFFFF;
-    arch_memcpy(data, (void *)&jid, 4);
-
-    return SUCCESS;
+BL_Err_Type ATTR_TCM_SECTION flash_read_jedec_id(uint8_t *data) {
+  uint32_t jid = 0;
+
+  cpu_global_irq_disable();
+  XIP_SFlash_Opt_Enter();
+  XIP_SFlash_GetJedecId_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, (uint8_t *)&jid);
+  XIP_SFlash_Opt_Exit();
+  cpu_global_irq_enable();
+  jid &= 0xFFFFFF;
+  arch_memcpy(data, (void *)&jid, 4);
+
+  return SUCCESS;
 }
 
 /**
@@ -189,15 +182,14 @@ BL_Err_Type ATTR_TCM_SECTION flash_read_jedec_id(uint8_t *data)
  * @param len
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_read_via_xip(uint32_t addr, uint8_t *data, uint32_t len)
-{
-    cpu_global_irq_disable();
-    L1C_Cache_Flush_Ext();
-    XIP_SFlash_Read_Via_Cache_Need_Lock(addr, data, len);
-    L1C_Cache_Flush_Ext();
-    cpu_global_irq_enable();
-
-    return SUCCESS;
+BL_Err_Type ATTR_TCM_SECTION flash_read_via_xip(uint32_t addr, uint8_t *data, uint32_t len) {
+  cpu_global_irq_disable();
+  L1C_Cache_Flush_Ext();
+  XIP_SFlash_Read_Via_Cache_Need_Lock(addr, data, len);
+  L1C_Cache_Flush_Ext();
+  cpu_global_irq_enable();
+
+  return SUCCESS;
 }
 
 /**
@@ -208,17 +200,16 @@ BL_Err_Type ATTR_TCM_SECTION flash_read_via_xip(uint32_t addr, uint8_t *data, ui
  * @param len
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_read(uint32_t addr, uint8_t *data, uint32_t len)
-{
-    BL_Err_Type ret = ERROR;
+BL_Err_Type ATTR_TCM_SECTION flash_read(uint32_t addr, uint8_t *data, uint32_t len) {
+  BL_Err_Type ret = ERROR;
 
-    cpu_global_irq_disable();
-    XIP_SFlash_Opt_Enter();
-    ret = XIP_SFlash_Read_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, addr, data, len);
-    XIP_SFlash_Opt_Exit();
-    cpu_global_irq_enable();
+  cpu_global_irq_disable();
+  XIP_SFlash_Opt_Enter();
+  ret = XIP_SFlash_Read_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, addr, data, len);
+  XIP_SFlash_Opt_Exit();
+  cpu_global_irq_enable();
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -229,17 +220,16 @@ BL_Err_Type ATTR_TCM_SECTION flash_read(uint32_t addr, uint8_t *data, uint32_t l
  * @param len
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_write(uint32_t addr, uint8_t *data, uint32_t len)
-{
-    BL_Err_Type ret = ERROR;
+BL_Err_Type ATTR_TCM_SECTION flash_write(uint32_t addr, uint8_t *data, uint32_t len) {
+  BL_Err_Type ret = ERROR;
 
-    cpu_global_irq_disable();
-    XIP_SFlash_Opt_Enter();
-    ret = XIP_SFlash_Write_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, addr, data, len);
-    XIP_SFlash_Opt_Exit();
-    cpu_global_irq_enable();
+  cpu_global_irq_disable();
+  XIP_SFlash_Opt_Enter();
+  ret = XIP_SFlash_Write_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, addr, data, len);
+  XIP_SFlash_Opt_Exit();
+  cpu_global_irq_enable();
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -249,17 +239,16 @@ BL_Err_Type ATTR_TCM_SECTION flash_write(uint32_t addr, uint8_t *data, uint32_t
  * @param endaddr
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_erase(uint32_t startaddr, uint32_t len)
-{
-    BL_Err_Type ret = ERROR;
+BL_Err_Type ATTR_TCM_SECTION flash_erase(uint32_t startaddr, uint32_t len) {
+  BL_Err_Type ret = ERROR;
 
-    cpu_global_irq_disable();
-    XIP_SFlash_Opt_Enter();
-    ret = XIP_SFlash_Erase_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, startaddr, startaddr + len - 1);
-    XIP_SFlash_Opt_Exit();
-    cpu_global_irq_enable();
+  cpu_global_irq_disable();
+  XIP_SFlash_Opt_Enter();
+  ret = XIP_SFlash_Erase_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, startaddr, startaddr + len - 1);
+  XIP_SFlash_Opt_Exit();
+  cpu_global_irq_enable();
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -268,17 +257,16 @@ BL_Err_Type ATTR_TCM_SECTION flash_erase(uint32_t startaddr, uint32_t len)
  * @param protect
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_write_protect_set(SFlash_Protect_Kh25v40_Type protect)
-{
-    BL_Err_Type ret = ERROR;
+BL_Err_Type ATTR_TCM_SECTION flash_write_protect_set(SFlash_Protect_Kh25v40_Type protect) {
+  BL_Err_Type ret = ERROR;
 
-    cpu_global_irq_disable();
-    XIP_SFlash_Opt_Enter();
-    ret = XIP_SFlash_KH25V40_Write_Protect_Need_Lock(&g_flash_cfg, protect);
-    XIP_SFlash_Opt_Exit();
-    cpu_global_irq_enable();
+  cpu_global_irq_disable();
+  XIP_SFlash_Opt_Enter();
+  ret = XIP_SFlash_KH25V40_Write_Protect_Need_Lock(&g_flash_cfg, protect);
+  XIP_SFlash_Opt_Exit();
+  cpu_global_irq_enable();
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -287,17 +275,16 @@ BL_Err_Type ATTR_TCM_SECTION flash_write_protect_set(SFlash_Protect_Kh25v40_Type
  * @param None
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_clear_status_register(void)
-{
-    BL_Err_Type ret = ERROR;
+BL_Err_Type ATTR_TCM_SECTION flash_clear_status_register(void) {
+  BL_Err_Type ret = ERROR;
 
-    cpu_global_irq_disable();
-    XIP_SFlash_Opt_Enter();
-    ret = XIP_SFlash_Clear_Status_Register_Need_Lock(&g_flash_cfg);
-    XIP_SFlash_Opt_Exit();
-    cpu_global_irq_enable();
+  cpu_global_irq_disable();
+  XIP_SFlash_Opt_Enter();
+  ret = XIP_SFlash_Clear_Status_Register_Need_Lock(&g_flash_cfg);
+  XIP_SFlash_Opt_Exit();
+  cpu_global_irq_enable();
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -309,38 +296,37 @@ BL_Err_Type ATTR_TCM_SECTION flash_clear_status_register(void)
  * @param flash_offset
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_set_cache(uint8_t cont_read, uint8_t cache_enable, uint8_t cache_way_disable, uint32_t flash_offset)
-{
-    uint32_t tmp[1];
-    BL_Err_Type stat;
+BL_Err_Type ATTR_TCM_SECTION flash_set_cache(uint8_t cont_read, uint8_t cache_enable, uint8_t cache_way_disable, uint32_t flash_offset) {
+  uint32_t    tmp[1];
+  BL_Err_Type stat;
 
-    SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB);
+  SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB);
 
-    XIP_SFlash_Opt_Enter();
-    /* To make it simple, exit cont read anyway */
-    SFlash_Reset_Continue_Read(&g_flash_cfg);
+  XIP_SFlash_Opt_Enter();
+  /* To make it simple, exit cont read anyway */
+  SFlash_Reset_Continue_Read(&g_flash_cfg);
 
-    if (g_flash_cfg.cReadSupport == 0) {
-        cont_read = 0;
-    }
+  if (g_flash_cfg.cReadSupport == 0) {
+    cont_read = 0;
+  }
 
-    if (cont_read == 1) {
-        stat = SFlash_Read(&g_flash_cfg, g_flash_cfg.ioMode & 0xf, 1, 0x00000000, (uint8_t *)tmp, sizeof(tmp));
+  if (cont_read == 1) {
+    stat = SFlash_Read(&g_flash_cfg, g_flash_cfg.ioMode & 0xf, 1, 0x00000000, (uint8_t *)tmp, sizeof(tmp));
 
-        if (SUCCESS != stat) {
-            XIP_SFlash_Opt_Exit();
-            return ERROR;
-        }
+    if (SUCCESS != stat) {
+      XIP_SFlash_Opt_Exit();
+      return ERROR;
     }
+  }
 
-    /* Set default value */
-    L1C_Cache_Enable_Set(0xf);
+  /* Set default value */
+  L1C_Cache_Enable_Set(0xf);
 
-    if (cache_enable) {
-        SF_Ctrl_Set_Flash_Image_Offset(flash_offset);
-        SFlash_Cache_Read_Enable(&g_flash_cfg, g_flash_cfg.ioMode & 0xf, cont_read, cache_way_disable);
-    }
-    XIP_SFlash_Opt_Exit();
+  if (cache_enable) {
+    SF_Ctrl_Set_Flash_Image_Offset(flash_offset);
+    SFlash_Cache_Read_Enable(&g_flash_cfg, g_flash_cfg.ioMode & 0xf, cont_read, cache_way_disable);
+  }
+  XIP_SFlash_Opt_Exit();
 
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_mtimer.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_mtimer.c
index 2305305efe..4821f514d0 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_mtimer.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_mtimer.c
@@ -28,11 +28,10 @@ static void (*systick_callback)(void);
 static uint64_t next_compare_tick = 0;
 static uint64_t current_set_ticks = 0;
 
-static void Systick_Handler(void)
-{
-    *(volatile uint64_t *)(CLIC_CTRL_ADDR + CLIC_MTIMECMP) = next_compare_tick;
-    systick_callback();
-    next_compare_tick += current_set_ticks;
+static void Systick_Handler(void) {
+  *(volatile uint64_t *)(CLIC_CTRL_ADDR + CLIC_MTIMECMP) = next_compare_tick;
+  systick_callback();
+  next_compare_tick += current_set_ticks;
 }
 
 /**
@@ -41,38 +40,36 @@ static void Systick_Handler(void)
  * @param time
  * @param interruptFun
  */
-void mtimer_set_alarm_time(uint64_t ticks, void (*interruptfun)(void))
-{
-    CPU_Interrupt_Disable(MTIME_IRQn);
+void mtimer_set_alarm_time(uint64_t ticks, void (*interruptfun)(void)) {
+  CPU_Interrupt_Disable(MTIME_IRQn);
 
-    uint32_t ulCurrentTimeHigh, ulCurrentTimeLow;
-    volatile uint32_t *const pulTimeHigh = (volatile uint32_t *const)(CLIC_CTRL_ADDR + CLIC_MTIME + 4);
-    volatile uint32_t *const pulTimeLow = (volatile uint32_t *const)(CLIC_CTRL_ADDR + CLIC_MTIME);
-    volatile uint32_t ulHartId = 0;
+  uint32_t                 ulCurrentTimeHigh, ulCurrentTimeLow;
+  volatile uint32_t *const pulTimeHigh = (volatile uint32_t *const)(CLIC_CTRL_ADDR + CLIC_MTIME + 4);
+  volatile uint32_t *const pulTimeLow  = (volatile uint32_t *const)(CLIC_CTRL_ADDR + CLIC_MTIME);
+  volatile uint32_t        ulHartId    = 0;
 
-    current_set_ticks = ticks;
-    systick_callback = interruptfun;
+  current_set_ticks = ticks;
+  systick_callback  = interruptfun;
 
-    __asm volatile("csrr %0, mhartid"
-                   : "=r"(ulHartId));
+  __asm volatile("csrr %0, mhartid" : "=r"(ulHartId));
 
-    do {
-        ulCurrentTimeHigh = *pulTimeHigh;
-        ulCurrentTimeLow = *pulTimeLow;
-    } while (ulCurrentTimeHigh != *pulTimeHigh);
+  do {
+    ulCurrentTimeHigh = *pulTimeHigh;
+    ulCurrentTimeLow  = *pulTimeLow;
+  } while (ulCurrentTimeHigh != *pulTimeHigh);
 
-    next_compare_tick = (uint64_t)ulCurrentTimeHigh;
-    next_compare_tick <<= 32ULL;
-    next_compare_tick |= (uint64_t)ulCurrentTimeLow;
-    next_compare_tick += (uint64_t)current_set_ticks;
+  next_compare_tick = (uint64_t)ulCurrentTimeHigh;
+  next_compare_tick <<= 32ULL;
+  next_compare_tick |= (uint64_t)ulCurrentTimeLow;
+  next_compare_tick += (uint64_t)current_set_ticks;
 
-    *(volatile uint64_t *)(CLIC_CTRL_ADDR + CLIC_MTIMECMP) = next_compare_tick;
+  *(volatile uint64_t *)(CLIC_CTRL_ADDR + CLIC_MTIMECMP) = next_compare_tick;
 
-    /* Prepare the time to use after the next tick interrupt. */
-    next_compare_tick += (uint64_t)current_set_ticks;
+  /* Prepare the time to use after the next tick interrupt. */
+  next_compare_tick += (uint64_t)current_set_ticks;
 
-    Interrupt_Handler_Register(MTIME_IRQn, Systick_Handler);
-    CPU_Interrupt_Enable(MTIME_IRQn);
+  Interrupt_Handler_Register(MTIME_IRQn, Systick_Handler);
+  CPU_Interrupt_Enable(MTIME_IRQn);
 }
 
 /**
@@ -80,64 +77,58 @@ void mtimer_set_alarm_time(uint64_t ticks, void (*interruptfun)(void))
  *
  * @return uint64_t
  */
-uint64_t mtimer_get_time_ms()
-{
-    return mtimer_get_time_us() / 1000;
-}
+uint64_t mtimer_get_time_ms() { return mtimer_get_time_us() / 1000; }
 /**
  * @brief
  *
  * @return uint64_t
  */
-uint64_t mtimer_get_time_us()
-{
-    uint32_t tmpValLow, tmpValHigh, tmpValHigh1;
+uint64_t mtimer_get_time_us() {
+  uint32_t tmpValLow, tmpValHigh, tmpValHigh1;
 
-    do {
-        tmpValLow = *(volatile uint32_t *)(CLIC_CTRL_ADDR + CLIC_MTIME);
-        tmpValHigh = *(volatile uint32_t *)(CLIC_CTRL_ADDR + CLIC_MTIME + 4);
-        tmpValHigh1 = *(volatile uint32_t *)(CLIC_CTRL_ADDR + CLIC_MTIME + 4);
-    } while (tmpValHigh != tmpValHigh1);
+  do {
+    tmpValLow   = *(volatile uint32_t *)(CLIC_CTRL_ADDR + CLIC_MTIME);
+    tmpValHigh  = *(volatile uint32_t *)(CLIC_CTRL_ADDR + CLIC_MTIME + 4);
+    tmpValHigh1 = *(volatile uint32_t *)(CLIC_CTRL_ADDR + CLIC_MTIME + 4);
+  } while (tmpValHigh != tmpValHigh1);
 
-    return (((uint64_t)tmpValHigh << 32) + tmpValLow);
+  return (((uint64_t)tmpValHigh << 32) + tmpValLow);
 }
 /**
  * @brief
  *
  * @param time
  */
-void mtimer_delay_ms(uint32_t time)
-{
-    uint64_t cnt = 0;
-    uint32_t clock = SystemCoreClockGet();
-    uint64_t startTime = mtimer_get_time_ms();
-
-    while (mtimer_get_time_ms() - startTime < time) {
-        cnt++;
-
-        /* assume BFLB_BSP_Get_Time_Ms take 32 cycles*/
-        if (cnt > (time * (clock >> (10 + 5))) * 2) {
-            break;
-        }
+void mtimer_delay_ms(uint32_t time) {
+  uint64_t cnt       = 0;
+  uint32_t clock     = SystemCoreClockGet();
+  uint64_t startTime = mtimer_get_time_ms();
+
+  while (mtimer_get_time_ms() - startTime < time) {
+    cnt++;
+
+    /* assume BFLB_BSP_Get_Time_Ms take 32 cycles*/
+    if (cnt > (time * (clock >> (10 + 5))) * 2) {
+      break;
     }
+  }
 }
 /**
  * @brief
  *
  * @param time
  */
-void mtimer_delay_us(uint32_t time)
-{
-    uint64_t cnt = 0;
-    uint32_t clock = SystemCoreClockGet();
-    uint64_t startTime = mtimer_get_time_us();
-
-    while (mtimer_get_time_us() - startTime < time) {
-        cnt++;
-
-        /* assume BFLB_BSP_Get_Time_Ms take 32 cycles*/
-        if (cnt > (time * (clock >> (10 + 5))) * 2) {
-            break;
-        }
+void mtimer_delay_us(uint32_t time) {
+  uint64_t cnt       = 0;
+  uint32_t clock     = SystemCoreClockGet();
+  uint64_t startTime = mtimer_get_time_us();
+
+  while (mtimer_get_time_us() - startTime < time) {
+    cnt++;
+
+    /* assume BFLB_BSP_Get_Time_Ms take 32 cycles*/
+    if (cnt > (time * (clock >> (10 + 5))) * 2) {
+      break;
     }
+  }
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm_util.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm_util.c
index 4636c9d1be..0a20b7195e 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm_util.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm_util.c
@@ -21,12 +21,12 @@
  *
  */
 
+#include "hal_pm_util.h"
+#include "bl702_glb.h"
 #include "bl702_romdriver.h"
 #include "bl702_sf_ctrl.h"
-#include "bl702_glb.h"
 #include "hal_clock.h"
 #include "hal_pm.h"
-#include "hal_pm_util.h"
 
 /* Cache Way Disable, will get from l1c register */
 extern uint8_t cacheWayDisable;
@@ -54,30 +54,29 @@ void (*hardware_recovery)(void) = NULL;
  *
  * @note If necessary,please application layer call vTaskStepTick,
  */
-uint32_t hal_pds_enter_with_time_compensation(uint32_t pdsLevel, uint32_t pdsSleepCycles)
-{
-    uint32_t rtcLowBeforeSleep = 0, rtcHighBeforeSleep = 0;
-    uint32_t rtcLowAfterSleep = 0, rtcHighAfterSleep = 0;
-    uint32_t actualSleepDuration_32768cycles = 0;
-    uint32_t actualSleepDuration_ms = 0;
+uint32_t hal_pds_enter_with_time_compensation(uint32_t pdsLevel, uint32_t pdsSleepCycles) {
+  uint32_t rtcLowBeforeSleep = 0, rtcHighBeforeSleep = 0;
+  uint32_t rtcLowAfterSleep = 0, rtcHighAfterSleep = 0;
+  uint32_t actualSleepDuration_32768cycles = 0;
+  uint32_t actualSleepDuration_ms          = 0;
 
-    pm_set_wakeup_callback(pm_pds_fastboot_entry);
+  pm_set_wakeup_callback(pm_pds_fastboot_entry);
 
-    HBN_Get_RTC_Timer_Val(&rtcLowBeforeSleep, &rtcHighBeforeSleep);
+  HBN_Get_RTC_Timer_Val(&rtcLowBeforeSleep, &rtcHighBeforeSleep);
 
-    pm_pds31_fast_mode_enter(pdsLevel, pdsSleepCycles);
+  pm_pds31_fast_mode_enter(pdsLevel, pdsSleepCycles);
 
-    HBN_Get_RTC_Timer_Val(&rtcLowAfterSleep, &rtcHighAfterSleep);
+  HBN_Get_RTC_Timer_Val(&rtcLowAfterSleep, &rtcHighAfterSleep);
 
-    CHECK_PARAM((rtcHighAfterSleep - rtcHighBeforeSleep) <= 1); // make sure sleep less than 1 hour (2^32 us > 1 hour)
+  CHECK_PARAM((rtcHighAfterSleep - rtcHighBeforeSleep) <= 1); // make sure sleep less than 1 hour (2^32 us > 1 hour)
 
-    actualSleepDuration_32768cycles = (rtcLowAfterSleep - rtcLowBeforeSleep);
+  actualSleepDuration_32768cycles = (rtcLowAfterSleep - rtcLowBeforeSleep);
 
-    actualSleepDuration_ms = (actualSleepDuration_32768cycles >> 5) - (actualSleepDuration_32768cycles >> 11) - (actualSleepDuration_32768cycles >> 12);
+  actualSleepDuration_ms = (actualSleepDuration_32768cycles >> 5) - (actualSleepDuration_32768cycles >> 11) - (actualSleepDuration_32768cycles >> 12);
 
-    // vTaskStepTick(actualSleepDuration_ms);
+  // vTaskStepTick(actualSleepDuration_ms);
 
-    return actualSleepDuration_ms;
+  return actualSleepDuration_ms;
 }
 /**
  * @brief get delay value of spi flash init
@@ -85,58 +84,56 @@ uint32_t hal_pds_enter_with_time_compensation(uint32_t pdsLevel, uint32_t pdsSle
  * @param delay_index
  * @return uint8_t
  */
-static uint8_t ATTR_PDS_RAM_SECTION bflb_spi_flash_get_delay_val(uint8_t delay_index)
-{
-    switch (delay_index) {
-        case 0:
-            return 0x00;
-        case 1:
-            return 0x80;
-        case 2:
-            return 0xc0;
-        case 3:
-            return 0xe0;
-        case 4:
-            return 0xf0;
-        case 5:
-            return 0xf8;
-        case 6:
-            return 0xfc;
-        case 7:
-            return 0xfe;
-        default:
-            return 0x00;
-    }
+static uint8_t ATTR_PDS_RAM_SECTION bflb_spi_flash_get_delay_val(uint8_t delay_index) {
+  switch (delay_index) {
+  case 0:
+    return 0x00;
+  case 1:
+    return 0x80;
+  case 2:
+    return 0xc0;
+  case 3:
+    return 0xe0;
+  case 4:
+    return 0xf0;
+  case 5:
+    return 0xf8;
+  case 6:
+    return 0xfc;
+  case 7:
+    return 0xfe;
+  default:
+    return 0x00;
+  }
 }
 /**
  * @brief config spi flash
  *
  * @param pFlashCfg flash parameter
  */
-static void ATTR_PDS_RAM_SECTION bflb_spi_flash_set_sf_ctrl(SPI_Flash_Cfg_Type *pFlashCfg)
-{
-    SF_Ctrl_Cfg_Type sfCtrlCfg;
-    uint8_t delay_index;
-
-    sfCtrlCfg.owner = SF_CTRL_OWNER_SAHB;
-
-    /* bit0-3 for clk delay */
-    sfCtrlCfg.clkDelay = (pFlashCfg->clkDelay & 0x0f);
-    /* bit0 for clk invert */
-    sfCtrlCfg.clkInvert = pFlashCfg->clkInvert & 0x01;
-    /* bit1 for rx clk invert */
-    sfCtrlCfg.rxClkInvert = (pFlashCfg->clkInvert >> 1) & 0x01;
-    /* bit4-6 for do delay */
-    delay_index = (pFlashCfg->clkDelay >> 4) & 0x07;
-    sfCtrlCfg.doDelay = bflb_spi_flash_get_delay_val(delay_index);
-    /* bit2-4 for di delay */
-    delay_index = (pFlashCfg->clkInvert >> 2) & 0x07;
-    sfCtrlCfg.diDelay = bflb_spi_flash_get_delay_val(delay_index);
-    /* bit5-7 for oe delay */
-    delay_index = (pFlashCfg->clkInvert >> 5) & 0x07;
-    sfCtrlCfg.oeDelay = bflb_spi_flash_get_delay_val(delay_index);
-
-    RomDriver_SFlash_Init(&sfCtrlCfg);
+static void ATTR_PDS_RAM_SECTION bflb_spi_flash_set_sf_ctrl(SPI_Flash_Cfg_Type *pFlashCfg) {
+  SF_Ctrl_Cfg_Type sfCtrlCfg;
+  uint8_t          delay_index;
+
+  sfCtrlCfg.owner = SF_CTRL_OWNER_SAHB;
+
+  /* bit0-3 for clk delay */
+  sfCtrlCfg.clkDelay = (pFlashCfg->clkDelay & 0x0f);
+  /* bit0 for clk invert */
+  sfCtrlCfg.clkInvert = pFlashCfg->clkInvert & 0x01;
+  /* bit1 for rx clk invert */
+  sfCtrlCfg.rxClkInvert = (pFlashCfg->clkInvert >> 1) & 0x01;
+  /* bit4-6 for do delay */
+  delay_index       = (pFlashCfg->clkDelay >> 4) & 0x07;
+  sfCtrlCfg.doDelay = bflb_spi_flash_get_delay_val(delay_index);
+  /* bit2-4 for di delay */
+  delay_index       = (pFlashCfg->clkInvert >> 2) & 0x07;
+  sfCtrlCfg.diDelay = bflb_spi_flash_get_delay_val(delay_index);
+  /* bit5-7 for oe delay */
+  delay_index       = (pFlashCfg->clkInvert >> 5) & 0x07;
+  sfCtrlCfg.oeDelay = bflb_spi_flash_get_delay_val(delay_index);
+
+  RomDriver_SFlash_Init(&sfCtrlCfg);
 }
 
 /**
@@ -145,177 +142,168 @@ static void ATTR_PDS_RAM_SECTION bflb_spi_flash_set_sf_ctrl(SPI_Flash_Cfg_Type *
  * @param media_boot
  * @return int32_t
  */
-int32_t ATTR_PDS_RAM_SECTION pm_spi_flash_init(uint8_t media_boot)
-{
-    uint32_t stat;
-    uint32_t jdecId = 0;
-    uint32_t flash_read_try = 0;
-
-    /*use fclk as flash clok */
-    RomDriver_GLB_Set_SF_CLK(1, GLB_SFLASH_CLK_XCLK, 0); // 32M
-    RomDriver_SF_Ctrl_Set_Clock_Delay(0);
-
-    bflb_spi_flash_set_sf_ctrl(flash_cfg);
-
-    /* Wake flash up from power down */
-    RomDriver_SFlash_Releae_Powerdown(flash_cfg);
-    //ARCH_Delay_US(15*((pFlashCfg->pdDelay&0x7)+1));
-    RomDriver_BL702_Delay_US(120);
-
-    do {
-        if (flash_read_try > 4) {
-            // bflb_bootrom_printd("Flash read id TO\r\n");
-            break;
-        } else if (flash_read_try > 0) {
-            RomDriver_BL702_Delay_US(500);
-        }
-
-        // bflb_bootrom_printd("reset flash\r\n");
-        /* Exit form continous read for accepting command */
-        RomDriver_SFlash_Reset_Continue_Read(flash_cfg);
-        /* Send software reset command(80bv has no this command)to deburst wrap for ISSI like */
-        RomDriver_SFlash_Software_Reset(flash_cfg);
-        /* Disable burst may be removed(except for 80BV) and only work with winbond,but just for make sure */
-        RomDriver_SFlash_Write_Enable(flash_cfg);
-        /* For disable command that is setting register instaed of send command, we need write enable */
-        RomDriver_SFlash_DisableBurstWrap(flash_cfg);
-
-        stat = RomDriver_SFlash_SetSPIMode(SF_CTRL_SPI_MODE);
-        if (SUCCESS != stat) {
-            // bflb_bootrom_printe("enter spi mode fail %d\r\n", stat);
-            // return BFLB_BOOTROM_FLASH_INIT_ERROR;
-            return -1;
-        }
-
-        RomDriver_SFlash_GetJedecId(flash_cfg, (uint8_t *)&jdecId);
-
-        /* Dummy disable burstwrap for make sure */
-        RomDriver_SFlash_Write_Enable(flash_cfg);
-        /* For disable command that is setting register instead of send command, we need write enable */
-        RomDriver_SFlash_DisableBurstWrap(flash_cfg);
-
-        jdecId = jdecId & 0xffffff;
-        // bflb_bootrom_printd("ID =%08x\r\n", jdecId);
-        flash_read_try++;
-    } while ((jdecId & 0x00ffff) == 0 || (jdecId & 0xffff00) == 0 || (jdecId & 0x00ffff) == 0xffff || (jdecId & 0xffff00) == 0xffff00);
-
-    /*clear offset setting*/
-
-    // reset image offset
-    BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET, flash_offset);
-
-    /* set read mode */
-    if ((flash_cfg->ioMode & 0x0f) == SF_CTRL_QO_MODE || (flash_cfg->ioMode & 0x0f) == SF_CTRL_QIO_MODE) {
-        stat = RomDriver_SFlash_Qspi_Enable(flash_cfg);
+int32_t ATTR_PDS_RAM_SECTION pm_spi_flash_init(uint8_t media_boot) {
+  uint32_t stat;
+  uint32_t jdecId         = 0;
+  uint32_t flash_read_try = 0;
+
+  /*use fclk as flash clok */
+  RomDriver_GLB_Set_SF_CLK(1, GLB_SFLASH_CLK_XCLK, 0); // 32M
+  RomDriver_SF_Ctrl_Set_Clock_Delay(0);
+
+  bflb_spi_flash_set_sf_ctrl(flash_cfg);
+
+  /* Wake flash up from power down */
+  RomDriver_SFlash_Releae_Powerdown(flash_cfg);
+  // ARCH_Delay_US(15*((pFlashCfg->pdDelay&0x7)+1));
+  RomDriver_BL702_Delay_US(120);
+
+  do {
+    if (flash_read_try > 4) {
+      // bflb_bootrom_printd("Flash read id TO\r\n");
+      break;
+    } else if (flash_read_try > 0) {
+      RomDriver_BL702_Delay_US(500);
     }
 
-    if (media_boot) {
-        RomDriver_L1C_Set_Wrap(DISABLE);
-
-        RomDriver_SFlash_Cache_Read_Enable(flash_cfg, flash_cfg->ioMode & 0xf, 0, 0x00);
+    // bflb_bootrom_printd("reset flash\r\n");
+    /* Exit form continous read for accepting command */
+    RomDriver_SFlash_Reset_Continue_Read(flash_cfg);
+    /* Send software reset command(80bv has no this command)to deburst wrap for ISSI like */
+    RomDriver_SFlash_Software_Reset(flash_cfg);
+    /* Disable burst may be removed(except for 80BV) and only work with winbond,but just for make sure */
+    RomDriver_SFlash_Write_Enable(flash_cfg);
+    /* For disable command that is setting register instaed of send command, we need write enable */
+    RomDriver_SFlash_DisableBurstWrap(flash_cfg);
+
+    stat = RomDriver_SFlash_SetSPIMode(SF_CTRL_SPI_MODE);
+    if (SUCCESS != stat) {
+      // bflb_bootrom_printe("enter spi mode fail %d\r\n", stat);
+      // return BFLB_BOOTROM_FLASH_INIT_ERROR;
+      return -1;
     }
 
-    return jdecId;
+    RomDriver_SFlash_GetJedecId(flash_cfg, (uint8_t *)&jdecId);
+
+    /* Dummy disable burstwrap for make sure */
+    RomDriver_SFlash_Write_Enable(flash_cfg);
+    /* For disable command that is setting register instead of send command, we need write enable */
+    RomDriver_SFlash_DisableBurstWrap(flash_cfg);
+
+    jdecId = jdecId & 0xffffff;
+    // bflb_bootrom_printd("ID =%08x\r\n", jdecId);
+    flash_read_try++;
+  } while ((jdecId & 0x00ffff) == 0 || (jdecId & 0xffff00) == 0 || (jdecId & 0x00ffff) == 0xffff || (jdecId & 0xffff00) == 0xffff00);
+
+  /*clear offset setting*/
+
+  // reset image offset
+  BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET, flash_offset);
+
+  /* set read mode */
+  if ((flash_cfg->ioMode & 0x0f) == SF_CTRL_QO_MODE || (flash_cfg->ioMode & 0x0f) == SF_CTRL_QIO_MODE) {
+    stat = RomDriver_SFlash_Qspi_Enable(flash_cfg);
+  }
+
+  if (media_boot) {
+    RomDriver_L1C_Set_Wrap(DISABLE);
+
+    RomDriver_SFlash_Cache_Read_Enable(flash_cfg, flash_cfg->ioMode & 0xf, 0, 0x00);
+  }
+
+  return jdecId;
 }
 
 // can be placed in flash, here placed in pds section to reduce fast boot time
-static void ATTR_PDS_RAM_SECTION pm_pds_restore_cpu_reg(void)
-{
-    __asm__ __volatile__(
-        "la     a2,     __ld_pds_bak_addr\n\t"
-        "lw     ra,     0(a2)\n\t"
-        "lw     sp,     1*4(a2)\n\t"
-        "lw     tp,     2*4(a2)\n\t"
-        "lw     t0,     3*4(a2)\n\t"
-        "lw     t1,     4*4(a2)\n\t"
-        "lw     t2,     5*4(a2)\n\t"
-        "lw     fp,     6*4(a2)\n\t"
-        "lw     s1,     7*4(a2)\n\t"
-        "lw     a0,     8*4(a2)\n\t"
-        "lw     a1,     9*4(a2)\n\t"
-        "lw     a3,     10*4(a2)\n\t"
-        "lw     a4,     11*4(a2)\n\t"
-        "lw     a5,     12*4(a2)\n\t"
-        "lw     a6,     13*4(a2)\n\t"
-        "lw     a7,     14*4(a2)\n\t"
-        "lw     s2,     15*4(a2)\n\t"
-        "lw     s3,     16*4(a2)\n\t"
-        "lw     s4,     17*4(a2)\n\t"
-        "lw     s5,     18*4(a2)\n\t"
-        "lw     s6,     19*4(a2)\n\t"
-        "lw     s7,     20*4(a2)\n\t"
-        "lw     s8,     21*4(a2)\n\t"
-        "lw     s9,     22*4(a2)\n\t"
-        "lw     s10,    23*4(a2)\n\t"
-        "lw     s11,    24*4(a2)\n\t"
-        "lw     t3,     25*4(a2)\n\t"
-        "lw     t4,     26*4(a2)\n\t"
-        "lw     t5,     27*4(a2)\n\t"
-        "lw     t6,     28*4(a2)\n\t"
-        "csrw   mtvec,  a0\n\t"
-        "csrw   mstatus,a1\n\t"
-        "ret\n\t");
+static void ATTR_PDS_RAM_SECTION pm_pds_restore_cpu_reg(void) {
+  __asm__ __volatile__("la     a2,     __ld_pds_bak_addr\n\t"
+                       "lw     ra,     0(a2)\n\t"
+                       "lw     sp,     1*4(a2)\n\t"
+                       "lw     tp,     2*4(a2)\n\t"
+                       "lw     t0,     3*4(a2)\n\t"
+                       "lw     t1,     4*4(a2)\n\t"
+                       "lw     t2,     5*4(a2)\n\t"
+                       "lw     fp,     6*4(a2)\n\t"
+                       "lw     s1,     7*4(a2)\n\t"
+                       "lw     a0,     8*4(a2)\n\t"
+                       "lw     a1,     9*4(a2)\n\t"
+                       "lw     a3,     10*4(a2)\n\t"
+                       "lw     a4,     11*4(a2)\n\t"
+                       "lw     a5,     12*4(a2)\n\t"
+                       "lw     a6,     13*4(a2)\n\t"
+                       "lw     a7,     14*4(a2)\n\t"
+                       "lw     s2,     15*4(a2)\n\t"
+                       "lw     s3,     16*4(a2)\n\t"
+                       "lw     s4,     17*4(a2)\n\t"
+                       "lw     s5,     18*4(a2)\n\t"
+                       "lw     s6,     19*4(a2)\n\t"
+                       "lw     s7,     20*4(a2)\n\t"
+                       "lw     s8,     21*4(a2)\n\t"
+                       "lw     s9,     22*4(a2)\n\t"
+                       "lw     s10,    23*4(a2)\n\t"
+                       "lw     s11,    24*4(a2)\n\t"
+                       "lw     t3,     25*4(a2)\n\t"
+                       "lw     t4,     26*4(a2)\n\t"
+                       "lw     t5,     27*4(a2)\n\t"
+                       "lw     t6,     28*4(a2)\n\t"
+                       "csrw   mtvec,  a0\n\t"
+                       "csrw   mstatus,a1\n\t"
+                       "ret\n\t");
 }
-void ATTR_PDS_RAM_SECTION sf_io_select(void)
-{
-    uint32_t tmpVal = 0;
-    uint8_t flashCfg = 0;
-    uint8_t psramCfg = 0;
-    uint8_t isInternalFlash = 0;
-    uint8_t isInternalPsram = 0;
-
-    /* SF io select from efuse value */
-    tmpVal = BL_RD_WORD(0x40007074);
-    flashCfg = ((tmpVal >> 26) & 7);
-    psramCfg = ((tmpVal >> 24) & 3);
-    if (flashCfg == 1 || flashCfg == 2) {
-        isInternalFlash = 1;
-    } else {
-        isInternalFlash = 0;
-    }
-    if (psramCfg == 1) {
-        isInternalPsram = 1;
-    } else {
-        isInternalPsram = 0;
-    }
-    tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO);
-    if (isInternalFlash == 1 && isInternalPsram == 0) {
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x3f);
-    } else {
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x00);
-    }
-    BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal);
+void ATTR_PDS_RAM_SECTION sf_io_select(void) {
+  uint32_t tmpVal          = 0;
+  uint8_t  flashCfg        = 0;
+  uint8_t  psramCfg        = 0;
+  uint8_t  isInternalFlash = 0;
+  uint8_t  isInternalPsram = 0;
+
+  /* SF io select from efuse value */
+  tmpVal   = BL_RD_WORD(0x40007074);
+  flashCfg = ((tmpVal >> 26) & 7);
+  psramCfg = ((tmpVal >> 24) & 3);
+  if (flashCfg == 1 || flashCfg == 2) {
+    isInternalFlash = 1;
+  } else {
+    isInternalFlash = 0;
+  }
+  if (psramCfg == 1) {
+    isInternalPsram = 1;
+  } else {
+    isInternalPsram = 0;
+  }
+  tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO);
+  if (isInternalFlash == 1 && isInternalPsram == 0) {
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x3f);
+  } else {
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x00);
+  }
+  BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal);
 }
 // must be placed in pds section
-void ATTR_PDS_RAM_SECTION pm_pds_fastboot_entry(void)
-{
-    // reload gp register
-    __asm__ __volatile__(
-        ".option push\n\t"
-        ".option norelax\n\t"
-        "la gp, __global_pointer$\n\t"
-        ".option pop\n\t");
+void ATTR_PDS_RAM_SECTION pm_pds_fastboot_entry(void) {
+  // reload gp register
+  __asm__ __volatile__(".option push\n\t"
+                       ".option norelax\n\t"
+                       "la gp, __global_pointer$\n\t"
+                       ".option pop\n\t");
 
 #if XTAL_TYPE != INTERNAL_RC_32M
-    /* power on Xtal_32M*/
-    (*(volatile uint32_t *)(AON_BASE + AON_RF_TOP_AON_OFFSET)) |= (3 << 4);
+  /* power on Xtal_32M*/
+  (*(volatile uint32_t *)(AON_BASE + AON_RF_TOP_AON_OFFSET)) |= (3 << 4);
 #endif
 
-    // recovery flash pad and param
-    RomDriver_SF_Cfg_Init_Flash_Gpio(0, 1);
-    pm_spi_flash_init(1);
-    sf_io_select();
+  // recovery flash pad and param
+  RomDriver_SF_Cfg_Init_Flash_Gpio(0, 1);
+  pm_spi_flash_init(1);
+  sf_io_select();
 
-    /* Recovery hardware , include tcm , gpio and clock */
-    if (hardware_recovery) {
-        hardware_recovery();
-    }
+  /* Recovery hardware , include tcm , gpio and clock */
+  if (hardware_recovery) {
+    hardware_recovery();
+  }
 
-    // Restore cpu registers
-    pm_pds_restore_cpu_reg();
+  // Restore cpu registers
+  pm_pds_restore_cpu_reg();
 }
 
-void pm_set_hardware_recovery_callback(void (*hardware_recovery_cb)(void))
-{
-    hardware_recovery = hardware_recovery_cb;
-}
\ No newline at end of file
+void pm_set_hardware_recovery_callback(void (*hardware_recovery_cb)(void)) { hardware_recovery = hardware_recovery_cb; }
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_rtc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_rtc.c
index 9b4a4368dd..d177b97605 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_rtc.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_rtc.c
@@ -29,73 +29,68 @@ static uint64_t current_timestamp = 0;
  *
  * @param sleep_time
  */
-void rtc_init(uint64_t sleep_time)
-{
-    uint32_t tmpVal;
-    uint32_t comp_l, comp_h;
+void rtc_init(uint64_t sleep_time) {
+  uint32_t tmpVal;
+  uint32_t comp_l, comp_h;
 
-    /* Clear & Disable RTC counter */
-    tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL);
-    /* Clear RTC control bit0 */
-    BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal & 0xfffffff0);
+  /* Clear & Disable RTC counter */
+  tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL);
+  /* Clear RTC control bit0 */
+  BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal & 0xfffffff0);
 
-    /* Get current RTC timer */
-    /* Tigger RTC val read */
-    tmpVal = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H);
-    tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
-    BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
-    tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
-    BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
+  /* Get current RTC timer */
+  /* Tigger RTC val read */
+  tmpVal = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H);
+  tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
+  BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
+  tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
+  BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
 
-    /* Read RTC val */
-    comp_l = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_L);
-    comp_h = (BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H) & 0xff);
+  /* Read RTC val */
+  comp_l = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_L);
+  comp_h = (BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H) & 0xff);
 
-    /* calculate RTC Comp time */
-    comp_l += (uint32_t)((sleep_time * 32768) & 0xFFFFFFFF);
-    comp_h += (uint32_t)(((sleep_time * 32768) >> 32) & 0xFFFFFFFF);
+  /* calculate RTC Comp time */
+  comp_l += (uint32_t)((sleep_time * 32768) & 0xFFFFFFFF);
+  comp_h += (uint32_t)(((sleep_time * 32768) >> 32) & 0xFFFFFFFF);
 
-    /* Set RTC Comp time  */
-    BL_WR_REG(HBN_BASE, HBN_TIME_L, comp_l);
-    BL_WR_REG(HBN_BASE, HBN_TIME_H, comp_h & 0xff);
+  /* Set RTC Comp time  */
+  BL_WR_REG(HBN_BASE, HBN_TIME_L, comp_l);
+  BL_WR_REG(HBN_BASE, HBN_TIME_H, comp_h & 0xff);
 
-    tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL);
-    /* Set interrupt delay option */
-    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_RTC_DLY_OPTION, HBN_RTC_INT_DELAY_0T);
-    /* Set RTC compare mode */
-    tmpVal |= (HBN_RTC_COMP_BIT0_39 << 1);
-    BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal);
+  tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL);
+  /* Set interrupt delay option */
+  tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_RTC_DLY_OPTION, HBN_RTC_INT_DELAY_0T);
+  /* Set RTC compare mode */
+  tmpVal |= (HBN_RTC_COMP_BIT0_39 << 1);
+  BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal);
 
-    /* Enable RTC Counter */
-    tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL);
-    /* Set RTC control bit0 */
-    BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal | 0x01);
+  /* Enable RTC Counter */
+  tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL);
+  /* Set RTC control bit0 */
+  BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal | 0x01);
 }
 
-void rtc_set_timestamp(uint64_t time_stamp)
-{
-    current_timestamp = time_stamp;
-}
+void rtc_set_timestamp(uint64_t time_stamp) { current_timestamp = time_stamp; }
 /**
-* @bref Get rtc value
-*
-*/
-uint64_t rtc_get_timestamp(void)
-{
-    uint32_t tmpVal;
-    uint64_t time_l;
-    uint64_t time_h;
+ * @bref Get rtc value
+ *
+ */
+uint64_t rtc_get_timestamp(void) {
+  uint32_t tmpVal;
+  uint64_t time_l;
+  uint64_t time_h;
 
-    /* Tigger RTC val read */
-    tmpVal = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H);
-    tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
-    BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
-    tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
-    BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
+  /* Tigger RTC val read */
+  tmpVal = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H);
+  tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
+  BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
+  tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
+  BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
 
-    /* Read RTC val */
-    time_l = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_L);
-    time_h = (BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H) & 0xff);
+  /* Read RTC val */
+  time_l = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_L);
+  time_h = (BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H) & 0xff);
 
-    return (((time_h << 32 | time_l) >> 15) + current_timestamp);
+  return (((time_h << 32 | time_l) >> 15) + current_timestamp);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_aes.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_aes.c
index 7cc6410a9e..833164c5e2 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_aes.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_aes.c
@@ -25,95 +25,87 @@
 
 static SEC_Eng_AES_Ctx aesCtx;
 
-int sec_aes_init(sec_aes_handle_t *handle, sec_aes_type aes_tye, sec_aes_key_type key_type)
-{
-    handle->aes_type = aes_tye;
-    handle->key_type = key_type;
+int sec_aes_init(sec_aes_handle_t *handle, sec_aes_type aes_tye, sec_aes_key_type key_type) {
+  handle->aes_type = aes_tye;
+  handle->key_type = key_type;
 
-    return 0;
+  return 0;
 }
 
-static SEC_ENG_AES_Key_Type sec_aes_get_key_type(sec_aes_handle_t *handle)
-{
-    SEC_ENG_AES_Key_Type type = 0;
+static SEC_ENG_AES_Key_Type sec_aes_get_key_type(sec_aes_handle_t *handle) {
+  SEC_ENG_AES_Key_Type type = 0;
 
-    switch (handle->key_type) {
-        case SEC_AES_KEY_128:
-            type = SEC_ENG_AES_KEY_128BITS;
-            break;
+  switch (handle->key_type) {
+  case SEC_AES_KEY_128:
+    type = SEC_ENG_AES_KEY_128BITS;
+    break;
 
-        case SEC_AES_KEY_256:
-            type = SEC_ENG_AES_KEY_256BITS;
-            break;
+  case SEC_AES_KEY_256:
+    type = SEC_ENG_AES_KEY_256BITS;
+    break;
 
-        case SEC_AES_KEY_192:
-            type = SEC_ENG_AES_KEY_192BITS;
-            break;
+  case SEC_AES_KEY_192:
+    type = SEC_ENG_AES_KEY_192BITS;
+    break;
 
-        default:
-            return SEC_ENG_AES_KEY_128BITS;
-    }
+  default:
+    return SEC_ENG_AES_KEY_128BITS;
+  }
 
-    return type;
+  return type;
 }
 
-int sec_aes_setkey(sec_aes_handle_t *handle, const uint8_t *key, uint8_t key_len, const uint8_t *nonce, uint8_t dir)
-{
-    SEC_ENG_AES_Key_Type type = sec_aes_get_key_type(handle);
-
-    switch (handle->aes_type) {
-        case SEC_AES_CBC:
-            Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID0);
-            Sec_Eng_AES_Init(&aesCtx, SEC_ENG_AES_ID0, SEC_ENG_AES_CBC, type,
-                             SEC_AES_DIR_ENCRYPT == dir ? SEC_ENG_AES_ENCRYPTION : SEC_ENG_AES_DECRYPTION);
-            break;
-
-        case SEC_AES_CTR:
-            Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID0);
-            Sec_Eng_AES_Init(&aesCtx, SEC_ENG_AES_ID0, SEC_ENG_AES_CTR, type,
-                             SEC_AES_DIR_ENCRYPT == dir ? SEC_ENG_AES_ENCRYPTION : SEC_ENG_AES_DECRYPTION);
-            break;
-
-        case SEC_AES_ECB:
-            break;
-
-        default:
-            return -1;
-    }
-
-    /* if key len is 0, means key is from efuse and *key value is key_sel value */
-    if (key_len == 0) {
-        Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID0, SEC_ENG_AES_KEY_HW, key, nonce);
-    } else {
-        Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID0, SEC_ENG_AES_KEY_SW, key, nonce);
-    }
-
-    return 0;
+int sec_aes_setkey(sec_aes_handle_t *handle, const uint8_t *key, uint8_t key_len, const uint8_t *nonce, uint8_t dir) {
+  SEC_ENG_AES_Key_Type type = sec_aes_get_key_type(handle);
+
+  switch (handle->aes_type) {
+  case SEC_AES_CBC:
+    Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID0);
+    Sec_Eng_AES_Init(&aesCtx, SEC_ENG_AES_ID0, SEC_ENG_AES_CBC, type, SEC_AES_DIR_ENCRYPT == dir ? SEC_ENG_AES_ENCRYPTION : SEC_ENG_AES_DECRYPTION);
+    break;
+
+  case SEC_AES_CTR:
+    Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID0);
+    Sec_Eng_AES_Init(&aesCtx, SEC_ENG_AES_ID0, SEC_ENG_AES_CTR, type, SEC_AES_DIR_ENCRYPT == dir ? SEC_ENG_AES_ENCRYPTION : SEC_ENG_AES_DECRYPTION);
+    break;
+
+  case SEC_AES_ECB:
+    break;
+
+  default:
+    return -1;
+  }
+
+  /* if key len is 0, means key is from efuse and *key value is key_sel value */
+  if (key_len == 0) {
+    Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID0, SEC_ENG_AES_KEY_HW, key, nonce);
+  } else {
+    Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID0, SEC_ENG_AES_KEY_SW, key, nonce);
+  }
+
+  return 0;
 }
 
-int sec_aes_encrypt(sec_aes_handle_t *handle, const uint8_t *in, uint32_t len, size_t offset, uint8_t *out)
-{
-    if (SUCCESS != Sec_Eng_AES_Crypt(&aesCtx, SEC_ENG_AES_ID0, in, len, out)) {
-        return -1;
-    }
+int sec_aes_encrypt(sec_aes_handle_t *handle, const uint8_t *in, uint32_t len, size_t offset, uint8_t *out) {
+  if (SUCCESS != Sec_Eng_AES_Crypt(&aesCtx, SEC_ENG_AES_ID0, in, len, out)) {
+    return -1;
+  }
 
-    return 0;
+  return 0;
 }
 
-int sec_aes_decrypt(sec_aes_handle_t *handle, const uint8_t *in, uint32_t len, size_t offset, uint8_t *out)
-{
-    if (SUCCESS != Sec_Eng_AES_Crypt(&aesCtx, SEC_ENG_AES_ID0, in, len, out)) {
-        return -1;
-    }
+int sec_aes_decrypt(sec_aes_handle_t *handle, const uint8_t *in, uint32_t len, size_t offset, uint8_t *out) {
+  if (SUCCESS != Sec_Eng_AES_Crypt(&aesCtx, SEC_ENG_AES_ID0, in, len, out)) {
+    return -1;
+  }
 
-    return 0;
+  return 0;
 }
 
-int sec_aes_deinit(sec_aes_handle_t *handle)
-{
-    Sec_Eng_AES_Finish(SEC_ENG_AES_ID0);
+int sec_aes_deinit(sec_aes_handle_t *handle) {
+  Sec_Eng_AES_Finish(SEC_ENG_AES_ID0);
 
-    memset(handle, 0, sizeof(sec_aes_handle_t));
+  memset(handle, 0, sizeof(sec_aes_handle_t));
 
-    return 0;
+  return 0;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_dsa.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_dsa.c
index 3929b90d6b..c9e6f07137 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_dsa.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_dsa.c
@@ -23,12 +23,12 @@
 #include "hal_sec_dsa.h"
 #include "bl702_sec_eng.h"
 
-//#define DSA_DBG                                   1
-//#define DSA_DBG_DETAIL                            1
+// #define DSA_DBG                                   1
+// #define DSA_DBG_DETAIL                            1
 void bflb_platform_dump(uint8_t *data, uint32_t len);
 
 #if (defined(DSA_DBG) || defined(DSA_DBG_DETAIL))
-uint32_t pka_tmp[64] = { 0 };
+uint32_t pka_tmp[64] = {0};
 #endif
 
 /*
@@ -43,44 +43,43 @@ h=qInv*(m1-m2)%p
 m=m2+h*q
 m=c^d
 */
-static SEC_ENG_PKA_REG_SIZE_Type sec_dsa_get_reg_size(uint32_t size)
-{
-    switch (size) {
-        case 64:
-            return SEC_ENG_PKA_REG_SIZE_8;
+static SEC_ENG_PKA_REG_SIZE_Type sec_dsa_get_reg_size(uint32_t size) {
+  switch (size) {
+  case 64:
+    return SEC_ENG_PKA_REG_SIZE_8;
 
-        case 128:
-            return SEC_ENG_PKA_REG_SIZE_16;
+  case 128:
+    return SEC_ENG_PKA_REG_SIZE_16;
 
-        case 256:
-            return SEC_ENG_PKA_REG_SIZE_32;
-
-        case 512:
-            return SEC_ENG_PKA_REG_SIZE_64;
+  case 256:
+    return SEC_ENG_PKA_REG_SIZE_32;
 
-        case 768:
-            return SEC_ENG_PKA_REG_SIZE_96;
+  case 512:
+    return SEC_ENG_PKA_REG_SIZE_64;
 
-        case 1024:
-            return SEC_ENG_PKA_REG_SIZE_128;
+  case 768:
+    return SEC_ENG_PKA_REG_SIZE_96;
 
-        case 1536:
-            return SEC_ENG_PKA_REG_SIZE_192;
+  case 1024:
+    return SEC_ENG_PKA_REG_SIZE_128;
 
-        case 2048:
-            return SEC_ENG_PKA_REG_SIZE_256;
+  case 1536:
+    return SEC_ENG_PKA_REG_SIZE_192;
 
-        case 3072:
-            return SEC_ENG_PKA_REG_SIZE_384;
+  case 2048:
+    return SEC_ENG_PKA_REG_SIZE_256;
 
-        case 4096:
-            return SEC_ENG_PKA_REG_SIZE_512;
+  case 3072:
+    return SEC_ENG_PKA_REG_SIZE_384;
 
-        default:
-            return SEC_ENG_PKA_REG_SIZE_32;
-    }
+  case 4096:
+    return SEC_ENG_PKA_REG_SIZE_512;
 
+  default:
     return SEC_ENG_PKA_REG_SIZE_32;
+  }
+
+  return SEC_ENG_PKA_REG_SIZE_32;
 }
 
 /* c code:
@@ -93,151 +92,138 @@ while b:
     base = base * base % c
 return number
 */
-int sec_dsa_mexp_binary(uint32_t size, const uint32_t *a, const uint32_t *b, const uint32_t *c, uint32_t *r)
-{
-    uint32_t i, j, k;
-    uint32_t tmp;
-    uint32_t isOne = 0;
-    uint8_t *p = (uint8_t *)b;
-    SEC_ENG_PKA_REG_SIZE_Type nregType = sec_dsa_get_reg_size(size);
-    SEC_ENG_PKA_REG_SIZE_Type lregType = sec_dsa_get_reg_size(size * 2);
-    uint32_t dataSize = (size >> 3) >> 2;
+int sec_dsa_mexp_binary(uint32_t size, const uint32_t *a, const uint32_t *b, const uint32_t *c, uint32_t *r) {
+  uint32_t                  i, j, k;
+  uint32_t                  tmp;
+  uint32_t                  isOne    = 0;
+  uint8_t                  *p        = (uint8_t *)b;
+  SEC_ENG_PKA_REG_SIZE_Type nregType = sec_dsa_get_reg_size(size);
+  SEC_ENG_PKA_REG_SIZE_Type lregType = sec_dsa_get_reg_size(size * 2);
+  uint32_t                  dataSize = (size >> 3) >> 2;
 #if 1
-    uint8_t oneBuf[128] ALIGN4 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 };
+  uint8_t oneBuf[128] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
 #endif
-    /* 0:c
-     * 4:a
-     * 5:number
-     * 6&7:temp
-     */
-
-    /* base = a */
-    Sec_Eng_PKA_Write_Data(nregType, 4, (uint32_t *)a, dataSize, 0);
-
-    /* number = 1 */
-    Sec_Eng_PKA_Write_Data(nregType, 5, (uint32_t *)oneBuf, sizeof(oneBuf) / 4, 0);
-    //Sec_Eng_PKA_Write_Immediate(nregType,5,0x01,1);
+  /* 0:c
+   * 4:a
+   * 5:number
+   * 6&7:temp
+   */
+
+  /* base = a */
+  Sec_Eng_PKA_Write_Data(nregType, 4, (uint32_t *)a, dataSize, 0);
+
+  /* number = 1 */
+  Sec_Eng_PKA_Write_Data(nregType, 5, (uint32_t *)oneBuf, sizeof(oneBuf) / 4, 0);
+  // Sec_Eng_PKA_Write_Immediate(nregType,5,0x01,1);
 #ifdef DSA_DBG
-    Sec_Eng_PKA_Read_Data(nregType, 5, (uint32_t *)pka_tmp, dataSize);
-    MSG("number:\r\n");
-    bflb_platform_dump(pka_tmp, dataSize * 4);
+  Sec_Eng_PKA_Read_Data(nregType, 5, (uint32_t *)pka_tmp, dataSize);
+  MSG("number:\r\n");
+  bflb_platform_dump(pka_tmp, dataSize * 4);
 #endif
 
-    Sec_Eng_PKA_Write_Data(nregType, 0, (uint32_t *)c, dataSize, 0);
+  Sec_Eng_PKA_Write_Data(nregType, 0, (uint32_t *)c, dataSize, 0);
 
-    Sec_Eng_PKA_CREG(nregType, 6, dataSize, 1);
-    Sec_Eng_PKA_CREG(nregType, 7, dataSize, 1);
+  Sec_Eng_PKA_CREG(nregType, 6, dataSize, 1);
+  Sec_Eng_PKA_CREG(nregType, 7, dataSize, 1);
 #ifdef DSA_DBG
-    Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
-    MSG("base:\r\n");
-    bflb_platform_dump(pka_tmp, dataSize * 4);
+  Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
+  MSG("base:\r\n");
+  bflb_platform_dump(pka_tmp, dataSize * 4);
 #endif
-    /* Remove zeros bytes*/
-    k = 0;
+  /* Remove zeros bytes*/
+  k = 0;
 
-    while (p[k] == 0 && k < (size >> 3)) {
-        k++;
-    }
+  while (p[k] == 0 && k < (size >> 3)) {
+    k++;
+  }
 
-    i = (size >> 3) - 1;
+  i = (size >> 3) - 1;
 
-    for (; i >= k; i--) {
-        tmp = p[i];
-        j = 0;
+  for (; i >= k; i--) {
+    tmp = p[i];
+    j   = 0;
 
-        for (j = 0; j < 8; j++) {
-            isOne = tmp & (1 << j);
+    for (j = 0; j < 8; j++) {
+      isOne = tmp & (1 << j);
 
-            if (isOne) {
-                /* number = number * base % c */
-                Sec_Eng_PKA_LMUL(lregType, 3, nregType, 5, nregType, 4, 0);
-                Sec_Eng_PKA_MREM(nregType, 5, lregType, 3, nregType, 0, 1);
+      if (isOne) {
+        /* number = number * base % c */
+        Sec_Eng_PKA_LMUL(lregType, 3, nregType, 5, nregType, 4, 0);
+        Sec_Eng_PKA_MREM(nregType, 5, lregType, 3, nregType, 0, 1);
 #ifdef DSA_DBG
-                Sec_Eng_PKA_Read_Data(nregType, 5, (uint32_t *)pka_tmp, dataSize);
-                MSG("number:\r\n");
-                bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
+        Sec_Eng_PKA_Read_Data(nregType, 5, (uint32_t *)pka_tmp, dataSize);
+        MSG("number:\r\n");
+        bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
 #endif
-            }
+      }
 
-            /* base = base * base % c */
-            Sec_Eng_PKA_LSQR(lregType, 3, nregType, 4, 0);
-            Sec_Eng_PKA_MREM(nregType, 4, lregType, 3, nregType, 0, 1);
+      /* base = base * base % c */
+      Sec_Eng_PKA_LSQR(lregType, 3, nregType, 4, 0);
+      Sec_Eng_PKA_MREM(nregType, 4, lregType, 3, nregType, 0, 1);
 #ifdef DSA_DBG
-            Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
-            MSG("base:\r\n");
-            bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
+      Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
+      MSG("base:\r\n");
+      bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
 #endif
-        }
     }
+  }
 
-    Sec_Eng_PKA_Read_Data(nregType, 5, (uint32_t *)r, dataSize);
+  Sec_Eng_PKA_Read_Data(nregType, 5, (uint32_t *)r, dataSize);
 #ifdef DSA_DBG
-    MSG("r:\r\n");
-    bflb_platform_dump(r, dataSize * 4);
+  MSG("r:\r\n");
+  bflb_platform_dump(r, dataSize * 4);
 #endif
-    return 0;
+  return 0;
 }
 
 /*r=a^b%c*/
-int sec_dsa_mexp_mont(uint32_t size, uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *invR_c, uint32_t *primeN_c, uint32_t *r)
-{
-    SEC_ENG_PKA_REG_SIZE_Type nregType = sec_dsa_get_reg_size(size);
-    SEC_ENG_PKA_REG_SIZE_Type lregType = sec_dsa_get_reg_size(size * 2);
-    uint32_t dataSize = (size >> 3) >> 2;
-
-    /* 0:c
-     * 1:NPrime_c
-     * 2:invR_c
-     * 4:a(mont domain)
-     * 5:b
-     * 6:a^b%c(mont domain)
-     * 7:a^b%c(gf domain)
-     * 10&11:2^size for GF2Mont*/
-    Sec_Eng_PKA_Write_Data(nregType, 0, (uint32_t *)c, dataSize, 0);
-    Sec_Eng_PKA_Write_Data(nregType, 1, (uint32_t *)primeN_c, dataSize, 1);
-    Sec_Eng_PKA_Write_Data(nregType, 2, (uint32_t *)invR_c, dataSize, 1);
-
-    /* change a into mont domain*/
-    Sec_Eng_PKA_Write_Data(nregType, 4, (uint32_t *)a, dataSize, 0);
-    Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
-    Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
-    Sec_Eng_PKA_GF2Mont(nregType, 4, nregType, 4, size, lregType, 5, nregType, 0);
+int sec_dsa_mexp_mont(uint32_t size, uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *invR_c, uint32_t *primeN_c, uint32_t *r) {
+  SEC_ENG_PKA_REG_SIZE_Type nregType = sec_dsa_get_reg_size(size);
+  SEC_ENG_PKA_REG_SIZE_Type lregType = sec_dsa_get_reg_size(size * 2);
+  uint32_t                  dataSize = (size >> 3) >> 2;
+
+  /* 0:c
+   * 1:NPrime_c
+   * 2:invR_c
+   * 4:a(mont domain)
+   * 5:b
+   * 6:a^b%c(mont domain)
+   * 7:a^b%c(gf domain)
+   * 10&11:2^size for GF2Mont*/
+  Sec_Eng_PKA_Write_Data(nregType, 0, (uint32_t *)c, dataSize, 0);
+  Sec_Eng_PKA_Write_Data(nregType, 1, (uint32_t *)primeN_c, dataSize, 1);
+  Sec_Eng_PKA_Write_Data(nregType, 2, (uint32_t *)invR_c, dataSize, 1);
+
+  /* change a into mont domain*/
+  Sec_Eng_PKA_Write_Data(nregType, 4, (uint32_t *)a, dataSize, 0);
+  Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
+  Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
+  Sec_Eng_PKA_GF2Mont(nregType, 4, nregType, 4, size, lregType, 5, nregType, 0);
 #ifdef DSA_DBG
-    Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
-    MSG("GF2Mont Result of a:\r\n");
-    bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
+  Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
+  MSG("GF2Mont Result of a:\r\n");
+  bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
 #endif
 
-    Sec_Eng_PKA_Write_Data(nregType, 5, (uint32_t *)b, dataSize, 0);
-    /* a^b%c*/
-    Sec_Eng_PKA_MEXP(nregType, 6, nregType, 4, nregType, 5, nregType, 0, 1);
+  Sec_Eng_PKA_Write_Data(nregType, 5, (uint32_t *)b, dataSize, 0);
+  /* a^b%c*/
+  Sec_Eng_PKA_MEXP(nregType, 6, nregType, 4, nregType, 5, nregType, 0, 1);
 
-    /* change result into gf domain*/
-    Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
-    Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
-    /*index 2 is invertR*/
-    Sec_Eng_PKA_Mont2GF(nregType, 7, nregType, 6, nregType, 2, lregType, 5, nregType, 0);
-    Sec_Eng_PKA_Read_Data(nregType, 7, (uint32_t *)r, dataSize);
+  /* change result into gf domain*/
+  Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
+  Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
+  /*index 2 is invertR*/
+  Sec_Eng_PKA_Mont2GF(nregType, 7, nregType, 6, nregType, 2, lregType, 5, nregType, 0);
+  Sec_Eng_PKA_Read_Data(nregType, 7, (uint32_t *)r, dataSize);
 #ifdef DSA_DBG
-    MSG("r:\r\n");
-    bflb_platform_dump(r, dataSize /*dataSize*4*/);
+  MSG("r:\r\n");
+  bflb_platform_dump(r, dataSize /*dataSize*4*/);
 #endif
-    return 0;
+  return 0;
 }
 
 /**
@@ -247,17 +233,16 @@ int sec_dsa_mexp_mont(uint32_t size, uint32_t *a, uint32_t *b, uint32_t *c, uint
  * invR_p*r%p=1(r is 1024/2048/256)
  * invR_q*r%q=1(r is 1024/2048/256)
  */
-int sec_dsa_decrypt_crt(uint32_t size, uint32_t *c, sec_dsa_crt_cfg_t *crtCfg, uint32_t *d, uint32_t *r)
-{
-    /*
-     * m1 = pow(c, dP, p)
-     * m2 = pow(c, dQ, q)
-     * h = (qInv * (m1 - m2)) % p
-     * m = m2 + h * q
-     * */
-    SEC_ENG_PKA_REG_SIZE_Type nregType = sec_dsa_get_reg_size(size);
-    SEC_ENG_PKA_REG_SIZE_Type lregType = sec_dsa_get_reg_size(size * 2);
-    uint32_t dataSize = (size >> 3) >> 2;
+int sec_dsa_decrypt_crt(uint32_t size, uint32_t *c, sec_dsa_crt_cfg_t *crtCfg, uint32_t *d, uint32_t *r) {
+  /*
+   * m1 = pow(c, dP, p)
+   * m2 = pow(c, dQ, q)
+   * h = (qInv * (m1 - m2)) % p
+   * m = m2 + h * q
+   * */
+  SEC_ENG_PKA_REG_SIZE_Type nregType = sec_dsa_get_reg_size(size);
+  SEC_ENG_PKA_REG_SIZE_Type lregType = sec_dsa_get_reg_size(size * 2);
+  uint32_t                  dataSize = (size >> 3) >> 2;
 #if 0
     uint8_t  m1[64] = {0x11, 0xdd, 0x19, 0x7e, 0x69, 0x1a, 0x40, 0x0a, 0x28, 0xfc, 0x3b, 0x31, 0x47, 0xa2, 0x6c, 0x14,
                        0x4e, 0xf6, 0xb0, 0xe6, 0xcd, 0x89, 0x0b, 0x4f, 0x02, 0xe4, 0x86, 0xe2, 0xe5, 0xbe, 0xe1, 0xaf,
@@ -270,120 +255,117 @@ int sec_dsa_decrypt_crt(uint32_t size, uint32_t *c, sec_dsa_crt_cfg_t *crtCfg, u
                        0x68, 0x90, 0x57, 0x97, 0xfc, 0x78, 0xd5, 0xdb, 0x07, 0x5b, 0xfe, 0x21, 0x0a, 0x2d, 0x7f, 0xc1
                       };
 #else
-    uint32_t m1[32];
-    uint32_t m2[32];
+  uint32_t m1[32];
+  uint32_t m2[32];
 #endif
-    /*
-     * 4:m1
-     * 5:m2
-     * 6:qInv
-     * 7:p
-     * 8:q
-     * 9:h
-     * 10&11:qInv*(m1-m2)
-     */
-    sec_dsa_mexp_mont(size, c, crtCfg->dP, crtCfg->p, crtCfg->invR_p, crtCfg->primeN_p, m1);
-    sec_dsa_mexp_mont(size, c, crtCfg->dQ, crtCfg->q, crtCfg->invR_q, crtCfg->primeN_q, m2);
-
-    Sec_Eng_PKA_Write_Data(nregType, 4, (uint32_t *)m1, dataSize, 0);
-    Sec_Eng_PKA_Write_Data(nregType, 5, (uint32_t *)m2, dataSize, 0);
-    Sec_Eng_PKA_Write_Data(nregType, 6, (uint32_t *)crtCfg->qInv, dataSize, 0);
-    Sec_Eng_PKA_Write_Data(nregType, 7, (uint32_t *)crtCfg->p, dataSize, 0);
-    Sec_Eng_PKA_Write_Data(nregType, 8, (uint32_t *)crtCfg->q, dataSize, 0);
-
-    /*(m1 - m2)%p*/
-    Sec_Eng_PKA_MSUB(nregType, 4, nregType, 4, nregType, 5, nregType, 7, 1);
+  /*
+   * 4:m1
+   * 5:m2
+   * 6:qInv
+   * 7:p
+   * 8:q
+   * 9:h
+   * 10&11:qInv*(m1-m2)
+   */
+  sec_dsa_mexp_mont(size, c, crtCfg->dP, crtCfg->p, crtCfg->invR_p, crtCfg->primeN_p, m1);
+  sec_dsa_mexp_mont(size, c, crtCfg->dQ, crtCfg->q, crtCfg->invR_q, crtCfg->primeN_q, m2);
+
+  Sec_Eng_PKA_Write_Data(nregType, 4, (uint32_t *)m1, dataSize, 0);
+  Sec_Eng_PKA_Write_Data(nregType, 5, (uint32_t *)m2, dataSize, 0);
+  Sec_Eng_PKA_Write_Data(nregType, 6, (uint32_t *)crtCfg->qInv, dataSize, 0);
+  Sec_Eng_PKA_Write_Data(nregType, 7, (uint32_t *)crtCfg->p, dataSize, 0);
+  Sec_Eng_PKA_Write_Data(nregType, 8, (uint32_t *)crtCfg->q, dataSize, 0);
+
+  /*(m1 - m2)%p*/
+  Sec_Eng_PKA_MSUB(nregType, 4, nregType, 4, nregType, 5, nregType, 7, 1);
 #ifdef DSA_DBG
-    Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
-    MSG("m1 - m2:\r\n");
-    bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
+  Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
+  MSG("m1 - m2:\r\n");
+  bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
 #endif
-    /* (qInv * (m1 - m2)) % p*/
-    Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
-    Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
-    Sec_Eng_PKA_LMUL(lregType, 5, nregType, 6, nregType, 4, 1);
+  /* (qInv * (m1 - m2)) % p*/
+  Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
+  Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
+  Sec_Eng_PKA_LMUL(lregType, 5, nregType, 6, nregType, 4, 1);
 #ifdef DSA_DBG
-    Sec_Eng_PKA_Read_Data(lregType, 5, (uint32_t *)pka_tmp, dataSize * 2);
-    MSG("qInv * (m1 - m2):\r\n");
-    bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*2*/);
+  Sec_Eng_PKA_Read_Data(lregType, 5, (uint32_t *)pka_tmp, dataSize * 2);
+  MSG("qInv * (m1 - m2):\r\n");
+  bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*2*/);
 #endif
-    Sec_Eng_PKA_MREM(nregType, 9, lregType, 5, nregType, 7, 1);
+  Sec_Eng_PKA_MREM(nregType, 9, lregType, 5, nregType, 7, 1);
 #ifdef DSA_DBG
-    Sec_Eng_PKA_Read_Data(nregType, 9, (uint32_t *)pka_tmp, dataSize);
-    MSG("h:\r\n");
-    bflb_platform_dump(pka_tmp, dataSize * 4);
+  Sec_Eng_PKA_Read_Data(nregType, 9, (uint32_t *)pka_tmp, dataSize);
+  MSG("h:\r\n");
+  bflb_platform_dump(pka_tmp, dataSize * 4);
 #endif
 
-    /* h*q */
-    Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
-    Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
-    Sec_Eng_PKA_LMUL(lregType, 5, nregType, 9, nregType, 8, 1);
+  /* h*q */
+  Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
+  Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
+  Sec_Eng_PKA_LMUL(lregType, 5, nregType, 9, nregType, 8, 1);
 #ifdef DSA_DBG
-    Sec_Eng_PKA_Read_Data(lregType, 5, (uint32_t *)pka_tmp, dataSize * 2);
-    MSG("h*q:\r\n");
-    bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*2*/);
+  Sec_Eng_PKA_Read_Data(lregType, 5, (uint32_t *)pka_tmp, dataSize * 2);
+  MSG("h*q:\r\n");
+  bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*2*/);
 #endif
-    /* m2 + h*q*/
-    Sec_Eng_PKA_LADD(lregType, 5, lregType, 5, nregType, 5, 1);
+  /* m2 + h*q*/
+  Sec_Eng_PKA_LADD(lregType, 5, lregType, 5, nregType, 5, 1);
 
-    Sec_Eng_PKA_Read_Data(lregType, 5, (uint32_t *)r, dataSize * 2);
+  Sec_Eng_PKA_Read_Data(lregType, 5, (uint32_t *)r, dataSize * 2);
 #ifdef DSA_DBG
-    MSG("r:\r\n");
-    bflb_platform_dump(r, dataSize * 4 * 2);
+  MSG("r:\r\n");
+  bflb_platform_dump(r, dataSize * 4 * 2);
 #endif
-    return 0;
+  return 0;
 }
 
-int sec_dsa_init(sec_dsa_handle_t *handle, uint32_t size)
-{
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
+int sec_dsa_init(sec_dsa_handle_t *handle, uint32_t size) {
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
 
-    memset(handle, 0, sizeof(sec_dsa_handle_t));
-    handle->size = size;
-    handle->crtSize = (size >> 1);
+  memset(handle, 0, sizeof(sec_dsa_handle_t));
+  handle->size    = size;
+  handle->crtSize = (size >> 1);
 
-    return 0;
+  return 0;
 }
 
-int sec_dsa_sign(sec_dsa_handle_t *handle, const uint32_t *hash, uint32_t hashLenInWord, uint32_t *s)
-{
-    uint32_t dsa_tmp[64] = { 0 };
+int sec_dsa_sign(sec_dsa_handle_t *handle, const uint32_t *hash, uint32_t hashLenInWord, uint32_t *s) {
+  uint32_t dsa_tmp[64] = {0};
 
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
 
-    memcpy(dsa_tmp + ((handle->crtSize >> 3) >> 2) - hashLenInWord, hash, hashLenInWord * 4);
+  memcpy(dsa_tmp + ((handle->crtSize >> 3) >> 2) - hashLenInWord, hash, hashLenInWord * 4);
 
-    if (0 == sec_dsa_decrypt_crt(handle->crtSize, dsa_tmp, &handle->crtCfg, handle->d, s)) {
-        return 0;
-    } else {
-        return -1;
-    }
+  if (0 == sec_dsa_decrypt_crt(handle->crtSize, dsa_tmp, &handle->crtCfg, handle->d, s)) {
+    return 0;
+  } else {
+    return -1;
+  }
 }
 
 /**
  */
-int sec_dsa_verify(sec_dsa_handle_t *handle, const uint32_t *hash, uint32_t hashLenInWord, const uint32_t *s)
-{
-    uint32_t dsa_tmp[64];
-    uint8_t i = 0;
-    uint8_t resultOffset = 0;
-
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
-
-    if (0 == sec_dsa_mexp_binary(handle->size, s, handle->e, handle->n, dsa_tmp)) {
-        resultOffset = (handle->size >> 5) - hashLenInWord;
-
-        for (i = 0; i < hashLenInWord; i++) {
-            if (dsa_tmp[resultOffset + i] != hash[i]) {
-                return -1;
-            }
-        }
-
-        return 0;
-    } else {
+int sec_dsa_verify(sec_dsa_handle_t *handle, const uint32_t *hash, uint32_t hashLenInWord, const uint32_t *s) {
+  uint32_t dsa_tmp[64];
+  uint8_t  i            = 0;
+  uint8_t  resultOffset = 0;
+
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
+
+  if (0 == sec_dsa_mexp_binary(handle->size, s, handle->e, handle->n, dsa_tmp)) {
+    resultOffset = (handle->size >> 5) - hashLenInWord;
+
+    for (i = 0; i < hashLenInWord; i++) {
+      if (dsa_tmp[resultOffset + i] != hash[i]) {
         return -1;
+      }
     }
+
+    return 0;
+  } else {
+    return -1;
+  }
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_ecdsa.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_ecdsa.c
index 8ba150f50b..92e423c018 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_ecdsa.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_ecdsa.c
@@ -11,431 +11,332 @@
 /* Used in verify */
 #define ECP_SECP256R1_S_REG_INDEX     5
 #define ECP_SECP256R1_BAR_S_REG_INDEX 6
-#define ECP_SECP256R1_HASH_REG_INDEX  6 //use ECP_SECP256R1_BAR_S_REG_INDEX since it's temp
+#define ECP_SECP256R1_HASH_REG_INDEX  6 // use ECP_SECP256R1_BAR_S_REG_INDEX since it's temp
 #define ECP_SECP256R1_U1_REG_INDEX    7
 #define ECP_SECP256R1_LT_REG_TYPE     SEC_ENG_PKA_REG_SIZE_64
 #define ECP_SECP256R1_LT_REG_INDEX    7
 #define ECP_SECP256R1_SLT_REG_TYPE    SEC_ENG_PKA_REG_SIZE_128
 #define ECP_SECP256R1_SLT_REG_INDEX   3
 
-//#define ECDSA_DBG                                   1
-//#define ECDSA_DBG_DETAIL                            1
+// #define ECDSA_DBG                                   1
+// #define ECDSA_DBG_DETAIL                            1
 
 #define secp256r1
 #define secp256k1
-#define SEC_ECC_POINT_MUL_PARAM_CFG(G) sec_ecc_point_mul_cfg( \
-    (uint32_t *)G##P,                                         \
-    (uint32_t *)G##PrimeN_P,                                  \
-    (uint32_t *)G##_1,                                        \
-    (uint32_t *)G##_BAR2,                                     \
-    (uint32_t *)G##_BAR3,                                     \
-    (uint32_t *)G##_BAR4,                                     \
-    (uint32_t *)G##_BAR8,                                     \
-    (uint32_t *)G##_1P1,                                      \
-    (uint32_t *)G##_1M1)
-
-#define SEC_ECC_BASIC_PARAM_CFG(G) sec_ecc_basic_parameter_cfg( \
-    (uint32_t *)G##N,                                           \
-    (uint32_t *)G##PrimeN_N,                                    \
-    (uint32_t *)G##InvR_N)
+#define SEC_ECC_POINT_MUL_PARAM_CFG(G)                                                                                                                                                             \
+  sec_ecc_point_mul_cfg((uint32_t *)G##P, (uint32_t *)G##PrimeN_P, (uint32_t *)G##_1, (uint32_t *)G##_BAR2, (uint32_t *)G##_BAR3, (uint32_t *)G##_BAR4, (uint32_t *)G##_BAR8, (uint32_t *)G##_1P1, \
+                        (uint32_t *)G##_1M1)
+
+#define SEC_ECC_BASIC_PARAM_CFG(G) sec_ecc_basic_parameter_cfg((uint32_t *)G##N, (uint32_t *)G##PrimeN_N, (uint32_t *)G##InvR_N)
 
 void bflb_platform_dump(uint8_t *data, uint32_t len);
 
 #if (defined(ECDSA_DBG) || defined(ECDSA_DBG_DETAIL))
-uint32_t pka_tmp[32] = { 0 };
+uint32_t pka_tmp[32] = {0};
 #endif
 /********************************************** secp256r1 *******************************************/
-const uint8_t secp256r1P[32] ALIGN4 = {
-    0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
-};
-const uint8_t secp256r1B[32] ALIGN4 = {
-    0x5a, 0xc6, 0x35, 0xd8, 0xaa, 0x3a, 0x93, 0xe7, 0xb3, 0xeb, 0xbd, 0x55, 0x76, 0x98, 0x86, 0xbc,
-    0x65, 0x1d, 0x06, 0xb0, 0xcc, 0x53, 0xb0, 0xf6, 0x3b, 0xce, 0x3c, 0x3e, 0x27, 0xd2, 0x60, 0x4b
-};
-const uint8_t secp256r1Gx[32] ALIGN4 = {
-    0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47, 0xf8, 0xbc, 0xe6, 0xe5, 0x63, 0xa4, 0x40, 0xf2,
-    0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb, 0x33, 0xa0, 0xf4, 0xa1, 0x39, 0x45, 0xd8, 0x98, 0xc2, 0x96
-};
-const uint8_t secp256r1Gy[32] ALIGN4 = {
-    0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16,
-    0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5
-};
-const uint8_t secp256r1N[32] ALIGN4 = {
-    0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51
-};
-const uint8_t secp256r1PrimeN_N[32] ALIGN4 = {
-    0x60, 0xd0, 0x66, 0x33, 0xa9, 0xd6, 0x28, 0x1c, 0x50, 0xfe, 0x77, 0xec, 0xc5, 0x88, 0xc6, 0xf6,
-    0x48, 0xc9, 0x44, 0x08, 0x7d, 0x74, 0xd2, 0xe4, 0xcc, 0xd1, 0xc8, 0xaa, 0xee, 0x00, 0xbc, 0x4f
-};
-const uint8_t secp256r1InvR_N[32] ALIGN4 = {
-    0x60, 0xd0, 0x66, 0x33, 0x49, 0x05, 0xc1, 0xe9, 0x07, 0xf8, 0xb6, 0x04, 0x1e, 0x60, 0x77, 0x25,
-    0xba, 0xde, 0xf3, 0xe2, 0x43, 0x56, 0x6f, 0xaf, 0xce, 0x1b, 0xc8, 0xf7, 0x9c, 0x19, 0x7c, 0x79
-};
-const uint8_t secp256r1PrimeN_P[32] ALIGN4 = {
-    0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
-};
-const uint8_t secp256r1InvR_P[32] ALIGN4 = {
-    0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xfd, 0x00, 0x00, 0x00, 0x02,
-    0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00
-};
-const uint8_t secp256r1_1[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
-};
-const uint8_t secp256r1_BAR2[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02
-};
-const uint8_t secp256r1_BAR3[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x02, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03
-};
-const uint8_t secp256r1_BAR4[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04
-};
-const uint8_t secp256r1_BAR8[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x07, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08
-};
-const uint8_t secp256r1_1P1[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02
-};
-const uint8_t secp256r1_1M1[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
-};
-const uint8_t secp256r1_Zerox[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
-};
-const uint8_t secp256r1_Zeroy[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
-};
-const uint8_t secp256r1_Gx[32] ALIGN4 = {
-    0x18, 0x90, 0x5f, 0x76, 0xa5, 0x37, 0x55, 0xc6, 0x79, 0xfb, 0x73, 0x2b, 0x77, 0x62, 0x25, 0x10,
-    0x75, 0xba, 0x95, 0xfc, 0x5f, 0xed, 0xb6, 0x01, 0x79, 0xe7, 0x30, 0xd4, 0x18, 0xa9, 0x14, 0x3c
-};
-const uint8_t secp256r1_Gy[32] ALIGN4 = {
-    0x85, 0x71, 0xff, 0x18, 0x25, 0x88, 0x5d, 0x85, 0xd2, 0xe8, 0x86, 0x88, 0xdd, 0x21, 0xf3, 0x25,
-    0x8b, 0x4a, 0xb8, 0xe4, 0xba, 0x19, 0xe4, 0x5c, 0xdd, 0xf2, 0x53, 0x57, 0xce, 0x95, 0x56, 0x0a
-};
+const uint8_t secp256r1P[32] ALIGN4
+    = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
+const uint8_t secp256r1B[32] ALIGN4
+    = {0x5a, 0xc6, 0x35, 0xd8, 0xaa, 0x3a, 0x93, 0xe7, 0xb3, 0xeb, 0xbd, 0x55, 0x76, 0x98, 0x86, 0xbc, 0x65, 0x1d, 0x06, 0xb0, 0xcc, 0x53, 0xb0, 0xf6, 0x3b, 0xce, 0x3c, 0x3e, 0x27, 0xd2, 0x60, 0x4b};
+const uint8_t secp256r1Gx[32] ALIGN4
+    = {0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47, 0xf8, 0xbc, 0xe6, 0xe5, 0x63, 0xa4, 0x40, 0xf2, 0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb, 0x33, 0xa0, 0xf4, 0xa1, 0x39, 0x45, 0xd8, 0x98, 0xc2, 0x96};
+const uint8_t secp256r1Gy[32] ALIGN4
+    = {0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16, 0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5};
+const uint8_t secp256r1N[32] ALIGN4
+    = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51};
+const uint8_t secp256r1PrimeN_N[32] ALIGN4
+    = {0x60, 0xd0, 0x66, 0x33, 0xa9, 0xd6, 0x28, 0x1c, 0x50, 0xfe, 0x77, 0xec, 0xc5, 0x88, 0xc6, 0xf6, 0x48, 0xc9, 0x44, 0x08, 0x7d, 0x74, 0xd2, 0xe4, 0xcc, 0xd1, 0xc8, 0xaa, 0xee, 0x00, 0xbc, 0x4f};
+const uint8_t secp256r1InvR_N[32] ALIGN4
+    = {0x60, 0xd0, 0x66, 0x33, 0x49, 0x05, 0xc1, 0xe9, 0x07, 0xf8, 0xb6, 0x04, 0x1e, 0x60, 0x77, 0x25, 0xba, 0xde, 0xf3, 0xe2, 0x43, 0x56, 0x6f, 0xaf, 0xce, 0x1b, 0xc8, 0xf7, 0x9c, 0x19, 0x7c, 0x79};
+const uint8_t secp256r1PrimeN_P[32] ALIGN4
+    = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
+const uint8_t secp256r1InvR_P[32] ALIGN4
+    = {0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xfd, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00};
+const uint8_t secp256r1_1[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
+const uint8_t secp256r1_BAR2[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02};
+const uint8_t secp256r1_BAR3[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x02, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03};
+const uint8_t secp256r1_BAR4[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04};
+const uint8_t secp256r1_BAR8[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x07, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08};
+const uint8_t secp256r1_1P1[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02};
+const uint8_t secp256r1_1M1[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+const uint8_t secp256r1_Zerox[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+const uint8_t secp256r1_Zeroy[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
+const uint8_t secp256r1_Gx[32] ALIGN4
+    = {0x18, 0x90, 0x5f, 0x76, 0xa5, 0x37, 0x55, 0xc6, 0x79, 0xfb, 0x73, 0x2b, 0x77, 0x62, 0x25, 0x10, 0x75, 0xba, 0x95, 0xfc, 0x5f, 0xed, 0xb6, 0x01, 0x79, 0xe7, 0x30, 0xd4, 0x18, 0xa9, 0x14, 0x3c};
+const uint8_t secp256r1_Gy[32] ALIGN4
+    = {0x85, 0x71, 0xff, 0x18, 0x25, 0x88, 0x5d, 0x85, 0xd2, 0xe8, 0x86, 0x88, 0xdd, 0x21, 0xf3, 0x25, 0x8b, 0x4a, 0xb8, 0xe4, 0xba, 0x19, 0xe4, 0x5c, 0xdd, 0xf2, 0x53, 0x57, 0xce, 0x95, 0x56, 0x0a};
 
 /********************************************** secp256k1 *******************************************/
-const uint8_t secp256k1P[32] ALIGN4 = {
-    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
-    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFC, 0x2F
-};
-const uint8_t secp256k1B[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07
-};
-const uint8_t secp256k1Gx[32] ALIGN4 = {
-    0x79, 0xBE, 0x66, 0x7E, 0xF9, 0xDC, 0xBB, 0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE, 0x87, 0x0B, 0x07,
-    0x02, 0x9B, 0xFC, 0xDB, 0x2D, 0xCE, 0x28, 0xD9, 0x59, 0xF2, 0x81, 0x5B, 0x16, 0xF8, 0x17, 0x98
-};
-const uint8_t secp256k1Gy[32] ALIGN4 = {
-    0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16,
-    0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5
-};
-const uint8_t secp256k1N[32] ALIGN4 = {
-    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
-    0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41
-};
-const uint8_t secp256k1PrimeN_N[32] ALIGN4 = {
-    0xd9, 0xe8, 0x89, 0xd, 0x64, 0x94, 0xef, 0x93, 0x89, 0x7f, 0x30, 0xc1, 0x27, 0xcf, 0xab, 0x5e,
-    0x50, 0xa5, 0x1a, 0xc8, 0x34, 0xb9, 0xec, 0x24, 0x4b, 0xd, 0xff, 0x66, 0x55, 0x88, 0xb1, 0x3f
-};
-const uint8_t secp256k1InvR_N[32] ALIGN4 = {
-    0xd9, 0xe8, 0x89, 0xd, 0x64, 0x94, 0xef, 0x93, 0x89, 0x7f, 0x30, 0xc1, 0x27, 0xcf, 0xab, 0x5d,
-    0x3b, 0xbb, 0xd4, 0x56, 0x7f, 0xa5, 0xc, 0x3c, 0x80, 0xfd, 0x22, 0x93, 0x80, 0x97, 0xc0, 0x16
-};
-const uint8_t secp256k1PrimeN_P[32] ALIGN4 = {
-    0xc9, 0xbd, 0x19, 0x5, 0x15, 0x53, 0x83, 0x99, 0x9c, 0x46, 0xc2, 0xc2, 0x95, 0xf2, 0xb7, 0x61,
-    0xbc, 0xb2, 0x23, 0xfe, 0xdc, 0x24, 0xa0, 0x59, 0xd8, 0x38, 0x9, 0x1d, 0xd2, 0x25, 0x35, 0x31
-};
-const uint8_t secp256k1InvR_P[32] ALIGN4 = {
-    0xc9, 0xbd, 0x19, 0x5, 0x15, 0x53, 0x83, 0x99, 0x9c, 0x46, 0xc2, 0xc2, 0x95, 0xf2, 0xb7, 0x61,
-    0xbc, 0xb2, 0x23, 0xfe, 0xdc, 0x24, 0xa0, 0x59, 0xd8, 0x38, 0x9, 0x1d, 0x8, 0x68, 0x19, 0x2a
-};
-const uint8_t secp256k1_1[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
-};
-const uint8_t secp256k1_BAR2[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x07, 0xa2
-};
-const uint8_t secp256k1_BAR3[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x0b, 0x73
-};
-const uint8_t secp256k1_BAR4[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x0f, 0x44
-};
-const uint8_t secp256k1_BAR8[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x1e, 0x88
-};
-const uint8_t secp256k1_1P1[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd2
-};
-const uint8_t secp256k1_1M1[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd0
-};
-const uint8_t secp256k1_Zerox[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
-};
-const uint8_t secp256k1_Zeroy[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd1
-};
-const uint8_t secp256k1_Gx[32] ALIGN4 = {
-    0x99, 0x81, 0xe6, 0x43, 0xe9, 0x08, 0x9f, 0x48, 0x97, 0x9f, 0x48, 0xc0, 0x33, 0xfd, 0x12, 0x9c,
-    0x23, 0x1e, 0x29, 0x53, 0x29, 0xbc, 0x66, 0xdb, 0xd7, 0x36, 0x2e, 0x5a, 0x48, 0x7e, 0x20, 0x97
-};
-const uint8_t secp256k1_Gy[32] ALIGN4 = {
-    0xcf, 0x3f, 0x85, 0x1f, 0xd4, 0xa5, 0x82, 0xd6, 0x70, 0xb6, 0xb5, 0x9a, 0xac, 0x19, 0xc1, 0x36,
-    0x8d, 0xfc, 0x5d, 0x5d, 0x1f, 0x1d, 0xc6, 0x4d, 0xb1, 0x5e, 0xa6, 0xd2, 0xd3, 0xdb, 0xab, 0xe2
-};
-
-static BL_Err_Type sec_ecc_basic_parameter_cfg(uint32_t *n, uint32_t *prime_n, uint32_t *invr_n)
-{
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)n, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_NPRIME_N_REG_INDEX, (uint32_t *)prime_n, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_INVR_N_REG_INDEX, (uint32_t *)invr_n, ECP_SECP256R1_SIZE / 4, 0);
-    return SUCCESS;
+const uint8_t secp256k1P[32] ALIGN4
+    = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFC, 0x2F};
+const uint8_t secp256k1B[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07};
+const uint8_t secp256k1Gx[32] ALIGN4
+    = {0x79, 0xBE, 0x66, 0x7E, 0xF9, 0xDC, 0xBB, 0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE, 0x87, 0x0B, 0x07, 0x02, 0x9B, 0xFC, 0xDB, 0x2D, 0xCE, 0x28, 0xD9, 0x59, 0xF2, 0x81, 0x5B, 0x16, 0xF8, 0x17, 0x98};
+const uint8_t secp256k1Gy[32] ALIGN4
+    = {0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16, 0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5};
+const uint8_t secp256k1N[32] ALIGN4
+    = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41};
+const uint8_t secp256k1PrimeN_N[32] ALIGN4
+    = {0xd9, 0xe8, 0x89, 0xd, 0x64, 0x94, 0xef, 0x93, 0x89, 0x7f, 0x30, 0xc1, 0x27, 0xcf, 0xab, 0x5e, 0x50, 0xa5, 0x1a, 0xc8, 0x34, 0xb9, 0xec, 0x24, 0x4b, 0xd, 0xff, 0x66, 0x55, 0x88, 0xb1, 0x3f};
+const uint8_t secp256k1InvR_N[32] ALIGN4
+    = {0xd9, 0xe8, 0x89, 0xd, 0x64, 0x94, 0xef, 0x93, 0x89, 0x7f, 0x30, 0xc1, 0x27, 0xcf, 0xab, 0x5d, 0x3b, 0xbb, 0xd4, 0x56, 0x7f, 0xa5, 0xc, 0x3c, 0x80, 0xfd, 0x22, 0x93, 0x80, 0x97, 0xc0, 0x16};
+const uint8_t secp256k1PrimeN_P[32] ALIGN4
+    = {0xc9, 0xbd, 0x19, 0x5, 0x15, 0x53, 0x83, 0x99, 0x9c, 0x46, 0xc2, 0xc2, 0x95, 0xf2, 0xb7, 0x61, 0xbc, 0xb2, 0x23, 0xfe, 0xdc, 0x24, 0xa0, 0x59, 0xd8, 0x38, 0x9, 0x1d, 0xd2, 0x25, 0x35, 0x31};
+const uint8_t secp256k1InvR_P[32] ALIGN4
+    = {0xc9, 0xbd, 0x19, 0x5, 0x15, 0x53, 0x83, 0x99, 0x9c, 0x46, 0xc2, 0xc2, 0x95, 0xf2, 0xb7, 0x61, 0xbc, 0xb2, 0x23, 0xfe, 0xdc, 0x24, 0xa0, 0x59, 0xd8, 0x38, 0x9, 0x1d, 0x8, 0x68, 0x19, 0x2a};
+const uint8_t secp256k1_1[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
+const uint8_t secp256k1_BAR2[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x07, 0xa2};
+const uint8_t secp256k1_BAR3[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x0b, 0x73};
+const uint8_t secp256k1_BAR4[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x0f, 0x44};
+const uint8_t secp256k1_BAR8[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x1e, 0x88};
+const uint8_t secp256k1_1P1[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd2};
+const uint8_t secp256k1_1M1[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd0};
+const uint8_t secp256k1_Zerox[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+const uint8_t secp256k1_Zeroy[32] ALIGN4
+    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd1};
+const uint8_t secp256k1_Gx[32] ALIGN4
+    = {0x99, 0x81, 0xe6, 0x43, 0xe9, 0x08, 0x9f, 0x48, 0x97, 0x9f, 0x48, 0xc0, 0x33, 0xfd, 0x12, 0x9c, 0x23, 0x1e, 0x29, 0x53, 0x29, 0xbc, 0x66, 0xdb, 0xd7, 0x36, 0x2e, 0x5a, 0x48, 0x7e, 0x20, 0x97};
+const uint8_t secp256k1_Gy[32] ALIGN4
+    = {0xcf, 0x3f, 0x85, 0x1f, 0xd4, 0xa5, 0x82, 0xd6, 0x70, 0xb6, 0xb5, 0x9a, 0xac, 0x19, 0xc1, 0x36, 0x8d, 0xfc, 0x5d, 0x5d, 0x1f, 0x1d, 0xc6, 0x4d, 0xb1, 0x5e, 0xa6, 0xd2, 0xd3, 0xdb, 0xab, 0xe2};
+
+static BL_Err_Type sec_ecc_basic_parameter_cfg(uint32_t *n, uint32_t *prime_n, uint32_t *invr_n) {
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)n, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_NPRIME_N_REG_INDEX, (uint32_t *)prime_n, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_INVR_N_REG_INDEX, (uint32_t *)invr_n, ECP_SECP256R1_SIZE / 4, 0);
+  return SUCCESS;
 }
-static BL_Err_Type sec_ecc_basic_parameter_init(uint8_t id)
-{
-    if (id >= ECP_TYPE_MAX) {
-        return ERROR;
-    }
-
-    if (id == ECP_SECP256R1) {
-        SEC_ECC_BASIC_PARAM_CFG(secp256r1);
-    } else if (id == ECP_SECP256K1) {
-        SEC_ECC_BASIC_PARAM_CFG(secp256k1);
-    }
-
-    return SUCCESS;
+static BL_Err_Type sec_ecc_basic_parameter_init(uint8_t id) {
+  if (id >= ECP_TYPE_MAX) {
+    return ERROR;
+  }
+
+  if (id == ECP_SECP256R1) {
+    SEC_ECC_BASIC_PARAM_CFG(secp256r1);
+  } else if (id == ECP_SECP256K1) {
+    SEC_ECC_BASIC_PARAM_CFG(secp256k1);
+  }
+
+  return SUCCESS;
 }
 
-static BL_Err_Type sec_ecc_point_mul_cfg(uint32_t *p, uint32_t *primeN_p, uint32_t *ori_1, uint32_t *bar2,
-                                         uint32_t *bar3, uint32_t *bar4, uint32_t *bar8, uint32_t *bar1p1, uint32_t *bar1m1)
-{
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 0, (uint32_t *)p, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 1, (uint32_t *)primeN_p, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 8, (uint32_t *)ori_1, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 9, (uint32_t *)bar2, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 10, (uint32_t *)bar3, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 11, (uint32_t *)bar4, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 12, (uint32_t *)bar8, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 19, (uint32_t *)bar1p1, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 20, (uint32_t *)bar1m1, ECP_SECP256R1_SIZE / 4, 0);
-
-    return SUCCESS;
+static BL_Err_Type sec_ecc_point_mul_cfg(uint32_t *p, uint32_t *primeN_p, uint32_t *ori_1, uint32_t *bar2, uint32_t *bar3, uint32_t *bar4, uint32_t *bar8, uint32_t *bar1p1, uint32_t *bar1m1) {
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 0, (uint32_t *)p, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 1, (uint32_t *)primeN_p, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 8, (uint32_t *)ori_1, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 9, (uint32_t *)bar2, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 10, (uint32_t *)bar3, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 11, (uint32_t *)bar4, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 12, (uint32_t *)bar8, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 19, (uint32_t *)bar1p1, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 20, (uint32_t *)bar1m1, ECP_SECP256R1_SIZE / 4, 0);
+
+  return SUCCESS;
 }
 
-static int sec_ecc_point_mul_init(uint8_t id)
-{
-    if (id >= ECP_TYPE_MAX) {
-        return ERROR;
-    }
+static int sec_ecc_point_mul_init(uint8_t id) {
+  if (id >= ECP_TYPE_MAX) {
+    return ERROR;
+  }
 
-    if (id == ECP_SECP256R1) {
-        SEC_ECC_POINT_MUL_PARAM_CFG(secp256r1);
-    } else if (id == ECP_SECP256K1) {
-        SEC_ECC_POINT_MUL_PARAM_CFG(secp256k1);
-    }
+  if (id == ECP_SECP256R1) {
+    SEC_ECC_POINT_MUL_PARAM_CFG(secp256r1);
+  } else if (id == ECP_SECP256K1) {
+    SEC_ECC_POINT_MUL_PARAM_CFG(secp256k1);
+  }
 
-    return SUCCESS;
+  return SUCCESS;
 }
 
-static void sec_ecdsa_point_add_inf_check(uint8_t *pka_p1_eq_inf, uint8_t *pka_p2_eq_inf)
-{
-    uint8_t res[4];
-
-    /* index 2:BAR_Zero_x
-     * index 3:BAR_Zero_y
-     * index 4:BAR_Zero_z
-     * index 5:BAR_G_x
-     * index 6:BAR_G_y
-     * index 7:BAR_G_z
-     * index 8:1
-     * index 9:2
-     * index 10:3
-     * index 11:4
-     * index 12:8
-     * index 19:1P1
-     * index 20:1m1*/
-
-    //cout = 1 if X1 = 0
-    Sec_Eng_PKA_LCMP(res, 3, 2, 3, 8); //s0 < s1 => cout = 1
-    //cout = 1 if Y1 < Bar_1p1
-    Sec_Eng_PKA_LCMP(res + 1, 3, 3, 3, 19);
-    //cout=1 if Y1 > Bar_1m1
-    Sec_Eng_PKA_LCMP(res + 2, 3, 20, 3, 3);
-    //cout =1 if Z1 = 0
-    Sec_Eng_PKA_LCMP(res + 3, 3, 4, 3, 8);
-    *pka_p1_eq_inf = res[0] & res[1] & res[2] & res[3];
-
-    //cout = 1 if X2 = 0
-    Sec_Eng_PKA_LCMP(res, 3, 5, 3, 8);
-    // cout = 1 if Y2 < Bar_1p1
-    Sec_Eng_PKA_LCMP(res + 1, 3, 6, 3, 19);
-    //cout = 1 if Y2 > Bar_1m1
-    Sec_Eng_PKA_LCMP(res + 2, 3, 20, 3, 6);
-    //cout = 1 if Z2 = 0
-    Sec_Eng_PKA_LCMP(res + 3, 3, 7, 3, 8);
-    *pka_p2_eq_inf = res[0] & res[1] & res[2] & res[3];
+static void sec_ecdsa_point_add_inf_check(uint8_t *pka_p1_eq_inf, uint8_t *pka_p2_eq_inf) {
+  uint8_t res[4];
+
+  /* index 2:BAR_Zero_x
+   * index 3:BAR_Zero_y
+   * index 4:BAR_Zero_z
+   * index 5:BAR_G_x
+   * index 6:BAR_G_y
+   * index 7:BAR_G_z
+   * index 8:1
+   * index 9:2
+   * index 10:3
+   * index 11:4
+   * index 12:8
+   * index 19:1P1
+   * index 20:1m1*/
+
+  // cout = 1 if X1 = 0
+  Sec_Eng_PKA_LCMP(res, 3, 2, 3, 8); // s0 < s1 => cout = 1
+  // cout = 1 if Y1 < Bar_1p1
+  Sec_Eng_PKA_LCMP(res + 1, 3, 3, 3, 19);
+  // cout=1 if Y1 > Bar_1m1
+  Sec_Eng_PKA_LCMP(res + 2, 3, 20, 3, 3);
+  // cout =1 if Z1 = 0
+  Sec_Eng_PKA_LCMP(res + 3, 3, 4, 3, 8);
+  *pka_p1_eq_inf = res[0] & res[1] & res[2] & res[3];
+
+  // cout = 1 if X2 = 0
+  Sec_Eng_PKA_LCMP(res, 3, 5, 3, 8);
+  // cout = 1 if Y2 < Bar_1p1
+  Sec_Eng_PKA_LCMP(res + 1, 3, 6, 3, 19);
+  // cout = 1 if Y2 > Bar_1m1
+  Sec_Eng_PKA_LCMP(res + 2, 3, 20, 3, 6);
+  // cout = 1 if Z2 = 0
+  Sec_Eng_PKA_LCMP(res + 3, 3, 7, 3, 8);
+  *pka_p2_eq_inf = res[0] & res[1] & res[2] & res[3];
 }
 
-static void sec_ecdsa_copy_x2_to_x1(uint8_t id)
-{
-    //X2->X1
-    Sec_Eng_PKA_Move_Data(3, 2, 3, 5, 0);
-    //Y2->Y1
-    Sec_Eng_PKA_Move_Data(3, 3, 3, 6, 0);
-    //Z2->Z1
-    Sec_Eng_PKA_Move_Data(3, 4, 3, 7, 1); //Caution!!! wait movdat ready to execute next command
+static void sec_ecdsa_copy_x2_to_x1(uint8_t id) {
+  // X2->X1
+  Sec_Eng_PKA_Move_Data(3, 2, 3, 5, 0);
+  // Y2->Y1
+  Sec_Eng_PKA_Move_Data(3, 3, 3, 6, 0);
+  // Z2->Z1
+  Sec_Eng_PKA_Move_Data(3, 4, 3, 7, 1); // Caution!!! wait movdat ready to execute next command
 }
 
-static void sec_ecdsa_point_add(uint8_t id)
-{
-    /* index 2:BAR_Zero_x
-     * index 3:BAR_Zero_y
-     * index 4:BAR_Zero_z
-     * index 5:BAR_G_x
-     * index 6:BAR_G_y
-     * index 7:BAR_G_z
-     * index 8:1
-     * index 9:2
-     * index 10:3
-     * index 11:4
-     * index 12:8
-     * index 19:1P1
-     * index 20:1m1*/
-
-    //U1 = Y2*Z1
-    //PKA_MMUL(0,3,13,3, 6,3, 4,3,0);//d_reg_type,d_reg_idx,s0_reg_type,s0_reg_idx,s1_reg_type,s1_reg_idx,s2_reg_type,s2_reg_idx
-    Sec_Eng_PKA_MMUL(3, 13, 3, 6, 3, 4, 3, 0, 0);
-
-    //U2 = Y1*Z2
-    //PKA_MMUL(0,3,14,3, 3,3, 7,3,0);
-    Sec_Eng_PKA_MMUL(3, 14, 3, 3, 3, 7, 3, 0, 0);
-
-    //V1 = X2*Z1
-    //PKA_MMUL(0,3,15,3, 5,3, 4,3,0);
-    Sec_Eng_PKA_MMUL(3, 15, 3, 5, 3, 4, 3, 0, 0);
-
-    //V2 = X1*Z2
-    //PKA_MMUL(0,3,16,3, 2,3, 7,3,0);
-    Sec_Eng_PKA_MMUL(3, 16, 3, 2, 3, 7, 3, 0, 0);
-
-    //U = U1-U2
-    //PKA_MSUB(0,3,13,3,13,3,14,3,0);
-    Sec_Eng_PKA_MSUB(3, 13, 3, 13, 3, 14, 3, 0, 0);
-
-    //V = V1-V2
-    //PKA_MSUB(0,3,15,3,15,3,16,3,0);
-    Sec_Eng_PKA_MSUB(3, 15, 3, 15, 3, 16, 3, 0, 0);
-
-    //W = Z1*Z2
-    //PKA_MMUL(0,3, 2,3, 4,3, 7,3,0);
-    Sec_Eng_PKA_MMUL(3, 2, 3, 4, 3, 7, 3, 0, 0);
-
-    //V^2
-    //PKA_MMUL(0,3, 3,3,15,3,15,3,0);
-    Sec_Eng_PKA_MMUL(3, 3, 3, 15, 3, 15, 3, 0, 0);
-
-    //V^3
-    //PKA_MMUL(0,3, 4,3, 3,3,15,3,0);
-    Sec_Eng_PKA_MMUL(3, 4, 3, 3, 3, 15, 3, 0, 0);
-
-    //U^2
-    //PKA_MMUL(0,3,17,3,13,3,13,3,0);
-    Sec_Eng_PKA_MMUL(3, 17, 3, 13, 3, 13, 3, 0, 0);
-
-    //U^2*W
-    //PKA_MMUL(0,3,17,3,17,3, 2,3,0);
-    Sec_Eng_PKA_MMUL(3, 17, 3, 17, 3, 2, 3, 0, 0);
-
-    //U^2*W-V^3
-    //PKA_MSUB(0,3,17,3,17,3, 4,3,0);
-    Sec_Eng_PKA_MSUB(3, 17, 3, 17, 3, 4, 3, 0, 0);
-
-    //2*V^2
-    //PKA_MMUL(0,3,18,3, 9,3, 3,3,0);
-    Sec_Eng_PKA_MMUL(3, 18, 3, 9, 3, 3, 3, 0, 0);
-
-    //2*V^2*V2
-    //PKA_MMUL(0,3,18,3,18,3,16,3,0);
-    Sec_Eng_PKA_MMUL(3, 18, 3, 18, 3, 16, 3, 0, 0);
-
-    //A = U^2*W-V^3-2*V^2*V2
-    //PKA_MSUB(0,3,18,3,17,3,18,3,0);
-    Sec_Eng_PKA_MSUB(3, 18, 3, 17, 3, 18, 3, 0, 0);
-
-    //V^2*V2
-    //PKA_MMUL(0,3, 3,3, 3,3,16,3,0);
-    Sec_Eng_PKA_MMUL(3, 3, 3, 3, 3, 16, 3, 0, 0);
-
-    //V^3*U2
-    //PKA_MMUL(0,3,14,3, 4,3,14,3,0);
-    Sec_Eng_PKA_MMUL(3, 14, 3, 4, 3, 14, 3, 0, 0);
-
-    //Z3 = V^3*W
-    //PKA_MMUL(0,3, 4,3, 4,3, 2,3,0);
-    Sec_Eng_PKA_MMUL(3, 4, 3, 4, 3, 2, 3, 0, 0);
-
-    //X3 = V*A
-    //PKA_MMUL(0,3, 2,3,15,3,18,3,0);
-    Sec_Eng_PKA_MMUL(3, 2, 3, 15, 3, 18, 3, 0, 0);
-
-    //V^2*V2-A
-    //PKA_MSUB(0,3, 3,3, 3,3,18,3,0);
-    Sec_Eng_PKA_MSUB(3, 3, 3, 3, 3, 18, 3, 0, 0);
-
-    //U*(V^2*V2-A)
-    //PKA_MMUL(0,3, 3,3,13,3, 3,3,0);
-    Sec_Eng_PKA_MMUL(3, 3, 3, 13, 3, 3, 3, 0, 0);
-
-    //Y3 = U*(V^2*V2-A)-V^3*U2
-    //PKA_MSUB(1,3, 3,3, 3,3,14,3,0);
-    Sec_Eng_PKA_MSUB(3, 3, 3, 3, 3, 14, 3, 0, 1);
+static void sec_ecdsa_point_add(uint8_t id) {
+  /* index 2:BAR_Zero_x
+   * index 3:BAR_Zero_y
+   * index 4:BAR_Zero_z
+   * index 5:BAR_G_x
+   * index 6:BAR_G_y
+   * index 7:BAR_G_z
+   * index 8:1
+   * index 9:2
+   * index 10:3
+   * index 11:4
+   * index 12:8
+   * index 19:1P1
+   * index 20:1m1*/
+
+  // U1 = Y2*Z1
+  // PKA_MMUL(0,3,13,3, 6,3, 4,3,0);//d_reg_type,d_reg_idx,s0_reg_type,s0_reg_idx,s1_reg_type,s1_reg_idx,s2_reg_type,s2_reg_idx
+  Sec_Eng_PKA_MMUL(3, 13, 3, 6, 3, 4, 3, 0, 0);
+
+  // U2 = Y1*Z2
+  // PKA_MMUL(0,3,14,3, 3,3, 7,3,0);
+  Sec_Eng_PKA_MMUL(3, 14, 3, 3, 3, 7, 3, 0, 0);
+
+  // V1 = X2*Z1
+  // PKA_MMUL(0,3,15,3, 5,3, 4,3,0);
+  Sec_Eng_PKA_MMUL(3, 15, 3, 5, 3, 4, 3, 0, 0);
+
+  // V2 = X1*Z2
+  // PKA_MMUL(0,3,16,3, 2,3, 7,3,0);
+  Sec_Eng_PKA_MMUL(3, 16, 3, 2, 3, 7, 3, 0, 0);
+
+  // U = U1-U2
+  // PKA_MSUB(0,3,13,3,13,3,14,3,0);
+  Sec_Eng_PKA_MSUB(3, 13, 3, 13, 3, 14, 3, 0, 0);
+
+  // V = V1-V2
+  // PKA_MSUB(0,3,15,3,15,3,16,3,0);
+  Sec_Eng_PKA_MSUB(3, 15, 3, 15, 3, 16, 3, 0, 0);
+
+  // W = Z1*Z2
+  // PKA_MMUL(0,3, 2,3, 4,3, 7,3,0);
+  Sec_Eng_PKA_MMUL(3, 2, 3, 4, 3, 7, 3, 0, 0);
+
+  // V^2
+  // PKA_MMUL(0,3, 3,3,15,3,15,3,0);
+  Sec_Eng_PKA_MMUL(3, 3, 3, 15, 3, 15, 3, 0, 0);
+
+  // V^3
+  // PKA_MMUL(0,3, 4,3, 3,3,15,3,0);
+  Sec_Eng_PKA_MMUL(3, 4, 3, 3, 3, 15, 3, 0, 0);
+
+  // U^2
+  // PKA_MMUL(0,3,17,3,13,3,13,3,0);
+  Sec_Eng_PKA_MMUL(3, 17, 3, 13, 3, 13, 3, 0, 0);
+
+  // U^2*W
+  // PKA_MMUL(0,3,17,3,17,3, 2,3,0);
+  Sec_Eng_PKA_MMUL(3, 17, 3, 17, 3, 2, 3, 0, 0);
+
+  // U^2*W-V^3
+  // PKA_MSUB(0,3,17,3,17,3, 4,3,0);
+  Sec_Eng_PKA_MSUB(3, 17, 3, 17, 3, 4, 3, 0, 0);
+
+  // 2*V^2
+  // PKA_MMUL(0,3,18,3, 9,3, 3,3,0);
+  Sec_Eng_PKA_MMUL(3, 18, 3, 9, 3, 3, 3, 0, 0);
+
+  // 2*V^2*V2
+  // PKA_MMUL(0,3,18,3,18,3,16,3,0);
+  Sec_Eng_PKA_MMUL(3, 18, 3, 18, 3, 16, 3, 0, 0);
+
+  // A = U^2*W-V^3-2*V^2*V2
+  // PKA_MSUB(0,3,18,3,17,3,18,3,0);
+  Sec_Eng_PKA_MSUB(3, 18, 3, 17, 3, 18, 3, 0, 0);
+
+  // V^2*V2
+  // PKA_MMUL(0,3, 3,3, 3,3,16,3,0);
+  Sec_Eng_PKA_MMUL(3, 3, 3, 3, 3, 16, 3, 0, 0);
+
+  // V^3*U2
+  // PKA_MMUL(0,3,14,3, 4,3,14,3,0);
+  Sec_Eng_PKA_MMUL(3, 14, 3, 4, 3, 14, 3, 0, 0);
+
+  // Z3 = V^3*W
+  // PKA_MMUL(0,3, 4,3, 4,3, 2,3,0);
+  Sec_Eng_PKA_MMUL(3, 4, 3, 4, 3, 2, 3, 0, 0);
+
+  // X3 = V*A
+  // PKA_MMUL(0,3, 2,3,15,3,18,3,0);
+  Sec_Eng_PKA_MMUL(3, 2, 3, 15, 3, 18, 3, 0, 0);
+
+  // V^2*V2-A
+  // PKA_MSUB(0,3, 3,3, 3,3,18,3,0);
+  Sec_Eng_PKA_MSUB(3, 3, 3, 3, 3, 18, 3, 0, 0);
+
+  // U*(V^2*V2-A)
+  // PKA_MMUL(0,3, 3,3,13,3, 3,3,0);
+  Sec_Eng_PKA_MMUL(3, 3, 3, 13, 3, 3, 3, 0, 0);
+
+  // Y3 = U*(V^2*V2-A)-V^3*U2
+  // PKA_MSUB(1,3, 3,3, 3,3,14,3,0);
+  Sec_Eng_PKA_MSUB(3, 3, 3, 3, 3, 14, 3, 0, 1);
 }
 /**
  * @brief calculate secp256r1's W
  *
  * @note index 13:W = 3X^2-3Z^2
  */
-static void sec_ecdsa_cal_secp256r1_w(void)
-{
-    //X1^2
-    //PKA_MMUL(0,3,13,3, 5,3, 5,3,0);//d_reg_type,d_reg_idx,s0_reg_type,s0_reg_idx,s1_reg_type,s1_reg_idx,s2_reg_type,s2_reg_idx
-    Sec_Eng_PKA_MMUL(3, 13, 3, 5, 3, 5, 3, 0, 0);
-
-    //Z1^2
-    //PKA_MMUL(0,3,14,3, 7,3, 7,3,0);
-    Sec_Eng_PKA_MMUL(3, 14, 3, 7, 3, 7, 3, 0, 0);
-
-    //X1^2-Z1^2
-    //PKA_MSUB(0,3,13,3,13,3,14,3,0);
-    Sec_Eng_PKA_MSUB(3, 13, 3, 13, 3, 14, 3, 0, 0);
-
-    //W = 3*(X1^2-Z1^2)
-    //PKA_MMUL(0,3,13,3,10,3,13,3,0);
-    Sec_Eng_PKA_MMUL(3, 13, 3, 10, 3, 13, 3, 0, 0);
+static void sec_ecdsa_cal_secp256r1_w(void) {
+  // X1^2
+  // PKA_MMUL(0,3,13,3, 5,3, 5,3,0);//d_reg_type,d_reg_idx,s0_reg_type,s0_reg_idx,s1_reg_type,s1_reg_idx,s2_reg_type,s2_reg_idx
+  Sec_Eng_PKA_MMUL(3, 13, 3, 5, 3, 5, 3, 0, 0);
+
+  // Z1^2
+  // PKA_MMUL(0,3,14,3, 7,3, 7,3,0);
+  Sec_Eng_PKA_MMUL(3, 14, 3, 7, 3, 7, 3, 0, 0);
+
+  // X1^2-Z1^2
+  // PKA_MSUB(0,3,13,3,13,3,14,3,0);
+  Sec_Eng_PKA_MSUB(3, 13, 3, 13, 3, 14, 3, 0, 0);
+
+  // W = 3*(X1^2-Z1^2)
+  // PKA_MMUL(0,3,13,3,10,3,13,3,0);
+  Sec_Eng_PKA_MMUL(3, 13, 3, 10, 3, 13, 3, 0, 0);
 }
 
 /**
@@ -443,1008 +344,955 @@ static void sec_ecdsa_cal_secp256r1_w(void)
  *
  * @note index 13:W = 3X^2
  */
-static void sec_ecdsa_cal_secp256k1_w(void)
-{
-    //X1^2
-    Sec_Eng_PKA_MMUL(3, 13, 3, 5, 3, 5, 3, 0, 0);
+static void sec_ecdsa_cal_secp256k1_w(void) {
+  // X1^2
+  Sec_Eng_PKA_MMUL(3, 13, 3, 5, 3, 5, 3, 0, 0);
 
-    //W = 3* (X1^2)
-    Sec_Eng_PKA_MMUL(3, 13, 3, 10, 3, 13, 3, 0, 0);
+  // W = 3* (X1^2)
+  Sec_Eng_PKA_MMUL(3, 13, 3, 10, 3, 13, 3, 0, 0);
 }
 
-static BL_Err_Type sec_ecdsa_point_double(sec_ecp_type id)
-{
-    /* index 2:BAR_Zero_x
-     * index 3:BAR_Zero_y
-     * index 4:BAR_Zero_z
-     * index 5:BAR_G_x
-     * index 6:BAR_G_y
-     * index 7:BAR_G_z
-     * index 8:1
-     * index 9:2
-     * index 10:3
-     * index 11:4
-     * index 12:8
-     * index 19:1P1
-     * index 20:1m1*/
-
-    if (id >= ECP_TYPE_MAX) {
-        return ERROR;
-    }
-
-    if (id == ECP_SECP256R1) {
-        sec_ecdsa_cal_secp256r1_w();
-    } else if (id == ECP_SECP256K1) {
-        sec_ecdsa_cal_secp256k1_w();
-    }
-
-    //S = Y1*Z1
-    //PKA_MMUL(0,3,14,3, 6,3, 7,3,0);
-    Sec_Eng_PKA_MMUL(3, 14, 3, 6, 3, 7, 3, 0, 0);
-
-    //X1*Y1
-    //PKA_MMUL(0,3,15,3, 5,3, 6,3,0);
-    Sec_Eng_PKA_MMUL(3, 15, 3, 5, 3, 6, 3, 0, 0);
-
-    //W^2
-    //PKA_MMUL(0,3, 7,3,13,3,13,3,0);
-    Sec_Eng_PKA_MMUL(3, 7, 3, 13, 3, 13, 3, 0, 0);
-
-    //B = X1*Y1*S
-    //PKA_MMUL(0,3,15,3,15,3,14,3,0);
-    Sec_Eng_PKA_MMUL(3, 15, 3, 15, 3, 14, 3, 0, 0);
-
-    //8*B
-    //PKA_MMUL(0,3, 5,3,12,3,15,3,0);
-    Sec_Eng_PKA_MMUL(3, 5, 3, 12, 3, 15, 3, 0, 0);
-
-    //H = W^2-8*B
-    //PKA_MSUB(0,3, 7,3, 7,3, 5,3,0);
-    Sec_Eng_PKA_MSUB(3, 7, 3, 7, 3, 5, 3, 0, 0);
-
-    //2*H
-    //PKA_MMUL(0,3, 5,3, 9,3, 7,3,0);
-    Sec_Eng_PKA_MMUL(3, 5, 3, 9, 3, 7, 3, 0, 0);
-
-    //X2 = 2*H*S
-    //PKA_MMUL(0,3, 5,3, 5,3,14,3,0);
-    Sec_Eng_PKA_MMUL(3, 5, 3, 5, 3, 14, 3, 0, 0);
-
-    //4*B
-    //PKA_MMUL(0,3,15,3,11,3,15,3,0);
-    Sec_Eng_PKA_MMUL(3, 15, 3, 11, 3, 15, 3, 0, 0);
-
-    //S^2
-    //PKA_MMUL(0,3,16,3,14,3,14,3,0);
-    Sec_Eng_PKA_MMUL(3, 16, 3, 14, 3, 14, 3, 0, 0);
-
-    //4*B-H
-    //PKA_MSUB(0,3,15,3,15,3, 7,3,0);
-    Sec_Eng_PKA_MSUB(3, 15, 3, 15, 3, 7, 3, 0, 0);
-
-    //Y1^2
-    //PKA_MMUL(0,3, 6,3, 6,3, 6,3,0);
-    Sec_Eng_PKA_MMUL(3, 6, 3, 6, 3, 6, 3, 0, 0);
-
-    //W*(4*B-H)
-    //PKA_MMUL(0,3,15,3,15,3,13,3,0);
-    Sec_Eng_PKA_MMUL(3, 15, 3, 15, 3, 13, 3, 0, 0);
-
-    //8*Y1^2
-    //PKA_MMUL(0,3, 6,3,12,3, 6,3,0);
-    Sec_Eng_PKA_MMUL(3, 6, 3, 12, 3, 6, 3, 0, 0);
-
-    //8*Y1^2*S^2
-    //PKA_MMUL(0,3, 6,3, 6,3,16,3,0);
-    Sec_Eng_PKA_MMUL(3, 6, 3, 6, 3, 16, 3, 0, 0);
-
-    //Y2 = W*(4*B-H)-8*Y1^2*S^2
-    //PKA_MSUB(0,3, 6,3,15,3, 6,3,0);
-    Sec_Eng_PKA_MSUB(3, 6, 3, 15, 3, 6, 3, 0, 0);
-
-    //S^3
-    //PKA_MMUL(0,3, 7,3,14,3,16,3,0);
-    Sec_Eng_PKA_MMUL(3, 7, 3, 14, 3, 16, 3, 0, 0);
-
-    //Z2 = 8*S^3
-    //PKA_MMUL(1,3, 7,3,12,3, 7,3,0);
-    Sec_Eng_PKA_MMUL(3, 7, 3, 12, 3, 7, 3, 0, 1);
-
-    return SUCCESS;
+static BL_Err_Type sec_ecdsa_point_double(sec_ecp_type id) {
+  /* index 2:BAR_Zero_x
+   * index 3:BAR_Zero_y
+   * index 4:BAR_Zero_z
+   * index 5:BAR_G_x
+   * index 6:BAR_G_y
+   * index 7:BAR_G_z
+   * index 8:1
+   * index 9:2
+   * index 10:3
+   * index 11:4
+   * index 12:8
+   * index 19:1P1
+   * index 20:1m1*/
+
+  if (id >= ECP_TYPE_MAX) {
+    return ERROR;
+  }
+
+  if (id == ECP_SECP256R1) {
+    sec_ecdsa_cal_secp256r1_w();
+  } else if (id == ECP_SECP256K1) {
+    sec_ecdsa_cal_secp256k1_w();
+  }
+
+  // S = Y1*Z1
+  // PKA_MMUL(0,3,14,3, 6,3, 7,3,0);
+  Sec_Eng_PKA_MMUL(3, 14, 3, 6, 3, 7, 3, 0, 0);
+
+  // X1*Y1
+  // PKA_MMUL(0,3,15,3, 5,3, 6,3,0);
+  Sec_Eng_PKA_MMUL(3, 15, 3, 5, 3, 6, 3, 0, 0);
+
+  // W^2
+  // PKA_MMUL(0,3, 7,3,13,3,13,3,0);
+  Sec_Eng_PKA_MMUL(3, 7, 3, 13, 3, 13, 3, 0, 0);
+
+  // B = X1*Y1*S
+  // PKA_MMUL(0,3,15,3,15,3,14,3,0);
+  Sec_Eng_PKA_MMUL(3, 15, 3, 15, 3, 14, 3, 0, 0);
+
+  // 8*B
+  // PKA_MMUL(0,3, 5,3,12,3,15,3,0);
+  Sec_Eng_PKA_MMUL(3, 5, 3, 12, 3, 15, 3, 0, 0);
+
+  // H = W^2-8*B
+  // PKA_MSUB(0,3, 7,3, 7,3, 5,3,0);
+  Sec_Eng_PKA_MSUB(3, 7, 3, 7, 3, 5, 3, 0, 0);
+
+  // 2*H
+  // PKA_MMUL(0,3, 5,3, 9,3, 7,3,0);
+  Sec_Eng_PKA_MMUL(3, 5, 3, 9, 3, 7, 3, 0, 0);
+
+  // X2 = 2*H*S
+  // PKA_MMUL(0,3, 5,3, 5,3,14,3,0);
+  Sec_Eng_PKA_MMUL(3, 5, 3, 5, 3, 14, 3, 0, 0);
+
+  // 4*B
+  // PKA_MMUL(0,3,15,3,11,3,15,3,0);
+  Sec_Eng_PKA_MMUL(3, 15, 3, 11, 3, 15, 3, 0, 0);
+
+  // S^2
+  // PKA_MMUL(0,3,16,3,14,3,14,3,0);
+  Sec_Eng_PKA_MMUL(3, 16, 3, 14, 3, 14, 3, 0, 0);
+
+  // 4*B-H
+  // PKA_MSUB(0,3,15,3,15,3, 7,3,0);
+  Sec_Eng_PKA_MSUB(3, 15, 3, 15, 3, 7, 3, 0, 0);
+
+  // Y1^2
+  // PKA_MMUL(0,3, 6,3, 6,3, 6,3,0);
+  Sec_Eng_PKA_MMUL(3, 6, 3, 6, 3, 6, 3, 0, 0);
+
+  // W*(4*B-H)
+  // PKA_MMUL(0,3,15,3,15,3,13,3,0);
+  Sec_Eng_PKA_MMUL(3, 15, 3, 15, 3, 13, 3, 0, 0);
+
+  // 8*Y1^2
+  // PKA_MMUL(0,3, 6,3,12,3, 6,3,0);
+  Sec_Eng_PKA_MMUL(3, 6, 3, 12, 3, 6, 3, 0, 0);
+
+  // 8*Y1^2*S^2
+  // PKA_MMUL(0,3, 6,3, 6,3,16,3,0);
+  Sec_Eng_PKA_MMUL(3, 6, 3, 6, 3, 16, 3, 0, 0);
+
+  // Y2 = W*(4*B-H)-8*Y1^2*S^2
+  // PKA_MSUB(0,3, 6,3,15,3, 6,3,0);
+  Sec_Eng_PKA_MSUB(3, 6, 3, 15, 3, 6, 3, 0, 0);
+
+  // S^3
+  // PKA_MMUL(0,3, 7,3,14,3,16,3,0);
+  Sec_Eng_PKA_MMUL(3, 7, 3, 14, 3, 16, 3, 0, 0);
+
+  // Z2 = 8*S^3
+  // PKA_MMUL(1,3, 7,3,12,3, 7,3,0);
+  Sec_Eng_PKA_MMUL(3, 7, 3, 12, 3, 7, 3, 0, 1);
+
+  return SUCCESS;
 }
 #ifdef ECDSA_DBG_DETAIL
-static void sec_ecdsa_dump_temp_result()
-{
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("2=\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("3=\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("4=\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
-
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("5=\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("6=\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 7, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("7=\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+static void sec_ecdsa_dump_temp_result() {
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("2=\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("3=\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("4=\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("5=\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("6=\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 7, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("7=\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 }
 #endif
-static int sec_ecdsa_verify_point_mul(uint8_t id, const uint32_t *m)
-{
-    uint32_t i, j, k;
-    uint32_t tmp;
-    uint32_t isOne = 0;
-    uint8_t *p = (uint8_t *)m;
-    uint8_t pka_p1_eq_inf, pka_p2_eq_inf;
-
-    /* Remove zeros bytes*/
-    k = 0;
-
-    while (p[k] == 0 && k < 31) {
-        k++;
-    }
+static int sec_ecdsa_verify_point_mul(uint8_t id, const uint32_t *m) {
+  uint32_t i, j, k;
+  uint32_t tmp;
+  uint32_t isOne = 0;
+  uint8_t *p     = (uint8_t *)m;
+  uint8_t  pka_p1_eq_inf, pka_p2_eq_inf;
 
-    i = 31;
+  /* Remove zeros bytes*/
+  k = 0;
 
-    for (; i >= k; i--) {
-        tmp = p[i];
-        j = 0;
+  while (p[k] == 0 && k < 31) {
+    k++;
+  }
 
-        for (j = 0; j < 8; j++) {
-            isOne = tmp & (1 << j);
+  i = 31;
 
-            if (isOne) {
-                sec_ecdsa_point_add_inf_check(&pka_p1_eq_inf, &pka_p2_eq_inf);
+  for (; i >= k; i--) {
+    tmp = p[i];
+    j   = 0;
 
-                if (pka_p1_eq_inf == 1 && pka_p2_eq_inf == 0) {
-                    //sum = X2
-                    sec_ecdsa_copy_x2_to_x1(id);
+    for (j = 0; j < 8; j++) {
+      isOne = tmp & (1 << j);
+
+      if (isOne) {
+        sec_ecdsa_point_add_inf_check(&pka_p1_eq_inf, &pka_p2_eq_inf);
+
+        if (pka_p1_eq_inf == 1 && pka_p2_eq_inf == 0) {
+          // sum = X2
+          sec_ecdsa_copy_x2_to_x1(id);
 #ifdef ECDSA_DBG_DETAIL
-                    MSG("sum = X2\r\n");
-                    sec_ecdsa_dump_temp_result();
+          MSG("sum = X2\r\n");
+          sec_ecdsa_dump_temp_result();
 #endif
-                } else if (pka_p1_eq_inf == 0 && pka_p2_eq_inf == 1) {
-                    //sum = X1
-                    //MSG("sum = X1\r\n");
-                } else if (pka_p1_eq_inf == 0 && pka_p2_eq_inf == 0) {
-                    //sum = X1 + X2
-                    sec_ecdsa_point_add(id);
+        } else if (pka_p1_eq_inf == 0 && pka_p2_eq_inf == 1) {
+          // sum = X1
+          // MSG("sum = X1\r\n");
+        } else if (pka_p1_eq_inf == 0 && pka_p2_eq_inf == 0) {
+          // sum = X1 + X2
+          sec_ecdsa_point_add(id);
 #ifdef ECDSA_DBG_DETAIL
-                    MSG("sum = X1+X2\r\n");
-                    sec_ecdsa_dump_temp_result();
+          MSG("sum = X1+X2\r\n");
+          sec_ecdsa_dump_temp_result();
 #endif
-                } else {
-                    //MSG("Error! infinite point + infinite point\r\n");
-                    return -1;
-                }
-            }
+        } else {
+          // MSG("Error! infinite point + infinite point\r\n");
+          return -1;
+        }
+      }
 
-            sec_ecdsa_point_double(id);
+      sec_ecdsa_point_double(id);
 #ifdef ECDSA_DBG_DETAIL
-            sec_ecdsa_dump_temp_result();
+      sec_ecdsa_dump_temp_result();
 #endif
-        }
+    }
 
-        if (i == 0) {
-            break;
-        }
+    if (i == 0) {
+      break;
     }
+  }
 
-    return 0;
+  return 0;
 }
 
 /*cal d*G if pkX(pky)==NULL
  * cal d(bG) if pkX(pky)!=NULL */
-static int32_t sec_ecdh_get_scalar_point(uint8_t id, const uint32_t *pkX, const uint32_t *pkY, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy)
-{
+static int32_t sec_ecdh_get_scalar_point(uint8_t id, const uint32_t *pkX, const uint32_t *pkY, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy) {
 #ifdef ECDSA_DBG
-    uint32_t pk_z[8];
+  uint32_t pk_z[8];
 #endif
 
-    if (id >= ECP_TYPE_MAX) {
-        return ERROR;
-    }
+  if (id >= ECP_TYPE_MAX) {
+    return ERROR;
+  }
 
-    /* Pointer check */
-    if (private_key == NULL) {
-        return -1;
-    }
+  /* Pointer check */
+  if (private_key == NULL) {
+    return -1;
+  }
 
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
 
-    sec_ecc_basic_parameter_init(id);
+  sec_ecc_basic_parameter_init(id);
 
-    //Clear D[7]
-    //PKA_CREG(1,4, 7,0);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
+  // Clear D[7]
+  // PKA_CREG(1,4, 7,0);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
 
-    sec_ecc_point_mul_init(id);
+  sec_ecc_point_mul_init(id);
 
+  if (id == ECP_SECP256R1) {
+    // X1
+    // PKA_CTREG(3, 2,8,bar_Zero_x);
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256r1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
+    // Y1
+    // PKA_CTREG(3, 3,8,bar_Zero_y);
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256r1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
+  } else if (id == ECP_SECP256K1) {
+    // X1
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256k1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
+    // Y1
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256k1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
+  }
+  // Z1
+  // PKA_CTREG(3, 4,8,bar_Zero_z);
+  // PKA_MOVDAT(1,3, 4,3, 2);
+  Sec_Eng_PKA_Move_Data(3, 4, 3, 2, 1);
+
+  if (pkX == NULL) {
     if (id == ECP_SECP256R1) {
-        //X1
-        //PKA_CTREG(3, 2,8,bar_Zero_x);
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256r1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
-        //Y1
-        //PKA_CTREG(3, 3,8,bar_Zero_y);
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256r1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
+      // X2
+      // PKA_CTREG(3, 5,8,bar_G_x);
+      Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)secp256r1_Gx, ECP_SECP256R1_SIZE / 4, 0);
+      // Y2
+      // PKA_CTREG(3, 6,8,bar_G_y);
+      Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1_Gy, ECP_SECP256R1_SIZE / 4, 0);
     } else if (id == ECP_SECP256K1) {
-        //X1
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256k1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
-        //Y1
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256k1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
+      // X2
+      Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)secp256k1_Gx, ECP_SECP256R1_SIZE / 4, 0);
+      // Y2
+      Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256k1_Gy, ECP_SECP256R1_SIZE / 4, 0);
     }
-    //Z1
-    //PKA_CTREG(3, 4,8,bar_Zero_z);
-    //PKA_MOVDAT(1,3, 4,3, 2);
-    Sec_Eng_PKA_Move_Data(3, 4, 3, 2, 1);
-
-    if (pkX == NULL) {
-        if (id == ECP_SECP256R1) {
-            //X2
-            //PKA_CTREG(3, 5,8,bar_G_x);
-            Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)secp256r1_Gx, ECP_SECP256R1_SIZE / 4, 0);
-            //Y2
-            //PKA_CTREG(3, 6,8,bar_G_y);
-            Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1_Gy, ECP_SECP256R1_SIZE / 4, 0);
-        } else if (id == ECP_SECP256K1) {
-            //X2
-            Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)secp256k1_Gx, ECP_SECP256R1_SIZE / 4, 0);
-            //Y2
-            Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256k1_Gy, ECP_SECP256R1_SIZE / 4, 0);
-        }
-    } else {
-        /* chaneg peer's public key to mont domain*/
-        //PUB_x
-        //PKA_CTREG(3, 5,8,PUB_x);
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pkX, ECP_SECP256R1_SIZE / 4, 0);
-        //bar_pub_x
-        //PKA_GF2MONT(3, 5,3, 5);
-        /* Change s to Mont domain,remember to clear temp register and index 0 is P256*/
-        /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
-        Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-        Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-        Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, 256,
-                            ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+  } else {
+    /* chaneg peer's public key to mont domain*/
+    // PUB_x
+    // PKA_CTREG(3, 5,8,PUB_x);
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pkX, ECP_SECP256R1_SIZE / 4, 0);
+    // bar_pub_x
+    // PKA_GF2MONT(3, 5,3, 5);
+    /* Change s to Mont domain,remember to clear temp register and index 0 is P256*/
+    /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
+    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+    Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, 256, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
 #ifdef ECDSA_DBG
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-        MSG("PK.x in Mont:\r\n");
-        bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+    MSG("PK.x in Mont:\r\n");
+    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
 
-        //PUB_y
-        //PKA_CTREG(3, 6,8,PUB_y);
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pkY, ECP_SECP256R1_SIZE / 4, 0);
-        //bar_pub_y
-        //PKA_GF2MONT(3, 6,3, 6);
-        Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-        Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-        Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 6, 256,
-                            ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+    // PUB_y
+    // PKA_CTREG(3, 6,8,PUB_y);
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pkY, ECP_SECP256R1_SIZE / 4, 0);
+    // bar_pub_y
+    // PKA_GF2MONT(3, 6,3, 6);
+    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+    Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 6, 256, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
 #ifdef ECDSA_DBG
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-        MSG("PK.y in Mont:\r\n");
-        bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+    MSG("PK.y in Mont:\r\n");
+    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
-    }
-
-    //Z2
-    //PKA_CTREG(3, 7,8,bar_G_z);
-    //PKA_MOVDAT(1,3, 7,3, 3);
-    Sec_Eng_PKA_Move_Data(3, 7, 3, 3, 1);
-    /* Clear temp register since it's used in point-mul*/
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
-
-    sec_ecdsa_verify_point_mul(id, private_key);
-    //get bar_u1_x
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pRx, ECP_SECP256R1_SIZE / 4);
+  }
+
+  // Z2
+  // PKA_CTREG(3, 7,8,bar_G_z);
+  // PKA_MOVDAT(1,3, 7,3, 3);
+  Sec_Eng_PKA_Move_Data(3, 7, 3, 3, 1);
+  /* Clear temp register since it's used in point-mul*/
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
+
+  sec_ecdsa_verify_point_mul(id, private_key);
+  // get bar_u1_x
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pRx, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u1_x\r\n");
-    bflb_platform_dump(pRx, ECP_SECP256R1_SIZE);
+  MSG("bar_u1_x\r\n");
+  bflb_platform_dump(pRx, ECP_SECP256R1_SIZE);
 #endif
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pRy, ECP_SECP256R1_SIZE / 4);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pRy, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u1_y\r\n");
-    bflb_platform_dump(pRy, ECP_SECP256R1_SIZE);
+  MSG("bar_u1_y\r\n");
+  bflb_platform_dump(pRy, ECP_SECP256R1_SIZE);
 #endif
 #ifdef ECDSA_DBG
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)pk_z, ECP_SECP256R1_SIZE / 4);
-    MSG("bar_u1_z\r\n");
-    bflb_platform_dump(pk_z, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)pk_z, ECP_SECP256R1_SIZE / 4);
+  MSG("bar_u1_z\r\n");
+  bflb_platform_dump(pk_z, ECP_SECP256R1_SIZE);
 #endif
 
-    //get R.x
-    //R.z ^ -1
-    Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_REG_TYPE, 0, 1);
-    if (id == ECP_SECP256R1) {
-        //inv_r
-        //PKA_CTREG(3, 6,8,inv_r);
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
-    } else if (id == ECP_SECP256K1) {
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256k1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
-    }
-    //R.z ^ -1
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-    //PKA_MONT2GF(3, 5,3, 5,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-
-    //R.x (Montgomery to GF)
-    //PKA_MONT2GF(3, 6,3, 2,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-
-    //R.x (GF to Affine domain)
-    //PKA_MONT2GF(3, 2,3, 5,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pRx, ECP_SECP256R1_SIZE / 4);
+  // get R.x
+  // R.z ^ -1
+  Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_REG_TYPE, 0, 1);
+  if (id == ECP_SECP256R1) {
+    // inv_r
+    // PKA_CTREG(3, 6,8,inv_r);
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
+  } else if (id == ECP_SECP256K1) {
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256k1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
+  }
+  // R.z ^ -1
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+  // PKA_MONT2GF(3, 5,3, 5,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+
+  // R.x (Montgomery to GF)
+  // PKA_MONT2GF(3, 6,3, 2,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+
+  // R.x (GF to Affine domain)
+  // PKA_MONT2GF(3, 2,3, 5,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pRx, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("R.x=\r\n");
-    bflb_platform_dump(pRx, ECP_SECP256R1_SIZE);
+  MSG("R.x=\r\n");
+  bflb_platform_dump(pRx, ECP_SECP256R1_SIZE);
 #endif
-    if (id == ECP_SECP256R1) {
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
-    } else if (id == ECP_SECP256K1) {
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256k1N, ECP_SECP256R1_SIZE / 4, 0);
-    }
-
-    Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 2,
-                     ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pRx, ECP_SECP256R1_SIZE / 4);
+  if (id == ECP_SECP256R1) {
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
+  } else if (id == ECP_SECP256K1) {
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256k1N, ECP_SECP256R1_SIZE / 4, 0);
+  }
+
+  Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pRx, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("R.x%n=\r\n");
-    bflb_platform_dump(pRx, ECP_SECP256R1_SIZE);
+  MSG("R.x%n=\r\n");
+  bflb_platform_dump(pRx, ECP_SECP256R1_SIZE);
 #endif
-    if (id == ECP_SECP256R1) {
-        /*after %n,re write p*/
-        Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 0, (uint32_t *)secp256r1P, ECP_SECP256R1_SIZE / 4, 0);
-    } else if (id == ECP_SECP256K1) {
-        Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 0, (uint32_t *)secp256k1P, ECP_SECP256R1_SIZE / 4, 0);
-    }
-
-    //get R.y
-    //R.z ^ -1
-    Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_REG_TYPE, 0, 1);
-    //inv_r
-    //PKA_CTREG(3, 6,8,inv_r);
-    if (id == ECP_SECP256R1) {
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
-    } else if (id == ECP_SECP256K1) {
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256k1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
-    }
-    //R.z ^ -1
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-    //PKA_MONT2GF(3, 5,3, 5,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-    //R.x (Montgomery to GF)
-    //PKA_MONT2GF(3, 6,3, 2,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 3, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-
-    //R.x (GF to Affine domain)
-    //PKA_MONT2GF(3, 2,3, 5,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 3, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pRy, ECP_SECP256R1_SIZE / 4);
+  if (id == ECP_SECP256R1) {
+    /*after %n,re write p*/
+    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 0, (uint32_t *)secp256r1P, ECP_SECP256R1_SIZE / 4, 0);
+  } else if (id == ECP_SECP256K1) {
+    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 0, (uint32_t *)secp256k1P, ECP_SECP256R1_SIZE / 4, 0);
+  }
+
+  // get R.y
+  // R.z ^ -1
+  Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_REG_TYPE, 0, 1);
+  // inv_r
+  // PKA_CTREG(3, 6,8,inv_r);
+  if (id == ECP_SECP256R1) {
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
+  } else if (id == ECP_SECP256K1) {
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256k1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
+  }
+  // R.z ^ -1
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+  // PKA_MONT2GF(3, 5,3, 5,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+  // R.x (Montgomery to GF)
+  // PKA_MONT2GF(3, 6,3, 2,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 3, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+
+  // R.x (GF to Affine domain)
+  // PKA_MONT2GF(3, 2,3, 5,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 3, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pRy, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("R.y=\r\n");
-    bflb_platform_dump(pRy, ECP_SECP256R1_SIZE);
+  MSG("R.y=\r\n");
+  bflb_platform_dump(pRy, ECP_SECP256R1_SIZE);
 #endif
-    if (id == ECP_SECP256R1) {
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
-    } else if (id == ECP_SECP256K1) {
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256k1N, ECP_SECP256R1_SIZE / 4, 0);
-    }
-    Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, 3, ECP_SECP256R1_REG_TYPE, 3,
-                     ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pRy, ECP_SECP256R1_SIZE / 4);
+  if (id == ECP_SECP256R1) {
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
+  } else if (id == ECP_SECP256K1) {
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256k1N, ECP_SECP256R1_SIZE / 4, 0);
+  }
+  Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, 3, ECP_SECP256R1_REG_TYPE, 3, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pRy, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("R.y%n=\r\n");
-    bflb_platform_dump(pRy, ECP_SECP256R1_SIZE);
+  MSG("R.y%n=\r\n");
+  bflb_platform_dump(pRy, ECP_SECP256R1_SIZE);
 #endif
-    return 0;
+  return 0;
 }
 
-static int32_t sec_ecc_is_zero(uint8_t *a, uint32_t len)
-{
-    uint32_t i = 0;
+static int32_t sec_ecc_is_zero(uint8_t *a, uint32_t len) {
+  uint32_t i = 0;
 
-    for (i = 0; i < len; i++) {
-        if (a[i] != 0) {
-            return 0;
-        }
+  for (i = 0; i < len; i++) {
+    if (a[i] != 0) {
+      return 0;
     }
+  }
 
-    return 1;
+  return 1;
 }
 
-static int32_t sec_ecc_cmp(uint8_t *a, uint8_t *b, uint32_t len)
-{
-    uint32_t i = 0, j = 0;
+static int32_t sec_ecc_cmp(uint8_t *a, uint8_t *b, uint32_t len) {
+  uint32_t i = 0, j = 0;
 
-    for (i = 0; i < len; i++) {
-        if (a[i] != 0) {
-            break;
-        }
+  for (i = 0; i < len; i++) {
+    if (a[i] != 0) {
+      break;
     }
+  }
 
-    for (j = 0; j < len; j++) {
-        if (b[j] != 0) {
-            break;
-        }
+  for (j = 0; j < len; j++) {
+    if (b[j] != 0) {
+      break;
     }
+  }
 
-    if (i == len && j == len) {
-        return (0);
-    }
+  if (i == len && j == len) {
+    return (0);
+  }
 
-    if (i > j) {
-        return (-1);
-    }
+  if (i > j) {
+    return (-1);
+  }
 
-    if (j > i) {
-        return (1);
-    }
+  if (j > i) {
+    return (1);
+  }
 
-    for (; i < len; i++) {
-        if (a[i] > b[i]) {
-            return (1);
-        }
+  for (; i < len; i++) {
+    if (a[i] > b[i]) {
+      return (1);
+    }
 
-        if (a[i] < b[i]) {
-            return (-1);
-        }
+    if (a[i] < b[i]) {
+      return (-1);
     }
+  }
 
-    return 0;
+  return 0;
 }
 
-int sec_ecdsa_init(sec_ecdsa_handle_t *handle, sec_ecp_type id)
-{
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
-    Sec_Eng_Trng_Enable();
+int sec_ecdsa_init(sec_ecdsa_handle_t *handle, sec_ecp_type id) {
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
+  Sec_Eng_Trng_Enable();
 
-    handle->ecpId = id;
+  handle->ecpId = id;
 
-    return 0;
+  return 0;
 }
 
-int sec_ecdsa_deinit(sec_ecdsa_handle_t *handle)
-{
-    Sec_Eng_PKA_Reset();
+int sec_ecdsa_deinit(sec_ecdsa_handle_t *handle) {
+  Sec_Eng_PKA_Reset();
 
-    return 0;
+  return 0;
 }
 
-int sec_ecdsa_verify(sec_ecdsa_handle_t *handle, const uint32_t *hash, uint32_t hashLenInWord, const uint32_t *r, const uint32_t *s)
-{
-    uint32_t bar_u1_x[8];
-    uint32_t bar_u1_y[8];
-    uint32_t bar_u1_z[8];
-    uint32_t bar_u2_x[8];
-    uint32_t bar_u2_y[8];
-    uint32_t bar_u2_z[8];
-    uint32_t pka_u1[8] = { 0 };
-    uint32_t pka_u2[8] = { 0 };
-    uint32_t i = 0;
-
-    /* Pointer check */
-    if (hash == NULL || handle->publicKeyx == NULL || handle->publicKeyy == NULL || r == NULL || s == NULL) {
-        return -1;
-    }
-
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
+int sec_ecdsa_verify(sec_ecdsa_handle_t *handle, const uint32_t *hash, uint32_t hashLenInWord, const uint32_t *r, const uint32_t *s) {
+  uint32_t bar_u1_x[8];
+  uint32_t bar_u1_y[8];
+  uint32_t bar_u1_z[8];
+  uint32_t bar_u2_x[8];
+  uint32_t bar_u2_y[8];
+  uint32_t bar_u2_z[8];
+  uint32_t pka_u1[8] = {0};
+  uint32_t pka_u2[8] = {0};
+  uint32_t i         = 0;
+
+  /* Pointer check */
+  if (hash == NULL || handle->publicKeyx == NULL || handle->publicKeyy == NULL || r == NULL || s == NULL) {
+    return -1;
+  }
 
-    /*Step 0: make sure r and s are in range 1..n-1*/
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
 
-    /* r and s should not be 0*/
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 8, (uint32_t *)secp256r1_1, ECP_SECP256R1_SIZE / 4, 0);
-    //cout = 1 if r = 0
-    Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, 8); //s0 < s1 => cout = 1
+  /*Step 0: make sure r and s are in range 1..n-1*/
 
-    if (i == 1) {
-        return -1;
-    }
+  /* r and s should not be 0*/
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 8, (uint32_t *)secp256r1_1, ECP_SECP256R1_SIZE / 4, 0);
+  // cout = 1 if r = 0
+  Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, 8); // s0 < s1 => cout = 1
 
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)s, ECP_SECP256R1_SIZE / 4, 0);
-    //cout = 1 if r = 0
-    Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, 8); //s0 < s1 => cout = 1
-
-    if (i == 1) {
-        return -1;
-    }
+  if (i == 1) {
+    return -1;
+  }
 
-    sec_ecc_basic_parameter_init(handle->ecpId);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)s, ECP_SECP256R1_SIZE / 4, 0);
+  // cout = 1 if r = 0
+  Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, 8); // s0 < s1 => cout = 1
 
-    /* r and s should not be 0*/
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
-    //cout = 1 if r < N
-    Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
+  if (i == 1) {
+    return -1;
+  }
 
-    if (i != 1) {
-        return -1;
-    }
+  sec_ecc_basic_parameter_init(handle->ecpId);
 
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)s, ECP_SECP256R1_SIZE / 4, 0);
-    //cout = 1 if r < N
-    Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
+  /* r and s should not be 0*/
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
+  // cout = 1 if r < N
+  Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
 
-    if (i != 1) {
-        return -1;
-    }
+  if (i != 1) {
+    return -1;
+  }
 
-    /* u1 = e / s mod n, u2 = r / s mod n
-     * R = u1 G + u2 Q*/
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)s, ECP_SECP256R1_SIZE / 4, 0);
+  // cout = 1 if r < N
+  Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
 
-    /* Step1: Get S^-1*/
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)s, ECP_SECP256R1_SIZE / 4, 0);
-    /* Change s to Mont domain */
-    /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, 256,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
+  if (i != 1) {
+    return -1;
+  }
+
+  /* u1 = e / s mod n, u2 = r / s mod n
+   * R = u1 G + u2 Q*/
+
+  /* Step1: Get S^-1*/
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)s, ECP_SECP256R1_SIZE / 4, 0);
+  /* Change s to Mont domain */
+  /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, 256, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX,
+                      ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
 #ifdef ECDSA_DBG
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("GF2Mont Result of s:\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("GF2Mont Result of s:\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Get S^-1 in Mont domain */
-    Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_BAR_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX,
-                     ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
+  /* Get S^-1 in Mont domain */
+  Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_BAR_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
 #ifdef ECDSA_DBG
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_BAR_S_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("s^-1 in Mont:\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_BAR_S_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("s^-1 in Mont:\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Change S^-1 into GF domain,now  ECP_SECP256R1_S_REG_INDEX store s^-1*/
-    /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_BAR_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_INVR_N_REG_INDEX,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
+  /* Change S^-1 into GF domain,now  ECP_SECP256R1_S_REG_INDEX store s^-1*/
+  /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_BAR_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_INVR_N_REG_INDEX,
+                      ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
 #ifdef ECDSA_DBG
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("S^-1:\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("S^-1:\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Step2: Get u1*/
-    //u1=hash(e)*s^-1;
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX, (uint32_t *)hash, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_LMUL(ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX,
-                     ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, 0);
-    Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX,
-                     ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, (uint32_t *)pka_u1, ECP_SECP256R1_SIZE / 4);
+  /* Step2: Get u1*/
+  // u1=hash(e)*s^-1;
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX, (uint32_t *)hash, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_LMUL(ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, 0);
+  Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, (uint32_t *)pka_u1, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("u1:\r\n");
-    bflb_platform_dump(pka_u1, ECP_SECP256R1_SIZE);
+  MSG("u1:\r\n");
+  bflb_platform_dump(pka_u1, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Step3: Get u2*/
-    //u2=r*s^-1;
-    // use hash and u1 temp register
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_LMUL(ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX,
-                     ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, 0);
-    Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX,
-                     ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, (uint32_t *)pka_u2, ECP_SECP256R1_SIZE / 4);
+  /* Step3: Get u2*/
+  // u2=r*s^-1;
+  //  use hash and u1 temp register
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_LMUL(ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, 0);
+  Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, (uint32_t *)pka_u2, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("u2:\r\n");
-    bflb_platform_dump(pka_u2, ECP_SECP256R1_SIZE);
+  MSG("u2:\r\n");
+  bflb_platform_dump(pka_u2, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Step4: Get u1*G*/
-
-    //Clear D[7]
-    //PKA_CREG(1,4, 7,0);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
-
-    sec_ecc_point_mul_init(handle->ecpId);
-
-    //X1
-    //PKA_CTREG(3, 2,8,bar_Zero_x);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256r1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
-    //Y1
-    //PKA_CTREG(3, 3,8,bar_Zero_y);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256r1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
-    //Z1
-    //PKA_CTREG(3, 4,8,bar_Zero_z);
-    //PKA_MOVDAT(1,3, 4,3, 2);
-    Sec_Eng_PKA_Move_Data(3, 4, 3, 2, 1);
-
-    //X2
-    //PKA_CTREG(3, 5,8,bar_G_x);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)secp256r1_Gx, ECP_SECP256R1_SIZE / 4, 0);
-    //Y2
-    //PKA_CTREG(3, 6,8,bar_G_y);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1_Gy, ECP_SECP256R1_SIZE / 4, 0);
-    //Z2
-    //PKA_CTREG(3, 7,8,bar_G_z);
-    //PKA_MOVDAT(1,3, 7,3, 3);
-    Sec_Eng_PKA_Move_Data(3, 7, 3, 3, 1);
-
-    sec_ecdsa_verify_point_mul(handle->ecpId, pka_u1);
-    //get bar_u1_x
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u1_x, ECP_SECP256R1_SIZE / 4);
+  /* Step4: Get u1*G*/
+
+  // Clear D[7]
+  // PKA_CREG(1,4, 7,0);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
+
+  sec_ecc_point_mul_init(handle->ecpId);
+
+  // X1
+  // PKA_CTREG(3, 2,8,bar_Zero_x);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256r1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
+  // Y1
+  // PKA_CTREG(3, 3,8,bar_Zero_y);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256r1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
+  // Z1
+  // PKA_CTREG(3, 4,8,bar_Zero_z);
+  // PKA_MOVDAT(1,3, 4,3, 2);
+  Sec_Eng_PKA_Move_Data(3, 4, 3, 2, 1);
+
+  // X2
+  // PKA_CTREG(3, 5,8,bar_G_x);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)secp256r1_Gx, ECP_SECP256R1_SIZE / 4, 0);
+  // Y2
+  // PKA_CTREG(3, 6,8,bar_G_y);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1_Gy, ECP_SECP256R1_SIZE / 4, 0);
+  // Z2
+  // PKA_CTREG(3, 7,8,bar_G_z);
+  // PKA_MOVDAT(1,3, 7,3, 3);
+  Sec_Eng_PKA_Move_Data(3, 7, 3, 3, 1);
+
+  sec_ecdsa_verify_point_mul(handle->ecpId, pka_u1);
+  // get bar_u1_x
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u1_x, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u1_x\r\n");
-    bflb_platform_dump(bar_u1_x, ECP_SECP256R1_SIZE);
+  MSG("bar_u1_x\r\n");
+  bflb_platform_dump(bar_u1_x, ECP_SECP256R1_SIZE);
 #endif
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)bar_u1_y, ECP_SECP256R1_SIZE / 4);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)bar_u1_y, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u1_y\r\n");
-    bflb_platform_dump(bar_u1_y, ECP_SECP256R1_SIZE);
+  MSG("bar_u1_y\r\n");
+  bflb_platform_dump(bar_u1_y, ECP_SECP256R1_SIZE);
 #endif
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)bar_u1_z, ECP_SECP256R1_SIZE / 4);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)bar_u1_z, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u1_z\r\n");
-    bflb_platform_dump(bar_u1_z, ECP_SECP256R1_SIZE);
+  MSG("bar_u1_z\r\n");
+  bflb_platform_dump(bar_u1_z, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Step4: Get u2*Q*/
-    //X1
-    //PKA_CTREG(3, 2,8,bar_Zero_x);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256r1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
-    //Y1
-    //PKA_CTREG(3, 3,8,bar_Zero_y);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256r1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
-    //Z1
-    //PKA_CTREG(3, 4,8,bar_Zero_z);
-    //PKA_MOVDAT(1,3, 4,3, 2);
-    Sec_Eng_PKA_Move_Data(3, 4, 3, 2, 1);
-
-    //PUB_x
-    //PKA_CTREG(3, 5,8,PUB_x);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)handle->publicKeyx, ECP_SECP256R1_SIZE / 4, 0);
-    //bar_pub_x
-    //PKA_GF2MONT(3, 5,3, 5);
-    /* Change s to Mont domain,remember to clear temp register and index 0 is P256*/
-    /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, 256,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+  /* Step4: Get u2*Q*/
+  // X1
+  // PKA_CTREG(3, 2,8,bar_Zero_x);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256r1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
+  // Y1
+  // PKA_CTREG(3, 3,8,bar_Zero_y);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256r1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
+  // Z1
+  // PKA_CTREG(3, 4,8,bar_Zero_z);
+  // PKA_MOVDAT(1,3, 4,3, 2);
+  Sec_Eng_PKA_Move_Data(3, 4, 3, 2, 1);
+
+  // PUB_x
+  // PKA_CTREG(3, 5,8,PUB_x);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)handle->publicKeyx, ECP_SECP256R1_SIZE / 4, 0);
+  // bar_pub_x
+  // PKA_GF2MONT(3, 5,3, 5);
+  /* Change s to Mont domain,remember to clear temp register and index 0 is P256*/
+  /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, 256, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
 #ifdef ECDSA_DBG
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("PK.x in Mont:\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("PK.x in Mont:\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
 
-    //PUB_y
-    //PKA_CTREG(3, 6,8,PUB_y);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)handle->publicKeyy, ECP_SECP256R1_SIZE / 4, 0);
-    //bar_pub_y
-    //PKA_GF2MONT(3, 6,3, 6);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 6, 256,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+  // PUB_y
+  // PKA_CTREG(3, 6,8,PUB_y);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)handle->publicKeyy, ECP_SECP256R1_SIZE / 4, 0);
+  // bar_pub_y
+  // PKA_GF2MONT(3, 6,3, 6);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 6, 256, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
 #ifdef ECDSA_DBG
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("PK.y in Mont:\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("PK.y in Mont:\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
 
-    //bar_pub_z
-    //PKA_CTREG(3, 7,8,PUB_z);
-    //PKA_MOVDAT(1,3, 7,3, 3);
-    Sec_Eng_PKA_Move_Data(3, 7, 3, 3, 1);
+  // bar_pub_z
+  // PKA_CTREG(3, 7,8,PUB_z);
+  // PKA_MOVDAT(1,3, 7,3, 3);
+  Sec_Eng_PKA_Move_Data(3, 7, 3, 3, 1);
 
-    /* Clear temp register since it's used in point-mul*/
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
+  /* Clear temp register since it's used in point-mul*/
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
 
-    sec_ecdsa_verify_point_mul(handle->ecpId, pka_u2);
-    //get bar_u1_x
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u2_x, ECP_SECP256R1_SIZE / 4);
+  sec_ecdsa_verify_point_mul(handle->ecpId, pka_u2);
+  // get bar_u1_x
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u2_x, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u2_x\r\n");
-    bflb_platform_dump(bar_u2_x, ECP_SECP256R1_SIZE);
+  MSG("bar_u2_x\r\n");
+  bflb_platform_dump(bar_u2_x, ECP_SECP256R1_SIZE);
 #endif
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)bar_u2_y, ECP_SECP256R1_SIZE / 4);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)bar_u2_y, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u2_y\r\n");
-    bflb_platform_dump(bar_u2_y, ECP_SECP256R1_SIZE);
+  MSG("bar_u2_y\r\n");
+  bflb_platform_dump(bar_u2_y, ECP_SECP256R1_SIZE);
 #endif
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)bar_u2_z, ECP_SECP256R1_SIZE / 4);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)bar_u2_z, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u2_z\r\n");
-    bflb_platform_dump(bar_u2_z, ECP_SECP256R1_SIZE);
+  MSG("bar_u2_z\r\n");
+  bflb_platform_dump(bar_u2_z, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Step5: Get u1*G+u2*Q*/
-    //move bar_u2_x
-    //PKA_MOVDAT(0,3, 5,3, 2);
-    Sec_Eng_PKA_Move_Data(3, 5, 3, 2, 0);
-    //move bar_u2_y
-    //PKA_MOVDAT(0,3, 6,3, 3);
-    Sec_Eng_PKA_Move_Data(3, 6, 3, 3, 0);
-    //move bar_u2_z
-    //PKA_MOVDAT(1,3, 7,3, 4);
-    Sec_Eng_PKA_Move_Data(3, 7, 3, 4, 1);
-
-    //bar_u1_x
-    //PKA_CTREG(3, 2,8,bar_u1_x);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u1_x, ECP_SECP256R1_SIZE / 4, 0);
-    //bar_u1_y
-    //PKA_CTREG(3, 3,8,bar_u1_y);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)bar_u1_y, ECP_SECP256R1_SIZE / 4, 0);
-    //bar_u1_z
-    //PKA_CTREG(3, 4,8,bar_u1_z);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)bar_u1_z, ECP_SECP256R1_SIZE / 4, 0);
-
-    //R = u1 * G + u2 * PUB
-    //PKA_POINT_ADDITION();
-    sec_ecdsa_point_add(handle->ecpId);
-
-    /* Step6 Get R.x(R=u1G+u2P)*/
-    //R.z ^ -1
-    //PKA_MINV(0,3, 5,3, 4,3, 0);
-    Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_REG_TYPE, 0, 1);
-    //inv_r
-    //PKA_CTREG(3, 6,8,inv_r);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
-    //R.z ^ -1
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-    //PKA_MONT2GF(3, 5,3, 5,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-
-    //R.x (Montgomery to GF)
-    //PKA_MONT2GF(3, 6,3, 2,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-
-    //R.x (GF to Affine domain)
-    //PKA_MONT2GF(3, 2,3, 5,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u2_x, ECP_SECP256R1_SIZE / 4);
+  /* Step5: Get u1*G+u2*Q*/
+  // move bar_u2_x
+  // PKA_MOVDAT(0,3, 5,3, 2);
+  Sec_Eng_PKA_Move_Data(3, 5, 3, 2, 0);
+  // move bar_u2_y
+  // PKA_MOVDAT(0,3, 6,3, 3);
+  Sec_Eng_PKA_Move_Data(3, 6, 3, 3, 0);
+  // move bar_u2_z
+  // PKA_MOVDAT(1,3, 7,3, 4);
+  Sec_Eng_PKA_Move_Data(3, 7, 3, 4, 1);
+
+  // bar_u1_x
+  // PKA_CTREG(3, 2,8,bar_u1_x);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u1_x, ECP_SECP256R1_SIZE / 4, 0);
+  // bar_u1_y
+  // PKA_CTREG(3, 3,8,bar_u1_y);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)bar_u1_y, ECP_SECP256R1_SIZE / 4, 0);
+  // bar_u1_z
+  // PKA_CTREG(3, 4,8,bar_u1_z);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)bar_u1_z, ECP_SECP256R1_SIZE / 4, 0);
+
+  // R = u1 * G + u2 * PUB
+  // PKA_POINT_ADDITION();
+  sec_ecdsa_point_add(handle->ecpId);
+
+  /* Step6 Get R.x(R=u1G+u2P)*/
+  // R.z ^ -1
+  // PKA_MINV(0,3, 5,3, 4,3, 0);
+  Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_REG_TYPE, 0, 1);
+  // inv_r
+  // PKA_CTREG(3, 6,8,inv_r);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
+  // R.z ^ -1
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+  // PKA_MONT2GF(3, 5,3, 5,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+
+  // R.x (Montgomery to GF)
+  // PKA_MONT2GF(3, 6,3, 2,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+
+  // R.x (GF to Affine domain)
+  // PKA_MONT2GF(3, 2,3, 5,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u2_x, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("R.x=\r\n");
-    bflb_platform_dump(bar_u2_x, ECP_SECP256R1_SIZE);
+  MSG("R.x=\r\n");
+  bflb_platform_dump(bar_u2_x, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Step7 check R.x=r*/
-    /* Check Result */
-    for (i = 0; i < 8; i++) {
-        if (bar_u2_x[i] != r[i]) {
-            return -1;
-        }
+  /* Step7 check R.x=r*/
+  /* Check Result */
+  for (i = 0; i < 8; i++) {
+    if (bar_u2_x[i] != r[i]) {
+      return -1;
     }
+  }
 
 #ifdef ECDSA_DBG
-    MSG("Verify success\r\n");
+  MSG("Verify success\r\n");
 #endif
-    return 0;
+  return 0;
 }
 
-int sec_ecdsa_sign(sec_ecdsa_handle_t *handle, const uint32_t *random_k, const uint32_t *hash, uint32_t hashLenInWord, uint32_t *r, uint32_t *s)
-{
-    uint32_t k[8];
-    uint32_t Rx[8];
-    uint32_t Ry[8];
-    uint32_t KInvert[8];
-    uint32_t maxTry1 = 100;
+int sec_ecdsa_sign(sec_ecdsa_handle_t *handle, const uint32_t *random_k, const uint32_t *hash, uint32_t hashLenInWord, uint32_t *r, uint32_t *s) {
+  uint32_t k[8];
+  uint32_t Rx[8];
+  uint32_t Ry[8];
+  uint32_t KInvert[8];
+  uint32_t maxTry1 = 100;
 
-    /* Pointer check */
-    if (handle->privateKey == NULL || hash == NULL || r == NULL || s == NULL) {
-        return -1;
-    }
+  /* Pointer check */
+  if (handle->privateKey == NULL || hash == NULL || r == NULL || s == NULL) {
+    return -1;
+  }
 
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
-    Sec_Eng_Trng_Enable();
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
+  Sec_Eng_Trng_Enable();
 
-    while (maxTry1--) {
-        /* step 1 ,get random k*/
-        if (random_k == NULL) {
-            if (sec_ecc_get_random_value(k, (uint32_t *)secp256r1N, 32) < 0) {
-                return -1;
-            }
-        } else {
-            memcpy(k, random_k, 32);
-        }
+  while (maxTry1--) {
+    /* step 1 ,get random k*/
+    if (random_k == NULL) {
+      if (sec_ecc_get_random_value(k, (uint32_t *)secp256r1N, 32) < 0) {
+        return -1;
+      }
+    } else {
+      memcpy(k, random_k, 32);
+    }
 
 #ifdef ECDSA_DBG
-        MSG("Random k:\r\n");
-        bflb_platform_dump(k, ECP_SECP256R1_SIZE);
+    MSG("Random k:\r\n");
+    bflb_platform_dump(k, ECP_SECP256R1_SIZE);
 #endif
 
-        /*step 2, calc R=kG*/
-        if (sec_ecdsa_get_public_key(handle, k, Rx, Ry) < 0) {
-            return -1;
-        }
+    /*step 2, calc R=kG*/
+    if (sec_ecdsa_get_public_key(handle, k, Rx, Ry) < 0) {
+      return -1;
+    }
 
-        if (sec_ecc_is_zero((uint8_t *)Rx, 32)) {
-            continue;
-        }
+    if (sec_ecc_is_zero((uint8_t *)Rx, 32)) {
+      continue;
+    }
 
-        memcpy(r, Rx, 32);
+    memcpy(r, Rx, 32);
 #ifdef ECDSA_DBG
-        MSG("r:\r\n");
-        bflb_platform_dump(r, ECP_SECP256R1_SIZE);
+    MSG("r:\r\n");
+    bflb_platform_dump(r, ECP_SECP256R1_SIZE);
 #endif
-        sec_ecc_basic_parameter_init(handle->ecpId);
-        /* step 3,get k^-1*/
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)k, ECP_SECP256R1_SIZE / 4, 0);
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
-        /* Change k to Mont domain */
-        /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
-        Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-        Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-        Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, 256,
-                            ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
+    sec_ecc_basic_parameter_init(handle->ecpId);
+    /* step 3,get k^-1*/
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)k, ECP_SECP256R1_SIZE / 4, 0);
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
+    /* Change k to Mont domain */
+    /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
+    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+    Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, 256, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
 #ifdef ECDSA_DBG
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-        MSG("GF2Mont Result of k:\r\n");
-        bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+    MSG("GF2Mont Result of k:\r\n");
+    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
 
-        /* Get k^-1 in Mont domain */
-        Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 5,
-                         ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
+    /* Get k^-1 in Mont domain */
+    Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
 #ifdef ECDSA_DBG
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)KInvert, ECP_SECP256R1_SIZE / 4);
-        MSG("k^-1 in Mont:\r\n");
-        bflb_platform_dump(KInvert, ECP_SECP256R1_SIZE);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)KInvert, ECP_SECP256R1_SIZE / 4);
+    MSG("k^-1 in Mont:\r\n");
+    bflb_platform_dump(KInvert, ECP_SECP256R1_SIZE);
 #endif
 
-        /* Change k^-1 into GF domain,now  ECP_SECP256R1_S_REG_INDEX store k^-1*/
-        /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
-        Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_INVR_N_REG_INDEX,
-                            ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)KInvert, ECP_SECP256R1_SIZE / 4);
+    /* Change k^-1 into GF domain,now  ECP_SECP256R1_S_REG_INDEX store k^-1*/
+    /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
+    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_INVR_N_REG_INDEX, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX,
+                        ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)KInvert, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-        MSG("k^-1:\r\n");
-        bflb_platform_dump(KInvert, ECP_SECP256R1_SIZE);
+    MSG("k^-1:\r\n");
+    bflb_platform_dump(KInvert, ECP_SECP256R1_SIZE);
 #endif
 
-        /* Step 4,r*d     ((e + r * d) / k) */
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)handle->privateKey, ECP_SECP256R1_SIZE / 4, 0);
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
-        Sec_Eng_PKA_LMUL(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 4,
-                         ECP_SECP256R1_REG_TYPE, 5, 1);
+    /* Step 4,r*d     ((e + r * d) / k) */
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)handle->privateKey, ECP_SECP256R1_SIZE / 4, 0);
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
+    Sec_Eng_PKA_LMUL(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_REG_TYPE, 5, 1);
 #ifdef ECDSA_DBG
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 2);
-        MSG("r*d:\r\n");
-        bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE * 2);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 2);
+    MSG("r*d:\r\n");
+    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE * 2);
 #endif
 
-        /* Step 5,e+r*d   ((e + r * d) / k) */
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)hash, ECP_SECP256R1_SIZE / 4, 0);
-        Sec_Eng_PKA_LADD(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX,
-                         ECP_SECP256R1_REG_TYPE, 5, 1);
+    /* Step 5,e+r*d   ((e + r * d) / k) */
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)hash, ECP_SECP256R1_SIZE / 4, 0);
+    Sec_Eng_PKA_LADD(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 5, 1);
 #ifdef ECDSA_DBG
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 2);
-        MSG("e+r*d:\r\n");
-        bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE * 2);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 2);
+    MSG("e+r*d:\r\n");
+    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE * 2);
 #endif
 
-        /* Step 6,(e+r*d)*k^-1   ((e + r * d) / k) */
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)KInvert, ECP_SECP256R1_SIZE / 4, 0);
-        Sec_Eng_PKA_LMUL(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX,
-                         ECP_SECP256R1_REG_TYPE, 5, 1);
+    /* Step 6,(e+r*d)*k^-1   ((e + r * d) / k) */
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)KInvert, ECP_SECP256R1_SIZE / 4, 0);
+    Sec_Eng_PKA_LMUL(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 5, 1);
 #ifdef ECDSA_DBG
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 2);
-        MSG("(e+r*d)*k^-1:\r\n");
-        bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE * 2);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 2);
+    MSG("(e+r*d)*k^-1:\r\n");
+    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE * 2);
 #endif
-        /*N write only this time,add following operation will not change this register*/
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
-        Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX,
-                         ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)s, ECP_SECP256R1_SIZE / 4);
+    /*N write only this time,add following operation will not change this register*/
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
+    Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)s, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-        MSG("s:\r\n");
-        bflb_platform_dump(s, ECP_SECP256R1_SIZE);
+    MSG("s:\r\n");
+    bflb_platform_dump(s, ECP_SECP256R1_SIZE);
 #endif
 
-        /* Check s zero*/
-        if (sec_ecc_is_zero((uint8_t *)s, 32)) {
-            continue;
-        }
-
-        return 0;
+    /* Check s zero*/
+    if (sec_ecc_is_zero((uint8_t *)s, 32)) {
+      continue;
     }
 
-    return -1;
+    return 0;
+  }
+
+  return -1;
 }
 
-int sec_ecdsa_get_private_key(sec_ecdsa_handle_t *handle, uint32_t *private_key)
-{
-    if (sec_ecc_get_random_value(private_key, (uint32_t *)secp256r1N, 32) < 0) {
-        return -1;
-    }
+int sec_ecdsa_get_private_key(sec_ecdsa_handle_t *handle, uint32_t *private_key) {
+  if (sec_ecc_get_random_value(private_key, (uint32_t *)secp256r1N, 32) < 0) {
+    return -1;
+  }
 
-    return 0;
+  return 0;
 }
 
-int sec_ecdsa_get_public_key(sec_ecdsa_handle_t *handle, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy)
-{
-    return sec_ecdh_get_scalar_point(handle->ecpId, NULL, NULL, private_key, pRx, pRy);
+int sec_ecdsa_get_public_key(sec_ecdsa_handle_t *handle, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy) {
+  return sec_ecdh_get_scalar_point(handle->ecpId, NULL, NULL, private_key, pRx, pRy);
 }
 
-int sec_ecc_get_random_value(uint32_t *randomData, uint32_t *maxRef, uint32_t size)
-{
-    uint32_t maxTry = 100;
-    int32_t ret = 0;
+int sec_ecc_get_random_value(uint32_t *randomData, uint32_t *maxRef, uint32_t size) {
+  uint32_t maxTry = 100;
+  int32_t  ret    = 0;
 
-    while (maxTry--) {
-        ret = Sec_Eng_Trng_Get_Random((uint8_t *)randomData, size);
+  while (maxTry--) {
+    ret = Sec_Eng_Trng_Get_Random((uint8_t *)randomData, size);
 
-        if (ret < 0) {
-            return -1;
-        }
+    if (ret < 0) {
+      return -1;
+    }
 
-        if (maxRef != NULL) {
-            if (sec_ecc_cmp((uint8_t *)maxRef, (uint8_t *)randomData, size) > 0) {
-                return 0;
-            }
-        } else {
-            return 0;
-        }
+    if (maxRef != NULL) {
+      if (sec_ecc_cmp((uint8_t *)maxRef, (uint8_t *)randomData, size) > 0) {
+        return 0;
+      }
+    } else {
+      return 0;
     }
+  }
 
-    return -1;
+  return -1;
 }
 
-int sec_eng_trng_enable(void)
-{
-    return Sec_Eng_Trng_Enable();
-}
+int sec_eng_trng_enable(void) { return Sec_Eng_Trng_Enable(); }
 
-void sec_eng_trng_disable(void)
-{
-    Sec_Eng_Trng_Disable();
-}
+void sec_eng_trng_disable(void) { Sec_Eng_Trng_Disable(); }
 
-int sec_eng_trng_read(uint8_t data[32])
-{
-    return Sec_Eng_Trng_Read(data);
-}
+int sec_eng_trng_read(uint8_t data[32]) { return Sec_Eng_Trng_Read(data); }
 
-int sec_ecdh_init(sec_ecdh_handle_t *handle, sec_ecp_type id)
-{
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
-    Sec_Eng_Trng_Enable();
+int sec_ecdh_init(sec_ecdh_handle_t *handle, sec_ecp_type id) {
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
+  Sec_Eng_Trng_Enable();
 
-    handle->ecpId = id;
+  handle->ecpId = id;
 
-    return 0;
+  return 0;
 }
 
-int sec_ecdh_deinit(sec_ecdh_handle_t *handle)
-{
-    Sec_Eng_PKA_Reset();
+int sec_ecdh_deinit(sec_ecdh_handle_t *handle) {
+  Sec_Eng_PKA_Reset();
 
-    return 0;
+  return 0;
 }
 
-int sec_ecdh_get_encrypt_key(sec_ecdh_handle_t *handle, const uint32_t *pkX, const uint32_t *pkY, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy)
-{
-    return sec_ecdh_get_scalar_point(handle->ecpId, pkX, pkY, private_key, pRx, pRy);
+int sec_ecdh_get_encrypt_key(sec_ecdh_handle_t *handle, const uint32_t *pkX, const uint32_t *pkY, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy) {
+  return sec_ecdh_get_scalar_point(handle->ecpId, pkX, pkY, private_key, pRx, pRy);
 }
 
-int sec_ecdh_get_public_key(sec_ecdh_handle_t *handle, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy)
-{
-    return sec_ecdh_get_scalar_point(handle->ecpId, NULL, NULL, private_key, pRx, pRy);
+int sec_ecdh_get_public_key(sec_ecdh_handle_t *handle, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy) {
+  return sec_ecdh_get_scalar_point(handle->ecpId, NULL, NULL, private_key, pRx, pRy);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_hash.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_hash.c
index 736c08119e..45c5de92c8 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_hash.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_hash.c
@@ -25,9 +25,7 @@
 
 void SEC_SHA_IRQHandler(void);
 
-static sec_hash_device_t sec_hashx_device[SEC_HASH_MAX_INDEX] = {
-    0
-};
+static sec_hash_device_t sec_hashx_device[SEC_HASH_MAX_INDEX] = {0};
 
 static SEC_Eng_SHA256_Ctx shaCtx;
 
@@ -40,37 +38,36 @@ static SEC_Eng_SHA256_Ctx sha256Ctx;
  * @param oflag
  * @return int
  */
-int sec_hash_open(struct device *dev, uint16_t oflag)
-{
-    sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
-    int ret = 0;
-
-    switch (sec_hash_device->type) {
-        case SEC_HASH_SHA1:
-            ret = -1;
-            break;
-
-        case SEC_HASH_SHA224:
-            Sec_Eng_SHA256_Init(&shaCtx, SEC_ENG_SHA_ID0, SEC_ENG_SHA224, sec_hash_device->shaBuf, sec_hash_device->shaPadding);
-            Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
-            break;
-
-        case SEC_HASH_SHA256:
-            Sec_Eng_SHA256_Init(&shaCtx, SEC_ENG_SHA_ID0, SEC_ENG_SHA256, sec_hash_device->shaBuf, sec_hash_device->shaPadding);
-            Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
-            break;
-
-        case SEC_HASH_SHA384:
-        case SEC_HASH_SHA512:
-            ret = -1;
-            break;
-
-        default:
-            ret = -1;
-            break;
-    }
-
-    return ret;
+int sec_hash_open(struct device *dev, uint16_t oflag) {
+  sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
+  int                ret             = 0;
+
+  switch (sec_hash_device->type) {
+  case SEC_HASH_SHA1:
+    ret = -1;
+    break;
+
+  case SEC_HASH_SHA224:
+    Sec_Eng_SHA256_Init(&shaCtx, SEC_ENG_SHA_ID0, SEC_ENG_SHA224, sec_hash_device->shaBuf, sec_hash_device->shaPadding);
+    Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
+    break;
+
+  case SEC_HASH_SHA256:
+    Sec_Eng_SHA256_Init(&shaCtx, SEC_ENG_SHA_ID0, SEC_ENG_SHA256, sec_hash_device->shaBuf, sec_hash_device->shaPadding);
+    Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
+    break;
+
+  case SEC_HASH_SHA384:
+  case SEC_HASH_SHA512:
+    ret = -1;
+    break;
+
+  default:
+    ret = -1;
+    break;
+  }
+
+  return ret;
 }
 /**
  * @brief
@@ -78,11 +75,10 @@ int sec_hash_open(struct device *dev, uint16_t oflag)
  * @param dev
  * @return int
  */
-int sec_hash_close(struct device *dev)
-{
-    //sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
-    //memset(sec_hash_device, 0, sizeof(sec_hash_device_t)); //will cause crash
-    return 0;
+int sec_hash_close(struct device *dev) {
+  // sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
+  // memset(sec_hash_device, 0, sizeof(sec_hash_device_t)); //will cause crash
+  return 0;
 }
 /**
  * @brief
@@ -92,10 +88,7 @@ int sec_hash_close(struct device *dev)
  * @param args
  * @return int
  */
-int sec_hash_control(struct device *dev, int cmd, void *args)
-{
-    return 0;
-}
+int sec_hash_control(struct device *dev, int cmd, void *args) { return 0; }
 
 /**
  * @brief
@@ -106,35 +99,34 @@ int sec_hash_control(struct device *dev, int cmd, void *args)
  * @param size
  * @return int
  */
-int sec_hash_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size)
-{
-    sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
-    int ret = 0;
-
-    switch (sec_hash_device->type) {
-        case SEC_HASH_SHA1:
-            ret = -1;
-            break;
-
-        case SEC_HASH_SHA224:
-            Sec_Eng_SHA256_Update(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
-            break;
-
-        case SEC_HASH_SHA256:
-            Sec_Eng_SHA256_Update(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
-            break;
-
-        case SEC_HASH_SHA384:
-        case SEC_HASH_SHA512:
-            ret = -1;
-            break;
-
-        default:
-            ret = -1;
-            break;
-    }
-
-    return ret;
+int sec_hash_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size) {
+  sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
+  int                ret             = 0;
+
+  switch (sec_hash_device->type) {
+  case SEC_HASH_SHA1:
+    ret = -1;
+    break;
+
+  case SEC_HASH_SHA224:
+    Sec_Eng_SHA256_Update(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
+    break;
+
+  case SEC_HASH_SHA256:
+    Sec_Eng_SHA256_Update(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
+    break;
+
+  case SEC_HASH_SHA384:
+  case SEC_HASH_SHA512:
+    ret = -1;
+    break;
+
+  default:
+    ret = -1;
+    break;
+  }
+
+  return ret;
 }
 
 /**
@@ -146,37 +138,36 @@ int sec_hash_write(struct device *dev, uint32_t pos, const void *buffer, uint32_
  * @param size
  * @return int
  */
-int sec_hash_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size)
-{
-    sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
-    int ret = 0;
-
-    switch (sec_hash_device->type) {
-        case SEC_HASH_SHA1:
-            ret = -1;
-            break;
-
-        case SEC_HASH_SHA224:
-            Sec_Eng_SHA256_Finish(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
-            ret = 28;
-            break;
-
-        case SEC_HASH_SHA256:
-            Sec_Eng_SHA256_Finish(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
-            ret = 32;
-            break;
-
-        case SEC_HASH_SHA384:
-        case SEC_HASH_SHA512:
-            ret = -1;
-            break;
-
-        default:
-            ret = -1;
-            break;
-    }
-
-    return ret;
+int sec_hash_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size) {
+  sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
+  int                ret             = 0;
+
+  switch (sec_hash_device->type) {
+  case SEC_HASH_SHA1:
+    ret = -1;
+    break;
+
+  case SEC_HASH_SHA224:
+    Sec_Eng_SHA256_Finish(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
+    ret = 28;
+    break;
+
+  case SEC_HASH_SHA256:
+    Sec_Eng_SHA256_Finish(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
+    ret = 32;
+    break;
+
+  case SEC_HASH_SHA384:
+  case SEC_HASH_SHA512:
+    ret = -1;
+    break;
+
+  default:
+    ret = -1;
+    break;
+  }
+
+  return ret;
 }
 
 /**
@@ -186,38 +177,37 @@ int sec_hash_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size)
  * @param type
  * @return int
  */
-int sec_hash_init(sec_hash_handle_t *handle, uint8_t type)
-{
-    int ret = 0;
-
-    switch (type) {
-        case SEC_HASH_SHA1:
-            ret = -1;
-            break;
-
-        case SEC_HASH_SHA224:
-            handle->type = type;
-            Sec_Eng_SHA256_Init(&sha256Ctx, SEC_ENG_SHA_ID0, SEC_ENG_SHA224, handle->shaBuf, handle->shaPadding);
-            Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
-            break;
-
-        case SEC_HASH_SHA256:
-            handle->type = type;
-            Sec_Eng_SHA256_Init(&sha256Ctx, SEC_ENG_SHA_ID0, SEC_ENG_SHA256, handle->shaBuf, handle->shaPadding);
-            Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
-            break;
-
-        case SEC_HASH_SHA384:
-        case SEC_HASH_SHA512:
-            ret = -1;
-            break;
-
-        default:
-            ret = -1;
-            break;
-    }
-
-    return ret;
+int sec_hash_init(sec_hash_handle_t *handle, uint8_t type) {
+  int ret = 0;
+
+  switch (type) {
+  case SEC_HASH_SHA1:
+    ret = -1;
+    break;
+
+  case SEC_HASH_SHA224:
+    handle->type = type;
+    Sec_Eng_SHA256_Init(&sha256Ctx, SEC_ENG_SHA_ID0, SEC_ENG_SHA224, handle->shaBuf, handle->shaPadding);
+    Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
+    break;
+
+  case SEC_HASH_SHA256:
+    handle->type = type;
+    Sec_Eng_SHA256_Init(&sha256Ctx, SEC_ENG_SHA_ID0, SEC_ENG_SHA256, handle->shaBuf, handle->shaPadding);
+    Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
+    break;
+
+  case SEC_HASH_SHA384:
+  case SEC_HASH_SHA512:
+    ret = -1;
+    break;
+
+  default:
+    ret = -1;
+    break;
+  }
+
+  return ret;
 }
 /**
  * @brief
@@ -225,12 +215,11 @@ int sec_hash_init(sec_hash_handle_t *handle, uint8_t type)
  * @param handle
  * @return int
  */
-int sec_hash_deinit(sec_hash_handle_t *handle)
-{
-    memset(handle->shaBuf, 0, sizeof(handle->shaBuf));
-    memset(handle->shaPadding, 0, sizeof(handle->shaPadding));
+int sec_hash_deinit(sec_hash_handle_t *handle) {
+  memset(handle->shaBuf, 0, sizeof(handle->shaBuf));
+  memset(handle->shaPadding, 0, sizeof(handle->shaPadding));
 
-    return 0;
+  return 0;
 }
 
 /**
@@ -241,34 +230,33 @@ int sec_hash_deinit(sec_hash_handle_t *handle)
  * @param size
  * @return int
  */
-int sec_hash_update(sec_hash_handle_t *handle, const void *buffer, uint32_t size)
-{
-    int ret = 0;
-
-    switch (handle->type) {
-        case SEC_HASH_SHA1:
-            ret = -1;
-            break;
-
-        case SEC_HASH_SHA224:
-            Sec_Eng_SHA256_Update(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
-            break;
-
-        case SEC_HASH_SHA256:
-            Sec_Eng_SHA256_Update(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
-            break;
-
-        case SEC_HASH_SHA384:
-        case SEC_HASH_SHA512:
-            ret = -1;
-            break;
-
-        default:
-            ret = -1;
-            break;
-    }
-
-    return ret;
+int sec_hash_update(sec_hash_handle_t *handle, const void *buffer, uint32_t size) {
+  int ret = 0;
+
+  switch (handle->type) {
+  case SEC_HASH_SHA1:
+    ret = -1;
+    break;
+
+  case SEC_HASH_SHA224:
+    Sec_Eng_SHA256_Update(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
+    break;
+
+  case SEC_HASH_SHA256:
+    Sec_Eng_SHA256_Update(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
+    break;
+
+  case SEC_HASH_SHA384:
+  case SEC_HASH_SHA512:
+    ret = -1;
+    break;
+
+  default:
+    ret = -1;
+    break;
+  }
+
+  return ret;
 }
 
 /**
@@ -278,36 +266,35 @@ int sec_hash_update(sec_hash_handle_t *handle, const void *buffer, uint32_t size
  * @param buffer
  * @return int
  */
-int sec_hash_finish(sec_hash_handle_t *handle, void *buffer)
-{
-    int ret = 0;
-
-    switch (handle->type) {
-        case SEC_HASH_SHA1:
-            ret = -1;
-            break;
-
-        case SEC_HASH_SHA224:
-            Sec_Eng_SHA256_Finish(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
-            ret = 28;
-            break;
-
-        case SEC_HASH_SHA256:
-            Sec_Eng_SHA256_Finish(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
-            ret = 32;
-            break;
-
-        case SEC_HASH_SHA384:
-        case SEC_HASH_SHA512:
-            ret = -1;
-            break;
-
-        default:
-            ret = -1;
-            break;
-    }
-
-    return ret;
+int sec_hash_finish(sec_hash_handle_t *handle, void *buffer) {
+  int ret = 0;
+
+  switch (handle->type) {
+  case SEC_HASH_SHA1:
+    ret = -1;
+    break;
+
+  case SEC_HASH_SHA224:
+    Sec_Eng_SHA256_Finish(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
+    ret = 28;
+    break;
+
+  case SEC_HASH_SHA256:
+    Sec_Eng_SHA256_Finish(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
+    ret = 32;
+    break;
+
+  case SEC_HASH_SHA384:
+  case SEC_HASH_SHA512:
+    ret = -1;
+    break;
+
+  default:
+    ret = -1;
+    break;
+  }
+
+  return ret;
 }
 
 /**
@@ -319,27 +306,26 @@ int sec_hash_finish(sec_hash_handle_t *handle, void *buffer)
  * @param flag
  * @return int
  */
-static int sec_hash_sha_register(enum sec_hash_index_type index, enum sec_hash_type type, const char *name)
-{
-    struct device *dev;
+static int sec_hash_sha_register(enum sec_hash_index_type index, enum sec_hash_type type, const char *name) {
+  struct device *dev;
 
-    if (SEC_HASH_MAX_INDEX == 0) {
-        return -DEVICE_EINVAL;
-    }
+  if (SEC_HASH_MAX_INDEX == 0) {
+    return -DEVICE_EINVAL;
+  }
 
-    dev = &(sec_hashx_device[index].parent);
-    sec_hashx_device[index].type = type;
+  dev                          = &(sec_hashx_device[index].parent);
+  sec_hashx_device[index].type = type;
 
-    dev->open = sec_hash_open;
-    dev->close = sec_hash_close;
-    dev->control = sec_hash_control;
-    dev->write = sec_hash_write;
-    dev->read = sec_hash_read;
+  dev->open    = sec_hash_open;
+  dev->close   = sec_hash_close;
+  dev->control = sec_hash_control;
+  dev->write   = sec_hash_write;
+  dev->read    = sec_hash_read;
 
-    dev->type = DEVICE_CLASS_SEC_HASH;
-    dev->handle = NULL;
+  dev->type   = DEVICE_CLASS_SEC_HASH;
+  dev->handle = NULL;
 
-    return device_register(dev, name);
+  return device_register(dev, name);
 }
 
 /**
@@ -350,10 +336,7 @@ static int sec_hash_sha_register(enum sec_hash_index_type index, enum sec_hash_t
  * @param flag
  * @return int
  */
-int sec_hash_sha256_register(enum sec_hash_index_type index, const char *name)
-{
-    return sec_hash_sha_register(index, SEC_HASH_SHA256, name);
-}
+int sec_hash_sha256_register(enum sec_hash_index_type index, const char *name) { return sec_hash_sha_register(index, SEC_HASH_SHA256, name); }
 
 /**
  * @brief
@@ -363,25 +346,17 @@ int sec_hash_sha256_register(enum sec_hash_index_type index, const char *name)
  * @param flag
  * @return int
  */
-int sec_hash_sha224_register(enum sec_hash_index_type index, const char *name)
-{
-    return sec_hash_sha_register(index, SEC_HASH_SHA224, name);
-}
+int sec_hash_sha224_register(enum sec_hash_index_type index, const char *name) { return sec_hash_sha_register(index, SEC_HASH_SHA224, name); }
 
 /**
  * @brief
  *
  * @param handle
  */
-void sec_hash_isr(void)
-{
-}
+void sec_hash_isr(void) {}
 
 /**
  * @brief
  *
  */
-void SEC_SHA_IRQ(void)
-{
-    sec_hash_isr();
-}
\ No newline at end of file
+void SEC_SHA_IRQ(void) { sec_hash_isr(); }
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c
index 26dbe0bb89..ea8aed72df 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c
@@ -21,10 +21,10 @@
  *
  */
 #include "hal_uart.h"
-#include "hal_dma.h"
-#include "hal_clock.h"
-#include "bl702_uart.h"
 #include "bl702_glb.h"
+#include "bl702_uart.h"
+#include "hal_clock.h"
+#include "hal_dma.h"
 #include "uart_config.h"
 
 #ifdef BSP_USING_UART0
@@ -49,71 +49,69 @@ static uart_device_t uartx_device[UART_MAX_INDEX] = {
  * @param oflag
  * @return int
  */
-int uart_open(struct device *dev, uint16_t oflag)
-{
-    uart_device_t *uart_device = (uart_device_t *)dev;
-    UART_FifoCfg_Type fifoCfg = { 0 };
-    UART_CFG_Type uart_cfg = { 0 };
-
-    /* disable all interrupt */
-    UART_IntMask(uart_device->id, UART_INT_ALL, MASK);
-    /* disable uart before config */
-    UART_Disable(uart_device->id, UART_TXRX);
-
-    uint32_t uart_clk = peripheral_clock_get(PERIPHERAL_CLOCK_UART);
-    uart_cfg.baudRate = uart_device->baudrate;
-    uart_cfg.dataBits = uart_device->databits;
-    uart_cfg.stopBits = uart_device->stopbits;
-    uart_cfg.parity = uart_device->parity;
-    uart_cfg.uartClk = uart_clk;
-    uart_cfg.ctsFlowControl = UART_CTS_FLOWCONTROL_ENABLE;
-    uart_cfg.rtsSoftwareControl = UART_RTS_FLOWCONTROL_ENABLE;
-    uart_cfg.byteBitInverse = UART_MSB_FIRST_ENABLE;
-    uart_cfg.txSoftwareControl = UART_TX_SWCONTROL_ENABLE;
-    uart_cfg.txLinMode = UART_TX_LINMODE_ENABLE;
-    uart_cfg.rxLinMode = UART_RX_LINMODE_ENABLE;
-    uart_cfg.txBreakBitCnt = UART_TX_BREAKBIT_CNT;
-    uart_cfg.rxDeglitch = ENABLE;
-
-    /* uart init with default configuration */
-    UART_Init(uart_device->id, &uart_cfg);
-
-    /* Enable tx free run mode */
-    UART_TxFreeRun(uart_device->id, ENABLE);
-    /*set de-glitch function cycle count value*/
-    UART_SetDeglitchCount(uart_device->id, 2);
-
-    /* Set rx time-out value */
-    UART_SetRxTimeoutValue(uart_device->id, UART_DEFAULT_RTO_TIMEOUT);
-
-    fifoCfg.txFifoDmaThreshold = uart_device->fifo_threshold;
-    fifoCfg.txFifoDmaEnable = DISABLE;
-    fifoCfg.rxFifoDmaThreshold = uart_device->fifo_threshold;
-    fifoCfg.rxFifoDmaEnable = DISABLE;
-
-    if (oflag & DEVICE_OFLAG_STREAM_TX) {
-    }
-    if ((oflag & DEVICE_OFLAG_INT_TX) || (oflag & DEVICE_OFLAG_INT_RX)) {
+int uart_open(struct device *dev, uint16_t oflag) {
+  uart_device_t    *uart_device = (uart_device_t *)dev;
+  UART_FifoCfg_Type fifoCfg     = {0};
+  UART_CFG_Type     uart_cfg    = {0};
+
+  /* disable all interrupt */
+  UART_IntMask(uart_device->id, UART_INT_ALL, MASK);
+  /* disable uart before config */
+  UART_Disable(uart_device->id, UART_TXRX);
+
+  uint32_t uart_clk           = peripheral_clock_get(PERIPHERAL_CLOCK_UART);
+  uart_cfg.baudRate           = uart_device->baudrate;
+  uart_cfg.dataBits           = uart_device->databits;
+  uart_cfg.stopBits           = uart_device->stopbits;
+  uart_cfg.parity             = uart_device->parity;
+  uart_cfg.uartClk            = uart_clk;
+  uart_cfg.ctsFlowControl     = UART_CTS_FLOWCONTROL_ENABLE;
+  uart_cfg.rtsSoftwareControl = UART_RTS_FLOWCONTROL_ENABLE;
+  uart_cfg.byteBitInverse     = UART_MSB_FIRST_ENABLE;
+  uart_cfg.txSoftwareControl  = UART_TX_SWCONTROL_ENABLE;
+  uart_cfg.txLinMode          = UART_TX_LINMODE_ENABLE;
+  uart_cfg.rxLinMode          = UART_RX_LINMODE_ENABLE;
+  uart_cfg.txBreakBitCnt      = UART_TX_BREAKBIT_CNT;
+  uart_cfg.rxDeglitch         = ENABLE;
+
+  /* uart init with default configuration */
+  UART_Init(uart_device->id, &uart_cfg);
+
+  /* Enable tx free run mode */
+  UART_TxFreeRun(uart_device->id, ENABLE);
+  /*set de-glitch function cycle count value*/
+  UART_SetDeglitchCount(uart_device->id, 2);
+
+  /* Set rx time-out value */
+  UART_SetRxTimeoutValue(uart_device->id, UART_DEFAULT_RTO_TIMEOUT);
+
+  fifoCfg.txFifoDmaThreshold = uart_device->fifo_threshold;
+  fifoCfg.txFifoDmaEnable    = DISABLE;
+  fifoCfg.rxFifoDmaThreshold = uart_device->fifo_threshold;
+  fifoCfg.rxFifoDmaEnable    = DISABLE;
+
+  if (oflag & DEVICE_OFLAG_STREAM_TX) {}
+  if ((oflag & DEVICE_OFLAG_INT_TX) || (oflag & DEVICE_OFLAG_INT_RX)) {
 #ifdef BSP_USING_UART0
-        if (uart_device->id == UART0_ID)
-            Interrupt_Handler_Register(UART0_IRQn, UART0_IRQ);
+    if (uart_device->id == UART0_ID)
+      Interrupt_Handler_Register(UART0_IRQn, UART0_IRQ);
 #endif
 #ifdef BSP_USING_UART1
-        if (uart_device->id == UART1_ID)
-            Interrupt_Handler_Register(UART1_IRQn, UART1_IRQ);
+    if (uart_device->id == UART1_ID)
+      Interrupt_Handler_Register(UART1_IRQn, UART1_IRQ);
 #endif
-    }
-    if (oflag & DEVICE_OFLAG_DMA_TX) {
-        fifoCfg.txFifoDmaEnable = ENABLE;
-    }
-    if (oflag & DEVICE_OFLAG_DMA_RX) {
-        fifoCfg.rxFifoDmaEnable = ENABLE;
-    }
-
-    UART_FifoConfig(uart_device->id, &fifoCfg);
-    /* enable uart */
-    UART_Enable(uart_device->id, UART_TXRX);
-    return 0;
+  }
+  if (oflag & DEVICE_OFLAG_DMA_TX) {
+    fifoCfg.txFifoDmaEnable = ENABLE;
+  }
+  if (oflag & DEVICE_OFLAG_DMA_RX) {
+    fifoCfg.rxFifoDmaEnable = ENABLE;
+  }
+
+  UART_FifoConfig(uart_device->id, &fifoCfg);
+  /* enable uart */
+  UART_Enable(uart_device->id, UART_TXRX);
+  return 0;
 }
 /**
  * @brief
@@ -121,17 +119,16 @@ int uart_open(struct device *dev, uint16_t oflag)
  * @param dev
  * @return int
  */
-int uart_close(struct device *dev)
-{
-    uart_device_t *uart_device = (uart_device_t *)dev;
-
-    UART_Disable(uart_device->id, UART_TXRX);
-    if (uart_device->id == 0) {
-        GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART0);
-    } else if (uart_device->id == 1) {
-        GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART1);
-    }
-    return 0;
+int uart_close(struct device *dev) {
+  uart_device_t *uart_device = (uart_device_t *)dev;
+
+  UART_Disable(uart_device->id, UART_TXRX);
+  if (uart_device->id == 0) {
+    GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART0);
+  } else if (uart_device->id == 1) {
+    GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART1);
+  }
+  return 0;
 }
 /**
  * @brief
@@ -141,123 +138,122 @@ int uart_close(struct device *dev)
  * @param args
  * @return int
  */
-int uart_control(struct device *dev, int cmd, void *args)
-{
-    uart_device_t *uart_device = (uart_device_t *)dev;
-
-    switch (cmd) {
-        case DEVICE_CTRL_SET_INT /* constant-expression */: {
-            uint32_t offset = __builtin_ctz((uint32_t)args);
-            while (offset < 9) {
-                if ((uint32_t)args & (1 << offset)) {
-                    UART_IntMask(uart_device->id, offset, UNMASK);
-                }
-                offset++;
-            }
-            if (uart_device->id == UART0_ID)
-                CPU_Interrupt_Enable(UART0_IRQn);
-            else if (uart_device->id == UART1_ID)
-                CPU_Interrupt_Enable(UART1_IRQn);
-
-            break;
-        }
-        case DEVICE_CTRL_CLR_INT /* constant-expression */: {
-            uint32_t offset = __builtin_ctz((uint32_t)args);
-            while (offset < 9) {
-                if ((uint32_t)args & (1 << offset)) {
-                    UART_IntMask(uart_device->id, offset, MASK);
-                }
-                offset++;
-            }
-            if (uart_device->id == UART0_ID)
-                CPU_Interrupt_Disable(UART0_IRQn);
-            else if (uart_device->id == UART1_ID)
-                CPU_Interrupt_Disable(UART1_IRQn);
-
-            break;
-        }
-        case DEVICE_CTRL_GET_INT /* constant-expression */:
-            /* code */
-            break;
-        case DEVICE_CTRL_RESUME /* constant-expression */:
-            UART_Enable(uart_device->id, UART_TXRX);
-            break;
-        case DEVICE_CTRL_SUSPEND /* constant-expression */:
-            UART_Disable(uart_device->id, UART_TXRX);
-            break;
-        case DEVICE_CTRL_CONFIG /* constant-expression */: {
-            uart_param_cfg_t *cfg = (uart_param_cfg_t *)args;
-            UART_CFG_Type uart_cfg;
-
-            uint32_t uart_clk = peripheral_clock_get(PERIPHERAL_CLOCK_UART);
-
-            uart_cfg.uartClk = uart_clk;
-            uart_cfg.baudRate = cfg->baudrate;
-            uart_cfg.stopBits = cfg->stopbits;
-            uart_cfg.parity = cfg->parity;
-            uart_cfg.dataBits = cfg->databits;
-            uart_cfg.ctsFlowControl = UART_CTS_FLOWCONTROL_ENABLE;
-            uart_cfg.rtsSoftwareControl = UART_RTS_FLOWCONTROL_ENABLE;
-            uart_cfg.byteBitInverse = UART_MSB_FIRST_ENABLE;
-            uart_cfg.txSoftwareControl = UART_TX_SWCONTROL_ENABLE;
-            uart_cfg.txLinMode = UART_TX_LINMODE_ENABLE;
-            uart_cfg.rxLinMode = UART_RX_LINMODE_ENABLE;
-            uart_cfg.txBreakBitCnt = UART_TX_BREAKBIT_CNT;
-            uart_cfg.rxDeglitch = ENABLE;
-            UART_Init(uart_device->id, &uart_cfg);
-            /*set de-glitch function cycle count value*/
-            UART_SetDeglitchCount(uart_device->id, 2);
-            break;
-        }
-        case DEVICE_CTRL_GET_CONFIG /* constant-expression */:
-            break;
-        case DEVICE_CTRL_ATTACH_TX_DMA /* constant-expression */:
-            uart_device->tx_dma = (struct device *)args;
-            break;
-        case DEVICE_CTRL_ATTACH_RX_DMA /* constant-expression */:
-            uart_device->rx_dma = (struct device *)args;
-            break;
-        case DEVICE_CTRL_TX_DMA_SUSPEND: {
-            uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, UART_DMA_TX_EN);
-            BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
-            dev->oflag &= ~DEVICE_OFLAG_DMA_TX;
-            break;
-        }
-        case DEVICE_CTRL_RX_DMA_SUSPEND: {
-            uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, UART_DMA_RX_EN);
-            BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
-            dev->oflag &= ~DEVICE_OFLAG_DMA_RX;
-            break;
-        }
-        case DEVICE_CTRL_TX_DMA_RESUME: {
-            uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
-            tmpVal = BL_SET_REG_BIT(tmpVal, UART_DMA_TX_EN);
-            BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
-            dev->oflag |= DEVICE_OFLAG_DMA_TX;
-            break;
-        }
-        case DEVICE_CTRL_RX_DMA_RESUME: {
-            uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
-            tmpVal = BL_SET_REG_BIT(tmpVal, UART_DMA_RX_EN);
-            BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
-            dev->oflag |= DEVICE_OFLAG_DMA_RX;
-            break;
-        }
-        case DEVICE_CTRL_UART_GET_TX_FIFO /* constant-expression */:
-            return UART_GetTxFifoCount(uart_device->id);
-        case DEVICE_CTRL_UART_GET_RX_FIFO /* constant-expression */:
-            return UART_GetRxFifoCount(uart_device->id);
-        case DEVICE_CTRL_UART_CLEAR_TX_FIFO /* constant-expression */:
-            return UART_TxFifoClear(uart_device->id);
-        case DEVICE_CTRL_UART_CLEAR_RX_FIFO /* constant-expression */:
-            return UART_RxFifoClear(uart_device->id);
-        default:
-            break;
+int uart_control(struct device *dev, int cmd, void *args) {
+  uart_device_t *uart_device = (uart_device_t *)dev;
+
+  switch (cmd) {
+  case DEVICE_CTRL_SET_INT /* constant-expression */: {
+    uint32_t offset = __builtin_ctz((uint32_t)args);
+    while (offset < 9) {
+      if ((uint32_t)args & (1 << offset)) {
+        UART_IntMask(uart_device->id, offset, UNMASK);
+      }
+      offset++;
+    }
+    if (uart_device->id == UART0_ID)
+      CPU_Interrupt_Enable(UART0_IRQn);
+    else if (uart_device->id == UART1_ID)
+      CPU_Interrupt_Enable(UART1_IRQn);
+
+    break;
+  }
+  case DEVICE_CTRL_CLR_INT /* constant-expression */: {
+    uint32_t offset = __builtin_ctz((uint32_t)args);
+    while (offset < 9) {
+      if ((uint32_t)args & (1 << offset)) {
+        UART_IntMask(uart_device->id, offset, MASK);
+      }
+      offset++;
     }
+    if (uart_device->id == UART0_ID)
+      CPU_Interrupt_Disable(UART0_IRQn);
+    else if (uart_device->id == UART1_ID)
+      CPU_Interrupt_Disable(UART1_IRQn);
+
+    break;
+  }
+  case DEVICE_CTRL_GET_INT /* constant-expression */:
+    /* code */
+    break;
+  case DEVICE_CTRL_RESUME /* constant-expression */:
+    UART_Enable(uart_device->id, UART_TXRX);
+    break;
+  case DEVICE_CTRL_SUSPEND /* constant-expression */:
+    UART_Disable(uart_device->id, UART_TXRX);
+    break;
+  case DEVICE_CTRL_CONFIG /* constant-expression */: {
+    uart_param_cfg_t *cfg = (uart_param_cfg_t *)args;
+    UART_CFG_Type     uart_cfg;
+
+    uint32_t uart_clk = peripheral_clock_get(PERIPHERAL_CLOCK_UART);
 
-    return 0;
+    uart_cfg.uartClk            = uart_clk;
+    uart_cfg.baudRate           = cfg->baudrate;
+    uart_cfg.stopBits           = cfg->stopbits;
+    uart_cfg.parity             = cfg->parity;
+    uart_cfg.dataBits           = cfg->databits;
+    uart_cfg.ctsFlowControl     = UART_CTS_FLOWCONTROL_ENABLE;
+    uart_cfg.rtsSoftwareControl = UART_RTS_FLOWCONTROL_ENABLE;
+    uart_cfg.byteBitInverse     = UART_MSB_FIRST_ENABLE;
+    uart_cfg.txSoftwareControl  = UART_TX_SWCONTROL_ENABLE;
+    uart_cfg.txLinMode          = UART_TX_LINMODE_ENABLE;
+    uart_cfg.rxLinMode          = UART_RX_LINMODE_ENABLE;
+    uart_cfg.txBreakBitCnt      = UART_TX_BREAKBIT_CNT;
+    uart_cfg.rxDeglitch         = ENABLE;
+    UART_Init(uart_device->id, &uart_cfg);
+    /*set de-glitch function cycle count value*/
+    UART_SetDeglitchCount(uart_device->id, 2);
+    break;
+  }
+  case DEVICE_CTRL_GET_CONFIG /* constant-expression */:
+    break;
+  case DEVICE_CTRL_ATTACH_TX_DMA /* constant-expression */:
+    uart_device->tx_dma = (struct device *)args;
+    break;
+  case DEVICE_CTRL_ATTACH_RX_DMA /* constant-expression */:
+    uart_device->rx_dma = (struct device *)args;
+    break;
+  case DEVICE_CTRL_TX_DMA_SUSPEND: {
+    uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
+    tmpVal          = BL_CLR_REG_BIT(tmpVal, UART_DMA_TX_EN);
+    BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
+    dev->oflag &= ~DEVICE_OFLAG_DMA_TX;
+    break;
+  }
+  case DEVICE_CTRL_RX_DMA_SUSPEND: {
+    uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
+    tmpVal          = BL_CLR_REG_BIT(tmpVal, UART_DMA_RX_EN);
+    BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
+    dev->oflag &= ~DEVICE_OFLAG_DMA_RX;
+    break;
+  }
+  case DEVICE_CTRL_TX_DMA_RESUME: {
+    uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
+    tmpVal          = BL_SET_REG_BIT(tmpVal, UART_DMA_TX_EN);
+    BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
+    dev->oflag |= DEVICE_OFLAG_DMA_TX;
+    break;
+  }
+  case DEVICE_CTRL_RX_DMA_RESUME: {
+    uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
+    tmpVal          = BL_SET_REG_BIT(tmpVal, UART_DMA_RX_EN);
+    BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
+    dev->oflag |= DEVICE_OFLAG_DMA_RX;
+    break;
+  }
+  case DEVICE_CTRL_UART_GET_TX_FIFO /* constant-expression */:
+    return UART_GetTxFifoCount(uart_device->id);
+  case DEVICE_CTRL_UART_GET_RX_FIFO /* constant-expression */:
+    return UART_GetRxFifoCount(uart_device->id);
+  case DEVICE_CTRL_UART_CLEAR_TX_FIFO /* constant-expression */:
+    return UART_TxFifoClear(uart_device->id);
+  case DEVICE_CTRL_UART_CLEAR_RX_FIFO /* constant-expression */:
+    return UART_RxFifoClear(uart_device->id);
+  default:
+    break;
+  }
+
+  return 0;
 }
 /**
  * @brief
@@ -268,27 +264,26 @@ int uart_control(struct device *dev, int cmd, void *args)
  * @param size
  * @return int
  */
-int uart_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size)
-{
-    int ret = 0;
-    uart_device_t *uart_device = (uart_device_t *)dev;
-    if (dev->oflag & DEVICE_OFLAG_DMA_TX) {
-        struct device *dma_ch = (struct device *)uart_device->tx_dma;
-        if (!dma_ch)
-            return -1;
-
-        if (uart_device->id == 0) {
-            ret = dma_reload(dma_ch, (uint32_t)buffer, (uint32_t)DMA_ADDR_UART0_TDR, size);
-            dma_channel_start(dma_ch);
-        } else if (uart_device->id == 1) {
-            ret = dma_reload(dma_ch, (uint32_t)buffer, (uint32_t)DMA_ADDR_UART1_TDR, size);
-            dma_channel_start(dma_ch);
-        }
-        return ret;
-    } else if (dev->oflag & DEVICE_OFLAG_INT_TX) {
-        return -2;
-    } else
-        return UART_SendData(uart_device->id, (uint8_t *)buffer, size);
+int uart_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size) {
+  int            ret         = 0;
+  uart_device_t *uart_device = (uart_device_t *)dev;
+  if (dev->oflag & DEVICE_OFLAG_DMA_TX) {
+    struct device *dma_ch = (struct device *)uart_device->tx_dma;
+    if (!dma_ch)
+      return -1;
+
+    if (uart_device->id == 0) {
+      ret = dma_reload(dma_ch, (uint32_t)buffer, (uint32_t)DMA_ADDR_UART0_TDR, size);
+      dma_channel_start(dma_ch);
+    } else if (uart_device->id == 1) {
+      ret = dma_reload(dma_ch, (uint32_t)buffer, (uint32_t)DMA_ADDR_UART1_TDR, size);
+      dma_channel_start(dma_ch);
+    }
+    return ret;
+  } else if (dev->oflag & DEVICE_OFLAG_INT_TX) {
+    return -2;
+  } else
+    return UART_SendData(uart_device->id, (uint8_t *)buffer, size);
 }
 /**
  * @brief
@@ -299,28 +294,27 @@ int uart_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t si
  * @param size
  * @return int
  */
-int uart_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size)
-{
-    int ret = -1;
-    uart_device_t *uart_device = (uart_device_t *)dev;
-    if (dev->oflag & DEVICE_OFLAG_DMA_RX) {
-        struct device *dma_ch = (struct device *)uart_device->rx_dma;
-        if (!dma_ch)
-            return -1;
-
-        if (uart_device->id == 0) {
-            ret = dma_reload(dma_ch, (uint32_t)DMA_ADDR_UART0_RDR, (uint32_t)buffer, size);
-            dma_channel_start(dma_ch);
-        } else if (uart_device->id == 1) {
-            ret = dma_reload(dma_ch, (uint32_t)DMA_ADDR_UART1_RDR, (uint32_t)buffer, size);
-            dma_channel_start(dma_ch);
-        }
-        return ret;
-    } else if (dev->oflag & DEVICE_OFLAG_INT_RX) {
-        return -2;
-    } else {
-        return UART_ReceiveData(uart_device->id, (uint8_t *)buffer, size);
+int uart_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size) {
+  int            ret         = -1;
+  uart_device_t *uart_device = (uart_device_t *)dev;
+  if (dev->oflag & DEVICE_OFLAG_DMA_RX) {
+    struct device *dma_ch = (struct device *)uart_device->rx_dma;
+    if (!dma_ch)
+      return -1;
+
+    if (uart_device->id == 0) {
+      ret = dma_reload(dma_ch, (uint32_t)DMA_ADDR_UART0_RDR, (uint32_t)buffer, size);
+      dma_channel_start(dma_ch);
+    } else if (uart_device->id == 1) {
+      ret = dma_reload(dma_ch, (uint32_t)DMA_ADDR_UART1_RDR, (uint32_t)buffer, size);
+      dma_channel_start(dma_ch);
     }
+    return ret;
+  } else if (dev->oflag & DEVICE_OFLAG_INT_RX) {
+    return -2;
+  } else {
+    return UART_ReceiveData(uart_device->id, (uint8_t *)buffer, size);
+  }
 }
 /**
  * @brief
@@ -330,94 +324,92 @@ int uart_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size)
  * @param flag
  * @return int
  */
-int uart_register(enum uart_index_type index, const char *name)
-{
-    struct device *dev;
+int uart_register(enum uart_index_type index, const char *name) {
+  struct device *dev;
 
-    if (UART_MAX_INDEX == 0)
-        return -DEVICE_EINVAL;
+  if (UART_MAX_INDEX == 0)
+    return -DEVICE_EINVAL;
 
-    dev = &(uartx_device[index].parent);
+  dev = &(uartx_device[index].parent);
 
-    dev->open = uart_open;
-    dev->close = uart_close;
-    dev->control = uart_control;
-    dev->write = uart_write;
-    dev->read = uart_read;
+  dev->open    = uart_open;
+  dev->close   = uart_close;
+  dev->control = uart_control;
+  dev->write   = uart_write;
+  dev->read    = uart_read;
 
-    dev->type = DEVICE_CLASS_UART;
-    dev->handle = NULL;
+  dev->type   = DEVICE_CLASS_UART;
+  dev->handle = NULL;
 
-    return device_register(dev, name);
+  return device_register(dev, name);
 }
 /**
  * @brief
  *
  * @param handle
  */
-void uart_isr(uart_device_t *handle)
-{
-    uint32_t tmpVal = 0;
-    uint32_t maskVal = 0;
-    uint32_t UARTx = (UART0_BASE + handle->id * 0x100);
-
-    tmpVal = BL_RD_REG(UARTx, UART_INT_STS);
-    maskVal = BL_RD_REG(UARTx, UART_INT_MASK);
-
-    if (!handle->parent.callback)
-        return;
-
-    /* Length of uart tx data transfer arrived interrupt */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_END_MASK)) {
-        BL_WR_REG(UARTx, UART_INT_CLEAR, 0x1);
-        handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_TX_END);
+void uart_isr(uart_device_t *handle) {
+  uint32_t tmpVal  = 0;
+  uint32_t maskVal = 0;
+  uint32_t UARTx   = (UART0_BASE + handle->id * 0x100);
+
+  tmpVal  = BL_RD_REG(UARTx, UART_INT_STS);
+  maskVal = BL_RD_REG(UARTx, UART_INT_MASK);
+
+  if (!handle->parent.callback)
+    return;
+
+  /* Length of uart tx data transfer arrived interrupt */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_END_MASK)) {
+    BL_WR_REG(UARTx, UART_INT_CLEAR, 0x1);
+    handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_TX_END);
+  }
+
+  /* Length of uart rx data transfer arrived interrupt */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_END_MASK)) {
+    BL_WR_REG(UARTx, UART_INT_CLEAR, 0x2);
+    handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_RX_END);
+  }
+
+  /* Tx fifo ready interrupt,auto-cleared when data is pushed */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FIFO_MASK)) {
+    handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_TX_FIFO);
+  }
+
+  /* Rx fifo ready interrupt,auto-cleared when data is popped */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FIFO_MASK)) {
+    uint8_t buffer[UART_FIFO_MAX_LEN];
+    uint8_t len = UART_ReceiveData(handle->id, buffer, UART_FIFO_MAX_LEN);
+    if (len) {
+      handle->parent.callback(&handle->parent, &buffer[0], len, UART_EVENT_RX_FIFO);
     }
-
-    /* Length of uart rx data transfer arrived interrupt */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_END_MASK)) {
-        BL_WR_REG(UARTx, UART_INT_CLEAR, 0x2);
-        handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_RX_END);
-    }
-
-    /* Tx fifo ready interrupt,auto-cleared when data is pushed */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FIFO_MASK)) {
-        handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_TX_FIFO);
-    }
-
-    /* Rx fifo ready interrupt,auto-cleared when data is popped */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FIFO_MASK)) {
-        uint8_t buffer[UART_FIFO_MAX_LEN];
-        uint8_t len = UART_ReceiveData(handle->id, buffer, UART_FIFO_MAX_LEN);
-        if (len) {
-            handle->parent.callback(&handle->parent, &buffer[0], len, UART_EVENT_RX_FIFO);
-        }
-    }
-
-    /* Rx time-out interrupt */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_RTO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_RTO_MASK)) {
-        BL_WR_REG(UARTx, UART_INT_CLEAR, 0x10);
-        uint8_t buffer[UART_FIFO_MAX_LEN];
-        uint8_t len = UART_ReceiveData(handle->id, buffer, UART_FIFO_MAX_LEN);
-        if (len) {
-            handle->parent.callback(&handle->parent, &buffer[0], len, UART_EVENT_RTO);
-        }
-    }
-
-    /* Rx parity check error interrupt */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_PCE_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_PCE_MASK)) {
-        BL_WR_REG(UARTx, UART_INT_CLEAR, 0x20);
-        handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_PCE);
-    }
-
-    /* Tx fifo overflow/underflow error interrupt */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FER_MASK)) {
-        handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_TX_FER);
-    }
-
-    /* Rx fifo overflow/underflow error interrupt */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FER_MASK)) {
-        handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_RX_FER);
+  }
+
+  /* Rx time-out interrupt */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_RTO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_RTO_MASK)) {
+    BL_WR_REG(UARTx, UART_INT_CLEAR, 0x10);
+    uint8_t buffer[UART_FIFO_MAX_LEN];
+    uint8_t len = UART_ReceiveData(handle->id, buffer, UART_FIFO_MAX_LEN);
+    if (len) {
+      handle->parent.callback(&handle->parent, &buffer[0], len, UART_EVENT_RTO);
     }
+  }
+
+  /* Rx parity check error interrupt */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_PCE_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_PCE_MASK)) {
+    BL_WR_REG(UARTx, UART_INT_CLEAR, 0x20);
+    handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_PCE);
+  }
+
+  /* Tx fifo overflow/underflow error interrupt */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FER_MASK)) {
+    handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_TX_FER);
+  }
+
+  /* Rx fifo overflow/underflow error interrupt */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FER_MASK)) {
+    handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_RX_FER);
+  }
 }
 
 #ifdef BSP_USING_UART0
@@ -425,18 +417,12 @@ void uart_isr(uart_device_t *handle)
  * @brief
  *
  */
-void UART0_IRQ(void)
-{
-    uart_isr(&uartx_device[UART0_INDEX]);
-}
+void UART0_IRQ(void) { uart_isr(&uartx_device[UART0_INDEX]); }
 #endif
 #ifdef BSP_USING_UART1
 /**
  * @brief
  *
  */
-void UART1_IRQ(void)
-{
-    uart_isr(&uartx_device[UART1_INDEX]);
-}
+void UART1_IRQ(void) { uart_isr(&uartx_device[UART1_INDEX]); }
 #endif
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c
index 6e925f2a20..da66fc55f8 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c
@@ -21,182 +21,174 @@
  *
  */
 #include "hal_usb.h"
+#include "bl702_glb.h"
+#include "bl702_usb.h"
 #include "hal_dma.h"
 #include "hal_mtimer.h"
-#include "bl702_usb.h"
-#include "bl702_glb.h"
 
 #define USE_INTERNAL_TRANSCEIVER
-//#define ENABLE_LPM_INT
-//#define ENABLE_SOF3MS_INT
-//#define ENABLE_ERROR_INT
+// #define ENABLE_LPM_INT
+// #define ENABLE_SOF3MS_INT
+// #define ENABLE_ERROR_INT
 
 #define MIN(a, b) (((a) < (b)) ? (a) : (b))
 
-#define USB_DC_LOG_WRN(a, ...) //bflb_platform_printf(a, ##__VA_ARGS__)
+#define USB_DC_LOG_WRN(a, ...) // bflb_platform_printf(a, ##__VA_ARGS__)
 #define USB_DC_LOG_DBG(a, ...)
-#define USB_DC_LOG_ERR(a, ...) //bflb_platform_printf(a, ##__VA_ARGS__)
+#define USB_DC_LOG_ERR(a, ...) // bflb_platform_printf(a, ##__VA_ARGS__)
 #define USB_DC_LOG(a, ...)
 
 static usb_dc_device_t usb_fs_device;
-static void USB_FS_IRQ(void);
-
-static dma_lli_ctrl_t usb_lli_list = {
-    .src_addr = 0,
-    .dst_addr = 0,
-    .nextlli = 0,
-    .cfg.bits.fix_cnt = 0,
-    .cfg.bits.dst_min_mode = 0,
-    .cfg.bits.dst_add_mode = 0,
-    .cfg.bits.SI = 0,
-    .cfg.bits.DI = 0,
-    .cfg.bits.SWidth = DMA_TRANSFER_WIDTH_8BIT,
-    .cfg.bits.DWidth = DMA_TRANSFER_WIDTH_8BIT,
-    .cfg.bits.SBSize = 0,
-    .cfg.bits.DBSize = 0,
-    .cfg.bits.I = 0,
-    .cfg.bits.TransferSize = 0
-};
-
-static void usb_set_power_up(void)
-{
-    uint32_t tmpVal = 0;
-
-    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-    tmpVal = BL_SET_REG_BIT(tmpVal, GLB_PU_USB);
-    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+static void            USB_FS_IRQ(void);
+
+static dma_lli_ctrl_t usb_lli_list = {.src_addr              = 0,
+                                      .dst_addr              = 0,
+                                      .nextlli               = 0,
+                                      .cfg.bits.fix_cnt      = 0,
+                                      .cfg.bits.dst_min_mode = 0,
+                                      .cfg.bits.dst_add_mode = 0,
+                                      .cfg.bits.SI           = 0,
+                                      .cfg.bits.DI           = 0,
+                                      .cfg.bits.SWidth       = DMA_TRANSFER_WIDTH_8BIT,
+                                      .cfg.bits.DWidth       = DMA_TRANSFER_WIDTH_8BIT,
+                                      .cfg.bits.SBSize       = 0,
+                                      .cfg.bits.DBSize       = 0,
+                                      .cfg.bits.I            = 0,
+                                      .cfg.bits.TransferSize = 0};
+
+static void usb_set_power_up(void) {
+  uint32_t tmpVal = 0;
+
+  tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+  tmpVal = BL_SET_REG_BIT(tmpVal, GLB_PU_USB);
+  BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
 }
 
-static void usb_set_power_off(void)
-{
-    uint32_t tmpVal = 0;
+static void usb_set_power_off(void) {
+  uint32_t tmpVal = 0;
 
-    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-    tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_PU_USB);
-    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+  tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+  tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_PU_USB);
+  BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
 }
 
-static uint8_t usb_ep_is_enabled(uint8_t ep)
-{
-    uint8_t ep_idx = USB_EP_GET_IDX(ep);
-
-    /* Check if ep enabled */
-    if ((USB_EP_DIR_IS_OUT(ep)) &&
-        usb_fs_device.out_ep[ep_idx].ep_ena) {
-        return 1;
-    } else if ((USB_EP_DIR_IS_IN(ep)) &&
-               usb_fs_device.in_ep[ep_idx].ep_ena) {
-        return 1;
-    }
+static uint8_t usb_ep_is_enabled(uint8_t ep) {
+  uint8_t ep_idx = USB_EP_GET_IDX(ep);
 
-    return 0;
+  /* Check if ep enabled */
+  if ((USB_EP_DIR_IS_OUT(ep)) && usb_fs_device.out_ep[ep_idx].ep_ena) {
+    return 1;
+  } else if ((USB_EP_DIR_IS_IN(ep)) && usb_fs_device.in_ep[ep_idx].ep_ena) {
+    return 1;
+  }
+
+  return 0;
 }
 
-static void usb_xcvr_config(BL_Fun_Type NewState)
-{
-    uint32_t tmpVal = 0;
+static void usb_xcvr_config(BL_Fun_Type NewState) {
+  uint32_t tmpVal = 0;
 
-    if (NewState != DISABLE) {
+  if (NewState != DISABLE) {
 #if defined(USE_EXTERNAL_TRANSCEIVER)
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 0); //use external tranceiver
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 0); // use external tranceiver
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
 #elif defined(USE_INTERNAL_TRANSCEIVER)
 #if 1
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 1);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
-
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SUS, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SPD, 1); //0 for 1.1 ls,1 for 1.1 fs
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_DATA_CONVERT, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_OEB_SEL, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_PMOS, 3);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_NMOS, 3);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
-
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_RISE, 2); //1 for 1.1 ls
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_FALL, 2); //1 for 1.1 ls
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_RISE, 2); //1 for 1.1 ls
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_FALL, 2); //1 for 1.1 ls
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_RES_PULLUP_TUNE, 5);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 1);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 1);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_P, 2);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_M, 2);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
-
-        ///* force BD=1, not use */
-        //tmpVal=BL_RD_REG(GLB_BASE,GLB_USB_XCVR);
-        //tmpVal=BL_SET_REG_BIT(tmpVal,GLB_PU_USB_LDO);
-        //BL_WR_REG(GLB_BASE,GLB_USB_XCVR,tmpVal);
-
-        /* BD_voltage_thresdhold=2.8V */
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 7);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 1);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SUS, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SPD, 1); // 0 for 1.1 ls,1 for 1.1 fs
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_DATA_CONVERT, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_OEB_SEL, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_PMOS, 3);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_NMOS, 3);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_RISE, 2); // 1 for 1.1 ls
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_FALL, 2); // 1 for 1.1 ls
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_RISE, 2); // 1 for 1.1 ls
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_FALL, 2); // 1 for 1.1 ls
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_RES_PULLUP_TUNE, 5);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 1);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 1);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_P, 2);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_M, 2);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
+
+    ///* force BD=1, not use */
+    // tmpVal=BL_RD_REG(GLB_BASE,GLB_USB_XCVR);
+    // tmpVal=BL_SET_REG_BIT(tmpVal,GLB_PU_USB_LDO);
+    // BL_WR_REG(GLB_BASE,GLB_USB_XCVR,tmpVal);
+
+    /* BD_voltage_thresdhold=2.8V */
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 7);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
 
 #else
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 1);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
-
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SUS, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SPD, 0); //0 for 1.1 ls,1 for 1.1 fs
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_DATA_CONVERT, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_OEB_SEL, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_PMOS, 3);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_NMOS, 3);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
-
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_RISE, 1); //4 for 1.1 fs
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_FALL, 1); //3 for 1.1 fs
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_RISE, 1); //4 for 1.1 fs
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_FALL, 1); //3 for 1.1 fs
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_RES_PULLUP_TUNE, 5);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 1);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 1);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_P, 2);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_M, 2);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 1);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SUS, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SPD, 0); // 0 for 1.1 ls,1 for 1.1 fs
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_DATA_CONVERT, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_OEB_SEL, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_PMOS, 3);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_NMOS, 3);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_RISE, 1); // 4 for 1.1 fs
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_FALL, 1); // 3 for 1.1 fs
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_RISE, 1); // 4 for 1.1 fs
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_FALL, 1); // 3 for 1.1 fs
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_RES_PULLUP_TUNE, 5);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 1);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 1);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_P, 2);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_M, 2);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
 #endif
 
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 1);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 1);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
 #endif
-    } else {
+  } else {
 #ifdef USE_INTERNAL_TRANSCEIVER
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 0);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 0);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
 
-        ///* force BD=1, not use */
-        //tmpVal=BL_RD_REG(GLB_BASE,GLB_USB_XCVR);
-        //tmpVal=BL_SET_REG_BIT(tmpVal,GLB_PU_USB_LDO);
-        //BL_WR_REG(GLB_BASE,GLB_USB_XCVR,tmpVal);
+    ///* force BD=1, not use */
+    // tmpVal=BL_RD_REG(GLB_BASE,GLB_USB_XCVR);
+    // tmpVal=BL_SET_REG_BIT(tmpVal,GLB_PU_USB_LDO);
+    // BL_WR_REG(GLB_BASE,GLB_USB_XCVR,tmpVal);
 
-        /* BD_voltage_thresdhold=2.8V */
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 7);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
+    /* BD_voltage_thresdhold=2.8V */
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 7);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
 
 #else
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 1); //use internal tranceiver
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
-
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 1);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 1); // use internal tranceiver
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
+
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 1);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
 #endif
-    }
+  }
 }
 
 /**
@@ -206,85 +198,84 @@ static void usb_xcvr_config(BL_Fun_Type NewState)
  * @param oflag
  * @return int
  */
-int usb_open(struct device *dev, uint16_t oflag)
-{
-    USB_Config_Type usbCfg = { 0 };
-
-    usb_set_power_off();
-    mtimer_delay_ms(10);
-    usb_set_power_up();
-
-    usb_xcvr_config(DISABLE);
-    usb_xcvr_config(ENABLE);
-
-    CPU_Interrupt_Disable(USB_IRQn);
-
-    usbCfg.DeviceAddress = 0;
-    usbCfg.EnumInEn = ENABLE;
-    usbCfg.EnumOutEn = ENABLE;
-    usbCfg.RomBaseDescriptorUsed = 0;
-    usbCfg.SoftwareCtrl = 1;
-    usbCfg.EnumMaxPacketSize = USB_CTRL_EP_MPS;
-
-    /* Init Device */
-    USB_Set_Config(DISABLE, &usbCfg);
-
-    usb_fs_device.out_ep[0].ep_ena = 1U;
-    usb_fs_device.in_ep[0].ep_ena = 1U;
-    usb_fs_device.out_ep[0].ep_cfg.ep_mps = USB_CTRL_EP_MPS;
-    usb_fs_device.out_ep[0].ep_cfg.ep_type = USBD_EP_TYPE_CTRL;
-    usb_fs_device.in_ep[0].ep_cfg.ep_mps = USB_CTRL_EP_MPS;
-    usb_fs_device.in_ep[0].ep_cfg.ep_type = USBD_EP_TYPE_CTRL;
-
-    /* USB interrupt enable config */
-    BL_WR_REG(USB_BASE, USB_INT_EN, 0);
-    USB_IntEn(USB_INT_RESET, ENABLE);          //1
-    USB_IntEn(USB_INT_EP0_SETUP_DONE, ENABLE); //5
-    USB_IntEn(USB_INT_EP0_IN_DONE, ENABLE);    //7
-    USB_IntEn(USB_INT_EP0_OUT_DONE, ENABLE);   //9
-    USB_IntEn(USB_INT_RESET_END, ENABLE);      //27
-
-    /* USB interrupt mask config */
-    BL_WR_REG(USB_BASE, USB_INT_MASK, 0xffffffff);
-    USB_IntMask(USB_INT_RESET, UNMASK);          //1
-    USB_IntMask(USB_INT_EP0_SETUP_DONE, UNMASK); //5
-    USB_IntMask(USB_INT_EP0_IN_DONE, UNMASK);    //7
-    USB_IntMask(USB_INT_EP0_OUT_DONE, UNMASK);   //9
-    USB_IntMask(USB_INT_RESET_END, UNMASK);      //27
+int usb_open(struct device *dev, uint16_t oflag) {
+  USB_Config_Type usbCfg = {0};
+
+  usb_set_power_off();
+  mtimer_delay_ms(10);
+  usb_set_power_up();
+
+  usb_xcvr_config(DISABLE);
+  usb_xcvr_config(ENABLE);
+
+  CPU_Interrupt_Disable(USB_IRQn);
+
+  usbCfg.DeviceAddress         = 0;
+  usbCfg.EnumInEn              = ENABLE;
+  usbCfg.EnumOutEn             = ENABLE;
+  usbCfg.RomBaseDescriptorUsed = 0;
+  usbCfg.SoftwareCtrl          = 1;
+  usbCfg.EnumMaxPacketSize     = USB_CTRL_EP_MPS;
+
+  /* Init Device */
+  USB_Set_Config(DISABLE, &usbCfg);
+
+  usb_fs_device.out_ep[0].ep_ena         = 1U;
+  usb_fs_device.in_ep[0].ep_ena          = 1U;
+  usb_fs_device.out_ep[0].ep_cfg.ep_mps  = USB_CTRL_EP_MPS;
+  usb_fs_device.out_ep[0].ep_cfg.ep_type = USBD_EP_TYPE_CTRL;
+  usb_fs_device.in_ep[0].ep_cfg.ep_mps   = USB_CTRL_EP_MPS;
+  usb_fs_device.in_ep[0].ep_cfg.ep_type  = USBD_EP_TYPE_CTRL;
+
+  /* USB interrupt enable config */
+  BL_WR_REG(USB_BASE, USB_INT_EN, 0);
+  USB_IntEn(USB_INT_RESET, ENABLE);          // 1
+  USB_IntEn(USB_INT_EP0_SETUP_DONE, ENABLE); // 5
+  USB_IntEn(USB_INT_EP0_IN_DONE, ENABLE);    // 7
+  USB_IntEn(USB_INT_EP0_OUT_DONE, ENABLE);   // 9
+  USB_IntEn(USB_INT_RESET_END, ENABLE);      // 27
+
+  /* USB interrupt mask config */
+  BL_WR_REG(USB_BASE, USB_INT_MASK, 0xffffffff);
+  USB_IntMask(USB_INT_RESET, UNMASK);          // 1
+  USB_IntMask(USB_INT_EP0_SETUP_DONE, UNMASK); // 5
+  USB_IntMask(USB_INT_EP0_IN_DONE, UNMASK);    // 7
+  USB_IntMask(USB_INT_EP0_OUT_DONE, UNMASK);   // 9
+  USB_IntMask(USB_INT_RESET_END, UNMASK);      // 27
 
 #ifdef ENABLE_LPM_INT
-    USB_IntEn(USB_INT_LPM_PACKET, ENABLE);
-    USB_IntEn(USB_INT_LPM_WAKEUP, ENABLE);
-    USB_IntMask(USB_INT_LPM_PACKET, UNMASK);
-    USB_IntMask(USB_INT_LPM_WAKEUP, UNMASK);
+  USB_IntEn(USB_INT_LPM_PACKET, ENABLE);
+  USB_IntEn(USB_INT_LPM_WAKEUP, ENABLE);
+  USB_IntMask(USB_INT_LPM_PACKET, UNMASK);
+  USB_IntMask(USB_INT_LPM_WAKEUP, UNMASK);
 
-    USB_LPM_Enable();
-    USB_Set_LPM_Default_Response(USB_LPM_DEFAULT_RESP_ACK);
+  USB_LPM_Enable();
+  USB_Set_LPM_Default_Response(USB_LPM_DEFAULT_RESP_ACK);
 
 #endif
 
 #ifdef ENABLE_SOF3MS_INT
-    /* disable sof3ms until reset_end */
-    USB_IntEn(USB_INT_LOST_SOF_3_TIMES, DISABLE);
-    USB_IntMask(USB_INT_LOST_SOF_3_TIMES, MASK);
+  /* disable sof3ms until reset_end */
+  USB_IntEn(USB_INT_LOST_SOF_3_TIMES, DISABLE);
+  USB_IntMask(USB_INT_LOST_SOF_3_TIMES, MASK);
 
-    /* recommended enable sof3ms after reset_end */
-    USB_IntEn(USB_INT_LOST_SOF_3_TIMES, ENABLE);
-    USB_IntMask(USB_INT_LOST_SOF_3_TIMES, UNMASK);
+  /* recommended enable sof3ms after reset_end */
+  USB_IntEn(USB_INT_LOST_SOF_3_TIMES, ENABLE);
+  USB_IntMask(USB_INT_LOST_SOF_3_TIMES, UNMASK);
 #endif
 
 #ifdef ENABLE_ERROR_INT
-    USB_IntEn(USB_INT_ERROR, ENABLE);
-    USB_IntMask(USB_INT_ERROR, UNMASK);
+  USB_IntEn(USB_INT_ERROR, ENABLE);
+  USB_IntMask(USB_INT_ERROR, UNMASK);
 #endif
-    /*Clear pending interrupts*/
-    USB_Clr_IntStatus(USB_INT_ALL);
+  /*Clear pending interrupts*/
+  USB_Clr_IntStatus(USB_INT_ALL);
 
-    Interrupt_Handler_Register(USB_IRQn, USB_FS_IRQ);
-    CPU_Interrupt_Enable(USB_IRQn);
-    USB_Enable();
+  Interrupt_Handler_Register(USB_IRQn, USB_FS_IRQ);
+  CPU_Interrupt_Enable(USB_IRQn);
+  USB_Enable();
 
-    return 0;
+  return 0;
 }
 /**
  * @brief
@@ -292,23 +283,22 @@ int usb_open(struct device *dev, uint16_t oflag)
  * @param dev
  * @return int
  */
-int usb_close(struct device *dev)
-{
-    /* disable all interrupts and force USB reset */
-    CPU_Interrupt_Disable(USB_IRQn);
-    USB_IntMask(USB_INT_LPM_WAKEUP, MASK);
-    USB_IntMask(USB_INT_LPM_PACKET, MASK);
+int usb_close(struct device *dev) {
+  /* disable all interrupts and force USB reset */
+  CPU_Interrupt_Disable(USB_IRQn);
+  USB_IntMask(USB_INT_LPM_WAKEUP, MASK);
+  USB_IntMask(USB_INT_LPM_PACKET, MASK);
 
-    USB_Disable();
+  USB_Disable();
 
-    /* clear interrupt status register */
-    USB_Clr_IntStatus(USB_INT_ALL);
+  /* clear interrupt status register */
+  USB_Clr_IntStatus(USB_INT_ALL);
 
-    usb_set_power_off();
+  usb_set_power_off();
 
-    usb_xcvr_config(DISABLE);
-    GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_USB);
-    return 0;
+  usb_xcvr_config(DISABLE);
+  GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_USB);
+  return 0;
 }
 /**
  * @brief
@@ -318,130 +308,127 @@ int usb_close(struct device *dev)
  * @param args
  * @return int
  */
-int usb_control(struct device *dev, int cmd, void *args)
-{
-    struct usb_dc_device *usb_device = (struct usb_dc_device *)dev;
-
-    switch (cmd) {
-        case DEVICE_CTRL_SET_INT /* constant-expression */: {
-            uint32_t offset = __builtin_ctz((uint32_t)args);
-
-            while (offset < 24) {
-                if ((uint32_t)args & (1 << offset)) {
-                    USB_IntEn(offset, ENABLE);
-                    USB_IntMask(offset, UNMASK);
-                }
-
-                offset++;
-            }
-            break;
-        }
-        case DEVICE_CTRL_CLR_INT /* constant-expression */: {
-            uint32_t offset = __builtin_ctz((uint32_t)args);
-
-            while (offset < 24) {
-                if ((uint32_t)args & (1 << offset)) {
-                    USB_IntEn(offset, DISABLE);
-                    USB_IntMask(offset, MASK);
-                }
-
-                offset++;
-            }
-            break;
-        }
-        case DEVICE_CTRL_USB_DC_SET_ACK /* constant-expression */:
-            USB_Set_EPx_Status(USB_EP_GET_IDX(((uint32_t)args) & 0x7f), USB_EP_STATUS_ACK);
-            return 0;
-        case DEVICE_CTRL_USB_DC_ENUM_ON: {
-            uint32_t tmpVal;
-            tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-            tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 1);
-            BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
-            return 0;
-        }
-        case DEVICE_CTRL_USB_DC_ENUM_OFF: {
-            uint32_t tmpVal;
-            tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-            tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 0);
-            BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
-            return 0;
-        }
-        case DEVICE_CTRL_USB_DC_GET_EP_TX_FIFO_CNT:
-            return USB_Get_EPx_TX_FIFO_CNT(((uint32_t)args) & 0x7f);
-
-        case DEVICE_CTRL_USB_DC_GET_EP_RX_FIFO_CNT:
-            return USB_Get_EPx_RX_FIFO_CNT(((uint32_t)args) & 0x7f);
-        case DEVICE_CTRL_ATTACH_TX_DMA /* constant-expression */:
-            usb_device->tx_dma = (struct device *)args;
-            break;
-
-        case DEVICE_CTRL_ATTACH_RX_DMA /* constant-expression */:
-            usb_device->rx_dma = (struct device *)args;
-            break;
-
-        case DEVICE_CTRL_USB_DC_SET_TX_DMA /* constant-expression */:
-            USB_Set_EPx_TX_DMA_Interface_Config(((uint32_t)args) & 0x7f, ENABLE);
-            break;
-
-        case DEVICE_CTRL_USB_DC_SET_RX_DMA /* constant-expression */:
-            USB_Set_EPx_RX_DMA_Interface_Config(((uint32_t)args) & 0x7f, ENABLE);
-            break;
-
-        default:
-            break;
-    }
+int usb_control(struct device *dev, int cmd, void *args) {
+  struct usb_dc_device *usb_device = (struct usb_dc_device *)dev;
+
+  switch (cmd) {
+  case DEVICE_CTRL_SET_INT /* constant-expression */: {
+    uint32_t offset = __builtin_ctz((uint32_t)args);
+
+    while (offset < 24) {
+      if ((uint32_t)args & (1 << offset)) {
+        USB_IntEn(offset, ENABLE);
+        USB_IntMask(offset, UNMASK);
+      }
 
+      offset++;
+    }
+    break;
+  }
+  case DEVICE_CTRL_CLR_INT /* constant-expression */: {
+    uint32_t offset = __builtin_ctz((uint32_t)args);
+
+    while (offset < 24) {
+      if ((uint32_t)args & (1 << offset)) {
+        USB_IntEn(offset, DISABLE);
+        USB_IntMask(offset, MASK);
+      }
+
+      offset++;
+    }
+    break;
+  }
+  case DEVICE_CTRL_USB_DC_SET_ACK /* constant-expression */:
+    USB_Set_EPx_Status(USB_EP_GET_IDX(((uint32_t)args) & 0x7f), USB_EP_STATUS_ACK);
+    return 0;
+  case DEVICE_CTRL_USB_DC_ENUM_ON: {
+    uint32_t tmpVal;
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 1);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
     return 0;
+  }
+  case DEVICE_CTRL_USB_DC_ENUM_OFF: {
+    uint32_t tmpVal;
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 0);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+    return 0;
+  }
+  case DEVICE_CTRL_USB_DC_GET_EP_TX_FIFO_CNT:
+    return USB_Get_EPx_TX_FIFO_CNT(((uint32_t)args) & 0x7f);
+
+  case DEVICE_CTRL_USB_DC_GET_EP_RX_FIFO_CNT:
+    return USB_Get_EPx_RX_FIFO_CNT(((uint32_t)args) & 0x7f);
+  case DEVICE_CTRL_ATTACH_TX_DMA /* constant-expression */:
+    usb_device->tx_dma = (struct device *)args;
+    break;
+
+  case DEVICE_CTRL_ATTACH_RX_DMA /* constant-expression */:
+    usb_device->rx_dma = (struct device *)args;
+    break;
+
+  case DEVICE_CTRL_USB_DC_SET_TX_DMA /* constant-expression */:
+    USB_Set_EPx_TX_DMA_Interface_Config(((uint32_t)args) & 0x7f, ENABLE);
+    break;
+
+  case DEVICE_CTRL_USB_DC_SET_RX_DMA /* constant-expression */:
+    USB_Set_EPx_RX_DMA_Interface_Config(((uint32_t)args) & 0x7f, ENABLE);
+    break;
+
+  default:
+    break;
+  }
+
+  return 0;
 }
 
-int usb_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size)
-{
-    struct usb_dc_device *usb_device = (struct usb_dc_device *)dev;
-    uint8_t ep_idx = USB_EP_GET_IDX(pos);
-
-    if (usb_device->in_ep[ep_idx].ep_cfg.ep_type == USBD_EP_TYPE_ISOC) {
-        uint32_t usb_ep_addr = USB_BASE + 0x308 + ep_idx * 0x10;
-
-        dma_channel_stop(usb_device->tx_dma);
-        usb_lli_list.src_addr = (uint32_t)buffer;
-        usb_lli_list.dst_addr = usb_ep_addr;
-        usb_lli_list.cfg.bits.TransferSize = size;
-        usb_lli_list.cfg.bits.DI = 0;
-        usb_lli_list.cfg.bits.SI = 1;
-        usb_lli_list.cfg.bits.SBSize = DMA_BURST_16BYTE;
-        usb_lli_list.cfg.bits.DBSize = DMA_BURST_1BYTE;
-        dma_channel_update(usb_device->tx_dma, (void *)((uint32_t)&usb_lli_list));
-        dma_channel_start(usb_device->tx_dma);
-        return 0;
-    } else {
-    }
+int usb_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size) {
+  struct usb_dc_device *usb_device = (struct usb_dc_device *)dev;
+  uint8_t               ep_idx     = USB_EP_GET_IDX(pos);
+
+  if (usb_device->in_ep[ep_idx].ep_cfg.ep_type == USBD_EP_TYPE_ISOC) {
+    uint32_t usb_ep_addr = USB_BASE + 0x308 + ep_idx * 0x10;
+
+    dma_channel_stop(usb_device->tx_dma);
+    usb_lli_list.src_addr              = (uint32_t)buffer;
+    usb_lli_list.dst_addr              = usb_ep_addr;
+    usb_lli_list.cfg.bits.TransferSize = size;
+    usb_lli_list.cfg.bits.DI           = 0;
+    usb_lli_list.cfg.bits.SI           = 1;
+    usb_lli_list.cfg.bits.SBSize       = DMA_BURST_16BYTE;
+    usb_lli_list.cfg.bits.DBSize       = DMA_BURST_1BYTE;
+    dma_channel_update(usb_device->tx_dma, (void *)((uint32_t)&usb_lli_list));
+    dma_channel_start(usb_device->tx_dma);
+    return 0;
+  } else {
+  }
 
-    return -1;
+  return -1;
 }
 
-int usb_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size)
-{
-    struct usb_dc_device *usb_device = (struct usb_dc_device *)dev;
-    uint8_t ep_idx = USB_EP_GET_IDX(pos);
-
-    if (usb_device->out_ep[ep_idx].ep_cfg.ep_type == USBD_EP_TYPE_ISOC) {
-        uint32_t usb_ep_addr = USB_BASE + 0x308 + ep_idx * 0x1c;
-
-        dma_channel_stop(usb_device->tx_dma);
-        usb_lli_list.src_addr = usb_ep_addr;
-        usb_lli_list.dst_addr = (uint32_t)buffer;
-        usb_lli_list.cfg.bits.TransferSize = size;
-        usb_lli_list.cfg.bits.DI = 1;
-        usb_lli_list.cfg.bits.SI = 0;
-        usb_lli_list.cfg.bits.SBSize = DMA_BURST_1BYTE;
-        usb_lli_list.cfg.bits.DBSize = DMA_BURST_16BYTE;
-        dma_channel_update(usb_device->rx_dma, (void *)((uint32_t)&usb_lli_list));
-        dma_channel_start(usb_device->rx_dma);
-        return 0;
-    } else {
-    }
+int usb_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size) {
+  struct usb_dc_device *usb_device = (struct usb_dc_device *)dev;
+  uint8_t               ep_idx     = USB_EP_GET_IDX(pos);
+
+  if (usb_device->out_ep[ep_idx].ep_cfg.ep_type == USBD_EP_TYPE_ISOC) {
+    uint32_t usb_ep_addr = USB_BASE + 0x308 + ep_idx * 0x1c;
+
+    dma_channel_stop(usb_device->tx_dma);
+    usb_lli_list.src_addr              = usb_ep_addr;
+    usb_lli_list.dst_addr              = (uint32_t)buffer;
+    usb_lli_list.cfg.bits.TransferSize = size;
+    usb_lli_list.cfg.bits.DI           = 1;
+    usb_lli_list.cfg.bits.SI           = 0;
+    usb_lli_list.cfg.bits.SBSize       = DMA_BURST_1BYTE;
+    usb_lli_list.cfg.bits.DBSize       = DMA_BURST_16BYTE;
+    dma_channel_update(usb_device->rx_dma, (void *)((uint32_t)&usb_lli_list));
+    dma_channel_start(usb_device->rx_dma);
+    return 0;
+  } else {
+  }
 
-    return -1;
+  return -1;
 }
 
 /**
@@ -452,26 +439,25 @@ int usb_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size)
  * @param flag
  * @return int
  */
-int usb_dc_register(enum usb_index_type index, const char *name)
-{
-    struct device *dev;
+int usb_dc_register(enum usb_index_type index, const char *name) {
+  struct device *dev;
 
-    if (USB_MAX_INDEX == 0) {
-        return -DEVICE_EINVAL;
-    }
+  if (USB_MAX_INDEX == 0) {
+    return -DEVICE_EINVAL;
+  }
 
-    dev = &(usb_fs_device.parent);
+  dev = &(usb_fs_device.parent);
 
-    dev->open = usb_open;
-    dev->close = usb_close;
-    dev->control = usb_control;
-    dev->write = usb_write;
-    dev->read = usb_read;
+  dev->open    = usb_open;
+  dev->close   = usb_close;
+  dev->control = usb_control;
+  dev->write   = usb_write;
+  dev->read    = usb_read;
 
-    dev->type = DEVICE_CLASS_USB;
-    dev->handle = NULL;
+  dev->type   = DEVICE_CLASS_USB;
+  dev->handle = NULL;
 
-    return device_register(dev, name);
+  return device_register(dev, name);
 }
 
 /**
@@ -481,10 +467,9 @@ int usb_dc_register(enum usb_index_type index, const char *name)
  *
  * @return 0 on success, negative errno code on fail.
  */
-int usb_dc_set_dev_address(const uint8_t addr)
-{
-    USB_Set_Device_Addr(addr);
-    return 0;
+int usb_dc_set_dev_address(const uint8_t addr) {
+  USB_Set_Device_Addr(addr);
+  return 0;
 }
 
 /**
@@ -496,77 +481,73 @@ int usb_dc_set_dev_address(const uint8_t addr)
  * @param ep_cfg  ep_cfg Endpoint
  * @return int
  */
-int usb_dc_ep_open(struct device *dev, const struct usb_dc_ep_cfg *ep_cfg)
-{
-    uint8_t ep;
-    EP_Config_Type epCfg;
-
-    if (!ep_cfg) {
-        return -1;
-    }
-
-    ep = ep_cfg->ep_addr;
-
-    uint8_t ep_idx = USB_EP_GET_IDX(ep);
-
-    USB_DC_LOG_DBG("%s ep %x, mps %d, type %d\r\n", __func__, ep, ep_cfg->ep_mps, ep_cfg->ep_type);
+int usb_dc_ep_open(struct device *dev, const struct usb_dc_ep_cfg *ep_cfg) {
+  uint8_t        ep;
+  EP_Config_Type epCfg;
 
-    if (ep_idx == 0) {
-        return 0;
-    }
-
-    if (USB_EP_DIR_IS_OUT(ep)) {
-        epCfg.dir = EP_OUT;
-        epCfg.EPMaxPacketSize = ep_cfg->ep_mps;
-        usb_fs_device.out_ep[ep_idx].ep_cfg.ep_mps = ep_cfg->ep_mps;
-        usb_fs_device.out_ep[ep_idx].ep_cfg.ep_type = ep_cfg->ep_type;
-    } else {
-        epCfg.dir = EP_IN;
-        epCfg.EPMaxPacketSize = ep_cfg->ep_mps;
-        usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps = ep_cfg->ep_mps;
-        usb_fs_device.in_ep[ep_idx].ep_cfg.ep_type = ep_cfg->ep_type;
-    }
-
-    switch (ep_cfg->ep_type) {
-        case USBD_EP_TYPE_CTRL:
-            epCfg.type = USB_DC_EP_TYPE_CTRL;
-            break;
-
-        case USBD_EP_TYPE_ISOC:
-            epCfg.type = USB_DC_EP_TYPE_ISOC;
-            break;
+  if (!ep_cfg) {
+    return -1;
+  }
 
-        case USBD_EP_TYPE_BULK:
-            epCfg.type = USB_DC_EP_TYPE_BULK;
-            break;
+  ep = ep_cfg->ep_addr;
 
-        case USBD_EP_TYPE_INTR:
-            epCfg.type = USB_DC_EP_TYPE_INTR;
-            break;
+  uint8_t ep_idx = USB_EP_GET_IDX(ep);
 
-        default:
-            return -1;
-    }
+  USB_DC_LOG_DBG("%s ep %x, mps %d, type %d\r\n", __func__, ep, ep_cfg->ep_mps, ep_cfg->ep_type);
 
-    USB_Set_EPx_Config(ep_idx, &epCfg);
+  if (ep_idx == 0) {
+    return 0;
+  }
+
+  if (USB_EP_DIR_IS_OUT(ep)) {
+    epCfg.dir                                   = EP_OUT;
+    epCfg.EPMaxPacketSize                       = ep_cfg->ep_mps;
+    usb_fs_device.out_ep[ep_idx].ep_cfg.ep_mps  = ep_cfg->ep_mps;
+    usb_fs_device.out_ep[ep_idx].ep_cfg.ep_type = ep_cfg->ep_type;
+  } else {
+    epCfg.dir                                  = EP_IN;
+    epCfg.EPMaxPacketSize                      = ep_cfg->ep_mps;
+    usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps  = ep_cfg->ep_mps;
+    usb_fs_device.in_ep[ep_idx].ep_cfg.ep_type = ep_cfg->ep_type;
+  }
+
+  switch (ep_cfg->ep_type) {
+  case USBD_EP_TYPE_CTRL:
+    epCfg.type = USB_DC_EP_TYPE_CTRL;
+    break;
+
+  case USBD_EP_TYPE_ISOC:
+    epCfg.type = USB_DC_EP_TYPE_ISOC;
+    break;
+
+  case USBD_EP_TYPE_BULK:
+    epCfg.type = USB_DC_EP_TYPE_BULK;
+    break;
+
+  case USBD_EP_TYPE_INTR:
+    epCfg.type = USB_DC_EP_TYPE_INTR;
+    break;
+
+  default:
+    return -1;
+  }
 
-    if (USB_EP_DIR_IS_OUT(ep)) {
-        /* Clear NAK and enable ep */
-        USB_Set_EPx_Status(USB_EP_GET_IDX(ep), USB_EP_STATUS_ACK);
-        usb_fs_device.out_ep[ep_idx].ep_ena = 1U;
-    } else {
-        //USB_Set_EPx_Status(USB_EP_GET_IDX(ep), USB_EP_STATUS_ACK);
-        USB_Set_EPx_Status(USB_EP_GET_IDX(ep), USB_EP_STATUS_NACK);
-        usb_fs_device.in_ep[ep_idx].ep_ena = 1U;
-    }
+  USB_Set_EPx_Config(ep_idx, &epCfg);
 
-    return 0;
+  if (USB_EP_DIR_IS_OUT(ep)) {
+    /* Clear NAK and enable ep */
+    USB_Set_EPx_Status(USB_EP_GET_IDX(ep), USB_EP_STATUS_ACK);
+    usb_fs_device.out_ep[ep_idx].ep_ena = 1U;
+  } else {
+    // USB_Set_EPx_Status(USB_EP_GET_IDX(ep), USB_EP_STATUS_ACK);
+    USB_Set_EPx_Status(USB_EP_GET_IDX(ep), USB_EP_STATUS_NACK);
+    usb_fs_device.in_ep[ep_idx].ep_ena = 1U;
+  }
+
+  return 0;
 }
 
-int usb_dc_ep_close(const uint8_t ep)
-{
-    return 0;
-}
+int usb_dc_ep_close(const uint8_t ep) { return 0; }
 
 /**
  * @brief Set stall condition for the selected endpoint
@@ -576,63 +557,62 @@ int usb_dc_ep_close(const uint8_t ep)
  *
  * @return 0 on success, negative errno code on fail.
  */
-int usb_dc_ep_set_stall(const uint8_t ep)
-{
-    uint32_t tmpVal = 0;
-    uint8_t ep_idx = USB_EP_GET_IDX(ep);
-
-    if (USB_EP_DIR_IS_OUT(ep)) {
-        usb_fs_device.out_ep[ep_idx].is_stalled = 1U;
-    } else {
-        usb_fs_device.in_ep[ep_idx].is_stalled = 1U;
-    }
-
-    switch (ep_idx) {
-        case 0:
-            tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL);
-            BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal);
-            break;
-        case 1:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL);
-            BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal);
-            break;
-        case 2:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL);
-            BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal);
-            break;
-        case 3:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL);
-            BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal);
-            break;
-        case 4:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL);
-            BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal);
-            break;
-        case 5:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL);
-            BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal);
-            break;
-        case 6:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL);
-            BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal);
-            break;
-        case 7:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL);
-            BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal);
-            break;
-
-        default:
-            break;
-    }
-    return 0;
+int usb_dc_ep_set_stall(const uint8_t ep) {
+  uint32_t tmpVal = 0;
+  uint8_t  ep_idx = USB_EP_GET_IDX(ep);
+
+  if (USB_EP_DIR_IS_OUT(ep)) {
+    usb_fs_device.out_ep[ep_idx].is_stalled = 1U;
+  } else {
+    usb_fs_device.in_ep[ep_idx].is_stalled = 1U;
+  }
+
+  switch (ep_idx) {
+  case 0:
+    tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL);
+    BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal);
+    break;
+  case 1:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL);
+    BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal);
+    break;
+  case 2:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL);
+    BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal);
+    break;
+  case 3:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL);
+    BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal);
+    break;
+  case 4:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL);
+    BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal);
+    break;
+  case 5:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL);
+    BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal);
+    break;
+  case 6:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL);
+    BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal);
+    break;
+  case 7:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL);
+    BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal);
+    break;
+
+  default:
+    break;
+  }
+  return 0;
 }
 /**
  * @brief Clear stall condition for the selected endpoint
@@ -642,72 +622,71 @@ int usb_dc_ep_set_stall(const uint8_t ep)
  *
  * @return 0 on success, negative errno code on fail.
  */
-int usb_dc_ep_clear_stall(const uint8_t ep)
-{
-    uint8_t ep_idx = USB_EP_GET_IDX(ep);
-    uint32_t tmpVal = 0;
-    if (USB_EP_DIR_IS_OUT(ep)) {
-        usb_fs_device.out_ep[ep_idx].is_stalled = 0;
-    } else {
-        usb_fs_device.in_ep[ep_idx].is_stalled = 0;
-    }
-    switch (ep_idx) {
-        case 0:
-            break;
-        case 1:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_RDY);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL);
-            BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal);
-            break;
-        case 2:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_RDY);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL);
-            BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal);
-            break;
-        case 3:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_RDY);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL);
-            BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal);
-            break;
-        case 4:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_RDY);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL);
-            BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal);
-            break;
-        case 5:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_RDY);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL);
-            BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal);
-            break;
-        case 6:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_RDY);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL);
-            BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal);
-            break;
-        case 7:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_RDY);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL);
-            BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal);
-            break;
-
-        default:
-            break;
-    }
-    return 0;
+int usb_dc_ep_clear_stall(const uint8_t ep) {
+  uint8_t  ep_idx = USB_EP_GET_IDX(ep);
+  uint32_t tmpVal = 0;
+  if (USB_EP_DIR_IS_OUT(ep)) {
+    usb_fs_device.out_ep[ep_idx].is_stalled = 0;
+  } else {
+    usb_fs_device.in_ep[ep_idx].is_stalled = 0;
+  }
+  switch (ep_idx) {
+  case 0:
+    break;
+  case 1:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_RDY);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK);
+    tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL);
+    BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal);
+    break;
+  case 2:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_RDY);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK);
+    tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL);
+    BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal);
+    break;
+  case 3:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_RDY);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK);
+    tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL);
+    BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal);
+    break;
+  case 4:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_RDY);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK);
+    tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL);
+    BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal);
+    break;
+  case 5:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_RDY);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK);
+    tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL);
+    BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal);
+    break;
+  case 6:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_RDY);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK);
+    tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL);
+    BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal);
+    break;
+  case 7:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_RDY);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK);
+    tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL);
+    BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal);
+    break;
+
+  default:
+    break;
+  }
+  return 0;
 }
 
 /**
@@ -720,27 +699,26 @@ int usb_dc_ep_clear_stall(const uint8_t ep)
  *
  * @return 0 on success, negative errno code on fail.
  */
-int usb_dc_ep_is_stalled(struct device *dev, const uint8_t ep, uint8_t *stalled)
-{
-    uint8_t ep_idx = USB_EP_GET_IDX(ep);
+int usb_dc_ep_is_stalled(struct device *dev, const uint8_t ep, uint8_t *stalled) {
+  uint8_t ep_idx = USB_EP_GET_IDX(ep);
 
-    if (!stalled) {
-        return -1;
-    }
+  if (!stalled) {
+    return -1;
+  }
 
-    *stalled = 0U;
+  *stalled = 0U;
 
-    if (USB_EP_DIR_IS_OUT(ep)) {
-        if ((USB_Get_EPx_Status(ep_idx) & USB_EP_STATUS_STALL) && usb_fs_device.out_ep[ep_idx].is_stalled) {
-            *stalled = 1U;
-        }
-    } else {
-        if ((USB_Get_EPx_Status(ep_idx) & USB_EP_STATUS_STALL) && usb_fs_device.in_ep[ep_idx].is_stalled) {
-            *stalled = 1U;
-        }
+  if (USB_EP_DIR_IS_OUT(ep)) {
+    if ((USB_Get_EPx_Status(ep_idx) & USB_EP_STATUS_STALL) && usb_fs_device.out_ep[ep_idx].is_stalled) {
+      *stalled = 1U;
+    }
+  } else {
+    if ((USB_Get_EPx_Status(ep_idx) & USB_EP_STATUS_STALL) && usb_fs_device.in_ep[ep_idx].is_stalled) {
+      *stalled = 1U;
     }
+  }
 
-    return 0;
+  return 0;
 }
 
 /**
@@ -762,93 +740,92 @@ int usb_dc_ep_is_stalled(struct device *dev, const uint8_t ep, uint8_t *stalled)
  *
  * @return 0 on success, negative errno code on fail.
  */
-int usb_dc_ep_write(struct device *dev, const uint8_t ep, const uint8_t *data, uint32_t data_len, uint32_t *ret_bytes)
-{
-    uint8_t ep_idx;
-    uint32_t timeout = 0x00FFFFFF;
-    uint32_t ep_tx_fifo_addr;
-
-    ep_idx = USB_EP_GET_IDX(ep);
-
-    /* Check if IN ep */
-    if (USB_EP_GET_DIR(ep) != USB_EP_DIR_IN) {
-        return -USB_DC_EP_DIR_ERR;
+int usb_dc_ep_write(struct device *dev, const uint8_t ep, const uint8_t *data, uint32_t data_len, uint32_t *ret_bytes) {
+  uint8_t  ep_idx;
+  uint32_t timeout = 0x00FFFFFF;
+  uint32_t ep_tx_fifo_addr;
+
+  ep_idx = USB_EP_GET_IDX(ep);
+
+  /* Check if IN ep */
+  if (USB_EP_GET_DIR(ep) != USB_EP_DIR_IN) {
+    return -USB_DC_EP_DIR_ERR;
+  }
+
+  /* Check if ep enabled */
+  if (!usb_ep_is_enabled(ep)) {
+    return -USB_DC_EP_EN_ERR;
+  }
+
+  if (!data && data_len) {
+    USB_DC_LOG_ERR("data is null\r\n");
+    return -USB_DC_ADDR_ERR;
+  }
+
+  /* Check if ep free */
+  while (!USB_Is_EPx_RDY_Free(ep_idx) && (usb_fs_device.in_ep[ep_idx].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
+    timeout--;
+
+    if (!timeout) {
+      USB_DC_LOG_ERR("ep%d wait free timeout\r\n", ep);
+      return -USB_DC_EP_TIMEOUT_ERR;
     }
-
-    /* Check if ep enabled */
-    if (!usb_ep_is_enabled(ep)) {
-        return -USB_DC_EP_EN_ERR;
-    }
-
-    if (!data && data_len) {
-        USB_DC_LOG_ERR("data is null\r\n");
-        return -USB_DC_ADDR_ERR;
-    }
-
-    /* Check if ep free */
-    while (!USB_Is_EPx_RDY_Free(ep_idx) && (usb_fs_device.in_ep[ep_idx].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
-        timeout--;
-
-        if (!timeout) {
-            USB_DC_LOG_ERR("ep%d wait free timeout\r\n", ep);
-            return -USB_DC_EP_TIMEOUT_ERR;
-        }
-    }
-
-    if (!data_len) {
-        /* Zero length packet */
-        if ((USB_EP_GET_IDX(ep) != 0)) {
-            /* Clear NAK and enable ep */
-            USB_Set_EPx_Rdy(USB_EP_GET_IDX(ep));
-            return USB_DC_OK;
-        }
-        return USB_DC_OK;
-    }
-
-    if (data_len > usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps) {
-        /* Check if transfer len is too big */
-        data_len = usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps;
+  }
+
+  if (!data_len) {
+    /* Zero length packet */
+    if ((USB_EP_GET_IDX(ep) != 0)) {
+      /* Clear NAK and enable ep */
+      USB_Set_EPx_Rdy(USB_EP_GET_IDX(ep));
+      return USB_DC_OK;
     }
+    return USB_DC_OK;
+  }
 
-    /* Wait for FIFO space available */
-    do {
-        uint32_t avail_space = USB_Get_EPx_TX_FIFO_CNT(ep_idx);
-
-        if (avail_space >= usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps) {
-            break;
-        }
-
-        //USB_DC_LOG_ERR("EP%d have remain data\r\n", ep_idx);
-    } while (1);
-
-    /*
-     * Write data to FIFO, make sure that we are protected against
-     * other USB register accesses.  According to "DesignWare Cores
-     * USB 1.1/2.0 Device Subsystem-AHB/VCI Databook": "During FIFO
-     * access, the application must not access the UDC/Subsystem
-     * registers or vendor registers (for ULPI mode). After starting
-     * to access a FIFO, the application must complete the transaction
-     * before accessing the register."
-     */
-    ep_tx_fifo_addr = USB_BASE + USB_EP0_TX_FIFO_WDATA_OFFSET + ep_idx * 0x10;
-
-    if ((data_len == 1) && (ep_idx == 0)) {
-        USB_Set_EPx_Xfer_Size(EP_ID0, 1);
-    } else if (ep_idx == 0) {
-        USB_Set_EPx_Xfer_Size(EP_ID0, 64);
-    }
+  if (data_len > usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps) {
+    /* Check if transfer len is too big */
+    data_len = usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps;
+  }
 
-    memcopy_to_fifo((void *)ep_tx_fifo_addr, (uint8_t *)data, data_len);
-    /* Clear NAK and enable ep */
-    if (USB_EP_GET_IDX(ep) != 0)
-        USB_Set_EPx_Rdy(USB_EP_GET_IDX(ep));
-    USB_DC_LOG_DBG("EP%d write %u bytes\r\n", ep_idx, data_len);
+  /* Wait for FIFO space available */
+  do {
+    uint32_t avail_space = USB_Get_EPx_TX_FIFO_CNT(ep_idx);
 
-    if (ret_bytes) {
-        *ret_bytes = data_len;
+    if (avail_space >= usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps) {
+      break;
     }
 
-    return USB_DC_OK;
+    // USB_DC_LOG_ERR("EP%d have remain data\r\n", ep_idx);
+  } while (1);
+
+  /*
+   * Write data to FIFO, make sure that we are protected against
+   * other USB register accesses.  According to "DesignWare Cores
+   * USB 1.1/2.0 Device Subsystem-AHB/VCI Databook": "During FIFO
+   * access, the application must not access the UDC/Subsystem
+   * registers or vendor registers (for ULPI mode). After starting
+   * to access a FIFO, the application must complete the transaction
+   * before accessing the register."
+   */
+  ep_tx_fifo_addr = USB_BASE + USB_EP0_TX_FIFO_WDATA_OFFSET + ep_idx * 0x10;
+
+  if ((data_len == 1) && (ep_idx == 0)) {
+    USB_Set_EPx_Xfer_Size(EP_ID0, 1);
+  } else if (ep_idx == 0) {
+    USB_Set_EPx_Xfer_Size(EP_ID0, 64);
+  }
+
+  memcopy_to_fifo((void *)ep_tx_fifo_addr, (uint8_t *)data, data_len);
+  /* Clear NAK and enable ep */
+  if (USB_EP_GET_IDX(ep) != 0)
+    USB_Set_EPx_Rdy(USB_EP_GET_IDX(ep));
+  USB_DC_LOG_DBG("EP%d write %u bytes\r\n", ep_idx, data_len);
+
+  if (ret_bytes) {
+    *ret_bytes = data_len;
+  }
+
+  return USB_DC_OK;
 }
 
 /**
@@ -870,61 +847,60 @@ int usb_dc_ep_write(struct device *dev, const uint8_t ep, const uint8_t *data, u
  *
  * @return 0 on success, negative errno code on fail.
  */
-int usb_dc_ep_read(struct device *dev, const uint8_t ep, uint8_t *data, uint32_t data_len, uint32_t *read_bytes)
-{
-    uint8_t ep_idx = USB_EP_GET_IDX(ep);
-    uint32_t read_count;
-    uint32_t ep_rx_fifo_addr;
-    uint32_t timeout = 0x00FFFFFF;
-
-    /* Check if OUT ep */
-    if (USB_EP_GET_DIR(ep) != USB_EP_DIR_OUT) {
-        USB_DC_LOG_ERR("Wrong endpoint direction\r\n");
-        return -USB_DC_EP_DIR_ERR;
+int usb_dc_ep_read(struct device *dev, const uint8_t ep, uint8_t *data, uint32_t data_len, uint32_t *read_bytes) {
+  uint8_t  ep_idx = USB_EP_GET_IDX(ep);
+  uint32_t read_count;
+  uint32_t ep_rx_fifo_addr;
+  uint32_t timeout = 0x00FFFFFF;
+
+  /* Check if OUT ep */
+  if (USB_EP_GET_DIR(ep) != USB_EP_DIR_OUT) {
+    USB_DC_LOG_ERR("Wrong endpoint direction\r\n");
+    return -USB_DC_EP_DIR_ERR;
+  }
+
+  /* Check if ep enabled */
+  if (!usb_ep_is_enabled(ep)) {
+    USB_DC_LOG_ERR("Not enabled endpoint\r\n");
+    return -USB_DC_EP_EN_ERR;
+  }
+
+  if (!data && data_len) {
+    USB_DC_LOG_ERR("data is null\r\n");
+    return -USB_DC_ADDR_ERR;
+  }
+
+  /* Check if ep free */
+  while (!USB_Is_EPx_RDY_Free(ep_idx) && (usb_fs_device.out_ep[ep_idx].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
+    timeout--;
+
+    if (!timeout) {
+      USB_DC_LOG_ERR("ep%d wait free timeout\r\n", ep);
+      return -USB_DC_EP_TIMEOUT_ERR;
     }
+  }
 
-    /* Check if ep enabled */
-    if (!usb_ep_is_enabled(ep)) {
-        USB_DC_LOG_ERR("Not enabled endpoint\r\n");
-        return -USB_DC_EP_EN_ERR;
+  if (!data_len) {
+    if ((USB_EP_GET_IDX(ep) != 0)) {
+      /* Clear NAK and enable ep */
+      USB_Set_EPx_Rdy(USB_EP_GET_IDX(ep));
+      return USB_DC_OK;
     }
+  }
 
-    if (!data && data_len) {
-        USB_DC_LOG_ERR("data is null\r\n");
-        return -USB_DC_ADDR_ERR;
-    }
-
-    /* Check if ep free */
-    while (!USB_Is_EPx_RDY_Free(ep_idx) && (usb_fs_device.out_ep[ep_idx].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
-        timeout--;
-
-        if (!timeout) {
-            USB_DC_LOG_ERR("ep%d wait free timeout\r\n", ep);
-            return -USB_DC_EP_TIMEOUT_ERR;
-        }
-    }
-
-    if (!data_len) {
-        if ((USB_EP_GET_IDX(ep) != 0)) {
-            /* Clear NAK and enable ep */
-            USB_Set_EPx_Rdy(USB_EP_GET_IDX(ep));
-            return USB_DC_OK;
-        }
-    }
-
-    read_count = USB_Get_EPx_RX_FIFO_CNT(ep_idx);
-    read_count = MIN(read_count, data_len);
+  read_count = USB_Get_EPx_RX_FIFO_CNT(ep_idx);
+  read_count = MIN(read_count, data_len);
 
-    /* Data in the FIFOs is always stored per 8-bit word*/
-    ep_rx_fifo_addr = (USB_BASE + USB_EP0_RX_FIFO_RDATA_OFFSET + ep_idx * 0x10);
-    fifocopy_to_mem((void *)ep_rx_fifo_addr, data, read_count);
-    USB_DC_LOG_DBG("Read EP%d, req %d, read %d bytes\r\n", ep, data_len, read_count);
+  /* Data in the FIFOs is always stored per 8-bit word*/
+  ep_rx_fifo_addr = (USB_BASE + USB_EP0_RX_FIFO_RDATA_OFFSET + ep_idx * 0x10);
+  fifocopy_to_mem((void *)ep_rx_fifo_addr, data, read_count);
+  USB_DC_LOG_DBG("Read EP%d, req %d, read %d bytes\r\n", ep, data_len, read_count);
 
-    if (read_bytes) {
-        *read_bytes = read_count;
-    }
+  if (read_bytes) {
+    *read_bytes = read_count;
+  }
 
-    return USB_DC_OK;
+  return USB_DC_OK;
 }
 /**
  * @brief
@@ -934,46 +910,45 @@ int usb_dc_ep_read(struct device *dev, const uint8_t ep, uint8_t *data, uint32_t
  * @param ep
  * @return int
  */
-int usb_dc_receive_to_ringbuffer(struct device *dev, Ring_Buffer_Type *rb, uint8_t ep)
-{
-    uint8_t ep_idx;
-    uint8_t recv_len;
-    static bool overflow_flag = false;
-
-    /* Check if OUT ep */
-    if (USB_EP_GET_DIR(ep) != USB_EP_DIR_OUT) {
-        USB_DC_LOG_ERR("Wrong endpoint direction\r\n");
-        return -USB_DC_EP_DIR_ERR;
-    }
+int usb_dc_receive_to_ringbuffer(struct device *dev, Ring_Buffer_Type *rb, uint8_t ep) {
+  uint8_t     ep_idx;
+  uint8_t     recv_len;
+  static bool overflow_flag = false;
+
+  /* Check if OUT ep */
+  if (USB_EP_GET_DIR(ep) != USB_EP_DIR_OUT) {
+    USB_DC_LOG_ERR("Wrong endpoint direction\r\n");
+    return -USB_DC_EP_DIR_ERR;
+  }
+
+  /* Check if ep enabled */
+  if (!usb_ep_is_enabled(ep)) {
+    return -USB_DC_EP_EN_ERR;
+  }
+
+  ep_idx = USB_EP_GET_IDX(ep);
+
+  recv_len = USB_Get_EPx_RX_FIFO_CNT(ep_idx);
+
+  /*if rx fifo count equal 0,it means last is send nack and ringbuffer is smaller than 64,
+   * so,if ringbuffer is larger than 64,set ack to recv next data.
+   */
+  if (overflow_flag && (Ring_Buffer_Get_Empty_Length(rb) > 64) && (!recv_len)) {
+    overflow_flag = false;
+    USB_Set_EPx_Rdy(ep_idx);
+    return 0;
+  } else {
+    uint32_t addr = USB_BASE + 0x11C + (ep_idx - 1) * 0x10;
+    Ring_Buffer_Write_Callback(rb, recv_len, fifocopy_to_mem, (void *)addr);
 
-    /* Check if ep enabled */
-    if (!usb_ep_is_enabled(ep)) {
-        return -USB_DC_EP_EN_ERR;
+    if (Ring_Buffer_Get_Empty_Length(rb) < 64) {
+      overflow_flag = true;
+      return -USB_DC_RB_SIZE_SMALL_ERR;
     }
 
-    ep_idx = USB_EP_GET_IDX(ep);
-
-    recv_len = USB_Get_EPx_RX_FIFO_CNT(ep_idx);
-
-    /*if rx fifo count equal 0,it means last is send nack and ringbuffer is smaller than 64,
-    * so,if ringbuffer is larger than 64,set ack to recv next data.
-    */
-    if (overflow_flag && (Ring_Buffer_Get_Empty_Length(rb) > 64) && (!recv_len)) {
-        overflow_flag = false;
-        USB_Set_EPx_Rdy(ep_idx);
-        return 0;
-    } else {
-        uint32_t addr = USB_BASE + 0x11C + (ep_idx - 1) * 0x10;
-        Ring_Buffer_Write_Callback(rb, recv_len, fifocopy_to_mem, (void *)addr);
-
-        if (Ring_Buffer_Get_Empty_Length(rb) < 64) {
-            overflow_flag = true;
-            return -USB_DC_RB_SIZE_SMALL_ERR;
-        }
-
-        USB_Set_EPx_Rdy(ep_idx);
-        return 0;
-    }
+    USB_Set_EPx_Rdy(ep_idx);
+    return 0;
+  }
 }
 /**
  * @brief
@@ -983,46 +958,45 @@ int usb_dc_receive_to_ringbuffer(struct device *dev, Ring_Buffer_Type *rb, uint8
  * @param ep
  * @return int
  */
-int usb_dc_send_from_ringbuffer(struct device *dev, Ring_Buffer_Type *rb, uint8_t ep)
-{
-    uint8_t ep_idx;
-    static bool zlp_flag = false;
-    static uint32_t send_total_len = 0;
+int usb_dc_send_from_ringbuffer(struct device *dev, Ring_Buffer_Type *rb, uint8_t ep) {
+  uint8_t         ep_idx;
+  static bool     zlp_flag       = false;
+  static uint32_t send_total_len = 0;
 
-    ep_idx = USB_EP_GET_IDX(ep);
+  ep_idx = USB_EP_GET_IDX(ep);
 
-    /* Check if IN ep */
-    if (USB_EP_GET_DIR(ep) != USB_EP_DIR_IN) {
-        return -USB_DC_EP_DIR_ERR;
-    }
+  /* Check if IN ep */
+  if (USB_EP_GET_DIR(ep) != USB_EP_DIR_IN) {
+    return -USB_DC_EP_DIR_ERR;
+  }
 
-    /* Check if ep enabled */
-    if (!usb_ep_is_enabled(ep)) {
-        return -USB_DC_EP_EN_ERR;
-    }
+  /* Check if ep enabled */
+  if (!usb_ep_is_enabled(ep)) {
+    return -USB_DC_EP_EN_ERR;
+  }
 
-    uint32_t addr = USB_BASE + 0x118 + (ep_idx - 1) * 0x10;
+  uint32_t addr = USB_BASE + 0x118 + (ep_idx - 1) * 0x10;
 
-    if (zlp_flag == false) {
-        if ((USB_Get_EPx_TX_FIFO_CNT(ep_idx) == USB_FS_MAX_PACKET_SIZE) && Ring_Buffer_Get_Length(rb)) {
-            uint32_t actual_len = Ring_Buffer_Read_Callback(rb, USB_FS_MAX_PACKET_SIZE, memcopy_to_fifo, (void *)addr);
-            send_total_len += actual_len;
+  if (zlp_flag == false) {
+    if ((USB_Get_EPx_TX_FIFO_CNT(ep_idx) == USB_FS_MAX_PACKET_SIZE) && Ring_Buffer_Get_Length(rb)) {
+      uint32_t actual_len = Ring_Buffer_Read_Callback(rb, USB_FS_MAX_PACKET_SIZE, memcopy_to_fifo, (void *)addr);
+      send_total_len += actual_len;
 
-            if (!Ring_Buffer_Get_Length(rb) && (!(send_total_len % 64))) {
-                zlp_flag = true;
-            }
+      if (!Ring_Buffer_Get_Length(rb) && (!(send_total_len % 64))) {
+        zlp_flag = true;
+      }
 
-            USB_Set_EPx_Rdy(ep_idx);
-            return 0;
-        } else {
-            return -USB_DC_RB_SIZE_SMALL_ERR;
-        }
+      USB_Set_EPx_Rdy(ep_idx);
+      return 0;
     } else {
-        zlp_flag = false;
-        send_total_len = 0;
-        USB_Set_EPx_Rdy(ep_idx);
-        return -USB_DC_ZLP_ERR;
+      return -USB_DC_RB_SIZE_SMALL_ERR;
     }
+  } else {
+    zlp_flag       = false;
+    send_total_len = 0;
+    USB_Set_EPx_Rdy(ep_idx);
+    return -USB_DC_ZLP_ERR;
+  }
 }
 
 /**
@@ -1030,144 +1004,139 @@ int usb_dc_send_from_ringbuffer(struct device *dev, Ring_Buffer_Type *rb, uint8_
  *
  * @param device
  */
-void usb_dc_isr(usb_dc_device_t *device)
-{
-    USB_EP_ID epnum = EP_ID0;
-
-    /* EP1_DONE -> EP2_DONE -> ...... -> EP7_DONE*/
-    for (USB_INT_Type epint = USB_INT_EP1_DONE; epint <= USB_INT_EP7_DONE; epint += 2) {
-        if (USB_Get_IntStatus(epint)) {
-            epnum = (epint - USB_INT_EP0_OUT_CMD) >> 1;
-            if (!USB_Is_EPx_RDY_Free(epnum) && (device->out_ep[epnum].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
-                USB_DC_LOG_ERR("ep%d out busy\r\n", epnum);
-                continue;
-            }
-            USB_Clr_IntStatus(epint);
-            device->parent.callback(&device->parent, (void *)((uint32_t)USB_SET_EP_OUT(epnum)), 0, USB_DC_EVENT_EP_OUT_NOTIFY);
-        }
-    }
-
-    /* EP1_CMD -> EP2_CMD -> ...... -> EP7_CMD*/
-    for (USB_INT_Type epint = USB_INT_EP1_CMD; epint <= USB_INT_EP7_CMD; epint += 2) {
-        if (USB_Get_IntStatus(epint)) {
-            epnum = (epint - USB_INT_EP0_OUT_CMD) >> 1;
-            if (!USB_Is_EPx_RDY_Free(epnum) && (device->in_ep[epnum].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
-                USB_DC_LOG_DBG("ep%d in busy\r\n", epnum);
-                continue;
-            }
-            USB_Clr_IntStatus(epint);
-            device->parent.callback(&device->parent, (void *)((uint32_t)USB_SET_EP_IN(epnum)), 0, USB_DC_EVENT_EP_IN_NOTIFY);
-        }
-    }
-
-    /* EP0 setup done */
-    if (USB_Get_IntStatus(USB_INT_EP0_SETUP_DONE)) {
-        if (!USB_Is_EPx_RDY_Free(0)) {
-            USB_DC_LOG_DBG("ep0 setup busy\r\n");
-            return;
-        }
-        USB_Clr_IntStatus(USB_INT_EP0_SETUP_DONE);
-        device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_SETUP_NOTIFY);
-        USB_Set_EPx_Rdy(EP_ID0);
-        return;
-    }
-
-    /* EP0 in done */
-    if (USB_Get_IntStatus(USB_INT_EP0_IN_DONE)) {
-        if (!USB_Is_EPx_RDY_Free(0)) {
-            USB_DC_LOG_DBG("ep0 in busy\r\n");
-            return;
-        }
-        USB_Clr_IntStatus(USB_INT_EP0_IN_DONE);
-        device->parent.callback(&device->parent, (void *)0x80, 0, USB_DC_EVENT_EP0_IN_NOTIFY);
-        USB_Set_EPx_Rdy(EP_ID0);
-        return;
-    }
-
-    /* EP0 out done */
-    if (USB_Get_IntStatus(USB_INT_EP0_OUT_DONE)) {
-        if (!USB_Is_EPx_RDY_Free(0)) {
-            USB_DC_LOG_DBG("ep0 out busy\r\n");
-            return;
-        }
-        USB_Clr_IntStatus(USB_INT_EP0_OUT_DONE);
-        device->parent.callback(&device->parent, (void *)0x00, 0, USB_DC_EVENT_EP0_OUT_NOTIFY);
-        USB_Set_EPx_Rdy(EP_ID0);
-        return;
+void usb_dc_isr(usb_dc_device_t *device) {
+  USB_EP_ID epnum = EP_ID0;
+
+  /* EP1_DONE -> EP2_DONE -> ...... -> EP7_DONE*/
+  for (USB_INT_Type epint = USB_INT_EP1_DONE; epint <= USB_INT_EP7_DONE; epint += 2) {
+    if (USB_Get_IntStatus(epint)) {
+      epnum = (epint - USB_INT_EP0_OUT_CMD) >> 1;
+      if (!USB_Is_EPx_RDY_Free(epnum) && (device->out_ep[epnum].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
+        USB_DC_LOG_ERR("ep%d out busy\r\n", epnum);
+        continue;
+      }
+      USB_Clr_IntStatus(epint);
+      device->parent.callback(&device->parent, (void *)((uint32_t)USB_SET_EP_OUT(epnum)), 0, USB_DC_EVENT_EP_OUT_NOTIFY);
     }
-
-    /* sof */
-    if (USB_Get_IntStatus(USB_INT_SOF)) {
-        USB_Clr_IntStatus(USB_INT_SOF);
-        device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_SOF);
-        return;
+  }
+
+  /* EP1_CMD -> EP2_CMD -> ...... -> EP7_CMD*/
+  for (USB_INT_Type epint = USB_INT_EP1_CMD; epint <= USB_INT_EP7_CMD; epint += 2) {
+    if (USB_Get_IntStatus(epint)) {
+      epnum = (epint - USB_INT_EP0_OUT_CMD) >> 1;
+      if (!USB_Is_EPx_RDY_Free(epnum) && (device->in_ep[epnum].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
+        USB_DC_LOG_DBG("ep%d in busy\r\n", epnum);
+        continue;
+      }
+      USB_Clr_IntStatus(epint);
+      device->parent.callback(&device->parent, (void *)((uint32_t)USB_SET_EP_IN(epnum)), 0, USB_DC_EVENT_EP_IN_NOTIFY);
     }
+  }
 
-    /* reset */
-    if (USB_Get_IntStatus(USB_INT_RESET)) {
-        USB_Clr_IntStatus(USB_INT_RESET);
-        device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_RESET);
-        return;
+  /* EP0 setup done */
+  if (USB_Get_IntStatus(USB_INT_EP0_SETUP_DONE)) {
+    if (!USB_Is_EPx_RDY_Free(0)) {
+      USB_DC_LOG_DBG("ep0 setup busy\r\n");
+      return;
     }
-
-    /* reset end */
-    if (USB_Get_IntStatus(USB_INT_RESET_END)) {
-        USB_Clr_IntStatus(USB_INT_RESET_END);
-        USB_Set_EPx_Rdy(EP_ID0);
-        return;
+    USB_Clr_IntStatus(USB_INT_EP0_SETUP_DONE);
+    device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_SETUP_NOTIFY);
+    USB_Set_EPx_Rdy(EP_ID0);
+    return;
+  }
+
+  /* EP0 in done */
+  if (USB_Get_IntStatus(USB_INT_EP0_IN_DONE)) {
+    if (!USB_Is_EPx_RDY_Free(0)) {
+      USB_DC_LOG_DBG("ep0 in busy\r\n");
+      return;
     }
-
-    /* vbus toggle */
-    if (USB_Get_IntStatus(USB_INT_VBUS_TGL)) {
-        USB_Clr_IntStatus(USB_INT_VBUS_TGL);
-        return;
+    USB_Clr_IntStatus(USB_INT_EP0_IN_DONE);
+    device->parent.callback(&device->parent, (void *)0x80, 0, USB_DC_EVENT_EP0_IN_NOTIFY);
+    USB_Set_EPx_Rdy(EP_ID0);
+    return;
+  }
+
+  /* EP0 out done */
+  if (USB_Get_IntStatus(USB_INT_EP0_OUT_DONE)) {
+    if (!USB_Is_EPx_RDY_Free(0)) {
+      USB_DC_LOG_DBG("ep0 out busy\r\n");
+      return;
     }
+    USB_Clr_IntStatus(USB_INT_EP0_OUT_DONE);
+    device->parent.callback(&device->parent, (void *)0x00, 0, USB_DC_EVENT_EP0_OUT_NOTIFY);
+    USB_Set_EPx_Rdy(EP_ID0);
+    return;
+  }
+
+  /* sof */
+  if (USB_Get_IntStatus(USB_INT_SOF)) {
+    USB_Clr_IntStatus(USB_INT_SOF);
+    device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_SOF);
+    return;
+  }
+
+  /* reset */
+  if (USB_Get_IntStatus(USB_INT_RESET)) {
+    USB_Clr_IntStatus(USB_INT_RESET);
+    device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_RESET);
+    return;
+  }
+
+  /* reset end */
+  if (USB_Get_IntStatus(USB_INT_RESET_END)) {
+    USB_Clr_IntStatus(USB_INT_RESET_END);
+    USB_Set_EPx_Rdy(EP_ID0);
+    return;
+  }
+
+  /* vbus toggle */
+  if (USB_Get_IntStatus(USB_INT_VBUS_TGL)) {
+    USB_Clr_IntStatus(USB_INT_VBUS_TGL);
+    return;
+  }
 #ifdef ENABLE_LPM_INT
-    /* LPM wakeup */
-    if (USB_Get_IntStatus(USB_INT_LPM_WAKEUP)) {
-        USB_Clr_IntStatus(USB_INT_LPM_WAKEUP);
-        return;
-    }
-
-    /* LPM packet */
-    if (USB_Get_IntStatus(USB_INT_LPM_PACKET)) {
-        /*************************************/
-        /* Force low-power mode in the macrocell */
-        if (USB_Get_IntStatus(USB_INT_LPM_WAKEUP) == 0) {
-        }
-
-        /*************************************/
-        USB_Clr_IntStatus(USB_INT_LPM_PACKET);
-        return;
-    }
+  /* LPM wakeup */
+  if (USB_Get_IntStatus(USB_INT_LPM_WAKEUP)) {
+    USB_Clr_IntStatus(USB_INT_LPM_WAKEUP);
+    return;
+  }
+
+  /* LPM packet */
+  if (USB_Get_IntStatus(USB_INT_LPM_PACKET)) {
+    /*************************************/
+    /* Force low-power mode in the macrocell */
+    if (USB_Get_IntStatus(USB_INT_LPM_WAKEUP) == 0) {}
+
+    /*************************************/
+    USB_Clr_IntStatus(USB_INT_LPM_PACKET);
+    return;
+  }
 #endif
 #ifdef ENABLE_SOF3MS_INT
-    /* lost 3 SOF */
-    if (USB_Get_IntStatus(USB_INT_LOST_SOF_3_TIMES)) {
-        USB_DC_LOG_ERR("Lost 3 SOFs\r\n");
-        /*************************************/
-        /*************************************/
-        USB_Clr_IntStatus(USB_INT_LOST_SOF_3_TIMES);
-        return;
-    }
+  /* lost 3 SOF */
+  if (USB_Get_IntStatus(USB_INT_LOST_SOF_3_TIMES)) {
+    USB_DC_LOG_ERR("Lost 3 SOFs\r\n");
+    /*************************************/
+    /*************************************/
+    USB_Clr_IntStatus(USB_INT_LOST_SOF_3_TIMES);
+    return;
+  }
 #endif
 #ifdef ENABLE_ERROR_INT
-    /* error */
-    if (USB_Get_IntStatus(USB_INT_ERROR)) {
-        USB_DC_LOG("USB bus error 0x%08x; EP2 fifo status 0x%08x\r\n", *(volatile uint32_t *)(0x4000D81C), *(volatile uint32_t *)(0x4000D920));
-        /*************************************/
-        /*************************************/
-        device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_ERROR);
-        USB_Clr_IntStatus(USB_INT_ERROR);
-        return;
-    }
+  /* error */
+  if (USB_Get_IntStatus(USB_INT_ERROR)) {
+    USB_DC_LOG("USB bus error 0x%08x; EP2 fifo status 0x%08x\r\n", *(volatile uint32_t *)(0x4000D81C), *(volatile uint32_t *)(0x4000D920));
+    /*************************************/
+    /*************************************/
+    device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_ERROR);
+    USB_Clr_IntStatus(USB_INT_ERROR);
+    return;
+  }
 #endif
 }
 /**
  * @brief
  *
  */
-void USB_FS_IRQ(void)
-{
-    usb_dc_isr(&usb_fs_device);
-}
\ No newline at end of file
+void USB_FS_IRQ(void) { usb_dc_isr(&usb_fs_device); }
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_wdt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_wdt.c
index 8b9ace43fc..bad6cf9802 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_wdt.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_wdt.c
@@ -33,138 +33,132 @@ static wdt_device_t wdtx_device[WDT_MAX_INDEX] = {
 #endif
 };
 
-int wdt_open(struct device *dev, uint16_t oflag)
-{
-    // uint32_t tmpval;
-
-    /* watchdog timer disable*/
-    // tmpval = BL_RD_REG(TIMER_BASE, TIMER_WMER);
-    // BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_CLR_REG_BIT(tmpval, TIMER_WE));
-    // // MSG("wdt timeout %d \r\n", wdt_device->wdt_timeout);
-    // /* Set watchdog timer match register value */
-    // BL_WR_REG(TIMER_BASE, TIMER_WMR, (uint16_t)wdt_device->wdt_timeout);
-
-    if (oflag & DEVICE_OFLAG_INT_TX) {
+int wdt_open(struct device *dev, uint16_t oflag) {
+  // uint32_t tmpval;
+
+  /* watchdog timer disable*/
+  // tmpval = BL_RD_REG(TIMER_BASE, TIMER_WMER);
+  // BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_CLR_REG_BIT(tmpval, TIMER_WE));
+  // // MSG("wdt timeout %d \r\n", wdt_device->wdt_timeout);
+  // /* Set watchdog timer match register value */
+  // BL_WR_REG(TIMER_BASE, TIMER_WMR, (uint16_t)wdt_device->wdt_timeout);
+
+  if (oflag & DEVICE_OFLAG_INT_TX) {
 #ifdef BSP_USING_WDT
-        wdt_device_t *wdt_device = (wdt_device_t *)dev;
-        // WDT_IntMask(WDT_INT, UNMASK);
-        if (wdt_device->id == 0) {
-            Interrupt_Handler_Register(TIMER_WDT_IRQn, WDT_IRQ);
-        }
-#endif
-    } else {
-        WDT_IntMask(WDT_INT, MASK);
+    wdt_device_t *wdt_device = (wdt_device_t *)dev;
+    // WDT_IntMask(WDT_INT, UNMASK);
+    if (wdt_device->id == 0) {
+      Interrupt_Handler_Register(TIMER_WDT_IRQn, WDT_IRQ);
     }
+#endif
+  } else {
+    WDT_IntMask(WDT_INT, MASK);
+  }
 
-    // /* enable watchdog timer */
-    WDT_Enable();
-    return 0;
+  // /* enable watchdog timer */
+  WDT_Enable();
+  return 0;
 }
 
-int wdt_close(struct device *dev)
-{
-    // wdt_device_t *wdt_device = (wdt_device_t *)(dev);
-    WDT_Disable();
-    return 0;
+int wdt_close(struct device *dev) {
+  // wdt_device_t *wdt_device = (wdt_device_t *)(dev);
+  WDT_Disable();
+  return 0;
 }
 
-int wdt_control(struct device *dev, int cmd, void *args)
-{
-    // wdt_device_t *wdt_device = (wdt_device_t *)dev;
-
-    switch (cmd) {
-        case DEVICE_CTRL_SET_INT: {
-            WDT_IntMask(WDT_INT, UNMASK);
-            CPU_Interrupt_Pending_Clear(TIMER_WDT_IRQn);
-            CPU_Interrupt_Enable(TIMER_WDT_IRQn);
-            break;
-        }
-        case DEVICE_CTRL_CLR_INT: {
-            WDT_IntMask(WDT_INT, MASK);
-            CPU_Interrupt_Disable(TIMER_WDT_IRQn);
-            break;
-        }
-        case DEVICE_CTRL_CONFIG: {
-            break;
-        }
-        case DEVICE_CTRL_RESUME: {
-            WDT_Enable();
-            break;
-        }
-        case DEVICE_CTRL_SUSPEND: {
-            WDT_Disable();
-            break;
-        }
-        case DEVICE_CTRL_GET_WDT_COUNTER: {
-            return WDT_GetCounterValue();
-            break;
-        }
-        case DEVICE_CTRL_RST_WDT_COUNTER: {
-            WDT_ResetCounterValue();
-            break;
-        }
-        case DEVICE_CTRL_GET_RST_STATUS: {
-            return WDT_GetResetStatus();
-            break;
-        }
-        case DEVICE_CTRL_CLR_RST_STATUS: {
-            WDT_ClearResetStatus();
-            break;
-        }
-        default:
-            break;
-    }
-
-    return 0;
+int wdt_control(struct device *dev, int cmd, void *args) {
+  // wdt_device_t *wdt_device = (wdt_device_t *)dev;
+
+  switch (cmd) {
+  case DEVICE_CTRL_SET_INT: {
+    WDT_IntMask(WDT_INT, UNMASK);
+    CPU_Interrupt_Pending_Clear(TIMER_WDT_IRQn);
+    CPU_Interrupt_Enable(TIMER_WDT_IRQn);
+    break;
+  }
+  case DEVICE_CTRL_CLR_INT: {
+    WDT_IntMask(WDT_INT, MASK);
+    CPU_Interrupt_Disable(TIMER_WDT_IRQn);
+    break;
+  }
+  case DEVICE_CTRL_CONFIG: {
+    break;
+  }
+  case DEVICE_CTRL_RESUME: {
+    WDT_Enable();
+    break;
+  }
+  case DEVICE_CTRL_SUSPEND: {
+    WDT_Disable();
+    break;
+  }
+  case DEVICE_CTRL_GET_WDT_COUNTER: {
+    return WDT_GetCounterValue();
+    break;
+  }
+  case DEVICE_CTRL_RST_WDT_COUNTER: {
+    WDT_ResetCounterValue();
+    break;
+  }
+  case DEVICE_CTRL_GET_RST_STATUS: {
+    return WDT_GetResetStatus();
+    break;
+  }
+  case DEVICE_CTRL_CLR_RST_STATUS: {
+    WDT_ClearResetStatus();
+    break;
+  }
+  default:
+    break;
+  }
+
+  return 0;
 }
 
-int wdt_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size)
-{
-    // wdt_device_t *wdt_device = (wdt_device_t *)dev;
-    uint16_t wdt_timeout = (uint16_t)(uint32_t)buffer;
+int wdt_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size) {
+  // wdt_device_t *wdt_device = (wdt_device_t *)dev;
+  uint16_t wdt_timeout = (uint16_t)(uint32_t)buffer;
 
-    WDT_Disable();
-    WDT_SetCompValue(wdt_timeout);
-    WDT_Enable();
+  WDT_Disable();
+  WDT_SetCompValue(wdt_timeout);
+  WDT_Enable();
 
-    return 0;
+  return 0;
 }
 
-int wdt_register(enum wdt_index_type index, const char *name)
-{
-    struct device *dev;
+int wdt_register(enum wdt_index_type index, const char *name) {
+  struct device *dev;
 
-    if (WDT_MAX_INDEX == 0) {
-        return -DEVICE_EINVAL;
-    }
+  if (WDT_MAX_INDEX == 0) {
+    return -DEVICE_EINVAL;
+  }
 
-    dev = &(wdtx_device[index].parent);
+  dev = &(wdtx_device[index].parent);
 
-    dev->open = wdt_open;
-    dev->close = wdt_close;
-    dev->control = wdt_control;
-    dev->write = wdt_write;
-    // dev->read = NULL;
+  dev->open    = wdt_open;
+  dev->close   = wdt_close;
+  dev->control = wdt_control;
+  dev->write   = wdt_write;
+  // dev->read = NULL;
 
-    dev->status = DEVICE_UNREGISTER;
-    dev->type = DEVICE_CLASS_TIMER;
-    dev->handle = NULL;
+  dev->status = DEVICE_UNREGISTER;
+  dev->type   = DEVICE_CLASS_TIMER;
+  dev->handle = NULL;
 
-    return device_register(dev, name);
+  return device_register(dev, name);
 }
 
-void wdt_isr(wdt_device_t *handle)
-{
-    uint32_t tmpval;
+void wdt_isr(wdt_device_t *handle) {
+  uint32_t tmpval;
 
-    if (!handle->parent.callback) {
-        return;
-    }
+  if (!handle->parent.callback) {
+    return;
+  }
 
-    tmpval = BL_RD_REG(TIMER_BASE, TIMER_WICR);
-    BL_WR_REG(TIMER_BASE, TIMER_WICR, BL_SET_REG_BIT(tmpval, TIMER_WICLR));
+  tmpval = BL_RD_REG(TIMER_BASE, TIMER_WICR);
+  BL_WR_REG(TIMER_BASE, TIMER_WICR, BL_SET_REG_BIT(tmpval, TIMER_WICLR));
 
-    handle->parent.callback(&handle->parent, NULL, 0, WDT_EVENT);
+  handle->parent.callback(&handle->parent, NULL, 0, WDT_EVENT);
 }
 
 #ifdef BSP_USING_WDT
@@ -172,8 +166,5 @@ void wdt_isr(wdt_device_t *handle)
  * @brief
  *
  */
-void WDT_IRQ(void)
-{
-    wdt_isr(&wdtx_device[WDT_INDEX]);
-}
+void WDT_IRQ(void) { wdt_isr(&wdtx_device[WDT_INDEX]); }
 #endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c
index 7369b7c503..61df6a9884 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c
@@ -29,25 +29,13 @@
 #define MEM_MANAGE_MINUM_MEM_SIZE         (MEM_MANAGE_MEM_STRUCT_SIZE << 1)
 #define MEM_MANAGE_ALLOCA_LABAL           ((size_t)((size_t)1 << (sizeof(size_t) * MEM_MANAGE_BITS_PER_BYTE - 1)))
 
-static inline size_t mmheap_align_down(size_t data, size_t align_byte)
-{
-    return data & ~(align_byte - 1);
-}
+static inline size_t mmheap_align_down(size_t data, size_t align_byte) { return data & ~(align_byte - 1); }
 
-static inline size_t mmheap_align_up(size_t data, size_t align_byte)
-{
-    return (data + align_byte - 1) & ~(align_byte - 1);
-}
+static inline size_t mmheap_align_up(size_t data, size_t align_byte) { return (data + align_byte - 1) & ~(align_byte - 1); }
 
-static inline struct heap_node *mmheap_addr_sub(const void *addr)
-{
-    return (struct heap_node *)((const uint8_t *)addr - MEM_MANAGE_MEM_STRUCT_SIZE);
-}
+static inline struct heap_node *mmheap_addr_sub(const void *addr) { return (struct heap_node *)((const uint8_t *)addr - MEM_MANAGE_MEM_STRUCT_SIZE); }
 
-static inline void *mmheap_addr_add(const struct heap_node *mem_node)
-{
-    return (void *)((const uint8_t *)mem_node + MEM_MANAGE_MEM_STRUCT_SIZE);
-}
+static inline void *mmheap_addr_add(const struct heap_node *mem_node) { return (void *)((const uint8_t *)mem_node + MEM_MANAGE_MEM_STRUCT_SIZE); }
 
 /**
  * @brief mmheap_insert_node_to_freelist
@@ -55,40 +43,38 @@ static inline void *mmheap_addr_add(const struct heap_node *mem_node)
  * @param pRoot
  * @param pNode
  */
-static inline void mmheap_insert_node_to_freelist(struct heap_info *pRoot, struct heap_node *pNode)
-{
-    struct heap_node *pPriv_Node;
-    struct heap_node *pNext_Node;
-    /*Find the node with an address similar to pNode*/
-    for (pPriv_Node = pRoot->pStart; pPriv_Node->next_node < pNode; pPriv_Node = pPriv_Node->next_node) {
-    }
+static inline void mmheap_insert_node_to_freelist(struct heap_info *pRoot, struct heap_node *pNode) {
+  struct heap_node *pPriv_Node;
+  struct heap_node *pNext_Node;
+  /*Find the node with an address similar to pNode*/
+  for (pPriv_Node = pRoot->pStart; pPriv_Node->next_node < pNode; pPriv_Node = pPriv_Node->next_node) {}
 
-    pNext_Node = pPriv_Node->next_node;
-    /*Try to merge the pNode with the previous block*/
-    if ((uint8_t *)mmheap_addr_add(pPriv_Node) + pPriv_Node->mem_size == (uint8_t *)pNode) {
-        if (pPriv_Node != pRoot->pStart) { /*can merge if not start block*/
-            pPriv_Node->mem_size += MEM_MANAGE_MEM_STRUCT_SIZE + pNode->mem_size;
-            pNode = pPriv_Node;
-        } else {
-            /*The latter is not merged if it is a Start block to avoid wasting memory*/
-            pRoot->pStart->next_node = pNode;
-        }
+  pNext_Node = pPriv_Node->next_node;
+  /*Try to merge the pNode with the previous block*/
+  if ((uint8_t *)mmheap_addr_add(pPriv_Node) + pPriv_Node->mem_size == (uint8_t *)pNode) {
+    if (pPriv_Node != pRoot->pStart) { /*can merge if not start block*/
+      pPriv_Node->mem_size += MEM_MANAGE_MEM_STRUCT_SIZE + pNode->mem_size;
+      pNode = pPriv_Node;
     } else {
-        /*Insert directly into the free single-chain table when merging is not possible*/
-        pPriv_Node->next_node = pNode;
+      /*The latter is not merged if it is a Start block to avoid wasting memory*/
+      pRoot->pStart->next_node = pNode;
     }
-    /*Try to merge the pNode with the next block*/
-    if ((uint8_t *)mmheap_addr_add(pNode) + pNode->mem_size == (uint8_t *)pNext_Node) {
-        if (pNext_Node != pRoot->pEnd) {
-            pNode->mem_size += MEM_MANAGE_MEM_STRUCT_SIZE + pNext_Node->mem_size;
-            pNode->next_node = pNext_Node->next_node;
-        } else {
-            pNode->next_node = pRoot->pEnd;
-        }
+  } else {
+    /*Insert directly into the free single-chain table when merging is not possible*/
+    pPriv_Node->next_node = pNode;
+  }
+  /*Try to merge the pNode with the next block*/
+  if ((uint8_t *)mmheap_addr_add(pNode) + pNode->mem_size == (uint8_t *)pNext_Node) {
+    if (pNext_Node != pRoot->pEnd) {
+      pNode->mem_size += MEM_MANAGE_MEM_STRUCT_SIZE + pNext_Node->mem_size;
+      pNode->next_node = pNext_Node->next_node;
     } else {
-        /*Insert directly into the free single-chain table when merging is not possible*/
-        pNode->next_node = pNext_Node;
+      pNode->next_node = pRoot->pEnd;
     }
+  } else {
+    /*Insert directly into the free single-chain table when merging is not possible*/
+    pNode->next_node = pNext_Node;
+  }
 }
 
 /**
@@ -97,24 +83,23 @@ static inline void mmheap_insert_node_to_freelist(struct heap_info *pRoot, struc
  * @param pRoot
  * @param pState
  */
-void mmheap_get_state(struct heap_info *pRoot, struct heap_state *pState)
-{
-    MMHEAP_ASSERT(pRoot->pStart != NULL);
-    MMHEAP_ASSERT(pRoot->pEnd != NULL);
-    pState->max_node_size = pRoot->pStart->next_node->mem_size;
-    pState->min_node_size = pRoot->pStart->next_node->mem_size;
-    pState->remain_size = 0;
-    pState->free_node_num = 0;
-    MMHEAP_LOCK();
-    for (struct heap_node *pNode = pRoot->pStart->next_node; pNode->next_node != NULL; pNode = pNode->next_node) {
-        pState->remain_size += pNode->mem_size;
-        pState->free_node_num++;
-        if (pNode->mem_size > pState->max_node_size)
-            pState->max_node_size = pNode->mem_size;
-        if (pNode->mem_size < pState->min_node_size)
-            pState->min_node_size = pNode->mem_size;
-    }
-    MMHEAP_UNLOCK();
+void mmheap_get_state(struct heap_info *pRoot, struct heap_state *pState) {
+  MMHEAP_ASSERT(pRoot->pStart != NULL);
+  MMHEAP_ASSERT(pRoot->pEnd != NULL);
+  pState->max_node_size = pRoot->pStart->next_node->mem_size;
+  pState->min_node_size = pRoot->pStart->next_node->mem_size;
+  pState->remain_size   = 0;
+  pState->free_node_num = 0;
+  MMHEAP_LOCK();
+  for (struct heap_node *pNode = pRoot->pStart->next_node; pNode->next_node != NULL; pNode = pNode->next_node) {
+    pState->remain_size += pNode->mem_size;
+    pState->free_node_num++;
+    if (pNode->mem_size > pState->max_node_size)
+      pState->max_node_size = pNode->mem_size;
+    if (pNode->mem_size < pState->min_node_size)
+      pState->min_node_size = pNode->mem_size;
+  }
+  MMHEAP_UNLOCK();
 }
 /**
  * @brief mmheap_align_alloc
@@ -124,88 +109,86 @@ void mmheap_get_state(struct heap_info *pRoot, struct heap_state *pState)
  * @param want_size
  * @return void*
  */
-void *mmheap_align_alloc(struct heap_info *pRoot, size_t align_size, size_t want_size)
-{
-    void *pReturn = NULL;
-    struct heap_node *pPriv_Node, *pNow_Node;
+void *mmheap_align_alloc(struct heap_info *pRoot, size_t align_size, size_t want_size) {
+  void             *pReturn = NULL;
+  struct heap_node *pPriv_Node, *pNow_Node;
 
-    MMHEAP_ASSERT(pRoot->pStart != NULL);
-    MMHEAP_ASSERT(pRoot->pEnd != NULL);
+  MMHEAP_ASSERT(pRoot->pStart != NULL);
+  MMHEAP_ASSERT(pRoot->pEnd != NULL);
 
-    if (want_size == 0) {
-        return NULL;
-    }
+  if (want_size == 0) {
+    return NULL;
+  }
 
-    if ((want_size & MEM_MANAGE_ALLOCA_LABAL) != 0) {
-        MMHEAP_MALLOC_FAIL();
-        return NULL;
-    }
+  if ((want_size & MEM_MANAGE_ALLOCA_LABAL) != 0) {
+    MMHEAP_MALLOC_FAIL();
+    return NULL;
+  }
 
-    if (align_size & (align_size - 1)) {
-        MMHEAP_MALLOC_FAIL();
-        return NULL;
-    }
+  if (align_size & (align_size - 1)) {
+    MMHEAP_MALLOC_FAIL();
+    return NULL;
+  }
 
-    MMHEAP_LOCK();
-    if (want_size < MEM_MANAGE_MINUM_MEM_SIZE)
-        want_size = MEM_MANAGE_MINUM_MEM_SIZE;
-    if (align_size < MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT)
-        align_size = MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT;
+  MMHEAP_LOCK();
+  if (want_size < MEM_MANAGE_MINUM_MEM_SIZE)
+    want_size = MEM_MANAGE_MINUM_MEM_SIZE;
+  if (align_size < MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT)
+    align_size = MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT;
 
-    want_size = mmheap_align_up(want_size, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT);
+  want_size = mmheap_align_up(want_size, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT);
 
-    pPriv_Node = pRoot->pStart;
-    pNow_Node = pRoot->pStart->next_node;
+  pPriv_Node = pRoot->pStart;
+  pNow_Node  = pRoot->pStart->next_node;
 
-    while (pNow_Node->next_node != NULL) {
-        if (pNow_Node->mem_size >= want_size + MEM_MANAGE_MEM_STRUCT_SIZE) {
-            size_t use_align_size;
-            size_t new_size;
-            pReturn = (void *)mmheap_align_up((size_t)mmheap_addr_add(pNow_Node), align_size); /*Calculate the aligned address*/
-            use_align_size = (uint8_t *)pReturn - (uint8_t *)mmheap_addr_add(pNow_Node);       /*Calculate the memory consumed by the alignment*/
-            if (use_align_size != 0) {                                                         /*if Memory misalignment*/
-                if (use_align_size < MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE) { /*The unaligned value is too small*/
-                    pReturn = (void *)mmheap_align_up(
-                        (size_t)mmheap_addr_add(pNow_Node) + MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE, align_size);
-                    use_align_size = (uint8_t *)pReturn - (uint8_t *)mmheap_addr_add(pNow_Node);
-                }
-                if (use_align_size <= pNow_Node->mem_size) {
-                    new_size = pNow_Node->mem_size - use_align_size; /*Calculate the remaining memory size by removing the memory consumed by alignment*/
-                    if (new_size >= want_size) {                     /*Meet the conditions for distribution*/
-                        struct heap_node *pNew_Node = mmheap_addr_sub(pReturn);
-                        pNow_Node->mem_size -= new_size + MEM_MANAGE_MEM_STRUCT_SIZE; /*Split Node*/
-                        pNew_Node->mem_size = new_size;                               /*The new node is also not in the free chain and does not need to be discharged from the free chain*/
-                        pNew_Node->next_node = NULL;
-                        pNow_Node = pNew_Node;
-                        break;
-                    }
-                }
-            } else { /*Memory is directly aligned*/
-                pPriv_Node->next_node = pNow_Node->next_node;
-                pNow_Node->next_node = NULL;
-                break;
-            }
+  while (pNow_Node->next_node != NULL) {
+    if (pNow_Node->mem_size >= want_size + MEM_MANAGE_MEM_STRUCT_SIZE) {
+      size_t use_align_size;
+      size_t new_size;
+      pReturn        = (void *)mmheap_align_up((size_t)mmheap_addr_add(pNow_Node), align_size); /*Calculate the aligned address*/
+      use_align_size = (uint8_t *)pReturn - (uint8_t *)mmheap_addr_add(pNow_Node);              /*Calculate the memory consumed by the alignment*/
+      if (use_align_size != 0) {                                                                /*if Memory misalignment*/
+        if (use_align_size < MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE) {          /*The unaligned value is too small*/
+          pReturn        = (void *)mmheap_align_up((size_t)mmheap_addr_add(pNow_Node) + MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE, align_size);
+          use_align_size = (uint8_t *)pReturn - (uint8_t *)mmheap_addr_add(pNow_Node);
         }
-        pPriv_Node = pNow_Node;
-        pNow_Node = pNow_Node->next_node;
-    }
-
-    if (pNow_Node == pRoot->pEnd) {
-        MMHEAP_UNLOCK();
-        MMHEAP_MALLOC_FAIL();
-        return NULL;
+        if (use_align_size <= pNow_Node->mem_size) {
+          new_size = pNow_Node->mem_size - use_align_size; /*Calculate the remaining memory size by removing the memory consumed by alignment*/
+          if (new_size >= want_size) {                     /*Meet the conditions for distribution*/
+            struct heap_node *pNew_Node = mmheap_addr_sub(pReturn);
+            pNow_Node->mem_size -= new_size + MEM_MANAGE_MEM_STRUCT_SIZE; /*Split Node*/
+            pNew_Node->mem_size  = new_size;                              /*The new node is also not in the free chain and does not need to be discharged from the free chain*/
+            pNew_Node->next_node = NULL;
+            pNow_Node            = pNew_Node;
+            break;
+          }
+        }
+      } else { /*Memory is directly aligned*/
+        pPriv_Node->next_node = pNow_Node->next_node;
+        pNow_Node->next_node  = NULL;
+        break;
+      }
     }
+    pPriv_Node = pNow_Node;
+    pNow_Node  = pNow_Node->next_node;
+  }
 
-    if (pNow_Node->mem_size >= MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE + want_size) {           /*Node memory is still available*/
-        struct heap_node *pNew_Node = (struct heap_node *)((uint8_t *)mmheap_addr_add(pNow_Node) + want_size); /*Calculate the address of the node that will be moved into the free chain table*/
-        pNew_Node->mem_size = pNow_Node->mem_size - want_size - MEM_MANAGE_MEM_STRUCT_SIZE;
-        pNew_Node->next_node = NULL;
-        pNow_Node->mem_size = want_size;
-        mmheap_insert_node_to_freelist(pRoot, pNew_Node);
-    }
-    pNow_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
+  if (pNow_Node == pRoot->pEnd) {
     MMHEAP_UNLOCK();
-    return pReturn;
+    MMHEAP_MALLOC_FAIL();
+    return NULL;
+  }
+
+  if (pNow_Node->mem_size >= MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE + want_size) {         /*Node memory is still available*/
+    struct heap_node *pNew_Node = (struct heap_node *)((uint8_t *)mmheap_addr_add(pNow_Node) + want_size); /*Calculate the address of the node that will be moved into the free chain table*/
+    pNew_Node->mem_size         = pNow_Node->mem_size - want_size - MEM_MANAGE_MEM_STRUCT_SIZE;
+    pNew_Node->next_node        = NULL;
+    pNow_Node->mem_size         = want_size;
+    mmheap_insert_node_to_freelist(pRoot, pNew_Node);
+  }
+  pNow_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
+  MMHEAP_UNLOCK();
+  return pReturn;
 }
 /**
  * @brief mmheap_alloc
@@ -214,10 +197,7 @@ void *mmheap_align_alloc(struct heap_info *pRoot, size_t align_size, size_t want
  * @param want_size
  * @return void*
  */
-void *mmheap_alloc(struct heap_info *pRoot, size_t want_size)
-{
-    return mmheap_align_alloc(pRoot, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT, want_size);
-}
+void *mmheap_alloc(struct heap_info *pRoot, size_t want_size) { return mmheap_align_alloc(pRoot, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT, want_size); }
 /**
  * @brief mmheap_realloc
  *
@@ -226,81 +206,77 @@ void *mmheap_alloc(struct heap_info *pRoot, size_t want_size)
  * @param want_size
  * @return void*
  */
-void *mmheap_realloc(struct heap_info *pRoot, void *src_addr, size_t want_size)
-{
-    void *pReturn = NULL;
-    struct heap_node *pNext_Node, *pPriv_Node;
-    struct heap_node *pSrc_Node;
-    MMHEAP_ASSERT(pRoot->pStart != NULL);
-    MMHEAP_ASSERT(pRoot->pEnd != NULL);
-    if (src_addr == NULL) {
-        return mmheap_align_alloc(pRoot, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT, want_size);
-    }
-    if (want_size == 0) {
-        mmheap_free(pRoot, src_addr);
-        return NULL;
-    }
+void *mmheap_realloc(struct heap_info *pRoot, void *src_addr, size_t want_size) {
+  void             *pReturn = NULL;
+  struct heap_node *pNext_Node, *pPriv_Node;
+  struct heap_node *pSrc_Node;
+  MMHEAP_ASSERT(pRoot->pStart != NULL);
+  MMHEAP_ASSERT(pRoot->pEnd != NULL);
+  if (src_addr == NULL) {
+    return mmheap_align_alloc(pRoot, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT, want_size);
+  }
+  if (want_size == 0) {
+    mmheap_free(pRoot, src_addr);
+    return NULL;
+  }
 
-    MMHEAP_LOCK();
-    if ((want_size & MEM_MANAGE_ALLOCA_LABAL) != 0) {
-        MMHEAP_UNLOCK();
-        MMHEAP_MALLOC_FAIL();
-        return NULL;
-    }
+  MMHEAP_LOCK();
+  if ((want_size & MEM_MANAGE_ALLOCA_LABAL) != 0) {
+    MMHEAP_UNLOCK();
+    MMHEAP_MALLOC_FAIL();
+    return NULL;
+  }
 
-    pSrc_Node = mmheap_addr_sub(src_addr);
+  pSrc_Node = mmheap_addr_sub(src_addr);
 
-    if ((pSrc_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) == 0) {
-        MMHEAP_UNLOCK();
-        MMHEAP_ASSERT((pSrc_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) != 0);
-        MMHEAP_MALLOC_FAIL();
-        return NULL;
-    }
+  if ((pSrc_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) == 0) {
+    MMHEAP_UNLOCK();
+    MMHEAP_ASSERT((pSrc_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) != 0);
+    MMHEAP_MALLOC_FAIL();
+    return NULL;
+  }
 
-    pSrc_Node->mem_size &= ~MEM_MANAGE_ALLOCA_LABAL;
-    if (pSrc_Node->mem_size >= want_size) {
-        pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
-        pReturn = src_addr;
-        MMHEAP_UNLOCK();
-        return pReturn;
-    }
-    /*Start looking in the free list for blocks similar to this block*/
-    for (pPriv_Node = pRoot->pStart; pPriv_Node->next_node < pSrc_Node; pPriv_Node = pPriv_Node->next_node) {
-    }
-    pNext_Node = pPriv_Node->next_node;
+  pSrc_Node->mem_size &= ~MEM_MANAGE_ALLOCA_LABAL;
+  if (pSrc_Node->mem_size >= want_size) {
+    pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
+    pReturn = src_addr;
+    MMHEAP_UNLOCK();
+    return pReturn;
+  }
+  /*Start looking in the free list for blocks similar to this block*/
+  for (pPriv_Node = pRoot->pStart; pPriv_Node->next_node < pSrc_Node; pPriv_Node = pPriv_Node->next_node) {}
+  pNext_Node = pPriv_Node->next_node;
 
-    if (pNext_Node != pRoot->pEnd &&
-        ((uint8_t *)src_addr + pSrc_Node->mem_size == (uint8_t *)pNext_Node) &&
-        (pSrc_Node->mem_size + pNext_Node->mem_size + MEM_MANAGE_MEM_STRUCT_SIZE >= want_size)) {
-        /*Meet next node non-end, memory contiguous, enough memory left*/
-        pReturn = src_addr;
-        pPriv_Node->next_node = pNext_Node->next_node;
-        pSrc_Node->mem_size += MEM_MANAGE_MEM_STRUCT_SIZE + pNext_Node->mem_size;
-        want_size = mmheap_align_up(want_size, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT);
-        if (pSrc_Node->mem_size >= MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE + want_size) { /*Removing the remaining space allocated is enough to open new blocks*/
-            struct heap_node *pNew_Node = (struct heap_node *)((uint8_t *)mmheap_addr_add(pSrc_Node) + want_size);
-            pNew_Node->next_node = NULL;
-            pNew_Node->mem_size = pSrc_Node->mem_size - want_size - MEM_MANAGE_MEM_STRUCT_SIZE;
-            pSrc_Node->mem_size = want_size;
-            mmheap_insert_node_to_freelist(pRoot, pNew_Node);
-        }
-        pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
-        MMHEAP_UNLOCK();
-    } else {
-        MMHEAP_UNLOCK();
-        pReturn = mmheap_align_alloc(pRoot, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT, want_size);
-        if (pReturn == NULL) {
-            pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
-            MMHEAP_MALLOC_FAIL();
-            return NULL;
-        }
-        MMHEAP_LOCK();
-        memcpy(pReturn, src_addr, pSrc_Node->mem_size);
-        pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
-        MMHEAP_UNLOCK();
-        mmheap_free(pRoot, src_addr);
+  if (pNext_Node != pRoot->pEnd && ((uint8_t *)src_addr + pSrc_Node->mem_size == (uint8_t *)pNext_Node) && (pSrc_Node->mem_size + pNext_Node->mem_size + MEM_MANAGE_MEM_STRUCT_SIZE >= want_size)) {
+    /*Meet next node non-end, memory contiguous, enough memory left*/
+    pReturn               = src_addr;
+    pPriv_Node->next_node = pNext_Node->next_node;
+    pSrc_Node->mem_size += MEM_MANAGE_MEM_STRUCT_SIZE + pNext_Node->mem_size;
+    want_size = mmheap_align_up(want_size, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT);
+    if (pSrc_Node->mem_size >= MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE + want_size) { /*Removing the remaining space allocated is enough to open new blocks*/
+      struct heap_node *pNew_Node = (struct heap_node *)((uint8_t *)mmheap_addr_add(pSrc_Node) + want_size);
+      pNew_Node->next_node        = NULL;
+      pNew_Node->mem_size         = pSrc_Node->mem_size - want_size - MEM_MANAGE_MEM_STRUCT_SIZE;
+      pSrc_Node->mem_size         = want_size;
+      mmheap_insert_node_to_freelist(pRoot, pNew_Node);
     }
-    return pReturn;
+    pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
+    MMHEAP_UNLOCK();
+  } else {
+    MMHEAP_UNLOCK();
+    pReturn = mmheap_align_alloc(pRoot, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT, want_size);
+    if (pReturn == NULL) {
+      pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
+      MMHEAP_MALLOC_FAIL();
+      return NULL;
+    }
+    MMHEAP_LOCK();
+    memcpy(pReturn, src_addr, pSrc_Node->mem_size);
+    pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
+    MMHEAP_UNLOCK();
+    mmheap_free(pRoot, src_addr);
+  }
+  return pReturn;
 }
 /**
  * @brief
@@ -310,17 +286,16 @@ void *mmheap_realloc(struct heap_info *pRoot, void *src_addr, size_t want_size)
  * @param size
  * @return void*
  */
-void *mmheap_calloc(struct heap_info *pRoot, size_t num, size_t size)
-{
-    void *pReturn = NULL;
+void *mmheap_calloc(struct heap_info *pRoot, size_t num, size_t size) {
+  void *pReturn = NULL;
 
-    pReturn = (void *)mmheap_alloc(pRoot, size * num);
+  pReturn = (void *)mmheap_alloc(pRoot, size * num);
 
-    if (pReturn) {
-        memset(pReturn, 0, num * size);
-    }
+  if (pReturn) {
+    memset(pReturn, 0, num * size);
+  }
 
-    return pReturn;
+  return pReturn;
 }
 /**
  * @brief mmheap_free
@@ -328,32 +303,31 @@ void *mmheap_calloc(struct heap_info *pRoot, size_t num, size_t size)
  * @param pRoot
  * @param addr
  */
-void mmheap_free(struct heap_info *pRoot, void *addr)
-{
-    struct heap_node *pFree_Node;
-    MMHEAP_ASSERT(pRoot->pStart != NULL);
-    MMHEAP_ASSERT(pRoot->pEnd != NULL);
-    MMHEAP_LOCK();
-    if (addr == NULL) {
-        MMHEAP_UNLOCK();
-        return;
-    }
-    pFree_Node = mmheap_addr_sub(addr);
+void mmheap_free(struct heap_info *pRoot, void *addr) {
+  struct heap_node *pFree_Node;
+  MMHEAP_ASSERT(pRoot->pStart != NULL);
+  MMHEAP_ASSERT(pRoot->pEnd != NULL);
+  MMHEAP_LOCK();
+  if (addr == NULL) {
+    MMHEAP_UNLOCK();
+    return;
+  }
+  pFree_Node = mmheap_addr_sub(addr);
 
-    if ((pFree_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) == 0) {
-        MMHEAP_UNLOCK();
-        MMHEAP_ASSERT((pFree_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) != 0);
-        return;
-    }
+  if ((pFree_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) == 0) {
+    MMHEAP_UNLOCK();
+    MMHEAP_ASSERT((pFree_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) != 0);
+    return;
+  }
 
-    if (pFree_Node->next_node != NULL) {
-        MMHEAP_UNLOCK();
-        MMHEAP_ASSERT(pFree_Node->next_node == NULL);
-        return;
-    }
-    pFree_Node->mem_size &= ~MEM_MANAGE_ALLOCA_LABAL;
-    mmheap_insert_node_to_freelist(pRoot, pFree_Node);
+  if (pFree_Node->next_node != NULL) {
     MMHEAP_UNLOCK();
+    MMHEAP_ASSERT(pFree_Node->next_node == NULL);
+    return;
+  }
+  pFree_Node->mem_size &= ~MEM_MANAGE_ALLOCA_LABAL;
+  mmheap_insert_node_to_freelist(pRoot, pFree_Node);
+  MMHEAP_UNLOCK();
 }
 /**
  * @brief mmheap_init
@@ -361,61 +335,60 @@ void mmheap_free(struct heap_info *pRoot, void *addr)
  * @param pRoot
  * @param pRegion
  */
-void mmheap_init(struct heap_info *pRoot, const struct heap_region *pRegion)
-{
-    struct heap_node *align_addr;
-    size_t align_size;
-    struct heap_node *pPriv_node = NULL;
+void mmheap_init(struct heap_info *pRoot, const struct heap_region *pRegion) {
+  struct heap_node *align_addr;
+  size_t            align_size;
+  struct heap_node *pPriv_node = NULL;
 
-    pRoot->total_size = 0;
-    pRoot->pEnd = NULL;
-    pRoot->pStart = NULL;
+  pRoot->total_size = 0;
+  pRoot->pEnd       = NULL;
+  pRoot->pStart     = NULL;
 
-    for (; pRegion->addr != NULL; pRegion++) {
-        align_addr = (struct heap_node *)mmheap_align_up((size_t)pRegion->addr, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT); /*Calculate the aligned address*/
-        if ((uint8_t *)align_addr > pRegion->mem_size + (uint8_t *)pRegion->addr)                                   /*Alignment consumes more memory than the memory area*/
-            continue;
-        align_size = pRegion->mem_size - ((uint8_t *)align_addr - (uint8_t *)pRegion->addr); /*Calculate the size of memory left after alignment*/
-        if (align_size < MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE)             /*if Aligning the remaining memory is too small*/
-            continue;
-        align_size -= MEM_MANAGE_MEM_STRUCT_SIZE; /*Find the size of the memory block after removing the table header*/
-        align_addr->mem_size = align_size;
-        align_addr->next_node = NULL;
-        if (pRoot->pStart == NULL) {
-            pRoot->pStart = align_addr;                                                                   /*set current addr for start*/
-            if (align_size >= MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE) {                   /*If the remaining blocks are large enough*/
-                align_size -= MEM_MANAGE_MEM_STRUCT_SIZE;                                                 /*Remove the next block of table headers remaining memory size*/
-                align_addr = (struct heap_node *)((uint8_t *)pRoot->pStart + MEM_MANAGE_MEM_STRUCT_SIZE); //the next block addr
-                align_addr->mem_size = align_size;
-                align_addr->next_node = NULL;
-                pRoot->pStart->mem_size = 0;
-                pRoot->pStart->next_node = align_addr;
-                pRoot->total_size = align_addr->mem_size;
-            } else { /*The memory is too small, and the address of the current memory block is recorded as start*/
-                pRoot->total_size = 0;
-                pRoot->pStart->mem_size = 0;
-            }
-        } else {
-            pPriv_node->next_node = align_addr;
-            pRoot->total_size += align_size;
-        }
-        pPriv_node = align_addr;
-    }
-    //At this point, pPriv_node is the last block, then place the end of the table at the end of the block, find the address to place the end block, end block is only convenient for traversal, so as small as possible, assigned to MEM_MANAGE_MEM_STRUCT_SIZE
-    align_addr = (struct heap_node *)mmheap_align_down(
-        (size_t)mmheap_addr_add(pPriv_node) + pPriv_node->mem_size - MEM_MANAGE_MEM_STRUCT_SIZE, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT);
-    align_size = (uint8_t *)align_addr - (uint8_t *)mmheap_addr_add(pPriv_node); /*Find the remaining size of the previous block after the end block is allocated*/
-    if (align_size >= MEM_MANAGE_MINUM_MEM_SIZE) {
-        pRoot->total_size -= pPriv_node->mem_size - align_size; /*Removing memory consumed by allocating end blocks*/
-        pRoot->pEnd = align_addr;                               /*Update the address at the end of the list*/
-        pPriv_node->next_node = align_addr;
-        pPriv_node->mem_size = align_size;
-        align_addr->next_node = NULL;
-        align_addr->mem_size = 0; /*The end block is not involved in memory allocation, so a direct 0 is sufficient*/
-    } else {                      /*The last block is too small, directly as the end block*/
-        pRoot->pEnd = pPriv_node;
-        pRoot->total_size -= pPriv_node->mem_size;
+  for (; pRegion->addr != NULL; pRegion++) {
+    align_addr = (struct heap_node *)mmheap_align_up((size_t)pRegion->addr, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT); /*Calculate the aligned address*/
+    if ((uint8_t *)align_addr > pRegion->mem_size + (uint8_t *)pRegion->addr)                                   /*Alignment consumes more memory than the memory area*/
+      continue;
+    align_size = pRegion->mem_size - ((uint8_t *)align_addr - (uint8_t *)pRegion->addr); /*Calculate the size of memory left after alignment*/
+    if (align_size < MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE)             /*if Aligning the remaining memory is too small*/
+      continue;
+    align_size -= MEM_MANAGE_MEM_STRUCT_SIZE; /*Find the size of the memory block after removing the table header*/
+    align_addr->mem_size  = align_size;
+    align_addr->next_node = NULL;
+    if (pRoot->pStart == NULL) {
+      pRoot->pStart = align_addr;                                                                               /*set current addr for start*/
+      if (align_size >= MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE) {                               /*If the remaining blocks are large enough*/
+        align_size -= MEM_MANAGE_MEM_STRUCT_SIZE;                                                               /*Remove the next block of table headers remaining memory size*/
+        align_addr               = (struct heap_node *)((uint8_t *)pRoot->pStart + MEM_MANAGE_MEM_STRUCT_SIZE); // the next block addr
+        align_addr->mem_size     = align_size;
+        align_addr->next_node    = NULL;
+        pRoot->pStart->mem_size  = 0;
+        pRoot->pStart->next_node = align_addr;
+        pRoot->total_size        = align_addr->mem_size;
+      } else { /*The memory is too small, and the address of the current memory block is recorded as start*/
+        pRoot->total_size       = 0;
+        pRoot->pStart->mem_size = 0;
+      }
+    } else {
+      pPriv_node->next_node = align_addr;
+      pRoot->total_size += align_size;
     }
-    MMHEAP_ASSERT(pRoot->pStart != NULL);
-    MMHEAP_ASSERT(pRoot->pEnd != NULL);
+    pPriv_node = align_addr;
+  }
+  // At this point, pPriv_node is the last block, then place the end of the table at the end of the block, find the address to place the end block, end block is only convenient for traversal, so as
+  // small as possible, assigned to MEM_MANAGE_MEM_STRUCT_SIZE
+  align_addr = (struct heap_node *)mmheap_align_down((size_t)mmheap_addr_add(pPriv_node) + pPriv_node->mem_size - MEM_MANAGE_MEM_STRUCT_SIZE, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT);
+  align_size = (uint8_t *)align_addr - (uint8_t *)mmheap_addr_add(pPriv_node); /*Find the remaining size of the previous block after the end block is allocated*/
+  if (align_size >= MEM_MANAGE_MINUM_MEM_SIZE) {
+    pRoot->total_size -= pPriv_node->mem_size - align_size; /*Removing memory consumed by allocating end blocks*/
+    pRoot->pEnd           = align_addr;                     /*Update the address at the end of the list*/
+    pPriv_node->next_node = align_addr;
+    pPriv_node->mem_size  = align_size;
+    align_addr->next_node = NULL;
+    align_addr->mem_size  = 0; /*The end block is not involved in memory allocation, so a direct 0 is sufficient*/
+  } else {                     /*The last block is too small, directly as the end block*/
+    pRoot->pEnd = pPriv_node;
+    pRoot->total_size -= pPriv_node->mem_size;
+  }
+  MMHEAP_ASSERT(pRoot->pStart != NULL);
+  MMHEAP_ASSERT(pRoot->pEnd != NULL);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c
index 65ef20a26d..929fb516c9 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c
@@ -20,12 +20,12 @@
  * under the License.
  *
  */
-#include "bl702_common.h"
 #include "bflb_platform.h"
+#include "bl702_common.h"
 #include "risc-v/Core/Include/clic.h"
 #include "risc-v/Core/Include/riscv_encoding.h"
 
-pFunc __Interrupt_Handlers[IRQn_LAST] = { 0 };
+pFunc __Interrupt_Handlers[IRQn_LAST] = {0};
 
 void Interrupt_Handler_Stub(void);
 
@@ -91,17 +91,18 @@ void MAC_PORT_TRG_IRQHandler_Wrapper(void) __attribute__((weak, alias("Interrupt
 void WIFI_IPC_PUBLIC_IRQHandler_Wrapper(void) __attribute__((weak, alias("Interrupt_Handler_Stub")));
 
 const pFunc __Vectors[] __attribute__((section(".init"), aligned(64))) = {
-    0,                                   /*         */
-    0,                                   /*         */
-    0,                                   /*         */
-    clic_msip_handler_Wrapper,           /* 3       */
-    0,                                   /*         */
-    0,                                   /*         */
-    0,                                   /*         */
-    clic_mtimer_handler_Wrapper,         /* 7       */
-    (pFunc)0x00000001,                   /*         */
-    0,                                   /*         */
-    (pFunc)0x00000102, /*         */     //disable log as default
+    0,                           /*         */
+    0,                           /*         */
+    0,                           /*         */
+    clic_msip_handler_Wrapper,   /* 3       */
+    0,                           /*         */
+    0,                           /*         */
+    0,                           /*         */
+    clic_mtimer_handler_Wrapper, /* 7       */
+    (pFunc)0x00000001,           /*         */
+    0,                           /*         */
+    (pFunc)0x00000102,
+    /*         */                        // disable log as default
     clic_mext_handler_Wrapper,           /* 11      */
     clic_csoft_handler_Wrapper,          /* 12      */
     0,                                   /*         */
@@ -180,204 +181,162 @@ void vAssertCalled(void) {
   epc = get_pc();
   MSG("mepc:0x%08x\r\n", (uint32_t)epc);
 
-//   PWM_Channel_Disable(PWM_Channel);
-//   gpio_set_mode(PWM_Out_Pin, GPIO_INPUT_PD_MODE);
+  //   PWM_Channel_Disable(PWM_Channel);
+  //   gpio_set_mode(PWM_Out_Pin, GPIO_INPUT_PD_MODE);
 
   while (1)
     ;
 }
 
+void Trap_Handler(void) {
+  unsigned long cause;
+  unsigned long epc;
+  unsigned long tval;
+  uint8_t       isecall = 0;
 
-void Trap_Handler(void)
-{
-    unsigned long cause;
-    unsigned long epc;
-    unsigned long tval;
-    uint8_t isecall = 0;
-
-    MSG("Trap_Handler\r\n");
-
-    cause = read_csr(mcause);
-    MSG("mcause=%08x\r\n", (uint32_t)cause);
-    epc = get_pc();
-    MSG("mepc:%08x\r\n", (uint32_t)epc);
-    tval = read_csr(mtval);
-    MSG("mtval:%08x\r\n", (uint32_t)tval);
-
-    cause = (cause & 0x3ff);
-
-    switch (cause) {
-        case 1:
-            MSG("Instruction access fault\r\n");
-            break;
-
-        case 2:
-            MSG("Illegal instruction\r\n");
-            break;
-
-        case 3:
-            MSG("Breakpoint\r\n");
-            break;
-
-        case 4:
-            MSG("Load address misaligned\r\n");
-            break;
-
-        case 5:
-            MSG("Load access fault\r\n");
-            break;
-
-        case 6:
-            MSG("Store/AMO address misaligned\r\n");
-            break;
-
-        case 7:
-            MSG("Store/AMO access fault\r\n");
-            break;
-
-        case 8:
-            MSG("Environment call from U-mode\r\n");
-            epc += 4;
-            write_csr(mepc, epc);
-            break;
-
-        case 11:
-            MSG("Environment call from M-mode\r\n");
-            epc += 4;
-            write_csr(mepc, epc);
-            isecall = 1;
-            break;
-
-        default:
-            MSG("Cause num=%d\r\n", (uint32_t)cause);
-            epc += 4;
-            write_csr(mepc, epc);
-            break;
-    }
+  MSG("Trap_Handler\r\n");
 
-    if (!isecall) {
-        while (1)
-            ;
-    }
+  cause = read_csr(mcause);
+  MSG("mcause=%08x\r\n", (uint32_t)cause);
+  epc = get_pc();
+  MSG("mepc:%08x\r\n", (uint32_t)epc);
+  tval = read_csr(mtval);
+  MSG("mtval:%08x\r\n", (uint32_t)tval);
+
+  cause = (cause & 0x3ff);
+
+  switch (cause) {
+  case 1:
+    MSG("Instruction access fault\r\n");
+    break;
+
+  case 2:
+    MSG("Illegal instruction\r\n");
+    break;
+
+  case 3:
+    MSG("Breakpoint\r\n");
+    break;
+
+  case 4:
+    MSG("Load address misaligned\r\n");
+    break;
+
+  case 5:
+    MSG("Load access fault\r\n");
+    break;
+
+  case 6:
+    MSG("Store/AMO address misaligned\r\n");
+    break;
+
+  case 7:
+    MSG("Store/AMO access fault\r\n");
+    break;
+
+  case 8:
+    MSG("Environment call from U-mode\r\n");
+    epc += 4;
+    write_csr(mepc, epc);
+    break;
+
+  case 11:
+    MSG("Environment call from M-mode\r\n");
+    epc += 4;
+    write_csr(mepc, epc);
+    isecall = 1;
+    break;
+
+  default:
+    MSG("Cause num=%d\r\n", (uint32_t)cause);
+    epc += 4;
+    write_csr(mepc, epc);
+    break;
+  }
+
+  if (!isecall) {
+    while (1)
+      ;
+  }
 }
 
-void Interrupt_Handler(void)
-{
-    pFunc interruptFun;
-    uint32_t num = 0;
-    volatile uint32_t ulMEPC = 0UL, ulMCAUSE = 0UL;
-
-    /* Store a few register values that might be useful when determining why this
-    function was called. */
-    __asm volatile("csrr %0, mepc"
-                   : "=r"(ulMEPC));
-    __asm volatile("csrr %0, mcause"
-                   : "=r"(ulMCAUSE));
-
-    if ((ulMCAUSE & 0x80000000) == 0) {
-        /*Exception*/
-        MSG("Exception should not be here\r\n");
-    } else {
-        num = ulMCAUSE & 0x3FF;
+void Interrupt_Handler(void) {
+  pFunc             interruptFun;
+  uint32_t          num    = 0;
+  volatile uint32_t ulMEPC = 0UL, ulMCAUSE = 0UL;
 
-        if (num < IRQn_LAST) {
-            interruptFun = __Interrupt_Handlers[num];
+  /* Store a few register values that might be useful when determining why this
+  function was called. */
+  __asm volatile("csrr %0, mepc" : "=r"(ulMEPC));
+  __asm volatile("csrr %0, mcause" : "=r"(ulMCAUSE));
 
-            if (NULL != interruptFun) {
-                interruptFun();
-            } else {
-                MSG("Interrupt num:%d IRQHandler not installed\r\n", (unsigned int)num);
+  if ((ulMCAUSE & 0x80000000) == 0) {
+    /*Exception*/
+    MSG("Exception should not be here\r\n");
+  } else {
+    num = ulMCAUSE & 0x3FF;
 
-                if (num >= IRQ_NUM_BASE) {
-                    MSG("Peripheral Interrupt num:%d \r\n", (unsigned int)num - IRQ_NUM_BASE);
-                }
+    if (num < IRQn_LAST) {
+      interruptFun = __Interrupt_Handlers[num];
 
-                while (1)
-                    ;
-            }
-        } else {
-            MSG("Unexpected interrupt num:%d\r\n", (unsigned int)num);
+      if (NULL != interruptFun) {
+        interruptFun();
+      } else {
+        MSG("Interrupt num:%d IRQHandler not installed\r\n", (unsigned int)num);
+
+        if (num >= IRQ_NUM_BASE) {
+          MSG("Peripheral Interrupt num:%d \r\n", (unsigned int)num - IRQ_NUM_BASE);
         }
+
+        while (1)
+          ;
+      }
+    } else {
+      MSG("Unexpected interrupt num:%d\r\n", (unsigned int)num);
     }
+  }
 }
 
-void handle_trap(void)
-{
+void handle_trap(void) {
 #define MCAUSE_INT_MASK  0x80000000 // [31]=1 interrupt, else exception
 #define MCAUSE_CODE_MASK 0x7FFFFFFF // low bits show code
 
-    unsigned long mcause_value = read_csr(mcause);
-    if (mcause_value & MCAUSE_INT_MASK) {
-        // Branch to interrupt handler here
-        Interrupt_Handler();
-    } else {
-        // Branch to exception handle
-        Trap_Handler();
-    }
-}
-
-void __IRQ_ALIGN64 Trap_Handler_Stub(void)
-{
+  unsigned long mcause_value = read_csr(mcause);
+  if (mcause_value & MCAUSE_INT_MASK) {
+    // Branch to interrupt handler here
+    Interrupt_Handler();
+  } else {
+    // Branch to exception handle
     Trap_Handler();
+  }
 }
 
-void __IRQ Interrupt_Handler_Stub(void)
-{
-    Interrupt_Handler();
-}
+void __IRQ_ALIGN64 Trap_Handler_Stub(void) { Trap_Handler(); }
 
-void FreeRTOS_Interrupt_Handler(void)
-{
-    Interrupt_Handler();
-}
+void __IRQ Interrupt_Handler_Stub(void) { Interrupt_Handler(); }
 
-void Interrupt_Handler_Register(IRQn_Type irq, pFunc interruptFun)
-{
-    if (irq < IRQn_LAST) {
-        __Interrupt_Handlers[irq] = interruptFun;
-    }
-}
+void FreeRTOS_Interrupt_Handler(void) { Interrupt_Handler(); }
 
-void System_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority)
-{
+void Interrupt_Handler_Register(IRQn_Type irq, pFunc interruptFun) {
+  if (irq < IRQn_LAST) {
+    __Interrupt_Handlers[irq] = interruptFun;
+  }
 }
 
-void clic_enable_interrupt(uint32_t source)
-{
-    *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIE + source) = 1;
-}
+void System_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority) {}
 
-void clic_disable_interrupt(uint32_t source)
-{
-    *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIE + source) = 0;
-}
+void clic_enable_interrupt(uint32_t source) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIE + source) = 1; }
 
-void clic_clear_pending(uint32_t source)
-{
-    *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIP + source) = 0;
-}
+void clic_disable_interrupt(uint32_t source) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIE + source) = 0; }
 
-void clic_set_pending(uint32_t source)
-{
-    *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIP + source) = 1;
-}
+void clic_clear_pending(uint32_t source) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIP + source) = 0; }
 
-void clic_set_intcfg(uint32_t source, uint32_t intcfg)
-{
-    *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTCFG + source) = intcfg;
-}
+void clic_set_pending(uint32_t source) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIP + source) = 1; }
 
-uint8_t clic_get_intcfg(uint32_t source)
-{
-    return *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTCFG + source);
-}
+void clic_set_intcfg(uint32_t source, uint32_t intcfg) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTCFG + source) = intcfg; }
 
-void clic_set_cliccfg(uint32_t cfg)
-{
-    *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_CFG) = cfg;
-}
+uint8_t clic_get_intcfg(uint32_t source) { return *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTCFG + source); }
+
+void clic_set_cliccfg(uint32_t cfg) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_CFG) = cfg; }
 
-uint8_t clic_get_cliccfg(void)
-{
-    return *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_CFG);
-}
\ No newline at end of file
+uint8_t clic_get_cliccfg(void) { return *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_CFG); }
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_acomp.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_acomp.c
index 666aa18965..190ccbaa94 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_acomp.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_acomp.c
@@ -1,38 +1,38 @@
 /**
-  ******************************************************************************
-  * @file    bl702_acomp.c
-  * @version V1.0
-  * @date
-  * @brief   This file is the standard driver c file
-  ******************************************************************************
-  * @attention
-  *
-  * 

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_acomp.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_acomp.h" @@ -85,114 +85,111 @@ */ /****************************************************************************/ /** - * @brief Analog compare init - * - * @param acompNo: Compare ID - * @param cfg: Compare consideration pointer - * - * @return None - * -*******************************************************************************/ -void AON_ACOMP_Init(AON_ACOMP_ID_Type acompNo, AON_ACOMP_CFG_Type *cfg) -{ - uint32_t tmpVal = 0; - - /* Check the parameters */ - CHECK_PARAM(IS_AON_ACOMP_ID_TYPE(acompNo)); - - if (acompNo == AON_ACOMP0_ID) { - /* Disable ACOMP first */ - tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP0_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_ACOMP0_EN); - tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP0_CTRL, tmpVal); - - /* Set ACOMP config */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_MUXEN, cfg->muxEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_POS_SEL, cfg->posChanSel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_NEG_SEL, cfg->negChanSel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_LEVEL_SEL, cfg->levelFactor); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_BIAS_PROG, cfg->biasProg); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_HYST_SELP, cfg->hysteresisPosVolt); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_HYST_SELN, cfg->hysteresisNegVolt); - - tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP0_CTRL, tmpVal); - - } else { - /* Disable ACOMP first */ - tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP1_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_ACOMP1_EN); - tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP1_CTRL, tmpVal); - - /* Set ACOMP config */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_MUXEN, cfg->muxEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_POS_SEL, cfg->posChanSel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_NEG_SEL, cfg->negChanSel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_LEVEL_SEL, cfg->levelFactor); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_BIAS_PROG, cfg->biasProg); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_HYST_SELP, cfg->hysteresisPosVolt); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_HYST_SELN, cfg->hysteresisNegVolt); - - tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP1_CTRL, tmpVal); - } + * @brief Analog compare init + * + * @param acompNo: Compare ID + * @param cfg: Compare consideration pointer + * + * @return None + * + *******************************************************************************/ +void AON_ACOMP_Init(AON_ACOMP_ID_Type acompNo, AON_ACOMP_CFG_Type *cfg) { + uint32_t tmpVal = 0; + + /* Check the parameters */ + CHECK_PARAM(IS_AON_ACOMP_ID_TYPE(acompNo)); + + if (acompNo == AON_ACOMP0_ID) { + /* Disable ACOMP first */ + tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP0_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_ACOMP0_EN); + tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP0_CTRL, tmpVal); + + /* Set ACOMP config */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_MUXEN, cfg->muxEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_POS_SEL, cfg->posChanSel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_NEG_SEL, cfg->negChanSel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_LEVEL_SEL, cfg->levelFactor); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_BIAS_PROG, cfg->biasProg); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_HYST_SELP, cfg->hysteresisPosVolt); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_HYST_SELN, cfg->hysteresisNegVolt); + + tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP0_CTRL, tmpVal); + + } else { + /* Disable ACOMP first */ + tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP1_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_ACOMP1_EN); + tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP1_CTRL, tmpVal); + + /* Set ACOMP config */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_MUXEN, cfg->muxEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_POS_SEL, cfg->posChanSel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_NEG_SEL, cfg->negChanSel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_LEVEL_SEL, cfg->levelFactor); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_BIAS_PROG, cfg->biasProg); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_HYST_SELP, cfg->hysteresisPosVolt); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_HYST_SELN, cfg->hysteresisNegVolt); + + tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP1_CTRL, tmpVal); + } } /****************************************************************************/ /** - * @brief Analog compare enable - * - * @param acompNo: Compare ID - * - * @return None - * -*******************************************************************************/ -void AON_ACOMP_Enable(AON_ACOMP_ID_Type acompNo) -{ - uint32_t tmpVal = 0; - - /* Check the parameters */ - CHECK_PARAM(IS_AON_ACOMP_ID_TYPE(acompNo)); - - if (acompNo == AON_ACOMP0_ID) { - tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP0_CTRL); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_ACOMP0_EN); - tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP0_CTRL, tmpVal); - } else { - tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP1_CTRL); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_ACOMP1_EN); - tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP1_CTRL, tmpVal); - } + * @brief Analog compare enable + * + * @param acompNo: Compare ID + * + * @return None + * + *******************************************************************************/ +void AON_ACOMP_Enable(AON_ACOMP_ID_Type acompNo) { + uint32_t tmpVal = 0; + + /* Check the parameters */ + CHECK_PARAM(IS_AON_ACOMP_ID_TYPE(acompNo)); + + if (acompNo == AON_ACOMP0_ID) { + tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP0_CTRL); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_ACOMP0_EN); + tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP0_CTRL, tmpVal); + } else { + tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP1_CTRL); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_ACOMP1_EN); + tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP1_CTRL, tmpVal); + } } /****************************************************************************/ /** - * @brief Analog compare enable - * - * @param acompNo: Compare ID - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type AON_ACOMP_Get_Result(AON_ACOMP_ID_Type acompNo) -{ - uint32_t tmpVal = 0; - - /* Check the parameters */ - CHECK_PARAM(IS_AON_ACOMP_ID_TYPE(acompNo)); - - tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP_CTRL); - - /* Disable ACOMP first */ - if (acompNo == AON_ACOMP0_ID) { - if (BL_IS_REG_BIT_SET(tmpVal, AON_ACOMP0_OUT_RAW)) { - return SET; - } else { - return RESET; - } + * @brief Analog compare enable + * + * @param acompNo: Compare ID + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type AON_ACOMP_Get_Result(AON_ACOMP_ID_Type acompNo) { + uint32_t tmpVal = 0; + + /* Check the parameters */ + CHECK_PARAM(IS_AON_ACOMP_ID_TYPE(acompNo)); + + tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP_CTRL); + + /* Disable ACOMP first */ + if (acompNo == AON_ACOMP0_ID) { + if (BL_IS_REG_BIT_SET(tmpVal, AON_ACOMP0_OUT_RAW)) { + return SET; + } else { + return RESET; + } + } else { + if (BL_IS_REG_BIT_SET(tmpVal, AON_ACOMP1_OUT_RAW)) { + return SET; } else { - if (BL_IS_REG_BIT_SET(tmpVal, AON_ACOMP1_OUT_RAW)) { - return SET; - } else { - return RESET; - } + return RESET; } + } } /*@} end of group ACOMP_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_aon.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_aon.c index d166455860..477cad311e 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_aon.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_aon.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_aon.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_aon.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_aon.h" @@ -48,16 +48,16 @@ * @{ */ #define AON_CLK_SET_DUMMY_WAIT \ - { \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - } + { \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + } /*@} end of group AON_Private_Macros */ @@ -96,483 +96,463 @@ */ /****************************************************************************/ /** - * @brief Power on MXX band gap - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Power on MXX band gap + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER -__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_On_MBG(void) -{ - uint32_t tmpVal = 0; +__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_On_MBG(void) { + uint32_t tmpVal = 0; - /* Power up RF for PLL to work */ - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_MBG_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + /* Power up RF for PLL to work */ + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_MBG_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - BL702_Delay_US(55); + BL702_Delay_US(55); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Power off MXX band gap - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Power off MXX band gap + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER -__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_Off_MBG(void) -{ - uint32_t tmpVal = 0; +__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_Off_MBG(void) { + uint32_t tmpVal = 0; - /* Power OFF */ - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_MBG_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + /* Power OFF */ + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_MBG_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Power on XTAL - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Power on XTAL + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER -__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_On_XTAL(void) -{ - uint32_t tmpVal = 0; - uint32_t timeOut = 0; - - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_XTAL_AON); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_XTAL_BUF_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - - /* Polling for ready */ - do { - BL702_Delay_US(10); - timeOut++; - tmpVal = BL_RD_REG(AON_BASE, AON_TSEN); - } while (!BL_IS_REG_BIT_SET(tmpVal, AON_XTAL_RDY) && timeOut < 120); - - if (timeOut >= 120) { - return TIMEOUT; - } - - return SUCCESS; +__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_On_XTAL(void) { + uint32_t tmpVal = 0; + uint32_t timeOut = 0; + + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_XTAL_AON); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_XTAL_BUF_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + + /* Polling for ready */ + do { + BL702_Delay_US(10); + timeOut++; + tmpVal = BL_RD_REG(AON_BASE, AON_TSEN); + } while (!BL_IS_REG_BIT_SET(tmpVal, AON_XTAL_RDY) && timeOut < 120); + + if (timeOut >= 120) { + return TIMEOUT; + } + + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Set XTAL cap code - * - * @param capIn: Cap code in - * @param capOut: Cap code out - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Set XTAL cap code + * + * @param capIn: Cap code in + * @param capOut: Cap code out + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER -__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Set_Xtal_CapCode(uint8_t capIn, uint8_t capOut) -{ - uint32_t tmpVal = 0; +__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Set_Xtal_CapCode(uint8_t capIn, uint8_t capOut) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_CAPCODE_IN_AON, capIn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_CAPCODE_OUT_AON, capOut); - BL_WR_REG(AON_BASE, AON_XTAL_CFG, tmpVal); + tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_CAPCODE_IN_AON, capIn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_CAPCODE_OUT_AON, capOut); + BL_WR_REG(AON_BASE, AON_XTAL_CFG, tmpVal); - BL702_Delay_US(100); + BL702_Delay_US(100); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Get XTAL cap code - * - * @param None - * - * @return Cap code - * -*******************************************************************************/ -uint8_t ATTR_CLOCK_SECTION AON_Get_Xtal_CapCode(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); - - return BL_GET_REG_BITS_VAL(tmpVal, AON_XTAL_CAPCODE_IN_AON); + * @brief Get XTAL cap code + * + * @param None + * + * @return Cap code + * + *******************************************************************************/ +uint8_t ATTR_CLOCK_SECTION AON_Get_Xtal_CapCode(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); + + return BL_GET_REG_BITS_VAL(tmpVal, AON_XTAL_CAPCODE_IN_AON); } /****************************************************************************/ /** - * @brief Set XTAL cap code - * - * @param extra: cap cpde extra aon - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION AON_Set_Xtal_CapCode_Extra(uint8_t extra) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); - if (extra) { - tmpVal = BL_SET_REG_BIT(tmpVal, AON_XTAL_CAPCODE_EXTRA_AON); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_XTAL_CAPCODE_EXTRA_AON); - } - BL_WR_REG(AON_BASE, AON_XTAL_CFG, tmpVal); - - return SUCCESS; + * @brief Set XTAL cap code + * + * @param extra: cap cpde extra aon + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION AON_Set_Xtal_CapCode_Extra(uint8_t extra) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); + if (extra) { + tmpVal = BL_SET_REG_BIT(tmpVal, AON_XTAL_CAPCODE_EXTRA_AON); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_XTAL_CAPCODE_EXTRA_AON); + } + BL_WR_REG(AON_BASE, AON_XTAL_CFG, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power off XTAL - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Power off XTAL + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER -__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_Off_XTAL(void) -{ - uint32_t tmpVal = 0; +__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_Off_XTAL(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_XTAL_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_XTAL_BUF_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_XTAL_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_XTAL_BUF_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Power on bandgap system - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_On_BG(void) -{ - uint32_t tmpVal = 0; - - /* power up RF for PLL to work */ - tmpVal = BL_RD_REG(AON_BASE, AON_BG_SYS_TOP); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_BG_SYS_AON); - BL_WR_REG(AON_BASE, AON_BG_SYS_TOP, tmpVal); - - BL702_Delay_US(55); - - return SUCCESS; + * @brief Power on bandgap system + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_On_BG(void) { + uint32_t tmpVal = 0; + + /* power up RF for PLL to work */ + tmpVal = BL_RD_REG(AON_BASE, AON_BG_SYS_TOP); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_BG_SYS_AON); + BL_WR_REG(AON_BASE, AON_BG_SYS_TOP, tmpVal); + + BL702_Delay_US(55); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power off bandgap system - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_BG(void) -{ - uint32_t tmpVal = 0; - - /* power up RF for PLL to work */ - tmpVal = BL_RD_REG(AON_BASE, AON_BG_SYS_TOP); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_BG_SYS_AON); - BL_WR_REG(AON_BASE, AON_BG_SYS_TOP, tmpVal); - - BL702_Delay_US(55); - - return SUCCESS; + * @brief Power off bandgap system + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_BG(void) { + uint32_t tmpVal = 0; + + /* power up RF for PLL to work */ + tmpVal = BL_RD_REG(AON_BASE, AON_BG_SYS_TOP); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_BG_SYS_AON); + BL_WR_REG(AON_BASE, AON_BG_SYS_TOP, tmpVal); + + BL702_Delay_US(55); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power on LDO11 - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_On_LDO11_SOC(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_LDO11SOC_AON); - BL_WR_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST, tmpVal); - - BL702_Delay_US(55); - - return SUCCESS; + * @brief Power on LDO11 + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_On_LDO11_SOC(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_LDO11SOC_AON); + BL_WR_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST, tmpVal); + + BL702_Delay_US(55); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power off LDO11 - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_LDO11_SOC(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_LDO11SOC_AON); - BL_WR_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST, tmpVal); - - BL702_Delay_US(55); - - return SUCCESS; + * @brief Power off LDO11 + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_LDO11_SOC(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_LDO11SOC_AON); + BL_WR_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST, tmpVal); + + BL702_Delay_US(55); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power on LDO15_RF - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_On_LDO15_RF(void) -{ - uint32_t tmpVal = 0; - - /* ldo15rf power on */ - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - - BL702_Delay_US(90); - - return SUCCESS; + * @brief Power on LDO15_RF + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_On_LDO15_RF(void) { + uint32_t tmpVal = 0; + + /* ldo15rf power on */ + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + + BL702_Delay_US(90); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power off LDO15_RF - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_LDO15_RF(void) -{ - uint32_t tmpVal = 0; - - /* ldo15rf power off */ - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - - return SUCCESS; + * @brief Power off LDO15_RF + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_LDO15_RF(void) { + uint32_t tmpVal = 0; + + /* ldo15rf power off */ + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief power on source follow regular - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_On_SFReg(void) -{ - uint32_t tmpVal = 0; - - /* power on sfreg */ - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_SFREG_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - - BL702_Delay_US(10); - - return SUCCESS; + * @brief power on source follow regular + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_On_SFReg(void) { + uint32_t tmpVal = 0; + + /* power on sfreg */ + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_SFREG_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + + BL702_Delay_US(10); + + return SUCCESS; } /****************************************************************************/ /** - * @brief power off source follow regular - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_SFReg(void) -{ - uint32_t tmpVal = 0; - - /* power off sfreg */ - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_SFREG_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - - return SUCCESS; + * @brief power off source follow regular + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_SFReg(void) { + uint32_t tmpVal = 0; + + /* power off sfreg */ + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_SFREG_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power off the power can be shut down in PDS0 - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_LowPower_Enter_PDS0(void) -{ - uint32_t tmpVal = 0; - - /* power off bz */ - tmpVal = BL_RD_REG(AON_BASE, AON_MISC); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_SW_BZ_EN_AON); - BL_WR_REG(AON_BASE, AON_MISC, tmpVal); - - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_SFREG_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_MBG_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - - /* gating Clock, no more use */ - //tmpVal=BL_RD_REG(GLB_BASE,GLB_CGEN_CFG0); - //tmpVal=tmpVal&(~(1<<6)); - //tmpVal=tmpVal&(~(1<<7)); - //BL_WR_REG(GLB_BASE,GLB_CGEN_CFG0,tmpVal); - - return SUCCESS; + * @brief Power off the power can be shut down in PDS0 + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_LowPower_Enter_PDS0(void) { + uint32_t tmpVal = 0; + + /* power off bz */ + tmpVal = BL_RD_REG(AON_BASE, AON_MISC); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_SW_BZ_EN_AON); + BL_WR_REG(AON_BASE, AON_MISC, tmpVal); + + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_SFREG_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_MBG_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + + /* gating Clock, no more use */ + // tmpVal=BL_RD_REG(GLB_BASE,GLB_CGEN_CFG0); + // tmpVal=tmpVal&(~(1<<6)); + // tmpVal=tmpVal&(~(1<<7)); + // BL_WR_REG(GLB_BASE,GLB_CGEN_CFG0,tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power on the power powered down in PDS0 - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_LowPower_Exit_PDS0(void) -{ - uint32_t tmpVal = 0; + * @brief Power on the power powered down in PDS0 + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_LowPower_Exit_PDS0(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_MBG_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_MBG_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - BL702_Delay_US(20); + BL702_Delay_US(20); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - BL702_Delay_US(60); + BL702_Delay_US(60); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_SFREG_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_SFREG_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - BL702_Delay_US(20); + BL702_Delay_US(20); - /* power on bz */ - tmpVal = BL_RD_REG(AON_BASE, AON_MISC); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_SW_BZ_EN_AON); - BL_WR_REG(AON_BASE, AON_MISC, tmpVal); + /* power on bz */ + tmpVal = BL_RD_REG(AON_BASE, AON_MISC); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_SW_BZ_EN_AON); + BL_WR_REG(AON_BASE, AON_MISC, tmpVal); - /* ungating Clock, no more use */ - //tmpVal=BL_RD_REG(GLB_BASE,GLB_CGEN_CFG0); - //tmpVal=tmpVal|((1<<6)); - //tmpVal=tmpVal|((1<<7)); - //BL_WR_REG(GLB_BASE,GLB_CGEN_CFG0,tmpVal); + /* ungating Clock, no more use */ + // tmpVal=BL_RD_REG(GLB_BASE,GLB_CGEN_CFG0); + // tmpVal=tmpVal|((1<<6)); + // tmpVal=tmpVal|((1<<7)); + // BL_WR_REG(GLB_BASE,GLB_CGEN_CFG0,tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Power on the power powered down in PDS0 - * - * @param delay: None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Set_LDO11_SOC_Sstart_Delay(uint8_t delay) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM((delay <= 0x3)); - - /* config ldo11soc_sstart_delay_aon */ - tmpVal = BL_RD_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_LDO11SOC_SSTART_DELAY_AON, delay); - BL_WR_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST, tmpVal); - - return SUCCESS; + * @brief Power on the power powered down in PDS0 + * + * @param delay: None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Set_LDO11_SOC_Sstart_Delay(uint8_t delay) { + uint32_t tmpVal = 0; + + CHECK_PARAM((delay <= 0x3)); + + /* config ldo11soc_sstart_delay_aon */ + tmpVal = BL_RD_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_LDO11SOC_SSTART_DELAY_AON, delay); + BL_WR_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief - * - * @param - * - * @return - * -*******************************************************************************/ -BL_Err_Type AON_Set_DCDC18_Top_0(uint8_t voutSel, uint8_t vpfm) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(AON_BASE, AON_DCDC18_TOP_0); - //dcdc18_vout_sel_aon, 1.425V*1.05=1.5V - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_DCDC18_VOUT_SEL_AON, voutSel); - //dcdc18_vpfm_aon - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_DCDC18_VPFM_AON, vpfm); - BL_WR_REG(AON_BASE, AON_DCDC18_TOP_0, tmpVal); - - return SUCCESS; + * @brief + * + * @param + * + * @return + * + *******************************************************************************/ +BL_Err_Type AON_Set_DCDC18_Top_0(uint8_t voutSel, uint8_t vpfm) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(AON_BASE, AON_DCDC18_TOP_0); + // dcdc18_vout_sel_aon, 1.425V*1.05=1.5V + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_DCDC18_VOUT_SEL_AON, voutSel); + // dcdc18_vpfm_aon + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_DCDC18_VPFM_AON, vpfm); + BL_WR_REG(AON_BASE, AON_DCDC18_TOP_0, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief - * - * @param - * - * @return - * -*******************************************************************************/ -BL_Err_Type AON_Set_Xtal_Cfg(uint8_t gmBoost, uint8_t ampCtrl, uint8_t fastStartup) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); - //xtal_gm_boost - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_GM_BOOST_AON, gmBoost); - //xtal_amp_ctrl - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_AMP_CTRL_AON, ampCtrl); - //xtal_fast_startup - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_FAST_STARTUP_AON, fastStartup); - BL_WR_REG(AON_BASE, AON_XTAL_CFG, tmpVal); - - return SUCCESS; + * @brief + * + * @param + * + * @return + * + *******************************************************************************/ +BL_Err_Type AON_Set_Xtal_Cfg(uint8_t gmBoost, uint8_t ampCtrl, uint8_t fastStartup) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); + // xtal_gm_boost + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_GM_BOOST_AON, gmBoost); + // xtal_amp_ctrl + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_AMP_CTRL_AON, ampCtrl); + // xtal_fast_startup + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_FAST_STARTUP_AON, fastStartup); + BL_WR_REG(AON_BASE, AON_XTAL_CFG, tmpVal); + + return SUCCESS; } /*@} end of group AON_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_cam.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_cam.c index 2112308657..d8192941c9 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_cam.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_cam.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_cam.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_cam.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "bl702.h" #include "bl702_cam.h" +#include "bl702.h" #include "bl702_glb.h" /** @addtogroup BL702_Peripheral_Driver @@ -61,7 +61,7 @@ /** @defgroup CAM_Private_Variables * @{ */ -static intCallback_Type *camIntCbfArra[CAM_INT_ALL] = { NULL }; +static intCallback_Type *camIntCbfArra[CAM_INT_ALL] = {NULL}; /*@} end of group CAM_Private_Variables */ @@ -88,670 +88,642 @@ static intCallback_Type *camIntCbfArra[CAM_INT_ALL] = { NULL }; */ /****************************************************************************/ /** - * @brief Camera module init - * - * @param cfg: Camera configuration structure pointer - * - * @return None - * -*******************************************************************************/ -void CAM_Init(CAM_CFG_Type *cfg) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_CAM_SW_MODE_TYPE(cfg->swMode)); - CHECK_PARAM(IS_CAM_FRAME_MODE_TYPE(cfg->frameMode)); - CHECK_PARAM(IS_CAM_YUV_MODE_TYPE(cfg->yuvMode)); - CHECK_PARAM(IS_CAM_FRAME_ACTIVE_POL(cfg->framePol)); - CHECK_PARAM(IS_CAM_LINE_ACTIVE_POL(cfg->linePol)); - CHECK_PARAM(IS_CAM_BURST_TYPE(cfg->burstType)); - CHECK_PARAM(IS_CAM_SENSOR_MODE_TYPE(cfg->camSensorMode)); - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_CAM); - - /* Set camera configuration */ - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DVP_ENABLE); - BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); - - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_SW_MODE, cfg->swMode); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_INTERLV_MODE, cfg->frameMode); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_FRAM_VLD_POL, cfg->framePol); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_LINE_VLD_POL, cfg->linePol); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_HBURST, cfg->burstType); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_DVP_MODE, cfg->camSensorMode); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_DVP_WAIT_CYCLE, cfg->waitCount); - - switch (cfg->yuvMode) { - case CAM_YUV422: - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); - break; - - case CAM_YUV420_EVEN: - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EVEN); - break; - - case CAM_YUV420_ODD: - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EVEN); - break; - - case CAM_YUV400_EVEN: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DROP_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EVEN); - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); - break; - - case CAM_YUV400_ODD: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DROP_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DROP_EVEN); - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); - break; - - default: - break; - } - - BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); - - /* Set frame count to issue interrupt at sw mode */ - tmpVal = BL_RD_REG(CAM_BASE, CAM_INT_CONTROL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_FRAME_CNT_TRGR_INT, cfg->swIntCnt); - BL_WR_REG(CAM_BASE, CAM_INT_CONTROL, tmpVal); - - /* Set camera memory start address, memory size and frame size in burst */ - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_ADDR_START_0, cfg->memStart0 & 0xFFFFFFF0); + * @brief Camera module init + * + * @param cfg: Camera configuration structure pointer + * + * @return None + * + *******************************************************************************/ +void CAM_Init(CAM_CFG_Type *cfg) { + uint32_t tmpVal; + + CHECK_PARAM(IS_CAM_SW_MODE_TYPE(cfg->swMode)); + CHECK_PARAM(IS_CAM_FRAME_MODE_TYPE(cfg->frameMode)); + CHECK_PARAM(IS_CAM_YUV_MODE_TYPE(cfg->yuvMode)); + CHECK_PARAM(IS_CAM_FRAME_ACTIVE_POL(cfg->framePol)); + CHECK_PARAM(IS_CAM_LINE_ACTIVE_POL(cfg->linePol)); + CHECK_PARAM(IS_CAM_BURST_TYPE(cfg->burstType)); + CHECK_PARAM(IS_CAM_SENSOR_MODE_TYPE(cfg->camSensorMode)); + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_CAM); + + /* Set camera configuration */ + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DVP_ENABLE); + BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); + + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_SW_MODE, cfg->swMode); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_INTERLV_MODE, cfg->frameMode); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_FRAM_VLD_POL, cfg->framePol); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_LINE_VLD_POL, cfg->linePol); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_HBURST, cfg->burstType); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_DVP_MODE, cfg->camSensorMode); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_DVP_WAIT_CYCLE, cfg->waitCount); + + switch (cfg->yuvMode) { + case CAM_YUV422: + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); + break; + + case CAM_YUV420_EVEN: + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EVEN); + break; + + case CAM_YUV420_ODD: + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EVEN); + break; + + case CAM_YUV400_EVEN: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DROP_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EVEN); + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); + break; + + case CAM_YUV400_ODD: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DROP_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DROP_EVEN); + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); + break; + + default: + break; + } + + BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); + + /* Set frame count to issue interrupt at sw mode */ + tmpVal = BL_RD_REG(CAM_BASE, CAM_INT_CONTROL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_FRAME_CNT_TRGR_INT, cfg->swIntCnt); + BL_WR_REG(CAM_BASE, CAM_INT_CONTROL, tmpVal); + + /* Set camera memory start address, memory size and frame size in burst */ + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_ADDR_START_0, cfg->memStart0 & 0xFFFFFFF0); + + if (cfg->burstType == CAM_BURST_TYPE_SINGLE) { + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 4); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 4); + } else if (cfg->burstType == CAM_BURST_TYPE_INCR4) { + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 16); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 16); + } else if (cfg->burstType == CAM_BURST_TYPE_INCR8) { + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 32); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 32); + } else if (cfg->burstType == CAM_BURST_TYPE_INCR16) { + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 64); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 64); + } + + if (!cfg->frameMode) { + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_ADDR_START_1, cfg->memStart1 & 0xFFFFFFF0); if (cfg->burstType == CAM_BURST_TYPE_SINGLE) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 4); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 4); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 4); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 4); } else if (cfg->burstType == CAM_BURST_TYPE_INCR4) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 16); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 16); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 16); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 16); } else if (cfg->burstType == CAM_BURST_TYPE_INCR8) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 32); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 32); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 32); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 32); } else if (cfg->burstType == CAM_BURST_TYPE_INCR16) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 64); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 64); - } - - if (!cfg->frameMode) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_ADDR_START_1, cfg->memStart1 & 0xFFFFFFF0); - - if (cfg->burstType == CAM_BURST_TYPE_SINGLE) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 4); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 4); - } else if (cfg->burstType == CAM_BURST_TYPE_INCR4) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 16); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 16); - } else if (cfg->burstType == CAM_BURST_TYPE_INCR8) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 32); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 32); - } else if (cfg->burstType == CAM_BURST_TYPE_INCR16) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 64); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 64); - } + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 64); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 64); } + } - /* Clear interrupt */ - BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, 0xFFFF0); + /* Clear interrupt */ + BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, 0xFFFF0); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(CAM_IRQn, CAM_IRQHandler); + Interrupt_Handler_Register(CAM_IRQn, CAM_IRQHandler); #endif } /****************************************************************************/ /** - * @brief Deinit camera module - * - * @param None - * - * @return None - * -*******************************************************************************/ -void CAM_Deinit(void) -{ - //GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_CAM); + * @brief Deinit camera module + * + * @param None + * + * @return None + * + *******************************************************************************/ +void CAM_Deinit(void) { + // GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_CAM); } /****************************************************************************/ /** - * @brief Enable camera module - * - * @param None - * - * @return None - * -*******************************************************************************/ -void CAM_Enable(void) -{ - uint32_t tmpVal; - - /* Enable camera module */ - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DVP_ENABLE); - BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); + * @brief Enable camera module + * + * @param None + * + * @return None + * + *******************************************************************************/ +void CAM_Enable(void) { + uint32_t tmpVal; + + /* Enable camera module */ + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DVP_ENABLE); + BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); } /****************************************************************************/ /** - * @brief Disable camera module - * - * @param None - * - * @return None - * -*******************************************************************************/ -void CAM_Disable(void) -{ - uint32_t tmpVal; - - /* Disable camera module */ - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DVP_ENABLE); - BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); + * @brief Disable camera module + * + * @param None + * + * @return None + * + *******************************************************************************/ +void CAM_Disable(void) { + uint32_t tmpVal; + + /* Disable camera module */ + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DVP_ENABLE); + BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); } /****************************************************************************/ /** - * @brief Camera clock gate function - * - * @param enable: Enable or disable - * - * @return None - * -*******************************************************************************/ -void CAM_Clock_Gate(BL_Fun_Type enable) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_DVP_PIX_CLK_CG, enable); - BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); + * @brief Camera clock gate function + * + * @param enable: Enable or disable + * + * @return None + * + *******************************************************************************/ +void CAM_Clock_Gate(BL_Fun_Type enable) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_DVP_PIX_CLK_CG, enable); + BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); } /****************************************************************************/ /** - * @brief Camera hsync crop function - * - * @param start: Valid hsync start count - * @param end: Valid hsync end count - * - * @return None - * -*******************************************************************************/ -void CAM_Hsync_Crop(uint16_t start, uint16_t end) -{ - BL_WR_REG(CAM_BASE, CAM_HSYNC_CONTROL, (start << 16) + end); -} + * @brief Camera hsync crop function + * + * @param start: Valid hsync start count + * @param end: Valid hsync end count + * + * @return None + * + *******************************************************************************/ +void CAM_Hsync_Crop(uint16_t start, uint16_t end) { BL_WR_REG(CAM_BASE, CAM_HSYNC_CONTROL, (start << 16) + end); } /****************************************************************************/ /** - * @brief Camera vsync crop function - * - * @param start: Valid vsync start count - * @param end: Valid vsync end count - * - * @return None - * -*******************************************************************************/ -void CAM_Vsync_Crop(uint16_t start, uint16_t end) -{ - BL_WR_REG(CAM_BASE, CAM_VSYNC_CONTROL, (start << 16) + end); -} + * @brief Camera vsync crop function + * + * @param start: Valid vsync start count + * @param end: Valid vsync end count + * + * @return None + * + *******************************************************************************/ +void CAM_Vsync_Crop(uint16_t start, uint16_t end) { BL_WR_REG(CAM_BASE, CAM_VSYNC_CONTROL, (start << 16) + end); } /****************************************************************************/ /** - * @brief Camera set total valid pix count in a line function - * - * @param count: Count value - * - * @return None - * -*******************************************************************************/ -void CAM_Set_Hsync_Total_Count(uint16_t count) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_TOTAL_HCNT, count); - BL_WR_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL, tmpVal); + * @brief Camera set total valid pix count in a line function + * + * @param count: Count value + * + * @return None + * + *******************************************************************************/ +void CAM_Set_Hsync_Total_Count(uint16_t count) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_TOTAL_HCNT, count); + BL_WR_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL, tmpVal); } /****************************************************************************/ /** - * @brief Camera set total valid line count in a frame function - * - * @param count: Count value - * - * @return None - * -*******************************************************************************/ -void CAM_Set_Vsync_Total_Count(uint16_t count) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_TOTAL_VCNT, count); - BL_WR_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL, tmpVal); + * @brief Camera set total valid line count in a frame function + * + * @param count: Count value + * + * @return None + * + *******************************************************************************/ +void CAM_Set_Vsync_Total_Count(uint16_t count) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_TOTAL_VCNT, count); + BL_WR_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL, tmpVal); } /****************************************************************************/ /** - * @brief Get one camera frame in interleave mode - * - * @param info: Interleave mode camera frame infomation pointer - * - * @return None - * -*******************************************************************************/ -void CAM_Interleave_Get_Frame_Info(CAM_Interleave_Frame_Info *info) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR); - - info->validFrames = BL_GET_REG_BITS_VAL(tmpVal, CAM_FRAME_VALID_CNT_0); - info->curFrameAddr = BL_RD_REG(CAM_BASE, CAM_FRAME_START_ADDR0_0); - info->curFrameBytes = BL_RD_REG(CAM_BASE, CAM_FRAME_BYTE_CNT0_0); - info->status = tmpVal; + * @brief Get one camera frame in interleave mode + * + * @param info: Interleave mode camera frame infomation pointer + * + * @return None + * + *******************************************************************************/ +void CAM_Interleave_Get_Frame_Info(CAM_Interleave_Frame_Info *info) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR); + + info->validFrames = BL_GET_REG_BITS_VAL(tmpVal, CAM_FRAME_VALID_CNT_0); + info->curFrameAddr = BL_RD_REG(CAM_BASE, CAM_FRAME_START_ADDR0_0); + info->curFrameBytes = BL_RD_REG(CAM_BASE, CAM_FRAME_BYTE_CNT0_0); + info->status = tmpVal; } /****************************************************************************/ /** - * @brief Get one camera frame in planar mode - * - * @param info: Planar mode camera frame infomation pointer - * - * @return None - * -*******************************************************************************/ -void CAM_Planar_Get_Frame_Info(CAM_Planar_Frame_Info *info) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR); - - info->validFrames0 = BL_GET_REG_BITS_VAL(tmpVal, CAM_FRAME_VALID_CNT_0); - info->validFrames1 = BL_GET_REG_BITS_VAL(tmpVal, CAM_FRAME_VALID_CNT_1); - info->curFrameAddr0 = BL_RD_REG(CAM_BASE, CAM_FRAME_START_ADDR0_0); - info->curFrameAddr1 = BL_RD_REG(CAM_BASE, CAM_FRAME_START_ADDR1_0); - info->curFrameBytes0 = BL_RD_REG(CAM_BASE, CAM_FRAME_BYTE_CNT0_0); - info->curFrameBytes1 = BL_RD_REG(CAM_BASE, CAM_FRAME_BYTE_CNT1_0); - info->status = tmpVal; + * @brief Get one camera frame in planar mode + * + * @param info: Planar mode camera frame infomation pointer + * + * @return None + * + *******************************************************************************/ +void CAM_Planar_Get_Frame_Info(CAM_Planar_Frame_Info *info) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR); + + info->validFrames0 = BL_GET_REG_BITS_VAL(tmpVal, CAM_FRAME_VALID_CNT_0); + info->validFrames1 = BL_GET_REG_BITS_VAL(tmpVal, CAM_FRAME_VALID_CNT_1); + info->curFrameAddr0 = BL_RD_REG(CAM_BASE, CAM_FRAME_START_ADDR0_0); + info->curFrameAddr1 = BL_RD_REG(CAM_BASE, CAM_FRAME_START_ADDR1_0); + info->curFrameBytes0 = BL_RD_REG(CAM_BASE, CAM_FRAME_BYTE_CNT0_0); + info->curFrameBytes1 = BL_RD_REG(CAM_BASE, CAM_FRAME_BYTE_CNT1_0); + info->status = tmpVal; } /****************************************************************************/ /** - * @brief Get available count 0 of frames - * - * @param None - * - * @return Frames count - * -*******************************************************************************/ -uint8_t CAM_Get_Frame_Count_0(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR), CAM_FRAME_VALID_CNT_0); -} + * @brief Get available count 0 of frames + * + * @param None + * + * @return Frames count + * + *******************************************************************************/ +uint8_t CAM_Get_Frame_Count_0(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR), CAM_FRAME_VALID_CNT_0); } /****************************************************************************/ /** - * @brief Get available count 1 of frames - * - * @param None - * - * @return Frames count - * -*******************************************************************************/ -uint8_t CAM_Get_Frame_Count_1(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR), CAM_FRAME_VALID_CNT_1); -} + * @brief Get available count 1 of frames + * + * @param None + * + * @return Frames count + * + *******************************************************************************/ +uint8_t CAM_Get_Frame_Count_1(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR), CAM_FRAME_VALID_CNT_1); } /****************************************************************************/ /** - * @brief Pop one camera frame in interleave mode - * - * @param None - * - * @return None - * -*******************************************************************************/ -void CAM_Interleave_Pop_Frame(void) -{ - /* Pop one frame */ - BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, 1); + * @brief Pop one camera frame in interleave mode + * + * @param None + * + * @return None + * + *******************************************************************************/ +void CAM_Interleave_Pop_Frame(void) { + /* Pop one frame */ + BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, 1); } /****************************************************************************/ /** - * @brief Pop one camera frame in planar mode - * - * @param None - * - * @return None - * -*******************************************************************************/ -void CAM_Planar_Pop_Frame(void) -{ - /* Pop one frame */ - BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, 3); + * @brief Pop one camera frame in planar mode + * + * @param None + * + * @return None + * + *******************************************************************************/ +void CAM_Planar_Pop_Frame(void) { + /* Pop one frame */ + BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, 3); } /****************************************************************************/ /** - * @brief CAMERA Enable Disable Interrupt - * - * @param intType: CAMERA Interrupt Type - * @param intMask: Enable or Disable - * - * @return None - * -*******************************************************************************/ -void CAM_IntMask(CAM_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_CAM_INT_TYPE(intType)); - CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); - - tmpVal = BL_RD_REG(CAM_BASE, CAM_INT_CONTROL); - - switch (intType) { - case CAM_INT_NORMAL_0: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_0_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_0_EN); - } - - break; - - case CAM_INT_NORMAL_1: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_1_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_1_EN); - } - - break; - - case CAM_INT_MEMORY_OVERWRITE_0: - case CAM_INT_MEMORY_OVERWRITE_1: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_MEM_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_MEM_EN); - } - - break; - - case CAM_INT_FRAME_OVERWRITE_0: - case CAM_INT_FRAME_OVERWRITE_1: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FRAME_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_FRAME_EN); - } - - break; - - case CAM_INT_FIFO_OVERWRITE_0: - case CAM_INT_FIFO_OVERWRITE_1: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FIFO_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_FIFO_EN); - } - - break; - - case CAM_INT_VSYNC_CNT_ERROR: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_VCNT_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_VCNT_EN); - } - - break; - - case CAM_INT_HSYNC_CNT_ERROR: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_HCNT_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_HCNT_EN); - } - - break; - - case CAM_INT_ALL: - if (intMask == UNMASK) { - /* Enable all interrupt */ - tmpVal |= 0x7F; - } else { - /* Disable all interrupt */ - tmpVal &= 0xFFFFFF80; - } - - break; - - default: - break; + * @brief CAMERA Enable Disable Interrupt + * + * @param intType: CAMERA Interrupt Type + * @param intMask: Enable or Disable + * + * @return None + * + *******************************************************************************/ +void CAM_IntMask(CAM_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_CAM_INT_TYPE(intType)); + CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); + + tmpVal = BL_RD_REG(CAM_BASE, CAM_INT_CONTROL); + + switch (intType) { + case CAM_INT_NORMAL_0: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_0_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_0_EN); } - BL_WR_REG(CAM_BASE, CAM_INT_CONTROL, tmpVal); -} + break; -/****************************************************************************/ /** - * @brief CAMERA Interrupt Clear - * - * @param intType: CAMERA Interrupt Type - * - * @return None - * -*******************************************************************************/ -void CAM_IntClr(CAM_INT_Type intType) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP); + case CAM_INT_NORMAL_1: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_1_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_1_EN); + } - switch (intType) { - case CAM_INT_NORMAL_0: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_CLR_0); - break; + break; - case CAM_INT_NORMAL_1: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_CLR_1); - break; + case CAM_INT_MEMORY_OVERWRITE_0: + case CAM_INT_MEMORY_OVERWRITE_1: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_MEM_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_MEM_EN); + } - case CAM_INT_MEMORY_OVERWRITE_0: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_MEM_CLR_0); - break; + break; - case CAM_INT_MEMORY_OVERWRITE_1: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_MEM_CLR_1); - break; + case CAM_INT_FRAME_OVERWRITE_0: + case CAM_INT_FRAME_OVERWRITE_1: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FRAME_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_FRAME_EN); + } - case CAM_INT_FRAME_OVERWRITE_0: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FRAME_CLR_0); - break; + break; - case CAM_INT_FRAME_OVERWRITE_1: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FRAME_CLR_1); - break; + case CAM_INT_FIFO_OVERWRITE_0: + case CAM_INT_FIFO_OVERWRITE_1: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FIFO_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_FIFO_EN); + } - case CAM_INT_FIFO_OVERWRITE_0: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FIFO_CLR_0); - break; + break; - case CAM_INT_FIFO_OVERWRITE_1: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FIFO_CLR_1); - break; + case CAM_INT_VSYNC_CNT_ERROR: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_VCNT_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_VCNT_EN); + } - case CAM_INT_VSYNC_CNT_ERROR: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_VCNT_CLR_0); - break; + break; - case CAM_INT_HSYNC_CNT_ERROR: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_HCNT_CLR_0); - break; + case CAM_INT_HSYNC_CNT_ERROR: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_HCNT_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_HCNT_EN); + } - case CAM_INT_ALL: - tmpVal = 0xFFFF0; + break; - default: - break; + case CAM_INT_ALL: + if (intMask == UNMASK) { + /* Enable all interrupt */ + tmpVal |= 0x7F; + } else { + /* Disable all interrupt */ + tmpVal &= 0xFFFFFF80; } - BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, tmpVal); + break; + + default: + break; + } + + BL_WR_REG(CAM_BASE, CAM_INT_CONTROL, tmpVal); } /****************************************************************************/ /** - * @brief Install camera interrupt callback function - * - * @param intType: CAMERA interrupt type - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return None - * -*******************************************************************************/ -void CAM_Int_Callback_Install(CAM_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_CAM_INT_TYPE(intType)); + * @brief CAMERA Interrupt Clear + * + * @param intType: CAMERA Interrupt Type + * + * @return None + * + *******************************************************************************/ +void CAM_IntClr(CAM_INT_Type intType) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP); + + switch (intType) { + case CAM_INT_NORMAL_0: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_CLR_0); + break; + + case CAM_INT_NORMAL_1: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_CLR_1); + break; + + case CAM_INT_MEMORY_OVERWRITE_0: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_MEM_CLR_0); + break; + + case CAM_INT_MEMORY_OVERWRITE_1: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_MEM_CLR_1); + break; + + case CAM_INT_FRAME_OVERWRITE_0: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FRAME_CLR_0); + break; + + case CAM_INT_FRAME_OVERWRITE_1: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FRAME_CLR_1); + break; + + case CAM_INT_FIFO_OVERWRITE_0: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FIFO_CLR_0); + break; + + case CAM_INT_FIFO_OVERWRITE_1: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FIFO_CLR_1); + break; + + case CAM_INT_VSYNC_CNT_ERROR: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_VCNT_CLR_0); + break; + + case CAM_INT_HSYNC_CNT_ERROR: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_HCNT_CLR_0); + break; + + case CAM_INT_ALL: + tmpVal = 0xFFFF0; + + default: + break; + } + + BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, tmpVal); +} - camIntCbfArra[intType] = cbFun; +/****************************************************************************/ /** + * @brief Install camera interrupt callback function + * + * @param intType: CAMERA interrupt type + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return None + * + *******************************************************************************/ +void CAM_Int_Callback_Install(CAM_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_CAM_INT_TYPE(intType)); + + camIntCbfArra[intType] = cbFun; } /****************************************************************************/ /** - * @brief CAM hardware mode with frame start address wrap to memory address start function enable or disable - * - * @param enable: Enable or disable - * @return None - * -*******************************************************************************/ -void CAM_HW_Mode_Wrap(BL_Fun_Type enable) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_HW_MODE_FWRAP, enable); - BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); + * @brief CAM hardware mode with frame start address wrap to memory address start function enable or disable + * + * @param enable: Enable or disable + * @return None + * + *******************************************************************************/ +void CAM_HW_Mode_Wrap(BL_Fun_Type enable) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_HW_MODE_FWRAP, enable); + BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); } /****************************************************************************/ /** - * @brief Camera interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Camera interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void CAM_IRQHandler(void) -{ - uint32_t tmpVal; +void CAM_IRQHandler(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR); + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR); - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_NORMAL_INT_0)) { - CAM_IntClr(CAM_INT_NORMAL_0); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_NORMAL_INT_0)) { + CAM_IntClr(CAM_INT_NORMAL_0); - if (camIntCbfArra[CAM_INT_NORMAL_0] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_NORMAL_0](); - } + if (camIntCbfArra[CAM_INT_NORMAL_0] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_NORMAL_0](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_NORMAL_INT_1)) { - CAM_IntClr(CAM_INT_NORMAL_1); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_NORMAL_INT_1)) { + CAM_IntClr(CAM_INT_NORMAL_1); - if (camIntCbfArra[CAM_INT_NORMAL_1] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_NORMAL_1](); - } + if (camIntCbfArra[CAM_INT_NORMAL_1] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_NORMAL_1](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_MEM_INT_0)) { - CAM_IntClr(CAM_INT_MEMORY_OVERWRITE_0); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_MEM_INT_0)) { + CAM_IntClr(CAM_INT_MEMORY_OVERWRITE_0); - if (camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_0] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_0](); - } + if (camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_0] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_0](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_MEM_INT_1)) { - CAM_IntClr(CAM_INT_MEMORY_OVERWRITE_1); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_MEM_INT_1)) { + CAM_IntClr(CAM_INT_MEMORY_OVERWRITE_1); - if (camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_1] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_1](); - } + if (camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_1] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_1](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FRAME_INT_0)) { - CAM_IntClr(CAM_INT_FRAME_OVERWRITE_0); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FRAME_INT_0)) { + CAM_IntClr(CAM_INT_FRAME_OVERWRITE_0); - if (camIntCbfArra[CAM_INT_FRAME_OVERWRITE_0] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_FRAME_OVERWRITE_0](); - } + if (camIntCbfArra[CAM_INT_FRAME_OVERWRITE_0] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_FRAME_OVERWRITE_0](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FRAME_INT_1)) { - CAM_IntClr(CAM_INT_FRAME_OVERWRITE_1); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FRAME_INT_1)) { + CAM_IntClr(CAM_INT_FRAME_OVERWRITE_1); - if (camIntCbfArra[CAM_INT_FRAME_OVERWRITE_1] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_FRAME_OVERWRITE_1](); - } + if (camIntCbfArra[CAM_INT_FRAME_OVERWRITE_1] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_FRAME_OVERWRITE_1](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FIFO_INT_0)) { - CAM_IntClr(CAM_INT_FIFO_OVERWRITE_0); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FIFO_INT_0)) { + CAM_IntClr(CAM_INT_FIFO_OVERWRITE_0); - if (camIntCbfArra[CAM_INT_FIFO_OVERWRITE_0] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_FIFO_OVERWRITE_0](); - } + if (camIntCbfArra[CAM_INT_FIFO_OVERWRITE_0] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_FIFO_OVERWRITE_0](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FIFO_INT_1)) { - CAM_IntClr(CAM_INT_FIFO_OVERWRITE_1); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FIFO_INT_1)) { + CAM_IntClr(CAM_INT_FIFO_OVERWRITE_1); - if (camIntCbfArra[CAM_INT_FIFO_OVERWRITE_1] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_FIFO_OVERWRITE_1](); - } + if (camIntCbfArra[CAM_INT_FIFO_OVERWRITE_1] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_FIFO_OVERWRITE_1](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_HCNT_INT)) { - CAM_IntClr(CAM_INT_HSYNC_CNT_ERROR); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_HCNT_INT)) { + CAM_IntClr(CAM_INT_HSYNC_CNT_ERROR); - if (camIntCbfArra[CAM_INT_HSYNC_CNT_ERROR] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_HSYNC_CNT_ERROR](); - } + if (camIntCbfArra[CAM_INT_HSYNC_CNT_ERROR] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_HSYNC_CNT_ERROR](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_VCNT_INT)) { - CAM_IntClr(CAM_INT_VSYNC_CNT_ERROR); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_VCNT_INT)) { + CAM_IntClr(CAM_INT_VSYNC_CNT_ERROR); - if (camIntCbfArra[CAM_INT_VSYNC_CNT_ERROR] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_VSYNC_CNT_ERROR](); - } + if (camIntCbfArra[CAM_INT_VSYNC_CNT_ERROR] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_VSYNC_CNT_ERROR](); } + } } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_clock.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_clock.c index ce869738d4..bf5e00e016 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_clock.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_clock.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_clock.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_clock.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_clock.h" @@ -86,77 +86,73 @@ static Clock_Cfg_Type clkCfg; */ /****************************************************************************/ /** - * @brief Set System Clock - * - * @param type: System clock type - * @param clock: System clock value - * - * @return None - * -*******************************************************************************/ -void Clock_System_Clock_Set(BL_System_Clock_Type type, uint32_t clock) -{ - if (type < BL_SYSTEM_CLOCK_MAX) { - clkCfg.systemClock[type] = clock / 1000000; - } + * @brief Set System Clock + * + * @param type: System clock type + * @param clock: System clock value + * + * @return None + * + *******************************************************************************/ +void Clock_System_Clock_Set(BL_System_Clock_Type type, uint32_t clock) { + if (type < BL_SYSTEM_CLOCK_MAX) { + clkCfg.systemClock[type] = clock / 1000000; + } } /****************************************************************************/ /** - * @brief Set Peripheral Clock - * - * @param type: Peripheral clock type - * @param clock: Peripheral clock value - * - * @return None - * -*******************************************************************************/ -void Clock_Peripheral_Clock_Set(BL_AHB_Slave1_Type type, uint32_t clock) -{ - if (type < BL_AHB_SLAVE1_MAX) { - if (type == BL_AHB_SLAVE1_I2S) { - clkCfg.i2sClock = clock; - } else { - clkCfg.peripheralClock[type] = clock / 1000000; - } + * @brief Set Peripheral Clock + * + * @param type: Peripheral clock type + * @param clock: Peripheral clock value + * + * @return None + * + *******************************************************************************/ +void Clock_Peripheral_Clock_Set(BL_AHB_Slave1_Type type, uint32_t clock) { + if (type < BL_AHB_SLAVE1_MAX) { + if (type == BL_AHB_SLAVE1_I2S) { + clkCfg.i2sClock = clock; + } else { + clkCfg.peripheralClock[type] = clock / 1000000; } + } } /****************************************************************************/ /** - * @brief Get System Clock - * - * @param type: System clock type - * - * @return System clock value - * -*******************************************************************************/ -uint32_t Clock_System_Clock_Get(BL_System_Clock_Type type) -{ - if (type < BL_SYSTEM_CLOCK_MAX) { - return clkCfg.systemClock[type] * 1000000; - } - - return 0; + * @brief Get System Clock + * + * @param type: System clock type + * + * @return System clock value + * + *******************************************************************************/ +uint32_t Clock_System_Clock_Get(BL_System_Clock_Type type) { + if (type < BL_SYSTEM_CLOCK_MAX) { + return clkCfg.systemClock[type] * 1000000; + } + + return 0; } /****************************************************************************/ /** - * @brief Get Peripheral Clock - * - * @param type: Peripheral clock type - * - * @return Peripheral clock value - * -*******************************************************************************/ -uint32_t Clock_Peripheral_Clock_Get(BL_AHB_Slave1_Type type) -{ - if (type < BL_AHB_SLAVE1_MAX) { - if (type == BL_AHB_SLAVE1_I2S) { - return clkCfg.i2sClock; - } else { - return clkCfg.peripheralClock[type] * 1000000; - } + * @brief Get Peripheral Clock + * + * @param type: Peripheral clock type + * + * @return Peripheral clock value + * + *******************************************************************************/ +uint32_t Clock_Peripheral_Clock_Get(BL_AHB_Slave1_Type type) { + if (type < BL_AHB_SLAVE1_MAX) { + if (type == BL_AHB_SLAVE1_I2S) { + return clkCfg.i2sClock; + } else { + return clkCfg.peripheralClock[type] * 1000000; } + } - return 0; + return 0; } /*@} end of group CLOCK_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_common.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_common.c index a9fafc0355..bdaaa66b66 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_common.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_common.c @@ -1,195 +1,185 @@ /** - ****************************************************************************** - * @file bl702_common.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ -#include "l1c_reg.h" + ****************************************************************************** + * @file bl702_common.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_common.h" +#include "l1c_reg.h" /** @addtogroup BL702_Periph_Driver * @{ */ /****************************************************************************/ /** - * @brief delay us - * - * @param[in] core: systemcoreclock - * - * @param[in] cnt: delay cnt us - * - * @return none - * - *******************************************************************************/ + * @brief delay us + * + * @param[in] core: systemcoreclock + * + * @param[in] cnt: delay cnt us + * + * @return none + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER #ifdef ARCH_ARM #ifndef __GNUC__ __WEAK -__ASM void ATTR_TCM_SECTION ASM_Delay_Us(uint32_t core, uint32_t cnt) -{ - lsrs r0, #0x10 muls r0, r1, r0 mov r2, r0 lsrs r2, #0x04 lsrs r2, #0x03 cmp r2, #0x01 beq end cmp r2, #0x00 beq end loop mov r0, r0 mov r0, r0 mov r0, r0 mov r0, r0 mov r0, r0 subs r2, r2, #0x01 cmp r2, #0x00 bne loop end bx lr -} +__ASM void ATTR_TCM_SECTION ASM_Delay_Us(uint32_t core, uint32_t cnt){ + lsrs r0, #0x10 muls r0, r1, r0 mov r2, r0 lsrs r2, #0x04 lsrs r2, #0x03 cmp r2, #0x01 beq end cmp r2, #0x00 beq end loop mov r0, r0 mov r0, r0 mov r0, + r0 mov r0, r0 mov r0, r0 subs r2, r2, #0x01 cmp r2, #0x00 bne loop end bx lr} #else __WEAK -void ATTR_TCM_SECTION ASM_Delay_Us(uint32_t core, uint32_t cnt) -{ - __asm__ __volatile__( - "lsr r0,#0x10\n\t" - "mul r0,r1,r0\n\t" - "mov r2,r0\n\t" - "lsr r2,#0x04\n\t" - "lsr r2,#0x03\n\t" - "cmp r2,#0x01\n\t" - "beq end\n\t" - "cmp r2,#0x00\n\t" - "beq end\n" - "loop :" - "mov r0,r0\n\t" - "mov r0,r0\n\t" - "mov r0,r0\n\t" - "mov r0,r0\n\t" - "mov r0,r0\n\t" - "sub r2,r2,#0x01\n\t" - "cmp r2,#0x00\n\t" - "bne loop\n" - "end :" - "mov r0,r0\n\t"); +void ATTR_TCM_SECTION ASM_Delay_Us(uint32_t core, uint32_t cnt) { + __asm__ __volatile__("lsr r0,#0x10\n\t" + "mul r0,r1,r0\n\t" + "mov r2,r0\n\t" + "lsr r2,#0x04\n\t" + "lsr r2,#0x03\n\t" + "cmp r2,#0x01\n\t" + "beq end\n\t" + "cmp r2,#0x00\n\t" + "beq end\n" + "loop :" + "mov r0,r0\n\t" + "mov r0,r0\n\t" + "mov r0,r0\n\t" + "mov r0,r0\n\t" + "mov r0,r0\n\t" + "sub r2,r2,#0x01\n\t" + "cmp r2,#0x00\n\t" + "bne loop\n" + "end :" + "mov r0,r0\n\t"); } #endif #endif #ifdef ARCH_RISCV -__WEAK -void ATTR_TCM_SECTION ASM_Delay_Us(uint32_t core, uint32_t cnt) -{ - uint32_t codeAddress = 0; - uint32_t divVal = 40; +__WEAK void ATTR_TCM_SECTION ASM_Delay_Us(uint32_t core, uint32_t cnt) { + uint32_t codeAddress = 0; + uint32_t divVal = 40; - codeAddress = (uint32_t)&ASM_Delay_Us; + codeAddress = (uint32_t)&ASM_Delay_Us; - /* 1M=100K*10, so multiple is 10 */ - /* loop function take 4 instructions, so instructionNum is 4 */ - /* if codeAddress locate at IROM space and irom_2t_access is 1, then irom2TAccess=2, else irom2TAccess=1 */ - /* divVal = multiple*instructionNum*irom2TAccess */ - if (((codeAddress & (0xF << 24)) >> 24) == 0x01) { - /* IROM space */ - if (BL_GET_REG_BITS_VAL(BL_RD_REG(L1C_BASE, L1C_CONFIG), L1C_IROM_2T_ACCESS)) { - /* instruction 2T */ - divVal = 80; - } + /* 1M=100K*10, so multiple is 10 */ + /* loop function take 4 instructions, so instructionNum is 4 */ + /* if codeAddress locate at IROM space and irom_2t_access is 1, then irom2TAccess=2, else irom2TAccess=1 */ + /* divVal = multiple*instructionNum*irom2TAccess */ + if (((codeAddress & (0xF << 24)) >> 24) == 0x01) { + /* IROM space */ + if (BL_GET_REG_BITS_VAL(BL_RD_REG(L1C_BASE, L1C_CONFIG), L1C_IROM_2T_ACCESS)) { + /* instruction 2T */ + divVal = 80; } + } - __asm__ __volatile__( - ".align 4\n\t" - "lw a4,%1\n\t" - "lui a5,0x18\n\t" - "addi a5,a5,1696\n\t" - "divu a5,a4,a5\n\t" - "sw a5,%1\n\t" - "lw a4,%1\n\t" - "lw a5,%0\n\t" - "mul a5,a4,a5\n\t" - "sw a5,%1\n\t" - "lw a4,%1\n\t" - "lw a5,%2\n\t" - "divu a5,a4,a5\n\t" - "sw a5,%1\n\t" - "lw a5,%1\n\t" - "li a4,0x1\n\t" - "beq a5,zero,end\n\t" - "beq a5,a4,end\n\t" - "nop\n\t" - "nop\n\t" - ".align 4\n\t" - "loop :\n" - "addi a4,a5,-1\n\t" - "mv a5,a4\n\t" - "bnez a5,loop\n\t" - "nop\n\t" - "end :\n\t" - "nop\n" - : /* output */ - : "m"(cnt), "m"(core), "m"(divVal) /* input */ - : "t1", "a4", "a5" /* destruct description */ - ); + __asm__ __volatile__(".align 4\n\t" + "lw a4,%1\n\t" + "lui a5,0x18\n\t" + "addi a5,a5,1696\n\t" + "divu a5,a4,a5\n\t" + "sw a5,%1\n\t" + "lw a4,%1\n\t" + "lw a5,%0\n\t" + "mul a5,a4,a5\n\t" + "sw a5,%1\n\t" + "lw a4,%1\n\t" + "lw a5,%2\n\t" + "divu a5,a4,a5\n\t" + "sw a5,%1\n\t" + "lw a5,%1\n\t" + "li a4,0x1\n\t" + "beq a5,zero,end\n\t" + "beq a5,a4,end\n\t" + "nop\n\t" + "nop\n\t" + ".align 4\n\t" + "loop :\n" + "addi a4,a5,-1\n\t" + "mv a5,a4\n\t" + "bnez a5,loop\n\t" + "nop\n\t" + "end :\n\t" + "nop\n" + : /* output */ + : "m"(cnt), "m"(core), "m"(divVal) /* input */ + : "t1", "a4", "a5" /* destruct description */ + ); } #endif #endif /****************************************************************************/ /** - * @brief delay us - * - * @param[in] cnt: delay cnt us - * - * @return none - * - *******************************************************************************/ + * @brief delay us + * + * @param[in] cnt: delay cnt us + * + * @return none + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION BL702_Delay_US(uint32_t cnt) -{ - ASM_Delay_Us(SystemCoreClockGet(), cnt); -} +void ATTR_TCM_SECTION BL702_Delay_US(uint32_t cnt) { ASM_Delay_Us(SystemCoreClockGet(), cnt); } #endif /****************************************************************************/ /** - * @brief delay ms - * - * @param[in] cnt: delay cnt ms - * - * @return none - * - *******************************************************************************/ + * @brief delay ms + * + * @param[in] cnt: delay cnt ms + * + * @return none + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION BL702_Delay_MS(uint32_t cnt) -{ - uint32_t i = 0; - uint32_t count = 0; +void ATTR_TCM_SECTION BL702_Delay_MS(uint32_t cnt) { + uint32_t i = 0; + uint32_t count = 0; - if (cnt >= 1024) { - /* delay (n*1024) ms */ - count = 1024; + if (cnt >= 1024) { + /* delay (n*1024) ms */ + count = 1024; - for (i = 0; i < (cnt / 1024); i++) { - BL702_Delay_US(1024 * 1000); - } + for (i = 0; i < (cnt / 1024); i++) { + BL702_Delay_US(1024 * 1000); } + } - if (cnt & 0x3FF) { - /* delay (1-1023)ms */ - count = cnt & 0x3FF; - BL702_Delay_US(count * 1000); - } + if (cnt & 0x3FF) { + /* delay (1-1023)ms */ + count = cnt & 0x3FF; + BL702_Delay_US(count * 1000); + } - //BL702_Delay_US(((cnt<<10)-(cnt<<4)-(cnt<<3))); + // BL702_Delay_US(((cnt<<10)-(cnt<<4)-(cnt<<3))); } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dac.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dac.c index 943b135f44..fc8ea68eae 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dac.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dac.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_dac.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_dac.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_dac.h" @@ -48,16 +48,16 @@ * @{ */ #define GPIP_CLK_SET_DUMMY_WAIT \ - { \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - } + { \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + } /*@} end of group DAC_Private_Macros */ @@ -96,419 +96,399 @@ */ /****************************************************************************/ /** - * @brief DAC initialization - * - * @param cfg: DAC configuration pointer - * - * @return None - * -*******************************************************************************/ -void GLB_DAC_Init(GLB_DAC_Cfg_Type *cfg) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_GLB_DAC_REF_SEL_TYPE(cfg->refSel)); - - /* Set DAC config */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_REF_SEL, cfg->refSel); - - if (ENABLE == cfg->resetChanA) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - } - - if (ENABLE == cfg->resetChanB) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - } - - /* Clear reset */ - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); + * @brief DAC initialization + * + * @param cfg: DAC configuration pointer + * + * @return None + * + *******************************************************************************/ +void GLB_DAC_Init(GLB_DAC_Cfg_Type *cfg) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_GLB_DAC_REF_SEL_TYPE(cfg->refSel)); + + /* Set DAC config */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_REF_SEL, cfg->refSel); + + if (ENABLE == cfg->resetChanA) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + } + + if (ENABLE == cfg->resetChanB) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + } + + /* Clear reset */ + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); } /****************************************************************************/ /** - * @brief DAC channel A initialization - * - * @param cfg: DAC channel configuration pointer - * - * @return None - * -*******************************************************************************/ -void GLB_DAC_Set_ChanA_Config(GLB_DAC_Chan_Cfg_Type *cfg) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_GLB_DAC_CHAN_TYPE(cfg->outMux)); - - /* Set channel A config */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_ACTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_OUTMUX, cfg->outMux); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOA_EN, cfg->outputEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_EN, cfg->chanEn); - - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_ACTRL, tmpVal); + * @brief DAC channel A initialization + * + * @param cfg: DAC channel configuration pointer + * + * @return None + * + *******************************************************************************/ +void GLB_DAC_Set_ChanA_Config(GLB_DAC_Chan_Cfg_Type *cfg) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_GLB_DAC_CHAN_TYPE(cfg->outMux)); + + /* Set channel A config */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_ACTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_OUTMUX, cfg->outMux); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOA_EN, cfg->outputEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_EN, cfg->chanEn); + + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_ACTRL, tmpVal); } /****************************************************************************/ /** - * @brief DAC channel B initialization - * - * @param cfg: DAC channel configuration pointer - * - * @return None - * -*******************************************************************************/ -void GLB_DAC_Set_ChanB_Config(GLB_DAC_Chan_Cfg_Type *cfg) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_GLB_DAC_CHAN_TYPE(cfg->outMux)); - - /* Set channel A config */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_BCTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_OUTMUX, cfg->outMux); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOB_EN, cfg->outputEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_EN, cfg->chanEn); - - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_BCTRL, tmpVal); + * @brief DAC channel B initialization + * + * @param cfg: DAC channel configuration pointer + * + * @return None + * + *******************************************************************************/ +void GLB_DAC_Set_ChanB_Config(GLB_DAC_Chan_Cfg_Type *cfg) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_GLB_DAC_CHAN_TYPE(cfg->outMux)); + + /* Set channel A config */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_BCTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_OUTMUX, cfg->outMux); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOB_EN, cfg->outputEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_EN, cfg->chanEn); + + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_BCTRL, tmpVal); } /****************************************************************************/ /** - * @brief Select DAC channel B source - * - * @param src: DAC channel B source selection type - * - * @return None - * -*******************************************************************************/ -void GPIP_Set_DAC_ChanB_SRC_SEL(GPIP_DAC_ChanB_SRC_Type src) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GPIP_DAC_CHANB_SRC_TYPE(src)); - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_B_SEL, src); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + * @brief Select DAC channel B source + * + * @param src: DAC channel B source selection type + * + * @return None + * + *******************************************************************************/ +void GPIP_Set_DAC_ChanB_SRC_SEL(GPIP_DAC_ChanB_SRC_Type src) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GPIP_DAC_CHANB_SRC_TYPE(src)); + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_B_SEL, src); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Select DAC channel A source - * - * @param src: DAC channel A source selection type - * - * @return None - * -*******************************************************************************/ -void GPIP_Set_DAC_ChanA_SRC_SEL(GPIP_DAC_ChanA_SRC_Type src) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GPIP_DAC_CHANA_SRC_TYPE(src)); - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_A_SEL, src); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + * @brief Select DAC channel A source + * + * @param src: DAC channel A source selection type + * + * @return None + * + *******************************************************************************/ +void GPIP_Set_DAC_ChanA_SRC_SEL(GPIP_DAC_ChanA_SRC_Type src) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GPIP_DAC_CHANA_SRC_TYPE(src)); + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_A_SEL, src); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Enable DAC channel B - * - * @param None - * - * @return None - * -*******************************************************************************/ -void GPIP_DAC_ChanB_Enable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, GPIP_GPDAC_EN2); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + * @brief Enable DAC channel B + * + * @param None + * + * @return None + * + *******************************************************************************/ +void GPIP_DAC_ChanB_Enable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, GPIP_GPDAC_EN2); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Disable DAC channel B - * - * @param None - * - * @return None - * -*******************************************************************************/ -void GPIP_DAC_ChanB_Disable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, GPIP_GPDAC_EN2); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + * @brief Disable DAC channel B + * + * @param None + * + * @return None + * + *******************************************************************************/ +void GPIP_DAC_ChanB_Disable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, GPIP_GPDAC_EN2); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Enable DAC channel A - * - * @param None - * - * @return None - * -*******************************************************************************/ -void GPIP_DAC_ChanA_Enable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, GPIP_GPDAC_EN); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + * @brief Enable DAC channel A + * + * @param None + * + * @return None + * + *******************************************************************************/ +void GPIP_DAC_ChanA_Enable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, GPIP_GPDAC_EN); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Disable DAC channel A - * - * @param None - * - * @return None - * -*******************************************************************************/ -void GPIP_DAC_ChanA_Disable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, GPIP_GPDAC_EN); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + * @brief Disable DAC channel A + * + * @param None + * + * @return None + * + *******************************************************************************/ +void GPIP_DAC_ChanA_Disable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, GPIP_GPDAC_EN); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Select DAC DMA TX format - * - * @param fmt: DAC DMA TX format selection type - * - * @return None - * -*******************************************************************************/ -void GPIP_Set_DAC_DMA_TX_FORMAT_SEL(GPIP_DAC_DMA_TX_FORMAT_Type fmt) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GPIP_DAC_DMA_TX_FORMAT_TYPE(fmt)); - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_DMA_FORMAT, fmt); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); + * @brief Select DAC DMA TX format + * + * @param fmt: DAC DMA TX format selection type + * + * @return None + * + *******************************************************************************/ +void GPIP_Set_DAC_DMA_TX_FORMAT_SEL(GPIP_DAC_DMA_TX_FORMAT_Type fmt) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GPIP_DAC_DMA_TX_FORMAT_TYPE(fmt)); + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_DMA_FORMAT, fmt); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Enable DAC DMA TX - * - * @param None - * - * @return None - * -*******************************************************************************/ -void GPIP_Set_DAC_DMA_TX_Enable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, GPIP_GPDAC_DMA_TX_EN); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); + * @brief Enable DAC DMA TX + * + * @param None + * + * @return None + * + *******************************************************************************/ +void GPIP_Set_DAC_DMA_TX_Enable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, GPIP_GPDAC_DMA_TX_EN); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Disable DAC DMA TX - * - * @param None - * - * @return None - * -*******************************************************************************/ -void GPIP_Set_DAC_DMA_TX_Disable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, GPIP_GPDAC_DMA_TX_EN); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); + * @brief Disable DAC DMA TX + * + * @param None + * + * @return None + * + *******************************************************************************/ +void GPIP_Set_DAC_DMA_TX_Disable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, GPIP_GPDAC_DMA_TX_EN); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Disable DAC DMA TX - * - * @param data: The data to be send - * - * @return None - * -*******************************************************************************/ -void GPIP_DAC_DMA_WriteData(uint32_t data) -{ - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_WDATA, data); -} + * @brief Disable DAC DMA TX + * + * @param data: The data to be send + * + * @return None + * + *******************************************************************************/ +void GPIP_DAC_DMA_WriteData(uint32_t data) { BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_WDATA, data); } /****************************************************************************/ /** - * @brief AON and GPIP DAC config - * - * @param cfg: AON and GPIP DAC configuration - * - * @return config success or not - * -*******************************************************************************/ -BL_Err_Type GLB_GPIP_DAC_Init(GLB_GPIP_DAC_Cfg_Type *cfg) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GLB_DAC_REF_SEL_TYPE(cfg->refSel)); - CHECK_PARAM(IS_GPIP_DAC_MOD_TYPE(cfg->div)); - CHECK_PARAM(IS_GPIP_DAC_DMA_TX_FORMAT_TYPE(cfg->dmaFmt)); - - /* AON Set DAC config */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_REF_SEL, cfg->refSel); - - if (ENABLE == cfg->resetChanA) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - } - - if (ENABLE == cfg->resetChanB) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - } - - /* AON Clear reset */ - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); + * @brief AON and GPIP DAC config + * + * @param cfg: AON and GPIP DAC configuration + * + * @return config success or not + * + *******************************************************************************/ +BL_Err_Type GLB_GPIP_DAC_Init(GLB_GPIP_DAC_Cfg_Type *cfg) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GLB_DAC_REF_SEL_TYPE(cfg->refSel)); + CHECK_PARAM(IS_GPIP_DAC_MOD_TYPE(cfg->div)); + CHECK_PARAM(IS_GPIP_DAC_DMA_TX_FORMAT_TYPE(cfg->dmaFmt)); + + /* AON Set DAC config */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_REF_SEL, cfg->refSel); + + if (ENABLE == cfg->resetChanA) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); - - /* GPIP Set DAC config */ - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_MODE, cfg->div); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); - - /* GPIP Set DMA config */ - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_DMA_TX_EN, cfg->dmaEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_DMA_FORMAT, cfg->dmaFmt); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); - - return SUCCESS; + __NOP(); + __NOP(); + __NOP(); + __NOP(); + } + + if (ENABLE == cfg->resetChanB) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + } + + /* AON Clear reset */ + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); + + /* GPIP Set DAC config */ + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_MODE, cfg->div); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + + /* GPIP Set DMA config */ + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_DMA_TX_EN, cfg->dmaEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_DMA_FORMAT, cfg->dmaFmt); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief AON and GPIP DAC channel A config - * - * @param cfg: AON and GPIP DAC channel A configuration - * - * @return None - * -*******************************************************************************/ -void GLB_GPIP_DAC_Set_ChanA_Config(GLB_GPIP_DAC_ChanA_Cfg_Type *cfg) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GPIP_DAC_CHANA_SRC_TYPE(cfg->src)); - - /* GPIP select source */ - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_A_SEL, cfg->src); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); - - /* GPIP enable or disable channel */ - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_EN, cfg->chanEn); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); - - /* AON enable or disable channel */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_ACTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOA_EN, cfg->outputEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_EN, cfg->chanCovtEn); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_ACTRL, tmpVal); + * @brief AON and GPIP DAC channel A config + * + * @param cfg: AON and GPIP DAC channel A configuration + * + * @return None + * + *******************************************************************************/ +void GLB_GPIP_DAC_Set_ChanA_Config(GLB_GPIP_DAC_ChanA_Cfg_Type *cfg) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GPIP_DAC_CHANA_SRC_TYPE(cfg->src)); + + /* GPIP select source */ + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_A_SEL, cfg->src); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + + /* GPIP enable or disable channel */ + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_EN, cfg->chanEn); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + + /* AON enable or disable channel */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_ACTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOA_EN, cfg->outputEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_EN, cfg->chanCovtEn); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_ACTRL, tmpVal); } /****************************************************************************/ /** - * @brief AON and GPIP DAC channel B config - * - * @param cfg: AON and GPIP DAC channel B configuration - * - * @return None - * -*******************************************************************************/ -void GLB_GPIP_DAC_Set_ChanB_Config(GLB_GPIP_DAC_ChanB_Cfg_Type *cfg) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GPIP_DAC_CHANB_SRC_TYPE(cfg->src)); - - /* GPIP select source */ - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_B_SEL, cfg->src); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); - - /* GPIP enable or disable channel */ - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_EN2, cfg->chanEn); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); - - /* AON enable or disable channel */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_BCTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOB_EN, cfg->outputEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_EN, cfg->chanCovtEn); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_BCTRL, tmpVal); + * @brief AON and GPIP DAC channel B config + * + * @param cfg: AON and GPIP DAC channel B configuration + * + * @return None + * + *******************************************************************************/ +void GLB_GPIP_DAC_Set_ChanB_Config(GLB_GPIP_DAC_ChanB_Cfg_Type *cfg) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GPIP_DAC_CHANB_SRC_TYPE(cfg->src)); + + /* GPIP select source */ + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_B_SEL, cfg->src); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + + /* GPIP enable or disable channel */ + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_EN2, cfg->chanEn); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + + /* AON enable or disable channel */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_BCTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOB_EN, cfg->outputEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_EN, cfg->chanCovtEn); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_BCTRL, tmpVal); } /****************************************************************************/ /** - * @brief DAC channel A set value - * - * @param val: DAC value - * - * @return None - * -*******************************************************************************/ -void GLB_DAC_Set_ChanA_Value(uint16_t val) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_DATA); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_DATA, val); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_DATA, tmpVal); + * @brief DAC channel A set value + * + * @param val: DAC value + * + * @return None + * + *******************************************************************************/ +void GLB_DAC_Set_ChanA_Value(uint16_t val) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_DATA); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_DATA, val); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_DATA, tmpVal); } /****************************************************************************/ /** - * @brief DAC channel B set value - * - * @param val: DAC value - * - * @return None - * -*******************************************************************************/ -void GLB_DAC_Set_ChanB_Value(uint16_t val) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_DATA); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_DATA, val); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_DATA, tmpVal); + * @brief DAC channel B set value + * + * @param val: DAC value + * + * @return None + * + *******************************************************************************/ +void GLB_DAC_Set_ChanB_Value(uint16_t val) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_DATA); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_DATA, val); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_DATA, tmpVal); } /*@} end of group DAC_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dma.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dma.c index d985ccc1b2..5c7cb93d7d 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dma.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dma.c @@ -1,43 +1,43 @@ /** - ****************************************************************************** - * @file bl702_dma.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_dma.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "bl702.h" #include "bl702_dma.h" -#include "string.h" +#include "bl702.h" #include "bl702_glb.h" +#include "string.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -51,13 +51,8 @@ * @{ */ #define DMA_CHANNEL_OFFSET 0x100 -#define DMA_Get_Channel(ch) (DMA_BASE + DMA_CHANNEL_OFFSET + (ch)*0x100) -static intCallback_Type *dmaIntCbfArra[DMA_CH_MAX][DMA_INT_ALL] = { - { NULL, NULL }, - { NULL, NULL }, - { NULL, NULL }, - { NULL, NULL } -}; +#define DMA_Get_Channel(ch) (DMA_BASE + DMA_CHANNEL_OFFSET + (ch) * 0x100) +static intCallback_Type *dmaIntCbfArra[DMA_CH_MAX][DMA_INT_ALL] = {{NULL, NULL}, {NULL, NULL}, {NULL, NULL}, {NULL, NULL}}; static DMA_LLI_Ctrl_Type PingPongListArra[DMA_CH_MAX][2]; /*@} end of group DMA_Private_Macros */ @@ -91,57 +86,56 @@ static DMA_LLI_Ctrl_Type PingPongListArra[DMA_CH_MAX][2]; */ /****************************************************************************/ /** - * @brief DMA interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief DMA interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void DMA_ALL_IRQHandler(void) -{ - uint32_t tmpVal; - uint32_t intClr; - uint8_t ch; - /* Get DMA register */ - uint32_t DMAChs = DMA_BASE; - - for (ch = 0; ch < DMA_CH_MAX; ch++) { - tmpVal = BL_RD_REG(DMAChs, DMA_INTTCSTATUS); - - if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCSTATUS) & (1 << ch)) != 0) { - /* Clear interrupt */ - tmpVal = BL_RD_REG(DMAChs, DMA_INTTCCLEAR); - intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR); - intClr |= (1 << ch); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR, intClr); - BL_WR_REG(DMAChs, DMA_INTTCCLEAR, tmpVal); - - if (dmaIntCbfArra[ch][DMA_INT_TCOMPLETED] != NULL) { - /* Call the callback function */ - dmaIntCbfArra[ch][DMA_INT_TCOMPLETED](); - } - } +void DMA_ALL_IRQHandler(void) { + uint32_t tmpVal; + uint32_t intClr; + uint8_t ch; + /* Get DMA register */ + uint32_t DMAChs = DMA_BASE; + + for (ch = 0; ch < DMA_CH_MAX; ch++) { + tmpVal = BL_RD_REG(DMAChs, DMA_INTTCSTATUS); + + if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCSTATUS) & (1 << ch)) != 0) { + /* Clear interrupt */ + tmpVal = BL_RD_REG(DMAChs, DMA_INTTCCLEAR); + intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR); + intClr |= (1 << ch); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR, intClr); + BL_WR_REG(DMAChs, DMA_INTTCCLEAR, tmpVal); + + if (dmaIntCbfArra[ch][DMA_INT_TCOMPLETED] != NULL) { + /* Call the callback function */ + dmaIntCbfArra[ch][DMA_INT_TCOMPLETED](); + } } - - for (ch = 0; ch < DMA_CH_MAX; ch++) { - tmpVal = BL_RD_REG(DMAChs, DMA_INTERRORSTATUS); - - if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRORSTATUS) & (1 << ch)) != 0) { - /*Clear interrupt */ - tmpVal = BL_RD_REG(DMAChs, DMA_INTERRCLR); - intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR); - intClr |= (1 << ch); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR, intClr); - BL_WR_REG(DMAChs, DMA_INTERRCLR, tmpVal); - - if (dmaIntCbfArra[ch][DMA_INT_ERR] != NULL) { - /* Call the callback function */ - dmaIntCbfArra[ch][DMA_INT_ERR](); - } - } + } + + for (ch = 0; ch < DMA_CH_MAX; ch++) { + tmpVal = BL_RD_REG(DMAChs, DMA_INTERRORSTATUS); + + if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRORSTATUS) & (1 << ch)) != 0) { + /*Clear interrupt */ + tmpVal = BL_RD_REG(DMAChs, DMA_INTERRCLR); + intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR); + intClr |= (1 << ch); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR, intClr); + BL_WR_REG(DMAChs, DMA_INTERRCLR, tmpVal); + + if (dmaIntCbfArra[ch][DMA_INT_ERR] != NULL) { + /* Call the callback function */ + dmaIntCbfArra[ch][DMA_INT_ERR](); + } } + } } #endif @@ -152,597 +146,572 @@ void DMA_ALL_IRQHandler(void) */ /****************************************************************************/ /** - * @brief DMA enable - * - * @param None - * - * @return None - * -*******************************************************************************/ -void DMA_Enable(void) -{ - uint32_t tmpVal; - /* Get DMA register */ - uint32_t DMAChs = DMA_BASE; - - tmpVal = BL_RD_REG(DMAChs, DMA_TOP_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, DMA_E); - BL_WR_REG(DMAChs, DMA_TOP_CONFIG, tmpVal); + * @brief DMA enable + * + * @param None + * + * @return None + * + *******************************************************************************/ +void DMA_Enable(void) { + uint32_t tmpVal; + /* Get DMA register */ + uint32_t DMAChs = DMA_BASE; + + tmpVal = BL_RD_REG(DMAChs, DMA_TOP_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, DMA_E); + BL_WR_REG(DMAChs, DMA_TOP_CONFIG, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(DMA_ALL_IRQn, DMA_ALL_IRQHandler); + Interrupt_Handler_Register(DMA_ALL_IRQn, DMA_ALL_IRQHandler); #endif } /****************************************************************************/ /** - * @brief DMA disable - * - * @param None - * - * @return None - * -*******************************************************************************/ -void DMA_Disable(void) -{ - uint32_t tmpVal; - /* Get DMA register */ - uint32_t DMAChs = DMA_BASE; - - tmpVal = BL_RD_REG(DMAChs, DMA_TOP_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_E); - BL_WR_REG(DMAChs, DMA_TOP_CONFIG, tmpVal); + * @brief DMA disable + * + * @param None + * + * @return None + * + *******************************************************************************/ +void DMA_Disable(void) { + uint32_t tmpVal; + /* Get DMA register */ + uint32_t DMAChs = DMA_BASE; + + tmpVal = BL_RD_REG(DMAChs, DMA_TOP_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_E); + BL_WR_REG(DMAChs, DMA_TOP_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief DMA channel init - * - * @param chCfg: DMA configuration - * - * @return None - * -*******************************************************************************/ -void DMA_Channel_Init(DMA_Channel_Cfg_Type *chCfg) -{ - uint32_t tmpVal; - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(chCfg->ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(chCfg->ch)); - CHECK_PARAM(IS_DMA_TRANS_WIDTH_TYPE(chCfg->srcTransfWidth)); - CHECK_PARAM(IS_DMA_TRANS_WIDTH_TYPE(chCfg->dstTransfWidth)); - CHECK_PARAM(IS_DMA_BURST_SIZE_TYPE(chCfg->srcBurstSzie)); - CHECK_PARAM(IS_DMA_BURST_SIZE_TYPE(chCfg->dstBurstSzie)); - CHECK_PARAM(IS_DMA_TRANS_DIR_TYPE(chCfg->dir)); - CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(chCfg->dstPeriph)); - CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(chCfg->srcPeriph)); - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_DMA); - - /* Config channel config */ - BL_WR_REG(DMAChs, DMA_SRCADDR, chCfg->srcDmaAddr); - BL_WR_REG(DMAChs, DMA_DSTADDR, chCfg->destDmaAddr); - - tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_TRANSFERSIZE, chCfg->transfLength); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SWIDTH, chCfg->srcTransfWidth); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DWIDTH, chCfg->dstTransfWidth); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SBSIZE, chCfg->srcBurstSzie); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DBSIZE, chCfg->dstBurstSzie); - - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DST_ADD_MODE, chCfg->dstAddMode); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DST_MIN_MODE, chCfg->dstMinMode); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_FIX_CNT, chCfg->fixCnt); - - /* FIXME: how to deal with SLargerD */ - tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_SLARGERD); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SI, chCfg->srcAddrInc); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DI, chCfg->destAddrInc); - BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); - - tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_FLOWCNTRL, chCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DSTPERIPHERAL, chCfg->dstPeriph); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SRCPERIPHERAL, chCfg->srcPeriph); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + * @brief DMA channel init + * + * @param chCfg: DMA configuration + * + * @return None + * + *******************************************************************************/ +void DMA_Channel_Init(DMA_Channel_Cfg_Type *chCfg) { + uint32_t tmpVal; + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(chCfg->ch); + + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(chCfg->ch)); + CHECK_PARAM(IS_DMA_TRANS_WIDTH_TYPE(chCfg->srcTransfWidth)); + CHECK_PARAM(IS_DMA_TRANS_WIDTH_TYPE(chCfg->dstTransfWidth)); + CHECK_PARAM(IS_DMA_BURST_SIZE_TYPE(chCfg->srcBurstSzie)); + CHECK_PARAM(IS_DMA_BURST_SIZE_TYPE(chCfg->dstBurstSzie)); + CHECK_PARAM(IS_DMA_TRANS_DIR_TYPE(chCfg->dir)); + CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(chCfg->dstPeriph)); + CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(chCfg->srcPeriph)); + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_DMA); + + /* Config channel config */ + BL_WR_REG(DMAChs, DMA_SRCADDR, chCfg->srcDmaAddr); + BL_WR_REG(DMAChs, DMA_DSTADDR, chCfg->destDmaAddr); + + tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_TRANSFERSIZE, chCfg->transfLength); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SWIDTH, chCfg->srcTransfWidth); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DWIDTH, chCfg->dstTransfWidth); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SBSIZE, chCfg->srcBurstSzie); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DBSIZE, chCfg->dstBurstSzie); + + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DST_ADD_MODE, chCfg->dstAddMode); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DST_MIN_MODE, chCfg->dstMinMode); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_FIX_CNT, chCfg->fixCnt); + + /* FIXME: how to deal with SLargerD */ + tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_SLARGERD); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SI, chCfg->srcAddrInc); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DI, chCfg->destAddrInc); + BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); + + tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_FLOWCNTRL, chCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DSTPERIPHERAL, chCfg->dstPeriph); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SRCPERIPHERAL, chCfg->srcPeriph); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief DMA channel update source memory address and len - * - * @param ch: DMA channel - * @param memAddr: source memoty address - * @param len: source memory data length - * - * @return None - * -*******************************************************************************/ -void DMA_Channel_Update_SrcMemcfg(uint8_t ch, uint32_t memAddr, uint32_t len) -{ - uint32_t tmpVal; - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - - /* config channel config*/ - BL_WR_REG(DMAChs, DMA_SRCADDR, memAddr); - tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_TRANSFERSIZE, len); - BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); + * @brief DMA channel update source memory address and len + * + * @param ch: DMA channel + * @param memAddr: source memoty address + * @param len: source memory data length + * + * @return None + * + *******************************************************************************/ +void DMA_Channel_Update_SrcMemcfg(uint8_t ch, uint32_t memAddr, uint32_t len) { + uint32_t tmpVal; + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); + + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + + /* config channel config*/ + BL_WR_REG(DMAChs, DMA_SRCADDR, memAddr); + tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_TRANSFERSIZE, len); + BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); } /****************************************************************************/ /** - * @brief DMA channel update destination memory address and len - * - * @param ch: DMA channel - * @param memAddr: destination memoty address - * @param len: destination memory data length - * - * @return None - * -*******************************************************************************/ -void DMA_Channel_Update_DstMemcfg(uint8_t ch, uint32_t memAddr, uint32_t len) -{ - uint32_t tmpVal; - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - - /* config channel config*/ - BL_WR_REG(DMAChs, DMA_DSTADDR, memAddr); - tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_TRANSFERSIZE, len); - BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); + * @brief DMA channel update destination memory address and len + * + * @param ch: DMA channel + * @param memAddr: destination memoty address + * @param len: destination memory data length + * + * @return None + * + *******************************************************************************/ +void DMA_Channel_Update_DstMemcfg(uint8_t ch, uint32_t memAddr, uint32_t len) { + uint32_t tmpVal; + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); + + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + + /* config channel config*/ + BL_WR_REG(DMAChs, DMA_DSTADDR, memAddr); + tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_TRANSFERSIZE, len); + BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); } /****************************************************************************/ /** - * @brief Get DMA channel tranfersize - * - * @param ch: DMA channel - * - * @return tranfersize size - * -*******************************************************************************/ -uint32_t DMA_Channel_TranferSize(uint8_t ch) -{ - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - - return BL_GET_REG_BITS_VAL(BL_RD_REG(DMAChs, DMA_CONTROL), DMA_TRANSFERSIZE); + * @brief Get DMA channel tranfersize + * + * @param ch: DMA channel + * + * @return tranfersize size + * + *******************************************************************************/ +uint32_t DMA_Channel_TranferSize(uint8_t ch) { + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); + + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + + return BL_GET_REG_BITS_VAL(BL_RD_REG(DMAChs, DMA_CONTROL), DMA_TRANSFERSIZE); } /****************************************************************************/ /** - * @brief Get DMA channel busy status - * - * @param ch: DMA channel - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type DMA_Channel_Is_Busy(uint8_t ch) -{ - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - - return BL_IS_REG_BIT_SET(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_E) == 1 ? SET : RESET; + * @brief Get DMA channel busy status + * + * @param ch: DMA channel + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type DMA_Channel_Is_Busy(uint8_t ch) { + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); + + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + + return BL_IS_REG_BIT_SET(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_E) == 1 ? SET : RESET; } /****************************************************************************/ /** - * @brief DMA enable - * - * @param ch: DMA channel number - * - * @return None - * -*******************************************************************************/ -void DMA_Channel_Enable(uint8_t ch) -{ - uint32_t tmpVal; - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - - tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, DMA_E); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + * @brief DMA enable + * + * @param ch: DMA channel number + * + * @return None + * + *******************************************************************************/ +void DMA_Channel_Enable(uint8_t ch) { + uint32_t tmpVal; + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); + + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + + tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, DMA_E); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief DMA disable - * - * @param ch: DMA channel number - * - * @return None - * -*******************************************************************************/ -void DMA_Channel_Disable(uint8_t ch) -{ - uint32_t tmpVal; - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - - tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_E); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + * @brief DMA disable + * + * @param ch: DMA channel number + * + * @return None + * + *******************************************************************************/ +void DMA_Channel_Disable(uint8_t ch) { + uint32_t tmpVal; + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); + + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + + tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_E); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief DMA init LLI transfer - * - * @param ch: DMA channel number - * @param lliCfg: LLI configuration - * - * @return None - * -*******************************************************************************/ -void DMA_LLI_Init(uint8_t ch, DMA_LLI_Cfg_Type *lliCfg) -{ - uint32_t tmpVal; - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - CHECK_PARAM(IS_DMA_TRANS_DIR_TYPE(lliCfg->dir)); - CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(lliCfg->dstPeriph)); - CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(lliCfg->srcPeriph)); - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_DMA); - - tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_FLOWCNTRL, lliCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DSTPERIPHERAL, lliCfg->dstPeriph); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SRCPERIPHERAL, lliCfg->srcPeriph); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + * @brief DMA init LLI transfer + * + * @param ch: DMA channel number + * @param lliCfg: LLI configuration + * + * @return None + * + *******************************************************************************/ +void DMA_LLI_Init(uint8_t ch, DMA_LLI_Cfg_Type *lliCfg) { + uint32_t tmpVal; + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); + + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + CHECK_PARAM(IS_DMA_TRANS_DIR_TYPE(lliCfg->dir)); + CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(lliCfg->dstPeriph)); + CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(lliCfg->srcPeriph)); + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_DMA); + + tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_FLOWCNTRL, lliCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DSTPERIPHERAL, lliCfg->dstPeriph); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SRCPERIPHERAL, lliCfg->srcPeriph); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief DMA channel update LLI - * - * @param ch: DMA channel number - * @param LLI: LLI addr - * - * @return None - * -*******************************************************************************/ -void DMA_LLI_Update(uint8_t ch, uint32_t LLI) -{ - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - - /* Config channel config */ - //BL_WR_REG(DMAChs, DMA_LLI, LLI); - BL702_MemCpy4((uint32_t *)DMAChs, (uint32_t *)LLI, 4); + * @brief DMA channel update LLI + * + * @param ch: DMA channel number + * @param LLI: LLI addr + * + * @return None + * + *******************************************************************************/ +void DMA_LLI_Update(uint8_t ch, uint32_t LLI) { + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); + + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + + /* Config channel config */ + // BL_WR_REG(DMAChs, DMA_LLI, LLI); + BL702_MemCpy4((uint32_t *)DMAChs, (uint32_t *)LLI, 4); } /****************************************************************************/ /** - * @brief DMA LLI PingPong Structure Start - * - * @param dmaPpStruct: dma pp struct pointer - * @param Ping_Transfer_len: ping len - * @param Pong_Transfer_len: pong len - * - * @return Succrss or not - * -*******************************************************************************/ -BL_Err_Type DMA_LLI_PpStruct_Set_Transfer_Len(DMA_LLI_PP_Struct *dmaPpStruct, uint16_t Ping_Transfer_len, uint16_t Pong_Transfer_len) -{ - struct DMA_Control_Reg dmaCtrlRegVal_temp; - - if (Ping_Transfer_len > 4096 || Pong_Transfer_len > 4096) { - return ERROR; - } - - dmaCtrlRegVal_temp = PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].dmaCtrl; - dmaCtrlRegVal_temp.TransferSize = Ping_Transfer_len; - PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].dmaCtrl = dmaCtrlRegVal_temp; - - dmaCtrlRegVal_temp = PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].dmaCtrl; - dmaCtrlRegVal_temp.TransferSize = Pong_Transfer_len; - PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].dmaCtrl = dmaCtrlRegVal_temp; - - DMA_LLI_Init(dmaPpStruct->dmaChan, dmaPpStruct->DMA_LLI_Cfg); - DMA_LLI_Update(dmaPpStruct->dmaChan, (uint32_t)&PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX]); - - return SUCCESS; + * @brief DMA LLI PingPong Structure Start + * + * @param dmaPpStruct: dma pp struct pointer + * @param Ping_Transfer_len: ping len + * @param Pong_Transfer_len: pong len + * + * @return Succrss or not + * + *******************************************************************************/ +BL_Err_Type DMA_LLI_PpStruct_Set_Transfer_Len(DMA_LLI_PP_Struct *dmaPpStruct, uint16_t Ping_Transfer_len, uint16_t Pong_Transfer_len) { + struct DMA_Control_Reg dmaCtrlRegVal_temp; + + if (Ping_Transfer_len > 4096 || Pong_Transfer_len > 4096) { + return ERROR; + } + + dmaCtrlRegVal_temp = PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].dmaCtrl; + dmaCtrlRegVal_temp.TransferSize = Ping_Transfer_len; + PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].dmaCtrl = dmaCtrlRegVal_temp; + + dmaCtrlRegVal_temp = PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].dmaCtrl; + dmaCtrlRegVal_temp.TransferSize = Pong_Transfer_len; + PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].dmaCtrl = dmaCtrlRegVal_temp; + + DMA_LLI_Init(dmaPpStruct->dmaChan, dmaPpStruct->DMA_LLI_Cfg); + DMA_LLI_Update(dmaPpStruct->dmaChan, (uint32_t)&PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX]); + + return SUCCESS; } /****************************************************************************/ /** - * @brief DMA LLI Start New Transmit for Ping-Pong Buf - * - * @param dmaPpBuf: DMA LLI Ping-Pong Buf - * - * @return None - * -*******************************************************************************/ -void DMA_LLI_PpBuf_Start_New_Transmit(DMA_LLI_PP_Buf *dmaPpBuf) -{ - CPU_Interrupt_Disable(DMA_ALL_IRQn); - - if (dmaPpBuf->lliListHeader[dmaPpBuf->idleIndex] != NULL) { - DMA_LLI_Update(dmaPpBuf->dmaChan, (uint32_t)dmaPpBuf->lliListHeader[dmaPpBuf->idleIndex]); - DMA_Channel_Enable(dmaPpBuf->dmaChan); - dmaPpBuf->idleIndex = (dmaPpBuf->idleIndex == 0) ? 1 : 0; - } - - CPU_Interrupt_Enable(DMA_ALL_IRQn); + * @brief DMA LLI Start New Transmit for Ping-Pong Buf + * + * @param dmaPpBuf: DMA LLI Ping-Pong Buf + * + * @return None + * + *******************************************************************************/ +void DMA_LLI_PpBuf_Start_New_Transmit(DMA_LLI_PP_Buf *dmaPpBuf) { + CPU_Interrupt_Disable(DMA_ALL_IRQn); + + if (dmaPpBuf->lliListHeader[dmaPpBuf->idleIndex] != NULL) { + DMA_LLI_Update(dmaPpBuf->dmaChan, (uint32_t)dmaPpBuf->lliListHeader[dmaPpBuf->idleIndex]); + DMA_Channel_Enable(dmaPpBuf->dmaChan); + dmaPpBuf->idleIndex = (dmaPpBuf->idleIndex == 0) ? 1 : 0; + } + + CPU_Interrupt_Enable(DMA_ALL_IRQn); } /****************************************************************************/ /** - * @brief DMA LLI Remove Completed Ping-Pong Buf List - * - * @param dmaPpBuf: DMA LLI Ping-Pong Buf - * - * @return Next Ping-Pong Buf List Header - * -*******************************************************************************/ -DMA_LLI_Ctrl_Type *DMA_LLI_PpBuf_Remove_Completed_List(DMA_LLI_PP_Buf *dmaPpBuf) -{ - CPU_Interrupt_Disable(DMA_ALL_IRQn); - - dmaPpBuf->lliListHeader[!dmaPpBuf->idleIndex] = NULL; - CPU_Interrupt_Enable(DMA_ALL_IRQn); - return dmaPpBuf->lliListHeader[!dmaPpBuf->idleIndex]; + * @brief DMA LLI Remove Completed Ping-Pong Buf List + * + * @param dmaPpBuf: DMA LLI Ping-Pong Buf + * + * @return Next Ping-Pong Buf List Header + * + *******************************************************************************/ +DMA_LLI_Ctrl_Type *DMA_LLI_PpBuf_Remove_Completed_List(DMA_LLI_PP_Buf *dmaPpBuf) { + CPU_Interrupt_Disable(DMA_ALL_IRQn); + + dmaPpBuf->lliListHeader[!dmaPpBuf->idleIndex] = NULL; + CPU_Interrupt_Enable(DMA_ALL_IRQn); + return dmaPpBuf->lliListHeader[!dmaPpBuf->idleIndex]; } /****************************************************************************/ /** - * @brief DMA LLI Append Buf to List - * - * @param dmaPpBuf: DMA LLI Ping-Pong Buf - * @param dmaLliList: New LLI Buf to Append - * - * @return None - * -*******************************************************************************/ -void DMA_LLI_PpBuf_Append(DMA_LLI_PP_Buf *dmaPpBuf, DMA_LLI_Ctrl_Type *dmaLliList) -{ - DMA_LLI_Ctrl_Type *pLliList = NULL; - CPU_Interrupt_Disable(DMA_ALL_IRQn); - - pLliList = dmaPpBuf->lliListHeader[dmaPpBuf->idleIndex]; - - if (pLliList == NULL) { - dmaLliList->nextLLI = 0; - dmaLliList->dmaCtrl.I = 1; - dmaPpBuf->lliListHeader[dmaPpBuf->idleIndex] = dmaLliList; - } else { - /*Append to last */ - while (pLliList->nextLLI != 0) { - pLliList = (DMA_LLI_Ctrl_Type *)pLliList->nextLLI; - } - - pLliList->nextLLI = (uint32_t)dmaLliList; - pLliList->dmaCtrl.I = 0; - dmaLliList->nextLLI = 0; - dmaLliList->dmaCtrl.I = 1; + * @brief DMA LLI Append Buf to List + * + * @param dmaPpBuf: DMA LLI Ping-Pong Buf + * @param dmaLliList: New LLI Buf to Append + * + * @return None + * + *******************************************************************************/ +void DMA_LLI_PpBuf_Append(DMA_LLI_PP_Buf *dmaPpBuf, DMA_LLI_Ctrl_Type *dmaLliList) { + DMA_LLI_Ctrl_Type *pLliList = NULL; + CPU_Interrupt_Disable(DMA_ALL_IRQn); + + pLliList = dmaPpBuf->lliListHeader[dmaPpBuf->idleIndex]; + + if (pLliList == NULL) { + dmaLliList->nextLLI = 0; + dmaLliList->dmaCtrl.I = 1; + dmaPpBuf->lliListHeader[dmaPpBuf->idleIndex] = dmaLliList; + } else { + /*Append to last */ + while (pLliList->nextLLI != 0) { + pLliList = (DMA_LLI_Ctrl_Type *)pLliList->nextLLI; } - if (DMA_Channel_Is_Busy(dmaPpBuf->dmaChan) == RESET) { - /* DMA stopped: maybe stop just a few minutes ago(not enter INT due to CPU_Interrupt_Disable) - or has already stopped before this function is called */ - if (dmaPpBuf->lliListHeader[!dmaPpBuf->idleIndex] == NULL) { - /* DMA has already stopped before this function is called */ - DMA_LLI_PpBuf_Start_New_Transmit(dmaPpBuf); - } + pLliList->nextLLI = (uint32_t)dmaLliList; + pLliList->dmaCtrl.I = 0; + dmaLliList->nextLLI = 0; + dmaLliList->dmaCtrl.I = 1; + } + + if (DMA_Channel_Is_Busy(dmaPpBuf->dmaChan) == RESET) { + /* DMA stopped: maybe stop just a few minutes ago(not enter INT due to CPU_Interrupt_Disable) + or has already stopped before this function is called */ + if (dmaPpBuf->lliListHeader[!dmaPpBuf->idleIndex] == NULL) { + /* DMA has already stopped before this function is called */ + DMA_LLI_PpBuf_Start_New_Transmit(dmaPpBuf); } + } - CPU_Interrupt_Enable(DMA_ALL_IRQn); + CPU_Interrupt_Enable(DMA_ALL_IRQn); } /****************************************************************************/ /** - * @brief DMA LLi Destroy Ping-Pong Buf - * - * @param dmaPpBuf: DMA LLI Ping-Pong Buf - * - * @return None - * -*******************************************************************************/ -void DMA_LLI_PpBuf_Destroy(DMA_LLI_PP_Buf *dmaPpBuf) -{ - /* DMA LLI Disable */ - DMA_Channel_Disable(dmaPpBuf->dmaChan); - - if (dmaPpBuf->lliListHeader[0] != NULL && dmaPpBuf->onTransCompleted != NULL) { - dmaPpBuf->onTransCompleted(dmaPpBuf->lliListHeader[0]); - } - - dmaPpBuf->lliListHeader[0] = NULL; - - if (dmaPpBuf->lliListHeader[1] != NULL && dmaPpBuf->onTransCompleted != NULL) { - dmaPpBuf->onTransCompleted(dmaPpBuf->lliListHeader[1]); - } - - dmaPpBuf->lliListHeader[1] = NULL; - dmaPpBuf->idleIndex = 0; + * @brief DMA LLi Destroy Ping-Pong Buf + * + * @param dmaPpBuf: DMA LLI Ping-Pong Buf + * + * @return None + * + *******************************************************************************/ +void DMA_LLI_PpBuf_Destroy(DMA_LLI_PP_Buf *dmaPpBuf) { + /* DMA LLI Disable */ + DMA_Channel_Disable(dmaPpBuf->dmaChan); + + if (dmaPpBuf->lliListHeader[0] != NULL && dmaPpBuf->onTransCompleted != NULL) { + dmaPpBuf->onTransCompleted(dmaPpBuf->lliListHeader[0]); + } + + dmaPpBuf->lliListHeader[0] = NULL; + + if (dmaPpBuf->lliListHeader[1] != NULL && dmaPpBuf->onTransCompleted != NULL) { + dmaPpBuf->onTransCompleted(dmaPpBuf->lliListHeader[1]); + } + + dmaPpBuf->lliListHeader[1] = NULL; + dmaPpBuf->idleIndex = 0; } /****************************************************************************/ /** - * @brief Mask/Unmask the DMA interrupt - * - * @param ch: DMA channel number - * @param intType: Specifies the interrupt type - * @param intMask: Enable/Disable Specified interrupt type - * - * @return None - * -*******************************************************************************/ -void DMA_IntMask(uint8_t ch, DMA_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - CHECK_PARAM(IS_DMA_INT_TYPE(intType)); - - switch (intType) { - case DMA_INT_TCOMPLETED: - if (intMask == UNMASK) { - /* UNMASK(Enable) this interrupt */ - tmpVal = BL_CLR_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_ITC); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); - tmpVal = BL_SET_REG_BIT(BL_RD_REG(DMAChs, DMA_CONTROL), DMA_I); - BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); - } else { - /* MASK(Disable) this interrupt */ - tmpVal = BL_SET_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_ITC); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); - tmpVal = BL_CLR_REG_BIT(BL_RD_REG(DMAChs, DMA_CONTROL), DMA_I); - BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); - } - - break; - - case DMA_INT_ERR: - if (intMask == UNMASK) { - /* UNMASK(Enable) this interrupt */ - tmpVal = BL_CLR_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_IE); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); - } else { - /* MASK(Disable) this interrupt */ - tmpVal = BL_SET_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_IE); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); - } - - break; - - case DMA_INT_ALL: - if (intMask == UNMASK) { - /* UNMASK(Enable) this interrupt */ - tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_ITC); - tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_IE); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); - tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); - tmpVal = BL_SET_REG_BIT(tmpVal, DMA_I); - BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); - } else { - /* MASK(Disable) this interrupt */ - tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, DMA_ITC); - tmpVal = BL_SET_REG_BIT(tmpVal, DMA_IE); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); - tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); - tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_I); - BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); - } - - break; - - default: - break; + * @brief Mask/Unmask the DMA interrupt + * + * @param ch: DMA channel number + * @param intType: Specifies the interrupt type + * @param intMask: Enable/Disable Specified interrupt type + * + * @return None + * + *******************************************************************************/ +void DMA_IntMask(uint8_t ch, DMA_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); + + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + CHECK_PARAM(IS_DMA_INT_TYPE(intType)); + + switch (intType) { + case DMA_INT_TCOMPLETED: + if (intMask == UNMASK) { + /* UNMASK(Enable) this interrupt */ + tmpVal = BL_CLR_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_ITC); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + tmpVal = BL_SET_REG_BIT(BL_RD_REG(DMAChs, DMA_CONTROL), DMA_I); + BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); + } else { + /* MASK(Disable) this interrupt */ + tmpVal = BL_SET_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_ITC); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + tmpVal = BL_CLR_REG_BIT(BL_RD_REG(DMAChs, DMA_CONTROL), DMA_I); + BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); } -} -/****************************************************************************/ /** - * @brief Install DMA interrupt callback function - * - * @param dmaChan: DMA Channel type - * @param intType: DMA interrupt type - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return None - * -*******************************************************************************/ -void DMA_Int_Callback_Install(DMA_Chan_Type dmaChan, DMA_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(dmaChan)); - CHECK_PARAM(IS_DMA_INT_TYPE(intType)); - - dmaIntCbfArra[dmaChan][intType] = cbFun; -} + break; -/****************************************************************************/ /** - * @brief DMA LLI PingPong Structure Initial - * - * @param dmaPpStruct: DMA LLI PingPong Config Parameter - * - * @return start success or not - * -*******************************************************************************/ -BL_Err_Type DMA_LLI_PpStruct_Init(DMA_LLI_PP_Struct *dmaPpStruct) -{ - //setup lliList - dmaPpStruct->dmaCtrlRegVal.I = 1; - dmaPpStruct->trans_index = 0; - - if (dmaPpStruct->DMA_LLI_Cfg->dir == DMA_TRNS_M2P) { - PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].srcDmaAddr = dmaPpStruct->chache_buf_addr[0]; - PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].destDmaAddr = dmaPpStruct->operatePeriphAddr; - - PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].srcDmaAddr = dmaPpStruct->chache_buf_addr[1]; - PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].destDmaAddr = dmaPpStruct->operatePeriphAddr; - } else if (dmaPpStruct->DMA_LLI_Cfg->dir == DMA_TRNS_P2M) { - PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].srcDmaAddr = dmaPpStruct->operatePeriphAddr; - PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].destDmaAddr = dmaPpStruct->chache_buf_addr[0]; - - PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].srcDmaAddr = dmaPpStruct->operatePeriphAddr; - PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].destDmaAddr = dmaPpStruct->chache_buf_addr[1]; + case DMA_INT_ERR: + if (intMask == UNMASK) { + /* UNMASK(Enable) this interrupt */ + tmpVal = BL_CLR_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_IE); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); } else { - return ERROR; - /*V1.0 version DMA LLI Ping-Pong structure not support P2P & M2M MODE*/ + /* MASK(Disable) this interrupt */ + tmpVal = BL_SET_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_IE); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); } - PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].nextLLI = (uint32_t)&PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX]; - PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].dmaCtrl = dmaPpStruct->dmaCtrlRegVal; - - PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].nextLLI = (uint32_t)&PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX]; - PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].dmaCtrl = dmaPpStruct->dmaCtrlRegVal; - - DMA_LLI_Init(dmaPpStruct->dmaChan, dmaPpStruct->DMA_LLI_Cfg); + break; + + case DMA_INT_ALL: + if (intMask == UNMASK) { + /* UNMASK(Enable) this interrupt */ + tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_ITC); + tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_IE); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); + tmpVal = BL_SET_REG_BIT(tmpVal, DMA_I); + BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); + } else { + /* MASK(Disable) this interrupt */ + tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, DMA_ITC); + tmpVal = BL_SET_REG_BIT(tmpVal, DMA_IE); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); + tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_I); + BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); + } - DMA_LLI_Update(dmaPpStruct->dmaChan, (uint32_t)&PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX]); + break; - return SUCCESS; + default: + break; + } } /****************************************************************************/ /** - * @brief DMA LLI PingPong Structure Start - * - * @param dmaPpStruct: None - * - * @return None - * -*******************************************************************************/ -void DMA_LLI_PpStruct_Start(DMA_LLI_PP_Struct *dmaPpStruct) -{ - DMA_Channel_Enable(dmaPpStruct->dmaChan); + * @brief Install DMA interrupt callback function + * + * @param dmaChan: DMA Channel type + * @param intType: DMA interrupt type + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return None + * + *******************************************************************************/ +void DMA_Int_Callback_Install(DMA_Chan_Type dmaChan, DMA_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(dmaChan)); + CHECK_PARAM(IS_DMA_INT_TYPE(intType)); + + dmaIntCbfArra[dmaChan][intType] = cbFun; } /****************************************************************************/ /** - * @brief DMA LLI PingPong Structure Stop - * - * @param dmaPpStruct: None - * - * @return None - * -*******************************************************************************/ -void DMA_LLI_PpStruct_Stop(DMA_LLI_PP_Struct *dmaPpStruct) -{ - DMA_Channel_Disable(dmaPpStruct->dmaChan); + * @brief DMA LLI PingPong Structure Initial + * + * @param dmaPpStruct: DMA LLI PingPong Config Parameter + * + * @return start success or not + * + *******************************************************************************/ +BL_Err_Type DMA_LLI_PpStruct_Init(DMA_LLI_PP_Struct *dmaPpStruct) { + // setup lliList + dmaPpStruct->dmaCtrlRegVal.I = 1; + dmaPpStruct->trans_index = 0; + + if (dmaPpStruct->DMA_LLI_Cfg->dir == DMA_TRNS_M2P) { + PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].srcDmaAddr = dmaPpStruct->chache_buf_addr[0]; + PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].destDmaAddr = dmaPpStruct->operatePeriphAddr; + + PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].srcDmaAddr = dmaPpStruct->chache_buf_addr[1]; + PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].destDmaAddr = dmaPpStruct->operatePeriphAddr; + } else if (dmaPpStruct->DMA_LLI_Cfg->dir == DMA_TRNS_P2M) { + PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].srcDmaAddr = dmaPpStruct->operatePeriphAddr; + PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].destDmaAddr = dmaPpStruct->chache_buf_addr[0]; + + PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].srcDmaAddr = dmaPpStruct->operatePeriphAddr; + PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].destDmaAddr = dmaPpStruct->chache_buf_addr[1]; + } else { + return ERROR; + /*V1.0 version DMA LLI Ping-Pong structure not support P2P & M2M MODE*/ + } + + PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].nextLLI = (uint32_t)&PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX]; + PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].dmaCtrl = dmaPpStruct->dmaCtrlRegVal; + + PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].nextLLI = (uint32_t)&PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX]; + PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].dmaCtrl = dmaPpStruct->dmaCtrlRegVal; + + DMA_LLI_Init(dmaPpStruct->dmaChan, dmaPpStruct->DMA_LLI_Cfg); + + DMA_LLI_Update(dmaPpStruct->dmaChan, (uint32_t)&PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX]); + + return SUCCESS; } +/****************************************************************************/ /** + * @brief DMA LLI PingPong Structure Start + * + * @param dmaPpStruct: None + * + * @return None + * + *******************************************************************************/ +void DMA_LLI_PpStruct_Start(DMA_LLI_PP_Struct *dmaPpStruct) { DMA_Channel_Enable(dmaPpStruct->dmaChan); } + +/****************************************************************************/ /** + * @brief DMA LLI PingPong Structure Stop + * + * @param dmaPpStruct: None + * + * @return None + * + *******************************************************************************/ +void DMA_LLI_PpStruct_Stop(DMA_LLI_PP_Struct *dmaPpStruct) { DMA_Channel_Disable(dmaPpStruct->dmaChan); } + /*@} end of group DMA_Public_Functions */ /*@} end of group DMA */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_emac.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_emac.c index 662ac30914..5e9e5c0438 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_emac.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_emac.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_emac.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_emac.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "bl702.h" #include "bl702_emac.h" +#include "bl702.h" #include "bl702_glb.h" /** @addtogroup BL702_Peripheral_Driver @@ -62,7 +62,7 @@ /** @defgroup EMAC_Private_Variables * @{ */ -static intCallback_Type *emacIntCbfArra[EMAC_INT_CNT] = { NULL }; +static intCallback_Type *emacIntCbfArra[EMAC_INT_CNT] = {NULL}; /*@} end of group EMAC_Private_Variables */ @@ -83,123 +83,118 @@ static intCallback_Type *emacIntCbfArra[EMAC_INT_CNT] = { NULL }; */ /****************************************************************************/ /** - * @brief Set MAC Address - * - * @param macAddr[6]: MAC address buffer array - * - * @return None - * -*******************************************************************************/ -static void EMAC_SetMACAddress(uint8_t macAddr[6]) -{ - BL_WR_REG(EMAC_BASE, EMAC_MAC_ADDR1, (macAddr[0] << 8) | macAddr[1]); - BL_WR_REG(EMAC_BASE, EMAC_MAC_ADDR0, (macAddr[2] << 24) | (macAddr[3] << 16) | (macAddr[4] << 8) | (macAddr[5] << 0)); + * @brief Set MAC Address + * + * @param macAddr[6]: MAC address buffer array + * + * @return None + * + *******************************************************************************/ +static void EMAC_SetMACAddress(uint8_t macAddr[6]) { + BL_WR_REG(EMAC_BASE, EMAC_MAC_ADDR1, (macAddr[0] << 8) | macAddr[1]); + BL_WR_REG(EMAC_BASE, EMAC_MAC_ADDR0, (macAddr[2] << 24) | (macAddr[3] << 16) | (macAddr[4] << 8) | (macAddr[5] << 0)); } /****************************************************************************/ /** - * @brief Set PHY Address - * - * @param phyAddress: Phy address - * - * @return None - * -*******************************************************************************/ -void EMAC_Phy_SetAddress(uint16_t phyAddress) -{ - uint32_t tmpVal; - - /* Set Phy Address */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIADDRESS); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_FIAD, phyAddress); - BL_WR_REG(EMAC_BASE, EMAC_MIIADDRESS, tmpVal); + * @brief Set PHY Address + * + * @param phyAddress: Phy address + * + * @return None + * + *******************************************************************************/ +void EMAC_Phy_SetAddress(uint16_t phyAddress) { + uint32_t tmpVal; + + /* Set Phy Address */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIADDRESS); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_FIAD, phyAddress); + BL_WR_REG(EMAC_BASE, EMAC_MIIADDRESS, tmpVal); } /****************************************************************************/ /** - * @brief Set PHY Address - * - * @param phyAddress: Phy address - * - * @return None - * -*******************************************************************************/ -void EMAC_Phy_Set_Full_Duplex(uint8_t fullDuplex) -{ - uint32_t tmpVal; - - /* Set MAC duplex config */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_FULLD, fullDuplex); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); + * @brief Set PHY Address + * + * @param phyAddress: Phy address + * + * @return None + * + *******************************************************************************/ +void EMAC_Phy_Set_Full_Duplex(uint8_t fullDuplex) { + uint32_t tmpVal; + + /* Set MAC duplex config */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_FULLD, fullDuplex); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); } /****************************************************************************/ /** - * @brief Read PHY register - * - * @param phyReg: PHY register - * @param regValue: PHY register value pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Phy_Read(uint16_t phyReg, uint16_t *regValue) -{ - uint32_t tmpVal; - - /* Set Register Address */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIADDRESS); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RGAD, phyReg); - BL_WR_REG(EMAC_BASE, EMAC_MIIADDRESS, tmpVal); - - /* Trigger read */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIICOMMAND); - tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_RSTAT); - BL_WR_REG(EMAC_BASE, EMAC_MIICOMMAND, tmpVal); - - BL_DRV_DUMMY; - - do { - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIISTATUS); - BL702_Delay_US(16); - } while (BL_IS_REG_BIT_SET(tmpVal, EMAC_MIIM_BUSY)); - - *regValue = BL_RD_REG(EMAC_BASE, EMAC_MIIRX_DATA); - - return SUCCESS; + * @brief Read PHY register + * + * @param phyReg: PHY register + * @param regValue: PHY register value pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Phy_Read(uint16_t phyReg, uint16_t *regValue) { + uint32_t tmpVal; + + /* Set Register Address */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIADDRESS); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RGAD, phyReg); + BL_WR_REG(EMAC_BASE, EMAC_MIIADDRESS, tmpVal); + + /* Trigger read */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIICOMMAND); + tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_RSTAT); + BL_WR_REG(EMAC_BASE, EMAC_MIICOMMAND, tmpVal); + + BL_DRV_DUMMY; + + do { + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIISTATUS); + BL702_Delay_US(16); + } while (BL_IS_REG_BIT_SET(tmpVal, EMAC_MIIM_BUSY)); + + *regValue = BL_RD_REG(EMAC_BASE, EMAC_MIIRX_DATA); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Write PHY register - * - * @param phyReg: PHY register - * @param regValue: PHY register value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Phy_Write(uint16_t phyReg, uint16_t regValue) -{ - uint32_t tmpVal; - - /* Set Register Address */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIADDRESS); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RGAD, phyReg); - BL_WR_REG(EMAC_BASE, EMAC_MIIADDRESS, tmpVal); - - /* Set Write data */ - BL_WR_REG(EMAC_BASE, EMAC_MIITX_DATA, regValue); - - /* Trigger write */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIICOMMAND); - tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_WCTRLDATA); - BL_WR_REG(EMAC_BASE, EMAC_MIICOMMAND, tmpVal); - - BL_DRV_DUMMY; - - do { - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIISTATUS); - } while (BL_IS_REG_BIT_SET(tmpVal, EMAC_MIIM_BUSY)); - - return SUCCESS; + * @brief Write PHY register + * + * @param phyReg: PHY register + * @param regValue: PHY register value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Phy_Write(uint16_t phyReg, uint16_t regValue) { + uint32_t tmpVal; + + /* Set Register Address */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIADDRESS); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RGAD, phyReg); + BL_WR_REG(EMAC_BASE, EMAC_MIIADDRESS, tmpVal); + + /* Set Write data */ + BL_WR_REG(EMAC_BASE, EMAC_MIITX_DATA, regValue); + + /* Trigger write */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIICOMMAND); + tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_WCTRLDATA); + BL_WR_REG(EMAC_BASE, EMAC_MIICOMMAND, tmpVal); + + BL_DRV_DUMMY; + + do { + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIISTATUS); + } while (BL_IS_REG_BIT_SET(tmpVal, EMAC_MIIM_BUSY)); + + return SUCCESS; } /*@} end of group EMAC_Private_Functions */ @@ -209,475 +204,451 @@ BL_Err_Type EMAC_Phy_Write(uint16_t phyReg, uint16_t regValue) */ /****************************************************************************/ /** - * @brief Initialize EMAC module - * - * @param cfg: EMAC configuration pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Init(EMAC_CFG_Type *cfg) -{ - uint32_t tmpVal; - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_EMAC); - - /* Set MAC config */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RMII_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RECSMALL, cfg->recvSmallFrame); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_PAD, cfg->padEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_HUGEN, cfg->recvHugeFrame); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_CRCEN, cfg->crcEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_NOPRE, cfg->noPreamble); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_BRO, cfg->recvBroadCast); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_PRO, ENABLE); - //tmpVal |= (1 << 7); /* local loopback in emac */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_IFG, cfg->interFrameGapCheck); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); - - /* Set inter frame gap value */ - BL_WR_REG(EMAC_BASE, EMAC_IPGT, cfg->interFrameGapValue); - - /* Set MII interface */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIMODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MIINOPRE, cfg->miiNoPreamble); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_CLKDIV, cfg->miiClkDiv); - BL_WR_REG(EMAC_BASE, EMAC_MIIMODE, tmpVal); - - /* Set collision */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_COLLCONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MAXRET, cfg->maxTxRetry); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_COLLVALID, cfg->collisionValid); - BL_WR_REG(EMAC_BASE, EMAC_COLLCONFIG, tmpVal); - - /* Set frame length */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_PACKETLEN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MINFL, cfg->minFrameLen); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MAXFL, cfg->maxFrameLen); - BL_WR_REG(EMAC_BASE, EMAC_PACKETLEN, tmpVal); - - EMAC_SetMACAddress(cfg->macAddr); - - void EMAC_IRQHandler(void); - Interrupt_Handler_Register(EMAC_IRQn, EMAC_IRQHandler); - - return SUCCESS; + * @brief Initialize EMAC module + * + * @param cfg: EMAC configuration pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Init(EMAC_CFG_Type *cfg) { + uint32_t tmpVal; + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_EMAC); + + /* Set MAC config */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RMII_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RECSMALL, cfg->recvSmallFrame); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_PAD, cfg->padEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_HUGEN, cfg->recvHugeFrame); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_CRCEN, cfg->crcEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_NOPRE, cfg->noPreamble); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_BRO, cfg->recvBroadCast); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_PRO, ENABLE); + // tmpVal |= (1 << 7); /* local loopback in emac */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_IFG, cfg->interFrameGapCheck); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); + + /* Set inter frame gap value */ + BL_WR_REG(EMAC_BASE, EMAC_IPGT, cfg->interFrameGapValue); + + /* Set MII interface */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIMODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MIINOPRE, cfg->miiNoPreamble); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_CLKDIV, cfg->miiClkDiv); + BL_WR_REG(EMAC_BASE, EMAC_MIIMODE, tmpVal); + + /* Set collision */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_COLLCONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MAXRET, cfg->maxTxRetry); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_COLLVALID, cfg->collisionValid); + BL_WR_REG(EMAC_BASE, EMAC_COLLCONFIG, tmpVal); + + /* Set frame length */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_PACKETLEN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MINFL, cfg->minFrameLen); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MAXFL, cfg->maxFrameLen); + BL_WR_REG(EMAC_BASE, EMAC_PACKETLEN, tmpVal); + + EMAC_SetMACAddress(cfg->macAddr); + + void EMAC_IRQHandler(void); + Interrupt_Handler_Register(EMAC_IRQn, EMAC_IRQHandler); + + return SUCCESS; } /****************************************************************************/ /** - * @brief DeInitialize EMAC module - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_DeInit(void) -{ - EMAC_Disable(); - - return SUCCESS; + * @brief DeInitialize EMAC module + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_DeInit(void) { + EMAC_Disable(); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Initialize EMAC TX RX MDA buffer - * - * @param handle: EMAC handle pointer - * @param txBuff: TX buffer - * @param txBuffCount: TX buffer count - * @param rxBuff: RX buffer - * @param rxBuffCount: RX buffer count - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_DMADescListInit(EMAC_Handle_Type *handle, uint8_t *txBuff, uint32_t txBuffCount, uint8_t *rxBuff, uint32_t rxBuffCount) -{ - uint32_t i = 0; - - /* Set the Ethernet handler env */ - handle->bd = (EMAC_BD_Desc_Type *)(EMAC_BASE + EMAC_DMA_DESC_OFFSET); - handle->txIndexEMAC = 0; - handle->txIndexCPU = 0; - handle->txBuffLimit = txBuffCount - 1; - /* The receive descriptors' address starts right after the last transmit BD. */ - handle->rxIndexEMAC = txBuffCount; - handle->rxIndexCPU = txBuffCount; - handle->rxBuffLimit = txBuffCount + rxBuffCount - 1; - - /* Fill each DMARxDesc descriptor with the right values */ - for (i = 0; i < txBuffCount; i++) { - /* Get the pointer on the ith member of the Tx Desc list */ - handle->bd[i].Buffer = (NULL == txBuff) ? 0 : (uint32_t)(txBuff + (ETH_MAX_PACKET_SIZE * i)); - handle->bd[i].C_S_L = 0; - } - - /* For the last TX DMA Descriptor, it should be wrap back */ - handle->bd[handle->txBuffLimit].C_S_L |= EMAC_BD_FIELD_MSK(TX_WR); - - for (i = txBuffCount; i < (txBuffCount + rxBuffCount); i++) { - /* Get the pointer on the ith member of the Rx Desc list */ - handle->bd[i].Buffer = (NULL == rxBuff) ? 0 : (uint32_t)(rxBuff + (ETH_MAX_PACKET_SIZE * (i - txBuffCount))); - handle->bd[i].C_S_L = (ETH_MAX_PACKET_SIZE << 16) | - EMAC_BD_FIELD_MSK(RX_IRQ) | - EMAC_BD_FIELD_MSK(RX_E); - } - - /* For the last RX DMA Descriptor, it should be wrap back */ - handle->bd[handle->rxBuffLimit].C_S_L |= EMAC_BD_FIELD_MSK(RX_WR); - - /* For the TX DMA Descriptor, it will wrap to 0 according to EMAC_TX_BD_NUM*/ - BL_WR_REG(EMAC_BASE, EMAC_TX_BD_NUM, txBuffCount); - - return SUCCESS; + * @brief Initialize EMAC TX RX MDA buffer + * + * @param handle: EMAC handle pointer + * @param txBuff: TX buffer + * @param txBuffCount: TX buffer count + * @param rxBuff: RX buffer + * @param rxBuffCount: RX buffer count + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_DMADescListInit(EMAC_Handle_Type *handle, uint8_t *txBuff, uint32_t txBuffCount, uint8_t *rxBuff, uint32_t rxBuffCount) { + uint32_t i = 0; + + /* Set the Ethernet handler env */ + handle->bd = (EMAC_BD_Desc_Type *)(EMAC_BASE + EMAC_DMA_DESC_OFFSET); + handle->txIndexEMAC = 0; + handle->txIndexCPU = 0; + handle->txBuffLimit = txBuffCount - 1; + /* The receive descriptors' address starts right after the last transmit BD. */ + handle->rxIndexEMAC = txBuffCount; + handle->rxIndexCPU = txBuffCount; + handle->rxBuffLimit = txBuffCount + rxBuffCount - 1; + + /* Fill each DMARxDesc descriptor with the right values */ + for (i = 0; i < txBuffCount; i++) { + /* Get the pointer on the ith member of the Tx Desc list */ + handle->bd[i].Buffer = (NULL == txBuff) ? 0 : (uint32_t)(txBuff + (ETH_MAX_PACKET_SIZE * i)); + handle->bd[i].C_S_L = 0; + } + + /* For the last TX DMA Descriptor, it should be wrap back */ + handle->bd[handle->txBuffLimit].C_S_L |= EMAC_BD_FIELD_MSK(TX_WR); + + for (i = txBuffCount; i < (txBuffCount + rxBuffCount); i++) { + /* Get the pointer on the ith member of the Rx Desc list */ + handle->bd[i].Buffer = (NULL == rxBuff) ? 0 : (uint32_t)(rxBuff + (ETH_MAX_PACKET_SIZE * (i - txBuffCount))); + handle->bd[i].C_S_L = (ETH_MAX_PACKET_SIZE << 16) | EMAC_BD_FIELD_MSK(RX_IRQ) | EMAC_BD_FIELD_MSK(RX_E); + } + + /* For the last RX DMA Descriptor, it should be wrap back */ + handle->bd[handle->rxBuffLimit].C_S_L |= EMAC_BD_FIELD_MSK(RX_WR); + + /* For the TX DMA Descriptor, it will wrap to 0 according to EMAC_TX_BD_NUM*/ + BL_WR_REG(EMAC_BASE, EMAC_TX_BD_NUM, txBuffCount); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Get TX MDA buffer descripter for data to send - * - * @param handle: EMAC handle pointer - * @param txDMADesc: TX DMA descriptor pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_DMATxDescGet(EMAC_Handle_Type *handle, EMAC_BD_Desc_Type **txDMADesc) -{ - return SUCCESS; -} + * @brief Get TX MDA buffer descripter for data to send + * + * @param handle: EMAC handle pointer + * @param txDMADesc: TX DMA descriptor pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_DMATxDescGet(EMAC_Handle_Type *handle, EMAC_BD_Desc_Type **txDMADesc) { return SUCCESS; } /****************************************************************************/ /** - * @brief Start TX - * - * @param handle: EMAC handle pointer - * @param txDMADesc: TX DMA descriptor pointer - * @param len: len - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_StartTx(EMAC_Handle_Type *handle, EMAC_BD_Desc_Type *txDMADesc, uint32_t len) -{ - return SUCCESS; -} + * @brief Start TX + * + * @param handle: EMAC handle pointer + * @param txDMADesc: TX DMA descriptor pointer + * @param len: len + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_StartTx(EMAC_Handle_Type *handle, EMAC_BD_Desc_Type *txDMADesc, uint32_t len) { return SUCCESS; } /****************************************************************************/ /** - * @brief Enable EMAC module - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Enable(void) -{ - uint32_t tmpVal; - - /* Enable EMAC */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_TXEN); - tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_RXEN); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); - - return SUCCESS; + * @brief Enable EMAC module + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Enable(void) { + uint32_t tmpVal; + + /* Enable EMAC */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_TXEN); + tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_RXEN); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief EMAC_Enable_TX - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Enable_TX(void) -{ - uint32_t tmpVal; - - /* Enable EMAC */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_TXEN); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); - - return SUCCESS; + * @brief EMAC_Enable_TX + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Enable_TX(void) { + uint32_t tmpVal; + + /* Enable EMAC */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_TXEN); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief EMAC_Disable_TX - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Disable_TX(void) -{ - uint32_t tmpVal; - - /* Enable EMAC */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpVal = BL_CLR_REG_BIT(tmpVal, EMAC_TXEN); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); - - return SUCCESS; + * @brief EMAC_Disable_TX + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Disable_TX(void) { + uint32_t tmpVal; + + /* Enable EMAC */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpVal = BL_CLR_REG_BIT(tmpVal, EMAC_TXEN); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief EMAC_Enable_RX - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Enable_RX(void) -{ - uint32_t tmpval; - - /* Enable EMAC TX*/ - tmpval = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpval = BL_SET_REG_BIT(tmpval, EMAC_RXEN); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpval); - - return SUCCESS; + * @brief EMAC_Enable_RX + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Enable_RX(void) { + uint32_t tmpval; + + /* Enable EMAC TX*/ + tmpval = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpval = BL_SET_REG_BIT(tmpval, EMAC_RXEN); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpval); + + return SUCCESS; } /****************************************************************************/ /** - * @brief EMAC_Disable_RX - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Disable_RX(void) -{ - uint32_t tmpval; - - /* Disable EMAC RX*/ - tmpval = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpval = BL_CLR_REG_BIT(tmpval, EMAC_RXEN); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpval); - - return SUCCESS; + * @brief EMAC_Disable_RX + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Disable_RX(void) { + uint32_t tmpval; + + /* Disable EMAC RX*/ + tmpval = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpval = BL_CLR_REG_BIT(tmpval, EMAC_RXEN); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpval); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Disable EMAC module - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Disable(void) -{ - uint32_t tmpVal; - - /* Enable EMAC */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpVal = BL_CLR_REG_BIT(tmpVal, EMAC_TXEN); - tmpVal = BL_CLR_REG_BIT(tmpVal, EMAC_RXEN); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); - - return SUCCESS; + * @brief Disable EMAC module + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Disable(void) { + uint32_t tmpVal; + + /* Enable EMAC */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpVal = BL_CLR_REG_BIT(tmpVal, EMAC_TXEN); + tmpVal = BL_CLR_REG_BIT(tmpVal, EMAC_RXEN); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief EMAC mask or unmask certain or all interrupt - * - * @param intType: EMAC interrupt type - * @param intMask: EMAC interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_IntMask(EMAC_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); - - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_MASK); - - /* Mask or unmask certain or all interrupt */ - if (MASK == intMask) { - tmpVal |= intType; - } else { - tmpVal &= (~intType); - } - - /* Write back */ - BL_WR_REG(EMAC_BASE, EMAC_INT_MASK, tmpVal); - - return SUCCESS; + * @brief EMAC mask or unmask certain or all interrupt + * + * @param intType: EMAC interrupt type + * @param intMask: EMAC interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_IntMask(EMAC_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); + + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_MASK); + + /* Mask or unmask certain or all interrupt */ + if (MASK == intMask) { + tmpVal |= intType; + } else { + tmpVal &= (~intType); + } + + /* Write back */ + BL_WR_REG(EMAC_BASE, EMAC_INT_MASK, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Get EMAC interrupt status - * - * @param intType: EMAC interrupt type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Sts_Type EMAC_GetIntStatus(EMAC_INT_Type intType) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_EMAC_INT_TYPE(intType)); - - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_SOURCE); - - return (tmpVal & intType) ? SET : RESET; + * @brief Get EMAC interrupt status + * + * @param intType: EMAC interrupt type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Sts_Type EMAC_GetIntStatus(EMAC_INT_Type intType) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_EMAC_INT_TYPE(intType)); + + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_SOURCE); + + return (tmpVal & intType) ? SET : RESET; } /****************************************************************************/ /** - * @brief Clear EMAC interrupt - * - * @param intType: EMAC interrupt type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_ClrIntStatus(EMAC_INT_Type intType) -{ - uint32_t tmpVal; + * @brief Clear EMAC interrupt + * + * @param intType: EMAC interrupt type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_ClrIntStatus(EMAC_INT_Type intType) { + uint32_t tmpVal; - /* Check the parameters */ - CHECK_PARAM(IS_EMAC_INT_TYPE(intType)); + /* Check the parameters */ + CHECK_PARAM(IS_EMAC_INT_TYPE(intType)); - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_SOURCE); + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_SOURCE); - BL_WR_REG(EMAC_BASE, EMAC_INT_SOURCE, tmpVal | intType); + BL_WR_REG(EMAC_BASE, EMAC_INT_SOURCE, tmpVal | intType); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief EMAC_Int_Callback_Install - * - * @param intIdx: EMAC_INT_Index - * @param cbFun: call back - * - * @return None - * -*******************************************************************************/ -BL_Err_Type EMAC_Int_Callback_Install(EMAC_INT_Index intIdx, intCallback_Type *cbFun) -{ - /* Check the parameters */ - - emacIntCbfArra[intIdx] = cbFun; - - return SUCCESS; + * @brief EMAC_Int_Callback_Install + * + * @param intIdx: EMAC_INT_Index + * @param cbFun: call back + * + * @return None + * + *******************************************************************************/ +BL_Err_Type EMAC_Int_Callback_Install(EMAC_INT_Index intIdx, intCallback_Type *cbFun) { + /* Check the parameters */ + + emacIntCbfArra[intIdx] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief EMAC_IRQHandler - * - * @param None - * - * @return None - * -*******************************************************************************/ -void EMAC_IRQHandler(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_MASK); - - if (SET == EMAC_GetIntStatus(EMAC_INT_TX_DONE) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_TXB_M)) { - EMAC_ClrIntStatus(EMAC_INT_TX_DONE); - - if (emacIntCbfArra[EMAC_INT_TX_DONE_IDX]) { - emacIntCbfArra[EMAC_INT_TX_DONE_IDX](); - } + * @brief EMAC_IRQHandler + * + * @param None + * + * @return None + * + *******************************************************************************/ +void EMAC_IRQHandler(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_MASK); + + if (SET == EMAC_GetIntStatus(EMAC_INT_TX_DONE) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_TXB_M)) { + EMAC_ClrIntStatus(EMAC_INT_TX_DONE); + + if (emacIntCbfArra[EMAC_INT_TX_DONE_IDX]) { + emacIntCbfArra[EMAC_INT_TX_DONE_IDX](); } + } - if (SET == EMAC_GetIntStatus(EMAC_INT_TX_ERROR) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_TXE_M)) { - EMAC_ClrIntStatus(EMAC_INT_TX_ERROR); + if (SET == EMAC_GetIntStatus(EMAC_INT_TX_ERROR) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_TXE_M)) { + EMAC_ClrIntStatus(EMAC_INT_TX_ERROR); - if (emacIntCbfArra[EMAC_INT_TX_ERROR_IDX]) { - emacIntCbfArra[EMAC_INT_TX_ERROR_IDX](); - } + if (emacIntCbfArra[EMAC_INT_TX_ERROR_IDX]) { + emacIntCbfArra[EMAC_INT_TX_ERROR_IDX](); } + } - if (SET == EMAC_GetIntStatus(EMAC_INT_RX_DONE) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_RXB_M)) { - EMAC_ClrIntStatus(EMAC_INT_RX_DONE); + if (SET == EMAC_GetIntStatus(EMAC_INT_RX_DONE) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_RXB_M)) { + EMAC_ClrIntStatus(EMAC_INT_RX_DONE); - if (emacIntCbfArra[EMAC_INT_RX_DONE_IDX]) { - emacIntCbfArra[EMAC_INT_RX_DONE_IDX](); - } + if (emacIntCbfArra[EMAC_INT_RX_DONE_IDX]) { + emacIntCbfArra[EMAC_INT_RX_DONE_IDX](); } + } - if (SET == EMAC_GetIntStatus(EMAC_INT_RX_ERROR) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_RXE_M)) { - EMAC_ClrIntStatus(EMAC_INT_RX_ERROR); + if (SET == EMAC_GetIntStatus(EMAC_INT_RX_ERROR) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_RXE_M)) { + EMAC_ClrIntStatus(EMAC_INT_RX_ERROR); - if (emacIntCbfArra[EMAC_INT_RX_ERROR_IDX]) { - emacIntCbfArra[EMAC_INT_RX_ERROR_IDX](); - } + if (emacIntCbfArra[EMAC_INT_RX_ERROR_IDX]) { + emacIntCbfArra[EMAC_INT_RX_ERROR_IDX](); } + } - if (SET == EMAC_GetIntStatus(EMAC_INT_RX_BUSY) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_BUSY_M)) { - EMAC_ClrIntStatus(EMAC_INT_RX_BUSY); + if (SET == EMAC_GetIntStatus(EMAC_INT_RX_BUSY) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_BUSY_M)) { + EMAC_ClrIntStatus(EMAC_INT_RX_BUSY); - if (emacIntCbfArra[EMAC_INT_RX_BUSY_IDX]) { - emacIntCbfArra[EMAC_INT_RX_BUSY_IDX](); - } + if (emacIntCbfArra[EMAC_INT_RX_BUSY_IDX]) { + emacIntCbfArra[EMAC_INT_RX_BUSY_IDX](); } + } - if (SET == EMAC_GetIntStatus(EMAC_INT_TX_CTRL) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_TXC_M)) { - EMAC_ClrIntStatus(EMAC_INT_TX_CTRL); + if (SET == EMAC_GetIntStatus(EMAC_INT_TX_CTRL) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_TXC_M)) { + EMAC_ClrIntStatus(EMAC_INT_TX_CTRL); - if (emacIntCbfArra[EMAC_INT_TX_CTRL_IDX]) { - emacIntCbfArra[EMAC_INT_TX_CTRL_IDX](); - } + if (emacIntCbfArra[EMAC_INT_TX_CTRL_IDX]) { + emacIntCbfArra[EMAC_INT_TX_CTRL_IDX](); } + } - if (SET == EMAC_GetIntStatus(EMAC_INT_RX_CTRL) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_RXC_M)) { - EMAC_ClrIntStatus(EMAC_INT_RX_CTRL); + if (SET == EMAC_GetIntStatus(EMAC_INT_RX_CTRL) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_RXC_M)) { + EMAC_ClrIntStatus(EMAC_INT_RX_CTRL); - if (emacIntCbfArra[EMAC_INT_RX_CTRL_IDX]) { - emacIntCbfArra[EMAC_INT_RX_CTRL_IDX](); - } + if (emacIntCbfArra[EMAC_INT_RX_CTRL_IDX]) { + emacIntCbfArra[EMAC_INT_RX_CTRL_IDX](); } + } } /****************************************************************************/ /** - * @brief Request to pause TX - * - * @param timeCount: Pause time count - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_TxPauseReq(uint16_t timeCount) -{ - BL_WR_REG(EMAC_BASE, EMAC_TXCTRL, (1 << 16) | timeCount); - - return SUCCESS; + * @brief Request to pause TX + * + * @param timeCount: Pause time count + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_TxPauseReq(uint16_t timeCount) { + BL_WR_REG(EMAC_BASE, EMAC_TXCTRL, (1 << 16) | timeCount); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Set hash value - * - * @param hash0: Hash value one - * @param hash1: Hash value two - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_SetHash(uint32_t hash0, uint32_t hash1) -{ - BL_WR_REG(EMAC_BASE, EMAC_HASH0_ADDR, hash0); - - BL_WR_REG(EMAC_BASE, EMAC_HASH1_ADDR, hash1); - - return SUCCESS; + * @brief Set hash value + * + * @param hash0: Hash value one + * @param hash1: Hash value two + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_SetHash(uint32_t hash0, uint32_t hash1) { + BL_WR_REG(EMAC_BASE, EMAC_HASH0_ADDR, hash0); + + BL_WR_REG(EMAC_BASE, EMAC_HASH1_ADDR, hash1); + + return SUCCESS; } /*@} end of group EMAC_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_glb.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_glb.c index 97c6d76972..14d27ecfc6 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_glb.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_glb.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_glb.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_glb.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_glb.h" #include "bl702_hbn.h" @@ -49,16 +49,16 @@ * @{ */ #define GLB_CLK_SET_DUMMY_WAIT \ - { \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - } + { \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + } #define GLB_GPIO_Get_Reg(pin) (glb_gpio_reg_t *)(GLB_BASE + GLB_GPIO_OFFSET + (pin / 2) * 4) #define GLB_GPIO_INT0_NUM (32) #define GLB_REG_BCLK_DIS_TRUE (*(volatile uint32_t *)(0x40000FFC) = (0x00000001)) @@ -76,16 +76,12 @@ /** @defgroup GLB_Private_Variables * @{ */ -static intCallback_Type *glbBmxErrIntCbfArra[BMX_ERR_INT_ALL] = { NULL }; -static intCallback_Type *glbBmxToIntCbfArra[BMX_TO_INT_ALL] = { NULL }; -static intCallback_Type *glbGpioInt0CbfArra[GLB_GPIO_INT0_NUM] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; -static intCallback_Type *glbGpioInt0CbfArra2[GLB_GPIO_INT0_NUM] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; +static intCallback_Type *glbBmxErrIntCbfArra[BMX_ERR_INT_ALL] = {NULL}; +static intCallback_Type *glbBmxToIntCbfArra[BMX_TO_INT_ALL] = {NULL}; +static intCallback_Type *glbGpioInt0CbfArra[GLB_GPIO_INT0_NUM] + = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; +static intCallback_Type *glbGpioInt0CbfArra2[GLB_GPIO_INT0_NUM] + = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; /*@} end of group GLB_Private_Variables */ @@ -112,3922 +108,3788 @@ static intCallback_Type *glbGpioInt0CbfArra2[GLB_GPIO_INT0_NUM] = { NULL, NULL, */ /****************************************************************************/ /** - * @brief get root clock selection - * - * @param None - * - * @return root clock selection - * -*******************************************************************************/ + * @brief get root clock selection + * + * @param None + * + * @return root clock selection + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -GLB_ROOT_CLK_Type ATTR_CLOCK_SECTION GLB_Get_Root_CLK_Sel(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - - switch (BL_GET_REG_BITS_VAL(tmpVal, GLB_HBN_ROOT_CLK_SEL)) { - case 0: - return GLB_ROOT_CLK_RC32M; - case 1: - return GLB_ROOT_CLK_XTAL; - case 2: - case 3: - return GLB_ROOT_CLK_DLL; - default: - return GLB_ROOT_CLK_RC32M; - } +GLB_ROOT_CLK_Type ATTR_CLOCK_SECTION GLB_Get_Root_CLK_Sel(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + + switch (BL_GET_REG_BITS_VAL(tmpVal, GLB_HBN_ROOT_CLK_SEL)) { + case 0: + return GLB_ROOT_CLK_RC32M; + case 1: + return GLB_ROOT_CLK_XTAL; + case 2: + case 3: + return GLB_ROOT_CLK_DLL; + default: + return GLB_ROOT_CLK_RC32M; + } } #endif /****************************************************************************/ /** - * @brief Set System clock divider - * - * @param hclkDiv: HCLK divider - * @param bclkDiv: BCLK divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_System_CLK_Div(uint8_t hclkDiv, uint8_t bclkDiv) -{ - /***********************************************************************************/ - /* NOTE */ - /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ - /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ - /***********************************************************************************/ - uint32_t tmpVal; - - /* recommend: fclk<=160MHz, bclk<=80MHz */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, hclkDiv); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, bclkDiv); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - GLB_REG_BCLK_DIS_TRUE; - GLB_REG_BCLK_DIS_FALSE; - //SystemCoreClockSet(SystemCoreClockGet() / ((uint16_t)hclkDiv + 1)); - GLB_CLK_SET_DUMMY_WAIT; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_HCLK_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_BCLK_EN); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - GLB_CLK_SET_DUMMY_WAIT; - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Get Bus clock divider - * - * @param None - * - * @return Clock Divider - * -*******************************************************************************/ + * @brief Set System clock divider + * + * @param hclkDiv: HCLK divider + * @param bclkDiv: BCLK divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_System_CLK_Div(uint8_t hclkDiv, uint8_t bclkDiv) { + /***********************************************************************************/ + /* NOTE */ + /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ + /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ + /***********************************************************************************/ + uint32_t tmpVal; + + /* recommend: fclk<=160MHz, bclk<=80MHz */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, hclkDiv); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, bclkDiv); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); + GLB_REG_BCLK_DIS_TRUE; + GLB_REG_BCLK_DIS_FALSE; + // SystemCoreClockSet(SystemCoreClockGet() / ((uint16_t)hclkDiv + 1)); + GLB_CLK_SET_DUMMY_WAIT; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_HCLK_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_BCLK_EN); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); + GLB_CLK_SET_DUMMY_WAIT; + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Get Bus clock divider + * + * @param None + * + * @return Clock Divider + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint8_t ATTR_CLOCK_SECTION GLB_Get_BCLK_Div(void) -{ - uint32_t tmpVal; +uint8_t ATTR_CLOCK_SECTION GLB_Get_BCLK_Div(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV); + return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV); } #endif /****************************************************************************/ /** - * @brief Get CPU clock divider - * - * @param None - * - * @return Clock Divider - * -*******************************************************************************/ + * @brief Get CPU clock divider + * + * @param None + * + * @return Clock Divider + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint8_t ATTR_CLOCK_SECTION GLB_Get_HCLK_Div(void) -{ - uint32_t tmpVal; +uint8_t ATTR_CLOCK_SECTION GLB_Get_HCLK_Div(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV); + return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV); } #endif /****************************************************************************/ /** - * @brief update SystemCoreClock value - * - * @param xtalType: XTAL frequency type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief update SystemCoreClock value + * + * @param xtalType: XTAL frequency type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION Update_SystemCoreClockWith_XTAL(GLB_DLL_XTAL_Type xtalType) -{ - CHECK_PARAM(IS_GLB_DLL_XTAL_TYPE(xtalType)); - - switch (xtalType) { - case GLB_DLL_XTAL_NONE: - break; - case GLB_DLL_XTAL_32M: - SystemCoreClockSet(32000000); - break; - case GLB_DLL_XTAL_RC32M: - SystemCoreClockSet(32000000); - break; - default: - break; - } - - return SUCCESS; +BL_Err_Type ATTR_CLOCK_SECTION Update_SystemCoreClockWith_XTAL(GLB_DLL_XTAL_Type xtalType) { + CHECK_PARAM(IS_GLB_DLL_XTAL_TYPE(xtalType)); + + switch (xtalType) { + case GLB_DLL_XTAL_NONE: + break; + case GLB_DLL_XTAL_32M: + SystemCoreClockSet(32000000); + break; + case GLB_DLL_XTAL_RC32M: + SystemCoreClockSet(32000000); + break; + default: + break; + } + + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Set System clock - * - * @param xtalType: XTAL frequency type - * @param clkFreq: clock frequency selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Set System clock + * + * @param xtalType: XTAL frequency type + * @param clkFreq: clock frequency selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_System_CLK(GLB_DLL_XTAL_Type xtalType, GLB_SYS_CLK_Type clkFreq) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GLB_DLL_XTAL_TYPE(xtalType)); - CHECK_PARAM(IS_GLB_SYS_CLK_TYPE(clkFreq)); - - /* reg_bclk_en = reg_hclk_en = reg_fclk_en = 1, cannot be zero */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_BCLK_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_HCLK_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_FCLK_EN); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - - /* Before config XTAL and DLL ,make sure root clk is from RC32M */ - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_RC32M); - GLB_Set_System_CLK_Div(0, 0); - SystemCoreClockSet(32 * 1000 * 1000); - - if (xtalType == GLB_DLL_XTAL_NONE) { - if (clkFreq == GLB_SYS_CLK_RC32M) { - return SUCCESS; - } else { - return ERROR; - } +BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_System_CLK(GLB_DLL_XTAL_Type xtalType, GLB_SYS_CLK_Type clkFreq) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GLB_DLL_XTAL_TYPE(xtalType)); + CHECK_PARAM(IS_GLB_SYS_CLK_TYPE(clkFreq)); + + /* reg_bclk_en = reg_hclk_en = reg_fclk_en = 1, cannot be zero */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_BCLK_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_HCLK_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_FCLK_EN); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); + + /* Before config XTAL and DLL ,make sure root clk is from RC32M */ + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_RC32M); + GLB_Set_System_CLK_Div(0, 0); + SystemCoreClockSet(32 * 1000 * 1000); + + if (xtalType == GLB_DLL_XTAL_NONE) { + if (clkFreq == GLB_SYS_CLK_RC32M) { + return SUCCESS; + } else { + return ERROR; } + } - if (xtalType != GLB_DLL_XTAL_RC32M) { - /* power on xtal first */ - AON_Power_On_XTAL(); - } + if (xtalType != GLB_DLL_XTAL_RC32M) { + /* power on xtal first */ + AON_Power_On_XTAL(); + } - /* Bl702 make PLL Setting out of RF, so following setting can be removed*/ - //AON_Power_On_MBG(); - //AON_Power_On_LDO15_RF(); + /* Bl702 make PLL Setting out of RF, so following setting can be removed*/ + // AON_Power_On_MBG(); + // AON_Power_On_LDO15_RF(); - /* always power up PLL and enable all PLL clock output */ - //PDS_Power_On_PLL((PDS_PLL_XTAL_Type)xtalType); - //BL702_Delay_US(55); - //PDS_Enable_PLL_All_Clks(); + /* always power up PLL and enable all PLL clock output */ + // PDS_Power_On_PLL((PDS_PLL_XTAL_Type)xtalType); + // BL702_Delay_US(55); + // PDS_Enable_PLL_All_Clks(); - /* always power up DLL and enable all DLL clock output */ - GLB_Power_Off_DLL(); - GLB_Power_On_DLL(xtalType); - GLB_Enable_DLL_All_Clks(); + /* always power up DLL and enable all DLL clock output */ + GLB_Power_Off_DLL(); + GLB_Power_On_DLL(xtalType); + GLB_Enable_DLL_All_Clks(); - /* reg_pll_en = 1, cannot be zero */ + /* reg_pll_en = 1, cannot be zero */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_PLL_EN); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); + + /* select pll output clock before select root clock */ + if (clkFreq >= GLB_SYS_CLK_DLL57P6M) { tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_PLL_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_PLL_SEL, clkFreq - GLB_SYS_CLK_DLL57P6M); BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - - /* select pll output clock before select root clock */ - if (clkFreq >= GLB_SYS_CLK_DLL57P6M) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_PLL_SEL, clkFreq - GLB_SYS_CLK_DLL57P6M); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - } - /* select root clock */ - switch (clkFreq) { - case GLB_SYS_CLK_RC32M: - break; - case GLB_SYS_CLK_XTAL: - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - Update_SystemCoreClockWith_XTAL(xtalType); - break; - case GLB_SYS_CLK_DLL57P6M: - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_DLL); - SystemCoreClockSet(57 * 6000 * 1000); - break; - case GLB_SYS_CLK_DLL96M: - L1C_IROM_2T_Access_Set(ENABLE); - GLB_Set_System_CLK_Div(0, 1); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_DLL); - SystemCoreClockSet(96 * 1000 * 1000); - break; - case GLB_SYS_CLK_DLL144M: - L1C_IROM_2T_Access_Set(ENABLE); - GLB_Set_System_CLK_Div(0, 1); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_DLL); - SystemCoreClockSet(144 * 1000 * 1000); - break; - default: - break; - } - - GLB_CLK_SET_DUMMY_WAIT; - - return SUCCESS; + } + /* select root clock */ + switch (clkFreq) { + case GLB_SYS_CLK_RC32M: + break; + case GLB_SYS_CLK_XTAL: + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + Update_SystemCoreClockWith_XTAL(xtalType); + break; + case GLB_SYS_CLK_DLL57P6M: + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_DLL); + SystemCoreClockSet(57 * 6000 * 1000); + break; + case GLB_SYS_CLK_DLL96M: + L1C_IROM_2T_Access_Set(ENABLE); + GLB_Set_System_CLK_Div(0, 1); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_DLL); + SystemCoreClockSet(96 * 1000 * 1000); + break; + case GLB_SYS_CLK_DLL144M: + L1C_IROM_2T_Access_Set(ENABLE); + GLB_Set_System_CLK_Div(0, 1); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_DLL); + SystemCoreClockSet(144 * 1000 * 1000); + break; + default: + break; + } + + GLB_CLK_SET_DUMMY_WAIT; + + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief This is demo for user that use RC32M as default bootup clock instead of DLL,when APP is - * started, this function can be called to set DLL to 160M - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief This is demo for user that use RC32M as default bootup clock instead of DLL,when APP is + * started, this function can be called to set DLL to 160M + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION System_Core_Clock_Update_From_RC32M(void) -{ - SF_Ctrl_Cfg_Type sfCtrlCfg = { - .owner = SF_CTRL_OWNER_IAHB, - .clkDelay = 1, - .clkInvert = 1, - .rxClkInvert = 1, - .doDelay = 0, - .diDelay = 0, - .oeDelay = 0, - }; - /* Use RC32M as DLL ref source to set up DLL to 144M */ - GLB_Set_System_CLK(GLB_DLL_XTAL_RC32M, GLB_SYS_CLK_DLL144M); - /* Flash controller also need changes since system (bus) clock changed */ - SF_Ctrl_Enable(&sfCtrlCfg); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - - return SUCCESS; +BL_Err_Type ATTR_CLOCK_SECTION System_Core_Clock_Update_From_RC32M(void) { + SF_Ctrl_Cfg_Type sfCtrlCfg = { + .owner = SF_CTRL_OWNER_IAHB, + .clkDelay = 1, + .clkInvert = 1, + .rxClkInvert = 1, + .doDelay = 0, + .diDelay = 0, + .oeDelay = 0, + }; + /* Use RC32M as DLL ref source to set up DLL to 144M */ + GLB_Set_System_CLK(GLB_DLL_XTAL_RC32M, GLB_SYS_CLK_DLL144M); + /* Flash controller also need changes since system (bus) clock changed */ + SF_Ctrl_Enable(&sfCtrlCfg); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief set CAM clock - * - * @param enable: Enable or disable CAM clock - * @param clkSel: CAM clock type - * @param div: clock divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_CAM_CLK(uint8_t enable, GLB_CAM_CLK_Type clkSel, uint8_t div) -{ - uint32_t tmpVal = 0; + * @brief set CAM clock + * + * @param enable: Enable or disable CAM clock + * @param clkSel: CAM clock type + * @param div: clock divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_CAM_CLK(uint8_t enable, GLB_CAM_CLK_Type clkSel, uint8_t div) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_CAM_CLK_TYPE(clkSel)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_CAM_REF_CLK_SRC_SEL, clkSel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_CAM_REF_CLK_DIV, div); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CAM_REF_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CAM_REF_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set mac154 and zigbee clock + * + * @param enable: Enable or disable mac154 and zigbee clock + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_MAC154_ZIGBEE_CLK(uint8_t enable) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_M154_ZBEN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_M154_ZBEN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + return SUCCESS; +} - CHECK_PARAM(IS_GLB_CAM_CLK_TYPE(clkSel)); +/****************************************************************************/ /** + * @brief set BLE clock + * + * @param enable: Enable or disable BLE clock + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_BLE_CLK(uint8_t enable) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_BLE_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_BLE_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set I2S clock + * + * @param enable: Enable or disable I2S clock + * @param outRef: I2S output ref clock type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_I2S_CLK(uint8_t enable, GLB_I2S_OUT_REF_CLK_Type outRef) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_I2S_OUT_REF_CLK_TYPE(outRef)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_I2S_0_REF_CLK_OE, outRef); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_I2S0_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_I2S0_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set USB clock + * + * @param enable: Enable or disable USB clock + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_USB_CLK(uint8_t enable) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_48M_DIV_EN, 1); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_USB_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_USB_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set QDEC clock + * + * @param clkSel: QDEC clock type + * @param div: clock divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_QDEC_CLK(GLB_QDEC_CLK_Type clkSel, uint8_t div) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_QDEC_CLK_TYPE(clkSel)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_QDEC_CLK_SEL, clkSel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_QDEC_CLK_DIV, div); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set DMA clock + * + * @param enable: Enable or disable DMA clock + * @param clk: DMA ID type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_DMA_CLK(uint8_t enable, GLB_DMA_CLK_ID_Type clk) { + uint32_t tmpVal; + uint32_t tmpVal2; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, GLB_DMA_CLK_EN); + if (enable) { + tmpVal2 |= (1 << clk); + } else { + tmpVal2 &= (~(1 << clk)); + } + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DMA_CLK_EN, tmpVal2); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set IR clock divider + * + * @param enable: enable or disable IR clock + * @param clkSel: IR clock type + * @param div: divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_IR_CLK(uint8_t enable, GLB_IR_CLK_SRC_Type clkSel, uint8_t div) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_IR_CLK_SRC_TYPE(clkSel)); + CHECK_PARAM((div <= 0x3F)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_IR_CLK_DIV, div); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_IR_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_IR_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set sflash clock + * + * @param enable: Enable or disable sflash clock + * @param clkSel: sflash clock type + * @param div: clock divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_SF_CLK(uint8_t enable, GLB_SFLASH_CLK_Type clkSel, uint8_t div) { + uint32_t tmpVal = 0; + GLB_DLL_CLK_Type clk; + + CHECK_PARAM(IS_GLB_SFLASH_CLK_TYPE(clkSel)); + CHECK_PARAM((div <= 0x7)); + + /* disable SFLASH clock first */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_SF_CLK_EN); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + + /* Select flash clock, all Flash CLKs are divied by DLL_288M */ + clk = GLB_DLL_CLK_288M; + GLB_Enable_DLL_Clk(clk); + /* clock divider */ + /* Select flash clock, all Flash CLKs are divied by DLL_288M */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_DIV, div); + switch (clkSel) { + case GLB_SFLASH_CLK_144M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL2, 0x0); + break; + case GLB_SFLASH_CLK_XCLK: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL2, 0x1); + break; + case GLB_SFLASH_CLK_57P6M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL2, 0x3); + break; + case GLB_SFLASH_CLK_72M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x1); + break; + case GLB_SFLASH_CLK_BCLK: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x2); + break; + case GLB_SFLASH_CLK_96M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x3); + break; + default: + break; + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + + /* enable or disable flash clock */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_SF_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_SF_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_CAM_REF_CLK_SRC_SEL, clkSel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_CAM_REF_CLK_DIV, div); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + return SUCCESS; +} +#endif - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CAM_REF_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CAM_REF_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); +/****************************************************************************/ /** + * @brief set UART clock + * + * @param enable: Enable or disable UART clock + * @param clkSel: UART clock type + * @param div: clock divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_UART_CLK(uint8_t enable, HBN_UART_CLK_Type clkSel, uint8_t div) { + uint32_t tmpVal = 0; + + CHECK_PARAM((div <= 0x7)); + CHECK_PARAM(IS_HBN_UART_CLK_TYPE(clkSel)); + + /* disable UART clock first */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_UART_CLK_EN); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + + /* Set div */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_UART_CLK_DIV, div); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + + /* Select clock source for uart */ + HBN_Set_UART_CLK_Sel(clkSel); + + /* Set enable or disable */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_UART_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_UART_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief set mac154 and zigbee clock - * - * @param enable: Enable or disable mac154 and zigbee clock - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_MAC154_ZIGBEE_CLK(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief select chip clock out 0 type + * + * @param clkSel: chip clock out type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_Chip_Out_0_CLK_Sel(GLB_CHIP_CLK_OUT_Type clkSel) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_M154_ZBEN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_M154_ZBEN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + CHECK_PARAM(IS_GLB_CHIP_CLK_OUT_TYPE(clkSel)); - return SUCCESS; + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CHIP_CLK_OUT_0_SEL, clkSel); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief set BLE clock - * - * @param enable: Enable or disable BLE clock - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_BLE_CLK(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief select chip clock out 1 type + * + * @param clkSel: chip clock out type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_Chip_Out_1_CLK_Sel(GLB_CHIP_CLK_OUT_Type clkSel) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_BLE_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_BLE_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + CHECK_PARAM(IS_GLB_CHIP_CLK_OUT_TYPE(clkSel)); - return SUCCESS; + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CHIP_CLK_OUT_1_SEL, clkSel); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief set I2S clock - * - * @param enable: Enable or disable I2S clock - * @param outRef: I2S output ref clock type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_I2S_CLK(uint8_t enable, GLB_I2S_OUT_REF_CLK_Type outRef) -{ - uint32_t tmpVal = 0; + * @brief set I2C clock + * + * @param enable: Enable or disable I2C clock + * @param div: clock divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_I2C_CLK(uint8_t enable, uint8_t div) { + uint32_t tmpVal = 0; - CHECK_PARAM(IS_GLB_I2S_OUT_REF_CLK_TYPE(outRef)); + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_I2C_CLK_DIV, div); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_I2S_0_REF_CLK_OE, outRef); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_I2S0_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_I2S0_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_I2C_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_I2C_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief set USB clock - * - * @param enable: Enable or disable USB clock - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_USB_CLK(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief invert eth rx clock + * + * @param enable: invert or not invert + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Invert_ETH_RX_CLK(uint8_t enable) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_ETH_RX_CLK); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_ETH_RX_CLK); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_48M_DIV_EN, 1); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + return SUCCESS; +} - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_USB_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_USB_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); +/****************************************************************************/ /** + * @brief invert rf test clock out + * + * @param enable: invert or not invert + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Invert_RF_TEST_O_CLK(uint8_t enable) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_RF_TEST_CLK_O); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_RF_TEST_CLK_O); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - return SUCCESS; + return SUCCESS; } -/****************************************************************************/ /** - * @brief set QDEC clock - * - * @param clkSel: QDEC clock type - * @param div: clock divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_QDEC_CLK(GLB_QDEC_CLK_Type clkSel, uint8_t div) -{ - uint32_t tmpVal = 0; +/****************************************************************************/ /** + * @brief set SPI clock + * + * @param enable: Enable or disable SPI clock + * @param div: clock divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_SPI_CLK(uint8_t enable, uint8_t div) { + uint32_t tmpVal = 0; - CHECK_PARAM(IS_GLB_QDEC_CLK_TYPE(clkSel)); + CHECK_PARAM((div <= 0x1F)); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_QDEC_CLK_SEL, clkSel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_QDEC_CLK_DIV, div); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SPI_CLK_DIV, div); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - return SUCCESS; + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_SPI_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_SPI_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief invert eth tx clock + * + * @param enable: invert or not invert + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Invert_ETH_TX_CLK(uint8_t enable) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_ETH_TX_CLK); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_ETH_TX_CLK); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief set DMA clock - * - * @param enable: Enable or disable DMA clock - * @param clk: DMA ID type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_DMA_CLK(uint8_t enable, GLB_DMA_CLK_ID_Type clk) -{ - uint32_t tmpVal; - uint32_t tmpVal2; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, GLB_DMA_CLK_EN); - if (enable) { - tmpVal2 |= (1 << clk); - } else { - tmpVal2 &= (~(1 << clk)); - } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DMA_CLK_EN, tmpVal2); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + * @brief invert eth ref clock out + * + * @param enable: invert or not invert + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Invert_ETH_REF_O_CLK(uint8_t enable) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_ETH_REF_CLK_O); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_ETH_REF_CLK_O); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief set IR clock divider - * - * @param enable: enable or disable IR clock - * @param clkSel: IR clock type - * @param div: divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_IR_CLK(uint8_t enable, GLB_IR_CLK_SRC_Type clkSel, uint8_t div) -{ - uint32_t tmpVal = 0; + * @brief select eth ref clock out + * + * @param clkSel: eth ref clock type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_ETH_REF_O_CLK_Sel(GLB_ETH_REF_CLK_OUT_Type clkSel) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_SEL_ETH_REF_CLK_O, clkSel); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - CHECK_PARAM(IS_GLB_IR_CLK_SRC_TYPE(clkSel)); - CHECK_PARAM((div <= 0x3F)); + return SUCCESS; +} - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_IR_CLK_DIV, div); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); +/****************************************************************************/ /** + * @brief select PKA clock source + * + * @param clkSel: PKA clock selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_PKA_CLK_Sel(GLB_PKA_CLK_Type clkSel) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_PKA_CLK_TYPE(clkSel)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PKA_CLK_SEL, clkSel); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_IR_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_IR_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + return SUCCESS; +} - return SUCCESS; +/****************************************************************************/ /** + * @brief Software system reset + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_SW_System_Reset(void) { + /***********************************************************************************/ + /* NOTE */ + /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ + /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ + /***********************************************************************************/ + uint32_t tmpVal; + + /* Swicth clock to 32M as default */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + GLB_CLK_SET_DUMMY_WAIT; + + /* HCLK is RC32M , so BCLK/HCLK no need divider */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, 0); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); + GLB_REG_BCLK_DIS_TRUE; + GLB_REG_BCLK_DIS_FALSE; + GLB_CLK_SET_DUMMY_WAIT; + + /* Do reset */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); + // tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_CTRL_PWRON_RST); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); + + /* waiting for reset */ + while (1) { + BL702_Delay_US(10); + } + + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief set sflash clock - * - * @param enable: Enable or disable sflash clock - * @param clkSel: sflash clock type - * @param div: clock divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Software CPU reset + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_SF_CLK(uint8_t enable, GLB_SFLASH_CLK_Type clkSel, uint8_t div) -{ - uint32_t tmpVal = 0; - GLB_DLL_CLK_Type clk; +BL_Err_Type ATTR_TCM_SECTION GLB_SW_CPU_Reset(void) { + /***********************************************************************************/ + /* NOTE */ + /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ + /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ + /***********************************************************************************/ + uint32_t tmpVal; + + /* Swicth clock to 32M as default */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + GLB_CLK_SET_DUMMY_WAIT; + + /* HCLK is RC32M , so BCLK/HCLK no need divider */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, 0); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); + GLB_REG_BCLK_DIS_TRUE; + GLB_REG_BCLK_DIS_FALSE; + GLB_CLK_SET_DUMMY_WAIT; + + /* Do reset */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); + // tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_CTRL_SYS_RESET); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); + // tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_CTRL_PWRON_RST); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); + + /* waiting for reset */ + while (1) { + BL702_Delay_US(10); + } + + return SUCCESS; +} +#endif - CHECK_PARAM(IS_GLB_SFLASH_CLK_TYPE(clkSel)); - CHECK_PARAM((div <= 0x7)); +/****************************************************************************/ /** + * @brief Software power on reset + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_SW_POR_Reset(void) { + /***********************************************************************************/ + /* NOTE */ + /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ + /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ + /***********************************************************************************/ + uint32_t tmpVal; + + /* Swicth clock to 32M as default */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + GLB_CLK_SET_DUMMY_WAIT; + + /* HCLK is RC32M , so BCLK/HCLK no need divider */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, 0); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); + GLB_REG_BCLK_DIS_TRUE; + GLB_REG_BCLK_DIS_FALSE; + GLB_CLK_SET_DUMMY_WAIT; + + /* Do reset */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); + + /* waiting for reset */ + while (1) { + BL702_Delay_US(10); + } + + return SUCCESS; +} +#endif - /* disable SFLASH clock first */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_SF_CLK_EN); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); - - /* Select flash clock, all Flash CLKs are divied by DLL_288M */ - clk = GLB_DLL_CLK_288M; - GLB_Enable_DLL_Clk(clk); - /* clock divider */ - /* Select flash clock, all Flash CLKs are divied by DLL_288M */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_DIV, div); - switch (clkSel) { - case GLB_SFLASH_CLK_144M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL2, 0x0); - break; - case GLB_SFLASH_CLK_XCLK: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL2, 0x1); - break; - case GLB_SFLASH_CLK_57P6M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL2, 0x3); - break; - case GLB_SFLASH_CLK_72M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x1); - break; - case GLB_SFLASH_CLK_BCLK: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x2); - break; - case GLB_SFLASH_CLK_96M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x3); - break; - default: - break; +/****************************************************************************/ /** + * @brief Reset slave 1 + * + * @param slave1: slave num + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_AHB_Slave1_Reset(BL_AHB_Slave1_Type slave1) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG1); + tmpVal &= (~(1 << slave1)); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG1, tmpVal); + BL_DRV_DUMMY; + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG1); + tmpVal |= (1 << slave1); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG1, tmpVal); + BL_DRV_DUMMY; + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG1); + tmpVal &= (~(1 << slave1)); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG1, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief clock gate + * + * @param enable: ENABLE or DISABLE + * @param slave1: AHB slaveClk type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_AHB_Slave1_Clock_Gate(uint8_t enable, BL_AHB_Slave1_Type slave1) { + /* gate QDEC <=> gate QDEC0 + QDEC1 +QDEC2 + I2S */ + /* gate I2S <=> gate I2S + QDEC2 */ + + uint32_t tmpVal = 0; + + if ((BL_AHB_SLAVE1_GLB == slave1) || (BL_AHB_SLAVE1_TZ2 == slave1) || (BL_AHB_SLAVE1_CCI == slave1) || (BL_AHB_SLAVE1_L1C == slave1) || (BL_AHB_SLAVE1_PDS_HBN_AON_HBNRAM == slave1)) { + /* not support */ + return ERROR; + } + + /* gate QDEC and I2S */ + if (BL_AHB_SLAVE1_QDEC == slave1) { + tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); + if (enable) { + /* clear bit means clock gate */ + tmpVal &= (~(1 << 0x18)); + tmpVal &= (~(1 << 0x19)); + tmpVal &= (~(1 << 0x1A)); + } else { + /* set bit means clock pass */ + tmpVal |= (1 << 0x18); + tmpVal |= (1 << 0x19); + tmpVal |= (1 << 0x1A); } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); + return SUCCESS; + } - /* enable or disable flash clock */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + /* gate KYS */ + if (BL_AHB_SLAVE1_KYS == slave1) { + tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_SF_CLK_EN); + /* clear bit means clock gate */ + tmpVal &= (~(1 << 0x1B)); } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_SF_CLK_EN); + /* set bit means clock pass */ + tmpVal |= (1 << 0x1B); } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); + return SUCCESS; + } + /* gate I2S and QDEC2 */ + if (BL_AHB_SLAVE1_I2S == slave1) { + tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); + if (enable) { + /* clear bit means clock gate */ + tmpVal &= (~(1 << 0x1A)); + } else { + /* set bit means clock pass */ + tmpVal |= (1 << 0x1A); + } + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); return SUCCESS; -} + } + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); + if (enable) { + /* clear bit means clock gate */ + tmpVal &= (~(1 << slave1)); + } else { + /* set bit means clock pass */ + tmpVal |= (1 << slave1); + } + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief get IPs clock gate value + * + * @param None + * + * @return clock gate value + * + *******************************************************************************/ +uint64_t GLB_PER_Clock_Gate_Status_Get(void) { + /* api request from cjy */ + + uint32_t tmpValCfg0 = 0; + uint32_t tmpValCfg1 = 0; + uint32_t tmpValCfg2 = 0; + uint32_t targetBit = 0; + uint64_t targetVal = 0; + + tmpValCfg0 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG0); + tmpValCfg1 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); + tmpValCfg2 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG2); + for (uint8_t i = 0; i < 64; i++) { + targetBit = 0; + switch (i) { + case GLB_AHB_CLOCK_IP_CPU: + targetBit = tmpValCfg0 & (1 << 0); + break; + case GLB_AHB_CLOCK_IP_SDU: + targetBit = tmpValCfg0 & (1 << 1); + break; + case GLB_AHB_CLOCK_IP_SEC: + targetBit = (tmpValCfg0 & (1 << 2)) && (tmpValCfg1 & (1 << 3)) && (tmpValCfg1 & (1 << 4)); + break; + case GLB_AHB_CLOCK_IP_DMA_0: + targetBit = (tmpValCfg0 & (1 << 3)) && (tmpValCfg1 & (1 << 12)); + break; + case GLB_AHB_CLOCK_IP_DMA_1: + break; + case GLB_AHB_CLOCK_IP_DMA_2: + break; + case GLB_AHB_CLOCK_IP_CCI: + targetBit = tmpValCfg0 & (1 << 4); + break; + case GLB_AHB_CLOCK_IP_RF_TOP: + break; + case GLB_AHB_CLOCK_IP_GPIP: + targetBit = tmpValCfg1 & (1 << 2); + break; + case GLB_AHB_CLOCK_IP_TZC: + targetBit = tmpValCfg1 & (1 << 5); + break; + case GLB_AHB_CLOCK_IP_EF_CTRL: + targetBit = tmpValCfg1 & (1 << 7); + break; + case GLB_AHB_CLOCK_IP_SF_CTRL: + targetBit = tmpValCfg1 & (1 << 11); + break; + case GLB_AHB_CLOCK_IP_EMAC: + targetBit = tmpValCfg1 & (1 << 13); + break; + case GLB_AHB_CLOCK_IP_UART0: + targetBit = tmpValCfg1 & (1 << 16); + break; + case GLB_AHB_CLOCK_IP_UART1: + targetBit = tmpValCfg1 & (1 << 17); + break; + case GLB_AHB_CLOCK_IP_UART2: + break; + case GLB_AHB_CLOCK_IP_UART3: + break; + case GLB_AHB_CLOCK_IP_UART4: + break; + case GLB_AHB_CLOCK_IP_SPI: + targetBit = tmpValCfg1 & (1 << 18); + break; + case GLB_AHB_CLOCK_IP_I2C: + targetBit = tmpValCfg1 & (1 << 19); + break; + case GLB_AHB_CLOCK_IP_PWM: + targetBit = tmpValCfg1 & (1 << 20); + break; + case GLB_AHB_CLOCK_IP_TIMER: + targetBit = tmpValCfg1 & (1 << 21); + break; + case GLB_AHB_CLOCK_IP_IR: + targetBit = tmpValCfg1 & (1 << 22); + break; + case GLB_AHB_CLOCK_IP_CHECKSUM: + targetBit = tmpValCfg1 & (1 << 23); + break; + case GLB_AHB_CLOCK_IP_QDEC: + targetBit = (tmpValCfg1 & (1 << 24)) && (tmpValCfg1 & (1 << 25)) && (tmpValCfg1 & (1 << 26)); + break; + case GLB_AHB_CLOCK_IP_KYS: + targetBit = tmpValCfg1 & (1 << 27); + break; + case GLB_AHB_CLOCK_IP_I2S: + targetBit = tmpValCfg1 & (1 << 26); + break; + case GLB_AHB_CLOCK_IP_USB11: + targetBit = tmpValCfg1 & (1 << 28); + break; + case GLB_AHB_CLOCK_IP_CAM: + targetBit = tmpValCfg1 & (1 << 29); + break; + case GLB_AHB_CLOCK_IP_MJPEG: + targetBit = tmpValCfg1 & (1 << 30); + break; + case GLB_AHB_CLOCK_IP_BT_BLE_NORMAL: + targetBit = (tmpValCfg2 & (1 << 0)) && (tmpValCfg2 & (1 << 4)); + break; + case GLB_AHB_CLOCK_IP_BT_BLE_LP: + break; + case GLB_AHB_CLOCK_IP_ZB_NORMAL: + targetBit = tmpValCfg2 & (1 << 0); + break; + case GLB_AHB_CLOCK_IP_ZB_LP: + break; + case GLB_AHB_CLOCK_IP_WIFI_NORMAL: + break; + case GLB_AHB_CLOCK_IP_WIFI_LP: + break; + case GLB_AHB_CLOCK_IP_BT_BLE_2_NORMAL: + break; + case GLB_AHB_CLOCK_IP_BT_BLE_2_LP: + break; + case GLB_AHB_CLOCK_IP_EMI_MISC: + break; + case GLB_AHB_CLOCK_IP_PSRAM0_CTRL: + break; + case GLB_AHB_CLOCK_IP_PSRAM1_CTRL: + break; + case GLB_AHB_CLOCK_IP_USB20: + break; + case GLB_AHB_CLOCK_IP_MIX2: + break; + case GLB_AHB_CLOCK_IP_AUDIO: + break; + case GLB_AHB_CLOCK_IP_SDH: + break; + default: + break; + } + if (!targetBit) { + targetVal |= ((uint64_t)1 << i); + } + } + + return targetVal; +} + +/****************************************************************************/ /** + * @brief get first 1 from u64, then clear it + * + * @param val: target value + * @param bit: first 1 in bit + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +static BL_Err_Type GLB_Get_And_Clr_First_Set_From_U64(uint64_t *val, uint32_t *bit) { + if (!*val) { + return ERROR; + } + + for (uint8_t i = 0; i < 64; i++) { + if ((*val) & ((uint64_t)1 << i)) { + *bit = i; + (*val) &= ~((uint64_t)1 << i); + break; + } + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief hold IPs clock + * + * @param ips: GLB_AHB_CLOCK_IP_xxx | GLB_AHB_CLOCK_IP_xxx | ...... + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_PER_Clock_Gate(uint64_t ips) { + /* api request from cjy */ + + uint32_t tmpValCfg0 = 0; + uint32_t tmpValCfg1 = 0; + uint32_t tmpValCfg2 = 0; + uint32_t bitfield = 0; + + tmpValCfg0 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG0); + tmpValCfg1 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); + tmpValCfg2 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG2); + while (ips) { + if (SUCCESS == GLB_Get_And_Clr_First_Set_From_U64(&ips, &bitfield)) { + switch (bitfield) { + case GLB_AHB_CLOCK_IP_CPU: + tmpValCfg0 &= ~(1 << 0); + break; + case GLB_AHB_CLOCK_IP_SDU: + tmpValCfg0 &= ~(1 << 1); + break; + case GLB_AHB_CLOCK_IP_SEC: + tmpValCfg0 &= ~(1 << 2); + tmpValCfg1 &= ~(1 << 3); + tmpValCfg1 &= ~(1 << 4); + break; + case GLB_AHB_CLOCK_IP_DMA_0: + tmpValCfg0 &= ~(1 << 3); + tmpValCfg1 &= ~(1 << 12); + break; + case GLB_AHB_CLOCK_IP_DMA_1: + break; + case GLB_AHB_CLOCK_IP_DMA_2: + break; + case GLB_AHB_CLOCK_IP_CCI: + tmpValCfg0 &= ~(1 << 4); + break; + case GLB_AHB_CLOCK_IP_RF_TOP: + break; + case GLB_AHB_CLOCK_IP_GPIP: + tmpValCfg1 &= ~(1 << 2); + break; + case GLB_AHB_CLOCK_IP_TZC: + tmpValCfg1 &= ~(1 << 5); + break; + case GLB_AHB_CLOCK_IP_EF_CTRL: + tmpValCfg1 &= ~(1 << 7); + break; + case GLB_AHB_CLOCK_IP_SF_CTRL: + tmpValCfg1 &= ~(1 << 11); + break; + case GLB_AHB_CLOCK_IP_EMAC: + tmpValCfg1 &= ~(1 << 13); + break; + case GLB_AHB_CLOCK_IP_UART0: + tmpValCfg1 &= ~(1 << 16); + break; + case GLB_AHB_CLOCK_IP_UART1: + tmpValCfg1 &= ~(1 << 17); + break; + case GLB_AHB_CLOCK_IP_UART2: + break; + case GLB_AHB_CLOCK_IP_UART3: + break; + case GLB_AHB_CLOCK_IP_UART4: + break; + case GLB_AHB_CLOCK_IP_SPI: + tmpValCfg1 &= ~(1 << 18); + break; + case GLB_AHB_CLOCK_IP_I2C: + tmpValCfg1 &= ~(1 << 19); + break; + case GLB_AHB_CLOCK_IP_PWM: + tmpValCfg1 &= ~(1 << 20); + break; + case GLB_AHB_CLOCK_IP_TIMER: + tmpValCfg1 &= ~(1 << 21); + break; + case GLB_AHB_CLOCK_IP_IR: + tmpValCfg1 &= ~(1 << 22); + break; + case GLB_AHB_CLOCK_IP_CHECKSUM: + tmpValCfg1 &= ~(1 << 23); + break; + case GLB_AHB_CLOCK_IP_QDEC: + tmpValCfg1 &= ~(1 << 24); + tmpValCfg1 &= ~(1 << 25); + tmpValCfg1 &= ~(1 << 26); + break; + case GLB_AHB_CLOCK_IP_KYS: + tmpValCfg1 &= ~(1 << 27); + break; + case GLB_AHB_CLOCK_IP_I2S: + tmpValCfg1 &= ~(1 << 26); + break; + case GLB_AHB_CLOCK_IP_USB11: + tmpValCfg1 &= ~(1 << 28); + break; + case GLB_AHB_CLOCK_IP_CAM: + tmpValCfg1 &= ~(1 << 29); + break; + case GLB_AHB_CLOCK_IP_MJPEG: + tmpValCfg1 &= ~(1 << 30); + break; + case GLB_AHB_CLOCK_IP_BT_BLE_NORMAL: + tmpValCfg2 &= ~(1 << 0); + tmpValCfg2 &= ~(1 << 4); + break; + case GLB_AHB_CLOCK_IP_BT_BLE_LP: + break; + case GLB_AHB_CLOCK_IP_ZB_NORMAL: + tmpValCfg2 &= ~(1 << 0); + break; + case GLB_AHB_CLOCK_IP_ZB_LP: + break; + case GLB_AHB_CLOCK_IP_WIFI_NORMAL: + break; + case GLB_AHB_CLOCK_IP_WIFI_LP: + break; + case GLB_AHB_CLOCK_IP_BT_BLE_2_NORMAL: + break; + case GLB_AHB_CLOCK_IP_BT_BLE_2_LP: + break; + case GLB_AHB_CLOCK_IP_EMI_MISC: + break; + case GLB_AHB_CLOCK_IP_PSRAM0_CTRL: + break; + case GLB_AHB_CLOCK_IP_PSRAM1_CTRL: + break; + case GLB_AHB_CLOCK_IP_USB20: + break; + case GLB_AHB_CLOCK_IP_MIX2: + break; + case GLB_AHB_CLOCK_IP_AUDIO: + break; + case GLB_AHB_CLOCK_IP_SDH: + break; + default: + break; + } + } + } + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG0, tmpValCfg0); + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpValCfg1); + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG2, tmpValCfg2); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief release IPs clock + * + * @param ips: GLB_AHB_CLOCK_IP_xxx | GLB_AHB_CLOCK_IP_xxx | ...... + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_PER_Clock_UnGate(uint64_t ips) { + /* api request from cjy */ + + uint32_t tmpValCfg0 = 0; + uint32_t tmpValCfg1 = 0; + uint32_t tmpValCfg2 = 0; + uint32_t bitfield = 0; + + tmpValCfg0 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG0); + tmpValCfg1 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); + tmpValCfg2 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG2); + while (ips) { + if (SUCCESS == GLB_Get_And_Clr_First_Set_From_U64(&ips, &bitfield)) { + switch (bitfield) { + case GLB_AHB_CLOCK_IP_CPU: + tmpValCfg0 |= (1 << 0); + break; + case GLB_AHB_CLOCK_IP_SDU: + tmpValCfg0 |= (1 << 1); + break; + case GLB_AHB_CLOCK_IP_SEC: + tmpValCfg0 |= (1 << 2); + tmpValCfg1 |= (1 << 3); + tmpValCfg1 |= (1 << 4); + break; + case GLB_AHB_CLOCK_IP_DMA_0: + tmpValCfg0 |= (1 << 3); + tmpValCfg1 |= (1 << 12); + break; + case GLB_AHB_CLOCK_IP_DMA_1: + break; + case GLB_AHB_CLOCK_IP_DMA_2: + break; + case GLB_AHB_CLOCK_IP_CCI: + tmpValCfg0 |= (1 << 4); + break; + case GLB_AHB_CLOCK_IP_RF_TOP: + break; + case GLB_AHB_CLOCK_IP_GPIP: + tmpValCfg1 |= (1 << 2); + break; + case GLB_AHB_CLOCK_IP_TZC: + tmpValCfg1 |= (1 << 5); + break; + case GLB_AHB_CLOCK_IP_EF_CTRL: + tmpValCfg1 |= (1 << 7); + break; + case GLB_AHB_CLOCK_IP_SF_CTRL: + tmpValCfg1 |= (1 << 11); + break; + case GLB_AHB_CLOCK_IP_EMAC: + tmpValCfg1 |= (1 << 13); + break; + case GLB_AHB_CLOCK_IP_UART0: + tmpValCfg1 |= (1 << 16); + break; + case GLB_AHB_CLOCK_IP_UART1: + tmpValCfg1 |= (1 << 17); + break; + case GLB_AHB_CLOCK_IP_UART2: + break; + case GLB_AHB_CLOCK_IP_UART3: + break; + case GLB_AHB_CLOCK_IP_UART4: + break; + case GLB_AHB_CLOCK_IP_SPI: + tmpValCfg1 |= (1 << 18); + break; + case GLB_AHB_CLOCK_IP_I2C: + tmpValCfg1 |= (1 << 19); + break; + case GLB_AHB_CLOCK_IP_PWM: + tmpValCfg1 |= (1 << 20); + break; + case GLB_AHB_CLOCK_IP_TIMER: + tmpValCfg1 |= (1 << 21); + break; + case GLB_AHB_CLOCK_IP_IR: + tmpValCfg1 |= (1 << 22); + break; + case GLB_AHB_CLOCK_IP_CHECKSUM: + tmpValCfg1 |= (1 << 23); + break; + case GLB_AHB_CLOCK_IP_QDEC: + tmpValCfg1 |= (1 << 24); + tmpValCfg1 |= (1 << 25); + tmpValCfg1 |= (1 << 26); + break; + case GLB_AHB_CLOCK_IP_KYS: + tmpValCfg1 |= (1 << 27); + break; + case GLB_AHB_CLOCK_IP_I2S: + tmpValCfg1 |= (1 << 26); + break; + case GLB_AHB_CLOCK_IP_USB11: + tmpValCfg1 |= (1 << 28); + break; + case GLB_AHB_CLOCK_IP_CAM: + tmpValCfg1 |= (1 << 29); + break; + case GLB_AHB_CLOCK_IP_MJPEG: + tmpValCfg1 |= (1 << 30); + break; + case GLB_AHB_CLOCK_IP_BT_BLE_NORMAL: + tmpValCfg2 |= (1 << 0); + tmpValCfg2 |= (1 << 4); + break; + case GLB_AHB_CLOCK_IP_BT_BLE_LP: + break; + case GLB_AHB_CLOCK_IP_ZB_NORMAL: + tmpValCfg2 |= (1 << 0); + break; + case GLB_AHB_CLOCK_IP_ZB_LP: + break; + case GLB_AHB_CLOCK_IP_WIFI_NORMAL: + break; + case GLB_AHB_CLOCK_IP_WIFI_LP: + break; + case GLB_AHB_CLOCK_IP_BT_BLE_2_NORMAL: + break; + case GLB_AHB_CLOCK_IP_BT_BLE_2_LP: + break; + case GLB_AHB_CLOCK_IP_EMI_MISC: + break; + case GLB_AHB_CLOCK_IP_PSRAM0_CTRL: + break; + case GLB_AHB_CLOCK_IP_PSRAM1_CTRL: + break; + case GLB_AHB_CLOCK_IP_USB20: + break; + case GLB_AHB_CLOCK_IP_MIX2: + break; + case GLB_AHB_CLOCK_IP_AUDIO: + break; + case GLB_AHB_CLOCK_IP_SDH: + break; + default: + break; + } + } + } + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG0, tmpValCfg0); + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpValCfg1); + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG2, tmpValCfg2); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief BMX init + * + * @param BmxCfg: BMX config + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_BMX_Init(BMX_Cfg_Type *BmxCfg) { + uint32_t tmpVal = 0; + + CHECK_PARAM((BmxCfg->timeoutEn) <= 0xF); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_BMX_TIMEOUT_EN, BmxCfg->timeoutEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_BMX_ERR_EN, BmxCfg->errEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_BMX_ARB_MODE, BmxCfg->arbMod); + BL_WR_REG(GLB_BASE, GLB_BMX_CFG1, tmpVal); + +#ifndef BFLB_USE_HAL_DRIVER + Interrupt_Handler_Register(BMX_ERR_IRQn, BMX_ERR_IRQHandler); + Interrupt_Handler_Register(BMX_TO_IRQn, BMX_TO_IRQHandler); #endif -/****************************************************************************/ /** - * @brief set UART clock - * - * @param enable: Enable or disable UART clock - * @param clkSel: UART clock type - * @param div: clock divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_UART_CLK(uint8_t enable, HBN_UART_CLK_Type clkSel, uint8_t div) -{ - uint32_t tmpVal = 0; + return SUCCESS; +} - CHECK_PARAM((div <= 0x7)); - CHECK_PARAM(IS_HBN_UART_CLK_TYPE(clkSel)); +/****************************************************************************/ /** + * @brief BMX address monitor enable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_BMX_Addr_Monitor_Enable(void) { + uint32_t tmpVal = 0; - /* disable UART clock first */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_UART_CLK_EN); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_BMX_ERR_ADDR_DIS); + BL_WR_REG(GLB_BASE, GLB_BMX_CFG2, tmpVal); - /* Set div */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_UART_CLK_DIV, div); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + return SUCCESS; +} - /* Select clock source for uart */ - HBN_Set_UART_CLK_Sel(clkSel); +/****************************************************************************/ /** + * @brief BMX address monitor disable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_BMX_Addr_Monitor_Disable(void) { + uint32_t tmpVal = 0; - /* Set enable or disable */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_UART_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_UART_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG2); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_BMX_ERR_ADDR_DIS); + BL_WR_REG(GLB_BASE, GLB_BMX_CFG2, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief select chip clock out 0 type - * - * @param clkSel: chip clock out type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_Chip_Out_0_CLK_Sel(GLB_CHIP_CLK_OUT_Type clkSel) -{ - uint32_t tmpVal = 0; + * @brief BMX bus error response enable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_BMX_BusErrResponse_Enable(void) { + uint32_t tmpVal = 0; - CHECK_PARAM(IS_GLB_CHIP_CLK_OUT_TYPE(clkSel)); + tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG1); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_BMX_ERR_EN); + BL_WR_REG(GLB_BASE, GLB_BMX_CFG1, tmpVal); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CHIP_CLK_OUT_0_SEL, clkSel); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief select chip clock out 1 type - * - * @param clkSel: chip clock out type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_Chip_Out_1_CLK_Sel(GLB_CHIP_CLK_OUT_Type clkSel) -{ - uint32_t tmpVal = 0; + * @brief BMX bus error response disable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_BMX_BusErrResponse_Disable(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG1); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_BMX_ERR_EN); + BL_WR_REG(GLB_BASE, GLB_BMX_CFG1, tmpVal); - CHECK_PARAM(IS_GLB_CHIP_CLK_OUT_TYPE(clkSel)); + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Get BMX error status + * + * @param errType: BMX error status type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type GLB_BMX_Get_Status(BMX_BUS_ERR_Type errType) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CHIP_CLK_OUT_1_SEL, clkSel); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + CHECK_PARAM(IS_BMX_BUS_ERR_TYPE(errType)); - return SUCCESS; + tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG2); + if (errType == BMX_BUS_ERR_TRUSTZONE_DECODE) { + return BL_GET_REG_BITS_VAL(tmpVal, GLB_BMX_ERR_TZ) ? SET : RESET; + } else { + return BL_GET_REG_BITS_VAL(tmpVal, GLB_BMX_ERR_DEC) ? SET : RESET; + } } /****************************************************************************/ /** - * @brief set I2C clock - * - * @param enable: Enable or disable I2C clock - * @param div: clock divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_I2C_CLK(uint8_t enable, uint8_t div) -{ - uint32_t tmpVal = 0; + * @brief Get BMX error address + * + * @param None + * + * @return NP BMX error address + * + *******************************************************************************/ +uint32_t GLB_BMX_Get_Err_Addr(void) { return BL_RD_REG(GLB_BASE, GLB_BMX_ERR_ADDR); } - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_I2C_CLK_DIV, div); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); +/****************************************************************************/ /** + * @brief BMX error interrupt callback install + * + * @param intType: BMX error interrupt type + * @param cbFun: callback + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type BMX_ERR_INT_Callback_Install(BMX_ERR_INT_Type intType, intCallback_Type *cbFun) { + CHECK_PARAM(IS_BMX_ERR_INT_TYPE(intType)); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_I2C_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_I2C_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + glbBmxErrIntCbfArra[intType] = cbFun; - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief invert eth rx clock - * - * @param enable: invert or not invert - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Invert_ETH_RX_CLK(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief BMX ERR interrupt IRQ handler + * + * @param None + * + * @return None + * + *******************************************************************************/ +#ifndef BFLB_USE_HAL_DRIVER +void BMX_ERR_IRQHandler(void) { + BMX_ERR_INT_Type intType; - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_ETH_RX_CLK); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_ETH_RX_CLK); + for (intType = BMX_ERR_INT_ERR; intType < BMX_ERR_INT_ALL; intType++) { + if (glbBmxErrIntCbfArra[intType] != NULL) { + glbBmxErrIntCbfArra[intType](); } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + } - return SUCCESS; + while (1) { + // MSG("BMX_ERR_IRQHandler\r\n"); + BL702_Delay_MS(1000); + } } +#endif /****************************************************************************/ /** - * @brief invert rf test clock out - * - * @param enable: invert or not invert - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Invert_RF_TEST_O_CLK(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief BMX timeout interrupt callback install + * + * @param intType: BMX timeout interrupt type + * @param cbFun: callback + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type BMX_TIMEOUT_INT_Callback_Install(BMX_TO_INT_Type intType, intCallback_Type *cbFun) { + CHECK_PARAM(IS_BMX_TO_INT_TYPE(intType)); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_RF_TEST_CLK_O); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_RF_TEST_CLK_O); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + glbBmxToIntCbfArra[intType] = cbFun; - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief set SPI clock - * - * @param enable: Enable or disable SPI clock - * @param div: clock divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_SPI_CLK(uint8_t enable, uint8_t div) -{ - uint32_t tmpVal = 0; + * @brief BMX Time Out interrupt IRQ handler + * + * @param None + * + * @return None + * + *******************************************************************************/ +#ifndef BFLB_USE_HAL_DRIVER +void BMX_TO_IRQHandler(void) { + BMX_TO_INT_Type intType; - CHECK_PARAM((div <= 0x1F)); + for (intType = BMX_TO_INT_TIMEOUT; intType < BMX_TO_INT_ALL; intType++) { + if (glbBmxToIntCbfArra[intType] != NULL) { + glbBmxToIntCbfArra[intType](); + } + } - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SPI_CLK_DIV, div); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + while (1) { + // MSG("BMX_TO_IRQHandler\r\n"); + BL702_Delay_MS(1000); + } +} +#endif - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_SPI_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_SPI_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); +/****************************************************************************/ /** + * @brief set sram_ret value + * + * @param value: value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_SRAM_RET(uint32_t value) { + BL_WR_REG(GLB_BASE, GLB_SRAM_RET, value); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief invert eth tx clock - * - * @param enable: invert or not invert - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Invert_ETH_TX_CLK(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief get sram_ret value + * + * @param None + * + * @return value + * + *******************************************************************************/ +uint32_t GLB_Get_SRAM_RET(void) { return BL_RD_REG(GLB_BASE, GLB_SRAM_RET); } - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_ETH_TX_CLK); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_ETH_TX_CLK); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); +/****************************************************************************/ /** + * @brief set sram_slp value + * + * @param value: value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_SRAM_SLP(uint32_t value) { + BL_WR_REG(GLB_BASE, GLB_SRAM_SLP, value); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief invert eth ref clock out - * - * @param enable: invert or not invert - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Invert_ETH_REF_O_CLK(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief get sram_slp value + * + * @param None + * + * @return value + * + *******************************************************************************/ +uint32_t GLB_Get_SRAM_SLP(void) { return BL_RD_REG(GLB_BASE, GLB_SRAM_SLP); } - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_ETH_REF_CLK_O); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_ETH_REF_CLK_O); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); +/****************************************************************************/ /** + * @brief set sram_param value + * + * @param value: value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_SRAM_PARM(uint32_t value) { + BL_WR_REG(GLB_BASE, GLB_SRAM_PARM, value); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief select eth ref clock out - * - * @param clkSel: eth ref clock type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_ETH_REF_O_CLK_Sel(GLB_ETH_REF_CLK_OUT_Type clkSel) -{ - uint32_t tmpVal = 0; + * @brief get sram_parm value + * + * @param None + * + * @return value + * + *******************************************************************************/ +uint32_t GLB_Get_SRAM_PARM(void) { return BL_RD_REG(GLB_BASE, GLB_SRAM_PARM); } - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_SEL_ETH_REF_CLK_O, clkSel); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); +/****************************************************************************/ /** + * @brief select EM type + * + * @param emType: EM type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_EM_Sel(GLB_EM_Type emType) { + uint32_t tmpVal = 0; - return SUCCESS; + CHECK_PARAM(IS_GLB_EM_TYPE(emType)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_SEAM_MISC); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_EM_SEL, emType); + BL_WR_REG(GLB_BASE, GLB_SEAM_MISC, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief select PKA clock source - * - * @param clkSel: PKA clock selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_PKA_CLK_Sel(GLB_PKA_CLK_Type clkSel) -{ - uint32_t tmpVal = 0; + * @brief select pin as EMAC or CAM + * + * @param pinType: pin type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_SWAP_EMAC_CAM_Pin(GLB_EMAC_CAM_PIN_Type pinType) { + uint32_t tmpVal = 0; - CHECK_PARAM(IS_GLB_PKA_CLK_TYPE(clkSel)); + CHECK_PARAM(IS_GLB_EMAC_CAM_PIN_TYPE(pinType)); - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PKA_CLK_SEL, clkSel); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PIN_SEL_EMAC_CAM, pinType); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Software system reset - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_SW_System_Reset(void) -{ - /***********************************************************************************/ - /* NOTE */ - /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ - /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ - /***********************************************************************************/ - uint32_t tmpVal; - - /* Swicth clock to 32M as default */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - GLB_CLK_SET_DUMMY_WAIT; - - /* HCLK is RC32M , so BCLK/HCLK no need divider */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, 0); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - GLB_REG_BCLK_DIS_TRUE; - GLB_REG_BCLK_DIS_FALSE; - GLB_CLK_SET_DUMMY_WAIT; - - /* Do reset */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); - //tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_CTRL_PWRON_RST); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); - - /* waiting for reset */ - while (1) { - BL702_Delay_US(10); - } - - return SUCCESS; -} -#endif + * @brief EXT_RST PAD SMT + * + * @param enable: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_Ext_Rst_Smt(uint8_t enable) { + uint32_t tmpVal = 0; -/****************************************************************************/ /** - * @brief Software CPU reset - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_SW_CPU_Reset(void) -{ - /***********************************************************************************/ - /* NOTE */ - /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ - /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ - /***********************************************************************************/ - uint32_t tmpVal; - - /* Swicth clock to 32M as default */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - GLB_CLK_SET_DUMMY_WAIT; - - /* HCLK is RC32M , so BCLK/HCLK no need divider */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, 0); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - GLB_REG_BCLK_DIS_TRUE; - GLB_REG_BCLK_DIS_FALSE; - GLB_CLK_SET_DUMMY_WAIT; - - /* Do reset */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); - //tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_CTRL_SYS_RESET); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); - //tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_CTRL_PWRON_RST); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); - - /* waiting for reset */ - while (1) { - BL702_Delay_US(10); - } + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_EXT_RST_SMT); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_EXT_RST_SMT); + } + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } -#endif /****************************************************************************/ /** - * @brief Software power on reset - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_SW_POR_Reset(void) -{ - /***********************************************************************************/ - /* NOTE */ - /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ - /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ - /***********************************************************************************/ - uint32_t tmpVal; - - /* Swicth clock to 32M as default */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - GLB_CLK_SET_DUMMY_WAIT; - - /* HCLK is RC32M , so BCLK/HCLK no need divider */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, 0); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - GLB_REG_BCLK_DIS_TRUE; - GLB_REG_BCLK_DIS_FALSE; - GLB_CLK_SET_DUMMY_WAIT; - - /* Do reset */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); - - /* waiting for reset */ - while (1) { - BL702_Delay_US(10); - } + * @brief Key Scan Column Drive + * + * @param enable: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_Kys_Drv_Col(uint8_t enable) { + uint32_t tmpVal = 0; - return SUCCESS; + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_KYS_DRV_VAL); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_KYS_DRV_VAL); + } + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); + + return SUCCESS; } -#endif /****************************************************************************/ /** - * @brief Reset slave 1 - * - * @param slave1: slave num - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_AHB_Slave1_Reset(BL_AHB_Slave1_Type slave1) -{ - uint32_t tmpVal = 0; + * @brief swap UART gpio pins sig function + * + * @param swapSel: UART swap set gpio pins selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_UART_Sig_Swap_Set(uint8_t swapSel) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG1); - tmpVal &= (~(1 << slave1)); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG1, tmpVal); - BL_DRV_DUMMY; - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG1); - tmpVal |= (1 << slave1); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG1, tmpVal); - BL_DRV_DUMMY; - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG1); - tmpVal &= (~(1 << slave1)); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG1, tmpVal); + CHECK_PARAM((swapSel <= 0xF)); - return SUCCESS; + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_UART_SWAP_SET, swapSel); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief clock gate - * - * @param enable: ENABLE or DISABLE - * @param slave1: AHB slaveClk type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_AHB_Slave1_Clock_Gate(uint8_t enable, BL_AHB_Slave1_Type slave1) -{ - /* gate QDEC <=> gate QDEC0 + QDEC1 +QDEC2 + I2S */ - /* gate I2S <=> gate I2S + QDEC2 */ - - uint32_t tmpVal = 0; - - if ((BL_AHB_SLAVE1_GLB == slave1) || (BL_AHB_SLAVE1_TZ2 == slave1) || - (BL_AHB_SLAVE1_CCI == slave1) || (BL_AHB_SLAVE1_L1C == slave1) || - (BL_AHB_SLAVE1_PDS_HBN_AON_HBNRAM == slave1)) { - /* not support */ - return ERROR; - } - - /* gate QDEC and I2S */ - if (BL_AHB_SLAVE1_QDEC == slave1) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); - if (enable) { - /* clear bit means clock gate */ - tmpVal &= (~(1 << 0x18)); - tmpVal &= (~(1 << 0x19)); - tmpVal &= (~(1 << 0x1A)); - } else { - /* set bit means clock pass */ - tmpVal |= (1 << 0x18); - tmpVal |= (1 << 0x19); - tmpVal |= (1 << 0x1A); - } - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); - return SUCCESS; - } - - /* gate KYS */ - if (BL_AHB_SLAVE1_KYS == slave1) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); - if (enable) { - /* clear bit means clock gate */ - tmpVal &= (~(1 << 0x1B)); - } else { - /* set bit means clock pass */ - tmpVal |= (1 << 0x1B); - } - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); - return SUCCESS; - } + * @brief swap JTAG gpio pins function + * + * @param swapSel: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_JTAG_Sig_Swap_Set(uint8_t swapSel) { + uint32_t tmpVal = 0; - /* gate I2S and QDEC2 */ - if (BL_AHB_SLAVE1_I2S == slave1) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); - if (enable) { - /* clear bit means clock gate */ - tmpVal &= (~(1 << 0x1A)); - } else { - /* set bit means clock pass */ - tmpVal |= (1 << 0x1A); - } - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); - return SUCCESS; - } + CHECK_PARAM((swapSel <= 0xFF)); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); - if (enable) { - /* clear bit means clock gate */ - tmpVal &= (~(1 << slave1)); - } else { - /* set bit means clock pass */ - tmpVal |= (1 << slave1); - } - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_JTAG_SWAP_SET, swapSel); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief get IPs clock gate value - * - * @param None - * - * @return clock gate value - * -*******************************************************************************/ -uint64_t GLB_PER_Clock_Gate_Status_Get(void) -{ - /* api request from cjy */ - - uint32_t tmpValCfg0 = 0; - uint32_t tmpValCfg1 = 0; - uint32_t tmpValCfg2 = 0; - uint32_t targetBit = 0; - uint64_t targetVal = 0; - - tmpValCfg0 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG0); - tmpValCfg1 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); - tmpValCfg2 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG2); - for (uint8_t i = 0; i < 64; i++) { - targetBit = 0; - switch (i) { - case GLB_AHB_CLOCK_IP_CPU: - targetBit = tmpValCfg0 & (1 << 0); - break; - case GLB_AHB_CLOCK_IP_SDU: - targetBit = tmpValCfg0 & (1 << 1); - break; - case GLB_AHB_CLOCK_IP_SEC: - targetBit = (tmpValCfg0 & (1 << 2)) && (tmpValCfg1 & (1 << 3)) && (tmpValCfg1 & (1 << 4)); - break; - case GLB_AHB_CLOCK_IP_DMA_0: - targetBit = (tmpValCfg0 & (1 << 3)) && (tmpValCfg1 & (1 << 12)); - break; - case GLB_AHB_CLOCK_IP_DMA_1: - break; - case GLB_AHB_CLOCK_IP_DMA_2: - break; - case GLB_AHB_CLOCK_IP_CCI: - targetBit = tmpValCfg0 & (1 << 4); - break; - case GLB_AHB_CLOCK_IP_RF_TOP: - break; - case GLB_AHB_CLOCK_IP_GPIP: - targetBit = tmpValCfg1 & (1 << 2); - break; - case GLB_AHB_CLOCK_IP_TZC: - targetBit = tmpValCfg1 & (1 << 5); - break; - case GLB_AHB_CLOCK_IP_EF_CTRL: - targetBit = tmpValCfg1 & (1 << 7); - break; - case GLB_AHB_CLOCK_IP_SF_CTRL: - targetBit = tmpValCfg1 & (1 << 11); - break; - case GLB_AHB_CLOCK_IP_EMAC: - targetBit = tmpValCfg1 & (1 << 13); - break; - case GLB_AHB_CLOCK_IP_UART0: - targetBit = tmpValCfg1 & (1 << 16); - break; - case GLB_AHB_CLOCK_IP_UART1: - targetBit = tmpValCfg1 & (1 << 17); - break; - case GLB_AHB_CLOCK_IP_UART2: - break; - case GLB_AHB_CLOCK_IP_UART3: - break; - case GLB_AHB_CLOCK_IP_UART4: - break; - case GLB_AHB_CLOCK_IP_SPI: - targetBit = tmpValCfg1 & (1 << 18); - break; - case GLB_AHB_CLOCK_IP_I2C: - targetBit = tmpValCfg1 & (1 << 19); - break; - case GLB_AHB_CLOCK_IP_PWM: - targetBit = tmpValCfg1 & (1 << 20); - break; - case GLB_AHB_CLOCK_IP_TIMER: - targetBit = tmpValCfg1 & (1 << 21); - break; - case GLB_AHB_CLOCK_IP_IR: - targetBit = tmpValCfg1 & (1 << 22); - break; - case GLB_AHB_CLOCK_IP_CHECKSUM: - targetBit = tmpValCfg1 & (1 << 23); - break; - case GLB_AHB_CLOCK_IP_QDEC: - targetBit = (tmpValCfg1 & (1 << 24)) && (tmpValCfg1 & (1 << 25)) && (tmpValCfg1 & (1 << 26)); - break; - case GLB_AHB_CLOCK_IP_KYS: - targetBit = tmpValCfg1 & (1 << 27); - break; - case GLB_AHB_CLOCK_IP_I2S: - targetBit = tmpValCfg1 & (1 << 26); - break; - case GLB_AHB_CLOCK_IP_USB11: - targetBit = tmpValCfg1 & (1 << 28); - break; - case GLB_AHB_CLOCK_IP_CAM: - targetBit = tmpValCfg1 & (1 << 29); - break; - case GLB_AHB_CLOCK_IP_MJPEG: - targetBit = tmpValCfg1 & (1 << 30); - break; - case GLB_AHB_CLOCK_IP_BT_BLE_NORMAL: - targetBit = (tmpValCfg2 & (1 << 0)) && (tmpValCfg2 & (1 << 4)); - break; - case GLB_AHB_CLOCK_IP_BT_BLE_LP: - break; - case GLB_AHB_CLOCK_IP_ZB_NORMAL: - targetBit = tmpValCfg2 & (1 << 0); - break; - case GLB_AHB_CLOCK_IP_ZB_LP: - break; - case GLB_AHB_CLOCK_IP_WIFI_NORMAL: - break; - case GLB_AHB_CLOCK_IP_WIFI_LP: - break; - case GLB_AHB_CLOCK_IP_BT_BLE_2_NORMAL: - break; - case GLB_AHB_CLOCK_IP_BT_BLE_2_LP: - break; - case GLB_AHB_CLOCK_IP_EMI_MISC: - break; - case GLB_AHB_CLOCK_IP_PSRAM0_CTRL: - break; - case GLB_AHB_CLOCK_IP_PSRAM1_CTRL: - break; - case GLB_AHB_CLOCK_IP_USB20: - break; - case GLB_AHB_CLOCK_IP_MIX2: - break; - case GLB_AHB_CLOCK_IP_AUDIO: - break; - case GLB_AHB_CLOCK_IP_SDH: - break; - default: - break; - } - if (!targetBit) { - targetVal |= ((uint64_t)1 << i); - } - } + * @brief CCI use GPIO 0 1 2 7 + * + * @param enable: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_CCI_Use_IO_0_1_2_7(uint8_t enable) { + uint32_t tmpVal = 0; - return targetVal; + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_P3_CCI_USE_IO_0_2_7); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_P3_CCI_USE_IO_0_2_7); + } + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief get first 1 from u64, then clear it - * - * @param val: target value - * @param bit: first 1 in bit - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -static BL_Err_Type GLB_Get_And_Clr_First_Set_From_U64(uint64_t *val, uint32_t *bit) -{ - if (!*val) { - return ERROR; - } + * @brief CCI use JTAG pin + * + * @param enable: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_CCI_Use_Jtag_Pin(uint8_t enable) { + uint32_t tmpVal = 0; - for (uint8_t i = 0; i < 64; i++) { - if ((*val) & ((uint64_t)1 << i)) { - *bit = i; - (*val) &= ~((uint64_t)1 << i); - break; - } - } + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CCI_USE_JTAG_PIN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CCI_USE_JTAG_PIN); + } + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief hold IPs clock - * - * @param ips: GLB_AHB_CLOCK_IP_xxx | GLB_AHB_CLOCK_IP_xxx | ...... - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_PER_Clock_Gate(uint64_t ips) -{ - /* api request from cjy */ - - uint32_t tmpValCfg0 = 0; - uint32_t tmpValCfg1 = 0; - uint32_t tmpValCfg2 = 0; - uint32_t bitfield = 0; - - tmpValCfg0 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG0); - tmpValCfg1 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); - tmpValCfg2 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG2); - while (ips) { - if (SUCCESS == GLB_Get_And_Clr_First_Set_From_U64(&ips, &bitfield)) { - switch (bitfield) { - case GLB_AHB_CLOCK_IP_CPU: - tmpValCfg0 &= ~(1 << 0); - break; - case GLB_AHB_CLOCK_IP_SDU: - tmpValCfg0 &= ~(1 << 1); - break; - case GLB_AHB_CLOCK_IP_SEC: - tmpValCfg0 &= ~(1 << 2); - tmpValCfg1 &= ~(1 << 3); - tmpValCfg1 &= ~(1 << 4); - break; - case GLB_AHB_CLOCK_IP_DMA_0: - tmpValCfg0 &= ~(1 << 3); - tmpValCfg1 &= ~(1 << 12); - break; - case GLB_AHB_CLOCK_IP_DMA_1: - break; - case GLB_AHB_CLOCK_IP_DMA_2: - break; - case GLB_AHB_CLOCK_IP_CCI: - tmpValCfg0 &= ~(1 << 4); - break; - case GLB_AHB_CLOCK_IP_RF_TOP: - break; - case GLB_AHB_CLOCK_IP_GPIP: - tmpValCfg1 &= ~(1 << 2); - break; - case GLB_AHB_CLOCK_IP_TZC: - tmpValCfg1 &= ~(1 << 5); - break; - case GLB_AHB_CLOCK_IP_EF_CTRL: - tmpValCfg1 &= ~(1 << 7); - break; - case GLB_AHB_CLOCK_IP_SF_CTRL: - tmpValCfg1 &= ~(1 << 11); - break; - case GLB_AHB_CLOCK_IP_EMAC: - tmpValCfg1 &= ~(1 << 13); - break; - case GLB_AHB_CLOCK_IP_UART0: - tmpValCfg1 &= ~(1 << 16); - break; - case GLB_AHB_CLOCK_IP_UART1: - tmpValCfg1 &= ~(1 << 17); - break; - case GLB_AHB_CLOCK_IP_UART2: - break; - case GLB_AHB_CLOCK_IP_UART3: - break; - case GLB_AHB_CLOCK_IP_UART4: - break; - case GLB_AHB_CLOCK_IP_SPI: - tmpValCfg1 &= ~(1 << 18); - break; - case GLB_AHB_CLOCK_IP_I2C: - tmpValCfg1 &= ~(1 << 19); - break; - case GLB_AHB_CLOCK_IP_PWM: - tmpValCfg1 &= ~(1 << 20); - break; - case GLB_AHB_CLOCK_IP_TIMER: - tmpValCfg1 &= ~(1 << 21); - break; - case GLB_AHB_CLOCK_IP_IR: - tmpValCfg1 &= ~(1 << 22); - break; - case GLB_AHB_CLOCK_IP_CHECKSUM: - tmpValCfg1 &= ~(1 << 23); - break; - case GLB_AHB_CLOCK_IP_QDEC: - tmpValCfg1 &= ~(1 << 24); - tmpValCfg1 &= ~(1 << 25); - tmpValCfg1 &= ~(1 << 26); - break; - case GLB_AHB_CLOCK_IP_KYS: - tmpValCfg1 &= ~(1 << 27); - break; - case GLB_AHB_CLOCK_IP_I2S: - tmpValCfg1 &= ~(1 << 26); - break; - case GLB_AHB_CLOCK_IP_USB11: - tmpValCfg1 &= ~(1 << 28); - break; - case GLB_AHB_CLOCK_IP_CAM: - tmpValCfg1 &= ~(1 << 29); - break; - case GLB_AHB_CLOCK_IP_MJPEG: - tmpValCfg1 &= ~(1 << 30); - break; - case GLB_AHB_CLOCK_IP_BT_BLE_NORMAL: - tmpValCfg2 &= ~(1 << 0); - tmpValCfg2 &= ~(1 << 4); - break; - case GLB_AHB_CLOCK_IP_BT_BLE_LP: - break; - case GLB_AHB_CLOCK_IP_ZB_NORMAL: - tmpValCfg2 &= ~(1 << 0); - break; - case GLB_AHB_CLOCK_IP_ZB_LP: - break; - case GLB_AHB_CLOCK_IP_WIFI_NORMAL: - break; - case GLB_AHB_CLOCK_IP_WIFI_LP: - break; - case GLB_AHB_CLOCK_IP_BT_BLE_2_NORMAL: - break; - case GLB_AHB_CLOCK_IP_BT_BLE_2_LP: - break; - case GLB_AHB_CLOCK_IP_EMI_MISC: - break; - case GLB_AHB_CLOCK_IP_PSRAM0_CTRL: - break; - case GLB_AHB_CLOCK_IP_PSRAM1_CTRL: - break; - case GLB_AHB_CLOCK_IP_USB20: - break; - case GLB_AHB_CLOCK_IP_MIX2: - break; - case GLB_AHB_CLOCK_IP_AUDIO: - break; - case GLB_AHB_CLOCK_IP_SDH: - break; - default: - break; - } - } - } - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG0, tmpValCfg0); - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpValCfg1); - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG2, tmpValCfg2); - - return SUCCESS; -} + * @brief swap SPI0 MOSI with MISO + * + * @param newState: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Swap_SPI_0_MOSI_With_MISO(BL_Fun_Type newState) { + uint32_t tmpVal = 0; -/****************************************************************************/ /** - * @brief release IPs clock - * - * @param ips: GLB_AHB_CLOCK_IP_xxx | GLB_AHB_CLOCK_IP_xxx | ...... - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_PER_Clock_UnGate(uint64_t ips) -{ - /* api request from cjy */ - - uint32_t tmpValCfg0 = 0; - uint32_t tmpValCfg1 = 0; - uint32_t tmpValCfg2 = 0; - uint32_t bitfield = 0; - - tmpValCfg0 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG0); - tmpValCfg1 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); - tmpValCfg2 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG2); - while (ips) { - if (SUCCESS == GLB_Get_And_Clr_First_Set_From_U64(&ips, &bitfield)) { - switch (bitfield) { - case GLB_AHB_CLOCK_IP_CPU: - tmpValCfg0 |= (1 << 0); - break; - case GLB_AHB_CLOCK_IP_SDU: - tmpValCfg0 |= (1 << 1); - break; - case GLB_AHB_CLOCK_IP_SEC: - tmpValCfg0 |= (1 << 2); - tmpValCfg1 |= (1 << 3); - tmpValCfg1 |= (1 << 4); - break; - case GLB_AHB_CLOCK_IP_DMA_0: - tmpValCfg0 |= (1 << 3); - tmpValCfg1 |= (1 << 12); - break; - case GLB_AHB_CLOCK_IP_DMA_1: - break; - case GLB_AHB_CLOCK_IP_DMA_2: - break; - case GLB_AHB_CLOCK_IP_CCI: - tmpValCfg0 |= (1 << 4); - break; - case GLB_AHB_CLOCK_IP_RF_TOP: - break; - case GLB_AHB_CLOCK_IP_GPIP: - tmpValCfg1 |= (1 << 2); - break; - case GLB_AHB_CLOCK_IP_TZC: - tmpValCfg1 |= (1 << 5); - break; - case GLB_AHB_CLOCK_IP_EF_CTRL: - tmpValCfg1 |= (1 << 7); - break; - case GLB_AHB_CLOCK_IP_SF_CTRL: - tmpValCfg1 |= (1 << 11); - break; - case GLB_AHB_CLOCK_IP_EMAC: - tmpValCfg1 |= (1 << 13); - break; - case GLB_AHB_CLOCK_IP_UART0: - tmpValCfg1 |= (1 << 16); - break; - case GLB_AHB_CLOCK_IP_UART1: - tmpValCfg1 |= (1 << 17); - break; - case GLB_AHB_CLOCK_IP_UART2: - break; - case GLB_AHB_CLOCK_IP_UART3: - break; - case GLB_AHB_CLOCK_IP_UART4: - break; - case GLB_AHB_CLOCK_IP_SPI: - tmpValCfg1 |= (1 << 18); - break; - case GLB_AHB_CLOCK_IP_I2C: - tmpValCfg1 |= (1 << 19); - break; - case GLB_AHB_CLOCK_IP_PWM: - tmpValCfg1 |= (1 << 20); - break; - case GLB_AHB_CLOCK_IP_TIMER: - tmpValCfg1 |= (1 << 21); - break; - case GLB_AHB_CLOCK_IP_IR: - tmpValCfg1 |= (1 << 22); - break; - case GLB_AHB_CLOCK_IP_CHECKSUM: - tmpValCfg1 |= (1 << 23); - break; - case GLB_AHB_CLOCK_IP_QDEC: - tmpValCfg1 |= (1 << 24); - tmpValCfg1 |= (1 << 25); - tmpValCfg1 |= (1 << 26); - break; - case GLB_AHB_CLOCK_IP_KYS: - tmpValCfg1 |= (1 << 27); - break; - case GLB_AHB_CLOCK_IP_I2S: - tmpValCfg1 |= (1 << 26); - break; - case GLB_AHB_CLOCK_IP_USB11: - tmpValCfg1 |= (1 << 28); - break; - case GLB_AHB_CLOCK_IP_CAM: - tmpValCfg1 |= (1 << 29); - break; - case GLB_AHB_CLOCK_IP_MJPEG: - tmpValCfg1 |= (1 << 30); - break; - case GLB_AHB_CLOCK_IP_BT_BLE_NORMAL: - tmpValCfg2 |= (1 << 0); - tmpValCfg2 |= (1 << 4); - break; - case GLB_AHB_CLOCK_IP_BT_BLE_LP: - break; - case GLB_AHB_CLOCK_IP_ZB_NORMAL: - tmpValCfg2 |= (1 << 0); - break; - case GLB_AHB_CLOCK_IP_ZB_LP: - break; - case GLB_AHB_CLOCK_IP_WIFI_NORMAL: - break; - case GLB_AHB_CLOCK_IP_WIFI_LP: - break; - case GLB_AHB_CLOCK_IP_BT_BLE_2_NORMAL: - break; - case GLB_AHB_CLOCK_IP_BT_BLE_2_LP: - break; - case GLB_AHB_CLOCK_IP_EMI_MISC: - break; - case GLB_AHB_CLOCK_IP_PSRAM0_CTRL: - break; - case GLB_AHB_CLOCK_IP_PSRAM1_CTRL: - break; - case GLB_AHB_CLOCK_IP_USB20: - break; - case GLB_AHB_CLOCK_IP_MIX2: - break; - case GLB_AHB_CLOCK_IP_AUDIO: - break; - case GLB_AHB_CLOCK_IP_SDH: - break; - default: - break; - } - } - } - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG0, tmpValCfg0); - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpValCfg1); - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG2, tmpValCfg2); + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_SPI_0_SWAP, newState); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief BMX init - * - * @param BmxCfg: BMX config - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_BMX_Init(BMX_Cfg_Type *BmxCfg) -{ - uint32_t tmpVal = 0; + * @brief Select SPI_0 act mode + * + * @param mod: SPI work mode + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_SPI_0_ACT_MOD_Sel(GLB_SPI_PAD_ACT_AS_Type mod) { + uint32_t tmpVal; - CHECK_PARAM((BmxCfg->timeoutEn) <= 0xF); + CHECK_PARAM(IS_GLB_SPI_PAD_ACT_AS_TYPE(mod)); - tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_BMX_TIMEOUT_EN, BmxCfg->timeoutEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_BMX_ERR_EN, BmxCfg->errEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_BMX_ARB_MODE, BmxCfg->arbMod); - BL_WR_REG(GLB_BASE, GLB_BMX_CFG1, tmpVal); - -#ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(BMX_ERR_IRQn, BMX_ERR_IRQHandler); - Interrupt_Handler_Register(BMX_TO_IRQn, BMX_TO_IRQHandler); -#endif + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_SPI_0_MASTER_MODE, mod); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief BMX address monitor enable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_BMX_Addr_Monitor_Enable(void) -{ - uint32_t tmpVal = 0; + * @brief use internal flash + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_Select_Internal_Flash(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_BMX_ERR_ADDR_DIS); - BL_WR_REG(GLB_BASE, GLB_BMX_CFG2, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x3f); + BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal); - return SUCCESS; + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief BMX address monitor disable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_BMX_Addr_Monitor_Disable(void) -{ - uint32_t tmpVal = 0; + * @brief use external flash + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_Select_External_Flash(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG2); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_BMX_ERR_ADDR_DIS); - BL_WR_REG(GLB_BASE, GLB_BMX_CFG2, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x00); + BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal); - return SUCCESS; + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief BMX bus error response enable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_BMX_BusErrResponse_Enable(void) -{ - uint32_t tmpVal = 0; + * @brief Deswap internal flash pin + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_Deswap_Flash_Pin(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG1); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_BMX_ERR_EN); - BL_WR_REG(GLB_BASE, GLB_BMX_CFG1, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief BMX bus error response disable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_BMX_BusErrResponse_Disable(void) -{ - uint32_t tmpVal = 0; + * @brief Swap internal flash CS and IO2 pin + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_Swap_Flash_CS_IO2_Pin(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG1); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_BMX_ERR_EN); - BL_WR_REG(GLB_BASE, GLB_BMX_CFG1, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief Get BMX error status - * - * @param errType: BMX error status type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type GLB_BMX_Get_Status(BMX_BUS_ERR_Type errType) -{ - uint32_t tmpVal = 0; + * @brief Swap internal flash IO3 and IO0 pin + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_Swap_Flash_IO0_IO3_Pin(void) { + uint32_t tmpVal; - CHECK_PARAM(IS_BMX_BUS_ERR_TYPE(errType)); + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG2); - if (errType == BMX_BUS_ERR_TRUSTZONE_DECODE) { - return BL_GET_REG_BITS_VAL(tmpVal, GLB_BMX_ERR_TZ) ? SET : RESET; - } else { - return BL_GET_REG_BITS_VAL(tmpVal, GLB_BMX_ERR_DEC) ? SET : RESET; - } + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief Get BMX error address - * - * @param None - * - * @return NP BMX error address - * -*******************************************************************************/ -uint32_t GLB_BMX_Get_Err_Addr(void) -{ - return BL_RD_REG(GLB_BASE, GLB_BMX_ERR_ADDR); + * @brief Swap internal flash IO3 and IO0 pin + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_Swap_Flash_Pin(void) { + /*To be removed*/ + + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief BMX error interrupt callback install - * - * @param intType: BMX error interrupt type - * @param cbFun: callback - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type BMX_ERR_INT_Callback_Install(BMX_ERR_INT_Type intType, intCallback_Type *cbFun) -{ - CHECK_PARAM(IS_BMX_ERR_INT_TYPE(intType)); + * @brief Select internal psram + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_Select_Internal_PSram(void) { + uint32_t tmpVal; - glbBmxErrIntCbfArra[intType] = cbFun; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x00); + BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal); - return SUCCESS; + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief BMX ERR interrupt IRQ handler - * - * @param None - * - * @return None - * -*******************************************************************************/ -#ifndef BFLB_USE_HAL_DRIVER -void BMX_ERR_IRQHandler(void) -{ - BMX_ERR_INT_Type intType; - - for (intType = BMX_ERR_INT_ERR; intType < BMX_ERR_INT_ALL; intType++) { - if (glbBmxErrIntCbfArra[intType] != NULL) { - glbBmxErrIntCbfArra[intType](); - } - } + * @brief set PDM clock + * + * @param enable: Enable or disable PDM clock + * @param div: clock divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_PDM_CLK(uint8_t enable, uint8_t div) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_PDM_CLK_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_PDM0_CLK_EN); + BL_WR_REG(GLB_BASE, GLB_PDM_CLK_CTRL, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_PDM_CLK_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_PDM0_CLK_DIV, div); + BL_WR_REG(GLB_BASE, GLB_PDM_CLK_CTRL, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_PDM_CLK_CTRL); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_PDM0_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_PDM0_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_PDM_CLK_CTRL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set MTimer clock + * + * @param enable: enable or disable MTimer clock + * @param clkSel: clock selection + * @param div: divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_MTimer_CLK(uint8_t enable, GLB_MTIMER_CLK_Type clkSel, uint32_t div) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GLB_MTIMER_CLK_TYPE(clkSel)); + CHECK_PARAM((div <= 0x1FFFF)); + + /* disable MTimer clock first */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CPU_CLK_CFG); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CPU_RTC_EN); + BL_WR_REG(GLB_BASE, GLB_CPU_CLK_CFG, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CPU_CLK_CFG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CPU_RTC_SEL, clkSel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CPU_RTC_DIV, div); + BL_WR_REG(GLB_BASE, GLB_CPU_CLK_CFG, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CPU_CLK_CFG); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CPU_RTC_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CPU_RTC_EN); + } + BL_WR_REG(GLB_BASE, GLB_CPU_CLK_CFG, tmpVal); - while (1) { - //MSG("BMX_ERR_IRQHandler\r\n"); - BL702_Delay_MS(1000); - } + return SUCCESS; } -#endif /****************************************************************************/ /** - * @brief BMX timeout interrupt callback install - * - * @param intType: BMX timeout interrupt type - * @param cbFun: callback - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type BMX_TIMEOUT_INT_Callback_Install(BMX_TO_INT_Type intType, intCallback_Type *cbFun) -{ - CHECK_PARAM(IS_BMX_TO_INT_TYPE(intType)); + * @brief set ADC clock + * + * @param enable: enable or disable ADC clock + * @param clkSel: ADC clock selection + * @param div: divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_ADC_CLK(uint8_t enable, GLB_ADC_CLK_Type clkSel, uint8_t div) { + uint32_t tmpVal; - glbBmxToIntCbfArra[intType] = cbFun; + CHECK_PARAM(IS_GLB_ADC_CLK_TYPE(clkSel)); - return SUCCESS; -} + /* disable ADC clock first */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPADC_32M_DIV_EN); + BL_WR_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL, tmpVal); -/****************************************************************************/ /** - * @brief BMX Time Out interrupt IRQ handler - * - * @param None - * - * @return None - * -*******************************************************************************/ -#ifndef BFLB_USE_HAL_DRIVER -void BMX_TO_IRQHandler(void) -{ - BMX_TO_INT_Type intType; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPADC_32M_CLK_DIV, div); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPADC_32M_CLK_SEL, clkSel); + BL_WR_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL, tmpVal); - for (intType = BMX_TO_INT_TIMEOUT; intType < BMX_TO_INT_ALL; intType++) { - if (glbBmxToIntCbfArra[intType] != NULL) { - glbBmxToIntCbfArra[intType](); - } - } + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPADC_32M_DIV_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPADC_32M_DIV_EN); + } + BL_WR_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL, tmpVal); - while (1) { - //MSG("BMX_TO_IRQHandler\r\n"); - BL702_Delay_MS(1000); - } + return SUCCESS; } -#endif /****************************************************************************/ /** - * @brief set sram_ret value - * - * @param value: value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_SRAM_RET(uint32_t value) -{ - BL_WR_REG(GLB_BASE, GLB_SRAM_RET, value); + * @brief set DAC clock + * + * @param enable: enable frequency divider or not + * @param clkSel: ADC clock selection + * @param div: src divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_DAC_CLK(uint8_t enable, GLB_DAC_CLK_Type clkSel, uint8_t div) { + uint32_t tmpVal; - return SUCCESS; + CHECK_PARAM(IS_GLB_DAC_CLK_TYPE(clkSel)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_COMP); + + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_CLK_SRC_SEL, clkSel); + + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_DIV, div); + + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_512K_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); + } + + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief select DIG clock source + * + * @param clkSel: DIG clock selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_DIG_CLK_Sel(GLB_DIG_CLK_Type clkSel) { + uint32_t tmpVal; + uint32_t dig512kEn; + uint32_t dig32kEn; + + /* disable DIG512K and DIG32K clock first */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + dig512kEn = BL_GET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_EN); + dig32kEn = BL_GET_REG_BITS_VAL(tmpVal, GLB_DIG_32K_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_32K_EN); + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_CLK_SRC_SEL, clkSel); + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + /* repristinate DIG512K and DIG32K clock */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_EN, dig512kEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_32K_EN, dig32kEn); + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set DIG 512K clock + * + * @param enable: enable or disable DIG 512K clock + * @param compensation: enable or disable DIG 512K clock compensation + * @param div: divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_DIG_512K_CLK(uint8_t enable, uint8_t compensation, uint8_t div) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + if (compensation) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_512K_COMP); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_COMP); + } + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_DIV, div); + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_512K_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); + } + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set DIG 32K clock + * + * @param enable: enable or disable DIG 32K clock + * @param compensation: enable or disable DIG 32K clock compensation + * @param div: divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_DIG_32K_CLK(uint8_t enable, uint8_t compensation, uint8_t div) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + if (compensation) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_32K_COMP); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_32K_COMP); + } + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_32K_DIV, div); + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_32K_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_32K_EN); + } + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set BT coex signal + * + * @param enable: ENABLE or DISABLE, if enable, the AP JTAG will be replaced by BT Coex Signal + * @param bandWidth: BT Bandwidth + * @param pti: BT Packet Traffic Information + * @param channel: BT Channel + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_BT_Coex_Signal(uint8_t enable, GLB_BT_BANDWIDTH_Type bandWidth, uint8_t pti, uint8_t channel) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_BT_BANDWIDTH_TYPE(bandWidth)); + CHECK_PARAM((pti <= 0xF)); + CHECK_PARAM((channel <= 78)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_COEX_BT_BW, bandWidth); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_COEX_BT_PTI, pti); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_COEX_BT_CHANNEL, channel); + BL_WR_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL); + if (enable) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_EN_GPIO_BT_COEX, 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_EN_GPIO_BT_COEX, 0); + } + BL_WR_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Select UART signal function + * + * @param sig: UART signal + * @param fun: UART function + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_UART_Fun_Sel(GLB_UART_SIG_Type sig, GLB_UART_SIG_FUN_Type fun) { + uint32_t sig_pos = 0; + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_UART_SIG_TYPE(sig)); + CHECK_PARAM(IS_GLB_UART_SIG_FUN_TYPE(fun)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_UART_SIG_SEL_0); + sig_pos = (sig * 4); + /* Clear original val */ + tmpVal &= (~(0xf << sig_pos)); + /* Set new value */ + tmpVal |= (fun << sig_pos); + BL_WR_REG(GLB_BASE, GLB_UART_SIG_SEL_0, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief power off DLL + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_CLOCK_SECTION GLB_Power_Off_DLL(void) { + uint32_t tmpVal = 0; + + /* GLB->dll.BF.ppu_dll = 0; */ + /* GLB->dll.BF.pu_dll = 0; */ + /* GLB->dll.BF.dll_reset = 1; */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PPU_DLL, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_DLL, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_RESET, 1); + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief get sram_ret value - * - * @param None - * - * @return value - * -*******************************************************************************/ -uint32_t GLB_Get_SRAM_RET(void) -{ - return BL_RD_REG(GLB_BASE, GLB_SRAM_RET); + * @brief power on DLL + * + * @param xtalType: DLL xtal type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_CLOCK_SECTION GLB_Power_On_DLL(GLB_DLL_XTAL_Type xtalType) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_DLL_XTAL_TYPE(xtalType)); + + /* GLB->dll.BF.dll_refclk_sel = XXX; */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + switch (xtalType) { + case GLB_DLL_XTAL_NONE: + return ERROR; + case GLB_DLL_XTAL_32M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_REFCLK_SEL, 0); + break; + case GLB_DLL_XTAL_RC32M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_REFCLK_SEL, 1); + break; + default: + break; + } + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + /* GLB->dll.BF.dll_prechg_sel = 1; */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_PRECHG_SEL, 1); + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + /* GLB->dll.BF.ppu_dll = 1; */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PPU_DLL, 1); + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + BL702_Delay_US(2); + + /* GLB->dll.BF.pu_dll = 1; */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_DLL, 1); + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + BL702_Delay_US(2); + + /* GLB->dll.BF.dll_reset = 0; */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_RESET, 0); + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + /* delay for settling */ + BL702_Delay_US(5); + + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief set sram_slp value - * - * @param value: value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_SRAM_SLP(uint32_t value) -{ - BL_WR_REG(GLB_BASE, GLB_SRAM_SLP, value); + * @brief enable all DLL output clock + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_CLOCK_SECTION GLB_Enable_DLL_All_Clks(void) { + uint32_t tmpVal = 0; - return SUCCESS; -} + /* GLB->dll.WORD = GLB->dll.WORD | 0x000000f8; include 288m and mmdiv */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 1); + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); -/****************************************************************************/ /** - * @brief get sram_slp value - * - * @param None - * - * @return value - * -*******************************************************************************/ -uint32_t GLB_Get_SRAM_SLP(void) -{ - return BL_RD_REG(GLB_BASE, GLB_SRAM_SLP); + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief set sram_param value - * - * @param value: value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_SRAM_PARM(uint32_t value) -{ - BL_WR_REG(GLB_BASE, GLB_SRAM_PARM, value); + * @brief enable one of DLL output clock + * + * @param dllClk: None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_CLOCK_SECTION GLB_Enable_DLL_Clk(GLB_DLL_CLK_Type dllClk) { + uint32_t tmpVal = 0; - return SUCCESS; + CHECK_PARAM(IS_GLB_DLL_CLK_TYPE(dllClk)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + switch (dllClk) { + case GLB_DLL_CLK_57P6M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 1); + break; + case GLB_DLL_CLK_96M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 1); + break; + case GLB_DLL_CLK_144M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 1); + break; + case GLB_DLL_CLK_288M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 1); + break; + case GLB_DLL_CLK_MMDIV: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 1); + break; + default: + break; + } + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief get sram_parm value - * - * @param None - * - * @return value - * -*******************************************************************************/ -uint32_t GLB_Get_SRAM_PARM(void) -{ - return BL_RD_REG(GLB_BASE, GLB_SRAM_PARM); + * @brief disable all DLL output clock + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_CLOCK_SECTION GLB_Disable_DLL_All_Clks(void) { + uint32_t tmpVal = 0; + + /* GLB->dll.WORD = GLB->dll.WORD & ~0x000000f8; */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 0); + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief select EM type - * - * @param emType: EM type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_EM_Sel(GLB_EM_Type emType) -{ - uint32_t tmpVal = 0; + * @brief disable one of DLL output clock + * + * @param dllClk: None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_CLOCK_SECTION GLB_Disable_DLL_Clk(GLB_DLL_CLK_Type dllClk) { + uint32_t tmpVal = 0; - CHECK_PARAM(IS_GLB_EM_TYPE(emType)); + CHECK_PARAM(IS_GLB_DLL_CLK_TYPE(dllClk)); - tmpVal = BL_RD_REG(GLB_BASE, GLB_SEAM_MISC); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_EM_SEL, emType); - BL_WR_REG(GLB_BASE, GLB_SEAM_MISC, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + switch (dllClk) { + case GLB_DLL_CLK_57P6M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 0); + break; + case GLB_DLL_CLK_96M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 0); + break; + case GLB_DLL_CLK_144M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 0); + break; + case GLB_DLL_CLK_288M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 0); + break; + case GLB_DLL_CLK_MMDIV: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 0); + break; + default: + break; + } + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - return SUCCESS; + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief select pin as EMAC or CAM - * - * @param pinType: pin type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_SWAP_EMAC_CAM_Pin(GLB_EMAC_CAM_PIN_Type pinType) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_GLB_EMAC_CAM_PIN_TYPE(pinType)); + * @brief Select ir rx gpio (gpio17~gpio31) + * + * @param gpio: IR gpio selected + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_IR_RX_GPIO_Sel(GLB_GPIO_Type gpio) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PIN_SEL_EMAC_CAM, pinType); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); + /* Select gpio between gpio17 and gpio31 */ + if (gpio > 16 && gpio < 32) { + tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_IR_RX_GPIO_SEL, gpio - 16); + BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief EXT_RST PAD SMT - * - * @param enable: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_Ext_Rst_Smt(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief Enable ir led driver + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_IR_LED_Driver_Enable(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_EXT_RST_SMT); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_EXT_RST_SMT); - } - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); + /* Enable led driver */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_PU_LEDDRV); + BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Key Scan Column Drive - * - * @param enable: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_Kys_Drv_Col(uint8_t enable) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_KYS_DRV_VAL); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_KYS_DRV_VAL); - } - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief swap UART gpio pins sig function - * - * @param swapSel: UART swap set gpio pins selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_UART_Sig_Swap_Set(uint8_t swapSel) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM((swapSel <= 0xF)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_UART_SWAP_SET, swapSel); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief swap JTAG gpio pins function - * - * @param swapSel: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_JTAG_Sig_Swap_Set(uint8_t swapSel) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM((swapSel <= 0xFF)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_JTAG_SWAP_SET, swapSel); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief CCI use GPIO 0 1 2 7 - * - * @param enable: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_CCI_Use_IO_0_1_2_7(uint8_t enable) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_P3_CCI_USE_IO_0_2_7); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_P3_CCI_USE_IO_0_2_7); - } - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief CCI use JTAG pin - * - * @param enable: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_CCI_Use_Jtag_Pin(uint8_t enable) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CCI_USE_JTAG_PIN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CCI_USE_JTAG_PIN); - } - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief swap SPI0 MOSI with MISO - * - * @param newState: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Swap_SPI_0_MOSI_With_MISO(BL_Fun_Type newState) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_SPI_0_SWAP, newState); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Select SPI_0 act mode - * - * @param mod: SPI work mode - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_SPI_0_ACT_MOD_Sel(GLB_SPI_PAD_ACT_AS_Type mod) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GLB_SPI_PAD_ACT_AS_TYPE(mod)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_SPI_0_MASTER_MODE, mod); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief use internal flash - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_Select_Internal_Flash(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x3f); - BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief use external flash - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_Select_External_Flash(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x00); - BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief Deswap internal flash pin - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_Deswap_Flash_Pin(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief Swap internal flash CS and IO2 pin - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_Swap_Flash_CS_IO2_Pin(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief Swap internal flash IO3 and IO0 pin - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_Swap_Flash_IO0_IO3_Pin(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief Swap internal flash IO3 and IO0 pin - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_Swap_Flash_Pin(void) -{ - /*To be removed*/ - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief Select internal psram - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_Select_Internal_PSram(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x00); - BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief set PDM clock - * - * @param enable: Enable or disable PDM clock - * @param div: clock divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_PDM_CLK(uint8_t enable, uint8_t div) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PDM_CLK_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_PDM0_CLK_EN); - BL_WR_REG(GLB_BASE, GLB_PDM_CLK_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PDM_CLK_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_PDM0_CLK_DIV, div); - BL_WR_REG(GLB_BASE, GLB_PDM_CLK_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PDM_CLK_CTRL); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_PDM0_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_PDM0_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_PDM_CLK_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief set MTimer clock - * - * @param enable: enable or disable MTimer clock - * @param clkSel: clock selection - * @param div: divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_MTimer_CLK(uint8_t enable, GLB_MTIMER_CLK_Type clkSel, uint32_t div) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GLB_MTIMER_CLK_TYPE(clkSel)); - CHECK_PARAM((div <= 0x1FFFF)); - - /* disable MTimer clock first */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CPU_CLK_CFG); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CPU_RTC_EN); - BL_WR_REG(GLB_BASE, GLB_CPU_CLK_CFG, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_CPU_CLK_CFG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CPU_RTC_SEL, clkSel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CPU_RTC_DIV, div); - BL_WR_REG(GLB_BASE, GLB_CPU_CLK_CFG, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_CPU_CLK_CFG); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CPU_RTC_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CPU_RTC_EN); - } - BL_WR_REG(GLB_BASE, GLB_CPU_CLK_CFG, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief set ADC clock - * - * @param enable: enable or disable ADC clock - * @param clkSel: ADC clock selection - * @param div: divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_ADC_CLK(uint8_t enable, GLB_ADC_CLK_Type clkSel, uint8_t div) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GLB_ADC_CLK_TYPE(clkSel)); - - /* disable ADC clock first */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPADC_32M_DIV_EN); - BL_WR_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPADC_32M_CLK_DIV, div); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPADC_32M_CLK_SEL, clkSel); - BL_WR_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPADC_32M_DIV_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPADC_32M_DIV_EN); - } - BL_WR_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief set DAC clock - * - * @param enable: enable frequency divider or not - * @param clkSel: ADC clock selection - * @param div: src divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_DAC_CLK(uint8_t enable, GLB_DAC_CLK_Type clkSel, uint8_t div) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GLB_DAC_CLK_TYPE(clkSel)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_COMP); - - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_CLK_SRC_SEL, clkSel); - - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_DIV, div); - - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_512K_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); - } - - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief select DIG clock source - * - * @param clkSel: DIG clock selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_DIG_CLK_Sel(GLB_DIG_CLK_Type clkSel) -{ - uint32_t tmpVal; - uint32_t dig512kEn; - uint32_t dig32kEn; - - /* disable DIG512K and DIG32K clock first */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - dig512kEn = BL_GET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_EN); - dig32kEn = BL_GET_REG_BITS_VAL(tmpVal, GLB_DIG_32K_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_32K_EN); - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_CLK_SRC_SEL, clkSel); - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - /* repristinate DIG512K and DIG32K clock */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_EN, dig512kEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_32K_EN, dig32kEn); - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief set DIG 512K clock - * - * @param enable: enable or disable DIG 512K clock - * @param compensation: enable or disable DIG 512K clock compensation - * @param div: divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_DIG_512K_CLK(uint8_t enable, uint8_t compensation, uint8_t div) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - if (compensation) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_512K_COMP); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_COMP); - } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_DIV, div); - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_512K_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); - } - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief set DIG 32K clock - * - * @param enable: enable or disable DIG 32K clock - * @param compensation: enable or disable DIG 32K clock compensation - * @param div: divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_DIG_32K_CLK(uint8_t enable, uint8_t compensation, uint8_t div) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - if (compensation) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_32K_COMP); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_32K_COMP); - } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_32K_DIV, div); - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_32K_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_32K_EN); - } - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief set BT coex signal - * - * @param enable: ENABLE or DISABLE, if enable, the AP JTAG will be replaced by BT Coex Signal - * @param bandWidth: BT Bandwidth - * @param pti: BT Packet Traffic Information - * @param channel: BT Channel - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_BT_Coex_Signal(uint8_t enable, GLB_BT_BANDWIDTH_Type bandWidth, uint8_t pti, uint8_t channel) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_GLB_BT_BANDWIDTH_TYPE(bandWidth)); - CHECK_PARAM((pti <= 0xF)); - CHECK_PARAM((channel <= 78)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_COEX_BT_BW, bandWidth); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_COEX_BT_PTI, pti); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_COEX_BT_CHANNEL, channel); - BL_WR_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL); - if (enable) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_EN_GPIO_BT_COEX, 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_EN_GPIO_BT_COEX, 0); - } - BL_WR_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Select UART signal function - * - * @param sig: UART signal - * @param fun: UART function - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_UART_Fun_Sel(GLB_UART_SIG_Type sig, GLB_UART_SIG_FUN_Type fun) -{ - uint32_t sig_pos = 0; - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_GLB_UART_SIG_TYPE(sig)); - CHECK_PARAM(IS_GLB_UART_SIG_FUN_TYPE(fun)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_UART_SIG_SEL_0); - sig_pos = (sig * 4); - /* Clear original val */ - tmpVal &= (~(0xf << sig_pos)); - /* Set new value */ - tmpVal |= (fun << sig_pos); - BL_WR_REG(GLB_BASE, GLB_UART_SIG_SEL_0, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief power off DLL - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Power_Off_DLL(void) -{ - uint32_t tmpVal = 0; - - /* GLB->dll.BF.ppu_dll = 0; */ - /* GLB->dll.BF.pu_dll = 0; */ - /* GLB->dll.BF.dll_reset = 1; */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PPU_DLL, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_DLL, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_RESET, 1); - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief power on DLL - * - * @param xtalType: DLL xtal type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Power_On_DLL(GLB_DLL_XTAL_Type xtalType) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_GLB_DLL_XTAL_TYPE(xtalType)); - - /* GLB->dll.BF.dll_refclk_sel = XXX; */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - switch (xtalType) { - case GLB_DLL_XTAL_NONE: - return ERROR; - case GLB_DLL_XTAL_32M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_REFCLK_SEL, 0); - break; - case GLB_DLL_XTAL_RC32M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_REFCLK_SEL, 1); - break; - default: - break; - } - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - /* GLB->dll.BF.dll_prechg_sel = 1; */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_PRECHG_SEL, 1); - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - /* GLB->dll.BF.ppu_dll = 1; */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PPU_DLL, 1); - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - BL702_Delay_US(2); - - /* GLB->dll.BF.pu_dll = 1; */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_DLL, 1); - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - BL702_Delay_US(2); - - /* GLB->dll.BF.dll_reset = 0; */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_RESET, 0); - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - /* delay for settling */ - BL702_Delay_US(5); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief enable all DLL output clock - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Enable_DLL_All_Clks(void) -{ - uint32_t tmpVal = 0; - - /* GLB->dll.WORD = GLB->dll.WORD | 0x000000f8; include 288m and mmdiv */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 1); - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief enable one of DLL output clock - * - * @param dllClk: None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Enable_DLL_Clk(GLB_DLL_CLK_Type dllClk) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_GLB_DLL_CLK_TYPE(dllClk)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - switch (dllClk) { - case GLB_DLL_CLK_57P6M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 1); - break; - case GLB_DLL_CLK_96M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 1); - break; - case GLB_DLL_CLK_144M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 1); - break; - case GLB_DLL_CLK_288M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 1); - break; - case GLB_DLL_CLK_MMDIV: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 1); - break; - default: - break; - } - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief disable all DLL output clock - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Disable_DLL_All_Clks(void) -{ - uint32_t tmpVal = 0; - - /* GLB->dll.WORD = GLB->dll.WORD & ~0x000000f8; */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 0); - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief disable one of DLL output clock - * - * @param dllClk: None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Disable_DLL_Clk(GLB_DLL_CLK_Type dllClk) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_GLB_DLL_CLK_TYPE(dllClk)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - switch (dllClk) { - case GLB_DLL_CLK_57P6M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 0); - break; - case GLB_DLL_CLK_96M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 0); - break; - case GLB_DLL_CLK_144M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 0); - break; - case GLB_DLL_CLK_288M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 0); - break; - case GLB_DLL_CLK_MMDIV: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 0); - break; - default: - break; - } - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief Select ir rx gpio (gpio17~gpio31) - * - * @param gpio: IR gpio selected - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_IR_RX_GPIO_Sel(GLB_GPIO_Type gpio) -{ - uint32_t tmpVal = 0; - - /* Select gpio between gpio17 and gpio31 */ - if (gpio > 16 && gpio < 32) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_IR_RX_GPIO_SEL, gpio - 16); - BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - } - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Enable ir led driver - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_IR_LED_Driver_Enable(void) -{ - uint32_t tmpVal = 0; - - /* Enable led driver */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_PU_LEDDRV); - BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Disable ir led driver - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_IR_LED_Driver_Disable(void) -{ - uint32_t tmpVal = 0; - - /* Disable led driver */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_PU_LEDDRV); - BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Enable ir led driver gpio output(gpio 22 or 23) - * - * @param gpio: IR gpio selected - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_IR_LED_Driver_Output_Enable(GLB_GPIO_Type gpio) -{ - uint32_t tmpVal = 0; - - if (gpio == GLB_GPIO_PIN_22) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) | 1); - BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - } else if (gpio == GLB_GPIO_PIN_23) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) | 2); - BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - } + * @brief Disable ir led driver + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_IR_LED_Driver_Disable(void) { + uint32_t tmpVal = 0; - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Disable ir led driver gpio output(gpio 22 or 23) - * - * @param gpio: IR gpio selected - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_IR_LED_Driver_Output_Disable(GLB_GPIO_Type gpio) -{ - uint32_t tmpVal = 0; - - if (gpio == GLB_GPIO_PIN_22) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) & ~1); - BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - } else if (gpio == GLB_GPIO_PIN_23) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) & ~2); - BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - } + /* Disable led driver */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_PU_LEDDRV); + BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Set ir led driver ibias - * - * @param ibias: Ibias value,0x0:0mA~0xf:120mA,8mA/step - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_IR_LED_Driver_Ibias(uint8_t ibias) -{ - uint32_t tmpVal = 0; + * @brief Enable ir led driver gpio output(gpio 22 or 23) + * + * @param gpio: IR gpio selected + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_IR_LED_Driver_Output_Enable(GLB_GPIO_Type gpio) { + uint32_t tmpVal = 0; - /* Set driver ibias */ + if (gpio == GLB_GPIO_PIN_22) { tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_IBIAS, ibias & 0xF); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) | 1); BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); + } else if (gpio == GLB_GPIO_PIN_23) { + tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) | 2); + BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief GPIO initialization - * - * @param cfg: GPIO configuration - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_Init(GLB_GPIO_Cfg_Type *cfg) -{ - uint8_t gpioPin = cfg->gpioPin; - uint8_t realPin; - uint32_t *pOut; - uint32_t pos; - uint32_t tmpOut; - uint32_t tmpVal; - - /* drive strength(drive) = 0 <=> 8.0mA @ 3.3V */ - /* drive strength(drive) = 1 <=> 9.6mA @ 3.3V */ - /* drive strength(drive) = 2 <=> 11.2mA @ 3.3V */ - /* drive strength(drive) = 3 <=> 12.8mA @ 3.3V */ - - pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET + ((gpioPin >> 5) << 2)); - pos = gpioPin % 32; - tmpOut = *pOut; - - /* Disable output anyway*/ - tmpOut &= (~(1 << pos)); - *pOut = tmpOut; - - realPin = gpioPin; - /* sf pad use exclusive ie/pd/pu/drive/smtctrl */ - if (gpioPin >= 23 && gpioPin <= 28) { - if ((BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) & (1 << (gpioPin - 23))) > 0) { - realPin += 9; - } - } - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4); - if (realPin % 2 == 0) { - if (cfg->gpioMode != GPIO_MODE_ANALOG) { - /* not analog mode */ - - /* Set input or output */ - if (cfg->gpioMode == GPIO_MODE_OUTPUT) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); - tmpOut |= (1 << pos); - } else { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); - } - - /* Set pull up or down */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD); - if (cfg->pullType == GPIO_PULL_UP) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU); - } else if (cfg->pullType == GPIO_PULL_DOWN) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD); - } - } else { - /* analog mode */ - - /* clear ie && oe */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); - tmpOut &= ~(1 << pos); - - /* clear pu && pd */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD); - } + * @brief Disable ir led driver gpio output(gpio 22 or 23) + * + * @param gpio: IR gpio selected + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_IR_LED_Driver_Output_Disable(GLB_GPIO_Type gpio) { + uint32_t tmpVal = 0; - /* set drive && smt && func */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_DRV, cfg->drive); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_SMT, cfg->smtCtrl); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_FUNC_SEL, cfg->gpioFun); + if (gpio == GLB_GPIO_PIN_22) { + tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) & ~1); + BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); + } else if (gpio == GLB_GPIO_PIN_23) { + tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) & ~2); + BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Set ir led driver ibias + * + * @param ibias: Ibias value,0x0:0mA~0xf:120mA,8mA/step + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_IR_LED_Driver_Ibias(uint8_t ibias) { + uint32_t tmpVal = 0; + + /* Set driver ibias */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_IBIAS, ibias & 0xF); + BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief GPIO initialization + * + * @param cfg: GPIO configuration + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_Init(GLB_GPIO_Cfg_Type *cfg) { + uint8_t gpioPin = cfg->gpioPin; + uint8_t realPin; + uint32_t *pOut; + uint32_t pos; + uint32_t tmpOut; + uint32_t tmpVal; + + /* drive strength(drive) = 0 <=> 8.0mA @ 3.3V */ + /* drive strength(drive) = 1 <=> 9.6mA @ 3.3V */ + /* drive strength(drive) = 2 <=> 11.2mA @ 3.3V */ + /* drive strength(drive) = 3 <=> 12.8mA @ 3.3V */ + + pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET + ((gpioPin >> 5) << 2)); + pos = gpioPin % 32; + tmpOut = *pOut; + + /* Disable output anyway*/ + tmpOut &= (~(1 << pos)); + *pOut = tmpOut; + + realPin = gpioPin; + /* sf pad use exclusive ie/pd/pu/drive/smtctrl */ + if (gpioPin >= 23 && gpioPin <= 28) { + if ((BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) & (1 << (gpioPin - 23))) > 0) { + realPin += 9; + } + } + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4); + if (realPin % 2 == 0) { + if (cfg->gpioMode != GPIO_MODE_ANALOG) { + /* not analog mode */ + + /* Set input or output */ + if (cfg->gpioMode == GPIO_MODE_OUTPUT) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); + tmpOut |= (1 << pos); + } else { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); + } + + /* Set pull up or down */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD); + if (cfg->pullType == GPIO_PULL_UP) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU); + } else if (cfg->pullType == GPIO_PULL_DOWN) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD); + } } else { - if (cfg->gpioMode != GPIO_MODE_ANALOG) { - /* not analog mode */ - - /* Set input or output */ - if (cfg->gpioMode == GPIO_MODE_OUTPUT) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); - tmpOut |= (1 << pos); - } else { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); - } - - /* Set pull up or down */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PU); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PD); - if (cfg->pullType == GPIO_PULL_UP) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_PU); - } else if (cfg->pullType == GPIO_PULL_DOWN) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_PD); - } - } else { - /* analog mode */ - - /* clear ie && oe */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); - tmpOut &= ~(1 << pos); - - /* clear pu && pd */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PU); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PD); - } - - /* set drive && smt && func */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_DRV, cfg->drive); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_SMT, cfg->smtCtrl); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_FUNC_SEL, cfg->gpioFun); - } - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4, tmpVal); - - *pOut = tmpOut; + /* analog mode */ - /* always on pads IE control (in HBN) */ - if (gpioPin >= 9 && gpioPin <= 13) { - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - uint32_t aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); + /* clear ie && oe */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); + tmpOut &= ~(1 << pos); - if (cfg->gpioMode != GPIO_MODE_ANALOG) { - /* not analog mode */ - - if (cfg->gpioMode == GPIO_MODE_OUTPUT) { - aonPadIeSmt &= ~(1 << (gpioPin - 9)); - } else { - aonPadIeSmt |= (1 << (gpioPin - 9)); - } - } else { - /* analog mode */ - - /* clear aon pad ie */ - aonPadIeSmt &= ~(1 << (gpioPin - 9)); - } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + /* clear pu && pd */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD); } - if (gpioPin >= 23 && gpioPin <= 28) { - if ((BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) & (1 << (gpioPin - 23))) > 0) { - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4); - if (gpioPin % 2 == 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_FUNC_SEL, cfg->gpioFun); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_FUNC_SEL, cfg->gpioFun); - } - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4, tmpVal); - - /* sf pad use GPIO23-GPIO28 pinmux&&outputEn */ - pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET + ((gpioPin >> 5) << 2)); - pos = gpioPin % 32; - tmpOut = *pOut; - /* Disable output anyway*/ - tmpOut &= (~(1 << pos)); - *pOut = tmpOut; - if (cfg->gpioMode != GPIO_MODE_ANALOG) { - /* not analog mode */ - - if (cfg->gpioMode == GPIO_MODE_OUTPUT) { - tmpOut |= (1 << pos); - } - } - *pOut = tmpOut; - } - } + /* set drive && smt && func */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_DRV, cfg->drive); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_SMT, cfg->smtCtrl); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_FUNC_SEL, cfg->gpioFun); + } else { + if (cfg->gpioMode != GPIO_MODE_ANALOG) { + /* not analog mode */ - return SUCCESS; -} + /* Set input or output */ + if (cfg->gpioMode == GPIO_MODE_OUTPUT) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); + tmpOut |= (1 << pos); + } else { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); + } + + /* Set pull up or down */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PU); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PD); + if (cfg->pullType == GPIO_PULL_UP) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_PU); + } else if (cfg->pullType == GPIO_PULL_DOWN) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_PD); + } + } else { + /* analog mode */ -/****************************************************************************/ /** - * @brief init GPIO function in pin list - * - * @param gpioFun: GPIO pin function - * @param pinList: GPIO pin list - * @param cnt: GPIO pin count - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_Func_Init(GLB_GPIO_FUNC_Type gpioFun, GLB_GPIO_Type *pinList, uint8_t cnt) -{ - GLB_GPIO_Cfg_Type gpioCfg = { - .gpioPin = GLB_GPIO_PIN_0, - .gpioFun = (uint8_t)gpioFun, - .gpioMode = GPIO_MODE_AF, - .pullType = GPIO_PULL_UP, - .drive = 3, - .smtCtrl = 1 - }; - - if (gpioFun == GPIO_FUN_ANALOG) { - gpioCfg.gpioMode = GPIO_MODE_ANALOG; - } + /* clear ie && oe */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); + tmpOut &= ~(1 << pos); - for (uint8_t i = 0; i < cnt; i++) { - gpioCfg.gpioPin = pinList[i]; - GLB_GPIO_Init(&gpioCfg); + /* clear pu && pd */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PU); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PD); } - return SUCCESS; -} + /* set drive && smt && func */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_DRV, cfg->drive); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_SMT, cfg->smtCtrl); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_FUNC_SEL, cfg->gpioFun); + } + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4, tmpVal); -/****************************************************************************/ /** - * @brief GPIO set input function enable - * - * @param gpioPin: GPIO pin - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_INPUT_Enable(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal; - uint32_t pinOffset; - uint32_t aonPadIeSmt; - - pinOffset = (gpioPin >> 1) << 2; - tmpVal = *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset); - if (gpioPin % 2 == 0) { - /* [0] is ie */ - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); - } else { - /* [16] is ie */ - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); - } - *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset) = tmpVal; + *pOut = tmpOut; - /* always on pads IE control (in HBN) */ - if (gpioPin >= 9 && gpioPin <= 13) { - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); - aonPadIeSmt |= (1 << (gpioPin - 9)); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - } + /* always on pads IE control (in HBN) */ + if (gpioPin >= 9 && gpioPin <= 13) { + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + uint32_t aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); - return SUCCESS; -} + if (cfg->gpioMode != GPIO_MODE_ANALOG) { + /* not analog mode */ -/****************************************************************************/ /** - * @brief GPIO set input function disable - * - * @param gpioPin: GPIO pin - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_INPUT_Disable(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal; - uint32_t pinOffset; - uint32_t aonPadIeSmt; - - pinOffset = (gpioPin >> 1) << 2; - tmpVal = *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset); - if (gpioPin % 2 == 0) { - /* [0] is ie */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); + if (cfg->gpioMode == GPIO_MODE_OUTPUT) { + aonPadIeSmt &= ~(1 << (gpioPin - 9)); + } else { + aonPadIeSmt |= (1 << (gpioPin - 9)); + } } else { - /* [16] is ie */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); - } - *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset) = tmpVal; + /* analog mode */ - /* always on pads IE control (in HBN) */ - if (gpioPin >= 9 && gpioPin <= 13) { - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); - aonPadIeSmt &= ~(1 << (gpioPin - 9)); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + /* clear aon pad ie */ + aonPadIeSmt &= ~(1 << (gpioPin - 9)); } + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + } - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief GPIO set output function enable - * - * @param gpioPin: GPIO pin - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_OUTPUT_Enable(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_CFGCTL34); - tmpVal = tmpVal | (1 << gpioPin); - BL_WR_REG(GLB_BASE, GLB_GPIO_CFGCTL34, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief GPIO set output function disable - * - * @param gpioPin: GPIO pin - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_OUTPUT_Disable(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_CFGCTL34); - tmpVal = tmpVal & ~(1 << gpioPin); - BL_WR_REG(GLB_BASE, GLB_GPIO_CFGCTL34, tmpVal); - - return SUCCESS; -} + if (gpioPin >= 23 && gpioPin <= 28) { + if ((BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) & (1 << (gpioPin - 23))) > 0) { + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4); + if (gpioPin % 2 == 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_FUNC_SEL, cfg->gpioFun); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_FUNC_SEL, cfg->gpioFun); + } + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4, tmpVal); + + /* sf pad use GPIO23-GPIO28 pinmux&&outputEn */ + pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET + ((gpioPin >> 5) << 2)); + pos = gpioPin % 32; + tmpOut = *pOut; + /* Disable output anyway*/ + tmpOut &= (~(1 << pos)); + *pOut = tmpOut; + if (cfg->gpioMode != GPIO_MODE_ANALOG) { + /* not analog mode */ + + if (cfg->gpioMode == GPIO_MODE_OUTPUT) { + tmpOut |= (1 << pos); + } + } + *pOut = tmpOut; + } + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief init GPIO function in pin list + * + * @param gpioFun: GPIO pin function + * @param pinList: GPIO pin list + * @param cnt: GPIO pin count + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_Func_Init(GLB_GPIO_FUNC_Type gpioFun, GLB_GPIO_Type *pinList, uint8_t cnt) { + GLB_GPIO_Cfg_Type gpioCfg = {.gpioPin = GLB_GPIO_PIN_0, .gpioFun = (uint8_t)gpioFun, .gpioMode = GPIO_MODE_AF, .pullType = GPIO_PULL_UP, .drive = 3, .smtCtrl = 1}; + + if (gpioFun == GPIO_FUN_ANALOG) { + gpioCfg.gpioMode = GPIO_MODE_ANALOG; + } + + for (uint8_t i = 0; i < cnt; i++) { + gpioCfg.gpioPin = pinList[i]; + GLB_GPIO_Init(&gpioCfg); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief GPIO set input function enable + * + * @param gpioPin: GPIO pin + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_INPUT_Enable(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal; + uint32_t pinOffset; + uint32_t aonPadIeSmt; + + pinOffset = (gpioPin >> 1) << 2; + tmpVal = *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset); + if (gpioPin % 2 == 0) { + /* [0] is ie */ + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); + } else { + /* [16] is ie */ + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); + } + *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset) = tmpVal; + + /* always on pads IE control (in HBN) */ + if (gpioPin >= 9 && gpioPin <= 13) { + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); + aonPadIeSmt |= (1 << (gpioPin - 9)); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief GPIO set input function disable + * + * @param gpioPin: GPIO pin + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_INPUT_Disable(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal; + uint32_t pinOffset; + uint32_t aonPadIeSmt; + + pinOffset = (gpioPin >> 1) << 2; + tmpVal = *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset); + if (gpioPin % 2 == 0) { + /* [0] is ie */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); + } else { + /* [16] is ie */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); + } + *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset) = tmpVal; + + /* always on pads IE control (in HBN) */ + if (gpioPin >= 9 && gpioPin <= 13) { + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); + aonPadIeSmt &= ~(1 << (gpioPin - 9)); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief GPIO set output function enable + * + * @param gpioPin: GPIO pin + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_OUTPUT_Enable(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_CFGCTL34); + tmpVal = tmpVal | (1 << gpioPin); + BL_WR_REG(GLB_BASE, GLB_GPIO_CFGCTL34, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief GPIO set output function disable + * + * @param gpioPin: GPIO pin + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_OUTPUT_Disable(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_CFGCTL34); + tmpVal = tmpVal & ~(1 << gpioPin); + BL_WR_REG(GLB_BASE, GLB_GPIO_CFGCTL34, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief GPIO set High-Z + * + * @param gpioPin: GPIO pin + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_Set_HZ(GLB_GPIO_Type gpioPin) { + uint32_t *pOut; + uint32_t pos; + uint32_t tmpOut; + uint32_t tmpVal; + uint32_t aonPadIeSmt; + uint8_t realPin; + + /* always on pads IE control (in HBN) */ + if (gpioPin >= 9 && gpioPin <= 13) { + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); + aonPadIeSmt &= ~(1 << (gpioPin - 9)); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + } + + realPin = gpioPin; + /* sf pad use exclusive ie/pd/pu/drive/smtctrl */ + if (gpioPin >= 23 && gpioPin <= 28) { + if ((BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) & (1 << (gpioPin - 23))) > 0) { + realPin += 9; + } + } + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4); + + /* pu=0, pd=0, ie=0 */ + if (realPin % 2 == 0) { + tmpVal = (tmpVal & 0xffffff00); + } else { + tmpVal = (tmpVal & 0xff00ffff); + } + + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4, tmpVal); + + pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET + ((gpioPin >> 5) << 2)); + pos = gpioPin % 32; + tmpOut = *pOut; + + /* Disable output anyway*/ + tmpOut &= (~(1 << pos)); + *pOut = tmpOut; + + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4); + + /* func_sel=swgpio */ + if (gpioPin % 2 == 0) { + tmpVal = (tmpVal & 0xffff00ff); + tmpVal |= 0x0B00; + } else { + tmpVal = (tmpVal & 0x00ffffff); + tmpVal |= (0x0B00 << 16); + } -/****************************************************************************/ /** - * @brief GPIO set High-Z - * - * @param gpioPin: GPIO pin - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_Set_HZ(GLB_GPIO_Type gpioPin) -{ - uint32_t *pOut; - uint32_t pos; - uint32_t tmpOut; - uint32_t tmpVal; - uint32_t aonPadIeSmt; - uint8_t realPin; - - /* always on pads IE control (in HBN) */ - if (gpioPin >= 9 && gpioPin <= 13) { - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); - aonPadIeSmt &= ~(1 << (gpioPin - 9)); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - } + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4, tmpVal); + + /* Disable output anyway*/ + *pOut = tmpOut; + + return SUCCESS; +} + +BL_Err_Type ATTR_TCM_SECTION GLB_Set_Flash_Pad_HZ(void) { + uint32_t tmpVal; + uint32_t offset; - realPin = gpioPin; - /* sf pad use exclusive ie/pd/pu/drive/smtctrl */ - if (gpioPin >= 23 && gpioPin <= 28) { - if ((BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) & (1 << (gpioPin - 23))) > 0) { - realPin += 9; - } - } - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4); + if (BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) != 0x00) { + return ERROR; + } + for (offset = 23; offset <= 28; offset++) { + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4); /* pu=0, pd=0, ie=0 */ - if (realPin % 2 == 0) { - tmpVal = (tmpVal & 0xffffff00); + if (offset % 2 == 0) { + tmpVal = (tmpVal & 0xffffff00); } else { - tmpVal = (tmpVal & 0xff00ffff); + tmpVal = (tmpVal & 0xff00ffff); } + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4, tmpVal); - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4, tmpVal); - - pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET + ((gpioPin >> 5) << 2)); - pos = gpioPin % 32; - tmpOut = *pOut; - - /* Disable output anyway*/ - tmpOut &= (~(1 << pos)); - *pOut = tmpOut; - - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4); - + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4); /* func_sel=swgpio */ - if (gpioPin % 2 == 0) { - tmpVal = (tmpVal & 0xffff00ff); - tmpVal |= 0x0B00; + if (offset % 2 == 0) { + tmpVal = (tmpVal & 0xffff00ff); + tmpVal |= 0x0B00; } else { - tmpVal = (tmpVal & 0x00ffffff); - tmpVal |= (0x0B00 << 16); + tmpVal = (tmpVal & 0x00ffffff); + tmpVal |= (0x0B00 << 16); } + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4, tmpVal); + } - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4, tmpVal); + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET); + tmpVal &= 0xE07FFFFF; + BL_WR_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET, tmpVal); - /* Disable output anyway*/ - *pOut = tmpOut; - - return SUCCESS; + return SUCCESS; } -BL_Err_Type ATTR_TCM_SECTION GLB_Set_Flash_Pad_HZ(void) -{ - uint32_t tmpVal; - uint32_t offset; - - if (BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) != 0x00) { - return ERROR; - } - - for (offset = 23; offset <= 28; offset++) { - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4); - /* pu=0, pd=0, ie=0 */ - if (offset % 2 == 0) { - tmpVal = (tmpVal & 0xffffff00); - } else { - tmpVal = (tmpVal & 0xff00ffff); - } - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4, tmpVal); - - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4); - /* func_sel=swgpio */ - if (offset % 2 == 0) { - tmpVal = (tmpVal & 0xffff00ff); - tmpVal |= 0x0B00; - } else { - tmpVal = (tmpVal & 0x00ffffff); - tmpVal |= (0x0B00 << 16); - } - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4, tmpVal); - } - - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET); - tmpVal &= 0xE07FFFFF; - BL_WR_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET, tmpVal); - - return SUCCESS; -} +BL_Err_Type ATTR_TCM_SECTION GLB_Set_Psram_Pad_HZ(void) { + uint32_t tmpVal; + uint32_t offset; -BL_Err_Type ATTR_TCM_SECTION GLB_Set_Psram_Pad_HZ(void) -{ - uint32_t tmpVal; - uint32_t offset; + if (BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) != 0x3F) { + return ERROR; + } - if (BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) != 0x3F) { - return ERROR; + for (offset = 32; offset <= 37; offset++) { + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4); + /* pu=0, pd=0, ie=0 */ + if (offset % 2 == 0) { + tmpVal = (tmpVal & 0xffffff00); + } else { + tmpVal = (tmpVal & 0xff00ffff); } + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4, tmpVal); - for (offset = 32; offset <= 37; offset++) { - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4); - /* pu=0, pd=0, ie=0 */ - if (offset % 2 == 0) { - tmpVal = (tmpVal & 0xffffff00); - } else { - tmpVal = (tmpVal & 0xff00ffff); - } - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4, tmpVal); - - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + (offset - 9) / 2 * 4); - /* func_sel=swgpio */ - if ((offset - 9) % 2 == 0) { - tmpVal = (tmpVal & 0xffff00ff); - tmpVal |= 0x0B00; - } else { - tmpVal = (tmpVal & 0x00ffffff); - tmpVal |= (0x0B00 << 16); - } - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + (offset - 9) / 2 * 4, tmpVal); + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + (offset - 9) / 2 * 4); + /* func_sel=swgpio */ + if ((offset - 9) % 2 == 0) { + tmpVal = (tmpVal & 0xffff00ff); + tmpVal |= 0x0B00; + } else { + tmpVal = (tmpVal & 0x00ffffff); + tmpVal |= (0x0B00 << 16); } + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + (offset - 9) / 2 * 4, tmpVal); + } - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET); - tmpVal &= 0xE07FFFFF; - BL_WR_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET, tmpVal); + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET); + tmpVal &= 0xE07FFFFF; + BL_WR_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Get GPIO function - * - * @param gpioPin: GPIO type - * - * @return GPIO function - * -*******************************************************************************/ + * @brief Get GPIO function + * + * @param gpioPin: GPIO type + * + * @return GPIO function + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint8_t ATTR_TCM_SECTION GLB_GPIO_Get_Fun(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal; +uint8_t ATTR_TCM_SECTION GLB_GPIO_Get_Fun(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal; - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4); + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4); - if (gpioPin % 2 == 0) { - return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_FUNC_SEL); - } else { - return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_FUNC_SEL); - } + if (gpioPin % 2 == 0) { + return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_FUNC_SEL); + } else { + return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_FUNC_SEL); + } } #endif /****************************************************************************/ /** - * @brief Write GPIO - * - * @param gpioPin: GPIO type - * @param val: GPIO value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_Write(GLB_GPIO_Type gpioPin, uint32_t val) -{ - uint32_t *pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_OFFSET + ((gpioPin >> 5) << 2)); - uint32_t pos = gpioPin % 32; - uint32_t tmpOut; - - tmpOut = *pOut; - if (val > 0) { - tmpOut |= (1 << pos); - } else { - tmpOut &= (~(1 << pos)); - } - *pOut = tmpOut; - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Read GPIO - * - * @param gpioPin: GPIO type - * - * @return GPIO value - * -*******************************************************************************/ -uint32_t GLB_GPIO_Read(GLB_GPIO_Type gpioPin) -{ - uint32_t *p = (uint32_t *)(GLB_BASE + GLB_GPIO_INPUT_OFFSET + ((gpioPin >> 5) << 2)); - uint32_t pos = gpioPin % 32; - - if ((*p) & (1 << pos)) { - return 1; + * @brief Write GPIO + * + * @param gpioPin: GPIO type + * @param val: GPIO value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_Write(GLB_GPIO_Type gpioPin, uint32_t val) { + uint32_t *pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_OFFSET + ((gpioPin >> 5) << 2)); + uint32_t pos = gpioPin % 32; + uint32_t tmpOut; + + tmpOut = *pOut; + if (val > 0) { + tmpOut |= (1 << pos); + } else { + tmpOut &= (~(1 << pos)); + } + *pOut = tmpOut; + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Read GPIO + * + * @param gpioPin: GPIO type + * + * @return GPIO value + * + *******************************************************************************/ +uint32_t GLB_GPIO_Read(GLB_GPIO_Type gpioPin) { + uint32_t *p = (uint32_t *)(GLB_BASE + GLB_GPIO_INPUT_OFFSET + ((gpioPin >> 5) << 2)); + uint32_t pos = gpioPin % 32; + + if ((*p) & (1 << pos)) { + return 1; + } else { + return 0; + } +} + +/****************************************************************************/ /** + * @brief Set GLB GPIO interrupt mask + * + * @param gpioPin: GPIO type + * @param intMask: GPIO interrupt MASK or UNMASK + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_IntMask(GLB_GPIO_Type gpioPin, BL_Mask_Type intMask) { + uint32_t tmpVal; + + if (gpioPin < 32) { + /* GPIO0 ~ GPIO31 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MASK1); + if (intMask == MASK) { + tmpVal = tmpVal | (1 << gpioPin); } else { - return 0; - } -} - -/****************************************************************************/ /** - * @brief Set GLB GPIO interrupt mask - * - * @param gpioPin: GPIO type - * @param intMask: GPIO interrupt MASK or UNMASK - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_IntMask(GLB_GPIO_Type gpioPin, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - - if (gpioPin < 32) { - /* GPIO0 ~ GPIO31 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MASK1); - if (intMask == MASK) { - tmpVal = tmpVal | (1 << gpioPin); - } else { - tmpVal = tmpVal & ~(1 << gpioPin); - } - BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MASK1, tmpVal); - } - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Set GLB GPIO interrupt mask - * - * @param gpioPin: GPIO type - * @param intClear: GPIO interrupt clear or unclear - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_IntClear(GLB_GPIO_Type gpioPin, BL_Sts_Type intClear) -{ - uint32_t tmpVal; - - if (gpioPin < 32) { - /* GPIO0 ~ GPIO31 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_CLR1); - if (intClear == SET) { - tmpVal = tmpVal | (1 << gpioPin); - } else { - tmpVal = tmpVal & ~(1 << gpioPin); - } - BL_WR_REG(GLB_BASE, GLB_GPIO_INT_CLR1, tmpVal); + tmpVal = tmpVal & ~(1 << gpioPin); } + BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MASK1, tmpVal); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Get GLB GPIO interrrupt status - * - * @param gpioPin: GPIO type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type GLB_Get_GPIO_IntStatus(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal = 0; - - if (gpioPin < 32) { - /* GPIO0 ~ GPIO31 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_STAT1); - } - - return (tmpVal & (1 << gpioPin)) ? SET : RESET; -} + * @brief Set GLB GPIO interrupt mask + * + * @param gpioPin: GPIO type + * @param intClear: GPIO interrupt clear or unclear + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_IntClear(GLB_GPIO_Type gpioPin, BL_Sts_Type intClear) { + uint32_t tmpVal; -/****************************************************************************/ /** - * @brief Set GLB GPIO interrupt mode - * - * @param gpioPin: GPIO type - * @param intCtlMod: GPIO interrupt control mode - * @param intTrgMod: GPIO interrupt trigger mode - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_GPIO_IntMod(GLB_GPIO_Type gpioPin, GLB_GPIO_INT_CONTROL_Type intCtlMod, GLB_GPIO_INT_TRIG_Type intTrgMod) -{ - uint32_t tmpVal; - uint32_t tmpGpioPin; - - CHECK_PARAM(IS_GLB_GPIO_INT_CONTROL_TYPE(intCtlMod)); - CHECK_PARAM(IS_GLB_GPIO_INT_TRIG_TYPE(intTrgMod)); - - if (gpioPin < GLB_GPIO_PIN_10) { - /* GPIO0 ~ GPIO9 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET1); - tmpGpioPin = gpioPin; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET1, tmpVal); - } else if (gpioPin < GLB_GPIO_PIN_20) { - /* GPIO10 ~ GPIO19 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET2); - tmpGpioPin = gpioPin - GLB_GPIO_PIN_10; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET2, tmpVal); - } else if (gpioPin < GLB_GPIO_PIN_30) { - /* GPIO20 ~ GPIO29 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET3); - tmpGpioPin = gpioPin - GLB_GPIO_PIN_20; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET3, tmpVal); + if (gpioPin < 32) { + /* GPIO0 ~ GPIO31 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_CLR1); + if (intClear == SET) { + tmpVal = tmpVal | (1 << gpioPin); } else { - /* GPIO30 ~ GPIO31 not recommend */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET4); - tmpGpioPin = gpioPin - GLB_GPIO_PIN_30; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET4, tmpVal); - } - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief get GPIO interrupt control mode - * - * @param gpioPin: GPIO pin type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -GLB_GPIO_INT_CONTROL_Type GLB_Get_GPIO_IntCtlMod(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal; - uint32_t bitVal; - - if (gpioPin < GLB_GPIO_PIN_10) { - /* GPIO0 - GPIO9 */ - bitVal = gpioPin - 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET1); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; - } else if ((gpioPin > GLB_GPIO_PIN_9) && (gpioPin < GLB_GPIO_PIN_20)) { - /* GPIO10 - GPIO19 */ - bitVal = gpioPin - 10; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET2); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; - } else if ((gpioPin > GLB_GPIO_PIN_19) && (gpioPin < GLB_GPIO_PIN_30)) { - /* GPIO20 - GPIO29 */ - bitVal = gpioPin - 20; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET3); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + tmpVal = tmpVal & ~(1 << gpioPin); + } + BL_WR_REG(GLB_BASE, GLB_GPIO_INT_CLR1, tmpVal); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Get GLB GPIO interrrupt status + * + * @param gpioPin: GPIO type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type GLB_Get_GPIO_IntStatus(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal = 0; + + if (gpioPin < 32) { + /* GPIO0 ~ GPIO31 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_STAT1); + } + + return (tmpVal & (1 << gpioPin)) ? SET : RESET; +} + +/****************************************************************************/ /** + * @brief Set GLB GPIO interrupt mode + * + * @param gpioPin: GPIO type + * @param intCtlMod: GPIO interrupt control mode + * @param intTrgMod: GPIO interrupt trigger mode + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_GPIO_IntMod(GLB_GPIO_Type gpioPin, GLB_GPIO_INT_CONTROL_Type intCtlMod, GLB_GPIO_INT_TRIG_Type intTrgMod) { + uint32_t tmpVal; + uint32_t tmpGpioPin; + + CHECK_PARAM(IS_GLB_GPIO_INT_CONTROL_TYPE(intCtlMod)); + CHECK_PARAM(IS_GLB_GPIO_INT_TRIG_TYPE(intTrgMod)); + + if (gpioPin < GLB_GPIO_PIN_10) { + /* GPIO0 ~ GPIO9 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET1); + tmpGpioPin = gpioPin; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET1, tmpVal); + } else if (gpioPin < GLB_GPIO_PIN_20) { + /* GPIO10 ~ GPIO19 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET2); + tmpGpioPin = gpioPin - GLB_GPIO_PIN_10; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET2, tmpVal); + } else if (gpioPin < GLB_GPIO_PIN_30) { + /* GPIO20 ~ GPIO29 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET3); + tmpGpioPin = gpioPin - GLB_GPIO_PIN_20; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET3, tmpVal); + } else { + /* GPIO30 ~ GPIO31 not recommend */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET4); + tmpGpioPin = gpioPin - GLB_GPIO_PIN_30; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET4, tmpVal); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief get GPIO interrupt control mode + * + * @param gpioPin: GPIO pin type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +GLB_GPIO_INT_CONTROL_Type GLB_Get_GPIO_IntCtlMod(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal; + uint32_t bitVal; + + if (gpioPin < GLB_GPIO_PIN_10) { + /* GPIO0 - GPIO9 */ + bitVal = gpioPin - 0; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET1); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } else if ((gpioPin > GLB_GPIO_PIN_9) && (gpioPin < GLB_GPIO_PIN_20)) { + /* GPIO10 - GPIO19 */ + bitVal = gpioPin - 10; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET2); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } else if ((gpioPin > GLB_GPIO_PIN_19) && (gpioPin < GLB_GPIO_PIN_30)) { + /* GPIO20 - GPIO29 */ + bitVal = gpioPin - 20; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET3); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } else { + /* GPIO30 ~ GPIO31 not recommend */ + bitVal = gpioPin - 30; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET4); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } +} + +/****************************************************************************/ /** + * @brief Set GLB GPIO interrupt mask 2 + * + * @param gpioPin: GPIO type + * @param intMask: GPIO interrupt MASK or UNMASK + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_Int2Mask(GLB_GPIO_Type gpioPin, BL_Mask_Type intMask) { + uint32_t tmpVal; + + if (gpioPin < 32) { + /* GPIO0 ~ GPIO31 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MASK1); + if (intMask == MASK) { + tmpVal = tmpVal | (1 << gpioPin); } else { - /* GPIO30 ~ GPIO31 not recommend */ - bitVal = gpioPin - 30; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET4); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; - } -} - -/****************************************************************************/ /** - * @brief Set GLB GPIO interrupt mask 2 - * - * @param gpioPin: GPIO type - * @param intMask: GPIO interrupt MASK or UNMASK - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_Int2Mask(GLB_GPIO_Type gpioPin, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - - if (gpioPin < 32) { - /* GPIO0 ~ GPIO31 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MASK1); - if (intMask == MASK) { - tmpVal = tmpVal | (1 << gpioPin); - } else { - tmpVal = tmpVal & ~(1 << gpioPin); - } - BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MASK1, tmpVal); - } - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Set GLB GPIO interrupt mask 2 - * - * @param gpioPin: GPIO type - * @param intClear: GPIO interrupt clear or unclear - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_Int2Clear(GLB_GPIO_Type gpioPin, BL_Sts_Type intClear) -{ - uint32_t tmpVal; - - if (gpioPin < 32) { - /* GPIO0 ~ GPIO31 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_CLR1); - if (intClear == SET) { - tmpVal = tmpVal | (1 << gpioPin); - } else { - tmpVal = tmpVal & ~(1 << gpioPin); - } - BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_CLR1, tmpVal); - } - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Get GLB GPIO interrrupt status 2 - * - * @param gpioPin: GPIO type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type GLB_Get_GPIO_Int2Status(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal = 0; - - if (gpioPin < 32) { - /* GPIO0 ~ GPIO31 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_STAT1); + tmpVal = tmpVal & ~(1 << gpioPin); } + BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MASK1, tmpVal); + } - return (tmpVal & (1 << gpioPin)) ? SET : RESET; + return SUCCESS; } /****************************************************************************/ /** - * @brief Set GLB GPIO interrupt mode 2 - * - * @param gpioPin: GPIO type - * @param intCtlMod: GPIO interrupt control mode - * @param intTrgMod: GPIO interrupt trigger mode - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_GPIO_Int2Mod(GLB_GPIO_Type gpioPin, GLB_GPIO_INT_CONTROL_Type intCtlMod, GLB_GPIO_INT_TRIG_Type intTrgMod) -{ - uint32_t tmpVal; - uint32_t tmpGpioPin; - - CHECK_PARAM(IS_GLB_GPIO_INT_CONTROL_TYPE(intCtlMod)); - CHECK_PARAM(IS_GLB_GPIO_INT_TRIG_TYPE(intTrgMod)); - - if (gpioPin < GLB_GPIO_PIN_10) { - /* GPIO0 ~ GPIO9 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET1); - tmpGpioPin = gpioPin; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET1, tmpVal); - } else if (gpioPin < GLB_GPIO_PIN_20) { - /* GPIO10 ~ GPIO19 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET2); - tmpGpioPin = gpioPin - GLB_GPIO_PIN_10; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET2, tmpVal); - } else if (gpioPin < GLB_GPIO_PIN_30) { - /* GPIO20 ~ GPIO29 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET3); - tmpGpioPin = gpioPin - GLB_GPIO_PIN_20; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET3, tmpVal); - } else { - /* GPIO30 ~ GPIO31 not recommend */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET4); - tmpGpioPin = gpioPin - GLB_GPIO_PIN_30; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET4, tmpVal); - } - - return SUCCESS; -} + * @brief Set GLB GPIO interrupt mask 2 + * + * @param gpioPin: GPIO type + * @param intClear: GPIO interrupt clear or unclear + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_Int2Clear(GLB_GPIO_Type gpioPin, BL_Sts_Type intClear) { + uint32_t tmpVal; -/****************************************************************************/ /** - * @brief get GPIO interrupt control mode 2 - * - * @param gpioPin: GPIO pin type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -GLB_GPIO_INT_CONTROL_Type GLB_Get_GPIO_Int2CtlMod(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal; - uint32_t bitVal; - - if (gpioPin < GLB_GPIO_PIN_10) { - /* GPIO0 - GPIO9 */ - bitVal = gpioPin - 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET1); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; - } else if ((gpioPin > GLB_GPIO_PIN_9) && (gpioPin < GLB_GPIO_PIN_20)) { - /* GPIO10 - GPIO19 */ - bitVal = gpioPin - 10; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET2); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; - } else if ((gpioPin > GLB_GPIO_PIN_19) && (gpioPin < GLB_GPIO_PIN_30)) { - /* GPIO20 - GPIO29 */ - bitVal = gpioPin - 20; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET3); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + if (gpioPin < 32) { + /* GPIO0 ~ GPIO31 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_CLR1); + if (intClear == SET) { + tmpVal = tmpVal | (1 << gpioPin); } else { - /* GPIO30 ~ GPIO31 not recommend */ - bitVal = gpioPin - 30; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET4); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; - } -} - -/****************************************************************************/ /** - * @brief GPIO INT0 IRQHandler install - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_INT0_IRQHandler_Install(void) -{ + tmpVal = tmpVal & ~(1 << gpioPin); + } + BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_CLR1, tmpVal); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Get GLB GPIO interrrupt status 2 + * + * @param gpioPin: GPIO type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type GLB_Get_GPIO_Int2Status(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal = 0; + + if (gpioPin < 32) { + /* GPIO0 ~ GPIO31 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_STAT1); + } + + return (tmpVal & (1 << gpioPin)) ? SET : RESET; +} + +/****************************************************************************/ /** + * @brief Set GLB GPIO interrupt mode 2 + * + * @param gpioPin: GPIO type + * @param intCtlMod: GPIO interrupt control mode + * @param intTrgMod: GPIO interrupt trigger mode + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_GPIO_Int2Mod(GLB_GPIO_Type gpioPin, GLB_GPIO_INT_CONTROL_Type intCtlMod, GLB_GPIO_INT_TRIG_Type intTrgMod) { + uint32_t tmpVal; + uint32_t tmpGpioPin; + + CHECK_PARAM(IS_GLB_GPIO_INT_CONTROL_TYPE(intCtlMod)); + CHECK_PARAM(IS_GLB_GPIO_INT_TRIG_TYPE(intTrgMod)); + + if (gpioPin < GLB_GPIO_PIN_10) { + /* GPIO0 ~ GPIO9 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET1); + tmpGpioPin = gpioPin; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET1, tmpVal); + } else if (gpioPin < GLB_GPIO_PIN_20) { + /* GPIO10 ~ GPIO19 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET2); + tmpGpioPin = gpioPin - GLB_GPIO_PIN_10; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET2, tmpVal); + } else if (gpioPin < GLB_GPIO_PIN_30) { + /* GPIO20 ~ GPIO29 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET3); + tmpGpioPin = gpioPin - GLB_GPIO_PIN_20; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET3, tmpVal); + } else { + /* GPIO30 ~ GPIO31 not recommend */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET4); + tmpGpioPin = gpioPin - GLB_GPIO_PIN_30; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET4, tmpVal); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief get GPIO interrupt control mode 2 + * + * @param gpioPin: GPIO pin type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +GLB_GPIO_INT_CONTROL_Type GLB_Get_GPIO_Int2CtlMod(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal; + uint32_t bitVal; + + if (gpioPin < GLB_GPIO_PIN_10) { + /* GPIO0 - GPIO9 */ + bitVal = gpioPin - 0; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET1); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } else if ((gpioPin > GLB_GPIO_PIN_9) && (gpioPin < GLB_GPIO_PIN_20)) { + /* GPIO10 - GPIO19 */ + bitVal = gpioPin - 10; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET2); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } else if ((gpioPin > GLB_GPIO_PIN_19) && (gpioPin < GLB_GPIO_PIN_30)) { + /* GPIO20 - GPIO29 */ + bitVal = gpioPin - 20; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET3); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } else { + /* GPIO30 ~ GPIO31 not recommend */ + bitVal = gpioPin - 30; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET4); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } +} + +/****************************************************************************/ /** + * @brief GPIO INT0 IRQHandler install + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_INT0_IRQHandler_Install(void) { #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(GPIO_INT0_IRQn, GPIO_INT0_IRQHandler); + Interrupt_Handler_Register(GPIO_INT0_IRQn, GPIO_INT0_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief GPIO interrupt IRQ handler callback install - * - * @param gpioPin: GPIO pin type - * @param cbFun: callback function - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_INT0_Callback_Install(GLB_GPIO_Type gpioPin, intCallback_Type *cbFun) -{ - if (gpioPin < 32) { - glbGpioInt0CbfArra[gpioPin] = cbFun; - } + * @brief GPIO interrupt IRQ handler callback install + * + * @param gpioPin: GPIO pin type + * @param cbFun: callback function + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_INT0_Callback_Install(GLB_GPIO_Type gpioPin, intCallback_Type *cbFun) { + if (gpioPin < 32) { + glbGpioInt0CbfArra[gpioPin] = cbFun; + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief GPIO interrupt IRQ handler callback install2 - * - * @param gpioPin: GPIO pin type - * @param cbFun: callback function - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_INT0_Callback_Install2(GLB_GPIO_Type gpioPin, intCallback_Type *cbFun) -{ - if (gpioPin < 32) { - glbGpioInt0CbfArra2[gpioPin] = cbFun; - } + * @brief GPIO interrupt IRQ handler callback install2 + * + * @param gpioPin: GPIO pin type + * @param cbFun: callback function + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_INT0_Callback_Install2(GLB_GPIO_Type gpioPin, intCallback_Type *cbFun) { + if (gpioPin < 32) { + glbGpioInt0CbfArra2[gpioPin] = cbFun; + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief GPIO interrupt IRQ handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief GPIO interrupt IRQ handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void GPIO_INT0_IRQHandler(void) -{ - GLB_GPIO_Type gpioPin; - uint32_t timeOut = 0; - - for (gpioPin = GLB_GPIO_PIN_0; gpioPin <= GLB_GPIO_PIN_31; gpioPin++) { - if (SET == GLB_Get_GPIO_IntStatus(gpioPin)) { - GLB_GPIO_IntClear(gpioPin, SET); - - /* timeout check */ - timeOut = GLB_GPIO_INT0_CLEAR_TIMEOUT; - do { - timeOut--; - } while ((SET == GLB_Get_GPIO_IntStatus(gpioPin)) && timeOut); - if (!timeOut) { - //MSG("WARNING: Clear GPIO interrupt status fail.\r\n"); - } - - /* if timeOut==0, GPIO interrupt status not cleared */ - GLB_GPIO_IntClear(gpioPin, RESET); - - if (glbGpioInt0CbfArra[gpioPin] != NULL) { - /* Call the callback function */ - glbGpioInt0CbfArra[gpioPin](); - } - } - if (SET == GLB_Get_GPIO_Int2Status(gpioPin)) { - GLB_GPIO_Int2Clear(gpioPin, SET); - - /* timeout check */ - timeOut = GLB_GPIO_INT0_CLEAR_TIMEOUT; - do { - timeOut--; - } while ((SET == GLB_Get_GPIO_Int2Status(gpioPin)) && timeOut); - if (!timeOut) { - //MSG("WARNING: Clear GPIO interrupt status fail.\r\n"); - } - - /* if timeOut==0, GPIO interrupt status not cleared */ - GLB_GPIO_Int2Clear(gpioPin, RESET); - - if (glbGpioInt0CbfArra2[gpioPin] != NULL) { - /* Call the callback function */ - glbGpioInt0CbfArra2[gpioPin](); - } - } - } +void GPIO_INT0_IRQHandler(void) { + GLB_GPIO_Type gpioPin; + uint32_t timeOut = 0; + + for (gpioPin = GLB_GPIO_PIN_0; gpioPin <= GLB_GPIO_PIN_31; gpioPin++) { + if (SET == GLB_Get_GPIO_IntStatus(gpioPin)) { + GLB_GPIO_IntClear(gpioPin, SET); + + /* timeout check */ + timeOut = GLB_GPIO_INT0_CLEAR_TIMEOUT; + do { + timeOut--; + } while ((SET == GLB_Get_GPIO_IntStatus(gpioPin)) && timeOut); + if (!timeOut) { + // MSG("WARNING: Clear GPIO interrupt status fail.\r\n"); + } + + /* if timeOut==0, GPIO interrupt status not cleared */ + GLB_GPIO_IntClear(gpioPin, RESET); + + if (glbGpioInt0CbfArra[gpioPin] != NULL) { + /* Call the callback function */ + glbGpioInt0CbfArra[gpioPin](); + } + } + if (SET == GLB_Get_GPIO_Int2Status(gpioPin)) { + GLB_GPIO_Int2Clear(gpioPin, SET); + + /* timeout check */ + timeOut = GLB_GPIO_INT0_CLEAR_TIMEOUT; + do { + timeOut--; + } while ((SET == GLB_Get_GPIO_Int2Status(gpioPin)) && timeOut); + if (!timeOut) { + // MSG("WARNING: Clear GPIO interrupt status fail.\r\n"); + } + + /* if timeOut==0, GPIO interrupt status not cleared */ + GLB_GPIO_Int2Clear(gpioPin, RESET); + + if (glbGpioInt0CbfArra2[gpioPin] != NULL) { + /* Call the callback function */ + glbGpioInt0CbfArra2[gpioPin](); + } + } + } } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_hbn.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_hbn.c index 9ddf2f9bfb..8742032259 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_hbn.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_hbn.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_hbn.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_hbn.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_hbn.h" #include "bl702_glb.h" @@ -50,16 +50,16 @@ * @{ */ #define HBN_CLK_SET_DUMMY_WAIT \ - { \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - } + { \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + } /*@} end of group HBN_Private_Macros */ @@ -72,8 +72,8 @@ /** @defgroup HBN_Private_Variables * @{ */ -static intCallback_Type *hbnInt0CbfArra[HBN_OUT0_MAX] = { NULL, NULL, NULL, NULL, NULL, NULL }; -static intCallback_Type *hbnInt1CbfArra[HBN_OUT1_MAX] = { NULL, NULL, NULL, NULL }; +static intCallback_Type *hbnInt0CbfArra[HBN_OUT0_MAX] = {NULL, NULL, NULL, NULL, NULL, NULL}; +static intCallback_Type *hbnInt1CbfArra[HBN_OUT1_MAX] = {NULL, NULL, NULL, NULL}; /*@} end of group HBN_Private_Variables */ @@ -100,1927 +100,1847 @@ static intCallback_Type *hbnInt1CbfArra[HBN_OUT1_MAX] = { NULL, NULL, NULL, NULL */ /****************************************************************************/ /** - * @brief Enter HBN - * - * @param cfg: HBN APP Config - * - * @return None - * -*******************************************************************************/ -void ATTR_TCM_SECTION HBN_Mode_Enter(HBN_APP_CFG_Type *cfg) -{ - uint32_t valLow = 0, valHigh = 0; - uint64_t val; - - /* work clock select */ - if (cfg->useXtal32k) { - HBN_32K_Sel(HBN_32K_XTAL); - } else { - HBN_32K_Sel(HBN_32K_RC); - HBN_Power_Off_Xtal_32K(); - } - - /* turn off RC32K during HBN */ - if ((cfg->hbnLevel) >= HBN_LEVEL_2) { - HBN_Power_Off_RC32K(); - } else { - HBN_Power_On_RC32K(); - } - - /* clear aon pad interrupt before config them */ - HBN_Clear_IRQ(HBN_INT_GPIO9); - HBN_Clear_IRQ(HBN_INT_GPIO10); - HBN_Clear_IRQ(HBN_INT_GPIO11); - HBN_Clear_IRQ(HBN_INT_GPIO12); - HBN_Clear_IRQ(HBN_INT_GPIO13); - - /* always disable HBN pin pull up/down to reduce PDS/HBN current, 0x4000F014[16]=0 */ - HBN_Hw_Pu_Pd_Cfg(DISABLE); - - HBN_Pin_WakeUp_Mask(~(cfg->gpioWakeupSrc)); - - if (cfg->gpioWakeupSrc != 0) { - HBN_Aon_Pad_IeSmt_Cfg(cfg->gpioWakeupSrc); - HBN_GPIO_INT_Enable(cfg->gpioTrigType); - } else { - HBN_Aon_Pad_IeSmt_Cfg(0); - } - - /* HBN RTC config and enable */ - if (cfg->sleepTime != 0) { - // set rtc enable flag - BL_WR_WORD(0x40010FFC, 0x1); - - HBN_Clear_RTC_Counter(); - HBN_Get_RTC_Timer_Val(&valLow, &valHigh); - val = valLow + ((uint64_t)valHigh << 32); - val += cfg->sleepTime; - HBN_Set_RTC_Timer(HBN_RTC_INT_DELAY_0T, val & 0xffffffff, val >> 32, HBN_RTC_COMP_BIT0_39); - HBN_Enable_RTC_Counter(); - } - - HBN_Power_Down_Flash(cfg->flashCfg); - - switch (cfg->flashPinCfg) { - case 0: - HBN_Set_Pad_23_28_Pullup(); - break; - - case 1: - /* need do nothing */ - break; - - case 2: - /* need do nothing */ - break; - - case 3: - /* can do nothing */ - break; - - default: - break; - } - - GLB_Set_System_CLK(GLB_DLL_XTAL_NONE, GLB_SYS_CLK_RC32M); - - /* power off xtal */ - AON_Power_Off_XTAL(); - - HBN_Enable_Ext(cfg->gpioWakeupSrc, cfg->ldoLevel, cfg->hbnLevel); -} - -/****************************************************************************/ /** - * @brief power down and switch clock - * - * @param flashCfg: None - * - * @return None - * -*******************************************************************************/ -void ATTR_TCM_SECTION HBN_Power_Down_Flash(SPI_Flash_Cfg_Type *flashCfg) -{ - SPI_Flash_Cfg_Type bhFlashCfg; - - if (flashCfg == NULL) { - /* fix this some time */ - /* SFlash_Cache_Flush(); */ - XIP_SFlash_Read_Via_Cache_Need_Lock(BL702_FLASH_XIP_BASE + 8 + 4, (uint8_t *)(&bhFlashCfg), sizeof(SPI_Flash_Cfg_Type)); - /* fix this some time */ - /* SFlash_Cache_Flush(); */ - - SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB); - SFlash_Reset_Continue_Read(&bhFlashCfg); - } else { - SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB); - SFlash_Reset_Continue_Read(flashCfg); - } - - SFlash_Powerdown(); -} - -/****************************************************************************/ /** - * @brief Enable HBN mode - * - * @param aGPIOIeCfg: AON GPIO IE config,Bit0->GPIO18. Bit(s) of Wakeup GPIO(s) must not be set to - * 0(s),say when use GPIO7 as wake up pin,aGPIOIeCfg should be 0x01. - * @param ldoLevel: LDO volatge level - * @param hbnLevel: HBN work level - * - * @return None - * -*******************************************************************************/ -void ATTR_TCM_SECTION HBN_Enable_Ext(uint8_t aGPIOIeCfg, HBN_LDO_LEVEL_Type ldoLevel, HBN_LEVEL_Type hbnLevel) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); - CHECK_PARAM(IS_HBN_LEVEL_TYPE(hbnLevel)); - - /* Setting from guide */ - /* RAM Retion, no longer use */ - /* BL_WR_REG(HBN_BASE,HBN_SRAM,0x24); */ - - /* AON GPIO IE */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aGPIOIeCfg); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - - /* HBN mode LDO level */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_LDO11_AON_VOUT_SEL, ldoLevel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_LDO11_RT_VOUT_SEL, ldoLevel); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - - /* Select RC32M */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - - /* Set HBN flag */ - BL_WR_REG(HBN_BASE, HBN_RSV0, HBN_STATUS_ENTER_FLAG); - - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - - /* Set HBN level, (HBN_PWRDN_HBN_RAM not use) */ - switch (hbnLevel) { - case HBN_LEVEL_0: - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - case HBN_LEVEL_1: - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - case HBN_LEVEL_2: - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - case HBN_LEVEL_3: - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - default: - break; - } - - /* Set power on option:0 for por reset twice for robust 1 for reset only once*/ - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWR_ON_OPTION); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - - /* Enable HBN mode */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_MODE); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - - while (1) { - BL702_Delay_MS(1000); - } -} - -/****************************************************************************/ /** - * @brief Reset HBN mode - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Enter HBN + * + * @param cfg: HBN APP Config + * + * @return None + * + *******************************************************************************/ +void ATTR_TCM_SECTION HBN_Mode_Enter(HBN_APP_CFG_Type *cfg) { + uint32_t valLow = 0, valHigh = 0; + uint64_t val; + + /* work clock select */ + if (cfg->useXtal32k) { + HBN_32K_Sel(HBN_32K_XTAL); + } else { + HBN_32K_Sel(HBN_32K_RC); + HBN_Power_Off_Xtal_32K(); + } + + /* turn off RC32K during HBN */ + if ((cfg->hbnLevel) >= HBN_LEVEL_2) { + HBN_Power_Off_RC32K(); + } else { + HBN_Power_On_RC32K(); + } + + /* clear aon pad interrupt before config them */ + HBN_Clear_IRQ(HBN_INT_GPIO9); + HBN_Clear_IRQ(HBN_INT_GPIO10); + HBN_Clear_IRQ(HBN_INT_GPIO11); + HBN_Clear_IRQ(HBN_INT_GPIO12); + HBN_Clear_IRQ(HBN_INT_GPIO13); + + /* always disable HBN pin pull up/down to reduce PDS/HBN current, 0x4000F014[16]=0 */ + HBN_Hw_Pu_Pd_Cfg(DISABLE); + + HBN_Pin_WakeUp_Mask(~(cfg->gpioWakeupSrc)); + + if (cfg->gpioWakeupSrc != 0) { + HBN_Aon_Pad_IeSmt_Cfg(cfg->gpioWakeupSrc); + HBN_GPIO_INT_Enable(cfg->gpioTrigType); + } else { + HBN_Aon_Pad_IeSmt_Cfg(0); + } + + /* HBN RTC config and enable */ + if (cfg->sleepTime != 0) { + // set rtc enable flag + BL_WR_WORD(0x40010FFC, 0x1); + + HBN_Clear_RTC_Counter(); + HBN_Get_RTC_Timer_Val(&valLow, &valHigh); + val = valLow + ((uint64_t)valHigh << 32); + val += cfg->sleepTime; + HBN_Set_RTC_Timer(HBN_RTC_INT_DELAY_0T, val & 0xffffffff, val >> 32, HBN_RTC_COMP_BIT0_39); + HBN_Enable_RTC_Counter(); + } + + HBN_Power_Down_Flash(cfg->flashCfg); + + switch (cfg->flashPinCfg) { + case 0: + HBN_Set_Pad_23_28_Pullup(); + break; + + case 1: + /* need do nothing */ + break; + + case 2: + /* need do nothing */ + break; + + case 3: + /* can do nothing */ + break; + + default: + break; + } + + GLB_Set_System_CLK(GLB_DLL_XTAL_NONE, GLB_SYS_CLK_RC32M); + + /* power off xtal */ + AON_Power_Off_XTAL(); + + HBN_Enable_Ext(cfg->gpioWakeupSrc, cfg->ldoLevel, cfg->hbnLevel); +} + +/****************************************************************************/ /** + * @brief power down and switch clock + * + * @param flashCfg: None + * + * @return None + * + *******************************************************************************/ +void ATTR_TCM_SECTION HBN_Power_Down_Flash(SPI_Flash_Cfg_Type *flashCfg) { + SPI_Flash_Cfg_Type bhFlashCfg; + + if (flashCfg == NULL) { + /* fix this some time */ + /* SFlash_Cache_Flush(); */ + XIP_SFlash_Read_Via_Cache_Need_Lock(BL702_FLASH_XIP_BASE + 8 + 4, (uint8_t *)(&bhFlashCfg), sizeof(SPI_Flash_Cfg_Type)); + /* fix this some time */ + /* SFlash_Cache_Flush(); */ + + SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB); + SFlash_Reset_Continue_Read(&bhFlashCfg); + } else { + SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB); + SFlash_Reset_Continue_Read(flashCfg); + } + + SFlash_Powerdown(); +} + +/****************************************************************************/ /** + * @brief Enable HBN mode + * + * @param aGPIOIeCfg: AON GPIO IE config,Bit0->GPIO18. Bit(s) of Wakeup GPIO(s) must not be set to + * 0(s),say when use GPIO7 as wake up pin,aGPIOIeCfg should be 0x01. + * @param ldoLevel: LDO volatge level + * @param hbnLevel: HBN work level + * + * @return None + * + *******************************************************************************/ +void ATTR_TCM_SECTION HBN_Enable_Ext(uint8_t aGPIOIeCfg, HBN_LDO_LEVEL_Type ldoLevel, HBN_LEVEL_Type hbnLevel) { + uint32_t tmpVal; + + CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); + CHECK_PARAM(IS_HBN_LEVEL_TYPE(hbnLevel)); + + /* Setting from guide */ + /* RAM Retion, no longer use */ + /* BL_WR_REG(HBN_BASE,HBN_SRAM,0x24); */ + + /* AON GPIO IE */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aGPIOIeCfg); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + + /* HBN mode LDO level */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_LDO11_AON_VOUT_SEL, ldoLevel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_LDO11_RT_VOUT_SEL, ldoLevel); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + + /* Select RC32M */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + + /* Set HBN flag */ + BL_WR_REG(HBN_BASE, HBN_RSV0, HBN_STATUS_ENTER_FLAG); + + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + + /* Set HBN level, (HBN_PWRDN_HBN_RAM not use) */ + switch (hbnLevel) { + case HBN_LEVEL_0: + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + case HBN_LEVEL_1: + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + case HBN_LEVEL_2: + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + case HBN_LEVEL_3: + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + default: + break; + } + + /* Set power on option:0 for por reset twice for robust 1 for reset only once*/ + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWR_ON_OPTION); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + + /* Enable HBN mode */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_MODE); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + + while (1) { + BL702_Delay_MS(1000); + } +} + +/****************************************************************************/ /** + * @brief Reset HBN mode + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION HBN_Reset(void) -{ - uint32_t tmpVal; +BL_Err_Type ATTR_TCM_SECTION HBN_Reset(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - /* Reset HBN mode */ - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_SW_RST); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + /* Reset HBN mode */ + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_SW_RST); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_SW_RST); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_SW_RST); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_SW_RST); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_SW_RST); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief reset HBN by software - * - * @param npXtalType: NP clock type - * @param bclkDiv: NP clock div - * @param apXtalType: AP clock type - * @param fclkDiv: AP clock div - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_App_Reset(uint8_t npXtalType, uint8_t bclkDiv, uint8_t apXtalType, uint8_t fclkDiv) -{ - uint32_t tmp[12]; - - tmp[0] = BL_RD_REG(HBN_BASE, HBN_CTL); - tmp[1] = BL_RD_REG(HBN_BASE, HBN_TIME_L); - tmp[2] = BL_RD_REG(HBN_BASE, HBN_TIME_H); - tmp[3] = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmp[4] = BL_RD_REG(HBN_BASE, HBN_IRQ_CLR); - tmp[5] = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); - tmp[6] = BL_RD_REG(HBN_BASE, HBN_PIR_VTH); - tmp[7] = BL_RD_REG(HBN_BASE, HBN_PIR_INTERVAL); - tmp[8] = BL_RD_REG(HBN_BASE, HBN_SRAM); - tmp[9] = BL_RD_REG(HBN_BASE, HBN_RSV0); - tmp[10] = BL_RD_REG(HBN_BASE, HBN_RSV1); - tmp[11] = BL_RD_REG(HBN_BASE, HBN_RSV2); - /* DO HBN reset */ - HBN_Reset(); - /* HBN need 3 32k cyclce to recovery */ - BL702_Delay_US(100); - /* Recover HBN value */ - BL_WR_REG(HBN_BASE, HBN_TIME_L, tmp[1]); - BL_WR_REG(HBN_BASE, HBN_TIME_H, tmp[2]); - BL_WR_REG(HBN_BASE, HBN_CTL, tmp[0]); - - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmp[3]); - BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, tmp[4]); - BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmp[5]); - BL_WR_REG(HBN_BASE, HBN_PIR_VTH, tmp[6]); - BL_WR_REG(HBN_BASE, HBN_PIR_INTERVAL, tmp[7]); - BL_WR_REG(HBN_BASE, HBN_SRAM, tmp[8]); - BL_WR_REG(HBN_BASE, HBN_RSV0, tmp[9]); - BL_WR_REG(HBN_BASE, HBN_RSV1, tmp[10]); - BL_WR_REG(HBN_BASE, HBN_RSV2, tmp[11]); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Disable HBN mode - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Disable(void) -{ - uint32_t tmpVal; + * @brief reset HBN by software + * + * @param npXtalType: NP clock type + * @param bclkDiv: NP clock div + * @param apXtalType: AP clock type + * @param fclkDiv: AP clock div + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_App_Reset(uint8_t npXtalType, uint8_t bclkDiv, uint8_t apXtalType, uint8_t fclkDiv) { + uint32_t tmp[12]; + + tmp[0] = BL_RD_REG(HBN_BASE, HBN_CTL); + tmp[1] = BL_RD_REG(HBN_BASE, HBN_TIME_L); + tmp[2] = BL_RD_REG(HBN_BASE, HBN_TIME_H); + tmp[3] = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmp[4] = BL_RD_REG(HBN_BASE, HBN_IRQ_CLR); + tmp[5] = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); + tmp[6] = BL_RD_REG(HBN_BASE, HBN_PIR_VTH); + tmp[7] = BL_RD_REG(HBN_BASE, HBN_PIR_INTERVAL); + tmp[8] = BL_RD_REG(HBN_BASE, HBN_SRAM); + tmp[9] = BL_RD_REG(HBN_BASE, HBN_RSV0); + tmp[10] = BL_RD_REG(HBN_BASE, HBN_RSV1); + tmp[11] = BL_RD_REG(HBN_BASE, HBN_RSV2); + /* DO HBN reset */ + HBN_Reset(); + /* HBN need 3 32k cyclce to recovery */ + BL702_Delay_US(100); + /* Recover HBN value */ + BL_WR_REG(HBN_BASE, HBN_TIME_L, tmp[1]); + BL_WR_REG(HBN_BASE, HBN_TIME_H, tmp[2]); + BL_WR_REG(HBN_BASE, HBN_CTL, tmp[0]); + + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmp[3]); + BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, tmp[4]); + BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmp[5]); + BL_WR_REG(HBN_BASE, HBN_PIR_VTH, tmp[6]); + BL_WR_REG(HBN_BASE, HBN_PIR_INTERVAL, tmp[7]); + BL_WR_REG(HBN_BASE, HBN_SRAM, tmp[8]); + BL_WR_REG(HBN_BASE, HBN_RSV0, tmp[9]); + BL_WR_REG(HBN_BASE, HBN_RSV1, tmp[10]); + BL_WR_REG(HBN_BASE, HBN_RSV2, tmp[11]); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Disable HBN mode + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Disable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + /* Disable HBN mode */ + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_MODE); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Enable HBN PIR + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_PIR_Enable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PIR_EN); + BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Disable HBN PIR + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_PIR_Disable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PIR_EN); + BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Config HBN PIR interrupt + * + * @param pirIntCfg: HBN PIR interrupt configuration + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_PIR_INT_Config(HBN_PIR_INT_CFG_Type *pirIntCfg) { + uint32_t tmpVal; + uint32_t bit4 = 0; + uint32_t bit5 = 0; + uint32_t bitVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - /* Disable HBN mode */ - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_MODE); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); - return SUCCESS; -} + /* low trigger interrupt */ + if (pirIntCfg->lowIntEn == ENABLE) { + bit5 = 0; + } else { + bit5 = 1; + } -/****************************************************************************/ /** - * @brief Enable HBN PIR - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_PIR_Enable(void) -{ - uint32_t tmpVal; + /* high trigger interrupt */ + if (pirIntCfg->highIntEn == ENABLE) { + bit4 = 0; + } else { + bit4 = 1; + } - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PIR_EN); - BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); + bitVal = bit4 | (bit5 << 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_DIS, bitVal); + BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Disable HBN PIR - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_PIR_Disable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PIR_EN); - BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); + * @brief Select HBN PIR low pass filter + * + * @param lpf: HBN PIR low pass filter selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_PIR_LPF_Sel(HBN_PIR_LPF_Type lpf) { + uint32_t tmpVal; - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Config HBN PIR interrupt - * - * @param pirIntCfg: HBN PIR interrupt configuration - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_PIR_INT_Config(HBN_PIR_INT_CFG_Type *pirIntCfg) -{ - uint32_t tmpVal; - uint32_t bit4 = 0; - uint32_t bit5 = 0; - uint32_t bitVal = 0; - - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); - - /* low trigger interrupt */ - if (pirIntCfg->lowIntEn == ENABLE) { - bit5 = 0; - } else { - bit5 = 1; - } + CHECK_PARAM(IS_HBN_PIR_LPF_TYPE(lpf)); - /* high trigger interrupt */ - if (pirIntCfg->highIntEn == ENABLE) { - bit4 = 0; - } else { - bit4 = 1; - } + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_LPF_SEL, lpf); + BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); - bitVal = bit4 | (bit5 << 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_DIS, bitVal); - BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); - - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Select HBN PIR low pass filter - * - * @param lpf: HBN PIR low pass filter selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_PIR_LPF_Sel(HBN_PIR_LPF_Type lpf) -{ - uint32_t tmpVal; + * @brief Select HBN PIR high pass filter + * + * @param hpf: HBN PIR high pass filter selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_PIR_HPF_Sel(HBN_PIR_HPF_Type hpf) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_PIR_LPF_TYPE(lpf)); + CHECK_PARAM(IS_HBN_PIR_HPF_TYPE(hpf)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_LPF_SEL, lpf); - BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_HPF_SEL, hpf); + BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Select HBN PIR high pass filter - * - * @param hpf: HBN PIR high pass filter selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_PIR_HPF_Sel(HBN_PIR_HPF_Type hpf) -{ - uint32_t tmpVal; + * @brief Set HBN PIR threshold value + * + * @param threshold: HBN PIR threshold value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_PIR_Threshold(uint16_t threshold) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_PIR_HPF_TYPE(hpf)); + CHECK_PARAM((threshold <= 0x3FFF)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_HPF_SEL, hpf); - BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_VTH); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_VTH, threshold); + BL_WR_REG(HBN_BASE, HBN_PIR_VTH, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Set HBN PIR threshold value - * - * @param threshold: HBN PIR threshold value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_PIR_Threshold(uint16_t threshold) -{ - uint32_t tmpVal; - - CHECK_PARAM((threshold <= 0x3FFF)); + * @brief Get HBN PIR threshold value + * + * @param None + * + * @return HBN PIR threshold value + * + *******************************************************************************/ +uint16_t HBN_Get_PIR_Threshold(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_VTH); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_VTH, threshold); - BL_WR_REG(HBN_BASE, HBN_PIR_VTH, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_VTH); - return SUCCESS; + return BL_GET_REG_BITS_VAL(tmpVal, HBN_PIR_VTH); } /****************************************************************************/ /** - * @brief Get HBN PIR threshold value - * - * @param None - * - * @return HBN PIR threshold value - * -*******************************************************************************/ -uint16_t HBN_Get_PIR_Threshold(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_VTH); - - return BL_GET_REG_BITS_VAL(tmpVal, HBN_PIR_VTH); -} + * @brief Set HBN PIR interval value + * + * @param interval: HBN PIR interval value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_PIR_Interval(uint16_t interval) { + uint32_t tmpVal; -/****************************************************************************/ /** - * @brief Set HBN PIR interval value - * - * @param interval: HBN PIR interval value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_PIR_Interval(uint16_t interval) -{ - uint32_t tmpVal; + CHECK_PARAM((interval <= 0xFFF)); - CHECK_PARAM((interval <= 0xFFF)); + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_INTERVAL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_INTERVAL, interval); + BL_WR_REG(HBN_BASE, HBN_PIR_INTERVAL, tmpVal); - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_INTERVAL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_INTERVAL, interval); - BL_WR_REG(HBN_BASE, HBN_PIR_INTERVAL, tmpVal); - - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Get HBN PIR interval value - * - * @param None - * - * @return HBN PIR interval value - * -*******************************************************************************/ -uint16_t HBN_Get_PIR_Interval(void) -{ - uint32_t tmpVal; + * @brief Get HBN PIR interval value + * + * @param None + * + * @return HBN PIR interval value + * + *******************************************************************************/ +uint16_t HBN_Get_PIR_Interval(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_INTERVAL); + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_INTERVAL); - return BL_GET_REG_BITS_VAL(tmpVal, HBN_PIR_INTERVAL); + return BL_GET_REG_BITS_VAL(tmpVal, HBN_PIR_INTERVAL); } /****************************************************************************/ /** - * @brief get HBN bor out state - * - * @param None - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type HBN_Get_BOR_OUT_State(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(HBN_BASE, HBN_MISC), HBN_R_BOR_OUT) ? SET : RESET; -} + * @brief get HBN bor out state + * + * @param None + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type HBN_Get_BOR_OUT_State(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(HBN_BASE, HBN_MISC), HBN_R_BOR_OUT) ? SET : RESET; } /****************************************************************************/ /** - * @brief set HBN bor config - * - * @param enable: ENABLE or DISABLE, if enable, Power up Brown Out Reset - * @param threshold: bor threshold - * @param mode: bor work mode with por - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_BOR_Config(uint8_t enable, HBN_BOR_THRES_Type threshold, HBN_BOR_MODE_Type mode) -{ - uint32_t tmpVal; + * @brief set HBN bor config + * + * @param enable: ENABLE or DISABLE, if enable, Power up Brown Out Reset + * @param threshold: bor threshold + * @param mode: bor work mode with por + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_BOR_Config(uint8_t enable, HBN_BOR_THRES_Type threshold, HBN_BOR_MODE_Type mode) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_BOR_THRES_TYPE(threshold)); - CHECK_PARAM(IS_HBN_BOR_MODE_TYPE(mode)); + CHECK_PARAM(IS_HBN_BOR_THRES_TYPE(threshold)); + CHECK_PARAM(IS_HBN_BOR_MODE_TYPE(mode)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); + tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); - if (enable) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PU_BOR, 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PU_BOR, 0); - } + if (enable) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PU_BOR, 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PU_BOR, 0); + } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_BOR_VTH, threshold); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_BOR_SEL, mode); - BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_BOR_VTH, threshold); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_BOR_SEL, mode); + BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN set ldo11aon voltage out - * - * @param ldoLevel: LDO volatge level - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Aon_Vout(HBN_LDO_LEVEL_Type ldoLevel) -{ - uint32_t tmpVal; + * @brief HBN set ldo11aon voltage out + * + * @param ldoLevel: LDO volatge level + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Aon_Vout(HBN_LDO_LEVEL_Type ldoLevel) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); + CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_AON_VOUT_SEL, ldoLevel); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_AON_VOUT_SEL, ldoLevel); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN set ldo11rt voltage out - * - * @param ldoLevel: LDO volatge level - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Rt_Vout(HBN_LDO_LEVEL_Type ldoLevel) -{ - uint32_t tmpVal; + * @brief HBN set ldo11rt voltage out + * + * @param ldoLevel: LDO volatge level + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Rt_Vout(HBN_LDO_LEVEL_Type ldoLevel) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); + CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_RT_VOUT_SEL, ldoLevel); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_RT_VOUT_SEL, ldoLevel); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN set ldo11soc voltage out - * - * @param ldoLevel: LDO volatge level - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Soc_Vout(HBN_LDO_LEVEL_Type ldoLevel) -{ - uint32_t tmpVal; + * @brief HBN set ldo11soc voltage out + * + * @param ldoLevel: LDO volatge level + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Soc_Vout(HBN_LDO_LEVEL_Type ldoLevel) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); + CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11SOC_VOUT_SEL_AON, ldoLevel); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11SOC_VOUT_SEL_AON, ldoLevel); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN set ldo11 all voltage out - * - * @param ldoLevel: LDO volatge level - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_All_Vout(HBN_LDO_LEVEL_Type ldoLevel) -{ - uint32_t tmpVal; + * @brief HBN set ldo11 all voltage out + * + * @param ldoLevel: LDO volatge level + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_All_Vout(HBN_LDO_LEVEL_Type ldoLevel) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); + CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_AON_VOUT_SEL, ldoLevel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_RT_VOUT_SEL, ldoLevel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11SOC_VOUT_SEL_AON, ldoLevel); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_AON_VOUT_SEL, ldoLevel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_RT_VOUT_SEL, ldoLevel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11SOC_VOUT_SEL_AON, ldoLevel); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN set ldo11rt drive strength - * - * @param strength: ldo11rt drive strength - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11rt_Drive_Strength(HBN_LDO11RT_DRIVE_STRENGTH_Type strength) -{ - uint32_t tmpVal; + * @brief HBN set ldo11rt drive strength + * + * @param strength: ldo11rt drive strength + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11rt_Drive_Strength(HBN_LDO11RT_DRIVE_STRENGTH_Type strength) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_LDO11RT_DRIVE_STRENGTH_TYPE(strength)); + CHECK_PARAM(IS_HBN_LDO11RT_DRIVE_STRENGTH_TYPE(strength)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_LDO11_RT_ILOAD_SEL, strength); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_LDO11_RT_ILOAD_SEL, strength); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN select 32K - * - * @param clkType: HBN 32k clock type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION HBN_32K_Sel(HBN_32K_CLK_Type clkType) -{ - uint32_t tmpVal; + * @brief HBN select 32K + * + * @param clkType: HBN 32k clock type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION HBN_32K_Sel(HBN_32K_CLK_Type clkType) { + uint32_t tmpVal; - /* Check the parameters */ - CHECK_PARAM(IS_HBN_32K_CLK_TYPE(clkType)); + /* Check the parameters */ + CHECK_PARAM(IS_HBN_32K_CLK_TYPE(clkType)); - HBN_Trim_RC32K(); + HBN_Trim_RC32K(); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_F32K_SEL, clkType); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_F32K_SEL, clkType); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Select uart clock source - * - * @param clkSel: uart clock type selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_UART_CLK_Sel(HBN_UART_CLK_Type clkSel) -{ - uint32_t tmpVal; + * @brief Select uart clock source + * + * @param clkSel: uart clock type selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_UART_CLK_Sel(HBN_UART_CLK_Type clkSel) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_UART_CLK_TYPE(clkSel)); + CHECK_PARAM(IS_HBN_UART_CLK_TYPE(clkSel)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_UART_CLK_SEL, clkSel); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_UART_CLK_SEL, clkSel); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Select xclk clock source - * - * @param xClk: xclk clock type selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_XCLK_CLK_Sel(HBN_XCLK_CLK_Type xClk) -{ - uint32_t tmpVal; - uint32_t tmpVal2; + * @brief Select xclk clock source + * + * @param xClk: xclk clock type selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_XCLK_CLK_Sel(HBN_XCLK_CLK_Type xClk) { + uint32_t tmpVal; + uint32_t tmpVal2; - CHECK_PARAM(IS_HBN_XCLK_CLK_TYPE(xClk)); + CHECK_PARAM(IS_HBN_XCLK_CLK_TYPE(xClk)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL); - switch (xClk) { - case HBN_XCLK_CLK_RC32M: - tmpVal2 &= (~(1 << 0)); - break; + switch (xClk) { + case HBN_XCLK_CLK_RC32M: + tmpVal2 &= (~(1 << 0)); + break; - case HBN_XCLK_CLK_XTAL: - tmpVal2 |= (1 << 0); - break; + case HBN_XCLK_CLK_XTAL: + tmpVal2 |= (1 << 0); + break; - default: - break; - } + default: + break; + } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, tmpVal2); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - HBN_CLK_SET_DUMMY_WAIT; + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, tmpVal2); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + HBN_CLK_SET_DUMMY_WAIT; - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Select root clk source - * - * @param rootClk: root clock type selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Select root clk source + * + * @param rootClk: root clock type selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_Type rootClk) -{ - uint32_t tmpVal; - uint32_t tmpVal2; +BL_Err_Type ATTR_CLOCK_SECTION HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_Type rootClk) { + uint32_t tmpVal; + uint32_t tmpVal2; - CHECK_PARAM(IS_HBN_ROOT_CLK_TYPE(rootClk)); + CHECK_PARAM(IS_HBN_ROOT_CLK_TYPE(rootClk)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL); - switch (rootClk) { - case HBN_ROOT_CLK_RC32M: - tmpVal2 = 0x0; - break; + switch (rootClk) { + case HBN_ROOT_CLK_RC32M: + tmpVal2 = 0x0; + break; - case HBN_ROOT_CLK_XTAL: - tmpVal2 = 0x1; - break; + case HBN_ROOT_CLK_XTAL: + tmpVal2 = 0x1; + break; - case HBN_ROOT_CLK_DLL: - tmpVal2 |= (1 << 1); - break; + case HBN_ROOT_CLK_DLL: + tmpVal2 |= (1 << 1); + break; - default: - break; - } + default: + break; + } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, tmpVal2); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - HBN_CLK_SET_DUMMY_WAIT; + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, tmpVal2); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + HBN_CLK_SET_DUMMY_WAIT; - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief set HBN_RAM sleep mode - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_HRAM_slp(void) -{ - uint32_t tmpVal = 0; + * @brief set HBN_RAM sleep mode + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_HRAM_slp(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_SRAM); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RETRAM_SLP); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RETRAM_RET); - BL_WR_REG(HBN_BASE, HBN_SRAM, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_SRAM); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RETRAM_SLP); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RETRAM_RET); + BL_WR_REG(HBN_BASE, HBN_SRAM, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief set HBN_RAM retension mode - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_HRAM_Ret(void) -{ - uint32_t tmpVal = 0; + * @brief set HBN_RAM retension mode + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_HRAM_Ret(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_SRAM); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RETRAM_SLP); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RETRAM_RET); - BL_WR_REG(HBN_BASE, HBN_SRAM, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_SRAM); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RETRAM_SLP); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RETRAM_RET); + BL_WR_REG(HBN_BASE, HBN_SRAM, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Power on XTAL 32K - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_On_Xtal_32K(void) -{ - uint32_t tmpVal = 0; + * @brief Power on XTAL 32K + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_On_Xtal_32K(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_XTAL32K); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_XTAL32K); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_XTAL32K_BUF); - BL_WR_REG(HBN_BASE, HBN_XTAL32K, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_XTAL32K); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_XTAL32K); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_XTAL32K_BUF); + BL_WR_REG(HBN_BASE, HBN_XTAL32K, tmpVal); - /* Delay >1s */ - BL702_Delay_US(1100); + /* Delay >1s */ + BL702_Delay_US(1100); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Power off XTAL 32K - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_Off_Xtal_32K(void) -{ - uint32_t tmpVal = 0; + * @brief Power off XTAL 32K + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_Off_Xtal_32K(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_XTAL32K); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_XTAL32K); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_XTAL32K_BUF); - BL_WR_REG(HBN_BASE, HBN_XTAL32K, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_XTAL32K); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_XTAL32K); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_XTAL32K_BUF); + BL_WR_REG(HBN_BASE, HBN_XTAL32K, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Power on RC32K - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_On_RC32K(void) -{ - uint32_t tmpVal = 0; + * @brief Power on RC32K + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_On_RC32K(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_RC32K); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_RC32K); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - /* Delay >800us */ - BL702_Delay_US(880); + /* Delay >800us */ + BL702_Delay_US(880); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Power off RC3K - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_Off_RC32K(void) -{ - uint32_t tmpVal = 0; + * @brief Power off RC3K + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_Off_RC32K(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_RC32K); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_RC32K); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Trim RC32K - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Trim RC32K + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION HBN_Trim_RC32K(void) -{ - Efuse_Ana_RC32K_Trim_Type trim; - int32_t tmpVal = 0; - - EF_Ctrl_Read_RC32K_Trim(&trim); - - if (trim.trimRc32kExtCodeEn) { - if (trim.trimRc32kCodeFrExtParity == EF_Ctrl_Get_Trim_Parity(trim.trimRc32kCodeFrExt, 10)) { - tmpVal = BL_RD_REG(HBN_BASE, HBN_RC32K_CTRL0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_RC32K_CODE_FR_EXT, trim.trimRc32kCodeFrExt); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RC32K_EXT_CODE_EN); - BL_WR_REG(HBN_BASE, HBN_RC32K_CTRL0, tmpVal); - BL702_Delay_US(2); - return SUCCESS; - } +BL_Err_Type ATTR_CLOCK_SECTION HBN_Trim_RC32K(void) { + Efuse_Ana_RC32K_Trim_Type trim; + int32_t tmpVal = 0; + + EF_Ctrl_Read_RC32K_Trim(&trim); + + if (trim.trimRc32kExtCodeEn) { + if (trim.trimRc32kCodeFrExtParity == EF_Ctrl_Get_Trim_Parity(trim.trimRc32kCodeFrExt, 10)) { + tmpVal = BL_RD_REG(HBN_BASE, HBN_RC32K_CTRL0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_RC32K_CODE_FR_EXT, trim.trimRc32kCodeFrExt); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RC32K_EXT_CODE_EN); + BL_WR_REG(HBN_BASE, HBN_RC32K_CTRL0, tmpVal); + BL702_Delay_US(2); + return SUCCESS; } + } - return ERROR; + return ERROR; } #endif /****************************************************************************/ /** - * @brief Get HBN status flag - * - * @param None - * - * @return HBN status flag value - * -*******************************************************************************/ -uint32_t HBN_Get_Status_Flag(void) -{ - return BL_RD_REG(HBN_BASE, HBN_RSV0); -} + * @brief Get HBN status flag + * + * @param None + * + * @return HBN status flag value + * + *******************************************************************************/ +uint32_t HBN_Get_Status_Flag(void) { return BL_RD_REG(HBN_BASE, HBN_RSV0); } -/****************************************************************************/ /** - * @brief Set HBN status flag - * - * @param flag: Status Flag - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_Status_Flag(uint32_t flag) -{ - BL_WR_REG(HBN_BASE, HBN_RSV0, flag); +/****************************************************************************/ /** + * @brief Set HBN status flag + * + * @param flag: Status Flag + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_Status_Flag(uint32_t flag) { + BL_WR_REG(HBN_BASE, HBN_RSV0, flag); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Get HBN wakeup address - * - * @param None - * - * @return HBN wakeup address - * -*******************************************************************************/ -uint32_t HBN_Get_Wakeup_Addr(void) -{ - return BL_RD_REG(HBN_BASE, HBN_RSV1); -} + * @brief Get HBN wakeup address + * + * @param None + * + * @return HBN wakeup address + * + *******************************************************************************/ +uint32_t HBN_Get_Wakeup_Addr(void) { return BL_RD_REG(HBN_BASE, HBN_RSV1); } -/****************************************************************************/ /** - * @brief Set HBN wakeup address - * - * @param addr: HBN wakeup address - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_Wakeup_Addr(uint32_t addr) -{ - BL_WR_REG(HBN_BASE, HBN_RSV1, addr); +/****************************************************************************/ /** + * @brief Set HBN wakeup address + * + * @param addr: HBN wakeup address + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_Wakeup_Addr(uint32_t addr) { + BL_WR_REG(HBN_BASE, HBN_RSV1, addr); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN clear RTC timer counter - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Clear_RTC_Counter(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - /* Clear RTC control bit0 */ - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal & 0xfffffffe); - - return SUCCESS; -} + * @brief HBN clear RTC timer counter + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Clear_RTC_Counter(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + /* Clear RTC control bit0 */ + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal & 0xfffffffe); + + return SUCCESS; +} /****************************************************************************/ /** - * @brief HBN clear RTC timer counter - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Enable_RTC_Counter(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - /* Set RTC control bit0 */ - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal | 0x01); - - return SUCCESS; -} + * @brief HBN clear RTC timer counter + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Enable_RTC_Counter(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + /* Set RTC control bit0 */ + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal | 0x01); + + return SUCCESS; +} /****************************************************************************/ /** - * @brief HBN set RTC timer configuration - * - * @param delay: RTC interrupt delay 32 clocks - * @param compValLow: RTC interrupt commpare value low 32 bits - * @param compValHigh: RTC interrupt commpare value high 32 bits - * @param compMode: RTC interrupt commpare - * mode:HBN_RTC_COMP_BIT0_39,HBN_RTC_COMP_BIT0_23,HBN_RTC_COMP_BIT13_39 - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_RTC_Timer(HBN_RTC_INT_Delay_Type delay, uint32_t compValLow, uint32_t compValHigh, uint8_t compMode) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_HBN_RTC_INT_DELAY_TYPE(delay)); + * @brief HBN set RTC timer configuration + * + * @param delay: RTC interrupt delay 32 clocks + * @param compValLow: RTC interrupt commpare value low 32 bits + * @param compValHigh: RTC interrupt commpare value high 32 bits + * @param compMode: RTC interrupt commpare + * mode:HBN_RTC_COMP_BIT0_39,HBN_RTC_COMP_BIT0_23,HBN_RTC_COMP_BIT13_39 + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_RTC_Timer(HBN_RTC_INT_Delay_Type delay, uint32_t compValLow, uint32_t compValHigh, uint8_t compMode) { + uint32_t tmpVal; - BL_WR_REG(HBN_BASE, HBN_TIME_L, compValLow); - BL_WR_REG(HBN_BASE, HBN_TIME_H, compValHigh & 0xff); + /* Check the parameters */ + CHECK_PARAM(IS_HBN_RTC_INT_DELAY_TYPE(delay)); + + BL_WR_REG(HBN_BASE, HBN_TIME_L, compValLow); + BL_WR_REG(HBN_BASE, HBN_TIME_H, compValHigh & 0xff); - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - /* Set interrupt delay option */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_RTC_DLY_OPTION, delay); - /* Set RTC compare mode */ - tmpVal |= (compMode << 1); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + /* Set interrupt delay option */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_RTC_DLY_OPTION, delay); + /* Set RTC compare mode */ + tmpVal |= (compMode << 1); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN get RTC async timer count value - * - * @param valLow: RTC count value pointer for low 32 bits - * @param valHigh: RTC count value pointer for high 8 bits - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -static BL_Err_Type HBN_Get_RTC_Timer_Async_Val(uint32_t *valLow, uint32_t *valHigh) -{ - uint32_t tmpVal; + * @brief HBN get RTC async timer count value + * + * @param valLow: RTC count value pointer for low 32 bits + * @param valHigh: RTC count value pointer for high 8 bits + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +static BL_Err_Type HBN_Get_RTC_Timer_Async_Val(uint32_t *valLow, uint32_t *valHigh) { + uint32_t tmpVal; - /* Tigger RTC val read */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH); - BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH); - BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal); + /* Tigger RTC val read */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH); + BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH); + BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal); - /* Read RTC val */ - *valLow = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_L); - *valHigh = (BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H) & 0xff); + /* Read RTC val */ + *valLow = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_L); + *valHigh = (BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H) & 0xff); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN get RTC timer count value - * - * @param valLow: RTC count value pointer for low 32 bits - * @param valHigh: RTC count value pointer for high 8 bits - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Get_RTC_Timer_Val(uint32_t *valLow, uint32_t *valHigh) -{ - uint32_t tmpValLow, tmpValHigh, tmpValLow1, tmpValHigh1; - uint64_t val, val1; + * @brief HBN get RTC timer count value + * + * @param valLow: RTC count value pointer for low 32 bits + * @param valHigh: RTC count value pointer for high 8 bits + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Get_RTC_Timer_Val(uint32_t *valLow, uint32_t *valHigh) { + uint32_t tmpValLow, tmpValHigh, tmpValLow1, tmpValHigh1; + uint64_t val, val1; - do { - HBN_Get_RTC_Timer_Async_Val(&tmpValLow, &tmpValHigh); - val = ((uint64_t)tmpValHigh << 32) | ((uint64_t)tmpValLow); - HBN_Get_RTC_Timer_Async_Val(&tmpValLow1, &tmpValHigh1); - val1 = ((uint64_t)tmpValHigh1 << 32) | ((uint64_t)tmpValLow1); - } while (val1 < val); + do { + HBN_Get_RTC_Timer_Async_Val(&tmpValLow, &tmpValHigh); + val = ((uint64_t)tmpValHigh << 32) | ((uint64_t)tmpValLow); + HBN_Get_RTC_Timer_Async_Val(&tmpValLow1, &tmpValHigh1); + val1 = ((uint64_t)tmpValHigh1 << 32) | ((uint64_t)tmpValLow1); + } while (val1 < val); - *valLow = tmpValLow1; - *valHigh = tmpValHigh1; + *valLow = tmpValLow1; + *valHigh = tmpValHigh1; - return SUCCESS; + return SUCCESS; } -/****************************************************************************/ /** - * @brief HBN clear RTC timer interrupt,this function must be called to clear delayed rtc IRQ - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Clear_RTC_INT(void) -{ - uint32_t tmpVal; +/****************************************************************************/ /** + * @brief HBN clear RTC timer interrupt,this function must be called to clear delayed rtc IRQ + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Clear_RTC_INT(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - /* Clear RTC commpare:bit1-3 for clearing Delayed RTC IRQ */ - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal & 0xfffffff1); + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + /* Clear RTC commpare:bit1-3 for clearing Delayed RTC IRQ */ + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal & 0xfffffff1); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN enable GPIO interrupt - * - * @param gpioIntTrigType: HBN GPIO interrupt trigger type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_GPIO_INT_Enable(HBN_GPIO_INT_Trigger_Type gpioIntTrigType) -{ - uint32_t tmpVal; + * @brief HBN enable GPIO interrupt + * + * @param gpioIntTrigType: HBN GPIO interrupt trigger type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_GPIO_INT_Enable(HBN_GPIO_INT_Trigger_Type gpioIntTrigType) { + uint32_t tmpVal; - /* Check the parameters */ - CHECK_PARAM(IS_HBN_GPIO_INT_TRIGGER_TYPE(gpioIntTrigType)); + /* Check the parameters */ + CHECK_PARAM(IS_HBN_GPIO_INT_TRIGGER_TYPE(gpioIntTrigType)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_MODE, gpioIntTrigType); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_MODE, gpioIntTrigType); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN disable GPIO interrupt - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_GPIO_INT_Disable(void) -{ - uint32_t tmpVal; + * @brief HBN disable GPIO interrupt + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_GPIO_INT_Disable(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_MASK, 0); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_MASK, 0); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN get interrupt status - * - * @param irqType: HBN interrupt type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type HBN_Get_INT_State(HBN_INT_Type irqType) -{ - uint32_t tmpVal; + * @brief HBN get interrupt status + * + * @param irqType: HBN interrupt type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type HBN_Get_INT_State(HBN_INT_Type irqType) { + uint32_t tmpVal; - /* Check the parameters */ + /* Check the parameters */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_STAT); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_STAT); - if (tmpVal & (1 << irqType)) { - return SET; - } else { - return RESET; - } + if (tmpVal & (1 << irqType)) { + return SET; + } else { + return RESET; + } } /****************************************************************************/ /** - * @brief HBN get pin wakeup mode value - * - * @param None - * - * @return HBN pin wakeup mode value - * -*******************************************************************************/ -uint8_t HBN_Get_Pin_Wakeup_Mode(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(HBN_BASE, HBN_IRQ_MODE), HBN_PIN_WAKEUP_MODE); -} + * @brief HBN get pin wakeup mode value + * + * @param None + * + * @return HBN pin wakeup mode value + * + *******************************************************************************/ +uint8_t HBN_Get_Pin_Wakeup_Mode(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(HBN_BASE, HBN_IRQ_MODE), HBN_PIN_WAKEUP_MODE); } /****************************************************************************/ /** - * @brief HBN clear interrupt status - * - * @param irqType: HBN interrupt type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Clear_IRQ(HBN_INT_Type irqType) -{ - uint32_t tmpVal; + * @brief HBN clear interrupt status + * + * @param irqType: HBN interrupt type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Clear_IRQ(HBN_INT_Type irqType) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_INT_TYPE(irqType)); + CHECK_PARAM(IS_HBN_INT_TYPE(irqType)); - /* set clear bit */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_CLR); - tmpVal |= (1 << irqType); - BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, tmpVal); + /* set clear bit */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_CLR); + tmpVal |= (1 << irqType); + BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, tmpVal); - /* unset clear bit */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_CLR); - tmpVal &= (~(1 << irqType)); - BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, tmpVal); + /* unset clear bit */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_CLR); + tmpVal &= (~(1 << irqType)); + BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN hardware pullup or pulldown configuration - * - * @param enable: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Hw_Pu_Pd_Cfg(uint8_t enable) -{ - uint32_t tmpVal; + * @brief HBN hardware pullup or pulldown configuration + * + * @param enable: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Hw_Pu_Pd_Cfg(uint8_t enable) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); - } + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); + } - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN Config AON pad input and SMT - * - * @param padCfg: AON pad config - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Aon_Pad_IeSmt_Cfg(uint8_t padCfg) -{ - uint32_t tmpVal; + * @brief HBN Config AON pad input and SMT + * + * @param padCfg: AON pad config + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Aon_Pad_IeSmt_Cfg(uint8_t padCfg) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, padCfg); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, padCfg); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN wakeup pin mask configuration - * - * @param maskVal: mask value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Pin_WakeUp_Mask(uint8_t maskVal) -{ - uint32_t tmpVal; + * @brief HBN wakeup pin mask configuration + * + * @param maskVal: mask value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Pin_WakeUp_Mask(uint8_t maskVal) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_MASK, maskVal); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_MASK, maskVal); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN enable ACOMP0 interrupt - * - * @param edge: HBN acomp interrupt edge type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Enable_AComp0_IRQ(HBN_ACOMP_INT_EDGE_Type edge) -{ - uint32_t tmpVal; - uint32_t tmpVal2; + * @brief HBN enable ACOMP0 interrupt + * + * @param edge: HBN acomp interrupt edge type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Enable_AComp0_IRQ(HBN_ACOMP_INT_EDGE_Type edge) { + uint32_t tmpVal; + uint32_t tmpVal2; - CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); + CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN); - tmpVal2 = tmpVal2 | (1 << edge); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN, tmpVal2); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN); + tmpVal2 = tmpVal2 | (1 << edge); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN, tmpVal2); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN disable ACOMP0 interrupt - * - * @param edge: HBN acomp interrupt edge type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Disable_AComp0_IRQ(HBN_ACOMP_INT_EDGE_Type edge) -{ - uint32_t tmpVal; - uint32_t tmpVal2; + * @brief HBN disable ACOMP0 interrupt + * + * @param edge: HBN acomp interrupt edge type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Disable_AComp0_IRQ(HBN_ACOMP_INT_EDGE_Type edge) { + uint32_t tmpVal; + uint32_t tmpVal2; - CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); + CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN); - tmpVal2 = tmpVal2 & (~(1 << edge)); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN, tmpVal2); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN); + tmpVal2 = tmpVal2 & (~(1 << edge)); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN, tmpVal2); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN enable ACOMP1 interrupt - * - * @param edge: HBN acomp interrupt edge type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Enable_AComp1_IRQ(HBN_ACOMP_INT_EDGE_Type edge) -{ - uint32_t tmpVal; - uint32_t tmpVal2; + * @brief HBN enable ACOMP1 interrupt + * + * @param edge: HBN acomp interrupt edge type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Enable_AComp1_IRQ(HBN_ACOMP_INT_EDGE_Type edge) { + uint32_t tmpVal; + uint32_t tmpVal2; - CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); + CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN); - tmpVal2 = tmpVal2 | (1 << edge); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN, tmpVal2); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN); + tmpVal2 = tmpVal2 | (1 << edge); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN, tmpVal2); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN disable ACOMP1 interrupt - * - * @param edge: HBN acomp interrupt edge type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Disable_AComp1_IRQ(HBN_ACOMP_INT_EDGE_Type edge) -{ - uint32_t tmpVal; - uint32_t tmpVal2; + * @brief HBN disable ACOMP1 interrupt + * + * @param edge: HBN acomp interrupt edge type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Disable_AComp1_IRQ(HBN_ACOMP_INT_EDGE_Type edge) { + uint32_t tmpVal; + uint32_t tmpVal2; - CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); + CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN); - tmpVal2 = tmpVal2 & (~(1 << edge)); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN, tmpVal2); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN); + tmpVal2 = tmpVal2 & (~(1 << edge)); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN, tmpVal2); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN enable BOR interrupt - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Enable_BOR_IRQ(void) -{ - uint32_t tmpVal; + * @brief HBN enable BOR interrupt + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Enable_BOR_IRQ(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_IRQ_BOR_EN); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_IRQ_BOR_EN); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN disable BOR interrupt - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Disable_BOR_IRQ(void) -{ - uint32_t tmpVal; + * @brief HBN disable BOR interrupt + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Disable_BOR_IRQ(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_IRQ_BOR_EN); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_IRQ_BOR_EN); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief get HBN reset event status - * - * @param event: HBN reset event type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type HBN_Get_Reset_Event(HBN_RST_EVENT_Type event) -{ - uint32_t tmpVal; + * @brief get HBN reset event status + * + * @param event: HBN reset event type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type HBN_Get_Reset_Event(HBN_RST_EVENT_Type event) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, HBN_RESET_EVENT); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, HBN_RESET_EVENT); - return (tmpVal & (1 << event)) ? SET : RESET; + return (tmpVal & (1 << event)) ? SET : RESET; } /****************************************************************************/ /** - * @brief clear HBN reset event status - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Clear_Reset_Event(void) -{ - uint32_t tmpVal; + * @brief clear HBN reset event status + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Clear_Reset_Event(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_CLEAR_RESET_EVENT); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_CLEAR_RESET_EVENT); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_CLEAR_RESET_EVENT); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_CLEAR_RESET_EVENT); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_CLEAR_RESET_EVENT); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_CLEAR_RESET_EVENT); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN out0 install interrupt callback - * - * @param intType: HBN out0 interrupt type - * @param cbFun: HBN out0 interrupt callback - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Out0_Callback_Install(HBN_OUT0_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_HBN_OUT0_INT_TYPE(intType)); + * @brief HBN out0 install interrupt callback + * + * @param intType: HBN out0 interrupt type + * @param cbFun: HBN out0 interrupt callback + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Out0_Callback_Install(HBN_OUT0_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_HBN_OUT0_INT_TYPE(intType)); - hbnInt0CbfArra[intType] = cbFun; + hbnInt0CbfArra[intType] = cbFun; - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN out1 install interrupt callback - * - * @param intType: HBN out1 interrupt type - * @param cbFun: HBN out1 interrupt callback - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Out1_Callback_Install(HBN_OUT1_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_HBN_OUT1_INT_TYPE(intType)); + * @brief HBN out1 install interrupt callback + * + * @param intType: HBN out1 interrupt type + * @param cbFun: HBN out1 interrupt callback + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Out1_Callback_Install(HBN_OUT1_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_HBN_OUT1_INT_TYPE(intType)); - hbnInt1CbfArra[intType] = cbFun; + hbnInt1CbfArra[intType] = cbFun; - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN GPIO debug pull config - * - * @param pupdEn: Enable or disable GPIO pull down and pull up - * @param dlyEn: Enable or disable GPIO wakeup delay function - * @param dlySec: GPIO wakeup delay sec 1 to 7 - * @param gpioIrq: HBN GPIO num - * @param gpioMask: HBN GPIO MASK or UNMASK - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief HBN GPIO debug pull config + * + * @param pupdEn: Enable or disable GPIO pull down and pull up + * @param dlyEn: Enable or disable GPIO wakeup delay function + * @param dlySec: GPIO wakeup delay sec 1 to 7 + * @param gpioIrq: HBN GPIO num + * @param gpioMask: HBN GPIO MASK or UNMASK + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION HBN_GPIO_Dbg_Pull_Cfg(BL_Fun_Type pupdEn, BL_Fun_Type dlyEn, uint8_t dlySec, HBN_INT_Type gpioIrq, BL_Mask_Type gpioMask) -{ - uint32_t tmpVal; - - CHECK_PARAM(((dlySec >= 1) && (dlySec <= 7))); - CHECK_PARAM((gpioIrq >= HBN_INT_GPIO9) && (gpioIrq <= HBN_INT_GPIO13)); - - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_EN, dlyEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_SEL, dlySec); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_EN_HW_PU_PD, pupdEn); - - if (gpioMask != UNMASK) { - tmpVal = tmpVal | (1 << (gpioIrq + 8)); - } else { - tmpVal = tmpVal & ~(1 << (gpioIrq + 8)); - } +BL_Err_Type ATTR_TCM_SECTION HBN_GPIO_Dbg_Pull_Cfg(BL_Fun_Type pupdEn, BL_Fun_Type dlyEn, uint8_t dlySec, HBN_INT_Type gpioIrq, BL_Mask_Type gpioMask) { + uint32_t tmpVal; + + CHECK_PARAM(((dlySec >= 1) && (dlySec <= 7))); + CHECK_PARAM((gpioIrq >= HBN_INT_GPIO9) && (gpioIrq <= HBN_INT_GPIO13)); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_EN, dlyEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_SEL, dlySec); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_EN_HW_PU_PD, pupdEn); - return SUCCESS; + if (gpioMask != UNMASK) { + tmpVal = tmpVal | (1 << (gpioIrq + 8)); + } else { + tmpVal = tmpVal & ~(1 << (gpioIrq + 8)); + } + + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Set pad 23-28 pull none - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_Pullnone(void) -{ - uint32_t tmpVal = 0; + * @brief Set pad 23-28 pull none + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_Pullnone(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x00); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x00); - BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x00); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x00); + BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Set pad 23-28 pull up - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_Pullup(void) -{ - uint32_t tmpVal = 0; + * @brief Set pad 23-28 pull up + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_Pullup(void) { + uint32_t tmpVal = 0; - /********************************************/ - /* GPIO28 is bootpin, so leave it pull none */ - /********************************************/ + /********************************************/ + /* GPIO28 is bootpin, so leave it pull none */ + /********************************************/ - tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x00); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x1F); - BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x00); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x1F); + BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Set pad 23-28 pull down - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_Pulldown(void) -{ - uint32_t tmpVal = 0; + * @brief Set pad 23-28 pull down + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_Pulldown(void) { + uint32_t tmpVal = 0; - /********************************************/ - /* GPIO28 is bootpin, so leave it pull none */ - /********************************************/ + /********************************************/ + /* GPIO28 is bootpin, so leave it pull none */ + /********************************************/ - tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x1F); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x00); - BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x1F); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x00); + BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Set pad 23-28 active ie - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_ActiveIE(void) -{ - uint32_t tmpVal = 0; + * @brief Set pad 23-28 active ie + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_ActiveIE(void) { + uint32_t tmpVal = 0; - /********************************************/ - /* GPIO28 is bootpin, so leave it pull none */ - /********************************************/ + /********************************************/ + /* GPIO28 is bootpin, so leave it pull none */ + /********************************************/ - tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x1F); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x1F); - BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x1F); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x1F); + BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Set BOR config - * - * @param cfg: Enable or disable - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_BOR_Cfg(HBN_BOR_CFG_Type *cfg) -{ - uint32_t tmpVal = 0; - - if (cfg->enableBorInt) { - HBN_Enable_BOR_IRQ(); - } else { - HBN_Disable_BOR_IRQ(); - } + * @brief Set BOR config + * + * @param cfg: Enable or disable + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_BOR_Cfg(HBN_BOR_CFG_Type *cfg) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); + if (cfg->enableBorInt) { + HBN_Enable_BOR_IRQ(); + } else { + HBN_Disable_BOR_IRQ(); + } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_BOR_VTH, cfg->borThreshold); + tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); - if (cfg->enablePorInBor) { - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_BOR_SEL); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_BOR_SEL); - } + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_BOR_VTH, cfg->borThreshold); - if (cfg->enableBor) { - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_BOR); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_BOR); - } + if (cfg->enablePorInBor) { + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_BOR_SEL); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_BOR_SEL); + } - BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); + if (cfg->enableBor) { + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_BOR); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_BOR); + } + + BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN OUT0 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ -void HBN_OUT0_IRQHandler(void) -{ - if (SET == HBN_Get_INT_State(HBN_INT_GPIO9)) { - HBN_Clear_IRQ(HBN_INT_GPIO9); - - if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO9] != NULL) { - hbnInt0CbfArra[HBN_OUT0_INT_GPIO9](); - } + * @brief HBN OUT0 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ +void HBN_OUT0_IRQHandler(void) { + if (SET == HBN_Get_INT_State(HBN_INT_GPIO9)) { + HBN_Clear_IRQ(HBN_INT_GPIO9); + + if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO9] != NULL) { + hbnInt0CbfArra[HBN_OUT0_INT_GPIO9](); } + } - if (SET == HBN_Get_INT_State(HBN_INT_GPIO10)) { - HBN_Clear_IRQ(HBN_INT_GPIO10); + if (SET == HBN_Get_INT_State(HBN_INT_GPIO10)) { + HBN_Clear_IRQ(HBN_INT_GPIO10); - if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO10] != NULL) { - hbnInt0CbfArra[HBN_OUT0_INT_GPIO10](); - } + if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO10] != NULL) { + hbnInt0CbfArra[HBN_OUT0_INT_GPIO10](); } + } - if (SET == HBN_Get_INT_State(HBN_INT_GPIO11)) { - HBN_Clear_IRQ(HBN_INT_GPIO11); + if (SET == HBN_Get_INT_State(HBN_INT_GPIO11)) { + HBN_Clear_IRQ(HBN_INT_GPIO11); - if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO11] != NULL) { - hbnInt0CbfArra[HBN_OUT0_INT_GPIO11](); - } + if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO11] != NULL) { + hbnInt0CbfArra[HBN_OUT0_INT_GPIO11](); } + } - if (SET == HBN_Get_INT_State(HBN_INT_GPIO12)) { - HBN_Clear_IRQ(HBN_INT_GPIO12); + if (SET == HBN_Get_INT_State(HBN_INT_GPIO12)) { + HBN_Clear_IRQ(HBN_INT_GPIO12); - if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO12] != NULL) { - hbnInt0CbfArra[HBN_OUT0_INT_GPIO12](); - } + if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO12] != NULL) { + hbnInt0CbfArra[HBN_OUT0_INT_GPIO12](); } + } - if (SET == HBN_Get_INT_State(HBN_INT_GPIO13)) { - HBN_Clear_IRQ(HBN_INT_GPIO13); + if (SET == HBN_Get_INT_State(HBN_INT_GPIO13)) { + HBN_Clear_IRQ(HBN_INT_GPIO13); - if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO13] != NULL) { - hbnInt0CbfArra[HBN_OUT0_INT_GPIO13](); - } + if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO13] != NULL) { + hbnInt0CbfArra[HBN_OUT0_INT_GPIO13](); } + } - if (SET == HBN_Get_INT_State(HBN_INT_RTC)) { - HBN_Clear_IRQ(HBN_INT_RTC); - HBN_Clear_RTC_INT(); + if (SET == HBN_Get_INT_State(HBN_INT_RTC)) { + HBN_Clear_IRQ(HBN_INT_RTC); + HBN_Clear_RTC_INT(); - if (hbnInt0CbfArra[HBN_OUT0_INT_RTC] != NULL) { - hbnInt0CbfArra[HBN_OUT0_INT_RTC](); - } + if (hbnInt0CbfArra[HBN_OUT0_INT_RTC] != NULL) { + hbnInt0CbfArra[HBN_OUT0_INT_RTC](); } + } } /****************************************************************************/ /** - * @brief HBN OUT1 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ -void HBN_OUT1_IRQHandler(void) -{ - /* PIR */ - if (SET == HBN_Get_INT_State(HBN_INT_PIR)) { - HBN_Clear_IRQ(HBN_INT_PIR); - - if (hbnInt1CbfArra[HBN_OUT1_INT_PIR] != NULL) { - hbnInt1CbfArra[HBN_OUT1_INT_PIR](); - } - } + * @brief HBN OUT1 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ +void HBN_OUT1_IRQHandler(void) { + /* PIR */ + if (SET == HBN_Get_INT_State(HBN_INT_PIR)) { + HBN_Clear_IRQ(HBN_INT_PIR); - /* BOR */ - if (SET == HBN_Get_INT_State(HBN_INT_BOR)) { - HBN_Clear_IRQ(HBN_INT_BOR); - - if (hbnInt1CbfArra[HBN_OUT1_INT_BOR] != NULL) { - hbnInt1CbfArra[HBN_OUT1_INT_BOR](); - } + if (hbnInt1CbfArra[HBN_OUT1_INT_PIR] != NULL) { + hbnInt1CbfArra[HBN_OUT1_INT_PIR](); } + } - /* ACOMP0 */ - if (SET == HBN_Get_INT_State(HBN_INT_ACOMP0)) { - HBN_Clear_IRQ(HBN_INT_ACOMP0); + /* BOR */ + if (SET == HBN_Get_INT_State(HBN_INT_BOR)) { + HBN_Clear_IRQ(HBN_INT_BOR); - if (hbnInt1CbfArra[HBN_OUT1_INT_ACOMP0] != NULL) { - hbnInt1CbfArra[HBN_OUT1_INT_ACOMP0](); - } + if (hbnInt1CbfArra[HBN_OUT1_INT_BOR] != NULL) { + hbnInt1CbfArra[HBN_OUT1_INT_BOR](); } + } - /* ACOMP1 */ - if (SET == HBN_Get_INT_State(HBN_INT_ACOMP1)) { - HBN_Clear_IRQ(HBN_INT_ACOMP1); - - if (hbnInt1CbfArra[HBN_OUT1_INT_ACOMP1] != NULL) { - hbnInt1CbfArra[HBN_OUT1_INT_ACOMP1](); - } - } -} + /* ACOMP0 */ + if (SET == HBN_Get_INT_State(HBN_INT_ACOMP0)) { + HBN_Clear_IRQ(HBN_INT_ACOMP0); -/****************************************************************************/ /** - * @brief Enable HBN mode - * - * @param aGPIOIeCfg: AON GPIO IE config,Bit0->GPIO18. Bit(s) of Wakeup GPIO(s) must not be set to - * 0(s),say when use GPIO7 as wake up pin,aGPIOIeCfg should be 0x01. - * @param ldoLevel: LDO volatge level - * @param hbnLevel: HBN work level - * - * @return None - * -*******************************************************************************/ -void ATTR_TCM_SECTION HBN_Enable(uint8_t aGPIOIeCfg, HBN_LDO_LEVEL_Type ldoLevel, HBN_LEVEL_Type hbnLevel) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); - CHECK_PARAM(IS_HBN_LEVEL_TYPE(hbnLevel)); - - /* Setting from guide */ - /* RAM Retion */ - BL_WR_REG(HBN_BASE, HBN_SRAM, 0x24); - /* AON GPIO IE */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aGPIOIeCfg); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - ///* Power off 1.8V */ - //tmpVal=BL_RD_REG(AON_BASE,AON_PMIP); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_TOPLDO11_SOC); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_TOPLDO18_RF); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_TOPLDO18_IO); - ///* SOC11 enum is not the same as VDD11*/ - //tmpVal=BL_SET_REG_BITS_VAL(tmpVal,AON_TOPLDO11_SOC_VOUT_SEL,ldoLevel-1); - //BL_WR_REG(AON_BASE,AON_PMIP,tmpVal); - // - ///* Set RT voltage */ - //tmpVal=BL_RD_REG(AON_BASE,AON); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_SW3); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_SW2); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_SW1); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_BYPASS); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_LDO18_AON); - ///* RT11 enum is not the same as VDD11*/ - //tmpVal=BL_SET_REG_BITS_VAL(tmpVal,AON_TOPLDO11_RT_VOUT_SEL,ldoLevel-1); - //tmpVal=BL_SET_REG_BITS_VAL(tmpVal,AON_VDD11_SEL,ldoLevel); - //BL_WR_REG(AON_BASE,AON,tmpVal); - - /* Select RC32M */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - - /* Set HBN flag */ - BL_WR_REG(HBN_BASE, HBN_RSV0, HBN_STATUS_ENTER_FLAG); - - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - - /* Set HBN level, (HBN_PWRDN_HBN_RAM not use) */ - switch (hbnLevel) { - case HBN_LEVEL_0: - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - case HBN_LEVEL_1: - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - case HBN_LEVEL_2: - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - case HBN_LEVEL_3: - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - default: - break; + if (hbnInt1CbfArra[HBN_OUT1_INT_ACOMP0] != NULL) { + hbnInt1CbfArra[HBN_OUT1_INT_ACOMP0](); } + } - /* Set power on option:0 for por reset twice for robust 1 for reset only once*/ - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWR_ON_OPTION); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - - /* Enable HBN mode */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_MODE); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + /* ACOMP1 */ + if (SET == HBN_Get_INT_State(HBN_INT_ACOMP1)) { + HBN_Clear_IRQ(HBN_INT_ACOMP1); - while (1) { - BL702_Delay_MS(1000); + if (hbnInt1CbfArra[HBN_OUT1_INT_ACOMP1] != NULL) { + hbnInt1CbfArra[HBN_OUT1_INT_ACOMP1](); } -} - -/****************************************************************************/ /** - * @brief HBN out0 IRQHandler install - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Out0_IRQHandler_Install(void) -{ - Interrupt_Handler_Register(HBN_OUT0_IRQn, HBN_OUT0_IRQHandler); - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief HBN out1 IRQHandler install - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Out1_IRQHandler_Install(void) -{ - Interrupt_Handler_Register(HBN_OUT1_IRQn, HBN_OUT1_IRQHandler); - return SUCCESS; + } +} + +/****************************************************************************/ /** + * @brief Enable HBN mode + * + * @param aGPIOIeCfg: AON GPIO IE config,Bit0->GPIO18. Bit(s) of Wakeup GPIO(s) must not be set to + * 0(s),say when use GPIO7 as wake up pin,aGPIOIeCfg should be 0x01. + * @param ldoLevel: LDO volatge level + * @param hbnLevel: HBN work level + * + * @return None + * + *******************************************************************************/ +void ATTR_TCM_SECTION HBN_Enable(uint8_t aGPIOIeCfg, HBN_LDO_LEVEL_Type ldoLevel, HBN_LEVEL_Type hbnLevel) { + uint32_t tmpVal; + + CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); + CHECK_PARAM(IS_HBN_LEVEL_TYPE(hbnLevel)); + + /* Setting from guide */ + /* RAM Retion */ + BL_WR_REG(HBN_BASE, HBN_SRAM, 0x24); + /* AON GPIO IE */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aGPIOIeCfg); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + ///* Power off 1.8V */ + // tmpVal=BL_RD_REG(AON_BASE,AON_PMIP); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_TOPLDO11_SOC); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_TOPLDO18_RF); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_TOPLDO18_IO); + ///* SOC11 enum is not the same as VDD11*/ + // tmpVal=BL_SET_REG_BITS_VAL(tmpVal,AON_TOPLDO11_SOC_VOUT_SEL,ldoLevel-1); + // BL_WR_REG(AON_BASE,AON_PMIP,tmpVal); + // + ///* Set RT voltage */ + // tmpVal=BL_RD_REG(AON_BASE,AON); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_SW3); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_SW2); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_SW1); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_BYPASS); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_LDO18_AON); + ///* RT11 enum is not the same as VDD11*/ + // tmpVal=BL_SET_REG_BITS_VAL(tmpVal,AON_TOPLDO11_RT_VOUT_SEL,ldoLevel-1); + // tmpVal=BL_SET_REG_BITS_VAL(tmpVal,AON_VDD11_SEL,ldoLevel); + // BL_WR_REG(AON_BASE,AON,tmpVal); + + /* Select RC32M */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + + /* Set HBN flag */ + BL_WR_REG(HBN_BASE, HBN_RSV0, HBN_STATUS_ENTER_FLAG); + + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + + /* Set HBN level, (HBN_PWRDN_HBN_RAM not use) */ + switch (hbnLevel) { + case HBN_LEVEL_0: + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + case HBN_LEVEL_1: + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + case HBN_LEVEL_2: + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + case HBN_LEVEL_3: + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + default: + break; + } + + /* Set power on option:0 for por reset twice for robust 1 for reset only once*/ + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWR_ON_OPTION); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + + /* Enable HBN mode */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_MODE); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + + while (1) { + BL702_Delay_MS(1000); + } +} + +/****************************************************************************/ /** + * @brief HBN out0 IRQHandler install + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Out0_IRQHandler_Install(void) { + Interrupt_Handler_Register(HBN_OUT0_IRQn, HBN_OUT0_IRQHandler); + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief HBN out1 IRQHandler install + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Out1_IRQHandler_Install(void) { + Interrupt_Handler_Register(HBN_OUT1_IRQn, HBN_OUT1_IRQHandler); + return SUCCESS; } /*@} end of group HBN_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2s.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2s.c index b79a187200..6bca22f9aa 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2s.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2s.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_i2s.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_i2s.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_i2s.h" #include "bl702_glb.h" @@ -86,380 +86,361 @@ */ /****************************************************************************/ /** - * @brief I2S BCLK config - * - * @param i2sCfg: I2S configuration pointer - * - * @return NONE - * -*******************************************************************************/ -void I2S_SetBclkPeriod(I2S_CFG_Type *i2sCfg) -{ - uint32_t overSampleRate; - uint32_t bclkDivCnt; - uint32_t tmpVal; - - CHECK_PARAM(IS_I2S_FRAME_SIZE_TYPE(i2sCfg->frameSize)); - - overSampleRate = i2sCfg->audioFreqHz / i2sCfg->sampleFreqHz; - - switch (i2sCfg->frameSize) { - case I2S_SIZE_FRAME_8: - bclkDivCnt = overSampleRate / 16; - break; - - case I2S_SIZE_FRAME_16: - bclkDivCnt = overSampleRate / 32; - break; - - case I2S_SIZE_FRAME_24: - bclkDivCnt = overSampleRate / 48; - break; - - case I2S_SIZE_FRAME_32: - bclkDivCnt = overSampleRate / 64; - break; - - default: - bclkDivCnt = overSampleRate / 16; - break; - } - - bclkDivCnt = (bclkDivCnt / 2) - 1; - - tmpVal = (bclkDivCnt << 16) | bclkDivCnt; - BL_WR_REG(I2S_BASE, I2S_BCLK_CONFIG, tmpVal); + * @brief I2S BCLK config + * + * @param i2sCfg: I2S configuration pointer + * + * @return NONE + * + *******************************************************************************/ +void I2S_SetBclkPeriod(I2S_CFG_Type *i2sCfg) { + uint32_t overSampleRate; + uint32_t bclkDivCnt; + uint32_t tmpVal; + + CHECK_PARAM(IS_I2S_FRAME_SIZE_TYPE(i2sCfg->frameSize)); + + overSampleRate = i2sCfg->audioFreqHz / i2sCfg->sampleFreqHz; + + switch (i2sCfg->frameSize) { + case I2S_SIZE_FRAME_8: + bclkDivCnt = overSampleRate / 16; + break; + + case I2S_SIZE_FRAME_16: + bclkDivCnt = overSampleRate / 32; + break; + + case I2S_SIZE_FRAME_24: + bclkDivCnt = overSampleRate / 48; + break; + + case I2S_SIZE_FRAME_32: + bclkDivCnt = overSampleRate / 64; + break; + + default: + bclkDivCnt = overSampleRate / 16; + break; + } + + bclkDivCnt = (bclkDivCnt / 2) - 1; + + tmpVal = (bclkDivCnt << 16) | bclkDivCnt; + BL_WR_REG(I2S_BASE, I2S_BCLK_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief I2S configuration - * - * @param i2sCfg: I2S configuration pointer - * - * @return NONE - * -*******************************************************************************/ -void I2S_Init(I2S_CFG_Type *i2sCfg) -{ - uint32_t tmpVal; + * @brief I2S configuration + * + * @param i2sCfg: I2S configuration pointer + * + * @return NONE + * + *******************************************************************************/ +void I2S_Init(I2S_CFG_Type *i2sCfg) { + uint32_t tmpVal; - /* Check the parameters */ - CHECK_PARAM(IS_I2S_ENDIAN_TYPE(i2sCfg->endianType)); - CHECK_PARAM(IS_I2S_MODE_TYPE(i2sCfg->modeType)); - CHECK_PARAM(IS_I2S_FRAME_SIZE_TYPE(i2sCfg->frameSize)); - CHECK_PARAM(IS_I2S_FS_MODE_TYPE(i2sCfg->fsMode)); - CHECK_PARAM(IS_I2S_FS_CHANNEL_TYPE(i2sCfg->fsChannel)); - CHECK_PARAM(IS_I2S_DATA_SIZE_TYPE(i2sCfg->dataSize)); - CHECK_PARAM(IS_I2S_MONO_MODE_CHANNEL(i2sCfg->monoModeChannel)); + /* Check the parameters */ + CHECK_PARAM(IS_I2S_ENDIAN_TYPE(i2sCfg->endianType)); + CHECK_PARAM(IS_I2S_MODE_TYPE(i2sCfg->modeType)); + CHECK_PARAM(IS_I2S_FRAME_SIZE_TYPE(i2sCfg->frameSize)); + CHECK_PARAM(IS_I2S_FS_MODE_TYPE(i2sCfg->fsMode)); + CHECK_PARAM(IS_I2S_FS_CHANNEL_TYPE(i2sCfg->fsChannel)); + CHECK_PARAM(IS_I2S_DATA_SIZE_TYPE(i2sCfg->dataSize)); + CHECK_PARAM(IS_I2S_MONO_MODE_CHANNEL(i2sCfg->monoModeChannel)); - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_I2S); + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_I2S); - tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); + tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); - /* Set data endian*/ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_ENDIAN, i2sCfg->endianType); + /* Set data endian*/ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_ENDIAN, i2sCfg->endianType); - /* Set I2S mode */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_MODE, i2sCfg->modeType); + /* Set I2S mode */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_MODE, i2sCfg->modeType); - /* Set BCLK invert */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_BCLK_INV, i2sCfg->bclkInvert); + /* Set BCLK invert */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_BCLK_INV, i2sCfg->bclkInvert); - /* Set FS size */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FRAME_SIZE, i2sCfg->frameSize); + /* Set FS size */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FRAME_SIZE, i2sCfg->frameSize); - /* Set FS invert */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_FS_INV, i2sCfg->fsInvert); + /* Set FS invert */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_FS_INV, i2sCfg->fsInvert); - /* Set FS mode */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FS_1T_MODE, i2sCfg->fsMode); + /* Set FS mode */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FS_1T_MODE, i2sCfg->fsMode); - /* Set FS channel mode */ + /* Set FS channel mode */ - switch (i2sCfg->fsChannel) { - case I2S_FS_CHANNELS_2: - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_3CH_MODE); - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_4CH_MODE); - break; + switch (i2sCfg->fsChannel) { + case I2S_FS_CHANNELS_2: + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_3CH_MODE); + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_4CH_MODE); + break; - case I2S_FS_CHANNELS_3: - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_FS_3CH_MODE); - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_4CH_MODE); - break; + case I2S_FS_CHANNELS_3: + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_FS_3CH_MODE); + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_4CH_MODE); + break; - case I2S_FS_CHANNELS_4: - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_3CH_MODE); - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_FS_4CH_MODE); - break; + case I2S_FS_CHANNELS_4: + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_3CH_MODE); + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_FS_4CH_MODE); + break; - default: - break; - } + default: + break; + } - /* Set Data size */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_DATA_SIZE, i2sCfg->dataSize); + /* Set Data size */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_DATA_SIZE, i2sCfg->dataSize); - /* Set Data offset */ - if (i2sCfg->dataOffset != 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_OFS_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_OFS_CNT, i2sCfg->dataOffset - 1); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_OFS_EN); - } + /* Set Data offset */ + if (i2sCfg->dataOffset != 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_OFS_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_OFS_CNT, i2sCfg->dataOffset - 1); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_OFS_EN); + } - /* Set mono mode */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_MONO_MODE, i2sCfg->monoMode); + /* Set mono mode */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_MONO_MODE, i2sCfg->monoMode); - /* Set rx mono mode channel left or right */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_MONO_RX_CH, i2sCfg->monoModeChannel); + /* Set rx mono mode channel left or right */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_MONO_RX_CH, i2sCfg->monoModeChannel); - /* Clear mute mode */ - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_MUTE_MODE); + /* Clear mute mode */ + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_MUTE_MODE); - BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); + BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); - I2S_SetBclkPeriod(i2sCfg); + I2S_SetBclkPeriod(i2sCfg); } /****************************************************************************/ /** - * @brief I2S configure FIFO function - * - * @param fifoCfg: FIFO configuration structure pointer - * - * @return None - * -*******************************************************************************/ -void I2S_FifoConfig(I2S_FifoCfg_Type *fifoCfg) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_0); - /* Set packed mode */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FIFO_LR_MERGE, fifoCfg->lRMerge); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FIFO_LR_EXCHG, fifoCfg->frameDataExchange); - /* Clear tx and rx FIFO signal */ - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_RX_FIFO_CLR); - - /* Set DMA config */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_DMA_TX_EN, fifoCfg->txfifoDmaEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_DMA_RX_EN, fifoCfg->rxfifoDmaEnable); - - BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_0, tmpVal); - - /* Set CLR signal to 0*/ - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_TX_FIFO_CLR); - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_RX_FIFO_CLR); - BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_0, tmpVal); - - tmpVal = BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1); - /* Set TX and RX FIFO threshold */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_TX_FIFO_TH, fifoCfg->txFifoLevel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_RX_FIFO_TH, fifoCfg->rxFifoLevel); - - BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_1, tmpVal); + * @brief I2S configure FIFO function + * + * @param fifoCfg: FIFO configuration structure pointer + * + * @return None + * + *******************************************************************************/ +void I2S_FifoConfig(I2S_FifoCfg_Type *fifoCfg) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_0); + /* Set packed mode */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FIFO_LR_MERGE, fifoCfg->lRMerge); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FIFO_LR_EXCHG, fifoCfg->frameDataExchange); + /* Clear tx and rx FIFO signal */ + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_RX_FIFO_CLR); + + /* Set DMA config */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_DMA_TX_EN, fifoCfg->txfifoDmaEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_DMA_RX_EN, fifoCfg->rxfifoDmaEnable); + + BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_0, tmpVal); + + /* Set CLR signal to 0*/ + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_TX_FIFO_CLR); + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_RX_FIFO_CLR); + BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_0, tmpVal); + + tmpVal = BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1); + /* Set TX and RX FIFO threshold */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_TX_FIFO_TH, fifoCfg->txFifoLevel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_RX_FIFO_TH, fifoCfg->rxFifoLevel); + + BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_1, tmpVal); } /****************************************************************************/ /** - * @brief I2S configure IO function - * - * @param ioCfg: IO configuration structure pointer - * - * @return None - * -*******************************************************************************/ -void I2S_IOConfig(I2S_IOCfg_Type *ioCfg) -{ - uint32_t tmpVal; + * @brief I2S configure IO function + * + * @param ioCfg: IO configuration structure pointer + * + * @return None + * + *******************************************************************************/ +void I2S_IOConfig(I2S_IOCfg_Type *ioCfg) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(I2S_BASE, I2S_IO_CONFIG); - /* Enable or disable deglitch */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_DEG_EN, ioCfg->deglitchEn); + tmpVal = BL_RD_REG(I2S_BASE, I2S_IO_CONFIG); + /* Enable or disable deglitch */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_DEG_EN, ioCfg->deglitchEn); - /* Set deglitch cycle count */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_DEG_CNT, ioCfg->deglitchCnt); + /* Set deglitch cycle count */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_DEG_CNT, ioCfg->deglitchCnt); - /* Enable or disable inverse BCLK signal */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_BCLK_INV, ioCfg->inverseBCLK); + /* Enable or disable inverse BCLK signal */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_BCLK_INV, ioCfg->inverseBCLK); - /* Enable or disable inverse FS signal */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_FS_INV, ioCfg->inverseFS); + /* Enable or disable inverse FS signal */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_FS_INV, ioCfg->inverseFS); - /* Enable or disable inverse RX signal */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_RXD_INV, ioCfg->inverseRX); + /* Enable or disable inverse RX signal */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_RXD_INV, ioCfg->inverseRX); - /* Enable or disable inverse TX signal */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_TXD_INV, ioCfg->inverseTX); + /* Enable or disable inverse TX signal */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_TXD_INV, ioCfg->inverseTX); - BL_WR_REG(I2S_BASE, I2S_IO_CONFIG, tmpVal); + BL_WR_REG(I2S_BASE, I2S_IO_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Enable I2S - * - * @param roleType: I2S master or slave - * - * @return None - * -*******************************************************************************/ -void I2S_Enable(I2S_Role_Type roleType) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_I2S_ROLE_TYPE(roleType)); - - tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_TXD_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_RXD_EN); - - /* Set role type */ - if (I2S_ROLE_MASTER == roleType) { - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_M_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_S_EN); - } else if (I2S_ROLE_SLAVE == roleType) { - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_M_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_S_EN); - } - - BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); + * @brief Enable I2S + * + * @param roleType: I2S master or slave + * + * @return None + * + *******************************************************************************/ +void I2S_Enable(I2S_Role_Type roleType) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_I2S_ROLE_TYPE(roleType)); + + tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_TXD_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_RXD_EN); + + /* Set role type */ + if (I2S_ROLE_MASTER == roleType) { + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_M_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_S_EN); + } else if (I2S_ROLE_SLAVE == roleType) { + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_M_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_S_EN); + } + + BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Disable I2S - * - * @param None - * - * @return None - * -*******************************************************************************/ -void I2S_Disable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_TXD_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_RXD_EN); - - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_M_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_S_EN); - BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); + * @brief Disable I2S + * + * @param None + * + * @return None + * + *******************************************************************************/ +void I2S_Disable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_TXD_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_RXD_EN); + + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_M_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_S_EN); + BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief I2S read data - * - * @param None - * - * @return Data read - * -*******************************************************************************/ -uint32_t I2S_Read(void) -{ - while (0 == BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_RX_FIFO_CNT)) { - }; - - return BL_RD_REG(I2S_BASE, I2S_FIFO_RDATA); + * @brief I2S read data + * + * @param None + * + * @return Data read + * + *******************************************************************************/ +uint32_t I2S_Read(void) { + while (0 == BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_RX_FIFO_CNT)) {}; + + return BL_RD_REG(I2S_BASE, I2S_FIFO_RDATA); } /****************************************************************************/ /** - * @brief I2S write data - * - * @param data: write data - * - * @return None - * -*******************************************************************************/ -void I2S_Write(uint32_t data) -{ - while (0 == BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_TX_FIFO_CNT)) { - }; - - BL_WR_REG(I2S_BASE, I2S_FIFO_WDATA, data); + * @brief I2S write data + * + * @param data: write data + * + * @return None + * + *******************************************************************************/ +void I2S_Write(uint32_t data) { + while (0 == BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_TX_FIFO_CNT)) {}; + + BL_WR_REG(I2S_BASE, I2S_FIFO_WDATA, data); } /****************************************************************************/ /** - * @brief I2S set mute - * - * @param enabled: mute enabled or not - * - * @return None - * -*******************************************************************************/ -void I2S_Mute(BL_Fun_Type enabled) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); - - if (enabled ? 1 : 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_MUTE_MODE); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_MUTE_MODE); - } + * @brief I2S set mute + * + * @param enabled: mute enabled or not + * + * @return None + * + *******************************************************************************/ +void I2S_Mute(BL_Fun_Type enabled) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); + + if (enabled ? 1 : 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_MUTE_MODE); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_MUTE_MODE); + } - BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); + BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief I2S set 24-bit data align mode in fifo - * - * @param justType: Align mode - * - * @return None - * -*******************************************************************************/ -void I2S_SetFifoJustified(I2S_FIFO_24_Justified_Type justType) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_I2S_FIFO_24_JUSTIFIED_TYPE(justType)); - - tmpVal = BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FIFO_24B_LJ, justType); - BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_0, tmpVal); + * @brief I2S set 24-bit data align mode in fifo + * + * @param justType: Align mode + * + * @return None + * + *******************************************************************************/ +void I2S_SetFifoJustified(I2S_FIFO_24_Justified_Type justType) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_I2S_FIFO_24_JUSTIFIED_TYPE(justType)); + + tmpVal = BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FIFO_24B_LJ, justType); + BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_0, tmpVal); } /****************************************************************************/ /** - * @brief I2S flush - * - * @param None - * - * @return data count in TX FIFO - * -*******************************************************************************/ -uint32_t I2S_GetTxFIFO_AvlCnt(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_TX_FIFO_CNT); -} + * @brief I2S flush + * + * @param None + * + * @return data count in TX FIFO + * + *******************************************************************************/ +uint32_t I2S_GetTxFIFO_AvlCnt(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_TX_FIFO_CNT); } /****************************************************************************/ /** - * @brief I2S flush - * - * @param None - * - * @return data count in RX FIFO - * -*******************************************************************************/ -uint32_t I2S_GetRxFIFO_AvlCnt(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_RX_FIFO_CNT); -} + * @brief I2S flush + * + * @param None + * + * @return data count in RX FIFO + * + *******************************************************************************/ +uint32_t I2S_GetRxFIFO_AvlCnt(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_RX_FIFO_CNT); } /****************************************************************************/ /** - * @brief I2S flush - * - * @param None - * - * @return None - * -*******************************************************************************/ -void I2S_Flush(void) -{ - while (I2S_TX_FIFO_SIZE != I2S_GetTxFIFO_AvlCnt()) - ; + * @brief I2S flush + * + * @param None + * + * @return None + * + *******************************************************************************/ +void I2S_Flush(void) { + while (I2S_TX_FIFO_SIZE != I2S_GetTxFIFO_AvlCnt()) + ; } /*@} end of group I2S_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ir.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ir.c index 681f8a1c5a..e45f357209 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ir.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ir.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_ir.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_ir.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_ir.h" #include "bl702_glb.h" @@ -72,7 +72,7 @@ /** @defgroup IR_Private_Variables * @{ */ -static intCallback_Type *irIntCbfArra[IR_INT_ALL] = { NULL, NULL }; +static intCallback_Type *irIntCbfArra[IR_INT_ALL] = {NULL, NULL}; /*@} end of group IR_Private_Variables */ @@ -99,1054 +99,1025 @@ static intCallback_Type *irIntCbfArra[IR_INT_ALL] = { NULL, NULL }; */ /****************************************************************************/ /** - * @brief IR RX IRQ handler function - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief IR RX IRQ handler function + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void IRRX_IRQHandler(void) -{ - uint32_t tmpVal; +void IRRX_IRQHandler(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); + tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); - if (BL_IS_REG_BIT_SET(tmpVal, IRRX_END_INT) && !BL_IS_REG_BIT_SET(tmpVal, IR_CR_IRRX_END_MASK)) { - BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); + if (BL_IS_REG_BIT_SET(tmpVal, IRRX_END_INT) && !BL_IS_REG_BIT_SET(tmpVal, IR_CR_IRRX_END_MASK)) { + BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); - if (irIntCbfArra[IR_INT_RX] != NULL) { - irIntCbfArra[IR_INT_RX](); - } + if (irIntCbfArra[IR_INT_RX] != NULL) { + irIntCbfArra[IR_INT_RX](); } + } } #endif /****************************************************************************/ /** - * @brief IR TX IRQ handler function - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief IR TX IRQ handler function + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void IRTX_IRQHandler(void) -{ - uint32_t tmpVal; +void IRTX_IRQHandler(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); + tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); - if (BL_IS_REG_BIT_SET(tmpVal, IRTX_END_INT) && !BL_IS_REG_BIT_SET(tmpVal, IR_CR_IRTX_END_MASK)) { - BL_WR_REG(IR_BASE, IRTX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_END_CLR)); + if (BL_IS_REG_BIT_SET(tmpVal, IRTX_END_INT) && !BL_IS_REG_BIT_SET(tmpVal, IR_CR_IRTX_END_MASK)) { + BL_WR_REG(IR_BASE, IRTX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_END_CLR)); - if (irIntCbfArra[IR_INT_TX] != NULL) { - irIntCbfArra[IR_INT_TX](); - } + if (irIntCbfArra[IR_INT_TX] != NULL) { + irIntCbfArra[IR_INT_TX](); } + } } #endif /****************************************************************************/ /** - * @brief IR tx initialization function - * - * @param irTxCfg: IR tx configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_TxInit(IR_TxCfg_Type *irTxCfg) -{ - uint32_t tmpVal; - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_IRR); - - tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); - /* Set data bit */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_DATA_NUM, irTxCfg->dataBits - 1); - /* Set tail pulse */ - ENABLE == irTxCfg->tailPulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_HL_INV)); - ENABLE == irTxCfg->tailPulse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_EN)); - /* Set head pulse */ - ENABLE == irTxCfg->headPulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_HL_INV)); - ENABLE == irTxCfg->headPulse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_EN)); - /* Enable or disable logic 1 and 0 pulse inverse */ - ENABLE == irTxCfg->logic1PulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC1_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC1_HL_INV)); - ENABLE == irTxCfg->logic0PulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC0_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC0_HL_INV)); - /* Enable or disable data pulse */ - ENABLE == irTxCfg->dataPulse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_DATA_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_DATA_EN)); - /* Enable or disable output modulation */ - ENABLE == irTxCfg->outputModulation ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_MOD_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_MOD_EN)); - /* Enable or disable output inverse */ - ENABLE == irTxCfg->outputInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_OUT_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_OUT_INV)); - - /* Write back */ - BL_WR_REG(IR_BASE, IRTX_CONFIG, tmpVal); + * @brief IR tx initialization function + * + * @param irTxCfg: IR tx configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_TxInit(IR_TxCfg_Type *irTxCfg) { + uint32_t tmpVal; + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_IRR); + + tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); + /* Set data bit */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_DATA_NUM, irTxCfg->dataBits - 1); + /* Set tail pulse */ + ENABLE == irTxCfg->tailPulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_HL_INV)); + ENABLE == irTxCfg->tailPulse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_EN)); + /* Set head pulse */ + ENABLE == irTxCfg->headPulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_HL_INV)); + ENABLE == irTxCfg->headPulse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_EN)); + /* Enable or disable logic 1 and 0 pulse inverse */ + ENABLE == irTxCfg->logic1PulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC1_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC1_HL_INV)); + ENABLE == irTxCfg->logic0PulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC0_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC0_HL_INV)); + /* Enable or disable data pulse */ + ENABLE == irTxCfg->dataPulse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_DATA_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_DATA_EN)); + /* Enable or disable output modulation */ + ENABLE == irTxCfg->outputModulation ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_MOD_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_MOD_EN)); + /* Enable or disable output inverse */ + ENABLE == irTxCfg->outputInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_OUT_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_OUT_INV)); + + /* Write back */ + BL_WR_REG(IR_BASE, IRTX_CONFIG, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(IRTX_IRQn, IRTX_IRQHandler); + Interrupt_Handler_Register(IRTX_IRQn, IRTX_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief IR tx pulse width configure function - * - * @param irTxPulseWidthCfg: IR tx pulse width configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_TxPulseWidthConfig(IR_TxPulseWidthCfg_Type *irTxPulseWidthCfg) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(IR_BASE, IRTX_PW); - /* Set logic 0 pulse phase 0 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC0_PH0_W, irTxPulseWidthCfg->logic0PulseWidth_0 - 1); - /* Set logic 0 pulse phase 1 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC0_PH1_W, irTxPulseWidthCfg->logic0PulseWidth_1 - 1); - /* Set logic 1 pulse phase 0 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC1_PH0_W, irTxPulseWidthCfg->logic1PulseWidth_0 - 1); - /* Set logic 1 pulse phase 1 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC1_PH1_W, irTxPulseWidthCfg->logic1PulseWidth_1 - 1); - /* Set head pulse phase 0 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_HEAD_PH0_W, irTxPulseWidthCfg->headPulseWidth_0 - 1); - /* Set head pulse phase 1 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_HEAD_PH1_W, irTxPulseWidthCfg->headPulseWidth_1 - 1); - /* Set tail pulse phase 0 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_TAIL_PH0_W, irTxPulseWidthCfg->tailPulseWidth_0 - 1); - /* Set tail pulse phase 1 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_TAIL_PH1_W, irTxPulseWidthCfg->tailPulseWidth_1 - 1); - BL_WR_REG(IR_BASE, IRTX_PW, tmpVal); - - tmpVal = BL_RD_REG(IR_BASE, IRTX_PULSE_WIDTH); - /* Set modulation phase 0 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_MOD_PH0_W, irTxPulseWidthCfg->moduWidth_0 - 1); - /* Set modulation phase 1 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_MOD_PH1_W, irTxPulseWidthCfg->moduWidth_1 - 1); - /* Set pulse width unit */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_PW_UNIT, irTxPulseWidthCfg->pulseWidthUnit - 1); - BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, tmpVal); - - return SUCCESS; + * @brief IR tx pulse width configure function + * + * @param irTxPulseWidthCfg: IR tx pulse width configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_TxPulseWidthConfig(IR_TxPulseWidthCfg_Type *irTxPulseWidthCfg) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(IR_BASE, IRTX_PW); + /* Set logic 0 pulse phase 0 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC0_PH0_W, irTxPulseWidthCfg->logic0PulseWidth_0 - 1); + /* Set logic 0 pulse phase 1 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC0_PH1_W, irTxPulseWidthCfg->logic0PulseWidth_1 - 1); + /* Set logic 1 pulse phase 0 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC1_PH0_W, irTxPulseWidthCfg->logic1PulseWidth_0 - 1); + /* Set logic 1 pulse phase 1 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC1_PH1_W, irTxPulseWidthCfg->logic1PulseWidth_1 - 1); + /* Set head pulse phase 0 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_HEAD_PH0_W, irTxPulseWidthCfg->headPulseWidth_0 - 1); + /* Set head pulse phase 1 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_HEAD_PH1_W, irTxPulseWidthCfg->headPulseWidth_1 - 1); + /* Set tail pulse phase 0 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_TAIL_PH0_W, irTxPulseWidthCfg->tailPulseWidth_0 - 1); + /* Set tail pulse phase 1 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_TAIL_PH1_W, irTxPulseWidthCfg->tailPulseWidth_1 - 1); + BL_WR_REG(IR_BASE, IRTX_PW, tmpVal); + + tmpVal = BL_RD_REG(IR_BASE, IRTX_PULSE_WIDTH); + /* Set modulation phase 0 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_MOD_PH0_W, irTxPulseWidthCfg->moduWidth_0 - 1); + /* Set modulation phase 1 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_MOD_PH1_W, irTxPulseWidthCfg->moduWidth_1 - 1); + /* Set pulse width unit */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_PW_UNIT, irTxPulseWidthCfg->pulseWidthUnit - 1); + BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR tx software mode pulse width(multiples of pulse width unit) configure function - * - * @param irTxSWMPulseWidthCfg: IR tx software mode pulse width configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_TxSWMPulseWidthConfig(IR_TxSWMPulseWidthCfg_Type *irTxSWMPulseWidthCfg) -{ - /* Set swm pulse width,multiples of pulse width unit */ - BL_WR_REG(IR_BASE, IRTX_SWM_PW_0, irTxSWMPulseWidthCfg->swmData0); - BL_WR_REG(IR_BASE, IRTX_SWM_PW_1, irTxSWMPulseWidthCfg->swmData1); - BL_WR_REG(IR_BASE, IRTX_SWM_PW_2, irTxSWMPulseWidthCfg->swmData2); - BL_WR_REG(IR_BASE, IRTX_SWM_PW_3, irTxSWMPulseWidthCfg->swmData3); - BL_WR_REG(IR_BASE, IRTX_SWM_PW_4, irTxSWMPulseWidthCfg->swmData4); - BL_WR_REG(IR_BASE, IRTX_SWM_PW_5, irTxSWMPulseWidthCfg->swmData5); - BL_WR_REG(IR_BASE, IRTX_SWM_PW_6, irTxSWMPulseWidthCfg->swmData6); - BL_WR_REG(IR_BASE, IRTX_SWM_PW_7, irTxSWMPulseWidthCfg->swmData7); - - return SUCCESS; + * @brief IR tx software mode pulse width(multiples of pulse width unit) configure function + * + * @param irTxSWMPulseWidthCfg: IR tx software mode pulse width configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_TxSWMPulseWidthConfig(IR_TxSWMPulseWidthCfg_Type *irTxSWMPulseWidthCfg) { + /* Set swm pulse width,multiples of pulse width unit */ + BL_WR_REG(IR_BASE, IRTX_SWM_PW_0, irTxSWMPulseWidthCfg->swmData0); + BL_WR_REG(IR_BASE, IRTX_SWM_PW_1, irTxSWMPulseWidthCfg->swmData1); + BL_WR_REG(IR_BASE, IRTX_SWM_PW_2, irTxSWMPulseWidthCfg->swmData2); + BL_WR_REG(IR_BASE, IRTX_SWM_PW_3, irTxSWMPulseWidthCfg->swmData3); + BL_WR_REG(IR_BASE, IRTX_SWM_PW_4, irTxSWMPulseWidthCfg->swmData4); + BL_WR_REG(IR_BASE, IRTX_SWM_PW_5, irTxSWMPulseWidthCfg->swmData5); + BL_WR_REG(IR_BASE, IRTX_SWM_PW_6, irTxSWMPulseWidthCfg->swmData6); + BL_WR_REG(IR_BASE, IRTX_SWM_PW_7, irTxSWMPulseWidthCfg->swmData7); + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR rx initialization function - * - * @param irRxCfg: IR rx configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_RxInit(IR_RxCfg_Type *irRxCfg) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_RXMODE_TYPE(irRxCfg->rxMode)); - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_IRR); - - tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - - /* Set rx mode */ - switch (irRxCfg->rxMode) { - case IR_RX_NEC: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x0); - break; - - case IR_RX_RC5: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x1); - break; - - case IR_RX_SWM: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x2); - break; - - default: - break; - } - - /* Enable or disable input inverse */ - ENABLE == irRxCfg->inputInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_IN_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_IN_INV)); - /* Enable or disable rx input de-glitch function */ - ENABLE == irRxCfg->rxDeglitch ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_DEG_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_DEG_EN)); - /* Set de-glitch function cycle count */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_DEG_CNT, irRxCfg->DeglitchCnt); - /* Write back */ - BL_WR_REG(IR_BASE, IRRX_CONFIG, tmpVal); - - tmpVal = BL_RD_REG(IR_BASE, IRRX_PW_CONFIG); - /* Set pulse width threshold to trigger end condition */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_END_TH, irRxCfg->endThreshold - 1); - /* Set pulse width threshold for logic0/1 detection */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_DATA_TH, irRxCfg->dataThreshold - 1); - /* Write back */ - BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, tmpVal); + * @brief IR rx initialization function + * + * @param irRxCfg: IR rx configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_RxInit(IR_RxCfg_Type *irRxCfg) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_RXMODE_TYPE(irRxCfg->rxMode)); + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_IRR); + + tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); + + /* Set rx mode */ + switch (irRxCfg->rxMode) { + case IR_RX_NEC: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x0); + break; + + case IR_RX_RC5: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x1); + break; + + case IR_RX_SWM: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x2); + break; + + default: + break; + } + + /* Enable or disable input inverse */ + ENABLE == irRxCfg->inputInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_IN_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_IN_INV)); + /* Enable or disable rx input de-glitch function */ + ENABLE == irRxCfg->rxDeglitch ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_DEG_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_DEG_EN)); + /* Set de-glitch function cycle count */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_DEG_CNT, irRxCfg->DeglitchCnt); + /* Write back */ + BL_WR_REG(IR_BASE, IRRX_CONFIG, tmpVal); + + tmpVal = BL_RD_REG(IR_BASE, IRRX_PW_CONFIG); + /* Set pulse width threshold to trigger end condition */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_END_TH, irRxCfg->endThreshold - 1); + /* Set pulse width threshold for logic0/1 detection */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_DATA_TH, irRxCfg->dataThreshold - 1); + /* Write back */ + BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(IRRX_IRQn, IRRX_IRQHandler); + Interrupt_Handler_Register(IRRX_IRQn, IRRX_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief IR set default value of all registers function - * - * @param None - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_DeInit(void) -{ - GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_IRR); - - return SUCCESS; + * @brief IR set default value of all registers function + * + * @param None + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_DeInit(void) { + GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_IRR); + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR enable function - * - * @param direct: IR direction type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_Enable(IR_Direction_Type direct) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_DIRECTION_TYPE(direct)); - - if (direct == IR_TX || direct == IR_TXRX) { - /* Enable ir tx unit */ - tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); - BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_EN)); - } - - if (direct == IR_RX || direct == IR_TXRX) { - /* Enable ir rx unit */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_EN)); - } - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief IR disable function - * - * @param direct: IR direction type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_Disable(IR_Direction_Type direct) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_DIRECTION_TYPE(direct)); - - if (direct == IR_TX || direct == IR_TXRX) { - /* Disable ir tx unit */ - tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); - BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_EN)); - } + * @brief IR enable function + * + * @param direct: IR direction type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_Enable(IR_Direction_Type direct) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_DIRECTION_TYPE(direct)); + + if (direct == IR_TX || direct == IR_TXRX) { + /* Enable ir tx unit */ + tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); + BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_EN)); + } - if (direct == IR_RX || direct == IR_TXRX) { - /* Disable ir rx unit */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_EN)); - } + if (direct == IR_RX || direct == IR_TXRX) { + /* Enable ir rx unit */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); + BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_EN)); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief IR tx software mode enable or disable function - * - * @param txSWM: Enable or disable - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_TxSWM(BL_Fun_Type txSWM) -{ - uint32_t tmpVal; - - /* Enable or disable tx swm */ + * @brief IR disable function + * + * @param direct: IR direction type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_Disable(IR_Direction_Type direct) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_DIRECTION_TYPE(direct)); + + if (direct == IR_TX || direct == IR_TXRX) { + /* Disable ir tx unit */ tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); + BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_EN)); + } - if (ENABLE == txSWM) { - BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_SWM_EN)); - } else { - BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_SWM_EN)); - } + if (direct == IR_RX || direct == IR_TXRX) { + /* Disable ir rx unit */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); + BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_EN)); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief IR clear rx fifo function - * - * @param None - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_RxFIFOClear(void) -{ - uint32_t tmpVal; - - /* Clear rx fifo */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0); - BL_WR_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, IR_RX_FIFO_CLR)); - - return SUCCESS; + * @brief IR tx software mode enable or disable function + * + * @param txSWM: Enable or disable + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_TxSWM(BL_Fun_Type txSWM) { + uint32_t tmpVal; + + /* Enable or disable tx swm */ + tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); + + if (ENABLE == txSWM) { + BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_SWM_EN)); + } else { + BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_SWM_EN)); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR send data function - * - * @param irWord: IR tx data word 0 or 1 - * @param data: data to send - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_SendData(IR_Word_Type irWord, uint32_t data) -{ - /* Check the parameters */ - CHECK_PARAM(IS_IR_WORD_TYPE(irWord)); - - /* Write word 0 or word 1 */ - if (IR_WORD_0 == irWord) { - BL_WR_REG(IR_BASE, IRTX_DATA_WORD0, data); - } else { - BL_WR_REG(IR_BASE, IRTX_DATA_WORD1, data); - } - - return SUCCESS; + * @brief IR clear rx fifo function + * + * @param None + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_RxFIFOClear(void) { + uint32_t tmpVal; + + /* Clear rx fifo */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0); + BL_WR_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, IR_RX_FIFO_CLR)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR software mode send pulse width data function - * - * @param data: data to send - * @param length: Length of send buffer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_SWMSendData(uint16_t *data, uint8_t length) -{ - uint8_t i = 0, j = 0; - uint16_t minData = data[0]; - uint32_t tmpVal; - uint32_t pwVal = 0; - uint32_t count = (length + 7) / 8; - - /* Search for min value */ - for (i = 1; i < length; i++) { - if (minData > data[i] && data[i] != 0) { - minData = data[i]; - } - } - - /* Set pulse width unit */ - tmpVal = BL_RD_REG(IR_BASE, IRTX_PULSE_WIDTH); - BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_PW_UNIT, minData)); - - /* Set tx SWM pulse width data as multiples of pulse width unit */ - for (i = 0; i < count; i++) { - pwVal = 0; - - if (i < count - 1) { - for (j = 0; j < 8; j++) { - tmpVal = ((2 * data[j + i * 8] + minData) / (2 * minData) - 1) & 0xf; - pwVal |= tmpVal << (4 * j); - } - - *(volatile uint32_t *)(IR_BASE + IRTX_SWM_PW_0_OFFSET + i * 4) = pwVal; - } else { - for (j = 0; j < length % 8; j++) { - tmpVal = ((2 * data[j + i * 8] + minData) / (2 * minData) - 1) & 0xf; - pwVal |= tmpVal << (4 * j); - } - - *(volatile uint32_t *)(IR_BASE + IRTX_SWM_PW_0_OFFSET + i * 4) = pwVal; - } - } - - return SUCCESS; + * @brief IR send data function + * + * @param irWord: IR tx data word 0 or 1 + * @param data: data to send + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_SendData(IR_Word_Type irWord, uint32_t data) { + /* Check the parameters */ + CHECK_PARAM(IS_IR_WORD_TYPE(irWord)); + + /* Write word 0 or word 1 */ + if (IR_WORD_0 == irWord) { + BL_WR_REG(IR_BASE, IRTX_DATA_WORD0, data); + } else { + BL_WR_REG(IR_BASE, IRTX_DATA_WORD1, data); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR send command function - * - * @param word1: IR send data word 1 - * @param word0: IR send data word 0 - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_SendCommand(uint32_t word1, uint32_t word0) -{ - uint32_t timeoutCnt = IR_TX_INT_TIMEOUT_COUNT; + * @brief IR software mode send pulse width data function + * + * @param data: data to send + * @param length: Length of send buffer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_SWMSendData(uint16_t *data, uint8_t length) { + uint8_t i = 0, j = 0; + uint16_t minData = data[0]; + uint32_t tmpVal; + uint32_t pwVal = 0; + uint32_t count = (length + 7) / 8; + + /* Search for min value */ + for (i = 1; i < length; i++) { + if (minData > data[i] && data[i] != 0) { + minData = data[i]; + } + } - /* Write data */ - IR_SendData(IR_WORD_1, word1); - IR_SendData(IR_WORD_0, word0); + /* Set pulse width unit */ + tmpVal = BL_RD_REG(IR_BASE, IRTX_PULSE_WIDTH); + BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_PW_UNIT, minData)); - /* Mask tx interrupt */ - IR_IntMask(IR_INT_TX, MASK); + /* Set tx SWM pulse width data as multiples of pulse width unit */ + for (i = 0; i < count; i++) { + pwVal = 0; - /* Clear tx interrupt */ - IR_ClrIntStatus(IR_INT_TX); + if (i < count - 1) { + for (j = 0; j < 8; j++) { + tmpVal = ((2 * data[j + i * 8] + minData) / (2 * minData) - 1) & 0xf; + pwVal |= tmpVal << (4 * j); + } - /* Enable ir tx */ - IR_Enable(IR_TX); + *(volatile uint32_t *)(IR_BASE + IRTX_SWM_PW_0_OFFSET + i * 4) = pwVal; + } else { + for (j = 0; j < length % 8; j++) { + tmpVal = ((2 * data[j + i * 8] + minData) / (2 * minData) - 1) & 0xf; + pwVal |= tmpVal << (4 * j); + } - /* Wait for tx interrupt */ - while (SET != IR_GetIntStatus(IR_INT_TX)) { - timeoutCnt--; + *(volatile uint32_t *)(IR_BASE + IRTX_SWM_PW_0_OFFSET + i * 4) = pwVal; + } + } - if (timeoutCnt == 0) { - IR_Disable(IR_TX); + return SUCCESS; +} - return TIMEOUT; - } +/****************************************************************************/ /** + * @brief IR send command function + * + * @param word1: IR send data word 1 + * @param word0: IR send data word 0 + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_SendCommand(uint32_t word1, uint32_t word0) { + uint32_t timeoutCnt = IR_TX_INT_TIMEOUT_COUNT; + + /* Write data */ + IR_SendData(IR_WORD_1, word1); + IR_SendData(IR_WORD_0, word0); + + /* Mask tx interrupt */ + IR_IntMask(IR_INT_TX, MASK); + + /* Clear tx interrupt */ + IR_ClrIntStatus(IR_INT_TX); + + /* Enable ir tx */ + IR_Enable(IR_TX); + + /* Wait for tx interrupt */ + while (SET != IR_GetIntStatus(IR_INT_TX)) { + timeoutCnt--; + + if (timeoutCnt == 0) { + IR_Disable(IR_TX); + + return TIMEOUT; } + } - /* Disable ir tx */ - IR_Disable(IR_TX); + /* Disable ir tx */ + IR_Disable(IR_TX); - /* Clear tx interrupt */ - IR_ClrIntStatus(IR_INT_TX); + /* Clear tx interrupt */ + IR_ClrIntStatus(IR_INT_TX); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief IR send command in software mode function - * - * @param data: IR fifo data to send - * @param length: Length of data - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_SWMSendCommand(uint16_t *data, uint8_t length) -{ - uint32_t timeoutCnt = IR_TX_INT_TIMEOUT_COUNT; + * @brief IR send command in software mode function + * + * @param data: IR fifo data to send + * @param length: Length of data + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_SWMSendCommand(uint16_t *data, uint8_t length) { + uint32_t timeoutCnt = IR_TX_INT_TIMEOUT_COUNT; - /* Write fifo */ - IR_SWMSendData(data, length); + /* Write fifo */ + IR_SWMSendData(data, length); - /* Mask tx interrupt */ - IR_IntMask(IR_INT_TX, MASK); + /* Mask tx interrupt */ + IR_IntMask(IR_INT_TX, MASK); - /* Clear tx interrupt */ - IR_ClrIntStatus(IR_INT_TX); + /* Clear tx interrupt */ + IR_ClrIntStatus(IR_INT_TX); - /* Enable ir tx */ - IR_Enable(IR_TX); + /* Enable ir tx */ + IR_Enable(IR_TX); - /* Wait for tx interrupt */ - while (SET != IR_GetIntStatus(IR_INT_TX)) { - timeoutCnt--; + /* Wait for tx interrupt */ + while (SET != IR_GetIntStatus(IR_INT_TX)) { + timeoutCnt--; - if (timeoutCnt == 0) { - IR_Disable(IR_TX); + if (timeoutCnt == 0) { + IR_Disable(IR_TX); - return TIMEOUT; - } + return TIMEOUT; } + } - /* Disable ir tx */ - IR_Disable(IR_TX); + /* Disable ir tx */ + IR_Disable(IR_TX); - /* Clear tx interrupt */ - IR_ClrIntStatus(IR_INT_TX); + /* Clear tx interrupt */ + IR_ClrIntStatus(IR_INT_TX); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief IR send in NEC protocol - * - * @param address: Address - * @param command: Command - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_SendNEC(uint8_t address, uint8_t command) -{ - uint32_t tmpVal = ((~command & 0xff) << 24) + (command << 16) + ((~address & 0xff) << 8) + address; - - IR_SendCommand(0, tmpVal); - - return SUCCESS; + * @brief IR send in NEC protocol + * + * @param address: Address + * @param command: Command + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_SendNEC(uint8_t address, uint8_t command) { + uint32_t tmpVal = ((~command & 0xff) << 24) + (command << 16) + ((~address & 0xff) << 8) + address; + + IR_SendCommand(0, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR interrupt mask or unmask function - * - * @param intType: IR interrupt type - * @param intMask: Mask or unmask - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_IntMask(IR_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_INT_TYPE(intType)); - - if (intType == IR_INT_TX || intType == IR_INT_ALL) { - /* Mask or unmask tx interrupt */ - tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); - BL_WR_REG(IR_BASE, IRTX_INT_STS, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_END_MASK, intMask)); - } + * @brief IR interrupt mask or unmask function + * + * @param intType: IR interrupt type + * @param intMask: Mask or unmask + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_IntMask(IR_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_INT_TYPE(intType)); + + if (intType == IR_INT_TX || intType == IR_INT_ALL) { + /* Mask or unmask tx interrupt */ + tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); + BL_WR_REG(IR_BASE, IRTX_INT_STS, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_END_MASK, intMask)); + } - if (intType == IR_INT_RX || intType == IR_INT_ALL) { - /* Mask or unmask rx interrupt */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); - BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_END_MASK, intMask)); - } + if (intType == IR_INT_RX || intType == IR_INT_ALL) { + /* Mask or unmask rx interrupt */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); + BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_END_MASK, intMask)); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Clear ir interrupt function - * - * @param intType: IR interrupt type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_ClrIntStatus(IR_INT_Type intType) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_INT_TYPE(intType)); - - if (intType == IR_INT_TX || intType == IR_INT_ALL) { - /* Clear tx interrupt */ - tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); - BL_WR_REG(IR_BASE, IRTX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_END_CLR)); - } + * @brief Clear ir interrupt function + * + * @param intType: IR interrupt type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_ClrIntStatus(IR_INT_Type intType) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_INT_TYPE(intType)); + + if (intType == IR_INT_TX || intType == IR_INT_ALL) { + /* Clear tx interrupt */ + tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); + BL_WR_REG(IR_BASE, IRTX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_END_CLR)); + } - if (intType == IR_INT_RX || intType == IR_INT_ALL) { - /* Clear rx interrupt */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); - BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); - } + if (intType == IR_INT_RX || intType == IR_INT_ALL) { + /* Clear rx interrupt */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); + BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief IR install interrupt callback function - * - * @param intType: IR interrupt type - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_Int_Callback_Install(IR_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_IR_INT_TYPE(intType)); - - irIntCbfArra[intType] = cbFun; - - return SUCCESS; + * @brief IR install interrupt callback function + * + * @param intType: IR interrupt type + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_Int_Callback_Install(IR_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_IR_INT_TYPE(intType)); + + irIntCbfArra[intType] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR get interrupt status function - * - * @param intType: IR int type - * - * @return IR tx or rx interrupt status - * -*******************************************************************************/ -BL_Sts_Type IR_GetIntStatus(IR_INT_Type intType) -{ - uint32_t tmpVal = 0; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_INT_TYPE(intType)); - - /* Read tx or rx interrupt status */ - if (IR_INT_TX == intType) { - tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IRTX_END_INT); - } else if (IR_INT_RX == intType) { - tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IRRX_END_INT); - } - - if (tmpVal) { - return SET; - } else { - return RESET; - } + * @brief IR get interrupt status function + * + * @param intType: IR int type + * + * @return IR tx or rx interrupt status + * + *******************************************************************************/ +BL_Sts_Type IR_GetIntStatus(IR_INT_Type intType) { + uint32_t tmpVal = 0; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_INT_TYPE(intType)); + + /* Read tx or rx interrupt status */ + if (IR_INT_TX == intType) { + tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IRTX_END_INT); + } else if (IR_INT_RX == intType) { + tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IRRX_END_INT); + } + + if (tmpVal) { + return SET; + } else { + return RESET; + } } /****************************************************************************/ /** - * @brief IR get rx fifo underflow or overflow status function - * - * @param fifoSts: IR fifo status type - * - * @return IR rx fifo status - * -*******************************************************************************/ -BL_Sts_Type IR_GetRxFIFOStatus(IR_FifoStatus_Type fifoSts) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_FIFOSTATUS_TYPE(fifoSts)); - - /* Read rx fifo status */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0); - - if (fifoSts == IR_RX_FIFO_UNDERFLOW) { - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_RX_FIFO_UNDERFLOW); - } else { - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_RX_FIFO_OVERFLOW); - } - - if (tmpVal) { - return SET; - } else { - return RESET; - } + * @brief IR get rx fifo underflow or overflow status function + * + * @param fifoSts: IR fifo status type + * + * @return IR rx fifo status + * + *******************************************************************************/ +BL_Sts_Type IR_GetRxFIFOStatus(IR_FifoStatus_Type fifoSts) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_FIFOSTATUS_TYPE(fifoSts)); + + /* Read rx fifo status */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0); + + if (fifoSts == IR_RX_FIFO_UNDERFLOW) { + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_RX_FIFO_UNDERFLOW); + } else { + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_RX_FIFO_OVERFLOW); + } + + if (tmpVal) { + return SET; + } else { + return RESET; + } } /****************************************************************************/ /** - * @brief IR receive data function - * - * @param irWord: IR rx data word 0 or 1 - * - * @return Data received - * -*******************************************************************************/ -uint32_t IR_ReceiveData(IR_Word_Type irWord) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_WORD_TYPE(irWord)); - - /* Read word 0 or word 1 */ - if (IR_WORD_0 == irWord) { - tmpVal = BL_RD_REG(IR_BASE, IRRX_DATA_WORD0); - } else { - tmpVal = BL_RD_REG(IR_BASE, IRRX_DATA_WORD1); - } - - return tmpVal; + * @brief IR receive data function + * + * @param irWord: IR rx data word 0 or 1 + * + * @return Data received + * + *******************************************************************************/ +uint32_t IR_ReceiveData(IR_Word_Type irWord) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_WORD_TYPE(irWord)); + + /* Read word 0 or word 1 */ + if (IR_WORD_0 == irWord) { + tmpVal = BL_RD_REG(IR_BASE, IRRX_DATA_WORD0); + } else { + tmpVal = BL_RD_REG(IR_BASE, IRRX_DATA_WORD1); + } + + return tmpVal; } /****************************************************************************/ /** - * @brief IR software mode receive pulse width data function - * - * @param data: Data received - * @param length: Max length of receive buffer - * - * @return Length of datas received - * -*******************************************************************************/ -uint8_t IR_SWMReceiveData(uint16_t *data, uint8_t length) -{ - uint8_t rxLen = 0; - - while (rxLen < length && IR_GetRxFIFOCount() > 0) { - /* Read data */ - data[rxLen++] = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_RDATA) & 0xffff; - } - - return rxLen; + * @brief IR software mode receive pulse width data function + * + * @param data: Data received + * @param length: Max length of receive buffer + * + * @return Length of datas received + * + *******************************************************************************/ +uint8_t IR_SWMReceiveData(uint16_t *data, uint8_t length) { + uint8_t rxLen = 0; + + while (rxLen < length && IR_GetRxFIFOCount() > 0) { + /* Read data */ + data[rxLen++] = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_RDATA) & 0xffff; + } + + return rxLen; } /****************************************************************************/ /** - * @brief IR receive in NEC protocol - * - * @param address: Address - * @param command: Command - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type IR_ReceiveNEC(uint8_t *address, uint8_t *command) -{ - uint32_t tmpVal = IR_ReceiveData(IR_WORD_0); - - *address = tmpVal & 0xff; - *command = (tmpVal >> 16) & 0xff; - - if ((~(*address) & 0xff) != ((tmpVal >> 8) & 0xff) || (~(*command) & 0xff) != ((tmpVal >> 24) & 0xff)) { - return ERROR; - } - - return SUCCESS; + * @brief IR receive in NEC protocol + * + * @param address: Address + * @param command: Command + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type IR_ReceiveNEC(uint8_t *address, uint8_t *command) { + uint32_t tmpVal = IR_ReceiveData(IR_WORD_0); + + *address = tmpVal & 0xff; + *command = (tmpVal >> 16) & 0xff; + + if ((~(*address) & 0xff) != ((tmpVal >> 8) & 0xff) || (~(*command) & 0xff) != ((tmpVal >> 24) & 0xff)) { + return ERROR; + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR get rx data bit count function - * - * @param None - * - * @return IR rx data bit count - * -*******************************************************************************/ -uint8_t IR_GetRxDataBitCount(void) -{ - uint32_t tmpVal; - - /* Read rx data bit count */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_DATA_COUNT); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_STS_IRRX_DATA_CNT); - - return tmpVal; + * @brief IR get rx data bit count function + * + * @param None + * + * @return IR rx data bit count + * + *******************************************************************************/ +uint8_t IR_GetRxDataBitCount(void) { + uint32_t tmpVal; + + /* Read rx data bit count */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_DATA_COUNT); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_STS_IRRX_DATA_CNT); + + return tmpVal; } /****************************************************************************/ /** - * @brief IR get rx fifo count function - * - * @param None - * - * @return IR rx fifo available count - * -*******************************************************************************/ -uint8_t IR_GetRxFIFOCount(void) -{ - uint32_t tmpVal; - - /* Read rx fifo count */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_RX_FIFO_CNT); - - return tmpVal; + * @brief IR get rx fifo count function + * + * @param None + * + * @return IR rx fifo available count + * + *******************************************************************************/ +uint8_t IR_GetRxFIFOCount(void) { + uint32_t tmpVal; + + /* Read rx fifo count */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_RX_FIFO_CNT); + + return tmpVal; } /****************************************************************************/ /** - * @brief IR learning to set rx and tx mode function - * - * @param data: Buffer to save data - * @param length: Length of data - * - * @return Protocol type - * -*******************************************************************************/ -IR_RxMode_Type IR_LearnToInit(uint32_t *data, uint8_t *length) -{ - uint32_t tmpVal; - uint32_t timeoutCnt = IR_RX_INT_TIMEOUT_COUNT; + * @brief IR learning to set rx and tx mode function + * + * @param data: Buffer to save data + * @param length: Length of data + * + * @return Protocol type + * + *******************************************************************************/ +IR_RxMode_Type IR_LearnToInit(uint32_t *data, uint8_t *length) { + uint32_t tmpVal; + uint32_t timeoutCnt = IR_RX_INT_TIMEOUT_COUNT; + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_IRR); + + /* Disable rx,set rx in software mode and enable rx input inverse */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x2); + tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_IN_INV); + BL_WR_REG(IR_BASE, IRRX_CONFIG, tmpVal); + /* Set pulse width threshold to trigger end condition */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_PW_CONFIG); + BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_END_TH, 19999)); + + /* Clear and mask rx interrupt */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); + tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_MASK); + BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); + + /* Enable rx */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); + BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_EN)); + + /* Wait for rx interrupt */ + while (SET != IR_GetIntStatus(IR_INT_RX)) { + timeoutCnt--; + + if (timeoutCnt == 0) { + IR_Disable(IR_RX); + + return IR_RX_SWM; + } + } - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_IRR); + /* Disable rx */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); + BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_EN)); - /* Disable rx,set rx in software mode and enable rx input inverse */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x2); - tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_IN_INV); - BL_WR_REG(IR_BASE, IRRX_CONFIG, tmpVal); - /* Set pulse width threshold to trigger end condition */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_PW_CONFIG); - BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_END_TH, 19999)); + /* Clear rx interrupt */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); + BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); - /* Clear and mask rx interrupt */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); - tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_MASK); - BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); + /*Receive data */ + *length = IR_GetRxFIFOCount(); + *length = IR_SWMReceiveData((uint16_t *)data, *length); - /* Enable rx */ + /* Judge protocol type */ + if (NEC_HEAD_H_MIN < (data[0] & 0xffff) && (data[0] & 0xffff) < NEC_HEAD_H_MAX && NEC_HEAD_L_MIN < (data[0] >> 16) && (data[0] >> 16) < NEC_HEAD_L_MAX && NEC_BIT0_H_MIN < (data[1] & 0xffff) + && (data[1] & 0xffff) < NEC_BIT0_H_MAX) { + /* Set rx in NEC mode */ tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_EN)); - - /* Wait for rx interrupt */ - while (SET != IR_GetIntStatus(IR_INT_RX)) { - timeoutCnt--; - - if (timeoutCnt == 0) { - IR_Disable(IR_RX); - - return IR_RX_SWM; - } - } - - /* Disable rx */ + BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x0)); + /* Set pulse width threshold to trigger end condition and pulse width threshold for logic0/1 detection */ + BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, 0x23270d47); + /* Set tx in NEC mode */ + /* Tx configure */ + BL_WR_REG(IR_BASE, IRTX_CONFIG, 0x1f514); + /* Set logic 0,logic 1,head and tail pulse width */ + BL_WR_REG(IR_BASE, IRTX_PW, 0x7f2000); + /* Set modulation phase width and pulse width unit */ + BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, 0x22110464); + + return IR_RX_NEC; + } else if (RC5_ONE_PLUSE_MIN < (data[0] & 0xffff) && (data[0] & 0xffff) < RC5_ONE_PLUSE_MAX + && ((RC5_ONE_PLUSE_MIN < (data[0] >> 16) && (data[0] >> 16) < RC5_ONE_PLUSE_MAX) || (RC5_TWO_PLUSE_MIN < (data[0] >> 16) && (data[0] >> 16) < RC5_TWO_PLUSE_MAX)) + && ((RC5_ONE_PLUSE_MIN < (data[1] & 0xffff) && (data[1] & 0xffff) < RC5_ONE_PLUSE_MAX) || (RC5_TWO_PLUSE_MIN < (data[1] & 0xffff) && (data[1] & 0xffff) < RC5_TWO_PLUSE_MAX))) { + /* Set rx in RC-5 mode */ tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_EN)); - - /* Clear rx interrupt */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); - BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); + BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x1)); + /* Set pulse width threshold to trigger end condition and pulse width threshold for logic0/1 detection */ + BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, 0x13870a6a); + /* Set tx in RC-5 mode */ + /* Tx configure */ + BL_WR_REG(IR_BASE, IRTX_CONFIG, 0xc134); + /* Set logic 0,logic 1,head and tail pulse width */ + BL_WR_REG(IR_BASE, IRTX_PW, 0); + /* Set modulation phase width and pulse width unit */ + BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, 0x221106f1); + + return IR_RX_RC5; + } else if ((data[0] >> 16) != 0) { + /* Set tx in software mode */ + /* Tx configure */ + BL_WR_REG(IR_BASE, IRTX_CONFIG, *length << 12 | 0xc); + /* Set modulation phase width */ + BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, 0x22110000); + + return IR_RX_SWM; + } else { + tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE); - /*Receive data */ - *length = IR_GetRxFIFOCount(); - *length = IR_SWMReceiveData((uint16_t *)data, *length); - - /* Judge protocol type */ - if (NEC_HEAD_H_MIN < (data[0] & 0xffff) && (data[0] & 0xffff) < NEC_HEAD_H_MAX && NEC_HEAD_L_MIN < (data[0] >> 16) && (data[0] >> 16) < NEC_HEAD_L_MAX && NEC_BIT0_H_MIN < (data[1] & 0xffff) && (data[1] & 0xffff) < NEC_BIT0_H_MAX) { - /* Set rx in NEC mode */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x0)); - /* Set pulse width threshold to trigger end condition and pulse width threshold for logic0/1 detection */ - BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, 0x23270d47); - /* Set tx in NEC mode */ - /* Tx configure */ - BL_WR_REG(IR_BASE, IRTX_CONFIG, 0x1f514); - /* Set logic 0,logic 1,head and tail pulse width */ - BL_WR_REG(IR_BASE, IRTX_PW, 0x7f2000); - /* Set modulation phase width and pulse width unit */ - BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, 0x22110464); - - return IR_RX_NEC; - } else if (RC5_ONE_PLUSE_MIN < (data[0] & 0xffff) && (data[0] & 0xffff) < RC5_ONE_PLUSE_MAX && ((RC5_ONE_PLUSE_MIN < (data[0] >> 16) && (data[0] >> 16) < RC5_ONE_PLUSE_MAX) || (RC5_TWO_PLUSE_MIN < (data[0] >> 16) && (data[0] >> 16) < RC5_TWO_PLUSE_MAX)) && - ((RC5_ONE_PLUSE_MIN < (data[1] & 0xffff) && (data[1] & 0xffff) < RC5_ONE_PLUSE_MAX) || (RC5_TWO_PLUSE_MIN < (data[1] & 0xffff) && (data[1] & 0xffff) < RC5_TWO_PLUSE_MAX))) { - /* Set rx in RC-5 mode */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x1)); - /* Set pulse width threshold to trigger end condition and pulse width threshold for logic0/1 detection */ - BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, 0x13870a6a); - /* Set tx in RC-5 mode */ - /* Tx configure */ - BL_WR_REG(IR_BASE, IRTX_CONFIG, 0xc134); - /* Set logic 0,logic 1,head and tail pulse width */ - BL_WR_REG(IR_BASE, IRTX_PW, 0); - /* Set modulation phase width and pulse width unit */ - BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, 0x221106f1); - - return IR_RX_RC5; - } else if ((data[0] >> 16) != 0) { - /* Set tx in software mode */ - /* Tx configure */ - BL_WR_REG(IR_BASE, IRTX_CONFIG, *length << 12 | 0xc); - /* Set modulation phase width */ - BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, 0x22110000); - - return IR_RX_SWM; + if (tmpVal == 0) { + return IR_RX_NEC; + } else if (tmpVal == 1) { + return IR_RX_RC5; } else { - tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE); - - if (tmpVal == 0) { - return IR_RX_NEC; - } else if (tmpVal == 1) { - return IR_RX_RC5; - } else { - return IR_RX_SWM; - } + return IR_RX_SWM; } + } } /****************************************************************************/ /** - * @brief IR receive data according to mode which is learned function - * - * @param mode: Protocol type - * @param data: Buffer to save data - * - * @return Length of data - * -*******************************************************************************/ -uint8_t IR_LearnToReceive(IR_RxMode_Type mode, uint32_t *data) -{ - uint8_t length = 0; - uint32_t timeoutCnt = IR_RX_INT_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_RXMODE_TYPE(mode)); - - /* Disable ir rx */ - IR_Disable(IR_RX); - - /* Clear and mask rx interrupt */ - IR_ClrIntStatus(IR_INT_RX); - IR_IntMask(IR_INT_RX, MASK); - - /* Enable ir rx */ - IR_Enable(IR_RX); - - /* Wait for rx interrupt */ - while (SET != IR_GetIntStatus(IR_INT_RX)) { - timeoutCnt--; - - if (timeoutCnt == 0) { - IR_Disable(IR_RX); - - return TIMEOUT; - } - } - - /* Disable ir rx */ - IR_Disable(IR_RX); - - /* Clear rx interrupt */ - IR_ClrIntStatus(IR_INT_RX); - - /* Receive data according to mode */ - if (mode == IR_RX_NEC || mode == IR_RX_RC5) { - /* Get data bit count */ - length = IR_GetRxDataBitCount(); - data[0] = IR_ReceiveData(IR_WORD_0); - } else { - /* Get fifo count */ - length = IR_GetRxFIFOCount(); - length = IR_SWMReceiveData((uint16_t *)data, length); + * @brief IR receive data according to mode which is learned function + * + * @param mode: Protocol type + * @param data: Buffer to save data + * + * @return Length of data + * + *******************************************************************************/ +uint8_t IR_LearnToReceive(IR_RxMode_Type mode, uint32_t *data) { + uint8_t length = 0; + uint32_t timeoutCnt = IR_RX_INT_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_RXMODE_TYPE(mode)); + + /* Disable ir rx */ + IR_Disable(IR_RX); + + /* Clear and mask rx interrupt */ + IR_ClrIntStatus(IR_INT_RX); + IR_IntMask(IR_INT_RX, MASK); + + /* Enable ir rx */ + IR_Enable(IR_RX); + + /* Wait for rx interrupt */ + while (SET != IR_GetIntStatus(IR_INT_RX)) { + timeoutCnt--; + + if (timeoutCnt == 0) { + IR_Disable(IR_RX); + + return TIMEOUT; } - - return length; + } + + /* Disable ir rx */ + IR_Disable(IR_RX); + + /* Clear rx interrupt */ + IR_ClrIntStatus(IR_INT_RX); + + /* Receive data according to mode */ + if (mode == IR_RX_NEC || mode == IR_RX_RC5) { + /* Get data bit count */ + length = IR_GetRxDataBitCount(); + data[0] = IR_ReceiveData(IR_WORD_0); + } else { + /* Get fifo count */ + length = IR_GetRxFIFOCount(); + length = IR_SWMReceiveData((uint16_t *)data, length); + } + + return length; } /****************************************************************************/ /** - * @brief IR send data according to mode which is learned function - * - * @param mode: Protocol type - * @param data: Buffer of data to send - * @param length: Length of data - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_LearnToSend(IR_RxMode_Type mode, uint32_t *data, uint8_t length) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_RXMODE_TYPE(mode)); - - /* Set send length */ - tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_DATA_NUM, length - 1); - BL_WR_REG(IR_BASE, IRTX_CONFIG, tmpVal); - - if (mode == IR_RX_NEC || mode == IR_RX_RC5) { - IR_SendCommand(0, data[0]); - } else { - IR_SWMSendCommand((uint16_t *)data, length); - } - - return SUCCESS; + * @brief IR send data according to mode which is learned function + * + * @param mode: Protocol type + * @param data: Buffer of data to send + * @param length: Length of data + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_LearnToSend(IR_RxMode_Type mode, uint32_t *data, uint8_t length) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_RXMODE_TYPE(mode)); + + /* Set send length */ + tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_DATA_NUM, length - 1); + BL_WR_REG(IR_BASE, IRTX_CONFIG, tmpVal); + + if (mode == IR_RX_NEC || mode == IR_RX_RC5) { + IR_SendCommand(0, data[0]); + } else { + IR_SWMSendCommand((uint16_t *)data, length); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR init to control led function - * - * @param clk: Clock source - * @param div: Clock division(1~64) - * @param unit: Pulse width unit(multiples of clock pulse width, 1~4096) - * @param code0H: code 0 high level time(multiples of pulse width unit, 1~16) - * @param code0L: code 0 low level time(multiples of pulse width unit, 1~16) - * @param code1H: code 1 high level time(multiples of pulse width unit, 1~16) - * @param code1L: code 1 low level time(multiples of pulse width unit, 1~16) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_LEDInit(HBN_XCLK_CLK_Type clk, uint8_t div, uint8_t unit, uint8_t code0H, uint8_t code0L, uint8_t code1H, uint8_t code1L) -{ - IR_TxCfg_Type txCfg = { - 24, /* 24-bit data */ - DISABLE, /* Disable signal of tail pulse inverse */ - DISABLE, /* Disable signal of tail pulse */ - DISABLE, /* Disable signal of head pulse inverse */ - DISABLE, /* Disable signal of head pulse */ - DISABLE, /* Disable signal of logic 1 pulse inverse */ - DISABLE, /* Disable signal of logic 0 pulse inverse */ - ENABLE, /* Enable signal of data pulse */ - DISABLE, /* Disable signal of output modulation */ - ENABLE /* Enable signal of output inverse */ - }; - - IR_TxPulseWidthCfg_Type txPWCfg = { - code0L, /* Pulse width of logic 0 pulse phase 1 */ - code0H, /* Pulse width of logic 0 pulse phase 0 */ - code1L, /* Pulse width of logic 1 pulse phase 1 */ - code1H, /* Pulse width of logic 1 pulse phase 0 */ - 1, /* Pulse width of head pulse phase 1 */ - 1, /* Pulse width of head pulse phase 0 */ - 1, /* Pulse width of tail pulse phase 1 */ - 1, /* Pulse width of tail pulse phase 0 */ - 1, /* Modulation phase 1 width */ - 1, /* Modulation phase 0 width */ - unit /* Pulse width unit */ - }; - - HBN_Set_XCLK_CLK_Sel(clk); - GLB_Set_IR_CLK(ENABLE, GLB_IR_CLK_SRC_XCLK, div - 1); - - /* Disable ir before config */ - IR_Disable(IR_TXRX); - - /* IR tx init */ - IR_TxInit(&txCfg); - IR_TxPulseWidthConfig(&txPWCfg); - - return SUCCESS; + * @brief IR init to control led function + * + * @param clk: Clock source + * @param div: Clock division(1~64) + * @param unit: Pulse width unit(multiples of clock pulse width, 1~4096) + * @param code0H: code 0 high level time(multiples of pulse width unit, 1~16) + * @param code0L: code 0 low level time(multiples of pulse width unit, 1~16) + * @param code1H: code 1 high level time(multiples of pulse width unit, 1~16) + * @param code1L: code 1 low level time(multiples of pulse width unit, 1~16) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_LEDInit(HBN_XCLK_CLK_Type clk, uint8_t div, uint8_t unit, uint8_t code0H, uint8_t code0L, uint8_t code1H, uint8_t code1L) { + IR_TxCfg_Type txCfg = { + 24, /* 24-bit data */ + DISABLE, /* Disable signal of tail pulse inverse */ + DISABLE, /* Disable signal of tail pulse */ + DISABLE, /* Disable signal of head pulse inverse */ + DISABLE, /* Disable signal of head pulse */ + DISABLE, /* Disable signal of logic 1 pulse inverse */ + DISABLE, /* Disable signal of logic 0 pulse inverse */ + ENABLE, /* Enable signal of data pulse */ + DISABLE, /* Disable signal of output modulation */ + ENABLE /* Enable signal of output inverse */ + }; + + IR_TxPulseWidthCfg_Type txPWCfg = { + code0L, /* Pulse width of logic 0 pulse phase 1 */ + code0H, /* Pulse width of logic 0 pulse phase 0 */ + code1L, /* Pulse width of logic 1 pulse phase 1 */ + code1H, /* Pulse width of logic 1 pulse phase 0 */ + 1, /* Pulse width of head pulse phase 1 */ + 1, /* Pulse width of head pulse phase 0 */ + 1, /* Pulse width of tail pulse phase 1 */ + 1, /* Pulse width of tail pulse phase 0 */ + 1, /* Modulation phase 1 width */ + 1, /* Modulation phase 0 width */ + unit /* Pulse width unit */ + }; + + HBN_Set_XCLK_CLK_Sel(clk); + GLB_Set_IR_CLK(ENABLE, GLB_IR_CLK_SRC_XCLK, div - 1); + + /* Disable ir before config */ + IR_Disable(IR_TXRX); + + /* IR tx init */ + IR_TxInit(&txCfg); + IR_TxPulseWidthConfig(&txPWCfg); + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR send 24-bit data to control led function - * - * @param data: Data to send(24-bit) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_LEDSend(uint32_t data) -{ - /* Change MSB_first to LSB_first */ - data = ((data >> 1) & 0x55555555) | ((data << 1) & 0xaaaaaaaa); - data = ((data >> 2) & 0x33333333) | ((data << 2) & 0xcccccccc); - data = ((data >> 4) & 0x0f0f0f0f) | ((data << 4) & 0xf0f0f0f0); - data = ((data >> 16) & 0xff) | (data & 0xff00) | ((data << 16) & 0xff0000); - IR_SendCommand(0, data); - - return SUCCESS; + * @brief IR send 24-bit data to control led function + * + * @param data: Data to send(24-bit) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_LEDSend(uint32_t data) { + /* Change MSB_first to LSB_first */ + data = ((data >> 1) & 0x55555555) | ((data << 1) & 0xaaaaaaaa); + data = ((data >> 2) & 0x33333333) | ((data << 2) & 0xcccccccc); + data = ((data >> 4) & 0x0f0f0f0f) | ((data << 4) & 0xf0f0f0f0); + data = ((data >> 16) & 0xff) | (data & 0xff00) | ((data << 16) & 0xff0000); + IR_SendCommand(0, data); + + return SUCCESS; } /*@} end of group IR_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_kys.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_kys.c index 45ca6a29dd..a96962200c 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_kys.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_kys.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_kys.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_kys.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_kys.h" @@ -59,7 +59,7 @@ /** @defgroup KYS_Private_Variables * @{ */ -static intCallback_Type *KYSIntCbfArra[1] = { NULL }; +static intCallback_Type *KYSIntCbfArra[1] = {NULL}; /*@} end of group KYS_Private_Variables */ @@ -86,185 +86,174 @@ static intCallback_Type *KYSIntCbfArra[1] = { NULL }; */ /****************************************************************************/ /** - * @brief KYS interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief KYS interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void KYS_IRQHandler(void) -{ - if (KYSIntCbfArra[0] != NULL) { - KYSIntCbfArra[0](); - } +void KYS_IRQHandler(void) { + if (KYSIntCbfArra[0] != NULL) { + KYSIntCbfArra[0](); + } } #endif /****************************************************************************/ /** - * @brief KYS initialization function - * - * @param kysCfg: KYS configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type KYS_Init(KYS_CFG_Type *kysCfg) -{ - uint32_t tmpVal; + * @brief KYS initialization function + * + * @param kysCfg: KYS configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type KYS_Init(KYS_CFG_Type *kysCfg) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); - /* Set col and row */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_COL_NUM, kysCfg->col - 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_ROW_NUM, kysCfg->row - 1); + tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); + /* Set col and row */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_COL_NUM, kysCfg->col - 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_ROW_NUM, kysCfg->row - 1); - /* Set idle duration between column scans */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_RC_EXT, kysCfg->idleDuration); + /* Set idle duration between column scans */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_RC_EXT, kysCfg->idleDuration); - /* Enable or disable ghost key event detection */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_GHOST_EN, kysCfg->ghostEn); + /* Enable or disable ghost key event detection */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_GHOST_EN, kysCfg->ghostEn); - /* Enable or disable deglitch function */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_DEG_EN, kysCfg->deglitchEn); + /* Enable or disable deglitch function */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_DEG_EN, kysCfg->deglitchEn); - /* Set deglitch count */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_DEG_CNT, kysCfg->deglitchCnt); + /* Set deglitch count */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_DEG_CNT, kysCfg->deglitchCnt); - /* Write back */ - BL_WR_REG(KYS_BASE, KYS_KS_CTRL, tmpVal); + /* Write back */ + BL_WR_REG(KYS_BASE, KYS_KS_CTRL, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(KYS_IRQn, KYS_IRQHandler); + Interrupt_Handler_Register(KYS_IRQn, KYS_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Enable KYS - * - * @param None - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type KYS_Enable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); - BL_WR_REG(KYS_BASE, KYS_KS_CTRL, BL_SET_REG_BIT(tmpVal, KYS_KS_EN)); - - return SUCCESS; + * @brief Enable KYS + * + * @param None + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type KYS_Enable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); + BL_WR_REG(KYS_BASE, KYS_KS_CTRL, BL_SET_REG_BIT(tmpVal, KYS_KS_EN)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Disable KYS - * - * @param None - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type KYS_Disable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); - BL_WR_REG(KYS_BASE, KYS_KS_CTRL, BL_CLR_REG_BIT(tmpVal, KYS_KS_EN)); - - return SUCCESS; + * @brief Disable KYS + * + * @param None + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type KYS_Disable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); + BL_WR_REG(KYS_BASE, KYS_KS_CTRL, BL_CLR_REG_BIT(tmpVal, KYS_KS_EN)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief KYS mask or unmask interrupt - * - * @param intMask: KYS interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type KYS_IntMask(BL_Mask_Type intMask) -{ - if (MASK == intMask) { - BL_WR_REG(KYS_BASE, KYS_KS_INT_EN, 0); - } else { - BL_WR_REG(KYS_BASE, KYS_KS_INT_EN, 1); - } - - return SUCCESS; + * @brief KYS mask or unmask interrupt + * + * @param intMask: KYS interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type KYS_IntMask(BL_Mask_Type intMask) { + if (MASK == intMask) { + BL_WR_REG(KYS_BASE, KYS_KS_INT_EN, 0); + } else { + BL_WR_REG(KYS_BASE, KYS_KS_INT_EN, 1); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief KYS clear interrupt - * - * @param None - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type KYS_IntClear(void) -{ - BL_WR_REG(KYS_BASE, KYS_KEYCODE_CLR, 0xf); - - return SUCCESS; + * @brief KYS clear interrupt + * + * @param None + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type KYS_IntClear(void) { + BL_WR_REG(KYS_BASE, KYS_KEYCODE_CLR, 0xf); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Install KYS interrupt callback function - * - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type KYS_Int_Callback_Install(intCallback_Type *cbFun) -{ - KYSIntCbfArra[0] = cbFun; - - return SUCCESS; + * @brief Install KYS interrupt callback function + * + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type KYS_Int_Callback_Install(intCallback_Type *cbFun) { + KYSIntCbfArra[0] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief KYS get interrupt status - * - * @param None - * - * @return Status of interrupt - * -*******************************************************************************/ -uint8_t KYS_GetIntStatus(void) -{ - return BL_RD_REG(KYS_BASE, KYS_KS_INT_STS) & 0xf; -} + * @brief KYS get interrupt status + * + * @param None + * + * @return Status of interrupt + * + *******************************************************************************/ +uint8_t KYS_GetIntStatus(void) { return BL_RD_REG(KYS_BASE, KYS_KS_INT_STS) & 0xf; } /****************************************************************************/ /** - * @brief KYS get keycode value - * - * @param keycode: KYS keycode type - * @param col: Col of key - * @param row: Row of key - * - * @return Keycode value - * -*******************************************************************************/ -uint8_t KYS_GetKeycode(KYS_Keycode_Type keycode, uint8_t *col, uint8_t *row) -{ - uint32_t tmpVal; - uint8_t keyValue; - - /* Get keycode value */ - keyValue = BL_RD_REG(KYS_BASE, KYS_KEYCODE_VALUE) >> (8 * keycode) & 0xff; - - /* Get total row number of keyboard */ - tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, KYS_ROW_NUM); - - /* Calculate col and row of the key */ - *col = keyValue / (tmpVal + 1); - *row = keyValue % (tmpVal + 1); - - return keyValue; + * @brief KYS get keycode value + * + * @param keycode: KYS keycode type + * @param col: Col of key + * @param row: Row of key + * + * @return Keycode value + * + *******************************************************************************/ +uint8_t KYS_GetKeycode(KYS_Keycode_Type keycode, uint8_t *col, uint8_t *row) { + uint32_t tmpVal; + uint8_t keyValue; + + /* Get keycode value */ + keyValue = BL_RD_REG(KYS_BASE, KYS_KEYCODE_VALUE) >> (8 * keycode) & 0xff; + + /* Get total row number of keyboard */ + tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, KYS_ROW_NUM); + + /* Calculate col and row of the key */ + *col = keyValue / (tmpVal + 1); + *row = keyValue % (tmpVal + 1); + + return keyValue; } /*@} end of group KYS_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_l1c.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_l1c.c index 303ebd1384..88fcd26c55 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_l1c.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_l1c.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_l1c.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_l1c.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_l1c.h" #include "bl702_common.h" @@ -60,8 +60,8 @@ /** @defgroup L1C_Private_Variables * @{ */ -static intCallback_Type *l1cBmxErrIntCbfArra[L1C_BMX_ERR_INT_ALL] = { NULL }; -static intCallback_Type *l1cBmxToIntCbfArra[L1C_BMX_TO_INT_ALL] = { NULL }; +static intCallback_Type *l1cBmxErrIntCbfArra[L1C_BMX_ERR_INT_ALL] = {NULL}; +static intCallback_Type *l1cBmxToIntCbfArra[L1C_BMX_TO_INT_ALL] = {NULL}; /*@} end of group L1C_Private_Variables */ @@ -88,573 +88,548 @@ static intCallback_Type *l1cBmxToIntCbfArra[L1C_BMX_TO_INT_ALL] = { NULL }; */ /****************************************************************************/ /** - * @brief Enable cache - * - * @param wayDisable: cache way disable config - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Enable cache + * + * @param wayDisable: cache way disable config + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION L1C_Cache_Enable_Set(uint8_t wayDisable) -{ - L1C_Cache_Flush(wayDisable); +BL_Err_Type ATTR_TCM_SECTION L1C_Cache_Enable_Set(uint8_t wayDisable) { + L1C_Cache_Flush(wayDisable); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief L1C cache write set - * - * @param wtEn: L1C write through enable - * @param wbEn: L1C write back enable - * @param waEn: L1C write allocate enable - * - * @return None - * -*******************************************************************************/ + * @brief L1C cache write set + * + * @param wtEn: L1C write through enable + * @param wbEn: L1C write back enable + * @param waEn: L1C write allocate enable + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION L1C_Cache_Write_Set(BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - - if (wtEn) { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WT_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WT_EN); - } - - if (wbEn) { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WB_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WB_EN); - } - - if (waEn) { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WA_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WA_EN); - } - - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); +void ATTR_TCM_SECTION L1C_Cache_Write_Set(BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + + if (wtEn) { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WT_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WT_EN); + } + + if (wbEn) { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WB_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WB_EN); + } + + if (waEn) { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WA_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WA_EN); + } + + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); } #endif /****************************************************************************/ /** - * @brief Flush cache - * - * @param wayDisable: cache way disable config - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Flush cache + * + * @param wayDisable: cache way disable config + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION L1C_Cache_Flush(uint8_t wayDisable) -{ - uint32_t tmpVal; - uint32_t cnt = 0; - uint8_t finWayDisable = 0; - +BL_Err_Type ATTR_TCM_SECTION L1C_Cache_Flush(uint8_t wayDisable) { + uint32_t tmpVal; + uint32_t cnt = 0; + uint8_t finWayDisable = 0; + + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BYPASS); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WAY_DIS); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CNT_EN); + finWayDisable = BL_GET_REG_BITS_VAL(tmpVal, L1C_WAY_DIS); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + + /*Set Tag RAM to zero */ + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_INVALID_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + /* Left space for hardware change status*/ + __NOP(); + __NOP(); + __NOP(); + __NOP(); + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_INVALID_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + /* Left space for hardware change status*/ + __NOP(); + __NOP(); + __NOP(); + __NOP(); + + /* Polling for invalid done */ + do { + BL702_Delay_US(1); + cnt++; tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BYPASS); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WAY_DIS); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CNT_EN); - finWayDisable = BL_GET_REG_BITS_VAL(tmpVal, L1C_WAY_DIS); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + } while (!BL_IS_REG_BIT_SET(tmpVal, L1C_INVALID_DONE) && cnt < 100); + + /* data flush */ + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_FLUSH_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + /* Left space for hardware change status*/ + __NOP(); + __NOP(); + __NOP(); + __NOP(); + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_FLUSH_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + /* Left space for hardware change status*/ + __NOP(); + __NOP(); + __NOP(); + __NOP(); + + /* Polling for flush done */ + do { + BL702_Delay_US(1); + cnt++; + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + } while (!BL_IS_REG_BIT_SET(tmpVal, L1C_FLUSH_DONE) && cnt < 100); - /*Set Tag RAM to zero */ - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_INVALID_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - /* Left space for hardware change status*/ - __NOP(); - __NOP(); - __NOP(); - __NOP(); - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_INVALID_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - /* Left space for hardware change status*/ - __NOP(); - __NOP(); - __NOP(); - __NOP(); - - /* Polling for invalid done */ - do { - BL702_Delay_US(1); - cnt++; - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - } while (!BL_IS_REG_BIT_SET(tmpVal, L1C_INVALID_DONE) && cnt < 100); - - /* data flush */ - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_FLUSH_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - /* Left space for hardware change status*/ - __NOP(); - __NOP(); - __NOP(); - __NOP(); - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_FLUSH_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - /* Left space for hardware change status*/ - __NOP(); - __NOP(); - __NOP(); - __NOP(); - - /* Polling for flush done */ - do { - BL702_Delay_US(1); - cnt++; - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - } while (!BL_IS_REG_BIT_SET(tmpVal, L1C_FLUSH_DONE) && cnt < 100); - - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_FLUSH_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_FLUSH_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BYPASS); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BYPASS); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_BYPASS); - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CNT_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_BYPASS); + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CNT_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - if (wayDisable != 0xff) { - finWayDisable = wayDisable; - } + if (wayDisable != 0xff) { + finWayDisable = wayDisable; + } - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WAY_DIS); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WAY_DIS); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - tmpVal |= (finWayDisable << L1C_WAY_DIS_POS); + tmpVal |= (finWayDisable << L1C_WAY_DIS_POS); - /* If way disable is 0x0f, cacheable can't be set */ - if (finWayDisable != 0x0f) { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CACHEABLE); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); - } + /* If way disable is 0x0f, cacheable can't be set */ + if (finWayDisable != 0x0f) { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CACHEABLE); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); + } - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Flush cache external api - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION L1C_Cache_Flush_Ext(void) -{ - uint32_t tmpVal; - - /* Disable early respone */ - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - L1C_Cache_Flush((tmpVal >> L1C_WAY_DIS_POS) & 0xf); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - - return SUCCESS; + * @brief Flush cache external api + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION L1C_Cache_Flush_Ext(void) { + uint32_t tmpVal; + + /* Disable early respone */ + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + L1C_Cache_Flush((tmpVal >> L1C_WAY_DIS_POS) & 0xf); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Get cache hit count - * - * @param hitCountLow: hit count low 32 bits pointer - * @param hitCountHigh: hit count high 32 bits pointer - * - * @return None - * -*******************************************************************************/ + * @brief Get cache hit count + * + * @param hitCountLow: hit count low 32 bits pointer + * @param hitCountHigh: hit count high 32 bits pointer + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION L1C_Cache_Hit_Count_Get(uint32_t *hitCountLow, uint32_t *hitCountHigh) -{ - *hitCountLow = BL_RD_REG(L1C_BASE, L1C_HIT_CNT_LSB); - *hitCountHigh = BL_RD_REG(L1C_BASE, L1C_HIT_CNT_MSB); +void ATTR_TCM_SECTION L1C_Cache_Hit_Count_Get(uint32_t *hitCountLow, uint32_t *hitCountHigh) { + *hitCountLow = BL_RD_REG(L1C_BASE, L1C_HIT_CNT_LSB); + *hitCountHigh = BL_RD_REG(L1C_BASE, L1C_HIT_CNT_MSB); } #endif /****************************************************************************/ /** - * @brief Get cache miss count - * - * @param None - * - * @return Cache miss count - * -*******************************************************************************/ + * @brief Get cache miss count + * + * @param None + * + * @return Cache miss count + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint32_t ATTR_TCM_SECTION L1C_Cache_Miss_Count_Get(void) -{ - return BL_RD_REG(L1C_BASE, L1C_MISS_CNT); -} +uint32_t ATTR_TCM_SECTION L1C_Cache_Miss_Count_Get(void) { return BL_RD_REG(L1C_BASE, L1C_MISS_CNT); } #endif /****************************************************************************/ /** - * @brief Disable read from flash or psram with cache - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Disable read from flash or psram with cache + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION L1C_Cache_Read_Disable(void) -{ - uint32_t tmpVal; +void ATTR_TCM_SECTION L1C_Cache_Read_Disable(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); } #endif /****************************************************************************/ /** - * @brief wrap set - * - * @param wrap: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief wrap set + * + * @param wrap: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION L1C_Set_Wrap(BL_Fun_Type wrap) -{ - uint32_t tmpVal = 0; - uint8_t cacheEn = 0; +BL_Err_Type ATTR_TCM_SECTION L1C_Set_Wrap(BL_Fun_Type wrap) { + uint32_t tmpVal = 0; + uint8_t cacheEn = 0; - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - cacheEn = BL_IS_REG_BIT_SET(L1C_BASE, L1C_CACHEABLE); + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + cacheEn = BL_IS_REG_BIT_SET(L1C_BASE, L1C_CACHEABLE); - if (cacheEn != 0) { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - } + if (cacheEn != 0) { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + } - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - if (wrap == ENABLE) { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WRAP_DIS); - } else { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WRAP_DIS); - } + if (wrap == ENABLE) { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WRAP_DIS); + } else { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WRAP_DIS); + } - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - if (cacheEn != 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CACHEABLE); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - } + if (cacheEn != 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CACHEABLE); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + } - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief cache way disable set - * - * @param disableVal: cache way disable value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief cache way disable set + * + * @param disableVal: cache way disable value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION L1C_Set_Way_Disable(uint8_t disableVal) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_TCM_SECTION L1C_Set_Way_Disable(uint8_t disableVal) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_WAY_DIS, disableVal); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_WAY_DIS, disableVal); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - if (disableVal != 0x0f) { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CACHEABLE); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); - } + if (disableVal != 0x0f) { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CACHEABLE); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); + } - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Set for ROM 2T access if CPU freq >120MHz - * - * @param enable: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Set for ROM 2T access if CPU freq >120MHz + * + * @param enable: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION L1C_IROM_2T_Access_Set(uint8_t enable) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_TCM_SECTION L1C_IROM_2T_Access_Set(uint8_t enable) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_IROM_2T_ACCESS); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_IROM_2T_ACCESS); - } + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_IROM_2T_ACCESS); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_IROM_2T_ACCESS); + } - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief L1C BMX init - * - * @param l1cBmxCfg: L1C BMX config - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type L1C_BMX_Init(L1C_BMX_Cfg_Type *l1cBmxCfg) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM((l1cBmxCfg->timeoutEn) <= 0xF); - - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_BMX_TIMEOUT_EN, l1cBmxCfg->timeoutEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_BMX_ERR_EN, l1cBmxCfg->errEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_BMX_ARB_MODE, l1cBmxCfg->arbMod); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + * @brief L1C BMX init + * + * @param l1cBmxCfg: L1C BMX config + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type L1C_BMX_Init(L1C_BMX_Cfg_Type *l1cBmxCfg) { + uint32_t tmpVal = 0; + + CHECK_PARAM((l1cBmxCfg->timeoutEn) <= 0xF); + + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_BMX_TIMEOUT_EN, l1cBmxCfg->timeoutEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_BMX_ERR_EN, l1cBmxCfg->errEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_BMX_ARB_MODE, l1cBmxCfg->arbMod); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(L1C_BMX_ERR_IRQn, L1C_BMX_ERR_IRQHandler); - Interrupt_Handler_Register(L1C_BMX_TO_IRQn, L1C_BMX_TO_IRQHandler); + Interrupt_Handler_Register(L1C_BMX_ERR_IRQn, L1C_BMX_ERR_IRQHandler); + Interrupt_Handler_Register(L1C_BMX_TO_IRQn, L1C_BMX_TO_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief L1C BMX address monitor enable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type L1C_BMX_Addr_Monitor_Enable(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_BMX_ERR_ADDR_DIS); - BL_WR_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN, tmpVal); - - return SUCCESS; + * @brief L1C BMX address monitor enable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type L1C_BMX_Addr_Monitor_Enable(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_BMX_ERR_ADDR_DIS); + BL_WR_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief L1C BMX address monitor disable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type L1C_BMX_Addr_Monitor_Disable(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BMX_ERR_ADDR_DIS); - BL_WR_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN, tmpVal); - - return SUCCESS; + * @brief L1C BMX address monitor disable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type L1C_BMX_Addr_Monitor_Disable(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BMX_ERR_ADDR_DIS); + BL_WR_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief L1C BMX bus error response enable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type L1C_BMX_BusErrResponse_Enable(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BMX_ERR_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - - return SUCCESS; + * @brief L1C BMX bus error response enable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type L1C_BMX_BusErrResponse_Enable(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BMX_ERR_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief L1C BMX bus error response disable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type L1C_BMX_BusErrResponse_Disable(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_BMX_ERR_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - - return SUCCESS; + * @brief L1C BMX bus error response disable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type L1C_BMX_BusErrResponse_Disable(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_BMX_ERR_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Get L1C BMX error status - * - * @param errType: L1C BMX error status type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type L1C_BMX_Get_Status(L1C_BMX_BUS_ERR_Type errType) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_L1C_BMX_BUS_ERR_TYPE(errType)); - - tmpVal = BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN); - - if (errType == L1C_BMX_BUS_ERR_TRUSTZONE_DECODE) { - return BL_GET_REG_BITS_VAL(tmpVal, L1C_BMX_ERR_TZ) ? SET : RESET; - } else { - return BL_GET_REG_BITS_VAL(tmpVal, L1C_BMX_ERR_DEC) ? SET : RESET; - } + * @brief Get L1C BMX error status + * + * @param errType: L1C BMX error status type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type L1C_BMX_Get_Status(L1C_BMX_BUS_ERR_Type errType) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_L1C_BMX_BUS_ERR_TYPE(errType)); + + tmpVal = BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN); + + if (errType == L1C_BMX_BUS_ERR_TRUSTZONE_DECODE) { + return BL_GET_REG_BITS_VAL(tmpVal, L1C_BMX_ERR_TZ) ? SET : RESET; + } else { + return BL_GET_REG_BITS_VAL(tmpVal, L1C_BMX_ERR_DEC) ? SET : RESET; + } } /****************************************************************************/ /** - * @brief Get L1C BMX error address - * - * @param None - * - * @return NP L1C BMX error address - * -*******************************************************************************/ -uint32_t L1C_BMX_Get_Err_Addr(void) -{ - return BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR); -} + * @brief Get L1C BMX error address + * + * @param None + * + * @return NP L1C BMX error address + * + *******************************************************************************/ +uint32_t L1C_BMX_Get_Err_Addr(void) { return BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR); } /****************************************************************************/ /** - * @brief L1C BMX error interrupt callback install - * - * @param intType: L1C BMX error interrupt type - * @param cbFun: callback - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type L1C_BMX_ERR_INT_Callback_Install(L1C_BMX_ERR_INT_Type intType, intCallback_Type *cbFun) -{ - CHECK_PARAM(IS_L1C_BMX_ERR_INT_TYPE(intType)); - - l1cBmxErrIntCbfArra[intType] = cbFun; - - return SUCCESS; + * @brief L1C BMX error interrupt callback install + * + * @param intType: L1C BMX error interrupt type + * @param cbFun: callback + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type L1C_BMX_ERR_INT_Callback_Install(L1C_BMX_ERR_INT_Type intType, intCallback_Type *cbFun) { + CHECK_PARAM(IS_L1C_BMX_ERR_INT_TYPE(intType)); + + l1cBmxErrIntCbfArra[intType] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief L1C BMX ERR interrupt IRQ handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief L1C BMX ERR interrupt IRQ handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void L1C_BMX_ERR_IRQHandler(void) -{ - L1C_BMX_ERR_INT_Type intType; - - for (intType = L1C_BMX_ERR_INT_ERR; intType < L1C_BMX_ERR_INT_ALL; intType++) { - if (l1cBmxErrIntCbfArra[intType] != NULL) { - l1cBmxErrIntCbfArra[intType](); - } - } +void L1C_BMX_ERR_IRQHandler(void) { + L1C_BMX_ERR_INT_Type intType; - while (1) { - //MSG("L1C_BMX_ERR_IRQHandler\r\n"); - BL702_Delay_MS(1000); + for (intType = L1C_BMX_ERR_INT_ERR; intType < L1C_BMX_ERR_INT_ALL; intType++) { + if (l1cBmxErrIntCbfArra[intType] != NULL) { + l1cBmxErrIntCbfArra[intType](); } + } + + while (1) { + // MSG("L1C_BMX_ERR_IRQHandler\r\n"); + BL702_Delay_MS(1000); + } } #endif /****************************************************************************/ /** - * @brief L1C BMX timeout interrupt callback install - * - * @param intType: L1C BMX timeout interrupt type - * @param cbFun: callback - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type L1C_BMX_TIMEOUT_INT_Callback_Install(L1C_BMX_TO_INT_Type intType, intCallback_Type *cbFun) -{ - CHECK_PARAM(IS_L1C_BMX_TO_INT_TYPE(intType)); - - l1cBmxToIntCbfArra[intType] = cbFun; - - return SUCCESS; + * @brief L1C BMX timeout interrupt callback install + * + * @param intType: L1C BMX timeout interrupt type + * @param cbFun: callback + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type L1C_BMX_TIMEOUT_INT_Callback_Install(L1C_BMX_TO_INT_Type intType, intCallback_Type *cbFun) { + CHECK_PARAM(IS_L1C_BMX_TO_INT_TYPE(intType)); + + l1cBmxToIntCbfArra[intType] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief L1C BMX Time Out interrupt IRQ handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief L1C BMX Time Out interrupt IRQ handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void L1C_BMX_TO_IRQHandler(void) -{ - L1C_BMX_TO_INT_Type intType; - - for (intType = L1C_BMX_TO_INT_TIMEOUT; intType < L1C_BMX_TO_INT_ALL; intType++) { - if (l1cBmxToIntCbfArra[intType] != NULL) { - l1cBmxToIntCbfArra[intType](); - } - } +void L1C_BMX_TO_IRQHandler(void) { + L1C_BMX_TO_INT_Type intType; - while (1) { - //MSG("L1C_BMX_TO_IRQHandler\r\n"); - BL702_Delay_MS(1000); + for (intType = L1C_BMX_TO_INT_TIMEOUT; intType < L1C_BMX_TO_INT_ALL; intType++) { + if (l1cBmxToIntCbfArra[intType] != NULL) { + l1cBmxToIntCbfArra[intType](); } + } + + while (1) { + // MSG("L1C_BMX_TO_IRQHandler\r\n"); + BL702_Delay_MS(1000); + } } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_mjpeg.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_mjpeg.c index 06ff2f9519..144d3c9adf 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_mjpeg.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_mjpeg.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_mjpeg.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_mjpeg.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "bl702.h" #include "bl702_mjpeg.h" +#include "bl702.h" #include "bl702_glb.h" /** @addtogroup BL702_Peripheral_Driver @@ -61,7 +61,7 @@ /** @defgroup MJPEG_Private_Variables * @{ */ -static intCallback_Type *mjpegIntCbfArra[MJPEG_INT_ALL] = { NULL }; +static intCallback_Type *mjpegIntCbfArra[MJPEG_INT_ALL] = {NULL}; /*@} end of group MJPEG_Private_Variables */ @@ -88,648 +88,611 @@ static intCallback_Type *mjpegIntCbfArra[MJPEG_INT_ALL] = { NULL }; */ /****************************************************************************/ /** - * @brief Mjpeg module init - * - * @param cfg: Mjpeg configuration structure pointer - * - * @return None - * -*******************************************************************************/ -void MJPEG_Init(MJPEG_CFG_Type *cfg) -{ - uint32_t tmpVal; - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_MJPEG); - - /* disable mjpeg */ - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_ENABLE); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); - - /* basic stuff */ - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_YUV_MODE, cfg->yuv); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_Q_MODE, cfg->quality); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_H_BUST, cfg->burst); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_MJPEG_BIT_ORDER, cfg->bitOrderEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_ORDER_U_EVEN, cfg->evenOrderEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_WR_OVER_STOP, cfg->overStopEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_REFLECT_DMY, cfg->reflectDmy); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_LAST_HF_HBLK_DMY, cfg->verticalDmy); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_LAST_HF_WBLK_DMY, cfg->horizationalDmy); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_MJPEG_WAIT_CYCLE, cfg->waitCount); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_FRAME_SIZE); - - switch (cfg->yuv) { - case MJPEG_YUV422_INTERLEAVE: - case MJPEG_YUV422_PLANAR: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_WBLK, (cfg->resolutionX + 15) >> 4); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_HBLK, (cfg->resolutionY + 7) >> 3); - break; - - case MJPEG_YUV420: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_WBLK, (cfg->resolutionX + 15) >> 4); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_HBLK, (cfg->resolutionY + 15) >> 4); - break; - - case MJPEG_YUV400: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_WBLK, (cfg->resolutionX + 7) >> 3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_HBLK, (cfg->resolutionY + 7) >> 3); - break; - - default: - break; - } - - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_SIZE, tmpVal); - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_W_SWAP_MODE, cfg->swapModeEnable); - BL_WR_REG(MJPEG_BASE, MJPEG_SWAP_MODE, tmpVal); - - /*align buffer to 16 bytes boundary, should be kept the same as CAM module*/ - BL_WR_REG(MJPEG_BASE, MJPEG_YY_FRAME_ADDR, (cfg->bufferCamYY & 0xFFFFFFF0)); - BL_WR_REG(MJPEG_BASE, MJPEG_UV_FRAME_ADDR, (cfg->bufferCamUV & 0xFFFFFFF0)); - BL_WR_REG(MJPEG_BASE, MJPEG_YUV_MEM, (cfg->sizeCamUV << 16) + cfg->sizeCamYY); - - /*align buffer to 16 bytes boundary*/ - BL_WR_REG(MJPEG_BASE, MJPEG_JPEG_FRAME_ADDR, (cfg->bufferMjpeg & 0xFFFFFFF0)); - /*align buffer size in unit of 64 bytes */ - BL_WR_REG(MJPEG_BASE, MJPEG_JPEG_STORE_MEMORY, cfg->sizeMjpeg >> 6); - - /* Clear interrupt */ - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x3F00); + * @brief Mjpeg module init + * + * @param cfg: Mjpeg configuration structure pointer + * + * @return None + * + *******************************************************************************/ +void MJPEG_Init(MJPEG_CFG_Type *cfg) { + uint32_t tmpVal; + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_MJPEG); + + /* disable mjpeg */ + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_ENABLE); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); + + /* basic stuff */ + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_YUV_MODE, cfg->yuv); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_Q_MODE, cfg->quality); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_H_BUST, cfg->burst); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_MJPEG_BIT_ORDER, cfg->bitOrderEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_ORDER_U_EVEN, cfg->evenOrderEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_WR_OVER_STOP, cfg->overStopEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_REFLECT_DMY, cfg->reflectDmy); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_LAST_HF_HBLK_DMY, cfg->verticalDmy); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_LAST_HF_WBLK_DMY, cfg->horizationalDmy); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_MJPEG_WAIT_CYCLE, cfg->waitCount); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_FRAME_SIZE); + + switch (cfg->yuv) { + case MJPEG_YUV422_INTERLEAVE: + case MJPEG_YUV422_PLANAR: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_WBLK, (cfg->resolutionX + 15) >> 4); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_HBLK, (cfg->resolutionY + 7) >> 3); + break; + + case MJPEG_YUV420: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_WBLK, (cfg->resolutionX + 15) >> 4); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_HBLK, (cfg->resolutionY + 15) >> 4); + break; + + case MJPEG_YUV400: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_WBLK, (cfg->resolutionX + 7) >> 3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_HBLK, (cfg->resolutionY + 7) >> 3); + break; + + default: + break; + } + + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_SIZE, tmpVal); + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_W_SWAP_MODE, cfg->swapModeEnable); + BL_WR_REG(MJPEG_BASE, MJPEG_SWAP_MODE, tmpVal); + + /*align buffer to 16 bytes boundary, should be kept the same as CAM module*/ + BL_WR_REG(MJPEG_BASE, MJPEG_YY_FRAME_ADDR, (cfg->bufferCamYY & 0xFFFFFFF0)); + BL_WR_REG(MJPEG_BASE, MJPEG_UV_FRAME_ADDR, (cfg->bufferCamUV & 0xFFFFFFF0)); + BL_WR_REG(MJPEG_BASE, MJPEG_YUV_MEM, (cfg->sizeCamUV << 16) + cfg->sizeCamYY); + + /*align buffer to 16 bytes boundary*/ + BL_WR_REG(MJPEG_BASE, MJPEG_JPEG_FRAME_ADDR, (cfg->bufferMjpeg & 0xFFFFFFF0)); + /*align buffer size in unit of 64 bytes */ + BL_WR_REG(MJPEG_BASE, MJPEG_JPEG_STORE_MEMORY, cfg->sizeMjpeg >> 6); + + /* Clear interrupt */ + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x3F00); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(MJPEG_IRQn, MJPEG_IRQHandler); + Interrupt_Handler_Register(MJPEG_IRQn, MJPEG_IRQHandler); #endif } /****************************************************************************/ /** - * @brief Mjpeg packet mode configure - * - * @param cfg: Packet configuration - * - * @return None - * -*******************************************************************************/ -void MJPEG_Packet_Config(MJPEG_Packet_Type *cfg) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_PAKET_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_PKET_EN, cfg->packetEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_JEND_TO_PEND, cfg->endToTail); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_PKET_BODY_BYTE, cfg->packetBody); - BL_WR_REG(MJPEG_BASE, MJPEG_PAKET_CTRL, tmpVal); - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_HEADER_BYTE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_HEAD_BYTE, cfg->frameHead); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_TAIL_EXP, cfg->frameTail); - BL_WR_REG(MJPEG_BASE, MJPEG_HEADER_BYTE, tmpVal); - - BL_WR_REG(MJPEG_BASE, MJPEG_PAKET_HEAD_TAIL, (cfg->packetTail << 16) + cfg->packetHead); + * @brief Mjpeg packet mode configure + * + * @param cfg: Packet configuration + * + * @return None + * + *******************************************************************************/ +void MJPEG_Packet_Config(MJPEG_Packet_Type *cfg) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_PAKET_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_PKET_EN, cfg->packetEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_JEND_TO_PEND, cfg->endToTail); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_PKET_BODY_BYTE, cfg->packetBody); + BL_WR_REG(MJPEG_BASE, MJPEG_PAKET_CTRL, tmpVal); + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_HEADER_BYTE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_HEAD_BYTE, cfg->frameHead); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_TAIL_EXP, cfg->frameTail); + BL_WR_REG(MJPEG_BASE, MJPEG_HEADER_BYTE, tmpVal); + + BL_WR_REG(MJPEG_BASE, MJPEG_PAKET_HEAD_TAIL, (cfg->packetTail << 16) + cfg->packetHead); } /****************************************************************************/ /** - * @brief Mjpeg set YUYV order, only work in interleave mode - * - * @param y0: Y0 order - * @param u0: U0 order - * @param y1: Y1 order - * @param v0: V0 order - * - * @return None - * -*******************************************************************************/ -void MJPEG_Set_YUYV_Order_Interleave(uint8_t y0, uint8_t u0, uint8_t y1, uint8_t v0) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_Y0_ORDER, y0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_U0_ORDER, u0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_Y1_ORDER, y1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_V0_ORDER, v0); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); - - MJPEG_Set_YUYV_Order_Planar(0, 1); + * @brief Mjpeg set YUYV order, only work in interleave mode + * + * @param y0: Y0 order + * @param u0: U0 order + * @param y1: Y1 order + * @param v0: V0 order + * + * @return None + * + *******************************************************************************/ +void MJPEG_Set_YUYV_Order_Interleave(uint8_t y0, uint8_t u0, uint8_t y1, uint8_t v0) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_Y0_ORDER, y0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_U0_ORDER, u0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_Y1_ORDER, y1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_V0_ORDER, v0); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); + + MJPEG_Set_YUYV_Order_Planar(0, 1); } /****************************************************************************/ /** - * @brief Mjpeg set YY/UV order, only work in planar mode - * - * @param yy: YY order - * @param uv: UV order - * - * @return None - * -*******************************************************************************/ -void MJPEG_Set_YUYV_Order_Planar(uint8_t yy, uint8_t uv) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_YY_DVP2AHB_LSEL, yy); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_YY_DVP2AHB_FSEL, yy); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_UV_DVP2AHB_LSEL, uv); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_UV_DVP2AHB_FSEL, uv); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); + * @brief Mjpeg set YY/UV order, only work in planar mode + * + * @param yy: YY order + * @param uv: UV order + * + * @return None + * + *******************************************************************************/ +void MJPEG_Set_YUYV_Order_Planar(uint8_t yy, uint8_t uv) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_YY_DVP2AHB_LSEL, yy); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_YY_DVP2AHB_FSEL, yy); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_UV_DVP2AHB_LSEL, uv); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_UV_DVP2AHB_FSEL, uv); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); } /****************************************************************************/ /** - * @brief Deinit mjpeg module - * - * @param None - * - * @return None - * -*******************************************************************************/ -void MJPEG_Deinit(void) -{ - //GLB_AHB_Slave2_Reset(BL_AHB_SLAVE2_MJPEG); + * @brief Deinit mjpeg module + * + * @param None + * + * @return None + * + *******************************************************************************/ +void MJPEG_Deinit(void) { + // GLB_AHB_Slave2_Reset(BL_AHB_SLAVE2_MJPEG); } /****************************************************************************/ /** - * @brief Enable mjpeg module - * - * @param None - * - * @return None - * -*******************************************************************************/ -void MJPEG_Enable(void) -{ - uint32_t tmpVal; - - /* Enable mjpeg module */ - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_MJPEG_ENABLE); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); + * @brief Enable mjpeg module + * + * @param None + * + * @return None + * + *******************************************************************************/ +void MJPEG_Enable(void) { + uint32_t tmpVal; + + /* Enable mjpeg module */ + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_MJPEG_ENABLE); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); } /****************************************************************************/ /** - * @brief Disable mjpeg module - * - * @param None - * - * @return None - * -*******************************************************************************/ -void MJPEG_Disable(void) -{ - uint32_t tmpVal; - - /* Disable mjpeg module */ - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_ENABLE); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); + * @brief Disable mjpeg module + * + * @param None + * + * @return None + * + *******************************************************************************/ +void MJPEG_Disable(void) { + uint32_t tmpVal; + + /* Disable mjpeg module */ + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_ENABLE); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); } /****************************************************************************/ /** - * @brief Enable&disable mjpeg software mode and set frame count - * - * @param count: Frame count - * - * @return None - * -*******************************************************************************/ -void MJPEG_SW_Enable(uint8_t count) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_SW_FRAME, count); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_MODE); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_MODE); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); + * @brief Enable&disable mjpeg software mode and set frame count + * + * @param count: Frame count + * + * @return None + * + *******************************************************************************/ +void MJPEG_SW_Enable(uint8_t count) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_SW_FRAME, count); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_MODE); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_MODE); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); } /****************************************************************************/ /** - * @brief MJPEG software mode run, software mode enable first - * - * @param None - * - * @return None - * -*******************************************************************************/ -void MJPEG_SW_Run(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_RUN); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_RUN); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); + * @brief MJPEG software mode run, software mode enable first + * + * @param None + * + * @return None + * + *******************************************************************************/ +void MJPEG_SW_Run(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_RUN); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_RUN); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); } /****************************************************************************/ /** - * @brief Get one mjpeg frame - * - * @param info: Mjpeg frame infomation pointer - * - * @return None - * -*******************************************************************************/ -void MJPEG_Get_Frame_Info(MJPEG_Frame_Info *info) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); - - info->validFrames = BL_GET_REG_BITS_VAL(tmpVal, MJPEG_FRAME_VALID_CNT); - info->curFrameAddr = BL_RD_REG(MJPEG_BASE, MJPEG_START_ADDR0); - info->curFrameBytes = (BL_RD_REG(MJPEG_BASE, MJPEG_BIT_CNT0) + 7) >> 3; - info->curFrameQ = BL_RD_REG(MJPEG_BASE, MJPEG_Q_MODE0) & 0x3f; - info->status = tmpVal; + * @brief Get one mjpeg frame + * + * @param info: Mjpeg frame infomation pointer + * + * @return None + * + *******************************************************************************/ +void MJPEG_Get_Frame_Info(MJPEG_Frame_Info *info) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); + + info->validFrames = BL_GET_REG_BITS_VAL(tmpVal, MJPEG_FRAME_VALID_CNT); + info->curFrameAddr = BL_RD_REG(MJPEG_BASE, MJPEG_START_ADDR0); + info->curFrameBytes = (BL_RD_REG(MJPEG_BASE, MJPEG_BIT_CNT0) + 7) >> 3; + info->curFrameQ = BL_RD_REG(MJPEG_BASE, MJPEG_Q_MODE0) & 0x3f; + info->status = tmpVal; } /****************************************************************************/ /** - * @brief Get available count of frames - * - * @param None - * - * @return Frames count - * -*******************************************************************************/ -uint8_t MJPEG_Get_Frame_Count(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3), MJPEG_FRAME_VALID_CNT); -} + * @brief Get available count of frames + * + * @param None + * + * @return Frames count + * + *******************************************************************************/ +uint8_t MJPEG_Get_Frame_Count(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3), MJPEG_FRAME_VALID_CNT); } /****************************************************************************/ /** - * @brief Pop one mjpeg frame - * - * @param None - * - * @return None - * -*******************************************************************************/ -void MJPEG_Pop_Frame(void) -{ - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 1); -} + * @brief Pop one mjpeg frame + * + * @param None + * + * @return None + * + *******************************************************************************/ +void MJPEG_Pop_Frame(void) { BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 1); } /****************************************************************************/ /** - * @brief Free current read memory block - * - * @param None - * - * @return None - * -*******************************************************************************/ -void MJPEG_Current_Block_Clear(void) -{ - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x2); -} + * @brief Free current read memory block + * + * @param None + * + * @return None + * + *******************************************************************************/ +void MJPEG_Current_Block_Clear(void) { BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x2); } /****************************************************************************/ /** - * @brief Current read memory block index - * - * @param None - * - * @return Block number - * -*******************************************************************************/ -MJPEG_Swap_Block_Type MJPEG_Get_Current_Block(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_READ_SWAP_IDX); -} + * @brief Current read memory block index + * + * @param None + * + * @return Block number + * + *******************************************************************************/ +MJPEG_Swap_Block_Type MJPEG_Get_Current_Block(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_READ_SWAP_IDX); } /****************************************************************************/ /** - * @brief Get block status, full or not full - * - * @param block: Block number - * - * @return Block status - * -*******************************************************************************/ -BL_Sts_Type MJPEG_Block_Is_Full(MJPEG_Swap_Block_Type block) -{ - CHECK_PARAM(IS_MJPEG_SWAP_BLOCK_TYPE(block)); - - if (MJPEG_BLOCK_0 == block) { - return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP0_FULL); - } else { - return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP1_FULL); - } + * @brief Get block status, full or not full + * + * @param block: Block number + * + * @return Block status + * + *******************************************************************************/ +BL_Sts_Type MJPEG_Block_Is_Full(MJPEG_Swap_Block_Type block) { + CHECK_PARAM(IS_MJPEG_SWAP_BLOCK_TYPE(block)); + + if (MJPEG_BLOCK_0 == block) { + return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP0_FULL); + } else { + return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP1_FULL); + } } /****************************************************************************/ /** - * @brief Current read memory block is frame start - * - * @param None - * - * @return Set or reset - * -*******************************************************************************/ -BL_Sts_Type MJPEG_Current_Block_Is_Start(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP_FSTART); -} + * @brief Current read memory block is frame start + * + * @param None + * + * @return Set or reset + * + *******************************************************************************/ +BL_Sts_Type MJPEG_Current_Block_Is_Start(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP_FSTART); } /****************************************************************************/ /** - * @brief Current read memory block is frame end - * - * @param None - * - * @return Set or reset - * -*******************************************************************************/ -BL_Sts_Type MJPEG_Current_Block_Is_End(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP_FEND); -} + * @brief Current read memory block is frame end + * + * @param None + * + * @return Set or reset + * + *******************************************************************************/ +BL_Sts_Type MJPEG_Current_Block_Is_End(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP_FEND); } /****************************************************************************/ /** - * @brief Get frame remain bit count in last block, only valid when current read memory block is - * frame end - * - * @param None - * - * @return Bit count - * -*******************************************************************************/ -uint32_t MJPEG_Get_Remain_Bit(void) -{ - return BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_BIT_CNT); -} + * @brief Get frame remain bit count in last block, only valid when current read memory block is + * frame end + * + * @param None + * + * @return Bit count + * + *******************************************************************************/ +uint32_t MJPEG_Get_Remain_Bit(void) { return BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_BIT_CNT); } /****************************************************************************/ /** - * @brief Set frame threshold to issue normal interrupt - * - * @param count: Frame threshold - * - * @return None - * -*******************************************************************************/ -void MJPEG_Set_Frame_Threshold(uint8_t count) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_CNT_TRGR_INT, count); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_3, tmpVal); + * @brief Set frame threshold to issue normal interrupt + * + * @param count: Frame threshold + * + * @return None + * + *******************************************************************************/ +void MJPEG_Set_Frame_Threshold(uint8_t count) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_CNT_TRGR_INT, count); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_3, tmpVal); } /****************************************************************************/ /** - * @brief MJPEG Enable Disable Interrupt - * - * @param intType: MJPEG Interrupt Type - * @param intMask: Enable or Disable - * - * @return None - * -*******************************************************************************/ -void MJPEG_IntMask(MJPEG_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_MJPEG_INT_TYPE(intType)); - CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); - - switch (intType) { - case MJPEG_INT_NORMAL: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); - } - - break; - - case MJPEG_INT_CAM_OVERWRITE: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); - } - - break; - - case MJPEG_INT_MEM_OVERWRITE: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); - } - - break; - - case MJPEG_INT_FRAME_OVERWRITE: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); - } - - break; - - case MJPEG_INT_BACK_IDLE: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); - } - - break; - - case MJPEG_INT_SWAP: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); - } - - break; - - case MJPEG_INT_ALL: - if (intMask == UNMASK) { - /* Enable all interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); - } else { - /* Disable all interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); - } - - break; - - default: - break; + * @brief MJPEG Enable Disable Interrupt + * + * @param intType: MJPEG Interrupt Type + * @param intMask: Enable or Disable + * + * @return None + * + *******************************************************************************/ +void MJPEG_IntMask(MJPEG_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_MJPEG_INT_TYPE(intType)); + CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); + + switch (intType) { + case MJPEG_INT_NORMAL: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); + } + + break; + + case MJPEG_INT_CAM_OVERWRITE: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); + } + + break; + + case MJPEG_INT_MEM_OVERWRITE: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); + } + + break; + + case MJPEG_INT_FRAME_OVERWRITE: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); } - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_3, tmpVal); + break; + + case MJPEG_INT_BACK_IDLE: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); + } + + break; + + case MJPEG_INT_SWAP: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); + } + + break; + + case MJPEG_INT_ALL: + if (intMask == UNMASK) { + /* Enable all interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); + } else { + /* Disable all interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); + } + + break; + + default: + break; + } + + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_3, tmpVal); } /****************************************************************************/ /** - * @brief MJPEG Interrupt Clear - * - * @param intType: MJPEG Interrupt Type - * - * @return None - * -*******************************************************************************/ -void MJPEG_IntClr(MJPEG_INT_Type intType) -{ - uint32_t tmpVal; + * @brief MJPEG Interrupt Clear + * + * @param intType: MJPEG Interrupt Type + * + * @return None + * + *******************************************************************************/ +void MJPEG_IntClr(MJPEG_INT_Type intType) { + uint32_t tmpVal; - CHECK_PARAM(IS_MJPEG_INT_TYPE(intType)); + CHECK_PARAM(IS_MJPEG_INT_TYPE(intType)); - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP); + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP); - switch (intType) { - case MJPEG_INT_NORMAL: - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_CLR); - break; + switch (intType) { + case MJPEG_INT_NORMAL: + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_CLR); + break; - case MJPEG_INT_CAM_OVERWRITE: - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_CLR); - break; + case MJPEG_INT_CAM_OVERWRITE: + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_CLR); + break; - case MJPEG_INT_MEM_OVERWRITE: - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_CLR); - break; + case MJPEG_INT_MEM_OVERWRITE: + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_CLR); + break; - case MJPEG_INT_FRAME_OVERWRITE: - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_CLR); - break; + case MJPEG_INT_FRAME_OVERWRITE: + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_CLR); + break; - case MJPEG_INT_BACK_IDLE: - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_CLR); - break; + case MJPEG_INT_BACK_IDLE: + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_CLR); + break; - case MJPEG_INT_SWAP: - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_CLR); - break; + case MJPEG_INT_SWAP: + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_CLR); + break; - case MJPEG_INT_ALL: - tmpVal = 0x3F00; + case MJPEG_INT_ALL: + tmpVal = 0x3F00; - default: - break; - } + default: + break; + } - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, tmpVal); + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, tmpVal); } /****************************************************************************/ /** - * @brief Install mjpeg interrupt callback function - * - * @param intType: MJPEG interrupt type - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return None - * -*******************************************************************************/ -void MJPEG_Int_Callback_Install(MJPEG_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_MJPEG_INT_TYPE(intType)); - - mjpegIntCbfArra[intType] = cbFun; + * @brief Install mjpeg interrupt callback function + * + * @param intType: MJPEG interrupt type + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return None + * + *******************************************************************************/ +void MJPEG_Int_Callback_Install(MJPEG_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_MJPEG_INT_TYPE(intType)); + + mjpegIntCbfArra[intType] = cbFun; } /****************************************************************************/ /** - * @brief Mjpeg interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Mjpeg interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void MJPEG_IRQHandler(void) -{ - uint32_t tmpVal; +void MJPEG_IRQHandler(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); - if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_NORMAL_INT)) { - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x100); + if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_NORMAL_INT)) { + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x100); - if (mjpegIntCbfArra[MJPEG_INT_NORMAL] != NULL) { - /* call the callback function */ - mjpegIntCbfArra[MJPEG_INT_NORMAL](); - } + if (mjpegIntCbfArra[MJPEG_INT_NORMAL] != NULL) { + /* call the callback function */ + mjpegIntCbfArra[MJPEG_INT_NORMAL](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_CAM_INT)) { - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x200); + if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_CAM_INT)) { + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x200); - if (mjpegIntCbfArra[MJPEG_INT_CAM_OVERWRITE] != NULL) { - /* call the callback function */ - mjpegIntCbfArra[MJPEG_INT_CAM_OVERWRITE](); - } + if (mjpegIntCbfArra[MJPEG_INT_CAM_OVERWRITE] != NULL) { + /* call the callback function */ + mjpegIntCbfArra[MJPEG_INT_CAM_OVERWRITE](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_MEM_INT)) { - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x400); + if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_MEM_INT)) { + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x400); - if (mjpegIntCbfArra[MJPEG_INT_MEM_OVERWRITE] != NULL) { - /* call the callback function */ - mjpegIntCbfArra[MJPEG_INT_MEM_OVERWRITE](); - } + if (mjpegIntCbfArra[MJPEG_INT_MEM_OVERWRITE] != NULL) { + /* call the callback function */ + mjpegIntCbfArra[MJPEG_INT_MEM_OVERWRITE](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_FRAME_INT)) { - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x800); + if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_FRAME_INT)) { + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x800); - if (mjpegIntCbfArra[MJPEG_INT_FRAME_OVERWRITE] != NULL) { - /* call the callback function */ - mjpegIntCbfArra[MJPEG_INT_FRAME_OVERWRITE](); - } + if (mjpegIntCbfArra[MJPEG_INT_FRAME_OVERWRITE] != NULL) { + /* call the callback function */ + mjpegIntCbfArra[MJPEG_INT_FRAME_OVERWRITE](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_IDLE_INT)) { - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x1000); + if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_IDLE_INT)) { + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x1000); - if (mjpegIntCbfArra[MJPEG_INT_BACK_IDLE] != NULL) { - /* call the callback function */ - mjpegIntCbfArra[MJPEG_INT_BACK_IDLE](); - } + if (mjpegIntCbfArra[MJPEG_INT_BACK_IDLE] != NULL) { + /* call the callback function */ + mjpegIntCbfArra[MJPEG_INT_BACK_IDLE](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_SWAP_INT)) { - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x2000); + if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_SWAP_INT)) { + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x2000); - if (mjpegIntCbfArra[MJPEG_INT_SWAP] != NULL) { - /* call the callback function */ - mjpegIntCbfArra[MJPEG_INT_SWAP](); - } + if (mjpegIntCbfArra[MJPEG_INT_SWAP] != NULL) { + /* call the callback function */ + mjpegIntCbfArra[MJPEG_INT_SWAP](); } + } } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pds.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pds.c index 28b6cbcf5d..a8aa807801 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pds.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pds.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_pds.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_pds.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "bl702.h" #include "bl702_pds.h" +#include "bl702.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -60,7 +60,7 @@ /** @defgroup PDS_Private_Variables * @{ */ -static intCallback_Type *pdsIntCbfArra[PDS_INT_MAX][1] = { { NULL }, { NULL }, { NULL }, { NULL }, { NULL }, { NULL }, { NULL }, { NULL }, { NULL }, { NULL }, { NULL } }; +static intCallback_Type *pdsIntCbfArra[PDS_INT_MAX][1] = {{NULL}, {NULL}, {NULL}, {NULL}, {NULL}, {NULL}, {NULL}, {NULL}, {NULL}, {NULL}, {NULL}}; /*@} end of group PDS_Private_Variables */ @@ -87,804 +87,773 @@ static intCallback_Type *pdsIntCbfArra[PDS_INT_MAX][1] = { { NULL }, { NULL }, { */ /****************************************************************************/ /** - * @brief power down sleep ram configure - * - * @param ramCfg: power down sleep force ram configuration - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION PDS_RAM_Config(PDS_RAM_CFG_Type *ramCfg) -{ - if (NULL == ramCfg) { - return ERROR; - } + * @brief power down sleep ram configure + * + * @param ramCfg: power down sleep force ram configuration + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION PDS_RAM_Config(PDS_RAM_CFG_Type *ramCfg) { + if (NULL == ramCfg) { + return ERROR; + } - /* PDS_RAM1 config */ - BL_WR_REG(PDS_BASE, PDS_RAM1, *(uint32_t *)ramCfg); + /* PDS_RAM1 config */ + BL_WR_REG(PDS_BASE, PDS_RAM1, *(uint32_t *)ramCfg); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief power down sleep set pad configure - * - * @param pin: power down sleep pad num - * @param cfg: power down sleep pad type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION PDS_Set_Pad_Config(PDS_PAD_PIN_Type pin, PDS_PAD_CFG_Type cfg) -{ - uint32_t tmpVal = 0; - uint32_t tmpPu = 0; - uint32_t tmpPd = 0; - - if (pin < PDS_PAD_PIN_GPIO_23) { - /* GPIO17 - GPIO22 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_SET_PU_PD); - - switch (cfg) { - case PDS_PAD_CFG_PULL_NONE: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) & ~(1 << pin); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) & ~(1 << pin); - break; - - case PDS_PAD_CFG_PULL_DOWN: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) | (1 << pin); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) & ~(1 << pin); - break; - - case PDS_PAD_CFG_PULL_UP: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) & ~(1 << pin); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) | (1 << pin); - break; - - case PDS_PAD_CFG_ACTIVE_IE: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) | (1 << pin); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) | (1 << pin); - break; - - default: - break; - } - - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD, tmpPd); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU, tmpPu); - BL_WR_REG(PDS_BASE, PDS_GPIO_SET_PU_PD, tmpVal); - } else { - /* GPIO23 - GPIO28 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_SET_PU_PD); - - switch (cfg) { - case PDS_PAD_CFG_PULL_NONE: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); - break; - - case PDS_PAD_CFG_PULL_DOWN: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); - break; - - case PDS_PAD_CFG_PULL_UP: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); - break; - - case PDS_PAD_CFG_ACTIVE_IE: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); - break; - - default: - break; - } - - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD, tmpPd); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU, tmpPu); - BL_WR_REG(PDS_BASE, PDS_GPIO_SET_PU_PD, tmpVal); + * @brief power down sleep set pad configure + * + * @param pin: power down sleep pad num + * @param cfg: power down sleep pad type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION PDS_Set_Pad_Config(PDS_PAD_PIN_Type pin, PDS_PAD_CFG_Type cfg) { + uint32_t tmpVal = 0; + uint32_t tmpPu = 0; + uint32_t tmpPd = 0; + + if (pin < PDS_PAD_PIN_GPIO_23) { + /* GPIO17 - GPIO22 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_SET_PU_PD); + + switch (cfg) { + case PDS_PAD_CFG_PULL_NONE: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) & ~(1 << pin); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) & ~(1 << pin); + break; + + case PDS_PAD_CFG_PULL_DOWN: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) | (1 << pin); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) & ~(1 << pin); + break; + + case PDS_PAD_CFG_PULL_UP: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) & ~(1 << pin); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) | (1 << pin); + break; + + case PDS_PAD_CFG_ACTIVE_IE: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) | (1 << pin); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) | (1 << pin); + break; + + default: + break; } - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Enable power down sleep - * - * @param cfg: power down sleep configuration 1 - * @param cfg4: power down sleep configuration 2 - * @param pdsSleepCnt: power down sleep count cycle - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION PDS_App_Enable(PDS_CTL_Type *cfg, PDS_CTL4_Type *cfg4, uint32_t pdsSleepCnt) -{ - /* PDS sleep time 0 <=> sleep forever */ - /* PDS sleep time 1~PDS_WARMUP_LATENCY_CNT <=> error */ - /* PDS sleep time >PDS_WARMUP_LATENCY_CNT <=> correct */ - if (!pdsSleepCnt) { - cfg->sleepForever = 0; - } else if ((pdsSleepCnt) && (pdsSleepCnt <= PDS_WARMUP_LATENCY_CNT)) { - return ERROR; - } else { - BL_WR_REG(PDS_BASE, PDS_TIME1, pdsSleepCnt - PDS_WARMUP_LATENCY_CNT); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD, tmpPd); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU, tmpPu); + BL_WR_REG(PDS_BASE, PDS_GPIO_SET_PU_PD, tmpVal); + } else { + /* GPIO23 - GPIO28 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_SET_PU_PD); + + switch (cfg) { + case PDS_PAD_CFG_PULL_NONE: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); + break; + + case PDS_PAD_CFG_PULL_DOWN: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); + break; + + case PDS_PAD_CFG_PULL_UP: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); + break; + + case PDS_PAD_CFG_ACTIVE_IE: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); + break; + + default: + break; } - /* PDS_CTL4 config */ - BL_WR_REG(PDS_BASE, PDS_CTL4, *(uint32_t *)cfg4); - - /* PDS_CTL config */ - if (cfg->pdsStart) { - BL_WR_REG(PDS_BASE, PDS_CTL, (*(uint32_t *)cfg & ~(1 << 0))); - BL_WR_REG(PDS_BASE, PDS_CTL, (*(uint32_t *)cfg | (1 << 0))); - } else { - BL_WR_REG(PDS_BASE, PDS_CTL, *(uint32_t *)cfg); - } + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD, tmpPd); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU, tmpPu); + BL_WR_REG(PDS_BASE, PDS_GPIO_SET_PU_PD, tmpVal); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief power down sleep force configure - * - * @param cfg2: power down sleep force configuration 1 - * @param cfg3: power down sleep force configuration 2 - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION PDS_Force_Config(PDS_CTL2_Type *cfg2, PDS_CTL3_Type *cfg3) -{ - /* PDS_CTL2 config */ - BL_WR_REG(PDS_BASE, PDS_CTL2, *(uint32_t *)cfg2); - - /* PDS_CTL3 config */ - BL_WR_REG(PDS_BASE, PDS_CTL3, *(uint32_t *)cfg3); - - return SUCCESS; + * @brief Enable power down sleep + * + * @param cfg: power down sleep configuration 1 + * @param cfg4: power down sleep configuration 2 + * @param pdsSleepCnt: power down sleep count cycle + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION PDS_App_Enable(PDS_CTL_Type *cfg, PDS_CTL4_Type *cfg4, uint32_t pdsSleepCnt) { + /* PDS sleep time 0 <=> sleep forever */ + /* PDS sleep time 1~PDS_WARMUP_LATENCY_CNT <=> error */ + /* PDS sleep time >PDS_WARMUP_LATENCY_CNT <=> correct */ + if (!pdsSleepCnt) { + cfg->sleepForever = 0; + } else if ((pdsSleepCnt) && (pdsSleepCnt <= PDS_WARMUP_LATENCY_CNT)) { + return ERROR; + } else { + BL_WR_REG(PDS_BASE, PDS_TIME1, pdsSleepCnt - PDS_WARMUP_LATENCY_CNT); + } + + /* PDS_CTL4 config */ + BL_WR_REG(PDS_BASE, PDS_CTL4, *(uint32_t *)cfg4); + + /* PDS_CTL config */ + if (cfg->pdsStart) { + BL_WR_REG(PDS_BASE, PDS_CTL, (*(uint32_t *)cfg & ~(1 << 0))); + BL_WR_REG(PDS_BASE, PDS_CTL, (*(uint32_t *)cfg | (1 << 0))); + } else { + BL_WR_REG(PDS_BASE, PDS_CTL, *(uint32_t *)cfg); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief power down sleep force configure - * - * @param defaultLvCfg: power down sleep default level configuration - * @param pdsSleepCnt: power down sleep time count - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION PDS_Default_Level_Config(PDS_DEFAULT_LV_CFG_Type *defaultLvCfg, uint32_t pdsSleepCnt) -{ - PDS_Force_Config((PDS_CTL2_Type *)&(defaultLvCfg->pdsCtl2), (PDS_CTL3_Type *)&(defaultLvCfg->pdsCtl3)); - PDS_App_Enable((PDS_CTL_Type *)&(defaultLvCfg->pdsCtl), (PDS_CTL4_Type *)&(defaultLvCfg->pdsCtl4), pdsSleepCnt); - - return SUCCESS; + * @brief power down sleep force configure + * + * @param cfg2: power down sleep force configuration 1 + * @param cfg3: power down sleep force configuration 2 + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION PDS_Force_Config(PDS_CTL2_Type *cfg2, PDS_CTL3_Type *cfg3) { + /* PDS_CTL2 config */ + BL_WR_REG(PDS_BASE, PDS_CTL2, *(uint32_t *)cfg2); + + /* PDS_CTL3 config */ + BL_WR_REG(PDS_BASE, PDS_CTL3, *(uint32_t *)cfg3); + + return SUCCESS; } /****************************************************************************/ /** - * @brief power down sleep int enable - * - * @param intType: PDS int type - * @param enable: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_IntEn(PDS_INT_Type intType, BL_Fun_Type enable) -{ - uint32_t offset = 0; - uint32_t tmpVal = 0; - - if ((intType < PDS_INT_PDS_SLEEP_CNT) || (intType > PDS_INT_KYS_QDEC)) { - return ERROR; - } - - switch (intType) { - case PDS_INT_WAKEUP: - case PDS_INT_RF_DONE: - case PDS_INT_PLL_DONE: - return ERROR; - - case PDS_INT_PDS_SLEEP_CNT: - offset = 16; - break; - - case PDS_INT_HBN_IRQ_OUT0: - offset = 17; - break; - - case PDS_INT_HBN_IRQ_OUT1: - offset = 18; - break; - - case PDS_INT_GPIO_IRQ: - offset = 19; - break; - - case PDS_INT_IRRX: - offset = 20; - break; - - case PDS_INT_BLE_SLP_IRQ: - offset = 21; - break; - - case PDS_INT_USB_WKUP: - offset = 22; - break; - - case PDS_INT_KYS_QDEC: - offset = 23; - break; - - case PDS_INT_MAX: - break; - - default: - break; - } - - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - - if (enable) { - tmpVal = tmpVal | (1 << offset); - } else { - tmpVal = tmpVal & ~(1 << offset); - } - - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); - - return SUCCESS; + * @brief power down sleep force configure + * + * @param defaultLvCfg: power down sleep default level configuration + * @param pdsSleepCnt: power down sleep time count + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION PDS_Default_Level_Config(PDS_DEFAULT_LV_CFG_Type *defaultLvCfg, uint32_t pdsSleepCnt) { + PDS_Force_Config((PDS_CTL2_Type *)&(defaultLvCfg->pdsCtl2), (PDS_CTL3_Type *)&(defaultLvCfg->pdsCtl3)); + PDS_App_Enable((PDS_CTL_Type *)&(defaultLvCfg->pdsCtl), (PDS_CTL4_Type *)&(defaultLvCfg->pdsCtl4), pdsSleepCnt); + + return SUCCESS; } /****************************************************************************/ /** - * @brief power down sleep int mask - * - * @param intType: PDS int type - * @param intMask: MASK or UNMASK - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_IntMask(PDS_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t offset = 0; - uint32_t tmpVal = 0; - - if (intType > PDS_INT_PLL_DONE) { - return ERROR; - } - - switch (intType) { - case PDS_INT_WAKEUP: - offset = 8; - break; - - case PDS_INT_RF_DONE: - offset = 10; - break; - - case PDS_INT_PLL_DONE: - offset = 11; - break; - - case PDS_INT_PDS_SLEEP_CNT: - case PDS_INT_HBN_IRQ_OUT0: - case PDS_INT_HBN_IRQ_OUT1: - case PDS_INT_GPIO_IRQ: - case PDS_INT_IRRX: - case PDS_INT_BLE_SLP_IRQ: - case PDS_INT_USB_WKUP: - case PDS_INT_KYS_QDEC: - case PDS_INT_MAX: - default: - return ERROR; - } - - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - - if (intMask != UNMASK) { - tmpVal = tmpVal | (1 << offset); - } else { - tmpVal = tmpVal & ~(1 << offset); - } - - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); - - return SUCCESS; -} + * @brief power down sleep int enable + * + * @param intType: PDS int type + * @param enable: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_IntEn(PDS_INT_Type intType, BL_Fun_Type enable) { + uint32_t offset = 0; + uint32_t tmpVal = 0; + + if ((intType < PDS_INT_PDS_SLEEP_CNT) || (intType > PDS_INT_KYS_QDEC)) { + return ERROR; + } -/****************************************************************************/ /** - * @brief get power down sleep int status - * - * @param intType: PDS int type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type PDS_Get_IntStatus(PDS_INT_Type intType) -{ - uint32_t offset = 0; + switch (intType) { + case PDS_INT_WAKEUP: + case PDS_INT_RF_DONE: + case PDS_INT_PLL_DONE: + return ERROR; - switch (intType) { - case PDS_INT_WAKEUP: - offset = 0; - break; + case PDS_INT_PDS_SLEEP_CNT: + offset = 16; + break; - case PDS_INT_RF_DONE: - offset = 2; - break; + case PDS_INT_HBN_IRQ_OUT0: + offset = 17; + break; - case PDS_INT_PLL_DONE: - offset = 3; - break; + case PDS_INT_HBN_IRQ_OUT1: + offset = 18; + break; - case PDS_INT_PDS_SLEEP_CNT: - offset = 24; - break; + case PDS_INT_GPIO_IRQ: + offset = 19; + break; - case PDS_INT_HBN_IRQ_OUT0: - offset = 25; - break; + case PDS_INT_IRRX: + offset = 20; + break; - case PDS_INT_HBN_IRQ_OUT1: - offset = 26; - break; + case PDS_INT_BLE_SLP_IRQ: + offset = 21; + break; - case PDS_INT_GPIO_IRQ: - offset = 27; - break; + case PDS_INT_USB_WKUP: + offset = 22; + break; - case PDS_INT_IRRX: - offset = 28; - break; + case PDS_INT_KYS_QDEC: + offset = 23; + break; - case PDS_INT_BLE_SLP_IRQ: - offset = 29; - break; + case PDS_INT_MAX: + break; - case PDS_INT_USB_WKUP: - offset = 30; - break; + default: + break; + } - case PDS_INT_KYS_QDEC: - offset = 31; - break; + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - case PDS_INT_MAX: - break; + if (enable) { + tmpVal = tmpVal | (1 << offset); + } else { + tmpVal = tmpVal & ~(1 << offset); + } - default: - break; - } + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); - return (BL_RD_REG(PDS_BASE, PDS_INT) & (1 << offset)) ? SET : RESET; + return SUCCESS; } /****************************************************************************/ /** - * @brief clear power down sleep int status - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_IntClear(void) -{ - uint32_t tmpVal = 0; + * @brief power down sleep int mask + * + * @param intType: PDS int type + * @param intMask: MASK or UNMASK + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_IntMask(PDS_INT_Type intType, BL_Mask_Type intMask) { + uint32_t offset = 0; + uint32_t tmpVal = 0; + + if (intType > PDS_INT_PLL_DONE) { + return ERROR; + } + + switch (intType) { + case PDS_INT_WAKEUP: + offset = 8; + break; + + case PDS_INT_RF_DONE: + offset = 10; + break; + + case PDS_INT_PLL_DONE: + offset = 11; + break; + + case PDS_INT_PDS_SLEEP_CNT: + case PDS_INT_HBN_IRQ_OUT0: + case PDS_INT_HBN_IRQ_OUT1: + case PDS_INT_GPIO_IRQ: + case PDS_INT_IRRX: + case PDS_INT_BLE_SLP_IRQ: + case PDS_INT_USB_WKUP: + case PDS_INT_KYS_QDEC: + case PDS_INT_MAX: + default: + return ERROR; + } - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CR_PDS_INT_CLR); - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CR_PDS_INT_CLR); - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + if (intMask != UNMASK) { + tmpVal = tmpVal | (1 << offset); + } else { + tmpVal = tmpVal & ~(1 << offset); + } - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CR_PDS_INT_CLR); - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief get power down sleep PLL status - * - * @param None - * - * @return PDS PLL status - * -*******************************************************************************/ -PDS_PLL_STS_Type PDS_Get_PdsPllStstus(void) -{ - return (PDS_PLL_STS_Type)BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_STAT), PDS_RO_PDS_PLL_STATE); + * @brief get power down sleep int status + * + * @param intType: PDS int type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type PDS_Get_IntStatus(PDS_INT_Type intType) { + uint32_t offset = 0; + + switch (intType) { + case PDS_INT_WAKEUP: + offset = 0; + break; + + case PDS_INT_RF_DONE: + offset = 2; + break; + + case PDS_INT_PLL_DONE: + offset = 3; + break; + + case PDS_INT_PDS_SLEEP_CNT: + offset = 24; + break; + + case PDS_INT_HBN_IRQ_OUT0: + offset = 25; + break; + + case PDS_INT_HBN_IRQ_OUT1: + offset = 26; + break; + + case PDS_INT_GPIO_IRQ: + offset = 27; + break; + + case PDS_INT_IRRX: + offset = 28; + break; + + case PDS_INT_BLE_SLP_IRQ: + offset = 29; + break; + + case PDS_INT_USB_WKUP: + offset = 30; + break; + + case PDS_INT_KYS_QDEC: + offset = 31; + break; + + case PDS_INT_MAX: + break; + + default: + break; + } + + return (BL_RD_REG(PDS_BASE, PDS_INT) & (1 << offset)) ? SET : RESET; } /****************************************************************************/ /** - * @brief get power down sleep RF status - * - * @param None - * - * @return PDS RF status - * -*******************************************************************************/ -PDS_RF_STS_Type PDS_Get_PdsRfStstus(void) -{ - return (PDS_RF_STS_Type)BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_STAT), PDS_RO_PDS_RF_STATE); + * @brief clear power down sleep int status + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_IntClear(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CR_PDS_INT_CLR); + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CR_PDS_INT_CLR); + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CR_PDS_INT_CLR); + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief get power down sleep status - * - * @param None - * - * @return PDS status - * -*******************************************************************************/ -PDS_STS_Type PDS_Get_PdsStstus(void) -{ - return (PDS_STS_Type)BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_STAT), PDS_RO_PDS_STATE); -} + * @brief get power down sleep PLL status + * + * @param None + * + * @return PDS PLL status + * + *******************************************************************************/ +PDS_PLL_STS_Type PDS_Get_PdsPllStstus(void) { return (PDS_PLL_STS_Type)BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_STAT), PDS_RO_PDS_PLL_STATE); } /****************************************************************************/ /** - * @brief power down sleep clear reset event - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_Clear_Reset_Event(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLR_RESET_EVENT); - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); - - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLR_RESET_EVENT); - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); - - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLR_RESET_EVENT); - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); - - return SUCCESS; -} + * @brief get power down sleep RF status + * + * @param None + * + * @return PDS RF status + * + *******************************************************************************/ +PDS_RF_STS_Type PDS_Get_PdsRfStstus(void) { return (PDS_RF_STS_Type)BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_STAT), PDS_RO_PDS_RF_STATE); } /****************************************************************************/ /** - * @brief get power down sleep reset event - * - * @param event: power down sleep reset event - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type PDS_Get_Reset_Event(PDS_RST_EVENT_Type event) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, PDS_RESET_EVENT); + * @brief get power down sleep status + * + * @param None + * + * @return PDS status + * + *******************************************************************************/ +PDS_STS_Type PDS_Get_PdsStstus(void) { return (PDS_STS_Type)BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_STAT), PDS_RO_PDS_STATE); } - return (tmpVal & (1 << event)) ? SET : RESET; +/****************************************************************************/ /** + * @brief power down sleep clear reset event + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_Clear_Reset_Event(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLR_RESET_EVENT); + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLR_RESET_EVENT); + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLR_RESET_EVENT); + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief set power down sleep VDDCORE gpio interrupt config - * - * @param src: PDS VDDCORE src pin num - * @param mode: PDS VDDCORE src pin interrupt type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_Set_Vddcore_GPIO_IntCfg(PDS_VDDCORE_GPIO_SRC_Type src, PDS_AON_GPIO_INT_Trigger_Type mode) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_PDS_VDDCORE_GPIO_SRC_TYPE(src)); - CHECK_PARAM(IS_PDS_AON_GPIO_INT_Trigger_TYPE(mode)); - - tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_GPIO_INT_SELECT, src); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_GPIO_INT_MODE, mode); - BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); - - return SUCCESS; + * @brief get power down sleep reset event + * + * @param event: power down sleep reset event + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type PDS_Get_Reset_Event(PDS_RST_EVENT_Type event) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, PDS_RESET_EVENT); + + return (tmpVal & (1 << event)) ? SET : RESET; } /****************************************************************************/ /** - * @brief set power down sleep VDDCORE gpio interrupt mask - * - * @param intMask: None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_Set_Vddcore_GPIO_IntMask(BL_Mask_Type intMask) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); - - if (intMask != UNMASK) { - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_GPIO_INT_MASK); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_GPIO_INT_MASK); - } - - BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); - - return SUCCESS; + * @brief set power down sleep VDDCORE gpio interrupt config + * + * @param src: PDS VDDCORE src pin num + * @param mode: PDS VDDCORE src pin interrupt type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_Set_Vddcore_GPIO_IntCfg(PDS_VDDCORE_GPIO_SRC_Type src, PDS_AON_GPIO_INT_Trigger_Type mode) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_PDS_VDDCORE_GPIO_SRC_TYPE(src)); + CHECK_PARAM(IS_PDS_AON_GPIO_INT_Trigger_TYPE(mode)); + + tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_GPIO_INT_SELECT, src); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_GPIO_INT_MODE, mode); + BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief set power down sleep VDDCORE gpio interrupt mask - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Sts_Type PDS_Get_Vddcore_GPIO_IntStatus(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_GPIO_INT), PDS_GPIO_INT_STAT) ? SET : RESET; + * @brief set power down sleep VDDCORE gpio interrupt mask + * + * @param intMask: None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_Set_Vddcore_GPIO_IntMask(BL_Mask_Type intMask) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); + + if (intMask != UNMASK) { + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_GPIO_INT_MASK); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_GPIO_INT_MASK); + } + + BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief set power down sleep VDDCORE gpio interrupt mask - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_Set_Vddcore_GPIO_IntClear(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_GPIO_INT_CLR); - BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); - - tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_GPIO_INT_CLR); - BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); + * @brief set power down sleep VDDCORE gpio interrupt mask + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Sts_Type PDS_Get_Vddcore_GPIO_IntStatus(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_GPIO_INT), PDS_GPIO_INT_STAT) ? SET : RESET; } - tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_GPIO_INT_CLR); - BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); - - return SUCCESS; +/****************************************************************************/ /** + * @brief set power down sleep VDDCORE gpio interrupt mask + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_Set_Vddcore_GPIO_IntClear(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_GPIO_INT_CLR); + BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); + + tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_GPIO_INT_CLR); + BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); + + tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_GPIO_INT_CLR); + BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Install PDS interrupt callback function - * - * @param intType: PDS int type - * @param cbFun: cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_Int_Callback_Install(PDS_INT_Type intType, intCallback_Type *cbFun) -{ - pdsIntCbfArra[intType][0] = cbFun; - - return SUCCESS; + * @brief Install PDS interrupt callback function + * + * @param intType: PDS int type + * @param cbFun: cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_Int_Callback_Install(PDS_INT_Type intType, intCallback_Type *cbFun) { + pdsIntCbfArra[intType][0] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief Trim RC32M - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Trim RC32M + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Trim_RC32M(void) -{ - Efuse_Ana_RC32M_Trim_Type trim; - int32_t tmpVal = 0; - - EF_Ctrl_Read_RC32M_Trim(&trim); - - if (trim.trimRc32mExtCodeEn) { - if (trim.trimRc32mCodeFrExtParity == EF_Ctrl_Get_Trim_Parity(trim.trimRc32mCodeFrExt, 8)) { - tmpVal = BL_RD_REG(PDS_BASE, PDS_RC32M_CTRL0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_RC32M_CODE_FR_EXT, trim.trimRc32mCodeFrExt); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_RC32M_EXT_CODE_EN); - BL_WR_REG(PDS_BASE, PDS_RC32M_CTRL0, tmpVal); - BL702_Delay_US(2); - return SUCCESS; - } +BL_Err_Type ATTR_CLOCK_SECTION PDS_Trim_RC32M(void) { + Efuse_Ana_RC32M_Trim_Type trim; + int32_t tmpVal = 0; + + EF_Ctrl_Read_RC32M_Trim(&trim); + + if (trim.trimRc32mExtCodeEn) { + if (trim.trimRc32mCodeFrExtParity == EF_Ctrl_Get_Trim_Parity(trim.trimRc32mCodeFrExt, 8)) { + tmpVal = BL_RD_REG(PDS_BASE, PDS_RC32M_CTRL0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_RC32M_CODE_FR_EXT, trim.trimRc32mCodeFrExt); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_RC32M_EXT_CODE_EN); + BL_WR_REG(PDS_BASE, PDS_RC32M_CTRL0, tmpVal); + BL702_Delay_US(2); + return SUCCESS; } + } - return ERROR; + return ERROR; } #endif /****************************************************************************/ /** - * @brief Select RC32M as PLL ref source - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Select RC32M as PLL ref source + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Select_RC32M_As_PLL_Ref(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Select_RC32M_As_PLL_Ref(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_XTAL_RC32M_SEL); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_XTAL_RC32M_SEL); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Select XTAL as PLL ref source - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Select XTAL as PLL ref source + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Select_XTAL_As_PLL_Ref(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Select_XTAL_As_PLL_Ref(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_XTAL_RC32M_SEL); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_XTAL_RC32M_SEL); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Power on PLL - * - * @param xtalType: xtal type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Power on PLL + * + * @param xtalType: xtal type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Power_On_PLL(PDS_PLL_XTAL_Type xtalType) -{ - uint32_t tmpVal = 0; - - /* Check parameter*/ - CHECK_PARAM(IS_PDS_PLL_XTAL_TYPE(xtalType)); - - /**************************/ - /* select PLL XTAL source */ - /**************************/ - - if ((xtalType == PDS_PLL_XTAL_RC32M) || (xtalType == PDS_PLL_XTAL_NONE)) { - PDS_Trim_RC32M(); - PDS_Select_RC32M_As_PLL_Ref(); - } else { - PDS_Select_XTAL_As_PLL_Ref(); - } - - /*******************************************/ - /* PLL power down first, not indispensable */ - /*******************************************/ - /* power off PLL first, this step is not indispensable */ - PDS_Power_Off_PLL(); - - /********************/ - /* PLL param config */ - /********************/ - - /* clkpll_icp_1u */ - /* clkpll_icp_5u */ - /* clkpll_int_frac_sw */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_CP); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_ICP_1U, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_ICP_5U, 2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_INT_FRAC_SW, 0); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_CP, tmpVal); - - /* clkpll_c3 */ - /* clkpll_cz */ - /* clkpll_rz */ - /* clkpll_r4 */ - /* clkpll_r4_short */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_RZ); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_C3, 3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_CZ, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_RZ, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_R4_SHORT, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_R4, 2); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_RZ, tmpVal); - - /* clkpll_refdiv_ratio */ - /* clkpll_postdiv */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_POSTDIV, 0x14); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_REFDIV_RATIO, 2); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); - - /* clkpll_sdmin */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_SDM); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SDMIN, 0x3C0000); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_SDM, tmpVal); - - /* clkpll_sel_fb_clk */ - /* clkpll_sel_sample_clk can be 0/1, default is 1 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_FBDV); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SEL_FB_CLK, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SEL_SAMPLE_CLK, 1); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_FBDV, tmpVal); - - /*************************/ - /* PLL power up sequence */ - /*************************/ - - /* pu_clkpll_sfreg=1 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_PU_CLKPLL_SFREG); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - - BL702_Delay_US(5); - - /* pu_clkpll=1 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_PU_CLKPLL); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - - /* clkpll_pu_cp=1 */ - /* clkpll_pu_pfd=1 */ - /* clkpll_pu_fbdv=1 */ - /* clkpll_pu_postdiv=1 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_CP); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_PFD); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_FBDV); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_POSTDIV); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - - BL702_Delay_US(5); - - /* clkpll_sdm_reset=1 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_SDM_RESET); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - BL702_Delay_US(1); - /* clkpll_reset_fbdv=1 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_RESET_FBDV); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - BL702_Delay_US(2); - /* clkpll_reset_fbdv=0 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_RESET_FBDV); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - BL702_Delay_US(1); - /* clkpll_sdm_reset=0 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_SDM_RESET); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - - return SUCCESS; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Power_On_PLL(PDS_PLL_XTAL_Type xtalType) { + uint32_t tmpVal = 0; + + /* Check parameter*/ + CHECK_PARAM(IS_PDS_PLL_XTAL_TYPE(xtalType)); + + /**************************/ + /* select PLL XTAL source */ + /**************************/ + + if ((xtalType == PDS_PLL_XTAL_RC32M) || (xtalType == PDS_PLL_XTAL_NONE)) { + PDS_Trim_RC32M(); + PDS_Select_RC32M_As_PLL_Ref(); + } else { + PDS_Select_XTAL_As_PLL_Ref(); + } + + /*******************************************/ + /* PLL power down first, not indispensable */ + /*******************************************/ + /* power off PLL first, this step is not indispensable */ + PDS_Power_Off_PLL(); + + /********************/ + /* PLL param config */ + /********************/ + + /* clkpll_icp_1u */ + /* clkpll_icp_5u */ + /* clkpll_int_frac_sw */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_CP); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_ICP_1U, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_ICP_5U, 2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_INT_FRAC_SW, 0); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_CP, tmpVal); + + /* clkpll_c3 */ + /* clkpll_cz */ + /* clkpll_rz */ + /* clkpll_r4 */ + /* clkpll_r4_short */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_RZ); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_C3, 3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_CZ, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_RZ, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_R4_SHORT, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_R4, 2); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_RZ, tmpVal); + + /* clkpll_refdiv_ratio */ + /* clkpll_postdiv */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_POSTDIV, 0x14); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_REFDIV_RATIO, 2); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); + + /* clkpll_sdmin */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_SDM); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SDMIN, 0x3C0000); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_SDM, tmpVal); + + /* clkpll_sel_fb_clk */ + /* clkpll_sel_sample_clk can be 0/1, default is 1 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_FBDV); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SEL_FB_CLK, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SEL_SAMPLE_CLK, 1); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_FBDV, tmpVal); + + /*************************/ + /* PLL power up sequence */ + /*************************/ + + /* pu_clkpll_sfreg=1 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_PU_CLKPLL_SFREG); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + + BL702_Delay_US(5); + + /* pu_clkpll=1 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_PU_CLKPLL); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + + /* clkpll_pu_cp=1 */ + /* clkpll_pu_pfd=1 */ + /* clkpll_pu_fbdv=1 */ + /* clkpll_pu_postdiv=1 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_CP); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_PFD); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_FBDV); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_POSTDIV); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + + BL702_Delay_US(5); + + /* clkpll_sdm_reset=1 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_SDM_RESET); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + BL702_Delay_US(1); + /* clkpll_reset_fbdv=1 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_RESET_FBDV); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + BL702_Delay_US(2); + /* clkpll_reset_fbdv=0 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_RESET_FBDV); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + BL702_Delay_US(1); + /* clkpll_sdm_reset=0 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_SDM_RESET); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + + return SUCCESS; } #endif /** PLL output config **/ @@ -901,451 +870,420 @@ BL_Err_Type ATTR_CLOCK_SECTION PDS_Power_On_PLL(PDS_PLL_XTAL_Type xtalType) */ /****************************************************************************/ /** - * @brief Enable all PLL clock - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Enable all PLL clock + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Enable_PLL_All_Clks(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Enable_PLL_All_Clks(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); - tmpVal |= 0x1FF; - BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); + tmpVal |= 0x1FF; + BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Disable all PLL clock - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Disable all PLL clock + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Disable_PLL_All_Clks(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Disable_PLL_All_Clks(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); - tmpVal &= (~0x1FF); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); + tmpVal &= (~0x1FF); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Enable PLL clock - * - * @param pllClk: PLL clock type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Enable PLL clock + * + * @param pllClk: PLL clock type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Enable_PLL_Clk(PDS_PLL_CLK_Type pllClk) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Enable_PLL_Clk(PDS_PLL_CLK_Type pllClk) { + uint32_t tmpVal = 0; - /* Check parameter*/ - CHECK_PARAM(IS_PDS_PLL_CLK_TYPE(pllClk)); + /* Check parameter*/ + CHECK_PARAM(IS_PDS_PLL_CLK_TYPE(pllClk)); - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); - tmpVal |= (1 << pllClk); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); + tmpVal |= (1 << pllClk); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Disable PLL clock - * - * @param pllClk: PLL clock type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Disable PLL clock + * + * @param pllClk: PLL clock type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Disable_PLL_Clk(PDS_PLL_CLK_Type pllClk) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Disable_PLL_Clk(PDS_PLL_CLK_Type pllClk) { + uint32_t tmpVal = 0; - /* Check parameter*/ - CHECK_PARAM(IS_PDS_PLL_CLK_TYPE(pllClk)); + /* Check parameter*/ + CHECK_PARAM(IS_PDS_PLL_CLK_TYPE(pllClk)); - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); - tmpVal &= (~(1 << pllClk)); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); + tmpVal &= (~(1 << pllClk)); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Power off PLL - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Power off PLL + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Power_Off_PLL(void) -{ - uint32_t tmpVal = 0; - - /* pu_clkpll_sfreg=0 */ - /* pu_clkpll=0 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_PU_CLKPLL_SFREG); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_PU_CLKPLL); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - - /* clkpll_pu_cp=0 */ - /* clkpll_pu_pfd=0 */ - /* clkpll_pu_fbdv=0 */ - /* clkpll_pu_postdiv=0 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_CP); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_PFD); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_FBDV); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_POSTDIV); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - - return SUCCESS; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Power_Off_PLL(void) { + uint32_t tmpVal = 0; + + /* pu_clkpll_sfreg=0 */ + /* pu_clkpll=0 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_PU_CLKPLL_SFREG); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_PU_CLKPLL); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + + /* clkpll_pu_cp=0 */ + /* clkpll_pu_pfd=0 */ + /* clkpll_pu_fbdv=0 */ + /* clkpll_pu_postdiv=0 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_CP); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_PFD); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_FBDV); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_POSTDIV); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Set Audio PLL clock - * - * @param audioPLLFreq: Audio PLL sel frequency , have two vaild input 12.288 or 11.289 MHZ - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Set Audio PLL clock + * + * @param audioPLLFreq: Audio PLL sel frequency , have two vaild input 12.288 or 11.289 MHZ + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Set_Audio_PLL_Freq(PDS_AUDIO_PLL_Type audioPLLFreq) -{ - uint32_t sdmin_table[] = { 0x374BC6, 0x32CCED, 0x32CCED, 0x6E978D, 0x6C0000 }; - uint32_t tmpVal = 0; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Set_Audio_PLL_Freq(PDS_AUDIO_PLL_Type audioPLLFreq) { + uint32_t sdmin_table[] = {0x374BC6, 0x32CCED, 0x32CCED, 0x6E978D, 0x6C0000}; + uint32_t tmpVal = 0; - CHECK_PARAM(IS_PDS_AUDIO_PLL_TYPE(audioPLLFreq)); + CHECK_PARAM(IS_PDS_AUDIO_PLL_TYPE(audioPLLFreq)); - /*set PDS_CLKPLL_REFDIV_RATIO as 0x2 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_REFDIV_RATIO, 0x2); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); + /*set PDS_CLKPLL_REFDIV_RATIO as 0x2 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_REFDIV_RATIO, 0x2); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); - /*set clkpll_sdmin as sdmin*/ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_SDM); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SDMIN, (uint32_t)sdmin_table[audioPLLFreq % (sizeof(sdmin_table) / sizeof(sdmin_table[0]))]); + /*set clkpll_sdmin as sdmin*/ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_SDM); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SDMIN, (uint32_t)sdmin_table[audioPLLFreq % (sizeof(sdmin_table) / sizeof(sdmin_table[0]))]); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_SDM, tmpVal); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_SDM, tmpVal); - /*reset pll */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + /*reset pll */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_PU_CLKPLL_SFREG, 1); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_PU_CLKPLL_SFREG, 1); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - BL702_Delay_MS(10); + BL702_Delay_MS(10); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_PU_CLKPLL, 1); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_PU_CLKPLL, 1); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_RESET_FBDV, 1); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_RESET_FBDV, 1); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - BL702_Delay_MS(10); + BL702_Delay_MS(10); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_RESET_FBDV, 0); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_RESET_FBDV, 0); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - /*set div for audio pll */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); + /*set div for audio pll */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); - if (audioPLLFreq != AUDIO_PLL_5644800_HZ) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_POSTDIV, 36); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_POSTDIV, 72); - } + if (audioPLLFreq != AUDIO_PLL_5644800_HZ) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_POSTDIV, 36); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_POSTDIV, 72); + } - BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief PDS software reset - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief PDS software reset + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION PDS_Reset(void) -{ - uint32_t tmpVal = 0; +void ATTR_TCM_SECTION PDS_Reset(void) { + uint32_t tmpVal = 0; - tmpVal = *(uint32_t *)0x40000010; - tmpVal = tmpVal | (1 << 14); - *(uint32_t *)0x40000010 = tmpVal; + tmpVal = *(uint32_t *)0x40000010; + tmpVal = tmpVal | (1 << 14); + *(uint32_t *)0x40000010 = tmpVal; - tmpVal = *(uint32_t *)0x40000010; - tmpVal = tmpVal & ~(1 << 14); - *(uint32_t *)0x40000010 = tmpVal; + tmpVal = *(uint32_t *)0x40000010; + tmpVal = tmpVal & ~(1 << 14); + *(uint32_t *)0x40000010 = tmpVal; } #endif /****************************************************************************/ /** - * @brief Enable power down sleep - * - * @param cfg: power down sleep configuration 1 - * @param pdsSleepCnt: power down sleep count cycle - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Enable power down sleep + * + * @param cfg: power down sleep configuration 1 + * @param pdsSleepCnt: power down sleep count cycle + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION PDS_Enable(PDS_CFG_Type *cfg, uint32_t pdsSleepCnt) -{ - uint32_t *p = (uint32_t *)cfg; +void ATTR_TCM_SECTION PDS_Enable(PDS_CFG_Type *cfg, uint32_t pdsSleepCnt) { + uint32_t *p = (uint32_t *)cfg; - if (pdsSleepCnt - PDS_WARMUP_CNT <= 0) { - return; - } + if (pdsSleepCnt - PDS_WARMUP_CNT <= 0) { + return; + } - BL_WR_REG(PDS_BASE, PDS_TIME1, pdsSleepCnt - PDS_WARMUP_CNT); + BL_WR_REG(PDS_BASE, PDS_TIME1, pdsSleepCnt - PDS_WARMUP_CNT); - /* Set PDS control register */ - BL_WR_REG(PDS_BASE, PDS_CTL, *p); + /* Set PDS control register */ + BL_WR_REG(PDS_BASE, PDS_CTL, *p); } #endif /****************************************************************************/ /** - * @brief PDS Auto mode wake up counter config - * - * @param sleepDuration: sleep time, total pds = sleep_duration + max_warmup_cnt (32K clock cycles), - * recommend maxWarmCnt*N+2 - * - * @return None - * -*******************************************************************************/ + * @brief PDS Auto mode wake up counter config + * + * @param sleepDuration: sleep time, total pds = sleep_duration + max_warmup_cnt (32K clock cycles), + * recommend maxWarmCnt*N+2 + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION PDS_Auto_Time_Config(uint32_t sleepDuration) -{ - /* PDS_TIME1 */ - BL_WR_REG(PDS_BASE, PDS_TIME1, sleepDuration); +void ATTR_TCM_SECTION PDS_Auto_Time_Config(uint32_t sleepDuration) { + /* PDS_TIME1 */ + BL_WR_REG(PDS_BASE, PDS_TIME1, sleepDuration); } #endif /****************************************************************************/ /** - * @brief PDS Auto mode config and enable - * - * @param powerCfg: PDS Auto mode power domain config - * @param normalCfg: PDS Auto mode power normal config - * @param enable: PDS Auto mode Enable or Disable - * - * @return None - * -*******************************************************************************/ + * @brief PDS Auto mode config and enable + * + * @param powerCfg: PDS Auto mode power domain config + * @param normalCfg: PDS Auto mode power normal config + * @param enable: PDS Auto mode Enable or Disable + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION PDS_Auto_Enable(PDS_AUTO_POWER_DOWN_CFG_Type *powerCfg, PDS_AUTO_NORMAL_CFG_Type *normalCfg, BL_Fun_Type enable) -{ - uint32_t pdsCtl = 0; - - CHECK_PARAM(IS_PDS_LDO_VOLTAGE_TYPE(normalCfg->vddcoreVol)); - - /* power config */ - pdsCtl |= (powerCfg->mbgPower << 31) | - (powerCfg->ldo18rfPower << 30) | - (powerCfg->sfregPower << 29) | - (powerCfg->pllPower << 28) | - (powerCfg->cpu0Power << 19) | - (powerCfg->rc32mPower << 17) | - (powerCfg->xtalPower << 14) | - (powerCfg->allPower << 13) | - (powerCfg->isoPower << 11) | - (powerCfg->bzPower << 10) | - (powerCfg->sramDisStanby << 9) | - (powerCfg->cgPower << 8) | - (powerCfg->cpu1Power << 7) | - (powerCfg->usbPower << 3); - pdsCtl = BL_SET_REG_BITS_VAL(pdsCtl, PDS_CR_PDS_LDO_VOL, normalCfg->vddcoreVol); - pdsCtl |= (normalCfg->vddcoreVolEn << 18) | - (normalCfg->cpu0NotNeedWFI << 21) | - (normalCfg->cpu1NotNeedWFI << 20) | - (normalCfg->busReset << 16) | - (normalCfg->disIrqWakeUp << 15) | - (normalCfg->powerOffXtalForever << 2) | - (normalCfg->sleepForever << 1); - BL_WR_REG(PDS_BASE, PDS_CTL, pdsCtl); - - pdsCtl = BL_RD_REG(PDS_BASE, PDS_CTL); - - if (enable) { - pdsCtl |= (1 << 0); - } else { - pdsCtl &= ~(1 << 0); - } +void ATTR_TCM_SECTION PDS_Auto_Enable(PDS_AUTO_POWER_DOWN_CFG_Type *powerCfg, PDS_AUTO_NORMAL_CFG_Type *normalCfg, BL_Fun_Type enable) { + uint32_t pdsCtl = 0; + + CHECK_PARAM(IS_PDS_LDO_VOLTAGE_TYPE(normalCfg->vddcoreVol)); + + /* power config */ + pdsCtl |= (powerCfg->mbgPower << 31) | (powerCfg->ldo18rfPower << 30) | (powerCfg->sfregPower << 29) | (powerCfg->pllPower << 28) | (powerCfg->cpu0Power << 19) | (powerCfg->rc32mPower << 17) + | (powerCfg->xtalPower << 14) | (powerCfg->allPower << 13) | (powerCfg->isoPower << 11) | (powerCfg->bzPower << 10) | (powerCfg->sramDisStanby << 9) | (powerCfg->cgPower << 8) + | (powerCfg->cpu1Power << 7) | (powerCfg->usbPower << 3); + pdsCtl = BL_SET_REG_BITS_VAL(pdsCtl, PDS_CR_PDS_LDO_VOL, normalCfg->vddcoreVol); + pdsCtl |= (normalCfg->vddcoreVolEn << 18) | (normalCfg->cpu0NotNeedWFI << 21) | (normalCfg->cpu1NotNeedWFI << 20) | (normalCfg->busReset << 16) | (normalCfg->disIrqWakeUp << 15) + | (normalCfg->powerOffXtalForever << 2) | (normalCfg->sleepForever << 1); + BL_WR_REG(PDS_BASE, PDS_CTL, pdsCtl); + + pdsCtl = BL_RD_REG(PDS_BASE, PDS_CTL); - BL_WR_REG(PDS_BASE, PDS_CTL, pdsCtl); + if (enable) { + pdsCtl |= (1 << 0); + } else { + pdsCtl &= ~(1 << 0); + } + + BL_WR_REG(PDS_BASE, PDS_CTL, pdsCtl); } #endif /****************************************************************************/ /** - * @brief PDS force turn off XXX domain - * - * @param domain: PDS domain - * - * @return None - * -*******************************************************************************/ + * @brief PDS force turn off XXX domain + * + * @param domain: PDS domain + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION PDS_Manual_Force_Turn_Off(PDS_FORCE_Type domain) -{ - uint32_t tmpVal = 0; - - /* memory sleep */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal |= 1 << (domain + PDS_FORCE_MEM_STBY_OFFSET); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* gate clock */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal |= 1 << (domain + PDS_FORCE_GATE_CLK_OFFSET); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* pds reset */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal |= 1 << (domain + PDS_FORCE_PDS_RST_OFFSET); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* isolation on */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal |= 1 << (domain + PDS_FORCE_ISO_EN_OFFSET); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* power off */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal |= 1 << (domain + PDS_FORCE_PWR_OFF_OFFSET); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); +void ATTR_TCM_SECTION PDS_Manual_Force_Turn_Off(PDS_FORCE_Type domain) { + uint32_t tmpVal = 0; + + /* memory sleep */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal |= 1 << (domain + PDS_FORCE_MEM_STBY_OFFSET); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* gate clock */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal |= 1 << (domain + PDS_FORCE_GATE_CLK_OFFSET); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* pds reset */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal |= 1 << (domain + PDS_FORCE_PDS_RST_OFFSET); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* isolation on */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal |= 1 << (domain + PDS_FORCE_ISO_EN_OFFSET); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* power off */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal |= 1 << (domain + PDS_FORCE_PWR_OFF_OFFSET); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); } #endif /****************************************************************************/ /** - * @brief PDS force turn on XXX domain - * - * @param domain: PDS domain - * - * @return None - * -*******************************************************************************/ + * @brief PDS force turn on XXX domain + * + * @param domain: PDS domain + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION PDS_Manual_Force_Turn_On(PDS_FORCE_Type domain) -{ - uint32_t tmpVal = 0; - - /* power on */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal &= ~(1 << (domain + PDS_FORCE_PWR_OFF_OFFSET)); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* isolation off */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal &= ~(1 << (domain + PDS_FORCE_ISO_EN_OFFSET)); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* pds de_reset */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal &= ~(1 << (domain + PDS_FORCE_PDS_RST_OFFSET)); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* memory active */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal &= ~(1 << (domain + PDS_FORCE_MEM_STBY_OFFSET)); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* clock on */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal &= ~(1 << (domain + PDS_FORCE_GATE_CLK_OFFSET)); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); +void ATTR_TCM_SECTION PDS_Manual_Force_Turn_On(PDS_FORCE_Type domain) { + uint32_t tmpVal = 0; + + /* power on */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal &= ~(1 << (domain + PDS_FORCE_PWR_OFF_OFFSET)); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* isolation off */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal &= ~(1 << (domain + PDS_FORCE_ISO_EN_OFFSET)); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* pds de_reset */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal &= ~(1 << (domain + PDS_FORCE_PDS_RST_OFFSET)); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* memory active */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal &= ~(1 << (domain + PDS_FORCE_MEM_STBY_OFFSET)); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* clock on */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal &= ~(1 << (domain + PDS_FORCE_GATE_CLK_OFFSET)); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); } #endif /****************************************************************************/ /** - * @brief Power down sleep wake up interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ -void PDS_WAKEUP_IRQHandler(void) -{ - for (PDS_INT_Type intType = PDS_INT_WAKEUP; intType < PDS_INT_MAX; intType++) { - if (PDS_Get_IntStatus(intType) && (pdsIntCbfArra[intType][0] != NULL)) { - pdsIntCbfArra[intType][0](); - } + * @brief Power down sleep wake up interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ +void PDS_WAKEUP_IRQHandler(void) { + for (PDS_INT_Type intType = PDS_INT_WAKEUP; intType < PDS_INT_MAX; intType++) { + if (PDS_Get_IntStatus(intType) && (pdsIntCbfArra[intType][0] != NULL)) { + pdsIntCbfArra[intType][0](); } - PDS_Set_Vddcore_GPIO_IntClear(); - PDS_IntClear(); + } + PDS_Set_Vddcore_GPIO_IntClear(); + PDS_IntClear(); } /****************************************************************************/ /** - * @brief PDS wakeup IRQHandler install - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_WAKEUP_IRQHandler_Install(void) -{ - Interrupt_Handler_Register(PDS_WAKEUP_IRQn, PDS_WAKEUP_IRQHandler); - return SUCCESS; + * @brief PDS wakeup IRQHandler install + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_WAKEUP_IRQHandler_Install(void) { + Interrupt_Handler_Register(PDS_WAKEUP_IRQn, PDS_WAKEUP_IRQHandler); + return SUCCESS; } /****************************************************************************/ /** - * @brief - * - * @param - * - * @return - * -*******************************************************************************/ -BL_Err_Type PDS_Set_Clkpll_Top_Ctrl(uint8_t vg11Sel) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); - //clkpll_vg11_sel - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_VG11_SEL, vg11Sel); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); - - return SUCCESS; + * @brief + * + * @param + * + * @return + * + *******************************************************************************/ +BL_Err_Type PDS_Set_Clkpll_Top_Ctrl(uint8_t vg11Sel) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); + // clkpll_vg11_sel + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_VG11_SEL, vg11Sel); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); + + return SUCCESS; } /*@} end of group PDS_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_psram.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_psram.c index a56c2d1057..e2fb744d46 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_psram.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_psram.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_psram.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_psram.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_psram.h" #include "bl702_l1c.h" @@ -86,674 +86,648 @@ */ /****************************************************************************/ /** - * @brief Init serial psram control interface - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param cmdsCfg: Serial Serial Flash controller configuration pointer - * @param sfCtrlPsramCfg: Serial psram controller configuration pointer - * - * @return None - * -*******************************************************************************/ -//#ifndef BFLB_USE_ROM_DRIVER + * @brief Init serial psram control interface + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param cmdsCfg: Serial Serial Flash controller configuration pointer + * @param sfCtrlPsramCfg: Serial psram controller configuration pointer + * + * @return None + * + *******************************************************************************/ +// #ifndef BFLB_USE_ROM_DRIVER //__WEAK -void ATTR_TCM_SECTION Psram_Init(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_Cmds_Cfg *cmdsCfg, SF_Ctrl_Psram_Cfg *sfCtrlPsramCfg) -{ - SF_Ctrl_Psram_Init(sfCtrlPsramCfg); - SF_Ctrl_Cmds_Set(cmdsCfg); +void ATTR_TCM_SECTION Psram_Init(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_Cmds_Cfg *cmdsCfg, SF_Ctrl_Psram_Cfg *sfCtrlPsramCfg) { + SF_Ctrl_Psram_Init(sfCtrlPsramCfg); + SF_Ctrl_Cmds_Set(cmdsCfg); - Psram_SetDriveStrength(psramCfg); - Psram_SetBurstWrap(psramCfg); + Psram_SetDriveStrength(psramCfg); + Psram_SetBurstWrap(psramCfg); } -//#endif +// #endif /****************************************************************************/ /** - * @brief Read psram register - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param regValue: Register value pointer to store data - * - * @return None - * -*******************************************************************************/ + * @brief Read psram register + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param regValue: Register value pointer to store data + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION Psram_ReadReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) -{ - /* Check the parameters */ - CHECK_PARAM(IS_PSRAM_CTRL_MODE(psramCfg->ctrlMode)); +void ATTR_TCM_SECTION Psram_ReadReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) { + /* Check the parameters */ + CHECK_PARAM(IS_PSRAM_CTRL_MODE(psramCfg->ctrlMode)); - uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; - SF_Ctrl_Cmd_Cfg_Type psramCmd; + uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; + SF_Ctrl_Cmd_Cfg_Type psramCmd; - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } - if (psramCfg->ctrlMode == PSRAM_QPI_CTRL_MODE) { - psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - } + if (psramCfg->ctrlMode == PSRAM_QPI_CTRL_MODE) { + psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + } - psramCmd.cmdBuf[0] = (psramCfg->readRegCmd) << 24; - psramCmd.rwFlag = SF_CTRL_READ; - psramCmd.addrSize = 3; - psramCmd.dummyClks = psramCfg->readRegDmyClk; - psramCmd.nbData = 1; + psramCmd.cmdBuf[0] = (psramCfg->readRegCmd) << 24; + psramCmd.rwFlag = SF_CTRL_READ; + psramCmd.addrSize = 3; + psramCmd.dummyClks = psramCfg->readRegDmyClk; + psramCmd.nbData = 1; - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) { - } + while (SET == SF_Ctrl_GetBusyState()) {} - BL702_MemCpy(regValue, psramCtrlBuf, 1); + BL702_MemCpy(regValue, psramCtrlBuf, 1); } #endif /****************************************************************************/ /** - * @brief Write psram register - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param regValue: Register value pointer storing data - * - * @return None - * -*******************************************************************************/ + * @brief Write psram register + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param regValue: Register value pointer storing data + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION Psram_WriteReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) -{ - /* Check the parameters */ - CHECK_PARAM(IS_PSRAM_CTRL_MODE(psramCfg->ctrlMode)); +void ATTR_TCM_SECTION Psram_WriteReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) { + /* Check the parameters */ + CHECK_PARAM(IS_PSRAM_CTRL_MODE(psramCfg->ctrlMode)); - uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; - SF_Ctrl_Cmd_Cfg_Type psramCmd; + uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; + SF_Ctrl_Cmd_Cfg_Type psramCmd; - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } - BL702_MemCpy(psramCtrlBuf, regValue, 1); + BL702_MemCpy(psramCtrlBuf, regValue, 1); - if (psramCfg->ctrlMode == PSRAM_QPI_CTRL_MODE) { - psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - } + if (psramCfg->ctrlMode == PSRAM_QPI_CTRL_MODE) { + psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + } - psramCmd.cmdBuf[0] = (psramCfg->writeRegCmd) << 24; - psramCmd.rwFlag = SF_CTRL_WRITE; - psramCmd.addrSize = 3; - psramCmd.nbData = 1; + psramCmd.cmdBuf[0] = (psramCfg->writeRegCmd) << 24; + psramCmd.rwFlag = SF_CTRL_WRITE; + psramCmd.addrSize = 3; + psramCmd.nbData = 1; - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); } #endif /****************************************************************************/ /** - * @brief Set psram driver strength - * - * @param psramCfg: Serial psram parameter configuration pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Set psram driver strength + * + * @param psramCfg: Serial psram parameter configuration pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_SetDriveStrength(SPI_Psram_Cfg_Type *psramCfg) -{ - uint32_t stat = 0; - /* Check the parameters */ - CHECK_PARAM(IS_PSRAM_DRIVE_STRENGTH(psramCfg->driveStrength)); +BL_Err_Type ATTR_TCM_SECTION Psram_SetDriveStrength(SPI_Psram_Cfg_Type *psramCfg) { + uint32_t stat = 0; + /* Check the parameters */ + CHECK_PARAM(IS_PSRAM_DRIVE_STRENGTH(psramCfg->driveStrength)); - Psram_ReadReg(psramCfg, (uint8_t *)&stat); + Psram_ReadReg(psramCfg, (uint8_t *)&stat); - if ((stat & 0x3) == psramCfg->driveStrength) { - return SUCCESS; - } + if ((stat & 0x3) == psramCfg->driveStrength) { + return SUCCESS; + } - stat &= (~0x3); - stat |= psramCfg->driveStrength; + stat &= (~0x3); + stat |= psramCfg->driveStrength; - Psram_WriteReg(psramCfg, (uint8_t *)&stat); - /* Wait for write done */ + Psram_WriteReg(psramCfg, (uint8_t *)&stat); + /* Wait for write done */ - Psram_ReadReg(psramCfg, (uint8_t *)&stat); + Psram_ReadReg(psramCfg, (uint8_t *)&stat); - if ((stat & 0x3) == psramCfg->driveStrength) { - return SUCCESS; - } + if ((stat & 0x3) == psramCfg->driveStrength) { + return SUCCESS; + } - return ERROR; + return ERROR; } #endif /****************************************************************************/ /** - * @brief Set psram burst wrap size - * - * @param psramCfg: Serial psram parameter configuration pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Set psram burst wrap size + * + * @param psramCfg: Serial psram parameter configuration pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_SetBurstWrap(SPI_Psram_Cfg_Type *psramCfg) -{ - uint32_t stat = 0; - /* Check the parameters */ - CHECK_PARAM(IS_PSRAM_BURST_LENGTH(psramCfg->burstLength)); +BL_Err_Type ATTR_TCM_SECTION Psram_SetBurstWrap(SPI_Psram_Cfg_Type *psramCfg) { + uint32_t stat = 0; + /* Check the parameters */ + CHECK_PARAM(IS_PSRAM_BURST_LENGTH(psramCfg->burstLength)); - Psram_ReadReg(psramCfg, (uint8_t *)&stat); + Psram_ReadReg(psramCfg, (uint8_t *)&stat); - if (((stat >> 5) & 0x3) == psramCfg->burstLength) { - return SUCCESS; - } + if (((stat >> 5) & 0x3) == psramCfg->burstLength) { + return SUCCESS; + } - stat &= (~(0x3 << 5)); - stat |= (psramCfg->burstLength << 5); + stat &= (~(0x3 << 5)); + stat |= (psramCfg->burstLength << 5); - Psram_WriteReg(psramCfg, (uint8_t *)&stat); - /* Wait for write done */ + Psram_WriteReg(psramCfg, (uint8_t *)&stat); + /* Wait for write done */ - Psram_ReadReg(psramCfg, (uint8_t *)&stat); + Psram_ReadReg(psramCfg, (uint8_t *)&stat); - if (((stat >> 5) & 0x3) == psramCfg->burstLength) { - return SUCCESS; - } + if (((stat >> 5) & 0x3) == psramCfg->burstLength) { + return SUCCESS; + } - return ERROR; + return ERROR; } #endif /****************************************************************************/ /** - * @brief Get psram ID - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param data: Data pointer to store read data - * - * @return None - * -*******************************************************************************/ + * @brief Get psram ID + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param data: Data pointer to store read data + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION Psram_ReadId(SPI_Psram_Cfg_Type *psramCfg, uint8_t *data) -{ - uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; - SF_Ctrl_Cmd_Cfg_Type psramCmd; +void ATTR_TCM_SECTION Psram_ReadId(SPI_Psram_Cfg_Type *psramCfg, uint8_t *data) { + uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; + SF_Ctrl_Cmd_Cfg_Type psramCmd; - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } - psramCmd.cmdBuf[0] = (psramCfg->readIdCmd) << 24; - psramCmd.rwFlag = SF_CTRL_READ; - psramCmd.addrSize = 3; - psramCmd.dummyClks = psramCfg->readIdDmyClk; - psramCmd.nbData = 8; + psramCmd.cmdBuf[0] = (psramCfg->readIdCmd) << 24; + psramCmd.rwFlag = SF_CTRL_READ; + psramCmd.addrSize = 3; + psramCmd.dummyClks = psramCfg->readIdDmyClk; + psramCmd.nbData = 8; - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) { - } + while (SET == SF_Ctrl_GetBusyState()) {} - BL702_MemCpy(data, psramCtrlBuf, 8); + BL702_MemCpy(data, psramCtrlBuf, 8); } #endif /****************************************************************************/ /** - * @brief Psram enter quad mode - * - * @param psramCfg: Serial psram parameter configuration pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Psram enter quad mode + * + * @param psramCfg: Serial psram parameter configuration pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_EnterQuadMode(SPI_Psram_Cfg_Type *psramCfg) -{ - SF_Ctrl_Cmd_Cfg_Type psramCmd; +BL_Err_Type ATTR_TCM_SECTION Psram_EnterQuadMode(SPI_Psram_Cfg_Type *psramCfg) { + SF_Ctrl_Cmd_Cfg_Type psramCmd; - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } - psramCmd.cmdBuf[0] = (psramCfg->enterQuadModeCmd) << 24; - psramCmd.rwFlag = SF_CTRL_READ; + psramCmd.cmdBuf[0] = (psramCfg->enterQuadModeCmd) << 24; + psramCmd.rwFlag = SF_CTRL_READ; - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) { - } + while (SET == SF_Ctrl_GetBusyState()) {} - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Psram exit quad mode - * - * @param psramCfg: Serial psram parameter configuration pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Psram exit quad mode + * + * @param psramCfg: Serial psram parameter configuration pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_ExitQuadMode(SPI_Psram_Cfg_Type *psramCfg) -{ - SF_Ctrl_Cmd_Cfg_Type psramCmd; +BL_Err_Type ATTR_TCM_SECTION Psram_ExitQuadMode(SPI_Psram_Cfg_Type *psramCfg) { + SF_Ctrl_Cmd_Cfg_Type psramCmd; - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } - psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - psramCmd.cmdBuf[0] = (psramCfg->exitQuadModeCmd) << 24; - psramCmd.rwFlag = SF_CTRL_READ; + psramCmd.cmdBuf[0] = (psramCfg->exitQuadModeCmd) << 24; + psramCmd.rwFlag = SF_CTRL_READ; - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) { - } + while (SET == SF_Ctrl_GetBusyState()) {} - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Psram toggle burst length - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param ctrlMode: Psram ctrl mode type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Psram toggle burst length + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param ctrlMode: Psram ctrl mode type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_ToggleBurstLength(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) -{ - SF_Ctrl_Cmd_Cfg_Type psramCmd; - /* Check the parameters */ - CHECK_PARAM(IS_PSRAM_CTRL_MODE(ctrlMode)); - - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } +BL_Err_Type ATTR_TCM_SECTION Psram_ToggleBurstLength(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) { + SF_Ctrl_Cmd_Cfg_Type psramCmd; + /* Check the parameters */ + CHECK_PARAM(IS_PSRAM_CTRL_MODE(ctrlMode)); + + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } + + if (ctrlMode == PSRAM_QPI_CTRL_MODE) { + psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + } - if (ctrlMode == PSRAM_QPI_CTRL_MODE) { - psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - } + psramCmd.cmdBuf[0] = (psramCfg->burstToggleCmd) << 24; + psramCmd.rwFlag = SF_CTRL_READ; - psramCmd.cmdBuf[0] = (psramCfg->burstToggleCmd) << 24; - psramCmd.rwFlag = SF_CTRL_READ; + SF_Ctrl_SendCmd(&psramCmd); - SF_Ctrl_SendCmd(&psramCmd); + while (SET == SF_Ctrl_GetBusyState()) {} - while (SET == SF_Ctrl_GetBusyState()) { - } - - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Psram software reset - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param ctrlMode: Psram ctrl mode type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Psram software reset + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param ctrlMode: Psram ctrl mode type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_SoftwareReset(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) -{ - SF_Ctrl_Cmd_Cfg_Type psramCmd; - /* Check the parameters */ - CHECK_PARAM(IS_PSRAM_CTRL_MODE(ctrlMode)); - - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } - - if (ctrlMode == PSRAM_QPI_CTRL_MODE) { - psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - } +BL_Err_Type ATTR_TCM_SECTION Psram_SoftwareReset(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) { + SF_Ctrl_Cmd_Cfg_Type psramCmd; + /* Check the parameters */ + CHECK_PARAM(IS_PSRAM_CTRL_MODE(ctrlMode)); + + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } + + if (ctrlMode == PSRAM_QPI_CTRL_MODE) { + psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + } - /* Reset enable */ - psramCmd.cmdBuf[0] = (psramCfg->resetEnableCmd) << 24; - /* rwFlag don't care */ - psramCmd.rwFlag = SF_CTRL_READ; - /* Wait for write done */ + /* Reset enable */ + psramCmd.cmdBuf[0] = (psramCfg->resetEnableCmd) << 24; + /* rwFlag don't care */ + psramCmd.rwFlag = SF_CTRL_READ; + /* Wait for write done */ - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) { - } + while (SET == SF_Ctrl_GetBusyState()) {} - /* Reset */ - psramCmd.cmdBuf[0] = (psramCfg->resetCmd) << 24; - /* rwFlag don't care */ - psramCmd.rwFlag = SF_CTRL_READ; - SF_Ctrl_SendCmd(&psramCmd); + /* Reset */ + psramCmd.cmdBuf[0] = (psramCfg->resetCmd) << 24; + /* rwFlag don't care */ + psramCmd.rwFlag = SF_CTRL_READ; + SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) { - } + while (SET == SF_Ctrl_GetBusyState()) {} - BL702_Delay_US(50); - return SUCCESS; + BL702_Delay_US(50); + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Psram set IDbus config - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param ioMode: Psram ctrl mode type - * @param addr: Address to read/write - * @param len: Data length to read/write - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Psram set IDbus config + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param ioMode: Psram ctrl mode type + * @param addr: Address to read/write + * @param len: Data length to read/write + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_Set_IDbus_Cfg(SPI_Psram_Cfg_Type *psramCfg, - SF_Ctrl_IO_Type ioMode, uint32_t addr, uint32_t len) -{ - uint8_t cmd, dummyClks; - SF_Ctrl_Cmd_Cfg_Type psramCmd; - uint8_t cmdValid = 1; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_IO_TYPE(ioMode)); - - SF_Ctrl_Set_Owner(SF_CTRL_OWNER_IAHB); - - /* read mode cache set */ - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } - - if (SF_CTRL_NIO_MODE == ioMode) { - cmd = psramCfg->fReadCmd; - dummyClks = psramCfg->fReadDmyClk; - } else if (SF_CTRL_QIO_MODE == ioMode) { - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - cmd = psramCfg->fReadQuadCmd; - dummyClks = psramCfg->fReadQuadDmyClk; - } else { - return ERROR; - } - - /* prepare command */ - psramCmd.rwFlag = SF_CTRL_READ; - psramCmd.addrSize = 3; - psramCmd.cmdBuf[0] = (cmd << 24) | addr; - psramCmd.dummyClks = dummyClks; - psramCmd.nbData = len; - SF_Ctrl_Psram_Read_Icache_Set(&psramCmd, cmdValid); - - /* write mode cache set */ - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } - - if (SF_CTRL_NIO_MODE == ioMode) { - cmd = psramCfg->writeCmd; - } else if (SF_CTRL_QIO_MODE == ioMode) { - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - cmd = psramCfg->quadWriteCmd; - } else { - return ERROR; - } - - dummyClks = 0; - - /* prepare command */ - psramCmd.rwFlag = SF_CTRL_WRITE; - psramCmd.addrSize = 3; - psramCmd.cmdBuf[0] = (cmd << 24) | addr; - psramCmd.dummyClks = dummyClks; - psramCmd.nbData = len; - SF_Ctrl_Psram_Write_Icache_Set(&psramCmd, cmdValid); - return SUCCESS; +BL_Err_Type ATTR_TCM_SECTION Psram_Set_IDbus_Cfg(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint32_t len) { + uint8_t cmd, dummyClks; + SF_Ctrl_Cmd_Cfg_Type psramCmd; + uint8_t cmdValid = 1; + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_IO_TYPE(ioMode)); + + SF_Ctrl_Set_Owner(SF_CTRL_OWNER_IAHB); + + /* read mode cache set */ + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } + + if (SF_CTRL_NIO_MODE == ioMode) { + cmd = psramCfg->fReadCmd; + dummyClks = psramCfg->fReadDmyClk; + } else if (SF_CTRL_QIO_MODE == ioMode) { + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + cmd = psramCfg->fReadQuadCmd; + dummyClks = psramCfg->fReadQuadDmyClk; + } else { + return ERROR; + } + + /* prepare command */ + psramCmd.rwFlag = SF_CTRL_READ; + psramCmd.addrSize = 3; + psramCmd.cmdBuf[0] = (cmd << 24) | addr; + psramCmd.dummyClks = dummyClks; + psramCmd.nbData = len; + SF_Ctrl_Psram_Read_Icache_Set(&psramCmd, cmdValid); + + /* write mode cache set */ + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } + + if (SF_CTRL_NIO_MODE == ioMode) { + cmd = psramCfg->writeCmd; + } else if (SF_CTRL_QIO_MODE == ioMode) { + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + cmd = psramCfg->quadWriteCmd; + } else { + return ERROR; + } + + dummyClks = 0; + + /* prepare command */ + psramCmd.rwFlag = SF_CTRL_WRITE; + psramCmd.addrSize = 3; + psramCmd.cmdBuf[0] = (cmd << 24) | addr; + psramCmd.dummyClks = dummyClks; + psramCmd.nbData = len; + SF_Ctrl_Psram_Write_Icache_Set(&psramCmd, cmdValid); + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Set cache write to psram with cache - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param ioMode: Psram controller interface mode - * @param wtEn: Psram cache write through enable - * @param wbEn: Psram cache write back enable - * @param waEn: Psram cache write allocate enable - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Set cache write to psram with cache + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param ioMode: Psram controller interface mode + * @param wtEn: Psram cache write through enable + * @param wbEn: Psram cache write back enable + * @param waEn: Psram cache write allocate enable + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_Cache_Write_Set(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, - BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) -{ - BL_Err_Type stat; +BL_Err_Type ATTR_TCM_SECTION Psram_Cache_Write_Set(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) { + BL_Err_Type stat; - /* Cache now only support 32 bytes read */ - stat = Psram_Set_IDbus_Cfg(psramCfg, ioMode, 0, 32); + /* Cache now only support 32 bytes read */ + stat = Psram_Set_IDbus_Cfg(psramCfg, ioMode, 0, 32); - if (SUCCESS != stat) { - return stat; - } + if (SUCCESS != stat) { + return stat; + } - L1C_Cache_Write_Set(wtEn, wbEn, waEn); - return SUCCESS; + L1C_Cache_Write_Set(wtEn, wbEn, waEn); + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Write psram one region - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param ioMode: Write mode: SPI mode or QPI mode - * @param addr: Start address to be write - * @param data: Data pointer to be write - * @param len: Data length to be write - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Write psram one region + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param ioMode: Write mode: SPI mode or QPI mode + * @param addr: Start address to be write + * @param data: Data pointer to be write + * @param len: Data length to be write + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_Write(SPI_Psram_Cfg_Type *psramCfg, - SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; - uint32_t i = 0, curLen = 0; - uint32_t burstLen = 512; - uint8_t cmd; - SF_Ctrl_Cmd_Cfg_Type psramCmd; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_IO_TYPE(ioMode)); - - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } +BL_Err_Type ATTR_TCM_SECTION Psram_Write(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; + uint32_t i = 0, curLen = 0; + uint32_t burstLen = 512; + uint8_t cmd; + SF_Ctrl_Cmd_Cfg_Type psramCmd; + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_IO_TYPE(ioMode)); + + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } + + if (SF_CTRL_NIO_MODE == ioMode) { + cmd = psramCfg->writeCmd; + } else if (SF_CTRL_QIO_MODE == ioMode) { + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + cmd = psramCfg->quadWriteCmd; + } else { + return ERROR; + } - if (SF_CTRL_NIO_MODE == ioMode) { - cmd = psramCfg->writeCmd; - } else if (SF_CTRL_QIO_MODE == ioMode) { - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - cmd = psramCfg->quadWriteCmd; - } else { - return ERROR; - } + /* Prepare command */ + psramCmd.rwFlag = SF_CTRL_WRITE; + psramCmd.addrSize = 3; - /* Prepare command */ - psramCmd.rwFlag = SF_CTRL_WRITE; - psramCmd.addrSize = 3; - - if (psramCfg->burstLength == PSRAM_BURST_LENGTH_16_BYTES) { - burstLen = 16; - } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_32_BYTES) { - burstLen = 32; - } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_64_BYTES) { - burstLen = 64; - } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_512_BYTES) { - burstLen = 512; - } + if (psramCfg->burstLength == PSRAM_BURST_LENGTH_16_BYTES) { + burstLen = 16; + } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_32_BYTES) { + burstLen = 32; + } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_64_BYTES) { + burstLen = 64; + } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_512_BYTES) { + burstLen = 512; + } - for (i = 0; i < len;) { - /* Get current programmed length within page size */ - curLen = burstLen - addr % burstLen; + for (i = 0; i < len;) { + /* Get current programmed length within page size */ + curLen = burstLen - addr % burstLen; - if (curLen > len - i) { - curLen = len - i; - } + if (curLen > len - i) { + curLen = len - i; + } - /* Prepare command */ - BL702_MemCpy_Fast(psramCtrlBuf, data, curLen); - psramCmd.cmdBuf[0] = (cmd << 24) | (addr); - psramCmd.nbData = curLen; + /* Prepare command */ + BL702_MemCpy_Fast(psramCtrlBuf, data, curLen); + psramCmd.cmdBuf[0] = (cmd << 24) | (addr); + psramCmd.nbData = curLen; - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); - /* Adjust address and programmed length */ - addr += curLen; - i += curLen; - data += curLen; + /* Adjust address and programmed length */ + addr += curLen; + i += curLen; + data += curLen; - /* Wait for write done */ - } + /* Wait for write done */ + } - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Read data from psram - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param ioMode: IoMode: psram controller interface mode - * @param addr: Psram read start address - * @param data: Data pointer to store data read from psram - * @param len: Data length to read - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Read data from psram + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param ioMode: IoMode: psram controller interface mode + * @param addr: Psram read start address + * @param data: Data pointer to store data read from psram + * @param len: Data length to read + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_Read(SPI_Psram_Cfg_Type *psramCfg, - SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; - uint32_t curLen, i; - uint32_t burstLen = 512; - uint8_t cmd, dummyClks; - SF_Ctrl_Cmd_Cfg_Type psramCmd; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_IO_TYPE(ioMode)); - - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } +BL_Err_Type ATTR_TCM_SECTION Psram_Read(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; + uint32_t curLen, i; + uint32_t burstLen = 512; + uint8_t cmd, dummyClks; + SF_Ctrl_Cmd_Cfg_Type psramCmd; + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_IO_TYPE(ioMode)); + + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } + + if (SF_CTRL_NIO_MODE == ioMode) { + cmd = psramCfg->fReadCmd; + dummyClks = psramCfg->fReadDmyClk; + } else if (SF_CTRL_QIO_MODE == ioMode) { + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + cmd = psramCfg->fReadQuadCmd; + dummyClks = psramCfg->fReadQuadDmyClk; + } else { + return ERROR; + } + + /* Prepare command */ + psramCmd.rwFlag = SF_CTRL_READ; + psramCmd.addrSize = 3; + psramCmd.dummyClks = dummyClks; + + if (psramCfg->burstLength == PSRAM_BURST_LENGTH_16_BYTES) { + burstLen = 16; + } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_32_BYTES) { + burstLen = 32; + } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_64_BYTES) { + burstLen = 64; + } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_512_BYTES) { + burstLen = 512; + } + + /* Read data */ + for (i = 0; i < len;) { + /* Prepare command */ + psramCmd.cmdBuf[0] = (cmd << 24) | (addr); + curLen = burstLen - addr % burstLen; - if (SF_CTRL_NIO_MODE == ioMode) { - cmd = psramCfg->fReadCmd; - dummyClks = psramCfg->fReadDmyClk; - } else if (SF_CTRL_QIO_MODE == ioMode) { - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - cmd = psramCfg->fReadQuadCmd; - dummyClks = psramCfg->fReadQuadDmyClk; - } else { - return ERROR; + if (curLen > len - i) { + curLen = len - i; } - /* Prepare command */ - psramCmd.rwFlag = SF_CTRL_READ; - psramCmd.addrSize = 3; - psramCmd.dummyClks = dummyClks; - - if (psramCfg->burstLength == PSRAM_BURST_LENGTH_16_BYTES) { - burstLen = 16; - } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_32_BYTES) { - burstLen = 32; - } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_64_BYTES) { - burstLen = 64; - } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_512_BYTES) { - burstLen = 512; + if (curLen >= FLASH_CTRL_BUF_SIZE) { + curLen = FLASH_CTRL_BUF_SIZE; + psramCmd.nbData = curLen; + } else { + /* Make sf_ctrl word read */ + psramCmd.nbData = ((curLen + 3) >> 2) << 2; } - /* Read data */ - for (i = 0; i < len;) { - /* Prepare command */ - psramCmd.cmdBuf[0] = (cmd << 24) | (addr); - curLen = burstLen - addr % burstLen; - - if (curLen > len - i) { - curLen = len - i; - } - - if (curLen >= FLASH_CTRL_BUF_SIZE) { - curLen = FLASH_CTRL_BUF_SIZE; - psramCmd.nbData = curLen; - } else { - /* Make sf_ctrl word read */ - psramCmd.nbData = ((curLen + 3) >> 2) << 2; - } - - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) { - } + while (SET == SF_Ctrl_GetBusyState()) {} - BL702_MemCpy_Fast(data, psramCtrlBuf, curLen); + BL702_MemCpy_Fast(data, psramCtrlBuf, curLen); - addr += curLen; - i += curLen; - data += curLen; - } + addr += curLen; + i += curLen; + data += curLen; + } - return SUCCESS; + return SUCCESS; } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pwm.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pwm.c index b63158016e..80188ee774 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pwm.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pwm.c @@ -48,7 +48,7 @@ /** @defgroup PWM_Private_Macros * @{ */ -#define PWM_Get_Channel_Reg(ch) (PWM_BASE + PWM_CHANNEL_OFFSET + (ch)*0x20) +#define PWM_Get_Channel_Reg(ch) (PWM_BASE + PWM_CHANNEL_OFFSET + (ch) * 0x20) #define PWM_INT_TIMEOUT_COUNT (160 * 1000) #define PWM_STOP_TIMEOUT_COUNT (160 * 1000) diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_qdec.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_qdec.c index c34af329ec..3ce8357abd 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_qdec.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_qdec.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_qdec.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_qdec.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_qdec.h" @@ -59,10 +59,8 @@ /** @defgroup QDEC_Private_Variables * @{ */ -static const uint32_t qdecAddr[QDEC_ID_MAX] = { QDEC0_BASE, QDEC1_BASE, QDEC2_BASE }; -static intCallback_Type *qdecIntCbfArra[QDEC_ID_MAX][QDEC_INT_ALL] = { { NULL, NULL, NULL, NULL }, - { NULL, NULL, NULL, NULL }, - { NULL, NULL, NULL, NULL } }; +static const uint32_t qdecAddr[QDEC_ID_MAX] = {QDEC0_BASE, QDEC1_BASE, QDEC2_BASE}; +static intCallback_Type *qdecIntCbfArra[QDEC_ID_MAX][QDEC_INT_ALL] = {{NULL, NULL, NULL, NULL}, {NULL, NULL, NULL, NULL}, {NULL, NULL, NULL, NULL}}; /*@} end of group QDEC_Private_Variables */ @@ -83,461 +81,443 @@ static intCallback_Type *qdecIntCbfArra[QDEC_ID_MAX][QDEC_INT_ALL] = { { NULL, N */ /****************************************************************************/ /** - * @brief QDEC init - * - * @param qdecId: QDEC ID - * @param qdecCfg: QDEC config - * - * @return None - * -*******************************************************************************/ -void QDEC_Init(QDEC_ID_Type qdecId, QDEC_CFG_Type *qdecCfg) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - CHECK_PARAM(IS_QDEC_SAMPLE_MODE_TYPE(qdecCfg->sampleCfg.sampleMod)); - CHECK_PARAM(IS_QDEC_SAMPLE_PERIOD_TYPE(qdecCfg->sampleCfg.samplePeriod)); - CHECK_PARAM(IS_QDEC_REPORT_MODE_TYPE(qdecCfg->reportCfg.reportMod)); - CHECK_PARAM((qdecCfg->ledCfg.ledPeriod) <= 0x1FF); - CHECK_PARAM((qdecCfg->deglitchCfg.deglitchStrength) <= 0xF); - - /* qdec_ctrl */ - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_PERIOD, qdecCfg->sampleCfg.samplePeriod); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_PERIOD, qdecCfg->reportCfg.reportPeriod); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_EN, qdecCfg->ledCfg.ledEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_POL, qdecCfg->ledCfg.ledSwap); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_EN, qdecCfg->deglitchCfg.deglitchEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_CNT, qdecCfg->deglitchCfg.deglitchStrength); - BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); - - /* qdec_ctrl1 */ - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_MODE, qdecCfg->sampleCfg.sampleMod); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_MODE, qdecCfg->reportCfg.reportMod); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_PERIOD, qdecCfg->ledCfg.ledPeriod); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_ACC_MODE, qdecCfg->accMod); - BL_WR_REG(QDECx, QDEC0_CTRL1, tmpVal); + * @brief QDEC init + * + * @param qdecId: QDEC ID + * @param qdecCfg: QDEC config + * + * @return None + * + *******************************************************************************/ +void QDEC_Init(QDEC_ID_Type qdecId, QDEC_CFG_Type *qdecCfg) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + CHECK_PARAM(IS_QDEC_SAMPLE_MODE_TYPE(qdecCfg->sampleCfg.sampleMod)); + CHECK_PARAM(IS_QDEC_SAMPLE_PERIOD_TYPE(qdecCfg->sampleCfg.samplePeriod)); + CHECK_PARAM(IS_QDEC_REPORT_MODE_TYPE(qdecCfg->reportCfg.reportMod)); + CHECK_PARAM((qdecCfg->ledCfg.ledPeriod) <= 0x1FF); + CHECK_PARAM((qdecCfg->deglitchCfg.deglitchStrength) <= 0xF); + + /* qdec_ctrl */ + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_PERIOD, qdecCfg->sampleCfg.samplePeriod); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_PERIOD, qdecCfg->reportCfg.reportPeriod); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_EN, qdecCfg->ledCfg.ledEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_POL, qdecCfg->ledCfg.ledSwap); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_EN, qdecCfg->deglitchCfg.deglitchEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_CNT, qdecCfg->deglitchCfg.deglitchStrength); + BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); + + /* qdec_ctrl1 */ + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_MODE, qdecCfg->sampleCfg.sampleMod); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_MODE, qdecCfg->reportCfg.reportMod); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_PERIOD, qdecCfg->ledCfg.ledPeriod); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_ACC_MODE, qdecCfg->accMod); + BL_WR_REG(QDECx, QDEC0_CTRL1, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(QDEC0_IRQn, QDEC0_IRQHandler); - Interrupt_Handler_Register(QDEC1_IRQn, QDEC1_IRQHandler); - Interrupt_Handler_Register(QDEC2_IRQn, QDEC2_IRQHandler); + Interrupt_Handler_Register(QDEC0_IRQn, QDEC0_IRQHandler); + Interrupt_Handler_Register(QDEC1_IRQn, QDEC1_IRQHandler); + Interrupt_Handler_Register(QDEC2_IRQn, QDEC2_IRQHandler); #endif } /****************************************************************************/ /** - * @brief QDEC deinit - * - * @param qdecId: QDEC ID - * - * @return None - * -*******************************************************************************/ -void QDEC_DeInit(QDEC_ID_Type qdecId) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - /* deconfig qdec */ - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_PERIOD, 10); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_PERIOD, 2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_CNT, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_POL, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_EN, 0); - BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_PERIOD, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_INPUT_SWAP, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_MODE, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_MODE, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_ACC_MODE, 1); - BL_WR_REG(QDECx, QDEC0_CTRL1, tmpVal); - - /* enable qdec */ - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_EN, 1); - BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); - - /* deconfig interrupt */ - tmpVal = BL_RD_REG(QDECx, QDEC0_INT_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_EN, 1); - BL_WR_REG(QDECx, QDEC0_INT_EN, tmpVal); - - /* clear status */ - tmpVal = BL_RD_REG(QDECx, QDEC0_INT_CLR); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_CLR, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_CLR, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_CLR, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_CLR, 1); - BL_WR_REG(QDECx, QDEC0_INT_STS, tmpVal); - - /* clear value */ - tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); - - /* disable qdec */ - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_EN, 0); - BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); + * @brief QDEC deinit + * + * @param qdecId: QDEC ID + * + * @return None + * + *******************************************************************************/ +void QDEC_DeInit(QDEC_ID_Type qdecId) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + /* deconfig qdec */ + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_PERIOD, 10); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_PERIOD, 2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_CNT, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_POL, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_EN, 0); + BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_PERIOD, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_INPUT_SWAP, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_MODE, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_MODE, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_ACC_MODE, 1); + BL_WR_REG(QDECx, QDEC0_CTRL1, tmpVal); + + /* enable qdec */ + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_EN, 1); + BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); + + /* deconfig interrupt */ + tmpVal = BL_RD_REG(QDECx, QDEC0_INT_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_EN, 1); + BL_WR_REG(QDECx, QDEC0_INT_EN, tmpVal); + + /* clear status */ + tmpVal = BL_RD_REG(QDECx, QDEC0_INT_CLR); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_CLR, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_CLR, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_CLR, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_CLR, 1); + BL_WR_REG(QDECx, QDEC0_INT_STS, tmpVal); + + /* clear value */ + tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); + + /* disable qdec */ + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_EN, 0); + BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); } /****************************************************************************/ /** - * @brief QDEC enable - * - * @param qdecId: QDEC ID - * - * @return None - * -*******************************************************************************/ -void QDEC_Enable(QDEC_ID_Type qdecId) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - /* qdec_ctrl */ - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); - tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_EN); - BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); + * @brief QDEC enable + * + * @param qdecId: QDEC ID + * + * @return None + * + *******************************************************************************/ +void QDEC_Enable(QDEC_ID_Type qdecId) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + /* qdec_ctrl */ + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); + tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_EN); + BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); } /****************************************************************************/ /** - * @brief QDEC disable - * - * @param qdecId: QDEC ID - * - * @return None - * -*******************************************************************************/ -void QDEC_Disable(QDEC_ID_Type qdecId) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - /* qdec_ctrl */ - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); - tmpVal = BL_CLR_REG_BIT(tmpVal, QDEC_EN); - BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); + * @brief QDEC disable + * + * @param qdecId: QDEC ID + * + * @return None + * + *******************************************************************************/ +void QDEC_Disable(QDEC_ID_Type qdecId) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + /* qdec_ctrl */ + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); + tmpVal = BL_CLR_REG_BIT(tmpVal, QDEC_EN); + BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); } /****************************************************************************/ /** - * @brief set QDEC interrupt mask - * - * @param qdecId: QDEC ID - * @param intType: QDEC interrupt type - * @param intMask: MASK or UNMASK - * - * @return None - * -*******************************************************************************/ -void QDEC_SetIntMask(QDEC_ID_Type qdecId, QDEC_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); - - /* qdec_int_en */ - tmpVal = BL_RD_REG(QDECx, QDEC0_INT_EN); - - switch (intType) { - case QDEC_INT_REPORT: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_EN, (intMask ? 0 : 1)); - break; - - case QDEC_INT_SAMPLE: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_EN, (intMask ? 0 : 1)); - break; - - case QDEC_INT_ERROR: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_EN, (intMask ? 0 : 1)); - break; - - case QDEC_INT_OVERFLOW: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_EN, (intMask ? 0 : 1)); - break; - - default: - break; - } - - BL_WR_REG(QDECx, QDEC0_INT_EN, tmpVal); + * @brief set QDEC interrupt mask + * + * @param qdecId: QDEC ID + * @param intType: QDEC interrupt type + * @param intMask: MASK or UNMASK + * + * @return None + * + *******************************************************************************/ +void QDEC_SetIntMask(QDEC_ID_Type qdecId, QDEC_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); + + /* qdec_int_en */ + tmpVal = BL_RD_REG(QDECx, QDEC0_INT_EN); + + switch (intType) { + case QDEC_INT_REPORT: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_EN, (intMask ? 0 : 1)); + break; + + case QDEC_INT_SAMPLE: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_EN, (intMask ? 0 : 1)); + break; + + case QDEC_INT_ERROR: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_EN, (intMask ? 0 : 1)); + break; + + case QDEC_INT_OVERFLOW: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_EN, (intMask ? 0 : 1)); + break; + + default: + break; + } + + BL_WR_REG(QDECx, QDEC0_INT_EN, tmpVal); } /****************************************************************************/ /** - * @brief get QDEC interrupt mask - * - * @param qdecId: QDEC ID - * @param intType: QDEC interrupt type - * - * @return MASK or UNMASK - * -*******************************************************************************/ -BL_Mask_Type QDEC_GetIntMask(QDEC_ID_Type qdecId, QDEC_INT_Type intType) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); - - /* qdec_int_en */ - tmpVal = BL_RD_REG(QDECx, QDEC0_INT_EN); - - switch (intType) { - case QDEC_INT_REPORT: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_EN) ? UNMASK : MASK; - - case QDEC_INT_SAMPLE: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_EN) ? UNMASK : MASK; - - case QDEC_INT_ERROR: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_EN) ? UNMASK : MASK; - - case QDEC_INT_OVERFLOW: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_EN) ? UNMASK : MASK; - - default: - return UNMASK; - } + * @brief get QDEC interrupt mask + * + * @param qdecId: QDEC ID + * @param intType: QDEC interrupt type + * + * @return MASK or UNMASK + * + *******************************************************************************/ +BL_Mask_Type QDEC_GetIntMask(QDEC_ID_Type qdecId, QDEC_INT_Type intType) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); + + /* qdec_int_en */ + tmpVal = BL_RD_REG(QDECx, QDEC0_INT_EN); + + switch (intType) { + case QDEC_INT_REPORT: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_EN) ? UNMASK : MASK; + + case QDEC_INT_SAMPLE: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_EN) ? UNMASK : MASK; + + case QDEC_INT_ERROR: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_EN) ? UNMASK : MASK; + + case QDEC_INT_OVERFLOW: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_EN) ? UNMASK : MASK; + + default: + return UNMASK; + } } /****************************************************************************/ /** - * @brief QDEC interrupt callback install - * - * @param qdecId: QDEC ID - * @param intType: QDEC interrupt type - * @param cbFun: interrupt callback - * - * @return None - * -*******************************************************************************/ -void QDEC_Int_Callback_Install(QDEC_ID_Type qdecId, QDEC_INT_Type intType, intCallback_Type *cbFun) -{ - qdecIntCbfArra[qdecId][intType] = cbFun; -} + * @brief QDEC interrupt callback install + * + * @param qdecId: QDEC ID + * @param intType: QDEC interrupt type + * @param cbFun: interrupt callback + * + * @return None + * + *******************************************************************************/ +void QDEC_Int_Callback_Install(QDEC_ID_Type qdecId, QDEC_INT_Type intType, intCallback_Type *cbFun) { qdecIntCbfArra[qdecId][intType] = cbFun; } /****************************************************************************/ /** - * @brief QDEC get interrupt status - * - * @param qdecId: QDEC ID - * @param intType: QDEC interrupt type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type QDEC_Get_Int_Status(QDEC_ID_Type qdecId, QDEC_INT_Type intType) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); - - /* qdec_int_sts */ - tmpVal = BL_RD_REG(QDECx, QDEC0_INT_STS); - - switch (intType) { - case QDEC_INT_REPORT: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_STS) ? SET : RESET; - - case QDEC_INT_SAMPLE: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_STS) ? SET : RESET; - - case QDEC_INT_ERROR: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_STS) ? SET : RESET; - - case QDEC_INT_OVERFLOW: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_STS) ? SET : RESET; - - default: - return RESET; - } + * @brief QDEC get interrupt status + * + * @param qdecId: QDEC ID + * @param intType: QDEC interrupt type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type QDEC_Get_Int_Status(QDEC_ID_Type qdecId, QDEC_INT_Type intType) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); + + /* qdec_int_sts */ + tmpVal = BL_RD_REG(QDECx, QDEC0_INT_STS); + + switch (intType) { + case QDEC_INT_REPORT: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_STS) ? SET : RESET; + + case QDEC_INT_SAMPLE: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_STS) ? SET : RESET; + + case QDEC_INT_ERROR: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_STS) ? SET : RESET; + + case QDEC_INT_OVERFLOW: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_STS) ? SET : RESET; + + default: + return RESET; + } } /****************************************************************************/ /** - * @brief QDEC clear interrupt status - * - * @param qdecId: QDEC ID - * @param intType: QDEC interrupt type - * - * @return None - * -*******************************************************************************/ -void QDEC_Clr_Int_Status(QDEC_ID_Type qdecId, QDEC_INT_Type intType) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); - - /* qdec_int_clr */ - tmpVal = BL_RD_REG(QDECx, QDEC0_INT_CLR); - - switch (intType) { - case QDEC_INT_REPORT: - tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_RPT_RDY_CLR); - break; - - case QDEC_INT_SAMPLE: - tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_SPL_RDY_CLR); - break; - - case QDEC_INT_ERROR: - tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_DBL_RDY_CLR); - break; - - case QDEC_INT_OVERFLOW: - tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_OVERFLOW_CLR); - break; - - default: - break; - } - - BL_WR_REG(QDECx, QDEC0_INT_CLR, tmpVal); + * @brief QDEC clear interrupt status + * + * @param qdecId: QDEC ID + * @param intType: QDEC interrupt type + * + * @return None + * + *******************************************************************************/ +void QDEC_Clr_Int_Status(QDEC_ID_Type qdecId, QDEC_INT_Type intType) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); + + /* qdec_int_clr */ + tmpVal = BL_RD_REG(QDECx, QDEC0_INT_CLR); + + switch (intType) { + case QDEC_INT_REPORT: + tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_RPT_RDY_CLR); + break; + + case QDEC_INT_SAMPLE: + tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_SPL_RDY_CLR); + break; + + case QDEC_INT_ERROR: + tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_DBL_RDY_CLR); + break; + + case QDEC_INT_OVERFLOW: + tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_OVERFLOW_CLR); + break; + + default: + break; + } + + BL_WR_REG(QDECx, QDEC0_INT_CLR, tmpVal); } /****************************************************************************/ /** - * @brief QDEC get sample direction - * - * @param qdecId: QDEC ID - * - * @return None - * -*******************************************************************************/ -QDEC_DIRECTION_Type QDEC_Get_Sample_Direction(QDEC_ID_Type qdecId) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - /* qdec_value */ - tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); - - return (QDEC_DIRECTION_Type)BL_GET_REG_BITS_VAL(tmpVal, QDEC_SPL_VAL); + * @brief QDEC get sample direction + * + * @param qdecId: QDEC ID + * + * @return None + * + *******************************************************************************/ +QDEC_DIRECTION_Type QDEC_Get_Sample_Direction(QDEC_ID_Type qdecId) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + /* qdec_value */ + tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); + + return (QDEC_DIRECTION_Type)BL_GET_REG_BITS_VAL(tmpVal, QDEC_SPL_VAL); } /****************************************************************************/ /** - * @brief QDEC get error count - * - * @param qdecId: QDEC ID - * - * @return None - * -*******************************************************************************/ -uint8_t QDEC_Get_Err_Cnt(QDEC_ID_Type qdecId) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - /* qdec_value */ - tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); - - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_ACC2_VAL); + * @brief QDEC get error count + * + * @param qdecId: QDEC ID + * + * @return None + * + *******************************************************************************/ +uint8_t QDEC_Get_Err_Cnt(QDEC_ID_Type qdecId) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + /* qdec_value */ + tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); + + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_ACC2_VAL); } /****************************************************************************/ /** - * @brief QDEC get sample value - * - * @param qdecId: QDEC ID - * - * @return None - * -*******************************************************************************/ -uint16_t QDEC_Get_Sample_Val(QDEC_ID_Type qdecId) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - /* qdec_value */ - tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); - - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_ACC1_VAL); + * @brief QDEC get sample value + * + * @param qdecId: QDEC ID + * + * @return None + * + *******************************************************************************/ +uint16_t QDEC_Get_Sample_Val(QDEC_ID_Type qdecId) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + /* qdec_value */ + tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); + + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_ACC1_VAL); } /****************************************************************************/ /** - * @brief QDEC interrupt handler - * - * @param qdecId: QDEC ID - * @param intType: QDEC interrupt type - * - * @return None - * -*******************************************************************************/ -void QDEC_IntHandler(QDEC_ID_Type qdecId, QDEC_INT_Type intType) -{ - if (SET == QDEC_Get_Int_Status(qdecId, intType)) { - QDEC_Clr_Int_Status(qdecId, intType); - - if (qdecIntCbfArra[qdecId][intType] != NULL) { - qdecIntCbfArra[qdecId][intType](); - } + * @brief QDEC interrupt handler + * + * @param qdecId: QDEC ID + * @param intType: QDEC interrupt type + * + * @return None + * + *******************************************************************************/ +void QDEC_IntHandler(QDEC_ID_Type qdecId, QDEC_INT_Type intType) { + if (SET == QDEC_Get_Int_Status(qdecId, intType)) { + QDEC_Clr_Int_Status(qdecId, intType); + + if (qdecIntCbfArra[qdecId][intType] != NULL) { + qdecIntCbfArra[qdecId][intType](); } + } } /****************************************************************************/ /** - * @brief QDEC0 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief QDEC0 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void QDEC0_IRQHandler(void) -{ - QDEC_INT_Type intType; - - for (intType = QDEC_INT_REPORT; intType < QDEC_INT_ALL; intType++) { - if (UNMASK == QDEC_GetIntMask(QDEC0_ID, intType)) { - QDEC_IntHandler(QDEC0_ID, intType); - } +void QDEC0_IRQHandler(void) { + QDEC_INT_Type intType; + + for (intType = QDEC_INT_REPORT; intType < QDEC_INT_ALL; intType++) { + if (UNMASK == QDEC_GetIntMask(QDEC0_ID, intType)) { + QDEC_IntHandler(QDEC0_ID, intType); } + } } #endif /****************************************************************************/ /** - * @brief QDEC1 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief QDEC1 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void QDEC1_IRQHandler(void) -{ - QDEC_INT_Type intType; - - for (intType = QDEC_INT_REPORT; intType < QDEC_INT_ALL; intType++) { - if (UNMASK == QDEC_GetIntMask(QDEC1_ID, intType)) { - QDEC_IntHandler(QDEC1_ID, intType); - } +void QDEC1_IRQHandler(void) { + QDEC_INT_Type intType; + + for (intType = QDEC_INT_REPORT; intType < QDEC_INT_ALL; intType++) { + if (UNMASK == QDEC_GetIntMask(QDEC1_ID, intType)) { + QDEC_IntHandler(QDEC1_ID, intType); } + } } #endif /****************************************************************************/ /** - * @brief QDEC2 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief QDEC2 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void QDEC2_IRQHandler(void) -{ - QDEC_INT_Type intType; - - for (intType = QDEC_INT_REPORT; intType < QDEC_INT_ALL; intType++) { - if (UNMASK == QDEC_GetIntMask(QDEC2_ID, intType)) { - QDEC_IntHandler(QDEC2_ID, intType); - } +void QDEC2_IRQHandler(void) { + QDEC_INT_Type intType; + + for (intType = QDEC_INT_REPORT; intType < QDEC_INT_ALL; intType++) { + if (UNMASK == QDEC_GetIntMask(QDEC2_ID, intType)) { + QDEC_IntHandler(QDEC2_ID, intType); } + } } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_romapi.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_romapi.c index 73040c439f..2576039c43 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_romapi.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_romapi.c @@ -1,112 +1,46 @@ #include "bl702_romdriver.h" /******************************************************************************/ -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - AON_Power_On_MBG(void) -{ - return RomDriver_AON_Power_On_MBG(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type AON_Power_On_MBG(void) { return RomDriver_AON_Power_On_MBG(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - AON_Power_Off_MBG(void) -{ - return RomDriver_AON_Power_Off_MBG(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type AON_Power_Off_MBG(void) { return RomDriver_AON_Power_Off_MBG(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - AON_Power_On_XTAL(void) -{ - return RomDriver_AON_Power_On_XTAL(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type AON_Power_On_XTAL(void) { return RomDriver_AON_Power_On_XTAL(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - AON_Set_Xtal_CapCode(uint8_t capIn, uint8_t capOut) -{ - return RomDriver_AON_Set_Xtal_CapCode(capIn, capOut); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type AON_Set_Xtal_CapCode(uint8_t capIn, uint8_t capOut) { return RomDriver_AON_Set_Xtal_CapCode(capIn, capOut); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - AON_Power_Off_XTAL(void) -{ - return RomDriver_AON_Power_Off_XTAL(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type AON_Power_Off_XTAL(void) { return RomDriver_AON_Power_Off_XTAL(); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_TCM_SECTION void ASM_Delay_Us(uint32_t core, uint32_t cnt) -{ - RomDriver_ASM_Delay_Us(core, cnt); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void ASM_Delay_Us(uint32_t core, uint32_t cnt) { RomDriver_ASM_Delay_Us(core, cnt); } -__ALWAYS_INLINE ATTR_TCM_SECTION void BL702_Delay_US(uint32_t cnt) -{ - RomDriver_BL702_Delay_US(cnt); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void BL702_Delay_US(uint32_t cnt) { RomDriver_BL702_Delay_US(cnt); } -__ALWAYS_INLINE ATTR_TCM_SECTION void BL702_Delay_MS(uint32_t cnt) -{ - RomDriver_BL702_Delay_MS(cnt); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void BL702_Delay_MS(uint32_t cnt) { RomDriver_BL702_Delay_MS(cnt); } -__ALWAYS_INLINE ATTR_TCM_SECTION void *BL702_MemCpy(void *dst, const void *src, uint32_t n) -{ - return RomDriver_BL702_MemCpy(dst, src, n); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void *BL702_MemCpy(void *dst, const void *src, uint32_t n) { return RomDriver_BL702_MemCpy(dst, src, n); } -__ALWAYS_INLINE ATTR_TCM_SECTION - uint32_t * - BL702_MemCpy4(uint32_t *dst, const uint32_t *src, uint32_t n) -{ - return RomDriver_BL702_MemCpy4(dst, src, n); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint32_t *BL702_MemCpy4(uint32_t *dst, const uint32_t *src, uint32_t n) { return RomDriver_BL702_MemCpy4(dst, src, n); } // __ALWAYS_INLINE ATTR_TCM_SECTION // void* BL702_MemCpy_Fast(void *pdst, const void *psrc, uint32_t n) { // return RomDriver_BL702_MemCpy_Fast(pdst, psrc, n); // } -__ALWAYS_INLINE ATTR_TCM_SECTION void *ARCH_MemCpy_Fast(void *pdst, const void *psrc, uint32_t n) -{ - return RomDriver_ARCH_MemCpy_Fast(pdst, psrc, n); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void *ARCH_MemCpy_Fast(void *pdst, const void *psrc, uint32_t n) { return RomDriver_ARCH_MemCpy_Fast(pdst, psrc, n); } -__ALWAYS_INLINE ATTR_TCM_SECTION void *BL702_MemSet(void *s, uint8_t c, uint32_t n) -{ - return RomDriver_BL702_MemSet(s, c, n); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void *BL702_MemSet(void *s, uint8_t c, uint32_t n) { return RomDriver_BL702_MemSet(s, c, n); } -__ALWAYS_INLINE ATTR_TCM_SECTION - uint32_t * - BL702_MemSet4(uint32_t *dst, const uint32_t val, uint32_t n) -{ - return RomDriver_BL702_MemSet4(dst, val, n); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint32_t *BL702_MemSet4(uint32_t *dst, const uint32_t val, uint32_t n) { return RomDriver_BL702_MemSet4(dst, val, n); } -__ALWAYS_INLINE ATTR_TCM_SECTION int BL702_MemCmp(const void *s1, const void *s2, uint32_t n) -{ - return RomDriver_BL702_MemCmp(s1, s2, n); -} +__ALWAYS_INLINE ATTR_TCM_SECTION int BL702_MemCmp(const void *s1, const void *s2, uint32_t n) { return RomDriver_BL702_MemCmp(s1, s2, n); } -__ALWAYS_INLINE ATTR_TCM_SECTION - uint32_t - BFLB_Soft_CRC32(void *dataIn, uint32_t len) -{ - return RomDriver_BFLB_Soft_CRC32(dataIn, len); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint32_t BFLB_Soft_CRC32(void *dataIn, uint32_t len) { return RomDriver_BFLB_Soft_CRC32(dataIn, len); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_CLOCK_SECTION - GLB_ROOT_CLK_Type - GLB_Get_Root_CLK_Sel(void) -{ - return RomDriver_GLB_Get_Root_CLK_Sel(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION GLB_ROOT_CLK_Type GLB_Get_Root_CLK_Sel(void) { return RomDriver_GLB_Get_Root_CLK_Sel(); } #if 0 __ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type @@ -115,145 +49,45 @@ __ALWAYS_INLINE ATTR_CLOCK_SECTION return RomDriver_GLB_Set_System_CLK_Div(hclkDiv, bclkDiv); } #endif -__ALWAYS_INLINE ATTR_CLOCK_SECTION - uint8_t - GLB_Get_BCLK_Div(void) -{ - return RomDriver_GLB_Get_BCLK_Div(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION uint8_t GLB_Get_BCLK_Div(void) { return RomDriver_GLB_Get_BCLK_Div(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - uint8_t - GLB_Get_HCLK_Div(void) -{ - return RomDriver_GLB_Get_HCLK_Div(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION uint8_t GLB_Get_HCLK_Div(void) { return RomDriver_GLB_Get_HCLK_Div(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - Update_SystemCoreClockWith_XTAL(GLB_DLL_XTAL_Type xtalType) -{ - return RomDriver_Update_SystemCoreClockWith_XTAL(xtalType); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type Update_SystemCoreClockWith_XTAL(GLB_DLL_XTAL_Type xtalType) { return RomDriver_Update_SystemCoreClockWith_XTAL(xtalType); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Set_System_CLK(GLB_DLL_XTAL_Type xtalType, GLB_SYS_CLK_Type clkFreq) -{ - return RomDriver_GLB_Set_System_CLK(xtalType, clkFreq); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Set_System_CLK(GLB_DLL_XTAL_Type xtalType, GLB_SYS_CLK_Type clkFreq) { return RomDriver_GLB_Set_System_CLK(xtalType, clkFreq); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - System_Core_Clock_Update_From_RC32M(void) -{ - return RomDriver_System_Core_Clock_Update_From_RC32M(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type System_Core_Clock_Update_From_RC32M(void) { return RomDriver_System_Core_Clock_Update_From_RC32M(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Set_SF_CLK(uint8_t enable, GLB_SFLASH_CLK_Type clkSel, uint8_t div) -{ - return RomDriver_GLB_Set_SF_CLK(enable, clkSel, div); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Set_SF_CLK(uint8_t enable, GLB_SFLASH_CLK_Type clkSel, uint8_t div) { return RomDriver_GLB_Set_SF_CLK(enable, clkSel, div); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Power_Off_DLL(void) -{ - return RomDriver_GLB_Power_Off_DLL(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Power_Off_DLL(void) { return RomDriver_GLB_Power_Off_DLL(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Power_On_DLL(GLB_DLL_XTAL_Type xtalType) -{ - return RomDriver_GLB_Power_On_DLL(xtalType); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Power_On_DLL(GLB_DLL_XTAL_Type xtalType) { return RomDriver_GLB_Power_On_DLL(xtalType); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Enable_DLL_All_Clks(void) -{ - return RomDriver_GLB_Enable_DLL_All_Clks(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Enable_DLL_All_Clks(void) { return RomDriver_GLB_Enable_DLL_All_Clks(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Enable_DLL_Clk(GLB_DLL_CLK_Type dllClk) -{ - return RomDriver_GLB_Enable_DLL_Clk(dllClk); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Enable_DLL_Clk(GLB_DLL_CLK_Type dllClk) { return RomDriver_GLB_Enable_DLL_Clk(dllClk); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Disable_DLL_All_Clks(void) -{ - return RomDriver_GLB_Disable_DLL_All_Clks(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Disable_DLL_All_Clks(void) { return RomDriver_GLB_Disable_DLL_All_Clks(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Disable_DLL_Clk(GLB_DLL_CLK_Type dllClk) -{ - return RomDriver_GLB_Disable_DLL_Clk(dllClk); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Disable_DLL_Clk(GLB_DLL_CLK_Type dllClk) { return RomDriver_GLB_Disable_DLL_Clk(dllClk); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_SW_System_Reset(void) -{ - return RomDriver_GLB_SW_System_Reset(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_SW_System_Reset(void) { return RomDriver_GLB_SW_System_Reset(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_SW_CPU_Reset(void) -{ - return RomDriver_GLB_SW_CPU_Reset(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_SW_CPU_Reset(void) { return RomDriver_GLB_SW_CPU_Reset(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_SW_POR_Reset(void) -{ - return RomDriver_GLB_SW_POR_Reset(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_SW_POR_Reset(void) { return RomDriver_GLB_SW_POR_Reset(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_Select_Internal_Flash(void) -{ - return RomDriver_GLB_Select_Internal_Flash(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_Select_Internal_Flash(void) { return RomDriver_GLB_Select_Internal_Flash(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_Swap_Flash_Pin(void) -{ - return RomDriver_GLB_Swap_Flash_Pin(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_Swap_Flash_Pin(void) { return RomDriver_GLB_Swap_Flash_Pin(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_Swap_Flash_CS_IO2_Pin(void) -{ - return RomDriver_GLB_Swap_Flash_CS_IO2_Pin(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_Swap_Flash_CS_IO2_Pin(void) { return RomDriver_GLB_Swap_Flash_CS_IO2_Pin(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_Swap_Flash_IO0_IO3_Pin(void) -{ - return RomDriver_GLB_Swap_Flash_IO0_IO3_Pin(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_Swap_Flash_IO0_IO3_Pin(void) { return RomDriver_GLB_Swap_Flash_IO0_IO3_Pin(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_Select_Internal_PSram(void) -{ - return RomDriver_GLB_Select_Internal_PSram(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_Select_Internal_PSram(void) { return RomDriver_GLB_Select_Internal_PSram(); } /* aon pads GPIO9~GPIO13 IE controlled by HBN reg_aon_pad_ie_smt, abandon romdriver for this reason */ #if 0 @@ -289,162 +123,61 @@ BL_Err_Type GLB_GPIO_Set_HZ(GLB_GPIO_Type gpioPin) } #endif -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_Deswap_Flash_Pin(void) -{ - return RomDriver_GLB_Deswap_Flash_Pin(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_Deswap_Flash_Pin(void) { return RomDriver_GLB_Deswap_Flash_Pin(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_Select_External_Flash(void) -{ - return RomDriver_GLB_Select_External_Flash(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_Select_External_Flash(void) { return RomDriver_GLB_Select_External_Flash(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - uint8_t - GLB_GPIO_Get_Fun(GLB_GPIO_Type gpioPin) -{ - return RomDriver_GLB_GPIO_Get_Fun(gpioPin); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint8_t GLB_GPIO_Get_Fun(GLB_GPIO_Type gpioPin) { return RomDriver_GLB_GPIO_Get_Fun(gpioPin); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Sts_Type - EF_Ctrl_Busy(void) -{ - return RomDriver_EF_Ctrl_Busy(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Sts_Type EF_Ctrl_Busy(void) { return RomDriver_EF_Ctrl_Busy(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void EF_Ctrl_Sw_AHB_Clk_0(void) -{ - RomDriver_EF_Ctrl_Sw_AHB_Clk_0(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void EF_Ctrl_Sw_AHB_Clk_0(void) { RomDriver_EF_Ctrl_Sw_AHB_Clk_0(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void EF_Ctrl_Load_Efuse_R0(void) -{ - RomDriver_EF_Ctrl_Load_Efuse_R0(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void EF_Ctrl_Load_Efuse_R0(void) { RomDriver_EF_Ctrl_Load_Efuse_R0(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void EF_Ctrl_Clear(uint32_t index, uint32_t len) -{ - RomDriver_EF_Ctrl_Clear(index, len); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void EF_Ctrl_Clear(uint32_t index, uint32_t len) { RomDriver_EF_Ctrl_Clear(index, len); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - uint8_t - EF_Ctrl_Get_Trim_Parity(uint32_t val, uint8_t len) -{ - return RomDriver_EF_Ctrl_Get_Trim_Parity(val, len); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION uint8_t EF_Ctrl_Get_Trim_Parity(uint32_t val, uint8_t len) { return RomDriver_EF_Ctrl_Get_Trim_Parity(val, len); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION void EF_Ctrl_Read_RC32K_Trim(Efuse_Ana_RC32K_Trim_Type *trim) -{ - RomDriver_EF_Ctrl_Read_RC32K_Trim(trim); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION void EF_Ctrl_Read_RC32K_Trim(Efuse_Ana_RC32K_Trim_Type *trim) { RomDriver_EF_Ctrl_Read_RC32K_Trim(trim); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION void EF_Ctrl_Read_RC32M_Trim(Efuse_Ana_RC32M_Trim_Type *trim) -{ - RomDriver_EF_Ctrl_Read_RC32M_Trim(trim); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION void EF_Ctrl_Read_RC32M_Trim(Efuse_Ana_RC32M_Trim_Type *trim) { RomDriver_EF_Ctrl_Read_RC32M_Trim(trim); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Trim_RC32M(void) -{ - return RomDriver_PDS_Trim_RC32M(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Trim_RC32M(void) { return RomDriver_PDS_Trim_RC32M(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Select_RC32M_As_PLL_Ref(void) -{ - return RomDriver_PDS_Select_RC32M_As_PLL_Ref(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Select_RC32M_As_PLL_Ref(void) { return RomDriver_PDS_Select_RC32M_As_PLL_Ref(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Select_XTAL_As_PLL_Ref(void) -{ - return RomDriver_PDS_Select_XTAL_As_PLL_Ref(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Select_XTAL_As_PLL_Ref(void) { return RomDriver_PDS_Select_XTAL_As_PLL_Ref(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Power_On_PLL(PDS_PLL_XTAL_Type xtalType) -{ - return RomDriver_PDS_Power_On_PLL(xtalType); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Power_On_PLL(PDS_PLL_XTAL_Type xtalType) { return RomDriver_PDS_Power_On_PLL(xtalType); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Enable_PLL_All_Clks(void) -{ - return RomDriver_PDS_Enable_PLL_All_Clks(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Enable_PLL_All_Clks(void) { return RomDriver_PDS_Enable_PLL_All_Clks(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Disable_PLL_All_Clks(void) -{ - return RomDriver_PDS_Disable_PLL_All_Clks(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Disable_PLL_All_Clks(void) { return RomDriver_PDS_Disable_PLL_All_Clks(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Enable_PLL_Clk(PDS_PLL_CLK_Type pllClk) -{ - return RomDriver_PDS_Enable_PLL_Clk(pllClk); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Enable_PLL_Clk(PDS_PLL_CLK_Type pllClk) { return RomDriver_PDS_Enable_PLL_Clk(pllClk); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Disable_PLL_Clk(PDS_PLL_CLK_Type pllClk) -{ - return RomDriver_PDS_Disable_PLL_Clk(pllClk); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Disable_PLL_Clk(PDS_PLL_CLK_Type pllClk) { return RomDriver_PDS_Disable_PLL_Clk(pllClk); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Power_Off_PLL(void) -{ - return RomDriver_PDS_Power_Off_PLL(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Power_Off_PLL(void) { return RomDriver_PDS_Power_Off_PLL(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Reset(void) -{ - RomDriver_PDS_Reset(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Reset(void) { RomDriver_PDS_Reset(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Enable(PDS_CFG_Type *cfg, uint32_t pdsSleepCnt) -{ - RomDriver_PDS_Enable(cfg, pdsSleepCnt); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Enable(PDS_CFG_Type *cfg, uint32_t pdsSleepCnt) { RomDriver_PDS_Enable(cfg, pdsSleepCnt); } -__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Auto_Time_Config(uint32_t sleepDuration) -{ - RomDriver_PDS_Auto_Time_Config(sleepDuration); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Auto_Time_Config(uint32_t sleepDuration) { RomDriver_PDS_Auto_Time_Config(sleepDuration); } -__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Auto_Enable(PDS_AUTO_POWER_DOWN_CFG_Type *powerCfg, PDS_AUTO_NORMAL_CFG_Type *normalCfg, BL_Fun_Type enable) -{ - RomDriver_PDS_Auto_Enable(powerCfg, normalCfg, enable); +__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Auto_Enable(PDS_AUTO_POWER_DOWN_CFG_Type *powerCfg, PDS_AUTO_NORMAL_CFG_Type *normalCfg, BL_Fun_Type enable) { + RomDriver_PDS_Auto_Enable(powerCfg, normalCfg, enable); } -__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Manual_Force_Turn_Off(PDS_FORCE_Type domain) -{ - RomDriver_PDS_Manual_Force_Turn_Off(domain); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Manual_Force_Turn_Off(PDS_FORCE_Type domain) { RomDriver_PDS_Manual_Force_Turn_Off(domain); } -__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Manual_Force_Turn_On(PDS_FORCE_Type domain) -{ - RomDriver_PDS_Manual_Force_Turn_On(domain); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Manual_Force_Turn_On(PDS_FORCE_Type domain) { RomDriver_PDS_Manual_Force_Turn_On(domain); } /******************************************************************************/ /******************************************************************************/ @@ -456,379 +189,169 @@ void HBN_Enable(uint8_t aGPIOIeCfg, HBN_LDO_LEVEL_Type ldoLevel, HBN_LEVEL_Type } #endif -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - HBN_Reset(void) -{ - return RomDriver_HBN_Reset(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type HBN_Reset(void) { return RomDriver_HBN_Reset(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - HBN_GPIO_Dbg_Pull_Cfg(BL_Fun_Type pupdEn, BL_Fun_Type dlyEn, uint8_t dlySec, HBN_INT_Type gpioIrq, BL_Mask_Type gpioMask) -{ - return RomDriver_HBN_GPIO_Dbg_Pull_Cfg(pupdEn, dlyEn, dlySec, gpioIrq, gpioMask); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type HBN_GPIO_Dbg_Pull_Cfg(BL_Fun_Type pupdEn, BL_Fun_Type dlyEn, uint8_t dlySec, HBN_INT_Type gpioIrq, BL_Mask_Type gpioMask) { + return RomDriver_HBN_GPIO_Dbg_Pull_Cfg(pupdEn, dlyEn, dlySec, gpioIrq, gpioMask); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - HBN_Trim_RC32K(void) -{ - return RomDriver_HBN_Trim_RC32K(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type HBN_Trim_RC32K(void) { return RomDriver_HBN_Trim_RC32K(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_Type rootClk) -{ - return RomDriver_HBN_Set_ROOT_CLK_Sel(rootClk); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_Type rootClk) { return RomDriver_HBN_Set_ROOT_CLK_Sel(rootClk); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_State_Save(SPI_Flash_Cfg_Type *pFlashCfg, uint32_t *offset) -{ - return RomDriver_XIP_SFlash_State_Save(pFlashCfg, offset); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_State_Save(SPI_Flash_Cfg_Type *pFlashCfg, uint32_t *offset) { return RomDriver_XIP_SFlash_State_Save(pFlashCfg, offset); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_State_Restore(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t offset) -{ - return RomDriver_XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_State_Restore(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t offset) { + return RomDriver_XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_Erase_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t startaddr, uint32_t endaddr) -{ - return RomDriver_XIP_SFlash_Erase_Need_Lock(pFlashCfg, ioMode, startaddr, endaddr); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_Erase_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t startaddr, uint32_t endaddr) { + return RomDriver_XIP_SFlash_Erase_Need_Lock(pFlashCfg, ioMode, startaddr, endaddr); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_Write_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - return RomDriver_XIP_SFlash_Write_Need_Lock(pFlashCfg, ioMode, addr, data, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_Write_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + return RomDriver_XIP_SFlash_Write_Need_Lock(pFlashCfg, ioMode, addr, data, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_Read_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - return RomDriver_XIP_SFlash_Read_Need_Lock(pFlashCfg, ioMode, addr, data, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_Read_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + return RomDriver_XIP_SFlash_Read_Need_Lock(pFlashCfg, ioMode, addr, data, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_GetJedecId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) -{ - return RomDriver_XIP_SFlash_GetJedecId_Need_Lock(pFlashCfg, ioMode, data); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_GetJedecId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) { + return RomDriver_XIP_SFlash_GetJedecId_Need_Lock(pFlashCfg, ioMode, data); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_GetDeviceId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) -{ - return RomDriver_XIP_SFlash_GetDeviceId_Need_Lock(pFlashCfg, ioMode, data); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_GetDeviceId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) { + return RomDriver_XIP_SFlash_GetDeviceId_Need_Lock(pFlashCfg, ioMode, data); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_GetUniqueId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data, uint8_t idLen) -{ - return RomDriver_XIP_SFlash_GetUniqueId_Need_Lock(pFlashCfg, ioMode, data, idLen); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_GetUniqueId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data, uint8_t idLen) { + return RomDriver_XIP_SFlash_GetUniqueId_Need_Lock(pFlashCfg, ioMode, data, idLen); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_Read_Via_Cache_Need_Lock(uint32_t addr, uint8_t *data, uint32_t len) -{ - return RomDriver_XIP_SFlash_Read_Via_Cache_Need_Lock(addr, data, len); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_Read_Via_Cache_Need_Lock(uint32_t addr, uint8_t *data, uint32_t len) { return RomDriver_XIP_SFlash_Read_Via_Cache_Need_Lock(addr, data, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION int XIP_SFlash_Read_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *dst, int len) -{ - return RomDriver_XIP_SFlash_Read_With_Lock(pFlashCfg, ioMode, addr, dst, len); +__ALWAYS_INLINE ATTR_TCM_SECTION int XIP_SFlash_Read_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *dst, int len) { + return RomDriver_XIP_SFlash_Read_With_Lock(pFlashCfg, ioMode, addr, dst, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION int XIP_SFlash_Write_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *src, int len) -{ - return RomDriver_XIP_SFlash_Write_With_Lock(pFlashCfg, ioMode, addr, src, len); +__ALWAYS_INLINE ATTR_TCM_SECTION int XIP_SFlash_Write_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *src, int len) { + return RomDriver_XIP_SFlash_Write_With_Lock(pFlashCfg, ioMode, addr, src, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION int XIP_SFlash_Erase_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, int len) -{ - return RomDriver_XIP_SFlash_Erase_With_Lock(pFlashCfg, ioMode, addr, len); +__ALWAYS_INLINE ATTR_TCM_SECTION int XIP_SFlash_Erase_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, int len) { + return RomDriver_XIP_SFlash_Erase_With_Lock(pFlashCfg, ioMode, addr, len); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Init(const SF_Ctrl_Cfg_Type *pSfCtrlCfg) -{ - RomDriver_SFlash_Init(pSfCtrlCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Init(const SF_Ctrl_Cfg_Type *pSfCtrlCfg) { RomDriver_SFlash_Init(pSfCtrlCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_SetSPIMode(SF_Ctrl_Mode_Type mode) -{ - return RomDriver_SFlash_SetSPIMode(mode); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_SetSPIMode(SF_Ctrl_Mode_Type mode) { return RomDriver_SFlash_SetSPIMode(mode); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Read_Reg(SPI_Flash_Cfg_Type *flashCfg, uint8_t regIndex, uint8_t *regValue, uint8_t regLen) -{ - return RomDriver_SFlash_Read_Reg(flashCfg, regIndex, regValue, regLen); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Read_Reg(SPI_Flash_Cfg_Type *flashCfg, uint8_t regIndex, uint8_t *regValue, uint8_t regLen) { + return RomDriver_SFlash_Read_Reg(flashCfg, regIndex, regValue, regLen); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Write_Reg(SPI_Flash_Cfg_Type *flashCfg, uint8_t regIndex, uint8_t *regValue, uint8_t regLen) -{ - return RomDriver_SFlash_Write_Reg(flashCfg, regIndex, regValue, regLen); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Write_Reg(SPI_Flash_Cfg_Type *flashCfg, uint8_t regIndex, uint8_t *regValue, uint8_t regLen) { + return RomDriver_SFlash_Write_Reg(flashCfg, regIndex, regValue, regLen); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Read_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t readRegCmd, uint8_t *regValue, uint8_t regLen) -{ - return RomDriver_SFlash_Read_Reg_With_Cmd(flashCfg, readRegCmd, regValue, regLen); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Read_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t readRegCmd, uint8_t *regValue, uint8_t regLen) { + return RomDriver_SFlash_Read_Reg_With_Cmd(flashCfg, readRegCmd, regValue, regLen); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Write_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t writeRegCmd, uint8_t *regValue, uint8_t regLen) -{ - return RomDriver_SFlash_Write_Reg_With_Cmd(flashCfg, writeRegCmd, regValue, regLen); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Write_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t writeRegCmd, uint8_t *regValue, uint8_t regLen) { + return RomDriver_SFlash_Write_Reg_With_Cmd(flashCfg, writeRegCmd, regValue, regLen); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Sts_Type - SFlash_Busy(SPI_Flash_Cfg_Type *flashCfg) -{ - return RomDriver_SFlash_Busy(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Sts_Type SFlash_Busy(SPI_Flash_Cfg_Type *flashCfg) { return RomDriver_SFlash_Busy(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Write_Enable(SPI_Flash_Cfg_Type *flashCfg) -{ - return RomDriver_SFlash_Write_Enable(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Write_Enable(SPI_Flash_Cfg_Type *flashCfg) { return RomDriver_SFlash_Write_Enable(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Qspi_Enable(SPI_Flash_Cfg_Type *flashCfg) -{ - return RomDriver_SFlash_Qspi_Enable(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Qspi_Enable(SPI_Flash_Cfg_Type *flashCfg) { return RomDriver_SFlash_Qspi_Enable(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Volatile_Reg_Write_Enable(SPI_Flash_Cfg_Type *flashCfg) -{ - RomDriver_SFlash_Volatile_Reg_Write_Enable(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Volatile_Reg_Write_Enable(SPI_Flash_Cfg_Type *flashCfg) { RomDriver_SFlash_Volatile_Reg_Write_Enable(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Chip_Erase(SPI_Flash_Cfg_Type *flashCfg) -{ - return RomDriver_SFlash_Chip_Erase(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Chip_Erase(SPI_Flash_Cfg_Type *flashCfg) { return RomDriver_SFlash_Chip_Erase(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Sector_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t secNum) -{ - return RomDriver_SFlash_Sector_Erase(flashCfg, secNum); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Sector_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t secNum) { return RomDriver_SFlash_Sector_Erase(flashCfg, secNum); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Blk32_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t blkNum) -{ - return RomDriver_SFlash_Blk32_Erase(flashCfg, blkNum); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Blk32_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t blkNum) { return RomDriver_SFlash_Blk32_Erase(flashCfg, blkNum); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Blk64_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t blkNum) -{ - return RomDriver_SFlash_Blk64_Erase(flashCfg, blkNum); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Blk64_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t blkNum) { return RomDriver_SFlash_Blk64_Erase(flashCfg, blkNum); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t startaddr, uint32_t endaddr) -{ - return RomDriver_SFlash_Erase(flashCfg, startaddr, endaddr); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t startaddr, uint32_t endaddr) { return RomDriver_SFlash_Erase(flashCfg, startaddr, endaddr); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Program(SPI_Flash_Cfg_Type *flashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - return RomDriver_SFlash_Program(flashCfg, ioMode, addr, data, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Program(SPI_Flash_Cfg_Type *flashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + return RomDriver_SFlash_Program(flashCfg, ioMode, addr, data, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_GetUniqueId(uint8_t *data, uint8_t idLen) -{ - RomDriver_SFlash_GetUniqueId(data, idLen); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_GetUniqueId(uint8_t *data, uint8_t idLen) { RomDriver_SFlash_GetUniqueId(data, idLen); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_GetJedecId(SPI_Flash_Cfg_Type *flashCfg, uint8_t *data) -{ - RomDriver_SFlash_GetJedecId(flashCfg, data); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_GetJedecId(SPI_Flash_Cfg_Type *flashCfg, uint8_t *data) { RomDriver_SFlash_GetJedecId(flashCfg, data); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_GetDeviceId(uint8_t *data) -{ - RomDriver_SFlash_GetDeviceId(data); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_GetDeviceId(uint8_t *data) { RomDriver_SFlash_GetDeviceId(data); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Powerdown(void) -{ - RomDriver_SFlash_Powerdown(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Powerdown(void) { RomDriver_SFlash_Powerdown(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Releae_Powerdown(SPI_Flash_Cfg_Type *flashCfg) -{ - RomDriver_SFlash_Releae_Powerdown(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Releae_Powerdown(SPI_Flash_Cfg_Type *flashCfg) { RomDriver_SFlash_Releae_Powerdown(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Restore_From_Powerdown(SPI_Flash_Cfg_Type *pFlashCfg, uint8_t flashContRead) -{ - return RomDriver_SFlash_Restore_From_Powerdown(pFlashCfg, flashContRead); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Restore_From_Powerdown(SPI_Flash_Cfg_Type *pFlashCfg, uint8_t flashContRead) { + return RomDriver_SFlash_Restore_From_Powerdown(pFlashCfg, flashContRead); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_SetBurstWrap(SPI_Flash_Cfg_Type *flashCfg) -{ - RomDriver_SFlash_SetBurstWrap(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_SetBurstWrap(SPI_Flash_Cfg_Type *flashCfg) { RomDriver_SFlash_SetBurstWrap(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_DisableBurstWrap(SPI_Flash_Cfg_Type *flashCfg) -{ - RomDriver_SFlash_DisableBurstWrap(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_DisableBurstWrap(SPI_Flash_Cfg_Type *flashCfg) { RomDriver_SFlash_DisableBurstWrap(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Software_Reset(SPI_Flash_Cfg_Type *flashCfg) -{ - return RomDriver_SFlash_Software_Reset(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Software_Reset(SPI_Flash_Cfg_Type *flashCfg) { return RomDriver_SFlash_Software_Reset(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Reset_Continue_Read(SPI_Flash_Cfg_Type *flashCfg) -{ - return RomDriver_SFlash_Reset_Continue_Read(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Reset_Continue_Read(SPI_Flash_Cfg_Type *flashCfg) { return RomDriver_SFlash_Reset_Continue_Read(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Set_IDbus_Cfg(SPI_Flash_Cfg_Type *flashCfg, - SF_Ctrl_IO_Type ioMode, uint8_t contRead, uint32_t addr, uint32_t len) -{ - return RomDriver_SFlash_Set_IDbus_Cfg(flashCfg, ioMode, contRead, addr, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Set_IDbus_Cfg(SPI_Flash_Cfg_Type *flashCfg, SF_Ctrl_IO_Type ioMode, uint8_t contRead, uint32_t addr, uint32_t len) { + return RomDriver_SFlash_Set_IDbus_Cfg(flashCfg, ioMode, contRead, addr, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_IDbus_Read_Enable(SPI_Flash_Cfg_Type *flashCfg, SF_Ctrl_IO_Type ioMode, uint8_t contRead) -{ - return RomDriver_SFlash_IDbus_Read_Enable(flashCfg, ioMode, contRead); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_IDbus_Read_Enable(SPI_Flash_Cfg_Type *flashCfg, SF_Ctrl_IO_Type ioMode, uint8_t contRead) { + return RomDriver_SFlash_IDbus_Read_Enable(flashCfg, ioMode, contRead); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Cache_Read_Enable(SPI_Flash_Cfg_Type *flashCfg, - SF_Ctrl_IO_Type ioMode, uint8_t contRead, uint8_t wayDisable) -{ - return RomDriver_SFlash_Cache_Read_Enable(flashCfg, ioMode, contRead, wayDisable); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Cache_Read_Enable(SPI_Flash_Cfg_Type *flashCfg, SF_Ctrl_IO_Type ioMode, uint8_t contRead, uint8_t wayDisable) { + return RomDriver_SFlash_Cache_Read_Enable(flashCfg, ioMode, contRead, wayDisable); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Cache_Read_Disable(void) -{ - RomDriver_SFlash_Cache_Read_Disable(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Cache_Read_Disable(void) { RomDriver_SFlash_Cache_Read_Disable(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Read(SPI_Flash_Cfg_Type *flashCfg, - SF_Ctrl_IO_Type ioMode, uint8_t contRead, uint32_t addr, uint8_t *data, uint32_t len) -{ - return RomDriver_SFlash_Read(flashCfg, ioMode, contRead, addr, data, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Read(SPI_Flash_Cfg_Type *flashCfg, SF_Ctrl_IO_Type ioMode, uint8_t contRead, uint32_t addr, uint8_t *data, uint32_t len) { + return RomDriver_SFlash_Read(flashCfg, ioMode, contRead, addr, data, len); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - L1C_Cache_Enable_Set(uint8_t wayDisable) -{ - return RomDriver_L1C_Cache_Enable_Set(wayDisable); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type L1C_Cache_Enable_Set(uint8_t wayDisable) { return RomDriver_L1C_Cache_Enable_Set(wayDisable); } -__ALWAYS_INLINE ATTR_TCM_SECTION void L1C_Cache_Write_Set(BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) -{ - RomDriver_L1C_Cache_Write_Set(wtEn, wbEn, waEn); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void L1C_Cache_Write_Set(BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) { RomDriver_L1C_Cache_Write_Set(wtEn, wbEn, waEn); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - L1C_Cache_Flush(uint8_t wayDisable) -{ - return RomDriver_L1C_Cache_Flush(wayDisable); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type L1C_Cache_Flush(uint8_t wayDisable) { return RomDriver_L1C_Cache_Flush(wayDisable); } -__ALWAYS_INLINE ATTR_TCM_SECTION void L1C_Cache_Hit_Count_Get(uint32_t *hitCountLow, uint32_t *hitCountHigh) -{ - RomDriver_L1C_Cache_Hit_Count_Get(hitCountLow, hitCountHigh); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void L1C_Cache_Hit_Count_Get(uint32_t *hitCountLow, uint32_t *hitCountHigh) { RomDriver_L1C_Cache_Hit_Count_Get(hitCountLow, hitCountHigh); } -__ALWAYS_INLINE ATTR_TCM_SECTION - uint32_t - L1C_Cache_Miss_Count_Get(void) -{ - return RomDriver_L1C_Cache_Miss_Count_Get(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint32_t L1C_Cache_Miss_Count_Get(void) { return RomDriver_L1C_Cache_Miss_Count_Get(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void L1C_Cache_Read_Disable(void) -{ - RomDriver_L1C_Cache_Read_Disable(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void L1C_Cache_Read_Disable(void) { RomDriver_L1C_Cache_Read_Disable(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - L1C_Set_Wrap(BL_Fun_Type wrap) -{ - return RomDriver_L1C_Set_Wrap(wrap); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type L1C_Set_Wrap(BL_Fun_Type wrap) { return RomDriver_L1C_Set_Wrap(wrap); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - L1C_Set_Way_Disable(uint8_t disableVal) -{ - return RomDriver_L1C_Set_Way_Disable(disableVal); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type L1C_Set_Way_Disable(uint8_t disableVal) { return RomDriver_L1C_Set_Way_Disable(disableVal); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - L1C_IROM_2T_Access_Set(uint8_t enable) -{ - return RomDriver_L1C_IROM_2T_Access_Set(enable); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type L1C_IROM_2T_Access_Set(uint8_t enable) { return RomDriver_L1C_IROM_2T_Access_Set(enable); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Enable(const SF_Ctrl_Cfg_Type *cfg) -{ - RomDriver_SF_Ctrl_Enable(cfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Enable(const SF_Ctrl_Cfg_Type *cfg) { RomDriver_SF_Ctrl_Enable(cfg); } #if 0 __ALWAYS_INLINE ATTR_TCM_SECTION @@ -838,156 +361,63 @@ void SF_Ctrl_Psram_Init(SF_Ctrl_Psram_Cfg *sfCtrlPsramCfg) } #endif -__ALWAYS_INLINE ATTR_TCM_SECTION - uint8_t - SF_Ctrl_Get_Clock_Delay(void) -{ - return RomDriver_SF_Ctrl_Get_Clock_Delay(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint8_t SF_Ctrl_Get_Clock_Delay(void) { return RomDriver_SF_Ctrl_Get_Clock_Delay(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Set_Clock_Delay(uint8_t delay) -{ - RomDriver_SF_Ctrl_Set_Clock_Delay(delay); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Set_Clock_Delay(uint8_t delay) { RomDriver_SF_Ctrl_Set_Clock_Delay(delay); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Cmds_Set(SF_Ctrl_Cmds_Cfg *cmdsCfg) -{ - RomDriver_SF_Ctrl_Cmds_Set(cmdsCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Cmds_Set(SF_Ctrl_Cmds_Cfg *cmdsCfg) { RomDriver_SF_Ctrl_Cmds_Set(cmdsCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Set_Owner(SF_Ctrl_Owner_Type owner) -{ - RomDriver_SF_Ctrl_Set_Owner(owner); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Set_Owner(SF_Ctrl_Owner_Type owner) { RomDriver_SF_Ctrl_Set_Owner(owner); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Disable(void) -{ - RomDriver_SF_Ctrl_Disable(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Disable(void) { RomDriver_SF_Ctrl_Disable(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Select_Pad(SF_Ctrl_Pad_Select sel) -{ - RomDriver_SF_Ctrl_Select_Pad(sel); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Select_Pad(SF_Ctrl_Pad_Select sel) { RomDriver_SF_Ctrl_Select_Pad(sel); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Select_Bank(SF_Ctrl_Select sel) -{ - RomDriver_SF_Ctrl_Select_Bank(sel); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Select_Bank(SF_Ctrl_Select sel) { RomDriver_SF_Ctrl_Select_Bank(sel); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Enable_BE(void) -{ - RomDriver_SF_Ctrl_AES_Enable_BE(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Enable_BE(void) { RomDriver_SF_Ctrl_AES_Enable_BE(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Enable_LE(void) -{ - RomDriver_SF_Ctrl_AES_Enable_LE(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Enable_LE(void) { RomDriver_SF_Ctrl_AES_Enable_LE(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_Region(uint8_t region, uint8_t enable, - uint8_t hwKey, uint32_t startAddr, uint32_t endAddr, uint8_t locked) -{ - RomDriver_SF_Ctrl_AES_Set_Region(region, enable, hwKey, startAddr, endAddr, locked); +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_Region(uint8_t region, uint8_t enable, uint8_t hwKey, uint32_t startAddr, uint32_t endAddr, uint8_t locked) { + RomDriver_SF_Ctrl_AES_Set_Region(region, enable, hwKey, startAddr, endAddr, locked); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_Key(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) -{ - RomDriver_SF_Ctrl_AES_Set_Key(region, key, keyType); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_Key(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) { RomDriver_SF_Ctrl_AES_Set_Key(region, key, keyType); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_Key_BE(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) -{ - RomDriver_SF_Ctrl_AES_Set_Key_BE(region, key, keyType); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_Key_BE(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) { RomDriver_SF_Ctrl_AES_Set_Key_BE(region, key, keyType); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_IV(uint8_t region, uint8_t *iv, uint32_t addrOffset) -{ - RomDriver_SF_Ctrl_AES_Set_IV(region, iv, addrOffset); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_IV(uint8_t region, uint8_t *iv, uint32_t addrOffset) { RomDriver_SF_Ctrl_AES_Set_IV(region, iv, addrOffset); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_IV_BE(uint8_t region, uint8_t *iv, uint32_t addrOffset) -{ - RomDriver_SF_Ctrl_AES_Set_IV_BE(region, iv, addrOffset); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_IV_BE(uint8_t region, uint8_t *iv, uint32_t addrOffset) { RomDriver_SF_Ctrl_AES_Set_IV_BE(region, iv, addrOffset); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Enable(void) -{ - RomDriver_SF_Ctrl_AES_Enable(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Enable(void) { RomDriver_SF_Ctrl_AES_Enable(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Disable(void) -{ - RomDriver_SF_Ctrl_AES_Disable(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Disable(void) { RomDriver_SF_Ctrl_AES_Disable(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - uint8_t - SF_Ctrl_Is_AES_Enable(void) -{ - return RomDriver_SF_Ctrl_Is_AES_Enable(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint8_t SF_Ctrl_Is_AES_Enable(void) { return RomDriver_SF_Ctrl_Is_AES_Enable(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Set_Flash_Image_Offset(uint32_t addrOffset) -{ - RomDriver_SF_Ctrl_Set_Flash_Image_Offset(addrOffset); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Set_Flash_Image_Offset(uint32_t addrOffset) { RomDriver_SF_Ctrl_Set_Flash_Image_Offset(addrOffset); } -__ALWAYS_INLINE ATTR_TCM_SECTION - uint32_t - SF_Ctrl_Get_Flash_Image_Offset(void) -{ - return RomDriver_SF_Ctrl_Get_Flash_Image_Offset(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint32_t SF_Ctrl_Get_Flash_Image_Offset(void) { return RomDriver_SF_Ctrl_Get_Flash_Image_Offset(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Select_Clock(SF_Ctrl_Sahb_Type sahbType) -{ - RomDriver_SF_Ctrl_Select_Clock(sahbType); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Select_Clock(SF_Ctrl_Sahb_Type sahbType) { RomDriver_SF_Ctrl_Select_Clock(sahbType); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_SendCmd(SF_Ctrl_Cmd_Cfg_Type *cfg) -{ - RomDriver_SF_Ctrl_SendCmd(cfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_SendCmd(SF_Ctrl_Cmd_Cfg_Type *cfg) { RomDriver_SF_Ctrl_SendCmd(cfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Flash_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) -{ - RomDriver_SF_Ctrl_Flash_Read_Icache_Set(cfg, cmdValid); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Flash_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) { RomDriver_SF_Ctrl_Flash_Read_Icache_Set(cfg, cmdValid); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Psram_Write_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) -{ - RomDriver_SF_Ctrl_Psram_Write_Icache_Set(cfg, cmdValid); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Psram_Write_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) { RomDriver_SF_Ctrl_Psram_Write_Icache_Set(cfg, cmdValid); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Psram_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) -{ - RomDriver_SF_Ctrl_Psram_Read_Icache_Set(cfg, cmdValid); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Psram_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) { RomDriver_SF_Ctrl_Psram_Read_Icache_Set(cfg, cmdValid); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Sts_Type - SF_Ctrl_GetBusyState(void) -{ - return RomDriver_SF_Ctrl_GetBusyState(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Sts_Type SF_Ctrl_GetBusyState(void) { return RomDriver_SF_Ctrl_GetBusyState(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Cfg_Deinit_Ext_Flash_Gpio(uint8_t extFlashPin) -{ - RomDriver_SF_Cfg_Deinit_Ext_Flash_Gpio(extFlashPin); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Cfg_Deinit_Ext_Flash_Gpio(uint8_t extFlashPin) { RomDriver_SF_Cfg_Deinit_Ext_Flash_Gpio(extFlashPin); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Cfg_Init_Ext_Flash_Gpio(uint8_t extFlashPin) -{ - RomDriver_SF_Cfg_Init_Ext_Flash_Gpio(extFlashPin); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Cfg_Init_Ext_Flash_Gpio(uint8_t extFlashPin) { RomDriver_SF_Cfg_Init_Ext_Flash_Gpio(extFlashPin); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SF_Cfg_Get_Flash_Cfg_Need_Lock(uint32_t flashID, SPI_Flash_Cfg_Type *pFlashCfg) -{ - return RomDriver_SF_Cfg_Get_Flash_Cfg_Need_Lock(flashID, pFlashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SF_Cfg_Get_Flash_Cfg_Need_Lock(uint32_t flashID, SPI_Flash_Cfg_Type *pFlashCfg) { return RomDriver_SF_Cfg_Get_Flash_Cfg_Need_Lock(flashID, pFlashCfg); } #if 0 __ALWAYS_INLINE ATTR_TCM_SECTION @@ -997,12 +427,8 @@ void SF_Cfg_Init_Flash_Gpio(uint8_t flashPinCfg, uint8_t restoreDefault) } #endif -__ALWAYS_INLINE ATTR_TCM_SECTION - uint32_t - SF_Cfg_Flash_Identify(uint8_t callFromFlash, uint32_t autoScan, uint32_t flashPinCfg, uint8_t restoreDefault, - SPI_Flash_Cfg_Type *pFlashCfg) -{ - return RomDriver_SF_Cfg_Flash_Identify(callFromFlash, autoScan, flashPinCfg, restoreDefault, pFlashCfg); +__ALWAYS_INLINE ATTR_TCM_SECTION uint32_t SF_Cfg_Flash_Identify(uint8_t callFromFlash, uint32_t autoScan, uint32_t flashPinCfg, uint8_t restoreDefault, SPI_Flash_Cfg_Type *pFlashCfg) { + return RomDriver_SF_Cfg_Flash_Identify(callFromFlash, autoScan, flashPinCfg, restoreDefault, pFlashCfg); } /******************************************************************************/ @@ -1015,92 +441,37 @@ void Psram_Init(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_Cmds_Cfg *cmdsCfg, SF_Ctrl } #endif -__ALWAYS_INLINE ATTR_TCM_SECTION void Psram_ReadReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) -{ - RomDriver_Psram_ReadReg(psramCfg, regValue); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void Psram_ReadReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) { RomDriver_Psram_ReadReg(psramCfg, regValue); } -__ALWAYS_INLINE ATTR_TCM_SECTION void Psram_WriteReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) -{ - RomDriver_Psram_WriteReg(psramCfg, regValue); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void Psram_WriteReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) { RomDriver_Psram_WriteReg(psramCfg, regValue); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_SetDriveStrength(SPI_Psram_Cfg_Type *psramCfg) -{ - return RomDriver_Psram_SetDriveStrength(psramCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_SetDriveStrength(SPI_Psram_Cfg_Type *psramCfg) { return RomDriver_Psram_SetDriveStrength(psramCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_SetBurstWrap(SPI_Psram_Cfg_Type *psramCfg) -{ - return RomDriver_Psram_SetBurstWrap(psramCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_SetBurstWrap(SPI_Psram_Cfg_Type *psramCfg) { return RomDriver_Psram_SetBurstWrap(psramCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION void Psram_ReadId(SPI_Psram_Cfg_Type *psramCfg, uint8_t *data) -{ - RomDriver_Psram_ReadId(psramCfg, data); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void Psram_ReadId(SPI_Psram_Cfg_Type *psramCfg, uint8_t *data) { RomDriver_Psram_ReadId(psramCfg, data); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_EnterQuadMode(SPI_Psram_Cfg_Type *psramCfg) -{ - return RomDriver_Psram_EnterQuadMode(psramCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_EnterQuadMode(SPI_Psram_Cfg_Type *psramCfg) { return RomDriver_Psram_EnterQuadMode(psramCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_ExitQuadMode(SPI_Psram_Cfg_Type *psramCfg) -{ - return RomDriver_Psram_ExitQuadMode(psramCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_ExitQuadMode(SPI_Psram_Cfg_Type *psramCfg) { return RomDriver_Psram_ExitQuadMode(psramCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_ToggleBurstLength(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) -{ - return RomDriver_Psram_ToggleBurstLength(psramCfg, ctrlMode); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_ToggleBurstLength(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) { return RomDriver_Psram_ToggleBurstLength(psramCfg, ctrlMode); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_SoftwareReset(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) -{ - return RomDriver_Psram_SoftwareReset(psramCfg, ctrlMode); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_SoftwareReset(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) { return RomDriver_Psram_SoftwareReset(psramCfg, ctrlMode); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_Set_IDbus_Cfg(SPI_Psram_Cfg_Type *psramCfg, - SF_Ctrl_IO_Type ioMode, uint32_t addr, uint32_t len) -{ - return RomDriver_Psram_Set_IDbus_Cfg(psramCfg, ioMode, addr, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_Set_IDbus_Cfg(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint32_t len) { + return RomDriver_Psram_Set_IDbus_Cfg(psramCfg, ioMode, addr, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_Cache_Write_Set(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, - BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) -{ - return RomDriver_Psram_Cache_Write_Set(psramCfg, ioMode, wtEn, wbEn, waEn); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_Cache_Write_Set(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) { + return RomDriver_Psram_Cache_Write_Set(psramCfg, ioMode, wtEn, wbEn, waEn); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_Write(SPI_Psram_Cfg_Type *psramCfg, - SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - return RomDriver_Psram_Write(psramCfg, ioMode, addr, data, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_Write(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + return RomDriver_Psram_Write(psramCfg, ioMode, addr, data, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_Read(SPI_Psram_Cfg_Type *psramCfg, - SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - return RomDriver_Psram_Read(psramCfg, ioMode, addr, data, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_Read(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + return RomDriver_Psram_Read(psramCfg, ioMode, addr, data, len); } /******************************************************************************/ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_dbg.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_dbg.c index 0db07bef1a..214761ae5b 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_dbg.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_dbg.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_sec_dbg.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_sec_dbg.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "string.h" #include "bl702_sec_dbg.h" +#include "string.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -80,69 +80,61 @@ */ /****************************************************************************/ /** - * @brief Sec Dbg read chip ID - * - * @param id[8]: chip ID buffer - * - * @return None - * -*******************************************************************************/ -void Sec_Dbg_Read_Chip_ID(uint8_t id[8]) -{ - uint32_t idLow, idHigh; - - idLow = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_CHIP_ID_LOW); - BL_WRWD_TO_BYTEP(id, idLow); - - idHigh = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_CHIP_ID_HIGH); - BL_WRWD_TO_BYTEP((id + 4), idHigh); + * @brief Sec Dbg read chip ID + * + * @param id[8]: chip ID buffer + * + * @return None + * + *******************************************************************************/ +void Sec_Dbg_Read_Chip_ID(uint8_t id[8]) { + uint32_t idLow, idHigh; + + idLow = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_CHIP_ID_LOW); + BL_WRWD_TO_BYTEP(id, idLow); + + idHigh = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_CHIP_ID_HIGH); + BL_WRWD_TO_BYTEP((id + 4), idHigh); } /****************************************************************************/ /** - * @brief Sec Dbg read MAC address - * - * @param macAddr[6]: MAC address buffer - * - * @return None - * -*******************************************************************************/ -void Sec_Dbg_Read_WiFi_MAC(uint8_t macAddr[6]) -{ - uint32_t macLow, macHigh; - - macLow = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_WIFI_MAC_LOW); - BL_WRWD_TO_BYTEP(macAddr, macLow); - - macHigh = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_WIFI_MAC_HIGH); - macAddr[4] = (macHigh >> 0) & 0xff; - macAddr[5] = (macHigh >> 8) & 0xff; + * @brief Sec Dbg read MAC address + * + * @param macAddr[6]: MAC address buffer + * + * @return None + * + *******************************************************************************/ +void Sec_Dbg_Read_WiFi_MAC(uint8_t macAddr[6]) { + uint32_t macLow, macHigh; + + macLow = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_WIFI_MAC_LOW); + BL_WRWD_TO_BYTEP(macAddr, macLow); + + macHigh = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_WIFI_MAC_HIGH); + macAddr[4] = (macHigh >> 0) & 0xff; + macAddr[5] = (macHigh >> 8) & 0xff; } /****************************************************************************/ /** - * @brief Sec Dbg read debug mode - * - * @param None - * - * @return debug mode status - * -*******************************************************************************/ -uint32_t Sec_Dbg_Read_Dbg_Mode(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_STATUS), SEC_DBG_SD_DBG_MODE); -} + * @brief Sec Dbg read debug mode + * + * @param None + * + * @return debug mode status + * + *******************************************************************************/ +uint32_t Sec_Dbg_Read_Dbg_Mode(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_STATUS), SEC_DBG_SD_DBG_MODE); } /****************************************************************************/ /** - * @brief Sec Dbg read debug enable status - * - * @param None - * - * @return enable status - * -*******************************************************************************/ -uint32_t Sec_Dbg_Read_Dbg_Enable(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_STATUS), SEC_DBG_SD_DBG_ENA); -} + * @brief Sec Dbg read debug enable status + * + * @param None + * + * @return enable status + * + *******************************************************************************/ +uint32_t Sec_Dbg_Read_Dbg_Enable(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_STATUS), SEC_DBG_SD_DBG_ENA); } /*@} end of group SEC_DBG_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_eng.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_eng.c index 8939276de1..6b86ef10f3 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_eng.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_eng.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_sec_eng.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_sec_eng.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "string.h" #include "bl702_sec_eng.h" +#include "string.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -48,24 +48,24 @@ /** @defgroup SEC_ENG_Private_Macros * @{ */ -#define PUT_UINT32_BE(n, b, i) \ - { \ - (b)[(i)] = (uint8_t)((n) >> 24); \ - (b)[(i) + 1] = (uint8_t)((n) >> 16); \ - (b)[(i) + 2] = (uint8_t)((n) >> 8); \ - (b)[(i) + 3] = (uint8_t)((n)); \ - } -#define PUT_UINT64_BE(n, b, i) \ - { \ - (b)[(i)] = (uint8_t)((n) >> 56); \ - (b)[(i) + 1] = (uint8_t)((n) >> 48); \ - (b)[(i) + 2] = (uint8_t)((n) >> 40); \ - (b)[(i) + 3] = (uint8_t)((n) >> 32); \ - (b)[(i) + 4] = (uint8_t)((n) >> 24); \ - (b)[(i) + 5] = (uint8_t)((n) >> 16); \ - (b)[(i) + 6] = (uint8_t)((n) >> 8); \ - (b)[(i) + 7] = (uint8_t)((n)); \ - } +#define PUT_UINT32_BE(n, b, i) \ + { \ + (b)[(i)] = (uint8_t)((n) >> 24); \ + (b)[(i) + 1] = (uint8_t)((n) >> 16); \ + (b)[(i) + 2] = (uint8_t)((n) >> 8); \ + (b)[(i) + 3] = (uint8_t)((n)); \ + } +#define PUT_UINT64_BE(n, b, i) \ + { \ + (b)[(i)] = (uint8_t)((n) >> 56); \ + (b)[(i) + 1] = (uint8_t)((n) >> 48); \ + (b)[(i) + 2] = (uint8_t)((n) >> 40); \ + (b)[(i) + 3] = (uint8_t)((n) >> 32); \ + (b)[(i) + 4] = (uint8_t)((n) >> 24); \ + (b)[(i) + 5] = (uint8_t)((n) >> 16); \ + (b)[(i) + 6] = (uint8_t)((n) >> 8); \ + (b)[(i) + 7] = (uint8_t)((n)); \ + } #define SEC_ENG_SHA_BUSY_TIMEOUT_COUNT (100 * 160 * 1000) #define SEC_ENG_AES_BUSY_TIMEOUT_COUNT (100 * 160 * 1000) #define SEC_ENG_TRNG_BUSY_TIMEOUT_COUNT (100 * 160 * 1000) @@ -78,96 +78,89 @@ * @{ */ struct pka0_pld_cfg { - union { - struct - { - uint32_t size : 12; /*[11: 0], r/w, 0x0 */ - uint32_t d_reg_index : 8; /*[19:12], r/w, 0x0 */ - uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ - uint32_t op : 7; /*[30:24], r/w, 0x0 */ - uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ - } BF; - uint32_t WORD; - } value; + union { + struct { + uint32_t size : 12; /*[11: 0], r/w, 0x0 */ + uint32_t d_reg_index : 8; /*[19:12], r/w, 0x0 */ + uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ + uint32_t op : 7; /*[30:24], r/w, 0x0 */ + uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ + } BF; + uint32_t WORD; + } value; }; struct pka0_pldi_cfg { - union { - struct - { - uint32_t rsvd : 12; /*[11: 0], r/w, 0x0 */ - uint32_t d_reg_index : 8; /*[19:12], r/w, 0x0 */ - uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ - uint32_t op : 7; /*[30:24], r/w, 0x0 */ - uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ - } BF; - uint32_t WORD; - } value; + union { + struct { + uint32_t rsvd : 12; /*[11: 0], r/w, 0x0 */ + uint32_t d_reg_index : 8; /*[19:12], r/w, 0x0 */ + uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ + uint32_t op : 7; /*[30:24], r/w, 0x0 */ + uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ + } BF; + uint32_t WORD; + } value; }; struct pka0_common_op_first_cfg { - union { - struct - { - uint32_t s0_reg_idx : 8; /*[7: 0], r/w, 0x0 */ - uint32_t s0_reg_type : 4; /*[11:8], r/w, 0x0 */ - uint32_t d_reg_idx : 8; /*[19:12], r/w, 0x0 */ - uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ - uint32_t op : 7; /*[30:24], r/w, 0x0 */ - uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ - } BF; - uint32_t WORD; - } value; + union { + struct { + uint32_t s0_reg_idx : 8; /*[7: 0], r/w, 0x0 */ + uint32_t s0_reg_type : 4; /*[11:8], r/w, 0x0 */ + uint32_t d_reg_idx : 8; /*[19:12], r/w, 0x0 */ + uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ + uint32_t op : 7; /*[30:24], r/w, 0x0 */ + uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ + } BF; + uint32_t WORD; + } value; }; struct pka0_common_op_snd_cfg_S1_only { - union { - struct - { - uint32_t reserved_0_11 : 12; /*[11: 0], rsvd, 0x0 */ - uint32_t s1_reg_idx : 8; /*[19:12], r/w, 0x0 */ - uint32_t s1_reg_type : 4; /*[23:20], r/w, 0x0 */ - uint32_t reserved_24_31 : 8; /*[31:24], rsvd, 0x0 */ - } BF; - uint32_t WORD; - } value; + union { + struct { + uint32_t reserved_0_11 : 12; /*[11: 0], rsvd, 0x0 */ + uint32_t s1_reg_idx : 8; /*[19:12], r/w, 0x0 */ + uint32_t s1_reg_type : 4; /*[23:20], r/w, 0x0 */ + uint32_t reserved_24_31 : 8; /*[31:24], rsvd, 0x0 */ + } BF; + uint32_t WORD; + } value; }; struct pka0_common_op_snd_cfg_S2_only { - union { - struct - { - uint32_t s2_reg_idx : 8; /*[7 : 0], r/w, 0x0 */ - uint32_t s2_reg_type : 4; /*[11: 8], r/w, 0x0 */ - uint32_t reserved_12_31 : 20; /*[31:12], rsvd, 0x0 */ - } BF; - uint32_t WORD; - } value; + union { + struct { + uint32_t s2_reg_idx : 8; /*[7 : 0], r/w, 0x0 */ + uint32_t s2_reg_type : 4; /*[11: 8], r/w, 0x0 */ + uint32_t reserved_12_31 : 20; /*[31:12], rsvd, 0x0 */ + } BF; + uint32_t WORD; + } value; }; struct pka0_common_op_snd_cfg_S1_S2 { - union { - struct - { - uint32_t s2_reg_idx : 8; /*[7 : 0], r/w, 0x0 */ - uint32_t s2_reg_type : 4; /*[11: 8], r/w, 0x0 */ - uint32_t s1_reg_idx : 8; /*[19:12], r/w, 0x0 */ - uint32_t s1_reg_type : 4; /*[23:20], r/w, 0x0 */ - uint32_t reserved_24_31 : 8; /*[31:24], rsvd, 0x0 */ - } BF; - uint32_t WORD; - } value; + union { + struct { + uint32_t s2_reg_idx : 8; /*[7 : 0], r/w, 0x0 */ + uint32_t s2_reg_type : 4; /*[11: 8], r/w, 0x0 */ + uint32_t s1_reg_idx : 8; /*[19:12], r/w, 0x0 */ + uint32_t s1_reg_type : 4; /*[23:20], r/w, 0x0 */ + uint32_t reserved_24_31 : 8; /*[31:24], rsvd, 0x0 */ + } BF; + uint32_t WORD; + } value; }; struct pka0_bit_shift_op_cfg { - union { - struct - { - uint32_t bit_shift : 15; /*[14: 0], r/w, 0x0 */ - uint32_t reserved_24_31 : 17; /*[31:15], rsvd, 0x0 */ - } BF; - uint32_t WORD; - } value; + union { + struct { + uint32_t bit_shift : 15; /*[14: 0], r/w, 0x0 */ + uint32_t reserved_24_31 : 17; /*[31:15], rsvd, 0x0 */ + } BF; + uint32_t WORD; + } value; }; /*@} end of group SEC_ENG_Private_Types */ @@ -175,7 +168,7 @@ struct pka0_bit_shift_op_cfg { /** @defgroup SEC_ENG_Private_Variables * @{ */ -static intCallback_Type *secEngIntCbfArra[SEC_ENG_INT_ALL] = { NULL }; +static intCallback_Type *secEngIntCbfArra[SEC_ENG_INT_ALL] = {NULL}; /*@} end of group SEC_ENG_Private_Variables */ @@ -196,3188 +189,3045 @@ static intCallback_Type *secEngIntCbfArra[SEC_ENG_INT_ALL] = { NULL }; */ /****************************************************************************/ /** - * @brief SHA256 initialization function - * - * @param shaCtx: SHA256 context pointer - * @param shaNo: SHA ID type - * @param shaType: SHA type - * @param shaTmpBuf[16]: SHA temp buffer for store data that is less than 64 bytes - * @param padding[16]: SHA padding buffer for store padding data - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_SHA256_Init(SEC_Eng_SHA256_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, SEC_ENG_SHA_Type shaType, uint32_t shaTmpBuf[16], uint32_t padding[16]) -{ - uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); - CHECK_PARAM(IS_SEC_ENG_SHA_TYPE(shaType)); - - /* Deal SHA control register to set SHA mode */ - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MODE, shaType); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); - - /* Clear context */ - memset(shaCtx, 0, sizeof(SEC_Eng_SHA256_Ctx)); - - /* Init temp buffer and padding buffer */ - shaCtx->shaBuf = shaTmpBuf; - shaCtx->shaPadding = padding; - BL702_MemSet(shaCtx->shaPadding, 0, 64); - BL702_MemSet(shaCtx->shaPadding, 0x80, 1); + * @brief SHA256 initialization function + * + * @param shaCtx: SHA256 context pointer + * @param shaNo: SHA ID type + * @param shaType: SHA type + * @param shaTmpBuf[16]: SHA temp buffer for store data that is less than 64 bytes + * @param padding[16]: SHA padding buffer for store padding data + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_SHA256_Init(SEC_Eng_SHA256_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, SEC_ENG_SHA_Type shaType, uint32_t shaTmpBuf[16], uint32_t padding[16]) { + uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + CHECK_PARAM(IS_SEC_ENG_SHA_TYPE(shaType)); + + /* Deal SHA control register to set SHA mode */ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MODE, shaType); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); + + /* Clear context */ + memset(shaCtx, 0, sizeof(SEC_Eng_SHA256_Ctx)); + + /* Init temp buffer and padding buffer */ + shaCtx->shaBuf = shaTmpBuf; + shaCtx->shaPadding = padding; + BL702_MemSet(shaCtx->shaPadding, 0, 64); + BL702_MemSet(shaCtx->shaPadding, 0x80, 1); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_SHA_IRQn, SEC_SHA_IRQHandler); + Interrupt_Handler_Register(SEC_SHA_IRQn, SEC_SHA_IRQHandler); #endif } /****************************************************************************/ /** - * @brief SHA start function - * - * @param shaNo: SHA ID type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_SHA_Start(SEC_ENG_SHA_ID_Type shaNo) -{ - uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; - uint32_t tmpVal; + * @brief SHA start function + * + * @param shaNo: SHA ID type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_SHA_Start(SEC_ENG_SHA_ID_Type shaNo) { + uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; + uint32_t tmpVal; - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); - /* Set SHA enable */ - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + /* Set SHA enable */ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_EN); - /* Hash sel 0 for new start */ - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_HASH_SEL); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_EN); + /* Hash sel 0 for new start */ + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_HASH_SEL); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); } /****************************************************************************/ /** - * @brief SHA256 update input data function - * - * @param shaCtx: SHA256 context pointer - * @param shaNo: SHA ID type - * @param input: SHA input data pointer, and the address should be word align - * @param len: SHA input data length - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_SHA256_Update(SEC_Eng_SHA256_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, const uint8_t *input, uint32_t len) -{ - uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; - uint32_t tmpVal; - uint32_t fill; - uint32_t left; - uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - if (len == 0) { - return SUCCESS; - } - - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); - - /* SHA need set se_sha_sel to 1 to keep the last SHA state */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_HASH_SEL, shaCtx->shaFeed); - - left = shaCtx->total[0] & 0x3F; - fill = 64 - left; + * @brief SHA256 update input data function + * + * @param shaCtx: SHA256 context pointer + * @param shaNo: SHA ID type + * @param input: SHA input data pointer, and the address should be word align + * @param len: SHA input data length + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_SHA256_Update(SEC_Eng_SHA256_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, const uint8_t *input, uint32_t len) { + uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; + uint32_t tmpVal; + uint32_t fill; + uint32_t left; + uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - shaCtx->total[0] += (uint32_t)len; - shaCtx->total[0] &= 0xFFFFFFFF; + if (len == 0) { + return SUCCESS; + } - if (shaCtx->total[0] < (uint32_t)len) { - shaCtx->total[1]++; - } + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + timeoutCnt--; - if (left && len >= fill) { - BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, fill); - /* Set data source address */ - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_MSA, (uint32_t)shaCtx->shaBuf); - - /* Set data length */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MSG_LEN, 1); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); - /* Trigger */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_TRIG_1T); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); - - shaCtx->shaFeed = 1; - input += fill; - len -= fill; - left = 0; + if (timeoutCnt == 0) { + return TIMEOUT; } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); - fill = len / 64; - len = len % 64; - - if (fill > 0) { - /* Wait finished */ - timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); + /* SHA need set se_sha_sel to 1 to keep the last SHA state */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_HASH_SEL, shaCtx->shaFeed); - /* SHA need set se_sha_sel to 1 to keep the last sha state */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_HASH_SEL, shaCtx->shaFeed); + left = shaCtx->total[0] & 0x3F; + fill = 64 - left; - /* Fill data */ - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_MSA, (uint32_t)input); + shaCtx->total[0] += (uint32_t)len; + shaCtx->total[0] &= 0xFFFFFFFF; - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MSG_LEN, fill); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); + if (shaCtx->total[0] < (uint32_t)len) { + shaCtx->total[1]++; + } - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_TRIG_1T); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); + if (left && len >= fill) { + BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, fill); + /* Set data source address */ + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_MSA, (uint32_t)shaCtx->shaBuf); - input += (fill * 64); - shaCtx->shaFeed = 1; - } - - if (len > 0) { - /* Wait finished */ - timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - timeoutCnt--; + /* Set data length */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MSG_LEN, 1); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); + /* Trigger */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_TRIG_1T); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); + shaCtx->shaFeed = 1; + input += fill; + len -= fill; + left = 0; + } - /* Copy left data into temp buffer */ - BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, len); - } + fill = len / 64; + len = len % 64; + if (fill > 0) { /* Wait finished */ timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - timeoutCnt--; + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } + if (timeoutCnt == 0) { + return TIMEOUT; + } } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief SHA256 finish to get output function - * - * @param shaCtx: SHA256 context pointer - * @param shaNo: SHA ID type - * @param hash: SHA output data of SHA result - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_SHA256_Finish(SEC_Eng_SHA256_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, uint8_t *hash) -{ - uint32_t last, padn; - uint32_t high, low; - uint8_t shaMode; - uint8_t msgLen[8]; - uint8_t *p = (uint8_t *)hash; - uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; - uint32_t tmpVal; - uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); - - /* Wait finished */ - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); + /* SHA need set se_sha_sel to 1 to keep the last sha state */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_HASH_SEL, shaCtx->shaFeed); - high = (shaCtx->total[0] >> 29) | (shaCtx->total[1] << 3); - low = (shaCtx->total[0] << 3); + /* Fill data */ + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_MSA, (uint32_t)input); - PUT_UINT32_BE(high, msgLen, 0); - PUT_UINT32_BE(low, msgLen, 4); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MSG_LEN, fill); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); - last = shaCtx->total[0] & 0x3F; - padn = (last < 56) ? (56 - last) : (120 - last); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_TRIG_1T); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); - Sec_Eng_SHA256_Update(shaCtx, shaNo, (uint8_t *)shaCtx->shaPadding, padn); + input += (fill * 64); + shaCtx->shaFeed = 1; + } - /* Wait for shaPadding idle */ + if (len > 0) { + /* Wait finished */ timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - timeoutCnt--; + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } + if (timeoutCnt == 0) { + return TIMEOUT; + } } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); - BL702_MemCpy_Fast(shaCtx->shaPadding, msgLen, 8); - Sec_Eng_SHA256_Update(shaCtx, shaNo, (uint8_t *)shaCtx->shaPadding, 8); - - /* Wait finished */ - timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - timeoutCnt--; + /* Copy left data into temp buffer */ + BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, len); + } - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); + /* Wait finished */ + timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; + do { tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - shaMode = (SEC_ENG_SHA_Type)BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MODE); - /* Copy SHA value */ - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_0); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_1); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_2); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_3); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_4); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - - if (shaMode == SEC_ENG_SHA224 || shaMode == SEC_ENG_SHA256) { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_5); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_6); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - - if (shaMode == SEC_ENG_SHA256) { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_7); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - } - } + timeoutCnt--; - /* Disable SHA engine*/ + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief SHA256 finish to get output function + * + * @param shaCtx: SHA256 context pointer + * @param shaNo: SHA ID type + * @param hash: SHA output data of SHA result + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_SHA256_Finish(SEC_Eng_SHA256_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, uint8_t *hash) { + uint32_t last, padn; + uint32_t high, low; + uint8_t shaMode; + uint8_t msgLen[8]; + uint8_t *p = (uint8_t *)hash; + uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + + /* Wait finished */ + do { tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_HASH_SEL); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_EN); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); - - return SUCCESS; -} + timeoutCnt--; -/****************************************************************************/ /** - * @brief SHA enable link mode and set link config address - * - * @param shaNo: SHA ID type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_SHA_Enable_Link(SEC_ENG_SHA_ID_Type shaNo) -{ - uint32_t SHAx = SEC_ENG_BASE; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); - /* Enable sha and enable link mode */ - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_LINK_MODE); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, tmpVal); -} + high = (shaCtx->total[0] >> 29) | (shaCtx->total[1] << 3); + low = (shaCtx->total[0] << 3); -/****************************************************************************/ /** - * @brief SHA disable link mode - * - * @param shaNo: SHA ID type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_SHA_Disable_Link(SEC_ENG_SHA_ID_Type shaNo) -{ - uint32_t SHAx = SEC_ENG_BASE; - uint32_t tmpVal; + PUT_UINT32_BE(high, msgLen, 0); + PUT_UINT32_BE(low, msgLen, 4); - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + last = shaCtx->total[0] & 0x3F; + padn = (last < 56) ? (56 - last) : (120 - last); - /* Disable sha and disable link mode */ - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_LINK_MODE); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_EN); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, tmpVal); -} + Sec_Eng_SHA256_Update(shaCtx, shaNo, (uint8_t *)shaCtx->shaPadding, padn); -/****************************************************************************/ /** - * @brief SHA256 link mode initialization function - * - * @param shaCtx: SHA256 link mode context pointer - * @param shaNo: SHA ID type - * @param linkAddr: SHA link configure address - * @param shaTmpBuf[16]: SHA temp buffer for store data that is less than 64 bytes - * @param padding[16]: SHA padding buffer for store padding data - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_SHA256_Link_Init(SEC_Eng_SHA256_Link_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, uint32_t linkAddr, uint32_t shaTmpBuf[16], uint32_t padding[16]) -{ - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); - - /* Clear context */ - memset(shaCtx, 0, sizeof(SEC_Eng_SHA256_Link_Ctx)); - - /* Init temp buffer,padding buffer and link address */ - shaCtx->shaBuf = shaTmpBuf; - shaCtx->shaPadding = padding; - BL702_MemSet(shaCtx->shaPadding, 0, 64); - BL702_MemSet(shaCtx->shaPadding, 0x80, 1); - shaCtx->linkAddr = linkAddr; + /* Wait for shaPadding idle */ + timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; -#ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_SHA_IRQn, SEC_SHA_IRQHandler); -#endif -} + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + timeoutCnt--; -/****************************************************************************/ /** - * @brief SHA256 link mode update input data function - * - * @param shaCtx: SHA256 link mode context pointer - * @param shaNo: SHA ID type - * @param input: SHA input data pointer, and the address should be word align - * @param len: SHA input data length - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_SHA256_Link_Update(SEC_Eng_SHA256_Link_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, const uint8_t *input, uint32_t len) -{ - uint32_t SHAx = SEC_ENG_BASE; - uint32_t tmpVal; - uint32_t fill; - uint32_t left; - uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - if (len == 0) { - return SUCCESS; + if (timeoutCnt == 0) { + return TIMEOUT; } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); - - /* Set link address */ - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_LINK, shaCtx->linkAddr); + BL702_MemCpy_Fast(shaCtx->shaPadding, msgLen, 8); + Sec_Eng_SHA256_Update(shaCtx, shaNo, (uint8_t *)shaCtx->shaPadding, 8); - left = shaCtx->total[0] & 0x3F; - fill = 64 - left; + /* Wait finished */ + timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - shaCtx->total[0] += (uint32_t)len; - shaCtx->total[0] &= 0xFFFFFFFF; + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + timeoutCnt--; - if (shaCtx->total[0] < (uint32_t)len) { - shaCtx->total[1]++; + if (timeoutCnt == 0) { + return TIMEOUT; } - - if (left && len >= fill) { - BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, fill); - /* Set data source address */ - *(uint32_t *)(shaCtx->linkAddr + 4) = (uint32_t)shaCtx->shaBuf; - - /* Set data length */ - *((uint16_t *)shaCtx->linkAddr + 1) = 1; - /* Trigger */ - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_TRIG_1T)); - - /* Choose accumulating last hash in the next time */ - *((uint32_t *)shaCtx->linkAddr) |= 0x40; - input += fill; - len -= fill; - left = 0; + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); + + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + shaMode = (SEC_ENG_SHA_Type)BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MODE); + /* Copy SHA value */ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_0); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_1); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_2); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_3); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_4); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); + + if (shaMode == SEC_ENG_SHA224 || shaMode == SEC_ENG_SHA256) { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_5); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_6); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); + + if (shaMode == SEC_ENG_SHA256) { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_7); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); } + } + + /* Disable SHA engine*/ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_HASH_SEL); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_EN); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief SHA enable link mode and set link config address + * + * @param shaNo: SHA ID type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_SHA_Enable_Link(SEC_ENG_SHA_ID_Type shaNo) { + uint32_t SHAx = SEC_ENG_BASE; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + + /* Enable sha and enable link mode */ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_LINK_MODE); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, tmpVal); +} + +/****************************************************************************/ /** + * @brief SHA disable link mode + * + * @param shaNo: SHA ID type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_SHA_Disable_Link(SEC_ENG_SHA_ID_Type shaNo) { + uint32_t SHAx = SEC_ENG_BASE; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + + /* Disable sha and disable link mode */ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_LINK_MODE); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_EN); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, tmpVal); +} + +/****************************************************************************/ /** + * @brief SHA256 link mode initialization function + * + * @param shaCtx: SHA256 link mode context pointer + * @param shaNo: SHA ID type + * @param linkAddr: SHA link configure address + * @param shaTmpBuf[16]: SHA temp buffer for store data that is less than 64 bytes + * @param padding[16]: SHA padding buffer for store padding data + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_SHA256_Link_Init(SEC_Eng_SHA256_Link_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, uint32_t linkAddr, uint32_t shaTmpBuf[16], uint32_t padding[16]) { + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + + /* Clear context */ + memset(shaCtx, 0, sizeof(SEC_Eng_SHA256_Link_Ctx)); + + /* Init temp buffer,padding buffer and link address */ + shaCtx->shaBuf = shaTmpBuf; + shaCtx->shaPadding = padding; + BL702_MemSet(shaCtx->shaPadding, 0, 64); + BL702_MemSet(shaCtx->shaPadding, 0x80, 1); + shaCtx->linkAddr = linkAddr; - fill = len / 64; - len = len % 64; +#ifndef BFLB_USE_HAL_DRIVER + Interrupt_Handler_Register(SEC_SHA_IRQn, SEC_SHA_IRQHandler); +#endif +} - if (fill > 0) { - /* Wait finished */ - timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; +/****************************************************************************/ /** + * @brief SHA256 link mode update input data function + * + * @param shaCtx: SHA256 link mode context pointer + * @param shaNo: SHA ID type + * @param input: SHA input data pointer, and the address should be word align + * @param len: SHA input data length + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_SHA256_Link_Update(SEC_Eng_SHA256_Link_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, const uint8_t *input, uint32_t len) { + uint32_t SHAx = SEC_ENG_BASE; + uint32_t tmpVal; + uint32_t fill; + uint32_t left; + uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; + + if (len == 0) { + return SUCCESS; + } - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - timeoutCnt--; + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); - /* Fill data */ - *(uint32_t *)(shaCtx->linkAddr + 4) = (uint32_t)input; - *((uint16_t *)shaCtx->linkAddr + 1) = fill; + /* Set link address */ + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_LINK, shaCtx->linkAddr); - /* Trigger */ - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_TRIG_1T)); + left = shaCtx->total[0] & 0x3F; + fill = 64 - left; - input += (fill * 64); - /* Choose accumulating last hash in the next time */ - *((uint32_t *)shaCtx->linkAddr) |= 0x40; - } + shaCtx->total[0] += (uint32_t)len; + shaCtx->total[0] &= 0xFFFFFFFF; - if (len > 0) { - /* Wait finished */ - timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; + if (shaCtx->total[0] < (uint32_t)len) { + shaCtx->total[1]++; + } - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - timeoutCnt--; + if (left && len >= fill) { + BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, fill); + /* Set data source address */ + *(uint32_t *)(shaCtx->linkAddr + 4) = (uint32_t)shaCtx->shaBuf; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); + /* Set data length */ + *((uint16_t *)shaCtx->linkAddr + 1) = 1; + /* Trigger */ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_TRIG_1T)); - /* Copy left data into temp buffer */ - BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, len); - } + /* Choose accumulating last hash in the next time */ + *((uint32_t *)shaCtx->linkAddr) |= 0x40; + input += fill; + len -= fill; + left = 0; + } + fill = len / 64; + len = len % 64; + + if (fill > 0) { /* Wait finished */ timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - timeoutCnt--; + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } + if (timeoutCnt == 0) { + return TIMEOUT; + } } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); - return SUCCESS; -} + /* Fill data */ + *(uint32_t *)(shaCtx->linkAddr + 4) = (uint32_t)input; + *((uint16_t *)shaCtx->linkAddr + 1) = fill; -/****************************************************************************/ /** - * @brief SHA256 link mode finish to get output function - * - * @param shaCtx: SHA256 link mode context pointer - * @param shaNo: SHA ID type - * @param hash: SHA output data of SHA result - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_SHA256_Link_Finish(SEC_Eng_SHA256_Link_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, uint8_t *hash) -{ - uint32_t last, padn; - uint32_t high, low; - uint8_t msgLen[8]; - uint32_t SHAx = SEC_ENG_BASE; - uint32_t tmpVal; - uint32_t shaMode = (*(uint32_t *)shaCtx->linkAddr) >> 2 & 0x7; - uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + /* Trigger */ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_TRIG_1T)); + + input += (fill * 64); + /* Choose accumulating last hash in the next time */ + *((uint32_t *)shaCtx->linkAddr) |= 0x40; + } + if (len > 0) { /* Wait finished */ + timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; + do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - timeoutCnt--; + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } + if (timeoutCnt == 0) { + return TIMEOUT; + } } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); - /* Set link address */ - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_LINK, shaCtx->linkAddr); + /* Copy left data into temp buffer */ + BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, len); + } - high = (shaCtx->total[0] >> 29) | (shaCtx->total[1] << 3); - low = (shaCtx->total[0] << 3); + /* Wait finished */ + timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - PUT_UINT32_BE(high, msgLen, 0); - PUT_UINT32_BE(low, msgLen, 4); - - last = shaCtx->total[0] & 0x3F; - padn = (last < 56) ? (56 - last) : (120 - last); - - Sec_Eng_SHA256_Link_Update(shaCtx, shaNo, (uint8_t *)shaCtx->shaPadding, padn); - - /* Wait for shaPadding idle */ - timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - timeoutCnt--; + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief SHA256 link mode finish to get output function + * + * @param shaCtx: SHA256 link mode context pointer + * @param shaNo: SHA ID type + * @param hash: SHA output data of SHA result + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_SHA256_Link_Finish(SEC_Eng_SHA256_Link_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, uint8_t *hash) { + uint32_t last, padn; + uint32_t high, low; + uint8_t msgLen[8]; + uint32_t SHAx = SEC_ENG_BASE; + uint32_t tmpVal; + uint32_t shaMode = (*(uint32_t *)shaCtx->linkAddr) >> 2 & 0x7; + uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + + /* Wait finished */ + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + timeoutCnt--; - Sec_Eng_SHA256_Link_Update(shaCtx, shaNo, msgLen, 8); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); - /* Wait finished */ - timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; + /* Set link address */ + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_LINK, shaCtx->linkAddr); - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - timeoutCnt--; + high = (shaCtx->total[0] >> 29) | (shaCtx->total[1] << 3); + low = (shaCtx->total[0] << 3); - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); + PUT_UINT32_BE(high, msgLen, 0); + PUT_UINT32_BE(low, msgLen, 4); - /* Get result according to SHA mode,result is placed in (link address + offset:8) */ - switch (shaMode) { - case 0: - BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 32); - break; + last = shaCtx->total[0] & 0x3F; + padn = (last < 56) ? (56 - last) : (120 - last); - case 1: - BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 28); - break; + Sec_Eng_SHA256_Link_Update(shaCtx, shaNo, (uint8_t *)shaCtx->shaPadding, padn); - case 2: - BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 20); - break; + /* Wait for shaPadding idle */ + timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - case 3: - BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 20); - break; + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + timeoutCnt--; - default: - break; + if (timeoutCnt == 0) { + return TIMEOUT; } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); - /* Choose new hash in the next time */ - *((uint32_t *)shaCtx->linkAddr) &= ~0x40; + Sec_Eng_SHA256_Link_Update(shaCtx, shaNo, msgLen, 8); - return SUCCESS; -} + /* Wait finished */ + timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; -/****************************************************************************/ /** - * @brief AES initialization function - * - * @param aesCtx: AES context pointer - * @param aesNo: AES ID type - * @param aesType: AES type:ECB,CTR,CBC - * @param keyType: AES key type:128,256,192 - * @param enDecType: AES encryption or decryption - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_AES_Init(SEC_Eng_AES_Ctx *aesCtx, SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Type aesType, SEC_ENG_AES_Key_Type keyType, SEC_ENG_AES_EnDec_Type enDecType) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - uint32_t tmpVal; - uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - CHECK_PARAM(IS_SEC_ENG_AES_TYPE(aesType)); - CHECK_PARAM(IS_SEC_ENG_AES_KEY_TYPE(keyType)); - CHECK_PARAM(IS_SEC_ENG_AES_ENDEC_TYPE(enDecType)); + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + timeoutCnt--; - /* Wait finished */ - do { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - timeoutCnt--; + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); + + /* Get result according to SHA mode,result is placed in (link address + offset:8) */ + switch (shaMode) { + case 0: + BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 32); + break; + + case 1: + BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 28); + break; + + case 2: + BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 20); + break; + + case 3: + BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 20); + break; + + default: + break; + } + + /* Choose new hash in the next time */ + *((uint32_t *)shaCtx->linkAddr) &= ~0x40; + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief AES initialization function + * + * @param aesCtx: AES context pointer + * @param aesNo: AES ID type + * @param aesType: AES type:ECB,CTR,CBC + * @param keyType: AES key type:128,256,192 + * @param enDecType: AES encryption or decryption + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_AES_Init(SEC_Eng_AES_Ctx *aesCtx, SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Type aesType, SEC_ENG_AES_Key_Type keyType, SEC_ENG_AES_EnDec_Type enDecType) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + CHECK_PARAM(IS_SEC_ENG_AES_TYPE(aesType)); + CHECK_PARAM(IS_SEC_ENG_AES_KEY_TYPE(keyType)); + CHECK_PARAM(IS_SEC_ENG_AES_ENDEC_TYPE(enDecType)); + + /* Wait finished */ + do { + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); - /* Set AES mode type*/ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_BLOCK_MODE, aesType); + /* Set AES mode type*/ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_BLOCK_MODE, aesType); - /* Set AES key type */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MODE, keyType); + /* Set AES key type */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MODE, keyType); - /* Set AES encryption or decryption */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_DEC_EN, enDecType); + /* Set AES encryption or decryption */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_DEC_EN, enDecType); - /* Clear dec_key_sel to select new key */ - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); + /* Clear dec_key_sel to select new key */ + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); - /* Clear aes iv sel to select new iv */ - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_IV_SEL); + /* Clear aes iv sel to select new iv */ + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_IV_SEL); - /* Clear AES interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_INT_CLR_1T); + /* Clear AES interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_INT_CLR_1T); - /* Enable AES */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_EN); + /* Enable AES */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_EN); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - /* Clear AES context */ - memset(aesCtx, 0, sizeof(SEC_Eng_AES_Ctx)); + /* Clear AES context */ + memset(aesCtx, 0, sizeof(SEC_Eng_AES_Ctx)); - /* Enable ID0 Access for HW Key */ - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_AES_0_CTRL_PROT, 0x03); + /* Enable ID0 Access for HW Key */ + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_AES_0_CTRL_PROT, 0x03); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_AES_IRQn, SEC_AES_IRQHandler); + Interrupt_Handler_Register(SEC_AES_IRQn, SEC_AES_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief AES enable function,set AES bigendian - * - * @param aesNo: AES ID type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID_Type aesNo) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + * @brief AES enable function,set AES bigendian + * + * @param aesNo: AES ID type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID_Type aesNo) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - BL_WR_REG(AESx, SEC_ENG_SE_AES_ENDIAN, 0x0f); + BL_WR_REG(AESx, SEC_ENG_SE_AES_ENDIAN, 0x0f); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_AES_IRQn, SEC_AES_IRQHandler); + Interrupt_Handler_Register(SEC_AES_IRQn, SEC_AES_IRQHandler); #endif } /****************************************************************************/ /** - * @brief AES enable function,set AES littleendian - * - * @param aesNo: AES ID type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Enable_LE(SEC_ENG_AES_ID_Type aesNo) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + * @brief AES enable function,set AES littleendian + * + * @param aesNo: AES ID type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Enable_LE(SEC_ENG_AES_ID_Type aesNo) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - BL_WR_REG(AESx, SEC_ENG_SE_AES_ENDIAN, 0x00); + BL_WR_REG(AESx, SEC_ENG_SE_AES_ENDIAN, 0x00); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_AES_IRQn, SEC_AES_IRQHandler); + Interrupt_Handler_Register(SEC_AES_IRQn, SEC_AES_IRQHandler); #endif } /****************************************************************************/ /** - * @brief AES enable link mode - * - * @param aesNo: AES ID type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Enable_Link(SEC_ENG_AES_ID_Type aesNo) -{ - uint32_t AESx = SEC_ENG_BASE; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - - /* Enable aes link mode */ - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); - BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_LINK_MODE)); - - /* Enable ID0 Access for HW Key */ - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_AES_0_CTRL_PROT, 0x03); -} - -/****************************************************************************/ /** - * @brief AES disable link mode - * - * @param aesNo: AES ID type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Disable_Link(SEC_ENG_AES_ID_Type aesNo) -{ - uint32_t AESx = SEC_ENG_BASE; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - - /* Disable aes link mode */ + * @brief AES enable link mode + * + * @param aesNo: AES ID type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Enable_Link(SEC_ENG_AES_ID_Type aesNo) { + uint32_t AESx = SEC_ENG_BASE; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + + /* Enable aes link mode */ + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); + BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_LINK_MODE)); + + /* Enable ID0 Access for HW Key */ + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_AES_0_CTRL_PROT, 0x03); +} + +/****************************************************************************/ /** + * @brief AES disable link mode + * + * @param aesNo: AES ID type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Disable_Link(SEC_ENG_AES_ID_Type aesNo) { + uint32_t AESx = SEC_ENG_BASE; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + + /* Disable aes link mode */ + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); + BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_LINK_MODE)); +} + +/****************************************************************************/ /** + * @brief AES work in link mode + * + * @param aesNo: AES ID type + * @param linkAddr: Address of config structure in link mode + * @param in: AES input data buffer to deal with + * @param len: AES input data length + * @param out: AES output data buffer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_AES_Link_Work(SEC_ENG_AES_ID_Type aesNo, uint32_t linkAddr, const uint8_t *in, uint32_t len, uint8_t *out) { + uint32_t AESx = SEC_ENG_BASE; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + + /* Link address should word align */ + if ((linkAddr & 0x03) != 0 || len % 16 != 0) { + return ERROR; + } + + /* Wait finished */ + do { tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); - BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_LINK_MODE)); -} + timeoutCnt--; -/****************************************************************************/ /** - * @brief AES work in link mode - * - * @param aesNo: AES ID type - * @param linkAddr: Address of config structure in link mode - * @param in: AES input data buffer to deal with - * @param len: AES input data length - * @param out: AES output data buffer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_AES_Link_Work(SEC_ENG_AES_ID_Type aesNo, uint32_t linkAddr, const uint8_t *in, uint32_t len, uint8_t *out) -{ - uint32_t AESx = SEC_ENG_BASE; - uint32_t tmpVal; - uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - - /* Link address should word align */ - if ((linkAddr & 0x03) != 0 || len % 16 != 0) { - return ERROR; + if (timeoutCnt == 0) { + return TIMEOUT; } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_0_BUSY)); - /* Wait finished */ - do { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_0_BUSY)); + /* Set link address */ + BL_WR_REG(AESx, SEC_ENG_SE_AES_0_LINK, linkAddr); - /* Set link address */ - BL_WR_REG(AESx, SEC_ENG_SE_AES_0_LINK, linkAddr); + /* Change source buffer address and destination buffer address */ + *(uint32_t *)(linkAddr + 4) = (uint32_t)in; + *(uint32_t *)(linkAddr + 8) = (uint32_t)out; - /* Change source buffer address and destination buffer address */ - *(uint32_t *)(linkAddr + 4) = (uint32_t)in; - *(uint32_t *)(linkAddr + 8) = (uint32_t)out; + /* Set data length */ + *((uint16_t *)linkAddr + 1) = len / 16; - /* Set data length */ - *((uint16_t *)linkAddr + 1) = len / 16; + /* Enable aes */ + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); + BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_EN)); - /* Enable aes */ - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); - BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_EN)); + /* Start aes engine and wait finishing */ + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); + BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_TRIG_1T)); + __NOP(); + __NOP(); + timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - /* Start aes engine and wait finishing */ + do { tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); - BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_TRIG_1T)); - __NOP(); - __NOP(); - timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - - do { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); - timeoutCnt--; + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_0_BUSY)); - - /* Disable aes */ - BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_EN)); - - return SUCCESS; -} + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_0_BUSY)); + + /* Disable aes */ + BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_EN)); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief AES set hardware key source:efuse region for CPU0 or region efuse for CPU1 + * + * @param aesNo: AES ID type + * @param src: AES key source type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Set_Hw_Key_Src(SEC_ENG_AES_ID_Type aesNo, uint8_t src) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_SBOOT); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_SBOOT_KEY_SEL, src); + + BL_WR_REG(AESx, SEC_ENG_SE_AES_SBOOT, tmpVal); +} + +/****************************************************************************/ /** + * @brief AES set KEY and IV + * + * @param aesNo: AES ID type + * @param keySrc: AES KEY type:SEC_ENG_AES_KEY_HW or SEC_ENG_AES_KEY_SW + * @param key: AES KEY pointer + * @param iv: AES IV pointer + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Set_Key_IV(SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Key_Src_Type keySrc, const uint8_t *key, const uint8_t *iv) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + uint32_t tmpVal; + uint32_t keyType; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + CHECK_PARAM(IS_SEC_ENG_AES_KEY_SRC_TYPE(keySrc)); + + /* Set IV */ + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_3, __REV(BL_RDWD_FRM_BYTEP(iv))); + iv += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_2, __REV(BL_RDWD_FRM_BYTEP(iv))); + iv += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_1, __REV(BL_RDWD_FRM_BYTEP(iv))); + iv += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_0, __REV(BL_RDWD_FRM_BYTEP(iv))); + iv += 4; + + /* Select hardware key */ + if (keySrc == SEC_ENG_AES_KEY_HW) { + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_HW); + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); -/****************************************************************************/ /** - * @brief AES set hardware key source:efuse region for CPU0 or region efuse for CPU1 - * - * @param aesNo: AES ID type - * @param src: AES key source type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Set_Hw_Key_Src(SEC_ENG_AES_ID_Type aesNo, uint8_t src) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - uint32_t tmpVal; + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_0, *key); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0, tmpVal); - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_1, *key); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1, tmpVal); - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_SBOOT); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_SBOOT_KEY_SEL, src); + return; + } - BL_WR_REG(AESx, SEC_ENG_SE_AES_SBOOT, tmpVal); -} + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_7, __REV(BL_RDWD_FRM_BYTEP(key))); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_6, __REV(BL_RDWD_FRM_BYTEP(key))); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_5, __REV(BL_RDWD_FRM_BYTEP(key))); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_4, __REV(BL_RDWD_FRM_BYTEP(key))); + key += 4; -/****************************************************************************/ /** - * @brief AES set KEY and IV - * - * @param aesNo: AES ID type - * @param keySrc: AES KEY type:SEC_ENG_AES_KEY_HW or SEC_ENG_AES_KEY_SW - * @param key: AES KEY pointer - * @param iv: AES IV pointer - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Set_Key_IV(SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Key_Src_Type keySrc, const uint8_t *key, const uint8_t *iv) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - uint32_t tmpVal; - uint32_t keyType; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - CHECK_PARAM(IS_SEC_ENG_AES_KEY_SRC_TYPE(keySrc)); - - /* Set IV */ - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_3, __REV(BL_RDWD_FRM_BYTEP(iv))); - iv += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_2, __REV(BL_RDWD_FRM_BYTEP(iv))); - iv += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_1, __REV(BL_RDWD_FRM_BYTEP(iv))); - iv += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_0, __REV(BL_RDWD_FRM_BYTEP(iv))); - iv += 4; - - /* Select hardware key */ - if (keySrc == SEC_ENG_AES_KEY_HW) { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_HW); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_0, *key); - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0, tmpVal); - - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_1, *key); - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1, tmpVal); - - return; - } + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); + keyType = BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MODE); - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_7, __REV(BL_RDWD_FRM_BYTEP(key))); + if (keyType == (uint32_t)SEC_ENG_AES_KEY_192BITS) { + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_3, __REV(BL_RDWD_FRM_BYTEP(key))); key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_6, __REV(BL_RDWD_FRM_BYTEP(key))); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_2, __REV(BL_RDWD_FRM_BYTEP(key))); key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_5, __REV(BL_RDWD_FRM_BYTEP(key))); + } else if (keyType == (uint32_t)SEC_ENG_AES_KEY_256BITS || keyType == (uint32_t)SEC_ENG_AES_DOUBLE_KEY_128BITS) { + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_3, __REV(BL_RDWD_FRM_BYTEP(key))); key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_4, __REV(BL_RDWD_FRM_BYTEP(key))); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_2, __REV(BL_RDWD_FRM_BYTEP(key))); key += 4; - + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_1, __REV(BL_RDWD_FRM_BYTEP(key))); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_0, __REV(BL_RDWD_FRM_BYTEP(key))); + key += 4; + } + + /* Select software key */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_SW); + + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); +} + +/****************************************************************************/ /** + * @brief AES set KEY and IV with bigendian + * + * @param aesNo: AES ID type + * @param keySrc: AES KEY type:SEC_ENG_AES_KEY_HW or SEC_ENG_AES_KEY_SW + * @param key: AES KEY pointer + * @param iv: AES IV pointer + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Key_Src_Type keySrc, const uint8_t *key, const uint8_t *iv) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + uint32_t tmpVal; + uint32_t keyType; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + CHECK_PARAM(IS_SEC_ENG_AES_KEY_SRC_TYPE(keySrc)); + + /* Set IV */ + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_0, BL_RDWD_FRM_BYTEP(iv)); + iv += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_1, BL_RDWD_FRM_BYTEP(iv)); + iv += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_2, BL_RDWD_FRM_BYTEP(iv)); + iv += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_3, BL_RDWD_FRM_BYTEP(iv)); + iv += 4; + + /* Select hardware key */ + if (keySrc == SEC_ENG_AES_KEY_HW) { tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - keyType = BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MODE); - - if (keyType == (uint32_t)SEC_ENG_AES_KEY_192BITS) { - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_3, __REV(BL_RDWD_FRM_BYTEP(key))); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_2, __REV(BL_RDWD_FRM_BYTEP(key))); - key += 4; - } else if (keyType == (uint32_t)SEC_ENG_AES_KEY_256BITS || keyType == (uint32_t)SEC_ENG_AES_DOUBLE_KEY_128BITS) { - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_3, __REV(BL_RDWD_FRM_BYTEP(key))); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_2, __REV(BL_RDWD_FRM_BYTEP(key))); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_1, __REV(BL_RDWD_FRM_BYTEP(key))); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_0, __REV(BL_RDWD_FRM_BYTEP(key))); - key += 4; - } + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_HW); + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - /* Select software key */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_SW); + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_0, *key); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0, tmpVal); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); -} + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_1, *key); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1, tmpVal); -/****************************************************************************/ /** - * @brief AES set KEY and IV with bigendian - * - * @param aesNo: AES ID type - * @param keySrc: AES KEY type:SEC_ENG_AES_KEY_HW or SEC_ENG_AES_KEY_SW - * @param key: AES KEY pointer - * @param iv: AES IV pointer - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Key_Src_Type keySrc, const uint8_t *key, const uint8_t *iv) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - uint32_t tmpVal; - uint32_t keyType; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - CHECK_PARAM(IS_SEC_ENG_AES_KEY_SRC_TYPE(keySrc)); - - /* Set IV */ - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_0, BL_RDWD_FRM_BYTEP(iv)); - iv += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_1, BL_RDWD_FRM_BYTEP(iv)); - iv += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_2, BL_RDWD_FRM_BYTEP(iv)); - iv += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_3, BL_RDWD_FRM_BYTEP(iv)); - iv += 4; - - /* Select hardware key */ - if (keySrc == SEC_ENG_AES_KEY_HW) { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_HW); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_0, *key); - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0, tmpVal); - - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_1, *key); - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1, tmpVal); - - return; - } + return; + } + + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_0, BL_RDWD_FRM_BYTEP(key)); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_1, BL_RDWD_FRM_BYTEP(key)); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_2, BL_RDWD_FRM_BYTEP(key)); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_3, BL_RDWD_FRM_BYTEP(key)); + key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_0, BL_RDWD_FRM_BYTEP(key)); + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); + keyType = BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MODE); + + if (keyType == (uint32_t)SEC_ENG_AES_KEY_192BITS) { + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_4, BL_RDWD_FRM_BYTEP(key)); key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_1, BL_RDWD_FRM_BYTEP(key)); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_5, BL_RDWD_FRM_BYTEP(key)); key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_2, BL_RDWD_FRM_BYTEP(key)); + } else if (keyType == (uint32_t)SEC_ENG_AES_KEY_256BITS || keyType == (uint32_t)SEC_ENG_AES_DOUBLE_KEY_128BITS) { + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_4, BL_RDWD_FRM_BYTEP(key)); key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_3, BL_RDWD_FRM_BYTEP(key)); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_5, BL_RDWD_FRM_BYTEP(key)); key += 4; - + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_6, BL_RDWD_FRM_BYTEP(key)); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_7, BL_RDWD_FRM_BYTEP(key)); + key += 4; + } + + /* Select software key */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_SW); + + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); +} + +/****************************************************************************/ /** + * @brief AES set counter byte type in CTR mode + * + * @param aesNo: AES ID type + * @param counterType: AES counter type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Set_Counter_Byte(SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Counter_Type counterType) { + uint32_t AESx = SEC_ENG_BASE; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + CHECK_PARAM(IS_SEC_ENG_AES_COUNTER_TYPE(counterType)); + + /* Set counter type */ + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_ENDIAN); + BL_WR_REG(AESx, SEC_ENG_SE_AES_0_ENDIAN, BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_0_CTR_LEN, counterType)); +} + +/****************************************************************************/ /** + * @brief AES encrypt or decrypt input data + * + * @param aesCtx: AES context pointer + * @param aesNo: AES ID type + * @param in: AES input data buffer to deal with + * @param len: AES input data length + * @param out: AES output data buffer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_AES_Crypt(SEC_Eng_AES_Ctx *aesCtx, SEC_ENG_AES_ID_Type aesNo, const uint8_t *in, uint32_t len, uint8_t *out) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; + + if (len % 16 != 0) { + return ERROR; + } + + /* Wait finished */ + do { tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - keyType = BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MODE); - - if (keyType == (uint32_t)SEC_ENG_AES_KEY_192BITS) { - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_4, BL_RDWD_FRM_BYTEP(key)); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_5, BL_RDWD_FRM_BYTEP(key)); - key += 4; - } else if (keyType == (uint32_t)SEC_ENG_AES_KEY_256BITS || keyType == (uint32_t)SEC_ENG_AES_DOUBLE_KEY_128BITS) { - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_4, BL_RDWD_FRM_BYTEP(key)); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_5, BL_RDWD_FRM_BYTEP(key)); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_6, BL_RDWD_FRM_BYTEP(key)); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_7, BL_RDWD_FRM_BYTEP(key)); - key += 4; + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); - /* Select software key */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_SW); + /* Clear trigger */ + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_TRIG_1T); + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); -} + /* Set input and output address */ + BL_WR_REG(AESx, SEC_ENG_SE_AES_MSA, (uint32_t)in); + BL_WR_REG(AESx, SEC_ENG_SE_AES_MDA, (uint32_t)out); -/****************************************************************************/ /** - * @brief AES set counter byte type in CTR mode - * - * @param aesNo: AES ID type - * @param counterType: AES counter type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Set_Counter_Byte(SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Counter_Type counterType) -{ - uint32_t AESx = SEC_ENG_BASE; - uint32_t tmpVal; + /* Set message length */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MSG_LEN, len / 16); - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - CHECK_PARAM(IS_SEC_ENG_AES_COUNTER_TYPE(counterType)); + if (aesCtx->mode == SEC_ENG_AES_CTR) { + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); + } - /* Set counter type */ - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_ENDIAN); - BL_WR_REG(AESx, SEC_ENG_SE_AES_0_ENDIAN, BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_0_CTR_LEN, counterType)); -} + /* Set IV sel:0 for new, 1 for last */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_IV_SEL, aesCtx->aesFeed); + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); -/****************************************************************************/ /** - * @brief AES encrypt or decrypt input data - * - * @param aesCtx: AES context pointer - * @param aesNo: AES ID type - * @param in: AES input data buffer to deal with - * @param len: AES input data length - * @param out: AES output data buffer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_AES_Crypt(SEC_Eng_AES_Ctx *aesCtx, SEC_ENG_AES_ID_Type aesNo, const uint8_t *in, uint32_t len, uint8_t *out) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - uint32_t tmpVal; - uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - - if (len % 16 != 0) { - return ERROR; - } + /* Trigger AES Engine */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_TRIG_1T); + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - /* Wait finished */ - do { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - timeoutCnt--; + /* Wait finished */ + timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); + do { + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); + timeoutCnt--; - /* Clear trigger */ - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_TRIG_1T); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); - /* Set input and output address */ - BL_WR_REG(AESx, SEC_ENG_SE_AES_MSA, (uint32_t)in); - BL_WR_REG(AESx, SEC_ENG_SE_AES_MDA, (uint32_t)out); + aesCtx->aesFeed = 1; - /* Set message length */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MSG_LEN, len / 16); + return SUCCESS; +} - if (aesCtx->mode == SEC_ENG_AES_CTR) { - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); - } +/****************************************************************************/ /** + * @brief AES finish function, clean register + * + * @param aesNo: AES ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_AES_Finish(SEC_ENG_AES_ID_Type aesNo) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - /* Set IV sel:0 for new, 1 for last */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_IV_SEL, aesCtx->aesFeed); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); + /* Wait finished */ + do { + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); + timeoutCnt--; - /* Trigger AES Engine */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_TRIG_1T); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); - /* Wait finished */ - timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_EN); - do { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - timeoutCnt--; + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_IV_SEL); - aesCtx->aesFeed = 1; + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief AES finish function, clean register - * - * @param aesNo: AES ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_AES_Finish(SEC_ENG_AES_ID_Type aesNo) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - uint32_t tmpVal; - uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - - /* Wait finished */ - do { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - timeoutCnt--; + * @brief TRNG enable TRNG interrupt + * + * @param None + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_Trng_Enable(void) { + uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_TRNG_BUSY_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_EN); - - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); + /* FIXME:default reseed number is 0x1ff, to verify, use 0xa to speed up */ + // tmpVal=BL_SET_REG_BITS_VAL(tmpVal,SEC_ENG_SE_TRNG_RESEED_N,0x1ff); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_IV_SEL); - - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief TRNG enable TRNG interrupt - * - * @param None - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_Trng_Enable(void) -{ - uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; - uint32_t tmpVal; - uint32_t timeoutCnt = SEC_ENG_TRNG_BUSY_TIMEOUT_COUNT; + /* No interrupt as default */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_EN); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_CLR_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + /* busy will be set to 1 after trigger, the gap is 1T */ + __NOP(); + __NOP(); + __NOP(); + __NOP(); + do { tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + timeoutCnt--; - /* FIXME:default reseed number is 0x1ff, to verify, use 0xa to speed up */ - //tmpVal=BL_SET_REG_BITS_VAL(tmpVal,SEC_ENG_SE_TRNG_RESEED_N,0x1ff); - - /* No interrupt as default */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_EN); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_CLR_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - /* busy will be set to 1 after trigger, the gap is 1T */ - __NOP(); - __NOP(); - __NOP(); - __NOP(); - - do { - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_TRNG_BUSY)); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_TRNG_BUSY)); - /* Clear trng interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_CLR_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + /* Clear trng interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_CLR_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_TRNG_IRQn, SEC_TRNG_IRQHandler); + Interrupt_Handler_Register(SEC_TRNG_IRQn, SEC_TRNG_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief TRNG enable TRNG interrupt - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_Trng_Int_Enable(void) -{ - uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; - uint32_t tmpVal; + * @brief TRNG enable TRNG interrupt + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_Trng_Int_Enable(void) { + uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; + uint32_t tmpVal; - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_MASK); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_MASK); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); } /****************************************************************************/ /** - * @brief TRNG disable TRNG interrupt - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_Trng_Int_Disable(void) -{ - uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; - uint32_t tmpVal; + * @brief TRNG disable TRNG interrupt + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_Trng_Int_Disable(void) { + uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; + uint32_t tmpVal; - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_MASK); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_MASK); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); } /****************************************************************************/ /** - * @brief TRNG get random data out - * - * @param data[32]: TRNG output data - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_Trng_Read(uint8_t data[32]) -{ - uint8_t *p = (uint8_t *)data; - uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; - uint32_t tmpVal; - uint32_t timeoutCnt = SEC_ENG_TRNG_BUSY_TIMEOUT_COUNT; + * @brief TRNG get random data out + * + * @param data[32]: TRNG output data + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_Trng_Read(uint8_t data[32]) { + uint8_t *p = (uint8_t *)data; + uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_TRNG_BUSY_TIMEOUT_COUNT; - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - /* Trigger */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + /* Trigger */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - /* busy will be set to 1 after trigger, the gap is 1T */ - __NOP(); - __NOP(); - __NOP(); - __NOP(); + /* busy will be set to 1 after trigger, the gap is 1T */ + __NOP(); + __NOP(); + __NOP(); + __NOP(); - do { - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_TRNG_BUSY)); - - /* copy trng value */ - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_0)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_1)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_2)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_3)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_4)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_5)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_6)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_7)); - p += 4; - - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - - /* Clear data */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief TRNG get random data out - * - * @param data: TRNG output data buffer - * - * @param len: total length to get in bytes - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_Trng_Get_Random(uint8_t *data, uint32_t len) -{ - uint8_t tmpBuf[32]; - uint32_t readLen = 0; - uint32_t i = 0, cnt = 0; - - while (readLen < len) { - if (Sec_Eng_Trng_Read(tmpBuf) != SUCCESS) { - return -1; - } + do { + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + timeoutCnt--; - cnt = len - readLen; + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_TRNG_BUSY)); + + /* copy trng value */ + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_0)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_1)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_2)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_3)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_4)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_5)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_6)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_7)); + p += 4; + + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + + /* Clear data */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief TRNG get random data out + * + * @param data: TRNG output data buffer + * + * @param len: total length to get in bytes + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_Trng_Get_Random(uint8_t *data, uint32_t len) { + uint8_t tmpBuf[32]; + uint32_t readLen = 0; + uint32_t i = 0, cnt = 0; + + while (readLen < len) { + if (Sec_Eng_Trng_Read(tmpBuf) != SUCCESS) { + return -1; + } - if (cnt > sizeof(tmpBuf)) { - cnt = sizeof(tmpBuf); - } + cnt = len - readLen; - for (i = 0; i < cnt; i++) { - data[readLen + i] = tmpBuf[i]; - } + if (cnt > sizeof(tmpBuf)) { + cnt = sizeof(tmpBuf); + } - readLen += cnt; + for (i = 0; i < cnt; i++) { + data[readLen + i] = tmpBuf[i]; } - return 0; + readLen += cnt; + } + + return 0; } -/****************************************************************************/ /** - * @brief TRNG Interrupt Read Trigger - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_Trng_Int_Read_Trigger(void) -{ - uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; - uint32_t tmpVal; - - Sec_Eng_Trng_Int_Enable(); +/****************************************************************************/ /** + * @brief TRNG Interrupt Read Trigger + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_Trng_Int_Read_Trigger(void) { + uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; + uint32_t tmpVal; - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - /* Trigger */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + Sec_Eng_Trng_Int_Enable(); + + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + /* Trigger */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); } /****************************************************************************/ /** - * @brief TRNG get random data out with Interrupt - * - * @param data[32]: TRNG output data - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_Trng_Int_Read(uint8_t data[32]) -{ - uint8_t *p = (uint8_t *)data; - uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; - uint32_t tmpVal; + * @brief TRNG get random data out with Interrupt + * + * @param data[32]: TRNG output data + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_Trng_Int_Read(uint8_t data[32]) { + uint8_t *p = (uint8_t *)data; + uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; + uint32_t tmpVal; - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - /* copy trng value */ - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_0)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_1)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_2)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_3)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_4)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_5)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_6)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_7)); - p += 4; - - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - - /* Clear data */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); -} - -/****************************************************************************/ /** - * @brief Disable TRNG - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_Trng_Disable(void) -{ - uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; - uint32_t tmpVal; + /* copy trng value */ + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_0)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_1)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_2)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_3)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_4)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_5)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_6)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_7)); + p += 4; - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_EN); - //tmpVal=BL_CLR_REG_BIT(tmpVal,SEC_ENG_SE_TRNG_RESEED_N); - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_CLR_1T); + /* Clear data */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); } /****************************************************************************/ /** - * @brief PKA Reset - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_Reset(void) -{ - uint8_t val; + * @brief Disable TRNG + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_Trng_Disable(void) { + uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; + uint32_t tmpVal; - //Disable sec engine - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, 0); + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - //Enable sec engine - val = 1 << 3; - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, val); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_EN); + // tmpVal=BL_CLR_REG_BIT(tmpVal,SEC_ENG_SE_TRNG_RESEED_N); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_CLR_1T); + + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); } /****************************************************************************/ /** - * @brief PKA Enable big endian - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_BigEndian_Enable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_PKA_0_ENDIAN); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, tmpVal); + * @brief PKA Reset + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_Reset(void) { + uint8_t val; + + // Disable sec engine + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, 0); + + // Enable sec engine + val = 1 << 3; + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, val); +} + +/****************************************************************************/ /** + * @brief PKA Enable big endian + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_BigEndian_Enable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_PKA_0_ENDIAN); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_PKA_IRQn, SEC_PKA_IRQHandler); + Interrupt_Handler_Register(SEC_PKA_IRQn, SEC_PKA_IRQHandler); #endif } /****************************************************************************/ /** - * @brief PKA Enable little endian - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LittleEndian_Enable(void) -{ - uint32_t tmpVal; + * @brief PKA Enable little endian + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LittleEndian_Enable(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_PKA_0_ENDIAN); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, tmpVal); + tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_PKA_0_ENDIAN); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_PKA_IRQn, SEC_PKA_IRQHandler); + Interrupt_Handler_Register(SEC_PKA_IRQn, SEC_PKA_IRQHandler); #endif } /****************************************************************************/ /** - * @brief PKA get status function - * - * @param status: Structure pointer of PKA status type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_GetStatus(SEC_Eng_PKA_Status_Type *status) -{ - uint32_t tmpVal; + * @brief PKA get status function + * + * @param status: Structure pointer of PKA status type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_GetStatus(SEC_Eng_PKA_Status_Type *status) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); - *(uint16_t *)status = (uint16_t)BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_PKA_0_STATUS); + tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + *(uint16_t *)status = (uint16_t)BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_PKA_0_STATUS); } /****************************************************************************/ /** - * @brief PKA clear interrupt - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_Clear_Int(void) -{ - uint32_t ctrl; + * @brief PKA clear interrupt + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_Clear_Int(void) { + uint32_t ctrl; - ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); - ctrl = BL_SET_REG_BIT(ctrl, SEC_ENG_SE_PKA_0_INT_CLR_1T); + ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + ctrl = BL_SET_REG_BIT(ctrl, SEC_ENG_SE_PKA_0_INT_CLR_1T); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, ctrl); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, ctrl); - ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); - ctrl = BL_CLR_REG_BIT(ctrl, SEC_ENG_SE_PKA_0_INT_CLR_1T); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, ctrl); + ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + ctrl = BL_CLR_REG_BIT(ctrl, SEC_ENG_SE_PKA_0_INT_CLR_1T); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, ctrl); } /****************************************************************************/ /** - * @brief PKA get Register size according to Register type - * - * @param reg_type: PKA Register type - * - * @return Register size - * -*******************************************************************************/ -static uint16_t Sec_Eng_PKA_Get_Reg_Size(SEC_ENG_PKA_REG_SIZE_Type reg_type) -{ - switch (reg_type) { - case SEC_ENG_PKA_REG_SIZE_8: - return 8; - - case SEC_ENG_PKA_REG_SIZE_16: - return 16; - - case SEC_ENG_PKA_REG_SIZE_32: - return 32; - - case SEC_ENG_PKA_REG_SIZE_64: - return 64; - - case SEC_ENG_PKA_REG_SIZE_96: - return 96; - - case SEC_ENG_PKA_REG_SIZE_128: - return 128; - - case SEC_ENG_PKA_REG_SIZE_192: - return 192; + * @brief PKA get Register size according to Register type + * + * @param reg_type: PKA Register type + * + * @return Register size + * + *******************************************************************************/ +static uint16_t Sec_Eng_PKA_Get_Reg_Size(SEC_ENG_PKA_REG_SIZE_Type reg_type) { + switch (reg_type) { + case SEC_ENG_PKA_REG_SIZE_8: + return 8; - case SEC_ENG_PKA_REG_SIZE_256: - return 256; + case SEC_ENG_PKA_REG_SIZE_16: + return 16; - case SEC_ENG_PKA_REG_SIZE_384: - return 384; + case SEC_ENG_PKA_REG_SIZE_32: + return 32; - case SEC_ENG_PKA_REG_SIZE_512: - return 512; + case SEC_ENG_PKA_REG_SIZE_64: + return 64; - default: - return 0; - } -} - -/****************************************************************************/ /** - * @brief PKA set pre-load register configuration - * - * @param size: Data size in word to write - * @param regIndex: Register index - * @param regType: Register type - * @param op: PKA operation - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -static void Sec_Eng_PKA_Write_Pld_Cfg(uint16_t size, uint8_t regIndex, SEC_ENG_PKA_REG_SIZE_Type regType, SEC_ENG_PKA_OP_Type op, uint8_t lastOp) -{ - struct pka0_pld_cfg cfg; + case SEC_ENG_PKA_REG_SIZE_96: + return 96; - cfg.value.BF.size = size; - cfg.value.BF.d_reg_index = regIndex; - cfg.value.BF.d_reg_type = regType; - cfg.value.BF.op = op; - cfg.value.BF.last_op = lastOp; - - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); -} - -/****************************************************************************/ /** - * @brief PKA write common operation first configuration - * - * @param s0RegIndex: Register index - * @param s0RegType: Register type - * @param dRegIndex: Result Register index - * @param dRegType: Result Register type - * @param op: PKA operation - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -static void Sec_Eng_PKA_Write_Common_OP_First_Cfg(uint8_t s0RegIndex, uint8_t s0RegType, uint8_t dRegIndex, uint8_t dRegType, - uint8_t op, uint8_t lastOp) -{ - struct pka0_common_op_first_cfg cfg; - - cfg.value.BF.s0_reg_idx = s0RegIndex; - cfg.value.BF.s0_reg_type = s0RegType; - - if (op != SEC_ENG_PKA_OP_LCMP) { - cfg.value.BF.d_reg_idx = dRegIndex; - cfg.value.BF.d_reg_type = dRegType; - } - - cfg.value.BF.op = op; - cfg.value.BF.last_op = lastOp; - - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); -} - -/****************************************************************************/ /** - * @brief PKA write common operation second configuration1 - * - * @param s1RegIndex: Register index - * @param s1RegType: Register type - * - * @return None - * -*******************************************************************************/ -static void Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(uint8_t s1RegIndex, uint8_t s1RegType) -{ - struct pka0_common_op_snd_cfg_S1_only cfg; + case SEC_ENG_PKA_REG_SIZE_128: + return 128; - cfg.value.BF.s1_reg_idx = s1RegIndex; - cfg.value.BF.s1_reg_type = s1RegType; + case SEC_ENG_PKA_REG_SIZE_192: + return 192; - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); -} + case SEC_ENG_PKA_REG_SIZE_256: + return 256; -/****************************************************************************/ /** - * @brief PKA write common operation second configuration2 - * - * @param s2RegIndex: Register index - * @param s2RegType: Register type - * - * @return None - * -*******************************************************************************/ -static void Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(uint8_t s2RegIndex, uint8_t s2RegType) -{ - struct pka0_common_op_snd_cfg_S2_only cfg; + case SEC_ENG_PKA_REG_SIZE_384: + return 384; - cfg.value.BF.s2_reg_idx = s2RegIndex; - cfg.value.BF.s2_reg_type = s2RegType; + case SEC_ENG_PKA_REG_SIZE_512: + return 512; - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); + default: + return 0; + } } -/****************************************************************************/ /** - * @brief PKA write common operation second configuration1 and configuration 2 - * - * @param s1RegIndex: Configuration 1 Register index - * @param s1RegType: Configuration 1 Register type - * @param s2RegIndex: Configuration 2 Register index - * @param s2RegType: Configuration 3 Register type - * - * @return None - * -*******************************************************************************/ -static void Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(uint8_t s1RegIndex, uint8_t s1RegType, uint8_t s2RegIndex, uint8_t s2RegType) -{ - struct pka0_common_op_snd_cfg_S1_S2 cfg; +/****************************************************************************/ /** + * @brief PKA set pre-load register configuration + * + * @param size: Data size in word to write + * @param regIndex: Register index + * @param regType: Register type + * @param op: PKA operation + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +static void Sec_Eng_PKA_Write_Pld_Cfg(uint16_t size, uint8_t regIndex, SEC_ENG_PKA_REG_SIZE_Type regType, SEC_ENG_PKA_OP_Type op, uint8_t lastOp) { + struct pka0_pld_cfg cfg; - cfg.value.BF.s1_reg_idx = s1RegIndex; - cfg.value.BF.s1_reg_type = s1RegType; - cfg.value.BF.s2_reg_idx = s2RegIndex; - cfg.value.BF.s2_reg_type = s2RegType; + cfg.value.BF.size = size; + cfg.value.BF.d_reg_index = regIndex; + cfg.value.BF.d_reg_type = regType; + cfg.value.BF.op = op; + cfg.value.BF.last_op = lastOp; + + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); +} - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); +/****************************************************************************/ /** + * @brief PKA write common operation first configuration + * + * @param s0RegIndex: Register index + * @param s0RegType: Register type + * @param dRegIndex: Result Register index + * @param dRegType: Result Register type + * @param op: PKA operation + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +static void Sec_Eng_PKA_Write_Common_OP_First_Cfg(uint8_t s0RegIndex, uint8_t s0RegType, uint8_t dRegIndex, uint8_t dRegType, uint8_t op, uint8_t lastOp) { + struct pka0_common_op_first_cfg cfg; + + cfg.value.BF.s0_reg_idx = s0RegIndex; + cfg.value.BF.s0_reg_type = s0RegType; + + if (op != SEC_ENG_PKA_OP_LCMP) { + cfg.value.BF.d_reg_idx = dRegIndex; + cfg.value.BF.d_reg_type = dRegType; + } + + cfg.value.BF.op = op; + cfg.value.BF.last_op = lastOp; + + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); +} + +/****************************************************************************/ /** + * @brief PKA write common operation second configuration1 + * + * @param s1RegIndex: Register index + * @param s1RegType: Register type + * + * @return None + * + *******************************************************************************/ +static void Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(uint8_t s1RegIndex, uint8_t s1RegType) { + struct pka0_common_op_snd_cfg_S1_only cfg; + + cfg.value.BF.s1_reg_idx = s1RegIndex; + cfg.value.BF.s1_reg_type = s1RegType; + + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); +} + +/****************************************************************************/ /** + * @brief PKA write common operation second configuration2 + * + * @param s2RegIndex: Register index + * @param s2RegType: Register type + * + * @return None + * + *******************************************************************************/ +static void Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(uint8_t s2RegIndex, uint8_t s2RegType) { + struct pka0_common_op_snd_cfg_S2_only cfg; + + cfg.value.BF.s2_reg_idx = s2RegIndex; + cfg.value.BF.s2_reg_type = s2RegType; + + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); +} + +/****************************************************************************/ /** + * @brief PKA write common operation second configuration1 and configuration 2 + * + * @param s1RegIndex: Configuration 1 Register index + * @param s1RegType: Configuration 1 Register type + * @param s2RegIndex: Configuration 2 Register index + * @param s2RegType: Configuration 3 Register type + * + * @return None + * + *******************************************************************************/ +static void Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(uint8_t s1RegIndex, uint8_t s1RegType, uint8_t s2RegIndex, uint8_t s2RegType) { + struct pka0_common_op_snd_cfg_S1_S2 cfg; + + cfg.value.BF.s1_reg_idx = s1RegIndex; + cfg.value.BF.s1_reg_type = s1RegType; + cfg.value.BF.s2_reg_idx = s2RegIndex; + cfg.value.BF.s2_reg_type = s2RegType; + + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); } /****************************************************************************/ /** - * @brief PKA wait for complete interrupt - * - * @param None - * - * @return SUCCESS - * -*******************************************************************************/ -static BL_Err_Type Sec_Eng_PKA_Wait_ISR(void) -{ - uint32_t pka0_ctrl; - uint32_t timeoutCnt = SEC_ENG_PKA_INT_TIMEOUT_COUNT; + * @brief PKA wait for complete interrupt + * + * @param None + * + * @return SUCCESS + * + *******************************************************************************/ +static BL_Err_Type Sec_Eng_PKA_Wait_ISR(void) { + uint32_t pka0_ctrl; + uint32_t timeoutCnt = SEC_ENG_PKA_INT_TIMEOUT_COUNT; - do { - pka0_ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); - timeoutCnt--; + do { + pka0_ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (!BL_GET_REG_BITS_VAL(pka0_ctrl, SEC_ENG_SE_PKA_0_INT)); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (!BL_GET_REG_BITS_VAL(pka0_ctrl, SEC_ENG_SE_PKA_0_INT)); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief PKA read block data from register - * - * @param dest: Pointer to buffer address - * @param src: Pointer to register address - * @param len: Data len in word - * - * @return None - * -*******************************************************************************/ + * @brief PKA read block data from register + * + * @param dest: Pointer to buffer address + * @param src: Pointer to register address + * @param len: Data len in word + * + * @return None + * + *******************************************************************************/ #ifdef ARCH_ARM #ifndef __GNUC__ -__ASM void Sec_Eng_PKA_Read_Block(uint32_t *dest, const uint32_t *src, uint32_t len) -{ - PUSH {R3-R6,LR} -Start0 - CMP R2,#4 - BLT Finish0 - LDR R3,[R1] - LDR R4,[R1] - LDR R5,[R1] - LDR R6,[R1] - STMIA R0!,{R3-R6} - SUBS R2,R2,#4 - B Start0 -Finish0 - POP {R3-R6,PC} +__ASM void Sec_Eng_PKA_Read_Block(uint32_t *dest, const uint32_t *src, uint32_t len) { + PUSH{R3 - R6, LR} Start0 CMP R2, #4 BLT Finish0 LDR R3, [R1] LDR R4, [R1] LDR R5, [R1] LDR R6, [R1] STMIA R0 !, {R3 - R6} SUBS R2, R2, #4 B Start0 Finish0 POP { R3 - R6, PC } } #else -void Sec_Eng_PKA_Read_Block(uint32_t *dest, const uint32_t *src, uint32_t len) -{ - __asm__ __volatile__("push {r3-r6,lr}\n\t" - "Start0 :" - "cmp r2,#4\n\t" - "blt Finish0\n\t" - "ldr r3,[r1]\n\t" - "ldr r4,[r1]\n\t" - "ldr r5,[r1]\n\t" - "ldr r6,[r1]\n\t" - "stmia r0!,{r3-r6}\n\t" - "sub r2,r2,#4\n\t" - "b Start0\n\t" - "Finish0 :" - "pop {r3-r6,pc}\n\t"); +void Sec_Eng_PKA_Read_Block(uint32_t *dest, const uint32_t *src, uint32_t len) { + __asm__ __volatile__("push {r3-r6,lr}\n\t" + "Start0 :" + "cmp r2,#4\n\t" + "blt Finish0\n\t" + "ldr r3,[r1]\n\t" + "ldr r4,[r1]\n\t" + "ldr r5,[r1]\n\t" + "ldr r6,[r1]\n\t" + "stmia r0!,{r3-r6}\n\t" + "sub r2,r2,#4\n\t" + "b Start0\n\t" + "Finish0 :" + "pop {r3-r6,pc}\n\t"); } #endif #endif #ifdef ARCH_RISCV -void Sec_Eng_PKA_Read_Block(uint32_t *dest, const uint32_t *src, uint32_t len) -{ - uint32_t wrLen = len - len % 4; - uint32_t i; +void Sec_Eng_PKA_Read_Block(uint32_t *dest, const uint32_t *src, uint32_t len) { + uint32_t wrLen = len - len % 4; + uint32_t i; - for (i = 0; i < wrLen; i++) { - dest[i] = *src; - } + for (i = 0; i < wrLen; i++) { + dest[i] = *src; + } } #endif /****************************************************************************/ /** - * @brief PKA Write block data to register - * - * @param dest: Pointer to register address - * @param src: Pointer to buffer address - * @param len: Data len in word - * - * @return None - * -*******************************************************************************/ + * @brief PKA Write block data to register + * + * @param dest: Pointer to register address + * @param src: Pointer to buffer address + * @param len: Data len in word + * + * @return None + * + *******************************************************************************/ #ifdef ARCH_ARM #ifndef __GNUC__ -__ASM void Sec_Eng_PKA_Write_Block(uint32_t *dest, const uint32_t *src, uint32_t len) -{ - PUSH {R3-R6,LR} -Start1 - CMP R2,#4 - BLT Finish1 - LDMIA R1!,{R3-R6} - STR R3,[R0] - STR R4,[R0] - STR R5,[R0] - STR R6,[R0] - SUBS R2,R2,#4 - B Start1 -Finish1 - POP {R3-R6,PC} +__ASM void Sec_Eng_PKA_Write_Block(uint32_t *dest, const uint32_t *src, uint32_t len) { + PUSH{R3 - R6, LR} Start1 CMP R2, #4 BLT Finish1 LDMIA R1 !, {R3 - R6} STR R3, [R0] STR R4, [R0] STR R5, [R0] STR R6, [R0] SUBS R2, R2, #4 B Start1 Finish1 POP { R3 - R6, PC } } #else -void Sec_Eng_PKA_Write_Block(uint32_t *dest, const uint32_t *src, uint32_t len) -{ - __asm__ __volatile__("push {r3-r6,lr}\n\t" - "Start1 :" - "cmp r2,#4\n\t" - "blt Finish1\n\t" - "ldmia r1!,{r3-r6}\n\t" - "str r3,[r0]\n\t" - "str r4,[r0]\n\t" - "str r5,[r0]\n\t" - "str r6,[r0]\n\t" - "sub r2,r2,#4\n\t" - "b Start1\n\t" - "Finish1 :" - "pop {r3-r6,pc}\n\t"); +void Sec_Eng_PKA_Write_Block(uint32_t *dest, const uint32_t *src, uint32_t len) { + __asm__ __volatile__("push {r3-r6,lr}\n\t" + "Start1 :" + "cmp r2,#4\n\t" + "blt Finish1\n\t" + "ldmia r1!,{r3-r6}\n\t" + "str r3,[r0]\n\t" + "str r4,[r0]\n\t" + "str r5,[r0]\n\t" + "str r6,[r0]\n\t" + "sub r2,r2,#4\n\t" + "b Start1\n\t" + "Finish1 :" + "pop {r3-r6,pc}\n\t"); } #endif #endif #ifdef ARCH_RISCV -void Sec_Eng_PKA_Write_Block(uint32_t *dest, const uint32_t *src, uint32_t len) -{ - uint32_t wrLen = len - len % 4; - uint32_t i; +void Sec_Eng_PKA_Write_Block(uint32_t *dest, const uint32_t *src, uint32_t len) { + uint32_t wrLen = len - len % 4; + uint32_t i; - for (i = 0; i < wrLen; i++) { - *dest = src[i]; - } + for (i = 0; i < wrLen; i++) { + *dest = src[i]; + } } #endif /****************************************************************************/ /** - * @brief PKA get result - * - * @param result: Pointer to store result - * @param retSize: Result length in word - * @param regLen: register length in byte - * - * @return None - * -*******************************************************************************/ -static void Sec_Eng_PKA_Get_Result(uint32_t *result, uint8_t retSize, uint16_t regLen) -{ - uint32_t ret_data = 0x00; - int index = 0x00; - - /* Wait for the result */ + * @brief PKA get result + * + * @param result: Pointer to store result + * @param retSize: Result length in word + * @param regLen: register length in byte + * + * @return None + * + *******************************************************************************/ +static void Sec_Eng_PKA_Get_Result(uint32_t *result, uint8_t retSize, uint16_t regLen) { + uint32_t ret_data = 0x00; + int index = 0x00; + + /* Wait for the result */ + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + Sec_Eng_PKA_Read_Block(result, (uint32_t *)(SEC_ENG_BASE + SEC_ENG_SE_PKA_0_RW_OFFSET), retSize); + index = retSize - (retSize % 4); + + while (index < retSize) { + ret_data = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW); + result[index] = ret_data; + index++; + } +} + +/****************************************************************************/ /** + * @brief PKA load data to register + * + * @param regType: Register type + * @param regIndex: Register index + * @param data: Data buffer + * @param size: Data length in word + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_Type regType, uint8_t regIndex, const uint32_t *data, uint16_t size, uint8_t lastOp) { + int index = 0x00; + uint16_t regLen = Sec_Eng_PKA_Get_Reg_Size(regType); + + Sec_Eng_PKA_Write_Pld_Cfg(size, regIndex, regType, SEC_ENG_PKA_OP_CTLIR_PLD, lastOp); + + if (size > regLen / 4) { + size = regLen / 4; + } + + Sec_Eng_PKA_Write_Block((uint32_t *)(SEC_ENG_BASE + SEC_ENG_SE_PKA_0_RW_OFFSET), data, size); + index = size - (size % 4); + + while (index < size) { + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, data[index]); + index++; + } +} + +/****************************************************************************/ /** + * @brief PKA read data from register + * + * @param regType: Register type + * @param regIdx: Register index + * @param result: Data buffer + * @param retSize: Data length in word + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_Read_Data(SEC_ENG_PKA_REG_SIZE_Type regType, uint8_t regIdx, uint32_t *result, uint8_t retSize) { + uint16_t regSize; + uint32_t dummyData = 0; + + regSize = Sec_Eng_PKA_Get_Reg_Size(regType); + + if (retSize > regSize / 4) { + result = NULL; + return; + } + + Sec_Eng_PKA_Write_Pld_Cfg(retSize, regIdx, regType, SEC_ENG_PKA_OP_CFLIR_BUFFER, 1); + + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); + + Sec_Eng_PKA_Get_Result(result, retSize, regSize); +} + +/****************************************************************************/ /** + * @brief PKA clear register + * + * @param dRegType: Register type + * @param dRegIdx: Register index + * @param size: Data length in word + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_CREG(SEC_ENG_PKA_REG_SIZE_Type dRegType, uint8_t dRegIdx, uint8_t size, uint8_t lastOp) { + uint32_t dummyData = 0; + + Sec_Eng_PKA_Write_Pld_Cfg(size, dRegIdx, dRegType, SEC_ENG_PKA_OP_CLIR, lastOp); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); + + if (lastOp) { Sec_Eng_PKA_Wait_ISR(); Sec_Eng_PKA_Clear_Int(); - Sec_Eng_PKA_Read_Block(result, (uint32_t *)(SEC_ENG_BASE + SEC_ENG_SE_PKA_0_RW_OFFSET), retSize); - index = retSize - (retSize % 4); - - while (index < retSize) { - ret_data = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW); - result[index] = ret_data; - index++; - } + } } /****************************************************************************/ /** - * @brief PKA load data to register - * - * @param regType: Register type - * @param regIndex: Register index - * @param data: Data buffer - * @param size: Data length in word - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_Type regType, uint8_t regIndex, const uint32_t *data, uint16_t size, uint8_t lastOp) -{ - int index = 0x00; - uint16_t regLen = Sec_Eng_PKA_Get_Reg_Size(regType); + * @brief PKA load data to register + * + * @param regType: regType: Register type + * @param regIndex: regIndex: Register index + * @param data: data: Data buffer + * @param lastOp: size: Data length in word + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_Write_Immediate(SEC_ENG_PKA_REG_SIZE_Type regType, uint8_t regIndex, uint32_t data, uint8_t lastOp) { + struct pka0_pldi_cfg cfg; - Sec_Eng_PKA_Write_Pld_Cfg(size, regIndex, regType, SEC_ENG_PKA_OP_CTLIR_PLD, lastOp); - - if (size > regLen / 4) { - size = regLen / 4; - } + cfg.value.BF.rsvd = 0; + cfg.value.BF.d_reg_index = regIndex; + cfg.value.BF.d_reg_type = regType; + cfg.value.BF.op = SEC_ENG_PKA_OP_SLIR; + cfg.value.BF.last_op = lastOp; - Sec_Eng_PKA_Write_Block((uint32_t *)(SEC_ENG_BASE + SEC_ENG_SE_PKA_0_RW_OFFSET), data, size); - index = size - (size % 4); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, data); - while (index < size) { - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, data[index]); - index++; - } + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } } /****************************************************************************/ /** - * @brief PKA read data from register - * - * @param regType: Register type - * @param regIdx: Register index - * @param result: Data buffer - * @param retSize: Data length in word - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_Read_Data(SEC_ENG_PKA_REG_SIZE_Type regType, uint8_t regIdx, uint32_t *result, uint8_t retSize) -{ - uint16_t regSize; - uint32_t dummyData = 0; + * @brief PKA negative source data:D = (1 << SIZE{S0})-S0 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source Register type + * @param s0RegIdx: Source Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_NREG(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) { + uint32_t dummyData = 0; - regSize = Sec_Eng_PKA_Get_Reg_Size(regType); + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_NLIR, lastOp); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); - if (retSize > regSize / 4) { - result = NULL; - return; - } - - Sec_Eng_PKA_Write_Pld_Cfg(retSize, regIdx, regType, SEC_ENG_PKA_OP_CFLIR_BUFFER, 1); - - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); - - Sec_Eng_PKA_Get_Result(result, retSize, regSize); + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } } /****************************************************************************/ /** - * @brief PKA clear register - * - * @param dRegType: Register type - * @param dRegIdx: Register index - * @param size: Data length in word - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_CREG(SEC_ENG_PKA_REG_SIZE_Type dRegType, uint8_t dRegIdx, uint8_t size, uint8_t lastOp) -{ - uint32_t dummyData = 0; - - Sec_Eng_PKA_Write_Pld_Cfg(size, dRegIdx, dRegType, SEC_ENG_PKA_OP_CLIR, lastOp); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); + * @brief PKA move data:D = S0 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source Register type + * @param s0RegIdx: Source Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_Move_Data(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) { + uint32_t dummyData = 0; - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MOVDAT, lastOp); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); -/****************************************************************************/ /** - * @brief PKA load data to register - * - * @param regType: regType: Register type - * @param regIndex: regIndex: Register index - * @param data: data: Data buffer - * @param lastOp: size: Data length in word - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_Write_Immediate(SEC_ENG_PKA_REG_SIZE_Type regType, uint8_t regIndex, uint32_t data, uint8_t lastOp) -{ - struct pka0_pldi_cfg cfg; - - cfg.value.BF.rsvd = 0; - cfg.value.BF.d_reg_index = regIndex; - cfg.value.BF.d_reg_type = regType; - cfg.value.BF.op = SEC_ENG_PKA_OP_SLIR; - cfg.value.BF.last_op = lastOp; - - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, data); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } } /****************************************************************************/ /** - * @brief PKA negative source data:D = (1 << SIZE{S0})-S0 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source Register type - * @param s0RegIdx: Source Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_NREG(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) -{ - uint32_t dummyData = 0; + * @brief PKA resize data:D = S0, D.Size = S0.Size + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source Register type + * @param s0RegIdx: Source Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_RESIZE(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) { + uint32_t dummyData = 0; - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_NLIR, lastOp); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_RESIZE, lastOp); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mod add:D = (S0 + S1) mod S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_MADD(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MADD, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mod sub:D = (S0 - S1) mod S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_MSUB(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MSUB, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mod :D = S0 mod S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_MREM(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MREM, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mod mul:D = (S0 * S1) mod S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_MMUL(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MMUL, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mod sqr:D = (S0 ^ 2) mod S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_MSQR(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MSQR, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mod exp:D = (S0 ^ S1) mod S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_MEXP(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MEXP, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mod exp:D = (S0 ^ (S2-2) ) mod S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_MINV(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MINV, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA Report COUT to 1 when S0 < S1 + * + * @param cout: Compare result + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LCMP(uint8_t *cout, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx) { + uint32_t pka0_ctrl = 0x00; + + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, 0, 0, SEC_ENG_PKA_OP_LCMP, 1); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); + + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + pka0_ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + + *cout = (pka0_ctrl & SEC_ENG_PKA_STATUS_LAST_OPC_MASK) >> SEC_ENG_PKA_STATUS_LAST_OPC_OFFSET; +} + +/****************************************************************************/ /** + * @brief PKA add:D = S0 + S1 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LADD(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LADD, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA sub:D = S0 - S1 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LSUB(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LSUB, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mul:D = S0 * S1 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LMUL(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LMUL, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } } /****************************************************************************/ /** - * @brief PKA move data:D = S0 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source Register type - * @param s0RegIdx: Source Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_Move_Data(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) -{ - uint32_t dummyData = 0; + * @brief PKA sqr:D = S0^2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LSQR(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) { + uint32_t dummyData = 0; - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MOVDAT, lastOp); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LSQR, lastOp); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA div:D = S0 / S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LDIV(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LDIV, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } } /****************************************************************************/ /** - * @brief PKA resize data:D = S0, D.Size = S0.Size - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source Register type - * @param s0RegIdx: Source Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_RESIZE(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) -{ - uint32_t dummyData = 0; + * @brief PKA shift:D = S0 << BIT SHIFT + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param bit_shift: Bits to shift + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LMUL2N(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint16_t bit_shift, uint8_t lastOp) { + struct pka0_bit_shift_op_cfg cfg; - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_RESIZE, lastOp); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LMUL2N, 0); - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + cfg.value.BF.bit_shift = bit_shift; + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); -/****************************************************************************/ /** - * @brief PKA mod add:D = (S0 + S1) mod S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_MADD(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MADD, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} - -/****************************************************************************/ /** - * @brief PKA mod sub:D = (S0 - S1) mod S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_MSUB(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MSUB, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } } /****************************************************************************/ /** - * @brief PKA mod :D = S0 mod S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_MREM(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MREM, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + * @brief PKA shift:D = S0 >> BIT SHIFT + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param bit_shift: Bits to shift + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LDIV2N(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint16_t bit_shift, uint8_t lastOp) { + struct pka0_bit_shift_op_cfg cfg; -/****************************************************************************/ /** - * @brief PKA mod mul:D = (S0 * S1) mod S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_MMUL(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MMUL, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LDIV2N, 0); -/****************************************************************************/ /** - * @brief PKA mod sqr:D = (S0 ^ 2) mod S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_MSQR(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MSQR, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + cfg.value.BF.bit_shift = bit_shift; + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); -/****************************************************************************/ /** - * @brief PKA mod exp:D = (S0 ^ S1) mod S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_MEXP(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MEXP, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } } /****************************************************************************/ /** - * @brief PKA mod exp:D = (S0 ^ (S2-2) ) mod S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_MINV(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MINV, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + * @brief PKA mod 2N:D = S0 % ((1 << BIT SHIFT)-1) + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param bit_shift: Bits to shift + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LMOD2N(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint16_t bit_shift, uint8_t lastOp) { + struct pka0_bit_shift_op_cfg cfg; -/****************************************************************************/ /** - * @brief PKA Report COUT to 1 when S0 < S1 - * - * @param cout: Compare result - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LCMP(uint8_t *cout, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx) -{ - uint32_t pka0_ctrl = 0x00; + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MOD2N, lastOp); - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, 0, 0, SEC_ENG_PKA_OP_LCMP, 1); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); + cfg.value.BF.bit_shift = bit_shift; + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); + if (lastOp) { Sec_Eng_PKA_Wait_ISR(); Sec_Eng_PKA_Clear_Int(); - pka0_ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + } +} + +/****************************************************************************/ /** + * @brief PKA GF to Mont filed 2N:d = (a<> SEC_ENG_PKA_STATUS_LAST_OPC_OFFSET; +#ifndef BFLB_USE_HAL_DRIVER + Interrupt_Handler_Register(SEC_GMAC_IRQn, SEC_GMAC_IRQHandler); +#endif } /****************************************************************************/ /** - * @brief PKA add:D = S0 + S1 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LADD(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s1RegType, uint8_t s1RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LADD, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + * @brief Set gmac big endian + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_GMAC_Enable_BE(void) { + uint32_t tmpVal; -/****************************************************************************/ /** - * @brief PKA sub:D = S0 - S1 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LSUB(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s1RegType, uint8_t s1RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LSUB, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_GMAC_0_CTRL_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_GMAC_0_T_ENDIAN); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_GMAC_0_H_ENDIAN); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_GMAC_0_X_ENDIAN); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_GMAC_0_CTRL_0, tmpVal); -/****************************************************************************/ /** - * @brief PKA mul:D = S0 * S1 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LMUL(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s1RegType, uint8_t s1RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LMUL, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } +#ifndef BFLB_USE_HAL_DRIVER + Interrupt_Handler_Register(SEC_GMAC_IRQn, SEC_GMAC_IRQHandler); +#endif } /****************************************************************************/ /** - * @brief PKA sqr:D = S0^2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LSQR(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) -{ - uint32_t dummyData = 0; - - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LSQR, lastOp); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + * @brief GMAC enable link mode + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_GMAC_Enable_Link(void) { + uint32_t tmpVal; + + /* Enable gmac link mode */ + tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_GMAC_0_CTRL_0); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_GMAC_0_CTRL_0, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_GMAC_0_EN)); +} + +/****************************************************************************/ /** + * @brief GMAC disable link mode + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_GMAC_Disable_Link(void) { + uint32_t tmpVal; + + /* Disable gmac link mode */ + tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_GMAC_0_CTRL_0); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_GMAC_0_CTRL_0, BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_GMAC_0_EN)); +} + +/****************************************************************************/ /** + * @brief GMAC work in link mode + * + * @param linkAddr: Address of config structure in link mode + * @param in: GMAC input data buffer to deal with + * @param len: GMAC input data length + * @param out: GMAC output data buffer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_GMAC_Link_Work(uint32_t linkAddr, const uint8_t *in, uint32_t len, uint8_t *out) { + uint32_t GMACx = SEC_ENG_BASE; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_GMAC_BUSY_TIMEOUT_COUNT; + + /* Link address should word align */ + if ((linkAddr & 0x03) != 0 || len % 16 != 0) { + return ERROR; + } + + /* Wait finished */ + do { + tmpVal = BL_RD_REG(GMACx, SEC_ENG_SE_GMAC_0_CTRL_0); + timeoutCnt--; -/****************************************************************************/ /** - * @brief PKA div:D = S0 / S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LDIV(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LDIV, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); + if (timeoutCnt == 0) { + return TIMEOUT; } -} + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_GMAC_0_BUSY)); -/****************************************************************************/ /** - * @brief PKA shift:D = S0 << BIT SHIFT - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param bit_shift: Bits to shift - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LMUL2N(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint16_t bit_shift, uint8_t lastOp) -{ - struct pka0_bit_shift_op_cfg cfg; + /* Set link address */ + BL_WR_REG(GMACx, SEC_ENG_SE_GMAC_0_LCA, linkAddr); - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LMUL2N, 0); + /* Change source buffer address */ + *(uint32_t *)(linkAddr + 4) = (uint32_t)in; - cfg.value.BF.bit_shift = bit_shift; - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); + /* Set data length */ + *((uint16_t *)linkAddr + 1) = len / 16; - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + /* Start gmac engine and wait finishing */ + tmpVal = BL_RD_REG(GMACx, SEC_ENG_SE_GMAC_0_CTRL_0); + BL_WR_REG(GMACx, SEC_ENG_SE_GMAC_0_CTRL_0, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_GMAC_0_TRIG_1T)); + timeoutCnt = SEC_ENG_GMAC_BUSY_TIMEOUT_COUNT; -/****************************************************************************/ /** - * @brief PKA shift:D = S0 >> BIT SHIFT - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param bit_shift: Bits to shift - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LDIV2N(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint16_t bit_shift, uint8_t lastOp) -{ - struct pka0_bit_shift_op_cfg cfg; + do { + tmpVal = BL_RD_REG(GMACx, SEC_ENG_SE_GMAC_0_CTRL_0); + timeoutCnt--; - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LDIV2N, 0); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_GMAC_0_BUSY)); - cfg.value.BF.bit_shift = bit_shift; - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); + /* Get result */ + BL702_MemCpy_Fast(out, (uint8_t *)(linkAddr + 0x18), 16); - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } + return SUCCESS; } +#ifndef BFLB_USE_HAL_DRIVER /****************************************************************************/ /** - * @brief PKA mod 2N:D = S0 % ((1 << BIT SHIFT)-1) - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param bit_shift: Bits to shift - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LMOD2N(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint16_t bit_shift, uint8_t lastOp) -{ - struct pka0_bit_shift_op_cfg cfg; + * @brief Sec Eng Interrupt Handler + * + * @param intType: IRQ Type + * + * @return None + * + *******************************************************************************/ +static void SEC_Eng_IntHandler(SEC_ENG_INT_Type intType) { + uint32_t tmpVal; - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MOD2N, lastOp); + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_INT_TYPE(intType)); - cfg.value.BF.bit_shift = bit_shift; - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); + switch (intType) { + case SEC_ENG_INT_TRNG: + tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_TRNG_0_CTRL_0); - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + if (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_TRNG_0_INT)) { + /* Clear interrupt */ + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_TRNG_0_CTRL_0, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_0_INT_CLR_1T)); -/****************************************************************************/ /** - * @brief PKA GF to Mont filed 2N:d = (a<
© COPYRIGHT(c) 2020 Bouffalo Lab
- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_sf_cfg.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "bl702_glb.h" #include "bl702_sf_cfg.h" -#include "softcrc.h" +#include "bl702_glb.h" #include "bl702_xip_sflash.h" +#include "softcrc.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -58,11 +58,10 @@ * @{ */ #ifndef BFLB_USE_ROM_DRIVER -typedef struct -{ - uint32_t jedecID; - char *name; - const SPI_Flash_Cfg_Type *cfg; +typedef struct { + uint32_t jedecID; + char *name; + const SPI_Flash_Cfg_Type *cfg; } Flash_Info_t; #endif @@ -73,1986 +72,1984 @@ typedef struct */ #ifndef BFLB_USE_ROM_DRIVER static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Winb_80DV = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xef, + .mid = 0xef, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 0, - .cReadMode = 0xFF, + .frQioDmyClk = 16 / 8, + .cReadSupport = 0, + .cReadMode = 0xFF, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3d, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 3, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 3, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Winb_16DV = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xef, + .mid = 0xef, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, /*Q08BV,Q16DV: 0x02.Q32FW,Q32FV: 0x01 */ - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3d, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 3, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 3, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Winb_80EW_16FW_32JW_32FW_32FV = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xef, + .mid = 0xef, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x31, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 400, - .timeE32k = 1600, - .timeE64k = 2000, + .timeE32k = 1600, + .timeE64k = 2000, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 3, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 3, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Issi = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x9d, + .mid = 0x9d, - .deBurstWrapCmd = 0xC0, + .deBurstWrapCmd = 0xC0, .deBurstWrapCmdDmyClk = 0x00, - .deBurstWrapDataMode = SF_CTRL_DATA_1_LINE, - .deBurstWrapData = 0x00, + .deBurstWrapDataMode = SF_CTRL_DATA_1_LINE, + .deBurstWrapData = 0x00, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0, - .qeBit = 0x06, + .qeIndex = 0, + .qeBit = 0x06, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x31, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0xA0, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0xA0, - .burstWrapCmd = 0xC0, + .burstWrapCmd = 0xC0, .burstWrapCmdDmyClk = 0x00, - .burstWrapDataMode = SF_CTRL_DATA_1_LINE, - .burstWrapData = 0x06, + .burstWrapDataMode = SF_CTRL_DATA_1_LINE, + .burstWrapData = 0x06, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 5, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 5, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Gd_Md_40D = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x51, + .mid = 0x51, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 0, - .cReadMode = 0xA0, + .frQioDmyClk = 16 / 8, + .cReadSupport = 0, + .cReadMode = 0xA0, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_DO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_DO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xc8, + .mid = 0xc8, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Gd_Q80E_Q16E = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xc8, + .mid = 0xc8, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0xA0, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0xA0, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Gd_WQ80E_WQ16E = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xc8, + .mid = 0xc8, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 32 / 8, - .cReadSupport = 1, - .cReadMode = 0xA0, + .frQioDmyClk = 32 / 8, + .cReadSupport = 1, + .cReadMode = 0xA0, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 8 / 8, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 8 / 8, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0x12, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0x12, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Gd_Q32C = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xc8, + .mid = 0xc8, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x31, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Mxic = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xC2, + .mid = 0xC2, - .deBurstWrapCmd = 0xC0, + .deBurstWrapCmd = 0xC0, .deBurstWrapCmdDmyClk = 0x00, - .deBurstWrapDataMode = SF_CTRL_DATA_1_LINE, - .deBurstWrapData = 0x10, + .deBurstWrapDataMode = SF_CTRL_DATA_1_LINE, + .deBurstWrapData = 0x10, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0, - .qeBit = 0x06, + .qeIndex = 0, + .qeBit = 0x06, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0xA5, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0xA5, - .burstWrapCmd = 0xC0, + .burstWrapCmd = 0xC0, .burstWrapCmdDmyClk = 0x00, - .burstWrapDataMode = SF_CTRL_DATA_1_LINE, - .burstWrapData = 0x02, + .burstWrapDataMode = SF_CTRL_DATA_1_LINE, + .burstWrapData = 0x02, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x38, - .qppAddrMode = SF_CTRL_ADDR_4_LINES, + .qppAddrMode = SF_CTRL_ADDR_4_LINES, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 45, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 45, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Mxic_1635F = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xC2, + .mid = 0xC2, - .deBurstWrapCmd = 0xC0, + .deBurstWrapCmd = 0xC0, .deBurstWrapCmdDmyClk = 0x00, - .deBurstWrapDataMode = SF_CTRL_DATA_1_LINE, - .deBurstWrapData = 0x10, + .deBurstWrapDataMode = SF_CTRL_DATA_1_LINE, + .deBurstWrapData = 0x10, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0, - .qeBit = 0x06, + .qeIndex = 0, + .qeBit = 0x06, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0xA5, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0xA5, - .burstWrapCmd = 0xC0, + .burstWrapCmd = 0xC0, .burstWrapCmdDmyClk = 0x00, - .burstWrapDataMode = SF_CTRL_DATA_1_LINE, - .burstWrapData = 0x02, + .burstWrapDataMode = SF_CTRL_DATA_1_LINE, + .burstWrapData = 0x02, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x38, - .qppAddrMode = SF_CTRL_ADDR_4_LINES, + .qppAddrMode = SF_CTRL_ADDR_4_LINES, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 45, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 45, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Xtx40 = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x0B, + .mid = 0x0B, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0x01, - .qeBit = 0x01, + .qeIndex = 0x01, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_DIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_DIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 6000, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Xtx = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x0B, + .mid = 0x0B, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0x01, - .qeBit = 0x01, + .qeIndex = 0x01, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 6000, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Puya_Q80L_Q80H_Q16H = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x85, + .mid = 0x85, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0x01, - .qeBit = 0x01, + .qeIndex = 0x01, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3d, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 8, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 8, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Puya_Q32H = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x85, + .mid = 0x85, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0x01, - .qeBit = 0x01, + .qeIndex = 0x01, + .qeBit = 0x01, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x31, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 8, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 8, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Boya40 = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x68, + .mid = 0x68, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 0, - .cReadMode = 0xA0, + .frQioDmyClk = 16 / 8, + .cReadSupport = 0, + .cReadMode = 0xA0, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_DO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_DO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Boya = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x68, + .mid = 0x68, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0x01, - .qeBit = 0x01, + .qeIndex = 0x01, + .qeBit = 0x01, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x31, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_FT_VQ80 = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xef, + .mid = 0xef, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x31, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 8, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 8, + .qeData = 0, }; -static const ATTR_TCM_CONST_SECTION Flash_Info_t flashInfos[] = { - { - .jedecID = 0x1440ef, - .name = "Winb_80DV_08_33", - .cfg = &flashCfg_Winb_80DV, - }, - { - .jedecID = 0x1540ef, - .name = "Winb_16DV_16_33", - .cfg = &flashCfg_Winb_16DV, - }, - { - .jedecID = 0x1640ef, - .name = "Winb_32FV_32_33", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x1460ef, - .name = "Winb_80EW_08_18", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x1560ef, - .name = "Winb_16FW_16_18", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x1660ef, - .name = "Winb_32FW_32_18", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x1860ef, - .name = "Winb_128FW_128_18", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x1680ef, - .name = "Winb_32JW_32_18", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x13605e, - .name = "Zbit_04_33", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x14605e, - .name = "Zbit_08_33", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x14609d, - .name = "ISSI_08_33", - .cfg = &flashCfg_Issi, - }, - { - .jedecID = 0x15609d, - .name = "ISSI_16_33", - .cfg = &flashCfg_Issi, - }, - { - .jedecID = 0x16609d, - .name = "ISSI_32_33", - .cfg = &flashCfg_Issi, - }, - { - .jedecID = 0x14709d, - .name = "ISSI_08_18", - .cfg = &flashCfg_Issi, - }, - { - .jedecID = 0x15709d, - .name = "ISSI_16_18", - .cfg = &flashCfg_Issi, - }, - { - .jedecID = 0x16709d, - .name = "ISSI_32_18", - .cfg = &flashCfg_Issi, - }, - { - .jedecID = 0x134051, - .name = "GD_MD04D_04_33", - .cfg = &flashCfg_Gd_Md_40D, - }, - { - .jedecID = 0x1440C8, - .name = "GD_Q08E_08_33", - .cfg = &flashCfg_Gd_Q80E_Q16E, - }, - { - .jedecID = 0x1540C8, - .name = "GD_Q16E_16_33", - .cfg = &flashCfg_Gd_Q80E_Q16E, - }, - { - .jedecID = 0x1640C8, - .name = "GD_Q32C_32_33", - .cfg = &flashCfg_Gd_Q32C, - }, - { - .jedecID = 0x1460C8, - .name = "GD_LQ08C_08_18", - .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, - }, - { - .jedecID = 0x1560C8, - .name = "GD_LE16C_16_18", - .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, - }, - { - .jedecID = 0x1660C8, - .name = "GD_LQ32D_32_18", - .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, - }, - { - .jedecID = 0x1465C8, - .name = "GD_WQ80E_80_33", - .cfg = &flashCfg_Gd_WQ80E_WQ16E, - }, - { - .jedecID = 0x1565C8, - .name = "GD_WQ16E_16_33", - .cfg = &flashCfg_Gd_WQ80E_WQ16E, - }, - { - .jedecID = 0x1665C8, - .name = "GD_WQ32E_32_33", - .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, - }, - { - .jedecID = 0x3425C2, - .name = "MX_25V80_08_18", - .cfg = &flashCfg_Mxic, - }, - { - .jedecID = 0x3525C2, - .name = "MX_25U16_35_18", - .cfg = &flashCfg_Mxic_1635F, - }, - { - .jedecID = 0x3625C2, - .name = "MX_25V32_32_18", - .cfg = &flashCfg_Mxic, - }, - { - .jedecID = 0x13400B, - .name = "XT_25F04D_04_33", - .cfg = &flashCfg_Xtx40, - }, - { - .jedecID = 0x15400B, - .name = "XT_25F16B_16_33", - .cfg = &flashCfg_Xtx, - }, - { - .jedecID = 0x16400B, - .name = "XT_25F32B_32_33", - .cfg = &flashCfg_Xtx, - }, - { - .jedecID = 0x14600B, - .name = "XT_25Q80B_08_18", - .cfg = &flashCfg_Xtx, - }, - { - .jedecID = 0x16600B, - .name = "XT_25Q32B_32_18", - .cfg = &flashCfg_Xtx, - }, - { - .jedecID = 0x146085, - .name = "Puya_Q80L/H_08_18/33", - .cfg = &flashCfg_Puya_Q80L_Q80H_Q16H, - }, - { - .jedecID = 0x156085, - .name = "Puya_Q16H_16_33", - .cfg = &flashCfg_Puya_Q80L_Q80H_Q16H, - }, - { - .jedecID = 0x166085, - .name = "Puya_Q32H_32_33", - .cfg = &flashCfg_Puya_Q32H, - }, - { - .jedecID = 0x134068, - .name = "Boya_Q04B_04_33", - .cfg = &flashCfg_Boya40, - }, - { - .jedecID = 0x144068, - .name = "Boya_Q08B_08_33", - .cfg = &flashCfg_Boya, - }, - { - .jedecID = 0x154068, - .name = "Boya_Q16B_16_33", - .cfg = &flashCfg_Boya, - }, - { - .jedecID = 0x164068, - .name = "Boya_Q32B_32_33", - .cfg = &flashCfg_Boya, - }, - { - .jedecID = 0x174068, - .name = "Boya_Q64A_64_33", - .cfg = &flashCfg_Boya, - }, - { - .jedecID = 0x184068, - .name = "Boya_Q128A_128_33", - .cfg = &flashCfg_Boya, - }, - { - .jedecID = 0x14605E, - .name = "FT_VQ80", - .cfg = &flashCfg_FT_VQ80, - } -}; +static const ATTR_TCM_CONST_SECTION Flash_Info_t flashInfos[] = {{ + .jedecID = 0x1440ef, + .name = "Winb_80DV_08_33", + .cfg = &flashCfg_Winb_80DV, + }, + { + .jedecID = 0x1540ef, + .name = "Winb_16DV_16_33", + .cfg = &flashCfg_Winb_16DV, + }, + { + .jedecID = 0x1640ef, + .name = "Winb_32FV_32_33", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x1460ef, + .name = "Winb_80EW_08_18", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x1560ef, + .name = "Winb_16FW_16_18", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x1660ef, + .name = "Winb_32FW_32_18", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x1860ef, + .name = "Winb_128FW_128_18", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x1680ef, + .name = "Winb_32JW_32_18", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x13605e, + .name = "Zbit_04_33", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x14605e, + .name = "Zbit_08_33", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x14609d, + .name = "ISSI_08_33", + .cfg = &flashCfg_Issi, + }, + { + .jedecID = 0x15609d, + .name = "ISSI_16_33", + .cfg = &flashCfg_Issi, + }, + { + .jedecID = 0x16609d, + .name = "ISSI_32_33", + .cfg = &flashCfg_Issi, + }, + { + .jedecID = 0x14709d, + .name = "ISSI_08_18", + .cfg = &flashCfg_Issi, + }, + { + .jedecID = 0x15709d, + .name = "ISSI_16_18", + .cfg = &flashCfg_Issi, + }, + { + .jedecID = 0x16709d, + .name = "ISSI_32_18", + .cfg = &flashCfg_Issi, + }, + { + .jedecID = 0x134051, + .name = "GD_MD04D_04_33", + .cfg = &flashCfg_Gd_Md_40D, + }, + { + .jedecID = 0x1440C8, + .name = "GD_Q08E_08_33", + .cfg = &flashCfg_Gd_Q80E_Q16E, + }, + { + .jedecID = 0x1540C8, + .name = "GD_Q16E_16_33", + .cfg = &flashCfg_Gd_Q80E_Q16E, + }, + { + .jedecID = 0x1640C8, + .name = "GD_Q32C_32_33", + .cfg = &flashCfg_Gd_Q32C, + }, + { + .jedecID = 0x1460C8, + .name = "GD_LQ08C_08_18", + .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, + }, + { + .jedecID = 0x1560C8, + .name = "GD_LE16C_16_18", + .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, + }, + { + .jedecID = 0x1660C8, + .name = "GD_LQ32D_32_18", + .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, + }, + { + .jedecID = 0x1465C8, + .name = "GD_WQ80E_80_33", + .cfg = &flashCfg_Gd_WQ80E_WQ16E, + }, + { + .jedecID = 0x1565C8, + .name = "GD_WQ16E_16_33", + .cfg = &flashCfg_Gd_WQ80E_WQ16E, + }, + { + .jedecID = 0x1665C8, + .name = "GD_WQ32E_32_33", + .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, + }, + { + .jedecID = 0x3425C2, + .name = "MX_25V80_08_18", + .cfg = &flashCfg_Mxic, + }, + { + .jedecID = 0x3525C2, + .name = "MX_25U16_35_18", + .cfg = &flashCfg_Mxic_1635F, + }, + { + .jedecID = 0x3625C2, + .name = "MX_25V32_32_18", + .cfg = &flashCfg_Mxic, + }, + { + .jedecID = 0x13400B, + .name = "XT_25F04D_04_33", + .cfg = &flashCfg_Xtx40, + }, + { + .jedecID = 0x15400B, + .name = "XT_25F16B_16_33", + .cfg = &flashCfg_Xtx, + }, + { + .jedecID = 0x16400B, + .name = "XT_25F32B_32_33", + .cfg = &flashCfg_Xtx, + }, + { + .jedecID = 0x14600B, + .name = "XT_25Q80B_08_18", + .cfg = &flashCfg_Xtx, + }, + { + .jedecID = 0x16600B, + .name = "XT_25Q32B_32_18", + .cfg = &flashCfg_Xtx, + }, + { + .jedecID = 0x146085, + .name = "Puya_Q80L/H_08_18/33", + .cfg = &flashCfg_Puya_Q80L_Q80H_Q16H, + }, + { + .jedecID = 0x156085, + .name = "Puya_Q16H_16_33", + .cfg = &flashCfg_Puya_Q80L_Q80H_Q16H, + }, + { + .jedecID = 0x166085, + .name = "Puya_Q32H_32_33", + .cfg = &flashCfg_Puya_Q32H, + }, + { + .jedecID = 0x134068, + .name = "Boya_Q04B_04_33", + .cfg = &flashCfg_Boya40, + }, + { + .jedecID = 0x144068, + .name = "Boya_Q08B_08_33", + .cfg = &flashCfg_Boya, + }, + { + .jedecID = 0x154068, + .name = "Boya_Q16B_16_33", + .cfg = &flashCfg_Boya, + }, + { + .jedecID = 0x164068, + .name = "Boya_Q32B_32_33", + .cfg = &flashCfg_Boya, + }, + { + .jedecID = 0x174068, + .name = "Boya_Q64A_64_33", + .cfg = &flashCfg_Boya, + }, + { + .jedecID = 0x184068, + .name = "Boya_Q128A_128_33", + .cfg = &flashCfg_Boya, + }, + { + .jedecID = 0x14605E, + .name = "FT_VQ80", + .cfg = &flashCfg_FT_VQ80, + }}; #endif /*@} end of group SF_CFG_Private_Variables */ @@ -2074,116 +2071,114 @@ static const ATTR_TCM_CONST_SECTION Flash_Info_t flashInfos[] = { */ /****************************************************************************/ /** - * @brief Init external flash GPIO according to flash GPIO config - * - * @param extFlashPin: Flash GPIO config - * - * @return None - * -*******************************************************************************/ + * @brief Init external flash GPIO according to flash GPIO config + * + * @param extFlashPin: Flash GPIO config + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -/* static */ void ATTR_TCM_SECTION SF_Cfg_Init_Ext_Flash_Gpio(uint8_t extFlashPin) -{ - GLB_GPIO_Cfg_Type cfg; - uint8_t gpiopins[6]; - uint8_t i = 0; - - cfg.gpioMode = GPIO_MODE_AF; - cfg.pullType = GPIO_PULL_UP; - cfg.drive = 1; - cfg.smtCtrl = 1; - cfg.gpioFun = GPIO_FUN_FLASH_PSRAM; - - if (extFlashPin == 0) { - gpiopins[0] = BFLB_EXTFLASH_CLK0_GPIO; - gpiopins[1] = BFLB_EXTFLASH_CS0_GPIO; - gpiopins[2] = BFLB_EXTFLASH_DATA00_GPIO; - gpiopins[3] = BFLB_EXTFLASH_DATA10_GPIO; - gpiopins[4] = BFLB_EXTFLASH_DATA20_GPIO; - gpiopins[5] = BFLB_EXTFLASH_DATA30_GPIO; - } else if (extFlashPin == 1) { - gpiopins[0] = BFLB_EXTFLASH_CLK1_GPIO; - gpiopins[1] = BFLB_EXTFLASH_CS1_GPIO; - gpiopins[2] = BFLB_EXTFLASH_DATA01_GPIO; - gpiopins[3] = BFLB_EXTFLASH_DATA11_GPIO; - gpiopins[4] = BFLB_EXTFLASH_DATA21_GPIO; - gpiopins[5] = BFLB_EXTFLASH_DATA31_GPIO; +/* static */ void ATTR_TCM_SECTION SF_Cfg_Init_Ext_Flash_Gpio(uint8_t extFlashPin) { + GLB_GPIO_Cfg_Type cfg; + uint8_t gpiopins[6]; + uint8_t i = 0; + + cfg.gpioMode = GPIO_MODE_AF; + cfg.pullType = GPIO_PULL_UP; + cfg.drive = 1; + cfg.smtCtrl = 1; + cfg.gpioFun = GPIO_FUN_FLASH_PSRAM; + + if (extFlashPin == 0) { + gpiopins[0] = BFLB_EXTFLASH_CLK0_GPIO; + gpiopins[1] = BFLB_EXTFLASH_CS0_GPIO; + gpiopins[2] = BFLB_EXTFLASH_DATA00_GPIO; + gpiopins[3] = BFLB_EXTFLASH_DATA10_GPIO; + gpiopins[4] = BFLB_EXTFLASH_DATA20_GPIO; + gpiopins[5] = BFLB_EXTFLASH_DATA30_GPIO; + } else if (extFlashPin == 1) { + gpiopins[0] = BFLB_EXTFLASH_CLK1_GPIO; + gpiopins[1] = BFLB_EXTFLASH_CS1_GPIO; + gpiopins[2] = BFLB_EXTFLASH_DATA01_GPIO; + gpiopins[3] = BFLB_EXTFLASH_DATA11_GPIO; + gpiopins[4] = BFLB_EXTFLASH_DATA21_GPIO; + gpiopins[5] = BFLB_EXTFLASH_DATA31_GPIO; + } else { + gpiopins[0] = BFLB_EXTFLASH_CLK2_GPIO; + gpiopins[1] = BFLB_EXTFLASH_CS2_GPIO; + gpiopins[2] = BFLB_EXTFLASH_DATA02_GPIO; + gpiopins[3] = BFLB_EXTFLASH_DATA12_GPIO; + gpiopins[4] = BFLB_EXTFLASH_DATA22_GPIO; + gpiopins[5] = BFLB_EXTFLASH_DATA32_GPIO; + } + + for (i = 0; i < sizeof(gpiopins); i++) { + cfg.gpioPin = gpiopins[i]; + + if (i == 0 || i == 1) { + /*flash clk and cs is output*/ + cfg.gpioMode = GPIO_MODE_OUTPUT; } else { - gpiopins[0] = BFLB_EXTFLASH_CLK2_GPIO; - gpiopins[1] = BFLB_EXTFLASH_CS2_GPIO; - gpiopins[2] = BFLB_EXTFLASH_DATA02_GPIO; - gpiopins[3] = BFLB_EXTFLASH_DATA12_GPIO; - gpiopins[4] = BFLB_EXTFLASH_DATA22_GPIO; - gpiopins[5] = BFLB_EXTFLASH_DATA32_GPIO; + /*data are bidir*/ + cfg.gpioMode = GPIO_MODE_AF; } - for (i = 0; i < sizeof(gpiopins); i++) { - cfg.gpioPin = gpiopins[i]; - - if (i == 0 || i == 1) { - /*flash clk and cs is output*/ - cfg.gpioMode = GPIO_MODE_OUTPUT; - } else { - /*data are bidir*/ - cfg.gpioMode = GPIO_MODE_AF; - } - - GLB_GPIO_Init(&cfg); - } + GLB_GPIO_Init(&cfg); + } } #endif /****************************************************************************/ /** - * @brief Deinit external flash GPIO according to flash GPIO config - * - * @param extFlashPin: Flash GPIO config - * - * @return None - * -*******************************************************************************/ + * @brief Deinit external flash GPIO according to flash GPIO config + * + * @param extFlashPin: Flash GPIO config + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -/* static */ void ATTR_TCM_SECTION SF_Cfg_Deinit_Ext_Flash_Gpio(uint8_t extFlashPin) -{ - GLB_GPIO_Cfg_Type cfg; - uint8_t gpiopins[6]; - uint8_t i = 0; - - cfg.gpioMode = GPIO_MODE_INPUT; - cfg.pullType = GPIO_PULL_UP; - cfg.drive = 1; - cfg.smtCtrl = 1; - cfg.gpioFun = GPIO_FUN_GPIO; - - if (extFlashPin == 0) { - gpiopins[0] = BFLB_EXTFLASH_CLK0_GPIO; - gpiopins[1] = BFLB_EXTFLASH_CS0_GPIO; - gpiopins[2] = BFLB_EXTFLASH_DATA00_GPIO; - gpiopins[3] = BFLB_EXTFLASH_DATA10_GPIO; - gpiopins[4] = BFLB_EXTFLASH_DATA20_GPIO; - gpiopins[5] = BFLB_EXTFLASH_DATA30_GPIO; - - } else if (extFlashPin == 1) { - gpiopins[0] = BFLB_EXTFLASH_CLK1_GPIO; - gpiopins[1] = BFLB_EXTFLASH_CS1_GPIO; - gpiopins[2] = BFLB_EXTFLASH_DATA01_GPIO; - gpiopins[3] = BFLB_EXTFLASH_DATA11_GPIO; - gpiopins[4] = BFLB_EXTFLASH_DATA21_GPIO; - gpiopins[5] = BFLB_EXTFLASH_DATA31_GPIO; - } else { - gpiopins[0] = BFLB_EXTFLASH_CLK2_GPIO; - gpiopins[1] = BFLB_EXTFLASH_CS2_GPIO; - gpiopins[2] = BFLB_EXTFLASH_DATA02_GPIO; - gpiopins[3] = BFLB_EXTFLASH_DATA12_GPIO; - gpiopins[4] = BFLB_EXTFLASH_DATA22_GPIO; - gpiopins[5] = BFLB_EXTFLASH_DATA32_GPIO; - } - - for (i = 0; i < sizeof(gpiopins); i++) { - cfg.gpioPin = gpiopins[i]; - GLB_GPIO_Init(&cfg); - } +/* static */ void ATTR_TCM_SECTION SF_Cfg_Deinit_Ext_Flash_Gpio(uint8_t extFlashPin) { + GLB_GPIO_Cfg_Type cfg; + uint8_t gpiopins[6]; + uint8_t i = 0; + + cfg.gpioMode = GPIO_MODE_INPUT; + cfg.pullType = GPIO_PULL_UP; + cfg.drive = 1; + cfg.smtCtrl = 1; + cfg.gpioFun = GPIO_FUN_GPIO; + + if (extFlashPin == 0) { + gpiopins[0] = BFLB_EXTFLASH_CLK0_GPIO; + gpiopins[1] = BFLB_EXTFLASH_CS0_GPIO; + gpiopins[2] = BFLB_EXTFLASH_DATA00_GPIO; + gpiopins[3] = BFLB_EXTFLASH_DATA10_GPIO; + gpiopins[4] = BFLB_EXTFLASH_DATA20_GPIO; + gpiopins[5] = BFLB_EXTFLASH_DATA30_GPIO; + + } else if (extFlashPin == 1) { + gpiopins[0] = BFLB_EXTFLASH_CLK1_GPIO; + gpiopins[1] = BFLB_EXTFLASH_CS1_GPIO; + gpiopins[2] = BFLB_EXTFLASH_DATA01_GPIO; + gpiopins[3] = BFLB_EXTFLASH_DATA11_GPIO; + gpiopins[4] = BFLB_EXTFLASH_DATA21_GPIO; + gpiopins[5] = BFLB_EXTFLASH_DATA31_GPIO; + } else { + gpiopins[0] = BFLB_EXTFLASH_CLK2_GPIO; + gpiopins[1] = BFLB_EXTFLASH_CS2_GPIO; + gpiopins[2] = BFLB_EXTFLASH_DATA02_GPIO; + gpiopins[3] = BFLB_EXTFLASH_DATA12_GPIO; + gpiopins[4] = BFLB_EXTFLASH_DATA22_GPIO; + gpiopins[5] = BFLB_EXTFLASH_DATA32_GPIO; + } + + for (i = 0; i < sizeof(gpiopins); i++) { + cfg.gpioPin = gpiopins[i]; + GLB_GPIO_Init(&cfg); + } } #endif @@ -2194,206 +2189,202 @@ __WEAK */ /****************************************************************************/ /** - * @brief Get flash config according to flash ID - * - * @param flashID: Flash ID - * @param pFlashCfg: Flash config pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Get flash config according to flash ID + * + * @param flashID: Flash ID + * @param pFlashCfg: Flash config pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION SF_Cfg_Get_Flash_Cfg_Need_Lock(uint32_t flashID, SPI_Flash_Cfg_Type *pFlashCfg) -{ - uint32_t i; - uint8_t buf[sizeof(SPI_Flash_Cfg_Type) + 8]; - uint32_t crc, *pCrc; - uint32_t xipOffset; - - if (flashID == 0) { - xipOffset = SF_Ctrl_Get_Flash_Image_Offset(); - SF_Ctrl_Set_Flash_Image_Offset(0); - XIP_SFlash_Read_Via_Cache_Need_Lock(8 + BL702_FLASH_XIP_BASE, buf, sizeof(SPI_Flash_Cfg_Type) + 8); - SF_Ctrl_Set_Flash_Image_Offset(xipOffset); - - if (BL702_MemCmp(buf, BFLB_FLASH_CFG_MAGIC, 4) == 0) { - crc = BFLB_Soft_CRC32((uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); - pCrc = (uint32_t *)(buf + 4 + sizeof(SPI_Flash_Cfg_Type)); - - if (*pCrc == crc) { - BL702_MemCpy_Fast(pFlashCfg, (uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); - return SUCCESS; - } - } - } else { - for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { - if (flashInfos[i].jedecID == flashID) { - BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); - return SUCCESS; - } - } +BL_Err_Type ATTR_TCM_SECTION SF_Cfg_Get_Flash_Cfg_Need_Lock(uint32_t flashID, SPI_Flash_Cfg_Type *pFlashCfg) { + uint32_t i; + uint8_t buf[sizeof(SPI_Flash_Cfg_Type) + 8]; + uint32_t crc, *pCrc; + uint32_t xipOffset; + + if (flashID == 0) { + xipOffset = SF_Ctrl_Get_Flash_Image_Offset(); + SF_Ctrl_Set_Flash_Image_Offset(0); + XIP_SFlash_Read_Via_Cache_Need_Lock(8 + BL702_FLASH_XIP_BASE, buf, sizeof(SPI_Flash_Cfg_Type) + 8); + SF_Ctrl_Set_Flash_Image_Offset(xipOffset); + + if (BL702_MemCmp(buf, BFLB_FLASH_CFG_MAGIC, 4) == 0) { + crc = BFLB_Soft_CRC32((uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); + pCrc = (uint32_t *)(buf + 4 + sizeof(SPI_Flash_Cfg_Type)); + + if (*pCrc == crc) { + BL702_MemCpy_Fast(pFlashCfg, (uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); + return SUCCESS; + } + } + } else { + for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { + if (flashInfos[i].jedecID == flashID) { + BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); + return SUCCESS; + } } + } - return ERROR; + return ERROR; } #endif /****************************************************************************/ /** - * @brief Init flash GPIO according to flash Pin config - * - * @param flashPinCfg: Specify flash Pin config - * @param restoreDefault: Wether to restore default setting - * - * @return None - * -*******************************************************************************/ + * @brief Init flash GPIO according to flash Pin config + * + * @param flashPinCfg: Specify flash Pin config + * @param restoreDefault: Wether to restore default setting + * + * @return None + * + *******************************************************************************/ __WEAK -void ATTR_TCM_SECTION SF_Cfg_Init_Flash_Gpio(uint8_t flashPinCfg, uint8_t restoreDefault) -{ - uint8_t flashCfg; - uint8_t swapCfg; - uint32_t tmpVal; - - flashCfg = (flashPinCfg >> 2) & 0x03; - swapCfg = flashPinCfg & 0x03; - - if (restoreDefault) { - /* Set Default first */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); - - if (BL_GET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO) == 0x00) { - SF_Cfg_Init_Ext_Flash_Gpio(1); - } - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - SF_Ctrl_Select_Pad(SF_CTRL_PAD_SEL_SF2); - - /* Default is set, so return */ - if (flashCfg == BFLB_FLASH_CFG_SF2_EXT_23_28 && swapCfg == BFLB_SF2_SWAP_NONE) { - return; - } +void ATTR_TCM_SECTION SF_Cfg_Init_Flash_Gpio(uint8_t flashPinCfg, uint8_t restoreDefault) { + uint8_t flashCfg; + uint8_t swapCfg; + uint32_t tmpVal; + + flashCfg = (flashPinCfg >> 2) & 0x03; + swapCfg = flashPinCfg & 0x03; + + if (restoreDefault) { + /* Set Default first */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); + + if (BL_GET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO) == 0x00) { + SF_Cfg_Init_Ext_Flash_Gpio(1); } - if (flashCfg == BFLB_FLASH_CFG_SF1_EXT_17_22) { - SF_Cfg_Init_Ext_Flash_Gpio(0); - SF_Ctrl_Select_Pad(SF_CTRL_PAD_SEL_SF1); + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); + + SF_Ctrl_Select_Pad(SF_CTRL_PAD_SEL_SF2); + + /* Default is set, so return */ + if (flashCfg == BFLB_FLASH_CFG_SF2_EXT_23_28 && swapCfg == BFLB_SF2_SWAP_NONE) { + return; + } + } + + if (flashCfg == BFLB_FLASH_CFG_SF1_EXT_17_22) { + SF_Cfg_Init_Ext_Flash_Gpio(0); + SF_Ctrl_Select_Pad(SF_CTRL_PAD_SEL_SF1); + } else { + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); + + if (BL_GET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO) == 0x00) { + SF_Cfg_Init_Ext_Flash_Gpio(1); + } + + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + + if (swapCfg == BFLB_SF2_SWAP_NONE) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); + } else if (swapCfg == BFLB_SF2_SWAP_CS_IO2) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); + } else if (swapCfg == BFLB_SF2_SWAP_IO0_IO3) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); } else { - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); - - if (BL_GET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO) == 0x00) { - SF_Cfg_Init_Ext_Flash_Gpio(1); - } - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - - if (swapCfg == BFLB_SF2_SWAP_NONE) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); - } else if (swapCfg == BFLB_SF2_SWAP_CS_IO2) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); - } else if (swapCfg == BFLB_SF2_SWAP_IO0_IO3) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); - } else { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); - } - - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - SF_Ctrl_Select_Pad(SF_CTRL_PAD_SEL_SF2); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); } + + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); + + SF_Ctrl_Select_Pad(SF_CTRL_PAD_SEL_SF2); + } } /****************************************************************************/ /** - * @brief Identify one flash - * - * @param callFromFlash: code run at flash or ram - * @param autoScan: Auto scan all GPIO pin - * @param flashPinCfg: Specify flash GPIO config, not auto scan - * @param restoreDefault: Wether restore default flash GPIO config - * @param pFlashCfg: Flash config pointer - * - * @return Flash ID - * -*******************************************************************************/ + * @brief Identify one flash + * + * @param callFromFlash: code run at flash or ram + * @param autoScan: Auto scan all GPIO pin + * @param flashPinCfg: Specify flash GPIO config, not auto scan + * @param restoreDefault: Wether restore default flash GPIO config + * @param pFlashCfg: Flash config pointer + * + * @return Flash ID + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint32_t ATTR_TCM_SECTION SF_Cfg_Flash_Identify(uint8_t callFromFlash, - uint32_t autoScan, uint32_t flashPinCfg, uint8_t restoreDefault, SPI_Flash_Cfg_Type *pFlashCfg) -{ - uint32_t jdecId = 0; - uint32_t i = 0; - uint32_t offset; - BL_Err_Type stat; +uint32_t ATTR_TCM_SECTION SF_Cfg_Flash_Identify(uint8_t callFromFlash, uint32_t autoScan, uint32_t flashPinCfg, uint8_t restoreDefault, SPI_Flash_Cfg_Type *pFlashCfg) { + uint32_t jdecId = 0; + uint32_t i = 0; + uint32_t offset; + BL_Err_Type stat; - BL702_MemCpy_Fast(pFlashCfg, &flashCfg_Gd_Q80E_Q16E, sizeof(SPI_Flash_Cfg_Type)); + BL702_MemCpy_Fast(pFlashCfg, &flashCfg_Gd_Q80E_Q16E, sizeof(SPI_Flash_Cfg_Type)); - if (callFromFlash == 1) { - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + if (callFromFlash == 1) { + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SF_Ctrl_Set_Owner(SF_CTRL_OWNER_IAHB); - return 0; - } + if (stat != SUCCESS) { + SF_Ctrl_Set_Owner(SF_CTRL_OWNER_IAHB); + return 0; } - - if (autoScan) { - flashPinCfg = 0; - - do { - if (flashPinCfg > 0x0f) { - jdecId = 0; - break; - } - - SF_Cfg_Init_Flash_Gpio(flashPinCfg, restoreDefault); - SFlash_Releae_Powerdown(pFlashCfg); - SFlash_Reset_Continue_Read(pFlashCfg); - SFlash_DisableBurstWrap(pFlashCfg); - jdecId = 0; - SFlash_GetJedecId(pFlashCfg, (uint8_t *)&jdecId); - SFlash_DisableBurstWrap(pFlashCfg); - jdecId = jdecId & 0xffffff; - flashPinCfg++; - } while ((jdecId & 0x00ffff) == 0 || (jdecId & 0xffff00) == 0 || (jdecId & 0x00ffff) == 0xffff || (jdecId & 0xffff00) == 0xffff00); - } else { - /* select media gpio */ - SF_Cfg_Init_Flash_Gpio(flashPinCfg, restoreDefault); - SFlash_Releae_Powerdown(pFlashCfg); - SFlash_Reset_Continue_Read(pFlashCfg); - SFlash_DisableBurstWrap(pFlashCfg); - SFlash_GetJedecId(pFlashCfg, (uint8_t *)&jdecId); - SFlash_DisableBurstWrap(pFlashCfg); - jdecId = jdecId & 0xffffff; + } + + if (autoScan) { + flashPinCfg = 0; + + do { + if (flashPinCfg > 0x0f) { + jdecId = 0; + break; + } + + SF_Cfg_Init_Flash_Gpio(flashPinCfg, restoreDefault); + SFlash_Releae_Powerdown(pFlashCfg); + SFlash_Reset_Continue_Read(pFlashCfg); + SFlash_DisableBurstWrap(pFlashCfg); + jdecId = 0; + SFlash_GetJedecId(pFlashCfg, (uint8_t *)&jdecId); + SFlash_DisableBurstWrap(pFlashCfg); + jdecId = jdecId & 0xffffff; + flashPinCfg++; + } while ((jdecId & 0x00ffff) == 0 || (jdecId & 0xffff00) == 0 || (jdecId & 0x00ffff) == 0xffff || (jdecId & 0xffff00) == 0xffff00); + } else { + /* select media gpio */ + SF_Cfg_Init_Flash_Gpio(flashPinCfg, restoreDefault); + SFlash_Releae_Powerdown(pFlashCfg); + SFlash_Reset_Continue_Read(pFlashCfg); + SFlash_DisableBurstWrap(pFlashCfg); + SFlash_GetJedecId(pFlashCfg, (uint8_t *)&jdecId); + SFlash_DisableBurstWrap(pFlashCfg); + jdecId = jdecId & 0xffffff; + } + + for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { + if (flashInfos[i].jedecID == jdecId) { + BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); + break; } + } - for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { - if (flashInfos[i].jedecID == jdecId) { - BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); - break; - } + if (i == sizeof(flashInfos) / sizeof(flashInfos[0])) { + if (callFromFlash == 1) { + XIP_SFlash_State_Restore(pFlashCfg, pFlashCfg->ioMode, offset); } - if (i == sizeof(flashInfos) / sizeof(flashInfos[0])) { - if (callFromFlash == 1) { - XIP_SFlash_State_Restore(pFlashCfg, pFlashCfg->ioMode, offset); - } - - return jdecId; - } else { - if (callFromFlash == 1) { - XIP_SFlash_State_Restore(pFlashCfg, pFlashCfg->ioMode, offset); - } - - return (jdecId | BFLB_FLASH_ID_VALID_FLAG); + return jdecId; + } else { + if (callFromFlash == 1) { + XIP_SFlash_State_Restore(pFlashCfg, pFlashCfg->ioMode, offset); } + + return (jdecId | BFLB_FLASH_ID_VALID_FLAG); + } } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg_ext.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg_ext.c index d90928c88f..5fc7f5af61 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg_ext.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg_ext.c @@ -1,44 +1,44 @@ /** - ****************************************************************************** - * @file bl702_sf_cfg_ext.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_sf_cfg_ext.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ +#include "bl702_sf_cfg_ext.h" #include "bl702_glb.h" +#include "bl702_romdriver.h" #include "bl702_sf_cfg.h" -#include "bl702_sf_cfg_ext.h" #include "bl702_xip_sflash.h" -#include "bl702_romdriver.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -58,11 +58,10 @@ /** @defgroup SF_CFG_EXT_Private_Types * @{ */ -typedef struct -{ - uint32_t jedecID; - char *name; - const SPI_Flash_Cfg_Type *cfg; +typedef struct { + uint32_t jedecID; + char *name; + const SPI_Flash_Cfg_Type *cfg; } Flash_Info_t; /*@} end of group SF_CFG_EXT_Private_Types */ @@ -71,488 +70,488 @@ typedef struct * @{ */ -static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Gd_Md_40D={ - .resetCreadCmd = 0xff, +static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Gd_Md_40D = { + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x51, + .mid = 0x51, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16/8, - .cReadSupport = 0, - .cReadMode = 0xA0, + .frQioDmyClk = 16 / 8, + .cReadSupport = 0, + .cReadMode = 0xA0, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, - /*erase*/ - .chipEraseCmd = 0xc7, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, + /*erase*/ + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = 0x11, - .clkDelay = 1, + .ioMode = 0x11, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8/8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8/8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8/8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8/8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16/8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, - /*AC*/ + /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20*1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_MX_KH25 = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xc2, + .mid = 0xc2, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x00, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x00, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x00, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 0, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 0, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = 0x11, - .clkDelay = 1, + .ioMode = 0x11, + .clkDelay = 1, .clkInvert = 0x01, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 33000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 33000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_FM_Q80 = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xc8, + .mid = 0xc8, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0xA0, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0xA0, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x01, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 33000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 33000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Winb_16JV = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xef, + .mid = 0xef, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x31, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x01, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 400, - .timeE32k = 1600, - .timeE64k = 2000, + .timeE32k = 1600, + .timeE64k = 2000, .timePagePgm = 5, - .timeCe = 33000, - .pdDelay = 3, - .qeData = 0, + .timeCe = 33000, + .pdDelay = 3, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION Flash_Info_t flashInfos[] = { { .jedecID = 0x134051, - .name = "GD_MD04D_04_33", - .cfg = &flashCfg_Gd_Md_40D, + .name = "GD_MD04D_04_33", + .cfg = &flashCfg_Gd_Md_40D, }, { .jedecID = 0x1320c2, - .name = "MX_KH40_04_33", - .cfg = &flashCfg_MX_KH25, + .name = "MX_KH40_04_33", + .cfg = &flashCfg_MX_KH25, }, { .jedecID = 0x1420c2, - .name = "MX_KH80_08_33", - .cfg = &flashCfg_MX_KH25, + .name = "MX_KH80_08_33", + .cfg = &flashCfg_MX_KH25, }, { .jedecID = 0x1520c2, - .name = "MX_KH16_16_33", - .cfg = &flashCfg_MX_KH25, + .name = "MX_KH16_16_33", + .cfg = &flashCfg_MX_KH25, }, { .jedecID = 0x1440A1, - .name = "FM_25Q80_80_33", - .cfg = &flashCfg_FM_Q80, + .name = "FM_25Q80_80_33", + .cfg = &flashCfg_FM_Q80, }, { .jedecID = 0x1570EF, - .name = "Winb_16JV_16_33", - .cfg = &flashCfg_Winb_16JV, + .name = "Winb_16JV_16_33", + .cfg = &flashCfg_Winb_16JV, }, { .jedecID = 0x1870EF, - .name = "Winb_128JV_128_33", - .cfg = &flashCfg_Winb_16JV, + .name = "Winb_128JV_128_33", + .cfg = &flashCfg_Winb_16JV, }, { .jedecID = 0x15605E, - .name = "ZB_VQ16_16_33", - .cfg = &flashCfg_Winb_16JV, + .name = "ZB_VQ16_16_33", + .cfg = &flashCfg_Winb_16JV, }, { .jedecID = 0x144020, - .name = "XM_25QH80_80_33", - .cfg = &flashCfg_Winb_16JV, + .name = "XM_25QH80_80_33", + .cfg = &flashCfg_Winb_16JV, }, { .jedecID = 0x154020, - .name = "XM_25QH16_16_33", - .cfg = &flashCfg_Winb_16JV, + .name = "XM_25QH16_16_33", + .cfg = &flashCfg_Winb_16JV, }, { .jedecID = 0x164020, - .name = "XM_25QH32_32_33", - .cfg = &flashCfg_Winb_16JV, + .name = "XM_25QH32_32_33", + .cfg = &flashCfg_Winb_16JV, }, { .jedecID = 0x174020, - .name = "XM_25QH64_64_33", - .cfg = &flashCfg_Winb_16JV, + .name = "XM_25QH64_64_33", + .cfg = &flashCfg_Winb_16JV, }, { .jedecID = 0x13325E, - .name = "ZB_D40B_80_33", - .cfg = &flashCfg_MX_KH25, + .name = "ZB_D40B_80_33", + .cfg = &flashCfg_MX_KH25, }, { .jedecID = 0x14325E, - .name = "ZB_D80B_80_33", - .cfg = &flashCfg_MX_KH25, + .name = "ZB_D80B_80_33", + .cfg = &flashCfg_MX_KH25, }, { .jedecID = 0x15405E, - .name = "ZB_25Q16B_15_33", - .cfg = &flashCfg_Winb_16JV, + .name = "ZB_25Q16B_15_33", + .cfg = &flashCfg_Winb_16JV, }, { .jedecID = 0x16405E, - .name = "ZB_25Q32B_16_33", - .cfg = &flashCfg_Winb_16JV, + .name = "ZB_25Q32B_16_33", + .cfg = &flashCfg_Winb_16JV, }, { .jedecID = 0x1560EB, - .name = "TH_25Q16HB_16_33", - .cfg = &flashCfg_FM_Q80, + .name = "TH_25Q16HB_16_33", + .cfg = &flashCfg_FM_Q80, }, { .jedecID = 0x15345E, - .name = "ZB_25Q16A_15_33", - .cfg = &flashCfg_Winb_16JV, + .name = "ZB_25Q16A_15_33", + .cfg = &flashCfg_Winb_16JV, }, }; @@ -575,127 +574,123 @@ static const ATTR_TCM_CONST_SECTION Flash_Info_t flashInfos[] = { */ /****************************************************************************/ /** - * @brief Init internal flash GPIO - * - * @param None - * - * @return None - * -*******************************************************************************/ -void ATTR_TCM_SECTION SF_Cfg_Init_Internal_Flash_Gpio(void) -{ - GLB_GPIO_Cfg_Type gpioCfg = { - .gpioPin = GLB_GPIO_PIN_0, - .gpioFun = GPIO_FUN_GPIO, - .gpioMode = GPIO_MODE_INPUT, - .pullType = GPIO_PULL_NONE, - .drive = 0, - .smtCtrl = 1, - }; - - /* Turn on Flash pad, GPIO23 - GPIO28 */ - for (uint32_t pin = 23; pin < 29; pin++) { - gpioCfg.gpioPin = pin; - - if (pin == 25) { - gpioCfg.pullType = GPIO_PULL_DOWN; - } else { - gpioCfg.pullType = GPIO_PULL_NONE; - } - - GLB_GPIO_Init(&gpioCfg); + * @brief Init internal flash GPIO + * + * @param None + * + * @return None + * + *******************************************************************************/ +void ATTR_TCM_SECTION SF_Cfg_Init_Internal_Flash_Gpio(void) { + GLB_GPIO_Cfg_Type gpioCfg = { + .gpioPin = GLB_GPIO_PIN_0, + .gpioFun = GPIO_FUN_GPIO, + .gpioMode = GPIO_MODE_INPUT, + .pullType = GPIO_PULL_NONE, + .drive = 0, + .smtCtrl = 1, + }; + + /* Turn on Flash pad, GPIO23 - GPIO28 */ + for (uint32_t pin = 23; pin < 29; pin++) { + gpioCfg.gpioPin = pin; + + if (pin == 25) { + gpioCfg.pullType = GPIO_PULL_DOWN; + } else { + gpioCfg.pullType = GPIO_PULL_NONE; } + + GLB_GPIO_Init(&gpioCfg); + } } /****************************************************************************/ /** - * @brief Get flash config according to flash ID - * - * @param flashID: Flash ID - * @param pFlashCfg: Flash config pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION SF_Cfg_Get_Flash_Cfg_Need_Lock_Ext(uint32_t flashID, SPI_Flash_Cfg_Type *pFlashCfg) -{ - uint32_t i; - uint8_t buf[sizeof(SPI_Flash_Cfg_Type) + 8]; - uint32_t crc, *pCrc; - char flashCfgMagic[] = "FCFG"; - - if (flashID == 0) { - XIP_SFlash_Read_Via_Cache_Need_Lock(8 + BL702_FLASH_XIP_BASE, buf, sizeof(SPI_Flash_Cfg_Type) + 8); - - if (BL702_MemCmp(buf, flashCfgMagic, 4) == 0) { - crc = BFLB_Soft_CRC32((uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); - pCrc = (uint32_t *)(buf + 4 + sizeof(SPI_Flash_Cfg_Type)); - - if (*pCrc == crc) { - BL702_MemCpy_Fast(pFlashCfg, (uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); - return SUCCESS; - } - } - } else { - if (SF_Cfg_Get_Flash_Cfg_Need_Lock(flashID, pFlashCfg) == SUCCESS) { - /* 0x134051 flash cfg is wrong in rom, find again */ - if ((flashID&0xFFFFFF) != 0x134051) { - return SUCCESS; - } - } - - for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { - if (flashInfos[i].jedecID == flashID) { - BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); - return SUCCESS; - } - } + * @brief Get flash config according to flash ID + * + * @param flashID: Flash ID + * @param pFlashCfg: Flash config pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION SF_Cfg_Get_Flash_Cfg_Need_Lock_Ext(uint32_t flashID, SPI_Flash_Cfg_Type *pFlashCfg) { + uint32_t i; + uint8_t buf[sizeof(SPI_Flash_Cfg_Type) + 8]; + uint32_t crc, *pCrc; + char flashCfgMagic[] = "FCFG"; + + if (flashID == 0) { + XIP_SFlash_Read_Via_Cache_Need_Lock(8 + BL702_FLASH_XIP_BASE, buf, sizeof(SPI_Flash_Cfg_Type) + 8); + + if (BL702_MemCmp(buf, flashCfgMagic, 4) == 0) { + crc = BFLB_Soft_CRC32((uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); + pCrc = (uint32_t *)(buf + 4 + sizeof(SPI_Flash_Cfg_Type)); + + if (*pCrc == crc) { + BL702_MemCpy_Fast(pFlashCfg, (uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); + return SUCCESS; + } + } + } else { + if (SF_Cfg_Get_Flash_Cfg_Need_Lock(flashID, pFlashCfg) == SUCCESS) { + /* 0x134051 flash cfg is wrong in rom, find again */ + if ((flashID & 0xFFFFFF) != 0x134051) { + return SUCCESS; + } } - return ERROR; + for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { + if (flashInfos[i].jedecID == flashID) { + BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); + return SUCCESS; + } + } + } + + return ERROR; } /****************************************************************************/ /** - * @brief Identify one flash - * - * @param callFromFlash: code run at flash or ram - * @param autoScan: Auto scan all GPIO pin - * @param flashPinCfg: Specify flash GPIO config, not auto scan - * @param restoreDefault: Wether restore default flash GPIO config - * @param pFlashCfg: Flash config pointer - * - * @return Flash ID - * -*******************************************************************************/ -uint32_t ATTR_TCM_SECTION SF_Cfg_Flash_Identify_Ext(uint8_t callFromFlash, - uint32_t autoScan, uint32_t flashPinCfg, uint8_t restoreDefault, SPI_Flash_Cfg_Type *pFlashCfg) -{ - uint32_t jdecId = 0; - uint32_t i = 0; - uint32_t ret = 0; - - ret = SF_Cfg_Flash_Identify(callFromFlash, autoScan, flashPinCfg, restoreDefault, pFlashCfg); - - if ((ret & BFLB_FLASH_ID_VALID_FLAG) != 0) { - /* 0x134051 flash cfg is wrong in rom, find again */ - if ((ret&0xFFFFFF) != 0x134051) { - return ret; - } + * @brief Identify one flash + * + * @param callFromFlash: code run at flash or ram + * @param autoScan: Auto scan all GPIO pin + * @param flashPinCfg: Specify flash GPIO config, not auto scan + * @param restoreDefault: Wether restore default flash GPIO config + * @param pFlashCfg: Flash config pointer + * + * @return Flash ID + * + *******************************************************************************/ +uint32_t ATTR_TCM_SECTION SF_Cfg_Flash_Identify_Ext(uint8_t callFromFlash, uint32_t autoScan, uint32_t flashPinCfg, uint8_t restoreDefault, SPI_Flash_Cfg_Type *pFlashCfg) { + uint32_t jdecId = 0; + uint32_t i = 0; + uint32_t ret = 0; + + ret = SF_Cfg_Flash_Identify(callFromFlash, autoScan, flashPinCfg, restoreDefault, pFlashCfg); + + if ((ret & BFLB_FLASH_ID_VALID_FLAG) != 0) { + /* 0x134051 flash cfg is wrong in rom, find again */ + if ((ret & 0xFFFFFF) != 0x134051) { + return ret; } + } - jdecId = (ret & 0xffffff); + jdecId = (ret & 0xffffff); - for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { - if (flashInfos[i].jedecID == jdecId) { - BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); - break; - } + for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { + if (flashInfos[i].jedecID == jdecId) { + BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); + break; } + } - if (i == sizeof(flashInfos) / sizeof(flashInfos[0])) { - return jdecId; - } else { - return (jdecId | BFLB_FLASH_ID_VALID_FLAG); - } + if (i == sizeof(flashInfos) / sizeof(flashInfos[0])) { + return jdecId; + } else { + return (jdecId | BFLB_FLASH_ID_VALID_FLAG); + } } /*@} end of group SF_CFG_EXT_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_ctrl.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_ctrl.c index a67e0e9836..93e8c59388 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_ctrl.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_ctrl.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_sf_ctrl.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_sf_ctrl.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_sf_ctrl.h" @@ -60,7 +60,7 @@ * @{ */ #define SF_CTRL_BUSY_STATE_TIMEOUT (5 * 160 * 1000) -#define SF_Ctrl_Get_AES_Region(addr, r) (addr + SF_CTRL_AES_REGION_OFFSET + (r)*0x100) +#define SF_Ctrl_Get_AES_Region(addr, r) (addr + SF_CTRL_AES_REGION_OFFSET + (r) * 0x100) /*@} end of group SF_CTRL_Private_Variables */ @@ -87,1359 +87,1324 @@ */ /****************************************************************************/ /** - * @brief Enable serail flash controller - * - * @param cfg: serial flash controller config - * - * @return None - * -*******************************************************************************/ + * @brief Enable serail flash controller + * + * @param cfg: serial flash controller config + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Enable(const SF_Ctrl_Cfg_Type *cfg) -{ - uint32_t tmpVal = 0; - uint32_t timeOut = 0; - - if (cfg == NULL) { - return; - } - - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_OWNER_TYPE(cfg->owner)); +void ATTR_TCM_SECTION SF_Ctrl_Enable(const SF_Ctrl_Cfg_Type *cfg) { + uint32_t tmpVal = 0; + uint32_t timeOut = 0; - timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; + if (cfg == NULL) { + return; + } - while (SET == SF_Ctrl_GetBusyState()) { - timeOut--; + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_OWNER_TYPE(cfg->owner)); - if (timeOut == 0) { - return; - } - } + timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); + while (SET == SF_Ctrl_GetBusyState()) { + timeOut--; - if (cfg->clkDelay > 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_N, cfg->clkDelay - 1); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); + if (timeOut == 0) { + return; } - - /* Serail out inverted, so sf ctrl send on negative edge */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_CLK_OUT_INV_SEL, cfg->clkInvert); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_CLK_SF_RX_INV_SEL, cfg->rxClkInvert); - - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); - - /* Set do di and oe delay */ - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_0_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_0_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_0_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_1, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_1_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_1_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_1_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_2, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_2_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_2_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_2_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_3, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_4); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_3_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_3_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_3_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_4, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_0_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_0_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_0_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_1, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_1_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_1_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_1_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_2, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_2_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_2_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_2_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_3, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_4); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_3_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_3_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_3_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_4, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_0_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_0_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_0_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_1, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_1_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_1_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_1_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_2, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_2_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_2_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_2_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_3, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_4); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_3_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_3_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_3_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_4, tmpVal); - - /* Enable AHB access sram buffer and enable sf interface */ - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SRAM_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_EN); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); - - SF_Ctrl_Set_Owner(cfg->owner); + } + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); + + if (cfg->clkDelay > 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_N, cfg->clkDelay - 1); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); + } + + /* Serail out inverted, so sf ctrl send on negative edge */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_CLK_OUT_INV_SEL, cfg->clkInvert); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_CLK_SF_RX_INV_SEL, cfg->rxClkInvert); + + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); + + /* Set do di and oe delay */ + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_0_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_0_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_0_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_1, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_1_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_1_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_1_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_2, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_2_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_2_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_2_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_3, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_4); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_3_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_3_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_3_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_4, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_0_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_0_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_0_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_1, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_1_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_1_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_1_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_2, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_2_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_2_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_2_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_3, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_4); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_3_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_3_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_3_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_4, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_0_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_0_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_0_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_1, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_1_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_1_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_1_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_2, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_2_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_2_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_2_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_3, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_4); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_3_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_3_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_3_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_4, tmpVal); + + /* Enable AHB access sram buffer and enable sf interface */ + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SRAM_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_EN); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); + + SF_Ctrl_Set_Owner(cfg->owner); } #endif /****************************************************************************/ /** - * @brief Enable serail psram controller - * - * @param sfCtrlPsramCfg: serial psram controller config - * - * @return None - * -*******************************************************************************/ -//#ifndef BFLB_USE_ROM_DRIVER + * @brief Enable serail psram controller + * + * @param sfCtrlPsramCfg: serial psram controller config + * + * @return None + * + *******************************************************************************/ +// #ifndef BFLB_USE_ROM_DRIVER //__WEAK -void ATTR_TCM_SECTION SF_Ctrl_Psram_Init(SF_Ctrl_Psram_Cfg *sfCtrlPsramCfg) -{ - uint32_t tmpVal = 0; +void ATTR_TCM_SECTION SF_Ctrl_Psram_Init(SF_Ctrl_Psram_Cfg *sfCtrlPsramCfg) { + uint32_t tmpVal = 0; - SF_Ctrl_Select_Pad(sfCtrlPsramCfg->padSel); - SF_Ctrl_Select_Bank(sfCtrlPsramCfg->bankSel); + SF_Ctrl_Select_Pad(sfCtrlPsramCfg->padSel); + SF_Ctrl_Select_Bank(sfCtrlPsramCfg->bankSel); - /* Select psram clock delay */ - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_12); + /* Select psram clock delay */ + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_12); - if (sfCtrlPsramCfg->psramRxClkInvertSrc) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SRC); + if (sfCtrlPsramCfg->psramRxClkInvertSrc) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SRC); - if (sfCtrlPsramCfg->psramRxClkInvertSel) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SEL); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SEL); - } + if (sfCtrlPsramCfg->psramRxClkInvertSel) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SEL); } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SRC); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SEL); } + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SRC); + } - if (sfCtrlPsramCfg->psramDelaySrc) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_SRC); + if (sfCtrlPsramCfg->psramDelaySrc) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_SRC); - if (sfCtrlPsramCfg->psramClkDelay > 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IF_READ_DLY_N, sfCtrlPsramCfg->psramClkDelay - 1); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_EN); - } + if (sfCtrlPsramCfg->psramClkDelay > 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IF_READ_DLY_N, sfCtrlPsramCfg->psramClkDelay - 1); } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_SRC); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_EN); } + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_SRC); + } - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_12, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_12, tmpVal); - /* Enable AHB access sram buffer and enable sf interface */ - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SRAM_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_EN); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); + /* Enable AHB access sram buffer and enable sf interface */ + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SRAM_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_EN); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); - SF_Ctrl_Set_Owner(sfCtrlPsramCfg->owner); + SF_Ctrl_Set_Owner(sfCtrlPsramCfg->owner); } -//#endif +// #endif /****************************************************************************/ /** - * @brief Get flash controller clock delay value - * - * @param None - * - * @return Clock delay value - * -*******************************************************************************/ + * @brief Get flash controller clock delay value + * + * @param None + * + * @return Clock delay value + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint8_t ATTR_TCM_SECTION SF_Ctrl_Get_Clock_Delay(void) -{ - uint32_t tmpVal; +uint8_t ATTR_TCM_SECTION SF_Ctrl_Get_Clock_Delay(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); - if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN) == 0) { - return 0; - } else { - return BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_N) + 1; - } + if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN) == 0) { + return 0; + } else { + return BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_N) + 1; + } } #endif /****************************************************************************/ /** - * @brief Set flash controller clock delay value - * - * @param delay: Clock delay value - * - * @return None - * -*******************************************************************************/ + * @brief Set flash controller clock delay value + * + * @param delay: Clock delay value + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Set_Clock_Delay(uint8_t delay) -{ - uint32_t tmpVal; +void ATTR_TCM_SECTION SF_Ctrl_Set_Clock_Delay(uint8_t delay) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); - if (delay > 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_N, delay - 1); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); - } + if (delay > 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_N, delay - 1); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); + } - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); } #endif /****************************************************************************/ /** - * @brief SF Ctrl set cmds config - * - * @param cmdsCfg: SF Ctrl cmds config - * - * @return None - * -*******************************************************************************/ + * @brief SF Ctrl set cmds config + * + * @param cmdsCfg: SF Ctrl cmds config + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Cmds_Set(SF_Ctrl_Cmds_Cfg *cmdsCfg) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_WRAP_LEN_TYPE(cmdsCfg->wrapLen)); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_3); - - if (cmdsCfg->cmdsEn) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_EN); - } - - if (cmdsCfg->burstToggleEn) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_BT_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_BT_EN); - } - - if (cmdsCfg->wrapModeEn) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_WRAP_MODE); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_WRAP_MODE); - } - - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_CMDS_WRAP_LEN, cmdsCfg->wrapLen); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_3, tmpVal); +void ATTR_TCM_SECTION SF_Ctrl_Cmds_Set(SF_Ctrl_Cmds_Cfg *cmdsCfg) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_WRAP_LEN_TYPE(cmdsCfg->wrapLen)); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_3); + + if (cmdsCfg->cmdsEn) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_EN); + } + + if (cmdsCfg->burstToggleEn) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_BT_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_BT_EN); + } + + if (cmdsCfg->wrapModeEn) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_WRAP_MODE); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_WRAP_MODE); + } + + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_CMDS_WRAP_LEN, cmdsCfg->wrapLen); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_3, tmpVal); } #endif /****************************************************************************/ /** - * @brief SF Ctrl pad select - * - * @param sel: pad select type - * - * @return None - * -*******************************************************************************/ + * @brief SF Ctrl pad select + * + * @param sel: pad select type + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Select_Pad(SF_Ctrl_Pad_Select sel) -{ - /* TODO: sf_if_bk_swap */ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_PAD_SELECT(sel)); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_2); - - if (sel <= SF_CTRL_PAD_SEL_SF3) { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, sel); - } else if (sel >= SF_CTRL_PAD_SEL_DUAL_BANK_SF1_SF2 && sel <= SF_CTRL_PAD_SEL_DUAL_BANK_SF3_SF1) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, sel - SF_CTRL_PAD_SEL_DUAL_BANK_SF1_SF2); - } else if (sel == SF_CTRL_PAD_SEL_DUAL_CS_SF2) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, 1); - } else if (sel == SF_CTRL_PAD_SEL_DUAL_CS_SF3) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, 2); - } - - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_2, tmpVal); +void ATTR_TCM_SECTION SF_Ctrl_Select_Pad(SF_Ctrl_Pad_Select sel) { + /* TODO: sf_if_bk_swap */ + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_PAD_SELECT(sel)); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_2); + + if (sel <= SF_CTRL_PAD_SEL_SF3) { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, sel); + } else if (sel >= SF_CTRL_PAD_SEL_DUAL_BANK_SF1_SF2 && sel <= SF_CTRL_PAD_SEL_DUAL_BANK_SF3_SF1) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, sel - SF_CTRL_PAD_SEL_DUAL_BANK_SF1_SF2); + } else if (sel == SF_CTRL_PAD_SEL_DUAL_CS_SF2) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, 1); + } else if (sel == SF_CTRL_PAD_SEL_DUAL_CS_SF3) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, 2); + } + + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_2, tmpVal); } #endif /****************************************************************************/ /** - * @brief SF Ctrl bank select - * - * @param sel: bank select type - * - * @return None - * -*******************************************************************************/ + * @brief SF Ctrl bank select + * + * @param sel: bank select type + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Select_Bank(SF_Ctrl_Select sel) -{ - /* TODO: sf_if_bk_swap */ - uint32_t tmpVal; +void ATTR_TCM_SECTION SF_Ctrl_Select_Bank(SF_Ctrl_Select sel) { + /* TODO: sf_if_bk_swap */ + uint32_t tmpVal; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_SELECT(sel)); + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_SELECT(sel)); - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_2); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_2); - if (sel == SF_CTRL_SEL_FLASH) { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_BK_SEL); - } else { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_BK_SEL); - } + if (sel == SF_CTRL_SEL_FLASH) { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_BK_SEL); + } else { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_BK_SEL); + } - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_2, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_2, tmpVal); } #endif /****************************************************************************/ /** - * @brief Set flash controller owner:I/D AHB or system AHB - * - * @param owner: owner type - * - * @return None - * -*******************************************************************************/ + * @brief Set flash controller owner:I/D AHB or system AHB + * + * @param owner: owner type + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Set_Owner(SF_Ctrl_Owner_Type owner) -{ - uint32_t tmpVal = 0; - uint32_t timeOut = 0; +void ATTR_TCM_SECTION SF_Ctrl_Set_Owner(SF_Ctrl_Owner_Type owner) { + uint32_t tmpVal = 0; + uint32_t timeOut = 0; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_OWNER_TYPE(owner)); + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_OWNER_TYPE(owner)); - timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; + timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; - while (SET == SF_Ctrl_GetBusyState()) { - timeOut--; + while (SET == SF_Ctrl_GetBusyState()) { + timeOut--; - if (timeOut == 0) { - return; - } + if (timeOut == 0) { + return; } + } - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - /* Set owner */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL, owner); + /* Set owner */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL, owner); - /* Set iahb to flash interface */ - if (owner == SF_CTRL_OWNER_IAHB) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SIF_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SIF_EN); - } + /* Set iahb to flash interface */ + if (owner == SF_CTRL_OWNER_IAHB) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SIF_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SIF_EN); + } - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); } #endif /****************************************************************************/ /** - * @brief Disable flash controller - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Disable flash controller + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Disable(void) -{ - uint32_t tmpVal; +void ATTR_TCM_SECTION SF_Ctrl_Disable(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_EN); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); } #endif /****************************************************************************/ /** - * @brief Enable flash controller AES with big indian - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Enable flash controller AES with big indian + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Enable_BE(void) -{ - uint32_t tmpVal; +void ATTR_TCM_SECTION SF_Ctrl_AES_Enable_BE(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_KEY_ENDIAN); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_IV_ENDIAN); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_DOUT_ENDIAN); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_KEY_ENDIAN); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_IV_ENDIAN); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_DOUT_ENDIAN); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); } #endif /****************************************************************************/ /** - * @brief Enable flash controller AES with little indian - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Enable flash controller AES with little indian + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Enable_LE(void) -{ - uint32_t tmpVal; +void ATTR_TCM_SECTION SF_Ctrl_AES_Enable_LE(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_KEY_ENDIAN); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_IV_ENDIAN); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_DOUT_ENDIAN); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_KEY_ENDIAN); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_IV_ENDIAN); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_DOUT_ENDIAN); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); } #endif /****************************************************************************/ /** - * @brief Serial flash controller set AES region - * - * @param region: region number - * @param enable: enable or not - * @param hwKey: hardware key or software key - * @param startAddr: region start address - * @param endAddr: region end address - * @param locked: lock this region or not - * - * @return None - * -*******************************************************************************/ + * @brief Serial flash controller set AES region + * + * @param region: region number + * @param enable: enable or not + * @param hwKey: hardware key or software key + * @param startAddr: region start address + * @param endAddr: region end address + * @param locked: lock this region or not + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Region(uint8_t region, uint8_t enable, - uint8_t hwKey, uint32_t startAddr, uint32_t endAddr, uint8_t locked) -{ - /* Do flash key eco*/ - uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); - uint32_t tmpVal; - - if (!hwKey) { - regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); - } +void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Region(uint8_t region, uint8_t enable, uint8_t hwKey, uint32_t startAddr, uint32_t endAddr, uint8_t locked) { + /* Do flash key eco*/ + uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); + uint32_t tmpVal; + + if (!hwKey) { + regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); + } - tmpVal = BL_RD_REG(regionRegBase, SF_CTRL_SF_AES_CFG); + tmpVal = BL_RD_REG(regionRegBase, SF_CTRL_SF_AES_CFG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_HW_KEY_EN, hwKey); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_START, startAddr / 1024); - /* sf_aes_end =1 means 1,11,1111,1111 */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_END, endAddr / 1024); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_EN, enable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_LOCK, locked); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_HW_KEY_EN, hwKey); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_START, startAddr / 1024); + /* sf_aes_end =1 means 1,11,1111,1111 */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_END, endAddr / 1024); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_EN, enable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_LOCK, locked); - BL_WR_REG(regionRegBase, SF_CTRL_SF_AES_CFG, tmpVal); + BL_WR_REG(regionRegBase, SF_CTRL_SF_AES_CFG, tmpVal); } #endif /****************************************************************************/ /** - * @brief Serial flash controller set AES key - * - * @param region: region number - * @param key: key data pointer - * @param keyType: flash controller AES key type:128 bits,192 bits or 256 bits - * - * @return None - * -*******************************************************************************/ + * @brief Serial flash controller set AES key + * + * @param region: region number + * @param key: key data pointer + * @param keyType: flash controller AES key type:128 bits,192 bits or 256 bits + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Key(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) -{ - /* Do flash key eco*/ - uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); - uint32_t tmpVal, i = 0; - - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_AES_KEY_TYPE(keyType)); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_MODE, keyType); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); - - if (NULL != key) { - if (keyType == SF_CTRL_AES_128BITS) { - i = 4; - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - */ - } else if (keyType == SF_CTRL_AES_256BITS) { - i = 8; - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - */ - } else if (keyType == SF_CTRL_AES_192BITS) { - i = 6; - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - */ - } - - tmpVal = SF_CTRL_SF_AES_KEY_7_OFFSET; - - while (i--) { - BL_WR_WORD(regionRegBase + tmpVal, __REV(BL_RDWD_FRM_BYTEP(key))); - key += 4; - tmpVal -= 4; - } +void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Key(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) { + /* Do flash key eco*/ + uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); + uint32_t tmpVal, i = 0; + + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_AES_KEY_TYPE(keyType)); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_MODE, keyType); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); + + if (NULL != key) { + if (keyType == SF_CTRL_AES_128BITS) { + i = 4; + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + */ + } else if (keyType == SF_CTRL_AES_256BITS) { + i = 8; + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + */ + } else if (keyType == SF_CTRL_AES_192BITS) { + i = 6; + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + */ } + + tmpVal = SF_CTRL_SF_AES_KEY_7_OFFSET; + + while (i--) { + BL_WR_WORD(regionRegBase + tmpVal, __REV(BL_RDWD_FRM_BYTEP(key))); + key += 4; + tmpVal -= 4; + } + } } #endif /****************************************************************************/ /** - * @brief Serial flash controller set AES key with big endian - * - * @param region: region number - * @param key: key data pointer - * @param keyType: flash controller AES key type:128 bits,192 bits or 256 bits - * - * @return None - * -*******************************************************************************/ + * @brief Serial flash controller set AES key with big endian + * + * @param region: region number + * @param key: key data pointer + * @param keyType: flash controller AES key type:128 bits,192 bits or 256 bits + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Key_BE(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) -{ - /* Do flash key eco*/ - uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); - uint32_t tmpVal, i = 0; - - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_AES_KEY_TYPE(keyType)); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_MODE, keyType); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); - - if (NULL != key) { - if (keyType == SF_CTRL_AES_128BITS) { - i = 4; - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,BL_RDWD_FRM_BYTEP(key)); - key+=4; - */ - } else if (keyType == SF_CTRL_AES_256BITS) { - i = 8; - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,BL_RDWD_FRM_BYTEP(key)); - key+=4; - */ - } else if (keyType == SF_CTRL_AES_192BITS) { - i = 6; - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,BL_RDWD_FRM_BYTEP(key)); - */ - } - - tmpVal = SF_CTRL_SF_AES_KEY_0_OFFSET; - - while (i--) { - BL_WR_WORD(regionRegBase + tmpVal, BL_RDWD_FRM_BYTEP(key)); - key += 4; - tmpVal += 4; - } +void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Key_BE(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) { + /* Do flash key eco*/ + uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); + uint32_t tmpVal, i = 0; + + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_AES_KEY_TYPE(keyType)); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_MODE, keyType); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); + + if (NULL != key) { + if (keyType == SF_CTRL_AES_128BITS) { + i = 4; + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,BL_RDWD_FRM_BYTEP(key)); + key+=4; + */ + } else if (keyType == SF_CTRL_AES_256BITS) { + i = 8; + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,BL_RDWD_FRM_BYTEP(key)); + key+=4; + */ + } else if (keyType == SF_CTRL_AES_192BITS) { + i = 6; + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,BL_RDWD_FRM_BYTEP(key)); + */ + } + + tmpVal = SF_CTRL_SF_AES_KEY_0_OFFSET; + + while (i--) { + BL_WR_WORD(regionRegBase + tmpVal, BL_RDWD_FRM_BYTEP(key)); + key += 4; + tmpVal += 4; } + } } #endif /****************************************************************************/ /** - * @brief Serial flash controller set AES iv - * - * @param region: region number - * @param iv: iv data pointer - * @param addrOffset: flash address offset - * - * @return None - * -*******************************************************************************/ + * @brief Serial flash controller set AES iv + * + * @param region: region number + * @param iv: iv data pointer + * @param addrOffset: flash address offset + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Set_IV(uint8_t region, uint8_t *iv, uint32_t addrOffset) -{ - /* Do flash key eco*/ - uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); - uint32_t tmpVal, i = 3; - - if (iv != NULL) { - tmpVal = SF_CTRL_SF_AES_IV_W3_OFFSET; - - while (i--) { - BL_WR_WORD(regionRegBase + tmpVal, __REV(BL_RDWD_FRM_BYTEP(iv))); - iv += 4; - tmpVal -= 4; - } - - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W3,__REV(BL_RDWD_FRM_BYTEP(iv))); - iv+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W2,__REV(BL_RDWD_FRM_BYTEP(iv))); - iv+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W1,__REV(BL_RDWD_FRM_BYTEP(iv))); - iv+=4; - */ - BL_WR_REG(regionRegBase, SF_CTRL_SF_AES_IV_W0, addrOffset); - iv += 4; +void ATTR_TCM_SECTION SF_Ctrl_AES_Set_IV(uint8_t region, uint8_t *iv, uint32_t addrOffset) { + /* Do flash key eco*/ + uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); + uint32_t tmpVal, i = 3; + + if (iv != NULL) { + tmpVal = SF_CTRL_SF_AES_IV_W3_OFFSET; + + while (i--) { + BL_WR_WORD(regionRegBase + tmpVal, __REV(BL_RDWD_FRM_BYTEP(iv))); + iv += 4; + tmpVal -= 4; } + + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W3,__REV(BL_RDWD_FRM_BYTEP(iv))); + iv+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W2,__REV(BL_RDWD_FRM_BYTEP(iv))); + iv+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W1,__REV(BL_RDWD_FRM_BYTEP(iv))); + iv+=4; + */ + BL_WR_REG(regionRegBase, SF_CTRL_SF_AES_IV_W0, addrOffset); + iv += 4; + } } #endif /****************************************************************************/ /** - * @brief Serial flash controller set AES iv with big endian - * - * @param region: region number - * @param iv: iv data pointer - * @param addrOffset: flash address offset - * - * @return None - * -*******************************************************************************/ + * @brief Serial flash controller set AES iv with big endian + * + * @param region: region number + * @param iv: iv data pointer + * @param addrOffset: flash address offset + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Set_IV_BE(uint8_t region, uint8_t *iv, uint32_t addrOffset) -{ - /* Do flash key eco*/ - uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); - uint32_t tmpVal, i = 3; - - if (iv != NULL) { - tmpVal = SF_CTRL_SF_AES_IV_W0_OFFSET; - - while (i--) { - BL_WR_WORD(regionRegBase + tmpVal, BL_RDWD_FRM_BYTEP(iv)); - iv += 4; - tmpVal += 4; - } - - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W0,BL_RDWD_FRM_BYTEP(iv)); - iv+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W1,BL_RDWD_FRM_BYTEP(iv)); - iv+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W2,BL_RDWD_FRM_BYTEP(iv)); - iv+=4; - */ - BL_WR_REG(regionRegBase, SF_CTRL_SF_AES_IV_W3, __REV(addrOffset)); - iv += 4; +void ATTR_TCM_SECTION SF_Ctrl_AES_Set_IV_BE(uint8_t region, uint8_t *iv, uint32_t addrOffset) { + /* Do flash key eco*/ + uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); + uint32_t tmpVal, i = 3; + + if (iv != NULL) { + tmpVal = SF_CTRL_SF_AES_IV_W0_OFFSET; + + while (i--) { + BL_WR_WORD(regionRegBase + tmpVal, BL_RDWD_FRM_BYTEP(iv)); + iv += 4; + tmpVal += 4; } + + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W0,BL_RDWD_FRM_BYTEP(iv)); + iv+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W1,BL_RDWD_FRM_BYTEP(iv)); + iv+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W2,BL_RDWD_FRM_BYTEP(iv)); + iv+=4; + */ + BL_WR_REG(regionRegBase, SF_CTRL_SF_AES_IV_W3, __REV(addrOffset)); + iv += 4; + } } #endif /****************************************************************************/ /** - * @brief Enable serial flash controller AES - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Enable serial flash controller AES + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Enable(void) -{ - uint32_t tmpVal; +void ATTR_TCM_SECTION SF_Ctrl_AES_Enable(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_EN); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_EN); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); } #endif /****************************************************************************/ /** - * @brief Disable serial flash controller AES - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Disable serial flash controller AES + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Disable(void) -{ - uint32_t tmpVal; +void ATTR_TCM_SECTION SF_Ctrl_AES_Disable(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_EN); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_EN); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); } #endif /****************************************************************************/ /** - * @brief Check is serial flash controller AES enable - * - * @param None - * - * @return Wether AES is enable - * -*******************************************************************************/ + * @brief Check is serial flash controller AES enable + * + * @param None + * + * @return Wether AES is enable + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint8_t ATTR_TCM_SECTION SF_Ctrl_Is_AES_Enable(void) -{ - uint32_t tmpVal; +uint8_t ATTR_TCM_SECTION SF_Ctrl_Is_AES_Enable(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); - return BL_IS_REG_BIT_SET(tmpVal, SF_CTRL_SF_AES_EN); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); + return BL_IS_REG_BIT_SET(tmpVal, SF_CTRL_SF_AES_EN); } #endif /****************************************************************************/ /** - * @brief Set flash image offset - * - * @param addrOffset: Address offset value - * - * @return None - * -*******************************************************************************/ + * @brief Set flash image offset + * + * @param addrOffset: Address offset value + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Set_Flash_Image_Offset(uint32_t addrOffset) -{ - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET, addrOffset); -} +void ATTR_TCM_SECTION SF_Ctrl_Set_Flash_Image_Offset(uint32_t addrOffset) { BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET, addrOffset); } #endif /****************************************************************************/ /** - * @brief Get flash image offset - * - * @param None - * - * @return :Address offset value - * -*******************************************************************************/ + * @brief Get flash image offset + * + * @param None + * + * @return :Address offset value + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint32_t ATTR_TCM_SECTION SF_Ctrl_Get_Flash_Image_Offset(void) -{ - return BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET); -} +uint32_t ATTR_TCM_SECTION SF_Ctrl_Get_Flash_Image_Offset(void) { return BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET); } #endif /****************************************************************************/ /** - * @brief SF controller send one command - * - * @param sahbType: Serial flash controller clock sahb sram select - * - * @return None - * -*******************************************************************************/ + * @brief SF controller send one command + * + * @param sahbType: Serial flash controller clock sahb sram select + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Select_Clock(SF_Ctrl_Sahb_Type sahbType) -{ - uint32_t tmpVal = 0; +void ATTR_TCM_SECTION SF_Ctrl_Select_Clock(SF_Ctrl_Sahb_Type sahbType) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); - if (sahbType == SF_CTRL_SAHB_CLOCK) { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CLK_SAHB_SRAM_SEL); - } else if (sahbType == SF_CTRL_FLASH_CLOCK) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CLK_SAHB_SRAM_SEL); - } + if (sahbType == SF_CTRL_SAHB_CLOCK) { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CLK_SAHB_SRAM_SEL); + } else if (sahbType == SF_CTRL_FLASH_CLOCK) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CLK_SAHB_SRAM_SEL); + } - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); } #endif /****************************************************************************/ /** - * @brief SF controller send one command - * - * @param cfg: Serial flash controller command configuration pointer - * - * @return None - * -*******************************************************************************/ + * @brief SF controller send one command + * + * @param cfg: Serial flash controller command configuration pointer + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_SendCmd(SF_Ctrl_Cmd_Cfg_Type *cfg) -{ - uint32_t tmpVal = 0; - uint32_t timeOut = 0; +void ATTR_TCM_SECTION SF_Ctrl_SendCmd(SF_Ctrl_Cmd_Cfg_Type *cfg) { + uint32_t tmpVal = 0; + uint32_t timeOut = 0; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); - CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); - CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); - CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); + CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); + CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); + CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); - timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; + timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; - while (SET == SF_Ctrl_GetBusyState()) { - timeOut--; + while (SET == SF_Ctrl_GetBusyState()) { + timeOut--; - if (timeOut == 0) { - return; - } + if (timeOut == 0) { + return; } - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - - if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_SAHB) { - return; - } - - /* Clear trigger */ - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_TRIG); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0, tmpVal); - - /* Copy command buffer */ - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_1, cfg->cmdBuf[0]); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_2, cfg->cmdBuf[1]); - - /* Configure SPI and IO mode*/ - if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_QPI_MODE_EN, SF_CTRL_SPI_MODE); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_QPI_MODE_EN, SF_CTRL_QPI_MODE); - } - - if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { - if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_NIO_MODE); - } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_DO_MODE); - } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_QO_MODE); - } - } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_DIO_MODE); - } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_QIO_MODE); - } - - /* Configure cmd */ - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_CMD_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_CMD_BYTE, 0); - - /* Configure address */ - if (cfg->addrSize != 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_ADR_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_ADR_BYTE, cfg->addrSize - 1); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_ADR_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_ADR_BYTE, 0); - } - - /* Configure dummy */ - if (cfg->dummyClks != 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DMY_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DMY_BYTE, cfg->dummyClks - 1); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DMY_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DMY_BYTE, 0); + } + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + + if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_SAHB) { + return; + } + + /* Clear trigger */ + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_TRIG); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0, tmpVal); + + /* Copy command buffer */ + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_1, cfg->cmdBuf[0]); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_2, cfg->cmdBuf[1]); + + /* Configure SPI and IO mode*/ + if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_QPI_MODE_EN, SF_CTRL_SPI_MODE); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_QPI_MODE_EN, SF_CTRL_QPI_MODE); + } + + if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { + if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_NIO_MODE); + } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_DO_MODE); + } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_QO_MODE); } - - /* Configure data */ - if (cfg->nbData != 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DAT_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DAT_BYTE, cfg->nbData - 1); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DAT_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DAT_BYTE, 0); - } - - /* Set read write flag */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DAT_RW, cfg->rwFlag); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0, tmpVal); - - //switch sf_clk_sahb_sram_sel = 1 - SF_Ctrl_Select_Clock(SF_CTRL_FLASH_CLOCK); - /* Trigger */ - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_TRIG); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0, tmpVal); - - timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; - - while (SET == SF_Ctrl_GetBusyState()) { - timeOut--; - - if (timeOut == 0) { - SF_Ctrl_Select_Clock(SF_CTRL_SAHB_CLOCK); - return; - } + } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_DIO_MODE); + } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_QIO_MODE); + } + + /* Configure cmd */ + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_CMD_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_CMD_BYTE, 0); + + /* Configure address */ + if (cfg->addrSize != 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_ADR_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_ADR_BYTE, cfg->addrSize - 1); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_ADR_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_ADR_BYTE, 0); + } + + /* Configure dummy */ + if (cfg->dummyClks != 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DMY_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DMY_BYTE, cfg->dummyClks - 1); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DMY_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DMY_BYTE, 0); + } + + /* Configure data */ + if (cfg->nbData != 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DAT_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DAT_BYTE, cfg->nbData - 1); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DAT_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DAT_BYTE, 0); + } + + /* Set read write flag */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DAT_RW, cfg->rwFlag); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0, tmpVal); + + // switch sf_clk_sahb_sram_sel = 1 + SF_Ctrl_Select_Clock(SF_CTRL_FLASH_CLOCK); + /* Trigger */ + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_TRIG); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0, tmpVal); + + timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; + + while (SET == SF_Ctrl_GetBusyState()) { + timeOut--; + + if (timeOut == 0) { + SF_Ctrl_Select_Clock(SF_CTRL_SAHB_CLOCK); + return; } + } - //switch sf_clk_sahb_sram_sel = 0 - SF_Ctrl_Select_Clock(SF_CTRL_SAHB_CLOCK); + // switch sf_clk_sahb_sram_sel = 0 + SF_Ctrl_Select_Clock(SF_CTRL_SAHB_CLOCK); } #endif /****************************************************************************/ /** - * @brief Config SF controller for flash I/D cache read - * - * @param cfg: Serial flash controller command configuration pointer - * @param cmdValid: command valid or not, for continous read, cache may need no command - * - * @return None - * -*******************************************************************************/ + * @brief Config SF controller for flash I/D cache read + * + * @param cfg: Serial flash controller command configuration pointer + * @param cmdValid: command valid or not, for continous read, cache may need no command + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Flash_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) -{ - uint32_t tmpVal = 0; - uint32_t timeOut = 0; - - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); - CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); - CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); - CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); +void ATTR_TCM_SECTION SF_Ctrl_Flash_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) { + uint32_t tmpVal = 0; + uint32_t timeOut = 0; - timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); + CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); + CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); + CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); - while (SET == SF_Ctrl_GetBusyState()) { - timeOut--; + timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; - if (timeOut == 0) { - return; - } - } - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - - if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_IAHB) { - return; - } - - /* Copy command buffer */ - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_1, cfg->cmdBuf[0]); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_2, cfg->cmdBuf[1]); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_0); - - /* Configure SPI and IO mode*/ - if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_SPI_MODE); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_QPI_MODE); - } - - if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { - if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_NIO_MODE); - } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DO_MODE); - } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QO_MODE); - } - } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DIO_MODE); - } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QIO_MODE); - } - - if (cmdValid) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); - } + while (SET == SF_Ctrl_GetBusyState()) { + timeOut--; - /* Configure address */ - if (cfg->addrSize != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, cfg->addrSize - 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, 0); + if (timeOut == 0) { + return; } - - /* configure dummy */ - if (cfg->dummyClks != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, cfg->dummyClks - 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, 0); + } + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + + if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_IAHB) { + return; + } + + /* Copy command buffer */ + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_1, cfg->cmdBuf[0]); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_2, cfg->cmdBuf[1]); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_0); + + /* Configure SPI and IO mode*/ + if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_SPI_MODE); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_QPI_MODE); + } + + if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { + if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_NIO_MODE); + } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DO_MODE); + } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QO_MODE); } - - /* Configure data */ - if (cfg->nbData != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 0); - } - - /* Set read write flag */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_RW, cfg->rwFlag); - - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_0, tmpVal); + } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DIO_MODE); + } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QIO_MODE); + } + + if (cmdValid) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); + } + + /* Configure address */ + if (cfg->addrSize != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, cfg->addrSize - 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, 0); + } + + /* configure dummy */ + if (cfg->dummyClks != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, cfg->dummyClks - 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, 0); + } + + /* Configure data */ + if (cfg->nbData != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 0); + } + + /* Set read write flag */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_RW, cfg->rwFlag); + + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_0, tmpVal); } #endif /****************************************************************************/ /** - * @brief Config psram controller for psram I/D cache write - * - * @param cfg: Serial flash controller command configuration pointer - * @param cmdValid: command valid or not, cache may need no command - * - * @return None - * -*******************************************************************************/ + * @brief Config psram controller for psram I/D cache write + * + * @param cfg: Serial flash controller command configuration pointer + * @param cmdValid: command valid or not, cache may need no command + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Psram_Write_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) -{ - uint32_t tmpVal = 0; - uint32_t timeOut = 0; +void ATTR_TCM_SECTION SF_Ctrl_Psram_Write_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) { + uint32_t tmpVal = 0; + uint32_t timeOut = 0; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); - CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); - CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); - CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); + CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); + CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); + CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); - timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; + timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; - while (SET == SF_Ctrl_GetBusyState()) { - timeOut--; + while (SET == SF_Ctrl_GetBusyState()) { + timeOut--; - if (timeOut == 0) { - return; - } + if (timeOut == 0) { + return; } - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - - if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_IAHB) { - return; + } + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + + if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_IAHB) { + return; + } + + /* Copy command buffer */ + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_4, cfg->cmdBuf[0]); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_5, cfg->cmdBuf[1]); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_3); + + /* Configure SPI and IO mode*/ + if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_QPI_MODE_EN, SF_CTRL_SPI_MODE); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_QPI_MODE_EN, SF_CTRL_QPI_MODE); + } + + if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { + if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_NIO_MODE); + } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_DO_MODE); + } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_QO_MODE); } - - /* Copy command buffer */ - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_4, cfg->cmdBuf[0]); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_5, cfg->cmdBuf[1]); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_3); - - /* Configure SPI and IO mode*/ - if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_QPI_MODE_EN, SF_CTRL_SPI_MODE); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_QPI_MODE_EN, SF_CTRL_QPI_MODE); - } - - if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { - if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_NIO_MODE); - } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_DO_MODE); - } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_QO_MODE); - } - } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_DIO_MODE); - } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_QIO_MODE); - } - - if (cmdValid) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_BYTE, 0); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_BYTE, 0); - } - - /* Configure address */ - if (cfg->addrSize != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_BYTE, cfg->addrSize - 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_BYTE, 0); - } - - /* configure dummy */ - if (cfg->dummyClks != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_BYTE, cfg->dummyClks - 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_BYTE, 0); - } - - /* Configure data */ - if (cfg->nbData != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DAT_EN, 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DAT_EN, 0); - } - - /* Set read write flag */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DAT_RW, cfg->rwFlag); - - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_3, tmpVal); + } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_DIO_MODE); + } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_QIO_MODE); + } + + if (cmdValid) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_BYTE, 0); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_BYTE, 0); + } + + /* Configure address */ + if (cfg->addrSize != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_BYTE, cfg->addrSize - 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_BYTE, 0); + } + + /* configure dummy */ + if (cfg->dummyClks != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_BYTE, cfg->dummyClks - 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_BYTE, 0); + } + + /* Configure data */ + if (cfg->nbData != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DAT_EN, 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DAT_EN, 0); + } + + /* Set read write flag */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DAT_RW, cfg->rwFlag); + + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_3, tmpVal); } #endif /****************************************************************************/ /** - * @brief Config psram controller for psram I/D cache read - * - * @param cfg: Serial flash controller command configuration pointer - * @param cmdValid: command valid or not, for continous read, cache may need no command - * - * @return None - * -*******************************************************************************/ + * @brief Config psram controller for psram I/D cache read + * + * @param cfg: Serial flash controller command configuration pointer + * @param cmdValid: command valid or not, for continous read, cache may need no command + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Psram_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) -{ - uint32_t tmpVal = 0; - uint32_t timeOut = 0; +void ATTR_TCM_SECTION SF_Ctrl_Psram_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) { + uint32_t tmpVal = 0; + uint32_t timeOut = 0; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); - CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); - CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); - CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); + CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); + CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); + CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); - timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; + timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; - while (SET == SF_Ctrl_GetBusyState()) { - timeOut--; + while (SET == SF_Ctrl_GetBusyState()) { + timeOut--; - if (timeOut == 0) { - return; - } + if (timeOut == 0) { + return; } - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - - if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_IAHB) { - return; + } + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + + if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_IAHB) { + return; + } + + /* Copy command buffer */ + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_10, cfg->cmdBuf[0]); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_11, cfg->cmdBuf[1]); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_9); + + /* Configure SPI and IO mode*/ + if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_SPI_MODE); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_QPI_MODE); + } + + if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { + if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_NIO_MODE); + } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DO_MODE); + } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QO_MODE); } - - /* Copy command buffer */ - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_10, cfg->cmdBuf[0]); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_11, cfg->cmdBuf[1]); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_9); - - /* Configure SPI and IO mode*/ - if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_SPI_MODE); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_QPI_MODE); - } - - if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { - if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_NIO_MODE); - } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DO_MODE); - } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QO_MODE); - } - } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DIO_MODE); - } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QIO_MODE); - } - - if (cmdValid) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); - } - - /* Configure address */ - if (cfg->addrSize != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, cfg->addrSize - 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, 0); - } - - /* configure dummy */ - if (cfg->dummyClks != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, cfg->dummyClks - 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, 0); - } - - /* Configure data */ - if (cfg->nbData != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 0); - } - - /* Set read write flag */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_RW, cfg->rwFlag); - - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_9, tmpVal); + } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DIO_MODE); + } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QIO_MODE); + } + + if (cmdValid) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); + } + + /* Configure address */ + if (cfg->addrSize != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, cfg->addrSize - 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, 0); + } + + /* configure dummy */ + if (cfg->dummyClks != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, cfg->dummyClks - 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, 0); + } + + /* Configure data */ + if (cfg->nbData != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 0); + } + + /* Set read write flag */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_RW, cfg->rwFlag); + + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_9, tmpVal); } #endif /****************************************************************************/ /** - * @brief Get SF Ctrl busy state - * - * @param None - * - * @return SET for SF ctrl busy or RESET for SF ctrl not busy - * -*******************************************************************************/ + * @brief Get SF Ctrl busy state + * + * @param None + * + * @return SET for SF ctrl busy or RESET for SF ctrl not busy + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Sts_Type ATTR_TCM_SECTION SF_Ctrl_GetBusyState(void) -{ - uint32_t tmpVal; +BL_Sts_Type ATTR_TCM_SECTION SF_Ctrl_GetBusyState(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0); - if (BL_IS_REG_BIT_SET(tmpVal, SF_CTRL_SF_IF_BUSY)) { - return SET; - } else { - return RESET; - } + if (BL_IS_REG_BIT_SET(tmpVal, SF_CTRL_SF_IF_BUSY)) { + return SET; + } else { + return RESET; + } } #endif /****************************************************************************/ /** - * @brief SF Controller interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief SF Controller interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void SF_Ctrl_IRQHandler(void) -{ - /* TODO: Not implemented */ -} +void SF_Ctrl_IRQHandler(void) { /* TODO: Not implemented */ } #endif /*@} end of group SF_CTRL_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash.c index 81ec04b319..8639fcd43c 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash.c @@ -39,7 +39,6 @@ #include "bl702_sf_ctrl.h" #include "string.h" - /** @addtogroup BL702_Peripheral_Driver * @{ */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash_ext.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash_ext.c index fba509518e..ae19f0da84 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash_ext.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash_ext.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_sflash_ext.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2019 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_sflash_ext.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2019 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_sflash_ext.h" #include "bl702_sf_ctrl.h" @@ -87,184 +87,179 @@ */ /****************************************************************************/ /** - * @brief KH25V40 flash write protect set - * - * @param flashCfg: Serial flash parameter configuration pointer - * @param protect: protect area - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief KH25V40 flash write protect set + * + * @param flashCfg: Serial flash parameter configuration pointer + * @param protect: protect area + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ __WEAK -BL_Err_Type ATTR_TCM_SECTION SFlash_KH25V40_Write_Protect(SPI_Flash_Cfg_Type *flashCfg, SFlash_Protect_Kh25v40_Type protect) -{ - uint32_t stat = 0, ret; +BL_Err_Type ATTR_TCM_SECTION SFlash_KH25V40_Write_Protect(SPI_Flash_Cfg_Type *flashCfg, SFlash_Protect_Kh25v40_Type protect) { + uint32_t stat = 0, ret; - SFlash_Read_Reg(flashCfg, 0, (uint8_t *)&stat, 1); - if (((stat >> 2) & 0xf) == protect) { - return SUCCESS; - } + SFlash_Read_Reg(flashCfg, 0, (uint8_t *)&stat, 1); + if (((stat >> 2) & 0xf) == protect) { + return SUCCESS; + } - stat |= ((protect << 2) & 0xff); + stat |= ((protect << 2) & 0xff); - ret = SFlash_Write_Enable(flashCfg); - if (SUCCESS != ret) { - return ERROR; - } + ret = SFlash_Write_Enable(flashCfg); + if (SUCCESS != ret) { + return ERROR; + } - SFlash_Write_Reg(flashCfg, 0, (uint8_t *)&stat, 1); - SFlash_Read_Reg(flashCfg, 0, (uint8_t *)&stat, 1); - if (((stat >> 2) & 0xf) == protect) { - return SUCCESS; - } + SFlash_Write_Reg(flashCfg, 0, (uint8_t *)&stat, 1); + SFlash_Read_Reg(flashCfg, 0, (uint8_t *)&stat, 1); + if (((stat >> 2) & 0xf) == protect) { + return SUCCESS; + } - return ERROR; + return ERROR; } /****************************************************************************/ /** - * @brief Read flash register with read command - * - * @param flashCfg: Serial flash parameter configuration pointer - * @param readRegCmd: read command - * @param regValue: register value pointer to store data - * @param regLen: register value length - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Read flash register with read command + * + * @param flashCfg: Serial flash parameter configuration pointer + * @param readRegCmd: read command + * @param regValue: register value pointer to store data + * @param regLen: register value length + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ __WEAK -BL_Err_Type ATTR_TCM_SECTION SFlash_Read_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t readRegCmd, uint8_t *regValue, uint8_t regLen) -{ - uint8_t *const flashCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; - SF_Ctrl_Cmd_Cfg_Type flashCmd; - uint32_t cnt = 0; - - if (((uint32_t)&flashCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&flashCmd, 0, sizeof(flashCmd) / 4); - } else { - BL702_MemSet(&flashCmd, 0, sizeof(flashCmd)); - } +BL_Err_Type ATTR_TCM_SECTION SFlash_Read_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t readRegCmd, uint8_t *regValue, uint8_t regLen) { + uint8_t *const flashCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; + SF_Ctrl_Cmd_Cfg_Type flashCmd; + uint32_t cnt = 0; + + if (((uint32_t)&flashCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&flashCmd, 0, sizeof(flashCmd) / 4); + } else { + BL702_MemSet(&flashCmd, 0, sizeof(flashCmd)); + } - flashCmd.cmdBuf[0] = readRegCmd << 24; - flashCmd.rwFlag = SF_CTRL_READ; - flashCmd.nbData = regLen; + flashCmd.cmdBuf[0] = readRegCmd << 24; + flashCmd.rwFlag = SF_CTRL_READ; + flashCmd.nbData = regLen; - SF_Ctrl_SendCmd(&flashCmd); + SF_Ctrl_SendCmd(&flashCmd); - while (SET == SF_Ctrl_GetBusyState()) { - BL702_Delay_US(1); - cnt++; + while (SET == SF_Ctrl_GetBusyState()) { + BL702_Delay_US(1); + cnt++; - if (cnt > 1000) { - return ERROR; - } + if (cnt > 1000) { + return ERROR; } + } - BL702_MemCpy(regValue, flashCtrlBuf, regLen); - return SUCCESS; + BL702_MemCpy(regValue, flashCtrlBuf, regLen); + return SUCCESS; } /****************************************************************************/ /** - * @brief Write flash register with write command - * - * @param flashCfg: Serial flash parameter configuration pointer - * @param writeRegCmd: write command - * @param regValue: register value pointer storing data - * @param regLen: register value length - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Write flash register with write command + * + * @param flashCfg: Serial flash parameter configuration pointer + * @param writeRegCmd: write command + * @param regValue: register value pointer storing data + * @param regLen: register value length + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ __WEAK -BL_Err_Type ATTR_TCM_SECTION SFlash_Write_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t writeRegCmd, uint8_t *regValue, uint8_t regLen) -{ - uint8_t *const flashCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; - uint32_t cnt = 0; - SF_Ctrl_Cmd_Cfg_Type flashCmd; - - if (((uint32_t)&flashCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&flashCmd, 0, sizeof(flashCmd) / 4); - } else { - BL702_MemSet(&flashCmd, 0, sizeof(flashCmd)); - } +BL_Err_Type ATTR_TCM_SECTION SFlash_Write_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t writeRegCmd, uint8_t *regValue, uint8_t regLen) { + uint8_t *const flashCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; + uint32_t cnt = 0; + SF_Ctrl_Cmd_Cfg_Type flashCmd; - BL702_MemCpy(flashCtrlBuf, regValue, regLen); + if (((uint32_t)&flashCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&flashCmd, 0, sizeof(flashCmd) / 4); + } else { + BL702_MemSet(&flashCmd, 0, sizeof(flashCmd)); + } - flashCmd.cmdBuf[0] = writeRegCmd << 24; - flashCmd.rwFlag = SF_CTRL_WRITE; - flashCmd.nbData = regLen; + BL702_MemCpy(flashCtrlBuf, regValue, regLen); - SF_Ctrl_SendCmd(&flashCmd); + flashCmd.cmdBuf[0] = writeRegCmd << 24; + flashCmd.rwFlag = SF_CTRL_WRITE; + flashCmd.nbData = regLen; - /* take 40ms for tw(write status register) as default */ - while (SET == SFlash_Busy(flashCfg)) { - BL702_Delay_US(100); - cnt++; + SF_Ctrl_SendCmd(&flashCmd); - if (cnt > 400) { - return ERROR; - } + /* take 40ms for tw(write status register) as default */ + while (SET == SFlash_Busy(flashCfg)) { + BL702_Delay_US(100); + cnt++; + + if (cnt > 400) { + return ERROR; } + } - return SUCCESS; + return SUCCESS; } -/****************************************************************************//** - * @brief Clear flash status register - * - * @param pFlashCfg: Flash configuration pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION SFlash_Clear_Status_Register(SPI_Flash_Cfg_Type *pFlashCfg) -{ - uint32_t ret = 0; - uint32_t qeValue = 0; - uint32_t regValue = 0; - uint32_t readValue = 0; - uint8_t readRegValue0 = 0; - uint8_t readRegValue1 = 0; - - if((pFlashCfg->ioMode&0xf)==SF_CTRL_QO_MODE || (pFlashCfg->ioMode&0xf)==SF_CTRL_QIO_MODE){ - qeValue = 1; - } +/****************************************************************************/ /** + * @brief Clear flash status register + * + * @param pFlashCfg: Flash configuration pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION SFlash_Clear_Status_Register(SPI_Flash_Cfg_Type *pFlashCfg) { + uint32_t ret = 0; + uint32_t qeValue = 0; + uint32_t regValue = 0; + uint32_t readValue = 0; + uint8_t readRegValue0 = 0; + uint8_t readRegValue1 = 0; + + if ((pFlashCfg->ioMode & 0xf) == SF_CTRL_QO_MODE || (pFlashCfg->ioMode & 0xf) == SF_CTRL_QIO_MODE) { + qeValue = 1; + } + + SFlash_Read_Reg(pFlashCfg, 0, (uint8_t *)&readRegValue0, 1); + SFlash_Read_Reg(pFlashCfg, 1, (uint8_t *)&readRegValue1, 1); + readValue = (readRegValue0 | (readRegValue1 << 8)); + if ((readValue & (~((1 << (pFlashCfg->qeIndex * 8 + pFlashCfg->qeBit)) | (1 << (pFlashCfg->busyIndex * 8 + pFlashCfg->busyBit)) | (1 << (pFlashCfg->wrEnableIndex * 8 + pFlashCfg->wrEnableBit))))) + == 0) { + return SUCCESS; + } - SFlash_Read_Reg(pFlashCfg, 0, (uint8_t *)&readRegValue0, 1); - SFlash_Read_Reg(pFlashCfg, 1, (uint8_t *)&readRegValue1, 1); - readValue = (readRegValue0|(readRegValue1<<8)); - if ((readValue & (~((1<<(pFlashCfg->qeIndex*8+pFlashCfg->qeBit)) | - (1<<(pFlashCfg->busyIndex*8+pFlashCfg->busyBit)) | - (1<<(pFlashCfg->wrEnableIndex*8+pFlashCfg->wrEnableBit))))) == 0){ - return SUCCESS; + ret = SFlash_Write_Enable(pFlashCfg); + if (SUCCESS != ret) { + return ERROR; + } + if (pFlashCfg->qeWriteRegLen == 2) { + regValue = (qeValue << (pFlashCfg->qeIndex * 8 + pFlashCfg->qeBit)); + SFlash_Write_Reg(pFlashCfg, 0, (uint8_t *)®Value, 2); + } else { + if (pFlashCfg->qeIndex == 0) { + regValue = (qeValue << pFlashCfg->qeBit); + } else { + regValue = 0; } - + SFlash_Write_Reg(pFlashCfg, 0, (uint8_t *)®Value, 1); ret = SFlash_Write_Enable(pFlashCfg); if (SUCCESS != ret) { - return ERROR; + return ERROR; } - if (pFlashCfg->qeWriteRegLen == 2) { - regValue = (qeValue<<(pFlashCfg->qeIndex*8+pFlashCfg->qeBit)); - SFlash_Write_Reg(pFlashCfg, 0, (uint8_t *)®Value, 2); + if (pFlashCfg->qeIndex == 1) { + regValue = (qeValue << pFlashCfg->qeBit); } else { - if (pFlashCfg->qeIndex == 0) { - regValue = (qeValue<qeBit); - } else { - regValue = 0; - } - SFlash_Write_Reg(pFlashCfg, 0, (uint8_t *)®Value, 1); - ret = SFlash_Write_Enable(pFlashCfg); - if (SUCCESS != ret) { - return ERROR; - } - if (pFlashCfg->qeIndex == 1) { - regValue = (qeValue<qeBit); - } else { - regValue = 0; - } - SFlash_Write_Reg(pFlashCfg, 1, (uint8_t *)®Value, 1); + regValue = 0; } - return SUCCESS; + SFlash_Write_Reg(pFlashCfg, 1, (uint8_t *)®Value, 1); + } + return SUCCESS; } /*@} end of group SFLASH_EXT_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_spi.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_spi.c index f831aaeda6..69a6e14ec7 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_spi.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_spi.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_spi.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_spi.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_spi.h" #include "bl702_glb.h" @@ -62,10 +62,8 @@ /** @defgroup SPI_Private_Variables * @{ */ -static const uint32_t spiAddr[SPI_ID_MAX] = { SPI_BASE }; -static intCallback_Type *spiIntCbfArra[SPI_ID_MAX][SPI_INT_ALL] = { - { NULL } -}; +static const uint32_t spiAddr[SPI_ID_MAX] = {SPI_BASE}; +static intCallback_Type *spiIntCbfArra[SPI_ID_MAX][SPI_INT_ALL] = {{NULL}}; /*@} end of group SPI_Private_Variables */ @@ -89,70 +87,69 @@ static void SPI_IntHandler(SPI_ID_Type spiNo); */ /****************************************************************************/ /** - * @brief SPI interrupt common handler function - * - * @param spiNo: SPI ID type - * - * @return None - * -*******************************************************************************/ + * @brief SPI interrupt common handler function + * + * @param spiNo: SPI ID type + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -static void SPI_IntHandler(SPI_ID_Type spiNo) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; +static void SPI_IntHandler(SPI_ID_Type spiNo) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); + tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); - /* Transfer end interrupt,shared by both master and slave mode */ - if (BL_IS_REG_BIT_SET(tmpVal, SPI_END_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_END_MASK)) { - BL_WR_REG(SPIx, SPI_INT_STS, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_END_CLR)); + /* Transfer end interrupt,shared by both master and slave mode */ + if (BL_IS_REG_BIT_SET(tmpVal, SPI_END_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_END_MASK)) { + BL_WR_REG(SPIx, SPI_INT_STS, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_END_CLR)); - if (spiIntCbfArra[spiNo][SPI_INT_END] != NULL) { - spiIntCbfArra[spiNo][SPI_INT_END](); - } + if (spiIntCbfArra[spiNo][SPI_INT_END] != NULL) { + spiIntCbfArra[spiNo][SPI_INT_END](); } + } - /* TX fifo ready interrupt(fifo count > fifo threshold) */ - if (BL_IS_REG_BIT_SET(tmpVal, SPI_TXF_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_TXF_MASK)) { - if (spiIntCbfArra[spiNo][SPI_INT_TX_FIFO_REQ] != NULL) { - spiIntCbfArra[spiNo][SPI_INT_TX_FIFO_REQ](); - } + /* TX fifo ready interrupt(fifo count > fifo threshold) */ + if (BL_IS_REG_BIT_SET(tmpVal, SPI_TXF_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_TXF_MASK)) { + if (spiIntCbfArra[spiNo][SPI_INT_TX_FIFO_REQ] != NULL) { + spiIntCbfArra[spiNo][SPI_INT_TX_FIFO_REQ](); } + } - /* RX fifo ready interrupt(fifo count > fifo threshold) */ - if (BL_IS_REG_BIT_SET(tmpVal, SPI_RXF_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_RXF_MASK)) { - if (spiIntCbfArra[spiNo][SPI_INT_RX_FIFO_REQ] != NULL) { - spiIntCbfArra[spiNo][SPI_INT_RX_FIFO_REQ](); - } + /* RX fifo ready interrupt(fifo count > fifo threshold) */ + if (BL_IS_REG_BIT_SET(tmpVal, SPI_RXF_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_RXF_MASK)) { + if (spiIntCbfArra[spiNo][SPI_INT_RX_FIFO_REQ] != NULL) { + spiIntCbfArra[spiNo][SPI_INT_RX_FIFO_REQ](); } + } - /* Slave mode transfer time-out interrupt,triggered when bus is idle for the given value */ - if (BL_IS_REG_BIT_SET(tmpVal, SPI_STO_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_STO_MASK)) { - BL_WR_REG(SPIx, SPI_INT_STS, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_STO_CLR)); + /* Slave mode transfer time-out interrupt,triggered when bus is idle for the given value */ + if (BL_IS_REG_BIT_SET(tmpVal, SPI_STO_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_STO_MASK)) { + BL_WR_REG(SPIx, SPI_INT_STS, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_STO_CLR)); - if (spiIntCbfArra[spiNo][SPI_INT_SLAVE_TIMEOUT] != NULL) { - spiIntCbfArra[spiNo][SPI_INT_SLAVE_TIMEOUT](); - } + if (spiIntCbfArra[spiNo][SPI_INT_SLAVE_TIMEOUT] != NULL) { + spiIntCbfArra[spiNo][SPI_INT_SLAVE_TIMEOUT](); } + } - /* Slave mode tx underrun error interrupt,trigged when tx is not ready during transfer */ - if (BL_IS_REG_BIT_SET(tmpVal, SPI_TXU_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_TXU_MASK)) { - BL_WR_REG(SPIx, SPI_INT_STS, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_TXU_CLR)); + /* Slave mode tx underrun error interrupt,trigged when tx is not ready during transfer */ + if (BL_IS_REG_BIT_SET(tmpVal, SPI_TXU_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_TXU_MASK)) { + BL_WR_REG(SPIx, SPI_INT_STS, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_TXU_CLR)); - if (spiIntCbfArra[spiNo][SPI_INT_SLAVE_UNDERRUN] != NULL) { - spiIntCbfArra[spiNo][SPI_INT_SLAVE_UNDERRUN](); - } + if (spiIntCbfArra[spiNo][SPI_INT_SLAVE_UNDERRUN] != NULL) { + spiIntCbfArra[spiNo][SPI_INT_SLAVE_UNDERRUN](); } + } - /* TX/RX fifo overflow/underflow interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, SPI_FER_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_FER_MASK)) { - if (spiIntCbfArra[spiNo][SPI_INT_FIFO_ERROR] != NULL) { - spiIntCbfArra[spiNo][SPI_INT_FIFO_ERROR](); - } + /* TX/RX fifo overflow/underflow interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, SPI_FER_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_FER_MASK)) { + if (spiIntCbfArra[spiNo][SPI_INT_FIFO_ERROR] != NULL) { + spiIntCbfArra[spiNo][SPI_INT_FIFO_ERROR](); } + } } #endif @@ -163,1645 +160,1607 @@ static void SPI_IntHandler(SPI_ID_Type spiNo) */ /****************************************************************************/ /** - * @brief SPI initialization function - * - * @param spiNo: SPI ID type - * @param spiCfg: SPI configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Init(SPI_ID_Type spiNo, SPI_CFG_Type *spiCfg) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_WORK_MODE_TYPE(spiCfg->mod)); - CHECK_PARAM(IS_SPI_BYTE_INVERSE_TYPE(spiCfg->byteSequence)); - CHECK_PARAM(IS_SPI_BIT_INVERSE_TYPE(spiCfg->bitSequence)); - CHECK_PARAM(IS_SPI_CLK_PHASE_INVERSE_TYPE(spiCfg->clkPhaseInv)); - CHECK_PARAM(IS_SPI_CLK_POLARITY_TYPE(spiCfg->clkPolarity)); - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_SPI); - - /* spi config */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_DEG_EN, spiCfg->deglitchEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_M_CONT_EN, spiCfg->continuousEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_BYTE_INV, spiCfg->byteSequence); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_BIT_INV, spiCfg->bitSequence); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_SCLK_PH, (spiCfg->clkPhaseInv + 1) & 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_SCLK_POL, spiCfg->clkPolarity); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, spiCfg->frameSize); - BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); + * @brief SPI initialization function + * + * @param spiNo: SPI ID type + * @param spiCfg: SPI configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Init(SPI_ID_Type spiNo, SPI_CFG_Type *spiCfg) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_WORK_MODE_TYPE(spiCfg->mod)); + CHECK_PARAM(IS_SPI_BYTE_INVERSE_TYPE(spiCfg->byteSequence)); + CHECK_PARAM(IS_SPI_BIT_INVERSE_TYPE(spiCfg->bitSequence)); + CHECK_PARAM(IS_SPI_CLK_PHASE_INVERSE_TYPE(spiCfg->clkPhaseInv)); + CHECK_PARAM(IS_SPI_CLK_POLARITY_TYPE(spiCfg->clkPolarity)); + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_SPI); + + /* spi config */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_DEG_EN, spiCfg->deglitchEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_M_CONT_EN, spiCfg->continuousEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_BYTE_INV, spiCfg->byteSequence); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_BIT_INV, spiCfg->bitSequence); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_SCLK_PH, (spiCfg->clkPhaseInv + 1) & 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_SCLK_POL, spiCfg->clkPolarity); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, spiCfg->frameSize); + BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SPI_IRQn, SPI_IRQHandler); + Interrupt_Handler_Register(SPI_IRQn, SPI_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI set default value of all registers function - * - * @param spiNo: SPI ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_DeInit(SPI_ID_Type spiNo) -{ - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - if (SPI_ID_0 == spiNo) { - GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_SPI); - } - - return SUCCESS; + * @brief SPI set default value of all registers function + * + * @param spiNo: SPI ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_DeInit(SPI_ID_Type spiNo) { + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + if (SPI_ID_0 == spiNo) { + GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_SPI); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief Length of data phase1/0,start/stop condition and interval between frame initialization - * function - * - * @param spiNo: SPI ID type - * @param clockCfg: Clock configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_ClockConfig(SPI_ID_Type spiNo, SPI_ClockCfg_Type *clockCfg) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Configure length of data phase1/0 and start/stop condition */ - tmpVal = BL_RD_REG(SPIx, SPI_PRD_0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_S, clockCfg->startLen - 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_P, clockCfg->stopLen - 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_0, clockCfg->dataPhase0Len - 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_1, clockCfg->dataPhase1Len - 1); - BL_WR_REG(SPIx, SPI_PRD_0, tmpVal); - - /* Configure length of interval between frame */ - tmpVal = BL_RD_REG(SPIx, SPI_PRD_1); - BL_WR_REG(SPIx, SPI_PRD_1, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_I, clockCfg->intervalLen - 1)); - - return SUCCESS; + * @brief Length of data phase1/0,start/stop condition and interval between frame initialization + * function + * + * @param spiNo: SPI ID type + * @param clockCfg: Clock configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_ClockConfig(SPI_ID_Type spiNo, SPI_ClockCfg_Type *clockCfg) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Configure length of data phase1/0 and start/stop condition */ + tmpVal = BL_RD_REG(SPIx, SPI_PRD_0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_S, clockCfg->startLen - 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_P, clockCfg->stopLen - 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_0, clockCfg->dataPhase0Len - 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_1, clockCfg->dataPhase1Len - 1); + BL_WR_REG(SPIx, SPI_PRD_0, tmpVal); + + /* Configure length of interval between frame */ + tmpVal = BL_RD_REG(SPIx, SPI_PRD_1); + BL_WR_REG(SPIx, SPI_PRD_1, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_I, clockCfg->intervalLen - 1)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI configure fifo function - * - * @param spiNo: SPI ID type - * @param fifoCfg: FIFO configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_FifoConfig(SPI_ID_Type spiNo, SPI_FifoCfg_Type *fifoCfg) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Set fifo threshold value */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_TX_FIFO_TH, fifoCfg->txFifoThreshold); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_RX_FIFO_TH, fifoCfg->rxFifoThreshold); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_1, tmpVal); - - /* Enable or disable dma function */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_DMA_TX_EN, fifoCfg->txFifoDmaEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_DMA_RX_EN, fifoCfg->rxFifoDmaEnable); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - return SUCCESS; + * @brief SPI configure fifo function + * + * @param spiNo: SPI ID type + * @param fifoCfg: FIFO configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_FifoConfig(SPI_ID_Type spiNo, SPI_FifoCfg_Type *fifoCfg) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Set fifo threshold value */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_TX_FIFO_TH, fifoCfg->txFifoThreshold); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_RX_FIFO_TH, fifoCfg->rxFifoThreshold); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_1, tmpVal); + + /* Enable or disable dma function */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_DMA_TX_EN, fifoCfg->txFifoDmaEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_DMA_RX_EN, fifoCfg->rxFifoDmaEnable); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Set SPI SCK Clcok - * - * @param spiNo: SPI ID type - * @param clk: Clk - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SetClock(SPI_ID_Type spiNo, uint32_t clk) -{ - uint32_t glb_div = 1, spi_div = 1; - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - if(clk > 36000000) { - clk = 36000000; - glb_div = 1; - spi_div = 1; - } else if(clk > 140625) { - glb_div = 1; - spi_div = 36000000 / clk; - } else if(clk > 70312) { - glb_div = 2; - spi_div = 18000000 / clk; - } else if(clk > 35156) { - glb_div = 4; - spi_div = 9000000 / clk; - } else if(clk > 4394) { - glb_div = 32; - spi_div = 1125000 / clk; - } else { - glb_div = 32; - spi_div = 256; - } - - /* Configure length of data phase1/0 and start/stop condition */ - tmpVal = BL_RD_REG(SPIx, SPI_PRD_0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_S, spi_div - 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_P, spi_div - 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_0, spi_div - 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_1, spi_div - 1); - BL_WR_REG(SPIx, SPI_PRD_0, tmpVal); - - tmpVal = BL_RD_REG(SPIx, SPI_PRD_1); - BL_WR_REG(SPIx, SPI_PRD_1, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_I, spi_div - 1)); - - GLB_Set_SPI_CLK(ENABLE, glb_div - 1); - - return SUCCESS; + * @brief Set SPI SCK Clcok + * + * @param spiNo: SPI ID type + * @param clk: Clk + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SetClock(SPI_ID_Type spiNo, uint32_t clk) { + uint32_t glb_div = 1, spi_div = 1; + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + if (clk > 36000000) { + clk = 36000000; + glb_div = 1; + spi_div = 1; + } else if (clk > 140625) { + glb_div = 1; + spi_div = 36000000 / clk; + } else if (clk > 70312) { + glb_div = 2; + spi_div = 18000000 / clk; + } else if (clk > 35156) { + glb_div = 4; + spi_div = 9000000 / clk; + } else if (clk > 4394) { + glb_div = 32; + spi_div = 1125000 / clk; + } else { + glb_div = 32; + spi_div = 256; + } + + /* Configure length of data phase1/0 and start/stop condition */ + tmpVal = BL_RD_REG(SPIx, SPI_PRD_0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_S, spi_div - 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_P, spi_div - 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_0, spi_div - 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_1, spi_div - 1); + BL_WR_REG(SPIx, SPI_PRD_0, tmpVal); + + tmpVal = BL_RD_REG(SPIx, SPI_PRD_1); + BL_WR_REG(SPIx, SPI_PRD_1, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_I, spi_div - 1)); + + GLB_Set_SPI_CLK(ENABLE, glb_div - 1); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Enable spi transfer - * - * @param spiNo: SPI ID type - * @param modeType: Master or slave mode select - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Enable(SPI_ID_Type spiNo, SPI_WORK_MODE_Type modeType) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_WORK_MODE_TYPE(modeType)); - - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - - if (modeType != SPI_WORK_MODE_SLAVE) { - /* master mode */ - tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_S_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_M_EN); - } else { - /* slave mode */ - tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_M_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_S_EN); - } + * @brief Enable spi transfer + * + * @param spiNo: SPI ID type + * @param modeType: Master or slave mode select + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Enable(SPI_ID_Type spiNo, SPI_WORK_MODE_Type modeType) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_WORK_MODE_TYPE(modeType)); + + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + + if (modeType != SPI_WORK_MODE_SLAVE) { + /* master mode */ + tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_S_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_M_EN); + } else { + /* slave mode */ + tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_M_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_S_EN); + } - BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); + BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Disable spi transfer - * - * @param spiNo: SPI ID type - * @param modeType: Master or slave mode select - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Disable(SPI_ID_Type spiNo, SPI_WORK_MODE_Type modeType) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_WORK_MODE_TYPE(modeType)); - - /* close master and slave */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_M_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_S_EN); - BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); - - return SUCCESS; + * @brief Disable spi transfer + * + * @param spiNo: SPI ID type + * @param modeType: Master or slave mode select + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Disable(SPI_ID_Type spiNo, SPI_WORK_MODE_Type modeType) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_WORK_MODE_TYPE(modeType)); + + /* close master and slave */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_M_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_S_EN); + BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Set time-out value to trigger interrupt when spi bus is idle for the given value - * - * @param spiNo: SPI ID type - * @param value: Time value - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SetTimeOutValue(SPI_ID_Type spiNo, uint16_t value) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Set time-out value */ - tmpVal = BL_RD_REG(SPIx, SPI_STO_VALUE); - BL_WR_REG(SPIx, SPI_STO_VALUE, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_STO_VALUE, value - 1)); - - return SUCCESS; + * @brief Set time-out value to trigger interrupt when spi bus is idle for the given value + * + * @param spiNo: SPI ID type + * @param value: Time value + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SetTimeOutValue(SPI_ID_Type spiNo, uint16_t value) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Set time-out value */ + tmpVal = BL_RD_REG(SPIx, SPI_STO_VALUE); + BL_WR_REG(SPIx, SPI_STO_VALUE, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_STO_VALUE, value - 1)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Set de-glitch function cycle count value - * - * @param spiNo: SPI ID type - * @param cnt: De-glitch function cycle count - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SetDeglitchCount(SPI_ID_Type spiNo, uint8_t cnt) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Set count value */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_DEG_CNT, cnt); - BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); - - return SUCCESS; + * @brief Set de-glitch function cycle count value + * + * @param spiNo: SPI ID type + * @param cnt: De-glitch function cycle count + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SetDeglitchCount(SPI_ID_Type spiNo, uint8_t cnt) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Set count value */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_DEG_CNT, cnt); + BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Enable rx data ignore function and set start/stop point - * - * @param spiNo: SPI ID type - * @param startPoint: Start point - * @param stopPoint: Stop point - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_RxIgnoreEnable(SPI_ID_Type spiNo, uint8_t startPoint, uint8_t stopPoint) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Enable rx ignore function */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Set start and stop point */ - tmpVal = startPoint << SPI_CR_SPI_RXD_IGNR_S_POS | stopPoint; - BL_WR_REG(SPIx, SPI_RXD_IGNR, tmpVal); - - return SUCCESS; + * @brief Enable rx data ignore function and set start/stop point + * + * @param spiNo: SPI ID type + * @param startPoint: Start point + * @param stopPoint: Stop point + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_RxIgnoreEnable(SPI_ID_Type spiNo, uint8_t startPoint, uint8_t stopPoint) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Enable rx ignore function */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Set start and stop point */ + tmpVal = startPoint << SPI_CR_SPI_RXD_IGNR_S_POS | stopPoint; + BL_WR_REG(SPIx, SPI_RXD_IGNR, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Disable rx data ignore function - * - * @param spiNo: SPI ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_RxIgnoreDisable(SPI_ID_Type spiNo) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Disable rx ignore function */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - return SUCCESS; + * @brief Disable rx data ignore function + * + * @param spiNo: SPI ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_RxIgnoreDisable(SPI_ID_Type spiNo) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Disable rx ignore function */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Clear tx fifo and tx fifo overflow/underflow status - * - * @param spiNo: SPI ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_ClrTxFifo(SPI_ID_Type spiNo) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Clear tx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR)); - - return SUCCESS; + * @brief Clear tx fifo and tx fifo overflow/underflow status + * + * @param spiNo: SPI ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_ClrTxFifo(SPI_ID_Type spiNo) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Clear tx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Clear rx fifo and rx fifo overflow/underflow status - * - * @param spiNo: SPI ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_ClrRxFifo(SPI_ID_Type spiNo) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Clear rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR)); - - return SUCCESS; + * @brief Clear rx fifo and rx fifo overflow/underflow status + * + * @param spiNo: SPI ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_ClrRxFifo(SPI_ID_Type spiNo) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Clear rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Clear spi interrupt status - * - * @param spiNo: SPI ID type - * @param intType: SPI interrupt type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_ClrIntStatus(SPI_ID_Type spiNo, SPI_INT_Type intType) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Clear certain or all interrupt */ - tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); - - if (SPI_INT_ALL == intType) { - tmpVal |= 0x1f << SPI_CR_SPI_END_CLR_POS; - } else { - tmpVal |= 1 << (intType + SPI_CR_SPI_END_CLR_POS); - } - - BL_WR_REG(SPIx, SPI_INT_STS, tmpVal); - - return SUCCESS; + * @brief Clear spi interrupt status + * + * @param spiNo: SPI ID type + * @param intType: SPI interrupt type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_ClrIntStatus(SPI_ID_Type spiNo, SPI_INT_Type intType) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Clear certain or all interrupt */ + tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); + + if (SPI_INT_ALL == intType) { + tmpVal |= 0x1f << SPI_CR_SPI_END_CLR_POS; + } else { + tmpVal |= 1 << (intType + SPI_CR_SPI_END_CLR_POS); + } + + BL_WR_REG(SPIx, SPI_INT_STS, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI mask or unmask certain or all interrupt - * - * @param spiNo: SPI ID type - * @param intType: SPI interrupt type - * @param intMask: SPI interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_IntMask(SPI_ID_Type spiNo, SPI_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_INT_TYPE(intType)); - CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); - - tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); - - /* Mask or unmask certain or all interrupt */ - if (SPI_INT_ALL == intType) { - if (MASK == intMask) { - tmpVal |= 0x3f << SPI_CR_SPI_END_MASK_POS; - } else { - tmpVal &= ~(0x3f << SPI_CR_SPI_END_MASK_POS); - } + * @brief SPI mask or unmask certain or all interrupt + * + * @param spiNo: SPI ID type + * @param intType: SPI interrupt type + * @param intMask: SPI interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_IntMask(SPI_ID_Type spiNo, SPI_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_INT_TYPE(intType)); + CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); + + tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); + + /* Mask or unmask certain or all interrupt */ + if (SPI_INT_ALL == intType) { + if (MASK == intMask) { + tmpVal |= 0x3f << SPI_CR_SPI_END_MASK_POS; } else { - if (MASK == intMask) { - tmpVal |= 1 << (intType + SPI_CR_SPI_END_MASK_POS); - } else { - tmpVal &= ~(1 << (intType + SPI_CR_SPI_END_MASK_POS)); - } + tmpVal &= ~(0x3f << SPI_CR_SPI_END_MASK_POS); + } + } else { + if (MASK == intMask) { + tmpVal |= 1 << (intType + SPI_CR_SPI_END_MASK_POS); + } else { + tmpVal &= ~(1 << (intType + SPI_CR_SPI_END_MASK_POS)); } + } - /* Write back */ - BL_WR_REG(SPIx, SPI_INT_STS, tmpVal); + /* Write back */ + BL_WR_REG(SPIx, SPI_INT_STS, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Install spi interrupt callback function - * - * @param spiNo: SPI ID type - * @param intType: SPI interrupt type - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Int_Callback_Install(SPI_ID_Type spiNo, SPI_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_INT_TYPE(intType)); - - spiIntCbfArra[spiNo][intType] = cbFun; - - return SUCCESS; + * @brief Install spi interrupt callback function + * + * @param spiNo: SPI ID type + * @param intType: SPI interrupt type + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Int_Callback_Install(SPI_ID_Type spiNo, SPI_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_INT_TYPE(intType)); + + spiIntCbfArra[spiNo][intType] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI write data to tx fifo - * - * @param spiNo: SPI ID type - * @param data: Data to write - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SendData(SPI_ID_Type spiNo, uint32_t data) -{ - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Write tx fifo */ - BL_WR_REG(SPIx, SPI_FIFO_WDATA, data); - - return SUCCESS; + * @brief SPI write data to tx fifo + * + * @param spiNo: SPI ID type + * @param data: Data to write + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SendData(SPI_ID_Type spiNo, uint32_t data) { + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Write tx fifo */ + BL_WR_REG(SPIx, SPI_FIFO_WDATA, data); + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send 8-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Send_8bits(SPI_ID_Type spiNo, uint8_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t rData; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 0)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send 8-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Send_8bits(SPI_ID_Type spiNo, uint8_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t rData; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 0)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send 16-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Send_16bits(SPI_ID_Type spiNo, uint16_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t rData; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 1)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send 16-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Send_16bits(SPI_ID_Type spiNo, uint16_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t rData; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 1)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send 24-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Send_24bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t rData; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 2)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send 24-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Send_24bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t rData; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 2)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send 32-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Send_32bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t rData; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 3)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send 32-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Send_32bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t rData; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 3)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI receive 8-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Recv_8bits(SPI_ID_Type spiNo, uint8_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t rxLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 0)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo with 0 */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (rxLen = 0; rxLen < tmpVal; rxLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); - } - - /* Wait receive data and send the rest of the data 0 */ - for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI receive 8-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Recv_8bits(SPI_ID_Type spiNo, uint8_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t rxLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 0)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo with 0 */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (rxLen = 0; rxLen < tmpVal; rxLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } + + /* Wait receive data and send the rest of the data 0 */ + for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - buff[rxLen] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } } - /* Wait receive the rest of the data */ - for (; rxLen < length; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + buff[rxLen] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (; rxLen < length; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - buff[rxLen] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + buff[rxLen] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI receive 16-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Recv_16bits(SPI_ID_Type spiNo, uint16_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t rxLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 1)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo with 0 */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (rxLen = 0; rxLen < tmpVal; rxLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); - } - - /* Wait receive data and send the rest of the data 0 */ - for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI receive 16-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Recv_16bits(SPI_ID_Type spiNo, uint16_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t rxLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 1)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo with 0 */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (rxLen = 0; rxLen < tmpVal; rxLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } + + /* Wait receive data and send the rest of the data 0 */ + for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - buff[rxLen++] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } } - /* Wait receive the rest of the data */ - for (; rxLen < length; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + buff[rxLen++] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (; rxLen < length; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - buff[rxLen++] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + buff[rxLen++] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI receive 24-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Recv_24bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t rxLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 2)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo with 0 */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (rxLen = 0; rxLen < tmpVal; rxLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); - } - - /* Wait receive data and send the rest of the data 0 */ - for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI receive 24-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Recv_24bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t rxLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 2)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo with 0 */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (rxLen = 0; rxLen < tmpVal; rxLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } + + /* Wait receive data and send the rest of the data 0 */ + for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } } - /* Wait receive the rest of the data */ - for (; rxLen < length; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (; rxLen < length; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI receive 32-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Recv_32bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t rxLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 3)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo with 0 */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (rxLen = 0; rxLen < tmpVal; rxLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); - } - - /* Wait receive data and send the rest of the data 0 */ - for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI receive 32-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Recv_32bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t rxLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 3)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo with 0 */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (rxLen = 0; rxLen < tmpVal; rxLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } + + /* Wait receive data and send the rest of the data 0 */ + for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } } - /* Wait receive the rest of the data */ - for (; rxLen < length; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (; rxLen < length; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send and receive 8-bit datas at the same time - * - * @param spiNo: SPI ID type - * @param sendBuff: Buffer of datas to send - * @param recvBuff: Buffer of datas received - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SendRecv_8bits(SPI_ID_Type spiNo, uint8_t *sendBuff, uint8_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 0)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send and receive 8-bit datas at the same time + * + * @param spiNo: SPI ID type + * @param sendBuff: Buffer of datas to send + * @param recvBuff: Buffer of datas received + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SendRecv_8bits(SPI_ID_Type spiNo, uint8_t *sendBuff, uint8_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 0)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - recvBuff[txLen - tmpVal] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + recvBuff[txLen - tmpVal] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - recvBuff[length - tmpVal + txLen] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + recvBuff[length - tmpVal + txLen] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send and receive 16-bit datas at the same time - * - * @param spiNo: SPI ID type - * @param sendBuff: Buffer of datas to send - * @param recvBuff: Buffer of datas received - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SendRecv_16bits(SPI_ID_Type spiNo, uint16_t *sendBuff, uint16_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 1)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send and receive 16-bit datas at the same time + * + * @param spiNo: SPI ID type + * @param sendBuff: Buffer of datas to send + * @param recvBuff: Buffer of datas received + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SendRecv_16bits(SPI_ID_Type spiNo, uint16_t *sendBuff, uint16_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 1)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - recvBuff[txLen - tmpVal] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + recvBuff[txLen - tmpVal] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - recvBuff[length - tmpVal + txLen] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + recvBuff[length - tmpVal + txLen] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send and receive 24-bit datas at the same time - * - * @param spiNo: SPI ID type - * @param sendBuff: Buffer of datas to send - * @param recvBuff: Buffer of datas received - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SendRecv_24bits(SPI_ID_Type spiNo, uint32_t *sendBuff, uint32_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 2)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send and receive 24-bit datas at the same time + * + * @param spiNo: SPI ID type + * @param sendBuff: Buffer of datas to send + * @param recvBuff: Buffer of datas received + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SendRecv_24bits(SPI_ID_Type spiNo, uint32_t *sendBuff, uint32_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 2)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - recvBuff[txLen - tmpVal] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; - BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + recvBuff[txLen - tmpVal] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; + BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - recvBuff[length - tmpVal + txLen] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + recvBuff[length - tmpVal + txLen] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send and receive 32-bit datas at the same time - * - * @param spiNo: SPI ID type - * @param sendBuff: Buffer of datas to send - * @param recvBuff: Buffer of datas received - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SendRecv_32bits(SPI_ID_Type spiNo, uint32_t *sendBuff, uint32_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 3)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send and receive 32-bit datas at the same time + * + * @param spiNo: SPI ID type + * @param sendBuff: Buffer of datas to send + * @param recvBuff: Buffer of datas received + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SendRecv_32bits(SPI_ID_Type spiNo, uint32_t *sendBuff, uint32_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 3)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - recvBuff[txLen - tmpVal] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + recvBuff[txLen - tmpVal] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - recvBuff[length - tmpVal + txLen] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + recvBuff[length - tmpVal + txLen] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI read data from rx fifo - * - * @param spiNo: SPI ID type - * - * @return Data readed - * -*******************************************************************************/ -uint32_t SPI_ReceiveData(SPI_ID_Type spiNo) -{ - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - return BL_RD_REG(SPIx, SPI_FIFO_RDATA); + * @brief SPI read data from rx fifo + * + * @param spiNo: SPI ID type + * + * @return Data readed + * + *******************************************************************************/ +uint32_t SPI_ReceiveData(SPI_ID_Type spiNo) { + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + return BL_RD_REG(SPIx, SPI_FIFO_RDATA); } /****************************************************************************/ /** - * @brief Get tx fifo available count value function - * - * @param spiNo: SPI ID type - * - * @return Count value - * -*******************************************************************************/ -uint8_t SPI_GetTxFifoCount(SPI_ID_Type spiNo) -{ - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Get count value */ - return BL_GET_REG_BITS_VAL(BL_RD_REG(SPIx, SPI_FIFO_CONFIG_1), SPI_TX_FIFO_CNT); + * @brief Get tx fifo available count value function + * + * @param spiNo: SPI ID type + * + * @return Count value + * + *******************************************************************************/ +uint8_t SPI_GetTxFifoCount(SPI_ID_Type spiNo) { + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Get count value */ + return BL_GET_REG_BITS_VAL(BL_RD_REG(SPIx, SPI_FIFO_CONFIG_1), SPI_TX_FIFO_CNT); } /****************************************************************************/ /** - * @brief Get rx fifo available count value function - * - * @param spiNo: SPI ID type - * - * @return Count value - * -*******************************************************************************/ -uint8_t SPI_GetRxFifoCount(SPI_ID_Type spiNo) -{ - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Get count value */ - return BL_GET_REG_BITS_VAL(BL_RD_REG(SPIx, SPI_FIFO_CONFIG_1), SPI_RX_FIFO_CNT); + * @brief Get rx fifo available count value function + * + * @param spiNo: SPI ID type + * + * @return Count value + * + *******************************************************************************/ +uint8_t SPI_GetRxFifoCount(SPI_ID_Type spiNo) { + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Get count value */ + return BL_GET_REG_BITS_VAL(BL_RD_REG(SPIx, SPI_FIFO_CONFIG_1), SPI_RX_FIFO_CNT); } /****************************************************************************/ /** - * @brief Get spi interrupt status - * - * @param spiNo: SPI ID type - * @param intType: SPI interrupt type - * - * @return Status of interrupt - * -*******************************************************************************/ -BL_Sts_Type SPI_GetIntStatus(SPI_ID_Type spiNo, SPI_INT_Type intType) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_INT_TYPE(intType)); - - /* Get certain or all interrupt status */ - tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); - - if (SPI_INT_ALL == intType) { - if ((tmpVal & 0x3f) != 0) { - return SET; - } else { - return RESET; - } + * @brief Get spi interrupt status + * + * @param spiNo: SPI ID type + * @param intType: SPI interrupt type + * + * @return Status of interrupt + * + *******************************************************************************/ +BL_Sts_Type SPI_GetIntStatus(SPI_ID_Type spiNo, SPI_INT_Type intType) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_INT_TYPE(intType)); + + /* Get certain or all interrupt status */ + tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); + + if (SPI_INT_ALL == intType) { + if ((tmpVal & 0x3f) != 0) { + return SET; } else { - if ((tmpVal & (1U << intType)) != 0) { - return SET; - } else { - return RESET; - } + return RESET; } -} - -/****************************************************************************/ /** - * @brief Get indicator of spi bus busy - * - * @param spiNo: SPI ID type - * - * @return Status of spi bus - * -*******************************************************************************/ -BL_Sts_Type SPI_GetBusyStatus(SPI_ID_Type spiNo) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Get bus busy status */ - tmpVal = BL_RD_REG(SPIx, SPI_BUS_BUSY); - - if (BL_IS_REG_BIT_SET(tmpVal, SPI_STS_SPI_BUS_BUSY)) { - return SET; + } else { + if ((tmpVal & (1U << intType)) != 0) { + return SET; } else { - return RESET; + return RESET; } + } } /****************************************************************************/ /** - * @brief Get tx/rx fifo overflow or underflow status - * - * @param spiNo: SPI ID type - * @param fifoSts: Select tx/rx overflow or underflow - * - * @return Status of tx/rx fifo - * -*******************************************************************************/ -BL_Sts_Type SPI_GetFifoStatus(SPI_ID_Type spiNo, SPI_FifoStatus_Type fifoSts) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_FIFOSTATUS_TYPE(fifoSts)); - - /* Get tx/rx fifo overflow or underflow status */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + * @brief Get indicator of spi bus busy + * + * @param spiNo: SPI ID type + * + * @return Status of spi bus + * + *******************************************************************************/ +BL_Sts_Type SPI_GetBusyStatus(SPI_ID_Type spiNo) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Get bus busy status */ + tmpVal = BL_RD_REG(SPIx, SPI_BUS_BUSY); + + if (BL_IS_REG_BIT_SET(tmpVal, SPI_STS_SPI_BUS_BUSY)) { + return SET; + } else { + return RESET; + } +} - if ((tmpVal & (1U << (fifoSts + SPI_TX_FIFO_OVERFLOW_POS))) != 0) { - return SET; - } else { - return RESET; - } +/****************************************************************************/ /** + * @brief Get tx/rx fifo overflow or underflow status + * + * @param spiNo: SPI ID type + * @param fifoSts: Select tx/rx overflow or underflow + * + * @return Status of tx/rx fifo + * + *******************************************************************************/ +BL_Sts_Type SPI_GetFifoStatus(SPI_ID_Type spiNo, SPI_FifoStatus_Type fifoSts) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_FIFOSTATUS_TYPE(fifoSts)); + + /* Get tx/rx fifo overflow or underflow status */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + + if ((tmpVal & (1U << (fifoSts + SPI_TX_FIFO_OVERFLOW_POS))) != 0) { + return SET; + } else { + return RESET; + } } /****************************************************************************/ /** - * @brief SPI interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief SPI interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void SPI_IRQHandler(void) -{ - SPI_IntHandler(SPI_ID_0); -} +void SPI_IRQHandler(void) { SPI_IntHandler(SPI_ID_0); } #endif /*@} end of group SPI_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_timer.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_timer.c index 0dec73f195..f5f9cfc2b5 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_timer.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_timer.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_timer.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_timer.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_timer.h" @@ -60,11 +60,7 @@ /** @defgroup TIMER_Private_Variables * @{ */ -intCallback_Type *timerIntCbfArra[3][TIMER_INT_ALL] = { - { NULL, NULL, NULL }, - { NULL, NULL, NULL }, - { NULL, NULL, NULL } -}; +intCallback_Type *timerIntCbfArra[3][TIMER_INT_ALL] = {{NULL, NULL, NULL}, {NULL, NULL, NULL}, {NULL, NULL, NULL}}; /*@} end of group TIMER_Private_Variables */ @@ -88,803 +84,770 @@ static void TIMER_IntHandler(IRQn_Type irqNo, TIMER_Chan_Type timerCh); */ /****************************************************************************/ /** - * @brief TIMER interrupt common handler function - * - * @param irqNo: Interrupt ID type - * @param timerCh: TIMER channel type - * - * @return None - * -*******************************************************************************/ + * @brief TIMER interrupt common handler function + * + * @param irqNo: Interrupt ID type + * @param timerCh: TIMER channel type + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void TIMER_IntHandler(IRQn_Type irqNo, TIMER_Chan_Type timerCh) -{ - uint32_t intId; - uint32_t tmpVal; - uint32_t tmpAddr; - - intId = BL_RD_WORD(TIMER_BASE + TIMER_TMSR2_OFFSET + 4 * timerCh); - tmpAddr = TIMER_BASE + TIMER_TICR2_OFFSET + 4 * timerCh; - tmpVal = BL_RD_WORD(tmpAddr); - - /* Comparator 0 match interrupt */ - if (BL_IS_REG_BIT_SET(intId, TIMER_TMSR_0)) { - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TCLR_0)); - - if (timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_0] != NULL) { - /* Call the callback function */ - timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_0](); - } +void TIMER_IntHandler(IRQn_Type irqNo, TIMER_Chan_Type timerCh) { + uint32_t intId; + uint32_t tmpVal; + uint32_t tmpAddr; + + intId = BL_RD_WORD(TIMER_BASE + TIMER_TMSR2_OFFSET + 4 * timerCh); + tmpAddr = TIMER_BASE + TIMER_TICR2_OFFSET + 4 * timerCh; + tmpVal = BL_RD_WORD(tmpAddr); + + /* Comparator 0 match interrupt */ + if (BL_IS_REG_BIT_SET(intId, TIMER_TMSR_0)) { + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TCLR_0)); + + if (timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_0] != NULL) { + /* Call the callback function */ + timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_0](); } + } - /* Comparator 1 match interrupt */ - if (BL_IS_REG_BIT_SET(intId, TIMER_TMSR_1)) { - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TCLR_1)); + /* Comparator 1 match interrupt */ + if (BL_IS_REG_BIT_SET(intId, TIMER_TMSR_1)) { + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TCLR_1)); - if (timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_1] != NULL) { - /* Call the callback function */ - timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_1](); - } + if (timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_1] != NULL) { + /* Call the callback function */ + timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_1](); } + } - /* Comparator 2 match interrupt */ - if (BL_IS_REG_BIT_SET(intId, TIMER_TMSR_2)) { - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TCLR_2)); + /* Comparator 2 match interrupt */ + if (BL_IS_REG_BIT_SET(intId, TIMER_TMSR_2)) { + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TCLR_2)); - if (timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_2] != NULL) { - /* Call the callback function */ - timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_2](); - } + if (timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_2] != NULL) { + /* Call the callback function */ + timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_2](); } + } } #endif /****************************************************************************/ /** - * @brief Get the specified channel and match comparator value - * - * @param timerCh: TIMER channel type - * @param cmpNo: TIMER comparator ID type - * - * @return Match comapre register value - * -*******************************************************************************/ -uint32_t TIMER_GetCompValue(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); - - tmpVal = BL_RD_WORD(TIMER_BASE + TIMER_TMR2_0_OFFSET + 4 * (TIMER_MAX_MATCH * timerCh + cmpNo)); - return tmpVal; + * @brief Get the specified channel and match comparator value + * + * @param timerCh: TIMER channel type + * @param cmpNo: TIMER comparator ID type + * + * @return Match comapre register value + * + *******************************************************************************/ +uint32_t TIMER_GetCompValue(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); + + tmpVal = BL_RD_WORD(TIMER_BASE + TIMER_TMR2_0_OFFSET + 4 * (TIMER_MAX_MATCH * timerCh + cmpNo)); + return tmpVal; } /****************************************************************************/ /** - * @brief TIMER set specified channel and comparator compare value - * - * @param timerCh: TIMER channel type - * @param cmpNo: TIMER comparator ID type - * @param val: TIMER match comapre register value - * - * @return None - * -*******************************************************************************/ -void TIMER_SetCompValue(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo, uint32_t val) -{ - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); - - BL_WR_WORD(TIMER_BASE + TIMER_TMR2_0_OFFSET + 4 * (TIMER_MAX_MATCH * timerCh + cmpNo), val); + * @brief TIMER set specified channel and comparator compare value + * + * @param timerCh: TIMER channel type + * @param cmpNo: TIMER comparator ID type + * @param val: TIMER match comapre register value + * + * @return None + * + *******************************************************************************/ +void TIMER_SetCompValue(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo, uint32_t val) { + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); + + BL_WR_WORD(TIMER_BASE + TIMER_TMR2_0_OFFSET + 4 * (TIMER_MAX_MATCH * timerCh + cmpNo), val); } /****************************************************************************/ /** - * @brief TIMER get the specified channel count value - * - * @param timerCh: TIMER channel type - * - * @return TIMER count register value - * -*******************************************************************************/ -uint32_t TIMER_GetCounterValue(TIMER_Chan_Type timerCh) -{ - uint32_t tmpVal; - uint32_t tmpAddr; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - - /* TO avoid risk of reading, don't read TCVWR directly*/ - /* request for read*/ - tmpAddr = TIMER_BASE + TIMER_TCVWR2_OFFSET + 4 * timerCh; - BL_WR_WORD(tmpAddr, 1); - - /* Need wait */ - tmpVal = BL_RD_WORD(tmpAddr); - tmpVal = BL_RD_WORD(tmpAddr); - tmpVal = BL_RD_WORD(tmpAddr); - - return tmpVal; + * @brief TIMER get the specified channel count value + * + * @param timerCh: TIMER channel type + * + * @return TIMER count register value + * + *******************************************************************************/ +uint32_t TIMER_GetCounterValue(TIMER_Chan_Type timerCh) { + uint32_t tmpVal; + uint32_t tmpAddr; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + + /* TO avoid risk of reading, don't read TCVWR directly*/ + /* request for read*/ + tmpAddr = TIMER_BASE + TIMER_TCVWR2_OFFSET + 4 * timerCh; + BL_WR_WORD(tmpAddr, 1); + + /* Need wait */ + tmpVal = BL_RD_WORD(tmpAddr); + tmpVal = BL_RD_WORD(tmpAddr); + tmpVal = BL_RD_WORD(tmpAddr); + + return tmpVal; } /****************************************************************************/ /** - * @brief TIMER get specified channel and comparator match status - * - * @param timerCh: TIMER channel type - * @param cmpNo: TIMER comparator ID type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type TIMER_GetMatchStatus(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo) -{ - uint32_t tmpVal; - BL_Sts_Type bitStatus = RESET; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); - - tmpVal = BL_RD_WORD(TIMER_BASE + TIMER_TMSR2_OFFSET + 4 * timerCh); - - switch (cmpNo) { - case TIMER_COMP_ID_0: - bitStatus = BL_IS_REG_BIT_SET(tmpVal, TIMER_TMSR_0) ? SET : RESET; - break; - - case TIMER_COMP_ID_1: - bitStatus = BL_IS_REG_BIT_SET(tmpVal, TIMER_TMSR_1) ? SET : RESET; - break; - - case TIMER_COMP_ID_2: - bitStatus = BL_IS_REG_BIT_SET(tmpVal, TIMER_TMSR_2) ? SET : RESET; - break; - - default: - break; - } - - return bitStatus; + * @brief TIMER get specified channel and comparator match status + * + * @param timerCh: TIMER channel type + * @param cmpNo: TIMER comparator ID type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type TIMER_GetMatchStatus(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo) { + uint32_t tmpVal; + BL_Sts_Type bitStatus = RESET; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); + + tmpVal = BL_RD_WORD(TIMER_BASE + TIMER_TMSR2_OFFSET + 4 * timerCh); + + switch (cmpNo) { + case TIMER_COMP_ID_0: + bitStatus = BL_IS_REG_BIT_SET(tmpVal, TIMER_TMSR_0) ? SET : RESET; + break; + + case TIMER_COMP_ID_1: + bitStatus = BL_IS_REG_BIT_SET(tmpVal, TIMER_TMSR_1) ? SET : RESET; + break; + + case TIMER_COMP_ID_2: + bitStatus = BL_IS_REG_BIT_SET(tmpVal, TIMER_TMSR_2) ? SET : RESET; + break; + + default: + break; + } + + return bitStatus; } /****************************************************************************/ /** - * @brief TIMER get specified channel preload value - * - * @param timerCh: TIMER channel type - * - * @return Preload register value - * -*******************************************************************************/ -uint32_t TIMER_GetPreloadValue(TIMER_Chan_Type timerCh) -{ - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - - return BL_RD_WORD(TIMER_BASE + TIMER_TPLVR2_OFFSET + 4 * timerCh); + * @brief TIMER get specified channel preload value + * + * @param timerCh: TIMER channel type + * + * @return Preload register value + * + *******************************************************************************/ +uint32_t TIMER_GetPreloadValue(TIMER_Chan_Type timerCh) { + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + + return BL_RD_WORD(TIMER_BASE + TIMER_TPLVR2_OFFSET + 4 * timerCh); } /****************************************************************************/ /** - * @brief TIMER set preload register low 32bits value - * - * @param timerCh: TIMER channel type - * @param val: Preload register low 32bits value - * - * @return None - * -*******************************************************************************/ -void TIMER_SetPreloadValue(TIMER_Chan_Type timerCh, uint32_t val) -{ - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - - BL_WR_WORD(TIMER_BASE + TIMER_TPLVR2_OFFSET + 4 * timerCh, val); + * @brief TIMER set preload register low 32bits value + * + * @param timerCh: TIMER channel type + * @param val: Preload register low 32bits value + * + * @return None + * + *******************************************************************************/ +void TIMER_SetPreloadValue(TIMER_Chan_Type timerCh, uint32_t val) { + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + + BL_WR_WORD(TIMER_BASE + TIMER_TPLVR2_OFFSET + 4 * timerCh, val); } /****************************************************************************/ /** - * @brief TIMER set preload trigger source,COMP0,COMP1,COMP2 or None - * - * @param timerCh: TIMER channel type - * @param plSrc: TIMER preload source type - * - * @return None - * -*******************************************************************************/ -void TIMER_SetPreloadTrigSrc(TIMER_Chan_Type timerCh, TIMER_PreLoad_Trig_Type plSrc) -{ - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - CHECK_PARAM(IS_TIMER_PRELOAD_TRIG_TYPE(plSrc)); - - BL_WR_WORD(TIMER_BASE + TIMER_TPLCR2_OFFSET + 4 * timerCh, plSrc); + * @brief TIMER set preload trigger source,COMP0,COMP1,COMP2 or None + * + * @param timerCh: TIMER channel type + * @param plSrc: TIMER preload source type + * + * @return None + * + *******************************************************************************/ +void TIMER_SetPreloadTrigSrc(TIMER_Chan_Type timerCh, TIMER_PreLoad_Trig_Type plSrc) { + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + CHECK_PARAM(IS_TIMER_PRELOAD_TRIG_TYPE(plSrc)); + + BL_WR_WORD(TIMER_BASE + TIMER_TPLCR2_OFFSET + 4 * timerCh, plSrc); } /****************************************************************************/ /** - * @brief TIMER set count mode:preload or free run - * - * @param timerCh: TIMER channel type - * @param countMode: TIMER count mode: TIMER_COUNT_PRELOAD or TIMER_COUNT_FREERUN - * - * @return None - * -*******************************************************************************/ -void TIMER_SetCountMode(TIMER_Chan_Type timerCh, TIMER_CountMode_Type countMode) -{ - uint32_t tmpval; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - CHECK_PARAM(IS_TIMER_COUNTMODE_TYPE(countMode)); - - tmpval = BL_RD_WORD(TIMER_BASE + TIMER_TCMR_OFFSET); - tmpval &= (~(1 << (timerCh + 1))); - tmpval |= (countMode << (timerCh + 1)); - - BL_WR_WORD(TIMER_BASE + TIMER_TCMR_OFFSET, tmpval); + * @brief TIMER set count mode:preload or free run + * + * @param timerCh: TIMER channel type + * @param countMode: TIMER count mode: TIMER_COUNT_PRELOAD or TIMER_COUNT_FREERUN + * + * @return None + * + *******************************************************************************/ +void TIMER_SetCountMode(TIMER_Chan_Type timerCh, TIMER_CountMode_Type countMode) { + uint32_t tmpval; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + CHECK_PARAM(IS_TIMER_COUNTMODE_TYPE(countMode)); + + tmpval = BL_RD_WORD(TIMER_BASE + TIMER_TCMR_OFFSET); + tmpval &= (~(1 << (timerCh + 1))); + tmpval |= (countMode << (timerCh + 1)); + + BL_WR_WORD(TIMER_BASE + TIMER_TCMR_OFFSET, tmpval); } /****************************************************************************/ /** - * @brief TIMER clear interrupt status - * - * @param timerCh: TIMER channel type - * @param cmpNo: TIMER macth comparator ID type - * - * @return None - * -*******************************************************************************/ -void TIMER_ClearIntStatus(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo) -{ - uint32_t tmpAddr; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); - - tmpAddr = TIMER_BASE + TIMER_TICR2_OFFSET + 4 * timerCh; - - tmpVal = BL_RD_WORD(tmpAddr); - tmpVal |= (1 << cmpNo); - - BL_WR_WORD(tmpAddr, tmpVal); + * @brief TIMER clear interrupt status + * + * @param timerCh: TIMER channel type + * @param cmpNo: TIMER macth comparator ID type + * + * @return None + * + *******************************************************************************/ +void TIMER_ClearIntStatus(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo) { + uint32_t tmpAddr; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); + + tmpAddr = TIMER_BASE + TIMER_TICR2_OFFSET + 4 * timerCh; + + tmpVal = BL_RD_WORD(tmpAddr); + tmpVal |= (1 << cmpNo); + + BL_WR_WORD(tmpAddr, tmpVal); } /****************************************************************************/ /** - * @brief TIMER initialization function - * - * @param timerCfg: TIMER configuration structure pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type TIMER_Init(TIMER_CFG_Type *timerCfg) -{ - TIMER_Chan_Type timerCh = timerCfg->timerCh; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CLKSRC_TYPE(timerCfg->clkSrc)); - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCfg->timerCh)); - CHECK_PARAM(IS_TIMER_PRELOAD_TRIG_TYPE(timerCfg->plTrigSrc)); - CHECK_PARAM(IS_TIMER_COUNTMODE_TYPE(timerCfg->countMode)); - - /* Configure timer clock source */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCCR); - - if (timerCh == TIMER_CH0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_CS_1, timerCfg->clkSrc); + * @brief TIMER initialization function + * + * @param timerCfg: TIMER configuration structure pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type TIMER_Init(TIMER_CFG_Type *timerCfg) { + TIMER_Chan_Type timerCh = timerCfg->timerCh; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CLKSRC_TYPE(timerCfg->clkSrc)); + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCfg->timerCh)); + CHECK_PARAM(IS_TIMER_PRELOAD_TRIG_TYPE(timerCfg->plTrigSrc)); + CHECK_PARAM(IS_TIMER_COUNTMODE_TYPE(timerCfg->countMode)); + + /* Configure timer clock source */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCCR); + + if (timerCh == TIMER_CH0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_CS_1, timerCfg->clkSrc); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_CS_2, timerCfg->clkSrc); + } + + BL_WR_REG(TIMER_BASE, TIMER_TCCR, tmpVal); + + /* Configure timer clock division */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCDR); + + if (timerCh == TIMER_CH0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_TCDR2, timerCfg->clockDivision); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_TCDR3, timerCfg->clockDivision); + } + + BL_WR_REG(TIMER_BASE, TIMER_TCDR, tmpVal); + + /* Configure timer count mode: preload or free run */ + TIMER_SetCountMode(timerCh, timerCfg->countMode); + + /* Configure timer preload trigger src */ + TIMER_SetPreloadTrigSrc(timerCh, timerCfg->plTrigSrc); + + if (timerCfg->countMode == TIMER_COUNT_PRELOAD) { + /* Configure timer preload value */ + TIMER_SetPreloadValue(timerCh, timerCfg->preLoadVal); + + /* Configure match compare values */ + if (timerCfg->matchVal0 > 1 + timerCfg->preLoadVal) { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0 - 2); } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_CS_2, timerCfg->clkSrc); + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0); } - BL_WR_REG(TIMER_BASE, TIMER_TCCR, tmpVal); - - /* Configure timer clock division */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCDR); - - if (timerCh == TIMER_CH0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_TCDR2, timerCfg->clockDivision); + if (timerCfg->matchVal1 > 1 + timerCfg->preLoadVal) { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1 - 2); } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_TCDR3, timerCfg->clockDivision); + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1); } - BL_WR_REG(TIMER_BASE, TIMER_TCDR, tmpVal); - - /* Configure timer count mode: preload or free run */ - TIMER_SetCountMode(timerCh, timerCfg->countMode); - - /* Configure timer preload trigger src */ - TIMER_SetPreloadTrigSrc(timerCh, timerCfg->plTrigSrc); - - if (timerCfg->countMode == TIMER_COUNT_PRELOAD) { - /* Configure timer preload value */ - TIMER_SetPreloadValue(timerCh, timerCfg->preLoadVal); - - /* Configure match compare values */ - if (timerCfg->matchVal0 > 1 + timerCfg->preLoadVal) { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0 - 2); - } else { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0); - } + if (timerCfg->matchVal2 > 1 + timerCfg->preLoadVal) { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2 - 2); + } else { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2); + } + } else { + /* Configure match compare values */ + if (timerCfg->matchVal0 > 1) { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0 - 2); + } else { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0); + } - if (timerCfg->matchVal1 > 1 + timerCfg->preLoadVal) { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1 - 2); - } else { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1); - } + if (timerCfg->matchVal1 > 1) { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1 - 2); + } else { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1); + } - if (timerCfg->matchVal2 > 1 + timerCfg->preLoadVal) { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2 - 2); - } else { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2); - } + if (timerCfg->matchVal2 > 1) { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2 - 2); } else { - /* Configure match compare values */ - if (timerCfg->matchVal0 > 1) { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0 - 2); - } else { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0); - } - - if (timerCfg->matchVal1 > 1) { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1 - 2); - } else { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1); - } - - if (timerCfg->matchVal2 > 1) { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2 - 2); - } else { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2); - } + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2); } + } #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(TIMER_CH0_IRQn, TIMER_CH0_IRQHandler); - Interrupt_Handler_Register(TIMER_CH1_IRQn, TIMER_CH1_IRQHandler); + Interrupt_Handler_Register(TIMER_CH0_IRQn, TIMER_CH0_IRQHandler); + Interrupt_Handler_Register(TIMER_CH1_IRQn, TIMER_CH1_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief TIMER enable one channel function - * - * @param timerCh: TIMER channel type - * - * @return None - * -*******************************************************************************/ -void TIMER_Enable(TIMER_Chan_Type timerCh) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCER); - tmpVal |= (1 << (timerCh + 1)); + * @brief TIMER enable one channel function + * + * @param timerCh: TIMER channel type + * + * @return None + * + *******************************************************************************/ +void TIMER_Enable(TIMER_Chan_Type timerCh) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCER); + tmpVal |= (1 << (timerCh + 1)); + + BL_WR_REG(TIMER_BASE, TIMER_TCER, tmpVal); +} - BL_WR_REG(TIMER_BASE, TIMER_TCER, tmpVal); +/****************************************************************************/ /** + * @brief TIMER disable one channel function + * + * @param timerCh: TIMER channel type + * + * @return None + * + *******************************************************************************/ +void TIMER_Disable(TIMER_Chan_Type timerCh) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCER); + tmpVal &= (~(1 << (timerCh + 1))); + + BL_WR_REG(TIMER_BASE, TIMER_TCER, tmpVal); } /****************************************************************************/ /** - * @brief TIMER disable one channel function - * - * @param timerCh: TIMER channel type - * - * @return None - * -*******************************************************************************/ -void TIMER_Disable(TIMER_Chan_Type timerCh) -{ - uint32_t tmpVal; + * @brief TIMER mask or unmask certain or all interrupt + * + * @param timerCh: TIMER channel type + * @param intType: TIMER interrupt type + * @param intMask: TIMER interrupt mask value:MASK:disbale interrupt.UNMASK:enable interrupt + * + * @return None + * + *******************************************************************************/ +void TIMER_IntMask(TIMER_Chan_Type timerCh, TIMER_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpAddr; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + CHECK_PARAM(IS_TIMER_INT_TYPE(intType)); + CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); + + tmpAddr = TIMER_BASE + TIMER_TIER2_OFFSET + 4 * timerCh; + tmpVal = BL_RD_WORD(tmpAddr); + + switch (intType) { + case TIMER_INT_COMP_0: + if (intMask == UNMASK) { + /* Enable this interrupt */ + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_0)); + } else { + /* Disable this interrupt */ + BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_0)); + } - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + break; - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCER); - tmpVal &= (~(1 << (timerCh + 1))); + case TIMER_INT_COMP_1: + if (intMask == UNMASK) { + /* Enable this interrupt */ + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_1)); + } else { + /* Disable this interrupt */ + BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_1)); + } - BL_WR_REG(TIMER_BASE, TIMER_TCER, tmpVal); -} + break; -/****************************************************************************/ /** - * @brief TIMER mask or unmask certain or all interrupt - * - * @param timerCh: TIMER channel type - * @param intType: TIMER interrupt type - * @param intMask: TIMER interrupt mask value:MASK:disbale interrupt.UNMASK:enable interrupt - * - * @return None - * -*******************************************************************************/ -void TIMER_IntMask(TIMER_Chan_Type timerCh, TIMER_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpAddr; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - CHECK_PARAM(IS_TIMER_INT_TYPE(intType)); - CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); - - tmpAddr = TIMER_BASE + TIMER_TIER2_OFFSET + 4 * timerCh; - tmpVal = BL_RD_WORD(tmpAddr); - - switch (intType) { - case TIMER_INT_COMP_0: - if (intMask == UNMASK) { - /* Enable this interrupt */ - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_0)); - } else { - /* Disable this interrupt */ - BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_0)); - } - - break; - - case TIMER_INT_COMP_1: - if (intMask == UNMASK) { - /* Enable this interrupt */ - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_1)); - } else { - /* Disable this interrupt */ - BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_1)); - } - - break; - - case TIMER_INT_COMP_2: - if (intMask == UNMASK) { - /* Enable this interrupt */ - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_2)); - } else { - /* Disable this interrupt */ - BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_2)); - } - - break; - - case TIMER_INT_ALL: - if (intMask == UNMASK) { - /* Enable this interrupt */ - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_0)); - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_1)); - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_2)); - } else { - /* Disable this interrupt */ - BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_0)); - BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_1)); - BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_2)); - } - - break; - - default: - break; + case TIMER_INT_COMP_2: + if (intMask == UNMASK) { + /* Enable this interrupt */ + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_2)); + } else { + /* Disable this interrupt */ + BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_2)); } -} - -/****************************************************************************/ /** - * @brief TIMER set watchdog clock source and clock division - * - * @param clkSrc: Watchdog timer clock source type - * @param div: Watchdog timer clock division value - * - * @return None - * -*******************************************************************************/ -void WDT_Set_Clock(TIMER_ClkSrc_Type clkSrc, uint8_t div) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CLKSRC_TYPE(clkSrc)); - - /* Configure watchdog timer clock source */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCCR); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_CS_WDT, clkSrc); - BL_WR_REG(TIMER_BASE, TIMER_TCCR, tmpVal); - - /* Configure watchdog timer clock divison */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCDR); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_WCDR, div); - BL_WR_REG(TIMER_BASE, TIMER_TCDR, tmpVal); -} -/****************************************************************************/ /** - * @brief TIMER get watchdog match compare value - * - * @param None - * - * @return Watchdog match comapre register value - * -*******************************************************************************/ -uint16_t WDT_GetMatchValue(void) -{ - uint32_t tmpVal; + break; - WDT_ENABLE_ACCESS(); + case TIMER_INT_ALL: + if (intMask == UNMASK) { + /* Enable this interrupt */ + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_0)); + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_1)); + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_2)); + } else { + /* Disable this interrupt */ + BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_0)); + BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_1)); + BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_2)); + } - /* Get watchdog timer match register value */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMR); + break; - return tmpVal; + default: + break; + } } /****************************************************************************/ /** - * @brief TIMER set watchdog match compare value - * - * @param val: Watchdog match compare value - * - * @return None - * -*******************************************************************************/ -void WDT_SetCompValue(uint16_t val) -{ - WDT_ENABLE_ACCESS(); - - /* Set watchdog timer match register value */ - BL_WR_REG(TIMER_BASE, TIMER_WMR, val); + * @brief TIMER set watchdog clock source and clock division + * + * @param clkSrc: Watchdog timer clock source type + * @param div: Watchdog timer clock division value + * + * @return None + * + *******************************************************************************/ +void WDT_Set_Clock(TIMER_ClkSrc_Type clkSrc, uint8_t div) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CLKSRC_TYPE(clkSrc)); + + /* Configure watchdog timer clock source */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCCR); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_CS_WDT, clkSrc); + BL_WR_REG(TIMER_BASE, TIMER_TCCR, tmpVal); + + /* Configure watchdog timer clock divison */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCDR); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_WCDR, div); + BL_WR_REG(TIMER_BASE, TIMER_TCDR, tmpVal); } /****************************************************************************/ /** - * @brief TIMER get watchdog count register value - * - * @param None - * - * @return Watchdog count register value - * -*******************************************************************************/ -uint16_t WDT_GetCounterValue(void) -{ - uint32_t tmpVal; - - WDT_ENABLE_ACCESS(); - - /* Get watchdog timer count register value */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WVR); - - return tmpVal; + * @brief TIMER get watchdog match compare value + * + * @param None + * + * @return Watchdog match comapre register value + * + *******************************************************************************/ +uint16_t WDT_GetMatchValue(void) { + uint32_t tmpVal; + + WDT_ENABLE_ACCESS(); + + /* Get watchdog timer match register value */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMR); + + return tmpVal; } /****************************************************************************/ /** - * @brief TIMER reset watchdog count register value - * - * @param None - * - * @return None - * -*******************************************************************************/ -void WDT_ResetCounterValue(void) -{ - uint32_t tmpVal; - - /* Reset watchdog timer count register value */ - WDT_ENABLE_ACCESS(); - - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WCR); - - /* Set watchdog counter reset register bit0 to 1 */ - BL_WR_REG(TIMER_BASE, TIMER_WCR, BL_SET_REG_BIT(tmpVal, TIMER_WCR)); + * @brief TIMER set watchdog match compare value + * + * @param val: Watchdog match compare value + * + * @return None + * + *******************************************************************************/ +void WDT_SetCompValue(uint16_t val) { + WDT_ENABLE_ACCESS(); + + /* Set watchdog timer match register value */ + BL_WR_REG(TIMER_BASE, TIMER_WMR, val); } /****************************************************************************/ /** - * @brief TIMER get watchdog reset status - * - * @param None - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type WDT_GetResetStatus(void) -{ - uint32_t tmpVal; - - WDT_ENABLE_ACCESS(); - - /* Get watchdog status register */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WSR); - - return (BL_IS_REG_BIT_SET(tmpVal, TIMER_WTS)) ? SET : RESET; + * @brief TIMER get watchdog count register value + * + * @param None + * + * @return Watchdog count register value + * + *******************************************************************************/ +uint16_t WDT_GetCounterValue(void) { + uint32_t tmpVal; + + WDT_ENABLE_ACCESS(); + + /* Get watchdog timer count register value */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WVR); + + return tmpVal; } /****************************************************************************/ /** - * @brief TIMER clear watchdog reset status - * - * @param None - * - * @return None - * -*******************************************************************************/ -void WDT_ClearResetStatus(void) -{ - uint32_t tmpVal; - - WDT_ENABLE_ACCESS(); + * @brief TIMER reset watchdog count register value + * + * @param None + * + * @return None + * + *******************************************************************************/ +void WDT_ResetCounterValue(void) { + uint32_t tmpVal; + + /* Reset watchdog timer count register value */ + WDT_ENABLE_ACCESS(); + + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WCR); + + /* Set watchdog counter reset register bit0 to 1 */ + BL_WR_REG(TIMER_BASE, TIMER_WCR, BL_SET_REG_BIT(tmpVal, TIMER_WCR)); +} - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WSR); +/****************************************************************************/ /** + * @brief TIMER get watchdog reset status + * + * @param None + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type WDT_GetResetStatus(void) { + uint32_t tmpVal; + + WDT_ENABLE_ACCESS(); + + /* Get watchdog status register */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WSR); + + return (BL_IS_REG_BIT_SET(tmpVal, TIMER_WTS)) ? SET : RESET; +} - /* Set watchdog status register */ - BL_WR_REG(TIMER_BASE, TIMER_WSR, BL_CLR_REG_BIT(tmpVal, TIMER_WTS)); +/****************************************************************************/ /** + * @brief TIMER clear watchdog reset status + * + * @param None + * + * @return None + * + *******************************************************************************/ +void WDT_ClearResetStatus(void) { + uint32_t tmpVal; + + WDT_ENABLE_ACCESS(); + + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WSR); + + /* Set watchdog status register */ + BL_WR_REG(TIMER_BASE, TIMER_WSR, BL_CLR_REG_BIT(tmpVal, TIMER_WTS)); } /****************************************************************************/ /** - * @brief TIMER enable watchdog function - * - * @param None - * - * @return None - * -*******************************************************************************/ -void WDT_Enable(void) -{ - uint32_t tmpVal; + * @brief TIMER enable watchdog function + * + * @param None + * + * @return None + * + *******************************************************************************/ +void WDT_Enable(void) { + uint32_t tmpVal; #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(TIMER_WDT_IRQn, TIMER_WDT_IRQHandler); + Interrupt_Handler_Register(TIMER_WDT_IRQn, TIMER_WDT_IRQHandler); #endif - WDT_ENABLE_ACCESS(); + WDT_ENABLE_ACCESS(); - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMER); + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMER); - BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_SET_REG_BIT(tmpVal, TIMER_WE)); + BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_SET_REG_BIT(tmpVal, TIMER_WE)); } /****************************************************************************/ /** - * @brief Watchdog timer disable function - * - * @param None - * - * @return None - * -*******************************************************************************/ -void WDT_Disable(void) -{ - uint32_t tmpVal; + * @brief Watchdog timer disable function + * + * @param None + * + * @return None + * + *******************************************************************************/ +void WDT_Disable(void) { + uint32_t tmpVal; - WDT_ENABLE_ACCESS(); + WDT_ENABLE_ACCESS(); - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMER); + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMER); - BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_CLR_REG_BIT(tmpVal, TIMER_WE)); + BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_CLR_REG_BIT(tmpVal, TIMER_WE)); } /****************************************************************************/ /** - * @brief Watchdog timer mask or unmask certain or all interrupt - * - * @param intType: Watchdog interrupt type - * @param intMask: Watchdog interrupt mask value:MASK:disbale interrupt.UNMASK:enable interrupt - * - * @return None - * -*******************************************************************************/ -void WDT_IntMask(WDT_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_WDT_INT_TYPE(intType)); - CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); - - WDT_ENABLE_ACCESS(); - - /* Deal with watchdog match/interrupt enable register, - WRIE:watchdog reset/interrupt enable */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMER); - - switch (intType) { - case WDT_INT: - if (intMask == UNMASK) { - /* Enable this interrupt */ - /* 0 means generates a watchdog interrupt, - a watchdog timer reset is not generated*/ - BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_CLR_REG_BIT(tmpVal, TIMER_WRIE)); - } else { - /* Disable this interrupt */ - /* 1 means generates a watchdog timer reset, - a watchdog interrupt is not generated*/ - BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_SET_REG_BIT(tmpVal, TIMER_WRIE)); - } - - break; - - default: - break; + * @brief Watchdog timer mask or unmask certain or all interrupt + * + * @param intType: Watchdog interrupt type + * @param intMask: Watchdog interrupt mask value:MASK:disbale interrupt.UNMASK:enable interrupt + * + * @return None + * + *******************************************************************************/ +void WDT_IntMask(WDT_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_WDT_INT_TYPE(intType)); + CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); + + WDT_ENABLE_ACCESS(); + + /* Deal with watchdog match/interrupt enable register, + WRIE:watchdog reset/interrupt enable */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMER); + + switch (intType) { + case WDT_INT: + if (intMask == UNMASK) { + /* Enable this interrupt */ + /* 0 means generates a watchdog interrupt, + a watchdog timer reset is not generated*/ + BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_CLR_REG_BIT(tmpVal, TIMER_WRIE)); + } else { + /* Disable this interrupt */ + /* 1 means generates a watchdog timer reset, + a watchdog interrupt is not generated*/ + BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_SET_REG_BIT(tmpVal, TIMER_WRIE)); } + + break; + + default: + break; + } } /****************************************************************************/ /** - * @brief TIMER channel 0 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief TIMER channel 0 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void TIMER_CH0_IRQHandler(void) -{ - TIMER_IntHandler(TIMER_CH0_IRQn, TIMER_CH0); -} +void TIMER_CH0_IRQHandler(void) { TIMER_IntHandler(TIMER_CH0_IRQn, TIMER_CH0); } #endif /****************************************************************************/ /** - * @brief TIMER channel 1 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief TIMER channel 1 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void TIMER_CH1_IRQHandler(void) -{ - TIMER_IntHandler(TIMER_CH1_IRQn, TIMER_CH1); -} +void TIMER_CH1_IRQHandler(void) { TIMER_IntHandler(TIMER_CH1_IRQn, TIMER_CH1); } #endif /****************************************************************************/ /** - * @brief TIMER watchdog interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief TIMER watchdog interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void TIMER_WDT_IRQHandler(void) -{ - uint32_t tmpVal; +void TIMER_WDT_IRQHandler(void) { + uint32_t tmpVal; - WDT_ENABLE_ACCESS(); + WDT_ENABLE_ACCESS(); - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WICR); - BL_WR_REG(TIMER_BASE, TIMER_WICR, BL_SET_REG_BIT(tmpVal, TIMER_WICLR)); + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WICR); + BL_WR_REG(TIMER_BASE, TIMER_WICR, BL_SET_REG_BIT(tmpVal, TIMER_WICLR)); - if (timerIntCbfArra[TIMER_WDT_IRQn - TIMER_CH0_IRQn][WDT_INT] != NULL) { - /* Call the callback function */ - timerIntCbfArra[TIMER_WDT_IRQn - TIMER_CH0_IRQn][WDT_INT](); - } + if (timerIntCbfArra[TIMER_WDT_IRQn - TIMER_CH0_IRQn][WDT_INT] != NULL) { + /* Call the callback function */ + timerIntCbfArra[TIMER_WDT_IRQn - TIMER_CH0_IRQn][WDT_INT](); + } } #endif /****************************************************************************/ /** - * @brief TIMER install interrupt callback - * - * @param timerChan: TIMER channel type - * @param intType: TIMER interrupt type - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return None - * -*******************************************************************************/ -void Timer_Int_Callback_Install(TIMER_Chan_Type timerChan, TIMER_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerChan)); - CHECK_PARAM(IS_TIMER_INT_TYPE(intType)); - - timerIntCbfArra[timerChan][intType] = cbFun; + * @brief TIMER install interrupt callback + * + * @param timerChan: TIMER channel type + * @param intType: TIMER interrupt type + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return None + * + *******************************************************************************/ +void Timer_Int_Callback_Install(TIMER_Chan_Type timerChan, TIMER_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerChan)); + CHECK_PARAM(IS_TIMER_INT_TYPE(intType)); + + timerIntCbfArra[timerChan][intType] = cbFun; } /****************************************************************************/ /** - * @brief Watchdog install interrupt callback - * - * @param wdtInt: Watchdog interrupt type - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return None - * -*******************************************************************************/ -void WDT_Int_Callback_Install(WDT_INT_Type wdtInt, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_WDT_INT_TYPE(wdtInt)); - - timerIntCbfArra[2][wdtInt] = cbFun; + * @brief Watchdog install interrupt callback + * + * @param wdtInt: Watchdog interrupt type + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return None + * + *******************************************************************************/ +void WDT_Int_Callback_Install(WDT_INT_Type wdtInt, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_WDT_INT_TYPE(wdtInt)); + + timerIntCbfArra[2][wdtInt] = cbFun; } /*@} end of group TIMER_Private_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_uart.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_uart.c index 6b8ce8f24c..82a9792fe2 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_uart.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_uart.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_uart.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_uart.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_uart.h" #include "bl702_glb.h" @@ -61,11 +61,8 @@ /** @defgroup UART_Private_Variables * @{ */ -static const uint32_t uartAddr[2] = { UART0_BASE, UART1_BASE }; -static intCallback_Type *uartIntCbfArra[2][UART_INT_ALL] = { - { NULL }, - { NULL } -}; +static const uint32_t uartAddr[2] = {UART0_BASE, UART1_BASE}; +static intCallback_Type *uartIntCbfArra[2][UART_INT_ALL] = {{NULL}, {NULL}}; /*@} end of group UART_Private_Variables */ @@ -89,95 +86,94 @@ static void UART_IntHandler(UART_ID_Type uartId); */ /****************************************************************************/ /** - * @brief UART interrupt common handler function - * - * @param uartId: UART ID type - * - * @return None - * -*******************************************************************************/ + * @brief UART interrupt common handler function + * + * @param uartId: UART ID type + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -static void UART_IntHandler(UART_ID_Type uartId) -{ - uint32_t tmpVal = 0; - uint32_t maskVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - tmpVal = BL_RD_REG(UARTx, UART_INT_STS); - maskVal = BL_RD_REG(UARTx, UART_INT_MASK); - - /* Length of uart tx data transfer arrived interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_END_MASK)) { - BL_WR_REG(UARTx, UART_INT_CLEAR, 0x1); - - if (uartIntCbfArra[uartId][UART_INT_TX_END] != NULL) { - uartIntCbfArra[uartId][UART_INT_TX_END](); - } +static void UART_IntHandler(UART_ID_Type uartId) { + uint32_t tmpVal = 0; + uint32_t maskVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + tmpVal = BL_RD_REG(UARTx, UART_INT_STS); + maskVal = BL_RD_REG(UARTx, UART_INT_MASK); + + /* Length of uart tx data transfer arrived interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_END_MASK)) { + BL_WR_REG(UARTx, UART_INT_CLEAR, 0x1); + + if (uartIntCbfArra[uartId][UART_INT_TX_END] != NULL) { + uartIntCbfArra[uartId][UART_INT_TX_END](); } + } - /* Length of uart rx data transfer arrived interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_END_MASK)) { - BL_WR_REG(UARTx, UART_INT_CLEAR, 0x2); + /* Length of uart rx data transfer arrived interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_END_MASK)) { + BL_WR_REG(UARTx, UART_INT_CLEAR, 0x2); - if (uartIntCbfArra[uartId][UART_INT_RX_END] != NULL) { - uartIntCbfArra[uartId][UART_INT_RX_END](); - } + if (uartIntCbfArra[uartId][UART_INT_RX_END] != NULL) { + uartIntCbfArra[uartId][UART_INT_RX_END](); } + } - /* Tx fifo ready interrupt,auto-cleared when data is pushed */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FIFO_MASK)) { - if (uartIntCbfArra[uartId][UART_INT_TX_FIFO_REQ] != NULL) { - uartIntCbfArra[uartId][UART_INT_TX_FIFO_REQ](); - } + /* Tx fifo ready interrupt,auto-cleared when data is pushed */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FIFO_MASK)) { + if (uartIntCbfArra[uartId][UART_INT_TX_FIFO_REQ] != NULL) { + uartIntCbfArra[uartId][UART_INT_TX_FIFO_REQ](); } + } - /* Rx fifo ready interrupt,auto-cleared when data is popped */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FIFO_MASK)) { - if (uartIntCbfArra[uartId][UART_INT_RX_FIFO_REQ] != NULL) { - uartIntCbfArra[uartId][UART_INT_RX_FIFO_REQ](); - } + /* Rx fifo ready interrupt,auto-cleared when data is popped */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FIFO_MASK)) { + if (uartIntCbfArra[uartId][UART_INT_RX_FIFO_REQ] != NULL) { + uartIntCbfArra[uartId][UART_INT_RX_FIFO_REQ](); } + } - /* Rx time-out interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_RTO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_RTO_MASK)) { - BL_WR_REG(UARTx, UART_INT_CLEAR, 0x10); + /* Rx time-out interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_RTO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_RTO_MASK)) { + BL_WR_REG(UARTx, UART_INT_CLEAR, 0x10); - if (uartIntCbfArra[uartId][UART_INT_RTO] != NULL) { - uartIntCbfArra[uartId][UART_INT_RTO](); - } + if (uartIntCbfArra[uartId][UART_INT_RTO] != NULL) { + uartIntCbfArra[uartId][UART_INT_RTO](); } + } - /* Rx parity check error interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_PCE_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_PCE_MASK)) { - BL_WR_REG(UARTx, UART_INT_CLEAR, 0x20); + /* Rx parity check error interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_PCE_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_PCE_MASK)) { + BL_WR_REG(UARTx, UART_INT_CLEAR, 0x20); - if (uartIntCbfArra[uartId][UART_INT_PCE] != NULL) { - uartIntCbfArra[uartId][UART_INT_PCE](); - } + if (uartIntCbfArra[uartId][UART_INT_PCE] != NULL) { + uartIntCbfArra[uartId][UART_INT_PCE](); } + } - /* Tx fifo overflow/underflow error interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FER_MASK)) { - if (uartIntCbfArra[uartId][UART_INT_TX_FER] != NULL) { - uartIntCbfArra[uartId][UART_INT_TX_FER](); - } + /* Tx fifo overflow/underflow error interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FER_MASK)) { + if (uartIntCbfArra[uartId][UART_INT_TX_FER] != NULL) { + uartIntCbfArra[uartId][UART_INT_TX_FER](); } + } - /* Rx fifo overflow/underflow error interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FER_MASK)) { - if (uartIntCbfArra[uartId][UART_INT_RX_FER] != NULL) { - uartIntCbfArra[uartId][UART_INT_RX_FER](); - } + /* Rx fifo overflow/underflow error interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FER_MASK)) { + if (uartIntCbfArra[uartId][UART_INT_RX_FER] != NULL) { + uartIntCbfArra[uartId][UART_INT_RX_FER](); } + } - /* Rx lin mode sync field error interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_LSE_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_LSE_MASK)) { - BL_WR_REG(UARTx, UART_INT_CLEAR, 0x100); + /* Rx lin mode sync field error interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_LSE_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_LSE_MASK)) { + BL_WR_REG(UARTx, UART_INT_CLEAR, 0x100); - if (uartIntCbfArra[uartId][UART_INT_LSE] != NULL) { - uartIntCbfArra[uartId][UART_INT_LSE](); - } + if (uartIntCbfArra[uartId][UART_INT_LSE] != NULL) { + uartIntCbfArra[uartId][UART_INT_LSE](); } + } } #endif @@ -188,1035 +184,996 @@ static void UART_IntHandler(UART_ID_Type uartId) */ /****************************************************************************/ /** - * @brief UART initialization function - * - * @param uartId: UART ID type - * @param uartCfg: UART configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_Init(UART_ID_Type uartId, UART_CFG_Type *uartCfg) -{ - uint32_t tmpValTxCfg = 0; - uint32_t tmpValRxCfg = 0; - uint32_t fraction = 0; - uint32_t baudRateDivisor = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_PARITY_TYPE(uartCfg->parity)); - CHECK_PARAM(IS_UART_DATABITS_TYPE(uartCfg->dataBits)); - CHECK_PARAM(IS_UART_STOPBITS_TYPE(uartCfg->stopBits)); - CHECK_PARAM(IS_UART_BYTEBITINVERSE_TYPE(uartCfg->byteBitInverse)); - - /* Cal the baud rate divisor */ - fraction = uartCfg->uartClk * 10 / uartCfg->baudRate % 10; - baudRateDivisor = uartCfg->uartClk / uartCfg->baudRate; - - if (fraction >= 5) { - ++baudRateDivisor; - } - - /* Set the baud rate register value */ - BL_WR_REG(UARTx, UART_BIT_PRD, ((baudRateDivisor - 1) << 0x10) | ((baudRateDivisor - 1) & 0xFFFF)); - - /* Configure parity type */ - tmpValTxCfg = BL_RD_REG(UARTx, UART_UTX_CONFIG); - tmpValRxCfg = BL_RD_REG(UARTx, UART_URX_CONFIG); - - switch (uartCfg->parity) { - case UART_PARITY_NONE: - tmpValTxCfg = BL_CLR_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_EN); - tmpValRxCfg = BL_CLR_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_EN); - break; - - case UART_PARITY_ODD: - tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_EN); - tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_SEL); - tmpValRxCfg = BL_SET_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_EN); - tmpValRxCfg = BL_SET_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_SEL); - break; - - case UART_PARITY_EVEN: - tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_EN); - tmpValTxCfg = BL_CLR_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_SEL); - tmpValRxCfg = BL_SET_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_EN); - tmpValRxCfg = BL_CLR_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_SEL); - break; - - default: - break; - } - - /* Configure data bits */ - tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_BIT_CNT_D, (uartCfg->dataBits + 4)); - tmpValRxCfg = BL_SET_REG_BITS_VAL(tmpValRxCfg, UART_CR_URX_BIT_CNT_D, (uartCfg->dataBits + 4)); - - /* Configure tx stop bits */ - tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_BIT_CNT_P, uartCfg->stopBits); - - /* Configure tx cts flow control function */ - tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_CTS_EN, uartCfg->ctsFlowControl); - - /* Configure rx input de-glitch function */ - tmpValRxCfg = BL_SET_REG_BITS_VAL(tmpValRxCfg, UART_CR_URX_DEG_EN, uartCfg->rxDeglitch); - - /* Configure tx lin mode function */ - tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_LIN_EN, uartCfg->txLinMode); - - /* Configure rx lin mode function */ - tmpValRxCfg = BL_SET_REG_BITS_VAL(tmpValRxCfg, UART_CR_URX_LIN_EN, uartCfg->rxLinMode); - - /* Set tx break bit count for lin protocol */ - tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_BIT_CNT_B, uartCfg->txBreakBitCnt); - - /* Write back */ - BL_WR_REG(UARTx, UART_UTX_CONFIG, tmpValTxCfg); - BL_WR_REG(UARTx, UART_URX_CONFIG, tmpValRxCfg); - - /* Configure LSB-first or MSB-first */ - tmpValTxCfg = BL_RD_REG(UARTx, UART_DATA_CONFIG); - - if (UART_MSB_FIRST == uartCfg->byteBitInverse) { - tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UART_BIT_INV); - } else { - tmpValTxCfg = BL_CLR_REG_BIT(tmpValTxCfg, UART_CR_UART_BIT_INV); - } - - BL_WR_REG(UARTx, UART_DATA_CONFIG, tmpValTxCfg); - - tmpValTxCfg = BL_RD_REG(UARTx, UART_SW_MODE); - /* Configure rx rts output SW control mode */ - tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_URX_RTS_SW_MODE, uartCfg->rtsSoftwareControl); - /* Configure tx output SW control mode */ - tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_TXD_SW_MODE, uartCfg->txSoftwareControl); - BL_WR_REG(UARTx, UART_SW_MODE, tmpValTxCfg); + * @brief UART initialization function + * + * @param uartId: UART ID type + * @param uartCfg: UART configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_Init(UART_ID_Type uartId, UART_CFG_Type *uartCfg) { + uint32_t tmpValTxCfg = 0; + uint32_t tmpValRxCfg = 0; + uint32_t fraction = 0; + uint32_t baudRateDivisor = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_PARITY_TYPE(uartCfg->parity)); + CHECK_PARAM(IS_UART_DATABITS_TYPE(uartCfg->dataBits)); + CHECK_PARAM(IS_UART_STOPBITS_TYPE(uartCfg->stopBits)); + CHECK_PARAM(IS_UART_BYTEBITINVERSE_TYPE(uartCfg->byteBitInverse)); + + /* Cal the baud rate divisor */ + fraction = uartCfg->uartClk * 10 / uartCfg->baudRate % 10; + baudRateDivisor = uartCfg->uartClk / uartCfg->baudRate; + + if (fraction >= 5) { + ++baudRateDivisor; + } + + /* Set the baud rate register value */ + BL_WR_REG(UARTx, UART_BIT_PRD, ((baudRateDivisor - 1) << 0x10) | ((baudRateDivisor - 1) & 0xFFFF)); + + /* Configure parity type */ + tmpValTxCfg = BL_RD_REG(UARTx, UART_UTX_CONFIG); + tmpValRxCfg = BL_RD_REG(UARTx, UART_URX_CONFIG); + + switch (uartCfg->parity) { + case UART_PARITY_NONE: + tmpValTxCfg = BL_CLR_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_EN); + tmpValRxCfg = BL_CLR_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_EN); + break; + + case UART_PARITY_ODD: + tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_EN); + tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_SEL); + tmpValRxCfg = BL_SET_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_EN); + tmpValRxCfg = BL_SET_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_SEL); + break; + + case UART_PARITY_EVEN: + tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_EN); + tmpValTxCfg = BL_CLR_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_SEL); + tmpValRxCfg = BL_SET_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_EN); + tmpValRxCfg = BL_CLR_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_SEL); + break; + + default: + break; + } + + /* Configure data bits */ + tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_BIT_CNT_D, (uartCfg->dataBits + 4)); + tmpValRxCfg = BL_SET_REG_BITS_VAL(tmpValRxCfg, UART_CR_URX_BIT_CNT_D, (uartCfg->dataBits + 4)); + + /* Configure tx stop bits */ + tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_BIT_CNT_P, uartCfg->stopBits); + + /* Configure tx cts flow control function */ + tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_CTS_EN, uartCfg->ctsFlowControl); + + /* Configure rx input de-glitch function */ + tmpValRxCfg = BL_SET_REG_BITS_VAL(tmpValRxCfg, UART_CR_URX_DEG_EN, uartCfg->rxDeglitch); + + /* Configure tx lin mode function */ + tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_LIN_EN, uartCfg->txLinMode); + + /* Configure rx lin mode function */ + tmpValRxCfg = BL_SET_REG_BITS_VAL(tmpValRxCfg, UART_CR_URX_LIN_EN, uartCfg->rxLinMode); + + /* Set tx break bit count for lin protocol */ + tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_BIT_CNT_B, uartCfg->txBreakBitCnt); + + /* Write back */ + BL_WR_REG(UARTx, UART_UTX_CONFIG, tmpValTxCfg); + BL_WR_REG(UARTx, UART_URX_CONFIG, tmpValRxCfg); + + /* Configure LSB-first or MSB-first */ + tmpValTxCfg = BL_RD_REG(UARTx, UART_DATA_CONFIG); + + if (UART_MSB_FIRST == uartCfg->byteBitInverse) { + tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UART_BIT_INV); + } else { + tmpValTxCfg = BL_CLR_REG_BIT(tmpValTxCfg, UART_CR_UART_BIT_INV); + } + + BL_WR_REG(UARTx, UART_DATA_CONFIG, tmpValTxCfg); + + tmpValTxCfg = BL_RD_REG(UARTx, UART_SW_MODE); + /* Configure rx rts output SW control mode */ + tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_URX_RTS_SW_MODE, uartCfg->rtsSoftwareControl); + /* Configure tx output SW control mode */ + tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_TXD_SW_MODE, uartCfg->txSoftwareControl); + BL_WR_REG(UARTx, UART_SW_MODE, tmpValTxCfg); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(UART0_IRQn, UART0_IRQHandler); - Interrupt_Handler_Register(UART1_IRQn, UART1_IRQHandler); + Interrupt_Handler_Register(UART0_IRQn, UART0_IRQHandler); + Interrupt_Handler_Register(UART1_IRQn, UART1_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set default value of all registers function - * - * @param uartId: UART ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_DeInit(UART_ID_Type uartId) -{ - if (UART0_ID == uartId) { - GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART0); - } else if (UART1_ID == uartId) { - GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART1); - } - - return SUCCESS; + * @brief UART set default value of all registers function + * + * @param uartId: UART ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_DeInit(UART_ID_Type uartId) { + if (UART0_ID == uartId) { + GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART0); + } else if (UART1_ID == uartId) { + GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART1); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART configure fifo function - * - * @param uartId: UART ID type - * @param fifoCfg: FIFO configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_FifoConfig(UART_ID_Type uartId, UART_FifoCfg_Type *fifoCfg) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Deal with uart fifo configure register */ - tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_1); - /* Configure dma tx fifo threshold */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_TX_FIFO_TH, fifoCfg->txFifoDmaThreshold); - /* Configure dma rx fifo threshold */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_RX_FIFO_TH, fifoCfg->rxFifoDmaThreshold); - /* Write back */ - BL_WR_REG(UARTx, UART_FIFO_CONFIG_1, tmpVal); - - /* Enable or disable uart fifo dma function */ - tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); - - if (ENABLE == fifoCfg->txFifoDmaEnable) { - tmpVal = BL_SET_REG_BIT(tmpVal, UART_DMA_TX_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, UART_DMA_TX_EN); - } - - if (ENABLE == fifoCfg->rxFifoDmaEnable) { - tmpVal = BL_SET_REG_BIT(tmpVal, UART_DMA_RX_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, UART_DMA_RX_EN); - } - - BL_WR_REG(UARTx, UART_FIFO_CONFIG_0, tmpVal); - - return SUCCESS; + * @brief UART configure fifo function + * + * @param uartId: UART ID type + * @param fifoCfg: FIFO configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_FifoConfig(UART_ID_Type uartId, UART_FifoCfg_Type *fifoCfg) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Deal with uart fifo configure register */ + tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_1); + /* Configure dma tx fifo threshold */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_TX_FIFO_TH, fifoCfg->txFifoDmaThreshold); + /* Configure dma rx fifo threshold */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_RX_FIFO_TH, fifoCfg->rxFifoDmaThreshold); + /* Write back */ + BL_WR_REG(UARTx, UART_FIFO_CONFIG_1, tmpVal); + + /* Enable or disable uart fifo dma function */ + tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); + + if (ENABLE == fifoCfg->txFifoDmaEnable) { + tmpVal = BL_SET_REG_BIT(tmpVal, UART_DMA_TX_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, UART_DMA_TX_EN); + } + + if (ENABLE == fifoCfg->rxFifoDmaEnable) { + tmpVal = BL_SET_REG_BIT(tmpVal, UART_DMA_RX_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, UART_DMA_RX_EN); + } + + BL_WR_REG(UARTx, UART_FIFO_CONFIG_0, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART configure infra function - * - * @param uartId: UART ID type - * @param irCfg: IR configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_IrConfig(UART_ID_Type uartId, UART_IrCfg_Type *irCfg) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + * @brief UART configure infra function + * + * @param uartId: UART ID type + * @param irCfg: IR configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_IrConfig(UART_ID_Type uartId, UART_IrCfg_Type *irCfg) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Configure tx ir mode */ + tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); + + if (ENABLE == irCfg->txIrEnable) { + tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_UTX_IR_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_IR_EN); + } + + if (ENABLE == irCfg->txIrInverse) { + tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_UTX_IR_INV); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_IR_INV); + } + + BL_WR_REG(UARTx, UART_UTX_CONFIG, tmpVal); + + /* Configure rx ir mode */ + tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); + + if (ENABLE == irCfg->rxIrEnable) { + tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_URX_IR_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_URX_IR_EN); + } + + if (ENABLE == irCfg->rxIrInverse) { + tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_URX_IR_INV); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_URX_IR_INV); + } + + BL_WR_REG(UARTx, UART_URX_CONFIG, tmpVal); + + /* Configure tx ir pulse start and stop position */ + BL_WR_REG(UARTx, UART_UTX_IR_POSITION, irCfg->txIrPulseStop << 0x10 | irCfg->txIrPulseStart); + + /* Configure rx ir pulse start position */ + BL_WR_REG(UARTx, UART_URX_IR_POSITION, irCfg->rxIrPulseStart); + + return SUCCESS; +} - /* Configure tx ir mode */ +/****************************************************************************/ /** + * @brief Enable UART + * + * @param uartId: UART ID type + * @param direct: UART direction type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_Enable(UART_ID_Type uartId, UART_Direction_Type direct) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_DIRECTION_TYPE(direct)); + + if (direct == UART_TX || direct == UART_TXRX) { + /* Enable UART tx unit */ tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); + BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_UTX_EN)); + } - if (ENABLE == irCfg->txIrEnable) { - tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_UTX_IR_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_IR_EN); - } - - if (ENABLE == irCfg->txIrInverse) { - tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_UTX_IR_INV); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_IR_INV); - } - - BL_WR_REG(UARTx, UART_UTX_CONFIG, tmpVal); - - /* Configure rx ir mode */ + if (direct == UART_RX || direct == UART_TXRX) { + /* Enable UART rx unit */ tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); + BL_WR_REG(UARTx, UART_URX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_URX_EN)); + } - if (ENABLE == irCfg->rxIrEnable) { - tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_URX_IR_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_URX_IR_EN); - } - - if (ENABLE == irCfg->rxIrInverse) { - tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_URX_IR_INV); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_URX_IR_INV); - } - - BL_WR_REG(UARTx, UART_URX_CONFIG, tmpVal); - - /* Configure tx ir pulse start and stop position */ - BL_WR_REG(UARTx, UART_UTX_IR_POSITION, irCfg->txIrPulseStop << 0x10 | irCfg->txIrPulseStart); - - /* Configure rx ir pulse start position */ - BL_WR_REG(UARTx, UART_URX_IR_POSITION, irCfg->rxIrPulseStart); - - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Enable UART - * - * @param uartId: UART ID type - * @param direct: UART direction type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_Enable(UART_ID_Type uartId, UART_Direction_Type direct) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_DIRECTION_TYPE(direct)); - - if (direct == UART_TX || direct == UART_TXRX) { - /* Enable UART tx unit */ - tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); - BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_UTX_EN)); - } + * @brief Disable UART + * + * @param uartId: UART ID type + * @param direct: UART direction type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_Disable(UART_ID_Type uartId, UART_Direction_Type direct) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_DIRECTION_TYPE(direct)); + + if (direct == UART_TX || direct == UART_TXRX) { + /* Disable UART tx unit */ + tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); + BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_EN)); + } - if (direct == UART_RX || direct == UART_TXRX) { - /* Enable UART rx unit */ - tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); - BL_WR_REG(UARTx, UART_URX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_URX_EN)); - } + if (direct == UART_RX || direct == UART_TXRX) { + /* Disable UART rx unit */ + tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); + BL_WR_REG(UARTx, UART_URX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_URX_EN)); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Disable UART - * - * @param uartId: UART ID type - * @param direct: UART direction type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_Disable(UART_ID_Type uartId, UART_Direction_Type direct) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_DIRECTION_TYPE(direct)); - - if (direct == UART_TX || direct == UART_TXRX) { - /* Disable UART tx unit */ - tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); - BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_EN)); - } - - if (direct == UART_RX || direct == UART_TXRX) { - /* Disable UART rx unit */ - tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); - BL_WR_REG(UARTx, UART_URX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_URX_EN)); - } - - return SUCCESS; + * @brief UART set length of tx data transfer,tx end interrupt will assert when this length is + * reached + * + * @param uartId: UART ID type + * @param length: Length of data (unit:character/byte) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SetTxDataLength(UART_ID_Type uartId, uint16_t length) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Set length */ + tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); + BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, UART_CR_UTX_LEN, length - 1)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set length of tx data transfer,tx end interrupt will assert when this length is - * reached - * - * @param uartId: UART ID type - * @param length: Length of data (unit:character/byte) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SetTxDataLength(UART_ID_Type uartId, uint16_t length) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Set length */ - tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); - BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, UART_CR_UTX_LEN, length - 1)); - - return SUCCESS; + * @brief UART set length of rx data transfer,rx end interrupt will assert when this length is + * reached + * + * @param uartId: UART ID type + * @param length: Length of data (unit:character/byte) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SetRxDataLength(UART_ID_Type uartId, uint16_t length) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Set length */ + tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); + BL_WR_REG(UARTx, UART_URX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, UART_CR_URX_LEN, length - 1)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set length of rx data transfer,rx end interrupt will assert when this length is - * reached - * - * @param uartId: UART ID type - * @param length: Length of data (unit:character/byte) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SetRxDataLength(UART_ID_Type uartId, uint16_t length) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Set length */ - tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); - BL_WR_REG(UARTx, UART_URX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, UART_CR_URX_LEN, length - 1)); - - return SUCCESS; + * @brief UART set rx time-out value for triggering RTO interrupt + * + * @param uartId: UART ID type + * @param time: Time-out value (unit:bit time) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SetRxTimeoutValue(UART_ID_Type uartId, uint8_t time) { + uint32_t UARTx = uartAddr[uartId]; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Set time-out value */ + tmpVal = BL_RD_REG(UARTx, UART_URX_RTO_TIMER); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_CR_URX_RTO_VALUE, time - 1); + BL_WR_REG(UARTx, UART_URX_RTO_TIMER, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set rx time-out value for triggering RTO interrupt - * - * @param uartId: UART ID type - * @param time: Time-out value (unit:bit time) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SetRxTimeoutValue(UART_ID_Type uartId, uint8_t time) -{ - uint32_t UARTx = uartAddr[uartId]; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Set time-out value */ - tmpVal = BL_RD_REG(UARTx, UART_URX_RTO_TIMER); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_CR_URX_RTO_VALUE, time - 1); - BL_WR_REG(UARTx, UART_URX_RTO_TIMER, tmpVal); - - return SUCCESS; + * @brief UART set de-glitch function cycle count value + * + * @param uartId: UART ID type + * @param deglitchCnt: De-glitch function cycle count + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SetDeglitchCount(UART_ID_Type uartId, uint8_t deglitchCnt) { + uint32_t UARTx = uartAddr[uartId]; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Set count value */ + tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_CR_URX_DEG_CNT, deglitchCnt); + BL_WR_REG(UARTx, UART_URX_CONFIG, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set de-glitch function cycle count value - * - * @param uartId: UART ID type - * @param deglitchCnt: De-glitch function cycle count - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SetDeglitchCount(UART_ID_Type uartId, uint8_t deglitchCnt) -{ - uint32_t UARTx = uartAddr[uartId]; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Set count value */ - tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_CR_URX_DEG_CNT, deglitchCnt); - BL_WR_REG(UARTx, UART_URX_CONFIG, tmpVal); - - return SUCCESS; + * @brief UART set tx and rx baudrate according to auto baudrate detection value + * + * @param uartId: UART ID type + * @param autoBaudDet: Choose detection value using codeword 0x55 or start bit + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_ApplyAbrResult(UART_ID_Type uartId, UART_AutoBaudDetection_Type autoBaudDet) { + uint32_t UARTx = uartAddr[uartId]; + uint16_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Get detection value */ + tmpVal = UART_GetAutoBaudCount(uartId, autoBaudDet); + + /* Set tx baudrate */ + BL_WR_REG(UARTx, UART_BIT_PRD, tmpVal << 0x10 | tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set tx and rx baudrate according to auto baudrate detection value - * - * @param uartId: UART ID type - * @param autoBaudDet: Choose detection value using codeword 0x55 or start bit - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_ApplyAbrResult(UART_ID_Type uartId, UART_AutoBaudDetection_Type autoBaudDet) -{ - uint32_t UARTx = uartAddr[uartId]; - uint16_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Get detection value */ - tmpVal = UART_GetAutoBaudCount(uartId, autoBaudDet); - - /* Set tx baudrate */ - BL_WR_REG(UARTx, UART_BIT_PRD, tmpVal << 0x10 | tmpVal); - - return SUCCESS; + * @brief UART set rx rts output software control value + * + * @param uartId: UART ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SetRtsValue(UART_ID_Type uartId) { + uint32_t UARTx = uartAddr[uartId]; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Rts set 1*/ + tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); + BL_WR_REG(UARTx, UART_SW_MODE, BL_SET_REG_BIT(tmpVal, UART_CR_URX_RTS_SW_VAL)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set rx rts output software control value - * - * @param uartId: UART ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SetRtsValue(UART_ID_Type uartId) -{ - uint32_t UARTx = uartAddr[uartId]; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Rts set 1*/ - tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); - BL_WR_REG(UARTx, UART_SW_MODE, BL_SET_REG_BIT(tmpVal, UART_CR_URX_RTS_SW_VAL)); - - return SUCCESS; + * @brief UART clear rx rts output software control value + * + * @param uartId: UART ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_ClrRtsValue(UART_ID_Type uartId) { + uint32_t UARTx = uartAddr[uartId]; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Rts clear 0 */ + tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); + BL_WR_REG(UARTx, UART_SW_MODE, BL_CLR_REG_BIT(tmpVal, UART_CR_URX_RTS_SW_VAL)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART clear rx rts output software control value - * - * @param uartId: UART ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_ClrRtsValue(UART_ID_Type uartId) -{ - uint32_t UARTx = uartAddr[uartId]; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Rts clear 0 */ - tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); - BL_WR_REG(UARTx, UART_SW_MODE, BL_CLR_REG_BIT(tmpVal, UART_CR_URX_RTS_SW_VAL)); - - return SUCCESS; + * @brief UART set tx output software control value + * + * @param uartId: UART ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SetTxValue(UART_ID_Type uartId) { + uint32_t UARTx = uartAddr[uartId]; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Tx set 1*/ + tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); + BL_WR_REG(UARTx, UART_SW_MODE, BL_SET_REG_BIT(tmpVal, UART_CR_UTX_TXD_SW_VAL)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set tx output software control value - * - * @param uartId: UART ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SetTxValue(UART_ID_Type uartId) -{ - uint32_t UARTx = uartAddr[uartId]; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Tx set 1*/ - tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); - BL_WR_REG(UARTx, UART_SW_MODE, BL_SET_REG_BIT(tmpVal, UART_CR_UTX_TXD_SW_VAL)); - - return SUCCESS; + * @brief UART clear tx output software control value + * + * @param uartId: UART ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_ClrTxValue(UART_ID_Type uartId) { + uint32_t UARTx = uartAddr[uartId]; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Rts clear 0 */ + tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); + BL_WR_REG(UARTx, UART_SW_MODE, BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_TXD_SW_VAL)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART clear tx output software control value - * - * @param uartId: UART ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_ClrTxValue(UART_ID_Type uartId) -{ - uint32_t UARTx = uartAddr[uartId]; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Rts clear 0 */ - tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); - BL_WR_REG(UARTx, UART_SW_MODE, BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_TXD_SW_VAL)); - - return SUCCESS; + * @brief UART configure tx free run mode function + * + * @param uartId: UART ID type + * @param txFreeRun: Enable or disable tx free run mode + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_TxFreeRun(UART_ID_Type uartId, BL_Fun_Type txFreeRun) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Enable or disable tx free run mode */ + tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); + + if (ENABLE == txFreeRun) { + BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_UTX_FRM_EN)); + } else { + BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_FRM_EN)); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART configure tx free run mode function - * - * @param uartId: UART ID type - * @param txFreeRun: Enable or disable tx free run mode - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_TxFreeRun(UART_ID_Type uartId, BL_Fun_Type txFreeRun) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Enable or disable tx free run mode */ - tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); - - if (ENABLE == txFreeRun) { - BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_UTX_FRM_EN)); - } else { - BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_FRM_EN)); - } - - return SUCCESS; + * @brief UART configure auto baud rate detection function + * + * @param uartId: UART ID type + * @param autoBaud: Enable or disable auto function + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_AutoBaudDetection(UART_ID_Type uartId, BL_Fun_Type autoBaud) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Enable or disable auto baud rate detection function */ + tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); + + if (ENABLE == autoBaud) { + BL_WR_REG(UARTx, UART_URX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_URX_ABR_EN)); + } else { + BL_WR_REG(UARTx, UART_URX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_URX_ABR_EN)); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART configure auto baud rate detection function - * - * @param uartId: UART ID type - * @param autoBaud: Enable or disable auto function - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_AutoBaudDetection(UART_ID_Type uartId, BL_Fun_Type autoBaud) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Enable or disable auto baud rate detection function */ - tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); - - if (ENABLE == autoBaud) { - BL_WR_REG(UARTx, UART_URX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_URX_ABR_EN)); - } else { - BL_WR_REG(UARTx, UART_URX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_URX_ABR_EN)); - } - - return SUCCESS; + * @brief UART tx fifo clear + * + * @param uartId: UART ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_TxFifoClear(UART_ID_Type uartId) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Clear tx fifo */ + tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); + BL_WR_REG(UARTx, UART_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, UART_TX_FIFO_CLR)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART tx fifo clear - * - * @param uartId: UART ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_TxFifoClear(UART_ID_Type uartId) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Clear tx fifo */ - tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); - BL_WR_REG(UARTx, UART_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, UART_TX_FIFO_CLR)); - - return SUCCESS; + * @brief UART rx fifo clear + * + * @param uartId: UART ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_RxFifoClear(UART_ID_Type uartId) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Clear rx fifo */ + tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); + BL_WR_REG(UARTx, UART_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, UART_RX_FIFO_CLR)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART rx fifo clear - * - * @param uartId: UART ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_RxFifoClear(UART_ID_Type uartId) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Clear rx fifo */ - tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); - BL_WR_REG(UARTx, UART_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, UART_RX_FIFO_CLR)); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief UART mask or unmask certain or all interrupt - * - * @param uartId: UART ID type - * @param intType: UART interrupt type - * @param intMask: UART interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_IntMask(UART_ID_Type uartId, UART_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_INT_TYPE(intType)); - CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); - - tmpVal = BL_RD_REG(UARTx, UART_INT_MASK); - - /* Mask or unmask certain or all interrupt */ - if (UART_INT_ALL == intType) { - if (MASK == intMask) { - tmpVal |= 0x1ff; - } else { - tmpVal &= 0; - } + * @brief UART mask or unmask certain or all interrupt + * + * @param uartId: UART ID type + * @param intType: UART interrupt type + * @param intMask: UART interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_IntMask(UART_ID_Type uartId, UART_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_INT_TYPE(intType)); + CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); + + tmpVal = BL_RD_REG(UARTx, UART_INT_MASK); + + /* Mask or unmask certain or all interrupt */ + if (UART_INT_ALL == intType) { + if (MASK == intMask) { + tmpVal |= 0x1ff; } else { - if (MASK == intMask) { - tmpVal |= 1 << intType; - } else { - tmpVal &= ~(1 << intType); - } + tmpVal &= 0; } - - /* Write back */ - BL_WR_REG(UARTx, UART_INT_MASK, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief UART clear certain or all interrupt - * - * @param uartId: UART ID type - * @param intType: UART interrupt type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_IntClear(UART_ID_Type uartId, UART_INT_Type intType) -{ - uint32_t tmpVal; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_INT_TYPE(intType)); - - tmpVal = BL_RD_REG(UARTx, UART_INT_CLEAR); - - /* Clear certain or all interrupt */ - if (UART_INT_ALL == intType) { - tmpVal |= 0x1ff; + } else { + if (MASK == intMask) { + tmpVal |= 1 << intType; } else { - tmpVal |= 1 << intType; + tmpVal &= ~(1 << intType); } + } - /* Write back */ - BL_WR_REG(UARTx, UART_INT_CLEAR, tmpVal); + /* Write back */ + BL_WR_REG(UARTx, UART_INT_MASK, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Install uart interrupt callback function - * - * @param uartId: UART ID type - * @param intType: UART interrupt type - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_Int_Callback_Install(UART_ID_Type uartId, UART_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_INT_TYPE(intType)); - - uartIntCbfArra[uartId][intType] = cbFun; - - return SUCCESS; + * @brief UART clear certain or all interrupt + * + * @param uartId: UART ID type + * @param intType: UART interrupt type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_IntClear(UART_ID_Type uartId, UART_INT_Type intType) { + uint32_t tmpVal; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_INT_TYPE(intType)); + + tmpVal = BL_RD_REG(UARTx, UART_INT_CLEAR); + + /* Clear certain or all interrupt */ + if (UART_INT_ALL == intType) { + tmpVal |= 0x1ff; + } else { + tmpVal |= 1 << intType; + } + + /* Write back */ + BL_WR_REG(UARTx, UART_INT_CLEAR, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART send data to tx fifo - * - * @param uartId: UART ID type - * @param data: The data to be send - * @param len: The length of the send buffer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SendData(UART_ID_Type uartId, uint8_t *data, uint32_t len) -{ - uint32_t txLen = 0; - uint32_t UARTx = uartAddr[uartId]; - uint32_t timeoutCnt = UART_TX_TIMEOUT_COUNT; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Send data */ - while (txLen < len) { - if (UART_GetTxFifoCount(uartId) > 0) { - BL_WR_BYTE(UARTx + UART_FIFO_WDATA_OFFSET, data[txLen++]); - timeoutCnt = UART_TX_TIMEOUT_COUNT; - } else { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } - - return SUCCESS; + * @brief Install uart interrupt callback function + * + * @param uartId: UART ID type + * @param intType: UART interrupt type + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_Int_Callback_Install(UART_ID_Type uartId, UART_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_INT_TYPE(intType)); + + uartIntCbfArra[uartId][intType] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART send data to tx fifo in block mode - * - * @param uartId: UART ID type - * @param data: The data to be send - * @param len: The length of the send buffer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SendDataBlock(UART_ID_Type uartId, uint8_t *data, uint32_t len) -{ - uint32_t txLen = 0; - uint32_t UARTx = uartAddr[uartId]; - uint32_t timeoutCnt = UART_TX_TIMEOUT_COUNT; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Send data */ - while (txLen < len) { - if (UART_GetTxFifoCount(uartId) > 0) { - BL_WR_BYTE(UARTx + UART_FIFO_WDATA_OFFSET, data[txLen++]); - timeoutCnt = UART_TX_TIMEOUT_COUNT; - } else { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + * @brief UART send data to tx fifo + * + * @param uartId: UART ID type + * @param data: The data to be send + * @param len: The length of the send buffer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SendData(UART_ID_Type uartId, uint8_t *data, uint32_t len) { + uint32_t txLen = 0; + uint32_t UARTx = uartAddr[uartId]; + uint32_t timeoutCnt = UART_TX_TIMEOUT_COUNT; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Send data */ + while (txLen < len) { + if (UART_GetTxFifoCount(uartId) > 0) { + BL_WR_BYTE(UARTx + UART_FIFO_WDATA_OFFSET, data[txLen++]); + timeoutCnt = UART_TX_TIMEOUT_COUNT; + } else { + timeoutCnt--; - while (UART_GetTxBusBusyStatus(uartId) == SET) { + if (timeoutCnt == 0) { + return TIMEOUT; + } } + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief UART receive data from rx fifo - * - * @param uartId: UART ID type - * @param data: The receive data buffer - * @param maxLen: The max length of the buffer - * - * @return The length of the received buffer - * -*******************************************************************************/ -uint32_t UART_ReceiveData(UART_ID_Type uartId, uint8_t *data, uint32_t maxLen) -{ - uint32_t rxLen = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Receive data */ - while (rxLen < maxLen && UART_GetRxFifoCount(uartId) > 0) { - data[rxLen++] = BL_RD_BYTE(UARTx + UART_FIFO_RDATA_OFFSET); + * @brief UART send data to tx fifo in block mode + * + * @param uartId: UART ID type + * @param data: The data to be send + * @param len: The length of the send buffer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SendDataBlock(UART_ID_Type uartId, uint8_t *data, uint32_t len) { + uint32_t txLen = 0; + uint32_t UARTx = uartAddr[uartId]; + uint32_t timeoutCnt = UART_TX_TIMEOUT_COUNT; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Send data */ + while (txLen < len) { + if (UART_GetTxFifoCount(uartId) > 0) { + BL_WR_BYTE(UARTx + UART_FIFO_WDATA_OFFSET, data[txLen++]); + timeoutCnt = UART_TX_TIMEOUT_COUNT; + } else { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; + } } + } - return rxLen; + while (UART_GetTxBusBusyStatus(uartId) == SET) {} + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART get auto baud count value - * - * @param uartId: UART ID type - * @param autoBaudDet: Detection using codeword 0x55 or start bit - * - * @return Bit period of auto baudrate detection - * -*******************************************************************************/ -uint16_t UART_GetAutoBaudCount(UART_ID_Type uartId, UART_AutoBaudDetection_Type autoBaudDet) -{ - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_AUTOBAUDDETECTION_TYPE(autoBaudDet)); - - /* Select 0x55 or start bit detection value */ - if (UART_AUTOBAUD_0X55 == autoBaudDet) { - return BL_RD_REG(UARTx, UART_STS_URX_ABR_PRD) >> 0x10 & 0xffff; - } else { - return BL_RD_REG(UARTx, UART_STS_URX_ABR_PRD) & 0xffff; - } + * @brief UART receive data from rx fifo + * + * @param uartId: UART ID type + * @param data: The receive data buffer + * @param maxLen: The max length of the buffer + * + * @return The length of the received buffer + * + *******************************************************************************/ +uint32_t UART_ReceiveData(UART_ID_Type uartId, uint8_t *data, uint32_t maxLen) { + uint32_t rxLen = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Receive data */ + while (rxLen < maxLen && UART_GetRxFifoCount(uartId) > 0) { + data[rxLen++] = BL_RD_BYTE(UARTx + UART_FIFO_RDATA_OFFSET); + } + + return rxLen; } /****************************************************************************/ /** - * @brief UART get tx fifo unoccupied count value - * - * @param uartId: UART ID type - * - * @return Tx fifo unoccupied count value - * -*******************************************************************************/ -uint8_t UART_GetTxFifoCount(UART_ID_Type uartId) -{ - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - return BL_GET_REG_BITS_VAL(BL_RD_REG(UARTx, UART_FIFO_CONFIG_1), UART_TX_FIFO_CNT); + * @brief UART get auto baud count value + * + * @param uartId: UART ID type + * @param autoBaudDet: Detection using codeword 0x55 or start bit + * + * @return Bit period of auto baudrate detection + * + *******************************************************************************/ +uint16_t UART_GetAutoBaudCount(UART_ID_Type uartId, UART_AutoBaudDetection_Type autoBaudDet) { + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_AUTOBAUDDETECTION_TYPE(autoBaudDet)); + + /* Select 0x55 or start bit detection value */ + if (UART_AUTOBAUD_0X55 == autoBaudDet) { + return BL_RD_REG(UARTx, UART_STS_URX_ABR_PRD) >> 0x10 & 0xffff; + } else { + return BL_RD_REG(UARTx, UART_STS_URX_ABR_PRD) & 0xffff; + } } /****************************************************************************/ /** - * @brief UART get rx fifo occupied count value - * - * @param uartId: UART ID type - * - * @return Rx fifo occupied count value - * -*******************************************************************************/ -uint8_t UART_GetRxFifoCount(UART_ID_Type uartId) -{ - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - return BL_GET_REG_BITS_VAL(BL_RD_REG(UARTx, UART_FIFO_CONFIG_1), UART_RX_FIFO_CNT); + * @brief UART get tx fifo unoccupied count value + * + * @param uartId: UART ID type + * + * @return Tx fifo unoccupied count value + * + *******************************************************************************/ +uint8_t UART_GetTxFifoCount(UART_ID_Type uartId) { + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + return BL_GET_REG_BITS_VAL(BL_RD_REG(UARTx, UART_FIFO_CONFIG_1), UART_TX_FIFO_CNT); } /****************************************************************************/ /** - * @brief Get uart interrupt status - * - * @param uartId: UART ID type - * @param intType: UART interrupt type - * - * @return Status of interrupt - * -*******************************************************************************/ -BL_Sts_Type UART_GetIntStatus(UART_ID_Type uartId, UART_INT_Type intType) -{ - uint32_t tmpVal; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_INT_TYPE(intType)); - - /* Get certain or all interrupt status */ - tmpVal = BL_RD_REG(UARTx, UART_INT_STS); - - if (UART_INT_ALL == intType) { - if ((tmpVal & 0x1ff) != 0) { - return SET; - } else { - return RESET; - } - } else { - if ((tmpVal & (1U << intType)) != 0) { - return SET; - } else { - return RESET; - } - } + * @brief UART get rx fifo occupied count value + * + * @param uartId: UART ID type + * + * @return Rx fifo occupied count value + * + *******************************************************************************/ +uint8_t UART_GetRxFifoCount(UART_ID_Type uartId) { + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + return BL_GET_REG_BITS_VAL(BL_RD_REG(UARTx, UART_FIFO_CONFIG_1), UART_RX_FIFO_CNT); } /****************************************************************************/ /** - * @brief Get indicator of uart tx bus busy - * - * @param uartId: UART ID type - * - * @return Status of tx bus - * -*******************************************************************************/ -BL_Sts_Type UART_GetTxBusBusyStatus(UART_ID_Type uartId) -{ - uint32_t tmpVal; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Get tx bus busy status */ - tmpVal = BL_RD_REG(UARTx, UART_STATUS); - - if (BL_IS_REG_BIT_SET(tmpVal, UART_STS_UTX_BUS_BUSY)) { - return SET; + * @brief Get uart interrupt status + * + * @param uartId: UART ID type + * @param intType: UART interrupt type + * + * @return Status of interrupt + * + *******************************************************************************/ +BL_Sts_Type UART_GetIntStatus(UART_ID_Type uartId, UART_INT_Type intType) { + uint32_t tmpVal; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_INT_TYPE(intType)); + + /* Get certain or all interrupt status */ + tmpVal = BL_RD_REG(UARTx, UART_INT_STS); + + if (UART_INT_ALL == intType) { + if ((tmpVal & 0x1ff) != 0) { + return SET; } else { - return RESET; + return RESET; } -} - -/****************************************************************************/ /** - * @brief Get indicator of uart rx bus busy - * - * @param uartId: UART ID type - * - * @return Status of rx bus - * -*******************************************************************************/ -BL_Sts_Type UART_GetRxBusBusyStatus(UART_ID_Type uartId) -{ - uint32_t tmpVal; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Get rx bus busy status */ - tmpVal = BL_RD_REG(UARTx, UART_STATUS); - - if (BL_IS_REG_BIT_SET(tmpVal, UART_STS_URX_BUS_BUSY)) { - return SET; + } else { + if ((tmpVal & (1U << intType)) != 0) { + return SET; } else { - return RESET; + return RESET; } + } } /****************************************************************************/ /** - * @brief Get tx/rx fifo overflow or underflow status - * - * @param uartId: UART ID type - * @param overflow: Select tx/rx overflow or underflow - * - * @return Status of tx/rx fifo - * -*******************************************************************************/ -BL_Sts_Type UART_GetOverflowStatus(UART_ID_Type uartId, UART_Overflow_Type overflow) -{ - uint32_t tmpVal; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_OVERFLOW_TYPE(overflow)); + * @brief Get indicator of uart tx bus busy + * + * @param uartId: UART ID type + * + * @return Status of tx bus + * + *******************************************************************************/ +BL_Sts_Type UART_GetTxBusBusyStatus(UART_ID_Type uartId) { + uint32_t tmpVal; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Get tx bus busy status */ + tmpVal = BL_RD_REG(UARTx, UART_STATUS); + + if (BL_IS_REG_BIT_SET(tmpVal, UART_STS_UTX_BUS_BUSY)) { + return SET; + } else { + return RESET; + } +} - /* Get tx/rx fifo overflow or underflow status */ - tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); +/****************************************************************************/ /** + * @brief Get indicator of uart rx bus busy + * + * @param uartId: UART ID type + * + * @return Status of rx bus + * + *******************************************************************************/ +BL_Sts_Type UART_GetRxBusBusyStatus(UART_ID_Type uartId) { + uint32_t tmpVal; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Get rx bus busy status */ + tmpVal = BL_RD_REG(UARTx, UART_STATUS); + + if (BL_IS_REG_BIT_SET(tmpVal, UART_STS_URX_BUS_BUSY)) { + return SET; + } else { + return RESET; + } +} - if ((tmpVal & (1U << (overflow + 4))) != 0) { - return SET; - } else { - return RESET; - } +/****************************************************************************/ /** + * @brief Get tx/rx fifo overflow or underflow status + * + * @param uartId: UART ID type + * @param overflow: Select tx/rx overflow or underflow + * + * @return Status of tx/rx fifo + * + *******************************************************************************/ +BL_Sts_Type UART_GetOverflowStatus(UART_ID_Type uartId, UART_Overflow_Type overflow) { + uint32_t tmpVal; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_OVERFLOW_TYPE(overflow)); + + /* Get tx/rx fifo overflow or underflow status */ + tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); + + if ((tmpVal & (1U << (overflow + 4))) != 0) { + return SET; + } else { + return RESET; + } } /****************************************************************************/ /** - * @brief UART0 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief UART0 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void UART0_IRQHandler(void) -{ - UART_IntHandler(UART0_ID); -} +void UART0_IRQHandler(void) { UART_IntHandler(UART0_ID); } #endif /****************************************************************************/ /** - * @brief UART1 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief UART1 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void UART1_IRQHandler(void) -{ - UART_IntHandler(UART1_ID); -} +void UART1_IRQHandler(void) { UART_IntHandler(UART1_ID); } #endif /*@} end of group UART_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_usb.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_usb.c index 647662655a..3b3b1f00ef 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_usb.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_usb.c @@ -1,42 +1,42 @@ /** - ****************************************************************************** - * @file bl70x_usb.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2019 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl70x_usb.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2019 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_usb.h" -#include "bl702_glb.h" #include "bl702_common.h" +#include "bl702_glb.h" /** @addtogroup BL70X_Peripheral_Driver * @{ @@ -86,2402 +86,2347 @@ * @{ */ -BL_Err_Type USB_Enable(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Enable(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EN); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EN); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Disable(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Disable(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EN); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EN); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_Config(BL_Fun_Type enable, USB_Config_Type *usbCfg) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_Config(BL_Fun_Type enable, USB_Config_Type *usbCfg) { + uint32_t tmpVal = 0; - /* disable USB first */ - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EN); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + /* disable USB first */ + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EN); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - /* USB config */ - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + /* USB config */ + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - if (usbCfg->SoftwareCtrl == ENABLE) { - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_ADDR, usbCfg->DeviceAddress); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_SIZE, usbCfg->EnumMaxPacketSize); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_NACK_IN, usbCfg->EnumInEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT, usbCfg->EnumOutEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_ROM_DCT_EN, usbCfg->RomBaseDescriptorUsed); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_ROM_DCT_EN, usbCfg->RomBaseDescriptorUsed); - } + if (usbCfg->SoftwareCtrl == ENABLE) { + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_ADDR, usbCfg->DeviceAddress); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_SIZE, usbCfg->EnumMaxPacketSize); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_NACK_IN, usbCfg->EnumInEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT, usbCfg->EnumOutEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_ROM_DCT_EN, usbCfg->RomBaseDescriptorUsed); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_ROM_DCT_EN, usbCfg->RomBaseDescriptorUsed); + } - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - /* enable/disable USB */ - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + /* enable/disable USB */ + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EN); - } + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EN); + } - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_Device_Addr(uint8_t addr) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_Device_Addr(uint8_t addr) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_ADDR, addr); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_ADDR, addr); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -uint8_t USB_Get_Device_Addr(void) -{ - uint32_t tmpVal = 0; +uint8_t USB_Get_Device_Addr(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - return BL_GET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_ADDR); + return BL_GET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_ADDR); } -BL_Err_Type USB_Set_EPx_Xfer_Size(USB_EP_ID epId, uint8_t size) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_Xfer_Size(USB_EP_ID epId, uint8_t size) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_SIZE, size); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_SIZE, size); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_IN_Busy(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_IN_Busy(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_IN_Stall(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_IN_Stall(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_OUT_Busy(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_OUT_Busy(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_OUT_Stall(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_OUT_Stall(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_Rdy(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; - - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } +BL_Err_Type USB_Set_EPx_Rdy(USB_EP_ID epId) { + uint32_t tmpVal = 0; + + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Sts_Type USB_Is_EPx_RDY_Free(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Sts_Type USB_Is_EPx_RDY_Free(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_USB_EP0_SW_RDY); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP1_RDY); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP2_RDY); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP3_RDY); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP4_RDY); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP5_RDY); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP6_RDY); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP7_RDY); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_USB_EP0_SW_RDY); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP1_RDY); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP2_RDY); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP3_RDY); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP4_RDY); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP5_RDY); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP6_RDY); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP7_RDY); + break; + + default: + break; } + } - return tmpVal ? RESET : SET; + return tmpVal ? RESET : SET; } -BL_Err_Type USB_Set_EPx_STALL(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_STALL(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Clr_EPx_STALL(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Clr_EPx_STALL(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - return SUCCESS; - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + return SUCCESS; + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_Busy(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_Busy(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_Status(USB_EP_ID epId, USB_EP_STATUS_Type sts) -{ - switch (sts) { - case USB_EP_STATUS_ACK: - USB_Set_EPx_Rdy(epId); - break; +BL_Err_Type USB_Set_EPx_Status(USB_EP_ID epId, USB_EP_STATUS_Type sts) { + switch (sts) { + case USB_EP_STATUS_ACK: + USB_Set_EPx_Rdy(epId); + break; - case USB_EP_STATUS_NACK: - USB_Set_EPx_Busy(epId); - break; + case USB_EP_STATUS_NACK: + USB_Set_EPx_Busy(epId); + break; - case USB_EP_STATUS_STALL: - USB_Set_EPx_STALL(epId); - break; + case USB_EP_STATUS_STALL: + USB_Set_EPx_STALL(epId); + break; - case USB_EP_STATUS_NSTALL: - USB_Clr_EPx_STALL(epId); - break; + case USB_EP_STATUS_NSTALL: + USB_Clr_EPx_STALL(epId); + break; - default: - break; - } + default: + break; + } - return SUCCESS; + return SUCCESS; } -USB_EP_STATUS_Type USB_Get_EPx_Status(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +USB_EP_STATUS_Type USB_Get_EPx_Status(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - switch ((tmpVal >> 24) & 0x7) { - case 0: - return USB_EP_STATUS_ACK; + switch ((tmpVal >> 24) & 0x7) { + case 0: + return USB_EP_STATUS_ACK; - case 1: - return USB_EP_STATUS_STALL; + case 1: + return USB_EP_STATUS_STALL; - case 2: - case 4: - case 6: - return USB_EP_STATUS_NACK; + case 2: + case 4: + case 6: + return USB_EP_STATUS_NACK; - default: - break; - } - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - break; - - default: - tmpVal = 0; - break; - } - - switch ((tmpVal >> 14) & 0x3) { - case 0: - return USB_EP_STATUS_ACK; - - case 1: - return USB_EP_STATUS_STALL; - - case 2: - return USB_EP_STATUS_NACK; - - case 3: - default: - break; - } + default: + break; } + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + break; - return USB_EP_STATUS_NSTALL; -} + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + break; -BL_Err_Type USB_IntEn(USB_INT_Type intType, uint8_t enable) -{ - uint32_t tmpVal = 0; + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + break; - if (USB_INT_ALL == intType) { - if (enable) { - BL_WR_REG(USB_BASE, USB_INT_EN, USB_INT_TYPE_ALL); - } else { - BL_WR_REG(USB_BASE, USB_INT_EN, ~USB_INT_TYPE_ALL); - } + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + break; - return SUCCESS; - } + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + break; - tmpVal = BL_RD_REG(USB_BASE, USB_INT_EN); + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + break; - if (enable) { - tmpVal |= (1 << intType); - } else { - tmpVal &= ~(1 << intType); - } + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + break; - BL_WR_REG(USB_BASE, USB_INT_EN, tmpVal); + default: + tmpVal = 0; + break; + } - return SUCCESS; -} + switch ((tmpVal >> 14) & 0x3) { + case 0: + return USB_EP_STATUS_ACK; -BL_Err_Type USB_IntMask(USB_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal = 0; + case 1: + return USB_EP_STATUS_STALL; - if (USB_INT_ALL == intType) { - if (intMask != UNMASK) { - BL_WR_REG(USB_BASE, USB_INT_MASK, USB_INT_TYPE_ALL); - } else { - BL_WR_REG(USB_BASE, USB_INT_MASK, ~USB_INT_TYPE_ALL); - } + case 2: + return USB_EP_STATUS_NACK; - return SUCCESS; + case 3: + default: + break; } + } - tmpVal = BL_RD_REG(USB_BASE, USB_INT_MASK); + return USB_EP_STATUS_NSTALL; +} - if (intMask != UNMASK) { - tmpVal |= (1 << intType); +BL_Err_Type USB_IntEn(USB_INT_Type intType, uint8_t enable) { + uint32_t tmpVal = 0; + + if (USB_INT_ALL == intType) { + if (enable) { + BL_WR_REG(USB_BASE, USB_INT_EN, USB_INT_TYPE_ALL); } else { - tmpVal &= ~(1 << intType); + BL_WR_REG(USB_BASE, USB_INT_EN, ~USB_INT_TYPE_ALL); } - BL_WR_REG(USB_BASE, USB_INT_MASK, tmpVal); - return SUCCESS; -} + } -BL_Sts_Type USB_Get_IntStatus(USB_INT_Type intType) -{ - if (USB_INT_ALL == intType) { - return BL_RD_REG(USB_BASE, USB_INT_STS) ? SET : RESET; - } + tmpVal = BL_RD_REG(USB_BASE, USB_INT_EN); - return ((BL_RD_REG(USB_BASE, USB_INT_STS) & (1 << intType))) ? SET : RESET; -} + if (enable) { + tmpVal |= (1 << intType); + } else { + tmpVal &= ~(1 << intType); + } + + BL_WR_REG(USB_BASE, USB_INT_EN, tmpVal); -BL_Err_Type USB_Clr_IntStatus(USB_INT_Type intType) -{ - uint32_t tmpVal = 0; + return SUCCESS; +} - if (USB_INT_ALL == intType) { - BL_WR_REG(USB_BASE, USB_INT_CLEAR, USB_INT_TYPE_ALL); +BL_Err_Type USB_IntMask(USB_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal = 0; - return SUCCESS; + if (USB_INT_ALL == intType) { + if (intMask != UNMASK) { + BL_WR_REG(USB_BASE, USB_INT_MASK, USB_INT_TYPE_ALL); + } else { + BL_WR_REG(USB_BASE, USB_INT_MASK, ~USB_INT_TYPE_ALL); } - tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); + return SUCCESS; + } + + tmpVal = BL_RD_REG(USB_BASE, USB_INT_MASK); + + if (intMask != UNMASK) { tmpVal |= (1 << intType); - BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); + } else { + tmpVal &= ~(1 << intType); + } - return SUCCESS; + BL_WR_REG(USB_BASE, USB_INT_MASK, tmpVal); + + return SUCCESS; } -BL_Err_Type USB_Clr_EPx_IntStatus(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Sts_Type USB_Get_IntStatus(USB_INT_Type intType) { + if (USB_INT_ALL == intType) { + return BL_RD_REG(USB_BASE, USB_INT_STS) ? SET : RESET; + } - tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); + return ((BL_RD_REG(USB_BASE, USB_INT_STS) & (1 << intType))) ? SET : RESET; +} - if (epId == EP_ID0) { - tmpVal |= (0x3F << 4); - } else { - tmpVal |= (0x3 << (epId * 2 + 8)); - } +BL_Err_Type USB_Clr_IntStatus(USB_INT_Type intType) { + uint32_t tmpVal = 0; - BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); + if (USB_INT_ALL == intType) { + BL_WR_REG(USB_BASE, USB_INT_CLEAR, USB_INT_TYPE_ALL); return SUCCESS; -} - -uint16_t USB_Get_Frame_Num(void) -{ - uint32_t tmpVal = 0; + } - tmpVal = BL_RD_REG(USB_BASE, USB_FRAME_NO); + tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); + tmpVal |= (1 << intType); + BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); - return tmpVal & 0x7ff; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_Config(USB_EP_ID epId, EP_Config_Type *epCfg) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Clr_EPx_IntStatus(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - return ERROR; - } + tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_TYPE, epCfg->type); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_DIR, epCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_SIZE, epCfg->EPMaxPacketSize); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_TYPE, epCfg->type); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_DIR, epCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_SIZE, epCfg->EPMaxPacketSize); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_TYPE, epCfg->type); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_DIR, epCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_SIZE, epCfg->EPMaxPacketSize); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_TYPE, epCfg->type); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_DIR, epCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_SIZE, epCfg->EPMaxPacketSize); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_TYPE, epCfg->type); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_DIR, epCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_SIZE, epCfg->EPMaxPacketSize); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_TYPE, epCfg->type); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_DIR, epCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_SIZE, epCfg->EPMaxPacketSize); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_TYPE, epCfg->type); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_DIR, epCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_SIZE, epCfg->EPMaxPacketSize); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal |= (0x3F << 4); + } else { + tmpVal |= (0x3 << (epId * 2 + 8)); + } - return SUCCESS; -} + BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); -BL_Err_Type USB_Set_EPx_Type(USB_EP_ID epId, EP_XFER_Type type) -{ - uint32_t tmpVal = 0; + return SUCCESS; +} - if (epId == EP_ID0) { - return ERROR; - } +uint16_t USB_Get_Frame_Num(void) { + uint32_t tmpVal = 0; - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_TYPE, type); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_TYPE, type); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_TYPE, type); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_TYPE, type); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_TYPE, type); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_TYPE, type); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_TYPE, type); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + tmpVal = BL_RD_REG(USB_BASE, USB_FRAME_NO); - return SUCCESS; + return tmpVal & 0x7ff; } -EP_XFER_Type USB_Get_EPx_Type(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; - - if (epId == EP_ID0) { - return EP_CTRL; - } +BL_Err_Type USB_Set_EPx_Config(USB_EP_ID epId, EP_Config_Type *epCfg) { + uint32_t tmpVal = 0; + + if (epId == EP_ID0) { + return ERROR; + } + + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_TYPE, epCfg->type); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_DIR, epCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_SIZE, epCfg->EPMaxPacketSize); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_TYPE, epCfg->type); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_DIR, epCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_SIZE, epCfg->EPMaxPacketSize); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_TYPE, epCfg->type); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_DIR, epCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_SIZE, epCfg->EPMaxPacketSize); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_TYPE, epCfg->type); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_DIR, epCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_SIZE, epCfg->EPMaxPacketSize); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_TYPE, epCfg->type); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_DIR, epCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_SIZE, epCfg->EPMaxPacketSize); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_TYPE, epCfg->type); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_DIR, epCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_SIZE, epCfg->EPMaxPacketSize); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_TYPE, epCfg->type); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_DIR, epCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_SIZE, epCfg->EPMaxPacketSize); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; + } + + return SUCCESS; +} - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP1_TYPE); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP2_TYPE); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP3_TYPE); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP4_TYPE); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP5_TYPE); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP6_TYPE); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP7_TYPE); - break; - - default: - break; - } +BL_Err_Type USB_Set_EPx_Type(USB_EP_ID epId, EP_XFER_Type type) { + uint32_t tmpVal = 0; + + if (epId == EP_ID0) { + return ERROR; + } + + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_TYPE, type); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_TYPE, type); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_TYPE, type); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_TYPE, type); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_TYPE, type); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_TYPE, type); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_TYPE, type); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; + } + + return SUCCESS; +} - return (EP_XFER_Type)tmpVal; +EP_XFER_Type USB_Get_EPx_Type(USB_EP_ID epId) { + uint32_t tmpVal = 0; + + if (epId == EP_ID0) { + return EP_CTRL; + } + + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP1_TYPE); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP2_TYPE); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP3_TYPE); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP4_TYPE); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP5_TYPE); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP6_TYPE); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP7_TYPE); + break; + + default: + break; + } + + return (EP_XFER_Type)tmpVal; } -BL_Err_Type USB_Set_EPx_Dir(USB_EP_ID epId, EP_XFER_DIR dir) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_Dir(USB_EP_ID epId, EP_XFER_DIR dir) { + uint32_t tmpVal = 0; + + if (epId == EP_ID0) { + return ERROR; + } + + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_DIR, dir); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_DIR, dir); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_DIR, dir); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_DIR, dir); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_DIR, dir); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_DIR, dir); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_DIR, dir); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; + } + + return SUCCESS; +} - if (epId == EP_ID0) { - return ERROR; - } +EP_XFER_DIR USB_Get_EPx_Dir(USB_EP_ID epId) { + uint32_t tmpVal = 0; + + if (epId == EP_ID0) { + return EP_DISABLED; + } + + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP1_DIR); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP2_DIR); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP3_DIR); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP4_DIR); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP5_DIR); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP6_DIR); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP7_DIR); + break; + + default: + break; + } + + return (EP_XFER_DIR)tmpVal; +} - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_DIR, dir); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_DIR, dir); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_DIR, dir); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_DIR, dir); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_DIR, dir); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_DIR, dir); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_DIR, dir); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } +BL_Err_Type USB_Set_EPx_Size(USB_EP_ID epId, uint32_t size) { + uint32_t tmpVal = 0; - return SUCCESS; + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_SIZE, size); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; + } + + return SUCCESS; } -EP_XFER_DIR USB_Get_EPx_Dir(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Sts_Type USB_Get_EPx_TX_FIFO_Errors(USB_EP_ID epId, USB_FIFO_ERROR_FLAG_Type errFlag) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - return EP_DISABLED; + if (errFlag == USB_FIFO_ERROR_OVERFLOW) { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_OVERFLOW); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_OVERFLOW); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_OVERFLOW); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_OVERFLOW); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_OVERFLOW); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_OVERFLOW); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_OVERFLOW); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_OVERFLOW); + break; + + default: + tmpVal = 0; + break; } - + } else { switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP1_DIR); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP2_DIR); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP3_DIR); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP4_DIR); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP5_DIR); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP6_DIR); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP7_DIR); - break; - - default: - break; + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_UNDERFLOW); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_UNDERFLOW); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_UNDERFLOW); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_UNDERFLOW); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_UNDERFLOW); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_UNDERFLOW); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_UNDERFLOW); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_UNDERFLOW); + break; + + default: + tmpVal = 0; + break; } + } - return (EP_XFER_DIR)tmpVal; + return tmpVal ? SET : RESET; } -BL_Err_Type USB_Set_EPx_Size(USB_EP_ID epId, uint32_t size) -{ - uint32_t tmpVal = 0; +BL_Sts_Type USB_Get_EPx_RX_FIFO_Errors(USB_EP_ID epId, USB_FIFO_ERROR_FLAG_Type errFlag) { + uint32_t tmpVal = 0; + if (errFlag == USB_FIFO_ERROR_OVERFLOW) { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_OVERFLOW); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_OVERFLOW); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_OVERFLOW); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_OVERFLOW); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_OVERFLOW); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_OVERFLOW); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_OVERFLOW); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_OVERFLOW); + break; + + default: + tmpVal = 0; + break; + } + } else { switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_SIZE, size); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_UNDERFLOW); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_UNDERFLOW); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_UNDERFLOW); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_UNDERFLOW); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_UNDERFLOW); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_UNDERFLOW); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_UNDERFLOW); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_UNDERFLOW); + break; + + default: + tmpVal = 0; + break; } + } - return SUCCESS; + return tmpVal ? SET : RESET; } -BL_Sts_Type USB_Get_EPx_TX_FIFO_Errors(USB_EP_ID epId, USB_FIFO_ERROR_FLAG_Type errFlag) -{ - uint32_t tmpVal = 0; - - if (errFlag == USB_FIFO_ERROR_OVERFLOW) { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_OVERFLOW); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_OVERFLOW); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_OVERFLOW); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_OVERFLOW); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_OVERFLOW); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_OVERFLOW); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_OVERFLOW); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_OVERFLOW); - break; - - default: - tmpVal = 0; - break; - } - } else { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_UNDERFLOW); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_UNDERFLOW); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_UNDERFLOW); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_UNDERFLOW); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_UNDERFLOW); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_UNDERFLOW); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_UNDERFLOW); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_UNDERFLOW); - break; - - default: - tmpVal = 0; - break; - } - } +BL_Err_Type USB_Clr_EPx_TX_FIFO_Errors(USB_EP_ID epId) { + uint32_t tmpVal = 0; + + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); + break; + + default: + break; + } + + return SUCCESS; +} - return tmpVal ? SET : RESET; +BL_Err_Type USB_Clr_EPx_RX_FIFO_Errors(USB_EP_ID epId) { + uint32_t tmpVal = 0; + + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); + break; + + default: + break; + } + + return SUCCESS; } -BL_Sts_Type USB_Get_EPx_RX_FIFO_Errors(USB_EP_ID epId, USB_FIFO_ERROR_FLAG_Type errFlag) -{ - uint32_t tmpVal = 0; - - if (errFlag == USB_FIFO_ERROR_OVERFLOW) { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_OVERFLOW); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_OVERFLOW); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_OVERFLOW); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_OVERFLOW); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_OVERFLOW); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_OVERFLOW); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_OVERFLOW); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_OVERFLOW); - break; - - default: - tmpVal = 0; - break; - } - } else { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_UNDERFLOW); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_UNDERFLOW); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_UNDERFLOW); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_UNDERFLOW); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_UNDERFLOW); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_UNDERFLOW); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_UNDERFLOW); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_UNDERFLOW); - break; - - default: - tmpVal = 0; - break; - } - } +BL_Err_Type USB_EPx_Write_Data_To_FIFO(USB_EP_ID epId, uint8_t *pData, uint16_t len) { + uint32_t timeout = 0x00FFFFFF; - return tmpVal ? SET : RESET; -} + while ((!USB_Is_EPx_RDY_Free(epId)) && timeout) { + timeout--; + } + + if (!timeout) { + return ERROR; + } -BL_Err_Type USB_Clr_EPx_TX_FIFO_Errors(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; + if (len == 1) { + USB_Set_EPx_Xfer_Size(EP_ID0, 1); + } else { + USB_Set_EPx_Xfer_Size(EP_ID0, 64); + } + for (uint16_t i = 0; i < len; i++) { switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); - break; - - default: - break; - } + case EP_ID0: + BL_WR_REG(USB_BASE, USB_EP0_TX_FIFO_WDATA, pData[i]); + break; - return SUCCESS; -} + case EP_ID1: + BL_WR_REG(USB_BASE, USB_EP1_TX_FIFO_WDATA, pData[i]); + break; -BL_Err_Type USB_Clr_EPx_RX_FIFO_Errors(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; + case EP_ID2: + BL_WR_REG(USB_BASE, USB_EP2_TX_FIFO_WDATA, pData[i]); + break; - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); - break; - - default: - break; - } + case EP_ID3: + BL_WR_REG(USB_BASE, USB_EP3_TX_FIFO_WDATA, pData[i]); + break; - return SUCCESS; -} + case EP_ID4: + BL_WR_REG(USB_BASE, USB_EP4_TX_FIFO_WDATA, pData[i]); + break; -BL_Err_Type USB_EPx_Write_Data_To_FIFO(USB_EP_ID epId, uint8_t *pData, uint16_t len) -{ - uint32_t timeout = 0x00FFFFFF; + case EP_ID5: + BL_WR_REG(USB_BASE, USB_EP5_TX_FIFO_WDATA, pData[i]); + break; - while ((!USB_Is_EPx_RDY_Free(epId)) && timeout) { - timeout--; - } + case EP_ID6: + BL_WR_REG(USB_BASE, USB_EP6_TX_FIFO_WDATA, pData[i]); + break; - if (!timeout) { - return ERROR; - } + case EP_ID7: + BL_WR_REG(USB_BASE, USB_EP7_TX_FIFO_WDATA, pData[i]); + break; - if (len == 1) { - USB_Set_EPx_Xfer_Size(EP_ID0, 1); - } else { - USB_Set_EPx_Xfer_Size(EP_ID0, 64); + default: + break; } + } + + return SUCCESS; +} - for (uint16_t i = 0; i < len; i++) { - switch (epId) { - case EP_ID0: - BL_WR_REG(USB_BASE, USB_EP0_TX_FIFO_WDATA, pData[i]); - break; +BL_Err_Type USB_EPx_Read_Data_From_FIFO(USB_EP_ID epId, uint8_t *pBuff, uint16_t len) { + for (uint16_t i = 0; i < len; i++) { + switch (epId) { + case EP_ID0: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP0_RX_FIFO_RDATA); + break; - case EP_ID1: - BL_WR_REG(USB_BASE, USB_EP1_TX_FIFO_WDATA, pData[i]); - break; + case EP_ID1: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP1_RX_FIFO_RDATA); + break; - case EP_ID2: - BL_WR_REG(USB_BASE, USB_EP2_TX_FIFO_WDATA, pData[i]); - break; + case EP_ID2: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP2_RX_FIFO_RDATA); + break; - case EP_ID3: - BL_WR_REG(USB_BASE, USB_EP3_TX_FIFO_WDATA, pData[i]); - break; + case EP_ID3: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP3_RX_FIFO_RDATA); + break; - case EP_ID4: - BL_WR_REG(USB_BASE, USB_EP4_TX_FIFO_WDATA, pData[i]); - break; + case EP_ID4: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP4_RX_FIFO_RDATA); + break; - case EP_ID5: - BL_WR_REG(USB_BASE, USB_EP5_TX_FIFO_WDATA, pData[i]); - break; + case EP_ID5: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP5_RX_FIFO_RDATA); + break; - case EP_ID6: - BL_WR_REG(USB_BASE, USB_EP6_TX_FIFO_WDATA, pData[i]); - break; + case EP_ID6: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP6_RX_FIFO_RDATA); + break; - case EP_ID7: - BL_WR_REG(USB_BASE, USB_EP7_TX_FIFO_WDATA, pData[i]); - break; + case EP_ID7: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP7_RX_FIFO_RDATA); + break; - default: - break; - } + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_EPx_Read_Data_From_FIFO(USB_EP_ID epId, uint8_t *pBuff, uint16_t len) -{ - for (uint16_t i = 0; i < len; i++) { - switch (epId) { - case EP_ID0: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP0_RX_FIFO_RDATA); - break; - - case EP_ID1: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP1_RX_FIFO_RDATA); - break; - - case EP_ID2: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP2_RX_FIFO_RDATA); - break; - - case EP_ID3: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP3_RX_FIFO_RDATA); - break; - - case EP_ID4: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP4_RX_FIFO_RDATA); - break; - - case EP_ID5: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP5_RX_FIFO_RDATA); - break; - - case EP_ID6: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP6_RX_FIFO_RDATA); - break; - - case EP_ID7: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP7_RX_FIFO_RDATA); - break; - - default: - break; - } +BL_Err_Type USB_Set_EPx_TX_DMA_Interface_Config(USB_EP_ID epId, BL_Fun_Type newState) { + uint32_t tmpVal = 0; + + if (newState == ENABLE) { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); + break; + + default: + break; + } + } else { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP0_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP1_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP2_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP3_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP4_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP5_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP6_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP7_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_TX_DMA_Interface_Config(USB_EP_ID epId, BL_Fun_Type newState) -{ - uint32_t tmpVal = 0; - - if (newState == ENABLE) { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); - break; - - default: - break; - } - } else { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP0_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP1_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP2_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP3_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP4_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP5_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP6_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP7_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); - break; - - default: - break; - } +BL_Err_Type USB_Set_EPx_RX_DMA_Interface_Config(USB_EP_ID epId, BL_Fun_Type newState) { + uint32_t tmpVal = 0; + + if (newState == ENABLE) { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); + break; + + default: + break; + } + } else { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP0_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP1_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP2_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP3_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP4_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP5_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP6_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP7_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_RX_DMA_Interface_Config(USB_EP_ID epId, BL_Fun_Type newState) -{ - uint32_t tmpVal = 0; - - if (newState == ENABLE) { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); - break; - - default: - break; - } - } else { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP0_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP1_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP2_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP3_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP4_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP5_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP6_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP7_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); - break; - - default: - break; - } - } +BL_Err_Type USB_EPx_Write_Data_To_FIFO_DMA(USB_EP_ID epId, uint8_t *pData, uint16_t len) { + /* not yet implemented */ - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_EPx_Write_Data_To_FIFO_DMA(USB_EP_ID epId, uint8_t *pData, uint16_t len) -{ - /* not yet implemented */ +BL_Err_Type USB_EPx_Read_Data_From_FIFO_DMA(USB_EP_ID epId, uint8_t *pBuff, uint16_t len) { + /* not yet implemented */ - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_EPx_Read_Data_From_FIFO_DMA(USB_EP_ID epId, uint8_t *pBuff, uint16_t len) -{ - /* not yet implemented */ +uint16_t USB_Get_EPx_TX_FIFO_CNT(USB_EP_ID epId) { + uint32_t tmpVal = 0; + + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_CNT); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_CNT); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_CNT); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_CNT); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_CNT); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_CNT); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_CNT); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_CNT); + break; + + default: + tmpVal = 0; + break; + } + + return tmpVal; +} - return SUCCESS; +uint16_t USB_Get_EPx_RX_FIFO_CNT(USB_EP_ID epId) { + uint32_t tmpVal = 0; + + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_CNT); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_CNT); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_CNT); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_CNT); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_CNT); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_CNT); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_CNT); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_CNT); + break; + + default: + tmpVal = 0; + break; + } + + return tmpVal; } -uint16_t USB_Get_EPx_TX_FIFO_CNT(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Sts_Type USB_Get_EPx_TX_FIFO_Status(USB_EP_ID epId, USB_FIFO_STATUS_Type sts) { + uint32_t tmpVal = 0; + if (sts == USB_FIFO_EMPTY) { switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_CNT); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_CNT); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_CNT); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_CNT); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_CNT); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_CNT); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_CNT); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_CNT); - break; - - default: - tmpVal = 0; - break; + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_EMPTY); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_EMPTY); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_EMPTY); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_EMPTY); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_EMPTY); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_EMPTY); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_EMPTY); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_EMPTY); + break; + + default: + tmpVal = 0; + break; } - - return tmpVal; -} - -uint16_t USB_Get_EPx_RX_FIFO_CNT(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; - + } else { switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_CNT); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_CNT); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_CNT); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_CNT); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_CNT); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_CNT); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_CNT); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_CNT); - break; - - default: - tmpVal = 0; - break; + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_FULL); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_FULL); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_FULL); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_FULL); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_FULL); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_FULL); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_FULL); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_FULL); + break; + + default: + tmpVal = 0; + break; } + } - return tmpVal; + return tmpVal ? SET : RESET; } -BL_Sts_Type USB_Get_EPx_TX_FIFO_Status(USB_EP_ID epId, USB_FIFO_STATUS_Type sts) -{ - uint32_t tmpVal = 0; - - if (sts == USB_FIFO_EMPTY) { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_EMPTY); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_EMPTY); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_EMPTY); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_EMPTY); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_EMPTY); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_EMPTY); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_EMPTY); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_EMPTY); - break; - - default: - tmpVal = 0; - break; - } - } else { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_FULL); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_FULL); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_FULL); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_FULL); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_FULL); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_FULL); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_FULL); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_FULL); - break; - - default: - tmpVal = 0; - break; - } - } - - return tmpVal ? SET : RESET; -} +BL_Sts_Type USB_Get_EPx_RX_FIFO_Status(USB_EP_ID epId, USB_FIFO_STATUS_Type sts) { + uint32_t tmpVal = 0; -BL_Sts_Type USB_Get_EPx_RX_FIFO_Status(USB_EP_ID epId, USB_FIFO_STATUS_Type sts) -{ - uint32_t tmpVal = 0; - - if (sts == USB_FIFO_EMPTY) { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_EMPTY); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_EMPTY); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_EMPTY); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_EMPTY); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_EMPTY); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_EMPTY); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_EMPTY); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_EMPTY); - break; - - default: - tmpVal = 0; - break; - } - } else { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_FULL); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_FULL); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_FULL); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_FULL); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_FULL); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_FULL); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_FULL); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_FULL); - break; - - default: - tmpVal = 0; - break; - } + if (sts == USB_FIFO_EMPTY) { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_EMPTY); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_EMPTY); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_EMPTY); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_EMPTY); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_EMPTY); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_EMPTY); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_EMPTY); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_EMPTY); + break; + + default: + tmpVal = 0; + break; } + } else { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_FULL); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_FULL); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_FULL); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_FULL); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_FULL); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_FULL); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_FULL); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_FULL); + break; + + default: + tmpVal = 0; + break; + } + } - return tmpVal ? SET : RESET; + return tmpVal ? SET : RESET; } -BL_Err_Type USB_Set_Internal_PullUp_Config(BL_Fun_Type newState) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_Internal_PullUp_Config(BL_Fun_Type newState) { + uint32_t tmpVal = 0; - /* recommended: fclk<=160MHz, bclk<=80MHz */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, newState); - BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal); + /* recommended: fclk<=160MHz, bclk<=80MHz */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, newState); + BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Sts_Type USB_Get_LPM_Status(void) -{ - uint32_t tmpVal = 0; +BL_Sts_Type USB_Get_LPM_Status(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); + tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); - return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_LPM) ? SET : RESET; + return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_LPM) ? SET : RESET; } -uint16_t USB_Get_LPM_Packet_Attr(void) -{ - uint32_t tmpVal = 0; +uint16_t USB_Get_LPM_Packet_Attr(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); + tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); - return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_LPM_ATTR); + return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_LPM_ATTR); } -BL_Err_Type USB_Set_LPM_Default_Response(USB_LPM_DEFAULT_RESP_Type defaultResp) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_LPM_Default_Response(USB_LPM_DEFAULT_RESP_Type defaultResp) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_LPM_RESP, defaultResp); - BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_LPM_RESP, defaultResp); + BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); - tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_LPM_RESP_UPD); - BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_LPM_RESP_UPD); + BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_LPM_Enable(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_LPM_Enable(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_LPM_EN); - BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_LPM_EN); + BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_LPM_Disable(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_LPM_Disable(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_LPM_EN); - BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_LPM_EN); + BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Device_Output_K_State(uint16_t stateWidth) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Device_Output_K_State(uint16_t stateWidth) { + uint32_t tmpVal = 0; - CHECK_PARAM((stateWidth <= 0x7FF)); + CHECK_PARAM((stateWidth <= 0x7FF)); - tmpVal = BL_RD_REG(USB_BASE, USB_RESUME_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_RES_WIDTH, stateWidth); - BL_WR_REG(USB_BASE, USB_RESUME_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_RESUME_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_RES_WIDTH, stateWidth); + BL_WR_REG(USB_BASE, USB_RESUME_CONFIG, tmpVal); - tmpVal = BL_RD_REG(USB_BASE, USB_RESUME_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_RES_TRIG); - BL_WR_REG(USB_BASE, USB_RESUME_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_RESUME_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_RES_TRIG); + BL_WR_REG(USB_BASE, USB_RESUME_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -uint8_t USB_Get_Current_Packet_PID(void) -{ - uint32_t tmpVal = 0; +uint8_t USB_Get_Current_Packet_PID(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_FRAME_NO); + tmpVal = BL_RD_REG(USB_BASE, USB_FRAME_NO); - return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_PID); + return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_PID); } -uint8_t USB_Get_Current_Packet_EP(void) -{ - uint32_t tmpVal = 0; +uint8_t USB_Get_Current_Packet_EP(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_FRAME_NO); + tmpVal = BL_RD_REG(USB_BASE, USB_FRAME_NO); - return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP_NO); + return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP_NO); } -BL_Sts_Type USB_Get_Error_Status(USB_ERROR_Type err) -{ - uint32_t tmpVal = 0; +BL_Sts_Type USB_Get_Error_Status(USB_ERROR_Type err) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_ERROR); + tmpVal = BL_RD_REG(USB_BASE, USB_ERROR); - return tmpVal & (1 << err) ? SET : RESET; + return tmpVal & (1 << err) ? SET : RESET; } -BL_Err_Type USB_Clr_Error_Status(USB_ERROR_Type err) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Clr_Error_Status(USB_ERROR_Type err) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); - tmpVal |= (1 << USB_INT_ERROR); - BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); + tmpVal |= (1 << USB_INT_ERROR); + BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Clr_RstEndIntStatus(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Clr_RstEndIntStatus(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); - tmpVal |= (1 << 27); - BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); + tmpVal |= (1 << 27); + BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); - return SUCCESS; + return SUCCESS; } /*@} end of group USB_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash.c index 23c28a6391..a53efa2c47 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_xip_sflash.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_xip_sflash.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "string.h" #include "bl702_xip_sflash.h" +#include "string.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -81,99 +81,95 @@ static uint8_t aesEnable; */ /****************************************************************************/ /** - * @brief XIP SFlash option save - * - * @param None - * - * @return None - * -*******************************************************************************/ -void ATTR_TCM_SECTION XIP_SFlash_Opt_Enter(void) -{ - aesEnable = SF_Ctrl_Is_AES_Enable(); - - if (aesEnable) { - SF_Ctrl_AES_Disable(); - } + * @brief XIP SFlash option save + * + * @param None + * + * @return None + * + *******************************************************************************/ +void ATTR_TCM_SECTION XIP_SFlash_Opt_Enter(void) { + aesEnable = SF_Ctrl_Is_AES_Enable(); + + if (aesEnable) { + SF_Ctrl_AES_Disable(); + } } /****************************************************************************/ /** - * @brief XIP SFlash option restore - * - * @param None - * - * @return None - * -*******************************************************************************/ -void ATTR_TCM_SECTION XIP_SFlash_Opt_Exit(void) -{ - if (aesEnable) { - SF_Ctrl_AES_Enable(); - } + * @brief XIP SFlash option restore + * + * @param None + * + * @return None + * + *******************************************************************************/ +void ATTR_TCM_SECTION XIP_SFlash_Opt_Exit(void) { + if (aesEnable) { + SF_Ctrl_AES_Enable(); + } } /****************************************************************************/ /** - * @brief Save flash controller state - * - * @param pFlashCfg: Flash config pointer - * @param offset: CPU XIP flash offset pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Save flash controller state + * + * @param pFlashCfg: Flash config pointer + * @param offset: CPU XIP flash offset pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_State_Save(SPI_Flash_Cfg_Type *pFlashCfg, uint32_t *offset) -{ - /* XIP_SFlash_Delay */ - volatile uint32_t i = 32 * 2; - - while (i--) - ; - - SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB); - /* Exit form continous read for accepting command */ - SFlash_Reset_Continue_Read(pFlashCfg); - /* Send software reset command(80bv has no this command)to deburst wrap for ISSI like */ - SFlash_Software_Reset(pFlashCfg); - /* For disable command that is setting register instaed of send command, we need write enable */ - SFlash_DisableBurstWrap(pFlashCfg); - /* Enable QE again in case reset command make it reset */ - SFlash_Qspi_Enable(pFlashCfg); - /* Deburst again to make sure */ - SFlash_DisableBurstWrap(pFlashCfg); - - /* Clear offset setting*/ - *offset = SF_Ctrl_Get_Flash_Image_Offset(); - SF_Ctrl_Set_Flash_Image_Offset(0); - - return SUCCESS; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_State_Save(SPI_Flash_Cfg_Type *pFlashCfg, uint32_t *offset) { + /* XIP_SFlash_Delay */ + volatile uint32_t i = 32 * 2; + + while (i--) + ; + + SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB); + /* Exit form continous read for accepting command */ + SFlash_Reset_Continue_Read(pFlashCfg); + /* Send software reset command(80bv has no this command)to deburst wrap for ISSI like */ + SFlash_Software_Reset(pFlashCfg); + /* For disable command that is setting register instaed of send command, we need write enable */ + SFlash_DisableBurstWrap(pFlashCfg); + /* Enable QE again in case reset command make it reset */ + SFlash_Qspi_Enable(pFlashCfg); + /* Deburst again to make sure */ + SFlash_DisableBurstWrap(pFlashCfg); + + /* Clear offset setting*/ + *offset = SF_Ctrl_Get_Flash_Image_Offset(); + SF_Ctrl_Set_Flash_Image_Offset(0); + + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Restore flash controller state - * - * @param pFlashCfg: Flash config pointer - * @param ioMode: flash controller interface mode - * @param offset: CPU XIP flash offset - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Restore flash controller state + * + * @param pFlashCfg: Flash config pointer + * @param ioMode: flash controller interface mode + * @param offset: CPU XIP flash offset + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_State_Restore(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t offset) -{ - uint32_t tmp[1]; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_State_Restore(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t offset) { + uint32_t tmp[1]; - SF_Ctrl_Set_Flash_Image_Offset(offset); + SF_Ctrl_Set_Flash_Image_Offset(offset); - SFlash_SetBurstWrap(pFlashCfg); - SFlash_Read(pFlashCfg, ioMode, 1, 0x0, (uint8_t *)tmp, sizeof(tmp)); - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + SFlash_SetBurstWrap(pFlashCfg); + SFlash_Read(pFlashCfg, ioMode, 1, 0x0, (uint8_t *)tmp, sizeof(tmp)); + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - return SUCCESS; + return SUCCESS; } #endif @@ -184,216 +180,209 @@ BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_State_Restore(SPI_Flash_Cfg_Type *pFlash */ /****************************************************************************/ /** - * @brief Erase flash one region - * - * @param pFlashCfg: Flash config pointer - * @param ioMode: flash controller interface mode - * @param startaddr: start address to erase - * @param endaddr: end address(include this address) to erase - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Erase flash one region + * + * @param pFlashCfg: Flash config pointer + * @param ioMode: flash controller interface mode + * @param startaddr: start address to erase + * @param endaddr: end address(include this address) to erase + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Erase_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t startaddr, uint32_t endaddr) -{ - BL_Err_Type stat; - uint32_t offset; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Erase_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t startaddr, uint32_t endaddr) { + BL_Err_Type stat; + uint32_t offset; - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - stat = SFlash_Erase(pFlashCfg, startaddr, endaddr); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + stat = SFlash_Erase(pFlashCfg, startaddr, endaddr); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } - return stat; + return stat; } #endif /****************************************************************************/ /** - * @brief Program flash one region - * - * @param pFlashCfg: Flash config pointer - * @param ioMode: flash controller interface mode - * @param addr: start address to be programed - * @param data: data pointer to be programed - * @param len: data length to be programed - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Program flash one region + * + * @param pFlashCfg: Flash config pointer + * @param ioMode: flash controller interface mode + * @param addr: start address to be programed + * @param data: data pointer to be programed + * @param len: data length to be programed + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Write_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - BL_Err_Type stat; - uint32_t offset; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Write_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + BL_Err_Type stat; + uint32_t offset; - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - stat = SFlash_Program(pFlashCfg, ioMode, addr, data, len); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + stat = SFlash_Program(pFlashCfg, ioMode, addr, data, len); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } - return stat; + return stat; } #endif /****************************************************************************/ /** - * @brief Read data from flash - * - * @param pFlashCfg: Flash config pointer - * @param ioMode: flash controller interface mode - * @param addr: flash read start address - * @param data: data pointer to store data read from flash - * @param len: data length to read - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Read data from flash + * + * @param pFlashCfg: Flash config pointer + * @param ioMode: flash controller interface mode + * @param addr: flash read start address + * @param data: data pointer to store data read from flash + * @param len: data length to read + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Read_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - BL_Err_Type stat; - uint32_t offset; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Read_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + BL_Err_Type stat; + uint32_t offset; - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - stat = SFlash_Read(pFlashCfg, ioMode, 0, addr, data, len); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + stat = SFlash_Read(pFlashCfg, ioMode, 0, addr, data, len); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } - return stat; + return stat; } #endif /****************************************************************************/ /** - * @brief Get Flash Jedec ID - * - * @param pFlashCfg: Flash config pointer - * @param ioMode: flash controller interface mode - * @param data: data pointer to store Jedec ID Read from flash - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Get Flash Jedec ID + * + * @param pFlashCfg: Flash config pointer + * @param ioMode: flash controller interface mode + * @param data: data pointer to store Jedec ID Read from flash + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetJedecId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) -{ - BL_Err_Type stat; - uint32_t offset; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetJedecId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) { + BL_Err_Type stat; + uint32_t offset; - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - SFlash_GetJedecId(pFlashCfg, data); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + SFlash_GetJedecId(pFlashCfg, data); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Get Flash Device ID - * - * @param pFlashCfg: Flash config pointer - * @param ioMode: flash controller interface mode - * @param data: data pointer to store Device ID Read from flash - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Get Flash Device ID + * + * @param pFlashCfg: Flash config pointer + * @param ioMode: flash controller interface mode + * @param data: data pointer to store Device ID Read from flash + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetDeviceId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) -{ - BL_Err_Type stat; - uint32_t offset; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetDeviceId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) { + BL_Err_Type stat; + uint32_t offset; - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - SFlash_GetDeviceId(data); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + SFlash_GetDeviceId(data); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Get Flash Unique ID - * - * @param pFlashCfg: Flash config pointer - * @param ioMode: flash controller interface mode - * @param data: data pointer to store Device ID Read from flash - * @param idLen: Unique id len - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Get Flash Unique ID + * + * @param pFlashCfg: Flash config pointer + * @param ioMode: flash controller interface mode + * @param data: data pointer to store Device ID Read from flash + * @param idLen: Unique id len + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetUniqueId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data, uint8_t idLen) -{ - BL_Err_Type stat; - uint32_t offset; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetUniqueId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data, uint8_t idLen) { + BL_Err_Type stat; + uint32_t offset; - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - SFlash_GetUniqueId(data, idLen); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + SFlash_GetUniqueId(data, idLen); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Read data from flash via XIP - * - * @param addr: flash read start address - * @param data: data pointer to store data read from flash - * @param len: data length to read - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Read data from flash via XIP + * + * @param addr: flash read start address + * @param data: data pointer to store data read from flash + * @param len: data length to read + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Read_Via_Cache_Need_Lock(uint32_t addr, uint8_t *data, uint32_t len) -{ - uint32_t offset; - - if (addr >= BL702_FLASH_XIP_BASE && addr < BL702_FLASH_XIP_END) { - offset = SF_Ctrl_Get_Flash_Image_Offset(); - SF_Ctrl_Set_Flash_Image_Offset(0); - /* Flash read */ - BL702_MemCpy_Fast(data, (void *)(addr - SF_Ctrl_Get_Flash_Image_Offset()), len); - SF_Ctrl_Set_Flash_Image_Offset(offset); - } - - return SUCCESS; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Read_Via_Cache_Need_Lock(uint32_t addr, uint8_t *data, uint32_t len) { + uint32_t offset; + + if (addr >= BL702_FLASH_XIP_BASE && addr < BL702_FLASH_XIP_END) { + offset = SF_Ctrl_Get_Flash_Image_Offset(); + SF_Ctrl_Set_Flash_Image_Offset(0); + /* Flash read */ + BL702_MemCpy_Fast(data, (void *)(addr - SF_Ctrl_Get_Flash_Image_Offset()), len); + SF_Ctrl_Set_Flash_Image_Offset(offset); + } + + return SUCCESS; } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash_ext.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash_ext.c index 2f75785da9..a4065391e4 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash_ext.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash_ext.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_xip_sflash_ext.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_xip_sflash_ext.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "string.h" #include "bl702_xip_sflash_ext.h" +#include "string.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -79,57 +79,55 @@ * @{ */ -/****************************************************************************//** - * @brief XIP KH25V40 flash write protect set - * - * @param pFlashCfg: Flash config pointer - * @param protect: protect area - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ +/****************************************************************************/ /** + * @brief XIP KH25V40 flash write protect set + * + * @param pFlashCfg: Flash config pointer + * @param protect: protect area + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_KH25V40_Write_Protect_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SFlash_Protect_Kh25v40_Type protect) -{ - BL_Err_Type stat; - uint32_t offset; - SF_Ctrl_IO_Type ioMode = (SF_Ctrl_IO_Type)pFlashCfg->ioMode&0xf; - - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - stat = SFlash_KH25V40_Write_Protect(pFlashCfg, protect); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } - - return stat; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_KH25V40_Write_Protect_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SFlash_Protect_Kh25v40_Type protect) { + BL_Err_Type stat; + uint32_t offset; + SF_Ctrl_IO_Type ioMode = (SF_Ctrl_IO_Type)pFlashCfg->ioMode & 0xf; + + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + stat = SFlash_KH25V40_Write_Protect(pFlashCfg, protect); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } + + return stat; } -/****************************************************************************//** - * @brief Clear flash status register need lock - * - * @param pFlashCfg: Flash config pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ +/****************************************************************************/ /** + * @brief Clear flash status register need lock + * + * @param pFlashCfg: Flash config pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Clear_Status_Register_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg) -{ - BL_Err_Type stat; - uint32_t offset; - SF_Ctrl_IO_Type ioMode = (SF_Ctrl_IO_Type)pFlashCfg->ioMode&0xf; - - stat=XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - stat=SFlash_Clear_Status_Register(pFlashCfg); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } - - return stat; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Clear_Status_Register_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg) { + BL_Err_Type stat; + uint32_t offset; + SF_Ctrl_IO_Type ioMode = (SF_Ctrl_IO_Type)pFlashCfg->ioMode & 0xf; + + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + stat = SFlash_Clear_Status_Register(pFlashCfg); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } + + return stat; } /*@} end of group XIP_SFLASH_EXT_Public_Functions */ diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c index f29ea6c512..712af4d4c1 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c +++ b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c @@ -1194,7 +1194,6 @@ HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef *hadc, uint32_t *pData, ui /* Set the DMA transfer complete callback */ hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt; - /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */ /* start (in case of SW start): */ @@ -1352,7 +1351,6 @@ void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc) { } } - /* Clear regular group conversion flag */ __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_STRT | ADC_FLAG_EOC); } @@ -1393,12 +1391,8 @@ void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc) { __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_JSTRT | ADC_FLAG_JEOC)); } } - - } - - /** * @} */ @@ -1438,7 +1432,7 @@ void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc) { * @retval HAL status */ HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef *hadc, ADC_ChannelConfTypeDef *sConfig) { - HAL_StatusTypeDef tmp_hal_status = HAL_OK; + HAL_StatusTypeDef tmp_hal_status = HAL_OK; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); @@ -1472,8 +1466,6 @@ HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef *hadc, ADC_ChannelConf MODIFY_REG(hadc->Instance->SMPR2, ADC_SMPR2(ADC_SMPR2_SMP0, sConfig->Channel), ADC_SMPR2(sConfig->SamplingTime, sConfig->Channel)); } - - /* Process unlocked */ __HAL_UNLOCK(hadc); @@ -1712,11 +1704,6 @@ void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma) { } } - - - - - /** * @} */ diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c index dc2e20e8ad..8412668478 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c +++ b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c @@ -661,7 +661,6 @@ HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef *hadc, uint32_t /* Set the DMA transfer complete callback */ hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt; - /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */ /* start (in case of SW start): */ @@ -899,7 +898,7 @@ __weak void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc) { * @retval None */ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_InjectionConfTypeDef *sConfigInjected) { - HAL_StatusTypeDef tmp_hal_status = HAL_OK; + HAL_StatusTypeDef tmp_hal_status = HAL_OK; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); @@ -1028,9 +1027,6 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_I MODIFY_REG(hadc->Instance->SMPR2, ADC_SMPR2(ADC_SMPR2_SMP0, sConfigInjected->InjectedChannel), ADC_SMPR2(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel)); } - - - /* Configure the offset: offset enable/disable, InjectedChannel, offset value */ switch (sConfigInjected->InjectedRank) { case 1: @@ -1051,7 +1047,6 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_I break; } - /* Process unlocked */ __HAL_UNLOCK(hadc); diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c index 5dd8b7c771..b442a4432b 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c +++ b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c @@ -956,8 +956,6 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData /* Clear ADDR flag */ __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - while (hi2c->XferSize > 0U) { /* Wait until TXE flag is set */ if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { @@ -3717,7 +3715,6 @@ static HAL_StatusTypeDef I2C_Master_SB(I2C_HandleTypeDef *hi2c) { return HAL_OK; } - /** * @brief Handle ADDR flag for Master * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains @@ -3963,7 +3960,6 @@ static HAL_StatusTypeDef I2C_MasterRequestWrite(I2C_HandleTypeDef *hi2c, uint16_ /* Send slave address */ hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(DevAddress); } - /* Wait until ADDR flag is set */ if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { @@ -4012,7 +4008,6 @@ static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t /* Send slave address */ hi2c->Instance->DR = I2C_7BIT_ADD_READ(DevAddress); } - /* Wait until ADDR flag is set */ if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c index d700f0caba..a3735b9b82 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c +++ b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c @@ -470,8 +470,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { /* Check if PLLI2S is enabled */ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) { /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; + pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul)); } } @@ -490,8 +490,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { /* Check if PLLI2S is enabled */ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) { /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; + pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul)); } } diff --git a/source/Core/brieflz/brieflz.c b/source/Core/brieflz/brieflz.c index e197f573bf..84fb061f46 100644 --- a/source/Core/brieflz/brieflz.c +++ b/source/Core/brieflz/brieflz.c @@ -32,14 +32,14 @@ #include #if _MSC_VER >= 1400 -# include -# define BLZ_BUILTIN_MSVC +#include +#define BLZ_BUILTIN_MSVC #elif defined(__clang__) && defined(__has_builtin) -# if __has_builtin(__builtin_clz) -# define BLZ_BUILTIN_GCC -# endif +#if __has_builtin(__builtin_clz) +#define BLZ_BUILTIN_GCC +#endif #elif __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) -# define BLZ_BUILTIN_GCC +#define BLZ_BUILTIN_GCC #endif // Type used to store values in workmem. @@ -60,270 +60,161 @@ typedef uint32_t blz_word; // compromise. // #ifndef BLZ_HASH_BITS -# define BLZ_HASH_BITS 17 +#define BLZ_HASH_BITS 17 #endif #define LOOKUP_SIZE (1UL << BLZ_HASH_BITS) -#define NO_MATCH_POS ((blz_word) -1) +#define NO_MATCH_POS ((blz_word)-1) // Internal data structure struct blz_state { - unsigned char *next_out; - unsigned char *tag_out; - unsigned int tag; - int bits_left; + unsigned char *next_out; + unsigned char *tag_out; + unsigned int tag; + int bits_left; }; #if !defined(BLZ_NO_LUT) static const unsigned short blz_gamma_lookup[512][2] = { - {0, 0}, - {0, 0}, - - {0x00, 2}, {0x02, 2}, - - {0x04, 4}, {0x06, 4}, {0x0C, 4}, {0x0E, 4}, - - {0x14, 6}, {0x16, 6}, {0x1C, 6}, {0x1E, 6}, - {0x34, 6}, {0x36, 6}, {0x3C, 6}, {0x3E, 6}, - - {0x54, 8}, {0x56, 8}, {0x5C, 8}, {0x5E, 8}, - {0x74, 8}, {0x76, 8}, {0x7C, 8}, {0x7E, 8}, - {0xD4, 8}, {0xD6, 8}, {0xDC, 8}, {0xDE, 8}, - {0xF4, 8}, {0xF6, 8}, {0xFC, 8}, {0xFE, 8}, - - {0x154, 10}, {0x156, 10}, {0x15C, 10}, {0x15E, 10}, - {0x174, 10}, {0x176, 10}, {0x17C, 10}, {0x17E, 10}, - {0x1D4, 10}, {0x1D6, 10}, {0x1DC, 10}, {0x1DE, 10}, - {0x1F4, 10}, {0x1F6, 10}, {0x1FC, 10}, {0x1FE, 10}, - {0x354, 10}, {0x356, 10}, {0x35C, 10}, {0x35E, 10}, - {0x374, 10}, {0x376, 10}, {0x37C, 10}, {0x37E, 10}, - {0x3D4, 10}, {0x3D6, 10}, {0x3DC, 10}, {0x3DE, 10}, - {0x3F4, 10}, {0x3F6, 10}, {0x3FC, 10}, {0x3FE, 10}, - - {0x554, 12}, {0x556, 12}, {0x55C, 12}, {0x55E, 12}, - {0x574, 12}, {0x576, 12}, {0x57C, 12}, {0x57E, 12}, - {0x5D4, 12}, {0x5D6, 12}, {0x5DC, 12}, {0x5DE, 12}, - {0x5F4, 12}, {0x5F6, 12}, {0x5FC, 12}, {0x5FE, 12}, - {0x754, 12}, {0x756, 12}, {0x75C, 12}, {0x75E, 12}, - {0x774, 12}, {0x776, 12}, {0x77C, 12}, {0x77E, 12}, - {0x7D4, 12}, {0x7D6, 12}, {0x7DC, 12}, {0x7DE, 12}, - {0x7F4, 12}, {0x7F6, 12}, {0x7FC, 12}, {0x7FE, 12}, - {0xD54, 12}, {0xD56, 12}, {0xD5C, 12}, {0xD5E, 12}, - {0xD74, 12}, {0xD76, 12}, {0xD7C, 12}, {0xD7E, 12}, - {0xDD4, 12}, {0xDD6, 12}, {0xDDC, 12}, {0xDDE, 12}, - {0xDF4, 12}, {0xDF6, 12}, {0xDFC, 12}, {0xDFE, 12}, - {0xF54, 12}, {0xF56, 12}, {0xF5C, 12}, {0xF5E, 12}, - {0xF74, 12}, {0xF76, 12}, {0xF7C, 12}, {0xF7E, 12}, - {0xFD4, 12}, {0xFD6, 12}, {0xFDC, 12}, {0xFDE, 12}, - {0xFF4, 12}, {0xFF6, 12}, {0xFFC, 12}, {0xFFE, 12}, - - {0x1554, 14}, {0x1556, 14}, {0x155C, 14}, {0x155E, 14}, - {0x1574, 14}, {0x1576, 14}, {0x157C, 14}, {0x157E, 14}, - {0x15D4, 14}, {0x15D6, 14}, {0x15DC, 14}, {0x15DE, 14}, - {0x15F4, 14}, {0x15F6, 14}, {0x15FC, 14}, {0x15FE, 14}, - {0x1754, 14}, {0x1756, 14}, {0x175C, 14}, {0x175E, 14}, - {0x1774, 14}, {0x1776, 14}, {0x177C, 14}, {0x177E, 14}, - {0x17D4, 14}, {0x17D6, 14}, {0x17DC, 14}, {0x17DE, 14}, - {0x17F4, 14}, {0x17F6, 14}, {0x17FC, 14}, {0x17FE, 14}, - {0x1D54, 14}, {0x1D56, 14}, {0x1D5C, 14}, {0x1D5E, 14}, - {0x1D74, 14}, {0x1D76, 14}, {0x1D7C, 14}, {0x1D7E, 14}, - {0x1DD4, 14}, {0x1DD6, 14}, {0x1DDC, 14}, {0x1DDE, 14}, - {0x1DF4, 14}, {0x1DF6, 14}, {0x1DFC, 14}, {0x1DFE, 14}, - {0x1F54, 14}, {0x1F56, 14}, {0x1F5C, 14}, {0x1F5E, 14}, - {0x1F74, 14}, {0x1F76, 14}, {0x1F7C, 14}, {0x1F7E, 14}, - {0x1FD4, 14}, {0x1FD6, 14}, {0x1FDC, 14}, {0x1FDE, 14}, - {0x1FF4, 14}, {0x1FF6, 14}, {0x1FFC, 14}, {0x1FFE, 14}, - {0x3554, 14}, {0x3556, 14}, {0x355C, 14}, {0x355E, 14}, - {0x3574, 14}, {0x3576, 14}, {0x357C, 14}, {0x357E, 14}, - {0x35D4, 14}, {0x35D6, 14}, {0x35DC, 14}, {0x35DE, 14}, - {0x35F4, 14}, {0x35F6, 14}, {0x35FC, 14}, {0x35FE, 14}, - {0x3754, 14}, {0x3756, 14}, {0x375C, 14}, {0x375E, 14}, - {0x3774, 14}, {0x3776, 14}, {0x377C, 14}, {0x377E, 14}, - {0x37D4, 14}, {0x37D6, 14}, {0x37DC, 14}, {0x37DE, 14}, - {0x37F4, 14}, {0x37F6, 14}, {0x37FC, 14}, {0x37FE, 14}, - {0x3D54, 14}, {0x3D56, 14}, {0x3D5C, 14}, {0x3D5E, 14}, - {0x3D74, 14}, {0x3D76, 14}, {0x3D7C, 14}, {0x3D7E, 14}, - {0x3DD4, 14}, {0x3DD6, 14}, {0x3DDC, 14}, {0x3DDE, 14}, - {0x3DF4, 14}, {0x3DF6, 14}, {0x3DFC, 14}, {0x3DFE, 14}, - {0x3F54, 14}, {0x3F56, 14}, {0x3F5C, 14}, {0x3F5E, 14}, - {0x3F74, 14}, {0x3F76, 14}, {0x3F7C, 14}, {0x3F7E, 14}, - {0x3FD4, 14}, {0x3FD6, 14}, {0x3FDC, 14}, {0x3FDE, 14}, - {0x3FF4, 14}, {0x3FF6, 14}, {0x3FFC, 14}, {0x3FFE, 14}, - - {0x5554, 16}, {0x5556, 16}, {0x555C, 16}, {0x555E, 16}, - {0x5574, 16}, {0x5576, 16}, {0x557C, 16}, {0x557E, 16}, - {0x55D4, 16}, {0x55D6, 16}, {0x55DC, 16}, {0x55DE, 16}, - {0x55F4, 16}, {0x55F6, 16}, {0x55FC, 16}, {0x55FE, 16}, - {0x5754, 16}, {0x5756, 16}, {0x575C, 16}, {0x575E, 16}, - {0x5774, 16}, {0x5776, 16}, {0x577C, 16}, {0x577E, 16}, - {0x57D4, 16}, {0x57D6, 16}, {0x57DC, 16}, {0x57DE, 16}, - {0x57F4, 16}, {0x57F6, 16}, {0x57FC, 16}, {0x57FE, 16}, - {0x5D54, 16}, {0x5D56, 16}, {0x5D5C, 16}, {0x5D5E, 16}, - {0x5D74, 16}, {0x5D76, 16}, {0x5D7C, 16}, {0x5D7E, 16}, - {0x5DD4, 16}, {0x5DD6, 16}, {0x5DDC, 16}, {0x5DDE, 16}, - {0x5DF4, 16}, {0x5DF6, 16}, {0x5DFC, 16}, {0x5DFE, 16}, - {0x5F54, 16}, {0x5F56, 16}, {0x5F5C, 16}, {0x5F5E, 16}, - {0x5F74, 16}, {0x5F76, 16}, {0x5F7C, 16}, {0x5F7E, 16}, - {0x5FD4, 16}, {0x5FD6, 16}, {0x5FDC, 16}, {0x5FDE, 16}, - {0x5FF4, 16}, {0x5FF6, 16}, {0x5FFC, 16}, {0x5FFE, 16}, - {0x7554, 16}, {0x7556, 16}, {0x755C, 16}, {0x755E, 16}, - {0x7574, 16}, {0x7576, 16}, {0x757C, 16}, {0x757E, 16}, - {0x75D4, 16}, {0x75D6, 16}, {0x75DC, 16}, {0x75DE, 16}, - {0x75F4, 16}, {0x75F6, 16}, {0x75FC, 16}, {0x75FE, 16}, - {0x7754, 16}, {0x7756, 16}, {0x775C, 16}, {0x775E, 16}, - {0x7774, 16}, {0x7776, 16}, {0x777C, 16}, {0x777E, 16}, - {0x77D4, 16}, {0x77D6, 16}, {0x77DC, 16}, {0x77DE, 16}, - {0x77F4, 16}, {0x77F6, 16}, {0x77FC, 16}, {0x77FE, 16}, - {0x7D54, 16}, {0x7D56, 16}, {0x7D5C, 16}, {0x7D5E, 16}, - {0x7D74, 16}, {0x7D76, 16}, {0x7D7C, 16}, {0x7D7E, 16}, - {0x7DD4, 16}, {0x7DD6, 16}, {0x7DDC, 16}, {0x7DDE, 16}, - {0x7DF4, 16}, {0x7DF6, 16}, {0x7DFC, 16}, {0x7DFE, 16}, - {0x7F54, 16}, {0x7F56, 16}, {0x7F5C, 16}, {0x7F5E, 16}, - {0x7F74, 16}, {0x7F76, 16}, {0x7F7C, 16}, {0x7F7E, 16}, - {0x7FD4, 16}, {0x7FD6, 16}, {0x7FDC, 16}, {0x7FDE, 16}, - {0x7FF4, 16}, {0x7FF6, 16}, {0x7FFC, 16}, {0x7FFE, 16}, - {0xD554, 16}, {0xD556, 16}, {0xD55C, 16}, {0xD55E, 16}, - {0xD574, 16}, {0xD576, 16}, {0xD57C, 16}, {0xD57E, 16}, - {0xD5D4, 16}, {0xD5D6, 16}, {0xD5DC, 16}, {0xD5DE, 16}, - {0xD5F4, 16}, {0xD5F6, 16}, {0xD5FC, 16}, {0xD5FE, 16}, - {0xD754, 16}, {0xD756, 16}, {0xD75C, 16}, {0xD75E, 16}, - {0xD774, 16}, {0xD776, 16}, {0xD77C, 16}, {0xD77E, 16}, - {0xD7D4, 16}, {0xD7D6, 16}, {0xD7DC, 16}, {0xD7DE, 16}, - {0xD7F4, 16}, {0xD7F6, 16}, {0xD7FC, 16}, {0xD7FE, 16}, - {0xDD54, 16}, {0xDD56, 16}, {0xDD5C, 16}, {0xDD5E, 16}, - {0xDD74, 16}, {0xDD76, 16}, {0xDD7C, 16}, {0xDD7E, 16}, - {0xDDD4, 16}, {0xDDD6, 16}, {0xDDDC, 16}, {0xDDDE, 16}, - {0xDDF4, 16}, {0xDDF6, 16}, {0xDDFC, 16}, {0xDDFE, 16}, - {0xDF54, 16}, {0xDF56, 16}, {0xDF5C, 16}, {0xDF5E, 16}, - {0xDF74, 16}, {0xDF76, 16}, {0xDF7C, 16}, {0xDF7E, 16}, - {0xDFD4, 16}, {0xDFD6, 16}, {0xDFDC, 16}, {0xDFDE, 16}, - {0xDFF4, 16}, {0xDFF6, 16}, {0xDFFC, 16}, {0xDFFE, 16}, - {0xF554, 16}, {0xF556, 16}, {0xF55C, 16}, {0xF55E, 16}, - {0xF574, 16}, {0xF576, 16}, {0xF57C, 16}, {0xF57E, 16}, - {0xF5D4, 16}, {0xF5D6, 16}, {0xF5DC, 16}, {0xF5DE, 16}, - {0xF5F4, 16}, {0xF5F6, 16}, {0xF5FC, 16}, {0xF5FE, 16}, - {0xF754, 16}, {0xF756, 16}, {0xF75C, 16}, {0xF75E, 16}, - {0xF774, 16}, {0xF776, 16}, {0xF77C, 16}, {0xF77E, 16}, - {0xF7D4, 16}, {0xF7D6, 16}, {0xF7DC, 16}, {0xF7DE, 16}, - {0xF7F4, 16}, {0xF7F6, 16}, {0xF7FC, 16}, {0xF7FE, 16}, - {0xFD54, 16}, {0xFD56, 16}, {0xFD5C, 16}, {0xFD5E, 16}, - {0xFD74, 16}, {0xFD76, 16}, {0xFD7C, 16}, {0xFD7E, 16}, - {0xFDD4, 16}, {0xFDD6, 16}, {0xFDDC, 16}, {0xFDDE, 16}, - {0xFDF4, 16}, {0xFDF6, 16}, {0xFDFC, 16}, {0xFDFE, 16}, - {0xFF54, 16}, {0xFF56, 16}, {0xFF5C, 16}, {0xFF5E, 16}, - {0xFF74, 16}, {0xFF76, 16}, {0xFF7C, 16}, {0xFF7E, 16}, - {0xFFD4, 16}, {0xFFD6, 16}, {0xFFDC, 16}, {0xFFDE, 16}, - {0xFFF4, 16}, {0xFFF6, 16}, {0xFFFC, 16}, {0xFFFE, 16} -}; + {0, 0}, {0, 0}, + + {0x00, 2}, {0x02, 2}, + + {0x04, 4}, {0x06, 4}, {0x0C, 4}, {0x0E, 4}, + + {0x14, 6}, {0x16, 6}, {0x1C, 6}, {0x1E, 6}, {0x34, 6}, {0x36, 6}, {0x3C, 6}, {0x3E, 6}, + + {0x54, 8}, {0x56, 8}, {0x5C, 8}, {0x5E, 8}, {0x74, 8}, {0x76, 8}, {0x7C, 8}, {0x7E, 8}, {0xD4, 8}, {0xD6, 8}, {0xDC, 8}, {0xDE, 8}, {0xF4, 8}, {0xF6, 8}, + {0xFC, 8}, {0xFE, 8}, + + {0x154, 10}, {0x156, 10}, {0x15C, 10}, {0x15E, 10}, {0x174, 10}, {0x176, 10}, {0x17C, 10}, {0x17E, 10}, {0x1D4, 10}, {0x1D6, 10}, {0x1DC, 10}, {0x1DE, 10}, {0x1F4, 10}, {0x1F6, 10}, + {0x1FC, 10}, {0x1FE, 10}, {0x354, 10}, {0x356, 10}, {0x35C, 10}, {0x35E, 10}, {0x374, 10}, {0x376, 10}, {0x37C, 10}, {0x37E, 10}, {0x3D4, 10}, {0x3D6, 10}, {0x3DC, 10}, {0x3DE, 10}, + {0x3F4, 10}, {0x3F6, 10}, {0x3FC, 10}, {0x3FE, 10}, + + {0x554, 12}, {0x556, 12}, {0x55C, 12}, {0x55E, 12}, {0x574, 12}, {0x576, 12}, {0x57C, 12}, {0x57E, 12}, {0x5D4, 12}, {0x5D6, 12}, {0x5DC, 12}, {0x5DE, 12}, {0x5F4, 12}, {0x5F6, 12}, + {0x5FC, 12}, {0x5FE, 12}, {0x754, 12}, {0x756, 12}, {0x75C, 12}, {0x75E, 12}, {0x774, 12}, {0x776, 12}, {0x77C, 12}, {0x77E, 12}, {0x7D4, 12}, {0x7D6, 12}, {0x7DC, 12}, {0x7DE, 12}, + {0x7F4, 12}, {0x7F6, 12}, {0x7FC, 12}, {0x7FE, 12}, {0xD54, 12}, {0xD56, 12}, {0xD5C, 12}, {0xD5E, 12}, {0xD74, 12}, {0xD76, 12}, {0xD7C, 12}, {0xD7E, 12}, {0xDD4, 12}, {0xDD6, 12}, + {0xDDC, 12}, {0xDDE, 12}, {0xDF4, 12}, {0xDF6, 12}, {0xDFC, 12}, {0xDFE, 12}, {0xF54, 12}, {0xF56, 12}, {0xF5C, 12}, {0xF5E, 12}, {0xF74, 12}, {0xF76, 12}, {0xF7C, 12}, {0xF7E, 12}, + {0xFD4, 12}, {0xFD6, 12}, {0xFDC, 12}, {0xFDE, 12}, {0xFF4, 12}, {0xFF6, 12}, {0xFFC, 12}, {0xFFE, 12}, + + {0x1554, 14}, {0x1556, 14}, {0x155C, 14}, {0x155E, 14}, {0x1574, 14}, {0x1576, 14}, {0x157C, 14}, {0x157E, 14}, {0x15D4, 14}, {0x15D6, 14}, {0x15DC, 14}, {0x15DE, 14}, {0x15F4, 14}, {0x15F6, 14}, + {0x15FC, 14}, {0x15FE, 14}, {0x1754, 14}, {0x1756, 14}, {0x175C, 14}, {0x175E, 14}, {0x1774, 14}, {0x1776, 14}, {0x177C, 14}, {0x177E, 14}, {0x17D4, 14}, {0x17D6, 14}, {0x17DC, 14}, {0x17DE, 14}, + {0x17F4, 14}, {0x17F6, 14}, {0x17FC, 14}, {0x17FE, 14}, {0x1D54, 14}, {0x1D56, 14}, {0x1D5C, 14}, {0x1D5E, 14}, {0x1D74, 14}, {0x1D76, 14}, {0x1D7C, 14}, {0x1D7E, 14}, {0x1DD4, 14}, {0x1DD6, 14}, + {0x1DDC, 14}, {0x1DDE, 14}, {0x1DF4, 14}, {0x1DF6, 14}, {0x1DFC, 14}, {0x1DFE, 14}, {0x1F54, 14}, {0x1F56, 14}, {0x1F5C, 14}, {0x1F5E, 14}, {0x1F74, 14}, {0x1F76, 14}, {0x1F7C, 14}, {0x1F7E, 14}, + {0x1FD4, 14}, {0x1FD6, 14}, {0x1FDC, 14}, {0x1FDE, 14}, {0x1FF4, 14}, {0x1FF6, 14}, {0x1FFC, 14}, {0x1FFE, 14}, {0x3554, 14}, {0x3556, 14}, {0x355C, 14}, {0x355E, 14}, {0x3574, 14}, {0x3576, 14}, + {0x357C, 14}, {0x357E, 14}, {0x35D4, 14}, {0x35D6, 14}, {0x35DC, 14}, {0x35DE, 14}, {0x35F4, 14}, {0x35F6, 14}, {0x35FC, 14}, {0x35FE, 14}, {0x3754, 14}, {0x3756, 14}, {0x375C, 14}, {0x375E, 14}, + {0x3774, 14}, {0x3776, 14}, {0x377C, 14}, {0x377E, 14}, {0x37D4, 14}, {0x37D6, 14}, {0x37DC, 14}, {0x37DE, 14}, {0x37F4, 14}, {0x37F6, 14}, {0x37FC, 14}, {0x37FE, 14}, {0x3D54, 14}, {0x3D56, 14}, + {0x3D5C, 14}, {0x3D5E, 14}, {0x3D74, 14}, {0x3D76, 14}, {0x3D7C, 14}, {0x3D7E, 14}, {0x3DD4, 14}, {0x3DD6, 14}, {0x3DDC, 14}, {0x3DDE, 14}, {0x3DF4, 14}, {0x3DF6, 14}, {0x3DFC, 14}, {0x3DFE, 14}, + {0x3F54, 14}, {0x3F56, 14}, {0x3F5C, 14}, {0x3F5E, 14}, {0x3F74, 14}, {0x3F76, 14}, {0x3F7C, 14}, {0x3F7E, 14}, {0x3FD4, 14}, {0x3FD6, 14}, {0x3FDC, 14}, {0x3FDE, 14}, {0x3FF4, 14}, {0x3FF6, 14}, + {0x3FFC, 14}, {0x3FFE, 14}, + + {0x5554, 16}, {0x5556, 16}, {0x555C, 16}, {0x555E, 16}, {0x5574, 16}, {0x5576, 16}, {0x557C, 16}, {0x557E, 16}, {0x55D4, 16}, {0x55D6, 16}, {0x55DC, 16}, {0x55DE, 16}, {0x55F4, 16}, {0x55F6, 16}, + {0x55FC, 16}, {0x55FE, 16}, {0x5754, 16}, {0x5756, 16}, {0x575C, 16}, {0x575E, 16}, {0x5774, 16}, {0x5776, 16}, {0x577C, 16}, {0x577E, 16}, {0x57D4, 16}, {0x57D6, 16}, {0x57DC, 16}, {0x57DE, 16}, + {0x57F4, 16}, {0x57F6, 16}, {0x57FC, 16}, {0x57FE, 16}, {0x5D54, 16}, {0x5D56, 16}, {0x5D5C, 16}, {0x5D5E, 16}, {0x5D74, 16}, {0x5D76, 16}, {0x5D7C, 16}, {0x5D7E, 16}, {0x5DD4, 16}, {0x5DD6, 16}, + {0x5DDC, 16}, {0x5DDE, 16}, {0x5DF4, 16}, {0x5DF6, 16}, {0x5DFC, 16}, {0x5DFE, 16}, {0x5F54, 16}, {0x5F56, 16}, {0x5F5C, 16}, {0x5F5E, 16}, {0x5F74, 16}, {0x5F76, 16}, {0x5F7C, 16}, {0x5F7E, 16}, + {0x5FD4, 16}, {0x5FD6, 16}, {0x5FDC, 16}, {0x5FDE, 16}, {0x5FF4, 16}, {0x5FF6, 16}, {0x5FFC, 16}, {0x5FFE, 16}, {0x7554, 16}, {0x7556, 16}, {0x755C, 16}, {0x755E, 16}, {0x7574, 16}, {0x7576, 16}, + {0x757C, 16}, {0x757E, 16}, {0x75D4, 16}, {0x75D6, 16}, {0x75DC, 16}, {0x75DE, 16}, {0x75F4, 16}, {0x75F6, 16}, {0x75FC, 16}, {0x75FE, 16}, {0x7754, 16}, {0x7756, 16}, {0x775C, 16}, {0x775E, 16}, + {0x7774, 16}, {0x7776, 16}, {0x777C, 16}, {0x777E, 16}, {0x77D4, 16}, {0x77D6, 16}, {0x77DC, 16}, {0x77DE, 16}, {0x77F4, 16}, {0x77F6, 16}, {0x77FC, 16}, {0x77FE, 16}, {0x7D54, 16}, {0x7D56, 16}, + {0x7D5C, 16}, {0x7D5E, 16}, {0x7D74, 16}, {0x7D76, 16}, {0x7D7C, 16}, {0x7D7E, 16}, {0x7DD4, 16}, {0x7DD6, 16}, {0x7DDC, 16}, {0x7DDE, 16}, {0x7DF4, 16}, {0x7DF6, 16}, {0x7DFC, 16}, {0x7DFE, 16}, + {0x7F54, 16}, {0x7F56, 16}, {0x7F5C, 16}, {0x7F5E, 16}, {0x7F74, 16}, {0x7F76, 16}, {0x7F7C, 16}, {0x7F7E, 16}, {0x7FD4, 16}, {0x7FD6, 16}, {0x7FDC, 16}, {0x7FDE, 16}, {0x7FF4, 16}, {0x7FF6, 16}, + {0x7FFC, 16}, {0x7FFE, 16}, {0xD554, 16}, {0xD556, 16}, {0xD55C, 16}, {0xD55E, 16}, {0xD574, 16}, {0xD576, 16}, {0xD57C, 16}, {0xD57E, 16}, {0xD5D4, 16}, {0xD5D6, 16}, {0xD5DC, 16}, {0xD5DE, 16}, + {0xD5F4, 16}, {0xD5F6, 16}, {0xD5FC, 16}, {0xD5FE, 16}, {0xD754, 16}, {0xD756, 16}, {0xD75C, 16}, {0xD75E, 16}, {0xD774, 16}, {0xD776, 16}, {0xD77C, 16}, {0xD77E, 16}, {0xD7D4, 16}, {0xD7D6, 16}, + {0xD7DC, 16}, {0xD7DE, 16}, {0xD7F4, 16}, {0xD7F6, 16}, {0xD7FC, 16}, {0xD7FE, 16}, {0xDD54, 16}, {0xDD56, 16}, {0xDD5C, 16}, {0xDD5E, 16}, {0xDD74, 16}, {0xDD76, 16}, {0xDD7C, 16}, {0xDD7E, 16}, + {0xDDD4, 16}, {0xDDD6, 16}, {0xDDDC, 16}, {0xDDDE, 16}, {0xDDF4, 16}, {0xDDF6, 16}, {0xDDFC, 16}, {0xDDFE, 16}, {0xDF54, 16}, {0xDF56, 16}, {0xDF5C, 16}, {0xDF5E, 16}, {0xDF74, 16}, {0xDF76, 16}, + {0xDF7C, 16}, {0xDF7E, 16}, {0xDFD4, 16}, {0xDFD6, 16}, {0xDFDC, 16}, {0xDFDE, 16}, {0xDFF4, 16}, {0xDFF6, 16}, {0xDFFC, 16}, {0xDFFE, 16}, {0xF554, 16}, {0xF556, 16}, {0xF55C, 16}, {0xF55E, 16}, + {0xF574, 16}, {0xF576, 16}, {0xF57C, 16}, {0xF57E, 16}, {0xF5D4, 16}, {0xF5D6, 16}, {0xF5DC, 16}, {0xF5DE, 16}, {0xF5F4, 16}, {0xF5F6, 16}, {0xF5FC, 16}, {0xF5FE, 16}, {0xF754, 16}, {0xF756, 16}, + {0xF75C, 16}, {0xF75E, 16}, {0xF774, 16}, {0xF776, 16}, {0xF77C, 16}, {0xF77E, 16}, {0xF7D4, 16}, {0xF7D6, 16}, {0xF7DC, 16}, {0xF7DE, 16}, {0xF7F4, 16}, {0xF7F6, 16}, {0xF7FC, 16}, {0xF7FE, 16}, + {0xFD54, 16}, {0xFD56, 16}, {0xFD5C, 16}, {0xFD5E, 16}, {0xFD74, 16}, {0xFD76, 16}, {0xFD7C, 16}, {0xFD7E, 16}, {0xFDD4, 16}, {0xFDD6, 16}, {0xFDDC, 16}, {0xFDDE, 16}, {0xFDF4, 16}, {0xFDF6, 16}, + {0xFDFC, 16}, {0xFDFE, 16}, {0xFF54, 16}, {0xFF56, 16}, {0xFF5C, 16}, {0xFF5E, 16}, {0xFF74, 16}, {0xFF76, 16}, {0xFF7C, 16}, {0xFF7E, 16}, {0xFFD4, 16}, {0xFFD6, 16}, {0xFFDC, 16}, {0xFFDE, 16}, + {0xFFF4, 16}, {0xFFF6, 16}, {0xFFFC, 16}, {0xFFFE, 16}}; #endif -static int -blz_log2(unsigned long n) -{ - assert(n > 0); +static int blz_log2(unsigned long n) { + assert(n > 0); #if defined(BLZ_BUILTIN_MSVC) - unsigned long msb_pos; - _BitScanReverse(&msb_pos, n); - return (int) msb_pos; + unsigned long msb_pos; + _BitScanReverse(&msb_pos, n); + return (int)msb_pos; #elif defined(BLZ_BUILTIN_GCC) - return (int) sizeof(n) * CHAR_BIT - 1 - __builtin_clzl(n); + return (int)sizeof(n) * CHAR_BIT - 1 - __builtin_clzl(n); #else - int bits = 0; + int bits = 0; - while (n >>= 1) { - ++bits; - } + while (n >>= 1) { + ++bits; + } - return bits; + return bits; #endif } -static unsigned long -blz_gamma_cost(unsigned long n) -{ - assert(n >= 2); +static unsigned long blz_gamma_cost(unsigned long n) { + assert(n >= 2); - return 2 * (unsigned long) blz_log2(n); + return 2 * (unsigned long)blz_log2(n); } -static unsigned long -blz_match_cost(unsigned long pos, unsigned long len) -{ - return 1 + blz_gamma_cost(len - 2) + blz_gamma_cost((pos >> 8) + 2) + 8; -} +static unsigned long blz_match_cost(unsigned long pos, unsigned long len) { return 1 + blz_gamma_cost(len - 2) + blz_gamma_cost((pos >> 8) + 2) + 8; } // Heuristic to compare matches -static int -blz_match_better(unsigned long cur, unsigned long new_pos, unsigned long new_len, - unsigned long pos, unsigned long len) -{ - const unsigned long offs = cur - pos - 1; - const unsigned long new_offs = cur - new_pos - 1; - - return (new_len > len + 1) - || (new_len >= len + 1 && new_offs / 8 <= offs); +static int blz_match_better(unsigned long cur, unsigned long new_pos, unsigned long new_len, unsigned long pos, unsigned long len) { + const unsigned long offs = cur - pos - 1; + const unsigned long new_offs = cur - new_pos - 1; + + return (new_len > len + 1) || (new_len >= len + 1 && new_offs / 8 <= offs); } // Heuristic to compare match with match at next position -static int -blz_next_match_better(unsigned long cur, unsigned long new_pos, unsigned long new_len, - unsigned long pos, unsigned long len) -{ - const unsigned long offs = cur - pos - 1; - const unsigned long new_offs = cur + 1 - new_pos - 1; - - return (new_len > len + 1 && new_offs / 8 < offs) - || (new_len > len && new_offs < offs) - || (new_len >= len && new_offs < offs / 4); +static int blz_next_match_better(unsigned long cur, unsigned long new_pos, unsigned long new_len, unsigned long pos, unsigned long len) { + const unsigned long offs = cur - pos - 1; + const unsigned long new_offs = cur + 1 - new_pos - 1; + + return (new_len > len + 1 && new_offs / 8 < offs) || (new_len > len && new_offs < offs) || (new_len >= len && new_offs < offs / 4); } -static void -blz_putbit(struct blz_state *bs, unsigned int bit) -{ - // Check if tag is full - if (!bs->bits_left--) { - // Store tag - bs->tag_out[0] = bs->tag & 0x00FF; - bs->tag_out[1] = (bs->tag >> 8) & 0x00FF; - - // Init next tag - bs->tag_out = bs->next_out; - bs->next_out += 2; - bs->bits_left = 15; - } - - // Shift bit into tag - bs->tag = (bs->tag << 1) + bit; +static void blz_putbit(struct blz_state *bs, unsigned int bit) { + // Check if tag is full + if (!bs->bits_left--) { + // Store tag + bs->tag_out[0] = bs->tag & 0x00FF; + bs->tag_out[1] = (bs->tag >> 8) & 0x00FF; + + // Init next tag + bs->tag_out = bs->next_out; + bs->next_out += 2; + bs->bits_left = 15; + } + + // Shift bit into tag + bs->tag = (bs->tag << 1) + bit; } -static void -blz_putbits(struct blz_state *bs, unsigned long bits, int num) -{ - assert(num >= 0 && num <= 16); - assert((bits & (~0UL << num)) == 0); +static void blz_putbits(struct blz_state *bs, unsigned long bits, int num) { + assert(num >= 0 && num <= 16); + assert((bits & (~0UL << num)) == 0); - // Shift num bits into tag - unsigned long tag = ((unsigned long) bs->tag << num) | bits; - bs->tag = (unsigned int) tag; + // Shift num bits into tag + unsigned long tag = ((unsigned long)bs->tag << num) | bits; + bs->tag = (unsigned int)tag; - // Check if tag is full - if (bs->bits_left < num) { - const unsigned int top16 = (unsigned int) (tag >> (num - bs->bits_left)); + // Check if tag is full + if (bs->bits_left < num) { + const unsigned int top16 = (unsigned int)(tag >> (num - bs->bits_left)); - // Store tag - bs->tag_out[0] = top16 & 0x00FF; - bs->tag_out[1] = (top16 >> 8) & 0x00FF; + // Store tag + bs->tag_out[0] = top16 & 0x00FF; + bs->tag_out[1] = (top16 >> 8) & 0x00FF; - // Init next tag - bs->tag_out = bs->next_out; - bs->next_out += 2; + // Init next tag + bs->tag_out = bs->next_out; + bs->next_out += 2; - bs->bits_left += 16; - } + bs->bits_left += 16; + } - bs->bits_left -= num; + bs->bits_left -= num; } // Encode val using a universal code based on Elias gamma. @@ -352,63 +243,59 @@ blz_putbits(struct blz_state *bs, unsigned long bits, int num) // known it as the gamma2 code. I am not sure where it originated from, but I // can see I used it in aPLib around 1998. // -static void -blz_putgamma(struct blz_state *bs, unsigned long val) -{ - assert(val >= 2); +static void blz_putgamma(struct blz_state *bs, unsigned long val) { + assert(val >= 2); #if !defined(BLZ_NO_LUT) - // Output small values using lookup - if (val < 512) { - const unsigned int bits = blz_gamma_lookup[val][0]; - const unsigned int shift = blz_gamma_lookup[val][1]; + // Output small values using lookup + if (val < 512) { + const unsigned int bits = blz_gamma_lookup[val][0]; + const unsigned int shift = blz_gamma_lookup[val][1]; - blz_putbits(bs, bits, (int) shift); + blz_putbits(bs, bits, (int)shift); - return; - } + return; + } #endif - // Create a mask for the second-highest bit of val + // Create a mask for the second-highest bit of val #if defined(BLZ_BUILTIN_MSVC) - unsigned long msb_pos; - _BitScanReverse(&msb_pos, val); - unsigned long mask = 1UL << (msb_pos - 1); + unsigned long msb_pos; + _BitScanReverse(&msb_pos, val); + unsigned long mask = 1UL << (msb_pos - 1); #elif defined(BLZ_BUILTIN_GCC) - unsigned long mask = 1UL << ((int) sizeof(val) * CHAR_BIT - 2 - __builtin_clzl(val)); + unsigned long mask = 1UL << ((int)sizeof(val) * CHAR_BIT - 2 - __builtin_clzl(val)); #else - unsigned long mask = val >> 1; + unsigned long mask = val >> 1; - // Clear bits except highest - while (mask & (mask - 1)) { - mask &= mask - 1; - } + // Clear bits except highest + while (mask & (mask - 1)) { + mask &= mask - 1; + } #endif - // Output gamma2-encoded bits - blz_putbit(bs, (val & mask) ? 1 : 0); + // Output gamma2-encoded bits + blz_putbit(bs, (val & mask) ? 1 : 0); - while (mask >>= 1) { - blz_putbit(bs, 1); - blz_putbit(bs, (val & mask) ? 1 : 0); - } + while (mask >>= 1) { + blz_putbit(bs, 1); + blz_putbit(bs, (val & mask) ? 1 : 0); + } - blz_putbit(bs, 0); + blz_putbit(bs, 0); } -static unsigned char* -blz_finalize(struct blz_state *bs) -{ - // Trailing one bit to delimit any literal tags - blz_putbit(bs, 1); +static unsigned char *blz_finalize(struct blz_state *bs) { + // Trailing one bit to delimit any literal tags + blz_putbit(bs, 1); - // Shift last tag into position and store - bs->tag <<= bs->bits_left; - bs->tag_out[0] = bs->tag & 0x00FF; - bs->tag_out[1] = (bs->tag >> 8) & 0x00FF; + // Shift last tag into position and store + bs->tag <<= bs->bits_left; + bs->tag_out[0] = bs->tag & 0x00FF; + bs->tag_out[1] = (bs->tag >> 8) & 0x00FF; - // Return pointer one past end of output - return bs->next_out; + // Return pointer one past end of output + return bs->next_out; } // Hash four bytes starting a p. @@ -416,37 +303,22 @@ blz_finalize(struct blz_state *bs) // This is Fibonacci hashing, also known as Knuth's multiplicative hash. The // constant is a prime close to 2^32/phi. // -static unsigned long -blz_hash4_bits(const unsigned char *p, int bits) -{ - assert(bits > 0 && bits <= 32); +static unsigned long blz_hash4_bits(const unsigned char *p, int bits) { + assert(bits > 0 && bits <= 32); - uint32_t val = (uint32_t) p[0] - | ((uint32_t) p[1] << 8) - | ((uint32_t) p[2] << 16) - | ((uint32_t) p[3] << 24); + uint32_t val = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); - return (val * UINT32_C(2654435761)) >> (32 - bits); + return (val * UINT32_C(2654435761)) >> (32 - bits); } -static unsigned long -blz_hash4(const unsigned char *p) -{ - return blz_hash4_bits(p, BLZ_HASH_BITS); -} +static unsigned long blz_hash4(const unsigned char *p) { return blz_hash4_bits(p, BLZ_HASH_BITS); } -size_t -blz_max_packed_size(size_t src_size) -{ - return src_size + src_size / 8 + 64; -} +size_t blz_max_packed_size(size_t src_size) { return src_size + src_size / 8 + 64; } -size_t -blz_workmem_size(size_t src_size) -{ - (void) src_size; +size_t blz_workmem_size(size_t src_size) { + (void)src_size; - return LOOKUP_SIZE * sizeof(blz_word); + return LOOKUP_SIZE * sizeof(blz_word); } // Simple LZSS using hashing. @@ -454,117 +326,113 @@ blz_workmem_size(size_t src_size) // The lookup table stores the previous position in the input that had a given // hash value, or NO_MATCH_POS if none. // -unsigned long -blz_pack(const void *src, void *dst, unsigned long src_size, void *workmem) -{ - struct blz_state bs; - blz_word *const lookup = (blz_word *) workmem; - const unsigned char *const in = (const unsigned char *) src; - const unsigned long last_match_pos = src_size > 4 ? src_size - 4 : 0; - unsigned long hash_pos = 0; - unsigned long cur = 0; - - assert(src_size < BLZ_WORD_MAX); - - // Check for empty input - if (src_size == 0) { - return 0; - } - - bs.next_out = (unsigned char *) dst; - - // First byte verbatim - *bs.next_out++ = in[0]; - - // Check for 1 byte input - if (src_size == 1) { - return 1; - } - - // Initialize first tag - bs.tag_out = bs.next_out; - bs.next_out += 2; - bs.tag = 0; - bs.bits_left = 16; - - // Initialize lookup - for (unsigned long i = 0; i < LOOKUP_SIZE; ++i) { - lookup[i] = NO_MATCH_POS; - } - - // Main compression loop - for (cur = 1; cur <= last_match_pos; ) { - // Update lookup up to current position - while (hash_pos < cur) { - lookup[blz_hash4(&in[hash_pos])] = hash_pos; - hash_pos++; - } - - // Look up match for current position - const unsigned long pos = lookup[blz_hash4(&in[cur])]; - unsigned long len = 0; - - // Check match - if (pos != NO_MATCH_POS) { - const unsigned long len_limit = src_size - cur; - - while (len < len_limit - && in[pos + len] == in[cur + len]) { - ++len; - } - } - - // Output match or literal - // - // When offs >= 0x1FFE00, encoding a match of length 4 - // (37 bits) is longer than encoding 4 literals (36 bits). - // - // The value 0x7E00 is a heuristic that sacrifices some - // length 4 matches in the hope that there will be a better - // match at the next position. - if (len > 4 || (len == 4 && cur - pos - 1 < 0x7E00UL)) { - const unsigned long offs = cur - pos - 1; - - // Output match tag - blz_putbit(&bs, 1); - - // Output match length - blz_putgamma(&bs, len - 2); - - // Output match offset - blz_putgamma(&bs, (offs >> 8) + 2); - *bs.next_out++ = offs & 0x00FF; - - cur += len; - } - else { - // Output literal tag - blz_putbit(&bs, 0); - - // Copy literal - *bs.next_out++ = in[cur++]; - } - } - - // Output any remaining literals - while (cur < src_size) { - // Output literal tag - blz_putbit(&bs, 0); - - // Copy literal - *bs.next_out++ = in[cur++]; - } - - // Trailing one bit to delimit any literal tags - blz_putbit(&bs, 1); - - // Shift last tag into position and store - bs.tag <<= bs.bits_left; - bs.tag_out[0] = bs.tag & 0x00FF; - bs.tag_out[1] = (bs.tag >> 8) & 0x00FF; - - // Return compressed size - return (unsigned long) (bs.next_out - (unsigned char *) dst); +unsigned long blz_pack(const void *src, void *dst, unsigned long src_size, void *workmem) { + struct blz_state bs; + blz_word *const lookup = (blz_word *)workmem; + const unsigned char *const in = (const unsigned char *)src; + const unsigned long last_match_pos = src_size > 4 ? src_size - 4 : 0; + unsigned long hash_pos = 0; + unsigned long cur = 0; + + assert(src_size < BLZ_WORD_MAX); + + // Check for empty input + if (src_size == 0) { + return 0; + } + + bs.next_out = (unsigned char *)dst; + + // First byte verbatim + *bs.next_out++ = in[0]; + + // Check for 1 byte input + if (src_size == 1) { + return 1; + } + + // Initialize first tag + bs.tag_out = bs.next_out; + bs.next_out += 2; + bs.tag = 0; + bs.bits_left = 16; + + // Initialize lookup + for (unsigned long i = 0; i < LOOKUP_SIZE; ++i) { + lookup[i] = NO_MATCH_POS; + } + + // Main compression loop + for (cur = 1; cur <= last_match_pos;) { + // Update lookup up to current position + while (hash_pos < cur) { + lookup[blz_hash4(&in[hash_pos])] = hash_pos; + hash_pos++; + } + + // Look up match for current position + const unsigned long pos = lookup[blz_hash4(&in[cur])]; + unsigned long len = 0; + + // Check match + if (pos != NO_MATCH_POS) { + const unsigned long len_limit = src_size - cur; + + while (len < len_limit && in[pos + len] == in[cur + len]) { + ++len; + } + } + + // Output match or literal + // + // When offs >= 0x1FFE00, encoding a match of length 4 + // (37 bits) is longer than encoding 4 literals (36 bits). + // + // The value 0x7E00 is a heuristic that sacrifices some + // length 4 matches in the hope that there will be a better + // match at the next position. + if (len > 4 || (len == 4 && cur - pos - 1 < 0x7E00UL)) { + const unsigned long offs = cur - pos - 1; + + // Output match tag + blz_putbit(&bs, 1); + + // Output match length + blz_putgamma(&bs, len - 2); + + // Output match offset + blz_putgamma(&bs, (offs >> 8) + 2); + *bs.next_out++ = offs & 0x00FF; + + cur += len; + } else { + // Output literal tag + blz_putbit(&bs, 0); + + // Copy literal + *bs.next_out++ = in[cur++]; + } + } + + // Output any remaining literals + while (cur < src_size) { + // Output literal tag + blz_putbit(&bs, 0); + + // Copy literal + *bs.next_out++ = in[cur++]; + } + + // Trailing one bit to delimit any literal tags + blz_putbit(&bs, 1); + + // Shift last tag into position and store + bs.tag <<= bs.bits_left; + bs.tag_out[0] = bs.tag & 0x00FF; + bs.tag_out[1] = (bs.tag >> 8) & 0x00FF; + + // Return compressed size + return (unsigned long)(bs.next_out - (unsigned char *)dst); } // Include compression algorithms used by blz_pack_level @@ -573,59 +441,54 @@ blz_pack(const void *src, void *dst, unsigned long src_size, void *workmem) #include "brieflz_lazy.h" #include "brieflz_leparse.h" -size_t -blz_workmem_size_level(size_t src_size, int level) -{ - switch (level) { - case 1: - return blz_workmem_size(src_size); - case 2: - return blz_lazy_workmem_size(src_size); - case 3: - return blz_hashbucket_workmem_size(src_size, 2); - case 4: - return blz_hashbucket_workmem_size(src_size, 4); - case 5: - case 6: - case 7: - return blz_leparse_workmem_size(src_size); - case 8: - case 9: - case 10: - return blz_btparse_workmem_size(src_size); - default: - return (size_t) -1; - } +size_t blz_workmem_size_level(size_t src_size, int level) { + switch (level) { + case 1: + return blz_workmem_size(src_size); + case 2: + return blz_lazy_workmem_size(src_size); + case 3: + return blz_hashbucket_workmem_size(src_size, 2); + case 4: + return blz_hashbucket_workmem_size(src_size, 4); + case 5: + case 6: + case 7: + return blz_leparse_workmem_size(src_size); + case 8: + case 9: + case 10: + return blz_btparse_workmem_size(src_size); + default: + return (size_t)-1; + } } -unsigned long -blz_pack_level(const void *src, void *dst, unsigned long src_size, - void *workmem, int level) -{ - switch (level) { - case 1: - return blz_pack(src, dst, src_size, workmem); - case 2: - return blz_pack_lazy(src, dst, src_size, workmem); - case 3: - return blz_pack_hashbucket(src, dst, src_size, workmem, 2, 16); - case 4: - return blz_pack_hashbucket(src, dst, src_size, workmem, 4, 16); - case 5: - return blz_pack_leparse(src, dst, src_size, workmem, 1, 16); - case 6: - return blz_pack_leparse(src, dst, src_size, workmem, 8, 32); - case 7: - return blz_pack_leparse(src, dst, src_size, workmem, 64, 64); - case 8: - return blz_pack_btparse(src, dst, src_size, workmem, 16, 96); - case 9: - return blz_pack_btparse(src, dst, src_size, workmem, 32, 224); - case 10: - return blz_pack_btparse(src, dst, src_size, workmem, ULONG_MAX, ULONG_MAX); - default: - return BLZ_ERROR; - } +unsigned long blz_pack_level(const void *src, void *dst, unsigned long src_size, void *workmem, int level) { + switch (level) { + case 1: + return blz_pack(src, dst, src_size, workmem); + case 2: + return blz_pack_lazy(src, dst, src_size, workmem); + case 3: + return blz_pack_hashbucket(src, dst, src_size, workmem, 2, 16); + case 4: + return blz_pack_hashbucket(src, dst, src_size, workmem, 4, 16); + case 5: + return blz_pack_leparse(src, dst, src_size, workmem, 1, 16); + case 6: + return blz_pack_leparse(src, dst, src_size, workmem, 8, 32); + case 7: + return blz_pack_leparse(src, dst, src_size, workmem, 64, 64); + case 8: + return blz_pack_btparse(src, dst, src_size, workmem, 16, 96); + case 9: + return blz_pack_btparse(src, dst, src_size, workmem, 32, 224); + case 10: + return blz_pack_btparse(src, dst, src_size, workmem, ULONG_MAX, ULONG_MAX); + default: + return BLZ_ERROR; + } } // clang -g -O1 -fsanitize=fuzzer,address -DBLZ_FUZZING brieflz.c depack.c @@ -637,23 +500,27 @@ blz_pack_level(const void *src, void *dst, unsigned long src_size, #include #ifndef BLZ_FUZZ_LEVEL -# define BLZ_FUZZ_LEVEL 1 +#define BLZ_FUZZ_LEVEL 1 #endif -extern int -LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) -{ - if (size > ULONG_MAX / 2) { return 0; } - void *workmem = malloc(blz_workmem_size_level(size, BLZ_FUZZ_LEVEL)); - void *packed = malloc(blz_max_packed_size(size)); - void *depacked = malloc(size); - if (!workmem || !packed || !depacked) { abort(); } - unsigned long packed_size = blz_pack_level(data, packed, size, workmem, BLZ_FUZZ_LEVEL); - blz_depack(packed, depacked, size); - if (memcmp(data, depacked, size)) { abort(); } - free(depacked); - free(packed); - free(workmem); - return 0; +extern int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { + if (size > ULONG_MAX / 2) { + return 0; + } + void *workmem = malloc(blz_workmem_size_level(size, BLZ_FUZZ_LEVEL)); + void *packed = malloc(blz_max_packed_size(size)); + void *depacked = malloc(size); + if (!workmem || !packed || !depacked) { + abort(); + } + unsigned long packed_size = blz_pack_level(data, packed, size, workmem, BLZ_FUZZ_LEVEL); + blz_depack(packed, depacked, size); + if (memcmp(data, depacked, size)) { + abort(); + } + free(depacked); + free(packed); + free(workmem); + return 0; } #endif diff --git a/source/Core/brieflz/depack.c b/source/Core/brieflz/depack.c index b2324cfd23..4175be41a8 100644 --- a/source/Core/brieflz/depack.c +++ b/source/Core/brieflz/depack.c @@ -29,243 +29,447 @@ /* Internal data structure */ struct blz_state { - const unsigned char *src; - unsigned char *dst; - unsigned int tag; - int bits_left; + const unsigned char *src; + unsigned char *dst; + unsigned int tag; + int bits_left; }; #if !defined(BLZ_NO_LUT) static const unsigned char blz_gamma_lookup[256][2] = { - /* 00xxxxxx = 2 */ - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, + /* 00xxxxxx = 2 */ + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + {2, 2}, + + /* 0100xxxx = 4 */ + {4, 4}, + {4, 4}, + {4, 4}, + {4, 4}, + {4, 4}, + {4, 4}, + {4, 4}, + {4, 4}, + {4, 4}, + {4, 4}, + {4, 4}, + {4, 4}, + {4, 4}, + {4, 4}, + {4, 4}, + {4, 4}, + + /* 010100xx = 8 */ + {8, 6}, + {8, 6}, + {8, 6}, + {8, 6}, + + /* 01010100 = 16 01010101 = 16+ 01010110 = 17 01010111 = 17+ */ + {16, 8}, + {16, 0}, + {17, 8}, + {17, 0}, + + /* 010110xx = 9 */ + {9, 6}, + {9, 6}, + {9, 6}, + {9, 6}, + + /* 01011100 = 18 01011101 = 18+ 01011110 = 19 01011111 = 19+ */ + {18, 8}, + {18, 0}, + {19, 8}, + {19, 0}, + + /* 0110xxxx = 5 */ + {5, 4}, + {5, 4}, + {5, 4}, + {5, 4}, + {5, 4}, + {5, 4}, + {5, 4}, + {5, 4}, + {5, 4}, + {5, 4}, + {5, 4}, + {5, 4}, + {5, 4}, + {5, 4}, + {5, 4}, + {5, 4}, + + /* 011100xx = 10 */ + {10, 6}, + {10, 6}, + {10, 6}, + {10, 6}, + + /* 01110100 = 20 01110101 = 20+ 01110110 = 21 01110111 = 21+ */ + {20, 8}, + {20, 0}, + {21, 8}, + {21, 0}, + + /* 011110xx = 11 */ + {11, 6}, + {11, 6}, + {11, 6}, + {11, 6}, + + /* 01111100 = 22 01111101 = 22+ 01111110 = 23 01111111 = 23+ */ + {22, 8}, + {22, 0}, + {23, 8}, + {23, 0}, + + /* 10xxxxxx = 3 */ + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + {3, 2}, + + /* 1100xxxx = 6 */ + {6, 4}, + {6, 4}, + {6, 4}, + {6, 4}, + {6, 4}, + {6, 4}, + {6, 4}, + {6, 4}, + {6, 4}, + {6, 4}, + {6, 4}, + {6, 4}, + {6, 4}, + {6, 4}, + {6, 4}, + {6, 4}, + + /* 110100xx = 12 */ + {12, 6}, + {12, 6}, + {12, 6}, + {12, 6}, + + /* 11010100 = 24 11010101 = 24+ 11010110 = 25 11010111 = 25+ */ + {24, 8}, + {24, 0}, + {25, 8}, + {25, 0}, + + /* 110110xx = 13 */ + {13, 6}, + {13, 6}, + {13, 6}, + {13, 6}, + + /* 11011100 = 26 11011101 = 26+ 11011110 = 27 11011111 = 27+ */ + {26, 8}, + {26, 0}, + {27, 8}, + {27, 0}, + + /* 1110xxxx = 7 */ + {7, 4}, + {7, 4}, + {7, 4}, + {7, 4}, + {7, 4}, + {7, 4}, + {7, 4}, + {7, 4}, + {7, 4}, + {7, 4}, + {7, 4}, + {7, 4}, + {7, 4}, + {7, 4}, + {7, 4}, + {7, 4}, + + /* 111100xx = 14 */ + {14, 6}, + {14, 6}, + {14, 6}, + {14, 6}, + + /* 11110100 = 28 11110101 = 28+ 11110110 = 29 11110111 = 29+ */ + {28, 8}, + {28, 0}, + {29, 8}, + {29, 0}, + + /* 111110xx = 15 */ + {15, 6}, + {15, 6}, + {15, 6}, + {15, 6}, + + /* 11111100 = 30 11111101 = 30+ 11111110 = 31 11111111 = 31+ */ + {30, 8}, + {30, 0}, + {31, 8}, + {31, 0}}; +#endif - /* 0100xxxx = 4 */ - {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, - {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, +static unsigned int blz_getbit(struct blz_state *bs) { + unsigned int bit; - /* 010100xx = 8 */ - {8, 6}, {8, 6}, {8, 6}, {8, 6}, + /* Check if tag is empty */ + if (!bs->bits_left--) { + /* Load next tag */ + bs->tag = (unsigned int)bs->src[0] | ((unsigned int)bs->src[1] << 8); + bs->src += 2; + bs->bits_left = 15; + } - /* 01010100 = 16 01010101 = 16+ 01010110 = 17 01010111 = 17+ */ - {16, 8}, {16, 0}, {17, 8}, {17, 0}, + /* Shift bit out of tag */ + bit = (bs->tag & 0x8000) ? 1 : 0; + bs->tag <<= 1; - /* 010110xx = 9 */ - {9, 6}, {9, 6}, {9, 6}, {9, 6}, + return bit; +} - /* 01011100 = 18 01011101 = 18+ 01011110 = 19 01011111 = 19+ */ - {18, 8}, {18, 0}, {19, 8}, {19, 0}, +static unsigned long blz_getgamma(struct blz_state *bs) { + unsigned long result = 1; - /* 0110xxxx = 5 */ - {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, - {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, +#if !defined(BLZ_NO_LUT) + /* Decode up to 8 bits of gamma2 code using lookup if possible */ + if (bs->bits_left >= 8) { + unsigned int top8 = (bs->tag >> 8) & 0x00FF; + int shift; + + result = blz_gamma_lookup[top8][0]; + shift = (int)blz_gamma_lookup[top8][1]; + + if (shift) { + bs->tag <<= shift; + bs->bits_left -= shift; + return result; + } + + bs->tag <<= 8; + bs->bits_left -= 8; + } +#endif - /* 011100xx = 10 */ - {10, 6}, {10, 6}, {10, 6}, {10, 6}, + /* Input gamma2-encoded bits */ + do { + result = (result << 1) + blz_getbit(bs); + } while (blz_getbit(bs)); - /* 01110100 = 20 01110101 = 20+ 01110110 = 21 01110111 = 21+ */ - {20, 8}, {20, 0}, {21, 8}, {21, 0}, + return result; +} - /* 011110xx = 11 */ - {11, 6}, {11, 6}, {11, 6}, {11, 6}, +unsigned long blz_depack(const void *src, void *dst, unsigned long depacked_size) { + struct blz_state bs; + unsigned long dst_size = 0; - /* 01111100 = 22 01111101 = 22+ 01111110 = 23 01111111 = 23+ */ - {22, 8}, {22, 0}, {23, 8}, {23, 0}, + bs.src = (const unsigned char *)src; + bs.dst = (unsigned char *)dst; - /* 10xxxxxx = 3 */ - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, + /* Initialise to one bit left in tag; that bit is zero (a literal) */ + bs.bits_left = 1; + bs.tag = 0x4000; - /* 1100xxxx = 6 */ - {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, - {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, + /* Main decompression loop */ + while (dst_size < depacked_size) { + if (blz_getbit(&bs)) { + /* Input match length and offset */ + unsigned long len = blz_getgamma(&bs) + 2; + unsigned long off = blz_getgamma(&bs) - 2; - /* 110100xx = 12 */ - {12, 6}, {12, 6}, {12, 6}, {12, 6}, + off = (off << 8) + (unsigned long)*bs.src++ + 1; - /* 11010100 = 24 11010101 = 24+ 11010110 = 25 11010111 = 25+ */ - {24, 8}, {24, 0}, {25, 8}, {25, 0}, + /* Copy match */ + { + const unsigned char *p = bs.dst - off; + unsigned long i; - /* 110110xx = 13 */ - {13, 6}, {13, 6}, {13, 6}, {13, 6}, + for (i = len; i > 0; --i) { + *bs.dst++ = *p++; + } + } - /* 11011100 = 26 11011101 = 26+ 11011110 = 27 11011111 = 27+ */ - {26, 8}, {26, 0}, {27, 8}, {27, 0}, + dst_size += len; + } else { + /* Copy literal */ + *bs.dst++ = *bs.src++; - /* 1110xxxx = 7 */ - {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, - {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, + dst_size++; + } + } - /* 111100xx = 14 */ - {14, 6}, {14, 6}, {14, 6}, {14, 6}, + /* Return decompressed size */ + return dst_size; +} - /* 11110100 = 28 11110101 = 28+ 11110110 = 29 11110111 = 29+ */ - {28, 8}, {28, 0}, {29, 8}, {29, 0}, +unsigned long blz_depack_srcsize(const void *src, void *dst, unsigned long src_size) { + struct blz_state bs; + unsigned long dst_size = 0; + const unsigned char *src_end = src + src_size; - /* 111110xx = 15 */ - {15, 6}, {15, 6}, {15, 6}, {15, 6}, + bs.src = (const unsigned char *)src; + bs.dst = (unsigned char *)dst; - /* 11111100 = 30 11111101 = 30+ 11111110 = 31 11111111 = 31+ */ - {30, 8}, {30, 0}, {31, 8}, {31, 0} -}; -#endif + /* Initialise to one bit left in tag; that bit is zero (a literal) */ + bs.bits_left = 1; + bs.tag = 0x4000; -static unsigned int -blz_getbit(struct blz_state *bs) -{ - unsigned int bit; - - /* Check if tag is empty */ - if (!bs->bits_left--) { - /* Load next tag */ - bs->tag = (unsigned int) bs->src[0] - | ((unsigned int) bs->src[1] << 8); - bs->src += 2; - bs->bits_left = 15; - } - - /* Shift bit out of tag */ - bit = (bs->tag & 0x8000) ? 1 : 0; - bs->tag <<= 1; - - return bit; -} + /* Main decompression loop */ + while (bs.src < src_end) { + if (blz_getbit(&bs)) { + /* Input match length and offset */ + unsigned long len = blz_getgamma(&bs) + 2; + unsigned long off = blz_getgamma(&bs) - 2; -static unsigned long -blz_getgamma(struct blz_state *bs) -{ - unsigned long result = 1; + off = (off << 8) + (unsigned long)*bs.src++ + 1; -#if !defined(BLZ_NO_LUT) - /* Decode up to 8 bits of gamma2 code using lookup if possible */ - if (bs->bits_left >= 8) { - unsigned int top8 = (bs->tag >> 8) & 0x00FF; - int shift; - - result = blz_gamma_lookup[top8][0]; - shift = (int) blz_gamma_lookup[top8][1]; - - if (shift) { - bs->tag <<= shift; - bs->bits_left -= shift; - return result; - } - - bs->tag <<= 8; - bs->bits_left -= 8; - } -#endif + /* Copy match */ + { + const unsigned char *p = bs.dst - off; + unsigned long i; - /* Input gamma2-encoded bits */ - do { - result = (result << 1) + blz_getbit(bs); - } while (blz_getbit(bs)); + for (i = len; i > 0; --i) { + *bs.dst++ = *p++; + } + } - return result; -} + dst_size += len; + } else { + /* Copy literal */ + *bs.dst++ = *bs.src++; -unsigned long -blz_depack(const void *src, void *dst, unsigned long depacked_size) -{ - struct blz_state bs; - unsigned long dst_size = 0; - - bs.src = (const unsigned char *) src; - bs.dst = (unsigned char *) dst; - - /* Initialise to one bit left in tag; that bit is zero (a literal) */ - bs.bits_left = 1; - bs.tag = 0x4000; - - /* Main decompression loop */ - while (dst_size < depacked_size) { - if (blz_getbit(&bs)) { - /* Input match length and offset */ - unsigned long len = blz_getgamma(&bs) + 2; - unsigned long off = blz_getgamma(&bs) - 2; - - off = (off << 8) + (unsigned long) *bs.src++ + 1; - - /* Copy match */ - { - const unsigned char *p = bs.dst - off; - unsigned long i; - - for (i = len; i > 0; --i) { - *bs.dst++ = *p++; - } - } - - dst_size += len; - } - else { - /* Copy literal */ - *bs.dst++ = *bs.src++; - - dst_size++; - } - } - - /* Return decompressed size */ - return dst_size; -} + dst_size++; + } + } -unsigned long -blz_depack_srcsize(const void *src, void *dst, unsigned long src_size) -{ - struct blz_state bs; - unsigned long dst_size = 0; - const unsigned char *src_end = src + src_size; - - bs.src = (const unsigned char *) src; - bs.dst = (unsigned char *) dst; - - /* Initialise to one bit left in tag; that bit is zero (a literal) */ - bs.bits_left = 1; - bs.tag = 0x4000; - - /* Main decompression loop */ - while (bs.src < src_end) { - if (blz_getbit(&bs)) { - /* Input match length and offset */ - unsigned long len = blz_getgamma(&bs) + 2; - unsigned long off = blz_getgamma(&bs) - 2; - - off = (off << 8) + (unsigned long) *bs.src++ + 1; - - /* Copy match */ - { - const unsigned char *p = bs.dst - off; - unsigned long i; - - for (i = len; i > 0; --i) { - *bs.dst++ = *p++; - } - } - - dst_size += len; - } - else { - /* Copy literal */ - *bs.dst++ = *bs.src++; - - dst_size++; - } - } - - /* Return decompressed size */ - return dst_size; + /* Return decompressed size */ + return dst_size; } From 3b8383c7907c124304cf4ce7c403ff05efa0e549 Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Tue, 26 Dec 2023 23:42:11 +1100 Subject: [PATCH 08/18] Who knew, header guards are a wise idea --- .../ble/ble_stack/host/avdtp_internal.h | 5 +++++ .../ble/ble_stack/host/conn_internal.h | 4 ++++ .../ble/ble_stack/include/bluetooth/att.h | 18 ++++++++---------- .../ble/ble_stack/include/bluetooth/avdtp.h | 2 ++ .../ble/ble_stack/include/bluetooth/conn.h | 1 + 5 files changed, 20 insertions(+), 10 deletions(-) diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/avdtp_internal.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/avdtp_internal.h index e182689f4b..7825a6e46a 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/avdtp_internal.h +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/avdtp_internal.h @@ -7,6 +7,9 @@ */ #include +#include "l2cap.h" +#ifndef BLE_STACK_HOST_AVDTP_INTERNAL_H_ +#define BLE_STACK_HOST_AVDTP_INTERNAL_H_ /* @brief A2DP ROLE's */ #define A2DP_SRC_ROLE 0x00 @@ -173,3 +176,5 @@ int bt_avdtp_register_sep(uint8_t media_type, uint8_t role, /* AVDTP Discover Request */ int bt_avdtp_discover(struct bt_avdtp *session, struct bt_avdtp_discover_params *param); + +#endif \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn_internal.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn_internal.h index 3e6f0fe7b5..824cb292e2 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn_internal.h +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn_internal.h @@ -8,6 +8,8 @@ #include "work_q.h" #include #include +#ifndef BLE_STACK_HOST_CONN_INTERNAL_H_ +#define BLE_STACK_HOST_CONN_INTERNAL_H_ /* * Copyright (c) 2015 Intel Corporation * @@ -324,3 +326,5 @@ void bt_conn_process_tx(struct bt_conn *conn); */ int bt_hci_get_conn_handle(const struct bt_conn *conn, u16_t *conn_handle); #endif + +#endif //BLE_STACK_HOST_CONN_INTERNAL_H_ \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/att.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/att.h index 4e99cf2d84..f46a0828ff 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/att.h +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/att.h @@ -13,7 +13,7 @@ #ifdef __cplusplus extern "C" { #endif - +#include "buf.h" #include /* Error codes for Error response PDU */ @@ -43,20 +43,18 @@ extern "C" { #define BT_ATT_ERR_PROCEDURE_IN_PROGRESS 0xfe #define BT_ATT_ERR_OUT_OF_RANGE 0xff -typedef void (*bt_att_func_t)(struct bt_conn *conn, u8_t err, - const void *pdu, u16_t length, - void *user_data); +typedef void (*bt_att_func_t)(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data); typedef void (*bt_att_destroy_t)(void *user_data); /* ATT request context */ struct bt_att_req { - sys_snode_t node; - bt_att_func_t func; - bt_att_destroy_t destroy; - struct net_buf_simple_state state; - struct net_buf *buf; + sys_snode_t node; + bt_att_func_t func; + bt_att_destroy_t destroy; + struct net_buf_simple_state state; + struct net_buf *buf; #if defined(CONFIG_BT_SMP) - bool retrying; + bool retrying; #endif /* CONFIG_BT_SMP */ }; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/avdtp.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/avdtp.h index 72cc2c537b..f9c0963231 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/avdtp.h +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/avdtp.h @@ -14,6 +14,8 @@ extern "C" { #endif +#include "avdtp_internal.h" + /** @brief AVDTP SEID Information */ struct bt_avdtp_seid_info { /** Stream End Point ID */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/conn.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/conn.h index 98ba3c8c9c..12a32c15ae 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/conn.h +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/conn.h @@ -26,6 +26,7 @@ extern "C" { #endif +#include "conn_internal.h" /** Opaque type representing a connection to a remote device */ struct bt_conn; From 7dd56d112f993f32916a99398df5d85d62a3830f Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Tue, 26 Dec 2023 23:47:51 +1100 Subject: [PATCH 09/18] Squash some sizing warnings --- .../components/ble/ble_stack/host/conn.c | 23 ++++++++++--------- .../components/ble/ble_stack/host/hci_core.c | 2 +- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c index bdea4bcf22..3d22b293cd 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c @@ -28,12 +28,13 @@ #include "log.h" #include "att_internal.h" -#include "conn_internal.h" #include "gatt_internal.h" #include "hci_core.h" #include "keys.h" #include "l2cap_internal.h" #include "smp.h" + +#include "conn_internal.h" #if defined(BFLB_BLE) #include "ble_config.h" @@ -405,7 +406,7 @@ static struct bt_conn *conn_new(void) { #if defined(BFLB_BLE) bool le_check_valid_conn(void) { - int i; + size_t i; for (i = 0; i < ARRAY_SIZE(conns); i++) { if (atomic_get(&conns[i].ref)) { @@ -418,7 +419,7 @@ bool le_check_valid_conn(void) { #if defined(BFLB_HOST_ASSISTANT) void bt_notify_disconnected(void) { - int i; + size_t i; for (i = 0; i < ARRAY_SIZE(conns); i++) { if (atomic_get(&conns[i].ref)) { @@ -568,7 +569,7 @@ struct bt_conn *bt_conn_create_sco(const bt_addr_t *peer) { } struct bt_conn *bt_conn_lookup_addr_sco(const bt_addr_t *peer) { - int i; + size_t i; for (i = 0; i < ARRAY_SIZE(sco_conns); i++) { if (!atomic_get(&sco_conns[i].ref)) { @@ -588,7 +589,7 @@ struct bt_conn *bt_conn_lookup_addr_sco(const bt_addr_t *peer) { } struct bt_conn *bt_conn_lookup_addr_br(const bt_addr_t *peer) { - int i; + size_t i; for (i = 0; i < ARRAY_SIZE(conns); i++) { if (!atomic_get(&conns[i].ref)) { @@ -1674,7 +1675,7 @@ void bt_conn_set_state(struct bt_conn *conn, bt_conn_state_t state) { } struct bt_conn *bt_conn_lookup_handle(u16_t handle) { - int i; + size_t i; for (i = 0; i < ARRAY_SIZE(conns); i++) { if (!atomic_get(&conns[i].ref)) { @@ -1726,7 +1727,7 @@ int bt_conn_addr_le_cmp(const struct bt_conn *conn, const bt_addr_le_t *peer) { } struct bt_conn *bt_conn_lookup_addr_le(u8_t id, const bt_addr_le_t *peer) { - int i; + size_t i; for (i = 0; i < ARRAY_SIZE(conns); i++) { if (!atomic_get(&conns[i].ref)) { @@ -1746,7 +1747,7 @@ struct bt_conn *bt_conn_lookup_addr_le(u8_t id, const bt_addr_le_t *peer) { } struct bt_conn *bt_conn_lookup_state_le(const bt_addr_le_t *peer, const bt_conn_state_t state) { - int i; + size_t i; for (i = 0; i < ARRAY_SIZE(conns); i++) { if (!atomic_get(&conns[i].ref)) { @@ -1770,7 +1771,7 @@ struct bt_conn *bt_conn_lookup_state_le(const bt_addr_le_t *peer, const bt_conn_ } void bt_conn_foreach(int type, void (*func)(struct bt_conn *conn, void *data), void *data) { - int i; + size_t i; for (i = 0; i < ARRAY_SIZE(conns); i++) { if (!atomic_get(&conns[i].ref)) { @@ -1855,7 +1856,7 @@ int bt_conn_get_info(const struct bt_conn *conn, struct bt_conn_info *info) { int bt_conn_get_remote_dev_info(struct bt_conn_info *info) { int link_num = 0; - for (int i = 0; i < ARRAY_SIZE(conns); i++) { + for (size_t i = 0; i < ARRAY_SIZE(conns); i++) { if (!atomic_get(&conns[i].ref)) { continue; } @@ -2445,7 +2446,7 @@ int bt_conn_init(void) { #if defined(CONFIG_BT_SMP) int err; #endif - int i; + size_t i; #if defined(BFLB_BLE) #if defined(BFLB_DYNAMIC_ALLOC_MEM) diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c index 908f260f8e..a2d5873d14 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c @@ -5401,7 +5401,7 @@ int bt_disable(void) { static int set_ad(u16_t hci_op, const struct bt_ad *ad, size_t ad_len) { struct bt_hci_cp_le_set_adv_data *set_data; struct net_buf *buf; - int c, i; + size_t c, i; buf = bt_hci_cmd_create(hci_op, sizeof(*set_data)); if (!buf) { From c29fb23de9c486738cd0c7fc91382f4b966dc75e Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Tue, 26 Dec 2023 23:55:48 +1100 Subject: [PATCH 10/18] Drop broken usb stack --- .../bsp/bsp_common/usb/uart_interface.c | 158 --- .../bsp/bsp_common/usb/uart_interface.h | 44 - .../bl_mcu_sdk/bsp/bsp_common/usb/usb_dc.c | 54 - .../components/usb_stack/CMakeLists.txt | 52 - .../usb_stack/class/audio/usbd_audio.c | 109 -- .../usb_stack/class/audio/usbd_audio.h | 277 ---- .../components/usb_stack/class/cdc/usbd_cdc.c | 153 --- .../components/usb_stack/class/cdc/usbd_cdc.h | 442 ------ .../components/usb_stack/class/hid/usbd_hid.c | 271 ---- .../components/usb_stack/class/hid/usbd_hid.h | 360 ----- .../components/usb_stack/class/msc/usbd_msc.c | 909 ------------- .../components/usb_stack/class/msc/usbd_msc.h | 109 -- .../usb_stack/class/msc/usbd_scsi.h | 325 ----- .../usb_stack/class/video/usbd_video.c | 131 -- .../usb_stack/class/video/usbd_video.h | 821 ------------ .../usb_stack/class/webusb/usbd_webusb.h | 22 - .../usb_stack/class/winusb/usbd_winusb.h | 26 - .../components/usb_stack/common/usb_dc.h | 197 --- .../components/usb_stack/common/usb_def.h | 566 -------- .../components/usb_stack/common/usb_slist.h | 224 ---- .../components/usb_stack/common/usb_util.h | 150 --- .../components/usb_stack/core/usbd_core.c | 1184 ----------------- .../components/usb_stack/core/usbd_core.h | 138 -- 23 files changed, 6722 deletions(-) delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.c delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.h delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/usb_dc.c delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/CMakeLists.txt delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.c delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.h delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.c delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.h delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.c delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.h delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.c delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.h delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_scsi.h delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.c delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.h delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/webusb/usbd_webusb.h delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/winusb/usbd_winusb.h delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_dc.h delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_def.h delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_slist.h delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_util.h delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.c delete mode 100644 source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.h diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.c deleted file mode 100644 index 82d6675a22..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.c +++ /dev/null @@ -1,158 +0,0 @@ -/** - * @file uart_interface.c - * @brief - * - * Copyright (c) 2021 Bouffalolab team - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - */ -#include "uart_interface.h" -#include "bflb_platform.h" -#include "hal_dma.h" -#include "hal_gpio.h" -#include "hal_usb.h" - -#define USB_OUT_RINGBUFFER_SIZE (8 * 1024) -#define UART_RX_RINGBUFFER_SIZE (8 * 1024) -#define UART_TX_DMA_SIZE (4095) - -uint8_t usb_rx_mem[USB_OUT_RINGBUFFER_SIZE] __attribute__((section(".system_ram"))); -uint8_t uart_rx_mem[UART_RX_RINGBUFFER_SIZE] __attribute__((section(".system_ram"))); - -uint8_t src_buffer[UART_TX_DMA_SIZE] __attribute__((section(".tcm_code"))); - -struct device *uart1; -struct device *dma_ch2; - -Ring_Buffer_Type usb_rx_rb; -Ring_Buffer_Type uart1_rx_rb; - -void uart_irq_callback(struct device *dev, void *args, uint32_t size, uint32_t state) { - if (state == UART_EVENT_RX_FIFO) { - if (size && size < Ring_Buffer_Get_Empty_Length(&uart1_rx_rb)) { - Ring_Buffer_Write(&uart1_rx_rb, (uint8_t *)args, size); - } else { - MSG("RF OV\r\n"); - } - } else if (state == UART_EVENT_RTO) { - if (size && size < Ring_Buffer_Get_Empty_Length(&uart1_rx_rb)) { - Ring_Buffer_Write(&uart1_rx_rb, (uint8_t *)args, size); - } else { - MSG("RTO OV\r\n"); - } - } else if (state == UART_RX_FER_IT) { - MSG("RX ERR\r\n"); - } -} -void uart1_init(void) { -#ifdef UART1_INDEX - uart_register(UART1_INDEX, "uart1"); - uart1 = device_find("uart1"); - - if (uart1) { - // device_open(uart1, DEVICE_OFLAG_DMA_TX | DEVICE_OFLAG_INT_RX); - // device_set_callback(uart1, uart_irq_callback); - // device_control(uart1, DEVICE_CTRL_SET_INT, (void *)(UART_RX_FIFO_IT | UART_RTO_IT)); - } - - dma_register(DMA0_CH2_INDEX, "ch2"); - dma_ch2 = device_find("ch2"); - - if (dma_ch2) { - DMA_DEV(dma_ch2)->direction = DMA_MEMORY_TO_PERIPH; - DMA_DEV(dma_ch2)->transfer_mode = DMA_LLI_ONCE_MODE; - DMA_DEV(dma_ch2)->src_req = DMA_REQUEST_NONE; - DMA_DEV(dma_ch2)->dst_req = DMA_REQUEST_UART1_TX; - DMA_DEV(dma_ch2)->src_addr_inc = DMA_ADDR_INCREMENT_ENABLE; - DMA_DEV(dma_ch2)->dst_addr_inc = DMA_ADDR_INCREMENT_DISABLE; - DMA_DEV(dma_ch2)->src_burst_size = DMA_BURST_1BYTE; - DMA_DEV(dma_ch2)->dst_burst_size = DMA_BURST_1BYTE; - DMA_DEV(dma_ch2)->src_width = DMA_TRANSFER_WIDTH_8BIT; - DMA_DEV(dma_ch2)->dst_width = DMA_TRANSFER_WIDTH_8BIT; - device_open(dma_ch2, 0); - } -#endif -} - -void uart1_config(uint32_t baudrate, uart_databits_t databits, uart_parity_t parity, uart_stopbits_t stopbits) { - device_close(uart1); - UART_DEV(uart1)->baudrate = baudrate; - UART_DEV(uart1)->stopbits = stopbits; - UART_DEV(uart1)->parity = parity; - UART_DEV(uart1)->databits = (databits - 5); - device_open(uart1, DEVICE_OFLAG_DMA_TX | DEVICE_OFLAG_INT_RX); - device_set_callback(uart1, uart_irq_callback); - device_control(uart1, DEVICE_CTRL_SET_INT, (void *)(UART_RX_FIFO_IT | UART_RTO_IT)); - Ring_Buffer_Reset(&usb_rx_rb); - Ring_Buffer_Reset(&uart1_rx_rb); -} - -static uint8_t uart1_dtr; -static uint8_t uart1_rts; - -void uart1_set_dtr_rts(uint8_t dtr, uint8_t rts) { - uart1_dtr = dtr; - uart1_rts = rts; -} - -void uart1_dtr_init(void) { gpio_set_mode(uart1_dtr, GPIO_OUTPUT_MODE); } -void uart1_rts_init(void) { gpio_set_mode(uart1_rts, GPIO_OUTPUT_MODE); } -void uart1_dtr_deinit(void) { gpio_set_mode(uart1_dtr, GPIO_INPUT_MODE); } -void uart1_rts_deinit(void) { gpio_set_mode(uart1_rts, GPIO_INPUT_MODE); } -void dtr_pin_set(uint8_t status) { gpio_write(uart1_dtr, status); } -void rts_pin_set(uint8_t status) { gpio_write(uart1_rts, status); } -void ringbuffer_lock() { cpu_global_irq_disable(); } -void ringbuffer_unlock() { cpu_global_irq_enable(); } - -void uart_ringbuffer_init(void) { - /* init mem for ring_buffer */ - memset(usb_rx_mem, 0, USB_OUT_RINGBUFFER_SIZE); - memset(uart_rx_mem, 0, UART_RX_RINGBUFFER_SIZE); - - /* init ring_buffer */ - Ring_Buffer_Init(&usb_rx_rb, usb_rx_mem, USB_OUT_RINGBUFFER_SIZE, ringbuffer_lock, ringbuffer_unlock); - Ring_Buffer_Init(&uart1_rx_rb, uart_rx_mem, UART_RX_RINGBUFFER_SIZE, ringbuffer_lock, ringbuffer_unlock); -} - -static dma_control_data_t uart_dma_ctrl_cfg = {.bits.fix_cnt = 0, - .bits.dst_min_mode = 0, - .bits.dst_add_mode = 0, - .bits.SI = 1, - .bits.DI = 0, - .bits.SWidth = DMA_TRANSFER_WIDTH_8BIT, - .bits.DWidth = DMA_TRANSFER_WIDTH_8BIT, - .bits.SBSize = 0, - .bits.DBSize = 0, - .bits.I = 0, - .bits.TransferSize = 4095}; -static dma_lli_ctrl_t uart_lli_list = {.src_addr = (uint32_t)src_buffer, .dst_addr = DMA_ADDR_UART1_TDR, .nextlli = 0}; - -void uart_send_from_ringbuffer(void) { - if (Ring_Buffer_Get_Length(&usb_rx_rb)) { - if (!dma_channel_check_busy(dma_ch2)) { - uint32_t avalibleCnt = Ring_Buffer_Read(&usb_rx_rb, src_buffer, UART_TX_DMA_SIZE); - - if (avalibleCnt) { - dma_channel_stop(dma_ch2); - uart_dma_ctrl_cfg.bits.TransferSize = avalibleCnt; - memcpy(&uart_lli_list.cfg, &uart_dma_ctrl_cfg, sizeof(dma_control_data_t)); - dma_channel_update(dma_ch2, (void *)((uint32_t)&uart_lli_list)); - dma_channel_start(dma_ch2); - } - } - } -} \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.h deleted file mode 100644 index 46d5b0c20d..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.h +++ /dev/null @@ -1,44 +0,0 @@ -/** - * @file uart_interface.h - * @brief - * - * Copyright (c) 2021 Bouffalolab team - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - */ - -#ifndef __UART_IF_H__ -#define __UART_IF_H__ - -#include "hal_uart.h" -#include "ring_buffer.h" - -extern Ring_Buffer_Type usb_rx_rb; -extern Ring_Buffer_Type uart1_rx_rb; - -void uart1_init(void); -void uart1_config(uint32_t baudrate, uart_databits_t databits, uart_parity_t parity, uart_stopbits_t stopbits); -void uart1_set_dtr_rts(uint8_t dtr, uint8_t rts); -void uart1_dtr_init(void); -void uart1_rts_init(void); -void uart1_dtr_deinit(void); -void uart1_rts_deinit(void); -void dtr_pin_set(uint8_t status); -void rts_pin_set(uint8_t status); -void uart_ringbuffer_init(void); -void uart_send_from_ringbuffer(void); -#endif \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/usb_dc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/usb_dc.c deleted file mode 100644 index 8b5712bafa..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/usb_dc.c +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @file usb_dc.c - * @brief - * - * Copyright (c) 2021 Bouffalolab team - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - */ - -#include "hal_usb.h" -#include "stdbool.h" -#include "usbd_core.h" - -struct device *usb; - -#ifdef USB_INDEX -static void usb_dc_event_callback(struct device *dev, void *args, uint32_t size, uint32_t state) { usbd_event_notify_handler(state, args); } -#endif -struct device *usb_dc_init(void) { -#ifdef USB_INDEX - usb_dc_register(USB_INDEX, "usb"); - usb = device_find("usb"); - device_set_callback(usb, usb_dc_event_callback); - device_open(usb, 0); - return usb; -#endif - return NULL; -} - -int usbd_set_address(const uint8_t addr) { return usb_dc_set_dev_address(addr); } - -int usbd_ep_open(const struct usbd_endpoint_cfg *ep_cfg) { return usb_dc_ep_open(usb, (const struct usb_dc_ep_cfg *)ep_cfg); } -int usbd_ep_close(const uint8_t ep) { return usb_dc_ep_close(ep); } -int usbd_ep_set_stall(const uint8_t ep) { return usb_dc_ep_set_stall(ep); } -int usbd_ep_clear_stall(const uint8_t ep) { return usb_dc_ep_clear_stall(ep); } -int usbd_ep_is_stalled(const uint8_t ep, uint8_t *stalled) { return usb_dc_ep_is_stalled(usb, ep, stalled); } - -int usbd_ep_write(const uint8_t ep, const uint8_t *data, uint32_t data_len, uint32_t *ret_bytes) { return usb_dc_ep_write(usb, ep, data, data_len, ret_bytes); } - -int usbd_ep_read(const uint8_t ep, uint8_t *data, uint32_t max_data_len, uint32_t *read_bytes) { return usb_dc_ep_read(usb, ep, data, max_data_len, read_bytes); } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/CMakeLists.txt b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/CMakeLists.txt deleted file mode 100644 index b140a92730..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/CMakeLists.txt +++ /dev/null @@ -1,52 +0,0 @@ -################# Add global include ################# -list(APPEND ADD_INCLUDE -"${CMAKE_CURRENT_SOURCE_DIR}/core" -"${CMAKE_CURRENT_SOURCE_DIR}/common" -"${CMAKE_CURRENT_SOURCE_DIR}/class/cdc" -"${CMAKE_CURRENT_SOURCE_DIR}/class/hid" -"${CMAKE_CURRENT_SOURCE_DIR}/class/msc" -"${CMAKE_CURRENT_SOURCE_DIR}/class/video" -"${CMAKE_CURRENT_SOURCE_DIR}/class/audio" -"${CMAKE_CURRENT_SOURCE_DIR}/class/winusb" -) -####################################################### - -################# Add private include ################# -# list(APPEND ADD_PRIVATE_INCLUDE -# ) -####################################################### - -############## Add current dir source files ########### -file(GLOB_RECURSE sources "${CMAKE_CURRENT_SOURCE_DIR}/core/*.c" -"${CMAKE_CURRENT_SOURCE_DIR}/class/*.c" -) -list(APPEND ADD_SRCS ${sources}) -# aux_source_directory(src ADD_SRCS) -####################################################### - -########### Add required/dependent components ######### -#list(APPEND ADD_REQUIREMENTS xxx) -####################################################### - -############ Add static libs ########################## -#list(APPEND ADD_STATIC_LIB "libxxx.a") -####################################################### - -############ Add dynamic libs ######################### -# list(APPEND ADD_DYNAMIC_LIB "libxxx.so" -# ) -####################################################### - -############ Add global compile option ################ -#add components denpend on this component -if(CONFIG_USB_HS) -list(APPEND ADD_DEFINITIONS -DCONFIG_USB_HS) -endif() -####################################################### - -############ Add private compile option ################ -#add compile option for this component that won't affect other modules -# list(APPEND ADD_PRIVATE_DEFINITIONS -Dxxx) -####################################################### - -generate_library() diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.c deleted file mode 100644 index 15c19a29f6..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.c +++ /dev/null @@ -1,109 +0,0 @@ -#include "usbd_audio.h" -#include "usbd_core.h" - -struct usbd_audio_control_info audio_control_info = {0xdb00, 0x0000, 0x0100, 0xf600, 0}; - -int audio_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) { - USBD_LOG_DBG("AUDIO Class request: " - "bRequest 0x%02x\r\n", - setup->bRequest); - - switch (setup->bRequest) { - case AUDIO_REQUEST_SET_CUR: - - if (setup->wValueL == 0x01) { - if (setup->wValueH == AUDIO_FU_CONTROL_MUTE) { - memcpy(&audio_control_info.mute, *data, *len); - } else if (setup->wValueH == AUDIO_FU_CONTROL_VOLUME) { - memcpy(&audio_control_info.vol_current, *data, *len); - uint32_t vol; - if (audio_control_info.vol_current == 0) { - vol = 100; - } else { - vol = (audio_control_info.vol_current - 0xDB00 + 1) * 100 / (0xFFFF - 0xDB00); - } - usbd_audio_set_volume(vol); - USBD_LOG_INFO("current audio volume:%d\r\n", vol); - } - } - - break; - - case AUDIO_REQUEST_GET_CUR: - if (setup->wValueH == AUDIO_FU_CONTROL_MUTE) { - *data = (uint8_t *)&audio_control_info.mute; - *len = 1; - } else if (setup->wValueH == AUDIO_FU_CONTROL_VOLUME) { - *data = (uint8_t *)&audio_control_info.vol_current; - *len = 2; - } - - break; - - case AUDIO_REQUEST_SET_RES: - break; - - case AUDIO_REQUEST_SET_MEM: - break; - - case AUDIO_REQUEST_GET_MIN: - *data = (uint8_t *)&audio_control_info.vol_min; - *len = 2; - break; - - case AUDIO_REQUEST_GET_MAX: - *data = (uint8_t *)&audio_control_info.vol_max; - *len = 2; - break; - - case AUDIO_REQUEST_GET_RES: - *data = (uint8_t *)&audio_control_info.vol_res; - *len = 2; - break; - case AUDIO_REQUEST_GET_MEM: - *data[0] = 0; - *len = 1; - break; - - default: - USBD_LOG_WRN("Unhandled Audio Class bRequest 0x%02x\r\n", setup->bRequest); - return -1; - } - - return 0; -} - -void audio_notify_handler(uint8_t event, void *arg) { - switch (event) { - case USB_EVENT_RESET: - - break; - - case USB_EVENT_SOF: - break; - - case USB_EVENT_SET_INTERFACE: - usbd_audio_set_interface_callback(((uint8_t *)arg)[3]); - break; - - default: - break; - } -} - -__weak void usbd_audio_set_volume(uint8_t vol) {} - -void usbd_audio_add_interface(usbd_class_t *class, usbd_interface_t *intf) { - static usbd_class_t *last_class = NULL; - - if (last_class != class) { - last_class = class; - usbd_class_register(class); - } - - intf->class_handler = audio_class_request_handler; - intf->custom_handler = NULL; - intf->vendor_handler = NULL; - intf->notify_handler = audio_notify_handler; - usbd_class_add_interface(class, intf); -} \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.h deleted file mode 100644 index 35f3fe25f2..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.h +++ /dev/null @@ -1,277 +0,0 @@ -/** - * @file - * @brief USB Audio Device Class public header - * - * Header follows below documentation: - * - USB Device Class Definition for Audio Devices (audio10.pdf) - * - * Additional documentation considered a part of USB Audio v1.0: - * - USB Device Class Definition for Audio Data Formats (frmts10.pdf) - * - USB Device Class Definition for Terminal Types (termt10.pdf) - */ - -#ifndef _USBD_AUDIO_H_ -#define _USBD_AUDIO_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -/** Audio Interface Subclass Codes - * Refer to Table A-2 from audio10.pdf - */ -#define AUDIO_SUBCLASS_UNDEFINED 0x00 -#define AUDIO_SUBCLASS_AUDIOCONTROL 0x01 -#define AUDIO_SUBCLASS_AUDIOSTREAMING 0x02 -#define AUDIO_SUBCLASS_MIDISTREAMING 0x03 - -#define AUDIO_PROTOCOL_UNDEFINED 0x00U - -#define AUDIO_ENDPOINT_GENERAL 0x01U - -/** Audio Class-Specific Control Interface Descriptor Subtypes - * Refer to Table A-5 from audio10.pdf - */ -#define AUDIO_CONTROL_UNDEFINED 0x01U -#define AUDIO_CONTROL_HEADER 0x01U -#define AUDIO_CONTROL_INPUT_TERMINAL 0x02U -#define AUDIO_CONTROL_OUTPUT_TERMINAL 0x03U -#define AUDIO_CONTROL_MIXER_UNIT 0x04U -#define AUDIO_CONTROL_SELECTOR_UNIT 0x05U -#define AUDIO_CONTROL_FEATURE_UNIT 0x06U -#define AUDIO_CONTROL_PROCESSING_UNIT 0x07U -#define AUDIO_CONTROL_EXTENSION_UNIT 0x08U - -/** Audio Class-Specific AS Interface Descriptor Subtypes - * Refer to Table A-6 from audio10.pdf - */ -#define AUDIO_STREAMING_UNDEFINED 0x00U -#define AUDIO_STREAMING_GENERAL 0x01U -#define AUDIO_STREAMING_FORMAT_TYPE 0x02U -#define AUDIO_STREAMING_FORMAT_SPECIFIC 0x03U - -/** Audio Class-Specific Request Codes - * Refer to Table A-9 from audio10.pdf - */ -#define AUDIO_REQUEST_UNDEFINED 0x00 -#define AUDIO_REQUEST_SET_CUR 0x01 -#define AUDIO_REQUEST_GET_CUR 0x81 -#define AUDIO_REQUEST_SET_MIN 0x02 -#define AUDIO_REQUEST_GET_MIN 0x82 -#define AUDIO_REQUEST_SET_MAX 0x03 -#define AUDIO_REQUEST_GET_MAX 0x83 -#define AUDIO_REQUEST_SET_RES 0x04 -#define AUDIO_REQUEST_GET_RES 0x84 -#define AUDIO_REQUEST_SET_MEM 0x05 -#define AUDIO_REQUEST_GET_MEM 0x85 -#define AUDIO_REQUEST_GET_STAT 0xFF - -/* Feature Unit Control Bits */ -#define AUDIO_CONTROL_MUTE 0x0001 -#define AUDIO_CONTROL_VOLUME 0x0002 -#define AUDIO_CONTROL_BASS 0x0004 -#define AUDIO_CONTROL_MID 0x0008 -#define AUDIO_CONTROL_TREBLE 0x0010 -#define AUDIO_CONTROL_GRAPHIC_EQUALIZER 0x0020 -#define AUDIO_CONTROL_AUTOMATIC_GAIN 0x0040 -#define AUDIO_CONTROL_DEALY 0x0080 -#define AUDIO_CONTROL_BASS_BOOST 0x0100 -#define AUDIO_CONTROL_LOUDNESS 0x0200 - -/** Feature Unit Control Selectors - * Refer to Table A-11 from audio10.pdf - */ -#define AUDIO_FU_CONTROL_MUTE 0x01 -#define AUDIO_FU_CONTROL_VOLUME 0x02 -#define AUDIO_FU_CONTROL_BASS 0x03 -#define AUDIO_FU_CONTROL_MID 0x04 -#define AUDIO_FU_CONTROL_TREBLE 0x05 -#define AUDIO_FU_CONTROL_GRAPHIC_EQUALIZER 0x06 -#define AUDIO_FU_CONTROL_AUTOMATIC_GAIN 0x07 -#define AUDIO_FU_CONTROL_DELAY 0x08 -#define AUDIO_FU_CONTROL_BASS_BOOST 0x09 -#define AUDIO_FU_CONTROL_LOUDNESS 0x0A - -/* Audio Descriptor Types */ -#define AUDIO_UNDEFINED_DESCRIPTOR_TYPE 0x20 -#define AUDIO_DEVICE_DESCRIPTOR_TYPE 0x21 -#define AUDIO_CONFIGURATION_DESCRIPTOR_TYPE 0x22 -#define AUDIO_STRING_DESCRIPTOR_TYPE 0x23 -#define AUDIO_INTERFACE_DESCRIPTOR_TYPE 0x24 -#define AUDIO_ENDPOINT_DESCRIPTOR_TYPE 0x25 - -/* Audio Data Format Type I Codes */ -#define AUDIO_FORMAT_TYPE_I_UNDEFINED 0x0000 -#define AUDIO_FORMAT_PCM 0x0001 -#define AUDIO_FORMAT_PCM8 0x0002 -#define AUDIO_FORMAT_IEEE_FLOAT 0x0003 -#define AUDIO_FORMAT_ALAW 0x0004 -#define AUDIO_FORMAT_MULAW 0x0005 - -/* Predefined Audio Channel Configuration Bits */ -#define AUDIO_CHANNEL_M 0x0000 /* Mono */ -#define AUDIO_CHANNEL_L 0x0001 /* Left Front */ -#define AUDIO_CHANNEL_R 0x0002 /* Right Front */ -#define AUDIO_CHANNEL_C 0x0004 /* Center Front */ -#define AUDIO_CHANNEL_LFE 0x0008 /* Low Freq. Enhance. */ -#define AUDIO_CHANNEL_LS 0x0010 /* Left Surround */ -#define AUDIO_CHANNEL_RS 0x0020 /* Right Surround */ -#define AUDIO_CHANNEL_LC 0x0040 /* Left of Center */ -#define AUDIO_CHANNEL_RC 0x0080 /* Right of Center */ -#define AUDIO_CHANNEL_S 0x0100 /* Surround */ -#define AUDIO_CHANNEL_SL 0x0200 /* Side Left */ -#define AUDIO_CHANNEL_SR 0x0400 /* Side Right */ -#define AUDIO_CHANNEL_T 0x0800 /* Top */ - -#define AUDIO_FORMAT_TYPE_I 0x01 -#define AUDIO_FORMAT_TYPE_II 0x02 -#define AUDIO_FORMAT_TYPE_III 0x03 - -/** USB Terminal Types - * Refer to Table 2-1 - Table 2-4 from termt10.pdf - */ -enum usb_audio_terminal_types { - /* USB Terminal Types */ - USB_AUDIO_USB_UNDEFINED = 0x0100, - USB_AUDIO_USB_STREAMING = 0x0101, - USB_AUDIO_USB_VENDOR_SPEC = 0x01FF, - - /* Input Terminal Types */ - USB_AUDIO_IN_UNDEFINED = 0x0200, - USB_AUDIO_IN_MICROPHONE = 0x0201, - USB_AUDIO_IN_DESKTOP_MIC = 0x0202, - USB_AUDIO_IN_PERSONAL_MIC = 0x0203, - USB_AUDIO_IN_OM_DIR_MIC = 0x0204, - USB_AUDIO_IN_MIC_ARRAY = 0x0205, - USB_AUDIO_IN_PROC_MIC_ARRAY = 0x0205, - - /* Output Terminal Types */ - USB_AUDIO_OUT_UNDEFINED = 0x0300, - USB_AUDIO_OUT_SPEAKER = 0x0301, - USB_AUDIO_OUT_HEADPHONES = 0x0302, - USB_AUDIO_OUT_HEAD_AUDIO = 0x0303, - USB_AUDIO_OUT_DESKTOP_SPEAKER = 0x0304, - USB_AUDIO_OUT_ROOM_SPEAKER = 0x0305, - USB_AUDIO_OUT_COMM_SPEAKER = 0x0306, - USB_AUDIO_OUT_LOW_FREQ_SPEAKER = 0x0307, - - /* Bi-directional Terminal Types */ - USB_AUDIO_IO_UNDEFINED = 0x0400, - USB_AUDIO_IO_HANDSET = 0x0401, - USB_AUDIO_IO_HEADSET = 0x0402, - USB_AUDIO_IO_SPEAKERPHONE_ECHO_NONE = 0x0403, - USB_AUDIO_IO_SPEAKERPHONE_ECHO_SUP = 0x0404, - USB_AUDIO_IO_SPEAKERPHONE_ECHO_CAN = 0x0405, -}; - -/** - * @warning Size of baInterface is 2 just to make it useable - * for all kind of devices: headphones, microphone and headset. - * Actual size of the struct should be checked by reading - * .bLength. - */ -struct cs_ac_if_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bDescriptorSubtype; - uint16_t bcdADC; - uint16_t wTotalLength; - uint8_t bInCollection; - uint8_t baInterfaceNr[2]; -} __packed; - -struct input_terminal_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bDescriptorSubtype; - uint8_t bTerminalID; - uint16_t wTerminalType; - uint8_t bAssocTerminal; - uint8_t bNrChannels; - uint16_t wChannelConfig; - uint8_t iChannelNames; - uint8_t iTerminal; -} __packed; - -/** - * @note Size of Feature unit descriptor is not fixed. - * This structure is just a helper not a common type. - */ -struct feature_unit_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bDescriptorSubtype; - uint8_t bUnitID; - uint8_t bSourceID; - uint8_t bControlSize; - uint16_t bmaControls[1]; -} __packed; - -struct output_terminal_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bDescriptorSubtype; - uint8_t bTerminalID; - uint16_t wTerminalType; - uint8_t bAssocTerminal; - uint8_t bSourceID; - uint8_t iTerminal; -} __packed; - -struct as_cs_interface_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bDescriptorSubtype; - uint8_t bTerminalLink; - uint8_t bDelay; - uint16_t wFormatTag; -} __packed; - -struct format_type_i_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bDescriptorSubtype; - uint8_t bFormatType; - uint8_t bNrChannels; - uint8_t bSubframeSize; - uint8_t bBitResolution; - uint8_t bSamFreqType; - uint8_t tSamFreq[3]; -} __packed; - -struct std_as_ad_endpoint_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bEndpointAddress; - uint8_t bmAttributes; - uint16_t wMaxPacketSize; - uint8_t bInterval; - uint8_t bRefresh; - uint8_t bSynchAddress; -} __packed; - -struct cs_as_ad_ep_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bDescriptorSubtype; - uint8_t bmAttributes; - uint8_t bLockDelayUnits; - uint16_t wLockDelay; -} __packed; - -struct usbd_audio_control_info { - uint16_t vol_min; - uint16_t vol_max; - uint16_t vol_res; - uint16_t vol_current; - uint8_t mute; -}; - -void usbd_audio_add_interface(usbd_class_t *class, usbd_interface_t *intf); -void usbd_audio_set_interface_callback(uint8_t value); -void usbd_audio_set_volume(uint8_t vol); -#ifdef __cplusplus -} -#endif - -#endif /* _USB_AUDIO_H_ */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.c deleted file mode 100644 index 81384d6f21..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.c +++ /dev/null @@ -1,153 +0,0 @@ -/** - * @file usbd_cdc.c - * @brief - * - * Copyright (c) 2021 Bouffalolab team - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - */ -#include "usbd_cdc.h" -#include "usbd_core.h" - -const char *stop_name[] = {"1", "1.5", "2"}; -const char *parity_name[] = {"N", "O", "E", "M", "S"}; - -/* Device data structure */ -struct cdc_acm_cfg_private { - /* CDC ACM line coding properties. LE order */ - struct cdc_line_coding line_coding; - /* CDC ACM line state bitmap, DTE side */ - uint8_t line_state; - /* CDC ACM serial state bitmap, DCE side */ - uint8_t serial_state; - /* CDC ACM notification sent status */ - uint8_t notification_sent; - /* CDC ACM configured flag */ - bool configured; - /* CDC ACM suspended flag */ - bool suspended; - uint32_t uart_first_init_flag; - -} usbd_cdc_acm_cfg; - -static void usbd_cdc_acm_reset(void) { - usbd_cdc_acm_cfg.line_coding.dwDTERate = 2000000; - usbd_cdc_acm_cfg.line_coding.bDataBits = 8; - usbd_cdc_acm_cfg.line_coding.bParityType = 0; - usbd_cdc_acm_cfg.line_coding.bCharFormat = 0; - usbd_cdc_acm_cfg.configured = false; - usbd_cdc_acm_cfg.uart_first_init_flag = 0; -} - -/** - * @brief Handler called for Class requests not handled by the USB stack. - * - * @param setup Information about the request to execute. - * @param len Size of the buffer. - * @param data Buffer containing the request result. - * - * @return 0 on success, negative errno code on fail. - */ -static int cdc_acm_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) { - USBD_LOG_DBG("CDC Class request: " - "bRequest 0x%02x\r\n", - setup->bRequest); - - switch (setup->bRequest) { - case CDC_REQUEST_SET_LINE_CODING: - - /*******************************************************************************/ - /* Line Coding Structure */ - /*-----------------------------------------------------------------------------*/ - /* Offset | Field | Size | Value | Description */ - /* 0 | dwDTERate | 4 | Number |Data terminal rate, in bits per second*/ - /* 4 | bCharFormat | 1 | Number | Stop bits */ - /* 0 - 1 Stop bit */ - /* 1 - 1.5 Stop bits */ - /* 2 - 2 Stop bits */ - /* 5 | bParityType | 1 | Number | Parity */ - /* 0 - None */ - /* 1 - Odd */ - /* 2 - Even */ - /* 3 - Mark */ - /* 4 - Space */ - /* 6 | bDataBits | 1 | Number Data bits (5, 6, 7, 8 or 16). */ - /*******************************************************************************/ - if (usbd_cdc_acm_cfg.uart_first_init_flag == 0) { - usbd_cdc_acm_cfg.uart_first_init_flag = 1; - return 0; - } - - memcpy(&usbd_cdc_acm_cfg.line_coding, *data, sizeof(usbd_cdc_acm_cfg.line_coding)); - USBD_LOG_DBG("CDC_SET_LINE_CODING <%d %d %s %s>\r\n", usbd_cdc_acm_cfg.line_coding.dwDTERate, usbd_cdc_acm_cfg.line_coding.bDataBits, parity_name[usbd_cdc_acm_cfg.line_coding.bParityType], - stop_name[usbd_cdc_acm_cfg.line_coding.bCharFormat]); - usbd_cdc_acm_set_line_coding(usbd_cdc_acm_cfg.line_coding.dwDTERate, usbd_cdc_acm_cfg.line_coding.bDataBits, usbd_cdc_acm_cfg.line_coding.bParityType, usbd_cdc_acm_cfg.line_coding.bCharFormat); - break; - - case CDC_REQUEST_SET_CONTROL_LINE_STATE: - usbd_cdc_acm_cfg.line_state = (uint8_t)setup->wValue; - bool dtr = (setup->wValue & 0x01); - bool rts = (setup->wValue & 0x02); - USBD_LOG_DBG("DTR 0x%x,RTS 0x%x\r\n", dtr, rts); - usbd_cdc_acm_set_dtr(dtr); - usbd_cdc_acm_set_rts(rts); - break; - - case CDC_REQUEST_GET_LINE_CODING: - *data = (uint8_t *)(&usbd_cdc_acm_cfg.line_coding); - *len = sizeof(usbd_cdc_acm_cfg.line_coding); - USBD_LOG_DBG("CDC_GET_LINE_CODING %d %d %d %d\r\n", usbd_cdc_acm_cfg.line_coding.dwDTERate, usbd_cdc_acm_cfg.line_coding.bCharFormat, usbd_cdc_acm_cfg.line_coding.bParityType, - usbd_cdc_acm_cfg.line_coding.bDataBits); - break; - - default: - USBD_LOG_WRN("Unhandled CDC Class bRequest 0x%02x\r\n", setup->bRequest); - return -1; - } - - return 0; -} - -static void cdc_notify_handler(uint8_t event, void *arg) { - switch (event) { - case USB_EVENT_RESET: - usbd_cdc_acm_reset(); - break; - - default: - break; - } -} - -__weak void usbd_cdc_acm_set_line_coding(uint32_t baudrate, uint8_t databits, uint8_t parity, uint8_t stopbits) {} -__weak void usbd_cdc_acm_set_dtr(bool dtr) {} -__weak void usbd_cdc_acm_set_rts(bool rts) {} - -void usbd_cdc_add_acm_interface(usbd_class_t *class, usbd_interface_t *intf) { - static usbd_class_t *last_class = NULL; - - if (last_class != class) { - last_class = class; - usbd_class_register(class); - } - - intf->class_handler = cdc_acm_class_request_handler; - intf->custom_handler = NULL; - intf->vendor_handler = NULL; - intf->notify_handler = cdc_notify_handler; - usbd_class_add_interface(class, intf); -} diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.h deleted file mode 100644 index 33c2ac29c4..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.h +++ /dev/null @@ -1,442 +0,0 @@ -/** - * @file - * @brief USB Communications Device Class (CDC) public header - * - * Header follows the Class Definitions for - * Communications Devices Specification (CDC120-20101103-track.pdf), - * PSTN Devices Specification (PSTN120.pdf) and - * Ethernet Control Model Devices Specification (ECM120.pdf). - * Header is limited to ACM and ECM Subclasses. - */ - -#ifndef _USBD_CDC_H -#define _USBD_CDC_H - -#ifdef __cplusplus -extern "C" { -#endif - -/*------------------------------------------------------------------------------ - * Definitions based on usbcdc11.pdf (www.usb.org) - *----------------------------------------------------------------------------*/ -/* Communication device class specification version 1.10 */ -#define CDC_V1_10 0x0110U -// Communication device class specification version 1.2 -#define CDC_V1_2_0 0x0120U - -/* Communication interface class code */ -/* (usbcdc11.pdf, 4.2, Table 15) */ -#define CDC_COMMUNICATION_INTERFACE_CLASS 0x02U - -/* Communication interface class subclass codes */ -/* (usbcdc11.pdf, 4.3, Table 16) */ -#define CDC_DIRECT_LINE_CONTROL_MODEL 0x01U -#define CDC_ABSTRACT_CONTROL_MODEL 0x02U -#define CDC_TELEPHONE_CONTROL_MODEL 0x03U -#define CDC_MULTI_CHANNEL_CONTROL_MODEL 0x04U -#define CDC_CAPI_CONTROL_MODEL 0x05U -#define CDC_ETHERNET_NETWORKING_CONTROL_MODEL 0x06U -#define CDC_ATM_NETWORKING_CONTROL_MODEL 0x07U -#define CDC_WIRELESS_HANDSET_CONTROL_MODEL 0x08U -#define CDC_DEVICE_MANAGEMENT 0x09U -#define CDC_MOBILE_DIRECT_LINE_MODEL 0x0AU -#define CDC_OBEX 0x0BU -#define CDC_ETHERNET_EMULATION_MODEL 0x0CU -#define CDC_NETWORK_CONTROL_MODEL 0x0DU - -/* Communication interface class control protocol codes */ -/* (usbcdc11.pdf, 4.4, Table 17) */ -#define CDC_COMMON_PROTOCOL_NONE 0x00U -#define CDC_COMMON_PROTOCOL_AT_COMMANDS 0x01U -#define CDC_COMMON_PROTOCOL_AT_COMMANDS_PCCA_101 0x02U -#define CDC_COMMON_PROTOCOL_AT_COMMANDS_PCCA_101_AND_ANNEXO 0x03U -#define CDC_COMMON_PROTOCOL_AT_COMMANDS_GSM_707 0x04U -#define CDC_COMMON_PROTOCOL_AT_COMMANDS_3GPP_27007 0x05U -#define CDC_COMMON_PROTOCOL_AT_COMMANDS_CDMA 0x06U -#define CDC_COMMON_PROTOCOL_ETHERNET_EMULATION_MODEL 0x07U -// NCM Communication Interface Protocol Codes -// (usbncm10.pdf, 4.2, Table 4-2) -#define CDC_NCM_PROTOCOL_NONE 0x00U -#define CDC_NCM_PROTOCOL_OEM 0xFEU - -/* Data interface class code */ -/* (usbcdc11.pdf, 4.5, Table 18) */ -#define CDC_DATA_INTERFACE_CLASS 0x0A - -/* Data interface class protocol codes */ -/* (usbcdc11.pdf, 4.7, Table 19) */ -#define CDC_DATA_PROTOCOL_ISDN_BRI 0x30 -#define CDC_DATA_PROTOCOL_HDLC 0x31 -#define CDC_DATA_PROTOCOL_TRANSPARENT 0x32 -#define CDC_DATA_PROTOCOL_Q921_MANAGEMENT 0x50 -#define CDC_DATA_PROTOCOL_Q921_DATA_LINK 0x51 -#define CDC_DATA_PROTOCOL_Q921_MULTIPLEXOR 0x52 -#define CDC_DATA_PROTOCOL_V42 0x90 -#define CDC_DATA_PROTOCOL_EURO_ISDN 0x91 -#define CDC_DATA_PROTOCOL_V24_RATE_ADAPTATION 0x92 -#define CDC_DATA_PROTOCOL_CAPI 0x93 -#define CDC_DATA_PROTOCOL_HOST_BASED_DRIVER 0xFD -#define CDC_DATA_PROTOCOL_DESCRIBED_IN_PUFD 0xFE - -/* Type values for bDescriptorType field of functional descriptors */ -/* (usbcdc11.pdf, 5.2.3, Table 24) */ -#define CDC_CS_INTERFACE 0x24 -#define CDC_CS_ENDPOINT 0x25 - -/* Type values for bDescriptorSubtype field of functional descriptors */ -/* (usbcdc11.pdf, 5.2.3, Table 25) */ -#define CDC_FUNC_DESC_HEADER 0x00 -#define CDC_FUNC_DESC_CALL_MANAGEMENT 0x01 -#define CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT 0x02 -#define CDC_FUNC_DESC_DIRECT_LINE_MANAGEMENT 0x03 -#define CDC_FUNC_DESC_TELEPHONE_RINGER 0x04 -#define CDC_FUNC_DESC_REPORTING_CAPABILITIES 0x05 -#define CDC_FUNC_DESC_UNION 0x06 -#define CDC_FUNC_DESC_COUNTRY_SELECTION 0x07 -#define CDC_FUNC_DESC_TELEPHONE_OPERATIONAL_MODES 0x08 -#define CDC_FUNC_DESC_USB_TERMINAL 0x09 -#define CDC_FUNC_DESC_NETWORK_CHANNEL 0x0A -#define CDC_FUNC_DESC_PROTOCOL_UNIT 0x0B -#define CDC_FUNC_DESC_EXTENSION_UNIT 0x0C -#define CDC_FUNC_DESC_MULTI_CHANNEL_MANAGEMENT 0x0D -#define CDC_FUNC_DESC_CAPI_CONTROL_MANAGEMENT 0x0E -#define CDC_FUNC_DESC_ETHERNET_NETWORKING 0x0F -#define CDC_FUNC_DESC_ATM_NETWORKING 0x10 -#define CDC_FUNC_DESC_WIRELESS_HANDSET_CONTROL_MODEL 0x11 -#define CDC_FUNC_DESC_MOBILE_DIRECT_LINE_MODEL 0x12 -#define CDC_FUNC_DESC_MOBILE_DIRECT_LINE_MODEL_DETAIL 0x13 -#define CDC_FUNC_DESC_DEVICE_MANAGEMENT_MODEL 0x14 -#define CDC_FUNC_DESC_OBEX 0x15 -#define CDC_FUNC_DESC_COMMAND_SET 0x16 -#define CDC_FUNC_DESC_COMMAND_SET_DETAIL 0x17 -#define CDC_FUNC_DESC_TELEPHONE_CONTROL_MODEL 0x18 -#define CDC_FUNC_DESC_OBEX_SERVICE_IDENTIFIER 0x19 - -/* CDC class-specific request codes */ -/* (usbcdc11.pdf, 6.2, Table 46) */ -/* see Table 45 for info about the specific requests. */ -#define CDC_REQUEST_SEND_ENCAPSULATED_COMMAND 0x00 -#define CDC_REQUEST_GET_ENCAPSULATED_RESPONSE 0x01 -#define CDC_REQUEST_SET_COMM_FEATURE 0x02 -#define CDC_REQUEST_GET_COMM_FEATURE 0x03 -#define CDC_REQUEST_CLEAR_COMM_FEATURE 0x04 -#define CDC_REQUEST_SET_AUX_LINE_STATE 0x10 -#define CDC_REQUEST_SET_HOOK_STATE 0x11 -#define CDC_REQUEST_PULSE_SETUP 0x12 -#define CDC_REQUEST_SEND_PULSE 0x13 -#define CDC_REQUEST_SET_PULSE_TIME 0x14 -#define CDC_REQUEST_RING_AUX_JACK 0x15 -#define CDC_REQUEST_SET_LINE_CODING 0x20 -#define CDC_REQUEST_GET_LINE_CODING 0x21 -#define CDC_REQUEST_SET_CONTROL_LINE_STATE 0x22 -#define CDC_REQUEST_SEND_BREAK 0x23 -#define CDC_REQUEST_SET_RINGER_PARMS 0x30 -#define CDC_REQUEST_GET_RINGER_PARMS 0x31 -#define CDC_REQUEST_SET_OPERATION_PARMS 0x32 -#define CDC_REQUEST_GET_OPERATION_PARMS 0x33 -#define CDC_REQUEST_SET_LINE_PARMS 0x34 -#define CDC_REQUEST_GET_LINE_PARMS 0x35 -#define CDC_REQUEST_DIAL_DIGITS 0x36 -#define CDC_REQUEST_SET_UNIT_PARAMETER 0x37 -#define CDC_REQUEST_GET_UNIT_PARAMETER 0x38 -#define CDC_REQUEST_CLEAR_UNIT_PARAMETER 0x39 -#define CDC_REQUEST_GET_PROFILE 0x3A -#define CDC_REQUEST_SET_ETHERNET_MULTICAST_FILTERS 0x40 -#define CDC_REQUEST_SET_ETHERNET_PMP_FILTER 0x41 -#define CDC_REQUEST_GET_ETHERNET_PMP_FILTER 0x42 -#define CDC_REQUEST_SET_ETHERNET_PACKET_FILTER 0x43 -#define CDC_REQUEST_GET_ETHERNET_STATISTIC 0x44 -#define CDC_REQUEST_SET_ATM_DATA_FORMAT 0x50 -#define CDC_REQUEST_GET_ATM_DEVICE_STATISTICS 0x51 -#define CDC_REQUEST_SET_ATM_DEFAULT_VC 0x52 -#define CDC_REQUEST_GET_ATM_VC_STATISTICS 0x53 - -/* Communication feature selector codes */ -/* (usbcdc11.pdf, 6.2.2..6.2.4, Table 47) */ -#define CDC_ABSTRACT_STATE 0x01 -#define CDC_COUNTRY_SETTING 0x02 - -/** Control Signal Bitmap Values for SetControlLineState */ -#define SET_CONTROL_LINE_STATE_RTS 0x02 -#define SET_CONTROL_LINE_STATE_DTR 0x01 - -/* Feature Status returned for ABSTRACT_STATE Selector */ -/* (usbcdc11.pdf, 6.2.3, Table 48) */ -#define CDC_IDLE_SETTING (1 << 0) -#define CDC_DATA_MULTPLEXED_STATE (1 << 1) - -/* Control signal bitmap values for the SetControlLineState request */ -/* (usbcdc11.pdf, 6.2.14, Table 51) */ -#define CDC_DTE_PRESENT (1 << 0) -#define CDC_ACTIVATE_CARRIER (1 << 1) - -/* CDC class-specific notification codes */ -/* (usbcdc11.pdf, 6.3, Table 68) */ -/* see Table 67 for Info about class-specific notifications */ -#define CDC_NOTIFICATION_NETWORK_CONNECTION 0x00 -#define CDC_RESPONSE_AVAILABLE 0x01 -#define CDC_AUX_JACK_HOOK_STATE 0x08 -#define CDC_RING_DETECT 0x09 -#define CDC_NOTIFICATION_SERIAL_STATE 0x20 -#define CDC_CALL_STATE_CHANGE 0x28 -#define CDC_LINE_STATE_CHANGE 0x29 -#define CDC_CONNECTION_SPEED_CHANGE 0x2A - -/* UART state bitmap values (Serial state notification). */ -/* (usbcdc11.pdf, 6.3.5, Table 69) */ -#define CDC_SERIAL_STATE_OVERRUN (1 << 6) /* receive data overrun error has occurred */ -#define CDC_SERIAL_STATE_OVERRUN_Pos (6) -#define CDC_SERIAL_STATE_OVERRUN_Msk (1 << CDC_SERIAL_STATE_OVERRUN_Pos) -#define CDC_SERIAL_STATE_PARITY (1 << 5) /* parity error has occurred */ -#define CDC_SERIAL_STATE_PARITY_Pos (5) -#define CDC_SERIAL_STATE_PARITY_Msk (1 << CDC_SERIAL_STATE_PARITY_Pos) -#define CDC_SERIAL_STATE_FRAMING (1 << 4) /* framing error has occurred */ -#define CDC_SERIAL_STATE_FRAMING_Pos (4) -#define CDC_SERIAL_STATE_FRAMING_Msk (1 << CDC_SERIAL_STATE_FRAMING_Pos) -#define CDC_SERIAL_STATE_RING (1 << 3) /* state of ring signal detection */ -#define CDC_SERIAL_STATE_RING_Pos (3) -#define CDC_SERIAL_STATE_RING_Msk (1 << CDC_SERIAL_STATE_RING_Pos) -#define CDC_SERIAL_STATE_BREAK (1 << 2) /* state of break detection */ -#define CDC_SERIAL_STATE_BREAK_Pos (2) -#define CDC_SERIAL_STATE_BREAK_Msk (1 << CDC_SERIAL_STATE_BREAK_Pos) -#define CDC_SERIAL_STATE_TX_CARRIER (1 << 1) /* state of transmission carrier */ -#define CDC_SERIAL_STATE_TX_CARRIER_Pos (1) -#define CDC_SERIAL_STATE_TX_CARRIER_Msk (1 << CDC_SERIAL_STATE_TX_CARRIER_Pos) -#define CDC_SERIAL_STATE_RX_CARRIER (1 << 0) /* state of receiver carrier */ -#define CDC_SERIAL_STATE_RX_CARRIER_Pos (0) -#define CDC_SERIAL_STATE_RX_CARRIER_Msk (1 << CDC_SERIAL_STATE_RX_CARRIER_Pos) - -/*------------------------------------------------------------------------------ - * Structures based on usbcdc11.pdf (www.usb.org) - *----------------------------------------------------------------------------*/ - -/* Header functional descriptor */ -/* (usbcdc11.pdf, 5.2.3.1) */ -/* This header must precede any list of class-specific descriptors. */ -struct cdc_header_descriptor { - uint8_t bFunctionLength; /* size of this descriptor in bytes */ - uint8_t bDescriptorType; /* CS_INTERFACE descriptor type */ - uint8_t bDescriptorSubtype; /* Header functional descriptor subtype */ - uint16_t bcdCDC; /* USB CDC specification release version */ -} __packed; - -/* Call management functional descriptor */ -/* (usbcdc11.pdf, 5.2.3.2) */ -/* Describes the processing of calls for the communication class interface. */ -struct cdc_call_management_descriptor { - uint8_t bFunctionLength; /* size of this descriptor in bytes */ - uint8_t bDescriptorType; /* CS_INTERFACE descriptor type */ - uint8_t bDescriptorSubtype; /* call management functional descriptor subtype */ - uint8_t bmCapabilities; /* capabilities that this configuration supports */ - uint8_t bDataInterface; /* interface number of the data class interface used for call management (optional) */ -} __packed; - -/* Abstract control management functional descriptor */ -/* (usbcdc11.pdf, 5.2.3.3) */ -/* Describes the command supported by the communication interface class with the Abstract Control Model subclass code. */ -struct cdc_abstract_control_management_descriptor { - uint8_t bFunctionLength; /* size of this descriptor in bytes */ - uint8_t bDescriptorType; /* CS_INTERFACE descriptor type */ - uint8_t bDescriptorSubtype; /* abstract control management functional descriptor subtype */ - uint8_t bmCapabilities; /* capabilities supported by this configuration */ -} __packed; - -/* Union functional descriptors */ -/* (usbcdc11.pdf, 5.2.3.8) */ -/* Describes the relationship between a group of interfaces that can be considered to form a functional unit. */ -struct cdc_union_descriptor { - uint8_t bFunctionLength; /* size of this descriptor in bytes */ - uint8_t bDescriptorType; /* CS_INTERFACE descriptor type */ - uint8_t bDescriptorSubtype; /* union functional descriptor subtype */ - uint8_t bMasterInterface; /* interface number designated as master */ -} __packed; - -/* Union functional descriptors with one slave interface */ -/* (usbcdc11.pdf, 5.2.3.8) */ -struct cdc_union_1slave_descriptor { - uint8_t bFunctionLength; - uint8_t bDescriptorType; - uint8_t bDescriptorSubtype; - uint8_t bControlInterface; - uint8_t bSubordinateInterface0; -} __packed; - -/* Line coding structure for GET_LINE_CODING / SET_LINE_CODING class requests*/ -/* Format of the data returned when a GetLineCoding request is received */ -/* (usbcdc11.pdf, 6.2.13) */ -struct cdc_line_coding { - uint32_t dwDTERate; /* Data terminal rate in bits per second */ - uint8_t bCharFormat; /* Number of stop bits */ - uint8_t bParityType; /* Parity bit type */ - uint8_t bDataBits; /* Number of data bits */ -} __packed; - -/** Data structure for the notification about SerialState */ -struct cdc_acm_notification { - uint8_t bmRequestType; - uint8_t bNotificationType; - uint16_t wValue; - uint16_t wIndex; - uint16_t wLength; - uint16_t data; -} __packed; - -/** Ethernet Networking Functional Descriptor */ -struct cdc_ecm_descriptor { - uint8_t bFunctionLength; - uint8_t bDescriptorType; - uint8_t bDescriptorSubtype; - uint8_t iMACAddress; - uint32_t bmEthernetStatistics; - uint16_t wMaxSegmentSize; - uint16_t wNumberMCFilters; - uint8_t bNumberPowerFilters; -} __packed; - -/*Length of template descriptor: 66 bytes*/ -#define CDC_ACM_DESCRIPTOR_LEN (8 + 9 + 5 + 5 + 4 + 5 + 7 + 9 + 7 + 7) -// clang-format off -#ifndef CONFIG_USB_HS -#define CDC_ACM_DESCRIPTOR_INIT(bFirstInterface, int_ep, out_ep, in_ep, str_idx) \ - /* Interface Associate */ \ - 0x08, /* bLength */ \ - USB_DESCRIPTOR_TYPE_INTERFACE_ASSOCIATION, /* bDescriptorType */ \ - bFirstInterface, /* bFirstInterface */ \ - 0x02, /* bInterfaceCount */ \ - USB_DEVICE_CLASS_CDC, /* bFunctionClass */ \ - CDC_ABSTRACT_CONTROL_MODEL, /* bFunctionSubClass */ \ - CDC_COMMON_PROTOCOL_AT_COMMANDS, /* bFunctionProtocol */ \ - 0x00, /* iFunction */ \ - 0x09, /* bLength */ \ - USB_DESCRIPTOR_TYPE_INTERFACE, /* bDescriptorType */ \ - bFirstInterface, /* bInterfaceNumber */ \ - 0x00, /* bAlternateSetting */ \ - 0x01, /* bNumEndpoints */ \ - USB_DEVICE_CLASS_CDC, /* bInterfaceClass */ \ - CDC_ABSTRACT_CONTROL_MODEL, /* bInterfaceSubClass */ \ - CDC_COMMON_PROTOCOL_AT_COMMANDS, /* bInterfaceProtocol */ \ - str_idx, /* iInterface */ \ - 0x05, /* bLength */ \ - CDC_CS_INTERFACE, /* bDescriptorType */ \ - CDC_FUNC_DESC_HEADER, /* bDescriptorSubtype */ \ - WBVAL(CDC_V1_10), /* bcdCDC */ \ - 0x05, /* bLength */ \ - CDC_CS_INTERFACE, /* bDescriptorType */ \ - CDC_FUNC_DESC_CALL_MANAGEMENT, /* bDescriptorSubtype */ \ - bFirstInterface, /* bmCapabilities */ \ - (uint8_t)(bFirstInterface + 1), /* bDataInterface */ \ - 0x04, /* bLength */ \ - CDC_CS_INTERFACE, /* bDescriptorType */ \ - CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT, /* bDescriptorSubtype */ \ - 0x02, /* bmCapabilities */ \ - 0x05, /* bLength */ \ - CDC_CS_INTERFACE, /* bDescriptorType */ \ - CDC_FUNC_DESC_UNION, /* bDescriptorSubtype */ \ - bFirstInterface, /* bMasterInterface */ \ - (uint8_t)(bFirstInterface + 1), /* bSlaveInterface0 */ \ - 0x07, /* bLength */ \ - USB_DESCRIPTOR_TYPE_ENDPOINT, /* bDescriptorType */ \ - int_ep, /* bEndpointAddress */ \ - 0x03, /* bmAttributes */ \ - 0x40, 0x00, /* wMaxPacketSize */ \ - 0x00, /* bInterval */ \ - 0x09, /* bLength */ \ - USB_DESCRIPTOR_TYPE_INTERFACE, /* bDescriptorType */ \ - (uint8_t)(bFirstInterface + 1), /* bInterfaceNumber */ \ - 0x00, /* bAlternateSetting */ \ - 0x02, /* bNumEndpoints */ \ - CDC_DATA_INTERFACE_CLASS, /* bInterfaceClass */ \ - 0x00, /* bInterfaceSubClass */ \ - 0x00, /* bInterfaceProtocol */ \ - 0x00, /* iInterface */ \ - 0x07, /* bLength */ \ - USB_DESCRIPTOR_TYPE_ENDPOINT, /* bDescriptorType */ \ - out_ep, /* bEndpointAddress */ \ - 0x02, /* bmAttributes */ \ - 0x40, 0x00, /* wMaxPacketSize */ \ - 0x00, /* bInterval */ \ - 0x07, /* bLength */ \ - USB_DESCRIPTOR_TYPE_ENDPOINT, /* bDescriptorType */ \ - in_ep, /* bEndpointAddress */ \ - 0x02, /* bmAttributes */ \ - 0x40, 0x00, /* wMaxPacketSize */ \ - 0x00 /* bInterval */ -#else -#define CDC_ACM_DESCRIPTOR_INIT(bFirstInterface, int_ep, out_ep, in_ep, str_idx) \ - /* Interface Associate */ \ - 0x08, /* bLength */ \ - USB_DESCRIPTOR_TYPE_INTERFACE_ASSOCIATION, /* bDescriptorType */ \ - bFirstInterface, /* bFirstInterface */ \ - 0x02, /* bInterfaceCount */ \ - USB_DEVICE_CLASS_CDC, /* bFunctionClass */ \ - CDC_ABSTRACT_CONTROL_MODEL, /* bFunctionSubClass */ \ - CDC_COMMON_PROTOCOL_AT_COMMANDS, /* bFunctionProtocol */ \ - 0x00, /* iFunction */ \ - 0x09, /* bLength */ \ - USB_DESCRIPTOR_TYPE_INTERFACE, /* bDescriptorType */ \ - bFirstInterface, /* bInterfaceNumber */ \ - 0x00, /* bAlternateSetting */ \ - 0x01, /* bNumEndpoints */ \ - USB_DEVICE_CLASS_CDC, /* bInterfaceClass */ \ - CDC_ABSTRACT_CONTROL_MODEL, /* bInterfaceSubClass */ \ - CDC_COMMON_PROTOCOL_AT_COMMANDS, /* bInterfaceProtocol */ \ - str_idx, /* iInterface */ \ - 0x05, /* bLength */ \ - CDC_CS_INTERFACE, /* bDescriptorType */ \ - CDC_FUNC_DESC_HEADER, /* bDescriptorSubtype */ \ - WBVAL(CDC_V1_10), /* bcdCDC */ \ - 0x05, /* bLength */ \ - CDC_CS_INTERFACE, /* bDescriptorType */ \ - CDC_FUNC_DESC_CALL_MANAGEMENT, /* bDescriptorSubtype */ \ - bFirstInterface, /* bmCapabilities */ \ - (uint8_t)(bFirstInterface + 1), /* bDataInterface */ \ - 0x04, /* bLength */ \ - CDC_CS_INTERFACE, /* bDescriptorType */ \ - CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT, /* bDescriptorSubtype */ \ - 0x02, /* bmCapabilities */ \ - 0x05, /* bLength */ \ - CDC_CS_INTERFACE, /* bDescriptorType */ \ - CDC_FUNC_DESC_UNION, /* bDescriptorSubtype */ \ - bFirstInterface, /* bMasterInterface */ \ - (uint8_t)(bFirstInterface + 1), /* bSlaveInterface0 */ \ - 0x07, /* bLength */ \ - USB_DESCRIPTOR_TYPE_ENDPOINT, /* bDescriptorType */ \ - int_ep, /* bEndpointAddress */ \ - 0x03, /* bmAttributes */ \ - 0x00, 0x02, /* wMaxPacketSize */ \ - 0x00, /* bInterval */ \ - 0x09, /* bLength */ \ - USB_DESCRIPTOR_TYPE_INTERFACE, /* bDescriptorType */ \ - (uint8_t)(bFirstInterface + 1), /* bInterfaceNumber */ \ - 0x00, /* bAlternateSetting */ \ - 0x02, /* bNumEndpoints */ \ - CDC_DATA_INTERFACE_CLASS, /* bInterfaceClass */ \ - 0x00, /* bInterfaceSubClass */ \ - 0x00, /* bInterfaceProtocol */ \ - 0x00, /* iInterface */ \ - 0x07, /* bLength */ \ - USB_DESCRIPTOR_TYPE_ENDPOINT, /* bDescriptorType */ \ - out_ep, /* bEndpointAddress */ \ - 0x02, /* bmAttributes */ \ - 0x00, 0x02, /* wMaxPacketSize */ \ - 0x00, /* bInterval */ \ - 0x07, /* bLength */ \ - USB_DESCRIPTOR_TYPE_ENDPOINT, /* bDescriptorType */ \ - in_ep, /* bEndpointAddress */ \ - 0x02, /* bmAttributes */ \ - 0x00, 0x02, /* wMaxPacketSize */ \ - 0x00 /* bInterval */ -#endif -// clang-format on - -void usbd_cdc_add_acm_interface(usbd_class_t *class, usbd_interface_t *intf); - -void usbd_cdc_acm_set_line_coding(uint32_t baudrate, uint8_t databits, uint8_t parity, uint8_t stopbits); -void usbd_cdc_acm_set_dtr(bool dtr); -void usbd_cdc_acm_set_rts(bool rts); - -#ifdef __cplusplus -} -#endif - -#endif /* USB_CDC_H_ */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.c deleted file mode 100644 index 6ee9e3c891..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.c +++ /dev/null @@ -1,271 +0,0 @@ -/** - * @file usbd_hid.c - * @brief - * - * Copyright (c) 2021 Bouffalolab team - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - */ -#include "usbd_hid.h" -#include "usbd_core.h" - -#define HID_STATE_IDLE 0 -#define HID_STATE_BUSY 1 - -struct usbd_hid_cfg_private { - const uint8_t *hid_descriptor; - const uint8_t *hid_report_descriptor; - uint32_t hid_report_descriptor_len; - uint8_t current_intf_num; - uint8_t hid_state; - uint8_t report; - uint8_t idle_state; - uint8_t protocol; - - uint8_t (*get_report_callback)(uint8_t report_id, uint8_t report_type); - void (*set_report_callback)(uint8_t report_id, uint8_t report_type, uint8_t *report, uint8_t report_len); - uint8_t (*get_idle_callback)(uint8_t report_id); - void (*set_idle_callback)(uint8_t report_id, uint8_t duration); - void (*set_protocol_callback)(uint8_t protocol); - uint8_t (*get_protocol_callback)(void); - - usb_slist_t list; -} usbd_hid_cfg[4]; - -static usb_slist_t usbd_hid_class_head = USB_SLIST_OBJECT_INIT(usbd_hid_class_head); - -static void usbd_hid_reset(void) { - usb_slist_t *i; - usb_slist_for_each(i, &usbd_hid_class_head) { - struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list); - hid_intf->hid_state = HID_STATE_IDLE; - hid_intf->report = 0; - hid_intf->idle_state = 0; - hid_intf->protocol = 0; - } -} - -int hid_custom_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) { - USBD_LOG_DBG("HID Custom request: " - "bRequest 0x%02x\r\n", - setup->bRequest); - - if (REQTYPE_GET_DIR(setup->bmRequestType) == USB_REQUEST_DEVICE_TO_HOST && setup->bRequest == USB_REQUEST_GET_DESCRIPTOR) { - uint8_t value = (uint8_t)(setup->wValue >> 8); - uint8_t intf_num = (uint8_t)setup->wIndex; - - struct usbd_hid_cfg_private *current_hid_intf = NULL; - usb_slist_t *i; - usb_slist_for_each(i, &usbd_hid_class_head) { - struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list); - - if (hid_intf->current_intf_num == intf_num) { - current_hid_intf = hid_intf; - break; - } - } - - if (current_hid_intf == NULL) { - return -2; - } - - switch (value) { - case HID_DESCRIPTOR_TYPE_HID: - USBD_LOG_INFO("get HID Descriptor\r\n"); - *data = (uint8_t *)current_hid_intf->hid_descriptor; - *len = current_hid_intf->hid_descriptor[0]; - break; - - case HID_DESCRIPTOR_TYPE_HID_REPORT: - USBD_LOG_INFO("get Report Descriptor\r\n"); - *data = (uint8_t *)current_hid_intf->hid_report_descriptor; - *len = current_hid_intf->hid_report_descriptor_len; - break; - - case HID_DESCRIPTOR_TYPE_HID_PHYSICAL: - USBD_LOG_INFO("get PHYSICAL Descriptor\r\n"); - - break; - - default: - return -2; - } - - return 0; - } - - return -1; -} - -int hid_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) { - USBD_LOG_DBG("HID Class request: " - "bRequest 0x%02x\r\n", - setup->bRequest); - - struct usbd_hid_cfg_private *current_hid_intf = NULL; - usb_slist_t *i; - usb_slist_for_each(i, &usbd_hid_class_head) { - struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list); - uint8_t intf_num = (uint8_t)setup->wIndex; - if (hid_intf->current_intf_num == intf_num) { - current_hid_intf = hid_intf; - break; - } - } - - if (current_hid_intf == NULL) { - return -2; - } - - switch (setup->bRequest) { - case HID_REQUEST_GET_REPORT: - if (current_hid_intf->get_report_callback) - current_hid_intf->report = current_hid_intf->get_report_callback(setup->wValueL, setup->wValueH); /*report id ,report type*/ - - *data = (uint8_t *)¤t_hid_intf->report; - *len = 1; - break; - case HID_REQUEST_GET_IDLE: - if (current_hid_intf->get_idle_callback) - current_hid_intf->idle_state = current_hid_intf->get_idle_callback(setup->wValueL); - - *data = (uint8_t *)¤t_hid_intf->idle_state; - *len = 1; - break; - case HID_REQUEST_GET_PROTOCOL: - if (current_hid_intf->get_protocol_callback) - current_hid_intf->protocol = current_hid_intf->get_protocol_callback(); - - *data = (uint8_t *)¤t_hid_intf->protocol; - *len = 1; - break; - case HID_REQUEST_SET_REPORT: - if (current_hid_intf->set_report_callback) - current_hid_intf->set_report_callback(setup->wValueL, setup->wValueH, *data, *len); /*report id ,report type,report,report len*/ - - current_hid_intf->report = **data; - break; - case HID_REQUEST_SET_IDLE: - if (current_hid_intf->set_idle_callback) - current_hid_intf->set_idle_callback(setup->wValueL, setup->wIndexH); /*report id ,duration*/ - - current_hid_intf->idle_state = setup->wIndexH; - break; - case HID_REQUEST_SET_PROTOCOL: - if (current_hid_intf->set_protocol_callback) - current_hid_intf->set_protocol_callback(setup->wValueL); /*protocol*/ - - current_hid_intf->protocol = setup->wValueL; - break; - - default: - USBD_LOG_WRN("Unhandled HID Class bRequest 0x%02x\r\n", setup->bRequest); - return -1; - } - - return 0; -} - -static void hid_notify_handler(uint8_t event, void *arg) { - switch (event) { - case USB_EVENT_RESET: - usbd_hid_reset(); - break; - - default: - break; - } -} - -void usbd_hid_reset_state(void) { - // usbd_hid_cfg.hid_state = HID_STATE_IDLE; -} - -void usbd_hid_send_report(uint8_t ep, uint8_t *data, uint8_t len) { - // if(usbd_hid_cfg.hid_state == HID_STATE_IDLE) - // { - // usbd_hid_cfg.hid_state = HID_STATE_BUSY; - // usbd_ep_write(ep, data, len, NULL); - // } -} - -void usbd_hid_descriptor_register(uint8_t intf_num, const uint8_t *desc) { - // usbd_hid_cfg.hid_descriptor = desc; -} - -void usbd_hid_report_descriptor_register(uint8_t intf_num, const uint8_t *desc, uint32_t desc_len) { - usb_slist_t *i; - usb_slist_for_each(i, &usbd_hid_class_head) { - struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list); - - if (hid_intf->current_intf_num == intf_num) { - hid_intf->hid_report_descriptor = desc; - hid_intf->hid_report_descriptor_len = desc_len; - return; - } - } -} -// clang-format off -void usbd_hid_set_request_callback( uint8_t intf_num, - uint8_t (*get_report_callback)(uint8_t report_id, uint8_t report_type), - void (*set_report_callback)(uint8_t report_id, uint8_t report_type, uint8_t *report, uint8_t report_len), - uint8_t (*get_idle_callback)(uint8_t report_id), - void (*set_idle_callback)(uint8_t report_id, uint8_t duration), - void (*set_protocol_callback)(uint8_t protocol), - uint8_t (*get_protocol_callback)(void)) -// clang-format on -{ - usb_slist_t *i; - usb_slist_for_each(i, &usbd_hid_class_head) { - struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list); - - if (hid_intf->current_intf_num == intf_num) { - if (get_report_callback) - hid_intf->get_report_callback = get_report_callback; - if (set_report_callback) - hid_intf->set_report_callback = set_report_callback; - if (get_idle_callback) - hid_intf->get_idle_callback = get_idle_callback; - if (set_idle_callback) - hid_intf->set_idle_callback = set_idle_callback; - if (set_protocol_callback) - hid_intf->set_protocol_callback = set_protocol_callback; - if (get_protocol_callback) - hid_intf->get_protocol_callback = get_protocol_callback; - return; - } - } -} - -void usbd_hid_add_interface(usbd_class_t *class, usbd_interface_t *intf) { - static usbd_class_t *last_class = NULL; - static uint8_t hid_num = 0; - if (last_class != class) { - last_class = class; - usbd_class_register(class); - } - - intf->class_handler = hid_class_request_handler; - intf->custom_handler = hid_custom_request_handler; - intf->vendor_handler = NULL; - intf->notify_handler = hid_notify_handler; - usbd_class_add_interface(class, intf); - - usbd_hid_cfg[hid_num].current_intf_num = intf->intf_num; - usb_slist_add_tail(&usbd_hid_class_head, &usbd_hid_cfg[hid_num].list); - hid_num++; -} diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.h deleted file mode 100644 index 9319e7f2c0..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.h +++ /dev/null @@ -1,360 +0,0 @@ -/** - * @file - * @brief USB Human Interface Device (HID) Class public header - * - * Header follows Device Class Definition for Human Interface Devices (HID) - * Version 1.11 document (HID1_11-1.pdf). - */ -#ifndef _USBD_HID_H_ -#define _USBD_HID_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -/* HID Protocol Codes */ -#define HID_PROTOCOL_NONE 0x00 -#define HID_PROTOCOL_BOOT 0x00 -#define HID_PROTOCOL_KEYBOARD 0x01 -#define HID_PROTOCOL_REPORT 0x01 -#define HID_PROTOCOL_MOUSE 0x02 - -/* HID Class Descriptor Types */ -#define HID_DESCRIPTOR_TYPE_HID 0x21 -#define HID_DESCRIPTOR_TYPE_HID_REPORT 0x22 -#define HID_DESCRIPTOR_TYPE_HID_PHYSICAL 0x23 - -/* HID Class Specific Requests */ -#define HID_REQUEST_GET_REPORT 0x01 -#define HID_REQUEST_GET_IDLE 0x02 -#define HID_REQUEST_GET_PROTOCOL 0x03 -#define HID_REQUEST_SET_REPORT 0x09 -#define HID_REQUEST_SET_IDLE 0x0A -#define HID_REQUEST_SET_PROTOCOL 0x0B - -/* HID Report Types */ -#define HID_REPORT_INPUT 0x01 -#define HID_REPORT_OUTPUT 0x02 -#define HID_REPORT_FEATURE 0x03 - -/* HID Report Definitions */ -struct usb_hid_class_subdescriptor { - uint8_t bDescriptorType; - uint16_t wDescriptorLength; -} __packed; - -struct usb_hid_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint16_t bcdHID; - uint8_t bCountryCode; - uint8_t bNumDescriptors; - - /* - * Specification says at least one Class Descriptor needs to - * be present (Report Descriptor). - */ - struct usb_hid_class_subdescriptor subdesc[1]; -} __packed; - -/* HID Items types */ -#define ITEM_MAIN 0x0 -#define ITEM_GLOBAL 0x1 -#define ITEM_LOCAL 0x2 - -/* HID Main Items tags */ -#define ITEM_TAG_INPUT 0x8 -#define ITEM_TAG_OUTPUT 0x9 -#define ITEM_TAG_COLLECTION 0xA -#define ITEM_TAG_COLLECTION_END 0xC - -/* HID Global Items tags */ -#define ITEM_TAG_USAGE_PAGE 0x0 -#define ITEM_TAG_LOGICAL_MIN 0x1 -#define ITEM_TAG_LOGICAL_MAX 0x2 -#define ITEM_TAG_REPORT_SIZE 0x7 -#define ITEM_TAG_REPORT_ID 0x8 -#define ITEM_TAG_REPORT_COUNT 0x9 - -/* HID Local Items tags */ -#define ITEM_TAG_USAGE 0x0 -#define ITEM_TAG_USAGE_MIN 0x1 -#define ITEM_TAG_USAGE_MAX 0x2 - -#define HID_ITEM(bTag, bType, bSize) (((bTag & 0xF) << 4) | \ - ((bType & 0x3) << 2) | (bSize & 0x3)) - -#define HID_MAIN_ITEM(bTag, bSize) HID_ITEM(bTag, ITEM_MAIN, bSize) -#define HID_GLOBAL_ITEM(bTag, bSize) HID_ITEM(bTag, ITEM_GLOBAL, bSize) -#define HID_LOCAL_ITEM(bTag, bSize) HID_ITEM(bTag, ITEM_LOCAL, bSize) - -#define HID_MI_COLLECTION HID_MAIN_ITEM(ITEM_TAG_COLLECTION, 1) -#define HID_MI_COLLECTION_END HID_MAIN_ITEM(ITEM_TAG_COLLECTION_END, \ - 0) -#define HID_MI_INPUT HID_MAIN_ITEM(ITEM_TAG_INPUT, 1) -#define HID_MI_OUTPUT HID_MAIN_ITEM(ITEM_TAG_OUTPUT, 1) - -#define HID_GI_USAGE_PAGE HID_GLOBAL_ITEM(ITEM_TAG_USAGE_PAGE, 1) -#define HID_GI_LOGICAL_MIN(size) HID_GLOBAL_ITEM(ITEM_TAG_LOGICAL_MIN, \ - size) -#define HID_GI_LOGICAL_MAX(size) HID_GLOBAL_ITEM(ITEM_TAG_LOGICAL_MAX, \ - size) -#define HID_GI_REPORT_SIZE HID_GLOBAL_ITEM(ITEM_TAG_REPORT_SIZE, \ - 1) -#define HID_GI_REPORT_ID HID_GLOBAL_ITEM(ITEM_TAG_REPORT_ID, \ - 1) -#define HID_GI_REPORT_COUNT HID_GLOBAL_ITEM(ITEM_TAG_REPORT_COUNT, \ - 1) - -#define HID_LI_USAGE HID_LOCAL_ITEM(ITEM_TAG_USAGE, 1) -#define HID_LI_USAGE_MIN(size) HID_LOCAL_ITEM(ITEM_TAG_USAGE_MIN, \ - size) -#define HID_LI_USAGE_MAX(size) HID_LOCAL_ITEM(ITEM_TAG_USAGE_MAX, \ - size) - -/* Defined in Universal Serial Bus HID Usage Tables version 1.11 */ -#define USAGE_GEN_DESKTOP 0x01 -#define USAGE_GEN_KEYBOARD 0x07 -#define USAGE_GEN_LEDS 0x08 -#define USAGE_GEN_BUTTON 0x09 - -/* Generic Desktop Page usages */ -#define USAGE_GEN_DESKTOP_UNDEFINED 0x00 -#define USAGE_GEN_DESKTOP_POINTER 0x01 -#define USAGE_GEN_DESKTOP_MOUSE 0x02 -#define USAGE_GEN_DESKTOP_JOYSTICK 0x04 -#define USAGE_GEN_DESKTOP_GAMEPAD 0x05 -#define USAGE_GEN_DESKTOP_KEYBOARD 0x06 -#define USAGE_GEN_DESKTOP_KEYPAD 0x07 -#define USAGE_GEN_DESKTOP_X 0x30 -#define USAGE_GEN_DESKTOP_Y 0x31 -#define USAGE_GEN_DESKTOP_WHEEL 0x38 - -/* Collection types */ -#define COLLECTION_PHYSICAL 0x00 -#define COLLECTION_APPLICATION 0x01 - -/* Example HID report descriptors */ -/** - * @brief Simple HID mouse report descriptor for n button mouse. - * - * @param bcnt Button count. Allowed values from 1 to 8. - */ -#define HID_MOUSE_REPORT_DESC(bcnt) \ - { \ - /* USAGE_PAGE (Generic Desktop) */ \ - HID_GI_USAGE_PAGE, USAGE_GEN_DESKTOP, /* USAGE (Mouse) */ \ - HID_LI_USAGE, USAGE_GEN_DESKTOP_MOUSE, /* COLLECTION (Application) */ \ - HID_MI_COLLECTION, COLLECTION_APPLICATION, /* USAGE (Pointer) */ \ - HID_LI_USAGE, USAGE_GEN_DESKTOP_POINTER, /* COLLECTION (Physical) */ \ - HID_MI_COLLECTION, COLLECTION_PHYSICAL, /* Bits used for button signalling */ /* USAGE_PAGE (Button) */ \ - HID_GI_USAGE_PAGE, USAGE_GEN_BUTTON, /* USAGE_MINIMUM (Button 1) */ \ - HID_LI_USAGE_MIN(1), 0x01, /* USAGE_MAXIMUM (Button bcnt) */ \ - HID_LI_USAGE_MAX(1), bcnt, /* LOGICAL_MINIMUM (0) */ \ - HID_GI_LOGICAL_MIN(1), 0x00, /* LOGICAL_MAXIMUM (1) */ \ - HID_GI_LOGICAL_MAX(1), 0x01, /* REPORT_SIZE (1) */ \ - HID_GI_REPORT_SIZE, 0x01, /* REPORT_COUNT (bcnt) */ \ - HID_GI_REPORT_COUNT, bcnt, /* INPUT (Data,Var,Abs) */ \ - HID_MI_INPUT, 0x02, /* Unused bits */ /* REPORT_SIZE (8 - bcnt) */ \ - HID_GI_REPORT_SIZE, (8 - bcnt), /* REPORT_COUNT (1) */ \ - HID_GI_REPORT_COUNT, 0x01, /* INPUT (Cnst,Ary,Abs) */ \ - HID_MI_INPUT, 0x01, /* X and Y axis, scroll */ /* USAGE_PAGE (Generic Desktop) */ \ - HID_GI_USAGE_PAGE, USAGE_GEN_DESKTOP, /* USAGE (X) */ \ - HID_LI_USAGE, USAGE_GEN_DESKTOP_X, /* USAGE (Y) */ \ - HID_LI_USAGE, USAGE_GEN_DESKTOP_Y, /* USAGE (WHEEL) */ \ - HID_LI_USAGE, USAGE_GEN_DESKTOP_WHEEL, /* LOGICAL_MINIMUM (-127) */ \ - HID_GI_LOGICAL_MIN(1), -127, /* LOGICAL_MAXIMUM (127) */ \ - HID_GI_LOGICAL_MAX(1), 127, /* REPORT_SIZE (8) */ \ - HID_GI_REPORT_SIZE, 0x08, /* REPORT_COUNT (3) */ \ - HID_GI_REPORT_COUNT, 0x03, /* INPUT (Data,Var,Rel) */ \ - HID_MI_INPUT, 0x06, /* END_COLLECTION */ \ - HID_MI_COLLECTION_END, /* END_COLLECTION */ \ - HID_MI_COLLECTION_END, \ - } - -/** - * @brief Simple HID keyboard report descriptor. - */ -#define HID_KEYBOARD_REPORT_DESC() \ - { \ - /* USAGE_PAGE (Generic Desktop) */ \ - HID_GI_USAGE_PAGE, USAGE_GEN_DESKTOP, /* USAGE (Keyboard) */ \ - HID_LI_USAGE, USAGE_GEN_DESKTOP_KEYBOARD, /* COLLECTION (Application) */ \ - HID_MI_COLLECTION, COLLECTION_APPLICATION, /* USAGE_PAGE (Keypad) */ \ - HID_GI_USAGE_PAGE, USAGE_GEN_DESKTOP_KEYPAD, /* USAGE_MINIMUM (Keyboard LeftControl) */ \ - HID_LI_USAGE_MIN(1), 0xE0, /* USAGE_MAXIMUM (Keyboard Right GUI) */ \ - HID_LI_USAGE_MAX(1), 0xE7, /* LOGICAL_MINIMUM (0) */ \ - HID_GI_LOGICAL_MIN(1), 0x00, /* LOGICAL_MAXIMUM (1) */ \ - HID_GI_LOGICAL_MAX(1), 0x01, /* REPORT_SIZE (1) */ \ - HID_GI_REPORT_SIZE, 0x01, /* REPORT_COUNT (8) */ \ - HID_GI_REPORT_COUNT, 0x08, /* INPUT (Data,Var,Abs) */ \ - HID_MI_INPUT, 0x02, /* REPORT_SIZE (8) */ \ - HID_GI_REPORT_SIZE, 0x08, /* REPORT_COUNT (1) */ \ - HID_GI_REPORT_COUNT, 0x01, /* INPUT (Cnst,Var,Abs) */ \ - HID_MI_INPUT, 0x03, /* REPORT_SIZE (1) */ \ - HID_GI_REPORT_SIZE, 0x01, /* REPORT_COUNT (5) */ \ - HID_GI_REPORT_COUNT, 0x05, /* USAGE_PAGE (LEDs) */ \ - HID_GI_USAGE_PAGE, USAGE_GEN_LEDS, /* USAGE_MINIMUM (Num Lock) */ \ - HID_LI_USAGE_MIN(1), 0x01, /* USAGE_MAXIMUM (Kana) */ \ - HID_LI_USAGE_MAX(1), 0x05, /* OUTPUT (Data,Var,Abs) */ \ - HID_MI_OUTPUT, 0x02, /* REPORT_SIZE (3) */ \ - HID_GI_REPORT_SIZE, 0x03, /* REPORT_COUNT (1) */ \ - HID_GI_REPORT_COUNT, 0x01, /* OUTPUT (Cnst,Var,Abs) */ \ - HID_MI_OUTPUT, 0x03, /* REPORT_SIZE (8) */ \ - HID_GI_REPORT_SIZE, 0x08, /* REPORT_COUNT (6) */ \ - HID_GI_REPORT_COUNT, 0x06, /* LOGICAL_MINIMUM (0) */ \ - HID_GI_LOGICAL_MIN(1), 0x00, /* LOGICAL_MAXIMUM (101) */ \ - HID_GI_LOGICAL_MAX(1), 0x65, /* USAGE_PAGE (Keypad) */ \ - HID_GI_USAGE_PAGE, USAGE_GEN_DESKTOP_KEYPAD, /* USAGE_MINIMUM (Reserved) */ \ - HID_LI_USAGE_MIN(1), 0x00, /* USAGE_MAXIMUM (Keyboard Application) */ \ - HID_LI_USAGE_MAX(1), 0x65, /* INPUT (Data,Ary,Abs) */ \ - HID_MI_INPUT, 0x00, /* END_COLLECTION */ \ - HID_MI_COLLECTION_END, \ - } - -/** - * @brief HID keyboard button codes. - */ -enum hid_kbd_code { - HID_KEY_A = 4, - HID_KEY_B = 5, - HID_KEY_C = 6, - HID_KEY_D = 7, - HID_KEY_E = 8, - HID_KEY_F = 9, - HID_KEY_G = 10, - HID_KEY_H = 11, - HID_KEY_I = 12, - HID_KEY_J = 13, - HID_KEY_K = 14, - HID_KEY_L = 15, - HID_KEY_M = 16, - HID_KEY_N = 17, - HID_KEY_O = 18, - HID_KEY_P = 19, - HID_KEY_Q = 20, - HID_KEY_R = 21, - HID_KEY_S = 22, - HID_KEY_T = 23, - HID_KEY_U = 24, - HID_KEY_V = 25, - HID_KEY_W = 26, - HID_KEY_X = 27, - HID_KEY_Y = 28, - HID_KEY_Z = 29, - HID_KEY_1 = 30, - HID_KEY_2 = 31, - HID_KEY_3 = 32, - HID_KEY_4 = 33, - HID_KEY_5 = 34, - HID_KEY_6 = 35, - HID_KEY_7 = 36, - HID_KEY_8 = 37, - HID_KEY_9 = 38, - HID_KEY_0 = 39, - HID_KEY_ENTER = 40, - HID_KEY_ESC = 41, - HID_KEY_BACKSPACE = 42, - HID_KEY_TAB = 43, - HID_KEY_SPACE = 44, - HID_KEY_MINUS = 45, - HID_KEY_EQUAL = 46, - HID_KEY_LEFTBRACE = 47, - HID_KEY_RIGHTBRACE = 48, - HID_KEY_BACKSLASH = 49, - HID_KEY_HASH = 50, /* Non-US # and ~ */ - HID_KEY_SEMICOLON = 51, - HID_KEY_APOSTROPHE = 52, - HID_KEY_GRAVE = 53, - HID_KEY_COMMA = 54, - HID_KEY_DOT = 55, - HID_KEY_SLASH = 56, - HID_KEY_CAPSLOCK = 57, - HID_KEY_F1 = 58, - HID_KEY_F2 = 59, - HID_KEY_F3 = 60, - HID_KEY_F4 = 61, - HID_KEY_F5 = 62, - HID_KEY_F6 = 63, - HID_KEY_F7 = 64, - HID_KEY_F8 = 65, - HID_KEY_F9 = 66, - HID_KEY_F10 = 67, - HID_KEY_F11 = 68, - HID_KEY_F12 = 69, - HID_KEY_SYSRQ = 70, /* PRINTSCREEN */ - HID_KEY_SCROLLLOCK = 71, - HID_KEY_PAUSE = 72, - HID_KEY_INSERT = 73, - HID_KEY_HOME = 74, - HID_KEY_PAGEUP = 75, - HID_KEY_DELETE = 76, - HID_KEY_END = 77, - HID_KEY_PAGEDOWN = 78, - HID_KEY_RIGHT = 79, - HID_KEY_LEFT = 80, - HID_KEY_DOWN = 81, - HID_KEY_UP = 82, - HID_KEY_NUMLOCK = 83, - HID_KEY_KPSLASH = 84, /* NUMPAD DIVIDE */ - HID_KEY_KPASTERISK = 85, /* NUMPAD MULTIPLY */ - HID_KEY_KPMINUS = 86, - HID_KEY_KPPLUS = 87, - HID_KEY_KPENTER = 88, - HID_KEY_KP_1 = 89, - HID_KEY_KP_2 = 90, - HID_KEY_KP_3 = 91, - HID_KEY_KP_4 = 92, - HID_KEY_KP_5 = 93, - HID_KEY_KP_6 = 94, - HID_KEY_KP_7 = 95, - HID_KEY_KP_8 = 96, - HID_KEY_KP_9 = 97, - HID_KEY_KP_0 = 98, -}; - -/** - * @brief HID keyboard modifiers. - */ -enum hid_kbd_modifier { - HID_KBD_MODIFIER_NONE = 0x00, - HID_KBD_MODIFIER_LEFT_CTRL = 0x01, - HID_KBD_MODIFIER_LEFT_SHIFT = 0x02, - HID_KBD_MODIFIER_LEFT_ALT = 0x04, - HID_KBD_MODIFIER_LEFT_UI = 0x08, - HID_KBD_MODIFIER_RIGHT_CTRL = 0x10, - HID_KBD_MODIFIER_RIGHT_SHIFT = 0x20, - HID_KBD_MODIFIER_RIGHT_ALT = 0x40, - HID_KBD_MODIFIER_RIGHT_UI = 0x80, -}; - -/** - * @brief HID keyboard LEDs. - */ -enum hid_kbd_led { - HID_KBD_LED_NUM_LOCK = 0x01, - HID_KBD_LED_CAPS_LOCK = 0x02, - HID_KBD_LED_SCROLL_LOCK = 0x04, - HID_KBD_LED_COMPOSE = 0x08, - HID_KBD_LED_KANA = 0x10, -}; - -void usbd_hid_descriptor_register(uint8_t intf_num, const uint8_t *desc); -void usbd_hid_report_descriptor_register(uint8_t intf_num, const uint8_t *desc, uint32_t desc_len); -void usbd_hid_add_interface(usbd_class_t *class, usbd_interface_t *intf); -void usbd_hid_reset_state(void); -void usbd_hid_send_report(uint8_t ep, uint8_t *data, uint8_t len); -// clang-format off -void usbd_hid_set_request_callback( uint8_t intf_num, - uint8_t (*get_report_callback)(uint8_t report_id, uint8_t report_type), - void (*set_report_callback)(uint8_t report_id, uint8_t report_type, uint8_t *report, uint8_t report_len), - uint8_t (*get_idle_callback)(uint8_t report_id), - void (*set_idle_callback)(uint8_t report_id, uint8_t duration), - void (*set_protocol_callback)(uint8_t protocol), - uint8_t (*get_protocol_callback)(void)); -// clang-format on -#ifdef __cplusplus -} -#endif - -#endif /* _USB_HID_H_ */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.c deleted file mode 100644 index 90cca19c0d..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.c +++ /dev/null @@ -1,909 +0,0 @@ -/** - * @file usbd_msc.c - * @brief - * - * Copyright (c) 2021 Bouffalolab team - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - */ -#include "usbd_msc.h" -#include "usbd_core.h" -#include "usbd_scsi.h" - -/* max USB packet size */ -#ifndef CONFIG_USB_HS -#define MASS_STORAGE_BULK_EP_MPS 64 -#else -#define MASS_STORAGE_BULK_EP_MPS 512 -#endif - -#define MSD_OUT_EP_IDX 0 -#define MSD_IN_EP_IDX 1 - -/* Describe EndPoints configuration */ -static usbd_endpoint_t mass_ep_data[2]; - -/* MSC Bulk-only Stage */ -enum Stage { - MSC_READ_CBW = 0, /* Command Block Wrapper */ - MSC_DATA_OUT = 1, /* Data Out Phase */ - MSC_DATA_IN = 2, /* Data In Phase */ - MSC_SEND_CSW = 3, /* Command Status Wrapper */ - MSC_WAIT_CSW = 4, /* Command Status Wrapper */ -}; - -/** MSC Bulk-Only Command Block Wrapper (CBW) */ -struct CBW { - uint32_t dSignature; - uint32_t dTag; - uint32_t dDataLength; - uint8_t bmFlags; - uint8_t bLUN; - uint8_t bCBLength; - uint8_t CB[16]; -} __packed; - -/** MSC Bulk-Only Command Status Wrapper (CSW) */ -struct CSW { - uint32_t dSignature; - uint32_t dTag; - uint32_t dDataResidue; - uint8_t bStatus; -} __packed; - -/* Device data structure */ -struct usbd_msc_cfg_private { - /* state of the bulk-only state machine */ - enum Stage stage; - struct CBW cbw; - struct CSW csw; - - uint8_t sKey; /* Sense key */ - uint8_t ASC; /* Additional Sense Code */ - uint8_t ASQ; /* Additional Sense Qualifier */ - uint8_t max_lun; - uint16_t scsi_blk_size; - uint32_t scsi_blk_nbr; - - uint32_t scsi_blk_addr; - uint32_t scsi_blk_len; - uint8_t *block_buffer; - -} usbd_msc_cfg; - -/*memory OK (after a usbd_msc_memory_verify)*/ -static bool memOK; - -static void usbd_msc_reset(void) { - usbd_msc_cfg.stage = MSC_READ_CBW; - usbd_msc_cfg.scsi_blk_addr = 0U; - usbd_msc_cfg.scsi_blk_len = 0U; - usbd_msc_cfg.max_lun = 0; - usbd_msc_cfg.sKey = 0; - usbd_msc_cfg.ASC = 0; - usbd_msc_cfg.ASQ = 0; - - (void)memset((void *)&usbd_msc_cfg.cbw, 0, sizeof(struct CBW)); - (void)memset((void *)&usbd_msc_cfg.csw, 0, sizeof(struct CSW)); - - usbd_msc_get_cap(0, &usbd_msc_cfg.scsi_blk_nbr, &usbd_msc_cfg.scsi_blk_size); - - if (usbd_msc_cfg.block_buffer) { - free(usbd_msc_cfg.block_buffer); - } - usbd_msc_cfg.block_buffer = malloc(usbd_msc_cfg.scsi_blk_size * sizeof(uint8_t)); - memset(usbd_msc_cfg.block_buffer, 0, usbd_msc_cfg.scsi_blk_size * sizeof(uint8_t)); -} - -/** - * @brief Handler called for Class requests not handled by the USB stack. - * - * @param setup Information about the request to execute. - * @param len Size of the buffer. - * @param data Buffer containing the request result. - * - * @return 0 on success, negative errno code on fail. - */ -static int msc_storage_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) { - USBD_LOG_DBG("MSC Class request: " - "bRequest 0x%02x\r\n", - setup->bRequest); - - switch (setup->bRequest) { - case MSC_REQUEST_RESET: - USBD_LOG_DBG("MSC_REQUEST_RESET\r\n"); - - if (setup->wLength) { - USBD_LOG_WRN("Invalid length\r\n"); - return -1; - } - - usbd_msc_reset(); - break; - - case MSC_REQUEST_GET_MAX_LUN: - USBD_LOG_DBG("MSC_REQUEST_GET_MAX_LUN\r\n"); - - if (setup->wLength != 1) { - USBD_LOG_WRN("Invalid length\r\n"); - return -1; - } - - *data = (uint8_t *)(&usbd_msc_cfg.max_lun); - *len = 1; - break; - - default: - USBD_LOG_WRN("Unhandled MSC Class bRequest 0x%02x\r\n", setup->bRequest); - return -1; - } - - return 0; -} - -static void usbd_msc_bot_abort(void) { - if ((usbd_msc_cfg.cbw.bmFlags == 0) && (usbd_msc_cfg.cbw.dDataLength != 0)) { - usbd_ep_set_stall(mass_ep_data[MSD_OUT_EP_IDX].ep_addr); - } - usbd_ep_set_stall(mass_ep_data[MSD_IN_EP_IDX].ep_addr); -} - -static void sendCSW(uint8_t CSW_Status) { - usbd_msc_cfg.csw.dSignature = MSC_CSW_Signature; - usbd_msc_cfg.csw.bStatus = CSW_Status; - - /* updating the State Machine , so that we wait CSW when this - * transfer is complete, ie when we get a bulk in callback - */ - usbd_msc_cfg.stage = MSC_WAIT_CSW; - - if (usbd_ep_write(mass_ep_data[MSD_IN_EP_IDX].ep_addr, (uint8_t *)&usbd_msc_cfg.csw, sizeof(struct CSW), NULL) != 0) { - USBD_LOG_ERR("usb write failure\r\n"); - } -} - -static void sendLastData(uint8_t *buffer, uint8_t size) { - size = MIN(size, usbd_msc_cfg.cbw.dDataLength); - - /* updating the State Machine , so that we send CSW when this - * transfer is complete, ie when we get a bulk in callback - */ - usbd_msc_cfg.stage = MSC_SEND_CSW; - - if (usbd_ep_write(mass_ep_data[MSD_IN_EP_IDX].ep_addr, buffer, size, NULL) != 0) { - USBD_LOG_ERR("USB write failed\r\n"); - } - - usbd_msc_cfg.csw.dDataResidue -= size; - usbd_msc_cfg.csw.bStatus = CSW_STATUS_CMD_PASSED; -} - -/** - * @brief SCSI COMMAND - */ -static bool SCSI_testUnitReady(uint8_t **data, uint32_t *len); -static bool SCSI_requestSense(uint8_t **data, uint32_t *len); -static bool SCSI_inquiry(uint8_t **data, uint32_t *len); -static bool SCSI_startStopUnit(uint8_t **data, uint32_t *len); -static bool SCSI_preventAllowMediaRemoval(uint8_t **data, uint32_t *len); -static bool SCSI_modeSense6(uint8_t **data, uint32_t *len); -static bool SCSI_modeSense10(uint8_t **data, uint32_t *len); -static bool SCSI_readFormatCapacity(uint8_t **data, uint32_t *len); -static bool SCSI_readCapacity10(uint8_t **data, uint32_t *len); -static bool SCSI_read10(uint8_t **data, uint32_t *len); -static bool SCSI_read12(uint8_t **data, uint32_t *len); -static bool SCSI_write10(uint8_t **data, uint32_t *len); -static bool SCSI_write12(uint8_t **data, uint32_t *len); -static bool SCSI_verify10(uint8_t **data, uint32_t *len); - -/** -* @brief SCSI_SenseCode -* Load the last error code in the error list -* @param sKey: Sense Key -* @param ASC: Additional Sense Code -* @retval none - -*/ -static void SCSI_SenseCode(uint8_t sKey, uint8_t ASC) { - usbd_msc_cfg.sKey = sKey; - usbd_msc_cfg.ASC = ASC; -} - -static bool SCSI_processRead(void) { - uint32_t transfer_len; - - USBD_LOG_DBG("read addr:%d\r\n", usbd_msc_cfg.scsi_blk_addr); - - transfer_len = MIN(usbd_msc_cfg.scsi_blk_len, MASS_STORAGE_BULK_EP_MPS); - - /* we read an entire block */ - if (!(usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size)) { - if (usbd_msc_sector_read((usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size), usbd_msc_cfg.block_buffer, usbd_msc_cfg.scsi_blk_size) != 0) { - SCSI_SenseCode(SCSI_SENSE_HARDWARE_ERROR, SCSI_ASC_UNRECOVERED_READ_ERROR); - return false; - } - } - - usbd_ep_write(mass_ep_data[MSD_IN_EP_IDX].ep_addr, &usbd_msc_cfg.block_buffer[usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size], transfer_len, NULL); - - usbd_msc_cfg.scsi_blk_addr += transfer_len; - usbd_msc_cfg.scsi_blk_len -= transfer_len; - usbd_msc_cfg.csw.dDataResidue -= transfer_len; - - if (usbd_msc_cfg.scsi_blk_len == 0) { - usbd_msc_cfg.stage = MSC_SEND_CSW; - } - - return true; -} - -static bool SCSI_processWrite(uint8_t *buf, uint16_t len) { - USBD_LOG_DBG("write addr:%d\r\n", usbd_msc_cfg.scsi_blk_addr); - - /* we fill an array in RAM of 1 block before writing it in memory */ - for (int i = 0; i < len; i++) { - usbd_msc_cfg.block_buffer[usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size + i] = buf[i]; - } - - /* if the array is filled, write it in memory */ - if ((usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size) + len >= usbd_msc_cfg.scsi_blk_size) { - if (usbd_msc_sector_write((usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size), usbd_msc_cfg.block_buffer, usbd_msc_cfg.scsi_blk_size) != 0) { - SCSI_SenseCode(SCSI_SENSE_HARDWARE_ERROR, SCSI_ASC_WRITE_FAULT); - return false; - } - } - - usbd_msc_cfg.scsi_blk_addr += len; - usbd_msc_cfg.scsi_blk_len -= len; - usbd_msc_cfg.csw.dDataResidue -= len; - - if (usbd_msc_cfg.scsi_blk_len == 0) { - sendCSW(CSW_STATUS_CMD_PASSED); - } - - return true; -} - -static bool SCSI_processVerify(uint8_t *buf, uint16_t len) { - USBD_LOG_DBG("verify addr:%d\r\n", usbd_msc_cfg.scsi_blk_addr); - - /* we read an entire block */ - if (!(usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size)) { - if (usbd_msc_sector_read((usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size), usbd_msc_cfg.block_buffer, usbd_msc_cfg.scsi_blk_size) != 0) { - SCSI_SenseCode(SCSI_SENSE_HARDWARE_ERROR, SCSI_ASC_UNRECOVERED_READ_ERROR); - return false; - } - } - - /* info are in RAM -> no need to re-read memory */ - for (uint16_t i = 0U; i < len; i++) { - if (usbd_msc_cfg.block_buffer[usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size + i] != buf[i]) { - USBD_LOG_DBG("Mismatch sector %d offset %d", usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size, i); - memOK = false; - break; - } - } - - usbd_msc_cfg.scsi_blk_addr += len; - usbd_msc_cfg.scsi_blk_len -= len; - usbd_msc_cfg.csw.dDataResidue -= len; - - if (usbd_msc_cfg.scsi_blk_len == 0) { - sendCSW(CSW_STATUS_CMD_PASSED); - } - - return true; -} - -static bool SCSI_CBWDecode(uint8_t *buf, uint16_t size) { - uint8_t send_buffer[64]; - uint8_t *buf2send = send_buffer; - uint32_t len2send = 0; - bool ret = false; - - if (size != sizeof(struct CBW)) { - USBD_LOG_ERR("size != sizeof(cbw)\r\n"); - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } - - memcpy((uint8_t *)&usbd_msc_cfg.cbw, buf, size); - - usbd_msc_cfg.csw.dTag = usbd_msc_cfg.cbw.dTag; - usbd_msc_cfg.csw.dDataResidue = usbd_msc_cfg.cbw.dDataLength; - - if ((usbd_msc_cfg.cbw.bLUN > 1) || (usbd_msc_cfg.cbw.dSignature != MSC_CBW_Signature) || (usbd_msc_cfg.cbw.bCBLength < 1) || (usbd_msc_cfg.cbw.bCBLength > 16)) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } else { - switch (usbd_msc_cfg.cbw.CB[0]) { - case SCSI_TEST_UNIT_READY: - ret = SCSI_testUnitReady(&buf2send, &len2send); - break; - case SCSI_REQUEST_SENSE: - ret = SCSI_requestSense(&buf2send, &len2send); - break; - case SCSI_INQUIRY: - ret = SCSI_inquiry(&buf2send, &len2send); - break; - case SCSI_START_STOP_UNIT: - ret = SCSI_startStopUnit(&buf2send, &len2send); - break; - case SCSI_PREVENT_ALLOW_MEDIA_REMOVAL: - ret = SCSI_preventAllowMediaRemoval(&buf2send, &len2send); - break; - case SCSI_MODE_SENSE6: - ret = SCSI_modeSense6(&buf2send, &len2send); - break; - case SCSI_MODE_SENSE10: - ret = SCSI_modeSense10(&buf2send, &len2send); - break; - case SCSI_READ_FORMAT_CAPACITIES: - ret = SCSI_readFormatCapacity(&buf2send, &len2send); - break; - case SCSI_READ_CAPACITY10: - ret = SCSI_readCapacity10(&buf2send, &len2send); - break; - case SCSI_READ10: - ret = SCSI_read10(NULL, 0); - break; - case SCSI_READ12: - ret = SCSI_read12(NULL, 0); - break; - case SCSI_WRITE10: - ret = SCSI_write10(NULL, 0); - break; - case SCSI_WRITE12: - ret = SCSI_write12(NULL, 0); - break; - case SCSI_VERIFY10: - ret = SCSI_verify10(NULL, 0); - break; - - default: - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - USBD_LOG_WRN("unsupported cmd:0x%02x\r\n", usbd_msc_cfg.cbw.CB[0]); - ret = false; - break; - } - } - if (ret) { - if (usbd_msc_cfg.stage == MSC_READ_CBW) { - if (len2send) { - sendLastData(buf2send, len2send); - } else { - sendCSW(CSW_STATUS_CMD_PASSED); - } - } - } - return ret; -} - -static bool SCSI_testUnitReady(uint8_t **data, uint32_t *len) { - if (usbd_msc_cfg.cbw.dDataLength != 0U) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } - *data = NULL; - *len = 0; - return true; -} - -static bool SCSI_requestSense(uint8_t **data, uint32_t *len) { - uint8_t data_len = REQUEST_SENSE_DATA_LEN; - if (usbd_msc_cfg.cbw.dDataLength == 0U) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } - - if (usbd_msc_cfg.cbw.CB[4] < REQUEST_SENSE_DATA_LEN) { - data_len = usbd_msc_cfg.cbw.CB[4]; - } - - uint8_t request_sense[REQUEST_SENSE_DATA_LEN] = { - 0x70, 0x00, 0x00, /* Sense Key */ - 0x00, 0x00, 0x00, 0x00, REQUEST_SENSE_DATA_LEN - 8, 0x00, 0x00, 0x00, 0x00, 0x00, /* Additional Sense Code */ - 0x00, /* Additional Sense Request */ - 0x00, 0x00, 0x00, 0x00, - }; - - request_sense[2] = usbd_msc_cfg.sKey; - request_sense[12] = usbd_msc_cfg.ASC; - request_sense[13] = usbd_msc_cfg.ASQ; -#if 0 - request_sense[ 2] = 0x06; /* UNIT ATTENTION */ - request_sense[12] = 0x28; /* Additional Sense Code: Not ready to ready transition */ - request_sense[13] = 0x00; /* Additional Sense Code Qualifier */ -#endif -#if 0 - request_sense[ 2] = 0x02; /* NOT READY */ - request_sense[12] = 0x3A; /* Additional Sense Code: Medium not present */ - request_sense[13] = 0x00; /* Additional Sense Code Qualifier */ -#endif -#if 0 - request_sense[ 2] = 0x05; /* ILLEGAL REQUEST */ - request_sense[12] = 0x20; /* Additional Sense Code: Invalid command */ - request_sense[13] = 0x00; /* Additional Sense Code Qualifier */ -#endif -#if 0 - request_sense[ 2] = 0x00; /* NO SENSE */ - request_sense[12] = 0x00; /* Additional Sense Code: No additional code */ - request_sense[13] = 0x00; /* Additional Sense Code Qualifier */ -#endif - - memcpy(*data, (uint8_t *)&request_sense, data_len); - *len = data_len; - return true; -} - -static bool SCSI_inquiry(uint8_t **data, uint32_t *len) { - uint8_t data_len = STANDARD_INQUIRY_DATA_LEN; - - uint8_t inquiry00[6] = {0x00, 0x00, 0x00, (0x06 - 4U), 0x00, 0x80}; - - /* USB Mass storage VPD Page 0x80 Inquiry Data for Unit Serial Number */ - uint8_t inquiry80[8] = {0x00, 0x80, 0x00, 0x08, 0x20, /* Put Product Serial number */ - 0x20, 0x20, 0x20}; - - uint8_t inquiry[STANDARD_INQUIRY_DATA_LEN] = { - /* 36 */ - - /* LUN 0 */ - 0x00, 0x80, 0x02, 0x02, (STANDARD_INQUIRY_DATA_LEN - 5), - 0x00, 0x00, 0x00, 'B', 'o', - 'u', 'f', 'f', 'a', 'l', - 'o', /* Manufacturer : 8 bytes */ - 'P', 'r', 'o', 'd', 'u', - 'c', 't', ' ', /* Product : 16 Bytes */ - ' ', ' ', ' ', ' ', ' ', - ' ', ' ', ' ', '0', '.', - '0', '1' /* Version : 4 Bytes */ - }; - - if (usbd_msc_cfg.cbw.dDataLength == 0U) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } - - if ((usbd_msc_cfg.cbw.CB[1] & 0x01U) != 0U) { /* Evpd is set */ - if (usbd_msc_cfg.cbw.CB[2] == 0U) { /* Request for Supported Vital Product Data Pages*/ - data_len = 0x06; - memcpy(*data, (uint8_t *)&inquiry00, data_len); - } else if (usbd_msc_cfg.cbw.CB[2] == 0x80U) { /* Request for VPD page 0x80 Unit Serial Number */ - data_len = 0x08; - memcpy(*data, (uint8_t *)&inquiry80, data_len); - } else { /* Request Not supported */ - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_FIELED_IN_COMMAND); - return false; - } - } else { - if (usbd_msc_cfg.cbw.CB[4] < STANDARD_INQUIRY_DATA_LEN) { - data_len = usbd_msc_cfg.cbw.CB[4]; - } - memcpy(*data, (uint8_t *)&inquiry, data_len); - } - - *len = data_len; - return true; -} - -static bool SCSI_startStopUnit(uint8_t **data, uint32_t *len) { - if (usbd_msc_cfg.cbw.dDataLength != 0U) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } - - if ((usbd_msc_cfg.cbw.CB[4] & 0x3U) == 0x1U) /* START=1 */ - { - // SCSI_MEDIUM_UNLOCKED; - } else if ((usbd_msc_cfg.cbw.CB[4] & 0x3U) == 0x2U) /* START=0 and LOEJ Load Eject=1 */ - { - // SCSI_MEDIUM_EJECTED; - } else if ((usbd_msc_cfg.cbw.CB[4] & 0x3U) == 0x3U) /* START=1 and LOEJ Load Eject=1 */ - { - // SCSI_MEDIUM_UNLOCKED; - } else { - } - - *data = NULL; - *len = 0; - return true; -} - -static bool SCSI_preventAllowMediaRemoval(uint8_t **data, uint32_t *len) { - if (usbd_msc_cfg.cbw.dDataLength != 0U) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } - if (usbd_msc_cfg.cbw.CB[4] == 0U) { - // SCSI_MEDIUM_UNLOCKED; - } else { - // SCSI_MEDIUM_LOCKED; - } - *data = NULL; - *len = 0; - return true; -} - -static bool SCSI_modeSense6(uint8_t **data, uint32_t *len) { - uint8_t data_len = 4; - if (usbd_msc_cfg.cbw.dDataLength == 0U) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } - if (usbd_msc_cfg.cbw.CB[4] < MODE_SENSE6_DATA_LEN) { - data_len = usbd_msc_cfg.cbw.CB[4]; - } - - uint8_t sense6[] = {0x03, 0x00, 0x00, 0x00}; - - memcpy(*data, (uint8_t *)&sense6, data_len); - *len = data_len; - return true; -} - -static bool SCSI_modeSense10(uint8_t **data, uint32_t *len) { - uint8_t data_len = MODE_SENSE10_DATA_LEN; - if (usbd_msc_cfg.cbw.dDataLength == 0U) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } - if (usbd_msc_cfg.cbw.CB[8] < MODE_SENSE10_DATA_LEN) { - data_len = usbd_msc_cfg.cbw.CB[8]; - } - - uint8_t sense10[MODE_SENSE10_DATA_LEN] - = {0x00, 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - memcpy(*data, (uint8_t *)&sense10, data_len); - *len = data_len; - return true; -} - -static bool SCSI_readFormatCapacity(uint8_t **data, uint32_t *len) { - if (usbd_msc_cfg.cbw.dDataLength == 0U) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } - uint8_t capacity[READ_FORMAT_CAPACITY_DATA_LEN] = { - 0x00, - 0x00, - 0x00, - 0x08, /* Capacity List Length */ - (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 24) & 0xff), - (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 16) & 0xff), - (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 8) & 0xff), - (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 0) & 0xff), - - 0x02, /* Descriptor Code: Formatted Media */ - 0x00, - (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 8) & 0xff), - (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 0) & 0xff), - }; - - memcpy(*data, (uint8_t *)&capacity, READ_FORMAT_CAPACITY_DATA_LEN); - *len = READ_FORMAT_CAPACITY_DATA_LEN; - return true; -} - -static bool SCSI_readCapacity10(uint8_t **data, uint32_t *len) { - if (usbd_msc_cfg.cbw.dDataLength == 0U) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } - - uint8_t capacity[READ_CAPACITY10_DATA_LEN] = { - (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 24) & 0xff), (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 16) & 0xff), - (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 8) & 0xff), (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 0) & 0xff), - - (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 24) & 0xff), (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 16) & 0xff), - (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 8) & 0xff), (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 0) & 0xff), - }; - - memcpy(*data, (uint8_t *)&capacity, READ_CAPACITY10_DATA_LEN); - *len = READ_CAPACITY10_DATA_LEN; - return true; -} - -static bool SCSI_read10(uint8_t **data, uint32_t *len) { - /* Logical Block Address of First Block */ - uint32_t lba = 0; - uint32_t blk_num = 0; - if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x80U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } - - lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]); - USBD_LOG_DBG("lba: 0x%x\r\n", lba); - - usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size; - - /* Number of Blocks to transfer */ - blk_num = GET_BE16(&usbd_msc_cfg.cbw.CB[7]); - - USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num); - usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size; - - if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) { - USBD_LOG_ERR("LBA out of range\r\n"); - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ADDRESS_OUT_OF_RANGE); - return false; - } - - if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) { - return false; - } - usbd_msc_cfg.stage = MSC_DATA_IN; - return SCSI_processRead(); -} - -static bool SCSI_read12(uint8_t **data, uint32_t *len) { - /* Logical Block Address of First Block */ - uint32_t lba = 0; - uint32_t blk_num = 0; - if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x80U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } - - lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]); - USBD_LOG_DBG("lba: 0x%x\r\n", lba); - - usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size; - - /* Number of Blocks to transfer */ - blk_num = GET_BE32(&usbd_msc_cfg.cbw.CB[6]); - - USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num); - usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size; - - if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) { - USBD_LOG_ERR("LBA out of range\r\n"); - return false; - } - - if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) { - return false; - } - usbd_msc_cfg.stage = MSC_DATA_IN; - return SCSI_processRead(); -} - -static bool SCSI_write10(uint8_t **data, uint32_t *len) { - /* Logical Block Address of First Block */ - uint32_t lba = 0; - uint32_t blk_num = 0; - if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x00U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } - - lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]); - USBD_LOG_DBG("lba: 0x%x\r\n", lba); - - usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size; - - /* Number of Blocks to transfer */ - blk_num = GET_BE16(&usbd_msc_cfg.cbw.CB[7]); - - USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num); - usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size; - - if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) { - USBD_LOG_ERR("LBA out of range\r\n"); - return false; - } - - if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) { - return false; - } - usbd_msc_cfg.stage = MSC_DATA_OUT; - return true; -} - -static bool SCSI_write12(uint8_t **data, uint32_t *len) { - /* Logical Block Address of First Block */ - uint32_t lba = 0; - uint32_t blk_num = 0; - if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x00U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } - - lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]); - USBD_LOG_DBG("lba: 0x%x\r\n", lba); - - usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size; - - /* Number of Blocks to transfer */ - blk_num = GET_BE32(&usbd_msc_cfg.cbw.CB[6]); - - USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num); - usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size; - - if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) { - USBD_LOG_ERR("LBA out of range\r\n"); - return false; - } - - if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) { - return false; - } - usbd_msc_cfg.stage = MSC_DATA_OUT; - return true; -} - -static bool SCSI_verify10(uint8_t **data, uint32_t *len) { - /* Logical Block Address of First Block */ - uint32_t lba = 0; - uint32_t blk_num = 0; - - if ((usbd_msc_cfg.cbw.CB[1] & 0x02U) == 0x00U) { - return true; - } - - if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x00U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB); - return false; - } - - if ((usbd_msc_cfg.cbw.CB[1] & 0x02U) == 0x02U) { - SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_FIELED_IN_COMMAND); - return false; /* Error, Verify Mode Not supported*/ - } - - lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]); - USBD_LOG_DBG("lba: 0x%x\r\n", lba); - - usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size; - - /* Number of Blocks to transfer */ - blk_num = GET_BE16(&usbd_msc_cfg.cbw.CB[7]); - - USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num); - usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size; - - if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) { - USBD_LOG_ERR("LBA out of range\r\n"); - return false; - } - - if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) { - return false; - } - - memOK = true; - usbd_msc_cfg.stage = MSC_DATA_OUT; - return true; -} - -static void mass_storage_bulk_out(uint8_t ep) { - uint8_t out_buf[MASS_STORAGE_BULK_EP_MPS]; - uint32_t bytes_read; - - usbd_ep_read(ep, out_buf, MASS_STORAGE_BULK_EP_MPS, &bytes_read); - - switch (usbd_msc_cfg.stage) { - case MSC_READ_CBW: - if (SCSI_CBWDecode(out_buf, bytes_read) == false) { - USBD_LOG_ERR("Command:0x%02x decode err\r\n", usbd_msc_cfg.cbw.CB[0]); - usbd_msc_bot_abort(); - return; - } - break; - /* last command is write10 or write12,and has caculated blk_addr and blk_len,so the device start reading data from host*/ - case MSC_DATA_OUT: - switch (usbd_msc_cfg.cbw.CB[0]) { - case SCSI_WRITE10: - case SCSI_WRITE12: - if (SCSI_processWrite(out_buf, bytes_read) == false) { - sendCSW(CSW_STATUS_CMD_FAILED); /* send fail status to host,and the host will retry*/ - // return; - } - break; - case SCSI_VERIFY10: - if (SCSI_processVerify(out_buf, bytes_read) == false) { - sendCSW(CSW_STATUS_CMD_FAILED); /* send fail status to host,and the host will retry*/ - // return; - } - break; - default: - break; - } - break; - default: - break; - } - - /*set ep ack to recv next data*/ - usbd_ep_read(ep, NULL, 0, NULL); -} - -/** - * @brief EP Bulk IN handler, used to send data to the Host - * - * @param ep Endpoint address. - * @param ep_status Endpoint status code. - * - * @return N/A. - */ -static void mass_storage_bulk_in(uint8_t ep) { - switch (usbd_msc_cfg.stage) { - /* last command is read10 or read12,and has caculated blk_addr and blk_len,so the device has to send remain data to host*/ - case MSC_DATA_IN: - switch (usbd_msc_cfg.cbw.CB[0]) { - case SCSI_READ10: - case SCSI_READ12: - if (SCSI_processRead() == false) { - sendCSW(CSW_STATUS_CMD_FAILED); /* send fail status to host,and the host will retry*/ - return; - } - break; - default: - break; - } - - break; - - /*the device has to send a CSW*/ - case MSC_SEND_CSW: - sendCSW(CSW_STATUS_CMD_PASSED); - break; - - /*the host has received the CSW*/ - case MSC_WAIT_CSW: - usbd_msc_cfg.stage = MSC_READ_CBW; - break; - - default: - break; - } -} - -void msc_storage_notify_handler(uint8_t event, void *arg) { - switch (event) { - case USB_EVENT_RESET: - usbd_msc_reset(); - break; - - default: - break; - } -} - -static usbd_class_t msc_class; - -static usbd_interface_t msc_intf = { - .class_handler = msc_storage_class_request_handler, - .vendor_handler = NULL, - .notify_handler = msc_storage_notify_handler, -}; - -void usbd_msc_class_init(uint8_t out_ep, uint8_t in_ep) { - msc_class.name = "usbd_msc"; - - usbd_class_register(&msc_class); - usbd_class_add_interface(&msc_class, &msc_intf); - - mass_ep_data[0].ep_addr = out_ep; - mass_ep_data[0].ep_cb = mass_storage_bulk_out; - mass_ep_data[1].ep_addr = in_ep; - mass_ep_data[1].ep_cb = mass_storage_bulk_in; - - usbd_interface_add_endpoint(&msc_intf, &mass_ep_data[0]); - usbd_interface_add_endpoint(&msc_intf, &mass_ep_data[1]); -} \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.h deleted file mode 100644 index 3b5fe3e5ca..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.h +++ /dev/null @@ -1,109 +0,0 @@ -/** - * @file - * @brief USB Mass Storage Class public header - * - * Header follows the Mass Storage Class Specification - * (Mass_Storage_Specification_Overview_v1.4_2-19-2010.pdf) and - * Mass Storage Class Bulk-Only Transport Specification - * (usbmassbulk_10.pdf). - * Header is limited to Bulk-Only Transfer protocol. - */ - -#ifndef _USBD_MSC_H__ -#define _USBD_MSC_H__ - -#ifdef __cplusplus -extern "C" { -#endif - -/* MSC Subclass Codes */ -#define MSC_SUBCLASS_RBC 0x01 -#define MSC_SUBCLASS_SFF8020I_MMC2 0x02 -#define MSC_SUBCLASS_QIC157 0x03 -#define MSC_SUBCLASS_UFI 0x04 -#define MSC_SUBCLASS_SFF8070I 0x05 -#define MSC_SUBCLASS_SCSI 0x06 - -/* MSC Protocol Codes */ -#define MSC_PROTOCOL_CBI_INT 0x00 -#define MSC_PROTOCOL_CBI_NOINT 0x01 -#define MSC_PROTOCOL_BULK_ONLY 0x50 - -/* MSC Request Codes */ -#define MSC_REQUEST_RESET 0xFF -#define MSC_REQUEST_GET_MAX_LUN 0xFE - -/** MSC Command Block Wrapper (CBW) Signature */ -#define MSC_CBW_Signature 0x43425355 -/** Bulk-only Command Status Wrapper (CSW) Signature */ -#define MSC_CSW_Signature 0x53425355 - -/** MSC Command Block Status Values */ -#define CSW_STATUS_CMD_PASSED 0x00 -#define CSW_STATUS_CMD_FAILED 0x01 -#define CSW_STATUS_PHASE_ERROR 0x02 - -/*Length of template descriptor: 23 bytes*/ -#define MSC_DESCRIPTOR_LEN (9 + 7 + 7) -// clang-format off -#ifndef SUPPORT_USB_HS -#define MSC_DESCRIPTOR_INIT(bFirstInterface, out_ep, in_ep,str_idx) \ - /* Interface */ \ - 0x09, /* bLength */ \ - USB_DESCRIPTOR_TYPE_INTERFACE, /* bDescriptorType */ \ - bFirstInterface, /* bInterfaceNumber */ \ - 0x00, /* bAlternateSetting */ \ - 0x02, /* bNumEndpoints */ \ - USB_DEVICE_CLASS_MASS_STORAGE, /* bInterfaceClass */ \ - MSC_SUBCLASS_SCSI, /* bInterfaceSubClass */ \ - MSC_PROTOCOL_BULK_ONLY, /* bInterfaceProtocol */ \ - str_idx, /* iInterface */ \ - 0x07, /* bLength */ \ - USB_DESCRIPTOR_TYPE_ENDPOINT, /* bDescriptorType */ \ - out_ep, /* bEndpointAddress */ \ - 0x02, /* bmAttributes */ \ - 0x40, 0x00, /* wMaxPacketSize */ \ - 0x00, /* bInterval */ \ - 0x07, /* bLength */ \ - USB_DESCRIPTOR_TYPE_ENDPOINT, /* bDescriptorType */ \ - in_ep, /* bEndpointAddress */ \ - 0x02, /* bmAttributes */ \ - 0x40, 0x00, /* wMaxPacketSize */ \ - 0x00 /* bInterval */ -#else -#define MSC_DESCRIPTOR_INIT(bFirstInterface, out_ep, in_ep,str_idx) \ - /* Interface */ \ - 0x09, /* bLength */ \ - USB_DESCRIPTOR_TYPE_INTERFACE, /* bDescriptorType */ \ - bFirstInterface, /* bInterfaceNumber */ \ - 0x00, /* bAlternateSetting */ \ - 0x02, /* bNumEndpoints */ \ - USB_DEVICE_CLASS_MASS_STORAGE, /* bInterfaceClass */ \ - MSC_SUBCLASS_SCSI, /* bInterfaceSubClass */ \ - MSC_PROTOCOL_BULK_ONLY, /* bInterfaceProtocol */ \ - str_idx, /* iInterface */ \ - 0x07, /* bLength */ \ - USB_DESCRIPTOR_TYPE_ENDPOINT, /* bDescriptorType */ \ - out_ep, /* bEndpointAddress */ \ - 0x02, /* bmAttributes */ \ - 0x00, 0x02, /* wMaxPacketSize */ \ - 0x00, /* bInterval */ \ - 0x07, /* bLength */ \ - USB_DESCRIPTOR_TYPE_ENDPOINT, /* bDescriptorType */ \ - in_ep, /* bEndpointAddress */ \ - 0x02, /* bmAttributes */ \ - 0x00, 0x02, /* wMaxPacketSize */ \ - 0x00 /* bInterval */ -#endif -// clang-format on - -void usbd_msc_class_init(uint8_t out_ep, uint8_t in_ep); -void usbd_msc_get_cap(uint8_t lun, uint32_t *block_num, uint16_t *block_size); -int usbd_msc_sector_read(uint32_t sector, uint8_t *buffer, uint32_t length); -int usbd_msc_sector_write(uint32_t sector, uint8_t *buffer, uint32_t length); - -#ifdef __cplusplus -} -#endif - -#endif /* USB_MSC_H_ */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_scsi.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_scsi.h deleted file mode 100644 index 618d8f7adb..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_scsi.h +++ /dev/null @@ -1,325 +0,0 @@ -/** - * @file - * @brief USB Mass Storage Class SCSI public header - * - * Header follows the Mass Storage Class Specification - * (Mass_Storage_Specification_Overview_v1.4_2-19-2010.pdf) and - * Mass Storage Class Bulk-Only Transport Specification - * (usbmassbulk_10.pdf). - * Header is limited to Bulk-Only Transfer protocol. - */ - -#ifndef _USBD_SCSI_H_ -#define _USBD_SCSI_H_ - -/* SCSI Commands */ -#define SCSI_TEST_UNIT_READY 0x00 -#define SCSI_REQUEST_SENSE 0x03 -#define SCSI_FORMAT_UNIT 0x04 -#define SCSI_INQUIRY 0x12 -#define SCSI_MODE_SELECT6 0x15 -#define SCSI_MODE_SENSE6 0x1A -#define SCSI_START_STOP_UNIT 0x1B -#define SCSI_SEND_DIAGNOSTIC 0x1D -#define SCSI_PREVENT_ALLOW_MEDIA_REMOVAL 0x1E -#define SCSI_READ_FORMAT_CAPACITIES 0x23 -#define SCSI_READ_CAPACITY10 0x25 -#define SCSI_READ10 0x28 -#define SCSI_WRITE10 0x2A -#define SCSI_VERIFY10 0x2F -#define SCSI_SYNC_CACHE10 0x35 -#define SCSI_READ12 0xA8 -#define SCSI_WRITE12 0xAA -#define SCSI_MODE_SELECT10 0x55 -#define SCSI_MODE_SENSE10 0x5A -#define SCSI_ATA_COMMAND_PASS_THROUGH16 0x85 -#define SCSI_READ16 0x88 -#define SCSI_WRITE16 0x8A -#define SCSI_VERIFY16 0x8F -#define SCSI_SYNC_CACHE16 0x91 -#define SCSI_SERVICE_ACTION_IN16 0x9E -#define SCSI_READ_CAPACITY16 0x9E -#define SCSI_SERVICE_ACTION_OUT16 0x9F -#define SCSI_ATA_COMMAND_PASS_THROUGH12 0xA1 -#define SCSI_REPORT_ID_INFO 0xA3 -#define SCSI_READ12 0xA8 -#define SCSI_SERVICE_ACTION_OUT12 0xA9 -#define SCSI_SERVICE_ACTION_IN12 0xAB -#define SCSI_VERIFY12 0xAF - -/* SCSI Sense Key */ -#define SCSI_SENSE_NONE 0x00 -#define SCSI_SENSE_RECOVERED_ERROR 0x01 -#define SCSI_SENSE_NOT_READY 0x02 -#define SCSI_SENSE_MEDIUM_ERROR 0x03 -#define SCSI_SENSE_HARDWARE_ERROR 0x04 -#define SCSI_SENSE_ILLEGAL_REQUEST 0x05 -#define SCSI_SENSE_UNIT_ATTENTION 0x06 -#define SCSI_SENSE_DATA_PROTECT 0x07 -#define SCSI_SENSE_FIRMWARE_ERROR 0x08 -#define SCSI_SENSE_ABORTED_COMMAND 0x0b -#define SCSI_SENSE_EQUAL 0x0c -#define SCSI_SENSE_VOLUME_OVERFLOW 0x0d -#define SCSI_SENSE_MISCOMPARE 0x0e - -/* Additional Sense Code */ -#define SCSI_ASC_INVALID_CDB 0x20U -#define SCSI_ASC_INVALID_FIELED_IN_COMMAND 0x24U -#define SCSI_ASC_PARAMETER_LIST_LENGTH_ERROR 0x1AU -#define SCSI_ASC_INVALID_FIELD_IN_PARAMETER_LIST 0x26U -#define SCSI_ASC_ADDRESS_OUT_OF_RANGE 0x21U -#define SCSI_ASC_MEDIUM_NOT_PRESENT 0x3AU -#define SCSI_ASC_MEDIUM_HAVE_CHANGED 0x28U -#define SCSI_ASC_WRITE_PROTECTED 0x27U -#define SCSI_ASC_UNRECOVERED_READ_ERROR 0x11U -#define SCSI_ASC_WRITE_FAULT 0x03U - -#define READ_FORMAT_CAPACITY_DATA_LEN 0x0CU -#define READ_CAPACITY10_DATA_LEN 0x08U -#define REQUEST_SENSE_DATA_LEN 0x12U -#define STANDARD_INQUIRY_DATA_LEN 0x24U -#define MODE_SENSE6_DATA_LEN 0x17U -#define MODE_SENSE10_DATA_LEN 0x1BU - -#define SCSI_MEDIUM_STATUS_UNLOCKED 0x00U -#define SCSI_MEDIUM_STATUS_LOCKED 0x01U -#define SCSI_MEDIUM_STATUS_EJECTED 0x02U - -//--------------------------------------------------------------------+ -// SCSI Primary Command (SPC-4) -//--------------------------------------------------------------------+ - -/// SCSI Test Unit Ready Command -typedef struct __packed { - uint8_t cmd_code; ///< SCSI OpCode for \ref SCSI_CMD_TEST_UNIT_READY - uint8_t lun; ///< Logical Unit - uint8_t reserved[3]; - uint8_t control; -} scsi_test_unit_ready_cmd_t; - -/// SCSI Inquiry Command -typedef struct __packed { - uint8_t cmd_code; ///< SCSI OpCode for \ref SCSI_CMD_INQUIRY - uint8_t reserved1; - uint8_t page_code; - uint8_t reserved2; - uint8_t alloc_length; ///< specifies the maximum number of bytes that USB host has allocated in the Data-In Buffer. An allocation length of zero specifies that no data shall be transferred. - uint8_t control; -} scsi_inquiry_cmd_t, scsi_request_sense_cmd_t; - -/// SCSI Inquiry Response Data -typedef struct __packed { - uint8_t peripheral_device_type : 5; - uint8_t peripheral_qualifier : 3; - - uint8_t : 7; - uint8_t is_removable : 1; - - uint8_t version; - - uint8_t response_data_format : 4; - uint8_t hierarchical_support : 1; - uint8_t normal_aca : 1; - uint8_t : 2; - - uint8_t additional_length; - - uint8_t protect : 1; - uint8_t : 2; - uint8_t third_party_copy : 1; - uint8_t target_port_group_support : 2; - uint8_t access_control_coordinator : 1; - uint8_t scc_support : 1; - - uint8_t addr16 : 1; - uint8_t : 3; - uint8_t multi_port : 1; - uint8_t : 1; // vendor specific - uint8_t enclosure_service : 1; - uint8_t : 1; - - uint8_t : 1; // vendor specific - uint8_t cmd_que : 1; - uint8_t : 2; - uint8_t sync : 1; - uint8_t wbus16 : 1; - uint8_t : 2; - - uint8_t vendor_id[8]; ///< 8 bytes of ASCII data identifying the vendor of the product. - uint8_t product_id[16]; ///< 16 bytes of ASCII data defined by the vendor. - uint8_t product_rev[4]; ///< 4 bytes of ASCII data defined by the vendor. -} scsi_inquiry_resp_t; - -typedef struct __packed { - uint8_t response_code : 7; ///< 70h - current errors, Fixed Format 71h - deferred errors, Fixed Format - uint8_t valid : 1; - - uint8_t reserved; - - uint8_t sense_key : 4; - uint8_t : 1; - uint8_t ili : 1; ///< Incorrect length indicator - uint8_t end_of_medium : 1; - uint8_t filemark : 1; - - uint32_t information; - uint8_t add_sense_len; - uint32_t command_specific_info; - uint8_t add_sense_code; - uint8_t add_sense_qualifier; - uint8_t field_replaceable_unit_code; - - uint8_t sense_key_specific[3]; ///< sense key specific valid bit is bit 7 of key[0], aka MSB in Big Endian layout - -} scsi_sense_fixed_resp_t; - -typedef struct __packed { - uint8_t cmd_code; ///< SCSI OpCode for \ref SCSI_CMD_MODE_SENSE_6 - - uint8_t : 3; - uint8_t disable_block_descriptor : 1; - uint8_t : 4; - - uint8_t page_code : 6; - uint8_t page_control : 2; - - uint8_t subpage_code; - uint8_t alloc_length; - uint8_t control; -} scsi_mode_sense6_cmd_t; - -// This is only a Mode parameter header(6). -typedef struct __packed { - uint8_t data_len; - uint8_t medium_type; - - uint8_t reserved : 7; - bool write_protected : 1; - - uint8_t block_descriptor_len; -} scsi_mode_sense6_resp_t; - -typedef struct -{ - uint8_t cmd_code; - - uint8_t reserved1 : 3; - uint8_t disable_block_descriptor : 1; - uint8_t long_LBA : 1; - uint8_t reserved2 : 3; - - uint8_t page_code : 6; - uint8_t page_control : 2; - - uint8_t subpage_code; - - uint8_t reserved3; - uint8_t reserved4; - uint8_t reserved5; - - uint8_t length[2]; - - uint8_t control; -} scsi_mode_sense_10_cmd_t; - -typedef struct -{ - uint8_t mode_data_length_high; - uint8_t mode_data_length_low; - uint8_t medium_type; - - uint8_t reserved1 : 4; - uint8_t DPO_FUA : 1; /**< [Disable Page Out] and [Force Unit Access] in the SCSI_READ10 command is valid or not */ - uint8_t reserved2 : 2; - uint8_t write_protect : 1; - - uint8_t long_LBA : 1; - uint8_t reserved3 : 7; - - uint8_t reserved4; - uint8_t block_desc_length[2]; -} scsi_mode_10_resp_t; - -typedef struct __packed { - uint8_t cmd_code; ///< SCSI OpCode for \ref SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL - uint8_t reserved[3]; - uint8_t prohibit_removal; - uint8_t control; -} scsi_prevent_allow_medium_removal_t; - -typedef struct __packed { - uint8_t cmd_code; - - uint8_t immded : 1; - uint8_t : 7; - - uint8_t TU_RESERVED; - - uint8_t power_condition_mod : 4; - uint8_t : 4; - - uint8_t start : 1; - uint8_t load_eject : 1; - uint8_t no_flush : 1; - uint8_t : 1; - uint8_t power_condition : 4; - - uint8_t control; -} scsi_start_stop_unit_cmd_t; - -//--------------------------------------------------------------------+ -// SCSI MMC -//--------------------------------------------------------------------+ -/// SCSI Read Format Capacity: Write Capacity -typedef struct __packed { - uint8_t cmd_code; - uint8_t reserved[6]; - uint16_t alloc_length; - uint8_t control; -} scsi_read_format_capacity_cmd_t; - -typedef struct __packed { - uint8_t reserved[3]; - uint8_t list_length; /// must be 8*n, length in bytes of formattable capacity descriptor followed it. - - uint32_t block_num; /// Number of Logical Blocks - uint8_t descriptor_type; // 00: reserved, 01 unformatted media , 10 Formatted media, 11 No media present - - uint8_t reserved2; - uint16_t block_size_u16; - -} scsi_read_format_capacity_resp_t; - -//--------------------------------------------------------------------+ -// SCSI Block Command (SBC-3) -// NOTE: All data in SCSI command are in Big Endian -//--------------------------------------------------------------------+ - -/// SCSI Read Capacity 10 Command: Read Capacity -typedef struct __packed { - uint8_t cmd_code; ///< SCSI OpCode for \ref SCSI_CMD_READ_CAPACITY_10 - uint8_t reserved1; - uint32_t lba; ///< The first Logical Block Address (LBA) accessed by this command - uint16_t reserved2; - uint8_t partial_medium_indicator; - uint8_t control; -} scsi_read_capacity10_cmd_t; - -/// SCSI Read Capacity 10 Response Data -typedef struct -{ - uint32_t last_lba; ///< The last Logical Block Address of the device - uint32_t block_size; ///< Block size in bytes -} scsi_read_capacity10_resp_t; - -/// SCSI Read 10 Command -typedef struct __packed { - uint8_t cmd_code; ///< SCSI OpCode - uint8_t reserved; // has LUN according to wiki - uint32_t lba; ///< The first Logical Block Address (LBA) accessed by this command - uint8_t reserved2; - uint16_t block_count; ///< Number of Blocks used by this command - uint8_t control; -} scsi_read10_t, scsi_write10_t, scsi_read_write_10_t; - -#endif /* ZEPHYR_INCLUDE_USB_CLASS_USB_CDC_H_ */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.c deleted file mode 100644 index 7e09da0b52..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.c +++ /dev/null @@ -1,131 +0,0 @@ -/** - * @file usbd_video.c - * - * Copyright (c) 2021 Bouffalolab team - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - */ -#include "usbd_video.h" -#include "usbd_core.h" - -extern struct video_probe_and_commit_controls probe; -extern struct video_probe_and_commit_controls commit; - -int video_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) { - USBD_LOG_DBG("Video Class request: " - "bRequest 0x%02x\r\n", - setup->bRequest); - - switch (setup->bRequest) { - case VIDEO_REQUEST_SET_CUR: - if (setup->wValue == 256) { - memcpy((uint8_t *)&probe, *data, setup->wLength); - } else if (setup->wValue == 512) { - memcpy((uint8_t *)&commit, *data, setup->wLength); - } - - break; - - case VIDEO_REQUEST_GET_CUR: - if (setup->wValue == 256) { - *data = (uint8_t *)&probe; - } else if (setup->wValue == 512) { - *data = (uint8_t *)&commit; - } - - break; - - case VIDEO_REQUEST_GET_MIN: - if (setup->wValue == 256) { - *data = (uint8_t *)&probe; - } else if (setup->wValue == 512) { - *data = (uint8_t *)&commit; - } - - break; - - case VIDEO_REQUEST_GET_MAX: - if (setup->wValue == 256) { - *data = (uint8_t *)&probe; - } else if (setup->wValue == 512) { - *data = (uint8_t *)&commit; - } - - break; - - case VIDEO_REQUEST_GET_RES: - - break; - - case VIDEO_REQUEST_GET_LEN: - - break; - - case VIDEO_REQUEST_GET_INFO: - - break; - - case VIDEO_REQUEST_GET_DEF: - if (setup->wLength == 256) { - *data = (uint8_t *)&probe; - } else if (setup->wLength == 512) { - *data = (uint8_t *)&commit; - } - - break; - - default: - USBD_LOG_WRN("Unhandled Video Class bRequest 0x%02x\r\n", setup->bRequest); - return -1; - } - - return 0; -} - -void video_notify_handler(uint8_t event, void *arg) { - switch (event) { - case USB_EVENT_RESET: - - break; - - case USB_EVENT_SOF: - usbd_video_sof_callback(); - break; - - case USB_EVENT_SET_INTERFACE: - usbd_video_set_interface_callback(((uint8_t *)arg)[3]); - break; - - default: - break; - } -} - -void usbd_video_add_interface(usbd_class_t *class, usbd_interface_t *intf) { - static usbd_class_t *last_class = NULL; - - if (last_class != class) { - last_class = class; - usbd_class_register(class); - } - - intf->class_handler = video_class_request_handler; - intf->custom_handler = NULL; - intf->vendor_handler = NULL; - intf->notify_handler = video_notify_handler; - usbd_class_add_interface(class, intf); -} \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.h deleted file mode 100644 index 09c452f5f7..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.h +++ /dev/null @@ -1,821 +0,0 @@ -/** - * @file - * @brief USB Video Device Class public header - * - * Header follows below documentation: - * - USB Device Class Definition for Video Devices UVC 1.5 Class specification.pdf - */ - -#ifndef _USBD_VIDEO_H_ -#define _USBD_VIDEO_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#define USB_DEVICE_VIDEO_CLASS_VERSION_1_5 0 - -/*! @brief Video device subclass code */ -#define VIDEO_SC_UNDEFINED 0x00U -#define VIDEO_SC_VIDEOCONTROL 0x01U -#define VIDEO_SC_VIDEOSTREAMING 0x02U -#define VIDEO_SC_VIDEO_INTERFACE_COLLECTION 0x03U - -/*! @brief Video device protocol code */ -#define VIDEO_PC_PROTOCOL_UNDEFINED 0x00U -#define VIDEO_PC_PROTOCOL_15 0x01U - -/*! @brief Video device class-specific descriptor type */ -#define VIDEO_CS_UNDEFINED_DESCRIPTOR_TYPE 0x20U -#define VIDEO_CS_DEVICE_DESCRIPTOR_TYPE 0x21U -#define VIDEO_CS_CONFIGURATION_DESCRIPTOR_TYPE 0x22U -#define VIDEO_CS_STRING_DESCRIPTOR_TYPE 0x23U -#define VIDEO_CS_INTERFACE_DESCRIPTOR_TYPE 0x24U -#define VIDEO_CS_ENDPOINT_DESCRIPTOR_TYPE 0x25U - -/*! @brief Video device class-specific VC interface descriptor subtype */ -#define VIDEO_VC_DESCRIPTOR_UNDEFINED_DESCRIPTOR_SUBTYPE 0x00U -#define VIDEO_VC_HEADER_DESCRIPTOR_SUBTYPE 0x01U -#define VIDEO_VC_INPUT_TERMINAL_DESCRIPTOR_SUBTYPE 0x02U -#define VIDEO_VC_OUTPUT_TERMINAL_DESCRIPTOR_SUBTYPE 0x03U -#define VIDEO_VC_SELECTOR_UNIT_DESCRIPTOR_SUBTYPE 0x04U -#define VIDEO_VC_PROCESSING_UNIT_DESCRIPTOR_SUBTYPE 0x05U -#define VIDEO_VC_EXTENSION_UNIT_DESCRIPTOR_SUBTYPE 0x06U -#define VIDEO_VC_ENCODING_UNIT_DESCRIPTOR_SUBTYPE 0x07U - -/*! @brief Video device class-specific VS interface descriptor subtype */ -#define VIDEO_VS_UNDEFINED_DESCRIPTOR_SUBTYPE 0x00U -#define VIDEO_VS_INPUT_HEADER_DESCRIPTOR_SUBTYPE 0x01U -#define VIDEO_VS_OUTPUT_HEADER_DESCRIPTOR_SUBTYPE 0x02U -#define VIDEO_VS_STILL_IMAGE_FRAME_DESCRIPTOR_SUBTYPE 0x03U -#define VIDEO_VS_FORMAT_UNCOMPRESSED_DESCRIPTOR_SUBTYPE 0x04U -#define VIDEO_VS_FRAME_UNCOMPRESSED_DESCRIPTOR_SUBTYPE 0x05U -#define VIDEO_VS_FORMAT_MJPEG_DESCRIPTOR_SUBTYPE 0x06U -#define VIDEO_VS_FRAME_MJPEG_DESCRIPTOR_SUBTYPE 0x07U -#define VIDEO_VS_FORMAT_MPEG2TS_DESCRIPTOR_SUBTYPE 0x0AU -#define VIDEO_VS_FORMAT_DV_DESCRIPTOR_SUBTYPE 0x0CU -#define VIDEO_VS_COLORFORMAT_DESCRIPTOR_SUBTYPE 0x0DU -#define VIDEO_VS_FORMAT_FRAME_BASED_DESCRIPTOR_SUBTYPE 0x10U -#define VIDEO_VS_FRAME_FRAME_BASED_DESCRIPTOR_SUBTYPE 0x11U -#define VIDEO_VS_FORMAT_STREAM_BASED_DESCRIPTOR_SUBTYPE 0x12U -#define VIDEO_VS_FORMAT_H264_DESCRIPTOR_SUBTYPE 0x13U -#define VIDEO_VS_FRAME_H264_DESCRIPTOR_SUBTYPE 0x14U -#define VIDEO_VS_FORMAT_H264_SIMULCAST_DESCRIPTOR_SUBTYPE 0x15U -#define VIDEO_VS_FORMAT_VP8_DESCRIPTOR_SUBTYPE 0x16U -#define VIDEO_VS_FRAME_VP8_DESCRIPTOR_SUBTYPE 0x17U -#define VIDEO_VS_FORMAT_VP8_SIMULCAST_DESCRIPTOR_SUBTYPE 0x18U - -/*! @brief Video device class-specific VC endpoint descriptor subtype */ -#define VIDEO_EP_UNDEFINED_DESCRIPTOR_SUBTYPE 0x00U -#define VIDEO_EP_GENERAL_DESCRIPTOR_SUBTYPE 0x01U -#define VIDEO_EP_ENDPOINT_DESCRIPTOR_SUBTYPE 0x02U -#define VIDEO_EP_INTERRUPT_DESCRIPTOR_SUBTYPE 0x03U - -/*! @brief Video device class-specific request code */ -#define VIDEO_REQUEST_UNDEFINED 0x00U -#define VIDEO_REQUEST_SET_CUR 0x01U -#define VIDEO_REQUEST_SET_CUR_ALL 0x11U -#define VIDEO_REQUEST_GET_CUR 0x81U -#define VIDEO_REQUEST_GET_MIN 0x82U -#define VIDEO_REQUEST_GET_MAX 0x83U -#define VIDEO_REQUEST_GET_RES 0x84U -#define VIDEO_REQUEST_GET_LEN 0x85U -#define VIDEO_REQUEST_GET_INFO 0x86U -#define VIDEO_REQUEST_GET_DEF 0x87U -#define VIDEO_REQUEST_GET_CUR_ALL 0x91U -#define VIDEO_REQUEST_GET_MIN_ALL 0x92U -#define VIDEO_REQUEST_GET_MAX_ALL 0x93U -#define VIDEO_REQUEST_GET_RES_ALL 0x94U -#define VIDEO_REQUEST_GET_DEF_ALL 0x97U - -/*! @brief Video device class-specific VideoControl interface control selector */ -#define VIDEO_VC_CONTROL_UNDEFINED 0x00U -#define VIDEO_VC_VIDEO_POWER_MODE_CONTROL 0x01U -#define VIDEO_VC_REQUEST_ERROR_CODE_CONTROL 0x02U - -/*! @brief Video device class-specific Terminal control selector */ -#define VIDEO_TE_CONTROL_UNDEFINED 0x00U - -/*! @brief Video device class-specific Selector Unit control selector */ -#define VIDEO_SU_CONTROL_UNDEFINED 0x00U -#define VIDEO_SU_INPUT_SELECT_CONTROL 0x01U - -/*! @brief Video device class-specific Camera Terminal control selector */ -#define VIDEO_CT_CONTROL_UNDEFINED 0x00U -#define VIDEO_CT_SCANNING_MODE_CONTROL 0x01U -#define VIDEO_CT_AE_MODE_CONTROL 0x02U -#define VIDEO_CT_AE_PRIORITY_CONTROL 0x03U -#define VIDEO_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x04U -#define VIDEO_CT_EXPOSURE_TIME_RELATIVE_CONTROL 0x05U -#define VIDEO_CT_FOCUS_ABSOLUTE_CONTROL 0x06U -#define VIDEO_CT_FOCUS_RELATIVE_CONTROL 0x07U -#define VIDEO_CT_FOCUS_AUTO_CONTROL 0x08U -#define VIDEO_CT_IRIS_ABSOLUTE_CONTROL 0x09U -#define VIDEO_CT_IRIS_RELATIVE_CONTROL 0x0AU -#define VIDEO_CT_ZOOM_ABSOLUTE_CONTROL 0x0BU -#define VIDEO_CT_ZOOM_RELATIVE_CONTROL 0x0CU -#define VIDEO_CT_PANTILT_ABSOLUTE_CONTROL 0x0DU -#define VIDEO_CT_PANTILT_RELATIVE_CONTROL 0x0EU -#define VIDEO_CT_ROLL_ABSOLUTE_CONTROL 0x0FU -#define VIDEO_CT_ROLL_RELATIVE_CONTROL 0x10U -#define VIDEO_CT_PRIVACY_CONTROL 0x11U -#define VIDEO_CT_FOCUS_SIMPLE_CONTROL 0x12U -#define VIDEO_CT_WINDOW_CONTROL 0x13U -#define VIDEO_CT_REGION_OF_INTEREST_CONTROL 0x14U - -/*! @brief Video device class-specific Processing Unit control selector */ -#define VIDEO_PU_CONTROL_UNDEFINED 0x00U -#define VIDEO_PU_BACKLIGHT_COMPENSATION_CONTROL 0x01U -#define VIDEO_PU_BRIGHTNESS_CONTROL 0x02U -#define VIDEO_PU_CONTRAST_CONTROL 0x03U -#define VIDEO_PU_GAIN_CONTROL 0x04U -#define VIDEO_PU_POWER_LINE_FREQUENCY_CONTROL 0x05U -#define VIDEO_PU_HUE_CONTROL 0x06U -#define VIDEO_PU_SATURATION_CONTROL 0x07U -#define VIDEO_PU_SHARPNESS_CONTROL 0x08U -#define VIDEO_PU_GAMMA_CONTROL 0x09U -#define VIDEO_PU_WHITE_BALANCE_TEMPERATURE_CONTROL 0x0AU -#define VIDEO_PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 0x0BU -#define VIDEO_PU_WHITE_BALANCE_COMPONENT_CONTROL 0x0CU -#define VIDEO_PU_WHITE_BALANCE_COMPONENT_AUTO_CONTROL 0x0DU -#define VIDEO_PU_DIGITAL_MULTIPLIER_CONTROL 0x0EU -#define VIDEO_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL 0x0FU -#define VIDEO_PU_HUE_AUTO_CONTROL 0x10U -#define VIDEO_PU_ANALOG_VIDEO_STANDARD_CONTROL 0x11U -#define VIDEO_PU_ANALOG_LOCK_STATUS_CONTROL 0x12U -#define VIDEO_PU_CONTRAST_AUTO_CONTROL 0x13U - -/*! @brief Video device class-specific Encoding Unit control selector */ -#define VIDEO_EU_CONTROL_UNDEFINED 0x00U -#define VIDEO_EU_SELECT_LAYER_CONTROL 0x01U -#define VIDEO_EU_PROFILE_TOOLSET_CONTROL 0x02U -#define VIDEO_EU_VIDEO_RESOLUTION_CONTROL 0x03U -#define VIDEO_EU_MIN_FRAME_INTERVAL_CONTROL 0x04U -#define VIDEO_EU_SLICE_MODE_CONTROL 0x05U -#define VIDEO_EU_RATE_CONTROL_MODE_CONTROL 0x06U -#define VIDEO_EU_AVERAGE_BITRATE_CONTROL 0x07U -#define VIDEO_EU_CPB_SIZE_CONTROL 0x08U -#define VIDEO_EU_PEAK_BIT_RATE_CONTROL 0x09U -#define VIDEO_EU_QUANTIZATION_PARAMS_CONTROL 0x0AU -#define VIDEO_EU_SYNC_REF_FRAME_CONTROL 0x0BU -#define VIDEO_EU_LTR_BUFFER_ CONTROL0x0CU -#define VIDEO_EU_LTR_PICTURE_CONTROL 0x0DU -#define VIDEO_EU_LTR_VALIDATION_CONTROL 0x0EU -#define VIDEO_EU_LEVEL_IDC_LIMIT_CONTROL 0x0FU -#define VIDEO_EU_SEI_PAYLOADTYPE_CONTROL 0x10U -#define VIDEO_EU_QP_RANGE_CONTROL 0x11U -#define VIDEO_EU_PRIORITY_CONTROL 0x12U -#define VIDEO_EU_START_OR_STOP_LAYER_CONTROL 0x13U -#define VIDEO_EU_ERROR_RESILIENCY_CONTROL 0x14U - -/*! @brief Video device class-specific Extension Unit control selector */ -#define VIDEO_XU_CONTROL_UNDEFINED 0x00U - -/*! @brief Video device class-specific VideoStreaming Interface control selector */ -#define VIDEO_VS_CONTROL_UNDEFINED 0x00U -#define VIDEO_VS_PROBE_CONTROL 0x01U -#define VIDEO_VS_COMMIT_CONTROL 0x02U -#define VIDEO_VS_STILL_PROBE_CONTROL 0x03U -#define VIDEO_VS_STILL_COMMIT_CONTROL 0x04U -#define VIDEO_VS_STILL_IMAGE_TRIGGER_CONTROL 0x05U -#define VIDEO_VS_STREAM_ERROR_CODE_CONTROL 0x06U -#define VIDEO_VS_GENERATE_KEY_FRAME_CONTROL 0x07U -#define VIDEO_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x08U -#define VIDEO_VS_SYNCH_DELAY_CONTROL 0x09U - -/*! @}*/ - -/*! - * @name USB Video class terminal types - * @{ - */ - -/*! @brief Video device USB terminal type */ -#define VIDEO_TT_VENDOR_SPECIFIC 0x0100U -#define VIDEO_TT_STREAMING 0x0101U - -/*! @brief Video device input terminal type */ -#define VIDEO_ITT_VENDOR_SPECIFIC 0x0200U -#define VIDEO_ITT_CAMERA 0x0201U -#define VIDEO_ITT_MEDIA_TRANSPORT_INPUT 0x0202U - -/*! @brief Video device output terminal type */ -#define VIDEO_OTT_VENDOR_SPECIFIC 0x0300U -#define VIDEO_OTT_DISPLAY 0x0301U -#define VIDEO_OTT_MEDIA_TRANSPORT_OUTPUT 0x0302U - -/*! @brief Video device external terminal type */ -#define VIDEO_ET_VENDOR_SPECIFIC 0x0400U -#define VIDEO_ET_COMPOSITE_CONNECTOR 0x0401U -#define VIDEO_ET_SVIDEO_CONNECTOR 0x0402U -#define VIDEO_ET_COMPONENT_CONNECTOR 0x0403U - -/*! @}*/ - -/*! - * @name USB Video class setup request types - * @{ - */ - -/*! @brief Video device class setup request set type */ -#define VIDEO_SET_REQUEST_INTERFACE 0x21U -#define VIDEO_SET_REQUEST_ENDPOINT 0x22U - -/*! @brief Video device class setup request get type */ -#define VIDEO_GET_REQUEST_INTERFACE 0xA1U -#define VIDEO_GET_REQUEST_ENDPOINT 0xA2U - -/*! @}*/ - -/*! @brief Video device still image trigger control */ -#define VIDEO_STILL_IMAGE_TRIGGER_NORMAL_OPERATION 0x00U -#define VIDEO_STILL_IMAGE_TRIGGER_TRANSMIT_STILL_IMAGE 0x01U -#define VIDEO_STILL_IMAGE_TRIGGER_TRANSMIT_STILL_IMAGE_VS_DEDICATED_BULK_PIPE 0x02U -#define VIDEO_STILL_IMAGE_TRIGGER_ABORT_STILL_IMAGE_TRANSMISSION 0x03U - -/*! - * @name USB Video device class-specific request commands - * @{ - */ - -/*! @brief Video device class-specific request GET CUR COMMAND */ -#define VIDEO_GET_CUR_VC_POWER_MODE_CONTROL 0x8101U -#define VIDEO_GET_CUR_VC_ERROR_CODE_CONTROL 0x8102U - -#define VIDEO_GET_CUR_PU_BACKLIGHT_COMPENSATION_CONTROL 0x8121U -#define VIDEO_GET_CUR_PU_BRIGHTNESS_CONTROL 0x8122U -#define VIDEO_GET_CUR_PU_CONTRACT_CONTROL 0x8123U -#define VIDEO_GET_CUR_PU_GAIN_CONTROL 0x8124U -#define VIDEO_GET_CUR_PU_POWER_LINE_FREQUENCY_CONTROL 0x8125U -#define VIDEO_GET_CUR_PU_HUE_CONTROL 0x8126U -#define VIDEO_GET_CUR_PU_SATURATION_CONTROL 0x8127U -#define VIDEO_GET_CUR_PU_SHARRNESS_CONTROL 0x8128U -#define VIDEO_GET_CUR_PU_GAMMA_CONTROL 0x8129U -#define VIDEO_GET_CUR_PU_WHITE_BALANCE_TEMPERATURE_CONTROL 0x812AU -#define VIDEO_GET_CUR_PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 0x812BU -#define VIDEO_GET_CUR_PU_WHITE_BALANCE_COMPONENT_CONTROL 0x812CU -#define VIDEO_GET_CUR_PU_WHITE_BALANCE_COMPONENT_AUTO_CONTROL 0x812DU -#define VIDEO_GET_CUR_PU_DIGITAL_MULTIPLIER_CONTROL 0x812EU -#define VIDEO_GET_CUR_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL 0x812FU -#define VIDEO_GET_CUR_PU_HUE_AUTO_CONTROL 0x8130U -#define VIDEO_GET_CUR_PU_ANALOG_VIDEO_STANDARD_CONTROL 0x8131U -#define VIDEO_GET_CUR_PU_ANALOG_LOCK_STATUS_CONTROL 0x8132U -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_GET_CUR_PU_CONTRAST_AUTO_CONTROL 0x8133U -#endif - -#define VIDEO_GET_CUR_CT_SCANNING_MODE_CONTROL 0x8141U -#define VIDEO_GET_CUR_CT_AE_MODE_CONTROL 0x8142U -#define VIDEO_GET_CUR_CT_AE_PRIORITY_CONTROL 0x8143U -#define VIDEO_GET_CUR_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x8144U -#define VIDEO_GET_CUR_CT_EXPOSURE_TIME_RELATIVE_CONTROL 0x8145U -#define VIDEO_GET_CUR_CT_FOCUS_ABSOLUTE_CONTROL 0x8146U -#define VIDEO_GET_CUR_CT_FOCUS_RELATIVE_CONTROL 0x8147U -#define VIDEO_GET_CUR_CT_FOCUS_AUTO_CONTROL 0x8148U -#define VIDEO_GET_CUR_CT_IRIS_ABSOLUTE_CONTROL 0x8149U -#define VIDEO_GET_CUR_CT_IRIS_RELATIVE_CONTROL 0x814AU -#define VIDEO_GET_CUR_CT_ZOOM_ABSOLUTE_CONTROL 0x814BU -#define VIDEO_GET_CUR_CT_ZOOM_RELATIVE_CONTROL 0x814CU -#define VIDEO_GET_CUR_CT_PANTILT_ABSOLUTE_CONTROL 0x814DU -#define VIDEO_GET_CUR_CT_PANTILT_RELATIVE_CONTROL 0x814EU -#define VIDEO_GET_CUR_CT_ROLL_ABSOLUTE_CONTROL 0x814FU -#define VIDEO_GET_CUR_CT_ROLL_RELATIVE_CONTROL 0x8150U -#define VIDEO_GET_CUR_CT_PRIVACY_CONTROL 0x8151U -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_GET_CUR_CT_FOCUS_SIMPLE_CONTROL 0x8152U -#define VIDEO_GET_CUR_CT_DIGITAL_WINDOW_CONTROL 0x8153U -#define VIDEO_GET_CUR_CT_REGION_OF_INTEREST_CONTROL 0x8154U -#endif - -#define VIDEO_GET_CUR_VS_PROBE_CONTROL 0x8161U -#define VIDEO_GET_CUR_VS_COMMIT_CONTROL 0x8162U -#define VIDEO_GET_CUR_VS_STILL_PROBE_CONTROL 0x8163U -#define VIDEO_GET_CUR_VS_STILL_COMMIT_CONTROL 0x8164U -#define VIDEO_GET_CUR_VS_STILL_IMAGE_TRIGGER_CONTROL 0x8165U -#define VIDEO_GET_CUR_VS_STREAM_ERROR_CODE_CONTROL 0x8166U -#define VIDEO_GET_CUR_VS_GENERATE_KEY_FRAME_CONTROL 0x8167U -#define VIDEO_GET_CUR_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x8168U -#define VIDEO_GET_CUR_VS_SYNCH_DELAY_CONTROL 0x8169U - -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_GET_CUR_EU_SELECT_LAYER_CONTROL 0x8181U -#define VIDEO_GET_CUR_EU_PROFILE_TOOLSET_CONTROL 0x8182U -#define VIDEO_GET_CUR_EU_VIDEO_RESOLUTION_CONTROL 0x8183U -#define VIDEO_GET_CUR_EU_MIN_FRAME_INTERVAL_CONTROL 0x8184U -#define VIDEO_GET_CUR_EU_SLICE_MODE_CONTROL 0x8185U -#define VIDEO_GET_CUR_EU_RATE_CONTROL_MODE_CONTROL 0x8186U -#define VIDEO_GET_CUR_EU_AVERAGE_BITRATE_CONTROL 0x8187U -#define VIDEO_GET_CUR_EU_CPB_SIZE_CONTROL 0x8188U -#define VIDEO_GET_CUR_EU_PEAK_BIT_RATE_CONTROL 0x8189U -#define VIDEO_GET_CUR_EU_QUANTIZATION_PARAMS_CONTROL 0x818AU -#define VIDEO_GET_CUR_EU_SYNC_REF_FRAME_CONTROL 0x818BU -#define VIDEO_GET_CUR_EU_LTR_BUFFER_CONTROL 0x818CU -#define VIDEO_GET_CUR_EU_LTR_PICTURE_CONTROL 0x818DU -#define VIDEO_GET_CUR_EU_LTR_VALIDATION_CONTROL 0x818EU -#define VIDEO_GET_CUR_EU_LEVEL_IDC_LIMIT_CONTROL 0x818FU -#define VIDEO_GET_CUR_EU_SEI_PAYLOADTYPE_CONTROL 0x8190U -#define VIDEO_GET_CUR_EU_QP_RANGE_CONTROL 0x8191U -#define VIDEO_GET_CUR_EU_PRIORITY_CONTROL 0x8192U -#define VIDEO_GET_CUR_EU_START_OR_STOP_LAYER_CONTROL 0x8193U -#define VIDEO_GET_CUR_EU_ERROR_RESILIENCY_CONTROL 0x8194U -#endif - -/*! @brief Video device class-specific request GET MIN COMMAND */ -#define VIDEO_GET_MIN_PU_BACKLIGHT_COMPENSATION_CONTROL 0x8221U -#define VIDEO_GET_MIN_PU_BRIGHTNESS_CONTROL 0x8222U -#define VIDEO_GET_MIN_PU_CONTRACT_CONTROL 0x8223U -#define VIDEO_GET_MIN_PU_GAIN_CONTROL 0x8224U -#define VIDEO_GET_MIN_PU_HUE_CONTROL 0x8226U -#define VIDEO_GET_MIN_PU_SATURATION_CONTROL 0x8227U -#define VIDEO_GET_MIN_PU_SHARRNESS_CONTROL 0x8228U -#define VIDEO_GET_MIN_PU_GAMMA_CONTROL 0x8229U -#define VIDEO_GET_MIN_PU_WHITE_BALANCE_TEMPERATURE_CONTROL 0x822AU -#define VIDEO_GET_MIN_PU_WHITE_BALANCE_COMPONENT_CONTROL 0x822CU -#define VIDEO_GET_MIN_PU_DIGITAL_MULTIPLIER_CONTROL 0x822EU -#define VIDEO_GET_MIN_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL 0x822FU - -#define VIDEO_GET_MIN_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x8244U -#define VIDEO_GET_MIN_CT_FOCUS_ABSOLUTE_CONTROL 0x8246U -#define VIDEO_GET_MIN_CT_FOCUS_RELATIVE_CONTROL 0x8247U -#define VIDEO_GET_MIN_CT_IRIS_ABSOLUTE_CONTROL 0x8249U -#define VIDEO_GET_MIN_CT_ZOOM_ABSOLUTE_CONTROL 0x824BU -#define VIDEO_GET_MIN_CT_ZOOM_RELATIVE_CONTROL 0x824CU -#define VIDEO_GET_MIN_CT_PANTILT_ABSOLUTE_CONTROL 0x824DU -#define VIDEO_GET_MIN_CT_PANTILT_RELATIVE_CONTROL 0x824EU -#define VIDEO_GET_MIN_CT_ROLL_ABSOLUTE_CONTROL 0x824FU -#define VIDEO_GET_MIN_CT_ROLL_RELATIVE_CONTROL 0x8250U -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_GET_MIN_CT_DIGITAL_WINDOW_CONTROL 0x8251U -#define VIDEO_GET_MIN_CT_REGION_OF_INTEREST_CONTROL 0x8252U -#endif - -#define VIDEO_GET_MIN_VS_PROBE_CONTROL 0x8261U -#define VIDEO_GET_MIN_VS_STILL_PROBE_CONTROL 0x8263U -#define VIDEO_GET_MIN_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x8268U -#define VIDEO_GET_MIN_VS_SYNCH_DELAY_CONTROL 0x8269U - -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_GET_MIN_EU_VIDEO_RESOLUTION_CONTROL 0x8283U -#define VIDEO_GET_MIN_EU_MIN_FRAME_INTERVAL_CONTROL 0x8284U -#define VIDEO_GET_MIN_EU_SLICE_MODE_CONTROL 0x8285U -#define VIDEO_GET_MIN_EU_AVERAGE_BITRATE_CONTROL 0x8287U -#define VIDEO_GET_MIN_EU_CPB_SIZE_CONTROL 0x8288U -#define VIDEO_GET_MIN_EU_PEAK_BIT_RATE_CONTROL 0x8289U -#define VIDEO_GET_MIN_EU_QUANTIZATION_PARAMS_CONTROL 0x828AU -#define VIDEO_GET_MIN_EU_SYNC_REF_FRAME_CONTROL 0x828BU -#define VIDEO_GET_MIN_EU_LEVEL_IDC_LIMIT_CONTROL 0x828FU -#define VIDEO_GET_MIN_EU_SEI_PAYLOADTYPE_CONTROL 0x8290U -#define VIDEO_GET_MIN_EU_QP_RANGE_CONTROL 0x8291U -#endif - -/*! @brief Video device class-specific request GET MAX COMMAND */ -#define VIDEO_GET_MAX_PU_BACKLIGHT_COMPENSATION_CONTROL 0x8321U -#define VIDEO_GET_MAX_PU_BRIGHTNESS_CONTROL 0x8322U -#define VIDEO_GET_MAX_PU_CONTRACT_CONTROL 0x8323U -#define VIDEO_GET_MAX_PU_GAIN_CONTROL 0x8324U -#define VIDEO_GET_MAX_PU_HUE_CONTROL 0x8326U -#define VIDEO_GET_MAX_PU_SATURATION_CONTROL 0x8327U -#define VIDEO_GET_MAX_PU_SHARRNESS_CONTROL 0x8328U -#define VIDEO_GET_MAX_PU_GAMMA_CONTROL 0x8329U -#define VIDEO_GET_MAX_PU_WHITE_BALANCE_TEMPERATURE_CONTROL 0x832AU -#define VIDEO_GET_MAX_PU_WHITE_BALANCE_COMPONENT_CONTROL 0x832CU -#define VIDEO_GET_MAX_PU_DIGITAL_MULTIPLIER_CONTROL 0x832EU -#define VIDEO_GET_MAX_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL 0x832FU - -#define VIDEO_GET_MAX_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x8344U -#define VIDEO_GET_MAX_CT_FOCUS_ABSOLUTE_CONTROL 0x8346U -#define VIDEO_GET_MAX_CT_FOCUS_RELATIVE_CONTROL 0x8347U -#define VIDEO_GET_MAX_CT_IRIS_ABSOLUTE_CONTROL 0x8349U -#define VIDEO_GET_MAX_CT_ZOOM_ABSOLUTE_CONTROL 0x834BU -#define VIDEO_GET_MAX_CT_ZOOM_RELATIVE_CONTROL 0x834CU -#define VIDEO_GET_MAX_CT_PANTILT_ABSOLUTE_CONTROL 0x834DU -#define VIDEO_GET_MAX_CT_PANTILT_RELATIVE_CONTROL 0x834EU -#define VIDEO_GET_MAX_CT_ROLL_ABSOLUTE_CONTROL 0x834FU -#define VIDEO_GET_MAX_CT_ROLL_RELATIVE_CONTROL 0x8350U -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_GET_MAX_CT_DIGITAL_WINDOW_CONTROL 0x8351U -#define VIDEO_GET_MAX_CT_REGION_OF_INTEREST_CONTROL 0x8352U -#endif - -#define VIDEO_GET_MAX_VS_PROBE_CONTROL 0x8361U -#define VIDEO_GET_MAX_VS_STILL_PROBE_CONTROL 0x8363U -#define VIDEO_GET_MAX_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x8368U -#define VIDEO_GET_MAX_VS_SYNCH_DELAY_CONTROL 0x8369U - -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_GET_MAX_EU_VIDEO_RESOLUTION_CONTROL 0x8383U -#define VIDEO_GET_MAX_EU_MIN_FRAME_INTERVAL_CONTROL 0x8384U -#define VIDEO_GET_MAX_EU_SLICE_MODE_CONTROL 0x8385U -#define VIDEO_GET_MAX_EU_AVERAGE_BITRATE_CONTROL 0x8387U -#define VIDEO_GET_MAX_EU_CPB_SIZE_CONTROL 0x8388U -#define VIDEO_GET_MAX_EU_PEAK_BIT_RATE_CONTROL 0x8389U -#define VIDEO_GET_MAX_EU_QUANTIZATION_PARAMS_CONTROL 0x838AU -#define VIDEO_GET_MAX_EU_SYNC_REF_FRAME_CONTROL 0x838BU -#define VIDEO_GET_MAX_EU_LTR_BUFFER_CONTROL 0x838CU -#define VIDEO_GET_MAX_EU_LEVEL_IDC_LIMIT_CONTROL 0x838FU -#define VIDEO_GET_MAX_EU_SEI_PAYLOADTYPE_CONTROL 0x8390U -#define VIDEO_GET_MAX_EU_QP_RANGE_CONTROL 0x8391U -#endif - -/*! @brief Video device class-specific request GET RES COMMAND */ -#define VIDEO_GET_RES_PU_BACKLIGHT_COMPENSATION_CONTROL 0x8421U -#define VIDEO_GET_RES_PU_BRIGHTNESS_CONTROL 0x8422U -#define VIDEO_GET_RES_PU_CONTRACT_CONTROL 0x8423U -#define VIDEO_GET_RES_PU_GAIN_CONTROL 0x8424U -#define VIDEO_GET_RES_PU_HUE_CONTROL 0x8426U -#define VIDEO_GET_RES_PU_SATURATION_CONTROL 0x8427U -#define VIDEO_GET_RES_PU_SHARRNESS_CONTROL 0x8428U -#define VIDEO_GET_RES_PU_GAMMA_CONTROL 0x8429U -#define VIDEO_GET_RES_PU_WHITE_BALANCE_TEMPERATURE_CONTROL 0x842AU -#define VIDEO_GET_RES_PU_WHITE_BALANCE_COMPONENT_CONTROL 0x842CU -#define VIDEO_GET_RES_PU_DIGITAL_MULTIPLIER_CONTROL 0x842EU -#define VIDEO_GET_RES_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL 0x842FU - -#define VIDEO_GET_RES_CT_AE_MODE_CONTROL 0x8442U -#define VIDEO_GET_RES_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x8444U -#define VIDEO_GET_RES_CT_FOCUS_ABSOLUTE_CONTROL 0x8446U -#define VIDEO_GET_RES_CT_FOCUS_RELATIVE_CONTROL 0x8447U -#define VIDEO_GET_RES_CT_IRIS_ABSOLUTE_CONTROL 0x8449U -#define VIDEO_GET_RES_CT_ZOOM_ABSOLUTE_CONTROL 0x844BU -#define VIDEO_GET_RES_CT_ZOOM_RELATIVE_CONTROL 0x844CU -#define VIDEO_GET_RES_CT_PANTILT_ABSOLUTE_CONTROL 0x844DU -#define VIDEO_GET_RES_CT_PANTILT_RELATIVE_CONTROL 0x844EU -#define VIDEO_GET_RES_CT_ROLL_ABSOLUTE_CONTROL 0x844FU -#define VIDEO_GET_RES_CT_ROLL_RELATIVE_CONTROL 0x8450U - -#define VIDEO_GET_RES_VS_PROBE_CONTROL 0x8461U -#define VIDEO_GET_RES_VS_STILL_PROBE_CONTROL 0x8463U -#define VIDEO_GET_RES_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x8468U -#define VIDEO_GET_RES_VS_SYNCH_DELAY_CONTROL 0x8469U - -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_GET_RES_EU_AVERAGE_BITRATE_CONTROL 0x8487U -#define VIDEO_GET_RES_EU_CPB_SIZE_CONTROL 0x8488U -#define VIDEO_GET_RES_EU_PEAK_BIT_RATE_CONTROL 0x8489U -#define VIDEO_GET_RES_EU_QUANTIZATION_PARAMS_CONTROL 0x848AU -#define VIDEO_GET_RES_EU_ERROR_RESILIENCY_CONTROL 0x8494U -#endif - -/*! @brief Video device class-specific request GET LEN COMMAND */ - -#define VIDEO_GET_LEN_VS_PROBE_CONTROL 0x8561U -#define VIDEO_GET_LEN_VS_COMMIT_CONTROL 0x8562U -#define VIDEO_GET_LEN_VS_STILL_PROBE_CONTROL 0x8563U -#define VIDEO_GET_LEN_VS_STILL_COMMIT_CONTROL 0x8564U - -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_GET_LEN_EU_SELECT_LAYER_CONTROL 0x8581U -#define VIDEO_GET_LEN_EU_PROFILE_TOOLSET_CONTROL 0x8582U -#define VIDEO_GET_LEN_EU_VIDEO_RESOLUTION_CONTROL 0x8583U -#define VIDEO_GET_LEN_EU_MIN_FRAME_INTERVAL_CONTROL 0x8584U -#define VIDEO_GET_LEN_EU_SLICE_MODE_CONTROL 0x8585U -#define VIDEO_GET_LEN_EU_RATE_CONTROL_MODE_CONTROL 0x8586U -#define VIDEO_GET_LEN_EU_AVERAGE_BITRATE_CONTROL 0x8587U -#define VIDEO_GET_LEN_EU_CPB_SIZE_CONTROL 0x8588U -#define VIDEO_GET_LEN_EU_PEAK_BIT_RATE_CONTROL 0x8589U -#define VIDEO_GET_LEN_EU_QUANTIZATION_PARAMS_CONTROL 0x858AU -#define VIDEO_GET_LEN_EU_SYNC_REF_FRAME_CONTROL 0x858BU -#define VIDEO_GET_LEN_EU_LTR_BUFFER_CONTROL 0x858CU -#define VIDEO_GET_LEN_EU_LTR_PICTURE_CONTROL 0x858DU -#define VIDEO_GET_LEN_EU_LTR_VALIDATION_CONTROL 0x858EU -#define VIDEO_GET_LEN_EU_QP_RANGE_CONTROL 0x8591U -#define VIDEO_GET_LEN_EU_PRIORITY_CONTROL 0x8592U -#define VIDEO_GET_LEN_EU_START_OR_STOP_LAYER_CONTROL 0x8593U -#endif - -/*! @brief Video device class-specific request GET INFO COMMAND */ -#define VIDEO_GET_INFO_VC_POWER_MODE_CONTROL 0x8601U -#define VIDEO_GET_INFO_VC_ERROR_CODE_CONTROL 0x8602U - -#define VIDEO_GET_INFO_PU_BACKLIGHT_COMPENSATION_CONTROL 0x8621U -#define VIDEO_GET_INFO_PU_BRIGHTNESS_CONTROL 0x8622U -#define VIDEO_GET_INFO_PU_CONTRACT_CONTROL 0x8623U -#define VIDEO_GET_INFO_PU_GAIN_CONTROL 0x8624U -#define VIDEO_GET_INFO_PU_POWER_LINE_FREQUENCY_CONTROL 0x8625U -#define VIDEO_GET_INFO_PU_HUE_CONTROL 0x8626U -#define VIDEO_GET_INFO_PU_SATURATION_CONTROL 0x8627U -#define VIDEO_GET_INFO_PU_SHARRNESS_CONTROL 0x8628U -#define VIDEO_GET_INFO_PU_GAMMA_CONTROL 0x8629U -#define VIDEO_GET_INFO_PU_WHITE_BALANCE_TEMPERATURE_CONTROL 0x862AU -#define VIDEO_GET_INFO_PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 0x862BU -#define VIDEO_GET_INFO_PU_WHITE_BALANCE_COMPONENT_CONTROL 0x862CU -#define VIDEO_GET_INFO_PU_WHITE_BALANCE_COMPONENT_AUTO_CONTROL 0x862DU -#define VIDEO_GET_INFO_PU_DIGITAL_MULTIPLIER_CONTROL 0x862EU -#define VIDEO_GET_INFO_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL 0x862FU -#define VIDEO_GET_INFO_PU_HUE_AUTO_CONTROL 0x8630U -#define VIDEO_GET_INFO_PU_ANALOG_VIDEO_STANDARD_CONTROL 0x8631U -#define VIDEO_GET_INFO_PU_ANALOG_LOCK_STATUS_CONTROL 0x8632U -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_GET_INFO_PU_CONTRAST_AUTO_CONTROL 0x8633U -#endif - -#define VIDEO_GET_INFO_CT_SCANNING_MODE_CONTROL 0x8641U -#define VIDEO_GET_INFO_CT_AE_MODE_CONTROL 0x8642U -#define VIDEO_GET_INFO_CT_AE_PRIORITY_CONTROL 0x8643U -#define VIDEO_GET_INFO_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x8644U -#define VIDEO_GET_INFO_CT_EXPOSURE_TIME_RELATIVE_CONTROL 0x8645U -#define VIDEO_GET_INFO_CT_FOCUS_ABSOLUTE_CONTROL 0x8646U -#define VIDEO_GET_INFO_CT_FOCUS_RELATIVE_CONTROL 0x8647U -#define VIDEO_GET_INFO_CT_FOCUS_AUTO_CONTROL 0x8648U -#define VIDEO_GET_INFO_CT_IRIS_ABSOLUTE_CONTROL 0x8649U -#define VIDEO_GET_INFO_CT_IRIS_RELATIVE_CONTROL 0x864AU -#define VIDEO_GET_INFO_CT_ZOOM_ABSOLUTE_CONTROL 0x864BU -#define VIDEO_GET_INFO_CT_ZOOM_RELATIVE_CONTROL 0x864CU -#define VIDEO_GET_INFO_CT_PANTILT_ABSOLUTE_CONTROL 0x864DU -#define VIDEO_GET_INFO_CT_PANTILT_RELATIVE_CONTROL 0x864EU -#define VIDEO_GET_INFO_CT_ROLL_ABSOLUTE_CONTROL 0x864FU -#define VIDEO_GET_INFO_CT_ROLL_RELATIVE_CONTROL 0x8650U -#define VIDEO_GET_INFO_CT_PRIVACY_CONTROL 0x8651U -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_GET_INFO_CT_FOCUS_SIMPLE_CONTROL 0x8652U -#endif - -#define VIDEO_GET_INFO_VS_PROBE_CONTROL 0x8661U -#define VIDEO_GET_INFO_VS_COMMIT_CONTROL 0x8662U -#define VIDEO_GET_INFO_VS_STILL_PROBE_CONTROL 0x8663U -#define VIDEO_GET_INFO_VS_STILL_COMMIT_CONTROL 0x8664U -#define VIDEO_GET_INFO_VS_STILL_IMAGE_TRIGGER_CONTROL 0x8665U -#define VIDEO_GET_INFO_VS_STREAM_ERROR_CODE_CONTROL 0x8666U -#define VIDEO_GET_INFO_VS_GENERATE_KEY_FRAME_CONTROL 0x8667U -#define VIDEO_GET_INFO_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x8668U -#define VIDEO_GET_INFO_VS_SYNCH_DELAY_CONTROL 0x8669U - -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_GET_INFO_EU_SELECT_LAYER_CONTROL 0x8681U -#define VIDEO_GET_INFO_EU_PROFILE_TOOLSET_CONTROL 0x8682U -#define VIDEO_GET_INFO_EU_VIDEO_RESOLUTION_CONTROL 0x8683U -#define VIDEO_GET_INFO_EU_MIN_FRAME_INTERVAL_CONTROL 0x8684U -#define VIDEO_GET_INFO_EU_SLICE_MODE_CONTROL 0x8685U -#define VIDEO_GET_INFO_EU_RATE_CONTROL_MODE_CONTROL 0x8686U -#define VIDEO_GET_INFO_EU_AVERAGE_BITRATE_CONTROL 0x8687U -#define VIDEO_GET_INFO_EU_CPB_SIZE_CONTROL 0x8688U -#define VIDEO_GET_INFO_EU_PEAK_BIT_RATE_CONTROL 0x8689U -#define VIDEO_GET_INFO_EU_QUANTIZATION_PARAMS_CONTROL 0x868AU -#define VIDEO_GET_INFO_EU_SYNC_REF_FRAME_CONTROL 0x868BU -#define VIDEO_GET_INFO_EU_LTR_BUFFER_CONTROL 0x868CU -#define VIDEO_GET_INFO_EU_LTR_PICTURE_CONTROL 0x868DU -#define VIDEO_GET_INFO_EU_LTR_VALIDATION_CONTROL 0x868EU -#define VIDEO_GET_INFO_EU_SEI_PAYLOADTYPE_CONTROL 0x8690U -#define VIDEO_GET_INFO_EU_QP_RANGE_CONTROL 0x8691U -#define VIDEO_GET_INFO_EU_PRIORITY_CONTROL 0x8692U -#define VIDEO_GET_INFO_EU_START_OR_STOP_LAYER_CONTROL 0x8693U -#endif - -/*! @brief Video device class-specific request GET DEF COMMAND */ -#define VIDEO_GET_DEF_PU_BACKLIGHT_COMPENSATION_CONTROL 0x8721U -#define VIDEO_GET_DEF_PU_BRIGHTNESS_CONTROL 0x8722U -#define VIDEO_GET_DEF_PU_CONTRACT_CONTROL 0x8723U -#define VIDEO_GET_DEF_PU_GAIN_CONTROL 0x8724U -#define VIDEO_GET_DEF_PU_POWER_LINE_FREQUENCY_CONTROL 0x8725U -#define VIDEO_GET_DEF_PU_HUE_CONTROL 0x8726U -#define VIDEO_GET_DEF_PU_SATURATION_CONTROL 0x8727U -#define VIDEO_GET_DEF_PU_SHARRNESS_CONTROL 0x8728U -#define VIDEO_GET_DEF_PU_GAMMA_CONTROL 0x8729U -#define VIDEO_GET_DEF_PU_WHITE_BALANCE_TEMPERATURE_CONTROL 0x872AU -#define VIDEO_GET_DEF_PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 0x872BU -#define VIDEO_GET_DEF_PU_WHITE_BALANCE_COMPONENT_CONTROL 0x872CU -#define VIDEO_GET_DEF_PU_WHITE_BALANCE_COMPONENT_AUTO_CONTROL 0x872DU -#define VIDEO_GET_DEF_PU_DIGITAL_MULTIPLIER_CONTROL 0x872EU -#define VIDEO_GET_DEF_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL 0x872FU -#define VIDEO_GET_DEF_PU_HUE_AUTO_CONTROL 0x8730U -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_GET_DEF_PU_CONTRAST_AUTO_CONTROL 0x8731U -#endif - -#define VIDEO_GET_DEF_CT_AE_MODE_CONTROL 0x8742U -#define VIDEO_GET_DEF_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x8744U -#define VIDEO_GET_DEF_CT_FOCUS_ABSOLUTE_CONTROL 0x8746U -#define VIDEO_GET_DEF_CT_FOCUS_RELATIVE_CONTROL 0x8747U -#define VIDEO_GET_DEF_CT_FOCUS_AUTO_CONTROL 0x8748U -#define VIDEO_GET_DEF_CT_IRIS_ABSOLUTE_CONTROL 0x8749U -#define VIDEO_GET_DEF_CT_ZOOM_ABSOLUTE_CONTROL 0x874BU -#define VIDEO_GET_DEF_CT_ZOOM_RELATIVE_CONTROL 0x874CU -#define VIDEO_GET_DEF_CT_PANTILT_ABSOLUTE_CONTROL 0x874DU -#define VIDEO_GET_DEF_CT_PANTILT_RELATIVE_CONTROL 0x874EU -#define VIDEO_GET_DEF_CT_ROLL_ABSOLUTE_CONTROL 0x874FU -#define VIDEO_GET_DEF_CT_ROLL_RELATIVE_CONTROL 0x8750U -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_GET_DEF_CT_FOCUS_SIMPLE_CONTROL 0x8751U -#define VIDEO_GET_DEF_CT_DIGITAL_WINDOW_CONTROL 0x8752U -#define VIDEO_GET_DEF_CT_REGION_OF_INTEREST_CONTROL 0x8753U -#endif - -#define VIDEO_GET_DEF_VS_PROBE_CONTROL 0x8761U -#define VIDEO_GET_DEF_VS_STILL_PROBE_CONTROL 0x8763U -#define VIDEO_GET_DEF_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x8768U -#define VIDEO_GET_DEF_VS_SYNCH_DELAY_CONTROL 0x8769U - -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_GET_DEF_EU_PROFILE_TOOLSET_CONTROL 0x8782U -#define VIDEO_GET_DEF_EU_VIDEO_RESOLUTION_CONTROL 0x8783U -#define VIDEO_GET_DEF_EU_MIN_FRAME_INTERVAL_CONTROL 0x8784U -#define VIDEO_GET_DEF_EU_SLICE_MODE_CONTROL 0x8785U -#define VIDEO_GET_DEF_EU_RATE_CONTROL_MODE_CONTROL 0x8786U -#define VIDEO_GET_DEF_EU_AVERAGE_BITRATE_CONTROL 0x8787U -#define VIDEO_GET_DEF_EU_CPB_SIZE_CONTROL 0x8788U -#define VIDEO_GET_DEF_EU_PEAK_BIT_RATE_CONTROL 0x8789U -#define VIDEO_GET_DEF_EU_QUANTIZATION_PARAMS_CONTROL 0x878AU -#define VIDEO_GET_DEF_EU_LTR_BUFFER_CONTROL 0x878CU -#define VIDEO_GET_DEF_EU_LTR_PICTURE_CONTROL 0x878DU -#define VIDEO_GET_DEF_EU_LTR_VALIDATION_CONTROL 0x878EU -#define VIDEO_GET_DEF_EU_LEVEL_IDC_LIMIT_CONTROL 0x878FU -#define VIDEO_GET_DEF_EU_SEI_PAYLOADTYPE_CONTROL 0x8790U -#define VIDEO_GET_DEF_EU_QP_RANGE_CONTROL 0x8791U -#define VIDEO_GET_DEF_EU_ERROR_RESILIENCY_CONTROL 0x8794U -#endif - -/*! @brief Video device class-specific request SET CUR COMMAND */ -#define VIDEO_SET_CUR_VC_POWER_MODE_CONTROL 0x0101U - -#define VIDEO_SET_CUR_PU_BACKLIGHT_COMPENSATION_CONTROL 0x0121U -#define VIDEO_SET_CUR_PU_BRIGHTNESS_CONTROL 0x0122U -#define VIDEO_SET_CUR_PU_CONTRACT_CONTROL 0x0123U -#define VIDEO_SET_CUR_PU_GAIN_CONTROL 0x0124U -#define VIDEO_SET_CUR_PU_POWER_LINE_FREQUENCY_CONTROL 0x0125U -#define VIDEO_SET_CUR_PU_HUE_CONTROL 0x0126U -#define VIDEO_SET_CUR_PU_SATURATION_CONTROL 0x0127U -#define VIDEO_SET_CUR_PU_SHARRNESS_CONTROL 0x0128U -#define VIDEO_SET_CUR_PU_GAMMA_CONTROL 0x0129U -#define VIDEO_SET_CUR_PU_WHITE_BALANCE_TEMPERATURE_CONTROL 0x012AU -#define VIDEO_SET_CUR_PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 0x012BU -#define VIDEO_SET_CUR_PU_WHITE_BALANCE_COMPONENT_CONTROL 0x012CU -#define VIDEO_SET_CUR_PU_WHITE_BALANCE_COMPONENT_AUTO_CONTROL 0x012DU -#define VIDEO_SET_CUR_PU_DIGITAL_MULTIPLIER_CONTROL 0x012EU -#define VIDEO_SET_CUR_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL 0x012FU -#define VIDEO_SET_CUR_PU_HUE_AUTO_CONTROL 0x0130U -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_SET_CUR_PU_CONTRAST_AUTO_CONTROL 0x0131U -#endif - -#define VIDEO_SET_CUR_CT_SCANNING_MODE_CONTROL 0x0141U -#define VIDEO_SET_CUR_CT_AE_MODE_CONTROL 0x0142U -#define VIDEO_SET_CUR_CT_AE_PRIORITY_CONTROL 0x0143U -#define VIDEO_SET_CUR_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x0144U -#define VIDEO_SET_CUR_CT_EXPOSURE_TIME_RELATIVE_CONTROL 0x0145U -#define VIDEO_SET_CUR_CT_FOCUS_ABSOLUTE_CONTROL 0x0146U -#define VIDEO_SET_CUR_CT_FOCUS_RELATIVE_CONTROL 0x0147U -#define VIDEO_SET_CUR_CT_FOCUS_AUTO_CONTROL 0x0148U -#define VIDEO_SET_CUR_CT_IRIS_ABSOLUTE_CONTROL 0x0149U -#define VIDEO_SET_CUR_CT_IRIS_RELATIVE_CONTROL 0x014AU -#define VIDEO_SET_CUR_CT_ZOOM_ABSOLUTE_CONTROL 0x014BU -#define VIDEO_SET_CUR_CT_ZOOM_RELATIVE_CONTROL 0x014CU -#define VIDEO_SET_CUR_CT_PANTILT_ABSOLUTE_CONTROL 0x014DU -#define VIDEO_SET_CUR_CT_PANTILT_RELATIVE_CONTROL 0x014EU -#define VIDEO_SET_CUR_CT_ROLL_ABSOLUTE_CONTROL 0x014FU -#define VIDEO_SET_CUR_CT_ROLL_RELATIVE_CONTROL 0x0150U -#define VIDEO_SET_CUR_CT_PRIVACY_CONTROL 0x0151U -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_SET_CUR_CT_FOCUS_SIMPLE_CONTROL 0x0152U -#define VIDEO_SET_CUR_CT_DIGITAL_WINDOW_CONTROL 0x0153U -#define VIDEO_SET_CUR_CT_REGION_OF_INTEREST_CONTROL 0x0154U -#endif - -#define VIDEO_SET_CUR_VS_PROBE_CONTROL 0x0161U -#define VIDEO_SET_CUR_VS_COMMIT_CONTROL 0x0162U -#define VIDEO_SET_CUR_VS_STILL_PROBE_CONTROL 0x0163U -#define VIDEO_SET_CUR_VS_STILL_COMMIT_CONTROL 0x0164U -#define VIDEO_SET_CUR_VS_STILL_IMAGE_TRIGGER_CONTROL 0x0165U -#define VIDEO_SET_CUR_VS_STREAM_ERROR_CODE_CONTROL 0x0166U -#define VIDEO_SET_CUR_VS_GENERATE_KEY_FRAME_CONTROL 0x0167U -#define VIDEO_SET_CUR_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x0168U -#define VIDEO_SET_CUR_VS_SYNCH_DELAY_CONTROL 0x0169U - -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 -#define VIDEO_SET_CUR_EU_SELECT_LAYER_CONTROL 0x0181U -#define VIDEO_SET_CUR_EU_PROFILE_TOOLSET_CONTROL 0x0182U -#define VIDEO_SET_CUR_EU_VIDEO_RESOLUTION_CONTROL 0x0183U -#define VIDEO_SET_CUR_EU_MIN_FRAME_INTERVAL_CONTROL 0x0184U -#define VIDEO_SET_CUR_EU_SLICE_MODE_CONTROL 0x0185U -#define VIDEO_SET_CUR_EU_RATE_CONTROL_MODE_CONTROL 0x0186U -#define VIDEO_SET_CUR_EU_AVERAGE_BITRATE_CONTROL 0x0187U -#define VIDEO_SET_CUR_EU_CPB_SIZE_CONTROL 0x0188U -#define VIDEO_SET_CUR_EU_PEAK_BIT_RATE_CONTROL 0x0189U -#define VIDEO_SET_CUR_EU_QUANTIZATION_PARAMS_CONTROL 0x018AU -#define VIDEO_SET_CUR_EU_SYNC_REF_FRAME_CONTROL 0x018BU -#define VIDEO_SET_CUR_EU_LTR_BUFFER_CONTROL 0x018CU -#define VIDEO_SET_CUR_EU_LTR_PICTURE_CONTROL 0x018DU -#define VIDEO_SET_CUR_EU_LTR_VALIDATION_CONTROL 0x018EU -#define VIDEO_SET_CUR_EU_LEVEL_IDC_LIMIT_CONTROL 0x018FU -#define VIDEO_SET_CUR_EU_SEI_PAYLOADTYPE_CONTROL 0x0190U -#define VIDEO_SET_CUR_EU_QP_RANGE_CONTROL 0x0191U -#define VIDEO_SET_CUR_EU_PRIORITY_CONTROL 0x0192U -#define VIDEO_SET_CUR_EU_START_OR_STOP_LAYER_CONTROL 0x0193U -#define VIDEO_SET_CUR_EU_ERROR_RESILIENCY_CONTROL 0x0194U -#endif - -/*! @brief The payload header structure for MJPEG payload format. */ -struct video_mjpeg_payload_header { - uint8_t bHeaderLength; /*!< The payload header length. */ - union { - uint8_t bmheaderInfo; /*!< The payload header bitmap field. */ - struct - { - uint8_t frameIdentifier : 1U; /*!< Frame Identifier. This bit toggles at each frame start boundary and stays - constant for the rest of the frame.*/ - uint8_t endOfFrame : 1U; /*!< End of Frame. This bit indicates the end of a video frame and is set in the - last video sample that belongs to a frame.*/ - uint8_t - presentationTimeStamp : 1U; /*!< Presentation Time Stamp. This bit, when set, indicates the presence of - a PTS field.*/ - uint8_t sourceClockReference : 1U; /*!< Source Clock Reference. This bit, when set, indicates the presence - of a SCR field.*/ - uint8_t reserved : 1U; /*!< Reserved. Set to 0. */ - uint8_t stillImage : 1U; /*!< Still Image. This bit, when set, identifies a video sample that belongs to a - still image.*/ - uint8_t errorBit : 1U; /*!< Error Bit. This bit, when set, indicates an error in the device streaming.*/ - uint8_t endOfHeader : 1U; /*!< End of Header. This bit, when set, indicates the end of the BFH fields.*/ - } headerInfoBits; - struct - { - uint8_t FID : 1U; /*!< Frame Identifier. This bit toggles at each frame start boundary and stays constant - for the rest of the frame.*/ - uint8_t EOI : 1U; /*!< End of Frame. This bit indicates the end of a video frame and is set in the last - video sample that belongs to a frame.*/ - uint8_t PTS : 1U; /*!< Presentation Time Stamp. This bit, when set, indicates the presence of a PTS field.*/ - uint8_t SCR : 1U; /*!< Source Clock Reference. This bit, when set, indicates the presence of a SCR field.*/ - uint8_t RES : 1U; /*!< Reserved. Set to 0. */ - uint8_t STI : 1U; /*!< Still Image. This bit, when set, identifies a video sample that belongs to a still - image.*/ - uint8_t ERR : 1U; /*!< Error Bit. This bit, when set, indicates an error in the device streaming.*/ - uint8_t EOH : 1U; /*!< End of Header. This bit, when set, indicates the end of the BFH fields.*/ - } headerInfoBitmap; - } headerInfoUnion; - uint32_t dwPresentationTime; /*!< Presentation time stamp (PTS) field.*/ - uint8_t bSourceClockReference[6]; /*!< Source clock reference (SCR) field.*/ -} __packed; - -/*! @brief The Video probe and commit controls structure.*/ -struct video_probe_and_commit_controls { - union { - uint8_t bmHint; /*!< Bit-field control indicating to the function what fields shall be kept fixed. */ - struct - { - uint8_t dwFrameInterval : 1U; /*!< dwFrameInterval field.*/ - uint8_t wKeyFrameRate : 1U; /*!< wKeyFrameRate field.*/ - uint8_t wPFrameRate : 1U; /*!< wPFrameRate field.*/ - uint8_t wCompQuality : 1U; /*!< wCompQuality field.*/ - uint8_t wCompWindowSize : 1U; /*!< wCompWindowSize field.*/ - uint8_t reserved : 3U; /*!< Reserved field.*/ - } hintBitmap; - } hintUnion; - union { - uint8_t bmHint; /*!< Bit-field control indicating to the function what fields shall be kept fixed. */ - struct - { - uint8_t reserved : 8U; /*!< Reserved field.*/ - } hintBitmap; - } hintUnion1; - uint8_t bFormatIndex; /*!< Video format index from a format descriptor.*/ - uint8_t bFrameIndex; /*!< Video frame index from a frame descriptor.*/ - uint32_t dwFrameInterval; /*!< Frame interval in 100ns units.*/ - uint16_t wKeyFrameRate; /*!< Key frame rate in key-frame per video-frame units.*/ - uint16_t wPFrameRate; /*!< PFrame rate in PFrame/key frame units.*/ - uint16_t wCompQuality; /*!< Compression quality control in abstract units 0U (lowest) to 10000U (highest).*/ - uint16_t wCompWindowSize; /*!< Window size for average bit rate control.*/ - uint16_t wDelay; /*!< Internal video streaming interface latency in ms from video data capture to presentation on - the USB.*/ - uint32_t dwMaxVideoFrameSize; /*!< Maximum video frame or codec-specific segment size in bytes.*/ - uint32_t dwMaxPayloadTransferSize; /*!< Specifies the maximum number of bytes that the device can transmit or - receive in a single payload transfer.*/ - uint32_t dwClockFrequency; /*!< The device clock frequency in Hz for the specified format. This specifies the - units used for the time information fields in the Video Payload Headers in the data - stream.*/ - uint8_t bmFramingInfo; /*!< Bit-field control supporting the following values: D0 Frame ID, D1 EOF.*/ - uint8_t bPreferedVersion; /*!< The preferred payload format version supported by the host or device for the - specified bFormatIndex value.*/ - uint8_t bMinVersion; /*!< The minimum payload format version supported by the device for the specified bFormatIndex - value.*/ - uint8_t bMaxVersion; /*!< The maximum payload format version supported by the device for the specified bFormatIndex - value.*/ -#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5 - uint8_t bUsage; /*!< This bitmap enables features reported by the bmUsages field of the Video Frame Descriptor.*/ - uint8_t - bBitDepthLuma; /*!< Represents bit_depth_luma_minus8 + 8U, which must be the same as bit_depth_chroma_minus8 + - 8.*/ - uint8_t bmSettings; /*!< A bitmap of flags that is used to discover and control specific features of a temporally - encoded video stream.*/ - uint8_t bMaxNumberOfRefFramesPlus1; /*!< Host indicates the maximum number of frames stored for use as references.*/ - uint16_t bmRateControlModes; /*!< This field contains 4U sub-fields, each of which is a 4U bit number.*/ - uint64_t bmLayoutPerStream; /*!< This field contains 4U sub-fields, each of which is a 2U byte number.*/ -#endif -} __packed; - -/*! @brief The Video still probe and still commit controls structure.*/ -struct video_still_probe_and_commit_controls { - uint8_t bFormatIndex; /*!< Video format index from a format descriptor.*/ - uint8_t bFrameIndex; /*!< Video frame index from a frame descriptor.*/ - uint8_t bCompressionIndex; /*!< Compression index from a frame descriptor.*/ - uint32_t dwMaxVideoFrameSize; /*!< Maximum still image size in bytes.*/ - uint32_t dwMaxPayloadTransferSize; /*!< Specifies the maximum number of bytes that the device can transmit or - receive in a single payload transfer.*/ -} __packed; - -void usbd_video_sof_callback(void); -void usbd_video_set_interface_callback(uint8_t value); -void usbd_video_add_interface(usbd_class_t *class, usbd_interface_t *intf); - -#ifdef __cplusplus -} -#endif - -#endif /* USB_VIDEO_H_ */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/webusb/usbd_webusb.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/webusb/usbd_webusb.h deleted file mode 100644 index d94d170218..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/webusb/usbd_webusb.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef _USBD_WEBUSB_H -#define _USBD_WEBUSB_H - -/* WebUSB Descriptor Types */ -#define WEBUSB_DESCRIPTOR_SET_HEADER_TYPE 0x00 -#define WEBUSB_CONFIGURATION_SUBSET_HEADER_TYPE 0x01 -#define WEBUSB_FUNCTION_SUBSET_HEADER_TYPE 0x02 -#define WEBUSB_URL_TYPE 0x03 - -/* WebUSB Request Codes */ -#define WEBUSB_REQUEST_GET_URL 0x02 - -/* bScheme in URL descriptor */ -#define WEBUSB_URL_SCHEME_HTTP 0x00 -#define WEBUSB_URL_SCHEME_HTTPS 0x01 - -/* WebUSB Descriptor sizes */ -#define WEBUSB_DESCRIPTOR_SET_HEADER_SIZE 5 -#define WEBUSB_CONFIGURATION_SUBSET_HEADER_SIZE 4 -#define WEBUSB_FUNCTION_SUBSET_HEADER_SIZE 3 - -#endif \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/winusb/usbd_winusb.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/winusb/usbd_winusb.h deleted file mode 100644 index dc4a51dd64..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/winusb/usbd_winusb.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef _USBD_WINUSB_H -#define _USBD_WINUSB_H - -/* WinUSB Microsoft OS 2.0 descriptor request codes */ -#define WINUSB_REQUEST_GET_DESCRIPTOR_SET 0x07 -#define WINUSB_REQUEST_SET_ALT_ENUM 0x08 - -/* WinUSB Microsoft OS 2.0 descriptor sizes */ -#define WINUSB_DESCRIPTOR_SET_HEADER_SIZE 10 -#define WINUSB_FUNCTION_SUBSET_HEADER_SIZE 8 -#define WINUSB_FEATURE_COMPATIBLE_ID_SIZE 20 - -/* WinUSB Microsoft OS 2.0 Descriptor Types */ -#define WINUSB_SET_HEADER_DESCRIPTOR_TYPE 0x00 -#define WINUSB_SUBSET_HEADER_CONFIGURATION_TYPE 0x01 -#define WINUSB_SUBSET_HEADER_FUNCTION_TYPE 0x02 -#define WINUSB_FEATURE_COMPATIBLE_ID_TYPE 0x03 -#define WINUSB_FEATURE_REG_PROPERTY_TYPE 0x04 -#define WINUSB_FEATURE_MIN_RESUME_TIME_TYPE 0x05 -#define WINUSB_FEATURE_MODEL_ID_TYPE 0x06 -#define WINUSB_FEATURE_CCGP_DEVICE_TYPE 0x07 - -#define WINUSB_PROP_DATA_TYPE_REG_SZ 0x01 -#define WINUSB_PROP_DATA_TYPE_REG_MULTI_SZ 0x07 - -#endif \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_dc.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_dc.h deleted file mode 100644 index bb83838264..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_dc.h +++ /dev/null @@ -1,197 +0,0 @@ -#ifndef _USB_DC_H -#define _USB_DC_H - -#include "stdint.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * USB endpoint direction and number. - */ -#define USB_EP_DIR_MASK 0x80U -#define USB_EP_DIR_IN 0x80U -#define USB_EP_DIR_OUT 0x00U - -/** Get endpoint index (number) from endpoint address */ -#define USB_EP_GET_IDX(ep) ((ep) & ~USB_EP_DIR_MASK) -/** Get direction from endpoint address */ -#define USB_EP_GET_DIR(ep) ((ep)&USB_EP_DIR_MASK) -/** Get endpoint address from endpoint index and direction */ -#define USB_EP_GET_ADDR(idx, dir) ((idx) | ((dir)&USB_EP_DIR_MASK)) -/** True if the endpoint is an IN endpoint */ -#define USB_EP_DIR_IS_IN(ep) (USB_EP_GET_DIR(ep) == USB_EP_DIR_IN) -/** True if the endpoint is an OUT endpoint */ -#define USB_EP_DIR_IS_OUT(ep) (USB_EP_GET_DIR(ep) == USB_EP_DIR_OUT) - -/** - * USB endpoint Transfer Type mask. - */ -#define USBD_EP_TYPE_CTRL 0 -#define USBD_EP_TYPE_ISOC 1 -#define USBD_EP_TYPE_BULK 2 -#define USBD_EP_TYPE_INTR 3 -#define USBD_EP_TYPE_MASK 3 - -/* Default USB control EP, always 0 and 0x80 */ -#define USB_CONTROL_OUT_EP0 0 -#define USB_CONTROL_IN_EP0 0x80 - -/** - * @brief USB Device Controller API - * @defgroup _usb_device_controller_api USB Device Controller API - * @{ - */ -/**< maximum packet size (MPS) for EP 0 */ -#define USB_CTRL_EP_MPS 64 - -/** - * @brief USB Endpoint Transfer Type - */ -enum usb_dc_ep_transfer_type { - /** Control type endpoint */ - USB_DC_EP_CONTROL = 0, - /** Isochronous type endpoint */ - USB_DC_EP_ISOCHRONOUS, - /** Bulk type endpoint */ - USB_DC_EP_BULK, - /** Interrupt type endpoint */ - USB_DC_EP_INTERRUPT -}; - -/** - * @brief USB Endpoint Configuration. - * - * Structure containing the USB endpoint configuration. - */ -struct usbd_endpoint_cfg { - /** The number associated with the EP in the device - * configuration structure - * IN EP = 0x80 | \ - * OUT EP = 0x00 | \ - */ - uint8_t ep_addr; - /** Endpoint max packet size */ - uint16_t ep_mps; - /** Endpoint Transfer Type. - * May be Bulk, Interrupt, Control or Isochronous - */ - enum usb_dc_ep_transfer_type ep_type; -}; - -/** - * @brief USB Device Core Layer API - * @defgroup _usb_device_core_api USB Device Core API - * @{ - */ - -/** - * @brief Set USB device address - * - * @param[in] addr Device address - * - * @return 0 on success, negative errno code on fail. - */ -int usbd_set_address(const uint8_t addr); - -/* - * @brief configure and enable endpoint - * - * This function sets endpoint configuration according to one specified in USB - * endpoint descriptor and then enables it for data transfers. - * - * @param [in] ep_desc Endpoint descriptor byte array - * - * @return true if successfully configured and enabled - */ -int usbd_ep_open(const struct usbd_endpoint_cfg *ep_cfg); -/** - * @brief Disable the selected endpoint - * - * Function to disable the selected endpoint. Upon success interrupts are - * disabled for the corresponding endpoint and the endpoint is no longer able - * for transmitting/receiving data. - * - * @param[in] ep Endpoint address corresponding to the one - * listed in the device configuration table - * - * @return 0 on success, negative errno code on fail. - */ -int usbd_ep_close(const uint8_t ep); -/** - * @brief Set stall condition for the selected endpoint - * - * @param[in] ep Endpoint address corresponding to the one - * listed in the device configuration table - * - * @return 0 on success, negative errno code on fail. - */ -int usbd_ep_set_stall(const uint8_t ep); -/** - * @brief Clear stall condition for the selected endpoint - * - * @param[in] ep Endpoint address corresponding to the one - * listed in the device configuration table - * - * @return 0 on success, negative errno code on fail. - */ -int usbd_ep_clear_stall(const uint8_t ep); -/** - * @brief Check if the selected endpoint is stalled - * - * @param[in] ep Endpoint address corresponding to the one - * listed in the device configuration table - * @param[out] stalled Endpoint stall status - * - * @return 0 on success, negative errno code on fail. - */ -int usbd_ep_is_stalled(const uint8_t ep, uint8_t *stalled); -/** - * @brief Write data to the specified endpoint - * - * This function is called to write data to the specified endpoint. The - * supplied usbd_endpoint_callback function will be called when data is transmitted - * out. - * - * @param[in] ep Endpoint address corresponding to the one - * listed in the device configuration table - * @param[in] data Pointer to data to write - * @param[in] data_len Length of the data requested to write. This may - * be zero for a zero length status packet. - * @param[out] ret_bytes Bytes scheduled for transmission. This value - * may be NULL if the application expects all - * bytes to be written - * - * @return 0 on success, negative errno code on fail. - */ -int usbd_ep_write(const uint8_t ep, const uint8_t *data, uint32_t data_len, uint32_t *ret_bytes); -/** - * @brief Read data from the specified endpoint - * - * This is similar to usb_dc_ep_read, the difference being that, it doesn't - * clear the endpoint NAKs so that the consumer is not bogged down by further - * upcalls till he is done with the processing of the data. The caller should - * reactivate ep by setting max_data_len 0 do so. - * - * @param[in] ep Endpoint address corresponding to the one - * listed in the device configuration table - * @param[in] data Pointer to data buffer to write to - * @param[in] max_data_len Max length of data to read - * @param[out] read_bytes Number of bytes read. If data is NULL and - * max_data_len is 0 the number of bytes - * available for read should be returned. - * - * @return 0 on success, negative errno code on fail. - */ -int usbd_ep_read(const uint8_t ep, uint8_t *data, uint32_t max_data_len, uint32_t *read_bytes); - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_def.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_def.h deleted file mode 100644 index 57903f6b7b..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_def.h +++ /dev/null @@ -1,566 +0,0 @@ -#ifndef USB_REQUEST_H -#define USB_REQUEST_H - -/* Useful define */ -#define USB_1_1 0x0110 -#define USB_2_0 0x0200 -/* Set USB version to 2.1 so that the host will request the BOS descriptor */ -#define USB_2_1 0x0210 - -// USB Speed -#define USB_SPEED_LOW 0U -#define USB_SPEED_FULL 1U -#define USB_SPEED_HIGH 2U - -// USB PID Types -#define USB_PID_RESERVED 0U -#define USB_PID_OUT 1U -#define USB_PID_ACK 2U -#define USB_PID_DATA0 3U -#define USB_PID_PING 4U -#define USB_PID_SOF 5U -#define USB_PID_DATA2 7U -#define USB_PID_NYET 6U -#define USB_PID_SPLIT 8U -#define USB_PID_IN 9U -#define USB_PID_NAK 10U -#define USB_PID_DATA1 11U -#define USB_PID_PRE 12U -#define USB_PID_ERR 12U -#define USB_PID_SETUP 13U -#define USB_PID_STALL 14U -#define USB_PID_MDATA 15U - -// bmRequestType.Dir -#define USB_REQUEST_HOST_TO_DEVICE 0U -#define USB_REQUEST_DEVICE_TO_HOST 1U - -// bmRequestType.Type -#define USB_REQUEST_STANDARD 0U -#define USB_REQUEST_CLASS 1U -#define USB_REQUEST_VENDOR 2U -#define USB_REQUEST_RESERVED 3U - -// bmRequestType.Recipient -#define USB_REQUEST_TO_DEVICE 0U -#define USB_REQUEST_TO_INTERFACE 1U -#define USB_REQUEST_TO_ENDPOINT 2U -#define USB_REQUEST_TO_OTHER 3U - -/* USB Standard Request Codes */ -#define USB_REQUEST_GET_STATUS 0x00 -#define USB_REQUEST_CLEAR_FEATURE 0x01 -#define USB_REQUEST_SET_FEATURE 0x03 -#define USB_REQUEST_SET_ADDRESS 0x05 -#define USB_REQUEST_GET_DESCRIPTOR 0x06 -#define USB_REQUEST_SET_DESCRIPTOR 0x07 -#define USB_REQUEST_GET_CONFIGURATION 0x08 -#define USB_REQUEST_SET_CONFIGURATION 0x09 -#define USB_REQUEST_GET_INTERFACE 0x0A -#define USB_REQUEST_SET_INTERFACE 0x0B -#define USB_REQUEST_SYNCH_FRAME 0x0C -#define USB_REQUEST_SET_ENCRYPTION 0x0D -#define USB_REQUEST_GET_ENCRYPTION 0x0E -#define USB_REQUEST_RPIPE_ABORT 0x0E -#define USB_REQUEST_SET_HANDSHAKE 0x0F -#define USB_REQUEST_RPIPE_RESET 0x0F -#define USB_REQUEST_GET_HANDSHAKE 0x10 -#define USB_REQUEST_SET_CONNECTION 0x11 -#define USB_REQUEST_SET_SECURITY_DATA 0x12 -#define USB_REQUEST_GET_SECURITY_DATA 0x13 -#define USB_REQUEST_SET_WUSB_DATA 0x14 -#define USB_REQUEST_LOOPBACK_DATA_WRITE 0x15 -#define USB_REQUEST_LOOPBACK_DATA_READ 0x16 -#define USB_REQUEST_SET_INTERFACE_DS 0x17 - -/* USB GET_STATUS Bit Values */ -#define USB_GETSTATUS_SELF_POWERED 0x01 -#define USB_GETSTATUS_REMOTE_WAKEUP 0x02 -#define USB_GETSTATUS_ENDPOINT_STALL 0x01 - -/* USB Standard Feature selectors */ -#define USB_FEATURE_ENDPOINT_STALL 0 -#define USB_FEATURE_REMOTE_WAKEUP 1 -#define USB_FEATURE_TEST_MODE 2 - -/* Descriptor size in bytes */ -#define USB_DEVICE_DESC_SIZE 0x12 -#define USB_CONFIGURATION_DESC_SIZE 0x09 -#define USB_INTERFACE_DESC_SIZE 0x09 -#define USB_ENDPOINT_DESC_SIZE 0x07 -#define USB_LANGID_STRING_DESC_SIZE 0x04 -#define USB_OTHER_SPEED_DESC_SIZE 0x09 -#define USB_DEVICE_QUAL_DESC_SIZE 0x0A -#define USB_INTERFACE_ASSOC_DESC_SIZE 0x08 -#define USB_FUNCTION_DESC_SIZE 0x03 -#define USB_OTG_DESC_SIZE 0x03 - -/* USB Descriptor Types */ -#define USB_DESCRIPTOR_TYPE_DEVICE 0x01U -#define USB_DESCRIPTOR_TYPE_CONFIGURATION 0x02U -#define USB_DESCRIPTOR_TYPE_STRING 0x03U -#define USB_DESCRIPTOR_TYPE_INTERFACE 0x04U -#define USB_DESCRIPTOR_TYPE_ENDPOINT 0x05U -#define USB_DESCRIPTOR_TYPE_DEVICE_QUALIFIER 0x06U -#define USB_DESCRIPTOR_TYPE_OTHER_SPEED 0x07U -#define USB_DESCRIPTOR_TYPE_INTERFACE_POWER 0x08U -#define USB_DESCRIPTOR_TYPE_OTG 0x09U -#define USB_DESCRIPTOR_TYPE_DEBUG 0x0AU -#define USB_DESCRIPTOR_TYPE_INTERFACE_ASSOCIATION 0x0BU -#define USB_DESCRIPTOR_TYPE_BINARY_OBJECT_STORE 0x0FU -#define USB_DESCRIPTOR_TYPE_DEVICE_CAPABILITY 0x10U - -#define USB_DESCRIPTOR_TYPE_FUNCTIONAL 0x21U - -// Class Specific Descriptor -#define USB_CS_DESCRIPTOR_TYPE_DEVICE 0x21U -#define USB_CS_DESCRIPTOR_TYPE_CONFIGURATION 0x22U -#define USB_CS_DESCRIPTOR_TYPE_STRING 0x23U -#define USB_CS_DESCRIPTOR_TYPE_INTERFACE 0x24U -#define USB_CS_DESCRIPTOR_TYPE_ENDPOINT 0x25U - -#define USB_DESCRIPTOR_TYPE_SUPERSPEED_ENDPOINT_COMPANION 0x30U -#define USB_DESCRIPTOR_TYPE_SUPERSPEED_ISO_ENDPOINT_COMPANION 0x31U - -/* USB Device Classes */ -#define USB_DEVICE_CLASS_RESERVED 0x00 -#define USB_DEVICE_CLASS_AUDIO 0x01 -#define USB_DEVICE_CLASS_CDC 0x02 -#define USB_DEVICE_CLASS_HID 0x03 -#define USB_DEVICE_CLASS_MONITOR 0x04 -#define USB_DEVICE_CLASS_PHYSICAL 0x05 -#define USB_DEVICE_CLASS_IMAGE 0x06 -#define USB_DEVICE_CLASS_PRINTER 0x07 -#define USB_DEVICE_CLASS_MASS_STORAGE 0x08 -#define USB_DEVICE_CLASS_HUB 0x09 -#define USB_DEVICE_CLASS_CDC_DATA 0x0a -#define USB_DEVICE_CLASS_SMART_CARD 0x0b -#define USB_DEVICE_CLASS_SECURITY 0x0d -#define USB_DEVICE_CLASS_VIDEO 0x0e -#define USB_DEVICE_CLASS_HEALTHCARE 0x0f -#define USB_DEVICE_CLASS_DIAG_DEVICE 0xdc -#define USB_DEVICE_CLASS_WIRELESS 0xe0 -#define USB_DEVICE_CLASS_MISC 0xef -#define USB_DEVICE_CLASS_APP_SPECIFIC 0xfe -#define USB_DEVICE_CLASS_VEND_SPECIFIC 0xff - -/* usb string index define */ -#define USB_STRING_LANGID_INDEX 0x00 -#define USB_STRING_MFC_INDEX 0x01 -#define USB_STRING_PRODUCT_INDEX 0x02 -#define USB_STRING_SERIAL_INDEX 0x03 -#define USB_STRING_CONFIG_INDEX 0x04 -#define USB_STRING_INTERFACE_INDEX 0x05 -#define USB_STRING_OS_INDEX 0x06 -#define USB_STRING_MAX USB_STRING_OS_INDEX -/* - * Devices supporting Microsoft OS Descriptors store special string - * descriptor at fixed index (0xEE). It is read when a new device is - * attached to a computer for the first time. - */ -#define USB_OSDESC_STRING_DESC_INDEX 0xEE - -/* bmAttributes in Configuration Descriptor */ -#define USB_CONFIG_POWERED_MASK 0x40 -#define USB_CONFIG_BUS_POWERED 0x80 -#define USB_CONFIG_SELF_POWERED 0xC0 -#define USB_CONFIG_REMOTE_WAKEUP 0x20 - -/* bMaxPower in Configuration Descriptor */ -#define USB_CONFIG_POWER_MA(mA) ((mA) / 2) - -/* bEndpointAddress in Endpoint Descriptor */ -#define USB_ENDPOINT_DIRECTION_MASK 0x80 -#define USB_ENDPOINT_OUT(addr) ((addr) | 0x00) -#define USB_ENDPOINT_IN(addr) ((addr) | 0x80) - -/* bmAttributes in Endpoint Descriptor */ -#define USB_ENDPOINT_TYPE_MASK 0x03 -#define USB_ENDPOINT_TYPE_CONTROL 0x00 -#define USB_ENDPOINT_TYPE_ISOCHRONOUS 0x01 -#define USB_ENDPOINT_TYPE_BULK 0x02 -#define USB_ENDPOINT_TYPE_INTERRUPT 0x03 -#define USB_ENDPOINT_SYNC_MASK 0x0C -#define USB_ENDPOINT_SYNC_NO_SYNCHRONIZATION 0x00 -#define USB_ENDPOINT_SYNC_ASYNCHRONOUS 0x04 -#define USB_ENDPOINT_SYNC_ADAPTIVE 0x08 -#define USB_ENDPOINT_SYNC_SYNCHRONOUS 0x0C -#define USB_ENDPOINT_USAGE_MASK 0x30 -#define USB_ENDPOINT_USAGE_DATA 0x00 -#define USB_ENDPOINT_USAGE_FEEDBACK 0x10 -#define USB_ENDPOINT_USAGE_IMPLICIT_FEEDBACK 0x20 -#define USB_ENDPOINT_USAGE_RESERVED 0x30 - -/* bDevCapabilityType in Device Capability Descriptor */ -#define USB_DEVICE_CAPABILITY_WIRELESS_USB 1 -#define USB_DEVICE_CAPABILITY_USB_2_0_EXTENSION 2 -#define USB_DEVICE_CAPABILITY_SUPERSPEED_USB 3 -#define USB_DEVICE_CAPABILITY_CONTAINER_ID 4 -#define USB_DEVICE_CAPABILITY_PLATFORM 5 -#define USB_DEVICE_CAPABILITY_POWER_DELIVERY_CAPABILITY 6 -#define USB_DEVICE_CAPABILITY_BATTERY_INFO_CAPABILITY 7 -#define USB_DEVICE_CAPABILITY_PD_CONSUMER_PORT_CAPABILITY 8 -#define USB_DEVICE_CAPABILITY_PD_PROVIDER_PORT_CAPABILITY 9 -#define USB_DEVICE_CAPABILITY_SUPERSPEED_PLUS 10 -#define USB_DEVICE_CAPABILITY_PRECISION_TIME_MEASUREMENT 11 -#define USB_DEVICE_CAPABILITY_WIRELESS_USB_EXT 12 - -#define USB_BOS_CAPABILITY_EXTENSION 0x02 -#define USB_BOS_CAPABILITY_PLATFORM 0x05 - -/* Setup packet definition used to read raw data from USB line */ -struct usb_setup_packet { - __packed union { - uint8_t bmRequestType; /* bmRequestType */ - struct - { - uint8_t Recipient : 5; /* D4..0: Recipient */ - uint8_t Type : 2; /* D6..5: Type */ - uint8_t Dir : 1; /* D7: Data Phase Txsfer Direction */ - } bmRequestType_b; - }; - uint8_t bRequest; - __packed union { - uint16_t wValue; /* wValue */ - struct - { - uint8_t wValueL; - uint8_t wValueH; - }; - }; - __packed union { - uint16_t wIndex; /* wIndex */ - struct - { - uint8_t wIndexL; - uint8_t wIndexH; - }; - }; - uint16_t wLength; -} __packed; - -/** Standard Device Descriptor */ -struct usb_device_descriptor { - uint8_t bLength; /* Descriptor size in bytes = 18 */ - uint8_t bDescriptorType; /* DEVICE descriptor type = 1 */ - uint16_t bcdUSB; /* USB spec in BCD, e.g. 0x0200 */ - uint8_t bDeviceClass; /* Class code, if 0 see interface */ - uint8_t bDeviceSubClass; /* Sub-Class code, 0 if class = 0 */ - uint8_t bDeviceProtocol; /* Protocol, if 0 see interface */ - uint8_t bMaxPacketSize0; /* Endpoint 0 max. size */ - uint16_t idVendor; /* Vendor ID per USB-IF */ - uint16_t idProduct; /* Product ID per manufacturer */ - uint16_t bcdDevice; /* Device release # in BCD */ - uint8_t iManufacturer; /* Index to manufacturer string */ - uint8_t iProduct; /* Index to product string */ - uint8_t iSerialNumber; /* Index to serial number string */ - uint8_t bNumConfigurations; /* Number of possible configurations */ -} __packed; - -/** USB device_qualifier descriptor */ -struct usb_device_qualifier_descriptor { - uint8_t bLength; /* Descriptor size in bytes = 10 */ - uint8_t bDescriptorType; /* DEVICE QUALIFIER type = 6 */ - uint16_t bcdUSB; /* USB spec in BCD, e.g. 0x0200 */ - uint8_t bDeviceClass; /* Class code, if 0 see interface */ - uint8_t bDeviceSubClass; /* Sub-Class code, 0 if class = 0 */ - uint8_t bDeviceProtocol; /* Protocol, if 0 see interface */ - uint8_t bMaxPacketSize; /* Endpoint 0 max. size */ - uint8_t bNumConfigurations; /* Number of possible configurations */ - uint8_t bReserved; /* Reserved = 0 */ -} __packed; - -/** Standard Configuration Descriptor */ -struct usb_configuration_descriptor { - uint8_t bLength; /* Descriptor size in bytes = 9 */ - uint8_t bDescriptorType; /* CONFIGURATION type = 2 or 7 */ - uint16_t wTotalLength; /* Length of concatenated descriptors */ - uint8_t bNumInterfaces; /* Number of interfaces, this config. */ - uint8_t bConfigurationValue; /* Value to set this config. */ - uint8_t iConfiguration; /* Index to configuration string */ - uint8_t bmAttributes; /* Config. characteristics */ - uint8_t bMaxPower; /* Max.power from bus, 2mA units */ -} __packed; - -/** Standard Interface Descriptor */ -struct usb_interface_descriptor { - uint8_t bLength; /* Descriptor size in bytes = 9 */ - uint8_t bDescriptorType; /* INTERFACE descriptor type = 4 */ - uint8_t bInterfaceNumber; /* Interface no.*/ - uint8_t bAlternateSetting; /* Value to select this IF */ - uint8_t bNumEndpoints; /* Number of endpoints excluding 0 */ - uint8_t bInterfaceClass; /* Class code, 0xFF = vendor */ - uint8_t bInterfaceSubClass; /* Sub-Class code, 0 if class = 0 */ - uint8_t bInterfaceProtocol; /* Protocol, 0xFF = vendor */ - uint8_t iInterface; /* Index to interface string */ -} __packed; - -/** Standard Endpoint Descriptor */ -struct usb_endpoint_descriptor { - uint8_t bLength; /* Descriptor size in bytes = 7 */ - uint8_t bDescriptorType; /* ENDPOINT descriptor type = 5 */ - uint8_t bEndpointAddress; /* Endpoint # 0 - 15 | IN/OUT */ - uint8_t bmAttributes; /* Transfer type */ - uint16_t wMaxPacketSize; /* Bits 10:0 = max. packet size */ - uint8_t bInterval; /* Polling interval in (micro) frames */ -} __packed; - -/** Unicode (UTF16LE) String Descriptor */ -struct usb_string_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint16_t bString; -} __packed; - -/* USB Interface Association Descriptor */ -struct usb_interface_association_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bFirstInterface; - uint8_t bInterfaceCount; - uint8_t bFunctionClass; - uint8_t bFunctionSubClass; - uint8_t bFunctionProtocol; - uint8_t iFunction; -} __packed; - -/* MS OS 1.0 string descriptor */ -struct usb_msosv1_string_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bString[14]; - uint8_t bMS_VendorCode; /* Vendor Code, used for a control request */ - uint8_t bPad; /* Padding byte for VendorCode look as UTF16 */ -} __packed; - -/* MS OS 1.0 Header descriptor */ -struct usb_msosv1_compat_id_header_descriptor { - uint32_t dwLength; - uint16_t bcdVersion; - uint16_t wIndex; - uint8_t bCount; - uint8_t reserved[7]; -} __packed; - -/* MS OS 1.0 Function descriptor */ -struct usb_msosv1_comp_id_function_descriptor { - uint8_t bFirstInterfaceNumber; - uint8_t reserved1; - uint8_t compatibleID[8]; - uint8_t subCompatibleID[8]; - uint8_t reserved2[6]; -} __packed; - -#define usb_msosv1_comp_id_create(x) \ - struct usb_msosv1_comp_id { \ - struct usb_msosv1_compat_id_header_descriptor compat_id_header; \ - struct usb_msosv1_comp_id_function_descriptor compat_id_function[x]; \ - }; - -struct usb_msosv1_descriptor { - uint8_t *string; - uint8_t string_len; - uint8_t vendor_code; - uint8_t *compat_id; - uint16_t compat_id_len; - uint8_t *comp_id_property; - uint16_t comp_id_property_len; -}; - -/* MS OS 2.0 Header descriptor */ -struct usb_msosv2_header_descriptor { - uint32_t dwLength; - uint16_t bcdVersion; - uint16_t wIndex; - uint8_t bCount; -} __packed; - -/*Microsoft OS 2.0 set header descriptor*/ -struct usb_msosv2_set_header_descriptor { - uint16_t wLength; - uint16_t wDescriptorType; - uint32_t dwWindowsVersion; - uint16_t wDescriptorSetTotalLength; -} __packed; - -/* Microsoft OS 2.0 compatibleID descriptor*/ -struct usb_msosv2_comp_id_descriptor { - uint16_t wLength; - uint16_t wDescriptorType; - uint8_t compatibleID[8]; - uint8_t subCompatibleID[8]; -} __packed; - -/* MS OS 2.0 property descriptor */ -struct usb_msosv2_property_descriptor { - uint16_t wLength; - uint16_t wDescriptorType; - uint32_t dwPropertyDataType; - uint16_t wPropertyNameLength; - const char *bPropertyName; - uint32_t dwPropertyDataLength; - const char *bPropertyData; -}; - -/* Microsoft OS 2.0 subset function descriptor */ -struct usb_msosv2_subset_function_descriptor { - uint16_t wLength; - uint16_t wDescriptorType; - uint8_t bFirstInterface; - uint8_t bReserved; - uint16_t wSubsetLength; -} __packed; - -struct usb_msosv2_descriptor { - uint8_t *compat_id; - uint16_t compat_id_len; - uint8_t vendor_code; -}; - -/* BOS header Descriptor */ -struct usb_bos_header_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint16_t wTotalLength; - uint8_t bNumDeviceCaps; -} __packed; - -/* BOS Capability platform Descriptor */ -struct usb_bos_capability_platform_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bDevCapabilityType; - uint8_t bReserved; - uint8_t PlatformCapabilityUUID[16]; -} __packed; - -/* BOS Capability MS OS Descriptors version 2 */ -struct usb_bos_capability_msosv2_descriptor { - uint32_t dwWindowsVersion; - uint16_t wMSOSDescriptorSetTotalLength; - uint8_t bVendorCode; - uint8_t bAltEnumCode; -} __packed; - -/* BOS Capability webusb */ -struct usb_bos_capability_webusb_descriptor { - uint16_t bcdVersion; - uint8_t bVendorCode; - uint8_t iLandingPage; -} __packed; - -/* BOS Capability extension Descriptor*/ -struct usb_bos_capability_extension_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bDevCapabilityType; - uint32_t bmAttributes; -} __packed; - -/* Microsoft OS 2.0 Platform Capability Descriptor -* See https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/ -* microsoft-defined-usb-descriptors -* Adapted from the source: -* https://github.com/sowbug/weblight/blob/master/firmware/webusb.c -* (BSD-2) Thanks http://janaxelson.com/files/ms_os_20_descriptors.c -*/ -struct usb_bos_capability_platform_msosv2_descriptor { - struct usb_bos_capability_platform_descriptor platform_msos; - struct usb_bos_capability_msosv2_descriptor data_msosv2; -} __packed; - -/* WebUSB Platform Capability Descriptor: -* https://wicg.github.io/webusb/#webusb-platform-capability-descriptor -*/ -struct usb_bos_capability_platform_webusb_descriptor { - struct usb_bos_capability_platform_descriptor platform_webusb; - struct usb_bos_capability_webusb_descriptor data_webusb; -} __packed; - -struct usb_webusb_url_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bScheme; - char URL[]; -} __packed; - -struct usb_bos_descriptor { - uint8_t *string; - uint32_t string_len; -}; - -/* USB Device Capability Descriptor */ -struct usb_device_capability_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bDevCapabilityType; -} __packed; - -/** USB descriptor header */ -struct usb_desc_header { - uint8_t bLength; /**< descriptor length */ - uint8_t bDescriptorType; /**< descriptor type */ -}; -// clang-format off -#define USB_DEVICE_DESCRIPTOR_INIT(bcdUSB, bDeviceClass, bDeviceSubClass, bDeviceProtocol, idVendor, idProduct, bcdDevice, bNumConfigurations) \ - 0x12, /* bLength */ \ - USB_DESCRIPTOR_TYPE_DEVICE, /* bDescriptorType */ \ - WBVAL(bcdUSB), /* bcdUSB */ \ - bDeviceClass, /* bDeviceClass */ \ - bDeviceSubClass, /* bDeviceSubClass */ \ - bDeviceProtocol, /* bDeviceProtocol */ \ - 0x40, /* bMaxPacketSize */ \ - WBVAL(idVendor), /* idVendor */ \ - WBVAL(idProduct), /* idProduct */ \ - WBVAL(bcdDevice), /* bcdDevice */ \ - USB_STRING_MFC_INDEX, /* iManufacturer */ \ - USB_STRING_PRODUCT_INDEX, /* iProduct */ \ - USB_STRING_SERIAL_INDEX, /* iSerial */ \ - bNumConfigurations /* bNumConfigurations */ - -#define USB_CONFIG_DESCRIPTOR_INIT(wTotalLength, bNumInterfaces, bConfigurationValue, bmAttributes, bMaxPower) \ - 0x09, /* bLength */ \ - USB_DESCRIPTOR_TYPE_CONFIGURATION, /* bDescriptorType */ \ - WBVAL(wTotalLength), /* wTotalLength */ \ - bNumInterfaces, /* bNumInterfaces */ \ - bConfigurationValue, /* bConfigurationValue */ \ - 0x00, /* iConfiguration */ \ - bmAttributes, /* bmAttributes */ \ - USB_CONFIG_POWER_MA(bMaxPower) /* bMaxPower */ - -#define USB_INTERFACE_DESCRIPTOR_INIT(bInterfaceNumber, bAlternateSetting, bNumEndpoints, \ - bInterfaceClass, bInterfaceSubClass, bInterfaceProtocol, iInterface) \ - 0x09, /* bLength */ \ - USB_DESCRIPTOR_TYPE_INTERFACE, /* bDescriptorType */ \ - bInterfaceNumber, /* bInterfaceNumber */ \ - bAlternateSetting, /* bAlternateSetting */ \ - bNumEndpoints, /* bNumEndpoints */ \ - bInterfaceClass, /* bInterfaceClass */ \ - bInterfaceSubClass, /* bInterfaceSubClass */ \ - bInterfaceProtocol, /* bInterfaceProtocol */ \ - iInterface /* iInterface */ - -#define USB_ENDPOINT_DESCRIPTOR_INIT(bEndpointAddress, bmAttributes, wMaxPacketSize, bInterval) \ - 0x07, /* bLength */ \ - USB_DESCRIPTOR_TYPE_ENDPOINT, /* bDescriptorType */ \ - bEndpointAddress, /* bEndpointAddress */ \ - bmAttributes, /* bmAttributes */ \ - WBVAL(wMaxPacketSize), /* wMaxPacketSize */ \ - bInterval /* bInterval */ - -#define USB_IAD_INIT(bFirstInterface, bInterfaceCount, bFunctionClass, bFunctionSubClass, bFunctionProtocol) \ - 0x08, /* bLength */ \ - USB_DESCRIPTOR_TYPE_INTERFACE_ASSOCIATION, /* bDescriptorType */ \ - bFirstInterface, /* bFirstInterface */ \ - bInterfaceCount, /* bInterfaceCount */ \ - bFunctionClass, /* bFunctionClass */ \ - bFunctionSubClass, /* bFunctionSubClass */ \ - bFunctionProtocol, /* bFunctionProtocol */ \ - 0x00 /* iFunction */ - -#define USB_LANGID_INIT(id) \ - 0x04, /* bLength */ \ - USB_DESCRIPTOR_TYPE_STRING, /* bDescriptorType */ \ - WBVAL(id) /* wLangID0 */ -// clang-format on -#endif \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_slist.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_slist.h deleted file mode 100644 index 357df1bede..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_slist.h +++ /dev/null @@ -1,224 +0,0 @@ -#ifndef __USB_SLIST_H__ -#define __USB_SLIST_H__ - -#include "string.h" -#include "stdint.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * usb_container_of - return the member address of ptr, if the type of ptr is the - * struct type. - */ -#define usb_container_of(ptr, type, member) \ - ((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member))) - -/** - * Single List structure - */ -struct usb_slist_node { - struct usb_slist_node *next; /**< point to next node. */ -}; -typedef struct usb_slist_node usb_slist_t; /**< Type for single list. */ - -/** - * @brief initialize a single list - * - * @param l the single list to be initialized - */ -static inline void usb_slist_init(usb_slist_t *l) -{ - l->next = NULL; -} - -static inline void usb_slist_add_head(usb_slist_t *l, usb_slist_t *n) -{ - n->next = l->next; - l->next = n; -} - -static inline void usb_slist_add_tail(usb_slist_t *l, usb_slist_t *n) -{ - while (l->next) { - l = l->next; - } - - /* append the node to the tail */ - l->next = n; - n->next = NULL; -} - -static inline void usb_slist_insert(usb_slist_t *l, usb_slist_t *next, usb_slist_t *n) -{ - if (!next) { - usb_slist_add_tail(next, l); - return; - } - - while (l->next) { - if (l->next == next) { - l->next = n; - n->next = next; - } - - l = l->next; - } -} - -static inline usb_slist_t *usb_slist_remove(usb_slist_t *l, usb_slist_t *n) -{ - /* remove slist head */ - while (l->next && l->next != n) { - l = l->next; - } - - /* remove node */ - if (l->next != (usb_slist_t *)0) { - l->next = l->next->next; - } - - return l; -} - -static inline unsigned int usb_slist_len(const usb_slist_t *l) -{ - unsigned int len = 0; - const usb_slist_t *list = l->next; - - while (list != NULL) { - list = list->next; - len++; - } - - return len; -} - -static inline unsigned int usb_slist_contains(usb_slist_t *l, usb_slist_t *n) -{ - while (l->next) { - if (l->next == n) { - return 0; - } - - l = l->next; - } - - return 1; -} - -static inline usb_slist_t *usb_slist_head(usb_slist_t *l) -{ - return l->next; -} - -static inline usb_slist_t *usb_slist_tail(usb_slist_t *l) -{ - while (l->next) { - l = l->next; - } - - return l; -} - -static inline usb_slist_t *usb_slist_next(usb_slist_t *n) -{ - return n->next; -} - -static inline int usb_slist_isempty(usb_slist_t *l) -{ - return l->next == NULL; -} - -/** - * @brief initialize a slist object - */ -#define USB_SLIST_OBJECT_INIT(object) \ - { \ - NULL \ - } - -/** - * @brief initialize a slist object - */ -#define USB_SLIST_DEFINE(slist) \ - usb_slist_t slist = { NULL } - -/** - * @brief get the struct for this single list node - * @param node the entry point - * @param type the type of structure - * @param member the name of list in structure - */ -#define usb_slist_entry(node, type, member) \ - usb_container_of(node, type, member) - -/** - * usb_slist_first_entry - get the first element from a slist - * @ptr: the slist head to take the element from. - * @type: the type of the struct this is embedded in. - * @member: the name of the slist_struct within the struct. - * - * Note, that slist is expected to be not empty. - */ -#define usb_slist_first_entry(ptr, type, member) \ - usb_slist_entry((ptr)->next, type, member) - -/** - * usb_slist_tail_entry - get the tail element from a slist - * @ptr: the slist head to take the element from. - * @type: the type of the struct this is embedded in. - * @member: the name of the slist_struct within the struct. - * - * Note, that slist is expected to be not empty. - */ -#define usb_slist_tail_entry(ptr, type, member) \ - usb_slist_entry(usb_slist_tail(ptr), type, member) - -/** - * usb_slist_first_entry_or_null - get the first element from a slist - * @ptr: the slist head to take the element from. - * @type: the type of the struct this is embedded in. - * @member: the name of the slist_struct within the struct. - * - * Note, that slist is expected to be not empty. - */ -#define usb_slist_first_entry_or_null(ptr, type, member) \ - (usb_slist_isempty(ptr) ? NULL : usb_slist_first_entry(ptr, type, member)) - -/** - * usb_slist_for_each - iterate over a single list - * @pos: the usb_slist_t * to use as a loop cursor. - * @head: the head for your single list. - */ -#define usb_slist_for_each(pos, head) \ - for (pos = (head)->next; pos != NULL; pos = pos->next) - -#define usb_slist_for_each_safe(pos, next, head) \ - for (pos = (head)->next, next = pos->next; pos; \ - pos = next, next = pos->next) - -/** - * usb_slist_for_each_entry - iterate over single list of given type - * @pos: the type * to use as a loop cursor. - * @head: the head for your single list. - * @member: the name of the list_struct within the struct. - */ -#define usb_slist_for_each_entry(pos, head, member) \ - for (pos = usb_slist_entry((head)->next, typeof(*pos), member); \ - &pos->member != (NULL); \ - pos = usb_slist_entry(pos->member.next, typeof(*pos), member)) - -#define usb_slist_for_each_entry_safe(pos, n, head, member) \ - for (pos = usb_slist_entry((head)->next, typeof(*pos), member), \ - n = usb_slist_entry(pos->member.next, typeof(*pos), member); \ - &pos->member != (NULL); \ - pos = n, n = usb_slist_entry(pos->member.next, typeof(*pos), member)) - -#ifdef __cplusplus -} -#endif - -#endif \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_util.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_util.h deleted file mode 100644 index 95e75cbac2..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_util.h +++ /dev/null @@ -1,150 +0,0 @@ -#ifndef _USB_UTIL_H -#define _USB_UTIL_H - -#include "stdbool.h" -#include "string.h" -#include "stdint.h" -#include "stdio.h" -#include "stdlib.h" -#include "usb_slist.h" -#include "bflb_platform.h" - -#ifndef __packed -#define __packed __attribute__((__packed__)) -#endif -#ifndef __aligned -#define __aligned(x) __attribute__((__aligned__(x))) -#endif -#define __may_alias __attribute__((__may_alias__)) -#ifndef __printf_like -#define __printf_like(f, a) __attribute__((format(printf, f, a))) -#endif -#define __used __attribute__((__used__)) -#ifndef __deprecated -#define __deprecated __attribute__((deprecated)) -#endif -#define ARG_UNUSED(x) (void)(x) - -// #define likely(x) __builtin_expect((bool)!!(x), true) -// #define unlikely(x) __builtin_expect((bool)!!(x), false) - -#define popcount(x) __builtin_popcount(x) - -#ifndef __no_optimization -#define __no_optimization __attribute__((optimize("-O0"))) -#endif - -#ifndef __weak -#define __weak __attribute__((__weak__)) -#endif -#define __unused __attribute__((__unused__)) - -#ifndef __ALIGN_BEGIN -#define __ALIGN_BEGIN -#endif -#ifndef __ALIGN_END -#define __ALIGN_END __attribute__((aligned(4))) -#endif - -#ifndef LO_BYTE -#define LO_BYTE(x) ((uint8_t)(x & 0x00FF)) -#endif - -#ifndef HI_BYTE -#define HI_BYTE(x) ((uint8_t)((x & 0xFF00) >> 8)) -#endif - -/** - * @def MAX - * @brief The larger value between @p a and @p b. - * @note Arguments are evaluated twice. - */ -#ifndef MAX -/* Use Z_MAX for a GCC-only, single evaluation version */ -#define MAX(a, b) (((a) > (b)) ? (a) : (b)) -#endif - -/** - * @def MIN - * @brief The smaller value between @p a and @p b. - * @note Arguments are evaluated twice. - */ -#ifndef MIN -/* Use Z_MIN for a GCC-only, single evaluation version */ -#define MIN(a, b) (((a) < (b)) ? (a) : (b)) -#endif - -#ifndef BCD -#define BCD(x) ((((x) / 10) << 4) | ((x) % 10)) -#endif - -#ifdef BIT -#undef BIT -#define BIT(n) (1UL << (n)) -#else -#define BIT(n) (1UL << (n)) -#endif - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(array) \ - ((int)((sizeof(array) / sizeof((array)[0])))) -#endif - -#ifndef BSWAP16 -#define BSWAP16(u16) (__builtin_bswap16(u16)) -#endif -#ifndef BSWAP32 -#define BSWAP32(u32) (__builtin_bswap32(u32)) -#endif - -#define GET_BE16(field) \ - (((uint16_t)(field)[0] << 8) | ((uint16_t)(field)[1])) - -#define GET_BE32(field) \ - (((uint32_t)(field)[0] << 24) | ((uint32_t)(field)[1] << 16) | ((uint32_t)(field)[2] << 8) | ((uint32_t)(field)[3] << 0)) - -#define SET_BE16(field, value) \ - do { \ - (field)[0] = (uint8_t)((value) >> 8); \ - (field)[1] = (uint8_t)((value) >> 0); \ - } while (0) - -#define SET_BE24(field, value) \ - do { \ - (field)[0] = (uint8_t)((value) >> 16); \ - (field)[1] = (uint8_t)((value) >> 8); \ - (field)[2] = (uint8_t)((value) >> 0); \ - } while (0) - -#define SET_BE32(field, value) \ - do { \ - (field)[0] = (uint8_t)((value) >> 24); \ - (field)[1] = (uint8_t)((value) >> 16); \ - (field)[2] = (uint8_t)((value) >> 8); \ - (field)[3] = (uint8_t)((value) >> 0); \ - } while (0) - -#define REQTYPE_GET_DIR(x) (((x) >> 7) & 0x01) -#define REQTYPE_GET_TYPE(x) (((x) >> 5) & 0x03U) -#define REQTYPE_GET_RECIP(x) ((x)&0x1F) - -#define GET_DESC_TYPE(x) (((x) >> 8) & 0xFFU) -#define GET_DESC_INDEX(x) ((x)&0xFFU) - -#define WBVAL(x) (x & 0xFF), ((x >> 8) & 0xFF) -#define DBVAL(x) (x & 0xFF), ((x >> 8) & 0xFF), ((x >> 16) & 0xFF), ((x >> 24) & 0xFF) - -#define USB_DESC_SECTION __attribute__((section("usb_desc"))) __used __aligned(1) - -#if 0 -#define USBD_LOG_WRN(a, ...) bflb_platform_printf(a, ##__VA_ARGS__) -#define USBD_LOG_DBG(a, ...) bflb_platform_printf(a, ##__VA_ARGS__) -#define USBD_LOG_ERR(a, ...) bflb_platform_printf(a, ##__VA_ARGS__) -#else -#define USBD_LOG_INFO(a, ...) bflb_platform_printf(a, ##__VA_ARGS__) -#define USBD_LOG_DBG(a, ...) -#define USBD_LOG_WRN(a, ...) bflb_platform_printf(a, ##__VA_ARGS__) -#define USBD_LOG_ERR(a, ...) bflb_platform_printf(a, ##__VA_ARGS__) -#endif - -#endif \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.c deleted file mode 100644 index 99e0072b3c..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.c +++ /dev/null @@ -1,1184 +0,0 @@ -/** - * @file usbd_core.c - * @brief - * - * Copyright (c) 2021 Bouffalolab team - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - */ -#include "usbd_core.h" -#include "usbd_winusb.h" - -#define USBD_EP_CALLBACK_LIST_SEARCH 0 -#define USBD_EP_CALLBACK_ARR_SEARCH 1 -#define USBD_EP_CALLBACK_SEARCH_METHOD USBD_EP_CALLBACK_ARR_SEARCH - -/* general descriptor field offsets */ -#define DESC_bLength 0 /** Length offset */ -#define DESC_bDescriptorType 1 /** Descriptor type offset */ - -/* config descriptor field offsets */ -#define CONF_DESC_wTotalLength 2 /** Total length offset */ -#define CONF_DESC_bConfigurationValue 5 /** Configuration value offset */ -#define CONF_DESC_bmAttributes 7 /** configuration characteristics */ - -/* interface descriptor field offsets */ -#define INTF_DESC_bInterfaceNumber 2 /** Interface number offset */ -#define INTF_DESC_bAlternateSetting 3 /** Alternate setting offset */ - -#define USB_REQUEST_BUFFER_SIZE 256 -#define USB_EP_OUT_NUM 8 -#define USB_EP_IN_NUM 8 - -static struct usbd_core_cfg_priv { - /** Setup packet */ - struct usb_setup_packet setup; - /** Pointer to data buffer */ - uint8_t *ep0_data_buf; - /** Remaining bytes in buffer */ - uint32_t ep0_data_buf_residue; - /** Total length of control transfer */ - uint32_t ep0_data_buf_len; - /** Zero length packet flag of control transfer */ - bool zlp_flag; - /** Pointer to registered descriptors */ - const uint8_t *descriptors; - /* Buffer used for storing standard, class and vendor request data */ - uint8_t req_data[USB_REQUEST_BUFFER_SIZE]; - -#if USBD_EP_CALLBACK_SEARCH_METHOD == 1 - usbd_endpoint_callback in_ep_cb[USB_EP_IN_NUM]; - usbd_endpoint_callback out_ep_cb[USB_EP_OUT_NUM]; -#endif - /** Variable to check whether the usb has been enabled */ - bool enabled; - /** Variable to check whether the usb has been configured */ - bool configured; - /** Currently selected configuration */ - uint8_t configuration; - /** Remote wakeup feature status */ - uint16_t remote_wakeup; - uint8_t reserved; -} usbd_core_cfg; - -static usb_slist_t usbd_class_head = USB_SLIST_OBJECT_INIT(usbd_class_head); -static struct usb_msosv1_descriptor *msosv1_desc; -static struct usb_msosv2_descriptor *msosv2_desc; -static struct usb_bos_descriptor *bos_desc; - -/** - * @brief print the contents of a setup packet - * - * @param [in] setup The setup packet - * - */ -static void usbd_print_setup(struct usb_setup_packet *setup) { - USBD_LOG_INFO("Setup: " - "bmRequestType 0x%02x, bRequest 0x%02x, wValue 0x%04x, wIndex 0x%04x, wLength 0x%04x\r\n", - setup->bmRequestType, setup->bRequest, setup->wValue, setup->wIndex, setup->wLength); -} - -/** - * @brief Check if the device is in Configured state - * - * @return true if Configured, false otherwise. - */ -static bool is_device_configured(void) { return (usbd_core_cfg.configuration != 0); } -/** - * @brief Check if the interface of given number is valid - * - * @param [in] interface Number of the addressed interface - * - * This function searches through descriptor and checks - * is the Host has addressed valid interface. - * - * @return true if interface exists - valid - */ -static bool is_interface_valid(uint8_t interface) { - const uint8_t *p = (uint8_t *)usbd_core_cfg.descriptors; - const struct usb_configuration_descriptor *cfg_descr; - - /* Search through descriptor for matching interface */ - while (p[DESC_bLength] != 0U) { - if (p[DESC_bDescriptorType] == USB_DESCRIPTOR_TYPE_CONFIGURATION) { - cfg_descr = (const struct usb_configuration_descriptor *)p; - - if (interface < cfg_descr->bNumInterfaces) { - return true; - } - } - - p += p[DESC_bLength]; - } - - return false; -} -/** - * @brief Check if the endpoint of given address is valid - * - * @param [in] ep Address of the Endpoint - * - * This function checks if the Endpoint of given address - * is valid for the configured device. Valid Endpoint is - * either Control Endpoint or one used by the device. - * - * @return true if endpoint exists - valid - */ -static bool is_ep_valid(uint8_t ep) { - /* Check if its Endpoint 0 */ - if ((ep & 0x7f) == 0) { - return true; - } - - return true; -} -#if USBD_EP_CALLBACK_SEARCH_METHOD == 1 -static void usbd_ep_callback_register(void) { - usb_slist_t *i, *j, *k; - usb_slist_for_each(i, &usbd_class_head) { - usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list); - - usb_slist_for_each(j, &class->intf_list) { - usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list); - - usb_slist_for_each(k, &intf->ep_list) { - usbd_endpoint_t *ept = usb_slist_entry(k, struct usbd_endpoint, list); - - if (ept->ep_cb) { - if (ept->ep_addr & 0x80) { - usbd_core_cfg.in_ep_cb[ept->ep_addr & 0x7f] = ept->ep_cb; - } else { - usbd_core_cfg.out_ep_cb[ept->ep_addr & 0x7f] = ept->ep_cb; - } - } - } - } - } -} -#endif -/** - * @brief configure and enable endpoint - * - * This function sets endpoint configuration according to one specified in USB - * endpoint descriptor and then enables it for data transfers. - * - * @param [in] ep_desc Endpoint descriptor byte array - * - * @return true if successfully configured and enabled - */ -static bool usbd_set_endpoint(const struct usb_endpoint_descriptor *ep_desc) { - struct usbd_endpoint_cfg ep_cfg; - - ep_cfg.ep_addr = ep_desc->bEndpointAddress; - ep_cfg.ep_mps = ep_desc->wMaxPacketSize; - ep_cfg.ep_type = ep_desc->bmAttributes & USBD_EP_TYPE_MASK; - - USBD_LOG_INFO("Open endpoint:0x%x type:%u mps:%u\r\n", ep_cfg.ep_addr, ep_cfg.ep_type, ep_cfg.ep_mps); - - usbd_ep_open(&ep_cfg); - usbd_core_cfg.configured = true; - - return true; -} -/** - * @brief Disable endpoint for transferring data - * - * This function cancels transfers that are associated with endpoint and - * disabled endpoint itself. - * - * @param [in] ep_desc Endpoint descriptor byte array - * - * @return true if successfully deconfigured and disabled - */ -static bool usbd_reset_endpoint(const struct usb_endpoint_descriptor *ep_desc) { - struct usbd_endpoint_cfg ep_cfg; - - ep_cfg.ep_addr = ep_desc->bEndpointAddress; - ep_cfg.ep_mps = ep_desc->wMaxPacketSize; - ep_cfg.ep_type = ep_desc->bmAttributes & USBD_EP_TYPE_MASK; - - USBD_LOG_INFO("Close endpoint:0x%x type:%u\r\n", ep_cfg.ep_addr, ep_cfg.ep_type); - - usbd_ep_close(ep_cfg.ep_addr); - - return true; -} - -/** - * @brief get specified USB descriptor - * - * This function parses the list of installed USB descriptors and attempts - * to find the specified USB descriptor. - * - * @param [in] type_index Type and index of the descriptor - * @param [in] lang_id Language ID of the descriptor (currently unused) - * @param [out] len Descriptor length - * @param [out] data Descriptor data - * - * @return true if the descriptor was found, false otherwise - */ -static bool usbd_get_descriptor(uint16_t type_index, uint8_t **data, uint32_t *len) { - uint8_t type = 0U; - uint8_t index = 0U; - uint8_t *p = NULL; - uint32_t cur_index = 0U; - bool found = false; - - type = GET_DESC_TYPE(type_index); - index = GET_DESC_INDEX(type_index); - - if ((type == USB_DESCRIPTOR_TYPE_STRING) && (index == USB_OSDESC_STRING_DESC_INDEX)) { - USBD_LOG_INFO("read MS OS 2.0 descriptor string\r\n"); - - if (!msosv1_desc) { - return false; - } - - *data = (uint8_t *)msosv1_desc->string; - *len = msosv1_desc->string_len; - - return true; - } else if (type == USB_DESCRIPTOR_TYPE_BINARY_OBJECT_STORE) { - USBD_LOG_INFO("read BOS descriptor string\r\n"); - - if (!bos_desc) { - return false; - } - - *data = bos_desc->string; - *len = bos_desc->string_len; - return true; - } - /* - * Invalid types of descriptors, - * see USB Spec. Revision 2.0, 9.4.3 Get Descriptor - */ - else if ((type == USB_DESCRIPTOR_TYPE_INTERFACE) || (type == USB_DESCRIPTOR_TYPE_ENDPOINT) || -#ifndef CONFIG_USB_HS - (type > USB_DESCRIPTOR_TYPE_ENDPOINT)) { -#else - (type > USB_DESCRIPTOR_TYPE_OTHER_SPEED)) { -#endif - return false; - } - - p = (uint8_t *)usbd_core_cfg.descriptors; - - cur_index = 0U; - - while (p[DESC_bLength] != 0U) { - if (p[DESC_bDescriptorType] == type) { - if (cur_index == index) { - found = true; - break; - } - - cur_index++; - } - - /* skip to next descriptor */ - p += p[DESC_bLength]; - } - - if (found) { - /* set data pointer */ - *data = p; - - /* get length from structure */ - if (type == USB_DESCRIPTOR_TYPE_CONFIGURATION) { - /* configuration descriptor is an - * exception, length is at offset - * 2 and 3 - */ - *len = (p[CONF_DESC_wTotalLength]) | (p[CONF_DESC_wTotalLength + 1] << 8); - } else { - /* normally length is at offset 0 */ - *len = p[DESC_bLength]; - } - } else { - /* nothing found */ - USBD_LOG_ERR("descriptor not found!\r\n", type, index); - } - - return found; -} - -/** - * @brief set USB configuration - * - * This function configures the device according to the specified configuration - * index and alternate setting by parsing the installed USB descriptor list. - * A configuration index of 0 unconfigures the device. - * - * @param [in] config_index Configuration index - * @param [in] alt_setting Alternate setting number - * - * @return true if successfully configured false if error or unconfigured - */ -static bool usbd_set_configuration(uint8_t config_index, uint8_t alt_setting) { - uint8_t *p = (uint8_t *)usbd_core_cfg.descriptors; - uint8_t cur_alt_setting = 0xFF; - uint8_t cur_config = 0xFF; - bool found = false; - - if (config_index == 0U) { - /* TODO: unconfigure device */ - USBD_LOG_ERR("Device not configured - invalid configuration\r\n"); - return true; - } - - /* configure endpoints for this configuration/altsetting */ - while (p[DESC_bLength] != 0U) { - switch (p[DESC_bDescriptorType]) { - case USB_DESCRIPTOR_TYPE_CONFIGURATION: - /* remember current configuration index */ - cur_config = p[CONF_DESC_bConfigurationValue]; - - if (cur_config == config_index) { - found = true; - } - - break; - - case USB_DESCRIPTOR_TYPE_INTERFACE: - /* remember current alternate setting */ - cur_alt_setting = p[INTF_DESC_bAlternateSetting]; - break; - - case USB_DESCRIPTOR_TYPE_ENDPOINT: - if ((cur_config != config_index) || (cur_alt_setting != alt_setting)) { - break; - } - - found = usbd_set_endpoint((struct usb_endpoint_descriptor *)p); - break; - - default: - break; - } - - /* skip to next descriptor */ - p += p[DESC_bLength]; - } - - return found; -} - -/** - * @brief set USB interface - * - * @param [in] iface Interface index - * @param [in] alt_setting Alternate setting number - * - * @return true if successfully configured false if error or unconfigured - */ -static bool usbd_set_interface(uint8_t iface, uint8_t alt_setting) { - const uint8_t *p = usbd_core_cfg.descriptors; - const uint8_t *if_desc = NULL; - struct usb_endpoint_descriptor *ep_desc; - uint8_t cur_alt_setting = 0xFF; - uint8_t cur_iface = 0xFF; - bool ret = false; - - USBD_LOG_DBG("iface %u alt_setting %u\r\n", iface, alt_setting); - - while (p[DESC_bLength] != 0U) { - switch (p[DESC_bDescriptorType]) { - case USB_DESCRIPTOR_TYPE_INTERFACE: - /* remember current alternate setting */ - cur_alt_setting = p[INTF_DESC_bAlternateSetting]; - cur_iface = p[INTF_DESC_bInterfaceNumber]; - - if (cur_iface == iface && cur_alt_setting == alt_setting) { - if_desc = (void *)p; - } - - USBD_LOG_DBG("Current iface %u alt setting %u", cur_iface, cur_alt_setting); - break; - - case USB_DESCRIPTOR_TYPE_ENDPOINT: - if (cur_iface == iface) { - ep_desc = (struct usb_endpoint_descriptor *)p; - - if (cur_alt_setting != alt_setting) { - ret = usbd_reset_endpoint(ep_desc); - } else { - ret = usbd_set_endpoint(ep_desc); - } - } - - break; - - default: - break; - } - - /* skip to next descriptor */ - p += p[DESC_bLength]; - } - - usbd_event_notify_handler(USB_EVENT_SET_INTERFACE, (void *)if_desc); - - return ret; -} - -/** - * @brief handle a standard device request - * - * @param [in] setup The setup packet - * @param [in,out] len Pointer to data length - * @param [in,out] ep0_data_buf Data buffer - * - * @return true if the request was handled successfully - */ -static bool usbd_std_device_req_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) { - uint16_t value = setup->wValue; - // uint16_t index = setup->wIndex; - bool ret = true; - - switch (setup->bRequest) { - case USB_REQUEST_GET_STATUS: - USBD_LOG_DBG("REQ_GET_STATUS\r\n"); - /* bit 0: self-powered */ - /* bit 1: remote wakeup */ - *data = (uint8_t *)&usbd_core_cfg.remote_wakeup; - - *len = 2; - break; - - case USB_REQUEST_CLEAR_FEATURE: - USBD_LOG_DBG("REQ_CLEAR_FEATURE\r\n"); - ret = false; - - if (value == USB_FEATURE_REMOTE_WAKEUP) { - usbd_core_cfg.remote_wakeup = 0; - usbd_event_notify_handler(USB_EVENT_CLEAR_REMOTE_WAKEUP, NULL); - ret = true; - } - - break; - - case USB_REQUEST_SET_FEATURE: - USBD_LOG_DBG("REQ_SET_FEATURE\r\n"); - ret = false; - - if (value == USB_FEATURE_REMOTE_WAKEUP) { - usbd_core_cfg.remote_wakeup = 1; - usbd_event_notify_handler(USB_EVENT_SET_REMOTE_WAKEUP, NULL); - ret = true; - } - - if (value == USB_FEATURE_TEST_MODE) { - /* put TEST_MODE code here */ - } - - break; - - case USB_REQUEST_SET_ADDRESS: - USBD_LOG_DBG("REQ_SET_ADDRESS, addr 0x%x\r\n", value); - usbd_set_address(value); - break; - - case USB_REQUEST_GET_DESCRIPTOR: - USBD_LOG_DBG("REQ_GET_DESCRIPTOR\r\n"); - ret = usbd_get_descriptor(value, data, len); - break; - - case USB_REQUEST_SET_DESCRIPTOR: - USBD_LOG_DBG("Device req 0x%02x not implemented\r\n", setup->bRequest); - ret = false; - break; - - case USB_REQUEST_GET_CONFIGURATION: - USBD_LOG_DBG("REQ_GET_CONFIGURATION\r\n"); - /* indicate if we are configured */ - *data = (uint8_t *)&usbd_core_cfg.configuration; - *len = 1; - break; - - case USB_REQUEST_SET_CONFIGURATION: - value &= 0xFF; - USBD_LOG_DBG("REQ_SET_CONFIGURATION, conf 0x%x\r\n", value); - - if (!usbd_set_configuration(value, 0)) { - USBD_LOG_DBG("USB Set Configuration failed\r\n"); - ret = false; - } else { - /* configuration successful, - * update current configuration - */ - usbd_core_cfg.configuration = value; - usbd_event_notify_handler(USB_EVENT_CONFIGURED, NULL); - } - - break; - - case USB_REQUEST_GET_INTERFACE: - break; - - case USB_REQUEST_SET_INTERFACE: - break; - - default: - USBD_LOG_ERR("Illegal device req 0x%02x\r\n", setup->bRequest); - ret = false; - break; - } - - return ret; -} - -/** - * @brief handle a standard interface request - * - * @param [in] setup The setup packet - * @param [in,out] len Pointer to data length - * @param [in] ep0_data_buf Data buffer - * - * @return true if the request was handled successfully - */ -static bool usbd_std_interface_req_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) { - /** The device must be configured to accept standard interface - * requests and the addressed Interface must be valid. - */ - if (!is_device_configured() || (!is_interface_valid((uint8_t)setup->wIndex))) { - return false; - } - - switch (setup->bRequest) { - case USB_REQUEST_GET_STATUS: - /* no bits specified */ - *data = (uint8_t *)&usbd_core_cfg.remote_wakeup; - - *len = 2; - break; - - case USB_REQUEST_CLEAR_FEATURE: - case USB_REQUEST_SET_FEATURE: - /* not defined for interface */ - return false; - - case USB_REQUEST_GET_INTERFACE: - /** This handler is called for classes that does not support - * alternate Interfaces so always return 0. Classes that - * support alternative interfaces handles GET_INTERFACE - * in custom_handler. - */ - *data = (uint8_t *)&usbd_core_cfg.reserved; - - *len = 1; - break; - - case USB_REQUEST_SET_INTERFACE: - USBD_LOG_DBG("REQ_SET_INTERFACE\r\n"); - usbd_set_interface(setup->wIndex, setup->wValue); - break; - - default: - USBD_LOG_ERR("Illegal interface req 0x%02x\r\n", setup->bRequest); - return false; - } - - return true; -} - -/** - * @brief handle a standard endpoint request - * - * @param [in] setup The setup packet - * @param [in,out] len Pointer to data length - * @param [in] ep0_data_buf Data buffer - * - * @return true if the request was handled successfully - */ -static bool usbd_std_endpoint_req_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) { - uint8_t ep = (uint8_t)setup->wIndex; - - /* Check if request addresses valid Endpoint */ - if (!is_ep_valid(ep)) { - return false; - } - - switch (setup->bRequest) { - case USB_REQUEST_GET_STATUS: - - /** This request is valid for Control Endpoints when - * the device is not yet configured. For other - * Endpoints the device must be configured. - * Firstly check if addressed ep is Control Endpoint. - * If no then the device must be in Configured state - * to accept the request. - */ - if (((ep & 0x7f) == 0) || is_device_configured()) { - /* bit 0 - Endpoint halted or not */ - usbd_ep_is_stalled(ep, (uint8_t *)&usbd_core_cfg.remote_wakeup); - *data = (uint8_t *)&usbd_core_cfg.remote_wakeup; - - *len = 2; - break; - } - - return false; - - case USB_REQUEST_CLEAR_FEATURE: - if (setup->wValue == USB_FEATURE_ENDPOINT_STALL) { - /** This request is valid for Control Endpoints when - * the device is not yet configured. For other - * Endpoints the device must be configured. - * Firstly check if addressed ep is Control Endpoint. - * If no then the device must be in Configured state - * to accept the request. - */ - if (((ep & 0x7f) == 0) || is_device_configured()) { - USBD_LOG_ERR("ep:%x clear halt\r\n", ep); - usbd_ep_clear_stall(ep); - usbd_event_notify_handler(USB_EVENT_CLEAR_HALT, NULL); - break; - } - } - - /* only ENDPOINT_HALT defined for endpoints */ - return false; - - case USB_REQUEST_SET_FEATURE: - if (setup->wValue == USB_FEATURE_ENDPOINT_STALL) { - /** This request is valid for Control Endpoints when - * the device is not yet configured. For other - * Endpoints the device must be configured. - * Firstly check if addressed ep is Control Endpoint. - * If no then the device must be in Configured state - * to accept the request. - */ - if (((ep & 0x7f) == 0) || is_device_configured()) { - /* set HALT by stalling */ - USBD_LOG_ERR("ep:%x set halt\r\n", ep); - usbd_ep_set_stall(ep); - usbd_event_notify_handler(USB_EVENT_SET_HALT, NULL); - break; - } - } - - /* only ENDPOINT_HALT defined for endpoints */ - return false; - - case USB_REQUEST_SYNCH_FRAME: - - /* For Synch Frame request the device must be configured */ - if (is_device_configured()) { - /* Not supported, return false anyway */ - USBD_LOG_DBG("ep req 0x%02x not implemented\r\n", setup->bRequest); - } - - return false; - - default: - USBD_LOG_ERR("Illegal ep req 0x%02x\r\n", setup->bRequest); - return false; - } - - return true; -} - -/** - * @brief default handler for standard ('chapter 9') requests - * - * If a custom request handler was installed, this handler is called first. - * - * @param [in] setup The setup packet - * @param [in] ep0_data_buf Data buffer - * @param [in,out] len Pointer to data length - * - * @return true if the request was handled successfully - */ -static int usbd_standard_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) { - int rc = 0; - - switch (setup->bmRequestType_b.Recipient) { - case USB_REQUEST_TO_DEVICE: - if (usbd_std_device_req_handler(setup, data, len) == false) { - rc = -1; - } - - break; - - case USB_REQUEST_TO_INTERFACE: - if (usbd_std_interface_req_handler(setup, data, len) == false) { - rc = -1; - } - - break; - - case USB_REQUEST_TO_ENDPOINT: - if (usbd_std_endpoint_req_handler(setup, data, len) == false) { - rc = -1; - } - - break; - - default: - rc = -1; - } - - return rc; -} - -/* - * The functions usbd_class_request_handler(), usbd_custom_request_handler() and usbd_vendor_request_handler() - * go through the interfaces one after the other and compare the - * bInterfaceNumber with the wIndex and and then call the appropriate - * callback of the USB function. - * Note, a USB function can have more than one interface and the - * request does not have to be directed to the first interface (unlikely). - * These functions can be simplified and moved to usb_handle_request() - * when legacy initialization throgh the usb_set_config() and - * usb_enable() is no longer needed. - */ -static int usbd_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) { - USBD_LOG_DBG("bRequest 0x%02x, wIndex 0x%04x\r\n", setup->bRequest, setup->wIndex); - - if (setup->bmRequestType_b.Recipient != USB_REQUEST_TO_INTERFACE) { - return -1; - } - - usb_slist_t *i, *j; - usb_slist_for_each(i, &usbd_class_head) { - usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list); - - usb_slist_for_each(j, &class->intf_list) { - usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list); - - if (intf->class_handler && (intf->intf_num == (setup->wIndex & 0xFF))) { - return intf->class_handler(setup, data, len); - } - } - } - return -1; -} - -static int usbd_vendor_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) { - USBD_LOG_DBG("bRequest 0x%02x, wValue0x%04x, wIndex 0x%04x\r\n", setup->bRequest, setup->wValue, setup->wIndex); - - // if(setup->bmRequestType_b.Recipient != USB_REQUEST_TO_DEVICE) - // { - // return -1; - // } - - if (msosv1_desc) { - if (setup->bRequest == msosv1_desc->vendor_code) { - switch (setup->wIndex) { - case 0x04: - USBD_LOG_INFO("get Compat ID\r\n"); - *data = (uint8_t *)msosv1_desc->compat_id; - *len = msosv1_desc->compat_id_len; - - return 0; - case 0x05: - USBD_LOG_INFO("get Compat id properties\r\n"); - *data = (uint8_t *)msosv1_desc->comp_id_property; - *len = msosv1_desc->comp_id_property_len; - - return 0; - default: - USBD_LOG_ERR("unknown vendor code\r\n"); - return -1; - } - } - } else if (msosv2_desc) { - if (setup->bRequest == msosv2_desc->vendor_code) { - switch (setup->wIndex) { - case WINUSB_REQUEST_GET_DESCRIPTOR_SET: - USBD_LOG_INFO("GET MS OS 2.0 Descriptor\r\n"); - *data = (uint8_t *)msosv2_desc->compat_id; - *len = msosv2_desc->compat_id_len; - return 0; - default: - USBD_LOG_ERR("unknown vendor code\r\n"); - return -1; - } - } - } - - usb_slist_t *i, *j; - - usb_slist_for_each(i, &usbd_class_head) { - usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list); - - usb_slist_for_each(j, &class->intf_list) { - usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list); - - if (intf->vendor_handler && !intf->vendor_handler(setup, data, len)) { - return 0; - } - } - } - - return -1; -} - -static int usbd_custom_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) { - USBD_LOG_DBG("bRequest 0x%02x, wIndex 0x%04x\r\n", setup->bRequest, setup->wIndex); - - if (setup->bmRequestType_b.Recipient != USB_REQUEST_TO_INTERFACE) { - return -1; - } - - usb_slist_t *i, *j; - usb_slist_for_each(i, &usbd_class_head) { - usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list); - - usb_slist_for_each(j, &class->intf_list) { - usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list); - - if (intf->custom_handler && (intf->intf_num == (setup->wIndex & 0xFF))) { - return intf->custom_handler(setup, data, len); - } - } - } - - return -1; -} - -/** - * @brief handle a request by calling one of the installed request handlers - * - * Local function to handle a request by calling one of the installed request - * handlers. In case of data going from host to device, the data is at *ppbData. - * In case of data going from device to host, the handler can either choose to - * write its data at *ppbData or update the data pointer. - * - * @param [in] setup The setup packet - * @param [in,out] data Data buffer - * @param [in,out] len Pointer to data length - * - * @return true if the request was handles successfully - */ -static bool usbd_setup_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len) { - uint8_t type = setup->bmRequestType_b.Type; - - if (type == USB_REQUEST_STANDARD) { - if (!usbd_custom_request_handler(setup, data, len)) { - return true; - } - - if (usbd_standard_request_handler(setup, data, len) < 0) { - USBD_LOG_ERR("Handler Error %d\r\n", type); - usbd_print_setup(setup); - return false; - } - } else if (type == USB_REQUEST_CLASS) { - if (usbd_class_request_handler(setup, data, len) < 0) { - USBD_LOG_ERR("Handler Error %d\r\n", type); - usbd_print_setup(setup); - return false; - } - } else if (type == USB_REQUEST_VENDOR) { - if (usbd_vendor_request_handler(setup, data, len) < 0) { - USBD_LOG_ERR("Handler Error %d\r\n", type); - usbd_print_setup(setup); - return false; - } - } else { - return false; - } - - return true; -} -/** - * @brief send data or status to host - * - * @return N/A - */ -static void usbd_send_to_host(uint16_t len) { - uint32_t chunk = 0U; - - if (usbd_core_cfg.zlp_flag == false) { - chunk = usbd_core_cfg.ep0_data_buf_residue; - - if (usbd_ep_write(USB_CONTROL_IN_EP0, usbd_core_cfg.ep0_data_buf, usbd_core_cfg.ep0_data_buf_residue, &chunk) < 0) { - USBD_LOG_ERR("USB write data failed\r\n"); - return; - } - - usbd_core_cfg.ep0_data_buf += chunk; - usbd_core_cfg.ep0_data_buf_residue -= chunk; - - /* - * Set ZLP flag when host asks for a bigger length and the - * last chunk is wMaxPacketSize long, to indicate the last - * packet. - */ - if ((!usbd_core_cfg.ep0_data_buf_residue) && (usbd_core_cfg.ep0_data_buf_len >= USB_CTRL_EP_MPS) && !(usbd_core_cfg.ep0_data_buf_len % USB_CTRL_EP_MPS)) { - /* Transfers a zero-length packet next*/ - usbd_core_cfg.zlp_flag = true; - } - } else { - usbd_core_cfg.zlp_flag = false; - USBD_LOG_DBG("send zlp\r\n"); - if (usbd_ep_write(USB_CONTROL_IN_EP0, NULL, 0, NULL) < 0) { - USBD_LOG_ERR("USB write zlp failed\r\n"); - return; - } - } -} - -static void usbd_ep0_setup_handler(void) { - struct usb_setup_packet *setup = &usbd_core_cfg.setup; - - /* - * OUT transfer, Setup packet, - * reset request message state machine - */ - if (usbd_ep_read(USB_CONTROL_OUT_EP0, (uint8_t *)setup, sizeof(struct usb_setup_packet), NULL) < 0) { - USBD_LOG_ERR("Read Setup Packet failed\r\n"); - usbd_ep_set_stall(USB_CONTROL_IN_EP0); - return; - } - - // usbd_print_setup(setup); - - if (setup->wLength > USB_REQUEST_BUFFER_SIZE) { - if (setup->bmRequestType_b.Dir != USB_REQUEST_DEVICE_TO_HOST) { - USBD_LOG_ERR("Request buffer too small\r\n"); - usbd_ep_set_stall(USB_CONTROL_IN_EP0); - return; - } - } - - // usbd_core_cfg.ep0_data_buf = usbd_core_cfg.req_data; - usbd_core_cfg.ep0_data_buf_residue = setup->wLength; - usbd_core_cfg.ep0_data_buf_len = setup->wLength; - usbd_core_cfg.zlp_flag = false; - - /* this maybe set code in class request code */ - if (setup->wLength && setup->bmRequestType_b.Dir == USB_REQUEST_HOST_TO_DEVICE) { - USBD_LOG_DBG("prepare to out data\r\n"); - return; - } - - /* Ask installed handler to process request */ - if (!usbd_setup_request_handler(setup, &usbd_core_cfg.ep0_data_buf, &usbd_core_cfg.ep0_data_buf_len)) { - USBD_LOG_ERR("usbd_setup_request_handler failed\r\n"); - usbd_ep_set_stall(USB_CONTROL_IN_EP0); - return; - } - - /* Send smallest of requested and offered length */ - usbd_core_cfg.ep0_data_buf_residue = MIN(usbd_core_cfg.ep0_data_buf_len, setup->wLength); - /*Send data or status to host*/ - usbd_send_to_host(setup->wLength); -} - -static void usbd_ep0_out_handler(void) { - uint32_t chunk = 0U; - struct usb_setup_packet *setup = &usbd_core_cfg.setup; - - /* OUT transfer, status packets */ - if (usbd_core_cfg.ep0_data_buf_residue == 0) { - /* absorb zero-length status message */ - USBD_LOG_DBG("recv status\r\n"); - - if (usbd_ep_read(USB_CONTROL_OUT_EP0, NULL, 0, NULL) < 0) { - USBD_LOG_ERR("Read DATA Packet failed\r\n"); - usbd_ep_set_stall(USB_CONTROL_IN_EP0); - } - - return; - } - - usbd_core_cfg.ep0_data_buf = usbd_core_cfg.req_data; - - /* OUT transfer, data packets */ - if (usbd_ep_read(USB_CONTROL_OUT_EP0, usbd_core_cfg.ep0_data_buf, usbd_core_cfg.ep0_data_buf_residue, &chunk) < 0) { - USBD_LOG_ERR("Read DATA Packet failed\r\n"); - usbd_ep_set_stall(USB_CONTROL_IN_EP0); - return; - } - - usbd_core_cfg.ep0_data_buf += chunk; - usbd_core_cfg.ep0_data_buf_residue -= chunk; - - if (usbd_core_cfg.ep0_data_buf_residue == 0) { - /* Received all, send data to handler */ - usbd_core_cfg.ep0_data_buf = usbd_core_cfg.req_data; - - if (!usbd_setup_request_handler(setup, &usbd_core_cfg.ep0_data_buf, &usbd_core_cfg.ep0_data_buf_len)) { - USBD_LOG_ERR("usbd_setup_request_handler1 failed\r\n"); - usbd_ep_set_stall(USB_CONTROL_IN_EP0); - return; - } - - /*Send status to host*/ - usbd_send_to_host(setup->wLength); - } else { - USBD_LOG_ERR("ep0_data_buf_residue is not zero\r\n"); - } -} - -static void usbd_ep0_in_handler(void) { - struct usb_setup_packet *setup = &usbd_core_cfg.setup; - - /* Send more data if available */ - if (usbd_core_cfg.ep0_data_buf_residue != 0 || usbd_core_cfg.zlp_flag == true) { - usbd_send_to_host(setup->wLength); - } else { - /*ep0 tx has completed,and no data to send,so do nothing*/ - } -} - -static void usbd_ep_out_handler(uint8_t ep) { -#if USBD_EP_CALLBACK_SEARCH_METHOD == 0 - usb_slist_t *i, *j, *k; - usb_slist_for_each(i, &usbd_class_head) { - usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list); - - usb_slist_for_each(j, &class->intf_list) { - usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list); - - usb_slist_for_each(k, &intf->ep_list) { - usbd_endpoint_t *ept = usb_slist_entry(k, struct usbd_endpoint, list); - - if ((ept->ep_addr == ep) && ept->ep_cb) { - ept->ep_cb(ep); - } - } - } - } -#else - - if (usbd_core_cfg.out_ep_cb[ep & 0x7f]) { - usbd_core_cfg.out_ep_cb[ep & 0x7f](ep); - } - -#endif -} - -static void usbd_ep_in_handler(uint8_t ep) { -#if USBD_EP_CALLBACK_SEARCH_METHOD == 0 - usb_slist_t *i, *j, *k; - usb_slist_for_each(i, &usbd_class_head) { - usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list); - - usb_slist_for_each(j, &class->intf_list) { - usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list); - - usb_slist_for_each(k, &intf->ep_list) { - usbd_endpoint_t *ept = usb_slist_entry(k, struct usbd_endpoint, list); - - if ((ept->ep_addr == ep) && ept->ep_cb) { - ept->ep_cb(ep); - } - } - } - } -#else - - if (usbd_core_cfg.in_ep_cb[ep & 0x7f]) { - usbd_core_cfg.in_ep_cb[ep & 0x7f](ep); - } - -#endif -} - -static void usbd_class_event_notify_handler(uint8_t event, void *arg) { - usb_slist_t *i, *j; - usb_slist_for_each(i, &usbd_class_head) { - usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list); - - usb_slist_for_each(j, &class->intf_list) { - usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list); - - if (intf->notify_handler) { - intf->notify_handler(event, arg); - } - } - } -} - -void usbd_event_notify_handler(uint8_t event, void *arg) { - switch (event) { - case USB_EVENT_RESET: - usbd_set_address(0); -#if USBD_EP_CALLBACK_SEARCH_METHOD == 1 - usbd_ep_callback_register(); -#endif - - case USB_EVENT_ERROR: - case USB_EVENT_SOF: - case USB_EVENT_CONNECTED: - case USB_EVENT_CONFIGURED: - case USB_EVENT_SUSPEND: - case USB_EVENT_DISCONNECTED: - case USB_EVENT_RESUME: - case USB_EVENT_SET_INTERFACE: - case USB_EVENT_SET_REMOTE_WAKEUP: - case USB_EVENT_CLEAR_REMOTE_WAKEUP: - case USB_EVENT_SET_HALT: - case USB_EVENT_CLEAR_HALT: - usbd_class_event_notify_handler(event, arg); - break; - - case USB_EVENT_SETUP_NOTIFY: - usbd_ep0_setup_handler(); - break; - - case USB_EVENT_EP0_IN_NOTIFY: - usbd_ep0_in_handler(); - break; - - case USB_EVENT_EP0_OUT_NOTIFY: - usbd_ep0_out_handler(); - break; - - case USB_EVENT_EP_IN_NOTIFY: - usbd_ep_in_handler((uint32_t)arg); - break; - - case USB_EVENT_EP_OUT_NOTIFY: - usbd_ep_out_handler((uint32_t)arg); - break; - - default: - USBD_LOG_ERR("USB unknown event: %d\r\n", event); - break; - } -} - -void usbd_desc_register(const uint8_t *desc) { usbd_core_cfg.descriptors = desc; } -/* Register MS OS Descriptors version 1 */ -void usbd_msosv1_desc_register(struct usb_msosv1_descriptor *desc) { msosv1_desc = desc; } - -/* Register MS OS Descriptors version 2 */ -void usbd_msosv2_desc_register(struct usb_msosv2_descriptor *desc) { msosv2_desc = desc; } - -void usbd_bos_desc_register(struct usb_bos_descriptor *desc) { bos_desc = desc; } - -void usbd_class_register(usbd_class_t *class) { - usb_slist_add_tail(&usbd_class_head, &class->list); - usb_slist_init(&class->intf_list); -} - -void usbd_class_add_interface(usbd_class_t *class, usbd_interface_t *intf) { - static uint8_t intf_offset = 0; - intf->intf_num = intf_offset; - usb_slist_add_tail(&class->intf_list, &intf->list); - usb_slist_init(&intf->ep_list); - intf_offset++; -} - -void usbd_interface_add_endpoint(usbd_interface_t *intf, usbd_endpoint_t *ep) { usb_slist_add_tail(&intf->ep_list, &ep->list); } - -bool usb_device_is_configured(void) { return usbd_core_cfg.configured; } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.h deleted file mode 100644 index 6884a76ef9..0000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.h +++ /dev/null @@ -1,138 +0,0 @@ -/** - * @file usbd_core.h - * - * Copyright (c) 2021 Bouffalolab team - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - */ -#ifndef _USBD_CORE_H -#define _USBD_CORE_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "usb_util.h" -#include "usb_def.h" -#include "usb_dc.h" - -enum usb_event_type { - /** USB error reported by the controller */ - USB_EVENT_ERROR, - /** USB reset */ - USB_EVENT_RESET, - /** Start of Frame received */ - USB_EVENT_SOF, - /** USB connection established, hardware enumeration is completed */ - USB_EVENT_CONNECTED, - /** USB configuration done */ - USB_EVENT_CONFIGURED, - /** USB connection suspended by the HOST */ - USB_EVENT_SUSPEND, - /** USB connection lost */ - USB_EVENT_DISCONNECTED, - /** USB connection resumed by the HOST */ - USB_EVENT_RESUME, - - /** USB interface selected */ - USB_EVENT_SET_INTERFACE, - /** USB interface selected */ - USB_EVENT_SET_REMOTE_WAKEUP, - /** USB interface selected */ - USB_EVENT_CLEAR_REMOTE_WAKEUP, - /** Set Feature ENDPOINT_HALT received */ - USB_EVENT_SET_HALT, - /** Clear Feature ENDPOINT_HALT received */ - USB_EVENT_CLEAR_HALT, - /** setup packet received */ - USB_EVENT_SETUP_NOTIFY, - /** ep0 in packet received */ - USB_EVENT_EP0_IN_NOTIFY, - /** ep0 out packet received */ - USB_EVENT_EP0_OUT_NOTIFY, - /** ep in packet except ep0 received */ - USB_EVENT_EP_IN_NOTIFY, - /** ep out packet except ep0 received */ - USB_EVENT_EP_OUT_NOTIFY, - /** Initial USB connection status */ - USB_EVENT_UNKNOWN -}; - -/** - * @brief Callback function signature for the USB Endpoint status - */ -typedef void (*usbd_endpoint_callback)(uint8_t ep); - -/** - * @brief Callback function signature for class specific requests - * - * Function which handles Class specific requests corresponding to an - * interface number specified in the device descriptor table. For host - * to device direction the 'len' and 'payload_data' contain the length - * of the received data and the pointer to the received data respectively. - * For device to host class requests, 'len' and 'payload_data' should be - * set by the callback function with the length and the address of the - * data to be transmitted buffer respectively. - */ -typedef int (*usbd_request_handler)(struct usb_setup_packet *setup, - uint8_t **data, uint32_t *transfer_len); - -/* callback function pointer structure for Application to handle events */ -typedef void (*usbd_notify_handler)(uint8_t event, void *arg); - -typedef struct usbd_endpoint { - usb_slist_t list; - uint8_t ep_addr; - usbd_endpoint_callback ep_cb; -} usbd_endpoint_t; - -typedef struct usbd_interface { - usb_slist_t list; - /** Handler for USB Class specific Control (EP 0) communications */ - usbd_request_handler class_handler; - /** Handler for USB Vendor specific commands */ - usbd_request_handler vendor_handler; - /** Handler for USB custom specific commands */ - usbd_request_handler custom_handler; - /** Handler for USB event notify commands */ - usbd_notify_handler notify_handler; - uint8_t intf_num; - usb_slist_t ep_list; -} usbd_interface_t; - -typedef struct usbd_class { - usb_slist_t list; - const char *name; - usb_slist_t intf_list; -} usbd_class_t; - -void usbd_event_notify_handler(uint8_t event, void *arg); - -void usbd_desc_register(const uint8_t *desc); -void usbd_class_register(usbd_class_t *class); -void usbd_msosv1_desc_register(struct usb_msosv1_descriptor *desc); -void usbd_msosv2_desc_register(struct usb_msosv2_descriptor *desc); -void usbd_bos_desc_register(struct usb_bos_descriptor *desc); -void usbd_class_add_interface(usbd_class_t *class, usbd_interface_t *intf); -void usbd_interface_add_endpoint(usbd_interface_t *intf, usbd_endpoint_t *ep); -bool usb_device_is_configured(void); - -#ifdef __cplusplus -} -#endif - -#endif From 315f8734b592d7d61bd88a4e8b0e993cb8ced30b Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Tue, 26 Dec 2023 23:55:56 +1100 Subject: [PATCH 11/18] Fix BLE headers to be sensible --- .../components/ble/ble_stack/common/buf.c | 3 ++- .../components/ble/ble_stack/host/conn_internal.h | 15 +++++++++++++-- .../components/ble/ble_stack/host/hci_core.c | 2 +- .../ble/ble_stack/include/bluetooth/att.h | 2 ++ .../ble/ble_stack/include/bluetooth/conn.h | 2 +- .../ble/ble_stack/sbc/enc/sbc_enc_func_declare.h | 4 +++- .../components/ble/ble_stack/services/hog.c | 2 +- .../components/ble/ble_stack/services/hog.h | 3 +++ .../components/ble/ble_stack/services/scps.h | 2 +- .../bl702_driver/std_drv/src/bl702_sf_ctrl.c | 3 ++- 10 files changed, 29 insertions(+), 9 deletions(-) diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c index 9fb971cb09..099130d51d 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c @@ -271,7 +271,8 @@ static u8_t *fixed_data_alloc(struct net_buf *buf, size_t *size, s32_t timeout) return fixed->data_pool + fixed->data_size * net_buf_id(buf); } -static void fixed_data_unref(struct net_buf *buf, u8_t *data) { /* Nothing needed for fixed-size data pools */ } +static void fixed_data_unref(struct net_buf *buf, u8_t *data) { /* Nothing needed for fixed-size data pools */ +} const struct net_buf_data_cb net_buf_fixed_cb = { .alloc = fixed_data_alloc, diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn_internal.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn_internal.h index 824cb292e2..180864e37c 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn_internal.h +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn_internal.h @@ -1,6 +1,9 @@ /** @file * @brief Internal APIs for Bluetooth connection handling. */ +#ifndef BLE_STACK_HOST_CONN_INTERNAL_H_ +#define BLE_STACK_HOST_CONN_INTERNAL_H_ + #include "addr.h" #include "atomic.h" #include "slist.h" @@ -8,8 +11,12 @@ #include "work_q.h" #include #include -#ifndef BLE_STACK_HOST_CONN_INTERNAL_H_ -#define BLE_STACK_HOST_CONN_INTERNAL_H_ +#include "conn.h" + + +#ifdef __cplusplus +extern "C" { +#endif /* * Copyright (c) 2015 Intel Corporation * @@ -327,4 +334,8 @@ void bt_conn_process_tx(struct bt_conn *conn); int bt_hci_get_conn_handle(const struct bt_conn *conn, u16_t *conn_handle); #endif +#ifdef __cplusplus +}; +#endif + #endif //BLE_STACK_HOST_CONN_INTERNAL_H_ \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c index a2d5873d14..fb643b2aeb 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c @@ -5401,7 +5401,7 @@ int bt_disable(void) { static int set_ad(u16_t hci_op, const struct bt_ad *ad, size_t ad_len) { struct bt_hci_cp_le_set_adv_data *set_data; struct net_buf *buf; - size_t c, i; + size_t c, i; buf = bt_hci_cmd_create(hci_op, sizeof(*set_data)); if (!buf) { diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/att.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/att.h index f46a0828ff..515320acd7 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/att.h +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/att.h @@ -15,6 +15,8 @@ extern "C" { #endif #include "buf.h" #include +#include "conn_internal.h" +#include "conn.h" /* Error codes for Error response PDU */ #define BT_ATT_ERR_INVALID_HANDLE 0x01 diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/conn.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/conn.h index 12a32c15ae..18b649715f 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/conn.h +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/conn.h @@ -21,12 +21,12 @@ #include #include #include +#include "conn_internal.h" #ifdef __cplusplus extern "C" { #endif -#include "conn_internal.h" /** Opaque type representing a connection to a remote device */ struct bt_conn; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_func_declare.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_func_declare.h index 1635b81a32..feb9d4b293 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_func_declare.h +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_func_declare.h @@ -24,8 +24,10 @@ #ifndef SBC_FUNCDECLARE_H #define SBC_FUNCDECLARE_H +#include "sbc_types.h" + +#include "sbc_encoder.h" -/*#include "sbc_encoder.h"*/ /* Global data */ #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == FALSE) extern const SINT16 gas32CoeffFor4SBs[]; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c index f9c971be46..cec925e58a 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c @@ -144,7 +144,7 @@ int hog_notify(struct bt_conn *conn, uint16_t hid_usage, uint8_t press) { struct hids_remote_key *remote_key = NULL; u8_t len = 4, data[4]; - for (int i = 0; i < (sizeof(remote_kbd_map_tab) / sizeof(remote_kbd_map_tab[0])); i++) { + for (size_t i = 0; i < (sizeof(remote_kbd_map_tab) / sizeof(remote_kbd_map_tab[0])); i++) { if (remote_kbd_map_tab[i].hid_usage == hid_usage) { remote_key = &remote_kbd_map_tab[i]; break; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.h index c3746aaef2..3855fe646a 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.h +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.h @@ -15,6 +15,9 @@ extern "C" { #endif #include +#include "conn.h" +#include "conn_internal.h" + #define HID_PAGE_KBD 0x07 #define HID_PAGE_CONS 0x0C diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.h index ede76ec22f..274304d49e 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.h +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.h @@ -15,8 +15,8 @@ extern "C" { #endif +#include #include - bool scps_init(u16_t scan_itvl, u16_t scan_win); #ifdef __cplusplus diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_ctrl.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_ctrl.c index 93e8c59388..d2ec8a72da 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_ctrl.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_ctrl.c @@ -1404,7 +1404,8 @@ BL_Sts_Type ATTR_TCM_SECTION SF_Ctrl_GetBusyState(void) { * *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void SF_Ctrl_IRQHandler(void) { /* TODO: Not implemented */ } +void SF_Ctrl_IRQHandler(void) { /* TODO: Not implemented */ +} #endif /*@} end of group SF_CTRL_Public_Functions */ From 72ad03cd8422f5c89982613ac4abbe5e9d83419c Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Wed, 27 Dec 2023 00:06:10 +1100 Subject: [PATCH 12/18] Cleaning up proper c styling --- .../Common/Source/system_gd32vf103.c | 3 +-- .../Pinecilv2/bl_mcu_sdk/common/misc/misc.c | 9 +++---- .../ble_stack/bl_hci_wrapper/bl_hci_wrapper.c | 3 ++- .../tinycrypt/source/ecc_platform_specific.c | 3 ++- .../components/ble/ble_stack/services/hog.c | 6 +++-- .../bl702_driver/hal_drv/src/hal_gpio.c | 5 ++-- .../drivers/bl702_driver/hal_drv/src/hal_pm.c | 11 +++++---- .../bl702_driver/hal_drv/src/hal_uart.c | 24 +++++++++++-------- .../drivers/bl702_driver/startup/interrupt.c | 9 +++---- 9 files changed, 41 insertions(+), 32 deletions(-) diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/system_gd32vf103.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/system_gd32vf103.c index 171bb151c8..bd83a3c239 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/system_gd32vf103.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/system_gd32vf103.c @@ -343,8 +343,7 @@ static void system_default_exception_handler(unsigned long mcause, unsigned long printf("MCAUSE: 0x%lx\r\n", mcause); printf("MEPC : 0x%lx\r\n", __RV_CSR_READ(CSR_MEPC)); printf("MTVAL : 0x%lx\r\n", __RV_CSR_READ(CSR_MBADADDR)); - while (1) - ; + while (1) {} } /** diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c index be8d852fbf..b05cda4100 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c @@ -200,8 +200,9 @@ int arch_ffsll(uint64_t *val, uint32_t *bit) { } int arch_ctzll(uint64_t *val, uint32_t *bit) { - if (!*val) + if (!*val) { return -1; + } *bit = __builtin_ctzll(*val); *val &= ~((1ULL) << (*bit)); @@ -209,8 +210,9 @@ int arch_ctzll(uint64_t *val, uint32_t *bit) { } int arch_clzll(uint64_t *val, uint32_t *bit) { - if (!*val) + if (!*val) { return -1; + } *bit = __builtin_clzll(*val); *val &= ~((1ULL) << (*bit)); @@ -229,8 +231,7 @@ int arch_clzll(uint64_t *val, uint32_t *bit) { *******************************************************************************/ void check_failed(uint8_t *file, uint32_t line) { /* Infinite loop */ - while (1) - ; + while (1) {} } #endif /* DEBUG */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c index 3fa6a18581..53a0120181 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c @@ -257,8 +257,9 @@ static void bl_onchiphci_rx_packet_handler(uint8_t pkt_type, uint16_t src_id, ui return; } buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT); - if (buf) + if (buf) { bl_packet_to_host(pkt_type, src_id, param, param_len, buf); + } return; } else { if (pkt_type != BT_HCI_ACL_DATA) { diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_platform_specific.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_platform_specific.c index 261ca747fe..f958eb95b4 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_platform_specific.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_platform_specific.c @@ -70,8 +70,9 @@ int default_CSPRNG(uint8_t *dest, unsigned int size) { /* input sanity check: */ - if (dest == (uint8_t *)0 || (size <= 0)) + if (dest == (uint8_t *)0 || (size <= 0)) { return 0; + } int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC); if (fd == -1) { diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c index cec925e58a..18dece817f 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c @@ -151,14 +151,16 @@ int hog_notify(struct bt_conn *conn, uint16_t hid_usage, uint8_t press) { } } - if (!remote_key) + if (!remote_key) { return EINVAL; + } if (remote_key->hid_page == HID_PAGE_KBD) { attr = &attrs[BT_CHAR_BLE_HID_REPORT_ATTR_VAL_INDEX]; len = 3; - } else + } else { return EINVAL; + } sys_put_le16(hid_usage, data); data[2] = 0; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_gpio.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_gpio.c index 20778c9067..251c2e92e4 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_gpio.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_gpio.c @@ -144,10 +144,11 @@ void gpio_set_mode(uint32_t pin, uint32_t mode) { void gpio_write(uint32_t pin, uint32_t value) { uint32_t tmp = BL_RD_REG(GLB_BASE, GLB_GPIO_OUTPUT); - if (value) + if (value) { tmp |= (1 << pin); - else + } else { tmp &= ~(1 << pin); + } BL_WR_REG(GLB_BASE, GLB_GPIO_OUTPUT, tmp); } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm.c index e7efc2ef5c..7d5c624e29 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm.c @@ -1159,13 +1159,15 @@ ATTR_TCM_SECTION void pm_hbn_mode_enter(enum pm_hbn_sleep_level hbn_level, uint8 /* To make it simple and safe*/ cpu_global_irq_disable(); - if (sleep_time && (hbn_level < PM_HBN_LEVEL_2)) + if (sleep_time && (hbn_level < PM_HBN_LEVEL_2)) { rtc_init(sleep_time); // sleep time,unit is second + } - if (hbn_level >= PM_HBN_LEVEL_2) + if (hbn_level >= PM_HBN_LEVEL_2) { HBN_Power_Off_RC32K(); - else + } else { HBN_Power_On_RC32K(); + } HBN_Power_Down_Flash(NULL); /* SF io select from efuse value */ @@ -1237,9 +1239,10 @@ ATTR_HBN_RAM_SECTION void pm_hbn_enter_again(bool reset) { BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, 0xffffffff); BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, 0); - if (!reset) + if (!reset) { /* Enable HBN mode */ BL_WR_REG(HBN_BASE, HBN_RSV0, HBN_STATUS_ENTER_FLAG); + } tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); tmpVal = BL_SET_REG_BIT(tmpVal, HBN_MODE); diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c index ea8aed72df..32ace75426 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c @@ -94,7 +94,7 @@ int uart_open(struct device *dev, uint16_t oflag) { if ((oflag & DEVICE_OFLAG_INT_TX) || (oflag & DEVICE_OFLAG_INT_RX)) { #ifdef BSP_USING_UART0 if (uart_device->id == UART0_ID) - Interrupt_Handler_Register(UART0_IRQn, UART0_IRQ); + {Interrupt_Handler_Register(UART0_IRQn, UART0_IRQ);} #endif #ifdef BSP_USING_UART1 if (uart_device->id == UART1_ID) @@ -151,9 +151,9 @@ int uart_control(struct device *dev, int cmd, void *args) { offset++; } if (uart_device->id == UART0_ID) - CPU_Interrupt_Enable(UART0_IRQn); + {CPU_Interrupt_Enable(UART0_IRQn);} else if (uart_device->id == UART1_ID) - CPU_Interrupt_Enable(UART1_IRQn); + {CPU_Interrupt_Enable(UART1_IRQn);} break; } @@ -166,9 +166,9 @@ int uart_control(struct device *dev, int cmd, void *args) { offset++; } if (uart_device->id == UART0_ID) - CPU_Interrupt_Disable(UART0_IRQn); + {CPU_Interrupt_Disable(UART0_IRQn);} else if (uart_device->id == UART1_ID) - CPU_Interrupt_Disable(UART1_IRQn); + {CPU_Interrupt_Disable(UART1_IRQn);} break; } @@ -270,7 +270,7 @@ int uart_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t si if (dev->oflag & DEVICE_OFLAG_DMA_TX) { struct device *dma_ch = (struct device *)uart_device->tx_dma; if (!dma_ch) - return -1; +{ return -1;} if (uart_device->id == 0) { ret = dma_reload(dma_ch, (uint32_t)buffer, (uint32_t)DMA_ADDR_UART0_TDR, size); @@ -282,8 +282,9 @@ int uart_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t si return ret; } else if (dev->oflag & DEVICE_OFLAG_INT_TX) { return -2; - } else + } else { return UART_SendData(uart_device->id, (uint8_t *)buffer, size); + } } /** * @brief @@ -299,8 +300,9 @@ int uart_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size) { uart_device_t *uart_device = (uart_device_t *)dev; if (dev->oflag & DEVICE_OFLAG_DMA_RX) { struct device *dma_ch = (struct device *)uart_device->rx_dma; - if (!dma_ch) + if (!dma_ch) { return -1; + } if (uart_device->id == 0) { ret = dma_reload(dma_ch, (uint32_t)DMA_ADDR_UART0_RDR, (uint32_t)buffer, size); @@ -327,8 +329,9 @@ int uart_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size) { int uart_register(enum uart_index_type index, const char *name) { struct device *dev; - if (UART_MAX_INDEX == 0) + if (UART_MAX_INDEX == 0) { return -DEVICE_EINVAL; + } dev = &(uartx_device[index].parent); @@ -356,8 +359,9 @@ void uart_isr(uart_device_t *handle) { tmpVal = BL_RD_REG(UARTx, UART_INT_STS); maskVal = BL_RD_REG(UARTx, UART_INT_MASK); - if (!handle->parent.callback) + if (!handle->parent.callback) { return; + } /* Length of uart tx data transfer arrived interrupt */ if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_END_MASK)) { diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c index 929fb516c9..131a3d2aad 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c @@ -184,8 +184,7 @@ void vAssertCalled(void) { // PWM_Channel_Disable(PWM_Channel); // gpio_set_mode(PWM_Out_Pin, GPIO_INPUT_PD_MODE); - while (1) - ; + while (1) {} } void Trap_Handler(void) { @@ -255,8 +254,7 @@ void Trap_Handler(void) { } if (!isecall) { - while (1) - ; + while (1) {} } } @@ -288,8 +286,7 @@ void Interrupt_Handler(void) { MSG("Peripheral Interrupt num:%d \r\n", (unsigned int)num - IRQ_NUM_BASE); } - while (1) - ; + while (1) {} } } else { MSG("Unexpected interrupt num:%d\r\n", (unsigned int)num); From c696cb26b10ec04ca3c75bc994b19975fcacda26 Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Wed, 27 Dec 2023 00:09:01 +1100 Subject: [PATCH 13/18] We have newer clang, it does bracketing now --- source/.clang-format | 1 + 1 file changed, 1 insertion(+) diff --git a/source/.clang-format b/source/.clang-format index a737f88cfe..f67663939e 100644 --- a/source/.clang-format +++ b/source/.clang-format @@ -86,6 +86,7 @@ IndentGotoLabels: true IndentPPDirectives: None IndentWidth: 2 IndentWrappedFunctionNames: false +InsertBraces: true JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: true From d2efa4c22367bce61d0289c12ba38e3c0bcf38f1 Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Wed, 27 Dec 2023 00:09:14 +1100 Subject: [PATCH 14/18] Run clang-format brackets --- source/Core/BSP/MHP30/BSP.cpp | 9 +- source/Core/BSP/Miniware/BSP.cpp | 3 +- source/Core/BSP/Pinecil/I2C_Wrapper.cpp | 9 +- .../Common/Source/Drivers/n200_func.c | 3 +- .../ble_stack/bl_hci_wrapper/bl_hci_wrapper.c | 3 +- .../ble_stack/common/tinycrypt/source/ecc.c | 3 +- .../common/tinycrypt/source/hmac_prng.c | 12 ++- .../components/ble/ble_stack/common/work_q.c | 3 +- .../components/ble/ble_stack/host/att.c | 15 ++- .../components/ble/ble_stack/host/conn.c | 3 +- .../components/ble/ble_stack/host/gatt.c | 23 +++-- .../components/ble/ble_stack/host/hci_core.c | 97 ++++++++++++------- .../components/ble/ble_stack/host/l2cap.c | 3 +- .../components/ble/ble_stack/host/multi_adv.c | 36 ++++--- .../components/ble/ble_stack/host/settings.c | 21 ++-- .../bl702_driver/hal_drv/src/hal_clock.c | 7 +- .../bl702_driver/hal_drv/src/hal_uart.c | 31 +++--- .../bl702_driver/hal_drv/src/hal_usb.c | 3 +- .../drivers/bl702_driver/startup/drv_mmheap.c | 18 ++-- source/Core/BSP/Pinecilv2/board.c | 3 +- source/Core/BSP/Sequre_S60/BSP.cpp | 3 +- source/Core/Drivers/Buttons.cpp | 29 +++--- source/Core/Drivers/I2CBB1.cpp | 37 ++++--- source/Core/Drivers/I2CBB2.cpp | 37 ++++--- source/Core/Drivers/Si7210.cpp | 30 ++++-- source/Core/Threads/PIDThread.cpp | 5 +- 26 files changed, 286 insertions(+), 160 deletions(-) diff --git a/source/Core/BSP/MHP30/BSP.cpp b/source/Core/BSP/MHP30/BSP.cpp index cbf5ce7907..dde331d461 100644 --- a/source/Core/BSP/MHP30/BSP.cpp +++ b/source/Core/BSP/MHP30/BSP.cpp @@ -230,8 +230,9 @@ uint16_t getInputVoltageX10(uint16_t divisor, uint8_t sample) { static uint32_t samples[BATTFILTERDEPTH]; static uint8_t index = 0; if (preFillneeded) { - for (uint8_t i = 0; i < BATTFILTERDEPTH; i++) + for (uint8_t i = 0; i < BATTFILTERDEPTH; i++) { samples[i] = getADC(1); + } preFillneeded--; } if (sample) { @@ -240,8 +241,9 @@ uint16_t getInputVoltageX10(uint16_t divisor, uint8_t sample) { } uint32_t sum = 0; - for (uint8_t i = 0; i < BATTFILTERDEPTH; i++) + for (uint8_t i = 0; i < BATTFILTERDEPTH; i++) { sum += samples[i]; + } sum /= BATTFILTERDEPTH; if (divisor == 0) { @@ -273,8 +275,9 @@ void unstick_I2C() { HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_SET); timeout_cnt++; - if (timeout_cnt > timeout) + if (timeout_cnt > timeout) { return; + } } } diff --git a/source/Core/BSP/Miniware/BSP.cpp b/source/Core/BSP/Miniware/BSP.cpp index e930f68246..df45516b5d 100644 --- a/source/Core/BSP/Miniware/BSP.cpp +++ b/source/Core/BSP/Miniware/BSP.cpp @@ -207,8 +207,9 @@ void unstick_I2C() { HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_SET); timeout_cnt++; - if (timeout_cnt > timeout) + if (timeout_cnt > timeout) { return; + } } // 12. Configure the SCL and SDA I/Os as Alternate function Open-Drain. diff --git a/source/Core/BSP/Pinecil/I2C_Wrapper.cpp b/source/Core/BSP/Pinecil/I2C_Wrapper.cpp index 46f334360f..2b2e55a37a 100644 --- a/source/Core/BSP/Pinecil/I2C_Wrapper.cpp +++ b/source/Core/BSP/Pinecil/I2C_Wrapper.cpp @@ -296,8 +296,9 @@ bool perform_i2c_transaction(uint16_t DevAddress, uint16_t memory_address, uint8 } bool FRToSI2C::Mem_Read(uint16_t DevAddress, uint16_t read_address, uint8_t *p_buffer, uint16_t number_of_byte) { - if (!lock()) + if (!lock()) { return false; + } bool res = perform_i2c_transaction(DevAddress, read_address, p_buffer, number_of_byte, false, false); if (!res) { I2C_Unstick(); @@ -307,8 +308,9 @@ bool FRToSI2C::Mem_Read(uint16_t DevAddress, uint16_t read_address, uint8_t *p_b } bool FRToSI2C::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, uint8_t *p_buffer, uint16_t number_of_byte) { - if (!lock()) + if (!lock()) { return false; + } bool res = perform_i2c_transaction(DevAddress, MemAddress, p_buffer, number_of_byte, true, false); if (!res) { I2C_Unstick(); @@ -349,8 +351,9 @@ bool FRToSI2C::writeRegistersBulk(const uint8_t address, const I2C_REG *register bool FRToSI2C::wakePart(uint16_t DevAddress) { // wakepart is a special case where only the device address is sent - if (!lock()) + if (!lock()) { return false; + } bool res = perform_i2c_transaction(DevAddress, 0, NULL, 0, false, true); if (!res) { I2C_Unstick(); diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/n200_func.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/n200_func.c index 15aa0fb128..48618134fd 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/n200_func.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/n200_func.c @@ -44,8 +44,9 @@ uint64_t get_timer_value(void) { while (1) { uint32_t hi = mtime_hi(); uint32_t lo = mtime_lo(); - if (hi == mtime_hi()) + if (hi == mtime_hi()) { return ((uint64_t)hi << 32) | lo; + } } } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c index 53a0120181..5778665edc 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c @@ -216,8 +216,9 @@ void bl_trigger_queued_msg() { break; } - if (bt_buf_get_rx_avail_cnt() <= CONFIG_BT_RX_BUF_RSV_COUNT) + if (bt_buf_get_rx_avail_cnt() <= CONFIG_BT_RX_BUF_RSV_COUNT) { break; + } buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT); if (!buf) { diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c index a1befa180e..f6a0cfb44e 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c @@ -751,8 +751,9 @@ int uECC_valid_point(const uECC_word_t *point, uECC_Curve curve) { curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */ /* Make sure that y^2 == x^3 + ax + b */ - if (uECC_vli_equal(tmp1, tmp2, num_words) != 0) + if (uECC_vli_equal(tmp1, tmp2, num_words) != 0) { return -3; + } return 0; } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac_prng.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac_prng.c index 3fe120442b..1c9971bd5f 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac_prng.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac_prng.c @@ -87,10 +87,12 @@ static void update(TCHmacPrng_t prng, const uint8_t *data, unsigned int datalen, (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); (void)tc_hmac_update(&prng->h, &separator0, sizeof(separator0)); - if (data && datalen) + if (data && datalen) { (void)tc_hmac_update(&prng->h, data, datalen); - if (additional_data && additional_datalen) + } + if (additional_data && additional_datalen) { (void)tc_hmac_update(&prng->h, additional_data, additional_datalen); + } (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h); @@ -102,8 +104,9 @@ static void update(TCHmacPrng_t prng, const uint8_t *data, unsigned int datalen, (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h); - if (data == 0 || datalen == 0) + if (data == 0 || datalen == 0) { return; + } /* configure the new prng key into the prng's instance of hmac */ tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key)); @@ -113,8 +116,9 @@ static void update(TCHmacPrng_t prng, const uint8_t *data, unsigned int datalen, (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); (void)tc_hmac_update(&prng->h, &separator1, sizeof(separator1)); (void)tc_hmac_update(&prng->h, data, datalen); - if (additional_data && additional_datalen) + if (additional_data && additional_datalen) { (void)tc_hmac_update(&prng->h, additional_data, additional_datalen); + } (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h); /* configure the new prng key into the prng's instance of hmac */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/work_q.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/work_q.c index 4c78637e5b..86d2285c11 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/work_q.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/work_q.c @@ -170,8 +170,9 @@ s32_t k_delayed_work_remaining_get(struct k_delayed_work *work) { } void k_delayed_work_del_timer(struct k_delayed_work *work) { - if (NULL == work || NULL == work->timer.timer.hdl) + if (NULL == work || NULL == work->timer.timer.hdl) { return; + } k_timer_delete(&work->timer); work->timer.timer.hdl = NULL; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c index 5796f5b38a..7ca97fe8ae 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c @@ -283,8 +283,9 @@ static u8_t att_mtu_req(struct bt_att *att, struct net_buf *buf) { BT_DBG("Negotiated MTU %u", att->chan.rx.mtu); #if defined(BFLB_BLE_MTU_CHANGE_CB) - if (att->chan.chan.ops->mtu_changed) + if (att->chan.chan.ops->mtu_changed) { att->chan.chan.ops->mtu_changed(&(att->chan.chan), att->chan.rx.mtu); + } #endif return 0; @@ -827,8 +828,9 @@ static u8_t att_read_type_rsp(struct bt_att *att, struct bt_uuid *uuid, u16_t st } #if defined(CONFIG_BT_STACK_PTS) - if (event_flag == att_read_by_type_ind) + if (event_flag == att_read_by_type_ind) { BT_PTS("handle : [0x%04x]\r\n", data.rsp->data->handle); + } #endif (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL); @@ -1489,8 +1491,9 @@ static int att_change_security(struct bt_conn *conn, u8_t err) { switch (err) { case BT_ATT_ERR_INSUFFICIENT_ENCRYPTION: - if (conn->sec_level >= BT_SECURITY_L2) + if (conn->sec_level >= BT_SECURITY_L2) { return -EALREADY; + } sec = BT_SECURITY_L2; break; case BT_ATT_ERR_AUTHENTICATION: @@ -1978,8 +1981,9 @@ static void bt_att_disconnected(struct bt_l2cap_chan *chan) { bt_gatt_disconnected(ch->chan.conn); #ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS - if (att->timeout_work.timer.timer.hdl) + if (att->timeout_work.timer.timer.hdl) { k_delayed_work_del_timer(&att->timeout_work); + } if (att->tx_queue._queue.hdl) { k_queue_free(&att->tx_queue._queue); @@ -1993,8 +1997,9 @@ static void bt_att_disconnected(struct bt_l2cap_chan *chan) { } #endif - if (att->tx_sem.sem.hdl) + if (att->tx_sem.sem.hdl) { k_sem_delete(&att->tx_sem); + } #endif } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c index 3d22b293cd..644ff68f69 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c @@ -1446,8 +1446,9 @@ static void conn_cleanup(struct bt_conn *conn) { // k_queue_free(&conn->tx_notify._queue); conn->tx_queue._queue.hdl = NULL; // conn->tx_notify._queue.hdl = NULL; - if (conn->update_work.timer.timer.hdl) + if (conn->update_work.timer.timer.hdl) { k_delayed_work_del_timer(&conn->update_work); + } #endif } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c index 2254d31a3f..7d8781f7d8 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c @@ -480,8 +480,9 @@ static u8_t gen_hash_m(const struct bt_gatt_attr *attr, void *user_data) { ssize_t len; u16_t value; - if (attr->uuid->type != BT_UUID_TYPE_16) + if (attr->uuid->type != BT_UUID_TYPE_16) { return BT_GATT_ITER_CONTINUE; + } u16 = (struct bt_uuid_16 *)attr->uuid; @@ -2187,8 +2188,9 @@ int bt_gatt_exchange_mtu(struct bt_conn *conn, struct bt_gatt_exchange_params *p static void gatt_discover_next(struct bt_conn *conn, u16_t last_handle, struct bt_gatt_discover_params *params) { /* Skip if last_handle is not set */ - if (!last_handle) + if (!last_handle) { goto discover; + } /* Continue from the last found handle */ params->start_handle = last_handle; @@ -2511,8 +2513,9 @@ static u16_t parse_characteristic(struct bt_conn *conn, const void *pdu, struct #if defined(CONFIG_BT_STACK_PTS) if (event_flag != gatt_discover_chara) { /* Skip if UUID is set but doesn't match */ - if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) + if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) { continue; + } } #else /* Skip if UUID is set but doesn't match */ @@ -3129,10 +3132,11 @@ static int gatt_exec_write(struct bt_conn *conn, struct bt_gatt_write_params *pa req = net_buf_add(buf, sizeof(*req)); #if defined(CONFIG_BT_STACK_PTS) - if (event_flag == gatt_cancel_write_req) + if (event_flag == gatt_cancel_write_req) { req->flags = BT_ATT_FLAG_CANCEL; - else + } else { req->flags = BT_ATT_FLAG_EXEC; + } #else req->flags = BT_ATT_FLAG_EXEC; #endif @@ -3511,8 +3515,9 @@ static int ccc_set(const char *name, size_t len_rd, settings_read_cb read_cb, vo #if defined(BFLB_BLE) err = bt_settings_get_bin(key, (u8_t *)ccc_store, CCC_STORE_MAX, &len); - if (err) + if (err) { return err; + } load.addr_with_id.id = id; load.addr_with_id.addr = addr; @@ -3793,8 +3798,9 @@ void bt_gatt_disconnected(struct bt_conn *conn) { #if defined(BFLB_BLE_MTU_CHANGE_CB) void bt_gatt_mtu_changed(struct bt_conn *conn, u16_t mtu) { - if (gatt_mtu_changed_cb) + if (gatt_mtu_changed_cb) { gatt_mtu_changed_cb(conn, (int)mtu); + } } void bt_gatt_register_mtu_callback(bt_gatt_mtu_changed_cb_t cb) { gatt_mtu_changed_cb = cb; } @@ -4057,8 +4063,9 @@ static int sc_set(const char *name, size_t len_rd, settings_read_cb read_cb, voi } err = bt_settings_get_bin(key, (u8_t *)cfg, sizeof(*cfg), NULL); - if (err) + if (err) { memset(cfg, 0, sizeof(*cfg)); + } return err; #else if (!name) { diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c index fb643b2aeb..b6319be366 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c @@ -1390,10 +1390,11 @@ static void enh_conn_complete(struct bt_hci_evt_le_enh_conn_complete *evt) { if (IS_ENABLED(CONFIG_BT_PRIVACY)) { #if defined(BFLB_BLE_PATCH_DHKEY_CHECK_FAILED) - if (memcmp(&evt->local_rpa, BT_ADDR_ANY, sizeof(bt_addr_t))) + if (memcmp(&evt->local_rpa, BT_ADDR_ANY, sizeof(bt_addr_t))) { bt_addr_copy(&conn->le.resp_addr.a, &evt->local_rpa); - else + } else { bt_addr_copy(&conn->le.resp_addr.a, &bt_dev.random_addr.a); + } #else bt_addr_copy(&conn->le.resp_addr.a, &evt->local_rpa); #endif @@ -1432,10 +1433,11 @@ static void enh_conn_complete(struct bt_hci_evt_le_enh_conn_complete *evt) { if (IS_ENABLED(CONFIG_BT_PRIVACY)) { #if defined(BFLB_BLE_PATCH_DHKEY_CHECK_FAILED) - if (memcmp(&evt->local_rpa, BT_ADDR_ANY, sizeof(bt_addr_t))) + if (memcmp(&evt->local_rpa, BT_ADDR_ANY, sizeof(bt_addr_t))) { bt_addr_copy(&conn->le.init_addr.a, &evt->local_rpa); - else + } else { bt_addr_copy(&conn->le.init_addr.a, &bt_dev.random_addr.a); + } #else bt_addr_copy(&conn->le.init_addr.a, &evt->local_rpa); #endif @@ -3636,21 +3638,24 @@ static int start_le_scan_with_isrpa(u8_t scan_type, u16_t interval, u16_t window set_param.filter_policy = 0x00; if (IS_ENABLED(CONFIG_BT_PRIVACY)) { - if (addre_type == 1) + if (addre_type == 1) { err = le_set_private_addr(BT_ID_DEFAULT); - else if (addre_type == 0) + } else if (addre_type == 0) { err = le_set_non_resolv_private_addr(BT_ID_DEFAULT); + } if (err) { return err; } if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { - if (addre_type == 2) + if (addre_type == 2) { set_param.addr_type = BT_ADDR_LE_PUBLIC; - if (addre_type == 1) + } + if (addre_type == 1) { set_param.addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; - else if (addre_type == 0) + } else if (addre_type == 0) { set_param.addr_type = BT_ADDR_LE_RANDOM; + } } else { set_param.addr_type = BT_ADDR_LE_RANDOM; } @@ -5024,8 +5029,9 @@ static int irk_init(void) { int err; /*local irk has been loaded from flash in bt_enable, check if irk is null*/ memset(empty_irk, 0, 16); - if (memcmp(bt_dev.irk[0], empty_irk, 16) != 0) + if (memcmp(bt_dev.irk[0], empty_irk, 16) != 0) { return 0; + } err = bt_rand(&bt_dev.irk[0], 16); @@ -5071,8 +5077,9 @@ static int bt_init(void) { char empty_name[CONFIG_BT_DEVICE_NAME_MAX]; memset(empty_name, 0, CONFIG_BT_DEVICE_NAME_MAX); - if (!memcmp(bt_dev.name, empty_name, CONFIG_BT_DEVICE_NAME_MAX)) + if (!memcmp(bt_dev.name, empty_name, CONFIG_BT_DEVICE_NAME_MAX)) { bt_set_name(CONFIG_BT_DEVICE_NAME); + } #endif #if defined(BFLB_BLE) @@ -5115,8 +5122,9 @@ static int bt_init(void) { if (HBN_Get_Status_Flag() == 0) #endif { - if (!bt_keys_load()) + if (!bt_keys_load()) { keys_commit(); + } } #endif #endif // CONFIG_BT_SMP @@ -5393,8 +5401,9 @@ int bt_disable_action(void) { int bt_disable(void) { if (le_check_valid_conn() || atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN) || atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { return -1; - } else + } else { return bt_disable_action(); + } } #endif @@ -5912,10 +5921,11 @@ int bt_le_adv_start_internal(const struct bt_le_adv_param *param, const struct b if (param->options & BT_LE_ADV_OPT_CONNECTABLE) { if (IS_ENABLED(CONFIG_BT_PRIVACY) && !(param->options & BT_LE_ADV_OPT_USE_IDENTITY)) { #if defined(CONFIG_BT_STACK_PTS) - if (param->addr_type == BT_ADDR_TYPE_RPA) + if (param->addr_type == BT_ADDR_TYPE_RPA) { err = le_set_private_addr(param->id); - else if (param->addr_type == BT_ADDR_TYPE_NON_RPA) + } else if (param->addr_type == BT_ADDR_TYPE_NON_RPA) { err = le_set_non_resolv_private_addr(param->id); + } #else err = le_set_private_addr(param->id); #endif @@ -5925,12 +5935,14 @@ int bt_le_adv_start_internal(const struct bt_le_adv_param *param, const struct b if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { #if defined(CONFIG_BT_STACK_PTS) - if (param->addr_type == BT_ADDR_LE_PUBLIC) + if (param->addr_type == BT_ADDR_LE_PUBLIC) { set_param.own_addr_type = BT_ADDR_LE_PUBLIC; - if (param->addr_type == BT_ADDR_TYPE_RPA) + } + if (param->addr_type == BT_ADDR_TYPE_RPA) { set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; - else if (param->addr_type == BT_ADDR_TYPE_NON_RPA) + } else if (param->addr_type == BT_ADDR_TYPE_NON_RPA) { set_param.own_addr_type = BT_ADDR_LE_RANDOM; + } #else set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; #endif @@ -5982,19 +5994,20 @@ int bt_le_adv_start_internal(const struct bt_le_adv_param *param, const struct b } else { #if defined(BFLB_BLE) && !defined(CONFIG_BT_MESH) #if defined(CONFIG_BT_STACK_PTS) - if (param->addr_type == BT_ADDR_TYPE_RPA) + if (param->addr_type == BT_ADDR_TYPE_RPA) { err = le_set_private_addr(param->id); - else if (param->addr_type == BT_ADDR_TYPE_NON_RPA) + } else if (param->addr_type == BT_ADDR_TYPE_NON_RPA) { err = le_set_non_resolv_private_addr(param->id); + } #else // #if !defined(CONFIG_BT_ADV_WITH_PUBLIC_ADDR) // err = le_set_private_addr(param->id); // #endif #endif // CONFIG_BT_STACK_PTS #if defined(CONFIG_BT_STACK_PTS) - if (param->addr_type == BT_ADDR_LE_PUBLIC) + if (param->addr_type == BT_ADDR_LE_PUBLIC) { set_param.own_addr_type = BT_ADDR_LE_PUBLIC; - else + } else #endif // set_param.own_addr_type = BT_ADDR_LE_RANDOM; // #if defined(CONFIG_BT_ADV_WITH_PUBLIC_ADDR) @@ -6051,8 +6064,9 @@ int bt_le_adv_start_internal(const struct bt_le_adv_param *param, const struct b atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_CONNECTABLE, param->options & BT_LE_ADV_OPT_CONNECTABLE); #if defined(BFLB_HOST_ASSISTANT) - if (!atomic_test_bit(bt_dev.flags, BT_DEV_ASSIST_RUN) && host_assist_cb && host_assist_cb->le_adv_cb) + if (!atomic_test_bit(bt_dev.flags, BT_DEV_ASSIST_RUN) && host_assist_cb && host_assist_cb->le_adv_cb) { host_assist_cb->le_adv_cb(param, ad, ad_len, sd, sd_len); + } #endif return 0; @@ -6144,10 +6158,11 @@ int set_adv_param(const struct bt_le_adv_param *param) { if (param->options & BT_LE_ADV_OPT_CONNECTABLE) { if (IS_ENABLED(CONFIG_BT_PRIVACY) && !(param->options & BT_LE_ADV_OPT_USE_IDENTITY)) { #if defined(CONFIG_BT_STACK_PTS) - if (param->addr_type == BT_ADDR_TYPE_RPA) + if (param->addr_type == BT_ADDR_TYPE_RPA) { err = le_set_private_addr(param->id); - else if (param->addr_type == BT_ADDR_TYPE_NON_RPA) + } else if (param->addr_type == BT_ADDR_TYPE_NON_RPA) { err = le_set_non_resolv_private_addr(param->id); + } #else err = le_set_private_addr(param->id); #endif @@ -6157,12 +6172,14 @@ int set_adv_param(const struct bt_le_adv_param *param) { if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { #if defined(CONFIG_BT_STACK_PTS) - if (param->addr_type == BT_ADDR_LE_PUBLIC) + if (param->addr_type == BT_ADDR_LE_PUBLIC) { set_param.own_addr_type = BT_ADDR_LE_PUBLIC; - if (param->addr_type == BT_ADDR_TYPE_RPA) + } + if (param->addr_type == BT_ADDR_TYPE_RPA) { set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; - else if (param->addr_type == BT_ADDR_TYPE_NON_RPA) + } else if (param->addr_type == BT_ADDR_TYPE_NON_RPA) { set_param.own_addr_type = BT_ADDR_LE_RANDOM; + } #else set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; #endif @@ -6198,17 +6215,18 @@ int set_adv_param(const struct bt_le_adv_param *param) { } else { #if defined(BFLB_BLE) && !defined(CONFIG_BT_MESH) #if defined(CONFIG_BT_STACK_PTS) - if (param->addr_type == BT_ADDR_TYPE_RPA) + if (param->addr_type == BT_ADDR_TYPE_RPA) { err = le_set_private_addr(param->id); - else if (param->addr_type == BT_ADDR_TYPE_NON_RPA) + } else if (param->addr_type == BT_ADDR_TYPE_NON_RPA) { err = le_set_non_resolv_private_addr(param->id); + } #else err = le_set_private_addr(param->id); #endif // CONFIG_BT_STACK_PTS #if defined(CONFIG_BT_STACK_PTS) - if (param->addr_type == BT_ADDR_LE_PUBLIC) + if (param->addr_type == BT_ADDR_LE_PUBLIC) { set_param.own_addr_type = BT_ADDR_LE_PUBLIC; - else + } else #endif set_param.own_addr_type = BT_ADDR_LE_RANDOM; #endif @@ -6253,8 +6271,9 @@ int set_ad_and_rsp_d(u16_t hci_op, u8_t *data, u32_t ad_len) { } else if (BT_HCI_OP_LE_SET_SCAN_RSP_DATA == hci_op) { size = sizeof(struct bt_hci_cp_le_set_scan_rsp_data); - } else + } else { return -ENOTSUP; + } buf = bt_hci_cmd_create(hci_op, size); if (!buf) { @@ -6292,8 +6311,9 @@ int set_ad_and_rsp_d(u16_t hci_op, u8_t *data, u32_t ad_len) { memcpy(set_data->data, data, set_data->len); - } else + } else { return -ENOBUFS; + } return bt_hci_cmd_send_sync(hci_op, buf, NULL); } @@ -6370,8 +6390,9 @@ static int set_ad_data(u16_t hci_op, const uint8_t *ad_data, int ad_len) { return -ENOBUFS; } - if (ad_len > 31) + if (ad_len > 31) { return -EINVAL; + } set_data = net_buf_add(buf, sizeof(*set_data)); @@ -6605,8 +6626,9 @@ int bt_le_scan_start(const struct bt_le_scan_param *param, bt_le_scan_cb_t cb) scan_dev_found_cb = cb; #if defined(BFLB_HOST_ASSISTANT) - if (!atomic_test_bit(bt_dev.flags, BT_DEV_ASSIST_RUN) && host_assist_cb && host_assist_cb->le_scan_cb) + if (!atomic_test_bit(bt_dev.flags, BT_DEV_ASSIST_RUN) && host_assist_cb && host_assist_cb->le_scan_cb) { host_assist_cb->le_scan_cb(param, cb); + } #endif return 0; @@ -6722,8 +6744,9 @@ int bt_set_tx_pwr(int8_t power) { struct net_buf *buf; int err; - if (power < 0 || power > 20) + if (power < 0 || power > 20) { return BT_HCI_ERR_INVALID_PARAM; + } memset(&set_param, 0, sizeof(set_param)); diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/l2cap.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/l2cap.c index 9137ee43d6..6d773ac69d 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/l2cap.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/l2cap.c @@ -238,8 +238,9 @@ void bt_l2cap_chan_del(struct bt_l2cap_chan *chan) { } #ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS - if (chan->rtx_work.timer.timer.hdl) + if (chan->rtx_work.timer.timer.hdl) { k_delayed_work_del_timer(&chan->rtx_work); + } #endif } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/multi_adv.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/multi_adv.c index 6f885a2e52..da344c9a21 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/multi_adv.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/multi_adv.c @@ -24,8 +24,9 @@ int multi_adv_get_instant_num(void) { struct multi_adv_instant *inst = &(g_multi_adv_list[0]); for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) { - if (inst[i].inuse_flag) + if (inst[i].inuse_flag) { num++; + } } return num; } @@ -104,13 +105,15 @@ int change_to_tick(int min_interval, int max_interval) { if (max_interval / SLOT_PER_PERIOD != min_interval / SLOT_PER_PERIOD) { tick = min_interval / SLOT_PER_PERIOD; - if (min_interval % SLOT_PER_PERIOD) + if (min_interval % SLOT_PER_PERIOD) { tick++; + } } else { tick = min_interval / SLOT_PER_PERIOD; } - if (tick <= 1) + if (tick <= 1) { tick = 1; + } return tick; } @@ -158,11 +161,13 @@ int calculate_offset(uint16_t interval[], uint16_t offset[], int num, int durati int offset_range; offset_range = interval[num]; - if (offset_range > duration) + if (offset_range > duration) { offset_range = duration; + } - if (num == 0) + if (num == 0) { return 0; + } min_max_instants = 0x7fffffff; /* using 0-interval-1 as offset */ @@ -177,8 +182,9 @@ int calculate_offset(uint16_t interval[], uint16_t offset[], int num, int durati instants++; } } - if (j % interval[num] == i) + if (j % interval[num] == i) { instants++; + } if (curr_max_instants < instants) { curr_max_instants = instants; } @@ -226,8 +232,9 @@ void multi_adv_schedule_timer_handle(void) { struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler; multi_adv_schedule_timer_stop(); - if (adv_scheduler->schedule_state == SCHEDULE_STOP) + if (adv_scheduler->schedule_state == SCHEDULE_STOP) { return; + } adv_scheduler->slot_clock = adv_scheduler->next_slot_clock; adv_scheduler->slot_offset = adv_scheduler->next_slot_offset; @@ -303,8 +310,9 @@ void multi_adv_schedule_timeslot(struct multi_adv_scheduler *adv_scheduler) { /* start instant */ adv_instant = multi_adv_find_instant_by_order(inst_order[match_order[insts]]); - if (adv_instant) + if (adv_instant) { multi_adv_start_adv_instant(adv_instant); + } } /* next instant in the same slot */ @@ -406,8 +414,9 @@ void multi_adv_new_schedule(void) { } if (inst_num == 1) { adv_instant = multi_adv_find_instant_by_order(inst_order[0]); - if (!adv_instant) + if (!adv_instant) { return; + } multi_adv_start_adv_instant(adv_instant); return; } @@ -444,12 +453,14 @@ int bt_le_multi_adv_start(const struct bt_le_adv_param *param, const struct bt_d struct multi_adv_instant *adv_instant; instant_num = multi_adv_get_instant_num(); - if (instant_num >= MAX_MULTI_ADV_INSTANT) + if (instant_num >= MAX_MULTI_ADV_INSTANT) { return -1; + } adv_instant = multi_adv_alloc_unused_instant(); - if (adv_instant == 0) + if (adv_instant == 0) { return -1; + } memcpy(&(adv_instant->param), param, sizeof(struct bt_le_adv_param)); @@ -463,8 +474,9 @@ int bt_le_multi_adv_start(const struct bt_le_adv_param *param, const struct bt_d } int bt_le_multi_adv_stop(int instant_id) { - if (multi_adv_find_instant_by_id(instant_id) == 0) + if (multi_adv_find_instant_by_id(instant_id) == 0) { return -1; + } // BT_WARN("%s id[%d]\n", __func__, instant_id); multi_adv_delete_instant_by_id(instant_id); diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/settings.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/settings.c index d5a2716191..3c7282eec6 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/settings.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/settings.c @@ -221,8 +221,9 @@ int bt_check_if_ef_ready() { if (!ef_ready_flag) { err = easyflash_init(); - if (!err) + if (!err) { ef_ready_flag = true; + } } return err; @@ -234,8 +235,9 @@ int bt_settings_set_bin(const char *key, const uint8_t *value, size_t length) { int err; err = bt_check_if_ef_ready(); - if (err) + if (err) { return err; + } str_value = pvPortMalloc(length * 2 + 1); @@ -261,8 +263,9 @@ int bt_settings_get_bin(const char *key, u8_t *value, size_t exp_len, size_t *re int err; err = bt_check_if_ef_ready(); - if (err) + if (err) { return err; + } str_value = ef_get_env(key); if (str_value == NULL) { @@ -275,8 +278,9 @@ int bt_settings_get_bin(const char *key, u8_t *value, size_t exp_len, size_t *re return -1; } - if (real_len) + if (real_len) { *real_len = str_value_len / 2; + } for (size_t i = 0; i < str_value_len / 2; i++) { strncpy(rand, str_value + 2 * i, 2); @@ -296,8 +300,9 @@ int settings_save_one(const char *key, const u8_t *value, size_t length) { retur void bt_settings_save_id(void) { #if defined(BFLB_BLE) #if defined(CONFIG_BT_SETTINGS) - if (bt_check_if_ef_ready()) + if (bt_check_if_ef_ready()) { return; + } bt_settings_set_bin(NV_LOCAL_ID_ADDR, (const u8_t *)&bt_dev.id_addr[0], sizeof(bt_addr_le_t) * CONFIG_BT_ID_MAX); #if defined(CONFIG_BT_PRIVACY) bt_settings_set_bin(NV_LOCAL_IRK, (const u8_t *)&bt_dev.irk[0], 16 * CONFIG_BT_ID_MAX); @@ -311,15 +316,17 @@ void bt_settings_save_id(void) { #if defined(BFLB_BLE) #if defined(CONFIG_BT_SETTINGS) void bt_settings_save_name(void) { - if (bt_check_if_ef_ready()) + if (bt_check_if_ef_ready()) { return; + } ef_set_env(NV_LOCAL_NAME, bt_dev.name); } void bt_local_info_load(void) { - if (bt_check_if_ef_ready()) + if (bt_check_if_ef_ready()) { return; + } #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC) char *dev_name; uint8_t len; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_clock.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_clock.c index 0a846dd88d..595784a6d5 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_clock.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_clock.c @@ -56,8 +56,9 @@ static void internal_rc32m_init(void) { tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); tmpVal = BL_CLR_REG_BIT(tmpVal, AON_XTAL_EXT_SEL_AON); BL_WR_REG(AON_BASE, AON_XTAL_CFG, tmpVal); - if (BL_IS_REG_BIT_SET(BL_RD_REG(GLB_BASE, GLB_CLK_CFG0), GLB_CHIP_RDY)) + if (BL_IS_REG_BIT_SET(BL_RD_REG(GLB_BASE, GLB_CLK_CFG0), GLB_CHIP_RDY)) { break; + } } } #endif @@ -464,9 +465,9 @@ uint32_t system_clock_get(enum system_clock_type type) { case SYSTEM_CLOCK_ROOT_CLOCK: if (GLB_Get_Root_CLK_Sel() == 0) { return 32 * 1000 * 1000; - } else if (GLB_Get_Root_CLK_Sel() == 1) + } else if (GLB_Get_Root_CLK_Sel() == 1) { return 32 * 1000 * 1000; - else { + } else { uint32_t tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); tmpVal = BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_PLL_SEL); if (tmpVal == 0) { diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c index 32ace75426..5a69576979 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c @@ -93,12 +93,14 @@ int uart_open(struct device *dev, uint16_t oflag) { if (oflag & DEVICE_OFLAG_STREAM_TX) {} if ((oflag & DEVICE_OFLAG_INT_TX) || (oflag & DEVICE_OFLAG_INT_RX)) { #ifdef BSP_USING_UART0 - if (uart_device->id == UART0_ID) - {Interrupt_Handler_Register(UART0_IRQn, UART0_IRQ);} + if (uart_device->id == UART0_ID) { + Interrupt_Handler_Register(UART0_IRQn, UART0_IRQ); + } #endif #ifdef BSP_USING_UART1 - if (uart_device->id == UART1_ID) + if (uart_device->id == UART1_ID) { Interrupt_Handler_Register(UART1_IRQn, UART1_IRQ); + } #endif } if (oflag & DEVICE_OFLAG_DMA_TX) { @@ -150,10 +152,11 @@ int uart_control(struct device *dev, int cmd, void *args) { } offset++; } - if (uart_device->id == UART0_ID) - {CPU_Interrupt_Enable(UART0_IRQn);} - else if (uart_device->id == UART1_ID) - {CPU_Interrupt_Enable(UART1_IRQn);} + if (uart_device->id == UART0_ID) { + CPU_Interrupt_Enable(UART0_IRQn); + } else if (uart_device->id == UART1_ID) { + CPU_Interrupt_Enable(UART1_IRQn); + } break; } @@ -165,10 +168,11 @@ int uart_control(struct device *dev, int cmd, void *args) { } offset++; } - if (uart_device->id == UART0_ID) - {CPU_Interrupt_Disable(UART0_IRQn);} - else if (uart_device->id == UART1_ID) - {CPU_Interrupt_Disable(UART1_IRQn);} + if (uart_device->id == UART0_ID) { + CPU_Interrupt_Disable(UART0_IRQn); + } else if (uart_device->id == UART1_ID) { + CPU_Interrupt_Disable(UART1_IRQn); + } break; } @@ -269,8 +273,9 @@ int uart_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t si uart_device_t *uart_device = (uart_device_t *)dev; if (dev->oflag & DEVICE_OFLAG_DMA_TX) { struct device *dma_ch = (struct device *)uart_device->tx_dma; - if (!dma_ch) -{ return -1;} + if (!dma_ch) { + return -1; + } if (uart_device->id == 0) { ret = dma_reload(dma_ch, (uint32_t)buffer, (uint32_t)DMA_ADDR_UART0_TDR, size); diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c index da66fc55f8..5c50725bf7 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c @@ -817,8 +817,9 @@ int usb_dc_ep_write(struct device *dev, const uint8_t ep, const uint8_t *data, u memcopy_to_fifo((void *)ep_tx_fifo_addr, (uint8_t *)data, data_len); /* Clear NAK and enable ep */ - if (USB_EP_GET_IDX(ep) != 0) + if (USB_EP_GET_IDX(ep) != 0) { USB_Set_EPx_Rdy(USB_EP_GET_IDX(ep)); + } USB_DC_LOG_DBG("EP%d write %u bytes\r\n", ep_idx, data_len); if (ret_bytes) { diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c index 61df6a9884..9de2920bc4 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c @@ -94,10 +94,12 @@ void mmheap_get_state(struct heap_info *pRoot, struct heap_state *pState) { for (struct heap_node *pNode = pRoot->pStart->next_node; pNode->next_node != NULL; pNode = pNode->next_node) { pState->remain_size += pNode->mem_size; pState->free_node_num++; - if (pNode->mem_size > pState->max_node_size) + if (pNode->mem_size > pState->max_node_size) { pState->max_node_size = pNode->mem_size; - if (pNode->mem_size < pState->min_node_size) + } + if (pNode->mem_size < pState->min_node_size) { pState->min_node_size = pNode->mem_size; + } } MMHEAP_UNLOCK(); } @@ -131,10 +133,12 @@ void *mmheap_align_alloc(struct heap_info *pRoot, size_t align_size, size_t want } MMHEAP_LOCK(); - if (want_size < MEM_MANAGE_MINUM_MEM_SIZE) + if (want_size < MEM_MANAGE_MINUM_MEM_SIZE) { want_size = MEM_MANAGE_MINUM_MEM_SIZE; - if (align_size < MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT) + } + if (align_size < MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT) { align_size = MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT; + } want_size = mmheap_align_up(want_size, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT); @@ -346,11 +350,13 @@ void mmheap_init(struct heap_info *pRoot, const struct heap_region *pRegion) { for (; pRegion->addr != NULL; pRegion++) { align_addr = (struct heap_node *)mmheap_align_up((size_t)pRegion->addr, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT); /*Calculate the aligned address*/ - if ((uint8_t *)align_addr > pRegion->mem_size + (uint8_t *)pRegion->addr) /*Alignment consumes more memory than the memory area*/ + if ((uint8_t *)align_addr > pRegion->mem_size + (uint8_t *)pRegion->addr) { /*Alignment consumes more memory than the memory area*/ continue; + } align_size = pRegion->mem_size - ((uint8_t *)align_addr - (uint8_t *)pRegion->addr); /*Calculate the size of memory left after alignment*/ - if (align_size < MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE) /*if Aligning the remaining memory is too small*/ + if (align_size < MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE) { /*if Aligning the remaining memory is too small*/ continue; + } align_size -= MEM_MANAGE_MEM_STRUCT_SIZE; /*Find the size of the memory block after removing the table header*/ align_addr->mem_size = align_size; align_addr->next_node = NULL; diff --git a/source/Core/BSP/Pinecilv2/board.c b/source/Core/BSP/Pinecilv2/board.c index a1ef0288aa..49f76f4a54 100644 --- a/source/Core/BSP/Pinecilv2/board.c +++ b/source/Core/BSP/Pinecilv2/board.c @@ -146,8 +146,9 @@ static void board_pin_mux_init(void) { /*if using gpio9-gpio12 and func is not analog and output ,should set reg_aon_pad_ie_smt corresponding bit = 1*/ if ((af_pin_table[i].pin > GPIO_PIN_8) && (af_pin_table[i].pin < GPIO_PIN_13)) { - if ((af_pin_table[i].func != 10) && ((af_pin_table[i].func < GPIO_FUN_GPIO_OUTPUT_UP) || (af_pin_table[i].func > GPIO_FUN_GPIO_OUTPUT_NONE))) + if ((af_pin_table[i].func != 10) && ((af_pin_table[i].func < GPIO_FUN_GPIO_OUTPUT_UP) || (af_pin_table[i].func > GPIO_FUN_GPIO_OUTPUT_NONE))) { hbn_aon_ie |= (1 << (af_pin_table[i].pin - 9)); + } } /*if reset state*/ diff --git a/source/Core/BSP/Sequre_S60/BSP.cpp b/source/Core/BSP/Sequre_S60/BSP.cpp index f960cd0dd0..3dbefcaf81 100644 --- a/source/Core/BSP/Sequre_S60/BSP.cpp +++ b/source/Core/BSP/Sequre_S60/BSP.cpp @@ -155,8 +155,9 @@ void unstick_I2C() { HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_SET); timeout_cnt++; - if (timeout_cnt > timeout) + if (timeout_cnt > timeout) { return; + } } // 12. Configure the SCL and SDA I/Os as Alternate function Open-Drain. diff --git a/source/Core/Drivers/Buttons.cpp b/source/Core/Drivers/Buttons.cpp index 4ab8718fba..8263742713 100644 --- a/source/Core/Drivers/Buttons.cpp +++ b/source/Core/Drivers/Buttons.cpp @@ -31,23 +31,27 @@ ButtonState getButtonState() { currentState = (getButtonA()) << 0; currentState |= (getButtonB()) << 1; - if (currentState) + if (currentState) { lastButtonTime = xTaskGetTickCount(); + } if (currentState == previousState) { - if (currentState == 0) + if (currentState == 0) { return BUTTON_NONE; + } if ((xTaskGetTickCount() - previousStateChange) >= timeout) { // User has been holding the button down // We want to send a button is held message longPressed = true; - if (currentState == 0x01) + if (currentState == 0x01) { return BUTTON_F_LONG; - else if (currentState == 0x02) + } else if (currentState == 0x02) { return BUTTON_B_LONG; - else + } else { return BUTTON_BOTH_LONG; // Both being held case - } else + } + } else { return BUTTON_NONE; + } } else { // A change in button state has occurred ButtonState retVal = BUTTON_NONE; @@ -65,12 +69,13 @@ ButtonState getButtonState() { // The user didn't hold the button for long // So we send button press - if (previousState == 0x01) + if (previousState == 0x01) { retVal = BUTTON_F_SHORT; - else if (previousState == 0x02) + } else if (previousState == 0x02) { retVal = BUTTON_B_SHORT; - else + } else { retVal = BUTTON_BOTH; // Both being held case + } } previousState = 0; longPressed = false; @@ -103,13 +108,15 @@ void waitForButtonPressOrTimeout(TickType_t timeout) { while (buttons) { buttons = getButtonState(); GUIDelay(); - if (xTaskGetTickCount() > timeout) + if (xTaskGetTickCount() > timeout) { return; + } } while (!buttons) { buttons = getButtonState(); GUIDelay(); - if (xTaskGetTickCount() > timeout) + if (xTaskGetTickCount() > timeout) { return; + } } } diff --git a/source/Core/Drivers/I2CBB1.cpp b/source/Core/Drivers/I2CBB1.cpp index 80909b2208..df83f3242d 100644 --- a/source/Core/Drivers/I2CBB1.cpp +++ b/source/Core/Drivers/I2CBB1.cpp @@ -45,8 +45,9 @@ void I2CBB1::init() { } bool I2CBB1::probe(uint8_t address) { - if (!lock()) + if (!lock()) { return false; + } start(); bool ack = send(address); stop(); @@ -55,8 +56,9 @@ bool I2CBB1::probe(uint8_t address) { } bool I2CBB1::Mem_Read(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return false; + } start(); bool ack = send(DevAddress); if (!ack) { @@ -91,8 +93,9 @@ bool I2CBB1::Mem_Read(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, } bool I2CBB1::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, const uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return false; + } start(); bool ack = send(DevAddress); if (!ack) { @@ -123,8 +126,9 @@ bool I2CBB1::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, const uint8_t * } void I2CBB1::Transmit(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return; + } start(); bool ack = send(DevAddress); if (!ack) { @@ -147,8 +151,9 @@ void I2CBB1::Transmit(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { } void I2CBB1::Receive(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return; + } start(); bool ack = send(DevAddress | 1); if (!ack) { @@ -166,10 +171,12 @@ void I2CBB1::Receive(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { } void I2CBB1::TransmitReceive(uint16_t DevAddress, uint8_t *pData_tx, uint16_t Size_tx, uint8_t *pData_rx, uint16_t Size_rx) { - if (Size_tx == 0 && Size_rx == 0) + if (Size_tx == 0 && Size_rx == 0) { return; - if (lock() == false) + } + if (lock() == false) { return; + } if (Size_tx) { start(); bool ack = send(DevAddress); @@ -251,10 +258,11 @@ uint8_t I2CBB1::read(bool ack) { } SOFT_SDA1_HIGH(); - if (ack) + if (ack) { write_bit(0); - else + } else { write_bit(1); + } return B; } @@ -266,10 +274,11 @@ uint8_t I2CBB1::read_bit() { SOFT_SCL1_HIGH(); SOFT_I2C_DELAY(); - if (SOFT_SDA1_READ()) + if (SOFT_SDA1_READ()) { b = 1; - else + } else { b = 0; + } SOFT_SCL1_LOW(); return b; @@ -309,16 +318,18 @@ bool I2CBB1::writeRegistersBulk(const uint8_t address, const I2C_REG *registers, if (!I2C_RegisterWrite(address, registers[index].reg, registers[index].val)) { return false; } - if (registers[index].pause_ms) + if (registers[index].pause_ms) { delay_ms(registers[index].pause_ms); + } } return true; } bool I2CBB1::wakePart(uint16_t DevAddress) { // wakepart is a special case where only the device address is sent - if (!lock()) + if (!lock()) { return false; + } start(); bool ack = send(DevAddress); stop(); diff --git a/source/Core/Drivers/I2CBB2.cpp b/source/Core/Drivers/I2CBB2.cpp index d0764d155e..6605018cd0 100644 --- a/source/Core/Drivers/I2CBB2.cpp +++ b/source/Core/Drivers/I2CBB2.cpp @@ -44,8 +44,9 @@ void I2CBB2::init() { } bool I2CBB2::probe(uint8_t address) { - if (!lock()) + if (!lock()) { return false; + } start(); bool ack = send(address); stop(); @@ -54,8 +55,9 @@ bool I2CBB2::probe(uint8_t address) { } bool I2CBB2::Mem_Read(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return false; + } start(); bool ack = send(DevAddress); if (!ack) { @@ -90,8 +92,9 @@ bool I2CBB2::Mem_Read(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, } bool I2CBB2::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, const uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return false; + } start(); bool ack = send(DevAddress); if (!ack) { @@ -122,8 +125,9 @@ bool I2CBB2::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, const uint8_t * } void I2CBB2::Transmit(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return; + } start(); bool ack = send(DevAddress); if (!ack) { @@ -146,8 +150,9 @@ void I2CBB2::Transmit(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { } void I2CBB2::Receive(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return; + } start(); bool ack = send(DevAddress | 1); if (!ack) { @@ -165,10 +170,12 @@ void I2CBB2::Receive(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { } void I2CBB2::TransmitReceive(uint16_t DevAddress, uint8_t *pData_tx, uint16_t Size_tx, uint8_t *pData_rx, uint16_t Size_rx) { - if (Size_tx == 0 && Size_rx == 0) + if (Size_tx == 0 && Size_rx == 0) { return; - if (lock() == false) + } + if (lock() == false) { return; + } if (Size_tx) { start(); bool ack = send(DevAddress); @@ -250,10 +257,11 @@ uint8_t I2CBB2::read(bool ack) { } SOFT_SDA2_HIGH(); - if (ack) + if (ack) { write_bit(0); - else + } else { write_bit(1); + } return B; } @@ -265,10 +273,11 @@ uint8_t I2CBB2::read_bit() { SOFT_SCL2_HIGH(); SOFT_I2C_DELAY(); - if (SOFT_SDA2_READ()) + if (SOFT_SDA2_READ()) { b = 1; - else + } else { b = 0; + } SOFT_SCL2_LOW(); return b; @@ -308,16 +317,18 @@ bool I2CBB2::writeRegistersBulk(const uint8_t address, const I2C_REG *registers, if (!I2C_RegisterWrite(address, registers[index].reg, registers[index].val)) { return false; } - if (registers[index].pause_ms) + if (registers[index].pause_ms) { delay_ms(registers[index].pause_ms); + } } return true; } bool I2CBB2::wakePart(uint16_t DevAddress) { // wakepart is a special case where only the device address is sent - if (!lock()) + if (!lock()) { return false; + } start(); bool ack = send(DevAddress); stop(); diff --git a/source/Core/Drivers/Si7210.cpp b/source/Core/Drivers/Si7210.cpp index 231b21a83c..0bffb671a4 100644 --- a/source/Core/Drivers/Si7210.cpp +++ b/source/Core/Drivers/Si7210.cpp @@ -31,27 +31,33 @@ bool Si7210::init() { } /* Disable periodic auto-wakeup by device, and tamper detect. */ - if ((!write_reg(SI7210_CTRL3, (uint8_t)~SL_TIMEENA_MASK, 0))) + if ((!write_reg(SI7210_CTRL3, (uint8_t)~SL_TIMEENA_MASK, 0))) { return false; + } /* Disable tamper detection by setting sw_tamper to 63 */ - if (!write_reg(SI7210_CTRL3, SL_FAST_MASK | SL_TIMEENA_MASK, 63 << 2)) + if (!write_reg(SI7210_CTRL3, SL_FAST_MASK | SL_TIMEENA_MASK, 63 << 2)) { return false; + } - if (!set_high_range()) + if (!set_high_range()) { return false; + } /* Stop the control loop by setting stop bit */ - if (!write_reg(SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, STOP_MASK)) /* WARNING: Removed USE_STORE MASK */ + if (!write_reg(SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, STOP_MASK)) { /* WARNING: Removed USE_STORE MASK */ return false; + } /* Use a burst size of 128/4096 samples in FIR and IIR modes */ - if (!write_reg(SI7210_CTRL4, 0, DF_BURSTSIZE_128 | DF_BW_4096)) + if (!write_reg(SI7210_CTRL4, 0, DF_BURSTSIZE_128 | DF_BW_4096)) { return false; + } /* Select field strength measurement */ - if (!write_reg(SI7210_DSPSIGSEL, 0, DSP_SIGSEL_FIELD_MASK)) + if (!write_reg(SI7210_DSPSIGSEL, 0, DSP_SIGSEL_FIELD_MASK)) { return false; + } return true; // start_periodic_measurement(); } @@ -84,8 +90,9 @@ bool Si7210::read_reg(const uint8_t reg, uint8_t *val) { return ACCEL_I2C_CLASS: bool Si7210::start_periodic_measurement() { /* Enable periodic wakeup */ - if (!write_reg(SI7210_CTRL3, (uint8_t)~SL_TIMEENA_MASK, SL_TIMEENA_MASK)) + if (!write_reg(SI7210_CTRL3, (uint8_t)~SL_TIMEENA_MASK, SL_TIMEENA_MASK)) { return false; + } /* Start measurement */ /* Change to ~STOP_MASK with STOP_MASK */ @@ -97,17 +104,20 @@ bool Si7210::get_field_strength(int16_t *field) { uint8_t val = 0; ACCEL_I2C_CLASS::wakePart(SI7210_ADDRESS); - if (!write_reg(SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, STOP_MASK)) + if (!write_reg(SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, STOP_MASK)) { return false; + } /* Read most-significant byte */ - if (!read_reg(SI7210_DSPSIGM, &val)) + if (!read_reg(SI7210_DSPSIGM, &val)) { return false; + } *field = (val & DSP_SIGM_DATA_MASK) << 8; /* Read least-significant byte of data */ - if (!read_reg(SI7210_DSPSIGL, &val)) + if (!read_reg(SI7210_DSPSIGL, &val)) { return false; + } *field += val; *field -= 16384U; diff --git a/source/Core/Threads/PIDThread.cpp b/source/Core/Threads/PIDThread.cpp index 615a966df6..2c23108f24 100644 --- a/source/Core/Threads/PIDThread.cpp +++ b/source/Core/Threads/PIDThread.cpp @@ -124,10 +124,11 @@ template struct PID { T output = kp_result + ki_result + kd_result; // Restrict to max / 0 - if (output > max_output) + if (output > max_output) { output = max_output; - else if (output < 0) + } else if (output < 0) { output = 0; + } // Save target_delta to previous target_delta previous_error_term = target_delta; From a2aab18e08fee18be2d2cc96f977c7aa7bc293ec Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Wed, 27 Dec 2023 00:09:50 +1100 Subject: [PATCH 15/18] We can drop the old messy bracket-checker with newer clang format --- scripts/deploy.sh | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/scripts/deploy.sh b/scripts/deploy.sh index f7964ce493..3f65426665 100755 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -91,21 +91,6 @@ check_style_file() fi; ret=1 fi; - # - clang-format has neat option for { } in condition blocks but it's available only since version 15: - # * https://clang.llvm.org/docs/ClangFormatStyleOptions.html#insertbraces - # - since reference env is alpine 3.16 with clang-format 13, implement custom parser to do the similar thing here with grep: - # it used to trace missing { and } for if/else/do/while/for BUT IT'S VERY SPECULATIVE, very-very hacky & dirty. - # - if file is problematic but filename only requested make final grep in pipe silent ... UPD: make code messy but shellcheck happy - if [ -z "${LIST}" ]; then - grep -H -n -e "^ .*if .*)$" -e "^ .*else$" -e "^ .* do$" -e "^ .*while .*)$" -e "^ .*for .*)$" "${src}" | grep -v -e "^.*//" -e "^.*:.*: .*if ((.*[^)])$" | sed 's,^,\n\n,; s,: ,:1: error: probably missing { or } for conditional or loop block:\n>>>,;' | grep -e "^.*$" - else - grep -H -n -e "^ .*if .*)$" -e "^ .*else$" -e "^ .* do$" -e "^ .*while .*)$" -e "^ .*for .*)$" "${src}" | grep -v -e "^.*//" -e "^.*:.*: .*if ((.*[^)])$" | sed 's,^,\n\n,; s,: ,:1: error: probably missing { or } for conditional or loop block:\n>>>,;' | grep -q -e "^.*$" - fi; - if [ "${?}" -ne 1 ]; then - # ... and only print the filename - test -z "${LIST}" || echo "${src}" - ret=1; - fi; return "${ret}" } From dee88cc987d1d3a0f6063a7f5b5eb60b0a8b7fd7 Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Wed, 27 Dec 2023 00:17:24 +1100 Subject: [PATCH 16/18] WiP formatter --- source/.clang-format | 158 ++++++++++++++++++++++++++++++++++--------- 1 file changed, 127 insertions(+), 31 deletions(-) diff --git a/source/.clang-format b/source/.clang-format index f67663939e..ee96b7b7a3 100644 --- a/source/.clang-format +++ b/source/.clang-format @@ -1,140 +1,236 @@ -# Roughly based on LLVM, tweaked a tad for readability on wide screens --- Language: Cpp # BasedOnStyle: LLVM AccessModifierOffset: -2 AlignAfterOpenBracket: Align -AlignConsecutiveMacros: true -AlignConsecutiveAssignments: true -AlignConsecutiveDeclarations: true -AlignEscapedNewlines: Left -AlignOperands: true -AlignTrailingComments: true +AlignArrayOfStructures: Right +AlignConsecutiveAssignments: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCaseColons: false +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 AllowAllArgumentsOnNextLine: true -AllowAllConstructorInitializersOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true -AllowShortBlocksOnASingleLine: Empty +AllowShortBlocksOnASingleLine: Never AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: true AllowShortFunctionsOnASingleLine: All -AllowShortLambdasOnASingleLine: All AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All AllowShortLoopsOnASingleLine: false -AllowShortEnumsOnASingleLine: false ### <<< Keeps enums as is AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability BinPackArguments: true BinPackParameters: true +BitFieldColonSpacing: Both BraceWrapping: AfterCaseLabel: false AfterClass: false - AfterControlStatement: false + AfterControlStatement: Never AfterEnum: false + AfterExternBlock: false AfterFunction: false AfterNamespace: false AfterObjCDeclaration: false AfterStruct: false AfterUnion: false - AfterExternBlock: false BeforeCatch: false BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: true -BreakBeforeBinaryOperators: true +BreakAfterAttributes: Never +BreakAfterJavaFieldAnnotations: false +BreakArrays: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: Always BreakBeforeBraces: Attach -BreakBeforeInheritanceComma: false -BreakInheritanceList: BeforeColon +BreakBeforeInlineASMColon: OnlyMultiline BreakBeforeTernaryOperators: true -BreakConstructorInitializersBeforeComma: false BreakConstructorInitializers: BeforeColon -BreakAfterJavaFieldAnnotations: false +BreakInheritanceList: BeforeColon BreakStringLiterals: true -ColumnLimit: 200 +ColumnLimit: 80 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false -ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: true -DeriveLineEnding: true DerivePointerAlignment: false DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock ExperimentalAutoDetectBinPacking: false FixNamespaceComments: true ForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE IncludeBlocks: Preserve IncludeCategories: - Regex: '^"(llvm|llvm-c|clang|clang-c)/' Priority: 2 SortPriority: 0 + CaseSensitive: false - Regex: '^(<|"(gtest|gmock|isl|json)/)' Priority: 3 SortPriority: 0 + CaseSensitive: false - Regex: '.*' Priority: 1 SortPriority: 0 + CaseSensitive: false IncludeIsMainRegex: '(Test)?$' IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false IndentCaseLabels: false +IndentExternBlock: AfterExternBlock IndentGotoLabels: true IndentPPDirectives: None +IndentRequiresClause: true IndentWidth: 2 IndentWrappedFunctionNames: false -InsertBraces: true +InsertBraces: false +InsertNewlineAtEOF: false +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: true +KeepEmptyLinesAtEOF: false +LambdaBodyIndentation: Signature +LineEnding: DeriveLF MacroBlockBegin: '' MacroBlockEnd: '' MaxEmptyLinesToKeep: 1 NamespaceIndentation: None ObjCBinPackProtocolList: Auto ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true +PackConstructorInitializers: BinPack PenaltyBreakAssignment: 2 PenaltyBreakBeforeFirstCallParameter: 19 PenaltyBreakComment: 300 PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 PenaltyBreakString: 1000 PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Right +PPIndentWidth: -1 +QualifierAlignment: Leave +ReferenceAlignment: Pointer ReflowComments: true -SortIncludes: true -SortUsingDeclarations: true +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric SpaceAfterCStyleCast: false SpaceAfterLogicalNot: false SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false SpaceBeforeCpp11BracedList: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false SpaceInEmptyBlock: false -SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 1 -SpacesInAngles: false -SpacesInConditionalStatement: false +SpacesInAngles: Never SpacesInContainerLiterals: true -SpacesInCStyleCastParentheses: false -SpacesInParentheses: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false SpacesInSquareBrackets: false -SpaceBeforeSquareBrackets: false Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT StatementMacros: - Q_UNUSED - QT_REQUIRE_VERSION TabWidth: 8 -UseCRLF: false UseTab: Never +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE ... From 887d5f0481fe3bbfd748b8b31cfdbdd559b1d371 Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Wed, 27 Dec 2023 00:19:40 +1100 Subject: [PATCH 17/18] Align grids of scripts by right side Massively easier to read in nearly all cases --- source/.clang-format | 150 +-- source/Core/BSP/MHP30/Setup.c | 4 +- .../STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c | 7 +- .../Src/stm32f1xx_hal_adc.c | 12 +- .../Src/stm32f1xx_hal_adc_ex.c | 4 +- .../Src/stm32f1xx_hal_cortex.c | 6 +- .../Src/stm32f1xx_hal_rcc.c | 8 +- .../Src/stm32f1xx_hal_rcc_ex.c | 8 +- .../Src/stm32f1xx_hal_tim.c | 24 +- .../Src/stm32f1xx_hal_tim_ex.c | 8 +- source/Core/BSP/MHP30/system_stm32f1xx.c | 4 +- .../STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c | 7 +- .../Src/stm32f1xx_hal_adc.c | 12 +- .../Src/stm32f1xx_hal_adc_ex.c | 4 +- .../Src/stm32f1xx_hal_cortex.c | 6 +- .../Src/stm32f1xx_hal_i2c.c | 4 +- .../Src/stm32f1xx_hal_rcc.c | 8 +- .../Src/stm32f1xx_hal_rcc_ex.c | 8 +- .../Src/stm32f1xx_hal_tim.c | 24 +- .../Src/stm32f1xx_hal_tim_ex.c | 8 +- source/Core/BSP/Miniware/port.c | 3 +- source/Core/BSP/Miniware/system_stm32f1xx.c | 4 +- source/Core/BSP/Pinecil/I2C_Wrapper.cpp | 24 +- .../Common/Source/Drivers/Usb/drv_usb_dev.c | 4 +- .../Common/Source/Drivers/Usb/drv_usbd_int.c | 7 +- .../Common/Source/Drivers/Usb/usbd_enum.c | 4 +- .../Common/Source/Drivers/Usb/usbh_enum.c | 92 +- .../Common/Source/Drivers/gd32vf103_adc.c | 6 +- .../Common/Source/Drivers/gd32vf103_dma.c | 5 +- .../Common/Source/Drivers/gd32vf103_exmc.c | 16 +- .../Common/Source/Drivers/gd32vf103_fmc.c | 3 +- .../Common/Source/Drivers/gd32vf103_rcu.c | 4 +- .../Common/Source/Drivers/gd32vf103_rtc.c | 6 +- .../Common/Source/Drivers/gd32vf103_timer.c | 4 +- .../Common/Source/system_gd32vf103.c | 24 +- source/Core/BSP/Pinecilv2/Setup.cpp | 8 +- .../bsp/bsp_common/platform/bflb_platform.c | 3 +- .../bsp/bsp_common/platform/syscalls.c | 3 +- .../Pinecilv2/bl_mcu_sdk/common/misc/misc.c | 3 +- .../bl_mcu_sdk/common/soft_crc/softcrc.c | 70 +- .../bl_mcu_sdk/common/timestamp/timestamp.c | 4 +- .../components/ble/ble_stack/common/buf.c | 10 +- .../common/tinycrypt/source/aes_decrypt.c | 18 +- .../common/tinycrypt/source/aes_encrypt.c | 18 +- .../common/tinycrypt/source/cbc_mode.c | 8 +- .../common/tinycrypt/source/ccm_mode.c | 8 +- .../ble_stack/common/tinycrypt/source/ecc.c | 3 +- .../common/tinycrypt/source/sha256.c | 10 +- .../components/ble/ble_stack/host/att.c | 78 +- .../components/ble/ble_stack/host/conn.c | 21 +- .../components/ble/ble_stack/host/gatt.c | 17 +- .../components/ble/ble_stack/host/hci_core.c | 6 +- .../components/ble/ble_stack/host/hci_ecc.c | 6 +- .../components/ble/ble_stack/host/hfp_hf.c | 18 +- .../components/ble/ble_stack/host/sdp.c | 4 +- .../ble/ble_stack/sbc/dec/bitalloc.c | 16 +- .../ble/ble_stack/sbc/dec/framing.c | 40 +- .../ble_stack/sbc/dec/synthesis-8-generated.c | 14 +- .../ble/ble_stack/sbc/dec/synthesis-dct8.c | 12 +- .../ble/ble_stack/sbc/dec/synthesis-sbc.c | 20 +- .../ble/ble_stack/sbc/enc/sbc_analysis.c | 1068 ++++++++--------- .../ble/ble_stack/sbc/enc/sbc_dct_coeffs.c | 40 +- .../sbc/enc/sbc_enc_bit_alloc_mono.c | 14 +- .../ble/ble_stack/sbc/enc/sbc_enc_coeffs.c | 130 +- .../ble/ble_stack/sbc/enc/sbc_encoder.c | 14 +- .../ble/ble_stack/sbc/enc/sbc_packing.c | 26 +- .../components/ble/ble_stack/services/hog.c | 4 +- .../components/ble/ble_stack/services/scps.c | 4 +- .../freertos/portable/gcc/risc-v/bl702/port.c | 8 +- .../bl702_driver/hal_drv/src/hal_common.c | 3 +- .../bl702_driver/hal_drv/src/hal_dma.c | 26 +- .../drivers/bl702_driver/hal_drv/src/hal_pm.c | 855 ++++++------- .../bl702_driver/hal_drv/src/hal_sec_ecdsa.c | 164 +-- .../bl702_driver/hal_drv/src/hal_uart.c | 3 +- .../bl702_driver/hal_drv/src/hal_usb.c | 3 +- .../drivers/bl702_driver/startup/drv_mmheap.c | 6 +- .../drivers/bl702_driver/startup/interrupt.c | 9 +- .../bl702_driver/std_drv/src/bl702_adc.c | 20 +- .../bl702_driver/std_drv/src/bl702_aon.c | 20 +- .../bl702_driver/std_drv/src/bl702_dac.c | 20 +- .../bl702_driver/std_drv/src/bl702_dma.c | 7 +- .../bl702_driver/std_drv/src/bl702_ef_ctrl.c | 42 +- .../bl702_driver/std_drv/src/bl702_glb.c | 32 +- .../bl702_driver/std_drv/src/bl702_hbn.c | 20 +- .../bl702_driver/std_drv/src/bl702_i2c.c | 12 +- .../bl702_driver/std_drv/src/bl702_i2s.c | 6 +- .../bl702_driver/std_drv/src/bl702_ir.c | 10 +- .../bl702_driver/std_drv/src/bl702_pds.c | 10 +- .../bl702_driver/std_drv/src/bl702_psram.c | 24 +- .../bl702_driver/std_drv/src/bl702_qdec.c | 6 +- .../bl702_driver/std_drv/src/bl702_sec_eng.c | 84 +- .../bl702_driver/std_drv/src/bl702_sf_cfg.c | 442 +++---- .../std_drv/src/bl702_sf_cfg_ext.c | 144 +-- .../bl702_driver/std_drv/src/bl702_sflash.c | 4 +- .../std_drv/src/bl702_sflash_ext.c | 4 +- .../bl702_driver/std_drv/src/bl702_timer.c | 6 +- .../bl702_driver/std_drv/src/bl702_uart.c | 3 +- source/Core/BSP/Pinecilv2/board.c | 20 +- source/Core/BSP/Sequre_S60/Setup.cpp | 4 +- .../STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c | 7 +- .../Src/stm32f1xx_hal_adc.c | 12 +- .../Src/stm32f1xx_hal_adc_ex.c | 4 +- .../Src/stm32f1xx_hal_cortex.c | 6 +- .../Src/stm32f1xx_hal_i2c.c | 4 +- .../Src/stm32f1xx_hal_rcc.c | 8 +- .../Src/stm32f1xx_hal_rcc_ex.c | 8 +- .../Src/stm32f1xx_hal_tim.c | 24 +- .../Src/stm32f1xx_hal_tim_ex.c | 8 +- source/Core/BSP/Sequre_S60/port.c | 3 +- source/Core/BSP/Sequre_S60/system_stm32f1xx.c | 4 +- source/Core/Drivers/BMA223.cpp | 20 +- source/Core/Drivers/I2CBB1.cpp | 3 +- source/Core/Drivers/I2CBB2.cpp | 3 +- source/Core/Drivers/LIS2DH12.cpp | 28 +- source/Core/Drivers/MMA8652FC.cpp | 26 +- source/Core/Drivers/MSA301.cpp | 13 +- source/Core/Drivers/OLED.cpp | 50 +- source/Core/Drivers/SC7A20.cpp | 60 +- source/Core/Drivers/USBPD.cpp | 3 +- source/Core/Src/Settings.cpp | 108 +- source/Core/Src/main.cpp | 3 +- .../Threads/OperatingModes/HomeScreen.cpp | 4 +- source/Core/brieflz/depack.c | 461 +++---- 123 files changed, 2622 insertions(+), 2505 deletions(-) diff --git a/source/.clang-format b/source/.clang-format index ee96b7b7a3..a7bddf26a0 100644 --- a/source/.clang-format +++ b/source/.clang-format @@ -1,43 +1,43 @@ --- -Language: Cpp +Language: Cpp # BasedOnStyle: LLVM AccessModifierOffset: -2 AlignAfterOpenBracket: Align AlignArrayOfStructures: Right AlignConsecutiveAssignments: - Enabled: true + Enabled: true AcrossEmptyLines: false - AcrossComments: false - AlignCompound: false - PadOperators: true + AcrossComments: false + AlignCompound: false + PadOperators: true AlignConsecutiveBitFields: - Enabled: true + Enabled: true AcrossEmptyLines: false - AcrossComments: false - AlignCompound: false - PadOperators: false + AcrossComments: false + AlignCompound: false + PadOperators: false AlignConsecutiveDeclarations: - Enabled: true + Enabled: true AcrossEmptyLines: false - AcrossComments: false - AlignCompound: false - PadOperators: false + AcrossComments: false + AlignCompound: false + PadOperators: false AlignConsecutiveMacros: - Enabled: true + Enabled: true AcrossEmptyLines: false - AcrossComments: false - AlignCompound: false - PadOperators: false + AcrossComments: false + AlignCompound: false + PadOperators: false AlignConsecutiveShortCaseStatements: - Enabled: true + Enabled: true AcrossEmptyLines: false - AcrossComments: false + AcrossComments: false AlignCaseColons: false AlignEscapedNewlines: Right -AlignOperands: Align +AlignOperands: Align AlignTrailingComments: - Kind: Always - OverEmptyLines: 0 + Kind: Always + OverEmptyLines: 0 AllowAllArgumentsOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: Never @@ -57,27 +57,27 @@ BinPackArguments: true BinPackParameters: true BitFieldColonSpacing: Both BraceWrapping: - AfterCaseLabel: false - AfterClass: false + AfterCaseLabel: false + AfterClass: false AfterControlStatement: Never - AfterEnum: false + AfterEnum: false AfterExternBlock: false - AfterFunction: false - AfterNamespace: false + AfterFunction: false + AfterNamespace: false AfterObjCDeclaration: false - AfterStruct: false - AfterUnion: false - BeforeCatch: false - BeforeElse: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false BeforeLambdaBody: false - BeforeWhile: false - IndentBraces: false + BeforeWhile: false + IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: true BreakAfterAttributes: Never BreakAfterJavaFieldAnnotations: false -BreakArrays: true +BreakArrays: true BreakBeforeBinaryOperators: None BreakBeforeConceptDeclarations: Always BreakBeforeBraces: Attach @@ -86,14 +86,14 @@ BreakBeforeTernaryOperators: true BreakConstructorInitializers: BeforeColon BreakInheritanceList: BeforeColon BreakStringLiterals: true -ColumnLimit: 80 -CommentPragmas: '^ IWYU pragma:' +ColumnLimit: 200 +CommentPragmas: "^ IWYU pragma:" CompactNamespaces: false ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: true DerivePointerAlignment: false -DisableFormat: false +DisableFormat: false EmptyLineAfterAccessModifier: Never EmptyLineBeforeAccessModifier: LogicalBlock ExperimentalAutoDetectBinPacking: false @@ -104,22 +104,22 @@ ForEachMacros: - BOOST_FOREACH IfMacros: - KJ_IF_MAYBE -IncludeBlocks: Preserve +IncludeBlocks: Preserve IncludeCategories: - - Regex: '^"(llvm|llvm-c|clang|clang-c)/' - Priority: 2 - SortPriority: 0 - CaseSensitive: false - - Regex: '^(<|"(gtest|gmock|isl|json)/)' - Priority: 3 - SortPriority: 0 - CaseSensitive: false - - Regex: '.*' - Priority: 1 - SortPriority: 0 - CaseSensitive: false -IncludeIsMainRegex: '(Test)?$' -IncludeIsMainSourceRegex: '' + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: ".*" + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: "(Test)?$" +IncludeIsMainSourceRegex: "" IndentAccessModifiers: false IndentCaseBlocks: false IndentCaseLabels: false @@ -127,26 +127,26 @@ IndentExternBlock: AfterExternBlock IndentGotoLabels: true IndentPPDirectives: None IndentRequiresClause: true -IndentWidth: 2 +IndentWidth: 2 IndentWrappedFunctionNames: false -InsertBraces: false +InsertBraces: false InsertNewlineAtEOF: false InsertTrailingCommas: None IntegerLiteralSeparator: - Binary: 0 + Binary: 0 BinaryMinDigits: 0 - Decimal: 0 + Decimal: 0 DecimalMinDigits: 0 - Hex: 0 - HexMinDigits: 0 + Hex: 0 + HexMinDigits: 0 JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: true KeepEmptyLinesAtEOF: false LambdaBodyIndentation: Signature -LineEnding: DeriveLF -MacroBlockBegin: '' -MacroBlockEnd: '' +LineEnding: DeriveLF +MacroBlockBegin: "" +MacroBlockEnd: "" MaxEmptyLinesToKeep: 1 NamespaceIndentation: None ObjCBinPackProtocolList: Auto @@ -166,10 +166,10 @@ PenaltyExcessCharacter: 1000000 PenaltyIndentedWhitespace: 0 PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Right -PPIndentWidth: -1 +PPIndentWidth: -1 QualifierAlignment: Leave ReferenceAlignment: Pointer -ReflowComments: true +ReflowComments: true RemoveBracesLLVM: false RemoveParentheses: Leave RemoveSemicolon: false @@ -177,7 +177,7 @@ RequiresClausePosition: OwnLine RequiresExpressionIndentation: OuterScope SeparateDefinitionBlocks: Leave ShortNamespaceLines: 1 -SortIncludes: CaseSensitive +SortIncludes: CaseSensitive SortJavaStaticImport: Before SortUsingDeclarations: LexicographicNumeric SpaceAfterCStyleCast: false @@ -196,7 +196,7 @@ SpaceBeforeParensOptions: AfterForeachMacros: true AfterFunctionDefinitionName: false AfterFunctionDeclarationName: false - AfterIfMacros: true + AfterIfMacros: true AfterOverloadedOperator: false AfterRequiresInClause: false AfterRequiresInExpression: false @@ -205,26 +205,26 @@ SpaceBeforeRangeBasedForLoopColon: true SpaceBeforeSquareBrackets: false SpaceInEmptyBlock: false SpacesBeforeTrailingComments: 1 -SpacesInAngles: Never +SpacesInAngles: Never SpacesInContainerLiterals: true SpacesInLineCommentPrefix: - Minimum: 1 - Maximum: -1 -SpacesInParens: Never + Minimum: 1 + Maximum: -1 +SpacesInParens: Never SpacesInParensOptions: - InCStyleCasts: false + InCStyleCasts: false InConditionalStatements: false InEmptyParentheses: false - Other: false + Other: false SpacesInSquareBrackets: false -Standard: Latest +Standard: Latest StatementAttributeLikeMacros: - Q_EMIT StatementMacros: - Q_UNUSED - QT_REQUIRE_VERSION -TabWidth: 8 -UseTab: Never +TabWidth: 8 +UseTab: Never VerilogBreakBetweenInstancePorts: true WhitespaceSensitiveMacros: - BOOST_PP_STRINGIZE @@ -232,5 +232,5 @@ WhitespaceSensitiveMacros: - NS_SWIFT_NAME - PP_STRINGIZE - STRINGIZE -... +--- diff --git a/source/Core/BSP/MHP30/Setup.c b/source/Core/BSP/MHP30/Setup.c index 8eaaaf3545..b354c6e3a0 100644 --- a/source/Core/BSP/MHP30/Setup.c +++ b/source/Core/BSP/MHP30/Setup.c @@ -336,8 +336,8 @@ static void MX_GPIO_Init(void) { GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_10 | GPIO_PIN_15; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); - GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_12 - | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15; + GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_12 | + GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /*Configure GPIO pins : KEY_B_Pin KEY_A_Pin */ diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c index f71efb0f47..4f8a7576f6 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c @@ -139,8 +139,8 @@ HAL_TickFreqTypeDef uwTickFreq = HAL_TICK_FREQ_DEFAULT; /* 1KHz */ HAL_StatusTypeDef HAL_Init(void) { /* Configure Flash prefetch */ #if (PREFETCH_ENABLE != 0) -#if defined(STM32F101x6) || defined(STM32F101xB) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) \ - || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) +#if defined(STM32F101x6) || defined(STM32F101xB) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) || \ + defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) /* Prefetch buffer is not available on value line devices */ __HAL_FLASH_PREFETCH_BUFFER_ENABLE(); @@ -347,7 +347,8 @@ __weak void HAL_Delay(uint32_t Delay) { wait += (uint32_t)(uwTickFreq); } - while ((HAL_GetTick() - tickstart) < wait) {} + while ((HAL_GetTick() - tickstart) < wait) { + } } /** diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c index bb7ac4fcf1..d0ea179adc 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c @@ -620,12 +620,12 @@ HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc) { __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD | ADC_FLAG_JEOC | ADC_FLAG_EOC | ADC_FLAG_JSTRT | ADC_FLAG_STRT)); /* Reset register CR1 */ - CLEAR_BIT(hadc->Instance->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM | ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO | ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE | ADC_CR1_AWDIE - | ADC_CR1_EOCIE | ADC_CR1_AWDCH)); + CLEAR_BIT(hadc->Instance->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM | ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO | ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE | + ADC_CR1_AWDIE | ADC_CR1_EOCIE | ADC_CR1_AWDCH)); /* Reset register CR2 */ - CLEAR_BIT(hadc->Instance->CR2, (ADC_CR2_TSVREFE | ADC_CR2_SWSTART | ADC_CR2_JSWSTART | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL | ADC_CR2_ALIGN | ADC_CR2_DMA - | ADC_CR2_RSTCAL | ADC_CR2_CAL | ADC_CR2_CONT | ADC_CR2_ADON)); + CLEAR_BIT(hadc->Instance->CR2, (ADC_CR2_TSVREFE | ADC_CR2_SWSTART | ADC_CR2_JSWSTART | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL | ADC_CR2_ALIGN | ADC_CR2_DMA | + ADC_CR2_RSTCAL | ADC_CR2_CAL | ADC_CR2_CONT | ADC_CR2_ADON)); /* Reset register SMPR1 */ CLEAR_BIT(hadc->Instance->SMPR1, (ADC_SMPR1_SMP17 | ADC_SMPR1_SMP16 | ADC_SMPR1_SMP15 | ADC_SMPR1_SMP14 | ADC_SMPR1_SMP13 | ADC_SMPR1_SMP12 | ADC_SMPR1_SMP11 | ADC_SMPR1_SMP10)); @@ -1874,8 +1874,8 @@ HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef *hadc, ADC_AnalogWDG assert_param(IS_ADC_RANGE(AnalogWDGConfig->HighThreshold)); assert_param(IS_ADC_RANGE(AnalogWDGConfig->LowThreshold)); - if ((AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG) || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC) - || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC)) { + if ((AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG) || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC) || + (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC)) { assert_param(IS_ADC_CHANNEL(AnalogWDGConfig->Channel)); } diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c index e24c8e54dc..ce5414e982 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c @@ -941,8 +941,8 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_I ADC_JSQR_JL | ADC_JSQR_RK_JL(ADC_JSQR_JSQ1, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion), - ADC_JSQR_JL_SHIFT(sConfigInjected->InjectedNbrOfConversion) - | ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion)); + ADC_JSQR_JL_SHIFT(sConfigInjected->InjectedNbrOfConversion) | + ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion)); } else { /* Clear the old SQx bits for the selected rank */ MODIFY_REG(hadc->Instance->JSQR, diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c index c77c460850..f644499729 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c @@ -305,9 +305,9 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) { assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); MPU->RBAR = MPU_Init->BaseAddress; - MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) - | ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) - | ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); + MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | + ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | + ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); } else { MPU->RBAR = 0x00U; MPU->RASR = 0x00U; diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c index dfea429d1f..f1a5d2c3b9 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c @@ -387,8 +387,8 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { assert_param(IS_RCC_CALIBRATION_VALUE(RCC_OscInitStruct->HSICalibrationValue)); /* Check if HSI is used as system clock or as PLL source when PLL is selected as system clock */ - if ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI) - || ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI_DIV2))) { + if ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI) || + ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI_DIV2))) { /* When HSI is used as system clock it will not disabled */ if ((__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) && (RCC_OscInitStruct->HSIState != RCC_HSI_ON)) { return HAL_ERROR; @@ -535,8 +535,8 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { if ((RCC_OscInitStruct->PLL2.PLL2State) != RCC_PLL2_NONE) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { if ((RCC_OscInitStruct->PLL2.PLL2State) == RCC_PLL2_ON) { diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c index 63f0523b67..4051fb9107 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c @@ -654,8 +654,8 @@ HAL_StatusTypeDef HAL_RCCEx_EnablePLL2(RCC_PLL2InitTypeDef *PLL2Init) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { /* Check the parameters */ @@ -714,8 +714,8 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLL2(void) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { /* Disable the main PLL2. */ diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c index 1990dcc574..c7e3f8cdac 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c @@ -2450,8 +2450,8 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t Outpu UNUSED(OutputChannel); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -2541,8 +2541,8 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t Ou UNUSED(OutputChannel); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -2874,8 +2874,8 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channe TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); @@ -2997,8 +2997,8 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Cha TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); @@ -3142,11 +3142,11 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Ch return HAL_ERROR; } } else { - if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) - || (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) { + if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || + (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) { return HAL_BUSY; - } else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (channel_2_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY) - && (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) { + } else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (channel_2_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && + (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) { if ((((pData1 == NULL) || (pData2 == NULL))) && (Length > 0U)) { return HAL_ERROR; } else { diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c index 9d6123bf29..87f66c3fdc 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c @@ -311,8 +311,8 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim) { assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -382,8 +382,8 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim) { assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } diff --git a/source/Core/BSP/MHP30/system_stm32f1xx.c b/source/Core/BSP/MHP30/system_stm32f1xx.c index 944abbccc4..e9b08e1064 100644 --- a/source/Core/BSP/MHP30/system_stm32f1xx.c +++ b/source/Core/BSP/MHP30/system_stm32f1xx.c @@ -3,8 +3,8 @@ #include "stm32f1xx.h" #if !defined(HSI_VALUE) -#define HSI_VALUE \ - 8000000U /*!< Default value of the Internal oscillator in Hz. \ +#define HSI_VALUE \ + 8000000U /*!< Default value of the Internal oscillator in Hz. \ This value can be provided and adapted by the user application. */ #endif /* HSI_VALUE */ diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c index cb32ffdf1c..8725243aa8 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c @@ -155,8 +155,8 @@ HAL_TickFreqTypeDef uwTickFreq = HAL_TICK_FREQ_DEFAULT; /* 1KHz */ HAL_StatusTypeDef HAL_Init(void) { /* Configure Flash prefetch */ #if (PREFETCH_ENABLE != 0) -#if defined(STM32F101x6) || defined(STM32F101xB) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) \ - || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) +#if defined(STM32F101x6) || defined(STM32F101xB) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) || \ + defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) /* Prefetch buffer is not available on value line devices */ __HAL_FLASH_PREFETCH_BUFFER_ENABLE(); @@ -352,7 +352,8 @@ __weak void HAL_Delay(uint32_t Delay) { wait += (uint32_t)(uwTickFreq); } - while ((HAL_GetTick() - tickstart) < wait) {} + while ((HAL_GetTick() - tickstart) < wait) { + } } /** diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c index 712af4d4c1..19ac9e7db1 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c @@ -555,12 +555,12 @@ HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc) { __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD | ADC_FLAG_JEOC | ADC_FLAG_EOC | ADC_FLAG_JSTRT | ADC_FLAG_STRT)); /* Reset register CR1 */ - CLEAR_BIT(hadc->Instance->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM | ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO | ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE | ADC_CR1_AWDIE - | ADC_CR1_EOCIE | ADC_CR1_AWDCH)); + CLEAR_BIT(hadc->Instance->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM | ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO | ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE | + ADC_CR1_AWDIE | ADC_CR1_EOCIE | ADC_CR1_AWDCH)); /* Reset register CR2 */ - CLEAR_BIT(hadc->Instance->CR2, (ADC_CR2_TSVREFE | ADC_CR2_SWSTART | ADC_CR2_JSWSTART | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL | ADC_CR2_ALIGN | ADC_CR2_DMA - | ADC_CR2_RSTCAL | ADC_CR2_CAL | ADC_CR2_CONT | ADC_CR2_ADON)); + CLEAR_BIT(hadc->Instance->CR2, (ADC_CR2_TSVREFE | ADC_CR2_SWSTART | ADC_CR2_JSWSTART | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL | ADC_CR2_ALIGN | ADC_CR2_DMA | + ADC_CR2_RSTCAL | ADC_CR2_CAL | ADC_CR2_CONT | ADC_CR2_ADON)); /* Reset register SMPR1 */ CLEAR_BIT(hadc->Instance->SMPR1, (ADC_SMPR1_SMP17 | ADC_SMPR1_SMP16 | ADC_SMPR1_SMP15 | ADC_SMPR1_SMP14 | ADC_SMPR1_SMP13 | ADC_SMPR1_SMP12 | ADC_SMPR1_SMP11 | ADC_SMPR1_SMP10)); @@ -1495,8 +1495,8 @@ HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef *hadc, ADC_AnalogWDG assert_param(IS_ADC_RANGE(AnalogWDGConfig->HighThreshold)); assert_param(IS_ADC_RANGE(AnalogWDGConfig->LowThreshold)); - if ((AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG) || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC) - || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC)) { + if ((AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG) || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC) || + (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC)) { assert_param(IS_ADC_CHANNEL(AnalogWDGConfig->Channel)); } diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c index 8412668478..03c947f341 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c @@ -963,8 +963,8 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_I ADC_JSQR_JL | ADC_JSQR_RK_JL(ADC_JSQR_JSQ1, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion), - ADC_JSQR_JL_SHIFT(sConfigInjected->InjectedNbrOfConversion) - | ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion)); + ADC_JSQR_JL_SHIFT(sConfigInjected->InjectedNbrOfConversion) | + ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion)); } else { /* Clear the old SQx bits for the selected rank */ MODIFY_REG(hadc->Instance->JSQR, diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c index e1f9b4e4ac..b973ec025d 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c @@ -321,9 +321,9 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) { assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); MPU->RBAR = MPU_Init->BaseAddress; - MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) - | ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) - | ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); + MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | + ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | + ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); } else { MPU->RBAR = 0x00U; MPU->RASR = 0x00U; diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c index b442a4432b..2c38ddb99f 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c @@ -3181,8 +3181,8 @@ void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c) { tmp2 = hi2c->XferCount; tmp3 = hi2c->State; tmp4 = hi2c->PreviousState; - if ((tmp1 == HAL_I2C_MODE_SLAVE) && (tmp2 == 0U) - && ((tmp3 == HAL_I2C_STATE_BUSY_TX) || (tmp3 == HAL_I2C_STATE_BUSY_TX_LISTEN) || ((tmp3 == HAL_I2C_STATE_LISTEN) && (tmp4 == I2C_STATE_SLAVE_BUSY_TX)))) { + if ((tmp1 == HAL_I2C_MODE_SLAVE) && (tmp2 == 0U) && + ((tmp3 == HAL_I2C_STATE_BUSY_TX) || (tmp3 == HAL_I2C_STATE_BUSY_TX_LISTEN) || ((tmp3 == HAL_I2C_STATE_LISTEN) && (tmp4 == I2C_STATE_SLAVE_BUSY_TX)))) { } else { hi2c->ErrorCode |= HAL_I2C_ERROR_AF; diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c index e56f9cbd01..56515b0b9b 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c @@ -360,8 +360,8 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { assert_param(IS_RCC_CALIBRATION_VALUE(RCC_OscInitStruct->HSICalibrationValue)); /* Check if HSI is used as system clock or as PLL source when PLL is selected as system clock */ - if ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI) - || ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI_DIV2))) { + if ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI) || + ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI_DIV2))) { /* When HSI is used as system clock it will not disabled */ if ((__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) && (RCC_OscInitStruct->HSIState != RCC_HSI_ON)) { return HAL_ERROR; @@ -416,8 +416,8 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { if ((RCC_OscInitStruct->PLL2.PLL2State) != RCC_PLL2_NONE) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { if ((RCC_OscInitStruct->PLL2.PLL2State) == RCC_PLL2_ON) { diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c index a3735b9b82..25e902fa0e 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c @@ -670,8 +670,8 @@ HAL_StatusTypeDef HAL_RCCEx_EnablePLL2(RCC_PLL2InitTypeDef *PLL2Init) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { /* Check the parameters */ @@ -730,8 +730,8 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLL2(void) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { /* Disable the main PLL2. */ diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c index 18e2fc3770..dfa0b557fc 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c @@ -2450,8 +2450,8 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t Outpu UNUSED(OutputChannel); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -2541,8 +2541,8 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t Ou UNUSED(OutputChannel); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -2874,8 +2874,8 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channe TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); @@ -2997,8 +2997,8 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Cha TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); @@ -3142,11 +3142,11 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Ch return HAL_ERROR; } } else { - if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) - || (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) { + if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || + (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) { return HAL_BUSY; - } else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (channel_2_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY) - && (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) { + } else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (channel_2_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && + (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) { if ((((pData1 == NULL) || (pData2 == NULL))) && (Length > 0U)) { return HAL_ERROR; } else { diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c index 9d6123bf29..87f66c3fdc 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c @@ -311,8 +311,8 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim) { assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -382,8 +382,8 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim) { assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } diff --git a/source/Core/BSP/Miniware/port.c b/source/Core/BSP/Miniware/port.c index a79eab6fa1..fb0e033041 100644 --- a/source/Core/BSP/Miniware/port.c +++ b/source/Core/BSP/Miniware/port.c @@ -208,7 +208,8 @@ static void prvTaskExitError(void) { // therefore not output an 'unreachable code' warning for code that appears // after it. */ // } - for (;;) {} + for (;;) { + } } /*-----------------------------------------------------------*/ diff --git a/source/Core/BSP/Miniware/system_stm32f1xx.c b/source/Core/BSP/Miniware/system_stm32f1xx.c index 06c843e06b..4c5df9cc02 100644 --- a/source/Core/BSP/Miniware/system_stm32f1xx.c +++ b/source/Core/BSP/Miniware/system_stm32f1xx.c @@ -3,8 +3,8 @@ #include "stm32f1xx.h" #if !defined(HSI_VALUE) -#define HSI_VALUE \ - 8000000U /*!< Default value of the Internal oscillator in Hz. \ +#define HSI_VALUE \ + 8000000U /*!< Default value of the Internal oscillator in Hz. \ This value can be provided and adapted by the user application. */ #endif /* HSI_VALUE */ diff --git a/source/Core/BSP/Pinecil/I2C_Wrapper.cpp b/source/Core/BSP/Pinecil/I2C_Wrapper.cpp index 2b2e55a37a..853f5fabec 100644 --- a/source/Core/BSP/Pinecil/I2C_Wrapper.cpp +++ b/source/Core/BSP/Pinecil/I2C_Wrapper.cpp @@ -145,11 +145,13 @@ void perform_i2c_step() { if (currentState.numberOfBytes == 1) { /* disable acknowledge */ i2c_master_addressing(I2C0, currentState.deviceAddress, I2C_RECEIVER); - while (!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND)) { + } i2c_ack_config(I2C0, I2C_ACK_DISABLE); i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND); /* wait for the byte to be received */ - while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) { + } /* read the byte received from the EEPROM */ *currentState.buffer = i2c_data_receive(I2C0); while (i2c_flag_get(I2C0, I2C_FLAG_RBNE)) { @@ -163,10 +165,12 @@ void perform_i2c_step() { } else if (currentState.numberOfBytes == 2) { /* disable acknowledge */ i2c_master_addressing(I2C0, currentState.deviceAddress, I2C_RECEIVER); - while (!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND)) { + } i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND); /* wait for the byte to be received */ - while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) { + } i2c_ackpos_config(I2C0, I2C_ACKPOS_CURRENT); i2c_ack_config(I2C0, I2C_ACK_DISABLE); @@ -175,7 +179,8 @@ void perform_i2c_step() { currentState.buffer++; /* wait for the byte to be received */ - while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) { + } /* read the byte received from the EEPROM */ *currentState.buffer = i2c_data_receive(I2C0); while (i2c_flag_get(I2C0, I2C_FLAG_RBNE)) { @@ -204,20 +209,23 @@ void perform_i2c_step() { if (3 == currentState.numberOfBytes) { /* wait until BTC bit is set */ - while (!i2c_flag_get(I2C0, I2C_FLAG_BTC)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_BTC)) { + } i2c_ackpos_config(I2C0, I2C_ACKPOS_CURRENT); /* disable acknowledge */ i2c_ack_config(I2C0, I2C_ACK_DISABLE); } else if (2 == currentState.numberOfBytes) { /* wait until BTC bit is set */ - while (!i2c_flag_get(I2C0, I2C_FLAG_BTC)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_BTC)) { + } /* disable acknowledge */ i2c_ack_config(I2C0, I2C_ACK_DISABLE); /* send a stop condition to I2C bus */ i2c_stop_on_bus(I2C0); } /* wait until RBNE bit is set */ - while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) { + } /* read a byte from the EEPROM */ *currentState.buffer = i2c_data_receive(I2C0); diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usb_dev.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usb_dev.c index 2700e660cd..0b61201f8d 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usb_dev.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usb_dev.c @@ -46,8 +46,8 @@ static uint16_t USBFS_TX_FIFO_SIZE[USBFS_MAX_EP_COUNT] = {(uint16_t)TX0_FIFO_FS_ #elif defined(USB_HS_CORE) -uint16_t USBHS_TX_FIFO_SIZE[USBHS_MAX_EP_COUNT] - = {(uint16_t)TX0_FIFO_HS_SIZE, (uint16_t)TX1_FIFO_HS_SIZE, (uint16_t)TX2_FIFO_HS_SIZE, (uint16_t)TX3_FIFO_HS_SIZE, (uint16_t)TX4_FIFO_HS_SIZE, (uint16_t)TX5_FIFO_HS_SIZE}; +uint16_t USBHS_TX_FIFO_SIZE[USBHS_MAX_EP_COUNT] = {(uint16_t)TX0_FIFO_HS_SIZE, (uint16_t)TX1_FIFO_HS_SIZE, (uint16_t)TX2_FIFO_HS_SIZE, + (uint16_t)TX3_FIFO_HS_SIZE, (uint16_t)TX4_FIFO_HS_SIZE, (uint16_t)TX5_FIFO_HS_SIZE}; #endif /* USBFS_CORE */ diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usbd_int.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usbd_int.c index f8733ef13a..900a1e25d4 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usbd_int.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usbd_int.c @@ -45,8 +45,8 @@ static uint32_t usbd_int_suspend(usb_core_driver *udev); static uint32_t usbd_emptytxfifo_write(usb_core_driver *udev, uint32_t ep_num); -static const uint8_t USB_SPEED[4] - = {[DSTAT_EM_HS_PHY_30MHZ_60MHZ] = USB_SPEED_HIGH, [DSTAT_EM_FS_PHY_30MHZ_60MHZ] = USB_SPEED_FULL, [DSTAT_EM_FS_PHY_48MHZ] = USB_SPEED_FULL, [DSTAT_EM_LS_PHY_6MHZ] = USB_SPEED_LOW}; +static const uint8_t USB_SPEED[4] = { + [DSTAT_EM_HS_PHY_30MHZ_60MHZ] = USB_SPEED_HIGH, [DSTAT_EM_FS_PHY_30MHZ_60MHZ] = USB_SPEED_FULL, [DSTAT_EM_FS_PHY_48MHZ] = USB_SPEED_FULL, [DSTAT_EM_LS_PHY_6MHZ] = USB_SPEED_LOW}; __IO uint8_t setupc_flag = 0U; @@ -230,7 +230,8 @@ void usbd_isr(usb_core_driver *udev) { /* OTG mode interrupt */ if (intr & GINTF_OTGIF) { - if (udev->regs.gr->GOTGINTF & GOTGINTF_SESEND) {} + if (udev->regs.gr->GOTGINTF & GOTGINTF_SESEND) { + } /* Clear OTG interrupt */ udev->regs.gr->GINTF = GINTF_OTGIF; diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbd_enum.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbd_enum.c index 8b976709c2..a1d359bb43 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbd_enum.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbd_enum.c @@ -70,8 +70,8 @@ static usb_reqsta (*_std_dev_req[])(usb_core_driver *udev, usb_req *req) = { }; /* get standard descriptor handler */ -static uint8_t *(*std_desc_get[])(usb_core_driver *udev, uint8_t index, uint16_t *len) - = {[USB_DESCTYPE_DEV - 1] = _usb_dev_desc_get, [USB_DESCTYPE_CONFIG - 1] = _usb_config_desc_get, [USB_DESCTYPE_STR - 1] = _usb_str_desc_get}; +static uint8_t *(*std_desc_get[])(usb_core_driver *udev, uint8_t index, + uint16_t *len) = {[USB_DESCTYPE_DEV - 1] = _usb_dev_desc_get, [USB_DESCTYPE_CONFIG - 1] = _usb_config_desc_get, [USB_DESCTYPE_STR - 1] = _usb_str_desc_get}; /*! \brief handle USB standard device request diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbh_enum.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbh_enum.c index 2ab5b8fae9..edb73d0fe0 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbh_enum.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbh_enum.c @@ -72,8 +72,8 @@ usbh_status usbh_devdesc_get(usb_core_driver *pudev, usbh_host *puhost, uint8_t usbh_control *usb_ctl = &puhost->control; if (CTL_IDLE == usb_ctl->ctl_state) { - usb_ctl->setup.req - = (usb_req){.bmRequestType = USB_TRX_IN | USB_RECPTYPE_DEV | USB_REQTYPE_STRD, .bRequest = USB_GET_DESCRIPTOR, .wValue = USBH_DESC(USB_DESCTYPE_DEV), .wIndex = 0U, .wLength = len}; + usb_ctl->setup.req = + (usb_req){.bmRequestType = USB_TRX_IN | USB_RECPTYPE_DEV | USB_REQTYPE_STRD, .bRequest = USB_GET_DESCRIPTOR, .wValue = USBH_DESC(USB_DESCTYPE_DEV), .wIndex = 0U, .wLength = len}; usbh_ctlstate_config(puhost, pudev->host.rx_buf, len); } @@ -102,8 +102,8 @@ usbh_status usbh_cfgdesc_get(usb_core_driver *pudev, usbh_host *puhost, uint16_t usbh_control *usb_ctl = &puhost->control; if (CTL_IDLE == usb_ctl->ctl_state) { - usb_ctl->setup.req - = (usb_req){.bmRequestType = USB_TRX_IN | USB_RECPTYPE_DEV | USB_REQTYPE_STRD, .bRequest = USB_GET_DESCRIPTOR, .wValue = USBH_DESC(USB_DESCTYPE_CONFIG), .wIndex = 0U, .wLength = len}; + usb_ctl->setup.req = + (usb_req){.bmRequestType = USB_TRX_IN | USB_RECPTYPE_DEV | USB_REQTYPE_STRD, .bRequest = USB_GET_DESCRIPTOR, .wValue = USBH_DESC(USB_DESCTYPE_CONFIG), .wIndex = 0U, .wLength = len}; usbh_ctlstate_config(puhost, pudev->host.rx_buf, len); } @@ -266,13 +266,15 @@ usbh_status usbh_clrfeature(usb_core_driver *pudev, usbh_host *puhost, uint8_t e \retval operation status */ static void usbh_devdesc_parse(usb_desc_dev *dev_desc, uint8_t *buf, uint16_t len) { - *dev_desc = (usb_desc_dev){.header = {.bLength = *(uint8_t *)(buf + 0U), .bDescriptorType = *(uint8_t *)(buf + 1U)}, + *dev_desc = (usb_desc_dev){ + .header = {.bLength = *(uint8_t *)(buf + 0U), .bDescriptorType = *(uint8_t *)(buf + 1U)}, - .bcdUSB = BYTE_SWAP(buf + 2U), - .bDeviceClass = *(uint8_t *)(buf + 4U), - .bDeviceSubClass = *(uint8_t *)(buf + 5U), - .bDeviceProtocol = *(uint8_t *)(buf + 6U), - .bMaxPacketSize0 = *(uint8_t *)(buf + 7U)}; + .bcdUSB = BYTE_SWAP(buf + 2U), + .bDeviceClass = *(uint8_t *)(buf + 4U), + .bDeviceSubClass = *(uint8_t *)(buf + 5U), + .bDeviceProtocol = *(uint8_t *)(buf + 6U), + .bMaxPacketSize0 = *(uint8_t *)(buf + 7U) + }; if (len > 8U) { /* for 1st time after device connection, host may issue only 8 bytes for device descriptor length */ @@ -295,19 +297,20 @@ static void usbh_devdesc_parse(usb_desc_dev *dev_desc, uint8_t *buf, uint16_t le */ static void usbh_cfgdesc_parse(usb_desc_config *cfg_desc, uint8_t *buf) { /* parse configuration descriptor */ - *cfg_desc = (usb_desc_config) { - .header = { - .bLength = *(uint8_t *)(buf + 0U), - .bDescriptorType = *(uint8_t *)(buf + 1U), - }, - - .wTotalLength = BYTE_SWAP(buf + 2U), - .bNumInterfaces = *(uint8_t *)(buf + 4U), - .bConfigurationValue = *(uint8_t *)(buf + 5U), - .iConfiguration = *(uint8_t *)(buf + 6U), - .bmAttributes = *(uint8_t *)(buf + 7U), - .bMaxPower = *(uint8_t *)(buf + 8U) - }; + *cfg_desc = (usb_desc_config){ + .header = + { + .bLength = *(uint8_t *)(buf + 0U), + .bDescriptorType = *(uint8_t *)(buf + 1U), + }, + + .wTotalLength = BYTE_SWAP(buf + 2U), + .bNumInterfaces = *(uint8_t *)(buf + 4U), + .bConfigurationValue = *(uint8_t *)(buf + 5U), + .iConfiguration = *(uint8_t *)(buf + 6U), + .bmAttributes = *(uint8_t *)(buf + 7U), + .bMaxPower = *(uint8_t *)(buf + 8U) + }; } /*! @@ -388,20 +391,21 @@ static void usbh_cfgset_parse(usb_dev_prop *udev, uint8_t *buf) { \retval operation status */ static void usbh_itfdesc_parse(usb_desc_itf *itf_desc, uint8_t *buf) { - *itf_desc = (usb_desc_itf) { - .header = { - .bLength = *(uint8_t *)(buf + 0U), - .bDescriptorType = *(uint8_t *)(buf + 1U), - }, - - .bInterfaceNumber = *(uint8_t *)(buf + 2U), - .bAlternateSetting = *(uint8_t *)(buf + 3U), - .bNumEndpoints = *(uint8_t *)(buf + 4U), - .bInterfaceClass = *(uint8_t *)(buf + 5U), - .bInterfaceSubClass = *(uint8_t *)(buf + 6U), - .bInterfaceProtocol = *(uint8_t *)(buf + 7U), - .iInterface = *(uint8_t *)(buf + 8U) - }; + *itf_desc = (usb_desc_itf){ + .header = + { + .bLength = *(uint8_t *)(buf + 0U), + .bDescriptorType = *(uint8_t *)(buf + 1U), + }, + + .bInterfaceNumber = *(uint8_t *)(buf + 2U), + .bAlternateSetting = *(uint8_t *)(buf + 3U), + .bNumEndpoints = *(uint8_t *)(buf + 4U), + .bInterfaceClass = *(uint8_t *)(buf + 5U), + .bInterfaceSubClass = *(uint8_t *)(buf + 6U), + .bInterfaceProtocol = *(uint8_t *)(buf + 7U), + .iInterface = *(uint8_t *)(buf + 8U) + }; } /*! @@ -412,12 +416,14 @@ static void usbh_itfdesc_parse(usb_desc_itf *itf_desc, uint8_t *buf) { \retval operation status */ static void usbh_epdesc_parse(usb_desc_ep *ep_desc, uint8_t *buf) { - *ep_desc = (usb_desc_ep){.header = {.bLength = *(uint8_t *)(buf + 0U), .bDescriptorType = *(uint8_t *)(buf + 1U)}, - - .bEndpointAddress = *(uint8_t *)(buf + 2U), - .bmAttributes = *(uint8_t *)(buf + 3U), - .wMaxPacketSize = BYTE_SWAP(buf + 4U), - .bInterval = *(uint8_t *)(buf + 6U)}; + *ep_desc = (usb_desc_ep){ + .header = {.bLength = *(uint8_t *)(buf + 0U), .bDescriptorType = *(uint8_t *)(buf + 1U)}, + + .bEndpointAddress = *(uint8_t *)(buf + 2U), + .bmAttributes = *(uint8_t *)(buf + 3U), + .wMaxPacketSize = BYTE_SWAP(buf + 4U), + .bInterval = *(uint8_t *)(buf + 6U) + }; } /*! diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_adc.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_adc.c index 9c04ec58a0..57f0f20644 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_adc.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_adc.c @@ -199,11 +199,13 @@ void adc_calibration_enable(uint32_t adc_periph) { /* reset the selected ADC1 calibration registers */ ADC_CTL1(adc_periph) |= (uint32_t)ADC_CTL1_RSTCLB; /* check the RSTCLB bit state */ - while ((uint32_t)RESET != (ADC_CTL1(adc_periph) & ADC_CTL1_RSTCLB)) {} + while ((uint32_t)RESET != (ADC_CTL1(adc_periph) & ADC_CTL1_RSTCLB)) { + } /* enable ADC calibration process */ ADC_CTL1(adc_periph) |= ADC_CTL1_CLB; /* check the CLB bit state */ - while ((uint32_t)RESET != (ADC_CTL1(adc_periph) & ADC_CTL1_CLB)) {} + while ((uint32_t)RESET != (ADC_CTL1(adc_periph) & ADC_CTL1_CLB)) { + } } /*! diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_dma.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_dma.c index e129f7cce2..b2eebe3ec3 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_dma.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_dma.c @@ -37,8 +37,9 @@ OF SUCH DAMAGE. #include "gd32vf103_dma.h" #include "gd32vf103_rcu.h" -#define DMA_WRONG_HANDLE \ - while (1) {} +#define DMA_WRONG_HANDLE \ + while (1) { \ + } /* check whether peripheral matches channels or not */ static ErrStatus dma_periph_and_channel_check(uint32_t dma_periph, dma_channel_enum channelx); diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_exmc.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_exmc.c index d148588160..436a34972a 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_exmc.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_exmc.c @@ -114,14 +114,14 @@ void exmc_norsram_init(exmc_norsram_parameter_struct *exmc_norsram_init_struct) /* clear relative bits */ snctl &= ((uint32_t) ~(EXMC_SNCTL_NREN | EXMC_SNCTL_NRTP | EXMC_SNCTL_NRW | EXMC_SNCTL_NRWTPOL | EXMC_SNCTL_WREN | EXMC_SNCTL_NRWTEN | EXMC_SNCTL_ASYNCWAIT | EXMC_SNCTL_NRMUX)); - snctl |= (uint32_t)((uint32_t)exmc_norsram_init_struct->address_data_mux << SNCTL_NRMUX_OFFSET) | exmc_norsram_init_struct->memory_type | exmc_norsram_init_struct->databus_width - | exmc_norsram_init_struct->nwait_polarity | ((uint32_t)exmc_norsram_init_struct->memory_write << SNCTL_WREN_OFFSET) - | ((uint32_t)exmc_norsram_init_struct->nwait_signal << SNCTL_NRWTEN_OFFSET) | ((uint32_t)exmc_norsram_init_struct->asyn_wait << SNCTL_ASYNCWAIT_OFFSET); - - sntcfg = (uint32_t)((exmc_norsram_init_struct->read_write_timing->asyn_address_setuptime - 1U) & EXMC_SNTCFG_ASET) - | (((exmc_norsram_init_struct->read_write_timing->asyn_address_holdtime - 1U) << SNTCFG_AHLD_OFFSET) & EXMC_SNTCFG_AHLD) - | (((exmc_norsram_init_struct->read_write_timing->asyn_data_setuptime - 1U) << SNTCFG_DSET_OFFSET) & EXMC_SNTCFG_DSET) - | (((exmc_norsram_init_struct->read_write_timing->bus_latency - 1U) << SNTCFG_BUSLAT_OFFSET) & EXMC_SNTCFG_BUSLAT); + snctl |= (uint32_t)((uint32_t)exmc_norsram_init_struct->address_data_mux << SNCTL_NRMUX_OFFSET) | exmc_norsram_init_struct->memory_type | exmc_norsram_init_struct->databus_width | + exmc_norsram_init_struct->nwait_polarity | ((uint32_t)exmc_norsram_init_struct->memory_write << SNCTL_WREN_OFFSET) | + ((uint32_t)exmc_norsram_init_struct->nwait_signal << SNCTL_NRWTEN_OFFSET) | ((uint32_t)exmc_norsram_init_struct->asyn_wait << SNCTL_ASYNCWAIT_OFFSET); + + sntcfg = (uint32_t)((exmc_norsram_init_struct->read_write_timing->asyn_address_setuptime - 1U) & EXMC_SNTCFG_ASET) | + (((exmc_norsram_init_struct->read_write_timing->asyn_address_holdtime - 1U) << SNTCFG_AHLD_OFFSET) & EXMC_SNTCFG_AHLD) | + (((exmc_norsram_init_struct->read_write_timing->asyn_data_setuptime - 1U) << SNTCFG_DSET_OFFSET) & EXMC_SNTCFG_DSET) | + (((exmc_norsram_init_struct->read_write_timing->bus_latency - 1U) << SNTCFG_BUSLAT_OFFSET) & EXMC_SNTCFG_BUSLAT); /* nor flash access enable */ if (EXMC_MEMORY_TYPE_NOR == exmc_norsram_init_struct->memory_type) { diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_fmc.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_fmc.c index 4811ec8775..3b38e5bde6 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_fmc.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_fmc.c @@ -188,7 +188,8 @@ void ob_unlock(void) { } /* wait until OBWEN bit is set by hardware */ - while (RESET == (FMC_CTL & FMC_CTL_OBWEN)) {} + while (RESET == (FMC_CTL & FMC_CTL_OBWEN)) { + } } /*! diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rcu.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rcu.c index af0b669d87..231431ac94 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rcu.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rcu.c @@ -54,8 +54,8 @@ void rcu_deinit(void) { RCU_CTL &= ~RCU_CTL_HXTALBPS; RCU_CTL &= ~(RCU_CTL_PLL1EN | RCU_CTL_PLL2EN); /* reset CFG0 register */ - RCU_CFG0 &= ~(RCU_CFG0_SCS | RCU_CFG0_AHBPSC | RCU_CFG0_APB1PSC | RCU_CFG0_APB2PSC | RCU_CFG0_ADCPSC | RCU_CFG0_PLLSEL | RCU_CFG0_PREDV0_LSB | RCU_CFG0_PLLMF | RCU_CFG0_USBFSPSC | RCU_CFG0_CKOUT0SEL - | RCU_CFG0_ADCPSC_2 | RCU_CFG0_PLLMF_4); + RCU_CFG0 &= ~(RCU_CFG0_SCS | RCU_CFG0_AHBPSC | RCU_CFG0_APB1PSC | RCU_CFG0_APB2PSC | RCU_CFG0_ADCPSC | RCU_CFG0_PLLSEL | RCU_CFG0_PREDV0_LSB | RCU_CFG0_PLLMF | RCU_CFG0_USBFSPSC | + RCU_CFG0_CKOUT0SEL | RCU_CFG0_ADCPSC_2 | RCU_CFG0_PLLMF_4); /* reset INT and CFG1 register */ RCU_INT = 0x00ff0000U; RCU_CFG1 &= ~(RCU_CFG1_PREDV0 | RCU_CFG1_PREDV1 | RCU_CFG1_PLL1MF | RCU_CFG1_PLL2MF | RCU_CFG1_PREDV0SEL | RCU_CFG1_I2S1SEL | RCU_CFG1_I2S2SEL); diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rtc.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rtc.c index 8a7bb21fdd..50d2909ab6 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rtc.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rtc.c @@ -97,7 +97,8 @@ void rtc_prescaler_set(uint32_t psc) { */ void rtc_lwoff_wait(void) { /* loop until LWOFF flag is set */ - while (RESET == (RTC_CTL & RTC_CTL_LWOFF)) {} + while (RESET == (RTC_CTL & RTC_CTL_LWOFF)) { + } } /*! @@ -110,7 +111,8 @@ void rtc_register_sync_wait(void) { /* clear RSYNF flag */ RTC_CTL &= ~RTC_CTL_RSYNF; /* loop until RSYNF flag is set */ - while (RESET == (RTC_CTL & RTC_CTL_RSYNF)) {} + while (RESET == (RTC_CTL & RTC_CTL_RSYNF)) { + } } /*! diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_timer.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_timer.c index 08192e3513..652fff3f73 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_timer.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_timer.c @@ -482,8 +482,8 @@ void timer_break_struct_para_init(timer_break_parameter_struct *breakpara) { \retval none */ void timer_break_config(uint32_t timer_periph, timer_break_parameter_struct *breakpara) { - TIMER_CCHP(timer_periph) = (uint32_t)(((uint32_t)(breakpara->runoffstate)) | ((uint32_t)(breakpara->ideloffstate)) | ((uint32_t)(breakpara->deadtime)) | ((uint32_t)(breakpara->breakpolarity)) - | ((uint32_t)(breakpara->outputautostate)) | ((uint32_t)(breakpara->protectmode)) | ((uint32_t)(breakpara->breakstate))); + TIMER_CCHP(timer_periph) = (uint32_t)(((uint32_t)(breakpara->runoffstate)) | ((uint32_t)(breakpara->ideloffstate)) | ((uint32_t)(breakpara->deadtime)) | ((uint32_t)(breakpara->breakpolarity)) | + ((uint32_t)(breakpara->outputautostate)) | ((uint32_t)(breakpara->protectmode)) | ((uint32_t)(breakpara->breakstate))); } /*! diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/system_gd32vf103.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/system_gd32vf103.c index bd83a3c239..60b09c16a5 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/system_gd32vf103.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/system_gd32vf103.c @@ -110,7 +110,8 @@ static void system_clock_108m_hxtal(void) { /* if fail */ if (0U == (RCU_CTL & RCU_CTL_HXTALSTB)) { - while (1) {} + while (1) { + } } /* HXTAL is stable */ @@ -133,12 +134,14 @@ static void system_clock_108m_hxtal(void) { /* enable PLL1 */ RCU_CTL |= RCU_CTL_PLL1EN; /* wait till PLL1 is ready */ - while (0U == (RCU_CTL & RCU_CTL_PLL1STB)) {} + while (0U == (RCU_CTL & RCU_CTL_PLL1STB)) { + } /* enable PLL1 */ RCU_CTL |= RCU_CTL_PLL2EN; /* wait till PLL1 is ready */ - while (0U == (RCU_CTL & RCU_CTL_PLL2STB)) {} + while (0U == (RCU_CTL & RCU_CTL_PLL2STB)) { + } } else if (HXTAL_VALUE == 8000000) { RCU_CFG1 &= ~(RCU_CFG1_PREDV0SEL | RCU_CFG1_PREDV1 | RCU_CFG1_PLL1MF | RCU_CFG1_PREDV0); RCU_CFG1 |= (RCU_PREDV0SRC_HXTAL | RCU_PREDV0_DIV2 | RCU_PREDV1_DIV2 | RCU_PLL1_MUL20 | RCU_PLL2_MUL20); @@ -146,25 +149,29 @@ static void system_clock_108m_hxtal(void) { /* enable PLL1 */ RCU_CTL |= RCU_CTL_PLL1EN; /* wait till PLL1 is ready */ - while (0U == (RCU_CTL & RCU_CTL_PLL1STB)) {} + while (0U == (RCU_CTL & RCU_CTL_PLL1STB)) { + } /* enable PLL2 */ RCU_CTL |= RCU_CTL_PLL2EN; /* wait till PLL1 is ready */ - while (0U == (RCU_CTL & RCU_CTL_PLL2STB)) {} + while (0U == (RCU_CTL & RCU_CTL_PLL2STB)) { + } } /* enable PLL */ RCU_CTL |= RCU_CTL_PLLEN; /* wait until PLL is stable */ - while (0U == (RCU_CTL & RCU_CTL_PLLSTB)) {} + while (0U == (RCU_CTL & RCU_CTL_PLLSTB)) { + } /* select PLL as system clock */ RCU_CFG0 &= ~RCU_CFG0_SCS; RCU_CFG0 |= RCU_CKSYSSRC_PLL; /* wait until PLL is selected as system clock */ - while (0U == (RCU_CFG0 & RCU_SCSS_PLL)) {} + while (0U == (RCU_CFG0 & RCU_SCSS_PLL)) { + } } /*! @@ -343,7 +350,8 @@ static void system_default_exception_handler(unsigned long mcause, unsigned long printf("MCAUSE: 0x%lx\r\n", mcause); printf("MEPC : 0x%lx\r\n", __RV_CSR_READ(CSR_MEPC)); printf("MTVAL : 0x%lx\r\n", __RV_CSR_READ(CSR_MBADADDR)); - while (1) {} + while (1) { + } } /** diff --git a/source/Core/BSP/Pinecilv2/Setup.cpp b/source/Core/BSP/Pinecilv2/Setup.cpp index 120ba2371c..7e8ea5423c 100644 --- a/source/Core/BSP/Pinecilv2/Setup.cpp +++ b/source/Core/BSP/Pinecilv2/Setup.cpp @@ -23,8 +23,8 @@ extern uint8_t _heap_start; extern uint8_t _heap_size; // @suppress("Type cannot be resolved") static HeapRegion_t xHeapRegions[] = { {&_heap_start, (unsigned int)&_heap_size}, - {NULL, 0}, /* Terminates the array. */ - {NULL, 0} /* Terminates the array. */ + { NULL, 0}, /* Terminates the array. */ + { NULL, 0} /* Terminates the array. */ }; // Functions @@ -86,8 +86,8 @@ void setup_pwm(void) { PWM_Channel_Disable(PWM_Channel); } -const ADC_Chan_Type adc_tip_pos_chans[] - = {TIP_TEMP_ADC_CHANNEL, TMP36_ADC_CHANNEL, TIP_TEMP_ADC_CHANNEL, VIN_ADC_CHANNEL, TIP_TEMP_ADC_CHANNEL, TMP36_ADC_CHANNEL, TIP_TEMP_ADC_CHANNEL, VIN_ADC_CHANNEL}; +const ADC_Chan_Type adc_tip_pos_chans[] = {TIP_TEMP_ADC_CHANNEL, TMP36_ADC_CHANNEL, TIP_TEMP_ADC_CHANNEL, VIN_ADC_CHANNEL, + TIP_TEMP_ADC_CHANNEL, TMP36_ADC_CHANNEL, TIP_TEMP_ADC_CHANNEL, VIN_ADC_CHANNEL}; const ADC_Chan_Type adc_tip_neg_chans[] = {ADC_CHAN_GND, ADC_CHAN_GND, ADC_CHAN_GND, ADC_CHAN_GND, ADC_CHAN_GND, ADC_CHAN_GND, ADC_CHAN_GND, ADC_CHAN_GND}; static_assert(sizeof(adc_tip_pos_chans) == sizeof(adc_tip_neg_chans)); diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/bflb_platform.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/bflb_platform.c index 47aad724f6..5f8cdface3 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/bflb_platform.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/bflb_platform.c @@ -36,7 +36,8 @@ static uint8_t uart_dbg_disable = 0; struct heap_info mmheap_root; static struct heap_region system_mmheap[] = { - {NULL, 0}, {NULL, 0}, /* Terminates the array. */ + {NULL, 0}, + {NULL, 0}, /* Terminates the array. */ }; __WEAK__ void board_init(void) {} diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/syscalls.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/syscalls.c index a87c44d558..6299cad805 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/syscalls.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/syscalls.c @@ -203,7 +203,8 @@ void *_sbrk_r(struct _reent *ptr, ptrdiff_t incr) { return NULL; } /* for exit() and abort() */ void __attribute__((noreturn)) _exit(int status) { - while (1) {} + while (1) { + } } void _system(const char *s) {} diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c index b05cda4100..92699a5049 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c @@ -231,7 +231,8 @@ int arch_clzll(uint64_t *val, uint32_t *bit) { *******************************************************************************/ void check_failed(uint8_t *file, uint32_t line) { /* Infinite loop */ - while (1) {} + while (1) { + } } #endif /* DEBUG */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/soft_crc/softcrc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/soft_crc/softcrc.c index 10c5635d56..cf45bff633 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/soft_crc/softcrc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/soft_crc/softcrc.c @@ -27,25 +27,25 @@ // CRC-16: x^16 + x^15 + x^2 + x^0 (0x8005,init 0xFFFF) // we use 0x8005 here and -const uint8_t chCRCHTalbe[] - = {0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40}; +const uint8_t chCRCHTalbe[] = { + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40}; -const uint8_t chCRCLTalbe[] - = {0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, - 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, 0x11, 0xD1, 0xD0, 0x10, - 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, - 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, - 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, - 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, - 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, - 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, 0x40}; +const uint8_t chCRCLTalbe[] = { + 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, + 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, 0x11, 0xD1, 0xD0, 0x10, + 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, + 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, + 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, + 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, + 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, + 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, 0x40}; uint16_t BFLB_Soft_CRC16(void *dataIn, uint32_t len) { uint8_t chCRCHi = 0xFF; @@ -65,23 +65,23 @@ uint16_t BFLB_Soft_CRC16(void *dataIn, uint32_t len) { /* x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1 */ -const uint32_t crc32Tab[256] - = {0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, - 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, - 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, - 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, - 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, - 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, - 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, - 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, - 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, - 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, - 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d}; +const uint32_t crc32Tab[256] = { + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, + 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, + 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, + 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, + 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, + 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, + 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, + 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, + 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, + 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, + 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, + 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, + 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, + 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d}; uint32_t BFLB_Soft_CRC32_Table(void *dataIn, uint32_t len) { uint32_t crc = 0; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/timestamp/timestamp.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/timestamp/timestamp.c index bf281746a9..e74475d419 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/timestamp/timestamp.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/timestamp/timestamp.c @@ -122,8 +122,8 @@ void unixtime2bejingtime(uint32_t unixtime, rtc_time *beijing_time) { /*利用基姆拉尔森计算日期公式 w=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)*/ - beijing_time->week - = beijing_time->day + 2 * beijing_time->month + 3 * (beijing_time->month + 1) / 5 + beijing_time->year + beijing_time->year / 4 - beijing_time->year / 100 + beijing_time->year / 400; + beijing_time->week = + beijing_time->day + 2 * beijing_time->month + 3 * (beijing_time->month + 1) / 5 + beijing_time->year + beijing_time->year / 4 - beijing_time->year / 100 + beijing_time->year / 400; cal_weekday(beijing_time); } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c index 099130d51d..bb3a5b54a3 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c @@ -33,11 +33,11 @@ #define NET_BUF_ERR(fmt, ...) LOG_ERR(fmt, ##__VA_ARGS__) #define NET_BUF_WARN(fmt, ...) LOG_WRN(fmt, ##__VA_ARGS__) #define NET_BUF_INFO(fmt, ...) LOG_INF(fmt, ##__VA_ARGS__) -#define NET_BUF_ASSERT(cond) \ - do { \ - if (!(cond)) { \ - NET_BUF_ERR("assert: '" #cond "' failed"); \ - } \ +#define NET_BUF_ASSERT(cond) \ + do { \ + if (!(cond)) { \ + NET_BUF_ERR("assert: '" #cond "' failed"); \ + } \ } while (0) #else diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_decrypt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_decrypt.c index fa89d3b0bd..a0ea2b814e 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_decrypt.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_decrypt.c @@ -34,15 +34,15 @@ #include #include -static const uint8_t inv_sbox[256] - = {0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, - 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, - 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, - 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, - 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, - 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, - 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, - 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d}; +static const uint8_t inv_sbox[256] = { + 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, + 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, + 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, + 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, + 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, + 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, + 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, + 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d}; int tc_aes128_set_decrypt_key(TCAesKeySched_t s, const uint8_t *k) { return tc_aes128_set_encrypt_key(s, k); } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_encrypt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_encrypt.c index c46a0cbb14..9d20d1c2a0 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_encrypt.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_encrypt.c @@ -34,15 +34,15 @@ #include "constants.h" #include "utils.h" -static const uint8_t sbox[256] - = {0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, - 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, - 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, - 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, - 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, - 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, - 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, - 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16}; +static const uint8_t sbox[256] = { + 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, + 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, + 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, + 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, + 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, + 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, + 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, + 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16}; static inline unsigned int rotword(unsigned int a) { return (((a) >> 24) | ((a) << 8)); } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cbc_mode.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cbc_mode.c index 7b8e1fd327..8c30104f8d 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cbc_mode.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cbc_mode.c @@ -39,8 +39,8 @@ int tc_cbc_mode_encrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, un unsigned int n, m; /* input sanity check: */ - if (out == (uint8_t *)0 || in == (const uint8_t *)0 || sched == (TCAesKeySched_t)0 || inlen == 0 || outlen == 0 || (inlen % TC_AES_BLOCK_SIZE) != 0 || (outlen % TC_AES_BLOCK_SIZE) != 0 - || outlen != inlen + TC_AES_BLOCK_SIZE) { + if (out == (uint8_t *)0 || in == (const uint8_t *)0 || sched == (TCAesKeySched_t)0 || inlen == 0 || outlen == 0 || (inlen % TC_AES_BLOCK_SIZE) != 0 || (outlen % TC_AES_BLOCK_SIZE) != 0 || + outlen != inlen + TC_AES_BLOCK_SIZE) { return TC_CRYPTO_FAIL; } @@ -69,8 +69,8 @@ int tc_cbc_mode_decrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, un unsigned int n, m; /* sanity check the inputs */ - if (out == (uint8_t *)0 || in == (const uint8_t *)0 || sched == (TCAesKeySched_t)0 || inlen == 0 || outlen == 0 || (inlen % TC_AES_BLOCK_SIZE) != 0 || (outlen % TC_AES_BLOCK_SIZE) != 0 - || outlen != inlen) { + if (out == (uint8_t *)0 || in == (const uint8_t *)0 || sched == (TCAesKeySched_t)0 || inlen == 0 || outlen == 0 || (inlen % TC_AES_BLOCK_SIZE) != 0 || (outlen % TC_AES_BLOCK_SIZE) != 0 || + outlen != inlen) { return TC_CRYPTO_FAIL; } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ccm_mode.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ccm_mode.c index 321473e258..e102957e7e 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ccm_mode.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ccm_mode.c @@ -121,8 +121,8 @@ static int ccm_ctr_mode(uint8_t *out, unsigned int outlen, const uint8_t *in, un int tc_ccm_generation_encryption(uint8_t *out, unsigned int olen, const uint8_t *associated_data, unsigned int alen, const uint8_t *payload, unsigned int plen, TCCcmMode_t c) { /* input sanity check: */ - if ((out == (uint8_t *)0) || (c == (TCCcmMode_t)0) || ((plen > 0) && (payload == (uint8_t *)0)) || ((alen > 0) && (associated_data == (uint8_t *)0)) || (alen >= TC_CCM_AAD_MAX_BYTES) - || /* associated data size unsupported */ + if ((out == (uint8_t *)0) || (c == (TCCcmMode_t)0) || ((plen > 0) && (payload == (uint8_t *)0)) || ((alen > 0) && (associated_data == (uint8_t *)0)) || + (alen >= TC_CCM_AAD_MAX_BYTES) || /* associated data size unsupported */ (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */ (olen < (plen + c->mlen))) { /* invalid output buffer size */ return TC_CRYPTO_FAIL; @@ -174,8 +174,8 @@ int tc_ccm_generation_encryption(uint8_t *out, unsigned int olen, const uint8_t int tc_ccm_decryption_verification(uint8_t *out, unsigned int olen, const uint8_t *associated_data, unsigned int alen, const uint8_t *payload, unsigned int plen, TCCcmMode_t c) { /* input sanity check: */ - if ((out == (uint8_t *)0) || (c == (TCCcmMode_t)0) || ((plen > 0) && (payload == (uint8_t *)0)) || ((alen > 0) && (associated_data == (uint8_t *)0)) || (alen >= TC_CCM_AAD_MAX_BYTES) - || /* associated data size unsupported */ + if ((out == (uint8_t *)0) || (c == (TCCcmMode_t)0) || ((plen > 0) && (payload == (uint8_t *)0)) || ((alen > 0) && (associated_data == (uint8_t *)0)) || + (alen >= TC_CCM_AAD_MAX_BYTES) || /* associated data size unsupported */ (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */ (olen < plen - c->mlen)) { /* invalid output buffer size */ return TC_CRYPTO_FAIL; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c index f6a0cfb44e..e9281a59b7 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c @@ -95,7 +95,8 @@ static wordcount_t vli_numDigits(const uECC_word_t *vli, const wordcount_t max_w wordcount_t i; /* Search from the end until we find a non-zero digit. We do it in reverse * because we expect that most digits will be nonzero. */ - for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) {} + for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) { + } return (i + 1); } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/sha256.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/sha256.c index 1ee9bdf12a..1dab36071d 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/sha256.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/sha256.c @@ -133,11 +133,11 @@ int tc_sha256_final(uint8_t *digest, TCSha256State_t s) { * These values correspond to the first 32 bits of the fractional parts of the * cube roots of the first 64 primes between 2 and 311. */ -static const unsigned int k256[64] - = {0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; +static const unsigned int k256[64] = {0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, + 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, + 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, + 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; static inline unsigned int ROTR(unsigned int a, unsigned int n) { return (((a) >> n) | ((a) << (32 - n))); } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c index 7ca97fe8ae..52f2ad92c7 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c @@ -1690,42 +1690,42 @@ static const struct att_handler { att_type_t type; u8_t (*func)(struct bt_att *att, struct net_buf *buf); } handlers[] = { - {BT_ATT_OP_MTU_REQ, sizeof(struct bt_att_exchange_mtu_req), ATT_REQUEST, att_mtu_req}, - {BT_ATT_OP_FIND_INFO_REQ, sizeof(struct bt_att_find_info_req), ATT_REQUEST, att_find_info_req}, - {BT_ATT_OP_FIND_TYPE_REQ, sizeof(struct bt_att_find_type_req), ATT_REQUEST, att_find_type_req}, - {BT_ATT_OP_READ_TYPE_REQ, sizeof(struct bt_att_read_type_req), ATT_REQUEST, att_read_type_req}, - {BT_ATT_OP_READ_REQ, sizeof(struct bt_att_read_req), ATT_REQUEST, att_read_req}, - {BT_ATT_OP_READ_BLOB_REQ, sizeof(struct bt_att_read_blob_req), ATT_REQUEST, att_read_blob_req}, + { BT_ATT_OP_MTU_REQ, sizeof(struct bt_att_exchange_mtu_req), ATT_REQUEST, att_mtu_req}, + { BT_ATT_OP_FIND_INFO_REQ, sizeof(struct bt_att_find_info_req), ATT_REQUEST, att_find_info_req}, + { BT_ATT_OP_FIND_TYPE_REQ, sizeof(struct bt_att_find_type_req), ATT_REQUEST, att_find_type_req}, + { BT_ATT_OP_READ_TYPE_REQ, sizeof(struct bt_att_read_type_req), ATT_REQUEST, att_read_type_req}, + { BT_ATT_OP_READ_REQ, sizeof(struct bt_att_read_req), ATT_REQUEST, att_read_req}, + { BT_ATT_OP_READ_BLOB_REQ, sizeof(struct bt_att_read_blob_req), ATT_REQUEST, att_read_blob_req}, #if defined(CONFIG_BT_GATT_READ_MULTIPLE) - {BT_ATT_OP_READ_MULT_REQ, BT_ATT_READ_MULT_MIN_LEN_REQ, ATT_REQUEST, att_read_mult_req}, -#endif /* CONFIG_BT_GATT_READ_MULTIPLE */ - {BT_ATT_OP_READ_GROUP_REQ, sizeof(struct bt_att_read_group_req), ATT_REQUEST, att_read_group_req}, - {BT_ATT_OP_WRITE_REQ, sizeof(struct bt_att_write_req), ATT_REQUEST, att_write_req}, - {BT_ATT_OP_PREPARE_WRITE_REQ, sizeof(struct bt_att_prepare_write_req), ATT_REQUEST, att_prepare_write_req}, - {BT_ATT_OP_EXEC_WRITE_REQ, sizeof(struct bt_att_exec_write_req), ATT_REQUEST, att_exec_write_req}, - {BT_ATT_OP_CONFIRM, 0, ATT_CONFIRMATION, att_confirm}, - {BT_ATT_OP_WRITE_CMD, sizeof(struct bt_att_write_cmd), ATT_COMMAND, att_write_cmd}, + { BT_ATT_OP_READ_MULT_REQ, BT_ATT_READ_MULT_MIN_LEN_REQ, ATT_REQUEST, att_read_mult_req}, +#endif /* CONFIG_BT_GATT_READ_MULTIPLE */ + { BT_ATT_OP_READ_GROUP_REQ, sizeof(struct bt_att_read_group_req), ATT_REQUEST, att_read_group_req}, + { BT_ATT_OP_WRITE_REQ, sizeof(struct bt_att_write_req), ATT_REQUEST, att_write_req}, + {BT_ATT_OP_PREPARE_WRITE_REQ, sizeof(struct bt_att_prepare_write_req), ATT_REQUEST, att_prepare_write_req}, + { BT_ATT_OP_EXEC_WRITE_REQ, sizeof(struct bt_att_exec_write_req), ATT_REQUEST, att_exec_write_req}, + { BT_ATT_OP_CONFIRM, 0, ATT_CONFIRMATION, att_confirm}, + { BT_ATT_OP_WRITE_CMD, sizeof(struct bt_att_write_cmd), ATT_COMMAND, att_write_cmd}, #if defined(CONFIG_BT_SIGNING) - {BT_ATT_OP_SIGNED_WRITE_CMD, (sizeof(struct bt_att_write_cmd) + sizeof(struct bt_att_signature)), ATT_COMMAND, att_signed_write_cmd}, -#endif /* CONFIG_BT_SIGNING */ + { BT_ATT_OP_SIGNED_WRITE_CMD, (sizeof(struct bt_att_write_cmd) + sizeof(struct bt_att_signature)), ATT_COMMAND, att_signed_write_cmd}, +#endif /* CONFIG_BT_SIGNING */ #if defined(CONFIG_BT_GATT_CLIENT) - {BT_ATT_OP_ERROR_RSP, sizeof(struct bt_att_error_rsp), ATT_RESPONSE, att_error_rsp}, - {BT_ATT_OP_MTU_RSP, sizeof(struct bt_att_exchange_mtu_rsp), ATT_RESPONSE, att_mtu_rsp}, - {BT_ATT_OP_FIND_INFO_RSP, sizeof(struct bt_att_find_info_rsp), ATT_RESPONSE, att_handle_find_info_rsp}, - {BT_ATT_OP_FIND_TYPE_RSP, sizeof(struct bt_att_find_type_rsp), ATT_RESPONSE, att_handle_find_type_rsp}, - {BT_ATT_OP_READ_TYPE_RSP, sizeof(struct bt_att_read_type_rsp), ATT_RESPONSE, att_handle_read_type_rsp}, - {BT_ATT_OP_READ_RSP, sizeof(struct bt_att_read_rsp), ATT_RESPONSE, att_handle_read_rsp}, - {BT_ATT_OP_READ_BLOB_RSP, sizeof(struct bt_att_read_blob_rsp), ATT_RESPONSE, att_handle_read_blob_rsp}, + { BT_ATT_OP_ERROR_RSP, sizeof(struct bt_att_error_rsp), ATT_RESPONSE, att_error_rsp}, + { BT_ATT_OP_MTU_RSP, sizeof(struct bt_att_exchange_mtu_rsp), ATT_RESPONSE, att_mtu_rsp}, + { BT_ATT_OP_FIND_INFO_RSP, sizeof(struct bt_att_find_info_rsp), ATT_RESPONSE, att_handle_find_info_rsp}, + { BT_ATT_OP_FIND_TYPE_RSP, sizeof(struct bt_att_find_type_rsp), ATT_RESPONSE, att_handle_find_type_rsp}, + { BT_ATT_OP_READ_TYPE_RSP, sizeof(struct bt_att_read_type_rsp), ATT_RESPONSE, att_handle_read_type_rsp}, + { BT_ATT_OP_READ_RSP, sizeof(struct bt_att_read_rsp), ATT_RESPONSE, att_handle_read_rsp}, + { BT_ATT_OP_READ_BLOB_RSP, sizeof(struct bt_att_read_blob_rsp), ATT_RESPONSE, att_handle_read_blob_rsp}, #if defined(CONFIG_BT_GATT_READ_MULTIPLE) - {BT_ATT_OP_READ_MULT_RSP, sizeof(struct bt_att_read_mult_rsp), ATT_RESPONSE, att_handle_read_mult_rsp}, -#endif /* CONFIG_BT_GATT_READ_MULTIPLE */ - {BT_ATT_OP_READ_GROUP_RSP, sizeof(struct bt_att_read_group_rsp), ATT_RESPONSE, att_handle_read_group_rsp}, - {BT_ATT_OP_WRITE_RSP, 0, ATT_RESPONSE, att_handle_write_rsp}, - {BT_ATT_OP_PREPARE_WRITE_RSP, sizeof(struct bt_att_prepare_write_rsp), ATT_RESPONSE, att_handle_prepare_write_rsp}, - {BT_ATT_OP_EXEC_WRITE_RSP, 0, ATT_RESPONSE, att_handle_exec_write_rsp}, - {BT_ATT_OP_NOTIFY, sizeof(struct bt_att_notify), ATT_NOTIFICATION, att_notify}, - {BT_ATT_OP_INDICATE, sizeof(struct bt_att_indicate), ATT_INDICATION, att_indicate}, -#endif /* CONFIG_BT_GATT_CLIENT */ + { BT_ATT_OP_READ_MULT_RSP, sizeof(struct bt_att_read_mult_rsp), ATT_RESPONSE, att_handle_read_mult_rsp}, +#endif /* CONFIG_BT_GATT_READ_MULTIPLE */ + { BT_ATT_OP_READ_GROUP_RSP, sizeof(struct bt_att_read_group_rsp), ATT_RESPONSE, att_handle_read_group_rsp}, + { BT_ATT_OP_WRITE_RSP, 0, ATT_RESPONSE, att_handle_write_rsp}, + {BT_ATT_OP_PREPARE_WRITE_RSP, sizeof(struct bt_att_prepare_write_rsp), ATT_RESPONSE, att_handle_prepare_write_rsp}, + { BT_ATT_OP_EXEC_WRITE_RSP, 0, ATT_RESPONSE, att_handle_exec_write_rsp}, + { BT_ATT_OP_NOTIFY, sizeof(struct bt_att_notify), ATT_NOTIFICATION, att_notify}, + { BT_ATT_OP_INDICATE, sizeof(struct bt_att_indicate), ATT_INDICATION, att_indicate}, +#endif /* CONFIG_BT_GATT_CLIENT */ }; static att_type_t att_op_get_type(u8_t op) { @@ -2051,17 +2051,17 @@ void bt_att_mtu_changed(struct bt_l2cap_chan *chan, u16_t mtu) { bt_gatt_mtu_cha static int bt_att_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { int i; - static struct bt_l2cap_chan_ops ops - = {.connected = bt_att_connected, - .disconnected = bt_att_disconnected, - .recv = bt_att_recv, + static struct bt_l2cap_chan_ops ops = { + .connected = bt_att_connected, + .disconnected = bt_att_disconnected, + .recv = bt_att_recv, #if defined(CONFIG_BT_SMP) - .encrypt_change = bt_att_encrypt_change, + .encrypt_change = bt_att_encrypt_change, #endif /* CONFIG_BT_SMP */ #if defined(BFLB_BLE_MTU_CHANGE_CB) - .mtu_changed = bt_att_mtu_changed, + .mtu_changed = bt_att_mtu_changed, #endif - }; + }; BT_DBG("conn %p handle %u", conn, conn->handle); diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c index 644ff68f69..1e389faeb2 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c @@ -99,10 +99,10 @@ enum pairing_method { /* based on table 5.7, Core Spec 4.2, Vol.3 Part C, 5.2.2.6 */ static const u8_t ssp_method[4 /* remote */][4 /* local */] = { - {JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS}, - {JUST_WORKS, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS}, + { JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS}, + { JUST_WORKS, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS}, {PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS}, - {JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS}, + { JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS}, }; #endif /* CONFIG_BT_BREDR */ @@ -187,8 +187,8 @@ void notify_le_param_updated(struct bt_conn *conn) { /* If new connection parameters meet requirement of pending * parameters don't send slave conn param request anymore on timeout */ - if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET) && conn->le.interval >= conn->le.interval_min && conn->le.interval <= conn->le.interval_max && conn->le.latency == conn->le.pending_latency - && conn->le.timeout == conn->le.pending_timeout) { + if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET) && conn->le.interval >= conn->le.interval_min && conn->le.interval <= conn->le.interval_max && + conn->le.latency == conn->le.pending_latency && conn->le.timeout == conn->le.pending_timeout) { atomic_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET); } @@ -233,8 +233,8 @@ static int send_conn_le_param_update(struct bt_conn *conn, const struct bt_le_co /* Use LE connection parameter request if both local and remote support * it; or if local role is master then use LE connection update. */ - if ((BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features) && BT_FEAT_LE_CONN_PARAM_REQ_PROC(conn->le.features) && !atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_L2CAP)) - || (conn->role == BT_HCI_ROLE_MASTER)) { + if ((BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features) && BT_FEAT_LE_CONN_PARAM_REQ_PROC(conn->le.features) && !atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_L2CAP)) || + (conn->role == BT_HCI_ROLE_MASTER)) { int rc; rc = bt_conn_le_conn_update(conn, param); @@ -2303,12 +2303,11 @@ int bt_conn_auth_cb_register(const struct bt_conn_auth_cb *cb) { /* The cancel callback must always be provided if the app provides * interactive callbacks. */ - if (!cb->cancel - && (cb->passkey_display || cb->passkey_entry || cb->passkey_confirm || + if (!cb->cancel && (cb->passkey_display || cb->passkey_entry || cb->passkey_confirm || #if defined(CONFIG_BT_BREDR) - cb->pincode_entry || + cb->pincode_entry || #endif - cb->pairing_confirm)) { + cb->pairing_confirm)) { return -EINVAL; } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c index 7d8781f7d8..ef9856cb50 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c @@ -2457,12 +2457,12 @@ static u16_t parse_include(struct bt_conn *conn, const void *pdu, struct bt_gatt return 0; } -#define BT_GATT_CHRC(_uuid, _handle, _props) \ - BT_GATT_ATTRIBUTE(BT_UUID_GATT_CHRC, BT_GATT_PERM_READ, bt_gatt_attr_read_chrc, NULL, \ - (&(struct bt_gatt_chrc){ \ - .uuid = _uuid, \ - .value_handle = _handle, \ - .properties = _props, \ +#define BT_GATT_CHRC(_uuid, _handle, _props) \ + BT_GATT_ATTRIBUTE(BT_UUID_GATT_CHRC, BT_GATT_PERM_READ, bt_gatt_attr_read_chrc, NULL, \ + (&(struct bt_gatt_chrc){ \ + .uuid = _uuid, \ + .value_handle = _handle, \ + .properties = _props, \ })) static u16_t parse_characteristic(struct bt_conn *conn, const void *pdu, struct bt_gatt_discover_params *params, u16_t length) { @@ -2856,9 +2856,8 @@ int bt_gatt_discover(struct bt_conn *conn, struct bt_gatt_discover_params *param return gatt_read_type(conn, params); case BT_GATT_DISCOVER_DESCRIPTOR: /* Only descriptors can be filtered */ - if (params->uuid - && (!bt_uuid_cmp(params->uuid, BT_UUID_GATT_PRIMARY) || !bt_uuid_cmp(params->uuid, BT_UUID_GATT_SECONDARY) || !bt_uuid_cmp(params->uuid, BT_UUID_GATT_INCLUDE) - || !bt_uuid_cmp(params->uuid, BT_UUID_GATT_CHRC))) { + if (params->uuid && (!bt_uuid_cmp(params->uuid, BT_UUID_GATT_PRIMARY) || !bt_uuid_cmp(params->uuid, BT_UUID_GATT_SECONDARY) || !bt_uuid_cmp(params->uuid, BT_UUID_GATT_INCLUDE) || + !bt_uuid_cmp(params->uuid, BT_UUID_GATT_CHRC))) { return -EINVAL; } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c index b6319be366..bfcdc05bd5 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c @@ -228,7 +228,7 @@ struct event_handler { void (*handler)(struct net_buf *buf); }; -#define EVENT_HANDLER(_evt, _handler, _min_len) \ +#define EVENT_HANDLER(_evt, _handler, _min_len) \ { .event = _evt, .handler = _handler, .min_len = _min_len, } static inline void handle_event(u8_t event, struct net_buf *buf, const struct event_handler *handlers, size_t num_handlers) { @@ -4843,8 +4843,8 @@ static void hci_vs_init(void) { * a static random address yet at this point, so the identity will * either be zeroes or a valid public address. */ - if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) - && (bt_dev.hci_version < BT_HCI_VERSION_5_0 || (!atomic_test_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR) && bt_addr_le_cmp(&bt_dev.id_addr[0], BT_ADDR_LE_ANY)))) { + if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) && + (bt_dev.hci_version < BT_HCI_VERSION_5_0 || (!atomic_test_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR) && bt_addr_le_cmp(&bt_dev.id_addr[0], BT_ADDR_LE_ANY)))) { BT_WARN("Controller doesn't seem to support Zephyr vendor HCI"); return; } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_ecc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_ecc.c index 36e6ac21d6..3a8a95b458 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_ecc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_ecc.c @@ -44,9 +44,9 @@ static BT_STACK_NOINIT(ecc_thread_stack, 1024); static const u32_t debug_private_key[8] = {0xcd3c1abd, 0x5899b8a6, 0xeb40b799, 0x4aff607b, 0xd2103f50, 0x74c9b3e3, 0xa3c55f38, 0x3f49f6d4}; #if defined(CONFIG_BT_USE_DEBUG_KEYS) -static const u8_t debug_public_key[64] - = {0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, 0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef, 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e, 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20, - 0x8b, 0xd2, 0x89, 0x15, 0xd0, 0x8e, 0x1c, 0x74, 0x24, 0x30, 0xed, 0x8f, 0xc2, 0x45, 0x63, 0x76, 0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63, 0x6d, 0xeb, 0x2a, 0x65, 0x49, 0x9c, 0x80, 0xdc}; +static const u8_t debug_public_key[64] = {0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, 0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef, 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, + 0x2c, 0x5e, 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20, 0x8b, 0xd2, 0x89, 0x15, 0xd0, 0x8e, 0x1c, 0x74, 0x24, 0x30, 0xed, 0x8f, + 0xc2, 0x45, 0x63, 0x76, 0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63, 0x6d, 0xeb, 0x2a, 0x65, 0x49, 0x9c, 0x80, 0xdc}; #endif enum { diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hfp_hf.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hfp_hf.c index ccd8ef8554..645ed2c81f 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hfp_hf.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hfp_hf.c @@ -77,13 +77,13 @@ static const struct { uint32_t min; uint32_t max; } ag_ind[] = { - {"service", 0, 1}, /* HF_SERVICE_IND */ - {"call", 0, 1}, /* HF_CALL_IND */ + { "service", 0, 1}, /* HF_SERVICE_IND */ + { "call", 0, 1}, /* HF_CALL_IND */ {"callsetup", 0, 3}, /* HF_CALL_SETUP_IND */ - {"callheld", 0, 2}, /* HF_CALL_HELD_IND */ - {"signal", 0, 5}, /* HF_SINGNAL_IND */ - {"roam", 0, 1}, /* HF_ROAM_IND */ - {"battchg", 0, 5} /* HF_BATTERY_IND */ + { "callheld", 0, 2}, /* HF_CALL_HELD_IND */ + { "signal", 0, 5}, /* HF_SINGNAL_IND */ + { "roam", 0, 1}, /* HF_ROAM_IND */ + { "battchg", 0, 5} /* HF_BATTERY_IND */ }; static void connected(struct bt_conn *conn) { BT_DBG("HFP HF Connected!"); } @@ -437,7 +437,11 @@ static const struct unsolicited { const char *cmd; enum at_cmd_type type; int (*func)(struct at_client *hf_at); -} handlers[] = {{"CIEV", AT_CMD_TYPE_UNSOLICITED, ciev_handle}, {"RING", AT_CMD_TYPE_OTHER, ring_handle}, {"BCS", AT_CMD_TYPE_UNSOLICITED, bcs_handle}}; +} handlers[] = { + {"CIEV", AT_CMD_TYPE_UNSOLICITED, ciev_handle}, + {"RING", AT_CMD_TYPE_OTHER, ring_handle}, + { "BCS", AT_CMD_TYPE_UNSOLICITED, bcs_handle} +}; static const struct unsolicited *hfp_hf_unsol_lookup(struct at_client *hf_at) { int i; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/sdp.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/sdp.c index a757f6cb39..3ed5bbf983 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/sdp.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/sdp.c @@ -1233,8 +1233,8 @@ static const struct { uint8_t op_code; uint16_t (*func)(struct bt_sdp *sdp, struct net_buf *buf, uint16_t tid); } handlers[] = { - {BT_SDP_SVC_SEARCH_REQ, sdp_svc_search_req}, - {BT_SDP_SVC_ATTR_REQ, sdp_svc_att_req}, + { BT_SDP_SVC_SEARCH_REQ, sdp_svc_search_req}, + { BT_SDP_SVC_ATTR_REQ, sdp_svc_att_req}, {BT_SDP_SVC_SEARCH_ATTR_REQ, sdp_svc_search_att_req}, }; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc.c index e3e20ddce5..8954dfb31d 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc.c @@ -117,9 +117,19 @@ INLINE OI_UINT16 OI_SBC_CalculateFrameAndHeaderlen(OI_CODEC_SBC_FRAME_INFO *fram * */ OI_UINT computeBitneed(OI_CODEC_SBC_COMMON_CONTEXT *common, OI_UINT8 *bitneeds, OI_UINT ch, OI_UINT *preferredBitpool) { - static const OI_INT8 offset4[4][4] = {{-1, 0, 0, 0}, {-2, 0, 0, 1}, {-2, 0, 0, 1}, {-2, 0, 0, 1}}; - - static const OI_INT8 offset8[4][8] = {{-2, 0, 0, 0, 0, 0, 0, 1}, {-3, 0, 0, 0, 0, 0, 1, 2}, {-4, 0, 0, 0, 0, 0, 1, 2}, {-4, 0, 0, 0, 0, 0, 1, 2}}; + static const OI_INT8 offset4[4][4] = { + {-1, 0, 0, 0}, + {-2, 0, 0, 1}, + {-2, 0, 0, 1}, + {-2, 0, 0, 1} + }; + + static const OI_INT8 offset8[4][8] = { + {-2, 0, 0, 0, 0, 0, 0, 1}, + {-3, 0, 0, 0, 0, 0, 1, 2}, + {-4, 0, 0, 0, 0, 0, 1, 2}, + {-4, 0, 0, 0, 0, 0, 1, 2} + }; const OI_UINT nrof_subbands = common->frameInfo.nrof_subbands; OI_UINT sb; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing.c index f68c0300ce..a809b1f812 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing.c @@ -62,15 +62,15 @@ const OI_BYTE crc8_wide[128] = { #elif defined(USE_NIBBLEWISE_CRC) const OI_BYTE crc8_narrow[16] = {0x00, 0x1d, 0x3a, 0x27, 0x74, 0x69, 0x4e, 0x53, 0xe8, 0xf5, 0xd2, 0xcf, 0x9c, 0x81, 0xa6, 0xbb}; #else -const OI_BYTE crc8_narrow[256] - = {0x00, 0x1d, 0x3a, 0x27, 0x74, 0x69, 0x4e, 0x53, 0xe8, 0xf5, 0xd2, 0xcf, 0x9c, 0x81, 0xa6, 0xbb, 0xcd, 0xd0, 0xf7, 0xea, 0xb9, 0xa4, 0x83, 0x9e, 0x25, 0x38, 0x1f, 0x02, 0x51, 0x4c, 0x6b, 0x76, - 0x87, 0x9a, 0xbd, 0xa0, 0xf3, 0xee, 0xc9, 0xd4, 0x6f, 0x72, 0x55, 0x48, 0x1b, 0x06, 0x21, 0x3c, 0x4a, 0x57, 0x70, 0x6d, 0x3e, 0x23, 0x04, 0x19, 0xa2, 0xbf, 0x98, 0x85, 0xd6, 0xcb, 0xec, 0xf1, - 0x13, 0x0e, 0x29, 0x34, 0x67, 0x7a, 0x5d, 0x40, 0xfb, 0xe6, 0xc1, 0xdc, 0x8f, 0x92, 0xb5, 0xa8, 0xde, 0xc3, 0xe4, 0xf9, 0xaa, 0xb7, 0x90, 0x8d, 0x36, 0x2b, 0x0c, 0x11, 0x42, 0x5f, 0x78, 0x65, - 0x94, 0x89, 0xae, 0xb3, 0xe0, 0xfd, 0xda, 0xc7, 0x7c, 0x61, 0x46, 0x5b, 0x08, 0x15, 0x32, 0x2f, 0x59, 0x44, 0x63, 0x7e, 0x2d, 0x30, 0x17, 0x0a, 0xb1, 0xac, 0x8b, 0x96, 0xc5, 0xd8, 0xff, 0xe2, - 0x26, 0x3b, 0x1c, 0x01, 0x52, 0x4f, 0x68, 0x75, 0xce, 0xd3, 0xf4, 0xe9, 0xba, 0xa7, 0x80, 0x9d, 0xeb, 0xf6, 0xd1, 0xcc, 0x9f, 0x82, 0xa5, 0xb8, 0x03, 0x1e, 0x39, 0x24, 0x77, 0x6a, 0x4d, 0x50, - 0xa1, 0xbc, 0x9b, 0x86, 0xd5, 0xc8, 0xef, 0xf2, 0x49, 0x54, 0x73, 0x6e, 0x3d, 0x20, 0x07, 0x1a, 0x6c, 0x71, 0x56, 0x4b, 0x18, 0x05, 0x22, 0x3f, 0x84, 0x99, 0xbe, 0xa3, 0xf0, 0xed, 0xca, 0xd7, - 0x35, 0x28, 0x0f, 0x12, 0x41, 0x5c, 0x7b, 0x66, 0xdd, 0xc0, 0xe7, 0xfa, 0xa9, 0xb4, 0x93, 0x8e, 0xf8, 0xe5, 0xc2, 0xdf, 0x8c, 0x91, 0xb6, 0xab, 0x10, 0x0d, 0x2a, 0x37, 0x64, 0x79, 0x5e, 0x43, - 0xb2, 0xaf, 0x88, 0x95, 0xc6, 0xdb, 0xfc, 0xe1, 0x5a, 0x47, 0x60, 0x7d, 0x2e, 0x33, 0x14, 0x09, 0x7f, 0x62, 0x45, 0x58, 0x0b, 0x16, 0x31, 0x2c, 0x97, 0x8a, 0xad, 0xb0, 0xe3, 0xfe, 0xd9, 0xc4}; +const OI_BYTE crc8_narrow[256] = { + 0x00, 0x1d, 0x3a, 0x27, 0x74, 0x69, 0x4e, 0x53, 0xe8, 0xf5, 0xd2, 0xcf, 0x9c, 0x81, 0xa6, 0xbb, 0xcd, 0xd0, 0xf7, 0xea, 0xb9, 0xa4, 0x83, 0x9e, 0x25, 0x38, 0x1f, 0x02, 0x51, 0x4c, 0x6b, 0x76, + 0x87, 0x9a, 0xbd, 0xa0, 0xf3, 0xee, 0xc9, 0xd4, 0x6f, 0x72, 0x55, 0x48, 0x1b, 0x06, 0x21, 0x3c, 0x4a, 0x57, 0x70, 0x6d, 0x3e, 0x23, 0x04, 0x19, 0xa2, 0xbf, 0x98, 0x85, 0xd6, 0xcb, 0xec, 0xf1, + 0x13, 0x0e, 0x29, 0x34, 0x67, 0x7a, 0x5d, 0x40, 0xfb, 0xe6, 0xc1, 0xdc, 0x8f, 0x92, 0xb5, 0xa8, 0xde, 0xc3, 0xe4, 0xf9, 0xaa, 0xb7, 0x90, 0x8d, 0x36, 0x2b, 0x0c, 0x11, 0x42, 0x5f, 0x78, 0x65, + 0x94, 0x89, 0xae, 0xb3, 0xe0, 0xfd, 0xda, 0xc7, 0x7c, 0x61, 0x46, 0x5b, 0x08, 0x15, 0x32, 0x2f, 0x59, 0x44, 0x63, 0x7e, 0x2d, 0x30, 0x17, 0x0a, 0xb1, 0xac, 0x8b, 0x96, 0xc5, 0xd8, 0xff, 0xe2, + 0x26, 0x3b, 0x1c, 0x01, 0x52, 0x4f, 0x68, 0x75, 0xce, 0xd3, 0xf4, 0xe9, 0xba, 0xa7, 0x80, 0x9d, 0xeb, 0xf6, 0xd1, 0xcc, 0x9f, 0x82, 0xa5, 0xb8, 0x03, 0x1e, 0x39, 0x24, 0x77, 0x6a, 0x4d, 0x50, + 0xa1, 0xbc, 0x9b, 0x86, 0xd5, 0xc8, 0xef, 0xf2, 0x49, 0x54, 0x73, 0x6e, 0x3d, 0x20, 0x07, 0x1a, 0x6c, 0x71, 0x56, 0x4b, 0x18, 0x05, 0x22, 0x3f, 0x84, 0x99, 0xbe, 0xa3, 0xf0, 0xed, 0xca, 0xd7, + 0x35, 0x28, 0x0f, 0x12, 0x41, 0x5c, 0x7b, 0x66, 0xdd, 0xc0, 0xe7, 0xfa, 0xa9, 0xb4, 0x93, 0x8e, 0xf8, 0xe5, 0xc2, 0xdf, 0x8c, 0x91, 0xb6, 0xab, 0x10, 0x0d, 0x2a, 0x37, 0x64, 0x79, 0x5e, 0x43, + 0xb2, 0xaf, 0x88, 0x95, 0xc6, 0xdb, 0xfc, 0xe1, 0x5a, 0x47, 0x60, 0x7d, 0x2e, 0x33, 0x14, 0x09, 0x7f, 0x62, 0x45, 0x58, 0x0b, 0x16, 0x31, 0x2c, 0x97, 0x8a, 0xad, 0xb0, 0xe3, 0xfe, 0xd9, 0xc4}; #endif const OI_UINT32 dequant_long_scaled[17] = { 0, 0, 0x1ee9e116, /* bits=2 0.24151243 1/3 * (1/1.38019122262781) (0x00000008)*/ @@ -198,17 +198,17 @@ void OI_SBC_ExpandFrameFields(OI_CODEC_SBC_FRAME_INFO *frame) { /** * Unrolled macro to copy 4 32-bit aligned 32-bit values backward in memory */ -#define COPY4WORDS_BACK(_dest, _src) \ - do { \ - OI_INT32 _a, _b, _c, _d; \ - _a = *--_src; \ - _b = *--_src; \ - _c = *--_src; \ - _d = *--_src; \ - *--_dest = _a; \ - *--_dest = _b; \ - *--_dest = _c; \ - *--_dest = _d; \ +#define COPY4WORDS_BACK(_dest, _src) \ + do { \ + OI_INT32 _a, _b, _c, _d; \ + _a = *--_src; \ + _b = *--_src; \ + _c = *--_src; \ + _d = *--_src; \ + *--_dest = _a; \ + *--_dest = _b; \ + *--_dest = _c; \ + *--_dest = _d; \ } while (0) #if defined(USE_PLATFORM_MEMMOVE) || defined(USE_PLATFORM_MEMCPY) diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-8-generated.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-8-generated.c index cc603f7d7a..1434d9d1fe 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-8-generated.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-8-generated.c @@ -35,13 +35,13 @@ #if defined(SBC_DEC_INCLUDED) #ifndef CLIP_INT16 -#define CLIP_INT16(x) \ - do { \ - if (x > OI_INT16_MAX) { \ - x = OI_INT16_MAX; \ - } else if (x < OI_INT16_MIN) { \ - x = OI_INT16_MIN; \ - } \ +#define CLIP_INT16(x) \ + do { \ + if (x > OI_INT16_MAX) { \ + x = OI_INT16_MAX; \ + } else if (x < OI_INT16_MIN) { \ + x = OI_INT16_MIN; \ + } \ } while (0) #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-dct8.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-dct8.c index d75b8ae7ae..4133ae5e3e 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-dct8.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-dct8.c @@ -82,10 +82,10 @@ static INLINE OI_INT32 default_mul_32s_32s_hi(OI_INT32 u, OI_INT32 v) { #ifdef DEBUG_DCT PRIVATE void float_dct2_8(float *RESTRICT out, OI_INT32 const *RESTRICT in) { #define FIX(x, bits) (((int)floor(0.5f + ((x) * ((float)(1 << bits))))) / ((float)(1 << bits))) -#define FLOAT_BUTTERFLY(x, y) \ - x += y; \ - y = x - (y * 2); \ - OI_ASSERT(VALID_INT32(x)); \ +#define FLOAT_BUTTERFLY(x, y) \ + x += y; \ + y = x - (y * 2); \ + OI_ASSERT(VALID_INT32(x)); \ OI_ASSERT(VALID_INT32(y)); #define FLOAT_MULT_DCT(K, sample) (FIX(K, 20) * sample) #define FLOAT_SCALE(x, y) (((x) / (double)(1 << (y)))) @@ -246,8 +246,8 @@ PRIVATE void float_dct2_8(float *RESTRICT out, OI_INT32 const *RESTRICT in) { * */ PRIVATE void dct2_8(SBC_BUFFER_T *RESTRICT out, OI_INT32 const *RESTRICT in) { -#define BUTTERFLY(x, y) \ - x += y; \ +#define BUTTERFLY(x, y) \ + x += y; \ y = x - (y << 1); #define FIX_MULT_DCT(K, x) (MUL_32S_32S_HI(K, x) << 2) diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-sbc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-sbc.c index 66cd17a1d6..f8926df5b8 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-sbc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-sbc.c @@ -201,13 +201,13 @@ const OI_INT32 dec_window_4[21] = { #endif #ifndef CLIP_INT16 -#define CLIP_INT16(x) \ - do { \ - if (x > OI_INT16_MAX) { \ - x = OI_INT16_MAX; \ - } else if (x < OI_INT16_MIN) { \ - x = OI_INT16_MIN; \ - } \ +#define CLIP_INT16(x) \ + do { \ + if (x > OI_INT16_MAX) { \ + x = OI_INT16_MAX; \ + } else if (x < OI_INT16_MIN) { \ + x = OI_INT16_MIN; \ + } \ } while (0) #endif @@ -247,9 +247,9 @@ PRIVATE void dct2_8(SBC_BUFFER_T *RESTRICT out, OI_INT32 const *RESTRICT x); typedef void (*SYNTH_FRAME)(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT blkstart, OI_UINT blkcount); #ifndef COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS -#define COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(dest, src) \ - do { \ - shift_buffer(dest, src, 72); \ +#define COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(dest, src) \ + do { \ + shift_buffer(dest, src, 72); \ } while (0) #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_analysis.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_analysis.c index bc03d6900c..40a079aec6 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_analysis.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_analysis.c @@ -174,81 +174,81 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf SHIFTUP_X8_2*/ #endif /* This macro is for 4 subbands */ -#define SHIFTUP_X4 \ - { \ - ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 38); \ - for (i = 0; i < 9; i++) { \ - *ps32X = *(ps32X - 2 - (ShiftCounter >> 1)); \ - ps32X--; \ - *ps32X = *(ps32X - 2 - (ShiftCounter >> 1)); \ - ps32X--; \ - } \ +#define SHIFTUP_X4 \ + { \ + ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 38); \ + for (i = 0; i < 9; i++) { \ + *ps32X = *(ps32X - 2 - (ShiftCounter >> 1)); \ + ps32X--; \ + *ps32X = *(ps32X - 2 - (ShiftCounter >> 1)); \ + ps32X--; \ + } \ } -#define SHIFTUP_X4_2 \ - { \ - ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 38); \ - ps32X2 = (SINT32 *)(s16X + (EncMaxShiftCounter << 1) + 78); \ - for (i = 0; i < 9; i++) { \ - *ps32X = *(ps32X - 2 - (ShiftCounter >> 1)); \ - *(ps32X2) = *(ps32X2 - 2 - (ShiftCounter >> 1)); \ - ps32X--; \ - ps32X2--; \ - *ps32X = *(ps32X - 2 - (ShiftCounter >> 1)); \ - *(ps32X2) = *(ps32X2 - 2 - (ShiftCounter >> 1)); \ - ps32X--; \ - ps32X2--; \ - } \ +#define SHIFTUP_X4_2 \ + { \ + ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 38); \ + ps32X2 = (SINT32 *)(s16X + (EncMaxShiftCounter << 1) + 78); \ + for (i = 0; i < 9; i++) { \ + *ps32X = *(ps32X - 2 - (ShiftCounter >> 1)); \ + *(ps32X2) = *(ps32X2 - 2 - (ShiftCounter >> 1)); \ + ps32X--; \ + ps32X2--; \ + *ps32X = *(ps32X - 2 - (ShiftCounter >> 1)); \ + *(ps32X2) = *(ps32X2 - 2 - (ShiftCounter >> 1)); \ + ps32X--; \ + ps32X2--; \ + } \ } /* This macro is for 8 subbands */ -#define SHIFTUP_X8 \ - { \ - ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 78); \ - for (i = 0; i < 9; i++) { \ - *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ - ps32X--; \ - *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ - ps32X--; \ - *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ - ps32X--; \ - *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ - ps32X--; \ - } \ +#define SHIFTUP_X8 \ + { \ + ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 78); \ + for (i = 0; i < 9; i++) { \ + *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ + ps32X--; \ + *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ + ps32X--; \ + *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ + ps32X--; \ + *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ + ps32X--; \ + } \ } -#define SHIFTUP_X8_2 \ - { \ - ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 78); \ - ps32X2 = (SINT32 *)(s16X + (EncMaxShiftCounter << 1) + 158); \ - for (i = 0; i < 9; i++) { \ - *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ - *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1)); \ - ps32X--; \ - ps32X2--; \ - *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ - *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1)); \ - ps32X--; \ - ps32X2--; \ - *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ - *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1)); \ - ps32X--; \ - ps32X2--; \ - *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ - *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1)); \ - ps32X--; \ - ps32X2--; \ - } \ +#define SHIFTUP_X8_2 \ + { \ + ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 78); \ + ps32X2 = (SINT32 *)(s16X + (EncMaxShiftCounter << 1) + 158); \ + for (i = 0; i < 9; i++) { \ + *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ + *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1)); \ + ps32X--; \ + ps32X2--; \ + *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ + *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1)); \ + ps32X--; \ + ps32X2--; \ + *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ + *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1)); \ + ps32X--; \ + ps32X2--; \ + *ps32X = *(ps32X - 4 - (ShiftCounter >> 1)); \ + *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1)); \ + ps32X--; \ + ps32X2--; \ + } \ } #if (SBC_ARM_ASM_OPT == TRUE) -#define WINDOW_ACCU_8_0 \ - { \ +#define WINDOW_ACCU_8_0 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_0_1,(s16X[ChOffset+16]-s16X[ChOffset+64]);\ MLA s32Hi,WIND_8_SUBBANDS_0_2,(s16X[ChOffset+32]-s16X[ChOffset+48]),s32Hi;\ - MOV s32DCTY[0],s32Hi; } \ + MOV s32DCTY[0],s32Hi; } \ } -#define WINDOW_ACCU_8_1_15 \ - { \ +#define WINDOW_ACCU_8_1_15 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_1_0,s16X[ChOffset+1];\ MUL s32Hi2,WIND_8_SUBBANDS_1_0,s16X[ChOffset+64+15];\ @@ -261,11 +261,11 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf SHIFTUP_X8_2*/ MLA s32Hi,WIND_8_SUBBANDS_1_4,s16X[ChOffset+64+1],s32Hi;\ MLA s32Hi2,WIND_8_SUBBANDS_1_4,s16X[ChOffset+15],s32Hi2;\ MOV s32DCTY[1],s32Hi;\ - MOV s32DCTY[15],s32Hi2; \ - } \ + MOV s32DCTY[15],s32Hi2; \ + } \ } -#define WINDOW_ACCU_8_2_14 \ - { \ +#define WINDOW_ACCU_8_2_14 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_2_0,s16X[ChOffset+2];\ MUL s32Hi2,WIND_8_SUBBANDS_2_0,s16X[ChOffset+64+14];\ @@ -278,11 +278,11 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf SHIFTUP_X8_2*/ MLA s32Hi,WIND_8_SUBBANDS_2_4,s16X[ChOffset+64+2],s32Hi;\ MLA s32Hi2,WIND_8_SUBBANDS_2_4,s16X[ChOffset+14],s32Hi2;\ MOV s32DCTY[2],s32Hi;\ - MOV s32DCTY[14],s32Hi2; \ - } \ + MOV s32DCTY[14],s32Hi2; \ + } \ } -#define WINDOW_ACCU_8_3_13 \ - { \ +#define WINDOW_ACCU_8_3_13 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_3_0,s16X[ChOffset+3];\ MUL s32Hi2,WIND_8_SUBBANDS_3_0,s16X[ChOffset+64+13];\ @@ -295,11 +295,11 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf SHIFTUP_X8_2*/ MLA s32Hi,WIND_8_SUBBANDS_3_4,s16X[ChOffset+64+3],s32Hi;\ MLA s32Hi2,WIND_8_SUBBANDS_3_4,s16X[ChOffset+13],s32Hi2;\ MOV s32DCTY[3],s32Hi;\ - MOV s32DCTY[13],s32Hi2; \ - } \ + MOV s32DCTY[13],s32Hi2; \ + } \ } -#define WINDOW_ACCU_8_4_12 \ - { \ +#define WINDOW_ACCU_8_4_12 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_4_0,s16X[ChOffset+4];\ MUL s32Hi2,WIND_8_SUBBANDS_4_0,s16X[ChOffset+64+12];\ @@ -312,11 +312,11 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf SHIFTUP_X8_2*/ MLA s32Hi,WIND_8_SUBBANDS_4_4,s16X[ChOffset+64+4],s32Hi;\ MLA s32Hi2,WIND_8_SUBBANDS_4_4,s16X[ChOffset+12],s32Hi2;\ MOV s32DCTY[4],s32Hi;\ - MOV s32DCTY[12],s32Hi2; \ - } \ + MOV s32DCTY[12],s32Hi2; \ + } \ } -#define WINDOW_ACCU_8_5_11 \ - { \ +#define WINDOW_ACCU_8_5_11 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_5_0,s16X[ChOffset+5];\ MUL s32Hi2,WIND_8_SUBBANDS_5_0,s16X[ChOffset+64+11];\ @@ -329,11 +329,11 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf SHIFTUP_X8_2*/ MLA s32Hi,WIND_8_SUBBANDS_5_4,s16X[ChOffset+64+5],s32Hi;\ MLA s32Hi2,WIND_8_SUBBANDS_5_4,s16X[ChOffset+11],s32Hi2;\ MOV s32DCTY[5],s32Hi;\ - MOV s32DCTY[11],s32Hi2; \ - } \ + MOV s32DCTY[11],s32Hi2; \ + } \ } -#define WINDOW_ACCU_8_6_10 \ - { \ +#define WINDOW_ACCU_8_6_10 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_6_0,s16X[ChOffset+6];\ MUL s32Hi2,WIND_8_SUBBANDS_6_0,s16X[ChOffset+64+10];\ @@ -346,11 +346,11 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf SHIFTUP_X8_2*/ MLA s32Hi,WIND_8_SUBBANDS_6_4,s16X[ChOffset+64+6],s32Hi;\ MLA s32Hi2,WIND_8_SUBBANDS_6_4,s16X[ChOffset+10],s32Hi2;\ MOV s32DCTY[6],s32Hi;\ - MOV s32DCTY[10],s32Hi2; \ - } \ + MOV s32DCTY[10],s32Hi2; \ + } \ } -#define WINDOW_ACCU_8_7_9 \ - { \ +#define WINDOW_ACCU_8_7_9 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_7_0,s16X[ChOffset+7];\ MUL s32Hi2,WIND_8_SUBBANDS_7_0,s16X[ChOffset+64+9];\ @@ -363,27 +363,27 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf SHIFTUP_X8_2*/ MLA s32Hi,WIND_8_SUBBANDS_7_4,s16X[ChOffset+64+7],s32Hi;\ MLA s32Hi2,WIND_8_SUBBANDS_7_4,s16X[ChOffset+9],s32Hi2;\ MOV s32DCTY[7],s32Hi;\ - MOV s32DCTY[9],s32Hi2; \ - } \ + MOV s32DCTY[9],s32Hi2; \ + } \ } -#define WINDOW_ACCU_8_8 \ - { \ +#define WINDOW_ACCU_8_8 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_8_0,(s16X[ChOffset+8]+s16X[ChOffset+8+64]);\ MLA s32Hi,WIND_8_SUBBANDS_8_1,(s16X[ChOffset+8+16]+s16X[ChOffset+8+64]),s32Hi;\ MLA s32Hi,WIND_8_SUBBANDS_8_2,s16X[ChOffset+8+32],s32Hi;\ - MOV s32DCTY[8],s32Hi; \ - } \ + MOV s32DCTY[8],s32Hi; \ + } \ } -#define WINDOW_ACCU_4_0 \ - { \ +#define WINDOW_ACCU_4_0 \ + { \ __asm {\ MUL s32Hi,WIND_4_SUBBANDS_0_1,(s16X[ChOffset+8]-s16X[ChOffset+32]);\ MLA s32Hi,WIND_4_SUBBANDS_0_2,(s16X[ChOffset+16]-s16X[ChOffset+24]),s32Hi;\ - MOV s32DCTY[0],s32Hi; } \ + MOV s32DCTY[0],s32Hi; } \ } -#define WINDOW_ACCU_4_1_7 \ - { \ +#define WINDOW_ACCU_4_1_7 \ + { \ __asm {\ MUL s32Hi,WIND_4_SUBBANDS_1_0,s16X[ChOffset+1];\ MUL s32Hi2,WIND_4_SUBBANDS_1_0,s16X[ChOffset+32+7];\ @@ -396,11 +396,11 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf SHIFTUP_X8_2*/ MLA s32Hi,WIND_4_SUBBANDS_1_4,s16X[ChOffset+32+1],s32Hi;\ MLA s32Hi2,WIND_4_SUBBANDS_1_4,s16X[ChOffset+7],s32Hi2;\ MOV s32DCTY[1],s32Hi;\ - MOV s32DCTY[7],s32Hi2; \ - } \ + MOV s32DCTY[7],s32Hi2; \ + } \ } -#define WINDOW_ACCU_4_2_6 \ - { \ +#define WINDOW_ACCU_4_2_6 \ + { \ __asm {\ MUL s32Hi,WIND_4_SUBBANDS_2_0,s16X[ChOffset+2];\ MUL s32Hi2,WIND_4_SUBBANDS_2_0,s16X[ChOffset+32+6];\ @@ -413,11 +413,11 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf SHIFTUP_X8_2*/ MLA s32Hi,WIND_4_SUBBANDS_2_4,s16X[ChOffset+32+2],s32Hi;\ MLA s32Hi2,WIND_4_SUBBANDS_2_4,s16X[ChOffset+6],s32Hi2;\ MOV s32DCTY[2],s32Hi;\ - MOV s32DCTY[6],s32Hi2; \ - } \ + MOV s32DCTY[6],s32Hi2; \ + } \ } -#define WINDOW_ACCU_4_3_5 \ - { \ +#define WINDOW_ACCU_4_3_5 \ + { \ __asm {\ MUL s32Hi,WIND_4_SUBBANDS_3_0,s16X[ChOffset+3];\ MUL s32Hi2,WIND_4_SUBBANDS_3_0,s16X[ChOffset+32+5];\ @@ -430,497 +430,497 @@ static SINT16 *s16X; /* s16X must be 32 bits aligned cf SHIFTUP_X8_2*/ MLA s32Hi,WIND_4_SUBBANDS_3_4,s16X[ChOffset+32+3],s32Hi;\ MLA s32Hi2,WIND_4_SUBBANDS_3_4,s16X[ChOffset+5],s32Hi2;\ MOV s32DCTY[3],s32Hi;\ - MOV s32DCTY[5],s32Hi2; \ - } \ + MOV s32DCTY[5],s32Hi2; \ + } \ } -#define WINDOW_ACCU_4_4 \ - { \ +#define WINDOW_ACCU_4_4 \ + { \ __asm {\ MUL s32Hi,WIND_4_SUBBANDS_4_0,(s16X[ChOffset+4]+s16X[ChOffset+4+32]);\ MLA s32Hi,WIND_4_SUBBANDS_4_1,(s16X[ChOffset+4+8]+s16X[ChOffset+4+24]),s32Hi;\ MLA s32Hi,WIND_4_SUBBANDS_4_2,s16X[ChOffset+4+16],s32Hi;\ - MOV s32DCTY[4],s32Hi; \ - } \ + MOV s32DCTY[4],s32Hi; \ + } \ } -#define WINDOW_PARTIAL_4 \ - { \ - WINDOW_ACCU_4_0; \ - WINDOW_ACCU_4_1_7; \ - WINDOW_ACCU_4_2_6; \ - WINDOW_ACCU_4_3_5; \ - WINDOW_ACCU_4_4; \ +#define WINDOW_PARTIAL_4 \ + { \ + WINDOW_ACCU_4_0; \ + WINDOW_ACCU_4_1_7; \ + WINDOW_ACCU_4_2_6; \ + WINDOW_ACCU_4_3_5; \ + WINDOW_ACCU_4_4; \ } -#define WINDOW_PARTIAL_8 \ - { \ - WINDOW_ACCU_8_0; \ - WINDOW_ACCU_8_1_15; \ - WINDOW_ACCU_8_2_14; \ - WINDOW_ACCU_8_3_13; \ - WINDOW_ACCU_8_4_12; \ - WINDOW_ACCU_8_5_11; \ - WINDOW_ACCU_8_6_10; \ - WINDOW_ACCU_8_7_9; \ - WINDOW_ACCU_8_8; \ +#define WINDOW_PARTIAL_8 \ + { \ + WINDOW_ACCU_8_0; \ + WINDOW_ACCU_8_1_15; \ + WINDOW_ACCU_8_2_14; \ + WINDOW_ACCU_8_3_13; \ + WINDOW_ACCU_8_4_12; \ + WINDOW_ACCU_8_5_11; \ + WINDOW_ACCU_8_6_10; \ + WINDOW_ACCU_8_7_9; \ + WINDOW_ACCU_8_8; \ } #else #if (SBC_IPAQ_OPT == TRUE) #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE) -#define WINDOW_ACCU_8_0 \ - { \ - s64Temp = (SINT64)WIND_8_SUBBANDS_0_1 * (SINT64)(s16X[ChOffset + 16] - s16X[ChOffset + 64]); \ - s64Temp += (SINT64)WIND_8_SUBBANDS_0_2 * (SINT64)(s16X[ChOffset + 32] - s16X[ChOffset + 48]); \ - s32DCTY[0] = (SINT32)(s64Temp >> 16); \ +#define WINDOW_ACCU_8_0 \ + { \ + s64Temp = (SINT64)WIND_8_SUBBANDS_0_1 * (SINT64)(s16X[ChOffset + 16] - s16X[ChOffset + 64]); \ + s64Temp += (SINT64)WIND_8_SUBBANDS_0_2 * (SINT64)(s16X[ChOffset + 32] - s16X[ChOffset + 48]); \ + s32DCTY[0] = (SINT32)(s64Temp >> 16); \ } -#define WINDOW_ACCU_8_1_15 \ - { \ - s64Temp = (SINT64)WIND_8_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 1]; \ - s64Temp2 = (SINT64)WIND_8_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 64 + 15]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 16 + 1]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 48 + 15]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 32 + 1]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 32 + 15]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 48 + 1]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 16 + 15]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 64 + 1]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 15]; \ - s32DCTY[1] = (SINT32)(s64Temp >> 16); \ - s32DCTY[15] = (SINT32)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_8_1_15 \ + { \ + s64Temp = (SINT64)WIND_8_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 1]; \ + s64Temp2 = (SINT64)WIND_8_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 64 + 15]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 16 + 1]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 48 + 15]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 32 + 1]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 32 + 15]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 48 + 1]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 16 + 15]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 64 + 1]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 15]; \ + s32DCTY[1] = (SINT32)(s64Temp >> 16); \ + s32DCTY[15] = (SINT32)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_8_2_14 \ - { \ - s64Temp = (SINT64)WIND_8_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 2]; \ - s64Temp2 = (SINT64)WIND_8_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 64 + 14]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 16 + 2]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 48 + 14]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 32 + 2]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 32 + 14]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 48 + 2]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 16 + 14]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 64 + 2]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 14]; \ - s32DCTY[2] = (SINT32)(s64Temp >> 16); \ - s32DCTY[14] = (SINT32)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_8_2_14 \ + { \ + s64Temp = (SINT64)WIND_8_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 2]; \ + s64Temp2 = (SINT64)WIND_8_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 64 + 14]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 16 + 2]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 48 + 14]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 32 + 2]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 32 + 14]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 48 + 2]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 16 + 14]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 64 + 2]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 14]; \ + s32DCTY[2] = (SINT32)(s64Temp >> 16); \ + s32DCTY[14] = (SINT32)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_8_3_13 \ - { \ - s64Temp = (SINT64)WIND_8_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 3]; \ - s64Temp2 = (SINT64)WIND_8_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 64 + 13]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 16 + 3]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 48 + 13]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 32 + 3]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 32 + 13]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 48 + 3]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 16 + 13]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 64 + 3]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 13]; \ - s32DCTY[3] = (SINT32)(s64Temp >> 16); \ - s32DCTY[13] = (SINT32)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_8_3_13 \ + { \ + s64Temp = (SINT64)WIND_8_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 3]; \ + s64Temp2 = (SINT64)WIND_8_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 64 + 13]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 16 + 3]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 48 + 13]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 32 + 3]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 32 + 13]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 48 + 3]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 16 + 13]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 64 + 3]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 13]; \ + s32DCTY[3] = (SINT32)(s64Temp >> 16); \ + s32DCTY[13] = (SINT32)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_8_4_12 \ - { \ - s64Temp = (SINT64)WIND_8_SUBBANDS_4_0 * (SINT64)s16X[ChOffset + 4]; \ - s64Temp2 = (SINT64)WIND_8_SUBBANDS_4_0 * (SINT64)s16X[ChOffset + 64 + 12]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_4_1 * (SINT64)s16X[ChOffset + 16 + 4]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_1 * (SINT64)s16X[ChOffset + 48 + 12]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_4_2 * (SINT64)s16X[ChOffset + 32 + 4]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_2 * (SINT64)s16X[ChOffset + 32 + 12]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_4_3 * (SINT64)s16X[ChOffset + 48 + 4]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_3 * (SINT64)s16X[ChOffset + 16 + 12]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_4_4 * (SINT64)s16X[ChOffset + 64 + 4]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_4 * (SINT64)s16X[ChOffset + 12]; \ - s32DCTY[4] = (SINT32)(s64Temp >> 16); \ - s32DCTY[12] = (SINT32)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_8_4_12 \ + { \ + s64Temp = (SINT64)WIND_8_SUBBANDS_4_0 * (SINT64)s16X[ChOffset + 4]; \ + s64Temp2 = (SINT64)WIND_8_SUBBANDS_4_0 * (SINT64)s16X[ChOffset + 64 + 12]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_4_1 * (SINT64)s16X[ChOffset + 16 + 4]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_1 * (SINT64)s16X[ChOffset + 48 + 12]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_4_2 * (SINT64)s16X[ChOffset + 32 + 4]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_2 * (SINT64)s16X[ChOffset + 32 + 12]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_4_3 * (SINT64)s16X[ChOffset + 48 + 4]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_3 * (SINT64)s16X[ChOffset + 16 + 12]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_4_4 * (SINT64)s16X[ChOffset + 64 + 4]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_4 * (SINT64)s16X[ChOffset + 12]; \ + s32DCTY[4] = (SINT32)(s64Temp >> 16); \ + s32DCTY[12] = (SINT32)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_8_5_11 \ - { \ - s64Temp = (SINT64)WIND_8_SUBBANDS_5_0 * (SINT64)s16X[ChOffset + 5]; \ - s64Temp2 = (SINT64)WIND_8_SUBBANDS_5_0 * (SINT64)s16X[ChOffset + 64 + 11]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_5_1 * (SINT64)s16X[ChOffset + 16 + 5]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_1 * (SINT64)s16X[ChOffset + 48 + 11]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_5_2 * (SINT64)s16X[ChOffset + 32 + 5]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_2 * (SINT64)s16X[ChOffset + 32 + 11]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_5_3 * (SINT64)s16X[ChOffset + 48 + 5]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_3 * (SINT64)s16X[ChOffset + 16 + 11]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_5_4 * (SINT64)s16X[ChOffset + 64 + 5]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_4 * (SINT64)s16X[ChOffset + 11]; \ - s32DCTY[5] = (SINT32)(s64Temp >> 16); \ - s32DCTY[11] = (SINT32)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_8_5_11 \ + { \ + s64Temp = (SINT64)WIND_8_SUBBANDS_5_0 * (SINT64)s16X[ChOffset + 5]; \ + s64Temp2 = (SINT64)WIND_8_SUBBANDS_5_0 * (SINT64)s16X[ChOffset + 64 + 11]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_5_1 * (SINT64)s16X[ChOffset + 16 + 5]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_1 * (SINT64)s16X[ChOffset + 48 + 11]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_5_2 * (SINT64)s16X[ChOffset + 32 + 5]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_2 * (SINT64)s16X[ChOffset + 32 + 11]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_5_3 * (SINT64)s16X[ChOffset + 48 + 5]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_3 * (SINT64)s16X[ChOffset + 16 + 11]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_5_4 * (SINT64)s16X[ChOffset + 64 + 5]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_4 * (SINT64)s16X[ChOffset + 11]; \ + s32DCTY[5] = (SINT32)(s64Temp >> 16); \ + s32DCTY[11] = (SINT32)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_8_6_10 \ - { \ - s64Temp = (SINT64)WIND_8_SUBBANDS_6_0 * (SINT64)s16X[ChOffset + 6]; \ - s64Temp2 = (SINT64)WIND_8_SUBBANDS_6_0 * (SINT64)s16X[ChOffset + 64 + 10]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_6_1 * (SINT64)s16X[ChOffset + 16 + 6]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_1 * (SINT64)s16X[ChOffset + 48 + 10]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_6_2 * (SINT64)s16X[ChOffset + 32 + 6]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_2 * (SINT64)s16X[ChOffset + 32 + 10]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_6_3 * (SINT64)s16X[ChOffset + 48 + 6]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_3 * (SINT64)s16X[ChOffset + 16 + 10]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_6_4 * (SINT64)s16X[ChOffset + 64 + 6]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_4 * (SINT64)s16X[ChOffset + 10]; \ - s32DCTY[6] = (SINT32)(s64Temp >> 16); \ - s32DCTY[10] = (SINT32)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_8_6_10 \ + { \ + s64Temp = (SINT64)WIND_8_SUBBANDS_6_0 * (SINT64)s16X[ChOffset + 6]; \ + s64Temp2 = (SINT64)WIND_8_SUBBANDS_6_0 * (SINT64)s16X[ChOffset + 64 + 10]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_6_1 * (SINT64)s16X[ChOffset + 16 + 6]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_1 * (SINT64)s16X[ChOffset + 48 + 10]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_6_2 * (SINT64)s16X[ChOffset + 32 + 6]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_2 * (SINT64)s16X[ChOffset + 32 + 10]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_6_3 * (SINT64)s16X[ChOffset + 48 + 6]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_3 * (SINT64)s16X[ChOffset + 16 + 10]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_6_4 * (SINT64)s16X[ChOffset + 64 + 6]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_4 * (SINT64)s16X[ChOffset + 10]; \ + s32DCTY[6] = (SINT32)(s64Temp >> 16); \ + s32DCTY[10] = (SINT32)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_8_7_9 \ - { \ - s64Temp = (SINT64)WIND_8_SUBBANDS_7_0 * (SINT64)s16X[ChOffset + 7]; \ - s64Temp2 = (SINT64)WIND_8_SUBBANDS_7_0 * (SINT64)s16X[ChOffset + 64 + 9]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_7_1 * (SINT64)s16X[ChOffset + 16 + 7]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_1 * (SINT64)s16X[ChOffset + 48 + 9]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_7_2 * (SINT64)s16X[ChOffset + 32 + 7]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_2 * (SINT64)s16X[ChOffset + 32 + 9]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_7_3 * (SINT64)s16X[ChOffset + 48 + 7]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_3 * (SINT64)s16X[ChOffset + 16 + 9]; \ - s64Temp += (SINT64)WIND_8_SUBBANDS_7_4 * (SINT64)s16X[ChOffset + 64 + 7]; \ - s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_4 * (SINT64)s16X[ChOffset + 9]; \ - s32DCTY[7] = (SINT32)(s64Temp >> 16); \ - s32DCTY[9] = (SINT32)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_8_7_9 \ + { \ + s64Temp = (SINT64)WIND_8_SUBBANDS_7_0 * (SINT64)s16X[ChOffset + 7]; \ + s64Temp2 = (SINT64)WIND_8_SUBBANDS_7_0 * (SINT64)s16X[ChOffset + 64 + 9]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_7_1 * (SINT64)s16X[ChOffset + 16 + 7]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_1 * (SINT64)s16X[ChOffset + 48 + 9]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_7_2 * (SINT64)s16X[ChOffset + 32 + 7]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_2 * (SINT64)s16X[ChOffset + 32 + 9]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_7_3 * (SINT64)s16X[ChOffset + 48 + 7]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_3 * (SINT64)s16X[ChOffset + 16 + 9]; \ + s64Temp += (SINT64)WIND_8_SUBBANDS_7_4 * (SINT64)s16X[ChOffset + 64 + 7]; \ + s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_4 * (SINT64)s16X[ChOffset + 9]; \ + s32DCTY[7] = (SINT32)(s64Temp >> 16); \ + s32DCTY[9] = (SINT32)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_8_8 \ - { \ - s64Temp = (SINT64)WIND_8_SUBBANDS_8_0 * (SINT64)(s16X[ChOffset + 8] + s16X[ChOffset + 64 + 8]); \ - s64Temp += (SINT64)WIND_8_SUBBANDS_8_1 * (SINT64)(s16X[ChOffset + 16 + 8] + s16X[ChOffset + 48 + 8]); \ - s64Temp += (SINT64)WIND_8_SUBBANDS_8_2 * (SINT64)s16X[ChOffset + 32 + 8]; \ - s32DCTY[8] = (SINT32)(s64Temp >> 16); \ +#define WINDOW_ACCU_8_8 \ + { \ + s64Temp = (SINT64)WIND_8_SUBBANDS_8_0 * (SINT64)(s16X[ChOffset + 8] + s16X[ChOffset + 64 + 8]); \ + s64Temp += (SINT64)WIND_8_SUBBANDS_8_1 * (SINT64)(s16X[ChOffset + 16 + 8] + s16X[ChOffset + 48 + 8]); \ + s64Temp += (SINT64)WIND_8_SUBBANDS_8_2 * (SINT64)s16X[ChOffset + 32 + 8]; \ + s32DCTY[8] = (SINT32)(s64Temp >> 16); \ } -#define WINDOW_ACCU_4_0 \ - { \ - s64Temp = (SINT64)WIND_4_SUBBANDS_0_1 * (SINT64)(s16X[ChOffset + 8] - s16X[ChOffset + 32]); \ - s64Temp += (SINT64)WIND_4_SUBBANDS_0_2 * (SINT64)(s16X[ChOffset + 16] - s16X[ChOffset + 24]); \ - s32DCTY[0] = (SINT32)(s64Temp >> 16); \ +#define WINDOW_ACCU_4_0 \ + { \ + s64Temp = (SINT64)WIND_4_SUBBANDS_0_1 * (SINT64)(s16X[ChOffset + 8] - s16X[ChOffset + 32]); \ + s64Temp += (SINT64)WIND_4_SUBBANDS_0_2 * (SINT64)(s16X[ChOffset + 16] - s16X[ChOffset + 24]); \ + s32DCTY[0] = (SINT32)(s64Temp >> 16); \ } -#define WINDOW_ACCU_4_1_7 \ - { \ - s64Temp = (SINT64)WIND_4_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 1]; \ - s64Temp2 = (SINT64)WIND_4_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 32 + 7]; \ - s64Temp += (SINT64)WIND_4_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 8 + 1]; \ - s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 24 + 7]; \ - s64Temp += (SINT64)WIND_4_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 16 + 1]; \ - s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 16 + 7]; \ - s64Temp += (SINT64)WIND_4_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 24 + 1]; \ - s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 8 + 7]; \ - s64Temp += (SINT64)WIND_4_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 32 + 1]; \ - s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 7]; \ - s32DCTY[1] = (SINT32)(s64Temp >> 16); \ - s32DCTY[7] = (SINT32)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_4_1_7 \ + { \ + s64Temp = (SINT64)WIND_4_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 1]; \ + s64Temp2 = (SINT64)WIND_4_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 32 + 7]; \ + s64Temp += (SINT64)WIND_4_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 8 + 1]; \ + s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 24 + 7]; \ + s64Temp += (SINT64)WIND_4_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 16 + 1]; \ + s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 16 + 7]; \ + s64Temp += (SINT64)WIND_4_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 24 + 1]; \ + s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 8 + 7]; \ + s64Temp += (SINT64)WIND_4_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 32 + 1]; \ + s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 7]; \ + s32DCTY[1] = (SINT32)(s64Temp >> 16); \ + s32DCTY[7] = (SINT32)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_4_2_6 \ - { \ - s64Temp = (SINT64)WIND_4_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 2]; \ - s64Temp2 = (SINT64)WIND_4_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 32 + 6]; \ - s64Temp += (SINT64)WIND_4_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 8 + 2]; \ - s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 24 + 6]; \ - s64Temp += (SINT64)WIND_4_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 16 + 2]; \ - s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 16 + 6]; \ - s64Temp += (SINT64)WIND_4_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 24 + 2]; \ - s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 8 + 6]; \ - s64Temp += (SINT64)WIND_4_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 32 + 2]; \ - s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 6]; \ - s32DCTY[2] = (SINT32)(s64Temp >> 16); \ - s32DCTY[6] = (SINT32)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_4_2_6 \ + { \ + s64Temp = (SINT64)WIND_4_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 2]; \ + s64Temp2 = (SINT64)WIND_4_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 32 + 6]; \ + s64Temp += (SINT64)WIND_4_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 8 + 2]; \ + s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 24 + 6]; \ + s64Temp += (SINT64)WIND_4_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 16 + 2]; \ + s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 16 + 6]; \ + s64Temp += (SINT64)WIND_4_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 24 + 2]; \ + s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 8 + 6]; \ + s64Temp += (SINT64)WIND_4_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 32 + 2]; \ + s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 6]; \ + s32DCTY[2] = (SINT32)(s64Temp >> 16); \ + s32DCTY[6] = (SINT32)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_4_3_5 \ - { \ - s64Temp = (SINT64)WIND_4_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 3]; \ - s64Temp2 = (SINT64)WIND_4_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 32 + 5]; \ - s64Temp += (SINT64)WIND_4_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 8 + 3]; \ - s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 24 + 5]; \ - s64Temp += (SINT64)WIND_4_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 16 + 3]; \ - s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 16 + 5]; \ - s64Temp += (SINT64)WIND_4_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 24 + 3]; \ - s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 8 + 5]; \ - s64Temp += (SINT64)WIND_4_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 32 + 3]; \ - s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 5]; \ - s32DCTY[3] = (SINT32)(s64Temp >> 16); \ - s32DCTY[5] = (SINT32)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_4_3_5 \ + { \ + s64Temp = (SINT64)WIND_4_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 3]; \ + s64Temp2 = (SINT64)WIND_4_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 32 + 5]; \ + s64Temp += (SINT64)WIND_4_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 8 + 3]; \ + s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 24 + 5]; \ + s64Temp += (SINT64)WIND_4_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 16 + 3]; \ + s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 16 + 5]; \ + s64Temp += (SINT64)WIND_4_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 24 + 3]; \ + s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 8 + 5]; \ + s64Temp += (SINT64)WIND_4_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 32 + 3]; \ + s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 5]; \ + s32DCTY[3] = (SINT32)(s64Temp >> 16); \ + s32DCTY[5] = (SINT32)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_4_4 \ - { \ - s64Temp = (SINT64)WIND_4_SUBBANDS_4_0 * (SINT64)(s16X[ChOffset + 4] + s16X[ChOffset + 4 + 32]); \ - s64Temp += (SINT64)WIND_4_SUBBANDS_4_1 * (SINT64)(s16X[ChOffset + 4 + 8] + s16X[ChOffset + 4 + 24]); \ - s64Temp += (SINT64)WIND_4_SUBBANDS_4_2 * (SINT64)s16X[ChOffset + 4 + 16]; \ - s32DCTY[4] = (SINT32)(s64Temp >> 16); \ +#define WINDOW_ACCU_4_4 \ + { \ + s64Temp = (SINT64)WIND_4_SUBBANDS_4_0 * (SINT64)(s16X[ChOffset + 4] + s16X[ChOffset + 4 + 32]); \ + s64Temp += (SINT64)WIND_4_SUBBANDS_4_1 * (SINT64)(s16X[ChOffset + 4 + 8] + s16X[ChOffset + 4 + 24]); \ + s64Temp += (SINT64)WIND_4_SUBBANDS_4_2 * (SINT64)s16X[ChOffset + 4 + 16]; \ + s32DCTY[4] = (SINT32)(s64Temp >> 16); \ } #else /* SBC_IS_64_MULT_IN_WINDOW_ACCU == FALSE */ -#define WINDOW_ACCU_8_0 \ - { \ - s32Temp = (SINT32)WIND_8_SUBBANDS_0_1 * (SINT32)(s16X[ChOffset + 16] - s16X[ChOffset + 64]); \ - s32Temp += (SINT32)WIND_8_SUBBANDS_0_2 * (SINT32)(s16X[ChOffset + 32] - s16X[ChOffset + 48]); \ - s32DCTY[0] = (SINT32)s32Temp; \ +#define WINDOW_ACCU_8_0 \ + { \ + s32Temp = (SINT32)WIND_8_SUBBANDS_0_1 * (SINT32)(s16X[ChOffset + 16] - s16X[ChOffset + 64]); \ + s32Temp += (SINT32)WIND_8_SUBBANDS_0_2 * (SINT32)(s16X[ChOffset + 32] - s16X[ChOffset + 48]); \ + s32DCTY[0] = (SINT32)s32Temp; \ } -#define WINDOW_ACCU_8_1_15 \ - { \ - s32Temp = (SINT32)WIND_8_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 1]; \ - s32Temp2 = (SINT32)WIND_8_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 64 + 15]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 16 + 1]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 48 + 15]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 32 + 1]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 32 + 15]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 48 + 1]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 16 + 15]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 64 + 1]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 15]; \ - s32DCTY[1] = (SINT32)s32Temp; \ - s32DCTY[15] = (SINT32)s32Temp2; \ +#define WINDOW_ACCU_8_1_15 \ + { \ + s32Temp = (SINT32)WIND_8_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 1]; \ + s32Temp2 = (SINT32)WIND_8_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 64 + 15]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 16 + 1]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 48 + 15]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 32 + 1]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 32 + 15]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 48 + 1]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 16 + 15]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 64 + 1]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 15]; \ + s32DCTY[1] = (SINT32)s32Temp; \ + s32DCTY[15] = (SINT32)s32Temp2; \ } -#define WINDOW_ACCU_8_2_14 \ - { \ - s32Temp = (SINT32)WIND_8_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 2]; \ - s32Temp2 = (SINT32)WIND_8_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 64 + 14]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 16 + 2]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 48 + 14]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 32 + 2]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 32 + 14]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 48 + 2]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 16 + 14]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 64 + 2]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 14]; \ - s32DCTY[2] = (SINT32)s32Temp; \ - s32DCTY[14] = (SINT32)s32Temp2; \ +#define WINDOW_ACCU_8_2_14 \ + { \ + s32Temp = (SINT32)WIND_8_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 2]; \ + s32Temp2 = (SINT32)WIND_8_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 64 + 14]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 16 + 2]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 48 + 14]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 32 + 2]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 32 + 14]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 48 + 2]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 16 + 14]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 64 + 2]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 14]; \ + s32DCTY[2] = (SINT32)s32Temp; \ + s32DCTY[14] = (SINT32)s32Temp2; \ } -#define WINDOW_ACCU_8_3_13 \ - { \ - s32Temp = (SINT32)WIND_8_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 3]; \ - s32Temp2 = (SINT32)WIND_8_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 64 + 13]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 16 + 3]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 48 + 13]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 32 + 3]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 32 + 13]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 48 + 3]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 16 + 13]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 64 + 3]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 13]; \ - s32DCTY[3] = (SINT32)s32Temp; \ - s32DCTY[13] = (SINT32)s32Temp2; \ +#define WINDOW_ACCU_8_3_13 \ + { \ + s32Temp = (SINT32)WIND_8_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 3]; \ + s32Temp2 = (SINT32)WIND_8_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 64 + 13]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 16 + 3]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 48 + 13]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 32 + 3]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 32 + 13]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 48 + 3]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 16 + 13]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 64 + 3]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 13]; \ + s32DCTY[3] = (SINT32)s32Temp; \ + s32DCTY[13] = (SINT32)s32Temp2; \ } -#define WINDOW_ACCU_8_4_12 \ - { \ - s32Temp = (SINT32)WIND_8_SUBBANDS_4_0 * (SINT32)s16X[ChOffset + 4]; \ - s32Temp2 = (SINT32)WIND_8_SUBBANDS_4_0 * (SINT32)s16X[ChOffset + 64 + 12]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_4_1 * (SINT32)s16X[ChOffset + 16 + 4]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_1 * (SINT32)s16X[ChOffset + 48 + 12]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_4_2 * (SINT32)s16X[ChOffset + 32 + 4]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_2 * (SINT32)s16X[ChOffset + 32 + 12]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_4_3 * (SINT32)s16X[ChOffset + 48 + 4]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_3 * (SINT32)s16X[ChOffset + 16 + 12]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_4_4 * (SINT32)s16X[ChOffset + 64 + 4]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_4 * (SINT32)s16X[ChOffset + 12]; \ - s32DCTY[4] = (SINT32)s32Temp; \ - s32DCTY[12] = (SINT32)s32Temp2; \ +#define WINDOW_ACCU_8_4_12 \ + { \ + s32Temp = (SINT32)WIND_8_SUBBANDS_4_0 * (SINT32)s16X[ChOffset + 4]; \ + s32Temp2 = (SINT32)WIND_8_SUBBANDS_4_0 * (SINT32)s16X[ChOffset + 64 + 12]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_4_1 * (SINT32)s16X[ChOffset + 16 + 4]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_1 * (SINT32)s16X[ChOffset + 48 + 12]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_4_2 * (SINT32)s16X[ChOffset + 32 + 4]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_2 * (SINT32)s16X[ChOffset + 32 + 12]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_4_3 * (SINT32)s16X[ChOffset + 48 + 4]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_3 * (SINT32)s16X[ChOffset + 16 + 12]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_4_4 * (SINT32)s16X[ChOffset + 64 + 4]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_4 * (SINT32)s16X[ChOffset + 12]; \ + s32DCTY[4] = (SINT32)s32Temp; \ + s32DCTY[12] = (SINT32)s32Temp2; \ } -#define WINDOW_ACCU_8_5_11 \ - { \ - s32Temp = (SINT32)WIND_8_SUBBANDS_5_0 * (SINT32)s16X[ChOffset + 5]; \ - s32Temp2 = (SINT32)WIND_8_SUBBANDS_5_0 * (SINT32)s16X[ChOffset + 64 + 11]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_5_1 * (SINT32)s16X[ChOffset + 16 + 5]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_1 * (SINT32)s16X[ChOffset + 48 + 11]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_5_2 * (SINT32)s16X[ChOffset + 32 + 5]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_2 * (SINT32)s16X[ChOffset + 32 + 11]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_5_3 * (SINT32)s16X[ChOffset + 48 + 5]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_3 * (SINT32)s16X[ChOffset + 16 + 11]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_5_4 * (SINT32)s16X[ChOffset + 64 + 5]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_4 * (SINT32)s16X[ChOffset + 11]; \ - s32DCTY[5] = (SINT32)s32Temp; \ - s32DCTY[11] = (SINT32)s32Temp2; \ +#define WINDOW_ACCU_8_5_11 \ + { \ + s32Temp = (SINT32)WIND_8_SUBBANDS_5_0 * (SINT32)s16X[ChOffset + 5]; \ + s32Temp2 = (SINT32)WIND_8_SUBBANDS_5_0 * (SINT32)s16X[ChOffset + 64 + 11]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_5_1 * (SINT32)s16X[ChOffset + 16 + 5]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_1 * (SINT32)s16X[ChOffset + 48 + 11]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_5_2 * (SINT32)s16X[ChOffset + 32 + 5]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_2 * (SINT32)s16X[ChOffset + 32 + 11]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_5_3 * (SINT32)s16X[ChOffset + 48 + 5]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_3 * (SINT32)s16X[ChOffset + 16 + 11]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_5_4 * (SINT32)s16X[ChOffset + 64 + 5]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_4 * (SINT32)s16X[ChOffset + 11]; \ + s32DCTY[5] = (SINT32)s32Temp; \ + s32DCTY[11] = (SINT32)s32Temp2; \ } -#define WINDOW_ACCU_8_6_10 \ - { \ - s32Temp = (SINT32)WIND_8_SUBBANDS_6_0 * (SINT32)s16X[ChOffset + 6]; \ - s32Temp2 = (SINT32)WIND_8_SUBBANDS_6_0 * (SINT32)s16X[ChOffset + 64 + 10]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_6_1 * (SINT32)s16X[ChOffset + 16 + 6]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_1 * (SINT32)s16X[ChOffset + 48 + 10]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_6_2 * (SINT32)s16X[ChOffset + 32 + 6]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_2 * (SINT32)s16X[ChOffset + 32 + 10]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_6_3 * (SINT32)s16X[ChOffset + 48 + 6]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_3 * (SINT32)s16X[ChOffset + 16 + 10]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_6_4 * (SINT32)s16X[ChOffset + 64 + 6]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_4 * (SINT32)s16X[ChOffset + 10]; \ - s32DCTY[6] = (SINT32)s32Temp; \ - s32DCTY[10] = (SINT32)s32Temp2; \ +#define WINDOW_ACCU_8_6_10 \ + { \ + s32Temp = (SINT32)WIND_8_SUBBANDS_6_0 * (SINT32)s16X[ChOffset + 6]; \ + s32Temp2 = (SINT32)WIND_8_SUBBANDS_6_0 * (SINT32)s16X[ChOffset + 64 + 10]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_6_1 * (SINT32)s16X[ChOffset + 16 + 6]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_1 * (SINT32)s16X[ChOffset + 48 + 10]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_6_2 * (SINT32)s16X[ChOffset + 32 + 6]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_2 * (SINT32)s16X[ChOffset + 32 + 10]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_6_3 * (SINT32)s16X[ChOffset + 48 + 6]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_3 * (SINT32)s16X[ChOffset + 16 + 10]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_6_4 * (SINT32)s16X[ChOffset + 64 + 6]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_4 * (SINT32)s16X[ChOffset + 10]; \ + s32DCTY[6] = (SINT32)s32Temp; \ + s32DCTY[10] = (SINT32)s32Temp2; \ } -#define WINDOW_ACCU_8_7_9 \ - { \ - s32Temp = (SINT32)WIND_8_SUBBANDS_7_0 * (SINT32)s16X[ChOffset + 7]; \ - s32Temp2 = (SINT32)WIND_8_SUBBANDS_7_0 * (SINT32)s16X[ChOffset + 64 + 9]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_7_1 * (SINT32)s16X[ChOffset + 16 + 7]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_1 * (SINT32)s16X[ChOffset + 48 + 9]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_7_2 * (SINT32)s16X[ChOffset + 32 + 7]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_2 * (SINT32)s16X[ChOffset + 32 + 9]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_7_3 * (SINT32)s16X[ChOffset + 48 + 7]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_3 * (SINT32)s16X[ChOffset + 16 + 9]; \ - s32Temp += (SINT32)WIND_8_SUBBANDS_7_4 * (SINT32)s16X[ChOffset + 64 + 7]; \ - s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_4 * (SINT32)s16X[ChOffset + 9]; \ - s32DCTY[7] = (SINT32)s32Temp; \ - s32DCTY[9] = (SINT32)s32Temp2; \ +#define WINDOW_ACCU_8_7_9 \ + { \ + s32Temp = (SINT32)WIND_8_SUBBANDS_7_0 * (SINT32)s16X[ChOffset + 7]; \ + s32Temp2 = (SINT32)WIND_8_SUBBANDS_7_0 * (SINT32)s16X[ChOffset + 64 + 9]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_7_1 * (SINT32)s16X[ChOffset + 16 + 7]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_1 * (SINT32)s16X[ChOffset + 48 + 9]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_7_2 * (SINT32)s16X[ChOffset + 32 + 7]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_2 * (SINT32)s16X[ChOffset + 32 + 9]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_7_3 * (SINT32)s16X[ChOffset + 48 + 7]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_3 * (SINT32)s16X[ChOffset + 16 + 9]; \ + s32Temp += (SINT32)WIND_8_SUBBANDS_7_4 * (SINT32)s16X[ChOffset + 64 + 7]; \ + s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_4 * (SINT32)s16X[ChOffset + 9]; \ + s32DCTY[7] = (SINT32)s32Temp; \ + s32DCTY[9] = (SINT32)s32Temp2; \ } -#define WINDOW_ACCU_8_8 \ - { \ - s32Temp = (SINT32)WIND_8_SUBBANDS_8_0 * (SINT32)(s16X[ChOffset + 8] + s16X[ChOffset + 64 + 8]); \ - s32Temp += (SINT32)WIND_8_SUBBANDS_8_1 * (SINT32)(s16X[ChOffset + 16 + 8] + s16X[ChOffset + 48 + 8]); \ - s32Temp += (SINT32)WIND_8_SUBBANDS_8_2 * (SINT32)s16X[ChOffset + 32 + 8]; \ - s32DCTY[8] = (SINT32)s32Temp; \ +#define WINDOW_ACCU_8_8 \ + { \ + s32Temp = (SINT32)WIND_8_SUBBANDS_8_0 * (SINT32)(s16X[ChOffset + 8] + s16X[ChOffset + 64 + 8]); \ + s32Temp += (SINT32)WIND_8_SUBBANDS_8_1 * (SINT32)(s16X[ChOffset + 16 + 8] + s16X[ChOffset + 48 + 8]); \ + s32Temp += (SINT32)WIND_8_SUBBANDS_8_2 * (SINT32)s16X[ChOffset + 32 + 8]; \ + s32DCTY[8] = (SINT32)s32Temp; \ } -#define WINDOW_ACCU_4_0 \ - { \ - s32Temp = (SINT32)WIND_4_SUBBANDS_0_1 * (SINT32)(s16X[ChOffset + 8] - s16X[ChOffset + 32]); \ - s32Temp += (SINT32)WIND_4_SUBBANDS_0_2 * (SINT32)(s16X[ChOffset + 16] - s16X[ChOffset + 24]); \ - s32DCTY[0] = (SINT32)(s32Temp); \ +#define WINDOW_ACCU_4_0 \ + { \ + s32Temp = (SINT32)WIND_4_SUBBANDS_0_1 * (SINT32)(s16X[ChOffset + 8] - s16X[ChOffset + 32]); \ + s32Temp += (SINT32)WIND_4_SUBBANDS_0_2 * (SINT32)(s16X[ChOffset + 16] - s16X[ChOffset + 24]); \ + s32DCTY[0] = (SINT32)(s32Temp); \ } -#define WINDOW_ACCU_4_1_7 \ - { \ - s32Temp = (SINT32)WIND_4_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 1]; \ - s32Temp2 = (SINT32)WIND_4_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 32 + 7]; \ - s32Temp += (SINT32)WIND_4_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 8 + 1]; \ - s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 24 + 7]; \ - s32Temp += (SINT32)WIND_4_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 16 + 1]; \ - s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 16 + 7]; \ - s32Temp += (SINT32)WIND_4_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 24 + 1]; \ - s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 8 + 7]; \ - s32Temp += (SINT32)WIND_4_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 32 + 1]; \ - s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 7]; \ - s32DCTY[1] = (SINT32)(s32Temp); \ - s32DCTY[7] = (SINT32)(s32Temp2); \ +#define WINDOW_ACCU_4_1_7 \ + { \ + s32Temp = (SINT32)WIND_4_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 1]; \ + s32Temp2 = (SINT32)WIND_4_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 32 + 7]; \ + s32Temp += (SINT32)WIND_4_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 8 + 1]; \ + s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 24 + 7]; \ + s32Temp += (SINT32)WIND_4_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 16 + 1]; \ + s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 16 + 7]; \ + s32Temp += (SINT32)WIND_4_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 24 + 1]; \ + s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 8 + 7]; \ + s32Temp += (SINT32)WIND_4_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 32 + 1]; \ + s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 7]; \ + s32DCTY[1] = (SINT32)(s32Temp); \ + s32DCTY[7] = (SINT32)(s32Temp2); \ } -#define WINDOW_ACCU_4_2_6 \ - { \ - s32Temp = (SINT32)WIND_4_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 2]; \ - s32Temp2 = (SINT32)WIND_4_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 32 + 6]; \ - s32Temp += (SINT32)WIND_4_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 8 + 2]; \ - s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 24 + 6]; \ - s32Temp += (SINT32)WIND_4_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 16 + 2]; \ - s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 16 + 6]; \ - s32Temp += (SINT32)WIND_4_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 24 + 2]; \ - s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 8 + 6]; \ - s32Temp += (SINT32)WIND_4_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 32 + 2]; \ - s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 6]; \ - s32DCTY[2] = (SINT32)(s32Temp); \ - s32DCTY[6] = (SINT32)(s32Temp2); \ +#define WINDOW_ACCU_4_2_6 \ + { \ + s32Temp = (SINT32)WIND_4_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 2]; \ + s32Temp2 = (SINT32)WIND_4_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 32 + 6]; \ + s32Temp += (SINT32)WIND_4_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 8 + 2]; \ + s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 24 + 6]; \ + s32Temp += (SINT32)WIND_4_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 16 + 2]; \ + s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 16 + 6]; \ + s32Temp += (SINT32)WIND_4_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 24 + 2]; \ + s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 8 + 6]; \ + s32Temp += (SINT32)WIND_4_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 32 + 2]; \ + s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 6]; \ + s32DCTY[2] = (SINT32)(s32Temp); \ + s32DCTY[6] = (SINT32)(s32Temp2); \ } -#define WINDOW_ACCU_4_3_5 \ - { \ - s32Temp = (SINT32)WIND_4_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 3]; \ - s32Temp2 = (SINT32)WIND_4_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 32 + 5]; \ - s32Temp += (SINT32)WIND_4_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 8 + 3]; \ - s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 24 + 5]; \ - s32Temp += (SINT32)WIND_4_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 16 + 3]; \ - s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 16 + 5]; \ - s32Temp += (SINT32)WIND_4_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 24 + 3]; \ - s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 8 + 5]; \ - s32Temp += (SINT32)WIND_4_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 32 + 3]; \ - s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 5]; \ - s32DCTY[3] = (SINT32)(s32Temp); \ - s32DCTY[5] = (SINT32)(s32Temp2); \ +#define WINDOW_ACCU_4_3_5 \ + { \ + s32Temp = (SINT32)WIND_4_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 3]; \ + s32Temp2 = (SINT32)WIND_4_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 32 + 5]; \ + s32Temp += (SINT32)WIND_4_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 8 + 3]; \ + s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 24 + 5]; \ + s32Temp += (SINT32)WIND_4_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 16 + 3]; \ + s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 16 + 5]; \ + s32Temp += (SINT32)WIND_4_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 24 + 3]; \ + s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 8 + 5]; \ + s32Temp += (SINT32)WIND_4_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 32 + 3]; \ + s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 5]; \ + s32DCTY[3] = (SINT32)(s32Temp); \ + s32DCTY[5] = (SINT32)(s32Temp2); \ } -#define WINDOW_ACCU_4_4 \ - { \ - s32Temp = (SINT32)WIND_4_SUBBANDS_4_0 * (SINT32)(s16X[ChOffset + 4] + s16X[ChOffset + 4 + 32]); \ - s32Temp += (SINT32)WIND_4_SUBBANDS_4_1 * (SINT32)(s16X[ChOffset + 4 + 8] + s16X[ChOffset + 4 + 24]); \ - s32Temp += (SINT32)WIND_4_SUBBANDS_4_2 * (SINT32)s16X[ChOffset + 4 + 16]; \ - s32DCTY[4] = (SINT32)(s32Temp); \ +#define WINDOW_ACCU_4_4 \ + { \ + s32Temp = (SINT32)WIND_4_SUBBANDS_4_0 * (SINT32)(s16X[ChOffset + 4] + s16X[ChOffset + 4 + 32]); \ + s32Temp += (SINT32)WIND_4_SUBBANDS_4_1 * (SINT32)(s16X[ChOffset + 4 + 8] + s16X[ChOffset + 4 + 24]); \ + s32Temp += (SINT32)WIND_4_SUBBANDS_4_2 * (SINT32)s16X[ChOffset + 4 + 16]; \ + s32DCTY[4] = (SINT32)(s32Temp); \ } #endif -#define WINDOW_PARTIAL_4 \ - { \ - WINDOW_ACCU_4_0; \ - WINDOW_ACCU_4_1_7; \ - WINDOW_ACCU_4_2_6; \ - WINDOW_ACCU_4_3_5; \ - WINDOW_ACCU_4_4; \ +#define WINDOW_PARTIAL_4 \ + { \ + WINDOW_ACCU_4_0; \ + WINDOW_ACCU_4_1_7; \ + WINDOW_ACCU_4_2_6; \ + WINDOW_ACCU_4_3_5; \ + WINDOW_ACCU_4_4; \ } -#define WINDOW_PARTIAL_8 \ - { \ - WINDOW_ACCU_8_0; \ - WINDOW_ACCU_8_1_15; \ - WINDOW_ACCU_8_2_14; \ - WINDOW_ACCU_8_3_13; \ - WINDOW_ACCU_8_4_12; \ - WINDOW_ACCU_8_5_11; \ - WINDOW_ACCU_8_6_10; \ - WINDOW_ACCU_8_7_9; \ - WINDOW_ACCU_8_8; \ +#define WINDOW_PARTIAL_8 \ + { \ + WINDOW_ACCU_8_0; \ + WINDOW_ACCU_8_1_15; \ + WINDOW_ACCU_8_2_14; \ + WINDOW_ACCU_8_3_13; \ + WINDOW_ACCU_8_4_12; \ + WINDOW_ACCU_8_5_11; \ + WINDOW_ACCU_8_6_10; \ + WINDOW_ACCU_8_7_9; \ + WINDOW_ACCU_8_8; \ } #else #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE) -#define WINDOW_ACCU_4(i) \ - { \ - s64Temp = ((SINT64)gas32CoeffFor4SBs[i] * (SINT64)s16X[ChOffset + i]); \ - s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 8)] * (SINT64)s16X[ChOffset + i + 8]); \ - s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 16)] * (SINT64)s16X[ChOffset + i + 16]); \ - s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 24)] * (SINT64)s16X[ChOffset + i + 24]); \ - s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 32)] * (SINT64)s16X[ChOffset + i + 32]); \ - s32DCTY[i] = (SINT32)(s64Temp >> 16); \ - /*BT_WARN("s32DCTY4: 0x%x \n", s32DCTY[i]);*/ \ +#define WINDOW_ACCU_4(i) \ + { \ + s64Temp = ((SINT64)gas32CoeffFor4SBs[i] * (SINT64)s16X[ChOffset + i]); \ + s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 8)] * (SINT64)s16X[ChOffset + i + 8]); \ + s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 16)] * (SINT64)s16X[ChOffset + i + 16]); \ + s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 24)] * (SINT64)s16X[ChOffset + i + 24]); \ + s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 32)] * (SINT64)s16X[ChOffset + i + 32]); \ + s32DCTY[i] = (SINT32)(s64Temp >> 16); \ + /*BT_WARN("s32DCTY4: 0x%x \n", s32DCTY[i]);*/ \ } #else -#define WINDOW_ACCU_4(i) \ - { \ - s32DCTY[i] = (gas32CoeffFor4SBs[i * 2] * s16X[ChOffset + i]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[(i * 2) + 1]) * s16X[ChOffset + i]) >> 16); \ - s32DCTY[i] += (gas32CoeffFor4SBs[(i + 8) * 2] * s16X[ChOffset + i + 8]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 8) * 2) + 1]) * s16X[ChOffset + i + 8]) >> 16); \ - s32DCTY[i] += (gas32CoeffFor4SBs[(i + 16) * 2] * s16X[ChOffset + i + 16]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 16) * 2) + 1]) * s16X[ChOffset + i + 16]) >> 16); \ - s32DCTY[i] += (gas32CoeffFor4SBs[(i + 24) * 2] * s16X[ChOffset + i + 24]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 24) * 2) + 1]) * s16X[ChOffset + i + 24]) >> 16); \ - s32DCTY[i] += (gas32CoeffFor4SBs[(i + 32) * 2] * s16X[ChOffset + i + 32]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 32) * 2) + 1]) * s16X[ChOffset + i + 32]) >> 16); \ +#define WINDOW_ACCU_4(i) \ + { \ + s32DCTY[i] = (gas32CoeffFor4SBs[i * 2] * s16X[ChOffset + i]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[(i * 2) + 1]) * s16X[ChOffset + i]) >> 16); \ + s32DCTY[i] += (gas32CoeffFor4SBs[(i + 8) * 2] * s16X[ChOffset + i + 8]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 8) * 2) + 1]) * s16X[ChOffset + i + 8]) >> 16); \ + s32DCTY[i] += (gas32CoeffFor4SBs[(i + 16) * 2] * s16X[ChOffset + i + 16]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 16) * 2) + 1]) * s16X[ChOffset + i + 16]) >> 16); \ + s32DCTY[i] += (gas32CoeffFor4SBs[(i + 24) * 2] * s16X[ChOffset + i + 24]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 24) * 2) + 1]) * s16X[ChOffset + i + 24]) >> 16); \ + s32DCTY[i] += (gas32CoeffFor4SBs[(i + 32) * 2] * s16X[ChOffset + i + 32]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 32) * 2) + 1]) * s16X[ChOffset + i + 32]) >> 16); \ } #endif -#define WINDOW_PARTIAL_4 \ - { \ - WINDOW_ACCU_4(0); \ - WINDOW_ACCU_4(1); \ - WINDOW_ACCU_4(2); \ - WINDOW_ACCU_4(3); \ - WINDOW_ACCU_4(4); \ - WINDOW_ACCU_4(5); \ - WINDOW_ACCU_4(6); \ - WINDOW_ACCU_4(7); \ +#define WINDOW_PARTIAL_4 \ + { \ + WINDOW_ACCU_4(0); \ + WINDOW_ACCU_4(1); \ + WINDOW_ACCU_4(2); \ + WINDOW_ACCU_4(3); \ + WINDOW_ACCU_4(4); \ + WINDOW_ACCU_4(5); \ + WINDOW_ACCU_4(6); \ + WINDOW_ACCU_4(7); \ } #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE) -#define WINDOW_ACCU_8(i) \ - { \ - s64Temp = ((((SINT64)gas32CoeffFor8SBs[i] * (SINT64)s16X[ChOffset + i]))); \ - s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 16)] * (SINT64)s16X[ChOffset + i + 16]))); \ - s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 32)] * (SINT64)s16X[ChOffset + i + 32]))); \ - s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 48)] * (SINT64)s16X[ChOffset + i + 48]))); \ - s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 64)] * (SINT64)s16X[ChOffset + i + 64]))); \ - /*BT_WARN("s32DCTY8: %d= 0x%x * %d\n", s32DCTY[i], gas32CoeffFor8SBs[i], s16X[ChOffset+i]);*/ \ - s32DCTY[i] = (SINT32)(s64Temp >> 16); \ +#define WINDOW_ACCU_8(i) \ + { \ + s64Temp = ((((SINT64)gas32CoeffFor8SBs[i] * (SINT64)s16X[ChOffset + i]))); \ + s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 16)] * (SINT64)s16X[ChOffset + i + 16]))); \ + s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 32)] * (SINT64)s16X[ChOffset + i + 32]))); \ + s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 48)] * (SINT64)s16X[ChOffset + i + 48]))); \ + s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 64)] * (SINT64)s16X[ChOffset + i + 64]))); \ + /*BT_WARN("s32DCTY8: %d= 0x%x * %d\n", s32DCTY[i], gas32CoeffFor8SBs[i], s16X[ChOffset+i]);*/ \ + s32DCTY[i] = (SINT32)(s64Temp >> 16); \ } #else -#define WINDOW_ACCU_8(i) \ - { \ - s32DCTY[i] = (gas32CoeffFor8SBs[i * 2] * s16X[ChOffset + i]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[(i * 2) + 1]) * s16X[ChOffset + i]) >> 16); \ - s32DCTY[i] += (gas32CoeffFor8SBs[(i + 16) * 2] * s16X[ChOffset + i + 16]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 16) * 2) + 1]) * s16X[ChOffset + i + 16]) >> 16); \ - s32DCTY[i] += (gas32CoeffFor8SBs[(i + 32) * 2] * s16X[ChOffset + i + 32]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 32) * 2) + 1]) * s16X[ChOffset + i + 32]) >> 16); \ - s32DCTY[i] += (gas32CoeffFor8SBs[(i + 48) * 2] * s16X[ChOffset + i + 48]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 48) * 2) + 1]) * s16X[ChOffset + i + 48]) >> 16); \ - s32DCTY[i] += (gas32CoeffFor8SBs[(i + 64) * 2] * s16X[ChOffset + i + 64]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 64) * 2) + 1]) * s16X[ChOffset + i + 64]) >> 16); \ - /*BT_WARN("s32DCTY8: %d = 0x%4x%4x * %d\n", s32DCTY[i], gas32CoeffFor8SBs[i * 2], (gas32CoeffFor8SBs[(i * 2) + 1]), s16X[ChOffset+i]);*/ \ - /*s32DCTY[i]=(SINT32)(s64Temp>>16);*/ \ +#define WINDOW_ACCU_8(i) \ + { \ + s32DCTY[i] = (gas32CoeffFor8SBs[i * 2] * s16X[ChOffset + i]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[(i * 2) + 1]) * s16X[ChOffset + i]) >> 16); \ + s32DCTY[i] += (gas32CoeffFor8SBs[(i + 16) * 2] * s16X[ChOffset + i + 16]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 16) * 2) + 1]) * s16X[ChOffset + i + 16]) >> 16); \ + s32DCTY[i] += (gas32CoeffFor8SBs[(i + 32) * 2] * s16X[ChOffset + i + 32]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 32) * 2) + 1]) * s16X[ChOffset + i + 32]) >> 16); \ + s32DCTY[i] += (gas32CoeffFor8SBs[(i + 48) * 2] * s16X[ChOffset + i + 48]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 48) * 2) + 1]) * s16X[ChOffset + i + 48]) >> 16); \ + s32DCTY[i] += (gas32CoeffFor8SBs[(i + 64) * 2] * s16X[ChOffset + i + 64]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 64) * 2) + 1]) * s16X[ChOffset + i + 64]) >> 16); \ + /*BT_WARN("s32DCTY8: %d = 0x%4x%4x * %d\n", s32DCTY[i], gas32CoeffFor8SBs[i * 2], (gas32CoeffFor8SBs[(i * 2) + 1]), s16X[ChOffset+i]);*/ \ + /*s32DCTY[i]=(SINT32)(s64Temp>>16);*/ \ } #endif -#define WINDOW_PARTIAL_8 \ - { \ - WINDOW_ACCU_8(0); \ - WINDOW_ACCU_8(1); \ - WINDOW_ACCU_8(2); \ - WINDOW_ACCU_8(3); \ - WINDOW_ACCU_8(4); \ - WINDOW_ACCU_8(5); \ - WINDOW_ACCU_8(6); \ - WINDOW_ACCU_8(7); \ - WINDOW_ACCU_8(8); \ - WINDOW_ACCU_8(9); \ - WINDOW_ACCU_8(10); \ - WINDOW_ACCU_8(11); \ - WINDOW_ACCU_8(12); \ - WINDOW_ACCU_8(13); \ - WINDOW_ACCU_8(14); \ - WINDOW_ACCU_8(15); \ +#define WINDOW_PARTIAL_8 \ + { \ + WINDOW_ACCU_8(0); \ + WINDOW_ACCU_8(1); \ + WINDOW_ACCU_8(2); \ + WINDOW_ACCU_8(3); \ + WINDOW_ACCU_8(4); \ + WINDOW_ACCU_8(5); \ + WINDOW_ACCU_8(6); \ + WINDOW_ACCU_8(7); \ + WINDOW_ACCU_8(8); \ + WINDOW_ACCU_8(9); \ + WINDOW_ACCU_8(10); \ + WINDOW_ACCU_8(11); \ + WINDOW_ACCU_8(12); \ + WINDOW_ACCU_8(13); \ + WINDOW_ACCU_8(14); \ + WINDOW_ACCU_8(15); \ } #endif #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct_coeffs.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct_coeffs.c index 30894fca6d..2cec78cfff 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct_coeffs.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct_coeffs.c @@ -42,26 +42,26 @@ const SINT16 gas16AnalDCTcoeff4[] = {(SINT16)(0.7071 * 32768), (SINT16)(0.9239 (SINT16)(0.7071 * 32768), (SINT16)(-0.3827 * 32768), (SINT16)(-0.0000 * 32768), (SINT16)(0.3827 * 32768)}; /*DCT coeff for 8 sub-band case.*/ -const SINT16 gas16AnalDCTcoeff8[] - = {(SINT16)(0.7071 * 32768), (SINT16)(0.8315 * 32768), (SINT16)(0.9239 * 32768), (SINT16)(0.9808 * 32768), (SINT16)(1.0000 * 32767), (SINT16)(0.9808 * 32768), (SINT16)(0.9239 * 32768), - (SINT16)(0.8315 * 32768), (SINT16)(0.7071 * 32768), (SINT16)(0.5556 * 32768), (SINT16)(0.3827 * 32768), (SINT16)(0.1951 * 32768), (SINT16)(0.0000 * 32768), (SINT16)(-0.1951 * 32768), - (SINT16)(-0.3827 * 32768), (SINT16)(-0.5556 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(0.3827 * 32768), (SINT16)(0.8315 * 32768), (SINT16)(1.0000 * 32767), - (SINT16)(0.8315 * 32768), (SINT16)(0.3827 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(-0.9808 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(-0.5556 * 32768), - (SINT16)(-0.0000 * 32768), (SINT16)(0.5556 * 32768), (SINT16)(0.9239 * 32768), (SINT16)(0.9808 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(-0.9808 * 32768), (SINT16)(-0.3827 * 32768), - (SINT16)(0.5556 * 32768), (SINT16)(1.0000 * 32767), (SINT16)(0.5556 * 32768), (SINT16)(-0.3827 * 32768), (SINT16)(-0.9808 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(0.1951 * 32768), - (SINT16)(0.9239 * 32768), (SINT16)(0.8315 * 32768), (SINT16)(0.0000 * 32768), (SINT16)(-0.8315 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(0.7071 * 32768), - (SINT16)(-0.5556 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(0.1951 * 32768), (SINT16)(1.0000 * 32767), (SINT16)(0.1951 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(-0.5556 * 32768), - (SINT16)(0.7071 * 32768), (SINT16)(0.8315 * 32768), (SINT16)(-0.3827 * 32768), (SINT16)(-0.9808 * 32768), (SINT16)(-0.0000 * 32768), (SINT16)(0.9808 * 32768), (SINT16)(0.3827 * 32768), - (SINT16)(-0.8315 * 32768), (SINT16)(0.7071 * 32768), (SINT16)(0.5556 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(1.0000 * 32767), (SINT16)(-0.1951 * 32768), - (SINT16)(-0.9239 * 32768), (SINT16)(0.5556 * 32768), (SINT16)(0.7071 * 32768), (SINT16)(-0.8315 * 32768), (SINT16)(-0.3827 * 32768), (SINT16)(0.9808 * 32768), (SINT16)(0.0000 * 32768), - (SINT16)(-0.9808 * 32768), (SINT16)(0.3827 * 32768), (SINT16)(0.8315 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(0.9808 * 32768), (SINT16)(-0.3827 * 32768), (SINT16)(-0.5556 * 32768), - (SINT16)(1.0000 * 32767), (SINT16)(-0.5556 * 32768), (SINT16)(-0.3827 * 32768), (SINT16)(0.9808 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(0.9239 * 32768), - (SINT16)(-0.8315 * 32768), (SINT16)(-0.0000 * 32768), (SINT16)(0.8315 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(0.1951 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(0.1951 * 32768), - (SINT16)(0.3827 * 32768), (SINT16)(-0.8315 * 32768), (SINT16)(1.0000 * 32767), (SINT16)(-0.8315 * 32768), (SINT16)(0.3827 * 32768), (SINT16)(0.1951 * 32768), (SINT16)(-0.7071 * 32768), - (SINT16)(0.9808 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(0.5556 * 32768), (SINT16)(-0.0000 * 32768), (SINT16)(-0.5556 * 32768), (SINT16)(0.9239 * 32768), (SINT16)(-0.9808 * 32768), - (SINT16)(0.7071 * 32768), (SINT16)(-0.8315 * 32768), (SINT16)(0.9239 * 32768), (SINT16)(-0.9808 * 32768), (SINT16)(1.0000 * 32767), (SINT16)(-0.9808 * 32768), (SINT16)(0.9239 * 32768), - (SINT16)(-0.8315 * 32768), (SINT16)(0.7071 * 32768), (SINT16)(-0.5556 * 32768), (SINT16)(0.3827 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(-0.0000 * 32768), (SINT16)(0.1951 * 32768), - (SINT16)(-0.3827 * 32768), (SINT16)(0.5556 * 32768)}; +const SINT16 gas16AnalDCTcoeff8[] = { + (SINT16)(0.7071 * 32768), (SINT16)(0.8315 * 32768), (SINT16)(0.9239 * 32768), (SINT16)(0.9808 * 32768), (SINT16)(1.0000 * 32767), (SINT16)(0.9808 * 32768), (SINT16)(0.9239 * 32768), + (SINT16)(0.8315 * 32768), (SINT16)(0.7071 * 32768), (SINT16)(0.5556 * 32768), (SINT16)(0.3827 * 32768), (SINT16)(0.1951 * 32768), (SINT16)(0.0000 * 32768), (SINT16)(-0.1951 * 32768), + (SINT16)(-0.3827 * 32768), (SINT16)(-0.5556 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(0.3827 * 32768), (SINT16)(0.8315 * 32768), (SINT16)(1.0000 * 32767), + (SINT16)(0.8315 * 32768), (SINT16)(0.3827 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(-0.9808 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(-0.5556 * 32768), + (SINT16)(-0.0000 * 32768), (SINT16)(0.5556 * 32768), (SINT16)(0.9239 * 32768), (SINT16)(0.9808 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(-0.9808 * 32768), (SINT16)(-0.3827 * 32768), + (SINT16)(0.5556 * 32768), (SINT16)(1.0000 * 32767), (SINT16)(0.5556 * 32768), (SINT16)(-0.3827 * 32768), (SINT16)(-0.9808 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(0.1951 * 32768), + (SINT16)(0.9239 * 32768), (SINT16)(0.8315 * 32768), (SINT16)(0.0000 * 32768), (SINT16)(-0.8315 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(0.7071 * 32768), + (SINT16)(-0.5556 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(0.1951 * 32768), (SINT16)(1.0000 * 32767), (SINT16)(0.1951 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(-0.5556 * 32768), + (SINT16)(0.7071 * 32768), (SINT16)(0.8315 * 32768), (SINT16)(-0.3827 * 32768), (SINT16)(-0.9808 * 32768), (SINT16)(-0.0000 * 32768), (SINT16)(0.9808 * 32768), (SINT16)(0.3827 * 32768), + (SINT16)(-0.8315 * 32768), (SINT16)(0.7071 * 32768), (SINT16)(0.5556 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(1.0000 * 32767), (SINT16)(-0.1951 * 32768), + (SINT16)(-0.9239 * 32768), (SINT16)(0.5556 * 32768), (SINT16)(0.7071 * 32768), (SINT16)(-0.8315 * 32768), (SINT16)(-0.3827 * 32768), (SINT16)(0.9808 * 32768), (SINT16)(0.0000 * 32768), + (SINT16)(-0.9808 * 32768), (SINT16)(0.3827 * 32768), (SINT16)(0.8315 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(0.9808 * 32768), (SINT16)(-0.3827 * 32768), (SINT16)(-0.5556 * 32768), + (SINT16)(1.0000 * 32767), (SINT16)(-0.5556 * 32768), (SINT16)(-0.3827 * 32768), (SINT16)(0.9808 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(0.9239 * 32768), + (SINT16)(-0.8315 * 32768), (SINT16)(-0.0000 * 32768), (SINT16)(0.8315 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(0.1951 * 32768), (SINT16)(-0.7071 * 32768), (SINT16)(0.1951 * 32768), + (SINT16)(0.3827 * 32768), (SINT16)(-0.8315 * 32768), (SINT16)(1.0000 * 32767), (SINT16)(-0.8315 * 32768), (SINT16)(0.3827 * 32768), (SINT16)(0.1951 * 32768), (SINT16)(-0.7071 * 32768), + (SINT16)(0.9808 * 32768), (SINT16)(-0.9239 * 32768), (SINT16)(0.5556 * 32768), (SINT16)(-0.0000 * 32768), (SINT16)(-0.5556 * 32768), (SINT16)(0.9239 * 32768), (SINT16)(-0.9808 * 32768), + (SINT16)(0.7071 * 32768), (SINT16)(-0.8315 * 32768), (SINT16)(0.9239 * 32768), (SINT16)(-0.9808 * 32768), (SINT16)(1.0000 * 32767), (SINT16)(-0.9808 * 32768), (SINT16)(0.9239 * 32768), + (SINT16)(-0.8315 * 32768), (SINT16)(0.7071 * 32768), (SINT16)(-0.5556 * 32768), (SINT16)(0.3827 * 32768), (SINT16)(-0.1951 * 32768), (SINT16)(-0.0000 * 32768), (SINT16)(0.1951 * 32768), + (SINT16)(-0.3827 * 32768), (SINT16)(0.5556 * 32768)}; #endif #endif /* #if defined(SBC_ENC_INCLUDED) */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_mono.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_mono.c index 25d3fb4a39..6d42695d93 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_mono.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_mono.c @@ -30,8 +30,18 @@ #if defined(SBC_ENC_INCLUDED) /*global arrays*/ -const SINT16 sbc_enc_as16Offset4[4][4] = {{-1, 0, 0, 0}, {-2, 0, 0, 1}, {-2, 0, 0, 1}, {-2, 0, 0, 1}}; -const SINT16 sbc_enc_as16Offset8[4][8] = {{-2, 0, 0, 0, 0, 0, 0, 1}, {-3, 0, 0, 0, 0, 0, 1, 2}, {-4, 0, 0, 0, 0, 0, 1, 2}, {-4, 0, 0, 0, 0, 0, 1, 2}}; +const SINT16 sbc_enc_as16Offset4[4][4] = { + {-1, 0, 0, 0}, + {-2, 0, 0, 1}, + {-2, 0, 0, 1}, + {-2, 0, 0, 1} +}; +const SINT16 sbc_enc_as16Offset8[4][8] = { + {-2, 0, 0, 0, 0, 0, 0, 1}, + {-3, 0, 0, 0, 0, 0, 1, 2}, + {-4, 0, 0, 0, 0, 0, 1, 2}, + {-4, 0, 0, 0, 0, 0, 1, 2} +}; /**************************************************************************** * BitAlloc - Calculates the required number of bits for the given scale factor diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_coeffs.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_coeffs.c index 8600235a44..77f75384f0 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_coeffs.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_coeffs.c @@ -29,77 +29,77 @@ #if (SBC_ARM_ASM_OPT == FALSE && SBC_IPAQ_OPT == FALSE) #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == FALSE) /*Window coeff for 4 sub band case*/ -const SINT16 gas32CoeffFor4SBs[] - = {(SINT16)((SINT32)0x00000000 >> 16), (SINT16)0x00000000, (SINT16)((SINT32)0x001194E6 >> 16), (SINT16)0x001194E6, (SINT16)((SINT32)0x0030E2D3 >> 16), (SINT16)0x0030E2D3, - (SINT16)((SINT32)0x00599403 >> 16), (SINT16)0x00599403, (SINT16)((SINT32)0x007DBCC8 >> 16), (SINT16)0x007DBCC8, (SINT16)((SINT32)0x007F88E4 >> 16), (SINT16)0x007F88E4, - (SINT16)((SINT32)0x003D239B >> 16), (SINT16)0x003D239B, (SINT16)((SINT32)0xFF9BB9D5 >> 16), (SINT16)0xFF9BB9D5, +const SINT16 gas32CoeffFor4SBs[] = { + (SINT16)((SINT32)0x00000000 >> 16), (SINT16)0x00000000, (SINT16)((SINT32)0x001194E6 >> 16), (SINT16)0x001194E6, (SINT16)((SINT32)0x0030E2D3 >> 16), (SINT16)0x0030E2D3, + (SINT16)((SINT32)0x00599403 >> 16), (SINT16)0x00599403, (SINT16)((SINT32)0x007DBCC8 >> 16), (SINT16)0x007DBCC8, (SINT16)((SINT32)0x007F88E4 >> 16), (SINT16)0x007F88E4, + (SINT16)((SINT32)0x003D239B >> 16), (SINT16)0x003D239B, (SINT16)((SINT32)0xFF9BB9D5 >> 16), (SINT16)0xFF9BB9D5, - (SINT16)((SINT32)0x01659F45 >> 16), (SINT16)0x01659F45, (SINT16)((SINT32)0x029DBAA3 >> 16), (SINT16)0x029DBAA3, (SINT16)((SINT32)0x03B23341 >> 16), (SINT16)0x03B23341, - (SINT16)((SINT32)0x041EEE40 >> 16), (SINT16)0x041EEE40, (SINT16)((SINT32)0x034FEE2C >> 16), (SINT16)0x034FEE2C, (SINT16)((SINT32)0x00C8F2BC >> 16), (SINT16)0x00C8F2BC, - (SINT16)((SINT32)0xFC4F91D4 >> 16), (SINT16)0xFC4F91D4, (SINT16)((SINT32)0xF60FAF37 >> 16), (SINT16)0xF60FAF37, + (SINT16)((SINT32)0x01659F45 >> 16), (SINT16)0x01659F45, (SINT16)((SINT32)0x029DBAA3 >> 16), (SINT16)0x029DBAA3, (SINT16)((SINT32)0x03B23341 >> 16), (SINT16)0x03B23341, + (SINT16)((SINT32)0x041EEE40 >> 16), (SINT16)0x041EEE40, (SINT16)((SINT32)0x034FEE2C >> 16), (SINT16)0x034FEE2C, (SINT16)((SINT32)0x00C8F2BC >> 16), (SINT16)0x00C8F2BC, + (SINT16)((SINT32)0xFC4F91D4 >> 16), (SINT16)0xFC4F91D4, (SINT16)((SINT32)0xF60FAF37 >> 16), (SINT16)0xF60FAF37, - (SINT16)((SINT32)0x115B1ED2 >> 16), (SINT16)0x115B1ED2, (SINT16)((SINT32)0x18F55C90 >> 16), (SINT16)0x18F55C90, (SINT16)((SINT32)0x1F91CA46 >> 16), (SINT16)0x1F91CA46, - (SINT16)((SINT32)0x2412F251 >> 16), (SINT16)0x2412F251, (SINT16)((SINT32)0x25AC1FF2 >> 16), (SINT16)0x25AC1FF2, (SINT16)((SINT32)0x2412F251 >> 16), (SINT16)0x2412F251, - (SINT16)((SINT32)0x1F91CA46 >> 16), (SINT16)0x1F91CA46, (SINT16)((SINT32)0x18F55C90 >> 16), (SINT16)0x18F55C90, + (SINT16)((SINT32)0x115B1ED2 >> 16), (SINT16)0x115B1ED2, (SINT16)((SINT32)0x18F55C90 >> 16), (SINT16)0x18F55C90, (SINT16)((SINT32)0x1F91CA46 >> 16), (SINT16)0x1F91CA46, + (SINT16)((SINT32)0x2412F251 >> 16), (SINT16)0x2412F251, (SINT16)((SINT32)0x25AC1FF2 >> 16), (SINT16)0x25AC1FF2, (SINT16)((SINT32)0x2412F251 >> 16), (SINT16)0x2412F251, + (SINT16)((SINT32)0x1F91CA46 >> 16), (SINT16)0x1F91CA46, (SINT16)((SINT32)0x18F55C90 >> 16), (SINT16)0x18F55C90, - (SINT16)((SINT32)0xEEA4E12E >> 16), (SINT16)0xEEA4E12E, (SINT16)((SINT32)0xF60FAF37 >> 16), (SINT16)0xF60FAF37, (SINT16)((SINT32)0xFC4F91D4 >> 16), (SINT16)0xFC4F91D4, - (SINT16)((SINT32)0x00C8F2BC >> 16), (SINT16)0x00C8F2BC, (SINT16)((SINT32)0x034FEE2C >> 16), (SINT16)0x034FEE2C, (SINT16)((SINT32)0x041EEE40 >> 16), (SINT16)0x041EEE40, - (SINT16)((SINT32)0x03B23341 >> 16), (SINT16)0x03B23341, (SINT16)((SINT32)0x029DBAA3 >> 16), (SINT16)0x029DBAA3, + (SINT16)((SINT32)0xEEA4E12E >> 16), (SINT16)0xEEA4E12E, (SINT16)((SINT32)0xF60FAF37 >> 16), (SINT16)0xF60FAF37, (SINT16)((SINT32)0xFC4F91D4 >> 16), (SINT16)0xFC4F91D4, + (SINT16)((SINT32)0x00C8F2BC >> 16), (SINT16)0x00C8F2BC, (SINT16)((SINT32)0x034FEE2C >> 16), (SINT16)0x034FEE2C, (SINT16)((SINT32)0x041EEE40 >> 16), (SINT16)0x041EEE40, + (SINT16)((SINT32)0x03B23341 >> 16), (SINT16)0x03B23341, (SINT16)((SINT32)0x029DBAA3 >> 16), (SINT16)0x029DBAA3, - (SINT16)((SINT32)0xFE9A60BB >> 16), (SINT16)0xFE9A60BB, (SINT16)((SINT32)0xFF9BB9D5 >> 16), (SINT16)0xFF9BB9D5, (SINT16)((SINT32)0x003D239B >> 16), (SINT16)0x003D239B, - (SINT16)((SINT32)0x007F88E4 >> 16), (SINT16)0x007F88E4, (SINT16)((SINT32)0x007DBCC8 >> 16), (SINT16)0x007DBCC8, (SINT16)((SINT32)0x00599403 >> 16), (SINT16)0x00599403, - (SINT16)((SINT32)0x0030E2D3 >> 16), (SINT16)0x0030E2D3, (SINT16)((SINT32)0x001194E6 >> 16), (SINT16)0x001194E6}; + (SINT16)((SINT32)0xFE9A60BB >> 16), (SINT16)0xFE9A60BB, (SINT16)((SINT32)0xFF9BB9D5 >> 16), (SINT16)0xFF9BB9D5, (SINT16)((SINT32)0x003D239B >> 16), (SINT16)0x003D239B, + (SINT16)((SINT32)0x007F88E4 >> 16), (SINT16)0x007F88E4, (SINT16)((SINT32)0x007DBCC8 >> 16), (SINT16)0x007DBCC8, (SINT16)((SINT32)0x00599403 >> 16), (SINT16)0x00599403, + (SINT16)((SINT32)0x0030E2D3 >> 16), (SINT16)0x0030E2D3, (SINT16)((SINT32)0x001194E6 >> 16), (SINT16)0x001194E6}; /*Window coeff for 8 sub band case*/ -const SINT16 gas32CoeffFor8SBs[] - = {(SINT16)((SINT32)0x00000000 >> 16), (SINT16)0x00000000, (SINT16)((SINT32)0x00052173 >> 16), (SINT16)0x00052173, (SINT16)((SINT32)0x000B3F71 >> 16), (SINT16)0x000B3F71, - (SINT16)((SINT32)0x00122C7D >> 16), (SINT16)0x00122C7D, (SINT16)((SINT32)0x001AFF89 >> 16), (SINT16)0x001AFF89, (SINT16)((SINT32)0x00255A62 >> 16), (SINT16)0x00255A62, - (SINT16)((SINT32)0x003060F4 >> 16), (SINT16)0x003060F4, (SINT16)((SINT32)0x003A72E7 >> 16), (SINT16)0x003A72E7, - - (SINT16)((SINT32)0x0041EC6A >> 16), (SINT16)0x0041EC6A, /* 8 */ - (SINT16)((SINT32)0x0044EF48 >> 16), (SINT16)0x0044EF48, (SINT16)((SINT32)0x00415B75 >> 16), (SINT16)0x00415B75, (SINT16)((SINT32)0x0034F8B6 >> 16), (SINT16)0x0034F8B6, - (SINT16)((SINT32)0x001D8FD2 >> 16), (SINT16)0x001D8FD2, (SINT16)((SINT32)0xFFFA2413 >> 16), (SINT16)0xFFFA2413, (SINT16)((SINT32)0xFFC9F10E >> 16), (SINT16)0xFFC9F10E, - (SINT16)((SINT32)0xFF8D6793 >> 16), (SINT16)0xFF8D6793, - - (SINT16)((SINT32)0x00B97348 >> 16), (SINT16)0x00B97348, /* 16 */ - (SINT16)((SINT32)0x01071B96 >> 16), (SINT16)0x01071B96, (SINT16)((SINT32)0x0156B3CA >> 16), (SINT16)0x0156B3CA, (SINT16)((SINT32)0x01A1B38B >> 16), (SINT16)0x01A1B38B, - (SINT16)((SINT32)0x01E0224C >> 16), (SINT16)0x01E0224C, (SINT16)((SINT32)0x0209291F >> 16), (SINT16)0x0209291F, (SINT16)((SINT32)0x02138653 >> 16), (SINT16)0x02138653, - (SINT16)((SINT32)0x01F5F424 >> 16), (SINT16)0x01F5F424, - - (SINT16)((SINT32)0x01A7ECEF >> 16), (SINT16)0x01A7ECEF, /* 24 */ - (SINT16)((SINT32)0x01223EBA >> 16), (SINT16)0x01223EBA, (SINT16)((SINT32)0x005FD0FF >> 16), (SINT16)0x005FD0FF, (SINT16)((SINT32)0xFF5EEB73 >> 16), (SINT16)0xFF5EEB73, - (SINT16)((SINT32)0xFE20435D >> 16), (SINT16)0xFE20435D, (SINT16)((SINT32)0xFCA86E7E >> 16), (SINT16)0xFCA86E7E, (SINT16)((SINT32)0xFAFF95FC >> 16), (SINT16)0xFAFF95FC, - (SINT16)((SINT32)0xF9312891 >> 16), (SINT16)0xF9312891, - - (SINT16)((SINT32)0x08B4307A >> 16), (SINT16)0x08B4307A, /* 32 */ - (SINT16)((SINT32)0x0A9F3E9A >> 16), (SINT16)0x0A9F3E9A, (SINT16)((SINT32)0x0C7D59B6 >> 16), (SINT16)0x0C7D59B6, (SINT16)((SINT32)0x0E3BB16F >> 16), (SINT16)0x0E3BB16F, - (SINT16)((SINT32)0x0FC721F9 >> 16), (SINT16)0x0FC721F9, (SINT16)((SINT32)0x110ECEF0 >> 16), (SINT16)0x110ECEF0, (SINT16)((SINT32)0x120435FA >> 16), (SINT16)0x120435FA, - (SINT16)((SINT32)0x129C226F >> 16), (SINT16)0x129C226F, - - (SINT16)((SINT32)0x12CF6C75 >> 16), (SINT16)0x12CF6C75, /* 40 */ - (SINT16)((SINT32)0x129C226F >> 16), (SINT16)0x129C226F, (SINT16)((SINT32)0x120435FA >> 16), (SINT16)0x120435FA, (SINT16)((SINT32)0x110ECEF0 >> 16), (SINT16)0x110ECEF0, - (SINT16)((SINT32)0x0FC721F9 >> 16), (SINT16)0x0FC721F9, (SINT16)((SINT32)0x0E3BB16F >> 16), (SINT16)0x0E3BB16F, (SINT16)((SINT32)0x0C7D59B6 >> 16), (SINT16)0x0C7D59B6, - (SINT16)((SINT32)0x0A9F3E9A >> 16), (SINT16)0x0A9F3E9A, - - (SINT16)((SINT32)0xF74BCF86 >> 16), (SINT16)0xF74BCF86, /* 48 */ - (SINT16)((SINT32)0xF9312891 >> 16), (SINT16)0xF9312891, (SINT16)((SINT32)0xFAFF95FC >> 16), (SINT16)0xFAFF95FC, (SINT16)((SINT32)0xFCA86E7E >> 16), (SINT16)0xFCA86E7E, - (SINT16)((SINT32)0xFE20435D >> 16), (SINT16)0xFE20435D, (SINT16)((SINT32)0xFF5EEB73 >> 16), (SINT16)0xFF5EEB73, (SINT16)((SINT32)0x005FD0FF >> 16), (SINT16)0x005FD0FF, - (SINT16)((SINT32)0x01223EBA >> 16), (SINT16)0x01223EBA, - - (SINT16)((SINT32)0x01A7ECEF >> 16), (SINT16)0x01A7ECEF, /* 56 */ - (SINT16)((SINT32)0x01F5F424 >> 16), (SINT16)0x01F5F424, (SINT16)((SINT32)0x02138653 >> 16), (SINT16)0x02138653, (SINT16)((SINT32)0x0209291F >> 16), (SINT16)0x0209291F, - (SINT16)((SINT32)0x01E0224C >> 16), (SINT16)0x01E0224C, (SINT16)((SINT32)0x01A1B38B >> 16), (SINT16)0x01A1B38B, (SINT16)((SINT32)0x0156B3CA >> 16), (SINT16)0x0156B3CA, - (SINT16)((SINT32)0x01071B96 >> 16), (SINT16)0x01071B96, - - (SINT16)((SINT32)0xFF468CB8 >> 16), (SINT16)0xFF468CB8, /* 64 */ - (SINT16)((SINT32)0xFF8D6793 >> 16), (SINT16)0xFF8D6793, (SINT16)((SINT32)0xFFC9F10E >> 16), (SINT16)0xFFC9F10E, (SINT16)((SINT32)0xFFFA2413 >> 16), (SINT16)0xFFFA2413, - (SINT16)((SINT32)0x001D8FD2 >> 16), (SINT16)0x001D8FD2, (SINT16)((SINT32)0x0034F8B6 >> 16), (SINT16)0x0034F8B6, (SINT16)((SINT32)0x00415B75 >> 16), (SINT16)0x00415B75, - (SINT16)((SINT32)0x0044EF48 >> 16), (SINT16)0x0044EF48, - - (SINT16)((SINT32)0x0041EC6A >> 16), (SINT16)0x0041EC6A, /* 72 */ - (SINT16)((SINT32)0x003A72E7 >> 16), (SINT16)0x003A72E7, (SINT16)((SINT32)0x003060F4 >> 16), (SINT16)0x003060F4, (SINT16)((SINT32)0x00255A62 >> 16), (SINT16)0x00255A62, - (SINT16)((SINT32)0x001AFF89 >> 16), (SINT16)0x001AFF89, (SINT16)((SINT32)0x00122C7D >> 16), (SINT16)0x00122C7D, (SINT16)((SINT32)0x000B3F71 >> 16), (SINT16)0x000B3F71, - (SINT16)((SINT32)0x00052173 >> 16), (SINT16)0x00052173}; +const SINT16 gas32CoeffFor8SBs[] = { + (SINT16)((SINT32)0x00000000 >> 16), (SINT16)0x00000000, (SINT16)((SINT32)0x00052173 >> 16), (SINT16)0x00052173, (SINT16)((SINT32)0x000B3F71 >> 16), (SINT16)0x000B3F71, + (SINT16)((SINT32)0x00122C7D >> 16), (SINT16)0x00122C7D, (SINT16)((SINT32)0x001AFF89 >> 16), (SINT16)0x001AFF89, (SINT16)((SINT32)0x00255A62 >> 16), (SINT16)0x00255A62, + (SINT16)((SINT32)0x003060F4 >> 16), (SINT16)0x003060F4, (SINT16)((SINT32)0x003A72E7 >> 16), (SINT16)0x003A72E7, + + (SINT16)((SINT32)0x0041EC6A >> 16), (SINT16)0x0041EC6A, /* 8 */ + (SINT16)((SINT32)0x0044EF48 >> 16), (SINT16)0x0044EF48, (SINT16)((SINT32)0x00415B75 >> 16), (SINT16)0x00415B75, (SINT16)((SINT32)0x0034F8B6 >> 16), (SINT16)0x0034F8B6, + (SINT16)((SINT32)0x001D8FD2 >> 16), (SINT16)0x001D8FD2, (SINT16)((SINT32)0xFFFA2413 >> 16), (SINT16)0xFFFA2413, (SINT16)((SINT32)0xFFC9F10E >> 16), (SINT16)0xFFC9F10E, + (SINT16)((SINT32)0xFF8D6793 >> 16), (SINT16)0xFF8D6793, + + (SINT16)((SINT32)0x00B97348 >> 16), (SINT16)0x00B97348, /* 16 */ + (SINT16)((SINT32)0x01071B96 >> 16), (SINT16)0x01071B96, (SINT16)((SINT32)0x0156B3CA >> 16), (SINT16)0x0156B3CA, (SINT16)((SINT32)0x01A1B38B >> 16), (SINT16)0x01A1B38B, + (SINT16)((SINT32)0x01E0224C >> 16), (SINT16)0x01E0224C, (SINT16)((SINT32)0x0209291F >> 16), (SINT16)0x0209291F, (SINT16)((SINT32)0x02138653 >> 16), (SINT16)0x02138653, + (SINT16)((SINT32)0x01F5F424 >> 16), (SINT16)0x01F5F424, + + (SINT16)((SINT32)0x01A7ECEF >> 16), (SINT16)0x01A7ECEF, /* 24 */ + (SINT16)((SINT32)0x01223EBA >> 16), (SINT16)0x01223EBA, (SINT16)((SINT32)0x005FD0FF >> 16), (SINT16)0x005FD0FF, (SINT16)((SINT32)0xFF5EEB73 >> 16), (SINT16)0xFF5EEB73, + (SINT16)((SINT32)0xFE20435D >> 16), (SINT16)0xFE20435D, (SINT16)((SINT32)0xFCA86E7E >> 16), (SINT16)0xFCA86E7E, (SINT16)((SINT32)0xFAFF95FC >> 16), (SINT16)0xFAFF95FC, + (SINT16)((SINT32)0xF9312891 >> 16), (SINT16)0xF9312891, + + (SINT16)((SINT32)0x08B4307A >> 16), (SINT16)0x08B4307A, /* 32 */ + (SINT16)((SINT32)0x0A9F3E9A >> 16), (SINT16)0x0A9F3E9A, (SINT16)((SINT32)0x0C7D59B6 >> 16), (SINT16)0x0C7D59B6, (SINT16)((SINT32)0x0E3BB16F >> 16), (SINT16)0x0E3BB16F, + (SINT16)((SINT32)0x0FC721F9 >> 16), (SINT16)0x0FC721F9, (SINT16)((SINT32)0x110ECEF0 >> 16), (SINT16)0x110ECEF0, (SINT16)((SINT32)0x120435FA >> 16), (SINT16)0x120435FA, + (SINT16)((SINT32)0x129C226F >> 16), (SINT16)0x129C226F, + + (SINT16)((SINT32)0x12CF6C75 >> 16), (SINT16)0x12CF6C75, /* 40 */ + (SINT16)((SINT32)0x129C226F >> 16), (SINT16)0x129C226F, (SINT16)((SINT32)0x120435FA >> 16), (SINT16)0x120435FA, (SINT16)((SINT32)0x110ECEF0 >> 16), (SINT16)0x110ECEF0, + (SINT16)((SINT32)0x0FC721F9 >> 16), (SINT16)0x0FC721F9, (SINT16)((SINT32)0x0E3BB16F >> 16), (SINT16)0x0E3BB16F, (SINT16)((SINT32)0x0C7D59B6 >> 16), (SINT16)0x0C7D59B6, + (SINT16)((SINT32)0x0A9F3E9A >> 16), (SINT16)0x0A9F3E9A, + + (SINT16)((SINT32)0xF74BCF86 >> 16), (SINT16)0xF74BCF86, /* 48 */ + (SINT16)((SINT32)0xF9312891 >> 16), (SINT16)0xF9312891, (SINT16)((SINT32)0xFAFF95FC >> 16), (SINT16)0xFAFF95FC, (SINT16)((SINT32)0xFCA86E7E >> 16), (SINT16)0xFCA86E7E, + (SINT16)((SINT32)0xFE20435D >> 16), (SINT16)0xFE20435D, (SINT16)((SINT32)0xFF5EEB73 >> 16), (SINT16)0xFF5EEB73, (SINT16)((SINT32)0x005FD0FF >> 16), (SINT16)0x005FD0FF, + (SINT16)((SINT32)0x01223EBA >> 16), (SINT16)0x01223EBA, + + (SINT16)((SINT32)0x01A7ECEF >> 16), (SINT16)0x01A7ECEF, /* 56 */ + (SINT16)((SINT32)0x01F5F424 >> 16), (SINT16)0x01F5F424, (SINT16)((SINT32)0x02138653 >> 16), (SINT16)0x02138653, (SINT16)((SINT32)0x0209291F >> 16), (SINT16)0x0209291F, + (SINT16)((SINT32)0x01E0224C >> 16), (SINT16)0x01E0224C, (SINT16)((SINT32)0x01A1B38B >> 16), (SINT16)0x01A1B38B, (SINT16)((SINT32)0x0156B3CA >> 16), (SINT16)0x0156B3CA, + (SINT16)((SINT32)0x01071B96 >> 16), (SINT16)0x01071B96, + + (SINT16)((SINT32)0xFF468CB8 >> 16), (SINT16)0xFF468CB8, /* 64 */ + (SINT16)((SINT32)0xFF8D6793 >> 16), (SINT16)0xFF8D6793, (SINT16)((SINT32)0xFFC9F10E >> 16), (SINT16)0xFFC9F10E, (SINT16)((SINT32)0xFFFA2413 >> 16), (SINT16)0xFFFA2413, + (SINT16)((SINT32)0x001D8FD2 >> 16), (SINT16)0x001D8FD2, (SINT16)((SINT32)0x0034F8B6 >> 16), (SINT16)0x0034F8B6, (SINT16)((SINT32)0x00415B75 >> 16), (SINT16)0x00415B75, + (SINT16)((SINT32)0x0044EF48 >> 16), (SINT16)0x0044EF48, + + (SINT16)((SINT32)0x0041EC6A >> 16), (SINT16)0x0041EC6A, /* 72 */ + (SINT16)((SINT32)0x003A72E7 >> 16), (SINT16)0x003A72E7, (SINT16)((SINT32)0x003060F4 >> 16), (SINT16)0x003060F4, (SINT16)((SINT32)0x00255A62 >> 16), (SINT16)0x00255A62, + (SINT16)((SINT32)0x001AFF89 >> 16), (SINT16)0x001AFF89, (SINT16)((SINT32)0x00122C7D >> 16), (SINT16)0x00122C7D, (SINT16)((SINT32)0x000B3F71 >> 16), (SINT16)0x000B3F71, + (SINT16)((SINT32)0x00052173 >> 16), (SINT16)0x00052173}; #else diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_encoder.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_encoder.c index adfd588b38..9db957ff90 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_encoder.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_encoder.c @@ -221,12 +221,12 @@ void SBC_Encoder_Init(SBC_ENC_PARAMS *pstrEncParams) { } if ((pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) || (pstrEncParams->s16ChannelMode == SBC_STEREO)) { - s16Bitpool = (SINT16)((pstrEncParams->u16BitRate * pstrEncParams->s16NumOfSubBands * 1000 / s16SamplingFreq) - - ((32 + (4 * pstrEncParams->s16NumOfSubBands * pstrEncParams->s16NumOfChannels) + ((pstrEncParams->s16ChannelMode - 2) * pstrEncParams->s16NumOfSubBands)) - / pstrEncParams->s16NumOfBlocks)); + s16Bitpool = (SINT16)((pstrEncParams->u16BitRate * pstrEncParams->s16NumOfSubBands * 1000 / s16SamplingFreq) - + ((32 + (4 * pstrEncParams->s16NumOfSubBands * pstrEncParams->s16NumOfChannels) + ((pstrEncParams->s16ChannelMode - 2) * pstrEncParams->s16NumOfSubBands)) / + pstrEncParams->s16NumOfBlocks)); - s16FrameLen = 4 + (4 * pstrEncParams->s16NumOfSubBands * pstrEncParams->s16NumOfChannels) / 8 - + (((pstrEncParams->s16ChannelMode - 2) * pstrEncParams->s16NumOfSubBands) + (pstrEncParams->s16NumOfBlocks * s16Bitpool)) / 8; + s16FrameLen = 4 + (4 * pstrEncParams->s16NumOfSubBands * pstrEncParams->s16NumOfChannels) / 8 + + (((pstrEncParams->s16ChannelMode - 2) * pstrEncParams->s16NumOfSubBands) + (pstrEncParams->s16NumOfBlocks * s16Bitpool)) / 8; s16BitRate = (8 * s16FrameLen * s16SamplingFreq) / (pstrEncParams->s16NumOfSubBands * pstrEncParams->s16NumOfBlocks * 1000); @@ -240,8 +240,8 @@ void SBC_Encoder_Init(SBC_ENC_PARAMS *pstrEncParams) { pstrEncParams->s16BitPool = (s16Bitpool > 128) ? 128 : s16Bitpool; } } else { - s16Bitpool = (SINT16)(((pstrEncParams->s16NumOfSubBands * pstrEncParams->u16BitRate * 1000) / (s16SamplingFreq * pstrEncParams->s16NumOfChannels)) - - (((32 / pstrEncParams->s16NumOfChannels) + (4 * pstrEncParams->s16NumOfSubBands)) / pstrEncParams->s16NumOfBlocks)); + s16Bitpool = (SINT16)(((pstrEncParams->s16NumOfSubBands * pstrEncParams->u16BitRate * 1000) / (s16SamplingFreq * pstrEncParams->s16NumOfChannels)) - + (((32 / pstrEncParams->s16NumOfChannels) + (4 * pstrEncParams->s16NumOfSubBands)) / pstrEncParams->s16NumOfBlocks)); pstrEncParams->s16BitPool = (s16Bitpool > (16 * pstrEncParams->s16NumOfSubBands)) ? (16 * pstrEncParams->s16NumOfSubBands) : s16Bitpool; } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_packing.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_packing.c index a83dcb9dd2..1a24388bf9 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_packing.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_packing.c @@ -28,25 +28,25 @@ #if defined(SBC_ENC_INCLUDED) #if (SBC_ARM_ASM_OPT == TRUE) -#define Mult32(s32In1, s32In2, s32OutLow) \ - { \ +#define Mult32(s32In1, s32In2, s32OutLow) \ + { \ __asm { \ - MUL s32OutLow,s32In1,s32In2; } \ + MUL s32OutLow,s32In1,s32In2; } \ } -#define Mult64(s32In1, s32In2, s32OutLow, s32OutHi) \ - { \ +#define Mult64(s32In1, s32In2, s32OutLow, s32OutHi) \ + { \ __asm { \ - SMULL s32OutLow,s32OutHi,s32In1,s32In2 } \ + SMULL s32OutLow,s32OutHi,s32In1,s32In2 } \ } #else #define Mult32(s32In1, s32In2, s32OutLow) s32OutLow = (SINT32)s32In1 * (SINT32)s32In2; -#define Mult64(s32In1, s32In2, s32OutLow, s32OutHi) \ - { \ - s32OutLow = ((SINT32)(UINT16)s32In1 * (UINT16)s32In2); \ - s32TempVal2 = (SINT32)((s32In1 >> 16) * (UINT16)s32In2); \ - s32Carry = ((((UINT32)(s32OutLow) >> 16) & 0xFFFF) + +(s32TempVal2 & 0xFFFF)) >> 16; \ - s32OutLow += (s32TempVal2 << 16); \ - s32OutHi = (s32TempVal2 >> 16) + s32Carry; \ +#define Mult64(s32In1, s32In2, s32OutLow, s32OutHi) \ + { \ + s32OutLow = ((SINT32)(UINT16)s32In1 * (UINT16)s32In2); \ + s32TempVal2 = (SINT32)((s32In1 >> 16) * (UINT16)s32In2); \ + s32Carry = ((((UINT32)(s32OutLow) >> 16) & 0xFFFF) + +(s32TempVal2 & 0xFFFF)) >> 16; \ + s32OutLow += (s32TempVal2 << 16); \ + s32OutHi = (s32TempVal2 >> 16) + s32Carry; \ } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c index 18dece817f..cc2935ac53 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c @@ -135,8 +135,8 @@ struct hids_remote_key { static struct hids_remote_key remote_kbd_map_tab[] = { {HID_PAGE_KBD, Key_a_or_A2}, - {HID_PAGE_KBD, Key_b_or_B}, - {HID_PAGE_KBD, Key_c_or_C}, + {HID_PAGE_KBD, Key_b_or_B}, + {HID_PAGE_KBD, Key_c_or_C}, }; int hog_notify(struct bt_conn *conn, uint16_t hid_usage, uint8_t press) { diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.c index 6bd0ed37e3..ee8ef026a8 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.c @@ -36,8 +36,8 @@ static ssize_t scan_intvl_win_write(struct bt_conn *conn, const struct bt_gatt_a return len; } -static struct bt_gatt_attr attrs[] - = {BT_GATT_PRIMARY_SERVICE(BT_UUID_SCPS), BT_GATT_CHARACTERISTIC(BT_UUID_SCPS_SCAN_INTVL_WIN, BT_GATT_CHRC_WRITE_WITHOUT_RESP, BT_GATT_PERM_NONE, NULL, NULL, &intvl_win)}; +static struct bt_gatt_attr attrs[] = {BT_GATT_PRIMARY_SERVICE(BT_UUID_SCPS), + BT_GATT_CHARACTERISTIC(BT_UUID_SCPS_SCAN_INTVL_WIN, BT_GATT_CHRC_WRITE_WITHOUT_RESP, BT_GATT_PERM_NONE, NULL, NULL, &intvl_win)}; static struct bt_gatt_service scps = BT_GATT_SERVICE(attrs); diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/freertos/portable/gcc/risc-v/bl702/port.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/freertos/portable/gcc/risc-v/bl702/port.c index 7a70a0938b..365edb3cf7 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/freertos/portable/gcc/risc-v/bl702/port.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/freertos/portable/gcc/risc-v/bl702/port.c @@ -91,10 +91,10 @@ the task stacks, and so will legitimately appear in many positions within the ISR stack. */ #define portISR_STACK_FILL_BYTE 0xee -static const uint8_t ucExpectedStackBytes[] - = {portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, - portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, - portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE}; +static const uint8_t ucExpectedStackBytes[] = {portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE}; #define portCHECK_ISR_STACK() configASSERT((memcmp((void *)xISRStack, (void *)ucExpectedStackBytes, sizeof(ucExpectedStackBytes)) == 0)) #else diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_common.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_common.c index 84888bdb5c..13f671c821 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_common.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_common.c @@ -64,7 +64,8 @@ void ATTR_TCM_SECTION hal_jump2app(uint32_t flash_offset) { L1C_Cache_Flush_Ext(); app_main(); } else { - while (1) {} + while (1) { + } } } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_dma.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_dma.c index ce242d6a1b..1bd8563059 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_dma.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_dma.c @@ -25,17 +25,17 @@ #define DMA_CHANNEL_BASE(id_base, ch) ((id_base) + DMA_CHANNEL_OFFSET + (ch) * 0x100) -static const uint32_t dma_channel_base[][8] = {{ - DMA_CHANNEL_BASE(DMA_BASE, 0), - DMA_CHANNEL_BASE(DMA_BASE, 1), - DMA_CHANNEL_BASE(DMA_BASE, 2), - DMA_CHANNEL_BASE(DMA_BASE, 3), - DMA_CHANNEL_BASE(DMA_BASE, 4), - DMA_CHANNEL_BASE(DMA_BASE, 5), - DMA_CHANNEL_BASE(DMA_BASE, 6), - DMA_CHANNEL_BASE(DMA_BASE, 7), -} - +static const uint32_t dma_channel_base[][8] = { + { + DMA_CHANNEL_BASE(DMA_BASE, 0), + DMA_CHANNEL_BASE(DMA_BASE, 1), + DMA_CHANNEL_BASE(DMA_BASE, 2), + DMA_CHANNEL_BASE(DMA_BASE, 3), + DMA_CHANNEL_BASE(DMA_BASE, 4), + DMA_CHANNEL_BASE(DMA_BASE, 5), + DMA_CHANNEL_BASE(DMA_BASE, 6), + DMA_CHANNEL_BASE(DMA_BASE, 7), + } }; static void DMA0_IRQ(void); @@ -271,8 +271,8 @@ int dma_allocate_register(const char *name) { * @return int */ int dma_reload(struct device *dev, uint32_t src_addr, uint32_t dst_addr, uint32_t transfer_size) { -#if defined(BSP_USING_DMA0_CH0) || defined(BSP_USING_DMA0_CH1) || defined(BSP_USING_DMA0_CH2) || defined(BSP_USING_DMA0_CH3) || defined(BSP_USING_DMA0_CH4) || defined(BSP_USING_DMA0_CH5) \ - || defined(BSP_USING_DMA0_CH6) || defined(BSP_USING_DMA0_CH7) +#if defined(BSP_USING_DMA0_CH0) || defined(BSP_USING_DMA0_CH1) || defined(BSP_USING_DMA0_CH2) || defined(BSP_USING_DMA0_CH3) || defined(BSP_USING_DMA0_CH4) || defined(BSP_USING_DMA0_CH5) || \ + defined(BSP_USING_DMA0_CH6) || defined(BSP_USING_DMA0_CH7) uint32_t malloc_count; uint32_t remain_len; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm.c index 7d5c624e29..8130246cbf 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm.c @@ -55,352 +55,364 @@ void HBN_OUT1_IRQ(void); * @{ */ static PDS_DEFAULT_LV_CFG_Type ATTR_TCM_CONST_SECTION pdsCfgLevel0 = { - .pdsCtl = { - .pdsStart = 1, - .sleepForever = 0, - .xtalForceOff = 0, - .saveWifiState = 0, - .dcdc18Off = 1, - .bgSysOff = 1, - .gpioIePuPd = 1, - .puFlash = 0, - .clkOff = 1, - .memStby = 1, - .swPuFlash = 1, - .isolation = 1, - .waitXtalRdy = 0, - .pdsPwrOff = 1, - .xtalOff = 0, - .socEnbForceOn = 1, - .pdsRstSocEn = 0, - .pdsRC32mOn = 0, - .pdsLdoVselEn = 0, - .pdsRamLowPowerWithClkEn = 1, - .cpu0WfiMask = 0, - .ldo11Off = 1, - .pdsForceRamClkEn = 0, - .pdsLdoVol = 0xA, - .pdsCtlRfSel = 3, - .pdsCtlPllSel = 0, - }, - .pdsCtl2 = { - .forceCpuPwrOff = 0, - .forceBzPwrOff = 0, - .forceUsbPwrOff = 0, - .forceCpuIsoEn = 0, - .forceBzIsoEn = 0, - .forceUsbIsoEn = 0, - .forceCpuPdsRst = 0, - .forceBzPdsRst = 0, - .forceUsbPdsRst = 0, - .forceCpuMemStby = 0, - .forceBzMemStby = 0, - .forceUsbMemStby = 0, - .forceCpuGateClk = 0, - .forceBzGateClk = 0, - .forceUsbGateClk = 0, - }, - .pdsCtl3 = { - .forceMiscPwrOff = 0, - .forceBlePwrOff = 0, - .forceBleIsoEn = 0, - .forceMiscPdsRst = 0, - .forceBlePdsRst = 0, - .forceMiscMemStby = 0, - .forceBleMemStby = 0, - .forceMiscGateClk = 0, - .forceBleGateClk = 0, - .CpuIsoEn = 0, - .BzIsoEn = 0, - .BleIsoEn = 1, - .UsbIsoEn = 0, - .MiscIsoEn = 0, - }, + .pdsCtl = + { + .pdsStart = 1, + .sleepForever = 0, + .xtalForceOff = 0, + .saveWifiState = 0, + .dcdc18Off = 1, + .bgSysOff = 1, + .gpioIePuPd = 1, + .puFlash = 0, + .clkOff = 1, + .memStby = 1, + .swPuFlash = 1, + .isolation = 1, + .waitXtalRdy = 0, + .pdsPwrOff = 1, + .xtalOff = 0, + .socEnbForceOn = 1, + .pdsRstSocEn = 0, + .pdsRC32mOn = 0, + .pdsLdoVselEn = 0, + .pdsRamLowPowerWithClkEn = 1, + .cpu0WfiMask = 0, + .ldo11Off = 1, + .pdsForceRamClkEn = 0, + .pdsLdoVol = 0xA, + .pdsCtlRfSel = 3, + .pdsCtlPllSel = 0, + }, + .pdsCtl2 = + { + .forceCpuPwrOff = 0, + .forceBzPwrOff = 0, + .forceUsbPwrOff = 0, + .forceCpuIsoEn = 0, + .forceBzIsoEn = 0, + .forceUsbIsoEn = 0, + .forceCpuPdsRst = 0, + .forceBzPdsRst = 0, + .forceUsbPdsRst = 0, + .forceCpuMemStby = 0, + .forceBzMemStby = 0, + .forceUsbMemStby = 0, + .forceCpuGateClk = 0, + .forceBzGateClk = 0, + .forceUsbGateClk = 0, + }, + .pdsCtl3 = + { + .forceMiscPwrOff = 0, + .forceBlePwrOff = 0, + .forceBleIsoEn = 0, + .forceMiscPdsRst = 0, + .forceBlePdsRst = 0, + .forceMiscMemStby = 0, + .forceBleMemStby = 0, + .forceMiscGateClk = 0, + .forceBleGateClk = 0, + .CpuIsoEn = 0, + .BzIsoEn = 0, + .BleIsoEn = 1, + .UsbIsoEn = 0, + .MiscIsoEn = 0, + }, .pdsCtl4 = { - .cpuPwrOff = 0, - .cpuRst = 0, - .cpuMemStby = 1, - .cpuGateClk = 1, - .BzPwrOff = 0, - .BzRst = 0, - .BzMemStby = 1, - .BzGateClk = 1, - .BlePwrOff = 1, - .BleRst = 1, - .BleMemStby = 1, - .BleGateClk = 1, - .UsbPwrOff = 0, - .UsbRst = 0, - .UsbMemStby = 1, - .UsbGateClk = 1, - .MiscPwrOff = 0, - .MiscRst = 0, - .MiscMemStby = 1, - .MiscGateClk = 1, - .MiscAnaPwrOff = 1, - .MiscDigPwrOff = 1, - } + .cpuPwrOff = 0, + .cpuRst = 0, + .cpuMemStby = 1, + .cpuGateClk = 1, + .BzPwrOff = 0, + .BzRst = 0, + .BzMemStby = 1, + .BzGateClk = 1, + .BlePwrOff = 1, + .BleRst = 1, + .BleMemStby = 1, + .BleGateClk = 1, + .UsbPwrOff = 0, + .UsbRst = 0, + .UsbMemStby = 1, + .UsbGateClk = 1, + .MiscPwrOff = 0, + .MiscRst = 0, + .MiscMemStby = 1, + .MiscGateClk = 1, + .MiscAnaPwrOff = 1, + .MiscDigPwrOff = 1, + } }; static PDS_DEFAULT_LV_CFG_Type ATTR_TCM_CONST_SECTION pdsCfgLevel1 = { - .pdsCtl = { - .pdsStart = 1, - .sleepForever = 0, - .xtalForceOff = 0, - .saveWifiState = 0, - .dcdc18Off = 1, - .bgSysOff = 1, - .gpioIePuPd = 1, - .puFlash = 0, - .clkOff = 1, - .memStby = 1, - .swPuFlash = 1, - .isolation = 1, - .waitXtalRdy = 0, - .pdsPwrOff = 1, - .xtalOff = 0, - .socEnbForceOn = 1, - .pdsRstSocEn = 0, - .pdsRC32mOn = 0, - .pdsLdoVselEn = 0, - .pdsRamLowPowerWithClkEn = 1, - .cpu0WfiMask = 0, - .ldo11Off = 1, - .pdsForceRamClkEn = 0, - .pdsLdoVol = 0xA, - .pdsCtlRfSel = 3, - .pdsCtlPllSel = 0, - }, - .pdsCtl2 = { - .forceCpuPwrOff = 0, - .forceBzPwrOff = 0, - .forceUsbPwrOff = 0, - .forceCpuIsoEn = 0, - .forceBzIsoEn = 0, - .forceUsbIsoEn = 0, - .forceCpuPdsRst = 0, - .forceBzPdsRst = 0, - .forceUsbPdsRst = 0, - .forceCpuMemStby = 0, - .forceBzMemStby = 0, - .forceUsbMemStby = 0, - .forceCpuGateClk = 0, - .forceBzGateClk = 0, - .forceUsbGateClk = 0, - }, - .pdsCtl3 = { - .forceMiscPwrOff = 0, - .forceBlePwrOff = 0, - .forceBleIsoEn = 0, - .forceMiscPdsRst = 0, - .forceBlePdsRst = 0, - .forceMiscMemStby = 0, - .forceBleMemStby = 0, - .forceMiscGateClk = 0, - .forceBleGateClk = 0, - .CpuIsoEn = 0, - .BzIsoEn = 0, - .BleIsoEn = 1, - .UsbIsoEn = 1, - .MiscIsoEn = 0, - }, + .pdsCtl = + { + .pdsStart = 1, + .sleepForever = 0, + .xtalForceOff = 0, + .saveWifiState = 0, + .dcdc18Off = 1, + .bgSysOff = 1, + .gpioIePuPd = 1, + .puFlash = 0, + .clkOff = 1, + .memStby = 1, + .swPuFlash = 1, + .isolation = 1, + .waitXtalRdy = 0, + .pdsPwrOff = 1, + .xtalOff = 0, + .socEnbForceOn = 1, + .pdsRstSocEn = 0, + .pdsRC32mOn = 0, + .pdsLdoVselEn = 0, + .pdsRamLowPowerWithClkEn = 1, + .cpu0WfiMask = 0, + .ldo11Off = 1, + .pdsForceRamClkEn = 0, + .pdsLdoVol = 0xA, + .pdsCtlRfSel = 3, + .pdsCtlPllSel = 0, + }, + .pdsCtl2 = + { + .forceCpuPwrOff = 0, + .forceBzPwrOff = 0, + .forceUsbPwrOff = 0, + .forceCpuIsoEn = 0, + .forceBzIsoEn = 0, + .forceUsbIsoEn = 0, + .forceCpuPdsRst = 0, + .forceBzPdsRst = 0, + .forceUsbPdsRst = 0, + .forceCpuMemStby = 0, + .forceBzMemStby = 0, + .forceUsbMemStby = 0, + .forceCpuGateClk = 0, + .forceBzGateClk = 0, + .forceUsbGateClk = 0, + }, + .pdsCtl3 = + { + .forceMiscPwrOff = 0, + .forceBlePwrOff = 0, + .forceBleIsoEn = 0, + .forceMiscPdsRst = 0, + .forceBlePdsRst = 0, + .forceMiscMemStby = 0, + .forceBleMemStby = 0, + .forceMiscGateClk = 0, + .forceBleGateClk = 0, + .CpuIsoEn = 0, + .BzIsoEn = 0, + .BleIsoEn = 1, + .UsbIsoEn = 1, + .MiscIsoEn = 0, + }, .pdsCtl4 = { - .cpuPwrOff = 0, - .cpuRst = 0, - .cpuMemStby = 1, - .cpuGateClk = 1, - .BzPwrOff = 0, - .BzRst = 0, - .BzMemStby = 1, - .BzGateClk = 1, - .BlePwrOff = 1, - .BleRst = 1, - .BleMemStby = 1, - .BleGateClk = 1, - .UsbPwrOff = 1, - .UsbRst = 1, - .UsbMemStby = 1, - .UsbGateClk = 1, - .MiscPwrOff = 0, - .MiscRst = 0, - .MiscMemStby = 1, - .MiscGateClk = 1, - .MiscAnaPwrOff = 1, - .MiscDigPwrOff = 1, - } + .cpuPwrOff = 0, + .cpuRst = 0, + .cpuMemStby = 1, + .cpuGateClk = 1, + .BzPwrOff = 0, + .BzRst = 0, + .BzMemStby = 1, + .BzGateClk = 1, + .BlePwrOff = 1, + .BleRst = 1, + .BleMemStby = 1, + .BleGateClk = 1, + .UsbPwrOff = 1, + .UsbRst = 1, + .UsbMemStby = 1, + .UsbGateClk = 1, + .MiscPwrOff = 0, + .MiscRst = 0, + .MiscMemStby = 1, + .MiscGateClk = 1, + .MiscAnaPwrOff = 1, + .MiscDigPwrOff = 1, + } }; static PDS_DEFAULT_LV_CFG_Type ATTR_TCM_CONST_SECTION pdsCfgLevel2 = { - .pdsCtl = { - .pdsStart = 1, - .sleepForever = 0, - .xtalForceOff = 0, - .saveWifiState = 0, - .dcdc18Off = 1, - .bgSysOff = 1, - .gpioIePuPd = 1, - .puFlash = 0, - .clkOff = 1, - .memStby = 1, - .swPuFlash = 1, - .isolation = 1, - .waitXtalRdy = 0, - .pdsPwrOff = 1, - .xtalOff = 0, - .socEnbForceOn = 1, - .pdsRstSocEn = 0, - .pdsRC32mOn = 0, - .pdsLdoVselEn = 0, - .pdsRamLowPowerWithClkEn = 1, - .cpu0WfiMask = 0, - .ldo11Off = 1, - .pdsForceRamClkEn = 0, - .pdsLdoVol = 0xA, - .pdsCtlRfSel = 2, - .pdsCtlPllSel = 0, - }, - .pdsCtl2 = { - .forceCpuPwrOff = 0, - .forceBzPwrOff = 0, - .forceUsbPwrOff = 0, - .forceCpuIsoEn = 0, - .forceBzIsoEn = 0, - .forceUsbIsoEn = 0, - .forceCpuPdsRst = 0, - .forceBzPdsRst = 0, - .forceUsbPdsRst = 0, - .forceCpuMemStby = 0, - .forceBzMemStby = 0, - .forceUsbMemStby = 0, - .forceCpuGateClk = 0, - .forceBzGateClk = 0, - .forceUsbGateClk = 0, - }, - .pdsCtl3 = { - .forceMiscPwrOff = 0, - .forceBlePwrOff = 0, - .forceBleIsoEn = 0, - .forceMiscPdsRst = 0, - .forceBlePdsRst = 0, - .forceMiscMemStby = 0, - .forceBleMemStby = 0, - .forceMiscGateClk = 0, - .forceBleGateClk = 0, - .CpuIsoEn = 0, - .BzIsoEn = 1, - .BleIsoEn = 1, - .UsbIsoEn = 0, - .MiscIsoEn = 0, - }, + .pdsCtl = + { + .pdsStart = 1, + .sleepForever = 0, + .xtalForceOff = 0, + .saveWifiState = 0, + .dcdc18Off = 1, + .bgSysOff = 1, + .gpioIePuPd = 1, + .puFlash = 0, + .clkOff = 1, + .memStby = 1, + .swPuFlash = 1, + .isolation = 1, + .waitXtalRdy = 0, + .pdsPwrOff = 1, + .xtalOff = 0, + .socEnbForceOn = 1, + .pdsRstSocEn = 0, + .pdsRC32mOn = 0, + .pdsLdoVselEn = 0, + .pdsRamLowPowerWithClkEn = 1, + .cpu0WfiMask = 0, + .ldo11Off = 1, + .pdsForceRamClkEn = 0, + .pdsLdoVol = 0xA, + .pdsCtlRfSel = 2, + .pdsCtlPllSel = 0, + }, + .pdsCtl2 = + { + .forceCpuPwrOff = 0, + .forceBzPwrOff = 0, + .forceUsbPwrOff = 0, + .forceCpuIsoEn = 0, + .forceBzIsoEn = 0, + .forceUsbIsoEn = 0, + .forceCpuPdsRst = 0, + .forceBzPdsRst = 0, + .forceUsbPdsRst = 0, + .forceCpuMemStby = 0, + .forceBzMemStby = 0, + .forceUsbMemStby = 0, + .forceCpuGateClk = 0, + .forceBzGateClk = 0, + .forceUsbGateClk = 0, + }, + .pdsCtl3 = + { + .forceMiscPwrOff = 0, + .forceBlePwrOff = 0, + .forceBleIsoEn = 0, + .forceMiscPdsRst = 0, + .forceBlePdsRst = 0, + .forceMiscMemStby = 0, + .forceBleMemStby = 0, + .forceMiscGateClk = 0, + .forceBleGateClk = 0, + .CpuIsoEn = 0, + .BzIsoEn = 1, + .BleIsoEn = 1, + .UsbIsoEn = 0, + .MiscIsoEn = 0, + }, .pdsCtl4 = { - .cpuPwrOff = 0, - .cpuRst = 0, - .cpuMemStby = 1, - .cpuGateClk = 1, - .BzPwrOff = 1, - .BzRst = 1, - .BzMemStby = 1, - .BzGateClk = 1, - .BlePwrOff = 1, - .BleRst = 1, - .BleMemStby = 1, - .BleGateClk = 1, - .UsbPwrOff = 0, - .UsbRst = 0, - .UsbMemStby = 1, - .UsbGateClk = 1, - .MiscPwrOff = 0, - .MiscRst = 0, - .MiscMemStby = 1, - .MiscGateClk = 1, - .MiscAnaPwrOff = 1, - .MiscDigPwrOff = 1, - } + .cpuPwrOff = 0, + .cpuRst = 0, + .cpuMemStby = 1, + .cpuGateClk = 1, + .BzPwrOff = 1, + .BzRst = 1, + .BzMemStby = 1, + .BzGateClk = 1, + .BlePwrOff = 1, + .BleRst = 1, + .BleMemStby = 1, + .BleGateClk = 1, + .UsbPwrOff = 0, + .UsbRst = 0, + .UsbMemStby = 1, + .UsbGateClk = 1, + .MiscPwrOff = 0, + .MiscRst = 0, + .MiscMemStby = 1, + .MiscGateClk = 1, + .MiscAnaPwrOff = 1, + .MiscDigPwrOff = 1, + } }; static PDS_DEFAULT_LV_CFG_Type ATTR_TCM_CONST_SECTION pdsCfgLevel3 = { - .pdsCtl = { - .pdsStart = 1, - .sleepForever = 0, - .xtalForceOff = 0, - .saveWifiState = 0, - .dcdc18Off = 1, - .bgSysOff = 1, - .gpioIePuPd = 1, - .puFlash = 0, - .clkOff = 1, - .memStby = 1, - .swPuFlash = 1, - .isolation = 1, - .waitXtalRdy = 0, - .pdsPwrOff = 1, - .xtalOff = 0, - .socEnbForceOn = 1, - .pdsRstSocEn = 0, - .pdsRC32mOn = 0, - .pdsLdoVselEn = 0, - .pdsRamLowPowerWithClkEn = 1, - .cpu0WfiMask = 0, - .ldo11Off = 1, - .pdsForceRamClkEn = 0, - .pdsLdoVol = 0xA, - .pdsCtlRfSel = 2, - .pdsCtlPllSel = 0, - }, - .pdsCtl2 = { - .forceCpuPwrOff = 0, - .forceBzPwrOff = 0, - .forceUsbPwrOff = 0, - .forceCpuIsoEn = 0, - .forceBzIsoEn = 0, - .forceUsbIsoEn = 0, - .forceCpuPdsRst = 0, - .forceBzPdsRst = 0, - .forceUsbPdsRst = 0, - .forceCpuMemStby = 0, - .forceBzMemStby = 0, - .forceUsbMemStby = 0, - .forceCpuGateClk = 0, - .forceBzGateClk = 0, - .forceUsbGateClk = 0, - }, - .pdsCtl3 = { - .forceMiscPwrOff = 0, - .forceBlePwrOff = 0, - .forceBleIsoEn = 0, - .forceMiscPdsRst = 0, - .forceBlePdsRst = 0, - .forceMiscMemStby = 0, - .forceBleMemStby = 0, - .forceMiscGateClk = 0, - .forceBleGateClk = 0, - .CpuIsoEn = 0, - .BzIsoEn = 1, - .BleIsoEn = 1, - .UsbIsoEn = 1, - .MiscIsoEn = 0, - }, + .pdsCtl = + { + .pdsStart = 1, + .sleepForever = 0, + .xtalForceOff = 0, + .saveWifiState = 0, + .dcdc18Off = 1, + .bgSysOff = 1, + .gpioIePuPd = 1, + .puFlash = 0, + .clkOff = 1, + .memStby = 1, + .swPuFlash = 1, + .isolation = 1, + .waitXtalRdy = 0, + .pdsPwrOff = 1, + .xtalOff = 0, + .socEnbForceOn = 1, + .pdsRstSocEn = 0, + .pdsRC32mOn = 0, + .pdsLdoVselEn = 0, + .pdsRamLowPowerWithClkEn = 1, + .cpu0WfiMask = 0, + .ldo11Off = 1, + .pdsForceRamClkEn = 0, + .pdsLdoVol = 0xA, + .pdsCtlRfSel = 2, + .pdsCtlPllSel = 0, + }, + .pdsCtl2 = + { + .forceCpuPwrOff = 0, + .forceBzPwrOff = 0, + .forceUsbPwrOff = 0, + .forceCpuIsoEn = 0, + .forceBzIsoEn = 0, + .forceUsbIsoEn = 0, + .forceCpuPdsRst = 0, + .forceBzPdsRst = 0, + .forceUsbPdsRst = 0, + .forceCpuMemStby = 0, + .forceBzMemStby = 0, + .forceUsbMemStby = 0, + .forceCpuGateClk = 0, + .forceBzGateClk = 0, + .forceUsbGateClk = 0, + }, + .pdsCtl3 = + { + .forceMiscPwrOff = 0, + .forceBlePwrOff = 0, + .forceBleIsoEn = 0, + .forceMiscPdsRst = 0, + .forceBlePdsRst = 0, + .forceMiscMemStby = 0, + .forceBleMemStby = 0, + .forceMiscGateClk = 0, + .forceBleGateClk = 0, + .CpuIsoEn = 0, + .BzIsoEn = 1, + .BleIsoEn = 1, + .UsbIsoEn = 1, + .MiscIsoEn = 0, + }, .pdsCtl4 = { - .cpuPwrOff = 0, - .cpuRst = 0, - .cpuMemStby = 1, - .cpuGateClk = 1, - .BzPwrOff = 1, - .BzRst = 1, - .BzMemStby = 1, - .BzGateClk = 1, - .BlePwrOff = 1, - .BleRst = 1, - .BleMemStby = 1, - .BleGateClk = 1, - .UsbPwrOff = 1, - .UsbRst = 1, - .UsbMemStby = 1, - .UsbGateClk = 1, - .MiscPwrOff = 0, - .MiscRst = 0, - .MiscMemStby = 1, - .MiscGateClk = 1, - .MiscAnaPwrOff = 1, - .MiscDigPwrOff = 1, - } + .cpuPwrOff = 0, + .cpuRst = 0, + .cpuMemStby = 1, + .cpuGateClk = 1, + .BzPwrOff = 1, + .BzRst = 1, + .BzMemStby = 1, + .BzGateClk = 1, + .BlePwrOff = 1, + .BleRst = 1, + .BleMemStby = 1, + .BleGateClk = 1, + .UsbPwrOff = 1, + .UsbRst = 1, + .UsbMemStby = 1, + .UsbGateClk = 1, + .MiscPwrOff = 0, + .MiscRst = 0, + .MiscMemStby = 1, + .MiscGateClk = 1, + .MiscAnaPwrOff = 1, + .MiscDigPwrOff = 1, + } }; #if 0 static PDS_DEFAULT_LV_CFG_Type ATTR_TCM_CONST_SECTION pdsCfgLevel4 = { @@ -753,91 +765,94 @@ static PDS_DEFAULT_LV_CFG_Type ATTR_TCM_CONST_SECTION pdsCfgLevel7 = { }; #endif static PDS_DEFAULT_LV_CFG_Type ATTR_TCM_CONST_SECTION pdsCfgLevel31 = { - .pdsCtl = { - .pdsStart = 1, - .sleepForever = 0, - .xtalForceOff = 0, - .saveWifiState = 0, - .dcdc18Off = 1, - .bgSysOff = 1, - .gpioIePuPd = 1, - .puFlash = 0, - .clkOff = 1, - .memStby = 1, - .swPuFlash = 1, - .isolation = 1, - .waitXtalRdy = 0, - .pdsPwrOff = 1, - .xtalOff = 0, - .socEnbForceOn = 0, - .pdsRstSocEn = 0, - .pdsRC32mOn = 0, - .pdsLdoVselEn = 0, - .pdsRamLowPowerWithClkEn = 1, - .cpu0WfiMask = 0, - .ldo11Off = 1, - .pdsForceRamClkEn = 0, - .pdsLdoVol = 0xA, - .pdsCtlRfSel = 2, - .pdsCtlPllSel = 0, - }, - .pdsCtl2 = { - .forceCpuPwrOff = 0, - .forceBzPwrOff = 0, - .forceUsbPwrOff = 0, - .forceCpuIsoEn = 0, - .forceBzIsoEn = 0, - .forceUsbIsoEn = 0, - .forceCpuPdsRst = 0, - .forceBzPdsRst = 0, - .forceUsbPdsRst = 0, - .forceCpuMemStby = 0, - .forceBzMemStby = 0, - .forceUsbMemStby = 0, - .forceCpuGateClk = 0, - .forceBzGateClk = 0, - .forceUsbGateClk = 0, - }, - .pdsCtl3 = { - .forceMiscPwrOff = 0, - .forceBlePwrOff = 0, - .forceBleIsoEn = 0, - .forceMiscPdsRst = 0, - .forceBlePdsRst = 0, - .forceMiscMemStby = 0, - .forceBleMemStby = 0, - .forceMiscGateClk = 0, - .forceBleGateClk = 0, - .CpuIsoEn = 1, - .BzIsoEn = 1, - .BleIsoEn = 1, - .UsbIsoEn = 1, - .MiscIsoEn = 1, - }, + .pdsCtl = + { + .pdsStart = 1, + .sleepForever = 0, + .xtalForceOff = 0, + .saveWifiState = 0, + .dcdc18Off = 1, + .bgSysOff = 1, + .gpioIePuPd = 1, + .puFlash = 0, + .clkOff = 1, + .memStby = 1, + .swPuFlash = 1, + .isolation = 1, + .waitXtalRdy = 0, + .pdsPwrOff = 1, + .xtalOff = 0, + .socEnbForceOn = 0, + .pdsRstSocEn = 0, + .pdsRC32mOn = 0, + .pdsLdoVselEn = 0, + .pdsRamLowPowerWithClkEn = 1, + .cpu0WfiMask = 0, + .ldo11Off = 1, + .pdsForceRamClkEn = 0, + .pdsLdoVol = 0xA, + .pdsCtlRfSel = 2, + .pdsCtlPllSel = 0, + }, + .pdsCtl2 = + { + .forceCpuPwrOff = 0, + .forceBzPwrOff = 0, + .forceUsbPwrOff = 0, + .forceCpuIsoEn = 0, + .forceBzIsoEn = 0, + .forceUsbIsoEn = 0, + .forceCpuPdsRst = 0, + .forceBzPdsRst = 0, + .forceUsbPdsRst = 0, + .forceCpuMemStby = 0, + .forceBzMemStby = 0, + .forceUsbMemStby = 0, + .forceCpuGateClk = 0, + .forceBzGateClk = 0, + .forceUsbGateClk = 0, + }, + .pdsCtl3 = + { + .forceMiscPwrOff = 0, + .forceBlePwrOff = 0, + .forceBleIsoEn = 0, + .forceMiscPdsRst = 0, + .forceBlePdsRst = 0, + .forceMiscMemStby = 0, + .forceBleMemStby = 0, + .forceMiscGateClk = 0, + .forceBleGateClk = 0, + .CpuIsoEn = 1, + .BzIsoEn = 1, + .BleIsoEn = 1, + .UsbIsoEn = 1, + .MiscIsoEn = 1, + }, .pdsCtl4 = { - .cpuPwrOff = 1, - .cpuRst = 1, - .cpuMemStby = 1, - .cpuGateClk = 1, - .BzPwrOff = 1, - .BzRst = 1, - .BzMemStby = 1, - .BzGateClk = 1, - .BlePwrOff = 1, - .BleRst = 1, - .BleMemStby = 1, - .BleGateClk = 1, - .UsbPwrOff = 1, - .UsbRst = 1, - .UsbMemStby = 1, - .UsbGateClk = 1, - .MiscPwrOff = 1, - .MiscRst = 1, - .MiscMemStby = 1, - .MiscGateClk = 1, - .MiscAnaPwrOff = 1, - .MiscDigPwrOff = 1, - } + .cpuPwrOff = 1, + .cpuRst = 1, + .cpuMemStby = 1, + .cpuGateClk = 1, + .BzPwrOff = 1, + .BzRst = 1, + .BzMemStby = 1, + .BzGateClk = 1, + .BlePwrOff = 1, + .BleRst = 1, + .BleMemStby = 1, + .BleGateClk = 1, + .UsbPwrOff = 1, + .UsbRst = 1, + .UsbMemStby = 1, + .UsbGateClk = 1, + .MiscPwrOff = 1, + .MiscRst = 1, + .MiscMemStby = 1, + .MiscGateClk = 1, + .MiscAnaPwrOff = 1, + .MiscDigPwrOff = 1, + } }; /****************************************************************************/ /** diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_ecdsa.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_ecdsa.c index 92e423c018..c41b03f8da 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_ecdsa.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_ecdsa.c @@ -23,8 +23,8 @@ #define secp256r1 #define secp256k1 -#define SEC_ECC_POINT_MUL_PARAM_CFG(G) \ - sec_ecc_point_mul_cfg((uint32_t *)G##P, (uint32_t *)G##PrimeN_P, (uint32_t *)G##_1, (uint32_t *)G##_BAR2, (uint32_t *)G##_BAR3, (uint32_t *)G##_BAR4, (uint32_t *)G##_BAR8, (uint32_t *)G##_1P1, \ +#define SEC_ECC_POINT_MUL_PARAM_CFG(G) \ + sec_ecc_point_mul_cfg((uint32_t *)G##P, (uint32_t *)G##PrimeN_P, (uint32_t *)G##_1, (uint32_t *)G##_BAR2, (uint32_t *)G##_BAR3, (uint32_t *)G##_BAR4, (uint32_t *)G##_BAR8, (uint32_t *)G##_1P1, \ (uint32_t *)G##_1M1) #define SEC_ECC_BASIC_PARAM_CFG(G) sec_ecc_basic_parameter_cfg((uint32_t *)G##N, (uint32_t *)G##PrimeN_N, (uint32_t *)G##InvR_N) @@ -35,88 +35,88 @@ void bflb_platform_dump(uint8_t *data, uint32_t len); uint32_t pka_tmp[32] = {0}; #endif /********************************************** secp256r1 *******************************************/ -const uint8_t secp256r1P[32] ALIGN4 - = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; -const uint8_t secp256r1B[32] ALIGN4 - = {0x5a, 0xc6, 0x35, 0xd8, 0xaa, 0x3a, 0x93, 0xe7, 0xb3, 0xeb, 0xbd, 0x55, 0x76, 0x98, 0x86, 0xbc, 0x65, 0x1d, 0x06, 0xb0, 0xcc, 0x53, 0xb0, 0xf6, 0x3b, 0xce, 0x3c, 0x3e, 0x27, 0xd2, 0x60, 0x4b}; -const uint8_t secp256r1Gx[32] ALIGN4 - = {0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47, 0xf8, 0xbc, 0xe6, 0xe5, 0x63, 0xa4, 0x40, 0xf2, 0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb, 0x33, 0xa0, 0xf4, 0xa1, 0x39, 0x45, 0xd8, 0x98, 0xc2, 0x96}; -const uint8_t secp256r1Gy[32] ALIGN4 - = {0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16, 0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5}; -const uint8_t secp256r1N[32] ALIGN4 - = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51}; -const uint8_t secp256r1PrimeN_N[32] ALIGN4 - = {0x60, 0xd0, 0x66, 0x33, 0xa9, 0xd6, 0x28, 0x1c, 0x50, 0xfe, 0x77, 0xec, 0xc5, 0x88, 0xc6, 0xf6, 0x48, 0xc9, 0x44, 0x08, 0x7d, 0x74, 0xd2, 0xe4, 0xcc, 0xd1, 0xc8, 0xaa, 0xee, 0x00, 0xbc, 0x4f}; -const uint8_t secp256r1InvR_N[32] ALIGN4 - = {0x60, 0xd0, 0x66, 0x33, 0x49, 0x05, 0xc1, 0xe9, 0x07, 0xf8, 0xb6, 0x04, 0x1e, 0x60, 0x77, 0x25, 0xba, 0xde, 0xf3, 0xe2, 0x43, 0x56, 0x6f, 0xaf, 0xce, 0x1b, 0xc8, 0xf7, 0x9c, 0x19, 0x7c, 0x79}; -const uint8_t secp256r1PrimeN_P[32] ALIGN4 - = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; -const uint8_t secp256r1InvR_P[32] ALIGN4 - = {0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xfd, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00}; -const uint8_t secp256r1_1[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; -const uint8_t secp256r1_BAR2[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}; -const uint8_t secp256r1_BAR3[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x02, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03}; -const uint8_t secp256r1_BAR4[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04}; -const uint8_t secp256r1_BAR8[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x07, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08}; -const uint8_t secp256r1_1P1[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}; -const uint8_t secp256r1_1M1[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; -const uint8_t secp256r1_Zerox[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; -const uint8_t secp256r1_Zeroy[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; -const uint8_t secp256r1_Gx[32] ALIGN4 - = {0x18, 0x90, 0x5f, 0x76, 0xa5, 0x37, 0x55, 0xc6, 0x79, 0xfb, 0x73, 0x2b, 0x77, 0x62, 0x25, 0x10, 0x75, 0xba, 0x95, 0xfc, 0x5f, 0xed, 0xb6, 0x01, 0x79, 0xe7, 0x30, 0xd4, 0x18, 0xa9, 0x14, 0x3c}; -const uint8_t secp256r1_Gy[32] ALIGN4 - = {0x85, 0x71, 0xff, 0x18, 0x25, 0x88, 0x5d, 0x85, 0xd2, 0xe8, 0x86, 0x88, 0xdd, 0x21, 0xf3, 0x25, 0x8b, 0x4a, 0xb8, 0xe4, 0xba, 0x19, 0xe4, 0x5c, 0xdd, 0xf2, 0x53, 0x57, 0xce, 0x95, 0x56, 0x0a}; +const uint8_t secp256r1P[32] ALIGN4 = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; +const uint8_t secp256r1B[32] ALIGN4 = {0x5a, 0xc6, 0x35, 0xd8, 0xaa, 0x3a, 0x93, 0xe7, 0xb3, 0xeb, 0xbd, 0x55, 0x76, 0x98, 0x86, 0xbc, + 0x65, 0x1d, 0x06, 0xb0, 0xcc, 0x53, 0xb0, 0xf6, 0x3b, 0xce, 0x3c, 0x3e, 0x27, 0xd2, 0x60, 0x4b}; +const uint8_t secp256r1Gx[32] ALIGN4 = {0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47, 0xf8, 0xbc, 0xe6, 0xe5, 0x63, 0xa4, 0x40, 0xf2, + 0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb, 0x33, 0xa0, 0xf4, 0xa1, 0x39, 0x45, 0xd8, 0x98, 0xc2, 0x96}; +const uint8_t secp256r1Gy[32] ALIGN4 = {0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16, + 0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5}; +const uint8_t secp256r1N[32] ALIGN4 = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51}; +const uint8_t secp256r1PrimeN_N[32] ALIGN4 = {0x60, 0xd0, 0x66, 0x33, 0xa9, 0xd6, 0x28, 0x1c, 0x50, 0xfe, 0x77, 0xec, 0xc5, 0x88, 0xc6, 0xf6, + 0x48, 0xc9, 0x44, 0x08, 0x7d, 0x74, 0xd2, 0xe4, 0xcc, 0xd1, 0xc8, 0xaa, 0xee, 0x00, 0xbc, 0x4f}; +const uint8_t secp256r1InvR_N[32] ALIGN4 = {0x60, 0xd0, 0x66, 0x33, 0x49, 0x05, 0xc1, 0xe9, 0x07, 0xf8, 0xb6, 0x04, 0x1e, 0x60, 0x77, 0x25, + 0xba, 0xde, 0xf3, 0xe2, 0x43, 0x56, 0x6f, 0xaf, 0xce, 0x1b, 0xc8, 0xf7, 0x9c, 0x19, 0x7c, 0x79}; +const uint8_t secp256r1PrimeN_P[32] ALIGN4 = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; +const uint8_t secp256r1InvR_P[32] ALIGN4 = {0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xfd, 0x00, 0x00, 0x00, 0x02, + 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00}; +const uint8_t secp256r1_1[32] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; +const uint8_t secp256r1_BAR2[32] ALIGN4 = {0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}; +const uint8_t secp256r1_BAR3[32] ALIGN4 = {0x00, 0x00, 0x00, 0x02, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03}; +const uint8_t secp256r1_BAR4[32] ALIGN4 = {0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04}; +const uint8_t secp256r1_BAR8[32] ALIGN4 = {0x00, 0x00, 0x00, 0x07, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08}; +const uint8_t secp256r1_1P1[32] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}; +const uint8_t secp256r1_1M1[32] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +const uint8_t secp256r1_Zerox[32] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +const uint8_t secp256r1_Zeroy[32] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; +const uint8_t secp256r1_Gx[32] ALIGN4 = {0x18, 0x90, 0x5f, 0x76, 0xa5, 0x37, 0x55, 0xc6, 0x79, 0xfb, 0x73, 0x2b, 0x77, 0x62, 0x25, 0x10, + 0x75, 0xba, 0x95, 0xfc, 0x5f, 0xed, 0xb6, 0x01, 0x79, 0xe7, 0x30, 0xd4, 0x18, 0xa9, 0x14, 0x3c}; +const uint8_t secp256r1_Gy[32] ALIGN4 = {0x85, 0x71, 0xff, 0x18, 0x25, 0x88, 0x5d, 0x85, 0xd2, 0xe8, 0x86, 0x88, 0xdd, 0x21, 0xf3, 0x25, + 0x8b, 0x4a, 0xb8, 0xe4, 0xba, 0x19, 0xe4, 0x5c, 0xdd, 0xf2, 0x53, 0x57, 0xce, 0x95, 0x56, 0x0a}; /********************************************** secp256k1 *******************************************/ -const uint8_t secp256k1P[32] ALIGN4 - = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFC, 0x2F}; -const uint8_t secp256k1B[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07}; -const uint8_t secp256k1Gx[32] ALIGN4 - = {0x79, 0xBE, 0x66, 0x7E, 0xF9, 0xDC, 0xBB, 0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE, 0x87, 0x0B, 0x07, 0x02, 0x9B, 0xFC, 0xDB, 0x2D, 0xCE, 0x28, 0xD9, 0x59, 0xF2, 0x81, 0x5B, 0x16, 0xF8, 0x17, 0x98}; -const uint8_t secp256k1Gy[32] ALIGN4 - = {0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16, 0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5}; -const uint8_t secp256k1N[32] ALIGN4 - = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41}; -const uint8_t secp256k1PrimeN_N[32] ALIGN4 - = {0xd9, 0xe8, 0x89, 0xd, 0x64, 0x94, 0xef, 0x93, 0x89, 0x7f, 0x30, 0xc1, 0x27, 0xcf, 0xab, 0x5e, 0x50, 0xa5, 0x1a, 0xc8, 0x34, 0xb9, 0xec, 0x24, 0x4b, 0xd, 0xff, 0x66, 0x55, 0x88, 0xb1, 0x3f}; -const uint8_t secp256k1InvR_N[32] ALIGN4 - = {0xd9, 0xe8, 0x89, 0xd, 0x64, 0x94, 0xef, 0x93, 0x89, 0x7f, 0x30, 0xc1, 0x27, 0xcf, 0xab, 0x5d, 0x3b, 0xbb, 0xd4, 0x56, 0x7f, 0xa5, 0xc, 0x3c, 0x80, 0xfd, 0x22, 0x93, 0x80, 0x97, 0xc0, 0x16}; -const uint8_t secp256k1PrimeN_P[32] ALIGN4 - = {0xc9, 0xbd, 0x19, 0x5, 0x15, 0x53, 0x83, 0x99, 0x9c, 0x46, 0xc2, 0xc2, 0x95, 0xf2, 0xb7, 0x61, 0xbc, 0xb2, 0x23, 0xfe, 0xdc, 0x24, 0xa0, 0x59, 0xd8, 0x38, 0x9, 0x1d, 0xd2, 0x25, 0x35, 0x31}; -const uint8_t secp256k1InvR_P[32] ALIGN4 - = {0xc9, 0xbd, 0x19, 0x5, 0x15, 0x53, 0x83, 0x99, 0x9c, 0x46, 0xc2, 0xc2, 0x95, 0xf2, 0xb7, 0x61, 0xbc, 0xb2, 0x23, 0xfe, 0xdc, 0x24, 0xa0, 0x59, 0xd8, 0x38, 0x9, 0x1d, 0x8, 0x68, 0x19, 0x2a}; -const uint8_t secp256k1_1[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; -const uint8_t secp256k1_BAR2[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x07, 0xa2}; -const uint8_t secp256k1_BAR3[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x0b, 0x73}; -const uint8_t secp256k1_BAR4[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x0f, 0x44}; -const uint8_t secp256k1_BAR8[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x1e, 0x88}; -const uint8_t secp256k1_1P1[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd2}; -const uint8_t secp256k1_1M1[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd0}; -const uint8_t secp256k1_Zerox[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; -const uint8_t secp256k1_Zeroy[32] ALIGN4 - = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd1}; -const uint8_t secp256k1_Gx[32] ALIGN4 - = {0x99, 0x81, 0xe6, 0x43, 0xe9, 0x08, 0x9f, 0x48, 0x97, 0x9f, 0x48, 0xc0, 0x33, 0xfd, 0x12, 0x9c, 0x23, 0x1e, 0x29, 0x53, 0x29, 0xbc, 0x66, 0xdb, 0xd7, 0x36, 0x2e, 0x5a, 0x48, 0x7e, 0x20, 0x97}; -const uint8_t secp256k1_Gy[32] ALIGN4 - = {0xcf, 0x3f, 0x85, 0x1f, 0xd4, 0xa5, 0x82, 0xd6, 0x70, 0xb6, 0xb5, 0x9a, 0xac, 0x19, 0xc1, 0x36, 0x8d, 0xfc, 0x5d, 0x5d, 0x1f, 0x1d, 0xc6, 0x4d, 0xb1, 0x5e, 0xa6, 0xd2, 0xd3, 0xdb, 0xab, 0xe2}; +const uint8_t secp256k1P[32] ALIGN4 = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFC, 0x2F}; +const uint8_t secp256k1B[32] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07}; +const uint8_t secp256k1Gx[32] ALIGN4 = {0x79, 0xBE, 0x66, 0x7E, 0xF9, 0xDC, 0xBB, 0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE, 0x87, 0x0B, 0x07, + 0x02, 0x9B, 0xFC, 0xDB, 0x2D, 0xCE, 0x28, 0xD9, 0x59, 0xF2, 0x81, 0x5B, 0x16, 0xF8, 0x17, 0x98}; +const uint8_t secp256k1Gy[32] ALIGN4 = {0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16, + 0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5}; +const uint8_t secp256k1N[32] ALIGN4 = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, + 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41}; +const uint8_t secp256k1PrimeN_N[32] ALIGN4 = {0xd9, 0xe8, 0x89, 0xd, 0x64, 0x94, 0xef, 0x93, 0x89, 0x7f, 0x30, 0xc1, 0x27, 0xcf, 0xab, 0x5e, + 0x50, 0xa5, 0x1a, 0xc8, 0x34, 0xb9, 0xec, 0x24, 0x4b, 0xd, 0xff, 0x66, 0x55, 0x88, 0xb1, 0x3f}; +const uint8_t secp256k1InvR_N[32] ALIGN4 = {0xd9, 0xe8, 0x89, 0xd, 0x64, 0x94, 0xef, 0x93, 0x89, 0x7f, 0x30, 0xc1, 0x27, 0xcf, 0xab, 0x5d, + 0x3b, 0xbb, 0xd4, 0x56, 0x7f, 0xa5, 0xc, 0x3c, 0x80, 0xfd, 0x22, 0x93, 0x80, 0x97, 0xc0, 0x16}; +const uint8_t secp256k1PrimeN_P[32] ALIGN4 = {0xc9, 0xbd, 0x19, 0x5, 0x15, 0x53, 0x83, 0x99, 0x9c, 0x46, 0xc2, 0xc2, 0x95, 0xf2, 0xb7, 0x61, + 0xbc, 0xb2, 0x23, 0xfe, 0xdc, 0x24, 0xa0, 0x59, 0xd8, 0x38, 0x9, 0x1d, 0xd2, 0x25, 0x35, 0x31}; +const uint8_t secp256k1InvR_P[32] ALIGN4 = {0xc9, 0xbd, 0x19, 0x5, 0x15, 0x53, 0x83, 0x99, 0x9c, 0x46, 0xc2, 0xc2, 0x95, 0xf2, 0xb7, 0x61, + 0xbc, 0xb2, 0x23, 0xfe, 0xdc, 0x24, 0xa0, 0x59, 0xd8, 0x38, 0x9, 0x1d, 0x8, 0x68, 0x19, 0x2a}; +const uint8_t secp256k1_1[32] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; +const uint8_t secp256k1_BAR2[32] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x07, 0xa2}; +const uint8_t secp256k1_BAR3[32] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x0b, 0x73}; +const uint8_t secp256k1_BAR4[32] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x0f, 0x44}; +const uint8_t secp256k1_BAR8[32] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x1e, 0x88}; +const uint8_t secp256k1_1P1[32] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd2}; +const uint8_t secp256k1_1M1[32] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd0}; +const uint8_t secp256k1_Zerox[32] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +const uint8_t secp256k1_Zeroy[32] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd1}; +const uint8_t secp256k1_Gx[32] ALIGN4 = {0x99, 0x81, 0xe6, 0x43, 0xe9, 0x08, 0x9f, 0x48, 0x97, 0x9f, 0x48, 0xc0, 0x33, 0xfd, 0x12, 0x9c, + 0x23, 0x1e, 0x29, 0x53, 0x29, 0xbc, 0x66, 0xdb, 0xd7, 0x36, 0x2e, 0x5a, 0x48, 0x7e, 0x20, 0x97}; +const uint8_t secp256k1_Gy[32] ALIGN4 = {0xcf, 0x3f, 0x85, 0x1f, 0xd4, 0xa5, 0x82, 0xd6, 0x70, 0xb6, 0xb5, 0x9a, 0xac, 0x19, 0xc1, 0x36, + 0x8d, 0xfc, 0x5d, 0x5d, 0x1f, 0x1d, 0xc6, 0x4d, 0xb1, 0x5e, 0xa6, 0xd2, 0xd3, 0xdb, 0xab, 0xe2}; static BL_Err_Type sec_ecc_basic_parameter_cfg(uint32_t *n, uint32_t *prime_n, uint32_t *invr_n) { Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)n, ECP_SECP256R1_SIZE / 4, 0); diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c index 5a69576979..5b7b37c05e 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c @@ -90,7 +90,8 @@ int uart_open(struct device *dev, uint16_t oflag) { fifoCfg.rxFifoDmaThreshold = uart_device->fifo_threshold; fifoCfg.rxFifoDmaEnable = DISABLE; - if (oflag & DEVICE_OFLAG_STREAM_TX) {} + if (oflag & DEVICE_OFLAG_STREAM_TX) { + } if ((oflag & DEVICE_OFLAG_INT_TX) || (oflag & DEVICE_OFLAG_INT_RX)) { #ifdef BSP_USING_UART0 if (uart_device->id == UART0_ID) { diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c index 5c50725bf7..0491bc7109 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c @@ -1107,7 +1107,8 @@ void usb_dc_isr(usb_dc_device_t *device) { if (USB_Get_IntStatus(USB_INT_LPM_PACKET)) { /*************************************/ /* Force low-power mode in the macrocell */ - if (USB_Get_IntStatus(USB_INT_LPM_WAKEUP) == 0) {} + if (USB_Get_IntStatus(USB_INT_LPM_WAKEUP) == 0) { + } /*************************************/ USB_Clr_IntStatus(USB_INT_LPM_PACKET); diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c index 9de2920bc4..a073e57d9d 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c @@ -47,7 +47,8 @@ static inline void mmheap_insert_node_to_freelist(struct heap_info *pRoot, struc struct heap_node *pPriv_Node; struct heap_node *pNext_Node; /*Find the node with an address similar to pNode*/ - for (pPriv_Node = pRoot->pStart; pPriv_Node->next_node < pNode; pPriv_Node = pPriv_Node->next_node) {} + for (pPriv_Node = pRoot->pStart; pPriv_Node->next_node < pNode; pPriv_Node = pPriv_Node->next_node) { + } pNext_Node = pPriv_Node->next_node; /*Try to merge the pNode with the previous block*/ @@ -248,7 +249,8 @@ void *mmheap_realloc(struct heap_info *pRoot, void *src_addr, size_t want_size) return pReturn; } /*Start looking in the free list for blocks similar to this block*/ - for (pPriv_Node = pRoot->pStart; pPriv_Node->next_node < pSrc_Node; pPriv_Node = pPriv_Node->next_node) {} + for (pPriv_Node = pRoot->pStart; pPriv_Node->next_node < pSrc_Node; pPriv_Node = pPriv_Node->next_node) { + } pNext_Node = pPriv_Node->next_node; if (pNext_Node != pRoot->pEnd && ((uint8_t *)src_addr + pSrc_Node->mem_size == (uint8_t *)pNext_Node) && (pSrc_Node->mem_size + pNext_Node->mem_size + MEM_MANAGE_MEM_STRUCT_SIZE >= want_size)) { diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c index 131a3d2aad..65f2f55f4d 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c @@ -184,7 +184,8 @@ void vAssertCalled(void) { // PWM_Channel_Disable(PWM_Channel); // gpio_set_mode(PWM_Out_Pin, GPIO_INPUT_PD_MODE); - while (1) {} + while (1) { + } } void Trap_Handler(void) { @@ -254,7 +255,8 @@ void Trap_Handler(void) { } if (!isecall) { - while (1) {} + while (1) { + } } } @@ -286,7 +288,8 @@ void Interrupt_Handler(void) { MSG("Peripheral Interrupt num:%d \r\n", (unsigned int)num - IRQ_NUM_BASE); } - while (1) {} + while (1) { + } } } else { MSG("Unexpected interrupt num:%d\r\n", (unsigned int)num); diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_adc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_adc.c index e4bd821370..ce425225e9 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_adc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_adc.c @@ -50,16 +50,16 @@ */ #undef MSG #define MSG(...) -#define AON_CLK_SET_DUMMY_WAIT \ - { \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ +#define AON_CLK_SET_DUMMY_WAIT \ + { \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ } #define ADC_RESTART_DUMMY_WAIT BL702_Delay_US(100) diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_aon.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_aon.c index 477cad311e..4e3c276da0 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_aon.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_aon.c @@ -47,16 +47,16 @@ /** @defgroup AON_Private_Macros * @{ */ -#define AON_CLK_SET_DUMMY_WAIT \ - { \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ +#define AON_CLK_SET_DUMMY_WAIT \ + { \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ } /*@} end of group AON_Private_Macros */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dac.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dac.c index fc8ea68eae..296126224f 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dac.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dac.c @@ -47,16 +47,16 @@ /** @defgroup DAC_Private_Macros * @{ */ -#define GPIP_CLK_SET_DUMMY_WAIT \ - { \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ +#define GPIP_CLK_SET_DUMMY_WAIT \ + { \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ } /*@} end of group DAC_Private_Macros */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dma.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dma.c index 5c7cb93d7d..7a30d1f281 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dma.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dma.c @@ -52,7 +52,12 @@ */ #define DMA_CHANNEL_OFFSET 0x100 #define DMA_Get_Channel(ch) (DMA_BASE + DMA_CHANNEL_OFFSET + (ch) * 0x100) -static intCallback_Type *dmaIntCbfArra[DMA_CH_MAX][DMA_INT_ALL] = {{NULL, NULL}, {NULL, NULL}, {NULL, NULL}, {NULL, NULL}}; +static intCallback_Type *dmaIntCbfArra[DMA_CH_MAX][DMA_INT_ALL] = { + {NULL, NULL}, + {NULL, NULL}, + {NULL, NULL}, + {NULL, NULL} +}; static DMA_LLI_Ctrl_Type PingPongListArra[DMA_CH_MAX][2]; /*@} end of group DMA_Private_Macros */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ef_ctrl.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ef_ctrl.c index 01d9917390..2db7810d4e 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ef_ctrl.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ef_ctrl.c @@ -111,9 +111,9 @@ __WEAK } } - tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) - | (EF_CTRL_SAHB_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) - | (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); + tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) | + (EF_CTRL_SAHB_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) | + (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); BL_WR_REG(EF_CTRL_BASE, EF_CTRL_EF_IF_CTRL_0, tmpVal); } @@ -131,24 +131,24 @@ static void EF_Ctrl_Program_Efuse_0(void) { uint32_t tmpVal; /* Select auto mode and select ef clock */ - tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) - | (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) - | (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); + tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) | + (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) | + (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); BL_WR_REG(EF_CTRL_BASE, EF_CTRL_EF_IF_CTRL_0, tmpVal); /* Program */ - tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) - | (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (1 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) - | (1 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); + tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) | + (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (1 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) | + (1 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); BL_WR_REG(EF_CTRL_BASE, EF_CTRL_EF_IF_CTRL_0, tmpVal); /* Add delay for POR to be stable */ BL702_Delay_US(4); /* Trigger */ - tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) - | (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (1 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) - | (1 << EF_CTRL_EF_IF_0_RW_POS) | (1 << EF_CTRL_EF_IF_0_TRIG_POS); + tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) | + (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (1 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) | + (1 << EF_CTRL_EF_IF_0_RW_POS) | (1 << EF_CTRL_EF_IF_0_TRIG_POS); BL_WR_REG(EF_CTRL_BASE, EF_CTRL_EF_IF_CTRL_0, tmpVal); } @@ -175,14 +175,14 @@ void ATTR_TCM_SECTION EF_Ctrl_Load_Efuse_R0(void) { EF_CTRL_DATA0_CLEAR; /* Trigger read */ - tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) - | (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) - | (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); + tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) | + (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) | + (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); BL_WR_REG(EF_CTRL_BASE, EF_CTRL_EF_IF_CTRL_0, tmpVal); - tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) - | (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) - | (0 << EF_CTRL_EF_IF_0_RW_POS) | (1 << EF_CTRL_EF_IF_0_TRIG_POS); + tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) | + (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) | + (0 << EF_CTRL_EF_IF_0_RW_POS) | (1 << EF_CTRL_EF_IF_0_TRIG_POS); BL_WR_REG(EF_CTRL_BASE, EF_CTRL_EF_IF_CTRL_0, tmpVal); BL702_Delay_US(10); @@ -200,9 +200,9 @@ void ATTR_TCM_SECTION EF_Ctrl_Load_Efuse_R0(void) { (!BL_IS_REG_BIT_SET(tmpVal, EF_CTRL_EF_IF_0_AUTOLOAD_DONE))); /* Switch to AHB clock */ - tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) - | (EF_CTRL_SAHB_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) - | (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); + tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) | + (EF_CTRL_SAHB_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) | + (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); BL_WR_REG(EF_CTRL_BASE, EF_CTRL_EF_IF_CTRL_0, tmpVal); } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_glb.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_glb.c index 14d27ecfc6..7499cbf133 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_glb.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_glb.c @@ -48,16 +48,16 @@ /** @defgroup GLB_Private_Macros * @{ */ -#define GLB_CLK_SET_DUMMY_WAIT \ - { \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ +#define GLB_CLK_SET_DUMMY_WAIT \ + { \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ } #define GLB_GPIO_Get_Reg(pin) (glb_gpio_reg_t *)(GLB_BASE + GLB_GPIO_OFFSET + (pin / 2) * 4) #define GLB_GPIO_INT0_NUM (32) @@ -76,12 +76,12 @@ /** @defgroup GLB_Private_Variables * @{ */ -static intCallback_Type *glbBmxErrIntCbfArra[BMX_ERR_INT_ALL] = {NULL}; -static intCallback_Type *glbBmxToIntCbfArra[BMX_TO_INT_ALL] = {NULL}; -static intCallback_Type *glbGpioInt0CbfArra[GLB_GPIO_INT0_NUM] - = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; -static intCallback_Type *glbGpioInt0CbfArra2[GLB_GPIO_INT0_NUM] - = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; +static intCallback_Type *glbBmxErrIntCbfArra[BMX_ERR_INT_ALL] = {NULL}; +static intCallback_Type *glbBmxToIntCbfArra[BMX_TO_INT_ALL] = {NULL}; +static intCallback_Type *glbGpioInt0CbfArra[GLB_GPIO_INT0_NUM] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; +static intCallback_Type *glbGpioInt0CbfArra2[GLB_GPIO_INT0_NUM] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; /*@} end of group GLB_Private_Variables */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_hbn.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_hbn.c index 8742032259..3cd799b97c 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_hbn.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_hbn.c @@ -49,16 +49,16 @@ /** @defgroup HBN_Private_Macros * @{ */ -#define HBN_CLK_SET_DUMMY_WAIT \ - { \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ +#define HBN_CLK_SET_DUMMY_WAIT \ + { \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ } /*@} end of group HBN_Private_Macros */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2c.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2c.c index b43c892a16..c2f6257bbb 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2c.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2c.c @@ -50,12 +50,12 @@ * @{ */ #define I2C_FIFO_STATUS_TIMEOUT (160 * 1000 * 2) -#define PUT_UINT32_LE(n, b, i) \ - { \ - (b)[(i)] = (uint8_t)((n)); \ - (b)[(i) + 1] = (uint8_t)((n) >> 8); \ - (b)[(i) + 2] = (uint8_t)((n) >> 16); \ - (b)[(i) + 3] = (uint8_t)((n) >> 24); \ +#define PUT_UINT32_LE(n, b, i) \ + { \ + (b)[(i)] = (uint8_t)((n)); \ + (b)[(i) + 1] = (uint8_t)((n) >> 8); \ + (b)[(i) + 2] = (uint8_t)((n) >> 16); \ + (b)[(i) + 3] = (uint8_t)((n) >> 24); \ } /*@} end of group I2C_Private_Macros */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2s.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2s.c index 6bca22f9aa..bb3972aa32 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2s.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2s.c @@ -350,7 +350,8 @@ void I2S_Disable(void) { * *******************************************************************************/ uint32_t I2S_Read(void) { - while (0 == BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_RX_FIFO_CNT)) {}; + while (0 == BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_RX_FIFO_CNT)) { + }; return BL_RD_REG(I2S_BASE, I2S_FIFO_RDATA); } @@ -364,7 +365,8 @@ uint32_t I2S_Read(void) { * *******************************************************************************/ void I2S_Write(uint32_t data) { - while (0 == BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_TX_FIFO_CNT)) {}; + while (0 == BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_TX_FIFO_CNT)) { + }; BL_WR_REG(I2S_BASE, I2S_FIFO_WDATA, data); } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ir.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ir.c index e45f357209..ca097a0562 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ir.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ir.c @@ -904,8 +904,8 @@ IR_RxMode_Type IR_LearnToInit(uint32_t *data, uint8_t *length) { *length = IR_SWMReceiveData((uint16_t *)data, *length); /* Judge protocol type */ - if (NEC_HEAD_H_MIN < (data[0] & 0xffff) && (data[0] & 0xffff) < NEC_HEAD_H_MAX && NEC_HEAD_L_MIN < (data[0] >> 16) && (data[0] >> 16) < NEC_HEAD_L_MAX && NEC_BIT0_H_MIN < (data[1] & 0xffff) - && (data[1] & 0xffff) < NEC_BIT0_H_MAX) { + if (NEC_HEAD_H_MIN < (data[0] & 0xffff) && (data[0] & 0xffff) < NEC_HEAD_H_MAX && NEC_HEAD_L_MIN < (data[0] >> 16) && (data[0] >> 16) < NEC_HEAD_L_MAX && NEC_BIT0_H_MIN < (data[1] & 0xffff) && + (data[1] & 0xffff) < NEC_BIT0_H_MAX) { /* Set rx in NEC mode */ tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x0)); @@ -920,9 +920,9 @@ IR_RxMode_Type IR_LearnToInit(uint32_t *data, uint8_t *length) { BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, 0x22110464); return IR_RX_NEC; - } else if (RC5_ONE_PLUSE_MIN < (data[0] & 0xffff) && (data[0] & 0xffff) < RC5_ONE_PLUSE_MAX - && ((RC5_ONE_PLUSE_MIN < (data[0] >> 16) && (data[0] >> 16) < RC5_ONE_PLUSE_MAX) || (RC5_TWO_PLUSE_MIN < (data[0] >> 16) && (data[0] >> 16) < RC5_TWO_PLUSE_MAX)) - && ((RC5_ONE_PLUSE_MIN < (data[1] & 0xffff) && (data[1] & 0xffff) < RC5_ONE_PLUSE_MAX) || (RC5_TWO_PLUSE_MIN < (data[1] & 0xffff) && (data[1] & 0xffff) < RC5_TWO_PLUSE_MAX))) { + } else if (RC5_ONE_PLUSE_MIN < (data[0] & 0xffff) && (data[0] & 0xffff) < RC5_ONE_PLUSE_MAX && + ((RC5_ONE_PLUSE_MIN < (data[0] >> 16) && (data[0] >> 16) < RC5_ONE_PLUSE_MAX) || (RC5_TWO_PLUSE_MIN < (data[0] >> 16) && (data[0] >> 16) < RC5_TWO_PLUSE_MAX)) && + ((RC5_ONE_PLUSE_MIN < (data[1] & 0xffff) && (data[1] & 0xffff) < RC5_ONE_PLUSE_MAX) || (RC5_TWO_PLUSE_MIN < (data[1] & 0xffff) && (data[1] & 0xffff) < RC5_TWO_PLUSE_MAX))) { /* Set rx in RC-5 mode */ tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x1)); diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pds.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pds.c index a8aa807801..de47c5f101 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pds.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pds.c @@ -1136,12 +1136,12 @@ void ATTR_TCM_SECTION PDS_Auto_Enable(PDS_AUTO_POWER_DOWN_CFG_Type *powerCfg, PD CHECK_PARAM(IS_PDS_LDO_VOLTAGE_TYPE(normalCfg->vddcoreVol)); /* power config */ - pdsCtl |= (powerCfg->mbgPower << 31) | (powerCfg->ldo18rfPower << 30) | (powerCfg->sfregPower << 29) | (powerCfg->pllPower << 28) | (powerCfg->cpu0Power << 19) | (powerCfg->rc32mPower << 17) - | (powerCfg->xtalPower << 14) | (powerCfg->allPower << 13) | (powerCfg->isoPower << 11) | (powerCfg->bzPower << 10) | (powerCfg->sramDisStanby << 9) | (powerCfg->cgPower << 8) - | (powerCfg->cpu1Power << 7) | (powerCfg->usbPower << 3); + pdsCtl |= (powerCfg->mbgPower << 31) | (powerCfg->ldo18rfPower << 30) | (powerCfg->sfregPower << 29) | (powerCfg->pllPower << 28) | (powerCfg->cpu0Power << 19) | (powerCfg->rc32mPower << 17) | + (powerCfg->xtalPower << 14) | (powerCfg->allPower << 13) | (powerCfg->isoPower << 11) | (powerCfg->bzPower << 10) | (powerCfg->sramDisStanby << 9) | (powerCfg->cgPower << 8) | + (powerCfg->cpu1Power << 7) | (powerCfg->usbPower << 3); pdsCtl = BL_SET_REG_BITS_VAL(pdsCtl, PDS_CR_PDS_LDO_VOL, normalCfg->vddcoreVol); - pdsCtl |= (normalCfg->vddcoreVolEn << 18) | (normalCfg->cpu0NotNeedWFI << 21) | (normalCfg->cpu1NotNeedWFI << 20) | (normalCfg->busReset << 16) | (normalCfg->disIrqWakeUp << 15) - | (normalCfg->powerOffXtalForever << 2) | (normalCfg->sleepForever << 1); + pdsCtl |= (normalCfg->vddcoreVolEn << 18) | (normalCfg->cpu0NotNeedWFI << 21) | (normalCfg->cpu1NotNeedWFI << 20) | (normalCfg->busReset << 16) | (normalCfg->disIrqWakeUp << 15) | + (normalCfg->powerOffXtalForever << 2) | (normalCfg->sleepForever << 1); BL_WR_REG(PDS_BASE, PDS_CTL, pdsCtl); pdsCtl = BL_RD_REG(PDS_BASE, PDS_CTL); diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_psram.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_psram.c index e2fb744d46..a35fef2bd9 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_psram.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_psram.c @@ -144,7 +144,8 @@ void ATTR_TCM_SECTION Psram_ReadReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regVa SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) {} + while (SET == SF_Ctrl_GetBusyState()) { + } BL702_MemCpy(regValue, psramCtrlBuf, 1); } @@ -294,7 +295,8 @@ void ATTR_TCM_SECTION Psram_ReadId(SPI_Psram_Cfg_Type *psramCfg, uint8_t *data) SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) {} + while (SET == SF_Ctrl_GetBusyState()) { + } BL702_MemCpy(data, psramCtrlBuf, 8); } @@ -324,7 +326,8 @@ BL_Err_Type ATTR_TCM_SECTION Psram_EnterQuadMode(SPI_Psram_Cfg_Type *psramCfg) { SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) {} + while (SET == SF_Ctrl_GetBusyState()) { + } return SUCCESS; } @@ -358,7 +361,8 @@ BL_Err_Type ATTR_TCM_SECTION Psram_ExitQuadMode(SPI_Psram_Cfg_Type *psramCfg) { SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) {} + while (SET == SF_Ctrl_GetBusyState()) { + } return SUCCESS; } @@ -397,7 +401,8 @@ BL_Err_Type ATTR_TCM_SECTION Psram_ToggleBurstLength(SPI_Psram_Cfg_Type *psramCf SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) {} + while (SET == SF_Ctrl_GetBusyState()) { + } return SUCCESS; } @@ -439,7 +444,8 @@ BL_Err_Type ATTR_TCM_SECTION Psram_SoftwareReset(SPI_Psram_Cfg_Type *psramCfg, P SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) {} + while (SET == SF_Ctrl_GetBusyState()) { + } /* Reset */ psramCmd.cmdBuf[0] = (psramCfg->resetCmd) << 24; @@ -447,7 +453,8 @@ BL_Err_Type ATTR_TCM_SECTION Psram_SoftwareReset(SPI_Psram_Cfg_Type *psramCfg, P psramCmd.rwFlag = SF_CTRL_READ; SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) {} + while (SET == SF_Ctrl_GetBusyState()) { + } BL702_Delay_US(50); return SUCCESS; @@ -718,7 +725,8 @@ BL_Err_Type ATTR_TCM_SECTION Psram_Read(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) {} + while (SET == SF_Ctrl_GetBusyState()) { + } BL702_MemCpy_Fast(data, psramCtrlBuf, curLen); diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_qdec.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_qdec.c index 3ce8357abd..f503f67e4e 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_qdec.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_qdec.c @@ -60,7 +60,11 @@ * @{ */ static const uint32_t qdecAddr[QDEC_ID_MAX] = {QDEC0_BASE, QDEC1_BASE, QDEC2_BASE}; -static intCallback_Type *qdecIntCbfArra[QDEC_ID_MAX][QDEC_INT_ALL] = {{NULL, NULL, NULL, NULL}, {NULL, NULL, NULL, NULL}, {NULL, NULL, NULL, NULL}}; +static intCallback_Type *qdecIntCbfArra[QDEC_ID_MAX][QDEC_INT_ALL] = { + {NULL, NULL, NULL, NULL}, + {NULL, NULL, NULL, NULL}, + {NULL, NULL, NULL, NULL} +}; /*@} end of group QDEC_Private_Variables */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_eng.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_eng.c index 6b86ef10f3..acff27d1c6 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_eng.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_eng.c @@ -48,23 +48,23 @@ /** @defgroup SEC_ENG_Private_Macros * @{ */ -#define PUT_UINT32_BE(n, b, i) \ - { \ - (b)[(i)] = (uint8_t)((n) >> 24); \ - (b)[(i) + 1] = (uint8_t)((n) >> 16); \ - (b)[(i) + 2] = (uint8_t)((n) >> 8); \ - (b)[(i) + 3] = (uint8_t)((n)); \ +#define PUT_UINT32_BE(n, b, i) \ + { \ + (b)[(i)] = (uint8_t)((n) >> 24); \ + (b)[(i) + 1] = (uint8_t)((n) >> 16); \ + (b)[(i) + 2] = (uint8_t)((n) >> 8); \ + (b)[(i) + 3] = (uint8_t)((n)); \ } -#define PUT_UINT64_BE(n, b, i) \ - { \ - (b)[(i)] = (uint8_t)((n) >> 56); \ - (b)[(i) + 1] = (uint8_t)((n) >> 48); \ - (b)[(i) + 2] = (uint8_t)((n) >> 40); \ - (b)[(i) + 3] = (uint8_t)((n) >> 32); \ - (b)[(i) + 4] = (uint8_t)((n) >> 24); \ - (b)[(i) + 5] = (uint8_t)((n) >> 16); \ - (b)[(i) + 6] = (uint8_t)((n) >> 8); \ - (b)[(i) + 7] = (uint8_t)((n)); \ +#define PUT_UINT64_BE(n, b, i) \ + { \ + (b)[(i)] = (uint8_t)((n) >> 56); \ + (b)[(i) + 1] = (uint8_t)((n) >> 48); \ + (b)[(i) + 2] = (uint8_t)((n) >> 40); \ + (b)[(i) + 3] = (uint8_t)((n) >> 32); \ + (b)[(i) + 4] = (uint8_t)((n) >> 24); \ + (b)[(i) + 5] = (uint8_t)((n) >> 16); \ + (b)[(i) + 6] = (uint8_t)((n) >> 8); \ + (b)[(i) + 7] = (uint8_t)((n)); \ } #define SEC_ENG_SHA_BUSY_TIMEOUT_COUNT (100 * 160 * 1000) #define SEC_ENG_AES_BUSY_TIMEOUT_COUNT (100 * 160 * 1000) @@ -80,11 +80,11 @@ struct pka0_pld_cfg { union { struct { - uint32_t size : 12; /*[11: 0], r/w, 0x0 */ - uint32_t d_reg_index : 8; /*[19:12], r/w, 0x0 */ - uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ - uint32_t op : 7; /*[30:24], r/w, 0x0 */ - uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ + uint32_t size : 12; /*[11: 0], r/w, 0x0 */ + uint32_t d_reg_index : 8; /*[19:12], r/w, 0x0 */ + uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ + uint32_t op : 7; /*[30:24], r/w, 0x0 */ + uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ } BF; uint32_t WORD; } value; @@ -93,11 +93,11 @@ struct pka0_pld_cfg { struct pka0_pldi_cfg { union { struct { - uint32_t rsvd : 12; /*[11: 0], r/w, 0x0 */ - uint32_t d_reg_index : 8; /*[19:12], r/w, 0x0 */ - uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ - uint32_t op : 7; /*[30:24], r/w, 0x0 */ - uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ + uint32_t rsvd : 12; /*[11: 0], r/w, 0x0 */ + uint32_t d_reg_index : 8; /*[19:12], r/w, 0x0 */ + uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ + uint32_t op : 7; /*[30:24], r/w, 0x0 */ + uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ } BF; uint32_t WORD; } value; @@ -106,12 +106,12 @@ struct pka0_pldi_cfg { struct pka0_common_op_first_cfg { union { struct { - uint32_t s0_reg_idx : 8; /*[7: 0], r/w, 0x0 */ + uint32_t s0_reg_idx : 8; /*[7: 0], r/w, 0x0 */ uint32_t s0_reg_type : 4; /*[11:8], r/w, 0x0 */ - uint32_t d_reg_idx : 8; /*[19:12], r/w, 0x0 */ - uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ - uint32_t op : 7; /*[30:24], r/w, 0x0 */ - uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ + uint32_t d_reg_idx : 8; /*[19:12], r/w, 0x0 */ + uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ + uint32_t op : 7; /*[30:24], r/w, 0x0 */ + uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ } BF; uint32_t WORD; } value; @@ -120,10 +120,10 @@ struct pka0_common_op_first_cfg { struct pka0_common_op_snd_cfg_S1_only { union { struct { - uint32_t reserved_0_11 : 12; /*[11: 0], rsvd, 0x0 */ - uint32_t s1_reg_idx : 8; /*[19:12], r/w, 0x0 */ - uint32_t s1_reg_type : 4; /*[23:20], r/w, 0x0 */ - uint32_t reserved_24_31 : 8; /*[31:24], rsvd, 0x0 */ + uint32_t reserved_0_11 : 12; /*[11: 0], rsvd, 0x0 */ + uint32_t s1_reg_idx : 8; /*[19:12], r/w, 0x0 */ + uint32_t s1_reg_type : 4; /*[23:20], r/w, 0x0 */ + uint32_t reserved_24_31 : 8; /*[31:24], rsvd, 0x0 */ } BF; uint32_t WORD; } value; @@ -132,8 +132,8 @@ struct pka0_common_op_snd_cfg_S1_only { struct pka0_common_op_snd_cfg_S2_only { union { struct { - uint32_t s2_reg_idx : 8; /*[7 : 0], r/w, 0x0 */ - uint32_t s2_reg_type : 4; /*[11: 8], r/w, 0x0 */ + uint32_t s2_reg_idx : 8; /*[7 : 0], r/w, 0x0 */ + uint32_t s2_reg_type : 4; /*[11: 8], r/w, 0x0 */ uint32_t reserved_12_31 : 20; /*[31:12], rsvd, 0x0 */ } BF; uint32_t WORD; @@ -143,10 +143,10 @@ struct pka0_common_op_snd_cfg_S2_only { struct pka0_common_op_snd_cfg_S1_S2 { union { struct { - uint32_t s2_reg_idx : 8; /*[7 : 0], r/w, 0x0 */ - uint32_t s2_reg_type : 4; /*[11: 8], r/w, 0x0 */ - uint32_t s1_reg_idx : 8; /*[19:12], r/w, 0x0 */ - uint32_t s1_reg_type : 4; /*[23:20], r/w, 0x0 */ + uint32_t s2_reg_idx : 8; /*[7 : 0], r/w, 0x0 */ + uint32_t s2_reg_type : 4; /*[11: 8], r/w, 0x0 */ + uint32_t s1_reg_idx : 8; /*[19:12], r/w, 0x0 */ + uint32_t s1_reg_type : 4; /*[23:20], r/w, 0x0 */ uint32_t reserved_24_31 : 8; /*[31:24], rsvd, 0x0 */ } BF; uint32_t WORD; @@ -156,7 +156,7 @@ struct pka0_common_op_snd_cfg_S1_S2 { struct pka0_bit_shift_op_cfg { union { struct { - uint32_t bit_shift : 15; /*[14: 0], r/w, 0x0 */ + uint32_t bit_shift : 15; /*[14: 0], r/w, 0x0 */ uint32_t reserved_24_31 : 17; /*[31:15], rsvd, 0x0 */ } BF; uint32_t WORD; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg.c index b3281d4472..1d36ddd00e 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg.c @@ -1830,226 +1830,228 @@ static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_FT_VQ80 = { .qeData = 0, }; -static const ATTR_TCM_CONST_SECTION Flash_Info_t flashInfos[] = {{ - .jedecID = 0x1440ef, - .name = "Winb_80DV_08_33", - .cfg = &flashCfg_Winb_80DV, - }, - { - .jedecID = 0x1540ef, - .name = "Winb_16DV_16_33", - .cfg = &flashCfg_Winb_16DV, - }, - { - .jedecID = 0x1640ef, - .name = "Winb_32FV_32_33", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x1460ef, - .name = "Winb_80EW_08_18", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x1560ef, - .name = "Winb_16FW_16_18", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x1660ef, - .name = "Winb_32FW_32_18", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x1860ef, - .name = "Winb_128FW_128_18", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x1680ef, - .name = "Winb_32JW_32_18", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x13605e, - .name = "Zbit_04_33", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x14605e, - .name = "Zbit_08_33", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, - { - .jedecID = 0x14609d, - .name = "ISSI_08_33", - .cfg = &flashCfg_Issi, - }, - { - .jedecID = 0x15609d, - .name = "ISSI_16_33", - .cfg = &flashCfg_Issi, - }, - { - .jedecID = 0x16609d, - .name = "ISSI_32_33", - .cfg = &flashCfg_Issi, - }, - { - .jedecID = 0x14709d, - .name = "ISSI_08_18", - .cfg = &flashCfg_Issi, - }, - { - .jedecID = 0x15709d, - .name = "ISSI_16_18", - .cfg = &flashCfg_Issi, - }, - { - .jedecID = 0x16709d, - .name = "ISSI_32_18", - .cfg = &flashCfg_Issi, - }, - { - .jedecID = 0x134051, - .name = "GD_MD04D_04_33", - .cfg = &flashCfg_Gd_Md_40D, - }, - { - .jedecID = 0x1440C8, - .name = "GD_Q08E_08_33", - .cfg = &flashCfg_Gd_Q80E_Q16E, - }, - { - .jedecID = 0x1540C8, - .name = "GD_Q16E_16_33", - .cfg = &flashCfg_Gd_Q80E_Q16E, - }, - { - .jedecID = 0x1640C8, - .name = "GD_Q32C_32_33", - .cfg = &flashCfg_Gd_Q32C, - }, - { - .jedecID = 0x1460C8, - .name = "GD_LQ08C_08_18", - .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, - }, - { - .jedecID = 0x1560C8, - .name = "GD_LE16C_16_18", - .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, - }, - { - .jedecID = 0x1660C8, - .name = "GD_LQ32D_32_18", - .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, - }, - { - .jedecID = 0x1465C8, - .name = "GD_WQ80E_80_33", - .cfg = &flashCfg_Gd_WQ80E_WQ16E, - }, - { - .jedecID = 0x1565C8, - .name = "GD_WQ16E_16_33", - .cfg = &flashCfg_Gd_WQ80E_WQ16E, - }, - { - .jedecID = 0x1665C8, - .name = "GD_WQ32E_32_33", - .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, - }, - { - .jedecID = 0x3425C2, - .name = "MX_25V80_08_18", - .cfg = &flashCfg_Mxic, - }, - { - .jedecID = 0x3525C2, - .name = "MX_25U16_35_18", - .cfg = &flashCfg_Mxic_1635F, - }, - { - .jedecID = 0x3625C2, - .name = "MX_25V32_32_18", - .cfg = &flashCfg_Mxic, - }, - { - .jedecID = 0x13400B, - .name = "XT_25F04D_04_33", - .cfg = &flashCfg_Xtx40, - }, - { - .jedecID = 0x15400B, - .name = "XT_25F16B_16_33", - .cfg = &flashCfg_Xtx, - }, - { - .jedecID = 0x16400B, - .name = "XT_25F32B_32_33", - .cfg = &flashCfg_Xtx, - }, - { - .jedecID = 0x14600B, - .name = "XT_25Q80B_08_18", - .cfg = &flashCfg_Xtx, - }, - { - .jedecID = 0x16600B, - .name = "XT_25Q32B_32_18", - .cfg = &flashCfg_Xtx, - }, - { - .jedecID = 0x146085, - .name = "Puya_Q80L/H_08_18/33", - .cfg = &flashCfg_Puya_Q80L_Q80H_Q16H, - }, - { - .jedecID = 0x156085, - .name = "Puya_Q16H_16_33", - .cfg = &flashCfg_Puya_Q80L_Q80H_Q16H, - }, - { - .jedecID = 0x166085, - .name = "Puya_Q32H_32_33", - .cfg = &flashCfg_Puya_Q32H, - }, - { - .jedecID = 0x134068, - .name = "Boya_Q04B_04_33", - .cfg = &flashCfg_Boya40, - }, - { - .jedecID = 0x144068, - .name = "Boya_Q08B_08_33", - .cfg = &flashCfg_Boya, - }, - { - .jedecID = 0x154068, - .name = "Boya_Q16B_16_33", - .cfg = &flashCfg_Boya, - }, - { - .jedecID = 0x164068, - .name = "Boya_Q32B_32_33", - .cfg = &flashCfg_Boya, - }, - { - .jedecID = 0x174068, - .name = "Boya_Q64A_64_33", - .cfg = &flashCfg_Boya, - }, - { - .jedecID = 0x184068, - .name = "Boya_Q128A_128_33", - .cfg = &flashCfg_Boya, - }, - { - .jedecID = 0x14605E, - .name = "FT_VQ80", - .cfg = &flashCfg_FT_VQ80, - }}; +static const ATTR_TCM_CONST_SECTION Flash_Info_t flashInfos[] = { + { + .jedecID = 0x1440ef, + .name = "Winb_80DV_08_33", + .cfg = &flashCfg_Winb_80DV, + }, + { + .jedecID = 0x1540ef, + .name = "Winb_16DV_16_33", + .cfg = &flashCfg_Winb_16DV, + }, + { + .jedecID = 0x1640ef, + .name = "Winb_32FV_32_33", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x1460ef, + .name = "Winb_80EW_08_18", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x1560ef, + .name = "Winb_16FW_16_18", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x1660ef, + .name = "Winb_32FW_32_18", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x1860ef, + .name = "Winb_128FW_128_18", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x1680ef, + .name = "Winb_32JW_32_18", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x13605e, + .name = "Zbit_04_33", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x14605e, + .name = "Zbit_08_33", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, + { + .jedecID = 0x14609d, + .name = "ISSI_08_33", + .cfg = &flashCfg_Issi, + }, + { + .jedecID = 0x15609d, + .name = "ISSI_16_33", + .cfg = &flashCfg_Issi, + }, + { + .jedecID = 0x16609d, + .name = "ISSI_32_33", + .cfg = &flashCfg_Issi, + }, + { + .jedecID = 0x14709d, + .name = "ISSI_08_18", + .cfg = &flashCfg_Issi, + }, + { + .jedecID = 0x15709d, + .name = "ISSI_16_18", + .cfg = &flashCfg_Issi, + }, + { + .jedecID = 0x16709d, + .name = "ISSI_32_18", + .cfg = &flashCfg_Issi, + }, + { + .jedecID = 0x134051, + .name = "GD_MD04D_04_33", + .cfg = &flashCfg_Gd_Md_40D, + }, + { + .jedecID = 0x1440C8, + .name = "GD_Q08E_08_33", + .cfg = &flashCfg_Gd_Q80E_Q16E, + }, + { + .jedecID = 0x1540C8, + .name = "GD_Q16E_16_33", + .cfg = &flashCfg_Gd_Q80E_Q16E, + }, + { + .jedecID = 0x1640C8, + .name = "GD_Q32C_32_33", + .cfg = &flashCfg_Gd_Q32C, + }, + { + .jedecID = 0x1460C8, + .name = "GD_LQ08C_08_18", + .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, + }, + { + .jedecID = 0x1560C8, + .name = "GD_LE16C_16_18", + .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, + }, + { + .jedecID = 0x1660C8, + .name = "GD_LQ32D_32_18", + .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, + }, + { + .jedecID = 0x1465C8, + .name = "GD_WQ80E_80_33", + .cfg = &flashCfg_Gd_WQ80E_WQ16E, + }, + { + .jedecID = 0x1565C8, + .name = "GD_WQ16E_16_33", + .cfg = &flashCfg_Gd_WQ80E_WQ16E, + }, + { + .jedecID = 0x1665C8, + .name = "GD_WQ32E_32_33", + .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, + }, + { + .jedecID = 0x3425C2, + .name = "MX_25V80_08_18", + .cfg = &flashCfg_Mxic, + }, + { + .jedecID = 0x3525C2, + .name = "MX_25U16_35_18", + .cfg = &flashCfg_Mxic_1635F, + }, + { + .jedecID = 0x3625C2, + .name = "MX_25V32_32_18", + .cfg = &flashCfg_Mxic, + }, + { + .jedecID = 0x13400B, + .name = "XT_25F04D_04_33", + .cfg = &flashCfg_Xtx40, + }, + { + .jedecID = 0x15400B, + .name = "XT_25F16B_16_33", + .cfg = &flashCfg_Xtx, + }, + { + .jedecID = 0x16400B, + .name = "XT_25F32B_32_33", + .cfg = &flashCfg_Xtx, + }, + { + .jedecID = 0x14600B, + .name = "XT_25Q80B_08_18", + .cfg = &flashCfg_Xtx, + }, + { + .jedecID = 0x16600B, + .name = "XT_25Q32B_32_18", + .cfg = &flashCfg_Xtx, + }, + { + .jedecID = 0x146085, + .name = "Puya_Q80L/H_08_18/33", + .cfg = &flashCfg_Puya_Q80L_Q80H_Q16H, + }, + { + .jedecID = 0x156085, + .name = "Puya_Q16H_16_33", + .cfg = &flashCfg_Puya_Q80L_Q80H_Q16H, + }, + { + .jedecID = 0x166085, + .name = "Puya_Q32H_32_33", + .cfg = &flashCfg_Puya_Q32H, + }, + { + .jedecID = 0x134068, + .name = "Boya_Q04B_04_33", + .cfg = &flashCfg_Boya40, + }, + { + .jedecID = 0x144068, + .name = "Boya_Q08B_08_33", + .cfg = &flashCfg_Boya, + }, + { + .jedecID = 0x154068, + .name = "Boya_Q16B_16_33", + .cfg = &flashCfg_Boya, + }, + { + .jedecID = 0x164068, + .name = "Boya_Q32B_32_33", + .cfg = &flashCfg_Boya, + }, + { + .jedecID = 0x174068, + .name = "Boya_Q64A_64_33", + .cfg = &flashCfg_Boya, + }, + { + .jedecID = 0x184068, + .name = "Boya_Q128A_128_33", + .cfg = &flashCfg_Boya, + }, + { + .jedecID = 0x14605E, + .name = "FT_VQ80", + .cfg = &flashCfg_FT_VQ80, + } +}; #endif /*@} end of group SF_CFG_Private_Variables */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg_ext.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg_ext.c index 5fc7f5af61..e74513200a 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg_ext.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg_ext.c @@ -464,95 +464,95 @@ static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Winb_16JV = { static const ATTR_TCM_CONST_SECTION Flash_Info_t flashInfos[] = { { - .jedecID = 0x134051, - .name = "GD_MD04D_04_33", - .cfg = &flashCfg_Gd_Md_40D, - }, + .jedecID = 0x134051, + .name = "GD_MD04D_04_33", + .cfg = &flashCfg_Gd_Md_40D, + }, { - .jedecID = 0x1320c2, - .name = "MX_KH40_04_33", - .cfg = &flashCfg_MX_KH25, - }, + .jedecID = 0x1320c2, + .name = "MX_KH40_04_33", + .cfg = &flashCfg_MX_KH25, + }, { - .jedecID = 0x1420c2, - .name = "MX_KH80_08_33", - .cfg = &flashCfg_MX_KH25, - }, + .jedecID = 0x1420c2, + .name = "MX_KH80_08_33", + .cfg = &flashCfg_MX_KH25, + }, { - .jedecID = 0x1520c2, - .name = "MX_KH16_16_33", - .cfg = &flashCfg_MX_KH25, - }, + .jedecID = 0x1520c2, + .name = "MX_KH16_16_33", + .cfg = &flashCfg_MX_KH25, + }, { - .jedecID = 0x1440A1, - .name = "FM_25Q80_80_33", - .cfg = &flashCfg_FM_Q80, - }, + .jedecID = 0x1440A1, + .name = "FM_25Q80_80_33", + .cfg = &flashCfg_FM_Q80, + }, { - .jedecID = 0x1570EF, - .name = "Winb_16JV_16_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x1570EF, + .name = "Winb_16JV_16_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x1870EF, - .name = "Winb_128JV_128_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x1870EF, + .name = "Winb_128JV_128_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x15605E, - .name = "ZB_VQ16_16_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x15605E, + .name = "ZB_VQ16_16_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x144020, - .name = "XM_25QH80_80_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x144020, + .name = "XM_25QH80_80_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x154020, - .name = "XM_25QH16_16_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x154020, + .name = "XM_25QH16_16_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x164020, - .name = "XM_25QH32_32_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x164020, + .name = "XM_25QH32_32_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x174020, - .name = "XM_25QH64_64_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x174020, + .name = "XM_25QH64_64_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x13325E, - .name = "ZB_D40B_80_33", - .cfg = &flashCfg_MX_KH25, - }, + .jedecID = 0x13325E, + .name = "ZB_D40B_80_33", + .cfg = &flashCfg_MX_KH25, + }, { - .jedecID = 0x14325E, - .name = "ZB_D80B_80_33", - .cfg = &flashCfg_MX_KH25, - }, + .jedecID = 0x14325E, + .name = "ZB_D80B_80_33", + .cfg = &flashCfg_MX_KH25, + }, { - .jedecID = 0x15405E, - .name = "ZB_25Q16B_15_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x15405E, + .name = "ZB_25Q16B_15_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x16405E, - .name = "ZB_25Q32B_16_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x16405E, + .name = "ZB_25Q32B_16_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x1560EB, - .name = "TH_25Q16HB_16_33", - .cfg = &flashCfg_FM_Q80, - }, + .jedecID = 0x1560EB, + .name = "TH_25Q16HB_16_33", + .cfg = &flashCfg_FM_Q80, + }, { - .jedecID = 0x15345E, - .name = "ZB_25Q16A_15_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x15345E, + .name = "ZB_25Q16A_15_33", + .cfg = &flashCfg_Winb_16JV, + }, }; /*@} end of group SF_CFG_EXT_Private_Variables */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash.c index 8639fcd43c..3b922ce569 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash.c @@ -670,8 +670,8 @@ BL_Err_Type ATTR_TCM_SECTION SFlash_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t /* 64K margin address,and length > 64K-sector size, erase one first */ ret = SFlash_Blk64_Erase(flashCfg, startaddr / BFLB_SPIFLASH_BLK64K_SIZE); eraseLen = BFLB_SPIFLASH_BLK64K_SIZE; - } else if (flashCfg->blk32EraseCmd != BFLB_SPIFLASH_CMD_INVALID && (startaddr & (BFLB_SPIFLASH_BLK32K_SIZE - 1)) == 0 - && len > (uint32_t)(BFLB_SPIFLASH_BLK32K_SIZE - flashCfg->sectorSize * 1024)) { + } else if (flashCfg->blk32EraseCmd != BFLB_SPIFLASH_CMD_INVALID && (startaddr & (BFLB_SPIFLASH_BLK32K_SIZE - 1)) == 0 && + len > (uint32_t)(BFLB_SPIFLASH_BLK32K_SIZE - flashCfg->sectorSize * 1024)) { /* 32K margin address,and length > 32K-sector size, erase one first */ ret = SFlash_Blk32_Erase(flashCfg, startaddr / BFLB_SPIFLASH_BLK32K_SIZE); eraseLen = BFLB_SPIFLASH_BLK32K_SIZE; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash_ext.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash_ext.c index ae19f0da84..24b2bf5841 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash_ext.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash_ext.c @@ -229,8 +229,8 @@ BL_Err_Type ATTR_TCM_SECTION SFlash_Clear_Status_Register(SPI_Flash_Cfg_Type *pF SFlash_Read_Reg(pFlashCfg, 0, (uint8_t *)&readRegValue0, 1); SFlash_Read_Reg(pFlashCfg, 1, (uint8_t *)&readRegValue1, 1); readValue = (readRegValue0 | (readRegValue1 << 8)); - if ((readValue & (~((1 << (pFlashCfg->qeIndex * 8 + pFlashCfg->qeBit)) | (1 << (pFlashCfg->busyIndex * 8 + pFlashCfg->busyBit)) | (1 << (pFlashCfg->wrEnableIndex * 8 + pFlashCfg->wrEnableBit))))) - == 0) { + if ((readValue & (~((1 << (pFlashCfg->qeIndex * 8 + pFlashCfg->qeBit)) | (1 << (pFlashCfg->busyIndex * 8 + pFlashCfg->busyBit)) | (1 << (pFlashCfg->wrEnableIndex * 8 + pFlashCfg->wrEnableBit))))) == + 0) { return SUCCESS; } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_timer.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_timer.c index f5f9cfc2b5..934c501e72 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_timer.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_timer.c @@ -60,7 +60,11 @@ /** @defgroup TIMER_Private_Variables * @{ */ -intCallback_Type *timerIntCbfArra[3][TIMER_INT_ALL] = {{NULL, NULL, NULL}, {NULL, NULL, NULL}, {NULL, NULL, NULL}}; +intCallback_Type *timerIntCbfArra[3][TIMER_INT_ALL] = { + {NULL, NULL, NULL}, + {NULL, NULL, NULL}, + {NULL, NULL, NULL} +}; /*@} end of group TIMER_Private_Variables */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_uart.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_uart.c index 82a9792fe2..fbc45c9a56 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_uart.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_uart.c @@ -952,7 +952,8 @@ BL_Err_Type UART_SendDataBlock(UART_ID_Type uartId, uint8_t *data, uint32_t len) } } - while (UART_GetTxBusBusyStatus(uartId) == SET) {} + while (UART_GetTxBusBusyStatus(uartId) == SET) { + } return SUCCESS; } diff --git a/source/Core/BSP/Pinecilv2/board.c b/source/Core/BSP/Pinecilv2/board.c index 49f76f4a54..7c56fdde9a 100644 --- a/source/Core/BSP/Pinecilv2/board.c +++ b/source/Core/BSP/Pinecilv2/board.c @@ -33,34 +33,34 @@ struct pin_mux_cfg { static const struct pin_mux_cfg af_pin_table[] = { #ifdef CONFIG_GPIO0_FUNC - {.pin = GPIO_PIN_0, .func = CONFIG_GPIO0_FUNC}, + { .pin = GPIO_PIN_0, .func = CONFIG_GPIO0_FUNC}, #endif #ifdef CONFIG_GPIO1_FUNC - {.pin = GPIO_PIN_1, .func = CONFIG_GPIO1_FUNC}, + { .pin = GPIO_PIN_1, .func = CONFIG_GPIO1_FUNC}, #endif #ifdef CONFIG_GPIO2_FUNC - {.pin = GPIO_PIN_2, .func = CONFIG_GPIO2_FUNC}, + { .pin = GPIO_PIN_2, .func = CONFIG_GPIO2_FUNC}, #endif #ifdef CONFIG_GPIO3_FUNC - {.pin = GPIO_PIN_3, .func = CONFIG_GPIO3_FUNC}, + { .pin = GPIO_PIN_3, .func = CONFIG_GPIO3_FUNC}, #endif #ifdef CONFIG_GPIO4_FUNC - {.pin = GPIO_PIN_4, .func = CONFIG_GPIO4_FUNC}, + { .pin = GPIO_PIN_4, .func = CONFIG_GPIO4_FUNC}, #endif #ifdef CONFIG_GPIO5_FUNC - {.pin = GPIO_PIN_5, .func = CONFIG_GPIO5_FUNC}, + { .pin = GPIO_PIN_5, .func = CONFIG_GPIO5_FUNC}, #endif #ifdef CONFIG_GPIO6_FUNC - {.pin = GPIO_PIN_6, .func = CONFIG_GPIO6_FUNC}, + { .pin = GPIO_PIN_6, .func = CONFIG_GPIO6_FUNC}, #endif #ifdef CONFIG_GPIO7_FUNC - {.pin = GPIO_PIN_7, .func = CONFIG_GPIO7_FUNC}, + { .pin = GPIO_PIN_7, .func = CONFIG_GPIO7_FUNC}, #endif #ifdef CONFIG_GPIO8_FUNC - {.pin = GPIO_PIN_8, .func = CONFIG_GPIO8_FUNC}, + { .pin = GPIO_PIN_8, .func = CONFIG_GPIO8_FUNC}, #endif #ifdef CONFIG_GPIO9_FUNC - {.pin = GPIO_PIN_9, .func = CONFIG_GPIO9_FUNC}, + { .pin = GPIO_PIN_9, .func = CONFIG_GPIO9_FUNC}, #endif #ifdef CONFIG_GPIO10_FUNC {.pin = GPIO_PIN_10, .func = CONFIG_GPIO10_FUNC}, diff --git a/source/Core/BSP/Sequre_S60/Setup.cpp b/source/Core/BSP/Sequre_S60/Setup.cpp index 51cd346876..87a383f1c7 100644 --- a/source/Core/BSP/Sequre_S60/Setup.cpp +++ b/source/Core/BSP/Sequre_S60/Setup.cpp @@ -410,8 +410,8 @@ static void MX_GPIO_Init(void) { GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_15; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); - GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_12 - | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15; + GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_12 | + GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /*Configure GPIO pins : KEY_B_Pin KEY_A_Pin */ diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c index cb32ffdf1c..8725243aa8 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c +++ b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c @@ -155,8 +155,8 @@ HAL_TickFreqTypeDef uwTickFreq = HAL_TICK_FREQ_DEFAULT; /* 1KHz */ HAL_StatusTypeDef HAL_Init(void) { /* Configure Flash prefetch */ #if (PREFETCH_ENABLE != 0) -#if defined(STM32F101x6) || defined(STM32F101xB) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) \ - || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) +#if defined(STM32F101x6) || defined(STM32F101xB) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) || \ + defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) /* Prefetch buffer is not available on value line devices */ __HAL_FLASH_PREFETCH_BUFFER_ENABLE(); @@ -352,7 +352,8 @@ __weak void HAL_Delay(uint32_t Delay) { wait += (uint32_t)(uwTickFreq); } - while ((HAL_GetTick() - tickstart) < wait) {} + while ((HAL_GetTick() - tickstart) < wait) { + } } /** diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c index 712af4d4c1..19ac9e7db1 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c +++ b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c @@ -555,12 +555,12 @@ HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc) { __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD | ADC_FLAG_JEOC | ADC_FLAG_EOC | ADC_FLAG_JSTRT | ADC_FLAG_STRT)); /* Reset register CR1 */ - CLEAR_BIT(hadc->Instance->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM | ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO | ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE | ADC_CR1_AWDIE - | ADC_CR1_EOCIE | ADC_CR1_AWDCH)); + CLEAR_BIT(hadc->Instance->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM | ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO | ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE | + ADC_CR1_AWDIE | ADC_CR1_EOCIE | ADC_CR1_AWDCH)); /* Reset register CR2 */ - CLEAR_BIT(hadc->Instance->CR2, (ADC_CR2_TSVREFE | ADC_CR2_SWSTART | ADC_CR2_JSWSTART | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL | ADC_CR2_ALIGN | ADC_CR2_DMA - | ADC_CR2_RSTCAL | ADC_CR2_CAL | ADC_CR2_CONT | ADC_CR2_ADON)); + CLEAR_BIT(hadc->Instance->CR2, (ADC_CR2_TSVREFE | ADC_CR2_SWSTART | ADC_CR2_JSWSTART | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL | ADC_CR2_ALIGN | ADC_CR2_DMA | + ADC_CR2_RSTCAL | ADC_CR2_CAL | ADC_CR2_CONT | ADC_CR2_ADON)); /* Reset register SMPR1 */ CLEAR_BIT(hadc->Instance->SMPR1, (ADC_SMPR1_SMP17 | ADC_SMPR1_SMP16 | ADC_SMPR1_SMP15 | ADC_SMPR1_SMP14 | ADC_SMPR1_SMP13 | ADC_SMPR1_SMP12 | ADC_SMPR1_SMP11 | ADC_SMPR1_SMP10)); @@ -1495,8 +1495,8 @@ HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef *hadc, ADC_AnalogWDG assert_param(IS_ADC_RANGE(AnalogWDGConfig->HighThreshold)); assert_param(IS_ADC_RANGE(AnalogWDGConfig->LowThreshold)); - if ((AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG) || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC) - || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC)) { + if ((AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG) || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC) || + (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC)) { assert_param(IS_ADC_CHANNEL(AnalogWDGConfig->Channel)); } diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c index 8412668478..03c947f341 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c +++ b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c @@ -963,8 +963,8 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_I ADC_JSQR_JL | ADC_JSQR_RK_JL(ADC_JSQR_JSQ1, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion), - ADC_JSQR_JL_SHIFT(sConfigInjected->InjectedNbrOfConversion) - | ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion)); + ADC_JSQR_JL_SHIFT(sConfigInjected->InjectedNbrOfConversion) | + ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion)); } else { /* Clear the old SQx bits for the selected rank */ MODIFY_REG(hadc->Instance->JSQR, diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c index e1f9b4e4ac..b973ec025d 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c +++ b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c @@ -321,9 +321,9 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) { assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); MPU->RBAR = MPU_Init->BaseAddress; - MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) - | ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) - | ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); + MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | + ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | + ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); } else { MPU->RBAR = 0x00U; MPU->RASR = 0x00U; diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c index b442a4432b..2c38ddb99f 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c +++ b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c @@ -3181,8 +3181,8 @@ void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c) { tmp2 = hi2c->XferCount; tmp3 = hi2c->State; tmp4 = hi2c->PreviousState; - if ((tmp1 == HAL_I2C_MODE_SLAVE) && (tmp2 == 0U) - && ((tmp3 == HAL_I2C_STATE_BUSY_TX) || (tmp3 == HAL_I2C_STATE_BUSY_TX_LISTEN) || ((tmp3 == HAL_I2C_STATE_LISTEN) && (tmp4 == I2C_STATE_SLAVE_BUSY_TX)))) { + if ((tmp1 == HAL_I2C_MODE_SLAVE) && (tmp2 == 0U) && + ((tmp3 == HAL_I2C_STATE_BUSY_TX) || (tmp3 == HAL_I2C_STATE_BUSY_TX_LISTEN) || ((tmp3 == HAL_I2C_STATE_LISTEN) && (tmp4 == I2C_STATE_SLAVE_BUSY_TX)))) { } else { hi2c->ErrorCode |= HAL_I2C_ERROR_AF; diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c index e56f9cbd01..56515b0b9b 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c +++ b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c @@ -360,8 +360,8 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { assert_param(IS_RCC_CALIBRATION_VALUE(RCC_OscInitStruct->HSICalibrationValue)); /* Check if HSI is used as system clock or as PLL source when PLL is selected as system clock */ - if ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI) - || ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI_DIV2))) { + if ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI) || + ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI_DIV2))) { /* When HSI is used as system clock it will not disabled */ if ((__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) && (RCC_OscInitStruct->HSIState != RCC_HSI_ON)) { return HAL_ERROR; @@ -416,8 +416,8 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { if ((RCC_OscInitStruct->PLL2.PLL2State) != RCC_PLL2_NONE) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { if ((RCC_OscInitStruct->PLL2.PLL2State) == RCC_PLL2_ON) { diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c index a3735b9b82..25e902fa0e 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c +++ b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c @@ -670,8 +670,8 @@ HAL_StatusTypeDef HAL_RCCEx_EnablePLL2(RCC_PLL2InitTypeDef *PLL2Init) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { /* Check the parameters */ @@ -730,8 +730,8 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLL2(void) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { /* Disable the main PLL2. */ diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c index 2fc30fd6f6..31a02a5cff 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c +++ b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c @@ -2450,8 +2450,8 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t Outpu UNUSED(OutputChannel); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -2541,8 +2541,8 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t Ou UNUSED(OutputChannel); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -2874,8 +2874,8 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channe TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); @@ -2997,8 +2997,8 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Cha TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); @@ -3142,11 +3142,11 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Ch return HAL_ERROR; } } else { - if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) - || (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) { + if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || + (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) { return HAL_BUSY; - } else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (channel_2_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY) - && (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) { + } else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (channel_2_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && + (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) { if ((((pData1 == NULL) || (pData2 == NULL))) && (Length > 0U)) { return HAL_ERROR; } else { diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c index 9d6123bf29..87f66c3fdc 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c +++ b/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c @@ -311,8 +311,8 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim) { assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -382,8 +382,8 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim) { assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } diff --git a/source/Core/BSP/Sequre_S60/port.c b/source/Core/BSP/Sequre_S60/port.c index 1b64177816..02d09c0e12 100644 --- a/source/Core/BSP/Sequre_S60/port.c +++ b/source/Core/BSP/Sequre_S60/port.c @@ -208,7 +208,8 @@ static void prvTaskExitError(void) { // therefore not output an 'unreachable code' warning for code that appears // after it. */ // } - for (;;) {} + for (;;) { + } } /*-----------------------------------------------------------*/ diff --git a/source/Core/BSP/Sequre_S60/system_stm32f1xx.c b/source/Core/BSP/Sequre_S60/system_stm32f1xx.c index f6c0db93bc..32d5b67444 100644 --- a/source/Core/BSP/Sequre_S60/system_stm32f1xx.c +++ b/source/Core/BSP/Sequre_S60/system_stm32f1xx.c @@ -3,8 +3,8 @@ #include "stm32f1xx.h" #if !defined(HSI_VALUE) -#define HSI_VALUE \ - 8000000U /*!< Default value of the Internal oscillator in Hz. \ +#define HSI_VALUE \ + 8000000U /*!< Default value of the Internal oscillator in Hz. \ This value can be provided and adapted by the user application. */ #endif /* HSI_VALUE */ diff --git a/source/Core/Drivers/BMA223.cpp b/source/Core/Drivers/BMA223.cpp index 6d0aa5077d..ab7757e589 100644 --- a/source/Core/Drivers/BMA223.cpp +++ b/source/Core/Drivers/BMA223.cpp @@ -22,18 +22,18 @@ bool BMA223::detect() { } static const ACCEL_I2C_CLASS::I2C_REG i2c_registers[] = { - // - // - {BMA223_PMU_RANGE, 0b00000011, 0}, // 2G range - {BMA223_PMU_BW, 0b00001101, 0}, // 250Hz filter - {BMA223_PMU_LPW, 0b00000000, 0}, // Full power - {BMA223_ACCD_HBW, 0b00000000, 0}, // filtered data out - {BMA223_INT_OUT_CTRL, 0b00001010, 0}, // interrupt active low and OD to get it hi-z + // + // + { BMA223_PMU_RANGE, 0b00000011, 0}, // 2G range + { BMA223_PMU_BW, 0b00001101, 0}, // 250Hz filter + { BMA223_PMU_LPW, 0b00000000, 0}, // Full power + { BMA223_ACCD_HBW, 0b00000000, 0}, // filtered data out + { BMA223_INT_OUT_CTRL, 0b00001010, 0}, // interrupt active low and OD to get it hi-z {BMA223_INT_RST_LATCH, 0b10000000, 0}, // interrupt active low and OD to get it hi-z - {BMA223_INT_EN_0, 0b01000000, 0}, // Enable orientation - {BMA223_INT_A, 0b00100111, 0}, // Setup orientation detection + { BMA223_INT_EN_0, 0b01000000, 0}, // Enable orientation + { BMA223_INT_A, 0b00100111, 0}, // Setup orientation detection - // + // }; bool BMA223::initalize() { // Setup acceleration readings diff --git a/source/Core/Drivers/I2CBB1.cpp b/source/Core/Drivers/I2CBB1.cpp index df83f3242d..bc250b3587 100644 --- a/source/Core/Drivers/I2CBB1.cpp +++ b/source/Core/Drivers/I2CBB1.cpp @@ -287,7 +287,8 @@ uint8_t I2CBB1::read_bit() { void I2CBB1::unlock() { xSemaphoreGive(I2CSemaphore); } bool I2CBB1::lock() { - if (I2CSemaphore == NULL) {} + if (I2CSemaphore == NULL) { + } bool a = xSemaphoreTake(I2CSemaphore, (TickType_t)100) == pdTRUE; return a; } diff --git a/source/Core/Drivers/I2CBB2.cpp b/source/Core/Drivers/I2CBB2.cpp index 6605018cd0..fee68bd16b 100644 --- a/source/Core/Drivers/I2CBB2.cpp +++ b/source/Core/Drivers/I2CBB2.cpp @@ -286,7 +286,8 @@ uint8_t I2CBB2::read_bit() { void I2CBB2::unlock() { xSemaphoreGive(I2CSemaphore); } bool I2CBB2::lock() { - if (I2CSemaphore == NULL) {} + if (I2CSemaphore == NULL) { + } bool a = xSemaphoreTake(I2CSemaphore, (TickType_t)100) == pdTRUE; return a; } diff --git a/source/Core/Drivers/LIS2DH12.cpp b/source/Core/Drivers/LIS2DH12.cpp index 2abb0216e2..1ff33ee41e 100644 --- a/source/Core/Drivers/LIS2DH12.cpp +++ b/source/Core/Drivers/LIS2DH12.cpp @@ -10,19 +10,21 @@ #include "LIS2DH12.hpp" #include "cmsis_os.h" -static const ACCEL_I2C_CLASS::I2C_REG i2c_registers[] = {{LIS_CTRL_REG1, 0x17, 0}, // 25Hz - {LIS_CTRL_REG2, 0b00001000, 0}, // Highpass filter off - {LIS_CTRL_REG3, 0b01100000, 0}, // Setup interrupt pins - {LIS_CTRL_REG4, 0b00001000, 0}, // Block update mode off, HR on - {LIS_CTRL_REG5, 0b00000010, 0}, // - {LIS_CTRL_REG6, 0b01100010, 0}, - // Basically setup the unit to run, and enable 4D orientation detection - {LIS_INT2_CFG, 0b01111110, 0}, // setup for movement detection - {LIS_INT2_THS, 0x28, 0}, // - {LIS_INT2_DURATION, 64, 0}, // - {LIS_INT1_CFG, 0b01111110, 0}, // - {LIS_INT1_THS, 0x28, 0}, // - {LIS_INT1_DURATION, 64, 0}}; +static const ACCEL_I2C_CLASS::I2C_REG i2c_registers[] = { + { LIS_CTRL_REG1, 0x17, 0}, // 25Hz + { LIS_CTRL_REG2, 0b00001000, 0}, // Highpass filter off + { LIS_CTRL_REG3, 0b01100000, 0}, // Setup interrupt pins + { LIS_CTRL_REG4, 0b00001000, 0}, // Block update mode off, HR on + { LIS_CTRL_REG5, 0b00000010, 0}, // + { LIS_CTRL_REG6, 0b01100010, 0}, + // Basically setup the unit to run, and enable 4D orientation detection + { LIS_INT2_CFG, 0b01111110, 0}, // setup for movement detection + { LIS_INT2_THS, 0x28, 0}, // + {LIS_INT2_DURATION, 64, 0}, // + { LIS_INT1_CFG, 0b01111110, 0}, // + { LIS_INT1_THS, 0x28, 0}, // + {LIS_INT1_DURATION, 64, 0} +}; bool LIS2DH12::initalize() { return ACCEL_I2C_CLASS::writeRegistersBulk(LIS2DH_I2C_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0])); } diff --git a/source/Core/Drivers/MMA8652FC.cpp b/source/Core/Drivers/MMA8652FC.cpp index 05a92e9e10..ac489d525d 100644 --- a/source/Core/Drivers/MMA8652FC.cpp +++ b/source/Core/Drivers/MMA8652FC.cpp @@ -11,19 +11,19 @@ #include static const ACCEL_I2C_CLASS::I2C_REG i2c_registers[] = { - {CTRL_REG2, 0, 0}, // Normal mode - {CTRL_REG2, 0x40, 2}, // Reset all registers to POR values - {FF_MT_CFG_REG, 0x78, 0}, // Enable motion detection for X, Y, Z axis, latch disabled - {PL_CFG_REG, 0x40, 0}, // Enable the orientation detection - {PL_COUNT_REG, 200, 0}, // 200 count debounce - {PL_BF_ZCOMP_REG, 0b01000111, 0}, // Set the threshold to 42 degrees - {P_L_THS_REG, 0b10011100, 0}, // Up the trip angles - {CTRL_REG4, 0x01 | (1 << 4), 0}, // Enable dataready interrupt & orientation interrupt - {CTRL_REG5, 0x01, 0}, // Route data ready interrupts to INT1 ->PB5 ->EXTI5, leaving orientation routed to INT2 - {CTRL_REG2, 0x12, 0}, // Set maximum resolution oversampling - {XYZ_DATA_CFG_REG, (1 << 4), 0}, // select high pass filtered data - {HP_FILTER_CUTOFF_REG, 0x03, 0}, // select high pass filtered data - {CTRL_REG1, 0x19, 0} // ODR=12 Hz, Active mode + { CTRL_REG2, 0, 0}, // Normal mode + { CTRL_REG2, 0x40, 2}, // Reset all registers to POR values + { FF_MT_CFG_REG, 0x78, 0}, // Enable motion detection for X, Y, Z axis, latch disabled + { PL_CFG_REG, 0x40, 0}, // Enable the orientation detection + { PL_COUNT_REG, 200, 0}, // 200 count debounce + { PL_BF_ZCOMP_REG, 0b01000111, 0}, // Set the threshold to 42 degrees + { P_L_THS_REG, 0b10011100, 0}, // Up the trip angles + { CTRL_REG4, 0x01 | (1 << 4), 0}, // Enable dataready interrupt & orientation interrupt + { CTRL_REG5, 0x01, 0}, // Route data ready interrupts to INT1 ->PB5 ->EXTI5, leaving orientation routed to INT2 + { CTRL_REG2, 0x12, 0}, // Set maximum resolution oversampling + { XYZ_DATA_CFG_REG, (1 << 4), 0}, // select high pass filtered data + {HP_FILTER_CUTOFF_REG, 0x03, 0}, // select high pass filtered data + { CTRL_REG1, 0x19, 0} // ODR=12 Hz, Active mode }; bool MMA8652FC::initalize() { return ACCEL_I2C_CLASS::writeRegistersBulk(MMA8652FC_I2C_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0])); } diff --git a/source/Core/Drivers/MSA301.cpp b/source/Core/Drivers/MSA301.cpp index 72ce023ca7..d732076963 100644 --- a/source/Core/Drivers/MSA301.cpp +++ b/source/Core/Drivers/MSA301.cpp @@ -13,14 +13,13 @@ bool MSA301::detect() { return ACCEL_I2C_CLASS::probe(MSA301_I2C_ADDRESS); } static const ACCEL_I2C_CLASS::I2C_REG i2c_registers[] = { - // - // - {MSA301_REG_ODR, 0b00001000, 1}, // X/Y/Z enabled @ 250Hz - {MSA301_REG_POWERMODE, 0b0001001, 1}, // Normal mode - {MSA301_REG_RESRANGE, 0b00000001, 0}, // 14bit resolution @ 4G range + // + // + { MSA301_REG_ODR, 0b00001000, 1}, // X/Y/Z enabled @ 250Hz + {MSA301_REG_POWERMODE, 0b0001001, 1}, // Normal mode + { MSA301_REG_RESRANGE, 0b00000001, 0}, // 14bit resolution @ 4G range {MSA301_REG_ORIENT_HY, 0b01000000, 0}, // 4*62.5mg hyst, no blocking, symmetrical - {MSA301_REG_INTSET0, 1 << 6, 0}, // Turn on orientation detection (by enabling its interrupt) - + { MSA301_REG_INTSET0, 1 << 6, 0}, // Turn on orientation detection (by enabling its interrupt) }; bool MSA301::initalize() { return ACCEL_I2C_CLASS::writeRegistersBulk(MSA301_I2C_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0])); } diff --git a/source/Core/Drivers/OLED.cpp b/source/Core/Drivers/OLED.cpp index 27f103fc5c..03668e624a 100644 --- a/source/Core/Drivers/OLED.cpp +++ b/source/Core/Drivers/OLED.cpp @@ -32,36 +32,36 @@ uint32_t OLED::displayChecksum; * Data packets are prefixed with 0x40 */ I2C_CLASS::I2C_REG OLED_Setup_Array[] = { - /**/ - {0x80, OLED_OFF, 0}, /* Display off */ - {0x80, OLED_DIVIDER, 0}, /* Set display clock divide ratio / osc freq */ - {0x80, 0x52, 0}, /* Divide ratios */ - {0x80, 0xA8, 0}, /* Set Multiplex Ratio */ - {0x80, OLED_HEIGHT - 1, 0}, /* Multiplex ratio adjusts how far down the matrix it scans */ - {0x80, 0xC0, 0}, /* Set COM Scan direction */ - {0x80, 0xD3, 0}, /* Set vertical Display offset */ - {0x80, 0x00, 0}, /* 0 Offset */ - {0x80, 0x40, 0}, /* Set Display start line to 0 */ + /**/ + {0x80, OLED_OFF, 0}, /* Display off */ + {0x80, OLED_DIVIDER, 0}, /* Set display clock divide ratio / osc freq */ + {0x80, 0x52, 0}, /* Divide ratios */ + {0x80, 0xA8, 0}, /* Set Multiplex Ratio */ + {0x80, OLED_HEIGHT - 1, 0}, /* Multiplex ratio adjusts how far down the matrix it scans */ + {0x80, 0xC0, 0}, /* Set COM Scan direction */ + {0x80, 0xD3, 0}, /* Set vertical Display offset */ + {0x80, 0x00, 0}, /* 0 Offset */ + {0x80, 0x40, 0}, /* Set Display start line to 0 */ #ifdef OLED_SEGMENT_MAP_REVERSED - {0x80, 0xA1, 0}, /* Set Segment remap to normal */ + {0x80, 0xA1, 0}, /* Set Segment remap to normal */ #else {0x80, 0xA0, 0}, /* Set Segment remap to normal */ #endif - {0x80, 0x8D, 0}, /* Charge Pump */ - {0x80, 0x14, 0}, /* Charge Pump settings */ - {0x80, 0xDA, 0}, /* Set VCOM Pins hardware config */ + {0x80, 0x8D, 0}, /* Charge Pump */ + {0x80, 0x14, 0}, /* Charge Pump settings */ + {0x80, 0xDA, 0}, /* Set VCOM Pins hardware config */ {0x80, OLED_VCOM_LAYOUT, 0}, /* Combination 0x2 or 0x12 depending on OLED model */ - {0x80, 0x81, 0}, /* Brightness */ - {0x80, 0x00, 0}, /* ^0 */ - {0x80, 0xD9, 0}, /* Set pre-charge period */ - {0x80, 0xF1, 0}, /* Pre charge period */ - {0x80, 0xDB, 0}, /* Adjust VCOMH regulator ouput */ - {0x80, 0x30, 0}, /* VCOM level */ - {0x80, 0xA4, 0}, /* Enable the display GDDR */ - {0x80, 0xA6, 0}, /* Normal display */ - {0x80, 0x20, 0}, /* Memory Mode */ - {0x80, 0x00, 0}, /* Wrap memory */ - {0x80, OLED_ON, 0}, /* Display on */ + {0x80, 0x81, 0}, /* Brightness */ + {0x80, 0x00, 0}, /* ^0 */ + {0x80, 0xD9, 0}, /* Set pre-charge period */ + {0x80, 0xF1, 0}, /* Pre charge period */ + {0x80, 0xDB, 0}, /* Adjust VCOMH regulator ouput */ + {0x80, 0x30, 0}, /* VCOM level */ + {0x80, 0xA4, 0}, /* Enable the display GDDR */ + {0x80, 0xA6, 0}, /* Normal display */ + {0x80, 0x20, 0}, /* Memory Mode */ + {0x80, 0x00, 0}, /* Wrap memory */ + {0x80, OLED_ON, 0}, /* Display on */ }; // Setup based on the SSD1307 and modified for the SSD1306 diff --git a/source/Core/Drivers/SC7A20.cpp b/source/Core/Drivers/SC7A20.cpp index 3e6a6a5324..7566d9d9ae 100644 --- a/source/Core/Drivers/SC7A20.cpp +++ b/source/Core/Drivers/SC7A20.cpp @@ -42,37 +42,39 @@ bool SC7A20::detect() { } static const ACCEL_I2C_CLASS::I2C_REG i2c_registers[] = { - // - // - {SC7A20_CTRL_REG1, 0b01100111, 0}, // 200Hz, XYZ enabled - {SC7A20_CTRL_REG2, 0b00000000, 0}, // Setup filter to 0x00 ?? - {SC7A20_CTRL_REG3, 0b00000000, 0}, // int1 off - {SC7A20_CTRL_REG4, 0b01001000, 0}, // Block mode off,little-endian,2G,High-pres,self test off - {SC7A20_CTRL_REG5, 0b00000100, 0}, // fifo off, D4D on int1 - {SC7A20_CTRL_REG6, 0x00, 0}, // INT2 off - // Basically setup the unit to run, and enable 4D orientation detection - {SC7A20_INT2_CFG, 0b01111110, 0}, // setup for movement detection - {SC7A20_INT2_THS, 0x28, 0}, // - {SC7A20_INT2_DURATION, 64, 0}, // - {SC7A20_INT1_CFG, 0b01111110, 0}, // - {SC7A20_INT1_THS, 0x28, 0}, // - {SC7A20_INT1_DURATION, 64, 0} + // + // + { SC7A20_CTRL_REG1, 0b01100111, 0}, // 200Hz, XYZ enabled + { SC7A20_CTRL_REG2, 0b00000000, 0}, // Setup filter to 0x00 ?? + { SC7A20_CTRL_REG3, 0b00000000, 0}, // int1 off + { SC7A20_CTRL_REG4, 0b01001000, 0}, // Block mode off,little-endian,2G,High-pres,self test off + { SC7A20_CTRL_REG5, 0b00000100, 0}, // fifo off, D4D on int1 + { SC7A20_CTRL_REG6, 0x00, 0}, // INT2 off + // Basically setup the unit to run, and enable 4D orientation detection + { SC7A20_INT2_CFG, 0b01111110, 0}, // setup for movement detection + { SC7A20_INT2_THS, 0x28, 0}, // + {SC7A20_INT2_DURATION, 64, 0}, // + { SC7A20_INT1_CFG, 0b01111110, 0}, // + { SC7A20_INT1_THS, 0x28, 0}, // + {SC7A20_INT1_DURATION, 64, 0} - // + // +}; +static const ACCEL_I2C_CLASS::I2C_REG i2c_registers_alt[] = { + { LIS_CTRL_REG1, 0b00110111, 0}, // 200Hz XYZ + { LIS_CTRL_REG2, 0b00000000, 0}, // + { LIS_CTRL_REG3, 0b01100000, 0}, // Setup interrupt pins + { LIS_CTRL_REG4, 0b00001000, 0}, // Block update mode off, HR on + { LIS_CTRL_REG5, 0b00000010, 0}, // + { LIS_CTRL_REG6, 0b01100010, 0}, + // Basically setup the unit to run, and enable 4D orientation detection + { LIS_INT2_CFG, 0b01111110, 0}, // setup for movement detection + { LIS_INT2_THS, 0x28, 0}, // + {LIS_INT2_DURATION, 64, 0}, // + { LIS_INT1_CFG, 0b01111110, 0}, // + { LIS_INT1_THS, 0x28, 0}, // + {LIS_INT1_DURATION, 64, 0} }; -static const ACCEL_I2C_CLASS::I2C_REG i2c_registers_alt[] = {{LIS_CTRL_REG1, 0b00110111, 0}, // 200Hz XYZ - {LIS_CTRL_REG2, 0b00000000, 0}, // - {LIS_CTRL_REG3, 0b01100000, 0}, // Setup interrupt pins - {LIS_CTRL_REG4, 0b00001000, 0}, // Block update mode off, HR on - {LIS_CTRL_REG5, 0b00000010, 0}, // - {LIS_CTRL_REG6, 0b01100010, 0}, - // Basically setup the unit to run, and enable 4D orientation detection - {LIS_INT2_CFG, 0b01111110, 0}, // setup for movement detection - {LIS_INT2_THS, 0x28, 0}, // - {LIS_INT2_DURATION, 64, 0}, // - {LIS_INT1_CFG, 0b01111110, 0}, // - {LIS_INT1_THS, 0x28, 0}, // - {LIS_INT1_DURATION, 64, 0}}; bool SC7A20::initalize() { // Setup acceleration readings diff --git a/source/Core/Drivers/USBPD.cpp b/source/Core/Drivers/USBPD.cpp index 276addb9cb..8ca000c504 100644 --- a/source/Core/Drivers/USBPD.cpp +++ b/source/Core/Drivers/USBPD.cpp @@ -46,7 +46,8 @@ void USBPowerDelivery::IRQOccured() { pe.IRQOccured(); } bool USBPowerDelivery::negotiationHasWorked() { return pe.pdHasNegotiated(); } uint8_t USBPowerDelivery::getStateNumber() { return pe.currentStateCode(true); } void USBPowerDelivery::step() { - while (pe.thread()) {} + while (pe.thread()) { + } } void USBPowerDelivery::PPSTimerCallback() { pe.TimersCallback(); } diff --git a/source/Core/Src/Settings.cpp b/source/Core/Src/Settings.cpp index 8d77bcda72..7ff16af78d 100644 --- a/source/Core/Src/Settings.cpp +++ b/source/Core/Src/Settings.cpp @@ -50,60 +50,60 @@ typedef struct { } SettingConstants; static const SettingConstants settingsConstants[(int)SettingsOptions::SettingsOptionsLength] = { - //{min,max,increment,default} - {MIN_TEMP_C, MAX_TEMP_F, 5, 320}, // SolderingTemp - {MIN_TEMP_C, MAX_TEMP_F, 5, 150}, // SleepTemp - {0, 15, 1, SLEEP_TIME}, // SleepTime - {0, 4, 1, CUT_OUT_SETTING}, // MinDCVoltageCells - {24, 38, 1, RECOM_VOL_CELL}, // MinVoltageCells - {90, QC_VOLTAGE_MAX, 2, 90}, // QCIdealVoltage - {0, 2, 1, ORIENTATION_MODE}, // OrientationMode - {0, 9, 1, SENSITIVITY}, // Sensitivity - {0, 1, 1, ANIMATION_LOOP}, // AnimationLoop - {0, settingOffSpeed_t::MAX_VALUE - 1, 1, ANIMATION_SPEED}, // AnimationSpeed - {0, 3, 1, AUTO_START_MODE}, // AutoStartMode - {0, 60, 1, SHUTDOWN_TIME}, // ShutdownTime - {0, 1, 1, COOLING_TEMP_BLINK}, // CoolingTempBlink - {0, 1, 1, DETAILED_IDLE}, // DetailedIDLE - {0, 1, 1, DETAILED_SOLDERING}, // DetailedSoldering - {0, (uint16_t)(HasFahrenheit ? 1 : 0), 1, TEMPERATURE_INF}, // TemperatureInF - {0, 1, 1, DESCRIPTION_SCROLL_SPEED}, // DescriptionScrollSpeed - {0, 2, 1, LOCKING_MODE}, // LockingMode - {0, 99, 1, POWER_PULSE_DEFAULT}, // KeepAwakePulse - {1, POWER_PULSE_WAIT_MAX, 1, POWER_PULSE_WAIT_DEFAULT}, // KeepAwakePulseWait - {1, POWER_PULSE_DURATION_MAX, 1, POWER_PULSE_DURATION_DEFAULT}, // KeepAwakePulseDuration - {360, 900, 1, VOLTAGE_DIV}, // VoltageDiv - {0, MAX_TEMP_F, 10, BOOST_TEMP}, // BoostTemp - {MIN_CALIBRATION_OFFSET, 2500, 1, CALIBRATION_OFFSET}, // CalibrationOffset - {0, MAX_POWER_LIMIT, POWER_LIMIT_STEPS, POWER_LIMIT}, // PowerLimit - {0, 1, 1, REVERSE_BUTTON_TEMP_CHANGE}, // ReverseButtonTempChangeEnabled - {5, TEMP_CHANGE_LONG_STEP_MAX, 5, TEMP_CHANGE_LONG_STEP}, // TempChangeLongStep - {1, TEMP_CHANGE_SHORT_STEP_MAX, 1, TEMP_CHANGE_SHORT_STEP}, // TempChangeShortStep - {0, 9, 1, 7}, // HallEffectSensitivity - {0, 9, 1, 0}, // AccelMissingWarningCounter - {0, 9, 1, 0}, // PDMissingWarningCounter - {0, 0xFFFF, 0, 41431 /*EN*/}, // UILanguage - {0, 50, 1, 20}, // PDNegTimeout - {0, 1, 1, 0}, // OLEDInversion - {MIN_BRIGHTNESS, MAX_BRIGHTNESS, BRIGHTNESS_STEP, DEFAULT_BRIGHTNESS}, // OLEDBrightness - {0, 6, 1, 1}, // LOGOTime - {0, 1, 1, 0}, // CalibrateCJC - {0, 1, 1, 0}, // BluetoothLE - {0, 1, 1, 1}, // PDVpdo - {1, 5, 1, 4}, // ProfilePhases - {MIN_TEMP_C, MAX_TEMP_F, 5, 90}, // ProfilePreheatTemp - {1, 10, 1, 1}, // ProfilePreheatSpeed - {MIN_TEMP_C, MAX_TEMP_F, 5, 130}, // ProfilePhase1Temp - {10, 180, 5, 90}, // ProfilePhase1Duration - {MIN_TEMP_C, MAX_TEMP_F, 5, 140}, // ProfilePhase2Temp - {10, 180, 5, 30}, // ProfilePhase2Duration - {MIN_TEMP_C, MAX_TEMP_F, 5, 165}, // ProfilePhase3Temp - {10, 180, 5, 30}, // ProfilePhase3Duration - {MIN_TEMP_C, MAX_TEMP_F, 5, 140}, // ProfilePhase4Temp - {10, 180, 5, 30}, // ProfilePhase4Duration - {MIN_TEMP_C, MAX_TEMP_F, 5, 90}, // ProfilePhase5Temp - {10, 180, 5, 30}, // ProfilePhase5Duration - {1, 10, 1, 2}, // ProfileCooldownSpeed + //{min,max,increment,default} + { MIN_TEMP_C, MAX_TEMP_F, 5, 320}, // SolderingTemp + { MIN_TEMP_C, MAX_TEMP_F, 5, 150}, // SleepTemp + { 0, 15, 1, SLEEP_TIME}, // SleepTime + { 0, 4, 1, CUT_OUT_SETTING}, // MinDCVoltageCells + { 24, 38, 1, RECOM_VOL_CELL}, // MinVoltageCells + { 90, QC_VOLTAGE_MAX, 2, 90}, // QCIdealVoltage + { 0, 2, 1, ORIENTATION_MODE}, // OrientationMode + { 0, 9, 1, SENSITIVITY}, // Sensitivity + { 0, 1, 1, ANIMATION_LOOP}, // AnimationLoop + { 0, settingOffSpeed_t::MAX_VALUE - 1, 1, ANIMATION_SPEED}, // AnimationSpeed + { 0, 3, 1, AUTO_START_MODE}, // AutoStartMode + { 0, 60, 1, SHUTDOWN_TIME}, // ShutdownTime + { 0, 1, 1, COOLING_TEMP_BLINK}, // CoolingTempBlink + { 0, 1, 1, DETAILED_IDLE}, // DetailedIDLE + { 0, 1, 1, DETAILED_SOLDERING}, // DetailedSoldering + { 0, (uint16_t)(HasFahrenheit ? 1 : 0), 1, TEMPERATURE_INF}, // TemperatureInF + { 0, 1, 1, DESCRIPTION_SCROLL_SPEED}, // DescriptionScrollSpeed + { 0, 2, 1, LOCKING_MODE}, // LockingMode + { 0, 99, 1, POWER_PULSE_DEFAULT}, // KeepAwakePulse + { 1, POWER_PULSE_WAIT_MAX, 1, POWER_PULSE_WAIT_DEFAULT}, // KeepAwakePulseWait + { 1, POWER_PULSE_DURATION_MAX, 1, POWER_PULSE_DURATION_DEFAULT}, // KeepAwakePulseDuration + { 360, 900, 1, VOLTAGE_DIV}, // VoltageDiv + { 0, MAX_TEMP_F, 10, BOOST_TEMP}, // BoostTemp + {MIN_CALIBRATION_OFFSET, 2500, 1, CALIBRATION_OFFSET}, // CalibrationOffset + { 0, MAX_POWER_LIMIT, POWER_LIMIT_STEPS, POWER_LIMIT}, // PowerLimit + { 0, 1, 1, REVERSE_BUTTON_TEMP_CHANGE}, // ReverseButtonTempChangeEnabled + { 5, TEMP_CHANGE_LONG_STEP_MAX, 5, TEMP_CHANGE_LONG_STEP}, // TempChangeLongStep + { 1, TEMP_CHANGE_SHORT_STEP_MAX, 1, TEMP_CHANGE_SHORT_STEP}, // TempChangeShortStep + { 0, 9, 1, 7}, // HallEffectSensitivity + { 0, 9, 1, 0}, // AccelMissingWarningCounter + { 0, 9, 1, 0}, // PDMissingWarningCounter + { 0, 0xFFFF, 0, 41431 /*EN*/}, // UILanguage + { 0, 50, 1, 20}, // PDNegTimeout + { 0, 1, 1, 0}, // OLEDInversion + { MIN_BRIGHTNESS, MAX_BRIGHTNESS, BRIGHTNESS_STEP, DEFAULT_BRIGHTNESS}, // OLEDBrightness + { 0, 6, 1, 1}, // LOGOTime + { 0, 1, 1, 0}, // CalibrateCJC + { 0, 1, 1, 0}, // BluetoothLE + { 0, 1, 1, 1}, // PDVpdo + { 1, 5, 1, 4}, // ProfilePhases + { MIN_TEMP_C, MAX_TEMP_F, 5, 90}, // ProfilePreheatTemp + { 1, 10, 1, 1}, // ProfilePreheatSpeed + { MIN_TEMP_C, MAX_TEMP_F, 5, 130}, // ProfilePhase1Temp + { 10, 180, 5, 90}, // ProfilePhase1Duration + { MIN_TEMP_C, MAX_TEMP_F, 5, 140}, // ProfilePhase2Temp + { 10, 180, 5, 30}, // ProfilePhase2Duration + { MIN_TEMP_C, MAX_TEMP_F, 5, 165}, // ProfilePhase3Temp + { 10, 180, 5, 30}, // ProfilePhase3Duration + { MIN_TEMP_C, MAX_TEMP_F, 5, 140}, // ProfilePhase4Temp + { 10, 180, 5, 30}, // ProfilePhase4Duration + { MIN_TEMP_C, MAX_TEMP_F, 5, 90}, // ProfilePhase5Temp + { 10, 180, 5, 30}, // ProfilePhase5Duration + { 1, 10, 1, 2}, // ProfileCooldownSpeed }; static_assert((sizeof(settingsConstants) / sizeof(SettingConstants)) == ((int)SettingsOptions::SettingsOptionsLength)); diff --git a/source/Core/Src/main.cpp b/source/Core/Src/main.cpp index 7b92316b8d..503fce5303 100644 --- a/source/Core/Src/main.cpp +++ b/source/Core/Src/main.cpp @@ -68,5 +68,6 @@ int main(void) { /* Start scheduler */ osKernelStart(); /* We should never get here as control is now taken by the scheduler */ - for (;;) {} + for (;;) { + } } diff --git a/source/Core/Threads/OperatingModes/HomeScreen.cpp b/source/Core/Threads/OperatingModes/HomeScreen.cpp index 7ac03e9eba..fa2511e8ac 100644 --- a/source/Core/Threads/OperatingModes/HomeScreen.cpp +++ b/source/Core/Threads/OperatingModes/HomeScreen.cpp @@ -197,8 +197,8 @@ void drawHomeScreen(bool buttonLockout) { // This is zero cost really as state is only changed on display updates OLED::setDisplayState(OLED::DisplayState::ON); - if ((tipTemp < 50) && getSettingValue(SettingsOptions::Sensitivity) - && (((xTaskGetTickCount() - lastMovementTime) > MOVEMENT_INACTIVITY_TIME) && ((xTaskGetTickCount() - lastButtonTime) > BUTTON_INACTIVITY_TIME))) { + if ((tipTemp < 50) && getSettingValue(SettingsOptions::Sensitivity) && + (((xTaskGetTickCount() - lastMovementTime) > MOVEMENT_INACTIVITY_TIME) && ((xTaskGetTickCount() - lastButtonTime) > BUTTON_INACTIVITY_TIME))) { OLED::setDisplayState(OLED::DisplayState::OFF); setStatusLED(LED_OFF); } else { diff --git a/source/Core/brieflz/depack.c b/source/Core/brieflz/depack.c index 4175be41a8..5252ce1213 100644 --- a/source/Core/brieflz/depack.c +++ b/source/Core/brieflz/depack.c @@ -37,305 +37,306 @@ struct blz_state { #if !defined(BLZ_NO_LUT) static const unsigned char blz_gamma_lookup[256][2] = { - /* 00xxxxxx = 2 */ - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - {2, 2}, - - /* 0100xxxx = 4 */ - {4, 4}, - {4, 4}, - {4, 4}, - {4, 4}, - {4, 4}, - {4, 4}, - {4, 4}, - {4, 4}, - {4, 4}, - {4, 4}, - {4, 4}, - {4, 4}, - {4, 4}, - {4, 4}, - {4, 4}, - {4, 4}, - - /* 010100xx = 8 */ - {8, 6}, - {8, 6}, - {8, 6}, - {8, 6}, - - /* 01010100 = 16 01010101 = 16+ 01010110 = 17 01010111 = 17+ */ + /* 00xxxxxx = 2 */ + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + + /* 0100xxxx = 4 */ + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + + /* 010100xx = 8 */ + { 8, 6}, + { 8, 6}, + { 8, 6}, + { 8, 6}, + + /* 01010100 = 16 01010101 = 16+ 01010110 = 17 01010111 = 17+ */ {16, 8}, {16, 0}, {17, 8}, {17, 0}, - /* 010110xx = 9 */ - {9, 6}, - {9, 6}, - {9, 6}, - {9, 6}, + /* 010110xx = 9 */ + { 9, 6}, + { 9, 6}, + { 9, 6}, + { 9, 6}, - /* 01011100 = 18 01011101 = 18+ 01011110 = 19 01011111 = 19+ */ + /* 01011100 = 18 01011101 = 18+ 01011110 = 19 01011111 = 19+ */ {18, 8}, {18, 0}, {19, 8}, {19, 0}, - /* 0110xxxx = 5 */ - {5, 4}, - {5, 4}, - {5, 4}, - {5, 4}, - {5, 4}, - {5, 4}, - {5, 4}, - {5, 4}, - {5, 4}, - {5, 4}, - {5, 4}, - {5, 4}, - {5, 4}, - {5, 4}, - {5, 4}, - {5, 4}, - - /* 011100xx = 10 */ + /* 0110xxxx = 5 */ + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + + /* 011100xx = 10 */ {10, 6}, {10, 6}, {10, 6}, {10, 6}, - /* 01110100 = 20 01110101 = 20+ 01110110 = 21 01110111 = 21+ */ + /* 01110100 = 20 01110101 = 20+ 01110110 = 21 01110111 = 21+ */ {20, 8}, {20, 0}, {21, 8}, {21, 0}, - /* 011110xx = 11 */ + /* 011110xx = 11 */ {11, 6}, {11, 6}, {11, 6}, {11, 6}, - /* 01111100 = 22 01111101 = 22+ 01111110 = 23 01111111 = 23+ */ + /* 01111100 = 22 01111101 = 22+ 01111110 = 23 01111111 = 23+ */ {22, 8}, {22, 0}, {23, 8}, {23, 0}, - /* 10xxxxxx = 3 */ - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - {3, 2}, - - /* 1100xxxx = 6 */ - {6, 4}, - {6, 4}, - {6, 4}, - {6, 4}, - {6, 4}, - {6, 4}, - {6, 4}, - {6, 4}, - {6, 4}, - {6, 4}, - {6, 4}, - {6, 4}, - {6, 4}, - {6, 4}, - {6, 4}, - {6, 4}, - - /* 110100xx = 12 */ + /* 10xxxxxx = 3 */ + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + + /* 1100xxxx = 6 */ + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + + /* 110100xx = 12 */ {12, 6}, {12, 6}, {12, 6}, {12, 6}, - /* 11010100 = 24 11010101 = 24+ 11010110 = 25 11010111 = 25+ */ + /* 11010100 = 24 11010101 = 24+ 11010110 = 25 11010111 = 25+ */ {24, 8}, {24, 0}, {25, 8}, {25, 0}, - /* 110110xx = 13 */ + /* 110110xx = 13 */ {13, 6}, {13, 6}, {13, 6}, {13, 6}, - /* 11011100 = 26 11011101 = 26+ 11011110 = 27 11011111 = 27+ */ + /* 11011100 = 26 11011101 = 26+ 11011110 = 27 11011111 = 27+ */ {26, 8}, {26, 0}, {27, 8}, {27, 0}, - /* 1110xxxx = 7 */ - {7, 4}, - {7, 4}, - {7, 4}, - {7, 4}, - {7, 4}, - {7, 4}, - {7, 4}, - {7, 4}, - {7, 4}, - {7, 4}, - {7, 4}, - {7, 4}, - {7, 4}, - {7, 4}, - {7, 4}, - {7, 4}, - - /* 111100xx = 14 */ + /* 1110xxxx = 7 */ + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + + /* 111100xx = 14 */ {14, 6}, {14, 6}, {14, 6}, {14, 6}, - /* 11110100 = 28 11110101 = 28+ 11110110 = 29 11110111 = 29+ */ + /* 11110100 = 28 11110101 = 28+ 11110110 = 29 11110111 = 29+ */ {28, 8}, {28, 0}, {29, 8}, {29, 0}, - /* 111110xx = 15 */ + /* 111110xx = 15 */ {15, 6}, {15, 6}, {15, 6}, {15, 6}, - /* 11111100 = 30 11111101 = 30+ 11111110 = 31 11111111 = 31+ */ + /* 11111100 = 30 11111101 = 30+ 11111110 = 31 11111111 = 31+ */ {30, 8}, {30, 0}, {31, 8}, - {31, 0}}; + {31, 0} +}; #endif static unsigned int blz_getbit(struct blz_state *bs) { From c281021ca0a6f45a69748a40e8ec774540494840 Mon Sep 17 00:00:00 2001 From: "Ben V. Brown" Date: Wed, 27 Dec 2023 00:21:30 +1100 Subject: [PATCH 18/18] Excempt the table for compression from formatter --- source/Core/brieflz/brieflz.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source/Core/brieflz/brieflz.c b/source/Core/brieflz/brieflz.c index 84fb061f46..ef904b92eb 100644 --- a/source/Core/brieflz/brieflz.c +++ b/source/Core/brieflz/brieflz.c @@ -75,6 +75,7 @@ struct blz_state { int bits_left; }; +// clang-format off #if !defined(BLZ_NO_LUT) static const unsigned short blz_gamma_lookup[512][2] = { {0, 0}, {0, 0}, @@ -129,6 +130,7 @@ static const unsigned short blz_gamma_lookup[512][2] = { {0xFDFC, 16}, {0xFDFE, 16}, {0xFF54, 16}, {0xFF56, 16}, {0xFF5C, 16}, {0xFF5E, 16}, {0xFF74, 16}, {0xFF76, 16}, {0xFF7C, 16}, {0xFF7E, 16}, {0xFFD4, 16}, {0xFFD6, 16}, {0xFFDC, 16}, {0xFFDE, 16}, {0xFFF4, 16}, {0xFFF6, 16}, {0xFFFC, 16}, {0xFFFE, 16}}; #endif +// clang-format on static int blz_log2(unsigned long n) { assert(n > 0);