xref: /openbmc/pldm/pldmd/pldmd.cpp (revision 6c7fed4c)
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 = std::make_unique<platform_config::Handler>();
236 
237     if (hostEID)
238     {
239         hostPDRHandler = std::make_shared<HostPDRHandler>(
240             pldmTransport.getEventSource(), hostEID, event, pdrRepo.get(),
241             EVENTS_JSONS_DIR, entityTree.get(), bmcEntityTree.get(),
242             instanceIdDb, &reqHandler);
243 
244         // HostFirmware interface needs access to hostPDR to know if host
245         // is running
246         dbusImplHost.setHostPdrObj(hostPDRHandler);
247 
248         hostEffecterParser =
249             std::make_unique<pldm::host_effecters::HostEffecterParser>(
250                 &instanceIdDb, pldmTransport.getEventSource(), pdrRepo.get(),
251                 &dbusHandler, HOST_JSONS_DIR, &reqHandler);
252         dbusToPLDMEventHandler = std::make_unique<DbusToPLDMEvent>(
253             pldmTransport.getEventSource(), hostEID, instanceIdDb, &reqHandler);
254     }
255 
256     auto fruHandler = std::make_unique<fru::Handler>(
257         FRU_JSONS_DIR, FRU_MASTER_JSON, pdrRepo.get(), entityTree.get(),
258         bmcEntityTree.get());
259 
260     // FRU table is built lazily when a FRU command or Get PDR command is
261     // handled. To enable building FRU table, the FRU handler is passed to the
262     // Platform handler.
263     auto platformHandler = std::make_unique<platform::Handler>(
264         &dbusHandler, hostEID, &instanceIdDb, PDR_JSONS_DIR, pdrRepo.get(),
265         hostPDRHandler.get(), dbusToPLDMEventHandler.get(), fruHandler.get(),
266         platformConfigHandler.get(), &reqHandler, event, true);
267 
268     auto biosHandler = std::make_unique<bios::Handler>(
269         pldmTransport.getEventSource(), hostEID, &instanceIdDb, &reqHandler,
270         platformConfigHandler.get(), requestPLDMServiceName);
271 
272     auto baseHandler = std::make_unique<base::Handler>(event);
273 
274 #ifdef OEM_IBM
275     pldm::oem_ibm::OemIBM oemIBM(&dbusHandler, pldmTransport.getEventSource(),
276                                  hostEID, pdrRepo.get(), instanceIdDb, event,
277                                  invoker, hostPDRHandler.get(),
278                                  platformHandler.get(), fruHandler.get(),
279                                  baseHandler.get(), &reqHandler);
280 #endif
281 
282     invoker.registerHandler(PLDM_BIOS, std::move(biosHandler));
283     invoker.registerHandler(PLDM_PLATFORM, std::move(platformHandler));
284     invoker.registerHandler(PLDM_FRU, std::move(fruHandler));
285     invoker.registerHandler(PLDM_BASE, std::move(baseHandler));
286 
287     dbus_api::Pdr dbusImplPdr(bus, "/xyz/openbmc_project/pldm", pdrRepo.get());
288     sdbusplus::xyz::openbmc_project::PLDM::server::Event dbusImplEvent(
289         bus, "/xyz/openbmc_project/pldm");
290 
291 #endif
292 
293     std::unique_ptr<fw_update::Manager> fwManager =
294         std::make_unique<fw_update::Manager>(event, reqHandler, instanceIdDb);
295     std::unique_ptr<platform_mc::Manager> platformManager =
296         std::make_unique<platform_mc::Manager>(event, reqHandler, instanceIdDb);
297     std::unique_ptr<MctpDiscovery> mctpDiscoveryHandler =
298         std::make_unique<MctpDiscovery>(
299             bus, std::initializer_list<MctpDiscoveryHandlerIntf*>{
300                      fwManager.get(), platformManager.get()});
301     auto callback = [verbose, &invoker, &reqHandler, &fwManager, &pldmTransport,
302                      TID](IO& io, int fd, uint32_t revents) mutable {
303         if (!(revents & EPOLLIN))
304         {
305             return;
306         }
307         if (fd < 0)
308         {
309             return;
310         }
311 
312         int returnCode = 0;
313         void* requestMsg;
314         size_t recvDataLength;
315         returnCode = pldmTransport.recvMsg(TID, requestMsg, recvDataLength);
316 
317         if (returnCode == PLDM_REQUESTER_SUCCESS)
318         {
319             std::vector<uint8_t> requestMsgVec(
320                 static_cast<uint8_t*>(requestMsg),
321                 static_cast<uint8_t*>(requestMsg) + recvDataLength);
322             FlightRecorder::GetInstance().saveRecord(requestMsgVec, false);
323             if (verbose)
324             {
325                 printBuffer(Rx, requestMsgVec);
326             }
327             // process message and send response
328             auto response = processRxMsg(requestMsgVec, invoker, reqHandler,
329                                          fwManager.get(), TID);
330             if (response.has_value())
331             {
332                 FlightRecorder::GetInstance().saveRecord(*response, true);
333                 if (verbose)
334                 {
335                     printBuffer(Tx, *response);
336                 }
337 
338                 returnCode = pldmTransport.sendMsg(TID, (*response).data(),
339                                                    (*response).size());
340                 if (returnCode != PLDM_REQUESTER_SUCCESS)
341                 {
342                     warning(
343                         "Failed to send pldmTransport message for TID '{TID}', response code '{RETURN_CODE}'",
344                         "TID", TID, "RETURN_CODE", returnCode);
345                 }
346             }
347         }
348         // TODO check that we get here if mctp-demux dies?
349         else if (returnCode == PLDM_REQUESTER_RECV_FAIL)
350         {
351             // MCTP daemon has closed the socket this daemon is connected to.
352             // This may or may not be an error scenario, in either case the
353             // recovery mechanism for this daemon is to restart, and hence exit
354             // the event loop, that will cause this daemon to exit with a
355             // failure code.
356             error(
357                 "MCTP daemon closed the socket, IO exiting with response code '{RC}'",
358                 "RC", returnCode);
359             io.get_event().exit(0);
360         }
361         else
362         {
363             warning(
364                 "Failed to receive PLDM request for pldmTransport, response code '{RETURN_CODE}'",
365                 "RETURN_CODE", returnCode);
366         }
367         /* Free requestMsg after using */
368         free(requestMsg);
369     };
370 
371     bus.attach_event(event.get(), SD_EVENT_PRIORITY_NORMAL);
372 #ifndef SYSTEM_SPECIFIC_BIOS_JSON
373     bus.request_name("xyz.openbmc_project.PLDM");
374 #endif
375     IO io(event, pldmTransport.getEventSource(), EPOLLIN, std::move(callback));
376 #ifdef LIBPLDMRESPONDER
377     if (hostPDRHandler)
378     {
379         hostPDRHandler->setHostFirmwareCondition();
380     }
381 #endif
382     stdplus::signal::block(SIGUSR1);
383     sdeventplus::source::Signal sigUsr1(
384         event, SIGUSR1, std::bind_front(&interruptFlightRecorderCallBack));
385     int returnCode = event.loop();
386     if (returnCode)
387     {
388         exit(EXIT_FAILURE);
389     }
390 
391     exit(EXIT_SUCCESS);
392 }
393