/**
 * flash_mutex.c
 *
 * Mutex (mutual exclusion) creation and access.
 * 
 * This mutex should be used for any Flash write command.
 * 
 * Flash writes are performed with the "efc_perform_command" function, 
 * which disables interrupts. This would seem that it is safe to use 
 * multithreaded. However, before the command function is called, the 
 * program must write to the Flash latch buffer. Interrupts are still 
 * enabled while the Flash buffer is being written. This means that 
 * potentially two different processes could be trying to write to the
 * Flash buffer at the same time, resulting in erroneous writes when 
 * either of those processes finally performs the Flash write command.
 * 
 * Copyright (c) 2022 Bigscreen, Inc.
 */

#include <asf.h>
#include "flash_mutex.h"

SemaphoreHandle_t Flash_Mutex_Handle;

uint32_t Init_Flash_Mutex(void) {
    Flash_Mutex_Handle = xSemaphoreCreateMutex();
    if(NULL == Flash_Mutex_Handle) return pdFAIL;
    return pdPASS;
}

SemaphoreHandle_t Get_Flash_Mutex(void) {
    return Flash_Mutex_Handle;
}

uint32_t Flash_Mutex_Lock(void) {
    return xSemaphoreTake(Flash_Mutex_Handle, portMAX_DELAY);
}
uint32_t Flash_Mutex_Unlock(void) {
    return xSemaphoreGive(Flash_Mutex_Handle);
}