Author SHA1 Message Date
Eric Callahan 2df22db77b stm32: add initial sdio support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-27 07:13:13 -04:00
Eric Callahan a7d3b3cfc4 sdcard_spi: minor fixes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-18 08:21:32 -04:00
Eric Callahan de9ab7c5e8 lpc176x: add sdcard configuration to build
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:55 -04:00
Eric Callahan d30928281f lpc176x: add spi_set_rate method
This slightly modifies the method used to set SPI rate

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:54 -04:00
Eric Callahan f6e783d825 lpc176x: allow 16 bit SPI length requests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:54 -04:00
Eric Callahan a357d04b05 lpc176x: add spi source from klipper
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:54 -04:00
Eric Callahan 8a674ab5c3 buildcommands: generate swspi pins
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:53 -04:00
Eric Callahan 8753d674cc sdcard_spi: add support for software spi
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:53 -04:00
Eric Callahan 95a5686fcc build: add software spi support to KConfig and Makefile
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:53 -04:00
Eric Callahan 9cb66f93b2 spi_software: add source from Klipper
This contains a port of Klipper's spi_software implementation
for use with CanBoot's sdcard.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:52 -04:00
Eric Callahan 536f8b7c3b buildcommands: generate sdcard cs pin code
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:52 -04:00
Eric Callahan 2cf2852bfa makefile: add sdcard source
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:52 -04:00
Eric Callahan 0ff774a2ce sdcard: initial implementation
Add support for firmware uploads from an SD Card via SPI.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:51 -04:00
Eric Callahan 4ca74c7984 command: support disabling command processing
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:51 -04:00
Eric Callahan b9d3da8c3e flashcmd: add set_in_transfer and set_complete methods
This allows local flashing to update transfer state.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:51 -04:00
Eric Callahan b19650f65b kconfig; Add SD Card menu
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:50 -04:00
Eric Callahan f3711f4d5b stm32: allow 16 bit SPI length requests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:50 -04:00
Eric Callahan 3de31f02c3 stm32: add spi_set_rate() method
Proper SPI initialization occurs at a rate of 100-400 kHz.  This should
be changed after init

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:50 -04:00
Eric Callahan 3b9f5f6d80 stm32: add spi implementation from klipper
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:49 -04:00
Eric Callahan 82c8cc327a lib: add fatfs dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 12:39:49 -04:00
28 changed files with 25327 additions and 3 deletions

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
FatFs License
FatFs has being developped as a personal project of the author, ChaN. It is free from the code anyone else wrote at current release. Following code block shows a copy of the FatFs license document that heading the source files.
/*----------------------------------------------------------------------------/
/ FatFs - Generic FAT Filesystem Module Rx.xx /
/-----------------------------------------------------------------------------/
/
/ Copyright (C) 20xx, ChaN, all right reserved.
/
/ FatFs module is an open source software. Redistribution and use of FatFs in
/ source and binary forms, with or without modification, are permitted provided
/ that the following condition is met:
/
/ 1. Redistributions of source code must retain the above copyright notice,
/ this condition and the following disclaimer.
/
/ This software is provided by the copyright holder and contributors "AS IS"
/ and any warranties related to this software are DISCLAIMED.
/ The copyright owner or contributors be NOT LIABLE for any damages caused
/ by use of this software.
/----------------------------------------------------------------------------*/
Therefore FatFs license is one of the BSD-style licenses, but there is a significant feature. FatFs is mainly intended for embedded systems. In order to extend the usability for commercial products, the redistributions of FatFs in binary form, such as embedded code, binary library and any forms without source code, do not need to include about FatFs in the documentations. This is equivalent to the 1-clause BSD license. Of course FatFs is compatible with the most of open source software licenses include GNU GPL. When you redistribute the FatFs source code with changes or create a fork, the license can also be changed to GNU GPL, BSD-style license or any open source software license that not conflict with FatFs license.
+77
View File
@@ -0,0 +1,77 @@
/*-----------------------------------------------------------------------/
/ Low level disk interface modlue include file (C)ChaN, 2019 /
/-----------------------------------------------------------------------*/
#ifndef _DISKIO_DEFINED
#define _DISKIO_DEFINED
#ifdef __cplusplus
extern "C" {
#endif
/* Status of Disk Functions */
typedef BYTE DSTATUS;
/* Results of Disk Functions */
typedef enum {
RES_OK = 0, /* 0: Successful */
RES_ERROR, /* 1: R/W Error */
RES_WRPRT, /* 2: Write Protected */
RES_NOTRDY, /* 3: Not Ready */
RES_PARERR /* 4: Invalid Parameter */
} DRESULT;
/*---------------------------------------*/
/* Prototypes for disk control functions */
DSTATUS disk_initialize (BYTE pdrv);
DSTATUS disk_status (BYTE pdrv);
DRESULT disk_read (BYTE pdrv, BYTE* buff, LBA_t sector, UINT count);
DRESULT disk_write (BYTE pdrv, const BYTE* buff, LBA_t sector, UINT count);
DRESULT disk_ioctl (BYTE pdrv, BYTE cmd, void* buff);
/* Disk Status Bits (DSTATUS) */
#define STA_NOINIT 0x01 /* Drive not initialized */
#define STA_NODISK 0x02 /* No medium in the drive */
#define STA_PROTECT 0x04 /* Write protected */
/* Command code for disk_ioctrl fucntion */
/* Generic command (Used by FatFs) */
#define CTRL_SYNC 0 /* Complete pending write process (needed at FF_FS_READONLY == 0) */
#define GET_SECTOR_COUNT 1 /* Get media size (needed at FF_USE_MKFS == 1) */
#define GET_SECTOR_SIZE 2 /* Get sector size (needed at FF_MAX_SS != FF_MIN_SS) */
#define GET_BLOCK_SIZE 3 /* Get erase block size (needed at FF_USE_MKFS == 1) */
#define CTRL_TRIM 4 /* Inform device that the data on the block of sectors is no longer used (needed at FF_USE_TRIM == 1) */
/* Generic command (Not used by FatFs) */
#define CTRL_POWER 5 /* Get/Set power status */
#define CTRL_LOCK 6 /* Lock/Unlock media removal */
#define CTRL_EJECT 7 /* Eject media */
#define CTRL_FORMAT 8 /* Create physical format on the media */
/* MMC/SDC specific ioctl command */
#define MMC_GET_TYPE 10 /* Get card type */
#define MMC_GET_CSD 11 /* Get CSD */
#define MMC_GET_CID 12 /* Get CID */
#define MMC_GET_OCR 13 /* Get OCR */
#define MMC_GET_SDSTAT 14 /* Get SD status */
#define ISDIO_READ 55 /* Read data form SD iSDIO register */
#define ISDIO_WRITE 56 /* Write data to SD iSDIO register */
#define ISDIO_MRITE 57 /* Masked write data to SD iSDIO register */
/* ATA/CF specific ioctl command */
#define ATA_GET_REV 20 /* Get F/W revision */
#define ATA_GET_MODEL 21 /* Get model name */
#define ATA_GET_SN 22 /* Get serial number */
#ifdef __cplusplus
}
#endif
#endif
+6982
View File
File diff suppressed because it is too large. Load diff
+422
View File
@@ -0,0 +1,422 @@
/*----------------------------------------------------------------------------/
/ FatFs - Generic FAT Filesystem module R0.14b /
/-----------------------------------------------------------------------------/
/
/ Copyright (C) 2021, ChaN, all right reserved.
/
/ FatFs module is an open source software. Redistribution and use of FatFs in
/ source and binary forms, with or without modification, are permitted provided
/ that the following condition is met:
/ 1. Redistributions of source code must retain the above copyright notice,
/ this condition and the following disclaimer.
/
/ This software is provided by the copyright holder and contributors "AS IS"
/ and any warranties related to this software are DISCLAIMED.
/ The copyright owner or contributors be NOT LIABLE for any damages caused
/ by use of this software.
/
/----------------------------------------------------------------------------*/
#ifndef FF_DEFINED
#define FF_DEFINED 86631 /* Revision ID */
#ifdef __cplusplus
extern "C" {
#endif
#include "ffconf.h" /* FatFs configuration options */
#if FF_DEFINED != FFCONF_DEF
#error Wrong configuration file (ffconf.h).
#endif
/* Integer types used for FatFs API */
#if defined(_WIN32) /* Windows VC++ (for development only) */
#define FF_INTDEF 2
#include <windows.h>
typedef unsigned __int64 QWORD;
#include <float.h>
#define isnan(v) _isnan(v)
#define isinf(v) (!_finite(v))
#elif (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__cplusplus) /* C99 or later */
#define FF_INTDEF 2
#include <stdint.h>
typedef unsigned int UINT; /* int must be 16-bit or 32-bit */
typedef unsigned char BYTE; /* char must be 8-bit */
typedef uint16_t WORD; /* 16-bit unsigned integer */
typedef uint32_t DWORD; /* 32-bit unsigned integer */
typedef uint64_t QWORD; /* 64-bit unsigned integer */
typedef WORD WCHAR; /* UTF-16 character type */
#else /* Earlier than C99 */
#define FF_INTDEF 1
typedef unsigned int UINT; /* int must be 16-bit or 32-bit */
typedef unsigned char BYTE; /* char must be 8-bit */
typedef unsigned short WORD; /* 16-bit unsigned integer */
typedef unsigned long DWORD; /* 32-bit unsigned integer */
typedef WORD WCHAR; /* UTF-16 character type */
#endif
/* Type of file size and LBA variables */
#if FF_FS_EXFAT
#if FF_INTDEF != 2
#error exFAT feature wants C99 or later
#endif
typedef QWORD FSIZE_t;
#if FF_LBA64
typedef QWORD LBA_t;
#else
typedef DWORD LBA_t;
#endif
#else
#if FF_LBA64
#error exFAT needs to be enabled when enable 64-bit LBA
#endif
typedef DWORD FSIZE_t;
typedef DWORD LBA_t;
#endif
/* Type of path name strings on FatFs API (TCHAR) */
#if FF_USE_LFN && FF_LFN_UNICODE == 1 /* Unicode in UTF-16 encoding */
typedef WCHAR TCHAR;
#define _T(x) L ## x
#define _TEXT(x) L ## x
#elif FF_USE_LFN && FF_LFN_UNICODE == 2 /* Unicode in UTF-8 encoding */
typedef char TCHAR;
#define _T(x) u8 ## x
#define _TEXT(x) u8 ## x
#elif FF_USE_LFN && FF_LFN_UNICODE == 3 /* Unicode in UTF-32 encoding */
typedef DWORD TCHAR;
#define _T(x) U ## x
#define _TEXT(x) U ## x
#elif FF_USE_LFN && (FF_LFN_UNICODE < 0 || FF_LFN_UNICODE > 3)
#error Wrong FF_LFN_UNICODE setting
#else /* ANSI/OEM code in SBCS/DBCS */
typedef char TCHAR;
#define _T(x) x
#define _TEXT(x) x
#endif
/* Definitions of volume management */
#if FF_MULTI_PARTITION /* Multiple partition configuration */
typedef struct {
BYTE pd; /* Physical drive number */
BYTE pt; /* Partition: 0:Auto detect, 1-4:Forced partition) */
} PARTITION;
extern PARTITION VolToPart[]; /* Volume - Partition mapping table */
#endif
#if FF_STR_VOLUME_ID
#ifndef FF_VOLUME_STRS
extern const char* VolumeStr[FF_VOLUMES]; /* User defied volume ID */
#endif
#endif
/* Filesystem object structure (FATFS) */
typedef struct {
BYTE fs_type; /* Filesystem type (0:not mounted) */
BYTE pdrv; /* Associated physical drive */
BYTE n_fats; /* Number of FATs (1 or 2) */
BYTE wflag; /* win[] flag (b0:dirty) */
BYTE fsi_flag; /* FSINFO flags (b7:disabled, b0:dirty) */
WORD id; /* Volume mount ID */
WORD n_rootdir; /* Number of root directory entries (FAT12/16) */
WORD csize; /* Cluster size [sectors] */
#if FF_MAX_SS != FF_MIN_SS
WORD ssize; /* Sector size (512, 1024, 2048 or 4096) */
#endif
#if FF_USE_LFN
WCHAR* lfnbuf; /* LFN working buffer */
#endif
#if FF_FS_EXFAT
BYTE* dirbuf; /* Directory entry block scratchpad buffer for exFAT */
#endif
#if FF_FS_REENTRANT
FF_SYNC_t sobj; /* Identifier of sync object */
#endif
#if !FF_FS_READONLY
DWORD last_clst; /* Last allocated cluster */
DWORD free_clst; /* Number of free clusters */
#endif
#if FF_FS_RPATH
DWORD cdir; /* Current directory start cluster (0:root) */
#if FF_FS_EXFAT
DWORD cdc_scl; /* Containing directory start cluster (invalid when cdir is 0) */
DWORD cdc_size; /* b31-b8:Size of containing directory, b7-b0: Chain status */
DWORD cdc_ofs; /* Offset in the containing directory (invalid when cdir is 0) */
#endif
#endif
DWORD n_fatent; /* Number of FAT entries (number of clusters + 2) */
DWORD fsize; /* Size of an FAT [sectors] */
LBA_t volbase; /* Volume base sector */
LBA_t fatbase; /* FAT base sector */
LBA_t dirbase; /* Root directory base sector/cluster */
LBA_t database; /* Data base sector */
#if FF_FS_EXFAT
LBA_t bitbase; /* Allocation bitmap base sector */
#endif
LBA_t winsect; /* Current sector appearing in the win[] */
BYTE win[FF_MAX_SS]; /* Disk access window for Directory, FAT (and file data at tiny cfg) */
} FATFS;
/* Object ID and allocation information (FFOBJID) */
typedef struct {
FATFS* fs; /* Pointer to the hosting volume of this object */
WORD id; /* Hosting volume mount ID */
BYTE attr; /* Object attribute */
BYTE stat; /* Object chain status (b1-0: =0:not contiguous, =2:contiguous, =3:fragmented in this session, b2:sub-directory stretched) */
DWORD sclust; /* Object data start cluster (0:no cluster or root directory) */
FSIZE_t objsize; /* Object size (valid when sclust != 0) */
#if FF_FS_EXFAT
DWORD n_cont; /* Size of first fragment - 1 (valid when stat == 3) */
DWORD n_frag; /* Size of last fragment needs to be written to FAT (valid when not zero) */
DWORD c_scl; /* Containing directory start cluster (valid when sclust != 0) */
DWORD c_size; /* b31-b8:Size of containing directory, b7-b0: Chain status (valid when c_scl != 0) */
DWORD c_ofs; /* Offset in the containing directory (valid when file object and sclust != 0) */
#endif
#if FF_FS_LOCK
UINT lockid; /* File lock ID origin from 1 (index of file semaphore table Files[]) */
#endif
} FFOBJID;
/* File object structure (FIL) */
typedef struct {
FFOBJID obj; /* Object identifier (must be the 1st member to detect invalid object pointer) */
BYTE flag; /* File status flags */
BYTE err; /* Abort flag (error code) */
FSIZE_t fptr; /* File read/write pointer (Zeroed on file open) */
DWORD clust; /* Current cluster of fpter (invalid when fptr is 0) */
LBA_t sect; /* Sector number appearing in buf[] (0:invalid) */
#if !FF_FS_READONLY
LBA_t dir_sect; /* Sector number containing the directory entry (not used at exFAT) */
BYTE* dir_ptr; /* Pointer to the directory entry in the win[] (not used at exFAT) */
#endif
#if FF_USE_FASTSEEK
DWORD* cltbl; /* Pointer to the cluster link map table (nulled on open, set by application) */
#endif
#if !FF_FS_TINY
BYTE buf[FF_MAX_SS]; /* File private data read/write window */
#endif
} FIL;
/* Directory object structure (DIR) */
typedef struct {
FFOBJID obj; /* Object identifier */
DWORD dptr; /* Current read/write offset */
DWORD clust; /* Current cluster */
LBA_t sect; /* Current sector (0:Read operation has terminated) */
BYTE* dir; /* Pointer to the directory item in the win[] */
BYTE fn[12]; /* SFN (in/out) {body[8],ext[3],status[1]} */
#if FF_USE_LFN
DWORD blk_ofs; /* Offset of current entry block being processed (0xFFFFFFFF:Invalid) */
#endif
#if FF_USE_FIND
const TCHAR* pat; /* Pointer to the name matching pattern */
#endif
} DIR;
/* File information structure (FILINFO) */
typedef struct {
FSIZE_t fsize; /* File size */
WORD fdate; /* Modified date */
WORD ftime; /* Modified time */
BYTE fattrib; /* File attribute */
#if FF_USE_LFN
TCHAR altname[FF_SFN_BUF + 1];/* Altenative file name */
TCHAR fname[FF_LFN_BUF + 1]; /* Primary file name */
#else
TCHAR fname[12 + 1]; /* File name */
#endif
} FILINFO;
/* Format parameter structure (MKFS_PARM) */
typedef struct {
BYTE fmt; /* Format option (FM_FAT, FM_FAT32, FM_EXFAT and FM_SFD) */
BYTE n_fat; /* Number of FATs */
UINT align; /* Data area alignment (sector) */
UINT n_root; /* Number of root directory entries */
DWORD au_size; /* Cluster size (byte) */
} MKFS_PARM;
/* File function return code (FRESULT) */
typedef enum {
FR_OK = 0, /* (0) Succeeded */
FR_DISK_ERR, /* (1) A hard error occurred in the low level disk I/O layer */
FR_INT_ERR, /* (2) Assertion failed */
FR_NOT_READY, /* (3) The physical drive cannot work */
FR_NO_FILE, /* (4) Could not find the file */
FR_NO_PATH, /* (5) Could not find the path */
FR_INVALID_NAME, /* (6) The path name format is invalid */
FR_DENIED, /* (7) Access denied due to prohibited access or directory full */
FR_EXIST, /* (8) Access denied due to prohibited access */
FR_INVALID_OBJECT, /* (9) The file/directory object is invalid */
FR_WRITE_PROTECTED, /* (10) The physical drive is write protected */
FR_INVALID_DRIVE, /* (11) The logical drive number is invalid */
FR_NOT_ENABLED, /* (12) The volume has no work area */
FR_NO_FILESYSTEM, /* (13) There is no valid FAT volume */
FR_MKFS_ABORTED, /* (14) The f_mkfs() aborted due to any problem */
FR_TIMEOUT, /* (15) Could not get a grant to access the volume within defined period */
FR_LOCKED, /* (16) The operation is rejected according to the file sharing policy */
FR_NOT_ENOUGH_CORE, /* (17) LFN working buffer could not be allocated */
FR_TOO_MANY_OPEN_FILES, /* (18) Number of open files > FF_FS_LOCK */
FR_INVALID_PARAMETER /* (19) Given parameter is invalid */
} FRESULT;
/*--------------------------------------------------------------*/
/* FatFs module application interface */
FRESULT f_open (FIL* fp, const TCHAR* path, BYTE mode); /* Open or create a file */
FRESULT f_close (FIL* fp); /* Close an open file object */
FRESULT f_read (FIL* fp, void* buff, UINT btr, UINT* br); /* Read data from the file */
FRESULT f_write (FIL* fp, const void* buff, UINT btw, UINT* bw); /* Write data to the file */
FRESULT f_lseek (FIL* fp, FSIZE_t ofs); /* Move file pointer of the file object */
FRESULT f_truncate (FIL* fp); /* Truncate the file */
FRESULT f_sync (FIL* fp); /* Flush cached data of the writing file */
FRESULT f_opendir (DIR* dp, const TCHAR* path); /* Open a directory */
FRESULT f_closedir (DIR* dp); /* Close an open directory */
FRESULT f_readdir (DIR* dp, FILINFO* fno); /* Read a directory item */
FRESULT f_findfirst (DIR* dp, FILINFO* fno, const TCHAR* path, const TCHAR* pattern); /* Find first file */
FRESULT f_findnext (DIR* dp, FILINFO* fno); /* Find next file */
FRESULT f_mkdir (const TCHAR* path); /* Create a sub directory */
FRESULT f_unlink (const TCHAR* path); /* Delete an existing file or directory */
FRESULT f_rename (const TCHAR* path_old, const TCHAR* path_new); /* Rename/Move a file or directory */
FRESULT f_stat (const TCHAR* path, FILINFO* fno); /* Get file status */
FRESULT f_chmod (const TCHAR* path, BYTE attr, BYTE mask); /* Change attribute of a file/dir */
FRESULT f_utime (const TCHAR* path, const FILINFO* fno); /* Change timestamp of a file/dir */
FRESULT f_chdir (const TCHAR* path); /* Change current directory */
FRESULT f_chdrive (const TCHAR* path); /* Change current drive */
FRESULT f_getcwd (TCHAR* buff, UINT len); /* Get current directory */
FRESULT f_getfree (const TCHAR* path, DWORD* nclst, FATFS** fatfs); /* Get number of free clusters on the drive */
FRESULT f_getlabel (const TCHAR* path, TCHAR* label, DWORD* vsn); /* Get volume label */
FRESULT f_setlabel (const TCHAR* label); /* Set volume label */
FRESULT f_forward (FIL* fp, UINT(*func)(const BYTE*,UINT), UINT btf, UINT* bf); /* Forward data to the stream */
FRESULT f_expand (FIL* fp, FSIZE_t fsz, BYTE opt); /* Allocate a contiguous block to the file */
FRESULT f_mount (FATFS* fs, const TCHAR* path, BYTE opt); /* Mount/Unmount a logical drive */
FRESULT f_mkfs (const TCHAR* path, const MKFS_PARM* opt, void* work, UINT len); /* Create a FAT volume */
FRESULT f_fdisk (BYTE pdrv, const LBA_t ptbl[], void* work); /* Divide a physical drive into some partitions */
FRESULT f_setcp (WORD cp); /* Set current code page */
int f_putc (TCHAR c, FIL* fp); /* Put a character to the file */
int f_puts (const TCHAR* str, FIL* cp); /* Put a string to the file */
int f_printf (FIL* fp, const TCHAR* str, ...); /* Put a formatted string to the file */
TCHAR* f_gets (TCHAR* buff, int len, FIL* fp); /* Get a string from the file */
#define f_eof(fp) ((int)((fp)->fptr == (fp)->obj.objsize))
#define f_error(fp) ((fp)->err)
#define f_tell(fp) ((fp)->fptr)
#define f_size(fp) ((fp)->obj.objsize)
#define f_rewind(fp) f_lseek((fp), 0)
#define f_rewinddir(dp) f_readdir((dp), 0)
#define f_rmdir(path) f_unlink(path)
#define f_unmount(path) f_mount(0, path, 0)
/*--------------------------------------------------------------*/
/* Additional user defined functions */
/* RTC function */
#if !FF_FS_READONLY && !FF_FS_NORTC
DWORD get_fattime (void);
#endif
/* LFN support functions */
#if FF_USE_LFN >= 1 /* Code conversion (defined in unicode.c) */
WCHAR ff_oem2uni (WCHAR oem, WORD cp); /* OEM code to Unicode conversion */
WCHAR ff_uni2oem (DWORD uni, WORD cp); /* Unicode to OEM code conversion */
DWORD ff_wtoupper (DWORD uni); /* Unicode upper-case conversion */
#endif
#if FF_USE_LFN == 3 /* Dynamic memory allocation */
void* ff_memalloc (UINT msize); /* Allocate memory block */
void ff_memfree (void* mblock); /* Free memory block */
#endif
/* Sync functions */
#if FF_FS_REENTRANT
int ff_cre_syncobj (BYTE vol, FF_SYNC_t* sobj); /* Create a sync object */
int ff_req_grant (FF_SYNC_t sobj); /* Lock sync object */
void ff_rel_grant (FF_SYNC_t sobj); /* Unlock sync object */
int ff_del_syncobj (FF_SYNC_t sobj); /* Delete a sync object */
#endif
/*--------------------------------------------------------------*/
/* Flags and offset address */
/* File access mode and open method flags (3rd argument of f_open) */
#define FA_READ 0x01
#define FA_WRITE 0x02
#define FA_OPEN_EXISTING 0x00
#define FA_CREATE_NEW 0x04
#define FA_CREATE_ALWAYS 0x08
#define FA_OPEN_ALWAYS 0x10
#define FA_OPEN_APPEND 0x30
/* Fast seek controls (2nd argument of f_lseek) */
#define CREATE_LINKMAP ((FSIZE_t)0 - 1)
/* Format options (2nd argument of f_mkfs) */
#define FM_FAT 0x01
#define FM_FAT32 0x02
#define FM_EXFAT 0x04
#define FM_ANY 0x07
#define FM_SFD 0x08
/* Filesystem type (FATFS.fs_type) */
#define FS_FAT12 1
#define FS_FAT16 2
#define FS_FAT32 3
#define FS_EXFAT 4
/* File attribute bits for directory entry (FILINFO.fattrib) */
#define AM_RDO 0x01 /* Read only */
#define AM_HID 0x02 /* Hidden */
#define AM_SYS 0x04 /* System */
#define AM_DIR 0x10 /* Directory */
#define AM_ARC 0x20 /* Archive */
#ifdef __cplusplus
}
#endif
#endif /* FF_DEFINED */
+301
View File
@@ -0,0 +1,301 @@
/*---------------------------------------------------------------------------/
/ FatFs Functional Configurations
/---------------------------------------------------------------------------*/
#define FFCONF_DEF 86631 /* Revision ID */
/*---------------------------------------------------------------------------/
/ Function Configurations
/---------------------------------------------------------------------------*/
#define FF_FS_READONLY 0
/* This option switches read-only configuration. (0:Read/Write or 1:Read-only)
/ Read-only configuration removes writing API functions, f_write(), f_sync(),
/ f_unlink(), f_mkdir(), f_chmod(), f_rename(), f_truncate(), f_getfree()
/ and optional writing functions as well. */
#define FF_FS_MINIMIZE 0
/* This option defines minimization level to remove some basic API functions.
/
/ 0: Basic functions are fully enabled.
/ 1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_truncate() and f_rename()
/ are removed.
/ 2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1.
/ 3: f_lseek() function is removed in addition to 2. */
#define FF_USE_FIND 0
/* This option switches filtered directory read functions, f_findfirst() and
/ f_findnext(). (0:Disable, 1:Enable 2:Enable with matching altname[] too) */
#define FF_USE_MKFS 0
/* This option switches f_mkfs() function. (0:Disable or 1:Enable) */
#define FF_USE_FASTSEEK 0
/* This option switches fast seek function. (0:Disable or 1:Enable) */
#define FF_USE_EXPAND 0
/* This option switches f_expand function. (0:Disable or 1:Enable) */
#define FF_USE_CHMOD 0
/* This option switches attribute manipulation functions, f_chmod() and f_utime().
/ (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */
#define FF_USE_LABEL 0
/* This option switches volume label functions, f_getlabel() and f_setlabel().
/ (0:Disable or 1:Enable) */
#define FF_USE_FORWARD 0
/* This option switches f_forward() function. (0:Disable or 1:Enable) */
#define FF_USE_STRFUNC 0
#define FF_PRINT_LLI 0
#define FF_PRINT_FLOAT 0
#define FF_STRF_ENCODE 0
/* FF_USE_STRFUNC switches string functions, f_gets(), f_putc(), f_puts() and
/ f_printf().
/
/ 0: Disable. FF_PRINT_LLI, FF_PRINT_FLOAT and FF_STRF_ENCODE have no effect.
/ 1: Enable without LF-CRLF conversion.
/ 2: Enable with LF-CRLF conversion.
/
/ FF_PRINT_LLI = 1 makes f_printf() support long long argument and FF_PRINT_FLOAT = 1/2
makes f_printf() support floating point argument. These features want C99 or later.
/ When FF_LFN_UNICODE >= 1 with LFN enabled, string functions convert the character
/ encoding in it. FF_STRF_ENCODE selects assumption of character encoding ON THE FILE
/ to be read/written via those functions.
/
/ 0: ANSI/OEM in current CP
/ 1: Unicode in UTF-16LE
/ 2: Unicode in UTF-16BE
/ 3: Unicode in UTF-8
*/
/*---------------------------------------------------------------------------/
/ Locale and Namespace Configurations
/---------------------------------------------------------------------------*/
#define FF_CODE_PAGE 437
/* This option specifies the OEM code page to be used on the target system.
/ Incorrect code page setting can cause a file open failure.
/
/ 437 - U.S.
/ 720 - Arabic
/ 737 - Greek
/ 771 - KBL
/ 775 - Baltic
/ 850 - Latin 1
/ 852 - Latin 2
/ 855 - Cyrillic
/ 857 - Turkish
/ 860 - Portuguese
/ 861 - Icelandic
/ 862 - Hebrew
/ 863 - Canadian French
/ 864 - Arabic
/ 865 - Nordic
/ 866 - Russian
/ 869 - Greek 2
/ 932 - Japanese (DBCS)
/ 936 - Simplified Chinese (DBCS)
/ 949 - Korean (DBCS)
/ 950 - Traditional Chinese (DBCS)
/ 0 - Include all code pages above and configured by f_setcp()
*/
#define FF_USE_LFN 0
#define FF_MAX_LFN 255
/* The FF_USE_LFN switches the support for LFN (long file name).
/
/ 0: Disable LFN. FF_MAX_LFN has no effect.
/ 1: Enable LFN with static working buffer on the BSS. Always NOT thread-safe.
/ 2: Enable LFN with dynamic working buffer on the STACK.
/ 3: Enable LFN with dynamic working buffer on the HEAP.
/
/ To enable the LFN, ffunicode.c needs to be added to the project. The LFN function
/ requiers certain internal working buffer occupies (FF_MAX_LFN + 1) * 2 bytes and
/ additional (FF_MAX_LFN + 44) / 15 * 32 bytes when exFAT is enabled.
/ The FF_MAX_LFN defines size of the working buffer in UTF-16 code unit and it can
/ be in range of 12 to 255. It is recommended to be set it 255 to fully support LFN
/ specification.
/ When use stack for the working buffer, take care on stack overflow. When use heap
/ memory for the working buffer, memory management functions, ff_memalloc() and
/ ff_memfree() exemplified in ffsystem.c, need to be added to the project. */
#define FF_LFN_UNICODE 0
/* This option switches the character encoding on the API when LFN is enabled.
/
/ 0: ANSI/OEM in current CP (TCHAR = char)
/ 1: Unicode in UTF-16 (TCHAR = WCHAR)
/ 2: Unicode in UTF-8 (TCHAR = char)
/ 3: Unicode in UTF-32 (TCHAR = DWORD)
/
/ Also behavior of string I/O functions will be affected by this option.
/ When LFN is not enabled, this option has no effect. */
#define FF_LFN_BUF 255
#define FF_SFN_BUF 12
/* This set of options defines size of file name members in the FILINFO structure
/ which is used to read out directory items. These values should be suffcient for
/ the file names to read. The maximum possible length of the read file name depends
/ on character encoding. When LFN is not enabled, these options have no effect. */
#define FF_FS_RPATH 0
/* This option configures support for relative path.
/
/ 0: Disable relative path and remove related functions.
/ 1: Enable relative path. f_chdir() and f_chdrive() are available.
/ 2: f_getcwd() function is available in addition to 1.
*/
/*---------------------------------------------------------------------------/
/ Drive/Volume Configurations
/---------------------------------------------------------------------------*/
#define FF_VOLUMES 1
/* Number of volumes (logical drives) to be used. (1-10) */
#define FF_STR_VOLUME_ID 0
#define FF_VOLUME_STRS "RAM","NAND","CF","SD","SD2","USB","USB2","USB3"
/* FF_STR_VOLUME_ID switches support for volume ID in arbitrary strings.
/ When FF_STR_VOLUME_ID is set to 1 or 2, arbitrary strings can be used as drive
/ number in the path name. FF_VOLUME_STRS defines the volume ID strings for each
/ logical drives. Number of items must not be less than FF_VOLUMES. Valid
/ characters for the volume ID strings are A-Z, a-z and 0-9, however, they are
/ compared in case-insensitive. If FF_STR_VOLUME_ID >= 1 and FF_VOLUME_STRS is
/ not defined, a user defined volume string table needs to be defined as:
/
/ const char* VolumeStr[FF_VOLUMES] = {"ram","flash","sd","usb",...
*/
#define FF_MULTI_PARTITION 0
/* This option switches support for multiple volumes on the physical drive.
/ By default (0), each logical drive number is bound to the same physical drive
/ number and only an FAT volume found on the physical drive will be mounted.
/ When this function is enabled (1), each logical drive number can be bound to
/ arbitrary physical drive and partition listed in the VolToPart[]. Also f_fdisk()
/ funciton will be available. */
#define FF_MIN_SS 512
#define FF_MAX_SS 512
/* This set of options configures the range of sector size to be supported. (512,
/ 1024, 2048 or 4096) Always set both 512 for most systems, generic memory card and
/ harddisk, but a larger value may be required for on-board flash memory and some
/ type of optical media. When FF_MAX_SS is larger than FF_MIN_SS, FatFs is configured
/ for variable sector size mode and disk_ioctl() function needs to implement
/ GET_SECTOR_SIZE command. */
#define FF_LBA64 0
/* This option switches support for 64-bit LBA. (0:Disable or 1:Enable)
/ To enable the 64-bit LBA, also exFAT needs to be enabled. (FF_FS_EXFAT == 1) */
#define FF_MIN_GPT 0x10000000
/* Minimum number of sectors to switch GPT as partitioning format in f_mkfs and
/ f_fdisk function. 0x100000000 max. This option has no effect when FF_LBA64 == 0. */
#define FF_USE_TRIM 0
/* This option switches support for ATA-TRIM. (0:Disable or 1:Enable)
/ To enable Trim function, also CTRL_TRIM command should be implemented to the
/ disk_ioctl() function. */
/*---------------------------------------------------------------------------/
/ System Configurations
/---------------------------------------------------------------------------*/
#define FF_FS_TINY 1
/* This option switches tiny buffer configuration. (0:Normal or 1:Tiny)
/ At the tiny configuration, size of file object (FIL) is shrinked FF_MAX_SS bytes.
/ Instead of private sector buffer eliminated from the file object, common sector
/ buffer in the filesystem object (FATFS) is used for the file data transfer. */
#define FF_FS_EXFAT 0
/* This option switches support for exFAT filesystem. (0:Disable or 1:Enable)
/ To enable exFAT, also LFN needs to be enabled. (FF_USE_LFN >= 1)
/ Note that enabling exFAT discards ANSI C (C89) compatibility. */
#define FF_FS_NORTC 1
#define FF_NORTC_MON 1
#define FF_NORTC_MDAY 1
#define FF_NORTC_YEAR 2020
/* The option FF_FS_NORTC switches timestamp functiton. If the system does not have
/ any RTC function or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable
/ the timestamp function. Every object modified by FatFs will have a fixed timestamp
/ defined by FF_NORTC_MON, FF_NORTC_MDAY and FF_NORTC_YEAR in local time.
/ To enable timestamp function (FF_FS_NORTC = 0), get_fattime() function need to be
/ added to the project to read current time form real-time clock. FF_NORTC_MON,
/ FF_NORTC_MDAY and FF_NORTC_YEAR have no effect.
/ These options have no effect in read-only configuration (FF_FS_READONLY = 1). */
#define FF_FS_NOFSINFO 0
/* If you need to know correct free space on the FAT32 volume, set bit 0 of this
/ option, and f_getfree() function at first time after volume mount will force
/ a full FAT scan. Bit 1 controls the use of last allocated cluster number.
/
/ bit0=0: Use free cluster count in the FSINFO if available.
/ bit0=1: Do not trust free cluster count in the FSINFO.
/ bit1=0: Use last allocated cluster number in the FSINFO if available.
/ bit1=1: Do not trust last allocated cluster number in the FSINFO.
*/
#define FF_FS_LOCK 0
/* The option FF_FS_LOCK switches file lock function to control duplicated file open
/ and illegal operation to open objects. This option must be 0 when FF_FS_READONLY
/ is 1.
/
/ 0: Disable file lock function. To avoid volume corruption, application program
/ should avoid illegal open, remove and rename to the open objects.
/ >0: Enable file lock function. The value defines how many files/sub-directories
/ can be opened simultaneously under file lock control. Note that the file
/ lock control is independent of re-entrancy. */
/* #include <somertos.h> // O/S definitions */
#define FF_FS_REENTRANT 0
#define FF_FS_TIMEOUT 1000
#define FF_SYNC_t HANDLE
/* The option FF_FS_REENTRANT switches the re-entrancy (thread safe) of the FatFs
/ module itself. Note that regardless of this option, file access to different
/ volume is always re-entrant and volume control functions, f_mount(), f_mkfs()
/ and f_fdisk() function, are always not re-entrant. Only file/directory access
/ to the same volume is under control of this function.
/
/ 0: Disable re-entrancy. FF_FS_TIMEOUT and FF_SYNC_t have no effect.
/ 1: Enable re-entrancy. Also user provided synchronization handlers,
/ ff_req_grant(), ff_rel_grant(), ff_del_syncobj() and ff_cre_syncobj()
/ function, must be added to the project. Samples are available in
/ option/syscall.c.
/
/ The FF_FS_TIMEOUT defines timeout period in unit of time tick.
/ The FF_SYNC_t defines O/S dependent sync object type. e.g. HANDLE, ID, OS_EVENT*,
/ SemaphoreHandle_t and etc. A header file for O/S definitions needs to be
/ included somewhere in the scope of ff.h. */
/*--- End of configuration options ---*/
+170
View File
@@ -0,0 +1,170 @@
/*------------------------------------------------------------------------*/
/* Sample Code of OS Dependent Functions for FatFs */
/* (C)ChaN, 2018 */
/*------------------------------------------------------------------------*/
#include "ff.h"
#if FF_USE_LFN == 3 /* Dynamic memory allocation */
/*------------------------------------------------------------------------*/
/* Allocate a memory block */
/*------------------------------------------------------------------------*/
void* ff_memalloc ( /* Returns pointer to the allocated memory block (null if not enough core) */
UINT msize /* Number of bytes to allocate */
)
{
return malloc(msize); /* Allocate a new memory block with POSIX API */
}
/*------------------------------------------------------------------------*/
/* Free a memory block */
/*------------------------------------------------------------------------*/
void ff_memfree (
void* mblock /* Pointer to the memory block to free (nothing to do if null) */
)
{
free(mblock); /* Free the memory block with POSIX API */
}
#endif
#if FF_FS_REENTRANT /* Mutal exclusion */
/*------------------------------------------------------------------------*/
/* Create a Synchronization Object */
/*------------------------------------------------------------------------*/
/* This function is called in f_mount() function to create a new
/ synchronization object for the volume, such as semaphore and mutex.
/ When a 0 is returned, the f_mount() function fails with FR_INT_ERR.
*/
//const osMutexDef_t Mutex[FF_VOLUMES]; /* Table of CMSIS-RTOS mutex */
int ff_cre_syncobj ( /* 1:Function succeeded, 0:Could not create the sync object */
BYTE vol, /* Corresponding volume (logical drive number) */
FF_SYNC_t* sobj /* Pointer to return the created sync object */
)
{
/* Win32 */
*sobj = CreateMutex(NULL, FALSE, NULL);
return (int)(*sobj != INVALID_HANDLE_VALUE);
/* uITRON */
// T_CSEM csem = {TA_TPRI,1,1};
// *sobj = acre_sem(&csem);
// return (int)(*sobj > 0);
/* uC/OS-II */
// OS_ERR err;
// *sobj = OSMutexCreate(0, &err);
// return (int)(err == OS_NO_ERR);
/* FreeRTOS */
// *sobj = xSemaphoreCreateMutex();
// return (int)(*sobj != NULL);
/* CMSIS-RTOS */
// *sobj = osMutexCreate(&Mutex[vol]);
// return (int)(*sobj != NULL);
}
/*------------------------------------------------------------------------*/
/* Delete a Synchronization Object */
/*------------------------------------------------------------------------*/
/* This function is called in f_mount() function to delete a synchronization
/ object that created with ff_cre_syncobj() function. When a 0 is returned,
/ the f_mount() function fails with FR_INT_ERR.
*/
int ff_del_syncobj ( /* 1:Function succeeded, 0:Could not delete due to an error */
FF_SYNC_t sobj /* Sync object tied to the logical drive to be deleted */
)
{
/* Win32 */
return (int)CloseHandle(sobj);
/* uITRON */
// return (int)(del_sem(sobj) == E_OK);
/* uC/OS-II */
// OS_ERR err;
// OSMutexDel(sobj, OS_DEL_ALWAYS, &err);
// return (int)(err == OS_NO_ERR);
/* FreeRTOS */
// vSemaphoreDelete(sobj);
// return 1;
/* CMSIS-RTOS */
// return (int)(osMutexDelete(sobj) == osOK);
}
/*------------------------------------------------------------------------*/
/* Request Grant to Access the Volume */
/*------------------------------------------------------------------------*/
/* This function is called on entering file functions to lock the volume.
/ When a 0 is returned, the file function fails with FR_TIMEOUT.
*/
int ff_req_grant ( /* 1:Got a grant to access the volume, 0:Could not get a grant */
FF_SYNC_t sobj /* Sync object to wait */
)
{
/* Win32 */
return (int)(WaitForSingleObject(sobj, FF_FS_TIMEOUT) == WAIT_OBJECT_0);
/* uITRON */
// return (int)(wai_sem(sobj) == E_OK);
/* uC/OS-II */
// OS_ERR err;
// OSMutexPend(sobj, FF_FS_TIMEOUT, &err));
// return (int)(err == OS_NO_ERR);
/* FreeRTOS */
// return (int)(xSemaphoreTake(sobj, FF_FS_TIMEOUT) == pdTRUE);
/* CMSIS-RTOS */
// return (int)(osMutexWait(sobj, FF_FS_TIMEOUT) == osOK);
}
/*------------------------------------------------------------------------*/
/* Release Grant to Access the Volume */
/*------------------------------------------------------------------------*/
/* This function is called on leaving file functions to unlock the volume.
*/
void ff_rel_grant (
FF_SYNC_t sobj /* Sync object to be signaled */
)
{
/* Win32 */
ReleaseMutex(sobj);
/* uITRON */
// sig_sem(sobj);
/* uC/OS-II */
// OSMutexPost(sobj);
/* FreeRTOS */
// xSemaphoreGive(sobj);
/* CMSIS-RTOS */
// osMutexRelease(sobj);
}
#endif
+15593
View File
File diff suppressed because it is too large. Load diff
+64
View File
@@ -300,6 +300,70 @@ int32_t button_gpio = %d, button_high = %d, button_pullup = %d; // "%s"
Handlers.append(HandleButton())
######################################################################
# SDCARD SPI CS Pin
######################################################################
class HandleSdcardChipSelectPin:
def __init__(self):
self.pin = None
self.ctr_dispatch = { 'DECL_SD_SPI_CS_PIN': self.decl_cs_pin }
def decl_cs_pin(self, req):
pin = req.split(None, 1)[1].strip()
if pin.startswith('"') and pin.endswith('"'):
pin = pin[1:-1].strip()
self.pin = pin
def generate_code(self, options):
cs_gpio = 0
pin = self.pin
if pin:
cs_gpio = HandlerConstants.lookup_pin(pin)
fmt = """
uint32_t sdcard_cs_gpio = %d; // "%s"
"""
return fmt % (cs_gpio, self.pin)
Handlers.append(HandleSdcardChipSelectPin())
######################################################################
# SDCARD SPI CS Pin
######################################################################
class HandleSoftwareSPIPins:
def __init__(self):
self.pins = {}
self.ctr_dispatch = {
'DECL_SWSPI_MOSI_PIN': self.decl_mosi_pin,
'DECL_SWSPI_MISO_PIN': self.decl_miso_pin,
'DECL_SWSPI_SCLK_PIN': self.decl_sclk_pin
}
def _parse_pin(self, req):
pin = req.split(None, 1)[1].strip()
if pin.startswith('"') and pin.endswith('"'):
pin = pin[1:-1].strip()
return pin
def decl_miso_pin(self, req):
self.pins["miso"] = self._parse_pin(req)
def decl_mosi_pin(self, req):
self.pins["mosi"] = self._parse_pin(req)
def decl_sclk_pin(self, req):
self.pins["sclk"] = self._parse_pin(req)
def generate_code(self, options):
args = []
for name in ["miso", "mosi", "sclk"]:
gpio = 0
pin = self.pins.get(name)
if pin:
gpio = HandlerConstants.lookup_pin(pin)
args.extend([gpio, pin])
fmt = """
uint32_t swspi_miso_gpio = %d; // "%s"
uint32_t swspi_mosi_gpio = %d; // "%s"
uint32_t swspi_sclk_gpio = %d; // "%s"
"""
return fmt % (*args,)
Handlers.append(HandleSoftwareSPIPins())
######################################################################
# Main code
+8
View File
@@ -85,3 +85,11 @@ config STATUS_LED_PIN
config HAVE_CHIPID
bool
default n
config HAVE_GPIO_SPI
bool
default n
config ENABLE_SDCARD
bool
default n
+6
View File
@@ -2,3 +2,9 @@
src-y += sched.c bootentry.c command.c flashcmd.c initial_pins.c
src-$(CONFIG_ENABLE_LED) += led.c
src-$(CONFIG_ENABLE_SDCARD) += ../lib/fatfs/ff.c sdcard.c
src-$(CONFIG_SDCARD_SPI) += sdcard_spi.c
src-$(CONFIG_SDCARD_SOFTWARE_SPI) += spi_software.c
dirs-$(CONFIG_ENABLE_SDCARD) += lib/fatfs
CFLAGS += -Ilib/fatfs
+21
View File
@@ -10,6 +10,14 @@
#include "byteorder.h" // cpu_to_le32
#include "command.h" // send_ack
static uint8_t command_enable = 1;
void
command_set_enable(uint8_t state)
{
command_enable = state;
}
uint_fast8_t
command_encode_and_frame(uint8_t *buf, const struct command_encoder *ce
, va_list args)
@@ -52,6 +60,13 @@ command_respond_nack(void)
command_respond(out, RESPONSE_NACK, ARRAY_SIZE(out));
}
static void
command_respond_busy(void)
{
uint32_t out[2];
command_respond(out, RESPONSE_COMMAND_BUSY, ARRAY_SIZE(out));
}
int
command_get_arg_count(uint32_t *data)
{
@@ -62,6 +77,12 @@ command_get_arg_count(uint32_t *data)
void
command_dispatch(uint8_t *buf, uint_fast8_t msglen)
{
if (CONFIG_ENABLE_SDCARD) {
if (!command_enable) {
command_respond_busy();
return;
}
}
uint32_t data[DIV_ROUND_UP(MESSAGE_MAX, 4)];
memcpy(data, buf, msglen);
uint32_t cmd = (le32_to_cpu(data[0]) >> 16) & 0xff;
+2
View File
@@ -28,6 +28,7 @@
#define RESPONSE_ACK 0xa0
#define RESPONSE_NACK 0xf1
#define RESPONSE_COMMAND_ERROR 0xf2
#define RESPONSE_COMMAND_BUSY 0xf3
// Command Format:
// <2 byte header> <1 byte cmd> <1 byte data word count> <data> <2 byte crc> <2 byte trailer>
@@ -58,6 +59,7 @@ void command_get_canbus_id(uint32_t *data);
void command_respond_ack(uint32_t acked_cmd, uint32_t *out, uint32_t out_len);
void command_respond_command_error(void);
int command_get_arg_count(uint32_t *data);
void command_set_enable(uint8_t state);
struct command_encoder {
uint32_t *data;
+15 -2
View File
@@ -35,13 +35,19 @@ command_connect(uint32_t *data)
static uint8_t complete;
static uint32_t complete_endtime;
void
set_complete(void)
{
complete = 1;
complete_endtime = timer_read_time() + timer_from_us(100000);
}
void
command_complete(uint32_t *data)
{
uint32_t out[3];
command_respond_ack(CMD_COMPLETE, out, ARRAY_SIZE(out));
complete = 1;
complete_endtime = timer_read_time() + timer_from_us(100000);
set_complete();
}
void
@@ -59,6 +65,13 @@ DECL_TASK(complete_task);
static uint8_t is_in_transfer;
void
set_in_transfer(uint8_t in_transfer)
{
is_in_transfer = in_transfer;
}
int
flashcmd_is_in_transfer(void)
{
+2
View File
@@ -1,6 +1,8 @@
#ifndef __FLASHCMD_H
#define __FLASHCMD_H
void set_complete(void);
int flashcmd_is_in_transfer(void);
void set_in_transfer(uint8_t in_transfer);
#endif // flashcmd.h
+45
View File
@@ -57,6 +57,51 @@ config FLASH_START
hex
default 0x0000
config SDCARD_SPI
bool
config SDCARD_SOFTWARE_SPI
bool
menu "SD Card Configuration"
depends on HAVE_GPIO_SPI
config ENABLE_SDCARD
bool "Enable SD Card"
default n
choice
depends on ENABLE_SDCARD
prompt "Interface"
config LPC_SD_SPI_SSP0
bool "SSP0 (on P0.17/P0.18/P0.15)"
select SDCARD_SPI
config LPC_SD_SPI_SSP1
bool "SSP1 (on P0.8/P0.9/P0.7)"
select SDCARD_SPI
config LPC_SOFTWARE_SPI
bool "Software SPI"
select SDCARD_SPI
select SDCARD_SOFTWARE_SPI
endchoice
config SWSPI_MISO_PIN
depends on SDCARD_SOFTWARE_SPI
string "Software SPI MISO Pin"
config SWSPI_MOSI_PIN
depends on SDCARD_SOFTWARE_SPI
string "Sofware SPI MOSI Pin"
config SWSPI_SCLK_PIN
depends on SDCARD_SOFTWARE_SPI
string "Software SPI SCLK Pin"
config SD_SPI_CS_PIN
depends on ENABLE_SDCARD
string "SPI CS Pin"
endmenu
config SD_SPI_BUS
int
default 0 if LPC_SD_SPI_SSP0
default 1 if LPC_SD_SPI_SSP1
default 0
config USBSERIAL
bool
config SERIAL
+1
View File
@@ -20,6 +20,7 @@ src-y += ../lib/lpc176x/device/system_LPC17xx.c
src-$(CONFIG_USBSERIAL) += lpc176x/usbserial.c lpc176x/chipid.c
src-$(CONFIG_USBSERIAL) += generic/usb_cdc.c
src-$(CONFIG_SERIAL) += lpc176x/serial.c generic/serial_irq.c
src-$(CONFIG_SDCARD_SPI) += lpc176x/spi.c
# Build the additional bin output file
+11
View File
@@ -21,4 +21,15 @@ struct gpio_in gpio_in_setup(uint8_t pin, int8_t pull_up);
void gpio_in_reset(struct gpio_in g, int8_t pull_up);
uint8_t gpio_in_read(struct gpio_in g);
struct spi_config {
void *spi;
uint32_t cr0, cpsr;
uint8_t bus;
};
struct spi_config spi_setup(uint32_t bus, uint8_t mode, uint32_t rate);
void spi_prepare(struct spi_config config);
void spi_transfer(struct spi_config config, uint8_t receive_data
, uint16_t len, uint8_t *data);
void spi_set_rate(struct spi_config *config, uint32_t rate);
#endif // gpio.h
+106
View File
@@ -0,0 +1,106 @@
// SPI support on lpc176x
//
// Copyright (C) 2018-2021 Kevin O'Connor <kevin@koconnor.net>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include "command.h" // DECL_ENUMERATION
#include "gpio.h" // spi_setup
#include "internal.h" // gpio_peripheral
struct spi_info {
LPC_SSP_TypeDef *spi;
uint8_t miso_pin, mosi_pin, sck_pin, pclk;
};
DECL_ENUMERATION("spi_bus", "ssp0", 0);
DECL_CONSTANT_STR("BUS_PINS_ssp0", "P0.17,P0.18,P0.15");
DECL_ENUMERATION("spi_bus", "ssp1", 1);
DECL_CONSTANT_STR("BUS_PINS_ssp1", "P0.8,P0.9,P0.7");
static const struct spi_info spi_bus[] = {
{ LPC_SSP0, GPIO(0, 17), GPIO(0, 18), GPIO(0, 15), PCLK_SSP0 },
{ LPC_SSP1, GPIO(0, 8), GPIO(0, 9), GPIO(0, 7), PCLK_SSP1 },
};
static void
spi_init(uint32_t bus)
{
static int have_run_init[ARRAY_SIZE(spi_bus)];
if (have_run_init[bus])
return;
have_run_init[bus] = 1;
// Configure MISO0, MOSI0, SCK0 pins
gpio_peripheral(spi_bus[bus].miso_pin, 2, 0);
gpio_peripheral(spi_bus[bus].mosi_pin, 2, 0);
gpio_peripheral(spi_bus[bus].sck_pin, 2, 0);
// Setup clock
enable_pclock(spi_bus[bus].pclk);
// Set initial registers
LPC_SSP_TypeDef *spi = spi_bus[bus].spi;
spi->CR0 = 0x07;
spi->CPSR = 254;
spi->CR1 = 1<<1;
}
void
spi_set_rate(struct spi_config *config, uint32_t rate)
{
config->cr0 &= 0xFF;
uint32_t pclk = get_pclock_frequency(spi_bus[config->bus].pclk);
uint32_t div = DIV_ROUND_UP(pclk/4, rate) << 1;
config->cpsr = div < 2 ? 2 : (div > 254 ? 254 : div);
}
struct spi_config
spi_setup(uint32_t bus, uint8_t mode, uint32_t rate)
{
// Make sure bus is enabled
spi_init(bus);
// Setup clock rate and mode
struct spi_config res = {spi_bus[bus].spi, 0, 0};
res.cr0 = 0x07 | ((mode & 2) << 5) | ((mode & 1) << 7) | (1 << 8);
res.bus = bus;
spi_set_rate(&res, rate);
return res;
}
void
spi_prepare(struct spi_config config)
{
LPC_SSP_TypeDef *spi = config.spi;
spi->CR0 = config.cr0;
spi->CPSR = config.cpsr;
}
void
spi_transfer(struct spi_config config, uint8_t receive_data
, uint16_t len, uint8_t *data)
{
LPC_SSP_TypeDef *spi = config.spi;
if (receive_data) {
while (len--) {
spi->DR = *data;
// wait for read data to be ready
while (!(spi->SR & (1<<2)))
;
// get data
*data++ = spi->DR;
}
} else {
while (len--) {
spi->DR = *data++;
// wait for read data to be ready
while (!(spi->SR & (1<<2)))
;
// read data (to clear receive fifo)
spi->DR;
}
}
}
+218
View File
@@ -0,0 +1,218 @@
// SDCard Upload implementation
//
// Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include <string.h> // memmove
#include "autoconf.h" // CONFIG_BLOCK_SIZE
#include "board/flash.h" // application_read_flash
#include "board/misc.h" // application_jump
#include "sdcard.h" // sdcard_init
#include "ff.h" // f_open
#include "diskio.h" // disk_initialize
#include "command.h" // command_set_enable
#include "flashcmd.h" // set_in_transfer
#include "sched.h" // DECL_TASK
static struct {
FATFS fs;
FIL file_obj;
DSTATUS disk_status;
uint8_t file_open;
uint8_t flash_state;
uint32_t block_address;
} ff_data;
enum {SDS_NEED_UPLOAD = 1, SDS_NEED_VERIFY, SDS_DONE};
/**********************************************************
*
* FatFS Callbacks
*
* ********************************************************/
DSTATUS
disk_initialize(BYTE pdrv)
{
if (sdcard_init()) {
ff_data.disk_status = 0;
return 0;
}
return STA_NOINIT;
}
DSTATUS
disk_status(BYTE pdrv)
{
return ff_data.disk_status;
}
DRESULT
disk_read(BYTE pdrv, BYTE *buff, LBA_t sector, UINT count)
{
uint8_t* read_buf = buff;
while (count) {
if (!sdcard_read_sector(read_buf, sector++))
return RES_ERROR;
count--;
if (count)
read_buf += SD_SECTOR_SIZE;
}
return RES_OK;
}
DRESULT
disk_write(BYTE pdrv, const BYTE *buff, LBA_t sector, UINT count)
{
uint8_t* write_buf = (uint8_t *)buff;
while (count) {
if (!sdcard_write_sector(write_buf, sector++))
return RES_ERROR;
count--;
if (count)
write_buf += SD_SECTOR_SIZE;
}
return RES_OK;
}
DRESULT
disk_ioctl(BYTE pdrv, BYTE cmd, void *buff)
{
// No need for ioctls in a minimal fatfs implementation
return RES_OK;
}
static void
sdcard_close(void)
{
set_in_transfer(0);
if (ff_data.file_open)
f_close(&(ff_data.file_obj));
ff_data.file_open = 0;
f_unmount("");
memset(&(ff_data.fs), 0, sizeof(ff_data.fs));
sdcard_deinit();
}
void
sdcard_open(void)
{
if (!CONFIG_ENABLE_SDCARD)
return;
ff_data.disk_status = STA_NOINIT;
FRESULT res;
res = f_mount(&(ff_data.fs), "", 1);
if (res != FR_OK)
goto fail;
// open file in read mode
res = f_open(&(ff_data.file_obj), "firmware.bin", 1);
if (res != FR_OK)
goto fail;
ff_data.file_open = 1;
ff_data.flash_state = SDS_NEED_UPLOAD;
ff_data.block_address = CONFIG_APPLICATION_START;
command_set_enable(0);
set_in_transfer(1);
return;
fail:
sdcard_close();
}
DECL_INIT(sdcard_open);
static void
rename_firmware(const char* new_fname)
{
if (ff_data.file_open) {
f_close(&ff_data.file_obj);
ff_data.file_open = 0;
}
f_unlink(new_fname);
f_rename("firmware.bin", new_fname);
}
static void
sdcard_flash_error(void)
{
ff_data.flash_state = 0;
rename_firmware("firmware.err");
sdcard_close();
set_complete();
}
static void
sdcard_upload_block(void)
{
uint32_t sd_buf[CONFIG_BLOCK_SIZE / 4];
memset(sd_buf, 0xFF, CONFIG_BLOCK_SIZE);
UINT bcount;
if (f_read(&(ff_data.file_obj), sd_buf, CONFIG_BLOCK_SIZE,
&bcount) != FR_OK) {
// Transfer Error
sdcard_flash_error();
return;
}
if (flash_write_block(ff_data.block_address, sd_buf) < 0) {
sdcard_flash_error();
return;
}
ff_data.block_address += CONFIG_BLOCK_SIZE;
if (bcount < CONFIG_BLOCK_SIZE) {
if (flash_complete() < 0)
sdcard_flash_error();
else {
f_rewind(&ff_data.file_obj);
ff_data.block_address = CONFIG_APPLICATION_START;
ff_data.flash_state = SDS_NEED_VERIFY;
}
}
}
static void
sdcard_verify_block(void)
{
uint32_t sd_buf[CONFIG_BLOCK_SIZE / 4];
uint32_t flash_buf[CONFIG_BLOCK_SIZE];
memset(sd_buf, 0xFF, CONFIG_BLOCK_SIZE);
UINT bcount;
if (f_read(&(ff_data.file_obj), sd_buf, CONFIG_BLOCK_SIZE,
&bcount) != FR_OK) {
// Transfer Error
sdcard_flash_error();
return;
}
application_read_flash(ff_data.block_address, flash_buf);
if (memcmp(flash_buf, sd_buf, CONFIG_BLOCK_SIZE) != 0) {
sdcard_flash_error();
return;
}
ff_data.block_address += CONFIG_BLOCK_SIZE;
if (bcount < CONFIG_BLOCK_SIZE)
ff_data.flash_state = SDS_DONE;
}
void
sdcard_upload_task(void)
{
if (!CONFIG_ENABLE_SDCARD)
return;
switch(ff_data.flash_state) {
case SDS_NEED_UPLOAD:
sdcard_upload_block();
break;
case SDS_NEED_VERIFY:
sdcard_verify_block();
break;
case SDS_DONE:
ff_data.flash_state = 0;
rename_firmware("firmware.cur");
sdcard_close();
set_complete();
}
}
DECL_TASK(sdcard_upload_task);
+29
View File
@@ -0,0 +1,29 @@
#ifndef SDCARD_H
#define SDCARD_H
#include <stdint.h>
#define SDCMD_GO_IDLE_STATE 0
#define SDCMD_ALL_SEND_CID 2
#define SDCMD_SEND_REL_ADDR 3
#define SDCMD_IO_SEND_OP_COND 5
#define SDCMD_SEL_DESEL_CARD 7
#define SDCMD_SEND_IF_COND 8
#define SDCMD_SEND_CSD 9
#define SDCMD_SEND_OP_COND 41
#define SDCMD_SET_CLR_CD_DETECT 42
#define SDCMD_SEND_STATUS 13
#define SDCMD_SET_BLOCKLEN 16
#define SDCMD_READ_SINGLE_BLOCK 17
#define SDCMD_WRITE_BLOCK 24
#define SDCMD_APP_CMD 55
#define SDCMD_READ_OCR 58
#define SDCMD_CRC_ON_OFF 59
#define SD_SECTOR_SIZE 512
uint8_t sdcard_write_sector(uint8_t* buf, uint32_t sector);
uint8_t sdcard_read_sector(uint8_t *buf, uint32_t sector);
uint8_t sdcard_init(void);
void sdcard_deinit(void);
#endif
+445
View File
@@ -0,0 +1,445 @@
// SPI SDCard Commands
//
// Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include <string.h> // memmove
#include "autoconf.h" // CONFIG_SD_SPI_CS
#include "sdcard.h" // sdcard_init
#include "board/gpio.h" // gpio_out_setup
#include "board/misc.h" // timer_read_time
#include "board/io.h" // readb
#include "sched.h" // udelay
#include "spi_software.h" // spi_software_setup
DECL_CTR("DECL_SD_SPI_CS_PIN " __stringify(CONFIG_SD_SPI_CS_PIN));
extern uint32_t sdcard_cs_gpio; // Generated by buildcommands.py
#define CRC7_POLY 0x12
#define CRC16_POLY 0x1021
#define SPI_INIT_RATE 400000
#define SPI_XFER_RATE 4000000
static struct {
struct spi_config config;
struct gpio_out cs_pin;
uint8_t flags;
uint8_t err;
} sd_spi;
enum {SDF_INITIALIZED = 1, SDF_HIGH_CAPACITY = 2, SDF_WRITE_PROTECTED = 4,
SDF_DEINIT = 8};
enum {SDE_NO_IDLE = 1, SDE_IF_COND_ERR = 2, SDE_CRC_ERR = 4,
SDE_OP_COND_ERR = 8, SDE_OCR_ERR = 16, SDE_READ_ERR = 32,
SDE_WRITE_ERR = 64, SDE_OTHER_ERR = 128};
// COMMAND FLAGS
enum {CF_APP_CMD = 1, CF_FULL_RESP = 2, CF_NOT_EXPECT = 4};
/**********************************************************
*
* CRC Helper Methods
*
* ********************************************************/
// Standard CRC
static uint8_t
calc_crc7(uint8_t *data, uint16_t length)
{
uint8_t crc = 0;
while (length--)
{
crc ^= *data++;
for (uint8_t i = 0; i < 8; i++) {
if (crc & 0x80)
crc = (crc << 1) ^ CRC7_POLY;
else
crc = crc << 1;
}
}
return crc | 1;
}
static uint16_t
calc_crc16(uint8_t *data, uint16_t length)
{
uint16_t crc = 0;
while (length--)
{
crc ^= (*data++ << 8);
for (uint8_t i = 0; i < 8; i++) {
if (crc & 0x8000)
crc = (crc << 1) ^ CRC16_POLY;
else
crc = crc << 1;
}
}
return crc;
}
/**********************************************************
*
* SPI Device Methods
*
* ********************************************************/
static void
spidev_setup(void)
{
if (CONFIG_SDCARD_SOFTWARE_SPI)
spi_software_setup(0);
else
sd_spi.config = spi_setup(CONFIG_SD_SPI_BUS, 0, SPI_INIT_RATE);
}
static void
spidev_set_rate(uint32_t rate)
{
if (CONFIG_SDCARD_SOFTWARE_SPI)
return;
spi_set_rate(&(sd_spi.config), rate);
}
static void
spidev_prepare(void)
{
if (CONFIG_SDCARD_SOFTWARE_SPI)
spi_software_prepare();
else
spi_prepare(sd_spi.config);
}
static void
spidev_transfer(uint8_t receive_data, uint16_t len, uint8_t *data)
{
if (CONFIG_SDCARD_SOFTWARE_SPI)
spi_software_transfer(receive_data, len, data);
else
spi_transfer(sd_spi.config, receive_data, len, data);
}
/**********************************************************
*
* SD Card Commands
*
* ********************************************************/
static void
populate_buffer(uint8_t command, uint32_t arg, uint8_t* buf)
{
buf[0] = command | 0x40;
buf[1] = (arg >> 24) & 0xFF;
buf[2] = (arg >> 16) & 0xFF;
buf[3] = (arg >> 8) & 0xFF;
buf[4] = (arg & 0xFF);
uint8_t crc = calc_crc7(buf, 5);
buf[5] = crc;
}
static uint8_t
send_command(uint8_t command, uint32_t arg, uint8_t* buf, uint8_t cmd_flags)
{
uint8_t ret;
spidev_prepare();
gpio_out_write(sd_spi.cs_pin, 0);
memset(buf, 0, 8);
if (cmd_flags & CF_APP_CMD) {
buf[0] = SDCMD_APP_CMD | 0x40;
uint8_t crc = calc_crc7(buf, 5);
buf[5] = crc;
spidev_transfer(0, 6, buf);
}
populate_buffer(command, arg, buf);
spidev_transfer(0, 6, buf);
memset(buf, 0xFF, 8);
spidev_transfer(1, 8, buf);
for (uint8_t i = 0; i < 8; i++) {
ret = readb(&buf[i]);
if (ret != 0xFF) {
if (i) {
uint8_t recd = 8 - i;
memmove(buf, &buf[i], recd);
if (cmd_flags & CF_FULL_RESP) {
// need to read out a complete response
uint8_t rem = 8 - recd;
memset(&buf[recd], 0xFF, rem);
spidev_transfer(1, rem, &buf[recd]);
}
}
break;
}
}
gpio_out_write(sd_spi.cs_pin, 1);
return ret;
}
static uint8_t
check_command(uint8_t cmd, uint32_t arg, uint8_t* buf, uint8_t flags,
uint8_t expect, uint8_t attempts)
{
while (attempts) {
uint8_t ret = send_command(cmd, arg, buf, flags);
if (flags & CF_NOT_EXPECT) {
if (ret != expect)
return 1;
}
else if (ret == expect)
return 1;
attempts--;
if (attempts)
udelay((cmd == SDCMD_SEND_OP_COND) ? 100000 : 1000);
}
return 0;
}
static uint8_t
find_token(uint8_t token, uint32_t timeout_us)
{
uint8_t buf[1];
uint32_t endtime = timer_read_time() + timer_from_us(timeout_us);
while(timer_is_before(timer_read_time(), endtime))
{
writeb(buf, 0xFF);
spidev_transfer(1, 1, buf);
if (readb(buf) == token) {
return 1;
}
}
return 0;
}
uint8_t
sdcard_write_sector(uint8_t *buf, uint32_t sector)
{
if (!(sd_spi.flags & SDF_INITIALIZED))
return 0;
uint32_t offset = sector;
if (!(sd_spi.flags & SDF_HIGH_CAPACITY))
offset = sector * SD_SECTOR_SIZE;
uint16_t crc = calc_crc16(buf, SD_SECTOR_SIZE);
uint8_t cmd_buf[8];
uint8_t ret = 1;
populate_buffer(SDCMD_WRITE_BLOCK, offset, cmd_buf);
spidev_prepare();
gpio_out_write(sd_spi.cs_pin, 0);
spidev_transfer(0, 6, cmd_buf);
memset(cmd_buf, 0xFF, 8);
spidev_transfer(1, 8, cmd_buf);
for (uint8_t i = 0; i < 8; i++) {
ret = readb(&cmd_buf[i]);
if (ret != 0xFF)
break;
}
if (ret == 0xFF) {
gpio_out_write(sd_spi.cs_pin, 1);
sd_spi.err |= SDE_WRITE_ERR;
return 0;
}
// Send Header
cmd_buf[0] = 0xFE;
spidev_transfer(0, 1, cmd_buf);
// Send Data
spidev_transfer(0, SD_SECTOR_SIZE, buf);
// Send CRC
cmd_buf[0] = (crc >> 8) & 0xFF;
cmd_buf[1] = crc & 0xFF;
spidev_transfer(0, 2, cmd_buf);
// Check for successful response
memset(cmd_buf, 0xFF, 8);
spidev_transfer(1, 8, cmd_buf);
// Check the response
for (uint8_t i = 0; i < 8; i ++)
{
ret = readb(&cmd_buf[i]);
if (ret != 0xFF)
break;
}
if ((ret & 0x1F) == 5)
ret = 0;
else
ret = 2;
// Wait for card to come out of busy state, 50ms timeout
if (!find_token(0xFF, 50000))
ret += 1;
gpio_out_write(sd_spi.cs_pin, 1);
if (ret > 0) {
sd_spi.err |= SDE_WRITE_ERR;
return 0;
}
return 1;
}
static uint8_t
read_data_block(uint8_t cmd, uint32_t arg, uint8_t* buf, uint32_t length)
{
uint8_t ret = 0;
uint8_t cmd_buf[8];
populate_buffer(cmd, arg, cmd_buf);
spidev_prepare();
gpio_out_write(sd_spi.cs_pin, 0);
spidev_transfer(0, 6, cmd_buf);
// find the first non-zero response, maximum of 16 tries
for (uint8_t i = 0; i < 16; i++) {
writeb(cmd_buf, 0xFF);
spidev_transfer(1, 1, cmd_buf);
ret = readb(cmd_buf);
if (ret != 0xFF)
break;
}
if (ret != 0)
// Invalid Response
ret = 1;
// Find Transfer Start token, 50ms timeout
if (!find_token(0xFE, 50000))
ret = 2;
// Read out the response. This is done regardless
// of success to make sure the sdcard response is
// flushed
memset(buf, 0xFF, length);
spidev_transfer(1, length, buf);
// Read and check crc
memset(cmd_buf, 0xFF, 8);
spidev_transfer(1, 2, cmd_buf);
// Exit busy state
find_token(0xFF, 50000);
gpio_out_write(sd_spi.cs_pin, 1);
uint16_t recd_crc = (cmd_buf[0] << 8) | cmd_buf[1];
uint16_t crc = calc_crc16(buf, length);
if (recd_crc != crc) {
sd_spi.err |= SDE_CRC_ERR;
ret = 3;
}
if (ret > 0) {
sd_spi.err |= SDE_READ_ERR;
return 0;
}
return 1;
}
uint8_t
sdcard_read_sector(uint8_t *buf, uint32_t sector)
{
if (!(sd_spi.flags & SDF_INITIALIZED))
return 0;
uint32_t offset = sector;
if (!(sd_spi.flags & SDF_HIGH_CAPACITY))
offset = sector * SD_SECTOR_SIZE;
return read_data_block(
SDCMD_READ_SINGLE_BLOCK, offset, buf, SD_SECTOR_SIZE
);
}
static uint8_t
sdcard_check_write_protect(void)
{
// Read the CSD register to check the write protect
// bit. A name change can't be performed on a
// write protected card.
uint8_t csd_buf[16];
if (!read_data_block(SDCMD_SEND_CSD, 0, csd_buf, 16))
return 0;
if ((csd_buf[14] & 0x30) != 0)
// card is write protected
return 0;
return 1;
}
uint8_t
sdcard_init(void)
{
sd_spi.cs_pin = gpio_out_setup(sdcard_cs_gpio, 1);
spidev_setup();
// per the spec, delay for 1ms and apply a minimum of 74 clocks
// with CS high
udelay(1000);
spidev_prepare();
uint8_t buf[8];
memset(buf, 0xFF, 8);
for (uint8_t i = 0; i < 10; i++) {
spidev_transfer(0, 8, buf);
}
// attempt to go idle
if (!check_command(SDCMD_GO_IDLE_STATE, 0, buf, 0, 1, 50)) {
sd_spi.err |= SDE_NO_IDLE;
return 0;
}
// Check SD Card Version
uint8_t sd_ver = 0;
if (!check_command(SDCMD_SEND_IF_COND, 0x10A, buf,
CF_FULL_RESP | CF_NOT_EXPECT, 0xFF, 3))
{
sd_spi.err |= SDE_IF_COND_ERR;
return 0;
}
if (buf[0] & 4)
sd_ver = 1;
else if (buf[0] == 1 && buf[3] == 1 && buf[4] == 10)
sd_ver = 2;
else {
sd_spi.err |= SDE_IF_COND_ERR;
return 0;
}
// Enable CRC Checks
if (!check_command(SDCMD_CRC_ON_OFF, 1, buf, 0, 1, 3)) {
sd_spi.err |= SDE_CRC_ERR;
return 0;
}
// Read OCR Register to determine if voltage is acceptable
if (!check_command(SDCMD_READ_OCR, 0, buf, CF_FULL_RESP, 1, 20)) {
sd_spi.err |= SDE_OCR_ERR;
return 0;
}
if ((buf[2] & 0x30) != 0x30) {
// Voltage between 3.2-3.4v not supported by this
// card
sd_spi.err |= SDE_OCR_ERR;
return 0;
}
// Finsh init and come out of idle. This can take some time,
// give up to 20 attempts (100 ms delay between attempts)
if (!check_command(SDCMD_SEND_OP_COND, (sd_ver == 1) ? 0 : (1 << 30),
buf, CF_APP_CMD, 0, 20))
{
sd_spi.err |= SDE_OP_COND_ERR;
return 0;
}
if (sd_ver == 2) {
// read OCR again to determine capacity
if (!check_command(SDCMD_READ_OCR, 0, buf, CF_FULL_RESP, 0, 5)) {
sd_spi.err |= SDE_OCR_ERR;
return 0;
}
if (buf[1] & 0x40)
sd_spi.flags |= SDF_HIGH_CAPACITY;
}
if (!check_command(SDCMD_SET_BLOCKLEN, SD_SECTOR_SIZE, buf, 0, 0, 3)) {
sd_spi.err |= SDE_OTHER_ERR;
return 0;
}
if (!sdcard_check_write_protect()) {
sd_spi.flags |= SDF_WRITE_PROTECTED;
return 0;
}
sd_spi.flags |= SDF_INITIALIZED;
spidev_set_rate(SPI_XFER_RATE);
return 1;
}
void
sdcard_deinit(void)
{
if (sd_spi.flags & SDF_DEINIT)
return;
sd_spi.flags |= SDF_DEINIT;
uint8_t buf[8];
// return to idle and disable crc checks
send_command(SDCMD_GO_IDLE_STATE, 0, buf, 0);
send_command(SDCMD_CRC_ON_OFF, 0, buf, 0);
}
+69
View File
@@ -0,0 +1,69 @@
// Software SPI emulation
//
// Copyright (C) 2019 Kevin O'Connor <kevin@koconnor.net>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include "autoconf.h"
#include "board/gpio.h" // gpio_out_setup
#include "ctr.h" // DECL_CTR
DECL_CTR("DECL_SWSPI_MISO_PIN " __stringify(CONFIG_SWSPI_MISO_PIN));
DECL_CTR("DECL_SWSPI_MOSI_PIN " __stringify(CONFIG_SWSPI_MOSI_PIN));
DECL_CTR("DECL_SWSPI_SCLK_PIN " __stringify(CONFIG_SWSPI_SCLK_PIN));
extern uint32_t swspi_miso_gpio; // Generated by buildcommands.py
extern uint32_t swspi_mosi_gpio; // Generated by buildcommands.py
extern uint32_t swspi_sclk_gpio; // Generated by buildcommands.py
static struct spi_software {
struct gpio_in miso;
struct gpio_out mosi, sclk;
uint8_t mode;
} ss;
void
spi_software_setup(uint8_t mode)
{
ss.miso = gpio_in_setup(swspi_miso_gpio, 1);
ss.mosi = gpio_out_setup(swspi_mosi_gpio, 0);
ss.sclk = gpio_out_setup(swspi_sclk_gpio, 0);
ss.mode = mode;
}
void
spi_software_prepare(void)
{
gpio_out_write(ss.sclk, ss.mode & 0x02);
}
void
spi_software_transfer(uint8_t receive_data, uint16_t len, uint8_t *data)
{
while (len--) {
uint8_t outbuf = *data;
uint8_t inbuf = 0;
for (uint_fast8_t i = 0; i < 8; i++) {
if (ss.mode & 0x01) {
// MODE 1 & 3
gpio_out_toggle(ss.sclk);
gpio_out_write(ss.mosi, outbuf & 0x80);
outbuf <<= 1;
gpio_out_toggle(ss.sclk);
inbuf <<= 1;
inbuf |= gpio_in_read(ss.miso);
} else {
// MODE 0 & 2
gpio_out_write(ss.mosi, outbuf & 0x80);
outbuf <<= 1;
gpio_out_toggle(ss.sclk);
inbuf <<= 1;
inbuf |= gpio_in_read(ss.miso);
gpio_out_toggle(ss.sclk);
}
}
if (receive_data)
*data = inbuf;
data++;
}
}
+10
View File
@@ -0,0 +1,10 @@
#ifndef __SPI_SOFTWARE_H
#define __SPI_SOFTWARE_H
#include <stdint.h> // uint8_t
void spi_software_setup(uint8_t mode);
void spi_software_prepare(void);
void spi_software_transfer(uint8_t receive_data, uint16_t len, uint8_t *data);
#endif // spi_software.h
+75 -1
View File
@@ -174,6 +174,80 @@ config STM32F103GD_DISABLE_SWD
and PA14 pins from being available. Selecting this option
disables SWD at startup and thus makes these pins available.
config SDCARD_SPI
bool
config SDCARD_SOFTWARE_SPI
bool
config SDCARD_SDIO
bool
menu "SD Card Configuration"
depends on HAVE_GPIO_SPI
config ENABLE_SDCARD
bool "Enable SD Card"
default n
choice
depends on ENABLE_SDCARD
prompt "Interface"
config STM32_SD_SPI_1
bool "SPI1 (on PA6/PA7/PA5)"
select SDCARD_SPI
config STM32_SD_SPI_1A
bool "SPI1A (on PB4/PB5/PB3)"
select SDCARD_SPI
config STM32_SD_SPI_2
bool "SPI2 (on PB14/PB15/PB13)"
select SDCARD_SPI
config STM32_SD_SPI_2A
bool "SPI2A (on PC2/PC3/PB10)" if !MACH_STM32F1
select SDCARD_SPI
config STM32_SD_SPI_2B
bool "SPI2B (on PI2/PI3/PI1)" if MACH_STM32F405 || MACH_STM32F407
select SDCARD_SPI
config STM32_SD_SPI_3
bool "SPI3 (on PB4/PB5/PB3)" if !MACH_STM32F0
select SDCARD_SPI
config STM32_SD_SPI_3A
bool "SPI3A (on PC11/PC12/PC10)" if MACH_STM32F4
select SDCARD_SPI
config STM32_SD_SPI_4
bool "SPI4 (on PE13,PE14,PE12)" if MACH_STM32F401 || MACH_STM32F446
select SDCARD_SPI
config STM32_SOFTWARE_SPI
bool "Software SPI"
select SDCARD_SPI
select SDCARD_SOFTWARE_SPI
config STM32_SDIO
bool "SDIO (on PD2,PC8,PC9,PC10,PC11,PC12)" if MACH_STM32F103 || MACH_STM32F4
select SDCARD_SDIO
endchoice
config SWSPI_MISO_PIN
depends on SDCARD_SOFTWARE_SPI
string "Software SPI MISO Pin"
config SWSPI_MOSI_PIN
depends on SDCARD_SOFTWARE_SPI
string "Sofware SPI MOSI Pin"
config SWSPI_SCLK_PIN
depends on SDCARD_SOFTWARE_SPI
string "Software SPI SCLK Pin"
config SD_SPI_CS_PIN
depends on SDCARD_SPI
string "SPI CS Pin"
endmenu
config SD_SPI_BUS
int
default 0 if STM32_SD_SPI_2
default 1 if STM32_SD_SPI_1
default 2 if STM32_SD_SPI_1A
default 3 if STM32_SD_SPI_2A
default 4 if STM32_SD_SPI_3
default 5 if STM32_SD_SPI_3A
default 6 if STM32_SD_SPI_4 || STM32_SD_SPI_2B
default 0
######################################################################
# Bootloader
@@ -346,7 +420,7 @@ choice
config STM32_APP_START_8000
bool "32KiB offset" if MACH_STM32F2 || MACH_STM32F4
config STM32_APP_START_4000
bool "16KiB offset" if MACH_STM32F2 || MACH_STM32F4
bool "16KiB offset"
config STM32_APP_START_2000
bool "8KiB offset" if MACH_STM32F0 || MACH_STM32F1 || MACH_STM32G0
config STM32_APP_START_1000
+2
View File
@@ -55,6 +55,8 @@ serial-src-$(CONFIG_MACH_STM32H7) := stm32/stm32h7_serial.c
src-$(CONFIG_SERIAL) += $(serial-src-y) generic/serial_irq.c
src-$(CONFIG_CANSERIAL) += stm32/can.c ../lib/fast-hash/fasthash.c
src-$(CONFIG_CANSERIAL) += generic/canbus.c
src-$(CONFIG_SDCARD_SPI) += stm32/spi.c
src-$(CONFIG_SDCARD_SDIO) += stm32/sdio.c
dirs-$(CONFIG_CANSERIAL) += lib/fast-hash
+10
View File
@@ -23,4 +23,14 @@ struct gpio_in gpio_in_setup(uint32_t pin, int32_t pull_up);
void gpio_in_reset(struct gpio_in g, int32_t pull_up);
uint8_t gpio_in_read(struct gpio_in g);
struct spi_config {
void *spi;
uint32_t spi_cr1;
};
struct spi_config spi_setup(uint32_t bus, uint8_t mode, uint32_t rate);
void spi_prepare(struct spi_config config);
void spi_transfer(struct spi_config config, uint8_t receive_data
, uint16_t len, uint8_t *data);
void spi_set_rate(struct spi_config *config, uint32_t rate);
#endif // gpio.h
+481
View File
@@ -0,0 +1,481 @@
// SDIO Support for STM32 microcontrollers
//
// Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include <string.h> // memcpy
#include "autoconf.h" // CONFIG_MACH_STM32F1
#include "command.h" // DECL_CONSTANT_STR
#include "sdcard.h" // sdcard_init
#include "internal.h" // enable_pclock
#include "sched.h" // udelay
DECL_CONSTANT_STR("RESERVE_PINS_SDIO", "PD2,PC8,PC9,PC10,PC11,PC12");
#define GPIO_SDIO_CMD GPIO('D', 2)
#define GPIO_SDIO_D0 GPIO('C', 8)
#define GPIO_SDIO_D1 GPIO('C', 9)
#define GPIO_SDIO_D2 GPIO('C', 10)
#define GPIO_SDIO_D3 GPIO('C', 11)
#define GPIO_SDIO_CLK GPIO('C', 12)
#define SDIO_RESPONSE_SUCCESS 0
#define SDIO_RESPONSE_TIMEOUT -1
#define SDIO_RESPONSE_CRCERR -2
#define SDIO_RESPONSE_STA_ERR -3
#define SDIO_SHORT_RESPONSE (1 << 6)
#define SDIO_LONG_RESPONSE (3 << 6)
#define SDIO_READ_TIMEOUT_MS 100
#define SDIO_WRITE_TIMEOUT_MS 250
#define SDIO_CLOCK_USB 48000000
#define SDIO_CLOCK_NO_USB 50000000
// Rx Error Mask:
// SDIO_STA_RXUNDERR | SDIO_STA_DCRCFAIL | SDIO_STA_DTIMEOUT | SDIO_STA_STBITERR
#define SDIO_RX_ERR_MASK 0x22A
// Tx Error Mask:
// SDIO_STA_TXUNDERR | SDIO_STA_DCRCFAIL | SDIO_STA_DTIMEOUT | SDIO_STA_STBITERR
#define SDIO_TX_ERR_MASK 0x21A
#define SDIO_STATUS_ERR_MASK 0xFDF98008
#define SDIO_ICR_CLEAR_FLAGS 0x7FF
static struct {
uint32_t read_timeout, write_timeout, rca;
uint8_t flags, error;
} sdio_config;
enum {SDF_INITIALIZED = 1, SDF_XFER_MODE = 2, SDF_HIGH_CAPACITY = 4,
SDF_WRITE_PROTECTED = 8, SDF_CD_OFF = 16, SDF_DEINIT = 32};
enum {
SDIO_ERROR_NO_IDLE = 1,
SDIO_ERROR_SEND_IF_COND,
SDIO_ERROR_SEND_OP_COND,
SDIO_ERROR_BAD_OCR,
SDIO_ERROR_READ_BLOCK,
SDIO_ERROR_WRITE_BLOCK,
SDIO_ERROR_ALL_SEND_CID,
SDIO_ERROR_SEND_REL_ADDR,
SDIO_ERROR_SEND_CSD,
SDIO_ERROR_SEL_DESEL_CARD,
SDIO_ERROR_SET_CARD_DETECT,
SDIO_ERROR_SET_BLOCKLEN
};
static uint8_t
get_response_type(uint8_t command)
{
switch (command) {
case 0:
case 4:
case 15:
// No response
return 0;
case 3:
return 6;
case 5:
return 4;
case 2:
case 9:
case 10:
return 2;
case 41:
return 3;
case 8:
return 7;
default:
return 1;
}
}
static uint16_t
get_response_length(uint8_t command)
{
if (get_response_type(command) == 2)
return SDIO_LONG_RESPONSE;
return SDIO_SHORT_RESPONSE;
}
static uint8_t
response_has_crc(uint8_t command)
{
// Commands that return an R3 and R4b response do not
// include a CRC
if (command == 1 || command == 5 || command == 41)
return 0;
return 1;
}
static void
sdio_set_rate(uint32_t rate)
{
uint32_t sdioclk;
if (CONFIG_MACH_STM32F103)
// SDIO on the STM32F103 uses the HCLK frequency
sdioclk = CONFIG_CLOCK_FREQ;
else if (CONFIG_USBSERIAL)
sdioclk = SDIO_CLOCK_USB;
else
sdioclk = SDIO_CLOCK_NO_USB;
uint32_t div = DIV_ROUND_UP(sdioclk, rate);
div = (div > 256) ? 255 : ((div >= 2) ? (div - 2) : 0);
SDIO->CLKCR = (1 << 8) | (div & 0xFF);
uint32_t rate_actual = sdioclk / (div + 2);
sdio_config.read_timeout = (rate_actual / 1000) * SDIO_READ_TIMEOUT_MS;
sdio_config.write_timeout = (rate_actual / 1000) * SDIO_WRITE_TIMEOUT_MS;
}
static void
sdio_init(void)
{
enable_pclock((uint32_t)SDIO);
// Init SDIO GPIOs
gpio_peripheral(GPIO_SDIO_CMD, GPIO_FUNCTION(12), 0);
gpio_peripheral(GPIO_SDIO_D0, GPIO_FUNCTION(12), 0);
gpio_peripheral(GPIO_SDIO_D1, GPIO_FUNCTION(12), 0);
gpio_peripheral(GPIO_SDIO_D2, GPIO_FUNCTION(12), 0);
gpio_peripheral(GPIO_SDIO_D3, GPIO_FUNCTION(12), 0);
gpio_peripheral(GPIO_SDIO_CLK, GPIO_FUNCTION(12), 0);
// Initialize rate to 400K
sdio_set_rate(400000);
// Power on SDIO
SDIO->POWER = 0x3;
}
static void
sdio_power_off(void)
{
SDIO->POWER = 0;
}
static int
sdio_send_command(uint8_t command, uint32_t arg)
{
// clear status flags
SDIO->ICR = SDIO_ICR_CLEAR_FLAGS;
// set the command argument
SDIO->ARG = arg;
uint8_t resp_type = get_response_type(command);
uint8_t resp_len = 0;
uint32_t sta_mask;
if (resp_type) {
resp_type = get_response_length(command);
sta_mask = SDIO_STA_CTIMEOUT | SDIO_STA_CMDREND | SDIO_STA_CCRCFAIL;
}
else
sta_mask = SDIO_STA_CTIMEOUT | SDIO_STA_CMDSENT;
SDIO->CMD = (1 << 10) | resp_type | (command & 0x3f);
while(!(SDIO->STA & sta_mask));
uint32_t done_sta = SDIO->STA;
if (done_sta & SDIO_STA_CTIMEOUT)
return SDIO_RESPONSE_TIMEOUT;
if (resp_len) {
if (response_has_crc(command) && (done_sta & SDIO_STA_CCRCFAIL))
return SDIO_RESPONSE_CRCERR;
if (resp_type == 1 && (SDIO->RESP1 && SDIO_STATUS_ERR_MASK))
{
return SDIO_RESPONSE_STA_ERR;
}
}
return SDIO_RESPONSE_SUCCESS;
}
static uint8_t
wait_programming_done(void)
{
int ret = 0;
uint8_t state;
uint8_t tries = 100;
uint32_t response;
while (tries) {
udelay(1000);
ret = sdio_send_command(SDCMD_SEND_STATUS, sdio_config.rca);
response = SDIO->RESP1;
state = ((response >> 9) & 0xF);
if (ret != SDIO_RESPONSE_SUCCESS || (response & SDIO_STATUS_ERR_MASK))
tries--;
else if (state != 6 && state != 7)
return 1;
}
return 0;
}
static int
sdio_write_block(uint32_t* write_buf, uint32_t address)
{
SDIO->DCTRL = 0;
// write a single block
int ret = sdio_send_command(SDCMD_WRITE_BLOCK, address);
if (ret != SDIO_RESPONSE_SUCCESS) {
sdio_config.error = SDIO_ERROR_WRITE_BLOCK;
return ret;
}
SDIO->ICR = SDIO_ICR_CLEAR_FLAGS;
SDIO->DTIMER = sdio_config.write_timeout;
SDIO->DLEN = SD_SECTOR_SIZE;
SDIO->DCTRL = (9 << 4) | SDIO_DCTRL_DTEN;
uint32_t word_count = 0;
uint32_t status;
while (1) {
status = SDIO->STA;
if (status & SDIO_STA_TXFIFOHE &&
(word_count < (SD_SECTOR_SIZE / 4)))
{
SDIO->FIFO = write_buf[word_count++];
SDIO->FIFO = write_buf[word_count++];
SDIO->FIFO = write_buf[word_count++];
SDIO->FIFO = write_buf[word_count++];
SDIO->FIFO = write_buf[word_count++];
SDIO->FIFO = write_buf[word_count++];
SDIO->FIFO = write_buf[word_count++];
SDIO->FIFO = write_buf[word_count++];
}
if (status & SDIO_TX_ERR_MASK) {
ret = -4;
sdio_config.error = SDIO_ERROR_WRITE_BLOCK;
break;
} else if(status & SDIO_STA_DBCKEND)
break;
}
// Wait for card to finish transmitting/programming
if (!wait_programming_done()) {
ret = -5;
sdio_config.error = SDIO_ERROR_WRITE_BLOCK;
}
// clear transfer state
SDIO->DCTRL = 0;
SDIO->ICR = SDIO_ICR_CLEAR_FLAGS;
return ret;
}
static int
sdio_read_block(uint32_t* read_buf, uint32_t address)
{
// read a single block
int ret = sdio_send_command(SDCMD_READ_SINGLE_BLOCK, address);
if (ret != SDIO_RESPONSE_SUCCESS) {
sdio_config.error = SDIO_ERROR_READ_BLOCK;
return ret;
}
SDIO->DTIMER = sdio_config.read_timeout;
SDIO->DLEN = SD_SECTOR_SIZE;
SDIO->DCTRL = (9 << 4) | SDIO_DCTRL_DTDIR | SDIO_DCTRL_DTEN;
uint32_t word_count = 0;
uint32_t status;
while (1) {
status = SDIO->STA;
// Read out 8 words when FIFO is half full to maximize
// performance and prevent buffer overrun
if (status & SDIO_STA_RXFIFOHF) {
read_buf[word_count++] = SDIO->FIFO;
read_buf[word_count++] = SDIO->FIFO;
read_buf[word_count++] = SDIO->FIFO;
read_buf[word_count++] = SDIO->FIFO;
read_buf[word_count++] = SDIO->FIFO;
read_buf[word_count++] = SDIO->FIFO;
read_buf[word_count++] = SDIO->FIFO;
read_buf[word_count++] = SDIO->FIFO;
}
if (status & SDIO_RX_ERR_MASK) {
ret = -4;
sdio_config.error = SDIO_ERROR_READ_BLOCK;
break;
}
else if (status & SDIO_STA_DBCKEND)
break;
}
// Clear the buffer remaining buffer
while (SDIO->STA & SDIO_STA_RXDAVL)
read_buf[word_count++] = SDIO->FIFO;
// Verify we received the full sector
if (ret == SDIO_RESPONSE_SUCCESS && (word_count != (SD_SECTOR_SIZE / 4))) {
ret = -5;
sdio_config.error = SDIO_ERROR_READ_BLOCK;
}
// clear transfer state
SDIO->DCTRL = 0;
SDIO->ICR = SDIO_ICR_CLEAR_FLAGS;
return ret;
}
static uint8_t
check_command(uint8_t cmd, uint32_t arg, uint8_t is_acmd,
uint32_t expect, uint32_t mask, uint8_t attempts)
{
int ret;
while (attempts--) {
if (is_acmd) {
ret = sdio_send_command(SDCMD_APP_CMD, sdio_config.rca);
if (ret != SDIO_RESPONSE_SUCCESS) {
if (attempts) udelay(1000);
continue;
}
}
ret = sdio_send_command(cmd, arg);
if (ret == SDIO_RESPONSE_SUCCESS)
{
if ((get_response_type(cmd) == 0) ||
((SDIO->RESP1 & mask) == expect))
{
return 1;
}
}
if (attempts)
udelay((cmd == SDCMD_SEND_OP_COND) ? 100000 : 1000);
}
return 0;
}
static uint8_t
check_interface_condition(void)
{
int ret;
uint8_t attempts = 3;
uint32_t response;
while(attempts--)
{
// CMD8, Request 2.7V-3.6V range, check pattern 0x0A
ret = sdio_send_command(SDCMD_SEND_IF_COND, 0x10A);
response = SDIO->RESP1;
if (ret == SDIO_RESPONSE_TIMEOUT || (response & (1 << 22)))
// illegal command, version 1 card
return 1;
else if (ret == SDIO_RESPONSE_SUCCESS && (response & 0xFFF) == 0x10A)
return 2;
if (attempts) udelay(1000);
}
return 0;
}
/**********************************************************
*
* SDCard Methods
*
* ********************************************************/
uint8_t
sdcard_write_sector(uint8_t *buf, uint32_t sector)
{
if (!(sdio_config.flags & SDF_INITIALIZED))
return 0;
uint32_t addr = sector;
if (!(sdio_config.flags & SDF_HIGH_CAPACITY))
addr = sector * SD_SECTOR_SIZE;
int ret = sdio_write_block((uint32_t *)buf, addr);
if (ret < 0)
return 0;
return 1;
}
uint8_t
sdcard_read_sector(uint8_t *buf, uint32_t sector)
{
if (!(sdio_config.flags & SDF_INITIALIZED))
return 0;
uint32_t addr = sector;
if (!(sdio_config.flags & SDF_HIGH_CAPACITY))
addr = sector * SD_SECTOR_SIZE;
int ret = sdio_read_block((uint32_t *)buf, addr);
if (ret < 0)
return 0;
return 1;
}
uint8_t
sdcard_init(void)
{
uint8_t sd_ver;
sdio_init();
// Attempt software reset
// Software Reset (CMD0)
sdio_send_command(SDCMD_GO_IDLE_STATE, 0);
// Check interface condition to determine card version
sd_ver = check_interface_condition();
if (!sd_ver) {
sdio_config.error = SDIO_ERROR_SEND_IF_COND;
return 0;
}
// CMD41 - Go Operational, voltage window 3.2-3.4v
uint8_t arg = ((sd_ver == 1) ? 0 : (1 << 30)) | (3 << 20);
uint32_t ocr_expect = (1 << 31) | (3 << 20);
if (!check_command(SDCMD_SEND_OP_COND, arg, 1, ocr_expect, ocr_expect, 20))
{
sdio_config.error = SDIO_ERROR_SEND_OP_COND;
return 0;
}
if (SDIO->RESP1 & (1 << 30))
sdio_config.flags |= SDF_HIGH_CAPACITY;
// request CID
if (sdio_send_command(SDCMD_ALL_SEND_CID, 0) < 0) {
sdio_config.error = SDIO_ERROR_ALL_SEND_CID;
return 0;
}
// Set Relative Address, don't allow the card to select "0"
while (!sdio_config.rca) {
if (sdio_send_command(SDCMD_SEND_REL_ADDR, 0) < 0) {
sdio_config.error = SDIO_ERROR_SEND_REL_ADDR;
return 0;
}
sdio_config.rca = SDIO->RESP1 & 0xFFFF0000;
}
// Request CSD
if (sdio_send_command(SDCMD_SEND_CSD, sdio_config.rca) < 0) {
sdio_config.error = SDIO_ERROR_SEND_CSD;
return 0;
}
if (SDIO->RESP4 & (3 << 12)) {
// card is write protected, can't rename the
// firmware file after upload.
sdio_config.flags |= SDF_WRITE_PROTECTED;
sdio_config.error = SDIO_ERROR_WRITE_BLOCK;
return 0;
}
// card is out of identification mode, increase clock
sdio_set_rate(4000000);
// put card in transfer mode
if (sdio_send_command(SDCMD_SEL_DESEL_CARD, sdio_config.rca) < 0) {
sdio_config.error = SDIO_ERROR_SEL_DESEL_CARD;
return 0;
}
sdio_config.flags |= SDF_XFER_MODE;
if (check_command(SDCMD_SET_CLR_CD_DETECT, 0, 1, 0, 0, 1))
sdio_config.flags |= SDF_CD_OFF;
else {
sdio_config.error = SDIO_ERROR_SET_CARD_DETECT;
return 0;
}
// Set block length to 512
if (sdio_send_command(SDCMD_SET_BLOCKLEN, SD_SECTOR_SIZE) < 0) {
sdio_config.error = SDIO_ERROR_SET_BLOCKLEN;
return 0;
}
sdio_config.flags |= SDF_INITIALIZED;
return 1;
}
void
sdcard_deinit(void)
{
if (sdio_config.flags & SDF_DEINIT)
return;
sdio_config.flags |= SDF_DEINIT;
if (sdio_config.flags & SDF_CD_OFF) {
if (check_command(SDCMD_SET_CLR_CD_DETECT, 1, 1, 0, 0, 1))
sdio_config.flags &= ~SDF_CD_OFF;
}
if (sdio_config.flags |= SDF_XFER_MODE) {
sdio_send_command(SDCMD_SEL_DESEL_CARD, 0);
sdio_config.flags &= ~SDF_XFER_MODE;
}
sdio_send_command(SDCMD_GO_IDLE_STATE, 0);
sdio_power_off();
sdio_config.rca = 0;
}
+138
View File
@@ -0,0 +1,138 @@
// SPI functions on STM32
//
// Copyright (C) 2019 Kevin O'Connor <kevin@koconnor.net>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include "board/io.h" // readb, writeb
#include "command.h" // DECL_ENUMERATION
#include "gpio.h" // spi_setup
#include "internal.h" // gpio_peripheral
#include "sched.h" // sched_shutdown
struct spi_info {
SPI_TypeDef *spi;
uint8_t miso_pin, mosi_pin, sck_pin, function;
};
DECL_ENUMERATION("spi_bus", "spi2", 0);
DECL_CONSTANT_STR("BUS_PINS_spi2", "PB14,PB15,PB13");
DECL_ENUMERATION("spi_bus", "spi1", 1);
DECL_CONSTANT_STR("BUS_PINS_spi1", "PA6,PA7,PA5");
DECL_ENUMERATION("spi_bus", "spi1a", 2);
DECL_CONSTANT_STR("BUS_PINS_spi1a", "PB4,PB5,PB3");
#if !CONFIG_MACH_STM32F1
DECL_ENUMERATION("spi_bus", "spi2a", 3);
DECL_CONSTANT_STR("BUS_PINS_spi2a", "PC2,PC3,PB10");
#endif
#ifdef SPI3
DECL_ENUMERATION("spi_bus", "spi3", 4);
DECL_CONSTANT_STR("BUS_PINS_spi3", "PB4,PB5,PB3");
#if CONFIG_MACH_STM32F4
DECL_ENUMERATION("spi_bus", "spi3a", 5);
DECL_CONSTANT_STR("BUS_PINS_spi3a", "PC11,PC12,PC10");
#ifdef SPI4
DECL_ENUMERATION("spi_bus", "spi4", 6);
DECL_CONSTANT_STR("BUS_PINS_spi4", "PE13,PE14,PE12");
#elif defined(GPIOI)
DECL_ENUMERATION("spi_bus", "spi2b", 6);
DECL_CONSTANT_STR("BUS_PINS_spi2b", "PI2,PI3,PI1");
#endif
#endif
#endif
#if CONFIG_MACH_STM32F0 || CONFIG_MACH_STM32G0
#define SPI_FUNCTION GPIO_FUNCTION(0)
#else
#define SPI_FUNCTION GPIO_FUNCTION(5)
#endif
static const struct spi_info spi_bus[] = {
{ SPI2, GPIO('B', 14), GPIO('B', 15), GPIO('B', 13), SPI_FUNCTION },
{ SPI1, GPIO('A', 6), GPIO('A', 7), GPIO('A', 5), SPI_FUNCTION },
{ SPI1, GPIO('B', 4), GPIO('B', 5), GPIO('B', 3), SPI_FUNCTION },
{ SPI2, GPIO('C', 2), GPIO('C', 3), GPIO('B', 10), SPI_FUNCTION },
#ifdef SPI3
{ SPI3, GPIO('B', 4), GPIO('B', 5), GPIO('B', 3), GPIO_FUNCTION(6) },
#if CONFIG_MACH_STM32F4
{ SPI3, GPIO('C', 11), GPIO('C', 12), GPIO('C', 10), GPIO_FUNCTION(6) },
#ifdef SPI4
{ SPI4, GPIO('E', 13), GPIO('E', 14), GPIO('E', 12), GPIO_FUNCTION(5) },
#elif defined(GPIOI)
{ SPI2, GPIO('I', 2), GPIO('I', 3), GPIO('I', 1), GPIO_FUNCTION(5) },
#endif
#endif
#endif
};
struct spi_config
spi_setup(uint32_t bus, uint8_t mode, uint32_t rate)
{
// Enable SPI
SPI_TypeDef *spi = spi_bus[bus].spi;
if (!is_enabled_pclock((uint32_t)spi)) {
enable_pclock((uint32_t)spi);
gpio_peripheral(spi_bus[bus].miso_pin, spi_bus[bus].function, 1);
gpio_peripheral(spi_bus[bus].mosi_pin, spi_bus[bus].function, 0);
gpio_peripheral(spi_bus[bus].sck_pin, spi_bus[bus].function, 0);
// Configure CR2 on stm32f0
#if CONFIG_MACH_STM32F0 || CONFIG_MACH_STM32G0
spi->CR2 = SPI_CR2_FRXTH | (7 << SPI_CR2_DS_Pos);
#endif
}
// Calculate CR1 register
uint32_t pclk = get_pclock_frequency((uint32_t)spi);
uint32_t div = 0;
while ((pclk >> (div + 1)) > rate && div < 7)
div++;
uint32_t cr1 = ((mode << SPI_CR1_CPHA_Pos) | (div << SPI_CR1_BR_Pos)
| SPI_CR1_SPE | SPI_CR1_MSTR | SPI_CR1_SSM | SPI_CR1_SSI);
return (struct spi_config){ .spi = spi, .spi_cr1 = cr1 };
}
void
spi_set_rate(struct spi_config *config, uint32_t rate)
{
SPI_TypeDef *spi = config->spi;
uint32_t pclk = get_pclock_frequency((uint32_t)spi);
uint32_t div = 0;
while ((pclk >> (div + 1)) > rate && div < 7)
div++;
config->spi_cr1 &= ~SPI_CR1_BR;
config->spi_cr1 |= div << SPI_CR1_BR_Pos;
}
void
spi_prepare(struct spi_config config)
{
SPI_TypeDef *spi = config.spi;
uint32_t cr1 = spi->CR1;
if (cr1 == config.spi_cr1)
return;
// The SPE bit must be disabled before changing CPOL/CPHA bits
spi->CR1 = cr1 & ~SPI_CR1_SPE;
spi->CR1; // Force flush of previous write
spi->CR1 = config.spi_cr1;
}
void
spi_transfer(struct spi_config config, uint8_t receive_data,
uint16_t len, uint8_t *data)
{
SPI_TypeDef *spi = config.spi;
while (len--) {
writeb((void*)&spi->DR, *data);
while (!(spi->SR & SPI_SR_RXNE))
;
uint8_t rdata = readb((void*)&spi->DR);
if (receive_data)
*data = rdata;
data++;
}
// Wait for any remaining SCLK updates before returning
while ((spi->SR & (SPI_SR_TXE|SPI_SR_BSY)) != SPI_SR_TXE)
;
}