1 // Copyright 2022 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 #include "handler.hpp" 15 16 #include "bmc_mode_enum.hpp" 17 #include "errors.hpp" 18 #include "handler_impl.hpp" 19 #include "util.hpp" 20 21 #include <fcntl.h> 22 #include <ipmid/api.h> 23 #include <mtd/mtd-abi.h> 24 #include <mtd/mtd-user.h> 25 #include <sys/ioctl.h> 26 #include <unistd.h> 27 28 #include <cinttypes> 29 #include <cstdio> 30 #include <filesystem> 31 #include <fstream> 32 #include <map> 33 #include <nlohmann/json.hpp> 34 #include <phosphor-logging/elog-errors.hpp> 35 #include <phosphor-logging/log.hpp> 36 #include <sdbusplus/bus.hpp> 37 #include <sstream> 38 #include <string> 39 #include <string_view> 40 #include <tuple> 41 #include <variant> 42 #include <xyz/openbmc_project/Common/error.hpp> 43 44 #include "bm_config.h" 45 46 #ifndef NCSI_IF_NAME 47 #define NCSI_IF_NAME eth0 48 #endif 49 50 // To deal with receiving a string without quotes. 51 #define QUOTE(name) #name 52 #define STR(macro) QUOTE(macro) 53 #define NCSI_IF_NAME_STR STR(NCSI_IF_NAME) 54 55 namespace ipmi 56 { 57 std::uint8_t getChannelByName(const std::string& chName); 58 } 59 60 namespace google 61 { 62 namespace ipmi 63 { 64 namespace fs = std::filesystem; 65 using Json = nlohmann::json; 66 using namespace phosphor::logging; 67 using InternalFailure = 68 sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; 69 70 uint8_t isBmcInBareMetalMode() 71 { 72 #if BARE_METAL 73 return static_cast<uint8_t>(BmcMode::BM_MODE); 74 #else 75 return static_cast<uint8_t>(BmcMode::NON_BM_MODE); 76 #endif 77 } 78 79 uint8_t Handler::getBmcMode() 80 { 81 // BM_CLEANING_MODE is not implemented yet 82 return isBmcInBareMetalMode(); 83 } 84 85 std::tuple<std::uint8_t, std::string> 86 Handler::getEthDetails(std::string intf) const 87 { 88 if (intf.empty()) 89 { 90 intf = NCSI_IF_NAME_STR; 91 } 92 return std::make_tuple(::ipmi::getChannelByName(intf), std::move(intf)); 93 } 94 95 std::int64_t Handler::getRxPackets(const std::string& name) const 96 { 97 std::ostringstream opath; 98 opath << "/sys/class/net/" << name << "/statistics/rx_packets"; 99 std::string path = opath.str(); 100 101 // Minor sanity & security check (of course, I'm less certain if unicode 102 // comes into play here. 103 // 104 // Basically you can't easily inject ../ or /../ into the path below. 105 if (name.find("/") != std::string::npos) 106 { 107 std::fprintf(stderr, "Invalid or illegal name: '%s'\n", name.c_str()); 108 throw IpmiException(::ipmi::ccInvalidFieldRequest); 109 } 110 111 std::error_code ec; 112 if (!fs::exists(path, ec)) 113 { 114 std::fprintf(stderr, "Path: '%s' doesn't exist.\n", path.c_str()); 115 throw IpmiException(::ipmi::ccInvalidFieldRequest); 116 } 117 // We're uninterested in the state of ec. 118 119 int64_t count = 0; 120 std::ifstream ifs; 121 ifs.exceptions(std::ifstream::failbit); 122 try 123 { 124 ifs.open(path); 125 ifs >> count; 126 } 127 catch (std::ios_base::failure& fail) 128 { 129 throw IpmiException(::ipmi::ccUnspecifiedError); 130 } 131 132 return count; 133 } 134 135 VersionTuple Handler::getCpldVersion(unsigned int id) const 136 { 137 std::ostringstream opath; 138 opath << "/run/cpld" << id << ".version"; 139 // Check for file 140 141 std::error_code ec; 142 if (!fs::exists(opath.str(), ec)) 143 { 144 std::fprintf(stderr, "Path: '%s' doesn't exist.\n", 145 opath.str().c_str()); 146 throw IpmiException(::ipmi::ccInvalidFieldRequest); 147 } 148 // We're uninterested in the state of ec. 149 150 // If file exists, read. 151 std::ifstream ifs; 152 ifs.exceptions(std::ifstream::failbit); 153 std::string value; 154 try 155 { 156 ifs.open(opath.str()); 157 ifs >> value; 158 } 159 catch (std::ios_base::failure& fail) 160 { 161 throw IpmiException(::ipmi::ccUnspecifiedError); 162 } 163 164 // If value parses as expected, return version. 165 VersionTuple version = std::make_tuple(0, 0, 0, 0); 166 167 int num_fields = 168 std::sscanf(value.c_str(), "%" SCNu8 ".%" SCNu8 ".%" SCNu8 ".%" SCNu8, 169 &std::get<0>(version), &std::get<1>(version), 170 &std::get<2>(version), &std::get<3>(version)); 171 if (num_fields == 0) 172 { 173 std::fprintf(stderr, "Invalid version.\n"); 174 throw IpmiException(::ipmi::ccUnspecifiedError); 175 } 176 177 return version; 178 } 179 180 static constexpr auto TIME_DELAY_FILENAME = "/run/psu_timedelay"; 181 static constexpr auto SYSTEMD_SERVICE = "org.freedesktop.systemd1"; 182 static constexpr auto SYSTEMD_ROOT = "/org/freedesktop/systemd1"; 183 static constexpr auto SYSTEMD_INTERFACE = "org.freedesktop.systemd1.Manager"; 184 static constexpr auto PSU_HARDRESET_TARGET = "gbmc-psu-hardreset.target"; 185 186 void Handler::psuResetDelay(std::uint32_t delay) const 187 { 188 std::ofstream ofs; 189 ofs.open(TIME_DELAY_FILENAME, std::ofstream::out); 190 if (!ofs.good()) 191 { 192 std::fprintf(stderr, "Unable to open file for output.\n"); 193 throw IpmiException(::ipmi::ccUnspecifiedError); 194 } 195 196 ofs << "PSU_HARDRESET_DELAY=" << delay << std::endl; 197 if (ofs.fail()) 198 { 199 std::fprintf(stderr, "Write failed\n"); 200 ofs.close(); 201 throw IpmiException(::ipmi::ccUnspecifiedError); 202 } 203 204 // Write succeeded, please continue. 205 ofs.flush(); 206 ofs.close(); 207 208 auto bus = sdbusplus::bus::new_default(); 209 auto method = bus.new_method_call(SYSTEMD_SERVICE, SYSTEMD_ROOT, 210 SYSTEMD_INTERFACE, "StartUnit"); 211 212 method.append(PSU_HARDRESET_TARGET); 213 method.append("replace"); 214 215 try 216 { 217 bus.call_noreply(method); 218 } 219 catch (const sdbusplus::exception::SdBusError& ex) 220 { 221 log<level::ERR>("Failed to call PSU hard reset"); 222 throw IpmiException(::ipmi::ccUnspecifiedError); 223 } 224 } 225 226 static constexpr auto RESET_ON_SHUTDOWN_FILENAME = "/run/powercycle_on_s5"; 227 228 void Handler::psuResetOnShutdown() const 229 { 230 std::ofstream ofs; 231 ofs.open(RESET_ON_SHUTDOWN_FILENAME, std::ofstream::out); 232 if (!ofs.good()) 233 { 234 std::fprintf(stderr, "Unable to open file for output.\n"); 235 throw IpmiException(::ipmi::ccUnspecifiedError); 236 } 237 ofs.close(); 238 } 239 240 uint32_t Handler::getFlashSize() 241 { 242 mtd_info_t info; 243 int fd = open("/dev/mtd0", O_RDONLY); 244 int err = ioctl(fd, MEMGETINFO, &info); 245 close(fd); 246 247 if (err) 248 { 249 throw IpmiException(::ipmi::ccUnspecifiedError); 250 } 251 return info.size; 252 } 253 254 std::string Handler::getEntityName(std::uint8_t id, std::uint8_t instance) 255 { 256 // Check if we support this Entity ID. 257 auto it = _entityIdToName.find(id); 258 if (it == _entityIdToName.end()) 259 { 260 log<level::ERR>("Unknown Entity ID", entry("ENTITY_ID=%d", id)); 261 throw IpmiException(::ipmi::ccInvalidFieldRequest); 262 } 263 264 std::string entityName; 265 try 266 { 267 // Parse the JSON config file. 268 if (!_entityConfigParsed) 269 { 270 _entityConfig = parseConfig(_configFile); 271 _entityConfigParsed = true; 272 } 273 274 // Find the "entity id:entity instance" mapping to entity name. 275 entityName = readNameFromConfig(it->second, instance, _entityConfig); 276 if (entityName.empty()) 277 { 278 throw IpmiException(::ipmi::ccInvalidFieldRequest); 279 } 280 } 281 catch (InternalFailure& e) 282 { 283 throw IpmiException(::ipmi::ccUnspecifiedError); 284 } 285 286 return entityName; 287 } 288 289 std::string Handler::getMachineName() 290 { 291 const char* path = "/etc/os-release"; 292 std::ifstream ifs(path); 293 if (ifs.fail()) 294 { 295 std::fprintf(stderr, "Failed to open: %s\n", path); 296 throw IpmiException(::ipmi::ccUnspecifiedError); 297 } 298 299 std::string line; 300 while (true) 301 { 302 std::getline(ifs, line); 303 if (ifs.eof()) 304 { 305 std::fprintf(stderr, "Failed to find OPENBMC_TARGET_MACHINE: %s\n", 306 path); 307 throw IpmiException(::ipmi::ccInvalidCommand); 308 } 309 if (ifs.fail()) 310 { 311 std::fprintf(stderr, "Failed to read: %s\n", path); 312 throw IpmiException(::ipmi::ccUnspecifiedError); 313 } 314 std::string_view lineView(line); 315 constexpr std::string_view prefix = "OPENBMC_TARGET_MACHINE="; 316 if (lineView.substr(0, prefix.size()) != prefix) 317 { 318 continue; 319 } 320 lineView.remove_prefix(prefix.size()); 321 lineView.remove_prefix( 322 std::min(lineView.find_first_not_of('"'), lineView.size())); 323 lineView.remove_suffix( 324 lineView.size() - 1 - 325 std::min(lineView.find_last_not_of('"'), lineView.size() - 1)); 326 return std::string(lineView); 327 } 328 } 329 330 static constexpr auto HOST_TIME_DELAY_FILENAME = "/run/host_poweroff_delay"; 331 static constexpr auto HOST_POWEROFF_TARGET = "gbmc-host-poweroff.target"; 332 333 void Handler::hostPowerOffDelay(std::uint32_t delay) const 334 { 335 // Set time delay 336 std::ofstream ofs; 337 ofs.open(HOST_TIME_DELAY_FILENAME, std::ofstream::out); 338 if (!ofs.good()) 339 { 340 std::fprintf(stderr, "Unable to open file for output.\n"); 341 throw IpmiException(::ipmi::ccUnspecifiedError); 342 } 343 344 ofs << "HOST_POWEROFF_DELAY=" << delay << std::endl; 345 ofs.close(); 346 if (ofs.fail()) 347 { 348 std::fprintf(stderr, "Write failed\n"); 349 throw IpmiException(::ipmi::ccUnspecifiedError); 350 } 351 352 // Write succeeded, please continue. 353 auto bus = sdbusplus::bus::new_default(); 354 auto method = bus.new_method_call(SYSTEMD_SERVICE, SYSTEMD_ROOT, 355 SYSTEMD_INTERFACE, "StartUnit"); 356 357 method.append(HOST_POWEROFF_TARGET); 358 method.append("replace"); 359 360 try 361 { 362 bus.call_noreply(method); 363 } 364 catch (const sdbusplus::exception::SdBusError& ex) 365 { 366 log<level::ERR>("Failed to call Power Off", 367 entry("WHAT=%s", ex.what())); 368 throw IpmiException(::ipmi::ccUnspecifiedError); 369 } 370 } 371 372 std::string readNameFromConfig(const std::string& type, uint8_t instance, 373 const Json& config) 374 { 375 static const std::vector<Json> empty{}; 376 std::vector<Json> readings = config.value(type, empty); 377 std::string name = ""; 378 379 for (const auto& j : readings) 380 { 381 uint8_t instanceNum = j.value("instance", 0); 382 // Not the instance we're interested in 383 if (instanceNum != instance) 384 { 385 continue; 386 } 387 388 // Found the instance we're interested in 389 name = j.value("name", ""); 390 391 break; 392 } 393 394 return name; 395 } 396 397 void Handler::buildI2cPcieMapping() 398 { 399 _pcie_i2c_map = buildPcieMap(); 400 } 401 402 size_t Handler::getI2cPcieMappingSize() const 403 { 404 return _pcie_i2c_map.size(); 405 } 406 407 std::tuple<std::uint32_t, std::string> 408 Handler::getI2cEntry(unsigned int entry) const 409 { 410 return _pcie_i2c_map[entry]; 411 } 412 413 namespace 414 { 415 416 static constexpr std::string_view ACCEL_OOB_ROOT = "/com/google/customAccel/"; 417 static constexpr char ACCEL_OOB_SERVICE[] = "com.google.custom_accel"; 418 static constexpr char ACCEL_OOB_INTERFACE[] = "com.google.custom_accel.BAR"; 419 420 // C type for "a{oa{sa{sv}}}" from DBus.ObjectManager::GetManagedObjects() 421 using AnyType = std::variant<std::string, uint8_t, uint32_t, uint64_t>; 422 using AnyTypeList = std::vector<std::pair<std::string, AnyType>>; 423 using NamedArrayOfAnyTypeLists = 424 std::vector<std::pair<std::string, AnyTypeList>>; 425 using ArrayOfObjectPathsAndTieredAnyTypeLists = std::vector< 426 std::pair<sdbusplus::message::object_path, NamedArrayOfAnyTypeLists>>; 427 428 } // namespace 429 430 sdbusplus::bus::bus Handler::getDbus() const 431 { 432 return sdbusplus::bus::new_default(); 433 } 434 435 uint32_t Handler::accelOobDeviceCount() const 436 { 437 ArrayOfObjectPathsAndTieredAnyTypeLists data; 438 439 try 440 { 441 auto bus = getDbus(); 442 auto method = bus.new_method_call(ACCEL_OOB_SERVICE, "/", 443 "org.freedesktop.DBus.ObjectManager", 444 "GetManagedObjects"); 445 bus.call(method).read(data); 446 } 447 catch (const sdbusplus::exception::SdBusError& ex) 448 { 449 log<level::ERR>( 450 "Failed to call GetManagedObjects on com.google.custom_accel", 451 entry("WHAT=%s", ex.what())); 452 throw IpmiException(::ipmi::ccUnspecifiedError); 453 } 454 455 return data.size(); 456 } 457 458 std::string Handler::accelOobDeviceName(size_t index) const 459 { 460 ArrayOfObjectPathsAndTieredAnyTypeLists data; 461 462 try 463 { 464 auto bus = getDbus(); 465 auto method = bus.new_method_call(ACCEL_OOB_SERVICE, "/", 466 "org.freedesktop.DBus.ObjectManager", 467 "GetManagedObjects"); 468 bus.call(method).read(data); 469 } 470 catch (const sdbusplus::exception::SdBusError& ex) 471 { 472 log<level::ERR>( 473 "Failed to call GetManagedObjects on com.google.custom_accel", 474 entry("WHAT=%s", ex.what())); 475 throw IpmiException(::ipmi::ccUnspecifiedError); 476 } 477 478 if (index >= data.size()) 479 { 480 log<level::WARNING>( 481 "Requested index is larger than the number of entries.", 482 entry("INDEX=%zu", index), entry("NUM_NAMES=%zu", data.size())); 483 throw IpmiException(::ipmi::ccParmOutOfRange); 484 } 485 486 std::string_view name(data[index].first.str); 487 if (!name.starts_with(ACCEL_OOB_ROOT)) 488 { 489 throw IpmiException(::ipmi::ccInvalidCommand); 490 } 491 name.remove_prefix(ACCEL_OOB_ROOT.length()); 492 return std::string(name); 493 } 494 495 uint64_t Handler::accelOobRead(std::string_view name, uint64_t address, 496 uint8_t num_bytes) const 497 { 498 static constexpr char ACCEL_OOB_METHOD[] = "Read"; 499 500 std::string object_name(ACCEL_OOB_ROOT); 501 object_name.append(name); 502 503 auto bus = getDbus(); 504 auto method = bus.new_method_call(ACCEL_OOB_SERVICE, object_name.c_str(), 505 ACCEL_OOB_INTERFACE, ACCEL_OOB_METHOD); 506 method.append(address, static_cast<uint64_t>(num_bytes)); 507 508 std::vector<uint8_t> bytes; 509 510 try 511 { 512 bus.call(method).read(bytes); 513 } 514 catch (const sdbusplus::exception::SdBusError& ex) 515 { 516 log<level::ERR>("Failed to call Read on com.google.custom_accel", 517 entry("WHAT=%s", ex.what()), 518 entry("DBUS_SERVICE=%s", ACCEL_OOB_SERVICE), 519 entry("DBUS_OBJECT=%s", object_name.c_str()), 520 entry("DBUS_INTERFACE=%s", ACCEL_OOB_INTERFACE), 521 entry("DBUS_METHOD=%s", ACCEL_OOB_METHOD), 522 entry("DBUS_ARG_ADDRESS=%016llx", address), 523 entry("DBUS_ARG_NUM_BYTES=%zu", (size_t)num_bytes)); 524 throw IpmiException(::ipmi::ccUnspecifiedError); 525 } 526 527 if (bytes.size() < num_bytes) 528 { 529 log<level::ERR>( 530 "Call to Read on com.google.custom_accel didn't return the expected" 531 " number of bytes.", 532 entry("DBUS_SERVICE=%s", ACCEL_OOB_SERVICE), 533 entry("DBUS_OBJECT=%s", object_name.c_str()), 534 entry("DBUS_INTERFACE=%s", ACCEL_OOB_INTERFACE), 535 entry("DBUS_METHOD=%s", ACCEL_OOB_METHOD), 536 entry("DBUS_ARG_ADDRESS=%016llx", address), 537 entry("DBUS_ARG_NUM_BYTES=%zu", (size_t)num_bytes), 538 entry("DBUS_RETURN_SIZE=%zu", bytes.size())); 539 throw IpmiException(::ipmi::ccUnspecifiedError); 540 } 541 542 if (bytes.size() > sizeof(uint64_t)) 543 { 544 log<level::ERR>( 545 "Call to Read on com.google.custom_accel returned more than 8B.", 546 entry("DBUS_SERVICE=%s", ACCEL_OOB_SERVICE), 547 entry("DBUS_OBJECT=%s", object_name.c_str()), 548 entry("DBUS_INTERFACE=%s", ACCEL_OOB_INTERFACE), 549 entry("DBUS_METHOD=%s", ACCEL_OOB_METHOD), 550 entry("DBUS_ARG_ADDRESS=%016llx", address), 551 entry("DBUS_ARG_NUM_BYTES=%zu", (size_t)num_bytes), 552 entry("DBUS_RETURN_SIZE=%zu", bytes.size())); 553 throw IpmiException(::ipmi::ccReqDataTruncated); 554 } 555 556 uint64_t data = 0; 557 for (size_t i = 0; i < num_bytes; ++i) 558 { 559 data = (data << 8) | bytes[i]; 560 } 561 562 return data; 563 } 564 565 void Handler::accelOobWrite(std::string_view name, uint64_t address, 566 uint8_t num_bytes, uint64_t data) const 567 { 568 static constexpr std::string_view ACCEL_OOB_METHOD = "Write"; 569 570 std::string object_name(ACCEL_OOB_ROOT); 571 object_name.append(name); 572 573 if (num_bytes > sizeof(data)) 574 { 575 log<level::ERR>( 576 "Call to Write on com.google.custom_accel requested more than 8B.", 577 entry("DBUS_SERVICE=%s", ACCEL_OOB_SERVICE), 578 entry("DBUS_OBJECT=%s", object_name.c_str()), 579 entry("DBUS_INTERFACE=%s", ACCEL_OOB_INTERFACE), 580 entry("DBUS_METHOD=%s", ACCEL_OOB_METHOD.data()), 581 entry("DBUS_ARG_ADDRESS=%016llx", address), 582 entry("DBUS_ARG_NUM_BYTES=%zu", (size_t)num_bytes), 583 entry("DBUS_ARG_DATA=%016llx", data)); 584 throw IpmiException(::ipmi::ccParmOutOfRange); 585 } 586 587 std::vector<uint8_t> bytes; 588 bytes.reserve(num_bytes); 589 for (size_t i = 0; i < num_bytes; ++i) 590 { 591 bytes.emplace_back(data & 0xff); 592 data >>= 8; 593 } 594 595 try 596 { 597 auto bus = getDbus(); 598 auto method = 599 bus.new_method_call(ACCEL_OOB_SERVICE, object_name.c_str(), 600 ACCEL_OOB_INTERFACE, ACCEL_OOB_METHOD.data()); 601 method.append(address, bytes); 602 bus.call_noreply(method); 603 } 604 catch (const sdbusplus::exception::SdBusError& ex) 605 { 606 log<level::ERR>("Failed to call Write on com.google.custom_accel", 607 entry("WHAT=%s", ex.what()), 608 entry("DBUS_SERVICE=%s", ACCEL_OOB_SERVICE), 609 entry("DBUS_OBJECT=%s", object_name.c_str()), 610 entry("DBUS_INTERFACE=%s", ACCEL_OOB_INTERFACE), 611 entry("DBUS_METHOD=%s", ACCEL_OOB_METHOD.data()), 612 entry("DBUS_ARG_ADDRESS=%016llx", address), 613 entry("DBUS_ARG_NUM_BYTES=%zu", (size_t)num_bytes), 614 entry("DBUS_ARG_DATA=%016llx", data)); 615 throw IpmiException(::ipmi::ccUnspecifiedError); 616 } 617 } 618 619 std::vector<uint8_t> Handler::pcieBifurcation(uint8_t index) 620 { 621 return bifurcationHelper.get().getBifurcation(index).value_or( 622 std::vector<uint8_t>{}); 623 } 624 625 } // namespace ipmi 626 } // namespace google 627