-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathsensorcommands.cpp
2882 lines (2561 loc) · 99 KB
/
sensorcommands.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
/*
// Copyright (c) 2017 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#include "config.h"
#include "dbus-sdr/sensorcommands.hpp"
#include "dbus-sdr/sdrutils.hpp"
#include "dbus-sdr/sensorutils.hpp"
#include "dbus-sdr/storagecommands.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/container/flat_map.hpp>
#include <ipmid/api.hpp>
#include <ipmid/entity_map_json.hpp>
#include <ipmid/types.hpp>
#include <ipmid/utils.hpp>
#include <phosphor-logging/lg2.hpp>
#include <sdbusplus/bus.hpp>
#include <user_channel/channel_layer.hpp>
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstring>
#include <format>
#include <iostream>
#include <map>
#include <optional>
#include <stdexcept>
#include <string>
#include <utility>
#include <variant>
#ifdef FEATURE_HYBRID_SENSORS
#include "sensordatahandler.hpp"
namespace ipmi
{
namespace sensor
{
extern const IdInfoMap sensors;
} // namespace sensor
} // namespace ipmi
#endif
namespace ipmi
{
namespace dcmi
{
// Refer Table 6-14, DCMI Entity ID Extension, DCMI v1.5 spec
static const std::map<uint8_t, uint8_t> validEntityId{
{0x40, 0x37}, {0x37, 0x40}, {0x41, 0x03},
{0x03, 0x41}, {0x42, 0x07}, {0x07, 0x42}};
constexpr uint8_t temperatureSensorType = 0x01;
constexpr uint8_t maxRecords = 8;
} // namespace dcmi
} // namespace ipmi
constexpr std::array<const char*, 7> suffixes = {
"_Output_Voltage", "_Input_Voltage", "_Output_Current", "_Input_Current",
"_Output_Power", "_Input_Power", "_Temperature"};
namespace ipmi
{
using phosphor::logging::entry;
using phosphor::logging::level;
using phosphor::logging::log;
static constexpr int sensorMapUpdatePeriod = 10;
static constexpr int sensorMapSdrUpdatePeriod = 60;
// BMC I2C address is generally at 0x20
static constexpr uint8_t bmcI2CAddr = 0x20;
constexpr size_t maxSDRTotalSize =
76; // Largest SDR Record Size (type 01) + SDR Overheader Size
constexpr static const uint32_t noTimestamp = 0xFFFFFFFF;
static uint16_t sdrReservationID;
static uint32_t sdrLastAdd = noTimestamp;
static uint32_t sdrLastRemove = noTimestamp;
static constexpr size_t lastRecordIndex = 0xFFFF;
// The IPMI spec defines four Logical Units (LUN), each capable of supporting
// 255 sensors. The 256 values assigned to LUN 2 are special and are not used
// for general purpose sensors. Each LUN reserves location 0xFF. The maximum
// number of IPMI sensors are LUN 0 + LUN 1 + LUN 3, less the reserved
// location.
static constexpr size_t maxIPMISensors = ((3 * 256) - (3 * 1));
static constexpr uint8_t lun0 = 0x0;
static constexpr uint8_t lun1 = 0x1;
static constexpr uint8_t lun3 = 0x3;
static constexpr size_t lun0MaxSensorNum = 0xfe;
static constexpr size_t lun1MaxSensorNum = 0x1fe;
static constexpr size_t lun3MaxSensorNum = 0x3fe;
static constexpr int GENERAL_ERROR = -1;
static boost::container::flat_map<std::string, ObjectValueTree> SensorCache;
// Specify the comparison required to sort and find char* map objects
struct CmpStr
{
bool operator()(const char* a, const char* b) const
{
return std::strcmp(a, b) < 0;
}
};
const static boost::container::flat_map<const char*, SensorUnits, CmpStr>
sensorUnits{{{"temperature", SensorUnits::degreesC},
{"voltage", SensorUnits::volts},
{"current", SensorUnits::amps},
{"fan_tach", SensorUnits::rpm},
{"power", SensorUnits::watts},
{"energy", SensorUnits::joules}}};
void registerSensorFunctions() __attribute__((constructor));
static sdbusplus::bus::match_t sensorAdded(
*getSdBus(),
"type='signal',member='InterfacesAdded',arg0path='/xyz/openbmc_project/"
"sensors/'",
[](sdbusplus::message_t&) {
getSensorTree().clear();
getIpmiDecoratorPaths(/*ctx=*/std::nullopt).reset();
sdrLastAdd = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
});
static sdbusplus::bus::match_t sensorRemoved(
*getSdBus(),
"type='signal',member='InterfacesRemoved',arg0path='/xyz/openbmc_project/"
"sensors/'",
[](sdbusplus::message_t&) {
getSensorTree().clear();
getIpmiDecoratorPaths(/*ctx=*/std::nullopt).reset();
sdrLastRemove = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
});
ipmi_ret_t getSensorConnection(ipmi::Context::ptr ctx, uint8_t sensnum,
std::string& connection, std::string& path,
std::vector<std::string>* interfaces)
{
auto& sensorTree = getSensorTree();
if (!getSensorSubtree(sensorTree) && sensorTree.empty())
{
return IPMI_CC_RESPONSE_ERROR;
}
if (ctx == nullptr)
{
return IPMI_CC_RESPONSE_ERROR;
}
path = getPathFromSensorNumber((ctx->lun << 8) | sensnum);
if (path.empty())
{
return IPMI_CC_INVALID_FIELD_REQUEST;
}
for (const auto& sensor : sensorTree)
{
if (path == sensor.first)
{
connection = sensor.second.begin()->first;
if (interfaces)
*interfaces = sensor.second.begin()->second;
break;
}
}
return 0;
}
SensorSubTree& getSensorTree()
{
static SensorSubTree sensorTree;
return sensorTree;
}
// this keeps track of deassertions for sensor event status command. A
// deasertion can only happen if an assertion was seen first.
static boost::container::flat_map<
std::string, boost::container::flat_map<std::string, std::optional<bool>>>
thresholdDeassertMap;
static sdbusplus::bus::match_t thresholdChanged(
*getSdBus(),
"type='signal',member='PropertiesChanged',interface='org.freedesktop.DBus."
"Properties',arg0namespace='xyz.openbmc_project.Sensor.Threshold'",
[](sdbusplus::message_t& m) {
boost::container::flat_map<std::string, std::variant<bool, double>>
values;
m.read(std::string(), values);
auto findAssert =
std::find_if(values.begin(), values.end(), [](const auto& pair) {
return pair.first.find("Alarm") != std::string::npos;
});
if (findAssert != values.end())
{
auto ptr = std::get_if<bool>(&(findAssert->second));
if (ptr == nullptr)
{
lg2::error("thresholdChanged: Assert non bool");
return;
}
if (*ptr)
{
lg2::info(
"thresholdChanged: Assert, sensor path: {SENSOR_PATH}",
"SENSOR_PATH", m.get_path());
thresholdDeassertMap[m.get_path()][findAssert->first] = *ptr;
}
else
{
auto& value =
thresholdDeassertMap[m.get_path()][findAssert->first];
if (value)
{
lg2::info(
"thresholdChanged: deassert, sensor path: {SENSOR_PATH}",
"SENSOR_PATH", m.get_path());
value = *ptr;
}
}
}
});
namespace sensor
{
static constexpr const char* vrInterface =
"xyz.openbmc_project.Control.VoltageRegulatorMode";
static constexpr const char* sensorInterface =
"xyz.openbmc_project.Sensor.Value";
} // namespace sensor
static void getSensorMaxMin(const DbusInterfaceMap& sensorMap, double& max,
double& min)
{
max = 127;
min = -128;
auto sensorObject = sensorMap.find(sensor::sensorInterface);
auto critical =
sensorMap.find("xyz.openbmc_project.Sensor.Threshold.Critical");
auto warning =
sensorMap.find("xyz.openbmc_project.Sensor.Threshold.Warning");
if (sensorObject != sensorMap.end())
{
auto maxMap = sensorObject->second.find("MaxValue");
auto minMap = sensorObject->second.find("MinValue");
if (maxMap != sensorObject->second.end())
{
max = std::visit(VariantToDoubleVisitor(), maxMap->second);
}
if (minMap != sensorObject->second.end())
{
min = std::visit(VariantToDoubleVisitor(), minMap->second);
}
}
if (critical != sensorMap.end())
{
auto lower = critical->second.find("CriticalLow");
auto upper = critical->second.find("CriticalHigh");
if (lower != critical->second.end())
{
double value = std::visit(VariantToDoubleVisitor(), lower->second);
if (std::isfinite(value))
{
min = std::fmin(value, min);
}
}
if (upper != critical->second.end())
{
double value = std::visit(VariantToDoubleVisitor(), upper->second);
if (std::isfinite(value))
{
max = std::fmax(value, max);
}
}
}
if (warning != sensorMap.end())
{
auto lower = warning->second.find("WarningLow");
auto upper = warning->second.find("WarningHigh");
if (lower != warning->second.end())
{
double value = std::visit(VariantToDoubleVisitor(), lower->second);
if (std::isfinite(value))
{
min = std::fmin(value, min);
}
}
if (upper != warning->second.end())
{
double value = std::visit(VariantToDoubleVisitor(), upper->second);
if (std::isfinite(value))
{
max = std::fmax(value, max);
}
}
}
}
static bool getSensorMap(ipmi::Context::ptr ctx, std::string sensorConnection,
std::string sensorPath, DbusInterfaceMap& sensorMap,
int updatePeriod = sensorMapUpdatePeriod)
{
#ifdef FEATURE_HYBRID_SENSORS
if (auto sensor = findStaticSensor(sensorPath);
sensor != ipmi::sensor::sensors.end() &&
getSensorEventTypeFromPath(sensorPath) !=
static_cast<uint8_t>(SensorEventTypeCodes::threshold))
{
// If the incoming sensor is a discrete sensor, it might fail in
// getManagedObjects(), return true, and use its own getFunc to get
// value.
return true;
}
#endif
static boost::container::flat_map<
std::string, std::chrono::time_point<std::chrono::steady_clock>>
updateTimeMap;
auto updateFind = updateTimeMap.find(sensorConnection);
auto lastUpdate = std::chrono::time_point<std::chrono::steady_clock>();
if (updateFind != updateTimeMap.end())
{
lastUpdate = updateFind->second;
}
auto now = std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::seconds>(now - lastUpdate)
.count() > updatePeriod)
{
bool found = false;
// Object managers for different kinds of OpenBMC DBus interfaces.
// Documented in the phosphor-dbus-interfaces repository.
const char* paths[] = {
"/xyz/openbmc_project/sensors",
"/xyz/openbmc_project/vr",
};
constexpr size_t num_paths = sizeof(paths) / sizeof(paths[0]);
ObjectValueTree allManagedObjects;
for (size_t i = 0; i < num_paths; i++)
{
ObjectValueTree managedObjects;
boost::system::error_code ec = getManagedObjects(
ctx, sensorConnection.c_str(), paths[i], managedObjects);
if (ec)
{
continue;
}
allManagedObjects.merge(managedObjects);
found = true;
}
if (!found)
{
lg2::error("GetMangagedObjects for getSensorMap failed, "
"service: {SERVICE}",
"SERVICE", sensorConnection);
return false;
}
SensorCache[sensorConnection] = allManagedObjects;
// Update time after finish building the map which allow the
// data to be cached for updatePeriod plus the build time.
updateTimeMap[sensorConnection] = std::chrono::steady_clock::now();
}
auto connection = SensorCache.find(sensorConnection);
if (connection == SensorCache.end())
{
return false;
}
auto path = connection->second.find(sensorPath);
if (path == connection->second.end())
{
return false;
}
sensorMap = path->second;
return true;
}
namespace sensor
{
// Read VR profiles from sensor(daemon) interface
static std::optional<std::vector<std::string>> getSupportedVrProfiles(
const ipmi::DbusInterfaceMap::mapped_type& object)
{
// get VR mode profiles from Supported Interface
auto supportedProperty = object.find("Supported");
if (supportedProperty == object.end() ||
object.find("Selected") == object.end())
{
lg2::error("Missing the required Supported and Selected properties");
return std::nullopt;
}
const auto profilesPtr =
std::get_if<std::vector<std::string>>(&supportedProperty->second);
if (profilesPtr == nullptr)
{
lg2::error("property is not array of string");
return std::nullopt;
}
return *profilesPtr;
}
// Calculate VR Mode from input IPMI discrete event bytes
static std::optional<std::string> calculateVRMode(
uint15_t assertOffset, const ipmi::DbusInterfaceMap::mapped_type& VRObject)
{
// get VR mode profiles from Supported Interface
auto profiles = getSupportedVrProfiles(VRObject);
if (!profiles)
{
return std::nullopt;
}
// interpret IPMI cmd bits into profiles' index
long unsigned int index = 0;
// only one bit should be set and the highest bit should not be used.
if (assertOffset == 0 || assertOffset == (1u << 15) ||
(assertOffset & (assertOffset - 1)))
{
lg2::error("IPMI cmd format incorrect, bytes: {BYTES}", "BYTES",
lg2::hex, static_cast<uint16_t>(assertOffset));
return std::nullopt;
}
while (assertOffset != 1)
{
assertOffset >>= 1;
index++;
}
if (index >= profiles->size())
{
lg2::error("profile index out of boundary");
return std::nullopt;
}
return profiles->at(index);
}
// Calculate sensor value from IPMI reading byte
static std::optional<double> calculateValue(
uint8_t reading, const ipmi::DbusInterfaceMap& sensorMap,
const ipmi::DbusInterfaceMap::mapped_type& valueObject)
{
if (valueObject.find("Value") == valueObject.end())
{
lg2::error("Missing the required Value property");
return std::nullopt;
}
double max = 0;
double min = 0;
getSensorMaxMin(sensorMap, max, min);
int16_t mValue = 0;
int16_t bValue = 0;
int8_t rExp = 0;
int8_t bExp = 0;
bool bSigned = false;
if (!getSensorAttributes(max, min, mValue, rExp, bValue, bExp, bSigned))
{
return std::nullopt;
}
double value = bSigned ? ((int8_t)reading) : reading;
value *= ((double)mValue);
value += ((double)bValue) * std::pow(10.0, bExp);
value *= std::pow(10.0, rExp);
return value;
}
// Extract file name from sensor path as the sensors SDR ID. Simplify the name
// if it is too long.
std::string parseSdrIdFromPath(const std::string& path)
{
std::string name;
size_t nameStart = path.rfind("/");
if (nameStart != std::string::npos)
{
name = path.substr(nameStart + 1, std::string::npos - nameStart);
}
if (name.size() > FULL_RECORD_ID_STR_MAX_LENGTH)
{
#ifdef SHORTNAME_REMOVE_SUFFIX
for (const auto& suffix : suffixes)
{
if (boost::ends_with(name, suffix))
{
boost::replace_all(name, suffix, "");
break;
}
}
#endif
#ifdef SHORTNAME_REPLACE_WORDS
constexpr std::array<std::pair<const char*, const char*>, 2>
replaceWords = {std::make_pair("Output", "Out"),
std::make_pair("Input", "In")};
for (const auto& [find, replace] : replaceWords)
{
boost::replace_all(name, find, replace);
}
#endif
// as a backup and if nothing else is configured
name.resize(FULL_RECORD_ID_STR_MAX_LENGTH);
}
return name;
}
bool getVrEventStatus(ipmi::Context::ptr ctx, const std::string& connection,
const std::string& path,
const ipmi::DbusInterfaceMap::mapped_type& object,
std::bitset<16>& assertions)
{
auto profiles = sensor::getSupportedVrProfiles(object);
if (!profiles)
{
return false;
}
std::string mode;
auto ec = getDbusProperty(ctx, connection, path, sensor::vrInterface,
"Selected", mode);
if (ec)
{
lg2::error("Failed to get Selected, path: {PATH}, "
"interface: {INTERFACE}, error: {ERROR}",
"PATH", path, "INTERFACE", sensor::sensorInterface, "ERROR",
ec.message());
return false;
}
auto itr = std::find(profiles->begin(), profiles->end(), mode);
if (itr == profiles->end())
{
lg2::error("VR mode doesn't match any of its profiles, path: {PATH}",
"PATH", path);
return false;
}
std::size_t index =
static_cast<std::size_t>(std::distance(profiles->begin(), itr));
// map index to response event assertion bit.
if (index < 16)
{
assertions.set(index);
}
else
{
lg2::error("VR profile index reaches max assertion bit, "
"path: {PATH}, index: {INDEX}",
"PATH", path, "INDEX", index);
return false;
}
if constexpr (debug)
{
std::cerr << "VR sensor " << sensor::parseSdrIdFromPath(path)
<< " mode is: [" << index << "] " << mode << std::endl;
}
return true;
}
/*
* Handle every Sensor Data Record besides Type 01
*
* The D-Bus sensors work well for generating Type 01 SDRs.
* After the Type 01 sensors are processed the remaining sensor types require
* special handling. Each BMC vendor is going to have their own requirements for
* insertion of non-Type 01 records.
* Manage non-Type 01 records:
*
* Create a new file: dbus-sdr/sensorcommands_oem.cpp
* Populate it with the two weakly linked functions below, without adding the
* 'weak' attribute definition prior to the function definition.
* getOtherSensorsCount(...)
* getOtherSensorsDataRecord(...)
* Example contents are provided in the weak definitions below
* Enable 'sensors-oem' in your phosphor-ipmi-host bbappend file
* 'EXTRA_OEMESON:append = " -Dsensors-oem=enabled"'
* The contents of the sensorcommands_oem.cpp file will then override the code
* provided below.
*/
size_t getOtherSensorsCount(ipmi::Context::ptr ctx) __attribute__((weak));
size_t getOtherSensorsCount(ipmi::Context::ptr ctx)
{
size_t fruCount = 0;
ipmi::Cc ret = ipmi::storage::getFruSdrCount(ctx, fruCount);
if (ret != ipmi::ccSuccess)
{
lg2::error("getOtherSensorsCount: getFruSdrCount error");
return std::numeric_limits<size_t>::max();
}
const auto& entityRecords =
ipmi::sensor::EntityInfoMapContainer::getContainer()
->getIpmiEntityRecords();
size_t entityCount = entityRecords.size();
return fruCount + ipmi::storage::type12Count + entityCount;
}
int getOtherSensorsDataRecord(ipmi::Context::ptr ctx, uint16_t recordID,
std::vector<uint8_t>& recordData)
__attribute__((weak));
int getOtherSensorsDataRecord(ipmi::Context::ptr ctx, uint16_t recordID,
std::vector<uint8_t>& recordData)
{
size_t otherCount{ipmi::sensor::getOtherSensorsCount(ctx)};
if (otherCount == std::numeric_limits<size_t>::max())
{
return GENERAL_ERROR;
}
const auto& entityRecords =
ipmi::sensor::EntityInfoMapContainer::getContainer()
->getIpmiEntityRecords();
size_t sdrIndex(recordID - ipmi::getNumberOfSensors());
size_t entityCount{entityRecords.size()};
size_t fruCount{otherCount - ipmi::storage::type12Count - entityCount};
if (sdrIndex > otherCount)
{
return std::numeric_limits<int>::min();
}
else if (sdrIndex >= fruCount + ipmi::storage::type12Count)
{
// handle type 8 entity map records
ipmi::sensor::EntityInfoMap::const_iterator entity =
entityRecords.find(static_cast<uint8_t>(
sdrIndex - fruCount - ipmi::storage::type12Count));
if (entity == entityRecords.end())
{
return GENERAL_ERROR;
}
recordData = ipmi::storage::getType8SDRs(entity, recordID);
}
else if (sdrIndex >= fruCount)
{
// handle type 12 hardcoded records
size_t type12Index = sdrIndex - fruCount;
if (type12Index >= ipmi::storage::type12Count)
{
lg2::error("getSensorDataRecord: type12Index error");
return GENERAL_ERROR;
}
recordData = ipmi::storage::getType12SDRs(type12Index, recordID);
}
else
{
// handle fru records
get_sdr::SensorDataFruRecord data;
if (ipmi::Cc ret = ipmi::storage::getFruSdrs(ctx, sdrIndex, data);
ret != IPMI_CC_OK)
{
return GENERAL_ERROR;
}
data.header.record_id_msb = recordID >> 8;
data.header.record_id_lsb = recordID & 0xFF;
recordData.insert(recordData.end(), reinterpret_cast<uint8_t*>(&data),
reinterpret_cast<uint8_t*>(&data) + sizeof(data));
}
return 0;
}
} // namespace sensor
ipmi::RspType<> ipmiSenPlatformEvent(ipmi::Context::ptr ctx,
ipmi::message::Payload& p)
{
constexpr const uint8_t validEnvmRev = 0x04;
constexpr const uint8_t lastSensorType = 0x2C;
constexpr const uint8_t oemReserved = 0xC0;
uint8_t sysgeneratorID = 0;
uint8_t evmRev = 0;
uint8_t sensorType = 0;
uint8_t sensorNum = 0;
uint8_t eventType = 0;
uint8_t eventData1 = 0;
std::optional<uint8_t> eventData2 = 0;
std::optional<uint8_t> eventData3 = 0;
[[maybe_unused]] uint16_t generatorID = 0;
ipmi::ChannelInfo chInfo;
if (ipmi::getChannelInfo(ctx->channel, chInfo) != ipmi::ccSuccess)
{
lg2::error("Failed to get Channel Info, channel: {CHANNEL}", "CHANNEL",
ctx->channel);
return ipmi::responseUnspecifiedError();
}
if (static_cast<ipmi::EChannelMediumType>(chInfo.mediumType) ==
ipmi::EChannelMediumType::systemInterface)
{
p.unpack(sysgeneratorID, evmRev, sensorType, sensorNum, eventType,
eventData1, eventData2, eventData3);
constexpr const uint8_t isSoftwareID = 0x01;
if (!(sysgeneratorID & isSoftwareID))
{
return ipmi::responseInvalidFieldRequest();
}
// Refer to IPMI Spec Table 32: SEL Event Records
generatorID = (ctx->channel << 12) // Channel
| (0x0 << 10) // Reserved
| (0x0 << 8) // 0x0 for sys-soft ID
| sysgeneratorID;
}
else
{
p.unpack(evmRev, sensorType, sensorNum, eventType, eventData1,
eventData2, eventData3);
// Refer to IPMI Spec Table 32: SEL Event Records
generatorID = (ctx->channel << 12) // Channel
| (0x0 << 10) // Reserved
| ((ctx->lun & 0x3) << 8) // Lun
| (ctx->rqSA << 1);
}
if (!p.fullyUnpacked())
{
return ipmi::responseReqDataLenInvalid();
}
// Check for valid evmRev and Sensor Type(per Table 42 of spec)
if (evmRev != validEnvmRev)
{
return ipmi::responseInvalidFieldRequest();
}
if ((sensorType > lastSensorType) && (sensorType < oemReserved))
{
return ipmi::responseInvalidFieldRequest();
}
return ipmi::responseSuccess();
}
ipmi::RspType<> ipmiSetSensorReading(
ipmi::Context::ptr ctx, uint8_t sensorNumber, uint8_t, uint8_t reading,
uint15_t assertOffset, bool, uint15_t, bool, uint8_t, uint8_t, uint8_t)
{
std::string connection;
std::string path;
std::vector<std::string> interfaces;
ipmi::Cc status =
getSensorConnection(ctx, sensorNumber, connection, path, &interfaces);
if (status)
{
return ipmi::response(status);
}
// we can tell the sensor type by its interface type
if (std::find(interfaces.begin(), interfaces.end(),
sensor::sensorInterface) != interfaces.end())
{
DbusInterfaceMap sensorMap;
if (!getSensorMap(ctx, connection, path, sensorMap))
{
return ipmi::responseResponseError();
}
auto sensorObject = sensorMap.find(sensor::sensorInterface);
if (sensorObject == sensorMap.end())
{
return ipmi::responseResponseError();
}
// Only allow external SetSensor if write permission granted
if (!details::sdrWriteTable.getWritePermission(
(ctx->lun << 8) | sensorNumber))
{
return ipmi::responseResponseError();
}
auto value =
sensor::calculateValue(reading, sensorMap, sensorObject->second);
if (!value)
{
return ipmi::responseResponseError();
}
if constexpr (debug)
{
lg2::info("IPMI SET_SENSOR, sensor number: {SENSOR_NUM}, "
"byte: {BYTE}, value: {VALUE}",
"SENSOR_NUM", sensorNumber, "BYTE", (unsigned int)reading,
"VALUE", *value);
}
boost::system::error_code ec =
setDbusProperty(ctx, connection, path, sensor::sensorInterface,
"Value", ipmi::Value(*value));
// setDbusProperty intended to resolve dbus exception/rc within the
// function but failed to achieve that. Catch exception in the ipmi
// callback functions for now (e.g. ipmiSetSensorReading).
if (ec)
{
lg2::error("Failed to set Value, path: {PATH}, "
"interface: {INTERFACE}, ERROR: {ERROR}",
"PATH", path, "INTERFACE", sensor::sensorInterface,
"ERROR", ec.message());
return ipmi::responseResponseError();
}
return ipmi::responseSuccess();
}
if (std::find(interfaces.begin(), interfaces.end(), sensor::vrInterface) !=
interfaces.end())
{
DbusInterfaceMap sensorMap;
if (!getSensorMap(ctx, connection, path, sensorMap))
{
return ipmi::responseResponseError();
}
auto sensorObject = sensorMap.find(sensor::vrInterface);
if (sensorObject == sensorMap.end())
{
return ipmi::responseResponseError();
}
// VR sensors are treated as a special case and we will not check the
// write permission for VR sensors, since they always deemed writable
// and permission table are not applied to VR sensors.
auto vrMode =
sensor::calculateVRMode(assertOffset, sensorObject->second);
if (!vrMode)
{
return ipmi::responseResponseError();
}
boost::system::error_code ec = setDbusProperty(
ctx, connection, path, sensor::vrInterface, "Selected", *vrMode);
// setDbusProperty intended to resolve dbus exception/rc within the
// function but failed to achieve that. Catch exception in the ipmi
// callback functions for now (e.g. ipmiSetSensorReading).
if (ec)
{
lg2::error("Failed to set Selected, path: {PATH}, "
"interface: {INTERFACE}, ERROR: {ERROR}",
"PATH", path, "INTERFACE", sensor::sensorInterface,
"ERROR", ec.message());
}
return ipmi::responseSuccess();
}
lg2::error("unknown sensor type, path: {PATH}", "PATH", path);
return ipmi::responseResponseError();
}
ipmi::RspType<uint8_t, uint8_t, uint8_t, std::optional<uint8_t>>
ipmiSenGetSensorReading(ipmi::Context::ptr ctx, uint8_t sensnum)
{
std::string connection;
std::string path;
if (sensnum == reservedSensorNumber)
{
return ipmi::responseInvalidFieldRequest();
}
auto status = getSensorConnection(ctx, sensnum, connection, path);
if (status)
{
return ipmi::response(status);
}
#ifdef FEATURE_HYBRID_SENSORS
if (auto sensor = findStaticSensor(path);
sensor != ipmi::sensor::sensors.end() &&
getSensorEventTypeFromPath(path) !=
static_cast<uint8_t>(SensorEventTypeCodes::threshold))
{
if (ipmi::sensor::Mutability::Read !=
(sensor->second.mutability & ipmi::sensor::Mutability::Read))
{
return ipmi::responseIllegalCommand();
}
uint8_t operation;
try
{
ipmi::sensor::GetSensorResponse getResponse =
sensor->second.getFunc(sensor->second);
if (getResponse.readingOrStateUnavailable)
{
operation |= static_cast<uint8_t>(
IPMISensorReadingByte2::readingStateUnavailable);
}
if (getResponse.scanningEnabled)
{
operation |= static_cast<uint8_t>(
IPMISensorReadingByte2::sensorScanningEnable);
}
if (getResponse.allEventMessagesEnabled)
{
operation |= static_cast<uint8_t>(
IPMISensorReadingByte2::eventMessagesEnable);
}
return ipmi::responseSuccess(
getResponse.reading, operation,
getResponse.thresholdLevelsStates,
getResponse.discreteReadingSensorStates);
}
catch (const std::exception& e)
{
operation |= static_cast<uint8_t>(
IPMISensorReadingByte2::readingStateUnavailable);
return ipmi::responseSuccess(0, operation, 0, std::nullopt);
}
}
#endif
DbusInterfaceMap sensorMap;
if (!getSensorMap(ctx, connection, path, sensorMap))
{
return ipmi::responseResponseError();
}
auto sensorObject = sensorMap.find(sensor::sensorInterface);
if (sensorObject == sensorMap.end() ||
sensorObject->second.find("Value") == sensorObject->second.end())
{
return ipmi::responseResponseError();
}
auto& valueVariant = sensorObject->second["Value"];
double reading = std::visit(VariantToDoubleVisitor(), valueVariant);
double max = 0;
double min = 0;
getSensorMaxMin(sensorMap, max, min);
int16_t mValue = 0;
int16_t bValue = 0;
int8_t rExp = 0;
int8_t bExp = 0;
bool bSigned = false;
if (!getSensorAttributes(max, min, mValue, rExp, bValue, bExp, bSigned))
{
return ipmi::responseResponseError();
}
uint8_t value =
scaleIPMIValueFromDouble(reading, mValue, rExp, bValue, bExp, bSigned);
uint8_t operation =
static_cast<uint8_t>(IPMISensorReadingByte2::sensorScanningEnable);
operation |=
static_cast<uint8_t>(IPMISensorReadingByte2::eventMessagesEnable);
bool notReading = std::isnan(reading);
if (!notReading)
{
auto availableObject =
sensorMap.find("xyz.openbmc_project.State.Decorator.Availability");
if (availableObject != sensorMap.end())
{
auto findAvailable = availableObject->second.find("Available");
if (findAvailable != availableObject->second.end())