-
Notifications
You must be signed in to change notification settings - Fork 10
/
apphandler.cpp
1806 lines (1633 loc) · 63 KB
/
apphandler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "config.h"
#include <arpa/inet.h>
#include <fcntl.h>
#include <limits.h>
#include <linux/i2c-dev.h>
#include <linux/i2c.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <systemd/sd-bus.h>
#include <unistd.h>
#include <app/channel.hpp>
#include <app/watchdog.hpp>
#include <apphandler.hpp>
#include <ipmid/api.hpp>
#include <ipmid/sessiondef.hpp>
#include <ipmid/sessionhelper.hpp>
#include <ipmid/types.hpp>
#include <ipmid/utils.hpp>
#include <nlohmann/json.hpp>
#include <phosphor-logging/elog-errors.hpp>
#include <phosphor-logging/lg2.hpp>
#include <sdbusplus/message/types.hpp>
#include <sys_info_param.hpp>
#include <xyz/openbmc_project/Common/error.hpp>
#include <xyz/openbmc_project/Control/Power/ACPIPowerState/server.hpp>
#include <xyz/openbmc_project/Software/Activation/server.hpp>
#include <xyz/openbmc_project/Software/Version/server.hpp>
#include <xyz/openbmc_project/State/BMC/server.hpp>
#include <algorithm>
#include <array>
#include <charconv>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <memory>
#include <regex>
#include <string>
#include <string_view>
#include <tuple>
#include <vector>
extern sd_bus* bus;
constexpr auto bmc_state_interface = "xyz.openbmc_project.State.BMC";
constexpr auto bmc_state_property = "CurrentBMCState";
static constexpr auto redundancyIntf =
"xyz.openbmc_project.Software.RedundancyPriority";
static constexpr auto versionIntf = "xyz.openbmc_project.Software.Version";
static constexpr auto activationIntf =
"xyz.openbmc_project.Software.Activation";
static constexpr auto softwareRoot = "/xyz/openbmc_project/software";
void register_netfn_app_functions() __attribute__((constructor));
using namespace phosphor::logging;
using namespace sdbusplus::error::xyz::openbmc_project::common;
using Version = sdbusplus::server::xyz::openbmc_project::software::Version;
using Activation =
sdbusplus::server::xyz::openbmc_project::software::Activation;
using BMC = sdbusplus::server::xyz::openbmc_project::state::BMC;
namespace fs = std::filesystem;
#ifdef ENABLE_I2C_WHITELIST_CHECK
typedef struct
{
uint8_t busId;
uint8_t targetAddr;
uint8_t targetAddrMask;
std::vector<uint8_t> data;
std::vector<uint8_t> dataMask;
} i2cControllerWRAllowlist;
static std::vector<i2cControllerWRAllowlist>& getWRAllowlist()
{
static std::vector<i2cControllerWRAllowlist> wrAllowlist;
return wrAllowlist;
}
static constexpr const char* i2cControllerWRAllowlistFile =
"/usr/share/ipmi-providers/master_write_read_white_list.json";
static constexpr const char* filtersStr = "filters";
static constexpr const char* busIdStr = "busId";
static constexpr const char* targetAddrStr = "slaveAddr";
static constexpr const char* targetAddrMaskStr = "slaveAddrMask";
static constexpr const char* cmdStr = "command";
static constexpr const char* cmdMaskStr = "commandMask";
static constexpr int base_16 = 16;
#endif // ENABLE_I2C_WHITELIST_CHECK
static constexpr uint8_t oemCmdStart = 192;
static constexpr uint8_t invalidParamSelectorStart = 8;
static constexpr uint8_t invalidParamSelectorEnd = 191;
/**
* @brief Returns the Version info from primary s/w object
*
* Get the Version info from the active s/w object which is having high
* "Priority" value(a smaller number is a higher priority) and "Purpose"
* is "BMC" from the list of all s/w objects those are implementing
* RedundancyPriority interface from the given softwareRoot path.
*
* @return On success returns the Version info from primary s/w object.
*
*/
std::string getActiveSoftwareVersionInfo(ipmi::Context::ptr ctx)
{
std::string revision{};
ipmi::ObjectTree objectTree;
try
{
objectTree =
ipmi::getAllDbusObjects(*ctx->bus, softwareRoot, redundancyIntf);
}
catch (const sdbusplus::exception_t& e)
{
lg2::error("Failed to fetch redundancy object from dbus, "
"interface: {INTERFACE}, error: {ERROR}",
"INTERFACE", redundancyIntf, "ERROR", e);
elog<InternalFailure>();
}
auto objectFound = false;
for (auto& softObject : objectTree)
{
auto service =
ipmi::getService(*ctx->bus, redundancyIntf, softObject.first);
auto objValueTree =
ipmi::getManagedObjects(*ctx->bus, service, softwareRoot);
auto minPriority = 0xFF;
for (const auto& objIter : objValueTree)
{
try
{
auto& intfMap = objIter.second;
auto& redundancyPriorityProps = intfMap.at(redundancyIntf);
auto& versionProps = intfMap.at(versionIntf);
auto& activationProps = intfMap.at(activationIntf);
auto priority =
std::get<uint8_t>(redundancyPriorityProps.at("Priority"));
auto purpose =
std::get<std::string>(versionProps.at("Purpose"));
auto activation =
std::get<std::string>(activationProps.at("Activation"));
auto version =
std::get<std::string>(versionProps.at("Version"));
if ((Version::convertVersionPurposeFromString(purpose) ==
Version::VersionPurpose::BMC) &&
(Activation::convertActivationsFromString(activation) ==
Activation::Activations::Active))
{
if (priority < minPriority)
{
minPriority = priority;
objectFound = true;
revision = std::move(version);
}
}
}
catch (const std::exception& e)
{
lg2::error("error message: {ERROR}", "ERROR", e);
}
}
}
if (!objectFound)
{
lg2::error("Could not found an BMC software Object");
elog<InternalFailure>();
}
return revision;
}
bool getCurrentBmcState()
{
sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
// Get the Inventory object implementing the BMC interface
ipmi::DbusObjectInfo bmcObject =
ipmi::getDbusObject(bus, bmc_state_interface);
auto variant =
ipmi::getDbusProperty(bus, bmcObject.second, bmcObject.first,
bmc_state_interface, bmc_state_property);
return std::holds_alternative<std::string>(variant) &&
BMC::convertBMCStateFromString(std::get<std::string>(variant)) ==
BMC::BMCState::Ready;
}
bool getCurrentBmcStateWithFallback(const bool fallbackAvailability)
{
try
{
return getCurrentBmcState();
}
catch (...)
{
// Nothing provided the BMC interface, therefore return whatever was
// configured as the default.
return fallbackAvailability;
}
}
namespace acpi_state
{
using namespace sdbusplus::server::xyz::openbmc_project::control::power;
const static constexpr char* acpiInterface =
"xyz.openbmc_project.Control.Power.ACPIPowerState";
const static constexpr char* sysACPIProp = "SysACPIStatus";
const static constexpr char* devACPIProp = "DevACPIStatus";
enum class PowerStateType : uint8_t
{
sysPowerState = 0x00,
devPowerState = 0x01,
};
// Defined in 20.6 of ipmi doc
enum class PowerState : uint8_t
{
s0G0D0 = 0x00,
s1D1 = 0x01,
s2D2 = 0x02,
s3D3 = 0x03,
s4 = 0x04,
s5G2 = 0x05,
s4S5 = 0x06,
g3 = 0x07,
sleep = 0x08,
g1Sleep = 0x09,
override = 0x0a,
legacyOn = 0x20,
legacyOff = 0x21,
unknown = 0x2a,
noChange = 0x7f,
};
static constexpr uint8_t stateChanged = 0x80;
std::map<ACPIPowerState::ACPI, PowerState> dbusToIPMI = {
{ACPIPowerState::ACPI::S0_G0_D0, PowerState::s0G0D0},
{ACPIPowerState::ACPI::S1_D1, PowerState::s1D1},
{ACPIPowerState::ACPI::S2_D2, PowerState::s2D2},
{ACPIPowerState::ACPI::S3_D3, PowerState::s3D3},
{ACPIPowerState::ACPI::S4, PowerState::s4},
{ACPIPowerState::ACPI::S5_G2, PowerState::s5G2},
{ACPIPowerState::ACPI::S4_S5, PowerState::s4S5},
{ACPIPowerState::ACPI::G3, PowerState::g3},
{ACPIPowerState::ACPI::SLEEP, PowerState::sleep},
{ACPIPowerState::ACPI::G1_SLEEP, PowerState::g1Sleep},
{ACPIPowerState::ACPI::OVERRIDE, PowerState::override},
{ACPIPowerState::ACPI::LEGACY_ON, PowerState::legacyOn},
{ACPIPowerState::ACPI::LEGACY_OFF, PowerState::legacyOff},
{ACPIPowerState::ACPI::Unknown, PowerState::unknown}};
bool isValidACPIState(acpi_state::PowerStateType type, uint8_t state)
{
if (type == acpi_state::PowerStateType::sysPowerState)
{
if ((state <= static_cast<uint8_t>(acpi_state::PowerState::override)) ||
(state == static_cast<uint8_t>(acpi_state::PowerState::legacyOn)) ||
(state ==
static_cast<uint8_t>(acpi_state::PowerState::legacyOff)) ||
(state == static_cast<uint8_t>(acpi_state::PowerState::unknown)) ||
(state == static_cast<uint8_t>(acpi_state::PowerState::noChange)))
{
return true;
}
else
{
return false;
}
}
else if (type == acpi_state::PowerStateType::devPowerState)
{
if ((state <= static_cast<uint8_t>(acpi_state::PowerState::s3D3)) ||
(state == static_cast<uint8_t>(acpi_state::PowerState::unknown)) ||
(state == static_cast<uint8_t>(acpi_state::PowerState::noChange)))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
return false;
}
} // namespace acpi_state
/** @brief implements Set ACPI Power State command
* @param sysAcpiState - ACPI system power state to set
* @param devAcpiState - ACPI device power state to set
*
* @return IPMI completion code on success
**/
ipmi::RspType<> ipmiSetAcpiPowerState(uint8_t sysAcpiState,
uint8_t devAcpiState)
{
auto s = static_cast<uint8_t>(acpi_state::PowerState::unknown);
sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
auto value = acpi_state::ACPIPowerState::ACPI::Unknown;
if (sysAcpiState & acpi_state::stateChanged)
{
// set system power state
s = sysAcpiState & ~acpi_state::stateChanged;
if (!acpi_state::isValidACPIState(
acpi_state::PowerStateType::sysPowerState, s))
{
lg2::error("set_acpi_power sys invalid input, S: {S}", "S", s);
return ipmi::responseParmOutOfRange();
}
// valid input
if (s == static_cast<uint8_t>(acpi_state::PowerState::noChange))
{
lg2::debug("No change for system power state");
}
else
{
auto found = std::find_if(
acpi_state::dbusToIPMI.begin(), acpi_state::dbusToIPMI.end(),
[&s](const auto& iter) {
return (static_cast<uint8_t>(iter.second) == s);
});
value = found->first;
try
{
auto acpiObject =
ipmi::getDbusObject(bus, acpi_state::acpiInterface);
ipmi::setDbusProperty(bus, acpiObject.second, acpiObject.first,
acpi_state::acpiInterface,
acpi_state::sysACPIProp,
convertForMessage(value));
}
catch (const InternalFailure& e)
{
lg2::error("Failed in set ACPI system property: {ERROR}",
"ERROR", e);
return ipmi::responseUnspecifiedError();
}
}
}
else
{
lg2::debug("Do not change system power state");
}
if (devAcpiState & acpi_state::stateChanged)
{
// set device power state
s = devAcpiState & ~acpi_state::stateChanged;
if (!acpi_state::isValidACPIState(
acpi_state::PowerStateType::devPowerState, s))
{
lg2::error("set_acpi_power dev invalid input, S: {S}", "S", s);
return ipmi::responseParmOutOfRange();
}
// valid input
if (s == static_cast<uint8_t>(acpi_state::PowerState::noChange))
{
lg2::debug("No change for device power state");
}
else
{
auto found = std::find_if(
acpi_state::dbusToIPMI.begin(), acpi_state::dbusToIPMI.end(),
[&s](const auto& iter) {
return (static_cast<uint8_t>(iter.second) == s);
});
value = found->first;
try
{
auto acpiObject =
ipmi::getDbusObject(bus, acpi_state::acpiInterface);
ipmi::setDbusProperty(bus, acpiObject.second, acpiObject.first,
acpi_state::acpiInterface,
acpi_state::devACPIProp,
convertForMessage(value));
}
catch (const InternalFailure& e)
{
lg2::error("Failed in set ACPI device property: {ERROR}",
"ERROR", e);
return ipmi::responseUnspecifiedError();
}
}
}
else
{
lg2::debug("Do not change device power state");
}
return ipmi::responseSuccess();
}
/**
* @brief implements the get ACPI power state command
*
* @return IPMI completion code plus response data on success.
* - ACPI system power state
* - ACPI device power state
**/
ipmi::RspType<uint8_t, // acpiSystemPowerState
uint8_t // acpiDevicePowerState
>
ipmiGetAcpiPowerState()
{
uint8_t sysAcpiState;
uint8_t devAcpiState;
sdbusplus::bus_t bus{ipmid_get_sd_bus_connection()};
try
{
auto acpiObject = ipmi::getDbusObject(bus, acpi_state::acpiInterface);
auto sysACPIVal = ipmi::getDbusProperty(
bus, acpiObject.second, acpiObject.first, acpi_state::acpiInterface,
acpi_state::sysACPIProp);
auto sysACPI = acpi_state::ACPIPowerState::convertACPIFromString(
std::get<std::string>(sysACPIVal));
sysAcpiState = static_cast<uint8_t>(acpi_state::dbusToIPMI.at(sysACPI));
auto devACPIVal = ipmi::getDbusProperty(
bus, acpiObject.second, acpiObject.first, acpi_state::acpiInterface,
acpi_state::devACPIProp);
auto devACPI = acpi_state::ACPIPowerState::convertACPIFromString(
std::get<std::string>(devACPIVal));
devAcpiState = static_cast<uint8_t>(acpi_state::dbusToIPMI.at(devACPI));
}
catch (const InternalFailure& e)
{
return ipmi::responseUnspecifiedError();
}
return ipmi::responseSuccess(sysAcpiState, devAcpiState);
}
typedef struct
{
char major;
char minor;
uint8_t aux[4];
} Revision;
/* Use regular expression searching matched pattern X.Y, and convert it to */
/* Major (X) and Minor (Y) version. */
/* Example: */
/* version = 2.14.0-dev */
/* ^ ^ */
/* | |---------------- Minor */
/* |------------------ Major */
/* */
/* Default regex string only tries to match Major and Minor version. */
/* */
/* To match more firmware version info, platforms need to define it own */
/* regex string to match more strings, and assign correct mapping index in */
/* matches array. */
/* */
/* matches[0]: matched index for major ver */
/* matches[1]: matched index for minor ver */
/* matches[2]: matched index for aux[0] (set 0 to skip) */
/* matches[3]: matched index for aux[1] (set 0 to skip) */
/* matches[4]: matched index for aux[2] (set 0 to skip) */
/* matches[5]: matched index for aux[3] (set 0 to skip) */
/* Example: */
/* regex = "([\d]+).([\d]+).([\d]+)-dev-([\d]+)-g([0-9a-fA-F]{2}) */
/* ([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})" */
/* matches = {1,2,5,6,7,8} */
/* version = 2.14.0-dev-750-g37a7c5ad1-dirty */
/* ^ ^ ^ ^ ^ ^ ^ ^ */
/* | | | | | | | | */
/* | | | | | | | |-- Aux byte 3 (0xAD), index 8 */
/* | | | | | | |---- Aux byte 2 (0xC5), index 7 */
/* | | | | | |------ Aux byte 1 (0xA7), index 6 */
/* | | | | |-------- Aux byte 0 (0x37), index 5 */
/* | | | |------------- Not used, index 4 */
/* | | |------------------- Not used, index 3 */
/* | |---------------------- Minor (14), index 2 */
/* |------------------------ Major (2), index 1 */
int convertVersion(std::string s, Revision& rev)
{
static const std::vector<size_t> matches = {
MAJOR_MATCH_INDEX, MINOR_MATCH_INDEX, AUX_0_MATCH_INDEX,
AUX_1_MATCH_INDEX, AUX_2_MATCH_INDEX, AUX_3_MATCH_INDEX};
std::regex fw_regex(FW_VER_REGEX);
std::smatch m;
Revision r = {0};
size_t val;
if (std::regex_search(s, m, fw_regex))
{
if (m.size() < *std::max_element(matches.begin(), matches.end()))
{ // max index higher than match count
return -1;
}
// convert major
{
std::string_view str = m[matches[0]].str();
auto [ptr, ec]{std::from_chars(str.begin(), str.end(), val)};
if (ec != std::errc() || ptr != str.begin() + str.size())
{ // failed to convert major string
return -1;
}
if (val >= 2000)
{ // For the platforms use year as major version, it would expect to
// have major version between 0 - 99. If the major version is
// greater than or equal to 2000, it is treated as a year and
// converted to 0 - 99.
r.major = val % 100;
}
else
{
r.major = val & 0x7F;
}
}
// convert minor
{
std::string_view str = m[matches[1]].str();
auto [ptr, ec]{std::from_chars(str.begin(), str.end(), val)};
if (ec != std::errc() || ptr != str.begin() + str.size())
{ // failed to convert minor string
return -1;
}
r.minor = val & 0xFF;
}
// convert aux bytes
{
size_t i;
for (i = 0; i < 4; i++)
{
if (matches[i + 2] == 0)
{
continue;
}
std::string_view str = m[matches[i + 2]].str();
auto [ptr,
ec]{std::from_chars(str.begin(), str.end(), val, 16)};
if (ec != std::errc() || ptr != str.begin() + str.size())
{ // failed to convert aux byte string
break;
}
r.aux[i] = val & 0xFF;
}
if (i != 4)
{ // something wrong durign converting aux bytes
return -1;
}
}
// all matched
rev = r;
return 0;
}
return -1;
}
/* @brief: Implement the Get Device ID IPMI command per the IPMI spec
* @param[in] ctx - shared_ptr to an IPMI context struct
*
* @returns IPMI completion code plus response data
* - Device ID (manufacturer defined)
* - Device revision[4 bits]; reserved[3 bits]; SDR support[1 bit]
* - FW revision major[7 bits] (binary encoded); available[1 bit]
* - FW Revision minor (BCD encoded)
* - IPMI version (0x02 for IPMI 2.0)
* - device support (bitfield of supported options)
* - MFG IANA ID (3 bytes)
* - product ID (2 bytes)
* - AUX info (4 bytes)
*/
ipmi::RspType<uint8_t, // Device ID
uint8_t, // Device Revision
uint8_t, // Firmware Revision Major
uint8_t, // Firmware Revision minor
uint8_t, // IPMI version
uint8_t, // Additional device support
uint24_t, // MFG ID
uint16_t, // Product ID
uint32_t // AUX info
>
ipmiAppGetDeviceId([[maybe_unused]] ipmi::Context::ptr ctx)
{
static struct
{
uint8_t id;
uint8_t revision;
uint8_t fw[2];
uint8_t ipmiVer;
uint8_t addnDevSupport;
uint24_t manufId;
uint16_t prodId;
uint32_t aux;
} devId;
static bool dev_id_initialized = false;
static bool defaultActivationSetting = true;
const char* filename = "/usr/share/ipmi-providers/dev_id.json";
constexpr auto ipmiDevIdStateShift = 7;
constexpr auto ipmiDevIdFw1Mask = ~(1 << ipmiDevIdStateShift);
#ifdef GET_DBUS_ACTIVE_SOFTWARE
static bool haveBMCVersion = false;
if (!haveBMCVersion || !dev_id_initialized)
{
int r = -1;
Revision rev = {0, 0, 0, 0};
try
{
auto version = getActiveSoftwareVersionInfo(ctx);
r = convertVersion(version, rev);
}
catch (const std::exception& e)
{
lg2::error("error message: {ERROR}", "ERROR", e);
}
if (r >= 0)
{
// bit7 identifies if the device is available
// 0=normal operation
// 1=device firmware, SDR update,
// or self-initialization in progress.
// The availability may change in run time, so mask here
// and initialize later.
devId.fw[0] = rev.major & ipmiDevIdFw1Mask;
rev.minor = (rev.minor > 99 ? 99 : rev.minor);
devId.fw[1] = rev.minor % 10 + (rev.minor / 10) * 16;
std::memcpy(&devId.aux, rev.aux, sizeof(rev.aux));
haveBMCVersion = true;
}
}
#endif
if (!dev_id_initialized)
{
// IPMI Spec version 2.0
devId.ipmiVer = 2;
std::ifstream devIdFile(filename);
if (devIdFile.is_open())
{
auto data = nlohmann::json::parse(devIdFile, nullptr, false);
if (!data.is_discarded())
{
devId.id = data.value("id", 0);
devId.revision = data.value("revision", 0);
devId.addnDevSupport = data.value("addn_dev_support", 0);
devId.manufId = data.value("manuf_id", 0);
devId.prodId = data.value("prod_id", 0);
#ifdef GET_DBUS_ACTIVE_SOFTWARE
if (!(AUX_0_MATCH_INDEX || AUX_1_MATCH_INDEX ||
AUX_2_MATCH_INDEX || AUX_3_MATCH_INDEX))
#endif
{
devId.aux = data.value("aux", 0);
}
if (data.contains("firmware_revision"))
{
const auto& firmwareRevision = data.at("firmware_revision");
if (firmwareRevision.contains("major"))
{
firmwareRevision.at("major").get_to(devId.fw[0]);
}
if (firmwareRevision.contains("minor"))
{
firmwareRevision.at("minor").get_to(devId.fw[1]);
}
}
// Set the availablitity of the BMC.
defaultActivationSetting = data.value("availability", true);
// Don't read the file every time if successful
dev_id_initialized = true;
}
else
{
lg2::error("Device ID JSON parser failure");
return ipmi::responseUnspecifiedError();
}
}
else
{
lg2::error("Device ID file not found");
return ipmi::responseUnspecifiedError();
}
}
// Set availability to the actual current BMC state
devId.fw[0] &= ipmiDevIdFw1Mask;
if (!getCurrentBmcStateWithFallback(defaultActivationSetting))
{
devId.fw[0] |= (1 << ipmiDevIdStateShift);
}
return ipmi::responseSuccess(
devId.id, devId.revision, devId.fw[0], devId.fw[1], devId.ipmiVer,
devId.addnDevSupport, devId.manufId, devId.prodId, devId.aux);
}
auto ipmiAppGetSelfTestResults() -> ipmi::RspType<uint8_t, uint8_t>
{
// Byte 2:
// 55h - No error.
// 56h - Self Test function not implemented in this controller.
// 57h - Corrupted or inaccesssible data or devices.
// 58h - Fatal hardware error.
// FFh - reserved.
// all other: Device-specific 'internal failure'.
// Byte 3:
// For byte 2 = 55h, 56h, FFh: 00h
// For byte 2 = 58h, all other: Device-specific
// For byte 2 = 57h: self-test error bitfield.
// Note: returning 57h does not imply that all test were run.
// [7] 1b = Cannot access SEL device.
// [6] 1b = Cannot access SDR Repository.
// [5] 1b = Cannot access BMC FRU device.
// [4] 1b = IPMB signal lines do not respond.
// [3] 1b = SDR Repository empty.
// [2] 1b = Internal Use Area of BMC FRU corrupted.
// [1] 1b = controller update 'boot block' firmware corrupted.
// [0] 1b = controller operational firmware corrupted.
constexpr uint8_t notImplemented = 0x56;
constexpr uint8_t zero = 0;
return ipmi::responseSuccess(notImplemented, zero);
}
static constexpr size_t uuidBinaryLength = 16;
static std::array<uint8_t, uuidBinaryLength> rfc4122ToIpmi(std::string rfc4122)
{
using Argument = xyz::openbmc_project::common::InvalidArgument;
// UUID is in RFC4122 format. Ex: 61a39523-78f2-11e5-9862-e6402cfc3223
// Per IPMI Spec 2.0 need to convert to 16 hex bytes and reverse the byte
// order
// Ex: 0x2332fc2c40e66298e511f2782395a361
constexpr size_t uuidHexLength = (2 * uuidBinaryLength);
constexpr size_t uuidRfc4122Length = (uuidHexLength + 4);
std::array<uint8_t, uuidBinaryLength> uuid;
if (rfc4122.size() == uuidRfc4122Length)
{
rfc4122.erase(std::remove(rfc4122.begin(), rfc4122.end(), '-'),
rfc4122.end());
}
if (rfc4122.size() != uuidHexLength)
{
elog<InvalidArgument>(Argument::ARGUMENT_NAME("rfc4122"),
Argument::ARGUMENT_VALUE(rfc4122.c_str()));
}
for (size_t ind = 0; ind < uuidHexLength; ind += 2)
{
char v[3];
v[0] = rfc4122[ind];
v[1] = rfc4122[ind + 1];
v[2] = 0;
size_t err;
long b;
try
{
b = std::stoul(v, &err, 16);
}
catch (const std::exception& e)
{
elog<InvalidArgument>(Argument::ARGUMENT_NAME("rfc4122"),
Argument::ARGUMENT_VALUE(rfc4122.c_str()));
}
// check that exactly two ascii bytes were converted
if (err != 2)
{
elog<InvalidArgument>(Argument::ARGUMENT_NAME("rfc4122"),
Argument::ARGUMENT_VALUE(rfc4122.c_str()));
}
uuid[uuidBinaryLength - (ind / 2) - 1] = static_cast<uint8_t>(b);
}
return uuid;
}
auto ipmiAppGetDeviceGuid()
-> ipmi::RspType<std::array<uint8_t, uuidBinaryLength>>
{
// return a fixed GUID based on /etc/machine-id
// This should match the /redfish/v1/Managers/bmc's UUID data
// machine specific application ID (for BMC ID)
// generated by systemd-id128 -p new as per man page
static constexpr sd_id128_t bmcUuidAppId = SD_ID128_MAKE(
e0, e1, 73, 76, 64, 61, 47, da, a5, 0c, d0, cc, 64, 12, 45, 78);
sd_id128_t bmcUuid;
// create the UUID from /etc/machine-id via the systemd API
sd_id128_get_machine_app_specific(bmcUuidAppId, &bmcUuid);
char bmcUuidCstr[SD_ID128_STRING_MAX];
std::string systemUuid = sd_id128_to_string(bmcUuid, bmcUuidCstr);
std::array<uint8_t, uuidBinaryLength> uuid = rfc4122ToIpmi(systemUuid);
return ipmi::responseSuccess(uuid);
}
auto ipmiAppGetBtCapabilities()
-> ipmi::RspType<uint8_t, uint8_t, uint8_t, uint8_t, uint8_t>
{
// Per IPMI 2.0 spec, the input and output buffer size must be the max
// buffer size minus one byte to allocate space for the length byte.
constexpr uint8_t nrOutstanding = 0x01;
constexpr uint8_t inputBufferSize = MAX_IPMI_BUFFER - 1;
constexpr uint8_t outputBufferSize = MAX_IPMI_BUFFER - 1;
constexpr uint8_t transactionTime = 0x0A;
constexpr uint8_t nrRetries = 0x01;
return ipmi::responseSuccess(nrOutstanding, inputBufferSize,
outputBufferSize, transactionTime, nrRetries);
}
auto ipmiAppGetSystemGuid(ipmi::Context::ptr& ctx)
-> ipmi::RspType<std::array<uint8_t, 16>>
{
static constexpr auto uuidInterface = "xyz.openbmc_project.Common.UUID";
static constexpr auto uuidProperty = "UUID";
// Get the Inventory object implementing BMC interface
ipmi::DbusObjectInfo objectInfo{};
boost::system::error_code ec = ipmi::getDbusObject(
ctx, uuidInterface, ipmi::sensor::inventoryRoot, objectInfo);
if (ec.value())
{
lg2::error("Failed to locate System UUID object, "
"interface: {INTERFACE}, error: {ERROR}",
"INTERFACE", uuidInterface, "ERROR", ec.message());
}
// Read UUID property value from bmcObject
// UUID is in RFC4122 format Ex: 61a39523-78f2-11e5-9862-e6402cfc3223
std::string rfc4122Uuid{};
ec = ipmi::getDbusProperty(ctx, objectInfo.second, objectInfo.first,
uuidInterface, uuidProperty, rfc4122Uuid);
if (ec.value())
{
lg2::error("Failed to read System UUID property, "
"interface: {INTERFACE}, property: {PROPERTY}, "
"error: {ERROR}",
"INTERFACE", uuidInterface, "PROPERTY", uuidProperty,
"ERROR", ec.message());
return ipmi::responseUnspecifiedError();
}
std::array<uint8_t, 16> uuid;
try
{
// convert to IPMI format
uuid = rfc4122ToIpmi(rfc4122Uuid);
}
catch (const InvalidArgument& e)
{
lg2::error("Failed in parsing BMC UUID property, "
"interface: {INTERFACE}, property: {PROPERTY}, "
"value: {VALUE}, error: {ERROR}",
"INTERFACE", uuidInterface, "PROPERTY", uuidProperty,
"VALUE", rfc4122Uuid, "ERROR", e);
return ipmi::responseUnspecifiedError();
}
return ipmi::responseSuccess(uuid);
}
/**
* @brief set the session state as teardown
*
* This function is to set the session state to tear down in progress if the
* state is active.
*
* @param[in] busp - Dbus obj
* @param[in] service - service name
* @param[in] obj - object path
*
* @return success completion code if it sets the session state to
* tearDownInProgress else return the corresponding error completion code.
**/
uint8_t setSessionState(std::shared_ptr<sdbusplus::asio::connection>& busp,
const std::string& service, const std::string& obj)
{
try
{
uint8_t sessionState = std::get<uint8_t>(ipmi::getDbusProperty(
*busp, service, obj, session::sessionIntf, "State"));
if (sessionState == static_cast<uint8_t>(session::State::active))
{
ipmi::setDbusProperty(
*busp, service, obj, session::sessionIntf, "State",
static_cast<uint8_t>(session::State::tearDownInProgress));
return ipmi::ccSuccess;
}
}
catch (const std::exception& e)
{
lg2::error("Failed in getting session state property, "
"service: {SERVICE}, object path: {OBJECT_PATH}, "
"interface: {INTERFACE}, error: {ERROR}",
"SERVICE", service, "OBJECT_PATH", obj, "INTERFACE",
session::sessionIntf, "ERROR", e);
return ipmi::ccUnspecifiedError;
}
return ipmi::ccInvalidFieldRequest;
}
ipmi::RspType<> ipmiAppCloseSession(uint32_t reqSessionId,
std::optional<uint8_t> requestSessionHandle)
{
auto busp = getSdBus();
uint8_t reqSessionHandle =
requestSessionHandle.value_or(session::defaultSessionHandle);
if (reqSessionId == session::sessionZero &&
reqSessionHandle == session::defaultSessionHandle)
{
return ipmi::response(session::ccInvalidSessionId);
}
if (reqSessionId == session::sessionZero &&
reqSessionHandle == session::invalidSessionHandle)
{
return ipmi::response(session::ccInvalidSessionHandle);
}
if (reqSessionId != session::sessionZero &&
reqSessionHandle != session::defaultSessionHandle)
{
return ipmi::response(ipmi::ccInvalidFieldRequest);
}
try
{
ipmi::ObjectTree objectTree = ipmi::getAllDbusObjects(
*busp, session::sessionManagerRootPath, session::sessionIntf);
for (auto& objectTreeItr : objectTree)
{
const std::string obj = objectTreeItr.first;
if (isSessionObjectMatched(obj, reqSessionId, reqSessionHandle))
{
auto& serviceMap = objectTreeItr.second;
// Session id and session handle are unique for each session.
// Session id and handler are retrived from the object path and
// object path will be unique for each session. Checking if
// multiple objects exist with same object path under multiple
// services.
if (serviceMap.size() != 1)
{
return ipmi::responseUnspecifiedError();
}
auto itr = serviceMap.begin();
const std::string service = itr->first;
return ipmi::response(setSessionState(busp, service, obj));
}
}
}
catch (const sdbusplus::exception_t& e)
{
lg2::error("Failed to fetch object from dbus, "
"interface: {INTERFACE}, error: {ERROR}",
"INTERFACE", session::sessionIntf, "ERROR", e);
return ipmi::responseUnspecifiedError();
}
return ipmi::responseInvalidFieldRequest();
}