eive-obsw/bsp_q7s/fs/SdCardManager.cpp

585 lines
18 KiB
C++

#include "SdCardManager.h"
#include <fsfw/ipc/MutexGuard.h>
#include <fsfw/timemanager/Countdown.h>
#include <fsfw/timemanager/Stopwatch.h>
#include <unistd.h>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <memory>
#include "OBSWConfig.h"
#include "bsp_q7s/memory/scratchApi.h"
#include "eive/definitions.h"
#include "eive/objects.h"
#include "fsfw/ipc/MutexFactory.h"
#include "fsfw/serviceinterface/ServiceInterface.h"
#include "linux/utility/utility.h"
SdCardManager* SdCardManager::INSTANCE = nullptr;
SdCardManager::SdCardManager() : SystemObject(objects::SDC_MANAGER), cmdExecutor(256) {
sdLock = MutexFactory::instance()->createMutex();
prefLock = MutexFactory::instance()->createMutex();
defaultLock = MutexFactory::instance()->createMutex();
MutexGuard mg(prefLock, LOCK_TYPE, OTHER_TIMEOUT, LOCK_CTX);
if (mg.getLockResult() != returnvalue::OK) {
sif::error << "SdCardManager::SdCardManager: Mutex lock failed" << std::endl;
}
uint8_t prefSdRaw = 0;
ReturnValue_t result = scratch::readNumber(scratch::PREFERED_SDC_KEY, prefSdRaw);
if (result != returnvalue::OK) {
if (result == scratch::KEY_NOT_FOUND) {
sif::warning << "CoreController::sdCardInit: "
"Preferred SD card not set. Setting to 0"
<< std::endl;
scratch::writeNumber(scratch::PREFERED_SDC_KEY, static_cast<uint8_t>(sd::SdCard::SLOT_0));
prefSdRaw = sd::SdCard::SLOT_0;
} else {
// Should not happen.
// TODO: Maybe trigger event?
sif::error << "SdCardManager::SdCardManager: Reading preferred SD card from scratch"
"buffer failed"
<< std::endl;
prefSdRaw = sd::SdCard::SLOT_0;
}
}
sdInfo.pref = static_cast<sd::SdCard>(prefSdRaw);
}
SdCardManager::~SdCardManager() {}
void SdCardManager::create() {
if (INSTANCE == nullptr) {
INSTANCE = new SdCardManager();
}
}
SdCardManager* SdCardManager::instance() {
SdCardManager::create();
return SdCardManager::INSTANCE;
}
ReturnValue_t SdCardManager::switchOnSdCard(sd::SdCard sdCard, bool doMountSdCard,
SdStatePair* statusPair) {
ReturnValue_t result = returnvalue::OK;
if (doMountSdCard) {
if (not blocking) {
sif::warning << "SdCardManager::switchOnSdCard: Two-step command but manager is"
" not configured for blocking operation. "
"Forcing blocking mode.."
<< std::endl;
blocking = true;
}
}
std::unique_ptr<SdStatePair> sdStatusPtr;
if (statusPair == nullptr) {
sdStatusPtr = std::make_unique<SdStatePair>();
statusPair = sdStatusPtr.get();
result = getSdCardsStatus(*statusPair);
if (result != returnvalue::OK) {
return result;
}
}
// Not allowed, this function turns on one SD card
if (sdCard == sd::SdCard::BOTH) {
sif::warning << "SdCardManager::switchOffSdCard: API does not allow sd::SdStatus::BOTH"
<< std::endl;
return returnvalue::FAILED;
}
sd::SdState currentState;
if (sdCard == sd::SdCard::SLOT_0) {
currentState = statusPair->first;
} else if (sdCard == sd::SdCard::SLOT_1) {
currentState = statusPair->second;
} else {
// Should not happen
currentState = sd::SdState::OFF;
}
if (currentState == sd::SdState::ON) {
if (not doMountSdCard) {
return ALREADY_ON;
} else {
return mountSdCard(sdCard);
}
} else if (currentState == sd::SdState::MOUNTED) {
result = ALREADY_MOUNTED;
} else if (currentState == sd::SdState::OFF) {
result = setSdCardState(sdCard, true);
} else {
result = returnvalue::FAILED;
}
if (result != returnvalue::OK or not doMountSdCard) {
return result;
}
return mountSdCard(sdCard);
}
ReturnValue_t SdCardManager::switchOffSdCard(sd::SdCard sdCard, SdStatePair& sdStates,
bool doUnmountSdCard) {
if (doUnmountSdCard) {
if (not blocking) {
sif::warning << "SdCardManager::switchOffSdCard: Two-step command but manager is"
" not configured for blocking operation. Forcing blocking mode.."
<< std::endl;
blocking = true;
}
}
// Not allowed, this function turns off one SD card
if (sdCard == sd::SdCard::BOTH) {
sif::warning << "SdCardManager::switchOffSdCard: API does not allow sd::SdStatus::BOTH"
<< std::endl;
return returnvalue::FAILED;
}
if (sdCard == sd::SdCard::SLOT_0) {
if (sdStates.first == sd::SdState::OFF) {
return ALREADY_OFF;
}
} else if (sdCard == sd::SdCard::SLOT_1) {
if (sdStates.second == sd::SdState::OFF) {
return ALREADY_OFF;
}
}
if (doUnmountSdCard) {
ReturnValue_t result = unmountSdCard(sdCard);
if (result != returnvalue::OK) {
return result;
}
}
return setSdCardState(sdCard, false);
}
ReturnValue_t SdCardManager::setSdCardState(sd::SdCard sdCard, bool on) {
using namespace std;
if (cmdExecutor.getCurrentState() == CommandExecutor::States::PENDING) {
return CommandExecutor::COMMAND_PENDING;
}
string sdstring = "";
string statestring = "";
if (sdCard == sd::SdCard::SLOT_0) {
sdstring = "0";
} else if (sdCard == sd::SdCard::SLOT_1) {
sdstring = "1";
}
if (on) {
currentOp = Operations::SWITCHING_ON;
statestring = "on";
} else {
currentOp = Operations::SWITCHING_OFF;
statestring = "off";
}
ostringstream command;
command << "q7hw sd set " << sdstring << " " << statestring;
cmdExecutor.load(command.str(), blocking, printCmdOutput);
ReturnValue_t result = cmdExecutor.execute();
if (result != returnvalue::OK) {
utility::handleSystemError(cmdExecutor.getLastError(), "SdCardManager::setSdCardState");
}
return result;
}
ReturnValue_t SdCardManager::getSdCardsStatus(SdStatePair& sdStates) {
MutexGuard mg(sdLock, LOCK_TYPE, SD_LOCK_TIMEOUT, LOCK_CTX);
sdStates = this->sdStates;
return returnvalue::OK;
}
ReturnValue_t SdCardManager::mountSdCard(sd::SdCard sdCard) {
using namespace std;
if (cmdExecutor.getCurrentState() == CommandExecutor::States::PENDING) {
sif::warning << "SdCardManager::mountSdCard: Command still pending" << std::endl;
return CommandExecutor::COMMAND_PENDING;
}
if (sdCard == sd::SdCard::BOTH) {
sif::warning << "SdCardManager::mountSdCard: API does not allow sd::SdStatus::BOTH"
<< std::endl;
return returnvalue::FAILED;
}
string mountDev;
string mountPoint;
if (sdCard == sd::SdCard::SLOT_0) {
mountDev = SD_0_DEV_NAME;
mountPoint = config::SD_0_MOUNT_POINT;
} else if (sdCard == sd::SdCard::SLOT_1) {
mountDev = SD_1_DEV_NAME;
mountPoint = config::SD_1_MOUNT_POINT;
}
std::error_code e;
if (not filesystem::exists(mountDev, e)) {
sif::warning << "SdCardManager::mountSdCard: Device file does not exists. Make sure to"
" turn on the SD card"
<< std::endl;
return MOUNT_ERROR;
}
if (not blocking) {
currentOp = Operations::MOUNTING;
}
string sdMountCommand = "mount " + mountDev + " " + mountPoint;
cmdExecutor.load(sdMountCommand, blocking, printCmdOutput);
ReturnValue_t result = cmdExecutor.execute();
if (blocking and result != returnvalue::OK) {
utility::handleSystemError(cmdExecutor.getLastError(), "SdCardManager::mountSdCard");
}
return result;
}
ReturnValue_t SdCardManager::unmountSdCard(sd::SdCard sdCard) {
if (cmdExecutor.getCurrentState() == CommandExecutor::States::PENDING) {
return CommandExecutor::COMMAND_PENDING;
}
using namespace std;
if (sdCard == sd::SdCard::BOTH) {
sif::warning << "SdCardManager::unmountSdCard: API does not allow sd::SdStatus::BOTH"
<< std::endl;
return returnvalue::FAILED;
}
string mountPoint;
if (sdCard == sd::SdCard::SLOT_0) {
mountPoint = config::SD_0_MOUNT_POINT;
} else if (sdCard == sd::SdCard::SLOT_1) {
mountPoint = config::SD_1_MOUNT_POINT;
}
std::error_code e;
if (not filesystem::exists(mountPoint, e)) {
sif::error << "SdCardManager::unmountSdCard: Default mount point " << mountPoint
<< "does not exist" << std::endl;
return UNMOUNT_ERROR;
}
if (filesystem::is_empty(mountPoint)) {
// The mount point will always exist, but if it is empty, that is strong hint that
// the SD card was not mounted properly. Still proceed with operation.
sif::warning << "SdCardManager::unmountSdCard: Mount point is empty!" << std::endl;
}
string sdUnmountCommand = "umount " + mountPoint;
if (not blocking) {
currentOp = Operations::UNMOUNTING;
}
cmdExecutor.load(sdUnmountCommand, blocking, printCmdOutput);
ReturnValue_t result = cmdExecutor.execute();
if (blocking and result != returnvalue::OK) {
utility::handleSystemError(cmdExecutor.getLastError(), "SdCardManager::unmountSdCard");
}
return result;
}
ReturnValue_t SdCardManager::sanitizeState(SdStatePair* statusPair, sd::SdCard prefSdCard) {
std::unique_ptr<SdStatePair> sdStatusPtr;
ReturnValue_t result = returnvalue::OK;
// Enforce blocking operation for now. Be careful to reset it when returning prematurely!
bool resetNonBlockingState = false;
if (not this->blocking) {
blocking = true;
resetNonBlockingState = true;
}
if (statusPair == nullptr) {
return returnvalue::FAILED;
}
getSdCardsStatus(*statusPair);
if (statusPair->first == sd::SdState::ON) {
result = mountSdCard(prefSdCard);
}
result = switchOnSdCard(prefSdCard, true, statusPair);
if (resetNonBlockingState) {
blocking = false;
}
return result;
}
void SdCardManager::resetState() {
cmdExecutor.reset();
currentOp = Operations::IDLE;
}
void SdCardManager::processSdStatusLine(std::string& line, uint8_t& idx, sd::SdCard& currentSd) {
using namespace std;
istringstream iss(line);
string word;
bool slotLine = false;
bool mountLine = false;
while (iss >> word) {
if (word == "Slot") {
slotLine = true;
}
if (word == "Mounted") {
mountLine = true;
}
if (slotLine) {
if (word == "1:") {
currentSd = sd::SdCard::SLOT_1;
}
if (word == "on") {
if (currentSd == sd::SdCard::SLOT_0) {
sdStates.first = sd::SdState::ON;
} else {
sdStates.second = sd::SdState::ON;
}
} else if (word == "off") {
MutexGuard mg(sdLock, LOCK_TYPE, SD_LOCK_TIMEOUT, LOCK_CTX);
if (currentSd == sd::SdCard::SLOT_0) {
sdStates.first = sd::SdState::OFF;
} else {
sdStates.second = sd::SdState::OFF;
}
}
}
if (mountLine) {
MutexGuard mg(sdLock, LOCK_TYPE, SD_LOCK_TIMEOUT, LOCK_CTX);
if (currentSd == sd::SdCard::SLOT_0) {
sdStates.first = sd::SdState::MOUNTED;
} else {
sdStates.second = sd::SdState::MOUNTED;
}
}
if (idx > 5) {
sif::warning << "SdCardManager::sdCardActive: /tmp/sd_status.txt has more than 6 "
"lines and might be invalid!"
<< std::endl;
}
}
idx++;
}
std::optional<sd::SdCard> SdCardManager::getPreferredSdCard() const {
MutexGuard mg(prefLock, LOCK_TYPE, OTHER_TIMEOUT, LOCK_CTX);
auto res = mg.getLockResult();
if (res != returnvalue::OK) {
sif::error << "SdCardManager::getPreferredSdCard: Lock error" << std::endl;
}
return sdInfo.pref;
}
ReturnValue_t SdCardManager::setPreferredSdCard(sd::SdCard sdCard) {
MutexGuard mg(prefLock, LOCK_TYPE, OTHER_TIMEOUT, LOCK_CTX);
if (sdCard == sd::SdCard::BOTH) {
return returnvalue::FAILED;
}
sdInfo.pref = sdCard;
return scratch::writeNumber(scratch::PREFERED_SDC_KEY, static_cast<uint8_t>(sdCard));
}
ReturnValue_t SdCardManager::updateSdCardStateFile() {
using namespace std;
if (cmdExecutor.getCurrentState() == CommandExecutor::States::PENDING) {
return CommandExecutor::COMMAND_PENDING;
}
// Use q7hw utility and pipe the command output into the state file
std::string updateCmd = "q7hw sd info all > " + std::string(SD_STATE_FILE);
cmdExecutor.load(updateCmd, true, printCmdOutput);
ReturnValue_t result = cmdExecutor.execute();
if (result != returnvalue::OK) {
utility::handleSystemError(cmdExecutor.getLastError(), "SdCardManager::mountSdCard");
}
std::error_code e;
if (not filesystem::exists(SD_STATE_FILE, e)) {
return STATUS_FILE_NEXISTS;
}
// Now the file should exist in any case. Still check whether it exists.
fstream sdStatus(SD_STATE_FILE);
if (not sdStatus.good()) {
return STATUS_FILE_NEXISTS;
}
string line;
uint8_t idx = 0;
sd::SdCard currentSd = sd::SdCard::SLOT_0;
// Process status file line by line
while (std::getline(sdStatus, line)) {
processSdStatusLine(line, idx, currentSd);
}
if (sdStates.first != sd::SdState::MOUNTED && sdStates.second != sd::SdState::MOUNTED) {
sdCardActive = false;
}
return returnvalue::OK;
}
const char* SdCardManager::getCurrentMountPrefix() const {
MutexGuard mg(defaultLock, LOCK_TYPE, OTHER_TIMEOUT, LOCK_CTX);
if (currentPrefix.has_value()) {
return currentPrefix.value().c_str();
}
return nullptr;
}
SdCardManager::OpStatus SdCardManager::checkCurrentOp(Operations& currentOp) {
CommandExecutor::States state = cmdExecutor.getCurrentState();
if (state == CommandExecutor::States::IDLE or state == CommandExecutor::States::COMMAND_LOADED) {
return OpStatus::IDLE;
}
currentOp = this->currentOp;
bool bytesRead = false;
#if OBSW_ENABLE_TIMERS == 1
Countdown timer(1000);
#endif
while (true) {
ReturnValue_t result = cmdExecutor.check(bytesRead);
// This timer can prevent deadlocks due to missconfigurations
#if OBSW_ENABLE_TIMERS == 1
if (timer.hasTimedOut()) {
sif::error << "SdCardManager::checkCurrentOp: Timeout!" << std::endl;
return OpStatus::FAIL;
}
#endif
switch (result) {
case (CommandExecutor::BYTES_READ): {
continue;
}
case (CommandExecutor::EXECUTION_FINISHED): {
return OpStatus::SUCCESS;
}
case (returnvalue::OK): {
return OpStatus::ONGOING;
}
case (returnvalue::FAILED): {
return OpStatus::FAIL;
}
default: {
sif::warning << "SdCardManager::checkCurrentOp: Unhandled case" << std::endl;
}
}
}
}
void SdCardManager::setBlocking(bool blocking) { this->blocking = blocking; }
void SdCardManager::setPrintCommandOutput(bool print) { this->printCmdOutput = print; }
bool SdCardManager::isSdCardUsable(std::optional<sd::SdCard> sdCard) {
{
MutexGuard mg(defaultLock, LOCK_TYPE, OTHER_TIMEOUT, LOCK_CTX);
if (markedUnusable) {
return false;
}
}
MutexGuard mg(sdLock, LOCK_TYPE, SD_LOCK_TIMEOUT, LOCK_CTX);
if (not sdCard) {
if (sdStates.first == sd::MOUNTED or sdStates.second == sd::MOUNTED) {
return true;
}
return false;
}
if (sdCard == sd::SLOT_0) {
if (sdStates.first == sd::MOUNTED) {
return true;
} else {
return false;
}
}
if (sdCard == sd::SLOT_1) {
if (sdStates.second == sd::MOUNTED) {
return true;
} else {
return false;
}
}
if (sdCard == sd::BOTH) {
if (sdStates.first == sd::MOUNTED && sdStates.second == sd::MOUNTED) {
return true;
}
}
return false;
}
ReturnValue_t SdCardManager::isSdCardMountedReadOnly(sd::SdCard sdcard, bool& readOnly) {
std::ostringstream command;
if (sdcard == sd::SdCard::SLOT_0) {
command << "grep -q '" << config::SD_0_MOUNT_POINT << " ext4 rw,' /proc/mounts";
} else if (sdcard == sd::SdCard::SLOT_1) {
command << "grep -q '" << config::SD_1_MOUNT_POINT << " ext4 rw,' /proc/mounts";
} else {
return returnvalue::FAILED;
}
ReturnValue_t result = cmdExecutor.load(command.str(), true, false);
if (result != returnvalue::OK) {
return result;
}
result = cmdExecutor.execute();
if (result == returnvalue::OK) {
readOnly = false;
return result;
}
readOnly = true;
return returnvalue::OK;
}
ReturnValue_t SdCardManager::remountReadWrite(sd::SdCard sdcard) {
std::ostringstream command;
if (sdcard == sd::SdCard::SLOT_0) {
command << "mount -o remount,rw " << SD_0_DEV_NAME << " " << config::SD_0_MOUNT_POINT;
} else {
command << "mount -o remount,rw " << SD_1_DEV_NAME << " " << config::SD_1_MOUNT_POINT;
}
ReturnValue_t result = cmdExecutor.load(command.str(), true, false);
if (result != returnvalue::OK) {
return result;
}
return cmdExecutor.execute();
}
ReturnValue_t SdCardManager::performFsck(sd::SdCard sdcard, bool printOutput, int& linuxError) {
std::ostringstream command;
if (sdcard == sd::SdCard::SLOT_0) {
command << "fsck -y " << SD_0_DEV_NAME;
} else {
command << "fsck -y " << SD_1_DEV_NAME;
}
ReturnValue_t result = cmdExecutor.load(command.str(), true, printOutput);
if (result != returnvalue::OK) {
return result;
}
result = cmdExecutor.execute();
if (result != returnvalue::OK) {
linuxError = cmdExecutor.getLastError();
}
return result;
}
void SdCardManager::setActiveSdCard(sd::SdCard sdCard) {
MutexGuard mg(defaultLock, LOCK_TYPE, OTHER_TIMEOUT, LOCK_CTX);
sdInfo.active = sdCard;
if (sdInfo.active == sd::SdCard::SLOT_0) {
currentPrefix = config::SD_0_MOUNT_POINT;
} else {
currentPrefix = config::SD_1_MOUNT_POINT;
}
}
std::optional<sd::SdCard> SdCardManager::getActiveSdCard() const {
MutexGuard mg(defaultLock, LOCK_TYPE, OTHER_TIMEOUT, LOCK_CTX);
if (markedUnusable) {
return std::nullopt;
}
return sdInfo.active;
}
void SdCardManager::markUnusable() {
MutexGuard mg(defaultLock, LOCK_TYPE, OTHER_TIMEOUT, LOCK_CTX);
markedUnusable = true;
}
void SdCardManager::markUsable() {
MutexGuard mg(defaultLock, LOCK_TYPE, OTHER_TIMEOUT, LOCK_CTX);
markedUnusable = false;
}