xref: /openbmc/pldm/libpldmresponder/fru.cpp (revision 0ce1424f)
1 #include "fru.hpp"
2 
3 #include "libpldm/entity.h"
4 #include "libpldm/utils.h"
5 
6 #include "common/utils.hpp"
7 
8 #include <config.h>
9 #include <systemd/sd-journal.h>
10 
11 #include <sdbusplus/bus.hpp>
12 
13 #include <iostream>
14 #include <set>
15 
16 namespace pldm
17 {
18 
19 namespace responder
20 {
21 
22 void FruImpl::buildFRUTable()
23 {
24     if (isBuilt)
25     {
26         return;
27     }
28 
29     fru_parser::DBusLookupInfo dbusInfo;
30     // Read the all the inventory D-Bus objects
31     auto& bus = pldm::utils::DBusHandler::getBus();
32     dbus::ObjectValueTree objects;
33 
34     try
35     {
36         dbusInfo = parser.inventoryLookup();
37         auto method = bus.new_method_call(
38             std::get<0>(dbusInfo).c_str(), std::get<1>(dbusInfo).c_str(),
39             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
40         auto reply = bus.call(method);
41         reply.read(objects);
42     }
43     catch (const std::exception& e)
44     {
45         std::cerr << "Look up of inventory objects failed and PLDM FRU table "
46                      "creation failed\n";
47         return;
48     }
49 
50     auto itemIntfsLookup = std::get<2>(dbusInfo);
51 
52     for (const auto& object : objects)
53     {
54         const auto& interfaces = object.second;
55 
56         for (const auto& interface : interfaces)
57         {
58             if (itemIntfsLookup.find(interface.first) != itemIntfsLookup.end())
59             {
60                 // An exception will be thrown by getRecordInfo, if the item
61                 // D-Bus interface name specified in FRU_Master.json does
62                 // not have corresponding config jsons
63                 try
64                 {
65                     pldm_entity entity{};
66                     entity.entity_type = parser.getEntityType(interface.first);
67                     pldm_entity_node* parent = nullptr;
68                     auto parentObj = pldm::utils::findParent(object.first.str);
69                     // To add a FRU to the entity association tree, we need to
70                     // determine if the FRU has a parent (D-Bus object). For eg
71                     // /system/backplane's parent is /system. /system has no
72                     // parent. Some D-Bus pathnames might just be namespaces
73                     // (not D-Bus objects), so we need to iterate upwards until
74                     // a parent is found, or we reach the root ("/").
75                     // Parents are always added first before children in the
76                     // entity association tree. We're relying on the fact that
77                     // the std::map containing object paths from the
78                     // GetManagedObjects call will have a sorted pathname list.
79                     do
80                     {
81                         auto iter = objToEntityNode.find(parentObj);
82                         if (iter != objToEntityNode.end())
83                         {
84                             parent = iter->second;
85                             break;
86                         }
87                         parentObj = pldm::utils::findParent(parentObj);
88                     } while (parentObj != "/");
89 
90                     auto node = pldm_entity_association_tree_add(
91                         entityTree, &entity, 0xFFFF, parent,
92                         PLDM_ENTITY_ASSOCIAION_PHYSICAL);
93                     objToEntityNode[object.first.str] = node;
94 
95                     auto recordInfos = parser.getRecordInfo(interface.first);
96                     populateRecords(interfaces, recordInfos, entity);
97 
98                     associatedEntityMap.emplace(object.first, entity);
99                     break;
100                 }
101                 catch (const std::exception& e)
102                 {
103                     std::cout << "Config JSONs missing for the item "
104                                  "interface type, interface = "
105                               << interface.first << "\n";
106                     break;
107                 }
108             }
109         }
110     }
111 
112     pldm_entity_association_pdr_add(entityTree, pdrRepo, false,
113                                     TERMINUS_HANDLE);
114     // save a copy of bmc's entity association tree
115     pldm_entity_association_tree_copy_root(entityTree, bmcEntityTree);
116 
117     if (table.size())
118     {
119         padBytes = utils::getNumPadBytes(table.size());
120         table.resize(table.size() + padBytes, 0);
121 
122         // Calculate the checksum
123         checksum = crc32(table.data(), table.size());
124     }
125     isBuilt = true;
126 }
127 std::string FruImpl::populatefwVersion()
128 {
129     static constexpr auto fwFunctionalObjPath =
130         "/xyz/openbmc_project/software/functional";
131     auto& bus = pldm::utils::DBusHandler::getBus();
132     std::string currentBmcVersion;
133     try
134     {
135         auto method =
136             bus.new_method_call(pldm::utils::mapperService, fwFunctionalObjPath,
137                                 pldm::utils::dbusProperties, "Get");
138         method.append("xyz.openbmc_project.Association", "endpoints");
139         std::variant<std::vector<std::string>> paths;
140         auto reply = bus.call(method);
141         reply.read(paths);
142         auto fwRunningVersion = std::get<std::vector<std::string>>(paths)[0];
143         constexpr auto versionIntf = "xyz.openbmc_project.Software.Version";
144         auto version = pldm::utils::DBusHandler().getDbusPropertyVariant(
145             fwRunningVersion.c_str(), "Version", versionIntf);
146         currentBmcVersion = std::get<std::string>(version);
147     }
148     catch (const std::exception& e)
149     {
150         std::cerr << "failed to make a d-bus call "
151                      "Asociation, ERROR= "
152                   << e.what() << "\n";
153         return {};
154     }
155     return currentBmcVersion;
156 }
157 void FruImpl::populateRecords(
158     const pldm::responder::dbus::InterfaceMap& interfaces,
159     const fru_parser::FruRecordInfos& recordInfos, const pldm_entity& entity)
160 {
161     // recordSetIdentifier for the FRU will be set when the first record gets
162     // added for the FRU
163     uint16_t recordSetIdentifier = 0;
164     auto numRecsCount = numRecs;
165     static uint32_t bmc_record_handle = 0;
166 
167     for (auto const& [recType, encType, fieldInfos] : recordInfos)
168     {
169         std::vector<uint8_t> tlvs;
170         uint8_t numFRUFields = 0;
171         for (auto const& [intf, prop, propType, fieldTypeNum] : fieldInfos)
172         {
173             try
174             {
175                 pldm::responder::dbus::Value propValue;
176 
177                 // Assuming that 0 container Id is assigned to the System (as
178                 // that should be the top most container as per dbus hierarchy)
179                 if (entity.entity_container_id == 0 && prop == "Version")
180                 {
181                     propValue = populatefwVersion();
182                 }
183                 else
184                 {
185                     propValue = interfaces.at(intf).at(prop);
186                 }
187                 if (propType == "bytearray")
188                 {
189                     auto byteArray = std::get<std::vector<uint8_t>>(propValue);
190                     if (!byteArray.size())
191                     {
192                         continue;
193                     }
194 
195                     numFRUFields++;
196                     tlvs.emplace_back(fieldTypeNum);
197                     tlvs.emplace_back(byteArray.size());
198                     std::move(std::begin(byteArray), std::end(byteArray),
199                               std::back_inserter(tlvs));
200                 }
201                 else if (propType == "string")
202                 {
203                     auto str = std::get<std::string>(propValue);
204                     if (!str.size())
205                     {
206                         continue;
207                     }
208 
209                     numFRUFields++;
210                     tlvs.emplace_back(fieldTypeNum);
211                     tlvs.emplace_back(str.size());
212                     std::move(std::begin(str), std::end(str),
213                               std::back_inserter(tlvs));
214                 }
215             }
216             catch (const std::out_of_range& e)
217             {
218                 continue;
219             }
220         }
221 
222         if (tlvs.size())
223         {
224             if (numRecs == numRecsCount)
225             {
226                 recordSetIdentifier = nextRSI();
227                 bmc_record_handle = nextRecordHandle();
228                 pldm_pdr_add_fru_record_set(
229                     pdrRepo, TERMINUS_HANDLE, recordSetIdentifier,
230                     entity.entity_type, entity.entity_instance_num,
231                     entity.entity_container_id, bmc_record_handle);
232             }
233             auto curSize = table.size();
234             table.resize(curSize + recHeaderSize + tlvs.size());
235             encode_fru_record(table.data(), table.size(), &curSize,
236                               recordSetIdentifier, recType, numFRUFields,
237                               encType, tlvs.data(), tlvs.size());
238             numRecs++;
239         }
240     }
241 }
242 
243 void FruImpl::getFRUTable(Response& response)
244 {
245     auto hdrSize = response.size();
246 
247     response.resize(hdrSize + table.size() + sizeof(checksum), 0);
248     std::copy(table.begin(), table.end(), response.begin() + hdrSize);
249 
250     // Copy the checksum to response data
251     auto iter = response.begin() + hdrSize + table.size();
252     std::copy_n(reinterpret_cast<const uint8_t*>(&checksum), sizeof(checksum),
253                 iter);
254 }
255 
256 int FruImpl::getFRURecordByOption(std::vector<uint8_t>& fruData,
257                                   uint16_t /* fruTableHandle */,
258                                   uint16_t recordSetIdentifer,
259                                   uint8_t recordType, uint8_t fieldType)
260 {
261     using sum = uint32_t;
262 
263     // FRU table is built lazily, build if not done.
264     buildFRUTable();
265 
266     /* 7 is sizeof(checksum,4) + padBytesMax(3)
267      * We can not know size of the record table got by options in advance, but
268      * it must be less than the source table. So it's safe to use sizeof the
269      * source table + 7 as the buffer length
270      */
271     size_t recordTableSize = table.size() - padBytes + 7;
272     fruData.resize(recordTableSize, 0);
273 
274     get_fru_record_by_option(table.data(), table.size() - padBytes,
275                              fruData.data(), &recordTableSize,
276                              recordSetIdentifer, recordType, fieldType);
277 
278     if (recordTableSize == 0)
279     {
280         return PLDM_FRU_DATA_STRUCTURE_TABLE_UNAVAILABLE;
281     }
282 
283     auto pads = utils::getNumPadBytes(recordTableSize);
284     crc32(fruData.data(), recordTableSize + pads);
285 
286     auto iter = fruData.begin() + recordTableSize + pads;
287     std::copy_n(reinterpret_cast<const uint8_t*>(&checksum), sizeof(checksum),
288                 iter);
289     fruData.resize(recordTableSize + pads + sizeof(sum));
290 
291     return PLDM_SUCCESS;
292 }
293 
294 namespace fru
295 {
296 
297 Response Handler::getFRURecordTableMetadata(const pldm_msg* request,
298                                             size_t /*payloadLength*/)
299 {
300     // FRU table is built lazily, build if not done.
301     buildFRUTable();
302 
303     constexpr uint8_t major = 0x01;
304     constexpr uint8_t minor = 0x00;
305     constexpr uint32_t maxSize = 0xFFFFFFFF;
306 
307     Response response(sizeof(pldm_msg_hdr) +
308                           PLDM_GET_FRU_RECORD_TABLE_METADATA_RESP_BYTES,
309                       0);
310     auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());
311 
312     auto rc = encode_get_fru_record_table_metadata_resp(
313         request->hdr.instance_id, PLDM_SUCCESS, major, minor, maxSize,
314         impl.size(), impl.numRSI(), impl.numRecords(), impl.checkSum(),
315         responsePtr);
316     if (rc != PLDM_SUCCESS)
317     {
318         return ccOnlyResponse(request, rc);
319     }
320 
321     return response;
322 }
323 
324 Response Handler::getFRURecordTable(const pldm_msg* request,
325                                     size_t payloadLength)
326 {
327     // FRU table is built lazily, build if not done.
328     buildFRUTable();
329 
330     if (payloadLength != PLDM_GET_FRU_RECORD_TABLE_REQ_BYTES)
331     {
332         return ccOnlyResponse(request, PLDM_ERROR_INVALID_LENGTH);
333     }
334 
335     Response response(
336         sizeof(pldm_msg_hdr) + PLDM_GET_FRU_RECORD_TABLE_MIN_RESP_BYTES, 0);
337     auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());
338 
339     auto rc =
340         encode_get_fru_record_table_resp(request->hdr.instance_id, PLDM_SUCCESS,
341                                          0, PLDM_START_AND_END, responsePtr);
342     if (rc != PLDM_SUCCESS)
343     {
344         return ccOnlyResponse(request, rc);
345     }
346 
347     impl.getFRUTable(response);
348 
349     return response;
350 }
351 
352 Response Handler::getFRURecordByOption(const pldm_msg* request,
353                                        size_t payloadLength)
354 {
355     if (payloadLength != sizeof(pldm_get_fru_record_by_option_req))
356     {
357         return ccOnlyResponse(request, PLDM_ERROR_INVALID_LENGTH);
358     }
359 
360     uint32_t retDataTransferHandle{};
361     uint16_t retFruTableHandle{};
362     uint16_t retRecordSetIdentifier{};
363     uint8_t retRecordType{};
364     uint8_t retFieldType{};
365     uint8_t retTransferOpFlag{};
366 
367     auto rc = decode_get_fru_record_by_option_req(
368         request, payloadLength, &retDataTransferHandle, &retFruTableHandle,
369         &retRecordSetIdentifier, &retRecordType, &retFieldType,
370         &retTransferOpFlag);
371 
372     if (rc != PLDM_SUCCESS)
373     {
374         return ccOnlyResponse(request, rc);
375     }
376 
377     std::vector<uint8_t> fruData;
378     rc = impl.getFRURecordByOption(fruData, retFruTableHandle,
379                                    retRecordSetIdentifier, retRecordType,
380                                    retFieldType);
381     if (rc != PLDM_SUCCESS)
382     {
383         return ccOnlyResponse(request, rc);
384     }
385 
386     auto respPayloadLength =
387         PLDM_GET_FRU_RECORD_BY_OPTION_MIN_RESP_BYTES + fruData.size();
388     Response response(sizeof(pldm_msg_hdr) + respPayloadLength, 0);
389     auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());
390 
391     rc = encode_get_fru_record_by_option_resp(
392         request->hdr.instance_id, PLDM_SUCCESS, 0, PLDM_START_AND_END,
393         fruData.data(), fruData.size(), responsePtr, respPayloadLength);
394 
395     if (rc != PLDM_SUCCESS)
396     {
397         return ccOnlyResponse(request, rc);
398     }
399 
400     return response;
401 }
402 
403 } // namespace fru
404 
405 } // namespace responder
406 
407 } // namespace pldm
408