38 #define likely(x) __builtin_expect(!!(x), 1)
39 #define unlikely(x) __builtin_expect(!!(x), 0)
41 #define MIN(x , y) (((x) < (y)) ? (x) : (y))
42 #define MAX(x , y) (((x) > (y)) ? (x) : (y))
43 #define IS_POWER_OF_TWO(s) ((s) && !((s) & ((s) - 1)))
45 #ifndef SDLOG_NUM_FILES
46 #error SDLOG_NUM_FILES should be defined in mcuconf.h
50 #if _FS_SHARE != 0 && _FS_SHARE < SDLOG_NUM_FILES
51 #error if _FS_SHARE is not zero, it should be equal of superior to SDLOG_NUM_FILES
55 #else // _FATFS > 8000
56 #if _FS_LOCK != 0 && _FS_LOCK < SDLOG_NUM_FILES
57 #error if _FS_LOCK is not zero, it should be equal of superior to SDLOG_NUM_FILES
61 #ifndef SDLOG_ALL_BUFFERS_SIZE
62 #error SDLOG_ALL_BUFFERS_SIZE should be defined in mcuconf.h
65 #if SDLOG_ALL_BUFFERS_SIZE > 65536
66 #error constraint 512 <= SDLOG_ALL_BUFFERS_SIZE <= 65536 not meet
69 #define SDLOG_WRITE_BUFFER_SIZE (SDLOG_ALL_BUFFERS_SIZE/SDLOG_NUM_FILES)
71 #ifndef SDLOG_MAX_MESSAGE_LEN
72 #error SDLOG_MAX_MESSAGE_LENshould be defined in mcuconf.h
75 #ifndef SDLOG_QUEUE_BUCKETS
76 #error SDLOG_QUEUE_BUCKETS should be defined in mcuconf.h
79 #if _FS_REENTRANT == 0
80 #warning "_FS_REENTRANT = 0 in ffconf.h DO NOT open close file during log"
83 #if SDLOG_WRITE_BUFFER_SIZE < 512
84 #error SDLOG_ALL_BUFFERS_SIZE / SDLOG_NUM_FILES cannot be < 512
87 #if (!(IS_POWER_OF_TWO (SDLOG_WRITE_BUFFER_SIZE)))
88 #error SDLOG_ALL_BUFFERS_SIZE / SDLOG_NUM_FILES should be a POWER OF 2
91 #ifdef SDLOG_NEED_QUEUE
116 #define WRITE_BYTE_CACHE_SIZE 15 // limit overhead :
128 struct FilePoolUnit {
131 systime_t lastFlushTs;
136 LogMessage *writeByteCache;
142 .fil = {{0}}, .inUse =
false, .tagAtClose =
false,
143 .writeByteCache = NULL, .writeByteSeek = 0
147 static volatile size_t nbBytesWritten = 0;
157 struct _SdLogBuffer {
164 #define LOG_MESSAGE_PREBUF_LEN (SDLOG_MAX_MESSAGE_LEN+sizeof(LogMessage))
165 #endif // SDLOG_NEED_QUEUE
170 #ifdef SDLOG_NEED_QUEUE
171 static size_t logMessageLen(
const LogMessage *lm);
172 static size_t logRawLen(
const size_t len);
173 static SdioError sdLoglaunchThread(
void);
175 static thread_t *sdLogThd = NULL;
177 static void removeFromQueue(
const size_t nbMsgToRFemov);
178 static void cleanQueue(
const bool allQueue);
179 static SdioError sdLogExpandLogFile(
const FileDes fileObject,
const size_t sizeInMo,
180 const bool preallocate);
182 #if (CH_KERNEL_MAJOR > 2)
183 static void thdSdLog(
void *arg) ;
185 static msg_t thdSdLog(
void *arg) ;
188 #endif // SDLOG_NEED_QUEUE
200 if (sdLogThd != NULL) {
205 #ifdef SDLOG_NEED_QUEUE
209 if (!sdc_lld_is_card_inserted(NULL)) {
215 chThdSleepMilliseconds(10);
223 FRESULT rc = f_mount(0, &fatfs);
225 FRESULT rc = f_mount(&fatfs,
"/", 1);
232 if (freeSpaceInKo != NULL) {
233 f_getfree(
"/", &clusters, &fsp);
234 *freeSpaceInKo = clusters * (
uint32_t)fatfs.csize / 2;
237 #ifdef SDLOG_NEED_QUEUE
239 fileDes[i].inUse = fileDes[i].tagAtClose =
false;
240 fileDes[i].writeByteCache = NULL;
241 fileDes[i].writeByteSeek = 0;
244 storageStatus = sdLoglaunchThread();
248 return storageStatus;
256 FRESULT rc = f_mount(0, NULL);
258 FRESULT rc = f_mount(NULL,
"", 0);
273 #ifdef SDLOG_NEED_QUEUE
275 const uint32_t autoFlushPeriod,
const bool appendTagAtClose,
276 const size_t sizeInMo,
const bool preallocate)
291 sde = getNextFIL(&ldf);
293 return storageStatus = sde;
296 sde =
getFileName(prefix, directoryName, fileName,
sizeof(fileName), +1);
303 rc = f_open(&fileDes[ldf].fil, fileName, FA_WRITE | FA_CREATE_ALWAYS);
305 fileDes[ldf].inUse =
false;
308 fileDes[ldf].tagAtClose = appendTagAtClose;
309 fileDes[ldf].autoFlushPeriod = autoFlushPeriod;
310 fileDes[ldf].lastFlushTs = 0;
311 sde = sdLogExpandLogFile(ldf, sizeInMo, preallocate);
315 return storageStatus = sde;
323 if (flush ==
false) {
330 if (fileDes[fd].inUse) {
331 FIL *
fo = &fileDes[
fd].fil;
332 if (fileDes[fd].tagAtClose) {
333 f_write(fo,
"\r\nEND_OF_LOG\r\n", 14, &bw);
334 nbBytesWritten += bw;
336 FRESULT trc = f_close(fo);
337 fileDes[
fd].inUse =
false;
350 if (sdLogThd == NULL) {
357 if (fileDes[fd].inUse) {
368 lm->op.fcntl = FCNTL_EXIT;
384 if (sdLogThd == NULL) {
391 if (fileDes[fd].inUse) {
392 status = sdLogFlushLog(fd);
399 return storageStatus =
status;
403 #define FD_CHECK(fd) if ((fd < 0) || (fd >= SDLOG_NUM_FILES) \
404 || (fileDes[fd].inUse == false)) \
405 return SDLOG_FATFS_ERROR
409 const bool preallocate)
414 const FRESULT rc = f_expand(&fileDes[fd].fil, sizeInMo * 1024 * 1024, preallocate);
437 lm->op.fcntl = FCNTL_WRITE;
438 lm->op.fd = fd & 0x1f;
444 const size_t msgLen = logMessageLen(lm);
475 lm->op.fcntl = FCNTL_FLUSH;
476 lm->op.fd = fd & 0x1f;
495 lm->op.fcntl = FCNTL_CLOSE;
496 lm->op.fd = fd & 0x1f;
513 if (
unlikely(fileDes[fd].writeByteCache != NULL)) {
514 if (
msgqueue_send(&messagesQueue, fileDes[fd].writeByteCache,
515 sizeof(LogMessage) + fileDes[fd].writeByteSeek,
519 fileDes[
fd].writeByteCache = NULL;
539 lm->op.fcntl = FCNTL_WRITE;
540 lm->op.fd = fd & 0x1f;
541 memcpy(lm->mess, buffer, len);
571 return sdb->lm->mess + sdb->offset;
576 if ((sdb->offset + offset) < sdb->len) {
586 return sdb->len - sdb->offset;
593 if ((fd < 0) || (fd >= SDLOG_NUM_FILES) || (fileDes[fd].inUse ==
false)) {
604 sdb->lm->op.fcntl = FCNTL_WRITE;
605 sdb->lm->op.fd = fd & 0x1f;
620 return storageStatus =
status;
631 if (fileDes[fd].writeByteCache == NULL) {
637 lm->op.fcntl = FCNTL_WRITE;
638 lm->op.fd = fd & 0x1f;
640 fileDes[
fd].writeByteCache = lm;
641 fileDes[
fd].writeByteSeek = 0;
643 lm = fileDes[
fd].writeByteCache;
646 lm->mess[fileDes[
fd].writeByteSeek++] = value;
648 if (fileDes[fd].writeByteSeek == WRITE_BYTE_CACHE_SIZE) {
653 fileDes[
fd].writeByteSeek = 0;
663 #define WA_LOG_BASE_SIZE 1024
676 chThdSleepMilliseconds(100);
678 sdLogThd = chThdCreateStatic(waThdSdLog,
sizeof(waThdSdLog),
679 NORMALPRIO + 1, thdSdLog, NULL);
680 if (sdLogThd == NULL) {
691 storageStatus = retVal;
692 if (sdLogThd == NULL) {
710 lm.op.fcntl = FCNTL_EXIT;
717 return storageStatus = retVal;
723 char *nextFileName,
const size_t nameLength,
const int indexOffset)
732 const size_t directoryNameLen =
MIN(strlen(directoryName), 128);
733 const size_t slashDirNameLen = directoryNameLen + 2;
734 char slashDirName[slashDirNameLen];
735 strlcpy(slashDirName,
"/", slashDirNameLen);
736 strlcat(slashDirName, directoryName, slashDirNameLen);
738 rc = f_opendir(&dir, directoryName);
740 rc = f_mkdir(slashDirName);
744 rc = f_opendir(&dir, directoryName);
751 rc = f_readdir(&dir, &fno);
752 if (rc != FR_OK || fno.fname[0] == 0) {
break; }
755 if (fno.fname[0] ==
'.') {
continue; }
757 if (!(fno.fattrib & AM_DIR)) {
760 maxCurrentIndex =
MAX(maxCurrentIndex, fileIndex);
767 rc = f_closedir(&dir);
774 directoryName, prefix, maxCurrentIndex + indexOffset);
777 chsnprintf(nextFileName, nameLength,
"%s\\%s%.ERR",
778 directoryName, prefix);
790 rc = f_opendir(&dir, directoryName);
796 rc = f_readdir(&dir, &fno);
797 if (rc != FR_OK || fno.fname[0] == 0) {
break; }
799 if (fno.fname[0] ==
'.') {
continue; }
801 if (!(fno.fattrib & AM_DIR)) {
803 if ((strncmp(fno.fname, prefix, strlen(prefix)) == 0) && (fno.fsize <= sizeConsideredEmpty)) {
804 char absPathName[128];
805 strlcpy(absPathName, directoryName,
sizeof(absPathName));
806 strlcat(absPathName,
"/",
sizeof(absPathName));
807 strlcat(absPathName, fno.fname,
sizeof(absPathName));
808 rc = f_unlink(absPathName);
820 rc = f_closedir(&dir);
845 const size_t len = strlen(prefix);
848 if (strncmp(prefix, fileName, len) != 0) {
853 const char *suffix = &(fileName[len]);
856 if (!isdigit((
int) suffix[0])) {
865 #ifdef SDLOG_NEED_QUEUE
866 static void cleanQueue(
const bool allQueue)
868 if (allQueue ==
false) {
872 const size_t freeRam = stat.mfree;
874 const bool queue_full = (chMBGetFreeCountI(&messagesQueue.
mb) <= 0);
877 if ((freeRam < 200) || (queue_full ==
true)) {
888 static void removeFromQueue(
const size_t nbMsgToRFemove)
900 LogMessage *lm = NULL;
901 for (
size_t i = 0; i < nbMsgToRFemove; i++) {
919 #if (CH_KERNEL_MAJOR > 2)
920 static void thdSdLog(
void *arg)
922 static msg_t thdSdLog(
void *arg)
935 chRegSetThreadName("thdSdLog");
937 LogMessage *lm = NULL;
940 FIL *fo = &fileDes[lm->op.fd].fil;
941 uint8_t *
const perfBuffer = perfBuffers[lm->op.fd].buffer;
943 switch (lm->op.fcntl) {
947 const uint16_t curBufFill = perfBuffers[lm->op.fd].size;
948 if (fileDes[lm->op.fd].inUse) {
950 f_write(fo, perfBuffer, curBufFill, &bw);
951 nbBytesWritten += bw;
952 perfBuffers[lm->op.fd].size = 0;
954 if (lm->op.fcntl == FCNTL_FLUSH) {
957 if (fileDes[lm->op.fd].tagAtClose) {
958 f_write(fo,
"\r\nEND_OF_LOG\r\n", 14, &bw);
959 nbBytesWritten += bw;
962 fileDes[lm->op.fd].inUse =
false;
976 const uint16_t curBufFill = perfBuffers[lm->op.fd].size;
977 if (fileDes[lm->op.fd].inUse) {
979 if (messLen < (SDLOG_WRITE_BUFFER_SIZE - curBufFill)) {
981 memcpy(&(perfBuffer[curBufFill]), lm->mess, (
size_t)(messLen));
982 perfBuffers[lm->op.fd].size = (
uint16_t)((perfBuffers[lm->op.fd].size) + messLen);
985 const int32_t stayLen = SDLOG_WRITE_BUFFER_SIZE - curBufFill;
986 memcpy(&(perfBuffer[curBufFill]), lm->mess, (
size_t)(stayLen));
987 FRESULT rc = f_write(fo, perfBuffer, SDLOG_WRITE_BUFFER_SIZE, &bw);
988 nbBytesWritten += bw;
991 if (fileDes[lm->op.fd].autoFlushPeriod) {
992 const systime_t now = chVTGetSystemTimeX();
993 if ((now - fileDes[lm->op.fd].lastFlushTs) >
996 fileDes[lm->op.fd].lastFlushTs = now;
1002 }
else if (bw != SDLOG_WRITE_BUFFER_SIZE) {
1006 memcpy(perfBuffer, &(lm->mess[stayLen]), (
uint32_t)(messLen - stayLen));
1007 perfBuffers[lm->op.fd].size = (
uint16_t)(messLen - stayLen);
1017 #if (CH_KERNEL_MAJOR == 2)
1022 static size_t logMessageLen(
const LogMessage *lm)
1027 static size_t logRawLen(
const size_t len)
1029 return sizeof(LogMessage) + len;
1038 if (fileDes[i].inUse ==
false) {
1040 fileDes[i].inUse =
true;
1047 size_t sdLogGetNbBytesWrittenToStorage(
void)
1049 return nbBytesWritten;
1054 return storageStatus;
SdioError sdLogFinish(void)
unmount filesystem
Specific RAM section for DMA usage on F7.
int32_t msgqueue_pop_timeout(MsgQueue *que, void **msgPtr, const systime_t timout)
receive message specifying timeout
static IN_DMA_SECTION(FATFS fatfs)
Mini printf-like functionality.
arch independent SDIO API
#define IN_STD_SECTION_CLEAR(var)
static SdioError flushWriteByteBuffer(const FileDes fd)
#define SDLOG_WRITE_BUFFER_SIZE
void msgqueue_init(MsgQueue *que, tlsf_memory_heap_t *heap, msg_t *mb_buf, const cnt_t mb_size)
initialise MsgQueue
#define SDLOG_MAX_MESSAGE_LEN
void chsnprintf(char *buffer, size_t size, const char *fmt,...)
static int32_t uiGetIndexOfLogFile(const char *prefix, const char *fileName)
int32_t msgqueue_copy_send(MsgQueue *que, const void *msg, const uint16_t msgLen, const MsgQueueUrgency urgency)
send a buffer NOT previously allocated
bool sdio_disconnect(void)
Disconnect a SD card on SDIO peripheral.
void tlsf_free_r(tlsf_memory_heap_t *heap, void *ptr)
void tlsf_stat_r(tlsf_memory_heap_t *heap, struct tlsf_stat_t *stat)
SdioError sdLogInit(uint32_t *freeSpaceInKo)
initialise sdLog
SdioError getFileName(const char *prefix, const char *directoryName, char *nextFileName, const size_t nameLength, const int indexOffset)
get last used name for a pattern, then add offset and return valid filename
#define SDLOG_QUEUE_BUCKETS
bool sdio_connect(void)
Connect a SD card on SDIO peripheral.
static const float offset[]
void * tlsf_realloc_r(tlsf_memory_heap_t *heap, void *ptr, size_t bytes)
SdioError removeEmptyLogs(const char *directoryName, const char *prefix, const size_t sizeConsideredEmpty)
remove spurious log file left on sd
void chvsnprintf(char *buffer, size_t size, const char *fmt, va_list ap)
int32_t msgqueue_pop(MsgQueue *que, void **msgPtr)
wait then receive message
int32_t msgqueue_send(MsgQueue *que, void *msg, const uint16_t msgLen, const MsgQueueUrgency urgency)
send a buffer previously allocated by msgqueue_malloc_before_send
#define IN_DMA_SECTION_CLEAR(var)
#define CH_CFG_ST_FREQUENCY
System tick frequency.
struct _SdLogBuffer SdLogBuffer
void * tlsf_malloc_r(tlsf_memory_heap_t *heap, size_t bytes)
static THD_WORKING_AREA(wa_thd_spi1, 1024)