1 /*
2 // Copyright (c) 2019 Intel 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 "post_code.hpp"
17 
18 #include <cereal/access.hpp>
19 #include <cereal/archives/binary.hpp>
20 #include <cereal/cereal.hpp>
21 #include <cereal/types/map.hpp>
22 #include <cereal/types/tuple.hpp>
23 #include <cereal/types/vector.hpp>
24 
25 #include <iomanip>
26 
27 const static constexpr auto timeoutMicroSeconds = 1000000;
28 
29 void PostCode::deleteAll()
30 {
31     std::uintmax_t n = fs::remove_all(postCodeListPath);
32     std::cerr << "clearPostCodes deleted " << n << " files in "
33               << postCodeListPath << std::endl;
34     fs::create_directories(postCodeListPath);
35     postCodes.clear();
36     currentBootCycleIndex = 0;
37     currentBootCycleCount(0);
38 }
39 
40 std::vector<postcode_t> PostCode::getPostCodes(uint16_t index)
41 {
42     std::vector<postcode_t> codesVec;
43     if (1 == index && !postCodes.empty())
44     {
45         std::transform(postCodes.begin(), postCodes.end(),
46                        std::back_inserter(codesVec),
47                        [](const auto& kv) { return kv.second; });
48     }
49     else
50     {
51         uint16_t bootNum = getBootNum(index);
52 
53         decltype(postCodes) codes;
54         deserializePostCodes(postCodeListPath / std::to_string(bootNum), codes);
55         std::transform(codes.begin(), codes.end(), std::back_inserter(codesVec),
56                        [](const auto& kv) { return kv.second; });
57     }
58     return codesVec;
59 }
60 
61 std::map<uint64_t, postcode_t>
62     PostCode::getPostCodesWithTimeStamp(uint16_t index)
63 {
64     if (1 == index && !postCodes.empty())
65     {
66         return postCodes;
67     }
68 
69     uint16_t bootNum = getBootNum(index);
70     decltype(postCodes) codes;
71     deserializePostCodes(postCodeListPath / std::to_string(bootNum), codes);
72     return codes;
73 }
74 
75 void PostCode::savePostCodes(postcode_t code)
76 {
77     if (!timer)
78     {
79         timer = std::make_unique<sdbusplus::Timer>(
80             event.get(), [this]() { serialize(postCodeListPath); });
81     }
82 
83     // steady_clock is a monotonic clock that is guaranteed to never be adjusted
84     auto postCodeTimeSteady = std::chrono::steady_clock::now();
85     uint64_t tsUS = std::chrono::duration_cast<std::chrono::microseconds>(
86                         std::chrono::system_clock::now().time_since_epoch())
87                         .count();
88 
89     if (postCodes.empty())
90     {
91         firstPostCodeTimeSteady = postCodeTimeSteady;
92         firstPostCodeUsSinceEpoch = tsUS; // uS since epoch for 1st post code
93         incrBootCycle();
94     }
95     else
96     {
97         // calculating tsUS so it is monotonic within the same boot
98         tsUS = firstPostCodeUsSinceEpoch +
99                std::chrono::duration_cast<std::chrono::microseconds>(
100                    postCodeTimeSteady - firstPostCodeTimeSteady)
101                    .count();
102     }
103 
104     postCodes.insert(std::make_pair(tsUS, code));
105     if (postCodes.size() > MAX_POST_CODE_SIZE_PER_CYCLE)
106     {
107         postCodes.erase(postCodes.begin());
108     }
109 
110     if (!timer->isRunning())
111     {
112         timer->start(std::chrono::microseconds(timeoutMicroSeconds));
113     }
114 
115     if (strlen(POSTCODE_DISPLAY_PATH) > 0)
116     {
117         std::string postCodeDisplayPath = POSTCODE_DISPLAY_PATH +
118                                           std::to_string(node);
119 
120         std::ofstream postCodeDisplayFile(postCodeDisplayPath);
121         postCodeDisplayFile << "0x" << std::setfill('0') << std::setw(2)
122                             << std::hex << std::get<0>(code);
123         postCodeDisplayFile.close();
124     }
125 
126 #ifdef ENABLE_BIOS_POST_CODE_LOG
127     uint64_t usTimeOffset = tsUS - firstPostCodeUsSinceEpoch;
128     std::ostringstream hexCode;
129     hexCode << "0x" << std::setfill('0') << std::setw(2) << std::hex
130             << std::get<0>(code);
131 
132     std::ostringstream timeOffsetStr;
133     // Set Fixed-Point Notation
134     timeOffsetStr << std::fixed;
135     // Set precision to 4 digits
136     timeOffsetStr << std::setprecision(4);
137     // Add double to stream
138     timeOffsetStr << static_cast<double>(usTimeOffset) / 1000 / 1000;
139 
140     phosphor::logging::log<phosphor::logging::level::INFO>(
141         "BIOS POST Code",
142         phosphor::logging::entry("REDFISH_MESSAGE_ID=%s",
143                                  "OpenBMC.0.2.BIOSPOSTCode"),
144         phosphor::logging::entry(
145             "REDFISH_MESSAGE_ARGS=%d,%s,%s", currentBootCycleIndex,
146             timeOffsetStr.str().c_str(), hexCode.str().c_str()));
147 #endif
148 
149     return;
150 }
151 
152 fs::path PostCode::serialize(const fs::path& path)
153 {
154     try
155     {
156         std::ofstream osIdx(path / CurrentBootCycleIndexName, std::ios::binary);
157         cereal::BinaryOutputArchive idxArchive(osIdx);
158         idxArchive(currentBootCycleIndex);
159 
160         uint16_t count = currentBootCycleCount();
161         std::ofstream osCnt(path / CurrentBootCycleCountName, std::ios::binary);
162         cereal::BinaryOutputArchive cntArchive(osCnt);
163         cntArchive(count);
164 
165         std::ofstream osPostCodes(path / std::to_string(currentBootCycleIndex));
166         cereal::BinaryOutputArchive oarchivePostCodes(osPostCodes);
167         oarchivePostCodes(postCodes);
168     }
169     catch (const cereal::Exception& e)
170     {
171         phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
172         return "";
173     }
174     catch (const fs::filesystem_error& e)
175     {
176         phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
177         return "";
178     }
179     return path;
180 }
181 
182 bool PostCode::deserialize(const fs::path& path, uint16_t& index)
183 {
184     try
185     {
186         if (fs::exists(path))
187         {
188             std::ifstream is(path, std::ios::in | std::ios::binary);
189             cereal::BinaryInputArchive iarchive(is);
190             iarchive(index);
191             return true;
192         }
193         return false;
194     }
195     catch (const cereal::Exception& e)
196     {
197         phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
198         return false;
199     }
200     catch (const fs::filesystem_error& e)
201     {
202         return false;
203     }
204 
205     return false;
206 }
207 
208 bool PostCode::deserializePostCodes(const fs::path& path,
209                                     std::map<uint64_t, postcode_t>& codes)
210 {
211     try
212     {
213         if (fs::exists(path))
214         {
215             std::ifstream is(path, std::ios::in | std::ios::binary);
216             cereal::BinaryInputArchive iarchive(is);
217             iarchive(codes);
218             return true;
219         }
220         return false;
221     }
222     catch (const cereal::Exception& e)
223     {
224         phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
225         return false;
226     }
227     catch (const fs::filesystem_error& e)
228     {
229         return false;
230     }
231     return false;
232 }
233 
234 void PostCode::incrBootCycle()
235 {
236     if (currentBootCycleIndex >= maxBootCycleNum())
237     {
238         currentBootCycleIndex = 1;
239     }
240     else
241     {
242         currentBootCycleIndex++;
243     }
244     currentBootCycleCount(std::min(
245         maxBootCycleNum(), static_cast<uint16_t>(currentBootCycleCount() + 1)));
246 }
247 
248 uint16_t PostCode::getBootNum(const uint16_t index) const
249 {
250     // bootNum assumes the oldest archive is boot number 1
251     // and the current boot number equals bootCycleCount
252     // map bootNum back to bootIndex that was used to archive postcode
253     uint16_t bootNum = currentBootCycleIndex;
254     if (index > bootNum) // need to wrap around
255     {
256         bootNum = (maxBootCycleNum() + currentBootCycleIndex) - index + 1;
257     }
258     else
259     {
260         bootNum = currentBootCycleIndex - index + 1;
261     }
262     return bootNum;
263 }
264