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