xref: /openbmc/bmcweb/redfish-core/lib/pcie.hpp (revision 1b8b02a4)
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 
17 #pragma once
18 
19 #include "app.hpp"
20 #include "dbus_utility.hpp"
21 #include "query.hpp"
22 #include "registries/privilege_registry.hpp"
23 #include "utils/collection.hpp"
24 #include "utils/dbus_utils.hpp"
25 #include "utils/pcie_util.hpp"
26 
27 #include <boost/system/linux_error.hpp>
28 #include <boost/url/format.hpp>
29 #include <sdbusplus/asio/property.hpp>
30 #include <sdbusplus/unpack_properties.hpp>
31 
32 namespace redfish
33 {
34 
35 static constexpr const char* inventoryPath = "/xyz/openbmc_project/inventory";
36 static constexpr std::array<std::string_view, 1> pcieDeviceInterface = {
37     "xyz.openbmc_project.Inventory.Item.PCIeDevice"};
38 static constexpr std::array<std::string_view, 1> pcieSlotInterface = {
39     "xyz.openbmc_project.Inventory.Item.PCIeSlot"};
40 
41 static inline void handlePCIeDevicePath(
42     const std::string& pcieDeviceId,
43     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
44     const dbus::utility::MapperGetSubTreePathsResponse& pcieDevicePaths,
45     const std::function<void(const std::string& pcieDevicePath,
46                              const std::string& service)>& callback)
47 
48 {
49     for (const std::string& pcieDevicePath : pcieDevicePaths)
50     {
51         std::string pciecDeviceName =
52             sdbusplus::message::object_path(pcieDevicePath).filename();
53         if (pciecDeviceName.empty() || pciecDeviceName != pcieDeviceId)
54         {
55             continue;
56         }
57 
58         dbus::utility::getDbusObject(
59             pcieDevicePath, {},
60             [pcieDevicePath, asyncResp,
61              callback](const boost::system::error_code& ec,
62                        const dbus::utility::MapperGetObject& object) {
63             if (ec || object.empty())
64             {
65                 BMCWEB_LOG_ERROR("DBUS response error {}", ec);
66                 messages::internalError(asyncResp->res);
67                 return;
68             }
69             callback(pcieDevicePath, object.begin()->first);
70             });
71         return;
72     }
73 
74     BMCWEB_LOG_WARNING("PCIe Device not found");
75     messages::resourceNotFound(asyncResp->res, "PCIeDevice", pcieDeviceId);
76 }
77 
78 static inline void getValidPCIeDevicePath(
79     const std::string& pcieDeviceId,
80     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
81     const std::function<void(const std::string& pcieDevicePath,
82                              const std::string& service)>& callback)
83 {
84     dbus::utility::getSubTreePaths(
85         inventoryPath, 0, pcieDeviceInterface,
86         [pcieDeviceId, asyncResp,
87          callback](const boost::system::error_code& ec,
88                    const dbus::utility::MapperGetSubTreePathsResponse&
89                        pcieDevicePaths) {
90         if (ec)
91         {
92             BMCWEB_LOG_ERROR("D-Bus response error on GetSubTree {}", ec);
93             messages::internalError(asyncResp->res);
94             return;
95         }
96         handlePCIeDevicePath(pcieDeviceId, asyncResp, pcieDevicePaths,
97                              callback);
98         return;
99         });
100 }
101 
102 static inline void handlePCIeDeviceCollectionGet(
103     crow::App& app, const crow::Request& req,
104     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
105     const std::string& systemName)
106 {
107     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
108     {
109         return;
110     }
111     if constexpr (bmcwebEnableMultiHost)
112     {
113         // Option currently returns no systems.  TBD
114         messages::resourceNotFound(asyncResp->res, "ComputerSystem",
115                                    systemName);
116         return;
117     }
118     if (systemName != "system")
119     {
120         messages::resourceNotFound(asyncResp->res, "ComputerSystem",
121                                    systemName);
122         return;
123     }
124 
125     asyncResp->res.addHeader(boost::beast::http::field::link,
126                              "</redfish/v1/JsonSchemas/PCIeDeviceCollection/"
127                              "PCIeDeviceCollection.json>; rel=describedby");
128     asyncResp->res.jsonValue["@odata.type"] =
129         "#PCIeDeviceCollection.PCIeDeviceCollection";
130     asyncResp->res.jsonValue["@odata.id"] =
131         "/redfish/v1/Systems/system/PCIeDevices";
132     asyncResp->res.jsonValue["Name"] = "PCIe Device Collection";
133     asyncResp->res.jsonValue["Description"] = "Collection of PCIe Devices";
134     asyncResp->res.jsonValue["Members"] = nlohmann::json::array();
135     asyncResp->res.jsonValue["Members@odata.count"] = 0;
136 
137     pcie_util::getPCIeDeviceList(asyncResp, "Members");
138 }
139 
140 inline void requestRoutesSystemPCIeDeviceCollection(App& app)
141 {
142     /**
143      * Functions triggers appropriate requests on DBus
144      */
145     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/PCIeDevices/")
146         .privileges(redfish::privileges::getPCIeDeviceCollection)
147         .methods(boost::beast::http::verb::get)(
148             std::bind_front(handlePCIeDeviceCollectionGet, std::ref(app)));
149 }
150 
151 inline void addPCIeSlotProperties(
152     crow::Response& res, const boost::system::error_code& ec,
153     const dbus::utility::DBusPropertiesMap& pcieSlotProperties)
154 {
155     if (ec)
156     {
157         BMCWEB_LOG_ERROR("DBUS response error for getAllProperties{}",
158                          ec.value());
159         messages::internalError(res);
160         return;
161     }
162     std::string generation;
163     size_t lanes = 0;
164     std::string slotType;
165 
166     bool success = sdbusplus::unpackPropertiesNoThrow(
167         dbus_utils::UnpackErrorPrinter(), pcieSlotProperties, "Generation",
168         generation, "Lanes", lanes, "SlotType", slotType);
169 
170     if (!success)
171     {
172         messages::internalError(res);
173         return;
174     }
175 
176     std::optional<pcie_device::PCIeTypes> pcieType =
177         pcie_util::redfishPcieGenerationFromDbus(generation);
178     if (!pcieType)
179     {
180         BMCWEB_LOG_WARNING("Unknown PCIeType: {}", generation);
181     }
182     else
183     {
184         if (*pcieType == pcie_device::PCIeTypes::Invalid)
185         {
186             BMCWEB_LOG_ERROR("Invalid PCIeType: {}", generation);
187             messages::internalError(res);
188             return;
189         }
190         res.jsonValue["Slot"]["PCIeType"] = *pcieType;
191     }
192 
193     if (lanes != 0)
194     {
195         res.jsonValue["Slot"]["Lanes"] = lanes;
196     }
197 
198     std::optional<pcie_slots::SlotTypes> redfishSlotType =
199         pcie_util::dbusSlotTypeToRf(slotType);
200     if (!redfishSlotType)
201     {
202         BMCWEB_LOG_WARNING("Unknown PCIeSlot Type: {}", slotType);
203     }
204     else
205     {
206         if (*redfishSlotType == pcie_slots::SlotTypes::Invalid)
207         {
208             BMCWEB_LOG_ERROR("Invalid PCIeSlot type: {}", slotType);
209             messages::internalError(res);
210             return;
211         }
212         res.jsonValue["Slot"]["SlotType"] = *redfishSlotType;
213     }
214 }
215 
216 inline void getPCIeDeviceSlotPath(
217     const std::string& pcieDevicePath,
218     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
219     std::function<void(const std::string& pcieDeviceSlot)>&& callback)
220 {
221     std::string associationPath = pcieDevicePath + "/contained_by";
222     dbus::utility::getAssociatedSubTreePaths(
223         associationPath, sdbusplus::message::object_path(inventoryPath), 0,
224         pcieSlotInterface,
225         [callback, asyncResp, pcieDevicePath](
226             const boost::system::error_code& ec,
227             const dbus::utility::MapperGetSubTreePathsResponse& endpoints) {
228         if (ec)
229         {
230             if (ec.value() == EBADR)
231             {
232                 // Missing association is not an error
233                 return;
234             }
235             BMCWEB_LOG_ERROR(
236                 "DBUS response error for getAssociatedSubTreePaths {}",
237                 ec.value());
238             messages::internalError(asyncResp->res);
239             return;
240         }
241         if (endpoints.size() > 1)
242         {
243             BMCWEB_LOG_ERROR(
244                 "PCIeDevice is associated with more than one PCIeSlot: {}",
245                 endpoints.size());
246             messages::internalError(asyncResp->res);
247             return;
248         }
249         if (endpoints.empty())
250         {
251             // If the device doesn't have an association, return without PCIe
252             // Slot properties
253             BMCWEB_LOG_DEBUG("PCIeDevice is not associated with PCIeSlot");
254             return;
255         }
256         callback(endpoints[0]);
257         });
258 }
259 
260 inline void
261     afterGetDbusObject(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
262                        const std::string& pcieDeviceSlot,
263                        const boost::system::error_code& ec,
264                        const dbus::utility::MapperGetObject& object)
265 {
266     if (ec || object.empty())
267     {
268         BMCWEB_LOG_ERROR("DBUS response error for getDbusObject {}",
269                          ec.value());
270         messages::internalError(asyncResp->res);
271         return;
272     }
273     sdbusplus::asio::getAllProperties(
274         *crow::connections::systemBus, object.begin()->first, pcieDeviceSlot,
275         "xyz.openbmc_project.Inventory.Item.PCIeSlot",
276         [asyncResp](
277             const boost::system::error_code& ec2,
278             const dbus::utility::DBusPropertiesMap& pcieSlotProperties) {
279         addPCIeSlotProperties(asyncResp->res, ec2, pcieSlotProperties);
280         });
281 }
282 
283 inline void afterGetPCIeDeviceSlotPath(
284     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
285     const std::string& pcieDeviceSlot)
286 {
287     dbus::utility::getDbusObject(
288         pcieDeviceSlot, pcieSlotInterface,
289         [asyncResp,
290          pcieDeviceSlot](const boost::system::error_code& ec,
291                          const dbus::utility::MapperGetObject& object) {
292         afterGetDbusObject(asyncResp, pcieDeviceSlot, ec, object);
293         });
294 }
295 
296 inline void
297     getPCIeDeviceHealth(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
298                         const std::string& pcieDevicePath,
299                         const std::string& service)
300 {
301     sdbusplus::asio::getProperty<bool>(
302         *crow::connections::systemBus, service, pcieDevicePath,
303         "xyz.openbmc_project.State.Decorator.OperationalStatus", "Functional",
304         [asyncResp](const boost::system::error_code& ec, const bool value) {
305         if (ec)
306         {
307             if (ec.value() != EBADR)
308             {
309                 BMCWEB_LOG_ERROR("DBUS response error for Health {}",
310                                  ec.value());
311                 messages::internalError(asyncResp->res);
312             }
313             return;
314         }
315 
316         if (!value)
317         {
318             asyncResp->res.jsonValue["Status"]["Health"] = "Critical";
319         }
320         });
321 }
322 
323 inline void
324     getPCIeDeviceState(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
325                        const std::string& pcieDevicePath,
326                        const std::string& service)
327 {
328     sdbusplus::asio::getProperty<bool>(
329         *crow::connections::systemBus, service, pcieDevicePath,
330         "xyz.openbmc_project.Inventory.Item", "Present",
331         [asyncResp](const boost::system::error_code& ec, bool value) {
332         if (ec)
333         {
334             if (ec.value() != EBADR)
335             {
336                 BMCWEB_LOG_ERROR("DBUS response error for State");
337                 messages::internalError(asyncResp->res);
338             }
339             return;
340         }
341 
342         if (!value)
343         {
344             asyncResp->res.jsonValue["Status"]["State"] = "Absent";
345         }
346         });
347 }
348 
349 inline void
350     getPCIeDeviceAsset(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
351                        const std::string& pcieDevicePath,
352                        const std::string& service)
353 {
354     sdbusplus::asio::getAllProperties(
355         *crow::connections::systemBus, service, pcieDevicePath,
356         "xyz.openbmc_project.Inventory.Decorator.Asset",
357         [pcieDevicePath, asyncResp{asyncResp}](
358             const boost::system::error_code& ec,
359             const dbus::utility::DBusPropertiesMap& assetList) {
360         if (ec)
361         {
362             if (ec.value() != EBADR)
363             {
364                 BMCWEB_LOG_ERROR("DBUS response error for Properties{}",
365                                  ec.value());
366                 messages::internalError(asyncResp->res);
367             }
368             return;
369         }
370 
371         const std::string* manufacturer = nullptr;
372         const std::string* model = nullptr;
373         const std::string* partNumber = nullptr;
374         const std::string* serialNumber = nullptr;
375         const std::string* sparePartNumber = nullptr;
376 
377         const bool success = sdbusplus::unpackPropertiesNoThrow(
378             dbus_utils::UnpackErrorPrinter(), assetList, "Manufacturer",
379             manufacturer, "Model", model, "PartNumber", partNumber,
380             "SerialNumber", serialNumber, "SparePartNumber", sparePartNumber);
381 
382         if (!success)
383         {
384             messages::internalError(asyncResp->res);
385             return;
386         }
387 
388         if (manufacturer != nullptr)
389         {
390             asyncResp->res.jsonValue["Manufacturer"] = *manufacturer;
391         }
392         if (model != nullptr)
393         {
394             asyncResp->res.jsonValue["Model"] = *model;
395         }
396 
397         if (partNumber != nullptr)
398         {
399             asyncResp->res.jsonValue["PartNumber"] = *partNumber;
400         }
401 
402         if (serialNumber != nullptr)
403         {
404             asyncResp->res.jsonValue["SerialNumber"] = *serialNumber;
405         }
406 
407         if (sparePartNumber != nullptr && !sparePartNumber->empty())
408         {
409             asyncResp->res.jsonValue["SparePartNumber"] = *sparePartNumber;
410         }
411         });
412 }
413 
414 inline void addPCIeDeviceProperties(
415     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
416     const std::string& pcieDeviceId,
417     const dbus::utility::DBusPropertiesMap& pcieDevProperties)
418 {
419     const std::string* generationInUse = nullptr;
420     const std::string* generationSupported = nullptr;
421     const size_t* lanesInUse = nullptr;
422     const size_t* maxLanes = nullptr;
423 
424     const bool success = sdbusplus::unpackPropertiesNoThrow(
425         dbus_utils::UnpackErrorPrinter(), pcieDevProperties, "GenerationInUse",
426         generationInUse, "GenerationSupported", generationSupported,
427         "LanesInUse", lanesInUse, "MaxLanes", maxLanes);
428 
429     if (!success)
430     {
431         messages::internalError(asyncResp->res);
432         return;
433     }
434 
435     if (generationInUse != nullptr)
436     {
437         std::optional<pcie_device::PCIeTypes> redfishGenerationInUse =
438             pcie_util::redfishPcieGenerationFromDbus(*generationInUse);
439 
440         if (!redfishGenerationInUse)
441         {
442             BMCWEB_LOG_WARNING("Unknown PCIe Device Generation: {}",
443                                *generationInUse);
444         }
445         else
446         {
447             if (*redfishGenerationInUse == pcie_device::PCIeTypes::Invalid)
448             {
449                 BMCWEB_LOG_ERROR("Invalid PCIe Device Generation: {}",
450                                  *generationInUse);
451                 messages::internalError(asyncResp->res);
452                 return;
453             }
454             asyncResp->res.jsonValue["PCIeInterface"]["PCIeType"] =
455                 *redfishGenerationInUse;
456         }
457     }
458 
459     if (generationSupported != nullptr)
460     {
461         std::optional<pcie_device::PCIeTypes> redfishGenerationSupported =
462             pcie_util::redfishPcieGenerationFromDbus(*generationSupported);
463 
464         if (!redfishGenerationSupported)
465         {
466             BMCWEB_LOG_WARNING("Unknown PCIe Device Generation: {}",
467                                *generationSupported);
468         }
469         else
470         {
471             if (*redfishGenerationSupported == pcie_device::PCIeTypes::Invalid)
472             {
473                 BMCWEB_LOG_ERROR("Invalid PCIe Device Generation: {}",
474                                  *generationSupported);
475                 messages::internalError(asyncResp->res);
476                 return;
477             }
478             asyncResp->res.jsonValue["PCIeInterface"]["MaxPCIeType"] =
479                 *redfishGenerationSupported;
480         }
481     }
482 
483     // The default value of LanesInUse is 0, and the field will be
484     // left as off if it is a default value.
485     if (lanesInUse != nullptr && *lanesInUse != 0)
486     {
487         asyncResp->res.jsonValue["PCIeInterface"]["LanesInUse"] = *lanesInUse;
488     }
489     // The default value of MaxLanes is 0, and the field will be
490     // left as off if it is a default value.
491     if (maxLanes != nullptr && *maxLanes != 0)
492     {
493         asyncResp->res.jsonValue["PCIeInterface"]["MaxLanes"] = *maxLanes;
494     }
495 
496     asyncResp->res.jsonValue["PCIeFunctions"]["@odata.id"] =
497         boost::urls::format(
498             "/redfish/v1/Systems/system/PCIeDevices/{}/PCIeFunctions",
499             pcieDeviceId);
500 }
501 
502 inline void getPCIeDeviceProperties(
503     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
504     const std::string& pcieDevicePath, const std::string& service,
505     const std::function<void(
506         const dbus::utility::DBusPropertiesMap& pcieDevProperties)>&& callback)
507 {
508     sdbusplus::asio::getAllProperties(
509         *crow::connections::systemBus, service, pcieDevicePath,
510         "xyz.openbmc_project.Inventory.Item.PCIeDevice",
511         [asyncResp,
512          callback](const boost::system::error_code& ec,
513                    const dbus::utility::DBusPropertiesMap& pcieDevProperties) {
514         if (ec)
515         {
516             if (ec.value() != EBADR)
517             {
518                 BMCWEB_LOG_ERROR("DBUS response error for Properties");
519                 messages::internalError(asyncResp->res);
520             }
521             return;
522         }
523         callback(pcieDevProperties);
524         });
525 }
526 
527 inline void addPCIeDeviceCommonProperties(
528     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
529     const std::string& pcieDeviceId)
530 {
531     asyncResp->res.addHeader(
532         boost::beast::http::field::link,
533         "</redfish/v1/JsonSchemas/PCIeDevice/PCIeDevice.json>; rel=describedby");
534     asyncResp->res.jsonValue["@odata.type"] = "#PCIeDevice.v1_9_0.PCIeDevice";
535     asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
536         "/redfish/v1/Systems/system/PCIeDevices/{}", pcieDeviceId);
537     asyncResp->res.jsonValue["Name"] = "PCIe Device";
538     asyncResp->res.jsonValue["Id"] = pcieDeviceId;
539     asyncResp->res.jsonValue["Status"]["State"] = "Enabled";
540     asyncResp->res.jsonValue["Status"]["Health"] = "OK";
541 }
542 
543 inline void afterGetValidPcieDevicePath(
544     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
545     const std::string& pcieDeviceId, const std::string& pcieDevicePath,
546     const std::string& service)
547 {
548     addPCIeDeviceCommonProperties(asyncResp, pcieDeviceId);
549     getPCIeDeviceAsset(asyncResp, pcieDevicePath, service);
550     getPCIeDeviceState(asyncResp, pcieDevicePath, service);
551     getPCIeDeviceHealth(asyncResp, pcieDevicePath, service);
552     getPCIeDeviceProperties(
553         asyncResp, pcieDevicePath, service,
554         std::bind_front(addPCIeDeviceProperties, asyncResp, pcieDeviceId));
555     getPCIeDeviceSlotPath(
556         pcieDevicePath, asyncResp,
557         std::bind_front(afterGetPCIeDeviceSlotPath, asyncResp));
558 }
559 
560 inline void
561     handlePCIeDeviceGet(App& app, const crow::Request& req,
562                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
563                         const std::string& systemName,
564                         const std::string& pcieDeviceId)
565 {
566     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
567     {
568         return;
569     }
570     if constexpr (bmcwebEnableMultiHost)
571     {
572         // Option currently returns no systems.  TBD
573         messages::resourceNotFound(asyncResp->res, "ComputerSystem",
574                                    systemName);
575         return;
576     }
577     if (systemName != "system")
578     {
579         messages::resourceNotFound(asyncResp->res, "ComputerSystem",
580                                    systemName);
581         return;
582     }
583 
584     getValidPCIeDevicePath(
585         pcieDeviceId, asyncResp,
586         std::bind_front(afterGetValidPcieDevicePath, asyncResp, pcieDeviceId));
587 }
588 
589 inline void requestRoutesSystemPCIeDevice(App& app)
590 {
591     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/PCIeDevices/<str>/")
592         .privileges(redfish::privileges::getPCIeDevice)
593         .methods(boost::beast::http::verb::get)(
594             std::bind_front(handlePCIeDeviceGet, std::ref(app)));
595 }
596 
597 inline void addPCIeFunctionList(
598     crow::Response& res, const std::string& pcieDeviceId,
599     const dbus::utility::DBusPropertiesMap& pcieDevProperties)
600 {
601     nlohmann::json& pcieFunctionList = res.jsonValue["Members"];
602     pcieFunctionList = nlohmann::json::array();
603     static constexpr const int maxPciFunctionNum = 8;
604 
605     for (int functionNum = 0; functionNum < maxPciFunctionNum; functionNum++)
606     {
607         // Check if this function exists by
608         // looking for a device ID
609         std::string devIDProperty = "Function" + std::to_string(functionNum) +
610                                     "DeviceId";
611         const std::string* property = nullptr;
612         for (const auto& propEntry : pcieDevProperties)
613         {
614             if (propEntry.first == devIDProperty)
615             {
616                 property = std::get_if<std::string>(&propEntry.second);
617                 break;
618             }
619         }
620         if (property == nullptr || property->empty())
621         {
622             continue;
623         }
624 
625         nlohmann::json::object_t pcieFunction;
626         pcieFunction["@odata.id"] = boost::urls::format(
627             "/redfish/v1/Systems/system/PCIeDevices/{}/PCIeFunctions/{}",
628             pcieDeviceId, std::to_string(functionNum));
629         pcieFunctionList.emplace_back(std::move(pcieFunction));
630     }
631     res.jsonValue["PCIeFunctions@odata.count"] = pcieFunctionList.size();
632 }
633 
634 inline void handlePCIeFunctionCollectionGet(
635     App& app, const crow::Request& req,
636     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
637     const std::string& systemName, const std::string& pcieDeviceId)
638 {
639     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
640     {
641         return;
642     }
643     if constexpr (bmcwebEnableMultiHost)
644     {
645         // Option currently returns no systems.  TBD
646         messages::resourceNotFound(asyncResp->res, "ComputerSystem",
647                                    systemName);
648         return;
649     }
650 
651     getValidPCIeDevicePath(
652         pcieDeviceId, asyncResp,
653         [asyncResp, pcieDeviceId](const std::string& pcieDevicePath,
654                                   const std::string& service) {
655         asyncResp->res.addHeader(
656             boost::beast::http::field::link,
657             "</redfish/v1/JsonSchemas/PCIeFunctionCollection/PCIeFunctionCollection.json>; rel=describedby");
658         asyncResp->res.jsonValue["@odata.type"] =
659             "#PCIeFunctionCollection.PCIeFunctionCollection";
660         asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
661             "/redfish/v1/Systems/system/PCIeDevices/{}/PCIeFunctions",
662             pcieDeviceId);
663         asyncResp->res.jsonValue["Name"] = "PCIe Function Collection";
664         asyncResp->res.jsonValue["Description"] =
665             "Collection of PCIe Functions for PCIe Device " + pcieDeviceId;
666         getPCIeDeviceProperties(
667             asyncResp, pcieDevicePath, service,
668             [asyncResp, pcieDeviceId](
669                 const dbus::utility::DBusPropertiesMap& pcieDevProperties) {
670             addPCIeFunctionList(asyncResp->res, pcieDeviceId,
671                                 pcieDevProperties);
672             });
673         });
674 }
675 
676 inline void requestRoutesSystemPCIeFunctionCollection(App& app)
677 {
678     /**
679      * Functions triggers appropriate requests on DBus
680      */
681     BMCWEB_ROUTE(app,
682                  "/redfish/v1/Systems/<str>/PCIeDevices/<str>/PCIeFunctions/")
683         .privileges(redfish::privileges::getPCIeFunctionCollection)
684         .methods(boost::beast::http::verb::get)(
685             std::bind_front(handlePCIeFunctionCollectionGet, std::ref(app)));
686 }
687 
688 inline bool validatePCIeFunctionId(
689     uint64_t pcieFunctionId,
690     const dbus::utility::DBusPropertiesMap& pcieDevProperties)
691 {
692     std::string functionName = "Function" + std::to_string(pcieFunctionId);
693     std::string devIDProperty = functionName + "DeviceId";
694 
695     const std::string* devIdProperty = nullptr;
696     for (const auto& property : pcieDevProperties)
697     {
698         if (property.first == devIDProperty)
699         {
700             devIdProperty = std::get_if<std::string>(&property.second);
701             break;
702         }
703     }
704     return (devIdProperty != nullptr && !devIdProperty->empty());
705 }
706 
707 inline void addPCIeFunctionProperties(
708     crow::Response& resp, uint64_t pcieFunctionId,
709     const dbus::utility::DBusPropertiesMap& pcieDevProperties)
710 {
711     std::string functionName = "Function" + std::to_string(pcieFunctionId);
712     for (const auto& property : pcieDevProperties)
713     {
714         const std::string* strProperty =
715             std::get_if<std::string>(&property.second);
716 
717         if (property.first == functionName + "DeviceId")
718         {
719             resp.jsonValue["DeviceId"] = *strProperty;
720         }
721         if (property.first == functionName + "VendorId")
722         {
723             resp.jsonValue["VendorId"] = *strProperty;
724         }
725         // TODO: FunctionType and DeviceClass are Redfish enums. The D-Bus
726         // property strings should be mapped correctly to ensure these
727         // strings are Redfish enum values. For now just check for empty.
728         if (property.first == functionName + "FunctionType")
729         {
730             if (!strProperty->empty())
731             {
732                 resp.jsonValue["FunctionType"] = *strProperty;
733             }
734         }
735         if (property.first == functionName + "DeviceClass")
736         {
737             if (!strProperty->empty())
738             {
739                 resp.jsonValue["DeviceClass"] = *strProperty;
740             }
741         }
742         if (property.first == functionName + "ClassCode")
743         {
744             resp.jsonValue["ClassCode"] = *strProperty;
745         }
746         if (property.first == functionName + "RevisionId")
747         {
748             resp.jsonValue["RevisionId"] = *strProperty;
749         }
750         if (property.first == functionName + "SubsystemId")
751         {
752             resp.jsonValue["SubsystemId"] = *strProperty;
753         }
754         if (property.first == functionName + "SubsystemVendorId")
755         {
756             resp.jsonValue["SubsystemVendorId"] = *strProperty;
757         }
758     }
759 }
760 
761 inline void addPCIeFunctionCommonProperties(crow::Response& resp,
762                                             const std::string& pcieDeviceId,
763                                             uint64_t pcieFunctionId)
764 {
765     resp.addHeader(
766         boost::beast::http::field::link,
767         "</redfish/v1/JsonSchemas/PCIeFunction/PCIeFunction.json>; rel=describedby");
768     resp.jsonValue["@odata.type"] = "#PCIeFunction.v1_2_3.PCIeFunction";
769     resp.jsonValue["@odata.id"] = boost::urls::format(
770         "/redfish/v1/Systems/system/PCIeDevices/{}/PCIeFunctions/{}",
771         pcieDeviceId, std::to_string(pcieFunctionId));
772     resp.jsonValue["Name"] = "PCIe Function";
773     resp.jsonValue["Id"] = std::to_string(pcieFunctionId);
774     resp.jsonValue["FunctionId"] = pcieFunctionId;
775     resp.jsonValue["Links"]["PCIeDevice"]["@odata.id"] = boost::urls::format(
776         "/redfish/v1/Systems/system/PCIeDevices/{}", pcieDeviceId);
777 }
778 
779 inline void
780     handlePCIeFunctionGet(App& app, const crow::Request& req,
781                           const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
782                           const std::string& systemName,
783                           const std::string& pcieDeviceId,
784                           const std::string& pcieFunctionIdStr)
785 {
786     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
787     {
788         return;
789     }
790     if constexpr (bmcwebEnableMultiHost)
791     {
792         // Option currently returns no systems.  TBD
793         messages::resourceNotFound(asyncResp->res, "ComputerSystem",
794                                    systemName);
795         return;
796     }
797     if (systemName != "system")
798     {
799         messages::resourceNotFound(asyncResp->res, "ComputerSystem",
800                                    systemName);
801         return;
802     }
803 
804     uint64_t pcieFunctionId = 0;
805     std::from_chars_result result = std::from_chars(
806         &*pcieFunctionIdStr.begin(), &*pcieFunctionIdStr.end(), pcieFunctionId);
807     if (result.ec != std::errc{} || result.ptr != &*pcieFunctionIdStr.end())
808     {
809         messages::resourceNotFound(asyncResp->res, "PCIeFunction",
810                                    pcieFunctionIdStr);
811         return;
812     }
813 
814     getValidPCIeDevicePath(pcieDeviceId, asyncResp,
815                            [asyncResp, pcieDeviceId,
816                             pcieFunctionId](const std::string& pcieDevicePath,
817                                             const std::string& service) {
818         getPCIeDeviceProperties(
819             asyncResp, pcieDevicePath, service,
820             [asyncResp, pcieDeviceId, pcieFunctionId](
821                 const dbus::utility::DBusPropertiesMap& pcieDevProperties) {
822             addPCIeFunctionCommonProperties(asyncResp->res, pcieDeviceId,
823                                             pcieFunctionId);
824             addPCIeFunctionProperties(asyncResp->res, pcieFunctionId,
825                                       pcieDevProperties);
826             });
827     });
828 }
829 
830 inline void requestRoutesSystemPCIeFunction(App& app)
831 {
832     BMCWEB_ROUTE(
833         app, "/redfish/v1/Systems/<str>/PCIeDevices/<str>/PCIeFunctions/<str>/")
834         .privileges(redfish::privileges::getPCIeFunction)
835         .methods(boost::beast::http::verb::get)(
836             std::bind_front(handlePCIeFunctionGet, std::ref(app)));
837 }
838 
839 } // namespace redfish
840