Skip to content
This repository has been archived by the owner on Mar 3, 2023. It is now read-only.

Commit

Permalink
Merge mesurefreq branch
Browse files Browse the repository at this point in the history
  • Loading branch information
xlz-jbleclere committed Feb 8, 2021
2 parents b6d7582 + 5890ced commit 67bc83e
Show file tree
Hide file tree
Showing 14 changed files with 442 additions and 169 deletions.
150 changes: 104 additions & 46 deletions source/drm_manager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,12 @@ limitations under the License.

#define NB_MAX_REGISTER 32

#define REG_FREQ_DETECTION_VERSION 0xFFF8
#define REG_FREQ_DETECTION_COUNTER 0xFFFC
#define REG_FREQ_DETECTION_VERSION 0xFFF0
#define REG_FREQ_DETECTION_COUNTER_DRMACLK 0xFFF4
#define REG_FREQ_DETECTION_COUNTER_AXIACLK 0xFFF8

#define FREQ_DETECTION_VERSION_EXPECTED 0x60DC0DE0
#define FREQ_DETECTION_VERSION_2 0x60DC0DE0
#define FREQ_DETECTION_VERSION_3 0x60DC0DE1


#define TRY try {
Expand Down Expand Up @@ -178,8 +180,9 @@ class DRM_LOCAL DrmManager::Impl {
int32_t mFrequencyCurr = 0;
uint32_t mFrequencyDetectionPeriod = 100; // in milliseconds
double mFrequencyDetectionThreshold = 12.0; // Error in percentage
bool mIsFreqDetectionMethod1 = false;
uint8_t mFreqDetectionMethod = 0;
bool mBypassFrequencyDetection = false;
uint32_t mAxiFrequency = 0;

// Session state
std::string mSessionID;
Expand Down Expand Up @@ -585,7 +588,7 @@ class DRM_LOCAL DrmManager::Impl {

Json::Value buildSettingsNode() {
Json::Value settings;
settings["frequency_detection_method"] = mIsFreqDetectionMethod1? 1:2;
settings["frequency_detection_method"] = mFreqDetectionMethod;
settings["bypass_frequency_detection"] = mBypassFrequencyDetection;
settings["frequency_detection_threshold"] = mFrequencyDetectionThreshold;
settings["frequency_detection_period"] = mFrequencyDetectionPeriod;
Expand All @@ -604,6 +607,7 @@ class DRM_LOCAL DrmManager::Impl {
settings["ws_api_retry_duration"] = mWSApiRetryDuration;
settings["host_data_verbosity"] = static_cast<uint32_t>( mHostDataVerbosity );
settings["simulation_flag"] = mSimulationFlag;
settings["axi_frequency"] = mAxiFrequency;
return settings;
}

Expand Down Expand Up @@ -896,7 +900,7 @@ class DRM_LOCAL DrmManager::Impl {
Debug( "DRM Communication Self-Test 2 succeeded" );
}

bool isNodeLockedMode() const {
bool isConfigInNodeLock() const {
return mLicenseType == eLicenseType::NODE_LOCKED;
}

Expand Down Expand Up @@ -940,10 +944,15 @@ class DRM_LOCAL DrmManager::Impl {
runBistLevel2();

// Determine frequency detection method if metering/floating mode is active
if ( !isNodeLockedMode() ) {
if ( !isConfigInNodeLock() ) {
determineFrequencyDetectionMethod();
if ( mIsFreqDetectionMethod1 ) {
detectDrmFrequencyMethod1();
if ( mFreqDetectionMethod == 3 ) {
detectDrmFrequencyMethod3();
} else if ( mFreqDetectionMethod == 2 ) {
detectDrmFrequencyMethod2();
} else if ( mFreqDetectionMethod == 1 ) {
} else {
Warning( "DRM frequency auto-detection is disabled: {} will be used to compute license timers", mFrequencyCurr );
}
}

Expand All @@ -954,7 +963,7 @@ class DRM_LOCAL DrmManager::Impl {
loadDerivedProduct( mDerivedProductFromConf );

// If node-locked license is requested, create license request file
if ( isNodeLockedMode() ) {
if ( isConfigInNodeLock() ) {

// Check license directory exists
if ( !isDir( mNodeLockLicenseDirPath ) )
Expand Down Expand Up @@ -1059,7 +1068,7 @@ class DRM_LOCAL DrmManager::Impl {
if ( !mBoardType.empty() )
json_output["boardType"] = mBoardType;
json_output["mode"] = (uint8_t)mLicenseType;
if ( !isNodeLockedMode() )
if ( !isConfigInNodeLock() )
json_output["drm_frequency_init"] = mFrequencyInit;

// Fulfill with DRM section
Expand Down Expand Up @@ -1152,7 +1161,7 @@ class DRM_LOCAL DrmManager::Impl {
json_request["saasChallenge"] = saasChallenge;
json_request["meteringFile"] = std::accumulate( meteringFile.begin(), meteringFile.end(), std::string("") );
json_request["request"] = "open";
if ( !isNodeLockedMode() )
if ( !isConfigInNodeLock() )
json_request["drm_frequency"] = mFrequencyCurr;
json_request["mode"] = (uint8_t)mLicenseType;

Expand All @@ -1175,7 +1184,7 @@ class DRM_LOCAL DrmManager::Impl {
json_request["sessionId"] = meteringFile[0].substr( 0, 16 );
checkSessionIDFromDRM( json_request );

if ( !isNodeLockedMode() )
if ( !isConfigInNodeLock() )
json_request["drm_frequency"] = mFrequencyCurr;
json_request["meteringFile"] = std::accumulate( meteringFile.begin(), meteringFile.end(), std::string("") );
json_request["request"] = "running";
Expand All @@ -1197,7 +1206,7 @@ class DRM_LOCAL DrmManager::Impl {
json_request["sessionId"] = meteringFile[0].substr( 0, 16 );
checkSessionIDFromDRM( json_request );

if ( !isNodeLockedMode() )
if ( !isConfigInNodeLock() )
json_request["drm_frequency"] = mFrequencyCurr;
json_request["meteringFile"] = std::accumulate( meteringFile.begin(), meteringFile.end(), std::string("") );
json_request["request"] = "close";
Expand All @@ -1217,7 +1226,7 @@ class DRM_LOCAL DrmManager::Impl {
Debug( "Build health request #{}", mHealthCounter );
{
std::lock_guard<std::recursive_mutex> lock( mDrmControllerMutex );
if ( isNodeLockedMode() || isSessionRunning() ) {
if ( isConfigInNodeLock() || isSessionRunning() ) {
checkDRMCtlrRet( getDrmController().asynchronousExtractMeteringFile(
numberOfDetectedIps, saasChallenge, meteringFile ) );
} else {
Expand Down Expand Up @@ -1429,7 +1438,7 @@ class DRM_LOCAL DrmManager::Impl {
/// Extract license key and license timer from web service response
if ( mLicenseCounter == 0 )
licenseKey = JVgetRequired( dna_node, "key", Json::stringValue ).asString();
if ( !isNodeLockedMode() )
if ( !isConfigInNodeLock() )
licenseTimer = JVgetRequired( dna_node, "licenseTimer", Json::stringValue ).asString();
mLicenseDuration = JVgetRequired( metering_node, "timeoutSecond", Json::uintValue ).asUInt();
if ( mLicenseDuration == 0 )
Expand All @@ -1448,7 +1457,7 @@ class DRM_LOCAL DrmManager::Impl {
}

// Load license timer
if ( !isNodeLockedMode() ) {
if ( !isConfigInNodeLock() ) {
checkDRMCtlrRet( getDrmController().loadLicenseTimerInit( licenseTimer ) );
Debug( "Wrote license timer #{} of session ID {} for a duration of {} seconds",
mLicenseCounter, mSessionID, mLicenseDuration );
Expand Down Expand Up @@ -1489,7 +1498,7 @@ class DRM_LOCAL DrmManager::Impl {
bool is_metered = isDrmCtrlInMetering();
if ( is_nodelocked && is_metered )
Unreachable( "DRM Controller cannot be in both Node-Locked and Metering/Floating license modes. " ); //LCOV_EXCL_LINE
if ( !isNodeLockedMode() ) {
if ( !isConfigInNodeLock() ) {
if ( !is_metered )
Unreachable( "DRM Controller failed to switch to Metering license mode" ); //LCOV_EXCL_LINE
Debug( "DRM Controller is in Metering license mode" );
Expand Down Expand Up @@ -1680,18 +1689,38 @@ class DRM_LOCAL DrmManager::Impl {
if ( ret != 0 ) {
Debug( "Failed to read DRM Ctrl frequency detection version register, errcode = {}. ", ret ); //LCOV_EXCL_LINE
}
if ( reg == FREQ_DETECTION_VERSION_EXPECTED ) {
// Use Method 1
Debug( "Use dedicated counter to compute DRM frequency (method 1)" );
mIsFreqDetectionMethod1 = true;
} else {
if ( reg == FREQ_DETECTION_VERSION_3 ) {
// Use Method 3
Debug( "Use dedicated counter to compute DRM frequency (method 3)" );
mFreqDetectionMethod = 3;
} else if ( reg == FREQ_DETECTION_VERSION_2 ) {
// Use Method 2
Debug( "Use license timer counter to compute DRM frequency (method 2)" );
mIsFreqDetectionMethod1 = false;
Debug( "Use dedicated counter to compute DRM frequency (method 2)" );
mFreqDetectionMethod = 2;
} else {
// Use Method 1
Debug( "Use license timer counter to compute DRM frequency (method 1)" );
mFreqDetectionMethod = 1;
}
}

void detectDrmFrequencyMethod1() {
std::vector<int32_t> frequency_list;

if ( mBypassFrequencyDetection ) {
return;
}

frequency_list.push_back( detectDrmFrequencyFromLicenseTimer() );
frequency_list.push_back( detectDrmFrequencyFromLicenseTimer() );
frequency_list.push_back( detectDrmFrequencyFromLicenseTimer() );
std::sort( frequency_list.begin(), frequency_list.end());

int32_t measured_frequency = frequency_list[1];
checkDrmFrequency( measured_frequency );
}

void detectDrmFrequencyMethod2() {
int ret;
uint32_t counter;
TClock::duration wait_duration = std::chrono::milliseconds( mFrequencyDetectionPeriod );
Expand All @@ -1702,16 +1731,16 @@ class DRM_LOCAL DrmManager::Impl {

std::lock_guard<std::recursive_mutex> lock( mDrmControllerMutex );

// Start detection counter
ret = writeDrmAddress( REG_FREQ_DETECTION_COUNTER, 0 );
// Reset detection counter by writing drm_aclk counter register
ret = writeDrmAddress( REG_FREQ_DETECTION_VERSION, 0 );
if ( ret != 0 )
Unreachable( "Failed to start DRM frequency detection counter, errcode = {}. ", ret ); //LCOV_EXCL_LINE

// Wait a fixed period of time
sleepOrExit( wait_duration );

// Sample counter
ret = readDrmAddress( REG_FREQ_DETECTION_COUNTER, counter );
// Sample drm_aclk counter
ret = readDrmAddress( REG_FREQ_DETECTION_COUNTER_DRMACLK, counter );
if ( ret != 0 ) {
Unreachable( "Failed to read DRM Ctrl frequency detection counter register, errcode = {}. ", ret ); //LCOV_EXCL_LINE
}
Expand All @@ -1728,20 +1757,52 @@ class DRM_LOCAL DrmManager::Impl {
checkDrmFrequency( measured_frequency );
}

void detectDrmFrequencyMethod2() {
std::vector<int32_t> frequency_list;
void detectDrmFrequencyMethod3() {
int ret;
uint32_t counter_drmaclk, counter_axiaclk;
TClock::duration wait_duration = std::chrono::milliseconds( mFrequencyDetectionPeriod );

if ( mBypassFrequencyDetection ) {
return;
}

frequency_list.push_back( detectDrmFrequencyFromLicenseTimer() );
frequency_list.push_back( detectDrmFrequencyFromLicenseTimer() );
frequency_list.push_back( detectDrmFrequencyFromLicenseTimer() );
std::sort( frequency_list.begin(), frequency_list.end());
std::lock_guard<std::recursive_mutex> lock( mDrmControllerMutex );

int32_t measured_frequency = frequency_list[1];
checkDrmFrequency( measured_frequency );
// Reset detection counter by writing drm_aclk counter register
ret = writeDrmAddress( REG_FREQ_DETECTION_VERSION, 0 );
if ( ret != 0 )
Unreachable( "Failed to start DRM frequency detection counter, errcode = {}. ", ret ); //LCOV_EXCL_LINE

// Wait a fixed period of time
sleepOrExit( wait_duration );

// Sample drm_aclk and s_axi_aclk counters
ret = readDrmAddress( REG_FREQ_DETECTION_COUNTER_DRMACLK, counter_drmaclk );
if ( ret != 0 ) {
Unreachable( "Failed to read drm_aclk frequency detection counter register, errcode = {}. ", ret ); //LCOV_EXCL_LINE
}
ret = readDrmAddress( REG_FREQ_DETECTION_COUNTER_AXIACLK, counter_axiaclk );
if ( ret != 0 ) {
Unreachable( "Failed to read s_axi_aclk frequency detection counter register, errcode = {}. ", ret ); //LCOV_EXCL_LINE
}

if ( counter_drmaclk == 0xFFFFFFFF )
Throw( DRM_BadFrequency, "Frequency auto-detection of drm_aclk failed: frequency_detection_period parameter ({} ms) is too long.",
mFrequencyDetectionPeriod );
if ( counter_axiaclk == 0xFFFFFFFF )
Throw( DRM_BadFrequency, "Frequency auto-detection of s_axi_aclk failed: frequency_detection_period parameter ({} ms) is too long.",
mFrequencyDetectionPeriod );

// Compute estimated DRM frequency for s_axi_aclk
mAxiFrequency = (int32_t)((double)counter_axiaclk / mFrequencyDetectionPeriod / 1000);
Debug( "Frequency detection of s_axi_aclk counter after {:f} ms is 0x{:08x} => estimated frequency = {} MHz",
(double)mFrequencyDetectionPeriod/1000, counter_axiaclk, mAxiFrequency );

// Compute estimated DRM frequency for drm_aclk
int32_t measured_drmaclk = (int32_t)((double)counter_drmaclk / mFrequencyDetectionPeriod / 1000);
Debug( "Frequency detection of drm_aclk counter after {:f} ms is 0x{:08x} => estimated frequency = {} MHz",
(double)mFrequencyDetectionPeriod/1000, counter_drmaclk, measured_drmaclk );
checkDrmFrequency( measured_drmaclk ); // Only drm_aclk can be verified because provided in the config.json
}

int32_t detectDrmFrequencyFromLicenseTimer() {
Expand Down Expand Up @@ -1852,8 +1913,8 @@ class DRM_LOCAL DrmManager::Impl {
getHostAndCardInfo();

/// Detecting DRM controller frequency if needed
if ( !mIsFreqDetectionMethod1 )
detectDrmFrequencyMethod2();
if ( mFreqDetectionMethod == 1 )
detectDrmFrequencyMethod1();

bool go_sleeping( false );

Expand Down Expand Up @@ -2202,7 +2263,7 @@ class DRM_LOCAL DrmManager::Impl {
TRY
Debug( "Calling 'activate' with 'resume_session_request'={}", resume_session_request );

if ( isNodeLockedMode() ) {
if ( isConfigInNodeLock() ) {
// Install the node-locked license
installNodelockedLicense();
return;
Expand Down Expand Up @@ -2249,7 +2310,7 @@ class DRM_LOCAL DrmManager::Impl {
TRY
Debug( "Calling 'deactivate' with 'pause_session_request'={}", pause_session_request );

if ( isNodeLockedMode() ) {
if ( isConfigInNodeLock() ) {
return;
}
if ( !isSessionRunning() ) {
Expand Down Expand Up @@ -2446,12 +2507,9 @@ class DRM_LOCAL DrmManager::Impl {
break;
}
case ParameterKey::frequency_detection_method: {
int32_t method_index = 2;
if ( mIsFreqDetectionMethod1 )
method_index = 1;
json_value[key_str] = method_index;
json_value[key_str] = mFreqDetectionMethod;
Debug( "Get value of parameter '{}' (ID={}): Method {}", key_str, key_id,
method_index );
mFreqDetectionMethod );
break;
}
case ParameterKey::frequency_detection_threshold: {
Expand Down
15 changes: 11 additions & 4 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,8 +421,14 @@ def __init__(self, path):
if not isdir(path):
raise IOError("Following path must be a valid directory: %s" % path)
self._path = path
self.image_files = {splitext(file_name)[0].strip('v'):realpath(join(self._path, file_name))
for file_name in listdir(self._path)}
self.image_files = {}
for filename in listdir(self._path):
bname = splitext(filename)[0]
s = search(r'v((\d\.)+\d)', bname)
if s:
self.image_files[s.group(0)] = realpath(join(self._path, filename))
else:
self.image_files[bname] = realpath(join(self._path, filename))
self.hdk_versions = sorted(filter(lambda x: match(r'^\d+', x), self.image_files.keys()))

def get_image_id(self, hdk_version=None):
Expand Down Expand Up @@ -603,11 +609,12 @@ def create_log_level(verbosity):
return verbosity

# Get frequency detection version
freq_version = fpga_driver[0].read_register(drm_ctrl_base_addr + 0xFFF8)
freq_version = fpga_driver[0].read_register(drm_ctrl_base_addr + 0xFFF0)
print('Frequency detection version: 0x%08X' % freq_version)

# Store some values for access in tests
import accelize_drm as _accelize_drm
_accelize_drm.pytest_new_freq_method_supported = freq_version == 0x60DC0DE0
_accelize_drm.pytest_freq_detection_version = freq_version
_accelize_drm.pytest_proxy_debug = pytestconfig.getoption("proxy_debug")
_accelize_drm.pytest_server = pytestconfig.getoption("server")
_accelize_drm.pytest_build_environment = build_environment
Expand Down
1 change: 1 addition & 0 deletions tests/fpga_drivers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ def _augment_exception(action):
try:
yield
except RuntimeError as exception:
print('Caugth exception:\n>', '\n> '.join(str(exception).strip().split('\n')))
exception.args = (
'Unable to %s FPGA: %s' % (action, exception.args[0].strip()),)
raise
Expand Down
Loading

0 comments on commit 67bc83e

Please sign in to comment.