xref: /openbmc/pldm/pldmd/pldmd.cpp (revision a881c170)
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 "oem_ibm.hpp"
64 #endif
65 
66 constexpr uint8_t MCTP_MSG_TYPE_PLDM = 1;
67 
68 using namespace pldm;
69 using namespace sdeventplus;
70 using namespace sdeventplus::source;
71 using namespace pldm::responder;
72 using namespace pldm::utils;
73 using sdeventplus::source::Signal;
74 using namespace pldm::flightrecorder;
75 
76 void interruptFlightRecorderCallBack(Signal& /*signal*/,
77                                      const struct signalfd_siginfo*)
78 {
79     error("Received SIGUR1(10) Signal interrupt");
80     // obtain the flight recorder instance and dump the recorder
81     FlightRecorder::GetInstance().playRecorder();
82 }
83 
84 void requestPLDMServiceName()
85 {
86     auto& bus = pldm::utils::DBusHandler::getBus();
87     bus.request_name("xyz.openbmc_project.PLDM");
88 }
89 
90 static std::optional<Response>
91     processRxMsg(const std::vector<uint8_t>& requestMsg, Invoker& invoker,
92                  requester::Handler<requester::Request>& handler,
93                  fw_update::Manager* fwManager, pldm_tid_t tid)
94 {
95     uint8_t eid = tid;
96 
97     pldm_header_info hdrFields{};
98     auto hdr = reinterpret_cast<const pldm_msg_hdr*>(requestMsg.data());
99     if (PLDM_SUCCESS != unpack_pldm_header(hdr, &hdrFields))
100     {
101         error("Empty PLDM request header");
102         return std::nullopt;
103     }
104 
105     if (PLDM_RESPONSE != hdrFields.msg_type)
106     {
107         Response response;
108         auto request = reinterpret_cast<const pldm_msg*>(hdr);
109         size_t requestLen = requestMsg.size() - sizeof(struct pldm_msg_hdr);
110         try
111         {
112             if (hdrFields.pldm_type != PLDM_FWUP)
113             {
114                 response = invoker.handle(tid, hdrFields.pldm_type,
115                                           hdrFields.command, request,
116                                           requestLen);
117             }
118             else
119             {
120                 response = fwManager->handleRequest(eid, hdrFields.command,
121                                                     request, requestLen);
122             }
123         }
124         catch (const std::out_of_range& e)
125         {
126             uint8_t completion_code = PLDM_ERROR_UNSUPPORTED_PLDM_CMD;
127             response.resize(sizeof(pldm_msg_hdr));
128             auto responseHdr = reinterpret_cast<pldm_msg_hdr*>(response.data());
129             pldm_header_info header{};
130             header.msg_type = PLDM_RESPONSE;
131             header.instance = hdrFields.instance;
132             header.pldm_type = hdrFields.pldm_type;
133             header.command = hdrFields.command;
134             if (PLDM_SUCCESS != pack_pldm_header(&header, responseHdr))
135             {
136                 error(
137                     "Failed to add response header for processing Rx, error - {ERROR}",
138                     "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<platform_config::Handler> platformConfigHandler{};
234     platformConfigHandler = std::make_unique<platform_config::Handler>();
235 
236     if (hostEID)
237     {
238         hostPDRHandler = std::make_shared<HostPDRHandler>(
239             pldmTransport.getEventSource(), hostEID, event, pdrRepo.get(),
240             EVENTS_JSONS_DIR, entityTree.get(), bmcEntityTree.get(),
241             instanceIdDb, &reqHandler);
242 
243         // HostFirmware interface needs access to hostPDR to know if host
244         // is running
245         dbusImplHost.setHostPdrObj(hostPDRHandler);
246 
247         hostEffecterParser =
248             std::make_unique<pldm::host_effecters::HostEffecterParser>(
249                 &instanceIdDb, pldmTransport.getEventSource(), pdrRepo.get(),
250                 &dbusHandler, HOST_JSONS_DIR, &reqHandler);
251         dbusToPLDMEventHandler = std::make_unique<DbusToPLDMEvent>(
252             pldmTransport.getEventSource(), hostEID, instanceIdDb, &reqHandler);
253     }
254 
255     auto fruHandler = std::make_unique<fru::Handler>(
256         FRU_JSONS_DIR, FRU_MASTER_JSON, pdrRepo.get(), entityTree.get(),
257         bmcEntityTree.get());
258 
259     // FRU table is built lazily when a FRU command or Get PDR command is
260     // handled. To enable building FRU table, the FRU handler is passed to the
261     // Platform handler.
262     auto platformHandler = std::make_unique<platform::Handler>(
263         &dbusHandler, hostEID, &instanceIdDb, PDR_JSONS_DIR, pdrRepo.get(),
264         hostPDRHandler.get(), dbusToPLDMEventHandler.get(), fruHandler.get(),
265         platformConfigHandler.get(), &reqHandler, event, true);
266 
267     auto biosHandler = std::make_unique<bios::Handler>(
268         pldmTransport.getEventSource(), hostEID, &instanceIdDb, &reqHandler,
269         platformConfigHandler.get(), requestPLDMServiceName);
270 
271     auto baseHandler = std::make_unique<base::Handler>(event);
272 
273 #ifdef OEM_IBM
274     pldm::oem_ibm::OemIBM oemIBM(&dbusHandler, pldmTransport.getEventSource(),
275                                  hostEID, pdrRepo.get(), instanceIdDb, event,
276                                  invoker, hostPDRHandler.get(),
277                                  platformHandler.get(), fruHandler.get(),
278                                  baseHandler.get(), &reqHandler);
279 #endif
280 
281     invoker.registerHandler(PLDM_BIOS, std::move(biosHandler));
282     invoker.registerHandler(PLDM_PLATFORM, std::move(platformHandler));
283     invoker.registerHandler(PLDM_FRU, std::move(fruHandler));
284     invoker.registerHandler(PLDM_BASE, std::move(baseHandler));
285 
286     dbus_api::Pdr dbusImplPdr(bus, "/xyz/openbmc_project/pldm", pdrRepo.get());
287     sdbusplus::xyz::openbmc_project::PLDM::server::Event dbusImplEvent(
288         bus, "/xyz/openbmc_project/pldm");
289 
290 #endif
291 
292     std::unique_ptr<fw_update::Manager> fwManager =
293         std::make_unique<fw_update::Manager>(event, reqHandler, instanceIdDb);
294     std::unique_ptr<MctpDiscovery> mctpDiscoveryHandler =
295         std::make_unique<MctpDiscovery>(
296             bus,
297             std::initializer_list<MctpDiscoveryHandlerIntf*>{fwManager.get()});
298     auto callback = [verbose, &invoker, &reqHandler, &fwManager, &pldmTransport,
299                      TID](IO& io, int fd, uint32_t revents) mutable {
300         if (!(revents & EPOLLIN))
301         {
302             return;
303         }
304         if (fd < 0)
305         {
306             return;
307         }
308 
309         int returnCode = 0;
310         void* requestMsg;
311         size_t recvDataLength;
312         returnCode = pldmTransport.recvMsg(TID, requestMsg, recvDataLength);
313 
314         if (returnCode == PLDM_REQUESTER_SUCCESS)
315         {
316             std::vector<uint8_t> requestMsgVec(
317                 static_cast<uint8_t*>(requestMsg),
318                 static_cast<uint8_t*>(requestMsg) + recvDataLength);
319             FlightRecorder::GetInstance().saveRecord(requestMsgVec, false);
320             if (verbose)
321             {
322                 printBuffer(Rx, requestMsgVec);
323             }
324             // process message and send response
325             auto response = processRxMsg(requestMsgVec, invoker, reqHandler,
326                                          fwManager.get(), TID);
327             if (response.has_value())
328             {
329                 FlightRecorder::GetInstance().saveRecord(*response, true);
330                 if (verbose)
331                 {
332                     printBuffer(Tx, *response);
333                 }
334 
335                 returnCode = pldmTransport.sendMsg(TID, (*response).data(),
336                                                    (*response).size());
337                 if (returnCode != PLDM_REQUESTER_SUCCESS)
338                 {
339                     warning(
340                         "Failed to send pldmTransport message for TID '{TID}', response code '{RETURN_CODE}'",
341                         "TID", TID, "RETURN_CODE", returnCode);
342                 }
343             }
344         }
345         // TODO check that we get here if mctp-demux dies?
346         else if (returnCode == PLDM_REQUESTER_RECV_FAIL)
347         {
348             // MCTP daemon has closed the socket this daemon is connected to.
349             // This may or may not be an error scenario, in either case the
350             // recovery mechanism for this daemon is to restart, and hence exit
351             // the event loop, that will cause this daemon to exit with a
352             // failure code.
353             error(
354                 "MCTP daemon closed the socket, IO exiting with response code '{RC}'",
355                 "RC", returnCode);
356             io.get_event().exit(0);
357         }
358         else
359         {
360             warning(
361                 "Failed to receive PLDM request for pldmTransport, response code '{RETURN_CODE}'",
362                 "RETURN_CODE", returnCode);
363         }
364         /* Free requestMsg after using */
365         free(requestMsg);
366     };
367 
368     bus.attach_event(event.get(), SD_EVENT_PRIORITY_NORMAL);
369 #ifndef SYSTEM_SPECIFIC_BIOS_JSON
370     bus.request_name("xyz.openbmc_project.PLDM");
371 #endif
372     IO io(event, pldmTransport.getEventSource(), EPOLLIN, std::move(callback));
373 #ifdef LIBPLDMRESPONDER
374     if (hostPDRHandler)
375     {
376         hostPDRHandler->setHostFirmwareCondition();
377     }
378 #endif
379     stdplus::signal::block(SIGUSR1);
380     sdeventplus::source::Signal sigUsr1(
381         event, SIGUSR1, std::bind_front(&interruptFlightRecorderCallBack));
382     int returnCode = event.loop();
383     if (returnCode)
384     {
385         exit(EXIT_FAILURE);
386     }
387 
388     exit(EXIT_SUCCESS);
389 }
390