xref: /openbmc/openpower-occ-control/pldm.hpp (revision 52328cb4)
1 #pragma once
2 
3 #include "occ_events.hpp"
4 #include "occ_status.hpp"
5 #include "utils.hpp"
6 
7 #include <libpldm/instance-id.h>
8 #include <libpldm/pldm.h>
9 #include <libpldm/transport.h>
10 #include <libpldm/transport/mctp-demux.h>
11 
12 #include <sdbusplus/bus/match.hpp>
13 #include <sdeventplus/event.hpp>
14 #include <sdeventplus/utility/timer.hpp>
15 
16 namespace pldm
17 {
18 
19 namespace MatchRules = sdbusplus::bus::match::rules;
20 using namespace open_power::occ;
21 
22 using CompositeEffecterCount = uint8_t;
23 using EffecterID = uint16_t;
24 using EntityType = uint16_t;
25 using EntityInstance = uint16_t;
26 using EventState = uint8_t;
27 using InstanceToEffecter = std::map<open_power::occ::instanceID, EffecterID>;
28 using PdrList = std::vector<std::vector<uint8_t>>;
29 using SensorID = uint16_t;
30 using SensorOffset = uint8_t;
31 using SensorToInstance = std::map<SensorID, open_power::occ::instanceID>;
32 using TerminusID = uint8_t;
33 
34 /** @brief OCC instance starts with 0 for example "occ0" */
35 constexpr open_power::occ::instanceID start = 0;
36 
37 /** @brief Hardcoded mctpEid for HBRT */
38 constexpr mctp_eid_t mctpEid = 10;
39 
40 /** @brief Hardcoded TID */
41 constexpr TerminusID tid = mctpEid;
42 
43 /** @class Interface
44  *
45  *  @brief Abstracts the PLDM details related to the OCC
46  */
47 class Interface
48 {
49   public:
50     Interface() = delete;
51     //~Interface() = default;
52     Interface(const Interface&) = delete;
53     Interface& operator=(const Interface&) = delete;
54     Interface(Interface&&) = delete;
55     Interface& operator=(Interface&&) = delete;
56 
57     /** @brief Constructs the PLDM Interface object for OCC functions
58      *
59      *  @param[in] callBack - callBack handler to invoke when the OCC state
60      *                        changes.
61      */
62     explicit Interface(
63         std::function<bool(open_power::occ::instanceID, bool)> callBack,
64         std::function<void(open_power::occ::instanceID, bool)> sbeCallBack,
65         std::function<void(bool)> safeModeCallBack, EventPtr& event) :
66         callBack(callBack),
67         sbeCallBack(sbeCallBack), safeModeCallBack(safeModeCallBack),
68         event(event),
69         pldmEventSignal(
70             open_power::occ::utils::getBus(),
71             MatchRules::type::signal() +
72                 MatchRules::member("StateSensorEvent") +
73                 MatchRules::path("/xyz/openbmc_project/pldm") +
74                 MatchRules::interface("xyz.openbmc_project.PLDM.Event"),
75             std::bind(std::mem_fn(&Interface::sensorEvent), this,
76                       std::placeholders::_1)),
77         hostStateSignal(
78             open_power::occ::utils::getBus(),
79             MatchRules::propertiesChanged("/xyz/openbmc_project/state/host0",
80                                           "xyz.openbmc_project.State.Host"),
81             std::bind(std::mem_fn(&Interface::hostStateEvent), this,
82                       std::placeholders::_1)),
83         sdpEvent(sdeventplus::Event::get_default()),
84         pldmRspTimer(
85             sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>(
86                 sdpEvent, std::bind(&Interface::pldmRspExpired, this)))
87     {
88         int rc = pldm_instance_db_init_default(&pldmInstanceIdDb);
89         if (rc)
90         {
91             throw std::system_category().default_error_condition(rc);
92         }
93     }
94 
95     ~Interface()
96     {
97         int rc = pldm_instance_db_destroy(pldmInstanceIdDb);
98         if (rc)
99         {
100             std::cout << "pldm_instance_db_destroy failed, rc =" << rc << "\n";
101         }
102     }
103 
104     /** @brief Fetch the state sensor PDRs and populate the cache with
105      *         sensorId to OCC/SBE instance mapping information and the sensor
106      *         offset for the relevent state set.
107      *
108      *  @param[in] stateSetId - the state set ID to look for
109      *  @param[out] sensorInstanceMap - map of sensorID to instance
110      *  @param[out] sensorOffset - sensor offset of interested state set ID
111      */
112     void fetchSensorInfo(uint16_t stateSetId,
113                          SensorToInstance& sensorInstanceMap,
114                          SensorOffset& sensorOffset);
115 
116     /** @brief Fetch the OCC/SBE state effecter PDRs and populate the cache
117      *         with OCC/SBE instance to EffecterID information.
118      *
119      *  @param[in] stateSetId - the state set ID to look for
120      *  @param[out] instanceToEffecterMap - map of instance to effecterID
121      *  @param[out] count - sensor offset of interested state set ID
122      *  @param[out] stateIdPos - position of the stateSetID
123      */
124     void fetchEffecterInfo(uint16_t stateSetId,
125                            InstanceToEffecter& instanceToEffecterMap,
126                            CompositeEffecterCount& count, uint8_t& stateIdPos);
127 
128     /** @brief Prepare the request for SetStateEffecterStates command
129      *
130      *  @param[in] effecterId - the instance effecter ID
131      *  @param[in] effecterCount - compositeEffecterCount for the effecter PDR
132      *  @param[in] stateIdPos - position of the stateSetID
133      *  @param[in] stateSetValue - the value to set the state set to
134      *
135      *  @return PLDM request message to be sent to host for OCC reset or SBE
136      *          HRESET, empty response in the case of failure.
137      */
138     std::vector<uint8_t>
139         prepareSetEffecterReq(EffecterID effecterId,
140                               CompositeEffecterCount effecterCount,
141                               uint8_t stateIdPos, uint8_t stateSetValue);
142 
143     /** @brief Send the PLDM message to reset the OCC
144      *
145      *  @param[in] instanceId - OCC instance to reset
146      *
147      */
148     void resetOCC(open_power::occ::instanceID occInstanceId);
149 
150     /** @brief Send the PLDM message to perform the HRESET
151      *
152      *  @param[in] instanceID - SBE instance to HRESET
153      */
154     void sendHRESET(open_power::occ::instanceID sbeInstanceId);
155 
156     /** @brief Check if the OCC active sensor is available
157      *         On successful read, the Manager callback will be called to update
158      *         the status
159      *
160      *  @param[in] instance  - OCC instance to check
161      */
162     void checkActiveSensor(uint8_t instance);
163 
164     /** @brief Set the throttleTraces flag
165      *
166      * @param[in] throttle - Flag to indicate if traces should be throttled
167      */
168     void setTraceThrottle(const bool throttle);
169 
170   private:
171     /** @brief PLDM instance ID database object used to get instance IDs
172      */
173     pldm_instance_db* pldmInstanceIdDb = nullptr;
174 
175     /** @brief PLDM instance number used in PLDM requests
176      */
177     std::optional<uint8_t> pldmInstanceID;
178 
179     /** @brief Callback handler to be invoked when the state of the OCC
180      *         changes
181      */
182     std::function<bool(open_power::occ::instanceID, bool)> callBack = nullptr;
183 
184     /** @brief Callback handler to be invoked when the maintenance state of the
185      *         SBE changes
186      */
187     std::function<void(open_power::occ::instanceID, bool)> sbeCallBack =
188         nullptr;
189 
190     /** @brief Callback handler to be invoked when the OCC is in SAFE Mode =
191      *         true or when OCCs are in_service = false.
192      */
193     std::function<void(bool)> safeModeCallBack = nullptr;
194 
195     /** @brief reference to sd_event wrapped in unique_ptr */
196     EventPtr& event;
197 
198     /** @brief event source wrapped in unique_ptr */
199     EventSourcePtr eventSource;
200 
201     /** @brief Used to subscribe to D-Bus PLDM StateSensorEvent signal and
202      *         processes if the event corresponds to OCC state change.
203      */
204     sdbusplus::bus::match_t pldmEventSignal;
205 
206     /** @brief Used to subscribe for host state change signal */
207     sdbusplus::bus::match_t hostStateSignal;
208 
209     /** @brief PLDM Sensor ID to OCC Instance mapping
210      */
211     SensorToInstance sensorToOCCInstance;
212 
213     /** @brief PLDM Sensor ID to SBE Instance mapping
214      */
215     SensorToInstance sensorToSBEInstance;
216 
217     /** @brief Sensor offset of OCC state set ID
218      * PLDM_STATE_SET_OPERATIONAL_RUNNING_STATUS in state sensor PDR.
219      */
220     SensorOffset OCCSensorOffset = 0;
221 
222     /** @brief Sensor offset of the SBE state set ID
223      * PLDM_OEM_IBM_SBE_HRESET_STATE in state sensor PDR.
224      */
225     SensorOffset SBESensorOffset = 0;
226 
227     /** @brief OCC Instance mapping to PLDM Effecter ID
228      */
229     InstanceToEffecter occInstanceToEffecter;
230 
231     /** @brief SBE instance mapping to PLDM Effecter ID
232      */
233     InstanceToEffecter sbeInstanceToEffecter;
234 
235     /** @brief compositeEffecterCount for OCC reset state effecter PDR */
236     CompositeEffecterCount OCCEffecterCount = 0;
237 
238     /** @brief compositeEffecterCount for SBE HRESET state effecter PDR */
239     CompositeEffecterCount SBEEffecterCount = 0;
240 
241     /** @brief Position of Boot/Restart Cause stateSetID in OCC state
242      *         effecter PDR
243      */
244     uint8_t bootRestartPosition = 0;
245 
246     /** @brief Position of the SBE maintenance stateSetID in the state
247      *         effecter PDR
248      */
249     uint8_t sbeMaintenanceStatePosition = 0;
250 
251     /** @brief OCC instance number for the PLDM message */
252     uint8_t pldmResponseOcc = 0;
253 
254     /** @brief File descriptor for PLDM messages */
255     int pldmFd = -1;
256 
257     /** pldm transport instance  */
258     struct pldm_transport* pldmTransport = NULL;
259 
260     struct pldm_transport_mctp_demux* mctpDemux;
261 
262     /** @brief The response for the PLDM request msg is received flag.
263      */
264     bool pldmResponseReceived = false;
265 
266     /** @brief The response for the PLDM request has timed out.
267      */
268     bool pldmResponseTimeout = false;
269 
270     /** @brief timer event */
271     sdeventplus::Event sdpEvent;
272 
273     /** @brief Timer that is started when PLDM command is sent
274      */
275     sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic> pldmRspTimer;
276 
277     std::set<uint8_t> outstandingHResets;
278 
279     /** @brief Flag to indicate that traces should be throttled.
280                Used to limit traces when there are issues getting OCC status.
281      */
282     static bool throttleTraces;
283 
284     /** @brief Callback when PLDM response has not been received within the
285      * timeout period.
286      */
287     void pldmRspExpired();
288 
289     /** @brief Close the MCTP file */
290     void pldmClose();
291 
292     /** @brief When the OCC state changes host sends PlatformEventMessage
293      *         StateSensorEvent, this function processes the D-Bus signal
294      *         with the sensor event information and invokes the callback
295      *         to change the OCC state.
296      *
297      *  @param[in] msg - data associated with the subscribed signal
298      */
299     void sensorEvent(sdbusplus::message_t& msg);
300 
301     /** @brief When the host state changes and if the CurrentHostState is
302      *         xyz.openbmc_project.State.Host.HostState.Off then
303      *         the cache of OCC sensors and effecters mapping is cleared.
304      *
305      *  @param[in] msg - data associated with the subscribed signal
306      */
307     void hostStateEvent(sdbusplus::message_t& msg);
308 
309     /** @brief Called when it is determined that the Host is not running.
310      *         The cache of OCC sensors and effecters mapping is cleared.
311      */
312     void clearData();
313 
314     /** @brief Check if the PDR cache for PLDM OCC sensors is valid
315      *
316      *  @return true if cache is populated and false if the cache is not
317      *          populated.
318      */
319     auto isOCCSensorCacheValid()
320     {
321         return (sensorToOCCInstance.empty() ? false : true);
322     }
323 
324     /** @brief Check if the PDR cache for PLDM OCC effecters is valid
325      *
326      *  @return true if cache is populated and false if the cache is not
327      *          populated.
328      */
329     auto isPDREffecterCacheValid()
330     {
331         return (occInstanceToEffecter.empty() ? false : true);
332     }
333 
334     /** @brief Get a PLDM requester instance id
335      *
336      * @return true if the id was found and false if not
337      */
338     bool getPldmInstanceId();
339 
340     /** @brief Free PLDM requester instance id */
341     void freePldmInstanceId();
342 
343     /** @brief Encode a GetStateSensor command into a PLDM request
344      *  @param[in] instance - OCC instance number
345      *  @param[in] sensorId - OCC Active sensor ID number
346      *
347      *  @return request - The encoded PLDM messsage to be sent
348      */
349     std::vector<uint8_t> encodeGetStateSensorRequest(uint8_t instance,
350                                                      uint16_t sensorId);
351 
352     /** @brief setup PLDM transport for sending and receiving PLDM messages.
353      *
354      * @return true on success, otherwise return false
355      */
356     int pldmOpen(void);
357 
358     /** @brief Opens the MCTP socket for sending and receiving messages.
359      *
360      * @return true on success, otherwise returns a negative error code
361      */
362     int openMctpDemuxTransport();
363 
364     /** @brief Send the PLDM request
365      *
366      * @param[in] request - the request data
367      * @param[in] rspExpected - false: no need to wait for the response
368      *                          true: will need to process response in callback
369      */
370     void sendPldm(const std::vector<uint8_t>& request, const uint8_t instance,
371                   const bool rspExpected = false);
372 
373     /** @brief Register a callback function to handle the PLDM response */
374     void registerPldmRspCallback();
375 
376     /** @brief callback for the PLDM response event
377      *
378      *  @param[in] es       - Populated event source
379      *  @param[in] fd       - Associated File descriptor
380      *  @param[in] revents  - Type of event
381      *  @param[in] userData - User data that was passed during registration
382      *
383      *  @return             - 0 or positive number on success and negative
384      *                        errno otherwise
385      */
386     static int pldmRspCallback(sd_event_source* es, int fd, uint32_t revents,
387                                void* userData);
388 };
389 
390 } // namespace pldm
391