Reorganization directory structure [2/n]

Change-Id: I47962d17d755e80dcd9476e1ed75560f433f6115
This commit is contained in:
kamdiedrich
2020-02-23 09:03:33 +01:00
committed by Jaroslaw Chodor
parent d015d3633f
commit e8852a68c4
1292 changed files with 171 additions and 142 deletions

View File

@ -0,0 +1,27 @@
#
# Copyright (C) 2018-2020 Intel Corporation
#
# SPDX-License-Identifier: MIT
#
set(IGDRCL_SRCS_tests_os_interface_base
${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt
${CMAKE_CURRENT_SOURCE_DIR}/device_factory_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/hw_info_config_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/hw_info_config_tests.h
${CMAKE_CURRENT_SOURCE_DIR}/mock_performance_counters.cpp
${CMAKE_CURRENT_SOURCE_DIR}/mock_performance_counters.h
${CMAKE_CURRENT_SOURCE_DIR}/os_context_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/os_interface_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/os_library_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/os_memory_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/performance_counters_gen_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/performance_counters_tests.cpp
)
get_property(NEO_CORE_OS_INTERFACE_AUB_TESTS GLOBAL PROPERTY NEO_CORE_OS_INTERFACE_AUB_TESTS)
list(APPEND IGDRCL_SRCS_tests_os_interface_base ${NEO_CORE_OS_INTERFACE_AUB_TESTS})
target_sources(igdrcl_tests PRIVATE ${IGDRCL_SRCS_tests_os_interface_base})
set_property(GLOBAL PROPERTY IGDRCL_SRCS_tests_os_interface_base ${IGDRCL_SRCS_tests_os_interface_base})
add_subdirectories()

View File

@ -0,0 +1,273 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/execution_environment/execution_environment.h"
#include "core/helpers/hw_info.h"
#include "core/memory_manager/memory_constants.h"
#include "core/os_interface/device_factory.h"
#include "core/os_interface/os_interface.h"
#include "core/os_interface/os_library.h"
#include "core/unit_tests/helpers/debug_manager_state_restore.h"
#include "opencl/source/platform/platform.h"
#include "gtest/gtest.h"
#include "hw_device_id.h"
#include "mocks/mock_execution_environment.h"
#include <set>
using namespace NEO;
OsLibrary *setAdapterInfo(const PLATFORM *platform, const GT_SYSTEM_INFO *gtSystemInfo, uint64_t gpuAddressSpace);
struct DeviceFactoryTest : public ::testing::Test {
public:
void SetUp() override {
const HardwareInfo *hwInfo = platformDevices[0];
executionEnvironment = platform()->peekExecutionEnvironment();
mockGdiDll = setAdapterInfo(&hwInfo->platform, &hwInfo->gtSystemInfo, hwInfo->capabilityTable.gpuAddressSpace);
}
void TearDown() override {
delete mockGdiDll;
}
protected:
OsLibrary *mockGdiDll;
ExecutionEnvironment *executionEnvironment;
};
TEST_F(DeviceFactoryTest, GetDevices_Expect_True_If_Returned) {
size_t numDevices = 0;
bool success = DeviceFactory::getDevices(numDevices, *executionEnvironment);
EXPECT_TRUE((numDevices > 0) ? success : !success);
}
TEST_F(DeviceFactoryTest, GetDevices_Check_HwInfo_Null) {
size_t numDevices = 0;
bool success = DeviceFactory::getDevices(numDevices, *executionEnvironment);
EXPECT_TRUE((numDevices > 0) ? success : !success);
}
TEST_F(DeviceFactoryTest, GetDevices_Check_HwInfo_Platform) {
const HardwareInfo *refHwinfo = *platformDevices;
size_t numDevices = 0;
bool success = DeviceFactory::getDevices(numDevices, *executionEnvironment);
const HardwareInfo *hwInfo = executionEnvironment->getHardwareInfo();
EXPECT_TRUE((numDevices > 0) ? success : !success);
if (numDevices > 0) {
EXPECT_EQ(refHwinfo->platform.eDisplayCoreFamily, hwInfo->platform.eDisplayCoreFamily);
}
}
TEST_F(DeviceFactoryTest, overrideKmdNotifySettings) {
DebugManagerStateRestore stateRestore;
size_t numDevices = 0;
bool success = DeviceFactory::getDevices(numDevices, *executionEnvironment);
auto hwInfo = executionEnvironment->getHardwareInfo();
ASSERT_TRUE(success);
auto refEnableKmdNotify = hwInfo->capabilityTable.kmdNotifyProperties.enableKmdNotify;
auto refDelayKmdNotifyMicroseconds = hwInfo->capabilityTable.kmdNotifyProperties.delayKmdNotifyMicroseconds;
auto refEnableQuickKmdSleep = hwInfo->capabilityTable.kmdNotifyProperties.enableQuickKmdSleep;
auto refDelayQuickKmdSleepMicroseconds = hwInfo->capabilityTable.kmdNotifyProperties.delayQuickKmdSleepMicroseconds;
auto refEnableQuickKmdSleepForSporadicWaits = hwInfo->capabilityTable.kmdNotifyProperties.enableQuickKmdSleepForSporadicWaits;
auto refDelayQuickKmdSleepForSporadicWaitsMicroseconds = hwInfo->capabilityTable.kmdNotifyProperties.delayQuickKmdSleepForSporadicWaitsMicroseconds;
DebugManager.flags.OverrideEnableKmdNotify.set(!refEnableKmdNotify);
DebugManager.flags.OverrideKmdNotifyDelayMicroseconds.set(static_cast<int32_t>(refDelayKmdNotifyMicroseconds) + 10);
DebugManager.flags.OverrideEnableQuickKmdSleep.set(!refEnableQuickKmdSleep);
DebugManager.flags.OverrideQuickKmdSleepDelayMicroseconds.set(static_cast<int32_t>(refDelayQuickKmdSleepMicroseconds) + 11);
DebugManager.flags.OverrideEnableQuickKmdSleepForSporadicWaits.set(!refEnableQuickKmdSleepForSporadicWaits);
DebugManager.flags.OverrideDelayQuickKmdSleepForSporadicWaitsMicroseconds.set(static_cast<int32_t>(refDelayQuickKmdSleepForSporadicWaitsMicroseconds) + 12);
success = DeviceFactory::getDevices(numDevices, *executionEnvironment);
ASSERT_TRUE(success);
hwInfo = executionEnvironment->getHardwareInfo();
EXPECT_EQ(!refEnableKmdNotify, hwInfo->capabilityTable.kmdNotifyProperties.enableKmdNotify);
EXPECT_EQ(refDelayKmdNotifyMicroseconds + 10, hwInfo->capabilityTable.kmdNotifyProperties.delayKmdNotifyMicroseconds);
EXPECT_EQ(!refEnableQuickKmdSleep, hwInfo->capabilityTable.kmdNotifyProperties.enableQuickKmdSleep);
EXPECT_EQ(refDelayQuickKmdSleepMicroseconds + 11, hwInfo->capabilityTable.kmdNotifyProperties.delayQuickKmdSleepMicroseconds);
EXPECT_EQ(!refEnableQuickKmdSleepForSporadicWaits,
hwInfo->capabilityTable.kmdNotifyProperties.enableQuickKmdSleepForSporadicWaits);
EXPECT_EQ(refDelayQuickKmdSleepForSporadicWaitsMicroseconds + 12,
hwInfo->capabilityTable.kmdNotifyProperties.delayQuickKmdSleepForSporadicWaitsMicroseconds);
}
TEST_F(DeviceFactoryTest, getEngineTypeDebugOverride) {
DebugManagerStateRestore dbgRestorer;
int32_t debugEngineType = 2;
DebugManager.flags.NodeOrdinal.set(debugEngineType);
size_t numDevices = 0;
bool success = DeviceFactory::getDevices(numDevices, *executionEnvironment);
ASSERT_TRUE(success);
auto hwInfo = executionEnvironment->getHardwareInfo();
int32_t actualEngineType = static_cast<int32_t>(hwInfo->capabilityTable.defaultEngineType);
EXPECT_EQ(debugEngineType, actualEngineType);
}
TEST_F(DeviceFactoryTest, givenPointerToHwInfoWhenGetDevicedCalledThenRequiedSurfaceSizeIsSettedProperly) {
size_t numDevices = 0;
bool success = DeviceFactory::getDevices(numDevices, *executionEnvironment);
ASSERT_TRUE(success);
auto hwInfo = executionEnvironment->getHardwareInfo();
EXPECT_EQ(hwInfo->gtSystemInfo.CsrSizeInMb * MemoryConstants::megaByte, hwInfo->capabilityTable.requiredPreemptionSurfaceSize);
}
TEST_F(DeviceFactoryTest, givenCreateMultipleRootDevicesDebugFlagWhenGetDevicesIsCalledThenNumberOfReturnedDevicesIsEqualToDebugVariable) {
DebugManagerStateRestore stateRestore;
auto requiredDeviceCount = 2u;
DebugManager.flags.CreateMultipleRootDevices.set(requiredDeviceCount);
size_t numDevices = 0;
bool success = DeviceFactory::getDevices(numDevices, *executionEnvironment);
ASSERT_TRUE(success);
EXPECT_EQ(requiredDeviceCount, numDevices);
EXPECT_EQ(requiredDeviceCount, executionEnvironment->rootDeviceEnvironments.size());
}
TEST_F(DeviceFactoryTest, givenCreateMultipleRootDevicesDebugFlagWhenGetDevicesForProductFamilyOverrideIsCalledThenNumberOfReturnedDevicesIsEqualToDebugVariable) {
DebugManagerStateRestore stateRestore;
auto requiredDeviceCount = 2u;
DebugManager.flags.CreateMultipleRootDevices.set(requiredDeviceCount);
size_t numDevices = 0;
bool success = DeviceFactory::getDevicesForProductFamilyOverride(numDevices, *executionEnvironment);
ASSERT_TRUE(success);
EXPECT_EQ(requiredDeviceCount, numDevices);
}
TEST_F(DeviceFactoryTest, givenDebugFlagSetWhenGetDevicesIsCalledThenOverrideGpuAddressSpace) {
DebugManagerStateRestore restore;
DebugManager.flags.OverrideGpuAddressSpace.set(12);
size_t numDevices = 0;
bool success = DeviceFactory::getDevices(numDevices, *executionEnvironment);
EXPECT_TRUE(success);
EXPECT_EQ(maxNBitValue(12), executionEnvironment->getHardwareInfo()->capabilityTable.gpuAddressSpace);
}
TEST_F(DeviceFactoryTest, givenDebugFlagSetWhenGetDevicesForProductFamilyOverrideIsCalledThenOverrideGpuAddressSpace) {
DebugManagerStateRestore restore;
DebugManager.flags.OverrideGpuAddressSpace.set(12);
size_t numDevices = 0;
bool success = DeviceFactory::getDevicesForProductFamilyOverride(numDevices, *executionEnvironment);
EXPECT_TRUE(success);
EXPECT_EQ(maxNBitValue(12), executionEnvironment->getHardwareInfo()->capabilityTable.gpuAddressSpace);
}
TEST_F(DeviceFactoryTest, whenGetDevicesIsCalledThenAllRootDeviceEnvironmentMembersAreInitialized) {
DebugManagerStateRestore stateRestore;
auto requiredDeviceCount = 2u;
DebugManager.flags.CreateMultipleRootDevices.set(requiredDeviceCount);
MockExecutionEnvironment executionEnvironment(*platformDevices, true, requiredDeviceCount);
size_t numDevices = 0;
bool success = DeviceFactory::getDevices(numDevices, executionEnvironment);
ASSERT_TRUE(success);
EXPECT_EQ(requiredDeviceCount, numDevices);
std::set<MemoryOperationsHandler *> memoryOperationHandlers;
std::set<OSInterface *> osInterfaces;
for (auto rootDeviceIndex = 0u; rootDeviceIndex < requiredDeviceCount; rootDeviceIndex++) {
auto rootDeviceEnvironment = static_cast<MockRootDeviceEnvironment *>(executionEnvironment.rootDeviceEnvironments[rootDeviceIndex].get());
auto memoryOperationInterface = rootDeviceEnvironment->memoryOperationsInterface.get();
EXPECT_NE(nullptr, memoryOperationInterface);
EXPECT_EQ(memoryOperationHandlers.end(), memoryOperationHandlers.find(memoryOperationInterface));
memoryOperationHandlers.insert(memoryOperationInterface);
auto osInterface = rootDeviceEnvironment->osInterface.get();
EXPECT_NE(nullptr, osInterface);
EXPECT_EQ(osInterfaces.end(), osInterfaces.find(osInterface));
osInterfaces.insert(osInterface);
}
}
TEST_F(DeviceFactoryTest, givenInvalidHwConfigStringGetDevicesForProductFamilyOverrideReturnsFalse) {
DebugManagerStateRestore stateRestore;
DebugManager.flags.HardwareInfoOverride.set("1x3");
MockExecutionEnvironment executionEnvironment(*platformDevices);
size_t numDevices = 0;
bool success = DeviceFactory::getDevicesForProductFamilyOverride(numDevices, executionEnvironment);
EXPECT_FALSE(success);
}
TEST_F(DeviceFactoryTest, givenValidHwConfigStringGetDevicesForProductFamilyOverrideReturnsTrue) {
DebugManagerStateRestore stateRestore;
DebugManager.flags.HardwareInfoOverride.set("1x1x1");
MockExecutionEnvironment executionEnvironment(*platformDevices);
size_t numDevices = 0;
EXPECT_ANY_THROW(DeviceFactory::getDevicesForProductFamilyOverride(numDevices, executionEnvironment));
}
TEST_F(DeviceFactoryTest, givenGetDevicesCallWhenItIsDoneThenOsInterfaceIsAllocated) {
size_t numDevices = 0;
bool success = DeviceFactory::getDevices(numDevices, *executionEnvironment);
EXPECT_TRUE(success);
EXPECT_NE(nullptr, executionEnvironment->rootDeviceEnvironments[0]->osInterface);
}
TEST(DeviceFactory, givenHwModeSelectedWhenIsHwModeSelectedIsCalledThenTrueIsReturned) {
DebugManagerStateRestore stateRestore;
constexpr int32_t hwModes[] = {-1, CommandStreamReceiverType::CSR_HW, CommandStreamReceiverType::CSR_HW_WITH_AUB};
for (const auto &hwMode : hwModes) {
DebugManager.flags.SetCommandStreamReceiver.set(hwMode);
EXPECT_TRUE(DeviceFactory::isHwModeSelected());
}
}
TEST(DeviceFactory, givenNonHwModeSelectedWhenIsHwModeSelectedIsCalledThenFalseIsReturned) {
DebugManagerStateRestore stateRestore;
constexpr int32_t nonHwModes[] = {CommandStreamReceiverType::CSR_AUB, CommandStreamReceiverType::CSR_TBX, CommandStreamReceiverType::CSR_TBX_WITH_AUB};
for (const auto &nonHwMode : nonHwModes) {
DebugManager.flags.SetCommandStreamReceiver.set(nonHwMode);
EXPECT_FALSE(DeviceFactory::isHwModeSelected());
}
}
TEST(DiscoverDevices, whenDiscoverDevicesAndForceDeviceIdIsDifferentFromTheExistingDeviceThenReturnNullptr) {
DebugManagerStateRestore stateRestore;
DebugManager.flags.ForceDeviceId.set("invalid");
auto hwDeviceIds = OSInterface::discoverDevices();
EXPECT_TRUE(hwDeviceIds.empty());
}
TEST(DiscoverDevices, whenDiscoverDevicesAndForceDeviceIdIsDifferentFromTheExistingDeviceThenGetDevicesReturnsFalse) {
DebugManagerStateRestore stateRestore;
DebugManager.flags.ForceDeviceId.set("invalid");
size_t numDevices = 0u;
ExecutionEnvironment executionEnviornment;
auto result = DeviceFactory::getDevices(numDevices, executionEnviornment);
EXPECT_FALSE(result);
}

View File

@ -0,0 +1,97 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "os_interface/hw_info_config_tests.h"
#include "core/helpers/hw_helper.h"
using namespace NEO;
using namespace std;
void HwInfoConfigTest::SetUp() {
PlatformFixture::SetUp();
pInHwInfo = pPlatform->getDevice(0)->getHardwareInfo();
testPlatform = &pInHwInfo.platform;
testSkuTable = &pInHwInfo.featureTable;
testWaTable = &pInHwInfo.workaroundTable;
testSysInfo = &pInHwInfo.gtSystemInfo;
outHwInfo = {};
}
void HwInfoConfigTest::TearDown() {
PlatformFixture::TearDown();
}
TEST_F(HwInfoConfigTest, givenHwInfoConfigSetHwInfoValuesFromConfigStringReturnsSetsProperValues) {
uint64_t hwInfoConfig = 0x0;
bool success = parseHwInfoConfigString("1x1x1", hwInfoConfig);
EXPECT_TRUE(success);
EXPECT_EQ(hwInfoConfig, 0x100010001u);
setHwInfoValuesFromConfig(hwInfoConfig, outHwInfo);
EXPECT_EQ(outHwInfo.gtSystemInfo.SliceCount, 1u);
EXPECT_EQ(outHwInfo.gtSystemInfo.SubSliceCount, 1u);
EXPECT_EQ(outHwInfo.gtSystemInfo.EUCount, 1u);
success = parseHwInfoConfigString("7x1x1", hwInfoConfig);
EXPECT_TRUE(success);
EXPECT_EQ(hwInfoConfig, 0x700010001u);
setHwInfoValuesFromConfig(hwInfoConfig, outHwInfo);
EXPECT_EQ(outHwInfo.gtSystemInfo.SliceCount, 7u);
EXPECT_EQ(outHwInfo.gtSystemInfo.SubSliceCount, 7u);
EXPECT_EQ(outHwInfo.gtSystemInfo.EUCount, 7u);
success = parseHwInfoConfigString("1x7x1", hwInfoConfig);
EXPECT_TRUE(success);
EXPECT_EQ(hwInfoConfig, 0x100070001u);
setHwInfoValuesFromConfig(hwInfoConfig, outHwInfo);
EXPECT_EQ(outHwInfo.gtSystemInfo.SliceCount, 1u);
EXPECT_EQ(outHwInfo.gtSystemInfo.SubSliceCount, 7u);
EXPECT_EQ(outHwInfo.gtSystemInfo.EUCount, 7u);
success = parseHwInfoConfigString("1x1x7", hwInfoConfig);
EXPECT_TRUE(success);
EXPECT_EQ(hwInfoConfig, 0x100010007u);
setHwInfoValuesFromConfig(hwInfoConfig, outHwInfo);
EXPECT_EQ(outHwInfo.gtSystemInfo.SliceCount, 1u);
EXPECT_EQ(outHwInfo.gtSystemInfo.SubSliceCount, 1u);
EXPECT_EQ(outHwInfo.gtSystemInfo.EUCount, 7u);
success = parseHwInfoConfigString("2x4x16", hwInfoConfig);
EXPECT_TRUE(success);
setHwInfoValuesFromConfig(hwInfoConfig, outHwInfo);
EXPECT_EQ(outHwInfo.gtSystemInfo.SliceCount, 2u);
EXPECT_EQ(outHwInfo.gtSystemInfo.SubSliceCount, 8u);
EXPECT_EQ(outHwInfo.gtSystemInfo.EUCount, 128u);
}
TEST_F(HwInfoConfigTest, givenInvalidHwInfoSetHwInfoValuesFromConfigString) {
uint64_t hwInfoConfig = 0x0;
bool success = parseHwInfoConfigString("1", hwInfoConfig);
EXPECT_FALSE(success);
success = parseHwInfoConfigString("1x3", hwInfoConfig);
EXPECT_FALSE(success);
success = parseHwInfoConfigString("65536x3x8", hwInfoConfig);
EXPECT_FALSE(success);
success = parseHwInfoConfigString("1x65536x8", hwInfoConfig);
EXPECT_FALSE(success);
success = parseHwInfoConfigString("1x3x65536", hwInfoConfig);
EXPECT_FALSE(success);
success = parseHwInfoConfigString("65535x65535x8", hwInfoConfig);
EXPECT_FALSE(success);
success = parseHwInfoConfigString("1x65535x65535", hwInfoConfig);
EXPECT_FALSE(success);
}

View File

@ -0,0 +1,31 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/device/device.h"
#include "test.h"
#include "fixtures/platform_fixture.h"
#include "gtest/gtest.h"
using namespace NEO;
using namespace std;
struct HwInfoConfigTest : public ::testing::Test,
public PlatformFixture {
void SetUp() override;
void TearDown() override;
HardwareInfo pInHwInfo;
HardwareInfo outHwInfo;
PLATFORM *testPlatform = nullptr;
FeatureTable *testSkuTable = nullptr;
WorkaroundTable *testWaTable = nullptr;
GT_SYSTEM_INFO *testSysInfo = nullptr;
};

View File

@ -0,0 +1,32 @@
---
Checks: 'clang-diagnostic-*,clang-analyzer-*,google-default-arguments,modernize-use-override,modernize-use-default-member-init,-clang-analyzer-alpha*,readability-identifier-naming,-clang-analyzer-optin.performance.Padding,-clang-analyzer-cplusplus.NewDelete,-clang-analyzer-cplusplus.NewDeleteLeaks,-clang-analyzer-optin.cplusplus.VirtualCall'
# WarningsAsErrors: '.*'
HeaderFilterRegex: '/runtime/|/core/|/offline_compiler/'
AnalyzeTemporaryDtors: false
CheckOptions:
- key: google-readability-braces-around-statements.ShortStatementLines
value: '1'
- key: google-readability-function-size.StatementThreshold
value: '800'
- key: google-readability-namespace-comments.ShortNamespaceLines
value: '10'
- key: google-readability-namespace-comments.SpacesBeforeComments
value: '2'
- key: readability-identifier-naming.ParameterCase
value: camelBack
- key: modernize-loop-convert.MaxCopySize
value: '16'
- key: modernize-loop-convert.MinConfidence
value: reasonable
- key: modernize-loop-convert.NamingStyle
value: CamelCase
- key: modernize-pass-by-value.IncludeStyle
value: llvm
- key: modernize-replace-auto-ptr.IncludeStyle
value: llvm
- key: modernize-use-nullptr.NullMacros
value: 'NULL'
- key: modernize-use-default-member-init.UseAssignment
value: '1'
...

View File

@ -0,0 +1,46 @@
#
# Copyright (C) 2018-2020 Intel Corporation
#
# SPDX-License-Identifier: MIT
#
set(IGDRCL_SRCS_tests_os_interface_linux
${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt
${CMAKE_CURRENT_SOURCE_DIR}/allocator_helper_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/debug_env_reader.cpp
${CMAKE_CURRENT_SOURCE_DIR}/device_command_stream_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/device_factory_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/device_factory_tests.h
${CMAKE_CURRENT_SOURCE_DIR}/device_os_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/driver_info_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/drm_buffer_object_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/drm_command_stream_mm_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/drm_command_stream_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}${BRANCH_DIR_SUFFIX}/drm_engine_info_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/drm_gem_close_worker_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}${BRANCH_DIR_SUFFIX}/drm_mapper_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}${BRANCH_DIR_SUFFIX}/drm_memory_info_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/drm_memory_manager_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/drm_memory_manager_tests.h
${CMAKE_CURRENT_SOURCE_DIR}${BRANCH_DIR_SUFFIX}/drm_memory_manager_allocate_in_device_pool_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/drm_neo_create.cpp
${CMAKE_CURRENT_SOURCE_DIR}/drm_os_memory_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/drm_residency_handler_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/drm_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/file_logger_linux_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/hw_info_config_linux_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/hw_info_config_linux_tests.h
${CMAKE_CURRENT_SOURCE_DIR}/linux_create_command_queue_with_properties_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/mock_os_time_linux.h
${CMAKE_CURRENT_SOURCE_DIR}/mock_performance_counters_linux.cpp
${CMAKE_CURRENT_SOURCE_DIR}/mock_performance_counters_linux.h
${CMAKE_CURRENT_SOURCE_DIR}/os_interface_linux_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/os_time_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/performance_counters_linux_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/self_lib_lin.cpp
)
if(UNIX)
target_sources(igdrcl_tests PRIVATE ${IGDRCL_SRCS_tests_os_interface_linux})
endif()
set_property(GLOBAL PROPERTY IGDRCL_SRCS_tests_os_interface_linux ${IGDRCL_SRCS_tests_os_interface_linux})
add_subdirectories()

View File

@ -0,0 +1,19 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/linux/allocator_helper.h"
#include "core/helpers/basic_math.h"
namespace NEO {
size_t getSizeToReserve() {
// 4 x sizeof(Heap32) + 2 x sizeof(Standard/Standard64k)
return (4 * 4 + 2 * 4) * GB;
}
} // namespace NEO

View File

@ -0,0 +1,15 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/helpers/basic_math.h"
#include "core/os_interface/linux/allocator_helper.h"
#include "gtest/gtest.h"
TEST(AllocatorHelper, givenExpectedSizeToReserveWhenGetSizeToReserveCalledThenExpectedValueReturned) {
EXPECT_EQ((4 * 4 + 2 * 4) * GB, NEO::getSizeToReserve());
}

View File

@ -0,0 +1,26 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/execution_environment/execution_environment.h"
#include "core/os_interface/linux/drm_memory_manager.h"
#include "core/os_interface/linux/os_interface.h"
#include "core/os_interface/os_interface.h"
#include "core/unit_tests/helpers/ult_hw_config.h"
#include "opencl/source/memory_manager/os_agnostic_memory_manager.h"
namespace NEO {
std::unique_ptr<MemoryManager> MemoryManager::createMemoryManager(ExecutionEnvironment &executionEnvironment) {
if (ultHwConfig.forceOsAgnosticMemoryManager) {
return std::make_unique<OsAgnosticMemoryManager>(executionEnvironment);
}
return std::make_unique<DrmMemoryManager>(gemCloseWorkerMode::gemCloseWorkerInactive,
DebugManager.flags.EnableForcePin.get(),
true,
executionEnvironment);
}
} // namespace NEO

View File

@ -0,0 +1,85 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/linux/debug_env_reader.h"
#include "test.h"
#include <memory>
namespace NEO {
class DebugEnvReaderTests : public ::testing::Test {
public:
void SetUp() override {
evr = SettingsReader::createOsReader(false, "");
EXPECT_NE(nullptr, evr);
}
void TearDown() override {
delete evr;
}
SettingsReader *evr = nullptr;
};
TEST_F(DebugEnvReaderTests, IfVariableIsSetReturnSetValue) {
int32_t ret;
std::string retString;
std::string defaultString = "Default Value";
std::string setString = "Expected Value";
const char *testingVariableValue = "1234";
setenv("TestingVariable", testingVariableValue, 0);
ret = evr->getSetting("TestingVariable", 1);
EXPECT_EQ(1234, ret);
setenv("TestingVariable", setString.c_str(), 1);
retString = evr->getSetting("TestingVariable", defaultString);
EXPECT_EQ(0, retString.compare(setString));
unsetenv("TestingVariable");
ret = evr->getSetting("TestingVariable", 1);
EXPECT_EQ(1, ret);
}
TEST_F(DebugEnvReaderTests, IfVariableIsNotSetReturnDefaultValue) {
int32_t ret;
std::string retString;
std::string defaultString = "Default Value";
unsetenv("TestingVariable");
ret = evr->getSetting("TestingVariable", 1);
EXPECT_EQ(1, ret);
retString = evr->getSetting("TestingVariable", defaultString);
EXPECT_EQ(0, retString.compare(defaultString));
}
TEST_F(DebugEnvReaderTests, CheckBoolEnvVariable) {
bool ret;
bool defaultValue = true;
bool expectedValue = false;
setenv("TestingVariable", "0", 0);
ret = evr->getSetting("TestingVariable", defaultValue);
EXPECT_EQ(expectedValue, ret);
unsetenv("TestingVariable");
ret = evr->getSetting("TestingVariable", defaultValue);
EXPECT_EQ(defaultValue, ret);
}
TEST_F(DebugEnvReaderTests, appSpecificLacationReturnClCacheLocation) {
std::string appSpecific;
appSpecific = "cl_cache_dir";
EXPECT_EQ(appSpecific, evr->appSpecificLocation(appSpecific));
}
TEST_F(DebugEnvReaderTests, givenEnvironmentVariableReaderWhenCreateOsReaderWithStringThenNotNullPointer) {
std::unique_ptr<SettingsReader> evr(SettingsReader::createOsReader(false, ""));
EXPECT_NE(nullptr, evr);
}
} // namespace NEO

View File

@ -0,0 +1,339 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/helpers/aligned_memory.h"
#include "core/helpers/hw_helper.h"
#include "core/os_interface/linux/drm_memory_manager.h"
#include "core/os_interface/linux/drm_neo.h"
#include "core/unit_tests/helpers/default_hw_info.h"
#include "opencl/source/platform/platform.h"
#include "drm/i915_drm.h"
#include "engine_node.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "helpers/gtest_helpers.h"
#include <atomic>
#include <cstdint>
#include <iostream>
#define RENDER_DEVICE_NAME_MATCHER ::testing::StrEq("/dev/dri/renderD128")
using NEO::constructPlatform;
using NEO::Drm;
using NEO::HwDeviceId;
using NEO::RootDeviceEnvironment;
static const int mockFd = 33;
class DrmMockImpl : public Drm {
public:
DrmMockImpl(int fd) : Drm(std::make_unique<HwDeviceId>(fd), *constructPlatform()->peekExecutionEnvironment()->rootDeviceEnvironments[0]){};
MOCK_METHOD2(ioctl, int(unsigned long request, void *arg));
};
class DrmMockSuccess : public Drm {
public:
DrmMockSuccess() : DrmMockSuccess(*constructPlatform()->peekExecutionEnvironment()->rootDeviceEnvironments[0]) {}
DrmMockSuccess(RootDeviceEnvironment &rootDeviceEnvironment) : Drm(std::make_unique<HwDeviceId>(mockFd), rootDeviceEnvironment) {}
int ioctl(unsigned long request, void *arg) override { return 0; };
};
class DrmMockFail : public Drm {
public:
DrmMockFail() : Drm(std::make_unique<HwDeviceId>(mockFd), *constructPlatform()->peekExecutionEnvironment()->rootDeviceEnvironments[0]) {}
int ioctl(unsigned long request, void *arg) override { return -1; };
};
class DrmMockTime : public DrmMockSuccess {
public:
int ioctl(unsigned long request, void *arg) override {
drm_i915_reg_read *reg = reinterpret_cast<drm_i915_reg_read *>(arg);
reg->val = getVal() << 32;
return 0;
};
uint64_t getVal() {
static uint64_t val = 0;
return ++val;
}
};
class DrmMockCustom : public Drm {
public:
struct IoctlResExt {
int32_t no;
int32_t res;
IoctlResExt(int32_t no, int32_t res) : no(no), res(res) {}
};
class Ioctls {
public:
void reset() {
total = 0;
execbuffer2 = 0;
gemUserptr = 0;
gemCreate = 0;
gemSetTiling = 0;
gemGetTiling = 0;
primeFdToHandle = 0;
handleToPrimeFd = 0;
gemMmap = 0;
gemSetDomain = 0;
gemWait = 0;
gemClose = 0;
regRead = 0;
getParam = 0;
contextGetParam = 0;
contextCreate = 0;
contextDestroy = 0;
}
std::atomic<int32_t> total;
std::atomic<int32_t> execbuffer2;
std::atomic<int32_t> gemUserptr;
std::atomic<int32_t> gemCreate;
std::atomic<int32_t> gemSetTiling;
std::atomic<int32_t> gemGetTiling;
std::atomic<int32_t> primeFdToHandle;
std::atomic<int32_t> handleToPrimeFd;
std::atomic<int32_t> gemMmap;
std::atomic<int32_t> gemSetDomain;
std::atomic<int32_t> gemWait;
std::atomic<int32_t> gemClose;
std::atomic<int32_t> regRead;
std::atomic<int32_t> getParam;
std::atomic<int32_t> contextGetParam;
std::atomic<int32_t> contextCreate;
std::atomic<int32_t> contextDestroy;
};
std::atomic<int> ioctl_res;
Ioctls ioctl_cnt;
Ioctls ioctl_expected;
std::atomic<IoctlResExt *> ioctl_res_ext;
void testIoctls() {
if (this->ioctl_expected.total == -1)
return;
#define NEO_IOCTL_EXPECT_EQ(PARAM) \
if (this->ioctl_expected.PARAM >= 0) { \
EXPECT_EQ(this->ioctl_expected.PARAM, this->ioctl_cnt.PARAM); \
}
NEO_IOCTL_EXPECT_EQ(execbuffer2);
NEO_IOCTL_EXPECT_EQ(gemUserptr);
NEO_IOCTL_EXPECT_EQ(gemCreate);
NEO_IOCTL_EXPECT_EQ(gemSetTiling);
NEO_IOCTL_EXPECT_EQ(gemGetTiling);
NEO_IOCTL_EXPECT_EQ(primeFdToHandle);
NEO_IOCTL_EXPECT_EQ(handleToPrimeFd);
NEO_IOCTL_EXPECT_EQ(gemMmap);
NEO_IOCTL_EXPECT_EQ(gemSetDomain);
NEO_IOCTL_EXPECT_EQ(gemWait);
NEO_IOCTL_EXPECT_EQ(gemClose);
NEO_IOCTL_EXPECT_EQ(regRead);
NEO_IOCTL_EXPECT_EQ(getParam);
NEO_IOCTL_EXPECT_EQ(contextGetParam);
NEO_IOCTL_EXPECT_EQ(contextCreate);
NEO_IOCTL_EXPECT_EQ(contextDestroy);
#undef NEO_IOCTL_EXPECT_EQ
}
//DRM_IOCTL_I915_GEM_EXECBUFFER2
drm_i915_gem_execbuffer2 execBuffer = {0};
//DRM_IOCTL_I915_GEM_CREATE
__u64 createParamsSize = 0;
__u32 createParamsHandle = 0;
//DRM_IOCTL_I915_GEM_SET_TILING
__u32 setTilingMode = 0;
__u32 setTilingHandle = 0;
__u32 setTilingStride = 0;
//DRM_IOCTL_I915_GEM_GET_TILING
__u32 getTilingModeOut = I915_TILING_NONE;
__u32 getTilingHandleIn = 0;
//DRM_IOCTL_PRIME_FD_TO_HANDLE
__u32 outputHandle = 0;
__s32 inputFd = 0;
//DRM_IOCTL_PRIME_HANDLE_TO_FD
__u32 inputHandle = 0;
__s32 outputFd = 0;
__s32 inputFlags = 0;
//DRM_IOCTL_I915_GEM_USERPTR
__u32 returnHandle = 0;
//DRM_IOCTL_I915_GEM_MMAP
__u32 mmapHandle = 0;
__u32 mmapPad = 0;
__u64 mmapOffset = 0;
__u64 mmapSize = 0;
__u64 mmapAddrPtr = 0x7F4000001000;
__u64 mmapFlags = 0;
//DRM_IOCTL_I915_GEM_SET_DOMAIN
__u32 setDomainHandle = 0;
__u32 setDomainReadDomains = 0;
__u32 setDomainWriteDomain = 0;
//DRM_IOCTL_I915_GETPARAM
drm_i915_getparam_t recordedGetParam = {0};
int getParamRetValue = 0;
//DRM_IOCTL_I915_GEM_CONTEXT_GETPARAM
drm_i915_gem_context_param recordedGetContextParam = {0};
__u64 getContextParamRetValue = 0;
int errnoValue = 0;
int ioctl(unsigned long request, void *arg) override {
auto ext = ioctl_res_ext.load();
//store flags
switch (request) {
case DRM_IOCTL_I915_GEM_EXECBUFFER2: {
drm_i915_gem_execbuffer2 *execbuf = (drm_i915_gem_execbuffer2 *)arg;
this->execBuffer = *execbuf;
ioctl_cnt.execbuffer2++;
} break;
case DRM_IOCTL_I915_GEM_USERPTR: {
auto *userPtrParams = (drm_i915_gem_userptr *)arg;
userPtrParams->handle = returnHandle;
returnHandle++;
ioctl_cnt.gemUserptr++;
} break;
case DRM_IOCTL_I915_GEM_CREATE: {
auto *createParams = (drm_i915_gem_create *)arg;
this->createParamsSize = createParams->size;
this->createParamsHandle = createParams->handle = 1u;
ioctl_cnt.gemCreate++;
} break;
case DRM_IOCTL_I915_GEM_SET_TILING: {
auto *setTilingParams = (drm_i915_gem_set_tiling *)arg;
setTilingMode = setTilingParams->tiling_mode;
setTilingHandle = setTilingParams->handle;
setTilingStride = setTilingParams->stride;
ioctl_cnt.gemSetTiling++;
} break;
case DRM_IOCTL_I915_GEM_GET_TILING: {
auto *getTilingParams = (drm_i915_gem_get_tiling *)arg;
getTilingParams->tiling_mode = getTilingModeOut;
getTilingHandleIn = getTilingParams->handle;
ioctl_cnt.gemGetTiling++;
} break;
case DRM_IOCTL_PRIME_FD_TO_HANDLE: {
auto *primeToHandleParams = (drm_prime_handle *)arg;
//return BO
primeToHandleParams->handle = outputHandle;
inputFd = primeToHandleParams->fd;
ioctl_cnt.primeFdToHandle++;
} break;
case DRM_IOCTL_PRIME_HANDLE_TO_FD: {
auto *handleToPrimeParams = (drm_prime_handle *)arg;
//return FD
inputHandle = handleToPrimeParams->handle;
inputFlags = handleToPrimeParams->flags;
handleToPrimeParams->fd = outputFd;
ioctl_cnt.handleToPrimeFd++;
} break;
case DRM_IOCTL_I915_GEM_MMAP: {
auto mmapParams = (drm_i915_gem_mmap *)arg;
mmapHandle = mmapParams->handle;
mmapPad = mmapParams->pad;
mmapOffset = mmapParams->offset;
mmapSize = mmapParams->size;
mmapFlags = mmapParams->flags;
mmapParams->addr_ptr = mmapAddrPtr;
ioctl_cnt.gemMmap++;
} break;
case DRM_IOCTL_I915_GEM_SET_DOMAIN: {
auto setDomainParams = (drm_i915_gem_set_domain *)arg;
setDomainHandle = setDomainParams->handle;
setDomainReadDomains = setDomainParams->read_domains;
setDomainWriteDomain = setDomainParams->write_domain;
ioctl_cnt.gemSetDomain++;
} break;
case DRM_IOCTL_I915_GEM_WAIT:
ioctl_cnt.gemWait++;
break;
case DRM_IOCTL_GEM_CLOSE:
ioctl_cnt.gemClose++;
break;
case DRM_IOCTL_I915_REG_READ:
ioctl_cnt.regRead++;
break;
case DRM_IOCTL_I915_GETPARAM: {
ioctl_cnt.contextGetParam++;
auto getParam = (drm_i915_getparam_t *)arg;
recordedGetParam = *getParam;
*getParam->value = getParamRetValue;
} break;
case DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM: {
} break;
case DRM_IOCTL_I915_GEM_CONTEXT_GETPARAM: {
ioctl_cnt.contextGetParam++;
auto getContextParam = (drm_i915_gem_context_param *)arg;
recordedGetContextParam = *getContextParam;
getContextParam->value = getContextParamRetValue;
} break;
case DRM_IOCTL_I915_GEM_CONTEXT_CREATE: {
auto contextCreateParam = reinterpret_cast<drm_i915_gem_context_create *>(arg);
contextCreateParam->ctx_id = ++ioctl_cnt.contextCreate;
} break;
case DRM_IOCTL_I915_GEM_CONTEXT_DESTROY: {
ioctl_cnt.contextDestroy++;
} break;
default:
ioctlExtra(request, arg);
}
if (ext->no != -1 && ext->no == ioctl_cnt.total.load()) {
ioctl_cnt.total.fetch_add(1);
return ext->res;
}
ioctl_cnt.total.fetch_add(1);
return ioctl_res.load();
};
virtual int ioctlExtra(unsigned long request, void *arg) {
switch (request) {
default:
std::cout << "unexpected IOCTL: " << std::hex << request << std::endl;
UNRECOVERABLE_IF(true);
break;
}
return 0;
}
IoctlResExt NONE = {-1, 0};
void reset() {
ioctl_res = 0;
ioctl_cnt.reset();
ioctl_expected.reset();
ioctl_res_ext = &NONE;
}
DrmMockCustom() : Drm(std::make_unique<HwDeviceId>(mockFd), *constructPlatform()->peekExecutionEnvironment()->rootDeviceEnvironments[0]) {
reset();
ioctl_expected.contextCreate = static_cast<int>(NEO::HwHelper::get(NEO::platformDevices[0]->platform.eRenderCoreFamily).getGpgpuEngineInstances().size());
ioctl_expected.contextDestroy = ioctl_expected.contextCreate.load();
}
int getErrno() override {
return errnoValue;
}
};

View File

@ -0,0 +1,62 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/command_stream/command_stream_receiver.h"
#include "core/command_stream/linear_stream.h"
#include "core/os_interface/linux/os_interface.h"
#include "opencl/source/command_stream/aub_command_stream_receiver.h"
#include "opencl/source/command_stream/device_command_stream.h"
#include "opencl/source/os_interface/linux/device_command_stream.inl"
#include "opencl/source/os_interface/linux/drm_command_stream.h"
#include "test.h"
#include "fixtures/device_fixture.h"
#include "fixtures/mock_aub_center_fixture.h"
#include "gtest/gtest.h"
#include "helpers/execution_environment_helper.h"
#include "os_interface/linux/device_command_stream_fixture.h"
#include <memory>
using namespace NEO;
struct DeviceCommandStreamLeaksTest : ::testing::Test {
void SetUp() override {
HardwareInfo *hwInfo = nullptr;
executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 1);
MockAubCenterFixture::setMockAubCenter(*executionEnvironment->rootDeviceEnvironments[0]);
}
ExecutionEnvironment *executionEnvironment;
};
HWTEST_F(DeviceCommandStreamLeaksTest, Create) {
std::unique_ptr<CommandStreamReceiver> ptr(DeviceCommandStreamReceiver<FamilyType>::create(false, *executionEnvironment, 0));
DrmMockSuccess mockDrm;
EXPECT_NE(nullptr, ptr);
}
HWTEST_F(DeviceCommandStreamLeaksTest, givenDefaultDrmCsrWhenItIsCreatedThenGemCloseWorkerInactiveModeIsSelected) {
std::unique_ptr<CommandStreamReceiver> ptr(DeviceCommandStreamReceiver<FamilyType>::create(false, *executionEnvironment, 0));
auto drmCsr = (DrmCommandStreamReceiver<FamilyType> *)ptr.get();
EXPECT_EQ(drmCsr->peekGemCloseWorkerOperationMode(), gemCloseWorkerMode::gemCloseWorkerActive);
}
HWTEST_F(DeviceCommandStreamLeaksTest, givenDefaultDrmCsrWithAubDumWhenItIsCreatedThenGemCloseWorkerInactiveModeIsSelected) {
std::unique_ptr<CommandStreamReceiver> ptr(DeviceCommandStreamReceiver<FamilyType>::create(true, *executionEnvironment, 0));
auto drmCsrWithAubDump = (CommandStreamReceiverWithAUBDump<DrmCommandStreamReceiver<FamilyType>> *)ptr.get();
EXPECT_EQ(drmCsrWithAubDump->peekGemCloseWorkerOperationMode(), gemCloseWorkerMode::gemCloseWorkerActive);
auto aubCSR = static_cast<CommandStreamReceiverWithAUBDump<DrmCommandStreamReceiver<FamilyType>> *>(ptr.get())->aubCSR.get();
EXPECT_NE(nullptr, aubCSR);
}
HWTEST_F(DeviceCommandStreamLeaksTest, givenDefaultDrmCsrWhenOsInterfaceIsNullptrThenValidateDrm) {
std::unique_ptr<CommandStreamReceiver> ptr(DeviceCommandStreamReceiver<FamilyType>::create(false, *executionEnvironment, 0));
auto drmCsr = (DrmCommandStreamReceiver<FamilyType> *)ptr.get();
EXPECT_NE(nullptr, executionEnvironment->rootDeviceEnvironments[0]->osInterface);
EXPECT_EQ(drmCsr->getOSInterface()->get()->getDrm(), executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->getDrm());
}

View File

@ -0,0 +1,63 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "os_interface/linux/device_factory_tests.h"
#include "core/execution_environment/root_device_environment.h"
#include "core/os_interface/linux/os_interface.h"
#include "core/os_interface/os_interface.h"
#include "core/unit_tests/helpers/default_hw_info.h"
TEST_F(DeviceFactoryLinuxTest, GetDevicesCheckEUCntSSCnt) {
const HardwareInfo *refHwinfo = *platformDevices;
size_t numDevices = 0;
pDrm->StoredEUVal = 11;
pDrm->StoredSSVal = 8;
bool success = DeviceFactory::getDevices(numDevices, executionEnvironment);
auto hwInfo = executionEnvironment.getHardwareInfo();
EXPECT_TRUE(success);
EXPECT_EQ((int)numDevices, 1);
EXPECT_NE(hwInfo, nullptr);
EXPECT_EQ(refHwinfo->platform.eDisplayCoreFamily, hwInfo->platform.eDisplayCoreFamily);
EXPECT_EQ((int)hwInfo->gtSystemInfo.EUCount, 11);
EXPECT_EQ((int)hwInfo->gtSystemInfo.SubSliceCount, 8);
//temporararily return GT2.
EXPECT_EQ(1u, hwInfo->featureTable.ftrGT2);
}
TEST_F(DeviceFactoryLinuxTest, GetDevicesDrmCreateFailedConfigureHwInfo) {
size_t numDevices = 0;
pDrm->StoredRetValForDeviceID = -1;
bool success = DeviceFactory::getDevices(numDevices, executionEnvironment);
EXPECT_FALSE(success);
pDrm->StoredRetValForDeviceID = 0;
}
TEST_F(DeviceFactoryLinuxTest, givenGetDeviceCallWhenItIsDoneThenOsInterfaceIsAllocatedAndItContainDrm) {
size_t numDevices = 0;
bool success = DeviceFactory::getDevices(numDevices, executionEnvironment);
EXPECT_TRUE(success);
EXPECT_NE(nullptr, executionEnvironment.rootDeviceEnvironments[0]->osInterface);
EXPECT_NE(nullptr, pDrm);
EXPECT_EQ(pDrm, executionEnvironment.rootDeviceEnvironments[0]->osInterface->get()->getDrm());
}
TEST_F(DeviceFactoryLinuxTest, whenDrmIsNotCretedThenGetDevicesFails) {
delete pDrm;
pDrm = nullptr;
size_t numDevices = 0;
bool success = DeviceFactory::getDevices(numDevices, executionEnvironment);
EXPECT_FALSE(success);
}

View File

@ -0,0 +1,38 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/device/device.h"
#include "core/execution_environment/execution_environment.h"
#include "core/os_interface/device_factory.h"
#include "test.h"
#include "gtest/gtest.h"
#include "helpers/variable_backup.h"
#include "mocks/mock_execution_environment.h"
#include "os_interface/linux/drm_mock.h"
namespace NEO {
extern Drm **pDrmToReturnFromCreateFunc;
}; // namespace NEO
using namespace NEO;
struct DeviceFactoryLinuxTest : public ::testing::Test {
void SetUp() override {
pDrm = new DrmMock;
pDrmToReturnFromCreateFunc = reinterpret_cast<Drm **>(&pDrm);
pDrm->setGtType(GTTYPE_GT2);
}
void TearDown() override {
}
VariableBackup<Drm **> drmBackup{&pDrmToReturnFromCreateFunc};
DrmMock *pDrm;
MockExecutionEnvironment executionEnvironment;
};

View File

@ -0,0 +1,121 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/device/device.h"
#include "core/helpers/get_info.h"
#include "core/unit_tests/helpers/debug_manager_state_restore.h"
#include "opencl/source/api/api.h"
#include "opencl/source/platform/platform.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "mocks/mock_buffer.h"
#include "mocks/mock_command_queue.h"
#include "mocks/mock_context.h"
#include "mocks/mock_device.h"
using namespace ::testing;
namespace NEO {
TEST(DeviceOsTest, GivenDefaultDeviceWhenCheckingForOsSpecificExtensionsThenCorrectExtensionsAreSet) {
auto hwInfo = *platformDevices;
auto pDevice = MockDevice::createWithNewExecutionEnvironment<Device>(hwInfo);
std::string extensionString(pDevice->getDeviceInfo().deviceExtensions);
EXPECT_THAT(extensionString, Not(testing::HasSubstr(std::string("cl_intel_dx9_media_sharing "))));
EXPECT_THAT(extensionString, Not(testing::HasSubstr(std::string("cl_khr_dx9_media_sharing "))));
EXPECT_THAT(extensionString, Not(testing::HasSubstr(std::string("cl_khr_d3d10_sharing "))));
EXPECT_THAT(extensionString, Not(testing::HasSubstr(std::string("cl_khr_d3d11_sharing "))));
EXPECT_THAT(extensionString, Not(testing::HasSubstr(std::string("cl_intel_d3d11_nv12_media_sharing "))));
EXPECT_THAT(extensionString, Not(testing::HasSubstr(std::string("cl_intel_simultaneous_sharing "))));
delete pDevice;
}
TEST(DeviceOsTest, GivenDefaultClDeviceWhenCheckingForOsSpecificExtensionsThenCorrectExtensionsAreSet) {
auto hwInfo = *platformDevices;
auto pDevice = MockDevice::createWithNewExecutionEnvironment<Device>(hwInfo);
auto pClDevice = new ClDevice{*pDevice, platform()};
std::string extensionString(pClDevice->getDeviceInfo().deviceExtensions);
EXPECT_THAT(extensionString, Not(testing::HasSubstr(std::string("cl_intel_dx9_media_sharing "))));
EXPECT_THAT(extensionString, Not(testing::HasSubstr(std::string("cl_khr_dx9_media_sharing "))));
EXPECT_THAT(extensionString, Not(testing::HasSubstr(std::string("cl_khr_d3d10_sharing "))));
EXPECT_THAT(extensionString, Not(testing::HasSubstr(std::string("cl_khr_d3d11_sharing "))));
EXPECT_THAT(extensionString, Not(testing::HasSubstr(std::string("cl_intel_d3d11_nv12_media_sharing "))));
EXPECT_THAT(extensionString, Not(testing::HasSubstr(std::string("cl_intel_simultaneous_sharing "))));
delete pClDevice;
}
TEST(DeviceOsTest, supportedSimultaneousInterops) {
auto pDevice = std::make_unique<MockClDevice>(MockDevice::createWithNewExecutionEnvironment<MockDevice>(*platformDevices));
std::vector<unsigned int> expected = {0};
EXPECT_TRUE(pDevice->simultaneousInterops == expected);
}
TEST(DeviceOsTest, DeviceCreationFail) {
auto hwInfo = *platformDevices;
auto pDevice = MockDevice::createWithNewExecutionEnvironment<FailDevice>(hwInfo);
EXPECT_THAT(pDevice, nullptr);
}
TEST(ApiOsTest, notSupportedApiTokens) {
MockContext context;
MockBuffer buffer;
cl_bool boolVal;
size_t size;
auto retVal = context.getInfo(CL_CONTEXT_D3D10_PREFER_SHARED_RESOURCES_KHR, sizeof(cl_bool), &boolVal, &size);
EXPECT_EQ(CL_INVALID_VALUE, retVal);
void *paramVal = nullptr;
retVal = buffer.getMemObjectInfo(CL_MEM_D3D10_RESOURCE_KHR, sizeof(void *), paramVal, &size);
EXPECT_EQ(CL_INVALID_VALUE, retVal);
}
TEST(ApiOsTest, notSupportedApiList) {
MockContext context;
EXPECT_EQ(nullptr, context.dispatch.crtDispatch->clGetDeviceIDsFromDX9INTEL);
EXPECT_EQ(nullptr, context.dispatch.crtDispatch->clCreateFromDX9MediaSurfaceINTEL);
EXPECT_EQ(nullptr, context.dispatch.crtDispatch->clEnqueueAcquireDX9ObjectsINTEL);
EXPECT_EQ(nullptr, context.dispatch.crtDispatch->clEnqueueReleaseDX9ObjectsINTEL);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clGetDeviceIDsFromDX9MediaAdapterKHR);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clCreateFromDX9MediaSurfaceKHR);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clEnqueueAcquireDX9MediaSurfacesKHR);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clEnqueueReleaseDX9MediaSurfacesKHR);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clGetDeviceIDsFromD3D10KHR);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clCreateFromD3D10BufferKHR);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clCreateFromD3D10Texture2DKHR);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clCreateFromD3D10Texture3DKHR);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clEnqueueAcquireD3D10ObjectsKHR);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clEnqueueReleaseD3D10ObjectsKHR);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clGetDeviceIDsFromD3D11KHR);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clCreateFromD3D11BufferKHR);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clCreateFromD3D11Texture2DKHR);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clCreateFromD3D11Texture3DKHR);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clEnqueueAcquireD3D11ObjectsKHR);
EXPECT_EQ(nullptr, context.dispatch.icdDispatch->clEnqueueReleaseD3D11ObjectsKHR);
}
TEST(DeviceOsTest, DeviceCreationFailMidThreadPreemption) {
DebugManagerStateRestore dbgRestore;
DebugManager.flags.ForcePreemptionMode.set(static_cast<int32_t>(PreemptionMode::MidThread));
auto pDevice = MockDevice::createWithNewExecutionEnvironment<FailDeviceAfterOne>(*platformDevices);
EXPECT_THAT(pDevice, nullptr);
}
} // namespace NEO

View File

@ -0,0 +1,36 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "opencl/source/device/driver_info.h"
#include "gtest/gtest.h"
#include <memory>
#include <string>
namespace NEO {
TEST(DriverInfo, GivenCreateDriverInfoWhenLinuxThenReturnNewInstance) {
std::unique_ptr<DriverInfo> driverInfo(DriverInfo::create(nullptr));
EXPECT_NE(nullptr, driverInfo.get());
}
TEST(DriverInfo, GivenDriverInfoWhenLinuxThenReturnDefault) {
std::unique_ptr<DriverInfo> driverInfo(DriverInfo::create(nullptr));
std::string defaultName = "testName";
std::string defaultVersion = "testVersion";
auto resultName = driverInfo.get()->getDeviceName(defaultName);
auto resultVersion = driverInfo.get()->getVersion(defaultVersion);
EXPECT_STREQ(defaultName.c_str(), resultName.c_str());
EXPECT_STREQ(defaultVersion.c_str(), resultVersion.c_str());
}
} // namespace NEO

View File

@ -0,0 +1,197 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/linux/drm_buffer_object.h"
#include "test.h"
#include "drm/i915_drm.h"
#include "os_interface/linux/device_command_stream_fixture.h"
#include <memory>
using namespace NEO;
class TestedBufferObject : public BufferObject {
public:
TestedBufferObject(Drm *drm) : BufferObject(drm, 1, 0) {
}
void tileBy(uint32_t mode) {
this->tiling_mode = mode;
}
void fillExecObject(drm_i915_gem_exec_object2 &execObject, uint32_t drmContextId) override {
BufferObject::fillExecObject(execObject, drmContextId);
execObjectPointerFilled = &execObject;
}
void setSize(size_t size) {
this->size = size;
}
drm_i915_gem_exec_object2 *execObjectPointerFilled = nullptr;
};
class DrmBufferObjectFixture {
public:
std::unique_ptr<DrmMockCustom> mock;
TestedBufferObject *bo;
drm_i915_gem_exec_object2 execObjectsStorage[256];
void SetUp() {
this->mock = std::make_unique<DrmMockCustom>();
ASSERT_NE(nullptr, this->mock);
bo = new TestedBufferObject(this->mock.get());
ASSERT_NE(nullptr, bo);
}
void TearDown() {
delete bo;
if (this->mock->ioctl_expected.total >= 0) {
EXPECT_EQ(this->mock->ioctl_expected.total, this->mock->ioctl_cnt.total);
}
}
};
typedef Test<DrmBufferObjectFixture> DrmBufferObjectTest;
TEST_F(DrmBufferObjectTest, exec) {
mock->ioctl_expected.total = 1;
mock->ioctl_res = 0;
drm_i915_gem_exec_object2 execObjectsStorage = {};
auto ret = bo->exec(0, 0, 0, false, 1, nullptr, 0u, &execObjectsStorage);
EXPECT_EQ(mock->ioctl_res, ret);
EXPECT_EQ(0u, mock->execBuffer.flags);
}
TEST_F(DrmBufferObjectTest, exec_ioctlFailed) {
mock->ioctl_expected.total = 1;
mock->ioctl_res = -1;
mock->errnoValue = EFAULT;
drm_i915_gem_exec_object2 execObjectsStorage = {};
EXPECT_EQ(EFAULT, bo->exec(0, 0, 0, false, 1, nullptr, 0u, &execObjectsStorage));
}
TEST_F(DrmBufferObjectTest, setTiling_success) {
mock->ioctl_expected.total = 1; //set_tiling
auto ret = bo->setTiling(I915_TILING_X, 0);
EXPECT_TRUE(ret);
}
TEST_F(DrmBufferObjectTest, setTiling_theSameTiling) {
mock->ioctl_expected.total = 0; //set_tiling
bo->tileBy(I915_TILING_X);
auto ret = bo->setTiling(I915_TILING_X, 0);
EXPECT_TRUE(ret);
}
TEST_F(DrmBufferObjectTest, setTiling_ioctlFailed) {
mock->ioctl_expected.total = 1; //set_tiling
mock->ioctl_res = -1;
auto ret = bo->setTiling(I915_TILING_X, 0);
EXPECT_FALSE(ret);
}
TEST_F(DrmBufferObjectTest, givenAddressThatWhenSizeIsAddedCrosses32BitBoundaryWhenExecIsCalledThen48BitFlagIsSet) {
drm_i915_gem_exec_object2 execObject;
memset(&execObject, 0, sizeof(execObject));
bo->setAddress(((uint64_t)1u << 32) - 0x1000u);
bo->setSize(0x1000);
bo->fillExecObject(execObject, 1);
//base address + size > size of 32bit address space
EXPECT_TRUE(execObject.flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS);
}
TEST_F(DrmBufferObjectTest, givenAddressThatWhenSizeIsAddedWithin32BitBoundaryWhenExecIsCalledThen48BitFlagSet) {
drm_i915_gem_exec_object2 execObject;
memset(&execObject, 0, sizeof(execObject));
bo->setAddress(((uint64_t)1u << 32) - 0x1000u);
bo->setSize(0xFFF);
bo->fillExecObject(execObject, 1);
//base address + size < size of 32bit address space
EXPECT_TRUE(execObject.flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS);
}
TEST_F(DrmBufferObjectTest, onPinIoctlFailed) {
std::unique_ptr<uint32_t[]> buff(new uint32_t[1024]);
mock->ioctl_expected.total = 1;
mock->ioctl_res = -1;
this->mock->errnoValue = EINVAL;
std::unique_ptr<BufferObject> boToPin(new TestedBufferObject(this->mock.get()));
ASSERT_NE(nullptr, boToPin.get());
bo->setAddress(reinterpret_cast<uint64_t>(buff.get()));
BufferObject *boArray[1] = {boToPin.get()};
auto ret = bo->pin(boArray, 1, 1);
EXPECT_EQ(EINVAL, ret);
}
TEST(DrmBufferObjectSimpleTest, givenInvalidBoWhenPinIsCalledThenErrorIsReturned) {
std::unique_ptr<uint32_t[]> buff(new uint32_t[256]);
std::unique_ptr<DrmMockCustom> mock(new DrmMockCustom);
ASSERT_NE(nullptr, mock.get());
std::unique_ptr<TestedBufferObject> bo(new TestedBufferObject(mock.get()));
ASSERT_NE(nullptr, bo.get());
// fail DRM_IOCTL_I915_GEM_EXECBUFFER2 in pin
mock->ioctl_res = -1;
std::unique_ptr<BufferObject> boToPin(new TestedBufferObject(mock.get()));
ASSERT_NE(nullptr, boToPin.get());
bo->setAddress(reinterpret_cast<uint64_t>(buff.get()));
mock->errnoValue = EFAULT;
BufferObject *boArray[1] = {boToPin.get()};
auto ret = bo->pin(boArray, 1, 1);
EXPECT_EQ(EFAULT, ret);
}
TEST(DrmBufferObjectSimpleTest, givenBufferObjectWhenConstructedWithASizeThenTheSizeIsInitialized) {
std::unique_ptr<DrmMockCustom> drmMock(new DrmMockCustom);
std::unique_ptr<BufferObject> bo(new BufferObject(drmMock.get(), 1, 0x1000, 0));
EXPECT_EQ(0x1000u, bo->peekSize());
}
TEST(DrmBufferObjectSimpleTest, givenArrayOfBosWhenPinnedThenAllBosArePinned) {
std::unique_ptr<uint32_t[]> buff(new uint32_t[256]);
std::unique_ptr<DrmMockCustom> mock(new DrmMockCustom);
ASSERT_NE(nullptr, mock.get());
std::unique_ptr<TestedBufferObject> bo(new TestedBufferObject(mock.get()));
ASSERT_NE(nullptr, bo.get());
mock->ioctl_res = 0;
std::unique_ptr<TestedBufferObject> boToPin(new TestedBufferObject(mock.get()));
std::unique_ptr<TestedBufferObject> boToPin2(new TestedBufferObject(mock.get()));
std::unique_ptr<TestedBufferObject> boToPin3(new TestedBufferObject(mock.get()));
ASSERT_NE(nullptr, boToPin.get());
ASSERT_NE(nullptr, boToPin2.get());
ASSERT_NE(nullptr, boToPin3.get());
BufferObject *array[3] = {boToPin.get(), boToPin2.get(), boToPin3.get()};
bo->setAddress(reinterpret_cast<uint64_t>(buff.get()));
auto ret = bo->pin(array, 3, 1);
EXPECT_EQ(mock->ioctl_res, ret);
uint32_t bb_end = 0x05000000;
EXPECT_EQ(buff[0], bb_end);
EXPECT_LT(0u, mock->execBuffer.batch_len);
EXPECT_EQ(4u, mock->execBuffer.buffer_count); // 3 bos to pin plus 1 exec bo
EXPECT_EQ(reinterpret_cast<uintptr_t>(boToPin->execObjectPointerFilled), mock->execBuffer.buffers_ptr);
EXPECT_NE(nullptr, boToPin2->execObjectPointerFilled);
EXPECT_NE(nullptr, boToPin3->execObjectPointerFilled);
bo->setAddress(0llu);
}

View File

@ -0,0 +1,152 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/command_stream/preemption.h"
#include "core/os_interface/linux/os_context_linux.h"
#include "core/os_interface/linux/os_interface.h"
#include "core/unit_tests/helpers/debug_manager_state_restore.h"
#include "opencl/source/os_interface/linux/drm_command_stream.h"
#include "test.h"
#include "fixtures/device_fixture.h"
#include "gmock/gmock.h"
#include "mocks/linux/mock_drm_command_stream_receiver.h"
#include "os_interface/linux/device_command_stream_fixture.h"
#include <algorithm>
class DrmCommandStreamTest : public ::testing::Test {
public:
template <typename GfxFamily>
void SetUpT() {
//make sure this is disabled, we don't want to test this now
DebugManager.flags.EnableForcePin.set(false);
mock = new ::testing::NiceMock<DrmMockImpl>(mockFd);
executionEnvironment.setHwInfo(*platformDevices);
executionEnvironment.prepareRootDeviceEnvironments(1);
executionEnvironment.rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
executionEnvironment.rootDeviceEnvironments[0]->osInterface->get()->setDrm(mock);
osContext = std::make_unique<OsContextLinux>(*mock, 0u, 1, HwHelper::get(platformDevices[0]->platform.eRenderCoreFamily).getGpgpuEngineInstances()[0],
PreemptionHelper::getDefaultPreemptionMode(*platformDevices[0]), false);
csr = new DrmCommandStreamReceiver<GfxFamily>(executionEnvironment, 0, gemCloseWorkerMode::gemCloseWorkerActive);
ASSERT_NE(nullptr, csr);
csr->setupContext(*osContext);
// Memory manager creates pinBB with ioctl, expect one call
EXPECT_CALL(*mock, ioctl(::testing::_, ::testing::_))
.Times(1);
memoryManager = new DrmMemoryManager(gemCloseWorkerMode::gemCloseWorkerActive,
DebugManager.flags.EnableForcePin.get(),
true,
executionEnvironment);
executionEnvironment.memoryManager.reset(memoryManager);
::testing::Mock::VerifyAndClearExpectations(mock);
//assert we have memory manager
ASSERT_NE(nullptr, memoryManager);
}
template <typename GfxFamily>
void TearDownT() {
memoryManager->waitForDeletions();
memoryManager->peekGemCloseWorker()->close(true);
delete csr;
::testing::Mock::VerifyAndClearExpectations(mock);
// Memory manager closes pinBB with ioctl, expect one call
EXPECT_CALL(*mock, ioctl(::testing::_, ::testing::_))
.Times(::testing::AtLeast(1));
}
CommandStreamReceiver *csr = nullptr;
DrmMemoryManager *memoryManager = nullptr;
::testing::NiceMock<DrmMockImpl> *mock;
const int mockFd = 33;
static const uint64_t alignment = MemoryConstants::allocationAlignment;
DebugManagerStateRestore dbgState;
ExecutionEnvironment executionEnvironment;
std::unique_ptr<OsContextLinux> osContext;
};
class DrmCommandStreamEnhancedTest : public ::testing::Test {
public:
std::unique_ptr<DebugManagerStateRestore> dbgState;
ExecutionEnvironment *executionEnvironment;
DrmMockCustom *mock;
CommandStreamReceiver *csr = nullptr;
DrmMemoryManager *mm = nullptr;
std::unique_ptr<MockDevice> device;
template <typename GfxFamily>
void SetUpT() {
executionEnvironment = new ExecutionEnvironment;
executionEnvironment->incRefInternal();
executionEnvironment->setHwInfo(*platformDevices);
executionEnvironment->prepareRootDeviceEnvironments(1);
executionEnvironment->initGmm();
this->dbgState = std::make_unique<DebugManagerStateRestore>();
//make sure this is disabled, we don't want to test this now
DebugManager.flags.EnableForcePin.set(false);
mock = new DrmMockCustom();
executionEnvironment->rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setDrm(mock);
csr = new TestedDrmCommandStreamReceiver<GfxFamily>(*executionEnvironment);
ASSERT_NE(nullptr, csr);
mm = new DrmMemoryManager(gemCloseWorkerMode::gemCloseWorkerInactive,
DebugManager.flags.EnableForcePin.get(),
true,
*executionEnvironment);
ASSERT_NE(nullptr, mm);
executionEnvironment->memoryManager.reset(mm);
device.reset(MockDevice::create<MockDevice>(executionEnvironment, 0u));
device->resetCommandStreamReceiver(csr);
ASSERT_NE(nullptr, device);
}
template <typename GfxFamily>
void TearDownT() {
executionEnvironment->decRefInternal();
}
template <typename GfxFamily>
void makeResidentBufferObjects(const DrmAllocation *drmAllocation) {
static_cast<TestedDrmCommandStreamReceiver<GfxFamily> *>(csr)->makeResidentBufferObjects(drmAllocation, 0u);
}
template <typename GfxFamily>
bool isResident(BufferObject *bo) const {
auto &residency = this->getResidencyVector<GfxFamily>();
return std::find(residency.begin(), residency.end(), bo) != residency.end();
}
template <typename GfxFamily>
const std::vector<BufferObject *> &getResidencyVector() const {
return static_cast<const TestedDrmCommandStreamReceiver<GfxFamily> *>(csr)->residency;
}
protected:
class MockBufferObject : public BufferObject {
friend DrmCommandStreamEnhancedTest;
protected:
MockBufferObject(Drm *drm, size_t size) : BufferObject(drm, 1, 0) {
this->size = alignUp(size, 4096);
}
};
MockBufferObject *createBO(size_t size) {
return new MockBufferObject(this->mock, size);
}
};

View File

@ -0,0 +1,84 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/execution_environment/root_device_environment.h"
#include "core/os_interface/linux/drm_memory_manager.h"
#include "core/os_interface/linux/drm_memory_operations_handler.h"
#include "core/os_interface/linux/os_interface.h"
#include "core/unit_tests/helpers/debug_manager_state_restore.h"
#include "opencl/source/os_interface/linux/drm_command_stream.h"
#include "opencl/source/platform/platform.h"
#include "test.h"
#include "mocks/linux/mock_drm_memory_manager.h"
#include "mocks/mock_execution_environment.h"
#include "os_interface/linux/device_command_stream_fixture.h"
using namespace NEO;
class DrmCommandStreamMMTest : public ::testing::Test {
};
HWTEST_F(DrmCommandStreamMMTest, MMwithPinBB) {
DebugManagerStateRestore dbgRestorer;
DebugManager.flags.EnableForcePin.set(true);
auto drm = new DrmMockCustom();
MockExecutionEnvironment executionEnvironment;
executionEnvironment.rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
executionEnvironment.rootDeviceEnvironments[0]->osInterface->get()->setDrm(drm);
executionEnvironment.rootDeviceEnvironments[0]->memoryOperationsInterface = std::make_unique<DrmMemoryOperationsHandler>();
DrmCommandStreamReceiver<FamilyType> csr(executionEnvironment, 0, gemCloseWorkerMode::gemCloseWorkerInactive);
auto memoryManager = new TestedDrmMemoryManager(false, true, false, executionEnvironment);
executionEnvironment.memoryManager.reset(memoryManager);
ASSERT_NE(nullptr, memoryManager);
EXPECT_NE(nullptr, memoryManager->pinBBs.at(0));
}
HWTEST_F(DrmCommandStreamMMTest, givenForcePinDisabledWhenMemoryManagerIsCreatedThenPinBBIsCreated) {
DebugManagerStateRestore dbgRestorer;
DebugManager.flags.EnableForcePin.set(false);
auto drm = new DrmMockCustom();
MockExecutionEnvironment executionEnvironment;
executionEnvironment.setHwInfo(*platformDevices);
executionEnvironment.rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
executionEnvironment.rootDeviceEnvironments[0]->osInterface->get()->setDrm(drm);
DrmCommandStreamReceiver<FamilyType> csr(executionEnvironment, 0, gemCloseWorkerMode::gemCloseWorkerInactive);
auto memoryManager = new TestedDrmMemoryManager(false, true, false, executionEnvironment);
executionEnvironment.memoryManager.reset(memoryManager);
ASSERT_NE(nullptr, memoryManager);
EXPECT_NE(nullptr, memoryManager->pinBBs.at(0));
}
HWTEST_F(DrmCommandStreamMMTest, givenExecutionEnvironmentWithMoreThanOneRootDeviceEnvWhenCreatingDrmMemoryManagerThenCreateAsManyPinBBs) {
DebugManagerStateRestore dbgRestorer;
MockExecutionEnvironment executionEnvironment;
executionEnvironment.prepareRootDeviceEnvironments(2);
executionEnvironment.setHwInfo(*platformDevices);
for (uint32_t rootDeviceIndex = 0; rootDeviceIndex < executionEnvironment.rootDeviceEnvironments.size(); rootDeviceIndex++) {
executionEnvironment.rootDeviceEnvironments[rootDeviceIndex]->osInterface = std::make_unique<OSInterface>();
executionEnvironment.rootDeviceEnvironments[rootDeviceIndex]->osInterface->get()->setDrm(new DrmMockCustom());
executionEnvironment.rootDeviceEnvironments[rootDeviceIndex]->memoryOperationsInterface = std::make_unique<DrmMemoryOperationsHandler>();
}
auto memoryManager = new TestedDrmMemoryManager(false, true, false, executionEnvironment);
executionEnvironment.memoryManager.reset(memoryManager);
ASSERT_NE(nullptr, memoryManager);
for (uint32_t rootDeviceIndex = 0; rootDeviceIndex < executionEnvironment.rootDeviceEnvironments.size(); rootDeviceIndex++) {
EXPECT_NE(nullptr, memoryManager->pinBBs.at(rootDeviceIndex));
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,34 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "gtest/gtest.h"
#include "os_interface/linux/drm_mock.h"
using namespace NEO;
TEST(DrmTest, whenQueryingDrmThenNullIsReturnedAndNoIoctlIsCalled) {
std::unique_ptr<DrmMock> drm = std::make_unique<DrmMock>();
EXPECT_NE(nullptr, drm);
EXPECT_EQ(nullptr, drm->query(1));
EXPECT_EQ(0u, drm->ioctlCallsCount);
}
TEST(DrmTest, whenQueryingEngineInfoThenNoIoctlIsCalled) {
std::unique_ptr<DrmMock> drm = std::make_unique<DrmMock>();
EXPECT_NE(nullptr, drm);
drm->queryEngineInfo();
EXPECT_EQ(0u, drm->ioctlCallsCount);
}
TEST(EngineInfoTest, givenEngineInfoImplementationWhenDestructingThenDestructorIsCalled) {
struct EngineInfoImpl : EngineInfo {
~EngineInfoImpl() override = default;
};
EngineInfoImpl engineInfo;
}

View File

@ -0,0 +1,190 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/execution_environment/execution_environment.h"
#include "core/helpers/aligned_memory.h"
#include "core/os_interface/linux/drm_buffer_object.h"
#include "core/os_interface/linux/drm_gem_close_worker.h"
#include "core/os_interface/linux/drm_memory_manager.h"
#include "core/os_interface/linux/drm_memory_operations_handler.h"
#include "core/os_interface/linux/os_interface.h"
#include "opencl/source/command_stream/device_command_stream.h"
#include "opencl/source/mem_obj/buffer.h"
#include "opencl/source/os_interface/linux/drm_command_stream.h"
#include "test.h"
#include "drm/i915_drm.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "mocks/mock_execution_environment.h"
#include "os_interface/linux/device_command_stream_fixture.h"
#include <iostream>
#include <memory>
#include <mutex>
#include <thread>
using namespace NEO;
class DrmMockForWorker : public Drm {
public:
std::mutex mutex;
std::atomic<int> gem_close_cnt;
std::atomic<int> gem_close_expected;
std::atomic<std::thread::id> ioctl_caller_thread_id;
DrmMockForWorker() : Drm(std::make_unique<HwDeviceId>(33), *platform()->peekExecutionEnvironment()->rootDeviceEnvironments[0]) {
}
int ioctl(unsigned long request, void *arg) override {
if (_IOC_TYPE(request) == DRM_IOCTL_BASE) {
//when drm ioctl is called, try acquire mutex
//main thread can hold mutex, to prevent ioctl handling
std::lock_guard<std::mutex> lock(mutex);
}
if (request == DRM_IOCTL_GEM_CLOSE)
gem_close_cnt++;
ioctl_caller_thread_id = std::this_thread::get_id();
return 0;
};
};
class DrmGemCloseWorkerFixture {
public:
DrmGemCloseWorkerFixture() : executionEnvironment(*platformDevices){};
//max loop count for while
static const uint32_t deadCntInit = 10 * 1000 * 1000;
DrmMemoryManager *mm;
DrmMockForWorker *drmMock;
uint32_t deadCnt = deadCntInit;
void SetUp() {
this->drmMock = new DrmMockForWorker;
this->drmMock->gem_close_cnt = 0;
this->drmMock->gem_close_expected = 0;
executionEnvironment.rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
executionEnvironment.rootDeviceEnvironments[0]->osInterface->get()->setDrm(drmMock);
executionEnvironment.rootDeviceEnvironments[0]->memoryOperationsInterface = std::make_unique<DrmMemoryOperationsHandler>();
this->mm = new DrmMemoryManager(gemCloseWorkerMode::gemCloseWorkerInactive,
false,
false,
executionEnvironment);
}
void TearDown() {
if (this->drmMock->gem_close_expected >= 0) {
EXPECT_EQ(this->drmMock->gem_close_expected, this->drmMock->gem_close_cnt);
}
delete this->mm;
}
protected:
class DrmAllocationWrapper : public DrmAllocation {
public:
DrmAllocationWrapper(BufferObject *bo)
: DrmAllocation(0, GraphicsAllocation::AllocationType::UNKNOWN, bo, nullptr, 0, (osHandle)0u, MemoryPool::MemoryNull) {
}
};
MockExecutionEnvironment executionEnvironment;
};
typedef Test<DrmGemCloseWorkerFixture> DrmGemCloseWorkerTests;
TEST_F(DrmGemCloseWorkerTests, gemClose) {
this->drmMock->gem_close_expected = 1;
auto worker = new DrmGemCloseWorker(*mm);
auto bo = new BufferObject(this->drmMock, 1, 0);
worker->push(bo);
delete worker;
}
TEST_F(DrmGemCloseWorkerTests, gemCloseExit) {
this->drmMock->gem_close_expected = -1;
auto worker = new DrmGemCloseWorker(*mm);
auto bo = new BufferObject(this->drmMock, 1, 0);
worker->push(bo);
//wait for worker to complete or deadCnt drops
while (!worker->isEmpty() && (deadCnt-- > 0))
pthread_yield(); //yield to another threads
worker->close(false);
//and check if GEM was closed
EXPECT_EQ(1, this->drmMock->gem_close_cnt.load());
delete worker;
}
TEST_F(DrmGemCloseWorkerTests, close) {
this->drmMock->gem_close_expected = -1;
auto worker = new DrmGemCloseWorker(*mm);
auto bo = new BufferObject(this->drmMock, 1, 0);
worker->push(bo);
worker->close(false);
//wait for worker to complete or deadCnt drops
while (!worker->isEmpty() && (deadCnt-- > 0))
pthread_yield(); //yield to another threads
//and check if GEM was closed
EXPECT_EQ(1, this->drmMock->gem_close_cnt.load());
delete worker;
}
TEST_F(DrmGemCloseWorkerTests, givenAllocationWhenAskedForUnreferenceWithForceFlagSetThenAllocationIsReleasedFromCallingThread) {
this->drmMock->gem_close_expected = 1;
auto worker = new DrmGemCloseWorker(*mm);
auto bo = new BufferObject(this->drmMock, 1, 0);
bo->reference();
worker->push(bo);
auto r = mm->unreference(bo, true);
EXPECT_EQ(1u, r);
EXPECT_EQ(drmMock->ioctl_caller_thread_id, std::this_thread::get_id());
delete worker;
}
TEST_F(DrmGemCloseWorkerTests, givenDrmGemCloseWorkerWhenCloseIsCalledWithBlockingFlagThenThreadIsClosed) {
struct mockDrmGemCloseWorker : DrmGemCloseWorker {
using DrmGemCloseWorker::DrmGemCloseWorker;
using DrmGemCloseWorker::thread;
};
std::unique_ptr<mockDrmGemCloseWorker> worker(new mockDrmGemCloseWorker(*mm));
EXPECT_NE(nullptr, worker->thread);
worker->close(true);
EXPECT_EQ(nullptr, worker->thread);
}
TEST_F(DrmGemCloseWorkerTests, givenDrmGemCloseWorkerWhenCloseIsCalledMultipleTimeWithBlockingFlagThenThreadIsClosed) {
struct mockDrmGemCloseWorker : DrmGemCloseWorker {
using DrmGemCloseWorker::DrmGemCloseWorker;
using DrmGemCloseWorker::thread;
};
std::unique_ptr<mockDrmGemCloseWorker> worker(new mockDrmGemCloseWorker(*mm));
worker->close(true);
worker->close(true);
worker->close(true);
EXPECT_EQ(nullptr, worker->thread);
}

View File

@ -0,0 +1,29 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/linux/drm_engine_mapper.h"
#include "test.h"
#include "drm/i915_drm.h"
using namespace NEO;
TEST(DrmMapperTests, engineNodeMapPass) {
unsigned int rcsFlag = DrmEngineMapper::engineNodeMap(aub_stream::ENGINE_RCS);
unsigned int bcsFlag = DrmEngineMapper::engineNodeMap(aub_stream::ENGINE_BCS);
unsigned int ccsFlag = DrmEngineMapper::engineNodeMap(aub_stream::ENGINE_CCS);
unsigned int expectedRcsFlag = I915_EXEC_RENDER;
unsigned int expectedBcsFlag = I915_EXEC_BLT;
unsigned int expectedCcsFlag = I915_EXEC_COMPUTE;
EXPECT_EQ(expectedRcsFlag, rcsFlag);
EXPECT_EQ(expectedBcsFlag, bcsFlag);
EXPECT_EQ(expectedCcsFlag, ccsFlag);
}
TEST(DrmMapperTests, engineNodeMapNegative) {
EXPECT_THROW(DrmEngineMapper::engineNodeMap(aub_stream::ENGINE_VCS), std::exception);
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/linux/memory_info.h"
#include "gtest/gtest.h"
#include "os_interface/linux/drm_mock.h"
using namespace NEO;
struct MemoryInfoImpl : public NEO::MemoryInfo {
MemoryInfoImpl() {}
~MemoryInfoImpl() override{};
};
TEST(DrmTest, whenQueryingEngineInfoThenEngineInfoIsNotCreatedAndNoIoctlsAreCalled) {
std::unique_ptr<DrmMock> drm = std::make_unique<DrmMock>();
EXPECT_NE(nullptr, drm);
EXPECT_TRUE(drm->queryEngineInfo());
EXPECT_EQ(nullptr, drm->engineInfo.get());
EXPECT_EQ(0u, drm->ioctlCallsCount);
}
TEST(DrmTest, whenQueryingMemoryInfoThenMemoryInfoIsNotCreatedAndNoIoctlsAreCalled) {
std::unique_ptr<DrmMock> drm = std::make_unique<DrmMock>();
EXPECT_NE(nullptr, drm);
EXPECT_TRUE(drm->queryMemoryInfo());
EXPECT_EQ(nullptr, drm->memoryInfo.get());
EXPECT_EQ(0u, drm->ioctlCallsCount);
}
TEST(DrmTest, givenMemoryInfoWhenGetMemoryInfoIsCalledThenValidPtrIsReturned) {
std::unique_ptr<DrmMock> drm = std::make_unique<DrmMock>();
EXPECT_NE(nullptr, drm);
drm->memoryInfo.reset(new MemoryInfoImpl);
EXPECT_EQ(drm->memoryInfo.get(), drm->getMemoryInfo());
}
TEST(MemoryInfo, givenMemoryInfoImplementationWhenDestructingThenDestructorIsCalled) {
MemoryInfoImpl memoryInfoImpl;
}
TEST(MemoryInfo, givenMemoryRegionIdWhenGetMemoryTypeFromRegionAndGetInstanceFromRegionAreCalledThenMemoryTypeAndInstanceAreReturned) {
std::unique_ptr<DrmMock> drm = std::make_unique<DrmMock>();
EXPECT_NE(nullptr, drm);
auto regionSmem = drm->createMemoryRegionId(0, 0);
EXPECT_EQ(0u, drm->getMemoryTypeFromRegion(regionSmem));
EXPECT_EQ(0u, drm->getInstanceFromRegion(regionSmem));
auto regionLmem = drm->createMemoryRegionId(1, 0);
EXPECT_EQ(1u, drm->getMemoryTypeFromRegion(regionLmem));
EXPECT_EQ(0u, drm->getInstanceFromRegion(regionLmem));
auto regionLmem1 = drm->createMemoryRegionId(1, 1);
EXPECT_EQ(1u, drm->getMemoryTypeFromRegion(regionLmem1));
EXPECT_EQ(1u, drm->getInstanceFromRegion(regionLmem1));
auto regionLmem2 = drm->createMemoryRegionId(1, 2);
EXPECT_EQ(1u, drm->getMemoryTypeFromRegion(regionLmem2));
EXPECT_EQ(2u, drm->getInstanceFromRegion(regionLmem2));
auto regionLmem3 = drm->createMemoryRegionId(1, 3);
EXPECT_EQ(1u, drm->getMemoryTypeFromRegion(regionLmem3));
EXPECT_EQ(3u, drm->getInstanceFromRegion(regionLmem3));
}

View File

@ -0,0 +1,94 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/execution_environment/execution_environment.h"
#include "core/os_interface/linux/drm_memory_manager.h"
#include "core/os_interface/linux/os_interface.h"
#include "test.h"
#include "gtest/gtest.h"
#include "mocks/linux/mock_drm_memory_manager.h"
#include "mocks/mock_execution_environment.h"
#include "os_interface/linux/drm_memory_manager_tests.h"
using namespace NEO;
using AllocationData = TestedDrmMemoryManager::AllocationData;
TEST(DrmMemoryManagerSimpleTest, givenDrmMemoryManagerWhenAllocateInDevicePoolIsCalledThenNullptrAndStatusRetryIsReturned) {
MockExecutionEnvironment executionEnvironment(*platformDevices);
executionEnvironment.rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
executionEnvironment.rootDeviceEnvironments[0]->osInterface->get()->setDrm(Drm::create(nullptr, *executionEnvironment.rootDeviceEnvironments[0]));
TestedDrmMemoryManager memoryManager(executionEnvironment);
MemoryManager::AllocationStatus status = MemoryManager::AllocationStatus::Success;
AllocationData allocData;
allocData.size = MemoryConstants::pageSize;
allocData.flags.useSystemMemory = true;
allocData.flags.allocateMemory = true;
auto allocation = memoryManager.allocateGraphicsMemoryInDevicePool(allocData, status);
EXPECT_EQ(nullptr, allocation);
EXPECT_EQ(MemoryManager::AllocationStatus::RetryInNonDevicePool, status);
}
TEST(DrmMemoryManagerSimpleTest, givenDrmMemoryManagerWhenLockResourceIsCalledOnNullBufferObjectThenReturnNullPtr) {
MockExecutionEnvironment executionEnvironment(*platformDevices);
executionEnvironment.rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
TestedDrmMemoryManager memoryManager(executionEnvironment);
DrmAllocation drmAllocation(0, GraphicsAllocation::AllocationType::UNKNOWN, nullptr, nullptr, 0u, 0u, MemoryPool::LocalMemory);
auto ptr = memoryManager.lockResourceInLocalMemoryImpl(drmAllocation.getBO());
EXPECT_EQ(nullptr, ptr);
memoryManager.unlockResourceInLocalMemoryImpl(drmAllocation.getBO());
}
TEST(DrmMemoryManagerSimpleTest, givenDrmMemoryManagerWhenFreeGraphicsMemoryIsCalledOnAllocationWithNullBufferObjectThenEarlyReturn) {
MockExecutionEnvironment executionEnvironment(*platformDevices);
executionEnvironment.rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
TestedDrmMemoryManager memoryManager(executionEnvironment);
auto drmAllocation = new DrmAllocation(0, GraphicsAllocation::AllocationType::UNKNOWN, nullptr, nullptr, 0u, 0u, MemoryPool::LocalMemory);
EXPECT_NE(nullptr, drmAllocation);
memoryManager.freeGraphicsMemoryImpl(drmAllocation);
}
using DrmMemoryManagerWithLocalMemoryTest = Test<DrmMemoryManagerWithLocalMemoryFixture>;
TEST_F(DrmMemoryManagerWithLocalMemoryTest, givenDrmMemoryManagerWithLocalMemoryWhenLockResourceIsCalledOnAllocationInLocalMemoryThenReturnNullPtr) {
DrmAllocation drmAllocation(0, GraphicsAllocation::AllocationType::UNKNOWN, nullptr, nullptr, 0u, 0u, MemoryPool::LocalMemory);
auto ptr = memoryManager->lockResource(&drmAllocation);
EXPECT_EQ(nullptr, ptr);
memoryManager->unlockResource(&drmAllocation);
}
using DrmMemoryManagerTest = Test<DrmMemoryManagerFixture>;
TEST_F(DrmMemoryManagerTest, givenDrmMemoryManagerWhenCopyMemoryToAllocationThenAllocationIsFilledWithCorrectData) {
mock->ioctl_expected.gemUserptr = 1;
mock->ioctl_expected.gemWait = 1;
mock->ioctl_expected.gemClose = 1;
std::vector<uint8_t> dataToCopy(MemoryConstants::pageSize, 1u);
auto allocation = memoryManager->allocateGraphicsMemoryWithProperties({0, dataToCopy.size(), GraphicsAllocation::AllocationType::BUFFER});
ASSERT_NE(nullptr, allocation);
auto ret = memoryManager->copyMemoryToAllocation(allocation, dataToCopy.data(), dataToCopy.size());
EXPECT_TRUE(ret);
EXPECT_EQ(0, memcmp(allocation->getUnderlyingBuffer(), dataToCopy.data(), dataToCopy.size()));
memoryManager->freeGraphicsMemory(allocation);
}
TEST_F(DrmMemoryManagerTest, givenDrmMemoryManagerWhenGetLocalMemoryIsCalledThenSizeOfLocalMemoryIsReturned) {
EXPECT_EQ(0 * GB, memoryManager->getLocalMemorySize(0u));
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,118 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/os_interface/linux/drm_memory_operations_handler.h"
#include "core/os_interface/linux/os_interface.h"
#include "fixtures/memory_management_fixture.h"
#include "mocks/linux/mock_drm_memory_manager.h"
#include "mocks/mock_device.h"
#include "mocks/mock_execution_environment.h"
#include "os_interface/linux/device_command_stream_fixture.h"
#include <memory>
namespace NEO {
using AllocationData = TestedDrmMemoryManager::AllocationData;
class DrmMemoryManagerBasic : public ::testing::Test {
public:
DrmMemoryManagerBasic() : executionEnvironment(*platformDevices){};
void SetUp() override {
executionEnvironment.rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
executionEnvironment.rootDeviceEnvironments[0]->osInterface->get()->setDrm(Drm::create(nullptr, *executionEnvironment.rootDeviceEnvironments[0]));
executionEnvironment.rootDeviceEnvironments[0]->memoryOperationsInterface = std::make_unique<DrmMemoryOperationsHandler>();
}
MockExecutionEnvironment executionEnvironment;
};
class DrmMemoryManagerFixture : public MemoryManagementFixture {
public:
DrmMockCustom *mock;
TestedDrmMemoryManager *memoryManager = nullptr;
MockClDevice *device = nullptr;
void SetUp() override {
MemoryManagementFixture::SetUp();
SetUp(new DrmMockCustom, false);
}
void SetUp(DrmMockCustom *mock, bool localMemoryEnabled) {
this->mock = mock;
executionEnvironment = new MockExecutionEnvironment(*platformDevices);
executionEnvironment->incRefInternal();
executionEnvironment->rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setDrm(mock);
memoryManager = new (std::nothrow) TestedDrmMemoryManager(localMemoryEnabled, false, false, *executionEnvironment);
//assert we have memory manager
ASSERT_NE(nullptr, memoryManager);
if (memoryManager->getgemCloseWorker()) {
memoryManager->getgemCloseWorker()->close(true);
}
device = new MockClDevice{MockDevice::createWithExecutionEnvironment<MockDevice>(*platformDevices, executionEnvironment, 0)};
}
void TearDown() override {
delete device;
delete memoryManager;
this->mock->testIoctls();
executionEnvironment->decRefInternal();
MemoryManagementFixture::TearDown();
}
protected:
ExecutionEnvironment *executionEnvironment;
DrmMockCustom::IoctlResExt ioctlResExt = {0, 0};
AllocationData allocationData;
};
class DrmMemoryManagerWithLocalMemoryFixture : public DrmMemoryManagerFixture {
public:
void SetUp() override {
MemoryManagementFixture::SetUp();
DrmMemoryManagerFixture::SetUp(new DrmMockCustom, true);
}
void TearDown() override {
DrmMemoryManagerFixture::TearDown();
}
};
class DrmMemoryManagerFixtureWithoutQuietIoctlExpectation {
public:
std::unique_ptr<TestedDrmMemoryManager> memoryManager;
DrmMockCustom *mock;
void SetUp() {
executionEnvironment = new ExecutionEnvironment;
executionEnvironment->setHwInfo(*platformDevices);
executionEnvironment->prepareRootDeviceEnvironments(1);
mock = new DrmMockCustom();
executionEnvironment->rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setDrm(mock);
memoryManager.reset(new TestedDrmMemoryManager(*executionEnvironment));
ASSERT_NE(nullptr, memoryManager);
if (memoryManager->getgemCloseWorker()) {
memoryManager->getgemCloseWorker()->close(true);
}
device.reset(MockDevice::createWithExecutionEnvironment<MockDevice>(*platformDevices, executionEnvironment, 0));
}
void TearDown() {
}
protected:
ExecutionEnvironment *executionEnvironment = nullptr;
std::unique_ptr<MockDevice> device;
DrmMockCustom::IoctlResExt ioctlResExt = {0, 0};
};
} // namespace NEO

View File

@ -0,0 +1,161 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "os_interface/linux/drm_mock.h"
const int DrmMock::mockFd;
int DrmMock::ioctl(unsigned long request, void *arg) {
ioctlCallsCount++;
if ((request == DRM_IOCTL_I915_GETPARAM) && (arg != nullptr)) {
auto gp = static_cast<drm_i915_getparam_t *>(arg);
if (gp->param == I915_PARAM_EU_TOTAL) {
if (0 == this->StoredRetValForEUVal) {
*gp->value = this->StoredEUVal;
}
return this->StoredRetValForEUVal;
}
if (gp->param == I915_PARAM_SUBSLICE_TOTAL) {
if (0 == this->StoredRetValForSSVal) {
*gp->value = this->StoredSSVal;
}
return this->StoredRetValForSSVal;
}
if (gp->param == I915_PARAM_CHIPSET_ID) {
if (0 == this->StoredRetValForDeviceID) {
*gp->value = this->StoredDeviceID;
}
return this->StoredRetValForDeviceID;
}
if (gp->param == I915_PARAM_REVISION) {
if (0 == this->StoredRetValForDeviceRevID) {
*gp->value = this->StoredDeviceRevID;
}
return this->StoredRetValForDeviceRevID;
}
if (gp->param == I915_PARAM_HAS_POOLED_EU) {
if (0 == this->StoredRetValForPooledEU) {
*gp->value = this->StoredHasPooledEU;
}
return this->StoredRetValForPooledEU;
}
if (gp->param == I915_PARAM_MIN_EU_IN_POOL) {
if (0 == this->StoredRetValForMinEUinPool) {
*gp->value = this->StoredMinEUinPool;
}
return this->StoredRetValForMinEUinPool;
}
if (gp->param == I915_PARAM_HAS_SCHEDULER) {
*gp->value = this->StoredPreemptionSupport;
return this->StoredRetVal;
}
if (gp->param == I915_PARAM_HAS_EXEC_SOFTPIN) {
*gp->value = this->StoredExecSoftPin;
return this->StoredRetVal;
}
}
if ((request == DRM_IOCTL_I915_GEM_CONTEXT_CREATE) && (arg != nullptr)) {
auto create = static_cast<drm_i915_gem_context_create *>(arg);
create->ctx_id = this->StoredCtxId;
return this->StoredRetVal;
}
if ((request == DRM_IOCTL_I915_GEM_CONTEXT_DESTROY) && (arg != nullptr)) {
auto destroy = static_cast<drm_i915_gem_context_destroy *>(arg);
this->receivedDestroyContextId = destroy->ctx_id;
return this->StoredRetVal;
}
if ((request == DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM) && (arg != nullptr)) {
receivedContextParamRequestCount++;
receivedContextParamRequest = *static_cast<drm_i915_gem_context_param *>(arg);
if (receivedContextParamRequest.param == I915_CONTEXT_PARAM_PRIORITY) {
return this->StoredRetVal;
}
if ((receivedContextParamRequest.param == I915_CONTEXT_PRIVATE_PARAM_BOOST) && (receivedContextParamRequest.value == 1)) {
return this->StoredRetVal;
}
if (receivedContextParamRequest.param == I915_CONTEXT_PARAM_SSEU) {
if (StoredRetValForSetSSEU == 0) {
storedParamSseu = (*static_cast<drm_i915_gem_context_param_sseu *>(reinterpret_cast<void *>(receivedContextParamRequest.value))).slice_mask;
}
return this->StoredRetValForSetSSEU;
}
if (receivedContextParamRequest.param == I915_CONTEXT_PARAM_PERSISTENCE) {
return this->StoredRetValForPersistant;
}
}
if ((request == DRM_IOCTL_I915_GEM_CONTEXT_GETPARAM) && (arg != nullptr)) {
receivedContextParamRequestCount++;
receivedContextParamRequest = *static_cast<drm_i915_gem_context_param *>(arg);
if (receivedContextParamRequest.param == I915_CONTEXT_PARAM_GTT_SIZE) {
static_cast<drm_i915_gem_context_param *>(arg)->value = this->storedGTTSize;
return this->StoredRetValForGetGttSize;
}
if (receivedContextParamRequest.param == I915_CONTEXT_PARAM_SSEU) {
if (StoredRetValForGetSSEU == 0) {
(*static_cast<drm_i915_gem_context_param_sseu *>(reinterpret_cast<void *>(receivedContextParamRequest.value))).slice_mask = storedParamSseu;
}
return this->StoredRetValForGetSSEU;
}
if (receivedContextParamRequest.param == I915_CONTEXT_PARAM_PERSISTENCE) {
static_cast<drm_i915_gem_context_param *>(arg)->value = this->StoredPersistentContextsSupport;
return this->StoredRetValForPersistant;
}
}
if (request == DRM_IOCTL_I915_GEM_EXECBUFFER2) {
auto execbuf = static_cast<drm_i915_gem_execbuffer2 *>(arg);
this->execBuffer = *execbuf;
return 0;
}
if (request == DRM_IOCTL_I915_GEM_USERPTR) {
auto userPtrParams = static_cast<drm_i915_gem_userptr *>(arg);
userPtrParams->handle = returnHandle;
returnHandle++;
return 0;
}
if (request == DRM_IOCTL_I915_GEM_CREATE) {
auto createParams = static_cast<drm_i915_gem_create *>(arg);
this->createParamsSize = createParams->size;
this->createParamsHandle = createParams->handle = 1u;
return 0;
}
if (request == DRM_IOCTL_I915_GEM_SET_TILING) {
auto setTilingParams = static_cast<drm_i915_gem_set_tiling *>(arg);
setTilingMode = setTilingParams->tiling_mode;
setTilingHandle = setTilingParams->handle;
setTilingStride = setTilingParams->stride;
return 0;
}
if (request == DRM_IOCTL_PRIME_FD_TO_HANDLE) {
auto primeToHandleParams = static_cast<drm_prime_handle *>(arg);
//return BO
primeToHandleParams->handle = outputHandle;
inputFd = primeToHandleParams->fd;
return 0;
}
if (request == DRM_IOCTL_I915_GEM_GET_APERTURE) {
auto aperture = static_cast<drm_i915_gem_get_aperture *>(arg);
aperture->aper_available_size = gpuMemSize;
aperture->aper_size = gpuMemSize;
return 0;
}
if (request == DRM_IOCTL_I915_GEM_MMAP) {
auto mmap_arg = static_cast<drm_i915_gem_mmap *>(arg);
mmap_arg->addr_ptr = reinterpret_cast<__u64>(lockedPtr);
return 0;
}
if (request == DRM_IOCTL_I915_GEM_WAIT) {
return 0;
}
return handleRemainingRequests(request, arg);
}

View File

@ -0,0 +1,143 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/execution_environment/execution_environment.h"
#include "core/memory_manager/memory_constants.h"
#include "core/os_interface/linux/drm_neo.h"
#include "opencl/source/platform/platform.h"
#include "drm/i915_drm.h"
#include <cstdio>
#include <fstream>
#include <limits.h>
using namespace NEO;
// Mock DRM class that responds to DRM_IOCTL_I915_GETPARAMs
class DrmMock : public Drm {
public:
using Drm::checkQueueSliceSupport;
using Drm::engineInfo;
using Drm::getQueueSliceCount;
using Drm::memoryInfo;
using Drm::nonPersistentContextsSupported;
using Drm::preemptionSupported;
using Drm::query;
using Drm::sliceCountChangeSupported;
DrmMock(RootDeviceEnvironment &rootDeviceEnvironment) : Drm(std::make_unique<HwDeviceId>(mockFd), rootDeviceEnvironment) {
sliceCountChangeSupported = true;
}
DrmMock() : DrmMock(*platform()->peekExecutionEnvironment()->rootDeviceEnvironments[0]) {}
~DrmMock() {
if (sysFsDefaultGpuPathToRestore != nullptr) {
sysFsDefaultGpuPath = sysFsDefaultGpuPathToRestore;
}
}
int ioctl(unsigned long request, void *arg) override;
void setSysFsDefaultGpuPath(const char *path) {
sysFsDefaultGpuPathToRestore = sysFsDefaultGpuPath;
sysFsDefaultGpuPath = path;
}
void writeConfigFile(const char *name, int deviceID) {
std::ofstream tempfile(name, std::ios::binary);
if (tempfile.is_open()) {
PCIConfig config;
config.DeviceID = deviceID;
tempfile.write(reinterpret_cast<char *>(&config), sizeof(config));
tempfile.close();
}
}
void deleteConfigFile(const char *name) {
std::ofstream tempfile(name);
if (tempfile.is_open()) {
tempfile.close();
remove(name);
}
}
void setFileDescriptor(int fd) {
hwDeviceId = std::make_unique<HwDeviceId>(fd);
}
void setDeviceID(int deviceId) { this->deviceId = deviceId; }
void setDeviceRevID(int revisionId) { this->revisionId = revisionId; }
inline uint32_t createMemoryRegionId(uint16_t type, uint16_t instance) const {
return (1u << (type + 16)) | (1u << instance);
}
static inline uint16_t getMemoryTypeFromRegion(uint32_t region) { return Math::log2(region >> 16); };
static inline uint16_t getInstanceFromRegion(uint32_t region) { return Math::log2(region & 0xFFFF); };
static const int mockFd = 33;
int StoredEUVal = -1;
int StoredSSVal = -1;
int StoredDeviceID = 1;
int StoredDeviceRevID = 1;
int StoredHasPooledEU = 1;
int StoredMinEUinPool = 1;
int StoredPersistentContextsSupport = 1;
int StoredRetVal = 0;
int StoredRetValForGetGttSize = 0;
int StoredRetValForGetSSEU = 0;
int StoredRetValForSetSSEU = 0;
int StoredRetValForDeviceID = 0;
int StoredRetValForEUVal = 0;
int StoredRetValForSSVal = 0;
int StoredRetValForDeviceRevID = 0;
int StoredRetValForPooledEU = 0;
int StoredRetValForMinEUinPool = 0;
int StoredRetValForPersistant = 0;
int StoredPreemptionSupport =
I915_SCHEDULER_CAP_ENABLED |
I915_SCHEDULER_CAP_PRIORITY |
I915_SCHEDULER_CAP_PREEMPTION;
int StoredExecSoftPin = 0;
uint32_t StoredCtxId = 1;
uint32_t receivedDestroyContextId = 0;
uint32_t ioctlCallsCount = 0;
uint32_t receivedContextParamRequestCount = 0;
drm_i915_gem_context_param receivedContextParamRequest = {};
//DRM_IOCTL_I915_GEM_EXECBUFFER2
drm_i915_gem_execbuffer2 execBuffer = {0};
//DRM_IOCTL_I915_GEM_CREATE
__u64 createParamsSize = 0;
__u32 createParamsHandle = 0;
//DRM_IOCTL_I915_GEM_SET_TILING
__u32 setTilingMode = 0;
__u32 setTilingHandle = 0;
__u32 setTilingStride = 0;
//DRM_IOCTL_PRIME_FD_TO_HANDLE
__u32 outputHandle = 0;
__s32 inputFd = 0;
//DRM_IOCTL_I915_GEM_USERPTR
__u32 returnHandle = 0;
__u64 gpuMemSize = 3u * MemoryConstants::gigaByte;
//DRM_IOCTL_I915_GEM_MMAP
uint64_t lockedPtr[4];
uint64_t storedGTTSize = 1ull << 47;
uint64_t storedParamSseu = ULONG_MAX;
virtual int handleRemainingRequests(unsigned long request, void *arg) { return -1; }
private:
const char *sysFsDefaultGpuPathToRestore = nullptr;
};

View File

@ -0,0 +1,35 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "drm/i915_drm.h"
#include "os_interface/linux/drm_mock.h"
namespace NEO {
class DrmMockDefault : public DrmMock {
public:
DrmMockDefault(RootDeviceEnvironment &rootDeviceEnvironment) : DrmMock(rootDeviceEnvironment) {
StoredRetVal = 0;
StoredRetValForDeviceID = 0;
StoredRetValForEUVal = 0;
StoredRetValForSSVal = 0;
StoredRetValForDeviceRevID = 0;
StoredRetValForPooledEU = 0;
StoredRetValForMinEUinPool = 0;
setGtType(GTTYPE_GT1);
}
};
Drm **pDrmToReturnFromCreateFunc = nullptr;
Drm *Drm::create(std::unique_ptr<HwDeviceId> hwDeviceId, RootDeviceEnvironment &rootDeviceEnvironment) {
if (pDrmToReturnFromCreateFunc) {
return *pDrmToReturnFromCreateFunc;
}
return new DrmMockDefault(rootDeviceEnvironment);
}
} // namespace NEO

View File

@ -0,0 +1,40 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/linux/os_memory_linux.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using ::testing::_;
namespace NEO {
class MockOSMemoryLinux : public OSMemoryLinux {
public:
static std::unique_ptr<MockOSMemoryLinux> create() {
return std::make_unique<MockOSMemoryLinux>();
}
MOCK_METHOD6(mmapWrapper, void *(void *, size_t, int, int, int, off_t));
MOCK_METHOD2(munmapWrapper, int(void *, size_t));
};
TEST(OSMemoryLinux, givenOSMemoryLinuxWhenReserveCpuAddressRangeIsCalledThenMinusOneIsPassedToMmapAsFdParam) {
auto mockOSMemoryLinux = MockOSMemoryLinux::create();
EXPECT_CALL(*mockOSMemoryLinux, mmapWrapper(_, _, _, _, -1, _));
size_t size = 0x1024;
auto reservedCpuAddr = mockOSMemoryLinux->reserveCpuAddressRange(size);
EXPECT_CALL(*mockOSMemoryLinux, munmapWrapper(reservedCpuAddr, size));
mockOSMemoryLinux->releaseCpuAddressRange(reservedCpuAddr, size);
}
}; // namespace NEO

View File

@ -0,0 +1,38 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/linux/drm_memory_operations_handler.h"
#include "test.h"
#include "mocks/mock_graphics_allocation.h"
#include <memory>
using namespace NEO;
struct DrmMemoryOperationsHandlerTest : public ::testing::Test {
void SetUp() override {
drmMemoryOperationsHandler = std::make_unique<DrmMemoryOperationsHandler>();
allocationPtr = &graphicsAllocation;
}
MockGraphicsAllocation graphicsAllocation;
GraphicsAllocation *allocationPtr;
std::unique_ptr<DrmMemoryOperationsHandler> drmMemoryOperationsHandler;
};
TEST_F(DrmMemoryOperationsHandlerTest, whenMakingResidentAllocaionExpectMakeResidentFail) {
EXPECT_EQ(drmMemoryOperationsHandler->makeResident(ArrayRef<GraphicsAllocation *>(&allocationPtr, 1)), MemoryOperationsStatus::UNSUPPORTED);
EXPECT_EQ(drmMemoryOperationsHandler->isResident(graphicsAllocation), MemoryOperationsStatus::UNSUPPORTED);
}
TEST_F(DrmMemoryOperationsHandlerTest, whenEvictingResidentAllocationExpectEvictFalse) {
EXPECT_EQ(drmMemoryOperationsHandler->makeResident(ArrayRef<GraphicsAllocation *>(&allocationPtr, 1)), MemoryOperationsStatus::UNSUPPORTED);
EXPECT_EQ(drmMemoryOperationsHandler->evict(graphicsAllocation), MemoryOperationsStatus::UNSUPPORTED);
EXPECT_EQ(drmMemoryOperationsHandler->isResident(graphicsAllocation), MemoryOperationsStatus::UNSUPPORTED);
}

View File

@ -0,0 +1,406 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/helpers/file_io.h"
#include "core/os_interface/device_factory.h"
#include "core/os_interface/linux/os_context_linux.h"
#include "core/os_interface/linux/os_interface.h"
#include "fixtures/memory_management_fixture.h"
#include "gtest/gtest.h"
#include "os_interface/linux/drm_mock.h"
#include <fstream>
#include <memory>
using namespace NEO;
using namespace std;
TEST(DrmTest, GetDeviceID) {
DrmMock *pDrm = new DrmMock;
EXPECT_NE(nullptr, pDrm);
pDrm->StoredDeviceID = 0x1234;
int deviceID = 0;
int ret = pDrm->getDeviceID(deviceID);
EXPECT_EQ(0, ret);
EXPECT_EQ(pDrm->StoredDeviceID, deviceID);
delete pDrm;
}
TEST(DrmTest, GivenConfigFileWithWrongDeviceIDWhenFrequencyIsQueriedThenReturnZero) {
DrmMock *pDrm = new DrmMock;
EXPECT_NE(nullptr, pDrm);
pDrm->StoredDeviceID = 0x4321;
int maxFrequency = 0;
int ret = pDrm->getMaxGpuFrequency(maxFrequency);
EXPECT_EQ(0, ret);
EXPECT_EQ(0, maxFrequency);
delete pDrm;
}
TEST(DrmTest, GivenConfigFileWithWrongDeviceIDFailIoctlWhenFrequencyIsQueriedThenReturnZero) {
DrmMock *pDrm = new DrmMock;
EXPECT_NE(nullptr, pDrm);
pDrm->StoredDeviceID = 0x4321;
pDrm->StoredRetValForDeviceID = -1;
int maxFrequency = 0;
int ret = pDrm->getMaxGpuFrequency(maxFrequency);
EXPECT_EQ(-1, ret);
EXPECT_EQ(0, maxFrequency);
delete pDrm;
}
TEST(DrmTest, GivenValidConfigFileWhenFrequencyIsQueriedThenValidValueIsReturned) {
int expectedMaxFrequency = 1000;
DrmMock *pDrm = new DrmMock;
EXPECT_NE(nullptr, pDrm);
pDrm->StoredDeviceID = 0x1234;
string gpuFile = "test_files/devices/config";
string gtMaxFreqFile = "test_files/devices/drm/card0/gt_max_freq_mhz";
EXPECT_TRUE(fileExists(gpuFile));
EXPECT_TRUE(fileExists(gtMaxFreqFile));
int maxFrequency = 0;
int ret = pDrm->getMaxGpuFrequency(maxFrequency);
EXPECT_EQ(0, ret);
EXPECT_EQ(expectedMaxFrequency, maxFrequency);
delete pDrm;
}
TEST(DrmTest, GivenNoConfigFileWhenFrequencyIsQueriedThenReturnZero) {
DrmMock *pDrm = new DrmMock;
EXPECT_NE(nullptr, pDrm);
pDrm->StoredDeviceID = 0x1234;
// change directory
pDrm->setSysFsDefaultGpuPath("./");
int maxFrequency = 0;
int ret = pDrm->getMaxGpuFrequency(maxFrequency);
EXPECT_EQ(0, ret);
EXPECT_EQ(0, maxFrequency);
delete pDrm;
}
TEST(DrmTest, GetRevisionID) {
DrmMock *pDrm = new DrmMock;
EXPECT_NE(nullptr, pDrm);
pDrm->StoredDeviceID = 0x1234;
pDrm->StoredDeviceRevID = 0xB;
int deviceID = 0;
int ret = pDrm->getDeviceID(deviceID);
EXPECT_EQ(0, ret);
int revID = 0;
ret = pDrm->getDeviceRevID(revID);
EXPECT_EQ(0, ret);
EXPECT_EQ(pDrm->StoredDeviceID, deviceID);
EXPECT_EQ(pDrm->StoredDeviceRevID, revID);
delete pDrm;
}
TEST(DrmTest, GivenDrmWhenAskedForGttSizeThenReturnCorrectValue) {
auto drm = make_unique<DrmMock>();
uint64_t queryGttSize = 0;
drm->StoredRetValForGetGttSize = 0;
drm->storedGTTSize = 1ull << 31;
EXPECT_EQ(0, drm->queryGttSize(queryGttSize));
EXPECT_EQ(drm->storedGTTSize, queryGttSize);
queryGttSize = 0;
drm->StoredRetValForGetGttSize = -1;
EXPECT_NE(0, drm->queryGttSize(queryGttSize));
EXPECT_EQ(0u, queryGttSize);
}
TEST(DrmTest, GivenDrmWhenAskedForPreemptionCorrectValueReturned) {
DrmMock *pDrm = new DrmMock;
pDrm->StoredRetVal = 0;
pDrm->StoredPreemptionSupport =
I915_SCHEDULER_CAP_ENABLED |
I915_SCHEDULER_CAP_PRIORITY |
I915_SCHEDULER_CAP_PREEMPTION;
pDrm->checkPreemptionSupport();
EXPECT_TRUE(pDrm->isPreemptionSupported());
pDrm->StoredPreemptionSupport = 0;
pDrm->checkPreemptionSupport();
EXPECT_FALSE(pDrm->isPreemptionSupported());
pDrm->StoredRetVal = -1;
pDrm->StoredPreemptionSupport =
I915_SCHEDULER_CAP_ENABLED |
I915_SCHEDULER_CAP_PRIORITY |
I915_SCHEDULER_CAP_PREEMPTION;
pDrm->checkPreemptionSupport();
EXPECT_FALSE(pDrm->isPreemptionSupported());
pDrm->StoredPreemptionSupport = 0;
pDrm->checkPreemptionSupport();
EXPECT_FALSE(pDrm->isPreemptionSupported());
delete pDrm;
}
TEST(DrmTest, GivenDrmWhenAskedForContextThatFailsThenFalseIsReturned) {
DrmMock *pDrm = new DrmMock;
pDrm->StoredRetVal = -1;
EXPECT_THROW(pDrm->createDrmContext(), std::exception);
pDrm->StoredRetVal = 0;
delete pDrm;
}
TEST(DrmTest, givenDrmWhenOsContextIsCreatedThenCreateAndDestroyNewDrmOsContext) {
DrmMock drmMock;
uint32_t drmContextId1 = 123;
uint32_t drmContextId2 = 456;
{
drmMock.StoredCtxId = drmContextId1;
OsContextLinux osContext1(drmMock, 0u, 1, aub_stream::ENGINE_RCS, PreemptionMode::Disabled, false);
EXPECT_EQ(1u, osContext1.getDrmContextIds().size());
EXPECT_EQ(drmContextId1, osContext1.getDrmContextIds()[0]);
EXPECT_EQ(0u, drmMock.receivedDestroyContextId);
{
drmMock.StoredCtxId = drmContextId2;
OsContextLinux osContext2(drmMock, 0u, 1, aub_stream::ENGINE_RCS, PreemptionMode::Disabled, false);
EXPECT_EQ(1u, osContext2.getDrmContextIds().size());
EXPECT_EQ(drmContextId2, osContext2.getDrmContextIds()[0]);
EXPECT_EQ(0u, drmMock.receivedDestroyContextId);
}
EXPECT_EQ(drmContextId2, drmMock.receivedDestroyContextId);
}
EXPECT_EQ(drmContextId1, drmMock.receivedDestroyContextId);
EXPECT_EQ(0u, drmMock.receivedContextParamRequestCount);
}
TEST(DrmTest, givenDrmAndNegativeCheckNonPersistentContextsSupportWhenOsContextIsCreatedThenReceivedContextParamRequestCountReturnsCorrectValue) {
DrmMock drmMock;
uint32_t drmContextId1 = 123;
drmMock.StoredCtxId = drmContextId1;
auto expectedCount = 0u;
{
drmMock.StoredRetValForPersistant = -1;
drmMock.checkNonPersistentContextsSupport();
++expectedCount;
OsContextLinux osContext(drmMock, 0u, 1, aub_stream::ENGINE_RCS, PreemptionMode::Disabled, false);
EXPECT_EQ(expectedCount, drmMock.receivedContextParamRequestCount);
}
{
drmMock.StoredRetValForPersistant = 0;
drmMock.checkNonPersistentContextsSupport();
++expectedCount;
OsContextLinux osContext(drmMock, 0u, 1, aub_stream::ENGINE_RCS, PreemptionMode::Disabled, false);
++expectedCount;
EXPECT_EQ(expectedCount, drmMock.receivedContextParamRequestCount);
}
}
TEST(DrmTest, givenDrmPreemptionEnabledAndLowPriorityEngineWhenCreatingOsContextThenCallSetContextPriorityIoctl) {
DrmMock drmMock;
drmMock.StoredCtxId = 123;
drmMock.preemptionSupported = false;
OsContextLinux osContext1(drmMock, 0u, 1, aub_stream::ENGINE_RCS, PreemptionMode::Disabled, false);
OsContextLinux osContext2(drmMock, 0u, 1, aub_stream::ENGINE_RCS, PreemptionMode::Disabled, true);
EXPECT_EQ(0u, drmMock.receivedContextParamRequestCount);
drmMock.preemptionSupported = true;
OsContextLinux osContext3(drmMock, 0u, 1, aub_stream::ENGINE_RCS, PreemptionMode::Disabled, false);
EXPECT_EQ(0u, drmMock.receivedContextParamRequestCount);
OsContextLinux osContext4(drmMock, 0u, 1, aub_stream::ENGINE_RCS, PreemptionMode::Disabled, true);
EXPECT_EQ(1u, drmMock.receivedContextParamRequestCount);
EXPECT_EQ(drmMock.StoredCtxId, drmMock.receivedContextParamRequest.ctx_id);
EXPECT_EQ(static_cast<uint64_t>(I915_CONTEXT_PARAM_PRIORITY), drmMock.receivedContextParamRequest.param);
EXPECT_EQ(static_cast<uint64_t>(-1023), drmMock.receivedContextParamRequest.value);
EXPECT_EQ(0u, drmMock.receivedContextParamRequest.size);
}
TEST(DrmTest, getExecSoftPin) {
DrmMock *pDrm = new DrmMock;
int execSoftPin = 0;
int ret = pDrm->getExecSoftPin(execSoftPin);
EXPECT_EQ(0, ret);
EXPECT_EQ(0, execSoftPin);
pDrm->StoredExecSoftPin = 1;
ret = pDrm->getExecSoftPin(execSoftPin);
EXPECT_EQ(0, ret);
EXPECT_EQ(1, execSoftPin);
delete pDrm;
}
TEST(DrmTest, enableTurboBoost) {
DrmMock *pDrm = new DrmMock;
int ret = pDrm->enableTurboBoost();
EXPECT_EQ(0, ret);
delete pDrm;
}
TEST(DrmTest, getEnabledPooledEu) {
DrmMock *pDrm = new DrmMock;
int enabled = 0;
int ret = 0;
pDrm->StoredHasPooledEU = -1;
#if defined(I915_PARAM_HAS_POOLED_EU)
ret = pDrm->getEnabledPooledEu(enabled);
EXPECT_EQ(0, ret);
EXPECT_EQ(-1, enabled);
pDrm->StoredHasPooledEU = 0;
ret = pDrm->getEnabledPooledEu(enabled);
EXPECT_EQ(0, ret);
EXPECT_EQ(0, enabled);
pDrm->StoredHasPooledEU = 1;
ret = pDrm->getEnabledPooledEu(enabled);
EXPECT_EQ(0, ret);
EXPECT_EQ(1, enabled);
pDrm->StoredRetValForPooledEU = -1;
ret = pDrm->getEnabledPooledEu(enabled);
EXPECT_EQ(-1, ret);
EXPECT_EQ(1, enabled);
#else
ret = pDrm->getEnabledPooledEu(enabled);
EXPECT_EQ(0, ret);
EXPECT_EQ(0, enabled);
#endif
delete pDrm;
}
TEST(DrmTest, getMinEuInPool) {
DrmMock *pDrm = new DrmMock;
pDrm->StoredMinEUinPool = -1;
int minEUinPool = 0;
int ret = 0;
#if defined(I915_PARAM_MIN_EU_IN_POOL)
ret = pDrm->getMinEuInPool(minEUinPool);
EXPECT_EQ(0, ret);
EXPECT_EQ(-1, minEUinPool);
pDrm->StoredMinEUinPool = 0;
ret = pDrm->getMinEuInPool(minEUinPool);
EXPECT_EQ(0, ret);
EXPECT_EQ(0, minEUinPool);
pDrm->StoredMinEUinPool = 1;
ret = pDrm->getMinEuInPool(minEUinPool);
EXPECT_EQ(0, ret);
EXPECT_EQ(1, minEUinPool);
pDrm->StoredRetValForMinEUinPool = -1;
ret = pDrm->getMinEuInPool(minEUinPool);
EXPECT_EQ(-1, ret);
EXPECT_EQ(1, minEUinPool);
#else
ret = pDrm->getMinEuInPool(minEUinPool);
EXPECT_EQ(0, ret);
EXPECT_EQ(0, minEUinPool);
#endif
delete pDrm;
}
TEST(DrmTest, givenDrmWhenGetErrnoIsCalledThenErrnoValueIsReturned) {
DrmMock *pDrm = new DrmMock;
EXPECT_NE(nullptr, pDrm);
auto errnoFromDrm = pDrm->getErrno();
EXPECT_EQ(errno, errnoFromDrm);
delete pDrm;
}
TEST(DrmTest, givenPlatformWhereGetSseuRetFailureWhenCallSetQueueSliceCountThenSliceCountIsNotSet) {
uint64_t newSliceCount = 1;
std::unique_ptr<DrmMock> drm = std::make_unique<DrmMock>();
drm->StoredRetValForGetSSEU = -1;
drm->checkQueueSliceSupport();
EXPECT_FALSE(drm->sliceCountChangeSupported);
EXPECT_FALSE(drm->setQueueSliceCount(newSliceCount));
EXPECT_NE(drm->getSliceMask(newSliceCount), drm->storedParamSseu);
}
TEST(DrmTest, whenCheckNonPeristentSupportIsCalledThenAreNonPersistentContextsSupportedReturnsCorrectValues) {
std::unique_ptr<DrmMock> drm = std::make_unique<DrmMock>();
drm->StoredRetValForPersistant = -1;
drm->checkNonPersistentContextsSupport();
EXPECT_FALSE(drm->areNonPersistentContextsSupported());
drm->StoredRetValForPersistant = 0;
drm->checkNonPersistentContextsSupport();
EXPECT_TRUE(drm->areNonPersistentContextsSupported());
}
TEST(DrmTest, givenPlatformWhereSetSseuRetFailureWhenCallSetQueueSliceCountThenReturnFalse) {
uint64_t newSliceCount = 1;
std::unique_ptr<DrmMock> drm = std::make_unique<DrmMock>();
drm->StoredRetValForSetSSEU = -1;
drm->StoredRetValForGetSSEU = 0;
drm->checkQueueSliceSupport();
EXPECT_TRUE(drm->sliceCountChangeSupported);
EXPECT_FALSE(drm->setQueueSliceCount(newSliceCount));
}
TEST(DrmTest, givenPlatformWithSupportToChangeSliceCountWhenCallSetQueueSliceCountThenReturnTrue) {
uint64_t newSliceCount = 1;
std::unique_ptr<DrmMock> drm = std::make_unique<DrmMock>();
drm->StoredRetValForSetSSEU = 0;
drm->StoredRetValForSetSSEU = 0;
drm->checkQueueSliceSupport();
EXPECT_TRUE(drm->sliceCountChangeSupported);
EXPECT_TRUE(drm->setQueueSliceCount(newSliceCount));
drm_i915_gem_context_param_sseu sseu = {};
EXPECT_EQ(0, drm->getQueueSliceCount(&sseu));
EXPECT_EQ(drm->getSliceMask(newSliceCount), sseu.slice_mask);
}
namespace NEO {
namespace SysCalls {
extern uint32_t closeFuncCalled;
extern int closeFuncArgPassed;
} // namespace SysCalls
} // namespace NEO
TEST(HwDeviceId, whenHwDeviceIdIsDestroyedThenFileDescriptorIsClosed) {
SysCalls::closeFuncCalled = 0;
int fileDescriptor = 0x1234;
{
HwDeviceId hwDeviceId(fileDescriptor);
}
EXPECT_EQ(1u, SysCalls::closeFuncCalled);
EXPECT_EQ(fileDescriptor, SysCalls::closeFuncArgPassed);
}

View File

@ -0,0 +1,110 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/debug_settings/debug_settings_manager.h"
#include "test.h"
#include "mocks/linux/mock_drm_allocation.h"
#include "utilities/file_logger_tests.h"
using namespace NEO;
TEST(FileLogger, GivenLogAllocationMemoryPoolFlagThenLogsCorrectInfo) {
std::string testFile = "testfile";
DebugVariables flags;
flags.LogAllocationMemoryPool.set(true);
FullyEnabledFileLogger fileLogger(testFile, flags);
// Log file not created
bool logFileCreated = fileExists(fileLogger.getLogFileName());
EXPECT_FALSE(logFileCreated);
MockDrmAllocation allocation(GraphicsAllocation::AllocationType::BUFFER, MemoryPool::System64KBPages);
MockBufferObject bo;
bo.handle = 4;
allocation.bufferObjects[0] = &bo;
fileLogger.logAllocation(&allocation);
std::thread::id thisThread = std::this_thread::get_id();
std::stringstream threadIDCheck;
threadIDCheck << " ThreadID: " << thisThread;
std::stringstream memoryPoolCheck;
memoryPoolCheck << " MemoryPool: " << allocation.getMemoryPool();
if (fileLogger.wasFileCreated(fileLogger.getLogFileName())) {
auto str = fileLogger.getFileString(fileLogger.getLogFileName());
EXPECT_TRUE(str.find(threadIDCheck.str()) != std::string::npos);
EXPECT_TRUE(str.find(memoryPoolCheck.str()) != std::string::npos);
EXPECT_TRUE(str.find("AllocationType: BUFFER") != std::string::npos);
EXPECT_TRUE(str.find("Handle: 4") != std::string::npos);
}
}
TEST(FileLogger, GivenDrmAllocationWithoutBOThenNoHandleLogged) {
std::string testFile = "testfile";
DebugVariables flags;
flags.LogAllocationMemoryPool.set(true);
FullyEnabledFileLogger fileLogger(testFile, flags);
// Log file not created
bool logFileCreated = fileExists(fileLogger.getLogFileName());
EXPECT_FALSE(logFileCreated);
MockDrmAllocation allocation(GraphicsAllocation::AllocationType::BUFFER, MemoryPool::System64KBPages);
fileLogger.logAllocation(&allocation);
std::thread::id thisThread = std::this_thread::get_id();
std::stringstream threadIDCheck;
threadIDCheck << " ThreadID: " << thisThread;
std::stringstream memoryPoolCheck;
memoryPoolCheck << " MemoryPool: " << allocation.getMemoryPool();
if (fileLogger.wasFileCreated(fileLogger.getLogFileName())) {
auto str = fileLogger.getFileString(fileLogger.getLogFileName());
EXPECT_TRUE(str.find(threadIDCheck.str()) != std::string::npos);
EXPECT_TRUE(str.find(memoryPoolCheck.str()) != std::string::npos);
EXPECT_TRUE(str.find("AllocationType: BUFFER") != std::string::npos);
EXPECT_FALSE(str.find("Handle: 4") != std::string::npos);
}
}
TEST(FileLogger, GivenLogAllocationMemoryPoolFlagSetFalseThenAllocationIsNotLogged) {
std::string testFile = "testfile";
DebugVariables flags;
flags.LogAllocationMemoryPool.set(false);
FullyEnabledFileLogger fileLogger(testFile, flags);
// Log file not created
bool logFileCreated = fileExists(fileLogger.getLogFileName());
EXPECT_FALSE(logFileCreated);
MockDrmAllocation allocation(GraphicsAllocation::AllocationType::BUFFER, MemoryPool::System64KBPages);
fileLogger.logAllocation(&allocation);
std::thread::id thisThread = std::this_thread::get_id();
std::stringstream threadIDCheck;
threadIDCheck << " ThreadID: " << thisThread;
std::stringstream memoryPoolCheck;
memoryPoolCheck << " MemoryPool: " << allocation.getMemoryPool();
if (fileLogger.wasFileCreated(fileLogger.getLogFileName())) {
auto str = fileLogger.getFileString(fileLogger.getLogFileName());
EXPECT_FALSE(str.find(threadIDCheck.str()) != std::string::npos);
EXPECT_FALSE(str.find(memoryPoolCheck.str()) != std::string::npos);
EXPECT_FALSE(str.find("AllocationType: BUFFER") != std::string::npos);
}
}

View File

@ -0,0 +1,469 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "os_interface/linux/hw_info_config_linux_tests.h"
#include "core/helpers/hw_helper.h"
#include "core/os_interface/linux/os_interface.h"
#include "core/unit_tests/helpers/debug_manager_state_restore.h"
#include "core/unit_tests/helpers/default_hw_info.h"
#include <cstring>
namespace NEO {
constexpr uint32_t hwConfigTestMidThreadBit = 1 << 8;
constexpr uint32_t hwConfigTestThreadGroupBit = 1 << 9;
constexpr uint32_t hwConfigTestMidBatchBit = 1 << 10;
template <>
int HwInfoConfigHw<IGFX_UNKNOWN>::configureHardwareCustom(HardwareInfo *hwInfo, OSInterface *osIface) {
FeatureTable *featureTable = &hwInfo->featureTable;
featureTable->ftrGpGpuMidThreadLevelPreempt = 0;
featureTable->ftrGpGpuThreadGroupLevelPreempt = 0;
featureTable->ftrGpGpuMidBatchPreempt = 0;
if (hwInfo->platform.usDeviceID == 30) {
GT_SYSTEM_INFO *gtSystemInfo = &hwInfo->gtSystemInfo;
gtSystemInfo->EdramSizeInKb = 128 * 1000;
}
if (hwInfo->platform.usDeviceID & hwConfigTestMidThreadBit) {
featureTable->ftrGpGpuMidThreadLevelPreempt = 1;
}
if (hwInfo->platform.usDeviceID & hwConfigTestThreadGroupBit) {
featureTable->ftrGpGpuThreadGroupLevelPreempt = 1;
}
if (hwInfo->platform.usDeviceID & hwConfigTestMidBatchBit) {
featureTable->ftrGpGpuMidBatchPreempt = 1;
}
return (hwInfo->platform.usDeviceID == 10) ? -1 : 0;
}
template <>
void HwInfoConfigHw<IGFX_UNKNOWN>::adjustPlatformForProductFamily(HardwareInfo *hwInfo) {
}
template <>
cl_unified_shared_memory_capabilities_intel HwInfoConfigHw<IGFX_UNKNOWN>::getHostMemCapabilities() {
return 0;
}
template <>
cl_unified_shared_memory_capabilities_intel HwInfoConfigHw<IGFX_UNKNOWN>::getDeviceMemCapabilities() {
return 0;
}
template <>
cl_unified_shared_memory_capabilities_intel HwInfoConfigHw<IGFX_UNKNOWN>::getSingleDeviceSharedMemCapabilities() {
return 0;
}
template <>
cl_unified_shared_memory_capabilities_intel HwInfoConfigHw<IGFX_UNKNOWN>::getCrossDeviceSharedMemCapabilities() {
return 0;
}
template <>
cl_unified_shared_memory_capabilities_intel HwInfoConfigHw<IGFX_UNKNOWN>::getSharedSystemMemCapabilities() {
return 0;
}
} // namespace NEO
struct DummyHwConfig : HwInfoConfigHw<IGFX_UNKNOWN> {
};
using namespace NEO;
using namespace std;
void mockCpuidex(int *cpuInfo, int functionId, int subfunctionId);
void HwInfoConfigTestLinux::SetUp() {
HwInfoConfigTest::SetUp();
osInterface = new OSInterface();
drm = new DrmMock();
osInterface->get()->setDrm(static_cast<Drm *>(drm));
drm->StoredDeviceID = pInHwInfo.platform.usDeviceID;
drm->StoredDeviceRevID = 0;
drm->StoredEUVal = pInHwInfo.gtSystemInfo.EUCount;
drm->StoredSSVal = pInHwInfo.gtSystemInfo.SubSliceCount;
rt_cpuidex_func = CpuInfo::cpuidexFunc;
CpuInfo::cpuidexFunc = mockCpuidex;
}
void HwInfoConfigTestLinux::TearDown() {
CpuInfo::cpuidexFunc = rt_cpuidex_func;
delete osInterface;
HwInfoConfigTest::TearDown();
}
void mockCpuidex(int *cpuInfo, int functionId, int subfunctionId) {
if (subfunctionId == 0) {
cpuInfo[0] = 0x7F;
}
if (subfunctionId == 1) {
cpuInfo[0] = 0x1F;
}
if (subfunctionId == 2) {
cpuInfo[0] = 0;
}
}
struct HwInfoConfigTestLinuxDummy : HwInfoConfigTestLinux {
void SetUp() override {
HwInfoConfigTestLinux::SetUp();
drm->StoredDeviceID = 1;
drm->setGtType(GTTYPE_GT0);
testPlatform->eRenderCoreFamily = platformDevices[0]->platform.eRenderCoreFamily;
}
void TearDown() override {
HwInfoConfigTestLinux::TearDown();
}
DummyHwConfig hwConfig;
};
TEST_F(HwInfoConfigTestLinuxDummy, dummyConfig) {
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
}
GTTYPE GtTypes[] = {
GTTYPE_GT1, GTTYPE_GT2, GTTYPE_GT1_5, GTTYPE_GT2_5, GTTYPE_GT3, GTTYPE_GT4, GTTYPE_GTA, GTTYPE_GTC, GTTYPE_GTX};
TEST_F(HwInfoConfigTestLinuxDummy, dummyConfigGtTypes) {
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_EQ(GTTYPE_GT0, outHwInfo.platform.eGTType);
EXPECT_EQ(0u, outHwInfo.featureTable.ftrGT1);
EXPECT_EQ(0u, outHwInfo.featureTable.ftrGT1_5);
EXPECT_EQ(0u, outHwInfo.featureTable.ftrGT2);
EXPECT_EQ(0u, outHwInfo.featureTable.ftrGT2_5);
EXPECT_EQ(0u, outHwInfo.featureTable.ftrGT3);
EXPECT_EQ(0u, outHwInfo.featureTable.ftrGT4);
EXPECT_EQ(0u, outHwInfo.featureTable.ftrGTA);
EXPECT_EQ(0u, outHwInfo.featureTable.ftrGTC);
EXPECT_EQ(0u, outHwInfo.featureTable.ftrGTX);
size_t arrSize = sizeof(GtTypes) / sizeof(GTTYPE);
uint32_t FtrSum = 0;
for (uint32_t i = 0; i < arrSize; i++) {
drm->setGtType(GtTypes[i]);
ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_EQ(GtTypes[i], outHwInfo.platform.eGTType);
bool FtrPresent = (outHwInfo.featureTable.ftrGT1 ||
outHwInfo.featureTable.ftrGT1_5 ||
outHwInfo.featureTable.ftrGT2 ||
outHwInfo.featureTable.ftrGT2_5 ||
outHwInfo.featureTable.ftrGT3 ||
outHwInfo.featureTable.ftrGT4 ||
outHwInfo.featureTable.ftrGTA ||
outHwInfo.featureTable.ftrGTC ||
outHwInfo.featureTable.ftrGTX);
EXPECT_TRUE(FtrPresent);
FtrSum += (outHwInfo.featureTable.ftrGT1 +
outHwInfo.featureTable.ftrGT1_5 +
outHwInfo.featureTable.ftrGT2 +
outHwInfo.featureTable.ftrGT2_5 +
outHwInfo.featureTable.ftrGT3 +
outHwInfo.featureTable.ftrGT4 +
outHwInfo.featureTable.ftrGTA +
outHwInfo.featureTable.ftrGTC +
outHwInfo.featureTable.ftrGTX);
}
EXPECT_EQ(arrSize, FtrSum);
}
TEST_F(HwInfoConfigTestLinuxDummy, dummyConfigEdramDetection) {
drm->StoredDeviceID = 30;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_EQ(1u, outHwInfo.featureTable.ftrEDram);
}
TEST_F(HwInfoConfigTestLinuxDummy, givenEnabledPlatformCoherencyWhenConfiguringHwInfoThenIgnoreAndSetAsDisabled) {
drm->StoredDeviceID = 21;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_FALSE(outHwInfo.capabilityTable.ftrSupportsCoherency);
}
TEST_F(HwInfoConfigTestLinuxDummy, givenDisabledPlatformCoherencyWhenConfiguringHwInfoThenSetValidCapability) {
drm->StoredDeviceID = 20;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_FALSE(outHwInfo.capabilityTable.ftrSupportsCoherency);
}
TEST_F(HwInfoConfigTestLinuxDummy, dummyNegativeUnknownGtType) {
drm->setGtType(GTTYPE_UNDEFINED);
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(-1, ret);
}
TEST_F(HwInfoConfigTestLinuxDummy, dummyNegativeUnknownDevId) {
drm->StoredDeviceID = 0;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(-1, ret);
}
TEST_F(HwInfoConfigTestLinuxDummy, dummyNegativeFailGetDevId) {
drm->StoredRetValForDeviceID = -2;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(-2, ret);
}
TEST_F(HwInfoConfigTestLinuxDummy, dummydummyNegativeFailGetDevRevId) {
drm->StoredRetValForDeviceRevID = -3;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(-3, ret);
}
TEST_F(HwInfoConfigTestLinuxDummy, dummydummyNegativeFailGetEuCount) {
drm->StoredRetValForEUVal = -4;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(-4, ret);
}
TEST_F(HwInfoConfigTestLinuxDummy, dummydummyNegativeFailGetSsCount) {
drm->StoredRetValForSSVal = -5;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(-5, ret);
}
TEST_F(HwInfoConfigTestLinuxDummy, dummyNegativeFailingConfigureCustom) {
drm->StoredDeviceID = 10;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(-1, ret);
}
TEST_F(HwInfoConfigTestLinuxDummy, dummyNegativeUnknownDeviceId) {
drm->StoredDeviceID = 0;
drm->setGtType(GTTYPE_GT1);
auto hwConfig = DummyHwConfig{};
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(-1, ret);
}
TEST_F(HwInfoConfigTestLinuxDummy, whenConfigureHwInfoIsCalledThenAreNonPersistentContextsSupportedReturnsTrue) {
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_TRUE(drm->areNonPersistentContextsSupported());
}
TEST_F(HwInfoConfigTestLinuxDummy, whenConfigureHwInfoIsCalledAndPersitentContextIsUnsupportedThenAreNonPersistentContextsSupportedReturnsFalse) {
drm->StoredPersistentContextsSupport = 0;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_FALSE(drm->areNonPersistentContextsSupported());
}
TEST_F(HwInfoConfigTestLinuxDummy, dummyConfigPreemptionDrmEnabledMidThreadOn) {
pInHwInfo.capabilityTable.defaultPreemptionMode = PreemptionMode::MidThread;
drm->StoredPreemptionSupport =
I915_SCHEDULER_CAP_ENABLED |
I915_SCHEDULER_CAP_PRIORITY |
I915_SCHEDULER_CAP_PREEMPTION;
drm->StoredDeviceID = hwConfigTestMidThreadBit;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_EQ(PreemptionMode::MidThread, outHwInfo.capabilityTable.defaultPreemptionMode);
EXPECT_TRUE(drm->isPreemptionSupported());
}
TEST_F(HwInfoConfigTestLinuxDummy, dummyConfigPreemptionDrmEnabledThreadGroupOn) {
pInHwInfo.capabilityTable.defaultPreemptionMode = PreemptionMode::MidThread;
drm->StoredPreemptionSupport =
I915_SCHEDULER_CAP_ENABLED |
I915_SCHEDULER_CAP_PRIORITY |
I915_SCHEDULER_CAP_PREEMPTION;
drm->StoredDeviceID = hwConfigTestThreadGroupBit;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_EQ(PreemptionMode::ThreadGroup, outHwInfo.capabilityTable.defaultPreemptionMode);
EXPECT_TRUE(drm->isPreemptionSupported());
}
TEST_F(HwInfoConfigTestLinuxDummy, givenDebugFlagSetWhenConfiguringHwInfoThenPrintGetParamIoctlsOutput) {
DebugManagerStateRestore restore;
DebugManager.flags.PrintDebugMessages.set(true);
testing::internal::CaptureStdout(); // start capturing
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
std::string euCount = std::to_string(outHwInfo.gtSystemInfo.EUCount);
std::string subSliceCount = std::to_string(outHwInfo.gtSystemInfo.SubSliceCount);
std::array<std::string, 6> expectedStrings = {{"DRM_IOCTL_I915_GETPARAM: param: I915_PARAM_CHIPSET_ID, output value: 1, retCode: 0",
"DRM_IOCTL_I915_GETPARAM: param: I915_PARAM_REVISION, output value: 0, retCode: 0",
"DRM_IOCTL_I915_GETPARAM: param: I915_PARAM_EU_TOTAL, output value: " + euCount + ", retCode: 0",
"DRM_IOCTL_I915_GETPARAM: param: I915_PARAM_SUBSLICE_TOTAL, output value: " + subSliceCount + ", retCode: 0",
"DRM_IOCTL_I915_GETPARAM: param: I915_PARAM_CHIPSET_ID, output value: 1, retCode: 0",
"DRM_IOCTL_I915_GETPARAM: param: I915_PARAM_HAS_SCHEDULER, output value: 7, retCode: 0"
}};
std::string output = testing::internal::GetCapturedStdout(); // stop capturing
for (const auto &expectedString : expectedStrings) {
EXPECT_NE(std::string::npos, output.find(expectedString));
}
EXPECT_EQ(std::string::npos, output.find("UNKNOWN"));
}
TEST_F(HwInfoConfigTestLinuxDummy, dummyConfigPreemptionDrmEnabledMidBatchOn) {
pInHwInfo.capabilityTable.defaultPreemptionMode = PreemptionMode::MidThread;
drm->StoredPreemptionSupport =
I915_SCHEDULER_CAP_ENABLED |
I915_SCHEDULER_CAP_PRIORITY |
I915_SCHEDULER_CAP_PREEMPTION;
drm->StoredDeviceID = hwConfigTestMidBatchBit;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_EQ(PreemptionMode::MidBatch, outHwInfo.capabilityTable.defaultPreemptionMode);
EXPECT_TRUE(drm->isPreemptionSupported());
}
TEST_F(HwInfoConfigTestLinuxDummy, dummyConfigPreemptionDrmEnabledNoPreemption) {
pInHwInfo.capabilityTable.defaultPreemptionMode = PreemptionMode::MidThread;
drm->StoredPreemptionSupport =
I915_SCHEDULER_CAP_ENABLED |
I915_SCHEDULER_CAP_PRIORITY |
I915_SCHEDULER_CAP_PREEMPTION;
drm->StoredDeviceID = 1;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_EQ(PreemptionMode::Disabled, outHwInfo.capabilityTable.defaultPreemptionMode);
EXPECT_TRUE(drm->isPreemptionSupported());
}
TEST_F(HwInfoConfigTestLinuxDummy, dummyConfigPreemptionDrmDisabledAllPreemption) {
pInHwInfo.capabilityTable.defaultPreemptionMode = PreemptionMode::MidThread;
drm->StoredPreemptionSupport = 0;
drm->StoredDeviceID = hwConfigTestMidThreadBit | hwConfigTestThreadGroupBit | hwConfigTestMidBatchBit;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_EQ(PreemptionMode::Disabled, outHwInfo.capabilityTable.defaultPreemptionMode);
EXPECT_FALSE(drm->isPreemptionSupported());
}
TEST_F(HwInfoConfigTestLinuxDummy, dummyConfigPreemptionDrmEnabledAllPreemptionDriverThreadGroup) {
pInHwInfo.capabilityTable.defaultPreemptionMode = PreemptionMode::ThreadGroup;
drm->StoredPreemptionSupport =
I915_SCHEDULER_CAP_ENABLED |
I915_SCHEDULER_CAP_PRIORITY |
I915_SCHEDULER_CAP_PREEMPTION;
drm->StoredDeviceID = hwConfigTestMidThreadBit | hwConfigTestThreadGroupBit | hwConfigTestMidBatchBit;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_EQ(PreemptionMode::ThreadGroup, outHwInfo.capabilityTable.defaultPreemptionMode);
EXPECT_TRUE(drm->isPreemptionSupported());
}
TEST_F(HwInfoConfigTestLinuxDummy, dummyConfigPreemptionDrmEnabledAllPreemptionDriverMidBatch) {
pInHwInfo.capabilityTable.defaultPreemptionMode = PreemptionMode::MidBatch;
drm->StoredPreemptionSupport =
I915_SCHEDULER_CAP_ENABLED |
I915_SCHEDULER_CAP_PRIORITY |
I915_SCHEDULER_CAP_PREEMPTION;
drm->StoredDeviceID = hwConfigTestMidThreadBit | hwConfigTestThreadGroupBit | hwConfigTestMidBatchBit;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_EQ(PreemptionMode::MidBatch, outHwInfo.capabilityTable.defaultPreemptionMode);
EXPECT_TRUE(drm->isPreemptionSupported());
}
TEST_F(HwInfoConfigTestLinuxDummy, dummyConfigPreemptionDrmEnabledAllPreemptionDriverDisabled) {
pInHwInfo.capabilityTable.defaultPreemptionMode = PreemptionMode::Disabled;
drm->StoredPreemptionSupport =
I915_SCHEDULER_CAP_ENABLED |
I915_SCHEDULER_CAP_PRIORITY |
I915_SCHEDULER_CAP_PREEMPTION;
drm->StoredDeviceID = hwConfigTestMidThreadBit | hwConfigTestThreadGroupBit | hwConfigTestMidBatchBit;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_EQ(PreemptionMode::Disabled, outHwInfo.capabilityTable.defaultPreemptionMode);
EXPECT_TRUE(drm->isPreemptionSupported());
}
TEST_F(HwInfoConfigTestLinuxDummy, givenPlatformEnabledFtrCompressionWhenInitializingThenForceDisable) {
pInHwInfo.capabilityTable.ftrRenderCompressedBuffers = true;
pInHwInfo.capabilityTable.ftrRenderCompressedImages = true;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_FALSE(outHwInfo.capabilityTable.ftrRenderCompressedBuffers);
EXPECT_FALSE(outHwInfo.capabilityTable.ftrRenderCompressedImages);
}
TEST_F(HwInfoConfigTestLinuxDummy, givenPointerToHwInfoWhenConfigureHwInfoCalledThenRequiedSurfaceSizeIsSettedProperly) {
EXPECT_EQ(MemoryConstants::pageSize, pInHwInfo.capabilityTable.requiredPreemptionSurfaceSize);
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_EQ(outHwInfo.gtSystemInfo.CsrSizeInMb * MemoryConstants::megaByte, outHwInfo.capabilityTable.requiredPreemptionSurfaceSize);
}
TEST_F(HwInfoConfigTestLinuxDummy, givenInstrumentationForHardwareIsEnabledOrDisabledWhenConfiguringHwInfoThenOverrideItUsingHaveInstrumentation) {
int ret;
pInHwInfo.capabilityTable.instrumentationEnabled = false;
ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
ASSERT_EQ(0, ret);
EXPECT_FALSE(outHwInfo.capabilityTable.instrumentationEnabled);
pInHwInfo.capabilityTable.instrumentationEnabled = true;
ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
ASSERT_EQ(0, ret);
EXPECT_TRUE(outHwInfo.capabilityTable.instrumentationEnabled == haveInstrumentation);
}
TEST_F(HwInfoConfigTestLinuxDummy, givenGttSizeReturnedWhenInitializingHwInfoThenSetSvmFtr) {
drm->storedGTTSize = MemoryConstants::max64BitAppAddress;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_FALSE(outHwInfo.capabilityTable.ftrSvm);
drm->storedGTTSize = MemoryConstants::max64BitAppAddress + 1;
ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_TRUE(outHwInfo.capabilityTable.ftrSvm);
}
TEST_F(HwInfoConfigTestLinuxDummy, givenGttSizeReturnedWhenInitializingHwInfoThenSetGpuAddressSpace) {
drm->storedGTTSize = maxNBitValue(40) + 1;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_EQ(drm->storedGTTSize - 1, outHwInfo.capabilityTable.gpuAddressSpace);
}
TEST_F(HwInfoConfigTestLinuxDummy, givenFailingGttSizeIoctlWhenInitializingHwInfoThenSetDefaultValues) {
drm->StoredRetValForGetGttSize = -1;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface);
EXPECT_EQ(0, ret);
EXPECT_TRUE(outHwInfo.capabilityTable.ftrSvm);
EXPECT_NE(0u, outHwInfo.capabilityTable.gpuAddressSpace);
EXPECT_EQ(pInHwInfo.capabilityTable.gpuAddressSpace, outHwInfo.capabilityTable.gpuAddressSpace);
}

View File

@ -0,0 +1,29 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/os_interface/hw_info_config.h"
#include "core/os_interface/os_interface.h"
#include "core/utilities/cpu_info.h"
#include "os_interface/hw_info_config_tests.h"
#include "os_interface/linux/drm_mock.h"
using namespace NEO;
using namespace std;
struct HwInfoConfigTestLinux : public HwInfoConfigTest {
void SetUp() override;
void TearDown() override;
OSInterface *osInterface;
DrmMock *drm;
void (*rt_cpuidex_func)(int *, int, int);
};

View File

@ -0,0 +1,232 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/linux/os_interface.h"
#include "opencl/source/command_queue/command_queue_hw.h"
#include "test.h"
#include "fixtures/ult_command_stream_receiver_fixture.h"
#include "mocks/linux/mock_drm_command_stream_receiver.h"
#include "mocks/linux/mock_drm_memory_manager.h"
#include "mocks/mock_context.h"
#include "os_interface/linux/drm_mock.h"
using namespace NEO;
struct clCreateCommandQueueWithPropertiesLinux : public UltCommandStreamReceiverTest {
void SetUp() override {
UltCommandStreamReceiverTest::SetUp();
ExecutionEnvironment *executionEnvironment = new MockExecutionEnvironment();
executionEnvironment->prepareRootDeviceEnvironments(1);
auto osInterface = new OSInterface();
osInterface->get()->setDrm(drm);
executionEnvironment->rootDeviceEnvironments[0]->osInterface.reset(osInterface);
executionEnvironment->memoryManager.reset(new TestedDrmMemoryManager(*executionEnvironment));
mdevice = std::make_unique<MockClDevice>(MockDevice::create<MockDevice>(executionEnvironment, 0u));
clDevice = mdevice.get();
retVal = CL_SUCCESS;
context = std::unique_ptr<Context>(Context::create<MockContext>(nullptr, ClDeviceVector(&clDevice, 1), nullptr, nullptr, retVal));
}
void TearDown() override {
UltCommandStreamReceiverTest::TearDown();
}
DrmMock *drm = new DrmMock();
std::unique_ptr<MockClDevice> mdevice = nullptr;
std::unique_ptr<Context> context;
cl_device_id clDevice;
cl_int retVal;
};
namespace ULT {
TEST_F(clCreateCommandQueueWithPropertiesLinux, givenUnPossiblePropertiesWithClQueueSliceCountWhenCreateCommandQueueThenQueueNotCreated) {
uint64_t newSliceCount = 1;
size_t maxSliceCount;
clGetDeviceInfo(clDevice, CL_DEVICE_SLICE_COUNT_INTEL, sizeof(size_t), &maxSliceCount, nullptr);
newSliceCount = maxSliceCount + 1;
cl_queue_properties properties[] = {CL_QUEUE_SLICE_COUNT_INTEL, newSliceCount, 0};
cl_command_queue cmdQ = clCreateCommandQueueWithProperties(context.get(), clDevice, properties, &retVal);
EXPECT_EQ(nullptr, cmdQ);
EXPECT_EQ(CL_INVALID_QUEUE_PROPERTIES, retVal);
}
TEST_F(clCreateCommandQueueWithPropertiesLinux, givenZeroWithClQueueSliceCountWhenCreateCommandQueueThenSliceCountEqualDefaultSliceCount) {
uint64_t newSliceCount = 0;
cl_queue_properties properties[] = {CL_QUEUE_SLICE_COUNT_INTEL, newSliceCount, 0};
cl_command_queue cmdQ = clCreateCommandQueueWithProperties(context.get(), clDevice, properties, &retVal);
ASSERT_NE(nullptr, cmdQ);
ASSERT_EQ(CL_SUCCESS, retVal);
auto commandQueue = castToObject<CommandQueue>(cmdQ);
EXPECT_EQ(commandQueue->getSliceCount(), QueueSliceCount::defaultSliceCount);
retVal = clReleaseCommandQueue(cmdQ);
EXPECT_EQ(CL_SUCCESS, retVal);
}
TEST_F(clCreateCommandQueueWithPropertiesLinux, givenPossiblePropertiesWithClQueueSliceCountWhenCreateCommandQueueThenSliceCountIsSet) {
uint64_t newSliceCount = 1;
size_t maxSliceCount;
clGetDeviceInfo(clDevice, CL_DEVICE_SLICE_COUNT_INTEL, sizeof(size_t), &maxSliceCount, nullptr);
if (maxSliceCount > 1) {
newSliceCount = maxSliceCount - 1;
}
cl_queue_properties properties[] = {CL_QUEUE_SLICE_COUNT_INTEL, newSliceCount, 0};
cl_command_queue cmdQ = clCreateCommandQueueWithProperties(context.get(), clDevice, properties, &retVal);
ASSERT_NE(nullptr, cmdQ);
ASSERT_EQ(CL_SUCCESS, retVal);
auto commandQueue = castToObject<CommandQueue>(cmdQ);
EXPECT_EQ(commandQueue->getSliceCount(), newSliceCount);
retVal = clReleaseCommandQueue(cmdQ);
EXPECT_EQ(CL_SUCCESS, retVal);
}
HWTEST_F(clCreateCommandQueueWithPropertiesLinux, givenPropertiesWithClQueueSliceCountWhenCreateCommandQueueThenCallFlushTaskAndSliceCountIsSet) {
uint64_t newSliceCount = 1;
size_t maxSliceCount;
clGetDeviceInfo(clDevice, CL_DEVICE_SLICE_COUNT_INTEL, sizeof(size_t), &maxSliceCount, nullptr);
if (maxSliceCount > 1) {
newSliceCount = maxSliceCount - 1;
}
cl_queue_properties properties[] = {CL_QUEUE_SLICE_COUNT_INTEL, newSliceCount, 0};
auto mockCsr = new TestedDrmCommandStreamReceiver<FamilyType>(*mdevice->executionEnvironment);
mdevice->resetCommandStreamReceiver(mockCsr);
cl_command_queue cmdQ = clCreateCommandQueueWithProperties(context.get(), clDevice, properties, &retVal);
ASSERT_NE(nullptr, cmdQ);
ASSERT_EQ(CL_SUCCESS, retVal);
auto commandQueue = castToObject<CommandQueueHw<FamilyType>>(cmdQ);
auto &commandStream = commandQueue->getCS(1024u);
DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags();
dispatchFlags.sliceCount = commandQueue->getSliceCount();
mockCsr->flushTask(commandStream,
0u,
dsh,
ioh,
ssh,
taskLevel,
dispatchFlags,
mdevice->getDevice());
auto expectedSliceMask = drm->getSliceMask(newSliceCount);
EXPECT_EQ(expectedSliceMask, drm->storedParamSseu);
drm_i915_gem_context_param_sseu sseu = {};
EXPECT_EQ(0, drm->getQueueSliceCount(&sseu));
EXPECT_EQ(expectedSliceMask, sseu.slice_mask);
EXPECT_EQ(newSliceCount, mockCsr->lastSentSliceCount);
retVal = clReleaseCommandQueue(cmdQ);
EXPECT_EQ(CL_SUCCESS, retVal);
}
HWTEST_F(clCreateCommandQueueWithPropertiesLinux, givenSameSliceCountAsRecentlySetWhenCreateCommandQueueThenSetQueueSliceCountNotCalled) {
uint64_t newSliceCount = 1;
size_t maxSliceCount;
clGetDeviceInfo(clDevice, CL_DEVICE_SLICE_COUNT_INTEL, sizeof(size_t), &maxSliceCount, nullptr);
if (maxSliceCount > 1) {
newSliceCount = maxSliceCount - 1;
}
cl_queue_properties properties[] = {CL_QUEUE_SLICE_COUNT_INTEL, newSliceCount, 0};
auto mockCsr = new TestedDrmCommandStreamReceiver<FamilyType>(*mdevice->executionEnvironment);
mdevice->resetCommandStreamReceiver(mockCsr);
cl_command_queue cmdQ = clCreateCommandQueueWithProperties(context.get(), clDevice, properties, &retVal);
ASSERT_NE(nullptr, cmdQ);
ASSERT_EQ(CL_SUCCESS, retVal);
auto commandQueue = castToObject<CommandQueueHw<FamilyType>>(cmdQ);
auto &commandStream = commandQueue->getCS(1024u);
DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags();
dispatchFlags.sliceCount = commandQueue->getSliceCount();
mockCsr->lastSentSliceCount = newSliceCount;
mockCsr->flushTask(commandStream,
0u,
dsh,
ioh,
ssh,
taskLevel,
dispatchFlags,
mdevice->getDevice());
auto expectedSliceMask = drm->getSliceMask(newSliceCount);
EXPECT_NE(expectedSliceMask, drm->storedParamSseu);
drm_i915_gem_context_param_sseu sseu = {};
EXPECT_EQ(0, drm->getQueueSliceCount(&sseu));
EXPECT_NE(expectedSliceMask, sseu.slice_mask);
retVal = clReleaseCommandQueue(cmdQ);
EXPECT_EQ(CL_SUCCESS, retVal);
}
HWTEST_F(clCreateCommandQueueWithPropertiesLinux, givenPropertiesWithClQueueSliceCountWhenCreateCommandQueueThenSetReturnFalseAndLastSliceCountNotModify) {
uint64_t newSliceCount = 1;
size_t maxSliceCount;
clGetDeviceInfo(clDevice, CL_DEVICE_SLICE_COUNT_INTEL, sizeof(size_t), &maxSliceCount, nullptr);
if (maxSliceCount > 1) {
newSliceCount = maxSliceCount - 1;
}
cl_queue_properties properties[] = {CL_QUEUE_SLICE_COUNT_INTEL, newSliceCount, 0};
auto mockCsr = new TestedDrmCommandStreamReceiver<FamilyType>(*mdevice->executionEnvironment);
mdevice->resetCommandStreamReceiver(mockCsr);
cl_command_queue cmdQ = clCreateCommandQueueWithProperties(context.get(), clDevice, properties, &retVal);
ASSERT_NE(nullptr, cmdQ);
ASSERT_EQ(CL_SUCCESS, retVal);
auto commandQueue = castToObject<CommandQueueHw<FamilyType>>(cmdQ);
auto &commandStream = commandQueue->getCS(1024u);
DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags();
dispatchFlags.sliceCount = commandQueue->getSliceCount();
drm->StoredRetValForSetSSEU = -1;
auto lastSliceCountBeforeFlushTask = mockCsr->lastSentSliceCount;
mockCsr->flushTask(commandStream,
0u,
dsh,
ioh,
ssh,
taskLevel,
dispatchFlags,
mdevice->getDevice());
EXPECT_NE(newSliceCount, mockCsr->lastSentSliceCount);
EXPECT_EQ(lastSliceCountBeforeFlushTask, mockCsr->lastSentSliceCount);
retVal = clReleaseCommandQueue(cmdQ);
EXPECT_EQ(CL_SUCCESS, retVal);
}
} // namespace ULT

View File

@ -0,0 +1,31 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/os_interface/linux/os_interface.h"
#include "core/os_interface/linux/os_time_linux.h"
namespace NEO {
class MockOSTimeLinux : public OSTimeLinux {
public:
MockOSTimeLinux(OSInterface *osInterface) : OSTimeLinux(osInterface){};
void setResolutionFunc(resolutionFunc_t func) {
this->resolutionFunc = func;
}
void setGetTimeFunc(getTimeFunc_t func) {
this->getTimeFunc = func;
}
void updateDrm(Drm *drm) {
osInterface->get()->setDrm(drm);
pDrm = drm;
timestampTypeDetect();
}
static std::unique_ptr<MockOSTimeLinux> create(OSInterface *osInterface) {
return std::unique_ptr<MockOSTimeLinux>(new MockOSTimeLinux(osInterface));
}
};
} // namespace NEO

View File

@ -0,0 +1,59 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "mock_performance_counters_linux.h"
#include "os_interface/linux/mock_os_time_linux.h"
#include "os_interface/mock_performance_counters.h"
namespace NEO {
//////////////////////////////////////////////////////
// MockPerformanceCountersLinux::MockPerformanceCountersLinux
//////////////////////////////////////////////////////
MockPerformanceCountersLinux::MockPerformanceCountersLinux(Device *device)
: PerformanceCountersLinux() {
}
//////////////////////////////////////////////////////
// MockPerformanceCounters::create
//////////////////////////////////////////////////////
std::unique_ptr<PerformanceCounters> MockPerformanceCounters::create(Device *device) {
auto performanceCounters = std::unique_ptr<PerformanceCounters>(new MockPerformanceCountersLinux(device));
auto metricsLibrary = std::make_unique<MockMetricsLibrary>();
auto metricsLibraryDll = std::make_unique<MockMetricsLibraryDll>();
metricsLibrary->api = std::make_unique<MockMetricsLibraryValidInterface>();
metricsLibrary->osLibrary = std::move(metricsLibraryDll);
performanceCounters->setMetricsLibraryInterface(std::move(metricsLibrary));
return performanceCounters;
}
//////////////////////////////////////////////////////
// PerformanceCountersFixture::createPerfCounters
//////////////////////////////////////////////////////
void PerformanceCountersFixture::createPerfCounters() {
performanceCountersBase = MockPerformanceCounters::create(&device->getDevice());
}
//////////////////////////////////////////////////////
// PerformanceCountersFixture::SetUp
//////////////////////////////////////////////////////
void PerformanceCountersFixture::SetUp() {
device = std::make_unique<MockClDevice>(new MockDevice());
context = std::make_unique<MockContext>(device.get());
queue = std::make_unique<MockCommandQueue>(context.get(), device.get(), &queueProperties);
osInterface = std::unique_ptr<OSInterface>(new OSInterface());
device->setOSTime(new MockOSTimeLinux(osInterface.get()));
}
//////////////////////////////////////////////////////
// PerformanceCountersFixture::TearDown
//////////////////////////////////////////////////////
void PerformanceCountersFixture::TearDown() {
}
} // namespace NEO

View File

@ -0,0 +1,17 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "opencl/source/os_interface/linux/performance_counters_linux.h"
namespace NEO {
class MockPerformanceCountersLinux : public PerformanceCountersLinux {
public:
MockPerformanceCountersLinux(Device *device);
};
} // namespace NEO

View File

@ -0,0 +1,33 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/os_library.h"
#include "common/gtsysinfo.h"
#include "igfxfmid.h"
namespace Os {
///////////////////////////////////////////////////////////////////////////////
// These options determine the Linux specific behavior for
// the runtime unit tests
///////////////////////////////////////////////////////////////////////////////
#if defined(__linux__)
const char *frontEndDllName = "libmock_igdfcl.so";
const char *igcDllName = "libmock_igc.so";
const char *libvaDllName = nullptr;
const char *testDllName = "libtest_dynamic_lib.so";
const char *gmmDllName = "libmock_gmm.so";
const char *gmmInitFuncName = "initMockGmm";
const char *gmmDestroyFuncName = "destroyMockGmm";
const char *metricsLibraryDllName = "";
#endif
const char *sysFsPciPath = "./test_files";
} // namespace Os
NEO::OsLibrary *setAdapterInfo(const PLATFORM *platform, const GT_SYSTEM_INFO *gtSystemInfo, uint64_t gpuAddressSpace) {
return nullptr;
}

View File

@ -0,0 +1,26 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/command_stream/preemption.h"
#include "core/helpers/hw_helper.h"
#include "core/os_interface/linux/os_context_linux.h"
#include "core/os_interface/linux/os_interface.h"
#include "gtest/gtest.h"
#include "os_interface/linux/drm_mock.h"
namespace NEO {
TEST(OsInterfaceTest, GivenLinuxWhenare64kbPagesEnabledThenFalse) {
EXPECT_FALSE(OSInterface::are64kbPagesEnabled());
}
TEST(OsInterfaceTest, GivenLinuxOsInterfaceWhenDeviceHandleQueriedthenZeroIsReturned) {
OSInterface osInterface;
EXPECT_EQ(0u, osInterface.getDeviceHandle());
}
} // namespace NEO

View File

@ -0,0 +1,245 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/linux/drm_neo.h"
#include "core/os_interface/linux/os_interface.h"
#include "core/os_interface/linux/os_time_linux.h"
#include "test.h"
#include "gtest/gtest.h"
#include "os_interface/linux/device_command_stream_fixture.h"
#include "os_interface/linux/mock_os_time_linux.h"
#include <dlfcn.h>
static int actualTime = 0;
int getTimeFuncFalse(clockid_t clkId, struct timespec *tp) throw() {
return -1;
}
int getTimeFuncTrue(clockid_t clkId, struct timespec *tp) throw() {
tp->tv_sec = 0;
tp->tv_nsec = ++actualTime;
return 0;
}
int resolutionFuncFalse(clockid_t clkId, struct timespec *res) throw() {
return -1;
}
int resolutionFuncTrue(clockid_t clkId, struct timespec *res) throw() {
res->tv_sec = 0;
res->tv_nsec = 5;
return 0;
}
using namespace NEO;
struct DrmTimeTest : public ::testing::Test {
public:
void SetUp() override {
osInterface = std::unique_ptr<OSInterface>(new OSInterface());
osTime = MockOSTimeLinux::create(osInterface.get());
osTime->setResolutionFunc(resolutionFuncTrue);
osTime->setGetTimeFunc(getTimeFuncTrue);
}
void TearDown() override {
}
std::unique_ptr<MockOSTimeLinux> osTime;
std::unique_ptr<OSInterface> osInterface;
};
TEST_F(DrmTimeTest, DetectWithNullDrmNoCrash) {
}
TEST_F(DrmTimeTest, GetCpuTime) {
uint64_t time = 0;
auto error = osTime->getCpuTime(&time);
EXPECT_TRUE(error);
EXPECT_NE(0ULL, time);
}
TEST_F(DrmTimeTest, GetCpuTimeFail) {
uint64_t time = 0;
osTime->setGetTimeFunc(getTimeFuncFalse);
auto error = osTime->getCpuTime(&time);
EXPECT_FALSE(error);
}
TEST_F(DrmTimeTest, GetGpuTime) {
uint64_t time = 0;
auto pDrm = new DrmMockTime();
osTime->updateDrm(pDrm);
auto error = osTime->getGpuTime32(&time);
EXPECT_TRUE(error);
EXPECT_NE(0ULL, time);
error = osTime->getGpuTime36(&time);
EXPECT_TRUE(error);
EXPECT_NE(0ULL, time);
error = osTime->getGpuTimeSplitted(&time);
EXPECT_TRUE(error);
EXPECT_NE(0ULL, time);
}
TEST_F(DrmTimeTest, GetGpuTimeFails) {
uint64_t time = 0;
auto pDrm = new DrmMockFail();
osTime->updateDrm(pDrm);
auto error = osTime->getGpuTime32(&time);
EXPECT_FALSE(error);
error = osTime->getGpuTime36(&time);
EXPECT_FALSE(error);
error = osTime->getGpuTimeSplitted(&time);
EXPECT_FALSE(error);
}
TEST_F(DrmTimeTest, GetCpuGpuTime) {
TimeStampData CPUGPUTime01 = {0, 0};
TimeStampData CPUGPUTime02 = {0, 0};
auto pDrm = new DrmMockTime();
osTime->updateDrm(pDrm);
auto error = osTime->getCpuGpuTime(&CPUGPUTime01);
EXPECT_TRUE(error);
EXPECT_NE(0ULL, CPUGPUTime01.CPUTimeinNS);
EXPECT_NE(0ULL, CPUGPUTime01.GPUTimeStamp);
error = osTime->getCpuGpuTime(&CPUGPUTime02);
EXPECT_TRUE(error);
EXPECT_NE(0ULL, CPUGPUTime02.CPUTimeinNS);
EXPECT_NE(0ULL, CPUGPUTime02.GPUTimeStamp);
EXPECT_GT(CPUGPUTime02.GPUTimeStamp, CPUGPUTime01.GPUTimeStamp);
EXPECT_GT(CPUGPUTime02.CPUTimeinNS, CPUGPUTime01.CPUTimeinNS);
}
TEST_F(DrmTimeTest, GIVENDrmWHENGetCpuGpuTimeTHENPassed) {
TimeStampData CPUGPUTime01 = {0, 0};
TimeStampData CPUGPUTime02 = {0, 0};
auto pDrm = new DrmMockTime();
osTime->updateDrm(pDrm);
auto error = osTime->getCpuGpuTime(&CPUGPUTime01);
EXPECT_TRUE(error);
EXPECT_NE(0ULL, CPUGPUTime01.CPUTimeinNS);
EXPECT_NE(0ULL, CPUGPUTime01.GPUTimeStamp);
error = osTime->getCpuGpuTime(&CPUGPUTime02);
EXPECT_TRUE(error);
EXPECT_NE(0ULL, CPUGPUTime02.CPUTimeinNS);
EXPECT_NE(0ULL, CPUGPUTime02.GPUTimeStamp);
EXPECT_GT(CPUGPUTime02.GPUTimeStamp, CPUGPUTime01.GPUTimeStamp);
EXPECT_GT(CPUGPUTime02.CPUTimeinNS, CPUGPUTime01.CPUTimeinNS);
}
TEST_F(DrmTimeTest, givenGetCpuGpuTimeWhenItIsUnavailableThenReturnFalse) {
TimeStampData CPUGPUTime = {0, 0};
auto error = osTime->getCpuGpuTime(&CPUGPUTime);
EXPECT_FALSE(error);
}
TEST_F(DrmTimeTest, GetCpuGpuTimeFails) {
TimeStampData CPUGPUTime01 = {0, 0};
auto pDrm = new DrmMockFail();
osTime->updateDrm(pDrm);
auto error = osTime->getCpuGpuTime(&CPUGPUTime01);
EXPECT_FALSE(error);
}
TEST_F(DrmTimeTest, GetCpuGpuTimeCpuFails) {
TimeStampData CPUGPUTime01 = {0, 0};
auto pDrm = new DrmMockTime();
osTime->setGetTimeFunc(getTimeFuncFalse);
osTime->updateDrm(pDrm);
auto error = osTime->getCpuGpuTime(&CPUGPUTime01);
EXPECT_FALSE(error);
}
TEST_F(DrmTimeTest, detect) {
auto drm = new DrmMockCustom;
osTime->updateDrm(drm);
{
auto p = osTime->getGpuTime;
EXPECT_EQ(p, &OSTimeLinux::getGpuTime36);
}
{
drm->ioctl_res = -1;
osTime->timestampTypeDetect();
auto p = osTime->getGpuTime;
EXPECT_EQ(p, &OSTimeLinux::getGpuTime32);
}
DrmMockCustom::IoctlResExt ioctlToPass = {1, 0};
{
drm->reset();
drm->ioctl_res = -1;
drm->ioctl_res_ext = &ioctlToPass; // 2nd ioctl is successful
osTime->timestampTypeDetect();
auto p = osTime->getGpuTime;
EXPECT_EQ(p, &OSTimeLinux::getGpuTimeSplitted);
drm->ioctl_res_ext = &drm->NONE;
}
}
TEST_F(DrmTimeTest, givenGpuTimestampResolutionQueryWhenIoctlFailsThenDefaultResolutionIsReturned) {
auto defaultResolution = platformDevices[0]->capabilityTable.defaultProfilingTimerResolution;
auto drm = new DrmMockCustom();
osTime->updateDrm(drm);
drm->getParamRetValue = 0;
drm->ioctl_res = -1;
auto result = osTime->getDynamicDeviceTimerResolution(*platformDevices[0]);
EXPECT_DOUBLE_EQ(result, defaultResolution);
}
TEST_F(DrmTimeTest, givenGpuTimestampResolutionQueryWhenNoDrmThenDefaultResolutionIsReturned) {
osTime->updateDrm(nullptr);
auto defaultResolution = platformDevices[0]->capabilityTable.defaultProfilingTimerResolution;
auto result = osTime->getDynamicDeviceTimerResolution(*platformDevices[0]);
EXPECT_DOUBLE_EQ(result, defaultResolution);
}
TEST_F(DrmTimeTest, givenGpuTimestampResolutionQueryWhenIoctlSuccedsThenCorrectResolutionIsReturned) {
auto drm = new DrmMockCustom();
osTime->updateDrm(drm);
// 19200000 is frequency yelding 52.083ns resolution
drm->getParamRetValue = 19200000;
drm->ioctl_res = 0;
auto result = osTime->getDynamicDeviceTimerResolution(*platformDevices[0]);
EXPECT_DOUBLE_EQ(result, 52.08333333333333);
}
TEST_F(DrmTimeTest, givenAlwaysFailingResolutionFuncWhenGetHostTimerResolutionIsCalledThenReturnsZero) {
osTime->setResolutionFunc(resolutionFuncFalse);
auto retVal = osTime->getHostTimerResolution();
EXPECT_EQ(0, retVal);
}
TEST_F(DrmTimeTest, givenAlwaysPassingResolutionFuncWhenGetHostTimerResolutionIsCalledThenReturnsNonzero) {
osTime->setResolutionFunc(resolutionFuncTrue);
auto retVal = osTime->getHostTimerResolution();
EXPECT_EQ(5, retVal);
}
TEST_F(DrmTimeTest, givenAlwaysFailingResolutionFuncWhenGetCpuRawTimestampIsCalledThenReturnsZero) {
osTime->setResolutionFunc(resolutionFuncFalse);
auto retVal = osTime->getCpuRawTimestamp();
EXPECT_EQ(0ull, retVal);
}
TEST_F(DrmTimeTest, givenAlwaysFailingGetTimeFuncWhenGetCpuRawTimestampIsCalledThenReturnsZero) {
osTime->setGetTimeFunc(getTimeFuncFalse);
auto retVal = osTime->getCpuRawTimestamp();
EXPECT_EQ(0ull, retVal);
}
TEST_F(DrmTimeTest, givenAlwaysPassingResolutionFuncWhenGetCpuRawTimestampIsCalledThenReturnsNonzero) {
actualTime = 4;
auto retVal = osTime->getCpuRawTimestamp();
EXPECT_EQ(1ull, retVal);
}

View File

@ -0,0 +1,23 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "gtest/gtest.h"
#include "os_interface/linux/mock_performance_counters_linux.h"
#include "os_interface/mock_performance_counters.h"
using namespace NEO;
struct PerformanceCountersLinuxTest : public PerformanceCountersFixture,
public ::testing::Test {
void SetUp() override {
PerformanceCountersFixture::SetUp();
}
void TearDown() override {
PerformanceCountersFixture::TearDown();
}
};

View File

@ -0,0 +1,9 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
extern "C" __attribute__((visibility("default"))) void selfDynamicLibraryFunc() {
}

View File

@ -0,0 +1,48 @@
/*
* Copyright (C) 2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/linux/sys_calls.h"
#include "drm/i915_drm.h"
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <sys/ioctl.h>
namespace NEO {
namespace SysCalls {
uint32_t closeFuncCalled = 0u;
int closeFuncArgPassed = 0;
constexpr int fakeFileDescriptor = 123;
int close(int fileDescriptor) {
closeFuncCalled++;
closeFuncArgPassed = fileDescriptor;
return 0;
}
int open(const char *file, int flags) {
if (strcmp(file, "/dev/dri/by-path/pci-0000:invalid-render") == 0) {
return 0;
}
if (strcmp(file, "/dev/dri/renderD129") == 0) {
return fakeFileDescriptor;
}
return 0;
}
int ioctl(int fileDescriptor, unsigned long int request, void *arg) {
if (fileDescriptor == fakeFileDescriptor) {
if (request == DRM_IOCTL_VERSION) {
auto pVersion = reinterpret_cast<drm_version_t *>(arg);
snprintf(pVersion->name, pVersion->name_len, "i915");
}
}
return 0;
}
} // namespace SysCalls
} // namespace NEO

View File

@ -0,0 +1,395 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "mock_performance_counters.h"
#include "core/execution_environment/root_device_environment.h"
#include "core/os_interface/os_interface.h"
#include "mocks/mock_execution_environment.h"
using namespace MetricsLibraryApi;
namespace NEO {
//////////////////////////////////////////////////////
// MockMetricsLibrary::open
//////////////////////////////////////////////////////
bool MockMetricsLibrary::open() {
if (validOpen) {
++openCount;
return true;
} else {
return false;
}
}
//////////////////////////////////////////////////////
// MockMetricsLibrary::contextCreate
//////////////////////////////////////////////////////
bool MockMetricsLibrary::contextCreate(const ClientType_1_0 &client, ClientData_1_0 &clientData, ContextCreateData_1_0 &createData, ContextHandle_1_0 &handle) {
if (client.Api != MetricsLibraryApi::ClientApi::OpenCL) {
return false;
}
handle.data = reinterpret_cast<void *>(this);
++contextCount;
return true;
}
//////////////////////////////////////////////////////
// MockMetricsLibrary::contextDelete
//////////////////////////////////////////////////////
bool MockMetricsLibrary::contextDelete(const ContextHandle_1_0 &handle) {
if (!handle.IsValid()) {
return false;
}
--contextCount;
return true;
}
//////////////////////////////////////////////////////
// MockMetricsLibrary::hwCountersCreate
//////////////////////////////////////////////////////
bool MockMetricsLibrary::hwCountersCreate(const ContextHandle_1_0 &context, const uint32_t slots, const ConfigurationHandle_1_0 mmio, QueryHandle_1_0 &handle) {
++queryCount;
return true;
};
//////////////////////////////////////////////////////
// MockMetricsLibrary::hwCountersDelete
//////////////////////////////////////////////////////
bool MockMetricsLibrary::hwCountersDelete(const QueryHandle_1_0 &handle) {
--queryCount;
return true;
}
//////////////////////////////////////////////////////
// MockMetricsLibrary::hwCountersGetReport
//////////////////////////////////////////////////////
bool MockMetricsLibrary::hwCountersGetReport(const QueryHandle_1_0 &handle, const uint32_t slot, const uint32_t slotsCount, const uint32_t dataSize, void *data) {
return validGetData;
}
//////////////////////////////////////////////////////
// MockMetricsLibrary::hwCountersGetApiReportSize
//////////////////////////////////////////////////////
uint32_t MockMetricsLibrary::hwCountersGetApiReportSize() {
return 1;
}
//////////////////////////////////////////////////////
// MockMetricsLibrary::hwCountersGetGpuReportSize
//////////////////////////////////////////////////////
uint32_t MockMetricsLibrary::hwCountersGetGpuReportSize() {
return sizeof(HwPerfCounter);
}
//////////////////////////////////////////////////////
// MockMetricsLibrary::commandBufferGet
//////////////////////////////////////////////////////
bool MockMetricsLibrary::commandBufferGet(CommandBufferData_1_0 &data) {
MI_REPORT_PERF_COUNT mirpc = {};
mirpc.init();
DEBUG_BREAK_IF(data.Data == nullptr);
memcpy(data.Data, &mirpc, sizeof(mirpc));
return true;
}
//////////////////////////////////////////////////////
// MockMetricsLibrary::commandBufferGetSize
//////////////////////////////////////////////////////
bool MockMetricsLibrary::commandBufferGetSize(const CommandBufferData_1_0 &commandBufferData, CommandBufferSize_1_0 &commandBufferSize) {
commandBufferSize.GpuMemorySize = sizeof(MI_REPORT_PERF_COUNT);
return true;
}
//////////////////////////////////////////////////////
// MockMetricsLibrary::getProcAddress
//////////////////////////////////////////////////////
void *MockMetricsLibraryDll::getProcAddress(const std::string &procName) {
if (procName == METRICS_LIBRARY_CONTEXT_CREATE_1_0) {
return validContextCreate
? reinterpret_cast<void *>(&MockMetricsLibraryValidInterface::ContextCreate)
: nullptr;
} else if (procName == METRICS_LIBRARY_CONTEXT_DELETE_1_0) {
return validContextDelete
? reinterpret_cast<void *>(&MockMetricsLibraryValidInterface::ContextDelete)
: nullptr;
} else {
return nullptr;
}
}
//////////////////////////////////////////////////////
// MockMetricsLibrary::isLoaded
//////////////////////////////////////////////////////
bool MockMetricsLibraryDll::isLoaded() {
return validIsLoaded;
}
//////////////////////////////////////////////////////
// MockMetricsLibraryValidInterface::ContextCreate
//////////////////////////////////////////////////////
StatusCode MockMetricsLibraryValidInterface::ContextCreate(ClientType_1_0 clientType, ContextCreateData_1_0 *createData, ContextHandle_1_0 *handle) {
// Validate input.
EXPECT_EQ(clientType.Api, ClientApi::OpenCL);
// Library handle.
auto library = new MockMetricsLibraryValidInterface();
handle->data = library;
EXPECT_TRUE(handle->IsValid());
// Context count.
library->contextCount++;
EXPECT_EQ(library->contextCount, 1u);
return handle->IsValid()
? StatusCode::Success
: StatusCode::Failed;
}
//////////////////////////////////////////////////////
// MockMetricsLibraryValidInterface::ContextDelete
//////////////////////////////////////////////////////
StatusCode MockMetricsLibraryValidInterface::ContextDelete(const ContextHandle_1_0 handle) {
auto validHandle = handle.IsValid();
auto library = static_cast<MockMetricsLibraryValidInterface *>(handle.data);
// Validate input.
EXPECT_TRUE(validHandle);
EXPECT_TRUE(validHandle);
EXPECT_EQ(--library->contextCount, 0u);
// Delete handle.
delete library;
return validHandle
? StatusCode::Success
: StatusCode::IncorrectObject;
}
//////////////////////////////////////////////////////
// MockMetricsLibraryInterface::QueryCreate
//////////////////////////////////////////////////////
StatusCode MockMetricsLibraryValidInterface::QueryCreate(const QueryCreateData_1_0 *createData, QueryHandle_1_0 *handle) {
EXPECT_NE(handle, nullptr);
EXPECT_NE(createData, nullptr);
EXPECT_GE(createData->Slots, 1u);
EXPECT_TRUE(createData->HandleContext.IsValid());
EXPECT_EQ(createData->Type, ObjectType::QueryHwCounters);
handle->data = new uint32_t(0);
return StatusCode::Success;
}
//////////////////////////////////////////////////////
// MockMetricsLibraryValidInterface::QueryDelete
//////////////////////////////////////////////////////
StatusCode MockMetricsLibraryValidInterface::QueryDelete(const QueryHandle_1_0 handle) {
EXPECT_TRUE(handle.IsValid());
delete (uint32_t *)handle.data;
return StatusCode::Success;
}
//////////////////////////////////////////////////////
// MockMetricsLibraryValidInterface::CommandBufferGetSize
//////////////////////////////////////////////////////
StatusCode MockMetricsLibraryValidInterface::CommandBufferGetSize(const CommandBufferData_1_0 *data, CommandBufferSize_1_0 *size) {
auto library = static_cast<MockMetricsLibraryValidInterface *>(data->HandleContext.data);
EXPECT_NE(data, nullptr);
EXPECT_TRUE(data->HandleContext.IsValid());
EXPECT_TRUE(data->QueryHwCounters.Handle.IsValid());
EXPECT_EQ(data->Type, GpuCommandBufferType::Render);
EXPECT_EQ(data->CommandsType, ObjectType::QueryHwCounters);
EXPECT_NE(size, nullptr);
size->GpuMemorySize = library->validGpuReportSize
? 123
: 0;
return library->validGpuReportSize
? StatusCode::Success
: StatusCode::Failed;
}
//////////////////////////////////////////////////////
// MockMetricsLibraryValidInterface::CommandBufferGet
//////////////////////////////////////////////////////
StatusCode MockMetricsLibraryValidInterface::CommandBufferGet(const CommandBufferData_1_0 *data) {
EXPECT_NE(data, nullptr);
EXPECT_TRUE(data->HandleContext.IsValid());
EXPECT_TRUE(data->QueryHwCounters.Handle.IsValid());
EXPECT_EQ(data->Type, GpuCommandBufferType::Render);
EXPECT_EQ(data->CommandsType, ObjectType::QueryHwCounters);
EXPECT_NE(data->Data, nullptr);
EXPECT_GT(data->Size, 0u);
return StatusCode::Success;
}
//////////////////////////////////////////////////////
// MockMetricsLibraryValidInterface::CommandBufferGet
//////////////////////////////////////////////////////
StatusCode MockMetricsLibraryValidInterface::GetParameter(const ParameterType parameter, ValueType *type, TypedValue_1_0 *value) {
EXPECT_NE(type, nullptr);
EXPECT_NE(value, nullptr);
switch (parameter) {
case ParameterType::QueryHwCountersReportApiSize:
*type = ValueType::Uint32;
value->ValueUInt32 = 123;
break;
case ParameterType::QueryHwCountersReportGpuSize:
*type = ValueType::Uint32;
value->ValueUInt32 = 123;
break;
default:
EXPECT_TRUE(false);
break;
}
return StatusCode::Success;
}
//////////////////////////////////////////////////////
// MockMetricsLibraryValidInterface::ConfigurationCreate
//////////////////////////////////////////////////////
StatusCode ML_STDCALL MockMetricsLibraryValidInterface::ConfigurationCreate(const ConfigurationCreateData_1_0 *createData, ConfigurationHandle_1_0 *handle) {
EXPECT_NE(createData, nullptr);
EXPECT_NE(handle, nullptr);
EXPECT_TRUE(createData->HandleContext.IsValid());
const bool validType = (createData->Type == ObjectType::ConfigurationHwCountersOa) ||
(createData->Type == ObjectType::ConfigurationHwCountersUser);
// Mock overrides
auto api = static_cast<MockMetricsLibraryValidInterface *>(createData->HandleContext.data);
if (!api->validCreateConfigurationOa && (createData->Type == ObjectType::ConfigurationHwCountersOa)) {
return StatusCode::Failed;
}
if (!api->validCreateConfigurationUser && (createData->Type == ObjectType::ConfigurationHwCountersUser)) {
return StatusCode::Failed;
}
EXPECT_TRUE(validType);
handle->data = api;
return StatusCode::Success;
}
//////////////////////////////////////////////////////
// MockMetricsLibraryValidInterface::ConfigurationActivate
//////////////////////////////////////////////////////
StatusCode ML_STDCALL MockMetricsLibraryValidInterface::ConfigurationActivate(const ConfigurationHandle_1_0 handle, const ConfigurationActivateData_1_0 *activateData) {
auto api = static_cast<MockMetricsLibraryValidInterface *>(handle.data);
return api->validActivateConfigurationOa
? StatusCode::Success
: StatusCode::Failed;
}
//////////////////////////////////////////////////////
// MockMetricsLibraryValidInterface::ConfigurationDelete
//////////////////////////////////////////////////////
StatusCode ML_STDCALL MockMetricsLibraryValidInterface::ConfigurationDelete(const ConfigurationHandle_1_0 handle) {
EXPECT_TRUE(handle.IsValid());
return StatusCode::Success;
}
//////////////////////////////////////////////////////
// MockMetricsLibraryValidInterface::GetData
//////////////////////////////////////////////////////
StatusCode MockMetricsLibraryValidInterface::GetData(GetReportData_1_0 *data) {
EXPECT_NE(data, nullptr);
EXPECT_EQ(data->Type, ObjectType::QueryHwCounters);
EXPECT_TRUE(data->Query.Handle.IsValid());
EXPECT_GE(data->Query.Slot, 0u);
EXPECT_GT(data->Query.SlotsCount, 0u);
EXPECT_NE(data->Query.Data, nullptr);
EXPECT_GT(data->Query.DataSize, 0u);
return StatusCode::Success;
}
//////////////////////////////////////////////////////
// PerformanceCountersDeviceFixture::SetUp
//////////////////////////////////////////////////////
void PerformanceCountersDeviceFixture::SetUp() {
createFunc = Device::createPerformanceCountersFunc;
Device::createPerformanceCountersFunc = MockPerformanceCounters::create;
}
//////////////////////////////////////////////////////
// PerformanceCountersDeviceFixture::TearDown
//////////////////////////////////////////////////////
void PerformanceCountersDeviceFixture::TearDown() {
Device::createPerformanceCountersFunc = createFunc;
}
//////////////////////////////////////////////////////
// PerformanceCountersMetricsLibraryFixture::SetUp
//////////////////////////////////////////////////////
void PerformanceCountersMetricsLibraryFixture::SetUp() {
PerformanceCountersFixture::SetUp();
}
//////////////////////////////////////////////////////
// PerformanceCountersMetricsLibraryFixture::TearDown
//////////////////////////////////////////////////////
void PerformanceCountersMetricsLibraryFixture::TearDown() {
device->setPerfCounters(nullptr);
PerformanceCountersFixture::TearDown();
}
//////////////////////////////////////////////////////
// PerformanceCountersFixture::PerformanceCountersFixture
//////////////////////////////////////////////////////
PerformanceCountersFixture::PerformanceCountersFixture() {
executionEnvironment = std::make_unique<MockExecutionEnvironment>();
rootDeviceEnvironment = std::make_unique<RootDeviceEnvironment>(*executionEnvironment);
}
//////////////////////////////////////////////////////
// PerformanceCountersFixture::~PerformanceCountersFixture
//////////////////////////////////////////////////////
PerformanceCountersFixture::~PerformanceCountersFixture() {
}
//////////////////////////////////////////////////////
// PerformanceCountersMetricsLibraryFixture::createPerformanceCounters
//////////////////////////////////////////////////////
void PerformanceCountersMetricsLibraryFixture::createPerformanceCounters(const bool validMetricsLibraryApi, const bool mockMetricsLibrary) {
performanceCountersBase = MockPerformanceCounters::create(&device->getDevice());
auto metricsLibraryInterface = performanceCountersBase->getMetricsLibraryInterface();
auto metricsLibraryDll = std::make_unique<MockMetricsLibraryDll>();
EXPECT_NE(performanceCountersBase, nullptr);
EXPECT_NE(metricsLibraryInterface, nullptr);
device->setPerfCounters(performanceCountersBase.get());
// Attached mock version of metrics library interface.
if (mockMetricsLibrary) {
performanceCountersBase->setMetricsLibraryInterface(std::make_unique<MockMetricsLibrary>());
metricsLibraryInterface = performanceCountersBase->getMetricsLibraryInterface();
} else {
performanceCountersBase->setMetricsLibraryInterface(std::make_unique<MetricsLibrary>());
metricsLibraryInterface = performanceCountersBase->getMetricsLibraryInterface();
}
if (validMetricsLibraryApi) {
metricsLibraryInterface->api = std::make_unique<MockMetricsLibraryValidInterface>();
metricsLibraryInterface->osLibrary = std::move(metricsLibraryDll);
} else {
metricsLibraryDll->validContextCreate = false;
metricsLibraryDll->validContextDelete = false;
metricsLibraryDll->validIsLoaded = false;
metricsLibraryInterface->api = std::make_unique<MockMetricsLibraryInvalidInterface>();
metricsLibraryInterface->osLibrary = std::move(metricsLibraryDll);
}
EXPECT_NE(metricsLibraryInterface->api, nullptr);
}
} // namespace NEO

View File

@ -0,0 +1,251 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/device/device.h"
#include "opencl/source/memory_manager/os_agnostic_memory_manager.h"
#include "instrumentation.h"
#include "mocks/mock_command_queue.h"
#include "mocks/mock_context.h"
#include "mocks/mock_device.h"
namespace NEO {
//////////////////////////////////////////////////////
// Metrics Library types
//////////////////////////////////////////////////////
using MetricsLibraryApi::ClientApi;
using MetricsLibraryApi::ClientData_1_0;
using MetricsLibraryApi::ClientGen;
using MetricsLibraryApi::ClientType_1_0;
using MetricsLibraryApi::CommandBufferData_1_0;
using MetricsLibraryApi::CommandBufferSize_1_0;
using MetricsLibraryApi::ConfigurationHandle_1_0;
using MetricsLibraryApi::ContextCreateData_1_0;
using MetricsLibraryApi::ContextHandle_1_0;
using MetricsLibraryApi::GpuMemory_1_0;
using MetricsLibraryApi::QueryHandle_1_0;
//////////////////////////////////////////////////////
// MI_REPORT_PERF_COUNT definition for all GENs
//////////////////////////////////////////////////////
struct MI_REPORT_PERF_COUNT {
uint32_t DwordLength : BITFIELD_RANGE(0, 5);
uint32_t Reserved_6 : BITFIELD_RANGE(6, 22);
uint32_t MiCommandOpcode : BITFIELD_RANGE(23, 28);
uint32_t CommandType : BITFIELD_RANGE(29, 31);
uint64_t UseGlobalGtt : BITFIELD_RANGE(0, 0);
uint64_t Reserved_33 : BITFIELD_RANGE(1, 3);
uint64_t CoreModeEnable : BITFIELD_RANGE(4, 4);
uint64_t Reserved_37 : BITFIELD_RANGE(5, 5);
uint64_t MemoryAddress : BITFIELD_RANGE(6, 63);
uint32_t ReportId;
typedef enum tagDWORD_LENGTH {
DWORD_LENGTH_EXCLUDES_DWORD_0_1 = 0x2,
} DWORD_LENGTH;
typedef enum tagMI_COMMAND_OPCODE {
MI_COMMAND_OPCODE_MI_REPORT_PERF_COUNT = 0x28,
} MI_COMMAND_OPCODE;
typedef enum tagCOMMAND_TYPE {
COMMAND_TYPE_MI_COMMAND = 0x0,
} COMMAND_TYPE;
inline void init(void) {
memset(this, 0, sizeof(MI_REPORT_PERF_COUNT));
DwordLength = DWORD_LENGTH_EXCLUDES_DWORD_0_1;
MiCommandOpcode = MI_COMMAND_OPCODE_MI_REPORT_PERF_COUNT;
CommandType = COMMAND_TYPE_MI_COMMAND;
}
};
// clang-format off
//////////////////////////////////////////////////////
// MockMetricsLibrary
//////////////////////////////////////////////////////
class MockMetricsLibrary : public MetricsLibrary {
public:
uint32_t openCount = 0;
uint32_t contextCount = 0;
uint32_t queryCount = 0;
bool validOpen = true;
bool validGetData = true;
// Library open / close functions.
bool open() override;
// Context create / destroy functions.
bool contextCreate (const ClientType_1_0 &client, ClientData_1_0& clientData, ContextCreateData_1_0 &createData, ContextHandle_1_0 &handle) override;
bool contextDelete (const ContextHandle_1_0 &handle) override;
// HwCounters functions.
bool hwCountersCreate (const ContextHandle_1_0 &context, const uint32_t slots, const ConfigurationHandle_1_0 mmio, QueryHandle_1_0 &handle) override;
bool hwCountersDelete (const QueryHandle_1_0 &handle) override;
bool hwCountersGetReport (const QueryHandle_1_0 &handle, const uint32_t slot, const uint32_t slotsCount, const uint32_t dataSize, void *data) override;
uint32_t hwCountersGetApiReportSize() override;
uint32_t hwCountersGetGpuReportSize() override;
// Command buffer functions.
bool commandBufferGet (CommandBufferData_1_0 &data) override;
bool commandBufferGetSize (const CommandBufferData_1_0 &commandBufferData, CommandBufferSize_1_0 &commandBufferSize) override;
// Oa configuration functions.
bool oaConfigurationCreate (const ContextHandle_1_0 &context, ConfigurationHandle_1_0 &handle) override { return true; }
bool oaConfigurationDelete (const ConfigurationHandle_1_0 &handle) override { return true; }
bool oaConfigurationActivate (const ConfigurationHandle_1_0 &handle) override { return true; }
bool oaConfigurationDeactivate (const ConfigurationHandle_1_0 &handle) override { return true; }
// User mmio configuration functions.
bool userConfigurationCreate (const ContextHandle_1_0 &context, ConfigurationHandle_1_0 &handle) override { return true; }
bool userConfigurationDelete (const ConfigurationHandle_1_0 &handle) override { return true; }
};
//////////////////////////////////////////////////////
// MockMetricsLibraryValidInterface
//////////////////////////////////////////////////////
class MockMetricsLibraryValidInterface: public MetricsLibraryInterface {
public:
uint32_t contextCount = 0;
bool validCreateConfigurationOa = true;
bool validCreateConfigurationUser = true;
bool validActivateConfigurationOa = true;
bool validGpuReportSize = true;
static StatusCode ML_STDCALL ContextCreate ( ClientType_1_0 clientType, ContextCreateData_1_0* createData, ContextHandle_1_0* handle );
static StatusCode ML_STDCALL ContextDelete (const ContextHandle_1_0 handle);
static StatusCode ML_STDCALL GetParameter (const ParameterType parameter, ValueType *type, TypedValue_1_0 *value);
static StatusCode ML_STDCALL CommandBufferGet (const CommandBufferData_1_0 *data);
static StatusCode ML_STDCALL CommandBufferGetSize (const CommandBufferData_1_0 *data, CommandBufferSize_1_0 *size);
static StatusCode ML_STDCALL QueryCreate (const QueryCreateData_1_0 *createData, QueryHandle_1_0 *handle);
static StatusCode ML_STDCALL QueryDelete (const QueryHandle_1_0 handle);
static StatusCode ML_STDCALL ConfigurationCreate (const ConfigurationCreateData_1_0 *createData, ConfigurationHandle_1_0 *handle);
static StatusCode ML_STDCALL ConfigurationActivate (const ConfigurationHandle_1_0 handle, const ConfigurationActivateData_1_0 *activateData);
static StatusCode ML_STDCALL ConfigurationDeactivate (const ConfigurationHandle_1_0 handle) { return StatusCode::Success; }
static StatusCode ML_STDCALL ConfigurationDelete (const ConfigurationHandle_1_0 handle);
static StatusCode ML_STDCALL GetData (GetReportData_1_0 *data);
MockMetricsLibraryValidInterface()
{
contextCreate = &ContextCreate;
contextDelete = &ContextDelete;
functions.GetParameter = &GetParameter;
functions.CommandBufferGet = &CommandBufferGet;
functions.CommandBufferGetSize = &CommandBufferGetSize;
functions.QueryCreate = &QueryCreate;
functions.QueryDelete = &QueryDelete;
functions.ConfigurationCreate = &ConfigurationCreate;
functions.ConfigurationActivate = &ConfigurationActivate;
functions.ConfigurationDeactivate = &ConfigurationDeactivate;
functions.ConfigurationDelete = &ConfigurationDelete;
functions.GetData = &GetData;
}
};
//////////////////////////////////////////////////////
// MockMetricsLibraryInvalidInterface
//////////////////////////////////////////////////////
class MockMetricsLibraryInvalidInterface: public MetricsLibraryInterface {
public:
static StatusCode ML_STDCALL ContextCreate ( ClientType_1_0 clientType, ContextCreateData_1_0* createData, ContextHandle_1_0* handle ){ return StatusCode::Failed;}
static StatusCode ML_STDCALL ContextDelete (const ContextHandle_1_0 handle){ return StatusCode::Failed;}
static StatusCode ML_STDCALL GetParameter (const ParameterType parameter, ValueType *type, TypedValue_1_0 *value){ return StatusCode::Failed;}
static StatusCode ML_STDCALL CommandBufferGet (const CommandBufferData_1_0 *data){ return StatusCode::Failed;}
static StatusCode ML_STDCALL CommandBufferGetSize (const CommandBufferData_1_0 *data, CommandBufferSize_1_0 *size){ return StatusCode::Failed;}
static StatusCode ML_STDCALL QueryCreate (const QueryCreateData_1_0 *createData, QueryHandle_1_0 *handle){ return StatusCode::Failed;}
static StatusCode ML_STDCALL QueryDelete (const QueryHandle_1_0 handle){ return StatusCode::Failed;}
static StatusCode ML_STDCALL ConfigurationCreate (const ConfigurationCreateData_1_0 *createData, ConfigurationHandle_1_0 *handle){ return StatusCode::Failed;}
static StatusCode ML_STDCALL ConfigurationActivate (const ConfigurationHandle_1_0 handle, const ConfigurationActivateData_1_0 *activateData){ return StatusCode::Failed;}
static StatusCode ML_STDCALL ConfigurationDeactivate (const ConfigurationHandle_1_0 handle){ return StatusCode::Failed;}
static StatusCode ML_STDCALL ConfigurationDelete (const ConfigurationHandle_1_0 handle){ return StatusCode::Failed;}
static StatusCode ML_STDCALL GetData (GetReportData_1_0 *data){ return StatusCode::Failed;}
MockMetricsLibraryInvalidInterface()
{
contextCreate = &ContextCreate;
contextDelete = &ContextDelete;
functions.GetParameter = &GetParameter;
functions.CommandBufferGet = &CommandBufferGet;
functions.CommandBufferGetSize = &CommandBufferGetSize;
functions.QueryCreate = &QueryCreate;
functions.QueryDelete = &QueryDelete;
functions.ConfigurationCreate = &ConfigurationCreate;
functions.ConfigurationActivate = &ConfigurationActivate;
functions.ConfigurationDeactivate = &ConfigurationDeactivate;
functions.ConfigurationDelete = &ConfigurationDelete;
functions.GetData = &GetData;
}
};
// clang-format on
//////////////////////////////////////////////////////
// MockMetricsLibraryDll
//////////////////////////////////////////////////////
class MockMetricsLibraryDll : public OsLibrary {
public:
bool validContextCreate = true;
bool validContextDelete = true;
bool validIsLoaded = true;
void *getProcAddress(const std::string &procName) override;
bool isLoaded() override;
};
//////////////////////////////////////////////////////
// MockPerformanceCounters
//////////////////////////////////////////////////////
class MockPerformanceCounters {
public:
static std::unique_ptr<PerformanceCounters> create(Device *device);
};
//////////////////////////////////////////////////////
// PerformanceCountersDeviceFixture
//////////////////////////////////////////////////////
struct PerformanceCountersDeviceFixture {
virtual void SetUp();
virtual void TearDown();
decltype(&PerformanceCounters::create) createFunc;
};
struct MockExecutionEnvironment;
struct RootDeviceEnvironment;
/////////////////////////////////////////////////////
// PerformanceCountersFixture
//////////////////////////////////////////////////////
struct PerformanceCountersFixture {
PerformanceCountersFixture();
~PerformanceCountersFixture();
virtual void SetUp();
virtual void TearDown();
virtual void createPerfCounters();
cl_queue_properties queueProperties = {};
std::unique_ptr<MockClDevice> device;
std::unique_ptr<MockContext> context;
std::unique_ptr<MockCommandQueue> queue;
std::unique_ptr<OSInterface> osInterface;
std::unique_ptr<PerformanceCounters> performanceCountersBase;
std::unique_ptr<MockExecutionEnvironment> executionEnvironment;
std::unique_ptr<RootDeviceEnvironment> rootDeviceEnvironment;
};
//////////////////////////////////////////////////////
// PerformanceCountersMetricsLibraryFixture
//////////////////////////////////////////////////////
struct PerformanceCountersMetricsLibraryFixture : PerformanceCountersFixture {
void SetUp() override;
void TearDown() override;
void createPerformanceCounters(const bool validMetricsLibraryApi, const bool mockMatricsLibrary);
std::unique_ptr<PerformanceCounters> performanceCountersBase;
};
} // namespace NEO

View File

@ -0,0 +1,18 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/os_context.h"
#include "gtest/gtest.h"
using namespace NEO;
TEST(OSContext, whenCreatingDefaultOsContextThenExpectInitializedAlways) {
OsContext *osContext = OsContext::create(nullptr, 0, 0, aub_stream::ENGINE_RCS, PreemptionMode::Disabled, false);
EXPECT_TRUE(osContext->isInitialized());
delete osContext;
}

View File

@ -0,0 +1,22 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/os_interface.h"
#include "gtest/gtest.h"
#include <type_traits>
TEST(OSInterface, NonCopyable) {
EXPECT_FALSE(std::is_move_constructible<NEO::OSInterface>::value);
EXPECT_FALSE(std::is_copy_constructible<NEO::OSInterface>::value);
}
TEST(OSInterface, NonAssignable) {
EXPECT_FALSE(std::is_move_assignable<NEO::OSInterface>::value);
EXPECT_FALSE(std::is_copy_assignable<NEO::OSInterface>::value);
}

View File

@ -0,0 +1,118 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#if defined(_WIN32)
#include "core/os_interface/windows/os_library_win.h"
#elif defined(__linux__)
#include "core/os_interface/linux/os_library_linux.h"
#endif
#include "core/os_interface/os_library.h"
#include "test.h"
#include "fixtures/memory_management_fixture.h"
#include "gtest/gtest.h"
#include <memory>
namespace Os {
extern const char *frontEndDllName;
extern const char *igcDllName;
extern const char *testDllName;
} // namespace Os
const std::string fakeLibName = "_fake_library_name_";
const std::string fnName = "testDynamicLibraryFunc";
using namespace NEO;
TEST(OSLibraryTest, whenLibraryNameIsEmptyThenCurrentProcesIsUsedAsLibrary) {
std::unique_ptr<OsLibrary> library{OsLibrary::load("")};
EXPECT_NE(nullptr, library);
void *ptr = library->getProcAddress("selfDynamicLibraryFunc");
EXPECT_NE(nullptr, ptr);
}
TEST(OSLibraryTest, CreateFake) {
OsLibrary *library = OsLibrary::load(fakeLibName);
EXPECT_EQ(nullptr, library);
}
TEST(OSLibraryTest, whenLibraryNameIsValidThenLibraryIsLoadedCorrectly) {
std::unique_ptr<OsLibrary> library(OsLibrary::load(Os::testDllName));
EXPECT_NE(nullptr, library);
}
TEST(OSLibraryTest, whenSymbolNameIsValidThenGetProcAddressReturnsNonNullPointer) {
std::unique_ptr<OsLibrary> library(OsLibrary::load(Os::testDllName));
EXPECT_NE(nullptr, library);
void *ptr = library->getProcAddress(fnName);
EXPECT_NE(nullptr, ptr);
}
TEST(OSLibraryTest, whenSymbolNameIsInvalidThenGetProcAddressReturnsNullPointer) {
std::unique_ptr<OsLibrary> library(OsLibrary::load(Os::testDllName));
EXPECT_NE(nullptr, library);
void *ptr = library->getProcAddress(fnName + "invalid");
EXPECT_EQ(nullptr, ptr);
}
using OsLibraryTestWithFailureInjection = Test<MemoryManagementFixture>;
TEST_F(OsLibraryTestWithFailureInjection, testFailNew) {
InjectedFunction method = [](size_t failureIndex) {
std::string libName(Os::testDllName);
// System under test
OsLibrary *library = OsLibrary::load(libName);
if (MemoryManagement::nonfailingAllocation == failureIndex) {
EXPECT_NE(nullptr, library);
} else {
EXPECT_EQ(nullptr, library);
}
// Make sure that we only have 1 buffer allocated at a time
delete library;
};
injectFailures(method);
}
TEST(OsLibrary, whenCallingIndexOperatorThenObjectConvertibleToFunctionOrVoidPointerIsReturned) {
struct MockOsLibrary : OsLibrary {
void *getProcAddress(const std::string &procName) override {
lastRequestedProcName = procName;
return ptrToReturn;
}
bool isLoaded() override { return true; }
void *ptrToReturn = nullptr;
std::string lastRequestedProcName;
};
MockOsLibrary lib;
int varA;
int varB;
int varC;
using FunctionTypeA = void (*)(int *, float);
using FunctionTypeB = int (*)();
lib.ptrToReturn = &varA;
FunctionTypeA functionA = lib["funcA"];
EXPECT_STREQ("funcA", lib.lastRequestedProcName.c_str());
EXPECT_EQ(&varA, reinterpret_cast<void *>(functionA));
lib.ptrToReturn = &varB;
FunctionTypeB functionB = lib["funcB"];
EXPECT_STREQ("funcB", lib.lastRequestedProcName.c_str());
EXPECT_EQ(&varB, reinterpret_cast<void *>(functionB));
lib.ptrToReturn = &varC;
void *rawPtr = lib["funcC"];
EXPECT_STREQ("funcC", lib.lastRequestedProcName.c_str());
EXPECT_EQ(&varC, rawPtr);
}

View File

@ -0,0 +1,20 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/os_memory.h"
#include "gtest/gtest.h"
using namespace NEO;
TEST(OSMemory, reserveCpuAddressRange) {
auto osMemory = OSMemory::create();
size_t reservedCpuAddressRangeSize = 1024;
auto reservedCpuAddressRange = osMemory->reserveCpuAddressRange(reservedCpuAddressRangeSize);
EXPECT_NE(reservedCpuAddressRange, nullptr);
osMemory->releaseCpuAddressRange(reservedCpuAddressRange, reservedCpuAddressRangeSize);
}

View File

@ -0,0 +1,20 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "opencl/source/os_interface/performance_counters.h"
#include "test.h"
using namespace NEO;
struct PerformanceCountersGenTest : public ::testing::Test {
};
class MockPerformanceCountersGen : public PerformanceCounters {
public:
MockPerformanceCountersGen() : PerformanceCounters() {
}
};

View File

@ -0,0 +1,592 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/execution_environment/root_device_environment.h"
#include "core/os_interface/os_interface.h"
#include "core/os_interface/os_time.h"
#include "core/unit_tests/helpers/debug_manager_state_restore.h"
#include "core/utilities/tag_allocator.h"
#include "fixtures/device_instrumentation_fixture.h"
#include "gtest/gtest.h"
#include "mocks/mock_device.h"
#include "mocks/mock_execution_environment.h"
#include "os_interface/mock_performance_counters.h"
using namespace NEO;
struct PerformanceCountersDeviceTest : public PerformanceCountersDeviceFixture,
public DeviceInstrumentationFixture,
public ::testing::Test {
void SetUp() override {
PerformanceCountersDeviceFixture::SetUp();
}
void TearDown() override {
PerformanceCountersDeviceFixture::TearDown();
}
};
TEST_F(PerformanceCountersDeviceTest, createDeviceWithPerformanceCounters) {
DeviceInstrumentationFixture::SetUp(true);
EXPECT_NE(nullptr, device->getPerformanceCounters());
}
TEST_F(PerformanceCountersDeviceTest, createDeviceWithoutPerformanceCounters) {
DeviceInstrumentationFixture::SetUp(false);
EXPECT_EQ(nullptr, device->getPerformanceCounters());
}
struct PerformanceCountersTest : public PerformanceCountersFixture,
public ::testing::Test {
public:
void SetUp() override {
PerformanceCountersFixture::SetUp();
}
void TearDown() override {
PerformanceCountersFixture::TearDown();
}
};
TEST_F(PerformanceCountersTest, createPerformanceCounters) {
auto performanceCounters = PerformanceCounters::create(&device->getDevice());
EXPECT_NE(nullptr, performanceCounters);
EXPECT_NE(nullptr, performanceCounters.get());
}
TEST_F(PerformanceCountersTest, givenPerformanceCountersWhenCreatedThenAllValuesProperlyInitialized) {
createPerfCounters();
EXPECT_NE(nullptr, performanceCountersBase->getMetricsLibraryInterface());
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
struct PerformanceCountersProcessEventTest : public PerformanceCountersTest,
public ::testing::WithParamInterface<bool> {
void SetUp() override {
PerformanceCountersTest::SetUp();
createPerfCounters();
eventComplete = true;
outputParamSize = 0;
inputParamSize = performanceCountersBase->getApiReportSize();
inputParam.reset(new uint8_t);
}
void TearDown() override {
performanceCountersBase->shutdown();
PerformanceCountersTest::TearDown();
}
std::unique_ptr<uint8_t> inputParam;
size_t inputParamSize;
size_t outputParamSize;
bool eventComplete;
};
TEST_P(PerformanceCountersProcessEventTest, givenNullptrInputParamWhenProcessEventPerfCountersIsCalledThenReturnsFalse) {
eventComplete = GetParam();
auto retVal = performanceCountersBase->getApiReport(inputParamSize, nullptr, &outputParamSize, eventComplete);
EXPECT_FALSE(retVal);
}
TEST_P(PerformanceCountersProcessEventTest, givenCorrectInputParamWhenProcessEventPerfCountersIsCalledAndEventIsCompletedThenReturnsTrue) {
eventComplete = GetParam();
EXPECT_EQ(0ull, outputParamSize);
auto retVal = performanceCountersBase->getApiReport(inputParamSize, inputParam.get(), &outputParamSize, eventComplete);
if (eventComplete) {
EXPECT_TRUE(retVal);
EXPECT_EQ(outputParamSize, inputParamSize);
} else {
EXPECT_FALSE(retVal);
EXPECT_EQ(inputParamSize, outputParamSize);
}
}
TEST_F(PerformanceCountersProcessEventTest, givenInvalidInputParamSizeWhenProcessEventPerfCountersIsCalledThenReturnsFalse) {
EXPECT_EQ(0ull, outputParamSize);
auto retVal = performanceCountersBase->getApiReport(inputParamSize - 1, inputParam.get(), &outputParamSize, eventComplete);
EXPECT_FALSE(retVal);
EXPECT_EQ(outputParamSize, inputParamSize);
}
TEST_F(PerformanceCountersProcessEventTest, givenNullptrOutputParamSizeWhenProcessEventPerfCountersIsCalledThenDoesNotReturnsOutputSize) {
EXPECT_EQ(0ull, outputParamSize);
auto retVal = performanceCountersBase->getApiReport(inputParamSize, inputParam.get(), nullptr, eventComplete);
EXPECT_TRUE(retVal);
EXPECT_EQ(0ull, outputParamSize);
}
TEST_F(PerformanceCountersProcessEventTest, givenNullptrInputZeroSizeWhenProcessEventPerfCountersIsCalledThenQueryProperSize) {
EXPECT_EQ(0ull, outputParamSize);
auto retVal = performanceCountersBase->getApiReport(0, nullptr, &outputParamSize, eventComplete);
EXPECT_TRUE(retVal);
EXPECT_EQ(inputParamSize, outputParamSize);
}
TEST_F(PerformanceCountersProcessEventTest, givenNullptrInputZeroSizeAndNullptrOutputSizeWhenProcessEventPerfCountersIsCalledThenReturnFalse) {
EXPECT_EQ(0ull, outputParamSize);
auto retVal = performanceCountersBase->getApiReport(0, nullptr, nullptr, eventComplete);
EXPECT_FALSE(retVal);
EXPECT_EQ(0ull, outputParamSize);
}
INSTANTIATE_TEST_CASE_P(
PerfCountersTests,
PerformanceCountersProcessEventTest,
testing::Bool());
struct PerformanceCountersMetricsLibraryTest : public PerformanceCountersMetricsLibraryFixture,
public ::testing::Test {
public:
void SetUp() override {
PerformanceCountersMetricsLibraryFixture::SetUp();
}
void TearDown() override {
PerformanceCountersMetricsLibraryFixture::TearDown();
}
};
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenMetricLibraryIsValidThenQueryIsCreated) {
// Create performance counters.
createPerformanceCounters(true, true);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
// Check metric library context.
auto context = static_cast<MockMetricsLibrary *>(performanceCountersBase->getMetricsLibraryContext().data);
EXPECT_NE(nullptr, context);
EXPECT_EQ(1u, context->contextCount);
// Close library.
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenMetricLibraryIsValidThenQueryReturnsValidGpuCommands) {
// Create performance counters.
createPerformanceCounters(true, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
// Obtain required command buffer size.
uint32_t commandsSize = performanceCountersBase->getGpuCommandsSize(MetricsLibraryApi::GpuCommandBufferType::Render, true);
EXPECT_NE(0u, commandsSize);
// Fill command buffer.
uint8_t buffer[1000] = {};
HwPerfCounter perfCounter = {};
TagNode<HwPerfCounter> query = {};
query.tagForCpuAccess = &perfCounter;
EXPECT_TRUE(performanceCountersBase->getGpuCommands(MetricsLibraryApi::GpuCommandBufferType::Render, query, true, sizeof(buffer), buffer));
// Close library.
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenInitialNonCcsEngineWhenEnablingThenDontAllowCcsOnNextCalls) {
createPerformanceCounters(true, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_FALSE(performanceCountersBase->enable(true));
performanceCountersBase->shutdown();
performanceCountersBase->shutdown();
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
EXPECT_TRUE(performanceCountersBase->enable(true));
performanceCountersBase->shutdown();
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenInitialCcsEngineWhenEnablingThenDontAllowNonCcsOnNextCalls) {
createPerformanceCounters(true, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_TRUE(performanceCountersBase->enable(true));
EXPECT_TRUE(performanceCountersBase->enable(true));
EXPECT_FALSE(performanceCountersBase->enable(false));
performanceCountersBase->shutdown();
performanceCountersBase->shutdown();
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
EXPECT_TRUE(performanceCountersBase->enable(false));
performanceCountersBase->shutdown();
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenMetricLibraryIsInvalidThenQueryReturnsInvalidGpuCommands) {
// Create performance counters.
createPerformanceCounters(false, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_FALSE(performanceCountersBase->enable(true));
// Obtain required command buffer size.
uint32_t commandsSize = performanceCountersBase->getGpuCommandsSize(MetricsLibraryApi::GpuCommandBufferType::Render, true);
EXPECT_EQ(0u, commandsSize);
// Close library.
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenMetricLibraryIsValidThenApiReportSizeIsValid) {
// Create performance counters.
createPerformanceCounters(true, true);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
// Obtain api report size.
uint32_t apiReportSize = performanceCountersBase->getApiReportSize();
EXPECT_GT(apiReportSize, 0u);
// Close library.
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenMetricLibraryIsInvalidThenApiReportSizeIsInvalid) {
// Create performance counters.
createPerformanceCounters(false, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_FALSE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
// Obtain api report size.
uint32_t apiReportSize = performanceCountersBase->getApiReportSize();
EXPECT_EQ(0u, apiReportSize);
// Close library.
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenMetricLibraryIsInvalidThenGpuReportSizeIsInvalid) {
// Create performance counters.
createPerformanceCounters(false, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_FALSE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
// Obtain gpu report size.
uint32_t gpuReportSize = performanceCountersBase->getGpuReportSize();
EXPECT_EQ(0u, gpuReportSize);
// Close library.
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenMetricLibraryIsValidThenQueryIsAvailable) {
// Create performance counters.
createPerformanceCounters(true, true);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
// Close library.
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenMetricLibraryIsInvalidThenQueryIsNotAvailable) {
// Create performance counters.
createPerformanceCounters(false, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_FALSE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
// Close library.
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenMetricLibraryHasInvalidExportFunctionsDestroyThenQueryIsNotAvailable) {
createPerformanceCounters(true, false);
auto metricsLibraryInterface = performanceCountersBase->getMetricsLibraryInterface();
auto metricsLibraryDll = reinterpret_cast<MockMetricsLibraryDll *>(metricsLibraryInterface->osLibrary.get());
metricsLibraryDll->validContextCreate = true;
metricsLibraryDll->validContextDelete = false;
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
EXPECT_FALSE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
// Close library.
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenMetricLibraryHasInvalidExportFunctionsCreateAndDestroyThenQueryIsNotAvailable) {
createPerformanceCounters(true, false);
auto metricsLibraryInterface = performanceCountersBase->getMetricsLibraryInterface();
auto metricsLibraryDll = reinterpret_cast<MockMetricsLibraryDll *>(metricsLibraryInterface->osLibrary.get());
metricsLibraryDll->validContextCreate = false;
metricsLibraryDll->validContextDelete = false;
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
EXPECT_FALSE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
// Close library.
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenMetricLibraryIsValidThenQueryReturnsCorrectApiReport) {
// Create performance counters.
createPerformanceCounters(true, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
// Obtain required command buffer size.
uint32_t commandsSize = performanceCountersBase->getGpuCommandsSize(MetricsLibraryApi::GpuCommandBufferType::Render, true);
EXPECT_NE(0u, commandsSize);
// Fill command buffer.
uint8_t buffer[1000] = {};
TagNode<HwPerfCounter> query = {};
HwPerfCounter perfCounter = {};
query.tagForCpuAccess = &perfCounter;
EXPECT_TRUE(performanceCountersBase->getGpuCommands(MetricsLibraryApi::GpuCommandBufferType::Render, query, true, sizeof(buffer), buffer));
// Obtain api report size.
uint32_t apiReportSize = performanceCountersBase->getApiReportSize();
EXPECT_GT(apiReportSize, 0u);
// Obtain gpu report size.
uint32_t gpuReportSize = performanceCountersBase->getGpuReportSize();
EXPECT_GT(gpuReportSize, 0u);
// Allocate memory for api report.
uint8_t *apiReport = new uint8_t[apiReportSize];
EXPECT_NE(apiReport, nullptr);
// Obtain api report.
EXPECT_TRUE(performanceCountersBase->getApiReport(apiReportSize, apiReport, nullptr, true));
delete[] apiReport;
apiReport = nullptr;
// Close library.
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenMetricLibraryIsValidThenReferenceCounterIsValid) {
createPerformanceCounters(true, true);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_EQ(2u, performanceCountersBase->getReferenceNumber());
performanceCountersBase->shutdown();
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenMetricLibraryIsValidThenQueryHandleIsValid) {
createPerformanceCounters(true, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_TRUE(performanceCountersBase->getQueryHandle().IsValid());
EXPECT_TRUE(performanceCountersBase->getQueryHandle().IsValid());
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenOaConfigurationIsInvalidThenGpuReportSizeIsInvalid) {
createPerformanceCounters(true, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
auto metricLibraryApi = static_cast<MockMetricsLibraryValidInterface *>(performanceCountersBase->getMetricsLibraryContext().data);
metricLibraryApi->validCreateConfigurationOa = false;
EXPECT_EQ(0u, performanceCountersBase->getGpuCommandsSize(MetricsLibraryApi::GpuCommandBufferType::Render, true));
EXPECT_GT(performanceCountersBase->getGpuCommandsSize(MetricsLibraryApi::GpuCommandBufferType::Render, false), 0u);
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenMetricsLibraryIsInvalidGpuReportSizeIsInvalid) {
createPerformanceCounters(true, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
auto metricLibraryApi = static_cast<MockMetricsLibraryValidInterface *>(performanceCountersBase->getMetricsLibraryContext().data);
metricLibraryApi->validGpuReportSize = false;
EXPECT_EQ(0u, performanceCountersBase->getGpuCommandsSize(MetricsLibraryApi::GpuCommandBufferType::Render, true));
EXPECT_EQ(0u, performanceCountersBase->getGpuCommandsSize(MetricsLibraryApi::GpuCommandBufferType::Render, false));
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenAllConfigurationsAreValidThenGpuReportSizeIsValid) {
createPerformanceCounters(true, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
auto metricLibraryApi = static_cast<MockMetricsLibraryValidInterface *>(performanceCountersBase->getMetricsLibraryContext().data);
metricLibraryApi->validCreateConfigurationOa = true;
metricLibraryApi->validCreateConfigurationUser = true;
EXPECT_GT(performanceCountersBase->getGpuCommandsSize(MetricsLibraryApi::GpuCommandBufferType::Render, true), 0u);
EXPECT_GT(performanceCountersBase->getGpuCommandsSize(MetricsLibraryApi::GpuCommandBufferType::Render, false), 0u);
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenOaConfigurationsActivationIsInvalidThenGpuReportSizeIsInvalid) {
createPerformanceCounters(true, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
auto metricLibraryApi = static_cast<MockMetricsLibraryValidInterface *>(performanceCountersBase->getMetricsLibraryContext().data);
metricLibraryApi->validActivateConfigurationOa = false;
EXPECT_EQ(0u, performanceCountersBase->getGpuCommandsSize(MetricsLibraryApi::GpuCommandBufferType::Render, true));
EXPECT_GT(performanceCountersBase->getGpuCommandsSize(MetricsLibraryApi::GpuCommandBufferType::Render, false), 0u);
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, givenPerformanceCountersWhenCreatingUserConfigurationThenReturnSuccess) {
createPerformanceCounters(true, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
ConfigurationHandle_1_0 configurationHandle = {};
auto metricsLibrary = performanceCountersBase->getMetricsLibraryInterface();
auto contextHandle = performanceCountersBase->getMetricsLibraryContext();
EXPECT_TRUE(metricsLibrary->userConfigurationCreate(contextHandle, configurationHandle));
EXPECT_TRUE(metricsLibrary->userConfigurationDelete(configurationHandle));
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, getHwPerfCounterReturnsValidPointer) {
createPerformanceCounters(true, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
ASSERT_NE(nullptr, queue->getPerfCounters());
std::unique_ptr<Event> event(new Event(queue.get(), CL_COMMAND_COPY_BUFFER, 0, 0));
ASSERT_NE(nullptr, event);
HwPerfCounter *perfCounter = event->getHwPerfCounterNode()->tagForCpuAccess;
ASSERT_NE(nullptr, perfCounter);
ASSERT_EQ(0ULL, perfCounter->report[0]);
EXPECT_TRUE(perfCounter->isCompleted());
HwPerfCounter *perfCounter2 = event->getHwPerfCounterNode()->tagForCpuAccess;
ASSERT_EQ(perfCounter, perfCounter2);
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, getHwPerfCounterAllocationReturnsValidPointer) {
createPerformanceCounters(true, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
ASSERT_NE(nullptr, queue->getPerfCounters());
std::unique_ptr<Event> event(new Event(queue.get(), CL_COMMAND_COPY_BUFFER, 0, 0));
ASSERT_NE(nullptr, event);
GraphicsAllocation *allocation = event->getHwPerfCounterNode()->getBaseGraphicsAllocation();
ASSERT_NE(nullptr, allocation);
void *memoryStorage = allocation->getUnderlyingBuffer();
size_t memoryStorageSize = allocation->getUnderlyingBufferSize();
EXPECT_NE(nullptr, memoryStorage);
EXPECT_GT(memoryStorageSize, 0u);
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, hwPerfCounterMemoryIsPlacedInGraphicsAllocation) {
createPerformanceCounters(true, false);
EXPECT_NE(nullptr, performanceCountersBase);
EXPECT_TRUE(performanceCountersBase->enable(false));
EXPECT_EQ(1u, performanceCountersBase->getReferenceNumber());
ASSERT_NE(nullptr, queue->getPerfCounters());
std::unique_ptr<Event> event(new Event(queue.get(), CL_COMMAND_COPY_BUFFER, 0, 0));
ASSERT_NE(nullptr, event);
HwPerfCounter *perfCounter = event->getHwPerfCounterNode()->tagForCpuAccess;
ASSERT_NE(nullptr, perfCounter);
GraphicsAllocation *allocation = event->getHwPerfCounterNode()->getBaseGraphicsAllocation();
ASSERT_NE(nullptr, allocation);
void *memoryStorage = allocation->getUnderlyingBuffer();
size_t graphicsAllocationSize = allocation->getUnderlyingBufferSize();
EXPECT_GE(perfCounter, memoryStorage);
EXPECT_LE(perfCounter + 1, ptrOffset(memoryStorage, graphicsAllocationSize));
performanceCountersBase->shutdown();
EXPECT_EQ(0u, performanceCountersBase->getReferenceNumber());
}
TEST_F(PerformanceCountersMetricsLibraryTest, hwPerfCounterNodeWhenPerformanceCountersObjectIsNotPresentThenNodeisNull) {
std::unique_ptr<Event> event(new Event(queue.get(), CL_COMMAND_COPY_BUFFER, 0, 0));
ASSERT_NE(nullptr, event);
auto node = event->getHwPerfCounterNode();
ASSERT_EQ(nullptr, node);
}
TEST_F(PerformanceCountersTest, givenRenderCoreFamilyThenMetricsLibraryGenIdentifierAreValid) {
const auto &hwInfo = device->getHardwareInfo();
const auto gen = hwInfo.platform.eRenderCoreFamily;
EXPECT_NE(ClientGen::Unknown, static_cast<ClientGen>(HwHelper::get(gen).getMetricsLibraryGenId()));
}

View File

@ -0,0 +1,51 @@
#
# Copyright (C) 2018-2020 Intel Corporation
#
# SPDX-License-Identifier: MIT
#
set(IGDRCL_SRCS_tests_os_interface_windows
${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt
${CMAKE_CURRENT_SOURCE_DIR}/deferrable_deletion_win_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/device_command_stream_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/device_os_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/driver_info_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/file_logger_win_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/gdi_dll_fixture.h
${CMAKE_CURRENT_SOURCE_DIR}/hw_info_config_win_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/hw_info_config_win_tests.h
${CMAKE_CURRENT_SOURCE_DIR}/mock_environment_variables.h
${CMAKE_CURRENT_SOURCE_DIR}/mock_kmdaf_listener.h
${CMAKE_CURRENT_SOURCE_DIR}/mock_os_time_win.h
${CMAKE_CURRENT_SOURCE_DIR}/mock_performance_counters_win.cpp
${CMAKE_CURRENT_SOURCE_DIR}/mock_performance_counters_win.h
${CMAKE_CURRENT_SOURCE_DIR}/mock_wddm_memory_manager.h
${CMAKE_CURRENT_SOURCE_DIR}/os_context_win_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/os_interface_win_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/os_interface_win_tests.h
${CMAKE_CURRENT_SOURCE_DIR}/os_library_win_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/os_time_win_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/performance_counters_win_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/registry_reader_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/registry_reader_tests.h
${CMAKE_CURRENT_SOURCE_DIR}/self_lib_win.cpp
${CMAKE_CURRENT_SOURCE_DIR}/wddm_address_space_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/wddm_fixture.h
${CMAKE_CURRENT_SOURCE_DIR}/wddm_kmdaf_listener_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/wddm_memory_manager_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/wddm_memory_manager_tests.h
${CMAKE_CURRENT_SOURCE_DIR}${BRANCH_DIR_SUFFIX}/wddm_mapper_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}${BRANCH_DIR_SUFFIX}/wddm_memory_manager_allocate_in_device_pool_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/wddm_memory_manager_allocate_in_device_pool_tests.inl
${CMAKE_CURRENT_SOURCE_DIR}/wddm_residency_controller_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/wddm_residency_handler_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/mock_registry_reader.cpp
)
if(WIN32)
file(GLOB IGDRCL_SRC_tests_wddm_interface "${CMAKE_CURRENT_SOURCE_DIR}/wddm2[0-9]_tests\.cpp")
target_sources(igdrcl_tests PRIVATE
${IGDRCL_SRCS_tests_os_interface_windows}
${IGDRCL_SRC_tests_wddm_interface}
)
endif()
add_subdirectories()

View File

@ -0,0 +1,23 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/execution_environment/execution_environment.h"
#include "core/os_interface/os_interface.h"
#include "core/os_interface/windows/os_interface.h"
#include "core/os_interface/windows/wddm_memory_manager.h"
#include "core/unit_tests/helpers/ult_hw_config.h"
#include "opencl/source/memory_manager/os_agnostic_memory_manager.h"
namespace NEO {
std::unique_ptr<MemoryManager> MemoryManager::createMemoryManager(ExecutionEnvironment &executionEnvironment) {
if (ultHwConfig.forceOsAgnosticMemoryManager) {
return std::make_unique<OsAgnosticMemoryManager>(executionEnvironment);
}
return std::make_unique<WddmMemoryManager>(executionEnvironment);
}
} // namespace NEO

View File

@ -0,0 +1,69 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/execution_environment/root_device_environment.h"
#include "core/os_interface/windows/deferrable_deletion_win.h"
#include "gtest/gtest.h"
#include "mocks/mock_execution_environment.h"
#include "mocks/mock_wddm.h"
#include <type_traits>
using namespace NEO;
TEST(DeferrableDeletionImpl, NonCopyable) {
EXPECT_FALSE(std::is_move_constructible<DeferrableDeletionImpl>::value);
EXPECT_FALSE(std::is_copy_constructible<DeferrableDeletionImpl>::value);
}
TEST(DeferrableDeletionImpl, NonAssignable) {
EXPECT_FALSE(std::is_move_assignable<DeferrableDeletionImpl>::value);
EXPECT_FALSE(std::is_copy_assignable<DeferrableDeletionImpl>::value);
}
class MockDeferrableDeletion : public DeferrableDeletionImpl {
public:
using DeferrableDeletionImpl::allocationCount;
using DeferrableDeletionImpl::DeferrableDeletionImpl;
using DeferrableDeletionImpl::handles;
using DeferrableDeletionImpl::resourceHandle;
using DeferrableDeletionImpl::wddm;
};
class DeferrableDeletionTest : public ::testing::Test {
public:
std::unique_ptr<MockExecutionEnvironment> executionEnvironment;
std::unique_ptr<WddmMock> wddm;
const D3DKMT_HANDLE handle = 0;
uint32_t allocationCount = 1;
D3DKMT_HANDLE resourceHandle = 0;
void SetUp() override {
executionEnvironment = std::make_unique<MockExecutionEnvironment>();
executionEnvironment->prepareRootDeviceEnvironments(1);
wddm = std::make_unique<WddmMock>(*executionEnvironment->rootDeviceEnvironments[0]);
}
};
TEST_F(DeferrableDeletionTest, givenDeferrableDeletionWhenIsCreatedThenObjectMembersAreSetProperly) {
MockDeferrableDeletion deletion(wddm.get(), &handle, allocationCount, resourceHandle);
EXPECT_EQ(wddm.get(), deletion.wddm);
EXPECT_NE(nullptr, deletion.handles);
EXPECT_EQ(handle, *deletion.handles);
EXPECT_NE(&handle, deletion.handles);
EXPECT_EQ(allocationCount, deletion.allocationCount);
EXPECT_EQ(resourceHandle, deletion.resourceHandle);
}
TEST_F(DeferrableDeletionTest, givenDeferrableDeletionWhenApplyIsCalledThenDeletionIsApplied) {
wddm->callBaseDestroyAllocations = false;
std::unique_ptr<DeferrableDeletion> deletion(DeferrableDeletion::create((Wddm *)wddm.get(), &handle, allocationCount, resourceHandle));
EXPECT_EQ(0, wddm->destroyAllocationResult.called);
deletion->apply();
EXPECT_EQ(1, wddm->destroyAllocationResult.called);
}

View File

@ -0,0 +1,989 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/command_stream/command_stream_receiver.h"
#include "core/command_stream/linear_stream.h"
#include "core/command_stream/preemption.h"
#include "core/helpers/flush_stamp.h"
#include "core/helpers/hw_cmds.h"
#include "core/helpers/windows/gmm_callbacks.h"
#include "core/memory_manager/internal_allocation_storage.h"
#include "core/memory_manager/memory_manager.h"
#include "core/os_interface/windows/os_context_win.h"
#include "core/os_interface/windows/os_interface.h"
#include "core/os_interface/windows/wddm_memory_manager.h"
#include "core/os_interface/windows/wddm_memory_operations_handler.h"
#include "core/os_interface/windows/wddm_residency_controller.h"
#include "core/unit_tests/helpers/debug_manager_state_restore.h"
#include "core/unit_tests/os_interface/windows/mock_gdi_interface.h"
#include "opencl/source/command_stream/aub_command_stream_receiver.h"
#include "opencl/source/command_stream/command_stream_receiver_with_aub_dump.h"
#include "opencl/source/command_stream/device_command_stream.h"
#include "opencl/source/helpers/built_ins_helper.h"
#include "opencl/source/mem_obj/buffer.h"
#include "opencl/source/os_interface/windows/wddm_device_command_stream.h"
#include "opencl/source/platform/platform.h"
#include "test.h"
#include "fixtures/device_fixture.h"
#include "fixtures/memory_management_fixture.h"
#include "fixtures/mock_aub_center_fixture.h"
#include "helpers/dispatch_flags_helper.h"
#include "helpers/execution_environment_helper.h"
#include "mocks/mock_buffer.h"
#include "mocks/mock_builtins.h"
#include "mocks/mock_device.h"
#include "mocks/mock_gmm_page_table_mngr.h"
#include "mocks/mock_graphics_allocation.h"
#include "mocks/mock_program.h"
#include "mocks/mock_submissions_aggregator.h"
#include "mocks/mock_wddm_interface23.h"
#include "os_interface/windows/mock_wddm_memory_manager.h"
#include "os_interface/windows/wddm_fixture.h"
using namespace NEO;
using namespace ::testing;
class WddmCommandStreamFixture {
public:
std::unique_ptr<MockDevice> device;
std::unique_ptr<OsContext> osContext;
DeviceCommandStreamReceiver<DEFAULT_TEST_FAMILY_NAME> *csr;
MockWddmMemoryManager *memoryManager = nullptr;
WddmMock *wddm = nullptr;
DebugManagerStateRestore stateRestore;
virtual void SetUp() {
HardwareInfo *hwInfo = nullptr;
DebugManager.flags.CsrDispatchMode.set(static_cast<uint32_t>(DispatchMode::ImmediateDispatch));
auto executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 1);
memoryManager = new MockWddmMemoryManager(*executionEnvironment);
executionEnvironment->memoryManager.reset(memoryManager);
wddm = static_cast<WddmMock *>(executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->getWddm());
osContext.reset(OsContext::create(executionEnvironment->rootDeviceEnvironments[0]->osInterface.get(),
0, 0, aub_stream::ENGINE_RCS, PreemptionMode::ThreadGroup, false));
csr = new WddmCommandStreamReceiver<DEFAULT_TEST_FAMILY_NAME>(*executionEnvironment, 0);
device.reset(MockDevice::create<MockDevice>(executionEnvironment, 0u));
device->resetCommandStreamReceiver(csr);
ASSERT_NE(nullptr, device);
}
virtual void TearDown() {
}
};
template <typename GfxFamily>
struct MockWddmCsr : public WddmCommandStreamReceiver<GfxFamily> {
using CommandStreamReceiver::commandStream;
using CommandStreamReceiver::dispatchMode;
using CommandStreamReceiver::getCS;
using CommandStreamReceiverHw<GfxFamily>::directSubmission;
using WddmCommandStreamReceiver<GfxFamily>::commandBufferHeader;
using WddmCommandStreamReceiver<GfxFamily>::WddmCommandStreamReceiver;
void overrideDispatchPolicy(DispatchMode overrideValue) {
this->dispatchMode = overrideValue;
}
SubmissionAggregator *peekSubmissionAggregator() {
return this->submissionAggregator.get();
}
void overrideSubmissionAggregator(SubmissionAggregator *newSubmissionsAggregator) {
this->submissionAggregator.reset(newSubmissionsAggregator);
}
void overrideRecorededCommandBuffer(Device &device) {
recordedCommandBuffer = std::unique_ptr<CommandBuffer>(new CommandBuffer(device));
}
int flushCalledCount = 0;
std::unique_ptr<CommandBuffer> recordedCommandBuffer = nullptr;
};
class WddmCommandStreamWithMockGdiFixture {
public:
MockWddmCsr<DEFAULT_TEST_FAMILY_NAME> *csr = nullptr;
MemoryManager *memoryManager = nullptr;
std::unique_ptr<MockDevice> device = nullptr;
WddmMock *wddm = nullptr;
MockGdi *gdi = nullptr;
DebugManagerStateRestore stateRestore;
GraphicsAllocation *preemptionAllocation = nullptr;
virtual void SetUp() {
HardwareInfo *hwInfo = nullptr;
ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 1);
wddm = static_cast<WddmMock *>(executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->getWddm());
gdi = new MockGdi();
wddm->resetGdi(gdi);
ASSERT_NE(wddm, nullptr);
DebugManager.flags.CsrDispatchMode.set(static_cast<uint32_t>(DispatchMode::ImmediateDispatch));
this->csr = new MockWddmCsr<DEFAULT_TEST_FAMILY_NAME>(*executionEnvironment, 0);
memoryManager = new WddmMemoryManager(*executionEnvironment);
ASSERT_NE(nullptr, memoryManager);
executionEnvironment->memoryManager.reset(memoryManager);
device = std::unique_ptr<MockDevice>(Device::create<MockDevice>(executionEnvironment, 0u));
device->resetCommandStreamReceiver(this->csr);
ASSERT_NE(nullptr, device);
this->csr->overrideRecorededCommandBuffer(*device);
}
virtual void TearDown() {
wddm = nullptr;
}
};
using WddmCommandStreamTest = ::Test<WddmCommandStreamFixture>;
using WddmCommandStreamMockGdiTest = ::Test<WddmCommandStreamWithMockGdiFixture>;
using WddmDefaultTest = ::Test<DeviceFixture>;
using DeviceCommandStreamTest = ::Test<MockAubCenterFixture>;
TEST_F(DeviceCommandStreamTest, CreateWddmCSR) {
ExecutionEnvironment *executionEnvironment = platform()->peekExecutionEnvironment();
auto wddm = Wddm::createWddm(nullptr, *executionEnvironment->rootDeviceEnvironments[0].get());
executionEnvironment->rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setWddm(static_cast<WddmMock *>(wddm));
executionEnvironment->initializeMemoryManager();
std::unique_ptr<WddmCommandStreamReceiver<DEFAULT_TEST_FAMILY_NAME>> csr(static_cast<WddmCommandStreamReceiver<DEFAULT_TEST_FAMILY_NAME> *>(WddmCommandStreamReceiver<DEFAULT_TEST_FAMILY_NAME>::create(false, *executionEnvironment, 0)));
EXPECT_NE(nullptr, csr);
auto wddmFromCsr = csr->peekWddm();
EXPECT_NE(nullptr, wddmFromCsr);
}
TEST_F(DeviceCommandStreamTest, CreateWddmCSRWithAubDump) {
ExecutionEnvironment *executionEnvironment = platform()->peekExecutionEnvironment();
auto wddm = Wddm::createWddm(nullptr, *executionEnvironment->rootDeviceEnvironments[0].get());
executionEnvironment->rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setWddm(static_cast<WddmMock *>(wddm));
executionEnvironment->initializeMemoryManager();
std::unique_ptr<WddmCommandStreamReceiver<DEFAULT_TEST_FAMILY_NAME>> csr(static_cast<WddmCommandStreamReceiver<DEFAULT_TEST_FAMILY_NAME> *>(WddmCommandStreamReceiver<DEFAULT_TEST_FAMILY_NAME>::create(true, *executionEnvironment, 0)));
EXPECT_NE(nullptr, csr);
auto wddmFromCsr = csr->peekWddm();
EXPECT_NE(nullptr, wddmFromCsr);
auto aubCSR = static_cast<CommandStreamReceiverWithAUBDump<WddmCommandStreamReceiver<DEFAULT_TEST_FAMILY_NAME>> *>(csr.get())->aubCSR.get();
EXPECT_NE(nullptr, aubCSR);
}
TEST_F(WddmCommandStreamTest, givenFlushStampWhenWaitCalledThenWaitForSpecifiedMonitoredFence) {
uint64_t stampToWait = 123;
wddm->waitFromCpuResult.called = 0u;
csr->waitForFlushStamp(stampToWait);
EXPECT_EQ(1u, wddm->waitFromCpuResult.called);
EXPECT_TRUE(wddm->waitFromCpuResult.success);
EXPECT_EQ(stampToWait, wddm->waitFromCpuResult.uint64ParamPassed);
}
TEST_F(WddmCommandStreamTest, Flush) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
csr->flush(batchBuffer, csr->getResidencyAllocations());
EXPECT_EQ(1u, wddm->submitResult.called);
EXPECT_TRUE(wddm->submitResult.success);
EXPECT_EQ(csr->obtainCurrentFlushStamp(), static_cast<OsContextWin &>(csr->getOsContext()).getResidencyController().getMonitoredFence().lastSubmittedFence);
memoryManager->freeGraphicsMemory(commandBuffer);
}
TEST_F(WddmCommandStreamTest, givenGraphicsAllocationWithDifferentGpuAddressThenCpuAddressWhenSubmitIsCalledThenGpuAddressIsUsed) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
auto cpuAddress = commandBuffer->getUnderlyingBuffer();
uint64_t mockGpuAddres = 1337;
commandBuffer->setCpuPtrAndGpuAddress(cpuAddress, mockGpuAddres);
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
csr->flush(batchBuffer, csr->getResidencyAllocations());
EXPECT_EQ(mockGpuAddres, wddm->submitResult.commandBufferSubmitted);
memoryManager->freeGraphicsMemory(commandBuffer);
}
TEST_F(WddmCommandStreamTest, FlushWithOffset) {
auto offset = 128u;
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), offset, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
csr->flush(batchBuffer, csr->getResidencyAllocations());
EXPECT_EQ(1u, wddm->submitResult.called);
EXPECT_TRUE(wddm->submitResult.success);
EXPECT_EQ(wddm->submitResult.commandBufferSubmitted, commandBuffer->getGpuAddress() + offset);
memoryManager->freeGraphicsMemory(commandBuffer);
}
TEST_F(WddmCommandStreamTest, givenWdmmWhenSubmitIsCalledThenCoherencyRequiredFlagIsSetToFalse) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
csr->flush(batchBuffer, csr->getResidencyAllocations());
auto commandHeader = wddm->submitResult.commandHeaderSubmitted;
COMMAND_BUFFER_HEADER *pHeader = reinterpret_cast<COMMAND_BUFFER_HEADER *>(commandHeader);
EXPECT_FALSE(pHeader->RequiresCoherency);
memoryManager->freeGraphicsMemory(commandBuffer);
}
TEST(WddmPreemptionHeaderTests, givenWddmCommandStreamReceiverWhenPreemptionIsOffWhenWorkloadIsSubmittedThenHeaderDoesntHavePreemptionFieldSet) {
HardwareInfo *hwInfo = nullptr;
ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 1);
hwInfo->capabilityTable.defaultPreemptionMode = PreemptionMode::Disabled;
executionEnvironment->setHwInfo(hwInfo);
auto wddm = static_cast<WddmMock *>(executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->getWddm());
auto csr = std::make_unique<MockWddmCsr<DEFAULT_TEST_FAMILY_NAME>>(*executionEnvironment, 0);
executionEnvironment->memoryManager.reset(new MemoryManagerCreate<WddmMemoryManager>(false, false, *executionEnvironment));
csr->overrideDispatchPolicy(DispatchMode::ImmediateDispatch);
OsContextWin osContext(*wddm, 0u, 1, HwHelper::get(platformDevices[0]->platform.eRenderCoreFamily).getGpgpuEngineInstances()[0],
PreemptionHelper::getDefaultPreemptionMode(*hwInfo), false);
csr->setupContext(osContext);
auto commandBuffer = executionEnvironment->memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
csr->flush(batchBuffer, csr->getResidencyAllocations());
auto commandHeader = wddm->submitResult.commandHeaderSubmitted;
COMMAND_BUFFER_HEADER *pHeader = reinterpret_cast<COMMAND_BUFFER_HEADER *>(commandHeader);
EXPECT_FALSE(pHeader->NeedsMidBatchPreEmptionSupport);
executionEnvironment->memoryManager->freeGraphicsMemory(commandBuffer);
}
TEST(WddmPreemptionHeaderTests, givenWddmCommandStreamReceiverWhenPreemptionIsOnWhenWorkloadIsSubmittedThenHeaderDoesHavePreemptionFieldSet) {
HardwareInfo *hwInfo = nullptr;
ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 1);
hwInfo->capabilityTable.defaultPreemptionMode = PreemptionMode::MidThread;
executionEnvironment->setHwInfo(hwInfo);
auto wddm = static_cast<WddmMock *>(executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->getWddm());
auto csr = std::make_unique<MockWddmCsr<DEFAULT_TEST_FAMILY_NAME>>(*executionEnvironment, 0);
executionEnvironment->memoryManager.reset(new MemoryManagerCreate<WddmMemoryManager>(false, false, *executionEnvironment));
csr->overrideDispatchPolicy(DispatchMode::ImmediateDispatch);
OsContextWin osContext(*wddm, 0u, 1, HwHelper::get(platformDevices[0]->platform.eRenderCoreFamily).getGpgpuEngineInstances()[0],
PreemptionHelper::getDefaultPreemptionMode(*hwInfo), false);
csr->setupContext(osContext);
auto commandBuffer = executionEnvironment->memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
csr->flush(batchBuffer, csr->getResidencyAllocations());
auto commandHeader = wddm->submitResult.commandHeaderSubmitted;
COMMAND_BUFFER_HEADER *pHeader = reinterpret_cast<COMMAND_BUFFER_HEADER *>(commandHeader);
EXPECT_TRUE(pHeader->NeedsMidBatchPreEmptionSupport);
executionEnvironment->memoryManager->freeGraphicsMemory(commandBuffer);
}
TEST(WddmPreemptionHeaderTests, givenDeviceSupportingPreemptionWhenCommandStreamReceiverIsCreatedThenHeaderContainsPreemptionFieldSet) {
HardwareInfo *hwInfo = nullptr;
ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 1);
hwInfo->capabilityTable.defaultPreemptionMode = PreemptionMode::MidThread;
executionEnvironment->setHwInfo(hwInfo);
auto commandStreamReceiver = std::make_unique<MockWddmCsr<DEFAULT_TEST_FAMILY_NAME>>(*executionEnvironment, 0);
auto commandHeader = commandStreamReceiver->commandBufferHeader;
auto header = reinterpret_cast<COMMAND_BUFFER_HEADER *>(commandHeader);
EXPECT_TRUE(header->NeedsMidBatchPreEmptionSupport);
}
TEST(WddmPreemptionHeaderTests, givenDevicenotSupportingPreemptionWhenCommandStreamReceiverIsCreatedThenHeaderPreemptionFieldIsNotSet) {
HardwareInfo *hwInfo = nullptr;
ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 1);
hwInfo->capabilityTable.defaultPreemptionMode = PreemptionMode::Disabled;
executionEnvironment->setHwInfo(hwInfo);
auto commandStreamReceiver = std::make_unique<MockWddmCsr<DEFAULT_TEST_FAMILY_NAME>>(*executionEnvironment, 0);
auto commandHeader = commandStreamReceiver->commandBufferHeader;
auto header = reinterpret_cast<COMMAND_BUFFER_HEADER *>(commandHeader);
EXPECT_FALSE(header->NeedsMidBatchPreEmptionSupport);
}
TEST_F(WddmCommandStreamTest, givenWdmmWhenSubmitIsCalledAndThrottleIsToLowThenSetHeaderFieldsProperly) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::LOW, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
csr->flush(batchBuffer, csr->getResidencyAllocations());
auto commandHeader = wddm->submitResult.commandHeaderSubmitted;
COMMAND_BUFFER_HEADER *pHeader = reinterpret_cast<COMMAND_BUFFER_HEADER *>(commandHeader);
EXPECT_EQ(0, pHeader->UmdRequestedSliceState);
EXPECT_EQ(0, pHeader->UmdRequestedSubsliceCount);
EXPECT_EQ(wddm->getGtSysInfo()->EUCount / wddm->getGtSysInfo()->SubSliceCount, pHeader->UmdRequestedEUCount);
memoryManager->freeGraphicsMemory(commandBuffer);
}
TEST_F(WddmCommandStreamTest, givenWdmmWhenSubmitIsCalledAndThrottleIsToMediumThenSetHeaderFieldsProperly) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
csr->flush(batchBuffer, csr->getResidencyAllocations());
auto commandHeader = wddm->submitResult.commandHeaderSubmitted;
COMMAND_BUFFER_HEADER *pHeader = reinterpret_cast<COMMAND_BUFFER_HEADER *>(commandHeader);
EXPECT_EQ(0, pHeader->UmdRequestedSliceState);
EXPECT_EQ(0, pHeader->UmdRequestedSubsliceCount);
EXPECT_EQ(wddm->getGtSysInfo()->EUCount / wddm->getGtSysInfo()->SubSliceCount, pHeader->UmdRequestedEUCount);
memoryManager->freeGraphicsMemory(commandBuffer);
}
TEST_F(WddmCommandStreamTest, givenWdmmWhenSubmitIsCalledAndThrottleIsToHighThenSetHeaderFieldsProperly) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::HIGH, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
csr->flush(batchBuffer, csr->getResidencyAllocations());
auto commandHeader = wddm->submitResult.commandHeaderSubmitted;
COMMAND_BUFFER_HEADER *pHeader = reinterpret_cast<COMMAND_BUFFER_HEADER *>(commandHeader);
const uint32_t maxRequestedSubsliceCount = 7;
EXPECT_EQ(0, pHeader->UmdRequestedSliceState);
EXPECT_EQ((wddm->getGtSysInfo()->SubSliceCount <= maxRequestedSubsliceCount) ? wddm->getGtSysInfo()->SubSliceCount : 0, pHeader->UmdRequestedSubsliceCount);
EXPECT_EQ(wddm->getGtSysInfo()->EUCount / wddm->getGtSysInfo()->SubSliceCount, pHeader->UmdRequestedEUCount);
memoryManager->freeGraphicsMemory(commandBuffer);
}
TEST_F(WddmCommandStreamTest, givenWddmWithKmDafDisabledWhenFlushIsCalledWithAllocationsForResidencyThenNoneAllocationShouldBeKmDafLocked) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
auto linearStreamAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize, GraphicsAllocation::AllocationType::LINEAR_STREAM});
ASSERT_NE(nullptr, linearStreamAllocation);
ResidencyContainer allocationsForResidency = {linearStreamAllocation};
EXPECT_FALSE(wddm->isKmDafEnabled());
csr->flush(batchBuffer, allocationsForResidency);
EXPECT_EQ(0u, wddm->kmDafLockResult.called);
EXPECT_EQ(0u, wddm->kmDafLockResult.lockedAllocations.size());
memoryManager->freeGraphicsMemory(commandBuffer);
memoryManager->freeGraphicsMemory(linearStreamAllocation);
}
TEST_F(WddmCommandStreamTest, givenWddmWithKmDafEnabledWhenFlushIsCalledWithoutAllocationsForResidencyThenNoneAllocationShouldBeKmDafLocked) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
wddm->setKmDafEnabled(true);
csr->flush(batchBuffer, csr->getResidencyAllocations());
EXPECT_EQ(0u, wddm->kmDafLockResult.called);
EXPECT_EQ(0u, wddm->kmDafLockResult.lockedAllocations.size());
memoryManager->freeGraphicsMemory(commandBuffer);
}
TEST_F(WddmCommandStreamTest, givenWddmWithKmDafEnabledWhenFlushIsCalledWithResidencyAllocationsInMemoryManagerThenLinearStreamAllocationsShouldBeKmDafLocked) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
auto linearStreamAllocation = static_cast<WddmAllocation *>(memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize, GraphicsAllocation::AllocationType::LINEAR_STREAM}));
ASSERT_NE(nullptr, linearStreamAllocation);
csr->makeResident(*linearStreamAllocation);
EXPECT_EQ(1u, csr->getResidencyAllocations().size());
EXPECT_EQ(linearStreamAllocation, csr->getResidencyAllocations()[0]);
wddm->setKmDafEnabled(true);
csr->flush(batchBuffer, csr->getResidencyAllocations());
EXPECT_EQ(1u, wddm->kmDafLockResult.called);
EXPECT_EQ(1u, wddm->kmDafLockResult.lockedAllocations.size());
EXPECT_EQ(linearStreamAllocation->getDefaultHandle(), wddm->kmDafLockResult.lockedAllocations[0]);
memoryManager->freeGraphicsMemory(commandBuffer);
memoryManager->freeGraphicsMemory(linearStreamAllocation);
}
TEST_F(WddmCommandStreamTest, givenWddmWithKmDafEnabledWhenFlushIsCalledWithAllocationsForResidencyThenLinearStreamAllocationsShouldBeKmDafLocked) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
auto linearStreamAllocation = static_cast<WddmAllocation *>(memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize, GraphicsAllocation::AllocationType::LINEAR_STREAM}));
ASSERT_NE(nullptr, linearStreamAllocation);
ResidencyContainer allocationsForResidency = {linearStreamAllocation};
wddm->setKmDafEnabled(true);
csr->flush(batchBuffer, allocationsForResidency);
EXPECT_EQ(1u, wddm->kmDafLockResult.called);
EXPECT_EQ(1u, wddm->kmDafLockResult.lockedAllocations.size());
EXPECT_EQ(linearStreamAllocation->getDefaultHandle(), wddm->kmDafLockResult.lockedAllocations[0]);
memoryManager->freeGraphicsMemory(commandBuffer);
memoryManager->freeGraphicsMemory(linearStreamAllocation);
}
TEST_F(WddmCommandStreamTest, givenWddmWithKmDafEnabledWhenFlushIsCalledWithAllocationsForResidencyThenFillPatternAllocationsShouldBeKmDafLocked) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
auto fillPatternAllocation = static_cast<WddmAllocation *>(memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize, GraphicsAllocation::AllocationType::FILL_PATTERN}));
ASSERT_NE(nullptr, fillPatternAllocation);
ResidencyContainer allocationsForResidency = {fillPatternAllocation};
wddm->setKmDafEnabled(true);
csr->flush(batchBuffer, allocationsForResidency);
EXPECT_EQ(1u, wddm->kmDafLockResult.called);
EXPECT_EQ(1u, wddm->kmDafLockResult.lockedAllocations.size());
EXPECT_EQ(fillPatternAllocation->getDefaultHandle(), wddm->kmDafLockResult.lockedAllocations[0]);
memoryManager->freeGraphicsMemory(commandBuffer);
memoryManager->freeGraphicsMemory(fillPatternAllocation);
}
TEST_F(WddmCommandStreamTest, givenWddmWithKmDafEnabledWhenFlushIsCalledWithAllocationsForResidencyThenCommandBufferAllocationsShouldBeKmDafLocked) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
auto commandBufferAllocation = static_cast<WddmAllocation *>(memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize, GraphicsAllocation::AllocationType::COMMAND_BUFFER}));
ASSERT_NE(nullptr, commandBufferAllocation);
ResidencyContainer allocationsForResidency = {commandBufferAllocation};
wddm->setKmDafEnabled(true);
csr->flush(batchBuffer, allocationsForResidency);
EXPECT_EQ(1u, wddm->kmDafLockResult.called);
EXPECT_EQ(1u, wddm->kmDafLockResult.lockedAllocations.size());
EXPECT_EQ(commandBufferAllocation->getDefaultHandle(), wddm->kmDafLockResult.lockedAllocations[0]);
memoryManager->freeGraphicsMemory(commandBuffer);
memoryManager->freeGraphicsMemory(commandBufferAllocation);
}
TEST_F(WddmCommandStreamTest, givenWddmWithKmDafEnabledWhenFlushIsCalledWithAllocationsForResidencyThenNonLinearStreamAllocationShouldNotBeKmDafLocked) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
auto nonLinearStreamAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, nonLinearStreamAllocation);
ResidencyContainer allocationsForResidency = {nonLinearStreamAllocation};
wddm->setKmDafEnabled(true);
csr->flush(batchBuffer, allocationsForResidency);
EXPECT_EQ(0u, wddm->kmDafLockResult.called);
EXPECT_EQ(0u, wddm->kmDafLockResult.lockedAllocations.size());
memoryManager->freeGraphicsMemory(commandBuffer);
memoryManager->freeGraphicsMemory(nonLinearStreamAllocation);
}
TEST_F(WddmCommandStreamTest, makeResident) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
csr->makeResident(*commandBuffer);
EXPECT_EQ(0u, wddm->makeResidentResult.called);
EXPECT_EQ(1u, csr->getResidencyAllocations().size());
EXPECT_EQ(commandBuffer, csr->getResidencyAllocations()[0]);
memoryManager->freeGraphicsMemory(commandBuffer);
}
TEST_F(WddmCommandStreamTest, makeNonResidentPutsAllocationInEvictionAllocations) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
csr->makeResident(*cs.getGraphicsAllocation());
csr->makeNonResident(*commandBuffer);
EXPECT_EQ(1u, csr->getEvictionAllocations().size());
memoryManager->freeGraphicsMemory(commandBuffer);
}
TEST_F(WddmCommandStreamTest, processEvictionPlacesAllAllocationsOnTrimCandidateList) {
GraphicsAllocation *allocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
GraphicsAllocation *allocation2 = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, allocation);
ASSERT_NE(nullptr, allocation2);
csr->getEvictionAllocations().push_back(allocation);
csr->getEvictionAllocations().push_back(allocation2);
EXPECT_EQ(2u, csr->getEvictionAllocations().size());
csr->processEviction();
EXPECT_EQ(2u, static_cast<OsContextWin &>(csr->getOsContext()).getResidencyController().peekTrimCandidateList().size());
memoryManager->freeGraphicsMemory(allocation);
memoryManager->freeGraphicsMemory(allocation2);
}
TEST_F(WddmCommandStreamTest, processEvictionClearsEvictionAllocations) {
GraphicsAllocation *allocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, allocation);
csr->getEvictionAllocations().push_back(allocation);
EXPECT_EQ(1u, csr->getEvictionAllocations().size());
csr->processEviction();
EXPECT_EQ(0u, csr->getEvictionAllocations().size());
memoryManager->freeGraphicsMemory(allocation);
}
TEST_F(WddmCommandStreamTest, makeResidentNonResidentMemObj) {
GraphicsAllocation *gfxAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
Buffer *buffer = new AlignedBuffer(gfxAllocation);
csr->makeResident(*buffer->getGraphicsAllocation());
EXPECT_EQ(0u, wddm->makeResidentResult.called);
EXPECT_EQ(1u, csr->getResidencyAllocations().size());
EXPECT_EQ(gfxAllocation, csr->getResidencyAllocations()[0]);
csr->makeNonResident(*buffer->getGraphicsAllocation());
EXPECT_EQ(gfxAllocation, csr->getEvictionAllocations()[0]);
delete buffer;
memoryManager->freeGraphicsMemory(gfxAllocation);
}
TEST_F(WddmCommandStreamTest, givenGraphicsAllocationWhenMakeResidentThenAllocationIsInResidencyContainer) {
void *hostPtr = reinterpret_cast<void *>(wddm->virtualAllocAddress + 0x1234);
auto size = 1234u;
auto gfxAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{false, size}, hostPtr);
ASSERT_NE(nullptr, gfxAllocation);
csr->makeResidentHostPtrAllocation(gfxAllocation);
EXPECT_EQ(1u, csr->getResidencyAllocations().size());
EXPECT_EQ(hostPtr, gfxAllocation->getUnderlyingBuffer());
memoryManager->freeGraphicsMemory(gfxAllocation);
}
TEST_F(WddmCommandStreamTest, givenHostPtrAllocationWhenMapFailsThenFragmentsAreClearedAndNullptrIsReturned) {
this->wddm->callBaseMapGpuVa = false;
this->wddm->mapGpuVaStatus = false;
void *hostPtr = reinterpret_cast<void *>(wddm->virtualAllocAddress + 0x1234);
auto size = 1234u;
wddm->mapGpuVirtualAddressResult.called = 0u;
wddm->destroyAllocationResult.called = 0u;
auto gfxAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{false, size}, hostPtr);
EXPECT_EQ(1u, wddm->mapGpuVirtualAddressResult.called);
EXPECT_EQ(1u, wddm->destroyAllocationResult.called);
EXPECT_EQ(nullptr, gfxAllocation);
}
TEST_F(WddmCommandStreamTest, givenAddressWithHighestBitSetWhenItIsMappedThenProperAddressIsPassed) {
uintptr_t address = 0xffff0000;
void *faultyAddress = reinterpret_cast<void *>(address);
wddm->mapGpuVirtualAddressResult.called = 0u;
auto gfxAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{false, MemoryConstants::pageSize}, faultyAddress);
EXPECT_EQ(1u, wddm->mapGpuVirtualAddressResult.called);
ASSERT_NE(nullptr, gfxAllocation);
auto expectedAddress = castToUint64(faultyAddress);
EXPECT_EQ(gfxAllocation->getGpuAddress(), expectedAddress);
ASSERT_EQ(gfxAllocation->fragmentsStorage.fragmentCount, 1u);
EXPECT_EQ(expectedAddress, gfxAllocation->fragmentsStorage.fragmentStorageData[0].osHandleStorage->gpuPtr);
memoryManager->freeGraphicsMemory(gfxAllocation);
}
TEST_F(WddmCommandStreamTest, givenHostPtrWhenPtrBelowRestrictionThenCreateAllocationAndMakeResident) {
void *hostPtr = reinterpret_cast<void *>(memoryManager->getAlignedMallocRestrictions()->minAddress - 0x1000);
auto size = 0x2000u;
auto gfxAllocation = static_cast<WddmAllocation *>(memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{false, size}, hostPtr));
void *expectedReserve = reinterpret_cast<void *>(wddm->virtualAllocAddress);
ASSERT_NE(nullptr, gfxAllocation);
csr->makeResidentHostPtrAllocation(gfxAllocation);
EXPECT_EQ(1u, csr->getResidencyAllocations().size());
EXPECT_EQ(hostPtr, gfxAllocation->getUnderlyingBuffer());
EXPECT_EQ(expectedReserve, gfxAllocation->getReservedAddressPtr());
memoryManager->freeGraphicsMemory(gfxAllocation);
}
TEST_F(WddmCommandStreamTest, givenTwoTemporaryAllocationsWhenCleanTemporaryAllocationListThenDestoryOnlyCompletedAllocations) {
void *host_ptr = (void *)0x1212341;
void *host_ptr2 = (void *)0x2212341;
auto size = 17262u;
GraphicsAllocation *graphicsAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{false, size}, host_ptr);
GraphicsAllocation *graphicsAllocation2 = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{false, size}, host_ptr2);
csr->getInternalAllocationStorage()->storeAllocation(std::unique_ptr<GraphicsAllocation>(graphicsAllocation), TEMPORARY_ALLOCATION);
csr->getInternalAllocationStorage()->storeAllocation(std::unique_ptr<GraphicsAllocation>(graphicsAllocation2), TEMPORARY_ALLOCATION);
graphicsAllocation->updateTaskCount(1, csr->getOsContext().getContextId());
graphicsAllocation2->updateTaskCount(100, csr->getOsContext().getContextId());
csr->waitForTaskCountAndCleanAllocationList(1, TEMPORARY_ALLOCATION);
// graphicsAllocation2 still lives
EXPECT_EQ(host_ptr2, graphicsAllocation2->getUnderlyingBuffer());
auto hostPtrManager = memoryManager->getHostPtrManager();
auto alignedPtr = alignDown(host_ptr, MemoryConstants::pageSize);
auto alignedPtr2 = alignDown(host_ptr2, MemoryConstants::pageSize);
auto fragment = hostPtrManager->getFragment(alignedPtr2);
ASSERT_NE(nullptr, fragment);
EXPECT_EQ(alignedPtr2, fragment->fragmentCpuPointer);
auto fragment2 = hostPtrManager->getFragment(alignedPtr);
EXPECT_EQ(nullptr, fragment2);
// destroy remaining allocation
csr->waitForTaskCountAndCleanAllocationList(100, TEMPORARY_ALLOCATION);
}
TEST_F(WddmCommandStreamMockGdiTest, FlushCallsWddmMakeResidentForResidencyAllocations) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
csr->makeResident(*commandBuffer);
EXPECT_EQ(1u, csr->getResidencyAllocations().size());
gdi->getMakeResidentArg().NumAllocations = 0;
BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr};
csr->flush(batchBuffer, csr->getResidencyAllocations());
EXPECT_NE(0u, gdi->getMakeResidentArg().NumAllocations);
memoryManager->freeGraphicsMemory(commandBuffer);
}
TEST_F(WddmCommandStreamMockGdiTest, makeResidentClearsResidencyAllocations) {
GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
ASSERT_NE(nullptr, commandBuffer);
LinearStream cs(commandBuffer);
csr->makeResident(*commandBuffer);
EXPECT_EQ(1u, csr->getResidencyAllocations().size());
EXPECT_EQ(0u, csr->getEvictionAllocations().size());
EXPECT_EQ(trimListUnusedPosition, static_cast<WddmAllocation *>(commandBuffer)->getTrimCandidateListPosition(csr->getOsContext().getContextId()));
csr->processResidency(csr->getResidencyAllocations(), 0u);
csr->makeSurfacePackNonResident(csr->getResidencyAllocations());
EXPECT_EQ(0u, csr->getResidencyAllocations().size());
EXPECT_EQ(0u, csr->getEvictionAllocations().size());
EXPECT_EQ(0u, static_cast<WddmAllocation *>(commandBuffer)->getTrimCandidateListPosition(csr->getOsContext().getContextId()));
memoryManager->freeGraphicsMemory(commandBuffer);
}
HWTEST_F(WddmCommandStreamMockGdiTest, givenRecordedCommandBufferWhenItIsSubmittedThenFlushTaskIsProperlyCalled) {
//preemption allocation + sip allocation
size_t csrSurfaceCount = 0;
GraphicsAllocation *tmpAllocation = nullptr;
if (device->getPreemptionMode() == PreemptionMode::MidThread) {
csrSurfaceCount = 2;
tmpAllocation = GlobalMockSipProgram::sipProgram->getAllocation();
GlobalMockSipProgram::sipProgram->resetAllocation(memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize}));
}
csr->overrideDispatchPolicy(DispatchMode::BatchedDispatch);
auto mockedSubmissionsAggregator = new mockSubmissionsAggregator();
csr->overrideSubmissionAggregator(mockedSubmissionsAggregator);
auto commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
auto dshAlloc = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
auto iohAlloc = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
auto sshAlloc = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
auto tagAllocation = csr->getTagAllocation();
LinearStream cs(commandBuffer);
IndirectHeap dsh(dshAlloc);
IndirectHeap ioh(iohAlloc);
IndirectHeap ssh(sshAlloc);
DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags();
dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(device->getHardwareInfo());
dispatchFlags.guardCommandBufferWithPipeControl = true;
dispatchFlags.requiresCoherency = true;
csr->flushTask(cs, 0u, dsh, ioh, ssh, 0u, dispatchFlags, *device);
auto &cmdBuffers = mockedSubmissionsAggregator->peekCommandBuffers();
auto storedCommandBuffer = cmdBuffers.peekHead();
ResidencyContainer copyOfResidency = storedCommandBuffer->surfaces;
copyOfResidency.push_back(storedCommandBuffer->batchBuffer.commandBufferAllocation);
csr->flushBatchedSubmissions();
EXPECT_TRUE(cmdBuffers.peekIsEmpty());
EXPECT_EQ(1u, wddm->submitResult.called);
auto csrCommandStream = csr->commandStream.getGraphicsAllocation();
EXPECT_EQ(csrCommandStream->getGpuAddress(), wddm->submitResult.commandBufferSubmitted);
EXPECT_TRUE(((COMMAND_BUFFER_HEADER *)wddm->submitResult.commandHeaderSubmitted)->RequiresCoherency);
EXPECT_EQ(6u + csrSurfaceCount, wddm->makeResidentResult.handleCount);
std::vector<D3DKMT_HANDLE> expectedHandles;
expectedHandles.push_back(static_cast<WddmAllocation *>(tagAllocation)->getDefaultHandle());
expectedHandles.push_back(static_cast<WddmAllocation *>(commandBuffer)->getDefaultHandle());
expectedHandles.push_back(static_cast<WddmAllocation *>(dshAlloc)->getDefaultHandle());
expectedHandles.push_back(static_cast<WddmAllocation *>(iohAlloc)->getDefaultHandle());
expectedHandles.push_back(static_cast<WddmAllocation *>(sshAlloc)->getDefaultHandle());
expectedHandles.push_back(static_cast<WddmAllocation *>(csrCommandStream)->getDefaultHandle());
for (auto i = 0u; i < wddm->makeResidentResult.handleCount; i++) {
auto handle = wddm->makeResidentResult.handlePack[i];
auto found = false;
for (auto &expectedHandle : expectedHandles) {
if (expectedHandle == handle) {
found = true;
}
}
EXPECT_TRUE(found);
}
EXPECT_NE(trimListUnusedPosition, static_cast<WddmAllocation *>(tagAllocation)->getTrimCandidateListPosition(csr->getOsContext().getContextId()));
EXPECT_NE(trimListUnusedPosition, static_cast<WddmAllocation *>(commandBuffer)->getTrimCandidateListPosition(csr->getOsContext().getContextId()));
EXPECT_EQ(trimListUnusedPosition, static_cast<WddmAllocation *>(dshAlloc)->getTrimCandidateListPosition(csr->getOsContext().getContextId()));
EXPECT_EQ(trimListUnusedPosition, static_cast<WddmAllocation *>(iohAlloc)->getTrimCandidateListPosition(csr->getOsContext().getContextId()));
EXPECT_NE(trimListUnusedPosition, static_cast<WddmAllocation *>(sshAlloc)->getTrimCandidateListPosition(csr->getOsContext().getContextId()));
EXPECT_NE(trimListUnusedPosition, static_cast<WddmAllocation *>(csrCommandStream)->getTrimCandidateListPosition(csr->getOsContext().getContextId()));
memoryManager->freeGraphicsMemory(dshAlloc);
memoryManager->freeGraphicsMemory(iohAlloc);
memoryManager->freeGraphicsMemory(sshAlloc);
memoryManager->freeGraphicsMemory(commandBuffer);
if (device->getPreemptionMode() == PreemptionMode::MidThread) {
memoryManager->freeGraphicsMemory(GlobalMockSipProgram::sipProgram->getAllocation());
GlobalMockSipProgram::sipProgram->resetAllocation(tmpAllocation);
}
}
using WddmSimpleTest = ::testing::Test;
HWTEST_F(WddmSimpleTest, givenDefaultWddmCsrWhenItIsCreatedThenBatchingIsTurnedOn) {
DebugManager.flags.CsrDispatchMode.set(0);
ExecutionEnvironment *executionEnvironment = platform()->peekExecutionEnvironment();
std::unique_ptr<MockDevice> device(Device::create<MockDevice>(executionEnvironment, 0u));
auto wddm = Wddm::createWddm(nullptr, *executionEnvironment->rootDeviceEnvironments[0].get());
executionEnvironment->rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setWddm(wddm);
executionEnvironment->rootDeviceEnvironments[0]->memoryOperationsInterface = std::make_unique<WddmMemoryOperationsHandler>(wddm);
std::unique_ptr<MockWddmCsr<FamilyType>> mockCsr(new MockWddmCsr<FamilyType>(*executionEnvironment, 0));
EXPECT_EQ(DispatchMode::BatchedDispatch, mockCsr->dispatchMode);
}
HWTEST_F(WddmDefaultTest, givenFtrWddmHwQueuesFlagWhenCreatingCsrThenPickWddmVersionBasingOnFtrFlag) {
auto wddm = Wddm::createWddm(nullptr, *pDevice->executionEnvironment->rootDeviceEnvironments[0].get());
pDevice->executionEnvironment->rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
pDevice->executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setWddm(wddm);
pDevice->executionEnvironment->rootDeviceEnvironments[0]->memoryOperationsInterface = std::make_unique<WddmMemoryOperationsHandler>(wddm);
WddmCommandStreamReceiver<FamilyType> wddmCsr(*pDevice->executionEnvironment, 0);
auto wddmFromCsr = wddmCsr.peekWddm();
EXPECT_EQ(typeid(*wddmFromCsr), typeid(WddmMock));
}
struct WddmCsrCompressionTests : ::testing::Test {
void setCompressionEnabled(bool enableForBuffer, bool enableForImages) {
RuntimeCapabilityTable capabilityTable = platformDevices[0]->capabilityTable;
capabilityTable.ftrRenderCompressedBuffers = enableForBuffer;
capabilityTable.ftrRenderCompressedImages = enableForImages;
hwInfo->capabilityTable = capabilityTable;
}
HardwareInfo *hwInfo = nullptr;
WddmMock *myMockWddm;
};
struct WddmCsrCompressionParameterizedTest : WddmCsrCompressionTests, ::testing::WithParamInterface<bool /*compressionEnabled*/> {
void SetUp() override {
compressionEnabled = GetParam();
}
bool compressionEnabled;
};
HWTEST_P(WddmCsrCompressionParameterizedTest, givenEnabledCompressionWhenInitializedThenCreatePagetableMngr) {
uint32_t index = 1u;
ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 2);
std::unique_ptr<MockDevice> device(Device::create<MockDevice>(executionEnvironment, 1u));
setCompressionEnabled(compressionEnabled, !compressionEnabled);
myMockWddm = static_cast<WddmMock *>(executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->getWddm());
EXPECT_EQ(nullptr, executionEnvironment->rootDeviceEnvironments[index]->pageTableManager.get());
MockWddmCsr<FamilyType> mockWddmCsr(*executionEnvironment, index);
mockWddmCsr.createPageTableManager();
ASSERT_NE(nullptr, executionEnvironment->rootDeviceEnvironments[index]->pageTableManager.get());
auto mockMngr = reinterpret_cast<MockGmmPageTableMngr *>(executionEnvironment->rootDeviceEnvironments[index]->pageTableManager.get());
EXPECT_EQ(1u, mockMngr->setCsrHanleCalled);
EXPECT_EQ(&mockWddmCsr, mockMngr->passedCsrHandle);
GMM_TRANSLATIONTABLE_CALLBACKS expectedTTCallbacks = {};
unsigned int expectedFlags = TT_TYPE::AUXTT;
expectedTTCallbacks.pfWriteL3Adr = TTCallbacks<FamilyType>::writeL3Address;
EXPECT_TRUE(memcmp(&expectedTTCallbacks, &mockMngr->translationTableCb, sizeof(GMM_TRANSLATIONTABLE_CALLBACKS)) == 0);
EXPECT_TRUE(memcmp(&expectedFlags, &mockMngr->translationTableFlags, sizeof(unsigned int)) == 0);
}
HWTEST_F(WddmCsrCompressionTests, givenDisabledCompressionWhenInitializedThenDontCreatePagetableMngr) {
ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 2);
std::unique_ptr<MockDevice> device(Device::create<MockDevice>(executionEnvironment, 1u));
setCompressionEnabled(false, false);
myMockWddm = static_cast<WddmMock *>(executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->getWddm());
MockWddmCsr<FamilyType> mockWddmCsr(*executionEnvironment, 1);
EXPECT_EQ(nullptr, executionEnvironment->rootDeviceEnvironments[1]->pageTableManager.get());
}
INSTANTIATE_TEST_CASE_P(
WddmCsrCompressionParameterizedTestCreate,
WddmCsrCompressionParameterizedTest,
::testing::Bool());
HWTEST_F(WddmCsrCompressionTests, givenDisabledCompressionWhenFlushingThenDontInitTranslationTable) {
ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 2);
setCompressionEnabled(false, false);
myMockWddm = static_cast<WddmMock *>(executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->getWddm());
auto mockWddmCsr = new MockWddmCsr<FamilyType>(*executionEnvironment, 1);
mockWddmCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch);
executionEnvironment->memoryManager.reset(new WddmMemoryManager(*executionEnvironment));
std::unique_ptr<MockDevice> device(Device::create<MockDevice>(executionEnvironment, 1u));
device->resetCommandStreamReceiver(mockWddmCsr);
auto memoryManager = executionEnvironment->memoryManager.get();
EXPECT_EQ(nullptr, executionEnvironment->rootDeviceEnvironments[1]->pageTableManager.get());
auto graphicsAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{MemoryConstants::pageSize});
IndirectHeap cs(graphicsAllocation);
EXPECT_EQ(nullptr, executionEnvironment->rootDeviceEnvironments[1]->pageTableManager.get());
DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags();
mockWddmCsr->flushTask(cs, 0u, cs, cs, cs, 0u, dispatchFlags, *device);
EXPECT_EQ(nullptr, executionEnvironment->rootDeviceEnvironments[1]->pageTableManager.get());
mockWddmCsr->flushBatchedSubmissions();
memoryManager->freeGraphicsMemory(graphicsAllocation);
}
TEST_F(WddmCommandStreamTest, whenDirectSubmissionDisabledThenExpectNoFeatureAvailable) {
bool ret = csr->initDirectSubmission(*device.get(), *osContext.get());
EXPECT_TRUE(ret);
EXPECT_FALSE(csr->isDirectSubmissionEnabled());
}
TEST_F(WddmCommandStreamTest, whenDirectSubmissionEnabledOnRcsThenExpectFeatureAvailable) {
DebugManager.flags.EnableDirectSubmission.set(1);
auto hwInfo = device->getExecutionEnvironment()->getMutableHardwareInfo();
hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].engineSupported = true;
bool ret = csr->initDirectSubmission(*device.get(), *osContext.get());
EXPECT_TRUE(ret);
EXPECT_TRUE(csr->isDirectSubmissionEnabled());
}
TEST_F(WddmCommandStreamTest, givenDirectSubmissionEnabledWhenPlatformNotSupportsRcsThenExpectFeatureNotAvailable) {
DebugManager.flags.EnableDirectSubmission.set(1);
auto hwInfo = device->getExecutionEnvironment()->getMutableHardwareInfo();
hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].engineSupported = false;
bool ret = csr->initDirectSubmission(*device.get(), *osContext.get());
EXPECT_TRUE(ret);
EXPECT_FALSE(csr->isDirectSubmissionEnabled());
}
TEST_F(WddmCommandStreamTest, whenDirectSubmissionEnabledOnBcsThenExpectFeatureAvailable) {
DebugManager.flags.EnableDirectSubmission.set(1);
osContext.reset(OsContext::create(device->getExecutionEnvironment()->rootDeviceEnvironments[0]->osInterface.get(),
0, 0, aub_stream::ENGINE_BCS, PreemptionMode::ThreadGroup, false));
auto hwInfo = device->getExecutionEnvironment()->getMutableHardwareInfo();
hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_BCS].engineSupported = true;
bool ret = csr->initDirectSubmission(*device.get(), *osContext.get());
EXPECT_TRUE(ret);
EXPECT_TRUE(csr->isDirectSubmissionEnabled());
}
TEST_F(WddmCommandStreamTest, givenDirectSubmissionEnabledWhenPlatformNotSupportsBcsThenExpectFeatureNotAvailable) {
DebugManager.flags.EnableDirectSubmission.set(1);
osContext.reset(OsContext::create(device->getExecutionEnvironment()->rootDeviceEnvironments[0]->osInterface.get(),
0, 0, aub_stream::ENGINE_BCS, PreemptionMode::ThreadGroup, false));
auto hwInfo = device->getExecutionEnvironment()->getMutableHardwareInfo();
hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_BCS].engineSupported = false;
bool ret = csr->initDirectSubmission(*device.get(), *osContext.get());
EXPECT_TRUE(ret);
EXPECT_FALSE(csr->isDirectSubmissionEnabled());
}

View File

@ -0,0 +1,86 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/device/device.h"
#include "core/helpers/get_info.h"
#include "core/unit_tests/helpers/debug_manager_state_restore.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "mocks/mock_device.h"
using namespace ::testing;
namespace NEO {
TEST(DeviceOsTest, GivenDefaultDeviceWhenCheckingForOsSpecificExtensionsThenCorrectExtensionsAreSet) {
auto hwInfo = *platformDevices;
auto pDevice = MockDevice::createWithNewExecutionEnvironment<Device>(hwInfo);
std::string extensionString(pDevice->getDeviceInfo().deviceExtensions);
EXPECT_THAT(extensionString, Not(HasSubstr(std::string("cl_intel_va_api_media_sharing "))));
EXPECT_THAT(extensionString, HasSubstr(std::string("cl_intel_dx9_media_sharing ")));
EXPECT_THAT(extensionString, HasSubstr(std::string("cl_khr_dx9_media_sharing ")));
EXPECT_THAT(extensionString, HasSubstr(std::string("cl_khr_d3d10_sharing ")));
EXPECT_THAT(extensionString, HasSubstr(std::string("cl_khr_d3d11_sharing ")));
EXPECT_THAT(extensionString, HasSubstr(std::string("cl_intel_d3d11_nv12_media_sharing ")));
EXPECT_THAT(extensionString, Not(HasSubstr(std::string("cl_intel_simultaneous_sharing "))));
delete pDevice;
}
TEST(DeviceOsTest, GivenDefaultClDeviceWhenCheckingForOsSpecificExtensionsThenCorrectExtensionsAreSet) {
auto hwInfo = *platformDevices;
auto pDevice = MockDevice::createWithNewExecutionEnvironment<Device>(hwInfo);
auto pClDevice = new ClDevice{*pDevice, platform()};
std::string extensionString(pClDevice->getDeviceInfo().deviceExtensions);
EXPECT_THAT(extensionString, Not(HasSubstr(std::string("cl_intel_va_api_media_sharing "))));
EXPECT_THAT(extensionString, HasSubstr(std::string("cl_intel_dx9_media_sharing ")));
EXPECT_THAT(extensionString, HasSubstr(std::string("cl_khr_dx9_media_sharing ")));
EXPECT_THAT(extensionString, HasSubstr(std::string("cl_khr_d3d10_sharing ")));
EXPECT_THAT(extensionString, HasSubstr(std::string("cl_khr_d3d11_sharing ")));
EXPECT_THAT(extensionString, HasSubstr(std::string("cl_intel_d3d11_nv12_media_sharing ")));
EXPECT_THAT(extensionString, HasSubstr(std::string("cl_intel_simultaneous_sharing ")));
delete pClDevice;
}
TEST(DeviceOsTest, supportedSimultaneousInterops) {
auto pDevice = std::make_unique<MockClDevice>(MockDevice::createWithNewExecutionEnvironment<MockDevice>(*platformDevices));
std::vector<unsigned int> expected = {CL_GL_CONTEXT_KHR,
CL_WGL_HDC_KHR,
CL_CONTEXT_ADAPTER_D3D9_KHR,
CL_CONTEXT_D3D9_DEVICE_INTEL,
CL_CONTEXT_ADAPTER_D3D9EX_KHR,
CL_CONTEXT_D3D9EX_DEVICE_INTEL,
CL_CONTEXT_ADAPTER_DXVA_KHR,
CL_CONTEXT_DXVA_DEVICE_INTEL,
CL_CONTEXT_D3D10_DEVICE_KHR,
CL_CONTEXT_D3D11_DEVICE_KHR,
0};
EXPECT_TRUE(pDevice->simultaneousInterops == expected);
}
TEST(DeviceOsTest, DeviceCreationFail) {
auto hwInfo = *platformDevices;
auto pDevice = MockDevice::createWithNewExecutionEnvironment<FailDevice>(hwInfo);
EXPECT_THAT(pDevice, nullptr);
}
TEST(DeviceOsTest, DeviceCreationFailMidThreadPreemption) {
DebugManagerStateRestore dbgRestore;
DebugManager.flags.ForcePreemptionMode.set(static_cast<int32_t>(PreemptionMode::MidThread));
auto pDevice = MockDevice::createWithNewExecutionEnvironment<FailDeviceAfterOne>(*platformDevices);
EXPECT_THAT(pDevice, nullptr);
}
} // namespace NEO

View File

@ -0,0 +1,171 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/command_stream/preemption.h"
#include "core/execution_environment/execution_environment.h"
#include "core/execution_environment/root_device_environment.h"
#include "core/os_interface/windows/debug_registry_reader.h"
#include "core/os_interface/windows/os_interface.h"
#include "core/unit_tests/helpers/ult_hw_config.h"
#include "opencl/source/memory_manager/os_agnostic_memory_manager.h"
#include "opencl/source/os_interface/windows/driver_info.h"
#include "gtest/gtest.h"
#include "helpers/variable_backup.h"
#include "mocks/mock_csr.h"
#include "mocks/mock_device.h"
#include "mocks/mock_execution_environment.h"
#include "mocks/mock_wddm.h"
#include "os_interface/windows/registry_reader_tests.h"
#include <memory>
namespace NEO {
extern CommandStreamReceiverCreateFunc commandStreamReceiverFactory[IGFX_MAX_CORE];
CommandStreamReceiver *createMockCommandStreamReceiver(bool withAubDump, ExecutionEnvironment &executionEnvironment, uint32_t rootDeviceIndex);
class DriverInfoDeviceTest : public ::testing::Test {
public:
void SetUp() {
hwInfo = platformDevices[0];
commandStreamReceiverCreateFunc = commandStreamReceiverFactory[hwInfo->platform.eRenderCoreFamily];
commandStreamReceiverFactory[hwInfo->platform.eRenderCoreFamily] = createMockCommandStreamReceiver;
}
void TearDown() {
commandStreamReceiverFactory[hwInfo->platform.eRenderCoreFamily] = commandStreamReceiverCreateFunc;
}
CommandStreamReceiverCreateFunc commandStreamReceiverCreateFunc;
const HardwareInfo *hwInfo;
};
CommandStreamReceiver *createMockCommandStreamReceiver(bool withAubDump, ExecutionEnvironment &executionEnvironment, uint32_t rootDeviceIndex) {
auto csr = new MockCommandStreamReceiver(executionEnvironment, rootDeviceIndex);
if (!executionEnvironment.rootDeviceEnvironments[rootDeviceIndex]->osInterface) {
executionEnvironment.rootDeviceEnvironments[rootDeviceIndex]->osInterface = std::make_unique<OSInterface>();
auto wddm = new WddmMock(*executionEnvironment.rootDeviceEnvironments[0]);
wddm->init();
executionEnvironment.rootDeviceEnvironments[rootDeviceIndex]->osInterface->get()->setWddm(wddm);
}
EXPECT_NE(nullptr, executionEnvironment.rootDeviceEnvironments[rootDeviceIndex]->osInterface.get());
return csr;
}
TEST_F(DriverInfoDeviceTest, GivenDeviceCreatedWhenCorrectOSInterfaceThenCreateDriverInfo) {
VariableBackup<UltHwConfig> backup(&ultHwConfig);
ultHwConfig.useHwCsr = true;
auto device = MockDevice::createWithNewExecutionEnvironment<MockDevice>(hwInfo);
EXPECT_TRUE(device->hasDriverInfo());
delete device;
}
TEST_F(DriverInfoDeviceTest, GivenDeviceCreatedWithoutCorrectOSInterfaceThenDontCreateDriverInfo) {
VariableBackup<UltHwConfig> backup(&ultHwConfig);
ultHwConfig.useHwCsr = false;
auto device = MockDevice::createWithNewExecutionEnvironment<MockDevice>(hwInfo);
EXPECT_FALSE(device->hasDriverInfo());
delete device;
}
class RegistryReaderMock : public SettingsReader {
public:
std::string nameString;
std::string versionString;
std::string getSetting(const char *settingName, const std::string &value) {
std::string key(settingName);
if (key == "HardwareInformation.AdapterString") {
properNameKey = true;
} else if (key == "DriverVersion") {
properVersionKey = true;
}
return value;
}
bool getSetting(const char *settingName, bool defaultValue) { return defaultValue; };
int32_t getSetting(const char *settingName, int32_t defaultValue) { return defaultValue; };
const char *appSpecificLocation(const std::string &name) { return name.c_str(); };
bool properNameKey = false;
bool properVersionKey = false;
};
TEST(DriverInfo, GivenDriverInfoWhenThenReturnNonNullptr) {
DriverInfoWindows driverInfo;
RegistryReaderMock *registryReaderMock = new RegistryReaderMock();
driverInfo.setRegistryReader(registryReaderMock);
std::string defaultName = "defaultName";
auto name = driverInfo.getDeviceName(defaultName);
EXPECT_STREQ(defaultName.c_str(), name.c_str());
EXPECT_TRUE(registryReaderMock->properNameKey);
std::string defaultVersion = "defaultVersion";
auto driverVersion = driverInfo.getVersion(defaultVersion);
EXPECT_STREQ(defaultVersion.c_str(), driverVersion.c_str());
EXPECT_TRUE(registryReaderMock->properVersionKey);
};
TEST(DriverInfo, givenInitializedOsInterfaceWhenCreateDriverInfoThenReturnDriverInfoWindowsNotNullptr) {
MockExecutionEnvironment executionEnvironment;
RootDeviceEnvironment rootDeviceEnvironment(executionEnvironment);
std::unique_ptr<OSInterface> osInterface(new OSInterface());
osInterface->get()->setWddm(Wddm::createWddm(nullptr, rootDeviceEnvironment));
EXPECT_NE(nullptr, osInterface->get()->getWddm());
std::unique_ptr<DriverInfo> driverInfo(DriverInfo::create(osInterface.get()));
EXPECT_NE(nullptr, driverInfo);
};
TEST(DriverInfo, givenNotInitializedOsInterfaceWhenCreateDriverInfoThenReturnDriverInfoWindowsNullptr) {
std::unique_ptr<OSInterface> osInterface;
std::unique_ptr<DriverInfo> driverInfo(DriverInfo::create(osInterface.get()));
EXPECT_EQ(nullptr, driverInfo);
};
class MockDriverInfoWindows : public DriverInfoWindows {
public:
const char *getRegistryReaderRegKey() {
return reader->getRegKey();
}
TestedRegistryReader *reader;
static MockDriverInfoWindows *create(std::string path) {
auto result = new MockDriverInfoWindows();
result->reader = new TestedRegistryReader(path);
result->setRegistryReader(result->reader);
return result;
};
};
TEST(DriverInfo, givenInitializedOsInterfaceWhenCreateDriverInfoWindowsThenSetRegistryReaderWithExpectRegKey) {
std::string path = "";
std::unique_ptr<MockDriverInfoWindows> driverInfo(MockDriverInfoWindows::create(path));
std::unique_ptr<TestedRegistryReader> reader(new TestedRegistryReader(path));
EXPECT_NE(nullptr, reader);
EXPECT_STREQ(driverInfo->getRegistryReaderRegKey(), reader->getRegKey());
};
} // namespace NEO

View File

@ -0,0 +1,91 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/debug_settings/debug_settings_manager.h"
#include "core/gmm_helper/gmm.h"
#include "opencl/source/platform/platform.h"
#include "test.h"
#include "os_interface/windows/mock_wddm_allocation.h"
#include "utilities/file_logger_tests.h"
using namespace NEO;
TEST(FileLogger, GivenLogAllocationMemoryPoolFlagThenLogsCorrectInfo) {
std::string testFile = "testfile";
DebugVariables flags;
flags.LogAllocationMemoryPool.set(true);
FullyEnabledFileLogger fileLogger(testFile, flags);
// Log file not created
bool logFileCreated = fileExists(fileLogger.getLogFileName());
EXPECT_FALSE(logFileCreated);
MockWddmAllocation allocation;
allocation.handle = 4;
allocation.setAllocationType(GraphicsAllocation::AllocationType::BUFFER);
allocation.memoryPool = MemoryPool::System64KBPages;
auto gmm = std::make_unique<Gmm>(platform()->peekExecutionEnvironment()->getGmmClientContext(), nullptr, 0, false);
allocation.setDefaultGmm(gmm.get());
allocation.getDefaultGmm()->resourceParams.Flags.Info.NonLocalOnly = 0;
fileLogger.logAllocation(&allocation);
std::thread::id thisThread = std::this_thread::get_id();
std::stringstream threadIDCheck;
threadIDCheck << " ThreadID: " << thisThread;
std::stringstream memoryPoolCheck;
memoryPoolCheck << " MemoryPool: " << allocation.getMemoryPool();
if (fileLogger.wasFileCreated(fileLogger.getLogFileName())) {
auto str = fileLogger.getFileString(fileLogger.getLogFileName());
EXPECT_TRUE(str.find(threadIDCheck.str()) != std::string::npos);
EXPECT_TRUE(str.find("Handle: 4") != std::string::npos);
EXPECT_TRUE(str.find(memoryPoolCheck.str()) != std::string::npos);
EXPECT_TRUE(str.find("AllocationType: BUFFER") != std::string::npos);
}
}
TEST(FileLogger, GivenLogAllocationMemoryPoolFlagSetFalseThenAllocationIsNotLogged) {
std::string testFile = "testfile";
DebugVariables flags;
flags.LogAllocationMemoryPool.set(false);
FullyEnabledFileLogger fileLogger(testFile, flags);
// Log file not created
bool logFileCreated = fileExists(fileLogger.getLogFileName());
EXPECT_FALSE(logFileCreated);
MockWddmAllocation allocation;
allocation.handle = 4;
allocation.setAllocationType(GraphicsAllocation::AllocationType::BUFFER);
allocation.memoryPool = MemoryPool::System64KBPages;
auto gmm = std::make_unique<Gmm>(platform()->peekExecutionEnvironment()->getGmmClientContext(), nullptr, 0, false);
allocation.setDefaultGmm(gmm.get());
allocation.getDefaultGmm()->resourceParams.Flags.Info.NonLocalOnly = 0;
fileLogger.logAllocation(&allocation);
std::thread::id thisThread = std::this_thread::get_id();
std::stringstream threadIDCheck;
threadIDCheck << " ThreadID: " << thisThread;
std::stringstream memoryPoolCheck;
memoryPoolCheck << " MemoryPool: " << allocation.getMemoryPool();
if (fileLogger.wasFileCreated(fileLogger.getLogFileName())) {
auto str = fileLogger.getFileString(fileLogger.getLogFileName());
EXPECT_FALSE(str.find(threadIDCheck.str()) != std::string::npos);
EXPECT_FALSE(str.find("Handle: 4") != std::string::npos);
EXPECT_FALSE(str.find(memoryPoolCheck.str()) != std::string::npos);
EXPECT_FALSE(str.find("AllocationType: BUFFER") != std::string::npos);
EXPECT_FALSE(str.find("NonLocalOnly: 0") != std::string::npos);
}
}

View File

@ -0,0 +1,90 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/helpers/hw_info.h"
#include "core/os_interface/os_library.h"
#include "core/unit_tests/helpers/default_hw_info.h"
#include "mock_gdi/mock_gdi.h"
using namespace NEO;
OsLibrary *setAdapterInfo(const PLATFORM *platform, const GT_SYSTEM_INFO *gtSystemInfo, uint64_t gpuAddressSpace);
struct GdiDllFixture {
virtual void SetUp() {
const HardwareInfo *hwInfo = platformDevices[0];
mockGdiDll.reset(setAdapterInfo(&hwInfo->platform, &hwInfo->gtSystemInfo, hwInfo->capabilityTable.gpuAddressSpace));
setSizesFcn = reinterpret_cast<decltype(&MockSetSizes)>(mockGdiDll->getProcAddress("MockSetSizes"));
getSizesFcn = reinterpret_cast<decltype(&GetMockSizes)>(mockGdiDll->getProcAddress("GetMockSizes"));
getMockLastDestroyedResHandleFcn =
reinterpret_cast<decltype(&GetMockLastDestroyedResHandle)>(mockGdiDll->getProcAddress("GetMockLastDestroyedResHandle"));
setMockLastDestroyedResHandleFcn =
reinterpret_cast<decltype(&SetMockLastDestroyedResHandle)>(mockGdiDll->getProcAddress("SetMockLastDestroyedResHandle"));
getMockCreateDeviceParamsFcn =
reinterpret_cast<decltype(&GetMockCreateDeviceParams)>(mockGdiDll->getProcAddress("GetMockCreateDeviceParams"));
setMockCreateDeviceParamsFcn =
reinterpret_cast<decltype(&SetMockCreateDeviceParams)>(mockGdiDll->getProcAddress("SetMockCreateDeviceParams"));
getMockAllocationFcn = reinterpret_cast<decltype(&getMockAllocation)>(mockGdiDll->getProcAddress("getMockAllocation"));
getAdapterInfoAddressFcn = reinterpret_cast<decltype(&getAdapterInfoAddress)>(mockGdiDll->getProcAddress("getAdapterInfoAddress"));
getLastCallMapGpuVaArgFcn = reinterpret_cast<decltype(&getLastCallMapGpuVaArg)>(mockGdiDll->getProcAddress("getLastCallMapGpuVaArg"));
getLastCallReserveGpuVaArgFcn = reinterpret_cast<decltype(&getLastCallReserveGpuVaArg)>(mockGdiDll->getProcAddress("getLastCallReserveGpuVaArg"));
setMapGpuVaFailConfigFcn = reinterpret_cast<decltype(&setMapGpuVaFailConfig)>(mockGdiDll->getProcAddress("setMapGpuVaFailConfig"));
setMapGpuVaFailConfigFcn(0, 0);
getCreateContextDataFcn = reinterpret_cast<decltype(&getCreateContextData)>(mockGdiDll->getProcAddress("getCreateContextData"));
getCreateHwQueueDataFcn = reinterpret_cast<decltype(&getCreateHwQueueData)>(mockGdiDll->getProcAddress("getCreateHwQueueData"));
getDestroyHwQueueDataFcn = reinterpret_cast<decltype(&getDestroyHwQueueData)>(mockGdiDll->getProcAddress("getDestroyHwQueueData"));
getSubmitCommandToHwQueueDataFcn =
reinterpret_cast<decltype(&getSubmitCommandToHwQueueData)>(mockGdiDll->getProcAddress("getSubmitCommandToHwQueueData"));
getDestroySynchronizationObjectDataFcn =
reinterpret_cast<decltype(&getDestroySynchronizationObjectData)>(mockGdiDll->getProcAddress("getDestroySynchronizationObjectData"));
getMonitorFenceCpuFenceAddressFcn =
reinterpret_cast<decltype(&getMonitorFenceCpuFenceAddress)>(mockGdiDll->getProcAddress("getMonitorFenceCpuFenceAddress"));
getCreateSynchronizationObject2FailCallFcn =
reinterpret_cast<decltype(&getCreateSynchronizationObject2FailCall)>(mockGdiDll->getProcAddress("getCreateSynchronizationObject2FailCall"));
getRegisterTrimNotificationFailCallFcn =
reinterpret_cast<decltype(&getRegisterTrimNotificationFailCall)>(mockGdiDll->getProcAddress("getRegisterTrimNotificationFailCall"));
setMockLastDestroyedResHandleFcn((D3DKMT_HANDLE)0);
*getDestroySynchronizationObjectDataFcn() = {};
*getCreateSynchronizationObject2FailCallFcn() = false;
*getRegisterTrimNotificationFailCallFcn() = false;
}
virtual void TearDown() {
*getCreateHwQueueDataFcn() = {};
*getDestroyHwQueueDataFcn() = {};
*getSubmitCommandToHwQueueDataFcn() = {};
*getDestroySynchronizationObjectDataFcn() = {};
setMapGpuVaFailConfigFcn(0, 0);
*getCreateSynchronizationObject2FailCallFcn() = false;
*getRegisterTrimNotificationFailCallFcn() = false;
}
std::unique_ptr<OsLibrary> mockGdiDll;
decltype(&MockSetSizes) setSizesFcn = nullptr;
decltype(&GetMockSizes) getSizesFcn = nullptr;
decltype(&GetMockLastDestroyedResHandle) getMockLastDestroyedResHandleFcn = nullptr;
decltype(&SetMockLastDestroyedResHandle) setMockLastDestroyedResHandleFcn = nullptr;
decltype(&GetMockCreateDeviceParams) getMockCreateDeviceParamsFcn = nullptr;
decltype(&SetMockCreateDeviceParams) setMockCreateDeviceParamsFcn = nullptr;
decltype(&getMockAllocation) getMockAllocationFcn = nullptr;
decltype(&getAdapterInfoAddress) getAdapterInfoAddressFcn = nullptr;
decltype(&getLastCallMapGpuVaArg) getLastCallMapGpuVaArgFcn = nullptr;
decltype(&getLastCallReserveGpuVaArg) getLastCallReserveGpuVaArgFcn = nullptr;
decltype(&setMapGpuVaFailConfig) setMapGpuVaFailConfigFcn = nullptr;
decltype(&getCreateContextData) getCreateContextDataFcn = nullptr;
decltype(&getCreateHwQueueData) getCreateHwQueueDataFcn = nullptr;
decltype(&getDestroyHwQueueData) getDestroyHwQueueDataFcn = nullptr;
decltype(&getSubmitCommandToHwQueueData) getSubmitCommandToHwQueueDataFcn = nullptr;
decltype(&getDestroySynchronizationObjectData) getDestroySynchronizationObjectDataFcn = nullptr;
decltype(&getMonitorFenceCpuFenceAddress) getMonitorFenceCpuFenceAddressFcn = nullptr;
decltype(&getCreateSynchronizationObject2FailCall) getCreateSynchronizationObject2FailCallFcn = nullptr;
decltype(&getRegisterTrimNotificationFailCall) getRegisterTrimNotificationFailCallFcn = nullptr;
};

View File

@ -0,0 +1,15 @@
#
# Copyright (C) 2017-2020 Intel Corporation
#
# SPDX-License-Identifier: MIT
#
if(WIN32)
set(IGDRCL_SRCS_tests_os_interface_windows_gl
${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt
${CMAKE_CURRENT_SOURCE_DIR}/gl_os_sharing_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/gl_options.cpp
${CMAKE_CURRENT_SOURCE_DIR}/gl_dll_helper.h
)
target_sources(igdrcl_tests PRIVATE ${IGDRCL_SRCS_tests_os_interface_windows_gl})
endif()

View File

@ -0,0 +1,95 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/helpers/debug_helpers.h"
#include "core/os_interface/os_library.h"
#include "opencl/source/extensions/public/cl_gl_private_intel.h"
#include "Gl/gl.h"
#include <memory>
using namespace NEO;
namespace Os {
extern const char *openglDllName;
}
namespace NEO {
struct GLMockReturnedValues;
}
using GLString = void (*)(const char *, unsigned int);
using GLSharedOCLContext = void (*)(GLboolean);
using glBoolean = GLboolean (*)();
using Void = void (*)(const char *);
using Int = int (*)(const char *);
using BufferParam = void (*)(CL_GL_BUFFER_INFO);
using TextureParam = void (*)(CL_GL_RESOURCE_INFO);
using BuffInfo = CL_GL_BUFFER_INFO (*)();
using TextureInfo = CL_GL_RESOURCE_INFO (*)();
using GLMockValue = GLMockReturnedValues (*)();
using setGLMockValue = void (*)(GLMockReturnedValues);
struct glDllHelper {
public:
glDllHelper() {
glDllLoad.reset(OsLibrary::load(Os::openglDllName));
if (glDllLoad) {
glSetString = (*glDllLoad)["glSetString"];
UNRECOVERABLE_IF(glSetString == nullptr);
glSetStringi = (*glDllLoad)["glSetStringi"];
UNRECOVERABLE_IF(glSetStringi == nullptr);
setGLSetSharedOCLContextStateReturnedValue = (*glDllLoad)["setGLSetSharedOCLContextStateReturnedValue"];
UNRECOVERABLE_IF(setGLSetSharedOCLContextStateReturnedValue == nullptr);
getGLSetSharedOCLContextStateReturnedValue = (*glDllLoad)["getGLSetSharedOCLContextStateReturnedValue"];
UNRECOVERABLE_IF(getGLSetSharedOCLContextStateReturnedValue == nullptr);
resetParam = (*glDllLoad)["resetParam"];
UNRECOVERABLE_IF(resetParam == nullptr);
getParam = (*glDllLoad)["getParam"];
UNRECOVERABLE_IF(getParam == nullptr);
loadBuffer = (*glDllLoad)["loadBuffer"];
UNRECOVERABLE_IF(loadBuffer == nullptr);
getBufferInfo = (*glDllLoad)["getBufferInfo"];
UNRECOVERABLE_IF(getBufferInfo == nullptr);
getTextureInfo = (*glDllLoad)["getTextureInfo"];
UNRECOVERABLE_IF(getTextureInfo == nullptr);
Void memParam = (*glDllLoad)["memParam"];
UNRECOVERABLE_IF(memParam == nullptr);
loadTexture = (*glDllLoad)["loadTexture"];
UNRECOVERABLE_IF(loadTexture == nullptr);
getGlMockReturnedValues = (*glDllLoad)["getGlMockReturnedValues"];
UNRECOVERABLE_IF(getGlMockReturnedValues == nullptr);
setGlMockReturnedValues = (*glDllLoad)["setGlMockReturnedValues"];
UNRECOVERABLE_IF(setGlMockReturnedValues == nullptr);
}
}
~glDllHelper() {
if (glDllLoad) {
glSetString("Intel", GL_VENDOR);
glSetString("4.0", GL_VERSION);
glSetStringi("GL_OES_framebuffer_object", 0);
glSetStringi("GL_EXT_framebuffer_object", 1);
}
}
GLString glSetString;
GLString glSetStringi;
GLSharedOCLContext setGLSetSharedOCLContextStateReturnedValue;
glBoolean getGLSetSharedOCLContextStateReturnedValue;
Void resetParam;
Int getParam;
BufferParam loadBuffer;
TextureParam loadTexture;
BuffInfo getBufferInfo;
TextureInfo getTextureInfo;
GLMockValue getGlMockReturnedValues;
setGLMockValue setGlMockReturnedValues;
private:
std::unique_ptr<OsLibrary> glDllLoad;
};

View File

@ -0,0 +1,13 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include <cstdint>
// above is workaround for copyright checker issue
namespace Os {
const char *openglDllName = "mock_opengl32.dll";
}

View File

@ -0,0 +1,456 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/execution_environment/root_device_environment.h"
#include "core/helpers/timestamp_packet.h"
#include "core/os_interface/os_interface.h"
#include "core/os_interface/windows/os_context_win.h"
#include "core/os_interface/windows/os_interface.h"
#include "core/os_interface/windows/wddm/wddm.h"
#include "core/os_interface/windows/wddm_memory_operations_handler.h"
#include "opencl/source/extensions/public/cl_gl_private_intel.h"
#include "opencl/source/sharings/gl/gl_arb_sync_event.h"
#include "opencl/source/sharings/gl/windows/gl_sharing_windows.h"
#include "gtest/gtest.h"
#include "mocks/gl/windows/mock_gl_sharing_windows.h"
#include "mocks/mock_execution_environment.h"
#include "os_interface/windows/wddm_fixture.h"
#include <GL/gl.h>
using namespace NEO;
struct MockOSInterfaceImpl : OSInterface::OSInterfaceImpl {
HANDLE createEvent(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState,
LPCSTR lpName) override {
if (eventNum++ == failEventNum) {
return INVALID_HANDLE;
}
return OSInterface::OSInterfaceImpl::createEvent(lpEventAttributes, bManualReset, bInitialState, lpName);
}
BOOL closeHandle(HANDLE hObject) override {
++closedEventsCount;
return OSInterface::OSInterfaceImpl::closeHandle(hObject);
}
int eventNum = 1;
int failEventNum = 0;
int closedEventsCount = 0;
};
struct MockOSInterface : OSInterface {
MockOSInterface() {
if (osInterfaceImpl != nullptr) {
delete osInterfaceImpl;
}
osInterfaceImpl = new MockOSInterfaceImpl();
}
};
TEST(glSharingBasicTest, GivenSharingFunctionsWhenItIsConstructedThenBackupContextIsCreated) {
GLType GLHDCType = CL_WGL_HDC_KHR;
GLContext GLHGLRCHandle = 0;
GLDisplay GLHDCHandle = 0;
int32_t expectedContextAttrs[3] = {0};
glDllHelper dllHelper;
auto glSharingFunctions = new GlSharingFunctionsMock(GLHDCType, GLHGLRCHandle, GLHGLRCHandle, GLHDCHandle);
EXPECT_EQ(1, dllHelper.getParam("WGLCreateContextCalled"));
EXPECT_EQ(1, dllHelper.getParam("WGLShareListsCalled"));
EXPECT_EQ(0, EGLChooseConfigCalled);
EXPECT_EQ(0, EGLCreateContextCalled);
EXPECT_EQ(0, GlxChooseFBConfigCalled);
EXPECT_EQ(0, GlxQueryContextCalled);
EXPECT_EQ(0, GlxCreateNewContextCalled);
EXPECT_EQ(0, GlxIsDirectCalled);
EXPECT_EQ(0, eglBkpContextParams.configAttrs);
EXPECT_EQ(0, eglBkpContextParams.numConfigs);
EXPECT_TRUE(glSharingFunctions->getBackupContextHandle() != 0);
EXPECT_TRUE(memcmp(eglBkpContextParams.contextAttrs, expectedContextAttrs, 3 * sizeof(int32_t)) == 0);
EXPECT_EQ(0, glxBkpContextParams.FBConfigAttrs);
EXPECT_EQ(0, glxBkpContextParams.queryAttribute);
EXPECT_EQ(0, glxBkpContextParams.renderType);
delete glSharingFunctions;
EXPECT_EQ(1, dllHelper.getParam("WGLDeleteContextCalled"));
EXPECT_EQ(1, dllHelper.getParam("GLDeleteContextCalled"));
}
struct GlArbSyncEventOsTest : public ::testing::Test {
void SetUp() override {
rootDeviceEnvironment = std::make_unique<RootDeviceEnvironment>(executionEnvironment);
sharing.GLContextHandle = 0x2cU;
sharing.GLDeviceHandle = 0x3cU;
wddm = new WddmMock(*rootDeviceEnvironment);
gdi = new MockGdi();
wddm->resetGdi(gdi);
osInterface.get()->setWddm(wddm);
}
MockExecutionEnvironment executionEnvironment;
std::unique_ptr<RootDeviceEnvironment> rootDeviceEnvironment;
GlSharingFunctionsMock sharing;
MockGdi *gdi = nullptr;
WddmMock *wddm = nullptr;
OSInterface osInterface;
CL_GL_SYNC_INFO syncInfo = {};
};
TEST_F(GlArbSyncEventOsTest, WhenCreateSynchronizationObjectSucceedsThenAllHAndlesAreValid) {
struct CreateSyncObjectMock {
static int &getHandle() {
static int handle = 1;
return handle;
}
static void reset() {
getHandle() = 1;
}
static NTSTATUS __stdcall createSynchObject(D3DKMT_CREATESYNCHRONIZATIONOBJECT *pData) {
if (pData == nullptr) {
return STATUS_INVALID_PARAMETER;
}
EXPECT_NE(NULL, pData->hDevice);
EXPECT_EQ(D3DDDI_SEMAPHORE, pData->Info.Type);
EXPECT_EQ(32, pData->Info.Semaphore.MaxCount);
EXPECT_EQ(0, pData->Info.Semaphore.InitialCount);
pData->hSyncObject = getHandle()++;
return STATUS_SUCCESS;
}
static NTSTATUS __stdcall createSynchObject2(D3DKMT_CREATESYNCHRONIZATIONOBJECT2 *pData) {
if (pData == nullptr) {
return STATUS_INVALID_PARAMETER;
}
EXPECT_NE(NULL, pData->hDevice);
EXPECT_EQ(D3DDDI_CPU_NOTIFICATION, pData->Info.Type);
EXPECT_NE(nullptr, pData->Info.CPUNotification.Event);
pData->hSyncObject = getHandle()++;
return STATUS_SUCCESS;
}
};
CreateSyncObjectMock::reset();
wddm->init();
gdi->createSynchronizationObject.mFunc = CreateSyncObjectMock::createSynchObject;
gdi->createSynchronizationObject2.mFunc = CreateSyncObjectMock::createSynchObject2;
auto ret = setupArbSyncObject(sharing, osInterface, syncInfo);
EXPECT_TRUE(ret);
EXPECT_EQ(1U, syncInfo.serverSynchronizationObject);
EXPECT_EQ(2U, syncInfo.clientSynchronizationObject);
EXPECT_EQ(3U, syncInfo.submissionSynchronizationObject);
EXPECT_EQ(sharing.GLContextHandle, syncInfo.hContextToBlock);
EXPECT_NE(nullptr, syncInfo.event);
EXPECT_NE(nullptr, syncInfo.eventName);
EXPECT_NE(nullptr, syncInfo.submissionEvent);
EXPECT_NE(nullptr, syncInfo.submissionEventName);
EXPECT_FALSE(syncInfo.waitCalled);
cleanupArbSyncObject(osInterface, &syncInfo);
}
TEST_F(GlArbSyncEventOsTest, GivenNewGlSyncInfoWhenCreateSynchronizationObjectFailsThenSetupArbSyncObjectFails) {
struct CreateSyncObjectMock {
static int &getHandle() {
static int handle = 1;
return handle;
}
static int &getFailHandleId() {
static int failHandleId = 0;
return failHandleId;
}
static void reset() {
getHandle() = 1;
getFailHandleId() = 0;
}
static NTSTATUS __stdcall createSynchObject(D3DKMT_CREATESYNCHRONIZATIONOBJECT *pData) {
auto newHandle = getHandle()++;
if (newHandle == getFailHandleId()) {
return STATUS_INVALID_PARAMETER;
}
return STATUS_SUCCESS;
}
static NTSTATUS __stdcall createSynchObject2(D3DKMT_CREATESYNCHRONIZATIONOBJECT2 *pData) {
auto newHandle = getHandle()++;
if (newHandle == getFailHandleId()) {
return STATUS_INVALID_PARAMETER;
}
return STATUS_SUCCESS;
}
};
CreateSyncObjectMock::reset();
wddm->init();
gdi->createSynchronizationObject.mFunc = CreateSyncObjectMock::createSynchObject;
gdi->createSynchronizationObject2.mFunc = CreateSyncObjectMock::createSynchObject2;
CreateSyncObjectMock::getFailHandleId() = CreateSyncObjectMock::getHandle();
int failuresCount = 0;
auto ret = setupArbSyncObject(sharing, osInterface, syncInfo);
while (false == ret) {
++failuresCount;
CreateSyncObjectMock::getHandle() = 1;
++CreateSyncObjectMock::getFailHandleId();
ret = setupArbSyncObject(sharing, osInterface, syncInfo);
}
EXPECT_EQ(3, failuresCount);
cleanupArbSyncObject(osInterface, &syncInfo);
}
TEST_F(GlArbSyncEventOsTest, GivenNewGlSyncInfoWhenCreateEventFailsThenSetupArbSyncObjectFails) {
MockOSInterface mockOsInterface;
MockOSInterfaceImpl *mockOsInterfaceImpl = static_cast<MockOSInterfaceImpl *>(mockOsInterface.get());
auto wddm = new WddmMock(*rootDeviceEnvironment.get());
auto gdi = new MockGdi();
wddm->resetGdi(gdi);
wddm->init();
mockOsInterface.get()->setWddm(wddm);
mockOsInterfaceImpl->failEventNum = mockOsInterfaceImpl->eventNum;
int failuresCount = 0;
auto ret = setupArbSyncObject(sharing, mockOsInterface, syncInfo);
while (false == ret) {
++failuresCount;
mockOsInterfaceImpl->eventNum = 1;
++mockOsInterfaceImpl->failEventNum;
ret = setupArbSyncObject(sharing, mockOsInterface, syncInfo);
}
EXPECT_EQ(2, failuresCount);
cleanupArbSyncObject(mockOsInterface, &syncInfo);
}
TEST_F(GlArbSyncEventOsTest, GivenInvalidGlSyncInfoWhenCleanupArbSyncObjectIsCalledThenDestructorsOfSyncOrEventsAreNotInvoked) {
struct DestroySyncObjectMock {
static NTSTATUS __stdcall destroySynchObject(_In_ CONST D3DKMT_DESTROYSYNCHRONIZATIONOBJECT *sync) {
EXPECT_FALSE(true);
return STATUS_INVALID_PARAMETER;
}
};
auto wddm = new WddmMock(*rootDeviceEnvironment.get());
auto gdi = new MockGdi();
wddm->resetGdi(gdi);
wddm->init();
MockOSInterface mockOsInterface;
MockOSInterfaceImpl *mockOsInterfaceImpl = static_cast<MockOSInterfaceImpl *>(mockOsInterface.get());
mockOsInterface.get()->setWddm(wddm);
gdi->destroySynchronizationObject = DestroySyncObjectMock::destroySynchObject;
cleanupArbSyncObject(mockOsInterface, nullptr);
EXPECT_EQ(0, mockOsInterfaceImpl->closedEventsCount);
}
TEST_F(GlArbSyncEventOsTest, GivenValidGlSyncInfoWhenCleanupArbSyncObjectIsCalledThenProperCountOfDestructorsOfSyncAndEventsIsNotInvoked) {
struct CreateDestroySyncObjectMock {
static int &getDestroyCounter() {
static int counter = 0;
return counter;
}
static NTSTATUS __stdcall destroySynchObject(_In_ CONST D3DKMT_DESTROYSYNCHRONIZATIONOBJECT *sync) {
++getDestroyCounter();
return STATUS_SUCCESS;
}
static void reset() {
getDestroyCounter() = 0;
}
};
auto wddm = new WddmMock(*rootDeviceEnvironment.get());
auto gdi = new MockGdi();
wddm->resetGdi(gdi);
wddm->init();
MockOSInterface mockOsInterface;
MockOSInterfaceImpl *mockOsInterfaceImpl = static_cast<MockOSInterfaceImpl *>(mockOsInterface.get());
mockOsInterface.get()->setWddm(wddm);
CreateDestroySyncObjectMock::reset();
gdi->destroySynchronizationObject = CreateDestroySyncObjectMock::destroySynchObject;
auto ret = setupArbSyncObject(sharing, mockOsInterface, syncInfo);
EXPECT_TRUE(ret);
syncInfo.serverSynchronizationObject = 0x5cU;
syncInfo.clientSynchronizationObject = 0x7cU;
syncInfo.submissionSynchronizationObject = 0x13cU;
cleanupArbSyncObject(mockOsInterface, &syncInfo);
EXPECT_EQ(2, mockOsInterfaceImpl->closedEventsCount);
EXPECT_EQ(3, CreateDestroySyncObjectMock::getDestroyCounter());
}
TEST_F(GlArbSyncEventOsTest, GivenCallToSignalArbSyncObjectWhenSignalSynchronizationObjectForServerClientSyncFailsThenSubmissionSyncDoesNotGetSignalled) {
struct FailSignalSyncObjectMock {
static NTSTATUS __stdcall signal(_In_ CONST D3DKMT_SIGNALSYNCHRONIZATIONOBJECT *obj) {
EXPECT_NE(nullptr, obj);
if (obj == nullptr) {
return STATUS_INVALID_PARAMETER;
}
EXPECT_EQ(2, obj->ObjectCount);
EXPECT_EQ(getExpectedSynchHandle0(), obj->ObjectHandleArray[0]);
EXPECT_EQ(getExpectedSynchHandle1(), obj->ObjectHandleArray[1]);
EXPECT_EQ(0, obj->Flags.SignalAtSubmission);
EXPECT_EQ(getExpectedContextHandle(), obj->hContext);
return STATUS_INVALID_PARAMETER;
}
static D3DKMT_HANDLE &getExpectedSynchHandle0() {
static D3DKMT_HANDLE handle = INVALID_HANDLE;
return handle;
}
static D3DKMT_HANDLE &getExpectedSynchHandle1() {
static D3DKMT_HANDLE handle = INVALID_HANDLE;
return handle;
}
static D3DKMT_HANDLE &getExpectedContextHandle() {
static D3DKMT_HANDLE handle = INVALID_HANDLE;
return handle;
}
static void reset() {
getExpectedSynchHandle0() = INVALID_HANDLE;
getExpectedSynchHandle1() = INVALID_HANDLE;
getExpectedContextHandle() = INVALID_HANDLE;
}
};
FailSignalSyncObjectMock::reset();
auto preemptionMode = PreemptionHelper::getDefaultPreemptionMode(*platformDevices[0]);
wddm->init();
OsContextWin osContext(*osInterface.get()->getWddm(), 0u, 1, HwHelper::get(platformDevices[0]->platform.eRenderCoreFamily).getGpgpuEngineInstances()[0], preemptionMode, false);
CL_GL_SYNC_INFO syncInfo = {};
syncInfo.serverSynchronizationObject = 0x5cU;
syncInfo.clientSynchronizationObject = 0x6cU;
gdi->signalSynchronizationObject.mFunc = FailSignalSyncObjectMock::signal;
FailSignalSyncObjectMock::getExpectedContextHandle() = osContext.getWddmContextHandle();
FailSignalSyncObjectMock::getExpectedSynchHandle0() = syncInfo.serverSynchronizationObject;
FailSignalSyncObjectMock::getExpectedSynchHandle1() = syncInfo.clientSynchronizationObject;
signalArbSyncObject(osContext, syncInfo);
}
TEST_F(GlArbSyncEventOsTest, GivenCallToSignalArbSyncObjectWhenSignalSynchronizationObjectForServerClientSyncSucceedsThenSubmissionSyncGetsSignalledAsWell) {
struct FailSignalSyncObjectMock {
static NTSTATUS __stdcall signal(_In_ CONST D3DKMT_SIGNALSYNCHRONIZATIONOBJECT *obj) {
EXPECT_NE(nullptr, obj);
if (obj == nullptr) {
return STATUS_INVALID_PARAMETER;
}
// validating only second call to signal
if (getCounter()++ != 1) {
return STATUS_SUCCESS;
}
EXPECT_EQ(1, obj->ObjectCount);
EXPECT_EQ(getExpectedSynchHandle0(), obj->ObjectHandleArray[0]);
EXPECT_EQ(1, obj->Flags.SignalAtSubmission);
EXPECT_EQ(getExpectedContextHandle(), obj->hContext);
return STATUS_SUCCESS;
}
static D3DKMT_HANDLE &getExpectedSynchHandle0() {
static D3DKMT_HANDLE handle = INVALID_HANDLE;
return handle;
}
static int &getCounter() {
static int counter = 0;
return counter;
}
static D3DKMT_HANDLE &getExpectedContextHandle() {
static D3DKMT_HANDLE handle = INVALID_HANDLE;
return handle;
}
static void reset() {
getExpectedSynchHandle0() = INVALID_HANDLE;
getCounter() = 0;
getExpectedContextHandle() = INVALID_HANDLE;
}
};
FailSignalSyncObjectMock::reset();
auto preemptionMode = PreemptionHelper::getDefaultPreemptionMode(*platformDevices[0]);
wddm->init();
OsContextWin osContext(*osInterface.get()->getWddm(), 0u, 1, HwHelper::get(platformDevices[0]->platform.eRenderCoreFamily).getGpgpuEngineInstances()[0], preemptionMode, false);
CL_GL_SYNC_INFO syncInfo = {};
syncInfo.submissionSynchronizationObject = 0x7cU;
gdi->signalSynchronizationObject.mFunc = FailSignalSyncObjectMock::signal;
FailSignalSyncObjectMock::getExpectedContextHandle() = osContext.getWddmContextHandle();
FailSignalSyncObjectMock::getExpectedSynchHandle0() = syncInfo.submissionSynchronizationObject;
signalArbSyncObject(osContext, syncInfo);
}
TEST_F(GlArbSyncEventOsTest, GivenCallToServerWaitForArbSyncObjectWhenWaitForSynchronizationObjectFailsThenWaitFlagDoesNotGetSet) {
struct FailWaitSyncObjectMock {
static NTSTATUS __stdcall waitForSynchObject(_In_ CONST_FROM_WDK_10_0_18328_0 D3DKMT_WAITFORSYNCHRONIZATIONOBJECT *waitData) {
EXPECT_NE(nullptr, waitData);
if (waitData == nullptr) {
return STATUS_INVALID_PARAMETER;
}
EXPECT_EQ(1, waitData->ObjectCount);
EXPECT_EQ(getExpectedSynchHandle0(), waitData->ObjectHandleArray[0]);
EXPECT_EQ(getExpectedContextHandle(), waitData->hContext);
return STATUS_INVALID_PARAMETER;
}
static D3DKMT_HANDLE &getExpectedSynchHandle0() {
static D3DKMT_HANDLE handle = INVALID_HANDLE;
return handle;
}
static D3DKMT_HANDLE &getExpectedContextHandle() {
static D3DKMT_HANDLE handle = INVALID_HANDLE;
return handle;
}
static void reset() {
getExpectedSynchHandle0() = INVALID_HANDLE;
getExpectedContextHandle() = INVALID_HANDLE;
}
};
FailWaitSyncObjectMock::reset();
CL_GL_SYNC_INFO syncInfo = {};
syncInfo.hContextToBlock = 0x4cU;
FailWaitSyncObjectMock::getExpectedSynchHandle0() = syncInfo.serverSynchronizationObject;
FailWaitSyncObjectMock::getExpectedContextHandle() = syncInfo.hContextToBlock;
gdi->waitForSynchronizationObject.mFunc = FailWaitSyncObjectMock::waitForSynchObject;
EXPECT_FALSE(syncInfo.waitCalled);
serverWaitForArbSyncObject(osInterface, syncInfo);
EXPECT_FALSE(syncInfo.waitCalled);
}
TEST_F(GlArbSyncEventOsTest, GivenCallToServerWaitForArbSyncObjectWhenWaitForSynchronizationObjectSucceedsThenWaitFlagGetsSet) {
CL_GL_SYNC_INFO syncInfo = {};
syncInfo.serverSynchronizationObject = 0x7cU;
EXPECT_FALSE(syncInfo.waitCalled);
serverWaitForArbSyncObject(osInterface, syncInfo);
EXPECT_TRUE(syncInfo.waitCalled);
}

View File

@ -0,0 +1,123 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "os_interface/windows/hw_info_config_win_tests.h"
#include "core/execution_environment/root_device_environment.h"
#include "core/helpers/hw_helper.h"
#include "core/os_interface/windows/os_interface.h"
#include "core/os_interface/windows/wddm/wddm.h"
#include "core/unit_tests/helpers/debug_manager_state_restore.h"
#include "test.h"
#include "instrumentation.h"
#include "mocks/mock_execution_environment.h"
namespace NEO {
template <>
uint64_t HwInfoConfigHw<IGFX_UNKNOWN>::getHostMemCapabilities() {
return 0;
}
template <>
uint64_t HwInfoConfigHw<IGFX_UNKNOWN>::getDeviceMemCapabilities() {
return 0;
}
template <>
uint64_t HwInfoConfigHw<IGFX_UNKNOWN>::getSingleDeviceSharedMemCapabilities() {
return 0;
}
template <>
uint64_t HwInfoConfigHw<IGFX_UNKNOWN>::getCrossDeviceSharedMemCapabilities() {
return 0;
}
template <>
uint64_t HwInfoConfigHw<IGFX_UNKNOWN>::getSharedSystemMemCapabilities() {
return 0;
}
template <>
int HwInfoConfigHw<IGFX_UNKNOWN>::configureHardwareCustom(HardwareInfo *hwInfo, OSInterface *osIface) {
return 0;
}
template <>
void HwInfoConfigHw<IGFX_UNKNOWN>::adjustPlatformForProductFamily(HardwareInfo *hwInfo) {
}
HwInfoConfigTestWindows::HwInfoConfigTestWindows() {
this->executionEnvironment = std::make_unique<MockExecutionEnvironment>();
this->rootDeviceEnvironment = std::make_unique<RootDeviceEnvironment>(*executionEnvironment);
}
HwInfoConfigTestWindows::~HwInfoConfigTestWindows() {
}
void HwInfoConfigTestWindows::SetUp() {
HwInfoConfigTest::SetUp();
osInterface.reset(new OSInterface());
std::unique_ptr<Wddm> wddm(Wddm::createWddm(nullptr, *rootDeviceEnvironment));
wddm->init();
outHwInfo = *executionEnvironment->getHardwareInfo();
}
void HwInfoConfigTestWindows::TearDown() {
HwInfoConfigTest::TearDown();
}
TEST_F(HwInfoConfigTestWindows, givenCorrectParametersWhenConfiguringHwInfoThenReturnSuccess) {
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface.get());
EXPECT_EQ(0, ret);
}
TEST_F(HwInfoConfigTestWindows, givenCorrectParametersWhenConfiguringHwInfoThenSetFtrSvmCorrectly) {
auto ftrSvm = outHwInfo.featureTable.ftrSVM;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface.get());
ASSERT_EQ(0, ret);
EXPECT_EQ(outHwInfo.capabilityTable.ftrSvm, ftrSvm);
}
TEST_F(HwInfoConfigTestWindows, givenInstrumentationForHardwareIsEnabledOrDisabledWhenConfiguringHwInfoThenOverrideItUsingHaveInstrumentation) {
int ret;
outHwInfo.capabilityTable.instrumentationEnabled = false;
ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface.get());
ASSERT_EQ(0, ret);
EXPECT_FALSE(outHwInfo.capabilityTable.instrumentationEnabled);
outHwInfo.capabilityTable.instrumentationEnabled = true;
ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface.get());
ASSERT_EQ(0, ret);
EXPECT_TRUE(outHwInfo.capabilityTable.instrumentationEnabled == haveInstrumentation);
}
HWTEST_F(HwInfoConfigTestWindows, givenFtrIaCoherencyFlagWhenConfiguringHwInfoThenSetCoherencySupportCorrectly) {
HardwareInfo initialHwInfo = **platformDevices;
auto &hwHelper = HwHelper::get(initialHwInfo.platform.eRenderCoreFamily);
auto hwInfoConfig = HwInfoConfig::get(initialHwInfo.platform.eProductFamily);
bool initialCoherencyStatus = false;
hwHelper.setCapabilityCoherencyFlag(&outHwInfo, initialCoherencyStatus);
initialHwInfo.featureTable.ftrL3IACoherency = false;
hwInfoConfig->configureHwInfo(&initialHwInfo, &outHwInfo, osInterface.get());
EXPECT_FALSE(outHwInfo.capabilityTable.ftrSupportsCoherency);
initialHwInfo.featureTable.ftrL3IACoherency = true;
hwInfoConfig->configureHwInfo(&initialHwInfo, &outHwInfo, osInterface.get());
EXPECT_EQ(initialCoherencyStatus, outHwInfo.capabilityTable.ftrSupportsCoherency);
}
} // namespace NEO

View File

@ -0,0 +1,37 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/os_interface/hw_info_config.h"
#include "os_interface/hw_info_config_tests.h"
#include <memory>
namespace NEO {
struct MockExecutionEnvironment;
struct RootDeviceEnvironment;
struct DummyHwConfig : HwInfoConfigHw<IGFX_UNKNOWN> {
};
struct HwInfoConfigTestWindows : public HwInfoConfigTest {
HwInfoConfigTestWindows();
~HwInfoConfigTestWindows();
void SetUp() override;
void TearDown() override;
std::unique_ptr<OSInterface> osInterface;
DummyHwConfig hwConfig;
std::unique_ptr<MockExecutionEnvironment> executionEnvironment;
std::unique_ptr<RootDeviceEnvironment> rootDeviceEnvironment;
};
} // namespace NEO

View File

@ -0,0 +1,19 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "os_interface/windows/mock_environment_variables.h"
#include "opencl/source/os_interface/windows/environment_variables.h"
extern uint32_t (*getEnvironmentVariableMock)(const char *name, char *outBuffer, uint32_t outBufferSize) = nullptr;
uint32_t getEnvironmentVariable(const char *name, char *outBuffer, uint32_t outBufferSize) {
if (getEnvironmentVariableMock == nullptr) {
return 0;
}
return getEnvironmentVariableMock(name, outBuffer, outBufferSize);
}

View File

@ -0,0 +1,10 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include <cstdint>
extern uint32_t (*getEnvironmentVariableMock)(const char *name, char *outBuffer, uint32_t outBufferSize);

View File

@ -0,0 +1,137 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/os_interface/windows/kmdaf_listener.h"
namespace NEO {
struct KmDafListenerMock : public KmDafListener {
inline void notifyLock(bool ftrKmdDaf, D3DKMT_HANDLE hAdapter, D3DKMT_HANDLE hDevice, const D3DKMT_HANDLE hAllocation, D3DDDICB_LOCKFLAGS *pLockFlags, PFND3DKMT_ESCAPE pfnEscape) override {
notifyLockParametrization.ftrKmdDaf = ftrKmdDaf;
notifyLockParametrization.hAdapter = hAdapter;
notifyLockParametrization.hDevice = hDevice;
notifyLockParametrization.hAllocation = hAllocation;
notifyLockParametrization.pLockFlags = pLockFlags;
notifyLockParametrization.pfnEscape = pfnEscape;
}
inline void notifyUnlock(bool ftrKmdDaf, D3DKMT_HANDLE hAdapter, D3DKMT_HANDLE hDevice, const D3DKMT_HANDLE *phAllocation, ULONG allocations, PFND3DKMT_ESCAPE pfnEscape) override {
notifyUnlockParametrization.ftrKmdDaf = ftrKmdDaf;
notifyUnlockParametrization.hAdapter = hAdapter;
notifyUnlockParametrization.hDevice = hDevice;
notifyUnlockParametrization.phAllocation = phAllocation;
notifyUnlockParametrization.allocations = allocations;
notifyUnlockParametrization.pfnEscape = pfnEscape;
}
inline void notifyMapGpuVA(bool ftrKmdDaf, D3DKMT_HANDLE hAdapter, D3DKMT_HANDLE hDevice, const D3DKMT_HANDLE hAllocation, D3DGPU_VIRTUAL_ADDRESS GpuVirtualAddress, PFND3DKMT_ESCAPE pfnEscape) override {
notifyMapGpuVAParametrization.ftrKmdDaf = ftrKmdDaf;
notifyMapGpuVAParametrization.hAdapter = hAdapter;
notifyMapGpuVAParametrization.hDevice = hDevice;
notifyMapGpuVAParametrization.hAllocation = hAllocation;
notifyMapGpuVAParametrization.GpuVirtualAddress = GpuVirtualAddress;
notifyMapGpuVAParametrization.pfnEscape = pfnEscape;
}
inline void notifyUnmapGpuVA(bool ftrKmdDaf, D3DKMT_HANDLE hAdapter, D3DKMT_HANDLE hDevice, D3DGPU_VIRTUAL_ADDRESS GpuVirtualAddress, PFND3DKMT_ESCAPE pfnEscape) override {
notifyUnmapGpuVAParametrization.ftrKmdDaf = ftrKmdDaf;
notifyUnmapGpuVAParametrization.hAdapter = hAdapter;
notifyUnmapGpuVAParametrization.hDevice = hDevice;
notifyUnmapGpuVAParametrization.GpuVirtualAddress = GpuVirtualAddress;
notifyUnmapGpuVAParametrization.pfnEscape = pfnEscape;
}
inline void notifyMakeResident(bool ftrKmdDaf, D3DKMT_HANDLE hAdapter, D3DKMT_HANDLE hDevice, const D3DKMT_HANDLE *phAllocation, ULONG allocations, PFND3DKMT_ESCAPE pfnEscape) override {
notifyMakeResidentParametrization.ftrKmdDaf = ftrKmdDaf;
notifyMakeResidentParametrization.hAdapter = hAdapter;
notifyMakeResidentParametrization.hDevice = hDevice;
notifyMakeResidentParametrization.phAllocation = phAllocation;
notifyMakeResidentParametrization.allocations = allocations;
notifyMakeResidentParametrization.pfnEscape = pfnEscape;
}
inline void notifyEvict(bool ftrKmdDaf, D3DKMT_HANDLE hAdapter, D3DKMT_HANDLE hDevice, const D3DKMT_HANDLE *phAllocation, ULONG allocations, PFND3DKMT_ESCAPE pfnEscape) override {
notifyEvictParametrization.ftrKmdDaf = ftrKmdDaf;
notifyEvictParametrization.hAdapter = hAdapter;
notifyEvictParametrization.hDevice = hDevice;
notifyEvictParametrization.phAllocation = phAllocation;
notifyEvictParametrization.allocations = allocations;
notifyEvictParametrization.pfnEscape = pfnEscape;
}
inline void notifyWriteTarget(bool ftrKmdDaf, D3DKMT_HANDLE hAdapter, D3DKMT_HANDLE hDevice, const D3DKMT_HANDLE hAllocation, PFND3DKMT_ESCAPE pfnEscape) override {
notifyWriteTargetParametrization.ftrKmdDaf = ftrKmdDaf;
notifyWriteTargetParametrization.hAdapter = hAdapter;
notifyWriteTargetParametrization.hDevice = hDevice;
notifyWriteTargetParametrization.hAllocation = hAllocation;
notifyWriteTargetParametrization.pfnEscape = pfnEscape;
}
struct NotifyLockParametrization {
bool ftrKmdDaf = false;
D3DKMT_HANDLE hAdapter = 0;
D3DKMT_HANDLE hDevice = 0;
D3DKMT_HANDLE hAllocation = 0;
D3DDDICB_LOCKFLAGS *pLockFlags = nullptr;
PFND3DKMT_ESCAPE pfnEscape = nullptr;
} notifyLockParametrization;
struct NotifyUnlockParametrization {
bool ftrKmdDaf = 0;
D3DKMT_HANDLE hAdapter = 0;
D3DKMT_HANDLE hDevice = 0;
const D3DKMT_HANDLE *phAllocation = nullptr;
ULONG allocations = 0;
PFND3DKMT_ESCAPE pfnEscape = nullptr;
} notifyUnlockParametrization;
struct NotifyMapGpuVAParametrization {
bool ftrKmdDaf = false;
D3DKMT_HANDLE hAdapter = 0;
D3DKMT_HANDLE hDevice = 0;
D3DKMT_HANDLE hAllocation = 0;
D3DGPU_VIRTUAL_ADDRESS GpuVirtualAddress = 0;
PFND3DKMT_ESCAPE pfnEscape = nullptr;
} notifyMapGpuVAParametrization;
struct NotifyUnmapGpuVAParametrization {
bool ftrKmdDaf = false;
D3DKMT_HANDLE hAdapter = 0;
D3DKMT_HANDLE hDevice = 0;
D3DGPU_VIRTUAL_ADDRESS GpuVirtualAddress = 0;
PFND3DKMT_ESCAPE pfnEscape = nullptr;
} notifyUnmapGpuVAParametrization;
struct NotifyMakeResidentParametrization {
bool ftrKmdDaf = 0;
D3DKMT_HANDLE hAdapter = 0;
D3DKMT_HANDLE hDevice = 0;
const D3DKMT_HANDLE *phAllocation = nullptr;
ULONG allocations = 0;
PFND3DKMT_ESCAPE pfnEscape = nullptr;
} notifyMakeResidentParametrization;
struct NotifyEvictParametrization {
bool ftrKmdDaf = 0;
D3DKMT_HANDLE hAdapter = 0;
D3DKMT_HANDLE hDevice = 0;
const D3DKMT_HANDLE *phAllocation = nullptr;
ULONG allocations = 0;
PFND3DKMT_ESCAPE pfnEscape = nullptr;
} notifyEvictParametrization;
struct NotifyWriteTargetParametrization {
bool ftrKmdDaf = 0;
D3DKMT_HANDLE hAdapter = 0;
D3DKMT_HANDLE hDevice = 0;
D3DKMT_HANDLE hAllocation = 0;
PFND3DKMT_ESCAPE pfnEscape = nullptr;
} notifyWriteTargetParametrization;
};
} // namespace NEO

View File

@ -0,0 +1,24 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/os_interface/windows/os_time_win.h"
namespace NEO {
class MockOSTimeWin : public OSTimeWin {
public:
MockOSTimeWin(OSInterface *osInterface) : OSTimeWin(osInterface){};
void overrideQueryPerformanceCounterFunction(decltype(&QueryPerformanceCounter) function) {
this->QueryPerfomanceCounterFnc = function;
}
void setFrequency(LARGE_INTEGER frequency) {
this->frequency = frequency;
}
};
} // namespace NEO

View File

@ -0,0 +1,66 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "mock_performance_counters_win.h"
#include "core/os_interface/os_interface.h"
#include "core/os_interface/windows/os_interface.h"
#include "core/os_interface/windows/windows_wrapper.h"
#include "mocks/mock_wddm.h"
#include "os_interface/windows/mock_os_time_win.h"
namespace NEO {
///////////////////////////////////////////////////////
// MockPerformanceCounters::create
///////////////////////////////////////////////////////
std::unique_ptr<PerformanceCounters> MockPerformanceCounters::create(Device *device) {
auto performanceCounters = std::unique_ptr<PerformanceCounters>(new MockPerformanceCountersWin(device));
auto metricsLibrary = std::make_unique<MockMetricsLibrary>();
auto metricsLibraryDll = std::make_unique<MockMetricsLibraryDll>();
metricsLibrary->api = std::make_unique<MockMetricsLibraryValidInterface>();
metricsLibrary->osLibrary = std::move(metricsLibraryDll);
performanceCounters->setMetricsLibraryInterface(std::move(metricsLibrary));
return performanceCounters;
}
///////////////////////////////////////////////////////
// MockPerformanceCountersWin::MockPerformanceCountersWin
///////////////////////////////////////////////////////
MockPerformanceCountersWin::MockPerformanceCountersWin(Device *device)
: PerformanceCountersWin() {
}
//////////////////////////////////////////////////////
// PerformanceCountersFixture::createPerfCounters
//////////////////////////////////////////////////////
void PerformanceCountersFixture::createPerfCounters() {
performanceCountersBase = MockPerformanceCounters::create(&device->getDevice());
}
//////////////////////////////////////////////////////
// PerformanceCountersFixture::SetUp
//////////////////////////////////////////////////////
void PerformanceCountersFixture::SetUp() {
device = std::make_unique<MockClDevice>(new MockDevice());
context = std::make_unique<MockContext>(device.get());
queue = std::make_unique<MockCommandQueue>(context.get(), device.get(), &queueProperties);
osInterface = std::unique_ptr<OSInterface>(new OSInterface());
osInterface->get()->setWddm(new WddmMock(*rootDeviceEnvironment));
device->setOSTime(new MockOSTimeWin(osInterface.get()));
}
//////////////////////////////////////////////////////
// PerformanceCountersFixture::TearDown
//////////////////////////////////////////////////////
void PerformanceCountersFixture::TearDown() {
}
} // namespace NEO

View File

@ -0,0 +1,19 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "opencl/source/os_interface/windows/performance_counters_win.h"
#include "os_interface/mock_performance_counters.h"
namespace NEO {
class MockPerformanceCountersWin : public PerformanceCountersWin {
public:
MockPerformanceCountersWin(Device *device);
};
} // namespace NEO

View File

@ -0,0 +1,27 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/windows/windows_wrapper.h"
LSTATUS APIENTRY RegOpenKeyExA(
HKEY hKey,
LPCSTR lpSubKey,
DWORD ulOptions,
REGSAM samDesired,
PHKEY phkResult) {
return ERROR_FILE_NOT_FOUND;
};
LSTATUS APIENTRY RegQueryValueExA(
HKEY hKey,
LPCSTR lpValueName,
LPDWORD lpReserved,
LPDWORD lpType,
LPBYTE lpData,
LPDWORD lpcbData) {
return ERROR_FILE_NOT_FOUND;
};

View File

@ -0,0 +1,25 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/os_interface/windows/wddm_allocation.h"
namespace NEO {
class MockWddmAllocation : public WddmAllocation {
public:
MockWddmAllocation() : WddmAllocation(0, GraphicsAllocation::AllocationType::UNKNOWN, nullptr, 0, nullptr, MemoryPool::MemoryNull), gpuPtr(gpuAddress), handle(handles[0]) {
}
using WddmAllocation::cpuPtr;
using WddmAllocation::memoryPool;
using WddmAllocation::size;
D3DGPU_VIRTUAL_ADDRESS &gpuPtr;
D3DKMT_HANDLE &handle;
};
} // namespace NEO

View File

@ -0,0 +1,60 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/memory_manager/deferred_deleter.h"
#include "core/os_interface/windows/wddm_memory_manager.h"
#include "mocks/mock_host_ptr_manager.h"
#include "mocks/mock_memory_manager.h"
namespace NEO {
class MockWddmMemoryManager : public MemoryManagerCreate<WddmMemoryManager> {
using BaseClass = WddmMemoryManager;
public:
using BaseClass::allocateGraphicsMemory64kb;
using BaseClass::allocateGraphicsMemoryForNonSvmHostPtr;
using BaseClass::allocateGraphicsMemoryInDevicePool;
using BaseClass::allocateGraphicsMemoryWithProperties;
using BaseClass::allocateShareableMemory;
using BaseClass::createGraphicsAllocation;
using BaseClass::createWddmAllocation;
using BaseClass::getWddm;
using BaseClass::gfxPartitions;
using BaseClass::localMemorySupported;
using BaseClass::supportsMultiStorageResources;
using MemoryManagerCreate<WddmMemoryManager>::MemoryManagerCreate;
MockWddmMemoryManager(ExecutionEnvironment &executionEnvironment) : MemoryManagerCreate(false, false, executionEnvironment) {
hostPtrManager.reset(new MockHostPtrManager);
};
void setDeferredDeleter(DeferredDeleter *deleter) {
this->deferredDeleter.reset(deleter);
}
void setForce32bitAllocations(bool newValue) {
this->force32bitAllocations = newValue;
}
bool validateAllocationMock(WddmAllocation *graphicsAllocation) {
return this->validateAllocation(graphicsAllocation);
}
GraphicsAllocation *allocate32BitGraphicsMemory(size_t size, const void *ptr, GraphicsAllocation::AllocationType allocationType) {
bool allocateMemory = ptr == nullptr;
AllocationData allocationData;
MockAllocationProperties properties(allocateMemory, size, allocationType);
getAllocationData(allocationData, properties, ptr, createStorageInfoFromProperties(properties));
return allocate32BitGraphicsMemoryImpl(allocationData);
}
void freeGraphicsMemoryImpl(GraphicsAllocation *gfxAllocation) override {
freeGraphicsMemoryImplCalled++;
BaseClass::freeGraphicsMemoryImpl(gfxAllocation);
}
uint32_t freeGraphicsMemoryImplCalled = 0u;
};
} // namespace NEO

View File

@ -0,0 +1,35 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/os_library.h"
#include "common/gtsysinfo.h"
#include "igfxfmid.h"
namespace Os {
///////////////////////////////////////////////////////////////////////////////
// These options determine the Windows specific behavior for
// the runtime unit tests
///////////////////////////////////////////////////////////////////////////////
const char *frontEndDllName = "";
const char *igcDllName = "";
const char *gdiDllName = "gdi32_mock.dll";
const char *testDllName = "test_dynamic_lib.dll";
const char *metricsLibraryDllName = "";
} // namespace Os
NEO::OsLibrary *setAdapterInfo(const PLATFORM *platform, const GT_SYSTEM_INFO *gtSystemInfo, uint64_t gpuAddressSpace) {
NEO::OsLibrary *mockGdiDll;
mockGdiDll = NEO::OsLibrary::load("gdi32_mock.dll");
typedef void(__stdcall * pfSetAdapterInfo)(const void *, const void *, uint64_t);
pfSetAdapterInfo setAdpaterInfo = reinterpret_cast<pfSetAdapterInfo>(mockGdiDll->getProcAddress("MockSetAdapterInfo"));
setAdpaterInfo(platform, gtSystemInfo, gpuAddressSpace);
return mockGdiDll;
}

View File

@ -0,0 +1,61 @@
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/unit_tests/helpers/debug_manager_state_restore.h"
#include "mocks/mock_wddm.h"
#include "os_interface/windows/wddm_fixture.h"
using namespace NEO;
struct OsContextWinTest : public WddmTestWithMockGdiDll {
void SetUp() override {
WddmTestWithMockGdiDll::SetUp();
preemptionMode = PreemptionHelper::getDefaultPreemptionMode(*platformDevices[0]);
engineType = HwHelper::get(platformDevices[0]->platform.eRenderCoreFamily).getGpgpuEngineInstances()[0];
init();
}
PreemptionMode preemptionMode;
aub_stream::EngineType engineType;
};
TEST_F(OsContextWinTest, givenWddm20WhenCreatingOsContextThenOsContextIsInitialized) {
osContext = std::make_unique<OsContextWin>(*osInterface->get()->getWddm(), 0u, 1, engineType, preemptionMode, false);
EXPECT_TRUE(osContext->isInitialized());
}
TEST_F(OsContextWinTest, givenWddm20WhenCreatingWddmContextFailThenOsContextIsNotInitialized) {
wddm->device = INVALID_HANDLE;
osContext = std::make_unique<OsContextWin>(*osInterface->get()->getWddm(), 0u, 1, engineType, preemptionMode, false);
EXPECT_FALSE(osContext->isInitialized());
}
TEST_F(OsContextWinTest, givenWddm20WhenCreatingWddmMonitorFenceFailThenOsContextIsNotInitialized) {
*getCreateSynchronizationObject2FailCallFcn() = true;
osContext = std::make_unique<OsContextWin>(*osInterface->get()->getWddm(), 0u, 1, engineType, preemptionMode, false);
EXPECT_FALSE(osContext->isInitialized());
}
TEST_F(OsContextWinTest, givenWddm20WhenRegisterTrimCallbackFailThenOsContextIsNotInitialized) {
*getRegisterTrimNotificationFailCallFcn() = true;
osContext = std::make_unique<OsContextWin>(*osInterface->get()->getWddm(), 0u, 1, engineType, preemptionMode, false);
EXPECT_FALSE(osContext->isInitialized());
}
TEST_F(OsContextWinTest, givenWddm20WhenRegisterTrimCallbackIsDisabledThenOsContextIsInitialized) {
DebugManagerStateRestore stateRestore;
DebugManager.flags.DoNotRegisterTrimCallback.set(true);
*getRegisterTrimNotificationFailCallFcn() = true;
osContext = std::make_unique<OsContextWin>(*osInterface->get()->getWddm(), 0u, 1, engineType, preemptionMode, false);
EXPECT_TRUE(osContext->isInitialized());
}

View File

@ -0,0 +1,56 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "os_interface/windows/os_interface_win_tests.h"
#include "core/execution_environment/root_device_environment.h"
#include "core/os_interface/windows/os_context_win.h"
#include "mocks/mock_execution_environment.h"
#include "os_interface/windows/wddm_fixture.h"
TEST_F(OsInterfaceTest, GivenWindowsWhenOsSupportFor64KBpagesIsBeingQueriedThenTrueIsReturned) {
EXPECT_TRUE(OSInterface::are64kbPagesEnabled());
}
TEST_F(OsInterfaceTest, GivenWindowsWhenCreateEentIsCalledThenValidEventHandleIsReturned) {
auto ev = osInterface->get()->createEvent(NULL, TRUE, FALSE, "DUMMY_EVENT_NAME");
EXPECT_NE(nullptr, ev);
auto ret = osInterface->get()->closeHandle(ev);
EXPECT_EQ(TRUE, ret);
}
TEST(OsContextTest, givenWddmWhenCreateOsContextAfterInitWddmThenOsContextIsInitializedTrimCallbackIsRegisteredMemoryOperationsHandlerCreated) {
MockExecutionEnvironment executionEnvironment;
RootDeviceEnvironment rootDeviceEnvironment(executionEnvironment);
auto wddm = new WddmMock(rootDeviceEnvironment);
OSInterface osInterface;
osInterface.get()->setWddm(wddm);
auto preemptionMode = PreemptionHelper::getDefaultPreemptionMode(*platformDevices[0]);
wddm->init();
EXPECT_EQ(0u, wddm->registerTrimCallbackResult.called);
auto osContext = std::make_unique<OsContextWin>(*wddm, 0u, 1, HwHelper::get(platformDevices[0]->platform.eRenderCoreFamily).getGpgpuEngineInstances()[0], preemptionMode, false);
EXPECT_TRUE(osContext->isInitialized());
EXPECT_EQ(osContext->getWddm(), wddm);
EXPECT_EQ(1u, wddm->registerTrimCallbackResult.called);
}
TEST_F(OsInterfaceTest, whenOsInterfaceSetupGmmInputArgsThenProperAdapterBDFIsSet) {
MockExecutionEnvironment executionEnvironment;
RootDeviceEnvironment rootDeviceEnvironment(executionEnvironment);
auto wddm = new WddmMock(rootDeviceEnvironment);
osInterface->get()->setWddm(wddm);
wddm->init();
auto &adapterBDF = wddm->adapterBDF;
adapterBDF.Bus = 0x12;
adapterBDF.Device = 0x34;
adapterBDF.Function = 0x56;
GMM_INIT_IN_ARGS gmmInputArgs = {};
EXPECT_NE(0, memcmp(&adapterBDF, &gmmInputArgs.stAdapterBDF, sizeof(ADAPTER_BDF)));
osInterface->setGmmInputArgs(&gmmInputArgs);
EXPECT_EQ(0, memcmp(&adapterBDF, &gmmInputArgs.stAdapterBDF, sizeof(ADAPTER_BDF)));
}

View File

@ -0,0 +1,29 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/helpers/hw_info.h"
#include "core/os_interface/device_factory.h"
#include "core/os_interface/windows/os_interface.h"
#include "core/os_interface/windows/wddm/wddm.h"
#include "gtest/gtest.h"
using namespace NEO;
class OsInterfaceTest : public ::testing::Test {
public:
void SetUp() override {
osInterface = std::unique_ptr<OSInterface>(new OSInterface());
}
void TearDown() override {
}
std::unique_ptr<OSInterface> osInterface;
};

View File

@ -0,0 +1,84 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/windows/os_library_win.h"
#include "test.h"
#include "gtest/gtest.h"
#include "helpers/variable_backup.h"
#include <memory>
namespace Os {
extern const char *testDllName;
}
using namespace NEO;
class OsLibraryBackup : public Windows::OsLibrary {
using Type = decltype(Windows::OsLibrary::loadLibraryExA);
using BackupType = typename VariableBackup<Type>;
using ModuleNameType = decltype(Windows::OsLibrary::getModuleFileNameA);
using ModuleNameBackupType = typename VariableBackup<ModuleNameType>;
struct Backup {
std::unique_ptr<BackupType> bkp1 = nullptr;
std::unique_ptr<ModuleNameBackupType> bkp2 = nullptr;
};
public:
static std::unique_ptr<Backup> backup(Type newValue, ModuleNameType newModuleName) {
std::unique_ptr<Backup> bkp(new Backup());
bkp->bkp1.reset(new BackupType(&OsLibrary::loadLibraryExA, newValue));
bkp->bkp2.reset(new ModuleNameBackupType(&OsLibrary::getModuleFileNameA, newModuleName));
return bkp;
};
};
bool mockWillFail = true;
void trimFileName(char *buff, size_t length) {
for (size_t l = length; l > 0; l--) {
if (buff[l - 1] == '\\') {
buff[l] = '\0';
break;
}
}
}
DWORD WINAPI GetModuleFileNameAMock(HMODULE hModule, LPSTR lpFilename, DWORD nSize) {
return snprintf(lpFilename, nSize, "z:\\SomeFakeName.dll");
}
HMODULE WINAPI LoadLibraryExAMock(LPCSTR lpFileName, HANDLE hFile, DWORD dwFlags) {
if (mockWillFail)
return NULL;
char fName[MAX_PATH];
auto lenFn = strlen(lpFileName);
strcpy_s(fName, sizeof(fName), lpFileName);
trimFileName(fName, lenFn);
EXPECT_STREQ("z:\\", fName);
return (HMODULE)1;
}
TEST(OSLibraryWinTest, gitOsLibraryWinWhenLoadDependencyFailsThenFallbackToNonDriverStore) {
auto bkp = OsLibraryBackup::backup(LoadLibraryExAMock, GetModuleFileNameAMock);
std::unique_ptr<OsLibrary> library(OsLibrary::load(Os::testDllName));
EXPECT_NE(nullptr, library);
}
TEST(OSLibraryWinTest, gitOsLibraryWinWhenLoadDependencyThenProperPathIsConstructed) {
auto bkp = OsLibraryBackup::backup(LoadLibraryExAMock, GetModuleFileNameAMock);
VariableBackup<bool> bkpM(&mockWillFail, false);
std::unique_ptr<OsLibrary> library(OsLibrary::load(Os::testDllName));
EXPECT_NE(nullptr, library);
}

View File

@ -0,0 +1,108 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/execution_environment/root_device_environment.h"
#include "core/os_interface/windows/os_interface.h"
#include "gtest/gtest.h"
#include "mock_os_time_win.h"
#include "mocks/mock_execution_environment.h"
#include "os_interface/windows/wddm_fixture.h"
#include <memory>
using namespace NEO;
LARGE_INTEGER valueToSet = {0};
BOOL WINAPI QueryPerformanceCounterMock(
_Out_ LARGE_INTEGER *lpPerformanceCount) {
*lpPerformanceCount = valueToSet;
return true;
};
struct OSTimeWinTest : public ::testing::Test {
public:
virtual void SetUp() override {
osTime = std::unique_ptr<MockOSTimeWin>(new MockOSTimeWin(nullptr));
}
virtual void TearDown() override {
}
std::unique_ptr<MockOSTimeWin> osTime;
};
TEST_F(OSTimeWinTest, givenZeroFrequencyWhenGetHostTimerFuncIsCalledThenReturnsZero) {
LARGE_INTEGER frequency;
frequency.QuadPart = 0;
osTime->setFrequency(frequency);
auto retVal = osTime->getHostTimerResolution();
EXPECT_EQ(0, retVal);
}
TEST_F(OSTimeWinTest, givenNonZeroFrequencyWhenGetHostTimerFuncIsCalledThenReturnsNonZero) {
LARGE_INTEGER frequency;
frequency.QuadPart = NSEC_PER_SEC;
osTime->setFrequency(frequency);
auto retVal = osTime->getHostTimerResolution();
EXPECT_EQ(1.0, retVal);
}
TEST_F(OSTimeWinTest, givenOsTimeWinWhenGetCpuRawTimestampIsCalledThenReturnsNonZero) {
auto retVal = osTime->getCpuRawTimestamp();
EXPECT_NE(0ull, retVal);
}
TEST_F(OSTimeWinTest, givenHighValueOfCpuTimestampWhenItIsObtainedThenItHasProperValue) {
osTime->overrideQueryPerformanceCounterFunction(QueryPerformanceCounterMock);
LARGE_INTEGER frequency = {0};
frequency.QuadPart = 190457;
osTime->setFrequency(frequency);
valueToSet.QuadPart = 700894514854;
uint64_t timeStamp = 0;
uint64_t expectedTimestamp = static_cast<uint64_t>((static_cast<double>(valueToSet.QuadPart) * static_cast<double>(NSEC_PER_SEC) / static_cast<double>(frequency.QuadPart)));
osTime->getCpuTime(&timeStamp);
EXPECT_EQ(expectedTimestamp, timeStamp);
}
TEST(OSTimeWinTests, givenNoOSInterfaceWhenGetCpuTimeThenReturnsSuccess) {
uint64_t time = 0;
auto osTime(OSTime::create(nullptr));
auto error = osTime->getCpuTime(&time);
EXPECT_TRUE(error);
EXPECT_NE(0, time);
}
TEST(OSTimeWinTests, givenNoOSInterfaceWhenGetCpuGpuTimeThenReturnsError) {
TimeStampData CPUGPUTime = {0};
auto osTime(OSTime::create(nullptr));
auto success = osTime->getCpuGpuTime(&CPUGPUTime);
EXPECT_FALSE(success);
EXPECT_EQ(0, CPUGPUTime.CPUTimeinNS);
EXPECT_EQ(0, CPUGPUTime.GPUTimeStamp);
}
TEST(OSTimeWinTests, givenOSInterfaceWhenGetCpuGpuTimeThenReturnsSuccess) {
MockExecutionEnvironment executionEnvironment;
RootDeviceEnvironment rootDeviceEnvironment(executionEnvironment);
auto wddm = new WddmMock(rootDeviceEnvironment);
TimeStampData CPUGPUTime01 = {0};
TimeStampData CPUGPUTime02 = {0};
std::unique_ptr<OSInterface> osInterface(new OSInterface());
osInterface->get()->setWddm(wddm);
auto osTime = OSTime::create(osInterface.get());
auto success = osTime->getCpuGpuTime(&CPUGPUTime01);
EXPECT_TRUE(success);
EXPECT_NE(0, CPUGPUTime01.CPUTimeinNS);
EXPECT_NE(0, CPUGPUTime01.GPUTimeStamp);
success = osTime->getCpuGpuTime(&CPUGPUTime02);
EXPECT_TRUE(success);
EXPECT_NE(0, CPUGPUTime02.CPUTimeinNS);
EXPECT_NE(0, CPUGPUTime02.GPUTimeStamp);
EXPECT_GT(CPUGPUTime02.GPUTimeStamp, CPUGPUTime01.GPUTimeStamp);
EXPECT_GT(CPUGPUTime02.CPUTimeinNS, CPUGPUTime01.CPUTimeinNS);
}

View File

@ -0,0 +1,23 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "gtest/gtest.h"
#include "os_interface/windows/mock_performance_counters_win.h"
using namespace NEO;
struct PerformanceCountersWinTest : public PerformanceCountersFixture,
public ::testing::Test {
public:
void SetUp() override {
PerformanceCountersFixture::SetUp();
}
void TearDown() override {
PerformanceCountersFixture::TearDown();
}
};

View File

@ -0,0 +1,63 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "os_interface/windows/registry_reader_tests.h"
#include "test.h"
using namespace NEO;
using RegistryReaderTest = ::testing::Test;
TEST_F(RegistryReaderTest, givenRegistryReaderWhenItIsCreatedWithUserScopeSetToFalseThenItsHkeyTypeIsInitializedToHkeyLocalMachine) {
bool userScope = false;
TestedRegistryReader registryReader(userScope);
EXPECT_EQ(HKEY_LOCAL_MACHINE, registryReader.getHkeyType());
}
TEST_F(RegistryReaderTest, givenRegistryReaderWhenItIsCreatedWithUserScopeSetToTrueThenItsHkeyTypeIsInitializedHkeyCurrentUser) {
bool userScope = true;
TestedRegistryReader registryReader(userScope);
EXPECT_EQ(HKEY_CURRENT_USER, registryReader.getHkeyType());
}
TEST_F(RegistryReaderTest, givenRegistryReaderWhenCallAppSpecificLocationThenReturnCurrentProcessName) {
char buff[MAX_PATH];
GetModuleFileNameA(nullptr, buff, MAX_PATH);
TestedRegistryReader registryReader(false);
const char *ret = registryReader.appSpecificLocation("cl_cache_dir");
EXPECT_STREQ(buff, ret);
}
TEST_F(RegistryReaderTest, givenRegistryReaderWhenRegKeyNotExistThenReturnDefaultValue) {
std::string regKey = "notExistPath";
std::string value = "defaultValue";
TestedRegistryReader registryReader(regKey);
EXPECT_EQ(value, registryReader.getSetting("", value));
}
TEST_F(RegistryReaderTest, givenRegistryReaderWhenItIsCreatedWithRegKeySpecifiedThenRegKeyIsInitializedAccordingly) {
std::string regKey = "Software\\Intel\\IGFX\\OCL\\regKey";
TestedRegistryReader registryReader(regKey);
EXPECT_STREQ(regKey.c_str(), registryReader.getRegKey());
}
TEST_F(RegistryReaderTest, givenRegistryReaderWhenEnvironmentVariableExistsThenReturnCorrectValue) {
char *envVar = "TestedEnvironmentVariable";
std::string value = "defaultValue";
TestedRegistryReader registryReader("");
EXPECT_EQ("TestedEnvironmentVariableValue", registryReader.getSetting(envVar, value));
}
TEST_F(RegistryReaderTest, givenRegistryReaderWhenEnvironmentIntVariableExistsThenReturnCorrectValue) {
char *envVar = "TestedEnvironmentIntVariable";
int32_t value = -1;
TestedRegistryReader registryReader("");
EXPECT_EQ(1234, registryReader.getSetting(envVar, value));
}

View File

@ -0,0 +1,34 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/windows/debug_registry_reader.h"
#include "opencl/source/os_interface/ocl_reg_path.h"
namespace NEO {
class TestedRegistryReader : public RegistryReader {
public:
TestedRegistryReader(bool userScope) : RegistryReader(userScope, oclRegPath){};
TestedRegistryReader(std::string regKey) : RegistryReader(false, regKey){};
HKEY getHkeyType() const {
return igdrclHkeyType;
}
using RegistryReader::getSetting;
char *getenv(const char *envVar) override {
if (strcmp(envVar, "TestedEnvironmentVariable") == 0) {
return "TestedEnvironmentVariableValue";
} else if (strcmp(envVar, "TestedEnvironmentIntVariable") == 0) {
return "1234";
} else {
return nullptr;
}
}
const char *getRegKey() const {
return registryReadRootKey.c_str();
}
};
} // namespace NEO

View File

@ -0,0 +1,9 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
extern "C" __declspec(dllexport) void selfDynamicLibraryFunc() {
}

View File

@ -0,0 +1,50 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "sys_calls.h"
namespace NEO {
namespace SysCalls {
constexpr uintptr_t dummyHandle = static_cast<uintptr_t>(0x7);
BOOL systemPowerStatusRetVal = 1;
BYTE systemPowerStatusACLineStatusOverride = 1;
HMODULE handleValue = reinterpret_cast<HMODULE>(dummyHandle);
const wchar_t *igdrclFilePath = L"";
HANDLE createEvent(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName) {
return reinterpret_cast<HANDLE>(dummyHandle);
}
BOOL closeHandle(HANDLE hObject) {
return (reinterpret_cast<HANDLE>(dummyHandle) == hObject) ? TRUE : FALSE;
}
BOOL getSystemPowerStatus(LPSYSTEM_POWER_STATUS systemPowerStatusPtr) {
systemPowerStatusPtr->ACLineStatus = systemPowerStatusACLineStatusOverride;
return systemPowerStatusRetVal;
}
BOOL getModuleHandle(DWORD dwFlags, LPCWSTR lpModuleName, HMODULE *phModule) {
constexpr auto expectedFlags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT;
if (dwFlags != expectedFlags) {
return FALSE;
}
*phModule = handleValue;
return TRUE;
}
DWORD getModuleFileName(HMODULE hModule, LPWSTR lpFilename, DWORD nSize) {
if (hModule != handleValue) {
return FALSE;
}
lstrcpyW(lpFilename, igdrclFilePath);
return TRUE;
}
} // namespace SysCalls
} // namespace NEO

View File

@ -0,0 +1,27 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "os_interface/windows/ult_dxgi_factory.h"
namespace NEO {
HRESULT WINAPI ULTCreateDXGIFactory(REFIID riid, void **ppFactory) {
UltIDXGIFactory1 *factory = new UltIDXGIFactory1;
*(UltIDXGIFactory1 **)ppFactory = factory;
return S_OK;
}
void WINAPI ULTGetSystemInfo(SYSTEM_INFO *pSystemInfo) {
pSystemInfo->lpMaximumApplicationAddress = is32bit ? (LPVOID)MemoryConstants::max32BitAppAddress : (LPVOID)MemoryConstants::max64BitAppAddress;
}
const wchar_t *UltIDXGIAdapter1::description = L"Intel";
} // namespace NEO

View File

@ -0,0 +1,191 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/memory_manager/memory_constants.h"
#include <cwchar>
#include <dxgi.h>
namespace NEO {
class UltIDXGIAdapter1 : public IDXGIAdapter1 {
public:
const static wchar_t *description;
// IDXGIAdapter1
HRESULT STDMETHODCALLTYPE GetDesc1(
_Out_ DXGI_ADAPTER_DESC1 *pDesc) {
if (pDesc == nullptr) {
return S_FALSE;
}
swprintf(pDesc->Description, 128, description);
pDesc->AdapterLuid.HighPart = 0x1234;
pDesc->DeviceId = 0x1234;
return S_OK;
}
// IDXGIAdapter
HRESULT STDMETHODCALLTYPE EnumOutputs(
UINT Output,
IDXGIOutput **ppOutput) {
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetDesc(
DXGI_ADAPTER_DESC *pDesc) {
return S_OK;
}
HRESULT STDMETHODCALLTYPE CheckInterfaceSupport(
_In_ REFGUID InterfaceName,
_Out_ LARGE_INTEGER *pUMDVersion) {
return S_OK;
}
// IDXGIObject
HRESULT STDMETHODCALLTYPE SetPrivateData(
_In_ REFGUID Name,
UINT DataSize,
const void *pData) {
return S_OK;
}
HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(
_In_ REFGUID Name,
_In_opt_ const IUnknown *pUnknown) {
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetPrivateData(
_In_ REFGUID Name,
_Inout_ UINT *pDataSize,
_Out_writes_bytes_(*pDataSize) void *pData) {
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetParent(
_In_ REFIID riid,
_COM_Outptr_ void **ppParent) {
return S_OK;
}
// IUnknown
HRESULT STDMETHODCALLTYPE QueryInterface(
REFIID riid,
void __RPC_FAR *__RPC_FAR *ppvObject) {
return S_OK;
}
ULONG STDMETHODCALLTYPE AddRef(void) {
return 0;
}
ULONG STDMETHODCALLTYPE Release(void) {
// this must be the last instruction
delete this;
return 0;
}
};
class UltIDXGIFactory1 : public IDXGIFactory1 {
public:
HRESULT STDMETHODCALLTYPE EnumAdapters1(
UINT Adapter,
IDXGIAdapter1 **ppAdapter) {
if (Adapter > 2) {
*(IDXGIAdapter1 **)ppAdapter = nullptr;
return DXGI_ERROR_NOT_FOUND;
}
*(IDXGIAdapter1 **)ppAdapter = new UltIDXGIAdapter1;
return S_OK;
}
BOOL STDMETHODCALLTYPE IsCurrent(void) {
return 0;
}
HRESULT STDMETHODCALLTYPE EnumAdapters(
UINT Adapter,
IDXGIAdapter **ppAdapter) {
return S_OK;
}
HRESULT STDMETHODCALLTYPE MakeWindowAssociation(
HWND WindowHandle,
UINT Flags) {
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetWindowAssociation(
_Out_ HWND *pWindowHandle) {
return S_OK;
}
HRESULT STDMETHODCALLTYPE CreateSwapChain(
_In_ IUnknown *pDevice,
_In_ DXGI_SWAP_CHAIN_DESC *pDesc,
IDXGISwapChain **ppSwapChain) {
return S_OK;
}
HRESULT STDMETHODCALLTYPE CreateSoftwareAdapter(
HMODULE Module,
IDXGIAdapter **ppAdapter) {
return S_OK;
}
// IDXGIObject
HRESULT STDMETHODCALLTYPE SetPrivateData(
_In_ REFGUID Name,
UINT DataSize,
const void *pData) {
return S_OK;
}
HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(
_In_ REFGUID Name,
_In_opt_ const IUnknown *pUnknown) {
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetPrivateData(
_In_ REFGUID Name,
_Inout_ UINT *pDataSize,
_Out_writes_bytes_(*pDataSize) void *pData) {
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetParent(
_In_ REFIID riid,
_COM_Outptr_ void **ppParent) {
return S_OK;
}
// IUnknown
HRESULT STDMETHODCALLTYPE QueryInterface(
REFIID riid,
void __RPC_FAR *__RPC_FAR *ppvObject) {
return S_OK;
}
ULONG STDMETHODCALLTYPE AddRef(void) {
return 0;
}
ULONG STDMETHODCALLTYPE Release(void) {
// this must be the last instruction
delete this;
return 0;
}
};
HRESULT WINAPI ULTCreateDXGIFactory(REFIID riid, void **ppFactory);
void WINAPI ULTGetSystemInfo(SYSTEM_INFO *pSystemInfo);
} // namespace NEO

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,204 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/command_stream/preemption.h"
#include "core/execution_environment/execution_environment.h"
#include "core/helpers/hw_helper.h"
#include "core/memory_manager/memory_constants.h"
#include "core/os_interface/windows/gdi_interface.h"
#include "core/os_interface/windows/os_context_win.h"
#include "core/os_interface/windows/os_interface.h"
#include "core/unit_tests/helpers/debug_manager_state_restore.h"
#include "opencl/source/platform/platform.h"
#include "test.h"
#include "mocks/mock_wddm.h"
#include "mocks/mock_wddm_interface23.h"
#include "os_interface/windows/gdi_dll_fixture.h"
using namespace NEO;
struct Wddm23TestsWithoutWddmInit : public ::testing::Test, GdiDllFixture {
void SetUp() override {
GdiDllFixture::SetUp();
executionEnvironment = platform()->peekExecutionEnvironment();
wddm = static_cast<WddmMock *>(Wddm::createWddm(nullptr, *executionEnvironment->rootDeviceEnvironments[0].get()));
osInterface = std::make_unique<OSInterface>();
osInterface->get()->setWddm(wddm);
wddm->featureTable->ftrWddmHwQueues = true;
wddmMockInterface = new WddmMockInterface23(*wddm);
wddm->wddmInterface.reset(wddmMockInterface);
wddm->registryReader.reset(new RegistryReaderMock());
}
void init() {
auto preemptionMode = PreemptionHelper::getDefaultPreemptionMode(*platformDevices[0]);
wddmMockInterface = static_cast<WddmMockInterface23 *>(wddm->wddmInterface.release());
wddm->init();
wddm->wddmInterface.reset(wddmMockInterface);
osContext = std::make_unique<OsContextWin>(*wddm, 0u, 1, HwHelper::get(platformDevices[0]->platform.eRenderCoreFamily).getGpgpuEngineInstances()[0], preemptionMode, false);
}
void TearDown() override {
GdiDllFixture::TearDown();
}
std::unique_ptr<OSInterface> osInterface;
std::unique_ptr<OsContextWin> osContext;
WddmMock *wddm = nullptr;
WddmMockInterface23 *wddmMockInterface = nullptr;
ExecutionEnvironment *executionEnvironment;
};
struct Wddm23Tests : public Wddm23TestsWithoutWddmInit {
using Wddm23TestsWithoutWddmInit::TearDown;
void SetUp() override {
Wddm23TestsWithoutWddmInit::SetUp();
init();
}
};
TEST_F(Wddm23Tests, whenGetDedicatedVideoMemoryIsCalledThenCorrectValueIsReturned) {
EXPECT_EQ(wddm->dedicatedVideoMemory, wddm->getDedicatedVideoMemory());
}
TEST_F(Wddm23Tests, whenCreateContextIsCalledThenEnableHwQueues) {
EXPECT_TRUE(wddm->wddmInterface->hwQueuesSupported());
EXPECT_EQ(1u, getCreateContextDataFcn()->Flags.HwQueueSupported);
}
TEST_F(Wddm23Tests, givenPreemptionModeWhenCreateHwQueueCalledThenSetGpuTimeoutIfEnabled) {
auto defaultEngine = HwHelper::get(platformDevices[0]->platform.eRenderCoreFamily).getGpgpuEngineInstances()[0];
OsContextWin osContextWithoutPreemption(*osInterface->get()->getWddm(), 0u, 1, defaultEngine, PreemptionMode::Disabled, false);
OsContextWin osContextWithPreemption(*osInterface->get()->getWddm(), 0u, 1, defaultEngine, PreemptionMode::MidBatch, false);
wddm->wddmInterface->createHwQueue(osContextWithoutPreemption);
EXPECT_EQ(0u, getCreateHwQueueDataFcn()->Flags.DisableGpuTimeout);
wddm->wddmInterface->createHwQueue(osContextWithPreemption);
EXPECT_EQ(1u, getCreateHwQueueDataFcn()->Flags.DisableGpuTimeout);
}
TEST_F(Wddm23Tests, whenDestroyHwQueueCalledThenPassExistingHandle) {
D3DKMT_HANDLE hwQueue = 123;
osContext->setHwQueue({hwQueue, 0, nullptr, 0});
wddmMockInterface->destroyHwQueue(osContext->getHwQueue().handle);
EXPECT_EQ(hwQueue, getDestroyHwQueueDataFcn()->hHwQueue);
hwQueue = 0;
osContext->setHwQueue({hwQueue, 0, nullptr, 0});
wddmMockInterface->destroyHwQueue(osContext->getHwQueue().handle);
EXPECT_NE(hwQueue, getDestroyHwQueueDataFcn()->hHwQueue); // gdi not called when 0
}
TEST_F(Wddm23Tests, whenObjectIsDestructedThenDestroyHwQueue) {
D3DKMT_HANDLE hwQueue = 123;
osContext->setHwQueue({hwQueue, 0, nullptr, 0});
osContext.reset();
EXPECT_EQ(hwQueue, getDestroyHwQueueDataFcn()->hHwQueue);
}
TEST_F(Wddm23Tests, givenCmdBufferWhenSubmitCalledThenSetAllRequiredFiledsAndUpdateMonitoredFence) {
uint64_t cmdBufferAddress = 123;
size_t cmdSize = 456;
auto hwQueue = osContext->getHwQueue();
COMMAND_BUFFER_HEADER cmdBufferHeader = {};
EXPECT_EQ(1u, osContext->getResidencyController().getMonitoredFence().currentFenceValue);
EXPECT_EQ(0u, osContext->getResidencyController().getMonitoredFence().lastSubmittedFence);
WddmSubmitArguments submitArgs = {};
submitArgs.contextHandle = osContext->getWddmContextHandle();
submitArgs.hwQueueHandle = hwQueue.handle;
submitArgs.monitorFence = &osContext->getResidencyController().getMonitoredFence();
wddm->submit(cmdBufferAddress, cmdSize, &cmdBufferHeader, submitArgs);
EXPECT_EQ(cmdBufferAddress, getSubmitCommandToHwQueueDataFcn()->CommandBuffer);
EXPECT_EQ(static_cast<UINT>(cmdSize), getSubmitCommandToHwQueueDataFcn()->CommandLength);
EXPECT_EQ(hwQueue.handle, getSubmitCommandToHwQueueDataFcn()->hHwQueue);
EXPECT_EQ(osContext->getResidencyController().getMonitoredFence().lastSubmittedFence, getSubmitCommandToHwQueueDataFcn()->HwQueueProgressFenceId);
EXPECT_EQ(&cmdBufferHeader, getSubmitCommandToHwQueueDataFcn()->pPrivateDriverData);
EXPECT_EQ(static_cast<UINT>(MemoryConstants::pageSize), getSubmitCommandToHwQueueDataFcn()->PrivateDriverDataSize);
EXPECT_EQ(0u, cmdBufferHeader.MonitorFenceVA);
EXPECT_EQ(0u, cmdBufferHeader.MonitorFenceValue);
EXPECT_EQ(2u, osContext->getResidencyController().getMonitoredFence().currentFenceValue);
EXPECT_EQ(1u, osContext->getResidencyController().getMonitoredFence().lastSubmittedFence);
}
TEST_F(Wddm23Tests, whenMonitoredFenceIsCreatedThenSetupAllRequiredFields) {
wddm->wddmInterface->createMonitoredFence(*osContext);
auto hwQueue = osContext->getHwQueue();
EXPECT_EQ(hwQueue.progressFenceCpuVA, osContext->getResidencyController().getMonitoredFence().cpuAddress);
EXPECT_EQ(1u, osContext->getResidencyController().getMonitoredFence().currentFenceValue);
EXPECT_EQ(hwQueue.progressFenceHandle, osContext->getResidencyController().getMonitoredFence().fenceHandle);
EXPECT_EQ(hwQueue.progressFenceGpuVA, osContext->getResidencyController().getMonitoredFence().gpuAddress);
EXPECT_EQ(0u, osContext->getResidencyController().getMonitoredFence().lastSubmittedFence);
}
TEST_F(Wddm23Tests, givenCurrentPendingFenceValueGreaterThanPendingFenceValueWhenSubmitCalledThenCallWaitOnGpu) {
uint64_t cmdBufferAddress = 123;
size_t cmdSize = 456;
COMMAND_BUFFER_HEADER cmdBufferHeader = {};
WddmSubmitArguments submitArgs = {};
submitArgs.contextHandle = osContext->getWddmContextHandle();
submitArgs.hwQueueHandle = osContext->getHwQueue().handle;
submitArgs.monitorFence = &osContext->getResidencyController().getMonitoredFence();
*wddm->pagingFenceAddress = 1;
wddm->currentPagingFenceValue = 1;
wddm->submit(cmdBufferAddress, cmdSize, &cmdBufferHeader, submitArgs);
EXPECT_EQ(0u, wddm->waitOnGPUResult.called);
wddm->currentPagingFenceValue = 2;
wddm->submit(cmdBufferAddress, cmdSize, &cmdBufferHeader, submitArgs);
EXPECT_EQ(1u, wddm->waitOnGPUResult.called);
}
TEST_F(Wddm23Tests, givenDestructionOsContextWinWhenCallingDestroyMonitorFenceThenDoNotCallGdiDestroy) {
osContext.reset(nullptr);
EXPECT_EQ(1u, wddmMockInterface->destroyMonitorFenceCalled);
EXPECT_EQ(0u, getDestroySynchronizationObjectDataFcn()->hSyncObject);
}
TEST_F(Wddm23TestsWithoutWddmInit, whenInitCalledThenInitializeNewGdiDDIsAndCallToCreateHwQueue) {
EXPECT_EQ(nullptr, wddm->getGdi()->createHwQueue.mFunc);
EXPECT_EQ(nullptr, wddm->getGdi()->destroyHwQueue.mFunc);
EXPECT_EQ(nullptr, wddm->getGdi()->submitCommandToHwQueue.mFunc);
init();
EXPECT_EQ(1u, wddmMockInterface->createHwQueueCalled);
EXPECT_NE(nullptr, wddm->getGdi()->createHwQueue.mFunc);
EXPECT_NE(nullptr, wddm->getGdi()->destroyHwQueue.mFunc);
EXPECT_NE(nullptr, wddm->getGdi()->submitCommandToHwQueue.mFunc);
}
TEST_F(Wddm23TestsWithoutWddmInit, whenCreateHwQueueFailedThenReturnFalseFromInit) {
wddmMockInterface->forceCreateHwQueueFail = true;
init();
EXPECT_FALSE(osContext->isInitialized());
}
TEST_F(Wddm23TestsWithoutWddmInit, givenFailureOnGdiInitializationWhenCreatingHwQueueThenReturnFailure) {
struct MyMockGdi : public Gdi {
bool setupHwQueueProcAddresses() override {
return false;
}
};
auto myMockGdi = new MyMockGdi();
wddm->resetGdi(myMockGdi);
init();
EXPECT_FALSE(osContext->isInitialized());
EXPECT_EQ(1u, wddmMockInterface->createHwQueueCalled);
EXPECT_FALSE(wddmMockInterface->createHwQueueResult);
}

View File

@ -0,0 +1,143 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/command_stream/preemption.h"
#include "core/execution_environment/root_device_environment.h"
#include "test.h"
#include "mocks/mock_execution_environment.h"
#include "mocks/mock_wddm.h"
using namespace NEO;
class WddmMockReserveAddress : public WddmMock {
public:
WddmMockReserveAddress(RootDeviceEnvironment &rootDeviceEnvironment) : WddmMock(rootDeviceEnvironment) {}
void *virtualAlloc(void *inPtr, size_t size, unsigned long flags, unsigned long type) override {
if (returnGood != 0) {
return WddmMock::virtualAlloc(inPtr, size, flags, type);
}
if (returnInvalidCount != 0) {
returnInvalidIter++;
if (returnInvalidIter > returnInvalidCount) {
return WddmMock::virtualAlloc(inPtr, size, flags, type);
}
if (returnNullCount != 0) {
returnNullIter++;
if (returnNullIter > returnNullCount) {
return nullptr;
}
return reinterpret_cast<void *>(0x1000);
}
return reinterpret_cast<void *>(0x1000);
}
return nullptr;
}
int virtualFree(void *ptr, size_t size, unsigned long flags) override {
if ((ptr == reinterpret_cast<void *>(0x1000)) || (ptr == reinterpret_cast<void *>(0x0))) {
return 1;
}
return WddmMock::virtualFree(ptr, size, flags);
}
uint32_t returnGood = 0;
uint32_t returnInvalidCount = 0;
uint32_t returnInvalidIter = 0;
uint32_t returnNullCount = 0;
uint32_t returnNullIter = 0;
};
TEST(WddmReserveAddressTest, givenWddmWhenFirstIsSuccessfulThenReturnReserveAddress) {
MockExecutionEnvironment executionEnvironment;
RootDeviceEnvironment rootDeviceEnvironment(executionEnvironment);
std::unique_ptr<WddmMockReserveAddress> wddm(new WddmMockReserveAddress(rootDeviceEnvironment));
size_t size = 0x1000;
void *reserve = nullptr;
wddm->init();
wddm->returnGood = 1;
auto ret = wddm->reserveValidAddressRange(size, reserve);
uintptr_t expectedReserve = wddm->virtualAllocAddress;
EXPECT_TRUE(ret);
EXPECT_EQ(expectedReserve, reinterpret_cast<uintptr_t>(reserve));
wddm->releaseReservedAddress(reserve);
}
TEST(WddmReserveAddressTest, givenWddmWhenFirstIsNullThenReturnNull) {
MockExecutionEnvironment executionEnvironment;
RootDeviceEnvironment rootDeviceEnvironment(executionEnvironment);
std::unique_ptr<WddmMockReserveAddress> wddm(new WddmMockReserveAddress(rootDeviceEnvironment));
size_t size = 0x1000;
void *reserve = nullptr;
wddm->init();
uintptr_t expectedReserve = 0;
auto ret = wddm->reserveValidAddressRange(size, reserve);
EXPECT_FALSE(ret);
EXPECT_EQ(expectedReserve, reinterpret_cast<uintptr_t>(reserve));
}
TEST(WddmReserveAddressTest, givenWddmWhenFirstIsInvalidSecondSuccessfulThenReturnSecond) {
MockExecutionEnvironment executionEnvironment;
RootDeviceEnvironment rootDeviceEnvironment(executionEnvironment);
std::unique_ptr<WddmMockReserveAddress> wddm(new WddmMockReserveAddress(rootDeviceEnvironment));
size_t size = 0x1000;
void *reserve = nullptr;
wddm->init();
wddm->returnInvalidCount = 1;
auto ret = wddm->reserveValidAddressRange(size, reserve);
uintptr_t expectedReserve = wddm->virtualAllocAddress;
EXPECT_TRUE(ret);
EXPECT_EQ(expectedReserve, reinterpret_cast<uintptr_t>(reserve));
wddm->releaseReservedAddress(reserve);
}
TEST(WddmReserveAddressTest, givenWddmWhenSecondIsInvalidThirdSuccessfulThenReturnThird) {
MockExecutionEnvironment executionEnvironment;
RootDeviceEnvironment rootDeviceEnvironment(executionEnvironment);
std::unique_ptr<WddmMockReserveAddress> wddm(new WddmMockReserveAddress(rootDeviceEnvironment));
size_t size = 0x1000;
void *reserve = nullptr;
wddm->init();
wddm->returnInvalidCount = 2;
auto ret = wddm->reserveValidAddressRange(size, reserve);
uintptr_t expectedReserve = wddm->virtualAllocAddress;
EXPECT_TRUE(ret);
EXPECT_EQ(expectedReserve, reinterpret_cast<uintptr_t>(reserve));
wddm->releaseReservedAddress(reserve);
}
TEST(WddmReserveAddressTest, givenWddmWhenFirstIsInvalidSecondNullThenReturnSecondNull) {
MockExecutionEnvironment executionEnvironment;
RootDeviceEnvironment rootDeviceEnvironment(executionEnvironment);
std::unique_ptr<WddmMockReserveAddress> wddm(new WddmMockReserveAddress(rootDeviceEnvironment));
size_t size = 0x1000;
void *reserve = nullptr;
wddm->init();
wddm->returnInvalidCount = 2;
wddm->returnNullCount = 1;
uintptr_t expectedReserve = 0;
auto ret = wddm->reserveValidAddressRange(size, reserve);
EXPECT_FALSE(ret);
EXPECT_EQ(expectedReserve, reinterpret_cast<uintptr_t>(reserve));
}

View File

@ -0,0 +1,38 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/memory_manager/host_ptr_defines.h"
#include "mocks/mock_wddm.h"
#include "os_interface/windows/ult_dxgi_factory.h"
namespace NEO {
BOOL WINAPI ULTVirtualFree(LPVOID ptr, SIZE_T size, DWORD flags) {
return 1;
}
LPVOID WINAPI ULTVirtualAlloc(LPVOID inPtr, SIZE_T size, DWORD flags, DWORD type) {
return reinterpret_cast<LPVOID>(virtualAllocAddress);
}
Wddm::CreateDXGIFactoryFcn getCreateDxgiFactory() {
return ULTCreateDXGIFactory;
}
Wddm::GetSystemInfoFcn getGetSystemInfo() {
return ULTGetSystemInfo;
}
Wddm::VirtualFreeFcn getVirtualFree() {
return ULTVirtualFree;
}
Wddm::VirtualAllocFcn getVirtualAlloc() {
return ULTVirtualAlloc;
}
} // namespace NEO

View File

@ -0,0 +1,14 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "mocks/mock_wddm.h"
namespace NEO {
Wddm *Wddm::createWddm(std::unique_ptr<HwDeviceId> hwDeviceId, RootDeviceEnvironment &rootDeviceEnvironment) {
return new WddmMock(rootDeviceEnvironment);
}
} // namespace NEO

View File

@ -0,0 +1,106 @@
/*
* Copyright (C) 2017-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "core/command_stream/preemption.h"
#include "core/execution_environment/execution_environment.h"
#include "core/execution_environment/root_device_environment.h"
#include "core/helpers/hw_helper.h"
#include "core/os_interface/windows/gdi_interface.h"
#include "core/os_interface/windows/os_context_win.h"
#include "core/os_interface/windows/os_interface.h"
#include "core/os_interface/windows/wddm_memory_operations_handler.h"
#include "core/unit_tests/helpers/default_hw_info.h"
#include "core/unit_tests/os_interface/windows/mock_gdi_interface.h"
#include "opencl/source/platform/platform.h"
#include "test.h"
#include "mock_gmm_memory.h"
#include "mocks/mock_wddm.h"
#include "mocks/mock_wddm_interface20.h"
#include "mocks/mock_wddm_residency_allocations_container.h"
#include "os_interface/windows/gdi_dll_fixture.h"
namespace NEO {
struct WddmFixture : ::testing::Test {
void SetUp() override {
executionEnvironment = platform()->peekExecutionEnvironment();
wddm = static_cast<WddmMock *>(Wddm::createWddm(nullptr, *executionEnvironment->rootDeviceEnvironments[0].get()));
executionEnvironment->rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setWddm(wddm);
executionEnvironment->rootDeviceEnvironments[0]->memoryOperationsInterface = std::make_unique<WddmMemoryOperationsHandler>(wddm);
osInterface = executionEnvironment->rootDeviceEnvironments[0]->osInterface.get();
gdi = new MockGdi();
wddm->resetGdi(gdi);
auto preemptionMode = PreemptionHelper::getDefaultPreemptionMode(*platformDevices[0]);
wddm->init();
osContext = std::make_unique<OsContextWin>(*osInterface->get()->getWddm(), 0u, 1u, HwHelper::get(platformDevices[0]->platform.eRenderCoreFamily).getGpgpuEngineInstances()[0], preemptionMode, false);
mockTemporaryResources = static_cast<MockWddmResidentAllocationsContainer *>(wddm->temporaryResources.get());
}
WddmMock *wddm = nullptr;
OSInterface *osInterface;
std::unique_ptr<OsContextWin> osContext;
ExecutionEnvironment *executionEnvironment;
MockGdi *gdi = nullptr;
MockWddmResidentAllocationsContainer *mockTemporaryResources;
};
struct WddmFixtureWithMockGdiDll : public GdiDllFixture {
void SetUp() override {
executionEnvironment = platform()->peekExecutionEnvironment();
GdiDllFixture::SetUp();
wddm = static_cast<WddmMock *>(Wddm::createWddm(nullptr, *executionEnvironment->rootDeviceEnvironments[0].get()));
wddmMockInterface = new WddmMockInterface20(*wddm);
wddm->wddmInterface.reset(wddmMockInterface);
executionEnvironment->rootDeviceEnvironments[0]->osInterface = std::make_unique<OSInterface>();
executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setWddm(wddm);
executionEnvironment->rootDeviceEnvironments[0]->memoryOperationsInterface = std::make_unique<WddmMemoryOperationsHandler>(wddm);
osInterface = executionEnvironment->rootDeviceEnvironments[0]->osInterface.get();
}
void init() {
auto preemptionMode = PreemptionHelper::getDefaultPreemptionMode(*platformDevices[0]);
wddmMockInterface = static_cast<WddmMockInterface20 *>(wddm->wddmInterface.release());
wddm->init();
wddm->wddmInterface.reset(wddmMockInterface);
osContext = std::make_unique<OsContextWin>(*osInterface->get()->getWddm(), 0u, 1, HwHelper::get(platformDevices[0]->platform.eRenderCoreFamily).getGpgpuEngineInstances()[0], preemptionMode, false);
}
void TearDown() override {
GdiDllFixture::TearDown();
}
WddmMock *wddm = nullptr;
OSInterface *osInterface;
std::unique_ptr<OsContextWin> osContext;
ExecutionEnvironment *executionEnvironment;
WddmMockInterface20 *wddmMockInterface = nullptr;
};
struct WddmInstrumentationGmmFixture {
void SetUp() {
executionEnvironment = platform()->peekExecutionEnvironment();
wddm.reset(static_cast<WddmMock *>(Wddm::createWddm(nullptr, *executionEnvironment->rootDeviceEnvironments[0].get())));
gmmMem = new ::testing::NiceMock<GmockGmmMemory>(executionEnvironment->getGmmClientContext());
wddm->gmmMemory.reset(gmmMem);
}
void TearDown() {
}
std::unique_ptr<WddmMock> wddm;
GmockGmmMemory *gmmMem = nullptr;
ExecutionEnvironment *executionEnvironment;
};
using WddmTest = WddmFixture;
using WddmTestWithMockGdiDll = Test<WddmFixtureWithMockGdiDll>;
using WddmInstrumentationTest = Test<WddmInstrumentationGmmFixture>;
using WddmTestSingle = ::testing::Test;
} // namespace NEO

View File

@ -0,0 +1,190 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/command_stream/preemption.h"
#include "core/execution_environment/root_device_environment.h"
#include "core/gmm_helper/gmm.h"
#include "core/gmm_helper/gmm_helper.h"
#include "core/memory_manager/memory_manager.h"
#include "core/os_interface/windows/wddm/wddm.h"
#include "core/os_interface/windows/wddm_allocation.h"
#include "core/unit_tests/os_interface/windows/mock_gdi_interface.h"
#include "opencl/source/platform/platform.h"
#include "test.h"
#include "mock_gdi/mock_gdi.h"
#include "os_interface/windows/mock_kmdaf_listener.h"
#include "os_interface/windows/mock_wddm_allocation.h"
using namespace NEO;
class WddmWithKmDafMock : public Wddm {
public:
using Wddm::featureTable;
using Wddm::mapGpuVirtualAddress;
WddmWithKmDafMock(RootDeviceEnvironment &rootDeviceEnvironment, Gdi *mockGdi) : Wddm(std::make_unique<HwDeviceId>(ADAPTER_HANDLE, LUID{}, std::unique_ptr<Gdi>(mockGdi)), rootDeviceEnvironment) {
kmDafListener.reset(new KmDafListenerMock);
}
KmDafListenerMock &getKmDafListenerMock() {
return static_cast<KmDafListenerMock &>(*this->kmDafListener);
}
};
class WddmKmDafListenerTest : public ::testing::Test {
public:
void SetUp() {
executionEnvironment = platform()->peekExecutionEnvironment();
wddmWithKmDafMock.reset(new WddmWithKmDafMock(*executionEnvironment->rootDeviceEnvironments[0].get(), new MockGdi()));
wddmWithKmDafMock->init();
wddmWithKmDafMock->featureTable->ftrKmdDaf = true;
}
void TearDown() {
}
std::unique_ptr<WddmWithKmDafMock> wddmWithKmDafMock;
ExecutionEnvironment *executionEnvironment;
};
TEST_F(WddmKmDafListenerTest, givenWddmWhenLockResourceIsCalledThenKmDafListenerNotifyLockIsFedWithCorrectParams) {
wddmWithKmDafMock->lockResource(ALLOCATION_HANDLE, false);
EXPECT_EQ(wddmWithKmDafMock->featureTable->ftrKmdDaf, wddmWithKmDafMock->getKmDafListenerMock().notifyLockParametrization.ftrKmdDaf);
EXPECT_EQ(wddmWithKmDafMock->getAdapter(), wddmWithKmDafMock->getKmDafListenerMock().notifyLockParametrization.hAdapter);
EXPECT_EQ(wddmWithKmDafMock->getDevice(), wddmWithKmDafMock->getKmDafListenerMock().notifyLockParametrization.hDevice);
EXPECT_EQ(ALLOCATION_HANDLE, wddmWithKmDafMock->getKmDafListenerMock().notifyLockParametrization.hAllocation);
EXPECT_EQ(0, wddmWithKmDafMock->getKmDafListenerMock().notifyLockParametrization.pLockFlags);
EXPECT_EQ(wddmWithKmDafMock->getGdi()->escape, wddmWithKmDafMock->getKmDafListenerMock().notifyLockParametrization.pfnEscape);
}
TEST_F(WddmKmDafListenerTest, givenWddmWhenUnlockResourceIsCalledThenKmDafListenerNotifyUnlockIsFedWithCorrectParams) {
wddmWithKmDafMock->unlockResource(ALLOCATION_HANDLE);
EXPECT_EQ(wddmWithKmDafMock->featureTable->ftrKmdDaf, wddmWithKmDafMock->getKmDafListenerMock().notifyUnlockParametrization.ftrKmdDaf);
EXPECT_EQ(wddmWithKmDafMock->getAdapter(), wddmWithKmDafMock->getKmDafListenerMock().notifyUnlockParametrization.hAdapter);
EXPECT_EQ(wddmWithKmDafMock->getDevice(), wddmWithKmDafMock->getKmDafListenerMock().notifyUnlockParametrization.hDevice);
EXPECT_EQ(ALLOCATION_HANDLE, *wddmWithKmDafMock->getKmDafListenerMock().notifyUnlockParametrization.phAllocation);
EXPECT_EQ(1u, wddmWithKmDafMock->getKmDafListenerMock().notifyUnlockParametrization.allocations);
EXPECT_EQ(wddmWithKmDafMock->getGdi()->escape, wddmWithKmDafMock->getKmDafListenerMock().notifyUnlockParametrization.pfnEscape);
}
TEST_F(WddmKmDafListenerTest, givenWddmWhenMapGpuVirtualAddressIsCalledThenKmDafListenerNotifyMapGpuVAIsFedWithCorrectParams) {
uint64_t gpuPtr = 0u;
auto gmm = std::make_unique<Gmm>(executionEnvironment->getGmmClientContext(), nullptr, 1, false);
wddmWithKmDafMock->mapGpuVirtualAddress(gmm.get(), ALLOCATION_HANDLE, wddmWithKmDafMock->getGfxPartition().Standard.Base,
wddmWithKmDafMock->getGfxPartition().Standard.Limit, 0u, gpuPtr);
EXPECT_EQ(wddmWithKmDafMock->featureTable->ftrKmdDaf, wddmWithKmDafMock->getKmDafListenerMock().notifyMapGpuVAParametrization.ftrKmdDaf);
EXPECT_EQ(wddmWithKmDafMock->getAdapter(), wddmWithKmDafMock->getKmDafListenerMock().notifyMapGpuVAParametrization.hAdapter);
EXPECT_EQ(wddmWithKmDafMock->getDevice(), wddmWithKmDafMock->getKmDafListenerMock().notifyMapGpuVAParametrization.hDevice);
EXPECT_EQ(ALLOCATION_HANDLE, wddmWithKmDafMock->getKmDafListenerMock().notifyMapGpuVAParametrization.hAllocation);
EXPECT_EQ(GmmHelper::decanonize(gpuPtr), wddmWithKmDafMock->getKmDafListenerMock().notifyMapGpuVAParametrization.GpuVirtualAddress);
EXPECT_EQ(wddmWithKmDafMock->getGdi()->escape, wddmWithKmDafMock->getKmDafListenerMock().notifyMapGpuVAParametrization.pfnEscape);
}
TEST_F(WddmKmDafListenerTest, givenWddmWhenFreeGpuVirtualAddressIsCalledThenKmDafListenerNotifyUnmapGpuVAIsFedWithCorrectParams) {
uint64_t gpuPtr = GPUVA;
wddmWithKmDafMock->freeGpuVirtualAddress(gpuPtr, MemoryConstants::pageSize);
EXPECT_EQ(wddmWithKmDafMock->featureTable->ftrKmdDaf, wddmWithKmDafMock->getKmDafListenerMock().notifyUnmapGpuVAParametrization.ftrKmdDaf);
EXPECT_EQ(wddmWithKmDafMock->getAdapter(), wddmWithKmDafMock->getKmDafListenerMock().notifyUnmapGpuVAParametrization.hAdapter);
EXPECT_EQ(wddmWithKmDafMock->getDevice(), wddmWithKmDafMock->getKmDafListenerMock().notifyUnmapGpuVAParametrization.hDevice);
EXPECT_EQ(GPUVA, wddmWithKmDafMock->getKmDafListenerMock().notifyUnmapGpuVAParametrization.GpuVirtualAddress);
EXPECT_EQ(wddmWithKmDafMock->getGdi()->escape, wddmWithKmDafMock->getKmDafListenerMock().notifyUnmapGpuVAParametrization.pfnEscape);
}
TEST_F(WddmKmDafListenerTest, givenWddmWhenMakeResidentIsCalledThenKmDafListenerNotifyMakeResidentIsFedWithCorrectParams) {
MockWddmAllocation allocation;
wddmWithKmDafMock->makeResident(&allocation.handle, 1, false, nullptr);
EXPECT_EQ(wddmWithKmDafMock->featureTable->ftrKmdDaf, wddmWithKmDafMock->getKmDafListenerMock().notifyMakeResidentParametrization.ftrKmdDaf);
EXPECT_EQ(wddmWithKmDafMock->getAdapter(), wddmWithKmDafMock->getKmDafListenerMock().notifyMakeResidentParametrization.hAdapter);
EXPECT_EQ(wddmWithKmDafMock->getDevice(), wddmWithKmDafMock->getKmDafListenerMock().notifyMakeResidentParametrization.hDevice);
EXPECT_EQ(allocation.handle, *wddmWithKmDafMock->getKmDafListenerMock().notifyMakeResidentParametrization.phAllocation);
EXPECT_EQ(1u, wddmWithKmDafMock->getKmDafListenerMock().notifyMakeResidentParametrization.allocations);
EXPECT_EQ(wddmWithKmDafMock->getGdi()->escape, wddmWithKmDafMock->getKmDafListenerMock().notifyMakeResidentParametrization.pfnEscape);
}
TEST_F(WddmKmDafListenerTest, givenWddmWhenEvictIsCalledThenKmDafListenerNotifyEvictIsFedWithCorrectParams) {
MockWddmAllocation allocation;
uint64_t sizeToTrim;
wddmWithKmDafMock->evict(&allocation.handle, 1, sizeToTrim);
EXPECT_EQ(wddmWithKmDafMock->featureTable->ftrKmdDaf, wddmWithKmDafMock->getKmDafListenerMock().notifyEvictParametrization.ftrKmdDaf);
EXPECT_EQ(wddmWithKmDafMock->getAdapter(), wddmWithKmDafMock->getKmDafListenerMock().notifyEvictParametrization.hAdapter);
EXPECT_EQ(wddmWithKmDafMock->getDevice(), wddmWithKmDafMock->getKmDafListenerMock().notifyEvictParametrization.hDevice);
EXPECT_EQ(allocation.handle, *wddmWithKmDafMock->getKmDafListenerMock().notifyEvictParametrization.phAllocation);
EXPECT_EQ(1u, wddmWithKmDafMock->getKmDafListenerMock().notifyEvictParametrization.allocations);
EXPECT_EQ(wddmWithKmDafMock->getGdi()->escape, wddmWithKmDafMock->getKmDafListenerMock().notifyEvictParametrization.pfnEscape);
}
TEST_F(WddmKmDafListenerTest, givenWddmWhenCreateAllocationIsCalledThenKmDafListenerNotifyWriteTargetIsFedWithCorrectParams) {
auto gmm = std::make_unique<Gmm>(executionEnvironment->getGmmClientContext(), nullptr, 1, false);
auto handle = 0u;
auto ptr = reinterpret_cast<void *>(0x10000);
wddmWithKmDafMock->createAllocation(ptr, gmm.get(), handle, false);
EXPECT_EQ(wddmWithKmDafMock->featureTable->ftrKmdDaf, wddmWithKmDafMock->getKmDafListenerMock().notifyWriteTargetParametrization.ftrKmdDaf);
EXPECT_EQ(wddmWithKmDafMock->getAdapter(), wddmWithKmDafMock->getKmDafListenerMock().notifyWriteTargetParametrization.hAdapter);
EXPECT_EQ(wddmWithKmDafMock->getDevice(), wddmWithKmDafMock->getKmDafListenerMock().notifyWriteTargetParametrization.hDevice);
EXPECT_EQ(handle, wddmWithKmDafMock->getKmDafListenerMock().notifyWriteTargetParametrization.hAllocation);
EXPECT_EQ(wddmWithKmDafMock->getGdi()->escape, wddmWithKmDafMock->getKmDafListenerMock().notifyWriteTargetParametrization.pfnEscape);
}
TEST_F(WddmKmDafListenerTest, givenWddmWhenCreateAllocation64IsCalledThenKmDafListenerNotifyWriteTargetIsFedWithCorrectParams) {
auto gmm = std::make_unique<Gmm>(executionEnvironment->getGmmClientContext(), nullptr, 1, false);
auto handle = 0u;
wddmWithKmDafMock->createAllocation64k(gmm.get(), handle);
EXPECT_EQ(wddmWithKmDafMock->featureTable->ftrKmdDaf, wddmWithKmDafMock->getKmDafListenerMock().notifyWriteTargetParametrization.ftrKmdDaf);
EXPECT_EQ(wddmWithKmDafMock->getAdapter(), wddmWithKmDafMock->getKmDafListenerMock().notifyWriteTargetParametrization.hAdapter);
EXPECT_EQ(wddmWithKmDafMock->getDevice(), wddmWithKmDafMock->getKmDafListenerMock().notifyWriteTargetParametrization.hDevice);
EXPECT_EQ(handle, wddmWithKmDafMock->getKmDafListenerMock().notifyWriteTargetParametrization.hAllocation);
EXPECT_EQ(wddmWithKmDafMock->getGdi()->escape, wddmWithKmDafMock->getKmDafListenerMock().notifyWriteTargetParametrization.pfnEscape);
}
TEST_F(WddmKmDafListenerTest, givenWddmWhenCreateAllocationsAndMapGpuVaIsCalledThenKmDafListenerNotifyWriteTargetAndMapGpuVAIsFedWithCorrectParams) {
OsHandleStorage storage;
OsHandle osHandle = {0};
auto gmm = std::unique_ptr<Gmm>(new Gmm(executionEnvironment->getGmmClientContext(), nullptr, 1, false));
storage.fragmentStorageData[0].osHandleStorage = &osHandle;
storage.fragmentStorageData[0].fragmentSize = 100;
storage.fragmentStorageData[0].osHandleStorage->gmm = gmm.get();
wddmWithKmDafMock->createAllocationsAndMapGpuVa(storage);
EXPECT_EQ(wddmWithKmDafMock->featureTable->ftrKmdDaf, wddmWithKmDafMock->getKmDafListenerMock().notifyWriteTargetParametrization.ftrKmdDaf);
EXPECT_EQ(wddmWithKmDafMock->getAdapter(), wddmWithKmDafMock->getKmDafListenerMock().notifyWriteTargetParametrization.hAdapter);
EXPECT_EQ(wddmWithKmDafMock->getDevice(), wddmWithKmDafMock->getKmDafListenerMock().notifyWriteTargetParametrization.hDevice);
EXPECT_EQ(osHandle.handle, wddmWithKmDafMock->getKmDafListenerMock().notifyWriteTargetParametrization.hAllocation);
EXPECT_EQ(wddmWithKmDafMock->getGdi()->escape, wddmWithKmDafMock->getKmDafListenerMock().notifyWriteTargetParametrization.pfnEscape);
EXPECT_EQ(wddmWithKmDafMock->featureTable->ftrKmdDaf, wddmWithKmDafMock->getKmDafListenerMock().notifyMapGpuVAParametrization.ftrKmdDaf);
EXPECT_EQ(wddmWithKmDafMock->getAdapter(), wddmWithKmDafMock->getKmDafListenerMock().notifyMapGpuVAParametrization.hAdapter);
EXPECT_EQ(wddmWithKmDafMock->getDevice(), wddmWithKmDafMock->getKmDafListenerMock().notifyMapGpuVAParametrization.hDevice);
EXPECT_EQ(osHandle.handle, wddmWithKmDafMock->getKmDafListenerMock().notifyMapGpuVAParametrization.hAllocation);
EXPECT_EQ(GmmHelper::decanonize(osHandle.gpuPtr), wddmWithKmDafMock->getKmDafListenerMock().notifyMapGpuVAParametrization.GpuVirtualAddress);
EXPECT_EQ(wddmWithKmDafMock->getGdi()->escape, wddmWithKmDafMock->getKmDafListenerMock().notifyMapGpuVAParametrization.pfnEscape);
}
TEST_F(WddmKmDafListenerTest, givenWddmWhenKmDafLockIsCalledThenKmDafListenerNotifyLockIsFedWithCorrectParams) {
wddmWithKmDafMock->kmDafLock(ALLOCATION_HANDLE);
EXPECT_EQ(wddmWithKmDafMock->featureTable->ftrKmdDaf, wddmWithKmDafMock->getKmDafListenerMock().notifyLockParametrization.ftrKmdDaf);
EXPECT_EQ(wddmWithKmDafMock->getAdapter(), wddmWithKmDafMock->getKmDafListenerMock().notifyLockParametrization.hAdapter);
EXPECT_EQ(wddmWithKmDafMock->getDevice(), wddmWithKmDafMock->getKmDafListenerMock().notifyLockParametrization.hDevice);
EXPECT_EQ(ALLOCATION_HANDLE, wddmWithKmDafMock->getKmDafListenerMock().notifyLockParametrization.hAllocation);
EXPECT_EQ(0, wddmWithKmDafMock->getKmDafListenerMock().notifyLockParametrization.pLockFlags);
EXPECT_EQ(wddmWithKmDafMock->getGdi()->escape, wddmWithKmDafMock->getKmDafListenerMock().notifyLockParametrization.pfnEscape);
}

View File

@ -0,0 +1,27 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/windows/wddm_engine_mapper.h"
#include "test.h"
using namespace NEO;
TEST(WddmMapperTests, givenRcsEngineTypeWhenAskedForNodeOrdinalThenReturn3d) {
GPUNODE_ORDINAL rcsNode = WddmEngineMapper::engineNodeMap(aub_stream::ENGINE_RCS);
GPUNODE_ORDINAL bcsNode = WddmEngineMapper::engineNodeMap(aub_stream::ENGINE_BCS);
GPUNODE_ORDINAL ccsNode = WddmEngineMapper::engineNodeMap(aub_stream::ENGINE_CCS);
GPUNODE_ORDINAL expectedRcsNode = GPUNODE_3D;
GPUNODE_ORDINAL expectedBcsNode = GPUNODE_BLT;
GPUNODE_ORDINAL expectedCcsNode = GPUNODE_CCS0;
EXPECT_EQ(expectedRcsNode, rcsNode);
EXPECT_EQ(expectedBcsNode, bcsNode);
EXPECT_EQ(expectedCcsNode, ccsNode);
}
TEST(WddmMapperTests, givenNotSupportedEngineWhenAskedForNodeThenAbort) {
EXPECT_THROW(WddmEngineMapper::engineNodeMap(aub_stream::ENGINE_VCS), std::exception);
}

View File

@ -0,0 +1,12 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "os_interface/windows/wddm_memory_manager_allocate_in_device_pool_tests.inl"
TEST_F(WddmMemoryManagerSimpleTest, givenWddmMemoryManagerWhenGetLocalMemoryIsCalledThenSizeOfLocalMemoryIsReturned) {
EXPECT_EQ(0 * GB, memoryManager->getLocalMemorySize(0u));
}

View File

@ -0,0 +1,27 @@
/*
* Copyright (C) 2018-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "core/os_interface/windows/wddm_memory_manager.h"
#include "gtest/gtest.h"
#include "mocks/mock_memory_manager.h"
#include "os_interface/windows/wddm_memory_manager_tests.h"
using namespace NEO;
using namespace ::testing;
TEST_F(WddmMemoryManagerSimpleTest, givenUseSystemMemorySetToTrueWhenAllocateInDevicePoolIsCalledThenNullptrIsReturned) {
memoryManager.reset(new MockWddmMemoryManager(false, false, *executionEnvironment));
MemoryManager::AllocationStatus status = MemoryManager::AllocationStatus::Success;
AllocationData allocData;
allocData.size = MemoryConstants::pageSize;
allocData.flags.useSystemMemory = true;
allocData.flags.allocateMemory = true;
auto allocation = memoryManager->allocateGraphicsMemoryInDevicePool(allocData, status);
EXPECT_EQ(nullptr, allocation);
EXPECT_EQ(MemoryManager::AllocationStatus::RetryInNonDevicePool, status);
}

Some files were not shown because too many files have changed in this diff Show More