Merge pull request #4034 from thread-liu/step4

[add] complicated dirvers for STM32MP157A-DK1 board
This commit is contained in:
Bernard Xiong 2020-12-05 10:27:16 +08:00 committed by GitHub
commit f4890efa0e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 5390 additions and 133 deletions

View File

@ -40,7 +40,21 @@ config BSP_USING_RNG
depends on (SOC_SERIES_STM32L4 || SOC_SERIES_STM32F4 || SOC_SERIES_STM32F7 || \
SOC_SERIES_STM32H7 || SOC_SERIES_STM32MP1)
default n
config BSP_USING_HASH
bool "Enable HASH (Hash House Harriers)"
select RT_USING_HWCRYPTO
select RT_HWCRYPTO_USING_HASH
depends on (SOC_SERIES_STM32MP1)
default n
config BSP_USING_CRYP
bool "Enable CRYP (Encrypt And Decrypt Data)"
select RT_USING_HWCRYPTO
select RT_HWCRYPTO_USING_CRYP
depends on (SOC_SERIES_STM32MP1)
default n
config BSP_USING_UDID
bool "Enable UDID (Unique Device Identifier)"
select RT_USING_HWCRYPTO

View File

@ -1,13 +1,11 @@
/*
* Copyright (c) 2006-2018, RT-Thread Development Team
* Copyright (c) 2006-2022, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2019-01-02 zylx first version
* 2019-01-08 SummerGift clean up the code
* 2020-06-20 thread-liu add stm32mp1
* 2020-06-20 thread-liu first version
*/
#ifndef __DMA_CONFIG_H__
@ -19,6 +17,22 @@
extern "C" {
#endif
/* DMA1 stream0 */
/* DMA1 stream1 */
/* DMA1 stream2 */
/* DMA1 stream3 */
/* DMA1 stream4 */
/* DMA1 stream5 */
/* DMA1 stream6 */
/* DMA1 stream7 */
/* DMA2 stream0 */
#if defined(BSP_UART3_RX_USING_DMA) && !defined(UART3_RX_DMA_INSTANCE)
#define UART3_RX_DMA_IRQHandler DMA2_Stream0_IRQHandler
@ -26,18 +40,12 @@ extern "C" {
#define UART3_RX_DMA_INSTANCE DMA2_Stream0
#define UART3_RX_DMA_CHANNEL DMA_REQUEST_USART3_RX
#define UART3_RX_DMA_IRQ DMA2_Stream0_IRQn
#elif defined(BSP_SPI4_RX_USING_DMA) && !defined(SPI4_RX_DMA_INSTANCE)
#define SPI4_DMA_RX_IRQHandler DMA2_Stream0_IRQHandler
#define SPI4_RX_DMA_RCC RCC_MC_AHB2ENSETR_DMA2EN
#define SPI4_RX_DMA_INSTANCE DMA2_Stream0
#define SPI4_RX_DMA_CHANNEL DMA_REQUEST_SPI4_RX
#define SPI4_RX_DMA_IRQ DMA2_Stream0_IRQn
#elif defined(BSP_UART5_RX_USING_DMA) && !defined(UART5_RX_DMA_INSTANCE)
#define UART5_DMA_RX_IRQHandler DMA2_Stream0_IRQHandler
#define UART5_RX_DMA_RCC RCC_MC_AHB2ENSETR_DMA2EN
#define UART5_RX_DMA_INSTANCE DMA2_Stream0
#define UART5_RX_DMA_CHANNEL DMA_REQUEST_UART5_RX
#define UART5_RX_DMA_IRQ DMA2_Stream0_IRQn
#elif defined(BSP_SPI5_RX_USING_DMA) && !defined(SPI5_RX_DMA_INSTANCE)
#define SPI5_DMA_RX_IRQHandler DMA2_Stream0_IRQHandler
#define SPI5_RX_DMA_RCC RCC_MC_AHB2ENSETR_DMA2EN
#define SPI5_RX_DMA_INSTANCE DMA2_Stream0
#define SPI5_RX_DMA_CHANNEL DMA_REQUEST_SPI5_RX
#define SPI5_RX_DMA_IRQ DMA2_Stream0_IRQn
#endif
/* DMA2 stream1 */
@ -47,12 +55,12 @@ extern "C" {
#define UART3_TX_DMA_INSTANCE DMA2_Stream1
#define UART3_TX_DMA_CHANNEL DMA_REQUEST_USART3_TX
#define UART3_TX_DMA_IRQ DMA2_Stream1_IRQn
#elif defined(BSP_SPI4_TX_USING_DMA) && !defined(SPI4_TX_DMA_INSTANCE)
#define SPI4_DMA_TX_IRQHandler DMA2_Stream1_IRQHandler
#define SPI4_TX_DMA_RCC RCC_MC_AHB2ENSETR_DMA2EN
#define SPI4_TX_DMA_INSTANCE DMA2_Stream1
#define SPI4_TX_DMA_CHANNEL DMA_REQUEST_SPI4_TX
#define SPI4_TX_DMA_IRQ DMA2_Stream1_IRQn
#elif defined(BSP_SPI5_TX_USING_DMA) && !defined(SPI5_TX_DMA_INSTANCE)
#define SPI5_DMA_TX_IRQHandler DMA2_Stream1_IRQHandler
#define SPI5_TX_DMA_RCC RCC_MC_AHB2ENSETR_DMA2EN
#define SPI5_TX_DMA_INSTANCE DMA2_Stream1
#define SPI5_TX_DMA_CHANNEL DMA_REQUEST_SPI5_TX
#define SPI5_TX_DMA_IRQ DMA2_Stream1_IRQn
#endif
/* DMA2 stream2 */
@ -65,48 +73,48 @@ extern "C" {
#endif
/* DMA2 stream3 */
#if defined(BSP_SPI5_RX_USING_DMA) && !defined(SPI5_RX_DMA_INSTANCE)
#define SPI5_DMA_RX_IRQHandler DMA2_Stream3_IRQHandler
#define SPI5_RX_DMA_RCC RCC_MC_AHB2ENSETR_DMA2EN
#define SPI5_RX_DMA_INSTANCE DMA2_Stream3
#define SPI5_RX_DMA_CHANNEL DMA_REQUEST_SPI5_RX
#define SPI5_RX_DMA_IRQ DMA2_Stream3_IRQn
#if defined(BSP_UART4_RX_USING_DMA) && !defined(UART4_RX_DMA_INSTANCE)
#define UART4_DMA_RX_IRQHandler DMA2_Stream3_IRQHandler
#define UART4_RX_DMA_RCC RCC_MC_AHB2ENSETR_DMA2EN
#define UART4_RX_DMA_INSTANCE DMA2_Stream3
#define UART4_RX_DMA_CHANNEL DMA_REQUEST_UART4_RX
#define UART4_RX_DMA_IRQ DMA2_Stream3_IRQn
#endif
/* DMA2 stream4 */
#if defined(BSP_SPI5_TX_USING_DMA) && !defined(SPI5_TX_DMA_INSTANCE)
#define SPI5_DMA_TX_IRQHandler DMA2_Stream4_IRQHandler
#define SPI5_TX_DMA_RCC RCC_MC_AHB2ENSETR_DMA2EN
#define SPI5_TX_DMA_INSTANCE DMA2_Stream4
#define SPI5_TX_DMA_CHANNEL DMA_REQUEST_SPI5_TX
#define SPI5_TX_DMA_IRQ DMA2_Stream4_IRQn
#if defined(BSP_UART4_TX_USING_DMA) && !defined(UART5_TX_DMA_INSTANCE)
#define UART4_DMA_TX_IRQHandler DMA2_Stream4_IRQHandler
#define UART4_TX_DMA_RCC RCC_MC_AHB2ENSETR_DMA2EN
#define UART4_TX_DMA_INSTANCE DMA2_Stream4
#define UART4_TX_DMA_CHANNEL DMA_REQUEST_UART4_TX
#define UART4_TX_DMA_IRQ DMA2_Stream4_IRQn
#endif
/* DMA2 stream5 */
#if defined(BSP_UART4_TX_USING_DMA) && !defined(UART5_TX_DMA_INSTANCE)
#define UART4_DMA_TX_IRQHandler DMA2_Stream5_IRQHandler
#define UART4_TX_DMA_RCC RCC_MC_AHB2ENSETR_DMA2EN
#define UART4_TX_DMA_INSTANCE DMA2_Stream5
#define UART4_TX_DMA_CHANNEL DMA_REQUEST_UART4_TX
#define UART4_TX_DMA_IRQ DMA2_Stream5_IRQn
#if defined(BSP_USING_CRYP) && !defined(CRYP2_OUT_DMA_INSTANCE)
#define CRYP2_DMA_OUT_IRQHandler DMA2_Stream5_IRQHandler
#define CRYP2_OUT_DMA_RCC RCC_MC_AHB2ENSETR_DMA2EN
#define CRYP2_OUT_DMA_INSTANCE DMA2_Stream5
#define CRYP2_OUT_DMA_CHANNEL DMA_REQUEST_CRYP2_OUT
#define CRYP2_OUT_DMA_IRQ DMA2_Stream5_IRQn
#endif
/* DMA2 stream6 */
#if defined(BSP_UART4_RX_USING_DMA) && !defined(UART4_RX_DMA_INSTANCE)
#define UART4_DMA_RX_IRQHandler DMA2_Stream6_IRQHandler
#define UART4_RX_DMA_RCC RCC_MC_AHB2ENSETR_DMA2EN
#define UART4_RX_DMA_INSTANCE DMA2_Stream6
#define UART4_RX_DMA_CHANNEL DMA_REQUEST_UART4_RX
#define UART4_RX_DMA_IRQ DMA2_Stream6_IRQn
#if defined(BSP_USING_CRYP) && !defined(CRYP2_IN_DMA_INSTANCE)
#define CRYP2_DMA_IN_IRQHandler DMA2_Stream6_IRQHandler
#define CRYP2_IN_DMA_RCC RCC_MC_AHB2ENSETR_DMA2EN
#define CRYP2_IN_DMA_INSTANCE DMA2_Stream6
#define CRYP2_IN_DMA_CHANNEL DMA_REQUEST_CRYP2_IN
#define CRYP2_IN_DMA_IRQ DMA2_Stream6_IRQn
#endif
/* DMA2 stream7 */
#if defined(BSP_UART5_TX_USING_DMA) && !defined(UART5_TX_DMA_INSTANCE)
#define UART5_DMA_TX_IRQHandler DMA2_Stream7_IRQHandler
#define UART5_TX_DMA_RCC RCC_MC_AHB2ENSETR_DMA2EN
#define UART5_TX_DMA_INSTANCE DMA2_Stream7
#define UART5_TX_DMA_CHANNEL DMA_REQUEST_UART5_TX
#define UART5_TX_DMA_IRQ DMA2_Stream7_IRQn
#if defined(BSP_USING_HASH) && !defined(HASH2_IN_DMA_INSTANCE)
#define HASH2_DMA_IN_IRQHandler DMA2_Stream7_IRQHandler
#define HASH2_IN_DMA_RCC RCC_MC_AHB2ENSETR_DMA2EN
#define HASH2_IN_DMA_INSTANCE DMA2_Stream7
#define HASH2_IN_DMA_CHANNEL DMA_REQUEST_HASH2_IN
#define HASH2_IN_DMA_IRQ DMA2_Stream7_IRQn
#endif
#ifdef __cplusplus

View File

@ -7,6 +7,8 @@
* Date Author Notes
* 2019-07-10 Ernest 1st version
* 2020-10-14 Dozingfiretruck Porting for stm32wbxx
* 2020-11-26 thread-liu add hash
* 2020-11-26 thread-liu add cryp
*/
#include <rtthread.h>
@ -15,7 +17,8 @@
#include <string.h>
#include "drv_crypto.h"
#include "board.h"
#include "drv_config.h"
struct stm32_hwcrypto_device
{
struct rt_hwcrypto_device dev;
@ -24,12 +27,7 @@ struct stm32_hwcrypto_device
#if defined(BSP_USING_CRC)
struct hash_ctx_des
{
CRC_HandleTypeDef contex;
};
#if defined(SOC_SERIES_STM32L4) || defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32H7) || defined(SOC_SERIES_STM32F7) || defined(SOC_SERIES_STM32WB)
#if defined(SOC_SERIES_STM32L4) || defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32H7) || defined(SOC_SERIES_STM32F7) || defined(SOC_SERIES_STM32WB) || defined(SOC_SERIES_STM32MP1)
static struct hwcrypto_crc_cfg crc_backup_cfg;
static int reverse_bit(rt_uint32_t n)
@ -49,12 +47,12 @@ static rt_uint32_t _crc_update(struct hwcrypto_crc *ctx, const rt_uint8_t *in, r
rt_uint32_t result = 0;
struct stm32_hwcrypto_device *stm32_hw_dev = (struct stm32_hwcrypto_device *)ctx->parent.device->user_data;
#if defined(SOC_SERIES_STM32L4)|| defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32H7) || defined(SOC_SERIES_STM32F7) || defined(SOC_SERIES_STM32WB)
#if defined(SOC_SERIES_STM32L4)|| defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32H7) || defined(SOC_SERIES_STM32F7) || defined(SOC_SERIES_STM32WB) || defined(SOC_SERIES_STM32MP1)
CRC_HandleTypeDef *HW_TypeDef = (CRC_HandleTypeDef *)(ctx->parent.contex);
#endif
rt_mutex_take(&stm32_hw_dev->mutex, RT_WAITING_FOREVER);
#if defined(SOC_SERIES_STM32L4) || defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32H7) || defined(SOC_SERIES_STM32F7) || defined(SOC_SERIES_STM32WB)
#if defined(SOC_SERIES_STM32L4) || defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32H7) || defined(SOC_SERIES_STM32F7) || defined(SOC_SERIES_STM32WB) || defined(SOC_SERIES_STM32MP1)
if (memcmp(&crc_backup_cfg, &ctx->crc_cfg, sizeof(struct hwcrypto_crc_cfg)) != 0)
{
if (HW_TypeDef->Init.DefaultPolynomialUse == DEFAULT_POLYNOMIAL_DISABLE)
@ -113,7 +111,7 @@ static rt_uint32_t _crc_update(struct hwcrypto_crc *ctx, const rt_uint8_t *in, r
result = HAL_CRC_Accumulate(ctx->parent.contex, (rt_uint32_t *)in, length);
#if defined(SOC_SERIES_STM32L4) || defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32H7) || defined(SOC_SERIES_STM32F7) || defined(SOC_SERIES_STM32WB)
#if defined(SOC_SERIES_STM32L4) || defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32H7) || defined(SOC_SERIES_STM32F7) || defined(SOC_SERIES_STM32WB) || defined(SOC_SERIES_STM32MP1)
if (HW_TypeDef->Init.OutputDataInversionMode)
{
ctx ->crc_cfg.last_val = reverse_bit(result);
@ -159,10 +157,213 @@ static const struct hwcrypto_rng_ops rng_ops =
};
#endif /* BSP_USING_RNG */
#if defined(BSP_USING_HASH)
static rt_err_t _hash_update(struct hwcrypto_hash *ctx, const rt_uint8_t *in, rt_size_t length)
{
rt_uint32_t tickstart = 0;
rt_uint32_t result = RT_EOK;
struct stm32_hwcrypto_device *stm32_hw_dev = (struct stm32_hwcrypto_device *)ctx->parent.device->user_data;
rt_mutex_take(&stm32_hw_dev->mutex, RT_WAITING_FOREVER);
#if defined(SOC_SERIES_STM32MP1)
HASH_HandleTypeDef *HW_TypeDef = (HASH_HandleTypeDef *)(ctx->parent.contex);
/* Start HASH computation using DMA transfer */
switch (ctx->parent.type)
{
case HWCRYPTO_TYPE_SHA224:
result = HAL_HASHEx_SHA224_Start_DMA(HW_TypeDef, (uint8_t *)in, length);
break;
case HWCRYPTO_TYPE_SHA256:
result = HAL_HASHEx_SHA256_Start_DMA(HW_TypeDef, (uint8_t *)in, length);
break;
case HWCRYPTO_TYPE_MD5:
result = HAL_HASH_MD5_Start_DMA(HW_TypeDef, (uint8_t *)in, length);
break;
case HWCRYPTO_TYPE_SHA1:
result = HAL_HASH_SHA1_Start_DMA(HW_TypeDef, (uint8_t *)in, length);
break;
default :
rt_kprintf("not support hash type: %x", ctx->parent.type);
break;
}
if (result != HAL_OK)
{
goto _exit;
}
/* Wait for DMA transfer to complete */
tickstart = rt_tick_get();
while (HAL_HASH_GetState(HW_TypeDef) == HAL_HASH_STATE_BUSY)
{
if (rt_tick_get() - tickstart > 0xFFFF)
{
result = RT_ETIMEOUT;
goto _exit;
}
}
#endif
_exit:
rt_mutex_release(&stm32_hw_dev->mutex);
return result;
}
static rt_err_t _hash_finish(struct hwcrypto_hash *ctx, rt_uint8_t *out, rt_size_t length)
{
rt_uint32_t result = RT_EOK;
struct stm32_hwcrypto_device *stm32_hw_dev = (struct stm32_hwcrypto_device *)ctx->parent.device->user_data;
rt_mutex_take(&stm32_hw_dev->mutex, RT_WAITING_FOREVER);
#if defined(SOC_SERIES_STM32MP1)
HASH_HandleTypeDef *HW_TypeDef = (HASH_HandleTypeDef *)(ctx->parent.contex);
/* Get the computed digest value */
switch (ctx->parent.type)
{
case HWCRYPTO_TYPE_SHA224:
result = HAL_HASHEx_SHA224_Finish(HW_TypeDef, (uint8_t *)out, length);
break;
case HWCRYPTO_TYPE_SHA256:
result = HAL_HASHEx_SHA256_Finish(HW_TypeDef, (uint8_t *)out, length);
break;
case HWCRYPTO_TYPE_MD5:
result = HAL_HASH_MD5_Finish(HW_TypeDef, (uint8_t *)out, length);
break;
case HWCRYPTO_TYPE_SHA1:
result = HAL_HASH_SHA1_Finish(HW_TypeDef, (uint8_t *)out, length);
break;
default :
rt_kprintf("not support hash type: %x", ctx->parent.type);
break;
}
if (result != HAL_OK)
{
goto _exit;
}
#endif
_exit:
rt_mutex_release(&stm32_hw_dev->mutex);
return result;
}
static const struct hwcrypto_hash_ops hash_ops =
{
.update = _hash_update,
.finish = _hash_finish
};
#endif /* BSP_USING_HASH */
#if defined(BSP_USING_CRYP)
static rt_err_t _cryp_crypt(struct hwcrypto_symmetric *ctx,
struct hwcrypto_symmetric_info *info)
{
rt_uint32_t result = RT_EOK;
rt_uint32_t tickstart = 0;
struct stm32_hwcrypto_device *stm32_hw_dev = (struct stm32_hwcrypto_device *)ctx->parent.device->user_data;
rt_mutex_take(&stm32_hw_dev->mutex, RT_WAITING_FOREVER);
#if defined(SOC_SERIES_STM32MP1)
CRYP_HandleTypeDef *HW_TypeDef = (CRYP_HandleTypeDef *)(ctx->parent.contex);
switch (ctx->parent.type)
{
case HWCRYPTO_TYPE_AES_ECB:
HW_TypeDef->Init.Algorithm = CRYP_AES_ECB;
break;
case HWCRYPTO_TYPE_AES_CBC:
HW_TypeDef->Init.Algorithm = CRYP_AES_CBC;
break;
case HWCRYPTO_TYPE_AES_CTR:
HW_TypeDef->Init.Algorithm = CRYP_AES_CTR;
break;
case HWCRYPTO_TYPE_DES_ECB:
HW_TypeDef->Init.Algorithm = CRYP_DES_ECB;
break;
case HWCRYPTO_TYPE_DES_CBC:
HW_TypeDef->Init.Algorithm = CRYP_DES_CBC;
break;
default :
rt_kprintf("not support cryp type: %x", ctx->parent.type);
break;
}
HAL_CRYP_DeInit(HW_TypeDef);
HW_TypeDef->Init.DataType = CRYP_DATATYPE_8B;
HW_TypeDef->Init.DataWidthUnit = CRYP_DATAWIDTHUNIT_BYTE;
HW_TypeDef->Init.KeySize = CRYP_KEYSIZE_128B;
HW_TypeDef->Init.pKey = (uint32_t*)ctx->key;
result = HAL_CRYP_Init(HW_TypeDef);
if (result != HAL_OK)
{
/* Initialization Error */
goto _exit;
}
if (info->mode == HWCRYPTO_MODE_ENCRYPT)
{
result = HAL_CRYP_Encrypt_DMA(HW_TypeDef, (uint32_t *)info->in, info->length, (uint32_t *)info->out);
}
else if (info->mode == HWCRYPTO_MODE_DECRYPT)
{
result = HAL_CRYP_Decrypt_DMA(HW_TypeDef, (uint32_t *)info->in, info->length, (uint32_t *)info->out);
}
else
{
rt_kprintf("error cryp mode : %02x!\n", info->mode);
result = RT_ERROR;
goto _exit;
}
if (result != HAL_OK)
{
goto _exit;
}
tickstart = rt_tick_get();
while (HAL_CRYP_GetState(HW_TypeDef) != HAL_CRYP_STATE_READY)
{
if (rt_tick_get() - tickstart > 0xFFFF)
{
result = RT_ETIMEOUT;
goto _exit;
}
}
#endif
if (result != HAL_OK)
{
goto _exit;
}
_exit:
rt_mutex_release(&stm32_hw_dev->mutex);
return result;
}
static const struct hwcrypto_symmetric_ops cryp_ops =
{
.crypt = _cryp_crypt
};
#endif
static rt_err_t _crypto_create(struct rt_hwcrypto_ctx *ctx)
{
rt_err_t res = RT_EOK;
switch (ctx->type & HWCRYPTO_MAIN_TYPE_MASK)
{
#if defined(BSP_USING_RNG)
@ -174,8 +375,11 @@ static rt_err_t _crypto_create(struct rt_hwcrypto_ctx *ctx)
res = -RT_ERROR;
break;
}
#if defined(SOC_SERIES_STM32MP1)
hrng->Instance = RNG2;
#else
hrng->Instance = RNG;
#endif
HAL_RNG_Init(hrng);
ctx->contex = hrng;
((struct hwcrypto_rng *)ctx)->ops = &rng_ops;
@ -193,9 +397,12 @@ static rt_err_t _crypto_create(struct rt_hwcrypto_ctx *ctx)
res = -RT_ERROR;
break;
}
#if defined(SOC_SERIES_STM32MP1)
hcrc->Instance = CRC2;
#else
hcrc->Instance = CRC;
#if defined(SOC_SERIES_STM32L4) || defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32H7) || defined(SOC_SERIES_STM32F7) || defined(SOC_SERIES_STM32WB)
#endif
#if defined(SOC_SERIES_STM32L4) || defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32H7) || defined(SOC_SERIES_STM32F7) || defined(SOC_SERIES_STM32WB) || defined(SOC_SERIES_STM32MP1)
hcrc->Init.DefaultPolynomialUse = DEFAULT_POLYNOMIAL_ENABLE;
hcrc->Init.DefaultInitValueUse = DEFAULT_INIT_VALUE_DISABLE;
hcrc->Init.InputDataInversionMode = CRC_INPUTDATA_INVERSION_BYTE;
@ -209,9 +416,77 @@ static rt_err_t _crypto_create(struct rt_hwcrypto_ctx *ctx)
#endif /* defined(SOC_SERIES_STM32L4) || defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32H7) || defined(SOC_SERIES_STM32F7) */
ctx->contex = hcrc;
((struct hwcrypto_crc *)ctx)->ops = &crc_ops;
break;
}
#endif /* BSP_USING_CRC */
#if defined(BSP_USING_HASH)
case HWCRYPTO_TYPE_MD5:
case HWCRYPTO_TYPE_SHA1:
case HWCRYPTO_TYPE_SHA2:
{
HASH_HandleTypeDef *hash = rt_calloc(1, sizeof(HASH_HandleTypeDef));
if (RT_NULL == hash)
{
res = -RT_ERROR;
break;
}
#if defined(SOC_SERIES_STM32MP1)
/* enable dma for hash */
__HAL_RCC_DMA2_CLK_ENABLE();
HAL_NVIC_SetPriority(DMA2_Stream7_IRQn, 2, 0);
HAL_NVIC_EnableIRQ(DMA2_Stream7_IRQn);
hash->Init.DataType = HASH_DATATYPE_8B;
if (HAL_HASH_Init(hash) != HAL_OK)
{
res = -RT_ERROR;
}
#endif
ctx->contex = hash;
((struct hwcrypto_hash *)ctx)->ops = &hash_ops;
break;
}
#endif /* BSP_USING_HASH */
#if defined(BSP_USING_CRYP)
case HWCRYPTO_TYPE_AES:
case HWCRYPTO_TYPE_DES:
case HWCRYPTO_TYPE_3DES:
case HWCRYPTO_TYPE_RC4:
case HWCRYPTO_TYPE_GCM:
{
CRYP_HandleTypeDef *cryp = rt_calloc(1, sizeof(CRYP_HandleTypeDef));
if (RT_NULL == cryp)
{
res = -RT_ERROR;
break;
}
#if defined(SOC_SERIES_STM32MP1)
cryp->Instance = CRYP2;
/* enable dma for cryp */
__HAL_RCC_DMA2_CLK_ENABLE();
HAL_NVIC_SetPriority(DMA2_Stream5_IRQn, 2, 0);
HAL_NVIC_EnableIRQ(DMA2_Stream5_IRQn);
HAL_NVIC_SetPriority(DMA2_Stream6_IRQn, 2, 0);
HAL_NVIC_EnableIRQ(DMA2_Stream6_IRQn);
if (HAL_CRYP_Init(cryp) != HAL_OK)
{
res = -RT_ERROR;
}
#endif
ctx->contex = cryp;
((struct hwcrypto_symmetric *)ctx)->ops = &cryp_ops;
break;
}
#endif /* BSP_USING_CRYP */
default:
res = -RT_ERROR;
break;
@ -234,6 +509,26 @@ static void _crypto_destroy(struct rt_hwcrypto_ctx *ctx)
HAL_CRC_DeInit((CRC_HandleTypeDef *)(ctx->contex));
break;
#endif /* BSP_USING_CRC */
#if defined(BSP_USING_HASH)
case HWCRYPTO_TYPE_MD5:
case HWCRYPTO_TYPE_SHA1:
case HWCRYPTO_TYPE_SHA2:
__HAL_HASH_RESET_HANDLE_STATE((HASH_HandleTypeDef *)(ctx->contex));
HAL_HASH_DeInit((HASH_HandleTypeDef *)(ctx->contex));
break;
#endif /* BSP_USING_HASH */
#if defined(BSP_USING_CRYP)
case HWCRYPTO_TYPE_AES:
case HWCRYPTO_TYPE_DES:
case HWCRYPTO_TYPE_3DES:
case HWCRYPTO_TYPE_RC4:
case HWCRYPTO_TYPE_GCM:
HAL_CRYP_DeInit((CRYP_HandleTypeDef *)(ctx->contex));
break;
#endif /* BSP_USING_CRYP */
default:
break;
}
@ -251,7 +546,7 @@ static rt_err_t _crypto_clone(struct rt_hwcrypto_ctx *des, const struct rt_hwcry
case HWCRYPTO_TYPE_RNG:
if (des->contex && src->contex)
{
rt_memcpy(des->contex, src->contex, sizeof(struct hash_ctx_des));
rt_memcpy(des->contex, src->contex, sizeof(RNG_HandleTypeDef));
}
break;
#endif /* BSP_USING_RNG */
@ -260,10 +555,35 @@ static rt_err_t _crypto_clone(struct rt_hwcrypto_ctx *des, const struct rt_hwcry
case HWCRYPTO_TYPE_CRC:
if (des->contex && src->contex)
{
rt_memcpy(des->contex, src->contex, sizeof(struct hash_ctx_des));
rt_memcpy(des->contex, src->contex, sizeof(CRC_HandleTypeDef));
}
break;
#endif /* BSP_USING_CRC */
#if defined(BSP_USING_HASH)
case HWCRYPTO_TYPE_MD5:
case HWCRYPTO_TYPE_SHA1:
case HWCRYPTO_TYPE_SHA2:
if (des->contex && src->contex)
{
rt_memcpy(des->contex, src->contex, sizeof(HASH_HandleTypeDef));
}
break;
#endif /* BSP_USING_HASH */
#if defined(BSP_USING_CRYP)
case HWCRYPTO_TYPE_AES:
case HWCRYPTO_TYPE_DES:
case HWCRYPTO_TYPE_3DES:
case HWCRYPTO_TYPE_RC4:
case HWCRYPTO_TYPE_GCM:
if (des->contex && src->contex)
{
rt_memcpy(des->contex, src->contex, sizeof(CRYP_HandleTypeDef));
}
break;
#endif /* BSP_USING_CRYP */
default:
res = -RT_ERROR;
break;
@ -285,11 +605,68 @@ static void _crypto_reset(struct rt_hwcrypto_ctx *ctx)
__HAL_CRC_DR_RESET((CRC_HandleTypeDef *)ctx-> contex);
break;
#endif /* BSP_USING_CRC */
#if defined(BSP_USING_HASH)
case HWCRYPTO_TYPE_MD5:
case HWCRYPTO_TYPE_SHA1:
case HWCRYPTO_TYPE_SHA2:
__HAL_HASH_RESET_HANDLE_STATE((HASH_HandleTypeDef *)(ctx->contex));
break;
#endif /* BSP_USING_HASH*/
#if defined(BSP_USING_CRYP)
case HWCRYPTO_TYPE_AES:
case HWCRYPTO_TYPE_DES:
case HWCRYPTO_TYPE_3DES:
case HWCRYPTO_TYPE_RC4:
case HWCRYPTO_TYPE_GCM:
break;
#endif /* BSP_USING_CRYP */
default:
break;
}
}
void HASH2_DMA_IN_IRQHandler(void)
{
extern DMA_HandleTypeDef hdma_hash_in;
/* enter interrupt */
rt_interrupt_enter();
HAL_DMA_IRQHandler(&hdma_hash_in);
/* leave interrupt */
rt_interrupt_leave();
}
void CRYP2_DMA_IN_IRQHandler(void)
{
extern DMA_HandleTypeDef hdma_cryp_in;
/* enter interrupt */
rt_interrupt_enter();
HAL_DMA_IRQHandler(&hdma_cryp_in);
/* leave interrupt */
rt_interrupt_leave();
}
void CRYP2_DMA_OUT_IRQHandler(void)
{
extern DMA_HandleTypeDef hdma_cryp_out;
/* enter interrupt */
rt_interrupt_enter();
HAL_DMA_IRQHandler(&hdma_cryp_out);
/* leave interrupt */
rt_interrupt_leave();
}
static const struct rt_hwcrypto_ops _ops =
{
.create = _crypto_create,
@ -306,10 +683,10 @@ int stm32_hw_crypto_device_init(void)
_crypto_dev.dev.ops = &_ops;
#if defined(BSP_USING_UDID)
#if defined(SOC_SERIES_STM32L4) || defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32F1) || defined(SOC_SERIES_STM32F4) || defined(SOC_SERIES_STM32F7) || defined(SOC_SERIES_STM32WB)
#if defined(SOC_SERIES_STM32L4) || defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32F1) || defined(SOC_SERIES_STM32F4) || defined(SOC_SERIES_STM32F7)
cpuid[0] = HAL_GetUIDw0();
cpuid[1] = HAL_GetUIDw1();
#elif defined(SOC_SERIES_STM32H7)
#elif defined(SOC_SERIES_STM32H7) || defined(SOC_SERIES_STM32MP1)
cpuid[0] = HAL_GetREVID();
cpuid[1] = HAL_GetDEVID();
#endif

View File

@ -45,9 +45,6 @@ if GetDepend(['RT_USING_USB_HOST']) or GetDepend(['RT_USING_USB_DEVICE']):
if GetDepend(['RT_USING_CAN']):
src += ['STM32MP1xx_HAL_Driver/Src/stm32mp1xx_hal_can.c']
if GetDepend(['BSP_USING_ETH']):
src += ['STM32MP1xx_HAL_Driver/Src/stm32mp1xx_hal_eth.c']
if GetDepend(['BSP_USING_WWDG']):
src += ['STM32MP1xx_HAL_Driver/Src/stm32mp1xx_hal_wwdg.c']
@ -92,6 +89,25 @@ if GetDepend(['BSP_USING_LTDC']):
src += ['STM32MP1xx_HAL_Driver/Src/stm32mp1xx_ll_dma2d.c']
src += ['STM32MP1xx_HAL_Driver/Src/stm32mp1xx_hal_dsi.c']
if GetDepend(['BSP_USING_SDMMC']):
src += ['STM32MP1xx_HAL_Driver/Src/stm32mp1xx_ll_sdmmc.c']
src += ['STM32MP1xx_HAL_Driver/Src/stm32mp1xx_hal_sd.c']
if GetDepend(['BSP_USING_HASH']):
src += ['STM32MP1xx_HAL_Driver/Src/stm32mp1xx_hal_hash.c']
src += ['STM32MP1xx_HAL_Driver/Src/stm32mp1xx_hal_hash_ex.c']
if GetDepend(['BSP_USING_CRC']):
src += ['STM32MP1xx_HAL_Driver/Src/stm32mp1xx_hal_crc.c']
src += ['STM32MP1xx_HAL_Driver/Src/stm32mp1xx_hal_crc_ex.c']
if GetDepend(['BSP_USING_RNG']):
src += ['STM32MP1xx_HAL_Driver/Src/stm32mp1xx_hal_rng.c']
if GetDepend(['BSP_USING_CRYP']):
src += ['STM32MP1xx_HAL_Driver/Src/stm32mp1xx_hal_cryp.c']
src += ['STM32MP1xx_HAL_Driver/Src/stm32mp1xx_hal_cryp_ex.c']
path = [cwd + '/STM32MP1xx_HAL_Driver/Inc',
cwd + '/CMSIS/Device/ST/STM32MP1xx/Include',
cwd + '/CMSIS/Core/Include',

View File

@ -3236,7 +3236,7 @@ uint32_t SD_HighSpeed(SD_HandleTypeDef *hsd)
{
SD_hs[(8U*loop)+count] = SDMMC_ReadFIFO(hsd->Instance);
}
loop += 8U;
loop ++;
}
if((HAL_GetTick()-Timeout) >= SDMMC_DATATIMEOUT)
@ -3351,7 +3351,7 @@ uint32_t SD_UltraHighSpeed(SD_HandleTypeDef *hsd)
{
SD_hs[(8U*loop)+count] = SDMMC_ReadFIFO(hsd->Instance);
}
loop += 8U;
loop ++;
}
if((HAL_GetTick()-Timeout) >= SDMMC_DATATIMEOUT)

View File

@ -123,6 +123,7 @@ CONFIG_RT_SERIAL_RB_BUFSZ=64
# CONFIG_RT_USING_HWTIMER is not set
# CONFIG_RT_USING_CPUTIME is not set
# CONFIG_RT_USING_I2C is not set
# CONFIG_RT_USING_PHY is not set
CONFIG_RT_USING_PIN=y
# CONFIG_RT_USING_ADC is not set
# CONFIG_RT_USING_DAC is not set
@ -199,12 +200,15 @@ CONFIG_RT_USING_PIN=y
#
# IoT - internet of things
#
# CONFIG_PKG_USING_LORAWAN_DRIVER is not set
# CONFIG_PKG_USING_PAHOMQTT is not set
# CONFIG_PKG_USING_UMQTT is not set
# CONFIG_PKG_USING_WEBCLIENT is not set
# CONFIG_PKG_USING_WEBNET is not set
# CONFIG_PKG_USING_MONGOOSE is not set
# CONFIG_PKG_USING_MYMQTT is not set
# CONFIG_PKG_USING_KAWAII_MQTT is not set
# CONFIG_PKG_USING_BC28_MQTT is not set
# CONFIG_PKG_USING_WEBTERMINAL is not set
# CONFIG_PKG_USING_CJSON is not set
# CONFIG_PKG_USING_JSMN is not set
@ -231,6 +235,7 @@ CONFIG_RT_USING_PIN=y
# CONFIG_PKG_USING_COAP is not set
# CONFIG_PKG_USING_NOPOLL is not set
# CONFIG_PKG_USING_NETUTILS is not set
# CONFIG_PKG_USING_CMUX is not set
# CONFIG_PKG_USING_PPP_DEVICE is not set
# CONFIG_PKG_USING_AT_DEVICE is not set
# CONFIG_PKG_USING_ATSRV_SOCKET is not set
@ -243,7 +248,7 @@ CONFIG_RT_USING_PIN=y
# CONFIG_PKG_USING_GAGENT_CLOUD is not set
# CONFIG_PKG_USING_ALI_IOTKIT is not set
# CONFIG_PKG_USING_AZURE is not set
# CONFIG_PKG_USING_TENCENT_IOTHUB is not set
# CONFIG_PKG_USING_TENCENT_IOT_EXPLORER is not set
# CONFIG_PKG_USING_JIOT-C-SDK is not set
# CONFIG_PKG_USING_UCLOUD_IOT_SDK is not set
# CONFIG_PKG_USING_JOYLINK is not set
@ -265,6 +270,11 @@ CONFIG_RT_USING_PIN=y
# CONFIG_PKG_USING_CAPNP is not set
# CONFIG_PKG_USING_RT_CJSON_TOOLS is not set
# CONFIG_PKG_USING_AGILE_TELNET is not set
# CONFIG_PKG_USING_NMEALIB is not set
# CONFIG_PKG_USING_AGILE_JSMN is not set
# CONFIG_PKG_USING_PDULIB is not set
# CONFIG_PKG_USING_BTSTACK is not set
# CONFIG_PKG_USING_LORAWAN_ED_STACK is not set
#
# security packages
@ -273,6 +283,7 @@ CONFIG_RT_USING_PIN=y
# CONFIG_PKG_USING_libsodium is not set
# CONFIG_PKG_USING_TINYCRYPT is not set
# CONFIG_PKG_USING_TFM is not set
# CONFIG_PKG_USING_YD_CRYPTO is not set
#
# language packages
@ -289,6 +300,8 @@ CONFIG_RT_USING_PIN=y
# CONFIG_PKG_USING_STEMWIN is not set
# CONFIG_PKG_USING_WAVPLAYER is not set
# CONFIG_PKG_USING_TJPGD is not set
# CONFIG_PKG_USING_HELIX is not set
# CONFIG_PKG_USING_AZUREGUIX is not set
#
# tools packages
@ -307,6 +320,9 @@ CONFIG_RT_USING_PIN=y
# CONFIG_PKG_USING_CHINESE_FONT_LIBRARY is not set
# CONFIG_PKG_USING_LUNAR_CALENDAR is not set
# CONFIG_PKG_USING_BS8116A is not set
# CONFIG_PKG_USING_GPS_RMC is not set
# CONFIG_PKG_USING_URLENCODE is not set
# CONFIG_PKG_USING_UMCN is not set
#
# system packages
@ -318,6 +334,7 @@ CONFIG_RT_USING_PIN=y
# CONFIG_PKG_USING_LWEXT4 is not set
# CONFIG_PKG_USING_PARTITION is not set
# CONFIG_PKG_USING_FAL is not set
# CONFIG_PKG_USING_FLASHDB is not set
# CONFIG_PKG_USING_SQLITE is not set
# CONFIG_PKG_USING_RTI is not set
# CONFIG_PKG_USING_LITTLEVGL2RTT is not set
@ -330,6 +347,19 @@ CONFIG_RT_USING_PIN=y
# CONFIG_PKG_USING_SYSWATCH is not set
# CONFIG_PKG_USING_SYS_LOAD_MONITOR is not set
# CONFIG_PKG_USING_PLCCORE is not set
# CONFIG_PKG_USING_RAMDISK is not set
# CONFIG_PKG_USING_MININI is not set
# CONFIG_PKG_USING_QBOOT is not set
#
# Micrium: Micrium software products porting for RT-Thread
#
# CONFIG_PKG_USING_UCOSIII_WRAPPER is not set
# CONFIG_PKG_USING_UC_CRC is not set
# CONFIG_PKG_USING_UC_CLK is not set
# CONFIG_PKG_USING_UC_COMMON is not set
# CONFIG_PKG_USING_UC_MODBUS is not set
# CONFIG_PKG_USING_PPOOL is not set
#
# peripheral libraries and drivers
@ -367,6 +397,7 @@ CONFIG_RT_USING_PIN=y
# CONFIG_PKG_USING_RPLIDAR is not set
# CONFIG_PKG_USING_AS608 is not set
# CONFIG_PKG_USING_RC522 is not set
# CONFIG_PKG_USING_WS2812B is not set
# CONFIG_PKG_USING_EMBARC_BSP is not set
# CONFIG_PKG_USING_EXTERN_RTC_DRIVERS is not set
# CONFIG_PKG_USING_MULTI_RTIMER is not set
@ -374,6 +405,17 @@ CONFIG_RT_USING_PIN=y
# CONFIG_PKG_USING_BEEP is not set
# CONFIG_PKG_USING_EASYBLINK is not set
# CONFIG_PKG_USING_PMS_SERIES is not set
# CONFIG_PKG_USING_CAN_YMODEM is not set
# CONFIG_PKG_USING_LORA_RADIO_DRIVER is not set
# CONFIG_PKG_USING_QLED is not set
# CONFIG_PKG_USING_PAJ7620 is not set
# CONFIG_PKG_USING_AGILE_CONSOLE is not set
# CONFIG_PKG_USING_LD3320 is not set
# CONFIG_PKG_USING_WK2124 is not set
# CONFIG_PKG_USING_LY68L6400 is not set
# CONFIG_PKG_USING_DM9051 is not set
# CONFIG_PKG_USING_SSD1306 is not set
# CONFIG_PKG_USING_QKEY is not set
#
# miscellaneous packages
@ -403,13 +445,20 @@ CONFIG_RT_USING_PIN=y
# CONFIG_PKG_USING_PERIPHERAL_SAMPLES is not set
# CONFIG_PKG_USING_HELLO is not set
# CONFIG_PKG_USING_VI is not set
# CONFIG_PKG_USING_KI is not set
# CONFIG_PKG_USING_NNOM is not set
# CONFIG_PKG_USING_LIBANN is not set
# CONFIG_PKG_USING_ELAPACK is not set
# CONFIG_PKG_USING_ARMv7M_DWT is not set
# CONFIG_PKG_USING_VT100 is not set
# CONFIG_PKG_USING_TETRIS is not set
# CONFIG_PKG_USING_ULAPACK is not set
# CONFIG_PKG_USING_UKAL is not set
# CONFIG_PKG_USING_CRCLIB is not set
# CONFIG_PKG_USING_THREES is not set
# CONFIG_PKG_USING_2048 is not set
# CONFIG_PKG_USING_LWGPS is not set
# CONFIG_PKG_USING_TENSORFLOWLITEMICRO is not set
CONFIG_SOC_FAMILY_STM32=y
CONFIG_SOC_SERIES_STM32MP1=y
@ -427,6 +476,10 @@ CONFIG_BSP_USING_STLINK_TO_USART=y
# CONFIG_BSP_USING_PWR is not set
# CONFIG_BSP_USING_RCC is not set
# CONFIG_BSP_USING_OPENAMP is not set
# CONFIG_BSP_USING_RS485 is not set
# CONFIG_BSP_USING_GBE is not set
# CONFIG_BSP_USING_SDMMC is not set
# CONFIG_BSP_USING_AUDIO is not set
#
# On-chip Peripheral Drivers
@ -435,7 +488,6 @@ CONFIG_BSP_USING_GPIO=y
# CONFIG_BSP_USING_WWDG is not set
CONFIG_BSP_USING_UART=y
# CONFIG_BSP_USING_UART3 is not set
# CONFIG_BSP_UART3_RX_USING_DMA is not set
CONFIG_BSP_USING_UART4=y
# CONFIG_BSP_UART4_RX_USING_DMA is not set
# CONFIG_BSP_UART4_TX_USING_DMA is not set
@ -448,6 +500,8 @@ CONFIG_BSP_USING_UART4=y
# CONFIG_BSP_USING_SPI is not set
# CONFIG_BSP_USING_CRC is not set
# CONFIG_BSP_USING_RNG is not set
# CONFIG_BSP_USING_HASH is not set
# CONFIG_BSP_USING_CRYP is not set
# CONFIG_BSP_USING_UDID is not set
#

View File

@ -34,8 +34,8 @@
#define HAL_MODULE_ENABLED
#define HAL_ADC_MODULE_ENABLED
/*#define HAL_CEC_MODULE_ENABLED */
/*#define HAL_CRC_MODULE_ENABLED */
/*#define HAL_CRYP_MODULE_ENABLED */
#define HAL_CRC_MODULE_ENABLED
#define HAL_CRYP_MODULE_ENABLED
#define HAL_DAC_MODULE_ENABLED
/*#define HAL_DCMI_MODULE_ENABLED */
/*#define HAL_DSI_MODULE_ENABLED */
@ -43,7 +43,7 @@
/*#define HAL_DTS_MODULE_ENABLED */
/*#define HAL_ETH_MODULE_ENABLED */
/*#define HAL_FDCAN_MODULE_ENABLED */
/*#define HAL_HASH_MODULE_ENABLED */
#define HAL_HASH_MODULE_ENABLED
/*#define HAL_HCD_MODULE_ENABLED */
#define HAL_HSEM_MODULE_ENABLED
#define HAL_I2C_MODULE_ENABLED
@ -56,9 +56,9 @@
/*#define HAL_NOR_MODULE_ENABLED */
/*#define HAL_PCD_MODULE_ENABLED */
/*#define HAL_QSPI_MODULE_ENABLED */
/*#define HAL_RNG_MODULE_ENABLED */
/*#define HAL_SAI_MODULE_ENABLED */
/*#define HAL_SD_MODULE_ENABLED */
#define HAL_RNG_MODULE_ENABLED
#define HAL_SAI_MODULE_ENABLED
#define HAL_SD_MODULE_ENABLED
/*#define HAL_MMC_MODULE_ENABLED */
/*#define HAL_RTC_MODULE_ENABLED */
/*#define HAL_SMBUS_MODULE_ENABLED */

View File

@ -26,7 +26,9 @@
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
DMA_HandleTypeDef hdma_hash_in = {0};
DMA_HandleTypeDef hdma_cryp_in = {0};
DMA_HandleTypeDef hdma_cryp_out = {0};
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
@ -58,8 +60,7 @@
/* USER CODE END 0 */
void HAL_TIM_MspPostInit(TIM_HandleTypeDef *htim);
/**
/**
* Initializes the Global MSP.
*/
void HAL_MspInit(void)
@ -942,6 +943,107 @@ void HAL_I2C_MspInit(I2C_HandleTypeDef *hI2c)
}
}
/**
* @brief SD MSP Initialization
* This function configures the hardware resources used in this example
* @param hsd: SD handle pointer
* @retval None
*/
void HAL_SD_MspInit(SD_HandleTypeDef* hsd)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
if(hsd->Instance==SDMMC1)
{
/* USER CODE BEGIN SDMMC1_MspInit 0 */
if (IS_ENGINEERING_BOOT_MODE())
{
/** Initializes the peripherals clock
*/
PeriphClkInit.Sdmmc12ClockSelection = RCC_SDMMC12CLKSOURCE_PLL4;
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_SDMMC12;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
/* USER CODE END SDMMC1_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_SDMMC1_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
/**SDMMC1 GPIO Configuration
PC8 ------> SDMMC1_D0
PC9 ------> SDMMC1_D1
PC10 ------> SDMMC1_D2
PC11 ------> SDMMC1_D3
PC12 ------> SDMMC1_CK
PD2 ------> SDMMC1_CMD
*/
GPIO_InitStruct.Pin = GPIO_PIN_8|GPIO_PIN_9|GPIO_PIN_10|GPIO_PIN_11
|GPIO_PIN_12;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF12_SDIO1;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_2;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
__HAL_RCC_SDMMC1_FORCE_RESET();
__HAL_RCC_SDMMC1_RELEASE_RESET();
/* SDMMC1 interrupt Init */
HAL_NVIC_SetPriority(SDMMC1_IRQn, 2, 0);
HAL_NVIC_EnableIRQ(SDMMC1_IRQn);
/* USER CODE BEGIN SDMMC1_MspInit 1 */
/* USER CODE END SDMMC1_MspInit 1 */
}
}
/**
* @brief SD MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param hsd: SD handle pointer
* @retval None
*/
void HAL_SD_MspDeInit(SD_HandleTypeDef* hsd)
{
if(hsd->Instance==SDMMC1)
{
/* USER CODE BEGIN SDMMC1_MspDeInit 0 */
/* USER CODE END SDMMC1_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_SDMMC1_CLK_DISABLE();
/**SDMMC1 GPIO Configuration
PC8 ------> SDMMC1_D0
PC9 ------> SDMMC1_D1
PC10 ------> SDMMC1_D2
PC11 ------> SDMMC1_D3
PC12 ------> SDMMC1_CK
PD2 ------> SDMMC1_CMD
*/
HAL_GPIO_DeInit(GPIOC, GPIO_PIN_8|GPIO_PIN_9|GPIO_PIN_10|GPIO_PIN_11
|GPIO_PIN_12);
HAL_GPIO_DeInit(GPIOD, GPIO_PIN_2);
/* SDMMC1 interrupt DeInit */
HAL_NVIC_DisableIRQ(SDMMC1_IRQn);
/* USER CODE BEGIN SDMMC1_MspDeInit 1 */
/* USER CODE END SDMMC1_MspDeInit 1 */
}
}
/**
* @brief DeInitializes I2C MSP.
* @param hI2c : I2C handler
@ -966,6 +1068,250 @@ void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hI2c)
}
}
/**
* @brief CRC MSP Initialization
* This function configures the hardware resources used in this example
* @param hcrc: CRC handle pointer
* @retval None
*/
void HAL_CRC_MspInit(CRC_HandleTypeDef* hcrc)
{
if(hcrc->Instance==CRC2)
{
/* USER CODE BEGIN CRC2_MspInit 0 */
/* USER CODE END CRC2_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_CRC2_CLK_ENABLE();
/* USER CODE BEGIN CRC2_MspInit 1 */
/* USER CODE END CRC2_MspInit 1 */
}
}
/**
* @brief CRC MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param hcrc: CRC handle pointer
* @retval None
*/
void HAL_CRC_MspDeInit(CRC_HandleTypeDef* hcrc)
{
if(hcrc->Instance==CRC2)
{
/* USER CODE BEGIN CRC2_MspDeInit 0 */
/* USER CODE END CRC2_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_CRC2_CLK_DISABLE();
/* USER CODE BEGIN CRC2_MspDeInit 1 */
/* USER CODE END CRC2_MspDeInit 1 */
}
}
/**
* @brief RNG MSP Initialization
* This function configures the hardware resources used in this example
* @param hrng: RNG handle pointer
* @retval None
*/
void HAL_RNG_MspInit(RNG_HandleTypeDef* hrng)
{
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
if(hrng->Instance==RNG2)
{
/* USER CODE BEGIN RNG2_MspInit 0 */
/* USER CODE END RNG2_MspInit 0 */
if(IS_ENGINEERING_BOOT_MODE())
{
/** Initializes the peripherals clock
*/
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_RNG2;
PeriphClkInit.Rng2ClockSelection = RCC_RNG2CLKSOURCE_CSI;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
/* Peripheral clock enable */
__HAL_RCC_RNG2_CLK_ENABLE();
/* USER CODE BEGIN RNG2_MspInit 1 */
/* USER CODE END RNG2_MspInit 1 */
}
}
/**
* @brief RNG MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param hrng: RNG handle pointer
* @retval None
*/
void HAL_RNG_MspDeInit(RNG_HandleTypeDef* hrng)
{
if(hrng->Instance==RNG2)
{
/* USER CODE BEGIN RNG2_MspDeInit 0 */
/* USER CODE END RNG2_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_RNG2_CLK_DISABLE();
/* USER CODE BEGIN RNG2_MspDeInit 1 */
/* USER CODE END RNG2_MspDeInit 1 */
}
}
/**
* @brief HASH MSP Initialization
* This function configures the hardware resources used in this example
* @param hhash: HASH handle pointer
* @retval None
*/
void HAL_HASH_MspInit(HASH_HandleTypeDef* hhash)
{
/* USER CODE BEGIN HASH2_MspInit 0 */
/* USER CODE END HASH2_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_HASH2_CLK_ENABLE();
/* USER CODE BEGIN HASH2_MspInit 1 */
__HAL_RCC_DMAMUX_CLK_ENABLE();
/* Peripheral DMA init*/
hdma_hash_in.Instance = DMA2_Stream7;
hdma_hash_in.Init.Request = DMA_REQUEST_HASH2_IN;
hdma_hash_in.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_hash_in.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_hash_in.Init.MemInc = DMA_MINC_ENABLE;
hdma_hash_in.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
hdma_hash_in.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;
hdma_hash_in.Init.Mode = DMA_NORMAL;
hdma_hash_in.Init.Priority = DMA_PRIORITY_HIGH;
hdma_hash_in.Init.FIFOMode = DMA_FIFOMODE_ENABLE;
hdma_hash_in.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_HALFFULL;
hdma_hash_in.Init.MemBurst = DMA_MBURST_SINGLE;
hdma_hash_in.Init.PeriphBurst = DMA_PBURST_SINGLE;
if (HAL_DMA_DeInit(&hdma_hash_in) != HAL_OK)
{
Error_Handler();
}
if (HAL_DMA_Init(&hdma_hash_in) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(hhash,hdmain,hdma_hash_in);
/* USER CODE END HASH2_MspInit 1 */
}
/**
* @brief HASH MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param hhash: HASH handle pointer
* @retval None
*/
void HAL_HASH_MspDeInit(HASH_HandleTypeDef* hhash)
{
/* USER CODE BEGIN HASH2_MspDeInit 0 */
/* USER CODE END HASH2_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_HASH2_CLK_DISABLE();
/* USER CODE BEGIN HASH2_MspDeInit 1 */
/* USER CODE END HASH2_MspDeInit 1 */
}
#if defined (CRYP1) || defined (CRYP2)
void HAL_CRYP_MspInit(CRYP_HandleTypeDef* hcryp)
{
if(hcryp->Instance==CRYP2)
{
/* Peripheral clock enable */
__HAL_RCC_CRYP2_CLK_ENABLE();
__HAL_RCC_DMAMUX_CLK_ENABLE();
/* Peripheral DMA init*/
hdma_cryp_in.Instance = DMA2_Stream6;
hdma_cryp_in.Init.Request = DMA_REQUEST_CRYP2_IN;
hdma_cryp_in.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_cryp_in.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_cryp_in.Init.MemInc = DMA_MINC_ENABLE;
hdma_cryp_in.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
hdma_cryp_in.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;
hdma_cryp_in.Init.Mode = DMA_NORMAL;
hdma_cryp_in.Init.Priority = DMA_PRIORITY_HIGH;
hdma_cryp_in.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
if (HAL_DMA_DeInit(&hdma_cryp_in) != HAL_OK)
{
Error_Handler();
}
if (HAL_DMA_Init(&hdma_cryp_in) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(hcryp,hdmain,hdma_cryp_in);
hdma_cryp_out.Instance = DMA2_Stream5;
hdma_cryp_out.Init.Request = DMA_REQUEST_CRYP2_OUT;
hdma_cryp_out.Init.Direction = DMA_PERIPH_TO_MEMORY;
hdma_cryp_out.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_cryp_out.Init.MemInc = DMA_MINC_ENABLE;
hdma_cryp_out.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
hdma_cryp_out.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;
hdma_cryp_out.Init.Mode = DMA_NORMAL;
hdma_cryp_out.Init.Priority = DMA_PRIORITY_VERY_HIGH;
hdma_cryp_out.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
if (HAL_DMA_DeInit(&hdma_cryp_out) != HAL_OK)
{
Error_Handler();
}
if (HAL_DMA_Init(&hdma_cryp_out) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(hcryp,hdmaout,hdma_cryp_out);
/* USER CODE BEGIN CRYP_MspInit 1 */
/* USER CODE END CRYP_MspInit 1 */
}
}
void HAL_CRYP_MspDeInit(CRYP_HandleTypeDef* hcryp)
{
if(hcryp->Instance==CRYP2)
{
/* USER CODE BEGIN CRYP_MspDeInit 0 */
/* USER CODE END CRYP_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_CRYP2_CLK_DISABLE();
/* Peripheral DMA DeInit*/
HAL_DMA_DeInit(hcryp->hdmain);
HAL_DMA_DeInit(hcryp->hdmaout);
}
/* USER CODE BEGIN CRYP_MspDeInit 1 */
/* USER CODE END CRYP_MspDeInit 1 */
}
#endif
/**
* @brief This function is executed in case of error occurrence.
* @retval None

View File

@ -50,7 +50,37 @@ menu "Onboard Peripheral Drivers"
config RS485_UART_DEVICE_NAME
string "the uart name for rs485"
default "uart3"
endif
config BSP_USING_GBE
bool "Enable Ethernet"
default n
select RT_USING_LWIP
config BSP_USING_SDMMC
bool "Enable SDMMC (SD card)"
select RT_USING_SDIO
select RT_USING_DFS
select RT_USING_DFS_ELMFAT
default n
menuconfig BSP_USING_AUDIO
bool "Enable Audio Device"
select RT_USING_AUDIO
select BSP_USING_PMIC
select BSP_USING_SDMMC
select BSP_USING_I2C
select BSP_USING_I2C4
default n
if BSP_USING_AUDIO
config BSP_USING_AUDIO_PLAY
bool "Enable Audio Play"
default y
config BSP_USING_AUDIO_RECORD
bool "Enable Audio Record"
default n
endif
endmenu
@ -196,7 +226,7 @@ menu "On-chip Peripheral Drivers"
range 1 176
default 117
endif
menuconfig BSP_USING_I2C3
menuconfig BSP_USING_I2C3
bool "Enable I2C3 BUS (software simulation)"
default n
if BSP_USING_I2C3
@ -210,6 +240,21 @@ menu "On-chip Peripheral Drivers"
range 1 191
default 181
endif
menuconfig BSP_USING_I2C4
bool "Enable I2C4 BUS (software simulation)"
default n
if BSP_USING_I2C4
comment "Notice: PD12 --> 60; PF15 --> 95"
config BSP_I2C4_SCL_PIN
int "i2c4 scl pin number"
range 1 191
default 60
config BSP_I2C4_SDA_PIN
int "I2C4 sda pin number"
range 1 191
default 95
endif
endif
menuconfig BSP_USING_SPI

View File

@ -40,6 +40,23 @@ if GetDepend(['BSP_USING_PMIC']):
if GetDepend(['BSP_USING_RS485']):
src += Glob('ports/drv_rs485.c')
if GetDepend(['BSP_USING_GBE']):
src += Glob('ports/drv_eth.c')
if GetDepend(['BSP_USING_SDMMC']):
src += Glob('ports/drv_sdio.c')
if GetDepend(['BSP_USING_AUDIO']):
src += Glob('ports/audio/drv_cs42l51.c')
src += Glob('ports/audio/drv_sound.c')
src += Glob('ports/audio/audio_play.c')
if GetDepend(['BSP_USING_AUDIO_RECORD']):
src += Glob('ports/audio/drv_mic.c')
if GetDepend(['(BSP_USING_RNG)']) or GetDepend(['(BSP_USING_HASH)']) or GetDepend(['(BSP_USING_CRC)']) or GetDepend(['BSP_USING_CRYP']):
src += Glob('ports/crypto/crypto_sample.c')
if GetDepend(['BSP_USING_OPENAMP']):
src += Glob('CubeMX_Config/CM4/Src/ipcc.c')
src += Glob('CubeMX_Config/CM4/Src/openamp.c')
@ -58,6 +75,7 @@ if GetDepend(['BSP_USING_OPENAMP']):
path = [cwd]
path += [cwd + '/CubeMX_Config/CM4/Inc']
path += [cwd + '/ports']
path += [cwd + '/ports/audio']
if GetDepend(['BSP_USING_OPENAMP']):
path += [cwd + '/ports/OpenAMP']

View File

@ -32,7 +32,7 @@ extern "C" {
#if defined(BSP_USING_OPENAMP)
#define STM32_SRAM_BEGIN (uint32_t)0x10020000
#define STM32_SRAM_BEGIN (uint32_t)0x10030000
#else
#define STM32_SRAM_BEGIN (uint32_t)0x2FFF0000
#endif
@ -42,8 +42,6 @@ extern "C" {
#define HEAP_BEGIN STM32_SRAM_BEGIN
#define HEAP_END STM32_SRAM_END
#define HEAP_END STM32_SRAM_END
void SystemClock_Config(void);
extern void _Error_Handler(char *s, int num);

View File

@ -5,7 +5,7 @@
define symbol __ICFEDIT_intvec_start__ = 0x00000000;
/*-Memory Regions-*/
define symbol __ICFEDIT_region_text_start__ = 0x10000000;
define symbol __ICFEDIT_region_text_end__ = 0x1001FFFF;
define symbol __ICFEDIT_region_text_end__ = 0x1002FFFF;
define symbol __ICFEDIT_region_data_start__ = 0x10030000;
define symbol __ICFEDIT_region_data_end__ = 0x1003FFFF;
/*-Sizes-*/
@ -27,11 +27,6 @@ define symbol __OPENAMP_region_size__ = 0x8000;
export symbol __OPENAMP_region_start__;
export symbol __OPENAMP_region_size__;
define symbol __SDMMC_region_start__ = 0x10048000;
define symbol __SDMMC_region_size__ = 0x1FFFF;
export symbol __SDMMC_region_start__;
export symbol __SDMMC_region_size__;
define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { };
define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { };

View File

@ -0,0 +1,258 @@
/*
* Copyright (c) 2006-2022, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2020-11-24 thread-liu first version
*/
#include <rtthread.h>
#include <rtdevice.h>
#include <dfs_posix.h>
#if defined(BSP_USING_AUDIO) && defined(BSP_USING_SDMMC)
#define BUFSZ 1024
#define SOUND_DEVICE_NAME "sound0"
static rt_device_t snd_dev;
struct RIFF_HEADER_DEF
{
char riff_id[4]; // 'R','I','F','F'
uint32_t riff_size;
char riff_format[4]; // 'W','A','V','E'
};
struct WAVE_FORMAT_DEF
{
uint16_t FormatTag;
uint16_t Channels;
uint32_t SamplesPerSec;
uint32_t AvgBytesPerSec;
uint16_t BlockAlign;
uint16_t BitsPerSample;
};
struct FMT_BLOCK_DEF
{
char fmt_id[4]; // 'f','m','t',' '
uint32_t fmt_size;
struct WAVE_FORMAT_DEF wav_format;
};
struct DATA_BLOCK_DEF
{
char data_id[4]; // 'R','I','F','F'
uint32_t data_size;
};
struct wav_info
{
struct RIFF_HEADER_DEF header;
struct FMT_BLOCK_DEF fmt_block;
struct DATA_BLOCK_DEF data_block;
};
int wavplay_sample(int argc, char **argv)
{
int fd = -1;
uint8_t *buffer = NULL;
struct wav_info *info = NULL;
struct rt_audio_caps caps = {0};
if (argc != 2)
{
rt_kprintf("Usage:\n");
rt_kprintf("wavplay_sample song.wav\n");
return 0;
}
fd = open(argv[1], O_WRONLY);
if (fd < 0)
{
rt_kprintf("open file failed!\n");
goto __exit;
}
buffer = rt_malloc(BUFSZ);
if (buffer == RT_NULL)
goto __exit;
info = (struct wav_info *) rt_malloc(sizeof * info);
if (info == RT_NULL)
goto __exit;
if (read(fd, &(info->header), sizeof(struct RIFF_HEADER_DEF)) <= 0)
goto __exit;
if (read(fd, &(info->fmt_block), sizeof(struct FMT_BLOCK_DEF)) <= 0)
goto __exit;
if (read(fd, &(info->data_block), sizeof(struct DATA_BLOCK_DEF)) <= 0)
goto __exit;
rt_kprintf("wav information:\n");
rt_kprintf("samplerate %d\n", info->fmt_block.wav_format.SamplesPerSec);
rt_kprintf("channel %d\n", info->fmt_block.wav_format.Channels);
snd_dev = rt_device_find(SOUND_DEVICE_NAME);
rt_device_open(snd_dev, RT_DEVICE_OFLAG_WRONLY);
caps.main_type = AUDIO_TYPE_OUTPUT;
caps.sub_type = AUDIO_DSP_PARAM;
caps.udata.config.samplerate = info->fmt_block.wav_format.SamplesPerSec;
caps.udata.config.channels = info->fmt_block.wav_format.Channels;
caps.udata.config.samplebits = 16;
rt_device_control(snd_dev, AUDIO_CTL_CONFIGURE, &caps);
while (1)
{
int length;
length = read(fd, buffer, BUFSZ);
if (length <= 0)
break;
rt_device_write(snd_dev, 0, buffer, length);
}
rt_device_close(snd_dev);
__exit:
if (fd >= 0)
close(fd);
if (buffer)
rt_free(buffer);
if (info)
rt_free(info);
return 0;
}
MSH_CMD_EXPORT(wavplay_sample, play wav file);
#endif
#if defined(BSP_USING_AUDIO) && defined(BSP_USING_SDMMC) && defined(BSP_USING_AUDIO_RECORD)
#define RECORD_TIME_MS 5000
#define RECORD_SAMPLERATE 16000
#define RECORD_CHANNEL 2
#define RECORD_CHUNK_SZ ((RECORD_SAMPLERATE * RECORD_CHANNEL * 2) * 20 / 1000)
#define MIC_DEVICE_NAME "mic0"
static rt_device_t mic_dev;
struct wav_header
{
char riff_id[4]; /* "RIFF" */
int riff_datasize; /* RIFF chunk data size,exclude riff_id[4] and riff_datasize,total - 8 */
char riff_type[4]; /* "WAVE" */
char fmt_id[4]; /* "fmt " */
int fmt_datasize; /* fmt chunk data size,16 for pcm */
short fmt_compression_code; /* 1 for PCM */
short fmt_channels; /* 1(mono) or 2(stereo) */
int fmt_sample_rate; /* samples per second */
int fmt_avg_bytes_per_sec; /* sample_rate * channels * bit_per_sample / 8 */
short fmt_block_align; /* number bytes per sample, bit_per_sample * channels / 8 */
short fmt_bit_per_sample; /* bits of each sample(8,16,32). */
char data_id[4]; /* "data" */
int data_datasize; /* data chunk size,pcm_size - 44 */
};
static void wavheader_init(struct wav_header *header, int sample_rate, int channels, int datasize)
{
memcpy(header->riff_id, "RIFF", 4);
header->riff_datasize = datasize + 44 - 8;
memcpy(header->riff_type, "WAVE", 4);
memcpy(header->fmt_id, "fmt ", 4);
header->fmt_datasize = 16;
header->fmt_compression_code = 1;
header->fmt_channels = channels;
header->fmt_sample_rate = sample_rate;
header->fmt_bit_per_sample = 16;
header->fmt_avg_bytes_per_sec = header->fmt_sample_rate * header->fmt_channels * header->fmt_bit_per_sample / 8;
header->fmt_block_align = header->fmt_bit_per_sample * header->fmt_channels / 8;
memcpy(header->data_id, "data", 4);
header->data_datasize = datasize;
}
int wavrecord_sample(int argc, char **argv)
{
int fd = -1;
uint8_t *buffer = NULL;
struct wav_header header;
struct rt_audio_caps caps = {0};
int length, total_length = 0;
if (argc != 2)
{
rt_kprintf("Usage:\n");
rt_kprintf("wavrecord_sample file.wav\n");
return -1;
}
fd = open(argv[1], O_WRONLY | O_CREAT);
if (fd < 0)
{
rt_kprintf("open file for recording failed!\n");
return -1;
}
write(fd, &header, sizeof(struct wav_header));
buffer = rt_malloc(RECORD_CHUNK_SZ);
if (buffer == RT_NULL)
goto __exit;
mic_dev = rt_device_find(MIC_DEVICE_NAME);
if (mic_dev == RT_NULL)
goto __exit;
rt_device_open(mic_dev, RT_DEVICE_OFLAG_RDONLY);
caps.main_type = AUDIO_TYPE_INPUT;
caps.sub_type = AUDIO_DSP_PARAM;
caps.udata.config.samplerate = RECORD_SAMPLERATE;
caps.udata.config.channels = RECORD_CHANNEL;
caps.udata.config.samplebits = 16;
rt_device_control(mic_dev, AUDIO_CTL_CONFIGURE, &caps);
while (1)
{
length = rt_device_read(mic_dev, 0, buffer, RECORD_CHUNK_SZ);
if (length)
{
write(fd, buffer, length);
total_length += length;
}
if ((total_length / RECORD_CHUNK_SZ) > (RECORD_TIME_MS / 20))
break;
}
/* write wav file head */
wavheader_init(&header, RECORD_SAMPLERATE, RECORD_CHANNEL, total_length);
lseek(fd, 0, SEEK_SET);
write(fd, &header, sizeof(struct wav_header));
close(fd);
/* close audio mic device */
rt_device_close(mic_dev);
__exit:
if (fd >= 0)
close(fd);
if (buffer)
rt_free(buffer);
return 0;
}
MSH_CMD_EXPORT(wavrecord_sample, record voice to a wav file);
#endif

View File

@ -0,0 +1,531 @@
/*
* Copyright (c) 2006-2020, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2020-07-02 thread-liu first version
*/
#include "board.h"
#if defined(BSP_USING_AUDIO)
#include <drv_cs42l51.h>
#define DRV_DEBUG
#define LOG_TAG "drv.audio"
#include <drv_log.h>
/* CS42L51 address */
#define CHIP_ADDRESS 0x4A
/* reset pin, active low */
#define CS42L51_RESET_PIN GET_PIN(G, 9)
static uint16_t CS42L51_Device = OUT_HEADPHONE;
static struct rt_i2c_bus_device *audio_dev = RT_NULL;
/* i2c read reg */
static rt_err_t read_reg(struct rt_i2c_bus_device *bus, rt_uint8_t reg, rt_uint8_t len, rt_uint8_t *buf)
{
struct rt_i2c_msg msg[2] = {0, 0};
RT_ASSERT(bus != RT_NULL);
msg[0].addr = CHIP_ADDRESS; /* Slave address */
msg[0].flags = RT_I2C_WR; /* Write flag */
msg[0].buf = &reg; /* Slave register address */
msg[0].len = 1; /* Number of bytes sent */
msg[1].addr = CHIP_ADDRESS;
msg[1].flags = RT_I2C_RD;
msg[1].len = len;
msg[1].buf = buf;
if (rt_i2c_transfer(bus, msg, 2) == 2)
{
return RT_EOK;
}
return RT_ERROR;
}
/* i2c write reg */
static rt_err_t write_reg(struct rt_i2c_bus_device *bus, rt_uint8_t reg, rt_uint8_t data)
{
rt_uint8_t buf[2];
struct rt_i2c_msg msgs;
RT_ASSERT(bus != RT_NULL);
buf[0] = reg;
buf[1] = data;
msgs.addr = CHIP_ADDRESS;
msgs.flags = RT_I2C_WR;
msgs.buf = buf;
msgs.len = 2;
if (rt_i2c_transfer(bus, &msgs, 1) == 1)
{
return RT_EOK;
}
return RT_ERROR;
}
/**
* @brief deinitializes cs42l51 low level.
* @retval none
*/
static void cs42l51_lowlevel_deinit(void)
{
rt_uint8_t temp = 0;
/* Mute DAC and ADC */
read_reg(audio_dev, CS42L51_DAC_OUT_CTL, 1, &temp);
write_reg(audio_dev, CS42L51_DAC_OUT_CTL, (temp | 0x03));
read_reg(audio_dev, CS42L51_ADC_INPUT, 1, &temp);
write_reg(audio_dev, CS42L51_ADC_INPUT, (temp | 0x03));
/* Disable soft ramp and zero cross */
read_reg(audio_dev, CS42L51_ADC_CTL, 1, &temp);
write_reg(audio_dev, CS42L51_ADC_CTL, (temp & 0xF0));
/* Set PDN to 1 */
read_reg(audio_dev, CS42L51_POWER_CTL1, 1, &temp);
write_reg(audio_dev, CS42L51_POWER_CTL1, (temp | 0x01));
/* Set all power down bits to 1 */
write_reg(audio_dev, CS42L51_POWER_CTL1, 0x7F);
read_reg(audio_dev, CS42L51_MIC_POWER_CTL, 1, &temp);
write_reg(audio_dev, CS42L51_MIC_POWER_CTL, (temp | 0x0E));
/* Power off the codec */
rt_pin_write(CS42L51_RESET_PIN, PIN_LOW);
}
/**
* @brief initializes cs42l51 low level.
* @retval none
*/
static void cs42l51_lowlevel_init(void)
{
rt_uint8_t temp = 0;
/* Initialized RESET IO */
rt_pin_mode(CS42L51_RESET_PIN, PIN_MODE_OUTPUT);
/* Power off the cs42l51 */
rt_pin_write(CS42L51_RESET_PIN, PIN_LOW);
/* wait until power supplies are stable */
rt_thread_mdelay(10);
/* Power on the cs42l51 */
rt_pin_write(CS42L51_RESET_PIN, PIN_HIGH);
/* Wait at least 500ns after reset */
rt_thread_mdelay(1);
/* Set the device in standby mode */
read_reg(audio_dev, CS42L51_POWER_CTL1, 1, &temp);
write_reg(audio_dev, CS42L51_POWER_CTL1, (temp | 0x01));
/* Set all power down bits to 1 */
write_reg(audio_dev, CS42L51_POWER_CTL1, 0x7F);
read_reg(audio_dev, CS42L51_MIC_POWER_CTL, 1, &temp);
write_reg(audio_dev, CS42L51_MIC_POWER_CTL, (temp | 0x0E));
}
/**
* @brief Initializes CS42L51.
* @param Device: Audio type.
* @param bus_name I2C device name.
* @param volume: Initial output volume level (from 0 (-100dB) to 100 (0dB)).
* @retval 0 if correct communication, else wrong communication
*/
static rt_err_t cs42l51_init(uint16_t device, const char *bus_name, uint8_t volume)
{
static uint8_t init_flag = 0;
rt_uint8_t temp = 0;
rt_uint8_t value = 0;
/* check if codec is already initialized */
if (init_flag == 0)
{
audio_dev = rt_i2c_bus_device_find(bus_name);
if (audio_dev == RT_NULL)
{
LOG_E("%s bus not found\n", bus_name);
return -RT_ERROR;
}
/* hard reset cs42l51 */
cs42l51_drv.reset();
/* Wait at least 500ns after reset */
rt_thread_mdelay(1);
/* Set the device in standby mode */
read_reg(audio_dev, CS42L51_POWER_CTL1, 1, &temp);
write_reg(audio_dev, CS42L51_POWER_CTL1, (temp | 0x01));
/* Set all power down bits to 1 */
write_reg(audio_dev, CS42L51_POWER_CTL1, 0x7F);
read_reg(audio_dev, CS42L51_MIC_POWER_CTL, 1, &temp);
write_reg(audio_dev, CS42L51_MIC_POWER_CTL, (temp | 0x0E));
init_flag = 1;
}
else
{
/* Set all power down bits to 1 exept PDN to mute ADCs and DACs*/
write_reg(audio_dev, CS42L51_POWER_CTL1, 0x7E);
read_reg(audio_dev, CS42L51_MIC_POWER_CTL, 1, &temp);
write_reg(audio_dev, CS42L51_MIC_POWER_CTL, (temp | 0x0E));
/* Disable zero cross and soft ramp */
read_reg(audio_dev, CS42L51_DAC_CTL, 1, &temp);
write_reg(audio_dev, CS42L51_DAC_CTL, (temp & 0xFC));
/* Power control : Enter standby (PDN = 1) */
read_reg(audio_dev, CS42L51_POWER_CTL1, 1, &temp);
write_reg(audio_dev, CS42L51_POWER_CTL1, (temp | 0x01));
}
/* Mic Power and Speed Control : Auto detect on, Speed mode SSM, tri state off, MCLK divide by 2 off */
read_reg(audio_dev, CS42L51_MIC_POWER_CTL, 1, &temp);
write_reg(audio_dev, CS42L51_MIC_POWER_CTL, ((temp & 0x0E) | 0xA0));
/* Interface control : Loopback off, Slave, I2S (SDIN and SOUT), Digital mix off, Mic mix off */
write_reg(audio_dev, CS42L51_INTF_CTL, 0x0C);
/* Mic control : ADC single volume off, ADCB boost off, ADCA boost off, MicBias on AIN3B/MICIN2 pin, MicBias level 0.8xVA, MICB boost 16db, MICA boost 16dB */
write_reg(audio_dev, CS42L51_MIC_CTL, 0x00);
/* ADC control : ADCB HPF off, ADCB HPF freeze off, ADCA HPF off, ADCA HPF freeze off, Soft ramp B off, Zero cross B off, Soft ramp A off, Zero cross A off */
write_reg(audio_dev, CS42L51_ADC_CTL, 0x00);
/* ADC Input Select, Invert and Mute : AIN1B to PGAB, AIN3A to PreAmp to PGAA, ADCB invert off, ADCA invert off, ADCB mute on, ADCA mute off */
write_reg(audio_dev, CS42L51_ADC_INPUT, 0x32);
/* DAC output control : HP Gain to 1, Single volume control off, PCM invert signals polarity off, DAC channels mute on */
write_reg(audio_dev, CS42L51_DAC_OUT_CTL, 0xC3);
/* DAC control : Signal processing to DAC, Freeze off, De-emphasis off, Analog output auto mute off, DAC soft ramp */
write_reg(audio_dev, CS42L51_DAC_CTL, 0x42);
/* ALCA and PGAA Control : ALCA soft ramp disable on, ALCA zero cross disable on, PGA A Gain 0dB */
write_reg(audio_dev, CS42L51_ALC_PGA_CTL, 0xC0);
/* ALCB and PGAB Control : ALCB soft ramp disable on, ALCB zero cross disable on, PGA B Gain 0dB */
write_reg(audio_dev, CS42L51_ALC_PGB_CTL, 0xC0);
/* ADCA Attenuator : 0dB */
write_reg(audio_dev, CS42L51_ADCA_ATT, 0x00);
/* ADCB Attenuator : 0dB */
write_reg(audio_dev, CS42L51_ADCB_ATT, 0x00);
/* ADCA mixer volume control : ADCA mixer channel mute on, ADCA mixer volume 0dB */
write_reg(audio_dev, CS42L51_ADCA_VOL, 0x80);
/* ADCB mixer volume control : ADCB mixer channel mute on, ADCB mixer volume 0dB */
write_reg(audio_dev, CS42L51_ADCB_VOL, 0x80);
/* PCMA mixer volume control : PCMA mixer channel mute off, PCMA mixer volume 0dB */
write_reg(audio_dev, CS42L51_PCMA_VOL, 0x00);
/* PCMB mixer volume control : PCMB mixer channel mute off, PCMB mixer volume 0dB */
write_reg(audio_dev, CS42L51_PCMB_VOL, 0x00);
/* PCM channel mixer : AOUTA Left, AOUTB Right */
write_reg(audio_dev, CS42L51_PCM_MIXER, 0x00);
if(device & OUT_HEADPHONE)
{
value = VOLUME_CONVERT(volume);
/* AOUTA volume control : AOUTA volume */
write_reg(audio_dev, CS42L51_AOUTA_VOL, value);
/* AOUTB volume control : AOUTB volume */
write_reg(audio_dev, CS42L51_AOUTB_VOL, value);
}
CS42L51_Device = device;
return RT_EOK;
}
/**
* @brief Deinitialize the audio codec.
* @param None
* @retval None
*/
static void cs42l51_deinit(void)
{
/* Deinitialize Audio Codec interface */
rt_uint8_t temp = 0;
/* Mute DAC and ADC */
read_reg(audio_dev, CS42L51_DAC_OUT_CTL, 1, &temp);
write_reg(audio_dev, CS42L51_DAC_OUT_CTL, (temp | 0x03));
read_reg(audio_dev, CS42L51_ADC_INPUT, 1, &temp);
write_reg(audio_dev, CS42L51_ADC_INPUT, (temp | 0x03));
/* Disable soft ramp and zero cross */
read_reg(audio_dev, CS42L51_ADC_CTL, 1, &temp);
write_reg(audio_dev, CS42L51_ADC_CTL, (temp & 0xF0));
/* Set PDN to 1 */
read_reg(audio_dev, CS42L51_POWER_CTL1, 1, &temp);
write_reg(audio_dev, CS42L51_POWER_CTL1, (temp | 0x01));
/* Set all power down bits to 1 */
write_reg(audio_dev, CS42L51_POWER_CTL1, 0x7F);
read_reg(audio_dev, CS42L51_MIC_POWER_CTL, 1, &temp);
write_reg(audio_dev, CS42L51_MIC_POWER_CTL, (temp | 0x0E));
/* Power off CS42L51*/
rt_pin_write(CS42L51_RESET_PIN, PIN_LOW);
}
/**
* @brief Verify that we have a CS42L51.
* @retval 0 if correct communication, else wrong communication
*/
static uint32_t cs42l51_read_id(void)
{
uint8_t temp;
/* read cs42l51 id */
read_reg(audio_dev, CS42L51_CHIP_REV_ID, 1, &temp);
if ((temp != CS42L51_MK_CHIP_REV(CS42L51_CHIP_ID, CS42L51_CHIP_REV_A)) &&
(temp != CS42L51_MK_CHIP_REV(CS42L51_CHIP_ID, CS42L51_CHIP_REV_B)))
{
LOG_E("device id : 0x%02x", temp);
return RT_ERROR;
}
LOG_D("device id : 0x%02x", temp);
return RT_EOK;
}
/**
* @brief Start the audio Codec play feature.
* @note For this codec no Play options are required.
* @retval 0 if correct communication, else wrong communication
*/
static uint32_t cs42l51_play(void)
{
rt_uint8_t temp = 0;
switch (CS42L51_Device)
{
case OUT_HEADPHONE:
{
/* Unmute the output first */
cs42l51_drv.set_mute(AUDIO_MUTE_OFF);
/* DAC control : Signal processing to DAC, Freeze off, De-emphasis off, Analog output auto mute off, DAC soft ramp */
write_reg(audio_dev, CS42L51_DAC_CTL, 0x42);
/* Power control 1 : PDN_DACA, PDN_DACB disable. */
read_reg(audio_dev, CS42L51_POWER_CTL1, 1, &temp);
write_reg(audio_dev, CS42L51_POWER_CTL1, (temp & 0x9F));
break;
}
case IN_LINE1:
{
/* ADC Input Select, Invert and Mute : AIN1B to PGAB, AIN1A to PGAA, ADCB invert off, ADCA invert off, ADCB mute off, ADCA mute off */
write_reg(audio_dev, CS42L51_ADC_INPUT, 0x00);
/* Power control 1 : PDN_PGAA, PDN_PGAA, PDN_ADCB, PDN_ADCA disable. */
read_reg(audio_dev, CS42L51_POWER_CTL1, 1, &temp);
write_reg(audio_dev, CS42L51_POWER_CTL1, (temp & 0x9F));
break;
}
case IN_MIC1:
{
/* ADC Input Select, Invert and Mute : AIN1B to PGAB, AIN3A to PreAmp to PGAA, ADCB invert off, ADCA invert off, ADCB mute on, ADCA mute off */
write_reg(audio_dev, CS42L51_ADC_INPUT, 0x32);
/* Power control 1 : PDN_PGAA, PDN_ADCA disable. */
read_reg(audio_dev, CS42L51_POWER_CTL1, 1, &temp);
write_reg(audio_dev, CS42L51_POWER_CTL1, (temp & 0xF5));
/* Mic Power and Speed Control : PDN_MICA, PDN_MIC_BIAS disable. */
read_reg(audio_dev, CS42L51_MIC_POWER_CTL, 1, &temp);
write_reg(audio_dev, CS42L51_MIC_POWER_CTL,(temp & 0xF9));
break;
}
case IN_MIC2:
{
/* Power control 1 : PDN_PGAB, PDN_ADCB disable. */
read_reg(audio_dev, CS42L51_POWER_CTL1, 1, &temp);
write_reg(audio_dev, CS42L51_POWER_CTL1, (temp & 0xEB));
/* Mic Power and Speed Control : PDN_MICB, PDN_MIC_BIAS disable. */
read_reg(audio_dev, CS42L51_MIC_POWER_CTL, 1, &temp);
write_reg(audio_dev, CS42L51_MIC_POWER_CTL,(temp & 0xF5));
break;
}
default:
LOG_D("error audio play mode!");
break;
}
/* Power control : Exit standby (PDN = 0) */
read_reg(audio_dev, CS42L51_POWER_CTL1, 1, &temp);
write_reg(audio_dev, CS42L51_POWER_CTL1, (temp & 0xFE));
return RT_EOK;
}
/**
* @brief Pause playing on the audio codec.
* @param audio_dev: Device address on communication Bus.
* @retval 0 if correct communication, else wrong communication
*/
static uint32_t cs42l51_pause(void)
{
/* Pause the audio file playing */
/* Mute the output first */
return cs42l51_drv.set_mute(AUDIO_MUTE_ON);
}
/**
* @brief Resume playing on the audio codec.
* @param audio_dev: Device address on communication Bus.
* @retval 0 if correct communication, else wrong communication
*/
static uint32_t cs42l51_resume(void)
{
/* Unmute the output */
return cs42l51_drv.set_mute(AUDIO_MUTE_OFF);
}
/**
* @brief Stop audio Codec playing. It powers down the codec.
* @retval 0 if correct communication, else wrong communication
*/
static uint32_t cs42l51_stop(void)
{
rt_uint8_t temp = 0;
/* Set all power down bits to 1 exept PDN to mute ADCs and DACs*/
write_reg(audio_dev, 0x02, 0x7E);
read_reg(audio_dev, 0x03, 1, &temp);
write_reg(audio_dev, 0x03, (temp | 0x0E));
/* Disable zero cross and soft ramp */
read_reg(audio_dev, 0x09, 1, &temp);
write_reg(audio_dev, 0x09, (temp & 0xFC));
/* Power control : Enter standby (PDN = 1) */
read_reg(audio_dev, 0x02, 1, &temp);
write_reg(audio_dev, 0x02, (temp | 0x01));
return RT_EOK;
}
/**
* @brief Set new frequency.
* @param AudioFreq: Audio frequency used to play the audio stream.
* @retval 0 if correct communication, else wrong communication
*/
static uint32_t cs42l51_set_frequency(uint32_t AudioFreq)
{
return RT_EOK;
}
/**
* @brief Set higher or lower the codec volume level.
* @param Volume: output volume level (from 0 (-100dB) to 100 (0dB)).
* @retval 0 if correct communication, else wrong communication
*/
static uint32_t cs42l51_set_volume(uint8_t Volume)
{
uint8_t convertedvol = VOLUME_CONVERT(Volume);
/* AOUTA volume control : AOUTA volume */
write_reg(audio_dev, CS42L51_AOUTA_VOL, convertedvol);
/* AOUTB volume control : AOUTB volume */
write_reg(audio_dev, CS42L51_AOUTB_VOL, convertedvol);
return RT_EOK;
}
/**
* @brief get higher or lower the codec volume level.
* @retval value if correct communication
*/
static uint32_t cs42l51_get_volume(void)
{
rt_uint8_t temp = 0;
/* AOUTA volume control : AOUTA volume */
read_reg(audio_dev, CS42L51_AOUTA_VOL, 1, &temp);
temp = VOLUME_INVERT(temp);
return temp;
}
/**
* @brief Enable or disable the mute feature on the audio codec.
* @param Cmd: AUDIO_MUTE_ON to enable the mute or AUDIO_MUTE_OFF to disable the
* mute mode.
* @retval 0 if correct communication, else wrong communication
*/
static uint32_t cs42l51_set_mute(uint32_t cmd)
{
rt_uint8_t temp = 0;
/* Read DAC output control register */
read_reg(audio_dev, 0x08, 1, &temp);
/* Set the Mute mode */
if(cmd == AUDIO_MUTE_ON)
{
/* Mute DAC channels */
write_reg(audio_dev, CS42L51_DAC_OUT_CTL, (temp | 0x03));
}
else /* AUDIO_MUTE_OFF Disable the Mute */
{
/* Unmute DAC channels */
write_reg(audio_dev, CS42L51_DAC_OUT_CTL, (temp & 0xFC));
}
return RT_EOK;
}
/**
* @brief Switch dynamically (while audio file is played) the output target
* (speaker, headphone, etc).
* @note This function is currently not used (only headphone output device).
* @param Output: specifies the audio output device target.
* @retval 0 if correct communication, else wrong communication
*/
static uint32_t cs42l51_set_output_mode(uint8_t Output)
{
return RT_EOK;
}
/**
* @brief Reset CS42L51 registers.
* @retval 0 if correct communication, else wrong communication
*/
static uint32_t cs42l51_reset(void)
{
cs42l51_lowlevel_deinit();
cs42l51_lowlevel_init();
return RT_EOK;
}
/* Audio codec driver structure initialization */
AUDIO_DrvTypeDef cs42l51_drv =
{
cs42l51_init,
cs42l51_deinit,
cs42l51_read_id,
cs42l51_play,
cs42l51_pause,
cs42l51_resume,
cs42l51_stop,
cs42l51_set_frequency,
cs42l51_set_volume,
cs42l51_get_volume,
cs42l51_set_mute,
cs42l51_set_output_mode,
cs42l51_reset,
};
#endif

View File

@ -0,0 +1,198 @@
/*
* Copyright (c) 2006-2018, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Date Author Notes
* 2020-07-02 thread-liu first version
*/
#ifndef __DRV_CS42L51_H__
#define __DRV_CS42L51_H__
#ifdef __cplusplus
extern "C" {
#endif
typedef struct
{
rt_err_t (*init)(uint16_t , const char *, uint8_t);
void (*deinit)(void);
uint32_t (*read_id)(void);
uint32_t (*play)(void);
uint32_t (*pause)(void);
uint32_t (*resume)(void);
uint32_t (*stop)(void);
uint32_t (*set_frequency)(uint32_t);
uint32_t (*set_volume)(uint8_t);
uint32_t (*get_volume)(void);
uint32_t (*set_mute)(uint32_t);
uint32_t (*set_output_mode)(uint8_t);
uint32_t (*reset)(void);
}AUDIO_DrvTypeDef;
extern AUDIO_DrvTypeDef cs42l51_drv;
/* CS42L51 register space */
#define CS42L51_CHIP_ID 0x1B
#define CS42L51_CHIP_REV_A 0x00
#define CS42L51_CHIP_REV_B 0x01
#define CS42L51_CHIP_REV_ID 0x01
#define CS42L51_MK_CHIP_REV(a, b) ((a)<<3|(b))
#define CS42L51_POWER_CTL1 0x02
#define CS42L51_POWER_CTL1_PDN_DACB (1<<6)
#define CS42L51_POWER_CTL1_PDN_DACA (1<<5)
#define CS42L51_POWER_CTL1_PDN_PGAB (1<<4)
#define CS42L51_POWER_CTL1_PDN_PGAA (1<<3)
#define CS42L51_POWER_CTL1_PDN_ADCB (1<<2)
#define CS42L51_POWER_CTL1_PDN_ADCA (1<<1)
#define CS42L51_POWER_CTL1_PDN (1<<0)
#define CS42L51_MIC_POWER_CTL 0x03
#define CS42L51_MIC_POWER_CTL_AUTO (1<<7)
#define CS42L51_MIC_POWER_CTL_SPEED(x) (((x)&3)<<5)
#define CS42L51_QSM_MODE 3
#define CS42L51_HSM_MODE 2
#define CS42L51_SSM_MODE 1
#define CS42L51_DSM_MODE 0
#define CS42L51_MIC_POWER_CTL_3ST_SP (1<<4)
#define CS42L51_MIC_POWER_CTL_PDN_MICB (1<<3)
#define CS42L51_MIC_POWER_CTL_PDN_MICA (1<<2)
#define CS42L51_MIC_POWER_CTL_PDN_BIAS (1<<1)
#define CS42L51_MIC_POWER_CTL_MCLK_DIV2 (1<<0)
#define CS42L51_INTF_CTL 0x04
#define CS42L51_INTF_CTL_LOOPBACK (1<<7)
#define CS42L51_INTF_CTL_MASTER (1<<6)
#define CS42L51_INTF_CTL_DAC_FORMAT(x) (((x)&7)<<3)
#define CS42L51_DAC_DIF_LJ24 0x00
#define CS42L51_DAC_DIF_I2S 0x01
#define CS42L51_DAC_DIF_RJ24 0x02
#define CS42L51_DAC_DIF_RJ20 0x03
#define CS42L51_DAC_DIF_RJ18 0x04
#define CS42L51_DAC_DIF_RJ16 0x05
#define CS42L51_INTF_CTL_ADC_I2S (1<<2)
#define CS42L51_INTF_CTL_DIGMIX (1<<1)
#define CS42L51_INTF_CTL_MICMIX (1<<0)
#define CS42L51_MIC_CTL 0x05
#define CS42L51_MIC_CTL_ADC_SNGVOL (1<<7)
#define CS42L51_MIC_CTL_ADCD_DBOOST (1<<6)
#define CS42L51_MIC_CTL_ADCA_DBOOST (1<<5)
#define CS42L51_MIC_CTL_MICBIAS_SEL (1<<4)
#define CS42L51_MIC_CTL_MICBIAS_LVL(x) (((x)&3)<<2)
#define CS42L51_MIC_CTL_MICB_BOOST (1<<1)
#define CS42L51_MIC_CTL_MICA_BOOST (1<<0)
#define CS42L51_ADC_CTL 0x06
#define CS42L51_ADC_CTL_ADCB_HPFEN (1<<7)
#define CS42L51_ADC_CTL_ADCB_HPFRZ (1<<6)
#define CS42L51_ADC_CTL_ADCA_HPFEN (1<<5)
#define CS42L51_ADC_CTL_ADCA_HPFRZ (1<<4)
#define CS42L51_ADC_CTL_SOFTB (1<<3)
#define CS42L51_ADC_CTL_ZCROSSB (1<<2)
#define CS42L51_ADC_CTL_SOFTA (1<<1)
#define CS42L51_ADC_CTL_ZCROSSA (1<<0)
#define CS42L51_ADC_INPUT 0x07
#define CS42L51_ADC_INPUT_AINB_MUX(x) (((x)&3)<<6)
#define CS42L51_ADC_INPUT_AINA_MUX(x) (((x)&3)<<4)
#define CS42L51_ADC_INPUT_INV_ADCB (1<<3)
#define CS42L51_ADC_INPUT_INV_ADCA (1<<2)
#define CS42L51_ADC_INPUT_ADCB_MUTE (1<<1)
#define CS42L51_ADC_INPUT_ADCA_MUTE (1<<0)
#define CS42L51_DAC_OUT_CTL 0x08
#define CS42L51_DAC_OUT_CTL_HP_GAIN(x) (((x)&7)<<5)
#define CS42L51_DAC_OUT_CTL_DAC_SNGVOL (1<<4)
#define CS42L51_DAC_OUT_CTL_INV_PCMB (1<<3)
#define CS42L51_DAC_OUT_CTL_INV_PCMA (1<<2)
#define CS42L51_DAC_OUT_CTL_DACB_MUTE (1<<1)
#define CS42L51_DAC_OUT_CTL_DACA_MUTE (1<<0)
#define CS42L51_DAC_CTL 0x09
#define CS42L51_DAC_CTL_DATA_SEL(x) (((x)&3)<<6)
#define CS42L51_DAC_CTL_FREEZE (1<<5)
#define CS42L51_DAC_CTL_DEEMPH (1<<3)
#define CS42L51_DAC_CTL_AMUTE (1<<2)
#define CS42L51_DAC_CTL_DACSZ(x) (((x)&3)<<0)
#define CS42L51_ALC_PGA_CTL 0x0A
#define CS42L51_ALC_PGB_CTL 0x0B
#define CS42L51_ALC_PGX_ALCX_SRDIS (1<<7)
#define CS42L51_ALC_PGX_ALCX_ZCDIS (1<<6)
#define CS42L51_ALC_PGX_PGX_VOL(x) (((x)&0x1f)<<0)
#define CS42L51_ADCA_ATT 0x0C
#define CS42L51_ADCB_ATT 0x0D
#define CS42L51_ADCA_VOL 0x0E
#define CS42L51_ADCB_VOL 0x0F
#define CS42L51_PCMA_VOL 0x10
#define CS42L51_PCMB_VOL 0x11
#define CS42L51_MIX_MUTE_ADCMIX (1<<7)
#define CS42L51_MIX_VOLUME(x) (((x)&0x7f)<<0)
#define CS42L51_BEEP_FREQ 0x12
#define CS42L51_BEEP_VOL 0x13
#define CS42L51_BEEP_CONF 0x14
#define CS42L51_TONE_CTL 0x15
#define CS42L51_TONE_CTL_TREB(x) (((x)&0xf)<<4)
#define CS42L51_TONE_CTL_BASS(x) (((x)&0xf)<<0)
#define CS42L51_AOUTA_VOL 0x16
#define CS42L51_AOUTB_VOL 0x17
#define CS42L51_PCM_MIXER 0x18
#define CS42L51_LIMIT_THRES_DIS 0x19
#define CS42L51_LIMIT_REL 0x1A
#define CS42L51_LIMIT_ATT 0x1B
#define CS42L51_ALC_EN 0x1C
#define CS42L51_ALC_REL 0x1D
#define CS42L51_ALC_THRES 0x1E
#define CS42L51_NOISE_CONF 0x1F
#define CS42L51_STATUS 0x20
#define CS42L51_STATUS_SP_CLKERR (1<<6)
#define CS42L51_STATUS_SPEA_OVFL (1<<5)
#define CS42L51_STATUS_SPEB_OVFL (1<<4)
#define CS42L51_STATUS_PCMA_OVFL (1<<3)
#define CS42L51_STATUS_PCMB_OVFL (1<<2)
#define CS42L51_STATUS_ADCA_OVFL (1<<1)
#define CS42L51_STATUS_ADCB_OVFL (1<<0)
#define CS42L51_CHARGE_FREQ 0x21
#define CS42L51_FIRSTREG 0x01
enum play_type {
NONE,
OUT_HEADPHONE,
IN_MIC1,
IN_MIC2,
IN_LINE1,
IN_LINE2,
IN_LINE3,
};
/*
* Hack: with register 0x21, it makes 33 registers. Looks like someone in the
* i2c layer doesn't like i2c smbus block read of 33 regs. Workaround by using
* 32 regs
*/
#define CS42L51_LASTREG 0x20
#define CS42L51_NUMREGS (CS42L51_LASTREG - CS42L51_FIRSTREG + 1)
#define VOLUME_CONVERT(Volume) ((Volume >= 100) ? 0 : ((uint8_t)(((Volume * 2) + 56))))
#define VOLUME_INVERT(Volume) (((Volume) == 0U) ? 100U : ((uint8_t)(((Volume) - 56U) / 2U)))
/* MUTE commands */
#define AUDIO_MUTE_ON 1
#define AUDIO_MUTE_OFF 0
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,390 @@
/*
* Copyright (c) 2006-2020, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2019-07-31 Zero-Free first implementation
* 2020-07-02 thread-liu Porting for STM32MP1
*/
#include <board.h>
#if defined(BSP_USING_AUDIO_RECORD)
#include "drv_cs42l51.h"
//#define DRV_DEBUG
#define DBG_TAG "drv.audio"
#define DBG_LVL DBG_INFO
#include <rtdbg.h>
#define MIC_BUS_NAME "i2c4"
/* SYSRAM */
#define RX_FIFO_SIZE (4096)
#if defined(__CC_ARM) || defined(__CLANG_ARM)
rt_uint8_t MIC_RX_FIFO[RX_FIFO_SIZE] __attribute__((at(0x2FFC2000)));
#elif defined(__ICCARM__)
#pragma location = 0x2FFC2000
rt_uint8_t MIC_RX_FIFO[RX_FIFO_SIZE];
#elif defined ( __GNUC__ )
rt_uint8_t MIC_RX_FIFO[RX_FIFO_SIZE] __attribute__((at(0x2FFC2000)));
#endif
struct mic_device
{
struct rt_audio_device audio;
struct rt_audio_configure record_config;
rt_uint8_t *rx_fifo;
rt_uint8_t volume;
};
static struct mic_device mic_dev = {0};
static rt_uint16_t zero_frame[2] = {0};
extern SAI_HandleTypeDef hsai_BlockA2;
extern DMA_HandleTypeDef hdma_sai2_a;
extern SAI_HandleTypeDef hsai_BlockB2;
extern DMA_HandleTypeDef hdma_sai2_b;
extern void SAIA_Frequency_Set(uint32_t frequency);
void SAIB_Init(void)
{
HAL_SAI_DeInit(&hsai_BlockB2);
hsai_BlockB2.Instance = SAI2_Block_B;
hsai_BlockB2.Init.AudioFrequency = SAI_AUDIO_FREQUENCY_44K;
hsai_BlockB2.Init.AudioMode = SAI_MODESLAVE_RX;
hsai_BlockB2.Init.Synchro = SAI_SYNCHRONOUS;
hsai_BlockB2.Init.OutputDrive = SAI_OUTPUTDRIVE_ENABLE;
hsai_BlockB2.Init.NoDivider = SAI_MASTERDIVIDER_ENABLE;
hsai_BlockB2.Init.FIFOThreshold = SAI_FIFOTHRESHOLD_1QF;
hsai_BlockB2.Init.Mckdiv = 0;
hsai_BlockB2.Init.MckOverSampling = SAI_MCK_OVERSAMPLING_DISABLE;
hsai_BlockB2.Init.MonoStereoMode = SAI_STEREOMODE;
hsai_BlockB2.Init.CompandingMode = SAI_NOCOMPANDING;
hsai_BlockB2.Init.TriState = SAI_OUTPUT_NOTRELEASED;
hsai_BlockB2.Init.PdmInit.Activation = DISABLE;
hsai_BlockB2.Init.PdmInit.MicPairsNbr = 1;
hsai_BlockB2.Init.PdmInit.ClockEnable = SAI_PDM_CLOCK1_ENABLE;
hsai_BlockB2.Init.Protocol = SAI_FREE_PROTOCOL;
hsai_BlockB2.Init.DataSize = SAI_DATASIZE_16;
hsai_BlockB2.Init.FirstBit = SAI_FIRSTBIT_MSB;
hsai_BlockB2.Init.ClockStrobing = SAI_CLOCKSTROBING_RISINGEDGE;
hsai_BlockB2.FrameInit.FrameLength = 64;
hsai_BlockB2.FrameInit.ActiveFrameLength = 32;
hsai_BlockB2.FrameInit.FSDefinition = SAI_FS_CHANNEL_IDENTIFICATION;
hsai_BlockB2.FrameInit.FSPolarity = SAI_FS_ACTIVE_LOW;
hsai_BlockB2.FrameInit.FSOffset = SAI_FS_BEFOREFIRSTBIT;
hsai_BlockB2.SlotInit.FirstBitOffset = 0;
hsai_BlockB2.SlotInit.SlotSize = SAI_SLOTSIZE_32B;
hsai_BlockB2.SlotInit.SlotNumber = 2;
hsai_BlockB2.SlotInit.SlotActive = SAI_SLOTACTIVE_0|SAI_SLOTACTIVE_1;
/* DeInit SAI PDM input */
HAL_SAI_DeInit(&hsai_BlockB2);
/* Init SAI PDM input */
if(HAL_OK != HAL_SAI_Init(&hsai_BlockB2))
{
Error_Handler();
}
/* Enable SAI to generate clock used by audio driver */
__HAL_SAI_ENABLE(&hsai_BlockB2);
}
void SAIB_Channels_Set(uint8_t channels)
{
if (channels == 1)
{
hsai_BlockB2.Init.MonoStereoMode = SAI_MONOMODE;
}
else
{
hsai_BlockB2.Init.MonoStereoMode = SAI_STEREOMODE;
}
__HAL_SAI_DISABLE(&hsai_BlockB2);
HAL_SAI_Init(&hsai_BlockB2);
__HAL_SAI_ENABLE(&hsai_BlockB2);
}
void DMA2_Stream4_IRQHandler(void)
{
HAL_DMA_IRQHandler(&hdma_sai2_b);
}
void HAL_SAI_RxHalfCpltCallback(SAI_HandleTypeDef *hsai)
{
rt_audio_rx_done(&mic_dev.audio, &mic_dev.rx_fifo[0], RX_FIFO_SIZE / 2);
}
void HAL_SAI_RxCpltCallback(SAI_HandleTypeDef *hsai)
{
rt_audio_rx_done(&mic_dev.audio, &mic_dev.rx_fifo[RX_FIFO_SIZE / 2], RX_FIFO_SIZE / 2);
}
static rt_err_t mic_getcaps(struct rt_audio_device *audio, struct rt_audio_caps *caps)
{
rt_err_t result = RT_EOK;
struct mic_device *mic_dev;
RT_ASSERT(audio != RT_NULL);
mic_dev = (struct mic_device *)audio->parent.user_data;
switch (caps->main_type)
{
case AUDIO_TYPE_QUERY: /* qurey the types of hw_codec device */
{
switch (caps->sub_type)
{
case AUDIO_TYPE_QUERY:
caps->udata.mask = AUDIO_TYPE_INPUT | AUDIO_TYPE_MIXER;
break;
default:
result = -RT_ERROR;
break;
}
break;
}
case AUDIO_TYPE_INPUT: /* Provide capabilities of INPUT unit */
{
switch (caps->sub_type)
{
case AUDIO_DSP_PARAM:
caps->udata.config.samplerate = mic_dev->record_config.samplerate;
caps->udata.config.channels = mic_dev->record_config.channels;
caps->udata.config.samplebits = mic_dev->record_config.samplebits;
break;
case AUDIO_DSP_SAMPLERATE:
caps->udata.config.samplerate = mic_dev->record_config.samplerate;
break;
case AUDIO_DSP_CHANNELS:
caps->udata.config.channels = mic_dev->record_config.channels;
break;
case AUDIO_DSP_SAMPLEBITS:
caps->udata.config.samplebits = mic_dev->record_config.samplebits;
break;
default:
result = -RT_ERROR;
break;
}
break;
}
case AUDIO_TYPE_MIXER: /* report the Mixer Units */
{
switch (caps->sub_type)
{
case AUDIO_MIXER_QUERY:
caps->udata.mask = AUDIO_MIXER_VOLUME | AUDIO_MIXER_LINE;
break;
case AUDIO_MIXER_VOLUME:
caps->udata.value = mic_dev->volume;
break;
case AUDIO_MIXER_LINE:
break;
default:
result = -RT_ERROR;
break;
}
break;
}
default:
result = -RT_ERROR;
break;
}
return result;
}
static rt_err_t mic_configure(struct rt_audio_device *audio, struct rt_audio_caps *caps)
{
rt_err_t result = RT_EOK;
struct mic_device *mic_dev;
RT_ASSERT(audio != RT_NULL);
mic_dev = (struct mic_device *)audio->parent.user_data;
switch (caps->main_type)
{
case AUDIO_TYPE_MIXER:
{
switch (caps->sub_type)
{
case AUDIO_MIXER_VOLUME:
{
rt_uint32_t volume = caps->udata.value;
mic_dev->volume = volume;
LOG_D("set volume %d", volume);
break;
}
default:
result = -RT_ERROR;
break;
}
break;
}
case AUDIO_TYPE_INPUT:
{
switch (caps->sub_type)
{
case AUDIO_DSP_PARAM:
{
SAIA_Frequency_Set(caps->udata.config.samplerate);
HAL_SAI_DMAStop(&hsai_BlockB2);
SAIB_Channels_Set(caps->udata.config.channels);
HAL_SAI_Transmit(&hsai_BlockA2, (uint8_t *)&zero_frame[0], 2, 0);
HAL_SAI_Receive_DMA(&hsai_BlockB2, mic_dev->rx_fifo, RX_FIFO_SIZE / 2);
/* save configs */
mic_dev->record_config.samplerate = caps->udata.config.samplerate;
mic_dev->record_config.channels = caps->udata.config.channels;
mic_dev->record_config.samplebits = caps->udata.config.samplebits;
LOG_D("set samplerate %d", mic_dev->record_config.samplerate);
LOG_D("set channels %d", mic_dev->record_config.channels);
break;
}
case AUDIO_DSP_SAMPLERATE:
{
mic_dev->record_config.samplerate = caps->udata.config.samplerate;
LOG_D("set channels %d", mic_dev->record_config.channels);
break;
}
case AUDIO_DSP_CHANNELS:
{
mic_dev->record_config.channels = caps->udata.config.channels;
LOG_D("set channels %d", mic_dev->record_config.channels);
break;
}
default:
break;
}
break;
}
default:
break;
}
return result;
}
static rt_err_t mic_init(struct rt_audio_device *audio)
{
struct mic_device *mic_dev;
RT_ASSERT(audio != RT_NULL);
mic_dev = (struct mic_device *)audio->parent.user_data;
SAIB_Init();
/* set default params */
SAIB_Channels_Set(mic_dev->record_config.channels);
return RT_EOK;
}
static rt_err_t mic_start(struct rt_audio_device *audio, int stream)
{
struct mic_device *mic_dev;
RT_ASSERT(audio != RT_NULL);
mic_dev = (struct mic_device *)audio->parent.user_data;
if (stream == AUDIO_STREAM_RECORD)
{
cs42l51_drv.init(IN_MIC1, MIC_BUS_NAME, 40);
/* open receive */
if (HAL_SAI_Receive_DMA(&hsai_BlockB2, mic_dev->rx_fifo, RX_FIFO_SIZE / 2) != HAL_OK)
{
return RT_ERROR;
}
/* supply clk */
HAL_SAI_Transmit(&hsai_BlockA2, (uint8_t *)&zero_frame[0], 2, 0);
cs42l51_drv.play();
}
return RT_EOK;
}
static rt_err_t mic_stop(struct rt_audio_device *audio, int stream)
{
if (stream == AUDIO_STREAM_RECORD)
{
HAL_SAI_DMAStop(&hsai_BlockB2);
HAL_SAI_Abort(&hsai_BlockB2);
cs42l51_drv.stop();
}
return RT_EOK;
}
static struct rt_audio_ops mic_ops =
{
.getcaps = mic_getcaps,
.configure = mic_configure,
.init = mic_init,
.start = mic_start,
.stop = mic_stop,
.transmit = RT_NULL,
.buffer_info = RT_NULL,
};
int rt_hw_mic_init(void)
{
rt_err_t result = RT_EOK;
struct rt_device *device;
rt_memset(MIC_RX_FIFO, 0, RX_FIFO_SIZE);
mic_dev.rx_fifo = MIC_RX_FIFO;
/* init default configuration */
{
mic_dev.record_config.samplerate = 44100;
mic_dev.record_config.channels = 2;
mic_dev.record_config.samplebits = 16;
mic_dev.volume = 55;
}
/* register sound device */
mic_dev.audio.ops = &mic_ops;
result = rt_audio_register(&mic_dev.audio, "mic0", RT_DEVICE_FLAG_RDONLY, &mic_dev);
if (result != RT_EOK)
{
device = &(mic_dev.audio.parent);
rt_device_unregister(device);
LOG_E("mic device init error!");
return RT_ERROR;
}
return RT_EOK;
}
INIT_DEVICE_EXPORT(rt_hw_mic_init);
#endif

View File

@ -0,0 +1,603 @@
/*
* Copyright (c) 2006-2020, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2019-07-31 Zero-Free first implementation
* 2020-07-02 thread-liu Porting for STM32MP1
*/
#include "board.h"
#include "drv_cs42l51.h"
#ifdef BSP_USING_AUDIO
//#define DRV_DEBUG
#define LOG_TAG "drv.audio"
#include <drv_log.h>
#define SOUND_BUS_NAME "i2c4"
/* SYSRAM */
#define TX_FIFO_SIZE (4096)
#if defined(__CC_ARM) || defined(__CLANG_ARM)
rt_uint8_t AUDIO_TX_FIFO[TX_FIFO_SIZE] __attribute__((at(0x2FFC3000)));
#elif defined(__ICCARM__)
#pragma location = 0x2FFC3000
rt_uint8_t AUDIO_TX_FIFO[TX_FIFO_SIZE];
#elif defined ( __GNUC__ )
rt_uint8_t AUDIO_TX_FIFO[TX_FIFO_SIZE] __attribute__((at(0x2FFC3000)));
#endif
struct sound_device
{
struct rt_audio_device audio;
struct rt_audio_configure replay_config;
rt_uint8_t *tx_fifo;
rt_uint8_t volume;
};
static struct sound_device snd_dev = {0};
SAI_HandleTypeDef hsai_BlockA2 = {0};
DMA_HandleTypeDef hdma_sai2_a = {0};
SAI_HandleTypeDef hsai_BlockB2 = {0};
DMA_HandleTypeDef hdma_sai2_b = {0};
void HAL_SAI_MspInit(SAI_HandleTypeDef* hsai)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
/* SAI2 */
if(hsai->Instance==SAI2_Block_A)
{
/* Peripheral clock enable */
if(IS_ENGINEERING_BOOT_MODE())
{
/** Initializes the peripherals clock
*/
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_SAI2;
PeriphClkInit.Sai2ClockSelection = RCC_SAI2CLKSOURCE_PLL3_Q;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
__HAL_RCC_GPIOE_CLK_ENABLE();
__HAL_RCC_GPIOI_CLK_ENABLE();
__HAL_RCC_GPIOF_CLK_ENABLE();
__HAL_RCC_SAI2_CLK_ENABLE();
/**SAI2_A_Block_A GPIO Configuration
PE0 ------> SAI2_MCLK_A
PI7 ------> SAI2_FS_A
PI5 ------> SAI2_SCK_A
PI6 ------> SAI2_SD_A
*/
GPIO_InitStruct.Pin = GPIO_PIN_0;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF10_SAI2;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_7|GPIO_PIN_5|GPIO_PIN_6;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF10_SAI2;
HAL_GPIO_Init(GPIOI, &GPIO_InitStruct);
/* Configure DMA used for SAI2 */
__HAL_RCC_DMAMUX_CLK_ENABLE();
__HAL_RCC_DMA2_CLK_ENABLE();
hdma_sai2_a.Instance = DMA2_Stream5;
hdma_sai2_a.Init.Request = DMA_REQUEST_SAI2_A;
hdma_sai2_a.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_sai2_a.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_sai2_a.Init.MemInc = DMA_MINC_ENABLE;
hdma_sai2_a.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD;
hdma_sai2_a.Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD;
hdma_sai2_a.Init.Mode = DMA_CIRCULAR;
hdma_sai2_a.Init.Priority = DMA_PRIORITY_HIGH;
hdma_sai2_a.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
HAL_DMA_DeInit(&hdma_sai2_a);
if (HAL_DMA_Init(&hdma_sai2_a) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(hsai,hdmatx,hdma_sai2_a);
__HAL_DMA_ENABLE(&hdma_sai2_a);
HAL_NVIC_SetPriority(DMA2_Stream5_IRQn, 2, 0);
HAL_NVIC_EnableIRQ(DMA2_Stream5_IRQn);
}
if(hsai->Instance==SAI2_Block_B)
{
/* Peripheral clock enable */
if(IS_ENGINEERING_BOOT_MODE())
{
/** Initializes the peripherals clock
*/
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_SAI2;
PeriphClkInit.Sai2ClockSelection = RCC_SAI2CLKSOURCE_PLL3_Q;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
__HAL_RCC_GPIOF_CLK_ENABLE();
__HAL_RCC_SAI2_CLK_ENABLE();
/**SAI2_B_Block_B GPIO Configuration
PF11 ------> SAI2_SD_B
*/
GPIO_InitStruct.Pin = GPIO_PIN_11;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF10_SAI2;
HAL_GPIO_Init(GPIOF, &GPIO_InitStruct);
__HAL_RCC_DMAMUX_CLK_ENABLE();
__HAL_RCC_DMA2_CLK_ENABLE();
/* Peripheral DMA init*/
hdma_sai2_b.Instance = DMA2_Stream4;
hdma_sai2_b.Init.Request = DMA_REQUEST_SAI2_B;
hdma_sai2_b.Init.Direction = DMA_PERIPH_TO_MEMORY;
hdma_sai2_b.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_sai2_b.Init.MemInc = DMA_MINC_ENABLE;
hdma_sai2_b.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD;
hdma_sai2_b.Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD;
hdma_sai2_b.Init.Mode = DMA_CIRCULAR;
hdma_sai2_b.Init.Priority = DMA_PRIORITY_HIGH;
hdma_sai2_b.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
hdma_sai2_b.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_FULL;
hdma_sai2_b.Init.MemBurst = DMA_MBURST_SINGLE;
hdma_sai2_b.Init.PeriphBurst = DMA_PBURST_SINGLE;
__HAL_LINKDMA(hsai,hdmarx,hdma_sai2_b);
HAL_DMA_DeInit(&hdma_sai2_b);
if (HAL_DMA_Init(&hdma_sai2_b) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(hsai,hdmarx,hdma_sai2_b);
__HAL_DMA_ENABLE(&hdma_sai2_b);
HAL_NVIC_SetPriority(DMA2_Stream4_IRQn, 2, 0);
HAL_NVIC_EnableIRQ(DMA2_Stream4_IRQn);
}
}
void HAL_SAI_MspDeInit(SAI_HandleTypeDef* hsai)
{
/* SAI2 */
if(hsai->Instance==SAI2_Block_A)
{
/* Peripheral clock disable */
__HAL_RCC_SAI2_CLK_DISABLE();
/**SAI2_A_Block_A GPIO Configuration
PE0 ------> SAI2_MCLK_A
PI7 ------> SAI2_FS_A
PI5 ------> SAI2_SCK_A
PI6 ------> SAI2_SD_A
*/
HAL_GPIO_DeInit(GPIOE, GPIO_PIN_0);
HAL_GPIO_DeInit(GPIOI, GPIO_PIN_7|GPIO_PIN_5|GPIO_PIN_6);
HAL_DMA_DeInit(hsai->hdmarx);
HAL_DMA_DeInit(hsai->hdmatx);
}
if(hsai->Instance==SAI2_Block_B)
{
/* Peripheral clock disable */
__HAL_RCC_SAI2_CLK_DISABLE();
/**SAI2_B_Block_B GPIO Configuration
PF11 ------> SAI2_SD_B
*/
HAL_GPIO_DeInit(GPIOF, GPIO_PIN_11);
HAL_DMA_DeInit(hsai->hdmarx);
HAL_DMA_DeInit(hsai->hdmatx);
}
}
static void rt_hw_sai2a_init(void)
{
HAL_SAI_DeInit(&hsai_BlockA2);
hsai_BlockA2.Instance = SAI2_Block_A;
hsai_BlockA2.Init.Protocol = SAI_FREE_PROTOCOL;
hsai_BlockA2.Init.AudioMode = SAI_MODEMASTER_TX;
hsai_BlockA2.Init.DataSize = SAI_DATASIZE_16;
hsai_BlockA2.Init.FirstBit = SAI_FIRSTBIT_MSB;
hsai_BlockA2.Init.ClockStrobing = SAI_CLOCKSTROBING_RISINGEDGE;
hsai_BlockA2.Init.Synchro = SAI_ASYNCHRONOUS;
hsai_BlockA2.Init.OutputDrive = SAI_OUTPUTDRIVE_ENABLE;
hsai_BlockA2.Init.NoDivider = SAI_MASTERDIVIDER_ENABLE;
hsai_BlockA2.Init.FIFOThreshold = SAI_FIFOTHRESHOLD_EMPTY;
hsai_BlockA2.Init.AudioFrequency = SAI_AUDIO_FREQUENCY_44K;
hsai_BlockA2.Init.SynchroExt = SAI_SYNCEXT_DISABLE;
hsai_BlockA2.Init.MonoStereoMode = SAI_STEREOMODE;
hsai_BlockA2.Init.CompandingMode = SAI_NOCOMPANDING;
hsai_BlockA2.Init.TriState = SAI_OUTPUT_NOTRELEASED;
hsai_BlockA2.Init.PdmInit.Activation = DISABLE;
hsai_BlockA2.Init.PdmInit.MicPairsNbr = 0;
hsai_BlockA2.Init.PdmInit.ClockEnable = SAI_PDM_CLOCK1_ENABLE;
hsai_BlockA2.FrameInit.FrameLength = 64;
hsai_BlockA2.FrameInit.ActiveFrameLength = 32;
hsai_BlockA2.FrameInit.FSDefinition = SAI_FS_CHANNEL_IDENTIFICATION;
hsai_BlockA2.FrameInit.FSPolarity = SAI_FS_ACTIVE_LOW;
hsai_BlockA2.FrameInit.FSOffset = SAI_FS_BEFOREFIRSTBIT;
hsai_BlockA2.SlotInit.FirstBitOffset = 0;
hsai_BlockA2.SlotInit.SlotSize = SAI_SLOTSIZE_32B;
hsai_BlockA2.SlotInit.SlotNumber = 2;
hsai_BlockA2.SlotInit.SlotActive = SAI_SLOTACTIVE_0 | SAI_SLOTACTIVE_1;
if(HAL_OK != HAL_SAI_Init(&hsai_BlockA2))
{
Error_Handler();
}
/* Enable SAI to generate clock used by audio driver */
__HAL_SAI_ENABLE(&hsai_BlockA2);
}
void DMA2_Stream5_IRQHandler(void)
{
HAL_DMA_IRQHandler(&hdma_sai2_a);
}
void HAL_SAI_TxHalfCpltCallback(SAI_HandleTypeDef *hsai)
{
if (hsai == &hsai_BlockA2)
{
rt_audio_tx_complete(&snd_dev.audio);
}
}
void HAL_SAI_TxCpltCallback(SAI_HandleTypeDef *hsai)
{
if (hsai == &hsai_BlockA2)
{
rt_audio_tx_complete(&snd_dev.audio);
}
}
void SAIA_Frequency_Set(uint32_t frequency)
{
return;
}
void SAIA_Channels_Set(uint8_t channels)
{
if (channels == 1)
{
hsai_BlockA2.Init.MonoStereoMode = SAI_MONOMODE;
}
else
{
hsai_BlockA2.Init.MonoStereoMode = SAI_STEREOMODE;
}
__HAL_SAI_DISABLE(&hsai_BlockA2);
HAL_SAI_Init(&hsai_BlockA2);
__HAL_SAI_ENABLE(&hsai_BlockA2);
}
/**
* RT-Thread Audio Device Driver Interface
*/
static rt_err_t sound_getcaps(struct rt_audio_device *audio, struct rt_audio_caps *caps)
{
rt_err_t result = RT_EOK;
struct sound_device *snd_dev;
RT_ASSERT(audio != RT_NULL);
snd_dev = (struct sound_device *)audio->parent.user_data;
switch (caps->main_type)
{
case AUDIO_TYPE_QUERY: /* qurey the types of hw_codec device */
{
switch (caps->sub_type)
{
case AUDIO_TYPE_QUERY:
caps->udata.mask = AUDIO_TYPE_OUTPUT | AUDIO_TYPE_MIXER;
break;
default:
result = -RT_ERROR;
break;
}
break;
}
case AUDIO_TYPE_OUTPUT: /* Provide capabilities of OUTPUT unit */
{
switch (caps->sub_type)
{
case AUDIO_DSP_PARAM:
caps->udata.config.samplerate = snd_dev->replay_config.samplerate;
caps->udata.config.channels = snd_dev->replay_config.channels;
caps->udata.config.samplebits = snd_dev->replay_config.samplebits;
break;
case AUDIO_DSP_SAMPLERATE:
caps->udata.config.samplerate = snd_dev->replay_config.samplerate;
break;
case AUDIO_DSP_CHANNELS:
caps->udata.config.channels = snd_dev->replay_config.channels;
break;
case AUDIO_DSP_SAMPLEBITS:
caps->udata.config.samplebits = snd_dev->replay_config.samplebits;
break;
default:
result = -RT_ERROR;
break;
}
break;
}
case AUDIO_TYPE_MIXER: /* report the Mixer Units */
{
switch (caps->sub_type)
{
case AUDIO_MIXER_QUERY:
caps->udata.mask = AUDIO_MIXER_VOLUME;
break;
case AUDIO_MIXER_VOLUME:
caps->udata.value = cs42l51_drv.get_volume();
break;
default:
result = -RT_ERROR;
break;
}
break;
}
default:
result = -RT_ERROR;
break;
}
return result;
}
static rt_err_t sound_configure(struct rt_audio_device *audio, struct rt_audio_caps *caps)
{
rt_err_t result = RT_EOK;
struct sound_device *snd_dev;
RT_ASSERT(audio != RT_NULL);
snd_dev = (struct sound_device *)audio->parent.user_data;
switch (caps->main_type)
{
case AUDIO_TYPE_MIXER:
{
switch (caps->sub_type)
{
case AUDIO_MIXER_VOLUME:
{
rt_uint8_t volume = caps->udata.value;
cs42l51_drv.set_volume(volume);
snd_dev->volume = volume;
LOG_D("set volume %d", volume);
break;
}
default:
result = -RT_ERROR;
break;
}
break;
}
case AUDIO_TYPE_OUTPUT:
{
switch (caps->sub_type)
{
case AUDIO_DSP_PARAM:
{
/* set samplerate */
SAIA_Frequency_Set(caps->udata.config.samplerate);
/* set channels */
SAIA_Channels_Set(caps->udata.config.channels);
/* save configs */
snd_dev->replay_config.samplerate = caps->udata.config.samplerate;
snd_dev->replay_config.channels = caps->udata.config.channels;
snd_dev->replay_config.samplebits = caps->udata.config.samplebits;
LOG_D("set samplerate %d", snd_dev->replay_config.samplerate);
break;
}
case AUDIO_DSP_SAMPLERATE:
{
SAIA_Frequency_Set(caps->udata.config.samplerate);
snd_dev->replay_config.samplerate = caps->udata.config.samplerate;
LOG_D("set samplerate %d", snd_dev->replay_config.samplerate);
break;
}
case AUDIO_DSP_CHANNELS:
{
SAIA_Channels_Set(caps->udata.config.channels);
snd_dev->replay_config.channels = caps->udata.config.channels;
LOG_D("set channels %d", snd_dev->replay_config.channels);
break;
}
case AUDIO_DSP_SAMPLEBITS:
{
/* not support */
snd_dev->replay_config.samplebits = caps->udata.config.samplebits;
break;
}
default:
result = -RT_ERROR;
break;
}
break;
}
default:
break;
}
return result;
}
static rt_err_t sound_init(struct rt_audio_device *audio)
{
rt_err_t result = RT_EOK;
struct sound_device *snd_dev;
RT_ASSERT(audio != RT_NULL);
snd_dev = (struct sound_device *)audio->parent.user_data;
cs42l51_drv.init(OUT_HEADPHONE, SOUND_BUS_NAME, 40);
if (cs42l51_drv.read_id() != RT_EOK)
{
LOG_E("can't find low level audio device!");
return RT_ERROR;
}
rt_hw_sai2a_init();
/* set default params */
SAIA_Frequency_Set(snd_dev->replay_config.samplerate);
SAIA_Channels_Set(snd_dev->replay_config.channels);
return result;
}
static rt_err_t sound_start(struct rt_audio_device *audio, int stream)
{
struct sound_device *snd_dev;
RT_ASSERT(audio != RT_NULL);
snd_dev = (struct sound_device *)audio->parent.user_data;
if (stream == AUDIO_STREAM_REPLAY)
{
LOG_D("open sound device");
cs42l51_drv.init(OUT_HEADPHONE, SOUND_BUS_NAME, 60); /* set work mode */
cs42l51_drv.play();
if (HAL_SAI_Transmit_DMA(&hsai_BlockA2, snd_dev->tx_fifo, TX_FIFO_SIZE / 2) != HAL_OK)
{
return RT_ERROR;
}
}
return RT_EOK;
}
static rt_err_t sound_stop(struct rt_audio_device *audio, int stream)
{
RT_ASSERT(audio != RT_NULL);
if (stream == AUDIO_STREAM_REPLAY)
{
HAL_SAI_DMAStop(&hsai_BlockA2);
HAL_SAI_Abort(&hsai_BlockA2);
cs42l51_drv.stop();
LOG_D("close sound device");
}
return RT_EOK;
}
static void sound_buffer_info(struct rt_audio_device *audio, struct rt_audio_buf_info *info)
{
struct sound_device *snd_dev;
RT_ASSERT(audio != RT_NULL);
snd_dev = (struct sound_device *)audio->parent.user_data;
/**
* TX_FIFO
* +----------------+----------------+
* | block1 | block2 |
* +----------------+----------------+
* \ block_size /
*/
info->buffer = snd_dev->tx_fifo;
info->total_size = TX_FIFO_SIZE;
info->block_size = TX_FIFO_SIZE / 2;
info->block_count = 2;
}
static struct rt_audio_ops snd_ops =
{
.getcaps = sound_getcaps,
.configure = sound_configure,
.init = sound_init,
.start = sound_start,
.stop = sound_stop,
.transmit = RT_NULL,
.buffer_info = sound_buffer_info,
};
int rt_hw_sound_init(void)
{
rt_err_t result = RT_EOK;
struct rt_device *device = RT_NULL;
rt_memset(AUDIO_TX_FIFO, 0, TX_FIFO_SIZE);
snd_dev.tx_fifo = AUDIO_TX_FIFO;
/* init default configuration */
snd_dev.replay_config.samplerate = 44100;
snd_dev.replay_config.channels = 2;
snd_dev.replay_config.samplebits = 16;
snd_dev.volume = 55;
/* register sound device */
snd_dev.audio.ops = &snd_ops;
result = rt_audio_register(&snd_dev.audio, "sound0", RT_DEVICE_FLAG_WRONLY, &snd_dev);
if (result != RT_EOK)
{
device = &(snd_dev.audio.parent);
rt_device_unregister(device);
LOG_E("sound device init error!");
return RT_ERROR;
}
return RT_EOK;
}
INIT_APP_EXPORT(rt_hw_sound_init);
#endif

View File

@ -0,0 +1,449 @@
/*
* Copyright (c) 2006-2022, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2020-06-27 thread-liu first version
*/
#include <board.h>
#include "drv_crypto.h"
#include <hwcrypto.h>
#include <string.h>
#include <stdlib.h>
#define __is_print(ch) ((unsigned int)((ch) - ' ') < 127u - ' ')
static void dump_hex(const rt_uint8_t *ptr, rt_size_t buflen)
{
unsigned char *buf = (unsigned char *)ptr;
int i, j;
for (i = 0; i < buflen; i += 16)
{
rt_kprintf("%08X: ", i);
for (j = 0; j < 16; j++)
{
if (i + j < buflen)
{
rt_kprintf("%02X ", buf[i + j]);
}
else
{
rt_kprintf(" ");
}
}
rt_kprintf(" ");
for (j = 0; j < 16; j++)
{
if (i + j < buflen)
{
rt_kprintf("%c", __is_print(buf[i + j]) ? buf[i + j] : '.');
}
}
rt_kprintf("\n");
}
}
#if defined(BSP_USING_RNG)
static rt_err_t hw_rng_sample(int random_num)
{
rt_err_t result = RT_EOK;
int i = 0, num0 = 0, num1 = 0;
if (random_num == 0)
{
return RT_ERROR;
}
for (i = 0; i< random_num; i++)
{
result = rt_hwcrypto_rng_update();
rt_kprintf("%d ", result);
result%2 ? num1++ : num0++;
}
rt_kprintf("\neven numbers : %d, odd numbers: %d\n",num1, num0);
return RT_EOK;
}
#endif
#if defined(BSP_USING_CRC)
static void hw_crc_sample(uint8_t *temp, int size)
{
struct rt_hwcrypto_ctx *ctx;
rt_uint32_t result = 0;
struct hwcrypto_crc_cfg cfg =
{
.last_val = 0xFFFFFFFF,
.poly = 0x04C11DB7,
.width = 32,
.xorout = 0x00000000,
.flags = 0,
};
ctx = rt_hwcrypto_crc_create(rt_hwcrypto_dev_default(), HWCRYPTO_CRC_CRC32);
rt_hwcrypto_crc_cfg(ctx, &cfg);
result = rt_hwcrypto_crc_update(ctx, temp, size);
rt_kprintf("crc result: %x \n", result);
rt_hwcrypto_crc_destroy(ctx);
}
#endif
#if defined(BSP_USING_HASH)
static void hw_hash_sample()
{
struct rt_hwcrypto_ctx *ctx = RT_NULL;
const uint8_t hash_input[] = "RT-Thread was born in 2006, it is an open source, neutral, and community-based real-time operating system (RTOS).";
static uint8_t sha1_output[20];
static uint8_t sha1_except[20] = {0xff, 0x3c, 0x95, 0x54, 0x95, 0xf0, 0xad,
0x02, 0x1b, 0xa8, 0xbc, 0xa2, 0x2e, 0xa5,
0xb0, 0x62, 0x1b, 0xdf, 0x7f, 0xec};
static uint8_t md5_output[16];
static uint8_t md5_except[16] = {0x40, 0x86, 0x03, 0x80, 0x0d, 0x8c, 0xb9,
0x4c, 0xd6, 0x7d, 0x28, 0xfc, 0xf6, 0xc3,
0xac, 0x8b};
static uint8_t sha224_output[28];
static uint8_t sha224_except[28] = {0x6f, 0x62, 0x52, 0x7d, 0x80, 0xe6,
0x9f, 0x82, 0x78, 0x7a, 0x46, 0x91,
0xb0, 0xe9, 0x64, 0x89, 0xe6, 0xc3,
0x6b, 0x7e, 0xcf, 0xca, 0x11, 0x42,
0xc8, 0x77, 0x13, 0x79};
static uint8_t sha256_output[32];
static uint8_t sha256_except[32] = {0x74, 0x19, 0xb9, 0x0e, 0xd1, 0x46,
0x37, 0x0a, 0x55, 0x18, 0x26, 0x6c,
0x50, 0xd8, 0x71, 0x34, 0xfa, 0x1f,
0x5f, 0x5f, 0xe4, 0x9a, 0xe9, 0x40,
0x0a, 0x7d, 0xa0, 0x26, 0x1b, 0x86,
0x67, 0x45};
rt_kprintf("======================== Hash Test start ========================\n");
rt_kprintf("Hash Test string: \n");
dump_hex(hash_input, sizeof(hash_input));
/* sh1 test*/
rt_kprintf("\n============ SHA1 Test Start ============\n");
ctx = rt_hwcrypto_hash_create(rt_hwcrypto_dev_default(), HWCRYPTO_TYPE_SHA1);
if (ctx == RT_NULL)
{
rt_kprintf("create hash[%08x] context err!\n", HWCRYPTO_TYPE_SHA1);
return ;
}
rt_kprintf("Create sha1 type success!\n");
rt_kprintf("Except sha1 result:\n");
dump_hex(sha1_except, sizeof(sha1_except));
/* start sha1 */
rt_hwcrypto_hash_update(ctx, hash_input, rt_strlen((char const *)hash_input));
/* get sha1 result */
rt_hwcrypto_hash_finish(ctx, sha1_output, rt_strlen((char const *)sha1_output));
rt_kprintf("Actual sha1 result:\n");
dump_hex(sha1_output, sizeof(sha1_output));
if(rt_memcmp(sha1_output, sha1_except, sizeof(sha1_except)/sizeof(sha1_except[0])) != 0)
{
rt_kprintf("Hash type sha1 Test error, The actual result is not equal to the except result\n");
}
else
{
rt_kprintf("Hash type sha1 Test success, The actual result is equal to the except result\n");
}
/* deinit hash*/
rt_hwcrypto_hash_destroy(ctx);
rt_kprintf("============ SHA1 Test Over ============\n");
/* md5 test*/
rt_kprintf("\n============ MD5 Test Start ============\n");
ctx = rt_hwcrypto_hash_create(rt_hwcrypto_dev_default(), HWCRYPTO_TYPE_MD5);
if (ctx == RT_NULL)
{
rt_kprintf("create hash[%08x] context err!\n", HWCRYPTO_TYPE_MD5);
return ;
}
rt_kprintf("Create md5 type success!\n");
rt_kprintf("Except md5 result:\n");
dump_hex(md5_except, sizeof(md5_except));
/* start md5 */
rt_hwcrypto_hash_update(ctx, hash_input, rt_strlen((char const *)hash_input));
/* get md5 result */
rt_hwcrypto_hash_finish(ctx, md5_output, rt_strlen((char const *)md5_output));
rt_kprintf("Actual md5 result:\n");
dump_hex(md5_output, sizeof(md5_output));
if(rt_memcmp(md5_output, md5_except, sizeof(md5_except)/sizeof(md5_except[0])) != 0)
{
rt_kprintf("Hash type md5 Test error, The actual result is not equal to the except result\n");
}
else
{
rt_kprintf("Hash type md5 Test success, The actual result is equal to the except result\n");
}
/* deinit hash*/
rt_hwcrypto_hash_destroy(ctx);
rt_kprintf("============ MD5 Test Over ============\n");
/* sha224 test */
rt_kprintf("\n============ SHA224 Test Start ============\n");
ctx = rt_hwcrypto_hash_create(rt_hwcrypto_dev_default(), HWCRYPTO_TYPE_SHA224);
if (ctx == RT_NULL)
{
rt_kprintf("create hash[%08x] context err!\n", HWCRYPTO_TYPE_SHA224);
return ;
}
rt_kprintf("Create sha224 type success!\n");
rt_kprintf("Except sha224 result:\n");
dump_hex(sha224_except, sizeof(sha224_except));
/* start sha224 */
rt_hwcrypto_hash_update(ctx, hash_input, rt_strlen((char const *)hash_input));
/* get sha224 result */
rt_hwcrypto_hash_finish(ctx, sha224_output, rt_strlen((char const *)sha224_output));
rt_kprintf("Actual sha224 result:\n");
dump_hex(sha224_output, sizeof(sha224_output));
if(rt_memcmp(sha224_output, sha224_except, sizeof(sha224_except)/sizeof(sha224_except[0])) != 0)
{
rt_kprintf("Hash type sha224 Test error, The actual result is not equal to the except result\n");
}
else
{
rt_kprintf("Hash type sha224 Test success, The actual result is equal to the except result\n");
}
rt_hwcrypto_hash_destroy(ctx);
rt_kprintf("============ SHA224 Test Over ============\n");
/* sha256 test*/
rt_kprintf("\n============ SHA256 Test Start ============\n");
ctx = rt_hwcrypto_hash_create(rt_hwcrypto_dev_default(), HWCRYPTO_TYPE_SHA256);
if (ctx == RT_NULL)
{
rt_kprintf("create hash[%08x] context err!\n", HWCRYPTO_TYPE_SHA256);
return ;
}
rt_kprintf("Create sha256 type success!\n");
rt_kprintf("Except sha256 result:\n");
dump_hex(sha256_except, sizeof(sha256_except));
/* start sha256 */
rt_hwcrypto_hash_update(ctx, hash_input, rt_strlen((char const *)hash_input));
/* get sha256 result */
rt_hwcrypto_hash_finish(ctx, sha256_output, rt_strlen((char const *)sha256_output));
rt_kprintf("Actual sha256 result\n");
dump_hex(sha256_output, sizeof(sha256_output));
if(rt_memcmp(sha256_output, sha256_except, sizeof(sha256_except)/sizeof(sha256_except[0])) != 0)
{
rt_kprintf("Hash type sha256 Test error, The actual result is not equal to the except result\n");
}
else
{
rt_kprintf("Hash type sha256 Test success, The actual result is equal to the except result\n");
}
/* destory */
rt_hwcrypto_hash_destroy(ctx);
rt_kprintf("============ SHA256 Test Over ============\n");
rt_kprintf("======================== Hash Test over! ========================\n");
}
#endif
#if defined(BSP_USING_CRYP)
/* key*/
static const rt_uint8_t cryp_key[16] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF};
static void hw_aes_cbc(const rt_uint8_t in[32], rt_uint8_t out[32], hwcrypto_mode mode)
{
struct rt_hwcrypto_ctx *ctx;
ctx = rt_hwcrypto_symmetric_create(rt_hwcrypto_dev_default(), HWCRYPTO_TYPE_AES_CBC);
if (ctx == RT_NULL)
{
rt_kprintf("create AES-CBC context err!");
return;
}
rt_hwcrypto_symmetric_setkey(ctx, cryp_key, 128);
rt_hwcrypto_symmetric_crypt(ctx, mode, 32, in, out);
rt_hwcrypto_symmetric_destroy(ctx);
}
static void hw_cryp_sample()
{
rt_uint8_t buf_in[32];
rt_uint8_t buf_out[32];
int i;
/* Populating test data */
for (i = 0; i < sizeof(buf_in); i++)
{
buf_in[i] = i;
}
/* dump primitive data */
rt_kprintf("key : \n");
dump_hex(cryp_key, sizeof(cryp_key));
rt_kprintf("primitive data : \n");
dump_hex(buf_in, sizeof(buf_in));
rt_memset(buf_out, 0, sizeof(buf_out));
/* encrypt */
hw_aes_cbc(buf_in, buf_out, HWCRYPTO_MODE_ENCRYPT);
/* dump encrypt data */
rt_kprintf("AES-enc : \n");
dump_hex(buf_out, sizeof(buf_out));
rt_memset(buf_in, 0, sizeof(buf_in));
/* decrypt */
hw_aes_cbc(buf_out, buf_in, HWCRYPTO_MODE_DECRYPT);
/* dump decrypt data */
rt_kprintf("AES-dec : \n");
dump_hex(buf_in, sizeof(buf_in));
}
#endif
static int crypto(int argc, char **argv)
{
int result = RT_EOK;
static rt_device_t device = RT_NULL;
char *result_str;
if (argc > 1)
{
if (!strcmp(argv[1], "probe"))
{
if (argc == 3)
{
char *dev_name = argv[2];
device = rt_device_find(dev_name);
result_str = (device == RT_NULL) ? "failure" : "success";
rt_kprintf("probe %s %s \n", argv[2], result_str);
}
else
{
rt_kprintf("crypto probe <crypto_name> - probe crypto by name\n");
}
}
else
{
if (device == RT_NULL)
{
rt_kprintf("Please using 'crypto probe <crypto_name>' first\n");
return -RT_ERROR;
}
if (!strcmp(argv[1], "rng"))
{
#if defined (BSP_USING_RNG)
if (argc == 3)
{
result = hw_rng_sample(atoi(argv[2]));
if(result != RT_EOK)
{
rt_kprintf("please input a legal number, not <%d>\n", atoi(argv[2]));
}
}
else
{
rt_kprintf("rng <number> - generate <number> digital\n");
}
#else
rt_kprintf("please enable RNG first!\n");
#endif
}
else if (!strcmp(argv[1], "crc"))
{
#if defined (BSP_USING_CRC)
int size = 0, i = 0;
if (argc > 3)
{
size = argc - 2;
uint8_t *data = rt_malloc(size);
if (data)
{
for (i = 0; i < size; i++)
{
data[i] = strtol(argv[2 + i], NULL, 0);
}
hw_crc_sample(data, size);
rt_free(data);
}
else
{
rt_kprintf("Low memory!\n");
}
}
else
{
rt_kprintf("crypto crc data1 ... dataN - calculate data1 ... dataN crc\n");
}
#else
rt_kprintf("please enable CRC first!\n");
#endif
}
else if (!strcmp(argv[1], "hash"))
{
#if defined (BSP_USING_HASH)
if (argc == 3)
{
hw_hash_sample();
}
else
{
rt_kprintf("crypto hash sample - hash use sample\n");
}
#else
rt_kprintf("please enable CRC first!\n");
#endif
}
else if (!strcmp(argv[1], "cryp"))
{
#if defined (BSP_USING_CRYP)
if (argc == 3)
{
hw_cryp_sample();
}
else
{
rt_kprintf("crypto cryp sample - encrypt and decrypt data sample\n");
}
#else
rt_kprintf("please enable CRYP first!\n");
#endif
}
else
{
rt_kprintf("Unknown command. Please enter 'crypto' for help\n");
}
}
}
else
{
rt_kprintf("Usage: \n");
rt_kprintf("crypto probe <crypto_name> - probe crypto by name\n");
rt_kprintf("crypto rng number - generate numbers digital\n");
rt_kprintf("crypto crc data1 ... dataN - calculate data1 ... dataN crc\n");
rt_kprintf("crypto hash sample - hash use sample\n");
rt_kprintf("crypto cryp sample - encrypt and decrypt data\n");
result = -RT_ERROR;
}
return result;
}
MSH_CMD_EXPORT(crypto, crypto function);

View File

@ -0,0 +1,882 @@
/*
* Copyright (c) 2006-2018, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2020-07-20 thread-liu the first version
*/
#include "board.h"
#include "drv_config.h"
#include <netif/ethernetif.h>
#include "lwipopts.h"
#include "drv_eth.h"
#if defined(BSP_USING_GBE)
#define DRV_DEBUG
//#define ETH_RX_DUMP
//#define ETH_TX_DUMP
#define LOG_TAG "drv.emac"
#include <drv_log.h>
#define MAX_ADDR_LEN 6
rt_base_t level;
#define TX_ADD_BASE 0x2FFC3000
#define RX_ADD_BASE 0x2FFC5000
#define TX_DMA_ADD_BASE 0x2FFC7000
#define RX_DMA_ADD_BASE 0x2FFC7100
#if defined(__ICCARM__)
/* transmit buffer */
#pragma location = TX_ADD_BASE
static rt_uint8_t txBuffer[ETH_TXBUFNB][ETH_TX_BUF_SIZE];
/* Receive buffer */
#pragma location = RX_ADD_BASE
static rt_uint8_t rxBuffer[ETH_RXBUFNB][ETH_RX_BUF_SIZE];
/* Transmit DMA descriptors */
#pragma location = TX_DMA_ADD_BASE
static TxDmaDesc txDmaDesc[ETH_TXBUFNB];
/* Receive DMA descriptors */
#pragma location = RX_DMA_ADD_BASE
static RxDmaDesc rxDmaDesc[ETH_RXBUFNB];
#elif defined(__CC_ARM) || defined(__CLANG_ARM)
/* transmit buffer */
static rt_uint8_t txBuffer[ETH_TXBUFNB][ETH_TX_BUF_SIZE] __attribute__((at(TX_ADD_BASE)));
/* Receive buffer */
static rt_uint8_t rxBuffer[ETH_RXBUFNB][ETH_RX_BUF_SIZE] __attribute__((at(RX_ADD_BASE)));
/* Transmit DMA descriptors */
static TxDmaDesc txDmaDesc[ETH_TXBUFNB] __attribute__((at(TX_DMA_ADD_BASE)));
/* Receive DMA descriptors */
static RxDmaDesc rxDmaDesc[ETH_RXBUFNB] __attribute__((at(RX_DMA_ADD_BASE)));
#elif defined ( __GNUC__ )
/* transmit buffer */
static rt_uint8_t txBuffer[ETH_TXBUFNB][ETH_TX_BUF_SIZE] __attribute__((at(TX_ADD_BASE)));
/* Receive buffer */
static rt_uint8_t rxBuffer[ETH_RXBUFNB][ETH_RX_BUF_SIZE] __attribute__((at(RX_ADD_BASE)));
/* Transmit DMA descriptors */
static TxDmaDesc txDmaDesc[ETH_TXBUFNB] __attribute__((at(TX_DMA_ADD_BASE)));
/* Receive DMA descriptors */
static RxDmaDesc rxDmaDesc[ETH_RXBUFNB] __attribute__((at(RX_DMA_ADD_BASE)));
#endif
/* Current transmit descriptor */
static rt_uint8_t txIndex = 0;
/* Current receive descriptor */
static rt_uint8_t rxIndex = 0;
/* eth rx event */
static struct rt_event rx_event = {0};
#define ETH_TIME_OUT 100000
struct rt_stm32_eth
{
/* inherit from ethernet device */
struct eth_device parent;
#ifndef PHY_USING_INTERRUPT_MODE
rt_timer_t poll_link_timer;
#endif
/* interface address info, hw address */
rt_uint8_t dev_addr[MAX_ADDR_LEN];
/* eth speed */
rt_uint32_t eth_speed;
/* eth duplex mode */
rt_uint32_t eth_mode;
};
static struct rt_stm32_eth stm32_eth_device = {0};
#if defined(ETH_RX_DUMP) || defined(ETH_TX_DUMP)
#define __is_print(ch) ((unsigned int)((ch) - ' ') < 127u - ' ')
static void dump_hex(const rt_uint8_t *ptr, rt_size_t buflen)
{
unsigned char *buf = (unsigned char *)ptr;
int i, j;
for (i = 0; i < buflen; i += 16)
{
rt_kprintf("%08X: ", i);
for (j = 0; j < 16; j++)
{
if (i + j < buflen)
{
rt_kprintf("%02X ", buf[i + j]);
}
else
{
rt_kprintf(" ");
}
}
rt_kprintf(" ");
for (j = 0; j < 16; j++)
{
if (i + j < buflen)
{
rt_kprintf("%c", __is_print(buf[i + j]) ? buf[i + j] : '.');
}
}
rt_kprintf("\n");
}
}
#endif
static rt_err_t phy_write_reg(uint8_t phy_addr, uint8_t reg_addr, uint16_t reg_value)
{
uint32_t temp;
volatile uint32_t tickstart = 0;
/* Take care not to alter MDC clock configuration */
temp = ETH->MACMDIOAR & ETH_MACMDIOAR_CR;
/* Set up a write operation */
temp |= ETH_MACMDIOAR_GOC_Val(1) | ETH_MACMDIOAR_GB;
/* PHY address */
temp |= (phy_addr << 21) & ETH_MACMDIOAR_PA;
/* Register address */
temp |= (reg_addr << 16) & ETH_MACMDIOAR_RDA;
/* Data to be written in the PHY register */
ETH->MACMDIODR = reg_value & ETH_MACMDIODR_GD;
/* Start a write operation */
ETH->MACMDIOAR = temp;
/* Wait for the write to complete */
tickstart = rt_tick_get();
while((ETH->MACMDIOAR & ETH_MACMDIOAR_GB) != 0)
{
/* judge timeout */
if((rt_tick_get() - tickstart) > ETH_TIME_OUT)
{
LOG_E("PHY write reg %02x date %04x timeout!", reg_addr, reg_value);
return -RT_ETIMEOUT;
}
}
return RT_EOK;
}
static uint16_t phy_read_reg(uint8_t phy_addr, uint8_t reg_addr)
{
uint16_t reg_value = 0;
uint32_t status = 0;
volatile uint32_t tickstart = 0;
/* Take care not to alter MDC clock configuration */
status = ETH->MACMDIOAR & ETH_MACMDIOAR_CR;
/* Set up a read operation */
status |= ETH_MACMDIOAR_GOC_Val(3) | ETH_MACMDIOAR_GB;
/* PHY address */
status |= (phy_addr << 21) & ETH_MACMDIOAR_PA;
/* Register address */
status |= (reg_addr << 16) & ETH_MACMDIOAR_RDA;
/* Start a read operation */
ETH->MACMDIOAR = status;
/* Wait for the read to complete */
tickstart = rt_tick_get();
while((ETH->MACMDIOAR & ETH_MACMDIOAR_GB) != 0)
{
/* judge timeout */
if((rt_tick_get() - tickstart) > ETH_TIME_OUT)
{
LOG_E("PHY read reg %02x timeout!", reg_addr);
return RT_ETIMEOUT;
}
}
/* Get register value */
reg_value = ETH->MACMDIODR & ETH_MACMDIODR_GD;
return reg_value;
}
static rt_err_t update_mac_mode(rt_uint32_t eth_speed, rt_uint32_t eth_mode)
{
uint32_t status;
/* Read current MAC configuration */
status = ETH->MACCR;
if (eth_speed == PHY_1000M)
{
status &= ~ETH_MACCR_PS;
status &= ~ETH_MACCR_FES;
}
else if (eth_speed == PHY_100M)
{
status |= ETH_MACCR_PS;
status |= ETH_MACCR_FES;
}
/* 10M */
else
{
status |= ETH_MACCR_PS;
status &= ~ETH_MACCR_FES;
}
if (eth_mode == PHY_FULL_DUPLEX)
{
status |= ETH_MACCR_DM;
}
else
{
status &= ~ETH_MACCR_DM;
}
/* Update MAC configuration register */
ETH->MACCR = status;
return RT_EOK;
}
static void HAL_ETH_MspInit(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
if(IS_ENGINEERING_BOOT_MODE())
{
/** Initializes the peripherals clock
*/
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ETH;
PeriphClkInit.EthClockSelection = RCC_ETHCLKSOURCE_PLL4;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
/* Enable SYSCFG clock */
__HAL_RCC_SYSCFG_CLK_ENABLE();
/* Enable GPIO clocks */
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOE_CLK_ENABLE();
__HAL_RCC_GPIOG_CLK_ENABLE();
/* Select RGMII interface mode */
HAL_SYSCFG_ETHInterfaceSelect(SYSCFG_ETH_RGMII);
/* Enable Ethernet MAC clock */
__HAL_RCC_ETH1MAC_CLK_ENABLE();
__HAL_RCC_ETH1TX_CLK_ENABLE();
__HAL_RCC_ETH1RX_CLK_ENABLE();
/**ETH1 GPIO Configuration
PA1 ------> ETH1_RX_CLK
PA7 ------> ETH1_RX_CTL
PB0 ------> ETH1_RXD2
PB1 ------> ETH1_RXD3
PC4 ------> ETH1_RXD0
PC5 ------> ETH1_RXD1
PA2 ------> ETH1_MDIO
PB11 ------> ETH1_TX_CTL
PC1 ------> ETH1_MDC
PC2 ------> ETH1_TXD2
PE2 ------> ETH1_TXD3
PG4 ------> ETH1_GTX_CLK
PG5 ------> ETH1_CLK125
PG13 ------> ETH1_TXD0
PG14 ------> ETH1_TXD1
*/
GPIO_InitStruct.Pin = GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF11_ETH;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_11;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_4|GPIO_PIN_5;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_2;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_4|GPIO_PIN_5|GPIO_PIN_13|GPIO_PIN_14;
HAL_GPIO_Init(GPIOG, &GPIO_InitStruct);
/* ETH interrupt Init */
HAL_NVIC_SetPriority(ETH1_IRQn, 0x01, 0x00);
HAL_NVIC_EnableIRQ(ETH1_IRQn);
/* Configure PHY_RST (PG0) */
GPIO_InitStruct.Pin = GPIO_PIN_0;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOG, &GPIO_InitStruct);
/* Reset PHY transceiver */
HAL_GPIO_WritePin(GPIOG, GPIO_PIN_0, GPIO_PIN_RESET);
rt_thread_mdelay(20);
HAL_GPIO_WritePin(GPIOG, GPIO_PIN_0, GPIO_PIN_SET);
rt_thread_mdelay(20);
}
static rt_err_t rt_stm32_eth_init(rt_device_t dev)
{
RT_ASSERT(dev != RT_NULL);
rt_uint32_t status, i;
volatile rt_uint32_t tickstart = 0;
rt_uint8_t *macAddr = &stm32_eth_device.dev_addr[0];
/* Initialize TX descriptor index */
txIndex = 0;
/* Initialize RX descriptor index */
rxIndex = 0;
HAL_ETH_MspInit();
/* Reset Ethernet MAC peripheral */
__HAL_RCC_ETH1MAC_FORCE_RESET();
__HAL_RCC_ETH1MAC_RELEASE_RESET();
/* Ethernet Software reset */
ETH->DMAMR |= ETH_DMAMR_SWR;
/* Wait for the reset to complete */
tickstart = rt_tick_get();
while (READ_BIT(ETH->DMAMR, ETH_DMAMR_SWR))
{
if(((HAL_GetTick() - tickstart ) > ETH_TIME_OUT))
{
LOG_E("ETH software reset timeout!");
return RT_ERROR;
}
}
/* Adjust MDC clock range depending on HCLK frequency */
ETH->MACMDIOAR = ETH_MACMDIOAR_CR_Val(5);
/* Use default MAC configuration */
ETH->MACCR = ETH_MACCR_DO;
/* Set the MAC address of the station */
ETH->MACA0LR = ((macAddr[3] << 24) | (macAddr[2] << 16) | (macAddr[1] << 8) | macAddr[0]);
ETH->MACA0HR = ((macAddr[5] << 8) | macAddr[4]);
/* The MAC supports 3 additional addresses for unicast perfect filtering */
ETH->MACA1LR = 0;
ETH->MACA1HR = 0;
ETH->MACA2LR = 0;
ETH->MACA2HR = 0;
ETH->MACA3LR = 0;
ETH->MACA3HR = 0;
/* Initialize hash table */
ETH->MACHT0R = 0;
ETH->MACHT1R = 0;
/* Configure the receive filter */
ETH->MACPFR = ETH_MACPFR_HPF | ETH_MACPFR_HMC;
/* Disable flow control */
ETH->MACQ0TXFCR = 0;
ETH->MACRXFCR = 0;
/* Enable the first RX queue */
ETH->MACRXQC0R = ETH_MACRXQC0R_RXQ0EN_Val(1);
/* Configure DMA operating mode */
ETH->DMAMR = ETH_DMAMR_INTM_Val(0) | ETH_DMAMR_PR_Val(0);
/* Configure system bus mode */
ETH->DMASBMR |= ETH_DMASBMR_AAL;
/* The DMA takes the descriptor table as contiguous */
ETH->DMAC0CR = ETH_DMAC0CR_DSL_Val(0);
/* Configure TX features */
ETH->DMAC0TXCR = ETH_DMAC0TXCR_TXPBL_Val(1);
/* Configure RX features */
ETH->DMAC0RXCR = ETH_DMAC0RXCR_RXPBL_Val(1) | ETH_DMAC0RXCR_RBSZ_Val(ETH_RX_BUF_SIZE);
/* Enable store and forward mode for transmission */
ETH->MTLTXQ0OMR = ETH_MTLTXQ0OMR_TQS_Val(7) | ETH_MTLTXQ0OMR_TXQEN_Val(2) | ETH_MTLTXQ0OMR_TSF;
/* Enable store and forward mode for reception */
ETH->MTLRXQ0OMR = ETH_MTLRXQ0OMR_RQS_Val(7) | ETH_MTLRXQ0OMR_RSF;
/* Initialize TX DMA descriptor list */
for (i = 0; i < ETH_TXBUFNB; i++)
{
/* The descriptor is initially owned by the application */
txDmaDesc[i].tdes0 = 0;
txDmaDesc[i].tdes1 = 0;
txDmaDesc[i].tdes2 = 0;
txDmaDesc[i].tdes3 = 0;
}
/* Initialize RX DMA descriptor list */
for (i = 0; i < ETH_RXBUFNB; i++)
{
/* The descriptor is initially owned by the DMA */
rxDmaDesc[i].rdes0 = (uint32_t) rxBuffer[i];
rxDmaDesc[i].rdes1 = 0;
rxDmaDesc[i].rdes2 = 0;
rxDmaDesc[i].rdes3 = ETH_RDES3_OWN | ETH_RDES3_IOC | ETH_RDES3_BUF1V;
}
/* Set Transmit Descriptor List Address Register */
ETH->DMAC0TXDLAR = (uint32_t) &txDmaDesc[0];
/* Length of the transmit descriptor ring */
ETH->DMAC0TXRLR = ETH_TXBUFNB - 1;
/* Set Receive Descriptor List Address Register */
ETH->DMAC0RXDLAR = (uint32_t) &rxDmaDesc[0];
/* Length of the receive descriptor ring */
ETH->DMAC0RXRLR = ETH_RXBUFNB - 1;
/* Prevent interrupts from being generated when the transmit statistic
* counters reach half their maximum value */
ETH->MMCTXIMR = ETH_MMCTXIMR_TXLPITRCIM | ETH_MMCTXIMR_TXLPIUSCIM | ETH_MMCTXIMR_TXGPKTIM | ETH_MMCTXIMR_TXMCOLGPIM | ETH_MMCTXIMR_TXSCOLGPIM;
/* Prevent interrupts from being generated when the receive statistic
* counters reach half their maximum value */
ETH->MMCRXIMR = ETH_MMCRXIMR_RXLPITRCIM | ETH_MMCRXIMR_RXLPIUSCIM | ETH_MMCRXIMR_RXUCGPIM | ETH_MMCRXIMR_RXALGNERPIM | ETH_MMCRXIMR_RXCRCERPIM;
/* Disable MAC interrupts */
ETH->MACIER = 0;
/* Enable the desired DMA interrupts */
ETH->DMAC0IER = ETH_DMAC0IER_NIE | ETH_DMAC0IER_RIE | ETH_DMAC0IER_TIE;
/* Enable MAC transmission and reception */
ETH->MACCR |= ETH_MACCR_TE | ETH_MACCR_RE;
/* Enable DMA transmission and reception */
ETH->DMAC0TXCR |= ETH_DMAC0TXCR_ST;
ETH->DMAC0RXCR |= ETH_DMAC0RXCR_SR;
/* Reset PHY transceiver */
phy_write_reg(RTL8211F_PHY_ADDR, RTL8211F_BMCR, RTL8211F_BMCR_RESET);
status = phy_read_reg(RTL8211F_PHY_ADDR, RTL8211F_BMCR);
/* Wait for the reset to complete */
tickstart = rt_tick_get();
while (status & RTL8211F_BMCR_RESET)
{
if((rt_tick_get() - tickstart) > ETH_TIME_OUT)
{
LOG_E("PHY software reset timeout!");
return RT_ETIMEOUT;
}
else
{
status = phy_read_reg(RTL8211F_PHY_ADDR, RTL8211F_BMCR);
}
}
/* The PHY will generate interrupts when link status changes are detected */
phy_write_reg(RTL8211F_PHY_ADDR, RTL8211F_INER, RTL8211F_INER_AN_COMPLETE | RTL8211F_INER_LINK_STATUS);
return RT_EOK;
}
static rt_err_t rt_stm32_eth_open(rt_device_t dev, rt_uint16_t oflag)
{
LOG_D("emac open");
return RT_EOK;
}
static rt_err_t rt_stm32_eth_close(rt_device_t dev)
{
LOG_D("emac close");
return RT_EOK;
}
static rt_size_t rt_stm32_eth_read(rt_device_t dev, rt_off_t pos, void *buffer, rt_size_t size)
{
LOG_D("emac read");
rt_set_errno(-RT_ENOSYS);
return 0;
}
static rt_size_t rt_stm32_eth_write(rt_device_t dev, rt_off_t pos, const void *buffer, rt_size_t size)
{
LOG_D("emac write");
rt_set_errno(-RT_ENOSYS);
return 0;
}
static rt_err_t rt_stm32_eth_control(rt_device_t dev, int cmd, void *args)
{
switch (cmd)
{
case NIOCTL_GADDR:
/* get mac address */
if (args)
{
rt_memcpy(args, stm32_eth_device.dev_addr, 6);
}
else
{
return -RT_ERROR;
}
break;
default :
break;
}
return RT_EOK;
}
rt_err_t rt_stm32_eth_tx(rt_device_t dev, struct pbuf *p)
{
uint32_t framelen = 0;
struct pbuf *q = RT_NULL;
/* Copy user data to the transmit buffer */
for (q = p; q != NULL; q = q->next)
{
/* Make sure the current buffer is available for writing */
if((txDmaDesc[txIndex].tdes3 & ETH_TDES3_OWN) != 0)
{
LOG_D("buffer not valid");
return ERR_USE;
}
level = rt_hw_interrupt_disable();
rt_memcpy(&txBuffer[txIndex][framelen], q->payload, q->len);
framelen += q->len;
rt_hw_interrupt_enable(level);
/* Check the frame length */
if (framelen > ETH_TX_BUF_SIZE - 1)
{
LOG_D(" tx buffer frame length over : %d", framelen);
return ERR_USE;
}
}
#ifdef ETH_TX_DUMP
rt_kprintf("Tx dump, len= %d\r\n", framelen);
dump_hex(txBuffer[txIndex], framelen);
#endif
/* Set the start address of the buffer */
txDmaDesc[txIndex].tdes0 = (uint32_t)txBuffer[txIndex];
/* Write the number of bytes to send */
txDmaDesc[txIndex].tdes2 = ETH_TDES2_IOC | (framelen & ETH_TDES2_B1L);
/* Give the ownership of the descriptor to the DMA */
txDmaDesc[txIndex].tdes3 = ETH_TDES3_OWN | ETH_TDES3_FD | ETH_TDES3_LD;
/* Data synchronization barrier */
__DSB();
/* Clear TBU flag to resume processing */
ETH->DMAC0SR = ETH_DMAC0SR_TBU;
/* Instruct the DMA to poll the transmit descriptor list */
ETH->DMAC0TXDTPR = 0;
if (++txIndex > ETH_TXBUFNB - 1)
{
txIndex = 0;
}
return ERR_OK;
}
struct pbuf *rt_stm32_eth_rx(rt_device_t dev)
{
rt_uint32_t framelength = 0;
uint32_t framelen = 0;
struct pbuf *p = RT_NULL, *q = RT_NULL;
/* The current buffer is available for reading */
if (!(rxDmaDesc[rxIndex].rdes3 & ETH_RDES3_OWN))
{
/* FD and LD flags should be set */
if ((rxDmaDesc[rxIndex].rdes3 & ETH_RDES3_FD) && (rxDmaDesc[rxIndex].rdes3 & ETH_RDES3_LD))
{
/* Make sure no error occurred */
if(!(rxDmaDesc[rxIndex].rdes3 & ETH_RDES3_ES))
{
/* Retrieve the length of the frame */
framelength = rxDmaDesc[rxIndex].rdes3 & ETH_RDES3_PL;
/* check the frame length */
framelength = (framelength > ETH_RX_BUF_SIZE) ? ETH_RX_BUF_SIZE : framelength;
p = pbuf_alloc(PBUF_RAW, framelength, PBUF_RAM);
if (p != NULL)
{
for (q = p; q != NULL; q = q->next)
{
level=rt_hw_interrupt_disable();
rt_memcpy(q->payload, &rxBuffer[rxIndex][framelen], q->len);
framelen += q->len;
rt_hw_interrupt_enable(level);
if (framelen > framelength)
{
LOG_E("frame len is too long!");
return RT_NULL;
}
}
}
}
else
{
/* The received packet contains an error */
LOG_D("the received packet contains an error!");
return RT_NULL;
}
}
else
{
/* The packet is not valid */
LOG_D("the packet is not valid");
return RT_NULL;
}
/* Set the start address of the buffer */
rxDmaDesc[rxIndex].rdes0 = (uint32_t)rxBuffer[rxIndex];
/* Give the ownership of the descriptor back to the DMA */
rxDmaDesc[rxIndex].rdes3 = ETH_RDES3_OWN | ETH_RDES3_IOC | ETH_RDES3_BUF1V;
#ifdef ETH_RX_DUMP
rt_kprintf("Rx dump, len= %d\r\n", framelen);
dump_hex(rxBuffer[rxIndex], framelen);
#endif
/* Increment index and wrap around if necessary */
if (++rxIndex > ETH_RXBUFNB - 1)
{
rxIndex = 0;
}
/* Clear RBU flag to resume processing */
ETH->DMAC0SR = ETH_DMAC0SR_RBU;
/* Instruct the DMA to poll the receive descriptor list */
ETH->DMAC0RXDTPR = 0;
}
return p;
}
void ETH1_IRQHandler(void)
{
rt_uint32_t status = 0;
/* enter interrupt */
rt_interrupt_enter();
/* Read DMA status register */
status = ETH->DMAC0SR;
/* Frame transmitted */
if (status & ETH_DMAC0SR_TI)
{
/* Clear the Eth DMA Tx IT pending bits */
ETH->DMAC0SR = ETH_DMAC0SR_TI;
}
/* Frame received */
else if (status & ETH_DMAC0SR_RI)
{
/* Disable RIE interrupt */
ETH->DMAC0IER &= ~ETH_DMAC0IER_RIE;
rt_event_send(&rx_event, status);
}
/* ETH DMA Error */
if (status & ETH_DMAC0SR_AIS)
{
ETH->DMAC0IER &= ~ETH_DMAC0IER_AIE;
LOG_E("eth dam err");
}
/* Clear the interrupt flags */
ETH->DMAC0SR = ETH_DMAC0SR_NIS;
/* leave interrupt */
rt_interrupt_leave();
}
static void phy_linkchange()
{
rt_uint32_t status = 0;
/* Read status register to acknowledge the interrupt */
status = phy_read_reg(RTL8211F_PHY_ADDR, RTL8211F_INSR);
if (status & (RTL8211F_BMSR_LINK_STATUS | RTL8211F_INSR_AN_COMPLETE))
{
status = phy_read_reg(RTL8211F_PHY_ADDR, RTL8211F_BMSR);
status = phy_read_reg(RTL8211F_PHY_ADDR, RTL8211F_BMSR);
if (status & RTL8211F_BMSR_LINK_STATUS)
{
LOG_D("link up");
status = phy_read_reg(RTL8211F_PHY_ADDR, RTL8211F_PHYSR);
switch (status & RTL8211F_PHYSR_SPEED)
{
case RTL8211F_PHYSR_SPEED_10MBPS:
{
LOG_D("speed: 10M");
stm32_eth_device.eth_speed |= PHY_10M;
}
break;
case RTL8211F_PHYSR_SPEED_100MBPS:
{
LOG_D("speed: 100M");
stm32_eth_device.eth_speed |= PHY_100M;
}
break;
case RTL8211F_PHYSR_SPEED_1000MBPS:
{
LOG_D("speed: 1000M");
stm32_eth_device.eth_speed |= PHY_1000M;
}
break;
/* Unknown speed */
default:
rt_kprintf("Invalid speed.");
break;
}
stm32_eth_device.eth_mode = (status & RTL8211F_PHYSR_DUPLEX)? PHY_FULL_DUPLEX : PHY_HALF_DUPLEX ;
update_mac_mode(stm32_eth_device.eth_speed, stm32_eth_device.eth_mode);
/* send link up. */
eth_device_linkchange(&stm32_eth_device.parent, RT_TRUE);
}
else
{
LOG_I("link down");
eth_device_linkchange(&stm32_eth_device.parent, RT_FALSE);
}
}
}
#ifdef PHY_USING_INTERRUPT_MODE
static void eth_phy_isr(void *args)
{
rt_uint32_t status = 0;
phy_read_reg(RTL8211F_PHY_ADDR, PHY_INTERRUPT_FLAG_REG, (uint32_t *)&status);
LOG_D("phy interrupt status reg is 0x%X", status);
phy_linkchange();
}
#endif /* PHY_USING_INTERRUPT_MODE */
static void phy_monitor_thread_entry(void *parameter)
{
rt_uint32_t status = 0;
phy_linkchange();
#ifdef PHY_USING_INTERRUPT_MODE
/* configuration intterrupt pin */
rt_pin_mode(PHY_INT_PIN, PIN_MODE_INPUT_PULLUP);
rt_pin_attach_irq(PHY_INT_PIN, PIN_IRQ_MODE_FALLING, eth_phy_isr, (void *)"callbackargs");
rt_pin_irq_enable(PHY_INT_PIN, PIN_IRQ_ENABLE);
/* enable phy interrupt */
phy_write_reg(RTL8211F_PHY_ADDR, PHY_INTERRUPT_MASK_REG, PHY_INT_MASK);
#if defined(PHY_INTERRUPT_CTRL_REG)
phy_write_reg( RTL8211F_PHY_ADDR, PHY_INTERRUPT_CTRL_REG, PHY_INTERRUPT_EN);
#endif
#else /* PHY_USING_INTERRUPT_MODE */
stm32_eth_device.poll_link_timer = rt_timer_create("phylnk", (void (*)(void*))phy_linkchange,
NULL, RT_TICK_PER_SECOND, RT_TIMER_FLAG_PERIODIC);
if (!stm32_eth_device.poll_link_timer || rt_timer_start(stm32_eth_device.poll_link_timer) != RT_EOK)
{
LOG_E("Start link change detection timer failed");
}
#endif /* PHY_USING_INTERRUPT_MODE */
while(1)
{
if (rt_event_recv(&rx_event, 0xffffffff, RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR,
RT_WAITING_FOREVER, &status) == RT_EOK)
{
/* check dma rx buffer */
if (ETH->DMAC0SR & ETH_DMAC0SR_RI)
{
/* Clear interrupt flag */
ETH->DMAC0SR = ETH_DMAC0SR_RI;
/* Process all pending packets */
while (rxDmaDesc[rxIndex].rdes3 & ETH_RDES3_PL)
{
/* trigger lwip receive thread */
eth_device_ready(&(stm32_eth_device.parent));
}
}
/* enable DMA interrupts */
ETH->DMAC0IER = ETH_DMAC0IER_NIE | ETH_DMAC0IER_RIE | ETH_DMAC0IER_TIE;
}
}
}
/* Register the EMAC device */
static int rt_hw_stm32_eth_init(void)
{
rt_err_t state = RT_EOK;
/* OUI 00-80-E1 STMICROELECTRONICS. */
stm32_eth_device.dev_addr[0] = 0x00;
stm32_eth_device.dev_addr[1] = 0x80;
stm32_eth_device.dev_addr[2] = 0xE1;
/* generate MAC addr from 96bit unique ID (only for test). */
stm32_eth_device.dev_addr[3] = *(rt_uint8_t *)(UID_BASE + 4);
stm32_eth_device.dev_addr[4] = *(rt_uint8_t *)(UID_BASE + 2);
stm32_eth_device.dev_addr[5] = *(rt_uint8_t *)(UID_BASE + 0);
stm32_eth_device.parent.parent.init = rt_stm32_eth_init;
stm32_eth_device.parent.parent.open = rt_stm32_eth_open;
stm32_eth_device.parent.parent.close = rt_stm32_eth_close;
stm32_eth_device.parent.parent.read = rt_stm32_eth_read;
stm32_eth_device.parent.parent.write = rt_stm32_eth_write;
stm32_eth_device.parent.parent.control = rt_stm32_eth_control;
stm32_eth_device.parent.parent.user_data = RT_NULL;
stm32_eth_device.parent.eth_rx = rt_stm32_eth_rx;
stm32_eth_device.parent.eth_tx = rt_stm32_eth_tx;
rt_event_init(&rx_event, "eth_rx", RT_IPC_FLAG_FIFO);
/* register eth device */
state = eth_device_init(&(stm32_eth_device.parent), "e0");
if (RT_EOK == state)
{
LOG_D("emac device init success");
}
else
{
LOG_E("emac device init faild: %d", state);
state = -RT_ERROR;
}
/* start phy monitor */
rt_thread_t tid;
tid = rt_thread_create("phy",
phy_monitor_thread_entry,
RT_NULL,
1024,
RT_THREAD_PRIORITY_MAX - 2,
2);
if (tid != RT_NULL)
{
rt_thread_startup(tid);
}
else
{
state = -RT_ERROR;
}
return state;
}
INIT_DEVICE_EXPORT(rt_hw_stm32_eth_init);
#endif

View File

@ -0,0 +1,404 @@
/*
* Copyright (c) 2006-2018, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2020-07-20 thread-liu the first version
*/
#ifndef __DRV_ETH_H__
#define __DRV_ETH_H__
#include <rtthread.h>
#include <rthw.h>
#include <rtdevice.h>
#include <board.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct
{
uint32_t Speed; /*!< Sets the Ethernet speed: 10/100/1000 Mbps.
This parameter can be a value of @ref ETH_Speed */
uint32_t DuplexMode; /*!< Selects the MAC duplex mode: Half-Duplex or Full-Duplex mode
This parameter can be a value of @ref ETH_Duplex_Mode */
} ETH_MACConfigTypeDef;
/**
* @brief Transmit descriptor
**/
typedef struct
{
uint32_t tdes0;
uint32_t tdes1;
uint32_t tdes2;
uint32_t tdes3;
} TxDmaDesc;
/**
* @brief Receive descriptor
**/
typedef struct
{
uint32_t rdes0;
uint32_t rdes1;
uint32_t rdes2;
uint32_t rdes3;
} RxDmaDesc;
enum {
PHY_LINK = (1 << 0),
PHY_10M = (1 << 1),
PHY_100M = (1 << 2),
PHY_1000M = (1 << 3),
PHY_FULL_DUPLEX = (1 << 4),
PHY_HALF_DUPLEX = (1 << 5)
};
#define RTL8211F_PHY_ADDR 1 /* PHY address */
#define ETH_TXBUFNB 4 /* 4 Tx buffers of size ETH_TX_BUF_SIZE */
#define ETH_TX_BUF_SIZE 1536 /* buffer size for transmit */
#define ETH_RXBUFNB 4 /* 4 Rx buffers of size ETH_RX_BUF_SIZE */
#define ETH_RX_BUF_SIZE 1536 /* buffer size for receive */
#define ETH_MMC_INTERRUPT_MASK_TXLPITRCIM_Msk ETH_MMCTXIMR_TXLPITRCIM_Msk /* ETH_MMCTXIMR register */
/* Register access macros */
#define ETH_MACRXQC0R_RXQ0EN_Val(n) (((n) << ETH_MACRXQC0R_RXQ0EN_Pos) & ETH_MACRXQC0R_RXQ0EN_Msk)
#define ETH_MACMDIOAR_CR_Val(n) (((n) << ETH_MACMDIOAR_CR_Pos) & ETH_MACMDIOAR_CR_Msk)
#define ETH_MACMDIOAR_GOC_Val(n) (((n) << ETH_MACMDIOAR_GOC_Pos) & ETH_MACMDIOAR_GOC_Msk)
#define ETH_MTLTXQ0OMR_TQS_Val(n) (((n) << ETH_MTLTXQ0OMR_TQS_Pos) & ETH_MTLTXQ0OMR_TQS_Msk)
#define ETH_MTLTXQ0OMR_TXQEN_Val(n) (((n) << ETH_MTLTXQ0OMR_TXQEN_Pos) & ETH_MTLTXQ0OMR_TXQEN_Msk)
#define ETH_MTLRXQ0OMR_RQS_Val(n) (((n) << ETH_MTLRXQ0OMR_RQS_Pos) & ETH_MTLRXQ0OMR_RQS_Msk)
#define ETH_DMAMR_INTM_Val(n) (((n) << ETH_DMAMR_INTM_Pos) & ETH_DMAMR_INTM_Msk)
#define ETH_DMAMR_PR_Val(n) (((n) << ETH_DMAMR_PR_Pos) & ETH_DMAMR_PR_Msk)
#define ETH_DMAC0CR_DSL_Val(n) (((n) << ETH_DMAC0CR_DSL_Pos) & ETH_DMAC0CR_DSL_Msk)
#define ETH_DMAC0TXCR_TXPBL_Val(n) (((n) << ETH_DMAC0TXCR_TXPBL_Pos) & ETH_DMAC0TXCR_TXPBL_Msk)
#define ETH_DMAC0RXCR_RXPBL_Val(n) (((n) << ETH_DMAC0RXCR_RXPBL_Pos) & ETH_DMAC0RXCR_RXPBL_Msk)
#define ETH_DMAC0RXCR_RBSZ_Val(n) (((n) << ETH_DMAC0RXCR_RBSZ_Pos) & ETH_DMAC0RXCR_RBSZ_Msk)
/* Transmit normal descriptor (read format) */
#define ETH_TDES0_BUF1AP 0xFFFFFFFF
#define ETH_TDES1_BUF2AP 0xFFFFFFFF
#define ETH_TDES2_IOC 0x80000000
#define ETH_TDES2_TTSE 0x40000000
#define ETH_TDES2_B2L 0x3FFF0000
#define ETH_TDES2_VTIR 0x0000C000
#define ETH_TDES2_B1L 0x00003FFF
#define ETH_TDES3_OWN 0x80000000
#define ETH_TDES3_CTXT 0x40000000
#define ETH_TDES3_FD 0x20000000
#define ETH_TDES3_LD 0x10000000
#define ETH_TDES3_CPC 0x0C000000
#define ETH_TDES3_SAIC 0x03800000
#define ETH_TDES3_THL 0x00780000
#define ETH_TDES3_TSE 0x00040000
#define ETH_TDES3_CIC 0x00030000
#define ETH_TDES3_FL 0x00007FFF
/* Transmit normal descriptor (write-back format) */
#define ETH_TDES0_TTSL 0xFFFFFFFF
#define ETH_TDES1_TTSH 0xFFFFFFFF
#define ETH_TDES3_OWN 0x80000000
#define ETH_TDES3_CTXT 0x40000000
#define ETH_TDES3_FD 0x20000000
#define ETH_TDES3_LD 0x10000000
#define ETH_TDES3_TTSS 0x00020000
#define ETH_TDES3_ES 0x00008000
#define ETH_TDES3_JT 0x00004000
#define ETH_TDES3_FF 0x00002000
#define ETH_TDES3_PCE 0x00001000
#define ETH_TDES3_LOC 0x00000800
#define ETH_TDES3_NC 0x00000400
#define ETH_TDES3_LC 0x00000200
#define ETH_TDES3_EC 0x00000100
#define ETH_TDES3_CC 0x000000F0
#define ETH_TDES3_ED 0x00000008
#define ETH_TDES3_UF 0x00000004
#define ETH_TDES3_DB 0x00000002
#define ETH_TDES3_IHE 0x00000001
/* Transmit context descriptor */
#define ETH_TDES0_TTSL 0xFFFFFFFF
#define ETH_TDES1_TTSH 0xFFFFFFFF
#define ETH_TDES2_IVT 0xFFFF0000
#define ETH_TDES2_MSS 0x00003FFF
#define ETH_TDES3_OWN 0x80000000
#define ETH_TDES3_CTXT 0x40000000
#define ETH_TDES3_OSTC 0x08000000
#define ETH_TDES3_TCMSSV 0x04000000
#define ETH_TDES3_CDE 0x00800000
#define ETH_TDES3_IVLTV 0x00020000
#define ETH_TDES3_VLTV 0x00010000
#define ETH_TDES3_VT 0x0000FFFF
/* Receive normal descriptor (read format) */
#define ETH_RDES0_BUF1AP 0xFFFFFFFF
#define ETH_RDES2_BUF2AP 0xFFFFFFFF
#define ETH_RDES3_OWN 0x80000000
#define ETH_RDES3_IOC 0x40000000
#define ETH_RDES3_BUF2V 0x02000000
#define ETH_RDES3_BUF1V 0x01000000
/* Receive normal descriptor (write-back format) */
#define ETH_RDES0_IVT 0xFFFF0000
#define ETH_RDES0_OVT 0x0000FFFF
#define ETH_RDES1_OPC 0xFFFF0000
#define ETH_RDES1_TD 0x00008000
#define ETH_RDES1_TSA 0x00004000
#define ETH_RDES1_PV 0x00002000
#define ETH_RDES1_PFT 0x00001000
#define ETH_RDES1_PMT 0x00000F00
#define ETH_RDES1_IPCE 0x00000080
#define ETH_RDES1_IPCB 0x00000040
#define ETH_RDES1_IPV6 0x00000020
#define ETH_RDES1_IPV4 0x00000010
#define ETH_RDES1_IPHE 0x00000008
#define ETH_RDES1_PT 0x00000007
#define ETH_RDES2_L3L4FM 0xE0000000
#define ETH_RDES2_L4FM 0x10000000
#define ETH_RDES2_L3FM 0x08000000
#define ETH_RDES2_MADRM 0x07F80000
#define ETH_RDES2_HF 0x00040000
#define ETH_RDES2_DAF 0x00020000
#define ETH_RDES2_SAF 0x00010000
#define ETH_RDES2_VF 0x00008000
#define ETH_RDES2_ARPRN 0x00000400
#define ETH_RDES3_OWN 0x80000000
#define ETH_RDES3_CTXT 0x40000000
#define ETH_RDES3_FD 0x20000000
#define ETH_RDES3_LD 0x10000000
#define ETH_RDES3_RS2V 0x08000000
#define ETH_RDES3_RS1V 0x04000000
#define ETH_RDES3_RS0V 0x02000000
#define ETH_RDES3_CE 0x01000000
#define ETH_RDES3_GP 0x00800000
#define ETH_RDES3_RWT 0x00400000
#define ETH_RDES3_OE 0x00200000
#define ETH_RDES3_RE 0x00100000
#define ETH_RDES3_DE 0x00080000
#define ETH_RDES3_LT 0x00070000
#define ETH_RDES3_ES 0x00008000
#define ETH_RDES3_PL 0x00007FFF
/* Receive context descriptor */
#define ETH_RDES0_RTSL 0xFFFFFFFF
#define ETH_RDES1_RTSH 0xFFFFFFFF
#define ETH_RDES3_OWN 0x80000000
#define ETH_RDES3_CTXT 0x40000000
#define RTL8211F_BMCR ((uint16_t)0x0000U) /* Basic Mode Control Register. */
#define RTL8211F_BMSR ((uint16_t)0x0001U) /* Basic Mode Status Register. */
#define RTL8211F_PHYID1 ((uint16_t)0x0002U) /* PHY Identifier Register 1. */
#define RTL8211F_PHYID2 ((uint16_t)0x0003U) /* PHY Identifier Register 2. */
#define RTL8211F_ANAR ((uint16_t)0x0004U) /* Auto-Negotiation Advertising Register. */
#define RTL8211F_ANLPAR ((uint16_t)0x0005U) /* Auto-Negotiation Link Partner Ability Register. */
#define RTL8211F_ANER ((uint16_t)0x0006U) /* Auto-Negotiation Expansion Register.*/
#define RTL8211F_ANNPTR ((uint16_t)0x0007U) /* Auto-Negotiation Next Page Transmit Register.*/
#define RTL8211F_ANNPRR ((uint16_t)0x0008U) /* Auto-Negotiation Next Page Receive Register. */
#define RTL8211F_GBCR ((uint16_t)0x0009U) /* 1000Base-T Control Register. */
#define RTL8211F_GBSR ((uint16_t)0x000AU) /* 1000Base-T Status Register. */
#define RTL8211F_MMDACR ((uint16_t)0x000DU) /* MMD Access Control Register. */
#define RTL8211F_MMDAADR ((uint16_t)0x000EU) /* MMD Access Address Data Register. */
#define RTL8211F_GBESR ((uint16_t)0x000FU) /* 1000Base-T Extended Status Register. */
#define RTL8211F_LCR ((uint16_t)0x0010U) /* LED Control Register. */
#define RTL8211F_INER ((uint16_t)0x0012U) /* Interrupt Enable Register. */
#define RTL8211F_PHYSCR ((uint16_t)0x0014U) /* PHY Special Cofig Register */
#define RTL8211F_PHYCR1 ((uint16_t)0x0018U) /* PHY Specific Control Register 1. */
#define RTL8211F_PHYCR2 ((uint16_t)0x0019U) /* PHY Specific Control Register 2. */
#define RTL8211F_PHYSR ((uint16_t)0x001AU) /* PHY Specific Status Register. */
#define RTL8211F_INSR ((uint16_t)0x001DU) /* Interrupt Status Register. */
#define RTL8211F_PAGSR ((uint16_t)0x001FU) /* Page Select Register. */
/* Basic Mode Control register */
#define RTL8211F_BMCR_RESET 0x8000
#define RTL8211F_BMCR_LOOPBACK 0x4000
#define RTL8211F_BMCR_SPEED_SEL_LSB 0x2000
#define RTL8211F_BMCR_AN_EN 0x1000
#define RTL8211F_BMCR_POWER_DOWN 0x0800
#define RTL8211F_BMCR_ISOLATE 0x0400
#define RTL8211F_BMCR_RESTART_AN 0x0200
#define RTL8211F_BMCR_DUPLEX_MODE 0x0100
#define RTL8211F_BMCR_COL_TEST 0x0080
#define RTL8211F_BMCR_SPEED_SEL_MSB 0x0040
#define RTL8211F_BMCR_UNI_DIR_EN 0x0020
/* Basic Mode Status register */
#define RTL8211F_BMSR_100BT4 0x8000
#define RTL8211F_BMSR_100BTX_FD 0x4000
#define RTL8211F_BMSR_100BTX_HD 0x2000
#define RTL8211F_BMSR_10BT_FD 0x1000
#define RTL8211F_BMSR_10BT_HD 0x0800
#define RTL8211F_BMSR_100BT2_FD 0x0400
#define RTL8211F_BMSR_100BT2_HD 0x0200
#define RTL8211F_BMSR_EXTENDED_STATUS 0x0100
#define RTL8211F_BMSR_UNI_DIR_CAPABLE 0x0080
#define RTL8211F_BMSR_PREAMBLE_SUPPR 0x0040
#define RTL8211F_BMSR_AN_COMPLETE 0x0020
#define RTL8211F_BMSR_REMOTE_FAULT 0x0010
#define RTL8211F_BMSR_AN_CAPABLE 0x0008
#define RTL8211F_BMSR_LINK_STATUS 0x0004
#define RTL8211F_BMSR_JABBER_DETECT 0x0002
#define RTL8211F_BMSR_EXTENDED_CAPABLE 0x0001
/* PHY Identifier 1 register */
#define RTL8211F_PHYID1_OUI_MSB 0xFFFF
#define RTL8211F_PHYID1_OUI_MSB_DEFAULT 0x001C
/* PHY Identifier 2 register */
#define RTL8211F_PHYID2_OUI_LSB 0xFC00
#define RTL8211F_PHYID2_OUI_LSB_DEFAULT 0xC800
#define RTL8211F_PHYID2_MODEL_NUM 0x03F0
#define RTL8211F_PHYID2_MODEL_NUM_DEFAULT 0x0110
#define RTL8211F_PHYID2_REVISION_NUM 0x000F
#define RTL8211F_PHYID2_REVISION_NUM_DEFAULT 0x0006
/* Auto-Negotiation Advertisement register */
#define RTL8211F_ANAR_NEXT_PAGE 0x8000
#define RTL8211F_ANAR_REMOTE_FAULT 0x2000
#define RTL8211F_ANAR_ASYM_PAUSE 0x0800
#define RTL8211F_ANAR_PAUSE 0x0400
#define RTL8211F_ANAR_100BT4 0x0200
#define RTL8211F_ANAR_100BTX_FD 0x0100
#define RTL8211F_ANAR_100BTX_HD 0x0080
#define RTL8211F_ANAR_10BT_FD 0x0040
#define RTL8211F_ANAR_10BT_HD 0x0020
#define RTL8211F_ANAR_SELECTOR 0x001F
#define RTL8211F_ANAR_SELECTOR_DEFAULT 0x0001
/* Auto-Negotiation Link Partner Ability register */
#define RTL8211F_ANLPAR_NEXT_PAGE 0x8000
#define RTL8211F_ANLPAR_ACK 0x4000
#define RTL8211F_ANLPAR_REMOTE_FAULT 0x2000
#define RTL8211F_ANLPAR_ASYM_PAUSE 0x0800
#define RTL8211F_ANLPAR_PAUSE 0x0400
#define RTL8211F_ANLPAR_100BT4 0x0200
#define RTL8211F_ANLPAR_100BTX_FD 0x0100
#define RTL8211F_ANLPAR_100BTX_HD 0x0080
#define RTL8211F_ANLPAR_10BT_FD 0x0040
#define RTL8211F_ANLPAR_10BT_HD 0x0020
#define RTL8211F_ANLPAR_SELECTOR 0x001F
#define RTL8211F_ANLPAR_SELECTOR_DEFAULT 0x0001
/* Auto-Negotiation Expansion register */
#define RTL8211F_ANER_RX_NP_LOCATION_ABLE 0x0040
#define RTL8211F_ANER_RX_NP_LOCATION 0x0020
#define RTL8211F_ANER_PAR_DETECT_FAULT 0x0010
#define RTL8211F_ANER_LP_NEXT_PAGE_ABLE 0x0008
#define RTL8211F_ANER_NEXT_PAGE_ABLE 0x0004
#define RTL8211F_ANER_PAGE_RECEIVED 0x0002
#define RTL8211F_ANER_LP_AN_ABLE 0x0001
/* Auto-Negotiation Next Page Transmit register */
#define RTL8211F_ANNPTR_NEXT_PAGE 0x8000
#define RTL8211F_ANNPTR_MSG_PAGE 0x2000
#define RTL8211F_ANNPTR_ACK2 0x1000
#define RTL8211F_ANNPTR_TOGGLE 0x0800
#define RTL8211F_ANNPTR_MESSAGE 0x07FF
/* Auto-Negotiation Next Page Receive register */
#define RTL8211F_ANNPRR_NEXT_PAGE 0x8000
#define RTL8211F_ANNPRR_ACK 0x4000
#define RTL8211F_ANNPRR_MSG_PAGE 0x2000
#define RTL8211F_ANNPRR_ACK2 0x1000
#define RTL8211F_ANNPRR_TOGGLE 0x0800
#define RTL8211F_ANNPRR_MESSAGE 0x07FF
/* 1000Base-T Control register */
#define RTL8211F_GBCR_TEST_MODE 0xE000
#define RTL8211F_GBCR_MS_MAN_CONF_EN 0x1000
#define RTL8211F_GBCR_MS_MAN_CONF_VAL 0x0800
#define RTL8211F_GBCR_PORT_TYPE 0x0400
#define RTL8211F_GBCR_1000BT_FD 0x0200
/* 1000Base-T Status register */
#define RTL8211F_GBSR_MS_CONF_FAULT 0x8000
#define RTL8211F_GBSR_MS_CONF_RES 0x4000
#define RTL8211F_GBSR_LOCAL_RECEIVER_STATUS 0x2000
#define RTL8211F_GBSR_REMOTE_RECEIVER_STATUS 0x1000
#define RTL8211F_GBSR_LP_1000BT_FD 0x0800
#define RTL8211F_GBSR_LP_1000BT_HD 0x0400
#define RTL8211F_GBSR_IDLE_ERR_COUNT 0x00FF
/* MMD Access Control register */
#define RTL8211F_MMDACR_FUNC 0xC000
#define RTL8211F_MMDACR_FUNC_ADDR 0x0000
#define RTL8211F_MMDACR_FUNC_DATA_NO_POST_INC 0x4000
#define RTL8211F_MMDACR_FUNC_DATA_POST_INC_RW 0x8000
#define RTL8211F_MMDACR_FUNC_DATA_POST_INC_W 0xC000
#define RTL8211F_MMDACR_DEVAD 0x001F
/* 1000Base-T Extended Status register */
#define RTL8211F_GBESR_1000BX_FD 0x8000
#define RTL8211F_GBESR_1000BX_HD 0x4000
#define RTL8211F_GBESR_1000BT_FD 0x2000
#define RTL8211F_GBESR_1000BT_HD 0x1000
/* Interrupt Enable register */
#define RTL8211F_INER_JABBER 0x0400
#define RTL8211F_INER_ALDPS_STATE 0x0200
#define RTL8211F_INER_PME 0x0080
#define RTL8211F_INER_PHY_REG_ACCESS 0x0020
#define RTL8211F_INER_LINK_STATUS 0x0010
#define RTL8211F_INER_AN_COMPLETE 0x0008
#define RTL8211F_INER_PAGE_RECEIVED 0x0004
#define RTL8211F_INER_AN_ERROR 0x0001
/* PHY Specific Control 1 register */
#define RTL8211F_PHYCR1_PHYAD_0_EN 0x2000
#define RTL8211F_PHYCR1_MDI_MODE_MANUAL_CONFIG 0x0200
#define RTL8211F_PHYCR1_MDI_MODE 0x0100
#define RTL8211F_PHYCR1_TX_CRS_EN 0x0080
#define RTL8211F_PHYCR1_PHYAD_NON_ZERO_DETECT 0x0040
#define RTL8211F_PHYCR1_PREAMBLE_CHECK_EN 0x0010
#define RTL8211F_PHYCR1_JABBER_DETECT_EN 0x0008
#define RTL8211F_PHYCR1_ALDPS_EN 0x0004
/* PHY Specific Control 2 register */
#define RTL8211F_PHYCR2_CLKOUT_FREQ_SEL 0x0800
#define RTL8211F_PHYCR2_CLKOUT_SSC_EN 0x0080
#define RTL8211F_PHYCR2_RXC_SSC_EN 0x0008
#define RTL8211F_PHYCR2_RXC_EN 0x0002
#define RTL8211F_PHYCR2_CLKOUT_EN 0x0001
/* PHY Specific Status register */
#define RTL8211F_PHYSR_ALDPS_STATE 0x4000
#define RTL8211F_PHYSR_MDI_PLUG 0x2000
#define RTL8211F_PHYSR_NWAY_EN 0x1000
#define RTL8211F_PHYSR_MASTER_MODE 0x0800
#define RTL8211F_PHYSR_EEE_CAPABLE 0x0100
#define RTL8211F_PHYSR_RX_FLOW_EN 0x0080
#define RTL8211F_PHYSR_TX_FLOW_EN 0x0040
#define RTL8211F_PHYSR_SPEED 0x0030
#define RTL8211F_PHYSR_SPEED_10MBPS 0x0000
#define RTL8211F_PHYSR_SPEED_100MBPS 0x0010
#define RTL8211F_PHYSR_SPEED_1000MBPS 0x0020
#define RTL8211F_PHYSR_DUPLEX 0x0008
#define RTL8211F_PHYSR_LINK 0x0004
#define RTL8211F_PHYSR_MDI_CROSSOVER_STATUS 0x0002
#define RTL8211F_PHYSR_JABBER 0x0001
/* Interrupt Status register */
#define RTL8211F_INSR_JABBER 0x0400
#define RTL8211F_INSR_ALDPS_STATE 0x0200
#define RTL8211F_INSR_PME 0x0080
#define RTL8211F_INSR_PHY_REG_ACCESS 0x0020
#define RTL8211F_INSR_LINK_STATUS 0x0010
#define RTL8211F_INSR_AN_COMPLETE 0x0008
#define RTL8211F_INSR_PAGE_RECEIVED 0x0004
#define RTL8211F_INSR_AN_ERROR 0x0001
/* Page Select register */
#define RTL8211F_PAGSR_PAGE_SEL 0x0007
#ifdef __cplusplus
}
#endif
#endif

View File

@ -19,6 +19,8 @@
#define LOG_TAG "drv.pmic"
#include <drv_log.h>
#define I2C_NAME "i2c3"
static struct rt_i2c_bus_device *pmic_dev = RT_NULL;
/* i2c read reg */
@ -796,47 +798,47 @@ static rt_err_t rt_hw_pmic_init_register(void)
stpmu1_write_reg(BUCK_ICC_TURNOFF_REG, 0x30);
stpmu1_write_reg(LDO_ICC_TURNOFF_REG, 0x3b);
/* vddcore */
STPMU1_Regulator_Voltage_Set(STPMU1_BUCK1, 1200);
STPMU1_Regulator_Enable(STPMU1_BUCK1);
/* vddcore */
STPMU1_Regulator_Voltage_Set(STPMU1_BUCK1, 1200);
STPMU1_Regulator_Enable(STPMU1_BUCK1);
/* vddddr */
STPMU1_Regulator_Voltage_Set(STPMU1_BUCK2, 1350);
STPMU1_Regulator_Enable(STPMU1_BUCK2);
/* vddddr */
STPMU1_Regulator_Voltage_Set(STPMU1_BUCK2, 1350);
STPMU1_Regulator_Enable(STPMU1_BUCK2);
/* vdd */
STPMU1_Regulator_Voltage_Set(STPMU1_BUCK3, 3300);
STPMU1_Regulator_Enable(STPMU1_BUCK3);
/* vdd */
STPMU1_Regulator_Voltage_Set(STPMU1_BUCK3, 3300);
STPMU1_Regulator_Enable(STPMU1_BUCK3);
/* 3v3 */
STPMU1_Regulator_Voltage_Set(STPMU1_BUCK4, 3300);
STPMU1_Regulator_Enable(STPMU1_BUCK4);
// /* 3v3 */
// STPMU1_Regulator_Voltage_Set(STPMU1_BUCK4, 3300);
// STPMU1_Regulator_Enable(STPMU1_BUCK4);
/* vdda */
STPMU1_Regulator_Voltage_Set(STPMU1_LDO1, 2900);
STPMU1_Regulator_Enable(STPMU1_LDO1);
/* 1v8_audio */
STPMU1_Regulator_Voltage_Set(STPMU1_LDO1, 1800);
STPMU1_Regulator_Enable(STPMU1_LDO1);
/* 2v8 */
STPMU1_Regulator_Voltage_Set(STPMU1_LDO2, 2800);
STPMU1_Regulator_Enable(STPMU1_LDO2);
/* vdd_emmc */
STPMU1_Regulator_Voltage_Set(STPMU1_LDO2, 2900);
STPMU1_Regulator_Enable(STPMU1_LDO2);
/* vtt_ddr lod3 mode buck2/2 */
STPMU1_Regulator_Voltage_Set(STPMU1_LDO3, 0xFFFF);
STPMU1_Regulator_Enable(STPMU1_LDO3);
/* vdd1_ddr */
STPMU1_Regulator_Voltage_Set(STPMU1_LDO3, 0xFFFF);
STPMU1_Regulator_Enable(STPMU1_LDO3);
/* vdd_usb */
STPMU1_Regulator_Voltage_Set(STPMU1_LDO4, 3300);
STPMU1_Regulator_Enable(STPMU1_LDO4);
/* vdd_usb */
STPMU1_Regulator_Voltage_Set(STPMU1_LDO4, 3300);
STPMU1_Regulator_Enable(STPMU1_LDO4);
/* vdd_sd */
STPMU1_Regulator_Voltage_Set(STPMU1_LDO5, 2900);
STPMU1_Regulator_Enable(STPMU1_LDO5);
/* vdda */
STPMU1_Regulator_Voltage_Set(STPMU1_LDO5, 2900);
STPMU1_Regulator_Enable(STPMU1_LDO5);
/* 1v8 */
STPMU1_Regulator_Voltage_Set(STPMU1_LDO6, 1800);
STPMU1_Regulator_Enable(STPMU1_LDO6);
/* 2v8 */
STPMU1_Regulator_Voltage_Set(STPMU1_LDO6, 2800);
STPMU1_Regulator_Enable(STPMU1_LDO6);
STPMU1_Regulator_Enable(STPMU1_VREFDDR);
STPMU1_Regulator_Enable(STPMU1_VREFDDR);
return RT_EOK;
}
@ -884,7 +886,7 @@ static int pmic_init(void)
{
BSP_PMIC_MspInit();
result = rt_hw_pmic_init("i2c3");
result = rt_hw_pmic_init(I2C_NAME);
if(result != RT_EOK)
{
LOG_D("stpmic init failed: %02x", result);
@ -893,10 +895,7 @@ static int pmic_init(void)
}
rt_hw_pmic_init_register();
}
if(IS_ENGINEERING_BOOT_MODE())
{
__HAL_RCC_VREF_CLK_ENABLE();
HAL_SYSCFG_VREFBUF_HighImpedanceConfig(SYSCFG_VREFBUF_HIGH_IMPEDANCE_DISABLE);
HAL_SYSCFG_EnableVREFBUF();

View File

@ -0,0 +1,555 @@
/*
* Copyright (c) 2006-2020, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2020-07-16 thread-liu first version
*/
#include "board.h"
#include "drv_sdio.h"
#include <dfs_fs.h>
#ifdef BSP_USING_SDMMC
//#define DRV_DEBUG
#define DBG_TAG "drv.sdio"
#ifdef DRV_DEBUG
#define DBG_LVL DBG_LOG
#else
#define DBG_LVL DBG_INFO
#endif /* DRV_DEBUG */
#include <rtdbg.h>
static SD_HandleTypeDef hsd;
static struct rt_mmcsd_host *host;
#define SDIO_TX_RX_COMPLETE_TIMEOUT_LOOPS (100000)
#define RTHW_SDIO_LOCK(_sdio) rt_mutex_take(&_sdio->mutex, RT_WAITING_FOREVER)
#define RTHW_SDIO_UNLOCK(_sdio) rt_mutex_release(&_sdio->mutex);
struct sdio_pkg
{
struct rt_mmcsd_cmd *cmd;
void *buff;
rt_uint32_t flag;
};
struct rthw_sdio
{
struct rt_mmcsd_host *host;
struct stm32_sdio_des sdio_des;
struct rt_event event;
struct rt_mutex mutex;
struct sdio_pkg *pkg;
};
/* SYSRAM SDMMC1/2 accesses */
#if defined(__CC_ARM) || defined(__CLANG_ARM)
rt_uint8_t cache_buf[SDIO_BUFF_SIZE] __attribute__((at(0x2FFC0000)));
#elif defined(__ICCARM__)
#pragma location=0x2FFC0000
rt_uint8_t cache_buf[SDIO_BUFF_SIZE];
#elif defined(__GNUC__)
rt_uint8_t cache_buf[SDIO_BUFF_SIZE] __attribute__((at(0x2FFC0000)));
#endif
/**
* @brief This function get order from sdio.
* @param data
* @retval sdio order
*/
static int get_order(rt_uint32_t data)
{
int order = 0;
switch (data)
{
case 1:
order = 0;
break;
case 2:
order = 1;
break;
case 4:
order = 2;
break;
case 8:
order = 3;
break;
case 16:
order = 4;
break;
case 32:
order = 5;
break;
case 64:
order = 6;
break;
case 128:
order = 7;
break;
case 256:
order = 8;
break;
case 512:
order = 9;
break;
case 1024:
order = 10;
break;
case 2048:
order = 11;
break;
case 4096:
order = 12;
break;
case 8192:
order = 13;
break;
case 16384:
order = 14;
break;
default :
order = 0;
break;
}
return order;
}
/**
* @brief This function wait sdio cmd completed.
* @param sdio rthw_sdio
* @retval None
*/
static void rthw_sdio_wait_completed(struct rthw_sdio *sdio)
{
rt_uint32_t status;
struct rt_mmcsd_cmd *cmd = sdio->pkg->cmd;
struct rt_mmcsd_data *data = cmd->data;
struct stm32_sdio *hw_sdio = sdio->sdio_des.hw_sdio;
if (rt_event_recv(&sdio->event, 0xffffffff, RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR,
rt_tick_from_millisecond(5000), &status) != RT_EOK)
{
LOG_E("wait cmd completed timeout");
cmd->err = -RT_ETIMEOUT;
return;
}
if (sdio->pkg == RT_NULL)
{
return;
}
cmd->resp[0] = hw_sdio->resp1;
cmd->resp[1] = hw_sdio->resp2;
cmd->resp[2] = hw_sdio->resp3;
cmd->resp[3] = hw_sdio->resp4;
if (status & SDIO_ERRORS)
{
if ((status & SDMMC_STA_CCRCFAIL) && (resp_type(cmd) & (RESP_R3 | RESP_R4)))
{
cmd->err = RT_EOK;
}
else
{
cmd->err = -RT_ERROR;
}
if (status & SDMMC_STA_CTIMEOUT)
{
cmd->err = -RT_ETIMEOUT;
}
if (status & SDMMC_STA_DCRCFAIL)
{
data->err = -RT_ERROR;
}
if (status & SDMMC_STA_DTIMEOUT)
{
data->err = -RT_ETIMEOUT;
}
if (cmd->err == RT_EOK)
{
LOG_D("sta:0x%08X [%08X %08X %08X %08X]", status, cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]);
}
else
{
LOG_D("err:0x%08x, %s%s%s%s%s%s%s cmd:%d arg:0x%08x rw:%c len:%d blksize:%d",
status,
status & SDMMC_STA_CCRCFAIL ? "CCRCFAIL " : "",
status & SDMMC_STA_DCRCFAIL ? "DCRCFAIL " : "",
status & SDMMC_STA_CTIMEOUT ? "CTIMEOUT " : "",
status & SDMMC_STA_DTIMEOUT ? "DTIMEOUT " : "",
status & SDMMC_STA_TXUNDERR ? "TXUNDERR " : "",
status & SDMMC_STA_RXOVERR ? "RXOVERR " : "",
status == 0 ? "NULL" : "",
cmd->cmd_code,
cmd->arg,
data ? (data->flags & DATA_DIR_WRITE ? 'w' : 'r') : '-',
data ? data->blks * data->blksize : 0,
data ? data->blksize : 0
);
}
}
else
{
cmd->err = RT_EOK;
LOG_D("sta:0x%08X [%08X %08X %08X %08X]", status, cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]);
}
}
/**
* @brief This function send command.
* @param sdio rthw_sdio
* @param pkg sdio package
* @retval None
*/
static void rthw_sdio_send_command(struct rthw_sdio *sdio, struct sdio_pkg *pkg)
{
struct rt_mmcsd_cmd *cmd = pkg->cmd;
struct rt_mmcsd_data *data = cmd->data;
struct stm32_sdio *hw_sdio = sdio->sdio_des.hw_sdio;
rt_uint32_t reg_cmd;
sdio->pkg = pkg;
LOG_D("CMD:%d ARG:0x%08x RES:%s%s%s%s%s%s%s%s%s rw:%c len:%d blksize:%d\n",
cmd->cmd_code,
cmd->arg,
resp_type(cmd) == RESP_NONE ? "NONE" : "",
resp_type(cmd) == RESP_R1 ? "R1" : "",
resp_type(cmd) == RESP_R1B ? "R1B" : "",
resp_type(cmd) == RESP_R2 ? "R2" : "",
resp_type(cmd) == RESP_R3 ? "R3" : "",
resp_type(cmd) == RESP_R4 ? "R4" : "",
resp_type(cmd) == RESP_R5 ? "R5" : "",
resp_type(cmd) == RESP_R6 ? "R6" : "",
resp_type(cmd) == RESP_R7 ? "R7" : "",
data ? (data->flags & DATA_DIR_WRITE ? 'w' : 'r') : '-',
data ? data->blks * data->blksize : 0,
data ? data->blksize : 0
);
/* config cmd reg */
reg_cmd = cmd->cmd_code | SDMMC_CMD_CPSMEN;
if (resp_type(cmd) == RESP_NONE)
reg_cmd |= SDMMC_RESPONSE_NO;
else if (resp_type(cmd) == RESP_R2)
reg_cmd |= SDMMC_RESPONSE_LONG;
else
reg_cmd |= SDMMC_RESPONSE_SHORT;
hw_sdio->mask |= SDIO_MASKR_ALL;
/* data pre configuration */
if (data != RT_NULL)
{
hw_sdio->dctrl = 0;
hw_sdio->mask &= ~(SDMMC_MASK_CMDRENDIE | SDMMC_MASK_CMDSENTIE);
reg_cmd |= SDMMC_CMD_CMDTRANS;
hw_sdio->dtimer = HW_SDIO_DATATIMEOUT;
hw_sdio->dlen = data->blks * data->blksize;
hw_sdio->dctrl = (get_order(data->blksize)<<4) | (data->flags & DATA_DIR_READ ? SDMMC_DCTRL_DTDIR : 0);
hw_sdio->idmabase0r = (rt_uint32_t)cache_buf;
hw_sdio->idmatrlr = SDMMC_ENABLE_IDMA_SINGLE_BUFF;
}
hw_sdio->arg = cmd->arg;
hw_sdio->cmd = reg_cmd;
/* wait completed */
rthw_sdio_wait_completed(sdio);
/* Waiting for data to be sent to completion */
if (data != RT_NULL)
{
volatile rt_uint32_t count = SDIO_TX_RX_COMPLETE_TIMEOUT_LOOPS;
while (count && (hw_sdio->sta & SDMMC_STA_DPSMACT))
{
count--;
}
if ((count == 0) || (hw_sdio->sta & SDIO_ERRORS))
{
cmd->err = -RT_ERROR;
}
}
/* close irq, keep sdio irq */
hw_sdio->mask = hw_sdio->mask & SDMMC_IT_SDIOIT ? SDMMC_IT_SDIOIT : 0x00;
/* data post configuration */
if (data != RT_NULL)
{
if (data->flags & DATA_DIR_READ)
{
rt_memcpy(data->buf, cache_buf, data->blks * data->blksize);
}
}
}
/**
* @brief This function send sdio request.
* @param sdio rthw_sdio
* @param req request
* @retval None
*/
static void rthw_sdio_request(struct rt_mmcsd_host *host, struct rt_mmcsd_req *req)
{
struct sdio_pkg pkg;
struct rthw_sdio *sdio = host->private_data;
struct rt_mmcsd_data *data;
RTHW_SDIO_LOCK(sdio);
if (req->cmd != RT_NULL)
{
rt_memset(&pkg, 0, sizeof(pkg));
data = req->cmd->data;
pkg.cmd = req->cmd;
if (data != RT_NULL)
{
rt_uint32_t size = data->blks * data->blksize;
RT_ASSERT(size <= SDIO_BUFF_SIZE);
if (data->flags & DATA_DIR_WRITE)
{
rt_memcpy(cache_buf, data->buf, size);
}
}
rthw_sdio_send_command(sdio, &pkg);
}
if (req->stop != RT_NULL)
{
rt_memset(&pkg, 0, sizeof(pkg));
pkg.cmd = req->stop;
rthw_sdio_send_command(sdio, &pkg);
}
RTHW_SDIO_UNLOCK(sdio);
mmcsd_req_complete(sdio->host);
}
/**
* @brief This function interrupt process function.
* @param host rt_mmcsd_host
* @retval None
*/
void rthw_sdio_irq_process(struct rt_mmcsd_host *host)
{
struct rthw_sdio *sdio = host->private_data;
struct stm32_sdio *hw_sdio = sdio->sdio_des.hw_sdio;
rt_uint32_t intstatus = hw_sdio->sta;
/* clear irq flag*/
hw_sdio->icr = intstatus;
rt_event_send(&sdio->event, intstatus);
}
/**
* @brief This function config sdio.
* @param host rt_mmcsd_host
* @param io_cfg rt_mmcsd_io_cfg
* @retval None
*/
static void rthw_sdio_iocfg(struct rt_mmcsd_host *host, struct rt_mmcsd_io_cfg *io_cfg)
{
rt_uint32_t temp, clk_src;
rt_uint32_t clk = io_cfg->clock;
struct rthw_sdio *sdio = host->private_data;
struct stm32_sdio *hw_sdio = sdio->sdio_des.hw_sdio;
LOG_D("clk:%dK width:%s%s%s power:%s%s%s",
clk/1000,
io_cfg->bus_width == MMCSD_BUS_WIDTH_8 ? "8" : "",
io_cfg->bus_width == MMCSD_BUS_WIDTH_4 ? "4" : "",
io_cfg->bus_width == MMCSD_BUS_WIDTH_1 ? "1" : "",
io_cfg->power_mode == MMCSD_POWER_OFF ? "OFF" : "",
io_cfg->power_mode == MMCSD_POWER_UP ? "UP" : "",
io_cfg->power_mode == MMCSD_POWER_ON ? "ON" : ""
);
RTHW_SDIO_LOCK(sdio);
clk_src = SDIO_CLOCK_FREQ;
if (clk > 0)
{
if (clk > host->freq_max)
{
clk = host->freq_max;
}
temp = DIV_ROUND_UP(clk_src, 2 * clk);
if (temp > 0x3FF)
{
temp = 0x3FF;
}
}
if (io_cfg->bus_width == MMCSD_BUS_WIDTH_8)
{
temp |= SDMMC_BUS_WIDE_8B;
}
else if (io_cfg->bus_width == MMCSD_BUS_WIDTH_4)
{
temp |= SDMMC_BUS_WIDE_4B;
}
else
{
temp |= SDMMC_BUS_WIDE_1B;
}
hw_sdio->clkcr = temp;
if (io_cfg->power_mode == MMCSD_POWER_ON)
hw_sdio->power |= SDMMC_POWER_PWRCTRL;
RTHW_SDIO_UNLOCK(sdio);
}
static const struct rt_mmcsd_host_ops ops =
{
rthw_sdio_request,
rthw_sdio_iocfg,
RT_NULL,
RT_NULL,
};
/**
* @brief This function create mmcsd host.
* @param sdio_des stm32_sdio_des
* @retval rt_mmcsd_host
*/
struct rt_mmcsd_host *sdio_host_create(struct stm32_sdio_des *sdio_des)
{
struct rt_mmcsd_host *host;
struct rthw_sdio *sdio = RT_NULL;
if (sdio_des == RT_NULL)
{
return RT_NULL;
}
sdio = rt_malloc(sizeof(struct rthw_sdio));
if (sdio == RT_NULL)
{
LOG_E("malloc rthw_sdio fail");
return RT_NULL;
}
rt_memset(sdio, 0, sizeof(struct rthw_sdio));
host = mmcsd_alloc_host();
if (host == RT_NULL)
{
LOG_E("alloc host fail");
goto err;
}
rt_memcpy(&sdio->sdio_des, sdio_des, sizeof(struct stm32_sdio_des));
sdio->sdio_des.hw_sdio = (struct stm32_sdio *)SDIO_BASE_ADDRESS;
rt_event_init(&sdio->event, "sdio", RT_IPC_FLAG_FIFO);
rt_mutex_init(&sdio->mutex, "sdio", RT_IPC_FLAG_FIFO);
/* set host default attributes */
host->ops = &ops;
host->freq_min = 400 * 1000;
host->freq_max = SDIO_MAX_FREQ;
host->valid_ocr = 0X00FFFF80;/* The voltage range supported is 1.65v-3.6v */
#ifndef SDIO_USING_1_BIT
host->flags = MMCSD_BUSWIDTH_4 | MMCSD_MUTBLKWRITE | MMCSD_SUP_HIGHSPEED;
#else
host->flags = MMCSD_MUTBLKWRITE | MMCSD_SUP_HIGHSPEED;
#endif
host->max_seg_size = SDIO_BUFF_SIZE;
host->max_dma_segs = 1;
host->max_blk_size = 512;
host->max_blk_count = 512;
/* link up host and sdio */
sdio->host = host;
host->private_data = sdio;
/* ready to change */
mmcsd_change(host);
return host;
err:
if (sdio)
{
rt_free(sdio);
}
return RT_NULL;
}
void SDMMC1_IRQHandler(void)
{
rt_interrupt_enter();
/* Process All SDIO Interrupt Sources */
rthw_sdio_irq_process(host);
rt_interrupt_leave();
}
int rt_hw_sdio_init(void)
{
struct stm32_sdio_des sdio_des;
hsd.Instance = SDMMC1;
HAL_SD_MspInit(&hsd);
host = sdio_host_create(&sdio_des);
if (host == RT_NULL)
{
LOG_E("host create fail");
return RT_NULL;
}
return RT_EOK;
}
INIT_DEVICE_EXPORT(rt_hw_sdio_init);
int mnt_init(void)
{
rt_device_t sd = RT_NULL;
rt_thread_delay(RT_TICK_PER_SECOND);
sd = rt_device_find("sd0");
if (sd == RT_NULL)
{
rt_kprintf("can't find sd0 device!\n");
return RT_ERROR;
}
if (dfs_mount("sd0", "/", "elm", 0, 0) != 0)
{
rt_kprintf("file system mount failed!\n");
}
else
{
rt_kprintf("file system mount success!\n");
}
return RT_EOK;
}
INIT_ENV_EXPORT(mnt_init);
#endif /* BSP_USING_SDMMC */

View File

@ -0,0 +1,117 @@
/*
* Copyright (c) 2006-2020, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2020-07-16 thread-liu first version
*/
#ifndef __DRV_SDIO_H__
#define __DRV_SDIO_H__
#include <rtthread.h>
#include "rtdevice.h"
#include <rthw.h>
#include <drv_common.h>
#include <string.h>
#include <drivers/mmcsd_core.h>
#include <drivers/sdio.h>
#define SDIO_BUFF_SIZE 4096
#define SDIO_ALIGN_LEN 32
#ifndef SDIO_BASE_ADDRESS
#define SDIO_BASE_ADDRESS (SDMMC1)
#endif
#ifndef SDIO_CLOCK_FREQ
#define SDIO_CLOCK_FREQ (99U * 1000 * 1000)
#endif
#ifndef SDIO_BUFF_SIZE
#define SDIO_BUFF_SIZE (4096)
#endif
#ifndef SDIO_ALIGN_LEN
#define SDIO_ALIGN_LEN (32)
#endif
#ifndef SDIO_MAX_FREQ
#define SDIO_MAX_FREQ (50 * 1000 * 1000)
#endif
#define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
#define SDMMC_POWER_OFF (0x00U)
#define SDMMC_POWER_UP (0x02U)
#define SDMMC_POWER_ON (0x03U)
#define SDIO_ERRORS \
(SDMMC_STA_IDMATE | SDMMC_STA_ACKTIMEOUT | \
SDMMC_STA_RXOVERR | SDMMC_STA_TXUNDERR | \
SDMMC_STA_DTIMEOUT | SDMMC_STA_CTIMEOUT | \
SDMMC_STA_DCRCFAIL | SDMMC_STA_CCRCFAIL)
#define SDIO_MASKR_ALL \
(SDMMC_MASK_CCRCFAILIE | SDMMC_MASK_DCRCFAILIE | SDMMC_MASK_CTIMEOUTIE | \
SDMMC_MASK_TXUNDERRIE | SDMMC_MASK_RXOVERRIE | SDMMC_MASK_CMDRENDIE | \
SDMMC_MASK_CMDSENTIE | SDMMC_MASK_DATAENDIE | SDMMC_MASK_ACKTIMEOUTIE)
#define HW_SDIO_DATATIMEOUT (0xFFFFFFFFU)
struct stm32_sdio
{
volatile rt_uint32_t power; /* offset 0x00 */
volatile rt_uint32_t clkcr; /* offset 0x04 */
volatile rt_uint32_t arg; /* offset 0x08 */
volatile rt_uint32_t cmd; /* offset 0x0C */
volatile rt_uint32_t respcmd; /* offset 0x10 */
volatile rt_uint32_t resp1; /* offset 0x14 */
volatile rt_uint32_t resp2; /* offset 0x18 */
volatile rt_uint32_t resp3; /* offset 0x1C */
volatile rt_uint32_t resp4; /* offset 0x20 */
volatile rt_uint32_t dtimer; /* offset 0x24 */
volatile rt_uint32_t dlen; /* offset 0x28 */
volatile rt_uint32_t dctrl; /* offset 0x2C */
volatile rt_uint32_t dcount; /* offset 0x30 */
volatile rt_uint32_t sta; /* offset 0x34 */
volatile rt_uint32_t icr; /* offset 0x38 */
volatile rt_uint32_t mask; /* offset 0x3C */
volatile rt_uint32_t acktimer; /* offset 0x40 */
volatile rt_uint32_t reserved0[3]; /* offset 0x44 ~ 0x4C */
volatile rt_uint32_t idmatrlr; /* offset 0x50 */
volatile rt_uint32_t idmabsizer; /* offset 0x54 */
volatile rt_uint32_t idmabase0r; /* offset 0x58 */
volatile rt_uint32_t idmabase1r; /* offset 0x5C */
volatile rt_uint32_t reserved1[1]; /* offset 0x60 */
volatile rt_uint32_t idmalar;
volatile rt_uint32_t idmabar;
volatile rt_uint32_t reserved2[5];
volatile rt_uint32_t fifo;
volatile rt_uint32_t reserved3[220];
volatile rt_uint32_t verr;
volatile rt_uint32_t ipidr;
volatile rt_uint32_t sidr;
};
typedef rt_uint32_t (*sdio_clk_get)(struct stm32_sdio *hw_sdio);
struct stm32_sdio_des
{
struct stm32_sdio *hw_sdio;
sdio_clk_get clk_get;
};
/* stm32 sdio dirver class */
struct stm32_sdio_class
{
struct stm32_sdio_des *des;
const struct stm32_sdio_config *cfg;
struct rt_mmcsd_host host;
};
extern void stm32_mmcsd_change(void);
#endif /* __DRV_SDIO_H__ */