From 0b02be925a29357f69abbc9e9a58e7c5aaed2eab Mon Sep 17 00:00:00 2001 From: Patrick Venture Date: Fri, 31 Aug 2018 11:55:55 -0700 Subject: add .clang-format Change-Id: I7c2a527b4751a560703a61fcbe9638b150546af5 Signed-off-by: Patrick Venture --- .clang-format | 99 +++++ app/channel.cpp | 93 ++--- app/channel.hpp | 54 ++- app/watchdog.cpp | 85 +++-- app/watchdog.hpp | 36 +- app/watchdog_service.cpp | 20 +- app/watchdog_service.hpp | 165 ++++---- apphandler.cpp | 320 ++++++++-------- apphandler.h | 24 +- chassishandler.cpp | 730 ++++++++++++++++++------------------ chassishandler.h | 33 +- dcmihandler.cpp | 467 +++++++++++------------ dcmihandler.hpp | 442 +++++++++++----------- elog-errors.hpp | 594 ++++++++++++++--------------- error-HostEvent.hpp | 14 +- fruread.hpp | 3 +- globalhandler.cpp | 21 +- groupext.cpp | 18 +- host-cmd-manager.cpp | 53 ++- host-cmd-manager.hpp | 154 ++++---- host-interface.cpp | 47 +-- host-interface.hpp | 73 ++-- host-ipmid/ipmid-api.h | 67 ++-- host-ipmid/ipmid-host-cmd-utils.hpp | 71 ++-- host-ipmid/ipmid-host-cmd.hpp | 5 +- host-ipmid/oemopenbmc.hpp | 5 +- host-ipmid/oemrouter.hpp | 48 +-- ipmi_fru_info_area.cpp | 195 +++++----- ipmi_fru_info_area.hpp | 5 +- ipmid.cpp | 381 ++++++++++--------- ipmid.hpp | 11 +- ipmisensor.cpp | 546 +++++++++++++++------------ ipmiwhitelist.hpp | 2 +- net.cpp | 5 +- oemrouter.cpp | 59 +-- read_fru_data.cpp | 77 ++-- read_fru_data.hpp | 9 +- sample.cpp | 2 +- selutility.cpp | 118 +++--- selutility.hpp | 71 ++-- sensordatahandler.cpp | 130 +++---- sensordatahandler.hpp | 84 ++--- sensorhandler.cpp | 472 ++++++++++++----------- sensorhandler.h | 169 ++++----- settings.cpp | 29 +- settings.hpp | 56 +-- softoff/mainapp.cpp | 22 +- softoff/softoff.cpp | 51 ++- softoff/softoff.hpp | 241 ++++++------ softoff/test/utest.cpp | 136 ++++--- storageaddsel.cpp | 176 +++++---- storageaddsel.h | 2 +- storagehandler.cpp | 271 +++++++------ storagehandler.h | 82 ++-- systemintfcmds.cpp | 69 ++-- systemintfcmds.h | 12 +- test/oemrouter_unittest.cpp | 76 ++-- test/sample_unittest.cpp | 4 +- testaddsel.cpp | 69 ++-- testit.cpp | 115 +++--- timer.cpp | 17 +- timer.hpp | 156 ++++---- transporthandler.cpp | 464 ++++++++++------------- transporthandler.hpp | 21 +- types.hpp | 102 +++-- utils.cpp | 260 ++++++------- utils.hpp | 168 ++++----- 67 files changed, 4311 insertions(+), 4365 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..ea71ad6 --- /dev/null +++ b/.clang-format @@ -0,0 +1,99 @@ +--- +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlinesLeft: false +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: true +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterClass: true + AfterControlStatement: true + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: true + AfterStruct: true + AfterUnion: true + BeforeCatch: true + BeforeElse: true + IndentBraces: false +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: AfterColon +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +PointerAlignment: Left +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '^[<"](gtest|gmock)' + Priority: 5 + - Regex: '^"config.h"' + Priority: -1 + - Regex: '^".*\.hpp"' + Priority: 1 + - Regex: '^<.*\.h>' + Priority: 2 + - Regex: '^<.*' + Priority: 3 + - Regex: '.*' + Priority: 4 +IndentCaseLabels: true +IndentWidth: 4 +IndentWrappedFunctionNames: true +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +ReflowComments: true +SortIncludes: true +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp11 +TabWidth: 4 +UseTab: Never +... + diff --git a/app/channel.cpp b/app/channel.cpp index 3c011fd..2fee5cc 100644 --- a/app/channel.cpp +++ b/app/channel.cpp @@ -1,17 +1,17 @@ #include "channel.hpp" -#include "types.hpp" + +#include "net.hpp" #include "transporthandler.hpp" +#include "types.hpp" #include "utils.hpp" -#include "net.hpp" -#include -#include #include -#include +#include #include -#include "xyz/openbmc_project/Common/error.hpp" - +#include +#include +#include using namespace phosphor::logging; using namespace sdbusplus::xyz::openbmc_project::Common::Error; @@ -22,8 +22,8 @@ using namespace sdbusplus::xyz::openbmc_project::Common::Error; */ struct GetChannelAccessRequest { - uint8_t channelNumber; //!< Channel number. - uint8_t volatileSetting; //!< Get non-volatile or the volatile setting. + uint8_t channelNumber; //!< Channel number. + uint8_t volatileSetting; //!< Get non-volatile or the volatile setting. } __attribute__((packed)); /** @struct GetChannelAccessResponse @@ -32,20 +32,21 @@ struct GetChannelAccessRequest */ struct GetChannelAccessResponse { - uint8_t settings; //!< Channel settings. - uint8_t privilegeLimit; //!< Channel privilege level limit. + uint8_t settings; //!< Channel settings. + uint8_t privilegeLimit; //!< Channel privilege level limit. } __attribute__((packed)); - ipmi_ret_t ipmi_get_channel_access(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { - auto requestData = reinterpret_cast - (request); + auto requestData = + reinterpret_cast(request); std::vector outPayload(sizeof(GetChannelAccessResponse)); - auto responseData = reinterpret_cast - (outPayload.data()); + auto responseData = + reinterpret_cast(outPayload.data()); /* * The value Eh is used as a way to identify the current channel that @@ -71,7 +72,7 @@ ipmi_ret_t ipmi_get_channel_access(ipmi_netfn_t netfn, ipmi_cmd_t cmd, constexpr auto channelSetting = 0x32; responseData->settings = channelSetting; - //Defaulting the channel privilege to administrator level. + // Defaulting the channel privilege to administrator level. responseData->privilegeLimit = PRIVILEGE_ADMIN; *data_len = outPayload.size(); @@ -91,26 +92,35 @@ ipmi_ret_t ipmi_get_channel_access(ipmi_netfn_t netfn, ipmi_cmd_t cmd, #define IPMI_CHANNEL_MEDIUM_TYPE_OTHER 6 ipmi_ret_t ipmi_app_channel_info(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; - uint8_t resp[] = { - 1, - IPMI_CHANNEL_MEDIUM_TYPE_OTHER, - IPMI_CHANNEL_TYPE_IPMB, - 1,0x41,0xA7,0x00,0,0}; - uint8_t *p = (uint8_t*) request; + uint8_t resp[] = {1, + IPMI_CHANNEL_MEDIUM_TYPE_OTHER, + IPMI_CHANNEL_TYPE_IPMB, + 1, + 0x41, + 0xA7, + 0x00, + 0, + 0}; + uint8_t* p = (uint8_t*)request; int channel = (*p) & CHANNEL_MASK; std::string ethdevice = ipmi::network::ChanneltoEthernet(channel); // The supported channels numbers are those which are configured. // Channel Number E is used as way to identify the current channel // that the command is being is received from. - if (channel != 0xe && ethdevice.empty()) { + if (channel != 0xe && ethdevice.empty()) + { rc = IPMI_CC_PARM_OUT_OF_RANGE; *data_len = 0; - } else { + } + else + { *data_len = sizeof(resp); memcpy(response, resp, *data_len); } @@ -161,7 +171,6 @@ std::vector getCipherRecords() records.push_back(record.value(oem, 0)); records.push_back(record.value(oem, 0) >> 8); records.push_back(record.value(oem, 0) >> 16); - } else { @@ -182,10 +191,9 @@ std::vector getCipherRecords() return records; } -} //namespace cipher +} // namespace cipher -ipmi_ret_t getChannelCipherSuites(ipmi_netfn_t netfn, - ipmi_cmd_t cmd, +ipmi_ret_t getChannelCipherSuites(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, @@ -197,7 +205,6 @@ ipmi_ret_t getChannelCipherSuites(ipmi_netfn_t netfn, auto requestData = reinterpret_cast(request); - if (*data_len < sizeof(GetChannelCipherRequest)) { *data_len = 0; @@ -208,7 +215,7 @@ ipmi_ret_t getChannelCipherSuites(ipmi_netfn_t netfn, // Support only for list algorithms by cipher suite if (cipher::listCipherSuite != - (requestData->listIndex & cipher::listTypeMask)) + (requestData->listIndex & cipher::listTypeMask)) { return IPMI_CC_INVALID_FIELD_REQUEST; } @@ -220,7 +227,7 @@ ipmi_ret_t getChannelCipherSuites(ipmi_netfn_t netfn, records = cipher::getCipherRecords(); recordInit = true; } - catch (const std::exception &e) + catch (const std::exception& e) { return IPMI_CC_UNSPECIFIED_ERROR; } @@ -228,17 +235,16 @@ ipmi_ret_t getChannelCipherSuites(ipmi_netfn_t netfn, // List index(00h-3Fh), 0h selects the first set of 16, 1h selects the next // set of 16 and so on. - auto index = static_cast( - requestData->listIndex & cipher::listIndexMask); + auto index = + static_cast(requestData->listIndex & cipher::listIndexMask); // Calculate the number of record data bytes to be returned. auto start = std::min(index * cipher::respSize, records.size()); - auto end = std::min((index * cipher::respSize) + cipher::respSize, - records.size()); + auto end = + std::min((index * cipher::respSize) + cipher::respSize, records.size()); auto size = end - start; - auto responseData = reinterpret_cast - (response); + auto responseData = reinterpret_cast(response); responseData->channelNumber = cipher::defaultChannelNumber; if (!size) @@ -247,8 +253,7 @@ ipmi_ret_t getChannelCipherSuites(ipmi_netfn_t netfn, } else { - std::copy_n(records.data() + start, - size, + std::copy_n(records.data() + start, size, static_cast(response) + 1); *data_len = size + sizeof(GetChannelCipherRespHeader); } diff --git a/app/channel.hpp b/app/channel.hpp index 79522e4..1b761f8 100644 --- a/app/channel.hpp +++ b/app/channel.hpp @@ -12,13 +12,11 @@ * * @return IPMI_CC_OK on success, non-zero otherwise. */ -ipmi_ret_t ipmi_set_channel_access( - ipmi_netfn_t netfn, - ipmi_cmd_t cmd, - ipmi_request_t request, - ipmi_response_t response, - ipmi_data_len_t data_len, - ipmi_context_t context); +ipmi_ret_t ipmi_set_channel_access(ipmi_netfn_t netfn, ipmi_cmd_t cmd, + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context); /** @brief The get channel access IPMI command. * @@ -31,13 +29,11 @@ ipmi_ret_t ipmi_set_channel_access( * * @return IPMI_CC_OK on success, non-zero otherwise. */ -ipmi_ret_t ipmi_get_channel_access( - ipmi_netfn_t netfn, - ipmi_cmd_t cmd, - ipmi_request_t request, - ipmi_response_t response, - ipmi_data_len_t data_len, - ipmi_context_t context); +ipmi_ret_t ipmi_get_channel_access(ipmi_netfn_t netfn, ipmi_cmd_t cmd, + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context); /** @brief The get channel info IPMI command. * @@ -50,13 +46,11 @@ ipmi_ret_t ipmi_get_channel_access( * * @return IPMI_CC_OK on success, non-zero otherwise. */ -ipmi_ret_t ipmi_app_channel_info( - ipmi_netfn_t netfn, - ipmi_cmd_t cmd, - ipmi_request_t request, - ipmi_response_t response, - ipmi_data_len_t data_len, - ipmi_context_t context); +ipmi_ret_t ipmi_app_channel_info(ipmi_netfn_t netfn, ipmi_cmd_t cmd, + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context); /** @brief Implementation of get channel cipher suites command * @@ -69,8 +63,7 @@ ipmi_ret_t ipmi_app_channel_info( * * @return IPMI_CC_OK on success, non-zero otherwise. */ -ipmi_ret_t getChannelCipherSuites(ipmi_netfn_t netfn, - ipmi_cmd_t cmd, +ipmi_ret_t getChannelCipherSuites(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, @@ -86,8 +79,7 @@ static constexpr auto listIndexMask = 0x3F; static constexpr auto respSize = 16; using Json = nlohmann::json; -static constexpr auto configFile = - "/usr/share/ipmi-providers/cipher_list.json"; +static constexpr auto configFile = "/usr/share/ipmi-providers/cipher_list.json"; static constexpr auto cipher = "cipher"; static constexpr auto stdCipherSuite = 0xC0; static constexpr auto oemCipherSuite = 0xC1; @@ -98,7 +90,7 @@ static constexpr auto integrityTag = 0x40; static constexpr auto conf = "confidentiality"; static constexpr auto confTag = 0x80; -} //namespace cipher +} // namespace cipher /** @struct GetChannelCipherRequest * @@ -106,9 +98,9 @@ static constexpr auto confTag = 0x80; */ struct GetChannelCipherRequest { - uint8_t channelNumber; //!< Channel Number - uint8_t payloadType; //!< Payload type number - uint8_t listIndex; //!< List Index + uint8_t channelNumber; //!< Channel Number + uint8_t payloadType; //!< Payload type number + uint8_t listIndex; //!< List Index } __attribute__((packed)); /** @struct GetChannelCipherRespHeader @@ -117,7 +109,5 @@ struct GetChannelCipherRequest */ struct GetChannelCipherRespHeader { - uint8_t channelNumber; //!< Channel Number + uint8_t channelNumber; //!< Channel Number } __attribute__((packed)); - - diff --git a/app/watchdog.cpp b/app/watchdog.cpp index da8ccf3..ad167df 100644 --- a/app/watchdog.cpp +++ b/app/watchdog.cpp @@ -1,29 +1,29 @@ #include "watchdog.hpp" -#include +#include "ipmid.hpp" +#include "watchdog_service.hpp" + #include -#include + +#include #include +#include #include #include #include -#include "watchdog_service.hpp" #include "host-ipmid/ipmid-api.h" -#include "ipmid.hpp" using phosphor::logging::level; using phosphor::logging::log; using phosphor::logging::report; using sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; -ipmi_ret_t ipmi_app_watchdog_reset( - ipmi_netfn_t netfn, - ipmi_cmd_t cmd, - ipmi_request_t request, - ipmi_response_t response, - ipmi_data_len_t data_len, - ipmi_context_t context) +ipmi_ret_t ipmi_app_watchdog_reset(ipmi_netfn_t netfn, ipmi_cmd_t cmd, + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { // We never return data with this command so immediately get rid of it *data_len = 0; @@ -66,7 +66,8 @@ ipmi_ret_t ipmi_app_watchdog_reset( static constexpr uint8_t wd_dont_stop = 0x1 << 6; static constexpr uint8_t wd_timeout_action_mask = 0x3; -enum class IpmiAction : uint8_t { +enum class IpmiAction : uint8_t +{ None = 0x0, HardReset = 0x1, PowerOff = 0x2, @@ -79,7 +80,7 @@ enum class IpmiAction : uint8_t { */ WatchdogService::Action ipmiActionToWdAction(IpmiAction ipmi_action) { - switch(ipmi_action) + switch (ipmi_action) { case IpmiAction::None: { @@ -104,24 +105,23 @@ WatchdogService::Action ipmiActionToWdAction(IpmiAction ipmi_action) } } -struct wd_set_req { +struct wd_set_req +{ uint8_t timer_use; uint8_t timer_action; - uint8_t pretimeout; // (seconds) + uint8_t pretimeout; // (seconds) uint8_t expire_flags; - uint16_t initial_countdown; // Little Endian (deciseconds) -} __attribute__ ((packed)); + uint16_t initial_countdown; // Little Endian (deciseconds) +} __attribute__((packed)); static_assert(sizeof(wd_set_req) == 6, "wd_set_req has invalid size."); static_assert(sizeof(wd_set_req) <= MAX_IPMI_BUFFER, - "wd_get_res can't fit in request buffer."); + "wd_get_res can't fit in request buffer."); -ipmi_ret_t ipmi_app_watchdog_set( - ipmi_netfn_t netfn, - ipmi_cmd_t cmd, - ipmi_request_t request, - ipmi_response_t response, - ipmi_data_len_t data_len, - ipmi_context_t context) +ipmi_ret_t ipmi_app_watchdog_set(ipmi_netfn_t netfn, ipmi_cmd_t cmd, + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { // Extract the request data if (*data_len < sizeof(wd_set_req)) @@ -144,8 +144,8 @@ ipmi_ret_t ipmi_app_watchdog_set( } // Set the action based on the request - const auto ipmi_action = static_cast( - req.timer_action & wd_timeout_action_mask); + const auto ipmi_action = + static_cast(req.timer_action & wd_timeout_action_mask); wd_service.setExpireAction(ipmiActionToWdAction(ipmi_action)); // Set the new interval and the time remaining deci -> mill seconds @@ -158,7 +158,7 @@ ipmi_ret_t ipmi_app_watchdog_set( return IPMI_CC_OK; } - catch (const std::domain_error &) + catch (const std::domain_error&) { return IPMI_CC_INVALID_FIELD_REQUEST; } @@ -188,7 +188,7 @@ ipmi_ret_t ipmi_app_watchdog_set( */ IpmiAction wdActionToIpmiAction(WatchdogService::Action wd_action) { - switch(wd_action) + switch (wd_action) { case WatchdogService::Action::None: { @@ -216,28 +216,27 @@ IpmiAction wdActionToIpmiAction(WatchdogService::Action wd_action) } } -struct wd_get_res { +struct wd_get_res +{ uint8_t timer_use; uint8_t timer_action; uint8_t pretimeout; uint8_t expire_flags; - uint16_t initial_countdown; // Little Endian (deciseconds) - uint16_t present_countdown; // Little Endian (deciseconds) -} __attribute__ ((packed)); + uint16_t initial_countdown; // Little Endian (deciseconds) + uint16_t present_countdown; // Little Endian (deciseconds) +} __attribute__((packed)); static_assert(sizeof(wd_get_res) == 8, "wd_get_res has invalid size."); static_assert(sizeof(wd_get_res) <= MAX_IPMI_BUFFER, - "wd_get_res can't fit in response buffer."); + "wd_get_res can't fit in response buffer."); static constexpr uint8_t wd_dont_log = 0x1 << 7; static constexpr uint8_t wd_running = 0x1 << 6; -ipmi_ret_t ipmi_app_watchdog_get( - ipmi_netfn_t netfn, - ipmi_cmd_t cmd, - ipmi_request_t request, - ipmi_response_t response, - ipmi_data_len_t data_len, - ipmi_context_t context) +ipmi_ret_t ipmi_app_watchdog_get(ipmi_netfn_t netfn, ipmi_cmd_t cmd, + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { // Assume we will fail and send no data outside the return code *data_len = 0; @@ -250,8 +249,8 @@ ipmi_ret_t ipmi_app_watchdog_get( // Build and return the response wd_get_res res; res.timer_use = wd_dont_log; - res.timer_action = static_cast( - wdActionToIpmiAction(wd_prop.expireAction)); + res.timer_action = + static_cast(wdActionToIpmiAction(wd_prop.expireAction)); if (wd_prop.enabled) { res.timer_use |= wd_running; diff --git a/app/watchdog.hpp b/app/watchdog.hpp index 5359a33..507695f 100644 --- a/app/watchdog.hpp +++ b/app/watchdog.hpp @@ -13,13 +13,11 @@ * * @return IPMI_CC_OK on success, an IPMI error code otherwise. */ -ipmi_ret_t ipmi_app_watchdog_reset( - ipmi_netfn_t netfn, - ipmi_cmd_t cmd, - ipmi_request_t request, - ipmi_response_t response, - ipmi_data_len_t data_len, - ipmi_context_t context); +ipmi_ret_t ipmi_app_watchdog_reset(ipmi_netfn_t netfn, ipmi_cmd_t cmd, + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context); /** @brief The SET watchdog IPMI command. * @@ -32,13 +30,11 @@ ipmi_ret_t ipmi_app_watchdog_reset( * * @return IPMI_CC_OK on success, an IPMI error code otherwise. */ -ipmi_ret_t ipmi_app_watchdog_set( - ipmi_netfn_t netfn, - ipmi_cmd_t cmd, - ipmi_request_t request, - ipmi_response_t response, - ipmi_data_len_t data_len, - ipmi_context_t context); +ipmi_ret_t ipmi_app_watchdog_set(ipmi_netfn_t netfn, ipmi_cmd_t cmd, + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context); /** @brief The GET watchdog IPMI command. * @param[in] netfn @@ -50,10 +46,8 @@ ipmi_ret_t ipmi_app_watchdog_set( * * @return IPMI_CC_OK on success, an IPMI error code otherwise. */ -ipmi_ret_t ipmi_app_watchdog_get( - ipmi_netfn_t netfn, - ipmi_cmd_t cmd, - ipmi_request_t request, - ipmi_response_t response, - ipmi_data_len_t data_len, - ipmi_context_t context); +ipmi_ret_t ipmi_app_watchdog_get(ipmi_netfn_t netfn, ipmi_cmd_t cmd, + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context); diff --git a/app/watchdog_service.cpp b/app/watchdog_service.cpp index 6c9edd4..923264b 100644 --- a/app/watchdog_service.cpp +++ b/app/watchdog_service.cpp @@ -1,8 +1,8 @@ #include "watchdog_service.hpp" #include -#include #include +#include #include #include #include @@ -13,8 +13,8 @@ #include "host-ipmid/ipmid-api.h" -using phosphor::logging::entry; using phosphor::logging::elog; +using phosphor::logging::entry; using phosphor::logging::level; using phosphor::logging::log; using sdbusplus::message::variant_ns::get; @@ -29,16 +29,14 @@ static constexpr char prop_intf[] = "org.freedesktop.DBus.Properties"; ipmi::ServiceCache WatchdogService::wd_service(wd_intf, wd_path); -WatchdogService::WatchdogService() - : bus(ipmid_get_sd_bus_connection()) +WatchdogService::WatchdogService() : bus(ipmid_get_sd_bus_connection()) { } void WatchdogService::resetTimeRemaining(bool enableWatchdog) { bool wasValid = wd_service.isValid(bus); - auto request = wd_service.newMethodCall( - bus, wd_intf, "ResetTimeRemaining"); + auto request = wd_service.newMethodCall(bus, wd_intf, "ResetTimeRemaining"); request.append(enableWatchdog); auto response = bus.call(request); if (response.is_method_error()) @@ -50,8 +48,8 @@ void WatchdogService::resetTimeRemaining(bool enableWatchdog) return resetTimeRemaining(enableWatchdog); } log( - "WatchdogService: Method error resetting time remaining", - entry("ENABLE_WATCHDOG=%d", !!enableWatchdog)); + "WatchdogService: Method error resetting time remaining", + entry("ENABLE_WATCHDOG=%d", !!enableWatchdog)); elog(); } } @@ -81,7 +79,7 @@ WatchdogService::Properties WatchdogService::getProperties() wd_prop.initialized = get(properties.at("Initialized")); wd_prop.enabled = get(properties.at("Enabled")); wd_prop.expireAction = Watchdog::convertActionFromString( - get(properties.at("ExpireAction"))); + get(properties.at("ExpireAction"))); wd_prop.interval = get(properties.at("Interval")); wd_prop.timeRemaining = get(properties.at("TimeRemaining")); return wd_prop; @@ -97,7 +95,7 @@ WatchdogService::Properties WatchdogService::getProperties() // Needed instead of elog() since the compiler can't // deduce the that elog<>() always throws throw std::runtime_error( - "WatchdogService: Should not reach end of getProperties"); + "WatchdogService: Should not reach end of getProperties"); } template @@ -137,7 +135,7 @@ T WatchdogService::getProperty(const std::string& key) // Needed instead of elog() since the compiler can't // deduce the that elog<>() always throws throw std::runtime_error( - "WatchdogService: Should not reach end of getProperty"); + "WatchdogService: Should not reach end of getProperty"); } template diff --git a/app/watchdog_service.hpp b/app/watchdog_service.hpp index dfc913a..8056fb7 100644 --- a/app/watchdog_service.hpp +++ b/app/watchdog_service.hpp @@ -1,104 +1,107 @@ #pragma once +#include "utils.hpp" + #include #include -#include "utils.hpp" - /** @class WatchdogService * @brief Access to the running OpenBMC watchdog implementation. * @details Easy accessor for servers that implement the * xyz.openbmc_project.State.Watchdog DBus API. */ -class WatchdogService { - public: - WatchdogService(); +class WatchdogService +{ + public: + WatchdogService(); - using Action = sdbusplus::xyz::openbmc_project::State::server::Watchdog::Action; + using Action = + sdbusplus::xyz::openbmc_project::State::server::Watchdog::Action; - /** @brief Resets the time remaining on the watchdog. - * Equivalent to setTimeRemaining(getInterval()). - * Optionally enables the watchdog. - * - * @param[in] enableWatchdog - Should the call also enable the watchdog - */ - void resetTimeRemaining(bool enableWatchdog); + /** @brief Resets the time remaining on the watchdog. + * Equivalent to setTimeRemaining(getInterval()). + * Optionally enables the watchdog. + * + * @param[in] enableWatchdog - Should the call also enable the watchdog + */ + void resetTimeRemaining(bool enableWatchdog); - /** @brief Contains a copy of the properties enumerated by the - * watchdog service. - */ - struct Properties { - bool initialized; - bool enabled; - Action expireAction; - uint64_t interval; - uint64_t timeRemaining; - }; + /** @brief Contains a copy of the properties enumerated by the + * watchdog service. + */ + struct Properties + { + bool initialized; + bool enabled; + Action expireAction; + uint64_t interval; + uint64_t timeRemaining; + }; - /** @brief Retrieves a copy of the currently set properties on the - * host watchdog - * - * @return A populated WatchdogProperties struct - */ - Properties getProperties(); + /** @brief Retrieves a copy of the currently set properties on the + * host watchdog + * + * @return A populated WatchdogProperties struct + */ + Properties getProperties(); - /** @brief Get the value of the initialized property on the host - * watchdog - * - * @return The value of the property - */ - bool getInitialized(); + /** @brief Get the value of the initialized property on the host + * watchdog + * + * @return The value of the property + */ + bool getInitialized(); - /** @brief Sets the value of the initialized property on the host - * watchdog - * - * @param[in] initialized - The new initializedvalue - */ - void setInitialized(bool initialized); + /** @brief Sets the value of the initialized property on the host + * watchdog + * + * @param[in] initialized - The new initializedvalue + */ + void setInitialized(bool initialized); - /** @brief Sets the value of the enabled property on the host watchdog - * - * @param[in] enabled - The new enabled value - */ - void setEnabled(bool enabled); + /** @brief Sets the value of the enabled property on the host watchdog + * + * @param[in] enabled - The new enabled value + */ + void setEnabled(bool enabled); - /** @brief Sets the value of the expireAction property on the host watchdog - * - * @param[in] expireAction - The new expireAction value - */ - void setExpireAction(Action expireAction); + /** @brief Sets the value of the expireAction property on the host watchdog + * + * @param[in] expireAction - The new expireAction value + */ + void setExpireAction(Action expireAction); - /** @brief Sets the value of the interval property on the host watchdog - * - * @param[in] interval - The new interval value - */ - void setInterval(uint64_t interval); + /** @brief Sets the value of the interval property on the host watchdog + * + * @param[in] interval - The new interval value + */ + void setInterval(uint64_t interval); - /** @brief Sets the value of the timeRemaining property on the host - * watchdog - * - * @param[in] timeRemaining - The new timeRemaining value - */ - void setTimeRemaining(uint64_t timeRemaining); + /** @brief Sets the value of the timeRemaining property on the host + * watchdog + * + * @param[in] timeRemaining - The new timeRemaining value + */ + void setTimeRemaining(uint64_t timeRemaining); - private: - /** @brief sdbusplus handle */ - sdbusplus::bus::bus bus; - /** @brief The name of the mapped host watchdog service */ - static ipmi::ServiceCache wd_service; + private: + /** @brief sdbusplus handle */ + sdbusplus::bus::bus bus; + /** @brief The name of the mapped host watchdog service */ + static ipmi::ServiceCache wd_service; - /** @brief Gets the value of the property on the host watchdog - * - * @param[in] key - The name of the property - * @return The value of the property - */ - template - T getProperty(const std::string& key); + /** @brief Gets the value of the property on the host watchdog + * + * @param[in] key - The name of the property + * @return The value of the property + */ + template + T getProperty(const std::string& key); - /** @brief Sets the value of the property on the host watchdog - * - * @param[in] key - The name of the property - * @param[in] val - The new value - */ - template - void setProperty(const std::string& key, const T& val); + /** @brief Sets the value of the property on the host watchdog + * + * @param[in] key - The name of the property + * @param[in] val - The new value + */ + template + void setProperty(const std::string& key, const T& val); }; diff --git a/apphandler.cpp b/apphandler.cpp index 05da67e..b089331 100644 --- a/apphandler.cpp +++ b/apphandler.cpp @@ -1,43 +1,46 @@ #include "apphandler.h" -#include "app/channel.hpp" -#include "app/watchdog.hpp" + +#include +#include +#include +#include +#include + #include "host-ipmid/ipmid-api.h" -#include "ipmid.hpp" -#include "nlohmann/json.hpp" -#include "types.hpp" -#include "utils.hpp" #if __has_include() #include #elif __has_include() #include -namespace std { - // splice experimental::filesystem into std - namespace filesystem = std::experimental::filesystem; -} +namespace std +{ +// splice experimental::filesystem into std +namespace filesystem = std::experimental::filesystem; +} // namespace std #else -# error filesystem not available +#error filesystem not available #endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "app/channel.hpp" +#include "app/watchdog.hpp" +#include "ipmid.hpp" +#include "nlohmann/json.hpp" #include "transporthandler.hpp" +#include "types.hpp" +#include "utils.hpp" -#include +#include +#include +#include #include -#include "xyz/openbmc_project/Common/error.hpp" -#include "xyz/openbmc_project/Software/Version/server.hpp" -#include "xyz/openbmc_project/Software/Activation/server.hpp" +#include +#include +#include +#include +#include +#include -extern sd_bus *bus; +extern sd_bus* bus; constexpr auto bmc_interface = "xyz.openbmc_project.Inventory.Item.Bmc"; constexpr auto bmc_guid_interface = "xyz.openbmc_project.Common.UUID"; @@ -46,8 +49,7 @@ constexpr auto bmc_guid_len = 16; static constexpr auto redundancyIntf = "xyz.openbmc_project.Software.RedundancyPriority"; -static constexpr auto versionIntf = - "xyz.openbmc_project.Software.Version"; +static constexpr auto versionIntf = "xyz.openbmc_project.Software.Version"; static constexpr auto activationIntf = "xyz.openbmc_project.Software.Activation"; static constexpr auto softwareRoot = "/xyz/openbmc_project/software"; @@ -64,15 +66,15 @@ namespace fs = std::filesystem; // Offset in get device id command. typedef struct { - uint8_t id; - uint8_t revision; - uint8_t fw[2]; - uint8_t ipmi_ver; - uint8_t addn_dev_support; - uint8_t manuf_id[3]; - uint8_t prod_id[2]; - uint8_t aux[4]; -}__attribute__((packed)) ipmi_device_id_t; + uint8_t id; + uint8_t revision; + uint8_t fw[2]; + uint8_t ipmi_ver; + uint8_t addn_dev_support; + uint8_t manuf_id[3]; + uint8_t prod_id[2]; + uint8_t aux[4]; +} __attribute__((packed)) ipmi_device_id_t; /** * @brief Returns the Version info from primary s/w object @@ -90,8 +92,8 @@ std::string getActiveSoftwareVersionInfo() sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; std::string revision{}; - auto objectTree = ipmi::getAllDbusObjects(bus, softwareRoot, redundancyIntf, - ""); + auto objectTree = + ipmi::getAllDbusObjects(bus, softwareRoot, redundancyIntf, ""); if (objectTree.empty()) { log("No Obj has implemented the s/w redundancy interface", @@ -149,10 +151,11 @@ std::string getActiveSoftwareVersionInfo() return revision; } - ipmi_ret_t ipmi_app_set_acpi_power_state(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; *data_len = 0; @@ -183,16 +186,16 @@ typedef struct /* Additional details : If the option group exists it will force Auxiliary */ /* Firmware Revision Information 4th byte to 1 indicating the build was */ /* derived with additional edits */ -int convert_version(const char * p, rev_t *rev) +int convert_version(const char* p, rev_t* rev) { std::string s(p); std::string token; uint16_t commits; - auto location = s.find_first_of('v'); + auto location = s.find_first_of('v'); if (location != std::string::npos) { - s = s.substr(location+1); + s = s.substr(location + 1); } if (!s.empty()) @@ -200,9 +203,9 @@ int convert_version(const char * p, rev_t *rev) location = s.find_first_of("."); if (location != std::string::npos) { - rev->major = static_cast( - std::stoi(s.substr(0, location), 0, 16)); - token = s.substr(location+1); + rev->major = + static_cast(std::stoi(s.substr(0, location), 0, 16)); + token = s.substr(location + 1); } if (!token.empty()) @@ -211,8 +214,8 @@ int convert_version(const char * p, rev_t *rev) if (location != std::string::npos) { rev->minor = static_cast( - std::stoi(token.substr(0, location), 0, 16)); - token = token.substr(location+1); + std::stoi(token.substr(0, location), 0, 16)); + token = token.substr(location + 1); } } @@ -222,43 +225,46 @@ int convert_version(const char * p, rev_t *rev) if (!token.empty()) { commits = std::stoi(token.substr(0, location), 0, 16); - rev->d[0] = (commits>>8) | (commits<<8); + rev->d[0] = (commits >> 8) | (commits << 8); // commit number we skip location = token.find_first_of(".-"); if (location != std::string::npos) { - token = token.substr(location+1); + token = token.substr(location + 1); } } - else { + else + { rev->d[0] = 0; } if (location != std::string::npos) { - token = token.substr(location+1); + token = token.substr(location + 1); } // Any value of the optional parameter forces it to 1 location = token.find_first_of(".-"); if (location != std::string::npos) { - token = token.substr(location+1); + token = token.substr(location + 1); } commits = (!token.empty()) ? 1 : 0; - //We do this operation to get this displayed in least significant bytes - //of ipmitool device id command. - rev->d[1] = (commits>>8) | (commits<<8); + // We do this operation to get this displayed in least significant bytes + // of ipmitool device id command. + rev->d[1] = (commits >> 8) | (commits << 8); } return 0; } ipmi_ret_t ipmi_app_get_device_id(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; int r = -1; @@ -282,7 +288,8 @@ ipmi_ret_t ipmi_app_get_device_id(ipmi_netfn_t netfn, ipmi_cmd_t cmd, log(e.what()); } - if( r >= 0 ) { + if (r >= 0) + { // bit7 identifies if the device is available // 0=normal operation // 1=device firmware, SDR update, @@ -317,7 +324,7 @@ ipmi_ret_t ipmi_app_get_device_id(ipmi_netfn_t netfn, ipmi_cmd_t cmd, dev_id.aux[1] = data.value("aux", 0) >> 16; dev_id.aux[0] = data.value("aux", 0) >> 24; - //Don't read the file every time if successful + // Don't read the file every time if successful dev_id_initialized = true; } else @@ -340,8 +347,10 @@ ipmi_ret_t ipmi_app_get_device_id(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } ipmi_ret_t ipmi_app_get_self_test_results(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; @@ -379,30 +388,32 @@ ipmi_ret_t ipmi_app_get_self_test_results(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } ipmi_ret_t ipmi_app_get_device_guid(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { - const char *objname = "/org/openbmc/control/chassis0"; - const char *iface = "org.freedesktop.DBus.Properties"; - const char *chassis_iface = "org.openbmc.control.Chassis"; - sd_bus_message *reply = NULL; + const char* objname = "/org/openbmc/control/chassis0"; + const char* iface = "org.freedesktop.DBus.Properties"; + const char* chassis_iface = "org.openbmc.control.Chassis"; + sd_bus_message* reply = NULL; sd_bus_error error = SD_BUS_ERROR_NULL; int r = 0; - char *uuid = NULL; - char *busname = NULL; + char* uuid = NULL; + char* busname = NULL; // UUID is in RFC4122 format. Ex: 61a39523-78f2-11e5-9862-e6402cfc3223 // Per IPMI Spec 2.0 need to convert to 16 hex bytes and reverse the byte // order // Ex: 0x2332fc2c40e66298e511f2782395a361 - const int resp_size = 16; // Response is 16 hex bytes per IPMI Spec + const int resp_size = 16; // Response is 16 hex bytes per IPMI Spec uint8_t resp_uuid[resp_size]; // Array to hold the formatted response // Point resp end of array to save in reverse order - int resp_loc = resp_size-1; + int resp_loc = resp_size - 1; int i = 0; - char *tokptr = NULL; - char *id_octet = NULL; + char* tokptr = NULL; + char* id_octet = NULL; // Status code. ipmi_ret_t rc = IPMI_CC_OK; @@ -410,19 +421,17 @@ ipmi_ret_t ipmi_app_get_device_guid(ipmi_netfn_t netfn, ipmi_cmd_t cmd, // Call Get properties method with the interface and property name r = mapper_get_service(bus, objname, &busname); - if (r < 0) { - log("Failed to get bus name", - entry("BUS=%s", objname), + if (r < 0) + { + log("Failed to get bus name", entry("BUS=%s", objname), entry("ERRNO=0x%X", -r)); goto finish; } - r = sd_bus_call_method(bus,busname,objname,iface, - "Get",&error, &reply, "ss", - chassis_iface, "uuid"); + r = sd_bus_call_method(bus, busname, objname, iface, "Get", &error, &reply, + "ss", chassis_iface, "uuid"); if (r < 0) { - log("Failed to call Get Method", - entry("ERRNO=0x%X", -r)); + log("Failed to call Get Method", entry("ERRNO=0x%X", -r)); rc = IPMI_CC_UNSPECIFIED_ERROR; goto finish; } @@ -430,8 +439,7 @@ ipmi_ret_t ipmi_app_get_device_guid(ipmi_netfn_t netfn, ipmi_cmd_t cmd, r = sd_bus_message_read(reply, "v", "s", &uuid); if (r < 0 || uuid == NULL) { - log("Failed to get a response", - entry("ERRNO=0x%X", -r)); + log("Failed to get a response", entry("ERRNO=0x%X", -r)); rc = IPMI_CC_RESPONSE_ERROR; goto finish; } @@ -443,8 +451,7 @@ ipmi_ret_t ipmi_app_get_device_guid(ipmi_netfn_t netfn, ipmi_cmd_t cmd, if (id_octet == NULL) { // Error - log("Unexpected UUID format", - entry("UUID=%s", uuid)); + log("Unexpected UUID format", entry("UUID=%s", uuid)); rc = IPMI_CC_RESPONSE_ERROR; goto finish; } @@ -453,9 +460,9 @@ ipmi_ret_t ipmi_app_get_device_guid(ipmi_netfn_t netfn, ipmi_cmd_t cmd, { // Calculate the octet string size since it varies // Divide it by 2 for the array size since 1 byte is built from 2 chars - int tmp_size = strlen(id_octet)/2; + int tmp_size = strlen(id_octet) / 2; - for(i = 0; i < tmp_size; i++) + for (i = 0; i < tmp_size; i++) { // Holder of the 2 chars that will become a byte char tmp_array[3] = {0}; @@ -465,9 +472,9 @@ ipmi_ret_t ipmi_app_get_device_guid(ipmi_netfn_t netfn, ipmi_cmd_t cmd, // Copy end to first memcpy((void*)&resp_uuid[resp_loc], &resp_byte, 1); resp_loc--; - id_octet+=2; // Finished with the 2 chars, advance + id_octet += 2; // Finished with the 2 chars, advance } - id_octet=strtok_r(NULL, "-", &tokptr); // Get next octet + id_octet = strtok_r(NULL, "-", &tokptr); // Get next octet } // Data length @@ -485,8 +492,10 @@ finish: } ipmi_ret_t ipmi_app_get_bt_capabilities(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { // Status code. @@ -494,7 +503,8 @@ ipmi_ret_t ipmi_app_get_bt_capabilities(ipmi_netfn_t netfn, ipmi_cmd_t cmd, // Per IPMI 2.0 spec, the input and output buffer size must be the max // buffer size minus one byte to allocate space for the length byte. - uint8_t str[] = {0x01, MAX_IPMI_BUFFER-1, MAX_IPMI_BUFFER-1, 0x0A, 0x01}; + uint8_t str[] = {0x01, MAX_IPMI_BUFFER - 1, MAX_IPMI_BUFFER - 1, 0x0A, + 0x01}; // Data length *data_len = sizeof(str); @@ -506,8 +516,10 @@ ipmi_ret_t ipmi_app_get_bt_capabilities(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } ipmi_ret_t ipmi_app_wildcard_handler(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { // Status code. ipmi_ret_t rc = IPMI_CC_INVALID; @@ -521,8 +533,10 @@ ipmi_ret_t ipmi_app_wildcard_handler(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } ipmi_ret_t ipmi_app_get_sys_guid(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; @@ -536,23 +550,23 @@ ipmi_ret_t ipmi_app_get_sys_guid(ipmi_netfn_t netfn, ipmi_cmd_t cmd, // Read UUID property value from bmcObject // UUID is in RFC4122 format Ex: 61a39523-78f2-11e5-9862-e6402cfc3223 - auto variant = ipmi::getDbusProperty( - bus, bmcObject.second, bmcObject.first, bmc_guid_interface, - bmc_guid_property); + auto variant = + ipmi::getDbusProperty(bus, bmcObject.second, bmcObject.first, + bmc_guid_interface, bmc_guid_property); std::string guidProp = variant.get(); // Erase "-" characters from the property value guidProp.erase(std::remove(guidProp.begin(), guidProp.end(), '-'), - guidProp.end()); + guidProp.end()); auto guidPropLen = guidProp.length(); // Validate UUID data // Divide by 2 as 1 byte is built from 2 chars - if ( (guidPropLen <=0) || ((guidPropLen/2) != bmc_guid_len) ) + if ((guidPropLen <= 0) || ((guidPropLen / 2) != bmc_guid_len)) { log("Invalid UUID property value", - entry("UUID_LENGTH=%d", guidPropLen)); + entry("UUID_LENGTH=%d", guidPropLen)); return IPMI_CC_RESPONSE_ERROR; } @@ -564,10 +578,10 @@ ipmi_ret_t ipmi_app_get_sys_guid(ipmi_netfn_t netfn, ipmi_cmd_t cmd, // Ticket raised: https://sourceforge.net/p/ipmitool/bugs/501/ uint8_t respGuid[bmc_guid_len]; for (size_t i = 0, respLoc = (bmc_guid_len - 1); - i < guidPropLen && respLoc >= 0; i += 2, respLoc--) + i < guidPropLen && respLoc >= 0; i += 2, respLoc--) { auto value = static_cast( - std::stoi(guidProp.substr(i, 2).c_str(), NULL, 16)); + std::stoi(guidProp.substr(i, 2).c_str(), NULL, 16)); respGuid[respLoc] = value; } @@ -588,95 +602,55 @@ ipmi_ret_t ipmi_app_get_sys_guid(ipmi_netfn_t netfn, ipmi_cmd_t cmd, void register_netfn_app_functions() { // - ipmi_register_callback(NETFUN_APP, - IPMI_CMD_GET_CAP_BIT, - NULL, - ipmi_app_get_bt_capabilities, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_CAP_BIT, NULL, + ipmi_app_get_bt_capabilities, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_APP, - IPMI_CMD_WILDCARD, - NULL, - ipmi_app_wildcard_handler, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_APP, IPMI_CMD_WILDCARD, NULL, + ipmi_app_wildcard_handler, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_APP, - IPMI_CMD_RESET_WD, - NULL, - ipmi_app_watchdog_reset, - PRIVILEGE_OPERATOR); + ipmi_register_callback(NETFUN_APP, IPMI_CMD_RESET_WD, NULL, + ipmi_app_watchdog_reset, PRIVILEGE_OPERATOR); // - ipmi_register_callback(NETFUN_APP, - IPMI_CMD_SET_WD, - NULL, - ipmi_app_watchdog_set, - PRIVILEGE_OPERATOR); + ipmi_register_callback(NETFUN_APP, IPMI_CMD_SET_WD, NULL, + ipmi_app_watchdog_set, PRIVILEGE_OPERATOR); // - ipmi_register_callback(NETFUN_APP, - IPMI_CMD_GET_WD, - NULL, - ipmi_app_watchdog_get, - PRIVILEGE_OPERATOR); + ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_WD, NULL, + ipmi_app_watchdog_get, PRIVILEGE_OPERATOR); // - ipmi_register_callback(NETFUN_APP, - IPMI_CMD_GET_DEVICE_ID, - NULL, - ipmi_app_get_device_id, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_DEVICE_ID, NULL, + ipmi_app_get_device_id, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_APP, - IPMI_CMD_GET_SELF_TEST_RESULTS, - NULL, - ipmi_app_get_self_test_results, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_SELF_TEST_RESULTS, NULL, + ipmi_app_get_self_test_results, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_APP, - IPMI_CMD_GET_DEVICE_GUID, - NULL, - ipmi_app_get_device_guid, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_DEVICE_GUID, NULL, + ipmi_app_get_device_guid, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_APP, - IPMI_CMD_SET_ACPI, - NULL, - ipmi_app_set_acpi_power_state, - PRIVILEGE_ADMIN); + ipmi_register_callback(NETFUN_APP, IPMI_CMD_SET_ACPI, NULL, + ipmi_app_set_acpi_power_state, PRIVILEGE_ADMIN); // - ipmi_register_callback(NETFUN_APP, - IPMI_CMD_GET_CHANNEL_ACCESS, - NULL, - ipmi_get_channel_access, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_CHANNEL_ACCESS, NULL, + ipmi_get_channel_access, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_APP, - IPMI_CMD_GET_CHAN_INFO, - NULL, - ipmi_app_channel_info, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_CHAN_INFO, NULL, + ipmi_app_channel_info, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_APP, - IPMI_CMD_GET_SYS_GUID, - NULL, - ipmi_app_get_sys_guid, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_SYS_GUID, NULL, + ipmi_app_get_sys_guid, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_APP, - IPMI_CMD_GET_CHAN_CIPHER_SUITES, - NULL, - getChannelCipherSuites, - PRIVILEGE_CALLBACK); + ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_CHAN_CIPHER_SUITES, NULL, + getChannelCipherSuites, PRIVILEGE_CALLBACK); return; } - diff --git a/apphandler.h b/apphandler.h index 7ed7bcd..db2d07c 100644 --- a/apphandler.h +++ b/apphandler.h @@ -7,18 +7,18 @@ enum ipmi_netfn_app_cmds { // Get capability bits - IPMI_CMD_GET_DEVICE_ID = 0x01, - IPMI_CMD_GET_SELF_TEST_RESULTS = 0x04, - IPMI_CMD_SET_ACPI = 0x06, - IPMI_CMD_GET_DEVICE_GUID = 0x08, - IPMI_CMD_RESET_WD = 0x22, - IPMI_CMD_SET_WD = 0x24, - IPMI_CMD_GET_WD = 0x25, - IPMI_CMD_GET_CAP_BIT = 0x36, - IPMI_CMD_GET_SYS_GUID = 0x37, - IPMI_CMD_SET_CHAN_ACCESS = 0x40, - IPMI_CMD_GET_CHANNEL_ACCESS = 0x41, - IPMI_CMD_GET_CHAN_INFO = 0x42, + IPMI_CMD_GET_DEVICE_ID = 0x01, + IPMI_CMD_GET_SELF_TEST_RESULTS = 0x04, + IPMI_CMD_SET_ACPI = 0x06, + IPMI_CMD_GET_DEVICE_GUID = 0x08, + IPMI_CMD_RESET_WD = 0x22, + IPMI_CMD_SET_WD = 0x24, + IPMI_CMD_GET_WD = 0x25, + IPMI_CMD_GET_CAP_BIT = 0x36, + IPMI_CMD_GET_SYS_GUID = 0x37, + IPMI_CMD_SET_CHAN_ACCESS = 0x40, + IPMI_CMD_GET_CHANNEL_ACCESS = 0x41, + IPMI_CMD_GET_CHAN_INFO = 0x42, IPMI_CMD_GET_CHAN_CIPHER_SUITES = 0x54, }; diff --git a/chassishandler.cpp b/chassishandler.cpp index 2ad9948..6002e7a 100644 --- a/chassishandler.cpp +++ b/chassishandler.cpp @@ -1,72 +1,78 @@ #include "chassishandler.h" -#include "host-ipmid/ipmid-api.h" -#include "types.hpp" + #include "ipmid.hpp" #include "settings.hpp" +#include "types.hpp" #include "utils.hpp" -#include -#include -#include -#include #include -#include +#include #include +#include +#include +#include +#include +#include #include -#include -#include + #include +#include #include #include -#include +#include + +#include "host-ipmid/ipmid-api.h" #if __has_include() #include #elif __has_include() #include -namespace std { - // splice experimental::filesystem into std - namespace filesystem = std::experimental::filesystem; -} +namespace std +{ +// splice experimental::filesystem into std +namespace filesystem = std::experimental::filesystem; +} // namespace std #else -# error filesystem not available +#error filesystem not available #endif -#include -#include +#include "config.h" -#include -#include -#include -#include "xyz/openbmc_project/Common/error.hpp" +#include "timer.hpp" +#include +#include +#include #include #include -#include +#include +#include #include +#include #include +#include #include - -#include "config.h" -#include "timer.hpp" -//Defines -#define SET_PARM_VERSION 0x01 -#define SET_PARM_BOOT_FLAGS_PERMANENT 0x40 //boot flags data1 7th bit on -#define SET_PARM_BOOT_FLAGS_VALID_ONE_TIME 0x80 //boot flags data1 8th bit on -#define SET_PARM_BOOT_FLAGS_VALID_PERMANENT 0xC0 //boot flags data1 7 & 8 bit on +// Defines +#define SET_PARM_VERSION 0x01 +#define SET_PARM_BOOT_FLAGS_PERMANENT 0x40 // boot flags data1 7th bit on +#define SET_PARM_BOOT_FLAGS_VALID_ONE_TIME 0x80 // boot flags data1 8th bit on +#define SET_PARM_BOOT_FLAGS_VALID_PERMANENT \ + 0xC0 // boot flags data1 7 & 8 bit + // on std::unique_ptr identifyTimer = nullptr; -constexpr size_t SIZE_MAC = 18; -constexpr size_t SIZE_BOOT_OPTION = (uint8_t)BootOptionResponseSize:: - OPAL_NETWORK_SETTINGS;//Maximum size of the boot option parametrs +constexpr size_t SIZE_MAC = 18; +constexpr size_t SIZE_BOOT_OPTION = (uint8_t) + BootOptionResponseSize::OPAL_NETWORK_SETTINGS; // Maximum size of the boot + // option parametrs constexpr size_t SIZE_PREFIX = 7; constexpr size_t MAX_PREFIX_VALUE = 32; constexpr size_t SIZE_COOKIE = 4; constexpr size_t SIZE_VERSION = 2; constexpr size_t DEFAULT_IDENTIFY_TIME_OUT = 15; -//PetiBoot-Specific +// PetiBoot-Specific static constexpr uint8_t net_conf_initial_bytes[] = {0x80, 0x21, 0x70, 0x62, - 0x21, 0x00, 0x01, 0x06}; + 0x21, 0x00, 0x01, 0x06}; static constexpr size_t COOKIE_OFFSET = 1; static constexpr size_t VERSION_OFFSET = 5; @@ -84,10 +90,10 @@ void register_netfn_chassis_functions() __attribute__((constructor)); // Host settings in dbus // Service name should be referenced by connection name got via object mapper -const char *settings_object_name = "/org/openbmc/settings/host0"; -const char *settings_intf_name = "org.freedesktop.DBus.Properties"; -const char *host_intf_name = "org.openbmc.settings.Host"; -const char *identify_led_object_name = +const char* settings_object_name = "/org/openbmc/settings/host0"; +const char* settings_intf_name = "org.freedesktop.DBus.Properties"; +const char* host_intf_name = "org.openbmc.settings.Host"; +const char* identify_led_object_name = "/xyz/openbmc_project/led/groups/enclosure_identify"; constexpr auto SETTINGS_ROOT = "/"; @@ -98,7 +104,7 @@ constexpr auto MAC_INTERFACE = "xyz.openbmc_project.Network.MACAddress"; static constexpr auto chassisStateRoot = "/xyz/openbmc_project/state"; static constexpr auto chassisPOHStateIntf = - "xyz.openbmc_project.State.PowerOnHours"; + "xyz.openbmc_project.State.PowerOnHours"; static constexpr auto pOHCounterProperty = "POHCounter"; static constexpr auto match = "chassis0"; @@ -110,7 +116,7 @@ typedef struct uint8_t sel_dev_addr; uint8_t system_management_dev_addr; uint8_t bridge_dev_addr; -}__attribute__((packed)) ipmi_chassis_cap_t; +} __attribute__((packed)) ipmi_chassis_cap_t; typedef struct { @@ -118,16 +124,16 @@ typedef struct uint8_t last_power_event; uint8_t misc_power_state; uint8_t front_panel_button_cap_status; -}__attribute__((packed)) ipmi_get_chassis_status_t; +} __attribute__((packed)) ipmi_get_chassis_status_t; /** * @struct Get POH counter command response data */ struct GetPOHCountResponse { - uint8_t minPerCount; ///< Minutes per count + uint8_t minPerCount; ///< Minutes per count uint8_t counterReading[4]; ///< Counter reading -}__attribute__((packed)); +} __attribute__((packed)); // Phosphor Host State manager namespace State = sdbusplus::xyz::openbmc_project::State::server; @@ -165,27 +171,28 @@ constexpr auto minutesPerCount = 60; } // namespace poh -//TODO : Can remove the below function as we have +// TODO : Can remove the below function as we have // new functions which uses sdbusplus. // // openbmc/openbmc#1489 -int dbus_get_property(const char *name, char **buf) +int dbus_get_property(const char* name, char** buf) { sd_bus_error error = SD_BUS_ERROR_NULL; - sd_bus_message *m = NULL; - sd_bus *bus = NULL; - char *temp_buf = NULL; - char *connection = NULL; + sd_bus_message* m = NULL; + sd_bus* bus = NULL; + char* temp_buf = NULL; + char* connection = NULL; int r; // Get the system bus where most system services are provided. bus = ipmid_get_sd_bus_connection(); r = mapper_get_service(bus, settings_object_name, &connection); - if (r < 0) { - log("Failed to get connection", - entry("OBJ_NAME=%s", settings_object_name), - entry("ERRNO=0x%X", -r)); + if (r < 0) + { + log("Failed to get connection", + entry("OBJ_NAME=%s", settings_object_name), + entry("ERRNO=0x%X", -r)); goto finish; } @@ -195,18 +202,18 @@ int dbus_get_property(const char *name, char **buf) * Signatures and input arguments are provided by the arguments at the * end. */ - r = sd_bus_call_method(bus, - connection, /* service to contact */ - settings_object_name, /* object path */ - settings_intf_name, /* interface name */ - "Get", /* method name */ - &error, /* object to return error in */ - &m, /* return message on success */ - "ss", /* input signature */ - host_intf_name, /* first argument */ - name); /* second argument */ - - if (r < 0) { + r = sd_bus_call_method(bus, connection, /* service to contact */ + settings_object_name, /* object path */ + settings_intf_name, /* interface name */ + "Get", /* method name */ + &error, /* object to return error in */ + &m, /* return message on success */ + "ss", /* input signature */ + host_intf_name, /* first argument */ + name); /* second argument */ + + if (r < 0) + { log("Failed to issue Get method call", entry("ERRNO=0x%X", r)); goto finish; @@ -217,7 +224,8 @@ int dbus_get_property(const char *name, char **buf) * specified. */ r = sd_bus_message_read(m, "v", "s", &temp_buf); - if (r < 0) { + if (r < 0) + { log("Failed to parse response message", entry("ERRNO=0x%X", -r)); goto finish; @@ -230,7 +238,6 @@ int dbus_get_property(const char *name, char **buf) } */ - finish: sd_bus_error_free(&error); sd_bus_message_unref(m); @@ -239,24 +246,25 @@ finish: return r; } -//TODO : Can remove the below function as we have +// TODO : Can remove the below function as we have // new functions which uses sdbusplus. // // openbmc/openbmc#1489 -int dbus_set_property(const char * name, const char *value) +int dbus_set_property(const char* name, const char* value) { sd_bus_error error = SD_BUS_ERROR_NULL; - sd_bus_message *m = NULL; - sd_bus *bus = NULL; - char *connection = NULL; + sd_bus_message* m = NULL; + sd_bus* bus = NULL; + char* connection = NULL; int r; // Get the system bus where most system services are provided. bus = ipmid_get_sd_bus_connection(); r = mapper_get_service(bus, settings_object_name, &connection); - if (r < 0) { + if (r < 0) + { log("Failed to get connection", entry("OBJ_NAME=%s", settings_object_name), entry("ERRNO=0x%X", -r)); @@ -269,26 +277,26 @@ int dbus_set_property(const char * name, const char *value) * Signatures and input arguments are provided by the arguments at the * end. */ - r = sd_bus_call_method(bus, - connection, /* service to contact */ - settings_object_name, /* object path */ - settings_intf_name, /* interface name */ - "Set", /* method name */ - &error, /* object to return error in */ - &m, /* return message on success */ - "ssv", /* input signature */ - host_intf_name, /* first argument */ - name, /* second argument */ - "s", /* third argument */ - value); /* fourth argument */ - - if (r < 0) { + r = sd_bus_call_method(bus, connection, /* service to contact */ + settings_object_name, /* object path */ + settings_intf_name, /* interface name */ + "Set", /* method name */ + &error, /* object to return error in */ + &m, /* return message on success */ + "ssv", /* input signature */ + host_intf_name, /* first argument */ + name, /* second argument */ + "s", /* third argument */ + value); /* fourth argument */ + + if (r < 0) + { log("Failed to issue Set method call", entry("ERRNO=0x%X", r)); goto finish; } - finish: +finish: sd_bus_error_free(&error); sd_bus_message_unref(m); free(connection); @@ -296,23 +304,25 @@ int dbus_set_property(const char * name, const char *value) return r; } -struct get_sys_boot_options_t { +struct get_sys_boot_options_t +{ uint8_t parameter; uint8_t set; uint8_t block; -} __attribute__ ((packed)); +} __attribute__((packed)); -struct get_sys_boot_options_response_t { +struct get_sys_boot_options_response_t +{ uint8_t version; uint8_t parm; uint8_t data[SIZE_BOOT_OPTION]; -} __attribute__ ((packed)); +} __attribute__((packed)); -struct set_sys_boot_options_t { +struct set_sys_boot_options_t +{ uint8_t parameter; uint8_t data[SIZE_BOOT_OPTION]; -} __attribute__ ((packed)); - +} __attribute__((packed)); int getHostNetworkData(get_sys_boot_options_response_t* respptr) { @@ -322,7 +332,7 @@ int getHostNetworkData(get_sys_boot_options_response_t* respptr) try { - //TODO There may be cases where an interface is implemented by multiple + // TODO There may be cases where an interface is implemented by multiple // objects,to handle such cases we are interested on that object // which are on interested busname. // Currenlty mapper doesn't give the readable busname(gives busid) @@ -338,22 +348,23 @@ int getHostNetworkData(get_sys_boot_options_response_t* respptr) auto macObjectInfo = ipmi::getDbusObject(bus, MAC_INTERFACE, SETTINGS_ROOT, SETTINGS_MATCH); - properties = ipmi::getAllDbusProperties(bus, ipObjectInfo.second, - ipObjectInfo.first, IP_INTERFACE); - auto variant = - ipmi::getDbusProperty(bus, macObjectInfo.second, - macObjectInfo.first, - MAC_INTERFACE, "MACAddress"); + properties = ipmi::getAllDbusProperties( + bus, ipObjectInfo.second, ipObjectInfo.first, IP_INTERFACE); + auto variant = ipmi::getDbusProperty(bus, macObjectInfo.second, + macObjectInfo.first, MAC_INTERFACE, + "MACAddress"); - auto ipAddress = properties["Address"].get(); + auto ipAddress = properties["Address"].get(); auto gateway = properties["Gateway"].get(); auto prefix = properties["PrefixLength"].get(); - uint8_t isStatic = (properties["Origin"].get() == - "xyz.openbmc_project.Network.IP.AddressOrigin.Static") - ? 1 : 0; + uint8_t isStatic = + (properties["Origin"].get() == + "xyz.openbmc_project.Network.IP.AddressOrigin.Static") + ? 1 + : 0; auto MACAddress = variant.get(); @@ -373,9 +384,8 @@ int getHostNetworkData(get_sys_boot_options_response_t* respptr) // should not be default one,don't send blank override. if (isStatic) { - if((ipAddress == ipmi::network::DEFAULT_ADDRESS) || - (gateway == ipmi::network::DEFAULT_ADDRESS) || - (!prefix)) + if ((ipAddress == ipmi::network::DEFAULT_ADDRESS) || + (gateway == ipmi::network::DEFAULT_ADDRESS) || (!prefix)) { memset(respptr->data, 0, SIZE_BOOT_OPTION); rc = -1; @@ -383,30 +393,28 @@ int getHostNetworkData(get_sys_boot_options_response_t* respptr) } } - sscanf(MACAddress.c_str(), ipmi::network::MAC_ADDRESS_FORMAT, - (respptr->data + MAC_OFFSET), - (respptr->data + MAC_OFFSET + 1), - (respptr->data + MAC_OFFSET + 2), - (respptr->data + MAC_OFFSET + 3), - (respptr->data + MAC_OFFSET + 4), - (respptr->data + MAC_OFFSET + 5)); + sscanf( + MACAddress.c_str(), ipmi::network::MAC_ADDRESS_FORMAT, + (respptr->data + MAC_OFFSET), (respptr->data + MAC_OFFSET + 1), + (respptr->data + MAC_OFFSET + 2), (respptr->data + MAC_OFFSET + 3), + (respptr->data + MAC_OFFSET + 4), (respptr->data + MAC_OFFSET + 5)); respptr->data[MAC_OFFSET + 6] = 0x00; - memcpy(respptr->data + ADDRTYPE_OFFSET, &isStatic, - sizeof(isStatic)); + memcpy(respptr->data + ADDRTYPE_OFFSET, &isStatic, sizeof(isStatic)); uint8_t addressFamily = (properties["Type"].get() == - "xyz.openbmc_project.Network.IP.Protocol.IPv4") ? - AF_INET : AF_INET6; + "xyz.openbmc_project.Network.IP.Protocol.IPv4") + ? AF_INET + : AF_INET6; - addrSize = (addressFamily == AF_INET) ? - ipmi::network::IPV4_ADDRESS_SIZE_BYTE : - ipmi::network::IPV6_ADDRESS_SIZE_BYTE; + addrSize = (addressFamily == AF_INET) + ? ipmi::network::IPV4_ADDRESS_SIZE_BYTE + : ipmi::network::IPV6_ADDRESS_SIZE_BYTE; // ipaddress and gateway would be in IPv4 format inet_pton(addressFamily, ipAddress.c_str(), - (respptr->data + IPADDR_OFFSET)); + (respptr->data + IPADDR_OFFSET)); uint8_t prefixOffset = IPADDR_OFFSET + addrSize; @@ -415,8 +423,7 @@ int getHostNetworkData(get_sys_boot_options_response_t* respptr) uint8_t gatewayOffset = prefixOffset + sizeof(decltype(prefix)); inet_pton(addressFamily, gateway.c_str(), - (respptr->data + gatewayOffset)); - + (respptr->data + gatewayOffset)); } catch (InternalFailure& e) { @@ -426,8 +433,8 @@ int getHostNetworkData(get_sys_boot_options_response_t* respptr) return rc; } - //PetiBoot-Specific - //If success then copy the first 9 bytes to the data + // PetiBoot-Specific + // If success then copy the first 9 bytes to the data memcpy(respptr->data, net_conf_initial_bytes, sizeof(net_conf_initial_bytes)); @@ -453,30 +460,32 @@ int getHostNetworkData(get_sys_boot_options_response_t* respptr) * @returns address in text form. */ -std::string getAddrStr(uint8_t family, uint8_t* data, - uint8_t offset, uint8_t addrSize) +std::string getAddrStr(uint8_t family, uint8_t* data, uint8_t offset, + uint8_t addrSize) { char ipAddr[INET6_ADDRSTRLEN] = {}; - switch(family) + switch (family) { case AF_INET: { - struct sockaddr_in addr4 {}; + struct sockaddr_in addr4 + { + }; memcpy(&addr4.sin_addr.s_addr, &data[offset], addrSize); - inet_ntop(AF_INET, &addr4.sin_addr, - ipAddr, INET_ADDRSTRLEN); + inet_ntop(AF_INET, &addr4.sin_addr, ipAddr, INET_ADDRSTRLEN); break; } case AF_INET6: { - struct sockaddr_in6 addr6 {}; + struct sockaddr_in6 addr6 + { + }; memcpy(&addr6.sin6_addr.s6_addr, &data[offset], addrSize); - inet_ntop(AF_INET6, &addr6.sin6_addr, - ipAddr, INET6_ADDRSTRLEN); + inet_ntop(AF_INET6, &addr6.sin6_addr, ipAddr, INET6_ADDRSTRLEN); break; } @@ -493,19 +502,18 @@ int setHostNetworkData(set_sys_boot_options_t* reqptr) { using namespace std::string_literals; std::string host_network_config; - char mac[] {"00:00:00:00:00:00"}; + char mac[]{"00:00:00:00:00:00"}; std::string ipAddress, gateway; - char addrOrigin {0}; - uint8_t addrSize {0}; + char addrOrigin{0}; + uint8_t addrSize{0}; std::string addressOrigin = "xyz.openbmc_project.Network.IP.AddressOrigin.DHCP"; - std::string addressType = - "xyz.openbmc_project.Network.IP.Protocol.IPv4"; - uint8_t prefix {0}; + std::string addressType = "xyz.openbmc_project.Network.IP.Protocol.IPv4"; + uint8_t prefix{0}; uint32_t zeroCookie = 0; uint8_t family = AF_INET; - //cookie starts from second byte + // cookie starts from second byte // version starts from sixth byte try @@ -514,13 +522,12 @@ int setHostNetworkData(set_sys_boot_options_t* reqptr) { // cookie == 0x21 0x70 0x62 0x21 if (memcmp(&(reqptr->data[COOKIE_OFFSET]), - (net_conf_initial_bytes + COOKIE_OFFSET), - SIZE_COOKIE) != 0) + (net_conf_initial_bytes + COOKIE_OFFSET), + SIZE_COOKIE) != 0) { - //cookie == 0 - if (memcmp(&(reqptr->data[COOKIE_OFFSET]), - &zeroCookie, - SIZE_COOKIE) == 0) + // cookie == 0 + if (memcmp(&(reqptr->data[COOKIE_OFFSET]), &zeroCookie, + SIZE_COOKIE) == 0) { // need to zero out the network settings. break; @@ -532,8 +539,8 @@ int setHostNetworkData(set_sys_boot_options_t* reqptr) // vesion == 0x00 0x01 if (memcmp(&(reqptr->data[VERSION_OFFSET]), - (net_conf_initial_bytes + VERSION_OFFSET), - SIZE_VERSION) != 0) + (net_conf_initial_bytes + VERSION_OFFSET), + SIZE_VERSION) != 0) { log("Invalid Version"); @@ -541,10 +548,8 @@ int setHostNetworkData(set_sys_boot_options_t* reqptr) } snprintf(mac, SIZE_MAC, ipmi::network::MAC_ADDRESS_FORMAT, - reqptr->data[MAC_OFFSET], - reqptr->data[MAC_OFFSET + 1], - reqptr->data[MAC_OFFSET + 2], - reqptr->data[MAC_OFFSET + 3], + reqptr->data[MAC_OFFSET], reqptr->data[MAC_OFFSET + 1], + reqptr->data[MAC_OFFSET + 2], reqptr->data[MAC_OFFSET + 3], reqptr->data[MAC_OFFSET + 4], reqptr->data[MAC_OFFSET + 5]); @@ -558,7 +563,8 @@ int setHostNetworkData(set_sys_boot_options_t* reqptr) } // Get the address size - memcpy(&addrSize ,&reqptr->data[ADDR_SIZE_OFFSET], sizeof(addrSize)); + memcpy(&addrSize, &reqptr->data[ADDR_SIZE_OFFSET], + sizeof(addrSize)); uint8_t prefixOffset = IPADDR_OFFSET + addrSize; @@ -573,17 +579,18 @@ int setHostNetworkData(set_sys_boot_options_t* reqptr) family = AF_INET6; } - ipAddress = getAddrStr(family, reqptr->data, IPADDR_OFFSET, addrSize); + ipAddress = + getAddrStr(family, reqptr->data, IPADDR_OFFSET, addrSize); gateway = getAddrStr(family, reqptr->data, gatewayOffset, addrSize); - } while(0); - - //Cookie == 0 or it is a valid cookie - host_network_config += "ipaddress="s + ipAddress + - ",prefix="s + std::to_string(prefix) + ",gateway="s + gateway + - ",mac="s + mac + ",addressOrigin="s + addressOrigin; + } while (0); + // Cookie == 0 or it is a valid cookie + host_network_config += "ipaddress="s + ipAddress + ",prefix="s + + std::to_string(prefix) + ",gateway="s + gateway + + ",mac="s + mac + ",addressOrigin="s + + addressOrigin; sdbusplus::bus::bus bus(ipmid_get_sd_bus_connection()); @@ -593,22 +600,22 @@ int setHostNetworkData(set_sys_boot_options_t* reqptr) SETTINGS_ROOT, SETTINGS_MATCH); // set the dbus property ipmi::setDbusProperty(bus, ipObjectInfo.second, ipObjectInfo.first, - IP_INTERFACE, "Address", std::string(ipAddress)); - ipmi::setDbusProperty(bus, ipObjectInfo.second, ipObjectInfo.first, - IP_INTERFACE, "PrefixLength", prefix); + IP_INTERFACE, "Address", std::string(ipAddress)); ipmi::setDbusProperty(bus, ipObjectInfo.second, ipObjectInfo.first, - IP_INTERFACE, "Origin", addressOrigin); + IP_INTERFACE, "PrefixLength", prefix); ipmi::setDbusProperty(bus, ipObjectInfo.second, ipObjectInfo.first, - IP_INTERFACE, "Gateway", std::string(gateway)); + IP_INTERFACE, "Origin", addressOrigin); ipmi::setDbusProperty(bus, ipObjectInfo.second, ipObjectInfo.first, - IP_INTERFACE, "Type", - std::string("xyz.openbmc_project.Network.IP.Protocol.IPv4")); + IP_INTERFACE, "Gateway", std::string(gateway)); + ipmi::setDbusProperty( + bus, ipObjectInfo.second, ipObjectInfo.first, IP_INTERFACE, "Type", + std::string("xyz.openbmc_project.Network.IP.Protocol.IPv4")); ipmi::setDbusProperty(bus, macObjectInfo.second, macObjectInfo.first, - MAC_INTERFACE,"MACAddress", std::string(mac)); - - log("Network configuration changed", - entry("NETWORKCONFIG=%s", host_network_config.c_str())); + MAC_INTERFACE, "MACAddress", std::string(mac)); + log( + "Network configuration changed", + entry("NETWORKCONFIG=%s", host_network_config.c_str())); } catch (InternalFailure& e) { @@ -623,15 +630,15 @@ uint32_t getPOHCounter() { sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; - auto chassisStateObj = ipmi::getDbusObject(bus, chassisPOHStateIntf, - chassisStateRoot, match); + auto chassisStateObj = + ipmi::getDbusObject(bus, chassisPOHStateIntf, chassisStateRoot, match); - auto service = ipmi::getService(bus, chassisPOHStateIntf, - chassisStateObj.first); + auto service = + ipmi::getService(bus, chassisPOHStateIntf, chassisStateObj.first); - auto propValue = ipmi::getDbusProperty(bus, service, chassisStateObj.first, - chassisPOHStateIntf, - pOHCounterProperty); + auto propValue = + ipmi::getDbusProperty(bus, service, chassisStateObj.first, + chassisPOHStateIntf, pOHCounterProperty); return propValue.get(); } @@ -649,8 +656,10 @@ ipmi_ret_t ipmi_chassis_wildcard(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } ipmi_ret_t ipmi_get_chassis_cap(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { // sd_bus error ipmi_ret_t rc = IPMI_CC_OK; @@ -665,9 +674,11 @@ ipmi_ret_t ipmi_get_chassis_cap(ipmi_netfn_t netfn, ipmi_cmd_t cmd, // [7..4] - reserved // [3] – 1b = provides power interlock (IPM 1.5) // [2] – 1b = provides Diagnostic Interrupt (FP NMI) - // [1] – 1b = provides “Front Panel Lockout” (indicates that the chassis has capabilities - // to lock out external power control and reset button or front panel interfaces - // and/or detect tampering with those interfaces). + // [1] – 1b = provides “Front Panel Lockout” (indicates that the chassis has + // capabilities + // to lock out external power control and reset button or front + // panel interfaces and/or detect tampering with those + // interfaces). // [0] -1b = Chassis provides intrusion (physical security) sensor. // set to default value 0x0. chassis_cap.cap_flags = 0x0; @@ -700,26 +711,26 @@ ipmi_ret_t ipmi_get_chassis_cap(ipmi_netfn_t netfn, ipmi_cmd_t cmd, int initiate_state_transition(State::Host::Transition transition) { // OpenBMC Host State Manager dbus framework - constexpr auto HOST_STATE_MANAGER_ROOT = "/xyz/openbmc_project/state/host0"; + constexpr auto HOST_STATE_MANAGER_ROOT = "/xyz/openbmc_project/state/host0"; constexpr auto HOST_STATE_MANAGER_IFACE = "xyz.openbmc_project.State.Host"; - constexpr auto DBUS_PROPERTY_IFACE = "org.freedesktop.DBus.Properties"; - constexpr auto PROPERTY = "RequestedHostTransition"; + constexpr auto DBUS_PROPERTY_IFACE = "org.freedesktop.DBus.Properties"; + constexpr auto PROPERTY = "RequestedHostTransition"; // sd_bus error int rc = 0; - char *busname = NULL; + char* busname = NULL; // SD Bus error report mechanism. sd_bus_error bus_error = SD_BUS_ERROR_NULL; // Gets a hook onto either a SYSTEM or SESSION bus - sd_bus *bus_type = ipmid_get_sd_bus_connection(); + sd_bus* bus_type = ipmid_get_sd_bus_connection(); rc = mapper_get_service(bus_type, HOST_STATE_MANAGER_ROOT, &busname); if (rc < 0) { - log("Failed to get bus name", - entry("ERRNO=0x%X, OBJPATH=%s", - -rc, HOST_STATE_MANAGER_ROOT)); + log( + "Failed to get bus name", + entry("ERRNO=0x%X, OBJPATH=%s", -rc, HOST_STATE_MANAGER_ROOT)); return rc; } @@ -734,10 +745,9 @@ int initiate_state_transition(State::Host::Transition transition) &bus_error, // object to return error nullptr, // Response buffer if any "ssv", // Takes 3 arguments - HOST_STATE_MANAGER_IFACE, - PROPERTY, - "s", request.c_str()); - if(rc < 0) + HOST_STATE_MANAGER_IFACE, PROPERTY, "s", + request.c_str()); + if (rc < 0) { log("Failed to initiate transition", entry("ERRNO=0x%X, REQUEST=%s", -rc, request.c_str())); @@ -760,12 +770,10 @@ using namespace sdbusplus::xyz::openbmc_project::Control::Power::server; using IpmiValue = uint8_t; using DbusValue = RestorePolicy::Policy; -std::map dbusToIpmi = -{ +std::map dbusToIpmi = { {RestorePolicy::Policy::AlwaysOff, 0x00}, {RestorePolicy::Policy::Restore, 0x01}, - {RestorePolicy::Policy::AlwaysOn, 0x02} -}; + {RestorePolicy::Policy::AlwaysOn, 0x02}}; } // namespace power_policy @@ -778,14 +786,14 @@ ipmi_ret_t ipmi_get_chassis_status(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_data_len_t data_len, ipmi_context_t context) { - const char *objname = "/org/openbmc/control/power0"; - const char *intf = "org.openbmc.control.Power"; + const char* objname = "/org/openbmc/control/power0"; + const char* intf = "org.openbmc.control.Power"; - sd_bus *bus = NULL; - sd_bus_message *reply = NULL; + sd_bus* bus = NULL; + sd_bus_message* reply = NULL; int r = 0; int pgood = 0; - char *busname = NULL; + char* busname = NULL; ipmi_ret_t rc = IPMI_CC_OK; ipmi_get_chassis_status_t chassis_status{}; @@ -796,12 +804,9 @@ ipmi_ret_t ipmi_get_chassis_status(ipmi_netfn_t netfn, ipmi_cmd_t cmd, using namespace power_policy; const auto& powerRestoreSetting = objects.map.at(powerRestoreIntf).front(); - auto method = - dbus.new_method_call( - objects.service(powerRestoreSetting, powerRestoreIntf).c_str(), - powerRestoreSetting.c_str(), - ipmi::PROP_INTF, - "Get"); + auto method = dbus.new_method_call( + objects.service(powerRestoreSetting, powerRestoreIntf).c_str(), + powerRestoreSetting.c_str(), ipmi::PROP_INTF, "Get"); method.append(powerRestoreIntf, "PowerRestorePolicy"); auto resp = dbus.call(method); if (resp.is_method_error()) @@ -821,29 +826,29 @@ ipmi_ret_t ipmi_get_chassis_status(ipmi_netfn_t netfn, ipmi_cmd_t cmd, bus = ipmid_get_sd_bus_connection(); r = mapper_get_service(bus, objname, &busname); - if (r < 0) { - log("Failed to get bus name", - entry("ERRNO=0x%X", -r)); + if (r < 0) + { + log("Failed to get bus name", entry("ERRNO=0x%X", -r)); rc = IPMI_CC_UNSPECIFIED_ERROR; goto finish; } - r = sd_bus_get_property(bus, busname, objname, intf, "pgood", NULL, &reply, "i"); - if (r < 0) { + r = sd_bus_get_property(bus, busname, objname, intf, "pgood", NULL, &reply, + "i"); + if (r < 0) + { log("Failed to call sd_bus_get_property", - entry("PROPERTY=%s","pgood"), - entry("ERRNO=0x%X", -r), - entry("BUS=%s", busname), - entry("PATH=%s", objname), + entry("PROPERTY=%s", "pgood"), entry("ERRNO=0x%X", -r), + entry("BUS=%s", busname), entry("PATH=%s", objname), entry("INTERFACE=%s", intf)); rc = IPMI_CC_UNSPECIFIED_ERROR; goto finish; } r = sd_bus_message_read(reply, "i", &pgood); - if (r < 0) { - log("Failed to read sensor:", - entry("ERRNO=0x%X", -r)); + if (r < 0) + { + log("Failed to read sensor:", entry("ERRNO=0x%X", -r)); rc = IPMI_CC_UNSPECIFIED_ERROR; goto finish; } @@ -859,7 +864,8 @@ ipmi_ret_t ipmi_get_chassis_status(ipmi_netfn_t netfn, ipmi_cmd_t cmd, // 10b = chassis always powers up after AC/mains returns // 11b = unknow // Set to 00b, by observing the hardware behavior. - // Do we need to define a dbus property to identify the restore policy? + // Do we need to define a dbus property to identify the restore + // policy? // [4] power control fault // 1b = controller attempted to turn system power on or off, but @@ -882,7 +888,7 @@ ipmi_ret_t ipmi_get_chassis_status(ipmi_netfn_t netfn, ipmi_cmd_t cmd, // 1b = system power is on // 0b = system power is off(soft-off S4/S5, or mechanical off) - chassis_status.cur_power_state = ((s & 0x3)<<5) | (pgood & 0x1); + chassis_status.cur_power_state = ((s & 0x3) << 5) | (pgood & 0x1); // Last Power Event // [7..5] – reserved @@ -901,7 +907,8 @@ ipmi_ret_t ipmi_get_chassis_status(ipmi_netfn_t netfn, ipmi_cmd_t cmd, // 0b = Chassis Identify command support unspecified via this command. // (The Get Command Support command , if implemented, would still // indicate support for the Chassis Identify command) - // [5..4] – Chassis Identify State. Mandatory when bit[6] =1b, reserved (return + // [5..4] – Chassis Identify State. Mandatory when bit[6] =1b, reserved + // (return // as 00b) otherwise. Returns the present chassis identify state. // Refer to the Chassis Identify command for more info. // 00b = chassis identify state = Off @@ -935,13 +942,13 @@ finish: //------------------------------------------------------------- int stop_soft_off_timer() { - constexpr auto iface = "org.freedesktop.DBus.Properties"; - constexpr auto soft_off_iface = "xyz.openbmc_project.Ipmi.Internal." - "SoftPowerOff"; + constexpr auto iface = "org.freedesktop.DBus.Properties"; + constexpr auto soft_off_iface = "xyz.openbmc_project.Ipmi.Internal." + "SoftPowerOff"; - constexpr auto property = "ResponseReceived"; - constexpr auto value = "xyz.openbmc_project.Ipmi.Internal." - "SoftPowerOff.HostResponse.HostShutdown"; + constexpr auto property = "ResponseReceived"; + constexpr auto value = "xyz.openbmc_project.Ipmi.Internal." + "SoftPowerOff.HostResponse.HostShutdown"; // Get the system bus where most system services are provided. auto bus = ipmid_get_sd_bus_connection(); @@ -953,9 +960,9 @@ int stop_soft_off_timer() // for now the code will directly call the soft off interface due to a // race condition with mapper usage // - //char *busname = nullptr; - //auto r = mapper_get_service(bus, SOFTOFF_OBJPATH, &busname); - //if (r < 0) + // char *busname = nullptr; + // auto r = mapper_get_service(bus, SOFTOFF_OBJPATH, &busname); + // if (r < 0) //{ // fprintf(stderr, "Failed to get %s bus name: %s\n", // SOFTOFF_OBJPATH, -r); @@ -964,16 +971,16 @@ int stop_soft_off_timer() // No error object or reply expected. int rc = sd_bus_call_method(bus, SOFTOFF_BUSNAME, SOFTOFF_OBJPATH, iface, - "Set", nullptr, nullptr, "ssv", - soft_off_iface, property, "s", value); + "Set", nullptr, nullptr, "ssv", soft_off_iface, + property, "s", value); if (rc < 0) { log("Failed to set property in SoftPowerOff object", entry("ERRNO=0x%X", -rc)); } - //TODO openbmc/openbmc#1661 - Mapper refactor - //free(busname); + // TODO openbmc/openbmc#1661 - Mapper refactor + // free(busname); return rc; } @@ -990,10 +997,10 @@ void indicate_no_softoff_needed() // Add the host instance (default 0 for now) to the file name std::string file{HOST_INBAND_REQUEST_FILE}; - auto size = std::snprintf(nullptr,0,file.c_str(),0); + auto size = std::snprintf(nullptr, 0, file.c_str(), 0); size++; // null std::unique_ptr buf(new char[size]); - std::snprintf(buf.get(),size,file.c_str(),0); + std::snprintf(buf.get(), size, file.c_str(), 0); // Append file name to directory and create it path /= buf.get(); @@ -1016,9 +1023,9 @@ ipmi_ret_t ipmi_chassis_control(ipmi_netfn_t netfn, ipmi_cmd_t cmd, *data_len = 0; // Catch the actual operaton by peeking into request buffer - uint8_t chassis_ctrl_cmd = *(uint8_t *)request; + uint8_t chassis_ctrl_cmd = *(uint8_t*)request; - switch(chassis_ctrl_cmd) + switch (chassis_ctrl_cmd) { case CMD_POWER_ON: rc = initiate_state_transition(State::Host::Transition::On); @@ -1086,7 +1093,7 @@ ipmi_ret_t ipmi_chassis_control(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } } - return ( (rc < 0) ? IPMI_CC_INVALID : IPMI_CC_OK); + return ((rc < 0) ? IPMI_CC_INVALID : IPMI_CC_OK); } /** @brief Return D-Bus connection string to enclosure identify LED object @@ -1098,16 +1105,12 @@ std::string getEnclosureIdentifyConnection() { // lookup enclosure_identify group owner(s) in mapper auto mapperCall = chassis::internal::dbus.new_method_call( - ipmi::MAPPER_BUS_NAME, - ipmi::MAPPER_OBJ, - ipmi::MAPPER_INTF, - "GetObject"); + ipmi::MAPPER_BUS_NAME, ipmi::MAPPER_OBJ, ipmi::MAPPER_INTF, + "GetObject"); mapperCall.append(identify_led_object_name); - static const std::vector interfaces = - { - "xyz.openbmc_project.Led.Group" - }; + static const std::vector interfaces = { + "xyz.openbmc_project.Led.Group"}; mapperCall.append(interfaces); auto mapperReply = chassis::internal::dbus.call(mapperCall); if (mapperReply.is_method_error()) @@ -1120,8 +1123,9 @@ std::string getEnclosureIdentifyConnection() if (mapperResp.size() != encIdentifyObjectsSize) { - log("Invalid number of enclosure identify objects.", - entry("ENC_IDENTITY_OBJECTS_SIZE=%d", mapperResp.size())); + log( + "Invalid number of enclosure identify objects.", + entry("ENC_IDENTITY_OBJECTS_SIZE=%d", mapperResp.size())); elog(); } auto pair = mapperResp[encIdentifyObjectsSize - 1]; @@ -1137,15 +1141,16 @@ void enclosureIdentifyLed(bool flag) { using namespace chassis::internal; std::string connection = std::move(getEnclosureIdentifyConnection()); - auto led = dbus.new_method_call(connection.c_str(), - identify_led_object_name, "org.freedesktop.DBus.Properties", "Set"); + auto led = + dbus.new_method_call(connection.c_str(), identify_led_object_name, + "org.freedesktop.DBus.Properties", "Set"); led.append("xyz.openbmc_project.Led.Group", "Asserted", - sdbusplus::message::variant(flag)); + sdbusplus::message::variant(flag)); auto ledReply = dbus.call(led); if (ledReply.is_method_error()) { log("Chassis Identify: Error Setting State On/Off\n", - entry("LED_STATE=%d", flag)); + entry("LED_STATE=%d", flag)); elog(); } } @@ -1185,11 +1190,14 @@ ipmi_ret_t ipmi_chassis_identify(ipmi_netfn_t netfn, ipmi_cmd_t cmd, { return IPMI_CC_REQ_DATA_LEN_INVALID; } - uint8_t identifyInterval = *data_len > identifyIntervalPos ? - (static_cast(request))[identifyIntervalPos] : - DEFAULT_IDENTIFY_TIME_OUT; - bool forceIdentify = (*data_len == chassisIdentifyReqLength) ? - (static_cast(request))[forceIdentifyPos] & 0x01 : false; + uint8_t identifyInterval = + *data_len > identifyIntervalPos + ? (static_cast(request))[identifyIntervalPos] + : DEFAULT_IDENTIFY_TIME_OUT; + bool forceIdentify = + (*data_len == chassisIdentifyReqLength) + ? (static_cast(request))[forceIdentifyPos] & 0x01 + : false; if (identifyInterval || forceIdentify) { @@ -1212,7 +1220,7 @@ ipmi_ret_t ipmi_chassis_identify(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } // start the timer auto time = std::chrono::duration_cast( - std::chrono::seconds(identifyInterval)); + std::chrono::seconds(identifyInterval)); identifyTimer->startTimer(time); } else if (!identifyInterval) @@ -1230,39 +1238,30 @@ using namespace sdbusplus::xyz::openbmc_project::Control::Boot::server; using IpmiValue = uint8_t; constexpr auto ipmiDefault = 0; -std::map sourceIpmiToDbus = -{ +std::map sourceIpmiToDbus = { {0x01, Source::Sources::Network}, {0x02, Source::Sources::Disk}, {0x05, Source::Sources::ExternalMedia}, - {ipmiDefault, Source::Sources::Default} -}; + {ipmiDefault, Source::Sources::Default}}; -std::map modeIpmiToDbus = -{ +std::map modeIpmiToDbus = { {0x03, Mode::Modes::Safe}, {0x06, Mode::Modes::Setup}, - {ipmiDefault, Mode::Modes::Regular} -}; + {ipmiDefault, Mode::Modes::Regular}}; -std::map sourceDbusToIpmi = -{ +std::map sourceDbusToIpmi = { {Source::Sources::Network, 0x01}, {Source::Sources::Disk, 0x02}, {Source::Sources::ExternalMedia, 0x05}, - {Source::Sources::Default, ipmiDefault} -}; + {Source::Sources::Default, ipmiDefault}}; -std::map modeDbusToIpmi = -{ +std::map modeDbusToIpmi = { {Mode::Modes::Safe, 0x03}, {Mode::Modes::Setup, 0x06}, - {Mode::Modes::Regular, ipmiDefault} -}; + {Mode::Modes::Regular, ipmiDefault}}; } // namespace boot_options - /** @brief Set the property value for boot source * @param[in] source - boot source value * @return On failure return IPMI error. @@ -1275,10 +1274,9 @@ static ipmi_ret_t setBootSource(const Source::Sources& source) convertForMessage(source); auto bootSetting = settings::boot::setting(objects, bootSourceIntf); const auto& bootSourceSetting = std::get(bootSetting); - auto method = - dbus.new_method_call( - objects.service(bootSourceSetting, bootSourceIntf).c_str(), - bootSourceSetting.c_str(), ipmi::PROP_INTF, "Set"); + auto method = dbus.new_method_call( + objects.service(bootSourceSetting, bootSourceIntf).c_str(), + bootSourceSetting.c_str(), ipmi::PROP_INTF, "Set"); method.append(bootSourceIntf, "BootSource", property); auto reply = dbus.call(method); if (reply.is_method_error()) @@ -1290,7 +1288,7 @@ static ipmi_ret_t setBootSource(const Source::Sources& source) return IPMI_CC_OK; } - /** @brief Set the property value for boot mode +/** @brief Set the property value for boot mode * @param[in] mode - boot mode value * @return On failure return IPMI error. */ @@ -1298,14 +1296,12 @@ static ipmi_ret_t setBootMode(const Mode::Modes& mode) { using namespace chassis::internal; using namespace chassis::internal::cache; - sdbusplus::message::variant property = - convertForMessage(mode); + sdbusplus::message::variant property = convertForMessage(mode); auto bootSetting = settings::boot::setting(objects, bootModeIntf); const auto& bootModeSetting = std::get(bootSetting); - auto method = - dbus.new_method_call( - objects.service(bootModeSetting, bootModeIntf).c_str(), - bootModeSetting.c_str(), ipmi::PROP_INTF, "Set"); + auto method = dbus.new_method_call( + objects.service(bootModeSetting, bootModeIntf).c_str(), + bootModeSetting.c_str(), ipmi::PROP_INTF, "Set"); method.append(bootModeIntf, "BootMode", property); auto reply = dbus.call(method); if (reply.is_method_error()) @@ -1325,23 +1321,24 @@ ipmi_ret_t ipmi_chassis_get_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd, { using namespace boot_options; ipmi_ret_t rc = IPMI_CC_PARM_NOT_SUPPORTED; - char *p = NULL; - get_sys_boot_options_response_t *resp = (get_sys_boot_options_response_t *) response; - get_sys_boot_options_t *reqptr = (get_sys_boot_options_t*) request; + char* p = NULL; + get_sys_boot_options_response_t* resp = + (get_sys_boot_options_response_t*)response; + get_sys_boot_options_t* reqptr = (get_sys_boot_options_t*)request; IpmiValue bootOption = ipmiDefault; - memset(resp,0,sizeof(*resp)); - resp->version = SET_PARM_VERSION; - resp->parm = 5; - resp->data[0] = SET_PARM_BOOT_FLAGS_VALID_ONE_TIME; - + memset(resp, 0, sizeof(*resp)); + resp->version = SET_PARM_VERSION; + resp->parm = 5; + resp->data[0] = SET_PARM_BOOT_FLAGS_VALID_ONE_TIME; /* * Parameter #5 means boot flags. Please refer to 28.13 of ipmi doc. * This is the only parameter used by petitboot. */ - if ( reqptr->parameter == static_cast - ( BootOptionParameter::BOOT_FLAGS )) { + if (reqptr->parameter == + static_cast(BootOptionParameter::BOOT_FLAGS)) + { *data_len = static_cast(BootOptionResponseSize::BOOT_FLAGS); using namespace chassis::internal; @@ -1354,12 +1351,9 @@ ipmi_ret_t ipmi_chassis_get_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd, std::get(bootSetting); auto oneTimeEnabled = std::get(bootSetting); - auto method = - dbus.new_method_call( - objects.service(bootSourceSetting, bootSourceIntf).c_str(), - bootSourceSetting.c_str(), - ipmi::PROP_INTF, - "Get"); + auto method = dbus.new_method_call( + objects.service(bootSourceSetting, bootSourceIntf).c_str(), + bootSourceSetting.c_str(), ipmi::PROP_INTF, "Get"); method.append(bootSourceIntf, "BootSource"); auto reply = dbus.call(method); if (reply.is_method_error()) @@ -1377,11 +1371,8 @@ ipmi_ret_t ipmi_chassis_get_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd, bootSetting = settings::boot::setting(objects, bootModeIntf); const auto& bootModeSetting = std::get(bootSetting); method = dbus.new_method_call( - objects.service(bootModeSetting, bootModeIntf). - c_str(), - bootModeSetting.c_str(), - ipmi::PROP_INTF, - "Get"); + objects.service(bootModeSetting, bootModeIntf).c_str(), + bootModeSetting.c_str(), ipmi::PROP_INTF, "Get"); method.append(bootModeIntf, "BootMode"); reply = dbus.call(method); if (reply.is_method_error()) @@ -1407,9 +1398,9 @@ ipmi_ret_t ipmi_chassis_get_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } resp->data[1] = (bootOption << 2); - resp->data[0] = oneTimeEnabled ? - SET_PARM_BOOT_FLAGS_VALID_ONE_TIME: - SET_PARM_BOOT_FLAGS_VALID_PERMANENT; + resp->data[0] = oneTimeEnabled + ? SET_PARM_BOOT_FLAGS_VALID_ONE_TIME + : SET_PARM_BOOT_FLAGS_VALID_PERMANENT; rc = IPMI_CC_OK; } @@ -1419,28 +1410,34 @@ ipmi_ret_t ipmi_chassis_get_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd, *data_len = 0; return IPMI_CC_UNSPECIFIED_ERROR; } - } else if ( reqptr->parameter == static_cast - ( BootOptionParameter::OPAL_NETWORK_SETTINGS )) { + } + else if (reqptr->parameter == + static_cast(BootOptionParameter::OPAL_NETWORK_SETTINGS)) + { - *data_len = static_cast(BootOptionResponseSize::OPAL_NETWORK_SETTINGS); + *data_len = + static_cast(BootOptionResponseSize::OPAL_NETWORK_SETTINGS); - resp->parm = static_cast(BootOptionParameter::OPAL_NETWORK_SETTINGS); + resp->parm = + static_cast(BootOptionParameter::OPAL_NETWORK_SETTINGS); int ret = getHostNetworkData(resp); - if (ret < 0) { + if (ret < 0) + { log( - "getHostNetworkData failed for get_sys_boot_options."); + "getHostNetworkData failed for get_sys_boot_options."); rc = IPMI_CC_UNSPECIFIED_ERROR; - - }else + } + else rc = IPMI_CC_OK; } - else { - log("Unsupported parameter", entry( - "PARAM=0x%x", reqptr->parameter)); + else + { + log("Unsupported parameter", + entry("PARAM=0x%x", reqptr->parameter)); } if (p) @@ -1454,8 +1451,6 @@ ipmi_ret_t ipmi_chassis_get_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return rc; } - - ipmi_ret_t ipmi_chassis_set_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, @@ -1464,9 +1459,10 @@ ipmi_ret_t ipmi_chassis_set_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd, { using namespace boot_options; ipmi_ret_t rc = IPMI_CC_OK; - set_sys_boot_options_t *reqptr = (set_sys_boot_options_t *) request; + set_sys_boot_options_t* reqptr = (set_sys_boot_options_t*)request; - printf("IPMI SET_SYS_BOOT_OPTIONS reqptr->parameter =[%d]\n",reqptr->parameter); + printf("IPMI SET_SYS_BOOT_OPTIONS reqptr->parameter =[%d]\n", + reqptr->parameter); // This IPMI command does not have any resposne data *data_len = 0; @@ -1484,7 +1480,7 @@ ipmi_ret_t ipmi_chassis_set_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd, auto oneTimeEnabled = false; constexpr auto enabledIntf = "xyz.openbmc_project.Object.Enable"; constexpr auto oneTimePath = - "/xyz/openbmc_project/control/host0/boot/one_time"; + "/xyz/openbmc_project/control/host0/boot/one_time"; try { @@ -1492,8 +1488,7 @@ ipmi_ret_t ipmi_chassis_set_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd, (reqptr->data[0] & SET_PARM_BOOT_FLAGS_PERMANENT) == SET_PARM_BOOT_FLAGS_PERMANENT; - auto bootSetting = - settings::boot::setting(objects, bootSourceIntf); + auto bootSetting = settings::boot::setting(objects, bootSourceIntf); oneTimeEnabled = std::get(bootSetting); @@ -1512,12 +1507,8 @@ ipmi_ret_t ipmi_chassis_set_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd, { auto service = ipmi::getService(dbus, enabledIntf, oneTimePath); - ipmi::setDbusProperty(dbus, - service, - oneTimePath, - enabledIntf, - "Enabled", - !permanent); + ipmi::setDbusProperty(dbus, service, oneTimePath, enabledIntf, + "Enabled", !permanent); } auto modeItr = modeIpmiToDbus.find(bootOption); @@ -1534,7 +1525,7 @@ ipmi_ret_t ipmi_chassis_set_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd, // the boot mode D-Bus property to default. // This way the ipmid code can determine which property is not // at the default value - if(sourceItr->second != Source::Sources::Default) + if (sourceItr->second != Source::Sources::Default) { setBootMode(Mode::Modes::Regular); } @@ -1551,7 +1542,7 @@ ipmi_ret_t ipmi_chassis_set_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd, // the boot source D-Bus property to default. // This way the ipmid code can determine which property is not // at the default value - if(modeItr->second != Mode::Modes::Regular) + if (modeItr->second != Mode::Modes::Regular) { setBootSource(Source::Sources::Default); } @@ -1563,26 +1554,33 @@ ipmi_ret_t ipmi_chassis_set_sys_boot_options(ipmi_netfn_t netfn, ipmi_cmd_t cmd, *data_len = 0; return IPMI_CC_UNSPECIFIED_ERROR; } - } else if (reqptr->parameter == - (uint8_t)BootOptionParameter::OPAL_NETWORK_SETTINGS) { + } + else if (reqptr->parameter == + (uint8_t)BootOptionParameter::OPAL_NETWORK_SETTINGS) + { int ret = setHostNetworkData(reqptr); - if (ret < 0) { + if (ret < 0) + { log( - "setHostNetworkData failed for set_sys_boot_options"); + "setHostNetworkData failed for set_sys_boot_options"); rc = IPMI_CC_UNSPECIFIED_ERROR; } - } else if (reqptr->parameter == - static_cast(BootOptionParameter::BOOT_INFO)) { + } + else if (reqptr->parameter == + static_cast(BootOptionParameter::BOOT_INFO)) + { // Handle parameter #4 and return command completed normally // (IPMI_CC_OK). There is no implementation in OpenBMC for this // parameter. This is added to support the ipmitool command `chassis // bootdev` which sends set on parameter #4, before setting the boot // flags. rc = IPMI_CC_OK; - } else { - log("Unsupported parameter", entry( - "PARAM=0x%x", reqptr->parameter)); + } + else + { + log("Unsupported parameter", + entry("PARAM=0x%x", reqptr->parameter)); rc = IPMI_CC_PARM_NOT_SUPPORTED; } @@ -1623,24 +1621,25 @@ void register_netfn_chassis_functions() createIdentifyTimer(); // - ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_WILDCARD, NULL, ipmi_chassis_wildcard, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_WILDCARD, NULL, + ipmi_chassis_wildcard, PRIVILEGE_USER); // Get Chassis Capabilities - ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_GET_CHASSIS_CAP, NULL, ipmi_get_chassis_cap, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_GET_CHASSIS_CAP, NULL, + ipmi_get_chassis_cap, PRIVILEGE_USER); // ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_GET_SYS_BOOT_OPTIONS, NULL, - ipmi_chassis_get_sys_boot_options, PRIVILEGE_OPERATOR); + ipmi_chassis_get_sys_boot_options, + PRIVILEGE_OPERATOR); // - ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_CHASSIS_STATUS, NULL, ipmi_get_chassis_status, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_CHASSIS_STATUS, NULL, + ipmi_get_chassis_status, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_CHASSIS_CONTROL, NULL, ipmi_chassis_control, - PRIVILEGE_OPERATOR); + ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_CHASSIS_CONTROL, NULL, + ipmi_chassis_control, PRIVILEGE_OPERATOR); // ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_CHASSIS_IDENTIFY, NULL, @@ -1648,7 +1647,8 @@ void register_netfn_chassis_functions() // ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_SET_SYS_BOOT_OPTIONS, NULL, - ipmi_chassis_set_sys_boot_options, PRIVILEGE_OPERATOR); + ipmi_chassis_set_sys_boot_options, + PRIVILEGE_OPERATOR); // ipmi_register_callback(NETFUN_CHASSIS, IPMI_CMD_GET_POH_COUNTER, NULL, ipmiGetPOHCounter, PRIVILEGE_USER); diff --git a/chassishandler.h b/chassishandler.h index fa7ad5d..edbac89 100644 --- a/chassishandler.h +++ b/chassishandler.h @@ -2,21 +2,22 @@ #define __HOST_IPMI_CHASSIS_HANDLER_H__ #include + #include // IPMI commands for Chassis net functions. enum ipmi_netfn_chassis_cmds { - IPMI_CMD_GET_CHASSIS_CAP = 0x00, + IPMI_CMD_GET_CHASSIS_CAP = 0x00, // Chassis Status - IPMI_CMD_CHASSIS_STATUS = 0x01, + IPMI_CMD_CHASSIS_STATUS = 0x01, // Chassis Control - IPMI_CMD_CHASSIS_CONTROL = 0x02, - IPMI_CMD_CHASSIS_IDENTIFY = 0x04, + IPMI_CMD_CHASSIS_CONTROL = 0x02, + IPMI_CMD_CHASSIS_IDENTIFY = 0x04, // Get capability bits IPMI_CMD_SET_SYS_BOOT_OPTIONS = 0x08, IPMI_CMD_GET_SYS_BOOT_OPTIONS = 0x09, - IPMI_CMD_GET_POH_COUNTER = 0x0F, + IPMI_CMD_GET_POH_COUNTER = 0x0F, }; // Command specific completion codes @@ -36,24 +37,24 @@ enum ipmi_generic_return_codes // Various Chassis operations under a single command. enum ipmi_chassis_control_cmds : uint8_t { - CMD_POWER_OFF = 0x00, - CMD_POWER_ON = 0x01, - CMD_POWER_CYCLE = 0x02, - CMD_HARD_RESET = 0x03, - CMD_PULSE_DIAGNOSTIC_INTR = 0x04, - CMD_SOFT_OFF_VIA_OVER_TEMP = 0x05, + CMD_POWER_OFF = 0x00, + CMD_POWER_ON = 0x01, + CMD_POWER_CYCLE = 0x02, + CMD_HARD_RESET = 0x03, + CMD_PULSE_DIAGNOSTIC_INTR = 0x04, + CMD_SOFT_OFF_VIA_OVER_TEMP = 0x05, }; enum class BootOptionParameter : size_t { - BOOT_INFO = 0x4, - BOOT_FLAGS = 0x5, - OPAL_NETWORK_SETTINGS = 0x61 + BOOT_INFO = 0x4, + BOOT_FLAGS = 0x5, + OPAL_NETWORK_SETTINGS = 0x61 }; enum class BootOptionResponseSize : size_t { - BOOT_FLAGS = 5, - OPAL_NETWORK_SETTINGS = 50 + BOOT_FLAGS = 5, + OPAL_NETWORK_SETTINGS = 50 }; #endif diff --git a/dcmihandler.cpp b/dcmihandler.cpp index d4f0ff5..951b6ba 100644 --- a/dcmihandler.cpp +++ b/dcmihandler.cpp @@ -1,27 +1,32 @@ +#include "config.h" + #include "dcmihandler.hpp" -#include "host-ipmid/ipmid-api.h" -#include -#include -#include -#include + +#include "net.hpp" #include "utils.hpp" + +#include #include #include -#include -#include + #include #include -#include "xyz/openbmc_project/Common/error.hpp" -#include "config.h" -#include "net.hpp" +#include +#include +#include +#include +#include +#include + +#include "host-ipmid/ipmid-api.h" using namespace phosphor::logging; using InternalFailure = - sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; + sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; void register_netfn_dcmi_functions() __attribute__((constructor)); -constexpr auto PCAP_PATH = "/xyz/openbmc_project/control/host0/power_cap"; +constexpr auto PCAP_PATH = "/xyz/openbmc_project/control/host0/power_cap"; constexpr auto PCAP_INTERFACE = "xyz.openbmc_project.Control.Power.Cap"; constexpr auto POWER_CAP_PROP = "PowerCap"; @@ -38,10 +43,10 @@ constexpr auto DCMI_ACTIVATE_DHCP_MASK = 0x01; constexpr auto DCMI_ACTIVATE_DHCP_REPLY = 0x00; constexpr auto DCMI_SET_CONF_PARAM_REQ_PACKET_MAX_SIZE = 0x05; constexpr auto DCMI_SET_CONF_PARAM_REQ_PACKET_MIN_SIZE = 0x04; -constexpr auto DHCP_TIMING1 = 0x04; // 4 sec -constexpr auto DHCP_TIMING2_UPPER = 0x00; //2 min +constexpr auto DHCP_TIMING1 = 0x04; // 4 sec +constexpr auto DHCP_TIMING2_UPPER = 0x00; // 2 min constexpr auto DHCP_TIMING2_LOWER = 0x78; -constexpr auto DHCP_TIMING3_UPPER = 0x00; //64 sec +constexpr auto DHCP_TIMING3_UPPER = 0x00; // 64 sec constexpr auto DHCP_TIMING3_LOWER = 0x40; // When DHCP Option 12 is enabled the string "SendHostName=true" will be // added into n/w configuration file and the parameter @@ -60,26 +65,16 @@ namespace dcmi { // Refer Table 6-14, DCMI Entity ID Extension, DCMI v1.5 spec -static const std::map entityIdToName -{ - {0x40, "inlet"}, - {0x37, "inlet"}, - {0x41, "cpu"}, - {0x03, "cpu"}, - {0x42, "baseboard"}, - {0x07, "baseboard"} -}; - +static const std::map entityIdToName{ + {0x40, "inlet"}, {0x37, "inlet"}, {0x41, "cpu"}, + {0x03, "cpu"}, {0x42, "baseboard"}, {0x07, "baseboard"}}; uint32_t getPcap(sdbusplus::bus::bus& bus) { - auto settingService = ipmi::getService(bus, - PCAP_INTERFACE,PCAP_PATH); + auto settingService = ipmi::getService(bus, PCAP_INTERFACE, PCAP_PATH); - auto method = bus.new_method_call(settingService.c_str(), - PCAP_PATH, - "org.freedesktop.DBus.Properties", - "Get"); + auto method = bus.new_method_call(settingService.c_str(), PCAP_PATH, + "org.freedesktop.DBus.Properties", "Get"); method.append(PCAP_INTERFACE, POWER_CAP_PROP); auto reply = bus.call(method); @@ -97,13 +92,10 @@ uint32_t getPcap(sdbusplus::bus::bus& bus) bool getPcapEnabled(sdbusplus::bus::bus& bus) { - auto settingService = ipmi::getService(bus, - PCAP_INTERFACE,PCAP_PATH); + auto settingService = ipmi::getService(bus, PCAP_INTERFACE, PCAP_PATH); - auto method = bus.new_method_call(settingService.c_str(), - PCAP_PATH, - "org.freedesktop.DBus.Properties", - "Get"); + auto method = bus.new_method_call(settingService.c_str(), PCAP_PATH, + "org.freedesktop.DBus.Properties", "Get"); method.append(PCAP_INTERFACE, POWER_CAP_ENABLE_PROP); auto reply = bus.call(method); @@ -123,10 +115,8 @@ void setPcap(sdbusplus::bus::bus& bus, const uint32_t powerCap) { auto service = ipmi::getService(bus, PCAP_INTERFACE, PCAP_PATH); - auto method = bus.new_method_call(service.c_str(), - PCAP_PATH, - "org.freedesktop.DBus.Properties", - "Set"); + auto method = bus.new_method_call(service.c_str(), PCAP_PATH, + "org.freedesktop.DBus.Properties", "Set"); method.append(PCAP_INTERFACE, POWER_CAP_PROP); method.append(sdbusplus::message::variant(powerCap)); @@ -144,10 +134,8 @@ void setPcapEnable(sdbusplus::bus::bus& bus, bool enabled) { auto service = ipmi::getService(bus, PCAP_INTERFACE, PCAP_PATH); - auto method = bus.new_method_call(service.c_str(), - PCAP_PATH, - "org.freedesktop.DBus.Properties", - "Set"); + auto method = bus.new_method_call(service.c_str(), PCAP_PATH, + "org.freedesktop.DBus.Properties", "Set"); method.append(PCAP_INTERFACE, POWER_CAP_ENABLE_PROP); method.append(sdbusplus::message::variant(enabled)); @@ -171,10 +159,8 @@ void readAssetTagObjectTree(dcmi::assettag::ObjectTree& objectTree) sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; auto depth = 0; - auto mapperCall = bus.new_method_call(mapperBusName, - mapperObjPath, - mapperIface, - "GetSubTree"); + auto mapperCall = bus.new_method_call(mapperBusName, mapperObjPath, + mapperIface, "GetSubTree"); mapperCall.append(inventoryRoot); mapperCall.append(depth); @@ -206,10 +192,8 @@ std::string readAssetTag() readAssetTagObjectTree(objectTree); auto method = bus.new_method_call( - (objectTree.begin()->second.begin()->first).c_str(), - (objectTree.begin()->first).c_str(), - dcmi::propIntf, - "Get"); + (objectTree.begin()->second.begin()->first).c_str(), + (objectTree.begin()->first).c_str(), dcmi::propIntf, "Get"); method.append(dcmi::assetTagIntf); method.append(dcmi::assetTagProp); @@ -236,10 +220,8 @@ void writeAssetTag(const std::string& assetTag) readAssetTagObjectTree(objectTree); auto method = bus.new_method_call( - (objectTree.begin()->second.begin()->first).c_str(), - (objectTree.begin()->first).c_str(), - dcmi::propIntf, - "Set"); + (objectTree.begin()->second.begin()->first).c_str(), + (objectTree.begin()->first).c_str(), dcmi::propIntf, "Set"); method.append(dcmi::assetTagIntf); method.append(dcmi::assetTagProp); method.append(sdbusplus::message::variant(assetTag)); @@ -254,11 +236,11 @@ void writeAssetTag(const std::string& assetTag) std::string getHostName(void) { - sdbusplus::bus::bus bus{ ipmid_get_sd_bus_connection() }; + sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; auto service = ipmi::getService(bus, networkConfigIntf, networkConfigObj); - auto value = ipmi::getDbusProperty(bus, service, - networkConfigObj, networkConfigIntf, hostNameProp); + auto value = ipmi::getDbusProperty(bus, service, networkConfigObj, + networkConfigIntf, hostNameProp); return value.get(); } @@ -267,13 +249,13 @@ bool getDHCPEnabled() { sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; - auto ethdevice = ipmi::network::ChanneltoEthernet( - ethernetDefaultChannelNum); - auto ethernetObj = ipmi::getDbusObject(bus, ethernetIntf, networkRoot, - ethdevice); + auto ethdevice = + ipmi::network::ChanneltoEthernet(ethernetDefaultChannelNum); + auto ethernetObj = + ipmi::getDbusObject(bus, ethernetIntf, networkRoot, ethdevice); auto service = ipmi::getService(bus, ethernetIntf, ethernetObj.first); - auto value = ipmi::getDbusProperty(bus, service, - ethernetObj.first, ethernetIntf, "DHCPEnabled"); + auto value = ipmi::getDbusProperty(bus, service, ethernetObj.first, + ethernetIntf, "DHCPEnabled"); return value.get(); } @@ -288,7 +270,6 @@ bool getDHCPOption(std::string prop) return value.get(); } - void setDHCPOption(std::string prop, bool value) { sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; @@ -322,11 +303,11 @@ ipmi_ret_t getPowerLimit(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { - auto requestData = reinterpret_cast - (request); + auto requestData = + reinterpret_cast(request); std::vector outPayload(sizeof(dcmi::GetPowerLimitResponse)); - auto responseData = reinterpret_cast - (outPayload.data()); + auto responseData = + reinterpret_cast(outPayload.data()); if (requestData->groupID != dcmi::groupExtId) { @@ -334,7 +315,7 @@ ipmi_ret_t getPowerLimit(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return IPMI_CC_INVALID_FIELD_REQUEST; } - sdbusplus::bus::bus sdbus {ipmid_get_sd_bus_connection()}; + sdbusplus::bus::bus sdbus{ipmid_get_sd_bus_connection()}; uint32_t pcapValue = 0; bool pcapEnable = false; @@ -383,11 +364,11 @@ ipmi_ret_t setPowerLimit(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { - auto requestData = reinterpret_cast - (request); + auto requestData = + reinterpret_cast(request); std::vector outPayload(sizeof(dcmi::SetPowerLimitResponse)); - auto responseData = reinterpret_cast - (outPayload.data()); + auto responseData = + reinterpret_cast(outPayload.data()); if (requestData->groupID != dcmi::groupExtId) { @@ -395,7 +376,7 @@ ipmi_ret_t setPowerLimit(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return IPMI_CC_INVALID_FIELD_REQUEST; } - sdbusplus::bus::bus sdbus {ipmid_get_sd_bus_connection()}; + sdbusplus::bus::bus sdbus{ipmid_get_sd_bus_connection()}; // Only process the power limit requested in watts. try @@ -422,11 +403,11 @@ ipmi_ret_t applyPowerLimit(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { - auto requestData = reinterpret_cast - (request); + auto requestData = + reinterpret_cast(request); std::vector outPayload(sizeof(dcmi::ApplyPowerLimitResponse)); - auto responseData = reinterpret_cast - (outPayload.data()); + auto responseData = + reinterpret_cast(outPayload.data()); if (requestData->groupID != dcmi::groupExtId) { @@ -434,7 +415,7 @@ ipmi_ret_t applyPowerLimit(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return IPMI_CC_INVALID_FIELD_REQUEST; } - sdbusplus::bus::bus sdbus {ipmid_get_sd_bus_connection()}; + sdbusplus::bus::bus sdbus{ipmid_get_sd_bus_connection()}; try { @@ -461,11 +442,11 @@ ipmi_ret_t getAssetTag(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { - auto requestData = reinterpret_cast - (request); + auto requestData = + reinterpret_cast(request); std::vector outPayload(sizeof(dcmi::GetAssetTagResponse)); - auto responseData = reinterpret_cast - (outPayload.data()); + auto responseData = + reinterpret_cast(outPayload.data()); if (requestData->groupID != dcmi::groupExtId) { @@ -536,11 +517,11 @@ ipmi_ret_t setAssetTag(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { - auto requestData = reinterpret_cast - (request); + auto requestData = + reinterpret_cast(request); std::vector outPayload(sizeof(dcmi::SetAssetTagResponse)); - auto responseData = reinterpret_cast - (outPayload.data()); + auto responseData = + reinterpret_cast(outPayload.data()); if (requestData->groupID != dcmi::groupExtId) { @@ -573,7 +554,7 @@ ipmi_ret_t setAssetTag(ipmi_netfn_t netfn, ipmi_cmd_t cmd, assetTag.replace(requestData->offset, assetTag.size() - requestData->offset, static_cast(request) + - sizeof(dcmi::SetAssetTagRequest), + sizeof(dcmi::SetAssetTagRequest), requestData->bytes); dcmi::writeAssetTag(assetTag); @@ -593,13 +574,13 @@ ipmi_ret_t setAssetTag(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } ipmi_ret_t getMgmntCtrlIdStr(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, ipmi_response_t response, + ipmi_data_len_t data_len, ipmi_context_t context) { - auto requestData = reinterpret_cast - (request); - auto responseData = reinterpret_cast - (response); + auto requestData = + reinterpret_cast(request); + auto responseData = + reinterpret_cast(response); std::string hostName; *data_len = 0; @@ -626,7 +607,7 @@ ipmi_ret_t getMgmntCtrlIdStr(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } auto responseStr = hostName.substr(requestData->offset, requestData->bytes); auto responseStrLen = std::min(static_cast(requestData->bytes), - responseStr.length() + 1); + responseStr.length() + 1); responseData->groupID = dcmi::groupExtId; responseData->strLen = hostName.length(); std::copy(begin(responseStr), end(responseStr), responseData->data); @@ -636,23 +617,24 @@ ipmi_ret_t getMgmntCtrlIdStr(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } ipmi_ret_t setMgmntCtrlIdStr(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, ipmi_response_t response, + ipmi_data_len_t data_len, ipmi_context_t context) { static std::array newCtrlIdStr; - auto requestData = reinterpret_cast - (request); - auto responseData = reinterpret_cast - (response); + auto requestData = + reinterpret_cast(request); + auto responseData = + reinterpret_cast(response); *data_len = 0; if (requestData->groupID != dcmi::groupExtId || requestData->bytes > dcmi::maxBytes || requestData->offset + requestData->bytes > dcmi::maxCtrlIdStrLen + 1 || - (requestData->offset + requestData->bytes == dcmi::maxCtrlIdStrLen + 1 && - requestData->data[requestData->bytes - 1] != '\0')) + (requestData->offset + requestData->bytes == + dcmi::maxCtrlIdStrLen + 1 && + requestData->data[requestData->bytes - 1] != '\0')) { return IPMI_CC_INVALID_FIELD_REQUEST; } @@ -670,8 +652,9 @@ ipmi_ret_t setMgmntCtrlIdStr(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } /* replace part of string and mark byte after the last as \0 */ - auto restStrIter = std::copy_n(requestData->data, - requestData->bytes, begin(newCtrlIdStr) + requestData->offset); + auto restStrIter = + std::copy_n(requestData->data, requestData->bytes, + begin(newCtrlIdStr) + requestData->offset); /* if the last written byte is not 64th - add '\0' */ if (requestData->offset + requestData->bytes <= dcmi::maxCtrlIdStrLen) { @@ -680,13 +663,14 @@ ipmi_ret_t setMgmntCtrlIdStr(ipmi_netfn_t netfn, ipmi_cmd_t cmd, /* if input data contains '\0' whole string is sent - update hostname */ auto it = std::find(requestData->data, - requestData->data + requestData->bytes, '\0'); + requestData->data + requestData->bytes, '\0'); if (it != requestData->data + requestData->bytes) { - sdbusplus::bus::bus bus{ ipmid_get_sd_bus_connection() }; + sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; ipmi::setDbusProperty(bus, dcmi::networkServiceName, - dcmi::networkConfigObj, dcmi::networkConfigIntf, - dcmi::hostNameProp, std::string(newCtrlIdStr.data())); + dcmi::networkConfigObj, + dcmi::networkConfigIntf, dcmi::hostNameProp, + std::string(newCtrlIdStr.data())); } } catch (InternalFailure& e) @@ -701,53 +685,35 @@ ipmi_ret_t setMgmntCtrlIdStr(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return IPMI_CC_OK; } -//List of the capabilities under each parameter -dcmi::DCMICaps dcmiCaps = -{ -//Supported DCMI Capabilities - { - dcmi::DCMICapParameters::SUPPORTED_DCMI_CAPS, - { - 3, {{"PowerManagement", 2, 0, 1}, - {"OOBSecondaryLan", 3, 2, 1}, - {"SerialTMODE", 3, 1, 1}, - {"InBandSystemInterfaceChannel", 3, 0, 1} - } - } - }, -//Mandatory Platform Attributes - { - dcmi::DCMICapParameters::MANDATORY_PLAT_ATTRIBUTES, - { - 5, {{"SELAutoRollOver", 1, 15, 1}, - {"FlushEntireSELUponRollOver", 1, 14, 1}, - {"RecordLevelSELFlushUponRollOver", 1, 13, 1}, - {"NumberOfSELEntries", 1, 0, 12}, - {"TempMonitoringSamplingFreq", 5, 0, 8} - } - } - }, -//Optional Platform Attributes - { - dcmi::DCMICapParameters::OPTIONAL_PLAT_ATTRIBUTES, - { - 2, {{"PowerMgmtDeviceSlaveAddress", 1, 1, 7}, - {"BMCChannelNumber", 2, 4, 4}, - {"DeviceRivision", 2, 0, 4} - } - } - }, -//Manageability Access Attributes - { - dcmi::DCMICapParameters::MANAGEABILITY_ACCESS_ATTRIBUTES, - { - 3, {{"MandatoryPrimaryLanOOBSupport", 1, 0, 8}, - {"OptionalSecondaryLanOOBSupport", 2, 0, 8}, - {"OptionalSerialOOBMTMODECapability", 3, 0, 8} - } - } - } -}; +// List of the capabilities under each parameter +dcmi::DCMICaps dcmiCaps = { + // Supported DCMI Capabilities + {dcmi::DCMICapParameters::SUPPORTED_DCMI_CAPS, + {3, + {{"PowerManagement", 2, 0, 1}, + {"OOBSecondaryLan", 3, 2, 1}, + {"SerialTMODE", 3, 1, 1}, + {"InBandSystemInterfaceChannel", 3, 0, 1}}}}, + // Mandatory Platform Attributes + {dcmi::DCMICapParameters::MANDATORY_PLAT_ATTRIBUTES, + {5, + {{"SELAutoRollOver", 1, 15, 1}, + {"FlushEntireSELUponRollOver", 1, 14, 1}, + {"RecordLevelSELFlushUponRollOver", 1, 13, 1}, + {"NumberOfSELEntries", 1, 0, 12}, + {"TempMonitoringSamplingFreq", 5, 0, 8}}}}, + // Optional Platform Attributes + {dcmi::DCMICapParameters::OPTIONAL_PLAT_ATTRIBUTES, + {2, + {{"PowerMgmtDeviceSlaveAddress", 1, 1, 7}, + {"BMCChannelNumber", 2, 4, 4}, + {"DeviceRivision", 2, 0, 4}}}}, + // Manageability Access Attributes + {dcmi::DCMICapParameters::MANAGEABILITY_ACCESS_ATTRIBUTES, + {3, + {{"MandatoryPrimaryLanOOBSupport", 1, 0, 8}, + {"OptionalSecondaryLanOOBSupport", 2, 0, 8}, + {"OptionalSerialOOBMTMODECapability", 3, 0, 8}}}}}; ipmi_ret_t getDCMICapabilities(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, @@ -768,10 +734,10 @@ ipmi_ret_t getDCMICapabilities(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return IPMI_CC_UNSPECIFIED_ERROR; } - auto requestData = reinterpret_cast - (request); + auto requestData = + reinterpret_cast(request); - //get list of capabilities in a parameter + // get list of capabilities in a parameter auto caps = dcmiCaps.find(static_cast(requestData->param)); if (caps == dcmiCaps.end()) @@ -786,24 +752,25 @@ ipmi_ret_t getDCMICapabilities(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return IPMI_CC_INVALID_FIELD_REQUEST; } - auto responseData = reinterpret_cast - (response); + auto responseData = reinterpret_cast(response); - //For each capabilities in a parameter fill the data from - //the json file based on the capability name. + // For each capabilities in a parameter fill the data from + // the json file based on the capability name. for (auto cap : caps->second.capList) { - //If the data is beyond first byte boundary, insert in a - //16bit pattern for example number of SEL entries are represented - //in 12bits. + // If the data is beyond first byte boundary, insert in a + // 16bit pattern for example number of SEL entries are represented + // in 12bits. if ((cap.length + cap.position) > 8) { - //Read the value corresponding to capability name and assign to - //16bit bitset. + // Read the value corresponding to capability name and assign to + // 16bit bitset. std::bitset<16> val(data.value(cap.name.c_str(), 0)); val <<= cap.position; - reinterpret_cast(responseData->data)[ - (cap.bytePosition - 1) / sizeof(uint16_t)] |= val.to_ulong(); + reinterpret_cast( + responseData + ->data)[(cap.bytePosition - 1) / sizeof(uint16_t)] |= + val.to_ulong(); } else { @@ -836,8 +803,8 @@ Temperature readTemp(const std::string& dbusService, // with a separate single bit for the sign. sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; - auto result = ipmi::getAllDbusProperties(bus, dbusService, dbusPath, - "xyz.openbmc_project.Sensor.Value"); + auto result = ipmi::getAllDbusProperties( + bus, dbusService, dbusPath, "xyz.openbmc_project.Sensor.Value"); auto temperature = result.at("Value").get(); uint64_t absTemp = std::abs(temperature); @@ -845,8 +812,7 @@ Temperature readTemp(const std::string& dbusService, uint64_t scale = std::pow(10, factor); // pow() returns float/double unsigned long long tempDegrees = 0; // Overflow safe multiplication when the scale is > 0 - if (scale && __builtin_umulll_overflow( - absTemp, scale, &tempDegrees)) + if (scale && __builtin_umulll_overflow(absTemp, scale, &tempDegrees)) { log("Multiplication overflow detected", entry("TEMP_VALUE=%llu", absTemp), @@ -898,9 +864,7 @@ std::tuple read(const std::string& type, try { service = - ipmi::getService(bus, - "xyz.openbmc_project.Sensor.Value", - path); + ipmi::getService(bus, "xyz.openbmc_project.Sensor.Value", path); } catch (std::exception& e) { @@ -956,9 +920,7 @@ std::tuple readAll(const std::string& type, std::string path = j.value("dbus", ""); auto service = - ipmi::getService(bus, - "xyz.openbmc_project.Sensor.Value", - path); + ipmi::getService(bus, "xyz.openbmc_project.Sensor.Value", path); Response r{}; r.instance = instanceNum; @@ -983,12 +945,12 @@ std::tuple readAll(const std::string& type, return std::make_tuple(response, numInstances); } -} // namsespace temp_readings -} // namsepace dcmi +} // namespace temp_readings +} // namespace dcmi ipmi_ret_t getTempReadings(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, ipmi_response_t response, + ipmi_data_len_t data_len, ipmi_context_t context) { auto requestData = reinterpret_cast(request); @@ -1051,13 +1013,11 @@ ipmi_ret_t getTempReadings(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } responseData->groupID = dcmi::groupExtId; - size_t payloadSize = - temps.size() * sizeof(dcmi::temp_readings::Response); + size_t payloadSize = temps.size() * sizeof(dcmi::temp_readings::Response); if (!temps.empty()) { memcpy(responseData + 1, // copy payload right after the response header - temps.data(), - payloadSize); + temps.data(), payloadSize); } *data_len = sizeof(dcmi::GetTempReadingsResponseHdr) + payloadSize; @@ -1071,7 +1031,7 @@ int64_t getPowerReading(sdbusplus::bus::bus& bus) if (!sensorFile.is_open()) { log("Power reading configuration file not found", - entry("POWER_SENSOR_FILE=%s", POWER_READING_SENSOR)); + entry("POWER_SENSOR_FILE=%s", POWER_READING_SENSOR)); elog(); } @@ -1079,7 +1039,7 @@ int64_t getPowerReading(sdbusplus::bus::bus& bus) if (data.is_discarded()) { log("Error in parsing configuration file", - entry("POWER_SENSOR_FILE=%s", POWER_READING_SENSOR)); + entry("POWER_SENSOR_FILE=%s", POWER_READING_SENSOR)); elog(); } @@ -1097,9 +1057,9 @@ int64_t getPowerReading(sdbusplus::bus::bus& bus) { auto service = ipmi::getService(bus, SENSOR_VALUE_INTF, objectPath); - //Read the sensor value and scale properties - auto properties = ipmi::getAllDbusProperties( - bus, service, objectPath, SENSOR_VALUE_INTF); + // Read the sensor value and scale properties + auto properties = ipmi::getAllDbusProperties(bus, service, objectPath, + SENSOR_VALUE_INTF); auto value = properties[SENSOR_VALUE_PROP].get(); auto scale = properties[SENSOR_SCALE_PROP].get(); @@ -1110,8 +1070,8 @@ int64_t getPowerReading(sdbusplus::bus::bus& bus) catch (std::exception& e) { log("Failure to read power value from D-Bus object", - entry("OBJECT_PATH=%s", objectPath.c_str()), - entry("INTERFACE=%s", SENSOR_VALUE_INTF)); + entry("OBJECT_PATH=%s", objectPath.c_str()), + entry("INTERFACE=%s", SENSOR_VALUE_INTF)); } return power; } @@ -1120,15 +1080,14 @@ ipmi_ret_t setDCMIConfParams(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { - auto requestData = reinterpret_cast - (request); - auto responseData = reinterpret_cast - (response); - + auto requestData = + reinterpret_cast(request); + auto responseData = + reinterpret_cast(response); - if (requestData->groupID != dcmi::groupExtId || *data_len < - DCMI_SET_CONF_PARAM_REQ_PACKET_MIN_SIZE || *data_len > - DCMI_SET_CONF_PARAM_REQ_PACKET_MAX_SIZE) + if (requestData->groupID != dcmi::groupExtId || + *data_len < DCMI_SET_CONF_PARAM_REQ_PACKET_MIN_SIZE || + *data_len > DCMI_SET_CONF_PARAM_REQ_PACKET_MAX_SIZE) { log("Invalid Group ID or Invalid Requested Packet size", entry("GROUP_ID=%d", requestData->groupID), @@ -1141,19 +1100,19 @@ ipmi_ret_t setDCMIConfParams(ipmi_netfn_t netfn, ipmi_cmd_t cmd, try { // Take action based on the Parameter Selector - switch (static_cast( - requestData->paramSelect)) + switch ( + static_cast(requestData->paramSelect)) { case dcmi::DCMIConfigParameters::ActivateDHCP: if ((requestData->data[0] & DCMI_ACTIVATE_DHCP_MASK) && - dcmi::getDHCPEnabled()) + dcmi::getDHCPEnabled()) { - // When these conditions are met we have to trigger DHCP - // protocol restart using the latest parameter settings, but - // as per n/w manager design, each time when we update n/w - // parameters, n/w service is restarted. So we no need to take - // any action in this case. + // When these conditions are met we have to trigger DHCP + // protocol restart using the latest parameter settings, but + // as per n/w manager design, each time when we update n/w + // parameters, n/w service is restarted. So we no need to + // take any action in this case. } break; @@ -1198,15 +1157,15 @@ ipmi_ret_t getDCMIConfParams(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_data_len_t data_len, ipmi_context_t context) { - auto requestData = reinterpret_cast - (request); - auto responseData = reinterpret_cast - (response); + auto requestData = + reinterpret_cast(request); + auto responseData = + reinterpret_cast(response); responseData->data[0] = 0x00; - if (requestData->groupID != dcmi::groupExtId || *data_len != sizeof( - dcmi::GetConfParamsRequest)) + if (requestData->groupID != dcmi::groupExtId || + *data_len != sizeof(dcmi::GetConfParamsRequest)) { log("Invalid Group ID or Invalid Requested Packet size", entry("GROUP_ID=%d", requestData->groupID), @@ -1219,8 +1178,8 @@ ipmi_ret_t getDCMIConfParams(ipmi_netfn_t netfn, ipmi_cmd_t cmd, try { // Take action based on the Parameter Selector - switch (static_cast( - requestData->paramSelect)) + switch ( + static_cast(requestData->paramSelect)) { case dcmi::DCMIConfigParameters::ActivateDHCP: responseData->data[0] = DCMI_ACTIVATE_DHCP_REPLY; @@ -1267,16 +1226,15 @@ ipmi_ret_t getDCMIConfParams(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return IPMI_CC_OK; } - ipmi_ret_t getPowerReading(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, ipmi_response_t response, + ipmi_data_len_t data_len, ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; - auto requestData = reinterpret_cast - (request); - auto responseData = reinterpret_cast - (response); + auto requestData = + reinterpret_cast(request); + auto responseData = + reinterpret_cast(response); if (requestData->groupID != dcmi::groupExtId) { @@ -1328,8 +1286,7 @@ Response createFromJson(const Json& config) } std::tuple read(const std::string& type, - uint8_t instance, - const Json& config) + uint8_t instance, const Json& config) { Response response{}; @@ -1366,9 +1323,8 @@ std::tuple read(const std::string& type, return std::make_tuple(response, numInstances); } -std::tuple readAll(const std::string& type, - uint8_t instanceStart, - const Json& config) +std::tuple + readAll(const std::string& type, uint8_t instanceStart, const Json& config) { ResponseList responses{}; @@ -1471,16 +1427,14 @@ ipmi_ret_t getSensorInfo(ipmi_netfn_t netfn, ipmi_cmd_t cmd, // Read all instances std::tie(sensors, responseData->numInstances) = dcmi::sensor_info::readAll(it->second, - requestData->instanceStart, - config); + requestData->instanceStart, config); } else { // Read one instance sensors.resize(1); std::tie(sensors[0], responseData->numInstances) = - dcmi::sensor_info::read(it->second, - requestData->entityInstance, + dcmi::sensor_info::read(it->second, requestData->entityInstance, config); } responseData->numRecords = sensors.size(); @@ -1495,8 +1449,7 @@ ipmi_ret_t getSensorInfo(ipmi_netfn_t netfn, ipmi_cmd_t cmd, if (!sensors.empty()) { memcpy(responseData + 1, // copy payload right after the response header - sensors.data(), - payloadSize); + sensors.data(), payloadSize); } *data_len = sizeof(dcmi::GetSensorInfoResponseHdr) + payloadSize; @@ -1507,13 +1460,13 @@ void register_netfn_dcmi_functions() { // - ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::GET_POWER_LIMIT, - NULL, getPowerLimit, PRIVILEGE_USER); + ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::GET_POWER_LIMIT, NULL, + getPowerLimit, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::SET_POWER_LIMIT, - NULL, setPowerLimit, PRIVILEGE_OPERATOR); + ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::SET_POWER_LIMIT, NULL, + setPowerLimit, PRIVILEGE_OPERATOR); // @@ -1522,26 +1475,26 @@ void register_netfn_dcmi_functions() // - ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::GET_ASSET_TAG, - NULL, getAssetTag, PRIVILEGE_USER); + ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::GET_ASSET_TAG, NULL, + getAssetTag, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::SET_ASSET_TAG, - NULL, setAssetTag, PRIVILEGE_OPERATOR); + ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::SET_ASSET_TAG, NULL, + setAssetTag, PRIVILEGE_OPERATOR); // ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::GET_MGMNT_CTRL_ID_STR, - NULL, getMgmntCtrlIdStr, PRIVILEGE_USER); + NULL, getMgmntCtrlIdStr, PRIVILEGE_USER); // ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::SET_MGMNT_CTRL_ID_STR, - NULL, setMgmntCtrlIdStr, PRIVILEGE_ADMIN); + NULL, setMgmntCtrlIdStr, PRIVILEGE_ADMIN); // ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::GET_CAPABILITIES, - NULL, getDCMICapabilities, PRIVILEGE_USER); + NULL, getDCMICapabilities, PRIVILEGE_USER); // ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::GET_TEMP_READINGS, @@ -1552,16 +1505,16 @@ void register_netfn_dcmi_functions() NULL, getPowerReading, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::GET_SENSOR_INFO, - NULL, getSensorInfo, PRIVILEGE_USER); + ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::GET_SENSOR_INFO, NULL, + getSensorInfo, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::GET_CONF_PARAMS, - NULL, getDCMIConfParams, PRIVILEGE_USER); + ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::GET_CONF_PARAMS, NULL, + getDCMIConfParams, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::SET_CONF_PARAMS, - NULL, setDCMIConfParams, PRIVILEGE_ADMIN); + ipmi_register_callback(NETFUN_GRPEXT, dcmi::Commands::SET_CONF_PARAMS, NULL, + setDCMIConfParams, PRIVILEGE_ADMIN); return; } diff --git a/dcmihandler.hpp b/dcmihandler.hpp index 5388344..6e64faf 100644 --- a/dcmihandler.hpp +++ b/dcmihandler.hpp @@ -1,11 +1,12 @@ #ifndef __HOST_IPMI_DCMI_HANDLER_H__ #define __HOST_IPMI_DCMI_HANDLER_H__ +#include "nlohmann/json.hpp" + #include +#include #include #include -#include -#include "nlohmann/json.hpp" namespace dcmi { @@ -33,25 +34,24 @@ enum Commands static constexpr auto propIntf = "org.freedesktop.DBus.Properties"; static constexpr auto assetTagIntf = - "xyz.openbmc_project.Inventory.Decorator.AssetTag"; + "xyz.openbmc_project.Inventory.Decorator.AssetTag"; static constexpr auto assetTagProp = "AssetTag"; static constexpr auto networkServiceName = "xyz.openbmc_project.Network"; -static constexpr auto networkConfigObj = - "/xyz/openbmc_project/network/config"; +static constexpr auto networkConfigObj = "/xyz/openbmc_project/network/config"; static constexpr auto networkConfigIntf = - "xyz.openbmc_project.Network.SystemConfiguration"; + "xyz.openbmc_project.Network.SystemConfiguration"; static constexpr auto hostNameProp = "HostName"; static constexpr auto temperatureSensorType = 0x01; static constexpr auto maxInstances = 255; static constexpr auto configFile = "/usr/share/ipmi-providers/dcmi_sensors.json"; static constexpr auto ethernetIntf = - "xyz.openbmc_project.Network.EthernetInterface"; + "xyz.openbmc_project.Network.EthernetInterface"; static constexpr auto ethernetDefaultChannelNum = 0x1; static constexpr auto networkRoot = "/xyz/openbmc_project/network"; static constexpr auto dhcpObj = "/xyz/openbmc_project/network/config/dhcp"; static constexpr auto dhcpIntf = - "xyz.openbmc_project.Network.DHCPConfiguration"; + "xyz.openbmc_project.Network.DHCPConfiguration"; static constexpr auto systemBusName = "org.freedesktop.systemd1"; static constexpr auto systemPath = "/org/freedesktop/systemd1"; static constexpr auto systemIntf = "org.freedesktop.systemd1.Manager"; @@ -59,56 +59,56 @@ static constexpr auto systemIntf = "org.freedesktop.systemd1.Manager"; namespace assettag { - using ObjectPath = std::string; - using Service = std::string; - using Interfaces = std::vector; - using ObjectTree = std::map>; +using ObjectPath = std::string; +using Service = std::string; +using Interfaces = std::vector; +using ObjectTree = std::map>; -} //namespace assettag +} // namespace assettag namespace temp_readings { - static constexpr auto maxDataSets = 8; - static constexpr auto maxTemp = 127; // degrees C +static constexpr auto maxDataSets = 8; +static constexpr auto maxTemp = 127; // degrees C - /** @struct Response - * - * DCMI payload for Get Temperature Readings response - */ - struct Response - { +/** @struct Response + * + * DCMI payload for Get Temperature Readings response + */ +struct Response +{ #if BYTE_ORDER == LITTLE_ENDIAN - uint8_t temperature: 7; //!< Temperature reading in Celsius - uint8_t sign: 1; //!< Sign bit + uint8_t temperature : 7; //!< Temperature reading in Celsius + uint8_t sign : 1; //!< Sign bit #endif #if BYTE_ORDER == BIG_ENDIAN - uint8_t sign: 1; //!< Sign bit - uint8_t temperature: 7; //!< Temperature reading in Celsius + uint8_t sign : 1; //!< Sign bit + uint8_t temperature : 7; //!< Temperature reading in Celsius #endif - uint8_t instance; //!< Entity instance number - } __attribute__((packed)); + uint8_t instance; //!< Entity instance number +} __attribute__((packed)); - using ResponseList = std::vector; - using Value = uint8_t; - using Sign = bool; - using Temperature = std::tuple; -} +using ResponseList = std::vector; +using Value = uint8_t; +using Sign = bool; +using Temperature = std::tuple; +} // namespace temp_readings namespace sensor_info { - static constexpr auto maxRecords = 8; +static constexpr auto maxRecords = 8; - /** @struct Response - * - * DCMI payload for Get Sensor Info response - */ - struct Response - { - uint8_t recordIdLsb; //!< SDR record id LS byte - uint8_t recordIdMsb; //!< SDR record id MS byte - } __attribute__((packed)); +/** @struct Response + * + * DCMI payload for Get Sensor Info response + */ +struct Response +{ + uint8_t recordIdLsb; //!< SDR record id LS byte + uint8_t recordIdMsb; //!< SDR record id MS byte +} __attribute__((packed)); - using ResponseList = std::vector; +using ResponseList = std::vector; } // namespace sensor_info static constexpr auto groupExtId = 0xDC; @@ -124,9 +124,9 @@ static constexpr size_t maxCtrlIdStrLen = 63; */ struct GetAssetTagRequest { - uint8_t groupID; //!< Group extension identification. - uint8_t offset; //!< Offset to read. - uint8_t bytes; //!< Number of bytes to read. + uint8_t groupID; //!< Group extension identification. + uint8_t offset; //!< Offset to read. + uint8_t bytes; //!< Number of bytes to read. } __attribute__((packed)); /** @struct GetAssetTagResponse @@ -135,8 +135,8 @@ struct GetAssetTagRequest */ struct GetAssetTagResponse { - uint8_t groupID; //!< Group extension identification. - uint8_t tagLength; //!< Total asset tag length. + uint8_t groupID; //!< Group extension identification. + uint8_t tagLength; //!< Total asset tag length. } __attribute__((packed)); /** @struct SetAssetTagRequest @@ -145,9 +145,9 @@ struct GetAssetTagResponse */ struct SetAssetTagRequest { - uint8_t groupID; //!< Group extension identification. - uint8_t offset; //!< Offset to write. - uint8_t bytes; //!< Number of bytes to write. + uint8_t groupID; //!< Group extension identification. + uint8_t offset; //!< Offset to write. + uint8_t bytes; //!< Number of bytes to write. } __attribute__((packed)); /** @struct SetAssetTagResponse @@ -156,8 +156,8 @@ struct SetAssetTagRequest */ struct SetAssetTagResponse { - uint8_t groupID; //!< Group extension identification. - uint8_t tagLength; //!< Total asset tag length. + uint8_t groupID; //!< Group extension identification. + uint8_t tagLength; //!< Total asset tag length. } __attribute__((packed)); /** @brief Read the object tree to fetch the object path that implemented the @@ -205,8 +205,8 @@ bool getPcapEnabled(sdbusplus::bus::bus& bus); */ struct GetPowerLimitRequest { - uint8_t groupID; //!< Group extension identification. - uint16_t reserved; //!< Reserved + uint8_t groupID; //!< Group extension identification. + uint16_t reserved; //!< Reserved } __attribute__((packed)); /** @struct GetPowerLimitResponse @@ -215,13 +215,13 @@ struct GetPowerLimitRequest */ struct GetPowerLimitResponse { - uint8_t groupID; //!< Group extension identification. - uint16_t reserved; //!< Reserved. - uint8_t exceptionAction; //!< Exception action. - uint16_t powerLimit; //!< Power limit requested in watts. - uint32_t correctionTime; //!< Correction time limit in milliseconds. - uint16_t reserved1; //!< Reserved. - uint16_t samplingPeriod; //!< Statistics sampling period in seconds. + uint8_t groupID; //!< Group extension identification. + uint16_t reserved; //!< Reserved. + uint8_t exceptionAction; //!< Exception action. + uint16_t powerLimit; //!< Power limit requested in watts. + uint32_t correctionTime; //!< Correction time limit in milliseconds. + uint16_t reserved1; //!< Reserved. + uint16_t samplingPeriod; //!< Statistics sampling period in seconds. } __attribute__((packed)); /** @brief Set the power cap value @@ -237,14 +237,14 @@ void setPcap(sdbusplus::bus::bus& bus, const uint32_t powerCap); */ struct SetPowerLimitRequest { - uint8_t groupID; //!< Group extension identification. - uint16_t reserved; //!< Reserved - uint8_t reserved1; //!< Reserved - uint8_t exceptionAction; //!< Exception action. - uint16_t powerLimit; //!< Power limit requested in watts. - uint32_t correctionTime; //!< Correction time limit in milliseconds. - uint16_t reserved2; //!< Reserved. - uint16_t samplingPeriod; //!< Statistics sampling period in seconds. + uint8_t groupID; //!< Group extension identification. + uint16_t reserved; //!< Reserved + uint8_t reserved1; //!< Reserved + uint8_t exceptionAction; //!< Exception action. + uint16_t powerLimit; //!< Power limit requested in watts. + uint32_t correctionTime; //!< Correction time limit in milliseconds. + uint16_t reserved2; //!< Reserved. + uint16_t samplingPeriod; //!< Statistics sampling period in seconds. } __attribute__((packed)); /** @struct SetPowerLimitResponse @@ -253,7 +253,7 @@ struct SetPowerLimitRequest */ struct SetPowerLimitResponse { - uint8_t groupID; //!< Group extension identification. + uint8_t groupID; //!< Group extension identification. } __attribute__((packed)); /** @brief Enable or disable the power capping @@ -269,9 +269,9 @@ void setPcapEnable(sdbusplus::bus::bus& bus, bool enabled); */ struct ApplyPowerLimitRequest { - uint8_t groupID; //!< Group extension identification. - uint8_t powerLimitAction; //!< Power limit activation - uint16_t reserved; //!< Reserved + uint8_t groupID; //!< Group extension identification. + uint8_t powerLimitAction; //!< Power limit activation + uint16_t reserved; //!< Reserved } __attribute__((packed)); /** @struct ApplyPowerLimitResponse @@ -280,7 +280,7 @@ struct ApplyPowerLimitRequest */ struct ApplyPowerLimitResponse { - uint8_t groupID; //!< Group extension identification. + uint8_t groupID; //!< Group extension identification. } __attribute__((packed)); /** @struct GetMgmntCtrlIdStrRequest @@ -289,9 +289,9 @@ struct ApplyPowerLimitResponse */ struct GetMgmntCtrlIdStrRequest { - uint8_t groupID; //!< Group extension identification. - uint8_t offset; //!< Offset to read. - uint8_t bytes; //!< Number of bytes to read. + uint8_t groupID; //!< Group extension identification. + uint8_t offset; //!< Offset to read. + uint8_t bytes; //!< Number of bytes to read. } __attribute__((packed)); /** @struct GetMgmntCtrlIdStrResponse @@ -300,9 +300,9 @@ struct GetMgmntCtrlIdStrRequest */ struct GetMgmntCtrlIdStrResponse { - uint8_t groupID; //!< Group extension identification. - uint8_t strLen; //!< ID string length. - char data[]; //!< ID string + uint8_t groupID; //!< Group extension identification. + uint8_t strLen; //!< ID string length. + char data[]; //!< ID string } __attribute__((packed)); /** @struct SetMgmntCtrlIdStrRequest @@ -311,10 +311,10 @@ struct GetMgmntCtrlIdStrResponse */ struct SetMgmntCtrlIdStrRequest { - uint8_t groupID; //!< Group extension identification. - uint8_t offset; //!< Offset to write. - uint8_t bytes; //!< Number of bytes to read. - char data[]; //!< ID string + uint8_t groupID; //!< Group extension identification. + uint8_t offset; //!< Offset to write. + uint8_t bytes; //!< Number of bytes to read. + char data[]; //!< ID string } __attribute__((packed)); /** @struct GetMgmntCtrlIdStrResponse @@ -323,8 +323,8 @@ struct SetMgmntCtrlIdStrRequest */ struct SetMgmntCtrlIdStrResponse { - uint8_t groupID; //!< Group extension identification. - uint8_t offset; //!< Last Offset Written. + uint8_t groupID; //!< Group extension identification. + uint8_t offset; //!< Last Offset Written. } __attribute__((packed)); /** @enum DCMICapParameters @@ -345,8 +345,8 @@ enum class DCMICapParameters */ struct GetDCMICapRequest { - uint8_t groupID; //!< Group extension identification. - uint8_t param; //!< Capability parameter selector. + uint8_t groupID; //!< Group extension identification. + uint8_t param; //!< Capability parameter selector. } __attribute__((packed)); /** @struct GetDCMICapRequest @@ -355,11 +355,11 @@ struct GetDCMICapRequest */ struct GetDCMICapResponse { - uint8_t groupID; //!< Group extension identification. - uint8_t major; //!< DCMI Specification Conformance - major ver - uint8_t minor; //!< DCMI Specification Conformance - minor ver - uint8_t paramRevision; //!< Parameter Revision = 02h - uint8_t data[]; //!< Capability array + uint8_t groupID; //!< Group extension identification. + uint8_t major; //!< DCMI Specification Conformance - major ver + uint8_t minor; //!< DCMI Specification Conformance - minor ver + uint8_t paramRevision; //!< Parameter Revision = 02h + uint8_t data[]; //!< Capability array } __attribute__((packed)); /** @struct DCMICap @@ -368,10 +368,10 @@ struct GetDCMICapResponse */ struct DCMICap { - std::string name; //!< Name of DCMI capability. - uint8_t bytePosition; //!< Starting byte number from DCMI spec. - uint8_t position; //!< bit position from the DCMI spec. - uint8_t length; //!< Length of the value from DCMI spec. + std::string name; //!< Name of DCMI capability. + uint8_t bytePosition; //!< Starting byte number from DCMI spec. + uint8_t position; //!< bit position from the DCMI spec. + uint8_t length; //!< Length of the value from DCMI spec. }; using DCMICapList = std::vector; @@ -382,8 +382,8 @@ using DCMICapList = std::vector; */ struct DCMICapEntry { - uint8_t size; //!< Size of capability array in bytes. - DCMICapList capList; //!< List of capabilities for a parameter. + uint8_t size; //!< Size of capability array in bytes. + DCMICapList capList; //!< List of capabilities for a parameter. }; using DCMICaps = std::map; @@ -394,11 +394,11 @@ using DCMICaps = std::map; */ struct GetTempReadingsRequest { - uint8_t groupID; //!< Group extension identification. - uint8_t sensorType; //!< Type of the sensor - uint8_t entityId; //!< Entity ID - uint8_t entityInstance; //!< Entity Instance (0 means all instances) - uint8_t instanceStart; //!< Instance start (used if instance is 0) + uint8_t groupID; //!< Group extension identification. + uint8_t sensorType; //!< Type of the sensor + uint8_t entityId; //!< Entity ID + uint8_t entityInstance; //!< Entity Instance (0 means all instances) + uint8_t instanceStart; //!< Instance start (used if instance is 0) } __attribute__((packed)); /** @struct GetTempReadingsResponse @@ -407,9 +407,9 @@ struct GetTempReadingsRequest */ struct GetTempReadingsResponseHdr { - uint8_t groupID; //!< Group extension identification. - uint8_t numInstances; //!< No. of instances for requested id - uint8_t numDataSets; //!< No. of sets of temperature data + uint8_t groupID; //!< Group extension identification. + uint8_t numInstances; //!< No. of instances for requested id + uint8_t numDataSets; //!< No. of sets of temperature data } __attribute__((packed)); /** @brief Parse out JSON config file containing information @@ -421,83 +421,81 @@ Json parseSensorConfig(); namespace temp_readings { - /** @brief Read temperature from a d-bus object, scale it as per dcmi - * get temperature reading requirements. - * - * @param[in] dbusService - the D-Bus service - * @param[in] dbusPath - the D-Bus path - * - * @return A temperature reading - */ - Temperature readTemp(const std::string& dbusService, - const std::string& dbusPath); - - /** @brief Read temperatures and fill up DCMI response for the Get - * Temperature Readings command. This looks at a specific - * instance. - * - * @param[in] type - one of "inlet", "cpu", "baseboard" - * @param[in] instance - A non-zero Entity instance number - * - * @return A tuple, containing a temperature reading and the - * number of instances. - */ - std::tuple read (const std::string& type, - uint8_t instance); - - /** @brief Read temperatures and fill up DCMI response for the Get - * Temperature Readings command. This looks at a range of - * instances. - * - * @param[in] type - one of "inlet", "cpu", "baseboard" - * @param[in] instanceStart - Entity instance start index - * - * @return A tuple, containing a list of temperature readings and the - * number of instances. - */ - std::tuple readAll(const std::string& type, - uint8_t instanceStart); -} +/** @brief Read temperature from a d-bus object, scale it as per dcmi + * get temperature reading requirements. + * + * @param[in] dbusService - the D-Bus service + * @param[in] dbusPath - the D-Bus path + * + * @return A temperature reading + */ +Temperature readTemp(const std::string& dbusService, + const std::string& dbusPath); + +/** @brief Read temperatures and fill up DCMI response for the Get + * Temperature Readings command. This looks at a specific + * instance. + * + * @param[in] type - one of "inlet", "cpu", "baseboard" + * @param[in] instance - A non-zero Entity instance number + * + * @return A tuple, containing a temperature reading and the + * number of instances. + */ +std::tuple read(const std::string& type, + uint8_t instance); + +/** @brief Read temperatures and fill up DCMI response for the Get + * Temperature Readings command. This looks at a range of + * instances. + * + * @param[in] type - one of "inlet", "cpu", "baseboard" + * @param[in] instanceStart - Entity instance start index + * + * @return A tuple, containing a list of temperature readings and the + * number of instances. + */ +std::tuple readAll(const std::string& type, + uint8_t instanceStart); +} // namespace temp_readings namespace sensor_info { - /** @brief Create response from JSON config. - * - * @param[in] config - JSON config info about DCMI sensors - * - * @return Sensor info response - */ - Response createFromJson(const Json& config); - - /** @brief Read sensor info and fill up DCMI response for the Get - * Sensor Info command. This looks at a specific - * instance. - * - * @param[in] type - one of "inlet", "cpu", "baseboard" - * @param[in] instance - A non-zero Entity instance number - * @param[in] config - JSON config info about DCMI sensors - * - * @return A tuple, containing a sensor info response and - * number of instances. - */ - std::tuple read(const std::string& type, - uint8_t instance, - const Json& config); - - /** @brief Read sensor info and fill up DCMI response for the Get - * Sensor Info command. This looks at a range of - * instances. - * - * @param[in] type - one of "inlet", "cpu", "baseboard" - * @param[in] instanceStart - Entity instance start index - * @param[in] config - JSON config info about DCMI sensors - * - * @return A tuple, containing a list of sensor info responses and the - * number of instances. - */ - std::tuple readAll(const std::string& type, - uint8_t instanceStart, - const Json& config); +/** @brief Create response from JSON config. + * + * @param[in] config - JSON config info about DCMI sensors + * + * @return Sensor info response + */ +Response createFromJson(const Json& config); + +/** @brief Read sensor info and fill up DCMI response for the Get + * Sensor Info command. This looks at a specific + * instance. + * + * @param[in] type - one of "inlet", "cpu", "baseboard" + * @param[in] instance - A non-zero Entity instance number + * @param[in] config - JSON config info about DCMI sensors + * + * @return A tuple, containing a sensor info response and + * number of instances. + */ +std::tuple read(const std::string& type, + uint8_t instance, const Json& config); + +/** @brief Read sensor info and fill up DCMI response for the Get + * Sensor Info command. This looks at a range of + * instances. + * + * @param[in] type - one of "inlet", "cpu", "baseboard" + * @param[in] instanceStart - Entity instance start index + * @param[in] config - JSON config info about DCMI sensors + * + * @return A tuple, containing a list of sensor info responses and the + * number of instances. + */ +std::tuple + readAll(const std::string& type, uint8_t instanceStart, const Json& config); } // namespace sensor_info /** @brief Read power reading from power reading sensor object @@ -515,9 +513,9 @@ int64_t getPowerReading(sdbusplus::bus::bus& bus); */ struct GetPowerReadingRequest { - uint8_t groupID; //!< Group extension identification. - uint8_t mode; //!< Mode - uint8_t modeAttribute; //!< Mode Attributes + uint8_t groupID; //!< Group extension identification. + uint8_t mode; //!< Mode + uint8_t modeAttribute; //!< Mode Attributes } __attribute__((packed)); /** @struct GetPowerReadingResponse @@ -527,18 +525,18 @@ struct GetPowerReadingRequest */ struct GetPowerReadingResponse { - uint8_t groupID; //!< Group extension identification. - uint16_t currentPower; //!< Current power in watts - uint16_t minimumPower; //!< Minimum power over sampling duration - //!< in watts - uint16_t maximumPower; //!< Maximum power over sampling duration - //!< in watts - uint16_t averagePower; //!< Average power over sampling duration - //!< in watts - uint32_t timeStamp; //!< IPMI specification based time stamp - uint32_t timeFrame; //!< Statistics reporting time period in milli - //!< seconds. - uint8_t powerReadingState; //!< Power Reading State + uint8_t groupID; //!< Group extension identification. + uint16_t currentPower; //!< Current power in watts + uint16_t minimumPower; //!< Minimum power over sampling duration + //!< in watts + uint16_t maximumPower; //!< Maximum power over sampling duration + //!< in watts + uint16_t averagePower; //!< Average power over sampling duration + //!< in watts + uint32_t timeStamp; //!< IPMI specification based time stamp + uint32_t timeFrame; //!< Statistics reporting time period in milli + //!< seconds. + uint8_t powerReadingState; //!< Power Reading State } __attribute__((packed)); /** @struct GetSensorInfoRequest @@ -547,11 +545,11 @@ struct GetPowerReadingResponse */ struct GetSensorInfoRequest { - uint8_t groupID; //!< Group extension identification. - uint8_t sensorType; //!< Type of the sensor - uint8_t entityId; //!< Entity ID - uint8_t entityInstance; //!< Entity Instance (0 means all instances) - uint8_t instanceStart; //!< Instance start (used if instance is 0) + uint8_t groupID; //!< Group extension identification. + uint8_t sensorType; //!< Type of the sensor + uint8_t entityId; //!< Entity ID + uint8_t entityInstance; //!< Entity Instance (0 means all instances) + uint8_t instanceStart; //!< Instance start (used if instance is 0) } __attribute__((packed)); /** @struct GetSensorInfoResponseHdr @@ -560,14 +558,14 @@ struct GetSensorInfoRequest */ struct GetSensorInfoResponseHdr { - uint8_t groupID; //!< Group extension identification. - uint8_t numInstances; //!< No. of instances for requested id - uint8_t numRecords; //!< No. of record ids in the response + uint8_t groupID; //!< Group extension identification. + uint8_t numInstances; //!< No. of instances for requested id + uint8_t numRecords; //!< No. of record ids in the response } __attribute__((packed)); /** * @brief Parameters for DCMI Configuration Parameters */ -enum class DCMIConfigParameters: uint8_t +enum class DCMIConfigParameters : uint8_t { ActivateDHCP = 1, DiscoveryConfig, @@ -583,11 +581,11 @@ enum class DCMIConfigParameters: uint8_t */ struct SetConfParamsRequest { - uint8_t groupID; //!< Group extension identification. - uint8_t paramSelect; //!< Parameter selector. - uint8_t setSelect; //!< Set Selector (use 00h for parameters that only - //!< have one set). - uint8_t data[]; //!< Configuration parameter data. + uint8_t groupID; //!< Group extension identification. + uint8_t paramSelect; //!< Parameter selector. + uint8_t setSelect; //!< Set Selector (use 00h for parameters that only + //!< have one set). + uint8_t data[]; //!< Configuration parameter data. } __attribute__((packed)); /** @struct SetConfParamsResponse @@ -597,7 +595,7 @@ struct SetConfParamsRequest */ struct SetConfParamsResponse { - uint8_t groupID; //!< Group extension identification. + uint8_t groupID; //!< Group extension identification. } __attribute__((packed)); /** @struct GetConfParamsRequest @@ -607,11 +605,11 @@ struct SetConfParamsResponse */ struct GetConfParamsRequest { - uint8_t groupID; //!< Group extension identification. - uint8_t paramSelect; //!< Parameter selector. - uint8_t setSelect; //!< Set Selector. Selects a given set of parameters - //!< under a given Parameter selector value. 00h if - //!< parameter doesn't use a Set Selector. + uint8_t groupID; //!< Group extension identification. + uint8_t paramSelect; //!< Parameter selector. + uint8_t setSelect; //!< Set Selector. Selects a given set of parameters + //!< under a given Parameter selector value. 00h if + //!< parameter doesn't use a Set Selector. } __attribute__((packed)); /** @struct GetConfParamsResponse @@ -621,11 +619,11 @@ struct GetConfParamsRequest */ struct GetConfParamsResponse { - uint8_t groupID; //!< Group extension identification. - uint8_t major; //!< DCMI Spec Conformance - major ver = 01h. - uint8_t minor; //!< DCMI Spec Conformance - minor ver = 05h. - uint8_t paramRevision; //!< Parameter Revision = 01h. - uint8_t data[]; //!< Parameter data. + uint8_t groupID; //!< Group extension identification. + uint8_t major; //!< DCMI Spec Conformance - major ver = 01h. + uint8_t minor; //!< DCMI Spec Conformance - minor ver = 05h. + uint8_t paramRevision; //!< Parameter Revision = 01h. + uint8_t data[]; //!< Parameter data. } __attribute__((packed)); diff --git a/elog-errors.hpp b/elog-errors.hpp index a8d7a1c..f11a203 100644 --- a/elog-errors.hpp +++ b/elog-errors.hpp @@ -2,12 +2,12 @@ // See elog-gen.py for more details #pragma once +#include +#include +#include #include #include #include -#include -#include -#include namespace sdbusplus { @@ -21,7 +21,7 @@ namespace Create { namespace Error { - struct QuotaExceeded; +struct QuotaExceeded; } // namespace Error } // namespace Create } // namespace Dump @@ -39,7 +39,7 @@ namespace Host { namespace Error { - struct Event; +struct Event; } // namespace Error } // namespace Host } // namespace open_power @@ -58,7 +58,7 @@ namespace Host { namespace Error { - struct SoftOffTimeout; +struct SoftOffTimeout; } // namespace Error } // namespace Host } // namespace State @@ -78,7 +78,7 @@ namespace Device { namespace Error { - struct ReadFailure; +struct ReadFailure; } // namespace Error } // namespace Device } // namespace Sensor @@ -98,7 +98,7 @@ namespace Device { namespace Error { - struct WriteFailure; +struct WriteFailure; } // namespace Error } // namespace Device } // namespace Control @@ -118,7 +118,7 @@ namespace File { namespace Error { - struct Seek; +struct Seek; } // namespace Error } // namespace File } // namespace Common @@ -138,7 +138,7 @@ namespace Callout { namespace Error { - struct Procedure; +struct Procedure; } // namespace Error } // namespace Callout } // namespace Common @@ -158,7 +158,7 @@ namespace Host { namespace Error { - struct CommandNotSupported; +struct CommandNotSupported; } // namespace Error } // namespace Host } // namespace Control @@ -176,7 +176,7 @@ namespace Common { namespace Error { - struct InternalFailure; +struct InternalFailure; } // namespace Error } // namespace Common } // namespace openbmc_project @@ -195,7 +195,7 @@ namespace Callout { namespace Error { - struct Device; +struct Device; } // namespace Error } // namespace Callout } // namespace Common @@ -215,7 +215,7 @@ namespace Access { namespace Error { - struct WriteCFAM; +struct WriteCFAM; } // namespace Error } // namespace Access } // namespace Host @@ -235,7 +235,7 @@ namespace File { namespace Error { - struct Open; +struct Open; } // namespace Error } // namespace File } // namespace Common @@ -253,7 +253,7 @@ namespace Host { namespace Error { - struct Checkstop; +struct Checkstop; } // namespace Error } // namespace Host } // namespace open_power @@ -272,7 +272,7 @@ namespace File { namespace Error { - struct Write; +struct Write; } // namespace Error } // namespace File } // namespace Common @@ -292,7 +292,7 @@ namespace Callout { namespace Error { - struct GPIO; +struct GPIO; } // namespace Error } // namespace Callout } // namespace Common @@ -310,7 +310,7 @@ namespace Common { namespace Error { - struct InvalidArgument; +struct InvalidArgument; } // namespace Error } // namespace Common } // namespace openbmc_project @@ -329,7 +329,7 @@ namespace Create { namespace Error { - struct Disabled; +struct Disabled; } // namespace Error } // namespace Create } // namespace Dump @@ -349,7 +349,7 @@ namespace Callout { namespace Error { - struct IPMISensor; +struct IPMISensor; } // namespace Error } // namespace Callout } // namespace Common @@ -367,7 +367,7 @@ namespace Common { namespace Error { - struct Timeout; +struct Timeout; } // namespace Error } // namespace Common } // namespace openbmc_project @@ -386,7 +386,7 @@ namespace Callout { namespace Error { - struct Inventory; +struct Inventory; } // namespace Error } // namespace Callout } // namespace Common @@ -406,7 +406,7 @@ namespace Callout { namespace Error { - struct IIC; +struct IIC; } // namespace Error } // namespace Callout } // namespace Common @@ -424,7 +424,7 @@ namespace Host { namespace Error { - struct WatchdogTimedOut; +struct WatchdogTimedOut; } // namespace Error } // namespace Host } // namespace open_power @@ -443,7 +443,7 @@ namespace Access { namespace Error { - struct ReadCFAM; +struct ReadCFAM; } // namespace Error } // namespace Access } // namespace Host @@ -461,7 +461,7 @@ namespace Host { namespace Error { - struct MaintenanceProcedure; +struct MaintenanceProcedure; } // namespace Error } // namespace Host } // namespace open_power @@ -489,20 +489,21 @@ struct CALLOUT_ERRNO { static constexpr auto str = "CALLOUT_ERRNO=%d"; static constexpr auto str_short = "CALLOUT_ERRNO"; - using type = std::tuple,int32_t>; - explicit constexpr CALLOUT_ERRNO(int32_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, int32_t>; + explicit constexpr CALLOUT_ERRNO(int32_t a) : _entry(entry(str, a)){}; type _entry; }; struct CALLOUT_DEVICE_PATH { static constexpr auto str = "CALLOUT_DEVICE_PATH=%s"; static constexpr auto str_short = "CALLOUT_DEVICE_PATH"; - using type = std::tuple,const char*>; - explicit constexpr CALLOUT_DEVICE_PATH(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr CALLOUT_DEVICE_PATH(const char* a) : + _entry(entry(str, a)){}; type _entry; }; -} // namespace _Device +} // namespace _Device struct Device { @@ -510,7 +511,6 @@ struct Device using CALLOUT_ERRNO = _Device::CALLOUT_ERRNO; using CALLOUT_DEVICE_PATH = _Device::CALLOUT_DEVICE_PATH; using metadata_types = std::tuple; - }; } // namespace Callout @@ -518,17 +518,17 @@ struct Device } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Common::Callout::Error::Device> { using type = xyz::openbmc_project::Common::Callout::Device; }; -} +} // namespace details namespace xyz { @@ -545,21 +545,23 @@ struct CALLOUT_GPIO_NUM { static constexpr auto str = "CALLOUT_GPIO_NUM=%u"; static constexpr auto str_short = "CALLOUT_GPIO_NUM"; - using type = std::tuple,uint32_t>; - explicit constexpr CALLOUT_GPIO_NUM(uint32_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, uint32_t>; + explicit constexpr CALLOUT_GPIO_NUM(uint32_t a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _GPIO +} // namespace _GPIO struct GPIO { static constexpr auto L = level::ERR; using CALLOUT_GPIO_NUM = _GPIO::CALLOUT_GPIO_NUM; - using CALLOUT_ERRNO = xyz::openbmc_project::Common::Callout::Device::CALLOUT_ERRNO; - using CALLOUT_DEVICE_PATH = xyz::openbmc_project::Common::Callout::Device::CALLOUT_DEVICE_PATH; - using metadata_types = std::tuple; - + using CALLOUT_ERRNO = + xyz::openbmc_project::Common::Callout::Device::CALLOUT_ERRNO; + using CALLOUT_DEVICE_PATH = + xyz::openbmc_project::Common::Callout::Device::CALLOUT_DEVICE_PATH; + using metadata_types = + std::tuple; }; } // namespace Callout @@ -567,17 +569,17 @@ struct GPIO } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Common::Callout::Error::GPIO> { using type = xyz::openbmc_project::Common::Callout::GPIO; }; -} +} // namespace details namespace xyz { @@ -594,30 +596,32 @@ struct CALLOUT_IIC_BUS { static constexpr auto str = "CALLOUT_IIC_BUS=%s"; static constexpr auto str_short = "CALLOUT_IIC_BUS"; - using type = std::tuple,const char*>; - explicit constexpr CALLOUT_IIC_BUS(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr CALLOUT_IIC_BUS(const char* a) : _entry(entry(str, a)){}; type _entry; }; struct CALLOUT_IIC_ADDR { static constexpr auto str = "CALLOUT_IIC_ADDR=0x%hx"; static constexpr auto str_short = "CALLOUT_IIC_ADDR"; - using type = std::tuple,uint16_t>; - explicit constexpr CALLOUT_IIC_ADDR(uint16_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, uint16_t>; + explicit constexpr CALLOUT_IIC_ADDR(uint16_t a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _IIC +} // namespace _IIC struct IIC { static constexpr auto L = level::ERR; using CALLOUT_IIC_BUS = _IIC::CALLOUT_IIC_BUS; using CALLOUT_IIC_ADDR = _IIC::CALLOUT_IIC_ADDR; - using CALLOUT_ERRNO = xyz::openbmc_project::Common::Callout::Device::CALLOUT_ERRNO; - using CALLOUT_DEVICE_PATH = xyz::openbmc_project::Common::Callout::Device::CALLOUT_DEVICE_PATH; - using metadata_types = std::tuple; - + using CALLOUT_ERRNO = + xyz::openbmc_project::Common::Callout::Device::CALLOUT_ERRNO; + using CALLOUT_DEVICE_PATH = + xyz::openbmc_project::Common::Callout::Device::CALLOUT_DEVICE_PATH; + using metadata_types = std::tuple; }; } // namespace Callout @@ -625,17 +629,17 @@ struct IIC } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Common::Callout::Error::IIC> { using type = xyz::openbmc_project::Common::Callout::IIC; }; -} +} // namespace details namespace xyz { @@ -652,19 +656,19 @@ struct CALLOUT_INVENTORY_PATH { static constexpr auto str = "CALLOUT_INVENTORY_PATH=%s"; static constexpr auto str_short = "CALLOUT_INVENTORY_PATH"; - using type = std::tuple,const char*>; - explicit constexpr CALLOUT_INVENTORY_PATH(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr CALLOUT_INVENTORY_PATH(const char* a) : + _entry(entry(str, a)){}; type _entry; }; -} // namespace _Inventory +} // namespace _Inventory struct Inventory { static constexpr auto L = level::ERR; using CALLOUT_INVENTORY_PATH = _Inventory::CALLOUT_INVENTORY_PATH; using metadata_types = std::tuple; - }; } // namespace Callout @@ -672,17 +676,17 @@ struct Inventory } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Common::Callout::Error::Inventory> { using type = xyz::openbmc_project::Common::Callout::Inventory; }; -} +} // namespace details namespace xyz { @@ -699,19 +703,19 @@ struct CALLOUT_IPMI_SENSOR_NUM { static constexpr auto str = "CALLOUT_IPMI_SENSOR_NUM=%u"; static constexpr auto str_short = "CALLOUT_IPMI_SENSOR_NUM"; - using type = std::tuple,uint32_t>; - explicit constexpr CALLOUT_IPMI_SENSOR_NUM(uint32_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, uint32_t>; + explicit constexpr CALLOUT_IPMI_SENSOR_NUM(uint32_t a) : + _entry(entry(str, a)){}; type _entry; }; -} // namespace _IPMISensor +} // namespace _IPMISensor struct IPMISensor { static constexpr auto L = level::ERR; using CALLOUT_IPMI_SENSOR_NUM = _IPMISensor::CALLOUT_IPMI_SENSOR_NUM; using metadata_types = std::tuple; - }; } // namespace Callout @@ -719,17 +723,17 @@ struct IPMISensor } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Common::Callout::Error::IPMISensor> { using type = xyz::openbmc_project::Common::Callout::IPMISensor; }; -} +} // namespace details namespace org { @@ -746,19 +750,18 @@ struct PROCEDURE { static constexpr auto str = "PROCEDURE=%u"; static constexpr auto str_short = "PROCEDURE"; - using type = std::tuple,uint32_t>; - explicit constexpr PROCEDURE(uint32_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, uint32_t>; + explicit constexpr PROCEDURE(uint32_t a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _Procedure +} // namespace _Procedure struct Procedure { static constexpr auto L = level::ERR; using PROCEDURE = _Procedure::PROCEDURE; using metadata_types = std::tuple; - }; } // namespace Callout @@ -766,17 +769,17 @@ struct Procedure } // namespace open_power } // namespace org - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::org::open_power::Common::Callout::Error::Procedure> { using type = org::open_power::Common::Callout::Procedure; }; -} +} // namespace details namespace xyz { @@ -791,36 +794,35 @@ struct TIMEOUT_IN_MSEC { static constexpr auto str = "TIMEOUT_IN_MSEC=%llu"; static constexpr auto str_short = "TIMEOUT_IN_MSEC"; - using type = std::tuple,uint64_t>; - explicit constexpr TIMEOUT_IN_MSEC(uint64_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, uint64_t>; + explicit constexpr TIMEOUT_IN_MSEC(uint64_t a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _Timeout +} // namespace _Timeout struct Timeout { static constexpr auto L = level::ERR; using TIMEOUT_IN_MSEC = _Timeout::TIMEOUT_IN_MSEC; using metadata_types = std::tuple; - }; } // namespace Common } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Common::Error::Timeout> { using type = xyz::openbmc_project::Common::Timeout; }; -} +} // namespace details namespace xyz { @@ -831,31 +833,29 @@ namespace Common namespace _InternalFailure { - -} // namespace _InternalFailure +} // namespace _InternalFailure struct InternalFailure { static constexpr auto L = level::ERR; using metadata_types = std::tuple<>; - }; } // namespace Common } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure> { using type = xyz::openbmc_project::Common::InternalFailure; }; -} +} // namespace details namespace xyz { @@ -870,20 +870,20 @@ struct ARGUMENT_NAME { static constexpr auto str = "ARGUMENT_NAME=%s"; static constexpr auto str_short = "ARGUMENT_NAME"; - using type = std::tuple,const char*>; - explicit constexpr ARGUMENT_NAME(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr ARGUMENT_NAME(const char* a) : _entry(entry(str, a)){}; type _entry; }; struct ARGUMENT_VALUE { static constexpr auto str = "ARGUMENT_VALUE=%s"; static constexpr auto str_short = "ARGUMENT_VALUE"; - using type = std::tuple,const char*>; - explicit constexpr ARGUMENT_VALUE(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr ARGUMENT_VALUE(const char* a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _InvalidArgument +} // namespace _InvalidArgument struct InvalidArgument { @@ -891,24 +891,23 @@ struct InvalidArgument using ARGUMENT_NAME = _InvalidArgument::ARGUMENT_NAME; using ARGUMENT_VALUE = _InvalidArgument::ARGUMENT_VALUE; using metadata_types = std::tuple; - }; } // namespace Common } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument> { using type = xyz::openbmc_project::Common::InvalidArgument; }; -} +} // namespace details namespace example { @@ -927,29 +926,32 @@ struct CALLOUT_ERRNO_TEST { static constexpr auto str = "CALLOUT_ERRNO_TEST=%d"; static constexpr auto str_short = "CALLOUT_ERRNO_TEST"; - using type = std::tuple,int32_t>; - explicit constexpr CALLOUT_ERRNO_TEST(int32_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, int32_t>; + explicit constexpr CALLOUT_ERRNO_TEST(int32_t a) : _entry(entry(str, a)){}; type _entry; }; struct CALLOUT_DEVICE_PATH_TEST { static constexpr auto str = "CALLOUT_DEVICE_PATH_TEST=%s"; static constexpr auto str_short = "CALLOUT_DEVICE_PATH_TEST"; - using type = std::tuple,const char*>; - explicit constexpr CALLOUT_DEVICE_PATH_TEST(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr CALLOUT_DEVICE_PATH_TEST(const char* a) : + _entry(entry(str, a)){}; type _entry; }; -} // namespace _Callout +} // namespace _Callout struct Callout : public sdbusplus::exception_t { - static constexpr auto errName = "example.xyz.openbmc_project.Example.Device.Callout"; + static constexpr auto errName = + "example.xyz.openbmc_project.Example.Device.Callout"; static constexpr auto errDesc = "Generic device callout"; static constexpr auto L = level::ERR; using CALLOUT_ERRNO_TEST = _Callout::CALLOUT_ERRNO_TEST; using CALLOUT_DEVICE_PATH_TEST = _Callout::CALLOUT_DEVICE_PATH_TEST; - using metadata_types = std::tuple; + using metadata_types = + std::tuple; const char* name() const noexcept { @@ -973,8 +975,6 @@ struct Callout : public sdbusplus::exception_t } // namespace xyz } // namespace example - - namespace xyz { namespace openbmc_project @@ -986,16 +986,16 @@ namespace Device namespace _ReadFailure { - -} // namespace _ReadFailure +} // namespace _ReadFailure struct ReadFailure { static constexpr auto L = level::ERR; - using CALLOUT_ERRNO = xyz::openbmc_project::Common::Callout::Device::CALLOUT_ERRNO; - using CALLOUT_DEVICE_PATH = xyz::openbmc_project::Common::Callout::Device::CALLOUT_DEVICE_PATH; + using CALLOUT_ERRNO = + xyz::openbmc_project::Common::Callout::Device::CALLOUT_ERRNO; + using CALLOUT_DEVICE_PATH = + xyz::openbmc_project::Common::Callout::Device::CALLOUT_DEVICE_PATH; using metadata_types = std::tuple; - }; } // namespace Device @@ -1003,17 +1003,17 @@ struct ReadFailure } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Sensor::Device::Error::ReadFailure> { using type = xyz::openbmc_project::Sensor::Device::ReadFailure; }; -} +} // namespace details namespace org { @@ -1024,21 +1024,18 @@ namespace Host namespace _Checkstop { - -} // namespace _Checkstop +} // namespace _Checkstop struct Checkstop { static constexpr auto L = level::ERR; using metadata_types = std::tuple<>; - }; } // namespace Host } // namespace open_power } // namespace org - namespace details { @@ -1048,7 +1045,7 @@ struct map_exception_type using type = org::open_power::Host::Checkstop; }; -} +} // namespace details namespace org { @@ -1059,31 +1056,29 @@ namespace Host namespace _WatchdogTimedOut { - -} // namespace _WatchdogTimedOut +} // namespace _WatchdogTimedOut struct WatchdogTimedOut { static constexpr auto L = level::ERR; using metadata_types = std::tuple<>; - }; } // namespace Host } // namespace open_power } // namespace org - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::org::open_power::Host::Error::WatchdogTimedOut> { using type = org::open_power::Host::WatchdogTimedOut; }; -} +} // namespace details namespace example { @@ -1102,32 +1097,33 @@ struct DEV_ADDR { static constexpr auto str = "DEV_ADDR=0x%.8X"; static constexpr auto str_short = "DEV_ADDR"; - using type = std::tuple,uint32_t>; - explicit constexpr DEV_ADDR(uint32_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, uint32_t>; + explicit constexpr DEV_ADDR(uint32_t a) : _entry(entry(str, a)){}; type _entry; }; struct DEV_ID { static constexpr auto str = "DEV_ID=%u"; static constexpr auto str_short = "DEV_ID"; - using type = std::tuple,uint32_t>; - explicit constexpr DEV_ID(uint32_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, uint32_t>; + explicit constexpr DEV_ID(uint32_t a) : _entry(entry(str, a)){}; type _entry; }; struct DEV_NAME { static constexpr auto str = "DEV_NAME=%s"; static constexpr auto str_short = "DEV_NAME"; - using type = std::tuple,const char*>; - explicit constexpr DEV_NAME(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr DEV_NAME(const char* a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _TestErrorTwo +} // namespace _TestErrorTwo struct TestErrorTwo : public sdbusplus::exception_t { - static constexpr auto errName = "example.xyz.openbmc_project.Example.Elog.TestErrorTwo"; + static constexpr auto errName = + "example.xyz.openbmc_project.Example.Elog.TestErrorTwo"; static constexpr auto errDesc = "This is test error two"; static constexpr auto L = level::ERR; using DEV_ADDR = _TestErrorTwo::DEV_ADDR; @@ -1157,8 +1153,6 @@ struct TestErrorTwo : public sdbusplus::exception_t } // namespace xyz } // namespace example - - namespace example { namespace xyz @@ -1176,16 +1170,17 @@ struct STRING { static constexpr auto str = "STRING=%s"; static constexpr auto str_short = "STRING"; - using type = std::tuple,const char*>; - explicit constexpr STRING(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr STRING(const char* a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _AutoTestSimple +} // namespace _AutoTestSimple struct AutoTestSimple : public sdbusplus::exception_t { - static constexpr auto errName = "example.xyz.openbmc_project.Example.Elog.AutoTestSimple"; + static constexpr auto errName = + "example.xyz.openbmc_project.Example.Elog.AutoTestSimple"; static constexpr auto errDesc = "This is a simple test error."; static constexpr auto L = level::ERR; using STRING = _AutoTestSimple::STRING; @@ -1213,8 +1208,6 @@ struct AutoTestSimple : public sdbusplus::exception_t } // namespace xyz } // namespace example - - namespace example { namespace xyz @@ -1232,22 +1225,26 @@ struct DEV_ADDR { static constexpr auto str = "DEV_ADDR=0x%.8X"; static constexpr auto str_short = "DEV_ADDR"; - using type = std::tuple,uint32_t>; - explicit constexpr DEV_ADDR(uint32_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, uint32_t>; + explicit constexpr DEV_ADDR(uint32_t a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _TestCallout +} // namespace _TestCallout struct TestCallout : public sdbusplus::exception_t { - static constexpr auto errName = "example.xyz.openbmc_project.Example.Elog.TestCallout"; + static constexpr auto errName = + "example.xyz.openbmc_project.Example.Elog.TestCallout"; static constexpr auto errDesc = "This is test error TestCallout"; static constexpr auto L = level::ERR; using DEV_ADDR = _TestCallout::DEV_ADDR; - using CALLOUT_ERRNO_TEST = example::xyz::openbmc_project::Example::Device::Callout::CALLOUT_ERRNO_TEST; - using CALLOUT_DEVICE_PATH_TEST = example::xyz::openbmc_project::Example::Device::Callout::CALLOUT_DEVICE_PATH_TEST; - using metadata_types = std::tuple; + using CALLOUT_ERRNO_TEST = example::xyz::openbmc_project::Example::Device:: + Callout::CALLOUT_ERRNO_TEST; + using CALLOUT_DEVICE_PATH_TEST = example::xyz::openbmc_project::Example:: + Device::Callout::CALLOUT_DEVICE_PATH_TEST; + using metadata_types = + std::tuple; const char* name() const noexcept { @@ -1271,8 +1268,6 @@ struct TestCallout : public sdbusplus::exception_t } // namespace xyz } // namespace example - - namespace org { namespace open_power @@ -1286,27 +1281,26 @@ struct ESEL { static constexpr auto str = "ESEL=%s"; static constexpr auto str_short = "ESEL"; - using type = std::tuple,const char*>; - explicit constexpr ESEL(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr ESEL(const char* a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _Event +} // namespace _Event struct Event { static constexpr auto L = level::ERR; using ESEL = _Event::ESEL; - using CALLOUT_INVENTORY_PATH = xyz::openbmc_project::Common::Callout::Inventory::CALLOUT_INVENTORY_PATH; + using CALLOUT_INVENTORY_PATH = xyz::openbmc_project::Common::Callout:: + Inventory::CALLOUT_INVENTORY_PATH; using metadata_types = std::tuple; - }; } // namespace Host } // namespace open_power } // namespace org - namespace details { @@ -1316,7 +1310,7 @@ struct map_exception_type using type = org::open_power::Host::Event; }; -} +} // namespace details namespace org { @@ -1331,12 +1325,12 @@ struct ESEL { static constexpr auto str = "ESEL=%s"; static constexpr auto str_short = "ESEL"; - using type = std::tuple,const char*>; - explicit constexpr ESEL(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr ESEL(const char* a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _MaintenanceProcedure +} // namespace _MaintenanceProcedure struct MaintenanceProcedure { @@ -1344,24 +1338,23 @@ struct MaintenanceProcedure using ESEL = _MaintenanceProcedure::ESEL; using PROCEDURE = org::open_power::Common::Callout::Procedure::PROCEDURE; using metadata_types = std::tuple; - }; } // namespace Host } // namespace open_power } // namespace org - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::org::open_power::Host::Error::MaintenanceProcedure> { using type = org::open_power::Host::MaintenanceProcedure; }; -} +} // namespace details namespace xyz { @@ -1374,16 +1367,16 @@ namespace Device namespace _WriteFailure { - -} // namespace _WriteFailure +} // namespace _WriteFailure struct WriteFailure { static constexpr auto L = level::ERR; - using CALLOUT_ERRNO = xyz::openbmc_project::Common::Callout::Device::CALLOUT_ERRNO; - using CALLOUT_DEVICE_PATH = xyz::openbmc_project::Common::Callout::Device::CALLOUT_DEVICE_PATH; + using CALLOUT_ERRNO = + xyz::openbmc_project::Common::Callout::Device::CALLOUT_ERRNO; + using CALLOUT_DEVICE_PATH = + xyz::openbmc_project::Common::Callout::Device::CALLOUT_DEVICE_PATH; using metadata_types = std::tuple; - }; } // namespace Device @@ -1391,17 +1384,17 @@ struct WriteFailure } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Control::Device::Error::WriteFailure> { using type = xyz::openbmc_project::Control::Device::WriteFailure; }; -} +} // namespace details namespace xyz { @@ -1418,20 +1411,20 @@ struct ERRNO { static constexpr auto str = "ERRNO=%d"; static constexpr auto str_short = "ERRNO"; - using type = std::tuple,int32_t>; - explicit constexpr ERRNO(int32_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, int32_t>; + explicit constexpr ERRNO(int32_t a) : _entry(entry(str, a)){}; type _entry; }; struct PATH { static constexpr auto str = "PATH=%s"; static constexpr auto str_short = "PATH"; - using type = std::tuple,const char*>; - explicit constexpr PATH(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr PATH(const char* a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _Open +} // namespace _Open struct Open { @@ -1439,7 +1432,6 @@ struct Open using ERRNO = _Open::ERRNO; using PATH = _Open::PATH; using metadata_types = std::tuple; - }; } // namespace File @@ -1447,17 +1439,17 @@ struct Open } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Common::File::Error::Open> { using type = xyz::openbmc_project::Common::File::Open; }; -} +} // namespace details namespace xyz { @@ -1474,36 +1466,36 @@ struct OFFSET { static constexpr auto str = "OFFSET=%ll"; static constexpr auto str_short = "OFFSET"; - using type = std::tuple,int64_t>; - explicit constexpr OFFSET(int64_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, int64_t>; + explicit constexpr OFFSET(int64_t a) : _entry(entry(str, a)){}; type _entry; }; struct WHENCE { static constexpr auto str = "WHENCE=%d"; static constexpr auto str_short = "WHENCE"; - using type = std::tuple,int32_t>; - explicit constexpr WHENCE(int32_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, int32_t>; + explicit constexpr WHENCE(int32_t a) : _entry(entry(str, a)){}; type _entry; }; struct ERRNO { static constexpr auto str = "ERRNO=%d"; static constexpr auto str_short = "ERRNO"; - using type = std::tuple,int32_t>; - explicit constexpr ERRNO(int32_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, int32_t>; + explicit constexpr ERRNO(int32_t a) : _entry(entry(str, a)){}; type _entry; }; struct PATH { static constexpr auto str = "PATH=%s"; static constexpr auto str_short = "PATH"; - using type = std::tuple,const char*>; - explicit constexpr PATH(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr PATH(const char* a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _Seek +} // namespace _Seek struct Seek { @@ -1513,7 +1505,6 @@ struct Seek using ERRNO = _Seek::ERRNO; using PATH = _Seek::PATH; using metadata_types = std::tuple; - }; } // namespace File @@ -1521,17 +1512,17 @@ struct Seek } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Common::File::Error::Seek> { using type = xyz::openbmc_project::Common::File::Seek; }; -} +} // namespace details namespace xyz { @@ -1548,20 +1539,20 @@ struct ERRNO { static constexpr auto str = "ERRNO=%d"; static constexpr auto str_short = "ERRNO"; - using type = std::tuple,int32_t>; - explicit constexpr ERRNO(int32_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, int32_t>; + explicit constexpr ERRNO(int32_t a) : _entry(entry(str, a)){}; type _entry; }; struct PATH { static constexpr auto str = "PATH=%s"; static constexpr auto str_short = "PATH"; - using type = std::tuple,const char*>; - explicit constexpr PATH(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr PATH(const char* a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _Write +} // namespace _Write struct Write { @@ -1569,7 +1560,6 @@ struct Write using ERRNO = _Write::ERRNO; using PATH = _Write::PATH; using metadata_types = std::tuple; - }; } // namespace File @@ -1577,17 +1567,17 @@ struct Write } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Common::File::Error::Write> { using type = xyz::openbmc_project::Common::File::Write; }; -} +} // namespace details namespace org { @@ -1604,21 +1594,23 @@ struct ADDRESS { static constexpr auto str = "ADDRESS=0x%X"; static constexpr auto str_short = "ADDRESS"; - using type = std::tuple,uint32_t>; - explicit constexpr ADDRESS(uint32_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, uint32_t>; + explicit constexpr ADDRESS(uint32_t a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _WriteCFAM +} // namespace _WriteCFAM struct WriteCFAM { static constexpr auto L = level::ERR; using ADDRESS = _WriteCFAM::ADDRESS; - using CALLOUT_ERRNO = xyz::openbmc_project::Common::Callout::Device::CALLOUT_ERRNO; - using CALLOUT_DEVICE_PATH = xyz::openbmc_project::Common::Callout::Device::CALLOUT_DEVICE_PATH; - using metadata_types = std::tuple; - + using CALLOUT_ERRNO = + xyz::openbmc_project::Common::Callout::Device::CALLOUT_ERRNO; + using CALLOUT_DEVICE_PATH = + xyz::openbmc_project::Common::Callout::Device::CALLOUT_DEVICE_PATH; + using metadata_types = + std::tuple; }; } // namespace Access @@ -1626,17 +1618,17 @@ struct WriteCFAM } // namespace open_power } // namespace org - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::org::open_power::Host::Access::Error::WriteCFAM> { using type = org::open_power::Host::Access::WriteCFAM; }; -} +} // namespace details namespace org { @@ -1653,21 +1645,23 @@ struct ADDRESS { static constexpr auto str = "ADDRESS=0x%X"; static constexpr auto str_short = "ADDRESS"; - using type = std::tuple,uint32_t>; - explicit constexpr ADDRESS(uint32_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, uint32_t>; + explicit constexpr ADDRESS(uint32_t a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _ReadCFAM +} // namespace _ReadCFAM struct ReadCFAM { static constexpr auto L = level::ERR; using ADDRESS = _ReadCFAM::ADDRESS; - using CALLOUT_ERRNO = xyz::openbmc_project::Common::Callout::Device::CALLOUT_ERRNO; - using CALLOUT_DEVICE_PATH = xyz::openbmc_project::Common::Callout::Device::CALLOUT_DEVICE_PATH; - using metadata_types = std::tuple; - + using CALLOUT_ERRNO = + xyz::openbmc_project::Common::Callout::Device::CALLOUT_ERRNO; + using CALLOUT_DEVICE_PATH = + xyz::openbmc_project::Common::Callout::Device::CALLOUT_DEVICE_PATH; + using metadata_types = + std::tuple; }; } // namespace Access @@ -1675,17 +1669,17 @@ struct ReadCFAM } // namespace open_power } // namespace org - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::org::open_power::Host::Access::Error::ReadCFAM> { using type = org::open_power::Host::Access::ReadCFAM; }; -} +} // namespace details namespace xyz { @@ -1698,15 +1692,14 @@ namespace Host namespace _SoftOffTimeout { - -} // namespace _SoftOffTimeout +} // namespace _SoftOffTimeout struct SoftOffTimeout { static constexpr auto L = level::ERR; - using TIMEOUT_IN_MSEC = xyz::openbmc_project::Common::Timeout::TIMEOUT_IN_MSEC; + using TIMEOUT_IN_MSEC = + xyz::openbmc_project::Common::Timeout::TIMEOUT_IN_MSEC; using metadata_types = std::tuple; - }; } // namespace Host @@ -1714,17 +1707,17 @@ struct SoftOffTimeout } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::State::Host::Error::SoftOffTimeout> { using type = xyz::openbmc_project::State::Host::SoftOffTimeout; }; -} +} // namespace details namespace xyz { @@ -1737,14 +1730,12 @@ namespace Create namespace _Disabled { - -} // namespace _Disabled +} // namespace _Disabled struct Disabled { static constexpr auto L = level::ERR; using metadata_types = std::tuple<>; - }; } // namespace Create @@ -1752,17 +1743,17 @@ struct Disabled } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Dump::Create::Error::Disabled> { using type = xyz::openbmc_project::Dump::Create::Disabled; }; -} +} // namespace details namespace xyz { @@ -1779,19 +1770,18 @@ struct REASON { static constexpr auto str = "REASON = %s"; static constexpr auto str_short = "REASON "; - using type = std::tuple,const char*>; - explicit constexpr REASON (const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr REASON(const char* a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _QuotaExceeded +} // namespace _QuotaExceeded struct QuotaExceeded { static constexpr auto L = level::ERR; - using REASON = _QuotaExceeded::REASON ; - using metadata_types = std::tuple; - + using REASON = _QuotaExceeded::REASON; + using metadata_types = std::tuple; }; } // namespace Create @@ -1799,17 +1789,17 @@ struct QuotaExceeded } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Dump::Create::Error::QuotaExceeded> { using type = xyz::openbmc_project::Dump::Create::QuotaExceeded; }; -} +} // namespace details namespace xyz { @@ -1822,14 +1812,12 @@ namespace Host namespace _CommandNotSupported { - -} // namespace _CommandNotSupported +} // namespace _CommandNotSupported struct CommandNotSupported { static constexpr auto L = level::ERR; using metadata_types = std::tuple<>; - }; } // namespace Host @@ -1837,17 +1825,17 @@ struct CommandNotSupported } // namespace openbmc_project } // namespace xyz - namespace details { template <> -struct map_exception_type +struct map_exception_type< + sdbusplus::xyz::openbmc_project::Control::Host::Error::CommandNotSupported> { using type = xyz::openbmc_project::Control::Host::CommandNotSupported; }; -} +} // namespace details namespace example { @@ -1866,41 +1854,46 @@ struct ERRNUM { static constexpr auto str = "ERRNUM=0x%.4X"; static constexpr auto str_short = "ERRNUM"; - using type = std::tuple,uint16_t>; - explicit constexpr ERRNUM(uint16_t a) : _entry(entry(str, a)) {}; + using type = std::tuple, uint16_t>; + explicit constexpr ERRNUM(uint16_t a) : _entry(entry(str, a)){}; type _entry; }; struct FILE_PATH { static constexpr auto str = "FILE_PATH=%s"; static constexpr auto str_short = "FILE_PATH"; - using type = std::tuple,const char*>; - explicit constexpr FILE_PATH(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr FILE_PATH(const char* a) : _entry(entry(str, a)){}; type _entry; }; struct FILE_NAME { static constexpr auto str = "FILE_NAME=%s"; static constexpr auto str_short = "FILE_NAME"; - using type = std::tuple,const char*>; - explicit constexpr FILE_NAME(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr FILE_NAME(const char* a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _TestErrorOne +} // namespace _TestErrorOne struct TestErrorOne : public sdbusplus::exception_t { - static constexpr auto errName = "example.xyz.openbmc_project.Example.Elog.TestErrorOne"; + static constexpr auto errName = + "example.xyz.openbmc_project.Example.Elog.TestErrorOne"; static constexpr auto errDesc = "this is test error one"; static constexpr auto L = level::INFO; using ERRNUM = _TestErrorOne::ERRNUM; using FILE_PATH = _TestErrorOne::FILE_PATH; using FILE_NAME = _TestErrorOne::FILE_NAME; - using DEV_ADDR = example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_ADDR; - using DEV_ID = example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_ID; - using DEV_NAME = example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_NAME; - using metadata_types = std::tuple; + using DEV_ADDR = + example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_ADDR; + using DEV_ID = + example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_ID; + using DEV_NAME = + example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_NAME; + using metadata_types = + std::tuple; const char* name() const noexcept { @@ -1924,8 +1917,6 @@ struct TestErrorOne : public sdbusplus::exception_t } // namespace xyz } // namespace example - - namespace example { namespace xyz @@ -1943,26 +1934,34 @@ struct FOO_DATA { static constexpr auto str = "FOO_DATA=%s"; static constexpr auto str_short = "FOO_DATA"; - using type = std::tuple,const char*>; - explicit constexpr FOO_DATA(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr FOO_DATA(const char* a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _Foo +} // namespace _Foo struct Foo : public sdbusplus::exception_t { - static constexpr auto errName = "example.xyz.openbmc_project.Example.Foo.Foo"; + static constexpr auto errName = + "example.xyz.openbmc_project.Example.Foo.Foo"; static constexpr auto errDesc = "this is test error Foo"; static constexpr auto L = level::INFO; using FOO_DATA = _Foo::FOO_DATA; - using ERRNUM = example::xyz::openbmc_project::Example::Elog::TestErrorOne::ERRNUM; - using FILE_PATH = example::xyz::openbmc_project::Example::Elog::TestErrorOne::FILE_PATH; - using FILE_NAME = example::xyz::openbmc_project::Example::Elog::TestErrorOne::FILE_NAME; - using DEV_ADDR = example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_ADDR; - using DEV_ID = example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_ID; - using DEV_NAME = example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_NAME; - using metadata_types = std::tuple; + using ERRNUM = + example::xyz::openbmc_project::Example::Elog::TestErrorOne::ERRNUM; + using FILE_PATH = + example::xyz::openbmc_project::Example::Elog::TestErrorOne::FILE_PATH; + using FILE_NAME = + example::xyz::openbmc_project::Example::Elog::TestErrorOne::FILE_NAME; + using DEV_ADDR = + example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_ADDR; + using DEV_ID = + example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_ID; + using DEV_NAME = + example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_NAME; + using metadata_types = std::tuple; const char* name() const noexcept { @@ -1986,8 +1985,6 @@ struct Foo : public sdbusplus::exception_t } // namespace xyz } // namespace example - - namespace example { namespace xyz @@ -2005,27 +2002,35 @@ struct BAR_DATA { static constexpr auto str = "BAR_DATA=%s"; static constexpr auto str_short = "BAR_DATA"; - using type = std::tuple,const char*>; - explicit constexpr BAR_DATA(const char* a) : _entry(entry(str, a)) {}; + using type = std::tuple, const char*>; + explicit constexpr BAR_DATA(const char* a) : _entry(entry(str, a)){}; type _entry; }; -} // namespace _Bar +} // namespace _Bar struct Bar : public sdbusplus::exception_t { - static constexpr auto errName = "example.xyz.openbmc_project.Example.Bar.Bar"; + static constexpr auto errName = + "example.xyz.openbmc_project.Example.Bar.Bar"; static constexpr auto errDesc = "this is test error Bar"; static constexpr auto L = level::INFO; using BAR_DATA = _Bar::BAR_DATA; using FOO_DATA = example::xyz::openbmc_project::Example::Foo::Foo::FOO_DATA; - using ERRNUM = example::xyz::openbmc_project::Example::Elog::TestErrorOne::ERRNUM; - using FILE_PATH = example::xyz::openbmc_project::Example::Elog::TestErrorOne::FILE_PATH; - using FILE_NAME = example::xyz::openbmc_project::Example::Elog::TestErrorOne::FILE_NAME; - using DEV_ADDR = example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_ADDR; - using DEV_ID = example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_ID; - using DEV_NAME = example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_NAME; - using metadata_types = std::tuple; + using ERRNUM = + example::xyz::openbmc_project::Example::Elog::TestErrorOne::ERRNUM; + using FILE_PATH = + example::xyz::openbmc_project::Example::Elog::TestErrorOne::FILE_PATH; + using FILE_NAME = + example::xyz::openbmc_project::Example::Elog::TestErrorOne::FILE_NAME; + using DEV_ADDR = + example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_ADDR; + using DEV_ID = + example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_ID; + using DEV_NAME = + example::xyz::openbmc_project::Example::Elog::TestErrorTwo::DEV_NAME; + using metadata_types = std::tuple; const char* name() const noexcept { @@ -2049,9 +2054,6 @@ struct Bar : public sdbusplus::exception_t } // namespace xyz } // namespace example - - - } // namespace logging } // namespace phosphor diff --git a/error-HostEvent.hpp b/error-HostEvent.hpp index 40872a1..72dc6e9 100644 --- a/error-HostEvent.hpp +++ b/error-HostEvent.hpp @@ -16,10 +16,9 @@ namespace Error struct Event final : public sdbusplus::exception_t { static constexpr auto errName = "org.open_power.Host.Error.Event"; - static constexpr auto errDesc = - "A host system event was received"; + static constexpr auto errDesc = "A host system event was received"; static constexpr auto errWhat = - "org.open_power.Host.Error.Event: A host system event was received"; + "org.open_power.Host.Error.Event: A host system event was received"; const char* name() const noexcept override; const char* description() const noexcept override; @@ -28,11 +27,13 @@ struct Event final : public sdbusplus::exception_t struct MaintenanceProcedure final : public sdbusplus::exception_t { - static constexpr auto errName = "org.open_power.Host.Error.MaintenanceProcedure"; + static constexpr auto errName = + "org.open_power.Host.Error.MaintenanceProcedure"; static constexpr auto errDesc = - "A host system event with a procedure callout"; + "A host system event with a procedure callout"; static constexpr auto errWhat = - "org.open_power.Host.Error.MaintenanceProcedure: A host system event with a procedure callout"; + "org.open_power.Host.Error.MaintenanceProcedure: A host system event " + "with a procedure callout"; const char* name() const noexcept override; const char* description() const noexcept override; @@ -44,4 +45,3 @@ struct MaintenanceProcedure final : public sdbusplus::exception_t } // namespace open_power } // namespace org } // namespace sdbusplus - diff --git a/fruread.hpp b/fruread.hpp index e035a74..20f260c 100644 --- a/fruread.hpp +++ b/fruread.hpp @@ -2,9 +2,10 @@ #define OPENBMC_IPMI_FRU_READ_H #include + #include -#include #include +#include #include struct IPMIFruData diff --git a/globalhandler.cpp b/globalhandler.cpp index 32f2bc6..55761b4 100644 --- a/globalhandler.cpp +++ b/globalhandler.cpp @@ -1,12 +1,15 @@ #include "globalhandler.h" -#include "host-ipmid/ipmid-api.h" + #include + +#include +#include #include #include -#include -#include -#include "xyz/openbmc_project/Common/error.hpp" -#include "xyz/openbmc_project/State/BMC/server.hpp" +#include +#include + +#include "host-ipmid/ipmid-api.h" static constexpr auto bmcStateRoot = "/xyz/openbmc_project/state"; static constexpr auto bmcStateIntf = "xyz.openbmc_project.State.BMC"; @@ -22,16 +25,16 @@ void resetBMC() { sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; - auto bmcStateObj = ipmi::getDbusObject(bus, bmcStateIntf, bmcStateRoot, - match); + auto bmcStateObj = + ipmi::getDbusObject(bus, bmcStateIntf, bmcStateRoot, match); auto service = ipmi::getService(bus, bmcStateIntf, bmcStateObj.first); ipmi::setDbusProperty(bus, service, bmcStateObj.first, bmcStateIntf, - reqTransition, convertForMessage(BMC::Transition::Reboot)); + reqTransition, + convertForMessage(BMC::Transition::Reboot)); } - ipmi_ret_t ipmi_global_reset(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) diff --git a/groupext.cpp b/groupext.cpp index 1166a3e..0d8bfe0 100644 --- a/groupext.cpp +++ b/groupext.cpp @@ -1,18 +1,20 @@ -#include "host-ipmid/ipmid-api.h" #include "ipmid.hpp" -#include + #include +#include + +#include "host-ipmid/ipmid-api.h" #define GRPEXT_GET_GROUP_CMD 0 void register_netfn_groupext_functions() __attribute__((constructor)); ipmi_ret_t ipmi_groupext(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, ipmi_response_t response, + ipmi_data_len_t data_len, ipmi_context_t context) { - // Generic return from IPMI commands. + // Generic return from IPMI commands. ipmi_ret_t rc = IPMI_CC_OK; - uint8_t *p = (uint8_t*) response; + uint8_t* p = (uint8_t*)response; printf("IPMI GROUP EXTENSIONS\n"); @@ -25,8 +27,8 @@ ipmi_ret_t ipmi_groupext(ipmi_netfn_t netfn, ipmi_cmd_t cmd, void register_netfn_groupext_functions() { // - ipmi_register_callback(NETFUN_GRPEXT, GRPEXT_GET_GROUP_CMD, NULL, ipmi_groupext, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_GRPEXT, GRPEXT_GET_GROUP_CMD, NULL, + ipmi_groupext, PRIVILEGE_USER); return; } diff --git a/host-cmd-manager.cpp b/host-cmd-manager.cpp index 4316451..90e932b 100644 --- a/host-cmd-manager.cpp +++ b/host-cmd-manager.cpp @@ -1,13 +1,14 @@ +#include +#include + #include -#include +#include #include +#include +#include +#include #include #include -#include -#include -#include -#include -#include namespace phosphor { @@ -25,20 +26,17 @@ constexpr auto HOST_TRANS_PROP = "RequestedHostTransition"; // For throwing exceptions using namespace phosphor::logging; -using InternalFailure = sdbusplus::xyz::openbmc_project::Common:: - Error::InternalFailure; +using InternalFailure = + sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; namespace sdbusRule = sdbusplus::bus::match::rules; Manager::Manager(sdbusplus::bus::bus& bus, sd_event* event) : - bus(bus), - timer(event, std::bind(&Manager::hostTimeout, this)), - hostTransitionMatch(bus, - sdbusRule::propertiesChanged( - HOST_STATE_PATH, - HOST_STATE_INTERFACE), - std::bind(&Manager::clearQueueOnPowerOn, this, - std::placeholders::_1)) + bus(bus), timer(event, std::bind(&Manager::hostTimeout, this)), + hostTransitionMatch( + bus, + sdbusRule::propertiesChanged(HOST_STATE_PATH, HOST_STATE_INTERFACE), + std::bind(&Manager::clearQueueOnPowerOn, this, std::placeholders::_1)) { // Nothing to do here. } @@ -51,10 +49,10 @@ IpmiCmdData Manager::getNextCommand() if (r < 0) { log("Failure to STOP the timer", - entry("ERROR=%s", strerror(-r))); + entry("ERROR=%s", strerror(-r))); } - if(this->workQueue.empty()) + if (this->workQueue.empty()) { // Just return a heartbeat in this case. A spurious SMS_ATN was // asserted for the host (probably from a previous boot). @@ -93,7 +91,7 @@ void Manager::hostTimeout() void Manager::clearQueue() { // Dequeue all entries and send fail signal - while(!this->workQueue.empty()) + while (!this->workQueue.empty()) { auto command = this->workQueue.front(); this->workQueue.pop(); @@ -117,11 +115,11 @@ void Manager::checkQueueAndAlertHost() std::string IPMI_PATH("/org/openbmc/HostIpmi/1"); std::string IPMI_INTERFACE("org.openbmc.HostIpmi"); - auto host = ::ipmi::getService(this->bus,IPMI_INTERFACE,IPMI_PATH); + auto host = ::ipmi::getService(this->bus, IPMI_INTERFACE, IPMI_PATH); // Start the timer for this transaction auto time = std::chrono::duration_cast( - std::chrono::seconds(IPMI_SMS_ATN_ACK_TIMEOUT_SECS)); + std::chrono::seconds(IPMI_SMS_ATN_ACK_TIMEOUT_SECS)); auto r = timer.startTimer(time); if (r < 0) @@ -130,10 +128,9 @@ void Manager::checkQueueAndAlertHost() return; } - auto method = this->bus.new_method_call(host.c_str(), - IPMI_PATH.c_str(), - IPMI_INTERFACE.c_str(), - "setAttention"); + auto method = + this->bus.new_method_call(host.c_str(), IPMI_PATH.c_str(), + IPMI_INTERFACE.c_str(), "setAttention"); auto reply = this->bus.call(method); if (reply.is_method_error()) @@ -149,7 +146,7 @@ void Manager::checkQueueAndAlertHost() void Manager::execute(CommandHandler command) { log("Pushing cmd on to queue", - entry("COMMAND=%d", std::get<0>(command).first)); + entry("COMMAND=%d", std::get<0>(command).first)); this->workQueue.emplace(command); @@ -184,7 +181,7 @@ void Manager::clearQueueOnPowerOn(sdbusplus::message::message& msg) auto& requestedState = properties.at(HOST_TRANS_PROP).get(); if (server::Host::convertTransitionFromString(requestedState) == - server::Host::Transition::On) + server::Host::Transition::On) { clearQueue(); } @@ -192,4 +189,4 @@ void Manager::clearQueueOnPowerOn(sdbusplus::message::message& msg) } // namespace command } // namespace host -} // namepsace phosphor +} // namespace phosphor diff --git a/host-cmd-manager.hpp b/host-cmd-manager.hpp index c25706c..949e798 100644 --- a/host-cmd-manager.hpp +++ b/host-cmd-manager.hpp @@ -1,11 +1,11 @@ #pragma once -#include +#include #include #include #include #include -#include +#include namespace phosphor { @@ -19,92 +19,92 @@ namespace command */ class Manager { - public: - Manager() = delete; - ~Manager() = default; - Manager(const Manager&) = delete; - Manager& operator=(const Manager&) = delete; - Manager(Manager&&) = delete; - Manager& operator=(Manager&&) = delete; + public: + Manager() = delete; + ~Manager() = default; + Manager(const Manager&) = delete; + Manager& operator=(const Manager&) = delete; + Manager(Manager&&) = delete; + Manager& operator=(Manager&&) = delete; - /** @brief Constructs Manager object - * - * @param[in] bus - dbus handler - * @param[in] event - pointer to sd_event - */ - Manager(sdbusplus::bus::bus& bus, sd_event* event); + /** @brief Constructs Manager object + * + * @param[in] bus - dbus handler + * @param[in] event - pointer to sd_event + */ + Manager(sdbusplus::bus::bus& bus, sd_event* event); - /** @brief Extracts the next entry in the queue and returns - * Command and data part of it. - * - * @detail Also calls into the registered handlers so that they can now - * send the CommandComplete signal since the interface contract - * is that we emit this signal once the message has been - * passed to the host (which is required when calling this) - * - * Also, if the queue has more commands, then it will alert the - * host - */ - IpmiCmdData getNextCommand(); + /** @brief Extracts the next entry in the queue and returns + * Command and data part of it. + * + * @detail Also calls into the registered handlers so that they can now + * send the CommandComplete signal since the interface contract + * is that we emit this signal once the message has been + * passed to the host (which is required when calling this) + * + * Also, if the queue has more commands, then it will alert the + * host + */ + IpmiCmdData getNextCommand(); - /** @brief Pushes the command onto the queue. - * - * @detail If the queue is empty, then it alerts the Host. If not, - * then it returns and the API documented above will handle - * the commands in Queue. - * - * @param[in] command - tuple of - */ - void execute(CommandHandler command); + /** @brief Pushes the command onto the queue. + * + * @detail If the queue is empty, then it alerts the Host. If not, + * then it returns and the API documented above will handle + * the commands in Queue. + * + * @param[in] command - tuple of + */ + void execute(CommandHandler command); - private: - /** @brief Check if anything in queue and alert host if so */ - void checkQueueAndAlertHost(); + private: + /** @brief Check if anything in queue and alert host if so */ + void checkQueueAndAlertHost(); - /** @brief Call back interface on message timeouts to host. - * - * @detail When this happens, a failure message would be sent - * to all the commands that are in the Queue and queue - * will be purged - */ - void hostTimeout(); + /** @brief Call back interface on message timeouts to host. + * + * @detail When this happens, a failure message would be sent + * to all the commands that are in the Queue and queue + * will be purged + */ + void hostTimeout(); - /** @brief Clears the command queue - * - * @detail Clears the command queue and calls all callbacks - * specifying the command wasn't successful. - */ - void clearQueue(); + /** @brief Clears the command queue + * + * @detail Clears the command queue and calls all callbacks + * specifying the command wasn't successful. + */ + void clearQueue(); - /** @brief Clears the command queue on a power on - * - * @detail The properties changed handler for the - * RequestedHostTransition property. When this property - * changes to 'On', this function will purge the command - * queue. - * - * This is done to avoid having commands that were issued - * before the host powers on from getting sent to the host, - * either due to race conditions around state transitions - * or from a user doing something like requesting an already - * powered off system to power off again and then immediately - * requesting a power on. - * - * @param[in] msg - the sdbusplus message containing the property - */ - void clearQueueOnPowerOn(sdbusplus::message::message& msg); + /** @brief Clears the command queue on a power on + * + * @detail The properties changed handler for the + * RequestedHostTransition property. When this property + * changes to 'On', this function will purge the command + * queue. + * + * This is done to avoid having commands that were issued + * before the host powers on from getting sent to the host, + * either due to race conditions around state transitions + * or from a user doing something like requesting an already + * powered off system to power off again and then immediately + * requesting a power on. + * + * @param[in] msg - the sdbusplus message containing the property + */ + void clearQueueOnPowerOn(sdbusplus::message::message& msg); - /** @brief Reference to the dbus handler */ - sdbusplus::bus::bus& bus; + /** @brief Reference to the dbus handler */ + sdbusplus::bus::bus& bus; - /** @brief Queue to store the requested commands */ - std::queue workQueue{}; + /** @brief Queue to store the requested commands */ + std::queue workQueue{}; - /** @brief Timer for commands to host */ - phosphor::ipmi::Timer timer; + /** @brief Timer for commands to host */ + phosphor::ipmi::Timer timer; - /** @brief Match handler for the requested host state */ - sdbusplus::bus::match_t hostTransitionMatch; + /** @brief Match handler for the requested host state */ + sdbusplus::bus::match_t hostTransitionMatch; }; } // namespace command diff --git a/host-interface.cpp b/host-interface.cpp index 8663929..1f27163 100644 --- a/host-interface.cpp +++ b/host-interface.cpp @@ -1,11 +1,12 @@ -#include +#include #include -#include + +#include +#include #include -#include +#include #include -#include -#include +#include namespace phosphor { namespace host @@ -25,44 +26,30 @@ using OEMCmd = uint8_t; // This is needed when invoking the callback handler to indicate // the status of the executed command. static const std::map intfCommand = { - { - CMD_HEARTBEAT, - Base::Host::Command::Heartbeat - }, - { - CMD_POWER, - Base::Host::Command::SoftOff - } -}; + {CMD_HEARTBEAT, Base::Host::Command::Heartbeat}, + {CMD_POWER, Base::Host::Command::SoftOff}}; // Map of Interface command to its corresponding IPMI OEM command. // This is needed when pushing IPMI commands to command manager's // queue. The same pair will be returned when IPMI asks us // why a SMS_ATN was sent static const std::map ipmiCommand = { - { - Base::Host::Command::Heartbeat, - std::make_pair(CMD_HEARTBEAT, 0x00) - }, - { - Base::Host::Command::SoftOff, - std::make_pair(CMD_POWER, SOFT_OFF) - } -}; + {Base::Host::Command::Heartbeat, std::make_pair(CMD_HEARTBEAT, 0x00)}, + {Base::Host::Command::SoftOff, std::make_pair(CMD_POWER, SOFT_OFF)}}; // Called at user request void Host::execute(Base::Host::Command command) { using namespace phosphor::logging; - log("Pushing cmd on to queue", - entry("CONTROL_HOST_CMD=%s", - convertForMessage(command).c_str())); + log( + "Pushing cmd on to queue", + entry("CONTROL_HOST_CMD=%s", convertForMessage(command).c_str())); auto cmd = std::make_tuple(ipmiCommand.at(command), - std::bind(&Host::commandStatusHandler, - this, std::placeholders::_1, - std::placeholders::_2)); + std::bind(&Host::commandStatusHandler, this, + std::placeholders::_1, + std::placeholders::_2)); return ipmid_send_cmd_to_host(std::move(cmd)); } @@ -79,4 +66,4 @@ void Host::commandStatusHandler(IpmiCmdData cmd, bool status) } // namespace command } // namespace host -} // namepsace phosphor +} // namespace phosphor diff --git a/host-interface.hpp b/host-interface.hpp index 5b2ac68..5c95a66 100644 --- a/host-interface.hpp +++ b/host-interface.hpp @@ -1,8 +1,8 @@ #pragma once +#include #include #include -#include namespace phosphor { namespace host @@ -16,46 +16,45 @@ namespace command * DBus API. */ class Host : public sdbusplus::server::object::object< - sdbusplus::xyz::openbmc_project::Control::server::Host> + sdbusplus::xyz::openbmc_project::Control::server::Host> { - public: - /** @brief Constructs Host Control Interface - * - * @param[in] bus - The Dbus bus object - * @param[in] objPath - The Dbus object path - */ - Host(sdbusplus::bus::bus& bus, - const char* objPath) : - sdbusplus::server::object::object< - sdbusplus::xyz::openbmc_project::Control::server::Host>( - bus, objPath), - bus(bus) - { - // Nothing to do - } + public: + /** @brief Constructs Host Control Interface + * + * @param[in] bus - The Dbus bus object + * @param[in] objPath - The Dbus object path + */ + Host(sdbusplus::bus::bus& bus, const char* objPath) : + sdbusplus::server::object::object< + sdbusplus::xyz::openbmc_project::Control::server::Host>(bus, + objPath), + bus(bus) + { + // Nothing to do + } - /** @brief Send input command to host - * Note that the command will be queued in a FIFO if - * other commands to the host have yet to be run - * - * @param[in] command - Input command to execute - */ - void execute(Command command) override; + /** @brief Send input command to host + * Note that the command will be queued in a FIFO if + * other commands to the host have yet to be run + * + * @param[in] command - Input command to execute + */ + void execute(Command command) override; - private: - /** @brief sdbusplus DBus bus connection. */ - sdbusplus::bus::bus& bus; + private: + /** @brief sdbusplus DBus bus connection. */ + sdbusplus::bus::bus& bus; - /** @brief Callback function to be invoked by command manager - * - * @detail Conveys the status of the last Host bound command. - * Depending on the status, a CommandComplete or - * CommandFailure signal would be sent - * - * @param[in] cmd - IPMI command and data sent to Host - * @param[in] status - Success or Failure - */ - void commandStatusHandler(IpmiCmdData cmd, bool status); + /** @brief Callback function to be invoked by command manager + * + * @detail Conveys the status of the last Host bound command. + * Depending on the status, a CommandComplete or + * CommandFailure signal would be sent + * + * @param[in] cmd - IPMI command and data sent to Host + * @param[in] status - Success or Failure + */ + void commandStatusHandler(IpmiCmdData cmd, bool status); }; } // namespace command diff --git a/host-ipmid/ipmid-api.h b/host-ipmid/ipmid-api.h index 1bec851..a085270 100644 --- a/host-ipmid/ipmid-api.h +++ b/host-ipmid/ipmid-api.h @@ -13,13 +13,14 @@ extern "C" { * privilege level. Those commands which can be executed via system interface * only should use SYSTEM_INTERFACE */ -enum CommandPrivilege { - PRIVILEGE_CALLBACK = 0x01, - PRIVILEGE_USER, - PRIVILEGE_OPERATOR, - PRIVILEGE_ADMIN, - PRIVILEGE_OEM, - SYSTEM_INTERFACE = 0xFF, +enum CommandPrivilege +{ + PRIVILEGE_CALLBACK = 0x01, + PRIVILEGE_USER, + PRIVILEGE_OPERATOR, + PRIVILEGE_ADMIN, + PRIVILEGE_OEM, + SYSTEM_INTERFACE = 0xFF, }; // length of Completion Code and its ALWAYS _1_ @@ -28,13 +29,13 @@ enum CommandPrivilege { // IPMI Net Function number as specified by IPMI V2.0 spec. // Example : // NETFUN_APP = (0x06 << 2), -typedef unsigned char ipmi_netfn_t; +typedef unsigned char ipmi_netfn_t; // IPMI Command for a Net Function number as specified by IPMI V2.0 spec. -typedef unsigned char ipmi_cmd_t; +typedef unsigned char ipmi_cmd_t; // Buffer containing data from sender of netfn and command as part of request -typedef void* ipmi_request_t; +typedef void* ipmi_request_t; // This is the response buffer that the provider of [netfn,cmd] will send back // to the caller. Provider will allocate the memory inside the handler and then @@ -44,7 +45,7 @@ typedef void* ipmi_request_t; // unsigned char str[] = {0x00, 0x01, 0xFE, 0xFF, 0x0A, 0x01}; // *data_len = 6; // memcpy(response, &str, *data_len); -typedef void* ipmi_response_t; +typedef void* ipmi_response_t; // This buffer contains any *user specific* data that is of interest only to the // plugin. For a ipmi function router, this data is opaque. At the time of @@ -52,11 +53,11 @@ typedef void* ipmi_response_t; // fill in whatever needed that will be of help during the actual handling of // command. IPMID will just pass the netfn, cmd and also this data to plugins // during the command handler invocation. -typedef void* ipmi_context_t; +typedef void* ipmi_context_t; // Length of request / response buffer depending on whether the data is a // request or a response from a plugin handler. -typedef size_t* ipmi_data_len_t; +typedef size_t* ipmi_data_len_t; // Plugin function return the status code typedef unsigned char ipmi_ret_t; @@ -67,14 +68,14 @@ typedef enum CommandPrivilege ipmi_cmd_privilege_t; // function router will then make a call to this callback handler with the // necessary arguments of netfn, cmd, request, response, size and context. typedef ipmi_ret_t (*ipmid_callback_t)(ipmi_netfn_t, ipmi_cmd_t, ipmi_request_t, - ipmi_response_t, ipmi_data_len_t, ipmi_context_t); + ipmi_response_t, ipmi_data_len_t, + ipmi_context_t); // This is the constructor function that is called into by each plugin handlers. // When ipmi sets up the callback handlers, a call is made to this with // information of netfn, cmd, callback handler pointer and context data. -void ipmi_register_callback(ipmi_netfn_t, ipmi_cmd_t, ipmi_context_t, ipmid_callback_t, - ipmi_cmd_privilege_t); - +void ipmi_register_callback(ipmi_netfn_t, ipmi_cmd_t, ipmi_context_t, + ipmid_callback_t, ipmi_cmd_privilege_t); unsigned short get_sel_reserve_id(void); @@ -85,18 +86,18 @@ unsigned short get_sel_reserve_id(void); // Note: these are also shifted left to make room for the LUN. enum ipmi_net_fns { - NETFUN_CHASSIS = 0x00, - NETFUN_BRIDGE = 0x02, - NETFUN_SENSOR = 0x04, - NETFUN_APP = 0x06, - NETFUN_FIRMWARE = 0x08, - NETFUN_STORAGE = 0x0a, - NETFUN_TRANSPORT = 0x0c, - NETFUN_GRPEXT = 0x2c, - NETFUN_OEM_GROUP = 0x2e, - NETFUN_NONE = 0x30, - NETFUN_OEM = 0x32, - NETFUN_IBM_OEM = 0x3A + NETFUN_CHASSIS = 0x00, + NETFUN_BRIDGE = 0x02, + NETFUN_SENSOR = 0x04, + NETFUN_APP = 0x06, + NETFUN_FIRMWARE = 0x08, + NETFUN_STORAGE = 0x0a, + NETFUN_TRANSPORT = 0x0c, + NETFUN_GRPEXT = 0x2c, + NETFUN_OEM_GROUP = 0x2e, + NETFUN_NONE = 0x30, + NETFUN_OEM = 0x32, + NETFUN_IBM_OEM = 0x3A }; // IPMI commands for net functions. Since this is to be used both by the ipmi @@ -104,7 +105,7 @@ enum ipmi_net_fns // in this .H file. enum ipmi_netfn_wild_card_cmd { - IPMI_CMD_WILDCARD = 0xFF, + IPMI_CMD_WILDCARD = 0xFF, }; // Return (completion) codes from a IPMI operation as needed by IPMI V2.0 spec. @@ -126,9 +127,9 @@ enum ipmi_return_codes IPMI_CC_UNSPECIFIED_ERROR = 0xFF, }; -sd_bus *ipmid_get_sd_bus_connection(void); -sd_event *ipmid_get_sd_event_connection(void); -sd_bus_slot *ipmid_get_sd_bus_slot(void); +sd_bus* ipmid_get_sd_bus_connection(void); +sd_event* ipmid_get_sd_event_connection(void); +sd_bus_slot* ipmid_get_sd_bus_slot(void); #ifdef __cplusplus } diff --git a/host-ipmid/ipmid-host-cmd-utils.hpp b/host-ipmid/ipmid-host-cmd-utils.hpp index 293cc0c..e7c6dc2 100644 --- a/host-ipmid/ipmid-host-cmd-utils.hpp +++ b/host-ipmid/ipmid-host-cmd-utils.hpp @@ -1,7 +1,8 @@ #pragma once -#include #include + +#include #include namespace phosphor @@ -10,40 +11,40 @@ namespace host { namespace command { - /** @detail After sending SMS_ATN to the Host, Host comes down and - * asks why an 'SMS_ATN` was sent. - * BMC then sends 'There is a Message to be Read` as response. - * Host then comes down asks for Message and the specified - * commands and data would go as data conforming to IPMI spec. - * - * Refer: 6.13.2 Send Message Command From System Interface - * in IPMI V2.0 spec. - */ - - /** @brief IPMI command */ - using IPMIcmd = uint8_t; - - /** @brief Data associated with command */ - using Data = uint8_t; - - /** @brief to be sent as payload when Host asks for - * the message that can be associated with the previous SMS_ATN - */ - using IpmiCmdData = std::pair; - - /** @detail Implementation specific callback function to be invoked - * conveying the status of the executed command. Specific - * implementations may then broadcast an agreed signal - */ - using CallBack = std::function; - - /** @detail Tuple encapsulating above 2 to enable using Manager by - * different implementations. Users of Manager will supply - * along with the callback handler. - * Manager will invoke the handler onveying the status of - * the command. - */ - using CommandHandler = std::tuple; +/** @detail After sending SMS_ATN to the Host, Host comes down and + * asks why an 'SMS_ATN` was sent. + * BMC then sends 'There is a Message to be Read` as response. + * Host then comes down asks for Message and the specified + * commands and data would go as data conforming to IPMI spec. + * + * Refer: 6.13.2 Send Message Command From System Interface + * in IPMI V2.0 spec. + */ + +/** @brief IPMI command */ +using IPMIcmd = uint8_t; + +/** @brief Data associated with command */ +using Data = uint8_t; + +/** @brief to be sent as payload when Host asks for + * the message that can be associated with the previous SMS_ATN + */ +using IpmiCmdData = std::pair; + +/** @detail Implementation specific callback function to be invoked + * conveying the status of the executed command. Specific + * implementations may then broadcast an agreed signal + */ +using CallBack = std::function; + +/** @detail Tuple encapsulating above 2 to enable using Manager by + * different implementations. Users of Manager will supply + * along with the callback handler. + * Manager will invoke the handler onveying the status of + * the command. + */ +using CommandHandler = std::tuple; } // namespace command } // namespace host diff --git a/host-ipmid/ipmid-host-cmd.hpp b/host-ipmid/ipmid-host-cmd.hpp index 6541bae..4fd95a9 100644 --- a/host-ipmid/ipmid-host-cmd.hpp +++ b/host-ipmid/ipmid-host-cmd.hpp @@ -1,9 +1,10 @@ +#include "ipmid-host-cmd-utils.hpp" + #include #include -#include "ipmid-host-cmd-utils.hpp" // Need this to use new sdbusplus compatible interfaces -using sdbusPtr = std::unique_ptr; +using sdbusPtr = std::unique_ptr; extern sdbusPtr& ipmid_get_sdbus_plus_handler(); // Global Host Bound Command manager diff --git a/host-ipmid/oemopenbmc.hpp b/host-ipmid/oemopenbmc.hpp index c3bfaa4..8b5dc0c 100644 --- a/host-ipmid/oemopenbmc.hpp +++ b/host-ipmid/oemopenbmc.hpp @@ -1,8 +1,9 @@ #pragma once -#include "host-ipmid/ipmid-api.h" #include "host-ipmid/oemrouter.hpp" +#include "host-ipmid/ipmid-api.h" + namespace oem { @@ -22,4 +23,4 @@ enum Cmd fanManualCmd = 4, }; -} // namespace oem +} // namespace oem diff --git a/host-ipmid/oemrouter.hpp b/host-ipmid/oemrouter.hpp index bc2b88c..d6f0735 100644 --- a/host-ipmid/oemrouter.hpp +++ b/host-ipmid/oemrouter.hpp @@ -12,38 +12,39 @@ namespace oem constexpr size_t groupMagicSize = 3; using Group = std::array; -using Number = uint32_t; // smallest standard size >= 24. +using Number = uint32_t; // smallest standard size >= 24. // Handler signature includes ipmi cmd to support wildcard cmd match. // Buffers and lengths exclude the OemGroup bytes in the IPMI message. // dataLen supplies length of reqBuf upon call, and should be set to the // length of replyBuf upon return - conventional in this code base. -using Handler = std::function; // dataLen +using Handler = std::function; // dataLen /// Router Interface class. /// @brief Abstract Router Interface class Router { - public: - virtual ~Router() {} + public: + virtual ~Router() + { + } - /// Enable message routing to begin. - virtual void activate() = 0; + /// Enable message routing to begin. + virtual void activate() = 0; - /// Register a handler for given OEMNumber & cmd. - /// Use IPMI_CMD_WILDCARD to catch any unregistered cmd - /// for the given OEMNumber. - /// - /// @param[in] oen - the OEM Number. - /// @param[in] cmd - the Command. - /// @param[in] handler - the handler to call given that OEN and - /// command. - virtual void registerHandler(Number oen, ipmi_cmd_t cmd, - Handler handler) = 0; + /// Register a handler for given OEMNumber & cmd. + /// Use IPMI_CMD_WILDCARD to catch any unregistered cmd + /// for the given OEMNumber. + /// + /// @param[in] oen - the OEM Number. + /// @param[in] cmd - the Command. + /// @param[in] handler - the handler to call given that OEN and + /// command. + virtual void registerHandler(Number oen, ipmi_cmd_t cmd, + Handler handler) = 0; }; /// Expose mutable Router for configuration & activation. @@ -75,9 +76,8 @@ constexpr Number toOemNumber(const Group& oeg) /// @return the OEM Group. constexpr Group toOemGroup(Number oen) { - return Group { static_cast(oen), - static_cast(oen >> 8), - static_cast(oen >> 16) }; + return Group{static_cast(oen), static_cast(oen >> 8), + static_cast(oen >> 16)}; } -} // namespace oem +} // namespace oem diff --git a/ipmi_fru_info_area.cpp b/ipmi_fru_info_area.cpp index ca3fa64..47979e9 100644 --- a/ipmi_fru_info_area.cpp +++ b/ipmi_fru_info_area.cpp @@ -1,10 +1,9 @@ +#include "ipmi_fru_info_area.hpp" + #include +#include #include #include - -#include - -#include "ipmi_fru_info_area.hpp" #include namespace ipmi { @@ -12,38 +11,38 @@ namespace fru { using namespace phosphor::logging; -//Property variables -static constexpr auto partNumber = "PartNumber"; -static constexpr auto serialNumber = "SerialNumber"; -static constexpr auto manufacturer = "Manufacturer"; -static constexpr auto buildDate = "BuildDate"; -static constexpr auto model = "Model"; -static constexpr auto prettyName = "PrettyName"; -static constexpr auto version = "Version"; - -//Board info areas -static constexpr auto board = "Board"; -static constexpr auto chassis = "Chassis"; -static constexpr auto product = "Product"; - -static constexpr auto specVersion = 0x1; -static constexpr auto recordUnitOfMeasurement = 0x8; //size in bytes -static constexpr auto checksumSize = 0x1; //size in bytes -static constexpr auto recordNotPresent = 0x0; -static constexpr auto englishLanguageCode = 0x0; -static constexpr auto typeLengthByteNull = 0x0; -static constexpr auto endOfCustomFields = 0xC1; -static constexpr auto commonHeaderFormatSize = 0x8; //size in bytes -static constexpr auto manufacturingDateSize = 0x3; -static constexpr auto areaSizeOffset = 0x1; -static constexpr uint8_t typeASCII = 0xC0; -static constexpr auto maxRecordAttributeValue = 0x1F; +// Property variables +static constexpr auto partNumber = "PartNumber"; +static constexpr auto serialNumber = "SerialNumber"; +static constexpr auto manufacturer = "Manufacturer"; +static constexpr auto buildDate = "BuildDate"; +static constexpr auto model = "Model"; +static constexpr auto prettyName = "PrettyName"; +static constexpr auto version = "Version"; + +// Board info areas +static constexpr auto board = "Board"; +static constexpr auto chassis = "Chassis"; +static constexpr auto product = "Product"; + +static constexpr auto specVersion = 0x1; +static constexpr auto recordUnitOfMeasurement = 0x8; // size in bytes +static constexpr auto checksumSize = 0x1; // size in bytes +static constexpr auto recordNotPresent = 0x0; +static constexpr auto englishLanguageCode = 0x0; +static constexpr auto typeLengthByteNull = 0x0; +static constexpr auto endOfCustomFields = 0xC1; +static constexpr auto commonHeaderFormatSize = 0x8; // size in bytes +static constexpr auto manufacturingDateSize = 0x3; +static constexpr auto areaSizeOffset = 0x1; +static constexpr uint8_t typeASCII = 0xC0; +static constexpr auto maxRecordAttributeValue = 0x1F; static constexpr auto secs_from_1970_1996 = 820454400; -static constexpr auto maxMfgDateValue = 0xFFFFFF; //3 Byte length +static constexpr auto maxMfgDateValue = 0xFFFFFF; // 3 Byte length static constexpr auto secs_per_min = 60; -static constexpr auto - secsToMaxMfgdate = secs_from_1970_1996 + secs_per_min * maxMfgDateValue; +static constexpr auto secsToMaxMfgdate = + secs_from_1970_1996 + secs_per_min * maxMfgDateValue; /** * @brief Format Beginning of Individual IPMI FRU Data Section @@ -53,10 +52,10 @@ static constexpr auto */ void preFormatProcessing(bool langCode, FruAreaData& data) { - //Add id for version of FRU Info Storage Spec used + // Add id for version of FRU Info Storage Spec used data.emplace_back(specVersion); - //Add Data Size - 0 as a placeholder, can edit after the data is finalized + // Add Data Size - 0 as a placeholder, can edit after the data is finalized data.emplace_back(typeLengthByteNull); if (langCode) @@ -99,14 +98,14 @@ void padData(FruAreaData& data) */ void postFormatProcessing(FruAreaData& data) { - //This area needs to be padded to a multiple of 8 bytes (after checksum) + // This area needs to be padded to a multiple of 8 bytes (after checksum) padData(data); - //Set size of data info area - data.at(areaSizeOffset) = (data.size() + checksumSize) / - (recordUnitOfMeasurement); + // Set size of data info area + data.at(areaSizeOffset) = + (data.size() + checksumSize) / (recordUnitOfMeasurement); - //Finally add area checksum + // Finally add area checksum appendDataChecksum(data); } @@ -124,35 +123,35 @@ void appendData(const Property& key, const PropertyMap& propMap, if (iter != propMap.end()) { auto value = iter->second; - //If starts with 0x or 0X remove them - //ex: 0x123a just take 123a + // If starts with 0x or 0X remove them + // ex: 0x123a just take 123a if ((value.compare(0, 2, "0x")) == 0 || - (value.compare(0, 2, "0X") == 0)) + (value.compare(0, 2, "0X") == 0)) { value.erase(0, 2); } // 5 bits for length - // if length is greater then 31(2^5) bytes then trim the data to 31 bytess. - auto valueLength = (value.length() > maxRecordAttributeValue) ? - maxRecordAttributeValue : value.length(); + // if length is greater then 31(2^5) bytes then trim the data to 31 + // bytess. + auto valueLength = (value.length() > maxRecordAttributeValue) + ? maxRecordAttributeValue + : value.length(); // 2 bits for type // Set the type to ascii uint8_t typeLength = valueLength | ipmi::fru::typeASCII; data.emplace_back(typeLength); - std::copy(value.begin(), - value.begin() + valueLength, + std::copy(value.begin(), value.begin() + valueLength, std::back_inserter(data)); } else { - //set 0 size + // set 0 size data.emplace_back(typeLengthByteNull); } } - /** * @brief Appends Build Date * @@ -161,7 +160,7 @@ void appendData(const Property& key, const PropertyMap& propMap, */ void appendMfgDate(const PropertyMap& propMap, FruAreaData& data) { - //MFG Date/Time + // MFG Date/Time auto iter = propMap.find(buildDate); if ((iter != propMap.end()) && (iter->second.size() > 0)) { @@ -188,7 +187,7 @@ void appendMfgDate(const PropertyMap& propMap, FruAreaData& data) fprintf(stderr, "MgfDate invalid date: %u secs since UNIX epoch\n", static_cast(raw)); } - //Blank date + // Blank date data.emplace_back(0); data.emplace_back(0); data.emplace_back(0); @@ -201,13 +200,13 @@ void appendMfgDate(const PropertyMap& propMap, FruAreaData& data) * @param[in] offset Current offset for data in overall record * @param[in/out] data Common Header section data container */ -void buildCommonHeaderSection( - const uint32_t& infoAreaSize, uint16_t& offset, FruAreaData& data) +void buildCommonHeaderSection(const uint32_t& infoAreaSize, uint16_t& offset, + FruAreaData& data) { - //Check if data for internal use section populated + // Check if data for internal use section populated if (infoAreaSize == 0) { - //Indicate record not present + // Indicate record not present data.emplace_back(recordNotPresent); } else @@ -217,7 +216,7 @@ void buildCommonHeaderSection( // add the padding bytes in the offset so that offset // will be multiple of 8 byte. offset += (remainder > 0) ? recordUnitOfMeasurement - remainder : 0; - //Place data to define offset to area data section + // Place data to define offset to area data section data.emplace_back(offset / recordUnitOfMeasurement); offset += infoAreaSize; @@ -235,22 +234,22 @@ FruAreaData buildChassisInfoArea(const PropertyMap& propMap) FruAreaData fruAreaData; if (!propMap.empty()) { - //Set formatting data that goes at the beginning of the record + // Set formatting data that goes at the beginning of the record preFormatProcessing(false, fruAreaData); - //chassis type + // chassis type fruAreaData.emplace_back(0); - //Chasiss part number, in config.yaml it is configured as model + // Chasiss part number, in config.yaml it is configured as model appendData(model, propMap, fruAreaData); - //Board serial number + // Board serial number appendData(serialNumber, propMap, fruAreaData); - //Indicate End of Custom Fields + // Indicate End of Custom Fields fruAreaData.emplace_back(endOfCustomFields); - //Complete record data formatting + // Complete record data formatting postFormatProcessing(fruAreaData); } return fruAreaData; @@ -269,28 +268,28 @@ FruAreaData buildBoardInfoArea(const PropertyMap& propMap) { preFormatProcessing(true, fruAreaData); - //Manufacturing date + // Manufacturing date appendMfgDate(propMap, fruAreaData); - //manufacturer + // manufacturer appendData(manufacturer, propMap, fruAreaData); - //Product name/Pretty name + // Product name/Pretty name appendData(prettyName, propMap, fruAreaData); - //Board serial number + // Board serial number appendData(serialNumber, propMap, fruAreaData); - //Board part number + // Board part number appendData(partNumber, propMap, fruAreaData); - //FRU File ID - Empty + // FRU File ID - Empty fruAreaData.emplace_back(typeLengthByteNull); // Empty FRU File ID bytes fruAreaData.emplace_back(recordNotPresent); - //End of custom fields + // End of custom fields fruAreaData.emplace_back(endOfCustomFields); postFormatProcessing(fruAreaData); @@ -309,34 +308,34 @@ FruAreaData buildProductInfoArea(const PropertyMap& propMap) FruAreaData fruAreaData; if (!propMap.empty()) { - //Set formatting data that goes at the beginning of the record + // Set formatting data that goes at the beginning of the record preFormatProcessing(true, fruAreaData); - //manufacturer + // manufacturer appendData(manufacturer, propMap, fruAreaData); - //Product name/Pretty name + // Product name/Pretty name appendData(prettyName, propMap, fruAreaData); - //Product part/model number + // Product part/model number appendData(model, propMap, fruAreaData); - //Product version + // Product version appendData(version, propMap, fruAreaData); - //Serial Number + // Serial Number appendData(serialNumber, propMap, fruAreaData); - //Add Asset Tag + // Add Asset Tag fruAreaData.emplace_back(recordNotPresent); - //FRU File ID - Empty + // FRU File ID - Empty fruAreaData.emplace_back(typeLengthByteNull); // Empty FRU File ID bytes fruAreaData.emplace_back(recordNotPresent); - //End of custom fields + // End of custom fields fruAreaData.emplace_back(endOfCustomFields); postFormatProcessing(fruAreaData); @@ -347,17 +346,17 @@ FruAreaData buildProductInfoArea(const PropertyMap& propMap) FruAreaData buildFruAreaData(const FruInventoryData& inventory) { FruAreaData combFruArea{}; - //Now build common header with data for this FRU Inv Record - //Use this variable to increment size of header as we go along to determine - //offset for the subsequent area offsets + // Now build common header with data for this FRU Inv Record + // Use this variable to increment size of header as we go along to determine + // offset for the subsequent area offsets uint16_t curDataOffset = commonHeaderFormatSize; - //First byte is id for version of FRU Info Storage Spec used + // First byte is id for version of FRU Info Storage Spec used combFruArea.emplace_back(specVersion); - //2nd byte is offset to internal use data + // 2nd byte is offset to internal use data combFruArea.emplace_back(recordNotPresent); - //3rd byte is offset to chassis data + // 3rd byte is offset to chassis data FruAreaData chassisArea; auto chassisIt = inventory.find(chassis); if (chassisIt != inventory.end()) @@ -367,7 +366,7 @@ FruAreaData buildFruAreaData(const FruInventoryData& inventory) // update the offset to chassis data. buildCommonHeaderSection(chassisArea.size(), curDataOffset, combFruArea); - //4th byte is offset to board data + // 4th byte is offset to board data FruAreaData boardArea; auto boardIt = inventory.find(board); if (boardIt != inventory.end()) @@ -377,7 +376,7 @@ FruAreaData buildFruAreaData(const FruInventoryData& inventory) // update the offset to the board data. buildCommonHeaderSection(boardArea.size(), curDataOffset, combFruArea); - //5th byte is offset to product data + // 5th byte is offset to product data FruAreaData prodArea; auto prodIt = inventory.find(product); if (prodIt != inventory.end()) @@ -387,28 +386,28 @@ FruAreaData buildFruAreaData(const FruInventoryData& inventory) // update the offset to the product data. buildCommonHeaderSection(prodArea.size(), curDataOffset, combFruArea); - //6th byte is offset to multirecord data + // 6th byte is offset to multirecord data combFruArea.emplace_back(recordNotPresent); - //7th byte is PAD + // 7th byte is PAD combFruArea.emplace_back(recordNotPresent); - //8th (Final byte of Header Format) is the checksum + // 8th (Final byte of Header Format) is the checksum appendDataChecksum(combFruArea); - //Combine everything into one full IPMI FRU specification Record - //add chassis use area data - combFruArea.insert( - combFruArea.end(), chassisArea.begin(), chassisArea.end()); + // Combine everything into one full IPMI FRU specification Record + // add chassis use area data + combFruArea.insert(combFruArea.end(), chassisArea.begin(), + chassisArea.end()); - //add board area data + // add board area data combFruArea.insert(combFruArea.end(), boardArea.begin(), boardArea.end()); - //add product use area data + // add product use area data combFruArea.insert(combFruArea.end(), prodArea.begin(), prodArea.end()); return combFruArea; } -} //fru -} //ipmi +} // namespace fru +} // namespace ipmi diff --git a/ipmi_fru_info_area.hpp b/ipmi_fru_info_area.hpp index 9fe0107..462a4ac 100644 --- a/ipmi_fru_info_area.hpp +++ b/ipmi_fru_info_area.hpp @@ -24,6 +24,5 @@ using FruInventoryData = std::map; */ FruAreaData buildFruAreaData(const FruInventoryData& inventory); -} //fru -} //ipmi - +} // namespace fru +} // namespace ipmi diff --git a/ipmid.cpp b/ipmid.cpp index f664488..6da7ff2 100644 --- a/ipmid.cpp +++ b/ipmid.cpp @@ -1,40 +1,43 @@ -#include -#include -#include -#include +#include "ipmid.hpp" + +#include "host-ipmid/oemrouter.hpp" +#include "settings.hpp" + #include #include -#include -#include -#include -#include -#include -#include -#include +#include #include #include -#include "sensorhandler.h" -#include +#include +#include +#include +#include +#include +#include + #include -#include +#include +#include +#include #include +#include +#include +#include +#include #include #include +#include +#include #include + #include "sensorhandler.h" -#include "ipmid.hpp" -#include "settings.hpp" -#include -#include -#include -#include "host-ipmid/oemrouter.hpp" using namespace phosphor::logging; namespace sdbusRule = sdbusplus::bus::match::rules; -sd_bus *bus = NULL; -sd_bus_slot *ipmid_slot = NULL; -sd_event *events = nullptr; +sd_bus* bus = NULL; +sd_bus_slot* ipmid_slot = NULL; +sd_event* events = nullptr; // Need this to use new sdbusplus compatible interfaces sdbusPtr sdbusp; @@ -55,17 +58,19 @@ bool restricted_mode = true; FILE *ipmiio, *ipmidbus, *ipmicmddetails; -void print_usage(void) { - fprintf(stderr, "Options: [-d mask]\n"); - fprintf(stderr, " mask : 0x01 - Print ipmi packets\n"); - fprintf(stderr, " mask : 0x02 - Print DBUS operations\n"); - fprintf(stderr, " mask : 0x04 - Print ipmi command details\n"); - fprintf(stderr, " mask : 0xFF - Print all trace\n"); +void print_usage(void) +{ + fprintf(stderr, "Options: [-d mask]\n"); + fprintf(stderr, " mask : 0x01 - Print ipmi packets\n"); + fprintf(stderr, " mask : 0x02 - Print DBUS operations\n"); + fprintf(stderr, " mask : 0x04 - Print ipmi command details\n"); + fprintf(stderr, " mask : 0xFF - Print all trace\n"); } -const char * DBUS_INTF = "org.openbmc.HostIpmi"; +const char* DBUS_INTF = "org.openbmc.HostIpmi"; -const char * FILTER = "type='signal',interface='org.openbmc.HostIpmi',member='ReceivedMessage'"; +const char* FILTER = + "type='signal',interface='org.openbmc.HostIpmi',member='ReceivedMessage'"; typedef std::pair ipmi_fn_cmd_t; typedef std::pair ipmi_fn_context_t; @@ -99,55 +104,59 @@ std::unique_ptr objects = nullptr; #define HEXDUMP_COLS 16 #endif -void hexdump(FILE *s, void *mem, size_t len) +void hexdump(FILE* s, void* mem, size_t len) { - unsigned int i, j; + unsigned int i, j; - for(i = 0; i < len + ((len % HEXDUMP_COLS) ? (HEXDUMP_COLS - len % HEXDUMP_COLS) : 0); i++) + for (i = 0; + i < + len + ((len % HEXDUMP_COLS) ? (HEXDUMP_COLS - len % HEXDUMP_COLS) : 0); + i++) + { + /* print offset */ + if (i % HEXDUMP_COLS == 0) { - /* print offset */ - if(i % HEXDUMP_COLS == 0) - { - fprintf(s,"0x%06x: ", i); - } + fprintf(s, "0x%06x: ", i); + } - /* print hex data */ - if(i < len) + /* print hex data */ + if (i < len) + { + fprintf(s, "%02x ", 0xFF & ((char*)mem)[i]); + } + else /* end of block, just aligning for ASCII dump */ + { + fprintf(s, " "); + } + + /* print ASCII dump */ + if (i % HEXDUMP_COLS == (HEXDUMP_COLS - 1)) + { + for (j = i - (HEXDUMP_COLS - 1); j <= i; j++) + { + if (j >= len) /* end of block, not really printing */ { - fprintf(s,"%02x ", 0xFF & ((char*)mem)[i]); + fputc(' ', s); } - else /* end of block, just aligning for ASCII dump */ + else if (isprint(((char*)mem)[j])) /* printable char */ { - fprintf(s," "); + fputc(0xFF & ((char*)mem)[j], s); } - - /* print ASCII dump */ - if(i % HEXDUMP_COLS == (HEXDUMP_COLS - 1)) + else /* other char */ { - for(j = i - (HEXDUMP_COLS - 1); j <= i; j++) - { - if(j >= len) /* end of block, not really printing */ - { - fputc(' ', s); - } - else if(isprint(((char*)mem)[j])) /* printable char */ - { - fputc(0xFF & ((char*)mem)[j], s); - } - else /* other char */ - { - fputc('.',s); - } - } - fputc('\n',s); + fputc('.', s); } + } + fputc('\n', s); } + } } - -// Method that gets called by shared libraries to get their command handlers registered -void ipmi_register_callback(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_context_t context, - ipmid_callback_t handler, ipmi_cmd_privilege_t priv) +// Method that gets called by shared libraries to get their command handlers +// registered +void ipmi_register_callback(ipmi_netfn_t netfn, ipmi_cmd_t cmd, + ipmi_context_t context, ipmid_callback_t handler, + ipmi_cmd_privilege_t priv) { // Pack NetFn and Command in one. auto netfn_and_cmd = std::make_pair(netfn, cmd); @@ -157,10 +166,9 @@ void ipmi_register_callback(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_context_t c // Check if the registration has already been made.. auto iter = g_ipmid_router_map.find(netfn_and_cmd); - if(iter != g_ipmid_router_map.end()) + if (iter != g_ipmid_router_map.end()) { - log("Duplicate registration", - entry("NETFN=0x%X", netfn), + log("Duplicate registration", entry("NETFN=0x%X", netfn), entry("CMD=0x%X", cmd)); } else @@ -173,22 +181,22 @@ void ipmi_register_callback(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_context_t c } // Looks at the map and calls corresponding handler functions. -ipmi_ret_t ipmi_netfn_router(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, - ipmi_response_t response, ipmi_data_len_t data_len) +ipmi_ret_t ipmi_netfn_router(ipmi_netfn_t netfn, ipmi_cmd_t cmd, + ipmi_request_t request, ipmi_response_t response, + ipmi_data_len_t data_len) { // return from the Command handlers. ipmi_ret_t rc = IPMI_CC_INVALID; // If restricted mode is true and command is not whitelisted, don't // execute the command - if(restricted_mode) + if (restricted_mode) { if (!std::binary_search(whitelist.cbegin(), whitelist.cend(), - std::make_pair(netfn, cmd))) + std::make_pair(netfn, cmd))) { log("Net function not whitelisted", - entry("NETFN=0x%X", netfn), - entry("CMD=0x%X", cmd)); + entry("NETFN=0x%X", netfn), entry("CMD=0x%X", cmd)); rc = IPMI_CC_INSUFFICIENT_PRIVILEGE; memcpy(response, &rc, IPMI_CC_LEN); *data_len = IPMI_CC_LEN; @@ -199,20 +207,20 @@ ipmi_ret_t ipmi_netfn_router(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t // Walk the map that has the registered handlers and invoke the approprite // handlers for matching commands. auto iter = g_ipmid_router_map.find(std::make_pair(netfn, cmd)); - if(iter == g_ipmid_router_map.end()) + if (iter == g_ipmid_router_map.end()) { /* By default should only print on failure to find wildcard command. */ #ifdef __IPMI_DEBUG__ log( - "No registered handlers for NetFn, trying Wilcard implementation", - entry("NET_FUN=0x%X", netfn) - entry("CMD=0x%X", IPMI_CMD_WILDCARD)); + "No registered handlers for NetFn, trying Wilcard implementation", + entry("NET_FUN=0x%X", netfn) entry("CMD=0x%X", IPMI_CMD_WILDCARD)); #endif // Now that we did not find any specific [NetFn,Cmd], tuple, check for // NetFn, WildCard command present. - iter = g_ipmid_router_map.find(std::make_pair(netfn, IPMI_CMD_WILDCARD)); - if(iter == g_ipmid_router_map.end()) + iter = + g_ipmid_router_map.find(std::make_pair(netfn, IPMI_CMD_WILDCARD)); + if (iter == g_ipmid_router_map.end()) { log("No Registered handlers for NetFn", entry("NET_FUN=0x%X", netfn), @@ -228,8 +236,7 @@ ipmi_ret_t ipmi_netfn_router(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t #ifdef __IPMI_DEBUG__ // We have either a perfect match -OR- a wild card atleast, log("Calling Net function", - entry("NET_FUN=0x%X", netfn) - entry("CMD=0x%X", cmd)); + entry("NET_FUN=0x%X", netfn) entry("CMD=0x%X", cmd)); #endif // Extract the map data onto appropriate containers @@ -238,18 +245,18 @@ ipmi_ret_t ipmi_netfn_router(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t // Creating a pointer type casted to char* to make sure we advance 1 byte // when we advance pointer to next's address. advancing void * would not // make sense. - char *respo = &((char *)response)[IPMI_CC_LEN]; + char* respo = &((char*)response)[IPMI_CC_LEN]; try { // Response message from the plugin goes into a byte post the base // response - rc = (handler_and_context.first) (netfn, cmd, request, respo, - data_len, handler_and_context.second); + rc = (handler_and_context.first)(netfn, cmd, request, respo, data_len, + handler_and_context.second); } // IPMI command handlers can throw unhandled exceptions, catch those // and return sane error code. - catch (const std::exception &e) + catch (const std::exception& e) { log(e.what(), entry("NET_FUN=0x%X", netfn), entry("CMD=0x%X", cmd)); @@ -267,63 +274,62 @@ ipmi_ret_t ipmi_netfn_router(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t return rc; } - - - -static int send_ipmi_message(sd_bus_message *req, unsigned char seq, unsigned char netfn, unsigned char lun, unsigned char cmd, unsigned char cc, unsigned char *buf, unsigned char len) { +static int send_ipmi_message(sd_bus_message* req, unsigned char seq, + unsigned char netfn, unsigned char lun, + unsigned char cmd, unsigned char cc, + unsigned char* buf, unsigned char len) +{ sd_bus_error error = SD_BUS_ERROR_NULL; - sd_bus_message *reply = NULL, *m=NULL; + sd_bus_message *reply = NULL, *m = NULL; const char *dest, *path; int r, pty; dest = sd_bus_message_get_sender(req); path = sd_bus_message_get_path(req); - r = sd_bus_message_new_method_call(bus,&m,dest,path, - DBUS_INTF, + r = sd_bus_message_new_method_call(bus, &m, dest, path, DBUS_INTF, "sendMessage"); - if (r < 0) { + if (r < 0) + { log("Failed to add the method object", entry("ERRNO=0x%X", -r)); return -1; } - // Responses in IPMI require a bit set. So there ya go... netfn |= 0x01; - // Add the bytes needed for the methods to be called r = sd_bus_message_append(m, "yyyyy", seq, netfn, lun, cmd, cc); - if (r < 0) { + if (r < 0) + { log("Failed add the netfn and others", entry("ERRNO=0x%X", -r)); goto final; } r = sd_bus_message_append_array(m, 'y', buf, len); - if (r < 0) { + if (r < 0) + { log("Failed to add the string of response bytes", entry("ERRNO=0x%X", -r)); goto final; } - - // Call the IPMI responder on the bus so the message can be sent to the CEC r = sd_bus_call(bus, m, 0, &error, &reply); - if (r < 0) { - log("Failed to call the method", - entry("DEST=%s", dest), - entry("PATH=%s", path), - entry("ERRNO=0x%X", -r)); + if (r < 0) + { + log("Failed to call the method", entry("DEST=%s", dest), + entry("PATH=%s", path), entry("ERRNO=0x%X", -r)); goto final; } r = sd_bus_message_read(reply, "x", &pty); - if (r < 0) { - log("Failed to get a reply from the method", + if (r < 0) + { + log("Failed to get a reply from the method", entry("ERRNO=0x%X", -r)); } @@ -345,11 +351,9 @@ void cache_restricted_mode() const auto& restrictionModeSetting = objects->map.at(restrictionModeIntf).front(); auto method = dbus.new_method_call( - objects->service(restrictionModeSetting, - restrictionModeIntf).c_str(), - restrictionModeSetting.c_str(), - "org.freedesktop.DBus.Properties", - "Get"); + objects->service(restrictionModeSetting, restrictionModeIntf).c_str(), + restrictionModeSetting.c_str(), "org.freedesktop.DBus.Properties", + "Get"); method.append(restrictionModeIntf, "RestrictionMode"); auto resp = dbus.call(method); if (resp.is_method_error()) @@ -363,45 +367,49 @@ void cache_restricted_mode() resp.read(result); auto restrictionMode = RestrictionMode::convertModesFromString(result.get()); - if(RestrictionMode::Modes::Whitelist == restrictionMode) + if (RestrictionMode::Modes::Whitelist == restrictionMode) { restricted_mode = true; } } -static int handle_restricted_mode_change(sd_bus_message *m, void *user_data, - sd_bus_error *ret_error) +static int handle_restricted_mode_change(sd_bus_message* m, void* user_data, + sd_bus_error* ret_error) { cache_restricted_mode(); return 0; } -static int handle_ipmi_command(sd_bus_message *m, void *user_data, sd_bus_error - *ret_error) { +static int handle_ipmi_command(sd_bus_message* m, void* user_data, + sd_bus_error* ret_error) +{ int r = 0; unsigned char sequence, netfn, lun, cmd; - const void *request; + const void* request; size_t sz; - size_t resplen =MAX_IPMI_BUFFER; + size_t resplen = MAX_IPMI_BUFFER; unsigned char response[MAX_IPMI_BUFFER]; memset(response, 0, MAX_IPMI_BUFFER); - r = sd_bus_message_read(m, "yyyy", &sequence, &netfn, &lun, &cmd); - if (r < 0) { + r = sd_bus_message_read(m, "yyyy", &sequence, &netfn, &lun, &cmd); + if (r < 0) + { log("Failed to parse signal message", entry("ERRNO=0x%X", -r)); return -1; } - r = sd_bus_message_read_array(m, 'y', &request, &sz ); - if (r < 0) { + r = sd_bus_message_read_array(m, 'y', &request, &sz); + if (r < 0) + { log("Failed to parse signal message", entry("ERRNO=0x%X", -r)); return -1; } - fprintf(ipmiio, "IPMI Incoming: Seq 0x%02x, NetFn 0x%02x, CMD: 0x%02x \n", sequence, netfn, cmd); + fprintf(ipmiio, "IPMI Incoming: Seq 0x%02x, NetFn 0x%02x, CMD: 0x%02x \n", + sequence, netfn, cmd); hexdump(ipmiio, (void*)request, sz); // Allow the length field to be used for both input and output of the @@ -410,14 +418,13 @@ static int handle_ipmi_command(sd_bus_message *m, void *user_data, sd_bus_error // Now that we have parsed the entire byte array from the caller // we can call the ipmi router to do the work... - r = ipmi_netfn_router(netfn, cmd, (void *)request, (void *)response, &resplen); - if(r != 0) + r = ipmi_netfn_router(netfn, cmd, (void*)request, (void*)response, + &resplen); + if (r != 0) { #ifdef __IPMI_DEBUG__ - log("ERROR in handling NetFn", - entry("ERRNO=0x%X", -r), - entry("NET_FUN=0x%X", netfn), - entry("CMD=0x%X", cmd)); + log("ERROR in handling NetFn", entry("ERRNO=0x%X", -r), + entry("NET_FUN=0x%X", netfn), entry("CMD=0x%X", cmd)); #endif resplen = 0; } @@ -427,27 +434,26 @@ static int handle_ipmi_command(sd_bus_message *m, void *user_data, sd_bus_error } fprintf(ipmiio, "IPMI Response:\n"); - hexdump(ipmiio, (void*)response, resplen); + hexdump(ipmiio, (void*)response, resplen); // Send the response buffer from the ipmi command r = send_ipmi_message(m, sequence, netfn, lun, cmd, response[0], - ((unsigned char *)response) + 1, resplen); - if (r < 0) { + ((unsigned char*)response) + 1, resplen); + if (r < 0) + { log("Failed to send the response message"); return -1; } - return 0; } - //---------------------------------------------------------------------- // handler_select // Select all the files ending with with .so. in the given diretcory // @d: dirent structure containing the file name //---------------------------------------------------------------------- -int handler_select(const struct dirent *entry) +int handler_select(const struct dirent* entry) { // To hold ".so" from entry->d_name; char dname_copy[4] = {0}; @@ -455,18 +461,19 @@ int handler_select(const struct dirent *entry) // We want to avoid checking for everything and isolate to the ones having // .so.* or .so in them. // Check for versioned libraries .so.* - if(strstr(entry->d_name, IPMI_PLUGIN_SONAME_EXTN)) + if (strstr(entry->d_name, IPMI_PLUGIN_SONAME_EXTN)) { return 1; } // Check for non versioned libraries .so - else if(strstr(entry->d_name, IPMI_PLUGIN_EXTN)) + else if (strstr(entry->d_name, IPMI_PLUGIN_EXTN)) { // It is possible that .so could be anywhere in the string but unlikely // But being careful here. Get the base address of the string, move // until end and come back 3 steps and that gets what we need. - strcpy(dname_copy, (entry->d_name + strlen(entry->d_name)-strlen(IPMI_PLUGIN_EXTN))); - if(strcmp(dname_copy, IPMI_PLUGIN_EXTN) == 0) + strcpy(dname_copy, (entry->d_name + strlen(entry->d_name) - + strlen(IPMI_PLUGIN_EXTN))); + if (strcmp(dname_copy, IPMI_PLUGIN_EXTN) == 0) { return 1; } @@ -474,18 +481,18 @@ int handler_select(const struct dirent *entry) return 0; } -// This will do a dlopen of every .so in ipmi_lib_path and will dlopen everything so that they will -// register a callback handler +// This will do a dlopen of every .so in ipmi_lib_path and will dlopen +// everything so that they will register a callback handler void ipmi_register_callback_handlers(const char* ipmi_lib_path) { // For walking the ipmi_lib_path - struct dirent **handler_list; + struct dirent** handler_list; int num_handlers = 0; // This is used to check and abort if someone tries to register a bad one. - void *lib_handler = NULL; + void* lib_handler = NULL; - if(ipmi_lib_path == NULL) + if (ipmi_lib_path == NULL) { log("No handlers to be registered for ipmi.. Aborting"); assert(0); @@ -503,11 +510,12 @@ void ipmi_register_callback_handlers(const char* ipmi_lib_path) // already a .so, adding one more is not any harm. handler_fqdn += "/"; - num_handlers = scandir(ipmi_lib_path, &handler_list, handler_select, alphasort); + num_handlers = + scandir(ipmi_lib_path, &handler_list, handler_select, alphasort); if (num_handlers < 0) return; - while(num_handlers--) + while (num_handlers--) { handler_fqdn = ipmi_lib_path; handler_fqdn += handler_list[num_handlers]->d_name; @@ -518,7 +526,7 @@ void ipmi_register_callback_handlers(const char* ipmi_lib_path) lib_handler = dlopen(handler_fqdn.c_str(), RTLD_NOW); - if(lib_handler == NULL) + if (lib_handler == NULL) { log("ERROR opening", entry("HANDLER=%s", handler_fqdn.c_str()), @@ -536,67 +544,75 @@ void ipmi_register_callback_handlers(const char* ipmi_lib_path) return; } -sd_bus *ipmid_get_sd_bus_connection(void) { +sd_bus* ipmid_get_sd_bus_connection(void) +{ return bus; } -sd_event *ipmid_get_sd_event_connection(void) { +sd_event* ipmid_get_sd_event_connection(void) +{ return events; } -sd_bus_slot *ipmid_get_sd_bus_slot(void) { +sd_bus_slot* ipmid_get_sd_bus_slot(void) +{ return ipmid_slot; } // Calls host command manager to do the right thing for the command -void ipmid_send_cmd_to_host(CommandHandler&& cmd) { - return cmdManager->execute(std::move(cmd)); +void ipmid_send_cmd_to_host(CommandHandler&& cmd) +{ + return cmdManager->execute(std::move(cmd)); } -cmdManagerPtr& ipmid_get_host_cmd_manager() { - return cmdManager; +cmdManagerPtr& ipmid_get_host_cmd_manager() +{ + return cmdManager; } -sdbusPtr& ipmid_get_sdbus_plus_handler() { - return sdbusp; +sdbusPtr& ipmid_get_sdbus_plus_handler() +{ + return sdbusp; } -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { int r; unsigned long tvalue; int c; - - // This file and subsequient switch is for turning on levels // of trace - ipmicmddetails = ipmiio = ipmidbus = fopen("/dev/null", "w"); + ipmicmddetails = ipmiio = ipmidbus = fopen("/dev/null", "w"); - while ((c = getopt (argc, argv, "h:d:")) != -1) - switch (c) { + while ((c = getopt(argc, argv, "h:d:")) != -1) + switch (c) + { case 'd': - tvalue = strtoul(optarg, NULL, 16); - if (1&tvalue) { + tvalue = strtoul(optarg, NULL, 16); + if (1 & tvalue) + { ipmiio = stdout; } - if (2&tvalue) { + if (2 & tvalue) + { ipmidbus = stdout; } - if (4&tvalue) { + if (4 & tvalue) + { ipmicmddetails = stdout; } break; - case 'h': - case '?': + case 'h': + case '?': print_usage(); return 1; } - /* Connect to system bus */ r = sd_bus_open_system(&bus); - if (r < 0) { + if (r < 0) + { log("Failed to connect to system bus", entry("ERRNO=0x%X", -r)); goto finish; @@ -614,8 +630,8 @@ int main(int argc, char *argv[]) // Now create the Host Bound Command manager. Need sdbusplus // to use the generated bindings sdbusp = std::make_unique(bus); - cmdManager = std::make_unique( - *sdbusp, events); + cmdManager = + std::make_unique(*sdbusp, events); // Activate OemRouter. oem::mutableRouter()->activate(); @@ -623,11 +639,11 @@ int main(int argc, char *argv[]) // Register all the handlers that provider implementation to IPMI commands. ipmi_register_callback_handlers(HOST_IPMI_LIB_PATH); - // Watch for BT messages + // Watch for BT messages r = sd_bus_add_match(bus, &ipmid_slot, FILTER, handle_ipmi_command, NULL); - if (r < 0) { - log("Failed: sd_bus_add_match", - entry("FILTER=%s", FILTER), + if (r < 0) + { + log("Failed: sd_bus_add_match", entry("FILTER=%s", FILTER), entry("ERRNO=0x%X", -r)); goto finish; } @@ -640,8 +656,7 @@ int main(int argc, char *argv[]) using namespace internal::cache; sdbusplus::bus::bus dbus{bus}; objects = std::make_unique( - dbus, - std::vector({restrictionModeIntf})); + dbus, std::vector({restrictionModeIntf})); // Initialize restricted mode cache_restricted_mode(); // Wait for changes on Restricted mode @@ -652,7 +667,8 @@ int main(int argc, char *argv[]) restrictionModeIntf), handle_restricted_mode_change); - for (;;) { + for (;;) + { /* Process requests */ r = sd_event_run(events, (uint64_t)-1); if (r < 0) @@ -670,5 +686,4 @@ finish: sd_bus_slot_unref(ipmid_slot); sd_bus_unref(bus); return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS; - } diff --git a/ipmid.hpp b/ipmid.hpp index e0873aa..9d62611 100644 --- a/ipmid.hpp +++ b/ipmid.hpp @@ -1,13 +1,16 @@ #ifndef __HOST_IPMID_IPMI_H__ #define __HOST_IPMID_IPMI_H__ -#include "host-ipmid/ipmid-api.h" #include +#include "host-ipmid/ipmid-api.h" + // When the requester sends in a netfn and a command along with data, this // function will look for registered handlers that will handle that [netfn,cmd] -// and will make a call to that plugin implementation and send back the response. -ipmi_ret_t ipmi_netfn_router(const ipmi_netfn_t, const ipmi_cmd_t, ipmi_request_t, - ipmi_response_t, unsigned int *data_len); +// and will make a call to that plugin implementation and send back the +// response. +ipmi_ret_t ipmi_netfn_router(const ipmi_netfn_t, const ipmi_cmd_t, + ipmi_request_t, ipmi_response_t, + unsigned int* data_len); // Plugin libraries need to _end_ with .so #define IPMI_PLUGIN_EXTN ".so" diff --git a/ipmisensor.cpp b/ipmisensor.cpp index bb5dd96..b3fac2c 100644 --- a/ipmisensor.cpp +++ b/ipmisensor.cpp @@ -1,305 +1,351 @@ +#include +#include #include #include -#include -#include + #include "sensorhandler.h" extern uint8_t find_type_for_sensor_number(uint8_t); - -struct sensorRES_t { - uint8_t sensor_number; - uint8_t operation; - uint8_t sensor_reading; - uint8_t assert_state7_0; - uint8_t assert_state14_8; - uint8_t deassert_state7_0; - uint8_t deassert_state14_8; - uint8_t event_data1; - uint8_t event_data2; - uint8_t event_data3; -} __attribute__ ((packed)); - -#define ISBITSET(x,y) (((x)>>(y))&0x01) +struct sensorRES_t +{ + uint8_t sensor_number; + uint8_t operation; + uint8_t sensor_reading; + uint8_t assert_state7_0; + uint8_t assert_state14_8; + uint8_t deassert_state7_0; + uint8_t deassert_state14_8; + uint8_t event_data1; + uint8_t event_data2; + uint8_t event_data3; +} __attribute__((packed)); + +#define ISBITSET(x, y) (((x) >> (y)) & 0x01) #define ASSERTINDEX 0 #define DEASSERTINDEX 1 -// Sensor Type, Offset, function handler, Dbus Method, Assert value, Deassert value -struct lookup_t { - uint8_t sensor_type; - uint8_t offset; - int (*func)(const sensorRES_t *, const lookup_t *, const char *); - char member[16]; - char assertion[64]; - char deassertion[64]; +// Sensor Type, Offset, function handler, Dbus Method, Assert value, Deassert +// value +struct lookup_t +{ + uint8_t sensor_type; + uint8_t offset; + int (*func)(const sensorRES_t*, const lookup_t*, const char*); + char member[16]; + char assertion[64]; + char deassertion[64]; }; -extern int updateDbusInterface(uint8_t , const char *, const char *); +extern int updateDbusInterface(uint8_t, const char*, const char*); -int set_sensor_dbus_state_simple(const sensorRES_t *pRec, const lookup_t *pTable, const char *value) { +int set_sensor_dbus_state_simple(const sensorRES_t* pRec, + const lookup_t* pTable, const char* value) +{ - return set_sensor_dbus_state_s(pRec->sensor_number, - pTable->member, - value); + return set_sensor_dbus_state_s(pRec->sensor_number, pTable->member, value); } -struct event_data_t { - uint8_t data; - char text[64]; +struct event_data_t +{ + uint8_t data; + char text[64]; }; -event_data_t g_fwprogress02h[] = { - {0x00, "Unspecified"}, - {0x01, "Memory Init"}, - {0x02, "HD Init"}, - {0x03, "Secondary Proc Init"}, - {0x04, "User Authentication"}, - {0x05, "User init system setup"}, - {0x06, "USB configuration"}, - {0x07, "PCI configuration"}, - {0x08, "Option ROM Init"}, - {0x09, "Video Init"}, - {0x0A, "Cache Init"}, - {0x0B, "SM Bus init"}, - {0x0C, "Keyboard Init"}, - {0x0D, "Embedded ctrl init"}, - {0x0E, "Docking station attachment"}, - {0x0F, "Enable docking station"}, - {0x10, "Docking station ejection"}, - {0x11, "Disabling docking station"}, - {0x12, "Calling OS Wakeup"}, - {0x13, "Starting OS"}, - {0x14, "Baseboard Init"}, - {0x15, ""}, - {0x16, "Floppy Init"}, - {0x17, "Keyboard Test"}, - {0x18, "Pointing Device Test"}, - {0x19, "Primary Proc Init"}, - {0xFF, "Unknown"} -}; +event_data_t g_fwprogress02h[] = {{0x00, "Unspecified"}, + {0x01, "Memory Init"}, + {0x02, "HD Init"}, + {0x03, "Secondary Proc Init"}, + {0x04, "User Authentication"}, + {0x05, "User init system setup"}, + {0x06, "USB configuration"}, + {0x07, "PCI configuration"}, + {0x08, "Option ROM Init"}, + {0x09, "Video Init"}, + {0x0A, "Cache Init"}, + {0x0B, "SM Bus init"}, + {0x0C, "Keyboard Init"}, + {0x0D, "Embedded ctrl init"}, + {0x0E, "Docking station attachment"}, + {0x0F, "Enable docking station"}, + {0x10, "Docking station ejection"}, + {0x11, "Disabling docking station"}, + {0x12, "Calling OS Wakeup"}, + {0x13, "Starting OS"}, + {0x14, "Baseboard Init"}, + {0x15, ""}, + {0x16, "Floppy Init"}, + {0x17, "Keyboard Test"}, + {0x18, "Pointing Device Test"}, + {0x19, "Primary Proc Init"}, + {0xFF, "Unknown"}}; event_data_t g_fwprogress00h[] = { - {0x00, "Unspecified."}, - {0x01, "No system memory detected"}, - {0x02, "No usable system memory"}, - {0x03, "Unrecoverable hard-disk/ATAPI/IDE"}, - {0x04, "Unrecoverable system-board"}, - {0x05, "Unrecoverable diskette"}, - {0x06, "Unrecoverable hard-disk controller"}, - {0x07, "Unrecoverable PS/2 or USB keyboard"}, - {0x08, "Removable boot media not found"}, - {0x09, "Unrecoverable video controller"}, - {0x0A, "No video device detected"}, - {0x0B, "Firmware ROM corruption detected"}, - {0x0C, "CPU voltage mismatch"}, - {0x0D, "CPU speed matching"}, - {0xFF, "unknown"}, + {0x00, "Unspecified."}, + {0x01, "No system memory detected"}, + {0x02, "No usable system memory"}, + {0x03, "Unrecoverable hard-disk/ATAPI/IDE"}, + {0x04, "Unrecoverable system-board"}, + {0x05, "Unrecoverable diskette"}, + {0x06, "Unrecoverable hard-disk controller"}, + {0x07, "Unrecoverable PS/2 or USB keyboard"}, + {0x08, "Removable boot media not found"}, + {0x09, "Unrecoverable video controller"}, + {0x0A, "No video device detected"}, + {0x0B, "Firmware ROM corruption detected"}, + {0x0C, "CPU voltage mismatch"}, + {0x0D, "CPU speed matching"}, + {0xFF, "unknown"}, }; +char* event_data_lookup(event_data_t* p, uint8_t b) +{ -char *event_data_lookup(event_data_t *p, uint8_t b) { - - while(p->data != 0xFF) { - if (p->data == b) { - break; - } - p++; - } + while (p->data != 0xFF) + { + if (p->data == b) + { + break; + } + p++; + } - return p->text; + return p->text; } - - -// The fw progress sensor contains some additional information that needs to be processed -// prior to calling the dbus code. -int set_sensor_dbus_state_fwprogress(const sensorRES_t *pRec, const lookup_t *pTable, const char *value) { - - char valuestring[128]; - char* p = valuestring; - - switch (pTable->offset) { - - case 0x00 : snprintf(p, sizeof(valuestring), "POST Error, %s", event_data_lookup(g_fwprogress00h, pRec->event_data2)); - break; - case 0x01 : /* Using g_fwprogress02h for 0x01 because that's what the ipmi spec says to do */ - snprintf(p, sizeof(valuestring), "FW Hang, %s", event_data_lookup(g_fwprogress02h, pRec->event_data2)); - break; - case 0x02 : snprintf(p, sizeof(valuestring), "FW Progress, %s", event_data_lookup(g_fwprogress02h, pRec->event_data2)); - break; - default : snprintf(p, sizeof(valuestring), "Internal warning, fw_progres offset unknown (0x%02x)", pTable->offset); - break; - } - - return set_sensor_dbus_state_s(pRec->sensor_number, - pTable->member, - p); +// The fw progress sensor contains some additional information that needs to be +// processed prior to calling the dbus code. +int set_sensor_dbus_state_fwprogress(const sensorRES_t* pRec, + const lookup_t* pTable, const char* value) +{ + + char valuestring[128]; + char* p = valuestring; + + switch (pTable->offset) + { + + case 0x00: + snprintf(p, sizeof(valuestring), "POST Error, %s", + event_data_lookup(g_fwprogress00h, pRec->event_data2)); + break; + case 0x01: /* Using g_fwprogress02h for 0x01 because that's what the + ipmi spec says to do */ + snprintf(p, sizeof(valuestring), "FW Hang, %s", + event_data_lookup(g_fwprogress02h, pRec->event_data2)); + break; + case 0x02: + snprintf(p, sizeof(valuestring), "FW Progress, %s", + event_data_lookup(g_fwprogress02h, pRec->event_data2)); + break; + default: + snprintf(p, sizeof(valuestring), + "Internal warning, fw_progres offset unknown (0x%02x)", + pTable->offset); + break; + } + + return set_sensor_dbus_state_s(pRec->sensor_number, pTable->member, p); } -// Handling this special OEM sensor by coping what is in byte 4. I also think that is odd -// considering byte 3 is for sensor reading. This seems like a misuse of the IPMI spec -int set_sensor_dbus_state_osbootcount(const sensorRES_t *pRec, const lookup_t *pTable, const char *value) { - return set_sensor_dbus_state_y(pRec->sensor_number, - "setValue", +// Handling this special OEM sensor by coping what is in byte 4. I also think +// that is odd considering byte 3 is for sensor reading. This seems like a +// misuse of the IPMI spec +int set_sensor_dbus_state_osbootcount(const sensorRES_t* pRec, + const lookup_t* pTable, const char* value) +{ + return set_sensor_dbus_state_y(pRec->sensor_number, "setValue", pRec->assert_state7_0); } -int set_sensor_dbus_state_system_event(const sensorRES_t *pRec, const lookup_t *pTable, const char *value) { - char valuestring[128]; - char* p = valuestring; - - switch (pTable->offset) { - - case 0x00 : snprintf(p, sizeof(valuestring), "System Reconfigured"); - break; - case 0x01 : snprintf(p, sizeof(valuestring), "OEM Boot Event"); - break; - case 0x02 : snprintf(p, sizeof(valuestring), "Undetermined System Hardware Failure"); - break; - case 0x03 : snprintf(p, sizeof(valuestring), "System Failure see error log for more details (0x%02x)", pRec->event_data2); - break; - case 0x04 : snprintf(p, sizeof(valuestring), "System Failure see PEF error log for more details (0x%02x)", pRec->event_data2); - break; - default : snprintf(p, sizeof(valuestring), "Internal warning, system_event offset unknown (0x%02x)", pTable->offset); - break; - } - - return set_sensor_dbus_state_s(pRec->sensor_number, - pTable->member, - p); +int set_sensor_dbus_state_system_event(const sensorRES_t* pRec, + const lookup_t* pTable, + const char* value) +{ + char valuestring[128]; + char* p = valuestring; + + switch (pTable->offset) + { + + case 0x00: + snprintf(p, sizeof(valuestring), "System Reconfigured"); + break; + case 0x01: + snprintf(p, sizeof(valuestring), "OEM Boot Event"); + break; + case 0x02: + snprintf(p, sizeof(valuestring), + "Undetermined System Hardware Failure"); + break; + case 0x03: + snprintf(p, sizeof(valuestring), + "System Failure see error log for more details (0x%02x)", + pRec->event_data2); + break; + case 0x04: + snprintf( + p, sizeof(valuestring), + "System Failure see PEF error log for more details (0x%02x)", + pRec->event_data2); + break; + default: + snprintf(p, sizeof(valuestring), + "Internal warning, system_event offset unknown (0x%02x)", + pTable->offset); + break; + } + + return set_sensor_dbus_state_s(pRec->sensor_number, pTable->member, p); } - // This table lists only senors we care about telling dbus about. // Offset definition cab be found in section 42.2 of the IPMI 2.0 // spec. Add more if/when there are more items of interest. lookup_t g_ipmidbuslookup[] = { - {0xe9, 0x00, set_sensor_dbus_state_simple, "setValue", "Disabled", ""}, // OCC Inactive 0 - {0xe9, 0x01, set_sensor_dbus_state_simple, "setValue", "Enabled", ""}, // OCC Active 1 - // Turbo Allowed - {0xda, 0x00, set_sensor_dbus_state_simple, "setValue", "True", "False"}, - // Power Supply Derating - {0xb4, 0x00, set_sensor_dbus_state_simple, "setValue", "", ""}, - // Power Cap - {0xC2, 0x00, set_sensor_dbus_state_simple, "setValue", "", ""}, - {0x07, 0x07, set_sensor_dbus_state_simple, "setPresent", "True", "False"}, - {0x07, 0x08, set_sensor_dbus_state_simple, "setFault", "True", "False"}, - {0x0C, 0x06, set_sensor_dbus_state_simple, "setPresent", "True", "False"}, - {0x0C, 0x04, set_sensor_dbus_state_simple, "setFault", "True", "False"}, - {0x0F, 0x02, set_sensor_dbus_state_fwprogress, "setValue", "True", "False"}, - {0x0F, 0x01, set_sensor_dbus_state_fwprogress, "setValue", "True", "False"}, - {0x0F, 0x00, set_sensor_dbus_state_fwprogress, "setValue", "True", "False"}, - {0xC7, 0x01, set_sensor_dbus_state_simple, "setFault", "True", "False"}, - {0xc3, 0x00, set_sensor_dbus_state_osbootcount, "setValue", "" ,""}, - {0x1F, 0x00, set_sensor_dbus_state_simple, "setValue", "Boot completed (00)", ""}, - {0x1F, 0x01, set_sensor_dbus_state_simple, "setValue", "Boot completed (01)", ""}, - {0x1F, 0x02, set_sensor_dbus_state_simple, "setValue", "PXE boot completed", ""}, - {0x1F, 0x03, set_sensor_dbus_state_simple, "setValue", "Diagnostic boot completed", ""}, - {0x1F, 0x04, set_sensor_dbus_state_simple, "setValue", "CD-ROM boot completed", ""}, - {0x1F, 0x05, set_sensor_dbus_state_simple, "setValue", "ROM boot completed", ""}, - {0x1F, 0x06, set_sensor_dbus_state_simple, "setValue", "Boot completed (06)", ""}, - {0x12, 0x00, set_sensor_dbus_state_system_event, "setValue", "", ""}, - {0x12, 0x01, set_sensor_dbus_state_system_event, "setValue", "", ""}, - {0x12, 0x02, set_sensor_dbus_state_system_event, "setValue", "", ""}, - {0x12, 0x03, set_sensor_dbus_state_system_event, "setValue", "", ""}, - {0x12, 0x04, set_sensor_dbus_state_system_event, "setValue", "", ""}, - {0xCA, 0x00, set_sensor_dbus_state_simple, "setValue", "Disabled", ""}, - {0xCA, 0x01, set_sensor_dbus_state_simple, "setValue", "Enabled", ""}, - {0xFF, 0xFF, NULL, "", "", ""} -}; - - -void reportSensorEventAssert(sensorRES_t *pRec, int index) { - lookup_t *pTable = &g_ipmidbuslookup[index]; - (*pTable->func)(pRec, pTable, pTable->assertion); + {0xe9, 0x00, set_sensor_dbus_state_simple, "setValue", "Disabled", + ""}, // OCC Inactive 0 + {0xe9, 0x01, set_sensor_dbus_state_simple, "setValue", "Enabled", + ""}, // OCC Active 1 + // Turbo Allowed + {0xda, 0x00, set_sensor_dbus_state_simple, "setValue", "True", "False"}, + // Power Supply Derating + {0xb4, 0x00, set_sensor_dbus_state_simple, "setValue", "", ""}, + // Power Cap + {0xC2, 0x00, set_sensor_dbus_state_simple, "setValue", "", ""}, + {0x07, 0x07, set_sensor_dbus_state_simple, "setPresent", "True", "False"}, + {0x07, 0x08, set_sensor_dbus_state_simple, "setFault", "True", "False"}, + {0x0C, 0x06, set_sensor_dbus_state_simple, "setPresent", "True", "False"}, + {0x0C, 0x04, set_sensor_dbus_state_simple, "setFault", "True", "False"}, + {0x0F, 0x02, set_sensor_dbus_state_fwprogress, "setValue", "True", "False"}, + {0x0F, 0x01, set_sensor_dbus_state_fwprogress, "setValue", "True", "False"}, + {0x0F, 0x00, set_sensor_dbus_state_fwprogress, "setValue", "True", "False"}, + {0xC7, 0x01, set_sensor_dbus_state_simple, "setFault", "True", "False"}, + {0xc3, 0x00, set_sensor_dbus_state_osbootcount, "setValue", "", ""}, + {0x1F, 0x00, set_sensor_dbus_state_simple, "setValue", + "Boot completed (00)", ""}, + {0x1F, 0x01, set_sensor_dbus_state_simple, "setValue", + "Boot completed (01)", ""}, + {0x1F, 0x02, set_sensor_dbus_state_simple, "setValue", "PXE boot completed", + ""}, + {0x1F, 0x03, set_sensor_dbus_state_simple, "setValue", + "Diagnostic boot completed", ""}, + {0x1F, 0x04, set_sensor_dbus_state_simple, "setValue", + "CD-ROM boot completed", ""}, + {0x1F, 0x05, set_sensor_dbus_state_simple, "setValue", "ROM boot completed", + ""}, + {0x1F, 0x06, set_sensor_dbus_state_simple, "setValue", + "Boot completed (06)", ""}, + {0x12, 0x00, set_sensor_dbus_state_system_event, "setValue", "", ""}, + {0x12, 0x01, set_sensor_dbus_state_system_event, "setValue", "", ""}, + {0x12, 0x02, set_sensor_dbus_state_system_event, "setValue", "", ""}, + {0x12, 0x03, set_sensor_dbus_state_system_event, "setValue", "", ""}, + {0x12, 0x04, set_sensor_dbus_state_system_event, "setValue", "", ""}, + {0xCA, 0x00, set_sensor_dbus_state_simple, "setValue", "Disabled", ""}, + {0xCA, 0x01, set_sensor_dbus_state_simple, "setValue", "Enabled", ""}, + {0xFF, 0xFF, NULL, "", "", ""}}; + +void reportSensorEventAssert(sensorRES_t* pRec, int index) +{ + lookup_t* pTable = &g_ipmidbuslookup[index]; + (*pTable->func)(pRec, pTable, pTable->assertion); } -void reportSensorEventDeassert(sensorRES_t *pRec, int index) { - lookup_t *pTable = &g_ipmidbuslookup[index]; - (*pTable->func)(pRec, pTable, pTable->deassertion); +void reportSensorEventDeassert(sensorRES_t* pRec, int index) +{ + lookup_t* pTable = &g_ipmidbuslookup[index]; + (*pTable->func)(pRec, pTable, pTable->deassertion); } +int findindex(const uint8_t sensor_type, int offset, int* index) +{ -int findindex(const uint8_t sensor_type, int offset, int *index) { - - int i=0, rc=0; - lookup_t *pTable = g_ipmidbuslookup; + int i = 0, rc = 0; + lookup_t* pTable = g_ipmidbuslookup; - do { - if ( ((pTable+i)->sensor_type == sensor_type) && - ((pTable+i)->offset == offset) ) { - rc = 1; - *index = i; - break; - } - i++; - } while ((pTable+i)->sensor_type != 0xFF); + do + { + if (((pTable + i)->sensor_type == sensor_type) && + ((pTable + i)->offset == offset)) + { + rc = 1; + *index = i; + break; + } + i++; + } while ((pTable + i)->sensor_type != 0xFF); - return rc; + return rc; } -bool shouldReport(uint8_t sensorType, int offset, int *index) { +bool shouldReport(uint8_t sensorType, int offset, int* index) +{ - bool rc = false; + bool rc = false; - if (findindex(sensorType, offset, index)) { rc = true; } - if (rc == false) { + if (findindex(sensorType, offset, index)) + { + rc = true; + } + if (rc == false) + { #ifdef __IPMI_DEBUG__ log("LOOKATME: Sensor should not be reported", - entry("SENSORTYPE=0x%02x", sensorType), - entry("OFFSET=0x%02x", offset)); + entry("SENSORTYPE=0x%02x", sensorType), + entry("OFFSET=0x%02x", offset)); #endif - } + } - return rc; + return rc; } +int updateSensorRecordFromSSRAESC(const void* record) +{ + + sensorRES_t* pRec = (sensorRES_t*)record; + uint8_t stype; + int index, i = 0; + + stype = find_type_for_sensor_number(pRec->sensor_number); + + // 0xC3 types use the assertion7_0 for the value to be set + // so skip the reseach and call the correct event reporting + // function + if (stype == 0xC3) + { + + shouldReport(stype, 0x00, &index); + reportSensorEventAssert(pRec, index); + } + else + { + // Scroll through each bit position . Determine + // if any bit is either asserted or Deasserted. + for (i = 0; i < 8; i++) + { + + if ((ISBITSET(pRec->assert_state7_0, i)) && + (shouldReport(stype, i, &index))) + { + reportSensorEventAssert(pRec, index); + } + if ((ISBITSET(pRec->assert_state14_8, i)) && + (shouldReport(stype, i + 8, &index))) + { + reportSensorEventAssert(pRec, index); + } + if ((ISBITSET(pRec->deassert_state7_0, i)) && + (shouldReport(stype, i, &index))) + { + reportSensorEventDeassert(pRec, index); + } + if ((ISBITSET(pRec->deassert_state14_8, i)) && + (shouldReport(stype, i + 8, &index))) + { + reportSensorEventDeassert(pRec, index); + } + } + } -int updateSensorRecordFromSSRAESC(const void *record) { - - sensorRES_t *pRec = (sensorRES_t *) record; - uint8_t stype; - int index, i=0; - - stype = find_type_for_sensor_number(pRec->sensor_number); - - // 0xC3 types use the assertion7_0 for the value to be set - // so skip the reseach and call the correct event reporting - // function - if (stype == 0xC3) { - - shouldReport(stype, 0x00, &index); - reportSensorEventAssert(pRec, index); - - } else { - // Scroll through each bit position . Determine - // if any bit is either asserted or Deasserted. - for(i=0;i<8;i++) { - - if ((ISBITSET(pRec->assert_state7_0,i)) && - (shouldReport(stype, i, &index))) - { - reportSensorEventAssert(pRec, index); - } - if ((ISBITSET(pRec->assert_state14_8,i)) && - (shouldReport(stype, i+8, &index))) - { - reportSensorEventAssert(pRec, index); - } - if ((ISBITSET(pRec->deassert_state7_0,i)) && - (shouldReport(stype, i, &index))) - { - reportSensorEventDeassert(pRec, index); - } - if ((ISBITSET(pRec->deassert_state14_8,i)) && - (shouldReport(stype, i+8, &index))) - { - reportSensorEventDeassert(pRec, index); - } - } - - } - - - return 0; + return 0; } diff --git a/ipmiwhitelist.hpp b/ipmiwhitelist.hpp index b07451a..7d096c2 100644 --- a/ipmiwhitelist.hpp +++ b/ipmiwhitelist.hpp @@ -1,8 +1,8 @@ #ifndef __HOST_IPMID_IPMI_WHITELIST_H__ #define __HOST_IPMID_IPMI_WHITELIST_H_ -#include #include +#include using netfncmd_pair = std::pair; diff --git a/net.cpp b/net.cpp index 17be41e..9de190f 100644 --- a/net.cpp +++ b/net.cpp @@ -1,8 +1,8 @@ +#include "utils.hpp" + #include #include -#include "utils.hpp" - // Not sure if this should live in utils. Because it's really a per-system // configuration, instead of just hard-coding channel 1 to be eth0, one could // conceivably configure it however they pleased. @@ -31,4 +31,3 @@ std::string ChanneltoEthernet(int channel) } // namespace network } // namespace ipmi - diff --git a/oemrouter.cpp b/oemrouter.cpp index 273a679..64944db 100644 --- a/oemrouter.cpp +++ b/oemrouter.cpp @@ -1,10 +1,10 @@ +#include "host-ipmid/oemrouter.hpp" + #include #include #include #include -#include "host-ipmid/oemrouter.hpp" - namespace oem { @@ -13,20 +13,21 @@ using Key = std::pair; // Private implementation of OemRouter Interface. class RouterImpl : public Router { - public: - RouterImpl() {} + public: + RouterImpl() + { + } - // Implement OemRouter Interface. - void activate() override; - void registerHandler(Number oen, ipmi_cmd_t cmd, - Handler handler) override; + // Implement OemRouter Interface. + void activate() override; + void registerHandler(Number oen, ipmi_cmd_t cmd, Handler handler) override; - // Actual message routing function. - ipmi_ret_t routeMsg(ipmi_cmd_t cmd, const uint8_t* reqBuf, - uint8_t* replyBuf, size_t* dataLen); + // Actual message routing function. + ipmi_ret_t routeMsg(ipmi_cmd_t cmd, const uint8_t* reqBuf, + uint8_t* replyBuf, size_t* dataLen); - private: - std::map handlers; + private: + std::map handlers; }; // Static global instance for simplicity. @@ -66,8 +67,10 @@ ipmi_ret_t RouterImpl::routeMsg(ipmi_cmd_t cmd, const uint8_t* reqBuf, iter = handlers.find(wildKey); if (iter == handlers.end()) { - fprintf(stderr, "No Registered handler for NetFn:[0x2E], " - "OEM:[%#08X], Cmd:[%#04X]\n", number, cmd); + fprintf(stderr, + "No Registered handler for NetFn:[0x2E], " + "OEM:[%#08X], Cmd:[%#04X]\n", + number, cmd); *dataLen = groupMagicSize; return IPMI_CC_INVALID; } @@ -91,8 +94,8 @@ ipmi_ret_t RouterImpl::routeMsg(ipmi_cmd_t cmd, const uint8_t* reqBuf, size_t oemDataLen = *dataLen - groupMagicSize; Handler& handler = iter->second; - auto rc = handler(cmd, reqBuf + groupMagicSize, - replyBuf + groupMagicSize, &oemDataLen); + auto rc = handler(cmd, reqBuf + groupMagicSize, replyBuf + groupMagicSize, + &oemDataLen); // Add OEMGroup bytes to nominal reply. *dataLen = oemDataLen + groupMagicSize; @@ -101,8 +104,8 @@ ipmi_ret_t RouterImpl::routeMsg(ipmi_cmd_t cmd, const uint8_t* reqBuf, // Function suitable for use as ipmi_netfn_router() call-back. // Translates call-back pointer args to more specific types. -ipmi_ret_t ipmi_oem_wildcard_handler(ipmi_netfn_t /* netfn */, - ipmi_cmd_t cmd, ipmi_request_t request, +ipmi_ret_t ipmi_oem_wildcard_handler(ipmi_netfn_t /* netfn */, ipmi_cmd_t cmd, + ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t dataLen, ipmi_context_t context) @@ -112,8 +115,7 @@ ipmi_ret_t ipmi_oem_wildcard_handler(ipmi_netfn_t /* netfn */, uint8_t* replyBuf = static_cast(response); // View context as router object, defaulting nullptr to global object. - auto router = static_cast( - context ? context : mutableRouter()); + auto router = static_cast(context ? context : mutableRouter()); // Send message parameters to dispatcher. return router->routeMsg(cmd, reqBuf, replyBuf, dataLen); @@ -123,14 +125,13 @@ ipmi_ret_t ipmi_oem_wildcard_handler(ipmi_netfn_t /* netfn */, void RouterImpl::activate() { // Register netfn 0x2e OEM Group, any (wildcard) command. - printf("Registering NetFn:[0x%X], Cmd:[0x%X]\n", - NETFUN_OEM_GROUP, IPMI_CMD_WILDCARD); + printf("Registering NetFn:[0x%X], Cmd:[0x%X]\n", NETFUN_OEM_GROUP, + IPMI_CMD_WILDCARD); ipmi_register_callback(NETFUN_OEM_GROUP, IPMI_CMD_WILDCARD, this, ipmi_oem_wildcard_handler, PRIVILEGE_OEM); } -void RouterImpl::registerHandler(Number oen, ipmi_cmd_t cmd, - Handler handler) +void RouterImpl::registerHandler(Number oen, ipmi_cmd_t cmd, Handler handler) { auto cmdKey = std::make_pair(oen, cmd); auto iter = handlers.find(cmdKey); @@ -141,9 +142,11 @@ void RouterImpl::registerHandler(Number oen, ipmi_cmd_t cmd, } else { - fprintf(stderr, "ERROR : Duplicate registration for NetFn:[0x2E], " - "OEM:[%#08X], Cmd:[%#04X]\n", oen, cmd); + fprintf(stderr, + "ERROR : Duplicate registration for NetFn:[0x2E], " + "OEM:[%#08X], Cmd:[%#04X]\n", + oen, cmd); } } -} // namespace oem +} // namespace oem diff --git a/read_fru_data.cpp b/read_fru_data.cpp index 5133612..4581a8c 100644 --- a/read_fru_data.cpp +++ b/read_fru_data.cpp @@ -1,11 +1,14 @@ -#include -#include -#include "xyz/openbmc_project/Common/error.hpp" #include "read_fru_data.hpp" + #include "fruread.hpp" -#include "host-ipmid/ipmid-api.h" -#include "utils.hpp" #include "types.hpp" +#include "utils.hpp" + +#include +#include +#include + +#include "host-ipmid/ipmid-api.h" extern const FruMap frus; namespace ipmi @@ -14,22 +17,22 @@ namespace fru { using namespace phosphor::logging; using InternalFailure = - sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; + sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; std::unique_ptr matchPtr(nullptr); -static constexpr auto INV_INTF = "xyz.openbmc_project.Inventory.Manager"; -static constexpr auto OBJ_PATH = "/xyz/openbmc_project/inventory"; +static constexpr auto INV_INTF = "xyz.openbmc_project.Inventory.Manager"; +static constexpr auto OBJ_PATH = "/xyz/openbmc_project/inventory"; static constexpr auto PROP_INTF = "org.freedesktop.DBus.Properties"; namespace cache { - //User initiate read FRU info area command followed by - //FRU read command. Also data is read in small chunks of - //the specified offset and count. - //Caching the data which will be invalidated when ever there - //is a change in FRU properties. - FRUAreaMap fruMap; -} +// User initiate read FRU info area command followed by +// FRU read command. Also data is read in small chunks of +// the specified offset and count. +// Caching the data which will be invalidated when ever there +// is a change in FRU properties. +FRUAreaMap fruMap; +} // namespace cache /** * @brief Read all the property value's for the specified interface * from Inventory. @@ -39,21 +42,19 @@ namespace cache * @return map of properties */ ipmi::PropertyMap readAllProperties(const std::string& intf, - const std::string& path) + const std::string& path) { ipmi::PropertyMap properties; sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; auto service = ipmi::getService(bus, INV_INTF, OBJ_PATH); std::string objPath = OBJ_PATH + path; - auto method = bus.new_method_call(service.c_str(), - objPath.c_str(), - PROP_INTF, - "GetAll"); + auto method = bus.new_method_call(service.c_str(), objPath.c_str(), + PROP_INTF, "GetAll"); method.append(intf); auto reply = bus.call(method); if (reply.is_method_error()) { - //If property is not found simply return empty value + // If property is not found simply return empty value log("Error in reading property values from inventory", entry("INTERFACE=%s", intf.c_str()), entry("PATH=%s", objPath.c_str())); @@ -65,12 +66,12 @@ ipmi::PropertyMap readAllProperties(const std::string& intf, void processFruPropChange(sdbusplus::message::message& msg) { - if(cache::fruMap.empty()) + if (cache::fruMap.empty()) { return; } std::string path = msg.get_path(); - //trim the object base path, if found at the beginning + // trim the object base path, if found at the beginning if (path.compare(0, strlen(OBJ_PATH), OBJ_PATH) == 0) { path.erase(0, strlen(OBJ_PATH)); @@ -82,7 +83,7 @@ void processFruPropChange(sdbusplus::message::message& msg) auto& instanceList = fru.second; for (auto& instance : instanceList) { - if(instance.path == path) + if (instance.path == path) { found = true; break; @@ -96,19 +97,17 @@ void processFruPropChange(sdbusplus::message::message& msg) } } -//register for fru property change +// register for fru property change int registerCallbackHandler() { - if(matchPtr == nullptr) + if (matchPtr == nullptr) { using namespace sdbusplus::bus::match::rules; sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; matchPtr = std::make_unique( bus, - path_namespace(OBJ_PATH) + - type::signal() + - member("PropertiesChanged") + - interface(PROP_INTF), + path_namespace(OBJ_PATH) + type::signal() + + member("PropertiesChanged") + interface(PROP_INTF), std::bind(processFruPropChange, std::placeholders::_1)); } return 0; @@ -125,7 +124,7 @@ FruInventoryData readDataFromInventory(const FRUId& fruNum) auto iter = frus.find(fruNum); if (iter == frus.end()) { - log("Unsupported FRU ID ",entry("FRUID=%d", fruNum)); + log("Unsupported FRU ID ", entry("FRUID=%d", fruNum)); elog(); } @@ -135,15 +134,17 @@ FruInventoryData readDataFromInventory(const FRUId& fruNum) { for (auto& intf : instance.interfaces) { - ipmi::PropertyMap allProp = readAllProperties( - intf.first, instance.path); + ipmi::PropertyMap allProp = + readAllProperties(intf.first, instance.path); for (auto& properties : intf.second) { auto iter = allProp.find(properties.first); if (iter != allProp.end()) { - data[properties.second.section].emplace(properties.first, - std::move(allProp[properties.first].get())); + data[properties.second.section].emplace( + properties.first, + std::move( + allProp[properties.first].get())); } } } @@ -160,10 +161,10 @@ const FruAreaData& getFruAreaData(const FRUId& fruNum) } auto invData = readDataFromInventory(fruNum); - //Build area info based on inventory data + // Build area info based on inventory data FruAreaData newdata = buildFruAreaData(std::move(invData)); cache::fruMap.emplace(fruNum, std::move(newdata)); return cache::fruMap.at(fruNum); } -} //fru -} //ipmi +} // namespace fru +} // namespace ipmi diff --git a/read_fru_data.hpp b/read_fru_data.hpp index d715858..d3268b8 100644 --- a/read_fru_data.hpp +++ b/read_fru_data.hpp @@ -1,8 +1,9 @@ #pragma once -#include -#include #include "ipmi_fru_info_area.hpp" +#include +#include + namespace ipmi { namespace fru @@ -24,5 +25,5 @@ const FruAreaData& getFruAreaData(const FRUId& fruNum); * @return negative value on failure */ int registerCallbackHandler(); -} //fru -} //ipmi +} // namespace fru +} // namespace ipmi diff --git a/sample.cpp b/sample.cpp index 451c6c4..72a120a 100644 --- a/sample.cpp +++ b/sample.cpp @@ -3,7 +3,7 @@ int Factorial(int n) { int result = 1; - for (int i=1; i<=n; i++) + for (int i = 1; i <= n; i++) { result *= i; } diff --git a/selutility.cpp b/selutility.cpp index 5935de2..8e04ad4 100644 --- a/selutility.cpp +++ b/selutility.cpp @@ -4,25 +4,29 @@ #include #elif __has_include() #include -namespace std { - // splice experimental::filesystem into std - namespace filesystem = std::experimental::filesystem; -} +namespace std +{ +// splice experimental::filesystem into std +namespace filesystem = std::experimental::filesystem; +} // namespace std #else -# error filesystem not available +#error filesystem not available #endif -#include -#include "host-ipmid/ipmid-api.h" -#include "xyz/openbmc_project/Common/error.hpp" #include "config.h" + #include "selutility.hpp" #include "types.hpp" #include "utils.hpp" +#include +#include + +#include "host-ipmid/ipmid-api.h" + extern const ipmi::sensor::InvObjectIDMap invSensors; using namespace phosphor::logging; using InternalFailure = - sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; + sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; namespace ipmi { @@ -33,20 +37,18 @@ namespace sel namespace internal { -GetSELEntryResponse prepareSELEntry( - const std::string& objPath, - ipmi::sensor::InvObjectIDMap::const_iterator iter) +GetSELEntryResponse + prepareSELEntry(const std::string& objPath, + ipmi::sensor::InvObjectIDMap::const_iterator iter) { - GetSELEntryResponse record {}; + GetSELEntryResponse record{}; sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; auto service = ipmi::getService(bus, logEntryIntf, objPath); // Read all the log entry properties. - auto methodCall = bus.new_method_call(service.c_str(), - objPath.c_str(), - propIntf, - "GetAll"); + auto methodCall = bus.new_method_call(service.c_str(), objPath.c_str(), + propIntf, "GetAll"); methodCall.append(logEntryIntf); auto reply = bus.call(methodCall); @@ -69,7 +71,7 @@ GetSELEntryResponse prepareSELEntry( } record.recordID = static_cast( - sdbusplus::message::variant_ns::get(iterId->second)); + sdbusplus::message::variant_ns::get(iterId->second)); // Read Timestamp from the log entry. static constexpr auto propTimeStamp = "Timestamp"; @@ -81,10 +83,10 @@ GetSELEntryResponse prepareSELEntry( } std::chrono::milliseconds chronoTimeStamp( - sdbusplus::message::variant_ns::get - (iterTimeStamp->second)); - record.timeStamp = static_cast(std::chrono::duration_cast< - std::chrono::seconds>(chronoTimeStamp).count()); + sdbusplus::message::variant_ns::get(iterTimeStamp->second)); + record.timeStamp = static_cast( + std::chrono::duration_cast(chronoTimeStamp) + .count()); static constexpr auto systemEventRecord = 0x02; static constexpr auto generatorID = 0x2000; @@ -134,10 +136,8 @@ GetSELEntryResponse convertLogEntrytoSEL(const std::string& objPath) auto service = ipmi::getService(bus, assocIntf, objPath); // Read the Associations interface. - auto methodCall = bus.new_method_call(service.c_str(), - objPath.c_str(), - propIntf, - "Get"); + auto methodCall = + bus.new_method_call(service.c_str(), objPath.c_str(), propIntf, "Get"); methodCall.append(assocIntf); methodCall.append(assocProp); @@ -148,14 +148,13 @@ GetSELEntryResponse convertLogEntrytoSEL(const std::string& objPath) elog(); } - using AssociationList = std::vector>; + using AssociationList = + std::vector>; sdbusplus::message::variant list; reply.read(list); - auto& assocs = sdbusplus::message::variant_ns::get - (list); + auto& assocs = sdbusplus::message::variant_ns::get(list); /* * Check if the log entry has any callout associations, if there is a @@ -166,18 +165,18 @@ GetSELEntryResponse convertLogEntrytoSEL(const std::string& objPath) { if (std::get<0>(item).compare(CALLOUT_FWD_ASSOCIATION) == 0) { - auto iter = invSensors.find(std::get<2>(item)); - if (iter == invSensors.end()) - { - iter = invSensors.find(BOARD_SENSOR); - if (iter == invSensors.end()) - { - log("Motherboard sensor not found"); - elog(); - } - } - - return internal::prepareSELEntry(objPath, iter); + auto iter = invSensors.find(std::get<2>(item)); + if (iter == invSensors.end()) + { + iter = invSensors.find(BOARD_SENSOR); + if (iter == invSensors.end()) + { + log("Motherboard sensor not found"); + elog(); + } + } + + return internal::prepareSELEntry(objPath, iter); } } @@ -202,10 +201,8 @@ std::chrono::seconds getEntryTimeStamp(const std::string& objPath) using namespace std::string_literals; static const auto propTimeStamp = "Timestamp"s; - auto methodCall = bus.new_method_call(service.c_str(), - objPath.c_str(), - propIntf, - "Get"); + auto methodCall = + bus.new_method_call(service.c_str(), objPath.c_str(), propIntf, "Get"); methodCall.append(logEntryIntf); methodCall.append(propTimeStamp); @@ -220,7 +217,7 @@ std::chrono::seconds getEntryTimeStamp(const std::string& objPath) reply.read(timeStamp); std::chrono::milliseconds chronoTimeStamp( - sdbusplus::message::variant_ns::get(timeStamp)); + sdbusplus::message::variant_ns::get(timeStamp)); return std::chrono::duration_cast(chronoTimeStamp); } @@ -231,10 +228,8 @@ void readLoggingObjectPaths(ObjectPaths& paths) auto depth = 0; paths.clear(); - auto mapperCall = bus.new_method_call(mapperBusName, - mapperObjPath, - mapperIntf, - "GetSubTreePaths"); + auto mapperCall = bus.new_method_call(mapperBusName, mapperObjPath, + mapperIntf, "GetSubTreePaths"); mapperCall.append(logBasePath); mapperCall.append(depth); mapperCall.append(ObjectPaths({logEntryIntf})); @@ -248,17 +243,16 @@ void readLoggingObjectPaths(ObjectPaths& paths) { reply.read(paths); - std::sort(paths.begin(), paths.end(), [](const std::string& a, - const std::string& b) - { - namespace fs = std::filesystem; - fs::path pathA(a); - fs::path pathB(b); - auto idA = std::stoul(pathA.filename().string()); - auto idB = std::stoul(pathB.filename().string()); - - return idA < idB; - }); + std::sort(paths.begin(), paths.end(), + [](const std::string& a, const std::string& b) { + namespace fs = std::filesystem; + fs::path pathA(a); + fs::path pathB(b); + auto idA = std::stoul(pathA.filename().string()); + auto idB = std::stoul(pathB.filename().string()); + + return idA < idB; + }); } } diff --git a/selutility.hpp b/selutility.hpp index 57ed24f..5262d82 100644 --- a/selutility.hpp +++ b/selutility.hpp @@ -1,8 +1,9 @@ #pragma once +#include "types.hpp" + #include #include -#include "types.hpp" namespace ipmi { @@ -28,7 +29,7 @@ using Timestamp = uint64_t; using Message = std::string; using AdditionalData = std::vector; using PropertyType = sdbusplus::message::variant; + Message, AdditionalData>; static constexpr auto selVersion = 0x51; static constexpr auto invalidTimeStamp = 0xFFFFFFFF; @@ -40,12 +41,12 @@ static constexpr auto operationSupport = 0x0A; */ struct GetSELInfoResponse { - uint8_t selVersion; //!< SEL revision. - uint16_t entries; //!< Number of log entries in SEL. - uint16_t freeSpace; //!< Free Space in bytes. - uint32_t addTimeStamp; //!< Most recent addition timestamp. - uint32_t eraseTimeStamp; //!< Most recent erase timestamp. - uint8_t operationSupport; //!< Operation support. + uint8_t selVersion; //!< SEL revision. + uint16_t entries; //!< Number of log entries in SEL. + uint16_t freeSpace; //!< Free Space in bytes. + uint32_t addTimeStamp; //!< Most recent addition timestamp. + uint32_t eraseTimeStamp; //!< Most recent erase timestamp. + uint8_t operationSupport; //!< Operation support. } __attribute__((packed)); static constexpr auto firstEntry = 0x0000; @@ -59,10 +60,10 @@ static constexpr auto selRecordSize = 16; */ struct GetSELEntryRequest { - uint16_t reservationID; //!< Reservation ID. - uint16_t selRecordID; //!< SEL Record ID. - uint8_t offset; //!< Offset into record. - uint8_t readLength; //!< Bytes to read. + uint16_t reservationID; //!< Reservation ID. + uint16_t selRecordID; //!< SEL Record ID. + uint8_t offset; //!< Offset into record. + uint8_t readLength; //!< Bytes to read. } __attribute__((packed)); /** @struct GetSELEntryResponse @@ -71,18 +72,18 @@ struct GetSELEntryRequest */ struct GetSELEntryResponse { - uint16_t nextRecordID; //!< Next RecordID. - uint16_t recordID; //!< Record ID. - uint8_t recordType; //!< Record Type. - uint32_t timeStamp; //!< Timestamp. - uint16_t generatorID; //!< Generator ID. - uint8_t eventMsgRevision; //!< Event Message Revision. - uint8_t sensorType; //!< Sensor Type. - uint8_t sensorNum; //!< Sensor Number. - uint8_t eventType; //!< Event Dir | Event Type. - uint8_t eventData1; //!< Event Data 1. - uint8_t eventData2; //!< Event Data 2. - uint8_t eventData3; //!< Event Data 3. + uint16_t nextRecordID; //!< Next RecordID. + uint16_t recordID; //!< Record ID. + uint8_t recordType; //!< Record Type. + uint32_t timeStamp; //!< Timestamp. + uint16_t generatorID; //!< Generator ID. + uint8_t eventMsgRevision; //!< Event Message Revision. + uint8_t sensorType; //!< Sensor Type. + uint8_t sensorNum; //!< Sensor Number. + uint8_t eventType; //!< Event Dir | Event Type. + uint8_t eventData1; //!< Event Data 1. + uint8_t eventData2; //!< Event Data 2. + uint8_t eventData3; //!< Event Data 3. } __attribute__((packed)); /** @struct DeleteSELEntryRequest @@ -91,8 +92,8 @@ struct GetSELEntryResponse */ struct DeleteSELEntryRequest { - uint16_t reservationID; //!< Reservation ID. - uint16_t selRecordID; //!< SEL Record ID. + uint16_t reservationID; //!< Reservation ID. + uint16_t selRecordID; //!< SEL Record ID. } __attribute__((packed)); static constexpr auto initiateErase = 0xAA; @@ -105,11 +106,11 @@ static constexpr auto eraseComplete = 0x01; */ struct ClearSELRequest { - uint16_t reservationID; //!< Reservation ID. - uint8_t charC; //!< Char 'C'(0x43h). - uint8_t charL; //!< Char 'L'(0x4Ch). - uint8_t charR; //!< Char 'R'(0x52h). - uint8_t eraseOperation; //!< Erase operation. + uint16_t reservationID; //!< Reservation ID. + uint8_t charC; //!< Char 'C'(0x43h). + uint8_t charL; //!< Char 'L'(0x4Ch). + uint8_t charR; //!< Char 'R'(0x52h). + uint8_t eraseOperation; //!< Erase operation. } __attribute__((packed)); /** @brief Convert logging entry to SEL @@ -156,11 +157,11 @@ namespace internal * @return On success return the SEL event record, throw an exception in case * of failure. */ -GetSELEntryResponse prepareSELEntry( - const std::string& objPath, - ipmi::sensor::InvObjectIDMap::const_iterator iter); +GetSELEntryResponse + prepareSELEntry(const std::string& objPath, + ipmi::sensor::InvObjectIDMap::const_iterator iter); -} +} // namespace internal } // namespace sel diff --git a/sensordatahandler.cpp b/sensordatahandler.cpp index ef5089a..d4f1251 100644 --- a/sensordatahandler.cpp +++ b/sensordatahandler.cpp @@ -3,20 +3,23 @@ #include #elif __has_include() #include -namespace std { - // splice experimental::filesystem into std - namespace filesystem = std::experimental::filesystem; -} +namespace std +{ +// splice experimental::filesystem into std +namespace filesystem = std::experimental::filesystem; +} // namespace std #else -# error filesystem not available +#error filesystem not available #endif +#include "sensordatahandler.hpp" +#include "types.hpp" +#include "utils.hpp" + #include #include -#include "xyz/openbmc_project/Common/error.hpp" -#include "types.hpp" +#include + #include "sensorhandler.h" -#include "sensordatahandler.hpp" -#include "utils.hpp" namespace ipmi { @@ -42,10 +45,8 @@ ServicePath getServiceAndPath(sdbusplus::bus::bus& bus, const std::string& path) { auto depth = 0; - auto mapperCall = bus.new_method_call(MAPPER_BUSNAME, - MAPPER_PATH, - MAPPER_INTERFACE, - "GetSubTree"); + auto mapperCall = bus.new_method_call(MAPPER_BUSNAME, MAPPER_PATH, + MAPPER_INTERFACE, "GetSubTree"); mapperCall.append("/"); mapperCall.append(depth); mapperCall.append(std::vector({interface})); @@ -71,7 +72,7 @@ ServicePath getServiceAndPath(sdbusplus::bus::bus& bus, if (path.empty()) { - //Get the first one if the path is not in list. + // Get the first one if the path is not in list. return std::make_pair(mapperResponse.begin()->first, mapperResponse.begin()->second.begin()->first); } @@ -139,7 +140,7 @@ GetSensorResponse mapDbusToAssertion(const Info& sensorInfo, const DbusInterface& interface) { sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; - GetSensorResponse response {}; + GetSensorResponse response{}; auto responseData = reinterpret_cast(response.data()); auto service = ipmi::getService(bus, interface, path); @@ -150,11 +151,8 @@ GetSensorResponse mapDbusToAssertion(const Info& sensorInfo, { for (const auto& property : interface.second) { - auto propValue = ipmi::getDbusProperty(bus, - service, - path, - interface.first, - property.first); + auto propValue = ipmi::getDbusProperty( + bus, service, path, interface.first, property.first); for (const auto& value : std::get(property.second)) { @@ -163,7 +161,6 @@ GetSensorResponse mapDbusToAssertion(const Info& sensorInfo, setOffset(value.first, responseData); break; } - } } } @@ -173,19 +170,17 @@ GetSensorResponse mapDbusToAssertion(const Info& sensorInfo, GetSensorResponse assertion(const Info& sensorInfo) { - return mapDbusToAssertion(sensorInfo, - sensorInfo.sensorPath, + return mapDbusToAssertion(sensorInfo, sensorInfo.sensorPath, sensorInfo.sensorInterface); } GetSensorResponse eventdata2(const Info& sensorInfo) { sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; - GetSensorResponse response {}; + GetSensorResponse response{}; auto responseData = reinterpret_cast(response.data()); - auto service = ipmi::getService(bus, - sensorInfo.sensorInterface, + auto service = ipmi::getService(bus, sensorInfo.sensorInterface, sensorInfo.sensorPath); const auto& interfaceList = sensorInfo.propertyInterfaces; @@ -194,11 +189,9 @@ GetSensorResponse eventdata2(const Info& sensorInfo) { for (const auto& property : interface.second) { - auto propValue = ipmi::getDbusProperty(bus, - service, - sensorInfo.sensorPath, - interface.first, - property.first); + auto propValue = + ipmi::getDbusProperty(bus, service, sensorInfo.sensorPath, + interface.first, property.first); for (const auto& value : std::get(property.second)) { @@ -214,7 +207,7 @@ GetSensorResponse eventdata2(const Info& sensorInfo) return response; } -} //namespace get +} // namespace get namespace set { @@ -227,25 +220,18 @@ IpmiUpdateData makeDbusMsg(const std::string& updateInterface, sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; using namespace std::string_literals; - auto dbusService = getService(bus, - sensorInterface, - sensorPath); + auto dbusService = getService(bus, sensorInterface, sensorPath); - return bus.new_method_call(dbusService.c_str(), - sensorPath.c_str(), - updateInterface.c_str(), - command.c_str()); + return bus.new_method_call(dbusService.c_str(), sensorPath.c_str(), + updateInterface.c_str(), command.c_str()); } -ipmi_ret_t eventdata(const SetSensorReadingReq& cmdData, - const Info& sensorInfo, +ipmi_ret_t eventdata(const SetSensorReadingReq& cmdData, const Info& sensorInfo, uint8_t data) { - auto msg = makeDbusMsg( - "org.freedesktop.DBus.Properties", - sensorInfo.sensorPath, - "Set", - sensorInfo.sensorInterface); + auto msg = + makeDbusMsg("org.freedesktop.DBus.Properties", sensorInfo.sensorPath, + "Set", sensorInfo.sensorInterface); const auto& interface = sensorInfo.propertyInterfaces.begin(); msg.append(interface->first); @@ -263,8 +249,7 @@ ipmi_ret_t eventdata(const SetSensorReadingReq& cmdData, return updateToDbus(msg); } -ipmi_ret_t assertion(const SetSensorReadingReq& cmdData, - const Info& sensorInfo) +ipmi_ret_t assertion(const SetSensorReadingReq& cmdData, const Info& sensorInfo) { std::bitset<16> assertionSet(getAssertionSet(cmdData).first); std::bitset<16> deassertionSet(getAssertionSet(cmdData).second); @@ -297,11 +282,9 @@ ipmi_ret_t assertion(const SetSensorReadingReq& cmdData, if (tmp.valid()) { - auto msg = makeDbusMsg( - "org.freedesktop.DBus.Properties", - sensorInfo.sensorPath, - "Set", - sensorInfo.sensorInterface); + auto msg = makeDbusMsg("org.freedesktop.DBus.Properties", + sensorInfo.sensorPath, "Set", + sensorInfo.sensorInterface); msg.append(interface->first); msg.append(property.first); msg.append(tmp); @@ -317,7 +300,7 @@ ipmi_ret_t assertion(const SetSensorReadingReq& cmdData, return IPMI_CC_OK; } -}//namespace set +} // namespace set namespace notify { @@ -333,20 +316,14 @@ IpmiUpdateData makeDbusMsg(const std::string& updateInterface, static const auto dbusPath = "/xyz/openbmc_project/inventory"s; std::string dbusService = ipmi::getService(bus, updateInterface, dbusPath); - return bus.new_method_call(dbusService.c_str(), - dbusPath.c_str(), - updateInterface.c_str(), - command.c_str()); + return bus.new_method_call(dbusService.c_str(), dbusPath.c_str(), + updateInterface.c_str(), command.c_str()); } -ipmi_ret_t assertion(const SetSensorReadingReq& cmdData, - const Info& sensorInfo) +ipmi_ret_t assertion(const SetSensorReadingReq& cmdData, const Info& sensorInfo) { - auto msg = makeDbusMsg( - sensorInfo.sensorInterface, - sensorInfo.sensorPath, - "Notify", - sensorInfo.sensorInterface); + auto msg = makeDbusMsg(sensorInfo.sensorInterface, sensorInfo.sensorPath, + "Notify", sensorInfo.sensorInterface); std::bitset<16> assertionSet(getAssertionSet(cmdData).first); std::bitset<16> deassertionSet(getAssertionSet(cmdData).second); @@ -354,8 +331,8 @@ ipmi_ret_t assertion(const SetSensorReadingReq& cmdData, ipmi::sensor::InterfaceMap interfaces; for (const auto& interface : sensorInfo.propertyInterfaces) { - //For a property like functional state the result will be - //calculated based on the true value of all conditions. + // For a property like functional state the result will be + // calculated based on the true value of all conditions. for (const auto& property : interface.second) { ipmi::sensor::PropertyMap props; @@ -365,7 +342,7 @@ ipmi_ret_t assertion(const SetSensorReadingReq& cmdData, { if (assertionSet.test(value.first)) { - //Skip update if skipOn is ASSERT + // Skip update if skipOn is ASSERT if (SkipAssertion::ASSERT == value.second.skip) { return IPMI_CC_OK; @@ -375,7 +352,7 @@ ipmi_ret_t assertion(const SetSensorReadingReq& cmdData, } else if (deassertionSet.test(value.first)) { - //Skip update if skipOn is DEASSERT + // Skip update if skipOn is DEASSERT if (SkipAssertion::DEASSERT == value.second.skip) { return IPMI_CC_OK; @@ -385,7 +362,7 @@ ipmi_ret_t assertion(const SetSensorReadingReq& cmdData, } } for (const auto& value : - std::get(property.second)) + std::get(property.second)) { if (assertionSet.test(value.first)) { @@ -409,7 +386,7 @@ ipmi_ret_t assertion(const SetSensorReadingReq& cmdData, return updateToDbus(msg); } -}//namespace notify +} // namespace notify namespace inventory { @@ -425,13 +402,12 @@ GetSensorResponse assertion(const Info& sensorInfo) path += sensorInfo.sensorPath; return ipmi::sensor::get::mapDbusToAssertion( - sensorInfo, - path.string(), - sensorInfo.propertyInterfaces.begin()->first); + sensorInfo, path.string(), + sensorInfo.propertyInterfaces.begin()->first); } -} //namespace get +} // namespace get } // namespace inventory -}//namespace sensor -}//namespace ipmi +} // namespace sensor +} // namespace ipmi diff --git a/sensordatahandler.hpp b/sensordatahandler.hpp index e36b71a..7185116 100644 --- a/sensordatahandler.hpp +++ b/sensordatahandler.hpp @@ -1,10 +1,12 @@ #pragma once -#include -#include "sensorhandler.h" #include "types.hpp" #include "utils.hpp" + +#include + #include "host-ipmid/ipmid-api.h" +#include "sensorhandler.h" namespace ipmi { @@ -89,8 +91,8 @@ inline SensorName nameProperty(const Info& sensorInfo) inline SensorName nameLeaf(const Info& sensorInfo) { return sensorInfo.sensorPath.substr( - sensorInfo.sensorPath.find_last_of('/') + 1, - sensorInfo.sensorPath.length()); + sensorInfo.sensorPath.find_last_of('/') + 1, + sensorInfo.sensorPath.length()); } /** @brief Populate sensor name from the D-Bus object associated with the @@ -147,23 +149,20 @@ GetSensorResponse eventdata2(const Info& sensorInfo); * * @return Response for get sensor reading command. */ -template +template GetSensorResponse readingAssertion(const Info& sensorInfo) { sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; - GetSensorResponse response {}; + GetSensorResponse response{}; auto responseData = reinterpret_cast(response.data()); - auto service = ipmi::getService(bus, - sensorInfo.sensorInterface, + auto service = ipmi::getService(bus, sensorInfo.sensorInterface, sensorInfo.sensorPath); auto propValue = ipmi::getDbusProperty( - bus, - service, - sensorInfo.sensorPath, - sensorInfo.propertyInterfaces.begin()->first, - sensorInfo.propertyInterfaces.begin()->second.begin()->first); + bus, service, sensorInfo.sensorPath, + sensorInfo.propertyInterfaces.begin()->first, + sensorInfo.propertyInterfaces.begin()->second.begin()->first); setAssertionBytes(static_cast(propValue.get()), responseData); @@ -178,38 +177,35 @@ GetSensorResponse readingAssertion(const Info& sensorInfo) * * @return Response for get sensor reading command. */ -template +template GetSensorResponse readingData(const Info& sensorInfo) { sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; - GetSensorResponse response {}; + GetSensorResponse response{}; auto responseData = reinterpret_cast(response.data()); enableScanning(responseData); - auto service = ipmi::getService(bus, - sensorInfo.sensorInterface, + auto service = ipmi::getService(bus, sensorInfo.sensorInterface, sensorInfo.sensorPath); auto propValue = ipmi::getDbusProperty( - bus, - service, - sensorInfo.sensorPath, - sensorInfo.propertyInterfaces.begin()->first, - sensorInfo.propertyInterfaces.begin()->second.begin()->first); + bus, service, sensorInfo.sensorPath, + sensorInfo.propertyInterfaces.begin()->first, + sensorInfo.propertyInterfaces.begin()->second.begin()->first); - double value = propValue.get() * pow(10, - sensorInfo.scale - sensorInfo.exponentR); + double value = + propValue.get() * pow(10, sensorInfo.scale - sensorInfo.exponentR); - auto rawData = static_cast( - (value - sensorInfo.scaledOffset) / sensorInfo.coefficientM); + auto rawData = static_cast((value - sensorInfo.scaledOffset) / + sensorInfo.coefficientM); setReading(rawData, responseData); return response; } -} //namespace get +} // namespace get namespace set { @@ -240,15 +236,13 @@ ipmi_ret_t assertion(const SetSensorReadingReq& cmdData, * @param[in] sensorInfo - sensor d-bus info * @return a IPMI error code */ -template +template ipmi_ret_t readingAssertion(const SetSensorReadingReq& cmdData, const Info& sensorInfo) { - auto msg = makeDbusMsg( - "org.freedesktop.DBus.Properties", - sensorInfo.sensorPath, - "Set", - sensorInfo.sensorInterface); + auto msg = + makeDbusMsg("org.freedesktop.DBus.Properties", sensorInfo.sensorPath, + "Set", sensorInfo.sensorInterface); const auto& interface = sensorInfo.propertyInterfaces.begin(); msg.append(interface->first); @@ -267,19 +261,18 @@ ipmi_ret_t readingAssertion(const SetSensorReadingReq& cmdData, * @param[in] sensorInfo - sensor d-bus info * @return an IPMI error code */ -template +template ipmi_ret_t readingData(const SetSensorReadingReq& cmdData, const Info& sensorInfo) { - T raw_value = (sensorInfo.coefficientM * cmdData.reading) + - sensorInfo.scaledOffset; + T raw_value = + (sensorInfo.coefficientM * cmdData.reading) + sensorInfo.scaledOffset; raw_value *= pow(10, sensorInfo.exponentR - sensorInfo.scale); - auto msg = makeDbusMsg("org.freedesktop.DBus.Properties", - sensorInfo.sensorPath, - "Set", - sensorInfo.sensorInterface); + auto msg = + makeDbusMsg("org.freedesktop.DBus.Properties", sensorInfo.sensorPath, + "Set", sensorInfo.sensorInterface); const auto& interface = sensorInfo.propertyInterfaces.begin(); msg.append(interface->first); @@ -298,8 +291,7 @@ ipmi_ret_t readingData(const SetSensorReadingReq& cmdData, * @param[in] sensorInfo - sensor d-bus info * @return a IPMI error code */ -ipmi_ret_t eventdata(const SetSensorReadingReq& cmdData, - const Info& sensorInfo, +ipmi_ret_t eventdata(const SetSensorReadingReq& cmdData, const Info& sensorInfo, uint8_t data); /** @brief Update d-bus based on eventdata1 type sensor data @@ -335,7 +327,7 @@ inline ipmi_ret_t eventdata3(const SetSensorReadingReq& cmdData, return eventdata(cmdData, sensorInfo, cmdData.eventData3); } -}//namespace set +} // namespace set namespace notify { @@ -361,7 +353,7 @@ IpmiUpdateData makeDbusMsg(const std::string& updateInterface, ipmi_ret_t assertion(const SetSensorReadingReq& cmdData, const Info& sensorInfo); -}//namespace notify +} // namespace notify namespace inventory { @@ -382,5 +374,5 @@ GetSensorResponse assertion(const Info& sensorInfo); } // namespace get } // namespace inventory -}//namespace sensor -}//namespace ipmi +} // namespace sensor +} // namespace ipmi diff --git a/sensorhandler.cpp b/sensorhandler.cpp index 609fdfd..41d393b 100644 --- a/sensorhandler.cpp +++ b/sensorhandler.cpp @@ -1,42 +1,46 @@ +#include "sensorhandler.h" + +#include "fruread.hpp" +#include "ipmid.hpp" +#include "types.hpp" +#include "utils.hpp" + #include #include #include #include -#include +#include + #include +#include +#include +#include +#include #include -#include + #include "host-ipmid/ipmid-api.h" -#include -#include -#include "fruread.hpp" -#include "ipmid.hpp" -#include "sensorhandler.h" -#include "types.hpp" -#include "utils.hpp" -#include "xyz/openbmc_project/Common/error.hpp" static constexpr uint8_t fruInventoryDevice = 0x10; static constexpr uint8_t IPMIFruInventory = 0x02; static constexpr uint8_t BMCSlaveAddress = 0x20; -extern int updateSensorRecordFromSSRAESC(const void *); -extern sd_bus *bus; +extern int updateSensorRecordFromSSRAESC(const void*); +extern sd_bus* bus; extern const ipmi::sensor::IdInfoMap sensors; extern const FruMap frus; - using namespace phosphor::logging; using InternalFailure = sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; -void register_netfn_sen_functions() __attribute__((constructor)); +void register_netfn_sen_functions() __attribute__((constructor)); -struct sensorTypemap_t { +struct sensorTypemap_t +{ uint8_t number; uint8_t typecode; char dbusname[32]; -} ; +}; sensorTypemap_t g_SensorTypeMap[] = { @@ -47,7 +51,8 @@ sensorTypemap_t g_SensorTypeMap[] = { {0x07, 0x6F, "CORE"}, {0x07, 0x6F, "CPU"}, {0x0F, 0x6F, "BootProgress"}, - {0xe9, 0x09, "OccStatus"}, // E9 is an internal mapping to handle sensor type code os 0x09 + {0xe9, 0x09, "OccStatus"}, // E9 is an internal mapping to handle sensor + // type code os 0x09 {0xC3, 0x6F, "BootCount"}, {0x1F, 0x6F, "OperatingSystemStatus"}, {0x12, 0x6F, "SYSTEM_EVENT"}, @@ -60,47 +65,53 @@ sensorTypemap_t g_SensorTypeMap[] = { {0xFF, 0x00, ""}, }; - -struct sensor_data_t { +struct sensor_data_t +{ uint8_t sennum; -} __attribute__ ((packed)) ; +} __attribute__((packed)); -struct sensorreadingresp_t { +struct sensorreadingresp_t +{ uint8_t value; uint8_t operation; uint8_t indication[2]; -} __attribute__ ((packed)) ; +} __attribute__((packed)); -int get_bus_for_path(const char *path, char **busname) { +int get_bus_for_path(const char* path, char** busname) +{ return mapper_get_service(bus, path, busname); } -int legacy_dbus_openbmc_path(const char *type, const uint8_t num, dbus_interface_t *interface) { - char *busname = NULL; - const char *iface = "org.openbmc.managers.System"; - const char *objname = "/org/openbmc/managers/System"; - char *str1 = NULL, *str2, *str3; +int legacy_dbus_openbmc_path(const char* type, const uint8_t num, + dbus_interface_t* interface) +{ + char* busname = NULL; + const char* iface = "org.openbmc.managers.System"; + const char* objname = "/org/openbmc/managers/System"; + char *str1 = NULL, *str2, *str3; sd_bus_error error = SD_BUS_ERROR_NULL; - sd_bus_message *reply = NULL; - + sd_bus_message* reply = NULL; int r; r = get_bus_for_path(objname, &busname); - if (r < 0) { - fprintf(stderr, "Failed to get %s busname: %s\n", - objname, strerror(-r)); + if (r < 0) + { + fprintf(stderr, "Failed to get %s busname: %s\n", objname, + strerror(-r)); goto final; } - r = sd_bus_call_method(bus,busname,objname,iface, "getObjectFromByteId", + r = sd_bus_call_method(bus, busname, objname, iface, "getObjectFromByteId", &error, &reply, "sy", type, num); - if (r < 0) { + if (r < 0) + { fprintf(stderr, "Failed to create a method call: %s", strerror(-r)); goto final; } r = sd_bus_message_read(reply, "(ss)", &str2, &str3); - if (r < 0) { + if (r < 0) + { fprintf(stderr, "Failed to get a response: %s", strerror(-r)); goto final; } @@ -113,9 +124,9 @@ int legacy_dbus_openbmc_path(const char *type, const uint8_t num, dbus_interface } r = get_bus_for_path(str2, &str1); - if (r < 0) { - fprintf(stderr, "Failed to get %s busname: %s\n", - str2, strerror(-r)); + if (r < 0) + { + fprintf(stderr, "Failed to get %s busname: %s\n", str2, strerror(-r)); goto final; } @@ -141,7 +152,8 @@ final: // Use a lookup table to find the interface name of a specific sensor // This will be used until an alternative is found. this is the first // step for mapping IPMI -int find_openbmc_path(uint8_t num, dbus_interface_t *interface) { +int find_openbmc_path(uint8_t num, dbus_interface_t* interface) +{ int rc; // When the sensor map does not contain the sensor requested, @@ -156,10 +168,10 @@ int find_openbmc_path(uint8_t num, dbus_interface_t *interface) { char* busname = nullptr; rc = get_bus_for_path(info.sensorPath.c_str(), &busname); - if (rc < 0) { + if (rc < 0) + { fprintf(stderr, "Failed to get %s busname: %s\n", - info.sensorPath.c_str(), - busname); + info.sensorPath.c_str(), busname); goto final; } @@ -170,7 +182,8 @@ int find_openbmc_path(uint8_t num, dbus_interface_t *interface) { // works for the Value interface but may not suffice for more complex // sensors. // tracked https://github.com/openbmc/phosphor-host-ipmid/issues/103 - strcpy(interface->interface, info.propertyInterfaces.begin()->first.c_str()); + strcpy(interface->interface, + info.propertyInterfaces.begin()->first.c_str()); interface->sensornumber = num; final: @@ -178,45 +191,51 @@ final: return rc; } - ///////////////////////////////////////////////////////////////////// // // Routines used by ipmi commands wanting to interact on the dbus // ///////////////////////////////////////////////////////////////////// -int set_sensor_dbus_state_s(uint8_t number, const char *method, const char *value) { - +int set_sensor_dbus_state_s(uint8_t number, const char* method, + const char* value) +{ dbus_interface_t a; int r; sd_bus_error error = SD_BUS_ERROR_NULL; - sd_bus_message *m=NULL; + sd_bus_message* m = NULL; - fprintf(ipmidbus, "Attempting to set a dbus Variant Sensor 0x%02x via %s with a value of %s\n", - number, method, value); + fprintf(ipmidbus, + "Attempting to set a dbus Variant Sensor 0x%02x via %s with a " + "value of %s\n", + number, method, value); r = find_openbmc_path(number, &a); - if (r < 0) { + if (r < 0) + { fprintf(stderr, "Failed to find Sensor 0x%02x\n", number); return 0; } - r = sd_bus_message_new_method_call(bus,&m,a.bus,a.path,a.interface,method); - if (r < 0) { + r = sd_bus_message_new_method_call(bus, &m, a.bus, a.path, a.interface, + method); + if (r < 0) + { fprintf(stderr, "Failed to create a method call: %s", strerror(-r)); goto final; } r = sd_bus_message_append(m, "v", "s", value); - if (r < 0) { + if (r < 0) + { fprintf(stderr, "Failed to create a input parameter: %s", strerror(-r)); goto final; } - r = sd_bus_call(bus, m, 0, &error, NULL); - if (r < 0) { + if (r < 0) + { fprintf(stderr, "Failed to call the method: %s", strerror(-r)); } @@ -226,39 +245,46 @@ final: return 0; } -int set_sensor_dbus_state_y(uint8_t number, const char *method, const uint8_t value) { - +int set_sensor_dbus_state_y(uint8_t number, const char* method, + const uint8_t value) +{ dbus_interface_t a; int r; sd_bus_error error = SD_BUS_ERROR_NULL; - sd_bus_message *m=NULL; + sd_bus_message* m = NULL; - fprintf(ipmidbus, "Attempting to set a dbus Variant Sensor 0x%02x via %s with a value of 0x%02x\n", - number, method, value); + fprintf(ipmidbus, + "Attempting to set a dbus Variant Sensor 0x%02x via %s with a " + "value of 0x%02x\n", + number, method, value); r = find_openbmc_path(number, &a); - if (r < 0) { + if (r < 0) + { fprintf(stderr, "Failed to find Sensor 0x%02x\n", number); return 0; } - r = sd_bus_message_new_method_call(bus,&m,a.bus,a.path,a.interface,method); - if (r < 0) { + r = sd_bus_message_new_method_call(bus, &m, a.bus, a.path, a.interface, + method); + if (r < 0) + { fprintf(stderr, "Failed to create a method call: %s", strerror(-r)); goto final; } r = sd_bus_message_append(m, "v", "i", value); - if (r < 0) { + if (r < 0) + { fprintf(stderr, "Failed to create a input parameter: %s", strerror(-r)); goto final; } - r = sd_bus_call(bus, m, 0, &error, NULL); - if (r < 0) { + if (r < 0) + { fprintf(stderr, "12 Failed to call the method: %s", strerror(-r)); } @@ -269,14 +295,17 @@ final: return 0; } -uint8_t dbus_to_sensor_type(char *p) { +uint8_t dbus_to_sensor_type(char* p) +{ - sensorTypemap_t *s = g_SensorTypeMap; - char r=0; - while (s->number != 0xFF) { - if (!strcmp(s->dbusname,p)) { + sensorTypemap_t* s = g_SensorTypeMap; + char r = 0; + while (s->number != 0xFF) + { + if (!strcmp(s->dbusname, p)) + { r = s->typecode; - break; + break; } s++; } @@ -287,75 +316,79 @@ uint8_t dbus_to_sensor_type(char *p) { return r; } +uint8_t get_type_from_interface(dbus_interface_t dbus_if) +{ -uint8_t get_type_from_interface(dbus_interface_t dbus_if) { - - char *p; + char* p; uint8_t type; // This is where sensors that do not exist in dbus but do // exist in the host code stop. This should indicate it // is not a supported sensor - if (dbus_if.interface[0] == 0) { return 0;} + if (dbus_if.interface[0] == 0) + { + return 0; + } // Fetch type from interface itself. if (dbus_if.sensortype != 0) { type = dbus_if.sensortype; - } else { + } + else + { // Non InventoryItems - p = strrchr (dbus_if.path, '/'); - type = dbus_to_sensor_type(p+1); + p = strrchr(dbus_if.path, '/'); + type = dbus_to_sensor_type(p + 1); } return type; - } +} // Replaces find_sensor -uint8_t find_type_for_sensor_number(uint8_t num) { +uint8_t find_type_for_sensor_number(uint8_t num) +{ int r; dbus_interface_t dbus_if; r = find_openbmc_path(num, &dbus_if); - if (r < 0) { + if (r < 0) + { fprintf(stderr, "Could not find sensor %d\n", num); return 0; } return get_type_from_interface(dbus_if); } - - - - ipmi_ret_t ipmi_sen_get_sensor_type(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { - sensor_data_t *reqptr = (sensor_data_t*)request; + sensor_data_t* reqptr = (sensor_data_t*)request; ipmi_ret_t rc = IPMI_CC_OK; - printf("IPMI GET_SENSOR_TYPE [0x%02X]\n",reqptr->sennum); + printf("IPMI GET_SENSOR_TYPE [0x%02X]\n", reqptr->sennum); // TODO Not sure what the System-event-sensor is suppose to return // need to ask Hostboot team - unsigned char buf[] = {0x00,0x6F}; + unsigned char buf[] = {0x00, 0x6F}; buf[0] = find_type_for_sensor_number(reqptr->sennum); // HACK UNTIL Dbus gets updated or we find a better way - if (buf[0] == 0) { + if (buf[0] == 0) + { rc = IPMI_CC_SENSOR_INVALID; } - *data_len = sizeof(buf); memcpy(response, &buf, *data_len); return rc; } -const std::set analogSensorInterfaces = -{ +const std::set analogSensorInterfaces = { "xyz.openbmc_project.Sensor.Value", "xyz.openbmc_project.Control.FanPwm", }; @@ -365,10 +398,10 @@ bool isAnalogSensor(const std::string& interface) return (analogSensorInterfaces.count(interface)); } -ipmi_ret_t setSensorReading(void *request) +ipmi_ret_t setSensorReading(void* request) { ipmi::sensor::SetSensorReadingReq cmdData = - *(static_cast(request)); + *(static_cast(request)); // Check if the Sensor Number is present const auto iter = sensors.find(cmdData.number); @@ -380,7 +413,7 @@ ipmi_ret_t setSensorReading(void *request) try { if (ipmi::sensor::Mutability::Write != - (iter->second.mutability & ipmi::sensor::Mutability::Write)) + (iter->second.mutability & ipmi::sensor::Mutability::Write)) { log("Sensor Set operation is not allowed", entry("SENSOR_NUM=%d", cmdData.number)); @@ -390,9 +423,9 @@ ipmi_ret_t setSensorReading(void *request) } catch (InternalFailure& e) { - log("Set sensor failed", - entry("SENSOR_NUM=%d", cmdData.number)); - commit(); + log("Set sensor failed", + entry("SENSOR_NUM=%d", cmdData.number)); + commit(); } catch (const std::runtime_error& e) { @@ -403,10 +436,10 @@ ipmi_ret_t setSensorReading(void *request) } ipmi_ret_t ipmi_sen_set_sensor(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, ipmi_response_t response, + ipmi_data_len_t data_len, ipmi_context_t context) { - sensor_data_t *reqptr = (sensor_data_t*)request; + sensor_data_t* reqptr = (sensor_data_t*)request; log("IPMI SET_SENSOR", entry("SENSOR_NUM=0x%02x", reqptr->sennum)); @@ -418,30 +451,29 @@ ipmi_ret_t ipmi_sen_set_sensor(ipmi_netfn_t netfn, ipmi_cmd_t cmd, */ auto ipmiRC = setSensorReading(request); - if(ipmiRC == IPMI_CC_SENSOR_INVALID) + if (ipmiRC == IPMI_CC_SENSOR_INVALID) { updateSensorRecordFromSSRAESC(reqptr); ipmiRC = IPMI_CC_OK; } - *data_len=0; + *data_len = 0; return ipmiRC; } -ipmi_ret_t legacyGetSensorReading(uint8_t sensorNum, - ipmi_response_t response, +ipmi_ret_t legacyGetSensorReading(uint8_t sensorNum, ipmi_response_t response, ipmi_data_len_t data_len) { int r; dbus_interface_t a; - sd_bus *bus = ipmid_get_sd_bus_connection(); + sd_bus* bus = ipmid_get_sd_bus_connection(); ipmi_ret_t rc = IPMI_CC_SENSOR_INVALID; uint8_t type = 0; - sd_bus_message *reply = NULL; + sd_bus_message* reply = NULL; int reading = 0; char* assertion = NULL; - sensorreadingresp_t *resp = (sensorreadingresp_t*) response; - *data_len=0; + sensorreadingresp_t* resp = (sensorreadingresp_t*)response; + *data_len = 0; r = find_openbmc_path(sensorNum, &a); if (r < 0) @@ -453,76 +485,84 @@ ipmi_ret_t legacyGetSensorReading(uint8_t sensorNum, type = get_type_from_interface(a); if (type == 0) { - sd_journal_print(LOG_ERR, "Failed to find Sensor 0x%02x\n", - sensorNum); + sd_journal_print(LOG_ERR, "Failed to find Sensor 0x%02x\n", sensorNum); return IPMI_CC_SENSOR_INVALID; } - switch(type) { + switch (type) + { case 0xC2: - r = sd_bus_get_property(bus,a.bus, a.path, a.interface, - "value", NULL, &reply, "i"); + r = sd_bus_get_property(bus, a.bus, a.path, a.interface, "value", + NULL, &reply, "i"); if (r < 0) { - sd_journal_print(LOG_ERR, "Failed to call sd_bus_get_property:" - " %d, %s\n", r, strerror(-r)); + sd_journal_print(LOG_ERR, + "Failed to call sd_bus_get_property:" + " %d, %s\n", + r, strerror(-r)); sd_journal_print(LOG_ERR, "Bus: %s, Path: %s, Interface: %s\n", a.bus, a.path, a.interface); break; } r = sd_bus_message_read(reply, "i", &reading); - if (r < 0) { + if (r < 0) + { sd_journal_print(LOG_ERR, "Failed to read sensor: %s\n", strerror(-r)); break; } rc = IPMI_CC_OK; - *data_len=sizeof(sensorreadingresp_t); + *data_len = sizeof(sensorreadingresp_t); - resp->value = (uint8_t)reading; - resp->operation = 0; + resp->value = (uint8_t)reading; + resp->operation = 0; resp->indication[0] = 0; resp->indication[1] = 0; break; case 0xC8: - r = sd_bus_get_property(bus,a.bus, a.path, a.interface, - "value", NULL, &reply, "i"); + r = sd_bus_get_property(bus, a.bus, a.path, a.interface, "value", + NULL, &reply, "i"); if (r < 0) { - sd_journal_print(LOG_ERR, "Failed to call sd_bus_get_property:" - " %d, %s\n", r, strerror(-r)); + sd_journal_print(LOG_ERR, + "Failed to call sd_bus_get_property:" + " %d, %s\n", + r, strerror(-r)); sd_journal_print(LOG_ERR, "Bus: %s, Path: %s, Interface: %s\n", a.bus, a.path, a.interface); break; } r = sd_bus_message_read(reply, "i", &reading); - if (r < 0) { + if (r < 0) + { sd_journal_print(LOG_ERR, "Failed to read sensor: %s\n", strerror(-r)); break; } rc = IPMI_CC_OK; - *data_len=sizeof(sensorreadingresp_t); + *data_len = sizeof(sensorreadingresp_t); - resp->value = 0; - resp->operation = 0; + resp->value = 0; + resp->operation = 0; resp->indication[0] = (uint8_t)reading; resp->indication[1] = 0; break; - //TODO openbmc/openbmc#2154 Move this sensor to right place. + // TODO openbmc/openbmc#2154 Move this sensor to right place. case 0xCA: - r = sd_bus_get_property(bus,a.bus, a.path, a.interface, "value", + r = sd_bus_get_property(bus, a.bus, a.path, a.interface, "value", NULL, &reply, "s"); if (r < 0) { - sd_journal_print(LOG_ERR, "Failed to call sd_bus_get_property:" - " %d, %s\n", r, strerror(-r)); + sd_journal_print(LOG_ERR, + "Failed to call sd_bus_get_property:" + " %d, %s\n", + r, strerror(-r)); sd_journal_print(LOG_ERR, "Bus: %s, Path: %s, Interface: %s\n", a.bus, a.path, a.interface); break; @@ -537,11 +577,11 @@ ipmi_ret_t legacyGetSensorReading(uint8_t sensorNum, } rc = IPMI_CC_OK; - *data_len=sizeof(sensorreadingresp_t); + *data_len = sizeof(sensorreadingresp_t); - resp->value = 0; - resp->operation = 0; - if (strcmp(assertion,"Enabled") == 0) + resp->value = 0; + resp->operation = 0; + if (strcmp(assertion, "Enabled") == 0) { resp->indication[0] = 0x02; } @@ -564,12 +604,14 @@ ipmi_ret_t legacyGetSensorReading(uint8_t sensorNum, } ipmi_ret_t ipmi_sen_get_sensor_reading(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { - sensor_data_t *reqptr = (sensor_data_t*)request; - sensorreadingresp_t *resp = (sensorreadingresp_t*) response; - ipmi::sensor::GetSensorResponse getResponse {}; + sensor_data_t* reqptr = (sensor_data_t*)request; + sensorreadingresp_t* resp = (sensorreadingresp_t*)response; + ipmi::sensor::GetSensorResponse getResponse{}; static constexpr auto scanningEnabledBit = 6; const auto iter = sensors.find(reqptr->sennum); @@ -578,14 +620,14 @@ ipmi_ret_t ipmi_sen_get_sensor_reading(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return legacyGetSensorReading(reqptr->sennum, response, data_len); } if (ipmi::sensor::Mutability::Read != - (iter->second.mutability & ipmi::sensor::Mutability::Read)) + (iter->second.mutability & ipmi::sensor::Mutability::Read)) { return IPMI_CC_ILLEGAL_COMMAND; } try { - getResponse = iter->second.getFunc(iter->second); + getResponse = iter->second.getFunc(iter->second); *data_len = getResponse.size(); memcpy(resp, getResponse.data(), *data_len); resp->operation = 1 << scanningEnabledBit; @@ -614,10 +656,8 @@ void getSensorThresholds(uint8_t sensorNum, auto service = ipmi::getService(bus, info.sensorInterface, info.sensorPath); - auto warnThresholds = ipmi::getAllDbusProperties(bus, - service, - info.sensorPath, - warningThreshIntf); + auto warnThresholds = ipmi::getAllDbusProperties( + bus, service, info.sensorPath, warningThreshIntf); double warnLow = mapbox::util::apply_visitor(ipmi::VariantToDoubleVisitor(), warnThresholds["WarningLow"]); @@ -627,25 +667,23 @@ void getSensorThresholds(uint8_t sensorNum, if (warnLow != 0) { warnLow *= pow(10, info.scale - info.exponentR); - response->lowerNonCritical = static_cast(( - warnLow - info.scaledOffset) / info.coefficientM); + response->lowerNonCritical = static_cast( + (warnLow - info.scaledOffset) / info.coefficientM); response->validMask |= static_cast( - ipmi::sensor::ThresholdMask::NON_CRITICAL_LOW_MASK); + ipmi::sensor::ThresholdMask::NON_CRITICAL_LOW_MASK); } if (warnHigh != 0) { warnHigh *= pow(10, info.scale - info.exponentR); - response->upperNonCritical = static_cast(( - warnHigh - info.scaledOffset) / info.coefficientM); + response->upperNonCritical = static_cast( + (warnHigh - info.scaledOffset) / info.coefficientM); response->validMask |= static_cast( - ipmi::sensor::ThresholdMask::NON_CRITICAL_HIGH_MASK); + ipmi::sensor::ThresholdMask::NON_CRITICAL_HIGH_MASK); } - auto critThresholds = ipmi::getAllDbusProperties(bus, - service, - info.sensorPath, - criticalThreshIntf); + auto critThresholds = ipmi::getAllDbusProperties( + bus, service, info.sensorPath, criticalThreshIntf); double critLow = mapbox::util::apply_visitor(ipmi::VariantToDoubleVisitor(), critThresholds["CriticalLow"]); double critHigh = mapbox::util::apply_visitor( @@ -654,25 +692,27 @@ void getSensorThresholds(uint8_t sensorNum, if (critLow != 0) { critLow *= pow(10, info.scale - info.exponentR); - response->lowerCritical = static_cast(( - critLow - info.scaledOffset) / info.coefficientM); + response->lowerCritical = static_cast( + (critLow - info.scaledOffset) / info.coefficientM); response->validMask |= static_cast( - ipmi::sensor::ThresholdMask::CRITICAL_LOW_MASK); + ipmi::sensor::ThresholdMask::CRITICAL_LOW_MASK); } if (critHigh != 0) { critHigh *= pow(10, info.scale - info.exponentR); - response->upperCritical = static_cast(( - critHigh - info.scaledOffset)/ info.coefficientM); + response->upperCritical = static_cast( + (critHigh - info.scaledOffset) / info.coefficientM); response->validMask |= static_cast( - ipmi::sensor::ThresholdMask::CRITICAL_HIGH_MASK); + ipmi::sensor::ThresholdMask::CRITICAL_HIGH_MASK); } } ipmi_ret_t ipmi_sen_get_sensor_thresholds(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { constexpr auto valueInterface = "xyz.openbmc_project.Sensor.Value"; @@ -682,7 +722,7 @@ ipmi_ret_t ipmi_sen_get_sensor_thresholds(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return IPMI_CC_REQ_DATA_LEN_INVALID; } - auto sensorNum = *(reinterpret_cast(request)); + auto sensorNum = *(reinterpret_cast(request)); *data_len = 0; const auto iter = sensors.find(sensorNum); @@ -693,11 +733,11 @@ ipmi_ret_t ipmi_sen_get_sensor_thresholds(ipmi_netfn_t netfn, ipmi_cmd_t cmd, const auto info = iter->second; - //Proceed only if the sensor value interface is implemented. + // Proceed only if the sensor value interface is implemented. if (info.propertyInterfaces.find(valueInterface) == info.propertyInterfaces.end()) { - //return with valid mask as 0 + // return with valid mask as 0 return IPMI_CC_OK; } @@ -710,7 +750,7 @@ ipmi_ret_t ipmi_sen_get_sensor_thresholds(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } catch (std::exception& e) { - //Mask if the property is not present + // Mask if the property is not present responseData->validMask = 0; } @@ -724,7 +764,7 @@ ipmi_ret_t ipmi_sen_wildcard(ipmi_netfn_t netfn, ipmi_cmd_t cmd, { ipmi_ret_t rc = IPMI_CC_INVALID; - printf("IPMI S/E Wildcard Netfn:[0x%X], Cmd:[0x%X]\n",netfn,cmd); + printf("IPMI S/E Wildcard Netfn:[0x%X], Cmd:[0x%X]\n", netfn, cmd); *data_len = 0; return rc; @@ -776,8 +816,8 @@ ipmi_ret_t ipmi_sen_reserve_sdr(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return IPMI_CC_OK; } -void setUnitFieldsForObject(const ipmi::sensor::Info *info, - get_sdr::SensorDataFullRecordBody *body) +void setUnitFieldsForObject(const ipmi::sensor::Info* info, + get_sdr::SensorDataFullRecordBody* body) { namespace server = sdbusplus::xyz::openbmc_project::Sensor::server; try @@ -791,7 +831,8 @@ void setUnitFieldsForObject(const ipmi::sensor::Info *info, body->sensor_units_2_base = get_sdr::SENSOR_UNIT_DEGREES_C; break; case server::Value::Unit::RPMS: - body->sensor_units_2_base = get_sdr::SENSOR_UNIT_REVOLUTIONS; // revolutions + body->sensor_units_2_base = + get_sdr::SENSOR_UNIT_REVOLUTIONS; // revolutions get_sdr::body::set_rate_unit(0b100, body); // per minute break; case server::Value::Unit::Volts: @@ -821,8 +862,8 @@ void setUnitFieldsForObject(const ipmi::sensor::Info *info, } } -ipmi_ret_t populate_record_from_dbus(get_sdr::SensorDataFullRecordBody *body, - const ipmi::sensor::Info *info, +ipmi_ret_t populate_record_from_dbus(get_sdr::SensorDataFullRecordBody* body, + const ipmi::sensor::Info* info, ipmi_data_len_t data_len) { /* Functional sensor case */ @@ -864,11 +905,11 @@ ipmi_ret_t ipmi_fru_get_sdr(ipmi_request_t request, ipmi_response_t response, { auto req = reinterpret_cast(request); auto resp = reinterpret_cast(response); - get_sdr::SensorDataFruRecord record {}; + get_sdr::SensorDataFruRecord record{}; auto dataLength = 0; auto fru = frus.begin(); - uint8_t fruID {}; + uint8_t fruID{}; auto recordID = get_sdr::request::get_record_id(req); fruID = recordID - FRU_RECORD_ID_START; @@ -896,21 +937,18 @@ ipmi_ret_t ipmi_fru_get_sdr(ipmi_request_t request, ipmi_response_t response, record.body.deviceTypeModifier = IPMIFruInventory; /* Device ID string */ - auto deviceID = fru->second[0].path.substr( - fru->second[0].path.find_last_of('/') + 1, - fru->second[0].path.length()); - + auto deviceID = + fru->second[0].path.substr(fru->second[0].path.find_last_of('/') + 1, + fru->second[0].path.length()); if (deviceID.length() > get_sdr::FRU_RECORD_DEVICE_ID_MAX_LENGTH) { get_sdr::body::set_device_id_strlen( - get_sdr::FRU_RECORD_DEVICE_ID_MAX_LENGTH, - &(record.body)); + get_sdr::FRU_RECORD_DEVICE_ID_MAX_LENGTH, &(record.body)); } else { - get_sdr::body::set_device_id_strlen(deviceID.length(), - &(record.body)); + get_sdr::body::set_device_id_strlen(deviceID.length(), &(record.body)); } strncpy(record.body.deviceID, deviceID.c_str(), @@ -918,12 +956,13 @@ ipmi_ret_t ipmi_fru_get_sdr(ipmi_request_t request, ipmi_response_t response, if (++fru == frus.end()) { - get_sdr::response::set_next_record_id(END_OF_RECORD, resp); // last record + get_sdr::response::set_next_record_id(END_OF_RECORD, + resp); // last record } else { get_sdr::response::set_next_record_id( - (FRU_RECORD_ID_START + fru->first), resp); + (FRU_RECORD_ID_START + fru->first), resp); } if (req->bytes_to_read > (sizeof(*resp) - req->offset)) @@ -932,7 +971,7 @@ ipmi_ret_t ipmi_fru_get_sdr(ipmi_request_t request, ipmi_response_t response, } else { - dataLength = req->bytes_to_read; + dataLength = req->bytes_to_read; } if (dataLength <= 0) @@ -940,9 +979,8 @@ ipmi_ret_t ipmi_fru_get_sdr(ipmi_request_t request, ipmi_response_t response, return IPMI_CC_REQ_DATA_LEN_INVALID; } - memcpy(resp->record_data, - reinterpret_cast(&record) + req->offset, - (dataLength)); + memcpy(resp->record_data, reinterpret_cast(&record) + req->offset, + (dataLength)); *data_len = dataLength; *data_len += 2; // additional 2 bytes for next record ID @@ -955,8 +993,8 @@ ipmi_ret_t ipmi_sen_get_sdr(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_data_len_t data_len, ipmi_context_t context) { ipmi_ret_t ret = IPMI_CC_OK; - get_sdr::GetSdrReq *req = (get_sdr::GetSdrReq*)request; - get_sdr::GetSdrResp *resp = (get_sdr::GetSdrResp*)response; + get_sdr::GetSdrReq* req = (get_sdr::GetSdrReq*)request; + get_sdr::GetSdrResp* resp = (get_sdr::GetSdrResp*)response; get_sdr::SensorDataFullRecord record = {0}; if (req != NULL) { @@ -1011,9 +1049,9 @@ ipmi_ret_t ipmi_sen_get_sdr(ipmi_netfn_t netfn, ipmi_cmd_t cmd, { // we have reached till end of sensor, so assign the next record id // to 256(Max Sensor ID = 255) + FRU ID(may start with 0). - auto next_record_id = (frus.size()) ? - frus.begin()->first + FRU_RECORD_ID_START : - END_OF_RECORD; + auto next_record_id = + (frus.size()) ? frus.begin()->first + FRU_RECORD_ID_START + : END_OF_RECORD; get_sdr::response::set_next_record_id(next_record_id, resp); } @@ -1030,43 +1068,35 @@ ipmi_ret_t ipmi_sen_get_sdr(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return ret; } - void register_netfn_sen_functions() { // - ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_WILDCARD, - nullptr, ipmi_sen_wildcard, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_WILDCARD, nullptr, + ipmi_sen_wildcard, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_SENSOR_TYPE, - nullptr, ipmi_sen_get_sensor_type, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_SENSOR_TYPE, nullptr, + ipmi_sen_get_sensor_type, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_SET_SENSOR, - nullptr, ipmi_sen_set_sensor, - PRIVILEGE_OPERATOR); + ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_SET_SENSOR, nullptr, + ipmi_sen_set_sensor, PRIVILEGE_OPERATOR); // - ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_SENSOR_READING, - nullptr, ipmi_sen_get_sensor_reading, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_SENSOR_READING, nullptr, + ipmi_sen_get_sensor_reading, PRIVILEGE_USER); // ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_RESERVE_DEVICE_SDR_REPO, - nullptr, ipmi_sen_reserve_sdr, - PRIVILEGE_USER); + nullptr, ipmi_sen_reserve_sdr, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_DEVICE_SDR_INFO, - nullptr, ipmi_sen_get_sdr_info, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_DEVICE_SDR_INFO, nullptr, + ipmi_sen_get_sdr_info, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_DEVICE_SDR, - nullptr, ipmi_sen_get_sdr, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_DEVICE_SDR, nullptr, + ipmi_sen_get_sdr, PRIVILEGE_USER); // ipmi_register_callback(NETFUN_SENSOR, IPMI_CMD_GET_SENSOR_THRESHOLDS, diff --git a/sensorhandler.h b/sensorhandler.h index d6426f6..3f2fd99 100644 --- a/sensorhandler.h +++ b/sensorhandler.h @@ -1,19 +1,21 @@ #ifndef __HOST_IPMI_SEN_HANDLER_H__ #define __HOST_IPMI_SEN_HANDLER_H__ -#include #include "types.hpp" + +#include + #include "host-ipmid/ipmid-api.h" // IPMI commands for net functions. enum ipmi_netfn_sen_cmds { IPMI_CMD_GET_DEVICE_SDR_INFO = 0x20, - IPMI_CMD_GET_DEVICE_SDR = 0x21, - IPMI_CMD_RESERVE_DEVICE_SDR_REPO = 0x22, + IPMI_CMD_GET_DEVICE_SDR = 0x21, + IPMI_CMD_RESERVE_DEVICE_SDR_REPO = 0x22, IPMI_CMD_GET_SENSOR_READING = 0x2D, - IPMI_CMD_GET_SENSOR_TYPE = 0x2F, - IPMI_CMD_SET_SENSOR = 0x30, + IPMI_CMD_GET_SENSOR_TYPE = 0x2F, + IPMI_CMD_SET_SENSOR = 0x30, IPMI_CMD_GET_SENSOR_THRESHOLDS = 0x27, }; @@ -30,26 +32,27 @@ enum device_type // Discrete sensor types. enum ipmi_sensor_types { - IPMI_SENSOR_TEMP = 0x01, + IPMI_SENSOR_TEMP = 0x01, IPMI_SENSOR_VOLTAGE = 0x02, IPMI_SENSOR_CURRENT = 0x03, - IPMI_SENSOR_FAN = 0x04, - IPMI_SENSOR_TPM = 0xCC, + IPMI_SENSOR_FAN = 0x04, + IPMI_SENSOR_TPM = 0xCC, }; #define MAX_DBUS_PATH 128 -struct dbus_interface_t { - uint8_t sensornumber; - uint8_t sensortype; +struct dbus_interface_t +{ + uint8_t sensornumber; + uint8_t sensortype; - char bus[MAX_DBUS_PATH]; - char path[MAX_DBUS_PATH]; - char interface[MAX_DBUS_PATH]; + char bus[MAX_DBUS_PATH]; + char path[MAX_DBUS_PATH]; + char interface[MAX_DBUS_PATH]; }; -int set_sensor_dbus_state_s(uint8_t , const char *, const char *); -int set_sensor_dbus_state_y(uint8_t , const char *, const uint8_t); -int find_openbmc_path(uint8_t , dbus_interface_t *); +int set_sensor_dbus_state_s(uint8_t, const char*, const char*); +int set_sensor_dbus_state_y(uint8_t, const char*, const uint8_t); +int find_openbmc_path(uint8_t, dbus_interface_t*); ipmi_ret_t ipmi_sen_get_sdr(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, @@ -78,7 +81,7 @@ namespace request // raw value for this call. inline bool get_count(void* req) { - return (bool)((uint64_t)(req) & 1); + return (bool)((uint64_t)(req)&1); } } // namespace request @@ -229,19 +232,19 @@ inline void set_owner_id_bmc(SensorDataRecordKey* key) inline void set_owner_id_address(uint8_t addr, SensorDataRecordKey* key) { key->owner_id &= 0x01; - key->owner_id |= addr<<1; + key->owner_id |= addr << 1; }; inline void set_owner_lun(uint8_t lun, SensorDataRecordKey* key) { key->owner_lun &= ~0x03; - key->owner_lun |= (lun&0x03); + key->owner_lun |= (lun & 0x03); }; inline void set_owner_lun_channel(uint8_t channel, SensorDataRecordKey* key) { key->owner_lun &= 0x0f; - key->owner_lun |= ((channel & 0xf)<<4); + key->owner_lun |= ((channel & 0xf) << 4); }; } // namespace key @@ -252,13 +255,13 @@ inline void set_owner_lun_channel(uint8_t channel, SensorDataRecordKey* key) */ struct GetSensorThresholdsResponse { - uint8_t validMask; //!< valid mask - uint8_t lowerNonCritical; //!< lower non-critical threshold - uint8_t lowerCritical; //!< lower critical threshold - uint8_t lowerNonRecoverable;//!< lower non-recoverable threshold - uint8_t upperNonCritical; //!< upper non-critical threshold - uint8_t upperCritical; //!< upper critical threshold - uint8_t upperNonRecoverable;//!< upper non-recoverable threshold + uint8_t validMask; //!< valid mask + uint8_t lowerNonCritical; //!< lower non-critical threshold + uint8_t lowerCritical; //!< lower critical threshold + uint8_t lowerNonRecoverable; //!< lower non-recoverable threshold + uint8_t upperNonCritical; //!< upper non-critical threshold + uint8_t upperCritical; //!< upper critical threshold + uint8_t upperNonRecoverable; //!< upper non-recoverable threshold } __attribute__((packed)); // Body - full record @@ -274,8 +277,8 @@ struct SensorDataFullRecordBody uint8_t sensor_capabilities; // no macro support uint8_t sensor_type; uint8_t event_reading_type; - uint8_t supported_assertions[2]; // no macro support - uint8_t supported_deassertions[2]; // no macro support + uint8_t supported_assertions[2]; // no macro support + uint8_t supported_deassertions[2]; // no macro support uint8_t discrete_reading_setting_mask[2]; // no macro support uint8_t sensor_units_1; uint8_t sensor_units_2_base; @@ -287,7 +290,7 @@ struct SensorDataFullRecordBody uint8_t b_msb_and_accuracy_lsb; uint8_t accuracy_and_sensor_direction; uint8_t r_b_exponents; - uint8_t analog_characteristic_flags; //no macro support + uint8_t analog_characteristic_flags; // no macro support uint8_t nominal_reading; uint8_t normal_max; uint8_t normal_min; @@ -329,145 +332,137 @@ namespace body inline void set_entity_instance_number(uint8_t n, SensorDataFullRecordBody* body) { - body->entity_instance &= 1<<7; - body->entity_instance |= (n & ~(1<<7)); + body->entity_instance &= 1 << 7; + body->entity_instance |= (n & ~(1 << 7)); }; inline void set_entity_physical_entity(SensorDataFullRecordBody* body) { - body->entity_instance &= ~(1<<7); + body->entity_instance &= ~(1 << 7); }; inline void set_entity_logical_container(SensorDataFullRecordBody* body) { - body->entity_instance |= 1<<7; + body->entity_instance |= 1 << 7; }; -inline void sensor_scanning_state(bool enabled, - SensorDataFullRecordBody* body) +inline void sensor_scanning_state(bool enabled, SensorDataFullRecordBody* body) { if (enabled) { - body->sensor_initialization |= 1<<0; + body->sensor_initialization |= 1 << 0; } else { - body->sensor_initialization &= ~(1<<0); + body->sensor_initialization &= ~(1 << 0); }; }; -inline void event_generation_state(bool enabled, - SensorDataFullRecordBody* body) +inline void event_generation_state(bool enabled, SensorDataFullRecordBody* body) { if (enabled) { - body->sensor_initialization |= 1<<1; + body->sensor_initialization |= 1 << 1; } else { - body->sensor_initialization &= ~(1<<1); + body->sensor_initialization &= ~(1 << 1); } }; -inline void init_types_state(bool enabled, - SensorDataFullRecordBody* body) +inline void init_types_state(bool enabled, SensorDataFullRecordBody* body) { if (enabled) { - body->sensor_initialization |= 1<<2; + body->sensor_initialization |= 1 << 2; } else { - body->sensor_initialization &= ~(1<<2); + body->sensor_initialization &= ~(1 << 2); } }; -inline void init_hyst_state(bool enabled, - SensorDataFullRecordBody* body) +inline void init_hyst_state(bool enabled, SensorDataFullRecordBody* body) { if (enabled) { - body->sensor_initialization |= 1<<3; + body->sensor_initialization |= 1 << 3; } else { - body->sensor_initialization &= ~(1<<3); + body->sensor_initialization &= ~(1 << 3); } }; -inline void init_thresh_state(bool enabled, - SensorDataFullRecordBody* body) +inline void init_thresh_state(bool enabled, SensorDataFullRecordBody* body) { if (enabled) { - body->sensor_initialization |= 1<<4; + body->sensor_initialization |= 1 << 4; } else { - body->sensor_initialization &= ~(1<<4); + body->sensor_initialization &= ~(1 << 4); } }; -inline void init_events_state(bool enabled, - SensorDataFullRecordBody* body) +inline void init_events_state(bool enabled, SensorDataFullRecordBody* body) { if (enabled) { - body->sensor_initialization |= 1<<5; + body->sensor_initialization |= 1 << 5; } else { - body->sensor_initialization &= ~(1<<5); + body->sensor_initialization &= ~(1 << 5); } }; -inline void init_scanning_state(bool enabled, - SensorDataFullRecordBody* body) +inline void init_scanning_state(bool enabled, SensorDataFullRecordBody* body) { if (enabled) { - body->sensor_initialization |= 1<<6; + body->sensor_initialization |= 1 << 6; } else { - body->sensor_initialization &= ~(1<<6); + body->sensor_initialization &= ~(1 << 6); } }; -inline void init_settable_state(bool enabled, - SensorDataFullRecordBody* body) +inline void init_settable_state(bool enabled, SensorDataFullRecordBody* body) { if (enabled) { - body->sensor_initialization |= 1<<7; + body->sensor_initialization |= 1 << 7; } else { - body->sensor_initialization &= ~(1<<7); + body->sensor_initialization &= ~(1 << 7); } }; inline void set_percentage(SensorDataFullRecordBody* body) { - body->sensor_units_1 |= 1<<0; + body->sensor_units_1 |= 1 << 0; }; inline void unset_percentage(SensorDataFullRecordBody* body) { - body->sensor_units_1 &= ~(1<<0); + body->sensor_units_1 &= ~(1 << 0); }; inline void set_modifier_operation(uint8_t op, SensorDataFullRecordBody* body) { - body->sensor_units_1 &= ~(3<<1); - body->sensor_units_1 |= (op & 0x3)<<1; + body->sensor_units_1 &= ~(3 << 1); + body->sensor_units_1 |= (op & 0x3) << 1; }; inline void set_rate_unit(uint8_t unit, SensorDataFullRecordBody* body) { - body->sensor_units_1 &= ~(7<<3); - body->sensor_units_1 |= (unit & 0x7)<<3; + body->sensor_units_1 &= ~(7 << 3); + body->sensor_units_1 |= (unit & 0x7) << 3; }; inline void set_analog_data_format(uint8_t format, SensorDataFullRecordBody* body) { - body->sensor_units_1 &= ~(3<<6); - body->sensor_units_1 |= (format & 0x3)<<6; + body->sensor_units_1 &= ~(3 << 6); + body->sensor_units_1 |= (format & 0x3) << 6; }; inline void set_m(uint16_t m, SensorDataFullRecordBody* body) { body->m_lsb = m & 0xff; - body->m_msb_and_tolerance &= ~(3<<6); - body->m_msb_and_tolerance |= ((m & (3<<8)) >> 2); + body->m_msb_and_tolerance &= ~(3 << 6); + body->m_msb_and_tolerance |= ((m & (3 << 8)) >> 2); }; inline void set_tolerance(uint8_t tol, SensorDataFullRecordBody* body) { @@ -478,8 +473,8 @@ inline void set_tolerance(uint8_t tol, SensorDataFullRecordBody* body) inline void set_b(uint16_t b, SensorDataFullRecordBody* body) { body->b_lsb = b & 0xff; - body->b_msb_and_accuracy_lsb &= ~(3<<6); - body->b_msb_and_accuracy_lsb |= ((b & (3<<8)) >> 2); + body->b_msb_and_accuracy_lsb &= ~(3 << 6); + body->b_msb_and_accuracy_lsb |= ((b & (3 << 8)) >> 2); }; inline void set_accuracy(uint16_t acc, SensorDataFullRecordBody* body) { @@ -492,12 +487,12 @@ inline void set_accuracy(uint16_t acc, SensorDataFullRecordBody* body) }; inline void set_accuracy_exp(uint8_t exp, SensorDataFullRecordBody* body) { - body->accuracy_and_sensor_direction &= ~(3<<2); - body->accuracy_and_sensor_direction |= (exp & 3)<<2; + body->accuracy_and_sensor_direction &= ~(3 << 2); + body->accuracy_and_sensor_direction |= (exp & 3) << 2; }; inline void set_sensor_dir(uint8_t dir, SensorDataFullRecordBody* body) { - body->accuracy_and_sensor_direction &= ~(3<<0); + body->accuracy_and_sensor_direction &= ~(3 << 0); body->accuracy_and_sensor_direction |= (dir & 3); }; @@ -509,7 +504,7 @@ inline void set_b_exp(uint8_t exp, SensorDataFullRecordBody* body) inline void set_r_exp(uint8_t exp, SensorDataFullRecordBody* body) { body->r_b_exponents &= 0x0f; - body->r_b_exponents |= (exp & 0x0f)<<4; + body->r_b_exponents |= (exp & 0x0f) << 4; }; inline void set_id_strlen(uint8_t len, SensorDataFullRecordBody* body) @@ -517,14 +512,14 @@ inline void set_id_strlen(uint8_t len, SensorDataFullRecordBody* body) body->id_string_info &= ~(0x1f); body->id_string_info |= len & 0x1f; }; -inline uint8_t get_id_strlen( SensorDataFullRecordBody* body) +inline uint8_t get_id_strlen(SensorDataFullRecordBody* body) { return body->id_string_info & 0x1f; }; inline void set_id_type(uint8_t type, SensorDataFullRecordBody* body) { - body->id_string_info &= ~(3<<6); - body->id_string_info |= (type & 0x3)<<6; + body->id_string_info &= ~(3 << 6); + body->id_string_info |= (type & 0x3) << 6; }; inline void set_device_id_strlen(uint8_t len, SensorDataFruRecordBody* body) @@ -577,7 +572,7 @@ struct SensorDataFruRecord SensorDataFruRecordBody body; } __attribute__((packed)); -} // get_sdr +} // namespace get_sdr namespace ipmi { diff --git a/settings.cpp b/settings.cpp index a1ca62c..770bde0 100644 --- a/settings.cpp +++ b/settings.cpp @@ -1,9 +1,11 @@ -#include -#include -#include "xyz/openbmc_project/Common/error.hpp" #include "settings.hpp" + #include "utils.hpp" +#include +#include +#include + namespace settings { @@ -15,14 +17,12 @@ constexpr auto mapperPath = "/xyz/openbmc_project/object_mapper"; constexpr auto mapperIntf = "xyz.openbmc_project.ObjectMapper"; Objects::Objects(sdbusplus::bus::bus& bus, - const std::vector& filter): + const std::vector& filter) : bus(bus) { auto depth = 0; - auto mapperCall = bus.new_method_call(mapperService, - mapperPath, - mapperIntf, + auto mapperCall = bus.new_method_call(mapperService, mapperPath, mapperIntf, "GetSubTree"); mapperCall.append(root); mapperCall.append(depth); @@ -66,10 +66,8 @@ Objects::Objects(sdbusplus::bus::bus& bus, Service Objects::service(const Path& path, const Interface& interface) const { using Interfaces = std::vector; - auto mapperCall = bus.new_method_call(mapperService, - mapperPath, - mapperIntf, - "GetObject"); + auto mapperCall = + bus.new_method_call(mapperService, mapperPath, mapperIntf, "GetObject"); mapperCall.append(path); mapperCall.append(Interfaces({interface})); @@ -118,12 +116,9 @@ std::tuple setting(const Objects& objects, const Path& oneTimeSetting = paths[index]; const Path& regularSetting = paths[!index]; - auto method = - objects.bus.new_method_call( - objects.service(oneTimeSetting, iface).c_str(), - oneTimeSetting.c_str(), - ipmi::PROP_INTF, - "Get"); + auto method = objects.bus.new_method_call( + objects.service(oneTimeSetting, iface).c_str(), oneTimeSetting.c_str(), + ipmi::PROP_INTF, "Get"); method.append(enabledIntf, "Enabled"); auto reply = objects.bus.call(method); if (reply.is_method_error()) diff --git a/settings.hpp b/settings.hpp index 91c9930..5382fdd 100644 --- a/settings.hpp +++ b/settings.hpp @@ -1,8 +1,8 @@ #pragma once +#include #include #include -#include namespace settings { @@ -18,36 +18,36 @@ constexpr auto root = "/"; */ struct Objects { - public: - /** @brief Constructor - fetch settings objects - * - * @param[in] bus - The Dbus bus object - * @param[in] filter - A vector of settings interfaces the caller is - * interested in. - */ - Objects(sdbusplus::bus::bus& bus, const std::vector& filter); - Objects(const Objects&) = default; - Objects& operator=(const Objects&) = default; - Objects(Objects&&) = delete; - Objects& operator=(Objects&&) = delete; - ~Objects() = default; + public: + /** @brief Constructor - fetch settings objects + * + * @param[in] bus - The Dbus bus object + * @param[in] filter - A vector of settings interfaces the caller is + * interested in. + */ + Objects(sdbusplus::bus::bus& bus, const std::vector& filter); + Objects(const Objects&) = default; + Objects& operator=(const Objects&) = default; + Objects(Objects&&) = delete; + Objects& operator=(Objects&&) = delete; + ~Objects() = default; - /** @brief Fetch d-bus service, given a path and an interface. The - * service can't be cached because mapper returns unique - * service names. - * - * @param[in] path - The Dbus object - * @param[in] interface - The Dbus interface - * - * @return std::string - the dbus service - */ - Service service(const Path& path, const Interface& interface) const; + /** @brief Fetch d-bus service, given a path and an interface. The + * service can't be cached because mapper returns unique + * service names. + * + * @param[in] path - The Dbus object + * @param[in] interface - The Dbus interface + * + * @return std::string - the dbus service + */ + Service service(const Path& path, const Interface& interface) const; - /** @brief map of settings objects */ - std::map> map; + /** @brief map of settings objects */ + std::map> map; - /** @brief The Dbus bus object */ - sdbusplus::bus::bus& bus; + /** @brief The Dbus bus object */ + sdbusplus::bus::bus& bus; }; namespace boot diff --git a/softoff/mainapp.cpp b/softoff/mainapp.cpp index 3a47cc4..3b153a8 100644 --- a/softoff/mainapp.cpp +++ b/softoff/mainapp.cpp @@ -13,13 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "config.h" + +#include "softoff.hpp" +#include "timer.hpp" + #include -#include + #include +#include #include -#include "softoff.hpp" -#include "config.h" -#include "timer.hpp" // Return -1 on any errors to ensure we follow the calling targets OnFailure= // path @@ -41,7 +44,7 @@ int main(int argc, char** argv) if (r < 0) { log("Failure to create sd_event handler", - entry("ERRNO=0x%X", -r)); + entry("ERRNO=0x%X", -r)); return -1; } @@ -58,22 +61,23 @@ int main(int argc, char** argv) // Wait for client requests until this application has processed // at least one successful SoftPowerOff or we timed out - while(!powerObj.isCompleted() && !powerObj.isTimerExpired()) + while (!powerObj.isCompleted() && !powerObj.isTimerExpired()) { // -1 denotes wait for ever r = sd_event_run(events, (uint64_t)-1); if (r < 0) { log("Failure in processing request", - entry("ERRNO=0x%X", -r)); + entry("ERRNO=0x%X", -r)); return -1; } } // Log an error if we timed out after getting Ack for SMS_ATN and before // getting the Host Shutdown response - if(powerObj.isTimerExpired() && (powerObj.responseReceived() == - phosphor::ipmi::Base::SoftPowerOff::HostResponse::SoftOffReceived)) + if (powerObj.isTimerExpired() && + (powerObj.responseReceived() == + phosphor::ipmi::Base::SoftPowerOff::HostResponse::SoftOffReceived)) { using error = sdbusplus::xyz::openbmc_project::State::Host::Error::SoftOffTimeout; diff --git a/softoff/softoff.cpp b/softoff/softoff.cpp index d76750a..921536f 100644 --- a/softoff/softoff.cpp +++ b/softoff/softoff.cpp @@ -13,12 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "config.h" + +#include "softoff.hpp" + #include #include -#include #include -#include "softoff.hpp" -#include "config.h" +#include namespace phosphor { namespace ipmi @@ -29,16 +31,13 @@ using namespace sdbusplus::xyz::openbmc_project::Control::server; void SoftPowerOff::sendHostShutDownCmd() { - auto ctrlHostPath = std::string{CONTROL_HOST_OBJ_MGR} + '/' + - HOST_NAME + '0'; - auto host = ::ipmi::getService(this->bus, - CONTROL_HOST_BUSNAME, + auto ctrlHostPath = + std::string{CONTROL_HOST_OBJ_MGR} + '/' + HOST_NAME + '0'; + auto host = ::ipmi::getService(this->bus, CONTROL_HOST_BUSNAME, ctrlHostPath.c_str()); - auto method = bus.new_method_call(host.c_str(), - ctrlHostPath.c_str(), - CONTROL_HOST_BUSNAME, - "Execute"); + auto method = bus.new_method_call(host.c_str(), ctrlHostPath.c_str(), + CONTROL_HOST_BUSNAME, "Execute"); method.append(convertForMessage(Host::Command::SoftOff).c_str()); @@ -53,7 +52,6 @@ void SoftPowerOff::sendHostShutDownCmd() return; } - // Function called on host control signals void SoftPowerOff::hostControlEvent(sdbusplus::message::message& msg) { @@ -63,32 +61,33 @@ void SoftPowerOff::hostControlEvent(sdbusplus::message::message& msg) msg.read(cmdCompleted, cmdStatus); log("Host control signal values", - entry("COMMAND=%s",cmdCompleted.c_str()), - entry("STATUS=%s",cmdStatus.c_str())); + entry("COMMAND=%s", cmdCompleted.c_str()), + entry("STATUS=%s", cmdStatus.c_str())); - if(Host::convertResultFromString(cmdStatus) == Host::Result::Success) + if (Host::convertResultFromString(cmdStatus) == Host::Result::Success) { // Set our internal property indicating we got host attention - sdbusplus::xyz::openbmc_project::Ipmi::Internal - ::server::SoftPowerOff::responseReceived( - HostResponse::SoftOffReceived); + sdbusplus::xyz::openbmc_project::Ipmi::Internal ::server::SoftPowerOff:: + responseReceived(HostResponse::SoftOffReceived); // Start timer for host shutdown using namespace std::chrono; auto time = duration_cast( - seconds(IPMI_HOST_SHUTDOWN_COMPLETE_TIMEOUT_SECS)); + seconds(IPMI_HOST_SHUTDOWN_COMPLETE_TIMEOUT_SECS)); auto r = startTimer(time); if (r < 0) { log("Failure to start Host shutdown wait timer", - entry("ERRNO=0x%X", -r)); + entry("ERRNO=0x%X", -r)); } else { - log("Timer started waiting for host to shutdown", + log( + "Timer started waiting for host to shutdown", entry("TIMEOUT_IN_MSEC=%llu", - (duration_cast(seconds - (IPMI_HOST_SHUTDOWN_COMPLETE_TIMEOUT_SECS))).count())); + (duration_cast( + seconds(IPMI_HOST_SHUTDOWN_COMPLETE_TIMEOUT_SECS))) + .count())); } } else @@ -120,15 +119,15 @@ auto SoftPowerOff::responseReceived(HostResponse response) -> HostResponse if (r < 0) { log("Failure to STOP the timer", - entry("ERRNO=0x%X", -r)); + entry("ERRNO=0x%X", -r)); } // This marks the completion of soft power off sequence. completed = true; } - return sdbusplus::xyz::openbmc_project::Ipmi::Internal - ::server::SoftPowerOff::responseReceived(response); + return sdbusplus::xyz::openbmc_project::Ipmi::Internal ::server:: + SoftPowerOff::responseReceived(response); } } // namespace ipmi diff --git a/softoff/softoff.hpp b/softoff/softoff.hpp index 43bc303..b7555e3 100644 --- a/softoff/softoff.hpp +++ b/softoff/softoff.hpp @@ -1,12 +1,14 @@ #pragma once +#include "config.h" + +#include "timer.hpp" + +#include #include #include -#include #include #include -#include "timer.hpp" -#include "config.h" namespace phosphor { namespace ipmi @@ -20,126 +22,121 @@ namespace sdbusRule = sdbusplus::bus::match::rules; /** @class SoftPowerOff * @brief Responsible for coordinating Host SoftPowerOff operation */ -class SoftPowerOff : public sdbusplus::server::object::object< - Base::SoftPowerOff> +class SoftPowerOff + : public sdbusplus::server::object::object { - public: - /** @brief Constructs SoftPowerOff object. - * - * @param[in] bus - system dbus handler - * @param[in] event - sd_event handler - * @param[in] objPath - The Dbus path hosting SoftPowerOff function - */ - SoftPowerOff(sdbusplus::bus::bus& bus, - sd_event* event, - const char* objPath) : - sdbusplus::server::object::object< - Base::SoftPowerOff>(bus, objPath, false), - bus(bus), - timer(event), - hostControlSignal( - bus, - sdbusRule::type::signal() + - sdbusRule::member("CommandComplete") + - sdbusRule::path("/xyz/openbmc_project/control/host0") + - sdbusRule::interface(CONTROL_HOST_BUSNAME) + - sdbusRule::argN(0,convertForMessage( - Host::Command::SoftOff)), - std::bind(std::mem_fn(&SoftPowerOff::hostControlEvent), - this, std::placeholders::_1)) - { - // Need to announce since we may get the response - // very quickly on host shutdown command - emit_object_added(); - - // The whole purpose of this application is to send a host shutdown - // command and watch for the soft power off to go through. We need - // the interface added signal emitted before we send the shutdown - // command just to attend to lightning fast response from host - sendHostShutDownCmd(); - } - - /** @brief Tells if the objective of this application is completed */ - inline auto isCompleted() - { - return completed; - } - - /** @brief Tells if the referenced timer is expired or not */ - inline auto isTimerExpired() - { - return timer.isExpired(); - } - - /** @brief overloaded property setter function - * - * @param[in] value - One of SoftOffReceived / HostShutdown - * - * @return Success or exception thrown - */ - HostResponse responseReceived(HostResponse value) override; - - /** @brief Using the base class's getter method */ - using Base::SoftPowerOff::responseReceived; - - /** @brief Calls to start a timer - * - * @param[in] usec - Time in microseconds - * - * @return Success or exception thrown - */ - int startTimer(const std::chrono::microseconds& usec); - - private: - // Need this to send SMS_ATTN - // TODO : Switch over to using mapper service in a different patch - static constexpr auto HOST_IPMI_BUS = "org.openbmc.HostIpmi"; - static constexpr auto HOST_IPMI_OBJ = "/org/openbmc/HostIpmi/1"; - static constexpr auto HOST_IPMI_INTF = "org.openbmc.HostIpmi"; - - /* @brief sdbusplus handle */ - sdbusplus::bus::bus& bus; - - /** @brief Reference to Timer object */ - Timer timer; - - /** @brief Marks the end of life of this application. - * - * This is set to true if host gives appropriate responses - * for the sequence of commands. - */ - bool completed = false; - - /** @brief Subscribe to host control signals - * - * Protocol is to send the host power off request to the host - * control interface and then wait for a signal indicating pass/fail - **/ - sdbusplus::bus::match_t hostControlSignal; - - /** @brief Sends host control command to tell host to shut down - * - * After sending the command, wait for a signal indicating the status - * of the command. - * - * After receiving the initial response, start a timer for 30 minutes - * to let host do a clean shutdown of partitions. When the response is - * received from the host, it indicates that BMC can do a power off. - * If BMC fails to get any response, then a hard power off would - * be forced. - * - * @return - Does not return anything. Error will result in exception - * being thrown - */ - void sendHostShutDownCmd(); - - /** @brief Callback function on host control signals - * - * @param[in] msg - Data associated with subscribed signal - * - */ - void hostControlEvent(sdbusplus::message::message& msg); - + public: + /** @brief Constructs SoftPowerOff object. + * + * @param[in] bus - system dbus handler + * @param[in] event - sd_event handler + * @param[in] objPath - The Dbus path hosting SoftPowerOff function + */ + SoftPowerOff(sdbusplus::bus::bus& bus, sd_event* event, + const char* objPath) : + sdbusplus::server::object::object(bus, objPath, + false), + bus(bus), timer(event), + hostControlSignal( + bus, + sdbusRule::type::signal() + sdbusRule::member("CommandComplete") + + sdbusRule::path("/xyz/openbmc_project/control/host0") + + sdbusRule::interface(CONTROL_HOST_BUSNAME) + + sdbusRule::argN(0, convertForMessage(Host::Command::SoftOff)), + std::bind(std::mem_fn(&SoftPowerOff::hostControlEvent), this, + std::placeholders::_1)) + { + // Need to announce since we may get the response + // very quickly on host shutdown command + emit_object_added(); + + // The whole purpose of this application is to send a host shutdown + // command and watch for the soft power off to go through. We need + // the interface added signal emitted before we send the shutdown + // command just to attend to lightning fast response from host + sendHostShutDownCmd(); + } + + /** @brief Tells if the objective of this application is completed */ + inline auto isCompleted() + { + return completed; + } + + /** @brief Tells if the referenced timer is expired or not */ + inline auto isTimerExpired() + { + return timer.isExpired(); + } + + /** @brief overloaded property setter function + * + * @param[in] value - One of SoftOffReceived / HostShutdown + * + * @return Success or exception thrown + */ + HostResponse responseReceived(HostResponse value) override; + + /** @brief Using the base class's getter method */ + using Base::SoftPowerOff::responseReceived; + + /** @brief Calls to start a timer + * + * @param[in] usec - Time in microseconds + * + * @return Success or exception thrown + */ + int startTimer(const std::chrono::microseconds& usec); + + private: + // Need this to send SMS_ATTN + // TODO : Switch over to using mapper service in a different patch + static constexpr auto HOST_IPMI_BUS = "org.openbmc.HostIpmi"; + static constexpr auto HOST_IPMI_OBJ = "/org/openbmc/HostIpmi/1"; + static constexpr auto HOST_IPMI_INTF = "org.openbmc.HostIpmi"; + + /* @brief sdbusplus handle */ + sdbusplus::bus::bus& bus; + + /** @brief Reference to Timer object */ + Timer timer; + + /** @brief Marks the end of life of this application. + * + * This is set to true if host gives appropriate responses + * for the sequence of commands. + */ + bool completed = false; + + /** @brief Subscribe to host control signals + * + * Protocol is to send the host power off request to the host + * control interface and then wait for a signal indicating pass/fail + **/ + sdbusplus::bus::match_t hostControlSignal; + + /** @brief Sends host control command to tell host to shut down + * + * After sending the command, wait for a signal indicating the status + * of the command. + * + * After receiving the initial response, start a timer for 30 minutes + * to let host do a clean shutdown of partitions. When the response is + * received from the host, it indicates that BMC can do a power off. + * If BMC fails to get any response, then a hard power off would + * be forced. + * + * @return - Does not return anything. Error will result in exception + * being thrown + */ + void sendHostShutDownCmd(); + + /** @brief Callback function on host control signals + * + * @param[in] msg - Data associated with subscribed signal + * + */ + void hostControlEvent(sdbusplus::message::message& msg); }; } // namespace ipmi } // namespace phosphor diff --git a/softoff/test/utest.cpp b/softoff/test/utest.cpp index baaead4..0dd99ae 100644 --- a/softoff/test/utest.cpp +++ b/softoff/test/utest.cpp @@ -1,85 +1,83 @@ -#include +#include "timer.hpp" + #include +#include + #include -#include "timer.hpp" using namespace phosphor::ipmi; class TimerTest : public ::testing::Test { - public: - // systemd event handler - sd_event* events; + public: + // systemd event handler + sd_event* events; - // Need this so that events can be initialized. - int rc; + // Need this so that events can be initialized. + int rc; - // Source of event - sd_event_source* eventSource = nullptr; + // Source of event + sd_event_source* eventSource = nullptr; - // Add a Timer Object - Timer timer; + // Add a Timer Object + Timer timer; - // Gets called as part of each TEST_F construction - TimerTest() - : rc(sd_event_default(&events)), - timer(events) - { - // Check for successful creation of - // event handler and timer object. - EXPECT_GE(rc, 0); - } + // Gets called as part of each TEST_F construction + TimerTest() : rc(sd_event_default(&events)), timer(events) + { + // Check for successful creation of + // event handler and timer object. + EXPECT_GE(rc, 0); + } - // Gets called as part of each TEST_F destruction - ~TimerTest() - { - events = sd_event_unref(events); - } + // Gets called as part of each TEST_F destruction + ~TimerTest() + { + events = sd_event_unref(events); + } }; - class TimerTestCallBack : public ::testing::Test { - public: - // systemd event handler - sd_event* events; + public: + // systemd event handler + sd_event* events; - // Need this so that events can be initialized. - int rc; + // Need this so that events can be initialized. + int rc; - // Source of event - sd_event_source* eventSource = nullptr; + // Source of event + sd_event_source* eventSource = nullptr; - // Add a Timer Object - std::unique_ptr timer = nullptr; + // Add a Timer Object + std::unique_ptr timer = nullptr; - // Indicates optional call back fun was called - bool callBackDone = false; + // Indicates optional call back fun was called + bool callBackDone = false; - void callBack() - { - callBackDone = true; - } + void callBack() + { + callBackDone = true; + } - // Gets called as part of each TEST_F construction - TimerTestCallBack() - : rc(sd_event_default(&events)) + // Gets called as part of each TEST_F construction + TimerTestCallBack() : rc(sd_event_default(&events)) - { - // Check for successful creation of - // event handler and timer object. - EXPECT_GE(rc, 0); + { + // Check for successful creation of + // event handler and timer object. + EXPECT_GE(rc, 0); - std::function func(std::bind( - &TimerTestCallBack::callBack, this)); - timer = std::make_unique(events, func); - } + std::function func( + std::bind(&TimerTestCallBack::callBack, this)); + timer = std::make_unique(events, func); + } - // Gets called as part of each TEST_F destruction - ~TimerTestCallBack() - { - events = sd_event_unref(events); - } + // Gets called as part of each TEST_F destruction + ~TimerTestCallBack() + { + events = sd_event_unref(events); + } }; /** @brief Makes sure that timer is expired and the @@ -95,11 +93,11 @@ TEST_F(TimerTest, timerExpiresAfter2seconds) // Waiting 2 seconds is enough here since we have // already spent some usec now int count = 0; - while(count < 2 && !timer.isExpired()) + while (count < 2 && !timer.isExpired()) { // Returns -0- on timeout and positive number on dispatch auto sleepTime = duration_cast(seconds(1)); - if(!sd_event_run(events, sleepTime.count())) + if (!sd_event_run(events, sleepTime.count())) { count++; } @@ -123,11 +121,11 @@ TEST_F(TimerTest, timerNotExpiredAfter2Seconds) // Wait 2 seconds and see that timer is not expired int count = 0; - while(count < 2) + while (count < 2) { // Returns -0- on timeout auto sleepTime = duration_cast(seconds(1)); - if(!sd_event_run(events, sleepTime.count())) + if (!sd_event_run(events, sleepTime.count())) { count++; } @@ -157,11 +155,11 @@ TEST_F(TimerTest, updateTimerAndExpectExpire) // Wait 3 seconds and see that timer is expired int count = 0; - while(count < 3 && !timer.isExpired()) + while (count < 3 && !timer.isExpired()) { // Returns -0- on timeout auto sleepTime = duration_cast(seconds(1)); - if(!sd_event_run(events, sleepTime.count())) + if (!sd_event_run(events, sleepTime.count())) { count++; } @@ -193,11 +191,11 @@ TEST_F(TimerTest, updateTimerAndNeverExpire) // Wait 2 seconds and see that timer is expired int count = 0; - while(count < 2) + while (count < 2) { // Returns -0- on timeout auto sleepTime = duration_cast(seconds(1)); - if(!sd_event_run(events, sleepTime.count())) + if (!sd_event_run(events, sleepTime.count())) { count++; } @@ -219,11 +217,11 @@ TEST_F(TimerTestCallBack, optionalFuncCallBackDone) // Waiting 2 seconds is enough here since we have // already spent some usec now int count = 0; - while(count < 2 && !timer->isExpired()) + while (count < 2 && !timer->isExpired()) { // Returns -0- on timeout and positive number on dispatch auto sleepTime = duration_cast(seconds(1)); - if(!sd_event_run(events, sleepTime.count())) + if (!sd_event_run(events, sleepTime.count())) { count++; } @@ -248,11 +246,11 @@ TEST_F(TimerTestCallBack, timerNotExpiredAfter2SecondsNoOptionalCallBack) // Wait 2 seconds and see that timer is not expired int count = 0; - while(count < 2) + while (count < 2) { // Returns -0- on timeout auto sleepTime = duration_cast(seconds(1)); - if(!sd_event_run(events, sleepTime.count())) + if (!sd_event_run(events, sleepTime.count())) { count++; } diff --git a/storageaddsel.cpp b/storageaddsel.cpp index ec33b1a..95fcddf 100644 --- a/storageaddsel.cpp +++ b/storageaddsel.cpp @@ -1,22 +1,24 @@ +#include "elog-errors.hpp" +#include "error-HostEvent.hpp" +#include "types.hpp" + +#include #include +#include + +#include #include #include #include #include -#include -#include #include -#include -#include #include +#include +#include + #include "host-ipmid/ipmid-api.h" -#include "elog-errors.hpp" -#include "error-HostEvent.hpp" #include "sensorhandler.h" #include "storagehandler.h" -#include "types.hpp" -#include "xyz/openbmc_project/Logging/Entry/server.hpp" - using namespace std; using namespace phosphor::logging; @@ -24,7 +26,8 @@ using namespace sdbusplus::xyz::openbmc_project::Logging::server; extern const ipmi::sensor::InvObjectIDMap invSensors; ////////////////////////// -struct esel_section_headers_t { +struct esel_section_headers_t +{ uint8_t sectionid[2]; uint8_t sectionlength[2]; uint8_t version; @@ -32,118 +35,128 @@ struct esel_section_headers_t { uint8_t compid; }; -struct severity_values_t { +struct severity_values_t +{ uint8_t type; Entry::Level level; }; - const std::vector g_sev_desc = { {0x10, Entry::Level::Warning}, // recoverable error {0x20, Entry::Level::Warning}, // predictive error - // TODO via github issue 3066 : map level below to Level::Unrecoverable - {0x40, Entry::Level::Error}, // unrecoverable error - // TODO via github issue 3066 : map level below to Level::Critical - {0x50, Entry::Level::Error}, // critical error - {0x60, Entry::Level::Error}, // error from a diagnostic test + // TODO via github issue 3066 : map level + // below to Level::Unrecoverable + {0x40, Entry::Level::Error}, // unrecoverable error + // TODO via github issue 3066 : map level below + // to Level::Critical + {0x50, Entry::Level::Error}, // critical error + {0x60, Entry::Level::Error}, // error from a diagnostic test {0x70, Entry::Level::Warning}, // recoverable symptom - {0xFF, Entry::Level::Error}, //unknown error + {0xFF, Entry::Level::Error}, // unknown error }; -Entry::Level sev_lookup(uint8_t n) { - auto i = std::find_if(std::begin(g_sev_desc), std::end(g_sev_desc), - [n](auto p){ return p.type == n || p.type == 0xFF; }); +Entry::Level sev_lookup(uint8_t n) +{ + auto i = + std::find_if(std::begin(g_sev_desc), std::end(g_sev_desc), + [n](auto p) { return p.type == n || p.type == 0xFF; }); return i->level; } - - - -int find_sensor_type_string(uint8_t sensor_number, char **s) { +int find_sensor_type_string(uint8_t sensor_number, char** s) +{ dbus_interface_t a; - const char *p; + const char* p; int r; r = find_openbmc_path(sensor_number, &a); - if ((r < 0) || (a.bus[0] == 0)) { + if ((r < 0) || (a.bus[0] == 0)) + { // Just make a generic message for errors that // occur on sensors that don't exist r = asprintf(s, "Unknown Sensor (0x%02x)", sensor_number); - } else { + } + else + { - if ((p = strrchr (a.path, '/')) == NULL) { + if ((p = strrchr(a.path, '/')) == NULL) + { p = "/Unknown Sensor"; } - *s = strdup(p+1); + *s = strdup(p + 1); } return 0; } +size_t getfilestream(const char* fn, uint8_t** buffer) +{ -size_t getfilestream(const char *fn, uint8_t **buffer) { - - FILE *fp; + FILE* fp; ssize_t size = 0; int r; - if ((fp = fopen(fn, "rb")) != NULL) { + if ((fp = fopen(fn, "rb")) != NULL) + { r = fseek(fp, 0, SEEK_END); - if (r) { + if (r) + { log("Fseek failed"); goto fclose_fp; } size = ftell(fp); - if (size == -1L) { - log("Ftell failed", - entry("ERROR=%s", strerror(errno))); + if (size == -1L) + { + log("Ftell failed", entry("ERROR=%s", strerror(errno))); size = 0; goto fclose_fp; } r = fseek(fp, 0, SEEK_SET); - if (r) { + if (r) + { log("Fseek failed"); size = 0; goto fclose_fp; } - *buffer = new uint8_t [size]; + *buffer = new uint8_t[size]; r = fread(*buffer, 1, size, fp); - if ( r != size) { + if (r != size) + { size = 0; log("Fread failed\n"); } -fclose_fp: + fclose_fp: fclose(fp); } return static_cast(size); } - -Entry::Level create_esel_severity(const uint8_t *buffer) { +Entry::Level create_esel_severity(const uint8_t* buffer) +{ uint8_t severity; // Dive in to the IBM log to find the severity - severity = (0xF0 & buffer[0x4A]); + severity = (0xF0 & buffer[0x4A]); return sev_lookup(severity); } -int create_esel_association(const uint8_t *buffer, std::string& inventoryPath) +int create_esel_association(const uint8_t* buffer, std::string& inventoryPath) { - ipmi_add_sel_request_t *p; + ipmi_add_sel_request_t* p; uint8_t sensor; - p = ( ipmi_add_sel_request_t *) buffer; + p = (ipmi_add_sel_request_t*)buffer; sensor = p->sensornumber; @@ -153,7 +166,7 @@ int create_esel_association(const uint8_t *buffer, std::string& inventoryPath) * Search the sensor number to inventory path mapping to figure out the * inventory associated with the ESEL. */ - for (auto const &iter : invSensors) + for (auto const& iter : invSensors) { if (iter.second.sensorID == sensor) { @@ -165,23 +178,22 @@ int create_esel_association(const uint8_t *buffer, std::string& inventoryPath) return 0; } +int create_esel_description(const uint8_t* buffer, Entry::Level level, + char** message) +{ - -int create_esel_description(const uint8_t *buffer, Entry::Level level, - char **message) { - - - ipmi_add_sel_request_t *p; - char *m; + ipmi_add_sel_request_t* p; + char* m; int r; - p = ( ipmi_add_sel_request_t *) buffer; + p = (ipmi_add_sel_request_t*)buffer; - find_sensor_type_string(p->sensornumber,&m); + find_sensor_type_string(p->sensornumber, &m); - r = asprintf(message, "A %s has experienced an error of level %d", - m, static_cast(level) ); - if (r == -1) { + r = asprintf(message, "A %s has experienced an error of level %d", m, + static_cast(level)); + if (r == -1) + { log("Failed to allocate memory for ESEL description"); } @@ -190,45 +202,42 @@ int create_esel_description(const uint8_t *buffer, Entry::Level level, return 0; } - -int send_esel_to_dbus(const char *desc, - Entry::Level level, - const std::string& inventoryPath, - uint8_t *debug, +int send_esel_to_dbus(const char* desc, Entry::Level level, + const std::string& inventoryPath, uint8_t* debug, size_t debuglen) { // Allocate enough space to represent the data in hex separated by spaces, // to mimic how IPMI would display the data. - unique_ptr selData(new char[(debuglen*3) + 1]()); + unique_ptr selData(new char[(debuglen * 3) + 1]()); uint32_t i = 0; - for(i = 0; i < debuglen; i++) + for (i = 0; i < debuglen; i++) { - sprintf(&selData[i*3], "%02x ", 0xFF & ((char*)debug)[i]); + sprintf(&selData[i * 3], "%02x ", 0xFF & ((char*)debug)[i]); } - selData[debuglen*3] = '\0'; + selData[debuglen * 3] = '\0'; - using error = sdbusplus::org::open_power::Host::Error::Event; + using error = sdbusplus::org::open_power::Host::Error::Event; using metadata = org::open_power::Host::Event; - report(level, - metadata::ESEL(selData.get()), + report(level, metadata::ESEL(selData.get()), metadata::CALLOUT_INVENTORY_PATH(inventoryPath.c_str())); return 0; } - -void send_esel(uint16_t recordid) { - char *desc; - uint8_t *buffer = NULL; - const char *path = "/tmp/esel"; +void send_esel(uint16_t recordid) +{ + char* desc; + uint8_t* buffer = NULL; + const char* path = "/tmp/esel"; ssize_t sz; int r; std::string inventoryPath; sz = getfilestream(path, &buffer); - if (sz == 0) { + if (sz == 0) + { log("Error file does not exist", entry("FILENAME=%s", path)); return; @@ -239,7 +248,8 @@ void send_esel(uint16_t recordid) { create_esel_description(buffer, sev, &desc); r = send_esel_to_dbus(desc, sev, inventoryPath, buffer, sz); - if (r < 0) { + if (r < 0) + { log("Failed to send esel to dbus"); } @@ -278,8 +288,8 @@ void createProcedureLogEntry(uint8_t procedureNum) // Each byte in eSEL is formatted as %02x with a space between bytes and // insert '/0' at the end of the character array. static constexpr auto byteSeparator = 3; - std::unique_ptr data(new char[ - (eSELData.size() * byteSeparator) + 1]()); + std::unique_ptr data( + new char[(eSELData.size() * byteSeparator) + 1]()); for (size_t i = 0; i < eSELData.size(); i++) { @@ -287,7 +297,7 @@ void createProcedureLogEntry(uint8_t procedureNum) } data[eSELData.size() * byteSeparator] = '\0'; - using error = sdbusplus::org::open_power::Host::Error::MaintenanceProcedure; + using error = sdbusplus::org::open_power::Host::Error::MaintenanceProcedure; using metadata = org::open_power::Host::MaintenanceProcedure; report(metadata::ESEL(data.get()), diff --git a/storageaddsel.h b/storageaddsel.h index 5cb826e..113254b 100644 --- a/storageaddsel.h +++ b/storageaddsel.h @@ -1,6 +1,6 @@ #include -void send_esel(uint16_t recordid) ; +void send_esel(uint16_t recordid); /** @brief Read eSEL data into a string * diff --git a/storagehandler.cpp b/storagehandler.cpp index f0997e8..72a0c08 100644 --- a/storagehandler.cpp +++ b/storagehandler.cpp @@ -1,49 +1,52 @@ -#include #include + +#include #include #include #if __has_include() #include #elif __has_include() #include -namespace std { - // splice experimental::filesystem into std - namespace filesystem = std::experimental::filesystem; -} +namespace std +{ +// splice experimental::filesystem into std +namespace filesystem = std::experimental::filesystem; +} // namespace std #else -# error filesystem not available +#error filesystem not available #endif +#include "fruread.hpp" +#include "read_fru_data.hpp" +#include "selutility.hpp" +#include "utils.hpp" + #include -#include #include -#include #include +#include #include +#include +#include -#include "fruread.hpp" #include "host-ipmid/ipmid-api.h" -#include "read_fru_data.hpp" -#include "selutility.hpp" +#include "sensorhandler.h" #include "storageaddsel.h" #include "storagehandler.h" -#include "utils.hpp" -#include "xyz/openbmc_project/Common/error.hpp" -#include "sensorhandler.h" - void register_netfn_storage_functions() __attribute__((constructor)); -unsigned int g_sel_time = 0xFFFFFFFF; +unsigned int g_sel_time = 0xFFFFFFFF; extern unsigned short g_sel_reserve; extern const ipmi::sensor::IdInfoMap sensors; extern const FruMap frus; -namespace { +namespace +{ constexpr auto TIME_INTERFACE = "xyz.openbmc_project.Time.EpochTime"; constexpr auto HOST_TIME_PATH = "/xyz/openbmc_project/time/host"; constexpr auto DBUS_PROPERTIES = "org.freedesktop.DBus.Properties"; -constexpr auto PROPERTY_ELAPSED= "Elapsed"; +constexpr auto PROPERTY_ELAPSED = "Elapsed"; const char* getTimeString(const uint64_t& usecSinceEpoch) { @@ -52,26 +55,26 @@ const char* getTimeString(const uint64_t& usecSinceEpoch) auto t = system_clock::to_time_t(tp); return std::ctime(&t); } -} +} // namespace namespace cache { - /* - * This cache contains the object paths of the logging entries sorted in the - * order of the filename(numeric order). The cache is initialized by - * invoking readLoggingObjectPaths with the cache as the parameter. The - * cache is invoked in the execution of the Get SEL info and Delete SEL - * entry command. The Get SEL Info command is typically invoked before the - * Get SEL entry command, so the cache is utilized for responding to Get SEL - * entry command. The cache is invalidated by clearing after Delete SEL - * entry and Clear SEL command. - */ - ipmi::sel::ObjectPaths paths; +/* + * This cache contains the object paths of the logging entries sorted in the + * order of the filename(numeric order). The cache is initialized by + * invoking readLoggingObjectPaths with the cache as the parameter. The + * cache is invoked in the execution of the Get SEL info and Delete SEL + * entry command. The Get SEL Info command is typically invoked before the + * Get SEL entry command, so the cache is utilized for responding to Get SEL + * entry command. The cache is invalidated by clearing after Delete SEL + * entry and Clear SEL command. + */ +ipmi::sel::ObjectPaths paths; -} // namespace objectPathsCache +} // namespace cache using InternalFailure = - sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; + sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; using namespace phosphor::logging; using namespace ipmi::fru; @@ -84,10 +87,11 @@ enum class AccessMode words ///< Device is accessed by words }; - ipmi_ret_t ipmi_storage_wildcard(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { // Status code. ipmi_ret_t rc = IPMI_CC_INVALID; @@ -100,8 +104,8 @@ ipmi_ret_t getSELInfo(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_data_len_t data_len, ipmi_context_t context) { std::vector outPayload(sizeof(ipmi::sel::GetSELInfoResponse)); - auto responseData = reinterpret_cast - (outPayload.data()); + auto responseData = + reinterpret_cast(outPayload.data()); responseData->selVersion = ipmi::sel::selVersion; // Last erase timestamp is not available from log manager. @@ -119,8 +123,7 @@ ipmi_ret_t getSELInfo(ipmi_netfn_t netfn, ipmi_cmd_t cmd, try { responseData->addTimeStamp = static_cast( - (ipmi::sel::getEntryTimeStamp(cache::paths.back()) - .count())); + (ipmi::sel::getEntryTimeStamp(cache::paths.back()).count())); } catch (InternalFailure& e) { @@ -141,8 +144,8 @@ ipmi_ret_t getSELEntry(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { - auto requestData = reinterpret_cast - (request); + auto requestData = + reinterpret_cast(request); if (requestData->reservationID != 0) { @@ -183,7 +186,7 @@ ipmi_ret_t getSELEntry(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } } - ipmi::sel::GetSELEntryResponse record {}; + ipmi::sel::GetSELEntryResponse record{}; // Convert the log entry into SEL record. try @@ -202,9 +205,8 @@ ipmi_ret_t getSELEntry(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return IPMI_CC_UNSPECIFIED_ERROR; } - // Identify the next SEL record ID - if(iter != cache::paths.end()) + if (iter != cache::paths.end()) { ++iter; if (iter == cache::paths.end()) @@ -215,8 +217,8 @@ ipmi_ret_t getSELEntry(ipmi_netfn_t netfn, ipmi_cmd_t cmd, { namespace fs = std::filesystem; fs::path path(*iter); - record.nextRecordID = static_cast - (std::stoul(std::string(path.filename().c_str()))); + record.nextRecordID = static_cast( + std::stoul(std::string(path.filename().c_str()))); } } else @@ -239,8 +241,8 @@ ipmi_ret_t getSELEntry(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } auto diff = ipmi::sel::selRecordSize - requestData->offset; - auto readLength = std::min(diff, - static_cast(requestData->readLength)); + auto readLength = + std::min(diff, static_cast(requestData->readLength)); memcpy(response, &record.nextRecordID, sizeof(record.nextRecordID)); memcpy(static_cast(response) + sizeof(record.nextRecordID), @@ -256,8 +258,8 @@ ipmi_ret_t deleteSELEntry(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_data_len_t data_len, ipmi_context_t context) { namespace fs = std::experimental::filesystem; - auto requestData = reinterpret_cast - (request); + auto requestData = + reinterpret_cast(request); if (g_sel_reserve != requestData->reservationID) { @@ -280,15 +282,15 @@ ipmi_ret_t deleteSELEntry(ipmi_netfn_t netfn, ipmi_cmd_t cmd, { iter = cache::paths.begin(); fs::path path(*iter); - delRecordID = static_cast - (std::stoul(std::string(path.filename().c_str()))); + delRecordID = static_cast( + std::stoul(std::string(path.filename().c_str()))); } else if (requestData->selRecordID == ipmi::sel::lastEntry) { iter = cache::paths.end(); fs::path path(*iter); - delRecordID = static_cast - (std::stoul(std::string(path.filename().c_str()))); + delRecordID = static_cast( + std::stoul(std::string(path.filename().c_str()))); } else { @@ -318,10 +320,8 @@ ipmi_ret_t deleteSELEntry(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return IPMI_CC_UNSPECIFIED_ERROR; } - auto methodCall = bus.new_method_call(service.c_str(), - (*iter).c_str(), - ipmi::sel::logDeleteIntf, - "Delete"); + auto methodCall = bus.new_method_call(service.c_str(), (*iter).c_str(), + ipmi::sel::logDeleteIntf, "Delete"); auto reply = bus.call(methodCall); if (reply.is_method_error()) { @@ -341,8 +341,8 @@ ipmi_ret_t clearSEL(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { - auto requestData = reinterpret_cast - (request); + auto requestData = + reinterpret_cast(request); if (g_sel_reserve != requestData->reservationID) { @@ -350,8 +350,7 @@ ipmi_ret_t clearSEL(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, return IPMI_CC_INVALID_RESERVATION_ID; } - if (requestData->charC != 'C' || - requestData->charL != 'L' || + if (requestData->charC != 'C' || requestData->charL != 'L' || requestData->charR != 'R') { *data_len = 0; @@ -374,10 +373,9 @@ ipmi_ret_t clearSEL(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; auto depth = 0; - auto mapperCall = bus.new_method_call(ipmi::sel::mapperBusName, - ipmi::sel::mapperObjPath, - ipmi::sel::mapperIntf, - "GetSubTreePaths"); + auto mapperCall = + bus.new_method_call(ipmi::sel::mapperBusName, ipmi::sel::mapperObjPath, + ipmi::sel::mapperIntf, "GetSubTreePaths"); mapperCall.append(ipmi::sel::logBasePath); mapperCall.append(depth); mapperCall.append(ipmi::sel::ObjectPaths({ipmi::sel::logEntryIntf})); @@ -403,8 +401,7 @@ ipmi_ret_t clearSEL(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, try { - service = ipmi::getService(bus, - ipmi::sel::logDeleteIntf, + service = ipmi::getService(bus, ipmi::sel::logDeleteIntf, objectPaths.front()); } catch (const std::runtime_error& e) @@ -416,10 +413,8 @@ ipmi_ret_t clearSEL(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, for (const auto& iter : objectPaths) { - auto methodCall = bus.new_method_call(service.c_str(), - iter.c_str(), - ipmi::sel::logDeleteIntf, - "Delete"); + auto methodCall = bus.new_method_call( + service.c_str(), iter.c_str(), ipmi::sel::logDeleteIntf, "Delete"); auto reply = bus.call(methodCall); if (reply.is_method_error()) @@ -437,8 +432,10 @@ ipmi_ret_t clearSEL(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, } ipmi_ret_t ipmi_storage_get_sel_time(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { using namespace std::chrono; uint64_t host_time_usec = 0; @@ -452,10 +449,8 @@ ipmi_ret_t ipmi_storage_get_sel_time(ipmi_netfn_t netfn, ipmi_cmd_t cmd, sdbusplus::message::variant value; // Get host time - auto method = bus.new_method_call(service.c_str(), - HOST_TIME_PATH, - DBUS_PROPERTIES, - "Get"); + auto method = bus.new_method_call(service.c_str(), HOST_TIME_PATH, + DBUS_PROPERTIES, "Get"); method.append(TIME_INTERFACE, PROPERTY_ELAPSED); auto reply = bus.call(method); @@ -483,7 +478,6 @@ ipmi_ret_t ipmi_storage_get_sel_time(ipmi_netfn_t netfn, ipmi_cmd_t cmd, hostTime << "Host time:" << getTimeString(host_time_usec); log(hostTime.str().c_str()); - // Time is really long int but IPMI wants just uint32. This works okay until // the number of seconds since 1970 overflows uint32 size.. Still a whole // lot of time here to even think about that. @@ -500,8 +494,10 @@ ipmi_ret_t ipmi_storage_get_sel_time(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } ipmi_ret_t ipmi_storage_set_sel_time(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { using namespace std::chrono; ipmi_ret_t rc = IPMI_CC_OK; @@ -518,10 +514,8 @@ ipmi_ret_t ipmi_storage_set_sel_time(ipmi_netfn_t netfn, ipmi_cmd_t cmd, sdbusplus::message::variant value{usec.count()}; // Set host time - auto method = bus.new_method_call(service.c_str(), - HOST_TIME_PATH, - DBUS_PROPERTIES, - "Set"); + auto method = bus.new_method_call(service.c_str(), HOST_TIME_PATH, + DBUS_PROPERTIES, "Set"); method.append(TIME_INTERFACE, PROPERTY_ELAPSED, value); auto reply = bus.call(method); @@ -548,13 +542,16 @@ ipmi_ret_t ipmi_storage_set_sel_time(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } ipmi_ret_t ipmi_storage_reserve_sel(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; - // IPMI spec, Reservation ID, the value simply increases against each execution of reserve_sel command. - if( ++g_sel_reserve == 0) + // IPMI spec, Reservation ID, the value simply increases against each + // execution of reserve_sel command. + if (++g_sel_reserve == 0) g_sel_reserve = 1; *data_len = sizeof(g_sel_reserve); @@ -566,12 +563,14 @@ ipmi_ret_t ipmi_storage_reserve_sel(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } ipmi_ret_t ipmi_storage_add_sel(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; - ipmi_add_sel_request_t *p = (ipmi_add_sel_request_t*) request; + ipmi_add_sel_request_t* p = (ipmi_add_sel_request_t*)request; uint16_t recordid; recordid = ((uint16_t)p->eventdata[1] << 8) | p->eventdata[2]; @@ -598,11 +597,10 @@ ipmi_ret_t ipmi_storage_add_sel(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return rc; } -//Read FRU info area +// Read FRU info area ipmi_ret_t ipmi_storage_get_fru_inv_area_info( - ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, - ipmi_response_t response, ipmi_data_len_t data_len, - ipmi_context_t context) + ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, + ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; const FruInvenAreaInfoRequest* reqptr = @@ -629,7 +627,7 @@ ipmi_ret_t ipmi_storage_get_fru_inv_area_info( // Pack the actual response memcpy(response, &resp, *data_len); } - catch(const InternalFailure& e) + catch (const InternalFailure& e) { rc = IPMI_CC_UNSPECIFIED_ERROR; *data_len = 0; @@ -638,17 +636,17 @@ ipmi_ret_t ipmi_storage_get_fru_inv_area_info( return rc; } -//Read FRU data -ipmi_ret_t ipmi_storage_read_fru_data( - ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, - ipmi_response_t response, ipmi_data_len_t data_len, - ipmi_context_t context) +// Read FRU data +ipmi_ret_t ipmi_storage_read_fru_data(ipmi_netfn_t netfn, ipmi_cmd_t cmd, + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; const ReadFruDataRequest* reqptr = reinterpret_cast(request); - auto resptr = - reinterpret_cast(response); + auto resptr = reinterpret_cast(response); auto iter = frus.find(reqptr->fruID); if (iter == frus.end()) @@ -680,8 +678,7 @@ ipmi_ret_t ipmi_storage_read_fru_data( } std::copy((fruArea.begin() + offset), - (fruArea.begin() + offset + resptr->count), - resptr->data); + (fruArea.begin() + offset + resptr->count), resptr->data); *data_len = resptr->count + 1; // additional one byte for count } @@ -695,14 +692,15 @@ ipmi_ret_t ipmi_storage_read_fru_data( } ipmi_ret_t ipmi_get_repository_info(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { constexpr auto sdrVersion = 0x51; - auto responseData = - reinterpret_cast(response); + auto responseData = reinterpret_cast(response); - memset(responseData, 0 , sizeof(GetRepositoryInfoResponse)); + memset(responseData, 0, sizeof(GetRepositoryInfoResponse)); responseData->sdrVersion = sdrVersion; @@ -721,63 +719,60 @@ ipmi_ret_t ipmi_get_repository_info(ipmi_netfn_t netfn, ipmi_cmd_t cmd, void register_netfn_storage_functions() { // - ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_WILDCARD, NULL, ipmi_storage_wildcard, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_WILDCARD, NULL, + ipmi_storage_wildcard, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_GET_SEL_INFO, NULL, getSELInfo, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_GET_SEL_INFO, NULL, + getSELInfo, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_GET_SEL_TIME, NULL, ipmi_storage_get_sel_time, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_GET_SEL_TIME, NULL, + ipmi_storage_get_sel_time, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_SET_SEL_TIME, NULL, ipmi_storage_set_sel_time, - PRIVILEGE_OPERATOR); + ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_SET_SEL_TIME, NULL, + ipmi_storage_set_sel_time, PRIVILEGE_OPERATOR); // - ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_RESERVE_SEL, NULL, ipmi_storage_reserve_sel, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_RESERVE_SEL, NULL, + ipmi_storage_reserve_sel, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_GET_SEL_ENTRY, NULL, getSELEntry, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_GET_SEL_ENTRY, NULL, + getSELEntry, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_DELETE_SEL, NULL, deleteSELEntry, - PRIVILEGE_OPERATOR); + ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_DELETE_SEL, NULL, + deleteSELEntry, PRIVILEGE_OPERATOR); // - ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_ADD_SEL, NULL, ipmi_storage_add_sel, - PRIVILEGE_OPERATOR); + ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_ADD_SEL, NULL, + ipmi_storage_add_sel, PRIVILEGE_OPERATOR); // ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_CLEAR_SEL, NULL, clearSEL, PRIVILEGE_OPERATOR); // ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_GET_FRU_INV_AREA_INFO, NULL, - ipmi_storage_get_fru_inv_area_info, PRIVILEGE_OPERATOR); + ipmi_storage_get_fru_inv_area_info, + PRIVILEGE_OPERATOR); // ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_GET_REPOSITORY_INFO, - nullptr, ipmi_get_repository_info, - PRIVILEGE_USER); + nullptr, ipmi_get_repository_info, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_RESERVE_SDR, - nullptr, ipmi_sen_reserve_sdr, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_RESERVE_SDR, nullptr, + ipmi_sen_reserve_sdr, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_GET_SDR, - nullptr, ipmi_sen_get_sdr, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_GET_SDR, nullptr, + ipmi_sen_get_sdr, PRIVILEGE_USER); ipmi::fru::registerCallbackHandler(); return; } - diff --git a/storagehandler.h b/storagehandler.h index 2e8f1fc..17ac7b8 100644 --- a/storagehandler.h +++ b/storagehandler.h @@ -5,33 +5,34 @@ enum ipmi_netfn_storage_cmds { // Get capability bits - IPMI_CMD_GET_FRU_INV_AREA_INFO = 0x10, + IPMI_CMD_GET_FRU_INV_AREA_INFO = 0x10, IPMI_CMD_GET_REPOSITORY_INFO = 0x20, - IPMI_CMD_READ_FRU_DATA = 0x11, - IPMI_CMD_RESERVE_SDR = 0x22, - IPMI_CMD_GET_SDR = 0x23, - IPMI_CMD_GET_SEL_INFO = 0x40, - IPMI_CMD_RESERVE_SEL = 0x42, - IPMI_CMD_GET_SEL_ENTRY = 0x43, - IPMI_CMD_ADD_SEL = 0x44, - IPMI_CMD_DELETE_SEL = 0x46, - IPMI_CMD_CLEAR_SEL = 0x47, - IPMI_CMD_GET_SEL_TIME = 0x48, - IPMI_CMD_SET_SEL_TIME = 0x49, + IPMI_CMD_READ_FRU_DATA = 0x11, + IPMI_CMD_RESERVE_SDR = 0x22, + IPMI_CMD_GET_SDR = 0x23, + IPMI_CMD_GET_SEL_INFO = 0x40, + IPMI_CMD_RESERVE_SEL = 0x42, + IPMI_CMD_GET_SEL_ENTRY = 0x43, + IPMI_CMD_ADD_SEL = 0x44, + IPMI_CMD_DELETE_SEL = 0x46, + IPMI_CMD_CLEAR_SEL = 0x47, + IPMI_CMD_GET_SEL_TIME = 0x48, + IPMI_CMD_SET_SEL_TIME = 0x49, }; -struct ipmi_add_sel_request_t { +struct ipmi_add_sel_request_t +{ - uint8_t recordid[2]; - uint8_t recordtype; - uint8_t timestampe[4]; - uint8_t generatorid[2]; - uint8_t evmrev; - uint8_t sensortype; - uint8_t sensornumber; - uint8_t eventdir; - uint8_t eventdata[3]; + uint8_t recordid[2]; + uint8_t recordtype; + uint8_t timestampe[4]; + uint8_t generatorid[2]; + uint8_t evmrev; + uint8_t sensortype; + uint8_t sensornumber; + uint8_t eventdir; + uint8_t eventdata[3]; }; /** @@ -39,20 +40,20 @@ struct ipmi_add_sel_request_t { */ struct ReadFruDataRequest { - uint8_t fruID; ///< FRU Device ID. FFh = reserved - uint8_t offsetLS; ///< FRU Inventory Offset to read, LS Byte - uint8_t offsetMS; ///< FRU Inventory Offset ro read, MS Byte - uint8_t count; ///< Count to read -}__attribute__ ((packed)); + uint8_t fruID; ///< FRU Device ID. FFh = reserved + uint8_t offsetLS; ///< FRU Inventory Offset to read, LS Byte + uint8_t offsetMS; ///< FRU Inventory Offset ro read, MS Byte + uint8_t count; ///< Count to read +} __attribute__((packed)); /** * @struct Read FRU Data command response data */ struct ReadFruDataResponse { - uint8_t count; ///< Response data Count. + uint8_t count; ///< Response data Count. uint8_t data[]; ///< Response data. -}__attribute__ ((packed)); +} __attribute__((packed)); /** * @struct Get FRU inventory area info command request data @@ -60,30 +61,29 @@ struct ReadFruDataResponse struct FruInvenAreaInfoRequest { uint8_t fruID; ///< FRU Device ID. FFH = reserved. -}__attribute__ ((packed)); - +} __attribute__((packed)); /** * @struct Get FRU inventory area info command response */ struct FruInvenAreaInfoResponse { - uint8_t sizels; ///< Fru Inventory area size in bytes, LS Byte - uint8_t sizems; ///< Fru Inventory are size in bytes, MS Byte - uint8_t access; ///< 0b Devices is accessed by bytes, 1b - by words -}__attribute__ ((packed)); + uint8_t sizels; ///< Fru Inventory area size in bytes, LS Byte + uint8_t sizems; ///< Fru Inventory are size in bytes, MS Byte + uint8_t access; ///< 0b Devices is accessed by bytes, 1b - by words +} __attribute__((packed)); /** * @struct Get Repository info command response */ struct GetRepositoryInfoResponse { - uint8_t sdrVersion; //< SDR version - uint8_t recordCountLs; //< Record count LS byte - uint8_t recordCountMs; //< Record count MS bte - uint8_t freeSpace[2]; //< Free space in bytes, LS first + uint8_t sdrVersion; //< SDR version + uint8_t recordCountLs; //< Record count LS byte + uint8_t recordCountMs; //< Record count MS bte + uint8_t freeSpace[2]; //< Free space in bytes, LS first uint8_t additionTimestamp[4]; //< Most recent addition timestamp LS first uint8_t deletionTimestamp[4]; //< Most recent deletion timestamp LS first - uint8_t operationSupport; //< Operation support -}__attribute__ ((packed)); + uint8_t operationSupport; //< Operation support +} __attribute__((packed)); #endif diff --git a/systemintfcmds.cpp b/systemintfcmds.cpp index d363233..c39a7af 100644 --- a/systemintfcmds.cpp +++ b/systemintfcmds.cpp @@ -1,12 +1,15 @@ -#include "systemintfcmds.h" -#include "host-ipmid/ipmid-api.h" -#include "host-ipmid/ipmid-host-cmd.hpp" #include "config.h" + +#include "systemintfcmds.h" + #include "host-cmd-manager.hpp" #include "host-interface.hpp" +#include "host-ipmid/ipmid-host-cmd.hpp" -#include #include +#include + +#include "host-ipmid/ipmid-api.h" void register_netfn_app_functions() __attribute__((constructor)); @@ -20,8 +23,8 @@ extern cmdManagerPtr& ipmid_get_host_cmd_manager(); // Called by Host post response from Get_Message_Flags //------------------------------------------------------------------- ipmi_ret_t ipmi_app_read_event(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, ipmi_response_t response, + ipmi_data_len_t data_len, ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; @@ -29,22 +32,22 @@ ipmi_ret_t ipmi_app_read_event(ipmi_netfn_t netfn, ipmi_cmd_t cmd, *data_len = sizeof(struct oem_sel_timestamped); // either id[0] -or- id[1] can be filled in. We will use id[0] - oem_sel.id[0] = SEL_OEM_ID_0; - oem_sel.id[1] = SEL_OEM_ID_0; - oem_sel.type = SEL_RECORD_TYPE_OEM; + oem_sel.id[0] = SEL_OEM_ID_0; + oem_sel.id[1] = SEL_OEM_ID_0; + oem_sel.type = SEL_RECORD_TYPE_OEM; // Following 3 bytes are from IANA Manufactre_Id field. See below - oem_sel.manuf_id[0]= 0x41; - oem_sel.manuf_id[1]= 0xA7; - oem_sel.manuf_id[2]= 0x00; + oem_sel.manuf_id[0] = 0x41; + oem_sel.manuf_id[1] = 0xA7; + oem_sel.manuf_id[2] = 0x00; // per IPMI spec NetFuntion for OEM - oem_sel.netfun = 0x3A; + oem_sel.netfun = 0x3A; // Read from the Command Manager queue. What gets returned is a // pair of that can be directly used here - auto hostCmd = ipmid_get_host_cmd_manager()->getNextCommand(); - oem_sel.cmd = hostCmd.first; + auto hostCmd = ipmid_get_host_cmd_manager()->getNextCommand(); + oem_sel.cmd = hostCmd.first; oem_sel.data[0] = hostCmd.second; // All '0xFF' since unused. @@ -60,8 +63,10 @@ ipmi_ret_t ipmi_app_read_event(ipmi_netfn_t netfn, ipmi_cmd_t cmd, // value of 0x2 indicating we need Host read some data. //------------------------------------------------------------------- ipmi_ret_t ipmi_app_get_msg_flags(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { // Generic return from IPMI commands. ipmi_ret_t rc = IPMI_CC_OK; @@ -82,8 +87,10 @@ ipmi_ret_t ipmi_app_get_msg_flags(ipmi_netfn_t netfn, ipmi_cmd_t cmd, } ipmi_ret_t ipmi_app_set_bmc_global_enables(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; *data_len = 0; @@ -96,29 +103,30 @@ ipmi_ret_t ipmi_app_set_bmc_global_enables(ipmi_netfn_t netfn, ipmi_cmd_t cmd, return rc; } -namespace { +namespace +{ // Static storage to keep the object alive during process life std::unique_ptr host - __attribute__((init_priority(101))); + __attribute__((init_priority(101))); std::unique_ptr objManager - __attribute__((init_priority(101))); -} + __attribute__((init_priority(101))); +} // namespace #include void register_netfn_app_functions() { // - ipmi_register_callback(NETFUN_APP, IPMI_CMD_READ_EVENT, NULL, ipmi_app_read_event, - SYSTEM_INTERFACE); + ipmi_register_callback(NETFUN_APP, IPMI_CMD_READ_EVENT, NULL, + ipmi_app_read_event, SYSTEM_INTERFACE); // ipmi_register_callback(NETFUN_APP, IPMI_CMD_SET_BMC_GLOBAL_ENABLES, NULL, ipmi_app_set_bmc_global_enables, SYSTEM_INTERFACE); // - ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_MSG_FLAGS, NULL, ipmi_app_get_msg_flags, - SYSTEM_INTERFACE); + ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_MSG_FLAGS, NULL, + ipmi_app_get_msg_flags, SYSTEM_INTERFACE); // Create new xyz.openbmc_project.host object on the bus auto objPath = std::string{CONTROL_HOST_OBJ_MGR} + '/' + HOST_NAME + '0'; @@ -126,11 +134,10 @@ void register_netfn_app_functions() // Add sdbusplus ObjectManager. auto& sdbusPlusHandler = ipmid_get_sdbus_plus_handler(); objManager = std::make_unique( - *sdbusPlusHandler, - CONTROL_HOST_OBJ_MGR); + *sdbusPlusHandler, CONTROL_HOST_OBJ_MGR); - host = std::make_unique( - *sdbusPlusHandler, objPath.c_str()); + host = std::make_unique(*sdbusPlusHandler, + objPath.c_str()); sdbusPlusHandler->request_name(CONTROL_HOST_BUSNAME); return; diff --git a/systemintfcmds.h b/systemintfcmds.h index d603aaa..0243c02 100644 --- a/systemintfcmds.h +++ b/systemintfcmds.h @@ -6,22 +6,22 @@ // These are per skiboot ipmi-sel code // OEM_SEL type with Timestamp -#define SEL_OEM_ID_0 0x55 +#define SEL_OEM_ID_0 0x55 // SEL type is OEM and -not- general SEL #define SEL_RECORD_TYPE_OEM 0xC0 // Minor command for soft shurdown -#define SOFT_OFF 0x00 +#define SOFT_OFF 0x00 // Major command for Any kind of power ops -#define CMD_POWER 0x04 +#define CMD_POWER 0x04 // Major command for the heartbeat operation (verify host is alive) -#define CMD_HEARTBEAT 0xFF +#define CMD_HEARTBEAT 0xFF // IPMI commands used via System Interface functions. enum ipmi_netfn_system_intf_cmds { IPMI_CMD_SET_BMC_GLOBAL_ENABLES = 0x2E, - IPMI_CMD_GET_MSG_FLAGS = 0x31, - IPMI_CMD_READ_EVENT = 0x35, + IPMI_CMD_GET_MSG_FLAGS = 0x31, + IPMI_CMD_READ_EVENT = 0x35, }; // A Mechanism to tell host to shtudown hosts by sending this PEM SEL. Really diff --git a/test/oemrouter_unittest.cpp b/test/oemrouter_unittest.cpp index a5a79dd..b48798b 100644 --- a/test/oemrouter_unittest.cpp +++ b/test/oemrouter_unittest.cpp @@ -1,8 +1,10 @@ -#include "host-ipmid/ipmid-api.h" #include "host-ipmid/oemrouter.hpp" -#include "sample.h" #include + +#include "host-ipmid/ipmid-api.h" +#include "sample.h" + #include // Watch for correct singleton behavior. @@ -52,19 +54,18 @@ void RegisterWithRouter(Number oen, ipmi_cmd_t cmd, Handler cb) singletonUnderTest->registerHandler(oen, cmd, cb); } -uint8_t msgPlain[] = { 0x56, 0x34, 0x12 }; -uint8_t replyPlain[] = { 0x56, 0x34, 0x12, 0x31, 0x41 }; -uint8_t msgPlus2[] = { 0x67, 0x45, 0x23, 0x10, 0x20 }; -uint8_t msgBadOen[] = { 0x57, 0x34, 0x12 }; +uint8_t msgPlain[] = {0x56, 0x34, 0x12}; +uint8_t replyPlain[] = {0x56, 0x34, 0x12, 0x31, 0x41}; +uint8_t msgPlus2[] = {0x67, 0x45, 0x23, 0x10, 0x20}; +uint8_t msgBadOen[] = {0x57, 0x34, 0x12}; -void RegisterTwoWays(ipmi_cmd_t *nextCmd) +void RegisterTwoWays(ipmi_cmd_t* nextCmd) { - Handler f = [](ipmi_cmd_t cmd, const uint8_t* reqBuf, - uint8_t* replyBuf, size_t* dataLen) - { + Handler f = [](ipmi_cmd_t cmd, const uint8_t* reqBuf, uint8_t* replyBuf, + size_t* dataLen) { // Check inputs EXPECT_EQ(0x78, cmd); - EXPECT_EQ(0, *dataLen); // Excludes OEN + EXPECT_EQ(0, *dataLen); // Excludes OEN // Generate reply. *dataLen = 2; @@ -75,11 +76,10 @@ void RegisterTwoWays(ipmi_cmd_t *nextCmd) *nextCmd = IPMI_CMD_WILDCARD; Handler g = [nextCmd](ipmi_cmd_t cmd, const uint8_t* reqBuf, - uint8_t* replyBuf, size_t* dataLen) - { + uint8_t* replyBuf, size_t* dataLen) { // Check inputs EXPECT_EQ(*nextCmd, cmd); - EXPECT_EQ(2, *dataLen); // Excludes OEN + EXPECT_EQ(2, *dataLen); // Excludes OEN if (2 != *dataLen) { return 0xE0; @@ -93,18 +93,21 @@ void RegisterTwoWays(ipmi_cmd_t *nextCmd) }; RegisterWithRouter(0x234567, IPMI_CMD_WILDCARD, g); } -} // namespace +} // namespace -TEST(OemRouterTest, MakeRouterProducesConsistentSingleton) { +TEST(OemRouterTest, MakeRouterProducesConsistentSingleton) +{ MakeRouter(); } -TEST(OemRouterTest, ActivateRouterSetsLastNetToOEMGROUP) { +TEST(OemRouterTest, ActivateRouterSetsLastNetToOEMGROUP) +{ lastNetFunction = 0; ActivateRouter(); } -TEST(OemRouterTest, VerifiesSpecificCommandMatches) { +TEST(OemRouterTest, VerifiesSpecificCommandMatches) +{ ipmi_cmd_t cmd; uint8_t reply[256]; size_t dataLen; @@ -112,9 +115,8 @@ TEST(OemRouterTest, VerifiesSpecificCommandMatches) { RegisterTwoWays(&cmd); dataLen = 3; - EXPECT_EQ(0, - wildHandler(NETFUN_OEM_GROUP, 0x78, msgPlain, reply, - &dataLen, nullptr)); + EXPECT_EQ(0, wildHandler(NETFUN_OEM_GROUP, 0x78, msgPlain, reply, &dataLen, + nullptr)); EXPECT_EQ(5, dataLen); EXPECT_EQ(replyPlain[0], reply[0]); EXPECT_EQ(replyPlain[1], reply[1]); @@ -123,7 +125,8 @@ TEST(OemRouterTest, VerifiesSpecificCommandMatches) { EXPECT_EQ(replyPlain[4], reply[4]); } -TEST(OemRouterTest, WildCardMatchesTwoRandomCodes) { +TEST(OemRouterTest, WildCardMatchesTwoRandomCodes) +{ ipmi_cmd_t cmd; uint8_t reply[256]; size_t dataLen; @@ -133,20 +136,19 @@ TEST(OemRouterTest, WildCardMatchesTwoRandomCodes) { // Check two random command codes. dataLen = 5; cmd = 0x89; - EXPECT_EQ(0, - wildHandler(NETFUN_OEM_GROUP, cmd, msgPlus2, reply, - &dataLen, nullptr)); + EXPECT_EQ(0, wildHandler(NETFUN_OEM_GROUP, cmd, msgPlus2, reply, &dataLen, + nullptr)); EXPECT_EQ(3, dataLen); dataLen = 5; cmd = 0x67; - EXPECT_EQ(0, - wildHandler(NETFUN_OEM_GROUP, cmd, msgPlus2, reply, - &dataLen, nullptr)); + EXPECT_EQ(0, wildHandler(NETFUN_OEM_GROUP, cmd, msgPlus2, reply, &dataLen, + nullptr)); EXPECT_EQ(3, dataLen); } -TEST(OemRouterTest, CommandsAreRejectedIfInvalid) { +TEST(OemRouterTest, CommandsAreRejectedIfInvalid) +{ ipmi_cmd_t cmd; uint8_t reply[256]; size_t dataLen; @@ -156,20 +158,18 @@ TEST(OemRouterTest, CommandsAreRejectedIfInvalid) { // Message too short to include whole OEN? dataLen = 2; EXPECT_EQ(IPMI_CC_REQ_DATA_LEN_INVALID, - wildHandler(NETFUN_OEM_GROUP, 0x78, msgPlain, reply, - &dataLen, nullptr)); + wildHandler(NETFUN_OEM_GROUP, 0x78, msgPlain, reply, &dataLen, + nullptr)); // Wrong specific command? dataLen = 3; - EXPECT_EQ(IPMI_CC_INVALID, - wildHandler(NETFUN_OEM_GROUP, 0x89, msgPlain, reply, - &dataLen, nullptr)); + EXPECT_EQ(IPMI_CC_INVALID, wildHandler(NETFUN_OEM_GROUP, 0x89, msgPlain, + reply, &dataLen, nullptr)); // Wrong OEN? dataLen = 3; - EXPECT_EQ(IPMI_CC_INVALID, - wildHandler(NETFUN_OEM_GROUP, 0x78, msgBadOen, reply, - &dataLen, nullptr)); + EXPECT_EQ(IPMI_CC_INVALID, wildHandler(NETFUN_OEM_GROUP, 0x78, msgBadOen, + reply, &dataLen, nullptr)); } -} // namespace oem +} // namespace oem diff --git a/test/sample_unittest.cpp b/test/sample_unittest.cpp index 2a27279..e574173 100644 --- a/test/sample_unittest.cpp +++ b/test/sample_unittest.cpp @@ -1,6 +1,8 @@ #include "sample.h" + #include -TEST(FactorialTest, Zero) { +TEST(FactorialTest, Zero) +{ EXPECT_EQ(1, Factorial(0)); } diff --git a/testaddsel.cpp b/testaddsel.cpp index c3b317a..7f42acb 100644 --- a/testaddsel.cpp +++ b/testaddsel.cpp @@ -1,63 +1,66 @@ -#include -#include -#include #include +#include +#include #include +#include +#include #include -#include "sensorhandler.h" -#include +#include "sensorhandler.h" extern void send_esel(uint16_t recordid); -sd_bus *bus = NULL; +sd_bus* bus = NULL; // Use a lookup table to find the interface name of a specific sensor // This will be used until an alternative is found. this is the first // step for mapping IPMI -int find_openbmc_path(const uint8_t num, dbus_interface_t *interface) { +int find_openbmc_path(const uint8_t num, dbus_interface_t* interface) +{ - const char *objname = "/org/openbmc/managers/System"; + const char* objname = "/org/openbmc/managers/System"; - char *str1, *str2, *str3; + char *str1, *str2, *str3; sd_bus_error error = SD_BUS_ERROR_NULL; - sd_bus_message *reply = NULL, *m=NULL; + sd_bus_message *reply = NULL, *m = NULL; int r; - char *busname = NULL; + char* busname = NULL; r = mapper_get_service(bus, objname, &busname); - if (r < 0) { - log("Failed to get busname", - entry("BUS=%s", objname), + if (r < 0) + { + log("Failed to get busname", entry("BUS=%s", objname), entry("ERRNO=0x%X", -r)); goto final; } - r = sd_bus_message_new_method_call(bus,&m,busname,objname,busname,"getObjectFromByteId"); - if (r < 0) { + r = sd_bus_message_new_method_call(bus, &m, busname, objname, busname, + "getObjectFromByteId"); + if (r < 0) + { log("Failed to create a method call", entry("ERRNO=0x%X", -r)); } r = sd_bus_message_append(m, "sy", type, num); - if (r < 0) { + if (r < 0) + { log("Failed to create a input parameter", entry("ERRNO=0x%X", -r)); } // Call the IPMI responder on the bus so the message can be sent to the CEC r = sd_bus_call(bus, m, 0, &error, &reply); - if (r < 0) { - log("Failed to call the method", - entry("ERRNO=0x%X", -r)); + if (r < 0) + { + log("Failed to call the method", entry("ERRNO=0x%X", -r)); goto final; } - r = sd_bus_message_read(reply, "(sss)", &str1, &str2, &str3); - if (r < 0) { - log("Failed to get a response", - entry("ERRNO=0x%X", -r)); + if (r < 0) + { + log("Failed to get a response", entry("ERRNO=0x%X", -r)); goto final; } @@ -71,15 +74,12 @@ final: sd_bus_error_free(&error); sd_bus_message_unref(m); - free (busname); + free(busname); return r; } - - - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { int base; char *endptr, *str; @@ -87,7 +87,8 @@ int main(int argc, char *argv[]) uint16_t num; int r; - if (argc < 2) { + if (argc < 2) + { fprintf(stderr, "Usage: %s sensornumber\n", argv[0]); return -1; } @@ -97,13 +98,12 @@ int main(int argc, char *argv[]) val = strtol(str, &endptr, base); - num = (uint16_t) val; - - + num = (uint16_t)val; /* Connect to system bus */ r = sd_bus_open_system(&bus); - if (r < 0) { + if (r < 0) + { log("Failed to connect to system bus", entry("ERRNO=0x%X", -r)); goto finish; @@ -111,7 +111,6 @@ int main(int argc, char *argv[]) send_esel(num); - finish: sd_bus_unref(bus); diff --git a/testit.cpp b/testit.cpp index 37bb146..2541915 100644 --- a/testit.cpp +++ b/testit.cpp @@ -1,33 +1,33 @@ +#include #include #include -#include +unsigned char g_sensortype[][2] = { + {0xC3, 0x01}, {0x07, 0x02}, {0x0F, 0x05}, {0x0c, 0x1F}, {0xFF, 0xff}}; -unsigned char g_sensortype [][2] = { - {0xC3, 0x01}, - {0x07, 0x02}, - {0x0F, 0x05}, - {0x0c, 0x1F}, - {0xFF ,0xff} -}; +uint8_t find_type_for_sensor_number(uint8_t sensor_number) +{ -uint8_t find_type_for_sensor_number(uint8_t sensor_number) { - - int i=0; + int i = 0; uint8_t rc; - while (g_sensortype[i][0] != 0xff) { - if (g_sensortype[i][1] == sensor_number) { + while (g_sensortype[i][0] != 0xff) + { + if (g_sensortype[i][1] == sensor_number) + { break; - } else { + } + else + { i++; } } rc = g_sensortype[i][0]; - if (rc == 0xFF) { + if (rc == 0xFF) + { rc = 0; } return rc; @@ -36,19 +36,21 @@ uint8_t find_type_for_sensor_number(uint8_t sensor_number) { char g_results_method[64]; char g_results_value[64]; - -int set_sensor_dbus_state_s(unsigned char number, const char *member, const char *value) { +int set_sensor_dbus_state_s(unsigned char number, const char* member, + const char* value) +{ strcpy(g_results_method, member); strcpy(g_results_value, value); return 0; } -int set_sensor_dbus_state_y(unsigned char number, char const* member, uint8_t value) { +int set_sensor_dbus_state_y(unsigned char number, char const* member, + uint8_t value) +{ char val[2]; - snprintf(val, 2, "%d", value); strcpy(g_results_method, member); @@ -57,40 +59,43 @@ int set_sensor_dbus_state_y(unsigned char number, char const* member, uint8_t va return 0; } - -extern int updateSensorRecordFromSSRAESC(const void *record); - - +extern int updateSensorRecordFromSSRAESC(const void* record); // DIMM Present -uint8_t testrec_sensor1[] = {0x1F, 0xa9, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +uint8_t testrec_sensor1[] = {0x1F, 0xa9, 0x00, 0x40, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00}; // DIMM Not present -uint8_t testrec_sensor2[] = {0x1F, 0xa9, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00}; +uint8_t testrec_sensor2[] = {0x1F, 0xa9, 0x00, 0x00, 0x00, + 0x40, 0x00, 0x00, 0x00, 0x00}; // DIMM Not present -uint8_t testrec_procfailed[] = {0x02, 0xa9, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00}; +uint8_t testrec_procfailed[] = {0x02, 0xa9, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x00, 0x00}; // Virtual Sensor 5, setting a Value of 0h -uint8_t testrec_bootprogress[] = {0x05, 0xa9, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x00}; +uint8_t testrec_bootprogress[] = {0x05, 0xa9, 0x00, 0x04, 0x00, + 0x00, 0x00, 0x00, 0x0E, 0x00}; // Virtual Sensor setting a boot count -uint8_t testrec_bootcount[] = {0x01, 0x09, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +uint8_t testrec_bootcount[] = {0x01, 0x09, 0x00, 0x03, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00}; // Invalid sensor number -uint8_t testrec_invalidnumber[]= {0x35, 0xa9, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00}; - - -int check_results(int rc, const char *method, const char *value) { - if (strcmp(g_results_method, method)) { - log("Method Failed", - entry("EXPECT=%s", method), +uint8_t testrec_invalidnumber[] = {0x35, 0xa9, 0x00, 0x04, 0x00, + 0x00, 0x00, 0x00, 0x03, 0x00}; + +int check_results(int rc, const char* method, const char* value) +{ + if (strcmp(g_results_method, method)) + { + log("Method Failed", entry("EXPECT=%s", method), entry("GOT=%s", g_results_method)); return -1; } - if (strcmp(g_results_value, value)) { - log("Value failed", - entry("EXPECT=%s", value), + if (strcmp(g_results_value, value)) + { + log("Value failed", entry("EXPECT=%s", value), entry("GOT=%s", g_results_method)); return -2; } @@ -98,20 +103,32 @@ int check_results(int rc, const char *method, const char *value) { return 0; } -void testprep(void) { +void testprep(void) +{ memset(g_results_method, 0, sizeof(g_results_method)); memset(g_results_value, 0, sizeof(g_results_value)); } +int main() +{ + + testprep(); + check_results(updateSensorRecordFromSSRAESC(testrec_bootprogress), + "setValue", "FW Progress, Docking station attachment"); + testprep(); + check_results(updateSensorRecordFromSSRAESC(testrec_sensor1), "setPresent", + "True"); + testprep(); + check_results(updateSensorRecordFromSSRAESC(testrec_sensor2), "setPresent", + "False"); + testprep(); + check_results(updateSensorRecordFromSSRAESC(testrec_procfailed), "setFault", + "False"); + testprep(); + check_results(updateSensorRecordFromSSRAESC(testrec_bootcount), "setValue", + "3"); + testprep(); + check_results(updateSensorRecordFromSSRAESC(testrec_invalidnumber), "", ""); -int main() { - - testprep(); check_results(updateSensorRecordFromSSRAESC(testrec_bootprogress), "setValue", "FW Progress, Docking station attachment"); - testprep(); check_results(updateSensorRecordFromSSRAESC(testrec_sensor1), "setPresent", "True"); - testprep(); check_results(updateSensorRecordFromSSRAESC(testrec_sensor2), "setPresent", "False"); - testprep(); check_results(updateSensorRecordFromSSRAESC(testrec_procfailed), "setFault", "False"); - testprep(); check_results(updateSensorRecordFromSSRAESC(testrec_bootcount), "setValue", "3"); - testprep(); check_results(updateSensorRecordFromSSRAESC(testrec_invalidnumber), "", ""); - - return 0; + return 0; } diff --git a/timer.cpp b/timer.cpp index 06965de..f1887fd 100644 --- a/timer.cpp +++ b/timer.cpp @@ -1,6 +1,7 @@ +#include "timer.hpp" + #include #include -#include "timer.hpp" namespace phosphor { namespace ipmi @@ -27,7 +28,7 @@ void Timer::initialize() if (r < 0) { log("Failure to set initial expiration time value", - entry("ERROR=%s", strerror(-r))); + entry("ERROR=%s", strerror(-r))); throw std::runtime_error("Timer initialization failed"); } @@ -37,7 +38,7 @@ void Timer::initialize() if (r < 0) { log("Failure to disable timer", - entry("ERROR=%s", strerror(-r))); + entry("ERROR=%s", strerror(-r))); throw std::runtime_error("Disabling the timer failed"); } @@ -45,15 +46,15 @@ void Timer::initialize() } /** @brief callback handler on timeout */ -int Timer::timeoutHandler(sd_event_source* eventSource, - uint64_t usec, void* userData) +int Timer::timeoutHandler(sd_event_source* eventSource, uint64_t usec, + void* userData) { auto timer = static_cast(userData); timer->expired = true; log("Timer expired"); // Call optional user call back function if available - if(timer->userCallBack) + if (timer->userCallBack) { timer->userCallBack(); } @@ -91,7 +92,7 @@ int Timer::startTimer(std::chrono::microseconds timeValue) if (r < 0) { log("Failure to set timer", - entry("ERROR=%s", strerror(-r))); + entry("ERROR=%s", strerror(-r))); return r; } @@ -101,7 +102,7 @@ int Timer::startTimer(std::chrono::microseconds timeValue) if (r < 0) { log("Failure to start timer", - entry("ERROR=%s", strerror(-r))); + entry("ERROR=%s", strerror(-r))); } return r; } diff --git a/timer.hpp b/timer.hpp index e39d85c..ec432ba 100644 --- a/timer.hpp +++ b/timer.hpp @@ -1,8 +1,9 @@ #pragma once +#include + #include #include -#include namespace phosphor { namespace ipmi @@ -13,88 +14,87 @@ namespace ipmi */ class Timer { - public: - /** @brief Only need the default Timer */ - Timer() = delete; - Timer(const Timer&) = delete; - Timer& operator=(const Timer&) = delete; - Timer(Timer&&) = delete; - Timer& operator=(Timer&&) = delete; - - /** @brief Constructs timer object - * - * @param[in] events - sd_event pointer - * @param[in] funcCallBack - optional function callback for timer - * expirations - */ - Timer(sd_event* events, - std::function userCallBack = nullptr) - : timeEvent(events), userCallBack(userCallBack) - { - // Initialize the timer - initialize(); - } + public: + /** @brief Only need the default Timer */ + Timer() = delete; + Timer(const Timer&) = delete; + Timer& operator=(const Timer&) = delete; + Timer(Timer&&) = delete; + Timer& operator=(Timer&&) = delete; - ~Timer() - { - if (eventSource) - { - eventSource = sd_event_source_unref(eventSource); - } - } + /** @brief Constructs timer object + * + * @param[in] events - sd_event pointer + * @param[in] funcCallBack - optional function callback for timer + * expirations + */ + Timer(sd_event* events, std::function userCallBack = nullptr) : + timeEvent(events), userCallBack(userCallBack) + { + // Initialize the timer + initialize(); + } - inline auto isExpired() const + ~Timer() + { + if (eventSource) { - return expired; + eventSource = sd_event_source_unref(eventSource); } + } + + inline auto isExpired() const + { + return expired; + } + + /** @brief Starts the timer with specified expiration value. + * input is an offset from the current steady_clock + */ + int startTimer(std::chrono::microseconds usec); + + /** @brief Enables / disables the timer */ + int setTimer(int action); + + private: + /** @brief the sd_event structure */ + sd_event* timeEvent = nullptr; + + /** @brief Source of events */ + sd_event_source* eventSource = nullptr; + + /** @brief Returns if the associated timer is expired + * + * This is set to true when the timeoutHandler is called into + */ + bool expired = true; + + /** @brief Initializes the timer object with infinite + * expiration time and sets up the callback handler + * + * @return None. + * + * @error std::runtime exception thrown + */ + void initialize(); + + /** @brief Callback function when timer goes off + * + * On getting the signal, initiate the hard power off request + * + * @param[in] eventSource - Source of the event + * @param[in] usec - time in micro seconds + * @param[in] userData - User data pointer + * + */ + static int timeoutHandler(sd_event_source* eventSource, uint64_t usec, + void* userData); + + /** @brief Gets the current time from steady clock */ + static std::chrono::microseconds getTime(); - /** @brief Starts the timer with specified expiration value. - * input is an offset from the current steady_clock - */ - int startTimer(std::chrono::microseconds usec); - - /** @brief Enables / disables the timer */ - int setTimer(int action); - - private: - /** @brief the sd_event structure */ - sd_event* timeEvent = nullptr; - - /** @brief Source of events */ - sd_event_source* eventSource = nullptr; - - /** @brief Returns if the associated timer is expired - * - * This is set to true when the timeoutHandler is called into - */ - bool expired = true; - - /** @brief Initializes the timer object with infinite - * expiration time and sets up the callback handler - * - * @return None. - * - * @error std::runtime exception thrown - */ - void initialize(); - - /** @brief Callback function when timer goes off - * - * On getting the signal, initiate the hard power off request - * - * @param[in] eventSource - Source of the event - * @param[in] usec - time in micro seconds - * @param[in] userData - User data pointer - * - */ - static int timeoutHandler(sd_event_source* eventSource, - uint64_t usec, void* userData); - - /** @brief Gets the current time from steady clock */ - static std::chrono::microseconds getTime(); - - /** @brief Optional function to call on timer expiration */ - std::function userCallBack; + /** @brief Optional function to call on timer expiration */ + std::function userCallBack; }; } // namespace ipmi diff --git a/transporthandler.cpp b/transporthandler.cpp index 95b983a..a6239ea 100644 --- a/transporthandler.cpp +++ b/transporthandler.cpp @@ -1,44 +1,47 @@ -#include -#include +#include +#include #include #include -#include -#include + +#include +#include #include #if __has_include() #include #elif __has_include() #include -namespace std { - // splice experimental::filesystem into std - namespace filesystem = std::experimental::filesystem; -} +namespace std +{ +// splice experimental::filesystem into std +namespace filesystem = std::experimental::filesystem; +} // namespace std #else -# error filesystem not available +#error filesystem not available #endif #include "app/channel.hpp" -#include "host-ipmid/ipmid-api.h" #include "ipmid.hpp" +#include "net.hpp" #include "timer.hpp" #include "transporthandler.hpp" #include "utils.hpp" -#include "net.hpp" -#include #include -#include "xyz/openbmc_project/Common/error.hpp" +#include +#include + +#include "host-ipmid/ipmid-api.h" #define SYSTEMD_NETWORKD_DBUS 1 #ifdef SYSTEMD_NETWORKD_DBUS -#include #include +#include #endif extern std::unique_ptr networkTimer; -const int SIZE_MAC = 18; //xx:xx:xx:xx:xx:xx +const int SIZE_MAC = 18; // xx:xx:xx:xx:xx:xx constexpr auto ipv4Protocol = "xyz.openbmc_project.Network.IP.Protocol.IPv4"; std::map> channelConfig; @@ -61,8 +64,8 @@ struct ChannelConfig_t* getChannelConfig(int channel) return channelConfig[channel].get(); } -// Helper Function to get IP Address/NetMask/Gateway/MAC Address from Network Manager or -// Cache based on Set-In-Progress State +// Helper Function to get IP Address/NetMask/Gateway/MAC Address from Network +// Manager or Cache based on Set-In-Progress State ipmi_ret_t getNetworkData(uint8_t lan_param, uint8_t* data, int channel) { ipmi_ret_t rc = IPMI_CC_OK; @@ -89,17 +92,13 @@ ipmi_ret_t getNetworkData(uint8_t lan_param, uint8_t* data, int channel) { try { - auto ipObjectInfo = ipmi::getIPObject( - bus, - ipmi::network::IP_INTERFACE, - ipmi::network::ROOT, - ethIP); + auto ipObjectInfo = + ipmi::getIPObject(bus, ipmi::network::IP_INTERFACE, + ipmi::network::ROOT, ethIP); auto properties = ipmi::getAllDbusProperties( - bus, - ipObjectInfo.second, - ipObjectInfo.first, - ipmi::network::IP_INTERFACE); + bus, ipObjectInfo.second, ipObjectInfo.first, + ipmi::network::IP_INTERFACE); ipaddress = properties["Address"].get(); } @@ -132,33 +131,29 @@ ipmi_ret_t getNetworkData(uint8_t lan_param, uint8_t* data, int channel) // if the system is having ip object,then // get the IP object. auto ipObject = ipmi::getDbusObject( - bus, - ipmi::network::IP_INTERFACE, - ipmi::network::ROOT, - ethIP); + bus, ipmi::network::IP_INTERFACE, + ipmi::network::ROOT, ethIP); // Get the parent interface of the IP object. try { ipmi::InterfaceList interfaces; interfaces.emplace_back( - ipmi::network::ETHERNET_INTERFACE); + ipmi::network::ETHERNET_INTERFACE); ancestorMap = ipmi::getAllAncestors( - bus, - ipObject.first, - std::move(interfaces)); + bus, ipObject.first, std::move(interfaces)); } catch (InternalFailure& e) { // if unable to get the parent interface // then commit the error and return. - log("Unable to get the parent interface", - entry("PATH=%s", ipObject.first.c_str()), - entry("INTERFACE=%s", - ipmi::network::ETHERNET_INTERFACE)); + log( + "Unable to get the parent interface", + entry("PATH=%s", ipObject.first.c_str()), + entry("INTERFACE=%s", + ipmi::network::ETHERNET_INTERFACE)); break; - } // for an ip object there would be single parent // interface. @@ -169,54 +164,45 @@ ipmi_ret_t getNetworkData(uint8_t lan_param, uint8_t* data, int channel) // if there is no ip configured on the system,then // get the network interface object. auto networkInterfaceObject = ipmi::getDbusObject( - bus, - ipmi::network::ETHERNET_INTERFACE, - ipmi::network::ROOT, - ethdevice); + bus, ipmi::network::ETHERNET_INTERFACE, + ipmi::network::ROOT, ethdevice); networkInterfacePath = networkInterfaceObject.first; } auto variant = ipmi::getDbusProperty( - bus, - ipmi::network::SERVICE, - networkInterfacePath, - ipmi::network::ETHERNET_INTERFACE, - "DHCPEnabled"); + bus, ipmi::network::SERVICE, networkInterfacePath, + ipmi::network::ETHERNET_INTERFACE, "DHCPEnabled"); auto dhcpEnabled = variant.get(); // As per IPMI spec 2=>DHCP, 1=STATIC - auto ipsrc = dhcpEnabled ? ipmi::network::IPOrigin::DHCP : - ipmi::network::IPOrigin::STATIC; + auto ipsrc = dhcpEnabled ? ipmi::network::IPOrigin::DHCP + : ipmi::network::IPOrigin::STATIC; memcpy(data, &ipsrc, ipmi::network::IPSRC_SIZE_BYTE); } else if (channelConf->lan_set_in_progress == SET_IN_PROGRESS) { - memcpy(data, &(channelConf->ipsrc), - ipmi::network::IPSRC_SIZE_BYTE); + memcpy(data, &(channelConf->ipsrc), + ipmi::network::IPSRC_SIZE_BYTE); } } break; case LAN_PARM_SUBNET: { - unsigned long mask {}; + unsigned long mask{}; if (channelConf->lan_set_in_progress == SET_COMPLETE) { try { auto ipObjectInfo = ipmi::getIPObject( - bus, - ipmi::network::IP_INTERFACE, - ipmi::network::ROOT, - ipmi::network::IP_TYPE); + bus, ipmi::network::IP_INTERFACE, + ipmi::network::ROOT, ipmi::network::IP_TYPE); auto properties = ipmi::getAllDbusProperties( - bus, - ipObjectInfo.second, - ipObjectInfo.first, - ipmi::network::IP_INTERFACE); + bus, ipObjectInfo.second, ipObjectInfo.first, + ipmi::network::IP_INTERFACE); auto prefix = properties["PrefixLength"].get(); mask = ipmi::network::MASK_32_BIT; @@ -235,7 +221,6 @@ ipmi_ret_t getNetworkData(uint8_t lan_param, uint8_t* data, int channel) inet_pton(AF_INET, channelConf->netmask.c_str(), reinterpret_cast(data)); } - } break; @@ -248,18 +233,15 @@ ipmi_ret_t getNetworkData(uint8_t lan_param, uint8_t* data, int channel) try { auto systemObject = ipmi::getDbusObject( - bus, - ipmi::network::SYSTEMCONFIG_INTERFACE, - ipmi::network::ROOT); + bus, ipmi::network::SYSTEMCONFIG_INTERFACE, + ipmi::network::ROOT); auto systemProperties = ipmi::getAllDbusProperties( - bus, - systemObject.second, - systemObject.first, - ipmi::network::SYSTEMCONFIG_INTERFACE); + bus, systemObject.second, systemObject.first, + ipmi::network::SYSTEMCONFIG_INTERFACE); - gateway = systemProperties["DefaultGateway"].get< - std::string>(); + gateway = systemProperties["DefaultGateway"] + .get(); } // ignore the exception, as it is a valid condition that // the system is not configured with any IP. @@ -267,7 +249,6 @@ ipmi_ret_t getNetworkData(uint8_t lan_param, uint8_t* data, int channel) { // nothing to do } - } else if (channelConf->lan_set_in_progress == SET_IN_PROGRESS) { @@ -284,21 +265,15 @@ ipmi_ret_t getNetworkData(uint8_t lan_param, uint8_t* data, int channel) std::string macAddress; if (channelConf->lan_set_in_progress == SET_COMPLETE) { - auto macObjectInfo = ipmi::getDbusObject( - bus, - ipmi::network::MAC_INTERFACE, - ipmi::network::ROOT, - ethdevice); + auto macObjectInfo = + ipmi::getDbusObject(bus, ipmi::network::MAC_INTERFACE, + ipmi::network::ROOT, ethdevice); auto variant = ipmi::getDbusProperty( - bus, - macObjectInfo.second, - macObjectInfo.first, - ipmi::network::MAC_INTERFACE, - "MACAddress"); + bus, macObjectInfo.second, macObjectInfo.first, + ipmi::network::MAC_INTERFACE, "MACAddress"); macAddress = variant.get(); - } else if (channelConf->lan_set_in_progress == SET_IN_PROGRESS) { @@ -306,36 +281,30 @@ ipmi_ret_t getNetworkData(uint8_t lan_param, uint8_t* data, int channel) } sscanf(macAddress.c_str(), ipmi::network::MAC_ADDRESS_FORMAT, - (data), - (data + 1), - (data + 2), - (data + 3), - (data + 4), + (data), (data + 1), (data + 2), (data + 3), (data + 4), (data + 5)); } break; case LAN_PARM_VLAN: { - uint16_t vlanID {}; + uint16_t vlanID{}; if (channelConf->lan_set_in_progress == SET_COMPLETE) { try { auto ipObjectInfo = ipmi::getIPObject( - bus, - ipmi::network::IP_INTERFACE, - ipmi::network::ROOT, - ipmi::network::IP_TYPE); + bus, ipmi::network::IP_INTERFACE, + ipmi::network::ROOT, ipmi::network::IP_TYPE); vlanID = static_cast( - ipmi::network::getVLAN(ipObjectInfo.first)); + ipmi::network::getVLAN(ipObjectInfo.first)); vlanID = htole16(vlanID); if (vlanID) { - //Enable the 16th bit + // Enable the 16th bit vlanID |= htole16(ipmi::network::VLAN_ENABLE_MASK); } } @@ -401,11 +370,13 @@ std::vector getCipherList() return cipherList; } -} //namespace cipher +} // namespace cipher ipmi_ret_t ipmi_transport_wildcard(ipmi_netfn_t netfn, ipmi_cmd_t cmd, - ipmi_request_t request, ipmi_response_t response, - ipmi_data_len_t data_len, ipmi_context_t context) + ipmi_request_t request, + ipmi_response_t response, + ipmi_data_len_t data_len, + ipmi_context_t context) { // Status code. ipmi_ret_t rc = IPMI_CC_INVALID; @@ -418,10 +389,9 @@ struct set_lan_t uint8_t channel; uint8_t parameter; uint8_t data[8]; // Per IPMI spec, not expecting more than this size -} __attribute__((packed)); +} __attribute__((packed)); -ipmi_ret_t ipmi_transport_set_lan(ipmi_netfn_t netfn, - ipmi_cmd_t cmd, +ipmi_ret_t ipmi_transport_set_lan(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, @@ -456,8 +426,8 @@ ipmi_ret_t ipmi_transport_set_lan(ipmi_netfn_t netfn, case LAN_PARM_IP: { snprintf(ipaddr, INET_ADDRSTRLEN, ipmi::network::IP_ADDRESS_FORMAT, - reqptr->data[0], reqptr->data[1], - reqptr->data[2], reqptr->data[3]); + reqptr->data[0], reqptr->data[1], reqptr->data[2], + reqptr->data[3]); channelConf->ipaddr.assign(ipaddr); } @@ -476,25 +446,16 @@ ipmi_ret_t ipmi_transport_set_lan(ipmi_netfn_t netfn, char mac[SIZE_MAC]; snprintf(mac, SIZE_MAC, ipmi::network::MAC_ADDRESS_FORMAT, - reqptr->data[0], - reqptr->data[1], - reqptr->data[2], - reqptr->data[3], - reqptr->data[4], - reqptr->data[5]); - - auto macObjectInfo = ipmi::getDbusObject( - bus, - ipmi::network::MAC_INTERFACE, - ipmi::network::ROOT, - ethdevice); - - ipmi::setDbusProperty(bus, - macObjectInfo.second, - macObjectInfo.first, - ipmi::network::MAC_INTERFACE, - "MACAddress", - std::string(mac)); + reqptr->data[0], reqptr->data[1], reqptr->data[2], + reqptr->data[3], reqptr->data[4], reqptr->data[5]); + + auto macObjectInfo = + ipmi::getDbusObject(bus, ipmi::network::MAC_INTERFACE, + ipmi::network::ROOT, ethdevice); + + ipmi::setDbusProperty( + bus, macObjectInfo.second, macObjectInfo.first, + ipmi::network::MAC_INTERFACE, "MACAddress", std::string(mac)); channelConf->macAddress = mac; } @@ -503,8 +464,8 @@ ipmi_ret_t ipmi_transport_set_lan(ipmi_netfn_t netfn, case LAN_PARM_SUBNET: { snprintf(netmask, INET_ADDRSTRLEN, ipmi::network::IP_ADDRESS_FORMAT, - reqptr->data[0], reqptr->data[1], - reqptr->data[2], reqptr->data[3]); + reqptr->data[0], reqptr->data[1], reqptr->data[2], + reqptr->data[3]); channelConf->netmask.assign(netmask); } break; @@ -512,15 +473,15 @@ ipmi_ret_t ipmi_transport_set_lan(ipmi_netfn_t netfn, case LAN_PARM_GATEWAY: { snprintf(gateway, INET_ADDRSTRLEN, ipmi::network::IP_ADDRESS_FORMAT, - reqptr->data[0], reqptr->data[1], - reqptr->data[2], reqptr->data[3]); + reqptr->data[0], reqptr->data[1], reqptr->data[2], + reqptr->data[3]); channelConf->gateway.assign(gateway); } break; case LAN_PARM_VLAN: { - uint16_t vlan {}; + uint16_t vlan{}; memcpy(&vlan, reqptr->data, ipmi::network::VLAN_SIZE_BYTE); // We are not storing the enable bit // We assume that ipmitool always send enable @@ -536,16 +497,17 @@ ipmi_ret_t ipmi_transport_set_lan(ipmi_netfn_t netfn, { channelConf->lan_set_in_progress = SET_COMPLETE; - log("Network data from Cache", - entry("PREFIX=%s", channelConf->netmask.c_str()), - entry("ADDRESS=%s", channelConf->ipaddr.c_str()), - entry("GATEWAY=%s", channelConf->gateway.c_str()), - entry("VLAN=%d", channelConf->vlanID)); + log( + "Network data from Cache", + entry("PREFIX=%s", channelConf->netmask.c_str()), + entry("ADDRESS=%s", channelConf->ipaddr.c_str()), + entry("GATEWAY=%s", channelConf->gateway.c_str()), + entry("VLAN=%d", channelConf->vlanID)); if (!networkTimer) { - log("Network timer is not instantiated"); - return IPMI_CC_UNSPECIFIED_ERROR; + log("Network timer is not instantiated"); + return IPMI_CC_UNSPECIFIED_ERROR; } // start/restart the timer @@ -574,10 +536,9 @@ struct get_lan_t uint8_t parameter; uint8_t parameter_set; uint8_t parameter_block; -} __attribute__((packed)); +} __attribute__((packed)); -ipmi_ret_t ipmi_transport_get_lan(ipmi_netfn_t netfn, - ipmi_cmd_t cmd, +ipmi_ret_t ipmi_transport_get_lan(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, @@ -587,7 +548,7 @@ ipmi_ret_t ipmi_transport_get_lan(ipmi_netfn_t netfn, *data_len = 0; const uint8_t current_revision = 0x11; // Current rev per IPMI Spec 2.0 - get_lan_t *reqptr = (get_lan_t*) request; + get_lan_t* reqptr = (get_lan_t*)request; // channel number is the lower nibble int channel = reqptr->rev_channel & CHANNEL_MASK; @@ -609,7 +570,7 @@ ipmi_ret_t ipmi_transport_get_lan(ipmi_netfn_t netfn, cipherList = cipher::getCipherList(); listInit = true; } - catch (const std::exception &e) + catch (const std::exception& e) { return IPMI_CC_UNSPECIFIED_ERROR; } @@ -630,13 +591,13 @@ ipmi_ret_t ipmi_transport_get_lan(ipmi_netfn_t netfn, } else if (reqptr->parameter == LAN_PARM_AUTHSUPPORT) { - uint8_t buf[] = {current_revision,0x04}; + uint8_t buf[] = {current_revision, 0x04}; *data_len = sizeof(buf); memcpy(response, &buf, *data_len); } else if (reqptr->parameter == LAN_PARM_AUTHENABLES) { - uint8_t buf[] = {current_revision,0x04,0x04,0x04,0x04,0x04}; + uint8_t buf[] = {current_revision, 0x04, 0x04, 0x04, 0x04, 0x04}; *data_len = sizeof(buf); memcpy(response, &buf, *data_len); } @@ -704,11 +665,10 @@ ipmi_ret_t ipmi_transport_get_lan(ipmi_netfn_t netfn, { *(static_cast(response)) = current_revision; // Byte 1 is reserved - std::copy_n(cipherList.data(), - cipherList.size(), + std::copy_n(cipherList.data(), cipherList.size(), static_cast(response) + 1); - *data_len = sizeof(current_revision) + - static_cast(cipherList.size()); + *data_len = + sizeof(current_revision) + static_cast(cipherList.size()); } else { @@ -724,8 +684,8 @@ void applyChanges(int channel) { std::string ipaddress; std::string gateway; - uint8_t prefix {}; - uint32_t vlanID {}; + uint8_t prefix{}; + uint32_t vlanID{}; std::string networkInterfacePath; ipmi::DbusObjectInfo ipObject; ipmi::DbusObjectInfo systemObject; @@ -752,8 +712,8 @@ void applyChanges(int channel) entry("IPSRC=%d", channelConf->ipsrc)); if (channelConf->vlanID != ipmi::network::VLAN_ID_MASK) { - //get the first twelve bits which is vlan id - //not interested in rest of the bits. + // get the first twelve bits which is vlan id + // not interested in rest of the bits. channelConf->vlanID = le32toh(channelConf->vlanID); vlanID = channelConf->vlanID & ipmi::network::VLAN_ID_MASK; } @@ -763,10 +723,9 @@ void applyChanges(int channel) if (channelConf->ipsrc != ipmi::network::IPOrigin::DHCP) { // always get the system object - systemObject = ipmi::getDbusObject( - bus, - ipmi::network::SYSTEMCONFIG_INTERFACE, - ipmi::network::ROOT); + systemObject = + ipmi::getDbusObject(bus, ipmi::network::SYSTEMCONFIG_INTERFACE, + ipmi::network::ROOT); // the below code is to determine the mode of the interface // as the handling is same, if the system is configured with @@ -775,21 +734,18 @@ void applyChanges(int channel) { ipmi::ObjectTree ancestorMap; - ipmi::InterfaceList interfaces { - ipmi::network::ETHERNET_INTERFACE }; + ipmi::InterfaceList interfaces{ + ipmi::network::ETHERNET_INTERFACE}; // if the system is having ip object,then // get the IP object. - ipObject = ipmi::getIPObject(bus, - ipmi::network::IP_INTERFACE, - ipmi::network::ROOT, - ethIp); + ipObject = ipmi::getIPObject(bus, ipmi::network::IP_INTERFACE, + ipmi::network::ROOT, ethIp); // Get the parent interface of the IP object. try { - ancestorMap = ipmi::getAllAncestors(bus, - ipObject.first, + ancestorMap = ipmi::getAllAncestors(bus, ipObject.first, std::move(interfaces)); } catch (InternalFailure& e) @@ -815,30 +771,27 @@ void applyChanges(int channel) // if there is no ip configured on the system,then // get the network interface object. - auto networkInterfaceObject = ipmi::getDbusObject( - bus, - ipmi::network::ETHERNET_INTERFACE, - ipmi::network::ROOT, - ethdevice); + auto networkInterfaceObject = + ipmi::getDbusObject(bus, ipmi::network::ETHERNET_INTERFACE, + ipmi::network::ROOT, ethdevice); networkInterfacePath = std::move(networkInterfaceObject.first); } // get the configured mode on the system. - auto enableDHCP = ipmi::getDbusProperty( - bus, - ipmi::network::SERVICE, - networkInterfacePath, - ipmi::network::ETHERNET_INTERFACE, - "DHCPEnabled").get(); + auto enableDHCP = + ipmi::getDbusProperty( + bus, ipmi::network::SERVICE, networkInterfacePath, + ipmi::network::ETHERNET_INTERFACE, "DHCPEnabled") + .get(); // if ip address source is not given then get the ip source mode // from the system so that it can be applied later. if (channelConf->ipsrc == ipmi::network::IPOrigin::UNSPECIFIED) { - channelConf->ipsrc = (enableDHCP) ? - ipmi::network::IPOrigin::DHCP : - ipmi::network::IPOrigin::STATIC; + channelConf->ipsrc = (enableDHCP) + ? ipmi::network::IPOrigin::DHCP + : ipmi::network::IPOrigin::STATIC; } // check whether user has given all the data @@ -849,13 +802,13 @@ void applyChanges(int channel) !channelConf->gateway.empty()) || (enableDHCP)) // configured system interface mode = DHCP { - //convert mask into prefix + // convert mask into prefix ipaddress = channelConf->ipaddr; prefix = ipmi::network::toPrefix(AF_INET, channelConf->netmask); gateway = channelConf->gateway; } else // asked ip src = static and configured system src = static - // or partially given data. + // or partially given data. { // We have partial filled cache so get the remaining // info from the system. @@ -869,36 +822,34 @@ void applyChanges(int channel) try { auto properties = ipmi::getAllDbusProperties( - bus, - ipObject.second, - ipObject.first, - ipmi::network::IP_INTERFACE); + bus, ipObject.second, ipObject.first, + ipmi::network::IP_INTERFACE); - ipaddress = channelConf->ipaddr.empty() ? - properties["Address"].get() : - channelConf->ipaddr; + ipaddress = channelConf->ipaddr.empty() + ? properties["Address"].get() + : channelConf->ipaddr; - prefix = channelConf->netmask.empty() ? - properties["PrefixLength"].get() : - ipmi::network::toPrefix(AF_INET, - channelConf->netmask); - } + prefix = channelConf->netmask.empty() + ? properties["PrefixLength"].get() + : ipmi::network::toPrefix( + AF_INET, channelConf->netmask); + } catch (InternalFailure& e) { - log("Failed to get IP object which matches", - entry("INTERFACE=%s", ipmi::network::IP_INTERFACE), - entry("MATCH=%s", ethIp.c_str())); + log( + "Failed to get IP object which matches", + entry("INTERFACE=%s", ipmi::network::IP_INTERFACE), + entry("MATCH=%s", ethIp.c_str())); } auto systemProperties = ipmi::getAllDbusProperties( - bus, - systemObject.second, - systemObject.first, - ipmi::network::SYSTEMCONFIG_INTERFACE); - - gateway = channelConf->gateway.empty() ? - systemProperties["DefaultGateway"].get() : - channelConf->gateway; + bus, systemObject.second, systemObject.first, + ipmi::network::SYSTEMCONFIG_INTERFACE); + + gateway = + channelConf->gateway.empty() + ? systemProperties["DefaultGateway"].get() + : channelConf->gateway; } } @@ -913,100 +864,74 @@ void applyChanges(int channel) // instead of deleting all the vlan interfaces and // all the ipv4 address,we will call reset method. - //delete all the vlan interfaces + // delete all the vlan interfaces - ipmi::deleteAllDbusObjects(bus, - ipmi::network::ROOT, + ipmi::deleteAllDbusObjects(bus, ipmi::network::ROOT, ipmi::network::VLAN_INTERFACE); // set the interface mode to static - auto networkInterfaceObject = ipmi::getDbusObject( - bus, - ipmi::network::ETHERNET_INTERFACE, - ipmi::network::ROOT, - ethdevice); + auto networkInterfaceObject = + ipmi::getDbusObject(bus, ipmi::network::ETHERNET_INTERFACE, + ipmi::network::ROOT, ethdevice); // setting the physical interface mode to static. - ipmi::setDbusProperty(bus, - ipmi::network::SERVICE, - networkInterfaceObject.first, - ipmi::network::ETHERNET_INTERFACE, - "DHCPEnabled", - false); + ipmi::setDbusProperty( + bus, ipmi::network::SERVICE, networkInterfaceObject.first, + ipmi::network::ETHERNET_INTERFACE, "DHCPEnabled", false); networkInterfacePath = networkInterfaceObject.first; - //delete all the ipv4 addresses - ipmi::deleteAllDbusObjects(bus, - ipmi::network::ROOT, - ipmi::network::IP_INTERFACE, - ethIp); + // delete all the ipv4 addresses + ipmi::deleteAllDbusObjects(bus, ipmi::network::ROOT, + ipmi::network::IP_INTERFACE, ethIp); if (vlanID) { - ipmi::network::createVLAN(bus, - ipmi::network::SERVICE, - ipmi::network::ROOT, - ethdevice, - vlanID); + ipmi::network::createVLAN(bus, ipmi::network::SERVICE, + ipmi::network::ROOT, ethdevice, vlanID); auto networkInterfaceObject = ipmi::getDbusObject( - bus, - ipmi::network::VLAN_INTERFACE, - ipmi::network::ROOT); + bus, ipmi::network::VLAN_INTERFACE, ipmi::network::ROOT); - networkInterfacePath = networkInterfaceObject.first; + networkInterfacePath = networkInterfaceObject.first; } if (channelConf->ipsrc == ipmi::network::IPOrigin::DHCP) { - ipmi::setDbusProperty(bus, - ipmi::network::SERVICE, - networkInterfacePath, - ipmi::network::ETHERNET_INTERFACE, - "DHCPEnabled", - true); + ipmi::setDbusProperty( + bus, ipmi::network::SERVICE, networkInterfacePath, + ipmi::network::ETHERNET_INTERFACE, "DHCPEnabled", true); } else { - //change the mode to static - ipmi::setDbusProperty(bus, - ipmi::network::SERVICE, - networkInterfacePath, - ipmi::network::ETHERNET_INTERFACE, - "DHCPEnabled", - false); + // change the mode to static + ipmi::setDbusProperty( + bus, ipmi::network::SERVICE, networkInterfacePath, + ipmi::network::ETHERNET_INTERFACE, "DHCPEnabled", false); if (!ipaddress.empty()) { - ipmi::network::createIP(bus, - ipmi::network::SERVICE, - networkInterfacePath, - ipv4Protocol, - ipaddress, - prefix); + ipmi::network::createIP(bus, ipmi::network::SERVICE, + networkInterfacePath, ipv4Protocol, + ipaddress, prefix); } if (!gateway.empty()) { - ipmi::setDbusProperty(bus, - systemObject.second, + ipmi::setDbusProperty(bus, systemObject.second, systemObject.first, ipmi::network::SYSTEMCONFIG_INTERFACE, - "DefaultGateway", - std::string(gateway)); + "DefaultGateway", std::string(gateway)); } } - } catch (InternalFailure& e) { - log("Failed to set network data", - entry("PREFIX=%d", prefix), - entry("ADDRESS=%s", ipaddress.c_str()), - entry("GATEWAY=%s", gateway.c_str()), - entry("VLANID=%d", vlanID), - entry("IPSRC=%d", channelConf->ipsrc)); + log( + "Failed to set network data", entry("PREFIX=%d", prefix), + entry("ADDRESS=%s", ipaddress.c_str()), + entry("GATEWAY=%s", gateway.c_str()), entry("VLANID=%d", vlanID), + entry("IPSRC=%d", channelConf->ipsrc)); commit(); } @@ -1016,7 +941,7 @@ void applyChanges(int channel) void commitNetworkChanges() { - for (const auto &channel : channelConfig) + for (const auto& channel : channelConfig) { if (channel.second->flush) { @@ -1030,14 +955,11 @@ void createNetworkTimer() if (!networkTimer) { std::function networkTimerCallback( - std::bind(&commitNetworkChanges)); + std::bind(&commitNetworkChanges)); - networkTimer = - std::make_unique( - ipmid_get_sd_event_connection(), - networkTimerCallback); + networkTimer = std::make_unique( + ipmid_get_sd_event_connection(), networkTimerCallback); } - } void register_netfn_transport_functions() @@ -1046,16 +968,16 @@ void register_netfn_transport_functions() // so creating it here. createNetworkTimer(); // - ipmi_register_callback(NETFUN_TRANSPORT, IPMI_CMD_WILDCARD, NULL, ipmi_transport_wildcard, - PRIVILEGE_USER); + ipmi_register_callback(NETFUN_TRANSPORT, IPMI_CMD_WILDCARD, NULL, + ipmi_transport_wildcard, PRIVILEGE_USER); // - ipmi_register_callback(NETFUN_TRANSPORT, IPMI_CMD_SET_LAN, NULL, ipmi_transport_set_lan, - PRIVILEGE_ADMIN); + ipmi_register_callback(NETFUN_TRANSPORT, IPMI_CMD_SET_LAN, NULL, + ipmi_transport_set_lan, PRIVILEGE_ADMIN); // - ipmi_register_callback(NETFUN_TRANSPORT, IPMI_CMD_GET_LAN, NULL, ipmi_transport_get_lan, - PRIVILEGE_OPERATOR); + ipmi_register_callback(NETFUN_TRANSPORT, IPMI_CMD_GET_LAN, NULL, + ipmi_transport_get_lan, PRIVILEGE_OPERATOR); return; } diff --git a/transporthandler.hpp b/transporthandler.hpp index 432bd68..a47b908 100644 --- a/transporthandler.hpp +++ b/transporthandler.hpp @@ -1,6 +1,7 @@ #pragma once #include "types.hpp" + #include // IPMI commands for Transport net functions. enum ipmi_netfn_storage_cmds @@ -17,22 +18,22 @@ enum ipmi_transport_return_codes }; // Parameters -static const int LAN_PARM_INPROGRESS = 0; +static const int LAN_PARM_INPROGRESS = 0; static const int LAN_PARM_AUTHSUPPORT = 1; static const int LAN_PARM_AUTHENABLES = 2; -static const int LAN_PARM_IP = 3; -static const int LAN_PARM_IPSRC = 4; -static const int LAN_PARM_MAC = 5; -static const int LAN_PARM_SUBNET = 6; -static const int LAN_PARM_GATEWAY = 12; -static const int LAN_PARM_VLAN = 20; -static const int CIPHER_SUITE_COUNT = 22; +static const int LAN_PARM_IP = 3; +static const int LAN_PARM_IPSRC = 4; +static const int LAN_PARM_MAC = 5; +static const int LAN_PARM_SUBNET = 6; +static const int LAN_PARM_GATEWAY = 12; +static const int LAN_PARM_VLAN = 20; +static const int CIPHER_SUITE_COUNT = 22; static const int CIPHER_SUITE_ENTRIES = 23; constexpr uint8_t SET_COMPLETE = 0; constexpr uint8_t SET_IN_PROGRESS = 1; -constexpr uint8_t SET_COMMIT_WRITE = 2; //Optional -constexpr uint8_t SET_IN_PROGRESS_RESERVED = 3; //Reserved +constexpr uint8_t SET_COMMIT_WRITE = 2; // Optional +constexpr uint8_t SET_IN_PROGRESS_RESERVED = 3; // Reserved const int CHANNEL_MASK = 0x0f; const int NUM_CHANNELS = 0x0f; diff --git a/types.hpp b/types.hpp index b6bab94..431d5b6 100644 --- a/types.hpp +++ b/types.hpp @@ -3,9 +3,8 @@ #include #include -#include - #include +#include namespace ipmi { @@ -22,8 +21,8 @@ using Value = sdbusplus::message::variant; -using ObjectTree = std::map>>; +using ObjectTree = + std::map>>; using InterfaceList = std::vector; @@ -43,16 +42,16 @@ using Offset = uint8_t; */ enum class SkipAssertion { - NONE, //No skip defined - ASSERT, //Skip on Assert - DEASSERT, //Skip on Deassert + NONE, // No skip defined + ASSERT, // Skip on Assert + DEASSERT, // Skip on Deassert }; struct Values { - SkipAssertion skip; - Value assert; - Value deassert; + SkipAssertion skip; + Value assert; + Value deassert; }; /** @@ -61,8 +60,8 @@ struct Values */ struct PreReqValues { - Value assert; //Value in case of assert. - Value deassert; //Value in case of deassert. + Value assert; // Value in case of assert. + Value deassert; // Value in case of deassert. }; using PreReqOffsetValueMap = std::map; @@ -93,17 +92,17 @@ struct SetSensorReadingReq */ struct GetReadingResponse { - uint8_t reading; //!< Sensor reading. - uint8_t operation; //!< Sensor scanning status / reading state. - uint8_t assertOffset0_7; //!< Discrete assertion states(0-7). - uint8_t assertOffset8_14; //!< Discrete assertion states(8-14). + uint8_t reading; //!< Sensor reading. + uint8_t operation; //!< Sensor scanning status / reading state. + uint8_t assertOffset0_7; //!< Discrete assertion states(0-7). + uint8_t assertOffset8_14; //!< Discrete assertion states(8-14). } __attribute__((packed)); constexpr auto inventoryRoot = "/xyz/openbmc_project/inventory"; using GetSensorResponse = std::array; -using OffsetValueMap = std::map; +using OffsetValueMap = std::map; using DbusPropertyValues = std::pair; @@ -126,47 +125,47 @@ using SensorName = std::string; enum class Mutability { - Read = 1 << 0, - Write = 1 << 1, + Read = 1 << 0, + Write = 1 << 1, }; inline Mutability operator|(Mutability lhs, Mutability rhs) { - return static_cast( - static_cast(lhs) | static_cast(rhs)); + return static_cast(static_cast(lhs) | + static_cast(rhs)); } inline Mutability operator&(Mutability lhs, Mutability rhs) { - return static_cast( - static_cast(lhs) & static_cast(rhs)); + return static_cast(static_cast(lhs) & + static_cast(rhs)); } struct Info { - EntityType entityType; - EntityInst instance; - Type sensorType; - InstancePath sensorPath; - DbusInterface sensorInterface; - ReadingType sensorReadingType; - Multiplier coefficientM; - OffsetB coefficientB; - Exponent exponentB; - ScaledOffset scaledOffset; - Exponent exponentR; - bool hasScale; - Scale scale; - Unit unit; - std::function updateFunc; - std::function getFunc; - Mutability mutability; - std::function sensorNameFunc; - DbusInterfaceMap propertyInterfaces; + EntityType entityType; + EntityInst instance; + Type sensorType; + InstancePath sensorPath; + DbusInterface sensorInterface; + ReadingType sensorReadingType; + Multiplier coefficientM; + OffsetB coefficientB; + Exponent exponentB; + ScaledOffset scaledOffset; + Exponent exponentR; + bool hasScale; + Scale scale; + Unit unit; + std::function updateFunc; + std::function getFunc; + Mutability mutability; + std::function sensorNameFunc; + DbusInterfaceMap propertyInterfaces; }; using Id = uint8_t; -using IdInfoMap = std::map; +using IdInfoMap = std::map; using PropertyMap = ipmi::PropertyMap; @@ -179,10 +178,10 @@ using IpmiUpdateData = sdbusplus::message::message; struct SelData { - Id sensorID; - Type sensorType; - ReadingType eventReadingType; - Offset eventOffset; + Id sensorID; + Type sensorType; + ReadingType eventReadingType; + Offset eventOffset; }; using InventoryPath = std::string; @@ -197,7 +196,7 @@ enum class ThresholdMask CRITICAL_HIGH_MASK = 0x10, }; -}// namespace sensor +} // namespace sensor namespace network { @@ -222,13 +221,12 @@ constexpr auto MASK_32_BIT = 0xFFFFFFFF; constexpr auto VLAN_ID_MASK = 0x00000FFF; constexpr auto VLAN_ENABLE_MASK = 0x8000; -enum class IPOrigin: uint8_t +enum class IPOrigin : uint8_t { UNSPECIFIED = 0, STATIC = 1, DHCP = 2, }; - -}//namespace network -}//namespace ipmi +} // namespace network +} // namespace ipmi diff --git a/utils.cpp b/utils.cpp index bfe924c..225b1cc 100644 --- a/utils.cpp +++ b/utils.cpp @@ -1,12 +1,13 @@ #include "utils.hpp" -#include -#include -#include "xyz/openbmc_project/Common/error.hpp" #include #include #include +#include +#include +#include + namespace ipmi { @@ -17,13 +18,13 @@ namespace network { /** @brief checks if the given ip is Link Local Ip or not. - * @param[in] ipaddress - IPAddress. - */ + * @param[in] ipaddress - IPAddress. + */ bool isLinkLocalIP(const std::string& ipaddress); -} +} // namespace network -//TODO There may be cases where an interface is implemented by multiple +// TODO There may be cases where an interface is implemented by multiple // objects,to handle such cases we are interested on that object // which are on interested busname. // Currently mapper doesn't give the readable busname(gives busid) so we can't @@ -39,10 +40,8 @@ DbusObjectInfo getDbusObject(sdbusplus::bus::bus& bus, auto depth = 0; - auto mapperCall = bus.new_method_call(MAPPER_BUS_NAME, - MAPPER_OBJ, - MAPPER_INTF, - "GetSubTree"); + auto mapperCall = bus.new_method_call(MAPPER_BUS_NAME, MAPPER_OBJ, + MAPPER_INTF, "GetSubTree"); mapperCall.append(serviceRoot, depth, interfaces); @@ -66,9 +65,10 @@ DbusObjectInfo getDbusObject(sdbusplus::bus::bus& bus, DbusObjectInfo objectInfo; // if match is empty then return the first object - if(match == "") + if (match == "") { - objectInfo = std::make_pair(objectTree.begin()->first, + objectInfo = std::make_pair( + objectTree.begin()->first, std::move(objectTree.begin()->second.begin()->first)); return objectInfo; } @@ -77,23 +77,22 @@ DbusObjectInfo getDbusObject(sdbusplus::bus::bus& bus, auto objectFound = false; for (auto& object : objectTree) { - if(object.first.find(match) != std::string::npos) + if (object.first.find(match) != std::string::npos) { objectFound = true; objectInfo = make_pair(object.first, - std::move(object.second.begin()->first)); + std::move(object.second.begin()->first)); break; } } - if(!objectFound) + if (!objectFound) { log("Failed to find object which matches", entry("MATCH=%s", match.c_str())); elog(); } return objectInfo; - } DbusObjectInfo getIPObject(sdbusplus::bus::bus& bus, @@ -115,13 +114,10 @@ DbusObjectInfo getIPObject(sdbusplus::bus::bus& bus, for (auto& object : objectTree) { auto variant = ipmi::getDbusProperty( - bus, - object.second.begin()->first, - object.first, - ipmi::network::IP_INTERFACE, - "Address"); + bus, object.second.begin()->first, object.first, + ipmi::network::IP_INTERFACE, "Address"); - objectInfo = std::make_pair(object.first, object.second.begin()->first); + objectInfo = std::make_pair(object.first, object.second.begin()->first); // if LinkLocalIP found look for Non-LinkLocalIP if (ipmi::network::isLinkLocalIP(variant.get())) @@ -136,20 +132,15 @@ DbusObjectInfo getIPObject(sdbusplus::bus::bus& bus, return objectInfo; } -Value getDbusProperty(sdbusplus::bus::bus& bus, - const std::string& service, - const std::string& objPath, - const std::string& interface, +Value getDbusProperty(sdbusplus::bus::bus& bus, const std::string& service, + const std::string& objPath, const std::string& interface, const std::string& property) { Value value; - auto method = bus.new_method_call( - service.c_str(), - objPath.c_str(), - PROP_INTF, - METHOD_GET); + auto method = bus.new_method_call(service.c_str(), objPath.c_str(), + PROP_INTF, METHOD_GET); method.append(interface, property); @@ -157,10 +148,10 @@ Value getDbusProperty(sdbusplus::bus::bus& bus, if (reply.is_method_error()) { - log("Failed to get property", - entry("PROPERTY=%s", property.c_str()), - entry("PATH=%s", objPath.c_str()), - entry("INTERFACE=%s", interface.c_str())); + log("Failed to get property", + entry("PROPERTY=%s", property.c_str()), + entry("PATH=%s", objPath.c_str()), + entry("INTERFACE=%s", interface.c_str())); elog(); } @@ -176,11 +167,8 @@ PropertyMap getAllDbusProperties(sdbusplus::bus::bus& bus, { PropertyMap properties; - auto method = bus.new_method_call( - service.c_str(), - objPath.c_str(), - PROP_INTF, - METHOD_GET_ALL); + auto method = bus.new_method_call(service.c_str(), objPath.c_str(), + PROP_INTF, METHOD_GET_ALL); method.append(interface); @@ -188,10 +176,10 @@ PropertyMap getAllDbusProperties(sdbusplus::bus::bus& bus, if (reply.is_method_error()) { - log("Failed to get all properties", - entry("PATH=%s", objPath.c_str()), - entry("INTERFACE=%s", interface.c_str())); - elog(); + log("Failed to get all properties", + entry("PATH=%s", objPath.c_str()), + entry("INTERFACE=%s", interface.c_str())); + elog(); } reply.read(properties); @@ -199,42 +187,34 @@ PropertyMap getAllDbusProperties(sdbusplus::bus::bus& bus, } ObjectValueTree getManagedObjects(sdbusplus::bus::bus& bus, - const std::string& service, - const std::string& objPath) + const std::string& service, + const std::string& objPath) { ipmi::ObjectValueTree interfaces; - auto method = bus.new_method_call( - service.c_str(), - objPath.c_str(), - "org.freedesktop.DBus.ObjectManager", - "GetManagedObjects"); + auto method = bus.new_method_call(service.c_str(), objPath.c_str(), + "org.freedesktop.DBus.ObjectManager", + "GetManagedObjects"); auto reply = bus.call(method); if (reply.is_method_error()) { - log("Failed to get managed objects", - entry("PATH=%s", objPath.c_str())); - elog(); + log("Failed to get managed objects", + entry("PATH=%s", objPath.c_str())); + elog(); } reply.read(interfaces); return interfaces; } -void setDbusProperty(sdbusplus::bus::bus& bus, - const std::string& service, - const std::string& objPath, - const std::string& interface, - const std::string& property, - const Value& value) +void setDbusProperty(sdbusplus::bus::bus& bus, const std::string& service, + const std::string& objPath, const std::string& interface, + const std::string& property, const Value& value) { - auto method = bus.new_method_call( - service.c_str(), - objPath.c_str(), - PROP_INTF, - METHOD_SET); + auto method = bus.new_method_call(service.c_str(), objPath.c_str(), + PROP_INTF, METHOD_SET); method.append(interface, property, value); @@ -242,24 +222,22 @@ void setDbusProperty(sdbusplus::bus::bus& bus, { log("Failed to set property", entry("PROPERTY=%s", property.c_str()), - entry("PATH=%s",objPath.c_str()), - entry("INTERFACE=%s",interface.c_str())); + entry("PATH=%s", objPath.c_str()), + entry("INTERFACE=%s", interface.c_str())); elog(); } - } - -ServiceCache::ServiceCache(const std::string& intf, const std::string& path) - : intf(intf), path(path), cachedService(std::experimental::nullopt), - cachedBusName(std::experimental::nullopt) +ServiceCache::ServiceCache(const std::string& intf, const std::string& path) : + intf(intf), path(path), cachedService(std::experimental::nullopt), + cachedBusName(std::experimental::nullopt) { } -ServiceCache::ServiceCache(std::string&& intf, std::string&& path) - : intf(std::move(intf)), path(std::move(path)), - cachedService(std::experimental::nullopt), - cachedBusName(std::experimental::nullopt) +ServiceCache::ServiceCache(std::string&& intf, std::string&& path) : + intf(std::move(intf)), path(std::move(path)), + cachedService(std::experimental::nullopt), + cachedBusName(std::experimental::nullopt) { } @@ -279,11 +257,12 @@ void ServiceCache::invalidate() cachedService = std::experimental::nullopt; } -sdbusplus::message::message ServiceCache::newMethodCall( - sdbusplus::bus::bus& bus, const char *intf, const char *method) +sdbusplus::message::message + ServiceCache::newMethodCall(sdbusplus::bus::bus& bus, const char* intf, + const char* method) { - return bus.new_method_call(getService(bus).c_str(), path.c_str(), - intf, method); + return bus.new_method_call(getService(bus).c_str(), path.c_str(), intf, + method); } bool ServiceCache::isValid(sdbusplus::bus::bus& bus) const @@ -291,14 +270,13 @@ bool ServiceCache::isValid(sdbusplus::bus::bus& bus) const return cachedService && cachedBusName == bus.get_unique_name(); } -std::string getService(sdbusplus::bus::bus& bus, - const std::string& intf, +std::string getService(sdbusplus::bus::bus& bus, const std::string& intf, const std::string& path) { - auto mapperCall = bus.new_method_call("xyz.openbmc_project.ObjectMapper", - "/xyz/openbmc_project/object_mapper", - "xyz.openbmc_project.ObjectMapper", - "GetObject"); + auto mapperCall = + bus.new_method_call("xyz.openbmc_project.ObjectMapper", + "/xyz/openbmc_project/object_mapper", + "xyz.openbmc_project.ObjectMapper", "GetObject"); mapperCall.append(path); mapperCall.append(std::vector({intf})); @@ -331,10 +309,8 @@ ipmi::ObjectTree getAllDbusObjects(sdbusplus::bus::bus& bus, auto depth = 0; - auto mapperCall = bus.new_method_call(MAPPER_BUS_NAME, - MAPPER_OBJ, - MAPPER_INTF, - "GetSubTree"); + auto mapperCall = bus.new_method_call(MAPPER_BUS_NAME, MAPPER_OBJ, + MAPPER_INTF, "GetSubTree"); mapperCall.append(serviceRoot, depth, interfaces); @@ -342,7 +318,7 @@ ipmi::ObjectTree getAllDbusObjects(sdbusplus::bus::bus& bus, if (mapperReply.is_method_error()) { log("Error in mapper call", - entry("SERVICEROOT=%s",serviceRoot.c_str()), + entry("SERVICEROOT=%s", serviceRoot.c_str()), entry("INTERFACE=%s", interface.c_str())); elog(); @@ -373,14 +349,13 @@ void deleteAllDbusObjects(sdbusplus::bus::bus& bus, { try { - auto objectTree = getAllDbusObjects(bus, serviceRoot, interface, match); + auto objectTree = getAllDbusObjects(bus, serviceRoot, interface, match); for (auto& object : objectTree) { - method_no_args::callDbusMethod(bus, - object.second.begin()->first, - object.first, - DELETE_INTERFACE, "Delete"); + method_no_args::callDbusMethod(bus, object.second.begin()->first, + object.first, DELETE_INTERFACE, + "Delete"); } } catch (InternalFailure& e) @@ -391,12 +366,10 @@ void deleteAllDbusObjects(sdbusplus::bus::bus& bus, } } -ObjectTree getAllAncestors(sdbusplus::bus::bus& bus, - const std::string& path, +ObjectTree getAllAncestors(sdbusplus::bus::bus& bus, const std::string& path, InterfaceList&& interfaces) { - auto convertToString = [](InterfaceList& interfaces) -> std::string - { + auto convertToString = [](InterfaceList& interfaces) -> std::string { std::string intfStr; for (const auto& intf : interfaces) { @@ -405,19 +378,16 @@ ObjectTree getAllAncestors(sdbusplus::bus::bus& bus, return intfStr; }; - auto mapperCall = bus.new_method_call(MAPPER_BUS_NAME, - MAPPER_OBJ, - MAPPER_INTF, - "GetAncestors"); + auto mapperCall = bus.new_method_call(MAPPER_BUS_NAME, MAPPER_OBJ, + MAPPER_INTF, "GetAncestors"); mapperCall.append(path, interfaces); auto mapperReply = bus.call(mapperCall); if (mapperReply.is_method_error()) { - log("Error in mapper call", - entry("PATH=%s", path.c_str()), - entry("INTERFACES=%s", - convertToString(interfaces).c_str())); + log( + "Error in mapper call", entry("PATH=%s", path.c_str()), + entry("INTERFACES=%s", convertToString(interfaces).c_str())); elog(); } @@ -427,10 +397,10 @@ ObjectTree getAllAncestors(sdbusplus::bus::bus& bus, if (objectTree.empty()) { - log("No Object has implemented the interface", - entry("PATH=%s", path.c_str()), - entry("INTERFACES=%s", - convertToString(interfaces).c_str())); + log( + "No Object has implemented the interface", + entry("PATH=%s", path.c_str()), + entry("INTERFACES=%s", convertToString(interfaces).c_str())); elog(); } @@ -440,18 +410,13 @@ ObjectTree getAllAncestors(sdbusplus::bus::bus& bus, namespace method_no_args { -void callDbusMethod(sdbusplus::bus::bus& bus, - const std::string& service, - const std::string& objPath, - const std::string& interface, +void callDbusMethod(sdbusplus::bus::bus& bus, const std::string& service, + const std::string& objPath, const std::string& interface, const std::string& method) { - auto busMethod = bus.new_method_call( - service.c_str(), - objPath.c_str(), - interface.c_str(), - method.c_str()); + auto busMethod = bus.new_method_call(service.c_str(), objPath.c_str(), + interface.c_str(), method.c_str()); auto reply = bus.call(busMethod); @@ -465,7 +430,7 @@ void callDbusMethod(sdbusplus::bus::bus& bus, } } -}// namespace method_no_args +} // namespace method_no_args namespace network { @@ -475,20 +440,14 @@ bool isLinkLocalIP(const std::string& address) return address.find(IPV4_PREFIX) == 0 || address.find(IPV6_PREFIX) == 0; } -void createIP(sdbusplus::bus::bus& bus, - const std::string& service, - const std::string& objPath, - const std::string& protocolType, - const std::string& ipaddress, - uint8_t prefix) +void createIP(sdbusplus::bus::bus& bus, const std::string& service, + const std::string& objPath, const std::string& protocolType, + const std::string& ipaddress, uint8_t prefix) { std::string gateway = ""; - auto busMethod = bus.new_method_call( - service.c_str(), - objPath.c_str(), - IP_CREATE_INTERFACE, - "IP"); + auto busMethod = bus.new_method_call(service.c_str(), objPath.c_str(), + IP_CREATE_INTERFACE, "IP"); busMethod.append(protocolType, ipaddress, prefix, gateway); @@ -496,25 +455,18 @@ void createIP(sdbusplus::bus::bus& bus, if (reply.is_method_error()) { - log("Failed to execute method", - entry("METHOD=%s", "IP"), + log("Failed to execute method", entry("METHOD=%s", "IP"), entry("PATH=%s", objPath.c_str())); elog(); } - } -void createVLAN(sdbusplus::bus::bus& bus, - const std::string& service, - const std::string& objPath, - const std::string& interfaceName, +void createVLAN(sdbusplus::bus::bus& bus, const std::string& service, + const std::string& objPath, const std::string& interfaceName, uint32_t vlanID) { - auto busMethod = bus.new_method_call( - service.c_str(), - objPath.c_str(), - VLAN_CREATE_INTERFACE, - "VLAN"); + auto busMethod = bus.new_method_call(service.c_str(), objPath.c_str(), + VLAN_CREATE_INTERFACE, "VLAN"); busMethod.append(interfaceName, vlanID); @@ -522,12 +474,10 @@ void createVLAN(sdbusplus::bus::bus& bus, if (reply.is_method_error()) { - log("Failed to execute method", - entry("METHOD=%s", "VLAN"), + log("Failed to execute method", entry("METHOD=%s", "VLAN"), entry("PATH=%s", objPath.c_str())); elog(); } - } uint8_t toPrefix(int addressFamily, const std::string& subnetMask) @@ -537,7 +487,7 @@ uint8_t toPrefix(int addressFamily, const std::string& subnetMask) return 0; } - uint32_t buff {}; + uint32_t buff{}; auto rc = inet_pton(addressFamily, subnetMask.c_str(), &buff); if (rc <= 0) @@ -549,7 +499,8 @@ uint8_t toPrefix(int addressFamily, const std::string& subnetMask) buff = be32toh(buff); // total no of bits - total no of leading zero == total no of ones - if (((sizeof(buff) * 8) - (__builtin_ctz(buff))) == __builtin_popcount(buff)) + if (((sizeof(buff) * 8) - (__builtin_ctz(buff))) == + __builtin_popcount(buff)) { return __builtin_popcount(buff); } @@ -569,8 +520,7 @@ uint32_t getVLAN(const std::string& path) uint32_t vlanID = 0; try { - auto intfObjectPath = path.substr(0, - path.find(IP_TYPE) - 1); + auto intfObjectPath = path.substr(0, path.find(IP_TYPE) - 1); auto intfName = intfObjectPath.substr(intfObjectPath.rfind("/") + 1); @@ -581,10 +531,10 @@ uint32_t getVLAN(const std::string& path) vlanID = std::stoul(str); } } - catch (std::exception & e) + catch (std::exception& e) { log("Exception occurred during getVLAN", - entry("PATH=%s",path.c_str()), + entry("PATH=%s", path.c_str()), entry("EXCEPTION=%s", e.what())); } return vlanID; diff --git a/utils.hpp b/utils.hpp index 535ea66..8b69b09 100644 --- a/utils.hpp +++ b/utils.hpp @@ -1,9 +1,9 @@ #pragma once +#include "types.hpp" + #include #include -#include "types.hpp" - namespace ipmi { @@ -29,54 +29,56 @@ constexpr auto METHOD_SET = "Set"; * require. This class reduces the number of such calls by caching * the lookup for a specific service. */ -class ServiceCache { - public: - /** @brief Creates a new service cache for the given interface - * and path. - * - * @param[in] intf - The interface used for each lookup - * @param[in] path - The path used for each lookup - */ - ServiceCache(const std::string& intf, const std::string& path); - ServiceCache(std::string&& intf, std::string&& path); - - /** @brief Gets the service name from the cache or does in a - * lookup when invalid. - * - * @param[in] bus - The bus associated with and used for looking - * up the service. - */ - const std::string& getService(sdbusplus::bus::bus& bus); - - /** @brief Invalidates the current service name */ - void invalidate(); - - /** @brief A wrapper around sdbusplus bus.new_method_call - * - * @param[in] bus - The bus used for calling the method - * @param[in] intf - The interface containing the method - * @param[in] method - The method name - * @return The message containing the method call. - */ - sdbusplus::message::message newMethodCall(sdbusplus::bus::bus& bus, - const char *intf, - const char *method); - - /** @brief Check to see if the current cache is valid - * - * @param[in] bus - The bus used for the service lookup - * @return True if the cache is valid false otherwise. - */ - bool isValid(sdbusplus::bus::bus& bus) const; - private: - /** @brief DBUS interface provided by the service */ - const std::string intf; - /** @brief DBUS path provided by the service */ - const std::string path; - /** @brief The name of the service if valid */ - std::experimental::optional cachedService; - /** @brief The name of the bus used in the service lookup */ - std::experimental::optional cachedBusName; +class ServiceCache +{ + public: + /** @brief Creates a new service cache for the given interface + * and path. + * + * @param[in] intf - The interface used for each lookup + * @param[in] path - The path used for each lookup + */ + ServiceCache(const std::string& intf, const std::string& path); + ServiceCache(std::string&& intf, std::string&& path); + + /** @brief Gets the service name from the cache or does in a + * lookup when invalid. + * + * @param[in] bus - The bus associated with and used for looking + * up the service. + */ + const std::string& getService(sdbusplus::bus::bus& bus); + + /** @brief Invalidates the current service name */ + void invalidate(); + + /** @brief A wrapper around sdbusplus bus.new_method_call + * + * @param[in] bus - The bus used for calling the method + * @param[in] intf - The interface containing the method + * @param[in] method - The method name + * @return The message containing the method call. + */ + sdbusplus::message::message newMethodCall(sdbusplus::bus::bus& bus, + const char* intf, + const char* method); + + /** @brief Check to see if the current cache is valid + * + * @param[in] bus - The bus used for the service lookup + * @return True if the cache is valid false otherwise. + */ + bool isValid(sdbusplus::bus::bus& bus) const; + + private: + /** @brief DBUS interface provided by the service */ + const std::string intf; + /** @brief DBUS path provided by the service */ + const std::string path; + /** @brief The name of the service if valid */ + std::experimental::optional cachedService; + /** @brief The name of the bus used in the service lookup */ + std::experimental::optional cachedBusName; }; /** @@ -87,8 +89,7 @@ class ServiceCache { * @param[in] path - DBUS Object Path * */ -std::string getService(sdbusplus::bus::bus& bus, - const std::string& intf, +std::string getService(sdbusplus::bus::bus& bus, const std::string& intf, const std::string& path); /** @brief Gets the dbus object info implementing the given interface @@ -127,10 +128,8 @@ DbusObjectInfo getIPObject(sdbusplus::bus::bus& bus, * @param[in] property - name of the property. * @return On success returns the value of the property. */ -Value getDbusProperty(sdbusplus::bus::bus& bus, - const std::string& service, - const std::string& objPath, - const std::string& interface, +Value getDbusProperty(sdbusplus::bus::bus& bus, const std::string& service, + const std::string& objPath, const std::string& interface, const std::string& property); /** @brief Gets all the properties associated with the given object @@ -154,8 +153,8 @@ PropertyMap getAllDbusProperties(sdbusplus::bus::bus& bus, * @return On success returns the map of name value pair. */ ObjectValueTree getManagedObjects(sdbusplus::bus::bus& bus, - const std::string& service, - const std::string& objPath); + const std::string& service, + const std::string& objPath); /** @brief Sets the property value of the given object. * @param[in] bus - DBUS Bus Object. @@ -165,12 +164,9 @@ ObjectValueTree getManagedObjects(sdbusplus::bus::bus& bus, * @param[in] property - name of the property. * @param[in] value - value which needs to be set. */ -void setDbusProperty(sdbusplus::bus::bus& bus, - const std::string& service, - const std::string& objPath, - const std::string& interface, - const std::string& property, - const Value& value); +void setDbusProperty(sdbusplus::bus::bus& bus, const std::string& service, + const std::string& objPath, const std::string& interface, + const std::string& property, const Value& value); /** @brief Gets all the dbus objects from the given service root * which matches the object identifier. @@ -204,8 +200,7 @@ void deleteAllDbusObjects(sdbusplus::bus::bus& bus, * @param[in] interfaces - Dbus interface list. * @return map of object path and service info. */ -ObjectTree getAllAncestors(sdbusplus::bus::bus& bus, - const std::string& path, +ObjectTree getAllAncestors(sdbusplus::bus::bus& bus, const std::string& path, InterfaceList&& interfaces); /** @struct VariantToDoubleVisitor @@ -216,14 +211,14 @@ struct VariantToDoubleVisitor { template std::enable_if_t::value, double> - operator()(const T &t) const + operator()(const T& t) const { return static_cast(t); } template std::enable_if_t::value, double> - operator()(const T &t) const + operator()(const T& t) const { throw std::invalid_argument("Cannot translate type to double"); } @@ -239,13 +234,11 @@ namespace method_no_args * @param[in] interface - Dbus interface. * @param[in] method - Dbus method. */ -void callDbusMethod(sdbusplus::bus::bus& bus, - const std::string& service, - const std::string& objPath, - const std::string& interface, +void callDbusMethod(sdbusplus::bus::bus& bus, const std::string& service, + const std::string& objPath, const std::string& interface, const std::string& method); -} //namespace method_no_args +} // namespace method_no_args namespace network { @@ -257,10 +250,13 @@ constexpr auto IPV4_PREFIX = "169.254"; constexpr auto IPV6_PREFIX = "fe80"; constexpr auto IP_INTERFACE = "xyz.openbmc_project.Network.IP"; constexpr auto MAC_INTERFACE = "xyz.openbmc_project.Network.MACAddress"; -constexpr auto SYSTEMCONFIG_INTERFACE = "xyz.openbmc_project.Network.SystemConfiguration"; -constexpr auto ETHERNET_INTERFACE = "xyz.openbmc_project.Network.EthernetInterface"; +constexpr auto SYSTEMCONFIG_INTERFACE = + "xyz.openbmc_project.Network.SystemConfiguration"; +constexpr auto ETHERNET_INTERFACE = + "xyz.openbmc_project.Network.EthernetInterface"; constexpr auto IP_CREATE_INTERFACE = "xyz.openbmc_project.Network.IP.Create"; -constexpr auto VLAN_CREATE_INTERFACE = "xyz.openbmc_project.Network.VLAN.Create"; +constexpr auto VLAN_CREATE_INTERFACE = + "xyz.openbmc_project.Network.VLAN.Create"; constexpr auto VLAN_INTERFACE = "xyz.openbmc_project.Network.VLAN"; /* @brief converts the given subnet into prefix notation. @@ -270,7 +266,6 @@ constexpr auto VLAN_INTERFACE = "xyz.openbmc_project.Network.VLAN"; */ uint8_t toPrefix(int addressFamily, const std::string& subnetMask); - /** @brief Sets the ip on the system. * @param[in] bus - DBUS Bus Object. * @param[in] service - Dbus service name. @@ -279,12 +274,9 @@ uint8_t toPrefix(int addressFamily, const std::string& subnetMask); * @param[in] ipaddress - IPaddress. * @param[in] prefix - Prefix length. */ -void createIP(sdbusplus::bus::bus& bus, - const std::string& service, - const std::string& objPath, - const std::string& protocolType, - const std::string& ipaddress, - uint8_t prefix); +void createIP(sdbusplus::bus::bus& bus, const std::string& service, + const std::string& objPath, const std::string& protocolType, + const std::string& ipaddress, uint8_t prefix); /** @brief Creates the VLAN on the given interface. * @param[in] bus - DBUS Bus Object. @@ -293,10 +285,8 @@ void createIP(sdbusplus::bus::bus& bus, * @param[in] interface - EthernetInterface. * @param[in] vlanID - Vlan ID. */ -void createVLAN(sdbusplus::bus::bus& bus, - const std::string& service, - const std::string& objPath, - const std::string& interface, +void createVLAN(sdbusplus::bus::bus& bus, const std::string& service, + const std::string& objPath, const std::string& interface, uint32_t vlanID); /** @brief Gets the vlan id from the given object path. @@ -304,7 +294,5 @@ void createVLAN(sdbusplus::bus::bus& bus, */ uint32_t getVLAN(const std::string& path); -} //namespace network +} // namespace network } // namespace ipmi - - -- cgit v1.2.1