xref: /openbmc/entity-manager/src/fru_device.cpp (revision f2f5b7ac)
1 /*
2 // Copyright (c) 2018 Intel Corporation
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 */
16 /// \file fru_device.cpp
17 
18 #include "fru_utils.hpp"
19 #include "utils.hpp"
20 
21 #include <fcntl.h>
22 #include <sys/inotify.h>
23 #include <sys/ioctl.h>
24 
25 #include <boost/algorithm/string/predicate.hpp>
26 #include <boost/asio/deadline_timer.hpp>
27 #include <boost/asio/io_service.hpp>
28 #include <boost/container/flat_map.hpp>
29 #include <nlohmann/json.hpp>
30 #include <sdbusplus/asio/connection.hpp>
31 #include <sdbusplus/asio/object_server.hpp>
32 
33 #include <array>
34 #include <cerrno>
35 #include <charconv>
36 #include <chrono>
37 #include <ctime>
38 #include <filesystem>
39 #include <fstream>
40 #include <functional>
41 #include <future>
42 #include <iomanip>
43 #include <iostream>
44 #include <limits>
45 #include <map>
46 #include <regex>
47 #include <set>
48 #include <sstream>
49 #include <string>
50 #include <thread>
51 #include <utility>
52 #include <variant>
53 #include <vector>
54 
55 extern "C"
56 {
57 #include <i2c/smbus.h>
58 #include <linux/i2c-dev.h>
59 }
60 
61 namespace fs = std::filesystem;
62 static constexpr bool debug = false;
63 constexpr size_t maxFruSize = 512;
64 constexpr size_t maxEepromPageIndex = 255;
65 constexpr size_t busTimeoutSeconds = 5;
66 
67 constexpr const char* blacklistPath = PACKAGE_DIR "blacklist.json";
68 
69 const static constexpr char* baseboardFruLocation =
70     "/etc/fru/baseboard.fru.bin";
71 
72 const static constexpr char* i2CDevLocation = "/dev";
73 
74 static std::set<size_t> busBlacklist;
75 struct FindDevicesWithCallback;
76 
77 static boost::container::flat_map<
78     std::pair<size_t, size_t>, std::shared_ptr<sdbusplus::asio::dbus_interface>>
79     foundDevices;
80 
81 static boost::container::flat_map<size_t, std::set<size_t>> failedAddresses;
82 static boost::container::flat_map<size_t, std::set<size_t>> fruAddresses;
83 
84 boost::asio::io_service io;
85 
86 bool updateFRUProperty(
87     const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
88     const std::string& propertyName,
89     boost::container::flat_map<
90         std::pair<size_t, size_t>,
91         std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
92     size_t& unknownBusObjectCount, const bool& powerIsOn,
93     sdbusplus::asio::object_server& objServer,
94     std::shared_ptr<sdbusplus::asio::connection>& systemBus);
95 
96 // Given a bus/address, produce the path in sysfs for an eeprom.
97 static std::string getEepromPath(size_t bus, size_t address)
98 {
99     std::stringstream output;
100     output << "/sys/bus/i2c/devices/" << bus << "-" << std::right
101            << std::setfill('0') << std::setw(4) << std::hex << address
102            << "/eeprom";
103     return output.str();
104 }
105 
106 static bool hasEepromFile(size_t bus, size_t address)
107 {
108     auto path = getEepromPath(bus, address);
109     try
110     {
111         return fs::exists(path);
112     }
113     catch (...)
114     {
115         return false;
116     }
117 }
118 
119 static int64_t readFromEeprom(int fd, off_t offset, size_t len, uint8_t* buf)
120 {
121     auto result = lseek(fd, offset, SEEK_SET);
122     if (result < 0)
123     {
124         std::cerr << "failed to seek\n";
125         return -1;
126     }
127 
128     return read(fd, buf, len);
129 }
130 
131 static int busStrToInt(const std::string_view busName)
132 {
133     auto findBus = busName.rfind('-');
134     if (findBus == std::string::npos)
135     {
136         return -1;
137     }
138     std::string_view num = busName.substr(findBus + 1);
139     int val = 0;
140     std::from_chars(num.data(), num.data() + num.size(), val);
141     return val;
142 }
143 
144 static int getRootBus(size_t bus)
145 {
146     auto ec = std::error_code();
147     auto path = std::filesystem::read_symlink(
148         std::filesystem::path("/sys/bus/i2c/devices/i2c-" +
149                               std::to_string(bus) + "/mux_device"),
150         ec);
151     if (ec)
152     {
153         return -1;
154     }
155 
156     std::string filename = path.filename();
157     auto findBus = filename.find('-');
158     if (findBus == std::string::npos)
159     {
160         return -1;
161     }
162     return std::stoi(filename.substr(0, findBus));
163 }
164 
165 static bool isMuxBus(size_t bus)
166 {
167     return is_symlink(std::filesystem::path(
168         "/sys/bus/i2c/devices/i2c-" + std::to_string(bus) + "/mux_device"));
169 }
170 
171 static void makeProbeInterface(size_t bus, size_t address,
172                                sdbusplus::asio::object_server& objServer)
173 {
174     if (isMuxBus(bus))
175     {
176         return; // the mux buses are random, no need to publish
177     }
178     auto [it, success] = foundDevices.emplace(
179         std::make_pair(bus, address),
180         objServer.add_interface(
181             "/xyz/openbmc_project/FruDevice/" + std::to_string(bus) + "_" +
182                 std::to_string(address),
183             "xyz.openbmc_project.Inventory.Item.I2CDevice"));
184     if (!success)
185     {
186         return; // already added
187     }
188     it->second->register_property("Bus", bus);
189     it->second->register_property("Address", address);
190     it->second->initialize();
191 }
192 
193 static std::optional<bool> isDevice16Bit(int file)
194 {
195     // Set the higher data word address bits to 0. It's safe on 8-bit addressing
196     // EEPROMs because it doesn't write any actual data.
197     int ret = i2c_smbus_write_byte(file, 0);
198     if (ret < 0)
199     {
200         return std::nullopt;
201     }
202 
203     /* Get first byte */
204     int byte1 = i2c_smbus_read_byte_data(file, 0);
205     if (byte1 < 0)
206     {
207         return std::nullopt;
208     }
209     /* Read 7 more bytes, it will read same first byte in case of
210      * 8 bit but it will read next byte in case of 16 bit
211      */
212     for (int i = 0; i < 7; i++)
213     {
214         int byte2 = i2c_smbus_read_byte_data(file, 0);
215         if (byte2 < 0)
216         {
217             return std::nullopt;
218         }
219         if (byte2 != byte1)
220         {
221             return true;
222         }
223     }
224     return false;
225 }
226 
227 // Issue an I2C transaction to first write to_slave_buf_len bytes,then read
228 // from_slave_buf_len bytes.
229 static int i2cSmbusWriteThenRead(int file, uint16_t address,
230                                  uint8_t* toSlaveBuf, uint8_t toSlaveBufLen,
231                                  uint8_t* fromSlaveBuf, uint8_t fromSlaveBufLen)
232 {
233     if (toSlaveBuf == nullptr || toSlaveBufLen == 0 ||
234         fromSlaveBuf == nullptr || fromSlaveBufLen == 0)
235     {
236         return -1;
237     }
238 
239     constexpr size_t smbusWriteThenReadMsgCount = 2;
240     std::array<struct i2c_msg, smbusWriteThenReadMsgCount> msgs{};
241     struct i2c_rdwr_ioctl_data rdwr
242     {};
243 
244     msgs[0].addr = address;
245     msgs[0].flags = 0;
246     msgs[0].len = toSlaveBufLen;
247     msgs[0].buf = toSlaveBuf;
248     msgs[1].addr = address;
249     msgs[1].flags = I2C_M_RD;
250     msgs[1].len = fromSlaveBufLen;
251     msgs[1].buf = fromSlaveBuf;
252 
253     rdwr.msgs = msgs.data();
254     rdwr.nmsgs = msgs.size();
255 
256     int ret = ioctl(file, I2C_RDWR, &rdwr);
257 
258     return (ret == static_cast<int>(msgs.size())) ? msgs[1].len : -1;
259 }
260 
261 static int64_t readBlockData(bool is16bit, int file, uint16_t address,
262                              off_t offset, size_t len, uint8_t* buf)
263 {
264     if (!is16bit)
265     {
266         return i2c_smbus_read_i2c_block_data(file, static_cast<uint8_t>(offset),
267                                              len, buf);
268     }
269 
270     offset = htobe16(offset);
271     // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
272     uint8_t* u8Offset = reinterpret_cast<uint8_t*>(&offset);
273     return i2cSmbusWriteThenRead(file, address, u8Offset, 2, buf, len);
274 }
275 
276 // TODO: This code is very similar to the non-eeprom version and can be merged
277 // with some tweaks.
278 static std::vector<uint8_t> processEeprom(int bus, int address)
279 {
280     auto path = getEepromPath(bus, address);
281 
282     int file = open(path.c_str(), O_RDONLY);
283     if (file < 0)
284     {
285         std::cerr << "Unable to open eeprom file: " << path << "\n";
286         return {};
287     }
288 
289     std::string errorMessage = "eeprom at " + std::to_string(bus) +
290                                " address " + std::to_string(address);
291     auto readFunc = [file](off_t offset, size_t length, uint8_t* outbuf) {
292         return readFromEeprom(file, offset, length, outbuf);
293     };
294     FRUReader reader(std::move(readFunc));
295     std::vector<uint8_t> device = readFRUContents(reader, errorMessage);
296 
297     close(file);
298     return device;
299 }
300 
301 std::set<int> findI2CEeproms(int i2cBus,
302                              const std::shared_ptr<DeviceMap>& devices)
303 {
304     std::set<int> foundList;
305 
306     std::string path = "/sys/bus/i2c/devices/i2c-" + std::to_string(i2cBus);
307 
308     // For each file listed under the i2c device
309     // NOTE: This should be faster than just checking for each possible address
310     // path.
311     for (const auto& p : fs::directory_iterator(path))
312     {
313         const std::string node = p.path().string();
314         std::smatch m;
315         bool found =
316             std::regex_match(node, m, std::regex(".+\\d+-([0-9abcdef]+$)"));
317 
318         if (!found)
319         {
320             continue;
321         }
322         if (m.size() != 2)
323         {
324             std::cerr << "regex didn't capture\n";
325             continue;
326         }
327 
328         std::ssub_match subMatch = m[1];
329         std::string addressString = subMatch.str();
330 
331         std::size_t ignored = 0;
332         const int hexBase = 16;
333         int address = std::stoi(addressString, &ignored, hexBase);
334 
335         const std::string eeprom = node + "/eeprom";
336 
337         try
338         {
339             if (!fs::exists(eeprom))
340             {
341                 continue;
342             }
343         }
344         catch (...)
345         {
346             continue;
347         }
348 
349         // There is an eeprom file at this address, it may have invalid
350         // contents, but we found it.
351         foundList.insert(address);
352 
353         std::vector<uint8_t> device = processEeprom(i2cBus, address);
354         if (!device.empty())
355         {
356             devices->emplace(address, device);
357         }
358     }
359 
360     return foundList;
361 }
362 
363 int getBusFRUs(int file, int first, int last, int bus,
364                std::shared_ptr<DeviceMap> devices, const bool& powerIsOn,
365                sdbusplus::asio::object_server& objServer)
366 {
367 
368     std::future<int> future = std::async(std::launch::async, [&]() {
369         // NOTE: When reading the devices raw on the bus, it can interfere with
370         // the driver's ability to operate, therefore read eeproms first before
371         // scanning for devices without drivers. Several experiments were run
372         // and it was determined that if there were any devices on the bus
373         // before the eeprom was hit and read, the eeprom driver wouldn't open
374         // while the bus device was open. An experiment was not performed to see
375         // if this issue was resolved if the i2c bus device was closed, but
376         // hexdumps of the eeprom later were successful.
377 
378         // Scan for i2c eeproms loaded on this bus.
379         std::set<int> skipList = findI2CEeproms(bus, devices);
380         std::set<size_t>& failedItems = failedAddresses[bus];
381         std::set<size_t>& foundItems = fruAddresses[bus];
382         foundItems.clear();
383 
384         std::set<size_t>* rootFailures = nullptr;
385         int rootBus = getRootBus(bus);
386 
387         if (rootBus >= 0)
388         {
389             rootFailures = &(failedAddresses[rootBus]);
390             foundItems = fruAddresses[rootBus];
391         }
392 
393         constexpr int startSkipSlaveAddr = 0;
394         constexpr int endSkipSlaveAddr = 12;
395 
396         for (int ii = first; ii <= last; ii++)
397         {
398             if (foundItems.find(ii) != foundItems.end())
399             {
400                 continue;
401             }
402             if (skipList.find(ii) != skipList.end())
403             {
404                 continue;
405             }
406             // skipping since no device is present in this range
407             if (ii >= startSkipSlaveAddr && ii <= endSkipSlaveAddr)
408             {
409                 continue;
410             }
411             // Set slave address
412             if (ioctl(file, I2C_SLAVE, ii) < 0)
413             {
414                 std::cerr << "device at bus " << bus << " address " << ii
415                           << " busy\n";
416                 continue;
417             }
418             // probe
419             if (i2c_smbus_read_byte(file) < 0)
420             {
421                 continue;
422             }
423 
424             if (debug)
425             {
426                 std::cout << "something at bus " << bus << " addr " << ii
427                           << "\n";
428             }
429 
430             makeProbeInterface(bus, ii, objServer);
431 
432             if (failedItems.find(ii) != failedItems.end())
433             {
434                 // if we failed to read it once, unlikely we can read it later
435                 continue;
436             }
437 
438             if (rootFailures != nullptr)
439             {
440                 if (rootFailures->find(ii) != rootFailures->end())
441                 {
442                     continue;
443                 }
444             }
445 
446             /* Check for Device type if it is 8 bit or 16 bit */
447             std::optional<bool> is16Bit = isDevice16Bit(file);
448             if (!is16Bit.has_value())
449             {
450                 std::cerr << "failed to read bus " << bus << " address " << ii
451                           << "\n";
452                 if (powerIsOn)
453                 {
454                     failedItems.insert(ii);
455                 }
456                 continue;
457             }
458             bool is16BitBool{*is16Bit};
459 
460             auto readFunc = [is16BitBool, file, ii](off_t offset, size_t length,
461                                                     uint8_t* outbuf) {
462                 return readBlockData(is16BitBool, file, ii, offset, length,
463                                      outbuf);
464             };
465             FRUReader reader(std::move(readFunc));
466             std::string errorMessage =
467                 "bus " + std::to_string(bus) + " address " + std::to_string(ii);
468             std::vector<uint8_t> device = readFRUContents(reader, errorMessage);
469             if (device.empty())
470             {
471                 continue;
472             }
473 
474             devices->emplace(ii, device);
475             fruAddresses[bus].insert(ii);
476         }
477         return 1;
478     });
479     std::future_status status =
480         future.wait_for(std::chrono::seconds(busTimeoutSeconds));
481     if (status == std::future_status::timeout)
482     {
483         std::cerr << "Error reading bus " << bus << "\n";
484         if (powerIsOn)
485         {
486             busBlacklist.insert(bus);
487         }
488         close(file);
489         return -1;
490     }
491 
492     close(file);
493     return future.get();
494 }
495 
496 void loadBlacklist(const char* path)
497 {
498     std::ifstream blacklistStream(path);
499     if (!blacklistStream.good())
500     {
501         // File is optional.
502         std::cerr << "Cannot open blacklist file.\n\n";
503         return;
504     }
505 
506     nlohmann::json data =
507         nlohmann::json::parse(blacklistStream, nullptr, false);
508     if (data.is_discarded())
509     {
510         std::cerr << "Illegal blacklist file detected, cannot validate JSON, "
511                      "exiting\n";
512         std::exit(EXIT_FAILURE);
513     }
514 
515     // It's expected to have at least one field, "buses" that is an array of the
516     // buses by integer. Allow for future options to exclude further aspects,
517     // such as specific addresses or ranges.
518     if (data.type() != nlohmann::json::value_t::object)
519     {
520         std::cerr << "Illegal blacklist, expected to read dictionary\n";
521         std::exit(EXIT_FAILURE);
522     }
523 
524     // If buses field is missing, that's fine.
525     if (data.count("buses") == 1)
526     {
527         // Parse the buses array after a little validation.
528         auto buses = data.at("buses");
529         if (buses.type() != nlohmann::json::value_t::array)
530         {
531             // Buses field present but invalid, therefore this is an error.
532             std::cerr << "Invalid contents for blacklist buses field\n";
533             std::exit(EXIT_FAILURE);
534         }
535 
536         // Catch exception here for type mis-match.
537         try
538         {
539             for (const auto& bus : buses)
540             {
541                 busBlacklist.insert(bus.get<size_t>());
542             }
543         }
544         catch (const nlohmann::detail::type_error& e)
545         {
546             // Type mis-match is a critical error.
547             std::cerr << "Invalid bus type: " << e.what() << "\n";
548             std::exit(EXIT_FAILURE);
549         }
550     }
551 }
552 
553 static void findI2CDevices(const std::vector<fs::path>& i2cBuses,
554                            BusMap& busmap, const bool& powerIsOn,
555                            sdbusplus::asio::object_server& objServer)
556 {
557     for (const auto& i2cBus : i2cBuses)
558     {
559         int bus = busStrToInt(i2cBus.string());
560 
561         if (bus < 0)
562         {
563             std::cerr << "Cannot translate " << i2cBus << " to int\n";
564             continue;
565         }
566         if (busBlacklist.find(bus) != busBlacklist.end())
567         {
568             continue; // skip previously failed busses
569         }
570 
571         int rootBus = getRootBus(bus);
572         if (busBlacklist.find(rootBus) != busBlacklist.end())
573         {
574             continue;
575         }
576 
577         auto file = open(i2cBus.c_str(), O_RDWR);
578         if (file < 0)
579         {
580             std::cerr << "unable to open i2c device " << i2cBus.string()
581                       << "\n";
582             continue;
583         }
584         unsigned long funcs = 0;
585 
586         if (ioctl(file, I2C_FUNCS, &funcs) < 0)
587         {
588             std::cerr
589                 << "Error: Could not get the adapter functionality matrix bus "
590                 << bus << "\n";
591             close(file);
592             continue;
593         }
594         if (((funcs & I2C_FUNC_SMBUS_READ_BYTE) == 0U) ||
595             ((I2C_FUNC_SMBUS_READ_I2C_BLOCK) == 0))
596         {
597             std::cerr << "Error: Can't use SMBus Receive Byte command bus "
598                       << bus << "\n";
599             continue;
600         }
601         auto& device = busmap[bus];
602         device = std::make_shared<DeviceMap>();
603 
604         //  i2cdetect by default uses the range 0x03 to 0x77, as
605         //  this is  what we have tested with, use this range. Could be
606         //  changed in future.
607         if (debug)
608         {
609             std::cerr << "Scanning bus " << bus << "\n";
610         }
611 
612         // fd is closed in this function in case the bus locks up
613         getBusFRUs(file, 0x03, 0x77, bus, device, powerIsOn, objServer);
614 
615         if (debug)
616         {
617             std::cerr << "Done scanning bus " << bus << "\n";
618         }
619     }
620 }
621 
622 // this class allows an async response after all i2c devices are discovered
623 struct FindDevicesWithCallback :
624     std::enable_shared_from_this<FindDevicesWithCallback>
625 {
626     FindDevicesWithCallback(const std::vector<fs::path>& i2cBuses,
627                             BusMap& busmap, const bool& powerIsOn,
628                             sdbusplus::asio::object_server& objServer,
629                             std::function<void(void)>&& callback) :
630         _i2cBuses(i2cBuses),
631         _busMap(busmap), _powerIsOn(powerIsOn), _objServer(objServer),
632         _callback(std::move(callback))
633     {}
634     ~FindDevicesWithCallback()
635     {
636         _callback();
637     }
638     void run()
639     {
640         findI2CDevices(_i2cBuses, _busMap, _powerIsOn, _objServer);
641     }
642 
643     const std::vector<fs::path>& _i2cBuses;
644     BusMap& _busMap;
645     const bool& _powerIsOn;
646     sdbusplus::asio::object_server& _objServer;
647     std::function<void(void)> _callback;
648 };
649 
650 void addFruObjectToDbus(
651     std::vector<uint8_t>& device,
652     boost::container::flat_map<
653         std::pair<size_t, size_t>,
654         std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
655     uint32_t bus, uint32_t address, size_t& unknownBusObjectCount,
656     const bool& powerIsOn, sdbusplus::asio::object_server& objServer,
657     std::shared_ptr<sdbusplus::asio::connection>& systemBus)
658 {
659     boost::container::flat_map<std::string, std::string> formattedFRU;
660 
661     std::optional<std::string> optionalProductName = getProductName(
662         device, formattedFRU, bus, address, unknownBusObjectCount);
663     if (!optionalProductName)
664     {
665         std::cerr << "getProductName failed. product name is empty.\n";
666         return;
667     }
668 
669     std::string productName =
670         "/xyz/openbmc_project/FruDevice/" + optionalProductName.value();
671 
672     std::optional<int> index = findIndexForFRU(dbusInterfaceMap, productName);
673     if (index.has_value())
674     {
675         productName += "_";
676         productName += std::to_string(++(*index));
677     }
678 
679     std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
680         objServer.add_interface(productName, "xyz.openbmc_project.FruDevice");
681     dbusInterfaceMap[std::pair<size_t, size_t>(bus, address)] = iface;
682 
683     for (auto& property : formattedFRU)
684     {
685 
686         std::regex_replace(property.second.begin(), property.second.begin(),
687                            property.second.end(), nonAsciiRegex, "_");
688         if (property.second.empty() && property.first != "PRODUCT_ASSET_TAG")
689         {
690             continue;
691         }
692         std::string key =
693             std::regex_replace(property.first, nonAsciiRegex, "_");
694 
695         if (property.first == "PRODUCT_ASSET_TAG")
696         {
697             std::string propertyName = property.first;
698             iface->register_property(
699                 key, property.second + '\0',
700                 [bus, address, propertyName, &dbusInterfaceMap,
701                  &unknownBusObjectCount, &powerIsOn, &objServer,
702                  &systemBus](const std::string& req, std::string& resp) {
703                     if (strcmp(req.c_str(), resp.c_str()) != 0)
704                     {
705                         // call the method which will update
706                         if (updateFRUProperty(req, bus, address, propertyName,
707                                               dbusInterfaceMap,
708                                               unknownBusObjectCount, powerIsOn,
709                                               objServer, systemBus))
710                         {
711                             resp = req;
712                         }
713                         else
714                         {
715                             throw std::invalid_argument(
716                                 "FRU property update failed.");
717                         }
718                     }
719                     return 1;
720                 });
721         }
722         else if (!iface->register_property(key, property.second + '\0'))
723         {
724             std::cerr << "illegal key: " << key << "\n";
725         }
726         if (debug)
727         {
728             std::cout << property.first << ": " << property.second << "\n";
729         }
730     }
731 
732     // baseboard will be 0, 0
733     iface->register_property("BUS", bus);
734     iface->register_property("ADDRESS", address);
735 
736     iface->initialize();
737 }
738 
739 static bool readBaseboardFRU(std::vector<uint8_t>& baseboardFRU)
740 {
741     // try to read baseboard fru from file
742     std::ifstream baseboardFRUFile(baseboardFruLocation, std::ios::binary);
743     if (baseboardFRUFile.good())
744     {
745         baseboardFRUFile.seekg(0, std::ios_base::end);
746         size_t fileSize = static_cast<size_t>(baseboardFRUFile.tellg());
747         baseboardFRU.resize(fileSize);
748         baseboardFRUFile.seekg(0, std::ios_base::beg);
749         // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
750         char* charOffset = reinterpret_cast<char*>(baseboardFRU.data());
751         baseboardFRUFile.read(charOffset, fileSize);
752     }
753     else
754     {
755         return false;
756     }
757     return true;
758 }
759 
760 bool writeFRU(uint8_t bus, uint8_t address, const std::vector<uint8_t>& fru)
761 {
762     boost::container::flat_map<std::string, std::string> tmp;
763     if (fru.size() > maxFruSize)
764     {
765         std::cerr << "Invalid fru.size() during writeFRU\n";
766         return false;
767     }
768     // verify legal fru by running it through fru parsing logic
769     if (formatIPMIFRU(fru, tmp) != resCodes::resOK)
770     {
771         std::cerr << "Invalid fru format during writeFRU\n";
772         return false;
773     }
774     // baseboard fru
775     if (bus == 0 && address == 0)
776     {
777         std::ofstream file(baseboardFruLocation, std::ios_base::binary);
778         if (!file.good())
779         {
780             std::cerr << "Error opening file " << baseboardFruLocation << "\n";
781             throw DBusInternalError();
782             return false;
783         }
784         // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
785         const char* charOffset = reinterpret_cast<const char*>(fru.data());
786         file.write(charOffset, fru.size());
787         return file.good();
788     }
789 
790     if (hasEepromFile(bus, address))
791     {
792         auto path = getEepromPath(bus, address);
793         int eeprom = open(path.c_str(), O_RDWR | O_CLOEXEC);
794         if (eeprom < 0)
795         {
796             std::cerr << "unable to open i2c device " << path << "\n";
797             throw DBusInternalError();
798             return false;
799         }
800 
801         ssize_t writtenBytes = write(eeprom, fru.data(), fru.size());
802         if (writtenBytes < 0)
803         {
804             std::cerr << "unable to write to i2c device " << path << "\n";
805             close(eeprom);
806             throw DBusInternalError();
807             return false;
808         }
809 
810         close(eeprom);
811         return true;
812     }
813 
814     std::string i2cBus = "/dev/i2c-" + std::to_string(bus);
815 
816     int file = open(i2cBus.c_str(), O_RDWR | O_CLOEXEC);
817     if (file < 0)
818     {
819         std::cerr << "unable to open i2c device " << i2cBus << "\n";
820         throw DBusInternalError();
821         return false;
822     }
823     if (ioctl(file, I2C_SLAVE_FORCE, address) < 0)
824     {
825         std::cerr << "unable to set device address\n";
826         close(file);
827         throw DBusInternalError();
828         return false;
829     }
830 
831     constexpr const size_t retryMax = 2;
832     uint16_t index = 0;
833     size_t retries = retryMax;
834     while (index < fru.size())
835     {
836         if (((index != 0U) && ((index % (maxEepromPageIndex + 1)) == 0)) &&
837             (retries == retryMax))
838         {
839             // The 4K EEPROM only uses the A2 and A1 device address bits
840             // with the third bit being a memory page address bit.
841             if (ioctl(file, I2C_SLAVE_FORCE, ++address) < 0)
842             {
843                 std::cerr << "unable to set device address\n";
844                 close(file);
845                 throw DBusInternalError();
846                 return false;
847             }
848         }
849 
850         if (i2c_smbus_write_byte_data(file, static_cast<uint8_t>(index),
851                                       fru[index]) < 0)
852         {
853             if ((retries--) == 0U)
854             {
855                 std::cerr << "error writing fru: " << strerror(errno) << "\n";
856                 close(file);
857                 throw DBusInternalError();
858                 return false;
859             }
860         }
861         else
862         {
863             retries = retryMax;
864             index++;
865         }
866         // most eeproms require 5-10ms between writes
867         std::this_thread::sleep_for(std::chrono::milliseconds(10));
868     }
869     close(file);
870     return true;
871 }
872 
873 void rescanOneBus(
874     BusMap& busmap, uint16_t busNum,
875     boost::container::flat_map<
876         std::pair<size_t, size_t>,
877         std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
878     bool dbusCall, size_t& unknownBusObjectCount, const bool& powerIsOn,
879     sdbusplus::asio::object_server& objServer,
880     std::shared_ptr<sdbusplus::asio::connection>& systemBus)
881 {
882     for (auto& [pair, interface] : foundDevices)
883     {
884         if (pair.first == static_cast<size_t>(busNum))
885         {
886             objServer.remove_interface(interface);
887             foundDevices.erase(pair);
888         }
889     }
890 
891     fs::path busPath = fs::path("/dev/i2c-" + std::to_string(busNum));
892     if (!fs::exists(busPath))
893     {
894         if (dbusCall)
895         {
896             std::cerr << "Unable to access i2c bus " << static_cast<int>(busNum)
897                       << "\n";
898             throw std::invalid_argument("Invalid Bus.");
899         }
900         return;
901     }
902 
903     std::vector<fs::path> i2cBuses;
904     i2cBuses.emplace_back(busPath);
905 
906     auto scan = std::make_shared<FindDevicesWithCallback>(
907         i2cBuses, busmap, powerIsOn, objServer,
908         [busNum, &busmap, &dbusInterfaceMap, &unknownBusObjectCount, &powerIsOn,
909          &objServer, &systemBus]() {
910             for (auto& busIface : dbusInterfaceMap)
911             {
912                 if (busIface.first.first == static_cast<size_t>(busNum))
913                 {
914                     objServer.remove_interface(busIface.second);
915                 }
916             }
917             auto found = busmap.find(busNum);
918             if (found == busmap.end() || found->second == nullptr)
919             {
920                 return;
921             }
922             for (auto& device : *(found->second))
923             {
924                 addFruObjectToDbus(device.second, dbusInterfaceMap,
925                                    static_cast<uint32_t>(busNum), device.first,
926                                    unknownBusObjectCount, powerIsOn, objServer,
927                                    systemBus);
928             }
929         });
930     scan->run();
931 }
932 
933 void rescanBusses(
934     BusMap& busmap,
935     boost::container::flat_map<
936         std::pair<size_t, size_t>,
937         std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
938     size_t& unknownBusObjectCount, const bool& powerIsOn,
939     sdbusplus::asio::object_server& objServer,
940     std::shared_ptr<sdbusplus::asio::connection>& systemBus)
941 {
942     static boost::asio::deadline_timer timer(io);
943     timer.expires_from_now(boost::posix_time::seconds(1));
944 
945     // setup an async wait in case we get flooded with requests
946     timer.async_wait([&](const boost::system::error_code& ec) {
947         if (ec == boost::asio::error::operation_aborted)
948         {
949             return;
950         }
951 
952         if (ec)
953         {
954             std::cerr << "Error in timer: " << ec.message() << "\n";
955             return;
956         }
957 
958         auto devDir = fs::path("/dev/");
959         std::vector<fs::path> i2cBuses;
960 
961         boost::container::flat_map<size_t, fs::path> busPaths;
962         if (!getI2cDevicePaths(devDir, busPaths))
963         {
964             std::cerr << "unable to find i2c devices\n";
965             return;
966         }
967 
968         for (const auto& busPath : busPaths)
969         {
970             i2cBuses.emplace_back(busPath.second);
971         }
972 
973         busmap.clear();
974         for (auto& [pair, interface] : foundDevices)
975         {
976             objServer.remove_interface(interface);
977         }
978         foundDevices.clear();
979 
980         auto scan = std::make_shared<FindDevicesWithCallback>(
981             i2cBuses, busmap, powerIsOn, objServer, [&]() {
982                 for (auto& busIface : dbusInterfaceMap)
983                 {
984                     objServer.remove_interface(busIface.second);
985                 }
986 
987                 dbusInterfaceMap.clear();
988                 unknownBusObjectCount = 0;
989 
990                 // todo, get this from a more sensable place
991                 std::vector<uint8_t> baseboardFRU;
992                 if (readBaseboardFRU(baseboardFRU))
993                 {
994                     // If no device on i2c bus 0, the insertion will happen.
995                     auto bus0 =
996                         busmap.try_emplace(0, std::make_shared<DeviceMap>());
997                     bus0.first->second->emplace(0, baseboardFRU);
998                 }
999                 for (auto& devicemap : busmap)
1000                 {
1001                     for (auto& device : *devicemap.second)
1002                     {
1003                         addFruObjectToDbus(device.second, dbusInterfaceMap,
1004                                            devicemap.first, device.first,
1005                                            unknownBusObjectCount, powerIsOn,
1006                                            objServer, systemBus);
1007                     }
1008                 }
1009             });
1010         scan->run();
1011     });
1012 }
1013 
1014 // Details with example of Asset Tag Update
1015 // To find location of Product Info Area asset tag as per FRU specification
1016 // 1. Find product Info area starting offset (*8 - as header will be in
1017 // multiple of 8 bytes).
1018 // 2. Skip 3 bytes of product info area (like format version, area length,
1019 // and language code).
1020 // 3. Traverse manufacturer name, product name, product version, & product
1021 // serial number, by reading type/length code to reach the Asset Tag.
1022 // 4. Update the Asset Tag, reposition the product Info area in multiple of
1023 // 8 bytes. Update the Product area length and checksum.
1024 
1025 bool updateFRUProperty(
1026     const std::string& updatePropertyReq, uint32_t bus, uint32_t address,
1027     const std::string& propertyName,
1028     boost::container::flat_map<
1029         std::pair<size_t, size_t>,
1030         std::shared_ptr<sdbusplus::asio::dbus_interface>>& dbusInterfaceMap,
1031     size_t& unknownBusObjectCount, const bool& powerIsOn,
1032     sdbusplus::asio::object_server& objServer,
1033     std::shared_ptr<sdbusplus::asio::connection>& systemBus)
1034 {
1035     size_t updatePropertyReqLen = updatePropertyReq.length();
1036     if (updatePropertyReqLen == 1 || updatePropertyReqLen > 63)
1037     {
1038         std::cerr
1039             << "FRU field data cannot be of 1 char or more than 63 chars. "
1040                "Invalid Length "
1041             << updatePropertyReqLen << "\n";
1042         return false;
1043     }
1044 
1045     std::vector<uint8_t> fruData;
1046 
1047     if (!getFruData(fruData, bus, address))
1048     {
1049         std::cerr << "Failure getting FRU Data \n";
1050         return false;
1051     }
1052 
1053     struct FruArea fruAreaParams
1054     {};
1055 
1056     if (!findFruAreaLocationAndField(fruData, propertyName, fruAreaParams))
1057     {
1058         std::cerr << "findFruAreaLocationAndField failed \n";
1059         return false;
1060     }
1061 
1062     std::vector<uint8_t> restFRUAreaFieldsData;
1063     if (!copyRestFRUArea(fruData, propertyName, fruAreaParams,
1064                          restFRUAreaFieldsData))
1065     {
1066         std::cerr << "copyRestFRUArea failed \n";
1067         return false;
1068     }
1069 
1070     // Push post update fru areas if any
1071     unsigned int nextFRUAreaLoc = 0;
1072     for (fruAreas nextFRUArea = fruAreas::fruAreaInternal;
1073          nextFRUArea <= fruAreas::fruAreaMultirecord; ++nextFRUArea)
1074     {
1075         unsigned int fruAreaLoc =
1076             fruData[getHeaderAreaFieldOffset(nextFRUArea)] * fruBlockSize;
1077         if ((fruAreaLoc > fruAreaParams.restFieldsEnd) &&
1078             ((nextFRUAreaLoc == 0) || (fruAreaLoc < nextFRUAreaLoc)))
1079         {
1080             nextFRUAreaLoc = fruAreaLoc;
1081         }
1082     }
1083     std::vector<uint8_t> restFRUAreasData;
1084     if (nextFRUAreaLoc != 0U)
1085     {
1086         std::copy_n(fruData.begin() + nextFRUAreaLoc,
1087                     fruData.size() - nextFRUAreaLoc,
1088                     std::back_inserter(restFRUAreasData));
1089     }
1090 
1091     // check FRU area size
1092     size_t fruAreaDataSize =
1093         ((fruAreaParams.updateFieldLoc - fruAreaParams.start + 1) +
1094          restFRUAreaFieldsData.size());
1095     size_t fruAreaAvailableSize = fruAreaParams.size - fruAreaDataSize;
1096     if ((updatePropertyReqLen + 1) > fruAreaAvailableSize)
1097     {
1098 
1099 #ifdef ENABLE_FRU_AREA_RESIZE
1100         size_t newFRUAreaSize = fruAreaDataSize + updatePropertyReqLen + 1;
1101         // round size to 8-byte blocks
1102         newFRUAreaSize =
1103             ((newFRUAreaSize - 1) / fruBlockSize + 1) * fruBlockSize;
1104         size_t newFRUDataSize =
1105             fruData.size() + newFRUAreaSize - fruAreaParams.size;
1106         fruData.resize(newFRUDataSize);
1107         fruAreaParams.size = newFRUAreaSize;
1108         fruAreaParams.end = fruAreaParams.start + fruAreaParams.size;
1109 #else
1110         std::cerr << "FRU field length: " << updatePropertyReqLen + 1
1111                   << " should not be greater than available FRU area size: "
1112                   << fruAreaAvailableSize << "\n";
1113         return false;
1114 #endif // ENABLE_FRU_AREA_RESIZE
1115     }
1116 
1117     // write new requested property field length and data
1118     constexpr uint8_t newTypeLenMask = 0xC0;
1119     fruData[fruAreaParams.updateFieldLoc] =
1120         static_cast<uint8_t>(updatePropertyReqLen | newTypeLenMask);
1121     fruAreaParams.updateFieldLoc++;
1122     std::copy(updatePropertyReq.begin(), updatePropertyReq.end(),
1123               fruData.begin() + fruAreaParams.updateFieldLoc);
1124 
1125     // Copy remaining data to main fru area - post updated fru field vector
1126     fruAreaParams.restFieldsLoc =
1127         fruAreaParams.updateFieldLoc + updatePropertyReqLen;
1128     size_t fruAreaDataEnd =
1129         fruAreaParams.restFieldsLoc + restFRUAreaFieldsData.size();
1130 
1131     std::copy(restFRUAreaFieldsData.begin(), restFRUAreaFieldsData.end(),
1132               fruData.begin() + fruAreaParams.restFieldsLoc);
1133 
1134     // Update final fru with new fru area length and checksum
1135     unsigned int nextFRUAreaNewLoc = updateFRUAreaLenAndChecksum(
1136         fruData, fruAreaParams.start, fruAreaDataEnd, fruAreaParams.end);
1137 
1138 #ifdef ENABLE_FRU_AREA_RESIZE
1139     ++nextFRUAreaNewLoc;
1140     ssize_t nextFRUAreaOffsetDiff =
1141         (nextFRUAreaNewLoc - nextFRUAreaLoc) / fruBlockSize;
1142     // Append rest FRU Areas if size changed and there were other sections after
1143     // updated one
1144     if (nextFRUAreaOffsetDiff && nextFRUAreaLoc)
1145     {
1146         std::copy(restFRUAreasData.begin(), restFRUAreasData.end(),
1147                   fruData.begin() + nextFRUAreaNewLoc);
1148         // Update Common Header
1149         for (int fruArea = fruAreaInternal; fruArea <= fruAreaMultirecord;
1150              fruArea++)
1151         {
1152             unsigned int fruAreaOffsetField = getHeaderAreaFieldOffset(fruArea);
1153             size_t curFRUAreaOffset = fruData[fruAreaOffsetField];
1154             if (curFRUAreaOffset > fruAreaOffsetFieldValue)
1155             {
1156                 fruData[fruAreaOffsetField] = static_cast<int8_t>(
1157                     curFRUAreaOffset + nextFRUAreaOffsetDiff);
1158             }
1159         }
1160         // Calculate new checksum
1161         std::vector<uint8_t> headerFRUData;
1162         std::copy_n(fruData.begin(), 7, std::back_inserter(headerFRUData));
1163         size_t checksumVal = calculateChecksum(headerFRUData);
1164         fruData[7] = static_cast<uint8_t>(checksumVal);
1165         // fill zeros if FRU Area size decreased
1166         if (nextFRUAreaOffsetDiff < 0)
1167         {
1168             std::fill(fruData.begin() + nextFRUAreaNewLoc +
1169                           restFRUAreasData.size(),
1170                       fruData.end(), 0);
1171         }
1172     }
1173 #else
1174     // this is to avoid "unused variable" warning
1175     (void)nextFRUAreaNewLoc;
1176 #endif // ENABLE_FRU_AREA_RESIZE
1177     if (fruData.empty())
1178     {
1179         return false;
1180     }
1181 
1182     if (!writeFRU(static_cast<uint8_t>(bus), static_cast<uint8_t>(address),
1183                   fruData))
1184     {
1185         return false;
1186     }
1187 
1188     // Rescan the bus so that GetRawFru dbus-call fetches updated values
1189     rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1190                  objServer, systemBus);
1191     return true;
1192 }
1193 
1194 int main()
1195 {
1196     auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);
1197     sdbusplus::asio::object_server objServer(systemBus);
1198 
1199     static size_t unknownBusObjectCount = 0;
1200     static bool powerIsOn = false;
1201     auto devDir = fs::path("/dev/");
1202     auto matchString = std::string(R"(i2c-\d+$)");
1203     std::vector<fs::path> i2cBuses;
1204 
1205     if (!findFiles(devDir, matchString, i2cBuses))
1206     {
1207         std::cerr << "unable to find i2c devices\n";
1208         return 1;
1209     }
1210 
1211     // check for and load blacklist with initial buses.
1212     loadBlacklist(blacklistPath);
1213 
1214     systemBus->request_name("xyz.openbmc_project.FruDevice");
1215 
1216     // this is a map with keys of pair(bus number, address) and values of
1217     // the object on dbus
1218     boost::container::flat_map<std::pair<size_t, size_t>,
1219                                std::shared_ptr<sdbusplus::asio::dbus_interface>>
1220         dbusInterfaceMap;
1221 
1222     std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
1223         objServer.add_interface("/xyz/openbmc_project/FruDevice",
1224                                 "xyz.openbmc_project.FruDeviceManager");
1225 
1226     iface->register_method("ReScan", [&]() {
1227         rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1228                      objServer, systemBus);
1229     });
1230 
1231     iface->register_method("ReScanBus", [&](uint16_t bus) {
1232         rescanOneBus(busMap, bus, dbusInterfaceMap, true, unknownBusObjectCount,
1233                      powerIsOn, objServer, systemBus);
1234     });
1235 
1236     iface->register_method("GetRawFru", getFRUInfo);
1237 
1238     iface->register_method("WriteFru", [&](const uint16_t bus,
1239                                            const uint8_t address,
1240                                            const std::vector<uint8_t>& data) {
1241         if (!writeFRU(bus, address, data))
1242         {
1243             throw std::invalid_argument("Invalid Arguments.");
1244             return;
1245         }
1246         // schedule rescan on success
1247         rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1248                      objServer, systemBus);
1249     });
1250     iface->initialize();
1251 
1252     std::function<void(sdbusplus::message_t & message)> eventHandler =
1253         [&](sdbusplus::message_t& message) {
1254             std::string objectName;
1255             boost::container::flat_map<
1256                 std::string,
1257                 std::variant<std::string, bool, int64_t, uint64_t, double>>
1258                 values;
1259             message.read(objectName, values);
1260             auto findState = values.find("CurrentHostState");
1261             if (findState != values.end())
1262             {
1263                 if (std::get<std::string>(findState->second) ==
1264                     "xyz.openbmc_project.State.Host.HostState.Running")
1265                 {
1266                     powerIsOn = true;
1267                 }
1268             }
1269 
1270             if (powerIsOn)
1271             {
1272                 rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount,
1273                              powerIsOn, objServer, systemBus);
1274             }
1275         };
1276 
1277     sdbusplus::bus::match_t powerMatch = sdbusplus::bus::match_t(
1278         static_cast<sdbusplus::bus_t&>(*systemBus),
1279         "type='signal',interface='org.freedesktop.DBus.Properties',path='/xyz/"
1280         "openbmc_project/state/"
1281         "host0',arg0='xyz.openbmc_project.State.Host'",
1282         eventHandler);
1283 
1284     int fd = inotify_init();
1285     inotify_add_watch(fd, i2CDevLocation, IN_CREATE | IN_MOVED_TO | IN_DELETE);
1286     std::array<char, 4096> readBuffer{};
1287     // monitor for new i2c devices
1288     boost::asio::posix::stream_descriptor dirWatch(io, fd);
1289     std::function<void(const boost::system::error_code, std::size_t)>
1290         watchI2cBusses = [&](const boost::system::error_code& ec,
1291                              std::size_t bytesTransferred) {
1292             if (ec)
1293             {
1294                 std::cout << "Callback Error " << ec << "\n";
1295                 return;
1296             }
1297             size_t index = 0;
1298             while ((index + sizeof(inotify_event)) <= bytesTransferred)
1299             {
1300                 const char* p = &readBuffer[index];
1301                 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
1302                 const auto* iEvent = reinterpret_cast<const inotify_event*>(p);
1303                 switch (iEvent->mask)
1304                 {
1305                     case IN_CREATE:
1306                     case IN_MOVED_TO:
1307                     case IN_DELETE:
1308                         std::string_view name(&iEvent->name[0], iEvent->len);
1309                         if (boost::starts_with(name, "i2c"))
1310                         {
1311                             int bus = busStrToInt(name);
1312                             if (bus < 0)
1313                             {
1314                                 std::cerr << "Could not parse bus " << name
1315                                           << "\n";
1316                                 continue;
1317                             }
1318                             rescanOneBus(busMap, static_cast<uint16_t>(bus),
1319                                          dbusInterfaceMap, false,
1320                                          unknownBusObjectCount, powerIsOn,
1321                                          objServer, systemBus);
1322                         }
1323                 }
1324                 index += sizeof(inotify_event) + iEvent->len;
1325             }
1326 
1327             dirWatch.async_read_some(boost::asio::buffer(readBuffer),
1328                                      watchI2cBusses);
1329         };
1330 
1331     dirWatch.async_read_some(boost::asio::buffer(readBuffer), watchI2cBusses);
1332     // run the initial scan
1333     rescanBusses(busMap, dbusInterfaceMap, unknownBusObjectCount, powerIsOn,
1334                  objServer, systemBus);
1335 
1336     io.run();
1337     return 0;
1338 }
1339