diff --git a/hal/common/flash-journal/flash-journal-strategy-sequential/config.h b/hal/common/flash-journal/flash-journal-strategy-sequential/config.h new file mode 100644 index 00000000000..f96eae908ac --- /dev/null +++ b/hal/common/flash-journal/flash-journal-strategy-sequential/config.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __FLASH_JOURNAL_CONFIG_H__ +#define __FLASH_JOURNAL_CONFIG_H__ + +#define SEQUENTIAL_FLASH_JOURNAL_MAX_LOGGED_BLOBS 4 + +#endif /* __FLASH_JOURNAL_CONFIG_H__ */ diff --git a/hal/common/flash-journal/flash-journal-strategy-sequential/flash_journal_private.h b/hal/common/flash-journal/flash-journal-strategy-sequential/flash_journal_private.h new file mode 100644 index 00000000000..207367745b6 --- /dev/null +++ b/hal/common/flash-journal/flash-journal-strategy-sequential/flash_journal_private.h @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __FLASH_JOURNAL_PRIVATE_H__ +#define __FLASH_JOURNAL_PRIVATE_H__ + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +#include "flash-journal/flash_journal.h" +#include "flash-journal-strategy-sequential/config.h" + +static const uint32_t SEQUENTIAL_FLASH_JOURNAL_INVALD_NEXT_SEQUENCE_NUMBER = 0xFFFFFFFFUL; +static const uint32_t SEQUENTIAL_FLASH_JOURNAL_VERSION = 1; +static const uint32_t SEQUENTIAL_FLASH_JOURNAL_MAGIC = 0xCE02102AUL; + +typedef enum { + SEQUENTIAL_JOURNAL_STATE_NOT_INITIALIZED, + SEQUENTIAL_JOURNAL_STATE_INIT_SCANNING_LOG_HEADERS, + SEQUENTIAL_JOURNAL_STATE_INITIALIZED, + SEQUENTIAL_JOURNAL_STATE_RESETING, + SEQUENTIAL_JOURNAL_STATE_LOGGING_ERASE, + SEQUENTIAL_JOURNAL_STATE_LOGGING_HEAD, + SEQUENTIAL_JOURNAL_STATE_LOGGING_BODY, + SEQUENTIAL_JOURNAL_STATE_LOGGING_TAIL, + SEQUENTIAL_JOURNAL_STATE_READING, +} SequentialFlashJournalState_t; + +/** + * Meta-data placed at the head of a sequential-log entry. + */ +typedef struct _SequentialFlashJournalLogHead { + uint32_t version; + uint32_t magic; + uint32_t sequenceNumber; + uint32_t reserved; +} SequentialFlashJournalLogHead_t; + +#define SEQUENTIAL_JOURNAL_VALID_HEAD(PTR) \ + (((PTR)->version == SEQUENTIAL_FLASH_JOURNAL_VERSION) && ((PTR)->magic == SEQUENTIAL_FLASH_JOURNAL_MAGIC)) + +/** + * Meta-data placed at the tail of a sequential-log entry. + * + * @note the most crucial items (the ones which play a role in the validation of + * the log-entry) are placed at the end of this structure; this ensures that + * a partially written log-entry-tail won't be accepted as valid. + */ +typedef struct _SequentialFlashJournalLogTail { + uint64_t sizeofBlob; /**< the size of the payload in this blob. */ + uint32_t magic; + uint32_t sequenceNumber; +} SequentialFlashJournalLogTail_t; + +#define SEQUENTIAL_JOURNAL_VALID_TAIL(TAIL_PTR) ((TAIL_PTR)->magic == SEQUENTIAL_FLASH_JOURNAL_MAGIC) + +typedef struct _SequentialFlashJournal_t { + FlashJournal_Ops_t ops; /**< the mandatory OPS table defining the strategy. */ + FlashJournal_Callback_t callback; /**< command completion callback. */ + FlashJournal_Info_t info; /**< the info structure returned from GetInfo(). */ + ARM_DRIVER_STORAGE *mtd; /**< The underlying Memory-Technology-Device. */ + ARM_STORAGE_CAPABILITIES mtdCapabilities; /**< the return from mtd->GetCapabilities(); held for quick reference. */ + uint64_t mtdStartOffset; /**< the start of the address range maintained by the underlying MTD. */ + uint32_t sequentialSkip; /**< size of the log stride. */ + uint32_t nextSequenceNumber; /**< the next valid sequence number to be used when logging the next blob. */ + uint32_t currentBlobIndex; /**< index of the most recently written blob. */ + SequentialFlashJournalState_t state; /**< state of the journal. SEQUENTIAL_JOURNAL_STATE_INITIALIZED being the default. */ + FlashJournal_OpCode_t prevCommand; /**< the last command issued to the journal. */ + + /** + * The following is a union of sub-structures meant to keep state relevant + * to the commands during their execution. + */ + union { + /** state relevant to initialization. */ + struct { + uint64_t currentOffset; + union { + SequentialFlashJournalLogHead_t head; + struct { + uint32_t headSequenceNumber; + SequentialFlashJournalLogTail_t tail; + }; + }; + } initScan; + + /** state relevant to logging of data. */ + struct { + const uint8_t *blob; /**< the original buffer holding source data. */ + size_t sizeofBlob; + union { + struct { + uint64_t eraseOffset; + }; + struct { + uint64_t offset; /**< the current offset at which data is being written. */ + uint64_t tailOffset; /**< offset at which the SequentialFlashJournalLogTail_t will be logged for this log-entry. */ + const uint8_t *dataBeingLogged; /**< temporary pointer aimed at the next data to be logged. */ + size_t amountLeftToLog; + union { + SequentialFlashJournalLogHead_t head; + SequentialFlashJournalLogTail_t tail; + }; + }; + }; + } log; + + /** state relevant to read-back of data. */ + struct { + const uint8_t *blob; /**< the original buffer holding source data. */ + size_t sizeofBlob; + uint64_t offset; /**< the current offset at which data is being written. */ + uint8_t *dataBeingRead; /**< temporary pointer aimed at the next data to be read-into. */ + size_t amountLeftToRead; + size_t totalDataRead; /**< the total data that has been read off the blob so far. */ + } read; + }; +} SequentialFlashJournal_t; + +/**< + * A static assert to ensure that the size of SequentialJournal is smaller than + * FlashJournal_t. The caller will only allocate a FlashJournal_t and expect the + * Sequential Strategy to reuse that space for a SequentialFlashJournal_t. + */ +typedef char AssertSequentialJournalSizeLessThanOrEqualToGenericJournal[sizeof(SequentialFlashJournal_t)<=sizeof(FlashJournal_t)?1:-1]; + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif /* __FLASH_JOURNAL_PRIVATE_H__ */ diff --git a/hal/common/flash-journal/flash-journal-strategy-sequential/flash_journal_strategy_sequential.h b/hal/common/flash-journal/flash-journal-strategy-sequential/flash_journal_strategy_sequential.h new file mode 100644 index 00000000000..12421877908 --- /dev/null +++ b/hal/common/flash-journal/flash-journal-strategy-sequential/flash_journal_strategy_sequential.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __FLASH_JOURNAL_STRATEGY_SEQUENTIAL_H__ +#define __FLASH_JOURNAL_STRATEGY_SEQUENTIAL_H__ + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +#include "flash-journal/flash_journal.h" + +int32_t flashJournalStrategySequential_initialize(FlashJournal_t *journal, + ARM_DRIVER_STORAGE *mtd, + const FlashJournal_Ops_t *ops, + FlashJournal_Callback_t callback); +FlashJournal_Status_t flashJournalStrategySequential_getInfo(FlashJournal_t *journal, FlashJournal_Info_t *info); +int32_t flashJournalStrategySequential_read(FlashJournal_t *journal, void *blob, size_t n); +int32_t flashJournalStrategySequential_log(FlashJournal_t *journal, const void *blob, size_t n); +int32_t flashJournalStrategySequential_commit(FlashJournal_t *journal); +int32_t flashJournalStrategySequential_reset(FlashJournal_t *journal); + +static const FlashJournal_Ops_t FLASH_JOURNAL_STRATEGY_SEQUENTIAL = { + flashJournalStrategySequential_initialize, + flashJournalStrategySequential_getInfo, + flashJournalStrategySequential_read, + flashJournalStrategySequential_log, + flashJournalStrategySequential_commit, + flashJournalStrategySequential_reset +}; + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif /* __FLASH_JOURNAL_STRATEGY_SEQUENTIAL_H__ */ diff --git a/hal/common/flash-journal/flash-journal-strategy-sequential/strategy.c b/hal/common/flash-journal/flash-journal-strategy-sequential/strategy.c new file mode 100644 index 00000000000..5a4a715868f --- /dev/null +++ b/hal/common/flash-journal/flash-journal-strategy-sequential/strategy.c @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "flash-journal-strategy-sequential/flash_journal_private.h" +#include "flash-journal-strategy-sequential/flash_journal_strategy_sequential.h" +#include "support_funcs.h" +#include +#include + +SequentialFlashJournal_t *activeJournal; + +/* forward declarations */ +void mtdHandler(int32_t status, ARM_STORAGE_OPERATION operation); + +static inline int32_t mtdGetTotalCapacity(ARM_DRIVER_STORAGE *mtd, uint64_t *capacityP) +{ + /* fetch MTD's INFO */ + ARM_STORAGE_INFO mtdInfo; + int32_t rc = mtd->GetInfo(&mtdInfo); + if (rc != ARM_DRIVER_OK) { + return JOURNAL_STATUS_STORAGE_API_ERROR; + } + *capacityP = mtdInfo.total_storage; + + return JOURNAL_STATUS_OK; +} + +static inline int32_t flashJournalStrategySequential_read_sanityChecks(SequentialFlashJournal_t *journal, const void *blob, size_t sizeofBlob) +{ + if ((journal == NULL) || (blob == NULL) || (sizeofBlob == 0)) { + return JOURNAL_STATUS_PARAMETER; + } + if ((journal->state == SEQUENTIAL_JOURNAL_STATE_NOT_INITIALIZED) || (journal->state == SEQUENTIAL_JOURNAL_STATE_INIT_SCANNING_LOG_HEADERS)) { + return JOURNAL_STATUS_NOT_INITIALIZED; + } + if (journal->state != SEQUENTIAL_JOURNAL_STATE_INITIALIZED) { + return JOURNAL_STATUS_ERROR; /* journal is in an un-expected state. */ + } + // printf("read sanity checks: totalDataRead = %lu, sizeofJournaledBlob = %lu\n", (uint32_t)journal->read.totalDataRead, (uint32_t)journal->info.sizeofJournaledBlob); + if ((journal->info.sizeofJournaledBlob == 0) || (journal->read.totalDataRead == journal->info.sizeofJournaledBlob)) { + journal->read.totalDataRead = 0; + return JOURNAL_STATUS_EMPTY; + } + + return JOURNAL_STATUS_OK; +} + +static inline int32_t flashJournalStrategySequential_log_sanityChecks(SequentialFlashJournal_t *journal, const void *blob, size_t sizeofBlob) +{ + if ((journal == NULL) || (blob == NULL) || (sizeofBlob == 0)) { + return JOURNAL_STATUS_PARAMETER; + } + if ((journal->state == SEQUENTIAL_JOURNAL_STATE_NOT_INITIALIZED) || (journal->state == SEQUENTIAL_JOURNAL_STATE_INIT_SCANNING_LOG_HEADERS)) { + return JOURNAL_STATUS_NOT_INITIALIZED; + } + if ((journal->state != SEQUENTIAL_JOURNAL_STATE_INITIALIZED) && (journal->state != SEQUENTIAL_JOURNAL_STATE_LOGGING_BODY)) { + return JOURNAL_STATUS_ERROR; /* journal is in an un-expected state. */ + } + if (journal->state == SEQUENTIAL_JOURNAL_STATE_INITIALIZED) { + if (sizeofBlob > journal->info.capacity) { + return JOURNAL_STATUS_BOUNDED_CAPACITY; /* adding this log chunk would cause us to exceed capacity (write past the tail). */ + } + } else if (journal->state == SEQUENTIAL_JOURNAL_STATE_LOGGING_BODY) { + if (journal->log.offset + sizeofBlob > journal->log.tailOffset) { + return JOURNAL_STATUS_BOUNDED_CAPACITY; /* adding this log chunk would cause us to exceed capacity (write past the tail). */ + } + } + + return JOURNAL_STATUS_OK; +} + +static inline int32_t flashJournalStrategySequential_commit_sanityChecks(SequentialFlashJournal_t *journal) +{ + if (journal == NULL) { + return JOURNAL_STATUS_PARAMETER; + } + if (journal->state == SEQUENTIAL_JOURNAL_STATE_LOGGING_BODY) { + if (journal->prevCommand != FLASH_JOURNAL_OPCODE_LOG_BLOB) { + return JOURNAL_STATUS_ERROR; + } + if ((journal->log.offset == ARM_STORAGE_INVALID_OFFSET) || + (journal->log.tailOffset == ARM_STORAGE_INVALID_OFFSET) || + (journal->log.tailOffset < journal->log.offset) || + (journal->log.tail.sizeofBlob == 0) || + (journal->log.tail.sizeofBlob > journal->info.capacity)) { + return JOURNAL_STATUS_ERROR; /* journal is in an un-expected state. */ + } + } + + return JOURNAL_STATUS_OK; +} + +int32_t flashJournalStrategySequential_initialize(FlashJournal_t *_journal, + ARM_DRIVER_STORAGE *mtd, + const FlashJournal_Ops_t *ops, + FlashJournal_Callback_t callback) +{ + int32_t rc; + + SequentialFlashJournal_t *journal; + activeJournal = journal = (SequentialFlashJournal_t *)_journal; + journal->state = SEQUENTIAL_JOURNAL_STATE_NOT_INITIALIZED; + + /* fetch MTD's total capacity */ + uint64_t mtdCapacity; + if ((rc = mtdGetTotalCapacity(mtd, &mtdCapacity)) != JOURNAL_STATUS_OK) { + return rc; + } + ARM_STORAGE_INFO mtdInfo; + if ((rc = mtd->GetInfo(&mtdInfo)) != ARM_DRIVER_OK) { + return JOURNAL_STATUS_STORAGE_API_ERROR; + } + + /* initialize the journal structure */ + memcpy(&journal->ops, ops, sizeof(FlashJournal_Ops_t)); + journal->mtd = mtd; + journal->mtdCapabilities = mtd->GetCapabilities(); /* fetch MTD's capabilities */ + journal->sequentialSkip = mtdCapacity / SEQUENTIAL_FLASH_JOURNAL_MAX_LOGGED_BLOBS; + journal->info.capacity = journal->sequentialSkip - (sizeof(SequentialFlashJournalLogHead_t) + sizeof(SequentialFlashJournalLogTail_t)); /* effective capacity */ + journal->info.program_unit = mtdInfo.program_unit; + journal->callback = callback; + journal->prevCommand = FLASH_JOURNAL_OPCODE_INITIALIZE; + + /* initialize MTD */ + ARM_STORAGE_CAPABILITIES mtdCaps = mtd->GetCapabilities(); + rc = mtd->Initialize(mtdHandler); + if (rc < ARM_DRIVER_OK) { + memset(journal, 0, sizeof(FlashJournal_t)); + return JOURNAL_STATUS_STORAGE_API_ERROR; + } + if ((mtdCaps.asynchronous_ops) && (rc == ARM_DRIVER_OK)) { + return JOURNAL_STATUS_OK; /* we've got pending asynchronous activity. */ + } + + if ((rc = discoverLatestLoggedBlob(journal)) != JOURNAL_STATUS_OK) { + return rc; + } + + return 1; /* synchronous completion */ +} + +FlashJournal_Status_t flashJournalStrategySequential_getInfo(FlashJournal_t *_journal, FlashJournal_Info_t *infoP) +{ + SequentialFlashJournal_t *journal; + activeJournal = journal = (SequentialFlashJournal_t *)_journal; + + memcpy(infoP, &journal->info, sizeof(FlashJournal_Info_t)); + return JOURNAL_STATUS_OK; +} + +int32_t flashJournalStrategySequential_read(FlashJournal_t *_journal, void *blob, size_t sizeofBlob) +{ + SequentialFlashJournal_t *journal; + activeJournal = journal = (SequentialFlashJournal_t *)_journal; + + int32_t rc; + if ((rc = flashJournalStrategySequential_read_sanityChecks(journal, blob, sizeofBlob)) != JOURNAL_STATUS_OK) { + return rc; + } + + journal->read.blob = blob; + journal->read.sizeofBlob = sizeofBlob; + + if ((journal->prevCommand != FLASH_JOURNAL_OPCODE_READ_BLOB) || (journal->read.totalDataRead == 0)) { + journal->read.offset = journal->mtdStartOffset + + (journal->currentBlobIndex * journal->sequentialSkip) + + sizeof(SequentialFlashJournalLogHead_t); + journal->read.totalDataRead = 0; + } else { + /* journal->read.offset is already set from the previous read execution */ + // printf("flashJournalStrategySequential_read: continuing read of %lu from offset %lu\n", sizeofBlob, (uint32_t)journal->read.offset); + } + journal->read.dataBeingRead = blob; + journal->read.amountLeftToRead = ((journal->info.sizeofJournaledBlob - journal->read.totalDataRead) < sizeofBlob) ? + (journal->info.sizeofJournaledBlob - journal->read.totalDataRead) : sizeofBlob; + // printf("amount left to read %u\n", journal->read.amountLeftToRead); + + journal->state = SEQUENTIAL_JOURNAL_STATE_READING; + journal->prevCommand = FLASH_JOURNAL_OPCODE_READ_BLOB; + return flashJournalStrategySequential_read_progress(); +} + +int32_t flashJournalStrategySequential_log(FlashJournal_t *_journal, const void *blob, size_t size) +{ + SequentialFlashJournal_t *journal; + activeJournal = journal = (SequentialFlashJournal_t *)_journal; + + int32_t rc; + if ((rc = flashJournalStrategySequential_log_sanityChecks(journal, blob, size)) != JOURNAL_STATUS_OK) { + return rc; + } + + journal->log.blob = blob; + journal->log.sizeofBlob = size; + + if (journal->prevCommand != FLASH_JOURNAL_OPCODE_LOG_BLOB) { + uint32_t logBlobIndex = journal->currentBlobIndex + 1; + if (logBlobIndex == SEQUENTIAL_FLASH_JOURNAL_MAX_LOGGED_BLOBS) { + logBlobIndex = 0; + } + journal->log.eraseOffset = journal->mtdStartOffset + (logBlobIndex * journal->sequentialSkip); + + /* ensure that the request is at least as large as the minimum program unit */ + if (size < journal->info.program_unit) { + return JOURNAL_STATUS_SMALL_LOG_REQUEST; + } + + journal->state = SEQUENTIAL_JOURNAL_STATE_LOGGING_ERASE; /* start with erasing the log region */ + journal->prevCommand = FLASH_JOURNAL_OPCODE_LOG_BLOB; + } else { + journal->log.dataBeingLogged = blob; + journal->log.amountLeftToLog = size; + } + + return flashJournalStrategySequential_log_progress(); +} + +int32_t flashJournalStrategySequential_commit(FlashJournal_t *_journal) +{ + SequentialFlashJournal_t *journal; + activeJournal = journal = (SequentialFlashJournal_t *)_journal; + + int32_t rc; + if ((rc = flashJournalStrategySequential_commit_sanityChecks(journal)) != JOURNAL_STATUS_OK) { + return rc; + } + + if (journal->prevCommand == FLASH_JOURNAL_OPCODE_LOG_BLOB) { + journal->log.offset = journal->log.tailOffset; + journal->log.dataBeingLogged = (const uint8_t *)&journal->log.tail; + journal->log.amountLeftToLog = sizeof(SequentialFlashJournalLogTail_t); + journal->state = SEQUENTIAL_JOURNAL_STATE_LOGGING_TAIL; + } else { + uint32_t logBlobIndex = journal->currentBlobIndex + 1; + if (logBlobIndex == SEQUENTIAL_FLASH_JOURNAL_MAX_LOGGED_BLOBS) { + logBlobIndex = 0; + } + journal->log.eraseOffset = journal->mtdStartOffset + (logBlobIndex * journal->sequentialSkip); + journal->state = SEQUENTIAL_JOURNAL_STATE_LOGGING_ERASE; + } + + journal->prevCommand = FLASH_JOURNAL_OPCODE_COMMIT; + return flashJournalStrategySequential_log_progress(); +} + +int32_t flashJournalStrategySequential_reset(FlashJournal_t *_journal) +{ + SequentialFlashJournal_t *journal; + activeJournal = journal = (SequentialFlashJournal_t *)_journal; + + journal->state = SEQUENTIAL_JOURNAL_STATE_RESETING; + + journal->prevCommand = FLASH_JOURNAL_OPCODE_RESET; + return flashJournalStrategySequential_reset_progress(); +} diff --git a/hal/common/flash-journal/flash-journal-strategy-sequential/support_funcs.c b/hal/common/flash-journal/flash-journal-strategy-sequential/support_funcs.c new file mode 100644 index 00000000000..3af02b357a0 --- /dev/null +++ b/hal/common/flash-journal/flash-journal-strategy-sequential/support_funcs.c @@ -0,0 +1,510 @@ +/* + * Copyright (c) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "support_funcs.h" +#include +#include +#include + +static inline int32_t mtdGetStartAddr(ARM_DRIVER_STORAGE *mtd, uint64_t *startAddrP) +{ + ARM_STORAGE_BLOCK mtdBlock; + if ((mtd->GetNextBlock(NULL, &mtdBlock)) != ARM_DRIVER_OK) { + return JOURNAL_STATUS_STORAGE_API_ERROR; + } + if (!ARM_STORAGE_VALID_BLOCK(&mtdBlock)) { + return JOURNAL_STATUS_ERROR; + } + + *startAddrP = mtdBlock.addr; + return JOURNAL_STATUS_OK; +} + +int32_t discoverLatestLoggedBlob(SequentialFlashJournal_t *journal) +{ + int32_t rc; + + /* reset top level journal metadata prior to scanning headers. */ + journal->nextSequenceNumber = SEQUENTIAL_FLASH_JOURNAL_INVALD_NEXT_SEQUENCE_NUMBER; /* we are currently unaware of previously written blobs */ + journal->currentBlobIndex = SEQUENTIAL_FLASH_JOURNAL_MAX_LOGGED_BLOBS; + journal->info.sizeofJournaledBlob = 0; + + /* begin header-scan from the first block of the MTD */ + ARM_DRIVER_STORAGE *mtd = journal->mtd; + if ((rc = mtdGetStartAddr(journal->mtd, &journal->mtdStartOffset)) != JOURNAL_STATUS_OK) { + return rc; + } + journal->initScan.currentOffset = journal->mtdStartOffset; + journal->state = SEQUENTIAL_JOURNAL_STATE_INIT_SCANNING_LOG_HEADERS; + + // printf("start of init scan\n"); + for (unsigned blobIndex = 0; + blobIndex < SEQUENTIAL_FLASH_JOURNAL_MAX_LOGGED_BLOBS; + blobIndex++, journal->initScan.currentOffset += journal->sequentialSkip) { + // printf("blob index %u\n", blobIndex); + /* TODO: it is possible that the header structure spans multiple blocks, needing multiple reads. */ + + if (((rc = mtd->ReadData(journal->initScan.currentOffset, &journal->initScan.head, sizeof(SequentialFlashJournalLogHead_t))) < ARM_DRIVER_OK) || + (rc != sizeof(SequentialFlashJournalLogHead_t))) { + /* TODO: add support for asynchronous scan */ + if ((rc == ARM_DRIVER_OK) && (journal->mtdCapabilities.asynchronous_ops)) { + return JOURNAL_STATUS_UNSUPPORTED; + } + + return JOURNAL_STATUS_STORAGE_IO_ERROR; + } + // printf("head->version: %lu\n", journal->initScan.head.version); + // printf("head->magic: %lx\n", journal->initScan.head.magic); + // printf("head->sequenceNumber: %lu\n", journal->initScan.head.sequenceNumber); + // printf("head->reserved: %lu\n", journal->initScan.head.reserved); + + if (SEQUENTIAL_JOURNAL_VALID_HEAD(&journal->initScan.head)) { + journal->initScan.headSequenceNumber = journal->initScan.head.sequenceNumber; + // printf("found valid header with sequenceNumber %lu\n", journal->initScan.headSequenceNumber); + + uint64_t tailoffset = journal->initScan.currentOffset + - ((journal->initScan.currentOffset - journal->mtdStartOffset) % journal->sequentialSkip) + + journal->sequentialSkip + - sizeof(SequentialFlashJournalLogTail_t); + + // printf("hoping to read a tail at offset %lu\n", (uint32_t)tailoffset); + if (((rc = mtd->ReadData(tailoffset, &journal->initScan.tail, sizeof(SequentialFlashJournalLogTail_t))) < ARM_DRIVER_OK) || + (rc != sizeof(SequentialFlashJournalLogTail_t))) { + return JOURNAL_STATUS_STORAGE_IO_ERROR; + } + + if (SEQUENTIAL_JOURNAL_VALID_TAIL(&journal->initScan.tail) && + (journal->initScan.tail.sequenceNumber == journal->initScan.headSequenceNumber)) { + // printf("found valid blob with sequence number %lu\n", journal->initScan.headSequenceNumber); + uint32_t nextSequenceNumber = journal->initScan.headSequenceNumber + 1; + if (nextSequenceNumber == SEQUENTIAL_FLASH_JOURNAL_INVALD_NEXT_SEQUENCE_NUMBER) { + nextSequenceNumber = 0; + } + + if ((journal->nextSequenceNumber == SEQUENTIAL_FLASH_JOURNAL_INVALD_NEXT_SEQUENCE_NUMBER) || + /* We take advantage of properties of unsigned arithmetic in the following + * expression. + * + * We want to calculate if (nextSequenceNumber > journal->nextSequenceNumber), + * instead we use the expression ((nextSequenceNumber - journal->nextSequenceNumber) > 0) + * to take wraparounds into account. + */ + ((int32_t)(nextSequenceNumber - journal->nextSequenceNumber) > 0)) { + journal->currentBlobIndex = blobIndex; + journal->nextSequenceNumber = nextSequenceNumber; + journal->info.sizeofJournaledBlob = journal->initScan.tail.sizeofBlob; + // printf("discoverLatestLoggedBlob: index %lu, sizeofBlob: %lu, nextSequenceNumber: %lu\n", + // journal->currentBlobIndex, (uint32_t)journal->info.sizeofJournaledBlob, journal->nextSequenceNumber); + } + } + } + } + // printf("finished init scan\n"); + + /* Handle the case where our scan hasn't yielded any results. */ + if (journal->nextSequenceNumber == SEQUENTIAL_FLASH_JOURNAL_INVALD_NEXT_SEQUENCE_NUMBER) { + // printf("discoverLatestLoggedBlob: initializing to defaults\n"); + journal->currentBlobIndex = (uint32_t)-1; /* to be incremented to 0 during the first attempt to log(). */ + journal->nextSequenceNumber = 0; + + /* setup info.current_program_unit */ + ARM_STORAGE_BLOCK storageBlock; + if ((rc = journal->mtd->GetBlock(journal->mtdStartOffset, &storageBlock)) != ARM_DRIVER_OK) { + return JOURNAL_STATUS_STORAGE_API_ERROR; + } + } + + journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; + + return JOURNAL_STATUS_OK; +} + +int32_t flashJournalStrategySequential_reset_progress(void) +{ + int32_t rc; + SequentialFlashJournal_t *journal = activeJournal; + + if (journal->mtdCapabilities.erase_all) { + if ((rc = journal->mtd->EraseAll()) < ARM_DRIVER_OK) { + journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; /* reset state */ + return JOURNAL_STATUS_STORAGE_IO_ERROR; + } + if ((journal->mtdCapabilities.asynchronous_ops) && (rc == ARM_DRIVER_OK)) { + return JOURNAL_STATUS_OK; /* we've got pending asynchronous activity. */ + } + /* else we fall through to handle synchronous completion */ + } else { + if ((rc = journal->mtd->Erase(journal->mtdStartOffset, SEQUENTIAL_FLASH_JOURNAL_MAX_LOGGED_BLOBS * journal->sequentialSkip)) < ARM_DRIVER_OK) { + journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; /* reset state */ + return JOURNAL_STATUS_STORAGE_IO_ERROR; + } + if ((journal->mtdCapabilities.asynchronous_ops) && (rc == ARM_DRIVER_OK)) { + printf("eturning JOURNAL_STATUS_OK\n"); + return JOURNAL_STATUS_OK; /* we've got pending asynchronous activity. */ + } + /* else we fall through to handle synchronous completion */ + } + + journal->nextSequenceNumber = 0; + journal->currentBlobIndex = (uint32_t)-1; + journal->info.sizeofJournaledBlob = 0; + journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; + return 1; +} + +int32_t flashJournalStrategySequential_read_progress(void) +{ + SequentialFlashJournal_t *journal = activeJournal; + + // printf("flashJournalStrategySequential_read_progress\n"); + if (journal->state != SEQUENTIAL_JOURNAL_STATE_READING) { + return JOURNAL_STATUS_ERROR; /* journal is in an un-expected state. */ + } + + int32_t rc; + ARM_STORAGE_BLOCK storageBlock; + + if ((journal->read.amountLeftToRead) && + ((rc = journal->mtd->GetBlock(journal->read.offset, &storageBlock)) != ARM_DRIVER_OK)) { + journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; /* reset state */ + return JOURNAL_STATUS_STORAGE_API_ERROR; + } + uint64_t storageBlockAvailableCapacity = storageBlock.size - (journal->read.offset - storageBlock.addr); + + while (journal->read.amountLeftToRead) { + while (!storageBlockAvailableCapacity) { + if ((rc = journal->mtd->GetNextBlock(&storageBlock, &storageBlock)) < ARM_DRIVER_OK) { + journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; /* reset state */ + return JOURNAL_STATUS_ERROR; /* We ran out of storage blocks. Journal is in an un-expected state. */ + } + journal->read.offset = storageBlock.addr; /* This should not be necessary since we assume + * storage map manages a contiguous address space. */ + storageBlockAvailableCapacity = storageBlock.size; + } + + /* compute the transfer size for this iteration. */ + uint32_t xfer = (journal->read.amountLeftToRead < storageBlockAvailableCapacity) ? + journal->read.amountLeftToRead : storageBlockAvailableCapacity; + + /* perform the IO */ + //printf("reading %lu bytes at offset %lu\n", xfer, (uint32_t)journal->read.offset); + rc = journal->mtd->ReadData(journal->read.offset, journal->read.dataBeingRead, xfer); + if (rc < ARM_DRIVER_OK) { + journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; /* reset state */ + return JOURNAL_STATUS_STORAGE_IO_ERROR; + } + if ((journal->mtdCapabilities.asynchronous_ops) && (rc == ARM_DRIVER_OK)) { + return JOURNAL_STATUS_OK; /* we've got pending asynchronous activity. */ + } else { + /* synchronous completion. 'rc' contains the actual number of bytes transferred. */ + journal->read.offset += rc; + journal->read.amountLeftToRead -= rc; + journal->read.dataBeingRead += rc; + journal->read.totalDataRead += rc; + } + } + + journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; + return (journal->read.dataBeingRead - journal->read.blob); +} + +int32_t flashJournalStrategySequential_log_progress(void) +{ + SequentialFlashJournal_t *journal = activeJournal; + + if ((journal->state != SEQUENTIAL_JOURNAL_STATE_LOGGING_ERASE) && + (journal->state != SEQUENTIAL_JOURNAL_STATE_LOGGING_HEAD) && + (journal->state != SEQUENTIAL_JOURNAL_STATE_LOGGING_BODY) && + (journal->state != SEQUENTIAL_JOURNAL_STATE_LOGGING_TAIL)) { + return JOURNAL_STATUS_ERROR; /* journal is in an un-expected state. */ + } + + uint32_t blobIndexBeingLogged = journal->currentBlobIndex + 1; + if (blobIndexBeingLogged == SEQUENTIAL_FLASH_JOURNAL_MAX_LOGGED_BLOBS) { + blobIndexBeingLogged = 0; + } + + while (true) { + int32_t rc; + + if (journal->state == SEQUENTIAL_JOURNAL_STATE_LOGGING_ERASE) { + uint64_t amountLeftToErase = journal->mtdStartOffset + + (blobIndexBeingLogged + 1) * journal->sequentialSkip + - journal->log.eraseOffset; + // printf("journal state: erasing; offset %lu [size %lu]\n", + // (uint32_t)journal->log.eraseOffset, (uint32_t)amountLeftToErase); + while (amountLeftToErase) { + if ((rc = journal->mtd->Erase(journal->log.eraseOffset, amountLeftToErase)) < ARM_DRIVER_OK) { + journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; /* reset state */ + return JOURNAL_STATUS_ERROR; /* We ran out of storage blocks. Journal is in an un-expected state. */ + } + if ((journal->mtdCapabilities.asynchronous_ops) && (rc == ARM_DRIVER_OK)) { + return JOURNAL_STATUS_OK; /* we've got pending asynchronous activity. */ + } else { + /* synchronous completion. */ + journal->log.eraseOffset += rc; + amountLeftToErase -= rc; + } + } + } else { + ARM_STORAGE_BLOCK storageBlock; + + /* find the available capacity in the current storage block */ + while (journal->log.amountLeftToLog) { + if (journal->log.amountLeftToLog < journal->info.program_unit) { + /* We cannot log any smaller than info.program_unit. 'xfer' + * amount of data would remain unlogged. We'll break out of this loop and report + * the amount actually logged. */ + break; + } + + /* check for alignment of next log offset with program_unit */ + if ((rc = journal->mtd->GetBlock(journal->log.offset, &storageBlock)) != ARM_DRIVER_OK) { + journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; /* reset state */ + return JOURNAL_STATUS_STORAGE_API_ERROR; + } + if ((journal->log.offset - storageBlock.addr) % journal->info.program_unit) { + journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; /* reset state */ + return JOURNAL_STATUS_ERROR; /* Program offset doesn't align with info.program_unit. This would result in an IO error if attempted. */ + } + + uint32_t xfer = journal->log.amountLeftToLog; + xfer -= xfer % journal->info.program_unit; /* align transfer-size with program_unit. */ + + /* perform the IO */ + // printf("programming %lu bytes at offset %lu\n", xfer, (uint32_t)journal->log.offset); + rc = journal->mtd->ProgramData(journal->log.offset, journal->log.dataBeingLogged, xfer); + if (rc < ARM_DRIVER_OK) { + journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; /* reset state */ + return JOURNAL_STATUS_STORAGE_IO_ERROR; + } + if ((journal->mtdCapabilities.asynchronous_ops) && (rc == ARM_DRIVER_OK)) { + return JOURNAL_STATUS_OK; /* we've got pending asynchronous activity. */ + } else { + /* synchronous completion. 'rc' contains the actual number of bytes transferred. */ + journal->log.offset += rc; + journal->log.amountLeftToLog -= rc; + journal->log.dataBeingLogged += rc; + if (journal->state == SEQUENTIAL_JOURNAL_STATE_LOGGING_BODY) { + journal->log.tail.sizeofBlob += rc; + } + } + } /* while (journal->log.amountLeftToLog) */ + } + + // printf("flashJournalStrategySequential_log_progress: state switch\n"); + + /* state transition */ + switch (journal->state) { + case SEQUENTIAL_JOURNAL_STATE_LOGGING_ERASE: + journal->state = SEQUENTIAL_JOURNAL_STATE_LOGGING_HEAD; + journal->log.offset = journal->mtdStartOffset + blobIndexBeingLogged * journal->sequentialSkip; + journal->log.head.version = SEQUENTIAL_FLASH_JOURNAL_VERSION; + journal->log.head.magic = SEQUENTIAL_FLASH_JOURNAL_MAGIC; + journal->log.head.sequenceNumber = journal->nextSequenceNumber; + journal->log.head.reserved = 0; + journal->log.dataBeingLogged = (const uint8_t *)&journal->log.head; + journal->log.amountLeftToLog = sizeof(SequentialFlashJournalLogHead_t); + // printf("newstate: program HEAD; amount to log %u\n", journal->log.amountLeftToLog); + break; + + case SEQUENTIAL_JOURNAL_STATE_LOGGING_HEAD: /* switch to writing the body */ + /* Prepare for the tail to be written out at a later time. + * This will only be done once Commit() is called. */ + journal->log.tailOffset = journal->mtdStartOffset + + (blobIndexBeingLogged + 1) * journal->sequentialSkip + - sizeof(SequentialFlashJournalLogTail_t); + journal->log.tail.magic = SEQUENTIAL_FLASH_JOURNAL_MAGIC; + journal->log.tail.sequenceNumber = journal->nextSequenceNumber; + journal->log.tail.sizeofBlob = 0; /* we'll update this as we complete our writes. */ + + if (journal->prevCommand == FLASH_JOURNAL_OPCODE_COMMIT) { + /* This branch is taken only when commit() is called without any preceding log() operations. */ + journal->state = SEQUENTIAL_JOURNAL_STATE_LOGGING_TAIL; + journal->log.dataBeingLogged = (const uint8_t *)&journal->log.tail; + journal->log.amountLeftToLog = sizeof(SequentialFlashJournalLogTail_t); + journal->log.offset = journal->log.tailOffset; + // printf("newstate: program TAIL at offset %lu\r\n", (uint32_t)journal->log.offset); + } else { + journal->state = SEQUENTIAL_JOURNAL_STATE_LOGGING_BODY; + journal->log.dataBeingLogged = journal->log.blob; + journal->log.amountLeftToLog = journal->log.sizeofBlob; + // printf("newstate: program BODY; amount to log %u\n", journal->log.amountLeftToLog); + } + break; + + case SEQUENTIAL_JOURNAL_STATE_LOGGING_BODY: + // printf("finished logging BODY; amount logged %u\n", journal->log.dataBeingLogged - journal->log.blob); + if (journal->log.dataBeingLogged == journal->log.blob) { + return JOURNAL_STATUS_SMALL_LOG_REQUEST; + } else { + return (journal->log.dataBeingLogged - journal->log.blob); + } + + case SEQUENTIAL_JOURNAL_STATE_LOGGING_TAIL: + journal->info.sizeofJournaledBlob = journal->log.tail.sizeofBlob; + journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; /* reset state to allow further operations */ + + ++journal->currentBlobIndex; + if (journal->currentBlobIndex == SEQUENTIAL_FLASH_JOURNAL_MAX_LOGGED_BLOBS) { + journal->currentBlobIndex = 0; + } + // printf("currentBlobIndex: %lu\n", journal->currentBlobIndex); + + /* increment next sequence number */ + ++journal->nextSequenceNumber; + if (journal->nextSequenceNumber == SEQUENTIAL_FLASH_JOURNAL_INVALD_NEXT_SEQUENCE_NUMBER) { + ++journal->nextSequenceNumber; + } + // printf("nextSequenceNumber %lu\n", journal->nextSequenceNumber); + + return 1; /* commit returns 1 upon completion. */ + + default: + journal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; + return JOURNAL_STATUS_ERROR; + } + } +} + +void mtdHandler(int32_t status, ARM_STORAGE_OPERATION operation) +{ + int32_t rc; + + if (status < ARM_DRIVER_OK) { + printf("mtdHandler: received error status %" PRId32 "\n", status); + switch (activeJournal->state) { + case SEQUENTIAL_JOURNAL_STATE_NOT_INITIALIZED: + case SEQUENTIAL_JOURNAL_STATE_INIT_SCANNING_LOG_HEADERS: + if (activeJournal->callback) { + activeJournal->callback(JOURNAL_STATUS_STORAGE_IO_ERROR, FLASH_JOURNAL_OPCODE_INITIALIZE); + } + break; + + case SEQUENTIAL_JOURNAL_STATE_RESETING: + activeJournal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; /* reset state */ + if (activeJournal->callback) { + activeJournal->callback(JOURNAL_STATUS_STORAGE_IO_ERROR, FLASH_JOURNAL_OPCODE_RESET); + } + break; + + case SEQUENTIAL_JOURNAL_STATE_INITIALIZED: + case SEQUENTIAL_JOURNAL_STATE_LOGGING_ERASE: + case SEQUENTIAL_JOURNAL_STATE_LOGGING_HEAD: + case SEQUENTIAL_JOURNAL_STATE_LOGGING_BODY: + case SEQUENTIAL_JOURNAL_STATE_LOGGING_TAIL: + /* reset journal state to allow further operation. */ + activeJournal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; + + if (activeJournal->callback) { + activeJournal->callback(JOURNAL_STATUS_STORAGE_IO_ERROR, FLASH_JOURNAL_OPCODE_LOG_BLOB); + } + break; + case SEQUENTIAL_JOURNAL_STATE_READING: + /* reset journal state to allow further operation. */ + activeJournal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; + + if (activeJournal->callback) { + activeJournal->callback(JOURNAL_STATUS_STORAGE_IO_ERROR, FLASH_JOURNAL_OPCODE_READ_BLOB); + } + break; + } + + return; + } + + switch (operation) { + case ARM_STORAGE_OPERATION_INITIALIZE: + if (activeJournal->callback) { + activeJournal->callback(JOURNAL_STATUS_OK, FLASH_JOURNAL_OPCODE_INITIALIZE); + } + break; + + case ARM_STORAGE_OPERATION_ERASE_ALL: + if (activeJournal->state == SEQUENTIAL_JOURNAL_STATE_RESETING) { + activeJournal->nextSequenceNumber = 0; + activeJournal->currentBlobIndex = (uint32_t)-1; + activeJournal->info.sizeofJournaledBlob = 0; + activeJournal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; + if (activeJournal->callback) { + activeJournal->callback(JOURNAL_STATUS_OK, FLASH_JOURNAL_OPCODE_RESET); + } + } + break; + + case ARM_STORAGE_OPERATION_ERASE: + if (activeJournal->state == SEQUENTIAL_JOURNAL_STATE_LOGGING_ERASE) { + if (status <= ARM_DRIVER_OK) { + if (activeJournal->callback) { + activeJournal->callback(JOURNAL_STATUS_STORAGE_API_ERROR, FLASH_JOURNAL_OPCODE_LOG_BLOB); + } + return; + } + + activeJournal->log.eraseOffset += status; + + if ((rc = flashJournalStrategySequential_log_progress()) != JOURNAL_STATUS_OK) { + activeJournal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; /* reset state */ + if (activeJournal->callback) { + activeJournal->callback(rc, FLASH_JOURNAL_OPCODE_LOG_BLOB); + } + return; + } + } else if (activeJournal->state == SEQUENTIAL_JOURNAL_STATE_RESETING) { + activeJournal->nextSequenceNumber = 0; + activeJournal->currentBlobIndex = (uint32_t)-1; + activeJournal->info.sizeofJournaledBlob = 0; + activeJournal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; + if (activeJournal->callback) { + activeJournal->callback(JOURNAL_STATUS_OK, FLASH_JOURNAL_OPCODE_RESET); + } + } + break; + + case ARM_STORAGE_OPERATION_PROGRAM_DATA: + // printf("PROGRAM_DATA: received status of %ld\n", status); + rc = status; + activeJournal->log.offset += rc; + activeJournal->log.amountLeftToLog -= rc; + activeJournal->log.dataBeingLogged += rc; + if (activeJournal->state == SEQUENTIAL_JOURNAL_STATE_LOGGING_BODY) { + activeJournal->log.tail.sizeofBlob += rc; + } + + if ((rc = flashJournalStrategySequential_log_progress()) < JOURNAL_STATUS_OK) { + activeJournal->state = SEQUENTIAL_JOURNAL_STATE_INITIALIZED; /* reset state */ + if (activeJournal->callback) { + activeJournal->callback(rc, + (activeJournal->state == SEQUENTIAL_JOURNAL_STATE_LOGGING_TAIL) ? + FLASH_JOURNAL_OPCODE_COMMIT : FLASH_JOURNAL_OPCODE_LOG_BLOB); + } + return; + } + if ((rc == JOURNAL_STATUS_OK) && (activeJournal->log.amountLeftToLog > 0)) { + return; /* we've got pending asynchronous activity */ + } + if (activeJournal->callback) { + activeJournal->callback(rc, (activeJournal->state == SEQUENTIAL_JOURNAL_STATE_INITIALIZED) ? + FLASH_JOURNAL_OPCODE_COMMIT : FLASH_JOURNAL_OPCODE_LOG_BLOB); + } + break; + + default: + printf("mtdHandler: unknown operation %u\n", operation); + break; + } +} diff --git a/hal/common/flash-journal/flash-journal-strategy-sequential/support_funcs.h b/hal/common/flash-journal/flash-journal-strategy-sequential/support_funcs.h new file mode 100644 index 00000000000..5a3145e701e --- /dev/null +++ b/hal/common/flash-journal/flash-journal-strategy-sequential/support_funcs.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __FLASH_JOURNAL_SEQUENTIAL_STRATEGY_SUPPORT_FUNCTIONS_H__ +#define __FLASH_JOURNAL_SEQUENTIAL_STRATEGY_SUPPORT_FUNCTIONS_H__ + +#include "flash-journal-strategy-sequential/flash_journal_private.h" +#include "flash-journal-strategy-sequential/flash_journal_strategy_sequential.h" + +extern SequentialFlashJournal_t *activeJournal; + +int32_t discoverLatestLoggedBlob(SequentialFlashJournal_t *journal); +int32_t flashJournalStrategySequential_reset_progress(void); +int32_t flashJournalStrategySequential_read_progress(void); +int32_t flashJournalStrategySequential_log_progress(void); +void mtdHandler(int32_t status, ARM_STORAGE_OPERATION operation); + +#endif /*__FLASH_JOURNAL_SEQUENTIAL_STRATEGY_SUPPORT_FUNCTIONS_H__*/ diff --git a/hal/common/flash-journal/flash_journal.h b/hal/common/flash-journal/flash_journal.h new file mode 100644 index 00000000000..569132875dd --- /dev/null +++ b/hal/common/flash-journal/flash_journal.h @@ -0,0 +1,618 @@ +/* + * Copyright (c) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __FLASH_JOURNAL_H__ +#define __FLASH_JOURNAL_H__ + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +#include "flash-abstraction/Driver_Storage.h" + +/** + * General return codes. All Flash-Journal APIs return an int32_t to allow for + * both error and success status returns. This enumeration contains all + * possible error status values. + */ +typedef enum _FlashJournal_Status +{ + JOURNAL_STATUS_OK = 0, + JOURNAL_STATUS_ERROR = -1, ///< Unspecified error + JOURNAL_STATUS_BUSY = -2, ///< Underlying storage is currently unavailable + JOURNAL_STATUS_TIMEOUT = -3, ///< Timeout occurred + JOURNAL_STATUS_UNSUPPORTED = -4, ///< Operation not supported + JOURNAL_STATUS_PARAMETER = -5, ///< Parameter error + JOURNAL_STATUS_BOUNDED_CAPACITY = -6, ///< Attempt to write larger than available capacity + JOURNAL_STATUS_STORAGE_API_ERROR = -7, ///< Failure from some Storage API + JOURNAL_STATUS_STORAGE_IO_ERROR = -8, ///< Failure from underlying storage during an IO operation. + JOURNAL_STATUS_NOT_INITIALIZED = -9, ///< journal not initialized + JOURNAL_STATUS_EMPTY = -10, ///< There is no further data to read + JOURNAL_STATUS_SMALL_LOG_REQUEST = -11, ///< log request is smaller than the program_unit of the underlying MTD block. +} FlashJournal_Status_t; + +/** + * Command opcodes for flash. Completion callbacks use these codes to refer to + * completing commands. Refer to \ref ARM_Flash_Callback_t. + */ +typedef enum _FlashJournal_OpCode { + FLASH_JOURNAL_OPCODE_INITIALIZE, + FLASH_JOURNAL_OPCODE_GET_INFO, + FLASH_JOURNAL_OPCODE_READ_BLOB, + FLASH_JOURNAL_OPCODE_LOG_BLOB, + FLASH_JOURNAL_OPCODE_COMMIT, + FLASH_JOURNAL_OPCODE_RESET, +} FlashJournal_OpCode_t; + +/** + * @brief Flash Journal information. This contains journal-metadata, and is the + * return value from calling GetInfo() on the journal driver. + */ +typedef struct _FlashJournal_Info { + uint64_t capacity; ///< Maximum capacity (in octets) of the flash journal--i.e. the largest 'blob' which can be contained as payload. + uint64_t sizeofJournaledBlob; ///< size (in octets) of the most recently logged blob. + uint32_t program_unit; ///< Minimum programming size (in units of octets) for + ///< the current storage block--the one which will be used + ///< for the next log() operation. This value may change as we + ///< cycle through the blocks of the underlying MTD. + ///< Callers of FlashJournal_log() should refer to this field + ///< upon receiving the error JOURNAL_STATUS_SMALL_LOG_REQUEST + ///< (of when the actual amount of data logged is smaller than + ///< the requested amount). +} FlashJournal_Info_t; + +/** + * This is the type of the command completion callback handler for the + * asynchronous flash-journal APIs: initialize(), read(), log(), commit() and + * reset() (which is nearly all APIs). + * + * @param status + * A code to indicate the status of the completed operation. For data + * transfer operations, the status field is overloaded in case of + * success to return the amount of data successfully transferred; this + * can be done safely because error codes are negative values. + * + * @param cmd_code + * The command op-code of type FlashJournal_OpCode_t. This value isn't + * essential for the callback, but it is expected that this information + * could be a quick and useful filter. + */ +typedef void (*FlashJournal_Callback_t)(int32_t status, FlashJournal_OpCode_t cmd_code); + +/* forward declarations. */ +typedef struct _FlashJournal_t FlashJournal_t; +typedef struct _FlashJournal_Ops_t FlashJournal_Ops_t; + +/** + * @ref FlashJournal_t is an abstraction implemented by a table of generic + * operations (i.e. strategy) together with an opaque, strategy-specific + * data. Taken together, the FlashJournal_t is an opaque handle containing + * such top-level metadata. + * + * Algorithms depending on the FlashJournal can be generic (i.e. independent of + * the strategy) in their use of the Flash-Journal APIs. For the sake of being + * able to allocate a FlashJournal_t for use in such generic algorithms, the + * FlashJournal_t contains a MAX_SIZE to accommodate the largest of the + * strategy-specific metadata. The value of this MAX_SIZE may need to be + * increased if some future journal-strategy needs more metadata. + */ +#define FLASH_JOURNAL_HANDLE_MAX_SIZE 140 + +/** + * This is the set of operations offered by the flash-journal abstraction. A set + * of implementations for these operations defines a logging strategy. + */ +typedef struct _FlashJournal_Ops_t { + /** + * \brief Initialize the flash journal. Refer to @ref FlashJournal_initialize. + */ + int32_t (*initialize)(FlashJournal_t *journal, ARM_DRIVER_STORAGE *mtd, const FlashJournal_Ops_t *ops, FlashJournal_Callback_t callback); + + /** + * \brief fetch journal metadata. Refer to @ref FlashJournal_getInfo. + */ + FlashJournal_Status_t (*getInfo) (FlashJournal_t *journal, FlashJournal_Info_t *info); + + /** + * @brief Read from the most recently logged blob. Refer to @ref FlashJournal_read. + */ + int32_t (*read) (FlashJournal_t *journal, void *buffer, size_t size); + + /** + * @brief Start logging a new blob or append to the one currently being logged. Refer to @ref FlashJournal_log. + */ + int32_t (*log) (FlashJournal_t *journal, const void *blob, size_t size); + + /** + * @brief commit a blob accumulated through a non-empty sequence of + * previously successful log() operations. Refer to @ref FlashJournal_commit. + */ + int32_t (*commit) (FlashJournal_t *journal); + + /** + * @brief Reset the journal. This has the effect of erasing all valid blobs. + * Refer to @ref FlashJournal_reset. + */ + int32_t (*reset) (FlashJournal_t *journal); +} FlashJournal_Ops_t; + +/** + * @brief An opaque handle constituting the Flash Journal. + * + * @details This structure is intentionally opaque to avoid exposing data + * internal to an implementation strategy; this prevents accesses through any + * means other than through the defined API. + * + * Having a known size for the handle allows the caller to remain malloc-free. + * + * @note: There should be static asserts in the code to verify our assumption + * that the real FlashJournal handle fits within FLASH_JOURNAL_HANDLE_MAX_SIZE + * bytes. + * + * @note: there is a risk of overallocation in case an implementation doesn't + * need FLASH_JOURNAL_HANDLE_MAX_SIZE bytes, but the impact should be small. + */ +typedef struct _FlashJournal_t { + FlashJournal_Ops_t ops; + + union { + ARM_DRIVER_STORAGE *mtd; + FlashJournal_Info_t info; + void *pointer; + uint8_t octet; + uint32_t data[FLASH_JOURNAL_HANDLE_MAX_SIZE / sizeof(uint32_t)]; + } opaque; +} FlashJournal_t; + +/** + * @brief Initialize a flash journal. + * + * This is a front-end for @ref FlashJournal_Ops_t::initialize() of the + * underlying strategy. + * + * This function must be called *before* the middle-ware component starts + * using a journal. As a part of bringing the journal to a ready state, it + * also discovers the most recently logged blob. + * + * Initialize() receives a callback handler to be invoked upon completion of + * asynchronous operations. + * + * @param [out] journal + * A caller-supplied buffer large enough to hold an + * initialized journal. The internals of the actual journal + * are opaque to the caller and depend on the logging + * strategy (as defined by the parameter 'ops'). This memory + * should be at least as large as 'FLASH_JOURNAL_HANDLE_MAX_SIZE'. + * Upon successful return, the journal is setup in an + * initialized state. + * + * @param [in] mtd + * The underlying Storage_Driver targeted by the journal. MTD + * stands for Memory-Technology-Device. + * + * @param [in] ops + * This is the set of operations which define the logging strategy. + * + * @param [in] callback + * Caller-defined callback to be invoked upon command completion of + * initialization; and also for all future invocations of + * asynchronous APIs. Use a NULL pointer when no + * callback signals are required. + * + * @note: this is an asynchronous operation, but it can finish + * synchronously if the underlying MTD supports that. + * + * @return + * The function executes in the following ways: + * - When the operation is asynchronous, the function only starts the + * initialization and control returns to the caller with an + * JOURNAL_STATUS_OK before the actual completion of the operation (or + * with an appropriate error code in case of failure). When the + * operation is completed the command callback is invoked with + * JOURNAL_STATUS_OK passed in as the 'status' parameter of the + * callback. In case of errors, the completion callback is invoked with + * an error status. + * - When the operation is executed by the journal in a blocking (i.e. + * synchronous) manner, control returns to the caller only upon the actual + * completion of the operation or the discovery of a failure condition. In + * this case, the function returns 1 to signal successful synchronous + * completion or an appropriate error code, and no further + * invocation of the completion callback should be expected at a later time. + * + * Here's a code snippet to suggest how this API might be used by callers: + * \code + * ASSERT(JOURNAL_STATUS_OK == 0); // this is a precondition; it doesn't need to be put in code + * int32_t returnValue = FlashJournal_initialize(&journal, MTD, &STRATEGY_SEQUENTIAL, callbackHandler); + * if (returnValue < JOURNAL_STATUS_OK) { + * // handle error + * } else if (returnValue == JOURNAL_STATUS_OK) { + * ASSERT(MTD->GetCapabilities().asynchronous_ops == 1); + * // handle early return from asynchronous execution + * } else { + * ASSERT(returnValue == 1); + * // handle synchronous completion + * } + * \endcode + */ +static inline int32_t FlashJournal_initialize(FlashJournal_t *journal, + ARM_DRIVER_STORAGE *mtd, + const FlashJournal_Ops_t *ops, + FlashJournal_Callback_t callback) +{ + return ops->initialize(journal, mtd, ops, callback); +} + +/** + * @brief Fetch journal metadata. A front-end for @ref FlashJournal_Ops_t::getInfo(). + * + * @param [in] journal + * A previously initialized journal. + * + * @param [out] info + * A caller-supplied buffer capable of being filled in with an + * FlashJournal_Info_t. + * + * @return JOURNAL_STATUS_OK if a FlashJournal_Info_t structure containing + * top level metadata about the journal is filled into the supplied + * buffer, else an appropriate error value. + * + * @note It is the caller's responsibility to ensure that the buffer passed in + * is able to be initialized with a FlashJournal_Info_t. + * + * @note getInfo()s can still be called during a sequence of + * log()s. + * + * @note This API returns synchronously--it does not result in an invocation + * of a completion callback. + * + * Here's a code snippet to suggest how this API might be used by callers: + * \code + * ASSERT(JOURNAL_STATUS_OK == 0); // this is a precondition; it doesn't need to be put in code + * FlashJournal_Info_t info; + * int32_t returnValue = FlashJournal_getInfo(&journal, &info); + * if (returnValue < JOURNAL_STATUS_OK) { + * // handle error + * } else { + * ASSERT(returnValue == JOURNAL_STATUS_OK); + * // work with the 'info'. + * } + * \endcode + */ +static inline FlashJournal_Status_t FlashJournal_getInfo(FlashJournal_t *journal, FlashJournal_Info_t *info) +{ + return journal->ops.getInfo(journal, info); +} + +/** + * @brief Read from the most recently logged blob. A front-end for @ref + * FlashJournal_Ops_t::read(). + * + * @details Read off a chunk of the logged blob sequentially. The blob may + * be larger than the size of the read (or even of available SRAM), so + * multiple calls to read() could be necessary before the entire blob is + * read off. The journal maintains a read-pointer internally to allow + * reads to continue where the previous one left off. + * + * @note: Once the entire blob is read, the final read() returns the error + * JOURNAL_STATUS_EMPTY (or passes that value as the status of a + * completion callback) and resets the read-pointer to allow re-reading + * the blob from the start. + * + * @param [in] journal + * A previously initialized journal. + * + * @param [out] buffer + * The destination of the read operation. The memory is owned + * by the caller and should remain valid for the lifetime + * of this operation. + * + * @param [in] size + * The maximum amount of data which can be read in this + * operation. The memory pointed to by 'buffer' should be as + * large as this amount. + * + * @return + * The function executes in the following ways: + * - When the operation is asynchronous--i.e. when the underlying MTD's + * ARM_STOR_CAPABILITIES::asynchronous_ops is set to 1--and the operation + * executed by the journal in a non-blocking (i.e. asynchronous) manner, + * control returns to the caller with JOURNAL_STATUS_OK before the actual + * completion of the operation (or with an appropriate error code in case of + * failure). When the operation completes, the command callback is + * invoked with the number of successfully transferred bytes passed in as + * the 'status' parameter of the callback. If any error is encountered + * after the launch of an asynchronous operation, the completion callback + * is invoked with an error status. + * - When the operation is executed by the journal in a blocking (i.e. + * synchronous) manner, control returns to the caller only upon the + * actual completion of the operation, or the discovery of a failure + * condition. In synchronous mode, the function returns the number + * of data items read or an appropriate error code. + * + * @note If the underlying MTD's ARM_STORAGE_CAPABILITIES::asynchronous_ops + * is set then this operation may execute asynchronously. In the case of + * asynchronous operation, the invocation returns early (with + * JOURNAL_STATUS_OK) and results in a completion callback later. + * + * @note If the underlying MTD's ARM_STORAGE_CAPABILITIES::asynchronous_ops + * is set, the journal is not required to operate asynchronously. A Read + * operation can be finished synchronously in spite of + * ARM_STORAGE_CAPABILITIES::asynchronous_ops being set, returning the + * number of data items read to indicate successful completion, or an + * appropriate error code. In this case no further invocation of a + * completion callback should be expected at a later time. + * + * Here's a code snippet to suggest how this API might be used by callers: + * \code + * ASSERT(JOURNAL_STATUS_OK == 0); // this is a precondition; it doesn't need to be put in code + * int32_t returnValue = FlashJournal_read(&journal, buffer, size); + * if (returnValue < JOURNAL_STATUS_OK) { + * // handle error + * } else if (returnValue == JOURNAL_STATUS_OK) { + * ASSERT(MTD->GetCapabilities().asynchronous_ops == 1); + * // handle early return from asynchronous execution + * } else { + * ASSERT(returnValue == size); + * // handle synchronous completion + * } + * \endcode + */ +static inline int32_t FlashJournal_read(FlashJournal_t *journal, void *blob, size_t n) +{ + return journal->ops.read(journal, blob, n); +} + +/** + * @brief Start logging a new blob or append to the one currently being logged. + * A front-end for @ref FlashJournal_Ops_t::log(). + * + * @details Extend (or start off) the currently logged blob sequentially. + * There could be several calls to log() before the entire blob is + * accumulated. A sequence of one or more log() must be terminated by a + * commit() before the state of the blob is sealed and made persistent. + * The journal maintains a log-pointer internally to allow + * log()s to continue where the previous one left off. + * + * @param [in] journal + * A previously initialized journal. + * + * @param [in] blob + * The source of the log operation. The memory is owned + * by the caller and should remain valid for the lifetime + * of this operation. + * + * @param [in] size + * The amount of data being logged in this operation. The + * buffer pointed to by 'blob' should be as large as this + * amount. + * + * @return [please be sure to read notes (below) regarding other return values] + * The function executes in the following ways: + * - When the operation is asynchronous--i.e. when the underlying MTD's + * ARM_STOR_CAPABILITIES::asynchronous_ops is set to 1--and the operation + * executed by the journal in a non-blocking (i.e. asynchronous) manner, + * control returns to the caller with JOURNAL_STATUS_OK before the actual + * completion of the operation (or with an appropriate error code in case of + * failure). When the operation completes, the command callback is + * invoked with the number of successfully transferred bytes passed in as + * the 'status' parameter of the callback. If any error is encountered + * after the launch of an asynchronous operation, the completion callback + * is invoked with an error status. + * - When the operation is executed by the journal in a blocking (i.e. + * synchronous) manner, control returns to the caller only upon the actual + * completion of the operation, or the discovery of a failure condition. In + * synchronous mode, the function returns the number of data items + * logged, or an appropriate error code. + * + * @note If the underlying MTD's ARM_STORAGE_CAPABILITIES::asynchronous_ops + * is set then this operation may execute asynchronously. In the case of + * asynchronous operation, the invocation returns early (with + * JOURNAL_STATUS_OK) and results in a completion callback later. + * + * @note If the underlying MTD's ARM_STORAGE_CAPABILITIES::asynchronous_ops + * is set, the journal is not required to operate asynchronously. A log + * operation can be finished synchronously in spite of + * ARM_STORAGE_CAPABILITIES::asynchronous_ops being set, returning the + * number of data items logged to indicate successful completion, or an + * appropriate error code. In this case no further invocation of a + * completion callback should be expected at a later time. + * + * @note If a log operation will exceed available capacity, it fails with the + * error JOURNAL_STATUS_BOUNDED_CAPACITY. + * + * @note The actual size of data transfer (as reported by the status + * parameter of the callback or the return value from log() in case of + * synchronous operation) may be smaller than the amount requested. This + * could be due to the 'program_unit' of the underlying storage block-- + * i.e. the minimum programmable size. Refer to @ref + * FlashJournal_Info_t::program_unit. It is the caller's responsibility + * for resubmitting this left-over data in a subsequent call to log. + * When logging an arbitrary amount of data, the last of a sequence of + * logs may need to be padded in order to align with the + * programming unit. + * + * @note If the total size requested to be logged is smaller + * than the MTD's program_unit, log() fails with an error value of + * JOURNAL_STATUS_SMALL_LOG_REQUEST. + * + * @note the data being logged isn't made persistent (or available for read- + * backs) until a commit. A sequence of log() operations is expected to end + * in a commit(). A new sequence of log()s should be initiated by the caller + * only after a commit() has completed. If a sequence of logs() is followed + * by an operation other than a commit, that operation will very likely + * return an error code. getInfo()s can still be called during a sequence of + * log()s. + * + * Here's a code snippet to suggest how this API might be used by callers: + * \code + * ASSERT(JOURNAL_STATUS_OK == 0); // this is a precondition; it doesn't need to be put in code + * int32_t returnValue = FlashJournal_log(&journal, buffer, size); + * if (returnValue < JOURNAL_STATUS_OK) { + * // handle error + * } else if (returnValue == JOURNAL_STATUS_OK) { + * ASSERT(MTD->GetCapabilities().asynchronous_ops == 1); + * // handle early return from asynchronous execution + * } else { + * ASSERT(returnValue <= size); + * // handle synchronous completion + * + * if (returnValue < size) { + * #if DEBUG + * FlashJournal_Info_t info; + * int32_t rc = FlashJournal_getInfo(&journal, &info); + * ASSERT(rc == JOURNAL_STATUS_OK); + * ASSERT(returnValue == (size - (size % info.program_unit))); + * #endif + * // move the last (size - returnValue) bytes of the buffer to the + * // beginning of the buffer to be used for the successive request. + * } + * } + * \endcode + */ +static inline int32_t FlashJournal_log(FlashJournal_t *journal, const void *blob, size_t n) +{ + return journal->ops.log(journal, blob, n); +} + +/** + * @brief Commit a blob accumulated through a (possibly empty) sequence of previously + * successful log() operations. A front-end for @ref FlashJournal_Ops_t::commit(). + * + * @param [in] journal + * A previously initialized journal. + * + * @return + * The function executes in the following ways: + * - When the operation is asynchronous--i.e. when the underlying MTD's + * ARM_STOR_CAPABILITIES::asynchronous_ops is set to 1--and the operation + * executed by the journal in a non-blocking (i.e. asynchronous) manner, + * control returns to the caller with JOURNAL_STATUS_OK before the actual + * completion of the operation (or with an appropriate error code in case of + * failure). When the operation completes, the command callback is invoked + * with 1 passed in as the 'status' parameter of the callback to indicate + * success. If any error is encountered after the launch of an asynchronous + * operation, the completion callback is invoked with an error status. + * - When the operation is executed by the journal in a blocking (i.e. + * synchronous) manner, control returns to the caller only upon the actual + * completion of the operation, or the discovery of a failure condition. In + * synchronous mode, the function returns 1 to indicate success, or an + * appropriate error code. + * + * @note If the underlying MTD's ARM_STORAGE_CAPABILITIES::asynchronous_ops + * is set then this operation may execute asynchronously. In the case of + * asynchronous operation, the invocation returns early (with + * JOURNAL_STATUS_OK) and results in a completion callback later. + * + * @note If the underlying MTD's ARM_STORAGE_CAPABILITIES::asynchronous_ops + * is set, the journal is not required to operate asynchronously. A + * commit operation can be finished synchronously in spite of + * ARM_STORAGE_CAPABILITIES::asynchronous_ops being set, returning the + * total size of the committed blob to indicate successful completion, + * or an appropriate error code. In this case no further invocation of a + * completion callback should be expected at a later time. + * + * Here's a code snippet to suggest how this API might be used by callers: + * \code + * ASSERT(JOURNAL_STATUS_OK == 0); // this is a precondition; it doesn't need to be put in code + * int32_t returnValue = FlashJournal_commit(&journal); + * if (returnValue < JOURNAL_STATUS_OK) { + * // handle error + * } else if (returnValue == JOURNAL_STATUS_OK) { + * ASSERT(MTD->GetCapabilities().asynchronous_ops == 1); + * // handle early return from asynchronous execution + * } else { + * // handle synchronous completion + * ASSERT(returnValue == 1); + * ... + * } + * \endcode + * + * @note A sequence of log() operations is expected to end in a commit(). A new + * sequence of log()s should be initiated by the caller only after a + * commit() has completed. If a sequence of logs() is followed + * by an operation other than a commit, that operation will very likely + * return an error code. + */ +static inline int32_t FlashJournal_commit(FlashJournal_t *journal) +{ + return journal->ops.commit(journal); +} + +/** + * @brief Reset the journal. This has the effect of erasing all valid blobs. A + * front-end for @ref FlashJournal_Ops_t::reset(). + * + * @param [in] journal + * A previously initialized journal. + * + * @return + * The function executes in the following ways: + * - When the operation is asynchronous--i.e. when the underlying MTD's + * ARM_STOR_CAPABILITIES::asynchronous_ops is set to 1--and the + * operation executed by the journal in a non-blocking (i.e. + * asynchronous) manner, control returns to the caller with + * JOURNAL_STATUS_OK before the actual completion of the operation (or + * with an appropriate error code in case of failure). When the + * operation completes, the command callback is invoked with + * JOURNAL_STATUS_OK passed in as the 'status' parameter of the + * callback. If any error is encountered after the launch of an + * asynchronous operation, the completion callback is invoked with an + * error status. + * - When the operation is executed by the journal in a blocking (i.e. + * synchronous) manner, control returns to the caller only upon the + * actual completion of the operation, or the discovery of a failure + * condition. In synchronous mode, the function returns 1 to signal + * successful completion, or an appropriate error code. + * + * @note If the underlying MTD's ARM_STORAGE_CAPABILITIES::asynchronous_ops + * is set then this operation may execute asynchronously. In the case of + * asynchronous operation, the invocation returns early (with + * JOURNAL_STATUS_OK) and results in a completion callback later. + * + * @note If the underlying MTD's ARM_STORAGE_CAPABILITIES::asynchronous_ops + * is set, the journal is not required to operate asynchronously. A + * reset operation can be finished synchronously in spite of + * ARM_STORAGE_CAPABILITIES::asynchronous_ops being set, returning 1 to + * indicate successful completion, or an appropriate error code. In this + * case no further invocation of a completion callback should be + * expected at a later time. + * + * Here's a code snippet to suggest how this API might be used by callers: + * \code + * ASSERT(JOURNAL_STATUS_OK == 0); // this is a precondition; it doesn't need to be put in code + * int32_t returnValue = FlashJournal_reset(&journal); + * if (returnValue < JOURNAL_STATUS_OK) { + * // handle error + * } else if (returnValue == JOURNAL_STATUS_OK) { + * ASSERT(MTD->GetCapabilities().asynchronous_ops == 1); + * // handle early return from asynchronous execution + * } else { + * ASSERT(returnValue == 1); + * // handle synchronous completion + * } + * \endcode + */ +static inline int32_t FlashJournal_reset(FlashJournal_t *journal) +{ + return journal->ops.reset(journal); +} + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif /* __FLASH_JOURNAL_H__ */ diff --git a/hal/hal/flash-abstraction/Driver_Common.h b/hal/hal/flash-abstraction/Driver_Common.h new file mode 100644 index 00000000000..794a0675161 --- /dev/null +++ b/hal/hal/flash-abstraction/Driver_Common.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __DRIVER_COMMON_H +#define __DRIVER_COMMON_H + +#include +#include +#include + +#define ARM_DRIVER_VERSION_MAJOR_MINOR(major,minor) (((major) << 8) | (minor)) + +/** +\brief Driver Version +*/ +typedef struct _ARM_DRIVER_VERSION { + uint16_t api; ///< API version + uint16_t drv; ///< Driver version +} ARM_DRIVER_VERSION; + +/* General return codes */ +#define ARM_DRIVER_OK 0 ///< Operation succeeded +#define ARM_DRIVER_ERROR -1 ///< Unspecified error +#define ARM_DRIVER_ERROR_BUSY -2 ///< Driver is busy +#define ARM_DRIVER_ERROR_TIMEOUT -3 ///< Timeout occurred +#define ARM_DRIVER_ERROR_UNSUPPORTED -4 ///< Operation not supported +#define ARM_DRIVER_ERROR_PARAMETER -5 ///< Parameter error +#define ARM_DRIVER_ERROR_SPECIFIC -6 ///< Start of driver specific errors + +/** +\brief General power states +*/ +typedef enum _ARM_POWER_STATE { + ARM_POWER_OFF, ///< Power off: no operation possible + ARM_POWER_LOW, ///< Low Power mode: retain state, detect and signal wake-up events + ARM_POWER_FULL ///< Power on: full operation at maximum performance +} ARM_POWER_STATE; + +#endif /* __DRIVER_COMMON_H */ diff --git a/hal/hal/flash-abstraction/Driver_Storage.h b/hal/hal/flash-abstraction/Driver_Storage.h new file mode 100644 index 00000000000..d0ca583bd57 --- /dev/null +++ b/hal/hal/flash-abstraction/Driver_Storage.h @@ -0,0 +1,765 @@ +/* + * Copyright (c) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __DRIVER_STORAGE_H +#define __DRIVER_STORAGE_H + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +#include "Driver_Common.h" + +#define ARM_STORAGE_API_VERSION ARM_DRIVER_VERSION_MAJOR_MINOR(1,00) /* API version */ + + +#define _ARM_Driver_Storage_(n) Driver_Storage##n +#define ARM_Driver_Storage_(n) _ARM_Driver_Storage_(n) + +#define ARM_STORAGE_INVALID_OFFSET (0xFFFFFFFFFFFFFFFFULL) ///< Invalid address (relative to a storage controller's + ///< address space). A storage block may never start at this address. + +#define ARM_STORAGE_INVALID_ADDRESS (0xFFFFFFFFUL) ///< Invalid address within the processor's memory address space. + ///< Refer to memory-mapped storage, i.e. < \ref ARM_DRIVER_STORAGE::ResolveAddress(). + +/****** Storage specific error codes *****/ +#define ARM_STORAGE_ERROR_NOT_ERASABLE (ARM_DRIVER_ERROR_SPECIFIC - 1) ///< Part (or all) of the range provided to Erase() isn't erasable. +#define ARM_STORAGE_ERROR_NOT_PROGRAMMABLE (ARM_DRIVER_ERROR_SPECIFIC - 2) ///< Part (or all) of the range provided to ProgramData() isn't programmable. +#define ARM_STORAGE_ERROR_PROTECTED (ARM_DRIVER_ERROR_SPECIFIC - 3) ///< Part (or all) of the range to Erase() or ProgramData() is protected. + +/** + * \brief Attributes of the storage range within a storage block. + */ +typedef struct _ARM_STORAGE_BLOCK_ATTRIBUTES { + uint32_t erasable : 1; ///< Erasing blocks is permitted with a minimum granularity of 'erase_unit'. + ///< @note: if 'erasable' is 0--i.e. the 'erase' operation isn't available--then + ///< 'erase_unit' (see below) is immaterial and should be 0. + uint32_t programmable : 1; ///< Writing to ranges is permitted with a minimum granularity of 'program_unit'. + ///< Writes are typically achieved through the ProgramData operation (following an erase); + ///< if storage isn't erasable (see 'erasable' above) but is memory-mapped + ///< (i.e. 'memory_mapped'), it can be written directly using memory-store operations. + uint32_t executable : 1; ///< This storage block can hold program data; the processor can fetch and execute code + ///< sourced from it. Often this is accompanied with the device being 'memory_mapped' (see \ref ARM_STORAGE_INFO). + uint32_t protectable : 1; ///< The entire block can be protected from program and erase operations. Once protection + ///< is enabled for a block, its 'erasable' and 'programmable' bits are turned off. + uint32_t reserved : 28; + uint32_t erase_unit; ///< Minimum erase size in bytes. + ///< The offset of the start of the erase-range should also be aligned with this value. + ///< Applicable if the 'erasable' attribute is set for the block. + ///< @note: if 'erasable' (see above) is 0--i.e. the 'erase' operation isn't available--then + ///< 'erase_unit' is immaterial and should be 0. + uint32_t protection_unit; ///< Minimum protectable size in bytes. Applicable if the 'protectable' + ///< attribute is set for the block. This should be a divisor of the block's size. A + ///< block can be considered to be made up of consecutive, individually-protectable fragments. +} ARM_STORAGE_BLOCK_ATTRIBUTES; + +/** + * \brief A storage block is a range of memory with uniform attributes. Storage blocks + * combine to make up the address map of a storage controller. + */ +typedef struct _ARM_STORAGE_BLOCK { + uint64_t addr; ///< This is the start address of the storage block. It is + ///< expressed as an offset from the start of the storage map + ///< maintained by the owning storage controller. + uint64_t size; ///< This is the size of the storage block, in units of bytes. + ///< Together with addr, it describes a range [addr, addr+size). + ARM_STORAGE_BLOCK_ATTRIBUTES attributes; ///< Attributes for this block. +} ARM_STORAGE_BLOCK; + +/** + * The check for a valid ARM_STORAGE_BLOCK. + */ +#define ARM_STORAGE_VALID_BLOCK(BLK) (((BLK)->addr != ARM_STORAGE_INVALID_OFFSET) && ((BLK)->size != 0)) + +/** + * \brief Values for encoding storage memory-types with respect to programmability. + * + * Please ensure that the maximum of the following memory types doesn't exceed 16; we + * encode this in a 4-bit field within ARM_STORAGE_INFO::programmability. + */ +#define ARM_STORAGE_PROGRAMMABILITY_RAM (0x0) +#define ARM_STORAGE_PROGRAMMABILITY_ROM (0x1) ///< Read-only memory. +#define ARM_STORAGE_PROGRAMMABILITY_WORM (0x2) ///< write-once-read-only-memory (WORM). +#define ARM_STORAGE_PROGRAMMABILITY_ERASABLE (0x3) ///< re-programmable based on erase. Supports multiple writes. + +/** + * Values for encoding data-retention levels for storage blocks. + * + * Please ensure that the maximum of the following retention types doesn't exceed 16; we + * encode this in a 4-bit field within ARM_STORAGE_INFO::retention_level. + */ +#define ARM_RETENTION_WHILE_DEVICE_ACTIVE (0x0) ///< Data is retained only during device activity. +#define ARM_RETENTION_ACROSS_SLEEP (0x1) ///< Data is retained across processor sleep. +#define ARM_RETENTION_ACROSS_DEEP_SLEEP (0x2) ///< Data is retained across processor deep-sleep. +#define ARM_RETENTION_BATTERY_BACKED (0x3) ///< Data is battery-backed. Device can be powered off. +#define ARM_RETENTION_NVM (0x4) ///< Data is retained in non-volatile memory. + +/** + * Device Data Security Protection Features. Applicable mostly to EXTERNAL_NVM. + */ +typedef struct _ARM_STORAGE_SECURITY_FEATURES { + uint32_t acls : 1; ///< Protection against internal software attacks using ACLs. + uint32_t rollback_protection : 1; ///< Roll-back protection. Set to true if the creator of the storage + ///< can ensure that an external attacker can't force an + ///< older firmware to run or to revert back to a previous state. + uint32_t tamper_proof : 1; ///< Tamper-proof memory (will be deleted on tamper-attempts using board level or chip level sensors). + uint32_t internal_flash : 1; ///< Internal flash. + uint32_t reserved1 : 12; + + /** + * Encode support for hardening against various classes of attacks. + */ + uint32_t software_attacks : 1; ///< device software (malware running on the device). + uint32_t board_level_attacks : 1; ///< board level attacks (debug probes, copy protection fuses.) + uint32_t chip_level_attacks : 1; ///< chip level attacks (tamper-protection). + uint32_t side_channel_attacks : 1; ///< side channel attacks. + uint32_t reserved2 : 12; +} ARM_STORAGE_SECURITY_FEATURES; + +#define ARM_STORAGE_PROGRAM_CYCLES_INFINITE (0UL) /**< Infinite or unknown endurance for reprogramming. */ + +/** + * \brief Storage information. This contains device-metadata. It is the return + * value from calling GetInfo() on the storage driver. + * + * \details These fields serve a different purpose than the ones contained in + * \ref ARM_STORAGE_CAPABILITIES, which is another structure containing + * device-level metadata. ARM_STORAGE_CAPABILITIES describes the API + * capabilities, whereas ARM_STORAGE_INFO describes the device. Furthermore + * ARM_STORAGE_CAPABILITIES fits within a single word, and is designed to be + * passed around by value; ARM_STORAGE_INFO, on the other hand, contains + * metadata which doesn't fit into a single word and requires the use of + * pointers to be moved around. + */ +typedef struct _ARM_STORAGE_INFO { + uint64_t total_storage; ///< Total available storage, in bytes. + uint32_t program_unit; ///< Minimum programming size in bytes. + ///< The offset of the start of the program-range should also be aligned with this value. + ///< Applicable only if the 'programmable' attribute is set for a block. + ///< @note: setting program_unit to 0 has the effect of disabling the size and alignment + ///< restrictions (setting it to 1 also has the same effect). + uint32_t optimal_program_unit; ///< Optimal programming page-size in bytes. Some storage controllers + ///< have internal buffers into which to receive data. Writing in chunks of + ///< 'optimal_program_unit' would achieve maximum programming speed. + ///< Applicable only if the 'programmable' attribute is set for the underlying block(s). + uint32_t program_cycles; ///< A measure of endurance for reprogramming. + ///< Use ARM_STORAGE_PROGRAM_CYCLES_INFINITE for infinite or unknown endurance. + uint32_t erased_value : 1; ///< Contents of erased memory (usually 1 to indicate erased bytes with state 0xFF). + uint32_t memory_mapped : 1; ///< This storage device has a mapping onto the processor's memory address space. + ///< @note: For a memory-mapped block which isn't erasable but is programmable (i.e. if + ///< 'erasable' is set to 0, but 'programmable' is 1), writes should be possible directly to + ///< the memory-mapped storage without going through the ProgramData operation. + uint32_t programmability : 4; ///< A value to indicate storage programmability. + uint32_t retention_level : 4; + uint32_t reserved : 22; + ARM_STORAGE_SECURITY_FEATURES security; ///< \ref ARM_STORAGE_SECURITY_FEATURES +} ARM_STORAGE_INFO; + +/** +\brief Operating status of the storage controller. +*/ +typedef struct _ARM_STORAGE_STATUS { + uint32_t busy : 1; ///< Controller busy flag + uint32_t error : 1; ///< Read/Program/Erase error flag (cleared on start of next operation) +} ARM_STORAGE_STATUS; + +/** + * \brief Storage Driver API Capabilities. + * + * This data structure is designed to fit within a single word so that it can be + * fetched cheaply using a call to driver->GetCapabilities(). + */ +typedef struct _ARM_STORAGE_CAPABILITIES { + uint32_t asynchronous_ops : 1; ///< Used to indicate if APIs like initialize, + ///< read, erase, program, etc. can operate in asynchronous mode. + ///< Setting this bit to 1 means that the driver is capable + ///< of launching asynchronous operations; command completion is + ///< signaled by the invocation of a completion callback. If + ///< set to 1, drivers may still complete asynchronous + ///< operations synchronously as necessary--in which case they + ///< return a positive error code to indicate synchronous completion. + uint32_t erase_all : 1; ///< Supports EraseAll operation. + uint32_t reserved : 30; +} ARM_STORAGE_CAPABILITIES; + +/** + * Command opcodes for Storage. Completion callbacks use these codes to refer to + * completing commands. Refer to \ref ARM_Storage_Callback_t. + */ +typedef enum _ARM_STORAGE_OPERATION { + ARM_STORAGE_OPERATION_GET_VERSION, + ARM_STORAGE_OPERATION_GET_CAPABILITIES, + ARM_STORAGE_OPERATION_INITIALIZE, + ARM_STORAGE_OPERATION_UNINITIALIZE, + ARM_STORAGE_OPERATION_POWER_CONTROL, + ARM_STORAGE_OPERATION_READ_DATA, + ARM_STORAGE_OPERATION_PROGRAM_DATA, + ARM_STORAGE_OPERATION_ERASE, + ARM_STORAGE_OPERATION_ERASE_ALL, + ARM_STORAGE_OPERATION_GET_STATUS, + ARM_STORAGE_OPERATION_GET_INFO, + ARM_STORAGE_OPERATION_RESOLVE_ADDRESS, + ARM_STORAGE_OPERATION_GET_NEXT_BLOCK, + ARM_STORAGE_OPERATION_GET_BLOCK +} ARM_STORAGE_OPERATION; + +/** + * Declaration of the callback-type for command completion. + * + * @param [in] status + * A code to indicate the status of the completed operation. For data + * transfer operations, the status field is overloaded in case of + * success to return the count of items successfully transferred; this + * can be done safely because error codes are negative values. + * + * @param [in] operation + * The command op-code. This value isn't essential for the callback in + * the presence of the command instance-id, but it is expected that + * this information could be a quick and useful filter. + */ +typedef void (*ARM_Storage_Callback_t)(int32_t status, ARM_STORAGE_OPERATION operation); + +/** + * This is the set of operations constituting the Storage driver. Their + * implementation is platform-specific, and needs to be supplied by the + * porting effort. + * + * Some APIs within `ARM_DRIVER_STORAGE` will always operate synchronously: + * GetVersion, GetCapabilities, GetStatus, GetInfo, ResolveAddress, + * GetNextBlock, and GetBlock. This means that control returns to the caller + * with a relevant status code only after the completion of the operation (or + * the discovery of a failure condition). + * + * The remainder of the APIs: Initialize, Uninitialize, PowerControl, ReadData, + * ProgramData, Erase, EraseAll, can function asynchronously if the underlying + * controller supports it--i.e. if ARM_STORAGE_CAPABILITIES::asynchronous_ops is + * set. In the case of asynchronous operation, the invocation returns early + * (with ARM_DRIVER_OK) and results in a completion callback later. If + * ARM_STORAGE_CAPABILITIES::asynchronous_ops is not set, then all such APIs + * execute synchronously, and control returns to the caller with a status code + * only after the completion of the operation (or the discovery of a failure + * condition). + * + * If ARM_STORAGE_CAPABILITIES::asynchronous_ops is set, a storage driver may + * still choose to execute asynchronous operations in a synchronous manner. If + * so, the driver returns a positive value to indicate successful synchronous + * completion (or an error code in case of failure) and no further invocation of + * completion callback should be expected. The expected return value for + * synchronous completion of such asynchronous operations varies depending on + * the operation. For operations involving data access, it often equals the + * amount of data transferred or affected. For non data-transfer operations, + * such as EraseAll or Initialize, it is usually 1. + * + * Here's a code snippet to suggest how asynchronous APIs might be used by + * callers to handle both synchronous and asynchronous execution by the + * underlying storage driver: + * \code + * ASSERT(ARM_DRIVER_OK == 0); // this is a precondition; it doesn't need to be put in code + * int32_t returnValue = drv->asynchronousAPI(...); + * if (returnValue < ARM_DRIVER_OK) { + * // handle error. + * } else if (returnValue == ARM_DRIVER_OK) { + * ASSERT(drv->GetCapabilities().asynchronous_ops == 1); + * // handle early return from asynchronous execution; remainder of the work is done in the callback handler. + * } else { + * ASSERT(returnValue == EXPECTED_RETURN_VALUE_FOR_SYNCHRONOUS_COMPLETION); + * // handle synchronous completion. + * } + * \endcode + */ +typedef struct _ARM_DRIVER_STORAGE { + /** + * \brief Get driver version. + * + * The function GetVersion() returns version information of the driver implementation in ARM_DRIVER_VERSION. + * + * - API version is the version of the CMSIS-Driver specification used to implement this driver. + * - Driver version is source code version of the actual driver implementation. + * + * Example: + * \code + * extern ARM_DRIVER_STORAGE *drv_info; + * + * void read_version (void) { + * ARM_DRIVER_VERSION version; + * + * version = drv_info->GetVersion (); + * if (version.api < 0x10A) { // requires at minimum API version 1.10 or higher + * // error handling + * return; + * } + * } + * \endcode + * + * @return \ref ARM_DRIVER_VERSION. + * + * @note This API returns synchronously--it does not result in an invocation + * of a completion callback. + * + * @note The function GetVersion() can be called any time to obtain the + * required information from the driver (even before initialization). It + * always returns the same information. + */ + ARM_DRIVER_VERSION (*GetVersion)(void); + + /** + * \brief Get driver capabilities. + * + * \details The function GetCapabilities() returns information about + * capabilities in this driver implementation. The data fields of the struct + * ARM_STORAGE_CAPABILITIES encode various capabilities, for example if the device + * is able to execute operations asynchronously. + * + * Example: + * \code + * extern ARM_DRIVER_STORAGE *drv_info; + * + * void read_capabilities (void) { + * ARM_STORAGE_CAPABILITIES drv_capabilities; + * + * drv_capabilities = drv_info->GetCapabilities (); + * // interrogate capabilities + * + * } + * \endcode + * + * @return \ref ARM_STORAGE_CAPABILITIES. + * + * @note This API returns synchronously--it does not result in an invocation + * of a completion callback. + * + * @note The function GetCapabilities() can be called any time to obtain the + * required information from the driver (even before initialization). It + * always returns the same information. + */ + ARM_STORAGE_CAPABILITIES (*GetCapabilities)(void); + + /** + * \brief Initialize the Storage Interface. + * + * The function Initialize is called when the middleware component starts + * operation. In addition to bringing the controller to a ready state, + * Initialize() receives a callback handler to be invoked upon completion of + * asynchronous operations. + * + * Initialize() needs to be called explicitly before + * powering the peripheral using PowerControl(), and before initiating other + * accesses to the storage controller. + * + * The function performs the following operations: + * - Initializes the resources needed for the Storage interface. + * - Registers the \ref ARM_Storage_Callback_t callback function. + * + * To start working with a peripheral the functions Initialize and PowerControl need to be called in this order: + * drv->Initialize (...); // Allocate I/O pins + * drv->PowerControl (ARM_POWER_FULL); // Power up peripheral, setup IRQ/DMA + * + * - Initialize() typically allocates the I/O resources (pins) for the + * peripheral. The function can be called multiple times; if the I/O resources + * are already initialized it performs no operation and just returns with + * ARM_DRIVER_OK. + * + * - PowerControl (ARM_POWER_FULL) sets the peripheral registers including + * interrupt (NVIC) and optionally DMA. The function can be called multiple + * times; if the registers are already set it performs no operation and just + * returns with ARM_DRIVER_OK. + * + * To stop working with a peripheral the functions PowerControl and Uninitialize need to be called in this order: + * drv->PowerControl (ARM_POWER_OFF); // Terminate any pending transfers, reset IRQ/DMA, power off peripheral + * drv->Uninitialize (...); // Release I/O pins + * + * The functions PowerControl and Uninitialize always execute and can be used + * to put the peripheral into a Safe State, for example after any data + * transmission errors. To restart the peripheral in an error condition, + * you should first execute the Stop Sequence and then the Start Sequence. + * + * @param [in] callback + * Caller-defined callback to be invoked upon command completion + * for asynchronous APIs (including the completion of + * initialization). Use a NULL pointer when no callback + * signals are required. + * + * @note This API may execute asynchronously if + * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous + * execution is optional even if 'asynchronous_ops' is set. + * + * @return If asynchronous activity is launched, an invocation returns + * ARM_DRIVER_OK, and the caller can expect to receive a callback in the + * future with a status value of ARM_DRIVER_OK or an error-code. In the + * case of synchronous execution, control returns after completion with a + * value of 1. Return values less than ARM_DRIVER_OK (0) signify errors. + */ + int32_t (*Initialize)(ARM_Storage_Callback_t callback); + + /** + * \brief De-initialize the Storage Interface. + * + * The function Uninitialize() de-initializes the resources of Storage interface. + * + * It is called when the middleware component stops operation, and wishes to + * release the software resources used by the interface. + * + * @note This API may execute asynchronously if + * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous + * execution is optional even if 'asynchronous_ops' is set. + * + * @return If asynchronous activity is launched, an invocation returns + * ARM_DRIVER_OK, and the caller can expect to receive a callback in the + * future with a status value of ARM_DRIVER_OK or an error-code. In the + * case of synchronous execution, control returns after completion with a + * value of 1. Return values less than ARM_DRIVER_OK (0) signify errors. + */ + int32_t (*Uninitialize)(void); + + /** + * \brief Control the Storage interface power. + * + * The function \b ARM_Storage_PowerControl operates the power modes of the Storage interface. + * + * To start working with a peripheral the functions Initialize and PowerControl need to be called in this order: + * drv->Initialize (...); // Allocate I/O pins + * drv->PowerControl (ARM_POWER_FULL); // Power up peripheral, setup IRQ/DMA + * + * - Initialize() typically allocates the I/O resources (pins) for the + * peripheral. The function can be called multiple times; if the I/O resources + * are already initialized it performs no operation and just returns with + * ARM_DRIVER_OK. + * + * - PowerControl (ARM_POWER_FULL) sets the peripheral registers including + * interrupt (NVIC) and optionally DMA. The function can be called multiple + * times; if the registers are already set it performs no operation and just + * returns with ARM_DRIVER_OK. + * + * To stop working with a peripheral the functions PowerControl and Uninitialize need to be called in this order: + * + * drv->PowerControl (ARM_POWER_OFF); // Terminate any pending transfers, reset IRQ/DMA, power off peripheral + * drv->Uninitialize (...); // Release I/O pins + * + * The functions PowerControl and Uninitialize always execute and can be used + * to put the peripheral into a Safe State, for example after any data + * transmission errors. To restart the peripheral in an error condition, + * you should first execute the Stop Sequence and then the Start Sequence. + * + * @param state + * \ref ARM_POWER_STATE. The target power-state for the storage controller. + * The parameter state can have the following values: + * - ARM_POWER_FULL : set-up peripheral for data transfers, enable interrupts + * (NVIC) and optionally DMA. Can be called multiple times. If the peripheral + * is already in this mode, then the function performs no operation and returns + * with ARM_DRIVER_OK. + * - ARM_POWER_LOW : may use power saving. Returns ARM_DRIVER_ERROR_UNSUPPORTED when not implemented. + * - ARM_POWER_OFF : terminates any pending data transfers, disables peripheral, disables related interrupts and DMA. + * + * @note This API may execute asynchronously if + * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous + * execution is optional even if 'asynchronous_ops' is set. + * + * @return If asynchronous activity is launched, an invocation returns + * ARM_DRIVER_OK, and the caller can expect to receive a callback in the + * future with a status value of ARM_DRIVER_OK or an error-code. In the + * case of synchronous execution, control returns after completion with a + * value of 1. Return values less than ARM_DRIVER_OK (0) signify errors. + */ + int32_t (*PowerControl)(ARM_POWER_STATE state); + + /** + * \brief read the contents of a given address range from the storage device. + * + * \details Read the contents of a range of storage memory into a buffer + * supplied by the caller. The buffer is owned by the caller and should + * remain accessible for the lifetime of this command. + * + * @param [in] addr + * This specifies the address from where to read data. + * + * @param [out] data + * The destination of the read operation. The buffer + * is owned by the caller and should remain accessible for the + * lifetime of this command. + * + * @param [in] size + * The number of bytes requested to read. The data buffer + * should be at least as large as this size. + * + * @note This API may execute asynchronously if + * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous + * execution is optional even if 'asynchronous_ops' is set. + * + * @return If asynchronous activity is launched, an invocation returns + * ARM_DRIVER_OK, and the caller can expect to receive a callback in the + * future with the number of successfully transferred bytes passed in as + * the 'status' parameter. In the case of synchronous execution, control + * returns after completion with a positive transfer-count. Return values + * less than ARM_DRIVER_OK (0) signify errors. + */ + int32_t (*ReadData)(uint64_t addr, void *data, uint32_t size); + + /** + * \brief program (write into) the contents of a given address range of the storage device. + * + * \details Write the contents of a given memory buffer into a range of + * storage memory. In the case of flash memory, the destination range in + * storage memory typically has its contents in an erased state from a + * preceding erase operation. The source memory buffer is owned by the + * caller and should remain accessible for the lifetime of this command. + * + * @param [in] addr + * This is the start address of the range to be written into. It + * needs to be aligned to the device's \em program_unit + * specified in \ref ARM_STORAGE_INFO. + * + * @param [in] data + * The source of the write operation. The buffer is owned by the + * caller and should remain accessible for the lifetime of this + * command. + * + * @param [in] size + * The number of bytes requested to be written. The buffer + * should be at least as large as this size. \note 'size' should + * be a multiple of the device's 'program_unit' (see \ref + * ARM_STORAGE_INFO). + * + * @note It is best for the middleware to write in units of + * 'optimal_program_unit' (\ref ARM_STORAGE_INFO) of the device. + * + * @note This API may execute asynchronously if + * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous + * execution is optional even if 'asynchronous_ops' is set. + * + * @return If asynchronous activity is launched, an invocation returns + * ARM_DRIVER_OK, and the caller can expect to receive a callback in the + * future with the number of successfully transferred bytes passed in as + * the 'status' parameter. In the case of synchronous execution, control + * returns after completion with a positive transfer-count. Return values + * less than ARM_DRIVER_OK (0) signify errors. + */ + int32_t (*ProgramData)(uint64_t addr, const void *data, uint32_t size); + + /** + * @brief Erase Storage range. + * + * @details This function erases a range of storage specified by [addr, addr + + * size). Both 'addr' and 'addr + size' should align with the + * 'erase_unit'(s) of the respective owning storage block(s) (see \ref + * ARM_STORAGE_BLOCK and \ref ARM_STORAGE_BLOCK_ATTRIBUTES). The range to + * be erased will have its contents returned to the un-programmed state-- + * i.e. to 'erased_value' (see \ref ARM_STORAGE_BLOCK_ATTRIBUTES), which + * is usually 1 to indicate the pattern of all ones: 0xFF. + * + * @param [in] addr + * This is the start-address of the range to be erased. It must + * start at an 'erase_unit' boundary of the underlying block. + * + * @param [in] size + * Size (in bytes) of the range to be erased. 'addr + size' + * must be aligned with the 'erase_unit' of the underlying + * block. + * + * @note This API may execute asynchronously if + * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous + * execution is optional even if 'asynchronous_ops' is set. + * + * @return + * If the range to be erased doesn't align with the erase_units of the + * respective start and end blocks, ARM_DRIVER_ERROR_PARAMETER is returned. + * If any part of the range is protected, ARM_STORAGE_ERROR_PROTECTED is + * returned. If any part of the range is not erasable, + * ARM_STORAGE_ERROR_NOT_ERASABLE is returned. All such sanity-check + * failures result in the error code being returned synchronously and the + * storage bytes within the range remain unaffected. + * Otherwise the function executes in the following ways: + * If asynchronous activity is launched, an invocation returns + * ARM_DRIVER_OK, and the caller can expect to receive a callback in the + * future with the number of successfully erased bytes passed in as + * the 'status' parameter. In the case of synchronous execution, control + * returns after completion with a positive erase-count. Return values + * less than ARM_DRIVER_OK (0) signify errors. + * + * @note Erase() may return a smaller (positive) value than the size of the + * requested range. The returned value indicates the actual number of bytes + * erased. It is the caller's responsibility to follow up with an appropriate + * request to complete the operation. + * + * @note in the case of a failed erase (except when + * ARM_DRIVER_ERROR_PARAMETER, ARM_STORAGE_ERROR_PROTECTED, or + * ARM_STORAGE_ERROR_NOT_ERASABLE is returned synchronously), the + * requested range should be assumed to be in an unknown state. The + * previous contents may not be retained. + */ + int32_t (*Erase)(uint64_t addr, uint32_t size); + + /** + * @brief Erase complete storage. Optional function for faster erase of the complete device. + * + * This optional function erases the complete device. If the device does not + * support global erase then the function returns the error value \ref + * ARM_DRIVER_ERROR_UNSUPPORTED. The data field \em 'erase_all' = + * \token{1} of the structure \ref ARM_STORAGE_CAPABILITIES encodes that + * \ref ARM_STORAGE_EraseAll is supported. + * + * @note This API may execute asynchronously if + * ARM_STORAGE_CAPABILITIES::asynchronous_ops is set. Asynchronous + * execution is optional even if 'asynchronous_ops' is set. + * + * @return + * If any part of the storage range is protected, + * ARM_STORAGE_ERROR_PROTECTED is returned. If any part of the storage + * range is not erasable, ARM_STORAGE_ERROR_NOT_ERASABLE is returned. All + * such sanity-check failures result in the error code being returned + * synchronously and the storage bytes within the range remain unaffected. + * Otherwise the function executes in the following ways: + * If asynchronous activity is launched, an invocation returns + * ARM_DRIVER_OK, and the caller can expect to receive a callback in the + * future with ARM_DRIVER_OK passed in as the 'status' parameter. In the + * case of synchronous execution, control returns after completion with a + * value of 1. Return values less than ARM_DRIVER_OK (0) signify errors. + */ + int32_t (*EraseAll)(void); + + /** + * @brief Get the status of the current (or previous) command executed by the + * storage controller; stored in the structure \ref ARM_STORAGE_STATUS. + * + * @return + * The status of the underlying controller. + * + * @note This API returns synchronously--it does not result in an invocation + * of a completion callback. + */ + ARM_STORAGE_STATUS (*GetStatus)(void); + + /** + * @brief Get information about the Storage device; stored in the structure \ref ARM_STORAGE_INFO. + * + * @param [out] info + * A caller-supplied buffer capable of being filled in with an + * \ref ARM_STORAGE_INFO. + * + * @return ARM_DRIVER_OK if a ARM_STORAGE_INFO structure containing top level + * metadata about the storage controller is filled into the supplied + * buffer, else an appropriate error value. + * + * @note It is the caller's responsibility to ensure that the buffer passed in + * is able to be initialized with a \ref ARM_STORAGE_INFO. + * + * @note This API returns synchronously--it does not result in an invocation + * of a completion callback. + */ + int32_t (*GetInfo)(ARM_STORAGE_INFO *info); + + /** + * \brief For memory-mapped storage, resolve an address relative to + * the storage controller into a memory address. + * + * @param addr + * This is the address for which we want a resolution to the + * processor's physical address space. It is an offset from the + * start of the storage map maintained by the owning storage + * controller. + * + * @return + * The resolved address in the processor's address space; else + * ARM_STORAGE_INVALID_ADDRESS, if no resolution is possible. + * + * @note This API returns synchronously. The invocation should return quickly, + * and result in a resolved address. + */ + uint32_t (*ResolveAddress)(uint64_t addr); + + /** + * @brief Advance to the successor of the current block (iterator), or fetch + * the first block (if 'prev_block' is passed in as NULL). + * + * @details This helper function fetches (an iterator to) the next block (or + * the first block if 'prev_block' is passed in as NULL). In the failure + * case, a terminating, invalid block iterator is filled into the out + * parameter: 'next_block'. In combination with \ref + * ARM_STORAGE_VALID_BLOCK(), it can be used to iterate over the sequence + * of blocks within the storage map: + * + * \code + * ARM_STORAGE_BLOCK block; + * for (drv->GetNextBlock(NULL, &block); ARM_STORAGE_VALID_BLOCK(&block); drv->GetNextBlock(&block, &block)) { + * // make use of block + * } + * \endcode + * + * @param[in] prev_block + * An existing block (iterator) within the same storage + * controller. The memory buffer holding this block is owned + * by the caller. This pointer may be NULL; if so, the + * invocation fills in the first block into the out parameter: + * 'next_block'. + * + * @param[out] next_block + * A caller-owned buffer large enough to be filled in with + * the following ARM_STORAGE_BLOCK. It is legal to provide the + * same buffer using 'next_block' as was passed in with 'prev_block'. It + * is also legal to pass a NULL into this parameter if the + * caller isn't interested in populating a buffer with the next + * block--i.e. if the caller only wishes to establish the + * presence of a next block. + * + * @return ARM_DRIVER_OK if a valid next block is found (or first block, if + * prev_block is passed as NULL); upon successful operation, the contents + * of the next (or first) block are filled into the buffer pointed to by + * the parameter 'next_block' and ARM_STORAGE_VALID_BLOCK(next_block) is + * guaranteed to be true. Upon reaching the end of the sequence of blocks + * (iterators), or in case the driver is unable to fetch information about + * the next (or first) block, an error (negative) value is returned and an + * invalid StorageBlock is populated into the supplied buffer. If + * prev_block is NULL, the first block is returned. + * + * @note This API returns synchronously--it does not result in an invocation + * of a completion callback. + */ + int32_t (*GetNextBlock)(const ARM_STORAGE_BLOCK* prev_block, ARM_STORAGE_BLOCK *next_block); + + /** + * @brief Find the storage block (iterator) encompassing a given storage address. + * + * @param[in] addr + * Storage address in bytes. + * + * @param[out] block + * A caller-owned buffer large enough to be filled in with the + * ARM_STORAGE_BLOCK encapsulating the given address. This value + * can also be passed in as NULL if the caller isn't interested + * in populating a buffer with the block--if the caller only + * wishes to establish the presence of a containing storage + * block. + * + * @return ARM_DRIVER_OK if a containing storage-block is found. In this case, + * if block is non-NULL, the buffer pointed to by it is populated with + * the contents of the storage block--i.e. if block is valid and a block is + * found, ARM_STORAGE_VALID_BLOCK(block) would return true following this + * call. If there is no storage block containing the given offset, or in + * case the driver is unable to resolve an address to a storage-block, an + * error (negative) value is returned and an invalid StorageBlock is + * populated into the supplied buffer. + * + * @note This API returns synchronously--it does not result in an invocation + * of a completion callback. + */ + int32_t (*GetBlock)(uint64_t addr, ARM_STORAGE_BLOCK *block); +} const ARM_DRIVER_STORAGE; + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif /* __DRIVER_STORAGE_H */ diff --git a/hal/targets/hal/TARGET_Freescale/TARGET_KSDK2_MCUS/TARGET_K64F/flash_storage.c b/hal/targets/hal/TARGET_Freescale/TARGET_KSDK2_MCUS/TARGET_K64F/flash_storage.c new file mode 100644 index 00000000000..8964eb883fe --- /dev/null +++ b/hal/targets/hal/TARGET_Freescale/TARGET_KSDK2_MCUS/TARGET_K64F/flash_storage.c @@ -0,0 +1,1058 @@ +/* + * Copyright (c) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * This is a mock driver using the flash abstraction layer. It allows for writing tests. + */ + +#include +#include + +#include "flash-abstraction/Driver_Storage.h" +#include "cmsis_nvic.h" +#include "MK64F12.h" + +#if defined(MCU_MEM_MAP_VERSION) && ((MCU_MEM_MAP_VERSION > 2) || ((MCU_MEM_MAP_VERSION == 2) && (MCU_MEM_MAP_VERSION_MINOR >= 8))) +#define USING_KSDK2 1 +#endif + +#ifndef USING_KSDK2 +#include "device/MK64F12/MK64F12_ftfe.h" +#else +#include "drivers/fsl_flash.h" +#endif + +#define YOTTA_CFG_MBED_TRACE //this can be defined also in the yotta configuration file config.yml +#include "mbed-trace/mbed_trace.h" +#define TRACE_GROUP "mtd-k64f" + +#ifdef USING_KSDK2 +/*! + * @name Misc utility defines + * @{ + */ +#ifndef ALIGN_DOWN +#define ALIGN_DOWN(x, a) ((x) & (uint32_t)(-((int32_t)(a)))) +#endif +#ifndef ALIGN_UP +#define ALIGN_UP(x, a) (-((int32_t)((uint32_t)(-((int32_t)(x))) & (uint32_t)(-((int32_t)(a)))))) +#endif + +#define BYTES_JOIN_TO_WORD_1_3(x, y) ((((uint32_t)(x)&0xFFU) << 24) | ((uint32_t)(y)&0xFFFFFFU)) +#define BYTES_JOIN_TO_WORD_2_2(x, y) ((((uint32_t)(x)&0xFFFFU) << 16) | ((uint32_t)(y)&0xFFFFU)) +#define BYTES_JOIN_TO_WORD_3_1(x, y) ((((uint32_t)(x)&0xFFFFFFU) << 8) | ((uint32_t)(y)&0xFFU)) +#define BYTES_JOIN_TO_WORD_1_1_2(x, y, z) \ + ((((uint32_t)(x)&0xFFU) << 24) | (((uint32_t)(y)&0xFFU) << 16) | ((uint32_t)(z)&0xFFFFU)) +#define BYTES_JOIN_TO_WORD_1_2_1(x, y, z) \ + ((((uint32_t)(x)&0xFFU) << 24) | (((uint32_t)(y)&0xFFFFU) << 8) | ((uint32_t)(z)&0xFFU)) +#define BYTES_JOIN_TO_WORD_2_1_1(x, y, z) \ + ((((uint32_t)(x)&0xFFFFU) << 16) | (((uint32_t)(y)&0xFFU) << 8) | ((uint32_t)(z)&0xFFU)) +#define BYTES_JOIN_TO_WORD_1_1_1_1(x, y, z, w) \ + ((((uint32_t)(x)&0xFFU) << 24) | (((uint32_t)(y)&0xFFU) << 16) | (((uint32_t)(z)&0xFFU) << 8) | \ + ((uint32_t)(w)&0xFFU)) +/*@}*/ + +/*! + * @name Common flash register info defines + * @{ + */ +#if defined(FTFA) +#define FTFx FTFA +#define FTFx_BASE FTFA_BASE +#define FTFx_FSTAT_CCIF_MASK FTFA_FSTAT_CCIF_MASK +#define FTFx_FSTAT_RDCOLERR_MASK FTFA_FSTAT_RDCOLERR_MASK +#define FTFx_FSTAT_ACCERR_MASK FTFA_FSTAT_ACCERR_MASK +#define FTFx_FSTAT_FPVIOL_MASK FTFA_FSTAT_FPVIOL_MASK +#define FTFx_FSTAT_MGSTAT0_MASK FTFA_FSTAT_MGSTAT0_MASK +#define FTFx_FSEC_SEC_MASK FTFA_FSEC_SEC_MASK +#define FTFx_FSEC_KEYEN_MASK FTFA_FSEC_KEYEN_MASK +#define FTFx_FCNFG_CCIF_MASK FTFA_FCNFG_CCIE_MASK +#if defined(FSL_FEATURE_FLASH_HAS_FLEX_RAM) && FSL_FEATURE_FLASH_HAS_FLEX_RAM +#define FTFx_FCNFG_RAMRDY_MASK FTFA_FCNFG_RAMRDY_MASK +#endif /* FSL_FEATURE_FLASH_HAS_FLEX_RAM */ +#if defined(FSL_FEATURE_FLASH_HAS_FLEX_NVM) && FSL_FEATURE_FLASH_HAS_FLEX_NVM +#define FTFx_FCNFG_EEERDY_MASK FTFA_FCNFG_EEERDY_MASK +#endif /* FSL_FEATURE_FLASH_HAS_FLEX_NVM */ +#elif defined(FTFE) +#define FTFx FTFE +#define FTFx_BASE FTFE_BASE +#define FTFx_FSTAT_CCIF_MASK FTFE_FSTAT_CCIF_MASK +#define FTFx_FSTAT_RDCOLERR_MASK FTFE_FSTAT_RDCOLERR_MASK +#define FTFx_FSTAT_ACCERR_MASK FTFE_FSTAT_ACCERR_MASK +#define FTFx_FSTAT_FPVIOL_MASK FTFE_FSTAT_FPVIOL_MASK +#define FTFx_FSTAT_MGSTAT0_MASK FTFE_FSTAT_MGSTAT0_MASK +#define FTFx_FSEC_SEC_MASK FTFE_FSEC_SEC_MASK +#define FTFx_FSEC_KEYEN_MASK FTFE_FSEC_KEYEN_MASK +#define FTFx_FCNFG_CCIF_MASK FTFE_FCNFG_CCIE_MASK +#if defined(FSL_FEATURE_FLASH_HAS_FLEX_RAM) && FSL_FEATURE_FLASH_HAS_FLEX_RAM +#define FTFx_FCNFG_RAMRDY_MASK FTFE_FCNFG_RAMRDY_MASK +#endif /* FSL_FEATURE_FLASH_HAS_FLEX_RAM */ +#if defined(FSL_FEATURE_FLASH_HAS_FLEX_NVM) && FSL_FEATURE_FLASH_HAS_FLEX_NVM +#define FTFx_FCNFG_EEERDY_MASK FTFE_FCNFG_EEERDY_MASK +#endif /* FSL_FEATURE_FLASH_HAS_FLEX_NVM */ +#elif defined(FTFL) +#define FTFx FTFL +#define FTFx_BASE FTFL_BASE +#define FTFx_FSTAT_CCIF_MASK FTFL_FSTAT_CCIF_MASK +#define FTFx_FSTAT_RDCOLERR_MASK FTFL_FSTAT_RDCOLERR_MASK +#define FTFx_FSTAT_ACCERR_MASK FTFL_FSTAT_ACCERR_MASK +#define FTFx_FSTAT_FPVIOL_MASK FTFL_FSTAT_FPVIOL_MASK +#define FTFx_FSTAT_MGSTAT0_MASK FTFL_FSTAT_MGSTAT0_MASK +#define FTFx_FSEC_SEC_MASK FTFL_FSEC_SEC_MASK +#define FTFx_FSEC_KEYEN_MASK FTFL_FSEC_KEYEN_MASK +#define FTFx_FCNFG_CCIF_MASK FTFL_FCNFG_CCIE_MASK +#if defined(FSL_FEATURE_FLASH_HAS_FLEX_RAM) && FSL_FEATURE_FLASH_HAS_FLEX_RAM +#define FTFx_FCNFG_RAMRDY_MASK FTFL_FCNFG_RAMRDY_MASK +#endif /* FSL_FEATURE_FLASH_HAS_FLEX_RAM */ +#if defined(FSL_FEATURE_FLASH_HAS_FLEX_NVM) && FSL_FEATURE_FLASH_HAS_FLEX_NVM +#define FTFx_FCNFG_EEERDY_MASK FTFL_FCNFG_EEERDY_MASK +#endif /* FSL_FEATURE_FLASH_HAS_FLEX_NVM */ +#else +#error "Unknown flash controller" +#endif +/*@}*/ + +/*! @brief Access to FTFx->FCCOB */ +volatile uint32_t *const kFCCOBx; + +static flash_config_t privateDeviceConfig; +#endif /* #ifdef USING_KSDK2 */ + +/* + * forward declarations + */ +static int32_t getBlock(uint64_t addr, ARM_STORAGE_BLOCK *blockP); +static int32_t nextBlock(const ARM_STORAGE_BLOCK* prevP, ARM_STORAGE_BLOCK *nextP); + +/* + * Global state for the driver. + */ +ARM_Storage_Callback_t commandCompletionCallback; +static bool initialized = false; +ARM_POWER_STATE powerState = ARM_POWER_OFF; + +ARM_STORAGE_OPERATION currentCommand; +uint64_t currentOperatingStorageAddress; +size_t sizeofCurrentOperation; +size_t amountLeftToOperate; +const uint8_t *currentOperatingData; + +#ifdef USING_KSDK2 +#define ERASE_UNIT (FSL_FEATURE_FLASH_PFLASH_BLOCK_SECTOR_SIZE) +#define BLOCK1_START_ADDR (FSL_FEATURE_FLASH_PFLASH_BLOCK_SIZE) +#define BLOCK1_SIZE (FSL_FEATURE_FLASH_PFLASH_BLOCK_SIZE) +#define PROGRAM_UNIT (FSL_FEATURE_FLASH_PFLASH_BLOCK_WRITE_UNIT_SIZE) +#define OPTIMAL_PROGRAM_UNIT (1024UL) +#define PROGRAM_PHRASE_SIZEOF_INLINE_DATA (8) +#define SIZEOF_DOUBLE_PHRASE (FSL_FEATURE_FLASH_PFLASH_SECTION_CMD_ADDRESS_ALIGMENT) +#else +#define ERASE_UNIT (4096) +#define BLOCK1_START_ADDR (0x80000UL) +#define BLOCK1_SIZE (0x80000UL) +#define PROGRAM_UNIT (8UL) +#define OPTIMAL_PROGRAM_UNIT (1024UL) +#define PROGRAM_PHRASE_SIZEOF_INLINE_DATA (8) +#define SIZEOF_DOUBLE_PHRASE (16) +#endif /* #ifdef USING_KSDK2 */ + +/* + * Static configuration. + */ +static const ARM_STORAGE_BLOCK blockTable[] = { + { + /**< This is the start address of the flash block. */ +#ifdef YOTTA_CFG_CONFIG_HARDWARE_MTD_START_ADDR + .addr = YOTTA_CFG_CONFIG_HARDWARE_MTD_START_ADDR, +#else + .addr = BLOCK1_START_ADDR, +#endif + + /**< This is the size of the flash block, in units of bytes. + * Together with addr, it describes a range [addr, addr+size). */ +#ifdef YOTTA_CFG_CONFIG_HARDWARE_MTD_SIZE + .size = YOTTA_CFG_CONFIG_HARDWARE_MTD_SIZE, +#else + .size = BLOCK1_SIZE, +#endif + + .attributes = { /**< Attributes for this block. */ + .erasable = 1, + .programmable = 1, + .executable = 1, + .protectable = 1, + .erase_unit = ERASE_UNIT, + .protection_unit = BLOCK1_SIZE / 32, + } + } +}; + +static const ARM_DRIVER_VERSION version = { + .api = ARM_STORAGE_API_VERSION, + .drv = ARM_DRIVER_VERSION_MAJOR_MINOR(1,00) +}; + +static const ARM_STORAGE_CAPABILITIES caps = { + /**< Signal Flash Ready event. In other words, can APIs like initialize, + * read, erase, program, etc. operate in asynchronous mode? + * Setting this bit to 1 means that the driver is capable of launching + * asynchronous operations; command completion is signaled by the + * generation of an event or the invocation of a completion callback + * (depending on how the flash controller has been initialized). If set to + * 1, drivers may still complete asynchronous operations synchronously as + * necessary--in which case they return a positive error code to indicate + * synchronous completion. */ +#ifndef YOTTA_CFG_CONFIG_HARDWARE_MTD_ASYNC_OPS + .asynchronous_ops = 1, +#else + .asynchronous_ops = YOTTA_CFG_CONFIG_HARDWARE_MTD_ASYNC_OPS, +#endif + + /* Enable chip-erase functionality if we own all of block-1. */ + #if ((!defined (YOTTA_CFG_CONFIG_HARDWARE_MTD_START_ADDR) || (YOTTA_CFG_CONFIG_HARDWARE_MTD_START_ADDR == BLOCK1_START_ADDR)) && \ + (!defined (YOTTA_CFG_CONFIG_HARDWARE_MTD_SIZE) || (YOTTA_CFG_CONFIG_HARDWARE_MTD_SIZE == BLOCK1_SIZE))) + .erase_all = 1, /**< Supports EraseChip operation. */ + #else + .erase_all = 0, /**< Supports EraseChip operation. */ + #endif +}; + +static const ARM_STORAGE_INFO info = { + .total_storage = 512 * 1024, /**< Total available storage, in units of octets. */ + + .program_unit = PROGRAM_UNIT, + .optimal_program_unit = OPTIMAL_PROGRAM_UNIT, + + .program_cycles = ARM_STORAGE_PROGRAM_CYCLES_INFINITE, /**< A measure of endurance for reprogramming. + * Use ARM_STOR_PROGRAM_CYCLES_INFINITE for infinite or unknown endurance. */ + + .erased_value = 0x1, /**< Contents of erased memory (1 to indicate erased octets with state 0xFF). */ + .memory_mapped = 1, + + .programmability = ARM_STORAGE_PROGRAMMABILITY_ERASABLE, /**< A value of type enum ARM_STOR_PROGRAMMABILITY. */ + .retention_level = ARM_RETENTION_NVM, + .security = { + .acls = 0, /**< against internal software attacks using ACLs. */ + .rollback_protection = 0, /**< roll-back protection. */ + .tamper_proof = 0, /**< tamper-proof memory (will be deleted on tamper-attempts using board level or chip level sensors). */ + .internal_flash = 1, /**< Internal flash. */ + + .software_attacks = 0, + .board_level_attacks = 0, + .chip_level_attacks = 0, + .side_channel_attacks = 0, + } +}; + + +/** + * This is the command code written into the first FCCOB register, FCCOB0. + */ +enum FlashCommandOps { + PGM8 = (uint8_t)0x07, /* program phrase */ + ERSBLK = (uint8_t)0x08, /* erase block */ + ERSSCR = (uint8_t)0x09, /* erase flash sector */ + PGMSEC = (uint8_t)0x0B, /* program section */ + SETRAM = (uint8_t)0x81, /* Set FlexRAM. (unused for now) */ +}; + + +/** + * Read out the CCIF (Command Complete Interrupt Flag) to ensure all previous + * operations have completed. + */ +static inline bool controllerCurrentlyBusy(void) +{ +#ifdef USING_KSDK2 + return ((FTFx->FSTAT & FTFx_FSTAT_CCIF_MASK) == 0); +#else + return (BR_FTFE_FSTAT_CCIF(FTFE) == 0); +#endif +} + +static inline bool failedWithAccessError(void) +{ +#ifdef USING_KSDK2 + /* Get flash status register value */ + uint8_t registerValue = FTFx->FSTAT; + + /* checking access error */ + return registerValue & FTFx_FSTAT_ACCERR_MASK; +#else + return BR_FTFE_FSTAT_ACCERR(FTFE); +#endif +} + +static inline bool failedWithProtectionError() +{ +#ifdef USING_KSDK2 + /* Get flash status register value */ + uint8_t registerValue = FTFx->FSTAT; + + /* checking protection error */ + return registerValue & FTFx_FSTAT_FPVIOL_MASK; +#else + return BR_FTFE_FSTAT_FPVIOL(FTFE); +#endif +} + +static inline bool failedWithRunTimeError() +{ +#ifdef USING_KSDK2 + /* Get flash status register value */ + uint8_t registerValue = FTFx->FSTAT; + + /* checking MGSTAT0 non-correctable error */ + return registerValue & FTFx_FSTAT_MGSTAT0_MASK; +#else + return BR_FTFE_FSTAT_MGSTAT0(FTFE); +#endif +} + +static inline void clearAccessError(void) +{ +#ifdef USING_KSDK2 + FTFx->FSTAT |= FTFx_FSTAT_ACCERR_MASK; +#else + BW_FTFE_FSTAT_ACCERR(FTFE, 1); +#endif +} + +static inline void clearProtectionError(void) +{ +#ifdef USING_KSDK2 + FTFx->FSTAT |= FTFx_FSTAT_FPVIOL_MASK; +#else + BW_FTFE_FSTAT_FPVIOL(FTFE, 1); +#endif +} + +/** + * @brief Clear the error bits before launching a command. + * + * The ACCERR error bit indicates an illegal access has occurred to an FTFE + * resource caused by a violation of the command write sequence or issuing an + * illegal FTFE command. While ACCERR is set, the CCIF flag cannot be cleared to + * launch a command. The ACCERR bit is cleared by writing a 1 to it. + * + * The FPVIOL error bit indicates an attempt was made to program or erase an + * address in a protected area of program flash or data flash memory during a + * command write sequence or a write was attempted to a protected area of the + * FlexRAM while enabled for EEPROM. While FPVIOL is set, the CCIF flag cannot + * be cleared to launch a command. The FPVIOL bit is cleared by writing a 1 to + * it. + */ +static inline void clearErrorStatusBits() +{ + if (failedWithAccessError()) { + clearAccessError(); + } + if (failedWithProtectionError()) { + clearProtectionError(); + } +} + +static inline void enableCommandCompletionInterrupt(void) +{ +#ifdef USING_KSDK2 + FTFx->FCNFG |= FTFE_FCNFG_CCIE_MASK; +#else + BW_FTFE_FCNFG_CCIE((uintptr_t)FTFE, 1); /* enable interrupt to detect CCIE being set. */ +#endif +} + +static inline void disbleCommandCompletionInterrupt(void) +{ +#ifdef USING_KSDK2 + FTFx->FCNFG &= ~FTFE_FCNFG_CCIE_MASK; +#else + BW_FTFE_FCNFG_CCIE((uintptr_t)FTFE, 0); /* disable command completion interrupt. */ +#endif +} + +static inline bool commandCompletionInterruptEnabled(void) +{ +#ifdef USING_KSDK2 + return ((FTFx->FCNFG & FTFE_FCNFG_CCIE_MASK) != 0); +#else + return (BR_FTFE_FCNFG_CCIE((uintptr_t)FTFE) != 0); +#endif +} + +static inline bool asyncOperationsEnabled(void) +{ + return caps.asynchronous_ops; +} + +/** + * Once all relevant command parameters have been loaded, the user launches the + * command by clearing the FSTAT[CCIF] bit by writing a '1' to it. The CCIF flag + * remains zero until the FTFE command completes. + */ +static inline void launchCommand(void) +{ +#ifdef USING_KSDK2 + FTFx->FSTAT = FTFx_FSTAT_CCIF_MASK; +#else + BW_FTFE_FSTAT_CCIF(FTFE, 1); +#endif +} + +#ifndef USING_KSDK2 +static inline void setupAddressInCCOB123(uint64_t addr) +{ + BW_FTFE_FCCOB1_CCOBn((uintptr_t)FTFE, (addr >> 16) & 0xFFUL); /* bits [23:16] of the address. */ + BW_FTFE_FCCOB2_CCOBn((uintptr_t)FTFE, (addr >> 8) & 0xFFUL); /* bits [15:8] of the address. */ + BW_FTFE_FCCOB3_CCOBn((uintptr_t)FTFE, (addr >> 0) & 0xFFUL); /* bits [7:0] of the address. */ +} +#endif + +static inline void setupEraseSector(uint64_t addr) +{ +#ifdef USING_KSDK2 + kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(ERSSCR, addr); +#else + BW_FTFE_FCCOB0_CCOBn((uintptr_t)FTFE, ERSSCR); + setupAddressInCCOB123(addr); +#endif +} + +static inline void setupEraseBlock(uint64_t addr) +{ +#ifdef USING_KSDK2 + kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(ERSBLK, addr); +#else + BW_FTFE_FCCOB0_CCOBn((uintptr_t)FTFE, ERSBLK); + setupAddressInCCOB123(addr); +#endif +} + +static inline void setup8ByteWrite(uint64_t addr, const void *data) +{ + /* Program FCCOB to load the required command parameters. */ +#ifdef USING_KSDK2 + kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(PGM8, addr); + + /* Program 8 bytes of data into FCCOB(4..11)_CCOBn */ + kFCCOBx[1] = ((const uint32_t *)data)[0]; + kFCCOBx[2] = ((const uint32_t *)data)[1]; +#else + BW_FTFE_FCCOB0_CCOBn((uintptr_t)FTFE, PGM8); + setupAddressInCCOB123(addr); + + BW_FTFE_FCCOB4_CCOBn((uintptr_t)FTFE, ((const uint8_t *)data)[3]); /* byte 3 of program value. */ + BW_FTFE_FCCOB5_CCOBn((uintptr_t)FTFE, ((const uint8_t *)data)[2]); /* byte 2 of program value. */ + BW_FTFE_FCCOB6_CCOBn((uintptr_t)FTFE, ((const uint8_t *)data)[1]); /* byte 1 of program value. */ + BW_FTFE_FCCOB7_CCOBn((uintptr_t)FTFE, ((const uint8_t *)data)[0]); /* byte 0 of program value. */ + BW_FTFE_FCCOB8_CCOBn((uintptr_t)FTFE, ((const uint8_t *)data)[7]); /* byte 7 of program value. */ + BW_FTFE_FCCOB9_CCOBn((uintptr_t)FTFE, ((const uint8_t *)data)[6]); /* byte 6 of program value. */ + BW_FTFE_FCCOBA_CCOBn((uintptr_t)FTFE, ((const uint8_t *)data)[5]); /* byte 5 of program value. */ + BW_FTFE_FCCOBB_CCOBn((uintptr_t)FTFE, ((const uint8_t *)data)[4]); /* byte 4 of program value. */ +#endif +} + +static inline void setupProgramSection(uint64_t addr, const void *data, size_t cnt) +{ +#ifdef USING_KSDK2 + static const uintptr_t FlexRAMBase = FSL_FEATURE_FLASH_FLEX_RAM_START_ADDRESS; + memcpy((void *)FlexRAMBase, (const uint8_t *)data, cnt); + + kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(PGMSEC, addr); + kFCCOBx[1] = BYTES_JOIN_TO_WORD_2_2(cnt >> 4, 0xFFFFU); +#else + static const uintptr_t FlexRAMBase = 0x14000000; + memcpy((void *)FlexRAMBase, (const uint8_t *)data, cnt); + + BW_FTFE_FCCOB0_CCOBn((uintptr_t)FTFE, PGMSEC); + setupAddressInCCOB123(addr); + + BW_FTFE_FCCOB4_CCOBn((uintptr_t)FTFE, ((((uint32_t)(cnt >> 4)) & (0x0000FF00)) >> 8)); /* number of 128-bits to program [15:8] */ + BW_FTFE_FCCOB5_CCOBn((uintptr_t)FTFE, (((uint32_t)(cnt >> 4)) & (0x000000FF))); /* number of 128-bits to program [7:0] */ +#endif +} + +/** + * Compute the size of the largest 'program-section' operation which is + * possible for the range [addr, addr+size) starting from addr. It is assumed + * that 'addr' is aligned to a double-phrase boundary (see \ref + * SIZEOF_DOUBLE_PHRASE)--if not, then only a single phrase (8-bytes) write is possible. + */ +static inline size_t sizeofLargestProgramSection(uint64_t addr, size_t size) +{ + /* ensure 'size' is aligned to a double-phrase boundary */ + if ((size % SIZEOF_DOUBLE_PHRASE) == PROGRAM_PHRASE_SIZEOF_INLINE_DATA) { + size -= PROGRAM_PHRASE_SIZEOF_INLINE_DATA; + } + + /* ensure 'size' isn't larger than OPTIMAL_PROGRAM_UNIT */ + if (size > OPTIMAL_PROGRAM_UNIT) { + size = OPTIMAL_PROGRAM_UNIT; + } + + /* ensure that the operation doesn't cross an erase boundary */ + size_t amountLeftInEraseUnit = ERASE_UNIT - (size_t)(addr % ERASE_UNIT); + if (size > amountLeftInEraseUnit) { + size = amountLeftInEraseUnit; + } + + return size; +} + +/** + * Advance the state machine for program-data. This function is called only if + * amountLeftToOperate is non-zero. + */ +static inline void setupNextProgramData(void) +{ + if ((amountLeftToOperate == PROGRAM_PHRASE_SIZEOF_INLINE_DATA) || + ((currentOperatingStorageAddress % SIZEOF_DOUBLE_PHRASE) == PROGRAM_PHRASE_SIZEOF_INLINE_DATA)) { + setup8ByteWrite(currentOperatingStorageAddress, currentOperatingData); + tr_debug("setupNextProgramData: W8, [%lu]", (uint32_t)currentOperatingStorageAddress); + + amountLeftToOperate -= PROGRAM_PHRASE_SIZEOF_INLINE_DATA; + currentOperatingStorageAddress += PROGRAM_PHRASE_SIZEOF_INLINE_DATA; + currentOperatingData += PROGRAM_PHRASE_SIZEOF_INLINE_DATA; + } else { + size_t amount = sizeofLargestProgramSection(currentOperatingStorageAddress, amountLeftToOperate); + setupProgramSection(currentOperatingStorageAddress, currentOperatingData, amount); + tr_debug("setupNextProgramData: W%u, [%lu]", amount, (uint32_t)currentOperatingStorageAddress); + + amountLeftToOperate -= amount; + currentOperatingStorageAddress += amount; + currentOperatingData += amount; + } +} + +/** + * Advance the state machine for erase. This function is called only if + * amountLeftToOperate is non-zero. + */ +static inline void setupNextErase(void) +{ + setupEraseSector(currentOperatingStorageAddress); /* Program FCCOB to load the required command parameters. */ + + amountLeftToOperate -= ERASE_UNIT; + currentOperatingStorageAddress += ERASE_UNIT; +} + +static int32_t executeCommand(void) +{ + tr_debug("executeCommand: top"); + launchCommand(); + + /* At this point, The FTFE reads the command code and performs a series of + * parameter checks and protection checks, if applicable, which are unique + * to each command. */ + + if (asyncOperationsEnabled()) { + /* Asynchronous operation */ + + /* Spin waiting for the command execution to begin. */ + while (!controllerCurrentlyBusy() && !failedWithAccessError() && !failedWithProtectionError()); + if (failedWithAccessError() || failedWithProtectionError()) { + clearErrorStatusBits(); + return ARM_DRIVER_ERROR_PARAMETER; + } + + enableCommandCompletionInterrupt(); + + tr_debug("executeCommand: async. return"); + return ARM_DRIVER_OK; /* signal asynchronous completion. An interrupt will signal completion later. */ + } else { + /* Synchronous operation. */ + + while (1) { + tr_debug("executeCommand: synchronous iteration"); + + /* Spin waiting for the command execution to complete. */ + while (controllerCurrentlyBusy()); + + /* Execution may result in failure. Check for errors */ + if (failedWithAccessError() || failedWithProtectionError()) { + clearErrorStatusBits(); + return ARM_DRIVER_ERROR_PARAMETER; + } + if (failedWithRunTimeError()) { + return ARM_DRIVER_ERROR; /* unspecified runtime error. */ + } + + /* signal synchronous completion. */ + switch (currentCommand) { + case ARM_STORAGE_OPERATION_PROGRAM_DATA: + if (amountLeftToOperate == 0) { + return sizeofCurrentOperation; + } + + /* start the successive program operation */ + setupNextProgramData(); + launchCommand(); + /* continue on to the next iteration of the parent loop */ + break; + + case ARM_STORAGE_OPERATION_ERASE: + if (amountLeftToOperate == 0) { + return sizeofCurrentOperation; + } + + setupNextErase(); /* start the successive erase operation */ + launchCommand(); + /* continue on to the next iteration of the parent loop */ + break; + + default: + return 1; + } + } + } +} + +static void ftfe_ccie_irq_handler(void) +{ + NVIC_ClearPendingIRQ(FTFE_IRQn); + disbleCommandCompletionInterrupt(); + + /* check for errors */ + if (failedWithAccessError() || failedWithProtectionError()) { + clearErrorStatusBits(); + if (commandCompletionCallback) { + commandCompletionCallback(ARM_DRIVER_ERROR_PARAMETER, currentCommand); + } + return; + } + if (failedWithRunTimeError()) { + if (commandCompletionCallback) { + commandCompletionCallback(ARM_DRIVER_ERROR, currentCommand); + } + return; + } + + switch (currentCommand) { + case ARM_STORAGE_OPERATION_PROGRAM_DATA: + if (amountLeftToOperate == 0) { + if (commandCompletionCallback) { + tr_debug("irq: [PROGRAM] invoking callback"); + commandCompletionCallback(sizeofCurrentOperation, ARM_STORAGE_OPERATION_PROGRAM_DATA); + } + return; + } + + /* start the successive program operation */ + setupNextProgramData(); + launchCommand(); + + while (!controllerCurrentlyBusy() && !failedWithAccessError() && !failedWithProtectionError()); + if (failedWithAccessError() || failedWithProtectionError()) { + clearErrorStatusBits(); + if (commandCompletionCallback) { + tr_debug("irq: [PROGRAM] invoking callback with error"); + commandCompletionCallback(ARM_DRIVER_ERROR_PARAMETER, ARM_STORAGE_OPERATION_PROGRAM_DATA); + } + return; + } + + enableCommandCompletionInterrupt(); + break; + + case ARM_STORAGE_OPERATION_ERASE: + if (amountLeftToOperate == 0) { + if (commandCompletionCallback) { + tr_debug("irq: [ERASE] invoking callback"); + commandCompletionCallback(sizeofCurrentOperation, ARM_STORAGE_OPERATION_ERASE); + } + return; + } + + setupNextErase(); + launchCommand(); + + while (!controllerCurrentlyBusy() && !failedWithAccessError() && !failedWithProtectionError()); + if (failedWithAccessError() || failedWithProtectionError()) { + clearErrorStatusBits(); + if (commandCompletionCallback) { + tr_debug("irq: [ERASE] invoking callback with error"); + commandCompletionCallback(ARM_DRIVER_ERROR_PARAMETER, ARM_STORAGE_OPERATION_ERASE); + } + return; + } + + enableCommandCompletionInterrupt(); + break; + + default: + if (commandCompletionCallback) { + tr_debug("irq: [default] invoking callback"); + commandCompletionCallback(ARM_DRIVER_OK, currentCommand); + } + break; + } +} + +/** + * This is a helper function which can be used to do arbitrary sanity checking + * on a range. + * + * It applies the 'check' function to every block in a given range. If any of + * the check() calls return failure (i.e. something other ARM_DRIVER_OK), + * validation terminates. Otherwise an ARM_DRIVER_OK is returned. + */ +static int32_t checkForEachBlockInRange(uint64_t startAddr, uint32_t size, int32_t (*check)(const ARM_STORAGE_BLOCK *block)) +{ + uint64_t addrBeingValidated = startAddr; + ARM_STORAGE_BLOCK block; + if (getBlock(addrBeingValidated, &block) != ARM_DRIVER_OK) { + return ARM_DRIVER_ERROR_PARAMETER; + } + while (addrBeingValidated < (startAddr + size)) { + int32_t rc; + if ((rc = check(&block)) != ARM_DRIVER_OK) { + return rc; + } + + + /* move on to the following block */ + if (nextBlock(&block, &block) != ARM_DRIVER_OK) { + break; + } + addrBeingValidated = block.addr; + } + + return ARM_DRIVER_OK; +} + +static int32_t blockIsProgrammable(const ARM_STORAGE_BLOCK *blockP) { + if (!blockP->attributes.programmable) { + return ARM_STORAGE_ERROR_NOT_PROGRAMMABLE; + } + + return ARM_DRIVER_OK; +} + +static int32_t blockIsErasable(const ARM_STORAGE_BLOCK *blockP) { + if (!blockP->attributes.erasable) { + return ARM_STORAGE_ERROR_NOT_ERASABLE; + } + + return ARM_DRIVER_OK; +} + +static ARM_DRIVER_VERSION getVersion(void) +{ + return version; +} + +static ARM_STORAGE_CAPABILITIES getCapabilities(void) +{ + return caps; +} + +static int32_t initialize(ARM_Storage_Callback_t callback) +{ + tr_debug("called initialize(%p)", callback); + currentCommand = ARM_STORAGE_OPERATION_INITIALIZE; + + if (initialized) { + commandCompletionCallback = callback; + + return 1; /* synchronous completion. */ + } + +#ifdef USING_KSDK2 + status_t rc = FLASH_Init(&privateDeviceConfig); + if (rc != kStatus_FLASH_Success) { + return ARM_DRIVER_ERROR; + } +#endif + + if (controllerCurrentlyBusy()) { + /* The user cannot initiate any further FTFE commands until notified that the + * current command has completed.*/ + return (int32_t)ARM_DRIVER_ERROR_BUSY; + } + + clearErrorStatusBits(); + + commandCompletionCallback = callback; + + /* Enable the command-completion interrupt. */ + if (asyncOperationsEnabled()) { + NVIC_SetVector(FTFE_IRQn, (uint32_t)ftfe_ccie_irq_handler); + NVIC_ClearPendingIRQ(FTFE_IRQn); + NVIC_EnableIRQ(FTFE_IRQn); + } + + initialized = true; + + return 1; /* synchronous completion. */ +} + +static int32_t uninitialize(void) { + tr_debug("called uninitialize"); + currentCommand = ARM_STORAGE_OPERATION_UNINITIALIZE; + + if (!initialized) { + return ARM_DRIVER_ERROR; + } + + /* Disable the command-completion interrupt. */ + if (asyncOperationsEnabled() && commandCompletionInterruptEnabled()) { + disbleCommandCompletionInterrupt(); + NVIC_DisableIRQ(FTFE_IRQn); + NVIC_ClearPendingIRQ(FTFE_IRQn); + } + + commandCompletionCallback = NULL; + initialized = false; + return 1; /* synchronous completion. */ +} + +static int32_t powerControl(ARM_POWER_STATE state) +{ + tr_debug("called powerControl(%u)", state); + currentCommand = ARM_STORAGE_OPERATION_POWER_CONTROL; + + powerState = state; + return 1; /* signal synchronous completion. */ +} + +static int32_t readData(uint64_t addr, void *data, uint32_t size) +{ + tr_debug("called ReadData(%lu, %lu)", (uint32_t)addr, size); + currentCommand = ARM_STORAGE_OPERATION_READ_DATA; + + if (!initialized) { + return ARM_DRIVER_ERROR; /* illegal */ + } + + /* Argument validation. */ + if ((data == NULL) || (size == 0)) { + return ARM_DRIVER_ERROR_PARAMETER; /* illegal */ + } + if ((getBlock(addr, NULL) != ARM_DRIVER_OK) || (getBlock(addr + size - 1, NULL) != ARM_DRIVER_OK)) { + return ARM_DRIVER_ERROR_PARAMETER; /* illegal address range */ + } + + memcpy(data, (const void *)(uintptr_t)addr, size); + return size; /* signal synchronous completion. */ +} + +static int32_t programData(uint64_t addr, const void *data, uint32_t size) +{ + tr_debug("called ProgramData(%lu, %lu)", (uint32_t)addr, size); + if (!initialized) { + return (int32_t)ARM_DRIVER_ERROR; /* illegal */ + } + + /* argument validation */ + if ((data == NULL) || (size == 0)) { + return ARM_DRIVER_ERROR_PARAMETER; /* illegal */ + } + /* range check */ + if ((getBlock(addr, NULL) != ARM_DRIVER_OK) || (getBlock(addr + size - 1, NULL) != ARM_DRIVER_OK)) { + return ARM_DRIVER_ERROR_PARAMETER; /* illegal address range */ + } + /* alignment */ + if (((addr % PROGRAM_UNIT) != 0) || ((size % PROGRAM_UNIT) != 0)) { + return ARM_DRIVER_ERROR_PARAMETER; + } + /* programmability */ + if (checkForEachBlockInRange(addr, size, blockIsProgrammable) != ARM_DRIVER_OK) { + return ARM_STORAGE_ERROR_NOT_PROGRAMMABLE; + } + + currentCommand = ARM_STORAGE_OPERATION_PROGRAM_DATA; + + if (controllerCurrentlyBusy()) { + /* The user cannot initiate any further FTFE commands until notified that the + * current command has completed.*/ + return ARM_DRIVER_ERROR_BUSY; + } + + sizeofCurrentOperation = size; + amountLeftToOperate = size; + currentOperatingData = data; + currentOperatingStorageAddress = addr; + + clearErrorStatusBits(); + setupNextProgramData(); + return executeCommand(); +} + +static int32_t erase(uint64_t addr, uint32_t size) +{ + tr_debug("called erase(%lu, %lu)", (uint32_t)addr, size); + if (!initialized) { + return (int32_t)ARM_DRIVER_ERROR; /* illegal */ + } + /* argument validation */ + if (size == 0) { + return ARM_DRIVER_ERROR_PARAMETER; + } + /* range check */ + if ((getBlock(addr, NULL) != ARM_DRIVER_OK) || (getBlock(addr + size - 1, NULL) != ARM_DRIVER_OK)) { + return ARM_DRIVER_ERROR_PARAMETER; /* illegal address range */ + } + /* alignment */ + if (((addr % ERASE_UNIT) != 0) || ((size % ERASE_UNIT) != 0)) { + return ARM_DRIVER_ERROR_PARAMETER; + } + /* erasability */ + if (checkForEachBlockInRange(addr, size, blockIsErasable) != ARM_DRIVER_OK) { + return ARM_STORAGE_ERROR_NOT_ERASABLE; + } + + currentCommand = ARM_STORAGE_OPERATION_ERASE; + + currentOperatingStorageAddress = addr; + sizeofCurrentOperation = size; + amountLeftToOperate = size; + + if (controllerCurrentlyBusy()) { + /* The user cannot initiate any further FTFE commands until notified that the + * current command has completed.*/ + return (int32_t)ARM_DRIVER_ERROR_BUSY; + } + + clearErrorStatusBits(); + setupNextErase(); + return executeCommand(); +} + +static int32_t eraseAll(void) +{ + tr_debug("called eraseAll"); + currentCommand = ARM_STORAGE_OPERATION_ERASE_ALL; + + if (!initialized) { + return (int32_t)ARM_DRIVER_ERROR; /* illegal */ + } + + /* unless we are managing all of block 1, we shouldn't allow chip-erase. */ + if ((caps.erase_all != 1) || + ((sizeof(blockTable) / sizeof(ARM_STORAGE_BLOCK)) != 1) || /* there are more than one flash blocks */ + (blockTable[0].addr != BLOCK1_START_ADDR) || + (blockTable[0].size != BLOCK1_SIZE)) { + return ARM_DRIVER_ERROR_UNSUPPORTED; + } + + if (controllerCurrentlyBusy()) { + /* The user cannot initiate any further FTFE commands until notified that the + * current command has completed.*/ + return (int32_t)ARM_DRIVER_ERROR_BUSY; + } + + clearErrorStatusBits(); + + /* Program FCCOB to load the required command parameters. */ + setupEraseBlock(BLOCK1_START_ADDR); + + return executeCommand(); +} + +static ARM_STORAGE_STATUS getStatus(void) +{ + ARM_STORAGE_STATUS status = { + .busy = 0, + .error = 0, + }; + + if (!initialized) { + status.error = 1; + return status; + } + + if (controllerCurrentlyBusy()) { + status.busy = 1; + } else if (failedWithAccessError() || failedWithProtectionError() || failedWithRunTimeError()) { + status.error = 1; + } + return status; +} + +static int32_t getInfo(ARM_STORAGE_INFO *infoP) +{ + memcpy(infoP, &info, sizeof(ARM_STORAGE_INFO)); + + return ARM_DRIVER_OK; +} + +static uint32_t resolveAddress(uint64_t addr) { + return (uint32_t)addr; +} + +int32_t nextBlock(const ARM_STORAGE_BLOCK* prevP, ARM_STORAGE_BLOCK *nextP) +{ + if (prevP == NULL) { + /* fetching the first block (instead of next) */ + if (nextP) { + memcpy(nextP, &blockTable[0], sizeof(ARM_STORAGE_BLOCK)); + } + return ARM_DRIVER_OK; + } + + static const size_t NUM_SEGMENTS = sizeof(blockTable) / sizeof(ARM_STORAGE_BLOCK); + for (size_t index = 0; index < (NUM_SEGMENTS - 1); index++) { + if ((blockTable[index].addr == prevP->addr) && (blockTable[index].size == prevP->size)) { + if (nextP) { + memcpy(nextP, &blockTable[index + 1], sizeof(ARM_STORAGE_BLOCK)); + } + return ARM_DRIVER_OK; + } + } + + if (nextP) { + nextP->addr = ARM_STORAGE_INVALID_OFFSET; + nextP->size = 0; + } + return ARM_DRIVER_ERROR; +} + +int32_t getBlock(uint64_t addr, ARM_STORAGE_BLOCK *blockP) +{ + static const size_t NUM_SEGMENTS = sizeof(blockTable) / sizeof(ARM_STORAGE_BLOCK); + + const ARM_STORAGE_BLOCK *iter = &blockTable[0]; + for (size_t index = 0; index < NUM_SEGMENTS; ++index, ++iter) { + if ((addr >= iter->addr) && (addr < (iter->addr + iter->size))) { + if (blockP) { + memcpy(blockP, iter, sizeof(ARM_STORAGE_BLOCK)); + } + return ARM_DRIVER_OK; + } + } + + if (blockP) { + blockP->addr = ARM_STORAGE_INVALID_OFFSET; + blockP->size = 0; + } + return ARM_DRIVER_ERROR; +} + +ARM_DRIVER_STORAGE ARM_Driver_Storage_(0) = { + .GetVersion = getVersion, + .GetCapabilities = getCapabilities, + .Initialize = initialize, + .Uninitialize = uninitialize, + .PowerControl = powerControl, + .ReadData = readData, + .ProgramData = programData, + .Erase = erase, + .EraseAll = eraseAll, + .GetStatus = getStatus, + .GetInfo = getInfo, + .ResolveAddress = resolveAddress, + .GetNextBlock = nextBlock, + .GetBlock = getBlock +};