1 #include <unistd.h>
2 
3 #include <analyzer/analyzer_main.hpp>
4 #include <attn/attn_common.hpp>
5 #include <attn/attn_dbus.hpp>
6 #include <attn/attn_dump.hpp>
7 #include <attn/attn_logging.hpp>
8 #include <attn/pel/pel_minimal.hpp>
9 #include <nlohmann/json.hpp>
10 #include <phosphor-logging/log.hpp>
11 #include <util/dbus.hpp>
12 #include <util/ffdc.hpp>
13 #include <util/trace.hpp>
14 
15 #include <fstream>
16 
17 namespace attn
18 {
19 /** @brief Tuple containing information about ffdc files */
20 using FFDCTuple =
21     std::tuple<util::FFDCFormat, uint8_t, uint8_t, sdbusplus::message::unix_fd>;
22 
23 /**
24  * Create FFDCTuple objects corresponding to the specified FFDC files.
25  *
26  * The D-Bus method to create an error log requires a vector of tuples to
27  * pass in the FFDC file information.
28  *
29  * @param   files - FFDC files
30  * @return  vector of FFDCTuple objects
31  */
32 std::vector<FFDCTuple>
33     createFFDCTuples(const std::vector<util::FFDCFile>& files)
34 {
35     std::vector<FFDCTuple> ffdcTuples{};
36     util::transformFFDC(files, ffdcTuples);
37 
38     return ffdcTuples;
39 }
40 
41 /**
42  * @brief Create an FFDCFile object containing raw data
43  *
44  * Throws an exception if an error occurs.
45  *
46  * @param   i_buffer - raw data to add to ffdc faw data file
47  * @param   i_size - size of the raw data
48  * @return  FFDCFile object
49  */
50 util::FFDCFile createFFDCRawFile(void* i_buffer, size_t i_size)
51 {
52     util::FFDCFile file{util::FFDCFormat::Custom};
53 
54     // Write buffer to file and then reset file description file offset
55     int fd = file.getFileDescriptor();
56     size_t numBytes = write(fd, static_cast<char*>(i_buffer), i_size);
57     if (i_size != numBytes)
58     {
59         trace::err("%s only %u of %u bytes written", file.getPath().c_str(),
60                    numBytes, i_size);
61     }
62 
63     lseek(fd, 0, SEEK_SET);
64 
65     return file;
66 }
67 
68 /**
69  * Create FFDCFile objects containing debug data to store in the error log.
70  *
71  * If an error occurs, the error is written to the journal but an exception
72  * is not thrown.
73  *
74  * @param   i_buffer - raw data (if creating raw dump ffdc entry in log)
75  * @return  vector of FFDCFile objects
76  */
77 std::vector<util::FFDCFile> createFFDCFiles(char* i_buffer = nullptr,
78                                             size_t i_size = 0)
79 {
80     std::vector<util::FFDCFile> files{};
81 
82     // Create raw dump file
83     if ((nullptr != i_buffer) && (0 != i_size))
84     {
85         files.emplace_back(createFFDCRawFile(i_buffer, i_size));
86     }
87 
88     // Create trace dump file
89     util::createFFDCTraceFiles(files);
90 
91     // Add PRD scratch registers
92     addPrdScratchRegs(files);
93 
94     return files;
95 }
96 
97 /**
98  * Create a PEL from an existing PEL
99  *
100  * Create a new PEL based on the specified raw PEL and submit the new PEL
101  * to the backend logging code as a raw PEL. Note that  additional data map
102  * here contains data to be committed to the PEL and it can also be used to
103  * create the PEL as it contains needed information.
104  *
105  * @param   i_rawPel - buffer containing a raw PEL
106  * @param   i_additional - additional data to be added to the new PEL
107  */
108 void createPelCustom(std::vector<uint8_t>& i_rawPel,
109                      std::map<std::string, std::string> i_additional)
110 {
111     // create PEL object from buffer
112     auto tiPel = std::make_unique<pel::PelMinimal>(i_rawPel);
113 
114     // The additional data contains the TI info as well as the value for the
115     // subystem that provided the TI info. Get the subystem from additional
116     // data and then populate the primary SRC and SRC words for the custom PEL
117     // based on the subsystem's TI info.
118     std::map<std::string, std::string>::iterator it;
119     uint8_t subsystem;
120 
121     it = i_additional.find("Subsystem");
122     if (it != i_additional.end())
123     {
124         subsystem = std::stoi(it->second);
125         tiPel->setSubsystem(subsystem);
126     }
127     else
128     {
129         // The entry with key "Subsystem" does not exist in the additional map.
130         // Log the error, create failure event, and return.
131         trace::err("Error the key Subsystem does not exist in the map.");
132         eventAttentionFail((int)AttnSection::attnLogging | ATTN_INVALID_KEY);
133         return;
134     }
135 
136     // If recoverable attentions are active we will call the analyzer and
137     // then link the custom pel to analyzer pel.
138     it = i_additional.find("recoverables");
139     if (it != i_additional.end() && "true" == it->second)
140     {
141         DumpParameters dumpParameters;
142         auto plid = analyzer::analyzeHardware(
143             analyzer::AnalysisType::TERMINATE_IMMEDIATE, dumpParameters);
144         if (0 != plid)
145         {
146             // Link the PLID if an attention was found and a PEL was generated.
147             tiPel->setPlid(plid);
148         }
149     }
150 
151     if (static_cast<uint8_t>(pel::SubsystemID::hypervisor) == subsystem)
152     {
153         // populate hypervisor SRC words
154         tiPel->setSrcWords(std::array<uint32_t, pel::numSrcWords>{
155             (uint32_t)std::stoul(i_additional["0x10 SRC Word 12"], 0, 16),
156             (uint32_t)std::stoul(i_additional["0x14 SRC Word 13"], 0, 16),
157             (uint32_t)std::stoul(i_additional["0x18 SRC Word 14"], 0, 16),
158             (uint32_t)std::stoul(i_additional["0x1c SRC Word 15"], 0, 16),
159             (uint32_t)std::stoul(i_additional["0x20 SRC Word 16"], 0, 16),
160             (uint32_t)std::stoul(i_additional["0x24 SRC Word 17"], 0, 16),
161             (uint32_t)std::stoul(i_additional["0x28 SRC Word 18"], 0, 16),
162             (uint32_t)std::stoul(i_additional["0x2c SRC Word 19"], 0, 16)});
163 
164         // Populate phyp primary SRC
165 
166         // char array for raw pel src
167         std::array<char, pel::asciiStringSize> srcChars{'0'};
168         std::string srcString;
169 
170         // src from TI info
171         it = i_additional.find("SrcAscii");
172         if (it != i_additional.end())
173         {
174             srcString = it->second;
175         }
176         else
177         {
178             // The entry with key "Subsystem" does not exist in the additional
179             // map. Log the error, create failure event, and return.
180             trace::err("Error the key SrcAscii does not exist in the map.");
181             eventAttentionFail((int)AttnSection::attnLogging |
182                                ATTN_INVALID_KEY);
183             return;
184         }
185 
186         // copy from string to char array
187         srcString.copy(srcChars.data(),
188                        std::min(srcString.size(), pel::asciiStringSize), 0);
189 
190         tiPel->setAsciiString(srcChars); // pel object src is char array
191 
192         // set symptom-id
193         auto symptomId = (srcString.substr(0, 8) + '_');
194 
195         symptomId += (i_additional["0x10 SRC Word 12"]);
196         symptomId += (i_additional["0x14 SRC Word 13"] + '_');
197         symptomId += (i_additional["0x18 SRC Word 14"]);
198         symptomId += (i_additional["0x1c SRC Word 15"] + '_');
199         symptomId += (i_additional["0x20 SRC Word 16"]);
200         symptomId += (i_additional["0x24 SRC Word 17"] + '_');
201         symptomId += (i_additional["0x28 SRC Word 18"]);
202         symptomId += (i_additional["0x2c SRC Word 19"]);
203 
204         // setSymptomId will take care of required null-terminate and padding
205         tiPel->setSymptomId(symptomId);
206     }
207     else
208     {
209         // Populate hostboot SRC words - note HB word 0 from the shared info
210         // data (additional data "0x10 HB Word") is reflected in the PEL as
211         // "reason code" so we zero it here. Also note that the first word
212         // in this group of words starts at word 0 and word 1 does not exits.
213         tiPel->setSrcWords(std::array<uint32_t, pel::numSrcWords>{
214             (uint32_t)0x00000000,
215             (uint32_t)std::stoul(i_additional["0x14 HB Word 2"], 0, 16),
216             (uint32_t)std::stoul(i_additional["0x18 HB Word 3"], 0, 16),
217             (uint32_t)std::stoul(i_additional["0x1c HB Word 4"], 0, 16),
218             (uint32_t)std::stoul(i_additional["0x20 HB Word 5"], 0, 16),
219             (uint32_t)std::stoul(i_additional["0x24 HB Word 6"], 0, 16),
220             (uint32_t)std::stoul(i_additional["0x28 HB Word 7"], 0, 16),
221             (uint32_t)std::stoul(i_additional["0x2c HB Word 8"], 0, 16)});
222 
223         // Populate hostboot primary SRC
224 
225         // char array for raw pel src
226         std::array<char, pel::asciiStringSize> srcChars{'0'};
227         std::string srcString;
228 
229         // src from TI info
230         it = i_additional.find("SrcAscii");
231         if (it != i_additional.end())
232         {
233             srcString = it->second;
234         }
235         else
236         {
237             // The entry with key "Subsystem" does not exist in the additional
238             // map. Log the error, create failure event, and return.
239             trace::err("Error the key SrcAscii does not exist in the map.");
240             eventAttentionFail((int)AttnSection::attnLogging |
241                                ATTN_INVALID_KEY);
242             return;
243         }
244 
245         // copy from string to char array
246         srcString.copy(srcChars.data(),
247                        std::min(srcString.size(), pel::asciiStringSize), 0);
248 
249         tiPel->setAsciiString(srcChars); // pel object src is char array
250 
251         // set symptom-id
252         auto symptomId = (srcString.substr(0, 8) + '_');
253 
254         symptomId += (i_additional["0x10 HB Word 0"]);       // note: word 1
255         symptomId += (i_additional["0x14 HB Word 2"] + '_'); // does not exist
256         symptomId += (i_additional["0x18 HB Word 3"]);
257         symptomId += (i_additional["0x1c HB Word 4"] + '_');
258         symptomId += (i_additional["0x20 HB Word 5"]);
259         symptomId += (i_additional["0x24 HB Word 6"] + '_');
260         symptomId += (i_additional["0x28 HB Word 7"]);
261         symptomId += (i_additional["0x2c HB Word 8"]);
262 
263         // setSymptomId will take care of required null-terminate and padding
264         tiPel->setSymptomId(symptomId);
265     }
266 
267     // set severity, event type and action flags
268     tiPel->setSeverity(static_cast<uint8_t>(pel::Severity::termination));
269     tiPel->setType(static_cast<uint8_t>(pel::EventType::na));
270 
271     auto actionFlags = pel::ActionFlags::service | pel::ActionFlags::report |
272                        pel::ActionFlags::call;
273 
274     it = i_additional.find("hidden");
275     if (it != i_additional.end() && "true" == it->second)
276     {
277         trace::inf("making HB TI PEL hidden");
278         actionFlags = actionFlags | pel::ActionFlags::hidden;
279     }
280 
281     tiPel->setAction(static_cast<uint16_t>(actionFlags));
282 
283     // The raw PEL that we used as the basis for this custom PEL contains some
284     // user data sections that do not need to be in this PEL. However we do
285     // want to include the raw TI information.
286     int ffdcCount = 0;
287     it = i_additional.find("FFDC count");
288     if (it != i_additional.end())
289     {
290         // remove all sections except 1 (raw Ti info)
291         ffdcCount = std::stoi(it->second) - 1;
292     }
293     tiPel->setSectionCount(tiPel->getSectionCount() - ffdcCount);
294 
295     // Update the raw PEL with the new custom PEL data
296     tiPel->raw(i_rawPel);
297 
298     // create PEL from raw data
299     createPelRaw(i_rawPel);
300 }
301 
302 /**
303  * Log an event handled by the attention handler
304  *
305  * Basic (non TI) events will generate a standard message-registry based PEL
306  *
307  * TI events will create two PEL's. One PEL will be informational and will
308  * contain trace information relevent to attention handler. The second PEL
309  * will be specific to the TI type (including the primary SRC) and will be
310  * based off of the TI information provided to the attention handler through
311  * shared TI info data area.
312  *
313  * @param  i_event - The event type
314  * @param  i_additional - Additional PEL data
315  * @param  i_ffdc - FFDC PEL data
316  * @param  i_severity - Severity level
317  * @return Event log Id (0 if no event log generated)
318  */
319 uint32_t event(EventType i_event,
320                std::map<std::string, std::string>& i_additional,
321                const std::vector<util::FFDCFile>& i_ffdc,
322                std::string i_severity = levelPelError)
323 {
324     uint32_t pelId = 0;      // assume no event log generated
325 
326     bool eventValid = false; // assume no event created
327     bool tiEvent = false;    // assume not a terminate event
328 
329     // count user data sections so we can fixup custom PEL
330     i_additional["FFDC count"] = std::to_string(i_ffdc.size());
331 
332     std::string eventName;
333 
334     switch (i_event)
335     {
336         case EventType::Checkstop:
337             eventName = "org.open_power.HwDiags.Error.Checkstop";
338             eventValid = true;
339             break;
340         case EventType::Terminate:
341             eventName = "org.open_power.Attn.Error.Terminate";
342             eventValid = true;
343             tiEvent = true;
344             break;
345         case EventType::Vital:
346             eventName = "org.open_power.Attn.Error.Vital";
347             eventValid = true;
348             break;
349         case EventType::HwDiagsFail:
350         case EventType::AttentionFail:
351             eventName = "org.open_power.Attn.Error.Fail";
352             eventValid = true;
353             break;
354         default:
355             eventValid = false;
356             break;
357     }
358 
359     if (true == eventValid)
360     {
361         // Create PEL with additional data and FFDC data. The newly created
362         // PEL's platform log-id will be returned.
363         pelId = util::dbus::createPel(eventName, i_severity, i_additional,
364                                       createFFDCTuples(i_ffdc));
365 
366         // If this is a TI event we will create an additional PEL that is
367         // specific to the subsystem that generated the TI.
368         if ((0 != pelId) && (true == tiEvent))
369         {
370             // get file descriptor and size of information PEL
371             int pelFd = getPel(pelId);
372 
373             // if PEL found, read into buffer
374             if (-1 != pelFd)
375             {
376                 auto pelSize = lseek(pelFd, 0, SEEK_END);
377                 lseek(pelFd, 0, SEEK_SET);
378 
379                 // read information PEL into buffer
380                 std::vector<uint8_t> buffer(pelSize);
381                 size_t numBytes = read(pelFd, buffer.data(), buffer.size());
382                 if (buffer.size() != numBytes)
383                 {
384                     trace::err("Error reading event log: %u of %u bytes read",
385                                numBytes, buffer.size());
386                 }
387                 else
388                 {
389                     // create PEL from buffer
390                     createPelCustom(buffer, i_additional);
391                 }
392 
393                 close(pelFd);
394             }
395 
396             std::map<std::string, std::string>::iterator it;
397             uint8_t subsystem;
398 
399             it = i_additional.find("Subsystem");
400             if (it != i_additional.end())
401             {
402                 subsystem = std::stoi(it->second);
403             }
404             else
405             {
406                 // The entry with key "Subsystem" does not exist in the
407                 // additional map. Log the error, create failure event, and
408                 // return.
409                 trace::err(
410                     "Error the key Subsystem does not exist in the map.");
411                 eventAttentionFail((int)AttnSection::attnLogging |
412                                    ATTN_INVALID_KEY);
413                 return 0;
414             }
415 
416             // If not hypervisor TI
417             if (static_cast<uint8_t>(pel::SubsystemID::hypervisor) != subsystem)
418             {
419                 // Request a dump and transition the host
420                 if ("true" == i_additional["Dump"])
421                 {
422                     // will not return until dump is complete
423                     requestDump(pelId, DumpParameters{0, DumpType::Hostboot});
424                 }
425             }
426         }
427     }
428     return pelId;
429 }
430 
431 /**
432  * Commit special attention TI event to log
433  *
434  * Create a event log with provided additional information and standard
435  * FFDC data plus TI FFDC data
436  *
437  * @param i_additional - Additional log data
438  * @param i_ti_InfoData - TI FFDC data
439  */
440 void eventTerminate(std::map<std::string, std::string> i_additionalData,
441                     char* i_tiInfoData)
442 {
443     uint32_t tiInfoSize = 0; // assume TI info was not available
444 
445     if (nullptr != i_tiInfoData)
446     {
447         tiInfoSize = 56; // assume not hypervisor TI
448 
449         std::map<std::string, std::string>::iterator it;
450         uint8_t subsystem;
451 
452         it = i_additionalData.find("Subsystem");
453         if (it != i_additionalData.end())
454         {
455             subsystem = std::stoi(it->second);
456         }
457         else
458         {
459             // The entry with key "Subsystem" does not exist in the additional
460             // map. Log the error, create failure event, and return.
461             trace::err("Error the key Subsystem does not exist in the map.");
462             eventAttentionFail((int)AttnSection::attnLogging |
463                                ATTN_INVALID_KEY);
464             return;
465         }
466 
467         // If hypervisor
468         if (static_cast<uint8_t>(pel::SubsystemID::hypervisor) == subsystem)
469         {
470             tiInfoSize = 1024; // assume hypervisor max
471 
472             // hypervisor may just want some of the data
473             if (0 == (*(i_tiInfoData + 0x09) & 0x01))
474             {
475                 uint32_t* additionalLength = (uint32_t*)(i_tiInfoData + 0x50);
476                 uint32_t tiAdditional = be32toh(*additionalLength);
477                 tiInfoSize = std::min(tiInfoSize, (84 + tiAdditional));
478             }
479         }
480     }
481 
482     trace::inf("TI info size = %u", tiInfoSize);
483 
484     auto userData = createFFDCFiles(i_tiInfoData, tiInfoSize);
485 
486     // Per request from the Hostboot team. Add a level 2 callout.
487     userData.emplace_back(util::FFDCFormat::JSON, 0xCA, 0x01);
488     std::ofstream o{userData.back().getPath()};
489     o << nlohmann::json::parse(R"(
490         [ { "Procedure": "next_level_support", "Priority": "L" } ]
491     )");
492     o.close();
493 
494     event(EventType::Terminate, i_additionalData, userData);
495 }
496 
497 /** @brief Commit SBE vital event to log, returns event log ID */
498 uint32_t eventVital(std::string severity)
499 {
500     // Additional data for log
501     std::map<std::string, std::string> additionalData;
502 
503     // Create log event with additional data and FFDC data
504     return event(EventType::Vital, additionalData, createFFDCFiles(nullptr, 0),
505                  severity);
506 }
507 
508 /**
509  * Commit attention handler failure event to log
510  *
511  * Create an event log containing the specified error code.
512  *
513  * @param i_error - Error code
514  */
515 void eventAttentionFail(int i_error)
516 {
517     // Additional data for log
518     std::map<std::string, std::string> additionalData;
519     additionalData["ERROR_CODE"] = std::to_string(i_error);
520 
521     // Create log event with additional data and FFDC data
522     event(EventType::AttentionFail, additionalData,
523           createFFDCFiles(nullptr, 0));
524 }
525 
526 } // namespace attn
527