xref: /openbmc/pldm/softoff/softoff.cpp (revision e3607a3c)
1 #include "softoff.hpp"
2 
3 #include "common/instance_id.hpp"
4 #include "common/transport.hpp"
5 #include "common/utils.hpp"
6 
7 #include <libpldm/entity.h>
8 #include <libpldm/platform.h>
9 #include <libpldm/state_set.h>
10 
11 #include <phosphor-logging/lg2.hpp>
12 #include <sdbusplus/bus.hpp>
13 #include <sdeventplus/clock.hpp>
14 #include <sdeventplus/exception.hpp>
15 #include <sdeventplus/source/io.hpp>
16 #include <sdeventplus/source/time.hpp>
17 
18 #include <array>
19 #include <iostream>
20 
21 PHOSPHOR_LOG2_USING;
22 
23 namespace pldm
24 {
25 using namespace sdeventplus;
26 using namespace sdeventplus::source;
27 constexpr auto clockId = sdeventplus::ClockId::RealTime;
28 using Clock = Clock<clockId>;
29 using Timer = Time<clockId>;
30 
31 constexpr pldm::pdr::TerminusID TID = 0; // TID will be implemented later.
32 namespace sdbusRule = sdbusplus::bus::match::rules;
33 
34 SoftPowerOff::SoftPowerOff(sdbusplus::bus_t& bus, sd_event* event) :
35     bus(bus), timer(event)
36 {
37     getHostState();
38     if (hasError || completed)
39     {
40         return;
41     }
42 
43     auto rc = getEffecterID();
44     if (completed)
45     {
46         error("pldm-softpoweroff: effecter to initiate softoff not found");
47         return;
48     }
49     else if (rc != PLDM_SUCCESS)
50     {
51         hasError = true;
52         return;
53     }
54 
55     rc = getSensorInfo();
56     if (rc != PLDM_SUCCESS)
57     {
58         error("Message get Sensor PDRs error. PLDM error code = {RC}", "RC",
59               lg2::hex, static_cast<int>(rc));
60         hasError = true;
61         return;
62     }
63 
64     // Matches on the pldm StateSensorEvent signal
65     pldmEventSignal = std::make_unique<sdbusplus::bus::match_t>(
66         bus,
67         sdbusRule::type::signal() + sdbusRule::member("StateSensorEvent") +
68             sdbusRule::path("/xyz/openbmc_project/pldm") +
69             sdbusRule::interface("xyz.openbmc_project.PLDM.Event"),
70         std::bind(std::mem_fn(&SoftPowerOff::hostSoftOffComplete), this,
71                   std::placeholders::_1));
72 }
73 
74 int SoftPowerOff::getHostState()
75 {
76     try
77     {
78         pldm::utils::PropertyValue propertyValue =
79             pldm::utils::DBusHandler().getDbusPropertyVariant(
80                 "/xyz/openbmc_project/state/host0", "CurrentHostState",
81                 "xyz.openbmc_project.State.Host");
82 
83         if ((std::get<std::string>(propertyValue) !=
84              "xyz.openbmc_project.State.Host.HostState.Running") &&
85             (std::get<std::string>(propertyValue) !=
86              "xyz.openbmc_project.State.Host.HostState.TransitioningToOff"))
87         {
88             // Host state is not "Running", this app should return success
89             completed = true;
90             return PLDM_SUCCESS;
91         }
92     }
93     catch (const std::exception& e)
94     {
95         error("PLDM host soft off: Can't get current host state: {ERROR}",
96               "ERROR", e);
97         hasError = true;
98         return PLDM_ERROR;
99     }
100 
101     return PLDM_SUCCESS;
102 }
103 
104 void SoftPowerOff::hostSoftOffComplete(sdbusplus::message_t& msg)
105 {
106     pldm::pdr::TerminusID msgTID;
107     pldm::pdr::SensorID msgSensorID;
108     pldm::pdr::SensorOffset msgSensorOffset;
109     pldm::pdr::EventState msgEventState;
110     pldm::pdr::EventState msgPreviousEventState;
111 
112     // Read the msg and populate each variable
113     msg.read(msgTID, msgSensorID, msgSensorOffset, msgEventState,
114              msgPreviousEventState);
115 
116     if (msgSensorID == sensorID && msgSensorOffset == sensorOffset &&
117         msgEventState == PLDM_SW_TERM_GRACEFUL_SHUTDOWN)
118     {
119         // Receive Graceful shutdown completion event message. Disable the timer
120         auto rc = timer.stop();
121         if (rc < 0)
122         {
123             error("PLDM soft off: Failure to STOP the timer. ERRNO={RC}", "RC",
124                   rc);
125         }
126 
127         // This marks the completion of pldm soft power off.
128         completed = true;
129     }
130 }
131 
132 int SoftPowerOff::getEffecterID()
133 {
134     auto& bus = pldm::utils::DBusHandler::getBus();
135 
136     // VMM is a logical entity, so the bit 15 in entity type is set.
137     pdr::EntityType entityType = PLDM_ENTITY_VIRTUAL_MACHINE_MANAGER | 0x8000;
138 
139     try
140     {
141         std::vector<std::vector<uint8_t>> VMMResponse{};
142         auto VMMMethod = bus.new_method_call(
143             "xyz.openbmc_project.PLDM", "/xyz/openbmc_project/pldm",
144             "xyz.openbmc_project.PLDM.PDR", "FindStateEffecterPDR");
145         VMMMethod.append(TID, entityType,
146                          (uint16_t)PLDM_STATE_SET_SW_TERMINATION_STATUS);
147 
148         auto VMMResponseMsg = bus.call(VMMMethod, dbusTimeout);
149 
150         VMMResponseMsg.read(VMMResponse);
151         if (VMMResponse.size() != 0)
152         {
153             for (auto& rep : VMMResponse)
154             {
155                 auto VMMPdr =
156                     reinterpret_cast<pldm_state_effecter_pdr*>(rep.data());
157                 effecterID = VMMPdr->effecter_id;
158             }
159         }
160         else
161         {
162             VMMPdrExist = false;
163         }
164     }
165     catch (const sdbusplus::exception_t& e)
166     {
167         error("PLDM soft off: Error get VMM PDR,ERROR={ERR_EXCEP}", "ERR_EXCEP",
168               e.what());
169         VMMPdrExist = false;
170     }
171 
172     if (VMMPdrExist)
173     {
174         return PLDM_SUCCESS;
175     }
176 
177     // If the Virtual Machine Manager PDRs doesn't exist, go find the System
178     // Firmware PDRs.
179     // System Firmware is a logical entity, so the bit 15 in entity type is set
180     entityType = PLDM_ENTITY_SYS_FIRMWARE | 0x8000;
181     try
182     {
183         std::vector<std::vector<uint8_t>> sysFwResponse{};
184         auto sysFwMethod = bus.new_method_call(
185             "xyz.openbmc_project.PLDM", "/xyz/openbmc_project/pldm",
186             "xyz.openbmc_project.PLDM.PDR", "FindStateEffecterPDR");
187         sysFwMethod.append(TID, entityType,
188                            (uint16_t)PLDM_STATE_SET_SW_TERMINATION_STATUS);
189 
190         auto sysFwResponseMsg = bus.call(sysFwMethod, dbusTimeout);
191 
192         sysFwResponseMsg.read(sysFwResponse);
193 
194         if (sysFwResponse.size() == 0)
195         {
196             error("No effecter ID has been found that matches the criteria");
197             return PLDM_ERROR;
198         }
199 
200         for (auto& rep : sysFwResponse)
201         {
202             auto sysFwPdr =
203                 reinterpret_cast<pldm_state_effecter_pdr*>(rep.data());
204             effecterID = sysFwPdr->effecter_id;
205         }
206     }
207     catch (const sdbusplus::exception_t& e)
208     {
209         error("PLDM soft off: Error get system firmware PDR,ERROR={ERR_EXCEP}",
210               "ERR_EXCEP", e.what());
211         completed = true;
212         return PLDM_ERROR;
213     }
214 
215     return PLDM_SUCCESS;
216 }
217 
218 int SoftPowerOff::getSensorInfo()
219 {
220     pldm::pdr::EntityType entityType;
221 
222     entityType = VMMPdrExist ? PLDM_ENTITY_VIRTUAL_MACHINE_MANAGER
223                              : PLDM_ENTITY_SYS_FIRMWARE;
224 
225     // The Virtual machine manager/System firmware is logical entity, so bit 15
226     // need to be set.
227     entityType = entityType | 0x8000;
228 
229     try
230     {
231         auto& bus = pldm::utils::DBusHandler::getBus();
232         std::vector<std::vector<uint8_t>> Response{};
233         auto method = bus.new_method_call(
234             "xyz.openbmc_project.PLDM", "/xyz/openbmc_project/pldm",
235             "xyz.openbmc_project.PLDM.PDR", "FindStateSensorPDR");
236         method.append(TID, entityType,
237                       (uint16_t)PLDM_STATE_SET_SW_TERMINATION_STATUS);
238 
239         auto ResponseMsg = bus.call(method, dbusTimeout);
240 
241         ResponseMsg.read(Response);
242 
243         if (Response.size() == 0)
244         {
245             error("No sensor PDR has been found that matches the criteria");
246             return PLDM_ERROR;
247         }
248 
249         pldm_state_sensor_pdr* pdr = nullptr;
250         for (auto& rep : Response)
251         {
252             pdr = reinterpret_cast<pldm_state_sensor_pdr*>(rep.data());
253             if (!pdr)
254             {
255                 error("Failed to get state sensor PDR.");
256                 return PLDM_ERROR;
257             }
258         }
259 
260         sensorID = pdr->sensor_id;
261 
262         auto compositeSensorCount = pdr->composite_sensor_count;
263         auto possibleStatesStart = pdr->possible_states;
264 
265         for (auto offset = 0; offset < compositeSensorCount; offset++)
266         {
267             auto possibleStates =
268                 reinterpret_cast<state_sensor_possible_states*>(
269                     possibleStatesStart);
270             auto setId = possibleStates->state_set_id;
271             auto possibleStateSize = possibleStates->possible_states_size;
272 
273             if (setId == PLDM_STATE_SET_SW_TERMINATION_STATUS)
274             {
275                 sensorOffset = offset;
276                 break;
277             }
278             possibleStatesStart += possibleStateSize + sizeof(setId) +
279                                    sizeof(possibleStateSize);
280         }
281     }
282     catch (const sdbusplus::exception_t& e)
283     {
284         error("PLDM soft off: Error get State Sensor PDR,ERROR={ERR_EXCEP}",
285               "ERR_EXCEP", e.what());
286         return PLDM_ERROR;
287     }
288 
289     return PLDM_SUCCESS;
290 }
291 
292 int SoftPowerOff::hostSoftOff(sdeventplus::Event& event)
293 {
294     constexpr uint8_t effecterCount = 1;
295     PldmTransport pldmTransport{};
296     uint8_t instanceID;
297     uint8_t mctpEID;
298 
299     mctpEID = pldm::utils::readHostEID();
300     // TODO: fix mapping to work around OpenBMC ecosystem deficiencies
301     pldm_tid_t pldmTID = static_cast<pldm_tid_t>(mctpEID);
302 
303     std::array<uint8_t, sizeof(pldm_msg_hdr) + sizeof(effecterID) +
304                             sizeof(effecterCount) +
305                             sizeof(set_effecter_state_field)>
306         requestMsg{};
307     auto request = reinterpret_cast<pldm_msg*>(requestMsg.data());
308     set_effecter_state_field stateField{
309         PLDM_REQUEST_SET, PLDM_SW_TERM_GRACEFUL_SHUTDOWN_REQUESTED};
310     pldm::InstanceIdDb instanceIdDb;
311     instanceID = instanceIdDb.next(pldmTID);
312     auto rc = encode_set_state_effecter_states_req(
313         instanceID, effecterID, effecterCount, &stateField, request);
314     if (rc != PLDM_SUCCESS)
315     {
316         instanceIdDb.free(pldmTID, instanceID);
317         error("Message encode failure. PLDM error code = {RC}", "RC", lg2::hex,
318               static_cast<int>(rc));
319         return PLDM_ERROR;
320     }
321 
322     // Add a timer to the event loop, default 30s.
323     auto timerCallback = [=, this](Timer& /*source*/,
324                                    Timer::TimePoint /*time*/) mutable {
325         if (!responseReceived)
326         {
327             instanceIdDb.free(pldmTID, instanceID);
328             error(
329                 "PLDM soft off: ERROR! Can't get the response for the PLDM request msg. Time out! Exit the pldm-softpoweroff");
330             exit(-1);
331         }
332         return;
333     };
334     Timer time(event, (Clock(event).now() + std::chrono::seconds{30}),
335                std::chrono::seconds{1}, std::move(timerCallback));
336 
337     // Add a callback to handle EPOLLIN on fd
338     auto callback = [=, &pldmTransport, this](IO& io, int fd,
339                                               uint32_t revents) mutable {
340         if (fd != pldmTransport.getEventSource())
341         {
342             return;
343         }
344 
345         if (!(revents & EPOLLIN))
346         {
347             return;
348         }
349 
350         void* responseMsg = nullptr;
351         size_t responseMsgSize{};
352         pldm_tid_t srcTID = pldmTID;
353 
354         auto rc = pldmTransport.recvMsg(pldmTID, responseMsg, responseMsgSize);
355         if (rc)
356         {
357             error("Soft off: failed to recv pldm data. PLDM RC = {RC}", "RC",
358                   static_cast<int>(rc));
359             return;
360         }
361 
362         std::unique_ptr<void, decltype(std::free)*> responseMsgPtr{responseMsg,
363                                                                    std::free};
364 
365         // We've got the response meant for the PLDM request msg that was
366         // sent out
367         io.set_enabled(Enabled::Off);
368         auto response = reinterpret_cast<pldm_msg*>(responseMsgPtr.get());
369 
370         if (srcTID != pldmTID ||
371             !pldm_msg_hdr_correlate_response(&request->hdr, &response->hdr))
372         {
373             /* This isn't the response we were looking for */
374             return;
375         }
376 
377         /* We have the right response, release the instance ID and process */
378         io.set_enabled(Enabled::Off);
379         instanceIdDb.free(pldmTID, instanceID);
380 
381         if (response->payload[0] != PLDM_SUCCESS)
382         {
383             error("Getting the wrong response. PLDM RC = {RC}", "RC",
384                   (unsigned)response->payload[0]);
385             exit(-1);
386         }
387 
388         responseReceived = true;
389 
390         // Start Timer
391         using namespace std::chrono;
392         auto timeMicroseconds =
393             duration_cast<microseconds>(seconds(SOFTOFF_TIMEOUT_SECONDS));
394 
395         auto ret = startTimer(timeMicroseconds);
396         if (ret < 0)
397         {
398             error(
399                 "Failure to start Host soft off wait timer, ERRNO = {RET}. Exit the pldm-softpoweroff",
400                 "RET", ret);
401             exit(-1);
402         }
403         else
404         {
405             error(
406                 "Timer started waiting for host soft off, TIMEOUT_IN_SEC = {TIMEOUT_SEC}",
407                 "TIMEOUT_SEC", SOFTOFF_TIMEOUT_SECONDS);
408         }
409         return;
410     };
411     IO io(event, pldmTransport.getEventSource(), EPOLLIN, std::move(callback));
412 
413     // Asynchronously send the PLDM request
414     rc = pldmTransport.sendMsg(pldmTID, requestMsg.data(), requestMsg.size());
415     if (0 > rc)
416     {
417         instanceIdDb.free(pldmTID, instanceID);
418         error(
419             "Failed to send message/receive response. RC = {RC}, errno = {ERR}",
420             "RC", static_cast<int>(rc), "ERR", errno);
421         return PLDM_ERROR;
422     }
423 
424     // Time out or soft off complete
425     while (!isCompleted() && !isTimerExpired())
426     {
427         try
428         {
429             event.run(std::nullopt);
430         }
431         catch (const sdeventplus::SdEventError& e)
432         {
433             instanceIdDb.free(pldmTID, instanceID);
434             error(
435                 "PLDM host soft off: Failure in processing request.ERROR= {ERR_EXCEP}",
436                 "ERR_EXCEP", e.what());
437             return PLDM_ERROR;
438         }
439     }
440 
441     return PLDM_SUCCESS;
442 }
443 
444 int SoftPowerOff::startTimer(const std::chrono::microseconds& usec)
445 {
446     return timer.start(usec);
447 }
448 } // namespace pldm
449