1 #pragma once
2 
3 #include "occ_pass_through.hpp"
4 #include "occ_status.hpp"
5 #ifdef PLDM
6 #include "pldm.hpp"
7 
8 #include <libphal.H>
9 #endif
10 #include "powercap.hpp"
11 #include "utils.hpp"
12 #ifdef POWER10
13 #include "powermode.hpp"
14 #endif
15 
16 #include <sdbusplus/bus.hpp>
17 #include <sdeventplus/event.hpp>
18 #include <sdeventplus/utility/timer.hpp>
19 
20 #include <cstring>
21 #include <functional>
22 #include <vector>
23 
24 namespace sdbusRule = sdbusplus::bus::match::rules;
25 namespace open_power
26 {
27 namespace occ
28 {
29 
30 #ifdef READ_OCC_SENSORS
31 enum occFruType
32 {
33     processorCore = 0,
34     internalMemCtlr = 1,
35     dimm = 2,
36     memCtrlAndDimm = 3,
37     VRMVdd = 6,
38     PMIC = 7,
39     memCtlrExSensor = 8,
40     processorIoRing = 9
41 };
42 #endif
43 
44 /** @brief Default time, in seconds, between OCC poll commands */
45 #ifndef POWER10
46 constexpr unsigned int defaultPollingInterval = 1;
47 #else
48 constexpr unsigned int defaultPollingInterval = 5;
49 #endif
50 
51 constexpr auto AMBIENT_PATH =
52     "/xyz/openbmc_project/sensors/temperature/Ambient_Virtual_Temp";
53 constexpr auto AMBIENT_INTERFACE = "xyz.openbmc_project.Sensor.Value";
54 constexpr auto AMBIENT_PROP = "Value";
55 constexpr auto ALTITUDE_PATH = "/xyz/openbmc_project/sensors/altitude/Altitude";
56 constexpr auto ALTITUDE_INTERFACE = "xyz.openbmc_project.Sensor.Value";
57 constexpr auto ALTITUDE_PROP = "Value";
58 
59 /** @class Manager
60  *  @brief Builds and manages OCC objects
61  */
62 struct Manager
63 {
64   public:
65     Manager() = delete;
66     Manager(const Manager&) = delete;
67     Manager& operator=(const Manager&) = delete;
68     Manager(Manager&&) = delete;
69     Manager& operator=(Manager&&) = delete;
70     ~Manager() = default;
71 
72     /** @brief Adds OCC pass-through and status objects on the bus
73      *         when corresponding CPU inventory is created.
74      *
75      *  @param[in] event - Unique ptr reference to sd_event
76      */
Manageropen_power::occ::Manager77     explicit Manager(EventPtr& event) :
78         event(event), pollInterval(defaultPollingInterval),
79         sdpEvent(sdeventplus::Event::get_default()),
80         _pollTimer(
81             std::make_unique<
82                 sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>>(
83                 sdpEvent, std::bind(&Manager::pollerTimerExpired, this))),
84         ambientPropChanged(
85             utils::getBus(),
86             sdbusRule::member("PropertiesChanged") +
87                 sdbusRule::path(AMBIENT_PATH) +
88                 sdbusRule::argN(0, AMBIENT_INTERFACE) +
89                 sdbusRule::interface("org.freedesktop.DBus.Properties"),
90             std::bind(&Manager::ambientCallback, this, std::placeholders::_1))
91 #ifdef PLDM
92         ,
93         pldmHandle(std::make_unique<pldm::Interface>(
94             std::bind(std::mem_fn(&Manager::updateOCCActive), this,
95                       std::placeholders::_1, std::placeholders::_2),
96             std::bind(std::mem_fn(&Manager::sbeHRESETResult), this,
97                       std::placeholders::_1, std::placeholders::_2),
98             std::bind(std::mem_fn(&Manager::updateOccSafeMode), this,
99                       std::placeholders::_1),
100             event))
101 #endif
102 #ifdef POWER10
103         ,
104         discoverTimer(
105             std::make_unique<
106                 sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>>(
107                 sdpEvent, std::bind(&Manager::findAndCreateObjects, this))),
108         waitForAllOccsTimer(
109             std::make_unique<
110                 sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>>(
111                 sdpEvent, std::bind(&Manager::occsNotAllRunning, this)))
112 #ifdef PLDM
113         ,
114         throttlePldmTraceTimer(
115             std::make_unique<
116                 sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>>(
117                 sdpEvent, std::bind(&Manager::throttlePldmTraceExpired, this)))
118 #endif
119 #endif // POWER10
120     {
121 #ifdef I2C_OCC
122         // I2C OCC status objects are initialized directly
123         initStatusObjects();
124 #else
125         findAndCreateObjects();
126 #endif
127         readAltitude();
128     }
129 
130     /** @brief Return the number of bound OCCs */
getNumOCCsopen_power::occ::Manager131     inline auto getNumOCCs() const
132     {
133         return activeCount;
134     }
135 
136 #ifdef PLDM
137     /** @brief Called by a Device to report that the SBE timed out
138      *         and appropriate action should be taken
139      *
140      * @param[in] instance - the OCC instance id
141      */
142     void sbeTimeout(unsigned int instance);
143 #endif
144 
145     /** @brief Return the latest ambient and altitude readings
146      *
147      *  @param[out] ambientValid - true if ambientTemp is valid
148      *  @param[out] ambient - ambient temperature in degrees C
149      *  @param[out] altitude - altitude in meters
150      */
151     void getAmbientData(bool& ambientValid, uint8_t& ambientTemp,
152                         uint16_t& altitude) const;
153 
154     /** @brief Notify pcap object to update bounds */
155     void updatePcapBounds() const;
156 
157     /**
158      * @brief Set all sensor values of this OCC to NaN.
159      * @param[in] id - Id of the OCC.
160      * */
161     void setSensorValueToNaN(uint32_t id) const;
162 
163     /** @brief Set all sensor values of this OCC to NaN and non functional.
164      *
165      *  @param[in] id - Id of the OCC.
166      */
167     void setSensorValueToNonFunctional(uint32_t id) const;
168 
169   private:
170     /** @brief Creates the OCC D-Bus objects.
171      */
172     void findAndCreateObjects();
173 
174     /** @brief Callback that responds to cpu creation in the inventory -
175      *         by creating the needed objects.
176      *
177      *  @param[in] msg - bus message
178      *
179      *  @returns 0 to indicate success
180      */
181     int cpuCreated(sdbusplus::message_t& msg);
182 
183     /** @brief Create child OCC objects.
184      *
185      *  @param[in] occ - the occ name, such as occ0.
186      */
187     void createObjects(const std::string& occ);
188 
189     /** @brief Callback handler invoked by Status object when the OccActive
190      *         property is changed. This is needed to make sure that the
191      *         error detection is started only after all the OCCs are bound.
192      *         Similarly, when one of the OCC gets its OccActive property
193      *         un-set, then the OCC error detection needs to be stopped on
194      *         all the OCCs
195      *
196      *  @param[in] status - OccActive status
197      */
198     void statusCallBack(instanceID instance, bool status);
199 
200     /** @brief Set flag that a PM Complex reset is needed (to be initiated
201      * later) */
202     void resetOccRequest(instanceID instance);
203 
204     /** @brief Initiate the request to reset the PM Complex (PLDM -> HBRT) */
205     void initiateOccRequest(instanceID instance);
206 
207     /** @brief Sends a Heartbeat command to host control command handler */
208     void sendHeartBeat();
209 
210     /** @brief reference to sd_event wrapped in unique_ptr */
211     EventPtr& event;
212 
213     /** @brief OCC pass-through objects */
214     std::vector<std::unique_ptr<PassThrough>> passThroughObjects;
215 
216     /** @brief OCC Status objects */
217     std::vector<std::unique_ptr<Status>> statusObjects;
218 
219     /** @brief Power cap monitor and occ notification object */
220     std::unique_ptr<open_power::occ::powercap::PowerCap> pcap;
221 
222 #ifdef POWER10
223     /** @brief Power mode monitor and notification object */
224     std::unique_ptr<open_power::occ::powermode::PowerMode> pmode;
225 #endif
226 
227     /** @brief sbdbusplus match objects */
228     std::vector<sdbusplus::bus::match_t> cpuMatches;
229 
230     /** @brief Number of OCCs that are bound */
231     uint8_t activeCount = 0;
232 
233     /** @brief Number of seconds between poll commands */
234     uint8_t pollInterval;
235 
236     /** @brief Ambient temperature of the system in degrees C */
237     uint8_t ambient = 0xFF; // default: not available
238 
239     /** @brief Altitude of the system in meters */
240     uint16_t altitude = 0xFFFF; // default: not available
241 
242     /** @brief Poll timer event */
243     sdeventplus::Event sdpEvent;
244 
245     /** @brief Flags to indicate if waiting for all of the OCC active sensors to
246      * come online */
247     bool waitingForAllOccActiveSensors = false;
248 
249     /** @brief Set containing intance numbers of any OCCs that became active
250      *         while waiting for status objects to be created */
251     std::set<uint8_t> queuedActiveState;
252 
253     /**
254      * @brief The timer to be used once the OCC goes active.  When it expires,
255      *        a POLL command will be sent to the OCC and then timer restarted.
256      */
257     std::unique_ptr<
258         sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>>
259         _pollTimer;
260 
261     /** @brief Subscribe to ambient temperature changed events */
262     sdbusplus::bus::match_t ambientPropChanged;
263 
264     /** @brief Flag to indicate that a PM complex reset needs to happen */
265     bool resetRequired = false;
266     /** @brief Instance number of the OCC/processor that triggered the reset */
267     uint8_t resetInstance = 255;
268     /** @brief Set when a PM complex reset has been issued (to prevent multiple
269      * requests) */
270     bool resetInProgress = false;
271 
272 #ifdef I2C_OCC
273     /** @brief Init Status objects for I2C OCC devices
274      *
275      * It iterates in /sys/bus/i2c/devices, finds all occ hwmon devices
276      * and creates status objects.
277      */
278     void initStatusObjects();
279 #endif
280 
281 #ifdef PLDM
282     /** @brief Callback handler invoked by the PLDM event handler when state of
283      *         the OCC is toggled by the host. The caller passes the instance
284      *         of the OCC and state of the OCC.
285      *
286      *  @param[in] instance - instance of the OCC
287      *  @param[in] status - true when the OCC goes active and false when the OCC
288      *                      goes inactive
289      *
290      *  @return true if setting the state of OCC is successful and false if it
291      *          fails.
292      */
293     bool updateOCCActive(instanceID instance, bool status);
294 
295     /** @brief Callback handler invoked by the PLDM event handler when mode of
296      *         the OCC SAFE MODE is inacted or cleared.
297      */
298     void updateOccSafeMode(bool safeState);
299 
300     /** @brief Callback handler invoked by PLDM sensor change when
301      *         the HRESET succeeds or fails.
302      *
303      *  @param[in] instance - the SBE instance id
304      *  @param[in] success - true if the HRESET succeeded, otherwise false
305      */
306     void sbeHRESETResult(instanceID instance, bool success);
307 
308     /** @brief Helper function to check whether an SBE dump should be collected
309      *         now.
310      *
311      *  @param[in] instance - the SBE instance id
312      *
313      *  @return true if an SBE dump should be collected and false if not
314      */
315     bool sbeCanDump(unsigned int instance);
316 
317     /** @brief Helper function to set the SBE state through PDBG/PHAL
318      *
319      * @param[in] instance - instance of the SBE
320      * @param[in] state - the state to which the SBE should be set
321      *
322      */
323     void setSBEState(unsigned int instance, enum sbe_state state);
324 
325     /** @brief Helper function to get the SBE instance PDBG processor target
326      *
327      * @param[in] instance - the SBE instance id
328      *
329      * @return a pointer to the PDBG target
330      */
331     struct pdbg_target* getPdbgTarget(unsigned int instance);
332 
333     /** @brief Whether pdbg_targets_init has been called */
334     bool pdbgInitialized = false;
335 
336     std::unique_ptr<pldm::Interface> pldmHandle = nullptr;
337 #endif
338 
339 #ifdef POWER10
340     /**
341      * @brief Timer used when discovering OCCs in /dev.
342      */
343     std::unique_ptr<
344         sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>>
345         discoverTimer;
346 
347     /**
348      * @brief Used when discovering /dev/occ objects to know if
349      *        any were added since the last check.
350      */
351     std::vector<int> prevOCCSearch;
352 
353     /**
354      * @brief Timer used when waiting for OCCs to go active.
355      */
356     std::unique_ptr<
357         sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>>
358         waitForAllOccsTimer;
359 
360 #ifdef PLDM
361     /**
362      * @brief Timer used to throttle PLDM traces when there are problems
363               determining the OCC status via pldm. Used to prevent excessive
364               journal traces.
365      */
366     std::unique_ptr<
367         sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>>
368         throttlePldmTraceTimer;
369     /**
370      * @brief onPldmTimeoutCreatePel flag will be used to indicate if
371      *        a PEL should get created when the throttlePldmTraceTimer expires.
372      *        The first time the throttlePldmTraceTimer expires, the traces
373      *        will be throttled and then the timer gets restarted. The
374      *        next time the timer expires, a PEL will get created.
375      */
376     bool onPldmTimeoutCreatePel = false;
377 
378     /** @brief Check if all of the OCC Active sensors are available and if not
379      * restart the discoverTimer
380      */
381     void throttlePldmTraceExpired();
382 
383     /** @brief Create a PEL when the code is not able to obtain the OCC PDRs
384      * via PLDM. This is called when the throttlePldmTraceTimer expires.
385      */
386     void createPldmSensorPEL();
387 #endif
388 
389     /** @brief Called when code times out waiting for all OCCs to be running or
390      *         after the app is restarted (Status does not callback into
391      * Manager).
392      */
393     void occsNotAllRunning();
394 
395     /** @brief Check if all of the OCC Active sensors are available and if not
396      * restart the discoverTimer
397      */
398     void checkAllActiveSensors();
399 #endif // POWER10
400 
401     /**
402      * @brief Called when poll timer expires and forces a POLL command to the
403      * OCC. The poll timer will then be restarted.
404      * */
405     void pollerTimerExpired();
406 
407     /**
408      * @brief Finds the OCC devices in /dev
409      *
410      * @return The IDs of the OCCs - 0, 1, etc.
411      */
412     std::vector<int> findOCCsInDev();
413 
414 #ifdef READ_OCC_SENSORS
415     /**
416      * @brief Gets the occ sensor values.
417      * @param[in] occ - pointer to OCCs Status object
418      * */
419     void getSensorValues(std::unique_ptr<Status>& occ);
420 
421     /**
422      * @brief Trigger OCC driver to read the temperature sensors.
423      * @param[in] path - path of the OCC sensors.
424      * @param[in] id - Id of the OCC.
425      * */
426     void readTempSensors(const fs::path& path, uint32_t id);
427 
428     /**
429      * @brief Trigger OCC driver to read the power sensors.
430      * @param[in] path - path of the OCC sensors.
431      * @param[in] id - Id of the OCC.
432      * */
433     void readPowerSensors(const fs::path& path, uint32_t id);
434 
435     /** @brief Store the existing OCC sensors on D-BUS */
436     std::map<std::string, uint32_t> existingSensors;
437 
438     /** @brief Get FunctionID from the `powerX_label` file.
439      *  @param[in] value - the value of the `powerX_label` file.
440      *  @returns FunctionID of the power sensors.
441      */
442     std::optional<std::string>
443         getPowerLabelFunctionID(const std::string& value);
444 
445     /** @brief The power sensor names map */
446     const std::map<std::string, std::string> powerSensorName = {
447         {"system", "total_power"}, {"1", "p0_mem_power"},
448         {"2", "p1_mem_power"},     {"3", "p2_mem_power"},
449         {"4", "p3_mem_power"},     {"5", "p0_power"},
450         {"6", "p1_power"},         {"7", "p2_power"},
451         {"8", "p3_power"},         {"9", "p0_cache_power"},
452         {"10", "p1_cache_power"},  {"11", "p2_cache_power"},
453         {"12", "p3_cache_power"},  {"13", "io_a_power"},
454         {"14", "io_b_power"},      {"15", "io_c_power"},
455         {"16", "fans_a_power"},    {"17", "fans_b_power"},
456         {"18", "storage_a_power"}, {"19", "storage_b_power"},
457         {"23", "mem_cache_power"}, {"25", "p0_mem_0_power"},
458         {"26", "p0_mem_1_power"},  {"27", "p0_mem_2_power"},
459         {"35", "pcie_dcm0_power"}, {"36", "pcie_dcm1_power"},
460         {"37", "pcie_dcm2_power"}, {"38", "pcie_dcm3_power"},
461         {"39", "io_dcm0_power"},   {"40", "io_dcm1_power"},
462         {"41", "io_dcm2_power"},   {"42", "io_dcm3_power"},
463         {"43", "avdd_total_power"}};
464 
465     /** @brief The dimm temperature sensor names map  */
466     const std::map<uint32_t, std::string> dimmTempSensorName = {
467         {internalMemCtlr, "_intmb_temp"},
468         {dimm, "_dram_temp"},
469         {memCtrlAndDimm, "_dram_extmb_temp"},
470         {PMIC, "_pmic_temp"},
471         {memCtlrExSensor, "_extmb_temp"}};
472 
473     /** @brief The dimm DVFS temperature sensor names map  */
474     const std::map<uint32_t, std::string> dimmDVFSSensorName = {
475         {internalMemCtlr, "dimm_intmb_dvfs_temp"},
476         {dimm, "dimm_dram_dvfs_temp"},
477         {memCtrlAndDimm, "dimm_dram_extmb_dvfs_temp"},
478         {PMIC, "dimm_pmic_dvfs_temp"},
479         {memCtlrExSensor, "dimm_extmb_dvfs_temp"}};
480 #endif
481 
482     /** @brief Read the altitude from DBus */
483     void readAltitude();
484 
485     /** @brief Callback function when ambient temperature changes
486      *
487      *  @param[in]  msg - Data associated with subscribed signal
488      */
489     void ambientCallback(sdbusplus::message_t& msg);
490 
491     /** @brief Confirm that a single OCC master was found and start presence
492      * monitoring
493      */
494     void validateOccMaster();
495 };
496 
497 } // namespace occ
498 } // namespace open_power
499