Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions firmware/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ or
- Instant RPM is now used automatically on triggers with 24 or more teeth per engine cycle (a 12 tooth crank wheel or better), instead of only when "Always use instant RPM" was enabled. RPM, and everything derived from it, now responds within a fraction of an engine cycle instead of once per cycle. The setting remains, and now forces instant RPM on triggers with fewer teeth than that.

### Fixed
- Configuration burns now serialize direct, scheduled, and background writes with configuration reads. Requests made during a burn are preserved, and a failed burn stays pending until a new request. The `flash_status` console command reports the last result and completed driver writes.
- Changing or clearing the MAP 2, MAF, MAF 2 or fuel level sensor input no longer leaves the sensor reading its old pin (and the pin claimed) until the ECU is rebooted. MAF and fuel level input changes now take effect immediately, like other analog sensors
- STM32F7 dual-bank ECUs no longer stall (potentially stopping the engine) when burning configuration with the engine running - configuration is now committed to flash when the engine is stopped #776
- SD card log field names now include their category prefix (e.g. `Boost: Target` instead of just `Target`), matching the names shown in TunerStudio
Expand Down
79 changes: 79 additions & 0 deletions firmware/controllers/configuration_write.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
#pragma once

#include "flash_int.h"

enum class ConfigurationWritePhase {
Complete,
Layout,
Erase,
Program,
Verify,
};

struct ConfigurationWriteResult {
ConfigurationWritePhase phase;
flashaddr_t address;
int error;
// Copies whose erase and program operations completed successfully.
unsigned completedCopies;

bool success() const {
return phase == ConfigurationWritePhase::Complete;
}
};

// Callers serialize access. A failed attempt remains pending, but only a new
// request permits an automatic retry. Requests arriving during a write survive it.
class ConfigurationWriteState {
public:
void request() {
m_pending = true;
m_requested = true;
}

bool pending() const {
return m_pending;
}
bool writing() const {
return m_writing;
}
bool reading() const {
return m_reading;
}
bool shouldWrite() const {
return m_requested && !m_writing && !m_reading;
}

bool begin(bool requestedOnly = false) {
if (m_writing || m_reading || (requestedOnly && !m_requested)) {
return false;
}
m_pending = true;
m_requested = false;
m_writing = true;
return true;
}

void complete(bool success) {
m_writing = false;
m_pending = !success || m_requested;
}

bool beginRead() {
if (m_writing || m_reading) {
return false;
}
m_reading = true;
return true;
}

void endRead() {
m_reading = false;
}

private:
bool m_pending = false;
bool m_requested = false;
bool m_writing = false;
bool m_reading = false;
};
186 changes: 131 additions & 55 deletions firmware/controllers/flash_main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,24 @@

#if EFI_INTERNAL_FLASH

#if !EFI_UNIT_TEST
#include "mpu_util.h"
#endif
#include "flash_main.h"
#include "eficonsole.h"

#include "flash_int.h"
#include "crc_accelerator.h"
#include "configuration_write.h"

#if EFI_TUNER_STUDIO
#include "tunerstudio.h"
#endif

#include "runtime_state.h"

static bool needToWriteConfiguration = false;
static ConfigurationWriteState configurationWriteState;
static ConfigurationWriteResult lastWriteResult{ConfigurationWritePhase::Complete, 0, FLASH_RETURN_SUCCESS, 0};

/**
* https://sourceforge.net/p/rusefi/tickets/335/
Expand All @@ -37,6 +41,8 @@ static uint32_t flashStateCrc(const persistent_config_container_s& state) {
return singleCrc(&state.persistentConfiguration, sizeof(persistent_config_s));
}

static void writeConfiguration(bool requestedOnly);

#if EFI_FLASH_WRITE_THREAD
chibios_rt::BinarySemaphore flashWriteSemaphore(/*taken =*/true);

Expand All @@ -49,106 +55,159 @@ static void flashWriteThread(void*) {
// Wait for a request to come in
flashWriteSemaphore.wait();

// Do the actual flash write operation
writeToFlashNow();
// Claim a pending request atomically; a direct write may have consumed it.
writeConfiguration(true);
}
}
#endif // EFI_FLASH_WRITE_THREAD

void setNeedToWriteConfiguration() {
efiPrintf("Scheduling configuration write");
needToWriteConfiguration = true;

static void wakeFlashWriter() {
#if EFI_FLASH_WRITE_THREAD
if (allowFlashWhileRunning()) {
// Signal the flash writer thread to wake up and write at its leisure
flashWriteSemaphore.signal();
}
#endif // EFI_FLASH_WRITE_THREAD
#endif
}

void setNeedToWriteConfiguration() {
efiPrintf("Scheduling configuration write");
{
chibios_rt::CriticalSectionLocker lock;
configurationWriteState.request();
}
wakeFlashWriter();
}

bool getNeedToWriteConfiguration() {
return needToWriteConfiguration;
chibios_rt::CriticalSectionLocker lock;
return configurationWriteState.pending();
}

static bool shouldWriteConfiguration() {
chibios_rt::CriticalSectionLocker lock;
return configurationWriteState.shouldWrite();
}

void writeToFlashIfPending() {
// with a flash write thread, the schedule happens directly from
// setNeedToWriteConfiguration, so there's nothing to do here
if (allowFlashWhileRunning() || !getNeedToWriteConfiguration()) {
// Allow sensor timeouts again now that we're done (and a little time has passed)
// Keep failures visible, but require a new request before an automatic retry.
if (allowFlashWhileRunning() || !shouldWriteConfiguration()) {
Sensor::inhibitTimeouts(false);
return;
}

// Prevent sensor timeouts while flashing
Sensor::inhibitTimeouts(true);
writeToFlashNow();
// we do not want to allow sensor timeouts right away, we re-enable next time method is invoked
writeConfiguration(true);
// Re-enable timeouts on the next invocation, after sensors have had time to update.
}

// Erase and write a copy of the configuration at the specified address
// Keep storage operations here until the integrity/verification change.
template <typename TStorage>
int eraseAndFlashCopy(flashaddr_t storageAddress, const TStorage& data) {
// error already reported, return
static ConfigurationWriteResult
eraseAndFlashCopy(flashaddr_t storageAddress, const TStorage& data, unsigned completedCopies) {
if (!storageAddress) {
return FLASH_RETURN_SUCCESS;
return {ConfigurationWritePhase::Layout, storageAddress, FLASH_RETURN_NO_PERMISSION, completedCopies};
}

auto err = intFlashErase(storageAddress, sizeof(TStorage));
if (FLASH_RETURN_SUCCESS != err) {
firmwareError("Failed to erase flash at 0x%08x: %d", storageAddress, err);
return err;
if (err != FLASH_RETURN_SUCCESS) {
return {ConfigurationWritePhase::Erase, storageAddress, err, completedCopies};
}

err = intFlashWrite(storageAddress, reinterpret_cast<const char*>(&data), sizeof(TStorage));
if (FLASH_RETURN_SUCCESS != err) {
firmwareError("Failed to write flash at 0x%08x: %d", storageAddress, err);
return err;
if (err != FLASH_RETURN_SUCCESS) {
return {ConfigurationWritePhase::Program, storageAddress, err, completedCopies};
}

return err;
return {ConfigurationWritePhase::Complete, 0, FLASH_RETURN_SUCCESS, completedCopies + 1};
}

bool burnWithoutFlash = false;

void writeToFlashNow() {
engine->configBurnTimer.reset();
bool isSuccess = false;
writeConfiguration(false);
}

if (burnWithoutFlash) {
needToWriteConfiguration = false;
return;
static void writeConfiguration(bool requestedOnly) {
{
chibios_rt::CriticalSectionLocker lock;
if (!configurationWriteState.begin(requestedOnly)) {
// Preserve direct requests that arrive during another flash operation.
if (!requestedOnly) {
configurationWriteState.request();
}
return;
}
}
efiPrintf("Writing pending configuration...");

// Set up the container
persistentState.size = sizeof(persistentState);
persistentState.version = FLASH_DATA_VERSION;
persistentState.value = flashStateCrc(persistentState);
engine->configBurnTimer.reset();
ConfigurationWriteResult result{ConfigurationWritePhase::Complete, 0, FLASH_RETURN_SUCCESS, 0};

#if EFI_STORAGE_INT_FLASH == TRUE
// Flash two copies
int result1 = eraseAndFlashCopy(getFlashAddrFirstCopy(), persistentState);
int result2 = FLASH_RETURN_SUCCESS;
/* Only if second copy is supported */
if (getFlashAddrSecondCopy()) {
result2 = eraseAndFlashCopy(getFlashAddrSecondCopy(), persistentState);
}
if (!burnWithoutFlash) {
efiPrintf("Writing pending configuration...");
// No system lock is held while the driver erases, programs or sleeps.

// handle success/failure
isSuccess = (result1 == FLASH_RETURN_SUCCESS) && (result2 == FLASH_RETURN_SUCCESS);
persistentState.size = sizeof(persistentState);
persistentState.version = FLASH_DATA_VERSION;
persistentState.value = flashStateCrc(persistentState);

#if EFI_STORAGE_INT_FLASH == TRUE
result = eraseAndFlashCopy(getFlashAddrFirstCopy(), persistentState, 0);
// A known failure of the first copy must leave the backup untouched.
if (result.success() && getFlashAddrSecondCopy()) {
result = eraseAndFlashCopy(getFlashAddrSecondCopy(), persistentState, result.completedCopies);
}
#else
result = {ConfigurationWritePhase::Layout, 0, FLASH_RETURN_NO_PERMISSION, 0};
#endif
resetMaxValues();
}

if (isSuccess) {
efiPrintf("FLASH_SUCCESS");
} else {
efiPrintf("Flashing failed");
{
chibios_rt::CriticalSectionLocker lock;
lastWriteResult = result;
configurationWriteState.complete(result.success());
}
if (!burnWithoutFlash) {
if (result.success()) {
efiPrintf("FLASH_SUCCESS");
} else {
// Publish completion before reporting an error: production firmwareError can return.
firmwareError(
"Configuration flash failed: phase %d address 0x%08x error %d copies %u",
static_cast<int>(result.phase),
result.address,
result.error,
result.completedCopies);
}
}

resetMaxValues();
// A new request may have arrived while the low-priority H7 writer was busy.
if (shouldWriteConfiguration()) {
wakeFlashWriter();
}
}

// Write complete, clear the flag
needToWriteConfiguration = false;
static void printFlashStatus() {
ConfigurationWriteResult result;
bool pending;
bool writing;
bool reading;
{
chibios_rt::CriticalSectionLocker lock;
result = lastWriteResult;
pending = configurationWriteState.pending();
writing = configurationWriteState.writing();
reading = configurationWriteState.reading();
}
efiPrintf(
"flash_status pending=%d writing=%d reading=%d phase=%d address=0x%08x error=%d copies=%u",
pending,
writing,
reading,
static_cast<int>(result.phase),
result.address,
result.error,
result.completedCopies);
}

static void doResetConfiguration() {
Expand Down Expand Up @@ -225,6 +284,15 @@ static FlashState readConfiguration() {
}

void readFromFlash() {
bool canRead;
{
chibios_rt::CriticalSectionLocker lock;
canRead = configurationWriteState.beginRead();
}
if (!canRead) {
efiPrintf("Cannot read configuration while another flash operation is active");
return;
}
FlashState result = readConfiguration();

switch (result) {
Expand Down Expand Up @@ -253,10 +321,18 @@ void readFromFlash() {
// we can only change the state after the CRC check
engineConfiguration->byFirmwareVersion = getRusEfiVersion();
validateConfiguration();
{
chibios_rt::CriticalSectionLocker lock;
configurationWriteState.endRead();
}
if (shouldWriteConfiguration()) {
wakeFlashWriter();
}
}

void initFlash() {
addConsoleAction("readconfig", readFromFlash);
addConsoleAction("flash_status", printFlashStatus);
/**
* This would write NOW (you should not be doing this while connected to real engine)
*/
Expand Down
1 change: 1 addition & 0 deletions unit_tests/global.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ extern "C" {
#endif /* __cplusplus */

#define CH_FREQUENCY 1000
#define HAL_SUCCESS 0
#define NO_CACHE

typedef uint32_t systime_t;
Expand Down
Loading
Loading