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