/********************************************************************* * @fn initNV * * @brief Initialize the NV flash pages. * * @param none * * @return TRUE */ static uint8 initNV( void ) { osalNvPgHdr_t pgHdr; uint8 oldPg = OSAL_NV_PAGE_NULL; uint8 newPg = OSAL_NV_PAGE_NULL; uint8 findDups = FALSE; uint8 pg; pgRes = OSAL_NV_PAGE_NULL; for ( pg = OSAL_NV_PAGE_BEG; pg <= OSAL_NV_PAGE_END; pg++ ) { HalFlashRead(pg, OSAL_NV_PAGE_HDR_OFFSET, (uint8 *)(&pgHdr), OSAL_NV_HDR_SIZE); if ( pgHdr.active == OSAL_NV_ERASED_ID ) { if ( pgRes == OSAL_NV_PAGE_NULL ) { pgRes = pg; } else { setPageUse( pg, TRUE ); } } else // Page is active. { // If the page is not yet in use, it is the tgt of items from an xfer. if ( pgHdr.inUse == OSAL_NV_ERASED_ID ) { newPg = pg; } // An Xfer from this page was in progress. else if ( pgHdr.xfer != OSAL_NV_ERASED_ID ) { oldPg = pg; } } // Calculate page offset and lost bytes - any "old" item triggers an N^2 re-scan from start. if ( initPage( pg, OSAL_NV_ITEM_NULL, findDups ) != OSAL_NV_ITEM_NULL ) { findDups = TRUE; pg = OSAL_NV_PAGE_BEG-1; continue; } } // for ( pg = OSAL_NV_PAGE_BEG; pg <= OSAL_NV_PAGE_END; pg++ ) /* First the old page is erased, and then the new page is put into use. * So if a transfer was in progress, the new page will always not yet be * marked as in use, since that is the last step to ending a transfer. */ if ( newPg != OSAL_NV_PAGE_NULL ) { /* If there is already a fallow page reserved, keep it and put the newPg in use. * An unfinished compaction will finish to the new reserve page and the old page * will be erased and reserved. */ if ( pgRes != OSAL_NV_PAGE_NULL ) { setPageUse( newPg, TRUE ); } /* If setting old page to 'xfer' failed or board reset before it was effected, there is no way * to know which page was the 'old page' - so just reset all NV pages to start clean. */ else if ( oldPg != OSAL_NV_PAGE_NULL ) { pgRes = newPg; } /* If a page compaction was interrupted and the page being compacted is not * yet erased, then there may be items remaining to xfer before erasing. */ if ( oldPg != OSAL_NV_PAGE_NULL ) { compactPage( oldPg ); } } /* If no page met the criteria to be the reserve page: * - A compactPage() failed or board reset before doing so. * - Perhaps the user changed which Flash pages are dedicated to NV and downloaded the code * without erasing Flash? */ if ( pgRes == OSAL_NV_PAGE_NULL ) { for ( pg = OSAL_NV_PAGE_BEG; pg <= OSAL_NV_PAGE_END; pg++ ) { erasePage( pg ); } initNV(); } return TRUE; }
/********************************************************************* * @fn osal_nv_init * * @brief Initialize NV service. * * @param p - Not used. * * @return none */ void osal_nv_init( void *p ) { (void)p; // Suppress Lint warning. (void)initNV(); // Always returns TRUE after pages have been erased. }