blob: 929e92211a617bd3a06a0f95fb54d0b44e92f70d [file] [log] [blame]
Patrick Venture0b02be92018-08-31 11:55:55 -07001#include <arpa/inet.h>
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05302#include <fcntl.h>
Xo Wang87651332017-08-11 10:17:59 -07003#include <limits.h>
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05304#include <linux/i2c-dev.h>
5#include <linux/i2c.h>
Patrick Venture0b02be92018-08-31 11:55:55 -07006#include <mapper.h>
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05307#include <sys/ioctl.h>
8#include <sys/stat.h>
9#include <sys/types.h>
Patrick Venture0b02be92018-08-31 11:55:55 -070010#include <systemd/sd-bus.h>
Xo Wang87651332017-08-11 10:17:59 -070011#include <unistd.h>
Patrick Venture0b02be92018-08-31 11:55:55 -070012
Patrick Venture3a5071a2018-09-12 13:27:42 -070013#include <algorithm>
Vernon Mauery0120b682019-03-25 13:08:54 -070014#include <app/channel.hpp>
15#include <app/watchdog.hpp>
16#include <apphandler.hpp>
Patrick Venture3a5071a2018-09-12 13:27:42 -070017#include <array>
18#include <cstddef>
Vernon Mauery0120b682019-03-25 13:08:54 -070019#include <cstdint>
Vernon Mauerybdda8002019-02-26 10:18:51 -080020#include <filesystem>
Patrick Venture3a5071a2018-09-12 13:27:42 -070021#include <fstream>
Vernon Mauery0120b682019-03-25 13:08:54 -070022#include <ipmid/api.hpp>
Vernon Mauery33250242019-03-12 16:49:26 -070023#include <ipmid/types.hpp>
Vernon Mauery6a98fe72019-03-11 15:57:48 -070024#include <ipmid/utils.hpp>
Patrick Venture3a5071a2018-09-12 13:27:42 -070025#include <memory>
Patrick Venture46470a32018-09-07 19:26:25 -070026#include <nlohmann/json.hpp>
Patrick Venture3a5071a2018-09-12 13:27:42 -070027#include <phosphor-logging/elog-errors.hpp>
28#include <phosphor-logging/log.hpp>
William A. Kennington III4c008022018-10-12 17:18:14 -070029#include <sdbusplus/message/types.hpp>
Patrick Venture3a5071a2018-09-12 13:27:42 -070030#include <string>
Vernon Mauery0120b682019-03-25 13:08:54 -070031#include <sys_info_param.hpp>
32#include <transporthandler.hpp>
Patrick Venture3a5071a2018-09-12 13:27:42 -070033#include <tuple>
34#include <vector>
35#include <xyz/openbmc_project/Common/error.hpp>
Yong Li18d77262018-10-09 01:59:45 +080036#include <xyz/openbmc_project/Control/Power/ACPIPowerState/server.hpp>
Patrick Venture3a5071a2018-09-12 13:27:42 -070037#include <xyz/openbmc_project/Software/Activation/server.hpp>
38#include <xyz/openbmc_project/Software/Version/server.hpp>
39#include <xyz/openbmc_project/State/BMC/server.hpp>
Ratan Guptab8e99552017-07-27 07:07:48 +053040
Patrick Venture0b02be92018-08-31 11:55:55 -070041extern sd_bus* bus;
vishwabmcba0bd5f2015-09-30 16:50:23 +053042
Alexander Amelkinba19c182018-09-04 15:49:36 +030043constexpr auto bmc_state_interface = "xyz.openbmc_project.State.BMC";
44constexpr auto bmc_state_property = "CurrentBMCState";
Marri Devender Rao5e007a52018-01-08 06:18:36 -060045constexpr auto bmc_interface = "xyz.openbmc_project.Inventory.Item.Bmc";
46constexpr auto bmc_guid_interface = "xyz.openbmc_project.Common.UUID";
47constexpr auto bmc_guid_property = "UUID";
48constexpr auto bmc_guid_len = 16;
49
Nagaraju Goruganti744398d2018-02-20 09:52:00 -060050static constexpr auto redundancyIntf =
51 "xyz.openbmc_project.Software.RedundancyPriority";
Patrick Venture0b02be92018-08-31 11:55:55 -070052static constexpr auto versionIntf = "xyz.openbmc_project.Software.Version";
Nagaraju Goruganti744398d2018-02-20 09:52:00 -060053static constexpr auto activationIntf =
54 "xyz.openbmc_project.Software.Activation";
55static constexpr auto softwareRoot = "/xyz/openbmc_project/software";
56
Chris Austen6caf28b2015-10-13 12:40:40 -050057void register_netfn_app_functions() __attribute__((constructor));
vishwabmcba0bd5f2015-09-30 16:50:23 +053058
Ratan Guptab8e99552017-07-27 07:07:48 +053059using namespace phosphor::logging;
60using namespace sdbusplus::xyz::openbmc_project::Common::Error;
Nagaraju Goruganti744398d2018-02-20 09:52:00 -060061using Version = sdbusplus::xyz::openbmc_project::Software::server::Version;
62using Activation =
63 sdbusplus::xyz::openbmc_project::Software::server::Activation;
Alexander Amelkinba19c182018-09-04 15:49:36 +030064using BMC = sdbusplus::xyz::openbmc_project::State::server::BMC;
Vernon Mauery185b9f82018-07-20 10:52:36 -070065namespace fs = std::filesystem;
Ratan Guptab8e99552017-07-27 07:07:48 +053066
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +053067typedef struct
68{
69 uint8_t busId;
70 uint8_t slaveAddr;
71 uint8_t slaveAddrMask;
72 std::vector<uint8_t> data;
73 std::vector<uint8_t> dataMask;
74} i2cMasterWRWhitelist;
75
76static std::vector<i2cMasterWRWhitelist>& getWRWhitelist()
77{
78 static std::vector<i2cMasterWRWhitelist> wrWhitelist;
79 return wrWhitelist;
80}
81
82static constexpr const char* i2cMasterWRWhitelistFile =
83 "/usr/share/ipmi-providers/master_write_read_white_list.json";
84
85static constexpr uint8_t maxIPMIWriteReadSize = 144;
86static constexpr const char* filtersStr = "filters";
87static constexpr const char* busIdStr = "busId";
88static constexpr const char* slaveAddrStr = "slaveAddr";
89static constexpr const char* slaveAddrMaskStr = "slaveAddrMask";
90static constexpr const char* cmdStr = "command";
91static constexpr const char* cmdMaskStr = "commandMask";
92static constexpr int base_16 = 16;
93
Nagaraju Goruganti744398d2018-02-20 09:52:00 -060094/**
95 * @brief Returns the Version info from primary s/w object
96 *
97 * Get the Version info from the active s/w object which is having high
98 * "Priority" value(a smaller number is a higher priority) and "Purpose"
99 * is "BMC" from the list of all s/w objects those are implementing
100 * RedundancyPriority interface from the given softwareRoot path.
101 *
102 * @return On success returns the Version info from primary s/w object.
103 *
104 */
Vernon Maueryea1c4012019-05-24 13:26:16 -0700105std::string getActiveSoftwareVersionInfo(ipmi::Context::ptr ctx)
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600106{
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600107 std::string revision{};
Vernon Mauery86a50822019-03-25 13:11:36 -0700108 ipmi::ObjectTree objectTree;
109 try
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600110 {
Vernon Mauery86a50822019-03-25 13:11:36 -0700111 objectTree =
Vernon Maueryea1c4012019-05-24 13:26:16 -0700112 ipmi::getAllDbusObjects(*ctx->bus, softwareRoot, redundancyIntf);
Vernon Mauery86a50822019-03-25 13:11:36 -0700113 }
114 catch (sdbusplus::exception::SdBusError& e)
115 {
116 log<level::ERR>("Failed to fetch redundancy object from dbus",
117 entry("INTERFACE=%s", redundancyIntf),
118 entry("ERRMSG=%s", e.what()));
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600119 elog<InternalFailure>();
120 }
121
122 auto objectFound = false;
123 for (auto& softObject : objectTree)
124 {
Vernon Mauery86a50822019-03-25 13:11:36 -0700125 auto service =
Vernon Maueryea1c4012019-05-24 13:26:16 -0700126 ipmi::getService(*ctx->bus, redundancyIntf, softObject.first);
Vernon Mauery86a50822019-03-25 13:11:36 -0700127 auto objValueTree =
Vernon Maueryea1c4012019-05-24 13:26:16 -0700128 ipmi::getManagedObjects(*ctx->bus, service, softwareRoot);
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600129
130 auto minPriority = 0xFF;
131 for (const auto& objIter : objValueTree)
132 {
133 try
134 {
135 auto& intfMap = objIter.second;
136 auto& redundancyPriorityProps = intfMap.at(redundancyIntf);
137 auto& versionProps = intfMap.at(versionIntf);
138 auto& activationProps = intfMap.at(activationIntf);
Vernon Maueryf442e112019-04-09 11:44:36 -0700139 auto priority =
140 std::get<uint8_t>(redundancyPriorityProps.at("Priority"));
William A. Kennington III4c008022018-10-12 17:18:14 -0700141 auto purpose =
Vernon Maueryf442e112019-04-09 11:44:36 -0700142 std::get<std::string>(versionProps.at("Purpose"));
143 auto activation =
144 std::get<std::string>(activationProps.at("Activation"));
William A. Kennington III4c008022018-10-12 17:18:14 -0700145 auto version =
Vernon Maueryf442e112019-04-09 11:44:36 -0700146 std::get<std::string>(versionProps.at("Version"));
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600147 if ((Version::convertVersionPurposeFromString(purpose) ==
148 Version::VersionPurpose::BMC) &&
149 (Activation::convertActivationsFromString(activation) ==
150 Activation::Activations::Active))
151 {
152 if (priority < minPriority)
153 {
154 minPriority = priority;
155 objectFound = true;
156 revision = std::move(version);
157 }
158 }
159 }
160 catch (const std::exception& e)
161 {
162 log<level::ERR>(e.what());
163 }
164 }
165 }
166
167 if (!objectFound)
168 {
169 log<level::ERR>("Could not found an BMC software Object");
170 elog<InternalFailure>();
171 }
172
173 return revision;
174}
175
Alexander Amelkinba19c182018-09-04 15:49:36 +0300176bool getCurrentBmcState()
177{
178 sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};
179
180 // Get the Inventory object implementing the BMC interface
181 ipmi::DbusObjectInfo bmcObject =
182 ipmi::getDbusObject(bus, bmc_state_interface);
183 auto variant =
184 ipmi::getDbusProperty(bus, bmcObject.second, bmcObject.first,
185 bmc_state_interface, bmc_state_property);
186
Vernon Maueryf442e112019-04-09 11:44:36 -0700187 return std::holds_alternative<std::string>(variant) &&
188 BMC::convertBMCStateFromString(std::get<std::string>(variant)) ==
189 BMC::BMCState::Ready;
Alexander Amelkinba19c182018-09-04 15:49:36 +0300190}
191
Patrick Venture94930a12019-04-30 10:01:58 -0700192bool getCurrentBmcStateWithFallback(const bool fallbackAvailability)
193{
194 try
195 {
196 return getCurrentBmcState();
197 }
198 catch (...)
199 {
200 // Nothing provided the BMC interface, therefore return whatever was
201 // configured as the default.
202 return fallbackAvailability;
203 }
204}
205
Yong Li18d77262018-10-09 01:59:45 +0800206namespace acpi_state
207{
208using namespace sdbusplus::xyz::openbmc_project::Control::Power::server;
209
210const static constexpr char* acpiObjPath =
211 "/xyz/openbmc_project/control/host0/acpi_power_state";
212const static constexpr char* acpiInterface =
213 "xyz.openbmc_project.Control.Power.ACPIPowerState";
214const static constexpr char* sysACPIProp = "SysACPIStatus";
215const static constexpr char* devACPIProp = "DevACPIStatus";
216
217enum class PowerStateType : uint8_t
218{
219 sysPowerState = 0x00,
220 devPowerState = 0x01,
221};
222
223// Defined in 20.6 of ipmi doc
224enum class PowerState : uint8_t
225{
226 s0G0D0 = 0x00,
227 s1D1 = 0x01,
228 s2D2 = 0x02,
229 s3D3 = 0x03,
230 s4 = 0x04,
231 s5G2 = 0x05,
232 s4S5 = 0x06,
233 g3 = 0x07,
234 sleep = 0x08,
235 g1Sleep = 0x09,
236 override = 0x0a,
237 legacyOn = 0x20,
238 legacyOff = 0x21,
239 unknown = 0x2a,
240 noChange = 0x7f,
241};
242
243static constexpr uint8_t stateChanged = 0x80;
244
245struct ACPIState
246{
247 uint8_t sysACPIState;
248 uint8_t devACPIState;
249} __attribute__((packed));
250
251std::map<ACPIPowerState::ACPI, PowerState> dbusToIPMI = {
252 {ACPIPowerState::ACPI::S0_G0_D0, PowerState::s0G0D0},
253 {ACPIPowerState::ACPI::S1_D1, PowerState::s1D1},
254 {ACPIPowerState::ACPI::S2_D2, PowerState::s2D2},
255 {ACPIPowerState::ACPI::S3_D3, PowerState::s3D3},
256 {ACPIPowerState::ACPI::S4, PowerState::s4},
257 {ACPIPowerState::ACPI::S5_G2, PowerState::s5G2},
258 {ACPIPowerState::ACPI::S4_S5, PowerState::s4S5},
259 {ACPIPowerState::ACPI::G3, PowerState::g3},
260 {ACPIPowerState::ACPI::SLEEP, PowerState::sleep},
261 {ACPIPowerState::ACPI::G1_SLEEP, PowerState::g1Sleep},
262 {ACPIPowerState::ACPI::OVERRIDE, PowerState::override},
263 {ACPIPowerState::ACPI::LEGACY_ON, PowerState::legacyOn},
264 {ACPIPowerState::ACPI::LEGACY_OFF, PowerState::legacyOff},
265 {ACPIPowerState::ACPI::Unknown, PowerState::unknown}};
266
267bool isValidACPIState(acpi_state::PowerStateType type, uint8_t state)
268{
269 if (type == acpi_state::PowerStateType::sysPowerState)
270 {
271 if ((state <= static_cast<uint8_t>(acpi_state::PowerState::override)) ||
272 (state == static_cast<uint8_t>(acpi_state::PowerState::legacyOn)) ||
273 (state ==
274 static_cast<uint8_t>(acpi_state::PowerState::legacyOff)) ||
275 (state == static_cast<uint8_t>(acpi_state::PowerState::unknown)) ||
276 (state == static_cast<uint8_t>(acpi_state::PowerState::noChange)))
277 {
278 return true;
279 }
280 else
281 {
282 return false;
283 }
284 }
285 else if (type == acpi_state::PowerStateType::devPowerState)
286 {
287 if ((state <= static_cast<uint8_t>(acpi_state::PowerState::s3D3)) ||
288 (state == static_cast<uint8_t>(acpi_state::PowerState::unknown)) ||
289 (state == static_cast<uint8_t>(acpi_state::PowerState::noChange)))
290 {
291 return true;
292 }
293 else
294 {
295 return false;
296 }
297 }
298 else
299 {
300 return false;
301 }
302 return false;
303}
304} // namespace acpi_state
305
Adriana Kobylak3a552e12015-10-19 16:11:00 -0500306ipmi_ret_t ipmi_app_set_acpi_power_state(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
Patrick Venture0b02be92018-08-31 11:55:55 -0700307 ipmi_request_t request,
308 ipmi_response_t response,
309 ipmi_data_len_t data_len,
310 ipmi_context_t context)
Chris Austen6caf28b2015-10-13 12:40:40 -0500311{
Yong Li18d77262018-10-09 01:59:45 +0800312 auto s = static_cast<uint8_t>(acpi_state::PowerState::unknown);
Chris Austen6caf28b2015-10-13 12:40:40 -0500313 ipmi_ret_t rc = IPMI_CC_OK;
Yong Li18d77262018-10-09 01:59:45 +0800314
315 sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};
316
317 auto value = acpi_state::ACPIPowerState::ACPI::Unknown;
318
319 auto* req = reinterpret_cast<acpi_state::ACPIState*>(request);
320
321 if (*data_len != sizeof(acpi_state::ACPIState))
322 {
323 log<level::ERR>("set_acpi invalid len");
324 *data_len = 0;
325 return IPMI_CC_REQ_DATA_LEN_INVALID;
326 }
327
Chris Austen6caf28b2015-10-13 12:40:40 -0500328 *data_len = 0;
329
Yong Li18d77262018-10-09 01:59:45 +0800330 if (req->sysACPIState & acpi_state::stateChanged)
331 {
332 // set system power state
333 s = req->sysACPIState & ~acpi_state::stateChanged;
334
335 if (!acpi_state::isValidACPIState(
336 acpi_state::PowerStateType::sysPowerState, s))
337 {
338 log<level::ERR>("set_acpi_power sys invalid input",
339 entry("S=%x", s));
340 return IPMI_CC_PARM_OUT_OF_RANGE;
341 }
342
343 // valid input
344 if (s == static_cast<uint8_t>(acpi_state::PowerState::noChange))
345 {
346 log<level::DEBUG>("No change for system power state");
347 }
348 else
349 {
350 auto found = std::find_if(
351 acpi_state::dbusToIPMI.begin(), acpi_state::dbusToIPMI.end(),
352 [&s](const auto& iter) {
353 return (static_cast<uint8_t>(iter.second) == s);
354 });
355
356 value = found->first;
357
358 try
359 {
360 auto acpiObject =
361 ipmi::getDbusObject(bus, acpi_state::acpiInterface);
362 ipmi::setDbusProperty(bus, acpiObject.second, acpiObject.first,
363 acpi_state::acpiInterface,
364 acpi_state::sysACPIProp,
365 convertForMessage(value));
366 }
367 catch (const InternalFailure& e)
368 {
369 log<level::ERR>("Failed in set ACPI system property",
370 entry("EXCEPTION=%s", e.what()));
371 return IPMI_CC_UNSPECIFIED_ERROR;
372 }
373 }
374 }
375 else
376 {
377 log<level::DEBUG>("Do not change system power state");
378 }
379
380 if (req->devACPIState & acpi_state::stateChanged)
381 {
382 // set device power state
383 s = req->devACPIState & ~acpi_state::stateChanged;
384 if (!acpi_state::isValidACPIState(
385 acpi_state::PowerStateType::devPowerState, s))
386 {
387 log<level::ERR>("set_acpi_power dev invalid input",
388 entry("S=%x", s));
389 return IPMI_CC_PARM_OUT_OF_RANGE;
390 }
391
392 // valid input
393 if (s == static_cast<uint8_t>(acpi_state::PowerState::noChange))
394 {
395 log<level::DEBUG>("No change for device power state");
396 }
397 else
398 {
399 auto found = std::find_if(
400 acpi_state::dbusToIPMI.begin(), acpi_state::dbusToIPMI.end(),
401 [&s](const auto& iter) {
402 return (static_cast<uint8_t>(iter.second) == s);
403 });
404
405 value = found->first;
406
407 try
408 {
409 auto acpiObject =
410 ipmi::getDbusObject(bus, acpi_state::acpiInterface);
411 ipmi::setDbusProperty(bus, acpiObject.second, acpiObject.first,
412 acpi_state::acpiInterface,
413 acpi_state::devACPIProp,
414 convertForMessage(value));
415 }
416 catch (const InternalFailure& e)
417 {
418 log<level::ERR>("Failed in set ACPI device property",
419 entry("EXCEPTION=%s", e.what()));
420 return IPMI_CC_UNSPECIFIED_ERROR;
421 }
422 }
423 }
424 else
425 {
426 log<level::DEBUG>("Do not change device power state");
427 }
428
429 return rc;
430}
431
Deepak Kumar Sahu4e6d2572019-05-07 19:53:37 +0000432/**
433 * @brief implements the get ACPI power state command
434 *
435 * @return IPMI completion code plus response data on success.
436 * - ACPI system power state
437 * - ACPI device power state
438 **/
439ipmi::RspType<uint8_t, // acpiSystemPowerState
440 uint8_t // acpiDevicePowerState
441 >
442 ipmiGetAcpiPowerState()
Yong Li18d77262018-10-09 01:59:45 +0800443{
Deepak Kumar Sahu4e6d2572019-05-07 19:53:37 +0000444 uint8_t sysAcpiState;
445 uint8_t devAcpiState;
Yong Li18d77262018-10-09 01:59:45 +0800446
447 sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};
448
Yong Li18d77262018-10-09 01:59:45 +0800449 try
450 {
451 auto acpiObject = ipmi::getDbusObject(bus, acpi_state::acpiInterface);
452
453 auto sysACPIVal = ipmi::getDbusProperty(
454 bus, acpiObject.second, acpiObject.first, acpi_state::acpiInterface,
455 acpi_state::sysACPIProp);
456 auto sysACPI = acpi_state::ACPIPowerState::convertACPIFromString(
Vernon Maueryf442e112019-04-09 11:44:36 -0700457 std::get<std::string>(sysACPIVal));
Deepak Kumar Sahu4e6d2572019-05-07 19:53:37 +0000458 sysAcpiState = static_cast<uint8_t>(acpi_state::dbusToIPMI.at(sysACPI));
Yong Li18d77262018-10-09 01:59:45 +0800459
460 auto devACPIVal = ipmi::getDbusProperty(
461 bus, acpiObject.second, acpiObject.first, acpi_state::acpiInterface,
462 acpi_state::devACPIProp);
463 auto devACPI = acpi_state::ACPIPowerState::convertACPIFromString(
Vernon Maueryf442e112019-04-09 11:44:36 -0700464 std::get<std::string>(devACPIVal));
Deepak Kumar Sahu4e6d2572019-05-07 19:53:37 +0000465 devAcpiState = static_cast<uint8_t>(acpi_state::dbusToIPMI.at(devACPI));
Yong Li18d77262018-10-09 01:59:45 +0800466 }
467 catch (const InternalFailure& e)
468 {
Deepak Kumar Sahu4e6d2572019-05-07 19:53:37 +0000469 return ipmi::responseUnspecifiedError();
Yong Li18d77262018-10-09 01:59:45 +0800470 }
Deepak Kumar Sahu4e6d2572019-05-07 19:53:37 +0000471
472 return ipmi::responseSuccess(sysAcpiState, devAcpiState);
Chris Austen6caf28b2015-10-13 12:40:40 -0500473}
474
Chris Austen7303bdc2016-04-17 11:50:54 -0500475typedef struct
476{
477 char major;
478 char minor;
Chris Austen176c9652016-04-30 16:32:17 -0500479 uint16_t d[2];
Vernon Mauery86a50822019-03-25 13:11:36 -0700480} Revision;
Chris Austen7303bdc2016-04-17 11:50:54 -0500481
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600482/* Currently supports the vx.x-x-[-x] and v1.x.x-x-[-x] format. It will */
483/* return -1 if not in those formats, this routine knows how to parse */
Chris Austen7303bdc2016-04-17 11:50:54 -0500484/* version = v0.6-19-gf363f61-dirty */
485/* ^ ^ ^^ ^ */
486/* | | |----------|-- additional details */
487/* | |---------------- Minor */
488/* |------------------ Major */
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600489/* and version = v1.99.10-113-g65edf7d-r3-0-g9e4f715 */
490/* ^ ^ ^^ ^ */
491/* | | |--|---------- additional details */
492/* | |---------------- Minor */
493/* |------------------ Major */
Chris Austen7303bdc2016-04-17 11:50:54 -0500494/* Additional details : If the option group exists it will force Auxiliary */
495/* Firmware Revision Information 4th byte to 1 indicating the build was */
496/* derived with additional edits */
Vernon Mauery86a50822019-03-25 13:11:36 -0700497int convertVersion(std::string s, Revision& rev)
Chris Austen7303bdc2016-04-17 11:50:54 -0500498{
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600499 std::string token;
Chris Austen176c9652016-04-30 16:32:17 -0500500 uint16_t commits;
Chris Austen7303bdc2016-04-17 11:50:54 -0500501
Patrick Venture0b02be92018-08-31 11:55:55 -0700502 auto location = s.find_first_of('v');
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600503 if (location != std::string::npos)
504 {
Patrick Venture0b02be92018-08-31 11:55:55 -0700505 s = s.substr(location + 1);
Chris Austen176c9652016-04-30 16:32:17 -0500506 }
Chris Austen7303bdc2016-04-17 11:50:54 -0500507
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600508 if (!s.empty())
509 {
510 location = s.find_first_of(".");
511 if (location != std::string::npos)
512 {
Vernon Mauery86a50822019-03-25 13:11:36 -0700513 rev.major =
Patrick Venture0b02be92018-08-31 11:55:55 -0700514 static_cast<char>(std::stoi(s.substr(0, location), 0, 16));
515 token = s.substr(location + 1);
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600516 }
Chris Austen176c9652016-04-30 16:32:17 -0500517
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600518 if (!token.empty())
519 {
520 location = token.find_first_of(".-");
521 if (location != std::string::npos)
522 {
Vernon Mauery86a50822019-03-25 13:11:36 -0700523 rev.minor = static_cast<char>(
Patrick Venture0b02be92018-08-31 11:55:55 -0700524 std::stoi(token.substr(0, location), 0, 16));
525 token = token.substr(location + 1);
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600526 }
527 }
Chris Austen7303bdc2016-04-17 11:50:54 -0500528
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600529 // Capture the number of commits on top of the minor tag.
530 // I'm using BE format like the ipmi spec asked for
531 location = token.find_first_of(".-");
532 if (!token.empty())
533 {
534 commits = std::stoi(token.substr(0, location), 0, 16);
Vernon Mauery86a50822019-03-25 13:11:36 -0700535 rev.d[0] = (commits >> 8) | (commits << 8);
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600536
537 // commit number we skip
538 location = token.find_first_of(".-");
539 if (location != std::string::npos)
540 {
Patrick Venture0b02be92018-08-31 11:55:55 -0700541 token = token.substr(location + 1);
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600542 }
543 }
Patrick Venture0b02be92018-08-31 11:55:55 -0700544 else
545 {
Vernon Mauery86a50822019-03-25 13:11:36 -0700546 rev.d[0] = 0;
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600547 }
548
549 if (location != std::string::npos)
550 {
Patrick Venture0b02be92018-08-31 11:55:55 -0700551 token = token.substr(location + 1);
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600552 }
553
554 // Any value of the optional parameter forces it to 1
555 location = token.find_first_of(".-");
556 if (location != std::string::npos)
557 {
Patrick Venture0b02be92018-08-31 11:55:55 -0700558 token = token.substr(location + 1);
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600559 }
560 commits = (!token.empty()) ? 1 : 0;
561
Patrick Venture0b02be92018-08-31 11:55:55 -0700562 // We do this operation to get this displayed in least significant bytes
563 // of ipmitool device id command.
Vernon Mauery86a50822019-03-25 13:11:36 -0700564 rev.d[1] = (commits >> 8) | (commits << 8);
Dinesh Chinari2b7e07d2017-11-08 15:38:50 -0600565 }
566
Chris Austen7303bdc2016-04-17 11:50:54 -0500567 return 0;
568}
569
Vernon Maueryea1c4012019-05-24 13:26:16 -0700570/* @brief: Implement the Get Device ID IPMI command per the IPMI spec
571 * @param[in] ctx - shared_ptr to an IPMI context struct
572 *
573 * @returns IPMI completion code plus response data
574 * - Device ID (manufacturer defined)
575 * - Device revision[4 bits]; reserved[3 bits]; SDR support[1 bit]
576 * - FW revision major[7 bits] (binary encoded); available[1 bit]
577 * - FW Revision minor (BCD encoded)
578 * - IPMI version (0x02 for IPMI 2.0)
579 * - device support (bitfield of supported options)
580 * - MFG IANA ID (3 bytes)
581 * - product ID (2 bytes)
582 * - AUX info (4 bytes)
583 */
584ipmi::RspType<uint8_t, // Device ID
585 uint8_t, // Device Revision
586 uint8_t, // Firmware Revision Major
587 uint8_t, // Firmware Revision minor
588 uint8_t, // IPMI version
589 uint8_t, // Additional device support
590 uint24_t, // MFG ID
591 uint16_t, // Product ID
592 uint32_t // AUX info
593 >
594 ipmiAppGetDeviceId(ipmi::Context::ptr ctx)
Chris Austen6caf28b2015-10-13 12:40:40 -0500595{
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600596 int r = -1;
Vernon Mauery86a50822019-03-25 13:11:36 -0700597 Revision rev = {0};
598 static struct
599 {
600 uint8_t id;
601 uint8_t revision;
602 uint8_t fw[2];
603 uint8_t ipmiVer;
604 uint8_t addnDevSupport;
605 uint24_t manufId;
606 uint16_t prodId;
607 uint32_t aux;
608 } devId;
David Cobbleya1adb072017-11-21 15:58:13 -0800609 static bool dev_id_initialized = false;
Patrick Venture94930a12019-04-30 10:01:58 -0700610 static bool defaultActivationSetting = true;
David Cobbleya1adb072017-11-21 15:58:13 -0800611 const char* filename = "/usr/share/ipmi-providers/dev_id.json";
Alexander Amelkinba19c182018-09-04 15:49:36 +0300612 constexpr auto ipmiDevIdStateShift = 7;
613 constexpr auto ipmiDevIdFw1Mask = ~(1 << ipmiDevIdStateShift);
Chris Austen6caf28b2015-10-13 12:40:40 -0500614
David Cobbleya1adb072017-11-21 15:58:13 -0800615 if (!dev_id_initialized)
616 {
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600617 try
618 {
Vernon Maueryea1c4012019-05-24 13:26:16 -0700619 auto version = getActiveSoftwareVersionInfo(ctx);
Vernon Mauery86a50822019-03-25 13:11:36 -0700620 r = convertVersion(version, rev);
David Cobbleya1adb072017-11-21 15:58:13 -0800621 }
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600622 catch (const std::exception& e)
623 {
624 log<level::ERR>(e.what());
625 }
Nan Liee0cb902016-07-11 15:38:03 +0800626
Patrick Venture0b02be92018-08-31 11:55:55 -0700627 if (r >= 0)
628 {
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600629 // bit7 identifies if the device is available
630 // 0=normal operation
631 // 1=device firmware, SDR update,
632 // or self-initialization in progress.
Alexander Amelkinba19c182018-09-04 15:49:36 +0300633 // The availability may change in run time, so mask here
634 // and initialize later.
Vernon Mauery86a50822019-03-25 13:11:36 -0700635 devId.fw[0] = rev.major & ipmiDevIdFw1Mask;
Nagaraju Goruganti744398d2018-02-20 09:52:00 -0600636
637 rev.minor = (rev.minor > 99 ? 99 : rev.minor);
Vernon Mauery86a50822019-03-25 13:11:36 -0700638 devId.fw[1] = rev.minor % 10 + (rev.minor / 10) * 16;
639 std::memcpy(&devId.aux, rev.d, 4);
David Cobbleya1adb072017-11-21 15:58:13 -0800640 }
Nan Liee0cb902016-07-11 15:38:03 +0800641
David Cobbleya1adb072017-11-21 15:58:13 -0800642 // IPMI Spec version 2.0
Vernon Mauery86a50822019-03-25 13:11:36 -0700643 devId.ipmiVer = 2;
Adriana Kobylak0e912642016-06-22 16:54:39 -0500644
Vernon Mauery86a50822019-03-25 13:11:36 -0700645 std::ifstream devIdFile(filename);
646 if (devIdFile.is_open())
David Cobbleya1adb072017-11-21 15:58:13 -0800647 {
Vernon Mauery86a50822019-03-25 13:11:36 -0700648 auto data = nlohmann::json::parse(devIdFile, nullptr, false);
David Cobbleya1adb072017-11-21 15:58:13 -0800649 if (!data.is_discarded())
650 {
Vernon Mauery86a50822019-03-25 13:11:36 -0700651 devId.id = data.value("id", 0);
652 devId.revision = data.value("revision", 0);
653 devId.addnDevSupport = data.value("addn_dev_support", 0);
654 devId.manufId = data.value("manuf_id", 0);
655 devId.prodId = data.value("prod_id", 0);
656 devId.aux = data.value("aux", 0);
David Cobbleya1adb072017-11-21 15:58:13 -0800657
Patrick Venture94930a12019-04-30 10:01:58 -0700658 // Set the availablitity of the BMC.
659 defaultActivationSetting = data.value("availability", true);
660
Patrick Venture0b02be92018-08-31 11:55:55 -0700661 // Don't read the file every time if successful
David Cobbleya1adb072017-11-21 15:58:13 -0800662 dev_id_initialized = true;
663 }
664 else
665 {
666 log<level::ERR>("Device ID JSON parser failure");
Vernon Maueryf2587fc2019-04-09 14:28:15 -0700667 return ipmi::responseUnspecifiedError();
David Cobbleya1adb072017-11-21 15:58:13 -0800668 }
669 }
670 else
671 {
672 log<level::ERR>("Device ID file not found");
Vernon Maueryf2587fc2019-04-09 14:28:15 -0700673 return ipmi::responseUnspecifiedError();
Chris Austen7303bdc2016-04-17 11:50:54 -0500674 }
675 }
Chris Austen6caf28b2015-10-13 12:40:40 -0500676
Alexander Amelkinba19c182018-09-04 15:49:36 +0300677 // Set availability to the actual current BMC state
Vernon Mauery86a50822019-03-25 13:11:36 -0700678 devId.fw[0] &= ipmiDevIdFw1Mask;
Patrick Venture94930a12019-04-30 10:01:58 -0700679 if (!getCurrentBmcStateWithFallback(defaultActivationSetting))
Alexander Amelkinba19c182018-09-04 15:49:36 +0300680 {
Vernon Mauery86a50822019-03-25 13:11:36 -0700681 devId.fw[0] |= (1 << ipmiDevIdStateShift);
Alexander Amelkinba19c182018-09-04 15:49:36 +0300682 }
683
Vernon Mauery86a50822019-03-25 13:11:36 -0700684 return ipmi::responseSuccess(
685 devId.id, devId.revision, devId.fw[0], devId.fw[1], devId.ipmiVer,
686 devId.addnDevSupport, devId.manufId, devId.prodId, devId.aux);
Chris Austen6caf28b2015-10-13 12:40:40 -0500687}
688
Vernon Maueryb84a5282019-03-25 13:39:03 -0700689auto ipmiAppGetSelfTestResults() -> ipmi::RspType<uint8_t, uint8_t>
Nan Li41fa24a2016-11-10 20:12:37 +0800690{
Nan Li41fa24a2016-11-10 20:12:37 +0800691 // Byte 2:
692 // 55h - No error.
Gunnar Mills8991dd62017-10-25 17:11:29 -0500693 // 56h - Self Test function not implemented in this controller.
Nan Li41fa24a2016-11-10 20:12:37 +0800694 // 57h - Corrupted or inaccesssible data or devices.
695 // 58h - Fatal hardware error.
696 // FFh - reserved.
697 // all other: Device-specific 'internal failure'.
698 // Byte 3:
699 // For byte 2 = 55h, 56h, FFh: 00h
700 // For byte 2 = 58h, all other: Device-specific
701 // For byte 2 = 57h: self-test error bitfield.
702 // Note: returning 57h does not imply that all test were run.
703 // [7] 1b = Cannot access SEL device.
704 // [6] 1b = Cannot access SDR Repository.
705 // [5] 1b = Cannot access BMC FRU device.
706 // [4] 1b = IPMB signal lines do not respond.
707 // [3] 1b = SDR Repository empty.
708 // [2] 1b = Internal Use Area of BMC FRU corrupted.
709 // [1] 1b = controller update 'boot block' firmware corrupted.
710 // [0] 1b = controller operational firmware corrupted.
Vernon Maueryb84a5282019-03-25 13:39:03 -0700711 constexpr uint8_t notImplemented = 0x56;
712 constexpr uint8_t zero = 0;
713 return ipmi::responseSuccess(notImplemented, zero);
Nan Li41fa24a2016-11-10 20:12:37 +0800714}
715
Vernon Mauery15541322019-03-25 13:33:03 -0700716static constexpr size_t uuidBinaryLength = 16;
717static std::array<uint8_t, uuidBinaryLength> rfc4122ToIpmi(std::string rfc4122)
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500718{
Vernon Mauery15541322019-03-25 13:33:03 -0700719 using Argument = xyz::openbmc_project::Common::InvalidArgument;
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500720 // UUID is in RFC4122 format. Ex: 61a39523-78f2-11e5-9862-e6402cfc3223
Patrick Ventured2117022018-02-06 08:54:37 -0800721 // Per IPMI Spec 2.0 need to convert to 16 hex bytes and reverse the byte
722 // order
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500723 // Ex: 0x2332fc2c40e66298e511f2782395a361
Vernon Mauery15541322019-03-25 13:33:03 -0700724 constexpr size_t uuidHexLength = (2 * uuidBinaryLength);
725 constexpr size_t uuidRfc4122Length = (uuidHexLength + 4);
726 std::array<uint8_t, uuidBinaryLength> uuid;
727 if (rfc4122.size() == uuidRfc4122Length)
Patrick Venture0b02be92018-08-31 11:55:55 -0700728 {
Vernon Mauery15541322019-03-25 13:33:03 -0700729 rfc4122.erase(std::remove(rfc4122.begin(), rfc4122.end(), '-'),
730 rfc4122.end());
Sergey Solomineb9b8142016-08-23 09:07:28 -0500731 }
Vernon Mauery15541322019-03-25 13:33:03 -0700732 if (rfc4122.size() != uuidHexLength)
vishwa1eaea4f2016-02-26 11:57:40 -0600733 {
Vernon Mauery15541322019-03-25 13:33:03 -0700734 elog<InvalidArgument>(Argument::ARGUMENT_NAME("rfc4122"),
735 Argument::ARGUMENT_VALUE(rfc4122.c_str()));
vishwa1eaea4f2016-02-26 11:57:40 -0600736 }
Vernon Mauery15541322019-03-25 13:33:03 -0700737 for (size_t ind = 0; ind < uuidHexLength; ind += 2)
vishwa1eaea4f2016-02-26 11:57:40 -0600738 {
Vernon Mauery15541322019-03-25 13:33:03 -0700739 char v[3];
740 v[0] = rfc4122[ind];
741 v[1] = rfc4122[ind + 1];
742 v[2] = 0;
743 size_t err;
744 long b;
745 try
Emily Shafferedb8bb02018-09-27 14:50:15 -0700746 {
Vernon Mauery15541322019-03-25 13:33:03 -0700747 b = std::stoul(v, &err, 16);
Emily Shafferedb8bb02018-09-27 14:50:15 -0700748 }
Vernon Mauery15541322019-03-25 13:33:03 -0700749 catch (std::exception& e)
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500750 {
Vernon Mauery15541322019-03-25 13:33:03 -0700751 elog<InvalidArgument>(Argument::ARGUMENT_NAME("rfc4122"),
752 Argument::ARGUMENT_VALUE(rfc4122.c_str()));
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500753 }
Vernon Mauery15541322019-03-25 13:33:03 -0700754 // check that exactly two ascii bytes were converted
755 if (err != 2)
756 {
757 elog<InvalidArgument>(Argument::ARGUMENT_NAME("rfc4122"),
758 Argument::ARGUMENT_VALUE(rfc4122.c_str()));
759 }
760 uuid[uuidBinaryLength - (ind / 2) - 1] = static_cast<uint8_t>(b);
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500761 }
Vernon Mauery15541322019-03-25 13:33:03 -0700762 return uuid;
763}
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500764
Vernon Mauery15541322019-03-25 13:33:03 -0700765auto ipmiAppGetDeviceGuid()
766 -> ipmi::RspType<std::array<uint8_t, uuidBinaryLength>>
767{
768 // return a fixed GUID based on /etc/machine-id
769 // This should match the /redfish/v1/Managers/bmc's UUID data
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500770
Vernon Mauery15541322019-03-25 13:33:03 -0700771 // machine specific application ID (for BMC ID)
772 // generated by systemd-id128 -p new as per man page
773 static constexpr sd_id128_t bmcUuidAppId = SD_ID128_MAKE(
774 e0, e1, 73, 76, 64, 61, 47, da, a5, 0c, d0, cc, 64, 12, 45, 78);
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500775
Vernon Mauery15541322019-03-25 13:33:03 -0700776 sd_id128_t bmcUuid;
777 // create the UUID from /etc/machine-id via the systemd API
778 sd_id128_get_machine_app_specific(bmcUuidAppId, &bmcUuid);
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500779
Vernon Mauery15541322019-03-25 13:33:03 -0700780 char bmcUuidCstr[SD_ID128_STRING_MAX];
781 std::string systemUuid = sd_id128_to_string(bmcUuid, bmcUuidCstr);
782
783 std::array<uint8_t, uuidBinaryLength> uuid = rfc4122ToIpmi(systemUuid);
784 return ipmi::responseSuccess(uuid);
Adriana Kobylakd100ee52015-10-20 17:02:37 -0500785}
Chris Austen6caf28b2015-10-13 12:40:40 -0500786
Vernon Mauerycc99ba42019-03-25 13:40:11 -0700787auto ipmiAppGetBtCapabilities()
788 -> ipmi::RspType<uint8_t, uint8_t, uint8_t, uint8_t, uint8_t>
vishwabmcba0bd5f2015-09-30 16:50:23 +0530789{
Adriana Kobylak88ad8152016-12-13 10:09:08 -0600790 // Per IPMI 2.0 spec, the input and output buffer size must be the max
791 // buffer size minus one byte to allocate space for the length byte.
Vernon Mauerycc99ba42019-03-25 13:40:11 -0700792 constexpr uint8_t nrOutstanding = 0x01;
793 constexpr uint8_t inputBufferSize = MAX_IPMI_BUFFER - 1;
794 constexpr uint8_t outputBufferSize = MAX_IPMI_BUFFER - 1;
795 constexpr uint8_t transactionTime = 0x0A;
796 constexpr uint8_t nrRetries = 0x01;
vishwabmcba0bd5f2015-09-30 16:50:23 +0530797
Vernon Mauerycc99ba42019-03-25 13:40:11 -0700798 return ipmi::responseSuccess(nrOutstanding, inputBufferSize,
799 outputBufferSize, transactionTime, nrRetries);
vishwabmcba0bd5f2015-09-30 16:50:23 +0530800}
801
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600802ipmi_ret_t ipmi_app_get_sys_guid(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
Patrick Venture0b02be92018-08-31 11:55:55 -0700803 ipmi_request_t request,
804 ipmi_response_t response,
805 ipmi_data_len_t data_len,
806 ipmi_context_t context)
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600807
808{
809 ipmi_ret_t rc = IPMI_CC_OK;
810 sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};
811
812 try
813 {
814 // Get the Inventory object implementing BMC interface
815 ipmi::DbusObjectInfo bmcObject =
816 ipmi::getDbusObject(bus, bmc_interface);
817
818 // Read UUID property value from bmcObject
819 // UUID is in RFC4122 format Ex: 61a39523-78f2-11e5-9862-e6402cfc3223
Patrick Venture0b02be92018-08-31 11:55:55 -0700820 auto variant =
821 ipmi::getDbusProperty(bus, bmcObject.second, bmcObject.first,
822 bmc_guid_interface, bmc_guid_property);
Vernon Maueryf442e112019-04-09 11:44:36 -0700823 std::string guidProp = std::get<std::string>(variant);
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600824
825 // Erase "-" characters from the property value
826 guidProp.erase(std::remove(guidProp.begin(), guidProp.end(), '-'),
Patrick Venture0b02be92018-08-31 11:55:55 -0700827 guidProp.end());
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600828
829 auto guidPropLen = guidProp.length();
830 // Validate UUID data
831 // Divide by 2 as 1 byte is built from 2 chars
Patrick Venture0b02be92018-08-31 11:55:55 -0700832 if ((guidPropLen <= 0) || ((guidPropLen / 2) != bmc_guid_len))
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600833
834 {
835 log<level::ERR>("Invalid UUID property value",
Patrick Venture0b02be92018-08-31 11:55:55 -0700836 entry("UUID_LENGTH=%d", guidPropLen));
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600837 return IPMI_CC_RESPONSE_ERROR;
838 }
839
840 // Convert data in RFC4122(MSB) format to LSB format
841 // Get 2 characters at a time as 1 byte is built from 2 chars and
842 // convert to hex byte
843 // TODO: Data printed for GUID command is not as per the
844 // GUID format defined in IPMI specification 2.0 section 20.8
845 // Ticket raised: https://sourceforge.net/p/ipmitool/bugs/501/
846 uint8_t respGuid[bmc_guid_len];
847 for (size_t i = 0, respLoc = (bmc_guid_len - 1);
Patrick Venture0b02be92018-08-31 11:55:55 -0700848 i < guidPropLen && respLoc >= 0; i += 2, respLoc--)
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600849 {
850 auto value = static_cast<uint8_t>(
Patrick Venture0b02be92018-08-31 11:55:55 -0700851 std::stoi(guidProp.substr(i, 2).c_str(), NULL, 16));
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600852 respGuid[respLoc] = value;
853 }
854
855 *data_len = bmc_guid_len;
Patrick Ventureb51bf9c2018-09-10 15:53:14 -0700856 std::memcpy(response, &respGuid, bmc_guid_len);
Marri Devender Rao5e007a52018-01-08 06:18:36 -0600857 }
858 catch (const InternalFailure& e)
859 {
860 log<level::ERR>("Failed in reading BMC UUID property",
861 entry("INTERFACE=%s", bmc_interface),
862 entry("PROPERTY_INTERFACE=%s", bmc_guid_interface),
863 entry("PROPERTY=%s", bmc_guid_property));
864 return IPMI_CC_UNSPECIFIED_ERROR;
865 }
866 return rc;
867}
868
Xo Wangf542e8b2017-08-09 15:34:16 -0700869static std::unique_ptr<SysInfoParamStore> sysInfoParamStore;
870
Xo Wang87651332017-08-11 10:17:59 -0700871static std::string sysInfoReadSystemName()
872{
873 // Use the BMC hostname as the "System Name."
874 char hostname[HOST_NAME_MAX + 1] = {};
875 if (gethostname(hostname, HOST_NAME_MAX) != 0)
876 {
877 perror("System info parameter: system name");
878 }
879 return hostname;
880}
881
Xo Wangf542e8b2017-08-09 15:34:16 -0700882struct IpmiSysInfoResp
883{
884 uint8_t paramRevision;
885 uint8_t setSelector;
886 union
887 {
888 struct
889 {
890 uint8_t encoding;
891 uint8_t stringLen;
892 uint8_t stringData0[14];
893 } __attribute__((packed));
894 uint8_t stringDataN[16];
895 uint8_t byteData;
896 };
897} __attribute__((packed));
898
899/**
900 * Split a string into (up to) 16-byte chunks as expected in response for get
901 * system info parameter.
902 *
903 * @param[in] fullString: Input string to be split
904 * @param[in] chunkIndex: Index of the chunk to be written out
905 * @param[in,out] chunk: Output data buffer; must have 14 byte capacity if
906 * chunk_index = 0 and 16-byte capacity otherwise
907 * @return the number of bytes written into the output buffer, or -EINVAL for
908 * invalid arguments.
909 */
910static int splitStringParam(const std::string& fullString, int chunkIndex,
911 uint8_t* chunk)
912{
913 constexpr int maxChunk = 255;
914 constexpr int smallChunk = 14;
915 constexpr int chunkSize = 16;
916 if (chunkIndex > maxChunk || chunk == nullptr)
917 {
918 return -EINVAL;
919 }
920 try
921 {
922 std::string output;
923 if (chunkIndex == 0)
924 {
925 // Output must have 14 byte capacity.
926 output = fullString.substr(0, smallChunk);
927 }
928 else
929 {
930 // Output must have 16 byte capacity.
931 output = fullString.substr((chunkIndex * chunkSize) - 2, chunkSize);
932 }
933
934 std::memcpy(chunk, output.c_str(), output.length());
935 return output.length();
936 }
937 catch (const std::out_of_range& e)
938 {
939 // The position was beyond the end.
940 return -EINVAL;
941 }
942}
943
944/**
945 * Packs the Get Sys Info Request Item into the response.
946 *
947 * @param[in] paramString - the parameter.
948 * @param[in] setSelector - the selector
949 * @param[in,out] resp - the System info response.
950 * @return The number of bytes packed or failure from splitStringParam().
951 */
952static int packGetSysInfoResp(const std::string& paramString,
953 uint8_t setSelector, IpmiSysInfoResp* resp)
954{
955 uint8_t* dataBuffer = resp->stringDataN;
956 resp->setSelector = setSelector;
957 if (resp->setSelector == 0) // First chunk has only 14 bytes.
958 {
959 resp->encoding = 0;
960 resp->stringLen = paramString.length();
961 dataBuffer = resp->stringData0;
962 }
963 return splitStringParam(paramString, resp->setSelector, dataBuffer);
964}
965
966ipmi_ret_t ipmi_app_get_system_info(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
967 ipmi_request_t request,
968 ipmi_response_t response,
969 ipmi_data_len_t dataLen,
970 ipmi_context_t context)
971{
972 IpmiSysInfoResp resp = {};
973 size_t respLen = 0;
974 uint8_t* const reqData = static_cast<uint8_t*>(request);
975 std::string paramString;
976 bool found;
977 std::tuple<bool, std::string> ret;
978 constexpr int minRequestSize = 4;
979 constexpr int paramSelector = 1;
980 constexpr uint8_t revisionOnly = 0x80;
981 const uint8_t paramRequested = reqData[paramSelector];
982 int rc;
983
984 if (*dataLen < minRequestSize)
985 {
986 return IPMI_CC_REQ_DATA_LEN_INVALID;
987 }
988
989 *dataLen = 0; // default to 0.
990
991 // Parameters revision as of IPMI spec v2.0 rev. 1.1 (Feb 11, 2014 E6)
992 resp.paramRevision = 0x11;
993 if (reqData[0] & revisionOnly) // Get parameter revision only
994 {
995 respLen = 1;
996 goto writeResponse;
997 }
998
999 // The "Set In Progress" parameter can be used for rollback of parameter
1000 // data and is not implemented.
1001 if (paramRequested == 0)
1002 {
1003 resp.byteData = 0;
1004 respLen = 2;
1005 goto writeResponse;
1006 }
1007
1008 if (sysInfoParamStore == nullptr)
1009 {
1010 sysInfoParamStore = std::make_unique<SysInfoParamStore>();
Xo Wang87651332017-08-11 10:17:59 -07001011 sysInfoParamStore->update(IPMI_SYSINFO_SYSTEM_NAME,
1012 sysInfoReadSystemName);
Xo Wangf542e8b2017-08-09 15:34:16 -07001013 }
1014
1015 // Parameters other than Set In Progress are assumed to be strings.
1016 ret = sysInfoParamStore->lookup(paramRequested);
1017 found = std::get<0>(ret);
1018 paramString = std::get<1>(ret);
1019 if (!found)
1020 {
1021 return IPMI_CC_SYSTEM_INFO_PARAMETER_NOT_SUPPORTED;
1022 }
1023 // TODO: Cache each parameter across multiple calls, until the whole string
1024 // has been read out. Otherwise, it's possible for a parameter to change
1025 // between requests for its chunks, returning chunks incoherent with each
1026 // other. For now, the parameter store is simply required to have only
1027 // idempotent callbacks.
1028 rc = packGetSysInfoResp(paramString, reqData[2], &resp);
1029 if (rc == -EINVAL)
1030 {
1031 return IPMI_CC_RESPONSE_ERROR;
1032 }
1033
1034 respLen = sizeof(resp); // Write entire string data chunk in response.
1035
1036writeResponse:
1037 std::memcpy(response, &resp, sizeof(resp));
1038 *dataLen = respLen;
1039 return IPMI_CC_OK;
1040}
1041
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05301042inline std::vector<uint8_t> convertStringToData(const std::string& command)
1043{
1044 std::istringstream iss(command);
1045 std::string token;
1046 std::vector<uint8_t> dataValue;
1047 while (std::getline(iss, token, ' '))
1048 {
1049 dataValue.emplace_back(
1050 static_cast<uint8_t>(std::stoul(token, nullptr, base_16)));
1051 }
1052 return dataValue;
1053}
1054
1055static bool populateI2CMasterWRWhitelist()
1056{
1057 nlohmann::json data = nullptr;
1058 std::ifstream jsonFile(i2cMasterWRWhitelistFile);
1059
1060 if (!jsonFile.good())
1061 {
1062 log<level::WARNING>("i2c white list file not found!",
1063 entry("FILE_NAME: %s", i2cMasterWRWhitelistFile));
1064 return false;
1065 }
1066
1067 try
1068 {
1069 data = nlohmann::json::parse(jsonFile, nullptr, false);
1070 }
1071 catch (nlohmann::json::parse_error& e)
1072 {
1073 log<level::ERR>("Corrupted i2c white list config file",
1074 entry("FILE_NAME: %s", i2cMasterWRWhitelistFile),
1075 entry("MSG: %s", e.what()));
1076 return false;
1077 }
1078
1079 try
1080 {
1081 // Example JSON Structure format
1082 // "filters": [
1083 // {
1084 // "Description": "Allow full read - ignore first byte write value
1085 // for 0x40 to 0x4F",
1086 // "busId": "0x01",
1087 // "slaveAddr": "0x40",
1088 // "slaveAddrMask": "0x0F",
1089 // "command": "0x00",
1090 // "commandMask": "0xFF"
1091 // },
1092 // {
1093 // "Description": "Allow full read - first byte match 0x05 and
1094 // ignore second byte",
1095 // "busId": "0x01",
1096 // "slaveAddr": "0x57",
1097 // "slaveAddrMask": "0x00",
1098 // "command": "0x05 0x00",
1099 // "commandMask": "0x00 0xFF"
1100 // },]
1101
1102 nlohmann::json filters = data[filtersStr].get<nlohmann::json>();
1103 std::vector<i2cMasterWRWhitelist>& whitelist = getWRWhitelist();
1104 for (const auto& it : filters.items())
1105 {
1106 nlohmann::json filter = it.value();
1107 if (filter.is_null())
1108 {
1109 log<level::ERR>(
1110 "Corrupted I2C master write read whitelist config file",
1111 entry("FILE_NAME: %s", i2cMasterWRWhitelistFile));
1112 return false;
1113 }
1114 const std::vector<uint8_t>& writeData =
1115 convertStringToData(filter[cmdStr].get<std::string>());
1116 const std::vector<uint8_t>& writeDataMask =
1117 convertStringToData(filter[cmdMaskStr].get<std::string>());
1118 if (writeDataMask.size() != writeData.size())
1119 {
1120 log<level::ERR>("I2C master write read whitelist filter "
1121 "mismatch for command & mask size");
1122 return false;
1123 }
1124 whitelist.push_back(
1125 {static_cast<uint8_t>(std::stoul(
1126 filter[busIdStr].get<std::string>(), nullptr, base_16)),
1127 static_cast<uint8_t>(
1128 std::stoul(filter[slaveAddrStr].get<std::string>(),
1129 nullptr, base_16)),
1130 static_cast<uint8_t>(
1131 std::stoul(filter[slaveAddrMaskStr].get<std::string>(),
1132 nullptr, base_16)),
1133 writeData, writeDataMask});
1134 }
1135 if (whitelist.size() != filters.size())
1136 {
1137 log<level::ERR>(
1138 "I2C master write read whitelist filter size mismatch");
1139 return false;
1140 }
1141 }
1142 catch (std::exception& e)
1143 {
1144 log<level::ERR>("I2C master write read whitelist unexpected exception",
1145 entry("ERROR=%s", e.what()));
1146 return false;
1147 }
1148 return true;
1149}
1150
1151static inline bool isWriteDataWhitelisted(const std::vector<uint8_t>& data,
1152 const std::vector<uint8_t>& dataMask,
1153 const std::vector<uint8_t>& writeData)
1154{
1155 std::vector<uint8_t> processedDataBuf(data.size());
1156 std::vector<uint8_t> processedReqBuf(dataMask.size());
1157 std::transform(writeData.begin(), writeData.end(), dataMask.begin(),
1158 processedReqBuf.begin(), std::bit_or<uint8_t>());
1159 std::transform(data.begin(), data.end(), dataMask.begin(),
1160 processedDataBuf.begin(), std::bit_or<uint8_t>());
1161
1162 return (processedDataBuf == processedReqBuf);
1163}
1164
1165static bool isCmdWhitelisted(uint8_t busId, uint8_t slaveAddr,
1166 std::vector<uint8_t>& writeData)
1167{
1168 std::vector<i2cMasterWRWhitelist>& whiteList = getWRWhitelist();
1169 for (const auto& wlEntry : whiteList)
1170 {
1171 if ((busId == wlEntry.busId) &&
1172 ((slaveAddr | wlEntry.slaveAddrMask) ==
1173 (wlEntry.slaveAddr | wlEntry.slaveAddrMask)))
1174 {
1175 const std::vector<uint8_t>& dataMask = wlEntry.dataMask;
1176 // Skip as no-match, if requested write data is more than the
1177 // write data mask size
1178 if (writeData.size() > dataMask.size())
1179 {
1180 continue;
1181 }
1182 if (isWriteDataWhitelisted(wlEntry.data, dataMask, writeData))
1183 {
1184 return true;
1185 }
1186 }
1187 }
1188 return false;
1189}
1190
1191/** @brief implements master write read IPMI command which can be used for
1192 * low-level I2C/SMBus write, read or write-read access
1193 * @param isPrivateBus -to indicate private bus usage
1194 * @param busId - bus id
1195 * @param channelNum - channel number
1196 * @param reserved - skip 1 bit
1197 * @param slaveAddr - slave address
1198 * @param read count - number of bytes to be read
1199 * @param writeData - data to be written
1200 *
1201 * @returns IPMI completion code plus response data
1202 * - readData - i2c response data
1203 */
1204ipmi::RspType<std::vector<uint8_t>>
1205 ipmiMasterWriteRead(bool isPrivateBus, uint3_t busId, uint4_t channelNum,
1206 bool reserved, uint7_t slaveAddr, uint8_t readCount,
1207 std::vector<uint8_t> writeData)
1208{
1209 i2c_rdwr_ioctl_data msgReadWrite = {0};
1210 i2c_msg i2cmsg[2] = {0};
1211
1212 if (readCount > maxIPMIWriteReadSize)
1213 {
1214 log<level::ERR>("Master write read command: Read count exceeds limit");
1215 return ipmi::responseParmOutOfRange();
1216 }
1217 const size_t writeCount = writeData.size();
1218 if (!readCount && !writeCount)
1219 {
1220 log<level::ERR>("Master write read command: Read & write count are 0");
1221 return ipmi::responseInvalidFieldRequest();
1222 }
1223 if (!isCmdWhitelisted(static_cast<uint8_t>(busId),
1224 static_cast<uint8_t>(slaveAddr), writeData))
1225 {
1226 log<level::ERR>("Master write read request blocked!",
1227 entry("BUS=%d", static_cast<uint8_t>(busId)),
1228 entry("ADDR=0x%x", static_cast<uint8_t>(slaveAddr)));
1229 return ipmi::responseInvalidFieldRequest();
1230 }
1231 std::vector<uint8_t> readBuf(readCount);
1232 std::string i2cBus =
1233 "/dev/i2c-" + std::to_string(static_cast<uint8_t>(busId));
1234
1235 int i2cDev = ::open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
1236 if (i2cDev < 0)
1237 {
1238 log<level::ERR>("Failed to open i2c bus",
1239 entry("BUS=%s", i2cBus.c_str()));
1240 return ipmi::responseInvalidFieldRequest();
1241 }
1242
1243 int msgCount = 0;
1244 if (writeCount)
1245 {
1246 i2cmsg[msgCount].addr = static_cast<uint8_t>(slaveAddr);
1247 i2cmsg[msgCount].flags = 0x00;
1248 i2cmsg[msgCount].len = writeCount;
1249 i2cmsg[msgCount].buf = writeData.data();
1250 msgCount++;
1251 }
1252 if (readCount)
1253 {
1254 i2cmsg[msgCount].addr = static_cast<uint8_t>(slaveAddr);
1255 i2cmsg[msgCount].flags = I2C_M_RD;
1256 i2cmsg[msgCount].len = readCount;
1257 i2cmsg[msgCount].buf = readBuf.data();
1258 msgCount++;
1259 }
1260
1261 msgReadWrite.msgs = i2cmsg;
1262 msgReadWrite.nmsgs = msgCount;
1263
1264 int ret = ::ioctl(i2cDev, I2C_RDWR, &msgReadWrite);
1265 ::close(i2cDev);
1266
1267 if (ret < 0)
1268 {
1269 log<level::ERR>("Master write read: Failed", entry("RET=%d", ret));
1270 return ipmi::responseUnspecifiedError();
1271 }
1272 if (readCount)
1273 {
1274 readBuf.resize(msgReadWrite.msgs[msgCount - 1].len);
1275 }
1276 return ipmi::responseSuccess(readBuf);
1277}
1278
Chris Austen6caf28b2015-10-13 12:40:40 -05001279void register_netfn_app_functions()
vishwabmcba0bd5f2015-09-30 16:50:23 +05301280{
Vernon Mauery86a50822019-03-25 13:11:36 -07001281 // <Get Device ID>
1282 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1283 ipmi::app::cmdGetDeviceId, ipmi::Privilege::User,
1284 ipmiAppGetDeviceId);
1285
Tom05732372016-09-06 17:21:23 +05301286 // <Get BT Interface Capabilities>
Vernon Mauerycc99ba42019-03-25 13:40:11 -07001287 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1288 ipmi::app::cmdGetBtIfaceCapabilities,
1289 ipmi::Privilege::User, ipmiAppGetBtCapabilities);
Chris Austen6caf28b2015-10-13 12:40:40 -05001290
Tom05732372016-09-06 17:21:23 +05301291 // <Reset Watchdog Timer>
Vernon Mauery11df4f62019-03-25 14:17:54 -07001292 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1293 ipmi::app::cmdResetWatchdogTimer,
1294 ipmi::Privilege::Operator, ipmiAppResetWatchdogTimer);
Chris Austen6caf28b2015-10-13 12:40:40 -05001295
Tom05732372016-09-06 17:21:23 +05301296 // <Set Watchdog Timer>
Patrick Venture0b02be92018-08-31 11:55:55 -07001297 ipmi_register_callback(NETFUN_APP, IPMI_CMD_SET_WD, NULL,
1298 ipmi_app_watchdog_set, PRIVILEGE_OPERATOR);
Chris Austen6caf28b2015-10-13 12:40:40 -05001299
William A. Kennington III73f44512018-02-09 15:28:46 -08001300 // <Get Watchdog Timer>
Patrick Venture0b02be92018-08-31 11:55:55 -07001301 ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_WD, NULL,
1302 ipmi_app_watchdog_get, PRIVILEGE_OPERATOR);
William A. Kennington III73f44512018-02-09 15:28:46 -08001303
Tom05732372016-09-06 17:21:23 +05301304 // <Get Self Test Results>
Vernon Maueryb84a5282019-03-25 13:39:03 -07001305 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1306 ipmi::app::cmdGetSelfTestResults,
1307 ipmi::Privilege::User, ipmiAppGetSelfTestResults);
Nan Li41fa24a2016-11-10 20:12:37 +08001308
Tom05732372016-09-06 17:21:23 +05301309 // <Get Device GUID>
Vernon Mauery15541322019-03-25 13:33:03 -07001310 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1311 ipmi::app::cmdGetDeviceGuid, ipmi::Privilege::User,
1312 ipmiAppGetDeviceGuid);
Adriana Kobylakd100ee52015-10-20 17:02:37 -05001313
Tom05732372016-09-06 17:21:23 +05301314 // <Set ACPI Power State>
Patrick Venture0b02be92018-08-31 11:55:55 -07001315 ipmi_register_callback(NETFUN_APP, IPMI_CMD_SET_ACPI, NULL,
1316 ipmi_app_set_acpi_power_state, PRIVILEGE_ADMIN);
Chris Austen6caf28b2015-10-13 12:40:40 -05001317
Yong Li18d77262018-10-09 01:59:45 +08001318 // <Get ACPI Power State>
Deepak Kumar Sahu4e6d2572019-05-07 19:53:37 +00001319 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1320 ipmi::app::cmdGetAcpiPowerState,
1321 ipmi::Privilege::Admin, ipmiGetAcpiPowerState);
Yong Li18d77262018-10-09 01:59:45 +08001322
Richard Marian Thomaiyar84bf9be2019-04-26 22:59:16 +05301323 // Note: For security reason, this command will be registered only when
1324 // there are proper I2C Master write read whitelist
1325 if (populateI2CMasterWRWhitelist())
1326 {
1327 // Note: For security reasons, registering master write read as admin
1328 // privilege command, even though IPMI 2.0 specification allows it as
1329 // operator privilege.
1330 ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp,
1331 ipmi::app::cmdMasterWriteRead,
1332 ipmi::Privilege::Admin, ipmiMasterWriteRead);
1333 }
1334
Marri Devender Rao5e007a52018-01-08 06:18:36 -06001335 // <Get System GUID Command>
Patrick Venture0b02be92018-08-31 11:55:55 -07001336 ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_SYS_GUID, NULL,
1337 ipmi_app_get_sys_guid, PRIVILEGE_USER);
Tom Joseph7cbe2282018-03-21 21:17:33 +05301338
1339 // <Get Channel Cipher Suites Command>
Patrick Venture0b02be92018-08-31 11:55:55 -07001340 ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_CHAN_CIPHER_SUITES, NULL,
1341 getChannelCipherSuites, PRIVILEGE_CALLBACK);
Vernon Maueryd2a57de2019-03-25 12:45:28 -07001342
Xo Wangf542e8b2017-08-09 15:34:16 -07001343 // <Get System Info Command>
1344 ipmi_register_callback(NETFUN_APP, IPMI_CMD_GET_SYSTEM_INFO, NULL,
1345 ipmi_app_get_system_info, PRIVILEGE_USER);
vishwabmcba0bd5f2015-09-30 16:50:23 +05301346 return;
1347}