1 /**
2  * Copyright © 2017 IBM Corporation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <phosphor-logging/log.hpp>
17 #include <phosphor-logging/elog.hpp>
18 #include <xyz/openbmc_project/Sensor/Device/error.hpp>
19 #include <xyz/openbmc_project/Control/Device/error.hpp>
20 #include <xyz/openbmc_project/Power/Fault/error.hpp>
21 #include "elog-errors.hpp"
22 #include "names_values.hpp"
23 #include "power_supply.hpp"
24 #include "pmbus.hpp"
25 #include "utility.hpp"
26 
27 using namespace phosphor::logging;
28 using namespace sdbusplus::xyz::openbmc_project::Control::Device::Error;
29 using namespace sdbusplus::xyz::openbmc_project::Sensor::Device::Error;
30 using namespace sdbusplus::xyz::openbmc_project::Power::Fault::Error;
31 
32 namespace witherspoon
33 {
34 namespace power
35 {
36 namespace psu
37 {
38 
39 constexpr auto INVENTORY_OBJ_PATH = "/xyz/openbmc_project/inventory";
40 constexpr auto INVENTORY_INTERFACE = "xyz.openbmc_project.Inventory.Item";
41 constexpr auto PRESENT_PROP = "Present";
42 constexpr auto POWER_OBJ_PATH = "/org/openbmc/control/power0";
43 constexpr auto POWER_INTERFACE = "org.openbmc.control.Power";
44 
45 PowerSupply::PowerSupply(const std::string& name, size_t inst,
46                          const std::string& objpath,
47                          const std::string& invpath,
48                          sdbusplus::bus::bus& bus,
49                          event::Event& e,
50                          std::chrono::seconds& t)
51     : Device(name, inst), monitorPath(objpath), pmbusIntf(objpath),
52       inventoryPath(invpath), bus(bus), event(e), powerOnInterval(t),
53       powerOnTimer(e, [this]()
54                    {
55                        this->powerOn = true;
56                    })
57 {
58     using namespace sdbusplus::bus;
59     auto present_obj_path = INVENTORY_OBJ_PATH + inventoryPath;
60     presentMatch = std::make_unique<match_t>(bus,
61                                              match::rules::propertiesChanged(
62                                                      present_obj_path,
63                                                      INVENTORY_INTERFACE),
64                                              [this](auto& msg)
65                                              {
66                                                  this->inventoryChanged(msg);
67                                              });
68     // Get initial presence state.
69     updatePresence();
70 
71     // Subscribe to power state changes
72     powerOnMatch = std::make_unique<match_t>(bus,
73                                              match::rules::propertiesChanged(
74                                                      POWER_OBJ_PATH,
75                                                      POWER_INTERFACE),
76                                              [this](auto& msg)
77                                              {
78                                                  this->powerStateChanged(msg);
79                                              });
80     // Get initial power state.
81     updatePowerState();
82 }
83 
84 
85 void PowerSupply::analyze()
86 {
87     using namespace witherspoon::pmbus;
88 
89     try
90     {
91         if (present)
92         {
93             std::uint16_t statusWord = 0;
94             std::uint8_t  statusInput = 0;
95 
96             // Read the 2 byte STATUS_WORD value to check for faults.
97             statusWord = pmbusIntf.read(STATUS_WORD, Type::Debug);
98 
99             //TODO: 3 consecutive reads should be performed.
100             // If 3 consecutive reads are seen, log the fault.
101             // Driver gives cached value, read once a second.
102             // increment for fault on, decrement for fault off, to deglitch.
103             // If count reaches 3, we have fault. If count reaches 0, fault is
104             // cleared.
105 
106             if ((statusWord & status_word::VIN_UV_FAULT) && !vinUVFault)
107             {
108                 vinUVFault = true;
109 
110                 util::NamesValues nv;
111                 nv.add("STATUS_WORD", statusWord);
112 
113                 using metadata = xyz::openbmc_project::Power::Fault::
114                         PowerSupplyUnderVoltageFault;
115 
116                 report<PowerSupplyUnderVoltageFault>(
117                         metadata::RAW_STATUS(nv.get().c_str()));
118 
119                 vinUVFault = true;
120             }
121             else
122             {
123                 vinUVFault = false;
124                 log<level::INFO>("VIN_UV_FAULT cleared",
125                                  entry("POWERSUPPLY=%s",
126                                  inventoryPath.c_str()));
127             }
128 
129             if ((statusWord & status_word::INPUT_FAULT_WARN) && !inputFault)
130             {
131                 inputFault = true;
132 
133                 statusInput = pmbusIntf.read(STATUS_INPUT, Type::Debug);
134 
135                 util::NamesValues nv;
136                 nv.add("STATUS_WORD", statusWord);
137                 nv.add("STATUS_INPUT", statusInput);
138 
139                 using metadata = xyz::openbmc_project::Power::Fault::
140                         PowerSupplyInputFault;
141 
142                 report<PowerSupplyInputFault>(metadata::RAW_STATUS(
143                                                       nv.get().c_str()));
144             }
145             else
146             {
147                 if ((inputFault) &&
148                     !(statusWord & status_word::INPUT_FAULT_WARN))
149                 {
150                     inputFault = false;
151 
152                     statusInput = pmbusIntf.read(STATUS_INPUT, Type::Debug);
153 
154                     log<level::INFO>("INPUT_FAULT_WARN cleared",
155                                      entry("POWERSUPPLY=%s",
156                                              inventoryPath.c_str()),
157                                      entry("STATUS_WORD=0x%04X", statusWord),
158                                      entry("STATUS_INPUT=0x%02X", statusInput));
159                 }
160             }
161 
162             if (powerOn)
163             {
164                 // Check PG# and UNIT_IS_OFF
165                 if (((statusWord & status_word::POWER_GOOD_NEGATED) ||
166                      (statusWord & status_word::UNIT_IS_OFF)) &&
167                     !powerOnFault)
168                 {
169                     std::uint8_t  statusVout = 0;
170                     std::uint8_t  statusIout = 0;
171                     std::uint8_t  statusMFR  = 0;
172 
173                     statusInput = pmbusIntf.read(STATUS_INPUT, Type::Debug);
174                     auto status0Vout = pmbusIntf.insertPageNum(STATUS_VOUT, 0);
175                     statusVout = pmbusIntf.read(status0Vout, Type::Debug);
176                     statusIout = pmbusIntf.read(STATUS_IOUT, Type::Debug);
177                     statusMFR = pmbusIntf.read(STATUS_MFR, Type::Debug);
178 
179                     util::NamesValues nv;
180                     nv.add("STATUS_WORD", statusWord);
181                     nv.add("STATUS_INPUT", statusInput);
182                     nv.add("STATUS_VOUT", statusVout);
183                     nv.add("STATUS_IOUT", statusIout);
184                     nv.add("MFR_SPECIFIC", statusMFR);
185 
186                     using metadata = xyz::openbmc_project::Power::Fault::
187                             PowerSupplyShouldBeOn;
188 
189                     // A power supply is OFF (or pgood low) but should be on.
190                     report<PowerSupplyShouldBeOn>(
191                             metadata::RAW_STATUS(nv.get().c_str()),
192                             metadata::CALLOUT_INVENTORY_PATH(
193                                     inventoryPath.c_str()));
194 
195                     powerOnFault = true;
196                 }
197 
198             }
199         }
200     }
201     catch (ReadFailure& e)
202     {
203         if (!readFailLogged)
204         {
205             commit<ReadFailure>();
206             readFailLogged = true;
207             // TODO - Need to reset that to false at start of power on, or
208             // presence change.
209         }
210     }
211 
212     return;
213 }
214 
215 void PowerSupply::inventoryChanged(sdbusplus::message::message& msg)
216 {
217     std::string msgSensor;
218     std::map<std::string, sdbusplus::message::variant<uint32_t, bool>> msgData;
219     msg.read(msgSensor, msgData);
220 
221     // Check if it was the Present property that changed.
222     auto valPropMap = msgData.find(PRESENT_PROP);
223     if (valPropMap != msgData.end())
224     {
225         present = sdbusplus::message::variant_ns::get<bool>(valPropMap->second);
226 
227         if (present)
228         {
229             readFailLogged = false;
230             vinUVFault = false;
231             inputFault = false;
232         }
233     }
234 
235     return;
236 }
237 
238 void PowerSupply::updatePresence()
239 {
240     // Use getProperty utility function to get presence status.
241     std::string path = INVENTORY_OBJ_PATH + inventoryPath;
242     std::string service = "xyz.openbmc_project.Inventory.Manager";
243 
244     try
245     {
246         util::getProperty(INVENTORY_INTERFACE, PRESENT_PROP, path,
247                           service, bus, this->present);
248     }
249     catch (std::exception& e)
250     {
251         // If we happen to be trying to update presence just as it is being
252         // updated, we may encounter a runtime_error. Just catch that for
253         // now, let the inventoryChanged signal handler update presence later.
254         present = false;
255     }
256 
257 }
258 
259 void PowerSupply::powerStateChanged(sdbusplus::message::message& msg)
260 {
261     int32_t state = 0;
262     std::string msgSensor;
263     std::map<std::string, sdbusplus::message::variant<int32_t, int32_t>>
264             msgData;
265     msg.read(msgSensor, msgData);
266 
267     // Check if it was the Present property that changed.
268     auto valPropMap = msgData.find("state");
269     if (valPropMap != msgData.end())
270     {
271         state = sdbusplus::message::variant_ns::get<int32_t>(valPropMap->second);
272 
273         // Power is on when state=1. Set the fault logged variables to false
274         // and start the power on timer when the state changes to 1.
275         if (state)
276         {
277             readFailLogged = false;
278             vinUVFault = false;
279             inputFault = false;
280             powerOnFault = false;
281             powerOnTimer.start(powerOnInterval, Timer::TimerType::oneshot);
282         }
283         else
284         {
285             powerOnTimer.stop();
286             powerOn = false;
287         }
288     }
289 
290 }
291 
292 void PowerSupply::updatePowerState()
293 {
294     // When state = 1, system is powered on
295     int32_t state = 0;
296 
297     try
298     {
299         auto service = util::getService(POWER_OBJ_PATH,
300                                         POWER_INTERFACE,
301                                         bus);
302 
303         // Use getProperty utility function to get power state.
304         util::getProperty<int32_t>(POWER_INTERFACE,
305                                    "state",
306                                    POWER_OBJ_PATH,
307                                    service,
308                                    bus,
309                                    state);
310 
311         if (state)
312         {
313             powerOn = true;
314         }
315         else
316         {
317             powerOn = false;
318         }
319     }
320     catch (std::exception& e)
321     {
322         log<level::INFO>("Failed to get power state. Assuming it is off.");
323         powerOn = false;
324     }
325 
326 }
327 
328 void PowerSupply::clearFaults()
329 {
330     //TODO - Clear faults at pre-poweron. openbmc/openbmc#1736
331     return;
332 }
333 
334 }
335 }
336 }
337