Merge amd-staging into amd-master 20221230

Signed-off-by: Hao Zhou <Hao.Zhou@amd.com>
Change-Id: I1548ada3cb8b63e9261115ebc7ee402664293298


[ROCm/amdsmi commit: 400baca011]
This commit is contained in:
Hao Zhou
2022-12-30 10:36:34 +08:00
8 changed files with 891 additions and 1380 deletions
+3 -2
View File
@@ -165,9 +165,10 @@ if(PYTHON3 AND PIP3)
COMMAND mkdir -p ${CMAKE_CURRENT_BINARY_DIR}/amdsmi_wrapper/amd_smi
COMMAND cp ${CMAKE_CURRENT_SOURCE_DIR}/rocm_smi/include/rocm_smi/kfd_ioctl.h
${CMAKE_CURRENT_BINARY_DIR}/amdsmi_wrapper/amd_smi/
COMMAND cp ${CMAKE_CURRENT_SOURCE_DIR}/tools/generator.py ${CMAKE_CURRENT_BINARY_DIR}/amdsmi_wrapper/
COMMAND
python3 ${CMAKE_CURRENT_SOURCE_DIR}/tools/generator.py ${CMAKE_CURRENT_BINARY_DIR}/amdsmi_wrapper/amdsmi.h
${CMAKE_CURRENT_BINARY_DIR}/amdsmi_wrapper/ ${CMAKE_CURRENT_BINARY_DIR}/amdsmi_wrapper/
python3 ${CMAKE_CURRENT_BINARY_DIR}/amdsmi_wrapper/generator.py -o ${CMAKE_CURRENT_BINARY_DIR}/amdsmi_wrapper/amdsmi_wrapper.py
-i ${CMAKE_CURRENT_BINARY_DIR}/amdsmi_wrapper/amdsmi.h -l ${CMAKE_CURRENT_BINARY_DIR}/src/libamd_smi.so
COMMAND cp ${CMAKE_CURRENT_BINARY_DIR}/amdsmi_wrapper/amdsmi_wrapper.py
${CMAKE_CURRENT_SOURCE_DIR}/py-interface/
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/amdsmi_wrapper)
+22 -2
View File
@@ -71,7 +71,7 @@ typedef enum amdsmi_init_flags {
AMDSMI_INIT_NON_AMD_GPUS = (1 << 3)
} amdsmi_init_flags_t;
/* Maximum size definitions GPUVSMI */
/* Maximum size definitions AMDSMI */
#define AMDSMI_MAX_MM_IP_COUNT 8
#define AMDSMI_MAX_DATE_LENGTH 32 /**< YYYY-MM-DD:HH:MM:SS.MSC */
#define AMDSMI_MAX_STRING_LENGTH 64
@@ -252,6 +252,7 @@ typedef enum amdsmi_fw_block {
typedef struct {
uint64_t lower_bound; //!< Lower bound of range
uint64_t upper_bound; //!< Upper bound of range
uint64_t reserved[2];
} amdsmi_range_t;
/// @cond Ignore in docs.
typedef amdsmi_range_t amdsmi_range;
@@ -262,6 +263,7 @@ typedef struct amdsmi_xgmi_info {
uint64_t xgmi_hive_id;
uint64_t xgmi_node_id;
uint32_t index;
uint32_t reserved[9];
} amdsmi_xgmi_info_t;
/**
@@ -272,16 +274,19 @@ typedef struct amdsmi_gpu_caps {
uint32_t gfxip_major;
uint32_t gfxip_minor;
uint16_t gfxip_cu_count;
uint32_t reserved[5];
} gfx;
struct {
uint8_t mm_ip_count;
uint8_t mm_ip_list[AMDSMI_MAX_MM_IP_COUNT];
uint32_t reserved[5];
} mm;
bool ras_supported;
uint8_t max_vf_num;
uint32_t gfx_ip_count;
uint32_t dma_ip_count;
uint32_t reserved[5];
} amdsmi_gpu_caps_t;
typedef struct amdsmi_vram_info {
@@ -292,6 +297,7 @@ typedef struct amdsmi_vram_info {
typedef struct amdsmi_frequency_range {
amdsmi_range_t supported_freq_range;
amdsmi_range_t current_freq_range;
uint32_t reserved[8];
} amdsmi_frequency_range_t;
typedef union amdsmi_bdf {
@@ -310,6 +316,7 @@ typedef struct amdsmi_power_cap_info {
uint64_t dpm_cap;
uint64_t min_power_cap;
uint64_t max_power_cap;
uint64_t reserved[3];
} amdsmi_power_cap_info_t;
typedef struct amdsmi_vbios_info {
@@ -318,6 +325,7 @@ typedef struct amdsmi_vbios_info {
char build_date[AMDSMI_MAX_DATE_LENGTH];
char part_number[AMDSMI_MAX_STRING_LENGTH];
char vbios_version_string[AMDSMI_NORMAL_STRING_LENGTH];
uint32_t reserved[15];
} amdsmi_vbios_info_t;
typedef struct amdsmi_fw_info {
@@ -325,7 +333,9 @@ typedef struct amdsmi_fw_info {
struct {
amdsmi_fw_block_t fw_id;
uint64_t fw_version;
uint64_t reserved[2];
} fw_info_list[FW_ID__MAX];
uint32_t reserved[7];
} amdsmi_fw_info_t;
typedef struct amdsmi_asic_info {
@@ -350,14 +360,17 @@ typedef struct amdsmi_board_info {
typedef struct amdsmi_temperature {
uint32_t cur_temp;
uint32_t reserved[7];
} amdsmi_temperature_t;
typedef struct amdsmi_temperature_limit {
uint32_t limit;
uint32_t reserved[7];
} amdsmi_temperature_limit_t;
typedef struct amdsmi_power_limit {
uint32_t limit;
uint32_t reserved[7];
} amdsmi_power_limit_t;
typedef struct amdsmi_power_measure {
@@ -366,6 +379,7 @@ typedef struct amdsmi_power_measure {
uint32_t voltage_gfx; // GFX voltage measurement in mV
uint32_t voltage_soc; // SOC voltage measurement in mV
uint32_t voltage_mem; // MEM voltage measurement in mV
uint32_t reserved[10];
} amdsmi_power_measure_t;
typedef struct amdsmi_clk_measure {
@@ -373,12 +387,14 @@ typedef struct amdsmi_clk_measure {
uint32_t avg_clk;
uint32_t min_clk;
uint32_t max_clk;
uint32_t reserved[4];
} amdsmi_clk_measure_t;
typedef struct amdsmi_engine_usage {
uint32_t gfx_activity;
uint32_t umc_activity;
uint32_t mm_activity[AMDSMI_MAX_MM_IP_COUNT];
uint32_t reserved[6];
} amdsmi_engine_usage_t;
typedef uint32_t amdsmi_process_handle;
@@ -399,7 +415,8 @@ typedef struct amdsmi_process_info {
uint64_t cpu_mem;
uint64_t vram_mem;
} memory_usage; /** in bytes */
char container_name[AMDSMI_NORMAL_STRING_LENGTH];
char container_name[AMDSMI_NORMAL_STRING_LENGTH];
uint32_t reserved[10];
} amdsmi_proc_info_t;
//! Guaranteed maximum possible number of supported frequencies
@@ -924,6 +941,7 @@ typedef struct {
uint32_t minor; //!< Minor version
uint32_t patch; //!< Patch, build or stepping version
const char *build; //!< Build string
uint32_t reserved[4];
} amdsmi_version_t;
/// @cond Ignore in docs.
typedef amdsmi_version_t amdsmi_version;
@@ -1093,6 +1111,7 @@ typedef struct {
typedef struct {
uint64_t correctable_count; //!< Accumulated correctable errors
uint64_t uncorrectable_count; //!< Accumulated uncorrectable errors
uint64_t reserved[2];
} amdsmi_error_count_t;
/**
@@ -1101,6 +1120,7 @@ typedef struct {
typedef struct amdsmi_pcie_info {
uint16_t pcie_lanes;
uint32_t pcie_speed;
uint32_t reserved[6];
} amdsmi_pcie_info_t;
/**
* @brief This structure contains information specific to a process.
+11 -11
View File
@@ -663,7 +663,7 @@ Description: Returns the clock measure for the given GPU
Input parameters:
* `device_handle` device which to query
* `clock_type` one of `AmdSmiClockType` enum values:
* `clock_type` one of `AmdSmiClkType` enum values:
Field | Description
---|---
@@ -701,7 +701,7 @@ try:
print("No GPUs on machine")
else:
for device in devices:
clock_measure = amdsmi_get_clock_measure(device, AmdSmiClockType.GFX)
clock_measure = amdsmi_get_clock_measure(device, AmdSmiClkType.GFX)
print(clock_measure['cur_clk'])
print(clock_measure['avg_clk'])
print(clock_measure['min_clk'])
@@ -901,7 +901,7 @@ Description: Returns the supported frequency target range for the given GPU
Input parameters:
* `device_handle` device which to query
* `clock_type` one of `AmdSmiClockType` enum values:
* `clock_type` one of `AmdSmiClkType` enum values:
Field | Description
---|---
@@ -941,21 +941,21 @@ try:
for device in devices:
print("=============== GFX DOMAIN ================")
freq_range = amdsmi_get_target_frequency_range(device,
AmdSmiClockType.GFX)
AmdSmiClkType.GFX)
print(freq_range['supported_upper_bound'])
print(freq_range['supported_lower_bound'])
print(freq_range['current_upper_bound'])
print(freq_range['current_lower_bound'])
print("=============== MEM DOMAIN ================")
freq_range = amdsmi_get_target_frequency_range(device,
AmdSmiClockType.MEM)
AmdSmiClkType.MEM)
print(freq_range['supported_upper_bound'])
print(freq_range['supported_lower_bound'])
print(freq_range['current_upper_bound'])
print(freq_range['current_lower_bound'])
print("=============== VCLK0 DOMAIN ================")
freq_range = amdsmi_get_target_frequency_range(device,
AmdSmiClockType.VCLK0)
AmdSmiClkType.VCLK0)
print(freq_range['supported_upper_bound'])
print(freq_range['supported_lower_bound'])
print(freq_range['current_upper_bound'])
@@ -1461,7 +1461,7 @@ try:
print("No GPUs on machine")
else:
for device in devices:
amdsmi_dev_set_clk_range(device, 0, 1000, AmdSmiClockType.AMDSMI_CLK_TYPE_SYS)
amdsmi_dev_set_clk_range(device, 0, 1000, AmdSmiClkType.AMDSMI_CLK_TYPE_SYS)
except AmdSmiException as e:
print(e)
```
@@ -1774,7 +1774,7 @@ try:
device,
AmdSmiFreqInd.AMDSMI_FREQ_IND_MAX,
1000,
AmdSmiClockType.AMDSMI_CLK_TYPE_SYS
AmdSmiClkType.AMDSMI_CLK_TYPE_SYS
)
except AmdSmiException as e:
print(e)
@@ -2221,7 +2221,7 @@ try:
print("No GPUs on machine")
else:
for device in devices:
amdsmi_dev_get_gpu_clk_freq(device, AmdSmiClockType.SYS)
amdsmi_dev_get_gpu_clk_freq(device, AmdSmiClkType.SYS)
except AmdSmiException as e:
print(e)
```
@@ -2705,7 +2705,7 @@ specified clock
Input parameters:
* `device_handle` handle for the given device
* `clk_type` the type of clock for which the set of frequencies will be modified
as AmdSmiClockType
as AmdSmiClkType
* `freq_bitmask` bitmask indicating the indices of the frequencies that are to
be enabled (1) and disabled (0). Only the lowest ::amdsmi_frequencies_t.num_supported
bits of this mask are relevant.
@@ -2726,7 +2726,7 @@ try:
else:
for device in devices:
freq_bitmask = 0
amdsmi_dev_set_clk_freq(device, AmdSmiClockType.GFX, freq_bitmask)
amdsmi_dev_set_clk_freq(device, AmdSmiClkType.GFX, freq_bitmask)
except AmdSmiException as e:
print(e)
```
+1 -1
View File
@@ -186,7 +186,7 @@ from .amdsmi_interface import AmdSmiContainerTypes
from .amdsmi_interface import AmdSmiDeviceType
from .amdsmi_interface import AmdSmiMmIp
from .amdsmi_interface import AmdSmiFWBlock
from .amdsmi_interface import AmdSmiClockType
from .amdsmi_interface import AmdSmiClkType
from .amdsmi_interface import AmdSmiTemperatureType
from .amdsmi_interface import AmdSmiDevPerfLevel
from .amdsmi_interface import AmdSmiSwComponent
@@ -104,7 +104,7 @@ class AmdSmiFWBlock(IntEnum):
FW_ID_DMCU = amdsmi_wrapper.FW_ID_DMCU
class AmdSmiClockType(IntEnum):
class AmdSmiClkType(IntEnum):
SYS = amdsmi_wrapper.CLK_TYPE_SYS
GFX = amdsmi_wrapper.CLK_TYPE_GFX
DF = amdsmi_wrapper.CLK_TYPE_DF
@@ -746,8 +746,8 @@ def amdsmi_get_clock_measure(
raise AmdSmiParameterException(
device_handle, amdsmi_wrapper.amdsmi_device_handle
)
if not isinstance(clock_type, AmdSmiClockType):
raise AmdSmiParameterException(clock_type, AmdSmiClockType)
if not isinstance(clock_type, AmdSmiClkType):
raise AmdSmiParameterException(clock_type, AmdSmiClkType)
clock_measure = amdsmi_wrapper.amdsmi_clk_measure_t()
_check_res(
@@ -862,8 +862,8 @@ def amdsmi_get_target_frequency_range(
raise AmdSmiParameterException(
device_handle, amdsmi_wrapper.amdsmi_device_handle
)
if not isinstance(clock_type, AmdSmiClockType):
raise AmdSmiParameterException(clock_type, AmdSmiClockType)
if not isinstance(clock_type, AmdSmiClkType):
raise AmdSmiParameterException(clock_type, AmdSmiClkType)
freq_range = amdsmi_wrapper.amdsmi_frequency_range_t()
_check_res(
@@ -966,7 +966,7 @@ def amdsmi_get_process_list(
device_handle, amdsmi_wrapper.amdsmi_device_handle
)
max_processes = amdsmi_wrapper.c_uint32(0)
max_processes = ctypes.c_uint32(0)
process_list = (amdsmi_wrapper.amdsmi_process_handle *
max_processes.value)()
_check_res(
@@ -999,7 +999,7 @@ def amdsmi_get_process_info(
raise AmdSmiParameterException(
process, amdsmi_wrapper.amdsmi_process_handle)
info = amdsmi_wrapper.amdsmi_process_info()
info = amdsmi_wrapper.amdsmi_proc_info_t()
_check_res(
amdsmi_wrapper.amdsmi_get_process_info(
device_handle, process, ctypes.byref(info)
@@ -1539,7 +1539,7 @@ def amdsmi_counter_get_available_counters(
)
if not isinstance(event_group, AmdSmiEventGroup):
raise AmdSmiParameterException(event_group, AmdSmiEventGroup)
available = amdsmi_wrapper.c_uint32()
available = ctypes.c_uint32()
_check_res(
amdsmi_wrapper. amdsmi_counter_get_available_counters(
@@ -1575,7 +1575,7 @@ def amdsmi_dev_get_power_profile_presets(
if not isinstance(sensor_idx, int):
raise AmdSmiParameterException(sensor_idx, int)
sensor_idx = amdsmi_wrapper.c_uint32(sensor_idx)
sensor_idx = ctypes.c_uint32(sensor_idx)
status = amdsmi_wrapper.amdsmi_power_profile_status_t()
_check_res(
@@ -1609,7 +1609,7 @@ def amdsmi_set_perf_determinism_mode(
)
if not isinstance(clock_value, int):
raise AmdSmiParameterException(clock_value, int)
clock_value = amdsmi_wrapper.c_uint64(clock_value)
clock_value = ctypes.c_uint64(clock_value)
_check_res(
amdsmi_wrapper.amdsmi_set_perf_determinism_mode(
@@ -1628,8 +1628,8 @@ def amdsmi_dev_set_fan_speed(
raise AmdSmiParameterException(sensor_idx, int)
if not isinstance(fan_speed, int):
raise AmdSmiParameterException(fan_speed, int)
sensor_idx = amdsmi_wrapper.c_uint32(sensor_idx)
fan_speed = amdsmi_wrapper.c_uint64(fan_speed)
sensor_idx = ctypes.c_uint32(sensor_idx)
fan_speed = ctypes.c_uint64(fan_speed)
_check_res(
amdsmi_wrapper.amdsmi_dev_set_fan_speed(
@@ -1646,25 +1646,25 @@ def amdsmi_dev_reset_fan(
)
if not isinstance(sensor_idx, int):
raise AmdSmiParameterException(sensor_idx, int)
sensor_idx = amdsmi_wrapper.c_uint32(sensor_idx)
sensor_idx = ctypes.c_uint32(sensor_idx)
_check_res(amdsmi_wrapper.amdsmi_dev_reset_fan(device_handle, sensor_idx))
def amdsmi_dev_set_clk_freq(
device_handle: amdsmi_wrapper.amdsmi_device_handle,
clk_type: AmdSmiClockType,
clk_type: AmdSmiClkType,
freq_bitmask: int,
):
if not isinstance(device_handle, amdsmi_wrapper.amdsmi_device_handle):
raise AmdSmiParameterException(
device_handle, amdsmi_wrapper.amdsmi_device_handle
)
if not isinstance(clk_type, AmdSmiClockType):
if not isinstance(clk_type, AmdSmiClkType):
raise AmdSmiParameterException(clk_type, AmdSmiParameterException)
if not isinstance(freq_bitmask, int):
raise AmdSmiParameterException(freq_bitmask, int)
freq_bitmask = amdsmi_wrapper.c_uint64(freq_bitmask)
freq_bitmask = ctypes.c_uint64(freq_bitmask)
_check_res(
amdsmi_wrapper. amdsmi_dev_set_clk_freq(
device_handle, clk_type, freq_bitmask
@@ -1681,7 +1681,7 @@ def amdsmi_dev_set_overdrive_level_v1(
)
if not isinstance(overdrive_value, int):
raise AmdSmiParameterException(overdrive_value, int)
overdrive_value = amdsmi_wrapper.c_uint32(overdrive_value)
overdrive_value = ctypes.c_uint32(overdrive_value)
_check_res(
amdsmi_wrapper. amdsmi_dev_set_overdrive_level_v1(
@@ -1698,7 +1698,7 @@ def amdsmi_dev_set_overdrive_level(
)
if not isinstance(overdrive_value, int):
raise AmdSmiParameterException(overdrive_value, int)
overdrive_value = amdsmi_wrapper.c_uint32(overdrive_value)
overdrive_value = ctypes.c_uint32(overdrive_value)
_check_res(
amdsmi_wrapper. amdsmi_dev_set_overdrive_level(
@@ -2001,7 +2001,7 @@ def amdsmi_dev_set_clk_range(
device_handle: amdsmi_wrapper.amdsmi_device_handle,
min_clk_value: int,
max_clk_value: int,
clk_type: AmdSmiClockType,
clk_type: AmdSmiClkType,
) -> None:
if not isinstance(device_handle, amdsmi_wrapper.amdsmi_device_handle):
raise AmdSmiParameterException(
@@ -2014,8 +2014,8 @@ def amdsmi_dev_set_clk_range(
if not isinstance(max_clk_value, int):
raise AmdSmiParameterException(min_clk_value, int)
if not isinstance(clk_type, AmdSmiClockType):
raise AmdSmiParameterException(clk_type, AmdSmiClockType)
if not isinstance(clk_type, AmdSmiClkType):
raise AmdSmiParameterException(clk_type, AmdSmiClkType)
_check_res(
amdsmi_wrapper.amdsmi_dev_set_clk_range(
@@ -2052,7 +2052,7 @@ def amdsmi_dev_set_od_clk_info(
device_handle: amdsmi_wrapper.amdsmi_device_handle,
level: AmdSmiFreqInd,
value: int,
clk_type: AmdSmiClockType,
clk_type: AmdSmiClkType,
) -> None:
if not isinstance(device_handle, amdsmi_wrapper.amdsmi_device_handle):
raise AmdSmiParameterException(
@@ -2065,8 +2065,8 @@ def amdsmi_dev_set_od_clk_info(
if not isinstance(value, int):
raise AmdSmiParameterException(value, int)
if not isinstance(clk_type, AmdSmiClockType):
raise AmdSmiParameterException(clk_type, AmdSmiClockType)
if not isinstance(clk_type, AmdSmiClkType):
raise AmdSmiParameterException(clk_type, AmdSmiClkType)
_check_res(
amdsmi_wrapper. amdsmi_dev_set_od_clk_info(
@@ -2167,7 +2167,7 @@ def amdsmi_dev_get_fan_rpms(
)
if not isinstance(sensor_idx, int):
raise AmdSmiParameterException(sensor_idx, int)
fan_speed = amdsmi_wrapper.c_int64()
fan_speed = ctypes.c_int64()
_check_res(
amdsmi_wrapper.amdsmi_dev_get_fan_rpms(
device_handle, sensor_idx, ctypes.byref(fan_speed)
@@ -2186,7 +2186,7 @@ def amdsmi_dev_get_fan_speed(
)
if not isinstance(sensor_idx, int):
raise AmdSmiParameterException(sensor_idx, int)
fan_speed = amdsmi_wrapper.c_int64()
fan_speed = ctypes.c_int64()
_check_res(
amdsmi_wrapper.amdsmi_dev_get_fan_speed(
device_handle, sensor_idx, ctypes.byref(fan_speed)
@@ -2205,7 +2205,7 @@ def amdsmi_dev_get_fan_speed_max(
)
if not isinstance(sensor_idx, int):
raise AmdSmiParameterException(sensor_idx, int)
fan_speed = amdsmi_wrapper.c_uint64()
fan_speed = ctypes.c_uint64()
_check_res(
amdsmi_wrapper.amdsmi_dev_get_fan_speed_max(
device_handle, sensor_idx, ctypes.byref(fan_speed)
@@ -2229,7 +2229,7 @@ def amdsmi_dev_get_temp_metric(
if not isinstance(metric, AmdSmiTemperatureMetric):
raise AmdSmiParameterException(metric, AmdSmiTemperatureMetric)
temp_value = amdsmi_wrapper.c_int64()
temp_value = ctypes.c_int64()
_check_res(
amdsmi_wrapper. amdsmi_dev_get_temp_metric(
device_handle, sensor_type, metric, ctypes.byref(temp_value)
@@ -2253,7 +2253,7 @@ def amdsmi_dev_get_volt_metric(
if not isinstance(metric, AmdSmiVoltageMetric):
raise AmdSmiParameterException(metric, AmdSmiVoltageMetric)
voltage = amdsmi_wrapper.c_int64()
voltage = ctypes.c_int64()
_check_res(
amdsmi_wrapper. amdsmi_dev_get_volt_metric(
device_handle, sensor_type, metric, ctypes.byref(voltage)
@@ -2271,7 +2271,7 @@ def amdsmi_dev_get_busy_percent(
device_handle, amdsmi_wrapper.amdsmi_device_handle
)
busy_percent = amdsmi_wrapper.c_uint32()
busy_percent = ctypes.c_uint32()
_check_res(
amdsmi_wrapper.amdsmi_dev_get_busy_percent(
device_handle, ctypes.byref(busy_percent)
@@ -2300,8 +2300,8 @@ def amdsmi_get_utilization_count(
counter.type = counter_type
counters.append(counter)
count = amdsmi_wrapper.c_uint32(len(counters))
timestamp = amdsmi_wrapper.c_uint64()
count = ctypes.c_uint32(len(counters))
timestamp = ctypes.c_uint64()
util_counter_list = (amdsmi_wrapper.amdsmi_utilization_counter_t * len(counters))(
*counters
)
@@ -2373,7 +2373,7 @@ def amdsmi_dev_get_overdrive_level(
device_handle, amdsmi_wrapper.amdsmi_device_handle
)
od_level = amdsmi_wrapper.c_uint32()
od_level = ctypes.c_uint32()
_check_res(
amdsmi_wrapper.amdsmi_dev_get_overdrive_level(
device_handle, ctypes.byref(od_level)
@@ -2384,14 +2384,14 @@ def amdsmi_dev_get_overdrive_level(
def amdsmi_dev_get_gpu_clk_freq(
device_handle: amdsmi_wrapper.amdsmi_device_handle, clk_type: AmdSmiClockType
device_handle: amdsmi_wrapper.amdsmi_device_handle, clk_type: AmdSmiClkType
) -> Dict[str, Any]:
if not isinstance(device_handle, amdsmi_wrapper.amdsmi_device_handle):
raise AmdSmiParameterException(
device_handle, amdsmi_wrapper.amdsmi_device_handle
)
if not isinstance(clk_type, AmdSmiClockType):
raise AmdSmiParameterException(clk_type, AmdSmiClockType)
if not isinstance(clk_type, AmdSmiClkType):
raise AmdSmiParameterException(clk_type, AmdSmiClkType)
freq = amdsmi_wrapper.amdsmi_frequencies_t()
_check_res(
@@ -2507,7 +2507,7 @@ def amdsmi_dev_get_od_volt_curve_regions(
if not isinstance(num_regions, int):
raise AmdSmiParameterException(num_regions, int)
region_count = amdsmi_wrapper.c_uint32(num_regions)
region_count = ctypes.c_uint32(num_regions)
buffer = (amdsmi_wrapper.amdsmi_freq_volt_region_t * num_regions)()
_check_res(
amdsmi_wrapper. amdsmi_dev_get_od_volt_curve_regions(
File diff suppressed because it is too large Load Diff
@@ -491,7 +491,7 @@ def amdsmi_tool_dev_pci_bandwidth_set(dev, dic):
def amdsmi_tool_dev_gpu_clk_freq_get(dev):
result = {}
for clock_type in smi_api.AmdSmiClockType:
for clock_type in smi_api.AmdSmiClkType:
try:
value = smi_api. amdsmi_dev_get_gpu_clk_freq(dev, clock_type)
result.update({clock_type.name: value})
@@ -618,7 +618,7 @@ def amdsmi_tool_dev_clk_range_set(dev, dic):
result = {}
min_clk = dic["min_clk"]
max_clk = dic["max_clk"]
for clock_type in smi_api.AmdSmiClockType:
for clock_type in smi_api.AmdSmiClkType:
try:
value = smi_api.amdsmi_dev_set_clk_range(dev, min_clk, max_clk, clock_type)
result.update({clock_type.name: value})
@@ -641,7 +641,7 @@ def amdsmi_tool_dev_counter_group_supported(dev):
def amdsmi_tool_dev_gpu_clk_freq_set(dev, dic):
result = {}
freq_bitmask = dic["freq_bitmask"]
for clock_type in smi_api.AmdSmiClockType:
for clock_type in smi_api.AmdSmiClkType:
try:
value = smi_api. amdsmi_dev_set_clk_freq(dev, clock_type, freq_bitmask)
result.update({clock_type.name: value})
@@ -654,10 +654,10 @@ def amdsmi_tool_dev_od_clk_info_set(dev, dic):
result = {}
value = dic["value"]
for freq_ind in smi_api.AmdSmiFreqInd:
for clock_type in smi_api.AmdSmiClockType:
for clock_type in smi_api.AmdSmiClkType:
try:
value = smi_api. amdsmi_dev_set_od_clk_info(dev, freq_ind, value, clock_type)
result.update({"AmdSmiFreqInd: " + freq_ind.name + ", AmdSmiClockType: " + clock_type.name: value})
result.update({"AmdSmiFreqInd: " + freq_ind.name + ", AmdSmiClkType: " + clock_type.name: value})
except smi_api.AmdSmiException as e:
print("{},{}:\t{}".format(freq_ind.name, clock_type.name, e))
+71 -453
View File
@@ -19,435 +19,18 @@
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
import os
import sys
import re
import os
from ctypes import *
from subprocess import call
from subprocess import check_output
sys.path.append(os.getcwd())
import ctypeslib
from ctypeslib.clang2py import main as clang2py
INTERFACE_SPECIFICATION = sys.argv[1]
OUTPUT_DIRECTORY = sys.argv[2]
LIBRARY_BINARY = sys.argv[3]
OUTPUT_FILE = "amdsmi_wrapper.py"
SMI_LIB_CTYPES = "amdsmi_lib_ctypes.py"
SMI_LIB_RET = "amdsmi_lib_ret.py"
INTERFACE_FUNCTIONS = os.path.join(OUTPUT_DIRECTORY, "amdsmi_functions.h")
API_REGEX_MATCHER = r"(\w+\s*\w*[\s\*]+)\s*(\w+)\(([^)]*)\);"
API_REGEX_TYPEDEF = r"typedef\s*(\w+)\s*(.*);"
# Pointer statuses
NO_POINTER = 0
SINGLE_POINTER = 1
DOUBLE_POINTER = 2
TRIPLE_POINTER = 3
clang_include_dir = "/usr/include/"
try:
clang_include_dir = os.path.join(
check_output(["clang", "-print-resource-dir"]).decode("utf-8").strip(),
"include/",
)
except Exception as e:
print(
"Clang not found on the system. The script might not work properly. {}".format(
e
)
)
def ParseHeaderFile() -> bool:
"""
This function will parse the data from the main header file, create separate
temporary files which will then be used as arguments for clang2py(). Afterwards,
when the generator successfully completes wrapper generation - these temporary
files will be removed.
`Parameters`: None.
`Returns`:
`bool`: True if success, False if failed.
"""
if not os.path.exists(INTERFACE_SPECIFICATION):
return False
lib_types = ""
type_read_enablers = [
"#include <stdlib.h>",
"typedef enum amdsmi_init_flags {",
"typedef enum amdsmi_clk_type {",
]
type_read_disablers = [
" * @brief Initialization flags",
"} device_type_t;",
"} amdsmi_func_id_value_t;",
]
reader_mask = False
with open(INTERFACE_SPECIFICATION, "r") as types:
for i, line in enumerate(types):
if line.strip() in type_read_enablers:
reader_mask = True
if reader_mask:
lib_types += line
if line.strip() in type_read_disablers:
reader_mask = False
with open(os.path.join(OUTPUT_DIRECTORY, "amdsmi_lib_types.h"), "w") as file_saver:
file_saver.write(lib_types)
lib_ret_out = ""
ret_reader_enablers = ["#include <stdlib.h>", "typedef enum amdsmi_status_t {"]
ret_reader_disablers = [" * @brief Initialization flags", "} amdsmi_status_t;"]
reader_mask = False
with open(INTERFACE_SPECIFICATION, "r") as ret_out:
for idx, line in enumerate(ret_out):
if line.strip() in ret_reader_enablers:
reader_mask = True
if reader_mask:
lib_ret_out += line
if line.strip() in ret_reader_disablers:
reader_mask = False
with open(os.path.join(OUTPUT_DIRECTORY, "amdsmi_lib_ret.h"), "w") as file_saver:
file_saver.write(lib_ret_out)
functions_out = ""
functions_reader_enablers = [
"#include <stdlib.h>",
"amdsmi_status_t amdsmi_init(uint64_t init_flags);",
]
functions_reader_disablers = [
"typedef enum amdsmi_init_flags {",
"amdsmi_get_ecc_error_count(amdsmi_device_handle dev, amdsmi_error_count_t *ec);",
]
reader_mask = False
with open(INTERFACE_SPECIFICATION, "r") as ret_out:
for idx, line in enumerate(ret_out):
if line.strip() in functions_reader_enablers:
reader_mask = True
if reader_mask:
functions_out += line
if line.strip() in functions_reader_disablers:
reader_mask = False
with open(INTERFACE_FUNCTIONS, "w") as file_saver:
file_saver.write(functions_out)
sys.argv = [
"generator.py",
"--clang-args=-I" + clang_include_dir,
os.path.join(OUTPUT_DIRECTORY, "amdsmi_lib_types.h"),
"-o",
os.path.join(OUTPUT_DIRECTORY, "amdsmi_lib_ctypes.py"),
]
clang2py()
sys.argv = [
"generator.py",
os.path.join(OUTPUT_DIRECTORY, "amdsmi_lib_ret.h"),
"-o",
os.path.join(OUTPUT_DIRECTORY, "amdsmi_lib_ret.py"),
]
clang2py()
return True
def DeducePointerStatus(variable: str) -> int:
"""
Function used to deduce pointer status of a specific variable.
`Parameters`:
* variable (`str`): Variable string for which the pointer status
is to be deduced.
`Returns`:
`int`: Degree of pointer deduced (0 for no pointer status found
and 3 for a triple pointer).
"""
if ("***" in variable) or ("**" in variable and "[]" in variable):
return TRIPLE_POINTER
elif ("**" in variable) or ("*" in variable and "[]" in variable):
return DOUBLE_POINTER
elif "*" in variable or "[]" in variable:
return SINGLE_POINTER
return NO_POINTER
def TypeCast(cxxtype: str, ptr_status=0) -> str:
"""
Function used to type cast a cxx type to the corresponding ctypes
type.
`Parameters`:
* cxxtype (`str`): String containing the cxx type.
* ptr_status (`int`): Integer describing pointer status of the
cxx type.
`Returns`:
`str`: String containing the corresponding ctypes type.
"""
if cxxtype == "void" and ptr_status:
return "c_void_p"
elif cxxtype == "char" and ptr_status:
return "c_char_p"
elif cxxtype == "int":
return "c_int"
elif cxxtype == "unsigned int":
return "c_uint"
elif cxxtype == "unsigned":
return "c_uint"
elif cxxtype == "uint8_t":
return "c_uint8"
elif cxxtype == "uint16_t":
return "c_uint16"
elif cxxtype == "uint32_t":
return "c_uint32"
elif cxxtype == "size_t":
return "c_uint64"
elif cxxtype == "uint64_t":
return "c_uint64"
elif cxxtype == "int8_t":
return "c_int8"
elif cxxtype == "int16_t":
return "c_int16"
elif cxxtype == "int32_t":
return "c_int32"
elif cxxtype == "int64_t":
return "c_int64"
elif cxxtype == "float":
return "c_float"
elif cxxtype == "double":
return "c_double"
elif cxxtype == "char":
return "c_char"
elif cxxtype == "bool":
return "c_bool"
elif cxxtype == "void":
return ""
else:
return cxxtype
def GetType(cxxtype: str, ptr_status=0) -> str:
"""
Function used to retrieve ctypes type of a cxx type.
`Parameters`:
* cxxtype (`str`): String containing the cxx type.
* ptr_status (`int`): Integer representing the pointer
status of the cxx type.
`Returns`:
`str`: String of the ctypes type that was retrieved.
"""
if cxxtype == "void" and ptr_status == 2:
return "POINTER(" + TypeCast(cxxtype, ptr_status=1) + ")"
elif cxxtype == "void" and ptr_status == 1:
return TypeCast(cxxtype, ptr_status)
elif cxxtype == "char" and ptr_status == 2:
return "POINTER(" + TypeCast(cxxtype, ptr_status=1) + ")"
elif cxxtype == "char" and ptr_status == 1:
return TypeCast(cxxtype, ptr_status)
elif ptr_status == 2:
return "POINTER(POINTER(" + TypeCast(cxxtype) + "))"
elif ptr_status == 1:
return "POINTER(" + TypeCast(cxxtype) + ")"
else:
return TypeCast(cxxtype)
def DetectOpaquePointer(variable_type: str, variable: str, ptr_status=0) -> bool:
"""
Function used to check whether a variable is an opaque pointer.
`Parameters`:
* variable_type (`str`): String containing the variable type.
* variable (`str`): String containing the variable name.
* ptr_status (`int`): Integer representing the pointer status found.
`Returns`:
`bool`: Bool representing whether an opaque pointer was deduced or not.
"""
if variable_type == "struct" and len(variable.split(" ")) > 1 and ptr_status == 1:
return True
return False
def TypeDefConvert(variable_type: str, variable: str) -> str:
"""
Function used to break down a typedef down and extract the cxx type.
This type will then further be converted to a ctypes type.
`Parameters`:
* variable_type (`str`): String containing the variable type.
* variable (`str`): String containing the variable name.
`Returns`:
`str`: Finalized string containing the proper definition with ctypes
type.
"""
ptr_status = DeducePointerStatus(variable)
variable = variable.replace("*", " ").strip()
cxxtypedef = str()
if DetectOpaquePointer(variable_type, variable, ptr_status):
variables = variable.split(" ")
cxxtypedef = variables[2] + " = ctypes." + GetType(variables[0], ptr_status)
else:
cxxtypedef = variable + " = ctypes." + GetType(variable_type, ptr_status)
return cxxtypedef
def ParseParameters(parameters: str) -> list:
"""
Function that parses function parameters and returns a list containing
ctypes types for the given parameters.
An example return value:
[smi_device_handle, POINTER(smi_device_handle), POINTER(smi_vf_config)]
`Parameters`:
* parameters (`str`): String containing the parameters for parsing.
`Returns`:
`list`: List containing ctypes types for the given parameters.
"""
if parameters == "":
return []
parameter_array = parameters.split(",")
result = []
for param in parameter_array:
ptr_status = DeducePointerStatus(param)
param = param.strip().split(" ")
while "const" in param:
param.remove("const")
if param[0] == "unsigned" and len(param) == 3:
input = param[0] + " " + param[1]
result.append(GetType(input, ptr_status))
elif param[0] == "struct" or param[0] == "union" or param[0] == "enum":
result.append(GetType(param[1], ptr_status))
else:
result.append(GetType(param[0], ptr_status))
return "[{}]".format(",".join(result))
def CleanTempFiles() -> None:
"""
This function cleans up the temporary files created by the generator.
`Parameters`: None.
`Returns`: None.
"""
os.remove(INTERFACE_FUNCTIONS)
os.remove(os.path.join(OUTPUT_DIRECTORY, "amdsmi_lib_ret.h"))
os.remove(os.path.join(OUTPUT_DIRECTORY, "amdsmi_lib_types.h"))
def main() -> str:
"""
Py wrapper generator.
`Parameters`: None.
`Returns`:
`str`: String containing status message.
"""
api = []
api_expose = []
typedef_list = []
typedef_expose = []
if not ParseHeaderFile():
return "Error - header file missing."
format_code = ["clang-format", "-i", INTERFACE_FUNCTIONS]
try:
ret = call(format_code)
if ret < 0:
print("Clang-format failed to run")
except Exception as e:
print(
"Clang-format not found on the system. The script might not work properly. {}".format(
e
)
)
with open(INTERFACE_FUNCTIONS) as specification:
file_specification = specification.read()
# find all typedefs and construct typedef_list in format [{typedef_name} = {ctypes_type}]
# typedef_expose is the list containing only the names of typedefs [{typedef_name}]
for variable_type, variable in re.findall(
API_REGEX_TYPEDEF, file_specification
):
typedef_list.append(TypeDefConvert(variable_type, variable))
typedef_expose.append(variable.replace("*", ""))
# Get all components from function declaration(return type, function name, parameters) and
# append to api list
# api = [{return_type} = {ctypes_type}, {function_name} = {name}, {args} = [{ctypes_type}]]
for returnType, functionName, parameters in re.findall(
API_REGEX_MATCHER, file_specification
):
ptr_status = DeducePointerStatus(returnType)
returnType = returnType.replace("*", " ").strip()
returnedType = GetType(returnType, ptr_status)
api.append(
{
"return_type": returnedType,
"function_name": functionName,
"args": ParseParameters(parameters),
}
)
# api_expose is the list of all functions(function names) in the interface
api_expose.append(functionName)
api_string = ""
for method in api:
api_string += """
_lib.{function_name}.argtypes = {argument_array}
_lib.{function_name}.restype = {return_type}
{function_name} = _lib.{function_name}
""".format(
function_name=method["function_name"],
argument_array=method["args"],
return_type=method["return_type"],
)
typedef_list_out = ""
for typedef_item in typedef_list:
typedef_list_out += typedef_item + "\n"
smi_lib_ctypes_out = ""
with open(os.path.join(OUTPUT_DIRECTORY, SMI_LIB_CTYPES), "r") as smi_lib_ctypes:
smi_lib_ctypes_out = smi_lib_ctypes.read()
smi_lib_ctypes_out = smi_lib_ctypes_out.replace("struct_", "")
smi_lib_ctypes_out = smi_lib_ctypes_out.replace("union_", "")
smi_lib_ctypes_out = smi_lib_ctypes_out.replace("POINTER(None)", "c_void_p")
smi_lib_ret_out = ""
with open(os.path.join(OUTPUT_DIRECTORY, SMI_LIB_RET), "r") as smi_lib_ret:
smi_lib_ret_out = smi_lib_ret.read()
smi_lib_ret_out = smi_lib_ret_out.replace("__all__ =", "__all__ +=")
with open(os.path.join(OUTPUT_DIRECTORY, OUTPUT_FILE), "w") as out:
out.write(
"""
import argparse
import tempfile
import shutil
import platform
from subprocess import run, PIPE
from ctypeslib.clang2py import main as clangToPy
HEADER = \
"""
#
# Copyright (C) 2022 Advanced Micro Devices. All rights reserved.
#
@@ -469,36 +52,71 @@ _lib.{function_name}.restype = {return_type}
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
from ctypes import *
from ctypes import POINTER
from subprocess import run
from subprocess import PIPE
import os
"""
{SMI_LIB_TYPES}
{SMI_LIB_RET}
{TYPEDEF_LIST}
__all__ += {API_EXPOSE}
__all__ += {TYPEDEF_EXPOSE}
def parseArgument():
parser = argparse.ArgumentParser(description="parse input arguments")
parser.add_argument('-o','--output', type=str, required=True,
help='The output file name')
parser.add_argument('-i','--input', type=str, required=True,
help='The input file name')
parser.add_argument('-l', '--library', type=str, required=True,
help='Loading dynamic link libraries')
args = vars(parser.parse_args())
_lib = CDLL(os.path.join(os.path.dirname(__file__), "libamd_smi.so"))
return args['output'], args['input'], args['library']
{API}
""".format(
SMI_LIB_TYPES=smi_lib_ctypes_out,
SMI_LIB_RET=smi_lib_ret_out,
TYPEDEF_LIST=typedef_list_out,
API_EXPOSE=api_expose,
TYPEDEF_EXPOSE=typedef_expose,
BINARY=LIBRARY_BINARY,
API=api_string,
)
)
CleanTempFiles()
return "Success - wrapper generated."
def replace_line(full_path_file_name, string_to_repalce, new_string):
fh, abs_path = tempfile.mkstemp()
with os.fdopen(fh, 'w') as new_file:
new_file.write(HEADER)
with open(full_path_file_name, 'r+') as old_file:
for line in old_file:
new_file.write(line.replace(string_to_repalce, new_string))
shutil.copymode(full_path_file_name, abs_path)
os.remove(full_path_file_name)
shutil.move(abs_path, full_path_file_name)
def main():
output_file, input_file, library = parseArgument()
library_name = os.path.basename(library)
clang_include_dir = \
run(["clang", "--print-resource-dir"], stdout=PIPE, stderr=PIPE, encoding="utf-8").stdout.strip()
os_platform = platform.system()
if os_platform == "Windows":
clang_include_dir += "\include"
if "Program Files(x86)" in clang_include_dir:
clang_include_dir = clang_include_dir.replace("Program Files(x86)", "Progra~2")
elif "Program Files" in clang_include_dir:
clang_include_dir = clang_include_dir.replace("Program Files", "Progra~1")
arguments = [input_file, "-o", output_file]
line_to_replace = "_libraries['FIXME_STUB'] = FunctionFactoryStub() # ctypes.CDLL('FIXME_STUB')"
new_line = "_libraries['FIXME_STUB'] = ctypes.CDLL('{}')".format(library_name)
elif os_platform == "Linux":
clang_include_dir += "/include"
arguments = [input_file, "-o", output_file, "-l", library]
library_path = os.path.join(os.path.dirname(__file__), library)
line_to_replace = "_libraries['{}'] = ctypes.CDLL('{}')".format(library_name, library_path)
new_line = "_libraries['{}'] = ctypes.CDLL(os.path.join(os.path.dirname(__file__), '{}'))" \
.format(library_name, library_name)
else:
print("Unknown operating system. It is only supporing Linux and Windows.")
return
arguments.append(f"--clang-args=-I" + clang_include_dir)
clangToPy(arguments)
replace_line(output_file, line_to_replace, new_line)
if __name__ == "__main__":
status = main()
print(status)
main()