code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/** mbed Microcontroller Library ****************************************************************************** * @file sleep_ex_api.h * @author * @version V1.0.0 * @brief This file provides mbed API for SLEEP. ****************************************************************************** * @attention * * Copyright (c) 2015, Realtek Semiconductor Corp. * All rights reserved. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. ****************************************************************************** */ #ifndef MBED_SLEEP_EX_API_H #define MBED_SLEEP_EX_API_H #include "device.h" #ifdef __cplusplus extern "C" { #endif /** @addtogroup sleep_ex SLEEP_EX * @ingroup hal * @brief sleep extended functions * @{ */ #if defined(CONFIG_PLATFORM_8195A) && (CONFIG_PLATFORM_8195A == 1) ///@name Ameba1 Only ///@{ /* Sleep Eake Up event, the User application also need to config the peripheral to trigger wake up event */ #define SLEEP_WAKEUP_BY_STIMER (SLP_STIMER) // wake up by system timer #define SLEEP_WAKEUP_BY_GTIMER (SLP_GTIMER) // wake up by General purpose timer timeout #define SLEEP_WAKEUP_BY_GPIO_INT (SLP_GPIO) // wake up by GPIO Port A[7:0] Interrupt #define SLEEP_WAKEUP_BY_WLAN (SLP_WL) // wake up by WLan event #define SLEEP_WAKEUP_BY_NFC (SLP_NFC) // wake up by NFC event #define SLEEP_WAKEUP_BY_SDIO (SLP_SDIO) // wake up by SDIO event #define SLEEP_WAKEUP_BY_USB (SLP_USB) // wake up by USB event // Deep Standby Wakeup event #define STANDBY_WAKEUP_BY_STIMER (BIT0) // wake up by system timer #define STANDBY_WAKEUP_BY_NFC (BIT1) // wake up by NFC event //#define SLEEP_WAKEUP_BY_DS_TIMER (BIT2) // The timer to wakeup from Deep Sleep timer // Do not modify these definition, or need to modify the code also. #define STANDBY_WAKEUP_BY_PA5 (BIT4) // GPIO Port A[5] #define STANDBY_WAKEUP_BY_PC7 (BIT5) // GPIO Port C[7] #define STANDBY_WAKEUP_BY_PD5 (BIT6) // GPIO Port D[5] #define STANDBY_WAKEUP_BY_PE3 (BIT7) // GPIO Port E[3] // Deep Sleep Wakeup event #define DSLEEP_WAKEUP_BY_TIMER (DS_TIMER33) #define DSLEEP_WAKEUP_BY_GPIO (DS_GPIO) // GPIO Port B[1] typedef struct _SLEEP_WKUP_EVENT_ { u8 wakeup_event; // Wake up event: Timer, NFC, GPIO u8 gpio_option; // GPIO Wakeup setting: [3:0]: Pin 3~0 enable, [7:4]: pin3~0 active high/low u32 timer_duration; // the sleep duration and then wakeup } SLEEP_WAKEUP_EVENT, *PSLEEP_WAKEUP_EVENT; ///@} #endif //CONFIG_PLATFORM_8195A #if defined(CONFIG_PLATFORM_8711B) && (CONFIG_PLATFORM_8711B == 1) ///@name AmebaZ Only ///@{ /* Sleep Eake Up event, the User application also need to config the peripheral to trigger wake up event */ #define SLEEP_WAKEUP_BY_STIMER (BIT_SYSON_WEVT_SYSTIM_MSK) // wake up by system timer #define SLEEP_WAKEUP_BY_GPIO_INT (BIT_SYSON_WEVT_GPIO_MSK) // wake up by GPIO Port A[31:0] Interrupt #define SLEEP_WAKEUP_BY_WLAN (BIT_SYSON_WEVT_WLAN_MSK) // wake up by WLan event #define SLEEP_WAKEUP_BY_SDIO (BIT_SYSON_WEVT_SDIO_MSK) // wake up by SDIO event #define SLEEP_WAKEUP_BY_USB (BIT_SYSON_WEVT_USB_MSK) // wake up by USB event #define SLEEP_WAKEUP_BY_GPIO (BIT_SYSON_WEVT_GPIO_DSTBY_MSK) // GPIO Port(PA_18, PA_5, PA_22, PA_23) #define SLEEP_WAKEUP_BY_UART (BIT_SYSON_WEVT_UART0_MSK | BIT_SYSON_WEVT_UART1_MSK) // wake up by UART event #define SLEEP_WAKEUP_BY_I2C (BIT_SYSON_WEVT_I2C0_MSK | BIT_SYSON_WEVT_I2C1_MSK) // wake up by I2C event #define SLEEP_WAKEUP_BY_RTC (BIT_SYSON_WEVT_RTC_MSK) // wake up by RTC event // Deep Standby Wakeup event #define STANDBY_WAKEUP_BY_STIMER (BIT_SYSON_WEVT_A33_AND_A33GPIO_MSK) // wake up by 1K timer #define STANDBY_WAKEUP_BY_GPIO (BIT_SYSON_WEVT_GPIO_DSTBY_MSK) // GPIO Port(PA_18, PA_5, PA_22, PA_23) #define STANDBY_WAKEUP_BY_RTC (BIT_SYSON_WEVT_RTC_MSK) // wake up by RTC event // Deep Sleep Wakeup event #define DSLEEP_WAKEUP_BY_TIMER BIT(0) #define DSLEEP_WAKEUP_BY_GPIO BIT(2) // GPIO Port(PA_18, PA_5, PA_22, PA_23) typedef struct _SLEEP_WKUP_EVENT_ { u32 wakeup_event; // Wake up event: Timer, NFC, GPIO u32 gpio_option; // GPIO Wakeup setting: [3:0]: Pin 3~0 enable, [11:8]: pin3~0 active high/low u32 timer_duration; // the sleep duration and then wakeup } SLEEP_WAKEUP_EVENT, *PSLEEP_WAKEUP_EVENT; ///@} #endif //CONFIG_PLATFORM_8711B ///@name Ameba Common ///@{ /** * @brief To make the system entering the Clock Gated power saving. * This function just make the system to enter the clock gated * power saving mode and pending on wake up event waitting. * The user application need to configure the peripheral to * generate system wake up event, like GPIO interrupt, * G-Timer timeout, etc. befor entering power saving mode. * @param wakeup_event: A bit map of wake up event. * This parameter can be any combination of the following values: * @arg SLEEP_WAKEUP_BY_STIMER * @arg SLEEP_WAKEUP_BY_GTIMER * @arg SLEEP_WAKEUP_BY_GPIO_INT * @arg SLEEP_WAKEUP_BY_WLAN * @arg SLEEP_WAKEUP_BY_SDIO * @arg SLEEP_WAKEUP_BY_USB * @arg SLEEP_WAKEUP_BY_GPIO * @arg SLEEP_WAKEUP_BY_UART * @arg SLEEP_WAKEUP_BY_I2C * @arg SLEEP_WAKEUP_BY_RTC * @arg SLEEP_WAKEUP_BY_RESETPIN * @param sleep_duration: the system sleep duration in ms, only valid * for SLEEP_WAKEUP_BY_STIMER wake up event. * @retval None */ void sleep_ex(uint32_t wakeup_event, uint32_t sleep_duration); /** * @brief To make the system entering the Clock Gated power saving. * This function just make the system to enter the clock gated * power saving mode and pending on wake up event waitting. * The user application need to configure the peripheral to * generate system wake up event, like GPIO interrupt * , G-Timer timeout, etc. befor entering power saving mode. * @param wakeup_event: A bit map of wake up event. * This parameter can be any combination of the following values: * @arg SLEEP_WAKEUP_BY_STIMER * @arg SLEEP_WAKEUP_BY_GTIMER * @arg SLEEP_WAKEUP_BY_GPIO_INT * @arg SLEEP_WAKEUP_BY_WLAN * @arg SLEEP_WAKEUP_BY_SDIO * @arg SLEEP_WAKEUP_BY_USB * @arg SLEEP_WAKEUP_BY_GPIO * @arg SLEEP_WAKEUP_BY_UART * @arg SLEEP_WAKEUP_BY_I2C * @arg SLEEP_WAKEUP_BY_RTC * @arg SLEEP_WAKEUP_BY_RESETPIN * @param sleep_duration: the system sleep duration in ms, only valid * for SLEEP_WAKEUP_BY_STIMER wake up event. * @param clk_sourec_enable: the option for SCLK on(1)/off(0) * @param sdr_enable: the option for turn off the SDR controller (1:off, 0:on) * @retval None */ void sleep_ex_selective(uint32_t wakeup_event, uint32_t sleep_duration, uint32_t clk_sourec_enable, uint32_t sdr_enable); #if defined(CONFIG_PLATFORM_8195A) && (CONFIG_PLATFORM_8195A == 1) ///@name Ameba1 Only ///@{ /** * @brief To make the system entering the Deep Standby power saving. * The CPU, memory and part fo peripheral power is off when * entering deep standby power saving mode. The program needs * to be reload from the flash at system resume. * @retval None */ void deepstandby_ex(void); ///@} #endif //CONFIG_PLATFORM_8195A #if defined(CONFIG_PLATFORM_8711B) && (CONFIG_PLATFORM_8711B == 1) ///@name AmebaZ Only ///@{ /** * @brief To make the system entering the Deep Standby power saving. * The CPU, memory and part fo peripheral power is off when * entering deep standby power saving mode. The program needs * to be reload from the flash at system resume. * @param sleep_duration_ms: the system sleep duration in ms, only valid * for STANDBY_WAKEUP_BY_STIMER wake up event. * @retval None */ void deepstandby_ex(uint32_t sleep_duration_ms); ///@} #endif //CONFIG_PLATFORM_8711B /** * @brief To make the system entering the Deep Sleep power saving mode. * The CPU, memory and peripheral power is off when entering * deep sleep power saving mode. The program needs to be reload * and all peripheral needs be re-configure when system resume. * @param wakeup_event: A bit map of wake up event. * This parameter can be any combination of the following values: * @arg DSLEEP_WAKEUP_BY_TIMER * @arg DSLEEP_WAKEUP_BY_GPIO * @param sleep_duration: the system sleep duration in ms, only valid * for DSLEEP_WAKEUP_BY_TIMER wake up event. * @retval None */ void deepsleep_ex(uint32_t wakeup_event, uint32_t sleep_duration); #if defined(CONFIG_PLATFORM_8195A) && (CONFIG_PLATFORM_8195A == 1) ///@name Ameba1 Only ///@{ /** * @brief To add a wake up event to wake up the system from the * deep standby power saving mode. * @param wakeup_event: A bit map of wake up event. * This parameter can be any combination of the following values: * @arg STANDBY_WAKEUP_BY_STIMER * @arg STANDBY_WAKEUP_BY_GPIO * @arg STANDBY_WAKEUP_BY_RTC * @arg STANDBY_WAKEUP_BY_RESETPIN * @param sleep_duration_ms: the system sleep duration in ms, only valid * for STANDBY_WAKEUP_BY_STIMER wake up event. * @param gpio_option: for a GPIO pin to wake up the system by goes high or low * This parameter can be any combination of the following values: * @arg WAKEUP_BY_GPIO_NONE * @arg WAKEUP_BY_GPIO_WAKEUP0_LOW * @arg WAKEUP_BY_GPIO_WAKEUP0_HIG * @arg WAKEUP_BY_GPIO_WAKEUP1_LOW * @arg WAKEUP_BY_GPIO_WAKEUP1_HIG * @arg WAKEUP_BY_GPIO_WAKEUP2_LOW * @arg WAKEUP_BY_GPIO_WAKEUP2_HIG * @arg WAKEUP_BY_GPIO_WAKEUP3_LOW * @arg WAKEUP_BY_GPIO_WAKEUP3_HIG * @retval None */ void standby_wakeup_event_add(uint32_t wakeup_event, uint32_t sleep_duration_ms, uint32_t gpio_active); ///@} #endif //CONFIG_PLATFORM_8195A #if defined(CONFIG_PLATFORM_8711B) && (CONFIG_PLATFORM_8711B == 1) ///@name AmebaZ Only ///@{ /** * @brief To add a wake up event to wake up the system from the * deep standby power saving mode. * @param wakeup_event: A bit map of wake up event. * This parameter can be any combination of the following values: * @arg STANDBY_WAKEUP_BY_STIMER * @arg STANDBY_WAKEUP_BY_GPIO * @arg STANDBY_WAKEUP_BY_RTC * @arg STANDBY_WAKEUP_BY_RESETPIN * @param gpio_option: for a GPIO pin to wake up the system by goes high or low * This parameter can be any combination of the following values: * @arg WAKEUP_BY_GPIO_NONE * @arg WAKEUP_BY_GPIO_WAKEUP0_LOW * @arg WAKEUP_BY_GPIO_WAKEUP0_HIG * @arg WAKEUP_BY_GPIO_WAKEUP1_LOW * @arg WAKEUP_BY_GPIO_WAKEUP1_HIG * @arg WAKEUP_BY_GPIO_WAKEUP2_LOW * @arg WAKEUP_BY_GPIO_WAKEUP2_HIG * @arg WAKEUP_BY_GPIO_WAKEUP3_LOW * @arg WAKEUP_BY_GPIO_WAKEUP3_HIG * @retval None */ void standby_wakeup_event_add(uint32_t wakeup_event, uint32_t gpio_active); ///@} #endif //CONFIG_PLATFORM_8711B /** * @brief To delete a wake up event for wakeing up the system from the * deep standby power saving mode. * @param wakeup_event: A bit map of wake up event. * This parameter can be any combination of the following values: * @arg STANDBY_WAKEUP_BY_STIMER * @arg STANDBY_WAKEUP_BY_GPIO * @arg STANDBY_WAKEUP_BY_RTC * @arg STANDBY_WAKEUP_BY_RESETPIN * @retval None */ void standby_wakeup_event_del(uint32_t wakeup_event); ///@} #ifdef __cplusplus } #endif //#endif /*\@}*/ #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/hal_ext/sleep_ex_api.h
C
apache-2.0
11,817
/****************************************************************************** * * Copyright(c) 2007 - 2021 Realtek Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ #ifndef __SPDIO_API_H__ #define __SPDIO_API_H__ #include <osdep_service.h> /** @addtogroup spdio_api SPDIO * @ingroup hal * @brief spdio functions * @{ */ ///@name Ameba Common ///@{ #define SPDIO_API_DBG #ifdef SPDIO_API_DBG #define SPDIO_API_PRINTK(fmt, args...) printf(fmt"\r\n",## args) #define _SPDIO_API_PRINTK(fmt, args...) printf(fmt,## args) #else #define SPDIO_API_PRINTK(fmt, args...) #define _SPDIO_API_PRINTK(fmt, args...) #endif #define SPDIO_DMA_ALIGN_4 4 #define SPDIO_RX_BUFSZ_ALIGN(x) ((((x-1)>>6)+1)<<6) //alignement to 64 #define SPDIO_RXDESC_SZ 24 /*Don't modify this enum table*/ enum spdio_rx_data_t{ SPDIO_RX_DATA_NULL = 0x00, SPDIO_RX_DATA_ETH = 0x83, //an ethernet packet received SPDIO_RX_DATA_ATCMD = 0x11, //an AT command packet received SPDIO_RX_DATA_USER = 0x41, //defined by user }; enum spdio_tx_data_t{ SPDIO_TX_DATA_NULL = 0x00, SPDIO_TX_DATA_ETH = 0x82, //an ethernet packet sent SPDIO_TX_DATA_ATCMDRSP = 0x10, //an AT command response packet sent SPDIO_TX_DATA_USER = 0x40, // defined by user }; struct spdio_buf_t{ void *priv; //priv data from user u32 buf_allocated; //The spdio buffer allocated address u16 size_allocated; //The actual allocated size u32 buf_addr; //The spdio buffer physical address, it must be 4-bytes aligned u16 buf_size; u8 type; //The type of the data which this buffer carries, spdio_rx_data_t and spdio_tx_data_t u8 reserved; }; struct spdio_t { void *priv; //not used by user u32 tx_bd_num; //for spdio send data to host, 2 bd for one packet, so this value must be rounded to 2 u32 rx_bd_num; //for spdio receive data from host u32 rx_bd_bufsz; //buffer size = desired packet length + 24(spdio header info), must be rounded to 64 struct spdio_buf_t *rx_buf; //buffer array for spdio receive assigned by user, rx_bd_bufsz * rx_bd_num /** *@brief pointer to callback function defined by user, called by spdio when one packet receive done *@param priv: a pointer to spdio_t structure which is used to initilize spdio interface *@param pbuf: a pointer to spdio_buf_t structure which is spdio receive buffer *@param pdata: the actual received packet payload *@param size: the actual payload length *@param type: the received packet type, spdio_rx_data_t *@retval SUCCESS or FAIL */ char (*rx_done_cb)(void *priv, void* pbuf, u8 *pdata, u16 size, u8 type); /** *@brief pointer to callback function defined by user, called by spdio when one packet sent done *@param priv: a pointer to spdio_t structure which is used to initilize spdio interface *@param pbuf: a pointer to spdio_buf_t structure which carries the transmit packet *@retval SUCCESS or FAIL */ char (*tx_done_cb)(void *priv, void* pbuf); }; /** * @brief Gets example setting for spdio obj. * @param obj: a pointer to an spdio_t structure which will be initialized with an example settings * @retval None */ void spdio_structinit(struct spdio_t *obj); /** * @brief Initialize spdio interface. * @param obj, a pointer to a spdio_t structure which should be initialized by user, * and which will be used to initialize spdio interface * obj->tx_bd_num: spdio write bd number, needs 2 bd for one transaction * obj->rx_bd_num: spdio read bd number * obj->rx_bd_bufsz: spdio read buffer size * obj->rx_buf: spdio read buffer array * @retval None */ void spdio_init(struct spdio_t *obj); /** * @brief Deinitialize spdio interface. * @param obj: a pointer to spdio_t structure which is already initialized * @retval None */ void spdio_deinit(struct spdio_t *obj); /** * @brief spdio write function. * @param obj: a pointer to spdio_t structure which is already initialized * @param pbuf: a pointer to spdio_buf_t structure which carries the payload * @retval SUCCESS or FAIL */ s8 spdio_tx(struct spdio_t *obj, struct spdio_buf_t *pbuf); /** * @brief an obj which will be used to initialize sdio interface * so it must be initialized before calling HalSdioInit(); */ extern struct spdio_t *g_spdio_priv; ///@} /*\@}*/ #endif //#ifndef __SPDIO_API_H__
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/hal_ext/spdio_api.h
C
apache-2.0
4,944
/****************************************************************************** * * Copyright(c) 2007 - 2021 Realtek Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ /** mbed Microcontroller Library ****************************************************************************** * @file spi_ex_api.h * @author * @version V1.0.0 * @brief This file provides following mbed SPI API ****************************************************************************** */ #ifndef MBED_SPI_EXT_API_H #define MBED_SPI_EXT_API_H #include "device.h" #ifdef __cplusplus extern "C" { #endif /** @addtogroup spi_ex SPI_EX * @ingroup hal * @brief spi extended functions * @{ */ ///@name Ameba Common ///@{ #define SPI_DMA_RX_EN (1<<0) #define SPI_DMA_TX_EN (1<<1) enum { SPI_SCLK_IDLE_LOW=0, // the SCLK is Low when SPI is inactive SPI_SCLK_IDLE_HIGH=2 // the SCLK is High when SPI is inactive }; // SPI Master mode: for continuous transfer, how the CS toggle: enum { SPI_CS_TOGGLE_EVERY_FRAME=0, // let SCPH=0 then the CS toggle every frame SPI_CS_TOGGLE_START_STOP=1 // let SCPH=1 the CS toggle at start and stop }; enum { SPI_SCLK_TOGGLE_MIDDLE=0, // Serial Clk toggle at middle of 1st data bit and latch data at 1st Clk edge SPI_SCLK_TOGGLE_START=1 // Serial Clk toggle at start of 1st data bit and latch data at 2nd Clk edge }; typedef enum { CS_0 = 0, CS_1 = 1, CS_2 = 2, CS_3 = 3, CS_4 = 4, CS_5 = 5, CS_6 = 6, CS_7 = 7 }ChipSelect; #define SPI_STATE_READY 0x00 #define SPI_STATE_RX_BUSY (1<<1) #define SPI_STATE_TX_BUSY (1<<2) typedef enum { SpiRxIrq, SpiTxIrq } SpiIrq; typedef void (*spi_irq_handler)(uint32_t id, SpiIrq event); /** * @brief Set SPI interrupt handler if needed. * @param obj: spi object define in application software. * @param handler: interrupt callback function * @param id: interrupt callback parameter * @retval none */ void spi_irq_hook(spi_t *obj, spi_irq_handler handler, uint32_t id); /** * @brief Set SPI interrupt bus tx done handler if needed. * @param obj: spi object define in application software. * @param handler: interrupt bus tx done callback function * @param id: interrupt callback parameter * @retval none */ void spi_bus_tx_done_irq_hook(spi_t *obj, spi_irq_handler handler, uint32_t id); /** * @brief Slave device to flush tx fifo. * @param obj: spi slave object define in application software. * @note : It will discard all data in both tx fifo and rx fifo */ void spi_slave_flush_fifo(spi_t * obj); /** * @brief slave recv target length data use interrupt mode. * @param obj: spi slave object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @retval : stream init status */ int32_t spi_slave_read_stream(spi_t *obj, char *rx_buffer, uint32_t length); /** * @brief slave send target length data use interrupt mode. * @param obj: spi slave object define in application software. * @param tx_buffer: buffer to be written to Tx FIFO. * @param length: number of data bytes to be send. * @retval : stream init status */ int32_t spi_slave_write_stream(spi_t *obj, char *tx_buffer, uint32_t length); /** * @brief master recv target length data use interrupt mode. * @param obj: spi master object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @retval : stream init status */ int32_t spi_master_read_stream(spi_t *obj, char *rx_buffer, uint32_t length); /** * @brief master send target length data use interrupt mode. * @param obj: spi master object define in application software. * @param tx_buffer: buffer to be written to Tx FIFO. * @param length: number of data bytes to be send. * @retval : stream init status */ int32_t spi_master_write_stream(spi_t *obj, char *tx_buffer, uint32_t length); /** * @brief master send & recv target length data use interrupt mode. * @param obj: spi master object define in application software. * @param tx_buffer: buffer to be written to Tx FIFO. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be send & recv. * @retval : stream init status */ int32_t spi_master_write_read_stream(spi_t *obj, char *tx_buffer, uint32_t tx_size, char *rx_buffer, uint32_t rx_size); /** * @brief slave recv target length data use interrupt mode and timeout mechanism. * @param obj: spi slave object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @param timeout_ms: timeout waiting time. * @retval : number of bytes read already */ int32_t spi_slave_read_stream_timeout(spi_t *obj, char *rx_buffer, uint32_t length, uint32_t timeout_ms); /** * @brief slave recv target length data use interrupt mode and stop if the spi bus is idle. * @param obj: spi slave object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @retval : number of bytes read already */ int32_t spi_slave_read_stream_terminate(spi_t *obj, char *rx_buffer, uint32_t length); //#ifdef CONFIG_GDMA_EN /** * @brief slave recv target length data use DMA mode. * @param obj: spi slave object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @retval : stream init status */ int32_t spi_slave_read_stream_dma(spi_t *obj, char *rx_buffer, uint32_t length); /** * @brief slave send target length data use DMA mode. * @param obj: spi slave object define in application software. * @param tx_buffer: buffer to be written to Tx FIFO. * @param length: number of data bytes to be send. * @retval : stream init status */ int32_t spi_slave_write_stream_dma(spi_t *obj, char *tx_buffer, uint32_t length); /** * @brief master send & recv target length data use DMA mode. * @param obj: spi master object define in application software. * @param tx_buffer: buffer to be written to Tx FIFO. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be send & recv. * @retval : stream init status */ int32_t spi_master_write_read_stream_dma(spi_t * obj, char * tx_buffer, char * rx_buffer, uint32_t length); /** * @brief master recv target length data use DMA mode. * @param obj: spi master object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @retval : stream init status * @note : DMA or Interrupt mode can be used to TX dummy data */ int32_t spi_master_read_stream_dma(spi_t *obj, char *rx_buffer, uint32_t length); /** * @brief master send target length data use DMA mode. * @param obj: spi master object define in application software. * @param tx_buffer: buffer to be written to Tx FIFO. * @param length: number of data bytes to be send. * @retval : stream init status */ int32_t spi_master_write_stream_dma(spi_t *obj, char *tx_buffer, uint32_t length); /** * @brief slave recv target length data use DMA mode and timeout mechanism. * @param obj: spi slave object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @param timeout_ms: timeout waiting time. * @retval : number of bytes read already */ int32_t spi_slave_read_stream_dma_timeout(spi_t *obj, char *rx_buffer, uint32_t length, uint32_t timeout_ms); /** * @brief slave recv target length data use DMA mode and stop if the spi bus is idle. * @param obj: spi slave object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @retval : number of bytes read already */ int32_t spi_slave_read_stream_dma_terminate(spi_t * obj, char * rx_buffer, uint32_t length); //#endif ///@} /*\@}*/ #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/hal_ext/spi_ex_api.h
C
apache-2.0
9,079
/** mbed Microcontroller Library ****************************************************************************** * @file sys_api.h * @author * @version V1.0.0 * @brief This file provides following mbed system API: * -JTAG OFF * -LOGUART ON/OFF * -OTA image switch * -System Reset ****************************************************************************** * @attention * * Copyright (c) 2015, Realtek Semiconductor Corp. * All rights reserved. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. ****************************************************************************** */ #ifndef MBED_SYS_API_H #define MBED_SYS_API_H #include "device.h" #ifdef __cplusplus extern "C" { #endif /** @addtogroup sys SYSTEM * @ingroup hal * @brief system functions * @{ */ ///@name Ameba Common ///@{ /** * @brief Turn off the JTAG function * @retval none */ void sys_jtag_off(void); /** * @brief switch OTA image if the othe OTA image is valid * @retval none * @note for AmebaZ, sys_clear_ota_signature is the same with sys_recover_ota_signature */ void sys_clear_ota_signature(void); /** * @brief switch OTA image if the othe OTA image is valid * @retval none * @note for AmebaZ, sys_clear_ota_signature is the same with sys_recover_ota_signature */ void sys_recover_ota_signature(void); /** * @brief open log uart * @retval none */ void sys_log_uart_on(void); /** * @brief close log uart * @retval none */ void sys_log_uart_off(void); /** * @brief store or load adc calibration parameter * @param write: this parameter can be one of the following values: * @arg 0: load adc calibration parameter offset & gain from flash system data region * @arg 1: store adc calibration parameter offset & gain to flash system data region * @param offset: pointer to adc parameter offset * @param gain: pointer to adc parameter gain * @retval none */ void sys_adc_calibration(u8 write, u16 *offset, u16 *gain); /** * @brief system software reset * @retval none */ void sys_reset(void); ///@} #if defined(CONFIG_PLATFORM_8195A) && (CONFIG_PLATFORM_8195A == 1) ///@name Ameba1 Only ///@{ /** * @brief check whether is sdram power on * @retval 1: power on * 0: power off */ u8 sys_is_sdram_power_on(void); /** * @brief sdram power off * @retval none */ void sys_sdram_off(void); ///@} #endif //CONFIG_PLATFORM_8195A #if defined(CONFIG_PLATFORM_8711B) && (CONFIG_PLATFORM_8711B == 1) ///@name AmebaZ Only ///@{ /** * @brief vector reset * @retval none */ void sys_cpu_reset(void); ///@} #endif //CONFIG_PLATFORM_8711B /*\@}*/ #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/hal_ext/sys_api.h
C
apache-2.0
2,825
/** mbed Microcontroller Library ****************************************************************************** * @file wdt_api.h * @author * @version V1.0.0 * @brief This file provides following mbed WDT API ****************************************************************************** * @attention * * Copyright (c) 2015, Realtek Semiconductor Corp. * All rights reserved. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. ****************************************************************************** */ #ifndef MBED_WATCHDOG_API_H #define MBED_WATCHDOG_API_H #include "device.h" #ifdef __cplusplus extern "C" { #endif /** @addtogroup wdt WDT * @ingroup hal * @brief wdt functions * @{ */ ///@name Ameba Common ///@{ typedef void (*wdt_irq_handler)(uint32_t id); /** * @brief Initializes the watch dog, include time setting, mode register * @param timeout_ms: the watch-dog timer timeout value, in ms. * default action of timeout is to reset the whole system. * @retval none */ void watchdog_init(uint32_t timeout_ms); /** * @brief Start the watchdog counting * @param None * @retval none */ void watchdog_start(void); /** * @brief Stop the watchdog counting * @param None * @retval none */ void watchdog_stop(void); /** * @brief Refresh the watchdog counting to prevent WDT timeout * @param None * @retval none */ void watchdog_refresh(void); /** * @brief Switch the watchdog timer to interrupt mode and * register a watchdog timer timeout interrupt handler. * The interrupt handler will be called when the watch-dog * timer is timeout. * @param handler: the callback function for WDT timeout interrupt. * @param id: the parameter for the callback function * @retval none */ void watchdog_irq_init(wdt_irq_handler handler, uint32_t id); ///@} /*\@}*/ #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/hal_ext/wdt_api.h
C
apache-2.0
2,081
/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBED_PERIPHERALNAMES_H #define MBED_PERIPHERALNAMES_H #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif typedef enum { UART_0 = (int)UART0_DEV, UART_1 = (int)UART1_DEV, UART_2 = (int)UART2_DEV, UART_3 = (int)UART3_DEV, } UARTName; typedef enum { ADC0_0 = 0, ADC0_1, ADC0_2, ADC0_3 } ADCName; typedef enum { SPI_0 = (int)SPI0_DEV, SPI_1 = (int)SPI1_DEV, } SPIName; typedef enum { I2C_0 = (int)I2C0_DEV, } I2CName; typedef enum { PWM_0 = 1, PWM_1, PWM_2, PWM_3, PWM_4, PWM_5 } PWMName; #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/PeripheralNames.h
C
apache-2.0
1,194
/****************************************************************************** * * Copyright(c) 2007 - 2021 Realtek Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ #ifndef _PINNAMES_H_ #define _PINNAMES_H_ #include "cmsis.h" #ifdef __cplusplus extern "C" { #endif #define PIN_DATA(PUPD, FUNC) (((PUPD) << 6) | (FUNC)) #define PIN_PIN_PUPD(X) ((X) & 0x03) /* PullNone/PullUp/PullDown */ #define PIN_FUNC(X) ((X) & 0x0F) /* PINMUX_FUNCTION_XXXX */ typedef enum { PORT_A = 0, PORT_B = 1, } GPIO_PORT; typedef enum { PIN_INPUT=0, PIN_OUTPUT } PinDirection; /* (((port)<<5)|(pin)) */ typedef enum { PA_0 = (PORT_A<<5|0), PA_1 = (PORT_A<<5|1), PA_2 = (PORT_A<<5|2), PA_3 = (PORT_A<<5|3), PA_4 = (PORT_A<<5|4), PA_5 = (PORT_A<<5|5), PA_6 = (PORT_A<<5|6), PA_7 = (PORT_A<<5|7), PA_8 = (PORT_A<<5|8), PA_9 = (PORT_A<<5|9), PA_10 = (PORT_A<<5|10), PA_11 = (PORT_A<<5|11), PA_12 = (PORT_A<<5|12), PA_13 = (PORT_A<<5|13), PA_14 = (PORT_A<<5|14), PA_15 = (PORT_A<<5|15), PA_16 = (PORT_A<<5|16), PA_17 = (PORT_A<<5|17), PA_18 = (PORT_A<<5|18), PA_19 = (PORT_A<<5|19), PA_20 = (PORT_A<<5|20), PA_21 = (PORT_A<<5|21), PA_22 = (PORT_A<<5|22), PA_23 = (PORT_A<<5|23), PA_24 = (PORT_A<<5|24), PA_25 = (PORT_A<<5|25), PA_26 = (PORT_A<<5|26), PA_27 = (PORT_A<<5|27), PA_28 = (PORT_A<<5|28), PA_29 = (PORT_A<<5|29), PA_30 = (PORT_A<<5|30), PA_31 = (PORT_A<<5|31), PB_0 = (PORT_B<<5|0), PB_1 = (PORT_B<<5|1), PB_2 = (PORT_B<<5|2), PB_3 = (PORT_B<<5|3), PB_4 = (PORT_B<<5|4), PB_5 = (PORT_B<<5|5), PB_6 = (PORT_B<<5|6), PB_7 = (PORT_B<<5|7), PB_8 = (PORT_B<<5|8), PB_9 = (PORT_B<<5|9), PB_10 = (PORT_B<<5|10), PB_11 = (PORT_B<<5|11), PB_12 = (PORT_B<<5|12), PB_13 = (PORT_B<<5|13), PB_14 = (PORT_B<<5|14), PB_15 = (PORT_B<<5|15), PB_16 = (PORT_B<<5|16), PB_17 = (PORT_B<<5|17), PB_18 = (PORT_B<<5|18), PB_19 = (PORT_B<<5|19), PB_20 = (PORT_B<<5|20), PB_21 = (PORT_B<<5|21), PB_22 = (PORT_B<<5|22), PB_23 = (PORT_B<<5|23), PB_24 = (PORT_B<<5|24), PB_25 = (PORT_B<<5|25), PB_26 = (PORT_B<<5|26), PB_27 = (PORT_B<<5|27), PB_28 = (PORT_B<<5|28), PB_29 = (PORT_B<<5|29), PB_30 = (PORT_B<<5|30), PB_31 = (PORT_B<<5|31), VBAT_MEAS = (0x7<<5|2), AD_0 = PB_4, //CH0 AD_1 = PB_5, //CH1 AD_2 = PB_6, //CH2 AD_3 = PB_7, //CH3 AD_4 = PB_1, //CH4 AD_5 = PB_2, //CH5 AD_6 = PB_3, //CH6 AD_7 = VBAT_MEAS,//CH7 // Not connected NC = (uint32_t)0xFFFFFFFF } PinName; typedef enum { PullNone = 0, //IN HIGHZ PullUp = 1, PullDown = 2, PullDefault = PullNone } PinMode; #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/PinNames.h
C
apache-2.0
3,280
/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBED_PORTNAMES_H #define MBED_PORTNAMES_H #ifdef __cplusplus extern "C" { #endif typedef enum { PortA = 0, PortB = 1, } PortName; #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/PortNames.h
C
apache-2.0
811
/** mbed Microcontroller Library ****************************************************************************** * @file analogin_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for ADC. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "objects.h" #include "PinNames.h" #include "analogin_api.h" #include "pinmap.h" static const PinMap PinMap_ADC[] = { {PB_4, ADC_CH0, 0}, {PB_5, ADC_CH1, 0}, {PB_6, ADC_CH2, 0}, {PB_7, ADC_CH3, 0}, {PB_1, ADC_CH4, 0}, {PB_2, ADC_CH5, 0}, {PB_3, ADC_CH6, 0}, {VBAT_MEAS, ADC_CH7, 0}, {NC, NC, 0} }; /** @defgroup AmebaD_Mbed_API * @{ */ /** @defgroup analog_in MBED_ADC * @brief MBED_ADC driver modules. * @{ */ /** @defgroup MBED_ADC_Exported_Functions MBED_ADC Exported Functions * @{ */ /** * @brief Initializes the ADC device, include clock/function/ADC registers. * @param obj: adc object define in application software. * @param pin: adc PinName according to pinmux spec. * @retval none */ void analogin_init(analogin_t *obj, PinName pin) { ADC_InitTypeDef ADC_InitStruct; uint32_t adc_idx; adc_idx = pinmap_peripheral(pin, PinMap_ADC); DBG_8195A("analogin_init [%x:%x ]\n", pin, adc_idx); assert_param(adc_idx != NC); /* Set ADC channel Number */ obj->adc_idx = adc_idx; /* Initialize ADC */ ADC_StructInit(&ADC_InitStruct); ADC_InitStruct.ADC_CvlistLen = 0; ADC_Init(&ADC_InitStruct); ADC_Cmd(ENABLE); } /** * @brief Reads data from the specified adc channel fifo. * @param obj: adc object define in application software. * @retval adc channel data(float) */ float analogin_read(analogin_t *obj) { float value; uint32_t AnalogDatFull = 0xFFF; uint8_t ChIdx = obj->adc_idx; uint32_t data; /* Set channel index into channel switch list*/ ADC->ADC_CHSW_LIST[0] = ChIdx; /* Clear FIFO */ ADC_ClearFIFO(); /* SW trigger to sample */ ADC_SWTrigCmd(ENABLE); while(ADC_Readable()== 0); ADC_SWTrigCmd(DISABLE); data = ADC_Read(); value = (float)(data) / (float)(AnalogDatFull); return (float)value; } /** * @brief Reads data from the specified adc channel fifo. * @param obj: adc object define in application software. * @retval 16bit adc channel data(int) */ uint16_t analogin_read_u16(analogin_t *obj) { uint8_t ChIdx = obj->adc_idx; uint32_t data; /* Set channel index into channel switch list*/ ADC->ADC_CHSW_LIST[0] = ChIdx; /* Clear FIFO */ ADC_ClearFIFO(); /* SW trigger to sample */ ADC_SWTrigCmd(ENABLE); while(ADC_Readable()== 0); ADC_SWTrigCmd(DISABLE); data = ADC_Read(); return (uint16_t)(data & BIT_MASK_DAT_GLOBAL); } /** * @brief Deinitializes the ADC device, include clock/function/ADC registers. * @param obj: adc object define in application software. * @retval none */ void analogin_deinit(analogin_t *obj) { /* To avoid gcc warnings */ ( void ) obj; /* Clear ADC Status */ ADC_INTClear(); /* Disable ADC */ ADC_Cmd(DISABLE); } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/analogin_api.c
C
apache-2.0
3,543
/** mbed Microcontroller Library ****************************************************************************** * @file captouch_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for CAPTOUCH. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "objects.h" #include "captouch_api.h" #include "PinNames.h" #include "pinmap.h" typedef void (*ctc_irq_handler)(u8 ch); /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_CAPTOUCH * @brief MBED_CAPTOUCH driver modules. * @{ */ /** @defgroup MBED_CAPTOUCH_Exported_Functions MBED_CAPTOUCH Exported Functions * @{ */ /** * @brief captouch related function and interrupt handler. * @param obj: captouch object define in application software. * @retval none */ static void captouch_irq_handler(captouch_t *obj) { u8 ch; u32 IntStatus; ctc_irq_handler handler_press; ctc_irq_handler handler_release; IntStatus = CapTouch_GetISR(CAPTOUCH_DEV); CapTouch_INTClearPendingBit(CAPTOUCH_DEV, IntStatus); for(ch = 0; ch < CT_CHANNEL_NUM; ch++) { if(IntStatus & CT_CHX_PRESS_INT(ch)) { DBG_8195A("Key %x press \n",ch); if (obj->irq_handler_press) { handler_press = (ctc_irq_handler)obj->irq_handler_press; handler_press(ch); } } if(IntStatus & CT_CHX_RELEASE_INT(ch)) { DBG_8195A("Key %x release \n", ch); if (obj->irq_handler_release) { handler_release = (ctc_irq_handler)obj->irq_handler_release; handler_release(ch); } } } /* User do not need care the Noise interrupt */ if(IntStatus & BIT_CT_OVER_P_NOISE_THRESHOLD_INT) { CapTouch_Cmd(CAPTOUCH_DEV, DISABLE); CapTouch_Cmd(CAPTOUCH_DEV, ENABLE); } } /** * @brief initializes the captouch device. * @param obj: captouch object define in application software. * @retval none */ void captouch_init (captouch_t *obj) { u32 ch = 0; CapTouch_InitTypeDef Touch_InitStruct; /* Load HAL initial data structure default value */ Touch_InitStruct.CT_DebounceEn = 1; Touch_InitStruct.CT_SampleCnt = 6; Touch_InitStruct.CT_ScanInterval = 60; Touch_InitStruct.CT_ETCStep = 1; Touch_InitStruct.CT_ETCFactor = 4; Touch_InitStruct.CT_ETCScanInterval = 3; for(ch = 0; ch < CT_CHANNEL_NUM; ch++) { if (obj->CT_Channel[ch].CT_CHEnable == ENABLE) { Touch_InitStruct.CT_Channel[ch].CT_CHEnable = obj->CT_Channel[ch].CT_CHEnable; Touch_InitStruct.CT_Channel[ch].CT_DiffThrehold = obj->CT_Channel[ch].CT_DiffThrehold; Touch_InitStruct.CT_Channel[ch].CT_MbiasCurrent = obj->CT_Channel[ch].CT_MbiasCurrent; Touch_InitStruct.CT_Channel[ch].CT_ETCNNoiseThr = obj->CT_Channel[ch].CT_ETCNNoiseThr; Touch_InitStruct.CT_Channel[ch].CT_ETCPNoiseThr = obj->CT_Channel[ch].CT_ETCPNoiseThr; PAD_PullCtrl((_PB_4 + ch), GPIO_PuPd_NOPULL); } } CapTouch_Init(CAPTOUCH_DEV, &Touch_InitStruct); CapTouch_Cmd(CAPTOUCH_DEV, ENABLE); CapTouch_INTConfig(CAPTOUCH_DEV, BIT_CT_ALL_INT_EN, ENABLE); /* Register interrupt Callback function */ InterruptRegister((IRQ_FUN) captouch_irq_handler, CTOUCH_IRQ, (u32)obj, 5); InterruptEn(CTOUCH_IRQ, 5); } /** * @brief deinitializes the captouch device. * @param obj: captouch object define in application software. * @retval none */ void captouch_deinit (captouch_t *obj) { /* To avoid gcc warnings */ ( void ) obj; InterruptDis(CTOUCH_IRQ); InterruptUnRegister(CTOUCH_IRQ); CapTouch_INTConfig(CAPTOUCH_DEV, BIT_CT_ALL_INT_EN, DISABLE); CapTouch_Cmd(CAPTOUCH_DEV, DISABLE); } /** * @brief enable specified channel. * @param obj: captouch object define in application software. * @param Channel: specified channel index, which can be 0~3 * @retval none */ void captouch_ch_enable(captouch_t *obj, u8 Channel) { /* To avoid gcc warnings */ ( void ) obj; CapTouch_ChCmd(CAPTOUCH_DEV, Channel, ENABLE); } /** * @brief disable specified channel. * @param obj: captouch object define in application software. * @param Channel: specified channel index, which can be 0~3 * @retval none */ void captouch_ch_disable(captouch_t *obj, u8 Channel) { /* To avoid gcc warnings */ ( void ) obj; CapTouch_ChCmd(CAPTOUCH_DEV, Channel, DISABLE); } /** * @brief set captouch scan interval. * @param obj: captouch object define in application software. * @param Interval: scan interval in units of ms * @retval none */ void captouch_set_scan_interval(captouch_t *obj, u32 Interval) { /* To avoid gcc warnings */ ( void ) obj; CapTouch_SetScanInterval(CAPTOUCH_DEV, Interval); } /** * @brief read baseline data from specified channel. * @param obj: captouch object define in application software. * @param Channel: specified channel index, which can be 0~3 * @retval baseline data */ u32 captouch_get_ch_baseline(captouch_t *obj, u8 Channel) { /* To avoid gcc warnings */ ( void ) obj; return CapTouch_GetChBaseline(CAPTOUCH_DEV, Channel); } /** * @brief read average data from specified channel. * @param obj: captouch object define in application software. * @param Channel: specified channel index, which can be 0~3 * @retval average data */ u32 captouch_get_ch_data(captouch_t *obj, u8 Channel) { /* To avoid gcc warnings */ ( void ) obj; return CapTouch_GetChAveData(CAPTOUCH_DEV, Channel); } /** * @} */ /** * @} */ /** * @} */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/captouch_api.c
C
apache-2.0
5,731
/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBED_DEVICE_H #define MBED_DEVICE_H #define DEVICE_PORTIN 1 #define DEVICE_PORTOUT 1 #define DEVICE_PORTINOUT 1 #define DEVICE_INTERRUPTIN 1 #define DEVICE_ANALOGIN 1 #define DEVICE_ANALOGOUT 0 #define DEVICE_SERIAL 1 #define DEVICE_I2C 1 #define DEVICE_I2CSLAVE 1 #define DEVICE_SPI 1 #define DEVICE_SPISLAVE 1 #define DEVICE_CAN 0 #define DEVICE_RTC 1 #define DEVICE_ETHERNET 0 #define DEVICE_PWMOUT 1 #define DEVICE_SLEEP 1 #include "objects.h" #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/device.h
C
apache-2.0
1,263
/** mbed Microcontroller Library ****************************************************************************** * @file dma_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed GDMA API for memcopy ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "dma_api.h" #include "cmsis.h" /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_GDMA * @brief MBED_GDMA driver modules. * @{ */ /** @defgroup MBED_GDMA_Exported_Functions MBED_GDMA Exported Functions * @{ */ static void dma_memcpy_int(void *pData) { gdma_t *dma_obj = (gdma_t *)pData; /* Clean Auto Reload Bit */ GDMA_ChCleanAutoReload(dma_obj->index, dma_obj->ch_num, CLEAN_RELOAD_DST); /* Clear Pending ISR */ GDMA_ClearINT(dma_obj->index, dma_obj->ch_num); GDMA_Cmd(dma_obj->index, dma_obj->ch_num, DISABLE); if (dma_obj->user_cb != NULL) { dma_obj->user_cb((VOID*)dma_obj->user_cb_data); } } /** * @brief Initial the GDMA * @param dma_obj: the GDMA object * @param handler: the callback function for a DMA transfer complete. * @param id: the argument of the callback function. * @retval None * */ void dma_memcpy_init(gdma_t *dma_obj, dma_irq_handler handler, uint32_t id) { u8 ch_num; dma_obj->index = 0; ch_num = GDMA_ChnlAlloc(dma_obj->index, (IRQ_FUN) dma_memcpy_int, (u32)dma_obj, 10); if (0xFF == ch_num) { DBG_8195A("%s: Cannot allocate a GDMA Channel\n", __FUNCTION__); return; } dma_obj->user_cb = (IRQ_FUN)handler; dma_obj->user_cb_data = id; dma_obj->ch_num = ch_num; } /** * @brief De-Initial the GDMA * @param dma_obj: the GDMA object * @retval None * */ void dma_memcpy_deinit(gdma_t *dma_obj) { GDMA_ChnlFree(dma_obj->index, dma_obj->ch_num); } /** * @brief To do a memory copy by DMA * @param dma_obj: the GDMA object * @param dst: destination memory address * @param src: source memory address * @param len: copy data length * @retval None */ void dma_memcpy(gdma_t *dma_obj, void *dst, void* src, uint32_t len) { GDMA_InitTypeDef GDMA_InitStruct; _memset((void *)&GDMA_InitStruct, 0, sizeof(GDMA_InitTypeDef)); GDMA_InitStruct.GDMA_ChNum = dma_obj->ch_num; GDMA_InitStruct.GDMA_Index = dma_obj->index; GDMA_InitStruct.GDMA_IsrType = (TransferType|ErrType); DBG_PRINTF(MODULE_GDMA, LEVEL_INFO, "%s: ==> Src=0x%x Dst=0x%x Len=%d\r\n", __FUNCTION__, src, dst, len); if ((((u32)src & 0x03)==0) && (((u32)dst & 0x03)==0) && ((len & 0x03)== 0)) { /* 4-bytes aligned, move 4 bytes each transfer */ GDMA_InitStruct.GDMA_SrcMsize = MsizeEight; GDMA_InitStruct.GDMA_SrcDataWidth = TrWidthFourBytes; GDMA_InitStruct.GDMA_DstMsize = MsizeEight; GDMA_InitStruct.GDMA_DstDataWidth = TrWidthFourBytes; GDMA_InitStruct.GDMA_BlockSize = len >> 2; } else { GDMA_InitStruct.GDMA_SrcMsize = MsizeEight; GDMA_InitStruct.GDMA_SrcDataWidth = TrWidthOneByte; GDMA_InitStruct.GDMA_DstMsize = MsizeEight; GDMA_InitStruct.GDMA_DstDataWidth = TrWidthOneByte; GDMA_InitStruct.GDMA_BlockSize = len; } GDMA_InitStruct.GDMA_SrcAddr = (u32)src; GDMA_InitStruct.GDMA_DstAddr = (u32)dst; GDMA_Init(dma_obj->index, dma_obj->ch_num, &GDMA_InitStruct); GDMA_Cmd(dma_obj->index, dma_obj->ch_num, ENABLE); } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/dma_api.c
C
apache-2.0
3,801
/** mbed Microcontroller Library ****************************************************************************** * @file efuse_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for EFUSE. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "ameba_soc.h" #include "rom_aes.h" //#ifdef CONFIG_EFUSE_EN /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_EFUSE * @brief MBED_EFUSE driver modules. * @{ */ /** @defgroup MBED_EFUSE_Exported_Functions MBED_EFUSE Exported Functions * @{ */ /** * @brief Get remaining efuse length * @retval remaining efuse length */ int efuse_get_remaining_length(void) { return EFUSE_RemainLength(); } /** * @brief Read efuse content of specified user * @param data: Specified the address to save the readback data. * @retval none * @note read user MTP(0x160~0x17f). */ void efuse_mtp_read(uint8_t * data) { u8 EfuseBuf[1024]; u8 ret; /*0xff will be efuse default value instead of 0x00. */ _memset(data, 0xFF, 32); ret = EFUSE_LMAP_READ(EfuseBuf); if (ret == _FAIL) { DBG_8195A("EFUSE_LogicalMap_Read fail \n"); } _memcpy(data, EfuseBuf+0x160, 32); } /** * @brief Write user's content to efuse * @param data: Specified the data to be programmed. * @param len: Specifies the data length of programmed data. * @retval status value: * - 1~32: Success * - 0 or -1: Failure * @note read user MTP(0x160~0x17f). */ int efuse_mtp_write(uint8_t *data, uint8_t len) { u32 bResult; if(len > 32) { DBG_8195A("string length should be smaller than 32\n"); return -1; } bResult = EFUSE_LMAP_WRITE(USER_SECTION << 3, len, data); if(!bResult){ DBG_8195A("write fail \n"); return -1; }else{ return len; } } /** * @brief Read efuse OTP contant * @param address: Specifies the offset of the OTP. * @param len: Specifies the length of readback data. * @param buf: Specified the address to save the readback data. * @retval status value: * - 0: Success * - -1: Failure * @note read user OTP(0x130~0x14f). */ int efuse_otp_read(u8 address, u8 len, u8 *buf) { u8 content[32]; // the OTP max length is 32 u8 index; u32 bResult; if((address+len) > 32) { return -1; } for (index = 0; index< 32; index++) { bResult = EFUSE_PMAP_READ8(0, 0x130 + index , content + index, L25EOUTVOLTAGE); if(!bResult){ return -1; } } _memcpy(buf, content+address, len); return 0; } /** * @brief Write user's contant to OTP efuse * @param address: Specifies the offset of the programmed OTP. * @param len: Specifies the data length of programmed data. * @param buf: Specified the data to be programmed. * @retval status value: * - 0: Success * - -1: Failure * @note read user OTP(0x130~0x14f). */ int efuse_otp_write(u8 address, u8 len, u8 *buf) { u8 index; u32 bResult; if((address+len) > 32) { return -1; } for (index = 0; index < len; index++) { bResult = EFUSE_PMAP_WRITE8(0, address + 0x130 +index, buf[index], L25EOUTVOLTAGE); if(!bResult){ return -1; } } return 0; } /** * @brief check user's contant to OTP efuse * @param *buf: Specified the data to be programmed. * @param len: Specifies the data length of programmed data. * @retval status: Success:0 or Failure: -1. */ int efuse_otp_chk(u8 len, u8 *buf) { /* To avoid gcc warnings */ ( void ) len; ( void ) buf; DBG_8195A("Ameba-D not support efuse_otp_chk function!\n"); return 0; } /** * @} */ /** * @} */ /** * @} */ //#endif /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/efuse_api.c
C
apache-2.0
4,113
/** mbed Microcontroller Library ****************************************************************************** * @file flash_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for flash. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "objects.h" #include "PinNames.h" #include "pinmap.h" #include "ameba_soc.h" #include "flash_api.h" extern u32 ConfigDebugInfo; /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_FLASH * @brief MBED_FLASH driver modules. * @{ */ /** @defgroup MBED_FLASH_Exported_Functions MBED_FLASH Exported Functions * @{ */ /** * @brief Control the flash chip write protect enable/disable. * @param obj: Flash object define in application software. * @param protect: This parameter can be 1 or 0. * @arg 1: Protect the whole chip from being programmed/erased. * @arg 0: Unprotect the whole chip from being programmed/erased. * @retval none */ void flash_write_protect(flash_t *obj, u32 protect) { /* To avoid gcc warnings */ ( void ) obj; FLASH_Write_Lock(); FLASH_SetStatusBits(0x1c, protect); FLASH_Write_Unlock(); } /** * @brief Set Status register to enable desired operation * @param obj: Flash object define in application software. * @param data: Specifies which bit users like to set. * ex: if users want to set the third bit, data = 0x8. * @retval 1: Success or Others: Failure. * @note Please refer to the datatsheet of flash for more details of the content of status register. * The block protected area and the corresponding control bits are provided in the flash datasheet. */ int flash_set_status(flash_t *obj, u32 data) { /* To avoid gcc warnings */ ( void ) obj; u8 status[2]; u8 StatusLen = 1; status[0] = (u8)data; FLASH_Write_Lock(); /* check if status2 */ if (flash_init_para.FLASH_Status2_exist) { StatusLen = 2; FLASH_RxCmd(flash_init_para.FLASH_cmd_rd_status2, 1, &status[1]); } if(!flash_init_para.FLASH_cmd_wr_status2){ FLASH_SetStatus(flash_init_para.FLASH_cmd_wr_status, StatusLen, status); } else { FLASH_SetStatus(flash_init_para.FLASH_cmd_wr_status, 1, &status[0]); FLASH_SetStatus(flash_init_para.FLASH_cmd_wr_status2, 1, &status[1]); } FLASH_Write_Unlock(); return 1; } /** * @brief This function aims to reset the status register to 0, please make sure the operation is appropriate. * @param obj: Flash object define in application software. * @retval none * @note Also reset the value of status register2 to 0 if flash chip has status register2 */ void flash_reset_status(flash_t *obj) { flash_set_status(obj, 0); return; } /** * @brief Get the value of status register1 * @param obj: Flash object define in application software. * @retval : The value of status register1. */ int flash_get_status(flash_t *obj) { /* To avoid gcc warnings */ ( void ) obj; int data; FLASH_Write_Lock(); FLASH_RxCmd(flash_init_para.FLASH_cmd_rd_status, 1, (u8*)&data); FLASH_Write_Unlock(); return data; } /** * @brief Erase flash sector(4KB) * @param obj: Flash object define in application software. * @param address: Specifies the starting address to be erased. LSB 12bits will be masked. * @retval none */ void flash_erase_sector(flash_t *obj, u32 address) { /* To avoid gcc warnings */ ( void ) obj; FLASH_Write_Lock(); FLASH_Erase(EraseSector, address); DCache_Invalidate(SPI_FLASH_BASE + address, 0x1000); FLASH_Write_Unlock(); } /** * @brief Erase flash block(64KB) * @param obj: Flash object define in application software. * @param address: Specifies the starting address to be erased. LSB 16bits will be masked. * @retval none */ void flash_erase_block(flash_t *obj, u32 address) { /* To avoid gcc warnings */ ( void ) obj; FLASH_Write_Lock(); FLASH_Erase(EraseBlock, address); DCache_Invalidate(SPI_FLASH_BASE + address, 0x10000); FLASH_Write_Unlock(); } /** * @brief Erase the whole flash chip * @param obj: Flash object define in application software. * @retval none */ void flash_erase_chip(flash_t *obj) { /* To avoid gcc warnings */ ( void ) obj; FLASH_Write_Lock(); FLASH_Erase(EraseChip, 0); Cache_Flush(); FLASH_Write_Unlock(); } /** * @brief Read a word from specified address * @param obj: Flash object define in application software. * @param address: Specifies the address to read from. * @param data: Specified the address to save the readback data. * @retval 1: Success or Others: Failure. * @note auto mode read is ok, because we have flash cache */ int flash_read_word(flash_t *obj, u32 address, u32 * data) { /* To avoid gcc warnings */ ( void ) obj; // FLASH_RxData(0, address, 4, data); assert_param(data != NULL); u32 offset_to_align = address & 0x03; u32 read_data; u32 temp; u32 i = 4 - offset_to_align; if(offset_to_align){ address -= offset_to_align; temp = HAL_READ32(SPI_FLASH_BASE, address); read_data= temp >> (offset_to_align * 8); address += 4; temp = HAL_READ32(SPI_FLASH_BASE, address); read_data |= (temp << (i * 8)); *data = read_data; }else{ * data = HAL_READ32(SPI_FLASH_BASE, address); } return 1; } /** * @brief Write a word to specified address * @param obj: Flash object define in application software. * @param address: Specifies the address to be programmed to. * @param data: Specified the data to be programmed. * @retval 1: Success or Others: Failure. * @note user mode write used */ int flash_write_word(flash_t *obj, u32 address, u32 data) { /* To avoid gcc warnings */ ( void ) obj; // Disable write protection // flash_unlock(); u32 write_word = data; u32 offset_to_align = address & 0x03; u32 temp; u32 i = 4 - offset_to_align; FLASH_Write_Lock(); if(offset_to_align){ address -= offset_to_align; temp = HAL_READ32(SPI_FLASH_BASE, address); temp = (temp << (i * 8))>>(8*i) | write_word << (8 * offset_to_align); FLASH_TxData12B(address, 4, (u8*)&temp); address += 4; temp = HAL_READ32(SPI_FLASH_BASE, address); temp = (temp >> (offset_to_align * 8)) << (offset_to_align * 8) | write_word >>(8*i); FLASH_TxData12B(address, 4, (u8*)&temp); }else{ FLASH_TxData12B(address, 4, (u8*)&write_word); } DCache_Invalidate(SPI_FLASH_BASE + address, 4); FLASH_Write_Unlock(); // Enable write protection // flash_lock(); return 1; } /** * @brief Read a stream of data from specified address * @param obj: Flash object define in application software. * @param address: Specifies the starting address to read from. * @param len: Specifies the length of the data to read. * @param data: Specified the address to save the readback data. * @retval 1: Success or Others: Failure. * @note auto mode is ok, because we have flash cache */ int flash_stream_read(flash_t *obj, u32 address, u32 len, u8 * data) { /* To avoid gcc warnings */ ( void ) obj; assert_param(data != NULL); u32 offset_to_align; u32 i; u32 read_word; u8 *ptr; u8 *pbuf; offset_to_align = address & 0x03; pbuf = data; if (offset_to_align != 0) { /* the start address is not 4-bytes aligned */ read_word = HAL_READ32(SPI_FLASH_BASE, (address - offset_to_align)); ptr = (u8*)&read_word + offset_to_align; offset_to_align = 4 - offset_to_align; for (i=0;i<offset_to_align;i++) { *pbuf = *(ptr+i); pbuf++; len--; if (len == 0) { break; } } } /* address = next 4-bytes aligned */ address = (((address-1) >> 2) + 1) << 2; ptr = (u8*)&read_word; if ((u32)pbuf & 0x03) { while (len >= 4) { read_word = HAL_READ32(SPI_FLASH_BASE, address); for (i=0;i<4;i++) { *pbuf = *(ptr+i); pbuf++; } address += 4; len -= 4; } } else { while (len >= 4) { *((u32 *)pbuf) = HAL_READ32(SPI_FLASH_BASE, address); pbuf += 4; address += 4; len -= 4; } } if (len > 0) { read_word = HAL_READ32(SPI_FLASH_BASE, address); for (i=0;i<len;i++) { *pbuf = *(ptr+i); pbuf++; } } return 1; } /** * @brief Write a stream of data to specified address * @param obj: Flash object define in application software. * @param address: Specifies the starting address to write to. * @param len: Specifies the length of the data to write. * @param data: Pointer to a byte array that is to be written. * @retval 1: Success or Others: Failure. */ int flash_stream_write(flash_t *obj, u32 address, u32 len, u8 * data) { /* To avoid gcc warnings */ ( void ) obj; // Check address: 4byte aligned & page(256bytes) aligned u32 page_begin = address & (~0xff); u32 page_end = (address + len) & (~0xff); u32 page_cnt = ((page_end - page_begin) >> 8) + 1; u32 addr_begin = address; u32 addr_end = (page_cnt == 1) ? (address + len) : (page_begin + 0x100); u32 size = addr_end - addr_begin; u8 *buffer = data; u8 write_data[12]; u32 offset_to_align; u32 read_word; u32 i; FLASH_Write_Lock(); while(page_cnt){ offset_to_align = addr_begin & 0x3; if(offset_to_align != 0){ read_word = HAL_READ32(SPI_FLASH_BASE, addr_begin - offset_to_align); for(i = offset_to_align;i < 4;i++){ read_word = (read_word & (~(0xff << (8*i)))) |( (*buffer) <<(8*i)); size--; buffer++; if(size == 0) break; } FLASH_TxData12B(addr_begin - offset_to_align, 4, (u8*)&read_word); #ifdef MICRON_N25Q00AA FLASH_ReadFlagStatusReg(); #endif } addr_begin = (((addr_begin-1) >> 2) + 1) << 2; for(;size >= 12 ;size -= 12){ _memcpy(write_data, buffer, 12); FLASH_TxData12B(addr_begin, 12, write_data); #ifdef MICRON_N25Q00AA FLASH_ReadFlagStatusReg(); #endif buffer += 12; addr_begin += 12; } for(;size >= 4; size -=4){ _memcpy(write_data, buffer, 4); FLASH_TxData12B(addr_begin, 4, write_data); #ifdef MICRON_N25Q00AA FLASH_ReadFlagStatusReg(); #endif buffer += 4; addr_begin += 4; } if(size > 0){ read_word = HAL_READ32(SPI_FLASH_BASE, addr_begin); for( i = 0;i < size;i++){ read_word = (read_word & (~(0xff << (8*i)))) | ((*buffer) <<(8*i)); buffer++; } FLASH_TxData12B(addr_begin, 4, (u8*)&read_word); #ifdef MICRON_N25Q00AA FLASH_ReadFlagStatusReg(); #endif } page_cnt--; addr_begin = addr_end; addr_end = (page_cnt == 1) ? (address + len) : (((addr_begin>>8) + 1)<<8); size = addr_end - addr_begin; } DCache_Invalidate(SPI_FLASH_BASE + address, len); FLASH_Write_Unlock(); return 1; } /** * @brief It is the same with flash_stream_write function which is used to write a stream of data to specified address. * @param obj: Flash object define in application software. * @param address: Specifies the starting address to write to. * @param len: Specifies the length of the data to write. * @param data: Pointer to a byte array that is to be written. * @retval 1: Success or Others: Failure. */ int flash_burst_write(flash_t *obj, u32 address ,u32 Length, u8 * data) { flash_stream_write(obj, address, Length, data); return 1; } /** * @brief It is the same with flash_stream_read function which is used to read a stream of data from specified address * @param obj: Flash object define in application software. * @param address: Specifies the starting address to read from. * @param len: Specifies the length of the data to read. * @param data: Specified the address to save the readback data. * @retval 1: Success or Others: Failure. */ int flash_burst_read(flash_t *obj, u32 address, u32 Length, u8 * data) { flash_stream_read(obj, address, Length, data); return 1; } /** * @brief This function is only for Micron 128MB flash to access beyond 16MB by switching between eight 16MB-area(segment). * Please refer to flash datasheet for more information about memory mapping. * @param obj: Flash object define in application software. * @param data: Specified which segment to choose. * @retval 1: Success or Others: Failure. */ int flash_set_extend_addr(flash_t *obj, u32 data) { /* To avoid gcc warnings */ ( void ) obj; /*Write Extended Address Register to select operating segment*/ u8 segnum = (u8)(data & 0x07); FLASH_Write_Lock(); FLASH_SetStatus(0xC5, 1, &segnum); FLASH_Write_Unlock(); return 1; } /** * @brief This function is only for Micron 128MB flash to read from Extended Address Register, which shows the current segment. * Please refer to flash datasheet for more information about memory mapping. * @param obj: Flash object define in application software. * @retval : The value of current Extended Address Register. */ int flash_get_extend_addr(flash_t *obj) { /* To avoid gcc warnings */ ( void ) obj; u8 temp = 0; FLASH_Write_Lock(); FLASH_RxCmd(0xC8, 1, &temp); FLASH_Write_Unlock(); return temp; } /** * @brief This function is to read flash id. * @param obj: Flash object define in application software. * @param buf: Specified the address to save the readback data. * @param len: Specifies the length of the flash id to read. * @retval : The length of the flash id. */ int flash_read_id(flash_t *obj, uint8_t *buf, uint8_t len) { /* To avoid gcc warnings */ ( void ) obj; assert_param(buf != NULL); assert_param(len >= 3); FLASH_Write_Lock(); FLASH_RxCmd(flash_init_para.FLASH_cmd_rd_id, len, buf); FLASH_Write_Unlock(); return len; } /** * @} */ /** * @} */ /** * @} */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/flash_api.c
C
apache-2.0
13,876
/** mbed Microcontroller Library ****************************************************************************** * @file gpio_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for GPIO. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "objects.h" #include "pinmap.h" #include "gpio_api.h" /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_GPIO * @brief MBED_GPIO driver modules. * @{ */ /** @defgroup MBED_GPIO_Exported_Functions MBED_GPIO Exported Functions * @{ */ /** * @brief Set the given pin as GPIO. * @param pin: PinName according to pinmux spec. * @retval : The given pin with GPIO function */ uint32_t gpio_set(PinName pin) { u32 ip_pin; assert_param(pin != (PinName)NC); pin_function(pin, 0); ip_pin = pin; return ip_pin; } /** * @brief Initializes the GPIO device, include mode/direction/pull control registers. * @param obj: gpio object define in application software. * @param pin: PinName according to pinmux spec. * @retval none */ void gpio_init(gpio_t *obj, PinName pin) { GPIO_InitTypeDef GPIO_InitStruct; if (pin == (PinName)NC) return; obj->pin = pin; GPIO_InitStruct.GPIO_Pin = obj->pin; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(&GPIO_InitStruct); } /** * @brief Set GPIO mode. * @param obj: gpio object define in application software. * @param mode: this parameter can be one of the following values: * @arg PullNone: HighZ, user can input high or low use this pin * @arg PullDown: pull down * @arg PullUp: pull up * @retval none */ void gpio_mode(gpio_t *obj, PinMode mode) { u32 GPIO_PuPd; switch (mode) { case PullNone:/* No driver -> Input & High Impendance */ GPIO_PuPd = GPIO_PuPd_NOPULL; //GPIO_Direction(obj->pin, GPIO_Mode_IN); break; case PullDown: GPIO_PuPd = GPIO_PuPd_DOWN; break; case PullUp: GPIO_PuPd = GPIO_PuPd_UP; break; default: GPIO_PuPd = GPIO_PuPd_NOPULL; break; } PAD_PullCtrl(obj->pin, GPIO_PuPd); } /** * @brief Set GPIO direction. * @param obj: gpio object define in application software. * @param direction: this parameter can be one of the following values: * @arg PIN_INPUT: this pin is input * @arg PIN_OUTPUT: this pin is output * @retval none */ void gpio_dir(gpio_t *obj, PinDirection direction) { assert_param(obj->pin != (PinName)NC); if (direction == PIN_OUTPUT) { GPIO_Direction(obj->pin, GPIO_Mode_OUT); } else { GPIO_Direction(obj->pin, GPIO_Mode_IN); } } /** * @brief Set GPIO direction. * @param obj: gpio object define in application software. * @param direction: this parameter can be one of the following values: * @arg PIN_INPUT: this pin is input * @arg PIN_OUTPUT: this pin is output * @retval none */ void gpio_change_dir(gpio_t *obj, PinDirection direction) { gpio_dir(obj, direction); } /** * @brief Sets value to the selected output port pin. * @param obj: gpio object define in application software. * @param value: specifies the value to be written to the selected pin * This parameter can be one of the following values: * @arg 0: Pin state set to low * @arg 1: Pin state set to high * @retval none */ void gpio_write(gpio_t *obj, int value) { assert_param(obj->pin != (PinName)NC); GPIO_WriteBit(obj->pin, value); } /** * @brief Sets value to the selected output port pin. * @param obj: gpio object define in application software. * @param value: specifies the value to be written to the selected pin * This parameter can be one of the following values: * @arg 0: Pin state set to low * @arg 1: Pin state set to high * @retval none */ void gpio_direct_write(gpio_t *obj, BOOL value) { gpio_write(obj, value); } /** * @brief Reads the specified gpio port pin. * @param obj: gpio object define in application software. * @retval state of the specified gpio port pin * - 1: pin state is high * - 0: pin state is low */ int gpio_read(gpio_t *obj) { assert_param(obj->pin != (PinName)NC); return GPIO_ReadDataBit(obj->pin); } /** * @brief Sets pull type to the selected pin. * @param obj: gpio object define in application software. * @param pull_type: this parameter can be one of the following values: * @arg PullNone: HighZ, user can input high or low use this pin * @arg PullDown: pull down * @arg PullUp: pull up * @retval none */ void gpio_pull_ctrl(gpio_t *obj, PinMode pull_type) { u32 GPIO_PuPd; switch (pull_type) { case PullNone:/* No driver -> Input & High Impendance */ GPIO_PuPd = GPIO_PuPd_NOPULL; break; case PullDown: GPIO_PuPd = GPIO_PuPd_DOWN; break; case PullUp: GPIO_PuPd = GPIO_PuPd_UP; break; default: GPIO_PuPd = GPIO_PuPd_NOPULL; break; } PAD_PullCtrl(obj->pin, GPIO_PuPd); } /** * @brief Deinitializes the GPIO device, include mode/direction/pull control registers. * @param obj: gpio object define in application software. * @retval none */ void gpio_deinit(gpio_t *obj) { GPIO_DeInit(obj->pin); } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/gpio_api.c
C
apache-2.0
5,721
/** mbed Microcontroller Library ****************************************************************************** * @file gpio_irq_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for GPIO IRQ. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "objects.h" #include "pinmap.h" #include "gpio_irq_api.h" #include "gpio_irq_ex_api.h" /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_GPIOIRQ * @brief MBED_GPIOIRQ driver modules. * @{ */ /** @defgroup MBED_GPIOIRQ_Exported_Functions MBED_GPIOIRQ Exported Functions * @{ */ /** * @brief Initializes the GPIO device interrupt mode, include mode/trigger/polarity registers. * @param obj: gpio irq object define in application software. * @param pin: PinName according to pinmux spec. * @param handler: Interrupt handler to be assigned to the specified pin. * @param id: handler parameter. * @retval none */ int gpio_irq_init(gpio_irq_t *obj, PinName pin, gpio_irq_handler handler, uint32_t id) { GPIO_InitTypeDef GPIO_InitStruct; u8 port_num; if (pin == NC) return -1; obj->pin = pin; port_num = PORT_NUM(pin); GPIO_INTConfig(pin, DISABLE); GPIO_InitStruct.GPIO_Pin = obj->pin; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_INT; GPIO_InitStruct.GPIO_ITTrigger = GPIO_INT_Trigger_EDGE; GPIO_InitStruct.GPIO_ITPolarity = GPIO_INT_POLARITY_ACTIVE_LOW; GPIO_Init(&GPIO_InitStruct); if (port_num == GPIO_PORT_A) { InterruptRegister(GPIO_INTHandler, GPIOA_IRQ, (u32)GPIOA_BASE, 5); InterruptEn(GPIOA_IRQ, 5); } else if (port_num == GPIO_PORT_B) { InterruptRegister(GPIO_INTHandler, GPIOB_IRQ, (u32)GPIOB_BASE, 5); InterruptEn(GPIOB_IRQ, 5); } GPIO_UserRegIrq(GPIO_InitStruct.GPIO_Pin, (VOID*) handler, (VOID*) id); return 0; } /** * @brief Deinitializes the GPIO device interrupt mode, include mode/trigger/polarity registers. * @param obj: gpio irq object define in application software. * @retval none */ void gpio_irq_free(gpio_irq_t *obj) { GPIO_DeInit(obj->pin); } /** * @brief Enable/Disable gpio interrupt. * @param obj: gpio irq object define in application software. * @param event: gpio interrupt event, this parameter can be one of the following values: * @arg IRQ_RISE: rising edge interrupt event * @arg IRQ_FALL: falling edge interrupt event * @arg IRQ_LOW: low level interrupt event * @arg IRQ_HIGH: high level interrupt event * @arg IRQ_NONE: no interrupt event * @param enable: this parameter can be one of the following values: * @arg 0 disable gpio interrupt * @arg 1 enable gpio interrupt * @retval none */ void gpio_irq_set(gpio_irq_t *obj, gpio_irq_event event, uint32_t enable) { u32 GPIO_ITTrigger; u32 GPIO_ITPolarity; switch((uint8_t)event) { case IRQ_RISE: GPIO_ITTrigger = GPIO_INT_Trigger_EDGE; GPIO_ITPolarity = GPIO_INT_POLARITY_ACTIVE_HIGH; break; case IRQ_FALL: GPIO_ITTrigger = GPIO_INT_Trigger_EDGE; GPIO_ITPolarity = GPIO_INT_POLARITY_ACTIVE_LOW; break; case IRQ_LOW: GPIO_ITTrigger = GPIO_INT_Trigger_LEVEL; GPIO_ITPolarity = GPIO_INT_POLARITY_ACTIVE_LOW; break; case IRQ_HIGH: GPIO_ITTrigger = GPIO_INT_Trigger_LEVEL; GPIO_ITPolarity = GPIO_INT_POLARITY_ACTIVE_HIGH; break; case IRQ_NONE: // ? break; default: break; } if (enable) { GPIO_INTMode(obj->pin, ENABLE, GPIO_ITTrigger, GPIO_ITPolarity, GPIO_INT_DEBOUNCE_ENABLE); } else { GPIO_INTMode(obj->pin, DISABLE, 0, 0, 0); } } /** * @brief Enable gpio interrupt. * @param obj: gpio irq object define in application software. * @retval none */ void gpio_irq_enable(gpio_irq_t *obj) { GPIO_INTConfig(obj->pin, ENABLE); } /** * @brief Disable gpio interrupt. * @param obj: gpio irq object define in application software. * @retval none */ void gpio_irq_disable(gpio_irq_t *obj) { GPIO_INTConfig(obj->pin, DISABLE); } /** * @brief Deinitializes the GPIO device interrupt mode, include mode/trigger/polarity registers. * @param obj: gpio irq object define in application software. * @retval none */ void gpio_irq_deinit(gpio_irq_t *obj) { GPIO_DeInit(obj->pin); } /** * @brief Sets pull type to the selected interrupt pin. * @param obj: gpio irq object define in application software. * @param pull_type: this parameter can be one of the following values: * @arg PullNone: HighZ, user can input high or low use this pin * @arg PullDown: pull down * @arg PullUp: pull up * @retval none */ void gpio_irq_pull_ctrl(gpio_irq_t *obj, PinMode pull_type) { u32 GPIO_PuPd; switch (pull_type) { case PullNone:/* No driver -> Input & High Impendance */ GPIO_PuPd = GPIO_PuPd_NOPULL; break; case PullDown: GPIO_PuPd = GPIO_PuPd_DOWN; break; case PullUp: GPIO_PuPd = GPIO_PuPd_UP; break; default: GPIO_PuPd = GPIO_PuPd_NOPULL; break; } PAD_PullCtrl(obj->pin, GPIO_PuPd); } /** * @brief Enable the specified gpio interrupt event. * @param obj: gpio irq object define in application software. * @param event: gpio interrupt event, this parameter can be one of the following values: * @arg IRQ_RISE: rising edge interrupt event * @arg IRQ_FALL: falling edge interrupt event * @arg IRQ_LOW: low level interrupt event * @arg IRQ_HIGH: high level interrupt event * @arg IRQ_NONE: no interrupt event * @retval none */ void gpio_irq_set_event(gpio_irq_t *obj, gpio_irq_event event) { gpio_irq_set(obj, event, ENABLE); } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/gpio_irq_api.c
C
apache-2.0
6,052
/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBED_GPIO_OBJECT_H #define MBED_GPIO_OBJECT_H #include "mbed_assert.h" #include "basic_types.h" #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/gpio_object.h
C
apache-2.0
817
/** mbed Microcontroller Library ****************************************************************************** * @file i2c_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for I2C. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "objects.h" #include "PinNames.h" #include "i2c_api.h" #include "pinmap.h" // See I2CSlave.h #define NoData 0 // the slave has not been addressed #define ReadAddressed 1 // the master has requested a read from this slave (slave = transmitter) #define WriteGeneral 2 // the master is writing to all slave #define WriteAddressed 3 // the master is writing to this slave (slave = receiver) static uint16_t i2c_target_addr[2]; extern u32 ConfigDebugErr; extern u32 ConfigDebuginfo; I2C_InitTypeDef I2CInitDat[2]; static u32 restart_enable = 0; static u32 master_addr_retry = 1; /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_I2C * @brief MBED_I2C driver modules. * @{ */ /** @defgroup MBED_I2C_Exported_Functions MBED_I2C Exported Functions * @{ */ void i2c_send_restart(I2C_TypeDef *I2Cx, u8* pBuf, u8 len, u8 restart); /** * @brief Read data with special length in master mode through the I2Cx peripheral under in-house IP. * @param I2Cx: where I2Cx can be I2C0_DEV. * @param pBuf: point to the buffer to hold the received data. * @param len: the length of data that to be received. * @note deal with condition that master send address while slave no ack * @retval the length of data read. */ u8 I2C_MasterRead_Patch(I2C_TypeDef *I2Cx, u8* pBuf, u8 len) { u8 cnt = 0; /* Check the parameters */ assert_param(IS_I2C_ALL_PERIPH(I2Cx)); /* read in the DR register the data to be received */ for(cnt = 0; cnt < len; cnt++) { if(cnt >= len - 1) { /* generate stop singal */ I2Cx->IC_DATA_CMD = 0x0003 << 8; } else { I2Cx->IC_DATA_CMD = 0x0001 << 8; } /* wait for I2C_FLAG_RFNE flag */ while((I2C_CheckFlagState(I2Cx, BIT_IC_STATUS_RFNE)) == 0) { if(I2C_GetRawINT(I2Cx) & BIT_IC_RAW_INTR_STAT_TX_ABRT) { DBG_8195A(" TX_ABRT\n"); I2C_ClearAllINT(I2Cx); return cnt; } } *pBuf++ = (u8)I2Cx->IC_DATA_CMD; } return cnt; } /** * @brief Write data with special length in master mode through the I2Cx peripheral under in-house IP. * @param I2Cx: where I2Cx can be I2C0_DEV. * @param pBuf: point to the data to be transmitted. * @param len: the length of data that send. * @note deal with condition that master send address while slave no ack * @retval the length of data send. */ u8 I2C_MasterWrite_Patch(I2C_TypeDef *I2Cx, u8* pBuf, u8 len) { u8 cnt = 0; /* Check the parameters */ assert_param(IS_I2C_ALL_PERIPH(I2Cx)); /* Write in the DR register the data to be sent */ for(cnt = 0; cnt < len; cnt++) { while((I2C_CheckFlagState(I2Cx, BIT_IC_STATUS_TFNF)) == 0); if(cnt >= len - 1) { /*generate stop signal*/ I2Cx->IC_DATA_CMD = (*pBuf++) | (1 << 9); } else { I2Cx->IC_DATA_CMD = (*pBuf++); } while((I2C_CheckFlagState(I2Cx, BIT_IC_STATUS_TFE)) == 0) { if(I2C_GetRawINT(I2Cx) & BIT_IC_RAW_INTR_STAT_TX_ABRT) { DBG_8195A(" TX_ABRT= %x\n",I2Cx->IC_TX_ABRT_SOURCE); I2C_ClearAllINT(I2Cx); return cnt; } } } return cnt; } /** * @brief Read data with special length in master mode through the I2Cx peripheral under in-house IP. * @param I2Cx: where I2Cx can be I2C0_DEV . * @param pBuf: point to the buffer to hold the received data. * @param len: the length of data that to be received. * @param timeout_ms: specifies timeout time, unit is ms. * @retval the length of data read. */ int I2C_MasterRead_TimeOut(I2C_TypeDef *I2Cx, u8* pBuf, u8 len, u32 timeout_ms) { int cnt = 0; u32 InTimeoutCount = 0; /* Check the parameters */ assert_param(IS_I2C_ALL_PERIPH(I2Cx)); /* read in the DR register the data to be received */ for(cnt = 0; cnt < len; cnt++) { InTimeoutCount = timeout_ms*500; if(cnt >= len - 1) { /* generate stop singal */ I2Cx->IC_DATA_CMD = 0x0003 << 8; } else { I2Cx->IC_DATA_CMD = 0x0001 << 8; } /* wait for I2C_FLAG_RFNE flag */ while((I2C_CheckFlagState(I2Cx, BIT_IC_STATUS_RFNE)) == 0) { if(I2C_GetRawINT(I2Cx) & BIT_IC_RAW_INTR_STAT_TX_ABRT) { DBG_8195A(" TX_ABRT\n"); I2C_ClearAllINT(I2Cx); return cnt; } DelayUs(2); if (InTimeoutCount == 0) { DBG_8195A("MasterRead_TimeOut\n"); return cnt; } InTimeoutCount--; } *pBuf++ = (u8)I2Cx->IC_DATA_CMD; } return cnt; } /** * @brief Write data with special length in master mode through the I2Cx peripheral under in-house IP. * @param I2Cx: where I2Cx can be I2C0_DEV. * @param pBuf: point to the data to be transmitted. * @param len: the length of data that to be received. * @param timeout_ms: specifies timeout time, unit is ms. * @retval the length of data send. */ int I2C_MasterWrite_TimeOut(I2C_TypeDef *I2Cx, u8* pBuf, u8 len, u32 timeout_ms) { int cnt = 0; u32 InTimeoutCount = 0; /* Check the parameters */ assert_param(IS_I2C_ALL_PERIPH(I2Cx)); /* Write in the DR register the data to be sent */ for(cnt = 0; cnt < len; cnt++) { InTimeoutCount = timeout_ms*500; while((I2C_CheckFlagState(I2Cx, BIT_IC_STATUS_TFNF)) == 0); if(cnt >= len - 1) { /*generate stop signal*/ I2Cx->IC_DATA_CMD = (*pBuf++) | (1 << 9); } else { I2Cx->IC_DATA_CMD = (*pBuf++); } while((I2C_CheckFlagState(I2Cx, BIT_IC_STATUS_TFE)) == 0) { if(I2C_GetRawINT(I2Cx) & BIT_IC_RAW_INTR_STAT_TX_ABRT) { DBG_8195A(" TX_ABRT\n"); I2C_ClearAllINT(I2Cx); return cnt; } DelayUs(2); if (InTimeoutCount == 0) { DBG_8195A("MasterWrite_TimeOut\n"); return cnt; } InTimeoutCount--; } } return cnt; } /** * @brief Master sends single byte through the I2Cx peripheral to detect slave device. * @param obj: i2c object defined in application software. * @param address: the address of slave that to be detected. * @param timeout_ms: specifies timeout time, unit is ms. * @retval Slave ack condition: * - 0: Slave available * - -1: Slave not available */ int I2C_MasterSendNullData_TimeOut(I2C_TypeDef *I2Cx, int address, u32 timeout_ms) { u8 I2CTemp = (u8)(address<<1); I2C_MasterSendNullData(I2Cx, &I2CTemp, 0, 1, 0); DelayMs(timeout_ms); if(I2C_GetRawINT(I2Cx) & BIT_IC_RAW_INTR_STAT_TX_ABRT) { I2C_ClearAllINT(I2Cx); /* Wait for i2c enter trap state from trap_stop state*/ DelayUs(100); I2C_Cmd(I2Cx, DISABLE); I2C_Cmd(I2Cx, ENABLE); return -1; } return 0; } /** * @brief Get i2c index according to the SDA PinName. * @param sda: SDA PinName according to pinmux spec. * @retval i2c index: * - 0: I2C0 Device */ static uint32_t i2c_index_get(PinName sda) { if ((sda == _PA_26) || (sda == _PB_6)) { return 0; } else { assert_param(0); } return 2; } /** * @brief Initializes the I2C device, include clock/function/I2C registers. * @param obj: i2c object defined in application software. * @param sda: SDA PinName according to pinmux spec. * @param scl: SCL PinName according to pinmux spec. * @retval none */ void i2c_init(i2c_t *obj, PinName sda, PinName scl) { uint32_t i2c_idx = i2c_index_get(sda); //ConfigDebugErr &= (~(_DBG_I2C_|_DBG_GDMA_)); //ConfigDebugInfo&= (~(_DBG_I2C_|_DBG_GDMA_)); DBG_8195A("i2c_idx:%x\n",i2c_idx); obj->i2c_idx = i2c_idx; obj->I2Cx = I2C_DEV_TABLE[i2c_idx].I2Cx; /* Set I2C Device Number */ I2CInitDat[obj->i2c_idx].I2CIdx = i2c_idx; /* Load I2C default value */ I2C_StructInit(&I2CInitDat[obj->i2c_idx]); /* Assign I2C Pin Mux */ I2CInitDat[obj->i2c_idx].I2CMaster = I2C_MASTER_MODE; I2CInitDat[obj->i2c_idx].I2CSpdMod = I2C_SS_MODE; I2CInitDat[obj->i2c_idx].I2CClk = 100; I2CInitDat[obj->i2c_idx].I2CAckAddr = 0; /* Init I2C now */ //if(I2CInitDat[obj->i2c_idx].I2CIdx == 0) { //RCC_PeriphClockCmd(APBPeriph_I2C0, APBPeriph_I2C0_CLOCK, DISABLE); //RCC_PeriphClockCmd(APBPeriph_I2C0, APBPeriph_I2C0_CLOCK, ENABLE); //} else { //RCC_PeriphClockCmd(APBPeriph_I2C1, APBPeriph_I2C1_CLOCK, DISABLE); //RCC_PeriphClockCmd(APBPeriph_I2C1, APBPeriph_I2C1_CLOCK, ENABLE); //} /* I2C Pin Mux Initialization */ Pinmux_Config(sda, PINMUX_FUNCTION_I2C); Pinmux_Config(scl, PINMUX_FUNCTION_I2C); PAD_PullCtrl(sda, GPIO_PuPd_UP); PAD_PullCtrl(scl, GPIO_PuPd_UP); /* I2C HAL Initialization */ I2C_Init(obj->I2Cx, &I2CInitDat[obj->i2c_idx]); /* I2C Enable Module */ I2C_Cmd(obj->I2Cx, ENABLE); } /** * @brief Set i2c frequency. * @param obj: i2c object defined in application software. * @param hz: i2c clock(unit is Hz). * @retval none */ void i2c_frequency(i2c_t *obj, int hz) { uint16_t i2c_default_clk = (uint16_t) I2CInitDat[obj->i2c_idx].I2CClk; uint16_t i2c_user_clk = (uint16_t) (hz/1000); if (i2c_default_clk != i2c_user_clk) { /* Deinit I2C first */ i2c_reset(obj); if (i2c_user_clk <= 100) { I2CInitDat[obj->i2c_idx].I2CSpdMod = I2C_SS_MODE; } else if ((i2c_user_clk > 100) && (i2c_user_clk <= 400)) { I2CInitDat[obj->i2c_idx].I2CSpdMod = I2C_FS_MODE; } else if (i2c_user_clk > 400) { I2CInitDat[obj->i2c_idx].I2CSpdMod = I2C_HS_MODE; } else { I2CInitDat[obj->i2c_idx].I2CSpdMod = I2C_SS_MODE; } /* Load the user defined I2C clock */ I2CInitDat[obj->i2c_idx].I2CClk = i2c_user_clk; /* Init I2C now */ I2C_Init(obj->I2Cx, &I2CInitDat[obj->i2c_idx]); I2C_Cmd(obj->I2Cx, ENABLE); } } /** * @brief Start i2c device. * @param obj: i2c object defined in application software. * @retval 0 */ inline int i2c_start(i2c_t *obj) { /* To avoid gcc warnings */ ( void ) obj; return 0; } /** * @brief Stop i2c device. * @param obj: i2c object defined in application software. * @retval 0 */ inline int i2c_stop(i2c_t *obj) { /* To avoid gcc warnings */ ( void ) obj; return 0; } /** * @brief I2C master read in poll mode. * @param obj: i2c object defined in application software. * @param address: slave address which will be transmitted. * @param data: point to the buffer to hold the received data. * @param length: the length of data that to be received. * @param stop: specifies whether a STOP is issued after all the bytes are received. * @param timeout_ms: specifies timeout time, unit is ms. * @retval the length of data received. If the retval less than the data length that want to be received, this transfer is not success. */ int i2c_read_timeout(i2c_t *obj, int address, char *data, int length, int stop, int timeout_ms) { /* To avoid gcc warnings */ ( void ) stop; if (i2c_target_addr[obj->i2c_idx] != address) { /* Deinit I2C first */ i2c_reset(obj); /* Load the user defined I2C target slave address */ i2c_target_addr[obj->i2c_idx] = address; I2CInitDat[obj->i2c_idx].I2CAckAddr = address; /* Init I2C now */ I2C_Init(obj->I2Cx, &I2CInitDat[obj->i2c_idx]); I2C_Cmd(obj->I2Cx, ENABLE); } return (I2C_MasterRead_TimeOut(obj->I2Cx, (unsigned char*)data, length,timeout_ms)); } /** * @brief I2C master wite in poll mode. * @param obj: i2c object defined in application software. * @param address: slave address which will be transmitted. * @param data: point to the buffer to hold the received data. * @param length: the length of data that to be received. * @param stop: specifies whether a STOP is issued after all the bytes are written. * @param timeout_ms: specifies timeout time, unit is ms. * @note If the length equal to zero, will call I2C_MasterSendNullData_TimeOut() * @retval the length of data written. If the retval less than the data length that want to be sent, this transfer is not success. */ int i2c_write_timeout(i2c_t *obj, int address, char *data, int length, int stop, int timeout_ms) { /* To avoid gcc warnings */ ( void ) stop; if (i2c_target_addr[obj->i2c_idx] != address) { /* Deinit I2C first */ i2c_reset(obj); /* Load the user defined I2C target slave address */ i2c_target_addr[obj->i2c_idx] = address; I2CInitDat[obj->i2c_idx].I2CAckAddr = address; /* Init I2C now */ I2C_Init(obj->I2Cx, &I2CInitDat[obj->i2c_idx]); I2C_Cmd(obj->I2Cx, ENABLE); } if(!length) { return (I2C_MasterSendNullData_TimeOut(obj->I2Cx, address, timeout_ms)); } return (I2C_MasterWrite_TimeOut(obj->I2Cx, (unsigned char*)data, length,timeout_ms)); } /** * @brief I2C master read in poll mode. * @param obj: i2c object defined in application software. * @param address: slave address which will be transmitted. * @param data: point to the buffer to hold the received data. * @param length: the length of data that to be received. * @param stop: specifies whether a STOP is issued after all the bytes are received. * @retval the length of data received. */ int i2c_read(i2c_t *obj, int address, char *data, int length, int stop) { /* To avoid gcc warnings */ ( void ) stop; if (i2c_target_addr[obj->i2c_idx] != address) { /* Deinit I2C first */ i2c_reset(obj); /* Load the user defined I2C target slave address */ i2c_target_addr[obj->i2c_idx] = address; I2CInitDat[obj->i2c_idx].I2CAckAddr = address; /* Init I2C now */ I2C_Init(obj->I2Cx, &I2CInitDat[obj->i2c_idx]); I2C_Cmd(obj->I2Cx, ENABLE); } if (!master_addr_retry) { I2C_MasterRead(obj->I2Cx, (unsigned char*)data, length); } else { while (0 == I2C_MasterRead_Patch(obj->I2Cx, (unsigned char*)data, length)) { /* Wait for i2c enter trap state from trap_stop state*/ DelayUs(100); /* Deinit I2C first */ i2c_reset(obj); /* Load the user defined I2C target slave address */ i2c_target_addr[obj->i2c_idx] = address; I2CInitDat[obj->i2c_idx].I2CAckAddr = address; /* Init I2C now */ I2C_Init(obj->I2Cx, &I2CInitDat[obj->i2c_idx]); I2C_Cmd(obj->I2Cx, ENABLE); } } return length; } /** * @brief I2C master write in poll mode. * @param obj: i2c object defined in application software. * @param address: slave address which will be transmitted. * @param data: point to the data to be sent. * @param length: the length of data that to be sent. * @param stop: specifies whether a STOP is issued after all the bytes are sent. * @retval the length of data send. */ int i2c_write(i2c_t *obj, int address, const char *data, int length, int stop) { if (i2c_target_addr[obj->i2c_idx] != address) { /* Deinit I2C first */ i2c_reset(obj); /* Load the user defined I2C target slave address */ i2c_target_addr[obj->i2c_idx] = address; I2CInitDat[obj->i2c_idx].I2CAckAddr = address; /* Init I2C now */ I2C_Init(obj->I2Cx, &I2CInitDat[obj->i2c_idx]); I2C_Cmd(obj->I2Cx, ENABLE); } if ((!restart_enable) |(1==stop)) { return (I2C_MasterWrite_Patch(obj->I2Cx, (unsigned char*)data, length)); } else { i2c_send_restart(obj->I2Cx, (unsigned char*)data, length, 1); } return length; } /** * @brief I2C master send data and read data in poll mode. * @param obj: i2c object defined in application software. * @param address: slave address which will be transmitted. * @param pWriteBuf: point to the data to be sent. * @param Writelen: the length of data that to be sent. * @param pReadBuf: point to the buffer to hold the received data. * @param Readlen: the length of data that to be received. * @retval the length of data received. */ int i2c_repeatread(i2c_t *obj, int address, uint8_t *pWriteBuf, int Writelen, uint8_t *pReadBuf, int Readlen) { u8 cnt = 0; if (i2c_target_addr[obj->i2c_idx] != address) { /* Deinit I2C first */ i2c_reset(obj); /* Load the user defined I2C target slave address */ i2c_target_addr[obj->i2c_idx] = address; I2CInitDat[obj->i2c_idx].I2CAckAddr = address; /* Init I2C now */ I2C_Init(obj->I2Cx, &I2CInitDat[obj->i2c_idx]); I2C_Cmd(obj->I2Cx, ENABLE); } /* write in the DR register the data to be sent */ for(cnt = 0; cnt < Writelen; cnt++) { while((I2C_CheckFlagState(obj->I2Cx, BIT_IC_STATUS_TFNF)) == 0); if(cnt >= Writelen - 1) { /*generate stop signal*/ obj->I2Cx->IC_DATA_CMD = (*pWriteBuf++) | (1 << 10); } else { obj->I2Cx->IC_DATA_CMD = (*pWriteBuf++); } } /*Wait I2C TX FIFO not full*/ while((I2C_CheckFlagState(obj->I2Cx, BIT_IC_STATUS_TFNF)) == 0); I2C_MasterRead(obj->I2Cx, pReadBuf, Readlen); return Readlen; } /** * @brief I2C master restart after all bytes are sent. * @param I2Cx: where I2Cx can be I2C0_DEV to select the I2C peripheral. * @param pBuf: point to the data to be sent. * @param len: the length of data that to be sent. * @param restart: specifies whether a RESTART is issued after all the bytes are sent. * @retval none */ void i2c_send_restart(I2C_TypeDef *I2Cx, u8* pBuf, u8 len, u8 restart) { u8 cnt = 0; /* Check the parameters */ assert_param(IS_I2C_ALL_PERIPH(I2Cx)); /* Write in the DR register the data to be sent */ for(cnt = 0; cnt < len; cnt++) { while((I2C_CheckFlagState(I2Cx, BIT_IC_STATUS_TFNF)) == 0); if(cnt >= len - 1) { /*generate restart signal*/ I2Cx->IC_DATA_CMD = (*pBuf++) | (restart << 10); } else { I2Cx->IC_DATA_CMD = (*pBuf++); } } while((I2C_CheckFlagState(I2Cx, BIT_IC_STATUS_TFE)) == 0); } /** * @brief I2C master receive single byte. * @param obj: i2c object defined in application software. * @param last: hold the received data. * @retval the data that received. */ int i2c_byte_read(i2c_t *obj, int last) { /* To avoid gcc warnings */ ( void ) last; uint8_t i2cdatlocal; I2C_MasterRead(obj->I2Cx, &i2cdatlocal, 1); return (int)i2cdatlocal; } /** * @brief I2C master send single byte. * @param obj: i2c object defined in application software. * @param data: the data to be sent. * @retval result. */ int i2c_byte_write(i2c_t *obj, int data) { uint8_t i2cdatlocal = data; I2C_MasterWrite(obj->I2Cx, &i2cdatlocal, 1); return 1; } /** * @brief Deinitializes the I2C device * @param obj: i2c object defined in application software. * @retval none */ void i2c_reset(i2c_t *obj) { /* Deinit I2C directly */ /* I2C HAL DeInitialization */ I2C_Cmd(obj->I2Cx, DISABLE); } /** * @brief Enable i2c master RESTART function * @param obj: i2c object defined in application software. * @retval none */ void i2c_restart_enable(i2c_t *obj) { uint32_t i2cen; if (obj->I2Cx->IC_ENABLE & BIT_CTRL_IC_ENABLE) { I2C_Cmd(obj->I2Cx, DISABLE); i2cen = 1; } obj->I2Cx->IC_CON |= BIT_CTRL_IC_CON_IC_RESTART_EN; if (i2cen) { I2C_Cmd(obj->I2Cx, ENABLE); } restart_enable = 1; } /** * @brief Disable i2c Master RESTART function * @param obj: i2c object defined in application software. * @retval none */ void i2c_restart_disable(i2c_t *obj) { uint32_t i2cen; if (obj->I2Cx->IC_ENABLE & BIT_CTRL_IC_ENABLE) { I2C_Cmd(obj->I2Cx, DISABLE); i2cen = 1; } obj->I2Cx->IC_CON &= ~BIT_CTRL_IC_CON_IC_RESTART_EN; if (i2cen) { I2C_Cmd(obj->I2Cx, ENABLE); } restart_enable = 0; } /** * @brief Enable/Disable i2c Device * @param obj: i2c object defined in application software. * @param enable: this parameter can be one of the following values: * @arg 0 disable * @arg 1 enable * @retval result */ int i2c_enable_control(i2c_t *obj, int enable) { if (enable) { I2C_Cmd(obj->I2Cx, ENABLE); } else { I2C_Cmd(obj->I2Cx, DISABLE); } return 0; } //#if DEVICE_I2CSLAVE /** * @brief Set i2c slave address. * @param obj: i2c object defined in application software. * @param idx: i2c index, this parameter can be : * @arg 0: I2C0 Device * @param address: slave address. * @param mask: the mask of address * @retval none */ void i2c_slave_address(i2c_t *obj, int idx, uint32_t address, uint32_t mask) { /* To avoid gcc warnings */ ( void ) idx; ( void ) mask; uint16_t i2c_default_addr = (uint16_t) I2CInitDat[obj->i2c_idx].I2CAckAddr; uint16_t i2c_user_addr = (uint16_t) address; if (i2c_default_addr != i2c_user_addr) { /* Deinit I2C first */ i2c_reset(obj); /* Load the user defined I2C clock */ I2CInitDat[obj->i2c_idx].I2CAckAddr = i2c_user_addr; /* Init I2C now */ I2C_Init(obj->I2Cx, &I2CInitDat[obj->i2c_idx]); I2C_Cmd(obj->I2Cx, ENABLE); } } /** * @brief Set i2c device to be slave. * @param obj: i2c object defined in application software. * @param enable_slave: enable slave function, this parameter can be one of the following values: * @arg 0 disable * @arg 1 enable * @retval none */ void i2c_slave_mode(i2c_t *obj, int enable_slave) { /* Deinit I2C first */ i2c_reset(obj); /* Load the user defined I2C clock */ I2CInitDat[obj->i2c_idx].I2CMaster = I2C_MASTER_MODE; if (enable_slave) I2CInitDat[obj->i2c_idx].I2CMaster = I2C_SLAVE_MODE; /* Init I2C now */ I2C_Init(obj->I2Cx, &I2CInitDat[obj->i2c_idx]); I2C_Cmd(obj->I2Cx, ENABLE); } /** * @brief Get i2c slave state. * @param obj: i2c object defined in application software. * @retval the state of i2c slave. */ int i2c_slave_receive(i2c_t *obj) { u32 I2CLocalTemp = I2C_GetRawINT(obj->I2Cx); if (I2CLocalTemp & BIT_IC_RAW_INTR_STAT_GEN_CALL) { return WriteGeneral; } else if (I2CLocalTemp & BIT_IC_RAW_INTR_STAT_RD_REQ) { return ReadAddressed; } if (I2C_CheckFlagState(obj->I2Cx, BIT_IC_STATUS_RFNE)) { return WriteAddressed; } return 0; } /** * @brief I2C slave read in poll mode. * @param obj: i2c object defined in application software. * @param data: point to the buffer to hold the received data. * @param length: the length of data that to be received. * @retval the length of data received. */ int i2c_slave_read(i2c_t *obj, char *data, int length) { I2C_SlaveRead(obj->I2Cx, (unsigned char*)data, length); return length; } /** * @brief I2C slave write in poll mode. * @param obj: i2c object defined in application software. * @param data: point to the data to be sent. * @param length: the length of data that to be sent. * @retval result. */ int i2c_slave_write(i2c_t *obj, const char *data, int length) { I2C_SlaveWrite(obj->I2Cx, (unsigned char*)data, length); return 1; } /** * @brief Set/clear i2c slave RD_REQ interrupt mask. * @param obj: i2c object defined in application software. * @param set: set or clear for read request. * @retval result. */ int i2c_slave_set_for_rd_req(i2c_t *obj, int set) { if (set) { I2C_INTConfig(obj->I2Cx, BIT_IC_INTR_MASK_M_RD_REQ, ENABLE); } else { I2C_INTConfig(obj->I2Cx, BIT_IC_INTR_MASK_M_RD_REQ, DISABLE); } return _TRUE; } /** * @brief Set/clear i2c slave NAK or ACK data part in transfer. * @param obj: i2c object defined in application software. * @param set_nak: set or clear for data NAK. * @retval result. */ int i2c_slave_set_for_data_nak(i2c_t *obj, int set_nak) { I2C_TypeDef * I2Cx = obj->I2Cx; u32 temp; while (1) { temp = I2Cx->IC_STATUS; if ((BIT_IC_STATUS_SLV_ACTIVITY & temp) == 0) { break; } } I2Cx->IC_SLV_DATA_NACK_ONLY = set_nak; return 0; } /** * @} */ /** * @} */ /** * @} */ //#endif // CONFIG_I2C_SLAVE_EN /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/i2c_api.c
C
apache-2.0
23,832
/** mbed Microcontroller Library ****************************************************************************** * @file i2s_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for I2S. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "objects.h" #include "i2s_api.h" #include "pinmap.h" /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_I2S * @brief MBED_I2S driver modules. * @{ */ /** @defgroup MBED_I2S_Exported_Types MBED_I2S Exported Types * @{ */ typedef struct { VOID (*TxCCB)(uint32_t id, char *pbuf); u32 TxCBId; VOID (*RxCCB)(uint32_t id, char *pbuf); u32 RxCBId; } I2S_USER_CB; static I2S_InitTypeDef I2SInitStruct; static I2S_USER_CB I2SUserCB; //Pointer to I2S User Callback static u32 next_tx_complete = 0; extern u32 i2s_cur_tx_page; extern u32 i2s_cur_rx_page; /** * @} */ /** @defgroup MBED_I2S_Exported_Functions MBED_I2S Exported Functions * @{ */ static void i2s_sw_reset(void) { i2s_cur_tx_page = 0; i2s_cur_rx_page = 0; next_tx_complete = 0; } static void i2s_isr(void *Data) { /* To avoid gcc warnings */ ( void ) Data; u32 I2STxIsr, I2SRxIsr; u8 I2SPageNum = I2SInitStruct.I2S_PageNum; u32 i; u32 pbuf; u32 cur_rx_page = 0; I2S_ISRGet(I2S_DEV, &I2STxIsr, &I2SRxIsr); I2S_INTClear(I2S_DEV, I2STxIsr, I2SRxIsr); for (i=0 ; i<I2SPageNum; i++) { // page 0, 1, 2, 3 cur_rx_page = I2S_GetRxPage(I2S_DEV); if (I2SRxIsr & (1<<cur_rx_page)) { pbuf = I2S_GetRxPageAddr(cur_rx_page); I2SRxIsr &= ~(1<<cur_rx_page); I2SUserCB.RxCCB(I2SUserCB.RxCBId, (char*)pbuf); } else { break; } } for (i=0 ; i<I2SPageNum; i++) { // page 0, 1, 2, 3 if (I2STxIsr & (1<<next_tx_complete)) { pbuf = I2S_GetTxPageAddr(next_tx_complete); I2STxIsr &= ~(1<<next_tx_complete); next_tx_complete++; next_tx_complete &= 0x03; I2SUserCB.TxCCB(I2SUserCB.TxCBId, (char*)pbuf); } else { break; } } } /** * @brief Initializes the I2S device, include clock/function/interrupt/I2S registers. * @param obj: i2s object define in application software. * @param sck: Serial clock PinName according to pinmux spec. * @param ws: Word select PinName according to pinmux spec. * @param sd_tx: Tx PinName according to pinmux spec. * @param sd_rx: Rx PinName according to pinmux spec. * @param mck: Master clock PinName according to pinmux spec. * @retval none */ void i2s_init(i2s_t *obj, PinName sck, PinName ws, PinName sd_tx, PinName sd_rx, PinName mck) { obj->i2s_idx = 0; DBG_PRINTF(MODULE_I2S, LEVEL_INFO, "%s: Use I2S%d \n", __func__, obj->i2s_idx); // Load user defined parameters I2S_StructInit(&I2SInitStruct); /*I2S Interrupt Initialization*/ InterruptRegister((IRQ_FUN) i2s_isr, I2S0_PCM0_IRQ, NULL, 5); InterruptEn(I2S0_PCM0_IRQ, 5); /* enable system pll */ PLL_I2S_Set(ENABLE); PLL_PCM_Set(ENABLE); /*I2S Pin Mux Initialization*/ RCC_PeriphClockCmd(APBPeriph_I2S0, APBPeriph_I2S0_CLOCK, ENABLE); Pinmux_Config(sck, PINMUX_FUNCTION_I2S); Pinmux_Config(ws, PINMUX_FUNCTION_I2S); Pinmux_Config(sd_tx, PINMUX_FUNCTION_I2S); Pinmux_Config(sd_rx, PINMUX_FUNCTION_I2S); Pinmux_Config(mck, PINMUX_FUNCTION_I2S); next_tx_complete = 0; I2SInitStruct.I2S_TRxAct = obj->direction; I2SInitStruct.I2S_ChNum = obj->channel_num; I2SInitStruct.I2S_Rate = obj->sampling_rate; I2SInitStruct.I2S_WordLen = obj->word_length; /*I2S HAL Initialization*/ I2S_Init(I2S_DEV, &I2SInitStruct); /*I2S Enable Module*/ I2S_Cmd(I2S_DEV, ENABLE); I2S_INTConfig(I2S_DEV, (I2S_TX_INT_PAGE0_OK|I2S_TX_INT_PAGE1_OK| I2S_TX_INT_PAGE2_OK|I2S_TX_INT_PAGE3_OK), (I2S_RX_INT_PAGE0_OK|I2S_RX_INT_PAGE1_OK | I2S_RX_INT_PAGE2_OK|I2S_RX_INT_PAGE3_OK)); } /** * @brief Sets page number, page size, page address. * @param obj: i2s object define in application software. * @param tx_buf: pointer to the start address of Tx page. * @param rx_buf: pointer to the start address of Rx page. * @param page_num: page number. This parameter must be set to a value in the 2~4 range * @param page_size: page size. This parameter must be set to a value in the 4~16384 bytes range * @retval none */ void i2s_set_dma_buffer(i2s_t *obj, char *tx_buf, char *rx_buf, uint32_t page_num, uint32_t page_size) { /* To avoid gcc warnings */ ( void ) obj; u32 i; //uint8_t i2s_idx = obj->i2s_idx; if ((page_num < 2) || (page_num > 4) || (page_size < 8)) { DBG_PRINTF(MODULE_I2S, LEVEL_INFO, "%s: PageNum(%d) valid value is 2~4; PageSize(%d must > 8)\r\n", \ __FUNCTION__, page_num, page_size); return; } I2SInitStruct.I2S_PageNum = page_num; I2SInitStruct.I2S_PageSize = page_size/4; // unit is 4-bytes I2S_SetPageSize(I2S_DEV, (page_size/4)); I2S_SetPageNum(I2S_DEV, (page_num)); I2S_SetDMABuf(I2S_DEV, (u8*)tx_buf, (u8*)rx_buf); for (i=0;i<page_num;i++) { I2S_SetTxPageAddr(i, (uint32_t)(tx_buf + ((page_size) * i))); I2S_SetRxPageAddr(i, (uint32_t)(rx_buf + ((page_size) * i))); } } /** * @brief Sets TX interrupt handler. * @param obj: i2s object define in application software. * @param handler: TX interrupt callback function. * @param id: TX interrupt callback function parameter. * @retval none */ void i2s_tx_irq_handler(i2s_t *obj, i2s_irq_handler handler, uint32_t id) { /* To avoid gcc warnings */ ( void ) obj; //uint8_t i2s_idx = obj->i2s_idx; I2SUserCB.TxCCB = handler; I2SUserCB.TxCBId = id; } /** * @brief Sets RX interrupt handler. * @param obj: i2s object define in application software. * @param handler: RX interrupt callback function. * @param id: RX interrupt callback function parameter. * @retval none */ void i2s_rx_irq_handler(i2s_t *obj, i2s_irq_handler handler, uint32_t id) { /* To avoid gcc warnings */ ( void ) obj; //uint8_t i2s_idx = obj->i2s_idx; I2SUserCB.RxCCB = handler; I2SUserCB.RxCBId = id; } /** * @brief Sets i2s data transfer direction. * @param obj: i2s object define in application software. * @param trx_type: transfer direction. * This parameter can be one of the following values: * @arg I2S_DIR_RX: Rx receive direction * @arg I2S_DIR_TX: Tx transmission direction * @arg I2S_DIR_TXRX: Tx & Rx bi-direction * @retval none */ void i2s_set_direction(i2s_t *obj, int trx_type) { obj->direction = trx_type; I2SInitStruct.I2S_TRxAct = trx_type; I2S_SetDirection(I2S_DEV, trx_type); if (trx_type == I2S_DIR_TX) { I2S_RxDmaCmd(I2S_DEV, DISABLE); } else if ((trx_type == I2S_DIR_TXRX) ||(trx_type == I2S_DIR_RX) ) { I2S_RxDmaCmd(I2S_DEV, ENABLE); } } /** * @brief Sets i2s channel number, sample rate, word length. * @param obj: i2s object define in application software. * @param channel_num: this parameter can be one of the following values: * @arg CH_STEREO: stereo channel * @arg CH_MONO: mono channel * @param rate: this parameter can be one of the following values: * @arg SR_8KHZ: sample rate is 8kHz * @arg SR_12KHZ: sample rate is 12kHz * @arg SR_16KHZ: sample rate is 16kHz * @arg SR_24KHZ: sample rate is 24kHz * @arg SR_32KHZ: sample rate is 32kHz * @arg SR_48KHZ: sample rate is 48kHz * @arg SR_64KHZ: sample rate is 64kHz * @arg SR_96KHZ: sample rate is 96kHz * @arg SR_192KHZ: sample rate is 192kHz * @arg SR_384KHZ: sample rate is 384kHz * @arg SR_7p35KHZ: sample rate is 7.35kHz * @arg SR_11p025KHZ: sample rate is 11.025kHz * @arg SR_14p7KHZ: sample rate is 14.7kHz * @arg SR_22p05KHZ: sample rate is 22.05kHz * @arg SR_29p4KHZ: sample rate is 29.4kHz * @arg SR_44p1KHZ: sample rate is 44.1kHz * @arg SR_58p8KHZ: sample rate is 58.8kHz * @arg SR_88p2KHZ: sample rate is 88.2kHz * @arg SR_176p4KHZ: sample rate is 176.4kHz * @param word_len: this parameter can be one of the following values: * @arg WL_16b: sample bit is 16 bit * @arg WL_24b: sample bit is 24 bit * @arg WL_32b: sample bit is 32 bit * @retval none */ void i2s_set_param(i2s_t *obj, int channel_num, int rate, int word_len) { obj->channel_num = channel_num; obj->sampling_rate = rate; obj->word_length = word_len; I2SInitStruct.I2S_ChNum = channel_num; I2SInitStruct.I2S_Rate = rate; I2SInitStruct.I2S_WordLen = word_len; I2S_SetChNum(I2S_DEV, I2SInitStruct.I2S_ChNum); I2S_SetRate(I2S_DEV, rate); I2S_SetWordLen(I2S_DEV, I2SInitStruct.I2S_WordLen); } /** * @brief Deinitializes the I2S device, include function/interrupt/I2S registers. * @param obj: i2s object define in application software. * @retval none */ void i2s_deinit(i2s_t *obj) { /* To avoid gcc warnings */ ( void ) obj; //uint8_t i2s_idx = obj->i2s_idx; IRQn_Type IrqNum = I2S0_PCM0_IRQ; /*I2S Interrupt DeInitialization*/ InterruptDis(IrqNum); InterruptUnRegister(IrqNum); /*I2S Disable Module*/ I2S_INTConfig(I2S_DEV, 0, 0); I2S_Cmd(I2S_DEV, DISABLE); i2s_sw_reset(); } /** * @brief Gets current tx page address. * @param obj: i2s object define in application software. * @retval address of current tx page or NULL * @note current page own by cpu, return address of current tx page * @note current page own by i2s, return NULL */ int* i2s_get_tx_page(i2s_t *obj) { /* To avoid gcc warnings */ ( void ) obj; //uint8_t i2s_idx = obj->i2s_idx; u8 cur_tx_page; cur_tx_page = I2S_GetTxPage(I2S_DEV); if (!I2S_TxPageBusy(I2S_DEV, cur_tx_page)) { return ((int*)I2S_GetTxPageAddr(cur_tx_page)); } else { return NULL; } } /** * @brief Sets current tx page own by i2s. * @param obj: i2s object define in application software. * @param pbuf: tx buffer adderss. * @retval none */ void i2s_send_page(i2s_t *obj, uint32_t *pbuf) { /* To avoid gcc warnings */ ( void ) obj; u32 cur_tx_page; cur_tx_page = I2S_GetTxPage(I2S_DEV); if (I2S_GetTxPageAddr(cur_tx_page) != (u32)pbuf) DBG_8195A("%s: tx buffer not match cur_tx_page \n", __func__); I2S_TxPageDMA_EN(I2S_DEV, cur_tx_page); } /** * @brief Sets current rx page own by i2s. * @param obj: i2s object define in application software. * @retval none */ void i2s_recv_page(i2s_t *obj) { /* To avoid gcc warnings */ ( void ) obj; u32 cur_rx_page; cur_rx_page = I2S_GetRxPage(I2S_DEV); if ((I2S_DEV->IS_RX_PAGE_OWN[cur_rx_page] & BIT(31)) == 0) { I2S_RxPageDMA_EN(I2S_DEV,cur_rx_page); } else { //DBG_8195A("i2s_recv_page: re-enable\r\n"); } } /** * @brief Enable i2s interrupt and function. * @param obj: i2s object define in application software. * @retval none */ void i2s_enable(i2s_t *obj) { /* To avoid gcc warnings */ ( void ) obj; //uint8_t i2s_idx = obj->i2s_idx; I2S_Cmd(I2S_DEV, ENABLE); I2S_INTConfig(I2S_DEV, (I2S_TX_INT_PAGE0_OK|I2S_TX_INT_PAGE1_OK| I2S_TX_INT_PAGE2_OK|I2S_TX_INT_PAGE3_OK), (I2S_RX_INT_PAGE0_OK|I2S_RX_INT_PAGE1_OK | I2S_RX_INT_PAGE2_OK|I2S_RX_INT_PAGE3_OK)); } /** * @brief Disable i2s interrupt and function. * @param obj: i2s object define in application software. * @retval none */ void i2s_disable(i2s_t *obj) { /* To avoid gcc warnings */ ( void ) obj; //uint8_t i2s_idx = obj->i2s_idx; I2S_INTConfig(I2S_DEV, 0, 0); I2S_Cmd(I2S_DEV, DISABLE); i2s_sw_reset(); } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/i2s_api.c
C
apache-2.0
11,981
/** mbed Microcontroller Library ****************************************************************************** * @file keyscan_api.c * @author * @version V1.0.0 * @date 2019-04-19 * @brief This file provides mbed API for KeyScan. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "objects.h" #include "PinNames.h" #include "keyscan_api.h" #include "pinmap.h" KeyScan_InitTypeDef KeyScanInitData; u32 keyrow[8] = {_PA_12, _PA_13, _PA_14, _PA_15, _PA_16, _PA_18, _PA_17, _PA_21}; u32 keycolumn[8] = {_PA_26, _PA_25, _PA_19, _PA_17, _PA_18, _PA_16, _PA_15, _PA_20}; /** * @brief initialization of pinmux settings and pad settings. * @param col: selected column num depending on KeyColumn(eg: col 0 & col 2, col is 5) . * @param row: selected column num depending on KeyRow . * @return void */ void keyscan_array_pinmux(u32 col, u32 row) { u32 temp; for(temp = 0; temp < 8; temp++) { if(col & (1 << temp)) { PAD_PullCtrl(keycolumn[temp], GPIO_PuPd_NOPULL); Pinmux_Config(keycolumn[temp], PINMUX_FUNCTION_KEYSCAN_COL); DBG_8195A("column:%d\n", keycolumn[temp]); } } for(temp = 0; temp < 8; temp++) { if(row & (1 << temp)) { PAD_PullCtrl(keyrow[temp], GPIO_PuPd_UP); Pinmux_Config(keyrow[temp], PINMUX_FUNCTION_KEYSCAN_ROW); DBG_8195A("row:%d\n", keyrow[temp]); } } } /** * @brief Get data number of keyscan FIFO. * @param obj: keyscan object defined in application software. * @retval data number of keyscan FIFO */ u8 keyscan_getdatanum(keyscan_t *obj) { u8 num; (void) obj; num = KeyScan_GetDataNum(KEYSCAN_DEV); return num; } /** * @brief Read data from keyscan FIFO. * @param obj: keyscan object defined in application software. * @param pBuf: buffer to save data read from KeyScan FIFO. * @param num: number of data to be read. * @retval None */ void keyscan_read(keyscan_t *obj, u32* pbuf, u8 num ) { (void) obj; KeyScan_Read(KEYSCAN_DEV, pbuf, num); } /** * @brief Initializes the KeyScan device. * @param obj: keyscan object defined in application software. * @retval None */ void keyscan_init(keyscan_t *obj) { /* keyscan not used */ if ((obj->col == 0) || (obj->row == 0)) { return; } /*init keyscan array*/ keyscan_array_pinmux(obj->col, obj->row); /*default value*/ KeyScan_StructInit(&KeyScanInitData); KeyScanInitData.KS_ColSel = obj->col; KeyScanInitData.KS_RowSel = obj->row; KeyScanInitData.KS_ClkDiv = obj->clk; KeyScanInitData.KS_WorkMode = obj->workmode<<3; KeyScanInitData.KS_LimitLevel = obj->keylimit; KeyScanInitData.KS_OverCtrl = obj->overctrl<<1; KeyScan_Init(KEYSCAN_DEV, &KeyScanInitData); } /** * @brief Enables or disables the specified KeyScan interrupts mask. * @param obj: keyscan object defined in application software. * @param keyscan_IT: specifies the KeyScan interrupt sources to be enabled or masked. * This parameter can be one or combinations of the following values: * @arg BIT_KS_SCAN_EVENT_INT_MSK: Mask Scan event interrupt status * @arg BIT_KS_FIFO_LIMIT_INT_MSK: Mask FIFO limit interrupt status * @arg BIT_KS_FIFO_OVERFLOW_INT_MSK: Mask FIFO overflow interrupt * @arg BIT_KS_FIFO_FULL_INT_MSK: Mask FIFO full interrupt * @arg BIT_KS_SCAN_FINISH_INT_MSK: Mask scan finish interrupt * @arg BIT_KS_FIFO_NOTEMPTY_INT_MSK: Mask FIFO nonempty interrupt * @arg BIT_KS_ALL_RELEASE_INT_MSK: Mask All Release interrupt * @param newstate: new state of the specified KeyScan interrupts mask. * This parameter can be: ENABLE or DISABLE. * @retval None */ void keyscan_set_irq(keyscan_t * obj, u32 keyscan_IT, u32 newstate) { ( void ) obj; KeyScan_INTConfig(KEYSCAN_DEV, keyscan_IT, newstate); } /** * @brief Clear the specified KeyScan interrupt pending bit. * @param obj: keyscan object defined in application software. * @param keyscan_IT: specifies the KeyScan interrupt to be cleared. * This parameter can be one or combinations of the following values: * @arg BIT_KS_FIFO_LIMIT_INT_STATUS: FIFO limit interrupt status * @arg BIT_KS_FIFO_OVERFLOW_INT_STATUS: FIFO overflow interrupt status * @arg BIT_KS_SCAN_FINISH_INT_STATUS: Scan finish interrupt status * @arg BIT_KS_ALL_RELEASE_INT_STATUS: All Release interrupt status * @note BIT_KS_SCAN_EVENT_INT_STATUS is automatically cleared by hardware when the data is read. * BIT_KS_FIFO_FULL_INT_STATUS is automatically cleared by hardware when the buffer level * goes below the BIT_KS_FIFO_THREHOLD_LEVEL threshold. * BIT_KS_FIFO_NOTEMPTY_INT_STATUS is automatically cleared by hardware when the FIFO is empty. * @retval None */ void keyscan_clear_irq(keyscan_t * obj, u32 keyscan_IT) { ( void ) obj; KeyScan_ClearINT(KEYSCAN_DEV, keyscan_IT); } /** * @brief Get KeyScan interrupt status. * @param obj: keyscan object defined in application software. * @retval interrupt status */ u32 keyscan_get_irq_status(keyscan_t * obj) { ( void ) obj; u32 irq_status = KeyScan_GetINT(KEYSCAN_DEV); return irq_status; } /** * @brief Set keyscan interrupt handler. * @param obj: keyscan object define in application software. * @param func: the interrupt handler function. * @retval None */ void keyscan_set_irq_handler(keyscan_t * obj, void * func) { ( void ) obj; InterruptRegister((IRQ_FUN)func, KEYSCAN_IRQ, (u32)obj, 5); InterruptEn(KEYSCAN_IRQ, 5); } /** * @brief Enable the specified KeyScan peripheral. * @param obj: keyscan object defined in application software. * @retval None */ void keyscan_enable(keyscan_t *obj) { (void) obj; KeyScan_Cmd(KEYSCAN_DEV, ENABLE); } /** * @brief disable the specified KeyScan peripheral. * @param obj: keyscan object defined in application software. * @retval None */ void keyscan_disable(keyscan_t *obj) { (void) obj; KeyScan_Cmd(KEYSCAN_DEV, DISABLE); } /** * @brief Clears the FIFO data. * @param obj: keyscan object defined in application software. * @retval None */ void keyscan_clearfifodata(keyscan_t *obj) { (void) obj; KeyScan_ClearFIFOData(KEYSCAN_DEV); } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/keyscan_api.c
C
apache-2.0
6,766
/** mbed Microcontroller Library ****************************************************************************** * @file lcdc_api.c * @author * @version V1.0.0 * @date 2019-04-19 * @brief This file provides mbed API for LCDC. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2019, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "objects.h" #include "lcdc_api.h" #include "pinmap.h" #include "PinNames.h" static PinName lcdc_mcu_pin[21] = {PB_28, PB_23, PB_22, PB_21, PB_20, PA_19, PA_20, PA_23, PA_24, PA_31, PB_0, PA_30, PA_28, PA_26, PA_25, PB_8, PB_9, PB_10, PB_11, PB_18, PB_19}; static PinName lcdc_rgb_pin[20] = {PB_28, PB_23, PB_22, PB_20, PA_19, PA_20, PA_23, PA_24, PA_31, PB_0, PA_30, PA_28, PA_26, PA_25, PB_8, PB_9, PB_10, PB_11, PB_18, PB_19}; static PinName lcdc_led_pin[9] = {PB_28, PB_23, PB_22, PA_19, PA_20, PA_23, PA_24, PA_31, PB_0}; static PinName lcdc_led_linesel_pin[10] = {PA_30, PA_28, PA_26, PA_25, PB_8, PB_9, PB_10, PB_11, PB_18, PB_19}; static void lcdc_pin_init(PinName* lcdc_pin, u32 length) { for(u32 i = 0; i < length; i++){ Pinmux_Config(lcdc_pin[i], PINMUX_FUNCTION_LCD); } } static int _log2(int n){ int a = 0; while(n%2 == 0){ n = n/2; a++; } return a; } /** * @brief Initializes the LCDC peripheral. * @param obj: lcdc object define in application software. * @retval None */ void lcdc_init(lcdc_t * obj) { if(obj->lcdc_type == 0){ LCDC_MCUInit(LCDC, &obj->lcdc_if.LCDC_MCUInitStruct); if(obj->lcdc_if.LCDC_MCUInitStruct.LCDC_MCUIfMode == LCDC_MCU_IF_16_BIT){ lcdc_pin_init(lcdc_mcu_pin, 21); }else{ lcdc_pin_init(lcdc_mcu_pin, 13); } }else if(obj->lcdc_type == 1){ LCDC_RGBInit(LCDC, &obj->lcdc_if.LCDC_RGBInitStruct); if(obj->lcdc_if.LCDC_RGBInitStruct.LCDC_RGBIfMode == LCDC_RGB_IF_16_BIT){ lcdc_pin_init(lcdc_rgb_pin, 20); }else{ lcdc_pin_init(lcdc_rgb_pin, 10); } }else if(obj->lcdc_type == 2){ LCDC_LEDInit(LCDC, &obj->lcdc_if.LCDC_LEDInitStruct); if(obj->lcdc_if.LCDC_LEDInitStruct.LCDC_LEDColorChnl == LCDC_LED_ONE_CHANNEL){ int line_sel; line_sel = _log2(obj->lcdc_if.LCDC_LEDInitStruct.LCDC_LEDImgHeight); lcdc_pin_init(lcdc_led_linesel_pin, line_sel); switch(obj->lcdc_if.LCDC_LEDInitStruct.LCDC_LEDColorNum ){ case LCDC_LED_ONE_COLOR: lcdc_pin_init(lcdc_led_pin, 4); break; case LCDC_LED_TWO_COLOR: lcdc_pin_init(lcdc_led_pin, 5); break; case LCDC_LED_THREE_COLOR: lcdc_pin_init(lcdc_led_pin, 6); break; } }else{ int line_sel; line_sel = _log2(obj->lcdc_if.LCDC_LEDInitStruct.LCDC_LEDImgHeight/2); lcdc_pin_init(lcdc_led_linesel_pin, line_sel); switch(obj->lcdc_if.LCDC_LEDInitStruct.LCDC_LEDColorNum ){ case LCDC_LED_ONE_COLOR: lcdc_pin_init(lcdc_led_pin, 5); break; case LCDC_LED_TWO_COLOR: lcdc_pin_init(lcdc_led_pin, 7); break; case LCDC_LED_THREE_COLOR: lcdc_pin_init(lcdc_led_pin, 9); break; } } }else{ DBG_8195A("LCDC IF ERROR: unknown lcdc interface type!!\n"); } } /** * @brief Trigger the hardware to transfer one frame from DMA buffer based * on sync signal. * @param obj: lcdc object define in application software. * @retval None */ void lcdc_mcu_dma_trigger(lcdc_t * obj) { /* To avoid gcc warnings */ ( void ) obj; LCDC_MCUDMATrigger(LCDC); } /** * @brief write data to MCU I/F bus. * @param obj: lcdc object define in application software. * @param Data: the data to transmit. * @retval None */ void lcdc_mcu_write_data(lcdc_t * obj, u16 data) { /* To avoid gcc warnings */ ( void ) obj; LCDC_MCUIOWriteData(LCDC, data); } /** * @brief read data from MCU I/F bus. * @param obj: lcdc object define in application software. * @retval the read value */ u16 lcdc_mcu_read_data(lcdc_t * obj) { /* To avoid gcc warnings */ ( void ) obj; return LCDC_MCUIOReadData(LCDC); } /** * @brief write command to MCU I/F bus. * @param obj: lcdc object define in application software. * @param Cmd: the command to transmit. * @retval None */ void lcdc_mcu_write_cmd(lcdc_t * obj, u16 cmd) { /* To avoid gcc warnings */ ( void ) obj; LCDC_MCUIOWriteCmd(LCDC, cmd); } /** * @brief Configure LCDC DMA burst size . * @param obj: lcdc object define in application software. * @param BurstSize: DMA burst size; Unit 64 Bytes. * @note If BurstSize=1, the actual burstsize = 1x64 Bytes; if the BurstSize=2, * the actual burstsize = 2x64 = 128 Bytes.... The parameter "BurstSize" is not more * than 8. * @retval None */ void lcdc_dma_burstsize_config(lcdc_t * obj, u32 BurstSize) { /* To avoid gcc warnings */ ( void ) obj; LCDC_DMAModeConfig(LCDC, BurstSize); } /** * @brief Configure LCDC DMA under flow mode and under flow error data . * @param obj: lcdc object define in application software. * @param DmaUnFlwMode: DMA under flow mode, this parameter * can be one of the following values: * @arg LCDC_DMAUNFW_OUTPUT_LASTDATA: output last data * @arg LCDC_DMAUNFW_OUTPUT_ERRORDATA: output error data * @param ErrorData: the output data when DMA FIFO underflow occurred. When under flow mode is configured as * LCDC_DMAUNFW_OUTPUT_ERRORDATA, this parameter is needed, and otherwise it can be ignored. * @retval None */ void lcdc_dma_underflow_config(lcdc_t * obj, u32 DmaUnFlwMode, u32 ErrorData) { /* To avoid gcc warnings */ ( void ) obj; LCDC_DMAUnderFlowConfig(LCDC, DmaUnFlwMode, ErrorData); } /** * @brief Configure image base address. * @param obj: lcdc object define in application software. * @param ImgBaseAddr: the image base address. * @retval None */ void lcdc_dma_addr_config(lcdc_t * obj, u32 ImgBaseAddr) { /* To avoid gcc warnings */ ( void ) obj; LCDC_DMAImageBaseAddrConfig(LCDC, ImgBaseAddr); } /** * @brief Set lcdc interrupt handler. * @param obj: lcdc object define in application software. * @param func: the interrupt handler function. * @retval None */ void lcdc_set_irq_handler(lcdc_t * obj, void * func) { InterruptRegister((IRQ_FUN)func, LCDC_IRQ, (u32)obj, 5); InterruptEn(LCDC_IRQ, 5); } /** * @brief Enables or disables the specified LCDC interrupts. * @param obj: lcdc object define in application software. * @param LCDC_IT: specifies the LCDC interrupts sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg LCDC_IT_DMAUNDFW: DMA FIFO underflow interrupt * @arg LCDC_IT_FRDN: LCD refresh done interrupt * @arg LCDC_IT_LINE: line interrupt * @arg LCDC_IT_IO_TIMEOUT: IO write/read timeout interrupt * @arg LCDC_IT_FRM_START: Frame Start interrupt * @param NewState: new state of the specified LCDC interrupts. * This parameter can be: ENABLE or DISABLE. * @retval None */ void lcdc_set_irq(lcdc_t * obj, u32 LCDC_IT, u32 NewState) { /* To avoid gcc warnings */ ( void ) obj; LCDC_INTConfig(LCDC, LCDC_IT, NewState); } /** * @brief Clears the LCDC's interrupt pending bits. * @param obj: lcdc object define in application software. * @param LCDC_IT: specifies the interrupt to be cleared. * This parameter can be any combination of the following values: * @arg LCDC_IT_LINE:line interrupt * @arg LCDC_IT_FRDN: refresh frame done interrupt * @arg LCDC_IT_DMAUNDFW: DMA FIFO under flow interrupt * @arg LCDC_IT_IO_TIMEOUT: IO write/read timeout interrupt * @arg LCDC_IT_FRM_START: Frame Start interrupt * @retval None */ void lcdc_clear_irq(lcdc_t * obj, u32 LCDC_IT) { /* To avoid gcc warnings */ ( void ) obj; LCDC_ClearINT(LCDC, LCDC_IT); } /** * @brief Get lcdc interrupt status. * @param obj: lcdc object define in application software. * @retval interrupt status */ u32 lcdc_get_irq_status(lcdc_t * obj) { /* To avoid gcc warnings */ ( void ) obj; return LCDC_GetINTStatus(LCDC); } /** * @brief Enables the LCDC. * @param obj: lcdc object define in application software. * @retval None */ void lcdc_enable(lcdc_t * obj) { /* To avoid gcc warnings */ ( void ) obj; LCDC_Cmd(LCDC, ENABLE); } /** * @brief Disables the LCDC. * @param obj: lcdc object define in application software. * @retval None */ void lcdc_disable(lcdc_t * obj) { /* To avoid gcc warnings */ ( void ) obj; LCDC_Cmd(LCDC, DISABLE); } /** * @brief Deinitializes the LCDC. * @param obj: lcdc object define in application software. * @note Disable LCDC instantly, clear and disable all interrupts. * @retval None */ void lcdc_deinit(lcdc_t * obj) { /* To avoid gcc warnings */ ( void ) obj; LCDC_DeInit(LCDC); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/lcdc_api.c
C
apache-2.0
9,548
/* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, Realtek Semiconductor Corp. * All rights reserved. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. ******************************************************************************* */ #include "objects.h" #include "pinmap.h" #if CONFIG_NFC_NORMAL #include "nfc_api.h" /** * @brief The NFC tag write callback function wrapper * * @return None * */ void nfc_tagwrite_callback(PNFC_ADAPTER pNFCAdp, uint32_t page, uint32_t wr_data) { nfctag_t *obj; nfc_write_cb handler; obj = pNFCAdp->nfc_obj; handler = (nfc_write_cb)obj->nfc_wr_cb; if (NULL != handler) { handler(obj->wr_cb_arg, page, wr_data); } } /** * @brief The NFC tag read callback function wrapper * * @return None * */ void nfc_event_callback(PNFC_ADAPTER pNFCAdp, uint32_t event) { nfctag_t *obj; nfc_event_cb handler; obj = pNFCAdp->nfc_obj; handler = (nfc_event_cb)obj->nfc_ev_cb; if (NULL != handler) { if (obj->event_mask & event) { handler(obj->ev_cb_arg, event); } } } /** * @brief The NFC tag read callback function wrapper * * @return None * */ void nfc_tagread_callback(PNFC_ADAPTER pNFCAdp, uint32_t page) { // notify upper layer when read tag page 0 only if (0 == page) { nfc_event_callback(pNFCAdp, NFC_EV_READ); } } /** * @brief The NFC cache read done callback function wrapper * * @return None * */ void nfc_cache_read_callback(PNFC_ADAPTER pNFCAdp, uint32_t start_pg, uint32_t *pbuf) { nfctag_t *obj; nfc_write_cb handler; obj = pNFCAdp->nfc_obj; handler = (nfc_write_cb)obj->nfc_cache_rd_cb; if (NULL != handler) { handler(obj->cache_read_cb_arg, start_pg, (uint32_t)pbuf); } } /** * @brief To initial NFC tag hardware and resource * * @return The result * */ int nfc_init(nfctag_t *obj, uint32_t *pg_init_val) { _memset((void *)obj, 0, sizeof(nfctag_t)); HalNFCDmemInit(pg_init_val, NFCTAGLENGTH); HalNFCInit(&(obj->NFCAdapter)); HalNFCFwDownload(); obj->NFCAdapter.nfc_obj = obj; obj->pwr_status = NFC_PWR_RUNNING; return NFC_OK; } /** * @brief To free NFC tag hardware and resource * * @return The result * */ int nfc_free(nfctag_t *obj) { HalNFCDeinit(&(obj->NFCAdapter)); return NFC_OK; } /** * @brief To register the callback function for NFC read occurred * * @return None * */ void nfc_read(nfctag_t *obj, nfc_read_cb handler, void *arg) { obj->nfc_rd_cb = (void *)handler; obj->rd_cb_arg = arg; } /** * @brief To register the callback function for NFC write occurred * * @return None * */ void nfc_write(nfctag_t *obj, nfc_write_cb handler, void *arg) { obj->nfc_wr_cb = (void *)handler; obj->wr_cb_arg = arg; } /** * @brief To register the callback function for NFC events occurred * and the event mask * * @return None * */ void nfc_event(nfctag_t *obj, nfc_event_cb handler, void *arg, unsigned int event_mask) { obj->nfc_ev_cb = (void *)handler; obj->ev_cb_arg = arg; obj->event_mask = event_mask; } /** * @brief To set a new power mode to the NFC device * * @return The result * */ int nfc_power(nfctag_t *obj, int pwr_mode, int wake_event) { // TODO: return NFC_OK; } /** * @brief to update the NFC read cache. The data in the NFC read cache * buffer will be transmitted out when NFC read occurred * * @return The result * */ int nfc_cache_write(nfctag_t *obj, uint32_t *tbuf, unsigned int spage, unsigned int pg_num) { u8 remain_pg; u8 pg_offset=0; u8 i; if ((spage+pg_num) > NFC_MAX_CACHE_PAGE_NUM) { return NFC_ERROR; } remain_pg = pg_num; while (remain_pg > 0) { if (remain_pg >= 4) { A2NWriteCatch (&obj->NFCAdapter, (spage+pg_offset), 4, (u32*)(&tbuf[pg_offset])); remain_pg -= 4; pg_offset += 4; } else { for(i=0;i<remain_pg;i++) { A2NWriteCatch (&obj->NFCAdapter, (spage+pg_offset), 1, (u32*)(&tbuf[pg_offset])); pg_offset++; } remain_pg = 0; } } return NFC_OK; } /** * @brief To get current NFC status * * @return The result * */ int nfc_cache_raed(nfctag_t *obj, nfc_cache_read_cb handler, void *arg, unsigned int start_pg) { if (start_pg > NFC_MAX_CACHE_PAGE_NUM) { return NFC_ERROR; } obj->nfc_cache_rd_cb = (void *)handler; obj->cache_read_cb_arg = arg; A2NReadCatch(&(obj->NFCAdapter), (u8)start_pg); return NFC_OK; } /** * @brief to read back the NFC read cache. * * @return The result * */ int nfc_status(nfctag_t *obj) { // TODO: return (obj->pwr_status); } #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/nfc_api.c
C
apache-2.0
5,196
/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBED_OBJECTS_H #define MBED_OBJECTS_H #include "cmsis.h" #include "PortNames.h" #include "PeripheralNames.h" #include "PinNames.h" #include "rtl8721d.h" #ifdef __cplusplus extern "C" { #endif typedef struct gpio_irq_s { PinName pin; } gpio_irq_t; typedef struct gpio_s { PinName pin; } gpio_t; struct port_s { PortName port; uint32_t mask; }; struct serial_s { uint8_t uart_idx; uint32_t tx_len; uint32_t rx_len; }; struct spi_s { /* user variables */ uint32_t spi_idx; /* internal variables */ uint32_t irq_handler; uint32_t irq_id; uint32_t state; uint8_t sclk; uint32_t bus_tx_done_handler; uint32_t bus_tx_done_irq_id; }; struct pwmout_s { uint8_t pwm_idx; uint32_t period;//in us float pulse;//in us }; struct i2c_s { uint32_t i2c_idx; I2C_TypeDef * I2Cx; }; struct flash_s { FLASH_InitTypeDef SpicInitPara; }; struct analogin_s { uint8_t adc_idx; }; struct gtimer_s { void *handler; uint32_t hid; uint8_t timer_id; uint8_t is_periodcal; }; struct i2s_s { uint8_t i2s_idx; uint8_t sampling_rate; uint8_t channel_num; uint8_t word_length; uint8_t direction; }; struct gdma_s { u8 index; u8 ch_num; IRQ_FUN user_cb; u32 user_cb_data; }; struct captouch_s { CapTouch_CHInitTypeDef CT_Channel[4]; void* irq_handler_press; void* irq_handler_release; }; struct keyscan_s { u32 row; u32 col; u32 clk; u32 workmode; //0 for regular scan mode, 1 for event trigger mode u32 keylimit; u32 overctrl; //0 for discard new, 1 for discard oldest }; struct lcdc_s{ u32 lcdc_type; union{ LCDC_MCUInitTypeDef LCDC_MCUInitStruct; LCDC_RGBInitTypeDef LCDC_RGBInitStruct; LCDC_LEDInitTypeDef LCDC_LEDInitStruct; }lcdc_if; }; #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/objects.h
C
apache-2.0
2,362
/* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, Realtek Semiconductor Corp. * All rights reserved. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. ******************************************************************************* */ #include "objects.h" #include "pinmap.h" /** * Configure pin enable and function */ void pin_function(PinName pin, int function) { u8 pin_index = 0; u32 Temp = 0; assert_param(pin != NC); /* 32bit per one pad */ /* get PADCTR index*/ pin_index = (pin) & 0x3F; /* get PADCTR */ Temp = PINMUX->PADCTR[pin_index]; /* set needs function */ Temp &= ~PAD_BIT_MASK_FUNCTION_ID; Temp |= (function & PAD_BIT_MASK_FUNCTION_ID); Temp &= ~PAD_BIT_SHUT_DWON; /* close pad power down */ /* set PADCTR register */ PINMUX->PADCTR[pin_index] = Temp; } /** * Configure pin pull-up/pull-down */ void pin_mode(PinName pin, PinMode mode) { u8 pull_type; switch (mode) { case PullNone: pull_type = GPIO_PuPd_NOPULL; break; case PullDown: pull_type = GPIO_PuPd_DOWN; break; case PullUp: pull_type = GPIO_PuPd_UP; break; default: pull_type = GPIO_PuPd_NOPULL; break; } PAD_PullCtrl((u32)pin, (u32)pull_type); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/pinmap.c
C
apache-2.0
1,380
/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "basic_types.h" #include "diag.h" #include "pinmap.h" void pinmap_pinout(PinName pin, const PinMap *map) { if (pin == NC) return; while (map->pin != NC) { if (map->pin == pin) { pin_mode(pin, PullNone); pin_function(pin, map->function); return; } map++; } } uint32_t pinmap_merge(uint32_t a, uint32_t b) { /* both are the same (inc both NC) */ if (a == b) return a; /* one (or both) is not connected */ if (a == (uint32_t)NC) return b; if (b == (uint32_t)NC) return a; /* mis-match error case */ DBG_8195A("%s: pinmap mis-match\n", __FUNCTION__); return (uint32_t)NC; } uint32_t pinmap_find_peripheral(PinName pin, const PinMap* map) { while (map->pin != NC) { if (map->pin == pin) { return map->peripheral; } map++; } return (uint32_t)NC; } uint32_t pinmap_peripheral(PinName pin, const PinMap* map) { uint32_t peripheral = (uint32_t)NC; if (pin == (PinName)NC) return (uint32_t)NC; peripheral = pinmap_find_peripheral(pin, map); if ((uint32_t)NC == peripheral) {// no mapping available DBG_8195A("%s: pinmap not found for peripheral\n", __FUNCTION__); } return peripheral; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/pinmap_common.c
C
apache-2.0
1,791
/** mbed Microcontroller Library ****************************************************************************** * @file port_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for GPIO PORT. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "objects.h" #include "port_api.h" #include "pinmap.h" #include "gpio_api.h" #include "PinNames.h" //#include "mbed_error.h" #define GPIO_PORT_NUM 2 /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_GPIOPORT * @brief MBED_GPIOPORT driver modules. * @{ */ /** @defgroup MBED_GPIOPORT_Exported_Functions MBED_GPIOPORT Exported Functions * @{ */ /** * @brief Get GPIO port pin name * @param port: PortName according to pinmux spec, this parameter can be one of the following values: * @arg PortA: port number is A, has 32 pins * @arg PortB: port number is B, has 32 pins * @param pin_n: pin number. * @retval port pin name * @note pin_n must be set to a value in the 0~31 range */ PinName port_pin(PortName port, int pin_n) { return (PinName)(port << 5 | pin_n); } /** * @brief Initializes the GPIO device port, include data direction registers. * @param obj: gpio port object define in application software. * @param port: PortName according to pinmux spec, this parameter can be one of the following values: * @arg PortA: port A, has 32 pins * @arg PortB: port B, has 32 pins * @param mask: One bit one gpio pin, select one or multiple pins of the specified port. * @param dir: gpio port direction, this parameter can be one of the following values: * @arg PIN_INPUT: port pins are input * @arg PIN_OUTPUT: port pins are output * @retval none */ void port_init(port_t *obj, PortName port, int mask, PinDirection dir) { assert_param(port < GPIO_PORT_NUM); obj->port = port; obj->mask = mask; port_dir(obj, dir); } /** * @brief Set GPIO port pins data direction. * @param obj: gpio port object define in application software. * @param dir: this parameter can be one of the following values: * @arg PIN_INPUT: port pins are input * @arg PIN_OUTPUT: port pins are output * @retval none */ void port_dir(port_t *obj, PinDirection dir) { if (dir == PIN_OUTPUT) { GPIO_PortDirection(obj->port, obj->mask, GPIO_Mode_OUT); } else { GPIO_PortDirection(obj->port, obj->mask, GPIO_Mode_IN); } } /** * @brief Configure GPIO port pins pull up/pull down. * @param obj: gpio port object define in application software. * @param mode: this parameter can be one of the following values: * @arg PullNone: HighZ * @arg PullDown: pull down * @arg PullUp: pull up * @retval none */ void port_mode(port_t *obj, PinMode mode) { uint32_t pin_idx; uint32_t max_num = 32; for (pin_idx = 0; pin_idx < max_num; pin_idx++) { if (obj->mask & BIT(pin_idx)) { /* PinName = (obj->port << 5 | pin_idx) */ pin_mode((obj->port << 5 | pin_idx), mode); } } } /** * @brief Sets value to the selected port pins. * @param obj: gpio port object define in application software. * @param value: One bit one gpio pin, set value to one or multiple pins of the specified port. * @note corresponding bit is 1, pin state set to high; corresponding bit is 0, pin state set to low * @retval none */ void port_write(port_t *obj, int value) { GPIO_PortWrite(obj->port, obj->mask, value); } /** * @brief Reads the specified gpio port pins. * @param obj: gpio port object define in application software. * @retval : state of the specified gpio port pins * @note corresponding bit is 1, pin state is high; corresponding bit is 0, pin state is low */ int port_read(port_t *obj) { u32 value = GPIO_PortRead(obj->port, obj->mask); return value; } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/port_api.c
C
apache-2.0
4,322
/** mbed Microcontroller Library ****************************************************************************** * @file pwmout_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for PWM. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "device.h" #include "objects.h" #include "pinmap.h" #include "pwmout_api.h" /** @defgroup AmebaD_Mbed_API * @{ */ /** @addtogroup MBED_PWM * @brief MBED_PWM driver modules. * @{ */ /** @defgroup MBED_PWM_Exported_Types MBED_PWM Exported Types * @{ */ #define PWM_TIMER 5 #define BIT_PWM_TIM_IDX_FLAG BIT(7) #define BIT_PWM_TIM_IDX_SHIFT 7 /** * @brief Table elements express the pin to PWM channel number, they are: * {pinName, km0_pin2chan, km4_pin2chan} */ const u32 pin2chan[19][3] = { {PA_12, 0, 0}, {PA_13, 1, 1}, {PA_23, 2, 2}, {PA_24, 3, 3}, {PA_25, 4, 4}, {PA_26, 5, 5}, {PA_28, 0, 6}, {PA_30, 1, 7}, {PB_4, 2, 8}, {PB_5, 3, 9}, {PB_18, 4, 10}, {PB_19, 5, 11}, {PB_20, 0, 12}, {PB_21, 1, 13}, {PB_22, 2, 14}, {PB_23, 3, 15}, {PB_24, 4, 16}, {PB_25, 5, 17}, {PB_7, 5, 17} }; u8 timer5_start = 0; u8 timer05_start = 0; u8 km4_ch_start[18] = {0}; u8 km0_ch_start[6] = {0}; u8 prescaler = 0; RTIM_TypeDef* PWM_TIM[2] = {TIMM05, TIM5}; /** * @} */ /** @defgroup MBED_PWM_Exported_Functions MBED_PWM Exported Functions * @{ */ /** * @brief Return PWM channel number according to pin name. * @param pin: The pin to be told. * @retval value: PWM channel number corresponding to the pin. */ u32 pwmout_pin2chan(PinName pin) { int i = 0; for(;i < 19;i++){ if(pin2chan[i][0] == pin){ return (pin2chan[i][2] | BIT_PWM_TIM_IDX_FLAG); } } return NC; } /** * @brief Initializes the TIM5/TIMM05 device, include TIM5/TIMM05 registers and function. * @param obj: PWM object define in application software. * @retval none */ void pwmout_timer5_init(pwmout_t* obj) { RTIM_TimeBaseInitTypeDef TIM_InitStruct; RTIM_TimeBaseStructInit(&TIM_InitStruct); TIM_InitStruct.TIM_Idx = PWM_TIMER; RTIM_TimeBaseInit(PWM_TIM[obj->pwm_idx >>BIT_PWM_TIM_IDX_SHIFT], &TIM_InitStruct, TIMER5_IRQ, NULL, (u32)&TIM_InitStruct); RTIM_Cmd(PWM_TIM[obj->pwm_idx >>BIT_PWM_TIM_IDX_SHIFT], ENABLE); if (obj->pwm_idx & BIT_PWM_TIM_IDX_FLAG) { timer5_start = 1; } else { timer05_start = 1; } } /** * @brief Initializes the PWM function/registers of the specified pin with default parameters. * @param obj: PWM object define in application software. * @param pin: the pinname of specified channel to be set. * @retval none * @note * - default period: 1638us * - default pulse width: 102us * - default duty cycle: 6.227% */ void pwmout_init(pwmout_t* obj, PinName pin) { u32 pwm_chan; TIM_CCInitTypeDef TIM_CCInitStruct; uint8_t pwm_tim_idx; pwm_chan = pwmout_pin2chan(pin); if(pwm_chan == NC) DBG_8195A("PinName error: pwm channel of PinName doesn't exist!\n"); obj->pwm_idx = pwm_chan; obj->period = 0x10000 * (prescaler + 1) / 40; obj->pulse = 0x1000 * (prescaler + 1) / 40; pwm_tim_idx = obj->pwm_idx >> BIT_PWM_TIM_IDX_SHIFT; pwm_chan = pwm_chan & (~BIT_PWM_TIM_IDX_FLAG); if(pwm_tim_idx && (!timer5_start)) { pwmout_timer5_init(obj); }else if ((!pwm_tim_idx) && (!timer05_start)) { pwmout_timer5_init(obj); } RTIM_CCStructInit(&TIM_CCInitStruct); RTIM_CCxInit(PWM_TIM[pwm_tim_idx], &TIM_CCInitStruct, pwm_chan); RTIM_CCxCmd(PWM_TIM[pwm_tim_idx], pwm_chan, TIM_CCx_Enable); if ((obj->pwm_idx & BIT_PWM_TIM_IDX_FLAG)) { Pinmux_Config(pin, PINMUX_FUNCTION_PWM_HS); } else { Pinmux_Config(pin, PINMUX_FUNCTION_PWM_LP); } if (obj->pwm_idx & BIT_PWM_TIM_IDX_FLAG) { km4_ch_start[pwm_chan] = 1; } else { km0_ch_start[pwm_chan] = 1; } } /** * @brief Deinitializes the PWM device of the specified channel. * @param obj: PWM object define in application software. * @retval none * @note If all channels are released, TIM5/TIMM05 will also be disabled. */ void pwmout_free(pwmout_t* obj) { /* disable pwm channel */ uint8_t pwm_chan = obj->pwm_idx & (~BIT_PWM_TIM_IDX_FLAG); uint8_t pwm_tim_idx = obj->pwm_idx >> BIT_PWM_TIM_IDX_SHIFT;; if(pwm_tim_idx && km4_ch_start[pwm_chan]){ km4_ch_start[pwm_chan] = 0; RTIM_CCxCmd(PWM_TIM[pwm_tim_idx], pwm_chan, TIM_CCx_Disable); /* stop timer5 if no pwm channels starts */ for(pwm_chan = 0;pwm_chan < 18;pwm_chan++){ if(km4_ch_start[pwm_chan]){ return; } } RTIM_Cmd(PWM_TIM[pwm_tim_idx], DISABLE); timer5_start = 0; } else if (!(pwm_tim_idx) && km0_ch_start[pwm_chan]) { km0_ch_start[pwm_chan] = 0; RTIM_CCxCmd(PWM_TIM[pwm_tim_idx], pwm_chan, TIM_CCx_Disable); /* stop timer05 if no pwm channels starts */ for(pwm_chan = 0;pwm_chan < 6;pwm_chan++){ if(km0_ch_start[pwm_chan]){ return; } } RTIM_Cmd(PWM_TIM[pwm_tim_idx], DISABLE); timer05_start = 0; } return; } /** * @brief Set the duty cycle of the specified channel. * @param obj: PWM object define in application software. * @param percent: The duty cycle value to be set. * @retval none */ void pwmout_write(pwmout_t* obj, float percent) //write duty-cycle { u32 ccrx; if (percent < (float)0.0) { percent = 0.0; } else if (percent > (float)1.0) { percent = 1.0; } obj->pulse = (percent * obj->period); ccrx = (u32)(obj->pulse * 40 / (prescaler + 1)) & 0x0000ffff; RTIM_CCRxSet(PWM_TIM[obj->pwm_idx >>BIT_PWM_TIM_IDX_SHIFT], ccrx, obj->pwm_idx & (~BIT_PWM_TIM_IDX_FLAG)); } /** * @brief Get the duty cycle value of the specified channel. * @param obj: PWM object define in application software. * @retval : the duty cycle value of the specified channel. */ float pwmout_read(pwmout_t* obj) //read duty-cycle { float value = 0; if (obj->period > 0) { value = (float)obj->pulse / (float)obj->period; } return ((value > 1.0) ? (1.0) : (value)); } /** * @brief Set the period of the specified channel in seconds. * @param obj: PWM object define in application software. * @param seconds: The period value to be set in seconds. * @retval none */ void pwmout_period(pwmout_t* obj, float seconds) { pwmout_period_us(obj, (int)(seconds * 1000000.0f)); } /** * @brief Set the period of the specified channel in millseconds. * @param obj: PWM object define in application software. * @param ms: The period value to be set in millseconds. * @retval none */ void pwmout_period_ms(pwmout_t* obj, int ms) { pwmout_period_us(obj, (int)(ms * 1000)); } /** * @brief Set the period of the specified channel in microseconds. * @param obj: PWM object define in application software. * @param us: The period value to be set in microseconds. * @retval none */ void pwmout_period_us(pwmout_t* obj, int us) { u32 arr; float dc = pwmout_read(obj); u32 tmp = us * 40 / (prescaler + 1); if(tmp > 0x10000){ prescaler = us * 40 / 0x10000; RTIM_PrescalerConfig(PWM_TIM[obj->pwm_idx >>BIT_PWM_TIM_IDX_SHIFT], prescaler, TIM_PSCReloadMode_Update); } obj->period = us; arr = us * 40 / (prescaler + 1) - 1; RTIM_ChangePeriod(PWM_TIM[obj->pwm_idx >>BIT_PWM_TIM_IDX_SHIFT], arr); pwmout_write(obj, dc); } /** * @brief Set the pulse width of the specified channel in seconds. * @param obj: PWM object define in application software. * @param seconds: The pulse width value to be set in seconds. * @retval none */ void pwmout_pulsewidth(pwmout_t* obj, float seconds) { pwmout_pulsewidth_us(obj, (int)(seconds * 1000000.0f)); } /** * @brief Set the pulse width of the specified channel in milliseconds. * @param obj: PWM object define in application software. * @param ms: The pulse width value to be set in milliseconds. * @retval none */ void pwmout_pulsewidth_ms(pwmout_t* obj, int ms) { pwmout_pulsewidth_us(obj, ms * 1000); } /** * @brief Set the pulse width of the specified channel in microseconds. * @param obj: PWM object define in application software. * @param us: The pulse width value to be set in microseconds. * @retval none */ void pwmout_pulsewidth_us(pwmout_t* obj, int us) { u32 ccrx; obj->pulse = (float)us; ccrx = (u32)(obj->pulse * 40 / (prescaler + 1)) & 0x0000ffff; RTIM_CCRxSet(PWM_TIM[obj->pwm_idx >>BIT_PWM_TIM_IDX_SHIFT], ccrx, obj->pwm_idx & (~BIT_PWM_TIM_IDX_FLAG)); } /** * @brief Enable the specified channel to output PWM. * @param obj: PWM object define in application software. * @retval none */ void pwmout_start(pwmout_t* obj) { RTIM_CCxCmd(PWM_TIM[obj->pwm_idx >>BIT_PWM_TIM_IDX_SHIFT], obj->pwm_idx & (~BIT_PWM_TIM_IDX_FLAG), TIM_CCx_Enable); } /** * @brief Disable the specified channel to output PWM. * @param obj: PWM object define in application software. * @retval none */ void pwmout_stop(pwmout_t* obj) { RTIM_CCxCmd(PWM_TIM[obj->pwm_idx >>BIT_PWM_TIM_IDX_SHIFT], obj->pwm_idx & (~BIT_PWM_TIM_IDX_FLAG), TIM_CCx_Disable); } /** * @} */ /** * @} */ /** * @} */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/pwmout_api.c
C
apache-2.0
9,435
/** mbed Microcontroller Library ****************************************************************************** * @file rtc_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for RTC. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "rtc_api.h" #include <time.h> #include "timer_api.h" static struct tm rtc_timeinfo; static int rtc_en = 0; static alarm_irq_handler rtc_alarm_handler; static const u8 dim[12] = { 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_RTC * @brief MBED_RTC driver modules. * @{ */ /** @defgroup MBED_RTC_Exported_Functions MBED_RTC Exported Functions * @{ */ /** * @brief This function is used to tell a year is a leap year or not. * @param year: The year need to be told. * @retval value: * - 1: This year is leap year. * - 0: This year is not leap year. */ static inline bool is_leap_year(unsigned int year) { u32 full_year = year + 1900; return (!(full_year % 4) && (full_year % 100)) || !(full_year % 400); } /** * @brief This function tells how many days in a month of a year. * @param year: Specified year * @param month: Specified month * @retval value: Number of days in the month. */ static u8 days_in_month (u8 month, u8 year) { u8 ret = dim[month]; if (ret == 0) ret = is_leap_year (year) ? 29 : 28; return ret; } /** * @brief This function is used to calculate month and day of month according to year and day of the year. * @param year: years since 1900. * @param yday: day of the year. * @param mon: pointer to the variable which stores month, the value can be 0-11 * @param mday: pointer to the variable which stores day of month, the value can be 1-31 * @retval value: none */ static void rtc_calculate_mday(int year, int yday, int* mon, int* mday) { int t_mon = -1, t_yday = yday + 1; while(t_yday > 0){ t_mon ++; t_yday -= days_in_month(t_mon, year); } *mon = t_mon; *mday = t_yday + days_in_month(t_mon, year); } /** * @brief This function is used to calculate day of week according to date. * @param year: years since 1900. * @param mon: which month of the year * @param mday: pointer to the variable which store day of month * @param wday: pointer to the variable which store day of week, the value can be 0-6, and 0 means Sunday * @retval value: none */ static void rtc_calculate_wday(int year, int mon, int mday, int* wday) { int t_year = year + 1900, t_mon = mon + 1; if(t_mon == 1 || t_mon == 2){ t_year --; t_mon += 12; } int c = t_year / 100; int y = t_year % 100; int week = (c / 4) - 2 * c + (y + y / 4) + (26 * (t_mon + 1) / 10) + mday -1; while(week < 0){ week += 7; } week %= 7; *wday = week; } /** * @brief This function is used to restore rtc_timeinfo global variable whose value is lost after system reset. * @param none * @retval value: none */ static void rtc_restore_timeinfo(void) { u32 value; int days_in_year; RTC_TimeTypeDef RTC_TimeStruct; RTC_GetTime(RTC_Format_BIN, &RTC_TimeStruct); rtc_timeinfo.tm_sec = RTC_TimeStruct.RTC_Seconds; rtc_timeinfo.tm_min = RTC_TimeStruct.RTC_Minutes; rtc_timeinfo.tm_hour = RTC_TimeStruct.RTC_Hours; rtc_timeinfo.tm_yday = RTC_TimeStruct.RTC_Days; value = BKUP_Read(0); rtc_timeinfo.tm_year = (value & BIT_RTC_BACKUP) >> BIT_RTC_BACKUP_SHIFT; days_in_year = (is_leap_year(rtc_timeinfo.tm_year) ? 366 : 365); if(rtc_timeinfo.tm_yday > (days_in_year - 1)){ rtc_timeinfo.tm_year ++; rtc_timeinfo.tm_yday -= days_in_year; /* over one year, update days in RTC_TR */ RTC_TimeStruct.RTC_Days = rtc_timeinfo.tm_yday; RTC_SetTime(RTC_Format_BIN, &RTC_TimeStruct); } rtc_calculate_mday(rtc_timeinfo.tm_year, rtc_timeinfo.tm_yday, &rtc_timeinfo.tm_mon, &rtc_timeinfo.tm_mday); rtc_calculate_wday(rtc_timeinfo.tm_year, rtc_timeinfo.tm_mon, rtc_timeinfo.tm_mday, &rtc_timeinfo.tm_wday); } /** * @brief This function is used to backup tm_year parameter in rtc_timeinfo global variable before system reset. * @param none * @retval value: none */ void rtc_backup_timeinfo(void) { u32 value = BKUP_Read(0); value = (value & ~BIT_RTC_BACKUP) | (rtc_timeinfo.tm_year << BIT_RTC_BACKUP_SHIFT); BKUP_Write(0, value); BKUP_Set(0, BIT_RTC_RESTORE); } /** * @brief Initializes the RTC device, include clock, RTC registers and function. * @param none * @retval none */ void rtc_init(void) { RTC_InitTypeDef RTC_InitStruct; RCC_PeriphClockSource_RTC(0); RTC_StructInit(&RTC_InitStruct); RTC_InitStruct.RTC_HourFormat = RTC_HourFormat_24; RTC_Init(&RTC_InitStruct); /* 32760 need add need add 15 cycles (256Hz) every 4 min*/ //RTC_SmoothCalibConfig(RTC_CalibSign_Positive, 15, // RTC_CalibPeriod_4MIN, RTC_Calib_Enable); rtc_en = 1; } /** * @brief Deinitializes the RTC device. * @param none * @retval none */ void rtc_free(void) { rtc_en = 0; rtc_alarm_handler = NULL; } /** * @brief This function tells whether RTC is enabled or not. * @param none * @retval status: * - 1: RTC is enable. * - 0: RTC is disable. */ int rtc_isenabled(void) { return rtc_en; } /** * @brief Set the specified timestamp in seconds to RTC. * @param t: Seconds from 1970.1.1 00:00:00 to specified data and time * which is to be set. * @retval none */ void rtc_write(time_t t) { /* Convert the time in to a tm*/ struct tm *timeinfo = localtime(&t); RTC_TimeTypeDef RTC_TimeStruct; /*set time in RTC */ RTC_TimeStruct.RTC_H12_PMAM = RTC_H12_AM; RTC_TimeStruct.RTC_Days = timeinfo->tm_yday; RTC_TimeStruct.RTC_Hours = timeinfo->tm_hour; RTC_TimeStruct.RTC_Minutes = timeinfo->tm_min; RTC_TimeStruct.RTC_Seconds = timeinfo->tm_sec; RTC_SetTime(RTC_Format_BIN, &RTC_TimeStruct); /* Set rtc_timeinfo*/ _memcpy((void*)&rtc_timeinfo, (void*)timeinfo, sizeof(struct tm)); } /** * @brief Get current timestamp in seconds from RTC. * @param none * @retval : The current timestamp in seconds which is calculated from 1970.1.1 00:00:00. */ time_t rtc_read(void) { time_t t; struct tm tm_temp; RTC_TimeTypeDef RTC_TimeStruct; u32 delta_days = 0; if(BKUP_Read(0) & BIT_RTC_RESTORE){ rtc_restore_timeinfo(); BKUP_Clear(0, BIT_RTC_RESTORE); } _memcpy((void*)&tm_temp, (void*)&rtc_timeinfo, sizeof(struct tm)); /*hour, min, sec get from RTC*/ RTC_GetTime(RTC_Format_BIN, &RTC_TimeStruct); tm_temp.tm_sec = RTC_TimeStruct.RTC_Seconds; tm_temp.tm_min = RTC_TimeStruct.RTC_Minutes; tm_temp.tm_hour = RTC_TimeStruct.RTC_Hours; /* calculate how many days later from last time update rtc_timeinfo */ delta_days = RTC_TimeStruct.RTC_Days - tm_temp.tm_yday; /* calculate wday, mday, yday, mon, year*/ tm_temp.tm_wday += delta_days; if(tm_temp.tm_wday >= 7){ tm_temp.tm_wday = tm_temp.tm_wday % 7; } tm_temp.tm_yday += delta_days; tm_temp.tm_mday += delta_days; while(tm_temp.tm_mday > days_in_month(tm_temp.tm_mon, tm_temp.tm_year)){ tm_temp.tm_mday -= days_in_month(tm_temp.tm_mon, tm_temp.tm_year); tm_temp.tm_mon++; if(tm_temp.tm_mon >= 12){ tm_temp.tm_mon -= 12; tm_temp.tm_yday -= is_leap_year(tm_temp.tm_year) ? 366 : 365; tm_temp.tm_year ++; /* over one year, update days in RTC_TR */ RTC_TimeStruct.RTC_Days = tm_temp.tm_yday; RTC_SetTime(RTC_Format_BIN, &RTC_TimeStruct); /* update rtc_timeinfo */ _memcpy((void*)&rtc_timeinfo, (void*)&tm_temp, sizeof(struct tm)); } } /* Convert to timestamp(seconds from 1970.1.1 00:00:00)*/ t = mktime(&tm_temp); return t; } /** * @brief Disable RTC Alarm and function. * @param none * @retval none */ void rtc_disable_alarm(void) { InterruptDis(RTC_IRQ); InterruptUnRegister(RTC_IRQ); RTC_AlarmCmd(DISABLE); rtc_alarm_handler = NULL; } /** * @brief RTC alarm interrupt handler function. * @param data: RTC IRQ callback data * @retval none */ void rtc_alarm_intr_handler(u32 data) { /* To avoid gcc warnings */ ( void ) data; alarm_irq_handler hdl; /*clear alarm flag*/ RTC_AlarmClear(); /* execute user handler*/ if(rtc_alarm_handler != NULL){ hdl = (alarm_irq_handler)rtc_alarm_handler; hdl(); } /*disable alarm*/ rtc_disable_alarm(); } /** * @brief Set the specified RTC Alarm and interrupt. * @param alarm: alarm object define in application software. * @param alarmHandler: alarm interrupt callback function. * @retval status: * - 1: success * - Others: failure */ u32 rtc_set_alarm(alarm_t *alrm, alarm_irq_handler alarmHandler) { RTC_AlarmTypeDef RTC_AlarmStruct_temp; rtc_alarm_handler = alarmHandler; /* set alarm */ RTC_AlarmStructInit(&RTC_AlarmStruct_temp); RTC_AlarmStruct_temp.RTC_AlarmTime.RTC_H12_PMAM = RTC_H12_AM; RTC_AlarmStruct_temp.RTC_AlarmTime.RTC_Days = alrm->yday; RTC_AlarmStruct_temp.RTC_AlarmTime.RTC_Hours = alrm->hour; RTC_AlarmStruct_temp.RTC_AlarmTime.RTC_Minutes = alrm->min; RTC_AlarmStruct_temp.RTC_AlarmTime.RTC_Seconds = alrm->sec; RTC_AlarmStruct_temp.RTC_AlarmMask = RTC_AlarmMask_None; RTC_AlarmStruct_temp.RTC_Alarm2Mask = RTC_Alarm2Mask_None; RTC_SetAlarm(RTC_Format_BIN, &RTC_AlarmStruct_temp); RTC_AlarmCmd(ENABLE); InterruptRegister((IRQ_FUN)rtc_alarm_intr_handler, RTC_IRQ, (u32)alrm, 5); InterruptEn(RTC_IRQ, 5); return _TRUE; } /** * @} */ /** * @} */ /** * @} */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/rtc_api.c
C
apache-2.0
9,848
/** mbed Microcontroller Library ****************************************************************************** * @file serial_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for UART. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "objects.h" #include "serial_api.h" #include "serial_ex_api.h" #include "pinmap.h" #include <string.h> /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_UART * @brief MBED_UART driver modules. * @{ */ /** @defgroup MBED_UART_Exported_Types MBED_UART Exported Types * @{ */ typedef VOID (*UARTCB_FUN)(VOID *); typedef struct { int TxCount; // how many byte to TX int RxCount; // how many bytes to RX u8 *pTxBuf; u8 *pRxBuf; u8 UartIndex; GDMA_InitTypeDef UARTTxGdmaInitStruct; GDMA_InitTypeDef UARTRxGdmaInitStruct; UART_InitTypeDef UART_InitStruct; UART_TypeDef* UARTx; IRQn_Type IrqNum; /* for rx DMA timeout */ u32 last_dma_addr; VOID (*TxCompCallback)(VOID *para); // User Tx complete callback function VOID (*RxCompCallback)(VOID *para); // User Rx complete callback function VOID *TxCompCbPara; // the pointer argument for TxCompCbPara VOID *RxCompCbPara; // the pointer argument for RxCompCallback }MBED_UART_ADAPTER, *PMBED_UART_ADAPTER; #define UART_NUM (3) #define SERIAL_TX_IRQ_EN 0x01 #define SERIAL_RX_IRQ_EN 0x02 #define SERIAL_TX_DMA_EN 0x01 #define SERIAL_RX_DMA_EN 0x02 //#define UART_USE_GTIMER_TO 1 #define UART_TIMER_ID 1 #define UART_TIMER_TO 5000 #define CONFIG_GDMA_EN 1 static uint32_t serial_irq_ids[UART_NUM] = {0, 0, 0}; static uart_irq_handler irq_handler[UART_NUM]; static uint32_t serial_irq_en[UART_NUM]={0, 0, 0}; static int current_baudrate; #ifdef CONFIG_GDMA_EN static uint32_t serial_dma_en[UART_NUM] = {0, 0, 0}; #endif MBED_UART_ADAPTER uart_adapter[MAX_UART_INDEX+1]; #ifdef CONFIG_MBED_ENABLED int stdio_uart_inited = 0; serial_t stdio_uart; #endif #ifdef UART_USE_GTIMER_TO static void uart_gtimer_deinit(void); #endif static const PinMap PinMap_UART_TX[] = { {PA_12, UART_3, PIN_DATA(PullUp, PINMUX_FUNCTION_UART)}, {PB_1, UART_3, PIN_DATA(PullUp, PINMUX_FUNCTION_UART)}, {PA_26, UART_3, PIN_DATA(PullUp, PINMUX_FUNCTION_UART)}, {PA_18, UART_0, PIN_DATA(PullUp , PINMUX_FUNCTION_UART)}, {PA_21, UART_0, PIN_DATA(PullUp, PINMUX_FUNCTION_UART)}, {PB_9, UART_0, PIN_DATA(PullUp, PINMUX_FUNCTION_UART)}, {PB_19, UART_0, PIN_DATA(PullUp, PINMUX_FUNCTION_UART)}, {NC, NC, 0} }; static const PinMap PinMap_UART_RX[] = { {PA_13, UART_3, PIN_DATA(PullUp, PINMUX_FUNCTION_UART)}, {PB_2, UART_3, PIN_DATA(PullUp, PINMUX_FUNCTION_UART)}, {PA_25, UART_3, PIN_DATA(PullUp, PINMUX_FUNCTION_UART)}, {PA_19, UART_0, PIN_DATA(PullUp, PINMUX_FUNCTION_UART)}, {PA_22, UART_0, PIN_DATA(PullUp, PINMUX_FUNCTION_UART)}, {PB_8, UART_0, PIN_DATA(PullUp, PINMUX_FUNCTION_UART)}, {PB_18, UART_0, PIN_DATA(PullUp, PINMUX_FUNCTION_UART)}, {NC, NC, 0} }; static u32 uart_index_get(PinName tx) { if ((tx == _PA_12) ||(tx == _PB_1)|| (tx == _PA_26)) { return 3; } else if ((tx == _PA_18) || (tx == _PA_21)||(tx == _PB_9)||(tx == _PB_19)) { return 0; } else { assert_param(0); } return 3; } /** * @} */ /** @defgroup MBED_UART_Exported_Functions MBED_UART Exported Functions * @{ */ static u32 uart_dmasend_complete( IN VOID *Data ) { PMBED_UART_ADAPTER puart_adapter = (PMBED_UART_ADAPTER) Data; PGDMA_InitTypeDef GDMA_InitStruct; puart_adapter->TxCount = 0; GDMA_InitStruct = &puart_adapter->UARTTxGdmaInitStruct; // Clean Auto Reload Bit GDMA_ChCleanAutoReload(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, CLEAN_RELOAD_DST); // Clear Pending ISR GDMA_ClearINT(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); /*disable UART TX DMA*/ UART_TXDMACmd(puart_adapter->UARTx, DISABLE); GDMA_Cmd(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, DISABLE); GDMA_ChnlFree(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); UART_SetTxFlag(puart_adapter->UartIndex, 0); // Call user TX complete callback if (NULL != puart_adapter->TxCompCallback) { puart_adapter->TxCompCallback(puart_adapter->TxCompCbPara); } return 0; } static u32 uart_dmarecv_complete( IN VOID *Data ) { PMBED_UART_ADAPTER puart_adapter = (PMBED_UART_ADAPTER) Data; PGDMA_InitTypeDef GDMA_InitStruct; //u8 LineStatus; GDMA_InitStruct = &puart_adapter->UARTRxGdmaInitStruct; #ifdef UART_USE_GTIMER_TO RTIM_Cmd(TIMx[UART_TIMER_ID], DISABLE); uart_gtimer_deinit(); #endif // Clean Auto Reload Bit GDMA_ChCleanAutoReload(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, CLEAN_RELOAD_SRC); // Clear Pending ISR GDMA_ClearINT(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); /*disable UART RX DMA*/ UART_RXDMACmd(puart_adapter->UARTx, DISABLE); GDMA_Cmd(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, DISABLE); GDMA_ChnlFree(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); // Check the Line Status //LineStatus = (u8)UART_LineStatusGet(puart_adapter->UARTx); UART_SetRxFlag(puart_adapter->UartIndex, 0); /* close time out */ UART_INTConfig(puart_adapter->UARTx, RUART_IER_ERBI | RUART_IER_ELSI |RUART_IER_ETOI, DISABLE); // Call User Rx complete callback if (puart_adapter->RxCompCallback != NULL) { puart_adapter->RxCompCallback (puart_adapter->RxCompCbPara); } return 0; } static u32 uart_dmarecv_irqhandler( IN VOID *Data ) { PMBED_UART_ADAPTER puart_adapter = (PMBED_UART_ADAPTER) Data; puart_adapter->RxCount = 0; uart_dmarecv_complete(puart_adapter); return 0; } static void uart_txdone_callback(VOID *pAdapter) { PMBED_UART_ADAPTER puart_adapter = pAdapter; u8 uart_idx = puart_adapter->UartIndex; // Mask UART TX FIFI empty UART_INTConfig(puart_adapter->UARTx, RUART_IER_ETBEI, DISABLE); if (irq_handler[uart_idx] != NULL) { irq_handler[uart_idx](serial_irq_ids[uart_idx], TxIrq); } } static void uart_rxdone_callback(VOID *pAdapter) { PMBED_UART_ADAPTER puart_adapter = pAdapter; u8 uart_idx = puart_adapter->UartIndex; if (irq_handler[uart_idx] != NULL) { irq_handler[uart_idx](serial_irq_ids[uart_idx], RxIrq); } } static VOID uart_intrecv_complete( IN PMBED_UART_ADAPTER puart_adapter ) { //volatile u8 LineStatus; // Disable RX Interrupt UART_INTConfig(puart_adapter->UARTx, (RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI), DISABLE); // Check the Line Status //LineStatus = (u8)UART_LineStatusGet(puart_adapter->UARTx); UART_SetRxFlag(puart_adapter->UartIndex, 0); // Call User Rx complete callback if (puart_adapter->RxCompCallback != NULL) { puart_adapter->RxCompCallback (puart_adapter->RxCompCbPara); } } static VOID uart_intsend_complete( IN PMBED_UART_ADAPTER puart_adapter ) { // Disable Tx FIFO empty interrupt UART_INTConfig(puart_adapter->UARTx, RUART_IER_ETBEI, DISABLE); UART_SetTxFlag(puart_adapter->UartIndex, 0); // Call user TX complete callback if (NULL != puart_adapter->TxCompCallback) { puart_adapter->TxCompCallback(puart_adapter->TxCompCbPara); } } static u32 uart_irqhandler( IN VOID *Data ) { volatile u8 reg_iir; u8 IntId; u32 RegValue; PMBED_UART_ADAPTER puart_adapter = (PMBED_UART_ADAPTER) Data; reg_iir = UART_IntStatus(puart_adapter->UARTx); if ((reg_iir & RUART_IIR_INT_PEND) != 0) { // No pending IRQ return 0; } IntId = (reg_iir & RUART_IIR_INT_ID) >> 1; switch (IntId) { case RUART_LP_RX_MONITOR_DONE: RegValue = UART_RxMonitorSatusGet(puart_adapter->UARTx); break; case RUART_MODEM_STATUS: RegValue = UART_ModemStatusGet(puart_adapter->UARTx); break; case RUART_RECEIVE_LINE_STATUS: RegValue = UART_LineStatusGet(puart_adapter->UARTx); break; case RUART_TX_FIFO_EMPTY: if (UART_GetTxFlag(puart_adapter->UartIndex)) { int cnt=16; while(cnt>0&&puart_adapter->TxCount>0){ UART_CharPut(puart_adapter->UARTx, *puart_adapter->pTxBuf); puart_adapter->TxCount --; puart_adapter->pTxBuf ++; cnt--; } if (0 == puart_adapter->TxCount) { uart_intsend_complete(puart_adapter); } } else { // Call Tx done callback uart_txdone_callback(puart_adapter); } break; case RUART_RECEIVER_DATA_AVAILABLE: case RUART_TIME_OUT_INDICATION: if (UART_GetRxFlag(puart_adapter->UartIndex) == STATERX_INT) { u32 TransCnt = 0; TransCnt = UART_ReceiveDataTO(puart_adapter->UARTx, puart_adapter->pRxBuf, puart_adapter->RxCount, 1); puart_adapter->RxCount -= TransCnt; puart_adapter->pRxBuf += TransCnt; if (puart_adapter->RxCount == 0) { uart_intrecv_complete(puart_adapter); } } else { // Call Rx data ready callback RegValue = (UART_LineStatusGet(puart_adapter->UARTx)); if (RegValue & RUART_LINE_STATUS_REG_DR) { uart_rxdone_callback(puart_adapter); } } break; default: DBG_PRINTF(MODULE_UART, LEVEL_ERROR, "Unknown Interrupt \n"); break; } return 0; } #ifdef UART_USE_GTIMER_TO static void uart_gtimer_handle( IN VOID *Data ) { PMBED_UART_ADAPTER puart_adapter = (PMBED_UART_ADAPTER) Data; PGDMA_InitTypeDef GDMA_InitStruct; u32 TransCnt = 0; GDMA_InitStruct = &puart_adapter->UARTRxGdmaInitStruct; RTIM_INTClear(TIMx[UART_TIMER_ID]); if (UART_GetRxFlag(puart_adapter->UartIndex) == STATERX_DMA) { u32 Current_Addr = GDMA_GetDstAddr(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); u32 data_in_fifo = UART_Readable(puart_adapter->UARTx); /* have Rx some data */ if ((Current_Addr != (u32)(puart_adapter->pRxBuf)) || data_in_fifo) { /* not increase for 5ms */ if (puart_adapter->last_dma_addr == Current_Addr) { /* rx stop 5ms, packet complete */ RTIM_Cmd(TIMx[UART_TIMER_ID], DISABLE); //DBG_8195A("%s:UART DMA TO Current_Addr:%x start_addr:%x RxCount: %d\n", // __func__, Current_Addr, puart_adapter->pRxBuf, puart_adapter->RxCount); puart_adapter->RxCount = puart_adapter->RxCount - (Current_Addr - (u32)puart_adapter->pRxBuf); puart_adapter->pRxBuf = (u8*)Current_Addr; TransCnt = UART_ReceiveDataTO(puart_adapter->UARTx, puart_adapter->pRxBuf, puart_adapter->RxCount, 1); puart_adapter->RxCount -= TransCnt; puart_adapter->pRxBuf += TransCnt; uart_dmarecv_complete(puart_adapter); GDMA_Cmd(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, DISABLE); //DBG_8195A("UART DMA TO RxCount: %d\n", puart_adapter->RxCount); } else { puart_adapter->last_dma_addr = Current_Addr; } } else { /* rx not start */ puart_adapter->last_dma_addr = (u32)(puart_adapter->pRxBuf); } } } /** * @brief Initialize the timer used for the Uart Rx Dma time out. * @param puart_adapter: a PRUART_VERIFY_PARAMETER pointer. * @param Period: the desired timeout value (Unit: microsecond). * * @retval none */ static void uart_gtimer_init(PMBED_UART_ADAPTER puart_adapter, u32 PeriodUs) { RTIM_TimeBaseInitTypeDef TIM_InitStructTmp; RTIM_TimeBaseStructInit(&TIM_InitStructTmp); TIM_InitStructTmp.TIM_Idx = UART_TIMER_ID; TIM_InitStructTmp.TIM_Prescaler = 0x00; TIM_InitStructTmp.TIM_Period = (PeriodUs / 31 - 1); TIM_InitStructTmp.TIM_UpdateEvent = ENABLE; /* UEV enable */ TIM_InitStructTmp.TIM_UpdateSource = TIM_UpdateSource_Overflow; TIM_InitStructTmp.TIM_ARRProtection = DISABLE; RTIM_TimeBaseInit(TIMx[UART_TIMER_ID], &TIM_InitStructTmp, TIMx_irq[UART_TIMER_ID], (IRQ_FUN) uart_gtimer_handle, (u32)puart_adapter); RTIM_INTConfig(TIMx[UART_TIMER_ID], TIM_IT_Update, ENABLE); } static void uart_gtimer_deinit(void) { InterruptDis(TIMx_irq[UART_TIMER_ID]); InterruptUnRegister(TIMx_irq[UART_TIMER_ID]); RTIM_DeInit(TIMx[UART_TIMER_ID]); } #endif /** * @brief Initializes the UART device, include clock/function/interrupt/UART registers. * @param obj: uart object define in application software. * @param tx: Tx PinName according to pinmux spec. * @param rx: Rx PinName according to pinmux spec. * @retval none */ void serial_init(serial_t *obj, PinName tx, PinName rx) { uint8_t uart_idx = uart_index_get(tx); UARTName uart_tx = (UARTName)pinmap_peripheral(tx, PinMap_UART_TX); UARTName uart_rx = (UARTName)pinmap_peripheral(rx, PinMap_UART_RX); UARTName UARTx = (UARTName)pinmap_merge(uart_tx, uart_rx); PMBED_UART_ADAPTER puart_adapter = NULL; assert_param(UARTx != (UARTName)NC); obj->uart_idx = uart_idx; puart_adapter = &(uart_adapter[obj->uart_idx]); puart_adapter->UartIndex = uart_idx; puart_adapter->UARTx = UART_DEV_TABLE[uart_idx].UARTx; puart_adapter->IrqNum = UART_DEV_TABLE[uart_idx].IrqNum; /*Enable Uart Ip Clock*/ //switch (puart_adapter->UartIndex) { //case 0: /* UART 0 */ // RCC_PeriphClockCmd(APBPeriph_UART0, APBPeriph_UART0_CLOCK, ENABLE); //break; //case 1: /* UART 1 */ // RCC_PeriphClockCmd(APBPeriph_UART1, APBPeriph_UART1_CLOCK, ENABLE); //break; //default: //break; //} /* Configure the UART pins */ pinmap_pinout(tx, PinMap_UART_TX); pinmap_pinout(rx, PinMap_UART_RX); pin_mode(tx, PullUp); pin_mode(rx, PullUp); UART_StructInit(&puart_adapter->UART_InitStruct); UART_Init(puart_adapter->UARTx, &puart_adapter->UART_InitStruct); InterruptRegister((IRQ_FUN)uart_irqhandler, puart_adapter->IrqNum, (u32)puart_adapter, 5); InterruptEn(puart_adapter->IrqNum, 5); #ifdef CONFIG_MBED_ENABLED // For stdio management if (uart_idx == STDIO_UART) { stdio_uart_inited = 1; memcpy(&stdio_uart, obj, sizeof(serial_t)); } #endif } /** * @brief Deinitializes the UART device, include clock/function/interrupt/UART registers. * @param obj: uart object define in application software. * @retval none */ void serial_free(serial_t *obj) { PMBED_UART_ADAPTER puart_adapter = &(uart_adapter[obj->uart_idx]); UART_DeInit(puart_adapter->UARTx); InterruptDis(puart_adapter->IrqNum); InterruptUnRegister(puart_adapter->IrqNum); #ifdef UART_USE_GTIMER_TO uart_gtimer_deinit(); #endif #ifdef CONFIG_GDMA_EN if (serial_dma_en[obj->uart_idx] & SERIAL_RX_DMA_EN) { GDMA_ChnlFree(puart_adapter->UARTRxGdmaInitStruct.GDMA_Index, puart_adapter->UARTRxGdmaInitStruct.GDMA_ChNum); serial_dma_en[obj->uart_idx] &= ~SERIAL_RX_DMA_EN; } if (serial_dma_en[obj->uart_idx] & SERIAL_TX_DMA_EN) { GDMA_ChnlFree(puart_adapter->UARTTxGdmaInitStruct.GDMA_Index, puart_adapter->UARTTxGdmaInitStruct.GDMA_ChNum); serial_dma_en[obj->uart_idx] &= ~SERIAL_TX_DMA_EN; } #endif // TODO: recovery Pin Mux } /** * @brief Set UART device baudrate. * @param obj: uart object define in application software. * @param baudrate: Baud Rate Val, like 115200 (unit is HZ). * @retval none */ void serial_baud(serial_t *obj, int baudrate) { current_baudrate=baudrate; PMBED_UART_ADAPTER puart_adapter = &(uart_adapter[obj->uart_idx]); UART_SetBaud(puart_adapter->UARTx, baudrate); UART_RxCmd(puart_adapter->UARTx, ENABLE); if (baudrate <= 500000) { if (uart_config[obj->uart_idx].LOW_POWER_RX_ENABLE) { UART_MonitorParaConfig(puart_adapter->UARTx, 100, ENABLE); UART_RxMonitorCmd(puart_adapter->UARTx, ENABLE); RCC_PeriphClockSource_UART(puart_adapter->UARTx, UART_RX_CLK_OSC_LP); UART_LPRxBaudSet(puart_adapter->UARTx, baudrate, 2000000); UART_RxCmd(puart_adapter->UARTx, ENABLE); } } } /** * @brief Set UART format. * @param obj: uart object define in application software. * @param data_bits: data bits, this parameter can be one of the following values: * @arg 7 * @arg 8 * @param parity: this parameter can be one of the following values: * @arg ParityNone * @arg ParityOdd * @arg ParityEven * @arg ParityForced1: same action with ParityOdd * @arg ParityForced0: same action with ParityEven * @param stop_bits: this parameter can be one of the following values: * @arg 2 * @arg 1 * @retval none */ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_bits) { PMBED_UART_ADAPTER puart_adapter = &(uart_adapter[obj->uart_idx]); UART_TypeDef* UARTx = UART_DEV_TABLE[obj->uart_idx].UARTx; UART_RxCmd(puart_adapter->UARTx, DISABLE); if (data_bits == 8) { puart_adapter->UART_InitStruct.WordLen = RUART_WLS_8BITS; } else { puart_adapter->UART_InitStruct.WordLen = RUART_WLS_7BITS; } switch (parity) { case ParityOdd: case ParityForced0: puart_adapter->UART_InitStruct.Parity = RUART_PARITY_ENABLE; puart_adapter->UART_InitStruct.ParityType = RUART_ODD_PARITY; break; case ParityEven: case ParityForced1: puart_adapter->UART_InitStruct.Parity = RUART_PARITY_ENABLE; puart_adapter->UART_InitStruct.ParityType = RUART_EVEN_PARITY; break; default: // ParityNone puart_adapter->UART_InitStruct.Parity = RUART_PARITY_DISABLE; break; } if (stop_bits == 2) { puart_adapter->UART_InitStruct.StopBit = RUART_STOP_BIT_2; } else { puart_adapter->UART_InitStruct.StopBit = RUART_STOP_BIT_1; } UARTx->LCR = ((puart_adapter->UART_InitStruct.WordLen) | (puart_adapter->UART_InitStruct.StopBit << 2) | (puart_adapter->UART_InitStruct.Parity << 3) | (puart_adapter->UART_InitStruct.ParityType << 4) | (puart_adapter->UART_InitStruct.StickParity << 5)); UART_RxCmd(puart_adapter->UARTx, ENABLE); } /** * @brief Set UART interrupt handler if needed. * @param obj: uart object define in application software. * @param handler: interrupt callback function * @param id: interrupt callback parameter * @retval none */ void serial_irq_handler(serial_t *obj, uart_irq_handler handler, uint32_t id) { PMBED_UART_ADAPTER puart_adapter; u8 uart_idx; puart_adapter = &(uart_adapter[obj->uart_idx]); uart_idx = puart_adapter->UartIndex; irq_handler[uart_idx] = handler; serial_irq_ids[uart_idx] = id; } /** * @brief Enable/Disable UART interrupt. * @param obj: uart object define in application software. * @param irq: Tx or Rx interrupt, this parameter can be one of the following values: * @arg RxIrq * @arg TxIrq * @param enable: this parameter can be one of the following values: * @arg 0 disable * @arg 1 enable * @retval none */ void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable) { PMBED_UART_ADAPTER puart_adapter; u8 uart_idx; puart_adapter = &(uart_adapter[obj->uart_idx]); uart_idx = puart_adapter->UartIndex; if (enable) { if (irq == RxIrq) { serial_irq_en[uart_idx] |= SERIAL_RX_IRQ_EN; UART_INTConfig(puart_adapter->UARTx, RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI, ENABLE); } else { serial_irq_en[uart_idx] |= SERIAL_TX_IRQ_EN; } } else { // disable if (irq == RxIrq) { serial_irq_en[uart_idx] &= ~SERIAL_RX_IRQ_EN; UART_INTConfig(puart_adapter->UARTx, (RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI), DISABLE); } else { serial_irq_en[uart_idx] &= ~SERIAL_TX_IRQ_EN; UART_INTConfig(puart_adapter->UARTx, RUART_IER_ETBEI, DISABLE); } } } /** * @brief get one byte from UART. * @param obj: uart object define in application software. * @retval : received character * @note this function is asynchronous API. */ int serial_getc(serial_t *obj) { PMBED_UART_ADAPTER puart_adapter=&(uart_adapter[obj->uart_idx]); u8 RxByte = 0; while (!serial_readable(obj)); UART_CharGet(puart_adapter->UARTx, &RxByte); return (int)RxByte; } /** * @brief send one byte use UART. * @param obj: uart object define in application software. * @param c: the data to transmit. * @retval none * @note this function is asynchronous API. */ void serial_putc(serial_t *obj, int c) { PMBED_UART_ADAPTER puart_adapter=&(uart_adapter[obj->uart_idx]); while (!serial_writable(obj)); UART_CharPut(puart_adapter->UARTx, (c & 0xFF)); if (serial_irq_en[obj->uart_idx] & SERIAL_TX_IRQ_EN) { // UnMask TX FIFO empty IRQ UART_INTConfig(puart_adapter->UARTx, RUART_IER_ETBEI, ENABLE); } } /** * @brief check if there is data in rx fifo. * @param obj: uart object define in application software. * @retval status value: * - 1: TRUE * - 0: FALSE */ int serial_readable(serial_t *obj) { PMBED_UART_ADAPTER puart_adapter=&(uart_adapter[obj->uart_idx]); if (UART_Readable(puart_adapter->UARTx)) { return 1; } else { return 0; } } /** * @brief check if write data to tx fifo is permitted. * @param obj: uart object define in application software. * @retval status value: * - 1: TRUE * - 0: FALSE */ int serial_writable(serial_t *obj) { PMBED_UART_ADAPTER puart_adapter=&(uart_adapter[obj->uart_idx]); if (UART_Writable(puart_adapter->UARTx)) { return 1; } else { return 0; } } /** * @brief Clear Rx fifo. * @param obj: uart object define in application software. * @retval none */ void serial_clear(serial_t *obj) { PMBED_UART_ADAPTER puart_adapter; puart_adapter = &(uart_adapter[obj->uart_idx]); UART_ClearRxFifo(puart_adapter->UARTx); } /** * @brief set tx pinmux. * @param tx: Tx PinName according to pinmux spec. * @retval none */ void serial_pinout_tx(PinName tx) { Pinmux_Config(tx, PINMUX_FUNCTION_UART); } /** * @brief enable UART break contol function. * @param obj: uart object define in application software. * @retval none */ void serial_break_set(serial_t *obj) { PMBED_UART_ADAPTER puart_adapter=&(uart_adapter[obj->uart_idx]); UART_BreakCtl(puart_adapter->UARTx, 1); } /** * @brief disable UART break contol function. * @param obj: uart object define in application software. * @retval none */ void serial_break_clear(serial_t *obj) { PMBED_UART_ADAPTER puart_adapter=&(uart_adapter[obj->uart_idx]); UART_BreakCtl(puart_adapter->UARTx, 0); } /** * @brief set TX complete handler. * @param obj: uart object define in application software. * @param handler: TX complete callback function. * @param id: TX complete callback function parameter. * @retval none * @note this function is used when asynchronous API is used. */ void serial_send_comp_handler(serial_t *obj, void *handler, uint32_t id) { PMBED_UART_ADAPTER puart_adapter; puart_adapter = &(uart_adapter[obj->uart_idx]); puart_adapter->TxCompCallback = (UARTCB_FUN)handler; puart_adapter->TxCompCbPara = (void*)id; } /** * @brief set RX complete handler. * @param obj: uart object define in application software. * @param handler: RX complete callback function. * @param id: RX complete callback function parameter. * @retval none * @note this function is used when asynchronous API is used. */ void serial_recv_comp_handler(serial_t *obj, void *handler, uint32_t id) { PMBED_UART_ADAPTER puart_adapter; puart_adapter = &(uart_adapter[obj->uart_idx]); puart_adapter->RxCompCallback = (UARTCB_FUN)handler; puart_adapter->RxCompCbPara = (void*)id; } /** * @brief recv target length data use interrupt mode. * @param obj: uart object define in application software. * @param prxbuf: buffer to save data read from UART FIFO. * @param len: number of data to be read. * @retval HAL_Status * @note this function is asynchronous API. */ int32_t serial_recv_stream (serial_t *obj, char *prxbuf, uint32_t len) { PMBED_UART_ADAPTER puart_adapter=&(uart_adapter[obj->uart_idx]); int ret = HAL_OK; u32 TransCnt = 0; assert_param(prxbuf != NULL); assert_param(len != 0); if (UART_GetRxFlag(puart_adapter->UartIndex)) { DBG_PRINTF(MODULE_UART, LEVEL_WARN, "uart int rx: busy\n"); return HAL_BUSY; } obj->rx_len = len; puart_adapter->pRxBuf = (uint8_t*)prxbuf; puart_adapter->RxCount = len; UART_SetRxFlag(puart_adapter->UartIndex, STATERX_INT); // Could be the RX FIFO has some data already TransCnt = UART_ReceiveDataTO(puart_adapter->UARTx, puart_adapter->pRxBuf, puart_adapter->RxCount, 1); puart_adapter->RxCount -= TransCnt; puart_adapter->pRxBuf += TransCnt; if (puart_adapter->RxCount == 0) { uart_intrecv_complete(puart_adapter); } else { // Enable RX Interrupt UART_INTConfig(puart_adapter->UARTx, RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI, ENABLE); } return (ret); } /** * @brief send target length data use interrupt mode. * @param obj: uart object define in application software. * @param ptxbuf: buffer to be written to Tx FIFO. * @param len: number of data to be send. * @retval HAL_Status * @note this function is asynchronous API. */ int32_t serial_send_stream (serial_t *obj, char *ptxbuf, uint32_t len) { PMBED_UART_ADAPTER puart_adapter=&(uart_adapter[obj->uart_idx]); int ret = 0; int cnt=16; assert_param(ptxbuf != NULL); assert_param(len != 0); if (UART_GetTxFlag(puart_adapter->UartIndex)) { DBG_PRINTF(MODULE_UART, LEVEL_WARN, "uart int tx: busy\n"); return HAL_BUSY; } obj->tx_len = len; puart_adapter->pTxBuf = (uint8_t*)ptxbuf; puart_adapter->TxCount = len; UART_SetTxFlag(puart_adapter->UartIndex, STATETX_INT); while(cnt>0&&puart_adapter->TxCount>0){ UART_CharPut(puart_adapter->UARTx, *puart_adapter->pTxBuf); puart_adapter->TxCount --; puart_adapter->pTxBuf ++; cnt--; } if (0 == puart_adapter->TxCount) { uart_intsend_complete(puart_adapter); } else { // Enable Tx FIFO empty interrupt UART_INTConfig(puart_adapter->UARTx, RUART_IER_ETBEI, ENABLE); } return (ret); } /** * @brief recv target length data use DMA mode. * @param obj: uart object define in application software. * @param prxbuf: buffer to save data read from UART FIFO. * @param len: number of data to be read. * @retval HAL_Status * @note this function is asynchronous API. */ int32_t serial_recv_stream_dma (serial_t *obj, char *prxbuf, uint32_t len) { PMBED_UART_ADAPTER puart_adapter=&(uart_adapter[obj->uart_idx]); HAL_Status ret = HAL_OK; u32 ret1; assert_param(prxbuf != NULL); assert_param(len != 0); if (UART_GetRxFlag(puart_adapter->UartIndex)) { DBG_PRINTF(MODULE_UART, LEVEL_WARN, "uart dma rx: busy\n"); return HAL_BUSY; } obj->rx_len = len; puart_adapter->pRxBuf = (uint8_t*)prxbuf; puart_adapter->RxCount = len; puart_adapter->last_dma_addr = (u32)prxbuf; UART_SetRxFlag(puart_adapter->UartIndex, STATERX_DMA); // Disable Rx interrupt UART_INTConfig(puart_adapter->UARTx, (RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI), DISABLE); UART_RXDMAConfig(puart_adapter->UARTx, 4); UART_RXDMACmd(puart_adapter->UARTx, ENABLE); ret1 = UART_RXGDMA_Init(puart_adapter->UartIndex, &puart_adapter->UARTRxGdmaInitStruct, puart_adapter, uart_dmarecv_irqhandler, puart_adapter->pRxBuf, puart_adapter->RxCount); NVIC_SetPriority(GDMA_GetIrqNum(0, puart_adapter->UARTRxGdmaInitStruct.GDMA_ChNum), 12); if ((serial_dma_en[obj->uart_idx] & SERIAL_RX_DMA_EN)==0) { if(ret1 == _TRUE) { serial_dma_en[obj->uart_idx] |= SERIAL_RX_DMA_EN; } else { return HAL_BUSY; } } return (ret); } /** * @brief send target length data use DMA mode. * @param obj: uart object define in application software. * @param ptxbuf: buffer to be written to Tx FIFO. * @param len: number of data to be send. * @retval : HAL_Status * @note this function is asynchronous API. */ int32_t serial_send_stream_dma (serial_t *obj, char *ptxbuf, uint32_t len) { PMBED_UART_ADAPTER puart_adapter=&(uart_adapter[obj->uart_idx]); int32_t ret = HAL_OK; u32 ret1; assert_param(ptxbuf != NULL); assert_param(len != 0); if (UART_GetTxFlag(puart_adapter->UartIndex)) { DBG_PRINTF(MODULE_UART, LEVEL_WARN, "uart dma tx: busy\n"); return HAL_BUSY; } obj->tx_len = len; puart_adapter->pTxBuf = (uint8_t*)ptxbuf; puart_adapter->TxCount = len; UART_SetTxFlag(puart_adapter->UartIndex, STATETX_DMA); UART_TXDMAConfig(puart_adapter->UARTx, 8); UART_TXDMACmd(puart_adapter->UARTx, ENABLE); ret1 = UART_TXGDMA_Init(puart_adapter->UartIndex, &puart_adapter->UARTTxGdmaInitStruct, puart_adapter, uart_dmasend_complete, puart_adapter->pTxBuf, puart_adapter->TxCount); NVIC_SetPriority(GDMA_GetIrqNum(0, puart_adapter->UARTTxGdmaInitStruct.GDMA_ChNum), 12); if ((serial_dma_en[obj->uart_idx] & SERIAL_TX_DMA_EN)==0) { if(ret1 == _TRUE) { serial_dma_en[obj->uart_idx] |= SERIAL_TX_DMA_EN; } else { return HAL_BUSY; } } return (ret); } /** * @brief stop the stream or stream_dma TX. * @param obj: uart object define in application software. * @retval : number of bytes sent before stop */ int32_t serial_send_stream_abort (serial_t *obj) { PMBED_UART_ADAPTER puart_adapter=&(uart_adapter[obj->uart_idx]); int ret = 0; if (!UART_GetTxFlag(puart_adapter->UartIndex)) { //DBG_PRINTF(MODULE_UART, LEVEL_WARN, "uart tx abort: Not in TX state \n"); return HAL_OK; } // Disable Tx FIFO empty interrupt UART_INTConfig(puart_adapter->UARTx, RUART_IER_ETBEI, DISABLE); if(UART_GetTxFlag(puart_adapter->UartIndex) == STATERX_DMA) { if (uart_config[obj->uart_idx].LOW_POWER_RX_ENABLE == DISABLE) { u32 Current_Addr; PGDMA_InitTypeDef GDMA_InitStruct = &puart_adapter->UARTTxGdmaInitStruct; Current_Addr = GDMA_GetSrcAddr(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); GDMA_Cmd(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, DISABLE); puart_adapter->TxCount = puart_adapter->TxCount - (Current_Addr - (u32)puart_adapter->pTxBuf); puart_adapter->pTxBuf = (u8*)Current_Addr; // Clean Auto Reload Bit GDMA_ChCleanAutoReload(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, CLEAN_RELOAD_DST); // Clear Pending ISR GDMA_ClearINT(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); //GDMA_Cmd(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, DISABLE); GDMA_ChnlFree(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); UART_TXDMACmd(puart_adapter->UARTx, DISABLE); } } UART_SetTxFlag(puart_adapter->UartIndex, 0); UART_ClearTxFifo(puart_adapter->UARTx); ret = obj->tx_len - puart_adapter->TxCount; return (ret); } /** * @brief stop the stream or stream_dma RX. * @param obj: uart object define in application software. * @retval : number of bytes received before stop */ int32_t serial_recv_stream_abort (serial_t *obj) { PMBED_UART_ADAPTER puart_adapter=&(uart_adapter[obj->uart_idx]); int ret = 0; if (!UART_GetRxFlag(puart_adapter->UartIndex)) { //DBG_PRINTF(MODULE_UART, LEVEL_WARN, "uart rx abort: Not in TX state \n"); return HAL_OK; } // Disable Rx interrupt UART_INTConfig(puart_adapter->UARTx, (RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI), DISABLE); if(UART_GetRxFlag(puart_adapter->UartIndex) == STATERX_DMA) { if (uart_config[obj->uart_idx].LOW_POWER_RX_ENABLE == DISABLE) { u32 Current_Addr; u32 TransCnt; PGDMA_InitTypeDef GDMA_InitStruct = &puart_adapter->UARTRxGdmaInitStruct; /*when stream DMA mode used, some data may be in uart rx fifo, get it if transmission aborted*/ Current_Addr = GDMA_GetDstAddr(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); GDMA_Cmd(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, DISABLE); puart_adapter->RxCount = puart_adapter->RxCount - (Current_Addr - (u32)puart_adapter->pRxBuf); puart_adapter->pRxBuf = (u8*)Current_Addr; TransCnt = UART_ReceiveDataTO(puart_adapter->UARTx, puart_adapter->pRxBuf, puart_adapter->RxCount, 1); puart_adapter->RxCount -= TransCnt; puart_adapter->pRxBuf += TransCnt; // Clean Auto Reload Bit GDMA_ChCleanAutoReload(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, CLEAN_RELOAD_DST); // Clear Pending ISR GDMA_ClearINT(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); //GDMA_Cmd(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, DISABLE); GDMA_ChnlFree(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); UART_RXDMACmd(puart_adapter->UARTx, DISABLE); } } UART_SetRxFlag(puart_adapter->UartIndex, 0); UART_ClearRxFifo(puart_adapter->UARTx); ret = obj->rx_len - puart_adapter->RxCount; return (ret); } /** * @brief Clear TX fifo. * @param obj: uart object define in application software. * @retval none */ void serial_clear_tx(serial_t *obj) { UART_TypeDef* UARTx = UART_DEV_TABLE[obj->uart_idx].UARTx; UART_ClearTxFifo(UARTx); } /** * @brief Clear RX fifo. * @param obj: uart object define in application software. * @retval none */ void serial_clear_rx(serial_t *obj) { UART_TypeDef* UARTx = UART_DEV_TABLE[obj->uart_idx].UARTx; UART_ClearRxFifo(UARTx); } /** * @brief recv target length data use poll mode, with time out. * @param obj: uart object define in application software. * @param ptxbuf: buffer to be written to Tx FIFO. * @param len: number of data to be recv. * @param timeout_ms: polling time before timeout. * @retval : return received bytes count * @note this function is synchronous API. */ int32_t serial_recv_blocked (serial_t *obj, char *prxbuf, uint32_t len, uint32_t timeout_ms) { UART_TypeDef* UARTx = UART_DEV_TABLE[obj->uart_idx].UARTx; uint32_t cnt = 0; uint32_t startcount = SYSTIMER_TickGet(); obj->rx_len = len; while (1) { while (!serial_readable(obj)); UART_CharGet(UARTx, (u8 *)prxbuf); prxbuf++; cnt++; if (cnt == len) { break; } if (SYSTIMER_GetPassTime(startcount) > timeout_ms) { break; } } return cnt; } /** * @brief send target length data use poll mode, with time out. * @param obj: uart object define in application software. * @param ptxbuf: buffer to be written to Tx FIFO. * @param len: number of data to be send. * @param timeout_ms: polling time before timeout. * @retval : transmitted bytes count * @note this function is synchronous API. */ int32_t serial_send_blocked (serial_t *obj, char *ptxbuf, uint32_t len, uint32_t timeout_ms) { UART_TypeDef* UARTx = UART_DEV_TABLE[obj->uart_idx].UARTx; uint32_t cnt = 0; uint32_t startcount = SYSTIMER_TickGet(); obj->tx_len = len; while (1) { while (!serial_writable(obj)); UART_CharPut(UARTx, *ptxbuf); ptxbuf++; cnt++; if (cnt == len) { break; } if (SYSTIMER_GetPassTime(startcount) > timeout_ms) { break; } } return cnt; } /** * @brief disable uart clock and function. * @param obj: uart object define in application software. * @retval none */ void serial_disable (serial_t *obj) { switch (obj->uart_idx) { case 0: /* UART 0 */ RCC_PeriphClockCmd(APBPeriph_UART0, APBPeriph_UART0_CLOCK, DISABLE); break; case 1: /* UART 1 */ RCC_PeriphClockCmd(APBPeriph_UART1, APBPeriph_UART1_CLOCK, DISABLE); break; default: break; } } /** * @brief enable uart clock and function. * @param obj: uart object define in application software. * @retval none */ void serial_enable (serial_t *obj) { switch (obj->uart_idx) { case 0: /* UART 0 */ RCC_PeriphClockCmd(APBPeriph_UART0, APBPeriph_UART0_CLOCK, ENABLE); break; case 1: /* UART 1 */ RCC_PeriphClockCmd(APBPeriph_UART1, APBPeriph_UART1_CLOCK, ENABLE); break; default: break; } } /** * @brief recv target length data use interrupt mode. * @param obj: uart object define in application software. * @param prxbuf: buffer to save data read from UART FIFO. * @param len: number of data to be recv. * @param timeout_ms: polling time before timeout. * @param force_cs: forcing context switch function. * @retval : the byte count received before timeout, or error(<0) * @note this function is asynchronous API. */ int32_t serial_recv_stream_timeout (serial_t *obj, char *prxbuf, uint32_t len, uint32_t timeout_ms, void *force_cs) { UART_TypeDef* UARTx = UART_DEV_TABLE[obj->uart_idx].UARTx; PMBED_UART_ADAPTER puart_adapter=&(uart_adapter[obj->uart_idx]); u32 TransCnt = 0; void (*task_yield)(void); uint32_t startcount = SYSTIMER_TickGet(); assert_param(prxbuf != NULL); assert_param(len != 0); assert_param(timeout_ms > 0); //ret = HalRuartRecv(puart_adapter, (u8*)prxbuf, len, INT_BASED); if (UART_GetRxFlag(obj->uart_idx)) { DBG_PRINTF(MODULE_UART, LEVEL_WARN, "uart int rx: busy\n"); return -1; } puart_adapter->pRxBuf = (uint8_t*)prxbuf; puart_adapter->RxCount = len; UART_SetRxFlag(obj->uart_idx, STATERX_INT); // Could be the RX FIFO has some data already TransCnt = UART_ReceiveDataTO(UARTx, puart_adapter->pRxBuf, puart_adapter->RxCount, 1); puart_adapter->RxCount -= TransCnt; puart_adapter->pRxBuf += TransCnt; if (puart_adapter->RxCount == 0) { uart_intrecv_complete(puart_adapter); return len; } else { // Enable RX Interrupt UART_INTConfig(UARTx, RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI, ENABLE); } if (puart_adapter->RxCount > 0) { task_yield = (void (*)(void))force_cs; while (1) { /* complete */ if (UART_GetRxFlag(obj->uart_idx) != STATERX_INT) { break; } /* time out */ if (SYSTIMER_GetPassTime(startcount) > timeout_ms) { serial_recv_stream_abort(obj); } if (NULL != task_yield) { task_yield(); } } } return (len - puart_adapter->RxCount); } /** * @brief recv data use DMA mode with hardware timeout and uart is flow controller. * @param obj: uart object define in application software. * @param prxbuf: buffer to save data read from UART FIFO. * @param len: not use, reserved for compatibility. * @param timeout_ms: hardware timeout for rx. * @param force_cs: not use, reserved for compatibility,it should be NULL. * @retval HAL_Status * @note this function is asynchronous API. */ int32_t serial_recv_stream_dma_timeout(serial_t *obj, char *prxbuf, uint32_t len, uint32_t timeout_ms, void *force_cs) { /* To avoid gcc warnings */ ( void ) force_cs; ( void ) len; PMBED_UART_ADAPTER puart_adapter=&(uart_adapter[obj->uart_idx]); HAL_Status ret = HAL_OK; u32 ret1; u32 timeout_count; timeout_count=timeout_ms*current_baudrate/1000; assert_param(prxbuf != NULL); assert_param(timeout_count>=64&&timeout_count<65536); if (UART_GetRxFlag(puart_adapter->UartIndex)) { DBG_PRINTF(MODULE_UART, LEVEL_WARN, "uart dma rx: busy\n"); return HAL_BUSY; } puart_adapter->pRxBuf = (uint8_t*)prxbuf; puart_adapter->last_dma_addr = (u32)prxbuf; if(0!=timeout_count){ int regval=puart_adapter->UARTx->RX_PATH; regval=(timeout_count<<16)|(0xffff&regval); puart_adapter->UARTx->RX_PATH=regval; } UART_SetRxFlag(puart_adapter->UartIndex, STATERX_DMA); // Disable Rx interrupt UART_INTConfig(puart_adapter->UARTx, (RUART_IER_ERBI | RUART_IER_ELSI | RUART_IER_ETOI), DISABLE); UART_RXDMAConfig(puart_adapter->UARTx, 4); UART_RXDMACmd(puart_adapter->UARTx, ENABLE); ret1 = UART_RXGDMA_Init(puart_adapter->UartIndex, &puart_adapter->UARTRxGdmaInitStruct, puart_adapter, uart_dmarecv_irqhandler, puart_adapter->pRxBuf, 0); NVIC_SetPriority(GDMA_GetIrqNum(0, puart_adapter->UARTRxGdmaInitStruct.GDMA_ChNum), 12); if ((serial_dma_en[obj->uart_idx] & SERIAL_RX_DMA_EN)==0) { if(ret1 == _TRUE) { serial_dma_en[obj->uart_idx] |= SERIAL_RX_DMA_EN; } else { return HAL_BUSY; } } return (ret); } /** * @brief set uart rx fifo trigger level. * @param obj: uart object define in application software. * @param FifoLv: FIFO level enum index. * @retval none */ void serial_rx_fifo_level(serial_t *obj, SerialFifoLevel FifoLv) { UART_TypeDef* UARTx = UART_DEV_TABLE[obj->uart_idx].UARTx; u32 Temp; switch(FifoLv) { case FifoLv1Byte: Temp = UART_RX_FIFOTRIG_LEVEL_1BYTES; break; case FifoLvQuarter: Temp = UART_RX_FIFOTRIG_LEVEL_4BYTES; break; case FifoLvHalf: Temp = UART_RX_FIFOTRIG_LEVEL_8BYTES; break; case FifoLvFull: Temp = UART_RX_FIFOTRIG_LEVEL_14BYTES; break; default: assert_param(0); break; } /*set rx fifo level*/ UART_SetRxLevel(UARTx, Temp); } /** * @brief uart autoflow control setting. * @param obj: uart object define in application software. * @param type: autoflow control type. * @param rxflow: RTS pin. * @param txflow: CTS pin. * @retval none */ void serial_set_flow_control(serial_t *obj, FlowControl type, PinName rxflow, PinName txflow) { /* To avoid gcc warnings */ ( void ) txflow; UART_TypeDef* UARTx = UART_DEV_TABLE[obj->uart_idx].UARTx; u32 Temp; /*autoflow control configuration*/ if(type != FlowControlNone) { /*config UART0 pinmux*/ if(rxflow == PA_14) { /*KM0 UART "S0" */ Pinmux_Config(_PA_14, PINMUX_FUNCTION_UART_RTSCTS); /*RTS*/ Pinmux_Config(_PA_15, PINMUX_FUNCTION_UART_RTSCTS); /*CTS*/ } else if (rxflow == PA_16) { /*KM4 UART "S0" */ Pinmux_Config(_PA_16, PINMUX_FUNCTION_UART_RTSCTS); /*RTS*/ Pinmux_Config(_PA_17, PINMUX_FUNCTION_UART_RTSCTS); /*CTS*/ } else if (rxflow == PA_27) { /*if using PA27, SWD should be closed first*/ Temp = HAL_READ32(SYSTEM_CTRL_BASE_HP, REG_SWD_PMUX_EN); Temp &= (~BIT_LSYS_SWD_PMUX_EN); HAL_WRITE32(SYSTEM_CTRL_BASE_HP, REG_SWD_PMUX_EN, Temp); Temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_SWD_PMUX_EN); Temp &= (~BIT_LSYS_SWD_PMUX_EN); HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_SWD_PMUX_EN, Temp); /*KM0 UART "S1" */ Pinmux_Config(_PA_27, PINMUX_FUNCTION_UART_RTSCTS); /*RTS*/ Pinmux_Config(_PA_28, PINMUX_FUNCTION_UART_RTSCTS); /*CTS*/ } else if (rxflow == PA_10) { /*KM4 UART "S1" */ Pinmux_Config(_PA_23, PINMUX_FUNCTION_UART_RTSCTS); /*RTS*/ Pinmux_Config(_PA_24, PINMUX_FUNCTION_UART_RTSCTS); /*CTS*/ } else if (rxflow == PB_11) { /*KM4 UART "S2" */ Pinmux_Config(_PB_11, PINMUX_FUNCTION_UART_RTSCTS); /*RTS*/ Pinmux_Config(_PB_10, PINMUX_FUNCTION_UART_RTSCTS); /*CTS*/ } else if (rxflow == PB_21) { /*KM4 UART "S3" */ Pinmux_Config(_PB_21, PINMUX_FUNCTION_UART_RTSCTS); /*RTS*/ Pinmux_Config(_PB_20, PINMUX_FUNCTION_UART_RTSCTS); /*CTS*/ } else { assert_param(0); } /*enable auto flow control*/ UARTx->MCR |= BIT(5); } else { /*disable auto flow control*/ UARTx->MCR &= ~ BIT(5); } /*no matter auto flow control is enabled or disabled, RTS pin should be always Low, and thus peer can send data*/ UARTx->MCR |= BIT(1); } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/serial_api.c
C
apache-2.0
42,611
/** mbed Microcontroller Library ****************************************************************************** * @file sleep.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for SLEEP. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "sleep_ex_api.h" #include "cmsis.h" /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_SLEEP * @brief MBED_SLEEP driver modules. * @{ */ /** @defgroup MBED_SLEEP_Exported_Functions MBED_SLEEP Exported Functions * @{ */ /** * @brief AmebaD don't support sleep api, please refer to AN400 power save Section */ void sleep_ex(uint32_t wakeup_event, uint32_t sleep_duration) { /* To avoid gcc warnings */ ( void ) wakeup_event; ( void ) sleep_duration; assert_param(0); } /** * @brief AmebaD don't support sleep api, please refer to AN400 power save Section */ void sleep_ex_selective(uint32_t wakeup_event, uint32_t sleep_duration, uint32_t clk_sourec_enable, uint32_t sdr_enable) { /* To avoid gcc warnings */ ( void ) wakeup_event; ( void ) sleep_duration; ( void ) clk_sourec_enable; ( void ) sdr_enable; assert_param(0); } /** * @brief AmebaD don't support deep sleep api, please refer to AN400 power save Section */ void deepsleep_ex(uint32_t wakeup_event, uint32_t sleep_duration) { /* To avoid gcc warnings */ ( void ) wakeup_event; ( void ) sleep_duration; assert_param(0); } /** * @brief AmebaD don't support deep sleep api, please refer to AN400 power save Section */ int deepsleep_get_bootup_reason(void) { assert_param(0); return 0; } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/sleep.c
C
apache-2.0
2,132
#include "FreeRTOS.h" #include "ameba_soc.h" #include "spdio_api.h" #include "rtl8721d_inic.h" /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_SPDIO * @brief MBED_SPDIO driver modules. * @{ */ /** @defgroup MBED_SPDIO_Exported_Types MBED_SPDIO Exported Types * @{ */ #define SPDIO_IRQ_PRIORITY 5 #define SPDIO_TX_BUF_SZ_UNIT 64 #define RX_BD_FREE_TH 5 #define MIN_RX_BD_SEND_PKT 2 #define MAX_RX_BD_BUF_SIZE 16380 // the Maximum size for a RX_BD point to, make it 4-bytes aligned typedef struct { u32 Address; /* The TX buffer physical address, it must be 4-bytes aligned */ }SPDIO_TX_BD; /* The RX Buffer Descriptor format */ typedef struct { u32 BuffSize:14; /* bit[13:0], RX Buffer Size, Maximum 16384-1 */ u32 LS:1; /* bit[14], is the Last Segment ? */ u32 FS:1; /* bit[15], is the First Segment ? */ u32 Seq:16; /* bit[31:16], The sequence number, it's no use for now */ u32 PhyAddr; /* The RX buffer physical address, it must be 4-bytes aligned */ } SPDIO_RX_BD; /* the data structer to bind a TX_BD with a TX Packet */ typedef struct { SPDIO_TX_BD *pTXBD; // Point to the TX_BD buffer VOID *priv; u8 isPktEnd; // For a packet over 1 BD , this flag to indicate is this BD contains a packet end u8 isFree; // is this TX BD free } SPDIO_TX_BD_HANDLE; /* the data structer to bind a RX_BD with a RX Packet */ typedef struct { VOID *priv; SPDIO_RX_BD *pRXBD; // Point to the RX_BD buffer INIC_RX_DESC *pRXDESC; // point to the Rx Packet u8 isPktEnd; // For a packet over 1 BD , this flag to indicate is this BD contains a packet end u8 isFree; // is this RX BD free (DMA done and its RX packet has been freed) } SPDIO_RX_BD_HANDLE; typedef struct { VOID *spdio_priv; /*Data from User*/ u8 *pTXBDAddr; /* The TX_BD start address */ SPDIO_TX_BD *pTXBDAddrAligned; /* The TX_BD start address, it must be 4-bytes aligned */ SPDIO_TX_BD_HANDLE* pTXBDHdl; /* point to the allocated memory for TX_BD Handle array */ u16 TXBDWPtr; /* The SDIO TX(Host->Device) BD local write index, different with HW maintained write Index. */ u16 TXBDRPtr; /* The SDIO TX(Host->Device) BD read index */ u16 TXBDRPtrReg; /* The SDIO TX(Host->Device) BD read index has been write to HW register */ u8 TxOverFlow; u8 *pRXBDAddr; /* The RX_BD start address */ SPDIO_RX_BD *pRXBDAddrAligned; /* The RX_BD start address, it must be 8-bytes aligned */ u8 *pRXDESCAddr; INIC_RX_DESC *pRXDESCAddrAligned; SPDIO_RX_BD_HANDLE* pRXBDHdl; /* point to the allocated memory for RX_BD Handle array */ u16 RXBDWPtr; /* The SDIO RX(Device->Host) BD write index */ u16 RXBDRPtr; /* The SDIO RX(Device->Host) BD local read index, different with HW maintained Read Index. */ _sema IrqSema; /* Semaphore for SDIO RX, use to wakeup the SDIO RX task */ xTaskHandle xSDIOIrqTaskHandle; /* The handle of the SDIO Task speical for RX, can be used to delte the task */ } HAL_SPDIO_ADAPTER, *PHAL_SPDIO_ADAPTER; struct spdio_t *g_spdio_priv = NULL; HAL_SPDIO_ADAPTER gSPDIODev; PHAL_SPDIO_ADAPTER pgSPDIODev = NULL; /** * @} */ /** @defgroup MBED_SPDIO_Exported_Functions MBED_SPDIO Exported Functions * @{ */ s8 spdio_rx_done_cb(void *padapter, void *data, u16 offset, u16 pktsize, u8 type) { struct spdio_buf_t *buf = (struct spdio_buf_t *)data; struct spdio_t *obj = (struct spdio_t *)padapter; if(obj) return obj->rx_done_cb(obj, buf, (u8 *)(buf->buf_addr+offset), pktsize, type); else DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "spdio rx done callback function is null!"); return SUCCESS; } s8 spdio_tx_done_cb(void *padapter, IN u8 *data) { struct spdio_t *obj = (struct spdio_t *)padapter; struct spdio_buf_t *buf = (struct spdio_buf_t *)data; if(obj) return obj->tx_done_cb(obj, buf); else DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "spdio tx done callback function is null!"); return SUCCESS; } s8 spdio_tx(struct spdio_t *obj, struct spdio_buf_t *pbuf) { PHAL_SPDIO_ADAPTER pgSDIODev = obj->priv; INIC_RX_DESC *pRxDesc; SPDIO_RX_BD_HANDLE *pRxBdHdl; SPDIO_RX_BD *pRXBD; u32 Offset=0; u16 RxBdWrite=0; // to count how much RX_BD used in a Transaction u16 RxBdRdPtr= pgSDIODev->RXBDRPtr; // RX_BD read pointer u32 pkt_size; #if defined(SDIO_RX_PKT_SIZE_OVER_16K) && SDIO_RX_PKT_SIZE_OVER_16K u8 needed_rxbd_num; #endif /* check if RX_BD available */ #if defined(SDIO_RX_PKT_SIZE_OVER_16K) && SDIO_RX_PKT_SIZE_OVER_16K needed_rxbd_num = ((pbuf->buf_size - 1)/MAX_RX_BD_BUF_SIZE) + MIN_RX_BD_SEND_PKT; #endif if (RxBdRdPtr != pgSDIODev->RXBDWPtr) { if (pgSDIODev->RXBDWPtr > RxBdRdPtr) { #if defined(SDIO_RX_PKT_SIZE_OVER_16K) && SDIO_RX_PKT_SIZE_OVER_16K if ((pgSDIODev->RXBDWPtr - RxBdRdPtr) >= (u16)(obj->tx_bd_num - needed_rxbd_num)) #else if ((pgSDIODev->RXBDWPtr - RxBdRdPtr) >= (u16)(obj->tx_bd_num - (u32)MIN_RX_BD_SEND_PKT)) #endif { DBG_PRINTF(MODULE_SDIO, LEVEL_WARN, "SDIO_Return_Rx_Data: No Available RX_BD, ReadPtr=%d WritePtr=%d\n", \ RxBdRdPtr, pgSDIODev->RXBDWPtr); return _FALSE; } } else { #if defined(SDIO_RX_PKT_SIZE_OVER_16K) && SDIO_RX_PKT_SIZE_OVER_16K if ((RxBdRdPtr - pgSDIODev->RXBDWPtr) <= (u16)needed_rxbd_num) #else if ((RxBdRdPtr - pgSDIODev->RXBDWPtr) <= (u16)MIN_RX_BD_SEND_PKT) #endif { DBG_PRINTF(MODULE_SDIO, LEVEL_WARN, "SDIO_Return_Rx_Data: No Available RX_BD, ReadPtr=%d WritePtr=%d\n", RxBdRdPtr, pgSDIODev->RXBDWPtr); return _FALSE; } } } // TODO: Add RX_DESC before the packet /* a SDIO RX packet will use at least 2 RX_BD, the 1st one is for RX_Desc, other RX_BDs are for packet payload */ /* Use a RX_BD to transmit RX_Desc */ pRXBD = pgSDIODev->pRXBDAddrAligned + pgSDIODev->RXBDWPtr; // get the RX_BD head pRxBdHdl = pgSDIODev->pRXBDHdl + pgSDIODev->RXBDWPtr; pRxDesc = pRxBdHdl->pRXDESC; pRxDesc->type = pbuf->type; pRxDesc->pkt_len = pbuf->buf_size; pRxDesc->offset = sizeof(INIC_RX_DESC); if (!pRxBdHdl->isFree) { DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "SDIO_Return_Rx_Data: Allocated a non-free RX_BD\n"); } pRxBdHdl->isFree = 0; pRXBD->FS = 1; pRXBD->LS = 0; pRXBD->PhyAddr = (u32)((u8 *)pRxBdHdl->pRXDESC); pRXBD->BuffSize = sizeof(INIC_RX_DESC); pRxBdHdl->isPktEnd = 0; pgSDIODev->RXBDWPtr += 1; if (pgSDIODev->RXBDWPtr >= obj->tx_bd_num) { pgSDIODev->RXBDWPtr -= obj->tx_bd_num; } RxBdWrite++; /* Take RX_BD to transmit packet payload */ pkt_size = pbuf->buf_size; Offset = 0; do { pRXBD = pgSDIODev->pRXBDAddrAligned + pgSDIODev->RXBDWPtr; // get the RX_BD head pRxBdHdl = pgSDIODev->pRXBDHdl + pgSDIODev->RXBDWPtr; pRxBdHdl->isFree = 0; pRXBD->FS = 0; pRXBD->PhyAddr = (u32)((u8 *)pbuf->buf_addr + Offset); #if defined(SDIO_RX_PKT_SIZE_OVER_16K) && SDIO_RX_PKT_SIZE_OVER_16K if ((pkt_size - Offset) <= MAX_RX_BD_BUF_SIZE) { pRXBD->BuffSize = pkt_size - Offset; pRxBdHdl->isPktEnd = 1; }else { pRXBD->BuffSize = MAX_RX_BD_BUF_SIZE; pRxBdHdl->isPktEnd = 0; DBG_PRINTF(MODULE_SDIO, LEVEL_INFO, "SDIO_Return_Rx_Data: Split RX_BD, Offset=%d PktSize=%d\n", \ Offset, pkt_size); } #else if (pkt_size > MAX_RX_BD_BUF_SIZE) { // if come to here, please enable "SDIO_RX_PKT_SIZE_OVER_16K" DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "SDIO_Return_Rx_Data: The Packet Size bigger than 16K\n"); pkt_size = MAX_RX_BD_BUF_SIZE; } pRXBD->BuffSize = pkt_size; pRxBdHdl->priv = (void*)pbuf; pRxBdHdl->isPktEnd = 1; #endif Offset += pRXBD->BuffSize; // Move the RX_BD Write pointer forward RxBdWrite++; pgSDIODev->RXBDWPtr += 1; if (pgSDIODev->RXBDWPtr >= obj->tx_bd_num) { pgSDIODev->RXBDWPtr -= obj->tx_bd_num; } if (Offset >= pkt_size) { pRXBD->LS = 1; } } while (Offset < pkt_size); if (RxBdWrite > 0) { SDIO_RXBD_WPTR_Set(pgSDIODev->RXBDWPtr); HAL_SDIO_WRITE8(REG_SPDIO_HCI_RX_REQ, BIT_HCI_RX_REQ); } DBG_PRINTF(MODULE_SDIO, LEVEL_INFO, "SDIO_Return_Rx_Data(%d)<==\n", RxBdWrite); return _TRUE; } void spdio_structinit(struct spdio_t *obj){ obj->rx_bd_bufsz = SPDIO_RX_BUFSZ_ALIGN(2048+24); //extra 24 bytes for sdio header obj->rx_bd_num = 24; obj->tx_bd_num = 24; obj->priv = NULL; obj->rx_buf = NULL; obj->rx_done_cb = NULL; obj->tx_done_cb = NULL; } /****************************************************************************** * Function: SDIO_TX_FIFO_DataReady * Desc: Handle the SDIO FIFO data ready interrupt. * 1. Send those data to the target driver via callback fun., like WLan. * 2. Allocate a buffer for the TX BD * * Para: * pSDIODev: The SDIO device data structor. ******************************************************************************/ VOID SPDIO_TX_FIFO_DataReady(IN PHAL_SPDIO_ADAPTER pSPDIODev) { SPDIO_TX_BD_HANDLE* pTxBdHdl; PINIC_TX_DESC pTxDesc; volatile u16 TxBDWPtr=0; u8 isForceBreak=0; s8 ret=FAIL; u32 reg; SPDIO_TX_BD *pTXBD = NULL; struct spdio_t *obj = (struct spdio_t *)pSPDIODev->spdio_priv; TxBDWPtr = SDIO_TXBD_WPTR_Get(); if (TxBDWPtr == pSPDIODev->TXBDRPtr) { if (unlikely(pSPDIODev->TxOverFlow != 0)) { pSPDIODev->TxOverFlow = 0; reg = HAL_SDIO_READ32(REG_SPDIO_AHB_DMA_CTRL); DBG_PRINTF(MODULE_SDIO, LEVEL_WARN, "SDIO TX Overflow Case: Reg DMA_CTRL==0x%x %x %x %x\n", (reg>> 24)&0xff , (reg>>16)&0xff, (reg>>8)&0xff, (reg)&0xff); } else { DBG_PRINTF(MODULE_SDIO, LEVEL_WARN, "SDIO TX Data Read False Triggered!!, TXBDWPtr=0x%x\n", TxBDWPtr); return; } } do { DBG_PRINTF(MODULE_SDIO, LEVEL_INFO, "SDIO_TX_DataReady: TxBDWPtr=%d TxBDRPtr=%d\n", TxBDWPtr, pSPDIODev->TXBDRPtr); pTXBD= (SPDIO_TX_BD*)(pSPDIODev->pTXBDAddrAligned + pSPDIODev->TXBDRPtr); pTxBdHdl = pSPDIODev->pTXBDHdl + pSPDIODev->TXBDRPtr; pTxDesc = (PINIC_TX_DESC)(pTXBD->Address); DBG_PRINTF(MODULE_SDIO, LEVEL_INFO, "SDIO_TX_DataReady: PktSz=%d Offset=%d\n", pTxDesc->txpktsize, pTxDesc->offset); if ((pTxDesc->txpktsize + pTxDesc->offset) <= obj->rx_bd_bufsz) { // use the callback function to fordward this packet to target(WLan) driver ret = spdio_rx_done_cb(obj, (u8*)pTxBdHdl->priv, pTxDesc->offset, pTxDesc->txpktsize, pTxDesc->type); if(ret == FAIL) DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "SDIO TX_Callback is Null!\n"); pTXBD->Address = obj->rx_buf[pSPDIODev->TXBDRPtr].buf_addr; } else { // Invalid packet, Just drop it ret = SUCCESS; // pretend we call the TX callback OK } if (SUCCESS != ret) { // may be is caused by TX queue is full, so we skip it and try again later isForceBreak = 1; break; // break the while loop } else { pSPDIODev->TXBDRPtr++; if (pSPDIODev->TXBDRPtr >= obj->rx_bd_num) { pSPDIODev->TXBDRPtr = 0; } pSPDIODev->TXBDRPtrReg = pSPDIODev->TXBDRPtr; SDIO_TXBD_RPTR_Set(pSPDIODev->TXBDRPtrReg); } TxBDWPtr = SDIO_TXBD_WPTR_Get(); if (isForceBreak) { break; // break the TX FIFO DMA Done processing } } while (pSPDIODev->TXBDRPtr != TxBDWPtr); // if not all TX data were processed, set an event to trigger SDIO_Task to process them later if (isForceBreak) { DBG_PRINTF(MODULE_SDIO, LEVEL_WARN, "SDIO_TX Force Break: TXBDWP=0x%x TXBDRP=0x%x\n", TxBDWPtr, pSPDIODev->TXBDRPtr); } } VOID SPDIO_Recycle_Rx_BD (IN PHAL_SPDIO_ADAPTER pgSPDIODev) { SPDIO_RX_BD_HANDLE *pRxBdHdl; SPDIO_RX_BD *pRXBD; u32 FreeCnt=0; // for debugging struct spdio_t *obj = (struct spdio_t *)pgSPDIODev->spdio_priv; SDIO_INTConfig(BIT_C2H_DMA_OK, DISABLE); while (SDIO_RXBD_RPTR_Get() != pgSPDIODev->RXBDRPtr) { pRxBdHdl = pgSPDIODev->pRXBDHdl + pgSPDIODev->RXBDRPtr; pRXBD = pRxBdHdl->pRXBD; if (!pRxBdHdl->isFree) { if(pRxBdHdl->isPktEnd){ spdio_tx_done_cb(obj, (u8*)(pRxBdHdl->priv)); } pRxBdHdl->isPktEnd = 0; _memset((void *)(pRxBdHdl->pRXDESC), 0, sizeof(INIC_RX_DESC)); _memset((void *)pRXBD , 0, sizeof(SPDIO_RX_BD)); // clean this RX_BD pRxBdHdl->isFree = 1; } else { DBG_PRINTF(MODULE_SDIO, LEVEL_WARN, "SDIO_Recycle_Rx_BD: Warring, Recycle a Free RX_BD,RXBDRPtr=%d\n",pgSPDIODev->RXBDRPtr); } pgSPDIODev->RXBDRPtr++; if (pgSPDIODev->RXBDRPtr >= obj->tx_bd_num) { pgSPDIODev->RXBDRPtr -= obj->tx_bd_num; } } SDIO_INTConfig(BIT_C2H_DMA_OK, ENABLE); DBG_PRINTF(MODULE_SDIO, LEVEL_INFO, "<==SDIO_Recycle_Rx_BD(%d)\n", FreeCnt); } /****************************************************************************** * Function: SPDIO_IRQ_Handler * Desc: SPDIO device interrupt service routine * 1. Read & clean the interrupt status * 2. Wake up the SDIO task to handle the IRQ event * * Para: * pSDIODev: The SDIO device data structor. ******************************************************************************/ VOID SPDIO_IRQ_Handler(VOID *pData) { PHAL_SPDIO_ADAPTER pSPDIODev = pData; InterruptDis(SDIO_DEVICE_IRQ); rtw_up_sema_from_isr(&pSPDIODev->IrqSema); } VOID SPDIO_IRQ_Handler_BH(VOID *pData) { PHAL_SPDIO_ADAPTER pgSPDIODev = pData; u16 IntStatus; for (;;) { /* Task blocked and wait the semaphore(events) here */ rtw_down_sema(&pgSPDIODev->IrqSema); IntStatus = HAL_SDIO_READ16(REG_SPDIO_CPU_INT_STAS); DBG_PRINTF(MODULE_SDIO, LEVEL_INFO, "%s:ISRStatus=0x%x\n", __FUNCTION__, IntStatus); HAL_SDIO_WRITE16(REG_SPDIO_CPU_INT_STAS, IntStatus); // clean the ISR InterruptEn(SDIO_DEVICE_IRQ, SPDIO_IRQ_PRIORITY); if (IntStatus & BIT_C2H_DMA_OK) { SPDIO_Recycle_Rx_BD(pgSPDIODev); } if (IntStatus & BIT_H2C_MSG_INT) { HAL_SDIO_READ32(REG_SPDIO_CPU_H2C_MSG); } if (IntStatus & BIT_H2C_DMA_OK) { SDIO_INTConfig(BIT_H2C_DMA_OK, DISABLE); SPDIO_TX_FIFO_DataReady(pgSPDIODev); SDIO_INTConfig(BIT_H2C_DMA_OK, ENABLE); } if (IntStatus & BIT_TXFIFO_H2C_OVF) { pgSPDIODev->TxOverFlow = 1; } DBG_PRINTF(MODULE_SDIO, LEVEL_INFO, "%s @2 IntStatus=0x%x\n", __FUNCTION__, IntStatus); } #if 0 SDIO_SetEvent(pgSPDIODev, (u32)SDIO_EVENT_IRQ_STOPPED); DBG_PRINTF(MODULE_SDIO, LEVEL_INFO, "SDIO irq Task Stopped!\n"); #if ( INCLUDE_vTaskDelete == 1 ) vTaskDelete(NULL); #endif #endif } /****************************************************************************** * Function: SPDIO_Device_Init * Desc: SDIO mbed device driver initialization. * 1. Allocate SDIO TX BD and RX BD adn RX Desc. * 2. Allocate SDIO RX Buffer Descriptor and RX Buffer. Initial RX related * register. * 3. Register the Interrupt function. * ******************************************************************************/ BOOL SPDIO_Device_Init(struct spdio_t * obj) { u32 i; SPDIO_TX_BD_HANDLE *pTxBdHdl; SPDIO_RX_BD_HANDLE *pRxBdHdl; int ret; //SPDIO_TX_BD *pTXBD = NULL; SDIO_InitTypeDef SDIO_InitStruct; u32 Temp = 0; if(obj == NULL){ DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "struct spdio_t must be inited\n"); return FAIL; } DBG_PRINTF(MODULE_SDIO, LEVEL_INFO, "SDIO_Device_Init==>\n"); pgSPDIODev = &gSPDIODev; pgSPDIODev->spdio_priv = (void*)obj; obj->priv = (void *)pgSPDIODev; // initial TX BD and RX BD pgSPDIODev->pTXBDAddr = _rtw_malloc((obj->rx_bd_num* sizeof(SPDIO_TX_BD))+3); if (NULL == pgSPDIODev->pTXBDAddr) { DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "SDIO_Device_Init: Malloc for TX_BD Err!!\n"); goto SDIO_INIT_ERR; } pgSPDIODev->pTXBDAddrAligned = (SPDIO_TX_BD*)(((((u32)pgSPDIODev->pTXBDAddr - 1) >> 2) + 1) << 2); // Make it 4-bytes aligned pgSPDIODev->pRXBDAddr = _rtw_malloc((obj->tx_bd_num * sizeof(SPDIO_RX_BD))+7); if (NULL == pgSPDIODev->pRXBDAddr) { DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "SDIO_Device_Init: Malloc for RX_BD Err!!\n"); goto SDIO_INIT_ERR; } pgSPDIODev->pRXBDAddrAligned = (SPDIO_RX_BD*)(((((u32)pgSPDIODev->pRXBDAddr - 1) >> 3) + 1) << 3); // Make it 8-bytes aligned pgSPDIODev->pRXDESCAddr = _rtw_zmalloc((obj->tx_bd_num * sizeof(INIC_RX_DESC)) + 3); if (NULL == pgSPDIODev->pRXDESCAddr) { DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "SDIO_Device_Init: Malloc for RX_DESC Err!!\n"); goto SDIO_INIT_ERR; } pgSPDIODev->pRXDESCAddrAligned = (INIC_RX_DESC*)(((((u32)pgSPDIODev->pRXDESCAddr - 1) >> 2) + 1) << 2); //Make it 4-bytes aligned // Clean boot from wakeup bit // SOCPS_BootFromPS(DISABLE); /* SDIO Function & CLock Enable */ RCC_PeriphClockCmd(APBPeriph_SDIOD, APBPeriph_SDIOD_CLOCK, ENABLE); Temp = HAL_READ32(SYSTEM_CTRL_BASE, REG_HS_SDIO_CTRL); Temp |= BIT_HS_SDIOD_PIN_EN; HAL_WRITE32(SYSTEM_CTRL_BASE, REG_HS_SDIO_CTRL, Temp); Temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LP_EFUSE_CTRL1); Temp |= BIT_SYS_EF_ALDEN; HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_EFUSE_CTRL1, Temp); // SDIO_SCLK / SPI_CLK pin pull-low //PAD_PullCtrl(_PA_3, GPIO_PuPd_DOWN); SDIO_StructInit(&SDIO_InitStruct); SDIO_InitStruct.TXBD_BAR = (u32)pgSPDIODev->pTXBDAddrAligned; SDIO_InitStruct.TXBD_RING_SIZE = obj->rx_bd_num; //SDIO_TX_BD_NUM; SDIO_InitStruct.TX_BUFFER_SIZE = ((((obj->rx_bd_bufsz-1)/SPDIO_TX_BUF_SZ_UNIT)+1)&0xff); SDIO_InitStruct.RXBD_BAR = (u32)pgSPDIODev->pRXBDAddrAligned; SDIO_InitStruct.RXBD_RING_SIZE = obj->tx_bd_num; SDIO_InitStruct.RXBD_FREE_TH = RX_BD_FREE_TH; SDIO_Init((&SDIO_InitStruct)); pgSPDIODev->TXBDWPtr = SDIO_TXBD_WPTR_Get(); pgSPDIODev->TXBDRPtr = pgSPDIODev->TXBDWPtr; pgSPDIODev->TXBDRPtrReg = pgSPDIODev->TXBDWPtr; pgSPDIODev->RXBDWPtr = pgSPDIODev->RXBDRPtr = SDIO_RXBD_RPTR_Get(); DBG_PRINTF(MODULE_SDIO, LEVEL_INFO, "TXBDWPtr=0x%x TXBDRPtr=0x%x\n", pgSPDIODev->TXBDWPtr, pgSPDIODev->TXBDRPtr); pgSPDIODev->pTXBDHdl = (SPDIO_TX_BD_HANDLE*)_rtw_zmalloc(obj->rx_bd_num * sizeof(SPDIO_TX_BD_HANDLE)); if (NULL == pgSPDIODev->pTXBDHdl) { DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "SDIO_Device_Init: Malloc for TX_BD Handle Err!!\n"); goto SDIO_INIT_ERR; } for(i=0;i<obj->rx_bd_num;i++){ pTxBdHdl = pgSPDIODev->pTXBDHdl + i; pTxBdHdl->pTXBD= pgSPDIODev->pTXBDAddrAligned + i; // Pre-allocate buffer by User pTxBdHdl->priv = (void *)&obj->rx_buf[i]; pTxBdHdl->pTXBD->Address = (u32)obj->rx_buf[i].buf_addr; if(pTxBdHdl->pTXBD->Address%4){ DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "buffer address must be aligned to 4!!\n"); goto SDIO_INIT_ERR; } if (NULL == (u32*)(pTxBdHdl->pTXBD->Address)) { DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "SDIO_Device_Init: Malloc buffer for TX_BD Err!!\n"); goto SDIO_INIT_ERR; } pTxBdHdl->isFree = 1; DBG_PRINTF(MODULE_SDIO, LEVEL_INFO, "TX_BD%d @ 0x%x 0x%x\n", i, pTxBdHdl, pTxBdHdl->pTXBD); } pgSPDIODev->pRXBDHdl = (SPDIO_RX_BD_HANDLE*)_rtw_zmalloc(obj->tx_bd_num * sizeof(SPDIO_RX_BD_HANDLE)); if (NULL == pgSPDIODev->pRXBDHdl) { DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "SDIO_Device_Init: Malloc for RX_BD Handle Err!!\n"); goto SDIO_INIT_ERR; } for (i=0; i<obj->tx_bd_num; i++) { pRxBdHdl = pgSPDIODev->pRXBDHdl + i; pRxBdHdl->pRXBD = pgSPDIODev->pRXBDAddrAligned + i; pRxBdHdl->pRXDESC = pgSPDIODev->pRXDESCAddrAligned + i; pRxBdHdl->isFree = 1; } rtw_init_sema(&(pgSPDIODev->IrqSema), 0); if (NULL == pgSPDIODev->IrqSema){ DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "SDIO_Device_Init Create IRQ Semaphore Err!!\n"); goto SDIO_INIT_ERR; } ret = xTaskCreate( SPDIO_IRQ_Handler_BH, "SPDIO_IRQ_TASK", ((1024*1)/sizeof(portBASE_TYPE)), (void *)pgSPDIODev, 1 + PRIORITIE_OFFSET, &pgSPDIODev->xSDIOIrqTaskHandle); if (pdTRUE != ret ) { DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "SDIO_Device_Init: Create IRQ Task Err(%d)!!\n", ret); goto SDIO_INIT_ERR; } //pgSPDIODev->CRPWM = SDIO_RPWM1_Get(); //pgSPDIODev->CRPWM2 = SDIO_RPWM2_Get(); // Indicate Host this is a iNIC FW //SDIO_CPWM2_Set(CPWM2_INIC_FW_RDY_BIT, ENABLE); /* enable the interrupt */ InterruptRegister((IRQ_FUN) SPDIO_IRQ_Handler, SDIO_DEVICE_IRQ, (u32) pgSPDIODev, SPDIO_IRQ_PRIORITY); InterruptEn(SDIO_DEVICE_IRQ, SPDIO_IRQ_PRIORITY); HAL_SDIO_WRITE16(REG_SPDIO_CPU_INT_STAS, SDIO_INIT_INT_MASK); // Clean pending interrupt first HAL_SDIO_WRITE16(REG_SPDIO_CPU_INT_MASK, SDIO_INIT_INT_MASK); // Update the power state indication SDIO_CPWM2_Set(CPWM2_ACT_BIT, ENABLE); /* Indicate the Host system that the TX/RX is ready */ HAL_SDIO_WRITE8(REG_SPDIO_CPU_IND, \ HAL_SDIO_READ8(REG_SPDIO_CPU_IND)|BIT_SYSTEM_TRX_RDY_IND); DBG_PRINTF(MODULE_SDIO, LEVEL_INFO, "<==SDIO_Device_Init\n"); return SUCCESS; SDIO_INIT_ERR: if (pgSPDIODev->pRXBDHdl) { _rtw_mfree((u8 *)pgSPDIODev->pRXBDHdl, obj->tx_bd_num * sizeof(SPDIO_RX_BD_HANDLE)); pgSPDIODev->pRXBDHdl = NULL; } if ((pgSPDIODev->pTXBDHdl)) { for (i=0;i<obj->rx_bd_num;i++){ pTxBdHdl = pgSPDIODev->pTXBDHdl + i; if (pTxBdHdl->pTXBD->Address) { pTxBdHdl->pTXBD->Address = (u32)NULL; } } _rtw_mfree((u8 *)pgSPDIODev->pTXBDHdl, (obj->rx_bd_num * sizeof(SPDIO_TX_BD_HANDLE))); pgSPDIODev->pTXBDHdl = NULL; } if (pgSPDIODev->pRXBDAddr) { _rtw_mfree((u8 *)pgSPDIODev->pRXBDAddr, (obj->tx_bd_num * sizeof(SPDIO_RX_BD))+7); pgSPDIODev->pRXBDAddr = NULL; } if (pgSPDIODev->pTXBDAddr) { _rtw_mfree(pgSPDIODev->pTXBDAddr, ((obj->rx_bd_num * sizeof(SPDIO_TX_BD))+3)); pgSPDIODev->pTXBDAddr = NULL; pgSPDIODev->pTXBDAddrAligned = NULL; } if (pgSPDIODev->pRXDESCAddr) { _rtw_mfree(pgSPDIODev->pRXDESCAddr, (((obj->rx_bd_num)* sizeof(INIC_RX_DESC)) + 3)); pgSPDIODev->pRXDESCAddr = NULL; pgSPDIODev->pRXDESCAddrAligned = NULL; } return FAIL; } /****************************************************************************** * Function: SPDIO_Device_DeInit * Desc: SDIO device driver free resource. This function should be called in * a task. * 1. Free TX FIFO buffer * * Para: * pSDIODev: The SDIO device data structor. ******************************************************************************/ //TODO: Call this function in a task VOID SPDIO_Device_DeInit(VOID) { u32 i=0; SPDIO_TX_BD_HANDLE *pTxBdHdl; SPDIO_TX_BD *pTXBD = NULL; struct spdio_t * obj; if (NULL == pgSPDIODev) return; obj = pgSPDIODev->spdio_priv; // Indicate the Host that Ameba is InActived SDIO_CPWM2_Set(CPWM2_ACT_BIT, DISABLE); if (pgSPDIODev->pRXBDHdl) { _rtw_mfree((u8 *)pgSPDIODev->pRXBDHdl, obj->tx_bd_num * sizeof(SPDIO_RX_BD_HANDLE)); pgSPDIODev->pRXBDHdl = NULL; } /* Free TX FIFO Buffer */ for (i=0;i<obj->rx_bd_num;i++) { pTXBD = (SPDIO_TX_BD*)(pgSPDIODev->pTXBDAddrAligned + i); pTxBdHdl = pgSPDIODev->pTXBDHdl + i; if (pTXBD->Address) { pTXBD->Address = (u32)NULL; } } if ((pgSPDIODev->pTXBDHdl)) { for (i=0;i<obj->rx_bd_num;i++){ pTxBdHdl = pgSPDIODev->pTXBDHdl + i; if (pTxBdHdl->pTXBD->Address) { pTxBdHdl->pTXBD->Address = (u32)NULL; } } _rtw_mfree((u8 *)pgSPDIODev->pTXBDHdl, (obj->rx_bd_num * sizeof(SPDIO_TX_BD_HANDLE))); pgSPDIODev->pTXBDHdl = NULL; } if (pgSPDIODev->pRXBDAddr) { _rtw_mfree((u8 *)pgSPDIODev->pRXBDAddr, (obj->tx_bd_num * sizeof(SPDIO_RX_BD))+7); pgSPDIODev->pRXBDAddr = NULL; } if (pgSPDIODev->pTXBDAddr) { _rtw_mfree(pgSPDIODev->pTXBDAddr, ((obj->rx_bd_num * sizeof(SPDIO_TX_BD))+3)); pgSPDIODev->pTXBDAddr = NULL; pgSPDIODev->pTXBDAddrAligned = NULL; } if (pgSPDIODev->pRXDESCAddr) { _rtw_mfree(pgSPDIODev->pRXDESCAddr, (((obj->rx_bd_num)* sizeof(INIC_RX_DESC)) + 3)); pgSPDIODev->pRXDESCAddr = NULL; pgSPDIODev->pRXDESCAddrAligned = NULL; } SDIO_INTConfig(0xffff, DISABLE); HAL_SDIO_WRITE16(REG_SPDIO_CPU_INT_STAS, 0xffff); // Clean pending interrupt first InterruptDis(SDIO_DEVICE_IRQ); InterruptUnRegister(SDIO_DEVICE_IRQ); if (pgSPDIODev->IrqSema) { rtw_free_sema(&pgSPDIODev->IrqSema); pgSPDIODev->IrqSema = NULL; } // Reset SDIO DMA SDIO_DMA_Reset(); #ifdef AMEBAD_TODO /* SDIO_OFF Disable, SDIO will lost if SDIO_ON OFF */ SDIOD_OFF_FCTRL(OFF); #endif } void spdio_init(struct spdio_t *obj) { if(obj == NULL){ DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "spdio obj is NULL, spdio init failed!\n"); return; } if((obj->rx_bd_num == 0) ||(obj->rx_bd_bufsz == 0) || (obj->rx_bd_bufsz%64) ||(obj->tx_bd_num == 0) ||(obj->tx_bd_num%2)||(obj->rx_buf == NULL)) { DBG_PRINTF(MODULE_SDIO, LEVEL_ERROR, "spdio obj resource isn't correctly inited, spdio init failed!\n"); return; } g_spdio_priv = obj; SPDIO_Device_Init(obj); } void spdio_deinit(struct spdio_t *obj) { if(obj == NULL){ SPDIO_API_PRINTK("spdio obj is NULL, spdio deinit failed"); return; } SPDIO_Device_DeInit(); g_spdio_priv = NULL; } /** * @} */ /** * @} */ /** * @} */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/spdio_api.c
C
apache-2.0
24,496
/** mbed Microcontroller Library ****************************************************************************** * @file spi_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for SPI. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "objects.h" #include "spi_api.h" #include "spi_ex_api.h" #include "PinNames.h" #include "pinmap.h" /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_SPI * @brief MBED_SPI driver modules. * @{ */ /** @defgroup MBED_SPI_Exported_Types MBED_SPI Exported Types * @{ */ typedef struct { GDMA_InitTypeDef SSITxGdmaInitStruct; GDMA_InitTypeDef SSIRxGdmaInitStruct; IRQn_Type IrqNum; SPI_TypeDef *spi_dev; void (*RxCompCallback)(void *Para); void *RxCompCbPara; void (*TxCompCallback)(void *Para); void *TxCompCbPara; void (*TxIdleCallback)(void *Para); void *TxIdleCbPara; void *RxData; void *TxData; u32 RxLength; u32 TxLength; u32 Index; u32 Role; /* mbed var */ u32 dma_en; }HAL_SSI_ADAPTOR, *PHAL_SSI_ADAPTOR; HAL_SSI_ADAPTOR ssi_adapter_g[2]; /** * @} */ /** @defgroup MBED_SPI_Exported_Functions MBED_SPI Exported Functions * @{ */ void spi_flush_rx_fifo (spi_t *obj); static void spi_tx_done_callback(VOID *spi_obj) { spi_t *obj = (spi_t *)spi_obj; spi_irq_handler handler; if (obj->state & SPI_STATE_TX_BUSY) { obj->state &= ~SPI_STATE_TX_BUSY; if (obj->irq_handler) { handler = (spi_irq_handler)obj->irq_handler; handler(obj->irq_id, SpiTxIrq); } } } static void spi_rx_done_callback(VOID *spi_obj) { spi_t *obj = (spi_t *)spi_obj; spi_irq_handler handler; obj->state &= ~SPI_STATE_RX_BUSY; if (obj->irq_handler) { handler = (spi_irq_handler)obj->irq_handler; handler(obj->irq_id, SpiRxIrq); } } // Bus Idle: Real TX done, TX FIFO empty and bus shift all data out already void spi_bus_tx_done_callback(VOID *spi_obj) { spi_t *obj = (spi_t *)spi_obj; spi_irq_handler handler; if (obj->bus_tx_done_handler) { handler = (spi_irq_handler)obj->bus_tx_done_handler; handler(obj->bus_tx_done_irq_id, 0); } } /** * @brief Set SPI interrupt bus tx done handler if needed. * @param obj: spi object define in application software. * @param handler: interrupt bus tx done callback function * @param id: interrupt callback parameter * @retval none */ void spi_bus_tx_done_irq_hook(spi_t *obj, spi_irq_handler handler, uint32_t id) { obj->bus_tx_done_handler = (u32)handler; obj->bus_tx_done_irq_id = (u32)id; } static u32 ssi_interrupt(void *Adaptor) { PHAL_SSI_ADAPTOR ssi_adapter = (PHAL_SSI_ADAPTOR) Adaptor; u32 InterruptStatus = SSI_GetIsr(ssi_adapter->spi_dev); u32 DataFrameSize = SSI_GetDataFrameSize(ssi_adapter->spi_dev); SSI_SetIsrClean(ssi_adapter->spi_dev, InterruptStatus); if (InterruptStatus & (BIT_ISR_TXOIS | BIT_ISR_RXUIS | BIT_ISR_RXOIS | BIT_ISR_MSTIS)) { DBG_PRINTF(MODULE_SPI, LEVEL_INFO, "[INT] Tx/Rx Warning %x \n", InterruptStatus); } if ((InterruptStatus & BIT_ISR_RXFIS) ) { u32 TransLen = 0; TransLen = SSI_ReceiveData(ssi_adapter->spi_dev, ssi_adapter->RxData, ssi_adapter->RxLength); ssi_adapter->RxLength -= TransLen; if (DataFrameSize > 8) { // 16~9 bits mode ssi_adapter->RxData = (void*)(((u16*)ssi_adapter->RxData) + TransLen); } else { // 8~4 bits mode ssi_adapter->RxData = (void*)(((u8*)ssi_adapter->RxData) + TransLen); } if (ssi_adapter->RxLength == 0) { SSI_INTConfig(ssi_adapter->spi_dev, (BIT_IMR_RXFIM | BIT_IMR_RXOIM | BIT_IMR_RXUIM), DISABLE); if (ssi_adapter->RxCompCallback != NULL) { ssi_adapter->RxCompCallback(ssi_adapter->RxCompCbPara); } } } if (InterruptStatus & BIT_ISR_TXEIS) { u32 TransLen = 0; volatile u32 bus_busy; u32 i; /* all data complete */ if (ssi_adapter->TxLength == 0) { SSI_INTConfig(ssi_adapter->spi_dev, (BIT_IMR_TXOIM | BIT_IMR_TXEIM), DISABLE); for (i=0;i<1000000;i++) { bus_busy = SSI_Busy(ssi_adapter->spi_dev); if (!bus_busy) { break; // break the for loop } } // If it's not a dummy TX for master read SPI, then call the TX_done callback if (ssi_adapter->TxData != NULL) { if (ssi_adapter->TxIdleCallback != NULL) { ssi_adapter->TxIdleCallback(ssi_adapter->TxIdleCbPara); } } return 0; } TransLen = SSI_SendData(ssi_adapter->spi_dev, ssi_adapter->TxData, ssi_adapter->TxLength, ssi_adapter->Role); ssi_adapter->TxLength -= TransLen; if (ssi_adapter->TxData != NULL) { if (DataFrameSize > 8) { // 16~9 bits mode ssi_adapter->TxData = (void*)(((u16*)ssi_adapter->TxData) + TransLen); } else { // 8~4 bits mode ssi_adapter->TxData = (void*)(((u8*)ssi_adapter->TxData) + TransLen); } } /* all data write into fifo */ if (ssi_adapter->TxLength == 0) { SSI_INTConfig(ssi_adapter->spi_dev, (BIT_IMR_TXOIM), DISABLE); // If it's not a dummy TX for master read SPI, then call the TX_done callback if (ssi_adapter->TxData != NULL) { if (ssi_adapter->TxCompCallback != NULL) { ssi_adapter->TxCompCallback(ssi_adapter->TxCompCbPara); } } } } return 0; } static u32 ssi_int_read(void *Adapter, void *RxData, u32 Length) { PHAL_SSI_ADAPTOR ssi_adapter = (PHAL_SSI_ADAPTOR) Adapter; u32 DataFrameSize = SSI_GetDataFrameSize(ssi_adapter->spi_dev); assert_param(Length != 0); /* As a Slave mode, if the peer(Master) side is power off, the BUSY flag is always on */ if (SSI_Busy(ssi_adapter->spi_dev)) { DBG_PRINTF(MODULE_SPI, LEVEL_WARN, "ssi_int_read: SSI is busy\n"); return _FALSE; } if (DataFrameSize > 8) { /* 16~9 bits mode */ ssi_adapter->RxLength = Length >> 1; // 2 bytes(16 bit) every transfer } else { /* 8~4 bits mode */ ssi_adapter->RxLength = Length; // 1 byte(8 bit) every transfer } ssi_adapter->RxData = RxData; SSI_INTConfig(ssi_adapter->spi_dev, (BIT_IMR_RXFIM | BIT_IMR_RXOIM | BIT_IMR_RXUIM), ENABLE); return _TRUE; } static u32 ssi_int_write(void *Adapter, u8 *pTxData, u32 Length) { PHAL_SSI_ADAPTOR ssi_adapter = (PHAL_SSI_ADAPTOR) Adapter; u32 DataFrameSize = SSI_GetDataFrameSize(ssi_adapter->spi_dev); assert_param(Length != 0); if (DataFrameSize > 8) { /* 16~9 bits mode */ ssi_adapter->TxLength = Length >> 1; // 2 bytes(16 bit) every transfer } else { /* 8~4 bits mode */ ssi_adapter->TxLength = Length; // 1 byte(8 bit) every transfer } ssi_adapter->TxData = (void*)pTxData; SSI_INTConfig(ssi_adapter->spi_dev, (BIT_IMR_TXOIM | BIT_IMR_TXEIM), ENABLE); return _TRUE; } /* GDMA IRQ Handler */ static void ssi_dma_tx_irq(void *Data) { PHAL_SSI_ADAPTOR ssi_adapter = (PHAL_SSI_ADAPTOR) Data; PGDMA_InitTypeDef GDMA_InitStruct; GDMA_InitStruct = &ssi_adapter->SSITxGdmaInitStruct; /* Clear Pending ISR */ GDMA_ClearINT(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); GDMA_Cmd(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, DISABLE); /* Call user TX complete callback */ if (NULL != ssi_adapter->TxCompCallback) { ssi_adapter->TxCompCallback(ssi_adapter->TxCompCbPara); } SSI_SetDmaEnable(ssi_adapter->spi_dev, DISABLE, BIT_SHIFT_DMACR_TDMAE); GDMA_ChnlFree(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); ssi_adapter->dma_en &= ~SPI_DMA_TX_EN; } static void ssi_dma_rx_irq(void *Data) { PHAL_SSI_ADAPTOR ssi_adapter = (PHAL_SSI_ADAPTOR) Data; PGDMA_InitTypeDef GDMA_InitStruct; GDMA_InitStruct = &ssi_adapter->SSIRxGdmaInitStruct; /* Clear Pending ISR */ GDMA_ClearINT(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); GDMA_Cmd(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, DISABLE); /* Set SSI DMA Disable */ SSI_SetDmaEnable(ssi_adapter->spi_dev, DISABLE, BIT_SHIFT_DMACR_RDMAE); /* Call user RX complete callback */ if (NULL != ssi_adapter->RxCompCallback) { ssi_adapter->RxCompCallback(ssi_adapter->RxCompCbPara); } GDMA_ChnlFree(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); ssi_adapter->dma_en &= ~SPI_DMA_RX_EN; } static u32 ssi_dma_send(void *Adapter, u8 *pTxData, u32 Length) { PHAL_SSI_ADAPTOR ssi_adapter = (PHAL_SSI_ADAPTOR) Adapter; u32 ret = _TRUE; assert_param(Length != 0); assert_param(pTxData != NULL); if (ssi_adapter->dma_en & SPI_DMA_TX_EN) { return _FALSE; } ssi_adapter->dma_en |= SPI_DMA_TX_EN; ssi_adapter->TxLength = Length; ssi_adapter->TxData = (void*)pTxData; SSI_SetDmaEnable(ssi_adapter->spi_dev, ENABLE, BIT_SHIFT_DMACR_TDMAE); ret = SSI_TXGDMA_Init(ssi_adapter->Index, &ssi_adapter->SSITxGdmaInitStruct, ssi_adapter, (IRQ_FUN) ssi_dma_tx_irq, pTxData, Length); NVIC_SetPriority(GDMA_GetIrqNum(0, ssi_adapter->SSITxGdmaInitStruct.GDMA_ChNum), 10); return ret; } static u32 ssi_dma_recv(void *Adapter, u8 *pRxData, u32 Length) { PHAL_SSI_ADAPTOR ssi_adapter = (PHAL_SSI_ADAPTOR) Adapter; u32 ret = _TRUE; assert_param(Length != 0); assert_param(pRxData != NULL); if (ssi_adapter->dma_en & SPI_DMA_RX_EN) { return _FALSE; } ssi_adapter->dma_en |= SPI_DMA_RX_EN; ssi_adapter->RxLength = Length; ssi_adapter->RxData = (void*)pRxData; ret = SSI_RXGDMA_Init(ssi_adapter->Index, &ssi_adapter->SSIRxGdmaInitStruct, ssi_adapter, (IRQ_FUN) ssi_dma_rx_irq, pRxData, Length); NVIC_SetPriority(GDMA_GetIrqNum(0, ssi_adapter->SSIRxGdmaInitStruct.GDMA_ChNum), 11); /* Set SSI DMA Enable */ SSI_SetDmaEnable(ssi_adapter->spi_dev, ENABLE, BIT_SHIFT_DMACR_RDMAE); return ret; } static u32 spi_stop_recv(spi_t *obj) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; PGDMA_InitTypeDef GDMA_InitStruct = &ssi_adapter->SSIRxGdmaInitStruct; u32 DMAStopAddr = 0; u32 ReceivedCnt; u8 DmaMode = 0; SSI_INTConfig(ssi_adapter->spi_dev, (BIT_IMR_RXFIM | BIT_IMR_RXOIM | BIT_IMR_RXUIM), DISABLE); if (ssi_adapter->dma_en & SPI_DMA_RX_EN) { DmaMode=1; /* Set SSI DMA Disable */ SSI_SetDmaEnable(ssi_adapter->spi_dev, DISABLE, BIT_SHIFT_DMACR_RDMAE); /* Clear Pending ISR */ GDMA_ClearINT(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); GDMA_ChCleanAutoReload(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, CLEAN_RELOAD_SRC_DST); GDMA_Cmd(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, DISABLE); DMAStopAddr = GDMA_GetDstAddr(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); GDMA_ChnlFree(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); ReceivedCnt = DMAStopAddr - (u32)(ssi_adapter->RxData); ssi_adapter->RxLength-= ReceivedCnt; ssi_adapter->RxData = (u8 *)(ssi_adapter->RxData) + ReceivedCnt; ssi_adapter->dma_en &= ~SPI_DMA_RX_EN; } if (ssi_adapter->RxLength > 0) { ReceivedCnt = SSI_ReceiveData(ssi_adapter->spi_dev, ssi_adapter->RxData, ssi_adapter->RxLength); if (DmaMode && (SSI_GetDataFrameSize(ssi_adapter->spi_dev) > 8)) ReceivedCnt=ReceivedCnt*2; ssi_adapter->RxLength -= ReceivedCnt; } if (ssi_adapter->RxLength == 0) { spi_flush_rx_fifo(obj); } obj->state &= ~ SPI_STATE_RX_BUSY; return HAL_OK; } /** * @brief Initializes the SPI device, include clock/function/interrupt/SPI registers. * @param obj: spi object define in application software. * @param mosi: MOSI PinName according to pinmux spec. * @param miso: MISO PinName according to pinmux spec. * @param sclk: SCLK PinName according to pinmux spec. * @param ssel: CS PinName according to pinmux spec. * @retval none * @note must set obj->spi_index to MBED_SPI0 or MBED_SPI1 before using spi_init */ void spi_init (spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; SSI_InitTypeDef SSI_InitStruct; if ((obj->spi_idx != MBED_SPI0) && (obj->spi_idx != MBED_SPI1)) { DBG_PRINTF(MODULE_SPI, LEVEL_ERROR, "spi_init: you should set spi_idx MBED_SPI0 or MBED_SPI1"); assert_param(0); } ssi_adapter->Index = spi_idx; ssi_adapter->spi_dev = SPI_DEV_TABLE[ssi_adapter->Index].SPIx; obj->sclk = (u8)sclk; SSI_StructInit(&SSI_InitStruct); if (spi_idx == 1) { RCC_PeriphClockCmd(APBPeriph_SPI1, APBPeriph_SPI1_CLOCK, ENABLE); Pinmux_Config(mosi, PINMUX_FUNCTION_SPIM); Pinmux_Config(miso, PINMUX_FUNCTION_SPIM); Pinmux_Config(sclk, PINMUX_FUNCTION_SPIM); Pinmux_Config(ssel, PINMUX_FUNCTION_SPIM); SSI_InitStruct.SPI_Role=SSI_MASTER; ssi_adapter->Role = SSI_MASTER; } else { RCC_PeriphClockCmd(APBPeriph_SPI0, APBPeriph_SPI0_CLOCK, ENABLE); Pinmux_Config(mosi, PINMUX_FUNCTION_SPIS); Pinmux_Config(miso, PINMUX_FUNCTION_SPIS); Pinmux_Config(sclk, PINMUX_FUNCTION_SPIS); Pinmux_Config(ssel, PINMUX_FUNCTION_SPIS); SSI_SetRole(ssi_adapter->spi_dev, SSI_MASTER); SSI_InitStruct.SPI_Role=SSI_MASTER; ssi_adapter->Role=SSI_MASTER; } SSI_Init(ssi_adapter->spi_dev, &SSI_InitStruct); ssi_adapter->IrqNum = SPI_DEV_TABLE[ssi_adapter->Index].IrqNum; InterruptRegister((IRQ_FUN)ssi_interrupt, ssi_adapter->IrqNum, (u32)ssi_adapter, 5); InterruptEn(ssi_adapter->IrqNum, 5); ssi_adapter->TxCompCallback = spi_tx_done_callback; ssi_adapter->TxCompCbPara = (void*)obj; ssi_adapter->RxCompCallback = spi_rx_done_callback; ssi_adapter->RxCompCbPara = (void*)obj; ssi_adapter->TxIdleCallback = spi_bus_tx_done_callback; ssi_adapter->TxIdleCbPara = (void*)obj; obj->state = SPI_STATE_READY; #ifdef CONFIG_GDMA_EN ssi_adapter->dma_en = 0; #endif } /** * @brief Deinitializes the SPI device, include interrupt/DMA/DISABLE SPI. * @param obj: spi object define in application software. * @retval none */ void spi_free (spi_t *obj) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; InterruptDis(ssi_adapter->IrqNum); InterruptUnRegister(ssi_adapter->IrqNum); SSI_INTConfig(ssi_adapter->spi_dev, (BIT_IMR_RXFIM | BIT_IMR_RXOIM | BIT_IMR_RXUIM), DISABLE); if (ssi_adapter->dma_en & SPI_DMA_RX_EN) { PGDMA_InitTypeDef GDMA_InitStruct = &ssi_adapter->SSIRxGdmaInitStruct; /* Set SSI DMA Disable */ SSI_SetDmaEnable(ssi_adapter->spi_dev, DISABLE, BIT_SHIFT_DMACR_RDMAE); /* Clear Pending ISR */ GDMA_ClearINT(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); GDMA_ChCleanAutoReload(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, CLEAN_RELOAD_SRC_DST); GDMA_Cmd(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, DISABLE); GDMA_ChnlFree(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); } if (ssi_adapter->dma_en & SPI_DMA_TX_EN) { PGDMA_InitTypeDef GDMA_InitStruct = &ssi_adapter->SSITxGdmaInitStruct; /* Set SSI DMA Disable */ SSI_SetDmaEnable(ssi_adapter->spi_dev, DISABLE, BIT_SHIFT_DMACR_TDMAE); /* Clear Pending ISR */ GDMA_ClearINT(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); GDMA_ChCleanAutoReload(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, CLEAN_RELOAD_SRC_DST); GDMA_Cmd(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum, DISABLE); GDMA_ChnlFree(GDMA_InitStruct->GDMA_Index, GDMA_InitStruct->GDMA_ChNum); } obj->state = 0; SSI_Cmd(ssi_adapter->spi_dev, DISABLE); } /** * @brief Set SPI format,include DFS/Phase/Polarity/Role. * @param obj: spi object define in application software. * @param bits: data frame size, 4-16 supported. * @param mode: this parameter can be one of the following values: * @arg 0 : [Polarity,Phase]=[0,0] * @arg 1 : [Polarity,Phase]=[0,1] * @arg 2 : [Polarity,Phase]=[1,0] * @arg 3 : [Polarity,Phase]=[1,1] * @param slave: this parameter can be one of the following values: * @arg 0 : indicates role-master * @arg 1 : indicates role-slave * @retval none */ void spi_format (spi_t *obj, int bits, int mode, int slave) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; u32 SclkPhase; u32 SclkPolarity; u32 DataFrameSize = (bits - 1); SSI_InitTypeDef SSI_InitStruct; /* * mode | POL PHA * -----+-------- * 0 | 0 0 * 1 | 0 1 * 2 | 1 0 * 3 | 1 1 * * SCPOL_INACTIVE_IS_LOW = 0, * SCPOL_INACTIVE_IS_HIGH = 1 * * SCPH_TOGGLES_IN_MIDDLE = 0, * SCPH_TOGGLES_AT_START = 1 */ switch (mode) { case 0: SclkPolarity = SCPOL_INACTIVE_IS_LOW; SclkPhase = SCPH_TOGGLES_IN_MIDDLE; break; case 1: SclkPolarity = SCPOL_INACTIVE_IS_LOW; SclkPhase = SCPH_TOGGLES_AT_START; break; case 2: SclkPolarity = SCPOL_INACTIVE_IS_HIGH; SclkPhase = SCPH_TOGGLES_IN_MIDDLE; break; case 3: SclkPolarity = SCPOL_INACTIVE_IS_HIGH; SclkPhase = SCPH_TOGGLES_AT_START; break; default: // same as 3 SclkPolarity = SCPOL_INACTIVE_IS_HIGH; SclkPhase = SCPH_TOGGLES_AT_START; break; } if (slave == 1) { if (spi_idx == 0) { SSI_SetRole(ssi_adapter->spi_dev, SSI_SLAVE); ssi_adapter->Role = SSI_SLAVE; // Re-init after setting role SSI_StructInit(&SSI_InitStruct); SSI_InitStruct.SPI_Role=SSI_SLAVE; SSI_Init(ssi_adapter->spi_dev, &SSI_InitStruct); } else { assert_param(0); } } else { if (spi_idx == 0) { SSI_SetRole(ssi_adapter->spi_dev, SSI_MASTER); ssi_adapter->Role = SSI_MASTER; } else { ssi_adapter->Role = SSI_MASTER; } } SSI_SetSclkPhase(ssi_adapter->spi_dev, SclkPhase); SSI_SetSclkPolarity(ssi_adapter->spi_dev, SclkPolarity); SSI_SetDataFrameSize(ssi_adapter->spi_dev, DataFrameSize); if (slave == 1) { if (SclkPolarity == SCPOL_INACTIVE_IS_LOW) { PAD_PullCtrl((u32)obj->sclk, GPIO_PuPd_DOWN); } else { PAD_PullCtrl((u32)obj->sclk, GPIO_PuPd_UP); } } } /** * @brief Set SPI baudrate. * @param obj: spi master object define in application software. * @param hz: baudrate for SPI bus * @retval none * @note * - "hz" should be less or equal to half of the SPI IpClk. * - IpClk for SPI1 is 50MHz and IpClk for SPI0 is 100MHz */ void spi_frequency (spi_t *obj, int hz) { uint8_t spi_idx = obj->spi_idx &0x0F; u32 IpClk; u32 ClockDivider; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; if (spi_idx == 0) IpClk=100000000; else IpClk=50000000; /*Adjust SCKDV-Parameter to an even number */ ClockDivider = IpClk/hz + 1; if ((IpClk%hz) > (u32)(hz/2)) { ClockDivider++; } if (ClockDivider >= 0xFFFF) { /* devider is 16 bits */ ClockDivider = 0xFFFE; } ClockDivider &= 0xFFFE; // bit 0 always is 0 SSI_SetBaudDiv(ssi_adapter->spi_dev, ClockDivider); } void spi_slave_select(spi_t *obj, ChipSelect slaveindex) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; if(ssi_adapter->Role == SSI_MASTER){ SSI_SetSlaveEnable(ssi_adapter->spi_dev,slaveindex); } else { assert_param(0); } } static inline void ssi_write (spi_t *obj, int value) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; while (!SSI_Writeable(ssi_adapter->spi_dev)); SSI_WriteData(ssi_adapter->spi_dev, value); } static inline int ssi_read(spi_t *obj) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; while (!SSI_Readable(ssi_adapter->spi_dev)); return (int)SSI_ReadData(ssi_adapter->spi_dev); } /** * @brief Master send one frame use SPI. * @param obj: spi master object define in application software. * @param value: the data to transmit. * @retval : data received from slave */ int spi_master_write (spi_t *obj, int value) { ssi_write(obj, value); return ssi_read(obj); } /** * @brief Get slave readable && busy state. * @param obj: spi slave object define in application software. * @retval : slave Readable && Busy State */ int spi_slave_receive (spi_t *obj) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; int Readable; int Busy; Readable = SSI_Readable(ssi_adapter->spi_dev); Busy = (int)SSI_Busy(ssi_adapter->spi_dev); return ((Readable && !Busy) ? 1 : 0); } /** * @brief Slave receive one frame use SPI. * @param obj: spi slave object define in application software. * @retval : data received from master */ int spi_slave_read (spi_t *obj) { return ssi_read(obj); } /** * @brief Slave send one frame use SPI. * @param obj: spi slave object define in application software. * @param value: the data to transmit. * @retval none */ void spi_slave_write (spi_t *obj, int value) { ssi_write(obj, value); } /** * @brief Get SPI busy state. * @param obj: spi object define in application software. * @retval : current busy state */ int spi_busy (spi_t *obj) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; return (int)SSI_Busy(ssi_adapter->spi_dev); } /** * @brief SPI device to flush rx fifo. * @param obj: spi object define in application software. * @retval none */ void spi_flush_rx_fifo (spi_t *obj) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; u32 rx_fifo_level; u32 i; while(SSI_Readable(ssi_adapter->spi_dev)){ rx_fifo_level = SSI_GetRxCount(ssi_adapter->spi_dev); for(i=0;i<rx_fifo_level;i++) { SSI_ReadData(ssi_adapter->spi_dev); } } } /** * @brief slave recv target length data use interrupt mode. * @param obj: spi slave object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @retval : stream init status */ int32_t spi_slave_read_stream(spi_t *obj, char *rx_buffer, uint32_t length) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; int32_t ret; if (obj->state & SPI_STATE_RX_BUSY) { DBG_PRINTF(MODULE_SPI, LEVEL_WARN, "spis int rx: state(0x%x) is not ready\r\n", obj->state); return HAL_BUSY; } //DBG_PRINTF(MODULE_SPI, LEVEL_INFO, "rx_buffer addr: %X, length: %d\n", rx_buffer, length); obj->state |= SPI_STATE_RX_BUSY; if ((ret = ssi_int_read(ssi_adapter, rx_buffer, length)) != _TRUE) { obj->state &= ~SPI_STATE_RX_BUSY; } return (ret == _TRUE) ? HAL_OK : HAL_BUSY; } /** * @brief slave send target length data use interrupt mode. * @param obj: spi slave object define in application software. * @param tx_buffer: buffer to be written to Tx FIFO. * @param length: number of data bytes to be send. * @retval : stream init status */ int32_t spi_slave_write_stream(spi_t *obj, char *tx_buffer, uint32_t length) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; int32_t ret; if (obj->state & SPI_STATE_TX_BUSY) { DBG_PRINTF(MODULE_SPI, LEVEL_WARN, "spis int tx: state(0x%x) is not ready\r\n", obj->state); return HAL_BUSY; } obj->state |= SPI_STATE_TX_BUSY; if ((ret=ssi_int_write(ssi_adapter, (u8 *) tx_buffer, length)) != _TRUE) { obj->state &= ~SPI_STATE_TX_BUSY; } return (ret == _TRUE) ? HAL_OK : HAL_BUSY; } /** * @brief master recv target length data use interrupt mode. * @param obj: spi master object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @retval : stream init status */ int32_t spi_master_read_stream(spi_t *obj, char *rx_buffer, uint32_t length) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; int32_t ret; if (obj->state & SPI_STATE_RX_BUSY) { DBG_PRINTF(MODULE_SPI, LEVEL_WARN, "spim int rx: state(0x%x) is not ready\r\n", obj->state); return HAL_BUSY; } // wait bus idle while(SSI_Busy(ssi_adapter->spi_dev)); obj->state |= SPI_STATE_RX_BUSY; if ((ret = ssi_int_read(ssi_adapter, rx_buffer, length)) == _TRUE) { /* as Master mode, it need to push data to TX FIFO to generate clock out then the slave can transmit data out */ // send some dummy data out if ((ret=ssi_int_write(ssi_adapter, NULL, length)) != _TRUE) { obj->state &= ~SPI_STATE_RX_BUSY; } } else { obj->state &= ~SPI_STATE_RX_BUSY; } return (ret == _TRUE) ? HAL_OK : HAL_BUSY; } /** * @brief master send target length data use interrupt mode. * @param obj: spi master object define in application software. * @param tx_buffer: buffer to be written to Tx FIFO. * @param length: number of data bytes to be send. * @retval : stream init status */ int32_t spi_master_write_stream(spi_t *obj, char *tx_buffer, uint32_t length) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; int32_t ret; if (obj->state & SPI_STATE_TX_BUSY) { DBG_PRINTF(MODULE_SPI, LEVEL_WARN, "spim int tx: state(0x%x) is not ready\r\n", obj->state); return HAL_BUSY; } obj->state |= SPI_STATE_TX_BUSY; /* as Master mode, sending data will receive data at sametime, so we need to drop those received dummy data */ if ((ret=ssi_int_write(ssi_adapter, (u8 *) tx_buffer, length)) != _TRUE) { obj->state &= ~SPI_STATE_TX_BUSY; } return (ret == _TRUE) ? HAL_OK : HAL_BUSY; } /** * @brief master send & recv target length data use interrupt mode. * @param obj: spi master object define in application software. * @param tx_buffer: buffer to be written to Tx FIFO. * @param tx_size: number of data bytes to be send. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param rx_size: number of data bytes to be recv. * @retval : stream init status */ int32_t spi_master_write_read_stream(spi_t *obj, char *tx_buffer, uint32_t tx_size, char *rx_buffer, uint32_t rx_size) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; int32_t ret; if (obj->state & (SPI_STATE_RX_BUSY|SPI_STATE_TX_BUSY)) { DBG_PRINTF(MODULE_SPI, LEVEL_WARN, "spim int trx: state(0x%x) is not ready\r\n", obj->state); return HAL_BUSY; } // wait bus idle while(SSI_Busy(ssi_adapter->spi_dev)); obj->state |= SPI_STATE_RX_BUSY; /* as Master mode, sending data will receive data at sametime */ if ((ret = ssi_int_read(ssi_adapter, rx_buffer, rx_size)) == _TRUE) { obj->state |= SPI_STATE_TX_BUSY; if ((ret=ssi_int_write(ssi_adapter, (u8 *) tx_buffer, tx_size)) != _TRUE) { obj->state &= ~(SPI_STATE_RX_BUSY|SPI_STATE_TX_BUSY); // Disable RX IRQ SSI_INTConfig(ssi_adapter->spi_dev, (BIT_IMR_RXFIM | BIT_IMR_RXOIM | BIT_IMR_RXUIM), DISABLE); } } else { obj->state &= ~(SPI_STATE_RX_BUSY); } return (ret == _TRUE) ? HAL_OK : HAL_BUSY; } /** * @brief Set SPI interrupt handler if needed. * @param obj: spi object define in application software. * @param handler: interrupt callback function * @param id: interrupt callback parameter * @retval none */ void spi_irq_hook(spi_t *obj, spi_irq_handler handler, uint32_t id) { obj->irq_handler = (u32)handler; obj->irq_id = (u32)id; } /** * @brief slave recv target length data use DMA mode. * @param obj: spi slave object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @retval : stream init status */ int32_t spi_slave_read_stream_dma(spi_t *obj, char *rx_buffer, uint32_t length) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; int32_t ret; if (obj->state & SPI_STATE_RX_BUSY) { DBG_PRINTF(MODULE_SPI, LEVEL_WARN, "spim dma rx: state(0x%x) is not ready\r\n", obj->state); return HAL_BUSY; } obj->state |= SPI_STATE_RX_BUSY; ret = ssi_dma_recv(ssi_adapter, (u8 *) rx_buffer, length); if (ret != _TRUE) { obj->state &= ~SPI_STATE_RX_BUSY; } return (ret == _TRUE) ? HAL_OK : HAL_BUSY; } /** * @brief slave send target length data use DMA mode. * @param obj: spi slave object define in application software. * @param tx_buffer: buffer to be written to Tx FIFO. * @param length: number of data bytes to be send. * @retval : stream init status */ int32_t spi_slave_write_stream_dma(spi_t *obj, char *tx_buffer, uint32_t length) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; int32_t ret; if (obj->state & SPI_STATE_TX_BUSY) { DBG_PRINTF(MODULE_SPI, LEVEL_WARN, "spis dma tx: state(0x%x) is not ready\r\n", obj->state); return HAL_BUSY; } obj->state |= SPI_STATE_TX_BUSY; ret = ssi_dma_send(ssi_adapter, (u8 *) tx_buffer, length); if (ret != _TRUE) { obj->state &= ~SPI_STATE_TX_BUSY; } return (ret == _TRUE) ? HAL_OK : HAL_BUSY; } #define USE_DMA_WRITE_MASTER_READ 1 /** * @brief master recv target length data use DMA mode. * @param obj: spi master object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @retval : stream init status * @note : DMA or Interrupt mode can be used to TX dummy data */ int32_t spi_master_read_stream_dma(spi_t *obj, char *rx_buffer, uint32_t length) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; int32_t ret; if (obj->state & SPI_STATE_RX_BUSY) { DBG_PRINTF(MODULE_SPI, LEVEL_WARN, "spim dma rx: state(0x%x) is not ready\r\n", obj->state); return HAL_BUSY; } obj->state |= SPI_STATE_RX_BUSY; ret = ssi_dma_recv(ssi_adapter, (u8 *) rx_buffer, length); if (ret != _TRUE) { obj->state &= ~SPI_STATE_RX_BUSY; } // for master mode, we need to send data to generate clock out #ifdef USE_DMA_WRITE_MASTER_READ // TX DMA is on already, so use DMA to TX data // Make the GDMA to use the rx_buffer too ret = ssi_dma_send(ssi_adapter, (u8 *) rx_buffer, length); if (ret != _TRUE) { obj->state &= ~SPI_STATE_RX_BUSY; } #else // TX DMA isn't enabled, so we just use Interrupt mode to TX dummy data if ((ret=ssi_int_write(ssi_adapter, NULL, length)) != _TRUE) { obj->state &= ~SPI_STATE_RX_BUSY; } #endif return (ret == _TRUE) ? HAL_OK : HAL_BUSY; } /** * @brief master send target length data use DMA mode. * @param obj: spi master object define in application software. * @param tx_buffer: buffer to be written to Tx FIFO. * @param length: number of data bytes to be send. * @retval : stream init status */ int32_t spi_master_write_stream_dma(spi_t *obj, char *tx_buffer, uint32_t length) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; int32_t ret; if (obj->state & SPI_STATE_TX_BUSY) { DBG_PRINTF(MODULE_SPI, LEVEL_WARN, "spim dma tx: state(0x%x) is not ready\r\n", obj->state); return HAL_BUSY; } obj->state |= SPI_STATE_TX_BUSY; ret = ssi_dma_send(ssi_adapter, (u8 *) tx_buffer, length); if (ret != _TRUE) { obj->state &= ~SPI_STATE_TX_BUSY; } return (ret == _TRUE) ? HAL_OK : HAL_BUSY; } /** * @brief master send & recv target length data use DMA mode. * @param obj: spi master object define in application software. * @param tx_buffer: buffer to be written to Tx FIFO. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be send & recv. * @retval : stream init status */ int32_t spi_master_write_read_stream_dma(spi_t *obj, char *tx_buffer, char *rx_buffer, uint32_t length) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; int32_t ret; if (obj->state & (SPI_STATE_RX_BUSY|SPI_STATE_TX_BUSY)) { DBG_PRINTF(MODULE_SPI, LEVEL_WARN, "spi_master_write_and_read_stream: state(0x%x) is not ready\r\n", obj->state); return HAL_BUSY; } obj->state |= SPI_STATE_RX_BUSY; ret = ssi_dma_recv(ssi_adapter, (u8 *) rx_buffer, length); if (ret != _TRUE) { obj->state &= ~SPI_STATE_RX_BUSY; return HAL_BUSY; } obj->state |= SPI_STATE_TX_BUSY; ret = ssi_dma_send(ssi_adapter, (u8 *) tx_buffer, length); if (ret != _TRUE) { obj->state &= ~SPI_STATE_TX_BUSY; return HAL_BUSY; } return (ret == _TRUE) ? HAL_OK : HAL_BUSY; } /** * @brief slave recv target length data use DMA mode and timeout mechanism. * @param obj: spi slave object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @param timeout_ms: timeout waiting time. * @retval : number of bytes read already */ int32_t spi_slave_read_stream_dma_timeout(spi_t *obj, char *rx_buffer, uint32_t length, uint32_t timeout_ms) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; int ret, timeout = 0; uint32_t StartCount = 0; assert_param(timeout_ms > 0); if (obj->state & SPI_STATE_RX_BUSY) { DBG_PRINTF(MODULE_SPI, LEVEL_WARN, "spi_slave_read_stream_dma: state(0x%x) is not ready\r\n", obj->state); return -HAL_BUSY; } obj->state |= SPI_STATE_RX_BUSY; ret = ssi_dma_recv(ssi_adapter, (u8 *) rx_buffer, length); if (ret != _TRUE) { obj->state &= ~SPI_STATE_RX_BUSY; return -HAL_BUSY; } StartCount = SYSTIMER_TickGet(); while (1) { /* complete */ if ((obj->state & SPI_STATE_RX_BUSY) == 0) { break; } /* time out */ if (SYSTIMER_GetPassTime(StartCount) > timeout_ms) { ret = spi_stop_recv(obj); obj->state &= ~ SPI_STATE_RX_BUSY; timeout = 1; DBG_PRINTF(MODULE_SPI, LEVEL_INFO, "Slave is timeout\n"); break; } } //if (SSI_GetDataFrameSize(SPIx) > 8){ // ssi_adapter->RxLength <<= 1; //} if(timeout) return (length - ssi_adapter->RxLength); else return length; } /** * @brief slave recv target length data use DMA mode and stop if the spi bus is idle. * @param obj: spi slave object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @retval : number of bytes read already */ int32_t spi_slave_read_stream_dma_terminate(spi_t *obj, char *rx_buffer, uint32_t length) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; SPI_TypeDef *SPIx = SPI_DEV_TABLE[spi_idx].SPIx; int ret; if (obj->state & SPI_STATE_RX_BUSY) { DBG_PRINTF(MODULE_SPI, LEVEL_WARN, "spi_slave_read_stream_dma: state(0x%x) is not ready\r\n", obj->state); return -HAL_BUSY; } obj->state |= SPI_STATE_RX_BUSY; ret = ssi_dma_recv(ssi_adapter, (u8 *) rx_buffer, length); if (ret != _TRUE) { obj->state &= ~SPI_STATE_RX_BUSY; return -HAL_BUSY; } while(obj->state & SPI_STATE_RX_BUSY){ if(SSI_Busy(SPIx) == 0){ ret = spi_stop_recv(obj); goto EndOfDMACS; } } EndOfDMACS: if((obj->state & SPI_STATE_RX_BUSY) != 0){ obj->state &= ~ SPI_STATE_RX_BUSY; } //if (SSI_GetDataFrameSize(SPIx) > 8) { // ssi_adapter->RxLength <<= 1; //} return (length - ssi_adapter->RxLength); } /** * @brief Slave device to flush tx fifo. * @param obj: spi slave object define in application software. * @note : It will discard all data in both tx fifo and rx fifo */ void spi_slave_flush_fifo(spi_t *obj) { uint8_t spi_idx = obj->spi_idx &0x0F; SPI_TypeDef *SPIx = SPI_DEV_TABLE[spi_idx].SPIx; SSI_Cmd(SPIx, DISABLE); SSI_Cmd(SPIx, ENABLE); obj->state &= ~SPI_STATE_TX_BUSY; } /** * @brief slave recv target length data use interrupt mode and timeout mechanism. * @param obj: spi slave object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @param timeout_ms: timeout waiting time. * @retval : number of bytes read already */ int32_t spi_slave_read_stream_timeout(spi_t *obj, char *rx_buffer, uint32_t length, uint32_t timeout_ms) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; SPI_TypeDef *SPIx = SPI_DEV_TABLE[spi_idx].SPIx; uint32_t ret; uint32_t timeout = 0; uint32_t StartCount = 0; assert_param(timeout_ms > 0); if (obj->state & SPI_STATE_RX_BUSY) { DBG_PRINTF(MODULE_SPI, LEVEL_WARN, "spi_slave_read_stream: state(0x%x) is not ready\r\n", obj->state); return -HAL_BUSY; } obj->state |= SPI_STATE_RX_BUSY; if ((ret = ssi_int_read(ssi_adapter, rx_buffer, length)) != _TRUE) { obj->state &= ~SPI_STATE_RX_BUSY; return -HAL_BUSY; } StartCount = SYSTIMER_TickGet(); while (1) { /* complete */ if ((obj->state & SPI_STATE_RX_BUSY) == 0) { break; } /* time out */ if (SYSTIMER_GetPassTime(StartCount) > timeout_ms) { ret = spi_stop_recv(obj); obj->state &= ~ SPI_STATE_RX_BUSY; timeout = 1; DBG_PRINTF(MODULE_SPI, LEVEL_INFO, "Slave is timeout\n"); break; } } if (SSI_GetDataFrameSize(SPIx) > 8){ ssi_adapter->RxLength <<= 1; } if(timeout) return (length - ssi_adapter->RxLength); else return length; } /** * @brief slave recv target length data use interrupt mode and stop if the spi bus is idle. * @param obj: spi slave object define in application software. * @param rx_buffer: buffer to save data read from SPI FIFO. * @param length: number of data bytes to be read. * @retval : number of bytes read already */ int32_t spi_slave_read_stream_terminate(spi_t *obj, char *rx_buffer, uint32_t length) { uint8_t spi_idx = obj->spi_idx &0x0F; PHAL_SSI_ADAPTOR ssi_adapter = &ssi_adapter_g[spi_idx]; SPI_TypeDef *SPIx = SPI_DEV_TABLE[spi_idx].SPIx; int ret; if (obj->state & SPI_STATE_RX_BUSY) { DBG_PRINTF(MODULE_SPI, LEVEL_WARN, "spi_slave_read_stream_dma: state(0x%x) is not ready\r\n", obj->state); return -HAL_BUSY; } obj->state |= SPI_STATE_RX_BUSY; if ((ret = ssi_int_read(ssi_adapter, rx_buffer, length)) != _TRUE) { obj->state &= ~SPI_STATE_RX_BUSY; return -HAL_BUSY; } while(obj->state & SPI_STATE_RX_BUSY) { if(SSI_Busy(SPIx) == 0){ ret = spi_stop_recv(obj); goto EndOfCS; } } EndOfCS: if((obj->state & SPI_STATE_RX_BUSY) != 0){ obj->state &= ~ SPI_STATE_RX_BUSY; } if (SSI_GetDataFrameSize(SPIx) > 8) { ssi_adapter->RxLength <<= 1; } return (length - ssi_adapter->RxLength); } /** * @brief Open SPI device clock. * @param obj: spi object define in application software. * @retval none */ void spi_enable(spi_t *obj) { uint8_t spi_idx = obj->spi_idx &0x0F; if (spi_idx == 1) { RCC_PeriphClockCmd(APBPeriph_SPI1, APBPeriph_SPI1_CLOCK, ENABLE); } else { RCC_PeriphClockCmd(APBPeriph_SPI0, APBPeriph_SPI0_CLOCK, ENABLE); } } /** * @brief Close SPI device clock. * @param obj: spi object define in application software. * @retval none */ void spi_disable(spi_t *obj) { uint8_t spi_idx = obj->spi_idx &0x0F; if (spi_idx == 1) { RCC_PeriphClockCmd(APBPeriph_SPI1, APBPeriph_SPI1_CLOCK, DISABLE); } else { RCC_PeriphClockCmd(APBPeriph_SPI0, APBPeriph_SPI0_CLOCK, DISABLE); } } /** * @} */ /** * @} */ /** * @} */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/spi_api.c
C
apache-2.0
39,169
/** mbed Microcontroller Library ****************************************************************************** * @file sys_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides following mbed system API: * -JTAG OFF * -LOGUART ON/OFF * -OTA image switch * -System Reset ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "cmsis.h" #include "sys_api.h" #include "flash_api.h" #include "device_lock.h" #include "rtl8721d_ota.h" void rtc_backup_timeinfo(void); //#define printf DiagPrintf /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_SYSAPI * @brief MBED_SYSAPI driver modules. * @{ */ /** @defgroup MBED_SYSAPI_Exported_Functions MBED_SYSAPI Exported Functions * @{ */ /** * @brief Turn off the JTAG function * @retval none */ void sys_jtag_off(void) { Pinmux_Swdoff(); } /** * @brief clear the signature of current firmware * @retval none */ void sys_clear_ota_signature(void) { u32 AddrStart, Offset, IsMinus, PhyAddr; u32 FwAddr; u8 EmpSig = 0; RSIP_REG_TypeDef* RSIP = ((RSIP_REG_TypeDef *) RSIP_REG_BASE); u32 CtrlTemp = RSIP->FLASH_MMU[0].MMU_ENTRYx_CTRL; if (CtrlTemp & MMU_BIT_ENTRY_VALID) { AddrStart = RSIP->FLASH_MMU[0].MMU_ENTRYx_STRADDR; Offset = RSIP->FLASH_MMU[0].MMU_ENTRYx_OFFSET; IsMinus = CtrlTemp & MMU_BIT_ENTRY_OFFSET_MINUS; if(IsMinus) PhyAddr = AddrStart - Offset; else PhyAddr = AddrStart + Offset; if(PhyAddr == LS_IMG2_OTA1_ADDR) FwAddr = LS_IMG2_OTA1_ADDR; else FwAddr = LS_IMG2_OTA2_ADDR; } FLASH_WriteStream(FwAddr - SPI_FLASH_BASE, 4, &EmpSig); } /** * @brief recover the signature of the other firmware * @retval none */ void sys_recover_ota_signature(void) { u32 AddrStart, Offset, IsMinus, PhyAddr; u8 Ota2Use = _FALSE; u32 DstAddr, CurAddr; u8 OldSig, NewSig; u8 *buf; RSIP_REG_TypeDef* RSIP = ((RSIP_REG_TypeDef *) RSIP_REG_BASE); u32 CtrlTemp = RSIP->FLASH_MMU[0].MMU_ENTRYx_CTRL; /* Get which firmware used */ if (CtrlTemp & MMU_BIT_ENTRY_VALID) { AddrStart = RSIP->FLASH_MMU[0].MMU_ENTRYx_STRADDR; Offset = RSIP->FLASH_MMU[0].MMU_ENTRYx_OFFSET; IsMinus = CtrlTemp & MMU_BIT_ENTRY_OFFSET_MINUS; if(IsMinus) PhyAddr = AddrStart - Offset; else PhyAddr = AddrStart + Offset; if(PhyAddr == LS_IMG2_OTA1_ADDR) Ota2Use = _FALSE; else Ota2Use = _TRUE; } if(Ota2Use) { CurAddr = LS_IMG2_OTA2_ADDR; DstAddr = LS_IMG2_OTA1_ADDR; } else { CurAddr = LS_IMG2_OTA1_ADDR; DstAddr = LS_IMG2_OTA2_ADDR; } /* Get signature of the two firmware */ ota_readstream_user(DstAddr, 4, &OldSig); ota_readstream_user(CurAddr, 4, &NewSig); DBG_8195A("old sig: %08x, new sig:%08x\n", OldSig, NewSig); if(OldSig == NewSig) { return; } /* Backup first 4KB of the old firmware */ buf = pvPortMalloc(4096); ota_readstream_user(DstAddr, 4096, buf); /* Modify signature */ _memcpy(buf, &NewSig, 4); /* Erase first sector */ flash_erase_sector(NULL, DstAddr); /* Write back 4KB to first sector */ flash_stream_write(NULL, DstAddr, 4096, buf); vPortFree(buf); } /** * @brief open log uart * @retval none */ void sys_log_uart_on(void) { /* Just Support S0 */ Pinmux_UartLogCtrl(PINMUX_S0, ON); UART_INTConfig(UART2_DEV, RUART_IER_ERBI, ENABLE); UART_RxCmd(UART2_DEV, ENABLE); } /** * @brief close log uart * @retval none */ void sys_log_uart_off(void) { UART_INTConfig(UART2_DEV, RUART_IER_ERBI, DISABLE); UART_RxCmd(UART2_DEV, DISABLE); /* Just Support S0 */ Pinmux_UartLogCtrl(PINMUX_S0, OFF); } /** * @brief store or load adc calibration parameter * @param write: this parameter can be one of the following values: * @arg 0: load adc calibration parameter offset & gain * @arg 1: store adc calibration parameter offset & gain * @param offset: pointer to adc parameter offset * @param gain: pointer to adc parameter gain * @retval none */ void sys_adc_calibration(u8 write, u16 *offset, u16 *gain) { /* To avoid gcc warnings */ ( void ) write; ( void ) offset; ( void ) gain; printf("ADC calibration is finished in FT test. Calibration parameters can be found in EFUSE." \ "Please refer to Battery Measurement chapter in Application Note to get calibration parameters.\n"); assert_param(0); } /** * @brief system software reset * @retval none */ void sys_reset(void) { WDG_InitTypeDef WDG_InitStruct; u32 CountProcess; u32 DivFacProcess; rtc_backup_timeinfo(); WDG_Scalar(50, &CountProcess, &DivFacProcess); WDG_InitStruct.CountProcess = CountProcess; WDG_InitStruct.DivFacProcess = DivFacProcess; WDG_Init(&WDG_InitStruct); WDG_Cmd(ENABLE); } /** * @brief vector reset * @retval none */ void sys_cpu_reset(void) { #ifdef AMEBAD_TODO u32 reg_value; rtc_backup_timeinfo(); reg_value = HAL_READ32(PERI_ON_BASE, REG_SOC_FUNC_EN); reg_value |= BIT_SOC_PATCH_FUNC1; HAL_WRITE32(PERI_ON_BASE, REG_SOC_FUNC_EN, reg_value); /* Ensure all outstanding memory accesses included */ /* buffered write are completed before reset */ __DSB(); /* CPU reset */ /* Keep priority group unchanged */ SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) | (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) | SCB_AIRCR_VECTRESET_Pos | SCB_AIRCR_VECTCLRACTIVE_Pos); /* Ensure completion of memory access */ __DSB(); while(1); #endif } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/sys_api.c
C
apache-2.0
5,884
/** mbed Microcontroller Library ****************************************************************************** * @file timer_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for gtimer. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "objects.h" #include "timer_api.h" extern void aos_interrupt_enter(); extern void aos_interrupt_leave(); /** @defgroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_TIMER * @brief MBED_TIMER driver modules. * @{ */ /** @defgroup MBED_TIMER_Exported_Functions MBED_TIMER Exported Functions * @{ */ /** * @brief gtimer interrupt handler function. * @param data: timer IRQ callback parameter * @retval none */ static void gtimer_timeout_handler (uint32_t data) { gtimer_t *obj = (gtimer_t *)data; uint32_t tid = obj->timer_id; gtimer_irq_handler handler; aos_interrupt_enter(); RTIM_INTClear(TIMx[tid]); if (obj->handler != NULL) { handler = (gtimer_irq_handler)obj->handler; handler(obj->hid); } if (!obj->is_periodcal) { gtimer_stop(obj); } aos_interrupt_leave(); } /** * @brief Initializes the timer device, include timer registers and interrupt. * @param obj: timer object define in application software. * @param tid: general timer ID, which can be one of the following parameters: * @arg TIMER0 * @arg TIMER1 * @arg TIMER2 * @arg TIMER3 * @note KM4 TIMER0/1/2/3 are recommended. * @retval none */ void gtimer_init (gtimer_t *obj, uint32_t tid) { RTIM_TimeBaseInitTypeDef TIM_InitStruct; assert_param(tid < GTIMER_MAX); obj->timer_id = tid; RTIM_TimeBaseStructInit(&TIM_InitStruct); TIM_InitStruct.TIM_Idx = (u8)tid; TIM_InitStruct.TIM_UpdateEvent = ENABLE; /* UEV enable */ TIM_InitStruct.TIM_UpdateSource = TIM_UpdateSource_Overflow; TIM_InitStruct.TIM_ARRProtection = ENABLE; RTIM_TimeBaseInit(TIMx[tid], &TIM_InitStruct, TIMx_irq[tid], (IRQ_FUN) gtimer_timeout_handler, (u32)obj); } /** * @brief Deinitializes the timer, including clock/function/timer registers. * @param obj: gtimer object defined in application software. * @retval none */ void gtimer_deinit (gtimer_t *obj) { uint32_t tid = obj->timer_id; assert_param(tid < GTIMER_MAX); RTIM_DeInit(TIMx[tid]); } /** * @brief Get counter value of the specified timer. * @param obj: timer object define in application software. * @retval value: counter value */ uint32_t gtimer_read_tick (gtimer_t *obj) { uint32_t tid = obj->timer_id; assert_param(tid < GTIMER_MAX); return (RTIM_GetCount(TIMx[tid])); } /** * @brief Read current timer tick in microsecond. * @param obj: gtimer object defined in application software. * @retval 64 bit tick time */ uint64_t gtimer_read_us (gtimer_t *obj) //need to be test in IAR(64bit computing) { assert_param(obj->timer_id < GTIMER_MAX); uint64_t time_us; time_us = gtimer_read_tick(obj) *1000000 /32768; return (time_us); } /** * @brief Change period of the specified timer. * @param obj: timer object define in application software. * @param duration_us: the new period to be set in microseconds. * @retval none */ void gtimer_reload (gtimer_t *obj, uint32_t duration_us) { uint32_t tid = obj->timer_id; uint32_t temp = (uint32_t)((float)duration_us / 1000000 *32768); assert_param(tid < GTIMER_MAX); RTIM_ChangePeriodImmediate(TIMx[tid], temp); } /** * @brief Start the specified timer and enable update interrupt. * @param obj: timer object define in application software. * @retval none */ void gtimer_start (gtimer_t *obj) { uint32_t tid = obj->timer_id; assert_param(tid < GTIMER_MAX); RTIM_INTConfig(TIMx[tid], TIM_IT_Update, ENABLE); RTIM_Cmd(TIMx[tid], ENABLE); } /** * @brief Start the specified timer in one-shot mode with specified period and interrupt handler. * @param obj: timer object define in application software. * @param duration_us: the new period to be set in microseconds. * @param handler: user defined IRQ callback function * @param hid: user defined IRQ callback parameter * @retval none * @note This function set the timer into one-shot mode which stops after the first time the counter overflows. */ void gtimer_start_one_shout (gtimer_t *obj, uint32_t duration_us, void* handler, uint32_t hid) { assert_param(obj->timer_id < GTIMER_MAX); obj->is_periodcal = _FALSE; obj->handler = handler; obj->hid = hid; gtimer_reload(obj, duration_us); gtimer_start(obj); } /** * @brief Start the specified timer in periodical mode with specified period and interrupt handler. * @param obj: timer object define in application software. * @param duration_us: the new period to be set in microseconds. * @param handler: user defined IRQ callback function * @param hid: user defined IRQ callback parameter * @retval none * @note This functon set the timer into periodical mode which will restart to count from 0 each time the counter overflows. */ void gtimer_start_periodical (gtimer_t *obj, uint32_t duration_us, void* handler, uint32_t hid) { assert_param(obj->timer_id < GTIMER_MAX); obj->is_periodcal = _TRUE; obj->handler = handler; obj->hid = hid; gtimer_reload(obj, duration_us); gtimer_start(obj); } /** * @brief Disable the specified timer peripheral. * @param obj: timer object define in application software. * @retval none */ void gtimer_stop (gtimer_t *obj) { uint32_t tid = obj->timer_id; assert_param(tid < GTIMER_MAX); RTIM_Cmd(TIMx[tid], DISABLE); } /** * @} */ /** * @} */ /** * @} */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/timer_api.c
C
apache-2.0
6,040
/* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, Realtek Semiconductor Corp. * All rights reserved. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. ******************************************************************************* */ #include "objects.h" #include <stddef.h> #include "us_ticker_api.h" #include "PeripheralNames.h" #define TICK_READ_FROM_CPU 0 //1: read tick from CPU, 0: read tick from G-Timer #define GTIMER_CLK_HZ (32768) #define GTIMER_TICK_US (1000000/GTIMER_CLK_HZ) #define SYS_TIM_ID 0 // the G-Timer ID for System #define APP_TIM_ID 1 // the G-Timer ID for Application static int us_ticker_inited = 0; VOID _us_ticker_irq_handler(void *Data) { /* To avoid gcc warnings */ ( void ) Data; us_ticker_irq_handler(); } void us_ticker_init(void) { RTIM_TimeBaseInitTypeDef TIM_InitStruct; if (us_ticker_inited) return; us_ticker_inited = 1; RTIM_TimeBaseStructInit(&TIM_InitStruct); TIM_InitStruct.TIM_Idx = APP_TIM_ID; TIM_InitStruct.TIM_Prescaler = 0; TIM_InitStruct.TIM_Period = 0xFFFFFFFF; TIM_InitStruct.TIM_UpdateEvent = ENABLE; /* UEV enable */ TIM_InitStruct.TIM_UpdateSource = TIM_UpdateSource_Overflow; TIM_InitStruct.TIM_ARRProtection = ENABLE; RTIM_TimeBaseInit(TIMM01, &TIM_InitStruct, 0, (IRQ_FUN) _us_ticker_irq_handler, (u32)NULL); RTIM_Cmd(TIMM01, ENABLE); DBG_PRINTF(MODULE_TIMER, LEVEL_INFO, "%s: Timer_Id=%d\n", __FUNCTION__, APP_TIM_ID); } #if (!TICK_READ_FROM_CPU) || !defined(PLATFORM_FREERTOS) uint32_t us_ticker_read(void) { uint32_t tick_cnt; uint64_t us_tick; tick_cnt = SYSTIMER_TickGet(); //up counter us_tick = tick_cnt * (1000000/32768); return ((uint32_t)us_tick); } #else // if the system tick didn't be initialed, call delay function may got system hang #define OS_CLOCK (200000000UL/6*5) // CPU clock = 166.66 MHz #define OS_TICK 1000 // OS ticks 1000/sec #define OS_TRV ((uint32_t)(((double)OS_CLOCK*(double)OS_TICK)/1E6)-1) #define NVIC_ST_CTRL (*((volatile uint32_t *)0xE000E010)) #define NVIC_ST_RELOAD (*((volatile uint32_t *)0xE000E014)) #define NVIC_ST_CURRENT (*((volatile uint32_t *)0xE000E018)) extern uint32_t xTaskGetTickCount( void ); uint32_t us_ticker_read(void) { uint32_t tick_cnt; uint32_t us_tick, ms; static uint32_t last_us_tick=0; ms = xTaskGetTickCount(); us_tick = (uint32_t)(ms*1000); tick_cnt = OS_TRV - NVIC_ST_CURRENT; us_tick += (uint32_t)((tick_cnt*1000)/(OS_TRV+1) ); if ( (last_us_tick > us_tick) && (last_us_tick < 0xFFFFFC00) ) { us_tick += 1000; } last_us_tick = us_tick; return us_tick; } #endif void us_ticker_set_interrupt(timestamp_t timestamp) { uint32_t cur_time_us; uint32_t duration_us; uint32_t timer_tick = 0; cur_time_us = us_ticker_read(); if ((uint32_t)timestamp >= cur_time_us) { duration_us = (uint32_t)timestamp - cur_time_us; } else { duration_us = 0xffffffff - cur_time_us + (uint32_t)timestamp; } if (duration_us < TIMER_TICK_US) { duration_us = TIMER_TICK_US; // at least 1 tick } timer_tick = (uint32_t)((float)duration_us / 1000000 *32000); RTIM_ChangePeriod(TIMx_LP[APP_TIM_ID], timer_tick); } void us_ticker_disable_interrupt(void) { RTIM_Cmd(TIMx_LP[APP_TIM_ID], DISABLE); } void us_ticker_clear_interrupt(void) { RTIM_INTClear(TIMx_LP[APP_TIM_ID]);//AembaD TODO }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/us_ticker.c
C
apache-2.0
3,546
/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stddef.h> #include "us_ticker_api.h" #include "cmsis.h" static ticker_event_handler event_handler; static ticker_event_t *head = NULL; void us_ticker_set_handler(ticker_event_handler handler) { us_ticker_init(); event_handler = handler; } void us_ticker_irq_handler(void) { us_ticker_clear_interrupt(); /* Go through all the pending TimerEvents */ while (1) { if (head == NULL) { /* There are no more TimerEvents left, so disable matches. */ us_ticker_disable_interrupt(); return; } if ((int)(head->timestamp - us_ticker_read()) <= 0) { /* This event was in the past: point to the following one and execute its handler */ ticker_event_t *p = head; head = head->next; if (event_handler != NULL) { event_handler(p->id); // NOTE: the handler can set new events } /* Note: We continue back to examining the head because calling the */ /* event handler may have altered the chain of pending events. */ } else { /* This event and the following ones in the list are in the future: set it as next interrupt and return */ us_ticker_set_interrupt(head->timestamp); return; } } } void us_ticker_insert_event(ticker_event_t *obj, timestamp_t timestamp, uint32_t id) { /* disable interrupts for the duration of the function */ __disable_irq(); /* initialise our data */ obj->timestamp = timestamp; obj->id = id; /* Go through the list until we either reach the end, or find */ /* an element this should come before (which is possibly the head). */ ticker_event_t *prev = NULL, *p = head; while (p != NULL) { /* check if we come before p */ if ((int)(timestamp - p->timestamp) <= 0) { break; } /* go to the next element */ prev = p; p = p->next; } /* if prev is NULL we're at the head */ if (prev == NULL) { head = obj; us_ticker_set_interrupt(timestamp); } else { prev->next = obj; } /* if we're at the end p will be NULL, which is correct */ obj->next = p; __enable_irq(); } void us_ticker_remove_event(ticker_event_t *obj) { __disable_irq(); /* remove this object from the list */ if (head == obj) { /* first in the list, so just drop me */ head = obj->next; if (head == NULL) { us_ticker_disable_interrupt(); } else { us_ticker_set_interrupt(head->timestamp); } } else { /* find the object before me, then drop me */ ticker_event_t* p = head; while (p != NULL) { if (p->next == obj) { p->next = obj->next; break; } p = p->next; } } __enable_irq(); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/us_ticker_api.c
C
apache-2.0
3,144
/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "wait_api.h" #include "us_ticker_api.h" //extern void DelayUs(u32 us); extern void DelayUs(unsigned int us); void wait(float s) { DelayUs((int)(s * 1000000.0f)); } void wait_ms(int ms) { DelayUs(ms * 1000); } void wait_us(int us) { DelayUs(us); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/wait_api.c
C
apache-2.0
896
/** mbed Microcontroller Library ****************************************************************************** * @file wdt_api.c * @author * @version V1.0.0 * @date 2016-08-01 * @brief This file provides mbed API for WDG. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "objects.h" #include "ameba_soc.h" #include "wdt_api.h" #include "cmsis.h" /** @addtogroup AmebaD_Mbed_API * @{ */ /** @defgroup MBED_WDG * @brief MBED_WDG driver modules. * @{ */ /** @defgroup MBED_WDG_Exported_Functions MBED_WDG Exported Functions * @{ */ /** * @brief Initializes the watch dog, include time setting, mode register * @param timeout_ms: the watch-dog timer timeout value, in ms. * default action of timeout is to reset the whole system. * @retval none */ void watchdog_init(uint32_t timeout_ms) { WDG_InitTypeDef WDG_InitStruct; u32 CountProcess; u32 DivFacProcess; WDG_Scalar(timeout_ms, &CountProcess, &DivFacProcess); WDG_InitStruct.CountProcess = CountProcess; WDG_InitStruct.DivFacProcess = DivFacProcess; WDG_Init(&WDG_InitStruct); } /** * @brief Start the watchdog counting * @param None * @retval none */ void watchdog_start(void) { WDG_Cmd(ENABLE); } /** * @brief Stop the watchdog counting * @param None * @retval none */ void watchdog_stop(void) { WDG_Cmd(DISABLE); } /** * @brief Refresh the watchdog counting to prevent WDT timeout * @param None * @retval none */ void watchdog_refresh(void) { WDG_Refresh(); } /** * @brief Switch the watchdog timer to interrupt mode and * register a watchdog timer timeout interrupt handler. * The interrupt handler will be called when the watch-dog * timer is timeout. * @param handler: the callback function for WDT timeout interrupt. * @param id: the parameter for the callback function * @retval none */ void watchdog_irq_init(wdt_irq_handler handler, uint32_t id) { WDG_IrqInit((VOID*)handler, (u32)id); } /** * @} */ /** * @} */ /** * @} */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/mbed/targets/hal/rtl8721d/wdt_api.c
C
apache-2.0
2,479
#include "dhcps.h" #include "lwip/tcpip.h" //static struct dhcp_server_state dhcp_server_state_machine; static uint8_t dhcp_server_state_machine = DHCP_SERVER_STATE_IDLE; /* recorded the client MAC addr(default sudo mac) */ //static uint8_t dhcps_record_first_client_mac[6] = {0xff,0xff,0xff,0xff,0xff,0xff}; /* recorded transaction ID (default sudo id)*/ static uint8_t dhcp_recorded_xid[4] = {0xff, 0xff, 0xff, 0xff}; /* UDP Protocol Control Block(PCB) */ static struct udp_pcb *dhcps_pcb; static ip_addr_t dhcps_send_broadcast_address; static ip_addr_t dhcps_local_address; static ip_addr_t dhcps_pool_start; static ip_addr_t dhcps_pool_end; static ip_addr_t dhcps_local_mask; static ip_addr_t dhcps_local_gateway; static ip_addr_t dhcps_network_id; static ip_addr_t dhcps_subnet_broadcast; static ip_addr_t dhcps_allocated_client_address; static int dhcps_addr_pool_set = 0; static ip_addr_t dhcps_addr_pool_start; static ip_addr_t dhcps_addr_pool_end; #if 1 static ip_addr_t dhcps_owned_first_ip; static ip_addr_t dhcps_owned_last_ip; static uint8_t dhcps_num_of_available_ips; #endif static struct dhcp_msg *dhcp_message_repository; static int dhcp_message_total_options_lenth; /* allocated IP range */ static struct table ip_table; static ip_addr_t client_request_ip; static uint8_t client_addr[6]; static _sema dhcps_ip_table_semaphore; static struct netif * dhcps_netif = NULL; /** * @brief latch the specific ip in the ip table. * @param d the specific index * @retval None. */ #if (!IS_USE_FIXED_IP) static void mark_ip_in_table(uint8_t d) { #if (debug_dhcps) printf("\r\nmark ip %d\r\n",d); #endif rtw_down_sema(&dhcps_ip_table_semaphore); if (0 < d && d <= 32) { ip_table.ip_range[0] = MARK_RANGE1_IP_BIT(ip_table, d); #if (debug_dhcps) printf("\r\n ip_table.ip_range[0] = 0x%x\r\n",ip_table.ip_range[0]); #endif } else if (32 < d && d <= 64) { ip_table.ip_range[1] = MARK_RANGE2_IP_BIT(ip_table, (d - 32)); #if (debug_dhcps) printf("\r\n ip_table.ip_range[1] = 0x%x\r\n",ip_table.ip_range[1]); #endif } else if (64 < d && d <= 96) { ip_table.ip_range[2] = MARK_RANGE3_IP_BIT(ip_table, (d - 64)); #if (debug_dhcps) printf("\r\n ip_table.ip_range[2] = 0x%x\r\n",ip_table.ip_range[2]); #endif } else if (96 < d && d <= 128) { ip_table.ip_range[3] = MARK_RANGE4_IP_BIT(ip_table, (d - 96)); #if (debug_dhcps) printf("\r\n ip_table.ip_range[3] = 0x%x\r\n",ip_table.ip_range[3]); #endif } else if(128 < d && d <= 160) { ip_table.ip_range[4] = MARK_RANGE5_IP_BIT(ip_table, d); #if (debug_dhcps) printf("\r\n ip_table.ip_range[4] = 0x%x\r\n",ip_table.ip_range[4]); #endif } else if (160 < d && d <= 192) { ip_table.ip_range[5] = MARK_RANGE6_IP_BIT(ip_table, (d - 160)); #if (debug_dhcps) printf("\r\n ip_table.ip_range[5] = 0x%x\r\n",ip_table.ip_range[5]); #endif } else if (192 < d && d <= 224) { ip_table.ip_range[6] = MARK_RANGE7_IP_BIT(ip_table, (d - 192)); #if (debug_dhcps) printf("\r\n ip_table.ip_range[6] = 0x%x\r\n",ip_table.ip_range[6]); #endif } else if (224 < d) { ip_table.ip_range[7] = MARK_RANGE8_IP_BIT(ip_table, (d - 224)); #if (debug_dhcps) printf("\r\n ip_table.ip_range[7] = 0x%x\r\n",ip_table.ip_range[7]); #endif } else { printf("\r\n Request ip over the range(1-128) \r\n"); } rtw_up_sema(&dhcps_ip_table_semaphore); } #ifdef CONFIG_DHCPS_KEPT_CLIENT_INFO static void save_client_addr(ip_addr_t *client_ip, uint8_t *hwaddr) { uint8_t d = (uint8_t)ip4_addr4(client_ip); rtw_down_sema(&dhcps_ip_table_semaphore); memcpy(ip_table.client_mac[d], hwaddr, 6); #if (debug_dhcps) printf("\r\n%s: ip %d.%d.%d.%d, hwaddr %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x\n", __func__, ip4_addr1(client_ip), ip4_addr2(client_ip), ip4_addr3(client_ip), ip4_addr4(client_ip), hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5]); #endif rtw_up_sema(&dhcps_ip_table_semaphore); } static uint8_t check_client_request_ip(ip_addr_t *client_req_ip, uint8_t *hwaddr) { /* To avoid gcc warnings */ ( void ) client_req_ip; int ip_addr4 = 0, i; #if (debug_dhcps) printf("\r\n%s: ip %d.%d.%d.%d, hwaddr %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x\n", __func__, ip4_addr1(client_req_ip), ip4_addr2(client_req_ip), ip4_addr3(client_req_ip), ip4_addr4(client_req_ip), hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5]); #endif rtw_down_sema(&dhcps_ip_table_semaphore); for(i=DHCP_POOL_START;i<=DHCP_POOL_END;i++) { //printf("client[%d] = %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x\n",i,ip_table.client_mac[i][0],ip_table.client_mac[i][0],ip_table.client_mac[i][1],ip_table.client_mac[i][2],ip_table.client_mac[i][3],ip_table.client_mac[i][4],ip_table.client_mac[i][5]); if(memcmp(ip_table.client_mac[i], hwaddr, 6) == 0){ if((ip_table.ip_range[i/32]>>(i%32-1)) & 1){ ip_addr4 = i; break; } } } rtw_up_sema(&dhcps_ip_table_semaphore); if(i == DHCP_POOL_END+1) ip_addr4 = 0; Exit: return ip_addr4; } static void dump_client_table() { #if 0 int i; uint8_t *p = NULL; printf("\r\nip_range: %2.2x %2.2x %2.2x %2.2x %2.2x %2.2x %2.2x %2.2x", ip_table.ip_range[0], ip_table.ip_range[1], ip_table.ip_range[2], ip_table.ip_range[3], ip_table.ip_range[4], ip_table.ip_range[5], ip_table.ip_range[6], ip_table.ip_range[7]); for(i=1; i<=DHCPS_MAX_CLIENT_NUM; i++) { p = ip_table.client_mac[i]; printf("\r\nClient[%d]: %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x", i, p[0], p[1], p[2], p[3], p[4], p[5]); } printf("\r\n"); #endif } #endif //CONFIG_DHCPS_KEPT_CLIENT_INFO #endif /** * @brief get one usable ip from the ip table of dhcp server. * @param: None * @retval the usable index which represent the ip4_addr(ip) of allocated ip addr. */ #if (!IS_USE_FIXED_IP) static uint8_t search_next_ip(void) { uint8_t range_count, offset_count; uint8_t start, end; volatile uint8_t max_count; if(dhcps_addr_pool_set){ start = (uint8_t)ip4_addr4(&dhcps_addr_pool_start); end = (uint8_t)ip4_addr4(&dhcps_addr_pool_end); }else{ start = 0; end = 255; } rtw_down_sema(&dhcps_ip_table_semaphore); for (range_count = 0; range_count < (max_count = 8); range_count++) { for (offset_count = 0;offset_count < 32; offset_count++) { if ((((ip_table.ip_range[range_count] >> offset_count) & 0x01) == 0) &&(((range_count * 32) + (offset_count + 1)) >= start) &&(((range_count * 32) + (offset_count + 1)) <= end)) { rtw_up_sema(&dhcps_ip_table_semaphore); return ((range_count * 32) + (offset_count + 1)); } } } rtw_up_sema(&dhcps_ip_table_semaphore); return 0; } #endif /** * @brief fill in the option field with message type of a dhcp message. * @param msg_option_base_addr: the addr be filled start. * message_type: the type code you want to fill in * @retval the start addr of the next dhcp option. */ static uint8_t *add_msg_type(uint8_t *msg_option_base_addr, uint8_t message_type) { uint8_t *option_start; msg_option_base_addr[0] = DHCP_OPTION_CODE_MSG_TYPE; msg_option_base_addr[1] = DHCP_OPTION_LENGTH_ONE; msg_option_base_addr[2] = message_type; option_start = msg_option_base_addr + 3; if (DHCP_MESSAGE_TYPE_NAK == message_type) *option_start++ = DHCP_OPTION_CODE_END; return option_start; } static uint8_t *fill_one_option_content(uint8_t *option_base_addr, uint8_t option_code, uint8_t option_length, void *copy_info) { uint8_t *option_data_base_address; uint8_t *next_option_start_address = NULL; option_base_addr[0] = option_code; option_base_addr[1] = option_length; option_data_base_address = option_base_addr + 2; switch (option_length) { case DHCP_OPTION_LENGTH_FOUR: memcpy(option_data_base_address, copy_info, DHCP_OPTION_LENGTH_FOUR); next_option_start_address = option_data_base_address + 4; break; case DHCP_OPTION_LENGTH_TWO: memcpy(option_data_base_address, copy_info, DHCP_OPTION_LENGTH_TWO); next_option_start_address = option_data_base_address + 2; break; case DHCP_OPTION_LENGTH_ONE: memcpy(option_data_base_address, copy_info, DHCP_OPTION_LENGTH_ONE); next_option_start_address = option_data_base_address + 1; break; } return next_option_start_address; } /** * @brief fill in the needed content of the dhcp offer message. * @param optptr the addr which the tail of dhcp magic field. * @retval 0, add ok * -1, add fail */ static int8_t add_offer_options(uint8_t *option_start_address) { // Total minimum len = 6+6+6+6+6+6+4+3+1 = 44 uint8_t *temp_option_addr = option_start_address; int max_addable_option_len = dhcp_message_total_options_lenth - 4 - 3; // -magic-type if(option_start_address == NULL) goto ERROR; /* add DHCP options 1. The subnet mask option specifies the client's subnet mask */ if(temp_option_addr + 6 -option_start_address <= max_addable_option_len) { temp_option_addr = fill_one_option_content(option_start_address, DHCP_OPTION_CODE_SUBNET_MASK, DHCP_OPTION_LENGTH_FOUR,(void *)&dhcps_local_mask); }else{ goto ERROR; } /* add DHCP options 3 (i.e router(gateway)). The time server option specifies a list of RFC 868 [6] time servers available to the client. */ if(temp_option_addr + 6 -option_start_address <= max_addable_option_len) { temp_option_addr = fill_one_option_content(temp_option_addr, DHCP_OPTION_CODE_ROUTER, DHCP_OPTION_LENGTH_FOUR, (void *)&dhcps_local_address); }else{ goto ERROR; } /* add DHCP options 6 (i.e DNS). The option specifies a list of DNS servers available to the client. */ if(temp_option_addr + 6 -option_start_address <= max_addable_option_len) { temp_option_addr = fill_one_option_content(temp_option_addr, DHCP_OPTION_CODE_DNS_SERVER, DHCP_OPTION_LENGTH_FOUR, (void *)&dhcps_local_address); }else{ goto ERROR; } /* add DHCP options 51. This option is used to request a lease time for the IP address. */ if(temp_option_addr + 6 -option_start_address <= max_addable_option_len) { temp_option_addr = fill_one_option_content(temp_option_addr, DHCP_OPTION_CODE_LEASE_TIME, DHCP_OPTION_LENGTH_FOUR, (void *)&dhcp_option_lease_time); }else{ goto ERROR; } /* add DHCP options 54. The identifier is the IP address of the selected server. */ if(temp_option_addr + 6 -option_start_address <= max_addable_option_len) { temp_option_addr = fill_one_option_content(temp_option_addr, DHCP_OPTION_CODE_SERVER_ID, DHCP_OPTION_LENGTH_FOUR, (void *)&dhcps_local_address); }else{ goto ERROR; } /* add DHCP options 28. This option specifies the broadcast address in use on client's subnet.*/ if(temp_option_addr + 6 -option_start_address <= max_addable_option_len) { temp_option_addr = fill_one_option_content(temp_option_addr, DHCP_OPTION_CODE_BROADCAST_ADDRESS, DHCP_OPTION_LENGTH_FOUR, (void *)&dhcps_subnet_broadcast); }else{ goto ERROR; } /* add DHCP options 26. This option specifies the Maximum transmission unit to use */ if(temp_option_addr + 4 -option_start_address <= max_addable_option_len) { temp_option_addr = fill_one_option_content(temp_option_addr, DHCP_OPTION_CODE_INTERFACE_MTU, DHCP_OPTION_LENGTH_TWO, (void *) &dhcp_option_interface_mtu);//dhcp_option_interface_mtu_576); }else{ goto ERROR; } /* add DHCP options 31. This option specifies whether or not the client should solicit routers */ if(temp_option_addr + 3 -option_start_address <= max_addable_option_len) { temp_option_addr = fill_one_option_content(temp_option_addr, DHCP_OPTION_CODE_PERFORM_ROUTER_DISCOVERY, DHCP_OPTION_LENGTH_ONE, NULL); }else{ goto ERROR; } // END if(temp_option_addr + 1 -option_start_address <= max_addable_option_len) { *temp_option_addr++ = DHCP_OPTION_CODE_END; }else{ goto ERROR; } return 0; ERROR: printf("\r\n[%s] error: add options fail !!", __func__); return -1; } /** * @brief fill in common content of a dhcp message. * @param m the pointer which point to the dhcp message store in. * @retval None. */ static void dhcps_initialize_message(struct dhcp_msg *dhcp_message_repository) { dhcp_message_repository->op = DHCP_MESSAGE_OP_REPLY; dhcp_message_repository->htype = DHCP_MESSAGE_HTYPE; dhcp_message_repository->hlen = DHCP_MESSAGE_HLEN; dhcp_message_repository->hops = 0; memcpy((char *)dhcp_recorded_xid, (char *) dhcp_message_repository->xid, sizeof(dhcp_message_repository->xid)); dhcp_message_repository->secs = 0; dhcp_message_repository->flags = htons(BOOTP_BROADCAST); memcpy((char *)dhcp_message_repository->yiaddr, (char *)&dhcps_allocated_client_address, sizeof(dhcp_message_repository->yiaddr)); memset((char *)dhcp_message_repository->ciaddr, 0, sizeof(dhcp_message_repository->ciaddr)); memset((char *)dhcp_message_repository->siaddr, 0, sizeof(dhcp_message_repository->siaddr)); memset((char *)dhcp_message_repository->giaddr, 0, sizeof(dhcp_message_repository->giaddr)); memset((char *)dhcp_message_repository->sname, 0, sizeof(dhcp_message_repository->sname)); memset((char *)dhcp_message_repository->file, 0, sizeof(dhcp_message_repository->file)); memset((char *)dhcp_message_repository->options, 0, dhcp_message_total_options_lenth); memcpy((char *)dhcp_message_repository->options, (char *)dhcp_magic_cookie, sizeof(dhcp_magic_cookie)); } /** * @brief init and fill in the needed content of dhcp offer message. * @param packet_buffer packet buffer for UDP. * @retval None. */ static void dhcps_send_offer(struct pbuf *packet_buffer) { uint8_t temp_ip = 0; struct pbuf *newly_malloc_packet_buffer = NULL; // newly malloc a longer pbuf for dhcp offer rather than using the short pbuf from dhcp discover newly_malloc_packet_buffer = pbuf_alloc(PBUF_TRANSPORT, DHCP_MSG_LEN + DHCP_OFFER_OPTION_TOTAL_LENGTH_MAX, PBUF_RAM); if(newly_malloc_packet_buffer == NULL) { printf("\r\n[%s] error: pbuf alloc fail !", __func__); return; } if(pbuf_copy(newly_malloc_packet_buffer, packet_buffer) != ERR_OK) { printf("\r\n[%s] error: pbuf copy fail !", __func__); pbuf_free(newly_malloc_packet_buffer); return; } dhcp_message_total_options_lenth = DHCP_OFFER_OPTION_TOTAL_LENGTH_MAX; dhcp_message_repository = (struct dhcp_msg *)newly_malloc_packet_buffer->payload; #if (!IS_USE_FIXED_IP) #ifdef CONFIG_DHCPS_KEPT_CLIENT_INFO temp_ip = check_client_request_ip(&client_request_ip, client_addr); #endif /* create new client ip */ if(temp_ip == 0) temp_ip = search_next_ip(); #if (debug_dhcps) printf("\r\n temp_ip = %d",temp_ip); #endif if (temp_ip == 0) { #if 0 memset(&ip_table, 0, sizeof(struct table)); mark_ip_in_table((uint8_t)ip4_addr4(&dhcps_local_address)); printf("\r\n reset ip table!!\r\n"); #endif printf("\r\n No useable ip!!!!\r\n"); } printf("\n\r[%d]DHCP assign ip = %d.%d.%d.%d\n", rtw_get_current_time(), ip4_addr1(&dhcps_network_id),ip4_addr2(&dhcps_network_id),ip4_addr3(&dhcps_network_id),temp_ip); IP4_ADDR(&dhcps_allocated_client_address, (ip4_addr1(&dhcps_network_id)), ip4_addr2(&dhcps_network_id), ip4_addr3(&dhcps_network_id), temp_ip); #endif dhcps_initialize_message(dhcp_message_repository); if(add_offer_options(add_msg_type(&dhcp_message_repository->options[4], DHCP_MESSAGE_TYPE_OFFER)) == 0) udp_sendto_if(dhcps_pcb, newly_malloc_packet_buffer, &dhcps_send_broadcast_address, DHCP_CLIENT_PORT, dhcps_netif); pbuf_free(newly_malloc_packet_buffer); } /** * @brief init and fill in the needed content of dhcp nak message. * @param packet buffer packet buffer for UDP. * @retval None. */ static void dhcps_send_nak(struct pbuf *packet_buffer) { dhcp_message_repository = (struct dhcp_msg *)packet_buffer->payload; dhcps_initialize_message(dhcp_message_repository); add_msg_type(&dhcp_message_repository->options[4], DHCP_MESSAGE_TYPE_NAK); udp_sendto_if(dhcps_pcb, packet_buffer, &dhcps_send_broadcast_address, DHCP_CLIENT_PORT, dhcps_netif); } /** * @brief init and fill in the needed content of dhcp ack message. * @param packet buffer packet buffer for UDP. * @retval None. */ static void dhcps_send_ack(struct pbuf *packet_buffer) { dhcp_message_repository = (struct dhcp_msg *)packet_buffer->payload; dhcps_initialize_message(dhcp_message_repository); if(add_offer_options(add_msg_type(&dhcp_message_repository->options[4], DHCP_MESSAGE_TYPE_ACK)) == 0) udp_sendto_if(dhcps_pcb, packet_buffer, &dhcps_send_broadcast_address, DHCP_CLIENT_PORT, dhcps_netif); } /** * @brief according by the input message type to reflect the correspond state. * @param option_message_type the input server state * @retval the server state which already transfer to. */ uint8_t dhcps_handle_state_machine_change(uint8_t option_message_type) { switch (option_message_type) { case DHCP_MESSAGE_TYPE_DECLINE: #if (debug_dhcps) printf("\r\nget message DHCP_MESSAGE_TYPE_DECLINE\n"); #endif dhcp_server_state_machine = DHCP_SERVER_STATE_IDLE; break; case DHCP_MESSAGE_TYPE_DISCOVER: #if (debug_dhcps) printf("\r\nget message DHCP_MESSAGE_TYPE_DISCOVER\n"); #endif if (dhcp_server_state_machine == DHCP_SERVER_STATE_IDLE) { dhcp_server_state_machine = DHCP_SERVER_STATE_OFFER; } break; case DHCP_MESSAGE_TYPE_REQUEST: #if (debug_dhcps) printf("\r\n[%d]get message DHCP_MESSAGE_TYPE_REQUEST\n", rtw_get_current_time()); #endif #if (!IS_USE_FIXED_IP) #if (debug_dhcps) printf("\r\ndhcp_server_state_machine=%d", dhcp_server_state_machine); printf("\r\ndhcps_allocated_client_address=%d.%d.%d.%d", ip4_addr1(&dhcps_allocated_client_address), ip4_addr2(&dhcps_allocated_client_address), ip4_addr3(&dhcps_allocated_client_address), ip4_addr4(&dhcps_allocated_client_address)); printf("\r\nclient_request_ip=%d.%d.%d.%d\n", ip4_addr1(&client_request_ip), ip4_addr2(&client_request_ip), ip4_addr3(&client_request_ip), ip4_addr4(&client_request_ip)); #endif if (dhcp_server_state_machine == DHCP_SERVER_STATE_OFFER) { if (ip4_addr4(&dhcps_allocated_client_address) != 0) { if (memcmp((void *)&dhcps_allocated_client_address, (void *)&client_request_ip, 4) == 0) { dhcp_server_state_machine = DHCP_SERVER_STATE_ACK; } else { dhcp_server_state_machine = DHCP_SERVER_STATE_NAK; } } else { dhcp_server_state_machine = DHCP_SERVER_STATE_NAK; } #ifdef CONFIG_DHCPS_KEPT_CLIENT_INFO } else if(dhcp_server_state_machine == DHCP_SERVER_STATE_IDLE){ uint8_t ip_addr4 = check_client_request_ip(&client_request_ip, client_addr); if(ip_addr4 > 0){ IP4_ADDR(&dhcps_allocated_client_address, (ip4_addr1(&dhcps_network_id)), ip4_addr2(&dhcps_network_id), ip4_addr3(&dhcps_network_id), ip_addr4); dhcp_server_state_machine = DHCP_SERVER_STATE_ACK; }else{ dhcp_server_state_machine = DHCP_SERVER_STATE_NAK; } #endif } else { dhcp_server_state_machine = DHCP_SERVER_STATE_NAK; } #else if (!(dhcp_server_state_machine == DHCP_SERVER_STATE_ACK || dhcp_server_state_machine == DHCP_SERVER_STATE_NAK)) { dhcp_server_state_machine = DHCP_SERVER_STATE_NAK; } #endif break; case DHCP_MESSAGE_TYPE_RELEASE: printf("get message DHCP_MESSAGE_TYPE_RELEASE\n"); dhcp_server_state_machine = DHCP_SERVER_STATE_IDLE; break; } return dhcp_server_state_machine; } /** * @brief parse the dhcp message option part. * @param optptr: the addr of the first option field. * len: the total length of all option fields. * @retval dhcp server state. */ static uint8_t dhcps_handle_msg_options(uint8_t *option_start, int16_t total_option_length) { int16_t option_message_type = 0; uint8_t *option_end = option_start + total_option_length; //dhcp_server_state_machine = DHCP_SERVER_STATE_IDLE; /* begin process the dhcp option info */ while (option_start < option_end) { switch ((uint8_t)*option_start) { case DHCP_OPTION_CODE_MSG_TYPE: option_message_type = *(option_start + 2); // 2 => code(1)+lenth(1) break; case DHCP_OPTION_CODE_REQUEST_IP_ADDRESS : #if IS_USE_FIXED_IP if (memcmp((char *)&dhcps_allocated_client_address, (char *)option_start + 2, 4) == 0) dhcp_server_state_machine = DHCP_SERVER_STATE_ACK; else dhcp_server_state_machine = DHCP_SERVER_STATE_NAK; #else memcpy((char *)&client_request_ip, (char *)option_start + 2, 4); #endif break; } // calculate the options offset to get next option's base addr option_start += option_start[1] + 2; // optptr[1]: length value + (code(1)+ Len(1)) } return dhcps_handle_state_machine_change(option_message_type); } /** * @brief get message from buffer then check whether it is dhcp related or not. * if yes , parse it more to undersatnd the client's request. * @param same as recv callback function definition * @retval if message is dhcp related then return dhcp server state, * otherwise return 0 */ static uint8_t dhcps_check_msg_and_handle_options(struct pbuf *packet_buffer) { int dhcp_message_option_offset; dhcp_message_repository = (struct dhcp_msg *)packet_buffer->payload; dhcp_message_option_offset = ((int)dhcp_message_repository->options - (int)packet_buffer->payload); dhcp_message_total_options_lenth = (packet_buffer->len - dhcp_message_option_offset); memcpy(client_addr, dhcp_message_repository->chaddr, 6); /* check the magic number,if correct parse the content of options */ if (memcmp((char *)dhcp_message_repository->options, (char *)dhcp_magic_cookie, sizeof(dhcp_magic_cookie)) == 0) { return dhcps_handle_msg_options(&dhcp_message_repository->options[4], (dhcp_message_total_options_lenth - 4)); } return 0; } /** * @brief handle imcoming dhcp message and response message to client * @param same as recv callback function definition * @retval None */ static void dhcps_receive_udp_packet_handler(void *arg, struct udp_pcb *udp_pcb, struct pbuf *udp_packet_buffer, struct ip_addr *sender_addr, uint16_t sender_port) { /* To avoid gcc warnings */ ( void ) sender_addr; ( void ) arg; int16_t total_length_of_packet_buffer; struct pbuf *merged_packet_buffer = NULL; dhcp_message_repository = (struct dhcp_msg *)udp_packet_buffer->payload; if (udp_packet_buffer == NULL) { printf("\n\r Error!!!! System doesn't allocate any buffer \n\r"); return; } if (sender_port == DHCP_CLIENT_PORT) { total_length_of_packet_buffer = udp_packet_buffer->tot_len; if (udp_packet_buffer->next != NULL) { merged_packet_buffer = pbuf_coalesce(udp_packet_buffer, PBUF_TRANSPORT); if (merged_packet_buffer->tot_len != total_length_of_packet_buffer) { pbuf_free(udp_packet_buffer); return; } udp_packet_buffer = merged_packet_buffer; } switch (dhcps_check_msg_and_handle_options(udp_packet_buffer)) { case DHCP_SERVER_STATE_OFFER: #if (debug_dhcps) printf("%s DHCP_SERVER_STATE_OFFER\n",__func__); #endif dhcps_send_offer(udp_packet_buffer); break; case DHCP_SERVER_STATE_ACK: #if (debug_dhcps) printf("%s DHCP_SERVER_STATE_ACK\n",__func__); #endif dhcps_send_ack(udp_packet_buffer); #if (!IS_USE_FIXED_IP) mark_ip_in_table((uint8_t)ip4_addr4(&dhcps_allocated_client_address)); #ifdef CONFIG_DHCPS_KEPT_CLIENT_INFO save_client_addr(&dhcps_allocated_client_address, client_addr); memset(&client_request_ip, 0, sizeof(client_request_ip)); memset(&client_addr, 0, sizeof(client_addr)); memset(&dhcps_allocated_client_address, 0, sizeof(dhcps_allocated_client_address)); #if (debug_dhcps) dump_client_table(); #endif #endif #endif dhcp_server_state_machine = DHCP_SERVER_STATE_IDLE; break; case DHCP_SERVER_STATE_NAK: #if (debug_dhcps) printf("%s DHCP_SERVER_STATE_NAK\n",__func__); #endif dhcps_send_nak(udp_packet_buffer); dhcp_server_state_machine = DHCP_SERVER_STATE_IDLE; break; case DHCP_OPTION_CODE_END: #if (debug_dhcps) printf("%s DHCP_OPTION_CODE_END\n",__func__); #endif break; } } /* free the UDP connection, so we can accept new clients */ udp_disconnect(udp_pcb); /* Free the packet buffer */ if (merged_packet_buffer != NULL) pbuf_free(merged_packet_buffer); else pbuf_free(udp_packet_buffer); } void dhcps_set_addr_pool(int addr_pool_set, ip_addr_t * addr_pool_start, ip_addr_t *addr_pool_end) { //uint8_t *ip; if(addr_pool_set){ dhcps_addr_pool_set = 1; memcpy(&dhcps_addr_pool_start, addr_pool_start, sizeof(ip_addr_t)); //ip = &dhcps_addr_pool_start; //ip[3] = 100; memcpy(&dhcps_addr_pool_end, addr_pool_end, sizeof(ip_addr_t)); //ip = &dhcps_addr_pool_end; //ip[3] = 200; }else{ dhcps_addr_pool_set = 0; } } /** * @brief Initialize dhcp server. * @param None. * @retval None. * Note, for now,we assume the server latch ip 192.168.1.1 and support dynamic * or fixed IP allocation. */ void dhcps_init(struct netif * pnetif) { uint8_t *ip; // printf("dhcps_init,wlan:%c\n\r",pnetif->name[1]); #ifdef CONFIG_DHCPS_KEPT_CLIENT_INFO memset(&ip_table, 0, sizeof(struct table)); // int i = 0; // for(i=0; i< DHCPS_MAX_CLIENT_NUM+2; i++) // memset(ip_table.client_mac[i], 0, 6); // dump_client_table(); #endif dhcps_netif = pnetif; if (dhcps_pcb != NULL) { udp_remove(dhcps_pcb); dhcps_pcb = NULL; } dhcps_pcb = udp_new(); if (dhcps_pcb == NULL) { printf("\n\r Error!!!upd_new error \n\r"); return; } IP4_ADDR(&dhcps_send_broadcast_address, 255, 255, 255, 255); /* get net info from net interface */ memcpy(&dhcps_local_address, &pnetif->ip_addr, sizeof( ip_addr_t)); memcpy(&dhcps_local_mask, &pnetif->netmask, sizeof(ip_addr_t)); memcpy(&dhcps_local_gateway, &pnetif->gw, sizeof(ip_addr_t)); /* calculate the usable network ip range */ dhcps_network_id.addr = ((pnetif->ip_addr.addr) & (pnetif->netmask.addr)); dhcps_subnet_broadcast.addr = ((dhcps_network_id.addr | ~(pnetif->netmask.addr))); #if 1 dhcps_owned_first_ip.addr = htonl((ntohl(dhcps_network_id.addr) + 1)); dhcps_owned_last_ip.addr = htonl(ntohl(dhcps_subnet_broadcast.addr) - 1); dhcps_num_of_available_ips = ((ntohl(dhcps_owned_last_ip.addr) - ntohl(dhcps_owned_first_ip.addr)) + 1); #endif #if CONFIG_EXAMPLE_UART_ATCMD || CONFIG_EXAMPLE_SPI_ATCMD #if IP_SOF_BROADCAST dhcps_pcb->so_options|=SOF_BROADCAST; #endif /* IP_SOF_BROADCAST */ #endif #if IS_USE_FIXED_IP IP4_ADDR(&dhcps_allocated_client_address, ip4_addr1(&dhcps_local_address) , ip4_addr2(&dhcps_local_address), ip4_addr3(&dhcps_local_address), (ip4_addr4(&dhcps_local_address)) + 1 ); #else if (dhcps_ip_table_semaphore.hdl != NULL) { rtw_free_sema(&dhcps_ip_table_semaphore); dhcps_ip_table_semaphore.hdl = NULL; } rtw_init_sema(&dhcps_ip_table_semaphore, 1); //dhcps_ip_table = (struct ip_table *)(pvPortMalloc(sizeof(struct ip_table))); memset(&ip_table, 0, sizeof(struct table)); mark_ip_in_table((uint8_t)ip4_addr4(&dhcps_local_address)); mark_ip_in_table((uint8_t)ip4_addr4(&dhcps_local_gateway)); #if 0 for (i = 1; i < ip4_addr4(&dhcps_local_address); i++) { mark_ip_in_table(i); } #endif #endif if(dhcps_addr_pool_start.addr== 0 && dhcps_addr_pool_end.addr == 0) { memcpy(&dhcps_pool_start,&dhcps_local_address,sizeof(ip_addr_t)); ip = (uint8_t *)&dhcps_pool_start; ip[3] = DHCP_POOL_START; memcpy(&dhcps_pool_end,&dhcps_local_address,sizeof(ip_addr_t)); ip = (uint8_t *)&dhcps_pool_end; ip[3] = DHCP_POOL_END; dhcps_set_addr_pool(1,&dhcps_pool_start,&dhcps_pool_end); } udp_bind(dhcps_pcb, IP_ADDR_ANY, DHCP_SERVER_PORT); udp_recv(dhcps_pcb, dhcps_receive_udp_packet_handler, NULL); } void dhcps_deinit(void) { if (dhcps_pcb != NULL) { udp_remove(dhcps_pcb); dhcps_pcb = NULL; } if (dhcps_ip_table_semaphore.hdl != NULL) { rtw_free_sema(&dhcps_ip_table_semaphore); dhcps_ip_table_semaphore.hdl = NULL; } }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/network/dhcp/dhcps.c
C
apache-2.0
28,083
#ifndef __DHCPS_H__ #define __DHCPS_H__ #include "lwip/arch.h" #include "lwip/netif.h" #include "lwip/udp.h" #include "lwip/stats.h" #include "lwip/sys.h" #include "osdep_service.h" #include <platform/platform_stdlib.h> #define CONFIG_DHCPS_KEPT_CLIENT_INFO #define DHCP_POOL_START 100 #define DHCP_POOL_END 200 #define DHCPS_MAX_CLIENT_NUM (DHCP_POOL_END-DHCP_POOL_START+1) #define IS_USE_FIXED_IP 0 #define debug_dhcps 0 /* dhcp server states */ #define DHCP_SERVER_STATE_OFFER (1) #define DHCP_SERVER_STATE_DECLINE (2) #define DHCP_SERVER_STATE_ACK (3) #define DHCP_SERVER_STATE_NAK (4) #define DHCP_SERVER_STATE_IDLE (5) #define BOOTP_BROADCAST (0x8000) #define DHCP_MESSAGE_OP_REQUEST (1) #define DHCP_MESSAGE_OP_REPLY (2) #define DHCP_MESSAGE_HTYPE (1) #define DHCP_MESSAGE_HLEN (6) #define DHCP_SERVER_PORT (67) #define DHCP_CLIENT_PORT (68) #define DHCP_MESSAGE_TYPE_DISCOVER (1) #define DHCP_MESSAGE_TYPE_OFFER (2) #define DHCP_MESSAGE_TYPE_REQUEST (3) #define DHCP_MESSAGE_TYPE_DECLINE (4) #define DHCP_MESSAGE_TYPE_ACK (5) #define DHCP_MESSAGE_TYPE_NAK (6) #define DHCP_MESSAGE_TYPE_RELEASE (7) #define DHCP_OPTION_LENGTH_ONE (1) #define DHCP_OPTION_LENGTH_TWO (2) #define DHCP_OPTION_LENGTH_THREE (3) #define DHCP_OPTION_LENGTH_FOUR (4) #ifndef DHCP_MSG_LEN #define DHCP_MSG_LEN 236 #endif #define DHCP_OFFER_OPTION_TOTAL_LENGTH_MAX 312 //(51)= 4(magic)+3(type)+44(option code: 1,3,6,51,54,28,26,32,end) #define DHCP_OPTION_CODE_SUBNET_MASK (1) #define DHCP_OPTION_CODE_ROUTER (3) #define DHCP_OPTION_CODE_DNS_SERVER (6) #define DHCP_OPTION_CODE_INTERFACE_MTU (26) #define DHCP_OPTION_CODE_BROADCAST_ADDRESS (28) #define DHCP_OPTION_CODE_PERFORM_ROUTER_DISCOVERY (31) #define DHCP_OPTION_CODE_REQUEST_IP_ADDRESS (50) #define DHCP_OPTION_CODE_LEASE_TIME (51) #define DHCP_OPTION_CODE_MSG_TYPE (53) #define DHCP_OPTION_CODE_SERVER_ID (54) #define DHCP_OPTION_CODE_REQ_LIST (55) #define DHCP_OPTION_CODE_END (255) #define IP_FREE_TO_USE (1) #define IP_ALREADY_IN_USE (0) #define HW_ADDRESS_LENGTH (6) /* Reference by RFC 2131 */ struct dhcp_msg { uint8_t op; /* Message op code/message type. 1 = BOOTREQUEST, 2 = BOOTREPLY */ uint8_t htype; /* Hardware address type */ uint8_t hlen; /* Hardware address length */ uint8_t hops; /* Client sets to zero, optionally used by relay agents when booting via a relay agent */ uint8_t xid[4]; /* Transaction ID, a random number chosen by the client, used by the client and server to associate messages and responses between a client and a server */ uint16_t secs; /* Filled in by client, seconds elapsed since client began address acquisition or renewal process.*/ uint16_t flags; /* bit 0: Broadcast flag, bit 1~15:MBZ must 0*/ uint8_t ciaddr[4]; /* Client IP address; only filled in if client is in BOUND, RENEW or REBINDING state and can respond to ARP requests. */ uint8_t yiaddr[4]; /* 'your' (client) IP address */ uint8_t siaddr[4]; /* IP address of next server to use in bootstrap; returned in DHCPOFFER, DHCPACK by server. */ uint8_t giaddr[4]; /* Relay agent IP address, used in booting via a relay agent.*/ uint8_t chaddr[16]; /* Client hardware address */ uint8_t sname[64]; /* Optional server host name, null terminated string.*/ uint8_t file[128]; /* Boot file name, null terminated string; "generic" name or null in DHCPDISCOVER, fully qualified directory-path name in DHCPOFFER.*/ uint8_t options[312]; /* Optional parameters field. reference the RFC 2132 */ }; /* use this to check whether the message is dhcp related or not */ static const uint8_t dhcp_magic_cookie[4] = {99, 130, 83, 99}; static const uint8_t dhcp_option_lease_time[] = {0x00, 0x00, 0x1c, 0x20}; //1 day //static const uint8_t dhcp_option_lease_time[] = {0x00, 0x00, 0x0e, 0x10}; // one hour //static const uint8_t dhcp_option_interface_mtu_576[] = {0x02, 0x40}; static const uint8_t dhcp_option_interface_mtu[] = {0x05, 0xDC}; struct table { uint32_t ip_range[8]; #ifdef CONFIG_DHCPS_KEPT_CLIENT_INFO uint8_t client_mac[256][6]; #endif }; struct address_pool{ uint32_t start; uint32_t end; }; /* 01~32 */ #define MARK_RANGE1_IP_BIT(table, ip) ((table.ip_range[0]) | (1 << ((ip) - 1))) /* 33~64 */ #define MARK_RANGE2_IP_BIT(table, ip) ((table.ip_range[1]) | (1 << ((ip) - 1))) /* 65~96 */ #define MARK_RANGE3_IP_BIT(table, ip) ((table.ip_range[2]) | (1 << ((ip) - 1))) /* 97~128 */ #define MARK_RANGE4_IP_BIT(table, ip) ((table.ip_range[3]) | (1 << ((ip) - 1))) /* 129~160 */ #define MARK_RANGE5_IP_BIT(table, ip) ((table.ip_range[4]) | (1 << ((ip) - 1))) /* 161~192 */ #define MARK_RANGE6_IP_BIT(table, ip) ((table.ip_range[5]) | (1 << ((ip) - 1))) /* 193~224 */ #define MARK_RANGE7_IP_BIT(table, ip) ((table.ip_range[6]) | (1 << ((ip) - 1))) /* 225~255 */ #define MARK_RANGE8_IP_BIT(table, ip) ((table.ip_range[7]) | (1 << ((ip) - 1))) /* expose API */ void dhcps_set_addr_pool(int addr_pool_set, ip_addr_t * addr_pool_start, ip_addr_t *addr_pool_end); void dhcps_init(struct netif * pnetif); void dhcps_deinit(void); extern struct netif *netif_default; #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/network/dhcp/dhcps.h
C
apache-2.0
5,349
#include <rom_ssl_ram_map.h> #include <section_config.h> #ifndef SSL_RAM_MAP_SECTION #define SSL_RAM_MAP_SECTION #endif #ifndef HAL_ROM_BSS_V02_SECTION #define HAL_ROM_BSS_V02_SECTION #endif /* RAM table referred by SSL ROM */ SSL_RAM_MAP_SECTION struct _rom_ssl_ram_map rom_ssl_ram_map; SSL_RAM_MAP_SECTION struct _rom_mbedtls_ram_map* p_rom_ssl_ram_map;
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/network/ssl/ssl_ram_map/rom/rom_ssl_ram_map.c
C
apache-2.0
359
#ifndef ROM_SSL_RAM_MAP_H #define ROM_SSL_RAM_MAP_H #include "basic_types.h" struct _rom_ssl_ram_map { /* OS interface */ void *(*ssl_malloc)(unsigned int sz); void (*ssl_free)(void *); int (*ssl_printf)(const char *, ...); //AES HW CRYPTO int (*hw_crypto_aes_ecb_init)(const u8* key, const u32 keylen); int (*hw_crypto_aes_ecb_decrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); int (*hw_crypto_aes_ecb_encrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); int (*hw_crypto_aes_cbc_init)(const u8* key, const u32 keylen); int (*hw_crypto_aes_cbc_decrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); int (*hw_crypto_aes_cbc_encrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); //DES HW CRYPTO int (*hw_crypto_des_cbc_init)(const u8* key, const u32 keylen); int (*hw_crypto_des_cbc_decrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); int (*hw_crypto_des_cbc_encrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); int (*hw_crypto_3des_cbc_init)(const u8* key, const u32 keylen); int (*hw_crypto_3des_cbc_decrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); int (*hw_crypto_3des_cbc_encrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); /* Variables */ u32 use_hw_crypto_func; }; struct _rom_mbedtls_ram_map { /* OS interface */ void *(*ssl_calloc)(unsigned int, unsigned int); void (*ssl_free)(void *); int (*ssl_printf)(const char *, ...); //AES HW CRYPTO int (*hw_crypto_aes_ecb_init)(const u8* key, const u32 keylen); int (*hw_crypto_aes_ecb_decrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); int (*hw_crypto_aes_ecb_encrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); int (*hw_crypto_aes_cbc_init)(const u8* key, const u32 keylen); int (*hw_crypto_aes_cbc_decrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); int (*hw_crypto_aes_cbc_encrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); //DES HW CRYPTO int (*hw_crypto_des_cbc_init)(const u8* key, const u32 keylen); int (*hw_crypto_des_cbc_decrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); int (*hw_crypto_des_cbc_encrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); int (*hw_crypto_3des_cbc_init)(const u8* key, const u32 keylen); int (*hw_crypto_3des_cbc_decrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); int (*hw_crypto_3des_cbc_encrypt)( const u8* message, const u32 msglen, const u8* iv, const u32 ivlen, u8* pResult); /* Variables */ u32 use_hw_crypto_func; }; extern struct _rom_ssl_ram_map rom_ssl_ram_map; extern struct _rom_mbedtls_ram_map *p_rom_ssl_ram_map; //=&rom_ssl_ram_map init in mbedtls_platform_set_calloc_free #endif /* ROM_SSL_RAM_MAP_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/network/ssl/ssl_ram_map/rom/rom_ssl_ram_map.h
C
apache-2.0
3,332
#include "rom_ssl_ram_map.h" #include <diag.h> extern struct _rom_ssl_ram_map rom_ssl_ram_map; //AES HW CRYPTO extern int rtl_crypto_aes_ecb_init(IN const u8* key, IN const u32 keylen); extern int rtl_crypto_aes_ecb_decrypt( IN const u8* message, IN const u32 msglen, IN const u8* iv, IN const u32 ivlen, OUT u8* pResult); extern int rtl_crypto_aes_ecb_encrypt( IN const u8* message, IN const u32 msglen, IN const u8* iv, IN const u32 ivlen, OUT u8* pResult); extern int rtl_crypto_aes_cbc_init(IN const u8* key, IN const u32 keylen); extern int rtl_crypto_aes_cbc_decrypt( IN const u8* message, IN const u32 msglen, IN const u8* iv, IN const u32 ivlen, OUT u8* pResult); extern int rtl_crypto_aes_cbc_encrypt( IN const u8* message, IN const u32 msglen, IN const u8* iv, IN const u32 ivlen, OUT u8* pResult); //DES HW CRYPTO extern int rtl_crypto_des_cbc_init(IN const u8* key, IN const u32 keylen); extern int rtl_crypto_des_cbc_decrypt( IN const u8* message, IN const u32 msglen, IN const u8* iv, IN const u32 ivlen, OUT u8* pResult); extern int rtl_crypto_des_cbc_encrypt( IN const u8* message, IN const u32 msglen, IN const u8* iv, IN const u32 ivlen, OUT u8* pResult); extern int rtl_crypto_3des_cbc_init(IN const u8* key, IN const u32 keylen); extern int rtl_crypto_3des_cbc_decrypt( IN const u8* message, IN const u32 msglen, IN const u8* iv, IN const u32 ivlen, OUT u8* pResult); extern int rtl_crypto_3des_cbc_encrypt( IN const u8* message, IN const u32 msglen, IN const u8* iv, IN const u32 ivlen, OUT u8* pResult); int platform_set_malloc_free( void * (*malloc_func)( size_t ), void (*free_func)( void * ) ) { /* OS interface */ rom_ssl_ram_map.ssl_malloc = malloc_func; rom_ssl_ram_map.ssl_free = free_func; rom_ssl_ram_map.ssl_printf = (int (*)(char const *, ...))DiagPrintf; //AES HW CRYPTO rom_ssl_ram_map.hw_crypto_aes_ecb_init = rtl_crypto_aes_ecb_init; rom_ssl_ram_map.hw_crypto_aes_ecb_decrypt = rtl_crypto_aes_ecb_decrypt; rom_ssl_ram_map.hw_crypto_aes_ecb_encrypt = rtl_crypto_aes_ecb_encrypt; rom_ssl_ram_map.hw_crypto_aes_cbc_init = rtl_crypto_aes_cbc_init; rom_ssl_ram_map.hw_crypto_aes_cbc_decrypt = rtl_crypto_aes_cbc_decrypt; rom_ssl_ram_map.hw_crypto_aes_cbc_encrypt = rtl_crypto_aes_cbc_encrypt; //DES HW CRYPTO rom_ssl_ram_map.hw_crypto_des_cbc_init = rtl_crypto_des_cbc_init; rom_ssl_ram_map.hw_crypto_des_cbc_decrypt = rtl_crypto_des_cbc_decrypt; rom_ssl_ram_map.hw_crypto_des_cbc_encrypt = rtl_crypto_des_cbc_encrypt; rom_ssl_ram_map.hw_crypto_3des_cbc_init = rtl_crypto_3des_cbc_init; rom_ssl_ram_map.hw_crypto_3des_cbc_decrypt = rtl_crypto_3des_cbc_decrypt; rom_ssl_ram_map.hw_crypto_3des_cbc_encrypt = rtl_crypto_3des_cbc_encrypt; /* Variables */ rom_ssl_ram_map.use_hw_crypto_func = 1; return 0; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/common/network/ssl/ssl_ram_map/ssl_ram_map.c
C
apache-2.0
2,859
/* * FreeRTOS Kernel V10.2.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #ifndef INC_FREERTOS_H #define INC_FREERTOS_H /* * Include the generic headers required for the FreeRTOS port being used. */ #include <stddef.h> /* * If stdint.h cannot be located then: * + If using GCC ensure the -nostdint options is *not* being used. * + Ensure the project's include path includes the directory in which your * compiler stores stdint.h. * + Set any compiler options necessary for it to support C99, as technically * stdint.h is only mandatory with C99 (FreeRTOS does not require C99 in any * other way). * + The FreeRTOS download includes a simple stdint.h definition that can be * used in cases where none is provided by the compiler. The files only * contains the typedefs required to build FreeRTOS. Read the instructions * in FreeRTOS/source/stdint.readme for more information. */ #include <stdint.h> /* READ COMMENT ABOVE. */ #ifdef __cplusplus extern "C" { #endif /* Application specific configuration options. */ #include "FreeRTOSConfig.h" /* Basic FreeRTOS definitions. */ #include "projdefs.h" /* Definitions specific to the port being used. */ #include "portable.h" /* * Check all the required application specific macros have been defined. * These macros are application specific and (as downloaded) are defined * within FreeRTOSConfig.h. */ #ifndef configMINIMAL_STACK_SIZE #error Missing definition: configMINIMAL_STACK_SIZE must be defined in FreeRTOSConfig.h. configMINIMAL_STACK_SIZE defines the size (in words) of the stack allocated to the idle task. Refer to the demo project provided for your port for a suitable value. #endif #ifndef configMAX_PRIORITIES #error Missing definition: configMAX_PRIORITIES must be defined in FreeRTOSConfig.h. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_PREEMPTION #error Missing definition: configUSE_PREEMPTION must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_IDLE_HOOK #error Missing definition: configUSE_IDLE_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_TICK_HOOK #error Missing definition: configUSE_TICK_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_CO_ROUTINES #error Missing definition: configUSE_CO_ROUTINES must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef INCLUDE_vTaskPrioritySet #error Missing definition: INCLUDE_vTaskPrioritySet must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef INCLUDE_uxTaskPriorityGet #error Missing definition: INCLUDE_uxTaskPriorityGet must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef INCLUDE_vTaskDelete #error Missing definition: INCLUDE_vTaskDelete must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef INCLUDE_vTaskSuspend #error Missing definition: INCLUDE_vTaskSuspend must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef INCLUDE_vTaskDelayUntil #error Missing definition: INCLUDE_vTaskDelayUntil must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef INCLUDE_vTaskDelay #error Missing definition: INCLUDE_vTaskDelay must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_16_BIT_TICKS #error Missing definition: configUSE_16_BIT_TICKS must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #if configUSE_CO_ROUTINES != 0 #ifndef configMAX_CO_ROUTINE_PRIORITIES #error configMAX_CO_ROUTINE_PRIORITIES must be greater than or equal to 1. #endif #endif #ifndef configMAX_PRIORITIES #error configMAX_PRIORITIES must be defined to be greater than or equal to 1. #endif #ifndef INCLUDE_xTaskGetIdleTaskHandle #define INCLUDE_xTaskGetIdleTaskHandle 0 #endif #ifndef INCLUDE_xTimerGetTimerDaemonTaskHandle #define INCLUDE_xTimerGetTimerDaemonTaskHandle 0 #endif #ifndef INCLUDE_xQueueGetMutexHolder #define INCLUDE_xQueueGetMutexHolder 0 #endif #ifndef INCLUDE_xSemaphoreGetMutexHolder #define INCLUDE_xSemaphoreGetMutexHolder INCLUDE_xQueueGetMutexHolder #endif #ifndef INCLUDE_pcTaskGetTaskName #define INCLUDE_pcTaskGetTaskName 0 #endif #ifndef configUSE_APPLICATION_TASK_TAG #define configUSE_APPLICATION_TASK_TAG 0 #endif #ifndef INCLUDE_uxTaskGetStackHighWaterMark #define INCLUDE_uxTaskGetStackHighWaterMark 1 #endif #ifndef INCLUDE_eTaskGetState #define INCLUDE_eTaskGetState 0 #endif #ifndef configUSE_RECURSIVE_MUTEXES #define configUSE_RECURSIVE_MUTEXES 0 #endif #ifndef configUSE_MUTEXES #define configUSE_MUTEXES 0 #endif #ifndef configUSE_TIMERS #define configUSE_TIMERS 0 #endif #ifndef configUSE_COUNTING_SEMAPHORES #define configUSE_COUNTING_SEMAPHORES 0 #endif #ifndef configUSE_ALTERNATIVE_API #define configUSE_ALTERNATIVE_API 0 #endif #ifndef portCRITICAL_NESTING_IN_TCB #define portCRITICAL_NESTING_IN_TCB 0 #endif #ifndef configMAX_TASK_NAME_LEN #define configMAX_TASK_NAME_LEN 16 #endif #ifndef configIDLE_SHOULD_YIELD #define configIDLE_SHOULD_YIELD 1 #endif #if configMAX_TASK_NAME_LEN < 1 #error configMAX_TASK_NAME_LEN must be set to a minimum of 1 in FreeRTOSConfig.h #endif #ifndef INCLUDE_xTaskResumeFromISR #define INCLUDE_xTaskResumeFromISR 1 #endif #ifndef INCLUDE_xEventGroupSetBitFromISR #define INCLUDE_xEventGroupSetBitFromISR 0 #endif #ifndef INCLUDE_xTimerPendFunctionCall #define INCLUDE_xTimerPendFunctionCall 0 #endif #ifndef configASSERT #define configASSERT( x ) #define configASSERT_DEFINED 0 #else #define configASSERT_DEFINED 1 #endif /* The timers module relies on xTaskGetSchedulerState(). */ #if configUSE_TIMERS == 1 #ifndef configTIMER_TASK_PRIORITY #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_PRIORITY must also be defined. #endif /* configTIMER_TASK_PRIORITY */ #ifndef configTIMER_QUEUE_LENGTH #error If configUSE_TIMERS is set to 1 then configTIMER_QUEUE_LENGTH must also be defined. #endif /* configTIMER_QUEUE_LENGTH */ #ifndef configTIMER_TASK_STACK_DEPTH #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_STACK_DEPTH must also be defined. #endif /* configTIMER_TASK_STACK_DEPTH */ #endif /* configUSE_TIMERS */ #ifndef INCLUDE_xTaskGetSchedulerState #define INCLUDE_xTaskGetSchedulerState 0 #endif #ifndef INCLUDE_xTaskGetCurrentTaskHandle #define INCLUDE_xTaskGetCurrentTaskHandle 0 #endif #ifndef portSET_INTERRUPT_MASK_FROM_ISR #define portSET_INTERRUPT_MASK_FROM_ISR() 0 #endif #ifndef portCLEAR_INTERRUPT_MASK_FROM_ISR #define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue #endif #ifndef portCLEAN_UP_TCB #define portCLEAN_UP_TCB( pxTCB ) ( void ) pxTCB #endif #ifndef portPRE_TASK_DELETE_HOOK #define portPRE_TASK_DELETE_HOOK( pvTaskToDelete, pxYieldPending ) #endif #ifndef portSETUP_TCB #define portSETUP_TCB( pxTCB ) ( void ) pxTCB #endif #ifndef configQUEUE_REGISTRY_SIZE #define configQUEUE_REGISTRY_SIZE 0U #endif #if ( configQUEUE_REGISTRY_SIZE < 1 ) #define vQueueAddToRegistry( xQueue, pcName ) #define vQueueUnregisterQueue( xQueue ) #endif #ifndef portPOINTER_SIZE_TYPE #define portPOINTER_SIZE_TYPE uint32_t #endif /* Remove any unused trace macros. */ #ifndef traceSTART /* Used to perform any necessary initialisation - for example, open a file into which trace is to be written. */ #define traceSTART() #endif #ifndef traceEND /* Use to close a trace, for example close a file into which trace has been written. */ #define traceEND() #endif #ifndef traceTASK_SWITCHED_IN /* Called after a task has been selected to run. pxCurrentTCB holds a pointer to the task control block of the selected task. */ #define traceTASK_SWITCHED_IN() #endif #ifndef traceINCREASE_TICK_COUNT /* Called before stepping the tick count after waking from tickless idle sleep. */ #define traceINCREASE_TICK_COUNT( x ) #endif #ifndef traceLOW_POWER_IDLE_BEGIN /* Called immediately before entering tickless idle. */ #define traceLOW_POWER_IDLE_BEGIN() #endif #ifndef traceLOW_POWER_IDLE_END /* Called when returning to the Idle task after a tickless idle. */ #define traceLOW_POWER_IDLE_END() #endif #ifndef traceTASK_SWITCHED_OUT /* Called before a task has been selected to run. pxCurrentTCB holds a pointer to the task control block of the task being switched out. */ #define traceTASK_SWITCHED_OUT() #endif #ifndef traceTASK_PRIORITY_INHERIT /* Called when a task attempts to take a mutex that is already held by a lower priority task. pxTCBOfMutexHolder is a pointer to the TCB of the task that holds the mutex. uxInheritedPriority is the priority the mutex holder will inherit (the priority of the task that is attempting to obtain the muted. */ #define traceTASK_PRIORITY_INHERIT( pxTCBOfMutexHolder, uxInheritedPriority ) #endif #ifndef traceTASK_PRIORITY_DISINHERIT /* Called when a task releases a mutex, the holding of which had resulted in the task inheriting the priority of a higher priority task. pxTCBOfMutexHolder is a pointer to the TCB of the task that is releasing the mutex. uxOriginalPriority is the task's configured (base) priority. */ #define traceTASK_PRIORITY_DISINHERIT( pxTCBOfMutexHolder, uxOriginalPriority ) #endif #ifndef traceBLOCKING_ON_QUEUE_RECEIVE /* Task is about to block because it cannot read from a queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore upon which the read was attempted. pxCurrentTCB points to the TCB of the task that attempted the read. */ #define traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ) #endif #ifndef traceBLOCKING_ON_QUEUE_SEND /* Task is about to block because it cannot write to a queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore upon which the write was attempted. pxCurrentTCB points to the TCB of the task that attempted the write. */ #define traceBLOCKING_ON_QUEUE_SEND( pxQueue ) #endif #ifndef configCHECK_FOR_STACK_OVERFLOW #define configCHECK_FOR_STACK_OVERFLOW 0 #endif /* The following event macros are embedded in the kernel API calls. */ #ifndef traceMOVED_TASK_TO_READY_STATE #define traceMOVED_TASK_TO_READY_STATE( pxTCB ) #endif #ifndef traceQUEUE_CREATE #define traceQUEUE_CREATE( pxNewQueue ) #endif #ifndef traceQUEUE_CREATE_FAILED #define traceQUEUE_CREATE_FAILED( ucQueueType ) #endif #ifndef traceCREATE_MUTEX #define traceCREATE_MUTEX( pxNewQueue ) #endif #ifndef traceCREATE_MUTEX_FAILED #define traceCREATE_MUTEX_FAILED() #endif #ifndef traceGIVE_MUTEX_RECURSIVE #define traceGIVE_MUTEX_RECURSIVE( pxMutex ) #endif #ifndef traceGIVE_MUTEX_RECURSIVE_FAILED #define traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ) #endif #ifndef traceTAKE_MUTEX_RECURSIVE #define traceTAKE_MUTEX_RECURSIVE( pxMutex ) #endif #ifndef traceTAKE_MUTEX_RECURSIVE_FAILED #define traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ) #endif #ifndef traceCREATE_COUNTING_SEMAPHORE #define traceCREATE_COUNTING_SEMAPHORE() #endif #ifndef traceCREATE_COUNTING_SEMAPHORE_FAILED #define traceCREATE_COUNTING_SEMAPHORE_FAILED() #endif #ifndef traceQUEUE_SEND #define traceQUEUE_SEND( pxQueue ) #endif #ifndef traceQUEUE_SEND_FAILED #define traceQUEUE_SEND_FAILED( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE #define traceQUEUE_RECEIVE( pxQueue ) #endif #ifndef traceQUEUE_PEEK #define traceQUEUE_PEEK( pxQueue ) #endif #ifndef traceQUEUE_PEEK_FROM_ISR #define traceQUEUE_PEEK_FROM_ISR( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE_FAILED #define traceQUEUE_RECEIVE_FAILED( pxQueue ) #endif #ifndef traceQUEUE_SEND_FROM_ISR #define traceQUEUE_SEND_FROM_ISR( pxQueue ) #endif #ifndef traceQUEUE_SEND_FROM_ISR_FAILED #define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE_FROM_ISR #define traceQUEUE_RECEIVE_FROM_ISR( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE_FROM_ISR_FAILED #define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ) #endif #ifndef traceQUEUE_PEEK_FROM_ISR_FAILED #define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ) #endif #ifndef traceQUEUE_DELETE #define traceQUEUE_DELETE( pxQueue ) #endif #ifndef traceTASK_CREATE #define traceTASK_CREATE( pxNewTCB ) #endif #ifndef traceTASK_CREATE_FAILED #define traceTASK_CREATE_FAILED() #endif #ifndef traceTASK_DELETE #define traceTASK_DELETE( pxTaskToDelete ) #endif #ifndef traceTASK_DELAY_UNTIL #define traceTASK_DELAY_UNTIL() #endif #ifndef traceTASK_DELAY #define traceTASK_DELAY() #endif #ifndef traceTASK_PRIORITY_SET #define traceTASK_PRIORITY_SET( pxTask, uxNewPriority ) #endif #ifndef traceTASK_SUSPEND #define traceTASK_SUSPEND( pxTaskToSuspend ) #endif #ifndef traceTASK_RESUME #define traceTASK_RESUME( pxTaskToResume ) #endif #ifndef traceTASK_RESUME_FROM_ISR #define traceTASK_RESUME_FROM_ISR( pxTaskToResume ) #endif #ifndef traceTASK_INCREMENT_TICK #define traceTASK_INCREMENT_TICK( xTickCount ) #endif #ifndef traceTIMER_CREATE #define traceTIMER_CREATE( pxNewTimer ) #endif #ifndef traceTIMER_CREATE_FAILED #define traceTIMER_CREATE_FAILED() #endif #ifndef traceTIMER_COMMAND_SEND #define traceTIMER_COMMAND_SEND( xTimer, xMessageID, xMessageValueValue, xReturn ) #endif #ifndef traceTIMER_EXPIRED #define traceTIMER_EXPIRED( pxTimer ) #endif #ifndef traceTIMER_COMMAND_RECEIVED #define traceTIMER_COMMAND_RECEIVED( pxTimer, xMessageID, xMessageValue ) #endif #ifndef traceMALLOC #define traceMALLOC( pvAddress, uiSize ) #endif #ifndef traceFREE #define traceFREE( pvAddress, uiSize ) #endif #ifndef traceEVENT_GROUP_CREATE #define traceEVENT_GROUP_CREATE( xEventGroup ) #endif #ifndef traceEVENT_GROUP_CREATE_FAILED #define traceEVENT_GROUP_CREATE_FAILED() #endif #ifndef traceEVENT_GROUP_SYNC_BLOCK #define traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ) #endif #ifndef traceEVENT_GROUP_SYNC_END #define traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred #endif #ifndef traceEVENT_GROUP_WAIT_BITS_BLOCK #define traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ) #endif #ifndef traceEVENT_GROUP_WAIT_BITS_END #define traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred #endif #ifndef traceEVENT_GROUP_CLEAR_BITS #define traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ) #endif #ifndef traceEVENT_GROUP_CLEAR_BITS_FROM_ISR #define traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ) #endif #ifndef traceEVENT_GROUP_SET_BITS #define traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ) #endif #ifndef traceEVENT_GROUP_SET_BITS_FROM_ISR #define traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ) #endif #ifndef traceEVENT_GROUP_DELETE #define traceEVENT_GROUP_DELETE( xEventGroup ) #endif #ifndef tracePEND_FUNC_CALL #define tracePEND_FUNC_CALL(xFunctionToPend, pvParameter1, ulParameter2, ret) #endif #ifndef tracePEND_FUNC_CALL_FROM_ISR #define tracePEND_FUNC_CALL_FROM_ISR(xFunctionToPend, pvParameter1, ulParameter2, ret) #endif #ifndef traceQUEUE_REGISTRY_ADD #define traceQUEUE_REGISTRY_ADD(xQueue, pcQueueName) #endif #ifndef configGENERATE_RUN_TIME_STATS #define configGENERATE_RUN_TIME_STATS 0 #endif #if ( configGENERATE_RUN_TIME_STATS == 1 ) #ifndef configUSE_STATS_FORMATTING_FUNCTIONS #define configUSE_STATS_FORMATTING_FUNCTIONS 1 #endif #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS #error If configGENERATE_RUN_TIME_STATS is defined then portCONFIGURE_TIMER_FOR_RUN_TIME_STATS must also be defined. portCONFIGURE_TIMER_FOR_RUN_TIME_STATS should call a port layer function to setup a peripheral timer/counter that can then be used as the run time counter time base. #endif /* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS */ #ifndef portGET_RUN_TIME_COUNTER_VALUE #ifndef portALT_GET_RUN_TIME_COUNTER_VALUE #error If configGENERATE_RUN_TIME_STATS is defined then either portGET_RUN_TIME_COUNTER_VALUE or portALT_GET_RUN_TIME_COUNTER_VALUE must also be defined. See the examples provided and the FreeRTOS web site for more information. #endif /* portALT_GET_RUN_TIME_COUNTER_VALUE */ #endif /* portGET_RUN_TIME_COUNTER_VALUE */ #endif /* configGENERATE_RUN_TIME_STATS */ #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS #define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() #endif #ifndef configUSE_MALLOC_FAILED_HOOK #define configUSE_MALLOC_FAILED_HOOK 0 #endif #ifndef portPRIVILEGE_BIT #define portPRIVILEGE_BIT ( ( UBaseType_t ) 0x00 ) #endif #ifndef portYIELD_WITHIN_API #define portYIELD_WITHIN_API portYIELD #endif #ifndef pvPortMallocAligned #define pvPortMallocAligned( x, puxStackBuffer ) ( ( ( puxStackBuffer ) == NULL ) ? ( pvPortMalloc( ( x ) ) ) : ( puxStackBuffer ) ) #endif #ifndef vPortFreeAligned #define vPortFreeAligned( pvBlockToFree ) vPortFree( pvBlockToFree ) #endif #ifndef portSUPPRESS_TICKS_AND_SLEEP #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) #endif #ifndef configEXPECTED_IDLE_TIME_BEFORE_SLEEP #define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 #endif #if configEXPECTED_IDLE_TIME_BEFORE_SLEEP < 2 #error configEXPECTED_IDLE_TIME_BEFORE_SLEEP must not be less than 2 #endif #ifndef configUSE_TICKLESS_IDLE #define configUSE_TICKLESS_IDLE 0 #endif #ifndef configPRE_SLEEP_PROCESSING #define configPRE_SLEEP_PROCESSING( x ) #endif #ifndef configPOST_SLEEP_PROCESSING #define configPOST_SLEEP_PROCESSING( x ) #endif #ifndef configUSE_QUEUE_SETS #define configUSE_QUEUE_SETS 0 #endif #ifndef portTASK_USES_FLOATING_POINT #define portTASK_USES_FLOATING_POINT() #endif #ifndef configUSE_TIME_SLICING #define configUSE_TIME_SLICING 1 #endif #ifndef configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS #define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0 #endif #ifndef configUSE_NEWLIB_REENTRANT #define configUSE_NEWLIB_REENTRANT 0 #endif #ifndef configUSE_STATS_FORMATTING_FUNCTIONS #define configUSE_STATS_FORMATTING_FUNCTIONS 0 #endif #ifndef portASSERT_IF_INTERRUPT_PRIORITY_INVALID #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() #endif #ifndef configUSE_TRACE_FACILITY #define configUSE_TRACE_FACILITY 0 #endif #ifndef mtCOVERAGE_TEST_MARKER #define mtCOVERAGE_TEST_MARKER() #endif #ifndef portASSERT_IF_IN_ISR #define portASSERT_IF_IN_ISR() #endif #ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION #define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 #endif /* Definitions to allow backward compatibility with FreeRTOS versions prior to V8 if desired. */ #ifndef configENABLE_BACKWARD_COMPATIBILITY #define configENABLE_BACKWARD_COMPATIBILITY 1 #endif #if configENABLE_BACKWARD_COMPATIBILITY == 1 #define eTaskStateGet eTaskGetState #define portTickType TickType_t #define xTaskHandle TaskHandle_t #define xQueueHandle QueueHandle_t //#define xSemaphoreHandle SemaphoreHandle_t #define xQueueSetHandle QueueSetHandle_t #define xQueueSetMemberHandle QueueSetMemberHandle_t #define xTimeOutType TimeOut_t #define xMemoryRegion MemoryRegion_t #define xTaskParameters TaskParameters_t #define xTaskStatusType TaskStatus_t #define xTimerHandle TimerHandle_t #define xCoRoutineHandle CoRoutineHandle_t #define pdTASK_HOOK_CODE TaskHookFunction_t #define portTICK_RATE_MS portTICK_PERIOD_MS /* Backward compatibility within the scheduler code only - these definitions are not really required but are included for completeness. */ #define tmrTIMER_CALLBACK TimerCallbackFunction_t #define pdTASK_CODE TaskFunction_t #define xListItem ListItem_t #define xList List_t #endif /* configENABLE_BACKWARD_COMPATIBILITY */ #ifdef __cplusplus } #endif #endif /* INC_FREERTOS_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/os/FreeRTOS.h
C
apache-2.0
22,460
#ifndef _FREERTOS_PMU_H_ #define _FREERTOS_PMU_H_ typedef enum { PMU_OS =0, PMU_WLAN_DEVICE =1, PMU_LOGUART_DEVICE =2, PMU_KM4_RUN =3, PMU_UART0_DEVICE =4, PMU_UART1_DEVICE =5, PMU_I2C0_DEVICE =6, PMU_TOUCH_DEVICE =7, PMU_USOC_DEVICE =8, PMU_DONGLE_DEVICE =9, PMU_RTC_DEVICE =10, PMU_CONSOL_DEVICE =11, PMU_ADC_DEVICE =12, PMU_WAKWLOCK_TIMEOUT=13, PMU_KEYSCAN_DEVICE =14, PMU_PSRAM_DEVICE =15, PMU_DEV_USER_BASE =16, /*number 16 ~ 31 is reserved for customer use*/ PMU_MAX =31 } PMU_DEVICE; enum SLEEP_TYPE { SLEEP_PG = 0, SLEEP_CG = 1, }; // default locked by OS and not to sleep until OS release wakelock in somewhere #define DEFAULT_WAKELOCK (BIT(PMU_OS)) #define DEFAULT_DEEP_WAKELOCK (BIT(PMU_OS)) #define SLEEP_MAX_DELAY (u32) 0xffffffffUL typedef uint32_t (*PSM_HOOK_FUN)( unsigned int, void* param_ptr ); #define PMU_DEVICE_TIMER_DEFAULT_INTERVAL 2000 #define PMU_DEVICE_TIMER_MAX_INTERVAL (1000*30) /* max 30sec */ typedef struct { u32 nDeviceId; PSM_HOOK_FUN sleep_hook_fun; void* sleep_param_ptr; PSM_HOOK_FUN wakeup_hook_fun; void* wakeup_param_ptr; }PSM_DD_HOOK_INFO; /** * @brief init system active timer for PMU. * @param none. * @retval status value: * - 0: _FAIL * - 1: _SUCCESS * @note can just used in late resume or later, can not used in wakeup_hook_fun. */ uint32_t pmu_yield_os_check(void); u32 pmu_exec_sleep_hook_funs(void); void pmu_exec_wakeup_hook_funs(u32 nDeviceIdMax); uint32_t pmu_set_sleep_type(uint32_t type); uint32_t pmu_get_sleep_type(void); void pmu_set_max_sleep_time(uint32_t timer_ms); #ifndef CONFIG_BUILD_ROM void pmu_deepsleep_cmd(u32 NewStatus); #endif void pmu_tickless_debug(u32 NewStatus); void pmu_set_dsleep_active_time(uint32_t TimeOutMs); void pmu_acquire_deepwakelock(uint32_t nDeviceId); void pmu_release_deepwakelock(uint32_t nDeviceId); void pmu_set_dev_wakeup_tick(u32 nDeviceId, u32 Ms); uint32_t pmu_set_sysactive_time(uint32_t timeout); void pmu_register_sleep_callback(u32 nDeviceId, PSM_HOOK_FUN sleep_hook_fun, void* sleep_param_ptr, PSM_HOOK_FUN wakeup_hook_fun, void* wakeup_param_ptr); void pmu_unregister_sleep_callback(u32 nDeviceId); int freertos_ready_to_sleep(void); int freertos_ready_to_dsleep(void); void freertos_pre_sleep_processing(unsigned int *expected_idle_time); void freertos_post_sleep_processing(unsigned int *expected_idle_time); void pmu_acquire_wakelock(uint32_t nDeviceId); void pmu_release_wakelock(uint32_t nDeviceId); uint32_t pmu_get_wakelock_status(void); uint32_t pmu_get_deepwakelock_status(void); extern u32 tickless_debug; extern u32 tick_last_tcp; #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/os/freertos_pmu.h
C
apache-2.0
2,761
/* * FreeRTOS Kernel V10.2.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #ifndef MPU_WRAPPERS_H #define MPU_WRAPPERS_H /* This file redefines API functions to be called through a wrapper macro, but only for ports that are using the MPU. */ #ifdef portUSING_MPU_WRAPPERS /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE will be defined when this file is included from queue.c or task.c to prevent it from having an effect within those files. */ #ifndef MPU_WRAPPERS_INCLUDED_FROM_API_FILE #define xTaskGenericCreate MPU_xTaskGenericCreate #define vTaskAllocateMPURegions MPU_vTaskAllocateMPURegions #define vTaskDelete MPU_vTaskDelete #define vTaskDelayUntil MPU_vTaskDelayUntil #define vTaskDelay MPU_vTaskDelay #define uxTaskPriorityGet MPU_uxTaskPriorityGet #define vTaskPrioritySet MPU_vTaskPrioritySet #define eTaskGetState MPU_eTaskGetState #define vTaskSuspend MPU_vTaskSuspend #define vTaskResume MPU_vTaskResume #define vTaskSuspendAll MPU_vTaskSuspendAll #define xTaskResumeAll MPU_xTaskResumeAll #define xTaskGetTickCount MPU_xTaskGetTickCount #define uxTaskGetNumberOfTasks MPU_uxTaskGetNumberOfTasks #define vTaskList MPU_vTaskList #define vTaskGetRunTimeStats MPU_vTaskGetRunTimeStats #define vTaskSetApplicationTaskTag MPU_vTaskSetApplicationTaskTag #define xTaskGetApplicationTaskTag MPU_xTaskGetApplicationTaskTag #define xTaskCallApplicationTaskHook MPU_xTaskCallApplicationTaskHook #define uxTaskGetStackHighWaterMark MPU_uxTaskGetStackHighWaterMark #define xTaskGetCurrentTaskHandle MPU_xTaskGetCurrentTaskHandle #define xTaskGetSchedulerState MPU_xTaskGetSchedulerState #define xTaskGetIdleTaskHandle MPU_xTaskGetIdleTaskHandle #define uxTaskGetSystemState MPU_uxTaskGetSystemState #define xQueueGenericCreate MPU_xQueueGenericCreate #define xQueueCreateMutex MPU_xQueueCreateMutex #define xQueueGiveMutexRecursive MPU_xQueueGiveMutexRecursive #define xQueueTakeMutexRecursive MPU_xQueueTakeMutexRecursive #define xQueueCreateCountingSemaphore MPU_xQueueCreateCountingSemaphore #define xQueueGenericSend MPU_xQueueGenericSend #define xQueueAltGenericSend MPU_xQueueAltGenericSend #define xQueueAltGenericReceive MPU_xQueueAltGenericReceive #define xQueueGenericReceive MPU_xQueueGenericReceive #define uxQueueMessagesWaiting MPU_uxQueueMessagesWaiting #define vQueueDelete MPU_vQueueDelete #define xQueueGenericReset MPU_xQueueGenericReset #define xQueueCreateSet MPU_xQueueCreateSet #define xQueueSelectFromSet MPU_xQueueSelectFromSet #define xQueueAddToSet MPU_xQueueAddToSet #define xQueueRemoveFromSet MPU_xQueueRemoveFromSet #define xQueuePeekFromISR MPU_xQueuePeekFromISR #define xQueueGetMutexHolder MPU_xQueueGetMutexHolder #define pvPortMalloc MPU_pvPortMalloc #define vPortFree MPU_vPortFree #define xPortGetFreeHeapSize MPU_xPortGetFreeHeapSize #define vPortInitialiseBlocks MPU_vPortInitialiseBlocks #if configQUEUE_REGISTRY_SIZE > 0 #define vQueueAddToRegistry MPU_vQueueAddToRegistry #define vQueueUnregisterQueue MPU_vQueueUnregisterQueue #endif /* Remove the privileged function macro. */ #define PRIVILEGED_FUNCTION #else /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ /* Ensure API functions go in the privileged execution section. */ #define PRIVILEGED_FUNCTION __attribute__((section("privileged_functions"))) #define PRIVILEGED_DATA __attribute__((section("privileged_data"))) #endif /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ #else /* portUSING_MPU_WRAPPERS */ #define PRIVILEGED_FUNCTION #define PRIVILEGED_DATA #define portUSING_MPU_WRAPPERS 0 #endif /* portUSING_MPU_WRAPPERS */ #endif /* MPU_WRAPPERS_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/os/mpu_wrappers.h
C
apache-2.0
5,122
/* * Routines to access hardware * * Copyright (c) 2013 Realtek Semiconductor Corp. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. */ #include "osdep_service.h" #include "device_lock.h" //------------------------------------------------------ #define DEVICE_MUTEX_IS_INIT(device) (mutex_init & (1<<device)) #define DEVICE_MUTEX_SET_INIT(device) (mutex_init |= (1<<device)) #define DEVICE_MUTEX_CLR_INIT(device) (mutex_init &= (~(1<<device))) static u32 mutex_init = 0; static _mutex device_mutex[RT_DEV_LOCK_MAX]; //====================================================== static void device_mutex_init(RT_DEV_LOCK_E device) { if(!DEVICE_MUTEX_IS_INIT(device)){ _lock lock; _irqL irqL; rtw_enter_critical(&lock, &irqL); if(!DEVICE_MUTEX_IS_INIT(device)){ rtw_mutex_init(&device_mutex[device]); DEVICE_MUTEX_SET_INIT(device); } rtw_exit_critical(&lock, &irqL); } } //====================================================== void device_mutex_free(RT_DEV_LOCK_E device) { if(DEVICE_MUTEX_IS_INIT(device)){ _lock lock; _irqL irqL; rtw_enter_critical(&lock, &irqL); if(!DEVICE_MUTEX_IS_INIT(device)){ rtw_mutex_free(&device_mutex[device]); DEVICE_MUTEX_CLR_INIT(device); } rtw_exit_critical(&lock, &irqL); } } //====================================================== void device_mutex_lock(RT_DEV_LOCK_E device) { device_mutex_init(device); while(rtw_mutex_get_timeout(&device_mutex[device], 10000)<0) printf("device lock timeout: %d\n", (int)device); } //====================================================== void device_mutex_unlock(RT_DEV_LOCK_E device) { device_mutex_init(device); rtw_mutex_put(&device_mutex[device]); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/os/os_dep/device_lock.c
C
apache-2.0
1,785
/* * Routines to access hardware * * Copyright (c) 2013 Realtek Semiconductor Corp. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. */ #ifndef _DEVICE_LOCK_H_ #define _DEVICE_LOCK_H_ enum _RT_DEV_LOCK_E { RT_DEV_LOCK_EFUSE = 0, RT_DEV_LOCK_FLASH = 1, RT_DEV_LOCK_CRYPTO = 2, RT_DEV_LOCK_PTA = 3, RT_DEV_LOCK_WLAN = 4, RT_DEV_LOCK_MAX = 5 }; typedef uint32_t RT_DEV_LOCK_E; void device_mutex_lock(RT_DEV_LOCK_E device); void device_mutex_unlock(RT_DEV_LOCK_E device); #endif //_DEVICE_LOCK_H_
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/os/os_dep/include/device_lock.h
C
apache-2.0
614
/****************************************************************************** * Copyright (c) 2013-2016 Realtek Semiconductor Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ #ifndef __OSDEP_SERVICE_H_ #define __OSDEP_SERVICE_H_ /** @addtogroup RTOS * @{ */ /*************************** OS dep feature enable *******************************/ /****************************************************** * Macros ******************************************************/ #define CONFIG_LITTLE_ENDIAN #if defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B) || defined(CONFIG_PLATFORM_8721D) #ifndef CONFIG_PLATFORM_AMEBA_X #define CONFIG_PLATFORM_AMEBA_X 1 #endif #endif #if defined(CONFIG_PLATFORM_8195A) #define CONFIG_USE_TCM_HEAP 1 /* USE TCM HEAP */ #define USE_MUTEX_FOR_SPINLOCK 1 #endif #if defined(CONFIG_PLATFORM_AMEBA_X) #define CONFIG_MEM_MONITOR MEM_MONITOR_SIMPLE #else #define CONFIG_MEM_MONITOR MEM_MONITOR_LEAK #endif /* Define compilor specific symbol */ /*************************** inline functions *******************************/ #if defined ( __ICCARM__ ) #define __inline__ inline #define __inline inline #define __inline_definition //In dialect C99, inline means that a function's definition is provided //only for inlining, and that there is another definition //(without inline) somewhere else in the program. //That means that this program is incomplete, because if //add isn't inlined (for example, when compiling without optimization), //then main will have an unresolved reference to that other definition. // Do not inline function is the function body is defined .c file and this // function will be called somewhere else, otherwise there is compile error #elif defined ( __CC_ARM ) #define __inline__ __inline //__linine__ is not supported in keil compilor, use __inline instead #define inline __inline #define __inline_definition // for dialect C99 #elif defined ( __GNUC__ ) #define __inline__ inline #define __inline inline #define __inline_definition inline #endif #include <stdio.h> #if defined(CONFIG_PLATFORM_8195A) || defined(CONFIG_PLATFORM_8711B) || defined(CONFIG_PLATFORM_8721D) #include "platform_autoconf.h" #else //for 8189FM/8189FTV add by frankie_li 20160408 #ifndef SUCCESS #define SUCCESS 0 #endif #ifndef FAIL #define FAIL (-1) #endif #ifndef _SUCCESS #define _SUCCESS 1 #endif #ifndef _FAIL #define _FAIL 0 #endif #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE (!FALSE) #endif #define _TRUE TRUE #define _FALSE FALSE #endif #if defined( PLATFORM_FREERTOS) #include "freertos_service.h" #elif defined( PLATFORM_ECOS) #include "ecos/ecos_service.h" #elif defined( PLATFORM_ALIOS) #include "aos_osdep.h" #endif #ifndef pdTRUE #define pdTRUE ( 1 ) #endif #ifndef pdFALSE #define pdFALSE ( 0 ) #endif #ifndef pdPASS #define pdPASS ( 1 ) #endif #ifndef pdFAIL #define pdFAIL ( 0 ) #endif #define RTW_MAX_DELAY 0xFFFFFFFF #define RTW_WAIT_FOREVER 0xFFFFFFFF /****************************************************** * Constants ******************************************************/ /** * @brief Definitions returned by xTaskGetSchedulerState(). */ #define OS_SCHEDULER_NOT_STARTED 0 #define OS_SCHEDULER_RUNNING 1 #define OS_SCHEDULER_SUSPENDED 2 /****************************************************** * Structures ******************************************************/ struct timer_list { _timerHandle timer_hdl; unsigned long data; void (*function)(void *); }; /****************************************************** * Type Definitions ******************************************************/ typedef void* (*thread_func_t)(void*); typedef void (*TIMER_FUN)(void* timer, void *context); typedef int (*event_handler_t)(char *buf, int buf_len, int flags, void *user_data); #define CONFIG_THREAD_COMM_SEMA struct task_struct { const char *task_name; aos_task_t task; /* I: workqueue thread */ #ifdef CONFIG_THREAD_COMM_SIGNAL const char *name; /* I: workqueue thread name */ u32 queue_num; /* total signal num */ u32 cur_queue_num; /* cur signal num should < queue_num */ #elif defined(CONFIG_THREAD_COMM_SEMA) _sema wakeup_sema; _sema terminate_sema; // _queue work_queue; //TODO #endif u32 blocked; u32 callback_running; }; typedef struct { _xqueue event_queue; struct task_struct thread; }rtw_worker_thread_t; typedef struct { event_handler_t function; char *buf; int buf_len; int flags; void *user_data; } rtw_event_message_t; struct worker_timer_entry { struct list_head list; _timerHandle timer_hdl; rtw_event_message_t message; rtw_worker_thread_t *worker_thread; u32 timeout; }; #ifdef CONFIG_THREAD_COMM_SIGNAL struct work_struct; typedef void (*work_func_t)(void *context); struct work_struct { _list list; u32 data; work_func_t func; void *context; struct task_struct *used_wq; }; struct delayed_work { struct work_struct work; struct timer_list timer; }; #endif #ifdef CONFIG_MEM_MONITOR /*************************** Memory Monitor *******************************/ #define MEM_MONITOR_SIMPLE 0x1 #define MEM_MONITOR_LEAK 0x2 #define MEM_MONITOR_FLAG_WIFI_DRV 0x1 #define MEM_MONITOR_FLAG_WPAS 0x2 #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK struct mem_entry { struct list_head list; int size; void *ptr; }; #endif #define ALLOC_CPSR u32 cpsr /** * @brief This function initializes a memory table. * @param[in] pmem_table: The pointer to the memory table. * @param[in] used_num: The number of mem_entry kept in monitor which will be set to 0. * @return None */ void init_mem_monitor(_list *pmem_table, int *used_num); /** * @brief This function deinitializes a memory table. * @param[in] pmem_table: The pointer to the memory table. * @param[in] used_num: The number of mem_entry kept in monitor. * @return None */ void deinit_mem_monitor(_list *pmem_table, int *used_num); /** * @brief This function alloc mem_entry to the memory table. * @param[in] pmem_table: The pointer to the memory table to be added. * @param[in] ptr: The pointer to the position to be added. * @param[in] size: The size of added memory. * @param[in] used_num: The number of mem_entry kept in monitor which will add 1 after. * @param[in] flag: MEM_MONITOR_FLAG_WPAS/MEM_MONITOR_FLAG_WIFI_DRV * @return None */ void add_mem_usage(_list *pmem_table, void *ptr, int size, int *used_num, int flag); /** * @brief This function frees memory from the memory table. * @param[in] pmem_table: The pointer to the memory table * @param[in] ptr: The pointer to the position to be free. * @param[in] used_num: The number of mem_entry kept in monitor. * @param[in] flag: MEM_MONITOR_FLAG_WPAS/MEM_MONITOR_FLAG_WIFI_DRV * @return None */ void del_mem_usage(_list *pmem_table, void *ptr, int *used_num, int flag); /** * @brief This function get the memory usage of a memory table. * @param[in] pmem_table: The pointer to the memory table. * @return The size of the memory used */ int get_mem_usage(_list *pmem_table); /*************************** End Memory Monitor *******************************/ #endif /*************************** Memory Management *******************************/ u8* _rtw_vmalloc(u32 sz); u8* _rtw_zvmalloc(u32 sz); void _rtw_vmfree(u8 *pbuf, u32 sz); u8* _rtw_zmalloc(u32 sz); u8* _rtw_malloc(u32 sz); void _rtw_mfree(u8 *pbuf, u32 sz); #ifdef CONFIG_MEM_MONITOR /** * @brief This function allocates the virtually contiguous memory. * @param[in] sz: The size of memory to be allocated. * @return The pointer to the beginning of the memory */ u8* rtw_vmalloc(u32 sz); /** * @brief This function allocates the virtually contiguous memory * and the values of the memory are setted to 0. * @param[in] sz: The size of memory to be allocated. * @return The pointer to the beginning of the memory */ u8* rtw_zvmalloc(u32 sz); /** * @brief This function frees the virtually contiguous memory. * @param[in] pbuf: The pointer to the beginning of the memory to be free * @param[in] sz: The size of memory allocated. * @return None */ void rtw_vmfree(u8 *pbuf, u32 sz); /** * @brief This function allocates the memory * and the values of the memory are setted to 0. * @param[in] sz: The size of memory to be allocated. * @return The pointer to the beginning of the memory */ u8* rtw_zmalloc(u32 sz); /** * @brief This function allocates the memory. * @param[in] sz: The size of memory to be allocated. * @return The pointer to the beginning of the memory */ u8* rtw_malloc(u32 sz); /** * @brief This function frees the virtually contiguous memory. * @param[in] pbuf: The pointer to the beginning of the memory to be free * @param[in] sz: The size of memory allocated. * @return None */ void rtw_mfree(u8 *pbuf, u32 sz); #else #define rtw_vmalloc _rtw_vmalloc #define rtw_zvmalloc _rtw_zvmalloc #define rtw_vmfree _rtw_vmfree #define rtw_zmalloc _rtw_zmalloc #define rtw_malloc _rtw_malloc #define rtw_mfree _rtw_mfree #endif #define rtw_free(buf) rtw_mfree((u8 *)buf, 0) /** * @brief This function allocates a 2 dimensional array memory. * @param[in] h: The height of the 2D array. * @param[in] w: The width of the 2D array. * @param[in] size: The size of the each charactor in array. * @return the pointer to the beginning of the block */ void* rtw_malloc2d(int h, int w, int size); /** * @brief This function deallocates the block of memory previously allocated to make it available again. * @param[in] pbuf: Pointer to a memory block previously allocated. * @param[in] h: The height of the 2D array. * @param[in] w: The width of the 2D array. * @param[in] size: The size of the each charactor in array. * @return None */ void rtw_mfree2d(void *pbuf, int h, int w, int size); /** * @brief This function copies the values of "sz" bytes from the location pointed to by "src" * directly to the memory block pointed to by "des". * @param[in] dst: Pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*. * @param[in] src: Pointer to the source of data to be copied, type-casted to a pointer of type void*. * @param[in] sz: Size of memory to copy. * @return None */ void rtw_memcpy(void* dst, void* src, u32 sz); /** * @brief This function compares the first "sz" bytes of the block of memory pointed by "dst" * to the first "sz" bytes pointed by "src". * @param[in] dst: Pointer to block of memory to be compared. * @param[in] src: pointer to block of memory to compare. * @param[in] sz: Size of memory to compare. * @return <0: The first byte that does not match in both memory blocks has a lower value in dst than in src. * @return 0: The contents of both memory blocks are equal. * @return <0: The first byte that does not match in both memory blocks has a greater value in dst than in src. */ int rtw_memcmp(void *dst, void *src, u32 sz); /** * @brief This function sets the first "sz" bytes of the block of memory pointed by "pbuf" to the specified "c". * @param[in] pbuf: Pointer to the block of memory to fill. * @param[in] c: Value to be set. * @param[in] sz: Size of memory to be set to the value "c". * @return None */ void rtw_memset(void *pbuf, int c, u32 sz); /*************************** End Memory Management *******************************/ /*************************** List *******************************/ /** * @brief This function initializes the head of the list. * @param[in] list: Pointer to the list to be initialized. * @return None */ void rtw_init_listhead(_list *list); /** * @brief This function tests whether a list is empty. * @param[in] phead: Pointer to the list to test. * @return _TRUE/_FALSE */ u32 rtw_is_list_empty(_list *phead); /** * @brief This function adds a new entry after "phead" for the list. * @param[in] plist: Pointer to the list to be added. * @param[in] phead: List head to add it after. * @return None */ void rtw_list_insert_head(_list *plist, _list *phead); /** * @brief This function adds a new entry before "phead" for the list. * @param[in] plist: Pointer to the list to be added. * @param[in] phead: List head to add it before. * @return None */ void rtw_list_insert_tail(_list *plist, _list *phead); /** * @brief This function deletes entry from list and reinitialize it. * @param[in] plist: The element to delete from the list. * @return None * @note Caller must check if the list is empty before calling rtw_list_delete */ void rtw_list_delete(_list *plist); /*************************** End List *******************************/ /*************************** Semaphores *******************************/ /** * @brief This function initializes the unnamed semaphore referred to by "sema" to the value "init_val". * @param[in] sema: Pointer to the semaphore handle to be initialized. * @param[in] init_val: Initial value for semaphore. * @return None */ void rtw_init_sema(_sema *sema, int init_val); /** * @brief This function deletes the semaphore. * @param[in] sema: The semaphore to be deleted. * @return None */ void rtw_free_sema(_sema *sema); /** * @brief This function releases the semaphore. * This macro must not be used from an ISR. * @param[in] sema: The semaphore to be released. * @return None */ void rtw_up_sema(_sema *sema); /** * @brief This function releases the semaphore. * This macro can be used from an ISR. * @param[in] sema: The semaphore to be released. * @return None */ void rtw_up_sema_from_isr(_sema *sema); /** * @brief This function acquires the semaphore. If no more tasks are allowed to acquire the semaphore, * calling this function will put the task to sleep until the semaphore is up. * @param[in] sema: The semaphore to be acquired. * @return pdTRUE: The semaphore was obtained. * @return pdFALSE: Obtain the semaphore failed. */ u32 rtw_down_sema(_sema *sema); /** * @brief This function acquires the semaphore. If no more tasks are allowed to acquire the semaphore, * calling this function will put the task to sleep until the semaphore is up. * @param[in] sema: The semaphore to be acquired. * @param[in] timeout: The time in ms to wait for the semaphore to become available. * @return pdTRUE: The semaphore was obtained. * @return pdFALSE: Timeout without the semaphore becoming available. */ u32 rtw_down_timeout_sema(_sema *sema, u32 timeout); /*************************** End Semaphores *******************************/ /*************************** Mutexes *******************************/ /** * @brief This function implements a mutex semaphore by using the existing queue mechanism. * @param[in] pmutex: Pointer to the created mutex semaphore. * @return None */ void rtw_mutex_init(_mutex *pmutex); /** * @brief This function deletes the mutex semaphore. * @param[in] pmutex: Pointer to the mutex semaphore to be deleted. * @return None */ void rtw_mutex_free(_mutex *pmutex); /** * @brief This function releases a mutex semaphore. * @param[in] pmutex: Pointer to the mutex semaphore to be released. * @return None */ void rtw_mutex_put(_mutex *pmutex); /** * @brief This function obtains a mutex semaphore. * @param[in] pmutex: Pointer to the mutex semaphore being taken - obtained when * the mutex semaphore was created. * @return None */ void rtw_mutex_get(_mutex *pmutex); /** * @brief This function obtains a mutex semaphore with a timeout setting. * @param[in] pmutex: Pointer to the mutex semaphore being taken - obtained when * the mutex semaphore was created. * @param[in] timeout: The time in ms to wait for the semaphore to become available. * @return 0: The semaphore was obtained. * @return -1: Timeout without the semaphore becoming available. */ int rtw_mutex_get_timeout(_mutex *pmutex, u32 timeout_ms); /*************************** End Mutexes *******************************/ /*************************** SchedulerControl *******************************/ /** * @brief This function marks the start of a critical code region. * Preemptive context switches cannot occur when in a critical region. * @param[in] plock: Pointer to the spin lock semaphore. * @param[in] pirqL: Pointer to the IRQ. * @return None * @note: This may alter the stack (depending on the portable implementation) * so must be used with care! */ #if 1 void rtw_enter_critical(_lock *plock, _irqL *pirqL); /** * @brief This function marks end of a critical code region. Preemptive context * switches cannot occur when in a critical region. * @param[in] plock: Pointer to the spin lock semaphore. * @param[in] pirqL: Pointer to the IRQ. * @return None * @note: This may alter the stack (depending on the portable implementation) * so must be used with care! */ void rtw_exit_critical(_lock *plock, _irqL *pirqL); /** * @brief This function marks the start of a critical code region from isr. * @param[in] plock: Pointer to the spin lock semaphore. * @param[in] pirqL: Pointer to the IRQ. * @return None */ void rtw_enter_critical_from_isr(_lock *plock, _irqL *pirqL); /** * @brief This function marks the end of a critical code region from isr. * @param[in] plock: Pointer to the spin lock semaphore. * @param[in] pirqL: Pointer to the IRQ. * @return None */ void rtw_exit_critical_from_isr(_lock *plock, _irqL *pirqL); #else #define rtw_enter_critical(plock,pirqL) {cpsr =cpu_intrpt_save();} #define rtw_exit_critical(plock,pirqL) {cpu_intrpt_restore(cpsr);} #define rtw_enter_critical_from_isr(plock,pirqL) {cpsr =cpu_intrpt_save();} #define rtw_exit_critical_from_isr(plock,pirqL) {cpu_intrpt_restore(cpsr);} #endif /** * @brief This function obtains a spin lock semaphore. * @param[in] plock: Pointer to the spin lock semaphore being taken - obtained when * the mutex semaphore was created. * @param[in] pirqL: Pointer to the IRQ. * @return None */ void rtw_enter_critical_bh(_lock *plock, _irqL *pirqL); /** * @brief This function releases a spin lock semaphore. * @param[in] plock: Pointer to the spin lock semaphore to be released. * @param[in] pirqL: Pointer to the IRQ. * @return None */ void rtw_exit_critical_bh(_lock *plock, _irqL *pirqL); /** * @brief This function obtains a semaphore. * @param[in] pmutex: The handle to the mutex semaphore to be obtained. * @param[in] pirqL: Pointer to the IRQ. * @return None */ int rtw_enter_critical_mutex(_mutex *pmutex, _irqL *pirqL); /** * @brief This function releases a semaphore. * @param[in] pmutex: The handle to the mutex semaphore to be released. * @param[in] pirqL: Pointer to the IRQ. * @return None */ void rtw_exit_critical_mutex(_mutex *pmutex, _irqL *pirqL); /*************************** End SchedulerControl *******************************/ /*************************** Semaphores *******************************/ /** * @brief This function implements a spin lock semaphore by using the existing queue mechanism. * @param[in] plock: Pointer to the created spin lock semaphore. * @return None */ void rtw_spinlock_init(_lock *plock); /** * @brief This function deletes the spin lock semaphore. * @param[in] pmutex: Pointer to the spin lock semaphore to be deleted. * @return None */ void rtw_spinlock_free(_lock *plock); /** * @brief This function obtains a spin lock semaphore. * @param[in] plock: Pointer to the spin lock semaphore being taken - obtained when * the mutex semaphore was created. * @return None */ void rtw_spin_lock(_lock *plock); /** * @brief This function releases a spin lock semaphore. * @param[in] plock: Pointer to the spin lock semaphore to be released. * @return None */ void rtw_spin_unlock(_lock *plock); /** * @brief This function marks the start of a critical code region and * obtains a spin lock semaphore. * @param[in] plock: Pointer to the spin lock semaphore being taken - obtained when * the mutex semaphore was created. * @param[in] irqL: Pointer to the IRQ. * @return None */ void rtw_spinlock_irqsave(_lock *plock, _irqL *irqL); /** * @brief This function releases a spin lock semaphore and marks the end of a critical code region. * @param[in] plock: Pointer to the spin lock semaphore to be released. * @param[in] irqL: Pointer to the IRQ. * @return None */ void rtw_spinunlock_irqsave(_lock *plock, _irqL *irqL); /*************************** End Semaphores *******************************/ /*************************** Queues *******************************/ /** * @brief This function creates a new queue instance. * @param[in] queue: The handle to the newly created queue. * @param[in] name: The name of the queue * @param[in] message_size: The number of bytes each message in the queue will require. * @param[in] number_of_messages: The maximum number of messages that kthe queue can contain. * @return 0: Creating queue success * @return -1: Creating queue fail */ int rtw_init_xqueue( _xqueue* queue, const char* name, u32 message_size, u32 number_of_messages ); /** * @brief This function posts a message to the back of a queue. * The message is queued by copy, not by reference. * @param[in] queue: The handle to the queue on which the message is to be posted. * @param[in] message: The pointer to the message that is to be placed on the queue. * @param[in] timeout_ms: The maximum amout of time the task should block waiting for the space to become available on the queue, should it already be full. The time is defined in ms. * @return 0: The message was successfully posted. * @return -1: The message was not posted. */ int rtw_push_to_xqueue( _xqueue* queue, void* message, u32 timeout_ms ); /** * @brief This function receives a message from a queue. * The message is recieved by copy so a buffer adequate size must be provided. * @param[in] queue: The handle to the queue from which the message is to be received. * @param[in] message: The pointer to the buffer into which the received message will be copied. * @param[in] timeout_ms: The maximum amout of time the task should block waiting for a message to * receive should the queue be empty at the time of the call. The time is defined in ms. * @return 0: A message was successfully received from the queue. * @return -1: No message was received from the queue. */ int rtw_pop_from_xqueue( _xqueue* queue, void* message, u32 timeout_ms ); /** * @brief Delete a queue - freeing all the memory allocated for storing of messages placed on the queue. * @param[in] queue: The handle to the queue to be deleted. * @return 0: The queue was successfully deleted. * @return -1: The queue was not empty so cannot be deleted. */ int rtw_deinit_xqueue( _xqueue* queue ); /** * @brief This function creates a new queue instance. * @param[in] pqueue: The handle to the newly created queue. * @return None */ void rtw_init_queue(_queue *pqueue); void rtw_deinit_queue(_queue *pqueue); u32 rtw_is_queue_empty(_queue *pqueue); /** * @brief This function tests whether the queue is empty. * @param[in] pqueue: The handle to the queue to be tested. * @return None */ u32 rtw_queue_empty(_queue *pqueue); /** * @brief This function tests whether the "pelement" is at the "queue". * @param[in] queue: The pointer to the queue that to be tested. * @param[in] pelement: The element that to be tested. * @return _TRUE/_FALSE */ u32 rtw_end_of_queue_search(_list *queue, _list *pelement); _list* rtw_get_queue_head(_queue *queue); /*************************** End Queues *******************************/ /*************************** Time Management *******************************/ /** * @brief Get the count of ticks since the vTaskStartScheduler was called. * @return The count of ticks since the vTaskStartScheduler was called. */ u32 rtw_get_current_time(void); /** * @brief Convert system time to milliseconds. * @param[in] systime: The system time to be converted. * @return : The milliseconds that converted by the system time. */ u32 rtw_systime_to_ms(u32 systime); /** * @brief Convert system time to seconds. * @param[in] systime: The system time to be converted. * @return : The seconds that converted by the system time. */ u32 rtw_systime_to_sec(u32 systime); /** * @brief Convert milliseconds to system time. * @param[in] systime: The milliseconds to be converted. * @return : The system time that converted by the milliseconds. */ u32 rtw_ms_to_systime(u32 ms); /** * @brief Convert seconds to system time. * @param[in] systime: The seconds to be converted. * @return : The system time that converted by the seconds. */ u32 rtw_sec_to_systime(u32 sec); /** * @brief Get the passing time from the "start" in milliseconds. * @param[in] start: The start time which is in system time format. * @return : The passing time from "start" in milliseconds. */ s32 rtw_get_passing_time_ms(u32 start); /** * @brief Get the interval time from the "start" to "end" in milliseconds. * @param[in] start: The start time which is in system time format. * @param[in] end: The end time which is in system time format. * @return : The interval time from "start" to "end" in milliseconds. */ s32 rtw_get_time_interval_ms(u32 start, u32 end); /*************************** End Time Management *******************************/ /** * @brief This function suspends execution of the calling thread for "ms" milliseconds. * @param[in] ms: The time that the function sleep in milliseconds * @return None */ void rtw_msleep_os(int ms); /** * @brief This function suspends execution of the calling thread for "us" microseconds. * @param[in] ms: The time that the function sleep in microseconds * @return None */ void rtw_usleep_os(int us); /** * @brief This function converts the initial portion of the string to integer. * @param[in] s: The pointer to the string to be converted. * @return The converted value. */ u32 rtw_atoi(u8* s); /** * @brief This function delays a task for the giving time in milliseconds. * @param[in] ms: The amount of time, in milliseconds, that the calling task should block. * @return None */ void rtw_mdelay_os(int ms); /** * @brief This function delays a task for the giving time in microseconds. * @param[in] ms: The amount of time, in microseconds, that the calling task should block. * @return None */ void rtw_udelay_os(int us); /** * @brief This function for forcing a context switch. * @return None */ void rtw_yield_os(void); /*************************** ATOMIC Integer *******************************/ /** * @brief This function atomically sets the value of the variable. * @param[in] v: Pointer of type atomic_t that to be set value. * @param[in] i: Required value. * @return None * @note The guaranteed useful range of an atomic_t is only 24 bits. */ void ATOMIC_SET(ATOMIC_T *v, int i); /** * @brief This function atomically reads the value of the variable. * @param[in] v: Pointer of type atomic_t that to be read. * @return The value of the variable. * @note The guaranteed useful range of an atomic_t is only 24 bits. */ int ATOMIC_READ(ATOMIC_T *v); /** * @brief This function adds "i" to the contained "v". * @param[in] v: Pointer of type atomic_t. * @param[in] i: value to add. * @return None */ void ATOMIC_ADD(ATOMIC_T *v, int i); /** * @brief This function subtracts "i" from th econtained "v". * @param[in] v: Pointer of type atomic_t. * @param[in] i: value to subtract. * @return None */ void ATOMIC_SUB(ATOMIC_T *v, int i); /** * @brief This function adds 1 to the contained "v". * @param[in] v: Pointer of type atomic_t. * @return None */ void ATOMIC_INC(ATOMIC_T *v); /** * @brief This function subtracts 1 from th econtained "v". * @param[in] v: Pointer of type atomic_t. * @return None */ void ATOMIC_DEC(ATOMIC_T *v); /** * @brief This function adds "i" to the contained "v" and returns the result. * @param[in] v: Pointer of type atomic_t. * @param[in] i: value to add. * @return None */ int ATOMIC_ADD_RETURN(ATOMIC_T *v, int i); /** * @brief This function subtracts "i" from th econtained "v" and returns the result. * @param[in] v: Pointer of type atomic_t. * @param[in] i: value to subtract. * @return None */ int ATOMIC_SUB_RETURN(ATOMIC_T *v, int i); /** * @brief This function adds 1 to the contained "v" and returns the result. * @param[in] v: Pointer of type atomic_t. * @return None */ int ATOMIC_INC_RETURN(ATOMIC_T *v); /** * @brief This function subtracts 1 from th econtained "v" and returns the result. * @param[in] v: Pointer of type atomic_t. * @return None */ int ATOMIC_DEC_RETURN(ATOMIC_T *v); /** * @brief This function subtracts 1 from th econtained "v" and test if the result equals 0. * @param[in] v: Pointer of type atomic_t. * @return 0: The result after subtracting 1 is 0 * @return -1: The result after subtracting 1 is not 0 */ int ATOMIC_DEC_AND_TEST(ATOMIC_T *v); /*************************** End ATOMIC *******************************/ u64 rtw_modular64(u64 x, u64 y); /** * @brief This function generates random bytes. * @param[in] dst: The pointer to the buffer to store the random bytes. * @param[in] size: The size of the random bytes. * @return 0 */ int rtw_get_random_bytes(void* dst, u32 size); /** * @brief This function gets the available heap size. * @return The value of the available heap size. */ u32 rtw_getFreeHeapSize(void); void flush_signals_thread(void); /** * @brief This function indicates that the WLAN needs to stay on which means cannot go into power saving mode. * @return None * @note Defining configUSE_WAKELOCK_PMU 1 in "FreeRTOSConfig.h" needs to be done before compiling, * or this API won't be effective. */ void rtw_acquire_wakelock(void); /** * @brief This function indicates that the WLAN does not need to stay on which means can go into power saving mode. * @return None * @note Defining configUSE_WAKELOCK_PMU 1 in "FreeRTOSConfig.h" needs to be done before compiling, * or this API won't be effective. */ void rtw_release_wakelock(void); void rtw_wakelock_timeout(u32 timeout); /*********************************** Thread related *****************************************/ /** * @brief This function creates a new task and adds it to the list of tasks that are ready to run. * @param[in] task: The task stucture which will store the task related infomation. * @param[in] name: A descriptive name for the task. * @param[in] stack_size: The size of the task stack specified as the variables the stack can hold. * @param[in] priority: The priority at which the task should run. * @param[in] func: The task entry function. * @param[in] thctx: The pointer that will be used as the parameter for the task being created. * @return pdPASS: The task was successfully created and added to a ready list. * @return other error code defined in the file errors.h. * @note For the task name, please do not use "rtw_little_wifi_mcu_thread", "rtw_check_in_req_state_thread", "rtw_TDMA_change_state_thread", "xmit_thread", "recv_thread", "rtw_recv_tasklet", "rtw_xmit_tasklet", "rtw_interrupt_thread", "cmd_thread", "usb_init", "MSC_BULK_CMD" and "MSC_BULK_DATA". */ int rtw_create_task(struct task_struct *task, const char *name, u32 stack_size, u32 priority, thread_func_t func, void *thctx); /** * @brief This function deletes a task. * @param[in] task: The task stucture which will be deleted. * @return None */ void rtw_delete_task(struct task_struct * task); /** * @brief This function wake up a task. * @param[in] task: The task stucture which will be waked up. * @return None */ void rtw_wakeup_task(struct task_struct *task); void rtw_set_priority_task(void* task, u32 NewPriority ); int rtw_get_priority_task(void* task); void rtw_suspend_task (void* task); void rtw_resume_task (void* task); /** * @brief This function creates a new worker thread. * @param[in] worker_thread: The pointer to the worker thread stucture. * @param[in] priority: The priority of the thread. * @param[in] stack_size: The size of the thread stack specified as the variables the stack can hold. * @param[in] event_queue_size: The queue size of events. * @return SUCCESS/FAIL. */ int rtw_create_worker_thread( rtw_worker_thread_t* worker_thread, u8 priority, u32 stack_size, u32 event_queue_size ); /** * @brief This function deletes a worker thread. * @param[in] worker_thread: The pointer to the worker thread stucture to be deleted. * @return SUCCESS/FAIL. */ int rtw_delete_worker_thread( rtw_worker_thread_t* worker_thread ); #if 0 //TODO void rtw_init_delayed_work(struct delayed_work *dwork, work_func_t func, const char *name); void rtw_deinit_delayed_work(struct delayed_work *dwork); int rtw_queue_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork, u32 delay, void* context); BOOLEAN rtw_cancel_delayed_work(struct delayed_work *dwork); #endif /** * @brief This function prints the name of the thread in DBG_INFO. * @param[in] name: The name of the thread. * @return None */ void rtw_thread_enter(char *name); /** * @brief This function exits the calling thread. * @return None */ void rtw_thread_exit(void); /** * @brief This function gets the scheduler state of the calling thread. * @return OS_SCHEDULER_NOT_STARTED * @return OS_SCHEDULER_RUNNING * @return OS_SCHEDULER_SUSPENDED */ u8 rtw_get_scheduler_state(void); /*************************** End Threads *******************************/ #ifdef PLATFORM_LINUX #define rtw_warn_on(condition) WARN_ON(condition) #else #define rtw_warn_on(condition) do {} while (0) #endif /*************************** Timers *******************************/ /** * @brief This function creates a new software timer instance. * @param[in] pcTimerName: A text name that is assigned to the timer. * @param[in] xTimerPeriodInTicks: The timer period which is defined in tick periods. * @param[in] uxAutoReload: If uxAutoReload is set to pdTRUE then the timer will * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. If * uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and * enter the dormant state after it expires. * @param[in] pvTimerID: An identifier that is assigned to the timer being created. * @param[in] pxCallbackFunction: The function to call when the timer expires. * @return If the timer is successfully create then a handle to the newly * created timer is returned. If the timer cannot be created, then 0 is returned. */ _timerHandle rtw_timerCreate( const signed char *pcTimerName, osdepTickType xTimerPeriodInTicks, u32 uxAutoReload, void * pvTimerID, TIMER_FUN pxCallbackFunction ); /** * @brief This function deletes a timer that was previously created using rtw_timerCreate. * @param[in] xTimer: The handle of the timer being deleted. * @param[in] xBlockTime: Specifies th etime, in ticks, that the calling task should be held in the Blocked * State to wait for the delete command to be successfully sent to the timer command queue, * should the queue already be full when rtw_timerDelete was called. * @return pdFAIL will be returned if the delete command could not be sent to * the timer command queue even after xTicksToWait ticks had passed. pdPASS will * be returned if the command was successfully sent to the timer command queue. * When the command is actually processed will depend on the priority of the * timer service/daemon task relative to other tasks in the system. */ u32 rtw_timerDelete( _timerHandle xTimer, osdepTickType xBlockTime ); /** * @brief This function queries a timer to see if it is active or dormant. * @param[in] xTimer: The timer being queried. * @return pdFALSE will be returned if the timer is dormant. A value other than * pdFALSE will be returned if the timer is active. * @note A timer will be dormant if: * 1) It has been created but not started, or * 2) It is an expired one-shot timer that has not been restarted. */ u32 rtw_timerIsTimerActive( _timerHandle xTimer ); /** * @brief This function stops a timer that was previously started. * @param[in] xTimer: The handle of the timer being stopped. * @param[in] xBlockTime: Specifies the time, in ticks, that the calling task should * be held in the Blocked state to wait for the stop command to be successfully * sent to the timer command queue, should the queue already be full when * rtw_timerStop() was called. * @return pdFAIL will be returned if the stop command could not be sent to * the timer command queue even after xTicksToWait ticks had passed. pdPASS will * be returned if the command was successfully sent to the timer command queue. * When the command is actually processed will depend on the priority of the * timer service/daemon task relative to other tasks in the system. */ u32 rtw_timerStop( _timerHandle xTimer, osdepTickType xBlockTime ); /** * @brief This function changes the period of a timer that was previously created. * @param[in] xTimer: The handle of the timer that is having its period changed. * @param[in] xNewPeriod: The new period for xTimer. * @param[in] xBlockTime: Specifies the time, in ticks, that the calling task should * be held in the Blocked state to wait for the change period command to be * successfully sent to the timer command queue, should the queue already be * full when rtw_timerChangePeriod() was called. * @return pdFAIL will be returned if the change period command could not be * sent to the timer command queue even after xTicksToWait ticks had passed. * pdPASS will be returned if the command was successfully sent to the timer * command queue. When the command is actually processed will depend on the * priority of the timer service/daemon task relative to other tasks in the * system. */ u32 rtw_timerChangePeriod( _timerHandle xTimer, osdepTickType xNewPeriod, osdepTickType xBlockTime ); void *rtw_timerGetID( _timerHandle xTimer ); u32 rtw_timerStart( _timerHandle xTimer, osdepTickType xBlockTime ); u32 rtw_timerStartFromISR( _timerHandle xTimer, osdepBASE_TYPE *pxHigherPriorityTaskWoken ); u32 rtw_timerStopFromISR( _timerHandle xTimer, osdepBASE_TYPE *pxHigherPriorityTaskWoken ); u32 rtw_timerResetFromISR( _timerHandle xTimer, osdepBASE_TYPE *pxHigherPriorityTaskWoken ); u32 rtw_timerChangePeriodFromISR( _timerHandle xTimer, osdepTickType xNewPeriod, osdepBASE_TYPE *pxHigherPriorityTaskWoken ); u32 rtw_timerReset( _timerHandle xTimer, osdepTickType xBlockTime ); /*************************** End Timers *******************************/ #define LIST_CONTAINOR(ptr, type, member) \ ((type *)((char *)(ptr)-(SIZE_T)((char *)&((type *)ptr)->member - (char *)ptr))) #define time_after(a,b) ((long)(b) - (long)(a) < 0) #define time_before(a,b) time_after(b,a) #define time_after_eq(a,b) ((long)(a) - (long)(b) >= 0) #define time_before_eq(a,b) time_after_eq(b,a) #define _RND(sz, r) ((((sz)+((r)-1))/(r))*(r)) #define RND4(x) (((x >> 2) + (((x & 3) == 0) ? 0: 1)) << 2) __inline static u32 _RND4(u32 sz) { u32 val; val = ((sz >> 2) + ((sz & 3) ? 1: 0)) << 2; return val; } __inline static u32 _RND8(u32 sz) { u32 val; val = ((sz >> 3) + ((sz & 7) ? 1: 0)) << 3; return val; } __inline static u32 _RND128(u32 sz) { u32 val; val = ((sz >> 7) + ((sz & 127) ? 1: 0)) << 7; return val; } __inline static u32 _RND256(u32 sz) { u32 val; val = ((sz >> 8) + ((sz & 255) ? 1: 0)) << 8; return val; } __inline static u32 _RND512(u32 sz) { u32 val; val = ((sz >> 9) + ((sz & 511) ? 1: 0)) << 9; return val; } __inline static u32 bitshift(u32 bitmask) { u32 i; for (i = 0; i <= 31; i++) if (((bitmask>>i) & 0x1) == 1) break; return i; } /* Macros for handling unaligned memory accesses */ #define RTW_GET_BE16(a) ((u16) (((a)[0] << 8) | (a)[1])) #define RTW_PUT_BE16(a, val) \ do { \ (a)[0] = ((u16) (val)) >> 8; \ (a)[1] = ((u16) (val)) & 0xff; \ } while (0) #define RTW_GET_LE16(a) ((u16) (((a)[1] << 8) | (a)[0])) #define RTW_PUT_LE16(a, val) \ do { \ (a)[1] = ((u16) (val)) >> 8; \ (a)[0] = ((u16) (val)) & 0xff; \ } while (0) #define RTW_GET_BE24(a) ((((u32) (a)[0]) << 16) | (((u32) (a)[1]) << 8) | \ ((u32) (a)[2])) #define RTW_PUT_BE24(a, val) \ do { \ (a)[0] = (u8) ((((u32) (val)) >> 16) & 0xff); \ (a)[1] = (u8) ((((u32) (val)) >> 8) & 0xff); \ (a)[2] = (u8) (((u32) (val)) & 0xff); \ } while (0) #define RTW_GET_BE32(a) ((((u32) (a)[0]) << 24) | (((u32) (a)[1]) << 16) | \ (((u32) (a)[2]) << 8) | ((u32) (a)[3])) #define RTW_PUT_BE32(a, val) \ do { \ (a)[0] = (u8) ((((u32) (val)) >> 24) & 0xff); \ (a)[1] = (u8) ((((u32) (val)) >> 16) & 0xff); \ (a)[2] = (u8) ((((u32) (val)) >> 8) & 0xff); \ (a)[3] = (u8) (((u32) (val)) & 0xff); \ } while (0) #define RTW_GET_LE32(a) ((((u32) (a)[3]) << 24) | (((u32) (a)[2]) << 16) | \ (((u32) (a)[1]) << 8) | ((u32) (a)[0])) #define RTW_PUT_LE32(a, val) \ do { \ (a)[3] = (u8) ((((u32) (val)) >> 24) & 0xff); \ (a)[2] = (u8) ((((u32) (val)) >> 16) & 0xff); \ (a)[1] = (u8) ((((u32) (val)) >> 8) & 0xff); \ (a)[0] = (u8) (((u32) (val)) & 0xff); \ } while (0) #define RTW_GET_BE64(a) ((((u64) (a)[0]) << 56) | (((u64) (a)[1]) << 48) | \ (((u64) (a)[2]) << 40) | (((u64) (a)[3]) << 32) | \ (((u64) (a)[4]) << 24) | (((u64) (a)[5]) << 16) | \ (((u64) (a)[6]) << 8) | ((u64) (a)[7])) #define RTW_PUT_BE64(a, val) \ do { \ (a)[0] = (u8) (((u64) (val)) >> 56); \ (a)[1] = (u8) (((u64) (val)) >> 48); \ (a)[2] = (u8) (((u64) (val)) >> 40); \ (a)[3] = (u8) (((u64) (val)) >> 32); \ (a)[4] = (u8) (((u64) (val)) >> 24); \ (a)[5] = (u8) (((u64) (val)) >> 16); \ (a)[6] = (u8) (((u64) (val)) >> 8); \ (a)[7] = (u8) (((u64) (val)) & 0xff); \ } while (0) #define RTW_GET_LE64(a) ((((u64) (a)[7]) << 56) | (((u64) (a)[6]) << 48) | \ (((u64) (a)[5]) << 40) | (((u64) (a)[4]) << 32) | \ (((u64) (a)[3]) << 24) | (((u64) (a)[2]) << 16) | \ (((u64) (a)[1]) << 8) | ((u64) (a)[0])) struct osdep_service_ops { u8* (*rtw_vmalloc)(u32 sz); u8* (*rtw_zvmalloc)(u32 sz); void (*rtw_vmfree)(u8 *pbuf, u32 sz); u8* (*rtw_malloc)(u32 sz); u8* (*rtw_zmalloc)(u32 sz); void (*rtw_mfree)(u8 *pbuf, u32 sz); void (*rtw_memcpy)(void* dst, void* src, u32 sz); int (*rtw_memcmp)(void *dst, void *src, u32 sz); void (*rtw_memset)(void *pbuf, int c, u32 sz); void (*rtw_init_sema)(_sema *sema, int init_val); void (*rtw_free_sema)(_sema *sema); void (*rtw_up_sema)(_sema *sema); void (*rtw_up_sema_from_isr)(_sema *sema); u32 (*rtw_down_timeout_sema)(_sema *sema, u32 timeout); void (*rtw_mutex_init)(_mutex *pmutex); void (*rtw_mutex_free)(_mutex *pmutex); void (*rtw_mutex_get)(_mutex *pmutex); int (*rtw_mutex_get_timeout)(_mutex *pmutex, u32 timeout_ms); void (*rtw_mutex_put)(_mutex *pmutex); void (*rtw_enter_critical)(_lock *plock, _irqL *pirqL); void (*rtw_exit_critical)(_lock *plock, _irqL *pirqL); void (*rtw_enter_critical_from_isr)(_lock *plock, _irqL *pirqL); void (*rtw_exit_critical_from_isr)(_lock *plock, _irqL *pirqL); void (*rtw_enter_critical_bh)(_lock *plock, _irqL *pirqL); void (*rtw_exit_critical_bh)(_lock *plock, _irqL *pirqL); int (*rtw_enter_critical_mutex)(_mutex *pmutex, _irqL *pirqL); void (*rtw_exit_critical_mutex)(_mutex *pmutex, _irqL *pirqL); void (*rtw_spinlock_init)(_lock *plock); void (*rtw_spinlock_free)(_lock *plock); void (*rtw_spin_lock)(_lock *plock); void (*rtw_spin_unlock)(_lock *plock); void (*rtw_spinlock_irqsave)(_lock *plock, _irqL *irqL); void (*rtw_spinunlock_irqsave)(_lock *plock, _irqL *irqL); int (*rtw_init_xqueue)( _xqueue* queue, const char* name, u32 message_size, u32 number_of_messages ); int (*rtw_push_to_xqueue)( _xqueue* queue, void* message, u32 timeout_ms ); int (*rtw_pop_from_xqueue)( _xqueue* queue, void* message, u32 timeout_ms ); int (*rtw_deinit_xqueue)( _xqueue* queue ); u32 (*rtw_get_current_time)(void); u32 (*rtw_systime_to_ms)(u32 systime); u32 (*rtw_systime_to_sec)(u32 systime); u32 (*rtw_ms_to_systime)(u32 ms); u32 (*rtw_sec_to_systime)(u32 sec); void (*rtw_msleep_os)(int ms); void (*rtw_usleep_os)(int us); void (*rtw_mdelay_os)(int ms); void (*rtw_udelay_os)(int us); void (*rtw_yield_os)(void); void (*ATOMIC_SET)(ATOMIC_T *v, int i); int (*ATOMIC_READ)(ATOMIC_T *v); void (*ATOMIC_ADD)(ATOMIC_T *v, int i); void (*ATOMIC_SUB)(ATOMIC_T *v, int i); void (*ATOMIC_INC)(ATOMIC_T *v); void (*ATOMIC_DEC)(ATOMIC_T *v); int (*ATOMIC_ADD_RETURN)(ATOMIC_T *v, int i); int (*ATOMIC_SUB_RETURN)(ATOMIC_T *v, int i); int (*ATOMIC_INC_RETURN)(ATOMIC_T *v); int (*ATOMIC_DEC_RETURN)(ATOMIC_T *v); u64 (*rtw_modular64)(u64 x, u64 y); int (*rtw_get_random_bytes)(void* dst, u32 size); u32 (*rtw_getFreeHeapSize)(void); int (*rtw_create_task)(struct task_struct *task, const char *name, u32 stack_size, u32 priority, thread_func_t func, void *thctx); void (*rtw_delete_task)(struct task_struct *task); void (*rtw_wakeup_task)(struct task_struct *task); void (*rtw_set_priority_task)(void* task, u32 NewPriority); int (*rtw_get_priority_task)(void* task); void (*rtw_suspend_task)(void* task); void (*rtw_resume_task)(void* task); #if 0 //TODO void (*rtw_init_delayed_work)(struct delayed_work *dwork, work_func_t func, const char *name); void (*rtw_deinit_delayed_work)(struct delayed_work *dwork); int (*rtw_queue_delayed_work)(struct workqueue_struct *wq, struct delayed_work *dwork, unsigned long delay, void* context); BOOLEAN (*rtw_cancel_delayed_work)(struct delayed_work *dwork); #endif void (*rtw_thread_enter)(char *name); void (*rtw_thread_exit)(void); _timerHandle (*rtw_timerCreate)( const signed char *pcTimerName, osdepTickType xTimerPeriodInTicks, u32 uxAutoReload, void * pvTimerID, TIMER_FUN pxCallbackFunction ); u32 (*rtw_timerDelete)( _timerHandle xTimer, osdepTickType xBlockTime ); u32 (*rtw_timerIsTimerActive)( _timerHandle xTimer ); u32 (*rtw_timerStop)( _timerHandle xTimer, osdepTickType xBlockTime ); u32 (*rtw_timerChangePeriod)( _timerHandle xTimer, osdepTickType xNewPeriod, osdepTickType xBlockTime ); void* (*rtw_timerGetID)( _timerHandle xTimer ); u32 (*rtw_timerStart)( _timerHandle xTimer, osdepTickType xBlockTime ); u32 (*rtw_timerStartFromISR)( _timerHandle xTimer, osdepBASE_TYPE *pxHigherPriorityTaskWoken ); u32 (*rtw_timerStopFromISR)( _timerHandle xTimer, osdepBASE_TYPE *pxHigherPriorityTaskWoken ); u32 (*rtw_timerResetFromISR)( _timerHandle xTimer, osdepBASE_TYPE *pxHigherPriorityTaskWoken ); u32 (*rtw_timerChangePeriodFromISR)( _timerHandle xTimer, osdepTickType xNewPeriod, osdepBASE_TYPE *pxHigherPriorityTaskWoken ); u32 (*rtw_timerReset)( _timerHandle xTimer, osdepTickType xBlockTime ); void (*rtw_acquire_wakelock)(void); void (*rtw_release_wakelock)(void); void (*rtw_wakelock_timeout)(u32 timeoutMs); u8 (*rtw_get_scheduler_state)(void); }; /*\@}*/ #endif //#ifndef __OSDEP_SERVICE_H_ //----------------------------------------------------------------------------//
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/os/os_dep/include/osdep_service.h
C
apache-2.0
48,567
#ifndef _PSRAM_RESERVE_H_ #define _PSRAM_RESERVE_H_ //#include <stdio.h> #include <stdint.h> #include <osdep_service.h> /* NOTE: struct size must be a 2's power! */ typedef struct _PsramMemChunk { struct _PsramMemChunk *next; int size; } PsramMemChunk; typedef PsramMemChunk Psram_heap_buf_t; // A heap typedef struct Psram_Heap { struct _PsramMemChunk *FreeList; ///< Head of the free list } Psram_Heap; /** * Utility macro to allocate a heap of size \a size. * * \param name Variable name for the heap. * \param size Heap size in bytes. */ #define PSRAM_HEAP_DEFINE_BUF(name, size) \ Psram_heap_buf_t name[((size) + sizeof(Psram_heap_buf_t) - 1) / sizeof(Psram_heap_buf_t)] #define Psram_ROUND_UP2(x, pad) (((x) + ((pad) - 1)) & ~((pad) - 1)) /// Initialize \a heap within the buffer pointed by \a memory which is of \a size bytes void Psram_heap_init(void); /// Allocate a chunk of memory of \a size bytes from the heap void *Psram_heap_allocmem(int size); /// Free a chunk of memory of \a size bytes from the heap void Psram_reserved_heap_freemem(void *mem, int size); int Psram_reserve_free_size(void); /** * \name Compatibility interface with C standard library * \{ */ void *Psram_reserve_malloc(int size); void *Psram_reserve_calloc(int num, int size); void Psram_reserve_free(void *mem); /** \} */ extern int g_Psram_heap_inited; #endif /* _PSRAM_RESERVE_H_ */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/os/os_dep/include/psram_reserve.h
C
apache-2.0
1,397
#ifndef STRUCT_HEAP_H #define STRUCT_HEAP_H //#include <stdio.h> #include <stdint.h> #include <osdep_service.h> /* NOTE: struct size must be a 2's power! */ typedef struct _MemChunk { struct _MemChunk *next; int size; } MemChunk; typedef MemChunk heap_buf_t; /// A heap typedef struct Heap { struct _MemChunk *FreeList; ///< Head of the free list } Heap; /** * Utility macro to allocate a heap of size \a size. * * \param name Variable name for the heap. * \param size Heap size in bytes. */ #define HEAP_DEFINE_BUF(name, size) \ heap_buf_t name[((size) + sizeof(heap_buf_t) - 1) / sizeof(heap_buf_t)] /// Initialize \a heap within the buffer pointed by \a memory which is of \a size bytes void tcm_heap_init(void); /// Allocate a chunk of memory of \a size bytes from the heap void *tcm_heap_allocmem(int size); /// Free a chunk of memory of \a size bytes from the heap void tcm_heap_freemem(void *mem, int size); int tcm_heap_freeSpace(void); #define HNEW(heap, type) \ (type*)tcm_heap_allocmem(heap, sizeof(type)) #define HNEWVEC(heap, type, nelem) \ (type*)tcm_heap_allocmem(heap, sizeof(type) * (nelem)) #define HDELETE(heap, type, mem) \ tcm_heap_freemem(heap, mem, sizeof(type)) #define HDELETEVEC(heap, type, nelem, mem) \ tcm_heap_freemem(heap, mem, sizeof(type) * (nelem)) /** * \name Compatibility interface with C standard library * \{ */ void *tcm_heap_malloc(int size); void *tcm_heap_calloc(int size); void tcm_heap_free(void * mem); /** \} */ #endif /* STRUCT_HEAP_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/os/os_dep/include/tcm_heap.h
C
apache-2.0
1,523
/****************************************************************************** * * Copyright(c) 2007 - 2012 Realtek Corporation. All rights reserved. * ******************************************************************************/ #include <osdep_service.h> #if defined(CONFIG_USE_TCM_HEAP) && CONFIG_USE_TCM_HEAP #include "tcm_heap.h" #endif #define OSDEP_DBG(x, ...) do {} while(0) extern struct osdep_service_ops osdep_service; #ifdef CONFIG_LITTLE_ENDIAN u16 _htons(u16 n) { return ((n & 0xff) << 8) | ((n & 0xff00) >> 8); } u16 _ntohs(u16 n) { return _htons(n); } u32 _htonl(u32 n) { return ((n & 0xff) << 24) | ((n & 0xff00) << 8) | ((n & 0xff0000UL) >> 8) | ((n & 0xff000000UL) >> 24); } u32 _ntohl(u32 n) { return _htonl(n); } #endif /* CONFIG_LITTLE_ENDIAN */ /* * Translate the OS dependent @param error_code to OS independent RTW_STATUS_CODE * @return: one of RTW_STATUS_CODE */ int RTW_STATUS_CODE(int error_code) { if(error_code >= 0) return _SUCCESS; return _FAIL; } u32 rtw_atoi(u8* s) { int num=0,flag=0; u32 i; for(i=0;i<=strlen((char *)s);i++) { if(s[i] >= '0' && s[i] <= '9') num = num * 10 + s[i] -'0'; else if(s[0] == '-' && i==0) flag =1; else break; } if(flag == 1) num = num * -1; return(num); } #if defined(CONFIG_USE_TCM_HEAP) && CONFIG_USE_TCM_HEAP void *tcm_heap_malloc(int size); void *tcm_heap_calloc(int size); #endif u8* _rtw_vmalloc(u32 sz) { u8 *pbuf = NULL; #if defined(CONFIG_USE_TCM_HEAP) && CONFIG_USE_TCM_HEAP pbuf = tcm_heap_malloc(sz); #endif if(pbuf==NULL){ if(osdep_service.rtw_vmalloc) { pbuf = osdep_service.rtw_vmalloc(sz); } else OSDEP_DBG("Not implement osdep service: rtw_vmalloc"); } return pbuf; } u8* _rtw_zvmalloc(u32 sz) { u8 *pbuf = NULL; #if defined(CONFIG_USE_TCM_HEAP) && CONFIG_USE_TCM_HEAP pbuf = tcm_heap_calloc(sz); #endif if(pbuf==NULL){ if(osdep_service.rtw_zvmalloc) { pbuf = osdep_service.rtw_zvmalloc(sz); } else OSDEP_DBG("Not implement osdep service: rtw_zvmalloc"); } return pbuf; } void _rtw_vmfree(u8 *pbuf, u32 sz) { #if defined(CONFIG_USE_TCM_HEAP) && CONFIG_USE_TCM_HEAP if( (u32)pbuf > 0x1FFF0000 && (u32)pbuf < 0x20000000 ) tcm_heap_free(pbuf); else #endif { if(osdep_service.rtw_vmfree) { osdep_service.rtw_vmfree(pbuf, sz); } else OSDEP_DBG("Not implement osdep service: rtw_vmfree"); } } u8* _rtw_malloc(u32 sz) { if(osdep_service.rtw_malloc) { u8 *pbuf = osdep_service.rtw_malloc(sz); return pbuf; } else OSDEP_DBG("Not implement osdep service: rtw_malloc"); return NULL; } u8* _rtw_zmalloc(u32 sz) { if(osdep_service.rtw_zmalloc) { u8 *pbuf = osdep_service.rtw_zmalloc(sz); return pbuf; } else OSDEP_DBG("Not implement osdep service: rtw_zmalloc"); return NULL; } u8* _rtw_calloc(u32 nelements, u32 elementSize) { u32 sz = nelements*elementSize; u8* pbuf = _rtw_zmalloc(sz); return pbuf; } void _rtw_mfree(u8 *pbuf, u32 sz) { if(osdep_service.rtw_mfree) { osdep_service.rtw_mfree(pbuf, sz); } else OSDEP_DBG("Not implement osdep service: rtw_mfree"); } #ifdef CONFIG_MEM_MONITOR #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK _list mem_table; int mem_used_num; #endif int min_free_heap_size; void init_mem_monitor(_list *pmem_table, int *used_num) { /* To avoid gcc warnings */ ( void ) pmem_table; ( void ) used_num; #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK rtw_init_listhead(pmem_table); *used_num = 0; #endif min_free_heap_size = rtw_getFreeHeapSize(); } void deinit_mem_monitor(_list *pmem_table, int *used_num) { /* To avoid gcc warnings */ ( void ) pmem_table; ( void ) used_num; #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK _list *plist; struct mem_entry *mem_entry; if(*used_num > 0) DBG_ERR("Have %d mem_entry kept in monitor", *used_num); else DBG_INFO("No mem_entry kept in monitor"); save_and_cli(); while (rtw_end_of_queue_search(pmem_table, get_next(pmem_table)) == _FALSE) { plist = get_next(pmem_table); mem_entry = LIST_CONTAINOR(plist, struct mem_entry, list); DBG_ERR("Not release memory at %p with size of %d", mem_entry->ptr, mem_entry->size); rtw_list_delete(plist); _rtw_mfree((u8 *) mem_entry, sizeof(struct mem_entry)); } restore_flags(); #endif } void add_mem_usage(_list *pmem_table, void *ptr, int size, int *used_num, int flag) { /* To avoid gcc warnings */ ( void ) pmem_table; ( void ) used_num; int free_heap_size = rtw_getFreeHeapSize(); #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK struct mem_entry *mem_entry; #endif if(ptr == NULL) { DBG_ERR("Catch a mem alloc fail with size of %d, current heap free size = %d", size, free_heap_size); return; } else{ if(flag == MEM_MONITOR_FLAG_WPAS) DBG_INFO("Alloc memory at %p with size of %d", ptr, size); else { DBG_INFO("Alloc memory at %p with size of %d", ptr, size); } } #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK mem_entry = (struct mem_entry *) _rtw_malloc(sizeof(struct mem_entry)); if(mem_entry == NULL) { DBG_ERR("Fail to alloc mem_entry"); return; } memset(mem_entry, 0, sizeof(struct mem_entry)); mem_entry->ptr = ptr; mem_entry->size = size; save_and_cli(); rtw_list_insert_head(&mem_entry->list, pmem_table); restore_flags(); *used_num ++; #endif if(min_free_heap_size > free_heap_size) min_free_heap_size = free_heap_size; } void del_mem_usage(_list *pmem_table, void *ptr, int *used_num, int flag) { /* To avoid gcc warnings */ ( void ) pmem_table; ( void ) ptr; ( void ) used_num; ( void ) flag; #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK _list *plist; struct mem_entry *mem_entry = NULL; if(ptr == NULL) return; if(flag == MEM_MONITOR_FLAG_WPAS) DBG_INFO("Free memory at %p", ptr); else DBG_INFO("Free memory at %p", ptr); save_and_cli(); plist = get_next(pmem_table); while ((rtw_end_of_queue_search(pmem_table, plist)) == _FALSE) { mem_entry = LIST_CONTAINOR(plist, struct mem_entry, list); if(mem_entry->ptr == ptr) { rtw_list_delete(plist); break; } plist = get_next(plist); } restore_flags(); if(plist == pmem_table) DBG_ERR("Fail to find the mem_entry in mem table"); else { *used_num --; _rtw_mfree((u8 *) mem_entry, sizeof(struct mem_entry)); } #endif } #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK int get_mem_usage(_list *pmem_table) { _list *plist; struct mem_entry *mem_entry; int mem_usage = 0; int entry_num = 0; save_and_cli(); if((plist = get_next(pmem_table)) == NULL) { DBG_ERR("No mem table available\n"); restore_flags(); return 0; } while (rtw_end_of_queue_search(pmem_table, plist) == _FALSE) { entry_num ++; mem_entry = LIST_CONTAINOR(plist, struct mem_entry, list); mem_usage += mem_entry->size; DBG_INFO("size of mem_entry(%d)=%d\n", entry_num, mem_entry->size); plist = get_next(plist); } restore_flags(); DBG_INFO("Get %d mem_entry\n", entry_num); return mem_usage; } #endif u8* rtw_vmalloc(u32 sz) { u8 *pbuf = _rtw_vmalloc(sz); #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK add_mem_usage(&mem_table, pbuf, sz, &mem_used_num, MEM_MONITOR_FLAG_WIFI_DRV); #else add_mem_usage(NULL, pbuf, sz, NULL, MEM_MONITOR_FLAG_WIFI_DRV); #endif return pbuf; } u8* rtw_zvmalloc(u32 sz) { u8 *pbuf = _rtw_zvmalloc(sz); #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK add_mem_usage(&mem_table, pbuf, sz, &mem_used_num, MEM_MONITOR_FLAG_WIFI_DRV); #else add_mem_usage(NULL, pbuf, sz, NULL, MEM_MONITOR_FLAG_WIFI_DRV); #endif return pbuf; } void rtw_vmfree(u8 *pbuf, u32 sz) { _rtw_vmfree(pbuf, sz); #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK del_mem_usage(&mem_table, pbuf, &mem_used_num, MEM_MONITOR_FLAG_WIFI_DRV); #else del_mem_usage(NULL, pbuf, NULL, MEM_MONITOR_FLAG_WIFI_DRV); #endif } u8* rtw_malloc(u32 sz) { u8 *pbuf = _rtw_malloc(sz); #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK add_mem_usage(&mem_table, pbuf, sz, &mem_used_num, MEM_MONITOR_FLAG_WIFI_DRV); #else add_mem_usage(NULL, pbuf, sz, NULL, MEM_MONITOR_FLAG_WIFI_DRV); #endif return pbuf; } u8* rtw_zmalloc(u32 sz) { u8 *pbuf = _rtw_zmalloc(sz); #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK add_mem_usage(&mem_table, pbuf, sz, &mem_used_num, MEM_MONITOR_FLAG_WIFI_DRV); #else add_mem_usage(NULL, pbuf, sz, NULL, MEM_MONITOR_FLAG_WIFI_DRV); #endif return pbuf; } u8* rtw_calloc(u32 nelements, u32 elementSize) { u8 *pbuf = _rtw_calloc(nelements, elementSize); u32 sz = nelements*elementSize; #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK add_mem_usage(&mem_table, pbuf, sz, &mem_used_num, MEM_MONITOR_FLAG_WIFI_DRV); #else add_mem_usage(NULL, pbuf, sz, NULL, MEM_MONITOR_FLAG_WIFI_DRV); #endif return pbuf; } void rtw_mfree(u8 *pbuf, u32 sz) { _rtw_mfree(pbuf, sz); #if CONFIG_MEM_MONITOR & MEM_MONITOR_LEAK del_mem_usage(&mem_table, pbuf, &mem_used_num, MEM_MONITOR_FLAG_WIFI_DRV); #else del_mem_usage(NULL, pbuf, NULL, MEM_MONITOR_FLAG_WIFI_DRV); #endif } #endif void* rtw_malloc2d(int h, int w, int size) { int j; void **a = (void **) rtw_zmalloc( h*sizeof(void *) + h*w*size ); if(a == NULL) { OSDEP_DBG("%s: alloc memory fail!\n", __FUNCTION__); return NULL; } for( j=0; j<h; j++ ) a[j] = ((char *)(a+h)) + j*w*size; return a; } void rtw_mfree2d(void *pbuf, int h, int w, int size) { rtw_mfree((u8 *)pbuf, h*sizeof(void*) + w*h*size); } void rtw_memcpy(void* dst, void* src, u32 sz) { if(osdep_service.rtw_memcpy) osdep_service.rtw_memcpy(dst, src, sz); else OSDEP_DBG("Not implement osdep service: rtw_memcpy"); } int rtw_memcmp(void *dst, void *src, u32 sz) { if(osdep_service.rtw_memcmp) return osdep_service.rtw_memcmp(dst, src, sz); else OSDEP_DBG("Not implement osdep service: rtw_memcmp"); return _FALSE; } void rtw_memset(void *pbuf, int c, u32 sz) { if(osdep_service.rtw_memset) osdep_service.rtw_memset(pbuf, c, sz); else OSDEP_DBG("Not implement osdep service: rtw_memset"); } void rtw_init_listhead(_list *list) { INIT_LIST_HEAD(list); } /* For the following list_xxx operations, caller must guarantee the atomic context. Otherwise, there will be racing condition. */ u32 rtw_is_list_empty(_list *phead) { if(list_empty(phead)) return _TRUE; return _FALSE; } void rtw_list_insert_head(_list *plist, _list *phead) { list_add(plist, phead); } void rtw_list_insert_tail(_list *plist, _list *phead) { list_add_tail(plist, phead); } /* Caller must check if the list is empty before calling rtw_list_delete */ void rtw_list_delete(_list *plist) { list_del_init(plist); } void rtw_init_sema(_sema *sema, int init_val) { if(osdep_service.rtw_init_sema) osdep_service.rtw_init_sema(sema, init_val); else OSDEP_DBG("Not implement osdep service: rtw_init_sema"); } void rtw_free_sema(_sema *sema) { if(osdep_service.rtw_free_sema) osdep_service.rtw_free_sema(sema); else OSDEP_DBG("Not implement osdep service: rtw_free_sema"); } #if defined(__GNUC__) #include <cmsis.h> #endif int rtw_in_interrupt(void) { #if defined(__ICCARM__) return (__get_PSR()&0x1FF)!=0; #elif defined(__GNUC__) return (__get_xPSR()&0x1FF)!=0; #endif } void rtw_up_sema(_sema *sema) { if(rtw_in_interrupt()){ if(osdep_service.rtw_up_sema_from_isr) osdep_service.rtw_up_sema_from_isr(sema); else OSDEP_DBG("Not implement osdep service: rtw_up_sema_from_isr"); }else{ if(osdep_service.rtw_up_sema) osdep_service.rtw_up_sema(sema); else OSDEP_DBG("Not implement osdep service: rtw_up_sema"); } } void rtw_up_sema_from_isr(_sema *sema) { if(osdep_service.rtw_up_sema_from_isr) osdep_service.rtw_up_sema_from_isr(sema); else OSDEP_DBG("Not implement osdep service: rtw_up_sema_from_isr"); } u32 rtw_down_timeout_sema(_sema *sema, u32 timeout) { if(osdep_service.rtw_down_timeout_sema) return osdep_service.rtw_down_timeout_sema(sema, timeout); else OSDEP_DBG("Not implement osdep service: rtw_down_timeout_sema"); return _FAIL; } u32 rtw_down_sema(_sema *sema) { while(rtw_down_timeout_sema(sema, RTW_MAX_DELAY) != _TRUE) // rom_e_rtw_msg_871X_LEVEL(DOWN_SEMA_1, _drv_always_, "%s(%p) failed, retry\n", __FUNCTION__, sema); //OSDEP_DBG_LEVEL(_drv_always_, "%s(%p) failed, retry\n", __FUNCTION__, sema); OSDEP_DBG("%s(%p) failed, retry\n", __FUNCTION__, sema); return _TRUE; } void rtw_mutex_init(_mutex *pmutex) { if(osdep_service.rtw_mutex_init) osdep_service.rtw_mutex_init(pmutex); else OSDEP_DBG("Not implement osdep service: rtw_mutex_init"); } void rtw_mutex_free(_mutex *pmutex) { if(osdep_service.rtw_mutex_free) osdep_service.rtw_mutex_free(pmutex); else OSDEP_DBG("Not implement osdep service: rtw_mutex_free"); } void rtw_mutex_put(_mutex *pmutex) { if(osdep_service.rtw_mutex_put) osdep_service.rtw_mutex_put(pmutex); else OSDEP_DBG("Not implement osdep service: rtw_mutex_put"); } void rtw_mutex_get(_mutex *pmutex) { if(osdep_service.rtw_mutex_get) osdep_service.rtw_mutex_get(pmutex); else OSDEP_DBG("Not implement osdep service: rtw_mutex_get"); } int rtw_mutex_get_timeout(_mutex *pmutex, u32 timeout_ms) { if(osdep_service.rtw_mutex_get_timeout) return osdep_service.rtw_mutex_get_timeout(pmutex, timeout_ms); else{ OSDEP_DBG("Not implement osdep service: rtw_mutex_get_timeout"); return -1; } } void rtw_enter_critical(_lock *plock, _irqL *pirqL) { if(rtw_in_interrupt()){ if(osdep_service.rtw_enter_critical_from_isr) osdep_service.rtw_enter_critical_from_isr(plock, pirqL); else OSDEP_DBG("Not implement osdep service: rtw_enter_critical_from_isr"); }else{ if(osdep_service.rtw_enter_critical) osdep_service.rtw_enter_critical(plock, pirqL); else OSDEP_DBG("Not implement osdep service: rtw_enter_critical"); } } void rtw_exit_critical(_lock *plock, _irqL *pirqL) { if(rtw_in_interrupt()){ if(osdep_service.rtw_exit_critical_from_isr) osdep_service.rtw_exit_critical_from_isr(plock, pirqL); else OSDEP_DBG("Not implement osdep service: rtw_exit_critical_from_isr"); }else{ if(osdep_service.rtw_exit_critical) osdep_service.rtw_exit_critical(plock, pirqL); else OSDEP_DBG("Not implement osdep service: rtw_exit_critical"); } } void rtw_enter_critical_from_isr(_lock *plock, _irqL *pirqL) { if(osdep_service.rtw_enter_critical) osdep_service.rtw_enter_critical(plock, pirqL); else OSDEP_DBG("Not implement osdep service: rtw_enter_critical_from_isr"); } void rtw_exit_critical_from_isr(_lock *plock, _irqL *pirqL) { if(osdep_service.rtw_exit_critical) osdep_service.rtw_exit_critical(plock, pirqL); else OSDEP_DBG("Not implement osdep service: rtw_exit_critical_from_isr"); } void rtw_enter_critical_bh(_lock *plock, _irqL *pirqL) { /* To avoid gcc warnings */ ( void ) pirqL; rtw_spin_lock(plock); } void rtw_exit_critical_bh(_lock *plock, _irqL *pirqL) { /* To avoid gcc warnings */ ( void ) pirqL; rtw_spin_unlock(plock); } int rtw_enter_critical_mutex(_mutex *pmutex, _irqL *pirqL) { if(osdep_service.rtw_enter_critical_mutex) return osdep_service.rtw_enter_critical_mutex(pmutex, pirqL); else OSDEP_DBG("Not implement osdep service: rtw_enter_critical_mutex"); return 0; } void rtw_exit_critical_mutex(_mutex *pmutex, _irqL *pirqL) { if(osdep_service.rtw_exit_critical_mutex) osdep_service.rtw_exit_critical_mutex(pmutex, pirqL); else OSDEP_DBG("Not implement osdep service: rtw_exit_critical_mutex"); } #if 0 void rtw_cpu_lock(void) { if(osdep_service.rtw_cpu_lock) osdep_service.rtw_cpu_lock(); else OSDEP_DBG("Not implement osdep service: rtw_cpu_lock"); } void rtw_cpu_unlock(void) { if(osdep_service.rtw_cpu_unlock) osdep_service.rtw_cpu_unlock(); else OSDEP_DBG("Not implement osdep service: rtw_cpu_unlock"); } #endif void rtw_init_queue(_queue *pqueue) { rtw_init_listhead(&(pqueue->queue)); rtw_spinlock_init(&(pqueue->lock)); } u32 rtw_queue_empty(_queue *pqueue) { return (rtw_is_list_empty(&(pqueue->queue))); } u32 rtw_end_of_queue_search(_list *head, _list *plist) { if (head == plist) return _TRUE; else return _FALSE; } #if 1 void rtw_spinlock_init(_lock *plock) { if(osdep_service.rtw_spinlock_init) osdep_service.rtw_spinlock_init(plock); else OSDEP_DBG("Not implement osdep service: rtw_spinlock_init"); } void rtw_spinlock_free(_lock *plock) { if(osdep_service.rtw_spinlock_free) osdep_service.rtw_spinlock_free(plock); else OSDEP_DBG("Not implement osdep service: rtw_spinlock_free"); } void rtw_spin_lock(_lock *plock) { if(osdep_service.rtw_spin_lock) osdep_service.rtw_spin_lock(plock); else OSDEP_DBG("Not implement osdep service: rtw_spin_lock"); } void rtw_spin_unlock(_lock *plock) { if(osdep_service.rtw_spin_unlock) osdep_service.rtw_spin_unlock(plock); else OSDEP_DBG("Not implement osdep service: rtw_spin_unlock"); } void rtw_spinlock_irqsave(_lock *plock, _irqL *irqL) { if(osdep_service.rtw_spinlock_irqsave) osdep_service.rtw_spinlock_irqsave(plock, irqL); else OSDEP_DBG("Not implement osdep service: rtw_spinlock_irqsave"); } void rtw_spinunlock_irqsave(_lock *plock, _irqL *irqL) { if(osdep_service.rtw_spinunlock_irqsave) osdep_service.rtw_spinunlock_irqsave(plock, irqL); else OSDEP_DBG("Not implement osdep service: rtw_spinunlock_irqsave"); } #endif int rtw_init_xqueue( _xqueue* queue, const char* name, u32 message_size, u32 number_of_messages ) { if(osdep_service.rtw_init_xqueue) return (int)osdep_service.rtw_init_xqueue(queue, name, message_size, number_of_messages); else OSDEP_DBG("Not implement osdep service: rtw_init_xqueue"); return FAIL; } int rtw_push_to_xqueue( _xqueue* queue, void* message, u32 timeout_ms ) { if(osdep_service.rtw_push_to_xqueue) return (int)osdep_service.rtw_push_to_xqueue(queue, message, timeout_ms); else OSDEP_DBG("Not implement osdep service: rtw_push_to_xqueue"); return FAIL; } int rtw_pop_from_xqueue( _xqueue* queue, void* message, u32 timeout_ms ) { if(osdep_service.rtw_pop_from_xqueue) return (int)osdep_service.rtw_pop_from_xqueue(queue, message, timeout_ms); else OSDEP_DBG("Not implement osdep service: rtw_pop_from_xqueue"); return FAIL; } int rtw_deinit_xqueue( _xqueue* queue ) { if(osdep_service.rtw_deinit_xqueue) return (int)osdep_service.rtw_deinit_xqueue(queue); else OSDEP_DBG("Not implement osdep service: rtw_deinit_xqueue"); return FAIL; } #if 0 void rtw_init_queue(_queue *pqueue) { rtw_init_listhead(&(pqueue->queue)); rtw_mutex_init(&(pqueue->lock)); } void rtw_deinit_queue(_queue *pqueue) { rtw_mutex_free(&(pqueue->lock)); } u32 rtw_is_queue_empty(_queue *pqueue) { return (rtw_is_list_empty(&(pqueue->queue))); } u32 rtw_end_of_queue_search(_list *head, _list *plist) { if (head == plist) return _TRUE; return _FALSE; } _list *rtw_get_queue_head(_queue *queue) { return (&(queue->queue)); } #endif u32 rtw_get_current_time(void) { if(osdep_service.rtw_get_current_time) return osdep_service.rtw_get_current_time(); else OSDEP_DBG("Not implement osdep service: rtw_get_current_time"); return 0; } u32 rtw_systime_to_ms(u32 systime) { if(osdep_service.rtw_systime_to_ms) return osdep_service.rtw_systime_to_ms(systime); else OSDEP_DBG("Not implement osdep service: rtw_systime_to_ms"); return 0; } u32 rtw_systime_to_sec(u32 systime) { if(osdep_service.rtw_systime_to_sec) return osdep_service.rtw_systime_to_sec(systime); else OSDEP_DBG("Not implement osdep service: rtw_systime_to_sec"); return 0; } u32 rtw_ms_to_systime(u32 ms) { if(osdep_service.rtw_ms_to_systime) return osdep_service.rtw_ms_to_systime(ms); else OSDEP_DBG("Not implement osdep service: rtw_ms_to_systime"); return 0; } u32 rtw_sec_to_systime(u32 sec) { if(osdep_service.rtw_sec_to_systime) return osdep_service.rtw_sec_to_systime(sec); else OSDEP_DBG("Not implement osdep service: rtw_sec_to_systime"); return 0; } // the input parameter start use the same unit as returned by rtw_get_current_time s32 rtw_get_passing_time_ms(u32 start) { return rtw_systime_to_ms(rtw_get_current_time() - start); } s32 rtw_get_time_interval_ms(u32 start, u32 end) { return rtw_systime_to_ms(end - start); } void rtw_msleep_os(int ms) { if(osdep_service.rtw_msleep_os) osdep_service.rtw_msleep_os(ms); else OSDEP_DBG("Not implement osdep service: rtw_msleep_os"); } void rtw_usleep_os(int us) { if(osdep_service.rtw_usleep_os) osdep_service.rtw_usleep_os(us); else OSDEP_DBG("Not implement osdep service: rtw_usleep_os"); } void rtw_mdelay_os(int ms) { if(osdep_service.rtw_mdelay_os) osdep_service.rtw_mdelay_os(ms); else OSDEP_DBG("Not implement osdep service: rtw_mdelay_os"); } void rtw_udelay_os(int us) { if(osdep_service.rtw_udelay_os) osdep_service.rtw_udelay_os(us); else OSDEP_DBG("Not implement osdep service: rtw_udelay_os"); } void rtw_yield_os(void) { if(osdep_service.rtw_yield_os) osdep_service.rtw_yield_os(); else OSDEP_DBG("Not implement osdep service: rtw_yield_os"); } void ATOMIC_SET(ATOMIC_T *v, int i) { if(osdep_service.ATOMIC_SET) osdep_service.ATOMIC_SET(v, i); else OSDEP_DBG("Not implement osdep service: ATOMIC_SET"); } int ATOMIC_READ(ATOMIC_T *v) { if(osdep_service.ATOMIC_READ) return osdep_service.ATOMIC_READ(v); else OSDEP_DBG("Not implement osdep service: ATOMIC_READ"); return 0; } void ATOMIC_ADD(ATOMIC_T *v, int i) { if(osdep_service.ATOMIC_ADD) osdep_service.ATOMIC_ADD(v, i); else OSDEP_DBG("Not implement osdep service: ATOMIC_ADD"); } void ATOMIC_SUB(ATOMIC_T *v, int i) { if(osdep_service.ATOMIC_SUB) osdep_service.ATOMIC_SUB(v, i); else OSDEP_DBG("Not implement osdep service: ATOMIC_SUB"); } void ATOMIC_INC(ATOMIC_T *v) { if(osdep_service.ATOMIC_INC) osdep_service.ATOMIC_INC(v); else OSDEP_DBG("Not implement osdep service: ATOMIC_INC"); } void ATOMIC_DEC(ATOMIC_T *v) { if(osdep_service.ATOMIC_DEC) osdep_service.ATOMIC_DEC(v); else OSDEP_DBG("Not implement osdep service: ATOMIC_DEC"); } int ATOMIC_ADD_RETURN(ATOMIC_T *v, int i) { if(osdep_service.ATOMIC_ADD_RETURN) return osdep_service.ATOMIC_ADD_RETURN(v, i); else OSDEP_DBG("Not implement osdep service: ATOMIC_ADD_RETURN"); return 0; } int ATOMIC_SUB_RETURN(ATOMIC_T *v, int i) { if(osdep_service.ATOMIC_SUB_RETURN) return osdep_service.ATOMIC_SUB_RETURN(v, i); else OSDEP_DBG("Not implement osdep service: ATOMIC_SUB_RETURN"); return 0; } int ATOMIC_INC_RETURN(ATOMIC_T *v) { if(osdep_service.ATOMIC_INC_RETURN) return osdep_service.ATOMIC_INC_RETURN(v); else OSDEP_DBG("Not implement osdep service: ATOMIC_INC_RETURN"); return 0; } int ATOMIC_DEC_RETURN(ATOMIC_T *v) { if(osdep_service.ATOMIC_DEC_RETURN) return osdep_service.ATOMIC_DEC_RETURN(v); else OSDEP_DBG("Not implement osdep service: ATOMIC_DEC_RETURN"); return 0; } int ATOMIC_DEC_AND_TEST(ATOMIC_T *v) { return ATOMIC_DEC_RETURN(v) == 0; } u64 rtw_modular64(u64 x, u64 y) { if(osdep_service.rtw_modular64) return osdep_service.rtw_modular64(x, y); else OSDEP_DBG("Not implement osdep service: rtw_modular64"); return 0; } int rtw_get_random_bytes(void* dst, u32 size) { if(osdep_service.rtw_get_random_bytes) return osdep_service.rtw_get_random_bytes(dst, size); else OSDEP_DBG("Not implement osdep service: rtw_get_random_bytes"); return 0; } u32 rtw_getFreeHeapSize(void) { if(osdep_service.rtw_getFreeHeapSize) return osdep_service.rtw_getFreeHeapSize(); else OSDEP_DBG("Not implement osdep service: rtw_getFreeHeapSize"); return 0; } int rtw_netif_queue_stopped(void *pnetdev) { /* To avoid gcc warnings */ ( void ) pnetdev; return 0; } void rtw_netif_wake_queue(void *pnetdev) { /* To avoid gcc warnings */ ( void ) pnetdev; } void rtw_netif_start_queue(void *pnetdev) { /* To avoid gcc warnings */ ( void ) pnetdev; } void rtw_netif_stop_queue(void *pnetdev) { /* To avoid gcc warnings */ ( void ) pnetdev; } void flush_signals_thread(void) { } void rtw_acquire_wakelock(void) { if (osdep_service.rtw_acquire_wakelock) osdep_service.rtw_acquire_wakelock(); else OSDEP_DBG("Not implement osdep service: rtw_acquire_wakelock"); } void rtw_release_wakelock(void) { if (osdep_service.rtw_release_wakelock) osdep_service.rtw_release_wakelock(); else OSDEP_DBG("Not implement osdep service: rtw_release_wakelock"); } void rtw_wakelock_timeout(u32 timeoutms) { if (osdep_service.rtw_wakelock_timeout) osdep_service.rtw_wakelock_timeout(timeoutms); else OSDEP_DBG("Not implement osdep service: rtw_wakelock_timeout"); } int rtw_create_task(struct task_struct *task, const char *name, u32 stack_size, u32 priority, thread_func_t func, void *thctx) { if(osdep_service.rtw_create_task) return osdep_service.rtw_create_task(task, name, stack_size, priority, func, thctx); else OSDEP_DBG("Not implement osdep service: rtw_create_task"); return 1; } void rtw_delete_task(struct task_struct *task) { if(osdep_service.rtw_delete_task) osdep_service.rtw_delete_task(task); else OSDEP_DBG("Not implement osdep service: rtw_delete_task"); return; } void rtw_wakeup_task(struct task_struct *task) { if(osdep_service.rtw_wakeup_task) osdep_service.rtw_wakeup_task(task); else OSDEP_DBG("Not implement osdep service: rtw_wakeup_task"); return; } void rtw_set_priority_task(void* task, u32 NewPriority) { if(osdep_service.rtw_set_priority_task) osdep_service.rtw_set_priority_task(task,NewPriority); else OSDEP_DBG("Not implement osdep service: rtw_set_priority_task"); return; } int rtw_get_priority_task(void* task) { if(osdep_service.rtw_get_priority_task) return osdep_service.rtw_get_priority_task(task); else OSDEP_DBG("Not implement osdep service: rtw_get_priority_task"); return -1; } void rtw_suspend_task(void * task) { if(osdep_service.rtw_suspend_task) osdep_service.rtw_suspend_task(task); else OSDEP_DBG("Not implement osdep service: rtw_suspend_task"); return; } void rtw_resume_task(void * task) { if(osdep_service.rtw_resume_task) osdep_service.rtw_resume_task(task); else OSDEP_DBG("Not implement osdep service: rtw_resume_task"); return; } static void worker_thread_main( void *arg ) { rtw_worker_thread_t* worker_thread = (rtw_worker_thread_t*) arg; while ( 1 ) { rtw_event_message_t message; if ( rtw_pop_from_xqueue( &worker_thread->event_queue, &message, RTW_WAIT_FOREVER ) == SUCCESS ) { message.function(message.buf, message.buf_len, message.flags, message.user_data); if(message.buf){ //printf("\n!!!!!Free %p(%d)\n", message.buf, message.buf_len); _rtw_mfree((u8 *)message.buf, message.buf_len); } } } } int rtw_create_worker_thread( rtw_worker_thread_t* worker_thread, u8 priority, u32 stack_size, u32 event_queue_size ) { if(NULL == worker_thread) return FAIL; memset( worker_thread, 0, sizeof( *worker_thread ) ); if ( rtw_init_xqueue( &worker_thread->event_queue, "worker queue", sizeof(rtw_event_message_t), event_queue_size ) != SUCCESS ) { return FAIL; } if ( !rtw_create_task( &worker_thread->thread, "worker thread", stack_size, priority, (thread_func_t)worker_thread_main, (void*) worker_thread ) ) { rtw_deinit_xqueue( &worker_thread->event_queue ); return FAIL; } return SUCCESS; } int rtw_delete_worker_thread( rtw_worker_thread_t* worker_thread ) { if(NULL == worker_thread) return FAIL; rtw_deinit_xqueue( &worker_thread->event_queue ); rtw_delete_task(&worker_thread->thread); return SUCCESS; } _timerHandle rtw_timerCreate( const signed char *pcTimerName, osdepTickType xTimerPeriodInTicks, u32 uxAutoReload, void * pvTimerID, TIMER_FUN pxCallbackFunction ) { if(osdep_service.rtw_timerCreate) return osdep_service.rtw_timerCreate(pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction); else OSDEP_DBG("Not implement osdep service: rtw_timerCreate"); return 0; } u32 rtw_timerDelete( _timerHandle xTimer, osdepTickType xBlockTime ) { if(osdep_service.rtw_timerDelete) return osdep_service.rtw_timerDelete( xTimer, xBlockTime ); else OSDEP_DBG("Not implement osdep service: rtw_timerDelete"); return 0; } u32 rtw_timerIsTimerActive( _timerHandle xTimer ) { if(osdep_service.rtw_timerIsTimerActive) return osdep_service.rtw_timerIsTimerActive(xTimer); else OSDEP_DBG("Not implement osdep service: rtw_timerIsTimerActive"); return 0; } u32 rtw_timerStop( _timerHandle xTimer, osdepTickType xBlockTime ) { if(osdep_service.rtw_timerStop) return osdep_service.rtw_timerStop(xTimer, xBlockTime); else OSDEP_DBG("Not implement osdep service: rtw_timerStop"); return 0; } u32 rtw_timerChangePeriod( _timerHandle xTimer, osdepTickType xNewPeriod, osdepTickType xBlockTime ) { if(osdep_service.rtw_timerChangePeriod) return osdep_service.rtw_timerChangePeriod(xTimer, xNewPeriod, xBlockTime); else OSDEP_DBG("Not implement osdep service: rtw_timerChangePeriod"); return 0; } void *rtw_timerGetID( _timerHandle xTimer ) { if(osdep_service.rtw_timerGetID) return osdep_service.rtw_timerGetID(xTimer); else OSDEP_DBG("Not implement osdep service: rtw_timerGetID"); return NULL; } u32 rtw_timerStart( _timerHandle xTimer, osdepTickType xBlockTime ) { if(osdep_service.rtw_timerStart) return osdep_service.rtw_timerStart(xTimer, xBlockTime); else OSDEP_DBG("Not implement osdep service: rtw_timerStart"); return 0; } u32 rtw_timerStartFromISR( _timerHandle xTimer, osdepBASE_TYPE *pxHigherPriorityTaskWoken ) { if(osdep_service.rtw_timerStartFromISR) return osdep_service.rtw_timerStartFromISR(xTimer, pxHigherPriorityTaskWoken); else OSDEP_DBG("Not implement osdep service: rtw_timerStartFromISR"); return 0; } u32 rtw_timerStopFromISR( _timerHandle xTimer, osdepBASE_TYPE *pxHigherPriorityTaskWoken ) { if(osdep_service.rtw_timerStopFromISR) return osdep_service.rtw_timerStopFromISR(xTimer, pxHigherPriorityTaskWoken); else OSDEP_DBG("Not implement osdep service: rtw_timerStopFromISR"); return 0; } u32 rtw_timerResetFromISR( _timerHandle xTimer, osdepBASE_TYPE *pxHigherPriorityTaskWoken ) { if(osdep_service.rtw_timerResetFromISR) return osdep_service.rtw_timerResetFromISR(xTimer, pxHigherPriorityTaskWoken); else OSDEP_DBG("Not implement osdep service: rtw_timerResetFromISR"); return 0; } u32 rtw_timerChangePeriodFromISR( _timerHandle xTimer, osdepTickType xNewPeriod, osdepBASE_TYPE *pxHigherPriorityTaskWoken ) { if(osdep_service.rtw_timerChangePeriodFromISR) return osdep_service.rtw_timerChangePeriodFromISR(xTimer, xNewPeriod, pxHigherPriorityTaskWoken); else OSDEP_DBG("Not implement osdep service: rtw_timerChangePeriodFromISR"); return 0; } u32 rtw_timerReset( _timerHandle xTimer, osdepTickType xBlockTime ) { if(osdep_service.rtw_timerReset) return osdep_service.rtw_timerReset(xTimer, xBlockTime); else OSDEP_DBG("Not implement osdep service: rtw_timerReset"); return 0; } #if 0 //TODO void rtw_init_delayed_work(struct delayed_work *dwork, work_func_t func, const char *name) { if(osdep_service.rtw_init_delayed_work) osdep_service.rtw_init_delayed_work(dwork, func, name); else OSDEP_DBG("Not implement osdep service: rtw_init_delayed_work"); return; } void rtw_deinit_delayed_work(struct delayed_work *dwork) { if(osdep_service.rtw_deinit_delayed_work) osdep_service.rtw_deinit_delayed_work(dwork); else OSDEP_DBG("Not implement osdep service: rtw_deinit_delayed_work"); return; } int rtw_queue_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork, u32 delay, void* context) { if(osdep_service.rtw_queue_delayed_work) osdep_service.rtw_queue_delayed_work(wq, dwork, delay, context); else OSDEP_DBG("Not implement osdep service: rtw_queue_delayed_work"); return; } BOOLEAN rtw_cancel_delayed_work(struct delayed_work *dwork) { if(osdep_service.rtw_cancel_delayed_work) osdep_service.rtw_cancel_delayed_work(dwork); else OSDEP_DBG("Not implement osdep service: rtw_cancel_delayed_work"); return; } #endif void rtw_thread_enter(char *name) { if(osdep_service.rtw_thread_enter) osdep_service.rtw_thread_enter(name); else OSDEP_DBG("Not implement osdep service: rtw_thread_enter"); } void rtw_thread_exit() { if(osdep_service.rtw_thread_exit) osdep_service.rtw_thread_exit(); else OSDEP_DBG("Not implement osdep service: rtw_thread_exit"); } u8 rtw_get_scheduler_state() { // OS_SCHEDULER_NOT_STARTED 0 // OS_SCHEDULER_RUNNING 1 // OS_SCHEDULER_SUSPENDED 2 // OS_SCHEDULER_UNREACHABLE 3 if(osdep_service.rtw_get_scheduler_state) return osdep_service.rtw_get_scheduler_state(); else{ OSDEP_DBG("Not implement osdep service: rtw_get_scheduler_state"); return 3; } }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/os/os_dep/osdep_service.c
C
apache-2.0
32,735
#include <string.h> // memset() #include <psram_reserve.h> #include <ameba_soc.h> static struct Psram_Heap g_Psram_heap; int g_Psram_heap_inited = 0; static _lock Psram_heap_lock; #define configTOTAL_PSRAM_HEAP_SIZE (0x200000) #define configBYTE_PSRAM_ALIGNMENT 32 PSRAM_HEAP_SECTION static unsigned char psRAMHeap[configTOTAL_PSRAM_HEAP_SIZE]; void Psram_heap_init(void) { /* Initialize heap with a single big chunk */ g_Psram_heap.FreeList = (PsramMemChunk *)(psRAMHeap); g_Psram_heap.FreeList->next = NULL; g_Psram_heap.FreeList->size = configTOTAL_PSRAM_HEAP_SIZE; g_Psram_heap_inited = 1; rtw_spinlock_init(&Psram_heap_lock); } /** * @brief allocate free memory from PSRAM. * @param size: size of the memory you want. * @retval: header address of the memory allocated. */ void *Psram_heap_allocmem(int size) { PsramMemChunk *chunk, *prev; struct Psram_Heap* h = &g_Psram_heap; _irqL irqL; rtw_enter_critical(&Psram_heap_lock, &irqL); if(!g_Psram_heap_inited) Psram_heap_init(); /* Round size up to the allocation granularity */ size = Psram_ROUND_UP2(size, configBYTE_PSRAM_ALIGNMENT); /* Handle allocations of 0 bytes */ if (!size) size = sizeof(PsramMemChunk); /* Walk on the free list looking for any chunk big enough to * fit the requested block size. */ for (prev = (PsramMemChunk *)&h->FreeList, chunk = h->FreeList; chunk; prev = chunk, chunk = chunk->next) { if (chunk->size >= size) { if (chunk->size == size) { /* Just remove this chunk from the free list */ prev->next = chunk->next; rtw_exit_critical(&Psram_heap_lock, &irqL); return (void *)chunk; } else { /* Allocate from the END of an existing chunk */ chunk->size -= size; void *result = (void *)((uint8_t *)chunk + chunk->size); rtw_exit_critical(&Psram_heap_lock, &irqL); return result; } } } rtw_exit_critical(&Psram_heap_lock, &irqL); return NULL; /* fail */ } /** * @brief free memory in PSRAM. * @param mem: header address of the memory to be freed. * @param size: size of the memory. * @retval none */ void Psram_reserved_heap_freemem(void *mem, int size) { PsramMemChunk *prev; struct Psram_Heap* h = &g_Psram_heap; _irqL irqL; rtw_enter_critical(&Psram_heap_lock, &irqL); if(!g_Psram_heap_inited) Psram_heap_init(); /* Round size up to the allocation granularity */ size = Psram_ROUND_UP2(size, configBYTE_PSRAM_ALIGNMENT); /* Handle allocations of 0 bytes */ if (!size) size = sizeof(PsramMemChunk); /* Special cases: first chunk in the free list or memory completely full */ if (((uint8_t *)mem) < ((uint8_t *)h->FreeList) || !h->FreeList) { /* Insert memory block before the current free list head */ prev = (PsramMemChunk *)mem; prev->next = h->FreeList; prev->size = size; h->FreeList = prev; } else /* Normal case: not the first chunk in the free list */ { /* * Walk on the free list. Stop at the insertion point (when mem * is between prev and prev->next) */ prev = h->FreeList; while (prev->next < (PsramMemChunk *)mem && prev->next) prev = prev->next; /* Should it be merged with previous block? */ if (((uint8_t *)prev) + prev->size == ((uint8_t *)mem)) { /* Yes */ prev->size += size; } else /* not merged with previous chunk */ { PsramMemChunk *curr = (PsramMemChunk*)mem; /* insert it after the previous node * and move the 'prev' pointer forward * for the following operations */ curr->next = prev->next; curr->size = size; prev->next = curr; /* Adjust for the following test */ prev = curr; } } /* Also merge with next chunk? */ if (((uint8_t *)prev) + prev->size == ((uint8_t *)prev->next)) { prev->size += prev->next->size; prev->next = prev->next->next; } rtw_exit_critical(&Psram_heap_lock, &irqL); } /** * @brief get the free memory size in PSRAM. * @retval size of free momery in PSRAM. */ int Psram_reserve_free_size(void) { int free_mem = 0; struct Psram_Heap* h = &g_Psram_heap; _irqL irqL; PsramMemChunk *chunk; rtw_enter_critical(&Psram_heap_lock, &irqL); if(!g_Psram_heap_inited) Psram_heap_init(); for (chunk = h->FreeList; chunk; chunk = chunk->next) free_mem += chunk->size; rtw_exit_critical(&Psram_heap_lock, &irqL); return free_mem; } /** * @brief allocate free memory from PSRAM. * @param size: size of the memory you want. * @retval: header address of the memory allocated. */ void *Psram_reserve_malloc(int size) { int *mem; size += sizeof(int); if ((mem = (int*)Psram_heap_allocmem(size))){ *mem++ = size; } return (void *)mem; } /** * @brief allocate several continuous blocks of free memory from PSRAM. * @param num: num of blocks you want. * @param size: size of every block. * @retval: header address of the memory allocated. */ void *Psram_reserve_calloc(int num, int size) { void *mem; if ((mem = Psram_reserve_malloc(num * size))) memset(mem, 0, num * size); return mem; } /** * @brief free memory in PSRAM. * @param mem: header address of the memory to be freed. * @retval none */ void Psram_reserve_free(void *mem) { int *_mem = (int *)mem; if (_mem) { --_mem; Psram_reserved_heap_freemem(_mem, *_mem); } }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/os/os_dep/psram_reserve.c
C
apache-2.0
5,283
//#include <autoconf.h> #include "tcm_heap.h" #include <string.h> // memset() #include <osdep_service.h> //#define _DEBUG #if CONFIG_USE_TCM_HEAP #define FREE_FILL_CODE 0xDEAD #define ALLOC_FILL_CODE 0xBEEF #define ROUND_UP2(x, pad) (((x) + ((pad) - 1)) & ~((pad) - 1)) #define TCM_HEAP_SIZE (40*1024) static struct Heap g_tcm_heap; #if defined (__ICCARM__) #pragma location=".tcm.heap" #else __attribute__((section(".tcm.heap"))) #endif HEAP_DEFINE_BUF(tcm_heap, TCM_HEAP_SIZE); //unsigned char tcm_heap[TCM_HEAP_SIZE]; static int g_heap_inited=0; static _lock tcm_lock; #if defined(PLATFORM_FREERTOS) extern void vPortSetExtFree( void (*free)( void *p ), uint32_t upper, uint32_t lower ); #elif defined(PLATFORM_CMSIS_RTOS) extern void rtw_set_mfree_ext( void (*free)( void *p ), uint32_t upper, uint32_t lower ); #endif void tcm_heap_init(void) { //#ifdef _DEBUG //memset(memory, FREE_FILL_CODE, size); //#endif //ASSERT2(((int)memory % alignof(heap_buf_t)) == 0, //"memory buffer is unaligned, please use the HEAP_DEFINE_BUF() macro to declare heap buffers!\n"); /* Initialize heap with a single big chunk */ g_tcm_heap.FreeList = (MemChunk *)&tcm_heap; g_tcm_heap.FreeList->next = NULL; g_tcm_heap.FreeList->size = sizeof(tcm_heap); g_heap_inited = 1; rtw_spinlock_init(&tcm_lock); #if defined(PLATFORM_FREERTOS) // let RTOS know how to free memory if using as task stack vPortSetExtFree(tcm_heap_free, 0x20000000, 0x1fff0000); #elif defined(PLATFORM_CMSIS_RTOS) rtw_set_mfree_ext(tcm_heap_free, 0x20000000, 0x1fff0000); #endif } void tcm_heap_dump(void) { MemChunk *chunk, *prev; struct Heap* h = &g_tcm_heap; printf("---Free List--\n\r"); for (prev = (MemChunk *)&h->FreeList, chunk = h->FreeList; chunk; prev = chunk, chunk = chunk->next) { printf(" prev %x, chunk %x, size %d \n\r", prev, chunk, chunk->size); } printf("--------------\n\r"); } void *tcm_heap_allocmem(int size) { MemChunk *chunk, *prev; struct Heap* h = &g_tcm_heap; _irqL irqL; rtw_enter_critical(&tcm_lock, &irqL); if(!g_heap_inited) tcm_heap_init(); /* Round size up to the allocation granularity */ size = ROUND_UP2(size, sizeof(MemChunk)); /* Handle allocations of 0 bytes */ if (!size) size = sizeof(MemChunk); /* Walk on the free list looking for any chunk big enough to * fit the requested block size. */ for (prev = (MemChunk *)&h->FreeList, chunk = h->FreeList; chunk; prev = chunk, chunk = chunk->next) { if (chunk->size >= size) { if (chunk->size == size) { /* Just remove this chunk from the free list */ prev->next = chunk->next; #ifdef _DEBUG memset(chunk, ALLOC_FILL_CODE, size); #endif rtw_exit_critical(&tcm_lock, &irqL); //printf("----ALLOC1-----\n\r"); //tcm_heap_dump(); //printf("--------------\n\r"); return (void *)chunk; } else { /* Allocate from the END of an existing chunk */ chunk->size -= size; #ifdef _DEBUG memset((uint8_t *)chunk + chunk->size, ALLOC_FILL_CODE, size); #endif rtw_exit_critical(&tcm_lock, &irqL); //printf("----ALLOC2-----\n\r"); //tcm_heap_dump(); //printf("--------------\n\r"); return (void *)((uint8_t *)chunk + chunk->size); } } } rtw_exit_critical(&tcm_lock, &irqL); //printf("----ALLOC3-----\n\r"); //tcm_heap_dump(); //printf("--------------\n\r"); return NULL; /* fail */ } void tcm_heap_freemem(void *mem, int size) { MemChunk *prev; //ASSERT(mem); struct Heap* h = &g_tcm_heap; _irqL irqL; rtw_enter_critical(&tcm_lock, &irqL); if(!g_heap_inited) tcm_heap_init(); #ifdef _DEBUG memset(mem, FREE_FILL_CODE, size); #endif /* Round size up to the allocation granularity */ size = ROUND_UP2(size, sizeof(MemChunk)); /* Handle allocations of 0 bytes */ if (!size) size = sizeof(MemChunk); /* Special cases: first chunk in the free list or memory completely full */ //ASSERT((uint8_t*)mem != (uint8_t*)h->FreeList); if (((uint8_t *)mem) < ((uint8_t *)h->FreeList) || !h->FreeList) { /* Insert memory block before the current free list head */ prev = (MemChunk *)mem; prev->next = h->FreeList; prev->size = size; h->FreeList = prev; } else /* Normal case: not the first chunk in the free list */ { /* * Walk on the free list. Stop at the insertion point (when mem * is between prev and prev->next) */ prev = h->FreeList; while (prev->next < (MemChunk *)mem && prev->next) prev = prev->next; /* Make sure mem is not *within* prev */ //ASSERT((uint8_t*)mem >= (uint8_t*)prev + prev->size); /* Should it be merged with previous block? */ if (((uint8_t *)prev) + prev->size == ((uint8_t *)mem)) { /* Yes */ prev->size += size; } else /* not merged with previous chunk */ { MemChunk *curr = (MemChunk*)mem; /* insert it after the previous node * and move the 'prev' pointer forward * for the following operations */ curr->next = prev->next; curr->size = size; prev->next = curr; /* Adjust for the following test */ prev = curr; } } /* Also merge with next chunk? */ if (((uint8_t *)prev) + prev->size == ((uint8_t *)prev->next)) { prev->size += prev->next->size; prev->next = prev->next->next; /* There should be only one merge opportunity, becuase we always merge on free */ //ASSERT((uint8_t*)prev + prev->size != (uint8_t*)prev->next); } rtw_exit_critical(&tcm_lock, &irqL); //printf("---FREE %x--\n\r", mem); //tcm_heap_dump(); //printf("--------------\n\r"); } int tcm_heap_freeSpace(void) { int free_mem = 0; struct Heap* h = &g_tcm_heap; _irqL irqL; MemChunk *chunk; rtw_enter_critical(&tcm_lock, &irqL); if(!g_heap_inited) tcm_heap_init(); for (chunk = h->FreeList; chunk; chunk = chunk->next) free_mem += chunk->size; rtw_exit_critical(&tcm_lock, &irqL); return free_mem; } /** * Standard malloc interface */ void *tcm_heap_malloc(int size) { #if defined(PLATFORM_CMSIS_RTOS) int64_t *mem; // Make sure that block is 8-byte aligned size = (size + 7U) & ~((uint32_t)7U); size += sizeof(int64_t); mem = (int64_t *)tcm_heap_allocmem(size); #else int *mem; size += sizeof(int); mem = (int*)tcm_heap_allocmem(size); #endif if (mem){ *mem++ = size; } return mem; } /** * Standard calloc interface */ void *tcm_heap_calloc(int size) { void *mem; mem = tcm_heap_malloc(size); if (mem) memset(mem, 0, size); return mem; } /** * Free a block of memory, determining its size automatically. * * \param h Heap from which the block was allocated. * \param mem Pointer to a block of memory previously allocated with * either heap_malloc() or heap_calloc(). * * \note If \a mem is a NULL pointer, no operation is performed. * * \note Freeing the same memory block twice has undefined behavior. * * \note This function works like the ANSI C free(). */ void tcm_heap_free(void *mem) { #if defined(PLATFORM_CMSIS_RTOS) int64_t *_mem = (int64_t *)mem; #else int *_mem = (int *)mem; #endif if (_mem) { --_mem; tcm_heap_freemem(_mem, *_mem); } } static void alloc_test(int size, int test_len) { //Simple test uint8_t *a[100]; int i, j; for (i = 0; i < test_len; i++) { a[i] = tcm_heap_allocmem(size); //ASSERT(a[i]); for (j = 0; j < size; j++) a[i][j] = i; } //ASSERT(heap_freeSpace(&h) == HEAP_SIZE - test_len * ROUND_UP2(size, sizeof(MemChunk))); for (i = 0; i < test_len; i++) { for (j = 0; j < size; j++) { printf("a[%d][%d] = %d\n", i, j, a[i][j]); //ASSERT(a[i][j] == i); } tcm_heap_freemem(a[i], size); } //ASSERT(heap_freeSpace(&h) == HEAP_SIZE); } #define ALLOC_SIZE 256 #define ALLOC_SIZE2 1024 #define TEST_LEN 20 #define TEST_LEN2 10 #define HEAP_SIZE 59*1024 int tcm_heap_testRun(void) { alloc_test(ALLOC_SIZE, TEST_LEN); alloc_test(ALLOC_SIZE2, TEST_LEN2); /* Try to allocate the whole heap */ uint8_t *b = tcm_heap_allocmem(HEAP_SIZE); int j; //ASSERT(b); //ASSERT(heap_freeSpace(&h) == 0); //ASSERT(!heap_allocmem(&h, HEAP_SIZE)); for (j = 0; j < HEAP_SIZE; j++) b[j] = j; for (j = 0; j < HEAP_SIZE; j++) { printf("b[%d] = %d\n", j, j); //ASSERT(b[j] == (j & 0xff)); } tcm_heap_freemem(b, HEAP_SIZE); //ASSERT(heap_freeSpace(&h) == HEAP_SIZE); return 0; } #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/os/os_dep/tcm_heap.c
C
apache-2.0
8,301
/* * FreeRTOS Kernel V10.2.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /*----------------------------------------------------------- * Portable layer API. Each function must be defined for each port. *----------------------------------------------------------*/ #ifndef PORTABLE_H #define PORTABLE_H /* Include the macro file relevant to the port being used. NOTE: The following definitions are *DEPRECATED* as it is preferred to instead just add the path to the correct portmacro.h header file to the compiler's include path. */ #ifdef OPEN_WATCOM_INDUSTRIAL_PC_PORT #include "..\..\Source\portable\owatcom\16bitdos\pc\portmacro.h" typedef void ( __interrupt __far *pxISR )(); #endif #ifdef OPEN_WATCOM_FLASH_LITE_186_PORT #include "..\..\Source\portable\owatcom\16bitdos\flsh186\portmacro.h" typedef void ( __interrupt __far *pxISR )(); #endif #ifdef GCC_MEGA_AVR #include "../portable/GCC/ATMega323/portmacro.h" #endif #ifdef IAR_MEGA_AVR #include "../portable/IAR/ATMega323/portmacro.h" #endif #ifdef MPLAB_PIC24_PORT #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" #endif #ifdef MPLAB_DSPIC_PORT #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" #endif #ifdef MPLAB_PIC18F_PORT #include "../../Source/portable/MPLAB/PIC18F/portmacro.h" #endif #ifdef MPLAB_PIC32MX_PORT #include "../../Source/portable/MPLAB/PIC32MX/portmacro.h" #endif #ifdef _FEDPICC #include "libFreeRTOS/Include/portmacro.h" #endif #ifdef SDCC_CYGNAL #include "../../Source/portable/SDCC/Cygnal/portmacro.h" #endif #ifdef GCC_ARM7 #include "../../Source/portable/GCC/ARM7_LPC2000/portmacro.h" #endif #ifdef GCC_ARM7_ECLIPSE #include "portmacro.h" #endif #ifdef ROWLEY_LPC23xx #include "../../Source/portable/GCC/ARM7_LPC23xx/portmacro.h" #endif #ifdef IAR_MSP430 #include "..\..\Source\portable\IAR\MSP430\portmacro.h" #endif #ifdef GCC_MSP430 #include "../../Source/portable/GCC/MSP430F449/portmacro.h" #endif #ifdef ROWLEY_MSP430 #include "../../Source/portable/Rowley/MSP430F449/portmacro.h" #endif #ifdef ARM7_LPC21xx_KEIL_RVDS #include "..\..\Source\portable\RVDS\ARM7_LPC21xx\portmacro.h" #endif #ifdef SAM7_GCC #include "../../Source/portable/GCC/ARM7_AT91SAM7S/portmacro.h" #endif #ifdef SAM7_IAR #include "..\..\Source\portable\IAR\AtmelSAM7S64\portmacro.h" #endif #ifdef SAM9XE_IAR #include "..\..\Source\portable\IAR\AtmelSAM9XE\portmacro.h" #endif #ifdef LPC2000_IAR #include "..\..\Source\portable\IAR\LPC2000\portmacro.h" #endif #ifdef STR71X_IAR #include "..\..\Source\portable\IAR\STR71x\portmacro.h" #endif #ifdef STR75X_IAR #include "..\..\Source\portable\IAR\STR75x\portmacro.h" #endif #ifdef STR75X_GCC #include "..\..\Source\portable\GCC\STR75x\portmacro.h" #endif #ifdef STR91X_IAR #include "..\..\Source\portable\IAR\STR91x\portmacro.h" #endif #ifdef GCC_H8S #include "../../Source/portable/GCC/H8S2329/portmacro.h" #endif #ifdef GCC_AT91FR40008 #include "../../Source/portable/GCC/ARM7_AT91FR40008/portmacro.h" #endif #ifdef RVDS_ARMCM3_LM3S102 #include "../../Source/portable/RVDS/ARM_CM3/portmacro.h" #endif #ifdef GCC_ARMCM3_LM3S102 #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" #endif #ifdef GCC_ARMCM3 #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" #endif #ifdef IAR_ARM_CM3 #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" #endif #ifdef IAR_ARMCM3_LM #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" #endif #ifdef HCS12_CODE_WARRIOR #include "../../Source/portable/CodeWarrior/HCS12/portmacro.h" #endif #ifdef MICROBLAZE_GCC #include "../../Source/portable/GCC/MicroBlaze/portmacro.h" #endif #ifdef TERN_EE #include "..\..\Source\portable\Paradigm\Tern_EE\small\portmacro.h" #endif #ifdef GCC_HCS12 #include "../../Source/portable/GCC/HCS12/portmacro.h" #endif #ifdef GCC_MCF5235 #include "../../Source/portable/GCC/MCF5235/portmacro.h" #endif #ifdef COLDFIRE_V2_GCC #include "../../../Source/portable/GCC/ColdFire_V2/portmacro.h" #endif #ifdef COLDFIRE_V2_CODEWARRIOR #include "../../Source/portable/CodeWarrior/ColdFire_V2/portmacro.h" #endif #ifdef GCC_PPC405 #include "../../Source/portable/GCC/PPC405_Xilinx/portmacro.h" #endif #ifdef GCC_PPC440 #include "../../Source/portable/GCC/PPC440_Xilinx/portmacro.h" #endif #ifdef _16FX_SOFTUNE #include "..\..\Source\portable\Softune\MB96340\portmacro.h" #endif #ifdef BCC_INDUSTRIAL_PC_PORT /* A short file name has to be used in place of the normal FreeRTOSConfig.h when using the Borland compiler. */ #include "frconfig.h" #include "..\portable\BCC\16BitDOS\PC\prtmacro.h" typedef void ( __interrupt __far *pxISR )(); #endif #ifdef BCC_FLASH_LITE_186_PORT /* A short file name has to be used in place of the normal FreeRTOSConfig.h when using the Borland compiler. */ #include "frconfig.h" #include "..\portable\BCC\16BitDOS\flsh186\prtmacro.h" typedef void ( __interrupt __far *pxISR )(); #endif #ifdef __GNUC__ #ifdef __AVR32_AVR32A__ #include "portmacro.h" #endif #endif #ifdef __ICCAVR32__ #ifdef __CORE__ #if __CORE__ == __AVR32A__ #include "portmacro.h" #endif #endif #endif #ifdef __91467D #include "portmacro.h" #endif #ifdef __96340 #include "portmacro.h" #endif #ifdef __IAR_V850ES_Fx3__ #include "../../Source/portable/IAR/V850ES/portmacro.h" #endif #ifdef __IAR_V850ES_Jx3__ #include "../../Source/portable/IAR/V850ES/portmacro.h" #endif #ifdef __IAR_V850ES_Jx3_L__ #include "../../Source/portable/IAR/V850ES/portmacro.h" #endif #ifdef __IAR_V850ES_Jx2__ #include "../../Source/portable/IAR/V850ES/portmacro.h" #endif #ifdef __IAR_V850ES_Hx2__ #include "../../Source/portable/IAR/V850ES/portmacro.h" #endif #ifdef __IAR_78K0R_Kx3__ #include "../../Source/portable/IAR/78K0R/portmacro.h" #endif #ifdef __IAR_78K0R_Kx3L__ #include "../../Source/portable/IAR/78K0R/portmacro.h" #endif /* Catch all to ensure portmacro.h is included in the build. Newer demos have the path as part of the project options, rather than as relative from the project location. If portENTER_CRITICAL() has not been defined then portmacro.h has not yet been included - as every portmacro.h provides a portENTER_CRITICAL() definition. Check the demo application for your demo to find the path to the correct portmacro.h file. */ #ifndef portENTER_CRITICAL #include "portmacro.h" #endif #if portBYTE_ALIGNMENT == 8 #define portBYTE_ALIGNMENT_MASK ( 0x0007U ) #endif #if portBYTE_ALIGNMENT == 4 #define portBYTE_ALIGNMENT_MASK ( 0x0003 ) #endif #if portBYTE_ALIGNMENT == 2 #define portBYTE_ALIGNMENT_MASK ( 0x0001 ) #endif #if portBYTE_ALIGNMENT == 1 #define portBYTE_ALIGNMENT_MASK ( 0x0000 ) #endif #ifndef portBYTE_ALIGNMENT_MASK #error "Invalid portBYTE_ALIGNMENT definition" #endif #ifndef portNUM_CONFIGURABLE_REGIONS #define portNUM_CONFIGURABLE_REGIONS 1 #endif #ifdef __cplusplus extern "C" { #endif #include "mpu_wrappers.h" /* * Setup the stack of a new task so it is ready to be placed under the * scheduler control. The registers have to be placed on the stack in * the order that the port expects to find them. * */ #if( portUSING_MPU_WRAPPERS == 1 ) StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; #else StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) PRIVILEGED_FUNCTION; #endif /* Used by heap_5.c. */ typedef struct HeapRegion { uint8_t *pucStartAddress; size_t xSizeInBytes; } HeapRegion_t; /* * Used to define multiple heap regions for use by heap_5.c. This function * must be called before any calls to pvPortMalloc() - not creating a task, * queue, semaphore, mutex, software timer, event group, etc. will result in * pvPortMalloc being called. * * pxHeapRegions passes in an array of HeapRegion_t structures - each of which * defines a region of memory that can be used as the heap. The array is * terminated by a HeapRegions_t structure that has a size of 0. The region * with the lowest start address must appear first in the array. */ void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ); /* * Map to the memory management routines required for the port. */ void *pvPortMalloc( size_t xSize ) PRIVILEGED_FUNCTION; void vPortFree( void *pv ) PRIVILEGED_FUNCTION; void vPortInitialiseBlocks( void ) PRIVILEGED_FUNCTION; size_t xPortGetFreeHeapSize( void ) PRIVILEGED_FUNCTION; size_t xPortGetMinimumEverFreeHeapSize( void ) PRIVILEGED_FUNCTION; /* * Setup the hardware ready for the scheduler to take control. This generally * sets up a tick interrupt and sets timers for the correct tick frequency. */ BaseType_t xPortStartScheduler( void ) PRIVILEGED_FUNCTION; /* * Undo any hardware/ISR setup that was performed by xPortStartScheduler() so * the hardware is left in its original condition after the scheduler stops * executing. */ void vPortEndScheduler( void ) PRIVILEGED_FUNCTION; /* * The structures and methods of manipulating the MPU are contained within the * port layer. * * Fills the xMPUSettings structure with the memory region information * contained in xRegions. */ #if( portUSING_MPU_WRAPPERS == 1 ) struct xMEMORY_REGION; void vPortStoreTaskMPUSettings( xMPU_SETTINGS *xMPUSettings, const struct xMEMORY_REGION * const xRegions, StackType_t *pxBottomOfStack, uint16_t usStackDepth ) PRIVILEGED_FUNCTION; #endif #ifdef __cplusplus } #endif #endif /* PORTABLE_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/os/portable.h
C
apache-2.0
11,126
/* * FreeRTOS Kernel V10.2.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #ifndef PORTMACRO_H #define PORTMACRO_H #ifdef __cplusplus extern "C" { #endif /*----------------------------------------------------------- * Port specific definitions. * * The settings in this file configure FreeRTOS correctly for the * given hardware and compiler. * * These settings should not be altered. *----------------------------------------------------------- */ /* Type definitions. */ #define portCHAR char #define portFLOAT float #define portDOUBLE double #define portLONG long #define portSHORT short #define portSTACK_TYPE uint32_t #define portBASE_TYPE long typedef portSTACK_TYPE StackType_t; typedef long BaseType_t; typedef unsigned long UBaseType_t; #if( configUSE_16_BIT_TICKS == 1 ) typedef uint16_t TickType_t; #define portMAX_DELAY ( TickType_t ) 0xffff #else typedef uint32_t TickType_t; #define portMAX_DELAY ( TickType_t ) 0xffffffffUL #endif /*-----------------------------------------------------------*/ /* Architecture specifics. */ #define portSTACK_GROWTH ( -1 ) #define portTICK_PERIOD_MS ( ( TickType_t ) 1000 / configTICK_RATE_HZ ) #define portBYTE_ALIGNMENT 8 /*-----------------------------------------------------------*/ /* Scheduler utilities. */ extern void vPortYield( void ); #define portNVIC_INT_CTRL_REG ( * ( ( volatile uint32_t * ) 0xe000ed04 ) ) #define portNVIC_PENDSVSET_BIT ( 1UL << 28UL ) #define portYIELD() vPortYield() #define portEND_SWITCHING_ISR( xSwitchRequired ) if( xSwitchRequired ) portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT #define portYIELD_FROM_ISR( x ) portEND_SWITCHING_ISR( x ) /*-----------------------------------------------------------*/ /* Critical section management. */ extern void vPortEnterCritical( void ); extern void vPortExitCritical( void ); extern uint32_t ulPortSetInterruptMask( void ); extern void vPortClearInterruptMask( uint32_t ulNewMaskValue ); #define portSET_INTERRUPT_MASK_FROM_ISR() ulPortSetInterruptMask() #define portCLEAR_INTERRUPT_MASK_FROM_ISR(x) vPortClearInterruptMask(x) #define portDISABLE_INTERRUPTS() ulPortSetInterruptMask() #define portENABLE_INTERRUPTS() vPortClearInterruptMask(0) #define portENTER_CRITICAL() vPortEnterCritical() #define portEXIT_CRITICAL() vPortExitCritical() /*-----------------------------------------------------------*/ /* Task function macros as described on the FreeRTOS.org WEB site. These are not necessary for to use this port. They are defined so the common demo files (which build with all the ports) will build. */ #define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters ) #define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters ) /*-----------------------------------------------------------*/ /* Tickless idle/low power functionality. */ #ifndef portSUPPRESS_TICKS_AND_SLEEP extern void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ); #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) vPortSuppressTicksAndSleep( xExpectedIdleTime ) #endif /*-----------------------------------------------------------*/ /* Architecture specific optimisations. */ #ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 #endif #if configUSE_PORT_OPTIMISED_TASK_SELECTION == 1 /* Generic helper function. */ __attribute__( ( always_inline ) ) static inline uint8_t ucPortCountLeadingZeros( uint32_t ulBitmap ) { uint8_t ucReturn; __asm volatile ( "clz %0, %1" : "=r" ( ucReturn ) : "r" ( ulBitmap ) ); return ucReturn; } /* Check the configuration. */ #if( configMAX_PRIORITIES > 32 ) #error configUSE_PORT_OPTIMISED_TASK_SELECTION can only be set to 1 when configMAX_PRIORITIES is less than or equal to 32. It is very rare that a system requires more than 10 to 15 difference priorities as tasks that share a priority will time slice. #endif /* Store/clear the ready priorities in a bit map. */ #define portRECORD_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) |= ( 1UL << ( uxPriority ) ) #define portRESET_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) &= ~( 1UL << ( uxPriority ) ) /*-----------------------------------------------------------*/ #define portGET_HIGHEST_PRIORITY( uxTopPriority, uxReadyPriorities ) uxTopPriority = ( 31 - ucPortCountLeadingZeros( ( uxReadyPriorities ) ) ) #endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ /*-----------------------------------------------------------*/ #ifdef configASSERT void vPortValidateInterruptPriority( void ); #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() vPortValidateInterruptPriority() #endif /* portNOP() is not required by this port. */ #define portNOP() #ifdef __cplusplus } #endif #endif /* PORTMACRO_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/os/portmacro.h
C
apache-2.0
6,228
/* * FreeRTOS Kernel V10.2.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #ifndef PROJDEFS_H #define PROJDEFS_H /* * Defines the prototype to which task functions must conform. Defined in this * file to ensure the type is known before portable.h is included. */ typedef void (*TaskFunction_t)( void * ); /* Converts a time in milliseconds to a time in ticks. */ #define pdMS_TO_TICKS( xTimeInMs ) ( ( ( TickType_t ) ( xTimeInMs ) * configTICK_RATE_HZ ) / ( TickType_t ) 1000 ) #define pdFALSE ( ( BaseType_t ) 0 ) #define pdTRUE ( ( BaseType_t ) 1 ) #define pdPASS ( pdTRUE ) #define pdFAIL ( pdFALSE ) #define errQUEUE_EMPTY ( ( BaseType_t ) 0 ) #define errQUEUE_FULL ( ( BaseType_t ) 0 ) /* Error definitions. */ #define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 ) #define errQUEUE_BLOCKED ( -4 ) #define errQUEUE_YIELD ( -5 ) #endif /* PROJDEFS_H */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/os/projdefs.h
C
apache-2.0
2,144
/* * Routines to access hardware * * Copyright (c) 2013 Realtek Semiconductor Corp. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. */ #ifndef _MONITOR_LIB_H_ #define _MONITOR_LIB_H_ _LONG_CALL_ extern u32 cmd_dump_word(u16 argc, u8 *argv[]); _LONG_CALL_ extern u32 cmd_write_word(u16 argc, u8 *argv[]); _LONG_CALL_ extern u32 cmd_flash(u16 argc, u8 *argv[]); _LONG_CALL_ extern u32 cmd_efuse(u16 argc, u8 *argv[]); _LONG_CALL_ u32 cmd_rom_table(void** PTable); #define CmdDumpWord cmd_dump_word #define CmdWriteWord cmd_write_word #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/app/monitor/include/monitor_rom.h
C
apache-2.0
659
/** ****************************************************************************** * @file rtl_trace.h * @author * @version V1.0.0 * @date 2016-05-17 * @brief This file contains all the functions for log print and mask. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2015, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ u32 LOG_PRINTF_BUFFER(const char *fmt); u32 LOG_PRINTF_BUFFER_INIT(u32 thread_init); u32 LOG_BUFF_SUSPEND(void); u32 LOG_BUFF_RESUME(void); #define LOG_BUFFER_NUM 6 #define LOG_BUFFER_SIZE 512 typedef struct { char buffer[LOG_BUFFER_SIZE]; /* please define member after buffer */ } log_buffer_t; extern log_buffer_t log_buffer[]; typedef u32 (*DIAG_PRINT_BUF_FUNC)(const char *fmt); extern DIAG_PRINT_BUF_FUNC ConfigDebugBufferGet; /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/app/monitor/include/rtl_trace.h
C
apache-2.0
1,190
/* * Routines to access hardware * * Copyright (c) 2013 Realtek Semiconductor Corp. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. */ #ifndef _RTK_CONSOL_H_ #define _RTK_CONSOL_H_ //Log UART //UART_LOG_CMD_BUFLEN: only 126 bytes could be used for keeping input // cmd, the last byte is for string end ('\0'). #define UART_LOG_CMD_BUFLEN 127 #define MAX_ARGV 16 typedef u32 (*ECHOFUNC)(IN u8*,...); //UART LOG echo-function type. typedef u32 (*monitor_cmd_handler)(u16 argc, u8* argv[]); typedef struct { u8 BufCount; //record the input cmd char number. u8 UARTLogBuf[UART_LOG_CMD_BUFLEN]; //record the input command. } UART_LOG_BUF, *PUART_LOG_BUF; typedef struct _COMMAND_TABLE_ { const u8* cmd; u16 ArgvCnt; u32 (*func)(u16 argc, u8* argv[]); const u8* msg; }COMMAND_TABLE, *PCOMMAND_TABLE; typedef struct { u8 NewIdx; u8 SeeIdx; u8 RevdNo; u8 EscSTS; u8 ExecuteCmd; u8 ExecuteEsc; u8 BootRdy; u8 Resvd; PUART_LOG_BUF pTmpLogBuf; VOID *pfINPUT; PCOMMAND_TABLE pCmdTbl; u32 CmdTblSz; u32 CRSTS; #ifdef CONFIG_UART_LOG_HISTORY u8 (*pHistoryBuf)[UART_LOG_CMD_BUFLEN]; #endif void (*GiveSema)(void); u32 shell_task_rdy; } UART_LOG_CTL, *PUART_LOG_CTL; #define KB_ASCII_NUL 0x00 #define KB_ASCII_BS 0x08 #define KB_ASCII_TAB 0x09 #define KB_ASCII_LF 0x0A #define KB_ASCII_CR 0x0D #define KB_ASCII_ESC 0x1B #define KB_ASCII_SP 0x20 #define KB_ASCII_BS_7F 0x7F #define KB_ASCII_LBRKT 0x5B //[ #define KB_SPACENO_TAB 1 #ifdef CONFIG_UART_LOG_HISTORY #define UART_LOG_HISTORY_LEN 5 #endif //#ifdef CONFIG_DEBUG_LOG #define _ConsolePrint DiagPrintf //#else //#define _ConsolePrint //#endif #define AMEBA_CONSOLE_PREFIX "#" #define CONSOLE_AMEBA(...) do {\ _ConsolePrint("\r"AMEBA_CONSOLE_PREFIX __VA_ARGS__);\ }while(0) _LONG_CALL_ VOID shell_init_rom(u32 TBLSz, VOID *pTBL); _LONG_CALL_ VOID shell_task_rom(VOID *Data); _LONG_CALL_ VOID shell_rom(u32 MaxWaitCount); _LONG_CALL_ void shell_uart_irq_rom(void * Data); _LONG_CALL_ extern VOID shell_cmd_history( IN u8 RevData, IN UART_LOG_CTL *prvUartLogCtl, IN u8 EchoFlag ); _LONG_CALL_ extern u8 shell_cmd_chk( IN u8 RevData, IN UART_LOG_CTL *prvUartLogCtl, IN u8 EchoFlag ); _LONG_CALL_ extern VOID shell_array_init( IN u8 *pArrayToInit, IN u8 ArrayLen, IN u8 InitValue ); extern u8** shell_get_argv(const u8 *string); extern u8 shell_get_argc(const u8 *string); VOID shell_init_ram(VOID); void shell_switch_ipc_int(VOID *Data, u32 IrqStatus, u32 ChanNum); #define RtlConsolTaskRom shell_task_rom extern u32 shell_recv_all_data_onetime; extern u32 shell_interrupt_on; #endif //_RTK_CONSOL_H_
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/app/monitor/include/shell.h
C
apache-2.0
3,051
#include <stdio.h> #include "ameba_soc.h" #if !defined (__ICCARM__) extern u8 RAM_IMG1_VALID_PATTEN[]; void *tmp = RAM_IMG1_VALID_PATTEN; #endif #if defined ( __ICCARM__ ) size_t __write(int Handle, const unsigned char * Buf, size_t Bufsize) { int nChars = 0; /* Check for stdout and stderr (only necessary if file descriptors are enabled.) */ if (Handle != 1 && Handle != 2) { return -1; } for (/*Empty */; Bufsize > 0; --Bufsize) { DiagPutChar(*Buf++); ++nChars; } return nChars; } size_t __read(int Handle, unsigned char * Buf, size_t Bufsize) { int nChars = 0; /* Check for stdin (only necessary if FILE descriptors are enabled) */ if (Handle != 0) { return -1; } for (/*Empty*/; Bufsize > 0; --Bufsize) { int c = DiagGetChar(_FALSE); if (c < 0) break; *(Buf++) = c; ++nChars; } return nChars; } #else int _write(int file, char * ptr, int len) { int nChars = 0; /* Check for stdout and stderr (only necessary if file descriptors are enabled.) */ if (file != 1 && file != 2) { return -1; } for (/*Empty */; len > 0; --len) { DiagPutChar(*ptr++); ++nChars; } return nChars; } int _read(int file, char * ptr, int len) { int nChars = 0; /* Check for stdin (only necessary if FILE descriptors are enabled) */ if (file != 0) { return -1; } for (/*Empty*/; len > 0; --len) { int c = DiagGetChar(_TRUE); if ((c < 0) || (c == '\r')) { *ptr = '\0'; break; } *(ptr++) = c; ++nChars; } return nChars; } #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/app/monitor/ram/low_level_io.c
C
apache-2.0
1,519
/* * Routines to access hardware * * Copyright (c) 2013 Realtek Semiconductor Corp. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. */ #include "ameba_soc.h" #include "freertos_pmu.h" #include "rom_map.h" KM4SLEEP_ParamDef dsleep_param; u32 CmdRamHelp( IN u16 argc, IN u8 *argv[] ); u32 CmdShellSwitch( IN u16 argc, IN u8 *argv[] ) { /* To avoid gcc warnings */ ( void ) argc; ( void ) argv; InterruptDis(UART_LOG_IRQ); ipc_send_message(IPC_INT_CHAN_SHELL_SWITCH, NULL); return 0; } u32 cmd_reboot( IN u16 argc, IN u8 *argv[] ) { /* To avoid gcc warnings */ ( void ) argc; ( void ) argv; DBG_8195A("\n\rRebooting ...\n\r"); if (_strcmp((const char*)argv[0], "uartburn") == 0){ BKUP_Set(0, BIT_UARTBURN_BOOT); WDG_InitTypeDef WDG_InitStruct; u32 CountProcess; u32 DivFacProcess; WDG_Scalar(5, &CountProcess, &DivFacProcess); WDG_InitStruct.CountProcess = CountProcess; WDG_InitStruct.DivFacProcess = DivFacProcess; WDG_Init(&WDG_InitStruct); WDG_Cmd(ENABLE); return _TRUE; } /* Let KM4 RUN */ u32 Temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LP_BOOT_CFG); Temp |= BIT_SOC_BOOT_PATCH_KM4_RUN; HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_BOOT_CFG, Temp); /* free loguart */ InterruptDis(UART_LOG_IRQ); ipc_send_message(IPC_INT_CHAN_SHELL_SWITCH, NULL); Temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LP_BOOT_CFG); Temp |= BIT_SOC_BOOT_WAKE_FROM_PS_HS; HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_BOOT_CFG, Temp); SOCPS_CPUReset(); return _TRUE; } u32 CmdTickPS( IN u16 argc, IN u8 *argv[] ) { if (_strcmp((const char*)argv[0], "r") == 0){// release if (argc >=2 && _strcmp((const char*)argv[1], "debug") == 0) { pmu_tickless_debug(ENABLE); } else { pmu_tickless_debug(DISABLE); } pmu_release_wakelock(PMU_OS); } if (_strcmp((const char*)argv[0], "a") == 0){// acquire pmu_acquire_wakelock(PMU_OS); } if (_strcmp((const char*)argv[0], "type") == 0){// PG or CG if (argc >=2 && _strcmp((const char*)argv[1], "pg") == 0) { pmu_set_sleep_type(SLEEP_PG); } else if (argc >=2 && _strcmp((const char*)argv[1], "cg") == 0) { pmu_set_sleep_type(SLEEP_CG); } else { pmu_set_sleep_type(SLEEP_PG); } } if (_strcmp((const char*)argv[0], "dslp") == 0){ u32 duration_ms = _strtoul((const char*)(argv[1]), (char **)NULL, 10); dsleep_param.dlps_enable = TRUE; dsleep_param.sleep_time = duration_ms; ipc_send_message(IPC_INT_KM4_TICKLESS_INDICATION, (u32)&dsleep_param); while (1); } if (_strcmp((const char*)argv[0], "get") == 0){// get sleep & wake time DBG_8195A("lockbit:%x \n", pmu_get_wakelock_status()); DBG_8195A("dslp_lockbit:%x\n", pmu_get_deepwakelock_status()); } return _TRUE; } u32 CmdRTC( IN u16 argc, IN u8 *argv[] ) { /* To avoid gcc warnings */ ( void ) argc; RTC_TimeTypeDef RTC_TimeStruct; if (_strcmp((const char*)argv[0], "get") == 0) {// dump RTC RTC_AlarmTypeDef RTC_AlarmStruct_temp; RTC_GetTime(RTC_Format_BIN, &RTC_TimeStruct); RTC_GetAlarm(RTC_Format_BIN, &RTC_AlarmStruct_temp); DBG_8195A("time: %d:%d:%d:%d (%d) \n", RTC_TimeStruct.RTC_Days, RTC_TimeStruct.RTC_Hours, RTC_TimeStruct.RTC_Minutes, RTC_TimeStruct.RTC_Seconds, RTC_TimeStruct.RTC_H12_PMAM); DBG_8195A("alarm: %d:%d:%d:%d (%d) \n", RTC_AlarmStruct_temp.RTC_AlarmTime.RTC_Days, RTC_AlarmStruct_temp.RTC_AlarmTime.RTC_Hours, RTC_AlarmStruct_temp.RTC_AlarmTime.RTC_Minutes, RTC_AlarmStruct_temp.RTC_AlarmTime.RTC_Seconds, RTC_AlarmStruct_temp.RTC_AlarmTime.RTC_H12_PMAM); } if (_strcmp((const char*)argv[0], "set") == 0) { RTC_TimeStructInit(&RTC_TimeStruct); RTC_TimeStruct.RTC_Hours = _strtoul((const char*)(argv[1]), (char **)NULL, 10); RTC_TimeStruct.RTC_Minutes = _strtoul((const char*)(argv[2]), (char **)NULL, 10); RTC_TimeStruct.RTC_Seconds = _strtoul((const char*)(argv[3]), (char **)NULL, 10); if (_strcmp((const char*)argv[5], "pm") == 0) { RTC_TimeStruct.RTC_H12_PMAM = RTC_H12_PM; } else { RTC_TimeStruct.RTC_H12_PMAM = RTC_H12_AM; } RTC_SetTime(RTC_Format_BIN, &RTC_TimeStruct); } return _TRUE; } u32 CmdLogBuf( IN u16 argc, IN u8 *argv[] ) { /* To avoid gcc warnings */ ( void ) argc; if (_strcmp((const char*)argv[0], "on") == 0) { ConfigDebugBuffer = 1; } else { ConfigDebugBuffer = 0; } DiagPrintf("AAAAA\n"); DiagPrintfD("BBBBB\n"); return _TRUE; } u32 cmd_efuse_protect(u16 argc, u8 *argv[]) { /* To avoid gcc warnings */ ( void ) argc; u8 EfuseBuf[1024]; u32 index; u8 ret = 0; /* efuse wmap 0x0 2 2187 */ /* efuse wmap 0x18 4 01020304 */ if (_strcmp((const char*)argv[0], "wmap") == 0) { u32 Addr = _strtoul((const char*)(argv[1]), (char **)NULL, 16); u32 Len = _strtoul((const char*)(argv[2]), (char **)NULL, 16); char* DString = (char*)argv[3]; u32 Cnt; Cnt = _strlen(DString); if (Cnt%2) { MONITOR_LOG("string length(%d) should be odd \n", Cnt); return FALSE; } Cnt = Cnt/2; if (Cnt != Len) { MONITOR_LOG("Oops: write lenth not match input string lentg, choose smaller one\n"); Len = (Cnt < Len) ? Cnt:Len; } MONITOR_LOG("efuse wmap write len:%d, string len:%d\n", Len, Cnt << 1); for (index= 0; index < Len; index++) { EfuseBuf[index] = _2char2hex(DString[index*2], DString[index*2+1]); } EFUSE_LMAP_WRITE(Addr, Len, (u8 *)(EfuseBuf)); } if (_strcmp((const char*)argv[0], "rmap") == 0) { MONITOR_LOG("efuse rmap \n"); ret = EFUSE_LMAP_READ(EfuseBuf); if (ret == _FAIL) { MONITOR_LOG("EFUSE_LogicalMap_Read fail \n"); } for (index = 0; index < 1024; index+=16) { MONITOR_LOG("EFUSE[%03x]: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", index, EfuseBuf[index], EfuseBuf[index+1], EfuseBuf[index+2], EfuseBuf[index+3], EfuseBuf[index+4], EfuseBuf[index+5], EfuseBuf[index+6], EfuseBuf[index+7], EfuseBuf[index+8], EfuseBuf[index+9], EfuseBuf[index+10], EfuseBuf[index+11], EfuseBuf[index+12], EfuseBuf[index+13], EfuseBuf[index+14], EfuseBuf[index+15]); } } if (_strcmp((const char*)argv[0], "rraw") == 0) { MONITOR_LOG("efuse rraw\n"); for (index = 0; index< EFUSE_REAL_CONTENT_LEN; index++) { if ((index < EFUSE_SECURE_START) || (index > EFUSE_SECURE_END)) { EFUSE_PMAP_READ8(0, index, EfuseBuf + index, L25EOUTVOLTAGE); } else { EfuseBuf[index] = 0xFF; } } for (index= 0; index < EFUSE_REAL_CONTENT_LEN; index+=16) { MONITOR_LOG("RawMap[%03x]: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", index, EfuseBuf[index], EfuseBuf[index+1], EfuseBuf[index+2], EfuseBuf[index+3], EfuseBuf[index+4], EfuseBuf[index+5], EfuseBuf[index+6], EfuseBuf[index+7], EfuseBuf[index+8], EfuseBuf[index+9], EfuseBuf[index+10], EfuseBuf[index+11], EfuseBuf[index+12], EfuseBuf[index+13], EfuseBuf[index+14], EfuseBuf[index+15]); } } /* efuse wraw 0xA0 1 aa */ /* efuse wraw 0xA0 2 aabb */ /* efuse wraw 0xA0 4 aabbccdd */ if (_strcmp((const char*)argv[0], "wraw") == 0) { u32 Addr = _strtoul((const char*)(argv[1]), (char **)NULL, 16); u32 Len = _strtoul((const char*)(argv[2]), (char **)NULL, 16); char* DString = (char*)argv[3]; u32 Cnt; Cnt = _strlen(DString); if (Cnt%2) { MONITOR_LOG("string length(%d) should be odd \n", Cnt); return FALSE; } Cnt = Cnt/2; if (Cnt != Len) { MONITOR_LOG("Oops: write lenth not match input string lentg, choose smaller one\n"); Len = (Cnt < Len) ? Cnt:Len; } for (index= 0; index < Len; index++) { EfuseBuf[index] = _2char2hex(DString[index*2], DString[index*2+1]); } MONITOR_LOG("efuse wraw write len:%d, string len:%d\n", Len, Cnt << 1); for (index = 0; index < Len; index++) { MONITOR_LOG("wraw: %x %x \n", Addr + index, EfuseBuf[index]); EFUSE_PMAP_WRITE8(0, Addr + index, EfuseBuf[index], L25EOUTVOLTAGE); } } return 0; } u32 CmdCloseUltraLowPower( IN u16 argc, IN u8 *argv[] ) { /* To avoid gcc warnings */ ( void ) argc; ( void ) argv; wifi_config.wifi_ultra_low_power = FALSE; return _TRUE; } u32 CmdTsfTest( IN u16 argc, IN u8 *argv[] ) { /* To avoid gcc warnings */ ( void ) argc; u32 temp; if (_strcmp((const char*)argv[0], "read") == 0){// release if (_strcmp((const char*)argv[1], "560") == 0) { DBG_8195A("0x40080560=%x\n",HAL_READ32(WIFI_REG_BASE,0x560)); } else if (_strcmp((const char*)argv[1], "568") == 0) { DBG_8195A("0x40080568=%x\n",HAL_READ32(WIFI_REG_BASE,0x568)); } else if (_strcmp((const char*)argv[1], "all") == 0) { DBG_8195A("0x40080560=%x 0x40080568=%x\n",HAL_READ32(WIFI_REG_BASE,0x560), HAL_READ32(WIFI_REG_BASE,0x568)); } } if (_strcmp((const char*)argv[0], "set") == 0){// release temp = HAL_READ32(WIFI_REG_BASE,0x560); HAL_WRITE32(WIFI_REG_BASE,0x568,temp); DBG_8195A("0x40080560=%x 0x40080568=%x\n",HAL_READ32(WIFI_REG_BASE,0x560), HAL_READ32(WIFI_REG_BASE,0x568)); } return 0; } CMD_TABLE_DATA_SECTION const COMMAND_TABLE shell_cmd_table[] = { {(const u8*)"?", 0, CmdRamHelp, (const u8*)"\tHELP (?) : \n" "\t\t Print help messag\n"}, {(const u8*)"DW", 2, cmd_dump_word, (const u8*)"\tDW <Address, Hex>\n" "\t\t Dump memory dword or Read Hw dword register; \n" "\t\t Can Dump only one dword at the same time \n" "\t\t Unit: 4Bytes \n"}, {(const u8*)"EW", 2, cmd_write_word, (const u8*)"\tEW <Address, Hex>\n" "\t\t Write memory dword or Write Hw dword register \n" "\t\t Can write only one dword at the same time \n" "\t\t Ex: EW Address Value \n"}, {(const u8*)"FLASH", 8, cmd_flash, (const u8*)"\tFLASH \n" "\t\t erase chip \n" "\t\t erase sector addr \n" "\t\t erase block addr \n" "\t\t read addr len \n" "\t\t write addr data \n"}, {(const u8*)"EFUSE", 8, cmd_efuse_protect, (const u8*)"\tEFUSE \n" "\t\t wmap addr len data\n" "\t\t rmap \n" "\t\t <wmap 0x00 2 8195> efuse[0]=0x95, efuse [1]=0x81\n" "\t\t <wmap 0xF0 4 11223344> [0xF0]=0x22, [0xF1]=0x11, [0xF2]=0x444, [0xF3]=0x33\n"}, {(const u8*)"REBOOT", 4, cmd_reboot, (const u8*)"\tREBOOT \n" "\t\t reboot \n" "\t\t reboot uartburn \n"}, {(const u8*)"TICKPS", 4, CmdTickPS, (const u8*)"\tTICKPS \n" "\t\t r: release os wakelock \n" "\t\t a: acquire os wakelock \n"}, {(const u8*)"RTC", 4, CmdRTC, (const u8*)"\tRTC \n" "\t\t get\n"}, {(const u8*)"APTEST", 4, CmdCloseUltraLowPower, (const u8*)"\tAPTEST \n" "\t\t get\n"}, {(const u8*)"TSFTEST", 4, CmdTsfTest, (const u8*)"\tTSFTEST \n" "\t\t get\n"}, {(const u8*)">>", 4, CmdShellSwitch, (const u8*)"\t>> \n" "\t\t switch shell to KM0 \n"}, {(const u8*)"LOGBUF", 4, CmdLogBuf, (const u8*)"\tLOGBUF \n" "\t\t KM0 help to print KM4 log\n"}, }; u32 CmdRamHelp( IN u16 argc, IN u8 *argv[] ) { /* To avoid gcc warnings */ ( void ) argc; ( void ) argv; COMMAND_TABLE* cmd_table = (COMMAND_TABLE*)__cmd_table_start__; u32 cmd_mum = ((__cmd_table_end__ - __cmd_table_start__) / sizeof(COMMAND_TABLE)); u32 index ; DiagPrintfD("----------------- TEST COMMAND MODE HELP %d [%08x:%08x]------------------\n", cmd_mum, __cmd_table_start__, __cmd_table_end__); for( index=0 ; index < cmd_mum; index++ ) { if( cmd_table[index].msg ) { DiagPrintfD( "%s\n",cmd_table[index].msg ); } } DiagPrintfD("----------------- TEST COMMAND MODE END %d [%08x:%08x]------------------\n", cmd_mum, __cmd_table_start__, __cmd_table_end__); return _TRUE ; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/app/monitor/ram/monitor_hp.c
C
apache-2.0
11,787
/* * Routines to access hardware * * Copyright (c) 2013 Realtek Semiconductor Corp. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. */ #include "ameba_soc.h" #include "freertos_pmu.h" #include "rom_map.h" u32 CmdRamHelp( IN u16 argc, IN u8 *argv[] ); u32 CmdShellSwitch( IN u16 argc, IN u8 *argv[] ) { /* To avoid gcc warnings */ ( void ) argc; ( void ) *argv; km4_set_wake_event(BIT_HP_WEVT_UART_STS); vTaskDelay(3); if ( km4_status_on()) { InterruptDis(UART_LOG_IRQ_LP); ipc_send_message(IPC_INT_CHAN_SHELL_SWITCH, NULL); } return 0; } u32 cmd_reboot( IN u16 argc, IN u8 *argv[] ) { /* To avoid gcc warnings */ ( void ) argc; FLASH_ClockSwitch(BIT_SHIFT_FLASH_CLK_XTAL, TRUE); UART_RxCmd(UART2_DEV, DISABLE); RCC_PeriphClockSource_UART(UART2_DEV, UART_RX_CLK_XTAL_40M); UART_RxMonitorCmd(UART2_DEV, DISABLE); UART_SetBaud(UART2_DEV, 115200); UART_RxCmd(UART2_DEV, ENABLE); if (_strcmp((const char*)argv[0], "uartburn") == 0){ /* make KM4 sleep*/ FLASH_Write_Lock(); BKUP_Set(0, BIT_UARTBURN_BOOT); } DBG_8195A("\n\rRebooting ...\n\r"); NVIC_SystemReset(); return _TRUE; } u32 CmdTickPS( IN u16 argc, IN u8 *argv[] ) { /* To avoid gcc warnings */ ( void ) argc; if (_strcmp((const char*)argv[0], "r") == 0){// release if (_strcmp((const char*)argv[1], "debug") == 0) { pmu_tickless_debug(ENABLE); } else { pmu_tickless_debug(DISABLE); } pmu_release_wakelock(PMU_OS); } if (_strcmp((const char*)argv[0], "a") == 0){// acquire pmu_acquire_wakelock(PMU_OS); } if (_strcmp((const char*)argv[0], "type") == 0){// PG or CG if (_strcmp((const char*)argv[1], "pg") == 0) { pmu_set_sleep_type(SLEEP_PG); } else if (_strcmp((const char*)argv[1], "cg") == 0) { pmu_set_sleep_type(SLEEP_CG); } else { pmu_set_sleep_type(SLEEP_PG); } } if (_strcmp((const char*)argv[0], "dslp") == 0){ u32 duration_ms = _strtoul((const char*)(argv[1]), (char **)NULL, 10); SOCPS_AONTimer(duration_ms); SOCPS_AONTimerCmd(ENABLE); SOCPS_DeepSleep_RAM(); } if (_strcmp((const char*)argv[0], "get") == 0){// get sleep & wake time DBG_8195A("lockbit:%x \n", pmu_get_wakelock_status()); DBG_8195A("dslp_lockbit:%x\n", pmu_get_deepwakelock_status()); } return _TRUE; } u32 CmdRTC( IN u16 argc, IN u8 *argv[] ) { /* To avoid gcc warnings */ ( void ) argc; RTC_TimeTypeDef RTC_TimeStruct; if (_strcmp((const char*)argv[0], "get") == 0) {// dump RTC RTC_AlarmTypeDef RTC_AlarmStruct_temp; RTC_GetTime(RTC_Format_BIN, &RTC_TimeStruct); RTC_GetAlarm(RTC_Format_BIN, &RTC_AlarmStruct_temp); DBG_8195A("time: %d:%d:%d:%d (%d) \n", RTC_TimeStruct.RTC_Days, RTC_TimeStruct.RTC_Hours, RTC_TimeStruct.RTC_Minutes, RTC_TimeStruct.RTC_Seconds, RTC_TimeStruct.RTC_H12_PMAM); DBG_8195A("alarm: %d:%d:%d:%d (%d) \n", RTC_AlarmStruct_temp.RTC_AlarmTime.RTC_Days, RTC_AlarmStruct_temp.RTC_AlarmTime.RTC_Hours, RTC_AlarmStruct_temp.RTC_AlarmTime.RTC_Minutes, RTC_AlarmStruct_temp.RTC_AlarmTime.RTC_Seconds, RTC_AlarmStruct_temp.RTC_AlarmTime.RTC_H12_PMAM); } if (_strcmp((const char*)argv[0], "set") == 0) { RTC_TimeStructInit(&RTC_TimeStruct); RTC_TimeStruct.RTC_Hours = _strtoul((const char*)(argv[1]), (char **)NULL, 10); RTC_TimeStruct.RTC_Minutes = _strtoul((const char*)(argv[2]), (char **)NULL, 10); RTC_TimeStruct.RTC_Seconds = _strtoul((const char*)(argv[3]), (char **)NULL, 10); if (_strcmp((const char*)argv[5], "pm") == 0) { RTC_TimeStruct.RTC_H12_PMAM = RTC_H12_PM; } else { RTC_TimeStruct.RTC_H12_PMAM = RTC_H12_AM; } RTC_SetTime(RTC_Format_BIN, &RTC_TimeStruct); } return _TRUE; } /** * @brief write p-efuse to patch a register when power on. * @param page: 3bit, when you set 4800_03C4, page=0x03 * @param addr: 8bit, when you set 4800_03C4, page=0xC4 * @param val: 8bit, when you set 4800_03C4, 4800_03C4[7:0]=val * @retval None ***/ void cmd_efuse_extpath_write(u8 page, u8 addr, u8 val) { u8 efuse_hear_b0; u8 efuse_hear_b1; u32 start_addr; efuse_hear_b0 = 0xF; //fixed efuse_hear_b0 |= page << 5; //0x03 << 5=>4800_0300 efuse_hear_b1 = 0x0E; //1x16bit=>efuse_b0 & efuse_b1 efuse_hear_b1 |= 0x0E << 4; //4800_0000 /* write at the end of logical mapping address */ /* so that hardware can aotoload it */ start_addr = LOGICAL_MAP_SECTION_LEN - EFUSE_RemainLength(); DBG_8195A("app_efuse_extpath_write: 0x%x 0x%x\n", start_addr, EFUSE_RemainLength()); DBG_8195A("app_efuse_extpath_write: %x \n", efuse_hear_b0); DBG_8195A("app_efuse_extpath_write: %x \n", efuse_hear_b1); DBG_8195A("app_efuse_extpath_write: %x \n", addr); DBG_8195A("app_efuse_extpath_write: %x \n", val); EFUSE_PMAP_WRITE8(0, start_addr, efuse_hear_b0, L25EOUTVOLTAGE); EFUSE_PMAP_WRITE8(0, start_addr+1, efuse_hear_b1, L25EOUTVOLTAGE); EFUSE_PMAP_WRITE8(0, start_addr+2, addr, L25EOUTVOLTAGE); //0xC=>4800_03C4 EFUSE_PMAP_WRITE8(0, start_addr+3, val, L25EOUTVOLTAGE); //4800_03C4[8:0]=val } u32 cmd_efuse_protect(u16 argc, u8 *argv[]) { u8 EfuseBuf[1024]; u32 index; u8 ret = 0; /* To avoid gcc warnings */ ( void ) argc; /* efuse wmap 0x0 2 2187 */ /* efuse wmap 0x18 4 01020304 */ if (_strcmp((const char*)argv[0], "wmap") == 0) { u32 Addr = _strtoul((const char*)(argv[1]), (char **)NULL, 16); u32 Len = _strtoul((const char*)(argv[2]), (char **)NULL, 16); char* DString = (char*)argv[3]; u32 Cnt; Cnt = _strlen(DString); if (Cnt%2) { MONITOR_LOG("string length(%d) should be odd \n", Cnt); return FALSE; } Cnt = Cnt/2; if (Cnt != Len) { MONITOR_LOG("Oops: write lenth not match input string lentg, choose smaller one\n"); Len = (Cnt < Len) ? Cnt:Len; } MONITOR_LOG("efuse wmap write len:%d, string len:%d\n", Len, Cnt << 1); for (index= 0; index < Len; index++) { EfuseBuf[index] = _2char2hex(DString[index*2], DString[index*2+1]); } EFUSE_LMAP_WRITE(Addr, Len, (u8 *)(EfuseBuf)); } if (_strcmp((const char*)argv[0], "rmap") == 0) { MONITOR_LOG("efuse rmap \n"); ret = EFUSE_LMAP_READ(EfuseBuf); if (ret == _FAIL) { MONITOR_LOG("EFUSE_LogicalMap_Read fail \n"); } for (index = 0; index < 1024; index+=16) { MONITOR_LOG("EFUSE[%03x]: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", index, EfuseBuf[index], EfuseBuf[index+1], EfuseBuf[index+2], EfuseBuf[index+3], EfuseBuf[index+4], EfuseBuf[index+5], EfuseBuf[index+6], EfuseBuf[index+7], EfuseBuf[index+8], EfuseBuf[index+9], EfuseBuf[index+10], EfuseBuf[index+11], EfuseBuf[index+12], EfuseBuf[index+13], EfuseBuf[index+14], EfuseBuf[index+15]); } } if (_strcmp((const char*)argv[0], "rraw") == 0) { MONITOR_LOG("efuse rraw\n"); for (index = 0; index< EFUSE_REAL_CONTENT_LEN; index++) { if ((index < EFUSE_SECURE_START) || (index > EFUSE_SECURE_END)) { EFUSE_PMAP_READ8(0, index, EfuseBuf + index, L25EOUTVOLTAGE); } else { EfuseBuf[index] = 0xFF; } } for (index= 0; index < EFUSE_REAL_CONTENT_LEN; index+=16) { MONITOR_LOG("RawMap[%03x]: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", index, EfuseBuf[index], EfuseBuf[index+1], EfuseBuf[index+2], EfuseBuf[index+3], EfuseBuf[index+4], EfuseBuf[index+5], EfuseBuf[index+6], EfuseBuf[index+7], EfuseBuf[index+8], EfuseBuf[index+9], EfuseBuf[index+10], EfuseBuf[index+11], EfuseBuf[index+12], EfuseBuf[index+13], EfuseBuf[index+14], EfuseBuf[index+15]); } } /* efuse wraw 0xA0 1 aa */ /* efuse wraw 0xA0 2 aabb */ /* efuse wraw 0xA0 4 aabbccdd */ if (_strcmp((const char*)argv[0], "wraw") == 0) { u32 Addr = _strtoul((const char*)(argv[1]), (char **)NULL, 16); u32 Len = _strtoul((const char*)(argv[2]), (char **)NULL, 16); char* DString = (char*)argv[3]; u32 Cnt; Cnt = _strlen(DString); if (Cnt%2) { MONITOR_LOG("string length(%d) should be odd \n", Cnt); return FALSE; } Cnt = Cnt/2; if (Cnt != Len) { MONITOR_LOG("Oops: write lenth not match input string lentg, choose smaller one\n"); Len = (Cnt < Len) ? Cnt:Len; } for (index= 0; index < Len; index++) { EfuseBuf[index] = _2char2hex(DString[index*2], DString[index*2+1]); } MONITOR_LOG("efuse wraw write len:%d, string len:%d\n", Len, Cnt << 1); for (index = 0; index < Len; index++) { MONITOR_LOG("wraw: %x %x \n", Addr + index, EfuseBuf[index]); EFUSE_PMAP_WRITE8(0, Addr + index, EfuseBuf[index], L25EOUTVOLTAGE); } } if (_strcmp((const char*)argv[0], "patch") == 0) { /* close PAD_A0~PAD_A9 & PAD_F0~PAD_F6 */ /* GPIO is PA7~PA11, PA22/23/24, PA27~PB3 */ cmd_efuse_extpath_write(0x03, 0x40, 0xEF);//0x4800_0340[7:0]=0xEF } return 0; } u32 CmdCTC( IN u16 argc, IN u8 *argv[] ) { /* To avoid gcc warnings */ ( void ) argc; if (_strcmp((const char*)argv[0], "dump") == 0) {// dump RTC CapTouch_DbgDumpReg(CAPTOUCH_DEV); } if (_strcmp((const char*)argv[0], "etc") == 0) { u32 ch = 0; for (ch = 0; ch < 2; ch++) { CapTouch_DbgDumpETC(CAPTOUCH_DEV, ch); } } return _TRUE; } u32 CmdHsSdm32K( IN u16 argc, IN u8 *argv[] ) { /* To avoid gcc warnings */ ( void ) argc; ( void ) *argv; u32 temp; DBG_8195A("ENABLE HS SDM 32K\n"); /*osc clk enable*/ temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LP_XTAL_CTRL2); temp &= (~BIT1); HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_XTAL_CTRL2, temp); /*select xtal 40M*/ temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_SYS_EFUSE_SYSCFG2); temp &= (~(0xf<<16)); HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_SYS_EFUSE_SYSCFG2, temp); /*enable hs sdm*/ temp = HAL_READ32(WIFI_REG_BASE, 0xe8); temp &= (~0x1f); HAL_WRITE32(WIFI_REG_BASE, 0xe8, temp); temp = HAL_READ32(WIFI_REG_BASE, 0xec); temp |= (0x3<<30); HAL_WRITE32(WIFI_REG_BASE, 0xec, temp); /*select hs_sdm & 32k*/ temp = HAL_READ32(WIFI_REG_BASE, 0x0); temp &= (~(0x3<<20)); temp |= (0x1<<20); HAL_WRITE32(WIFI_REG_BASE, 0x0, temp); return _TRUE; } CMD_TABLE_DATA_SECTION const COMMAND_TABLE shell_cmd_table[] = { {(const u8*)"?", 0, CmdRamHelp, (const u8*)"\tHELP (?) : \n" "\t\t Print help messag\n"}, {(const u8*)"DW", 2, CmdDumpWord, (const u8*)"\tDW <Address, Hex>\n" "\t\t Dump memory dword or Read Hw dword register; \n" "\t\t Can Dump only one dword at the same time \n" "\t\t Unit: 4Bytes \n"}, {(const u8*)"EW", 2, CmdWriteWord, (const u8*)"\tEW <Address, Hex>\n" "\t\t Write memory dword or Write Hw dword register \n" "\t\t Can write only one dword at the same time \n" "\t\t Ex: EW Address Value \n"}, {(const u8*)"FLASH", 8, cmd_flash, (const u8*)"\tFLASH \n" "\t\t erase chip \n" "\t\t erase sector addr \n" "\t\t erase block addr \n" "\t\t read addr len \n" "\t\t write addr data \n"}, {(const u8*)"EFUSE", 8, cmd_efuse_protect, (const u8*)"\tEFUSE \n" "\t\t wmap addr len data\n" "\t\t rmap \n"}, {(const u8*)"REBOOT", 4, cmd_reboot, (const u8*)"\tREBOOT \n" "\t\t reboot \n" "\t\t reboot uartburn \n"}, {(const u8*)"TICKPS", 4, CmdTickPS, (const u8*)"\tTICKPS \n" "\t\t r: release os wakelock \n" "\t\t a: acquire os wakelock \n"}, {(const u8*)"RTC", 4, CmdRTC, (const u8*)"\tRTC \n" "\t\t get\n"}, {(const u8*)"CTC", 4, CmdCTC, (const u8*)"\tCTC \n" "\t\t dump/etc\n"}, {(const u8*)">>", 4, CmdShellSwitch, (const u8*)"\t>> \n" "\t\t switch shell to KM4 \n"}, {(const u8*)"HSSDM32K", 0, CmdHsSdm32K, (const u8*)"\tHSSDM32K \n" "\t\t enable hs sdm 32k\n"}, }; u32 CmdRamHelp( IN u16 argc, IN u8 *argv[] ) { /* To avoid gcc warnings */ ( void ) argc; ( void ) *argv; COMMAND_TABLE* cmd_table = (COMMAND_TABLE*)__cmd_table_start__; u32 cmd_mum = ((__cmd_table_end__ - __cmd_table_start__) / sizeof(COMMAND_TABLE)); u32 index ; DiagPrintfD("----------------- TEST COMMAND MODE HELP %d------------------\n", cmd_mum); for( index=0 ; index < cmd_mum; index++ ) { if( cmd_table[index].msg ) { DiagPrintfD( "%s\n",cmd_table[index].msg ); } } DiagPrintfD("----------------- TEST COMMAND MODE END %x------------------\n", cmd_mum); return _TRUE ; }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/app/monitor/ram/monitor_lp.c
C
apache-2.0
12,420
/** ****************************************************************************** * @file rtl_trace.c * @author * @version V1.0.0 * @date 2016-05-17 * @brief This file contains all the functions for log print and mask. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2015, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "ameba_soc.h" SRAM_NOCACHE_DATA_SECTION u32 log_buffer_start; SRAM_NOCACHE_DATA_SECTION u32 log_buffer_end; SRAM_NOCACHE_DATA_SECTION TaskHandle_t log_buffer_thread_handle; #if defined (ARM_CORE_CM4) u32 LOG_PRINTF_BUFFER(const char *fmt) { /* To avoid gcc warnings */ ( void ) fmt; IPC_TypeDef *IPC0 = IPCM0_DEV; u32 write_pointer = IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP]; u32 read_pointer = IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP]; u32 write_pointer_next = 0; write_pointer_next = write_pointer + sizeof(log_buffer_t); if (write_pointer_next > log_buffer_end) { write_pointer_next = log_buffer_start; } /* write pointer catch up with read pointer, wait */ while (1) { read_pointer = IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP]; if (write_pointer_next != read_pointer) break; } /* make sure write pointer buffer is empty */ IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP] = write_pointer_next; //DiagPrintfD("LOG_PRINTF_BUFFER: %x\n", IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP]); return (write_pointer); } u32 LOG_PRINTF_BUFFER_INIT(u32 thread_init) { /* To avoid gcc wanrings */ ( void ) thread_init; IPC_TypeDef *IPC0 = IPCM0_DEV; log_buffer_start = IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP]; if (log_buffer_start == 0) { DBG_8195A("KM0 dont open logbuf \n"); return 0; } log_buffer_end = log_buffer_start + (LOG_BUFFER_NUM - 1) * sizeof(log_buffer_t); ConfigDebugBufferGet = LOG_PRINTF_BUFFER; DBG_8195A("LOG_PRINTF_BUFFER_INIT KM4 %x %x\n", log_buffer_start, log_buffer_end); /* open/close in CmdLogBuf */ ConfigDebugBuffer = 1; return 0; } #else /* reserve one to avoid memory overflow */ SRAM_NOCACHE_DATA_SECTION log_buffer_t log_buffer[LOG_BUFFER_NUM + 1]; static VOID LOG_BUFF_TASK(VOID *Data) { /* To avoid gcc warnings */ ( void ) Data; IPC_TypeDef *IPC0 = IPCM0_DEV; u32 write_pointer = IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP]; u32 read_pointer = IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP]; do { //DBG_8195A("write_pointer:%x read_pointer:%x \n", IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP], // IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP]); /* read pointer catch up with write pointer, wait */ while (1) { write_pointer = IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP]; if ((write_pointer != read_pointer) && (write_pointer != 0)) break; taskYIELD(); } DiagPrintf((const char *)read_pointer); read_pointer = (read_pointer + sizeof(log_buffer_t)); if (read_pointer > log_buffer_end) { read_pointer = log_buffer_start; } IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP] = read_pointer; } while(1); } u32 LOG_PRINTF_BUFFER_INIT(u32 thread_init) { IPC_TypeDef *IPC0 = IPCM0_DEV; log_buffer_thread_handle = NULL; return 0; /* init read/write pointer */ IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP] = (u32)&log_buffer[0]; /* write_pointer */ IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP] = (u32)&log_buffer[0]; /* read_pointer */ log_buffer_end = (u32)&log_buffer[LOG_BUFFER_NUM-1]; log_buffer_start = (u32)&log_buffer[0]; log_buffer[0].buffer[0]='\0'; DBG_8195A("LOG_PRINTF_BUFFER_INIT %x %x %x\n", IPC0->IPCx_USR[IPC_USER_BUF_LOG_WP], \ IPC0->IPCx_USR[IPC_USER_BUF_LOG_RP], log_buffer_end); if (!thread_init) return 0; /* init thread, low-priority */ if (pdTRUE != xTaskCreate(LOG_BUFF_TASK, (const char * const)"LOGBUFF_TASK", 128, NULL, tskIDLE_PRIORITY + 3 , &log_buffer_thread_handle)) { DiagPrintf("CreateLOGBUFF_TASK Err!!\n"); } return 0; } u32 LOG_BUFF_SUSPEND(void) { if (log_buffer_thread_handle) { vTaskSuspend(log_buffer_thread_handle); } return TRUE; } u32 LOG_BUFF_RESUME(void) { if (log_buffer_thread_handle) { vTaskResume(log_buffer_thread_handle); } return TRUE; } #endif /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/app/monitor/ram/rtl_trace.c
C
apache-2.0
4,412
/* * Routines to access hardware * * Copyright (c) 2013 Realtek Semiconductor Corp. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. */ #include "ameba_soc.h" #include "osdep_service.h" #include <stdarg.h> #include "strproc.h" #if defined ( __ICCARM__ ) #pragma section=".cmd.table.data" SECTION(".data") u8* __cmd_table_start__; SECTION(".data") u8* __cmd_table_end__; #endif extern volatile UART_LOG_CTL shell_ctl; extern UART_LOG_BUF shell_buf; #ifdef CONFIG_UART_LOG_HISTORY extern u8 shell_history_cmd[UART_LOG_HISTORY_LEN][UART_LOG_CMD_BUFLEN]; #endif extern COMMAND_TABLE shell_cmd_table[]; _sema shell_sema; #if defined(CONFIG_WIFI_NORMAL) #if SUPPORT_LOG_SERVICE extern char log_buf[LOG_SERVICE_BUFLEN]; extern _sema log_rx_interrupt_sema; extern void log_service_init(void); #endif #endif static monitor_cmd_handler shell_get_cmd(char* argv) { PCOMMAND_TABLE pCmdTbl = shell_ctl.pCmdTbl; u32 CmdCnt = 0; u32 CmdNum = shell_ctl.CmdTblSz; monitor_cmd_handler cmd_handler = NULL; for (CmdCnt = 0; CmdCnt< CmdNum; CmdCnt++) { if ((_stricmp(argv, (const char *)pCmdTbl[CmdCnt].cmd))==0){ cmd_handler = pCmdTbl[CmdCnt].func; break; } } return cmd_handler; } static void shell_give_sema(void) { if (shell_ctl.shell_task_rdy) { portBASE_TYPE taskWoken = pdFALSE; rtw_up_sema_from_isr(&shell_sema); } } //====================================================== u32 shell_cmd_exec(u8 argc, u8 **argv) { /* To avoid gcc warnings */ ( void ) argc; ( void ) *argv; #if defined(CONFIG_WIFI_NORMAL) if(argc == 0) { return FALSE; } #if SUPPORT_LOG_SERVICE rtw_up_sema((_sema *)&log_rx_interrupt_sema); #endif shell_array_init(argv[0], sizeof(argv[0]) ,0); #endif return TRUE; } //====================================================== static u32 shell_cmd_exec_ram(u8 argc, u8 **argv) { monitor_cmd_handler cmd_handler = NULL; if (argc > 0){ cmd_handler = shell_get_cmd((char *)argv[0]); if (cmd_handler != NULL) { _strupr(argv[0]); cmd_handler((argc-1) , (argv+1)); shell_array_init(argv[0], sizeof(argv[0]) ,0); return TRUE; } } //(*pUartLogBuf).BufCount = 0; //shell_array_init(&(*pUartLogBuf).UARTLogBuf[0], UART_LOG_CMD_BUFLEN, '\0'); return FALSE; } static VOID shell_task_ram(VOID *Data) { /* To avoid gcc warnings */ ( void ) Data; u32 ret = TRUE; //4 Set this for UartLog check cmd history shell_ctl.shell_task_rdy = 1; shell_ctl.BootRdy = 1; do{ rtw_down_sema(&shell_sema); if (shell_ctl.ExecuteCmd) { u8 argc = 0; u8 **argv; PUART_LOG_BUF pUartLogBuf = shell_ctl.pTmpLogBuf; #if defined(CONFIG_WIFI_NORMAL) #if SUPPORT_LOG_SERVICE _strncpy(log_buf, (const char*)&(*pUartLogBuf).UARTLogBuf[0], LOG_SERVICE_BUFLEN-1); #endif #endif argc = shell_get_argc((const u8*)&((*pUartLogBuf).UARTLogBuf[0])); argv = (u8**)shell_get_argv((const u8*)&((*pUartLogBuf).UARTLogBuf[0])); /* UARTLogBuf will be changed */ if (argc > 0) { /* FPGA Verification */ ret = shell_cmd_exec_ram(argc, argv); /* normal for LOG service */ if (ret == FALSE) { ret = shell_cmd_exec(argc, argv); } (*pUartLogBuf).BufCount = 0; shell_array_init(&(*pUartLogBuf).UARTLogBuf[0], UART_LOG_CMD_BUFLEN, '\0'); } else { /*In some exception case, even if argc parsed is 0(when the first character value in log buffer is '\0'), log buffer may not be empty and log buffer counter may not be zero. If not clean log buffer and counter , some error will happen. Therefore, clean log buffer and initialize buffer counter when it occurs.*/ if((*pUartLogBuf).BufCount != 0) { (*pUartLogBuf).BufCount = 0; shell_array_init(&(*pUartLogBuf).UARTLogBuf[0], UART_LOG_CMD_BUFLEN, '\0'); } CONSOLE_AMEBA(); } shell_ctl.ExecuteCmd = _FALSE; pmu_set_sysactive_time(10000); } }while(1); } VOID shell_init_ram(VOID) { #if defined(CONFIG_WIFI_NORMAL) #if SUPPORT_LOG_SERVICE // log_service_init(); #endif #endif #ifdef AMEBAD_TODO LOGUART_SetBaud_FromFlash(); #endif #if defined ( __ICCARM__ ) __cmd_table_start__ = (u8*)__section_begin(".cmd.table.data"); __cmd_table_end__ = (u8*)__section_end(".cmd.table.data"); #endif shell_ctl.pCmdTbl = (PCOMMAND_TABLE)__cmd_table_start__; shell_ctl.CmdTblSz = ((__cmd_table_end__ - __cmd_table_start__) / sizeof(COMMAND_TABLE)); shell_ctl.ExecuteCmd = _FALSE; shell_ctl.ExecuteEsc= _TRUE;//don't check Esc anymore shell_ctl.GiveSema = shell_give_sema; /* Create a Semaphone */ rtw_init_sema(&shell_sema, 0); rtw_down_timeout_sema(&shell_sema, 1/portTICK_RATE_MS); aos_task_new("LOGUART_TASK", shell_task_ram, NULL, 1024*4); #if 0 if (pdTRUE != xTaskCreate( shell_task_ram, (const char * const)"LOGUART_TASK", 1024*2, NULL, 5 , NULL)) { DiagPrintf("Create Log UART Task Err!!\n"); } #endif //CONSOLE_AMEBA(); } void shell_switch_ipc_int(VOID *Data, u32 IrqStatus, u32 ChanNum) { /* To avoid gcc warnings */ ( void ) Data; ( void ) IrqStatus; ( void ) ChanNum; u8 CpuId = IPCM0_DEV->IPCx_CPUID; if (CpuId == 1) { DBG_8195A("KM4 shell\n"); InterruptEn(UART_LOG_IRQ, 10); pmu_set_sysactive_time(1000); } else { DBG_8195A("KM0 shell\n"); InterruptEn(UART_LOG_IRQ_LP, 10); } }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/app/monitor/ram/shell_ram.c
C
apache-2.0
5,363
/* * Routines to access hardware * * Copyright (c) 2013 Realtek Semiconductor Corp. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. */ #include "ameba_soc.h" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" //====================================================== //<Function>: CmdTest //<Usage >: This function is a demo test function. //<Argus >: argc --> number of argus // argv --> pointer to a cmd parameter array //<Return >: VOID //<Notes >: NA //====================================================== static u32 cmd_rom_help(u16 argc, u8 *argv[]); SHELL_ROM_TEXT_SECTION u32 cmd_dump_word(u16 argc, u8 *argv[]) { u32 Src; //u32 Len,LenIndex; u32 OTF_Enable = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_SYS_EFUSE_SYSCFG3) & BIT_SYS_FLASH_ENCRYPT_EN; if(argc<1) { MONITOR_LOG("Wrong argument number!\r\n"); return _FALSE; } if(argv[0]) { Src= _strtoul((const char*)(argv[0]), (char **)NULL, 16); } else { MONITOR_LOG("Wrong argument number!\r\n"); return _FALSE; } //if(!argv[1]) // Len = 1; //else // Len = _strtoul((const char*)(argv[1]), (char **)NULL, 10); Src &= ~(0x03); /* read encrypt image for FW protection */ if ((Src & 0x08000000) != 0) { if (OTF_Enable != 0) { RSIP_OTF_Cmd(DISABLE); } } MONITOR_LOG("%08X: %08X \n", Src, *(u32 *)(Src)); if ((Src & 0x08000000) != 0) { if (OTF_Enable != 0) { RSIP_OTF_Cmd(ENABLE); Cache_Flush(); } } return _TRUE; } SHELL_ROM_TEXT_SECTION u32 cmd_write_word(u16 argc, u8 *argv[]) { u32 Src; u32 Value; Src = _strtoul((const char*)(argv[0]), (char **)NULL, 16); Src &= ~(0x03); Value= _strtoul((const char*)(argv[1]), (char **)NULL, 16); MONITOR_LOG("%08X: %08X \n", Src, Value); *(volatile u32 *)(Src) = Value; return 0; } SHELL_ROM_TEXT_SECTION u32 cmd_flash(u16 argc, u8 *argv[]) { if (_strcmp((const char*)argv[0], "erase") == 0) {/* SPI Flash Chip Erase Command */ u32 AddrTemp = 0; MONITOR_LOG("Erase Falsh Start\n"); AddrTemp = _strtoul((const char*)(argv[2]), (char **)NULL, 16); if (_strcmp((const char*)argv[1], "chip") == 0) { MONITOR_LOG("Erase Chip start!!\n"); FLASH_Erase(EraseChip, 0); MONITOR_LOG("Erase Chip success!!\n"); } else if (_strcmp((const char*)argv[1], "block") == 0) { MONITOR_LOG("Erase block = %x\n",(AddrTemp)); FLASH_Erase(EraseBlock, AddrTemp); MONITOR_LOG("Erase block success!!\n"); } else if (_strcmp((const char*)argv[1], "sector") == 0) { MONITOR_LOG("Erase Sector = %x\n",(AddrTemp)); FLASH_Erase(EraseSector, AddrTemp); MONITOR_LOG("Erase Sector success!!\n"); } /* for calibration use */ FLASH_TxData12B(0, 4, (u8*)SPIC_CALIB_PATTERN); Cache_Flush(); MONITOR_LOG("Erase Falsh End\n"); } if (_strcmp((const char*)argv[0], "read") == 0) { u32 address = 0; u32 len = 0; u32 idx = 0; u32 OTF_Enable = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_SYS_EFUSE_SYSCFG3) & BIT_SYS_FLASH_ENCRYPT_EN; MONITOR_LOG("Falsh read\n"); /* read encrypt image for FW protection */ if (OTF_Enable) { RSIP_OTF_Cmd(DISABLE); } address = _strtoul((const char*)(argv[1]), (char **)NULL, 16); len = _strtoul((const char*)(argv[2]), (char **)NULL, 10)/4; for (idx = 0; idx < len; idx++) { MONITOR_LOG("%08x: %08x %08x %08x %08x \n", address, HAL_READ32(SPI_FLASH_BASE, address), HAL_READ32(SPI_FLASH_BASE, address+4), HAL_READ32(SPI_FLASH_BASE, address+8), HAL_READ32(SPI_FLASH_BASE, address+12)); address = address + 16; } if (OTF_Enable) { RSIP_OTF_Cmd(ENABLE); Cache_Flush(); } } if (_strcmp((const char*)argv[0], "write") == 0) { u32 address = 0; u32 data = 0; address = _strtoul((const char*)(argv[1]), (char **)NULL, 16); data = _strtoul((const char*)(argv[2]), (char **)NULL, 16); MONITOR_LOG("Falsh write addr:%x data:%x \n", address, data); FLASH_TxData12B(address, 4, (u8*)&data); //max is 12 Cache_Flush(); } if (_strcmp((const char*)argv[0], "status") == 0) { u8 status[2]; u8 wstatus = _strtoul((const char*)(argv[2]), (char **)NULL, 16); if (_strcmp((const char*)argv[1], "get") == 0) { FLASH_RxCmd(flash_init_para.FLASH_cmd_rd_status, 1, &status[0]); if (flash_init_para.FLASH_Status2_exist) { FLASH_RxCmd(flash_init_para.FLASH_cmd_rd_status2, 1, &status[1]); } MONITOR_LOG("status: %x %x\n", status[0], status[1]); } if (_strcmp((const char*)argv[1], "set1") == 0) { FLASH_SetStatus(flash_init_para.FLASH_cmd_wr_status, 1, &wstatus); } if (_strcmp((const char*)argv[1], "set2") == 0) { if(!flash_init_para.FLASH_cmd_wr_status2){ FLASH_RxCmd(flash_init_para.FLASH_cmd_rd_status, 1, &status[0]); status[1] = wstatus; FLASH_SetStatus(flash_init_para.FLASH_cmd_wr_status, 2, status); }else{ FLASH_SetStatus(flash_init_para.FLASH_cmd_wr_status2, 1, &wstatus); } } } if (_strcmp((const char*)argv[0], "cache") == 0) { if (_strcmp((const char*)argv[1], "disable") == 0) { MONITOR_LOG("cache disable \n"); Cache_Enable(DISABLE); } else if (_strcmp((const char*)argv[1], "enable") == 0) { MONITOR_LOG("cache enable \n"); Cache_Enable(ENABLE); } else if (_strcmp((const char*)argv[1], "flush") == 0) { MONITOR_LOG("cache flush \n"); Cache_Flush(); } } return 0; } SHELL_ROM_TEXT_SECTION u32 cmd_efuse(u16 argc, u8 *argv[]) { u8 EfuseBuf[1024]; u32 index; u8 ret = 0; /* efuse wmap 0x0 2 2187 */ /* efuse wmap 0x18 4 01020304 */ if (_strcmp((const char*)argv[0], "wmap") == 0) { u32 Addr = _strtoul((const char*)(argv[1]), (char **)NULL, 16); u32 Len = _strtoul((const char*)(argv[2]), (char **)NULL, 16); char* DString = (char*)argv[3]; u32 Cnt; Cnt = _strlen(DString); if (Cnt%2) { MONITOR_LOG("string length(%d) should be odd \n", Cnt); return FALSE; } Cnt = Cnt/2; if (Cnt != Len) { MONITOR_LOG("Oops: write lenth not match input string lentg, choose smaller one\n"); Len = (Cnt < Len) ? Cnt:Len; } MONITOR_LOG("efuse wmap write len:%d, string len:%d\n", Len, Cnt << 1); for (index= 0; index < Len; index++) { EfuseBuf[index] = _2char2hex(DString[index*2], DString[index*2+1]); } EFUSE_LMAP_WRITE(Addr, Len, (u8 *)(EfuseBuf)); } if (_strcmp((const char*)argv[0], "rmap") == 0) { MONITOR_LOG("efuse rmap \n"); ret = EFUSE_LogicalMap_Read(EfuseBuf); if (ret == _FAIL) { MONITOR_LOG("EFUSE_LogicalMap_Read fail \n"); } for (index = 0; index < 1024; index+=16) { MONITOR_LOG("EFUSE[%03x]: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", index, EfuseBuf[index], EfuseBuf[index+1], EfuseBuf[index+2], EfuseBuf[index+3], EfuseBuf[index+4], EfuseBuf[index+5], EfuseBuf[index+6], EfuseBuf[index+7], EfuseBuf[index+8], EfuseBuf[index+9], EfuseBuf[index+10], EfuseBuf[index+11], EfuseBuf[index+12], EfuseBuf[index+13], EfuseBuf[index+14], EfuseBuf[index+15]); } } if (_strcmp((const char*)argv[0], "rraw") == 0) { MONITOR_LOG("efuse rraw\n"); for (index = 0; index< EFUSE_REAL_CONTENT_LEN; index++) { if ((index < EFUSE_SECURE_START) || (index > EFUSE_SECURE_END)) { EFUSERead8(0, index, EfuseBuf + index, L25EOUTVOLTAGE); } else { EfuseBuf[index] = 0xFF; } } for (index= 0; index < EFUSE_REAL_CONTENT_LEN; index+=16) { MONITOR_LOG("RawMap[%03x]: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", index, EfuseBuf[index], EfuseBuf[index+1], EfuseBuf[index+2], EfuseBuf[index+3], EfuseBuf[index+4], EfuseBuf[index+5], EfuseBuf[index+6], EfuseBuf[index+7], EfuseBuf[index+8], EfuseBuf[index+9], EfuseBuf[index+10], EfuseBuf[index+11], EfuseBuf[index+12], EfuseBuf[index+13], EfuseBuf[index+14], EfuseBuf[index+15]); } } /* efuse wraw 0xA0 1 aa */ /* efuse wraw 0xA0 2 aabb */ /* efuse wraw 0xA0 4 aabbccdd */ if (_strcmp((const char*)argv[0], "wraw") == 0) { u32 Addr = _strtoul((const char*)(argv[1]), (char **)NULL, 16); u32 Len = _strtoul((const char*)(argv[2]), (char **)NULL, 16); char* DString = (char*)argv[3]; u32 Cnt; Cnt = _strlen(DString); if (Cnt%2) { MONITOR_LOG("string length(%d) should be odd \n", Cnt); return FALSE; } Cnt = Cnt/2; if (Cnt != Len) { MONITOR_LOG("Oops: write lenth not match input string lentg, choose smaller one\n"); Len = (Cnt < Len) ? Cnt:Len; } for (index= 0; index < Len; index++) { EfuseBuf[index] = _2char2hex(DString[index*2], DString[index*2+1]); } MONITOR_LOG("efuse wraw write len:%d, string len:%d\n", Len, Cnt << 1); for (index = 0; index < Len; index++) { MONITOR_LOG("wraw: %x %x \n", Addr + index, EfuseBuf[index]); EFUSEWrite8(0, Addr + index, EfuseBuf[index], L25EOUTVOLTAGE); } } return 0; } SHELL_ROM_TEXT_SECTION static u32 cmd_reboot( IN u16 argc, IN u8 *argv[] ) { if (_strcmp((const char*)argv[0], "uartburn") == 0){ BKUP_Set(0, BIT_UARTBURN_BOOT); } MONITOR_LOG("\n\rRebooting ...\n\r"); NVIC_SystemReset(); return _TRUE; } SHELL_ROM_DATA_SECTION static COMMAND_TABLE shell_cmd_table_rom[] = { {(const u8*)"?", 0, cmd_rom_help, (const u8*)"\tHELP (?) \n" "\t\t Print this help messag\n"}, {(const u8*)"DW", 4, CmdDumpWord, (const u8*)"\tDW \n" "\t\t <Address, Hex> <Len, Dec>: \n" "\t\t Dump memory word or Read Hw word register"}, {(const u8*)"EW", 4, CmdWriteWord, (const u8*)"\tEW \n" "\t\t <Address, Hex> <Value, Hex>: \n" "\t\t Write memory word or Write Hw word register \n" "\t\t Can write one word at the same time \n" "\t\t Ex: EW Address Value0 Value1"}, {(const u8*)"FLASH", 8, cmd_flash, (const u8*)"\tFLASH \n" "\t\t erase chip \n" "\t\t erase sector addr \n" "\t\t erase block addr \n" "\t\t read addr len \n" "\t\t write addr data \n"}, {(const u8*)"EFUSE", 8, cmd_efuse, (const u8*)"\tEFUSE \n" "\t\t wmap addr len data\n" "\t\t rmap \n" "\t\t autoload \n"}, {(const u8*)"REBOOT", 4, cmd_reboot, (const u8*)"\tREBOOT \n" "\t\t <item, string> : \n" "\t\t item: uartburn or N/A \n" "\t\t \n"}, }; SHELL_ROM_TEXT_SECTION u32 cmd_rom_table(void** PTable) { *PTable = (void*)&shell_cmd_table_rom; return (sizeof(shell_cmd_table_rom)/sizeof(COMMAND_TABLE)); } SHELL_ROM_TEXT_SECTION static u32 cmd_rom_help(u16 argc, u8 *argv[]) { u32 LoopINdex ; MONITOR_LOG("----------------- COMMAND MODE HELP ------------------\n"); for( LoopINdex=0 ; LoopINdex < (sizeof(shell_cmd_table_rom) / sizeof(COMMAND_TABLE)) ; LoopINdex++ ) { if( shell_cmd_table_rom[LoopINdex].msg ) { MONITOR_LOG( "%s\n",shell_cmd_table_rom[LoopINdex].msg ); } } MONITOR_LOG("----------------- COMMAND MODE END ------------------\n"); return _TRUE ; } #pragma GCC diagnostic pop
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/app/monitor/rom/monitor_rom.c
C
apache-2.0
11,060
/* * Routines to access hardware * * Copyright (c) 2013 Realtek Semiconductor Corp. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. */ #include "ameba_soc.h" #include <stdarg.h> #include "strproc.h" #include "k_api.h" SHELL_ROM_BSS_SECTION volatile UART_LOG_CTL shell_ctl; SHELL_ROM_BSS_SECTION u8 *shell_argv_array[MAX_ARGV]; SHELL_ROM_BSS_SECTION UART_LOG_BUF shell_buf; #ifdef CONFIG_UART_LOG_HISTORY SHELL_ROM_BSS_SECTION u8 shell_history_cmd[UART_LOG_HISTORY_LEN][UART_LOG_CMD_BUFLEN]; #endif SHELL_ROM_BSS_SECTION u32 shell_recv_all_data_onetime; //================================================= //====================================================== //<Function>: shell_array_init //<Usage >: This function is to initialize an array with a given value. //<Argus >: pArrayToInit --> pointer to an array // ArrayLen --> number of array elements // InitValue --> initial value for the array //<Return >: VOID //<Notes >: NA //====================================================== SHELL_ROM_TEXT_SECTION _LONG_CALL_ VOID shell_array_init(u8 *pArrayToInit, u8 ArrayLen, u8 InitValue) { u8 ItemCount =0; for (ItemCount=0; ItemCount<ArrayLen; ItemCount++){ *(pArrayToInit+ItemCount) = InitValue; } } //====================================================== //<Function>: shell_get_argc //<Usage >: This function is to calcute how many parameters in the cmd string //<Argus >: string --> pointer to an input cmd string //<Return >: number of parameters in the string.(****except the cmd itself****) //<Notes >: NA //====================================================== SHELL_ROM_TEXT_SECTION _LONG_CALL_ u8 shell_get_argc(const u8 *string) { u16 argc; u8 *pStr; argc = 0; pStr = (u8 *)string; while(*pStr){ if ((*pStr != ' ') && (*pStr)){ argc++; while ((*pStr != ' ') && (*pStr)){ pStr++; } continue; } pStr++; } if (argc >= MAX_ARGV){ argc = MAX_ARGV - 1; } return argc; } //====================================================== //<Function>: shell_get_argv //<Usage >: This function is to transfer a cmd string to a char array. //<Argus >: string --> pointer to an input cmd string //<Return >: pointer to a char array //<Notes >: NA //====================================================== SHELL_ROM_TEXT_SECTION _LONG_CALL_ u8** shell_get_argv(const u8 *string) { u8 ArgvCount = 0; u8 *pStr; shell_array_init((u8*)shell_argv_array, MAX_ARGV*sizeof(char *), 0); pStr = (u8 *)string; while(*pStr){ shell_argv_array[ArgvCount] = pStr; while((*pStr != ' ') && (*pStr)){ pStr++; } *(pStr++) = '\0'; while((*pStr == ' ') && (*pStr)){ pStr++; } ArgvCount++; if (ArgvCount == MAX_ARGV){ break; } } return (u8 **)&shell_argv_array; } //====================================================== //<Function>: shell_cmd_exec_rom //<Usage >: This function is to parse Uart-Log cmds. If there's a matched // one, it goes to execute that. //<Argus >: pointer to Uart-Log cmd temp buffer //<Return >: VOID //<Notes >: NA //====================================================== SHELL_ROM_TEXT_SECTION _LONG_CALL_ static VOID shell_cmd_exec_rom(PUART_LOG_CTL pUartLogCtlExe) { u8 CmdCnt = 0; u8 argc = 0; u8 **argv; u32 CmdNum; PUART_LOG_BUF pUartLogBuf = pUartLogCtlExe->pTmpLogBuf; PCOMMAND_TABLE pCmdTbl = pUartLogCtlExe->pCmdTbl; argc = shell_get_argc((const u8*)&((*pUartLogBuf).UARTLogBuf[0])); argv = shell_get_argv((const u8*)&((*pUartLogBuf).UARTLogBuf[0])); CmdNum = pUartLogCtlExe->CmdTblSz; if (argc > 0){ _strupr(argv[0]); for (CmdCnt = 0; CmdCnt< CmdNum; CmdCnt++){ if ((_strcmp((const char*)argv[0], (const char*)(pCmdTbl[CmdCnt].cmd)))==0){ pCmdTbl[CmdCnt].func((argc-1) , (argv+1)); shell_array_init(argv[0], sizeof(argv[0]) ,0); break; } } } (*pUartLogBuf).BufCount = 0; shell_array_init(&(*pUartLogBuf).UARTLogBuf[0], UART_LOG_CMD_BUFLEN, '\0'); } //====================================================== //<Function>: shell_show_backspace //<Usage >: To dispaly backspace on the target interface. //<Argus >: BackLen --> backspace number to show // EchoFlag --> a control flag to show msg or not. // pfINPUT --> func pointer to the display function //<Return >: VOID //<Notes >: NA //====================================================== SHELL_ROM_TEXT_SECTION _LONG_CALL_ static VOID shell_show_backspace(u8 BackLen, u8 EchoFlag, VOID *pfINPUT) { u8 BackCnt; ECHOFUNC pfEcho; pfEcho = (ECHOFUNC)pfINPUT; for(BackCnt=0; BackCnt<BackLen; BackCnt++){ if (EchoFlag){ pfEcho((u8*)"%c",KB_ASCII_BS); pfEcho((u8*)" "); pfEcho((u8*)"%c",KB_ASCII_BS); } } } //====================================================== //<Function>: shell_recall_oldcmd //<Usage >: To retrieve the old cmd and may show it on the target interface. //<Argus >: pTmpBuf --> cmd temp buffer, the retrieved cmd will be stored in // it. // OldBuf --> pointer to an cmd buffer. // EchoFlag --> a control flag to show msg or not. // pfINPUT --> func pointer to the display function //<Return >: VOID //<Notes >: NA //====================================================== #ifdef CONFIG_UART_LOG_HISTORY SHELL_ROM_TEXT_SECTION _LONG_CALL_ static VOID shell_recall_oldcmd( PUART_LOG_BUF pTmpBuf, u8 *OldBuf, u8 EchoFlag, VOID *pfINPUT) { ECHOFUNC pfEcho; pfEcho = (ECHOFUNC)pfINPUT; _strcpy((char*)&((*pTmpBuf).UARTLogBuf[0]), (char*)OldBuf); (*pTmpBuf).BufCount = _strlen((char*)&(*pTmpBuf).UARTLogBuf[0]); if (EchoFlag){ pfEcho(&((*pTmpBuf).UARTLogBuf[0])); } } //====================================================== //<Function>: shell_cmd_history //<Usage >: To deal with history-cmds, get the next/previous cmd and show it. //<Argus >: RevData --> a received data. // prvUartLogCtl --> pointer to UART_LOG_CTL // EchoFlag --> a control flag to show msg or not. //<Return >: VOID //<Notes >: NA //====================================================== SHELL_ROM_TEXT_SECTION _LONG_CALL_ VOID shell_cmd_history( u8 RevData, UART_LOG_CTL *prvUartLogCtl, u8 EchoFlag) { ECHOFUNC pfEcho; pfEcho = (ECHOFUNC)(*prvUartLogCtl).pfINPUT; if (RevData == 'A'){ if ((*prvUartLogCtl).CRSTS == 0){ if ((*prvUartLogCtl).RevdNo > 0){ if ((*prvUartLogCtl).SeeIdx == 0){ (*prvUartLogCtl).SeeIdx = (*prvUartLogCtl).RevdNo - 1; } else{ (*prvUartLogCtl).SeeIdx--; } } } shell_show_backspace((*(*prvUartLogCtl).pTmpLogBuf).BufCount, EchoFlag, pfEcho); if ((*prvUartLogCtl).RevdNo > 0){ shell_recall_oldcmd((*prvUartLogCtl).pTmpLogBuf , (u8*)&(*prvUartLogCtl).pHistoryBuf[(*prvUartLogCtl).SeeIdx], 1, (VOID*)pfEcho); } (*prvUartLogCtl).CRSTS = 0; } else if (RevData == 'B'){ if ((*prvUartLogCtl).RevdNo > 0){ if ((*prvUartLogCtl).SeeIdx == ((*prvUartLogCtl).RevdNo-1)){ (*prvUartLogCtl).SeeIdx = 0; } else{ (*prvUartLogCtl).SeeIdx++; } } shell_show_backspace(((*(*prvUartLogCtl).pTmpLogBuf).BufCount), 1, pfEcho); if ((*prvUartLogCtl).RevdNo > 0){ shell_recall_oldcmd((*prvUartLogCtl).pTmpLogBuf, (u8*)&(*prvUartLogCtl).pHistoryBuf[(*prvUartLogCtl).SeeIdx], 1, (VOID*)pfEcho); } (*prvUartLogCtl).CRSTS = 0; } } #endif //====================================================== //<Function>: shell_cmd_chk //<Usage >: To deal with Uart-Log input characters //<Argus >: RevData --> a received data. // prvUartLogCtl --> pointer to UART_LOG_CTL // EchoFlag --> a control flag to show msg or not. //<Return >: VOID //<Notes >: NA //====================================================== SHELL_ROM_TEXT_SECTION _LONG_CALL_ u8 shell_cmd_chk( u8 RevData, UART_LOG_CTL *prvUartLogCtl, u8 EchoFlag) { u8 RTNSTS = 0; u8 SpaceCount = 0; //Cast the input function pointer to the actual echo function pointer type----- ECHOFUNC pfEcho; pfEcho = (ECHOFUNC)(*prvUartLogCtl).pfINPUT; //---------------------------------------------------------------- if (((*(*prvUartLogCtl).pTmpLogBuf).BufCount<(UART_LOG_CMD_BUFLEN-1)) || (((*(*prvUartLogCtl).pTmpLogBuf).BufCount==(UART_LOG_CMD_BUFLEN-1)) && ((RevData == KB_ASCII_CR)||(RevData == '\0')|| (RevData == KB_ASCII_BS) || (RevData == KB_ASCII_BS_7F)))){ if (RevData == 0xFF){ //invlid char, ignore it RTNSTS = 1; } if (RevData == KB_ASCII_LF){ RTNSTS = 1; } else if ((RevData == KB_ASCII_CR)||(RevData == '\0')){ RTNSTS = 2; (*prvUartLogCtl).CRSTS = 1; (*(*prvUartLogCtl).pTmpLogBuf).UARTLogBuf[(*(*prvUartLogCtl).pTmpLogBuf).BufCount] = '\0'; if (EchoFlag){ pfEcho((u8*)"\r\n"); } if((*(*prvUartLogCtl).pTmpLogBuf).BufCount != 0) { #ifdef CONFIG_UART_LOG_HISTORY _strcpy((u8*)&((*prvUartLogCtl).pHistoryBuf[(*prvUartLogCtl).NewIdx]), (const u8*)&((*(*prvUartLogCtl).pTmpLogBuf).UARTLogBuf)); ((*prvUartLogCtl).RevdNo < UART_LOG_HISTORY_LEN) ? ((*prvUartLogCtl).RevdNo++) : ((*prvUartLogCtl).RevdNo = UART_LOG_HISTORY_LEN); (*prvUartLogCtl).SeeIdx = (*prvUartLogCtl).NewIdx; ((*prvUartLogCtl).NewIdx < (UART_LOG_HISTORY_LEN-1)) ? ((*prvUartLogCtl).NewIdx++) : ((*prvUartLogCtl).NewIdx = 0); #endif } } else if ((RevData == KB_ASCII_BS) || (RevData == KB_ASCII_BS_7F)){ RTNSTS = 1; if ((*(*prvUartLogCtl).pTmpLogBuf).BufCount > 0){ (*(*prvUartLogCtl).pTmpLogBuf).BufCount--; shell_show_backspace(1,1,(VOID *)pfEcho); } } else if (RevData == KB_ASCII_TAB){ //the TAB is fixed to be one space(' ') RTNSTS = 1; for(SpaceCount=0; SpaceCount< KB_SPACENO_TAB; SpaceCount++){ (*(*prvUartLogCtl).pTmpLogBuf).UARTLogBuf[(*(*prvUartLogCtl).pTmpLogBuf).BufCount] = ' '; (*(*prvUartLogCtl).pTmpLogBuf).BufCount++; } if (EchoFlag){ pfEcho((u8 *)" "); } } else{ RTNSTS = 1; if (EchoFlag){ pfEcho((u8*)"%c",RevData); } (*(*prvUartLogCtl).pTmpLogBuf).UARTLogBuf[(*(*prvUartLogCtl).pTmpLogBuf).BufCount] = RevData; (*(*prvUartLogCtl).pTmpLogBuf).BufCount++; } } else if ((*(*prvUartLogCtl).pTmpLogBuf).BufCount==(UART_LOG_CMD_BUFLEN-1)){ RTNSTS = 1; pfEcho((u8*)"\n\r <<<Too long cmd string.>>> \n"); (*(*prvUartLogCtl).pTmpLogBuf).UARTLogBuf[(*(*prvUartLogCtl).pTmpLogBuf).BufCount] = '\0'; pfEcho(&(*(*prvUartLogCtl).pTmpLogBuf).UARTLogBuf[0]); } return RTNSTS; } //====================================================== //<Function>: shell_uart_irq_rom //<Usage >: To deal with Uart-Log RX IRQ //<Argus >: VOID //<Return >: VOID //<Notes >: NA //====================================================== SHELL_ROM_TEXT_SECTION _LONG_CALL_ VOID shell_uart_irq_rom(VOID * Data) { krhino_intrpt_enter(); /* To avoid gcc warnings */ ( void ) Data; u8 UartReceiveData = 0; //For Test BOOL PullMode = _FALSE; u32 IrqEn = LOGUART_GetIMR(); LOGUART_SetIMR(0); recv_again: UartReceiveData = LOGUART_GetChar(PullMode); extern int g_uart_init; if(g_uart_init != 0) { extern size_t uart0_rx_buffer_produce(const void *buf, size_t count); (void)uart0_rx_buffer_produce(&UartReceiveData, 1); } //KB_ESC chk is for cmd history, it's a special case here. if (UartReceiveData == KB_ASCII_ESC) { //4 Esc detection is only valid in the first stage of boot sequence (few seconds) if (shell_ctl.ExecuteEsc != _TRUE) { shell_ctl.ExecuteEsc = _TRUE; shell_ctl.EscSTS = 0; } else { //4 the input commands are valid only when the task is ready to execute commands if ((shell_ctl.BootRdy == 1) ||(shell_ctl.shell_task_rdy == 1)) { if (shell_ctl.EscSTS==0) { shell_ctl.EscSTS = 1; } } else { shell_ctl.EscSTS = 0; } } } else if (shell_ctl.EscSTS==1) { if (UartReceiveData != KB_ASCII_LBRKT){ shell_ctl.EscSTS = 0; } else { shell_ctl.EscSTS = 2; } } else { if (shell_ctl.EscSTS==2){ shell_ctl.EscSTS = 0; #ifdef CONFIG_UART_LOG_HISTORY if ((UartReceiveData=='A')|| UartReceiveData=='B'){ shell_cmd_history(UartReceiveData,(UART_LOG_CTL *)&shell_ctl,1); } #endif } else{ } } /* recv all data one time */ if (shell_recv_all_data_onetime == 1) { if (LOGUART_Readable()) goto recv_again; } LOGUART_SetIMR(IrqEn); krhino_intrpt_exit(); } SHELL_ROM_TEXT_SECTION _LONG_CALL_ VOID shell_init_rom(u32 TBLSz, VOID *pTBL) { shell_buf.BufCount = 0; shell_array_init(&shell_buf.UARTLogBuf[0],UART_LOG_CMD_BUFLEN,'\0'); shell_ctl.NewIdx = 0; shell_ctl.SeeIdx = 0; shell_ctl.RevdNo = 0; shell_ctl.EscSTS = 0; shell_ctl.BootRdy = 0; shell_ctl.pTmpLogBuf = &shell_buf; #ifdef CONFIG_UART_LOG_HISTORY shell_ctl.CRSTS = 0; shell_ctl.pHistoryBuf = &shell_history_cmd[0]; #endif shell_ctl.pfINPUT = (VOID *)&DiagPrintf; if (TBLSz != 0) { shell_ctl.pCmdTbl = (PCOMMAND_TABLE) pTBL; shell_ctl.CmdTblSz = TBLSz; } else { void *PTable = NULL; u32 TblSize = cmd_rom_table(&PTable); shell_ctl.pCmdTbl = (PCOMMAND_TABLE) PTable; shell_ctl.CmdTblSz = TblSize; } shell_ctl.shell_task_rdy = 0; //executing boot sequence shell_ctl.ExecuteCmd = _FALSE; shell_ctl.ExecuteEsc = _FALSE; CONSOLE_AMEBA(); } SHELL_ROM_TEXT_SECTION _LONG_CALL_ VOID shell_task_rom(VOID *Data) { /* To avoid gcc warnings */ ( void ) Data; //4 Set this for UartLog check cmd history #ifndef CONFIG_KERNEL shell_ctl.BootRdy = 1; #endif do{ if ((shell_ctl.ExecuteCmd) == _TRUE) { shell_cmd_exec_rom((PUART_LOG_CTL)&shell_ctl); CONSOLE_AMEBA(); shell_ctl.ExecuteCmd = _FALSE; } }while(1); } SHELL_ROM_TEXT_SECTION _LONG_CALL_ static BOOLEAN shell_exit(u32 MaxWaitCount) { u32 WaitCount = 0; do{ if (WaitCount > MaxWaitCount) { return _TRUE;// go back to the normal boot sequence } DelayUs(100); // DBG_8195A("Wait %d\n",WaitCount); WaitCount++; //4 there is a ESC key input in Boot Sequence check stage if (shell_ctl.ExecuteEsc == _TRUE) { CONSOLE_AMEBA(); shell_ctl.EscSTS = 0; break; } }while(1); return _FALSE; } SHELL_ROM_TEXT_SECTION _LONG_CALL_ VOID shell_rom(u32 MaxWaitCount) { if (shell_exit(MaxWaitCount)) { //Go back to normal boot sequence return; } /* rom cmd consol need this */ LOG_MASK(LEVEL_ERROR, 0xFFFFFFFF); shell_ctl.BootRdy = 1; //4 Stay in console stage do{ if ((shell_ctl.ExecuteCmd) == _TRUE) { shell_cmd_exec_rom((PUART_LOG_CTL)&shell_ctl); CONSOLE_AMEBA(); shell_ctl.ExecuteCmd = _FALSE; } }while(1); }
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/app/monitor/rom/shell_rom.c
C
apache-2.0
15,017
/* * xModem protocol * * Copyright (c) 2013 Realtek Semiconductor Corp. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. */ #include <ameba_soc.h> #include "touch_key.h" #define HP_JACK_DET _PA_21 /*headphone detect pin*/ #define HP_JACK_INSET_LEVEL GPIO_PIN_LOW /*insert level*/ typedef struct { u32 pinmux; /* PAx or PBx */ u32 valid; /* 0 or 1 */ } KeyMatrix_TypeDef; #if defined (ARM_CORE_CM4) static CapTouch_CHInitTypeDef CTCChan[4] = { /*DiffThrehold, MbiasCurrent, ETCNNoiseThr, ETCPNoiseThr, CHEnable*/ {35, 0x16, 3, 18, ENABLE}, /* Channel 0 */ {500, 0x08, 250, 250, DISABLE}, /* Channel 1 */ {500, 0x08, 250, 250, DISABLE}, /* Channel 2 */ {500, 0x0b, 250, 250, DISABLE}, /* Channel 3 */ }; static KeyMatrix_TypeDef KeyRow[8] = { /* pinmux, valid */ {_PA_12, 1}, /* row 0 */ {_PA_13, 1}, /* row 1 */ {_PA_14, 1}, /* row 2 */ {_PA_15, 1}, /* row 3 */ {_PA_16, 1}, /* row 4 */ {_PA_18, 0}, /* row 5 */ {_PA_17, 0}, /* row 6 */ {_PA_21, 0}, /* row 7 */ }; static KeyMatrix_TypeDef KeyColumn[8] = { /* pinmux, valid */ {_PA_26, 1}, /* Col 0 */ {_PA_25, 1}, /* Col 1 */ {_PA_19, 1}, /* Col 2 */ {_PA_17, 1}, /* Col 3 */ {_PA_18, 1}, /* Col 4 */ {_PA_16, 0}, /* Col 5 */ {_PA_15, 0}, /* Col 6 */ {_PA_20, 1}, /* Col 7 */ }; #define HP_JACK_DELAY_DET /*detect headphone insert use a delay timer*/ #ifdef HP_JACK_DELAY_DET #include <timers.h> #define HP_JACK_DELAY 50 static TimerHandle_t xTimers = NULL; static void app_hp_jack_timer_callback( TimerHandle_t pxExpiredTimer ) { /* To avoid gcc warinigs */ ( void ) pxExpiredTimer; u32 level = GPIO_ReadDataBit(HP_JACK_DET); if (level == GPIO_PIN_LOW) { GPIO_INTMode(HP_JACK_DET, ENABLE, GPIO_INT_Trigger_LEVEL, GPIO_INT_POLARITY_ACTIVE_HIGH, GPIO_INT_DEBOUNCE_ENABLE); DBG_8195A("hp jack insert \n"); } else { GPIO_INTMode(HP_JACK_DET, ENABLE, GPIO_INT_Trigger_LEVEL, GPIO_INT_POLARITY_ACTIVE_LOW, GPIO_INT_DEBOUNCE_ENABLE); DBG_8195A("hp jack pull out\n"); } /*Should delay at least 63us between GPIO_INTMode & GPIO_INTConfig*/ DelayUs(70); GPIO_INTConfig(HP_JACK_DET, ENABLE); } #endif static void app_hp_jack_int_handler(uint32_t id, u32 event) { /* To avoid gcc warinigs */ ( void ) id; u32 level = event & BIT(0); GPIO_INTConfig(HP_JACK_DET, DISABLE); #ifdef HP_JACK_DELAY_DET portBASE_TYPE taskWoken = pdFALSE; if (xTimers) { if (xTimerChangePeriodFromISR(xTimers, HP_JACK_DELAY, &taskWoken) == pdPASS) { pmu_set_sysactive_time(HP_JACK_DELAY); xTimerStartFromISR(xTimers, &taskWoken); portEND_SWITCHING_ISR(taskWoken); return; } } else #endif if (level == GPIO_INT_POLARITY_ACTIVE_HIGH) { GPIO_INTMode(HP_JACK_DET, ENABLE, GPIO_INT_Trigger_LEVEL, GPIO_INT_POLARITY_ACTIVE_LOW, GPIO_INT_DEBOUNCE_ENABLE); } else { GPIO_INTMode(HP_JACK_DET, ENABLE, GPIO_INT_Trigger_LEVEL, GPIO_INT_POLARITY_ACTIVE_HIGH, GPIO_INT_DEBOUNCE_ENABLE); } DelayUs(70); GPIO_INTConfig(HP_JACK_DET, ENABLE); } void app_hp_jack_init(void) { GPIO_InitTypeDef GPIO_InitStruct_jack; #ifdef HP_JACK_DELAY_DET xTimers = xTimerCreate("Jack_Timer", HP_JACK_DELAY, pdFALSE,NULL,app_hp_jack_timer_callback); if(xTimers ==NULL) DBG_8195A("HP timer create error\n"); #endif GPIO_INTConfig(HP_JACK_DET, DISABLE); GPIO_InitStruct_jack.GPIO_Pin = HP_JACK_DET; GPIO_InitStruct_jack.GPIO_PuPd = GPIO_PuPd_UP; GPIO_InitStruct_jack.GPIO_Mode = GPIO_Mode_INT; GPIO_InitStruct_jack.GPIO_ITTrigger= GPIO_INT_Trigger_LEVEL; GPIO_InitStruct_jack.GPIO_ITPolarity = HP_JACK_INSET_LEVEL; /*GPIOA or GPIOB */ if (HP_JACK_DET < _PB_0) { InterruptRegister(GPIO_INTHandler, GPIOA_IRQ, (u32)GPIOA_BASE, 5); InterruptEn(GPIOA_IRQ, 5); } else { InterruptRegister(GPIO_INTHandler, GPIOB_IRQ, (u32)GPIOB_BASE, 5); InterruptEn(GPIOB_IRQ, 5); } GPIO_Init(&GPIO_InitStruct_jack); GPIO_UserRegIrq(HP_JACK_DET, (VOID *)app_hp_jack_int_handler, NULL); GPIO_INTMode(HP_JACK_DET, ENABLE, GPIO_INT_Trigger_LEVEL, HP_JACK_INSET_LEVEL, GPIO_INT_DEBOUNCE_ENABLE); GPIO_INTConfig(HP_JACK_DET, ENABLE); } /*captouch related function and interrupt handler*/ static void app_captouch_irq_handler(void) { u8 ch; u32 IntStatus; IntStatus = CapTouch_GetISR(CAPTOUCH_DEV); CapTouch_INTClearPendingBit(CAPTOUCH_DEV, IntStatus); for(ch=0; ch<5; ch++) { if(IntStatus & CT_CHX_PRESS_INT(ch)) { DBG_8195A("Key %x press \n",ch); pmu_set_sysactive_time(5); } if(IntStatus & CT_CHX_RELEASE_INT(ch)) { DBG_8195A("Key %x release \n", ch); pmu_set_sysactive_time(5); } } if(IntStatus & BIT_CT_FIFO_OVERFLOW_INT) { DBG_8195A("BIT_CT_FIFO_OVERFLOW_INT \n"); } /* User do not need care the Noise interrupt */ if(IntStatus & BIT_CT_OVER_P_NOISE_THRESHOLD_INT) { CapTouch_Cmd(CAPTOUCH_DEV, DISABLE); CapTouch_Cmd(CAPTOUCH_DEV, ENABLE); } } void app_captouch_init(void) { u32 dslp_wakeup = SOCPS_DsleepWakeStatusGet(); u32 temp = 0; u32 ch = 0; if (dslp_wakeup == FALSE) { CapTouch_InitTypeDef Touch_InitStruct; CapTouch_StructInit(&Touch_InitStruct); _memcpy((void*)Touch_InitStruct.CT_Channel, (void*)CTCChan, 4 * sizeof(CapTouch_CHInitTypeDef)); for (ch = 0; ch < 4; ch++) { if (CTCChan[ch].CT_CHEnable == ENABLE) { PAD_PullCtrl((_PB_4 + ch), GPIO_PuPd_NOPULL); } } CapTouch_Init(CAPTOUCH_DEV, &Touch_InitStruct); CapTouch_Cmd(CAPTOUCH_DEV, ENABLE); CapTouch_INTConfig(CAPTOUCH_DEV, BIT_CT_ALL_INT_EN, ENABLE); //DelayMs(10); //CapTouch_DbgDumpETC(CAPTOUCH_DEV, 0); } /* Register interrupt Callback function */ InterruptRegister((IRQ_FUN) app_captouch_irq_handler, CTOUCH_IRQ, (u32)NULL, 5); InterruptEn(CTOUCH_IRQ, 5); /* enable cap-touch wakeup */ SOCPS_SetWakeEventAON(BIT_CAPTOUCH_WAKE_MSK, ENABLE); /* fix boot reason issue, when cap-touch wakeup */ temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_AON_PM_OPT); temp &= ~BIT_AON_PMC_EN_SNOZ2NORM; HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_AON_PM_OPT, temp); //DBG_8195A("km4 app_captouch_init dslp_wakeup:%x \n", dslp_wakeup); } static void app_keyscan_data_process(u32 ksdata) { u32 row = (ksdata & BIT_KS_ROW_INDEX) >> 4; u32 col = (ksdata & BIT_KS_COL_INDEX) >> 0; u32 press = (ksdata & BIT_KS_PRESS_EVENT) >> 8; DBG_8195A("ksdata:%x (row:%x col:%x press:%x) \n", ksdata, row, col, press); } static void app_keyscan_irq_handler(void) { u32 intr_status = KeyScan_GetINT(KEYSCAN_DEV); u32 temp; u32 tempi; u32 ksdata[16]; /*clear intr*/ KeyScan_ClearINT(KEYSCAN_DEV, intr_status); if (intr_status & BIT_KS_SCAN_EVENT_INT_STATUS) { //auto cleared /*clear keyscan wakeevent*/ SOCPS_AONWakeClear(BIT_KEYSCAN_WAKE_STS); temp = KeyScan_GetDataNum(KEYSCAN_DEV); KeyScan_Read(KEYSCAN_DEV, ksdata, temp); pmu_acquire_wakelock(PMU_KEYSCAN_DEVICE); //DBG_8195A("SCAN_EVENT_INT FIFO Data:"); for(tempi = 0; tempi < temp; tempi++) { app_keyscan_data_process(ksdata[tempi]); } } if (intr_status & BIT_KS_SCAN_FINISH_INT_STATUS) { DBG_8195A("KEYSCAN BIT_KS_SCAN_FINISH_INT_STATUS Intr\n"); } if (intr_status & BIT_KS_ALL_RELEASE_INT_STATUS) { temp = KeyScan_GetDataNum(KEYSCAN_DEV); KeyScan_Read(KEYSCAN_DEV, ksdata, temp); pmu_release_wakelock(PMU_KEYSCAN_DEVICE); //DBG_8195A("ALL RELEASE \n"); for(tempi = 0; tempi < temp; tempi++) { app_keyscan_data_process(ksdata[tempi]); } } } static u32 app_keyscan_suspend(u32 expected_idle_time, void *param) { /* To avoid gcc warning */ ( void ) expected_idle_time; ( void ) param; if(KEYSCAN_DEV->KS_CTRL & BIT_KS_BUSY_STATUS) { return FALSE; } /*reset keyscan for glitch issue*/ if(SOCPS_AONWakeReason() & BIT_KEYSCAN_WAKE_STS) { SOCPS_AONWakeClear(BIT_KEYSCAN_WAKE_STS); //DBG_8195A("ks reset\n"); app_keyscan_init(TRUE); } return TRUE; } static u32 app_keyscan_resume(u32 expected_idle_time, void *param) { /* To avoid gcc warning */ ( void ) expected_idle_time; ( void ) param; if(SOCPS_AONWakeReason() & BIT_KEYSCAN_WAKE_STS) { pmu_set_sysactive_time(20); } return TRUE; } void app_keyscan_init(u8 reset_status) { u32 dslp_wakeup = SOCPS_DsleepWakeStatusGet(); u32 index = 0; u32 column_sel = 0; u32 row_sel = 0; for(index = 0; index < 8; index++) { if (KeyColumn[index].valid) { if(FALSE == reset_status) { PAD_PullCtrl(KeyColumn[index].pinmux, GPIO_PuPd_NOPULL); Pinmux_Config(KeyColumn[index].pinmux, PINMUX_FUNCTION_KEYSCAN_COL); } column_sel |= BIT(index); } } for(index = 0; index < 8; index++) { if (KeyRow[index].valid) { if(FALSE == reset_status) { PAD_PullCtrl(KeyRow[index].pinmux, GPIO_PuPd_UP); Pinmux_Config(KeyRow[index].pinmux, PINMUX_FUNCTION_KEYSCAN_ROW); } row_sel |= BIT(index); } } //DBG_8195A("app_keyscan_init column_sel:%08x, row_sel:%08x\n", column_sel, row_sel); /* keyscan not used */ if ((column_sel == 0) || (row_sel == 0)) { return; } if ((dslp_wakeup == FALSE) || ((dslp_wakeup == TRUE) && (0 == KeyScan_GetDataNum(KEYSCAN_DEV)))) { KeyScan_InitTypeDef KeyScan_InitStruct; /*reset keyscan when dslp keyscan wakeup while no key is scanned*/ RCC_PeriphClockCmd_AON(APBPeriph_KEYSCAN, APBPeriph_KEYSCAN_CLOCK, DISABLE); RCC_PeriphClockCmd_AON(APBPeriph_KEYSCAN, APBPeriph_KEYSCAN_CLOCK, ENABLE); KeyScan_StructInit(&KeyScan_InitStruct); KeyScan_InitStruct.KS_ClkDiv = 49; /* KEYSCAN_2M */ KeyScan_InitStruct.KS_ColSel = column_sel; KeyScan_InitStruct.KS_RowSel = row_sel; KeyScan_InitStruct.KS_WorkMode = KS_EVENT_TRIGGER_MODE; KeyScan_InitStruct.KS_LimitLevel = 2; KeyScan_Init(KEYSCAN_DEV, &KeyScan_InitStruct); //KeyScan_RegDump(); //KeyScan_INTConfig(KEYSCAN_DEV, BIT_KS_FIFO_FULL_INT_MSK| BIT_KS_ALL_RELEASE_INT_MSK, ENABLE); KeyScan_INTConfig(KEYSCAN_DEV, BIT_KS_ALL_RELEASE_INT_MSK | BIT_KS_SCAN_EVENT_INT_MSK, ENABLE); KeyScan_Cmd(KEYSCAN_DEV, ENABLE); } if(FALSE == reset_status) { pmu_register_sleep_callback(PMU_KEYSCAN_DEVICE, (PSM_HOOK_FUN)app_keyscan_suspend, NULL, (PSM_HOOK_FUN)app_keyscan_resume, NULL); InterruptRegister((IRQ_FUN) app_keyscan_irq_handler, KEYSCAN_IRQ, NULL, 5); InterruptEn(KEYSCAN_IRQ, 5); } } #else /*KM0*/ /*if stimuli is used to wakeup KM4, Two things must be configured * 1 the wake up source must be configured in hs_wakeevent_config[] * 2 in case KM0 can't fall sleep dure to some wakelock, user should implement * its own wake event check in km4_wake_event_check() */ #endif
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/app/touch_key/touch_key.c
C
apache-2.0
10,487
/* * Routines to access hardware * * Copyright (c) 2013 Realtek Semiconductor Corp. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. */ #ifndef _TOUCH_KEY_H_ #define _TOUCH_KEY_H_ void app_hp_jack_init(void); void app_captouch_init(void); void app_keyscan_init(u8 reset_status); #endif /* _RCU_STIMULI_H_ */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/app/touch_key/touch_key.h
C
apache-2.0
423
/* X-Modem Header File 1999/09/03 sprite, support Xmode Tx & Rx */ #ifndef _XMODE_H_ #define _XMODE_H_ #include <basic_types.h> /***************** * X-Modem status *****************/ #define XMODEM_OK 1 #define XMODEM_CANCEL 2 #define XMODEM_ACK 3 #define XMODEM_NAK 4 #define XMODEM_COMPLETE 5 #define XMODEM_NO_SESSION 6 #define XMODEM_ABORT 7 #define XMODEM_TIMEOUT 8 /**************************** * flow control character ****************************/ #define SOH 0x01 /* Start of header */ #define STX 0x02 /* Start of header XModem-1K */ #define EOT 0x04 /* End of transmission */ #define ACK 0x06 /* Acknowledge */ #define NAK 0x15 /* Not acknowledge */ #define CAN 0x18 /* Cancel */ #define ESC 0x1b /* User Break */ #define BAUDSET 0x05 /* Part of shakehands, added by Realtek*/ #define BAUDCHK 0x07 /* Part of shakehands, added by Realtek*/ #define XMERASE 0x17 /* Erase Flash, added by Realtek*/ #define XMREAD 0x19 /* Read Flash, added by Realtek*/ #define XMREADV2 0x20 /* Read Flash, added by Realtek*/ #define RXSTATUS 0x21 /* Read Status Register, added by Realtek*/ #define TXSTATUS 0x26 /* Write Status Register, added by Realtek, AZ ACUT ROM not support*/ #define XM_CHECKSUM 0x27 /* check flash write checksum: AZ ACUT ROM not support */ #define XM_TXREG 0x29 /* Write REG or RAM, AZ ACUT ROM not support */ #define XM_RXREG 0x31 /* Read REG or RAM, AZ ACUT ROM not support */ #define XM_ROMVER 0x33 /* read rom code version(02/03/04...): AZ ACUT ROM not support */ /**************************** * Xmode paramters ****************************/ #define FRAME_SIZE 132 /* X-modem structure */ #define FRAME_SIZE_1K 1028 /* X-modem structure */ #define XM_BUFFER_SIZE 1024 /* X-modem buffer */ #define WAIT_FRAME_TIME (830 * 1000) /* 1 sec, wait frame timeout, AmebaZ SMIC: (2500 * 10000), AmebaZ UMC: (2500 * 1000)*/ #define WAIT_CHAR_TIME (415 * 1000) /* 0.5 sec, wait char timeout AmebaZ SMIC: (1250 * 10000), AmebaZ UMC: (1250 * 1000)*/ #define WAIT_HANDSHAKE_TIME (1660 * 1000) /* 2 sec, handshake timeout AmebaZ SMIC: (2500 * 10000), AmebaZ UMC: (1250 * 1000)*/ #define XMODEM_READ_MAXRETRANS 25 /*********************** * frame structure ***********************/ typedef struct { unsigned char soh; unsigned char recordNo; unsigned char recordNoInverted; unsigned char buffer[XM_BUFFER_SIZE]; unsigned char CRC; } XMODEM_FRAME; typedef struct _XMODEM_CTRL_ { u16 currentFrame; /* current frame number */ u16 expected; s32 rFinish; u32 total_frame; }XMODEM_CTRL, *PXMODEM_CTRL; u32 xmodem_img_rxbuffer(u32 baud_rate); /* wll define in section header later */ #define FWU_DATA_SECTION #endif /* _XMODE_H_ */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/app/xmodem/xmodem_rom.h
C
apache-2.0
2,752
/* * Routines to access hardware * * Copyright (c) 2013 Realtek Semiconductor Corp. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. */ #ifndef _XMPORT_UART_H_ #define _XMPORT_UART_H_ struct _xmodem_uart_map { void (*xmodem_uart_init)(u8 uart_idx, u8 pin_mux, u32 baud_rate); void (*xmodem_uart_deinit)(void); void (*xmodem_uart_port_init)(u8 uart_idx, u8 pin_mux, u32 baud_rate); void (*xmodem_uart_port_deinit)(u8 uart_idx); char (*xmodem_uart_readable)(void); char (*xmodem_uart_writable)(void); char (*xmodem_uart_getc)(void); void (*xmodem_uart_putc)(char c); void (*xmodem_uart_putdata)(u8* buf, u32 cnt); char (*xmodem_uart_getc_to)(char *pch, u32 timeout); void (*xmodem_uart_clean_rx)(void); }; extern UART_TypeDef* xmodem_uartx; _LONG_CALL_ void xmodem_uart_init(u8 uart_idx, u8 pin_mux, u32 baud_rate); _LONG_CALL_ void xmodem_uart_deinit(void) ; _LONG_CALL_ void xmodem_uart_port_init(u8 uart_idx, u8 pin_mux, u32 baud_rate); _LONG_CALL_ void xmodem_uart_port_deinit(u8 uart_idx); _LONG_CALL_ char xmodem_uart_readable(void) ; _LONG_CALL_ char xmodem_uart_writable(void) ; _LONG_CALL_ char xmodem_uart_getc(void) ; _LONG_CALL_ void xmodem_uart_putc(char c) ; _LONG_CALL_ void xmodem_uart_putdata(u8* buf, u32 cnt) ; _LONG_CALL_ char xmodem_uart_getc_to(char *pch, u32 timeout); _LONG_CALL_ void xmodem_uart_clean_rx(void); #endif // end of "#define _XMPORT_UART_H_"
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/app/xmodem/xmodem_uart_rom.h
C
apache-2.0
1,507
/* * Routines to access hardware * * Copyright (c) 2013 Realtek Semiconductor Corp. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. */ #ifndef _FW_UPDATE_ROM_H_ #define _FW_UPDATE_ROM_H_ #include "ameba_soc.h" #define BOOT_UART_IDX 0 #define BOOT_UART_PIN_MUX 1 #define BOOT_UART_BAUD_RATE 38400 #define BOOT_UART_MAX_IMG_SZ (32*1024*1024) // 32M extern VOID xmodem_img_write(char *ptr, unsigned int wr_offset, unsigned int frame_size); extern VOID xmodem_img_download(u8 uart_idx); #endif // end of "#define _FW_UPDATE_ROM_H_"
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/app/xmodem/xmodem_update_rom.h
C
apache-2.0
676
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_abs_f32.c * Description: Floating-point vector absolute value * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" #include <math.h> /** * @ingroup groupMath */ /** * @defgroup BasicAbs Vector Absolute Value * * Computes the absolute value of a vector on an element-by-element basis. * * <pre> * pDst[n] = abs(pSrc[n]), 0 <= n < blockSize. * </pre> * * The functions support in-place computation allowing the source and * destination pointers to reference the same memory buffer. * There are separate functions for floating-point, Q7, Q15, and Q31 data types. */ /** * @addtogroup BasicAbs * @{ */ /** * @brief Floating-point vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. */ void arm_abs_f32( float32_t * pSrc, float32_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ float32_t in1, in2, in3, in4; /* temporary variables */ /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = |A| */ /* Calculate absolute and then store the results in the destination buffer. */ /* read sample from source */ in1 = *pSrc; in2 = *(pSrc + 1); in3 = *(pSrc + 2); /* find absolute value */ in1 = fabsf(in1); /* read sample from source */ in4 = *(pSrc + 3); /* find absolute value */ in2 = fabsf(in2); /* read sample from source */ *pDst = in1; /* find absolute value */ in3 = fabsf(in3); /* find absolute value */ in4 = fabsf(in4); /* store result to destination */ *(pDst + 1) = in2; /* store result to destination */ *(pDst + 2) = in3; /* store result to destination */ *(pDst + 3) = in4; /* Update source pointer to process next sampels */ pSrc += 4u; /* Update destination pointer to process next sampels */ pDst += 4u; /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_DSP) */ while (blkCnt > 0u) { /* C = |A| */ /* Calculate absolute and then store the results in the destination buffer. */ *pDst++ = fabsf(*pSrc++); /* Decrement the loop counter */ blkCnt--; } } /** * @} end of BasicAbs group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_abs_f32.c
C
apache-2.0
3,847
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_abs_q15.c * Description: Q15 vector absolute value * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup BasicAbs * @{ */ /** * @brief Q15 vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The function uses saturating arithmetic. * The Q15 value -1 (0x8000) will be saturated to the maximum allowable positive value 0x7FFF. */ void arm_abs_q15( q15_t * pSrc, q15_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) __SIMD32_TYPE *simd; /* Run the below code for Cortex-M4 and Cortex-M3 */ q15_t in1; /* Input value1 */ q15_t in2; /* Input value2 */ /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ simd = __SIMD32_CONST(pDst); while (blkCnt > 0u) { /* C = |A| */ /* Read two inputs */ in1 = *pSrc++; in2 = *pSrc++; /* Store the Absolute result in the destination buffer by packing the two values, in a single cycle */ #ifndef ARM_MATH_BIG_ENDIAN *simd++ = __PKHBT(((in1 > 0) ? in1 : (q15_t)__QSUB16(0, in1)), ((in2 > 0) ? in2 : (q15_t)__QSUB16(0, in2)), 16); #else *simd++ = __PKHBT(((in2 > 0) ? in2 : (q15_t)__QSUB16(0, in2)), ((in1 > 0) ? in1 : (q15_t)__QSUB16(0, in1)), 16); #endif /* #ifndef ARM_MATH_BIG_ENDIAN */ in1 = *pSrc++; in2 = *pSrc++; #ifndef ARM_MATH_BIG_ENDIAN *simd++ = __PKHBT(((in1 > 0) ? in1 : (q15_t)__QSUB16(0, in1)), ((in2 > 0) ? in2 : (q15_t)__QSUB16(0, in2)), 16); #else *simd++ = __PKHBT(((in2 > 0) ? in2 : (q15_t)__QSUB16(0, in2)), ((in1 > 0) ? in1 : (q15_t)__QSUB16(0, in1)), 16); #endif /* #ifndef ARM_MATH_BIG_ENDIAN */ /* Decrement the loop counter */ blkCnt--; } pDst = (q15_t *)simd; /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; while (blkCnt > 0u) { /* C = |A| */ /* Read the input */ in1 = *pSrc++; /* Calculate absolute value of input and then store the result in the destination buffer. */ *pDst++ = (in1 > 0) ? in1 : (q15_t)__QSUB16(0, in1); /* Decrement the loop counter */ blkCnt--; } #else /* Run the below code for Cortex-M0 */ q15_t in; /* Temporary input variable */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; while (blkCnt > 0u) { /* C = |A| */ /* Read the input */ in = *pSrc++; /* Calculate absolute value of input and then store the result in the destination buffer. */ *pDst++ = (in > 0) ? in : ((in == (q15_t) 0x8000) ? 0x7fff : -in); /* Decrement the loop counter */ blkCnt--; } #endif /* #if defined (ARM_MATH_DSP) */ } /** * @} end of BasicAbs group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_abs_q15.c
C
apache-2.0
4,275
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_abs_q31.c * Description: Q31 vector absolute value * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup BasicAbs * @{ */ /** * @brief Q31 vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The function uses saturating arithmetic. * The Q31 value -1 (0x80000000) will be saturated to the maximum allowable positive value 0x7FFFFFFF. */ void arm_abs_q31( q31_t * pSrc, q31_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ q31_t in; /* Input value */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q31_t in1, in2, in3, in4; /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = |A| */ /* Calculate absolute of input (if -1 then saturated to 0x7fffffff) and then store the results in the destination buffer. */ in1 = *pSrc++; in2 = *pSrc++; in3 = *pSrc++; in4 = *pSrc++; *pDst++ = (in1 > 0) ? in1 : (q31_t)__QSUB(0, in1); *pDst++ = (in2 > 0) ? in2 : (q31_t)__QSUB(0, in2); *pDst++ = (in3 > 0) ? in3 : (q31_t)__QSUB(0, in3); *pDst++ = (in4 > 0) ? in4 : (q31_t)__QSUB(0, in4); /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_DSP) */ while (blkCnt > 0u) { /* C = |A| */ /* Calculate absolute value of the input (if -1 then saturated to 0x7fffffff) and then store the results in the destination buffer. */ in = *pSrc++; *pDst++ = (in > 0) ? in : ((in == INT32_MIN) ? INT32_MAX : -in); /* Decrement the loop counter */ blkCnt--; } } /** * @} end of BasicAbs group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_abs_q31.c
C
apache-2.0
3,297
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_abs_q7.c * Description: Q7 vector absolute value * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup BasicAbs * @{ */ /** * @brief Q7 vector absolute value. * @param[in] *pSrc points to the input buffer * @param[out] *pDst points to the output buffer * @param[in] blockSize number of samples in each vector * @return none. * * \par Conditions for optimum performance * Input and output buffers should be aligned by 32-bit * * * <b>Scaling and Overflow Behavior:</b> * \par * The function uses saturating arithmetic. * The Q7 value -1 (0x80) will be saturated to the maximum allowable positive value 0x7F. */ void arm_abs_q7( q7_t * pSrc, q7_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ q7_t in; /* Input value1 */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q31_t in1, in2, in3, in4; /* temporary input variables */ q31_t out1, out2, out3, out4; /* temporary output variables */ /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = |A| */ /* Read inputs */ in1 = (q31_t) * pSrc; in2 = (q31_t) * (pSrc + 1); in3 = (q31_t) * (pSrc + 2); /* find absolute value */ out1 = (in1 > 0) ? in1 : (q31_t)__QSUB8(0, in1); /* read input */ in4 = (q31_t) * (pSrc + 3); /* find absolute value */ out2 = (in2 > 0) ? in2 : (q31_t)__QSUB8(0, in2); /* store result to destination */ *pDst = (q7_t) out1; /* find absolute value */ out3 = (in3 > 0) ? in3 : (q31_t)__QSUB8(0, in3); /* find absolute value */ out4 = (in4 > 0) ? in4 : (q31_t)__QSUB8(0, in4); /* store result to destination */ *(pDst + 1) = (q7_t) out2; /* store result to destination */ *(pDst + 2) = (q7_t) out3; /* store result to destination */ *(pDst + 3) = (q7_t) out4; /* update pointers to process next samples */ pSrc += 4u; pDst += 4u; /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ blkCnt = blockSize; #endif /* #define ARM_MATH_CM0_FAMILY */ while (blkCnt > 0u) { /* C = |A| */ /* Read the input */ in = *pSrc++; /* Store the Absolute result in the destination buffer */ *pDst++ = (in > 0) ? in : ((in == (q7_t) 0x80) ? 0x7f : -in); /* Decrement the loop counter */ blkCnt--; } } /** * @} end of BasicAbs group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_abs_q7.c
C
apache-2.0
3,843
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_add_f32.c * Description: Floating-point vector addition * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @defgroup BasicAdd Vector Addition * * Element-by-element addition of two vectors. * * <pre> * pDst[n] = pSrcA[n] + pSrcB[n], 0 <= n < blockSize. * </pre> * * There are separate functions for floating-point, Q7, Q15, and Q31 data types. */ /** * @addtogroup BasicAdd * @{ */ /** * @brief Floating-point vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_add_f32( float32_t * pSrcA, float32_t * pSrcB, float32_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ float32_t inA1, inA2, inA3, inA4; /* temporary input variabels */ float32_t inB1, inB2, inB3, inB4; /* temporary input variables */ /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = A + B */ /* Add and then store the results in the destination buffer. */ /* read four inputs from sourceA and four inputs from sourceB */ inA1 = *pSrcA; inB1 = *pSrcB; inA2 = *(pSrcA + 1); inB2 = *(pSrcB + 1); inA3 = *(pSrcA + 2); inB3 = *(pSrcB + 2); inA4 = *(pSrcA + 3); inB4 = *(pSrcB + 3); /* C = A + B */ /* add and store result to destination */ *pDst = inA1 + inB1; *(pDst + 1) = inA2 + inB2; *(pDst + 2) = inA3 + inB3; *(pDst + 3) = inA4 + inB4; /* update pointers to process next samples */ pSrcA += 4u; pSrcB += 4u; pDst += 4u; /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_DSP) */ while (blkCnt > 0u) { /* C = A + B */ /* Add and then store the results in the destination buffer. */ *pDst++ = (*pSrcA++) + (*pSrcB++); /* Decrement the loop counter */ blkCnt--; } } /** * @} end of BasicAdd group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_add_f32.c
C
apache-2.0
3,600
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_add_q15.c * Description: Q15 vector addition * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup BasicAdd * @{ */ /** * @brief Q15 vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The function uses saturating arithmetic. * Results outside of the allowable Q15 range [0x8000 0x7FFF] will be saturated. */ void arm_add_q15( q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q31_t inA1, inA2, inB1, inB2; /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = A + B */ /* Add and then store the results in the destination buffer. */ inA1 = *__SIMD32(pSrcA)++; inA2 = *__SIMD32(pSrcA)++; inB1 = *__SIMD32(pSrcB)++; inB2 = *__SIMD32(pSrcB)++; *__SIMD32(pDst)++ = __QADD16(inA1, inB1); *__SIMD32(pDst)++ = __QADD16(inA2, inB2); /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; while (blkCnt > 0u) { /* C = A + B */ /* Add and then store the results in the destination buffer. */ *pDst++ = (q15_t) __QADD16(*pSrcA++, *pSrcB++); /* Decrement the loop counter */ blkCnt--; } #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; while (blkCnt > 0u) { /* C = A + B */ /* Add and then store the results in the destination buffer. */ *pDst++ = (q15_t) __SSAT(((q31_t) * pSrcA++ + *pSrcB++), 16); /* Decrement the loop counter */ blkCnt--; } #endif /* #if defined (ARM_MATH_DSP) */ } /** * @} end of BasicAdd group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_add_q15.c
C
apache-2.0
3,276
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_add_q31.c * Description: Q31 vector addition * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup BasicAdd * @{ */ /** * @brief Q31 vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The function uses saturating arithmetic. * Results outside of the allowable Q31 range[0x80000000 0x7FFFFFFF] will be saturated. */ void arm_add_q31( q31_t * pSrcA, q31_t * pSrcB, q31_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q31_t inA1, inA2, inA3, inA4; q31_t inB1, inB2, inB3, inB4; /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = A + B */ /* Add and then store the results in the destination buffer. */ inA1 = *pSrcA++; inA2 = *pSrcA++; inB1 = *pSrcB++; inB2 = *pSrcB++; inA3 = *pSrcA++; inA4 = *pSrcA++; inB3 = *pSrcB++; inB4 = *pSrcB++; *pDst++ = __QADD(inA1, inB1); *pDst++ = __QADD(inA2, inB2); *pDst++ = __QADD(inA3, inB3); *pDst++ = __QADD(inA4, inB4); /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; while (blkCnt > 0u) { /* C = A + B */ /* Add and then store the results in the destination buffer. */ *pDst++ = __QADD(*pSrcA++, *pSrcB++); /* Decrement the loop counter */ blkCnt--; } #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; while (blkCnt > 0u) { /* C = A + B */ /* Add and then store the results in the destination buffer. */ *pDst++ = (q31_t) clip_q63_to_q31((q63_t) * pSrcA++ + *pSrcB++); /* Decrement the loop counter */ blkCnt--; } #endif /* #if defined (ARM_MATH_DSP) */ } /** * @} end of BasicAdd group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_add_q31.c
C
apache-2.0
3,397
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_add_q7.c * Description: Q7 vector addition * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup BasicAdd * @{ */ /** * @brief Q7 vector addition. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The function uses saturating arithmetic. * Results outside of the allowable Q7 range [0x80 0x7F] will be saturated. */ void arm_add_q7( q7_t * pSrcA, q7_t * pSrcB, q7_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = A + B */ /* Add and then store the results in the destination buffer. */ *__SIMD32(pDst)++ = __QADD8(*__SIMD32(pSrcA)++, *__SIMD32(pSrcB)++); /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; while (blkCnt > 0u) { /* C = A + B */ /* Add and then store the results in the destination buffer. */ *pDst++ = (q7_t) __SSAT(*pSrcA++ + *pSrcB++, 8); /* Decrement the loop counter */ blkCnt--; } #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; while (blkCnt > 0u) { /* C = A + B */ /* Add and then store the results in the destination buffer. */ *pDst++ = (q7_t) __SSAT((q15_t) * pSrcA++ + *pSrcB++, 8); /* Decrement the loop counter */ blkCnt--; } #endif /* #if defined (ARM_MATH_DSP) */ } /** * @} end of BasicAdd group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_add_q7.c
C
apache-2.0
3,086
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_dot_prod_f32.c * Description: Floating-point dot product * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @defgroup dot_prod Vector Dot Product * * Computes the dot product of two vectors. * The vectors are multiplied element-by-element and then summed. * * <pre> * sum = pSrcA[0]*pSrcB[0] + pSrcA[1]*pSrcB[1] + ... + pSrcA[blockSize-1]*pSrcB[blockSize-1] * </pre> * * There are separate functions for floating-point, Q7, Q15, and Q31 data types. */ /** * @addtogroup dot_prod * @{ */ /** * @brief Dot product of floating-point vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. */ void arm_dot_prod_f32( float32_t * pSrcA, float32_t * pSrcB, uint32_t blockSize, float32_t * result) { float32_t sum = 0.0f; /* Temporary result storage */ uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = A[0]* B[0] + A[1]* B[1] + A[2]* B[2] + .....+ A[blockSize-1]* B[blockSize-1] */ /* Calculate dot product and then store the result in a temporary buffer */ sum += (*pSrcA++) * (*pSrcB++); sum += (*pSrcA++) * (*pSrcB++); sum += (*pSrcA++) * (*pSrcB++); sum += (*pSrcA++) * (*pSrcB++); /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_DSP) */ while (blkCnt > 0u) { /* C = A[0]* B[0] + A[1]* B[1] + A[2]* B[2] + .....+ A[blockSize-1]* B[blockSize-1] */ /* Calculate dot product and then store the result in a temporary buffer. */ sum += (*pSrcA++) * (*pSrcB++); /* Decrement the loop counter */ blkCnt--; } /* Store the result back in the destination buffer */ *result = sum; } /** * @} end of dot_prod group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_dot_prod_f32.c
C
apache-2.0
3,476
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_dot_prod_q15.c * Description: Q15 dot product * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup dot_prod * @{ */ /** * @brief Dot product of Q15 vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The intermediate multiplications are in 1.15 x 1.15 = 2.30 format and these * results are added to a 64-bit accumulator in 34.30 format. * Nonsaturating additions are used and given that there are 33 guard bits in the accumulator * there is no risk of overflow. * The return result is in 34.30 format. */ void arm_dot_prod_q15( q15_t * pSrcA, q15_t * pSrcB, uint32_t blockSize, q63_t * result) { q63_t sum = 0; /* Temporary result storage */ uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = A[0]* B[0] + A[1]* B[1] + A[2]* B[2] + .....+ A[blockSize-1]* B[blockSize-1] */ /* Calculate dot product and then store the result in a temporary buffer. */ sum = __SMLALD(*__SIMD32(pSrcA)++, *__SIMD32(pSrcB)++, sum); sum = __SMLALD(*__SIMD32(pSrcA)++, *__SIMD32(pSrcB)++, sum); /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; while (blkCnt > 0u) { /* C = A[0]* B[0] + A[1]* B[1] + A[2]* B[2] + .....+ A[blockSize-1]* B[blockSize-1] */ /* Calculate dot product and then store the results in a temporary buffer. */ sum = __SMLALD(*pSrcA++, *pSrcB++, sum); /* Decrement the loop counter */ blkCnt--; } #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; while (blkCnt > 0u) { /* C = A[0]* B[0] + A[1]* B[1] + A[2]* B[2] + .....+ A[blockSize-1]* B[blockSize-1] */ /* Calculate dot product and then store the results in a temporary buffer. */ sum += (q63_t) ((q31_t) * pSrcA++ * *pSrcB++); /* Decrement the loop counter */ blkCnt--; } #endif /* #if defined (ARM_MATH_DSP) */ /* Store the result in the destination buffer in 34.30 format */ *result = sum; } /** * @} end of dot_prod group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_dot_prod_q15.c
C
apache-2.0
3,754
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_dot_prod_q31.c * Description: Q31 dot product * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup dot_prod * @{ */ /** * @brief Dot product of Q31 vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The intermediate multiplications are in 1.31 x 1.31 = 2.62 format and these * are truncated to 2.48 format by discarding the lower 14 bits. * The 2.48 result is then added without saturation to a 64-bit accumulator in 16.48 format. * There are 15 guard bits in the accumulator and there is no risk of overflow as long as * the length of the vectors is less than 2^16 elements. * The return result is in 16.48 format. */ void arm_dot_prod_q31( q31_t * pSrcA, q31_t * pSrcB, uint32_t blockSize, q63_t * result) { q63_t sum = 0; /* Temporary result storage */ uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q31_t inA1, inA2, inA3, inA4; q31_t inB1, inB2, inB3, inB4; /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = A[0]* B[0] + A[1]* B[1] + A[2]* B[2] + .....+ A[blockSize-1]* B[blockSize-1] */ /* Calculate dot product and then store the result in a temporary buffer. */ inA1 = *pSrcA++; inA2 = *pSrcA++; inA3 = *pSrcA++; inA4 = *pSrcA++; inB1 = *pSrcB++; inB2 = *pSrcB++; inB3 = *pSrcB++; inB4 = *pSrcB++; sum += ((q63_t) inA1 * inB1) >> 14u; sum += ((q63_t) inA2 * inB2) >> 14u; sum += ((q63_t) inA3 * inB3) >> 14u; sum += ((q63_t) inA4 * inB4) >> 14u; /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_DSP) */ while (blkCnt > 0u) { /* C = A[0]* B[0] + A[1]* B[1] + A[2]* B[2] + .....+ A[blockSize-1]* B[blockSize-1] */ /* Calculate dot product and then store the result in a temporary buffer. */ sum += ((q63_t) * pSrcA++ * *pSrcB++) >> 14u; /* Decrement the loop counter */ blkCnt--; } /* Store the result in the destination buffer in 16.48 format */ *result = sum; } /** * @} end of dot_prod group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_dot_prod_q31.c
C
apache-2.0
3,833
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_dot_prod_q7.c * Description: Q7 dot product * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup dot_prod * @{ */ /** * @brief Dot product of Q7 vectors. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[in] blockSize number of samples in each vector * @param[out] *result output result returned here * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The intermediate multiplications are in 1.7 x 1.7 = 2.14 format and these * results are added to an accumulator in 18.14 format. * Nonsaturating additions are used and there is no danger of wrap around as long as * the vectors are less than 2^18 elements long. * The return result is in 18.14 format. */ void arm_dot_prod_q7( q7_t * pSrcA, q7_t * pSrcB, uint32_t blockSize, q31_t * result) { uint32_t blkCnt; /* loop counter */ q31_t sum = 0; /* Temporary variables to store output */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q31_t input1, input2; /* Temporary variables to store input */ q31_t inA1, inA2, inB1, inB2; /* Temporary variables to store input */ /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* read 4 samples at a time from sourceA */ input1 = *__SIMD32(pSrcA)++; /* read 4 samples at a time from sourceB */ input2 = *__SIMD32(pSrcB)++; /* extract two q7_t samples to q15_t samples */ inA1 = __SXTB16(__ROR(input1, 8)); /* extract reminaing two samples */ inA2 = __SXTB16(input1); /* extract two q7_t samples to q15_t samples */ inB1 = __SXTB16(__ROR(input2, 8)); /* extract reminaing two samples */ inB2 = __SXTB16(input2); /* multiply and accumulate two samples at a time */ sum = __SMLAD(inA1, inB1, sum); sum = __SMLAD(inA2, inB2, sum); /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; while (blkCnt > 0u) { /* C = A[0]* B[0] + A[1]* B[1] + A[2]* B[2] + .....+ A[blockSize-1]* B[blockSize-1] */ /* Dot product and then store the results in a temporary buffer. */ sum = __SMLAD(*pSrcA++, *pSrcB++, sum); /* Decrement the loop counter */ blkCnt--; } #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; while (blkCnt > 0u) { /* C = A[0]* B[0] + A[1]* B[1] + A[2]* B[2] + .....+ A[blockSize-1]* B[blockSize-1] */ /* Dot product and then store the results in a temporary buffer. */ sum += (q31_t) ((q15_t) * pSrcA++ * *pSrcB++); /* Decrement the loop counter */ blkCnt--; } #endif /* #if defined (ARM_MATH_DSP) */ /* Store the result in the destination buffer in 18.14 format */ *result = sum; } /** * @} end of dot_prod group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_dot_prod_q7.c
C
apache-2.0
4,231
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_mult_f32.c * Description: Floating-point vector multiplication * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @defgroup BasicMult Vector Multiplication * * Element-by-element multiplication of two vectors. * * <pre> * pDst[n] = pSrcA[n] * pSrcB[n], 0 <= n < blockSize. * </pre> * * There are separate functions for floating-point, Q7, Q15, and Q31 data types. */ /** * @addtogroup BasicMult * @{ */ /** * @brief Floating-point vector multiplication. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. */ void arm_mult_f32( float32_t * pSrcA, float32_t * pSrcB, float32_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counters */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ float32_t inA1, inA2, inA3, inA4; /* temporary input variables */ float32_t inB1, inB2, inB3, inB4; /* temporary input variables */ float32_t out1, out2, out3, out4; /* temporary output variables */ /* loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = A * B */ /* Multiply the inputs and store the results in output buffer */ /* read sample from sourceA */ inA1 = *pSrcA; /* read sample from sourceB */ inB1 = *pSrcB; /* read sample from sourceA */ inA2 = *(pSrcA + 1); /* read sample from sourceB */ inB2 = *(pSrcB + 1); /* out = sourceA * sourceB */ out1 = inA1 * inB1; /* read sample from sourceA */ inA3 = *(pSrcA + 2); /* read sample from sourceB */ inB3 = *(pSrcB + 2); /* out = sourceA * sourceB */ out2 = inA2 * inB2; /* read sample from sourceA */ inA4 = *(pSrcA + 3); /* store result to destination buffer */ *pDst = out1; /* read sample from sourceB */ inB4 = *(pSrcB + 3); /* out = sourceA * sourceB */ out3 = inA3 * inB3; /* store result to destination buffer */ *(pDst + 1) = out2; /* out = sourceA * sourceB */ out4 = inA4 * inB4; /* store result to destination buffer */ *(pDst + 2) = out3; /* store result to destination buffer */ *(pDst + 3) = out4; /* update pointers to process next samples */ pSrcA += 4u; pSrcB += 4u; pDst += 4u; /* Decrement the blockSize loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_DSP) */ while (blkCnt > 0u) { /* C = A * B */ /* Multiply the inputs and store the results in output buffer */ *pDst++ = (*pSrcA++) * (*pSrcB++); /* Decrement the blockSize loop counter */ blkCnt--; } } /** * @} end of BasicMult group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_mult_f32.c
C
apache-2.0
4,272
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_mult_q15.c * Description: Q15 vector multiplication * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup BasicMult * @{ */ /** * @brief Q15 vector multiplication * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The function uses saturating arithmetic. * Results outside of the allowable Q15 range [0x8000 0x7FFF] will be saturated. */ void arm_mult_q15( q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counters */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q31_t inA1, inA2, inB1, inB2; /* temporary input variables */ q15_t out1, out2, out3, out4; /* temporary output variables */ q31_t mul1, mul2, mul3, mul4; /* temporary variables */ /* loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* read two samples at a time from sourceA */ inA1 = *__SIMD32(pSrcA)++; /* read two samples at a time from sourceB */ inB1 = *__SIMD32(pSrcB)++; /* read two samples at a time from sourceA */ inA2 = *__SIMD32(pSrcA)++; /* read two samples at a time from sourceB */ inB2 = *__SIMD32(pSrcB)++; /* multiply mul = sourceA * sourceB */ mul1 = (q31_t) ((q15_t) (inA1 >> 16) * (q15_t) (inB1 >> 16)); mul2 = (q31_t) ((q15_t) inA1 * (q15_t) inB1); mul3 = (q31_t) ((q15_t) (inA2 >> 16) * (q15_t) (inB2 >> 16)); mul4 = (q31_t) ((q15_t) inA2 * (q15_t) inB2); /* saturate result to 16 bit */ out1 = (q15_t) __SSAT(mul1 >> 15, 16); out2 = (q15_t) __SSAT(mul2 >> 15, 16); out3 = (q15_t) __SSAT(mul3 >> 15, 16); out4 = (q15_t) __SSAT(mul4 >> 15, 16); /* store the result */ #ifndef ARM_MATH_BIG_ENDIAN *__SIMD32(pDst)++ = __PKHBT(out2, out1, 16); *__SIMD32(pDst)++ = __PKHBT(out4, out3, 16); #else *__SIMD32(pDst)++ = __PKHBT(out2, out1, 16); *__SIMD32(pDst)++ = __PKHBT(out4, out3, 16); #endif /* #ifndef ARM_MATH_BIG_ENDIAN */ /* Decrement the blockSize loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_DSP) */ while (blkCnt > 0u) { /* C = A * B */ /* Multiply the inputs and store the result in the destination buffer */ *pDst++ = (q15_t) __SSAT((((q31_t) (*pSrcA++) * (*pSrcB++)) >> 15), 16); /* Decrement the blockSize loop counter */ blkCnt--; } } /** * @} end of BasicMult group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_mult_q15.c
C
apache-2.0
4,131
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_mult_q31.c * Description: Q31 vector multiplication * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup BasicMult * @{ */ /** * @brief Q31 vector multiplication. * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The function uses saturating arithmetic. * Results outside of the allowable Q31 range[0x80000000 0x7FFFFFFF] will be saturated. */ void arm_mult_q31( q31_t * pSrcA, q31_t * pSrcB, q31_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counters */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q31_t inA1, inA2, inA3, inA4; /* temporary input variables */ q31_t inB1, inB2, inB3, inB4; /* temporary input variables */ q31_t out1, out2, out3, out4; /* temporary output variables */ /* loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = A * B */ /* Multiply the inputs and then store the results in the destination buffer. */ inA1 = *pSrcA++; inA2 = *pSrcA++; inA3 = *pSrcA++; inA4 = *pSrcA++; inB1 = *pSrcB++; inB2 = *pSrcB++; inB3 = *pSrcB++; inB4 = *pSrcB++; out1 = ((q63_t) inA1 * inB1) >> 32; out2 = ((q63_t) inA2 * inB2) >> 32; out3 = ((q63_t) inA3 * inB3) >> 32; out4 = ((q63_t) inA4 * inB4) >> 32; out1 = __SSAT(out1, 31); out2 = __SSAT(out2, 31); out3 = __SSAT(out3, 31); out4 = __SSAT(out4, 31); *pDst++ = out1 << 1u; *pDst++ = out2 << 1u; *pDst++ = out3 << 1u; *pDst++ = out4 << 1u; /* Decrement the blockSize loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; while (blkCnt > 0u) { /* C = A * B */ /* Multiply the inputs and then store the results in the destination buffer. */ inA1 = *pSrcA++; inB1 = *pSrcB++; out1 = ((q63_t) inA1 * inB1) >> 32; out1 = __SSAT(out1, 31); *pDst++ = out1 << 1u; /* Decrement the blockSize loop counter */ blkCnt--; } #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; while (blkCnt > 0u) { /* C = A * B */ /* Multiply the inputs and then store the results in the destination buffer. */ *pDst++ = (q31_t) clip_q63_to_q31(((q63_t) (*pSrcA++) * (*pSrcB++)) >> 31); /* Decrement the blockSize loop counter */ blkCnt--; } #endif /* #if defined (ARM_MATH_DSP) */ } /** * @} end of BasicMult group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_mult_q31.c
C
apache-2.0
4,027
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_mult_q7.c * Description: Q7 vector multiplication * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup BasicMult * @{ */ /** * @brief Q7 vector multiplication * @param[in] *pSrcA points to the first input vector * @param[in] *pSrcB points to the second input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in each vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The function uses saturating arithmetic. * Results outside of the allowable Q7 range [0x80 0x7F] will be saturated. */ void arm_mult_q7( q7_t * pSrcA, q7_t * pSrcB, q7_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counters */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q7_t out1, out2, out3, out4; /* Temporary variables to store the product */ /* loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = A * B */ /* Multiply the inputs and store the results in temporary variables */ out1 = (q7_t) __SSAT((((q15_t) (*pSrcA++) * (*pSrcB++)) >> 7), 8); out2 = (q7_t) __SSAT((((q15_t) (*pSrcA++) * (*pSrcB++)) >> 7), 8); out3 = (q7_t) __SSAT((((q15_t) (*pSrcA++) * (*pSrcB++)) >> 7), 8); out4 = (q7_t) __SSAT((((q15_t) (*pSrcA++) * (*pSrcB++)) >> 7), 8); /* Store the results of 4 inputs in the destination buffer in single cycle by packing */ *__SIMD32(pDst)++ = __PACKq7(out1, out2, out3, out4); /* Decrement the blockSize loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_DSP) */ while (blkCnt > 0u) { /* C = A * B */ /* Multiply the inputs and store the result in the destination buffer */ *pDst++ = (q7_t) __SSAT((((q15_t) (*pSrcA++) * (*pSrcB++)) >> 7), 8); /* Decrement the blockSize loop counter */ blkCnt--; } } /** * @} end of BasicMult group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_mult_q7.c
C
apache-2.0
3,392
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_negate_f32.c * Description: Negates floating-point vectors * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @defgroup negate Vector Negate * * Negates the elements of a vector. * * <pre> * pDst[n] = -pSrc[n], 0 <= n < blockSize. * </pre> * * The functions support in-place computation allowing the source and * destination pointers to reference the same memory buffer. * There are separate functions for floating-point, Q7, Q15, and Q31 data types. */ /** * @addtogroup negate * @{ */ /** * @brief Negates the elements of a floating-point vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_negate_f32( float32_t * pSrc, float32_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ float32_t in1, in2, in3, in4; /* temporary variables */ /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* read inputs from source */ in1 = *pSrc; in2 = *(pSrc + 1); in3 = *(pSrc + 2); in4 = *(pSrc + 3); /* negate the input */ in1 = -in1; in2 = -in2; in3 = -in3; in4 = -in4; /* store the result to destination */ *pDst = in1; *(pDst + 1) = in2; *(pDst + 2) = in3; *(pDst + 3) = in4; /* update pointers to process next samples */ pSrc += 4u; pDst += 4u; /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_DSP) */ while (blkCnt > 0u) { /* C = -A */ /* Negate and then store the results in the destination buffer. */ *pDst++ = -*pSrc++; /* Decrement the loop counter */ blkCnt--; } } /** * @} end of negate group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_negate_f32.c
C
apache-2.0
3,311
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_negate_q15.c * Description: Negates Q15 vectors * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup negate * @{ */ /** * @brief Negates the elements of a Q15 vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. * * \par Conditions for optimum performance * Input and output buffers should be aligned by 32-bit * * * <b>Scaling and Overflow Behavior:</b> * \par * The function uses saturating arithmetic. * The Q15 value -1 (0x8000) will be saturated to the maximum allowable positive value 0x7FFF. */ void arm_negate_q15( q15_t * pSrc, q15_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ q15_t in; #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q31_t in1, in2; /* Temporary variables */ /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = -A */ /* Read two inputs at a time */ in1 = _SIMD32_OFFSET(pSrc); in2 = _SIMD32_OFFSET(pSrc + 2); /* negate two samples at a time */ in1 = __QSUB16(0, in1); /* negate two samples at a time */ in2 = __QSUB16(0, in2); /* store the result to destination 2 samples at a time */ _SIMD32_OFFSET(pDst) = in1; /* store the result to destination 2 samples at a time */ _SIMD32_OFFSET(pDst + 2) = in2; /* update pointers to process next samples */ pSrc += 4u; pDst += 4u; /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_DSP) */ while (blkCnt > 0u) { /* C = -A */ /* Negate and then store the result in the destination buffer. */ in = *pSrc++; *pDst++ = (in == (q15_t) 0x8000) ? 0x7fff : -in; /* Decrement the loop counter */ blkCnt--; } } /** * @} end of negate group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_negate_q15.c
C
apache-2.0
3,378
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_negate_q31.c * Description: Negates Q31 vectors * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup negate * @{ */ /** * @brief Negates the elements of a Q31 vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The function uses saturating arithmetic. * The Q31 value -1 (0x80000000) will be saturated to the maximum allowable positive value 0x7FFFFFFF. */ void arm_negate_q31( q31_t * pSrc, q31_t * pDst, uint32_t blockSize) { q31_t in; /* Temporary variable */ uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q31_t in1, in2, in3, in4; /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = -A */ /* Negate and then store the results in the destination buffer. */ in1 = *pSrc++; in2 = *pSrc++; in3 = *pSrc++; in4 = *pSrc++; *pDst++ = __QSUB(0, in1); *pDst++ = __QSUB(0, in2); *pDst++ = __QSUB(0, in3); *pDst++ = __QSUB(0, in4); /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_DSP) */ while (blkCnt > 0u) { /* C = -A */ /* Negate and then store the result in the destination buffer. */ in = *pSrc++; *pDst++ = (in == INT32_MIN) ? INT32_MAX : -in; /* Decrement the loop counter */ blkCnt--; } } /** * @} end of negate group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_negate_q31.c
C
apache-2.0
3,043
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_negate_q7.c * Description: Negates Q7 vectors * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup negate * @{ */ /** * @brief Negates the elements of a Q7 vector. * @param[in] *pSrc points to the input vector * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The function uses saturating arithmetic. * The Q7 value -1 (0x80) will be saturated to the maximum allowable positive value 0x7F. */ void arm_negate_q7( q7_t * pSrc, q7_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ q7_t in; #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q31_t input; /* Input values1-4 */ q31_t zero = 0x00000000; /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = -A */ /* Read four inputs */ input = *__SIMD32(pSrc)++; /* Store the Negated results in the destination buffer in a single cycle by packing the results */ *__SIMD32(pDst)++ = __QSUB8(zero, input); /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_DSP) */ while (blkCnt > 0u) { /* C = -A */ /* Negate and then store the results in the destination buffer. */ \ in = *pSrc++; *pDst++ = (in == (q7_t) 0x80) ? 0x7f : -in; /* Decrement the loop counter */ blkCnt--; } } /** * @} end of negate group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_negate_q7.c
C
apache-2.0
2,973
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_offset_f32.c * Description: Floating-point vector offset * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @defgroup offset Vector Offset * * Adds a constant offset to each element of a vector. * * <pre> * pDst[n] = pSrc[n] + offset, 0 <= n < blockSize. * </pre> * * The functions support in-place computation allowing the source and * destination pointers to reference the same memory buffer. * There are separate functions for floating-point, Q7, Q15, and Q31 data types. */ /** * @addtogroup offset * @{ */ /** * @brief Adds a constant offset to a floating-point vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_offset_f32( float32_t * pSrc, float32_t offset, float32_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ float32_t in1, in2, in3, in4; /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = A + offset */ /* Add offset and then store the results in the destination buffer. */ /* read samples from source */ in1 = *pSrc; in2 = *(pSrc + 1); /* add offset to input */ in1 = in1 + offset; /* read samples from source */ in3 = *(pSrc + 2); /* add offset to input */ in2 = in2 + offset; /* read samples from source */ in4 = *(pSrc + 3); /* add offset to input */ in3 = in3 + offset; /* store result to destination */ *pDst = in1; /* add offset to input */ in4 = in4 + offset; /* store result to destination */ *(pDst + 1) = in2; /* store result to destination */ *(pDst + 2) = in3; /* store result to destination */ *(pDst + 3) = in4; /* update pointers to process next samples */ pSrc += 4u; pDst += 4u; /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_DSP) */ while (blkCnt > 0u) { /* C = A + offset */ /* Add offset and then store the result in the destination buffer. */ *pDst++ = (*pSrc++) + offset; /* Decrement the loop counter */ blkCnt--; } } /** * @} end of offset group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_offset_f32.c
C
apache-2.0
3,797
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_offset_q15.c * Description: Q15 vector offset * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup offset * @{ */ /** * @brief Adds a constant offset to a Q15 vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The function uses saturating arithmetic. * Results outside of the allowable Q15 range [0x8000 0x7FFF] are saturated. */ void arm_offset_q15( q15_t * pSrc, q15_t offset, q15_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q31_t offset_packed; /* Offset packed to 32 bit */ /*loop Unrolling */ blkCnt = blockSize >> 2u; /* Offset is packed to 32 bit in order to use SIMD32 for addition */ offset_packed = __PKHBT(offset, offset, 16); /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = A + offset */ /* Add offset and then store the results in the destination buffer, 2 samples at a time. */ *__SIMD32(pDst)++ = __QADD16(*__SIMD32(pSrc)++, offset_packed); *__SIMD32(pDst)++ = __QADD16(*__SIMD32(pSrc)++, offset_packed); /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; while (blkCnt > 0u) { /* C = A + offset */ /* Add offset and then store the results in the destination buffer. */ *pDst++ = (q15_t) __QADD16(*pSrc++, offset); /* Decrement the loop counter */ blkCnt--; } #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; while (blkCnt > 0u) { /* C = A + offset */ /* Add offset and then store the results in the destination buffer. */ *pDst++ = (q15_t) __SSAT(((q31_t) * pSrc++ + offset), 16); /* Decrement the loop counter */ blkCnt--; } #endif /* #if defined (ARM_MATH_DSP) */ } /** * @} end of offset group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_offset_q15.c
C
apache-2.0
3,389
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_offset_q31.c * Description: Q31 vector offset * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup offset * @{ */ /** * @brief Adds a constant offset to a Q31 vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The function uses saturating arithmetic. * Results outside of the allowable Q31 range [0x80000000 0x7FFFFFFF] are saturated. */ void arm_offset_q31( q31_t * pSrc, q31_t offset, q31_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q31_t in1, in2, in3, in4; /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = A + offset */ /* Add offset and then store the results in the destination buffer. */ in1 = *pSrc++; in2 = *pSrc++; in3 = *pSrc++; in4 = *pSrc++; *pDst++ = __QADD(in1, offset); *pDst++ = __QADD(in2, offset); *pDst++ = __QADD(in3, offset); *pDst++ = __QADD(in4, offset); /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; while (blkCnt > 0u) { /* C = A + offset */ /* Add offset and then store the result in the destination buffer. */ *pDst++ = __QADD(*pSrc++, offset); /* Decrement the loop counter */ blkCnt--; } #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; while (blkCnt > 0u) { /* C = A + offset */ /* Add offset and then store the result in the destination buffer. */ *pDst++ = (q31_t) clip_q63_to_q31((q63_t) * pSrc++ + offset); /* Decrement the loop counter */ blkCnt--; } #endif /* #if defined (ARM_MATH_DSP) */ } /** * @} end of offset group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_offset_q31.c
C
apache-2.0
3,278
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_offset_q7.c * Description: Q7 vector offset * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup offset * @{ */ /** * @brief Adds a constant offset to a Q7 vector. * @param[in] *pSrc points to the input vector * @param[in] offset is the offset to be added * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The function uses saturating arithmetic. * Results outside of the allowable Q7 range [0x80 0x7F] are saturated. */ void arm_offset_q7( q7_t * pSrc, q7_t offset, q7_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q31_t offset_packed; /* Offset packed to 32 bit */ /*loop Unrolling */ blkCnt = blockSize >> 2u; /* Offset is packed to 32 bit in order to use SIMD32 for addition */ offset_packed = __PACKq7(offset, offset, offset, offset); /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = A + offset */ /* Add offset and then store the results in the destination bufferfor 4 samples at a time. */ *__SIMD32(pDst)++ = __QADD8(*__SIMD32(pSrc)++, offset_packed); /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; while (blkCnt > 0u) { /* C = A + offset */ /* Add offset and then store the result in the destination buffer. */ *pDst++ = (q7_t) __SSAT(*pSrc++ + offset, 8); /* Decrement the loop counter */ blkCnt--; } #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; while (blkCnt > 0u) { /* C = A + offset */ /* Add offset and then store the result in the destination buffer. */ *pDst++ = (q7_t) __SSAT((q15_t) * pSrc++ + offset, 8); /* Decrement the loop counter */ blkCnt--; } #endif /* #if defined (ARM_MATH_DSP) */ } /** * @} end of offset group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_offset_q7.c
C
apache-2.0
3,318
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_scale_f32.c * Description: Multiplies a floating-point vector by a scalar * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @defgroup scale Vector Scale * * Multiply a vector by a scalar value. For floating-point data, the algorithm used is: * * <pre> * pDst[n] = pSrc[n] * scale, 0 <= n < blockSize. * </pre> * * In the fixed-point Q7, Q15, and Q31 functions, <code>scale</code> is represented by * a fractional multiplication <code>scaleFract</code> and an arithmetic shift <code>shift</code>. * The shift allows the gain of the scaling operation to exceed 1.0. * The algorithm used with fixed-point data is: * * <pre> * pDst[n] = (pSrc[n] * scaleFract) << shift, 0 <= n < blockSize. * </pre> * * The overall scale factor applied to the fixed-point data is * <pre> * scale = scaleFract * 2^shift. * </pre> * * The functions support in-place computation allowing the source and destination * pointers to reference the same memory buffer. */ /** * @addtogroup scale * @{ */ /** * @brief Multiplies a floating-point vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scale scale factor to be applied * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. */ void arm_scale_f32( float32_t * pSrc, float32_t scale, float32_t * pDst, uint32_t blockSize) { uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ float32_t in1, in2, in3, in4; /* temporary variabels */ /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* C = A * scale */ /* Scale the input and then store the results in the destination buffer. */ /* read input samples from source */ in1 = *pSrc; in2 = *(pSrc + 1); /* multiply with scaling factor */ in1 = in1 * scale; /* read input sample from source */ in3 = *(pSrc + 2); /* multiply with scaling factor */ in2 = in2 * scale; /* read input sample from source */ in4 = *(pSrc + 3); /* multiply with scaling factor */ in3 = in3 * scale; in4 = in4 * scale; /* store the result to destination */ *pDst = in1; *(pDst + 1) = in2; *(pDst + 2) = in3; *(pDst + 3) = in4; /* update pointers to process next samples */ pSrc += 4u; pDst += 4u; /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_DSP) */ while (blkCnt > 0u) { /* C = A * scale */ /* Scale the input and then store the result in the destination buffer. */ *pDst++ = (*pSrc++) * scale; /* Decrement the loop counter */ blkCnt--; } } /** * @} end of scale group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_scale_f32.c
C
apache-2.0
4,240
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_scale_q15.c * Description: Multiplies a Q15 vector by a scalar * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup scale * @{ */ /** * @brief Multiplies a Q15 vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scaleFract fractional portion of the scale value * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The input data <code>*pSrc</code> and <code>scaleFract</code> are in 1.15 format. * These are multiplied to yield a 2.30 intermediate result and this is shifted with saturation to 1.15 format. */ void arm_scale_q15( q15_t * pSrc, q15_t scaleFract, int8_t shift, q15_t * pDst, uint32_t blockSize) { int8_t kShift = 15 - shift; /* shift to apply after scaling */ uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q15_t in1, in2, in3, in4; q31_t inA1, inA2; /* Temporary variables */ q31_t out1, out2, out3, out4; /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* Reading 2 inputs from memory */ inA1 = *__SIMD32(pSrc)++; inA2 = *__SIMD32(pSrc)++; /* C = A * scale */ /* Scale the inputs and then store the 2 results in the destination buffer * in single cycle by packing the outputs */ out1 = (q31_t) ((q15_t) (inA1 >> 16) * scaleFract); out2 = (q31_t) ((q15_t) inA1 * scaleFract); out3 = (q31_t) ((q15_t) (inA2 >> 16) * scaleFract); out4 = (q31_t) ((q15_t) inA2 * scaleFract); /* apply shifting */ out1 = out1 >> kShift; out2 = out2 >> kShift; out3 = out3 >> kShift; out4 = out4 >> kShift; /* saturate the output */ in1 = (q15_t) (__SSAT(out1, 16)); in2 = (q15_t) (__SSAT(out2, 16)); in3 = (q15_t) (__SSAT(out3, 16)); in4 = (q15_t) (__SSAT(out4, 16)); /* store the result to destination */ *__SIMD32(pDst)++ = __PKHBT(in2, in1, 16); *__SIMD32(pDst)++ = __PKHBT(in4, in3, 16); /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; while (blkCnt > 0u) { /* C = A * scale */ /* Scale the input and then store the result in the destination buffer. */ *pDst++ = (q15_t) (__SSAT(((*pSrc++) * scaleFract) >> kShift, 16)); /* Decrement the loop counter */ blkCnt--; } #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; while (blkCnt > 0u) { /* C = A * scale */ /* Scale the input and then store the result in the destination buffer. */ *pDst++ = (q15_t) (__SSAT(((q31_t) * pSrc++ * scaleFract) >> kShift, 16)); /* Decrement the loop counter */ blkCnt--; } #endif /* #if defined (ARM_MATH_DSP) */ } /** * @} end of scale group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_scale_q15.c
C
apache-2.0
4,318
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_scale_q31.c * Description: Multiplies a Q31 vector by a scalar * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup scale * @{ */ /** * @brief Multiplies a Q31 vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scaleFract fractional portion of the scale value * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The input data <code>*pSrc</code> and <code>scaleFract</code> are in 1.31 format. * These are multiplied to yield a 2.62 intermediate result and this is shifted with saturation to 1.31 format. */ void arm_scale_q31( q31_t * pSrc, q31_t scaleFract, int8_t shift, q31_t * pDst, uint32_t blockSize) { int8_t kShift = shift + 1; /* Shift to apply after scaling */ int8_t sign = (kShift & 0x80); uint32_t blkCnt; /* loop counter */ q31_t in, out; #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q31_t in1, in2, in3, in4; /* temporary input variables */ q31_t out1, out2, out3, out4; /* temporary output variabels */ /*loop Unrolling */ blkCnt = blockSize >> 2u; if (sign == 0u) { /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* read four inputs from source */ in1 = *pSrc; in2 = *(pSrc + 1); in3 = *(pSrc + 2); in4 = *(pSrc + 3); /* multiply input with scaler value */ in1 = ((q63_t) in1 * scaleFract) >> 32; in2 = ((q63_t) in2 * scaleFract) >> 32; in3 = ((q63_t) in3 * scaleFract) >> 32; in4 = ((q63_t) in4 * scaleFract) >> 32; /* apply shifting */ out1 = in1 << kShift; out2 = in2 << kShift; /* saturate the results. */ if (in1 != (out1 >> kShift)) out1 = 0x7FFFFFFF ^ (in1 >> 31); if (in2 != (out2 >> kShift)) out2 = 0x7FFFFFFF ^ (in2 >> 31); out3 = in3 << kShift; out4 = in4 << kShift; *pDst = out1; *(pDst + 1) = out2; if (in3 != (out3 >> kShift)) out3 = 0x7FFFFFFF ^ (in3 >> 31); if (in4 != (out4 >> kShift)) out4 = 0x7FFFFFFF ^ (in4 >> 31); /* Store result destination */ *(pDst + 2) = out3; *(pDst + 3) = out4; /* Update pointers to process next sampels */ pSrc += 4u; pDst += 4u; /* Decrement the loop counter */ blkCnt--; } } else { /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* read four inputs from source */ in1 = *pSrc; in2 = *(pSrc + 1); in3 = *(pSrc + 2); in4 = *(pSrc + 3); /* multiply input with scaler value */ in1 = ((q63_t) in1 * scaleFract) >> 32; in2 = ((q63_t) in2 * scaleFract) >> 32; in3 = ((q63_t) in3 * scaleFract) >> 32; in4 = ((q63_t) in4 * scaleFract) >> 32; /* apply shifting */ out1 = in1 >> -kShift; out2 = in2 >> -kShift; out3 = in3 >> -kShift; out4 = in4 >> -kShift; /* Store result destination */ *pDst = out1; *(pDst + 1) = out2; *(pDst + 2) = out3; *(pDst + 3) = out4; /* Update pointers to process next sampels */ pSrc += 4u; pDst += 4u; /* Decrement the loop counter */ blkCnt--; } } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_DSP) */ if (sign == 0) { while (blkCnt > 0u) { /* C = A * scale */ /* Scale the input and then store the result in the destination buffer. */ in = *pSrc++; in = ((q63_t) in * scaleFract) >> 32; out = in << kShift; if (in != (out >> kShift)) out = 0x7FFFFFFF ^ (in >> 31); *pDst++ = out; /* Decrement the loop counter */ blkCnt--; } } else { while (blkCnt > 0u) { /* C = A * scale */ /* Scale the input and then store the result in the destination buffer. */ in = *pSrc++; in = ((q63_t) in * scaleFract) >> 32; out = in >> -kShift; *pDst++ = out; /* Decrement the loop counter */ blkCnt--; } } } /** * @} end of scale group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_scale_q31.c
C
apache-2.0
5,733
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_scale_q7.c * Description: Multiplies a Q7 vector by a scalar * * $Date: 27. January 2017 * $Revision: V.1.5.1 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2017 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "arm_math.h" /** * @ingroup groupMath */ /** * @addtogroup scale * @{ */ /** * @brief Multiplies a Q7 vector by a scalar. * @param[in] *pSrc points to the input vector * @param[in] scaleFract fractional portion of the scale value * @param[in] shift number of bits to shift the result by * @param[out] *pDst points to the output vector * @param[in] blockSize number of samples in the vector * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The input data <code>*pSrc</code> and <code>scaleFract</code> are in 1.7 format. * These are multiplied to yield a 2.14 intermediate result and this is shifted with saturation to 1.7 format. */ void arm_scale_q7( q7_t * pSrc, q7_t scaleFract, int8_t shift, q7_t * pDst, uint32_t blockSize) { int8_t kShift = 7 - shift; /* shift to apply after scaling */ uint32_t blkCnt; /* loop counter */ #if defined (ARM_MATH_DSP) /* Run the below code for Cortex-M4 and Cortex-M3 */ q7_t in1, in2, in3, in4, out1, out2, out3, out4; /* Temporary variables to store input & output */ /*loop Unrolling */ blkCnt = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while (blkCnt > 0u) { /* Reading 4 inputs from memory */ in1 = *pSrc++; in2 = *pSrc++; in3 = *pSrc++; in4 = *pSrc++; /* C = A * scale */ /* Scale the inputs and then store the results in the temporary variables. */ out1 = (q7_t) (__SSAT(((in1) * scaleFract) >> kShift, 8)); out2 = (q7_t) (__SSAT(((in2) * scaleFract) >> kShift, 8)); out3 = (q7_t) (__SSAT(((in3) * scaleFract) >> kShift, 8)); out4 = (q7_t) (__SSAT(((in4) * scaleFract) >> kShift, 8)); /* Packing the individual outputs into 32bit and storing in * destination buffer in single write */ *__SIMD32(pDst)++ = __PACKq7(out1, out2, out3, out4); /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ blkCnt = blockSize % 0x4u; while (blkCnt > 0u) { /* C = A * scale */ /* Scale the input and then store the result in the destination buffer. */ *pDst++ = (q7_t) (__SSAT(((*pSrc++) * scaleFract) >> kShift, 8)); /* Decrement the loop counter */ blkCnt--; } #else /* Run the below code for Cortex-M0 */ /* Initialize blkCnt with number of samples */ blkCnt = blockSize; while (blkCnt > 0u) { /* C = A * scale */ /* Scale the input and then store the result in the destination buffer. */ *pDst++ = (q7_t) (__SSAT((((q15_t) * pSrc++ * scaleFract) >> kShift), 8)); /* Decrement the loop counter */ blkCnt--; } #endif /* #if defined (ARM_MATH_DSP) */ } /** * @} end of scale group */
YifuLiu/AliOS-Things
hardware/chip/rtl872xd/sdk/component/soc/realtek/amebad/cmsis-dsp/Source/BasicMathFunctions/arm_scale_q7.c
C
apache-2.0
4,006