38 #define likely(x) __builtin_expect(!!(x), 1)
39 #define unlikely(x) __builtin_expect(!!(x), 0)
42 #define MIN(x , y) (((x) < (y)) ? (x) : (y))
45 #define MAX(x , y) (((x) > (y)) ? (x) : (y))
47 #define IS_POWER_OF_TWO(s) ((s) && !((s) & ((s) - 1)))
49 #ifndef SDLOG_NUM_FILES
50 #error SDLOG_NUM_FILES should be defined in mcuconf.h
55 #define FFCONF_DEF _FATFS
59 #if _FS_SHARE != 0 && _FS_SHARE < SDLOG_NUM_FILES
60 #error if _FS_SHARE is not zero, it should be equal of superior to SDLOG_NUM_FILES
64 #else // FFCONF_DEF > 8000
65 #if FF_FS_LOCK != 0 && FF_FS_LOCK < SDLOG_NUM_FILES
66 #error if FF_FS_LOCK is not zero, it should be equal of superior to SDLOG_NUM_FILES
70 #ifndef SDLOG_ALL_BUFFERS_SIZE
71 #error SDLOG_ALL_BUFFERS_SIZE should be defined in mcuconf.h
74 #if SDLOG_ALL_BUFFERS_SIZE > 65536
75 #error constraint 512 <= SDLOG_ALL_BUFFERS_SIZE <= 65536 not meet
78 #define SDLOG_WRITE_BUFFER_SIZE (SDLOG_ALL_BUFFERS_SIZE/SDLOG_NUM_FILES)
80 #ifndef SDLOG_MAX_MESSAGE_LEN
81 #error SDLOG_MAX_MESSAGE_LENshould be defined in mcuconf.h
84 #ifndef SDLOG_QUEUE_BUCKETS
85 #error SDLOG_QUEUE_BUCKETS should be defined in mcuconf.h
88 #if FF_FS_REENTRANT == 0
89 #warning "FF_FS_REENTRANT = 0 in ffconf.h DO NOT open close file during log"
92 #if SDLOG_WRITE_BUFFER_SIZE < 512
93 #error SDLOG_ALL_BUFFERS_SIZE / SDLOG_NUM_FILES cannot be < 512
96 #if (!(IS_POWER_OF_TWO (SDLOG_WRITE_BUFFER_SIZE)))
97 #error SDLOG_ALL_BUFFERS_SIZE / SDLOG_NUM_FILES should be a POWER OF 2
100 #ifdef SDLOG_NEED_QUEUE
125 #define WRITE_BYTE_CACHE_SIZE 15 // limit overhead :
137 struct FilePoolUnit {
140 systime_t lastFlushTs;
145 LogMessage *writeByteCache;
151 .fil = {{0}}, .inUse =
false, .tagAtClose =
false,
152 .writeByteCache = NULL, .writeByteSeek = 0
156 static volatile size_t nbBytesWritten = 0;
166 struct _SdLogBuffer {
173 #define LOG_MESSAGE_PREBUF_LEN (SDLOG_MAX_MESSAGE_LEN+sizeof(LogMessage))
174 #endif // SDLOG_NEED_QUEUE
179 #ifdef SDLOG_NEED_QUEUE
180 static size_t logMessageLen(
const LogMessage *lm);
181 static size_t logRawLen(
const size_t len);
182 static SdioError sdLoglaunchThread(
void);
184 static thread_t *sdLogThd = NULL;
186 static void removeFromQueue(
const size_t nbMsgToRFemov);
187 static void cleanQueue(
const bool allQueue);
188 static SdioError sdLogExpandLogFile(
const FileDes fileObject,
const size_t sizeInMo,
189 const bool preallocate);
191 #if (CH_KERNEL_MAJOR > 2)
192 static void thdSdLog(
void *arg) ;
194 static msg_t thdSdLog(
void *arg) ;
197 #endif // SDLOG_NEED_QUEUE
209 if (sdLogThd != NULL) {
214 #ifdef SDLOG_NEED_QUEUE
218 if (!sdc_lld_is_card_inserted(NULL)) {
224 chThdSleepMilliseconds(10);
231 #if FFCONF_DEF < 8000
232 FRESULT rc = f_mount(0, &fatfs);
234 FRESULT rc = f_mount(&fatfs,
"/", 1);
241 if (freeSpaceInKo != NULL) {
242 f_getfree(
"/", &clusters, &fsp);
243 *freeSpaceInKo = clusters * (
uint32_t)fatfs.csize / 2;
246 #ifdef SDLOG_NEED_QUEUE
248 fileDes[i].inUse = fileDes[i].tagAtClose =
false;
249 fileDes[i].writeByteCache = NULL;
250 fileDes[i].writeByteSeek = 0;
253 storageStatus = sdLoglaunchThread();
257 return storageStatus;
264 #if FFCONF_DEF < 8000
265 FRESULT rc = f_mount(0, NULL);
267 FRESULT rc = f_mount(NULL,
"", 0);
282 #ifdef SDLOG_NEED_QUEUE
284 const uint32_t autoFlushPeriod,
const bool appendTagAtClose,
285 const size_t sizeInMo,
const bool preallocate)
300 sde = getNextFIL(&ldf);
302 return storageStatus = sde;
305 sde =
getFileName(prefix, directoryName, fileName,
sizeof(fileName), +1);
312 rc = f_open(&fileDes[ldf].fil, fileName, FA_WRITE | FA_CREATE_ALWAYS);
314 fileDes[ldf].inUse =
false;
317 fileDes[ldf].tagAtClose = appendTagAtClose;
318 fileDes[ldf].autoFlushPeriod = autoFlushPeriod;
319 fileDes[ldf].lastFlushTs = 0;
320 sde = sdLogExpandLogFile(ldf, sizeInMo, preallocate);
324 return storageStatus = sde;
332 if (flush ==
false) {
339 if (fileDes[fd].inUse) {
340 FIL *
fo = &fileDes[
fd].fil;
341 if (fileDes[fd].tagAtClose) {
342 f_write(fo,
"\r\nEND_OF_LOG\r\n", 14, &bw);
343 nbBytesWritten += bw;
345 FRESULT trc = f_close(fo);
346 fileDes[
fd].inUse =
false;
359 if (sdLogThd == NULL) {
366 if (fileDes[fd].inUse) {
377 lm->op.fcntl = FCNTL_EXIT;
393 if (sdLogThd == NULL) {
400 if (fileDes[fd].inUse) {
401 status = sdLogFlushLog(fd);
408 return storageStatus =
status;
412 #define FD_CHECK(fd) if ((fd < 0) || (fd >= SDLOG_NUM_FILES) \
413 || (fileDes[fd].inUse == false)) \
414 return SDLOG_FATFS_ERROR
418 const bool preallocate)
423 const FRESULT rc = f_expand(&fileDes[fd].fil, sizeInMo * 1024 * 1024, preallocate);
446 lm->op.fcntl = FCNTL_WRITE;
447 lm->op.fd = fd & 0x1f;
453 const size_t msgLen = logMessageLen(lm);
484 lm->op.fcntl = FCNTL_FLUSH;
485 lm->op.fd = fd & 0x1f;
504 lm->op.fcntl = FCNTL_CLOSE;
505 lm->op.fd = fd & 0x1f;
522 if (
unlikely(fileDes[fd].writeByteCache != NULL)) {
523 if (
msgqueue_send(&messagesQueue, fileDes[fd].writeByteCache,
524 sizeof(LogMessage) + fileDes[fd].writeByteSeek,
528 fileDes[
fd].writeByteCache = NULL;
548 lm->op.fcntl = FCNTL_WRITE;
549 lm->op.fd = fd & 0x1f;
550 memcpy(lm->mess, buffer, len);
580 return sdb->lm->mess + sdb->offset;
585 if ((sdb->offset + offset) < sdb->len) {
595 return sdb->len - sdb->offset;
602 if ((fd < 0) || (fd >= SDLOG_NUM_FILES) || (fileDes[fd].inUse ==
false)) {
613 sdb->lm->op.fcntl = FCNTL_WRITE;
614 sdb->lm->op.fd = fd & 0x1f;
629 return storageStatus =
status;
640 if (fileDes[fd].writeByteCache == NULL) {
646 lm->op.fcntl = FCNTL_WRITE;
647 lm->op.fd = fd & 0x1f;
649 fileDes[
fd].writeByteCache = lm;
650 fileDes[
fd].writeByteSeek = 0;
652 lm = fileDes[
fd].writeByteCache;
655 lm->mess[fileDes[
fd].writeByteSeek++] = value;
657 if (fileDes[fd].writeByteSeek == WRITE_BYTE_CACHE_SIZE) {
662 fileDes[
fd].writeByteSeek = 0;
672 #define WA_LOG_BASE_SIZE 1024
675 static THD_WORKING_AREA(waThdSdLog, WA_LOG_BASE_SIZE+((_MAX_LFN+1)*2)+(19*32));
685 chThdSleepMilliseconds(100);
687 sdLogThd = chThdCreateStatic(waThdSdLog,
sizeof(waThdSdLog),
688 NORMALPRIO + 1, thdSdLog, NULL);
689 if (sdLogThd == NULL) {
700 storageStatus = retVal;
701 if (sdLogThd == NULL) {
719 lm.op.fcntl = FCNTL_EXIT;
726 return storageStatus = retVal;
732 char *nextFileName,
const size_t nameLength,
const int indexOffset)
741 const size_t directoryNameLen =
MIN(strlen(directoryName), 128);
742 const size_t slashDirNameLen = directoryNameLen + 2;
743 char slashDirName[slashDirNameLen];
744 strlcpy(slashDirName,
"/", slashDirNameLen);
745 strlcat(slashDirName, directoryName, slashDirNameLen);
747 rc = f_opendir(&dir, directoryName);
749 rc = f_mkdir(slashDirName);
753 rc = f_opendir(&dir, directoryName);
760 rc = f_readdir(&dir, &fno);
761 if (rc != FR_OK || fno.fname[0] == 0) {
break; }
764 if (fno.fname[0] ==
'.') {
continue; }
766 if (!(fno.fattrib & AM_DIR)) {
769 maxCurrentIndex =
MAX(maxCurrentIndex, fileIndex);
776 rc = f_closedir(&dir);
783 directoryName, prefix, maxCurrentIndex + indexOffset);
786 chsnprintf(nextFileName, nameLength,
"%s\\%s%.ERR",
787 directoryName, prefix);
799 rc = f_opendir(&dir, directoryName);
805 rc = f_readdir(&dir, &fno);
806 if (rc != FR_OK || fno.fname[0] == 0) {
break; }
808 if (fno.fname[0] ==
'.') {
continue; }
810 if (!(fno.fattrib & AM_DIR)) {
812 if ((strncmp(fno.fname, prefix, strlen(prefix)) == 0) && (fno.fsize <= sizeConsideredEmpty)) {
813 char absPathName[128];
814 strlcpy(absPathName, directoryName,
sizeof(absPathName));
815 strlcat(absPathName,
"/",
sizeof(absPathName));
816 strlcat(absPathName, fno.fname,
sizeof(absPathName));
817 rc = f_unlink(absPathName);
829 rc = f_closedir(&dir);
854 const size_t len = strlen(prefix);
857 if (strncmp(prefix, fileName, len) != 0) {
862 const char *suffix = &(fileName[len]);
865 if (!isdigit((
int) suffix[0])) {
874 #ifdef SDLOG_NEED_QUEUE
875 static void cleanQueue(
const bool allQueue)
877 if (allQueue ==
false) {
881 const size_t freeRam = stat.mfree;
883 const bool queue_full = (chMBGetFreeCountI(&messagesQueue.
mb) <= 0);
886 if ((freeRam < 200) || (queue_full ==
true)) {
897 static void removeFromQueue(
const size_t nbMsgToRFemove)
909 LogMessage *lm = NULL;
910 for (
size_t i = 0; i < nbMsgToRFemove; i++) {
928 #if (CH_KERNEL_MAJOR > 2)
929 static void thdSdLog(
void *arg)
931 static msg_t thdSdLog(
void *arg)
944 chRegSetThreadName("thdSdLog");
946 LogMessage *lm = NULL;
949 FIL *fo = &fileDes[lm->op.fd].fil;
950 uint8_t *
const perfBuffer = perfBuffers[lm->op.fd].buffer;
952 switch (lm->op.fcntl) {
956 const uint16_t curBufFill = perfBuffers[lm->op.fd].size;
957 if (fileDes[lm->op.fd].inUse) {
959 f_write(fo, perfBuffer, curBufFill, &bw);
960 nbBytesWritten += bw;
961 perfBuffers[lm->op.fd].size = 0;
963 if (lm->op.fcntl == FCNTL_FLUSH) {
966 if (fileDes[lm->op.fd].tagAtClose) {
967 f_write(fo,
"\r\nEND_OF_LOG\r\n", 14, &bw);
968 nbBytesWritten += bw;
971 fileDes[lm->op.fd].inUse =
false;
985 const uint16_t curBufFill = perfBuffers[lm->op.fd].size;
986 if (fileDes[lm->op.fd].inUse) {
988 if (messLen < (SDLOG_WRITE_BUFFER_SIZE - curBufFill)) {
990 memcpy(&(perfBuffer[curBufFill]), lm->mess, (
size_t)(messLen));
991 perfBuffers[lm->op.fd].size = (
uint16_t)((perfBuffers[lm->op.fd].size) + messLen);
994 const int32_t stayLen = SDLOG_WRITE_BUFFER_SIZE - curBufFill;
995 memcpy(&(perfBuffer[curBufFill]), lm->mess, (
size_t)(stayLen));
996 FRESULT rc = f_write(fo, perfBuffer, SDLOG_WRITE_BUFFER_SIZE, &bw);
997 nbBytesWritten += bw;
1000 if (fileDes[lm->op.fd].autoFlushPeriod) {
1001 const systime_t now = chVTGetSystemTimeX();
1002 if ((now - fileDes[lm->op.fd].lastFlushTs) >
1005 fileDes[lm->op.fd].lastFlushTs = now;
1011 }
else if (bw != SDLOG_WRITE_BUFFER_SIZE) {
1015 memcpy(perfBuffer, &(lm->mess[stayLen]), (
uint32_t)(messLen - stayLen));
1016 perfBuffers[lm->op.fd].size = (
uint16_t)(messLen - stayLen);
1026 #if (CH_KERNEL_MAJOR == 2)
1031 static size_t logMessageLen(
const LogMessage *lm)
1036 static size_t logRawLen(
const size_t len)
1038 return sizeof(LogMessage) + len;
1047 if (fileDes[i].inUse ==
false) {
1049 fileDes[i].inUse =
true;
1056 size_t sdLogGetNbBytesWrittenToStorage(
void)
1058 return nbBytesWritten;
1063 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
static THD_WORKING_AREA(wa_thd_spi1, 256)
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)