xref: /openbmc/pldm/pldmd/pldmd.cpp (revision 963c0fdf)
1 
2 #include "common/flight_recorder.hpp"
3 #include "common/instance_id.hpp"
4 #include "common/transport.hpp"
5 #include "common/utils.hpp"
6 #include "dbus_impl_requester.hpp"
7 #include "fw-update/manager.hpp"
8 #include "invoker.hpp"
9 #include "requester/handler.hpp"
10 #include "requester/mctp_endpoint_discovery.hpp"
11 #include "requester/request.hpp"
12 
13 #include <err.h>
14 #include <getopt.h>
15 #include <libpldm/base.h>
16 #include <libpldm/bios.h>
17 #include <libpldm/pdr.h>
18 #include <libpldm/platform.h>
19 #include <libpldm/transport.h>
20 #include <poll.h>
21 #include <stdlib.h>
22 #include <sys/socket.h>
23 #include <sys/types.h>
24 #include <sys/un.h>
25 #include <unistd.h>
26 
27 #include <phosphor-logging/lg2.hpp>
28 #include <sdeventplus/event.hpp>
29 #include <sdeventplus/source/io.hpp>
30 #include <sdeventplus/source/signal.hpp>
31 #include <stdplus/signal.hpp>
32 
33 #include <cstdio>
34 #include <cstring>
35 #include <fstream>
36 #include <iomanip>
37 #include <iterator>
38 #include <memory>
39 #include <ranges>
40 #include <sstream>
41 #include <stdexcept>
42 #include <string>
43 #include <vector>
44 
45 PHOSPHOR_LOG2_USING;
46 
47 #ifdef LIBPLDMRESPONDER
48 #include "dbus_impl_pdr.hpp"
49 #include "host-bmc/dbus_to_event_handler.hpp"
50 #include "host-bmc/dbus_to_host_effecters.hpp"
51 #include "host-bmc/host_condition.hpp"
52 #include "host-bmc/host_pdr_handler.hpp"
53 #include "libpldmresponder/base.hpp"
54 #include "libpldmresponder/bios.hpp"
55 #include "libpldmresponder/fru.hpp"
56 #include "libpldmresponder/oem_handler.hpp"
57 #include "libpldmresponder/platform.hpp"
58 #include "libpldmresponder/platform_config.hpp"
59 #include "xyz/openbmc_project/PLDM/Event/server.hpp"
60 #endif
61 
62 #ifdef OEM_IBM
63 #include "libpldmresponder/file_io.hpp"
64 #include "libpldmresponder/fru_oem_ibm.hpp"
65 #include "libpldmresponder/oem_ibm_handler.hpp"
66 #endif
67 
68 constexpr uint8_t MCTP_MSG_TYPE_PLDM = 1;
69 
70 using namespace pldm;
71 using namespace sdeventplus;
72 using namespace sdeventplus::source;
73 using namespace pldm::responder;
74 using namespace pldm::utils;
75 using sdeventplus::source::Signal;
76 using namespace pldm::flightrecorder;
77 
78 void interruptFlightRecorderCallBack(Signal& /*signal*/,
79                                      const struct signalfd_siginfo*)
80 {
81     error("Received SIGUR1(10) Signal interrupt");
82     // obtain the flight recorder instance and dump the recorder
83     FlightRecorder::GetInstance().playRecorder();
84 }
85 
86 void requestPLDMServiceName()
87 {
88     auto& bus = pldm::utils::DBusHandler::getBus();
89     bus.request_name("xyz.openbmc_project.PLDM");
90 }
91 
92 static std::optional<Response>
93     processRxMsg(const std::vector<uint8_t>& requestMsg, Invoker& invoker,
94                  requester::Handler<requester::Request>& handler,
95                  fw_update::Manager* fwManager, pldm_tid_t tid)
96 {
97     uint8_t eid = tid;
98 
99     pldm_header_info hdrFields{};
100     auto hdr = reinterpret_cast<const pldm_msg_hdr*>(requestMsg.data());
101     if (PLDM_SUCCESS != unpack_pldm_header(hdr, &hdrFields))
102     {
103         error("Empty PLDM request header");
104         return std::nullopt;
105     }
106 
107     if (PLDM_RESPONSE != hdrFields.msg_type)
108     {
109         Response response;
110         auto request = reinterpret_cast<const pldm_msg*>(hdr);
111         size_t requestLen = requestMsg.size() - sizeof(struct pldm_msg_hdr);
112         try
113         {
114             if (hdrFields.pldm_type != PLDM_FWUP)
115             {
116                 response = invoker.handle(tid, hdrFields.pldm_type,
117                                           hdrFields.command, request,
118                                           requestLen);
119             }
120             else
121             {
122                 response = fwManager->handleRequest(eid, hdrFields.command,
123                                                     request, requestLen);
124             }
125         }
126         catch (const std::out_of_range& e)
127         {
128             uint8_t completion_code = PLDM_ERROR_UNSUPPORTED_PLDM_CMD;
129             response.resize(sizeof(pldm_msg_hdr));
130             auto responseHdr = reinterpret_cast<pldm_msg_hdr*>(response.data());
131             pldm_header_info header{};
132             header.msg_type = PLDM_RESPONSE;
133             header.instance = hdrFields.instance;
134             header.pldm_type = hdrFields.pldm_type;
135             header.command = hdrFields.command;
136             if (PLDM_SUCCESS != pack_pldm_header(&header, responseHdr))
137             {
138                 error("Failed adding response header: {ERROR}", "ERROR", e);
139                 return std::nullopt;
140             }
141             response.insert(response.end(), completion_code);
142         }
143         return response;
144     }
145     else if (PLDM_RESPONSE == hdrFields.msg_type)
146     {
147         auto response = reinterpret_cast<const pldm_msg*>(hdr);
148         size_t responseLen = requestMsg.size() - sizeof(struct pldm_msg_hdr);
149         handler.handleResponse(eid, hdrFields.instance, hdrFields.pldm_type,
150                                hdrFields.command, response, responseLen);
151     }
152     return std::nullopt;
153 }
154 
155 void optionUsage(void)
156 {
157     info("Usage: pldmd [options]");
158     info("Options:");
159     info(" [--verbose] - would enable verbosity");
160 }
161 
162 int main(int argc, char** argv)
163 {
164     bool verbose = false;
165     static struct option long_options[] = {{"verbose", no_argument, 0, 'v'},
166                                            {0, 0, 0, 0}};
167 
168     auto argflag = getopt_long(argc, argv, "v", long_options, nullptr);
169     switch (argflag)
170     {
171         case 'v':
172             verbose = true;
173             break;
174         case -1:
175             break;
176         default:
177             optionUsage();
178             exit(EXIT_FAILURE);
179     }
180     // Setup PLDM requester transport
181     auto hostEID = pldm::utils::readHostEID();
182     /* To maintain current behaviour until we have the infrastructure to find
183      * and use the correct TIDs */
184     pldm_tid_t TID = hostEID;
185     PldmTransport pldmTransport{};
186     auto event = Event::get_default();
187     auto& bus = pldm::utils::DBusHandler::getBus();
188     sdbusplus::server::manager_t objManager(bus,
189                                             "/xyz/openbmc_project/software");
190 
191     InstanceIdDb instanceIdDb;
192     dbus_api::Requester dbusImplReq(bus, "/xyz/openbmc_project/pldm",
193                                     instanceIdDb);
194     sdbusplus::server::manager_t inventoryManager(
195         bus, "/xyz/openbmc_project/inventory");
196 
197     Invoker invoker{};
198     requester::Handler<requester::Request> reqHandler(&pldmTransport, event,
199                                                       instanceIdDb, verbose);
200 
201 #ifdef LIBPLDMRESPONDER
202     using namespace pldm::state_sensor;
203     dbus_api::Host dbusImplHost(bus, "/xyz/openbmc_project/pldm");
204     std::unique_ptr<pldm_pdr, decltype(&pldm_pdr_destroy)> pdrRepo(
205         pldm_pdr_init(), pldm_pdr_destroy);
206     if (!pdrRepo)
207     {
208         throw std::runtime_error("Failed to instantiate PDR repository");
209     }
210     std::unique_ptr<pldm_entity_association_tree,
211                     decltype(&pldm_entity_association_tree_destroy)>
212         entityTree(pldm_entity_association_tree_init(),
213                    pldm_entity_association_tree_destroy);
214     if (!entityTree)
215     {
216         throw std::runtime_error(
217             "Failed to instantiate general PDR entity association tree");
218     }
219     std::unique_ptr<pldm_entity_association_tree,
220                     decltype(&pldm_entity_association_tree_destroy)>
221         bmcEntityTree(pldm_entity_association_tree_init(),
222                       pldm_entity_association_tree_destroy);
223     if (!bmcEntityTree)
224     {
225         throw std::runtime_error(
226             "Failed to instantiate BMC PDR entity association tree");
227     }
228     std::shared_ptr<HostPDRHandler> hostPDRHandler;
229     std::unique_ptr<pldm::host_effecters::HostEffecterParser>
230         hostEffecterParser;
231     std::unique_ptr<DbusToPLDMEvent> dbusToPLDMEventHandler;
232     DBusHandler dbusHandler;
233     std::unique_ptr<oem_platform::Handler> oemPlatformHandler{};
234     std::unique_ptr<platform_config::Handler> platformConfigHandler{};
235     platformConfigHandler = std::make_unique<platform_config::Handler>();
236     std::unique_ptr<oem_fru::Handler> oemFruHandler{};
237 
238 #ifdef OEM_IBM
239     std::unique_ptr<pldm::responder::CodeUpdate> codeUpdate =
240         std::make_unique<pldm::responder::CodeUpdate>(&dbusHandler);
241     codeUpdate->clearDirPath(LID_STAGING_DIR);
242     oemPlatformHandler = std::make_unique<oem_ibm_platform::Handler>(
243         &dbusHandler, codeUpdate.get(), pldmTransport.getEventSource(), hostEID,
244         instanceIdDb, event, &reqHandler);
245     codeUpdate->setOemPlatformHandler(oemPlatformHandler.get());
246     oemFruHandler = std::make_unique<oem_ibm_fru::Handler>(pdrRepo.get());
247     invoker.registerHandler(PLDM_OEM, std::make_unique<oem_ibm::Handler>(
248                                           oemPlatformHandler.get(),
249                                           pldmTransport.getEventSource(),
250                                           hostEID, &instanceIdDb, &reqHandler));
251 #endif
252     if (hostEID)
253     {
254         hostPDRHandler = std::make_shared<HostPDRHandler>(
255             pldmTransport.getEventSource(), hostEID, event, pdrRepo.get(),
256             EVENTS_JSONS_DIR, entityTree.get(), bmcEntityTree.get(),
257             instanceIdDb, &reqHandler, oemPlatformHandler.get());
258         // HostFirmware interface needs access to hostPDR to know if host
259         // is running
260         dbusImplHost.setHostPdrObj(hostPDRHandler);
261 
262         hostEffecterParser =
263             std::make_unique<pldm::host_effecters::HostEffecterParser>(
264                 &instanceIdDb, pldmTransport.getEventSource(), pdrRepo.get(),
265                 &dbusHandler, HOST_JSONS_DIR, &reqHandler);
266         dbusToPLDMEventHandler = std::make_unique<DbusToPLDMEvent>(
267             pldmTransport.getEventSource(), hostEID, instanceIdDb, &reqHandler);
268     }
269     auto biosHandler = std::make_unique<bios::Handler>(
270         pldmTransport.getEventSource(), hostEID, &instanceIdDb, &reqHandler,
271         platformConfigHandler.get(), requestPLDMServiceName);
272 
273     auto fruHandler = std::make_unique<fru::Handler>(
274         FRU_JSONS_DIR, FRU_MASTER_JSON, pdrRepo.get(), entityTree.get(),
275         bmcEntityTree.get(), oemFruHandler.get());
276 
277     // FRU table is built lazily when a FRU command or Get PDR command is
278     // handled. To enable building FRU table, the FRU handler is passed to the
279     // Platform handler.
280     auto platformHandler = std::make_unique<platform::Handler>(
281         &dbusHandler, hostEID, &instanceIdDb, PDR_JSONS_DIR, pdrRepo.get(),
282         hostPDRHandler.get(), dbusToPLDMEventHandler.get(), fruHandler.get(),
283         oemPlatformHandler.get(), platformConfigHandler.get(), &reqHandler,
284         event, true);
285 #ifdef OEM_IBM
286     pldm::responder::oem_ibm_platform::Handler* oemIbmPlatformHandler =
287         dynamic_cast<pldm::responder::oem_ibm_platform::Handler*>(
288             oemPlatformHandler.get());
289     oemIbmPlatformHandler->setPlatformHandler(platformHandler.get());
290 
291     pldm::responder::oem_ibm_fru::Handler* oemIbmFruHandler =
292         dynamic_cast<pldm::responder::oem_ibm_fru::Handler*>(
293             oemFruHandler.get());
294     oemIbmFruHandler->setIBMFruHandler(fruHandler.get());
295 #endif
296 
297     invoker.registerHandler(PLDM_BIOS, std::move(biosHandler));
298     invoker.registerHandler(PLDM_PLATFORM, std::move(platformHandler));
299     invoker.registerHandler(PLDM_BASE, std::make_unique<base::Handler>(
300                                            event, oemPlatformHandler.get()));
301     invoker.registerHandler(PLDM_FRU, std::move(fruHandler));
302     dbus_api::Pdr dbusImplPdr(bus, "/xyz/openbmc_project/pldm", pdrRepo.get());
303     sdbusplus::xyz::openbmc_project::PLDM::server::Event dbusImplEvent(
304         bus, "/xyz/openbmc_project/pldm");
305 
306 #endif
307 
308     std::unique_ptr<fw_update::Manager> fwManager =
309         std::make_unique<fw_update::Manager>(event, reqHandler, instanceIdDb);
310     std::unique_ptr<MctpDiscovery> mctpDiscoveryHandler =
311         std::make_unique<MctpDiscovery>(bus, fwManager.get());
312     auto callback = [verbose, &invoker, &reqHandler, &fwManager, &pldmTransport,
313                      TID](IO& io, int fd, uint32_t revents) mutable {
314         if (!(revents & EPOLLIN))
315         {
316             return;
317         }
318         if (fd < 0)
319         {
320             return;
321         }
322 
323         int returnCode = 0;
324         void* requestMsg;
325         size_t recvDataLength;
326         returnCode = pldmTransport.recvMsg(TID, requestMsg, recvDataLength);
327 
328         if (returnCode == PLDM_REQUESTER_SUCCESS)
329         {
330             std::vector<uint8_t> requestMsgVec(
331                 static_cast<uint8_t*>(requestMsg),
332                 static_cast<uint8_t*>(requestMsg) + recvDataLength);
333             FlightRecorder::GetInstance().saveRecord(requestMsgVec, false);
334             if (verbose)
335             {
336                 printBuffer(Rx, requestMsgVec);
337             }
338             // process message and send response
339             auto response = processRxMsg(requestMsgVec, invoker, reqHandler,
340                                          fwManager.get(), TID);
341             if (response.has_value())
342             {
343                 FlightRecorder::GetInstance().saveRecord(*response, true);
344                 if (verbose)
345                 {
346                     printBuffer(Tx, *response);
347                 }
348 
349                 returnCode = pldmTransport.sendMsg(TID, (*response).data(),
350                                                    (*response).size());
351                 if (returnCode != PLDM_REQUESTER_SUCCESS)
352                 {
353                     warning("Failed to send PLDM response: {RETURN_CODE}",
354                             "RETURN_CODE", returnCode);
355                 }
356             }
357         }
358         // TODO check that we get here if mctp-demux dies?
359         else if (returnCode == PLDM_REQUESTER_RECV_FAIL)
360         {
361             // MCTP daemon has closed the socket this daemon is connected to.
362             // This may or may not be an error scenario, in either case the
363             // recovery mechanism for this daemon is to restart, and hence exit
364             // the event loop, that will cause this daemon to exit with a
365             // failure code.
366             error("io exiting");
367             io.get_event().exit(0);
368         }
369         else
370         {
371             warning("Failed to receive PLDM request: {RETURN_CODE}",
372                     "RETURN_CODE", returnCode);
373         }
374         /* Free requestMsg after using */
375         free(requestMsg);
376     };
377 
378     bus.attach_event(event.get(), SD_EVENT_PRIORITY_NORMAL);
379 #ifndef SYSTEM_SPECIFIC_BIOS_JSON
380     bus.request_name("xyz.openbmc_project.PLDM");
381 #endif
382     IO io(event, pldmTransport.getEventSource(), EPOLLIN, std::move(callback));
383 #ifdef LIBPLDMRESPONDER
384     if (hostPDRHandler)
385     {
386         hostPDRHandler->setHostFirmwareCondition();
387     }
388 #endif
389     stdplus::signal::block(SIGUSR1);
390     sdeventplus::source::Signal sigUsr1(
391         event, SIGUSR1, std::bind_front(&interruptFlightRecorderCallBack));
392     int returnCode = event.loop();
393     if (returnCode)
394     {
395         exit(EXIT_FAILURE);
396     }
397 
398     exit(EXIT_SUCCESS);
399 }
400