/*-----------------------------------------------------------------------*/
/* Low level disk I/O module SKELETON for FatFs     (C)ChaN, 2019        */
/*-----------------------------------------------------------------------*/
/* If a working storage control module is available, it should be        */
/* attached to the FatFs via a glue function rather than modifying it.   */
/* This is an example of glue functions to attach various exsisting      */
/* storage control modules to the FatFs module with a defined API.       */
/*-----------------------------------------------------------------------*/

#include "ff.h"			/* Obtains integer types */
#include "diskio.h"		/* Declarations of disk functions */

#include <string.h>
#include "main.h"
#include "FreeRTOS.h"
#include "semphr.h"
#include "elog.h"
#include "heap.h"

static const char *TAG = "diskio_sdcard";
static SemaphoreHandle_t sd_tx_semphr = NULL;
static SemaphoreHandle_t sd_rx_semphr = NULL;

void HAL_SD_TxCpltCallback(SD_HandleTypeDef *hsd)
{
  BaseType_t higher_task_woken = pdFALSE;

  // elog_verbose(TAG, "in write complete ISR");
  if (hsd == &hsd1) {
    xSemaphoreGiveFromISR(sd_tx_semphr, &higher_task_woken);
  }

  portYIELD_FROM_ISR(higher_task_woken);
}

void HAL_SD_RxCpltCallback(SD_HandleTypeDef *hsd)
{
  BaseType_t higher_task_woken = pdFALSE;

  // elog_verbose(TAG, "in read complete ISR");
  if (hsd == &hsd1) {
    xSemaphoreGiveFromISR(sd_rx_semphr, &higher_task_woken);
  }

  portYIELD_FROM_ISR(higher_task_woken);
}

/*-----------------------------------------------------------------------*/
/* Get Drive Status                                                      */
/*-----------------------------------------------------------------------*/

DSTATUS disk_status (
	BYTE pdrv		/* Physical drive nmuber to identify the drive */
)
{
  UNUSED(pdrv);

  HAL_SD_CardStateTypeDef card_result = HAL_SD_GetCardState(&hsd1);

  if(card_result != HAL_SD_CARD_TRANSFER) {
    elog_error(TAG, "card status error, status code is %d", card_result);
    return STA_NOINIT;
  }

  return 0;
}


/*-----------------------------------------------------------------------*/
/* Inidialize a Drive                                                    */
/*-----------------------------------------------------------------------*/

DSTATUS disk_initialize (
	BYTE pdrv				/* Physical drive nmuber to identify the drive */
)
{
  UNUSED(pdrv);

  sd_tx_semphr = xSemaphoreCreateBinary();
  sd_rx_semphr = xSemaphoreCreateBinary();

  if (sd_tx_semphr == NULL || sd_rx_semphr == NULL) {
    elog_error(TAG, "error while creating interrupt semphr");
    goto ERROR;
  }

  HAL_StatusTypeDef init_result = HAL_SD_InitCard(&hsd1);
  if (init_result != HAL_OK) {
    elog_error(TAG, "error while initializing card");
    goto ERROR;
  }

  init_result = HAL_SD_ConfigWideBusOperation(&hsd1, SDMMC_BUS_WIDE_4B);
  if(init_result != HAL_OK) {
    elog_error(TAG, "error while configuring bus width");
    goto ERROR;
  }

  init_result = HAL_SD_ConfigSpeedBusOperation(&hsd1, SDMMC_SPEED_MODE_AUTO);
  if(init_result != HAL_OK) {
    elog_error(TAG, "error while configuring bus speed");
    goto ERROR;
  }

  return 0;

ERROR:
  vSemaphoreDelete(sd_tx_semphr);
  vSemaphoreDelete(sd_rx_semphr);
  return STA_NOINIT;
}


/*-----------------------------------------------------------------------*/
/* Read Sector(s)                                                        */
/*-----------------------------------------------------------------------*/

DRESULT disk_read (
	BYTE pdrv,		/* Physical drive nmuber to identify the drive */
	BYTE *buff,		/* Data buffer to store read data */
	LBA_t sector,	/* Start sector in LBA */
	UINT count		/* Number of sectors to read */
)
{
  UNUSED(pdrv);

	DRESULT res = RES_OK;
  HAL_StatusTypeDef read_result;
  uint8_t *buff_aligned = NULL;

  // elog_verbose(TAG, "start reading %d block%s@ %d", count, count == 1 ? "" : "s", (int)sector);

  if ((uint32_t)buff % 4 != 0) { //缓冲区4字节未对齐
    // elog_warn(TAG, "unaligned read buffer @ %p", buff);
    buff_aligned = malloc(count * BLOCKSIZE); //申请4字节对齐buffer
    read_result = HAL_SD_ReadBlocks_DMA(&hsd1, buff_aligned, sector, count);
  } else {
    read_result = HAL_SD_ReadBlocks_DMA(&hsd1, buff, sector, count); //使用DMA方式
  }
  xSemaphoreTake(sd_rx_semphr, portMAX_DELAY);

  uint32_t timeout = 100;
  if (read_result == HAL_OK) {
    while(HAL_SD_GetCardState(&hsd1) != HAL_SD_CARD_TRANSFER) { //wait busy
      vTaskDelay(1);
      // elog_verbose(TAG, "waiting for card to get ready");
      if (timeout == 0) {
        res = RES_ERROR;
      }
    }
  } else {
    res = RES_ERROR;
  }

  if ((uint32_t)buff % 4 != 0) { //缓冲区4字节未对齐
    memcpy(buff, buff_aligned, count * BLOCKSIZE);
    free(buff_aligned);
  }

	return res;
}


/*-----------------------------------------------------------------------*/
/* Write Sector(s)                                                       */
/*-----------------------------------------------------------------------*/

#if FF_FS_READONLY == 0

DRESULT disk_write (
	BYTE pdrv,			/* Physical drive nmuber to identify the drive */
	const BYTE *buff,	/* Data to be written */
	LBA_t sector,		/* Start sector in LBA */
	UINT count			/* Number of sectors to write */
)
{
	DRESULT res = RES_OK;
  HAL_StatusTypeDef write_result;

  // elog_verbose(TAG, "start writing %d block%s@ %d", count, count == 1 ? "" : "s", (int)sector);

  if ((uint32_t)buff % 4 == 0) { //缓冲区4字节对齐
    write_result = HAL_SD_WriteBlocks_DMA(&hsd1, buff, sector, count); //使用DMA方式
  } else {
    write_result = HAL_SD_WriteBlocks_IT(&hsd1, buff, sector, count); //使用查询方式
    elog_warn(TAG, "unaligned buffer access@%p, fall back to polling method", buff);
  }
  xSemaphoreTake(sd_tx_semphr, portMAX_DELAY);

  uint32_t timeout = 100;
  if (write_result == HAL_OK) {
    while(HAL_SD_GetCardState(&hsd1) != HAL_SD_CARD_TRANSFER) { //wait busy
      vTaskDelay(1);
      // elog_verbose(TAG, "waiting for card to get ready");
      if (timeout == 0) {
        res = RES_ERROR;
      }
    }
  } else {
    res = RES_ERROR;
  }

	return res;
}

#endif


/*-----------------------------------------------------------------------*/
/* Miscellaneous Functions                                               */
/*-----------------------------------------------------------------------*/

DRESULT disk_ioctl (
	BYTE pdrv,		/* Physical drive nmuber (0..) */
	BYTE cmd,		/* Control code */
	void *buff		/* Buffer to send/receive control data */
)
{
  DRESULT res = RES_ERROR;
  HAL_SD_CardInfoTypeDef card_info;

  switch (cmd) {
  /* Make sure that no pending write process */
  case CTRL_SYNC:
    res = RES_OK;
    break;

  /* Get number of sectors on the disk (DWORD) */
  case GET_SECTOR_COUNT:
    HAL_SD_GetCardInfo(&hsd1, &card_info);
    *(DWORD *)buff = card_info.LogBlockNbr;
    res = RES_OK;
    break;

  /* Get R/W sector size (WORD) */
  case GET_SECTOR_SIZE:
  /* Get erase block size in unit of sector (DWORD) */
  case GET_BLOCK_SIZE:
    HAL_SD_GetCardInfo(&hsd1, &card_info);
    *(WORD *)buff = card_info.LogBlockSize;
    res = RES_OK;
    break;

  default:
    res = RES_PARERR;
  }
  return res;
}
