From 3af95e3dd472e342f1d8d108e079e9b552509d23 Mon Sep 17 00:00:00 2001 From: Pavel Kirienko Date: Tue, 5 May 2015 11:31:55 +0300 Subject: [PATCH] Log initialization fix --- .../uc_dynamic_node_id_allocation_server.cpp | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/libuavcan/src/protocol/uc_dynamic_node_id_allocation_server.cpp b/libuavcan/src/protocol/uc_dynamic_node_id_allocation_server.cpp index c358b80f88..55045e505a 100644 --- a/libuavcan/src/protocol/uc_dynamic_node_id_allocation_server.cpp +++ b/libuavcan/src/protocol/uc_dynamic_node_id_allocation_server.cpp @@ -228,10 +228,24 @@ int Log::initEmptyLogStorage() { MarshallingStorageDecorator io(storage_); - // Initializing last index + /* + * Writing the zero entry - it must always be default-initialized + */ + entries_[0] = protocol::dynamic_node_id::server::Entry(); + int res = writeEntryToStorage(0, entries_[0]); + if (res < 0) + { + return res; + } + + /* + * Initializing last index + * Last index must be written AFTER the zero entry, otherwise if the write fails here the storage will be + * left in an inconsistent state. + */ last_index_ = 0; uint32_t stored_index = 0; - int res = io.setAndGetBack(getLastIndexKey(), stored_index); + res = io.setAndGetBack(getLastIndexKey(), stored_index); if (res < 0) { return res; @@ -241,14 +255,6 @@ int Log::initEmptyLogStorage() return -ErrFailure; } - // Writing the zero entry - it must always be default-initialized - entries_[0] = protocol::dynamic_node_id::server::Entry(); - res = writeEntryToStorage(0, entries_[0]); - if (res < 0) - { - return res; - } - return 0; }