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