From 3ef0e8f603b294b6d51e98a6bdd3070076ca75d8 Mon Sep 17 00:00:00 2001
From: swym <0xfd000000@gmail.com>
Date: Mon, 19 Aug 2019 22:00:52 +0200
Subject: [PATCH] fatfs_schedule_attach: attach directly if we're running in
 thread context

---
 epicardium/fs/filesystem_fat.c |  9 ++++++++-
 epicardium/modules/usb.c       | 10 ++++++++--
 2 files changed, 16 insertions(+), 3 deletions(-)

diff --git a/epicardium/fs/filesystem_fat.c b/epicardium/fs/filesystem_fat.c
index 1e4998c4..2f513b76 100644
--- a/epicardium/fs/filesystem_fat.c
+++ b/epicardium/fs/filesystem_fat.c
@@ -25,6 +25,7 @@
 #include "modules/log.h"
 #include "modules/modules.h"
 #include "api/common.h"
+#include "core_cmFunc.h" //__get_IPSR()
 
 #define SSLOG_DEBUG(...) LOG_DEBUG("fatfs", __VA_ARGS__)
 #define SSLOG_INFO(...) LOG_INFO("fatfs", __VA_ARGS__)
@@ -167,7 +168,13 @@ int fatfs_attach()
 
 void fatfs_schedule_attach(void)
 {
-	xTimerPendFunctionCallFromISR(cb_attachTimer, NULL, 0, NULL);
+	//if we're running in thread context, cont't call the *FromISR version
+	if (__get_IPSR() == 0) {
+		xTimerPendFunctionCall(
+			cb_attachTimer, NULL, 0, 1); //wait 1 tick
+	} else {
+		xTimerPendFunctionCallFromISR(cb_attachTimer, NULL, 0, NULL);
+	}
 }
 
 void fatfs_detach()
diff --git a/epicardium/modules/usb.c b/epicardium/modules/usb.c
index 302ea846..e14032e4 100644
--- a/epicardium/modules/usb.c
+++ b/epicardium/modules/usb.c
@@ -133,23 +133,29 @@ static int mscmem_ready()
 	return mx25_ready();
 }
 
+static bool s_fsDetached = false;
 int epic_usb_shutdown(void)
 {
 	esb_deinit();
-	fatfs_attach();
+	if (s_fsDetached) {
+		fatfs_attach();
+	}
 	return 0;
 }
 
 int epic_usb_storage(void)
 {
 	esb_deinit();
+	s_fsDetached = true;
 	return esb_init(&s_cfg_msc);
 }
 
 int epic_usb_cdcacm(void)
 {
 	esb_deinit();
-	fatfs_attach();
+	if (s_fsDetached) {
+		fatfs_attach();
+	}
 	return esb_init(&s_cfg_cdcacm);
 }
 
-- 
GitLab