LCOV - code coverage report
Current view: top level - acl/aclrt_impl - acl.cpp (source / functions) Hit Total Coverage
Test: coverage.info Lines: 710 761 93.3 %
Date: 2026-08-27 13:24:42 Functions: 41 41 100.0 %

          Line data    Source code
       1             : /**
       2             :  * Copyright (c) 2025 Huawei Technologies Co., Ltd.
       3             :  * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
       4             :  * CANN Open Software License Agreement Version 2.0 (the "License").
       5             :  * Please refer to the License for details. You may not use this file except in compliance with the License.
       6             :  * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
       7             :  * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
       8             :  * See LICENSE in the root of the software repository for the full text of the License.
       9             :  */
      10             : 
      11             : #include "acl/acl.h"
      12             : 
      13             : #include <mutex>
      14             : #include <fstream>
      15             : #include <cctype>
      16             : #include <algorithm>
      17             : #include "acl_rt_impl.h"
      18             : #include "runtime/rt_preload_task.h"
      19             : #include "runtime/rt.h"
      20             : #include "runtime/rts/rts_device.h"
      21             : #include "runtime/rts/rts_stars.h"
      22             : #include "runtime/event.h"
      23             : #include "adx_datadump_server.h"
      24             : #include "base/err_mgr.h"
      25             : #include "common/log_inner.h"
      26             : #include "toolchain/plog.h"
      27             : #include "toolchain/dump.h"
      28             : #include "toolchain/profiling.h"
      29             : #include "common/error_codes_inner.h"
      30             : #include "common/resource_statistics.h"
      31             : #include "platform/platform_info.h"
      32             : #include "common/json_parser.h"
      33             : #include "utils/hash_utils.h"
      34             : #include "utils/string_utils.h"
      35             : #include "utils/file_utils.h"
      36             : #include "aclrt_impl/acl_rt_impl_base.h"
      37             : #include "aclrt_impl/init_callback_manager.h"
      38             : 
      39             : namespace {
      40             :     bool aclFinalizeFlag = false;
      41             :     thread_local static std::string aclRecentErrMsg;
      42             :     bool isEnableDefaultDevice = false;
      43             :     constexpr int32_t INVALID_DEFAULT_DEVICE = -1;
      44             :     constexpr int32_t ACL_DEFAULT_DEVICE_DISABLE = 0xFFFFFFFF;
      45             :     std::string aclInitJsonHash;
      46             :     std::string aclInitJsonPath;
      47             :     constexpr const char_t *const kAscendHomeEnvName = "ASCEND_HOME_PATH";
      48             :     constexpr const char_t *const kVersionInfoKey = "Version=";
      49             :     constexpr const char_t *const kDriverPathKey = "Driver_Install_Path_Param=";
      50             :     constexpr const char_t *const kFirmwarePathKey = "Firmware_Install_Path_Param=";
      51             :     constexpr const char_t *const kDriverPkgName = "driver";
      52             :     constexpr const char_t *const kFirmwarePkgName = "firmware";
      53             :     constexpr const char_t *const kRelPathInfo = "/share/info/";
      54             :     constexpr const char_t *const kInfoFileName = "/version.info";
      55             :     constexpr const char_t *const kPreAlpha = "alpha";
      56             :     constexpr const char_t *const kPreBeta = "beta";
      57             :     constexpr const char_t *const kPreRC = "rc";
      58             :     const int32_t kWeightMajor = 10000000;
      59             :     const int32_t kWeightMinor = 100000;
      60             :     const int32_t kWeightPatch = 1000;
      61             :     const int32_t kWeightAlpha = 300;
      62             :     const int32_t kWeightBeta = 200;
      63             :     const int32_t kWeightRC = 100;
      64             :     const std::string kAscendInstallPath = "/etc/ascend_install.info";
      65             :     const std::map<aclCANNPackageName, std::string> kMapToPkgName = {
      66             :         { ACL_PKG_NAME_CANN, "runtime" },
      67             :         { ACL_PKG_NAME_RUNTIME, "runtime" },
      68             :         { ACL_PKG_NAME_COMPILER, "bisheng-compiler" },
      69             :         { ACL_PKG_NAME_HCCL, "hccl" },
      70             :         { ACL_PKG_NAME_TOOLKIT, "oam-tools" },
      71             :         { ACL_PKG_NAME_OPP, "ops-legacy" },
      72             :         { ACL_PKG_NAME_OPP_KERNEL, "ops-legacy" },
      73             :         { ACL_PKG_NAME_DRIVER, "driver" },
      74             :     };
      75             : 
      76           5 :     aclError GetPlatformInfoWithKey(const std::string &key, int64_t *value)
      77             :     {
      78             : #ifdef __GNUC__
      79           5 :         const char *socName = aclrtGetSocNameImpl();
      80           5 :         if (socName == nullptr) {
      81           0 :             ACL_LOG_ERROR("Init SocVersion failed");
      82           0 :             return ACL_ERROR_INTERNAL_ERROR;
      83             :         }
      84             :         // call after aclInit
      85          15 :         const string socVersion(socName);
      86             : 
      87             :         // init platform info
      88           5 :         if (fe::PlatformInfoManager::GeInstance().InitializePlatformInfo() != 0U) {
      89           1 :             ACL_LOG_INNER_ERROR("init runtime platform info failed, SocVersion = %s", socVersion.c_str());
      90           1 :             return ACL_ERROR_INTERNAL_ERROR;
      91             :         }
      92             : 
      93           8 :         fe::PlatFormInfos platformInfos;
      94           8 :         fe::OptionalInfos optionalInfos;
      95           4 :         if (fe::PlatformInfoManager::GeInstance().GetPlatformInfos(socVersion, platformInfos, optionalInfos) != 0U) {
      96           1 :             ACL_LOG_INNER_ERROR("get platform info failed, SocVersion = %s", socVersion.c_str());
      97           1 :             return ACL_ERROR_INTERNAL_ERROR;
      98             :         }
      99           6 :         std::string strVal;
     100           3 :         if (!platformInfos.GetPlatformResWithLock("SoCInfo", key, strVal)) {
     101           1 :             ACL_LOG_CALL_ERROR("get platform result failed, key = %s", key.c_str());
     102           1 :             return ACL_ERROR_INTERNAL_ERROR;
     103             :         }
     104             : 
     105             :         try {
     106           2 :             *value = std::stoll(strVal);
     107           1 :         } catch (...) {
     108           1 :             ACL_LOG_INNER_ERROR("strVal[%s] can not be converted to digital value", strVal.c_str());
     109           1 :             return ACL_ERROR_INTERNAL_ERROR;
     110             :         }
     111           1 :         ACL_LOG_INFO("Successfully get platform info, key = %s, value = %ld", key.c_str(), *value);
     112             : #endif
     113           1 :         return ACL_SUCCESS;
     114             :     }
     115             : 
     116          44 :     std::string ConvertVersion(const std::string& version)
     117             :     {
     118          44 :         size_t dashPos = version.find('-');
     119          44 :         if (dashPos == std::string::npos) {
     120          43 :             return version;
     121             :         }
     122             : 
     123           2 :         std::string prefix = version.substr(0, dashPos);
     124           2 :         std::string suffix = version.substr(dashPos + 1U);
     125           1 :         suffix.erase(std::remove(suffix.begin(), suffix.end(), '.'), suffix.end());
     126             : 
     127           2 :         return prefix + "." + suffix;
     128             :     }
     129             :     const std::map<rtLimitType_t, std::string> limitToKeyMap = {
     130             :         {RT_LIMIT_TYPE_STACK_SIZE, "aicore_stack_size"},
     131             :         {RT_LIMIT_TYPE_SIMT_STACK_SIZE, "simt_stack_size"},
     132             :         {RT_LIMIT_TYPE_SIMT_DVG_WARP_STACK_SIZE, "simt_divergence_stack_size"}};
     133             : 
     134          90 :     aclError SetStackSizeByType(const char_t* const configPath, rtLimitType_t limitType, const std::string& typeName)
     135             :     {
     136          90 :         size_t stackSize = 0;
     137          90 :         bool stackSizeExist = false;
     138             : 
     139          90 :         auto ret = acl::JsonParser::GetStackSizeByType(configPath, typeName, stackSize, stackSizeExist);
     140          90 :         if (ret != ACL_SUCCESS) {
     141           3 :             return ACL_ERROR_FAILURE;
     142             :         }
     143             : 
     144          87 :         if (!stackSizeExist) {
     145             :             // 如果 stackSizeExist 为 false,直接返回 ACL_SUCCESS
     146          69 :             return ACL_SUCCESS;
     147             :         }
     148             : 
     149          18 :         rtError_t rtErr = rtDeviceSetLimit(0, limitType, static_cast<uint32_t>(stackSize));
     150          18 :         if (rtErr != RT_ERROR_NONE) {
     151           3 :             ACL_LOG_CALL_ERROR(
     152             :                 "set limit (%s %zu) failed, runtime result = %d.", typeName.c_str(), stackSize,
     153             :                 static_cast<int32_t>(rtErr));
     154           3 :             return ACL_GET_ERRCODE_RTS(rtErr);
     155             :         }
     156          15 :         ACL_LOG_INFO("get %s stack size %zu success\n", typeName.c_str(), stackSize);
     157          15 :         return ACL_SUCCESS;
     158             :     }
     159          32 :     aclError SetAllStackSizes(const char_t* const configPath)
     160             :     {
     161         119 :         for (const auto& entry : limitToKeyMap) {
     162          90 :             rtLimitType_t limitType = entry.first;
     163          90 :             const std::string& typeName = entry.second;
     164             : 
     165          90 :             aclError ret = SetStackSizeByType(configPath, limitType, typeName.c_str());
     166          90 :             if (ret == ACL_ERROR_FAILURE) {
     167           3 :                 return ret; // 如果返回 ACL_ERROR_FAILURE,直接返回错误
     168             :             }
     169             :         }
     170          29 :         return ACL_SUCCESS;
     171             :     }
     172             : 
     173             :     const std::map<rtLimitType_t, std::string> fifoSizeToKeyMap = {
     174             :         {RT_LIMIT_TYPE_SIMD_PRINTF_FIFO_SIZE_PER_CORE, "simd_printf_fifo_size_per_core"},
     175             :         {RT_LIMIT_TYPE_SIMT_PRINTF_FIFO_SIZE, "simt_printf_fifo_size"}};
     176             : 
     177          31 :     aclError SetPrintFifoSizeByType(const char_t* const configPath, rtLimitType_t limitType, const std::string& typeName)
     178             :     {
     179          31 :         size_t fifoSize = 0;
     180          31 :         bool found = false;
     181             : 
     182          31 :         auto ret = acl::JsonParser::GetPrintFifoSizeByType(configPath, typeName, fifoSize, found);
     183          31 :         if (ret != ACL_SUCCESS) {
     184           2 :             return ACL_ERROR_FAILURE;
     185             :         }
     186             : 
     187          29 :         if (!found) {
     188          26 :             return ACL_SUCCESS;
     189             :         }
     190             : 
     191           3 :         rtError_t rtErr = rtDeviceSetLimit(0, limitType, static_cast<uint32_t>(fifoSize));
     192           3 :         if (rtErr != RT_ERROR_NONE) {
     193           1 :             ACL_LOG_CALL_ERROR("set limit (%s %zu) failed, runtime result = %d.", typeName.c_str(), fifoSize,
     194             :                 static_cast<int32_t>(rtErr));
     195           1 :             return ACL_GET_ERRCODE_RTS(rtErr);
     196             :         }
     197           2 :         ACL_LOG_INFO("set %s fifo size %zu success", typeName.c_str(), fifoSize);
     198           2 :         return ACL_SUCCESS;
     199             :     }
     200             : 
     201          17 :     aclError SetPrintFifoSizes(const char_t* const configPath)
     202             :     {
     203          45 :         for (const auto& entry : fifoSizeToKeyMap) {
     204          31 :             rtLimitType_t limitType = entry.first;
     205          31 :             const std::string& typeName = entry.second;
     206             : 
     207          31 :             aclError ret = SetPrintFifoSizeByType(configPath, limitType, typeName);
     208          31 :             if (ret != ACL_SUCCESS) {
     209           3 :                 return ret;
     210             :             }
     211             :         }
     212          14 :         return ACL_SUCCESS;
     213             :     }
     214             : }
     215             : 
     216             : namespace acl {
     217         463 : void resetAclJsonHash()
     218             : {
     219         463 :     aclInitJsonHash.clear();
     220         463 : }
     221             : 
     222           6 : void aclGetMsgCallback(const char_t *msg, uint32_t len)
     223             : {
     224           6 :     if (msg == nullptr) {
     225           1 :         return;
     226             :     }
     227           5 :     (void)aclRecentErrMsg.assign(msg, static_cast<size_t>(len));
     228             : }
     229             : 
     230           6 : int32_t UpdateOpSystemRunCfg(void *cfgAddr, uint32_t cfgLen)
     231             : {
     232           6 :     ACL_LOG_INFO("start to execute UpdateOpSystemRunCfg");
     233           6 :     if ((cfgAddr == nullptr) || (static_cast<size_t>(cfgLen) < sizeof(size_t))) {
     234           2 :         ACL_LOG_ERROR("UpdateOpSystemRunCfg failed, invalid config address(null) or invalid length %u.", cfgLen);
     235           2 :         return ACL_ERROR_RT_PARAM_INVALID;
     236             :     }
     237             : 
     238             :     // get device id
     239           4 :     int32_t devId = 0;
     240           4 :     auto rtErr = rtGetDevice(&devId);
     241           4 :     if (rtErr != RT_ERROR_NONE) {
     242           1 :         ACL_LOG_ERROR("can not get device id, runtime errorCode is %d", rtErr);
     243           1 :         return rtErr;
     244             :     }
     245             : 
     246           3 :     uint64_t offset = 0;
     247             :     // rts interface
     248           3 :     rtErr = rtGetL2CacheOffset(devId, &offset);
     249           3 :     if (rtErr != RT_ERROR_NONE) {
     250           2 :         if (rtErr == ACL_ERROR_RT_FEATURE_NOT_SUPPORT) {
     251           1 :             ACL_LOG_WARN("can not get l2 cache offset, feature not support, device id = %d", devId);
     252             :         } else {
     253           1 :             ACL_LOG_ERROR("can not get l2 cache offset, runtime errorCode is %d, device id = %d", rtErr, devId);
     254             :         }
     255           2 :         return rtErr;
     256             :     }
     257             : 
     258           1 :     uint64_t *addr = static_cast<uint64_t *>(cfgAddr);
     259           1 :     *addr = offset;
     260             : 
     261           1 :     ACL_LOG_INFO("execute UpdateOpSystemRunCfg successfully, l2 cache offset is %lu, device id = %d", offset, devId);
     262           1 :     return ACL_RT_SUCCESS;
     263             : }
     264             : 
     265          40 : aclError HandleErrorManagerConfig(const char_t *const configPath, error_message::ErrorMessageMode &error_mode) {
     266         120 :     const std::string ACL_ERR_MSG_CONFIG_NAME = "err_msg_mode";
     267         120 :     const std::string INTERNAL_MODE = "\"0\"";
     268         120 :     const std::string PROCESS_MODE = "\"1\"";
     269          40 :     error_mode = error_message::ErrorMessageMode::INTERNAL_MODE;
     270             : 
     271          40 :     if ((configPath != nullptr) && (strlen(configPath) != 0UL)) {
     272          26 :         std::string strConfig = PROCESS_MODE;
     273          26 :         bool found = false;
     274          26 :         auto ret = acl::JsonParser::GetJsonCtxByKey(configPath, strConfig, ACL_ERR_MSG_CONFIG_NAME, found);
     275          26 :         if (ret != ACL_SUCCESS) {
     276           1 :             ACL_LOG_INNER_ERROR("can not parse err_msg config from file[%s], errorCode = %d", configPath, ret);
     277           1 :             return ret;
     278             :         }
     279          25 :         if (!found) {
     280          21 :             return ACL_SUCCESS;
     281             :         }
     282           4 :         ACL_LOG_INFO("err_msg mode is set [%s].", strConfig.c_str());
     283           4 :         if (strConfig == INTERNAL_MODE) {
     284           1 :             error_mode = error_message::ErrorMessageMode::INTERNAL_MODE;
     285           3 :         } else if (strConfig == PROCESS_MODE) {
     286           1 :             error_mode = error_message::ErrorMessageMode::PROCESS_MODE;
     287             :         } else {
     288           2 :             ACL_LOG_INNER_ERROR("err_msg mode config is invalid %s", strConfig.c_str());
     289           2 :             return ACL_ERROR_INVALID_PARAM;
     290             :         }
     291             :     }
     292          16 :     return ACL_SUCCESS;
     293             : }
     294             : 
     295          15 : aclError HandleEventModeConfig(const char_t *const configPath) {
     296          15 :     ACL_LOG_INFO("Start to execute HandleEventModeConfig, configPath:[%s].", configPath);
     297          30 :     std::string strConfig;
     298          15 :     uint8_t event_mode = 0;
     299          15 :     bool found = false;
     300             : 
     301          15 :     auto ret = acl::JsonParser::GetEventModeFromFile(configPath, event_mode, found);
     302          15 :     if (ret != ACL_SUCCESS) {
     303           2 :         ACL_LOG_ERROR("Can not parse event mode config from file[%s], errorCode = %d", configPath, ret);
     304           2 :         return ret;
     305             :     }
     306          13 :     if (!found) {
     307          11 :         ACL_LOG_INFO("Event mode config is not found in file[%s].", configPath);
     308          11 :         return ACL_SUCCESS;
     309             :     }
     310           2 :     ACL_LOG_INFO("event mode is set [%d].", event_mode);
     311           2 :     ACL_REQUIRES_CALL_RTS_OK(rtEventWorkModeSet(event_mode), rtEventWorkModeSet);
     312           2 :     ACL_LOG_INFO("Successfully handled event mode config.");
     313           2 :     return ACL_SUCCESS;
     314             : }
     315             : 
     316          17 : aclError HandlePrintFifoSizeConfig(const char_t *const configPath) {
     317          17 :     ACL_REQUIRES_OK(SetPrintFifoSizes(configPath));
     318          14 :     return ACL_SUCCESS;
     319             : }
     320             : 
     321          32 : aclError HandleDefaultDeviceAndStackSize(const char_t *const configPath) {
     322             :     // 调用批量设置函数
     323          32 :     ACL_REQUIRES_OK(SetAllStackSizes(configPath));
     324             :     // 设置默认设备
     325          29 :     int32_t defaultDeviceId = INVALID_DEFAULT_DEVICE;
     326          29 :     auto ret = acl::JsonParser::GetDefaultDeviceIdFromFile(configPath, defaultDeviceId);
     327          29 :     if (ret != ACL_SUCCESS) {
     328           3 :         return ACL_ERROR_FAILURE;
     329             :     }
     330          26 :     if (defaultDeviceId == INVALID_DEFAULT_DEVICE) {
     331          22 :         return ACL_SUCCESS;
     332             :     }
     333           4 :     rtError_t rtErr = rtSetDefaultDeviceId(defaultDeviceId);
     334           4 :     if (rtErr != RT_ERROR_NONE) {
     335           2 :         ACL_LOG_CALL_ERROR("set default device id failed, ret:%d", rtErr);
     336           2 :         return ACL_GET_ERRCODE_RTS(rtErr);
     337             :     }
     338           2 :     isEnableDefaultDevice = true;
     339           2 :     ACL_LOG_INFO("set default device %d success\n", defaultDeviceId);
     340           2 :     return ACL_SUCCESS;
     341             : }
     342             : 
     343             : 
     344          48 : bool IsEnableAutoUCMemeory()
     345             : {
     346          48 :     const char_t *autoUcMemory = nullptr;
     347          48 :     MM_SYS_GET_ENV(MM_ENV_AUTO_USE_UC_MEMORY, autoUcMemory);
     348             :     // enable: env does not exist or set to 1
     349          48 :     bool enable = ((autoUcMemory == nullptr) || (strlen(autoUcMemory) == 0UL) || (autoUcMemory[0] == '1'));
     350          48 :     ACL_LOG_INFO("auto-uc-memory is %s.", enable ? "enabled" : "disabled");
     351          48 :     return enable;
     352             : }
     353             : 
     354          20 : void GetAllPackageVersion()
     355             : {
     356         180 :     for (const auto &pkgName : kMapToPkgName) {
     357         160 :         aclCANNPackageVersion pkgVersion = {};
     358         160 :         auto ret = aclsysGetCANNVersionImpl(pkgName.first, &pkgVersion);
     359         160 :         if (ret == ACL_SUCCESS) {
     360          39 :             ACL_LOG_EVENT("Version of %s package is %s", pkgName.second.c_str(), pkgVersion.version);
     361             :         } else {
     362         121 :             ACL_LOG_EVENT("Version of %s package is not found", pkgName.second.c_str());
     363             :         }
     364             :     }
     365          20 : }
     366             : }
     367             : 
     368          52 : aclError aclInitImpl(const char *configPath)
     369             : {
     370          52 :     ACL_LOG_INFO("start to execute aclInit");
     371         104 :     const std::unique_lock<std::recursive_mutex> lk(acl::GetAclInitMutex());
     372             : 
     373          52 :     auto &aclInitRefCount = acl::GetAclInitRefCount();
     374          52 :     if (aclInitRefCount > 0) {
     375          10 :         aclInitRefCount++;
     376          10 :         ACL_LOG_INFO("repeatedly initialized, new aclInitRefCount: %lu", aclInitRefCount);
     377          10 :         return ACL_ERROR_REPEAT_INITIALIZE;
     378             :     }
     379             : 
     380          84 :     std::string configStr;
     381          42 :     auto ret = acl::GetStrFromConfigPath(configPath, configStr);
     382          42 :     if (ret != ACL_SUCCESS) {
     383           1 :       ACL_LOG_INNER_ERROR("Get Content from configPath failed, ret=%d", ret);
     384           1 :       return ret;
     385             :     }
     386          41 :     acl::SetConfigPathStr(configStr);
     387             : 
     388             :     // 读取并计算当前文件的哈希值(若文件不存在或无法打开,上面的json_parser中会检验住,此处无须再次判断)
     389          82 :     std::string currentHash;
     390          41 :     acl::hash_utils::CalculateSimpleHash(configPath, configStr, currentHash);
     391             :     // 内容不一致
     392          41 :     if (!aclInitJsonHash.empty() && currentHash != aclInitJsonHash) {
     393           1 :         ACL_LOG_ERROR("config content of [%s] differs from the first aclInit config file path: [%s]", configPath, aclInitJsonPath.c_str());
     394           1 :         return ACL_ERROR_INVALID_PARAM;
     395             :     }
     396             : 
     397          40 :     error_message::ErrorMessageMode error_mode = error_message::ErrorMessageMode::INTERNAL_MODE;
     398          40 :     ACL_LOG_INFO("call ErrorManager.Initialize");
     399          40 :     ret = acl::HandleErrorManagerConfig(configPath, error_mode);
     400          40 :     if (ret != ACL_SUCCESS) {
     401           3 :         ACL_LOG_INNER_ERROR("[Process][ErrorMsg]process HandleErrorManagerConfig failed, ret=%d", ret);
     402           3 :         return ret;
     403             :     }
     404             : 
     405          37 :     int32_t initRet = static_cast<uint32_t>(error_message::ErrMgrInit(error_mode));
     406          37 :     if (initRet != 0) {
     407           1 :         ACL_LOG_WARN("can not init ge errorManager, ge errorCode = %d", initRet);
     408             :     }
     409             : 
     410          37 :     if (DlogReportInitialize() != 0) {
     411          37 :         ACL_LOG_WARN("can not init device's log module");
     412             :     }
     413             : 
     414             :     // init acl_model
     415          37 :     auto cfgStr = configStr.c_str();
     416          37 :     auto cfgLen = configStr.size();
     417          37 :     ret = acl::InitCallbackManager::GetInstance().NotifyInitCallback(ACL_REG_TYPE_ACL_MODEL,
     418             :                                                                      cfgStr, cfgLen);
     419          37 :     if (ret != ACL_SUCCESS) {
     420           1 :       ACL_LOG_INNER_ERROR("call acl_model init callback failed, ret:%d", ret);
     421           1 :       return ret;
     422             :     }
     423             : 
     424          36 :     if ((configPath != nullptr) && (strlen(configPath) != 0UL)) {
     425             :         // config dump
     426          23 :         ACL_LOG_INFO("set DumpConfig in aclInit");
     427          23 :         ret = acl::AclDump::GetInstance().HandleDumpConfig(configPath);
     428          23 :         if (ret != ACL_SUCCESS) {
     429           0 :             ACL_LOG_INNER_ERROR("[Process][DumpConfig]process HandleDumpConfig failed");
     430           0 :             return ret;
     431             :         }
     432          23 :         ACL_LOG_INFO("set HandleDumpConfig success in aclInit");
     433             : 
     434             :         // init acl_op_executor
     435          23 :         ret = acl::InitCallbackManager::GetInstance().NotifyInitCallback(ACL_REG_TYPE_ACL_OP_EXECUTOR,
     436             :                                                                          cfgStr, cfgLen);
     437          23 :         if (ret != ACL_SUCCESS) {
     438           1 :           ACL_LOG_INNER_ERROR("call acl_op_executor init callback failed, ret:%d", ret);
     439           1 :           return ret;
     440             :         }
     441             : 
     442          22 :         ACL_LOG_INFO("set HandleDefaultDeviceAndStackSize in aclInit");
     443             :         // parse configPath for defaultDevice and call rtSetDefaultDeviced; parse device limit
     444          22 :         ret = acl::HandleDefaultDeviceAndStackSize(configPath);
     445          22 :         if (ret != ACL_SUCCESS) {
     446           5 :             ACL_LOG_INNER_ERROR("[Process][DefaultDevice]process HandleDefaultDevice failed");
     447           5 :             return ret;
     448             :         }
     449          17 :         ACL_LOG_INFO("set HandleDefaultDeviceAndStackSize success in aclInit");
     450             : 
     451             :         // print fifo size config
     452          17 :         ret = acl::HandlePrintFifoSizeConfig(configPath);
     453          17 :         if (ret != ACL_SUCCESS) {
     454           3 :             ACL_LOG_INNER_ERROR("[Process][PrintFifoSize]process HandlePrintFifoSizeConfig failed, ret=%d", ret);
     455           3 :             return ret;
     456             :         }
     457          14 :         ACL_LOG_INFO("set HandlePrintFifoSizeConfig success in aclInit");
     458             : 
     459          14 :         ret = acl::HandleEventModeConfig(configPath);
     460          14 :         if (ret != ACL_SUCCESS) {
     461           1 :             ACL_LOG_INNER_ERROR("[Process][EventMode]process HandleEventModeConfig failed, ret=%d", ret);
     462           1 :             return ret;
     463             :         }
     464             :     }
     465          26 :     const auto profRet = MsprofRegisterCallback(ASCENDCL, &acl::AclProfCtrlHandle);
     466          26 :     if (profRet != 0) {
     467          26 :         ACL_LOG_WARN("can not register Callback, prof result = %d", profRet);
     468             :     }
     469             : 
     470             :     // config profiling
     471          26 :     ACL_LOG_INFO("set ProfilingConfig in aclInit");
     472          26 :     ret = acl::AclProfiling::HandleProfilingConfig(configPath);
     473          26 :     if (ret != ACL_SUCCESS) {
     474           0 :         ACL_LOG_INNER_ERROR("[Process][ProfConfig]process HandleProfilingConfig failed");
     475           0 :         return ret;
     476             :     }
     477             : 
     478             :     // get socVersion
     479          26 :     const char *socName = aclrtGetSocNameImpl();
     480          26 :     if (socName == nullptr) {
     481           0 :         ACL_LOG_INNER_ERROR("[Init][Version]init soc version failed.");
     482           0 :         return ACL_ERROR_INTERNAL_ERROR;
     483             :     }
     484             : 
     485             :     // init acl dvpp
     486          26 :     ret = acl::InitCallbackManager::GetInstance().NotifyInitCallback(ACL_REG_TYPE_ACL_DVPP,
     487             :                                                                      cfgStr, cfgLen);
     488          26 :     if (ret != ACL_SUCCESS) {
     489           1 :         ACL_LOG_INNER_ERROR("call acl_dvpp init callback failed, ret:%d", ret);
     490           1 :         return ret;
     491             :     }
     492             : 
     493             :     // register kernel launch fill function
     494          25 :     if (acl::IsEnableAutoUCMemeory()) {
     495          25 :         ACL_LOG_INFO("register kernel launch fill function in aclInit");
     496          25 :         auto rtRegErr = rtRegKernelLaunchFillFunc("g_opSystemRunCfg", acl::UpdateOpSystemRunCfg);
     497          25 :         if (rtRegErr != RT_ERROR_NONE) {
     498           2 :             if (rtRegErr == ACL_ERROR_RT_FEATURE_NOT_SUPPORT) {
     499           1 :                 ACL_LOG_WARN("can not register kernel launch fill function, feature not support.");
     500             :             } else {
     501           1 :                 ACL_LOG_INNER_ERROR("[Init][RegFillFunc]register failed,ret = %d.", rtRegErr);
     502           1 :                 return ACL_GET_ERRCODE_RTS(rtRegErr);
     503             :             }
     504             :         }
     505             :     }
     506             : 
     507          24 :     ret = acl::InitCallbackManager::GetInstance().NotifyInitCallback(ACL_REG_TYPE_OTHER, cfgStr, cfgLen);
     508          24 :     if (ret != ACL_SUCCESS) {
     509           4 :       ACL_LOG_ERROR("[Init][NotifyCallback]notify other init callback failed, ret = %d", ret);
     510           4 :       return ret;
     511             :     }
     512             : 
     513          20 :     acl::GetAllPackageVersion();
     514             : 
     515          20 :     aclFinalizeFlag = false;
     516          20 :     aclInitRefCount = 1;
     517             :     // 如果 aclJsonHash 为空,说明是第一次调用,设置aclJsonHash
     518          20 :     if (aclInitJsonHash.empty()) {
     519          15 :         aclInitJsonHash = currentHash;
     520          15 :         if (configPath != nullptr) {
     521          11 :             aclInitJsonPath = configPath;
     522             :         }
     523             :     }
     524          20 :     ACL_LOG_INFO("successfully execute aclInit, aclInitRefCount is %lu",aclInitRefCount);
     525          20 :     return ACL_SUCCESS;
     526             : }
     527             : 
     528          30 : aclError aclFinalizeInternal()
     529             : {
     530          30 :     ACL_LOG_INFO("start to execute aclFinalizeInternal");
     531             : 
     532          30 :     if (DlogReportFinalize() != 0) {
     533          30 :         ACL_LOG_WARN("can not init device's log module");
     534             :     }
     535          30 :     acl::ResourceStatistics::GetInstance().TraverseStatistics();
     536          30 :     const int32_t profRet = MsprofFinalize();
     537          30 :     if (profRet != MSPROF_ERROR_NONE) {
     538           0 :         ACL_LOG_CALL_ERROR("[Finalize][Profiling]failed to call MsprofFinalize, prof errorCode = %d", profRet);
     539             :     }
     540             : 
     541          30 :     auto ret = acl::InitCallbackManager::GetInstance().NotifyFinalizeCallback(ACL_REG_TYPE_ACL_OP_COMPILER);
     542          30 :     if (ret != ACL_SUCCESS) {
     543           1 :       ACL_LOG_INNER_ERROR("call acl_op_compiler finalize callback failed, ret:%d", ret);
     544           1 :       return ret;
     545             :     }
     546             : 
     547          29 :     ret = acl::InitCallbackManager::GetInstance().NotifyFinalizeCallback(ACL_REG_TYPE_ACL_MODEL);
     548          29 :     if (ret != ACL_SUCCESS) {
     549           3 :       ACL_LOG_INNER_ERROR("call acl_model finalize callback failed, ret:%d", ret);
     550           3 :       return ret;
     551             :     }
     552             : 
     553          26 :     if (acl::AclDump::GetInstance().GetAdxInitFromAclInitFlag()) {
     554          26 :         const int32_t adxRet = AdxDataDumpServerUnInit();
     555          26 :         if (adxRet != 0) {
     556           1 :             ACL_LOG_CALL_ERROR("[Generate][DumpFile]generate dump file failed in disk, adx errorCode = %d", adxRet);
     557           1 :             return ACL_ERROR_INTERNAL_ERROR;
     558             :         }
     559             :     }
     560             : 
     561             :     // finalize acl dvpp
     562          25 :     ret = acl::InitCallbackManager::GetInstance().NotifyFinalizeCallback(ACL_REG_TYPE_ACL_DVPP);
     563          25 :     if (ret != ACL_SUCCESS) {
     564           2 :         ACL_LOG_INNER_ERROR("call acl_dvpp finalize callback failed, ret:%d", ret);
     565           2 :         return ret;
     566             :     }
     567             : 
     568          23 :     if (acl::IsEnableAutoUCMemeory()) {
     569             :         // unregister kernel launch fill function
     570          23 :         ACL_LOG_INFO("unregister kernel launch fill function in aclFinalize");
     571          23 :         auto rtRegErr = rtUnRegKernelLaunchFillFunc("g_opSystemRunCfg");
     572          23 :         if (rtRegErr != RT_ERROR_NONE) {
     573           2 :             if (rtRegErr == ACL_ERROR_RT_FEATURE_NOT_SUPPORT) {
     574           1 :                 ACL_LOG_WARN("can not unregister kernel launch fill function, feature not support.");
     575             :             } else {
     576           1 :                 ACL_LOG_INNER_ERROR("Finalize][UnRegFillFunc]unregister failed,ret = %d.", rtRegErr);
     577           1 :                 return ACL_GET_ERRCODE_RTS(rtRegErr);
     578             :             }
     579             :         }
     580             :     }
     581             : 
     582             :     // disable default device
     583          22 :     if (isEnableDefaultDevice) {
     584          20 :         ACL_LOG_INFO("disable default device");
     585          20 :         const auto rtErr = rtSetDefaultDeviceId(ACL_DEFAULT_DEVICE_DISABLE);
     586          20 :         if (rtErr != RT_ERROR_NONE) {
     587           1 :             ACL_LOG_WARN("close default device failed, ret:%d", rtErr);
     588           1 :             return ACL_GET_ERRCODE_RTS(rtErr);
     589             :         }
     590             :     }
     591             : 
     592          21 :     ret = acl::InitCallbackManager::GetInstance().NotifyFinalizeCallback(ACL_REG_TYPE_OTHER);
     593          21 :     if (ret != ACL_SUCCESS) {
     594           1 :       ACL_LOG_ERROR("[Init][NotifyCallback]notify other finalize callback failed, ret = %d", ret);
     595           1 :       return ret;
     596             :     }
     597             : 
     598          20 :     aclFinalizeFlag = true;
     599          20 :     auto &aclInitRefCount = acl::GetAclInitRefCount();
     600          20 :     aclInitRefCount = 0;
     601          20 :     ACL_LOG_INFO("execute aclFinalizeInternal successfully");
     602          20 :     return ACL_SUCCESS;
     603             : }
     604             : 
     605          27 : aclError aclFinalizeImpl()
     606             : {
     607          27 :     ACL_LOG_INFO("start to execute aclFinalize");
     608          54 :     const std::unique_lock<std::recursive_mutex> lk(acl::GetAclInitMutex());
     609          27 :     if (aclFinalizeFlag) {
     610           0 :         ACL_LOG_INNER_ERROR("[Finalize][Acl]repeatedly finalized");
     611           0 :         return ACL_ERROR_REPEAT_FINALIZE;
     612             :     }
     613             : 
     614          27 :     const aclError ret = aclFinalizeInternal();
     615          27 :     if (ret != ACL_SUCCESS) {
     616           9 :         ACL_LOG_INNER_ERROR("[Finalize][Acl]finalize internal failed, errorCode = %d", ret);
     617           9 :         return ret;
     618             :     }
     619          18 :     ACL_LOG_INFO("successfully execute aclFinalize");
     620          18 :     return ACL_SUCCESS;
     621             : }
     622             : 
     623          14 : aclError aclFinalizeReferenceImpl(uint64_t *refCount)
     624             : {
     625          14 :     ACL_LOG_INFO("start to execute aclFinalizeReference");
     626          28 :     const std::unique_lock<std::recursive_mutex> lk(acl::GetAclInitMutex());
     627          14 :     auto &aclInitRefCount = acl::GetAclInitRefCount();
     628          14 :     if (refCount != nullptr) {
     629          14 :         *refCount = aclInitRefCount;
     630             :     }
     631             :     // 如果计数器大于1,则减少计数器并返回
     632          14 :     if (aclInitRefCount > 1) {
     633          10 :         aclInitRefCount--;
     634          10 :         if (refCount != nullptr) {
     635          10 :             *refCount = aclInitRefCount;
     636             :         }
     637          10 :         ACL_LOG_INFO("Found multiple acl references, reducing aclInitRefCount by 1. New aclInitRefCount: %lu", aclInitRefCount);
     638          10 :         return ACL_SUCCESS;
     639             :     }
     640             :     // 如果计数器小于1,报错
     641           4 :     if (aclInitRefCount < 1) {
     642           1 :         ACL_LOG_INNER_ERROR("[Finalize][Acl]aclFinalizeReference called repeatedly or called without proper aclInit");
     643           1 :         return ACL_ERROR_REPEAT_FINALIZE;
     644             :     }
     645             : 
     646             :     // 如果计数器等于1,则执行实际的资源清理操作
     647           3 :     const aclError ret = aclFinalizeInternal();
     648           3 :     if (refCount != nullptr) {
     649           3 :         *refCount = aclInitRefCount;
     650             :     }
     651           3 :     if (ret != ACL_SUCCESS) {
     652           1 :         ACL_LOG_INNER_ERROR("[Finalize][Acl]finalize internal failed, errorCode = %d", ret);
     653           1 :         return ret;
     654             :     }
     655           2 :     ACL_LOG_INFO("successfully execute aclFinalizeReference");
     656           2 :     return ACL_SUCCESS;
     657             : }
     658             : 
     659         189 : bool IsFileExist(const std::string &path)
     660             : {
     661         189 :     char_t realPath[MMPA_MAX_PATH] = {};
     662         189 :     return mmRealPath(path.c_str(), realPath, MMPA_MAX_PATH) == EN_OK;
     663             : }
     664             : 
     665          47 : bool ParseVersionInfo(const std::string &path, std::string &versionInfo)
     666             : {
     667          94 :     std::ifstream ifs(path, std::ifstream::in);
     668          47 :     if (!ifs.is_open()) {
     669           0 :         ACL_LOG_ERROR("[Check]Open file [%s] failed, reason is [%s].", path.c_str(), strerror(errno));
     670           0 :         return false;
     671             :     }
     672             : 
     673          94 :     std::string line;
     674          94 :     std::string lineVersion;
     675          51 :     while (std::getline(ifs, line)) {
     676          48 :         const auto &pos = line.find(kVersionInfoKey);
     677          48 :         if (pos != std::string::npos) {
     678          44 :             ACL_LOG_DEBUG("Parse version success, content is [%s].", line.c_str());
     679          44 :             lineVersion = line.substr(pos + strlen(kVersionInfoKey));
     680          44 :             break;
     681             :         }
     682             :     }
     683          47 :     ifs.close();
     684             : 
     685          47 :     if (!lineVersion.empty()) {
     686          44 :         versionInfo = lineVersion;
     687          44 :         return true;
     688             :     }
     689           3 :     return false;
     690             : }
     691             : 
     692          44 : bool FillinPackageVersion(const std::string &versionInfo, aclCANNPackageVersion &version)
     693             : {
     694          88 :     std::string versionAlternative = ConvertVersion(versionInfo);
     695          44 :     (void)memset_s(&version, sizeof(aclCANNPackageVersion), 0, sizeof(aclCANNPackageVersion));
     696          88 :     std::vector<std::string> parts;
     697          44 :     acl::StringUtils::Split(versionAlternative, '.', parts);
     698          44 :     constexpr uint32_t pkgVersionPartsMinCount = 2;
     699          44 :     constexpr uint32_t pkgVersionPartsMaxCount = 4;
     700             : 
     701          44 :     if (parts.size() < pkgVersionPartsMinCount) {
     702           2 :         return false;
     703             :     }
     704             : 
     705          81 :     while (parts.size() < pkgVersionPartsMaxCount) {
     706          39 :         parts.push_back("0");
     707             :     }
     708             : 
     709          42 :     if ((versionAlternative.copy(version.version, ACL_PKG_VERSION_MAX_SIZE - 1) > 0) &&
     710          42 :         (parts[0].copy(version.majorVersion, ACL_PKG_VERSION_PARTS_MAX_SIZE - 1) > 0) &&
     711          42 :         (parts[1].copy(version.minorVersion, ACL_PKG_VERSION_PARTS_MAX_SIZE - 1) > 0) &&
     712         126 :         (parts[2].copy(version.releaseVersion, ACL_PKG_VERSION_PARTS_MAX_SIZE - 1) > 0) &&
     713          42 :         (parts[3].copy(version.patchVersion, ACL_PKG_VERSION_PARTS_MAX_SIZE - 1) > 0)) {
     714          42 :         return true;
     715             :     }
     716             : 
     717           0 :     return false;
     718             : }
     719             : 
     720          28 : bool GetDriverPath(const std::string &ascendInstallPath, std::string &driverPath)
     721             : {
     722          28 :     if (!IsFileExist(ascendInstallPath)) {
     723          21 :         ACL_LOG_WARN("[Check]ascendInstallPath [%s] does not exist.", ascendInstallPath.c_str());
     724          21 :         return false;
     725             :     }
     726             : 
     727          14 :     std::ifstream ifs(ascendInstallPath, std::ifstream::in);
     728           7 :     if (!ifs.is_open()) {
     729           0 :         ACL_LOG_ERROR("[Check]Open file [%s] failed, reason is [%s].", ascendInstallPath.c_str(), strerror(errno));
     730           0 :         return false;
     731             :     }
     732             : 
     733           7 :     driverPath.clear();
     734          14 :     std::string line;
     735           8 :     while (std::getline(ifs, line)) {
     736           7 :         const auto &pos = line.find(kDriverPathKey);
     737           7 :         if (pos == std::string::npos) {
     738           1 :             continue;
     739             :         }
     740           6 :         ACL_LOG_DEBUG("Parse driver path success, content is [%s].", line.c_str());
     741           6 :         driverPath = line.substr(pos + strlen(kDriverPathKey));
     742           6 :         if (!driverPath.empty()) {
     743           6 :             ifs.close();
     744           6 :             ACL_LOG_INFO("driver path is [%s].", driverPath.c_str());
     745           6 :             return true;
     746             :         }
     747             :     }
     748           1 :     ifs.close();
     749           1 :     return false;
     750             : }
     751             : 
     752         103 : aclError GetCANNVersionInternal(const aclCANNPackageName name, aclCANNPackageVersion &version,
     753             :     const std::string &installPath)
     754             : {
     755         206 :     std::string pkgName = kMapToPkgName.at(name);
     756             : 
     757         412 :     std::string versionInfoPath = installPath + "/" + pkgName + "/version.info";
     758         103 :     if (!IsFileExist(versionInfoPath)) {
     759          57 :         ACL_LOG_INFO("[Check]versionInfoPath [%s] does not exist, try use Alternative versionInfoPath.", versionInfoPath.c_str());
     760          57 :         std::string pkgNameAlternative = pkgName;
     761          57 :         if (pkgName.find('-') != std::string::npos) {
     762          40 :             std::replace(pkgNameAlternative.begin(), pkgNameAlternative.end(), '-', '_');
     763             :         }
     764          57 :         versionInfoPath = installPath + "/" + pkgNameAlternative + "/version.info";
     765          57 :         ACL_LOG_INFO("[Check]use Alternative versionInfoPath [%s].", versionInfoPath.c_str());
     766          57 :         if (!IsFileExist(versionInfoPath)) {
     767          56 :             ACL_LOG_WARN("[Check]versionInfoPath [%s] does not exist.", versionInfoPath.c_str());
     768          56 :             return ACL_ERROR_INVALID_FILE;
     769             :         }
     770             :     }
     771             : 
     772          94 :     std::string versionInfo;
     773          47 :     if (!ParseVersionInfo(versionInfoPath, versionInfo)) {
     774           3 :         ACL_LOG_ERROR("[Check]failed to parse versionInfo, the versionInfoPath is [%s].",
     775             :             versionInfoPath.c_str());
     776           3 :         return ACL_ERROR_INVALID_FILE;
     777             :     }
     778             : 
     779          44 :     ACL_LOG_INFO("versionInfo is [%s].", versionInfo.c_str());
     780          44 :     if (!FillinPackageVersion(versionInfo, version)) {
     781           2 :         ACL_LOG_ERROR("[Check]failed to run FillinPackageVersion.");
     782           2 :         return ACL_ERROR_INVALID_FILE;
     783             :     }
     784             : 
     785          42 :     return ACL_SUCCESS;
     786             : }
     787             : 
     788         167 : aclError aclsysGetCANNVersionImpl(aclCANNPackageName name, aclCANNPackageVersion *version)
     789             : {
     790         167 :     ACL_LOG_INFO("start to execute aclsysGetCANNVersion.");
     791         167 :     ACL_REQUIRES_NOT_NULL_WITH_INPUT_REPORT(version);
     792         167 :     ACL_LOG_INFO("enum name id is [%d], enum name is [%s].", (int32_t)name,
     793             :         kMapToPkgName.count(name) ? kMapToPkgName.at(name).c_str() : "unknown" );
     794             : 
     795         167 :     char *pathEnv = nullptr;
     796         167 :     std::string driverPath;
     797         167 :     aclError ret = ACL_SUCCESS;
     798         167 :     switch (name) {
     799         146 :         case ACL_PKG_NAME_CANN:
     800             :         case ACL_PKG_NAME_RUNTIME:
     801             :         case ACL_PKG_NAME_COMPILER:
     802             :         case ACL_PKG_NAME_HCCL:
     803             :         case ACL_PKG_NAME_TOOLKIT:
     804             :         case ACL_PKG_NAME_OPP:
     805             :         case ACL_PKG_NAME_OPP_KERNEL:
     806         146 :             MM_SYS_GET_ENV(MM_ENV_ASCEND_HOME_PATH, pathEnv);
     807         146 :             if (!pathEnv) {
     808          50 :                 ACL_LOG_WARN("[Check]can not get env [%s].", kAscendHomeEnvName);
     809          50 :                 ret = ACL_ERROR_INVALID_FILE;
     810          50 :                 break;
     811             :             }
     812          96 :             ACL_LOG_INFO("value of env [%s] is [%s].", kAscendHomeEnvName, pathEnv);
     813          96 :             ret = GetCANNVersionInternal(name, *version, std::string(pathEnv) + "/share/info");
     814          96 :             break;
     815          20 :         case ACL_PKG_NAME_DRIVER:
     816          20 :             if (!GetDriverPath(kAscendInstallPath, driverPath)) {
     817          20 :                 ret = ACL_ERROR_INVALID_FILE;
     818          20 :                 break;
     819             :             }
     820           0 :             ret = GetCANNVersionInternal(name, *version, driverPath);
     821           0 :             break;
     822           1 :         default:
     823           1 :             ACL_LOG_ERROR("[Check]package name enum id [%d] is invalid.", (int32_t)name);
     824           1 :             ret = ACL_ERROR_INVALID_PARAM;
     825           1 :             break;
     826             :     }
     827         167 :     return ret;
     828             : }
     829             : 
     830           1 : bool GetPkgPath(const std::string &ascendInstallPath, std::string &pkgPath, const std::string &pkgPathKey)
     831             : {
     832             :     // Get the path of driver or firmware
     833           1 :     if (!IsFileExist(ascendInstallPath)) {
     834           0 :         ACL_LOG_WARN("[Check]ascendInstallPath [%s] does not exist. Please check if ASCEND_HOME_PATH is set.", ascendInstallPath.c_str());
     835           0 :         return false;
     836             :     }
     837             : 
     838           2 :     std::ifstream ifs(ascendInstallPath, std::ifstream::in);
     839           1 :     if (!ifs.is_open()) {
     840           0 :         ACL_LOG_ERROR("[Check]Open file [%s] failed, reason is [%s]. Please check if ASCEND_HOME_PATH is set.", ascendInstallPath.c_str(), strerror(errno));
     841           0 :         return false;
     842             :     }
     843             : 
     844           1 :     pkgPath.clear();
     845           2 :     std::string line;
     846           1 :     while (std::getline(ifs, line)) {
     847           1 :         const auto pos = line.find(pkgPathKey);
     848           1 :         if (pos == std::string::npos) {
     849           0 :             continue;
     850             :         }
     851           1 :         ACL_LOG_DEBUG("Parse path success, key is [%s], content is [%s].", pkgPathKey.c_str(), line.c_str());
     852           1 :         pkgPath = line.substr(pos + pkgPathKey.length());
     853           1 :         if (!pkgPath.empty()) {
     854           1 :             ifs.close();
     855           1 :             ACL_LOG_INFO("pkg path is [%s].", pkgPath.c_str());
     856           1 :             return true;
     857             :         }
     858             :     }
     859           0 :     ifs.close();
     860           0 :     return false;
     861             : }
     862             : 
     863          14 : aclError GetVersionStringInternal(const std::string &fullPath, const char_t *pkgName, std::string &versionOut, bool isSilent = false) {
     864          28 :     std::ifstream ifs(fullPath);
     865          14 :     if (!ifs.is_open()) {
     866           2 :         if (isSilent) {
     867           2 :             ACL_LOG_WARN("Version file not found at [%s] (Silent check, will retry alternative).", fullPath.c_str());
     868             :         } else {
     869           0 :             ACL_LOG_ERROR("Version file not found at [%s]. Please check if the package name [%s] is correct and the package is installed.",
     870             :                           fullPath.c_str(), pkgName);
     871             :         }
     872           2 :         return ACL_ERROR_INVALID_FILE;
     873             :     }
     874             : 
     875          24 :     std::string line;
     876          12 :     bool found = false;
     877          12 :     const size_t keyLen = std::strlen(kVersionInfoKey);
     878             : 
     879          13 :     while (std::getline(ifs, line)) {
     880          12 :         size_t pos = line.find(kVersionInfoKey);
     881          12 :         if (pos != std::string::npos) {
     882          11 :             versionOut = acl::StringUtils::Trim(line.substr(pos + keyLen));
     883          11 :             found = true;
     884          11 :             break;
     885             :         }
     886             :     }
     887          12 :     ifs.close();
     888             : 
     889          12 :     if (!found || versionOut.empty()) {
     890           1 :         ACL_LOG_ERROR("Keyword [%s] not found in file [%s].", kVersionInfoKey, fullPath.c_str());
     891           1 :         return ACL_ERROR_INVALID_FILE;
     892             :     }
     893             : 
     894          11 :     return ACL_SUCCESS;
     895             : }
     896             : 
     897          16 : aclError GetVersionByPkgName(const std::string &targetPkgName, std::string &versionContent, bool isSilent) {
     898          32 :     std::string fullPath;
     899             : 
     900             :     // Driver/Firmware
     901          16 :     if (targetPkgName == kDriverPkgName || targetPkgName == kFirmwarePkgName) {
     902           0 :         std::string pkgPath;
     903           0 :         std::string pkgPathKey = (targetPkgName == kDriverPkgName) ? kDriverPathKey : kFirmwarePathKey;
     904             : 
     905           0 :         if (!GetPkgPath(kAscendInstallPath, pkgPath, pkgPathKey)) {
     906           0 :             return ACL_ERROR_INVALID_FILE;
     907             :         }
     908           0 :         fullPath = pkgPath + "/" + targetPkgName + kInfoFileName;
     909             :     } else {
     910          16 :         char *pathEnv = nullptr;
     911          16 :         MM_SYS_GET_ENV(MM_ENV_ASCEND_HOME_PATH, pathEnv);
     912          16 :         if (pathEnv == nullptr) {
     913           1 :             ACL_LOG_WARN("Can not get env [%s]. Please check if ASCEND_HOME_PATH is set.", "ASCEND_HOME_PATH");
     914           1 :             return ACL_ERROR_INVALID_FILE;
     915             :         }
     916          30 :         std::string homePath(pathEnv);
     917          15 :         homePath = acl::file_utils::GetLocalRealPath(homePath);
     918          15 :         if(homePath.empty()){
     919           2 :             ACL_LOG_WARN("ASCEND_HOME_PATH [%s] does not exist.", homePath.c_str());
     920           2 :             return ACL_ERROR_INVALID_FILE;
     921             :         }
     922          13 :         fullPath = homePath + kRelPathInfo + targetPkgName + kInfoFileName;
     923             :     }
     924             : 
     925          13 :     return GetVersionStringInternal(fullPath, targetPkgName.c_str(), versionContent, isSilent);
     926             : }
     927             : 
     928          14 : aclError GetPkgVersionContent(const char *pkgName, std::string &versionContent) {
     929          42 :     std::string originPkgName(pkgName);
     930          28 :     std::string altPkgName = originPkgName;
     931          14 :     bool hasAlternative = false;
     932             : 
     933          14 :     if (originPkgName.find('-') != std::string::npos) {
     934           1 :         std::replace(altPkgName.begin(), altPkgName.end(), '-', '_');
     935           1 :         hasAlternative = true;
     936          13 :     } else if (originPkgName.find('_') != std::string::npos) {
     937           1 :         std::replace(altPkgName.begin(), altPkgName.end(), '_', '-');
     938           1 :         hasAlternative = true;
     939             :     }
     940             : 
     941          14 :     bool isSilent = hasAlternative;
     942             : 
     943          14 :     aclError ret = GetVersionByPkgName(originPkgName, versionContent, isSilent);
     944          14 :     if (ret == ACL_SUCCESS) {
     945           8 :         return ret;
     946             :     }
     947             : 
     948           6 :     if (hasAlternative) {
     949           2 :         ACL_LOG_INFO("Pkg [%s] not found, trying alternative name [%s]...",
     950             :                      originPkgName.c_str(), altPkgName.c_str());
     951             : 
     952           2 :         ret = GetVersionByPkgName(altPkgName, versionContent, false);
     953           2 :         if (ret == ACL_SUCCESS) {
     954           2 :             ACL_LOG_INFO("Found version info using alternative name [%s].", altPkgName.c_str());
     955           2 :             return ACL_SUCCESS;
     956             :         }
     957             :     }
     958             : 
     959           4 :     return ret;
     960             : }
     961             : 
     962           7 : aclError aclsysGetVersionStrImpl(char *pkgName, char *versionStr)
     963             : {
     964           7 :     ACL_LOG_INFO("start to execute aclsysGetVersionStr.");
     965           7 :     ACL_REQUIRES_NOT_NULL_WITH_INPUT_REPORT(versionStr);
     966           7 :     ACL_REQUIRES_NOT_NULL_WITH_INPUT_REPORT(pkgName);
     967             : 
     968          14 :     std::string verInfo;
     969             : 
     970           7 :     aclError ret = GetPkgVersionContent(pkgName, verInfo);
     971           7 :     if (ret != ACL_SUCCESS) {
     972           4 :         return ret;
     973             :     }
     974             : 
     975           3 :     if (strcpy_s(versionStr, ACL_PKG_VERSION_MAX_SIZE, verInfo.c_str()) != EOK) {
     976           0 :         ACL_LOG_ERROR("Copy string failed. Dest buffer size is [%d], source len is [%lu].",
     977             :                       ACL_PKG_VERSION_MAX_SIZE, verInfo.length());
     978           0 :         return ACL_ERROR_INTERNAL_ERROR;
     979             :     }
     980             : 
     981           3 :     ACL_LOG_INFO("aclsysGetVersionStr success. Pkg:[%s], Ver:[%s]", pkgName, versionStr);
     982           3 :     return ret;
     983             : }
     984             : 
     985             : // Allowed format: "001", ".1", "-1"
     986             : // Not allowed format: "..1", ".", "-a", "a"
     987           2 : bool ParsePreNumStrict(const std::string &suffix, int32_t &outNum) {
     988           2 :     if (suffix.empty()) {
     989           0 :         outNum = 0;
     990           0 :         return true;
     991             :     }
     992             : 
     993           2 :     size_t digitPos = std::string::npos;
     994             : 
     995             :     // scan characters
     996           4 :     for (size_t i = 0; i < suffix.length(); ++i) {
     997           4 :         char c = suffix[i];
     998           4 :         if (std::isdigit(static_cast<unsigned char>(c))) {
     999           2 :             digitPos = i;
    1000           2 :             break;
    1001           2 :         } else if (c == '.' || c == '-') {
    1002           2 :             continue; // legal character
    1003             :         } else {
    1004           0 :             return false; // illegal character
    1005             :         }
    1006             :     }
    1007             : 
    1008             :     // No number found.
    1009           2 :     if (digitPos == std::string::npos) {
    1010           0 :         return false;
    1011             :     }
    1012             : 
    1013             :     // Separators more than one.
    1014           2 :     if (digitPos > 1) {
    1015           0 :         return false;
    1016             :     }
    1017             : 
    1018             :     // Analyze prerelease number.
    1019           4 :     std::string numStr = suffix.substr(digitPos);
    1020           2 :     size_t endPos = 0;
    1021             :     try {
    1022           2 :         outNum = std::stoi(numStr, &endPos);
    1023           0 :     } catch (...) {
    1024           0 :         return false;
    1025             :     }
    1026             : 
    1027             :     // Ensure that number does not contain any suffix characters.
    1028           2 :     if (endPos != numStr.length()) {
    1029           1 :         return false;
    1030             :     }
    1031             : 
    1032           1 :     return true;
    1033             : }
    1034             : 
    1035           7 : aclError ParseBaseVersion(const std::string &verStr, int32_t &baseVal, size_t &endPos) {
    1036           7 :     int major = 0;
    1037           7 :     int minor = 0;
    1038           7 :     int patch = 0;
    1039             : 
    1040             :     try {
    1041             :         // Find first point
    1042           7 :         size_t dot1 = verStr.find('.');
    1043           7 :         if (dot1 == std::string::npos || dot1 == 0) {
    1044           2 :             ACL_LOG_ERROR("Invalid format [%s]. Missing major version.", verStr.c_str());
    1045           2 :             return ACL_ERROR_INTERNAL_ERROR;
    1046             :         }
    1047             : 
    1048             :         // Find second point
    1049           5 :         size_t dot2 = verStr.find('.', dot1 + 1);
    1050           5 :         if (dot2 == std::string::npos || dot2 == dot1 + 1) {
    1051           1 :             ACL_LOG_ERROR("Invalid format [%s]. Missing minor version.", verStr.c_str());
    1052           1 :             return ACL_ERROR_INTERNAL_ERROR;
    1053             :         }
    1054             : 
    1055             :         // Find patch number
    1056           4 :         size_t numStart = dot2 + 1;
    1057           4 :         size_t numEnd = numStart;
    1058           8 :         while (numEnd < verStr.length() && std::isdigit(static_cast<unsigned char>(verStr[numEnd]))) {
    1059           4 :             numEnd++;
    1060             :         }
    1061             : 
    1062           4 :         if (numEnd == numStart) {
    1063           0 :             ACL_LOG_ERROR("Invalid format [%s]. Missing patch version.", verStr.c_str());
    1064           0 :             return ACL_ERROR_INTERNAL_ERROR;
    1065             :         }
    1066             : 
    1067           4 :         major = std::stoi(verStr.substr(0, dot1));
    1068           4 :         minor = std::stoi(verStr.substr(dot1 + 1, dot2 - dot1 - 1));
    1069           4 :         patch = std::stoi(verStr.substr(numStart, numEnd - numStart));
    1070             : 
    1071           4 :         endPos = numEnd;
    1072           0 :     } catch (...) {
    1073           0 :         ACL_LOG_ERROR("Parse base version failed. Contains non-numeric chars?");
    1074           0 :         return ACL_ERROR_INTERNAL_ERROR;
    1075             :     }
    1076             : 
    1077           4 :     baseVal = major * kWeightMajor + minor * kWeightMinor + patch * kWeightPatch;
    1078           4 :     return ACL_SUCCESS;
    1079             : }
    1080             : 
    1081           4 : aclError ParsePrereleasePart(const std::string &rawSuffix, int32_t &adjustment) {
    1082           8 :     std::string suffix = rawSuffix;
    1083             :     std::transform(suffix.begin(), suffix.end(), suffix.begin(),
    1084          30 :                    [](unsigned char c){ return std::tolower(c); });
    1085             : 
    1086             :     // Match prerelease keyword(alpha:300, beta:200, rc:100)
    1087           4 :     int32_t weight = 0;
    1088           4 :     size_t keywordLen = 0;
    1089           4 :     size_t keywordIndex = std::string::npos;
    1090             : 
    1091           4 :     if ((keywordIndex = suffix.find(kPreAlpha)) != std::string::npos) {
    1092           1 :         weight = kWeightAlpha;
    1093           1 :         keywordLen = strlen(kPreAlpha);
    1094           3 :     } else if ((keywordIndex = suffix.find(kPreBeta)) != std::string::npos) {
    1095           1 :         weight = kWeightBeta;
    1096           1 :         keywordLen = strlen(kPreBeta);
    1097           2 :     } else if ((keywordIndex = suffix.find(kPreRC)) != std::string::npos) {
    1098           1 :         weight = kWeightRC;
    1099           1 :         keywordLen = strlen(kPreRC);
    1100             :     } else {
    1101           1 :         ACL_LOG_ERROR("Unknown version suffix in [%s].", rawSuffix.c_str());
    1102           1 :         return ACL_ERROR_INTERNAL_ERROR;
    1103             :     }
    1104             : 
    1105             :     // Verify the separator before the keyword(zero or one separator allowed).
    1106           3 :     if (keywordIndex > 1) {
    1107           1 :          ACL_LOG_ERROR("Invalid separator format in [%s]. Too many separators before keyword.", rawSuffix.c_str());
    1108           1 :          return ACL_ERROR_INTERNAL_ERROR;
    1109             :     }
    1110             : 
    1111             :     // Obtain the numeric part after the keyword.
    1112           4 :     std::string numPart = rawSuffix.substr(keywordIndex + keywordLen);
    1113           2 :     int32_t preNum = 0;
    1114             : 
    1115             :     // Strictly verify the format of the numeric part.
    1116           2 :     if (!ParsePreNumStrict(numPart, preNum)) {
    1117           1 :         ACL_LOG_ERROR("Invalid prerelease number format in [%s].", rawSuffix.c_str());
    1118           1 :         return ACL_ERROR_INTERNAL_ERROR;
    1119             :     }
    1120             : 
    1121             :     // Calculate the final version number: baseValue - weight + preNum
    1122           1 :     adjustment = - weight + preNum;
    1123           1 :     return ACL_SUCCESS;
    1124             : }
    1125             : 
    1126           7 : aclError CalculateVersionNum(const std::string &verStr, int32_t *verNum) {
    1127           7 :     int32_t baseValue = 0;
    1128           7 :     size_t endPos = 0;
    1129             : 
    1130             :     // Analyze base version (X.Y.Z)
    1131           7 :     aclError ret = ParseBaseVersion(verStr, baseValue, endPos);
    1132           7 :     if (ret != ACL_SUCCESS) {
    1133           3 :         return ret;
    1134             :     }
    1135             : 
    1136             :     // Check if there is a suffix content.
    1137           4 :     if (endPos >= verStr.length()) {
    1138           0 :         *verNum = baseValue;
    1139           0 :         return ACL_SUCCESS;
    1140             :     }
    1141             : 
    1142           8 :     std::string suffixStr = verStr.substr(endPos);
    1143           4 :     int32_t adjustment = 0;
    1144             : 
    1145           4 :     ret = ParsePrereleasePart(suffixStr, adjustment);
    1146           4 :     if (ret != ACL_SUCCESS) {
    1147           3 :         return ret;
    1148             :     }
    1149             : 
    1150           1 :     *verNum = baseValue + adjustment;
    1151           1 :     return ACL_SUCCESS;
    1152             : }
    1153             : 
    1154           7 : aclError aclsysGetVersionNumImpl(char *pkgName, int32_t *versionNum)
    1155             : {
    1156           7 :     ACL_LOG_INFO("start to execute aclsysGetVersionNum.");
    1157           7 :     ACL_REQUIRES_NOT_NULL_WITH_INPUT_REPORT(versionNum);
    1158           7 :     ACL_REQUIRES_NOT_NULL_WITH_INPUT_REPORT(pkgName);
    1159             : 
    1160          14 :     std::string verInfo;
    1161             : 
    1162           7 :     aclError ret = GetPkgVersionContent(pkgName, verInfo);
    1163           7 :     if (ret != ACL_SUCCESS) {
    1164           0 :         return ret;
    1165             :     }
    1166             : 
    1167           7 :     ret = CalculateVersionNum(verInfo, versionNum);
    1168           7 :     if (ret != ACL_SUCCESS) {
    1169           6 :         return ret;
    1170             :     }
    1171             : 
    1172           1 :     ACL_LOG_INFO("aclsysGetVersionNum success. Pkg:[%s], Num:[%d]", pkgName, *versionNum);
    1173           1 :     return ACL_SUCCESS;
    1174             : }
    1175             : 
    1176           9 : static std::string GetFaultEventInfo()
    1177             : {
    1178           9 :     std::string faultInfo;
    1179             : 
    1180           9 :     int32_t deviceId = 0;
    1181           9 :     auto ret = rtGetDevice(&deviceId);
    1182           9 :     if (ret != RT_ERROR_NONE) {
    1183           1 :         ACL_LOG_INFO("can not get device id, runtime errorCode is %d", static_cast<int32_t>(ret));
    1184           1 :         return faultInfo;
    1185             :     }
    1186             : 
    1187           8 :     rtDmsEventFilter filter = {};
    1188           8 :     const uint32_t maxFaultNum = 128UL; // max is 128
    1189           8 :     rtDmsFaultEvent faultEventInfo[maxFaultNum] = {};
    1190           8 :     uint32_t eventCount = 0UL;
    1191           8 :     ret = rtGetFaultEvent(deviceId, &filter, faultEventInfo, maxFaultNum, &eventCount);
    1192           8 :     if (ret != RT_ERROR_NONE || eventCount == 0UL) {
    1193           4 :         ACL_LOG_INFO("can not get fault event of device %d, runtime errorCode is %d",
    1194             :             deviceId, static_cast<int32_t>(ret));
    1195           4 :         return faultInfo;
    1196             :     }
    1197             : 
    1198          12 :     for (uint32_t faultIndex = 0; faultIndex < eventCount; ++faultIndex) {
    1199          16 :         std::ostringstream oss;
    1200           8 :         oss << std::hex << faultEventInfo[faultIndex].eventId;
    1201          24 :         faultInfo = faultInfo + "[0x" + oss.str() + "]"
    1202          16 :             + faultEventInfo[faultIndex].eventName + ";";
    1203             :     }
    1204             : 
    1205           4 :     if (faultInfo.empty()) {
    1206           0 :         return faultInfo;
    1207             :     }
    1208           4 :     faultInfo = "Fault diagnosis analysis: " + faultInfo;
    1209           4 :     return faultInfo;
    1210             : }
    1211             : 
    1212           9 : const char *aclGetRecentErrMsgImpl()
    1213             : {
    1214           9 :     ACL_LOG_INFO("start to execute aclGetRecentErrMsg.");
    1215           9 :     constexpr const rtGetDevMsgType_t msgType = RT_GET_DEV_ERROR_MSG;
    1216           9 :     const auto ret = rtGetDevMsg(msgType, &acl::aclGetMsgCallback);
    1217           9 :     if (ret != RT_ERROR_NONE) {
    1218           1 :         ACL_LOG_DEBUG("can not get device errorMessage, runtime errorCode is %d",
    1219             :             static_cast<int32_t>(ret));
    1220             :     }
    1221             : 
    1222          18 :     const std::string faultEventMsg = GetFaultEventInfo();
    1223           9 :     if (!faultEventMsg.empty()) {
    1224           4 :         if (aclRecentErrMsg.empty()) {
    1225           2 :             aclRecentErrMsg = faultEventMsg;
    1226             :         } else {
    1227           2 :             aclRecentErrMsg = aclRecentErrMsg + "\n" + faultEventMsg;
    1228             :         }
    1229             :     }
    1230             : 
    1231          36 :     const std::string aclHostErrMsg = std::string(error_message::GetErrMgrErrorMessage().get());
    1232           9 :     if ((aclHostErrMsg.empty()) && (aclRecentErrMsg.empty())) {
    1233           0 :         ACL_LOG_DEBUG("get errorMessage is empty");
    1234           0 :         return nullptr;
    1235             :     }
    1236             : 
    1237           9 :     if (aclHostErrMsg.empty()) {
    1238           3 :         return aclRecentErrMsg.c_str();
    1239             :     }
    1240             : 
    1241           6 :     if (aclRecentErrMsg.empty()) {
    1242           1 :         (void)aclRecentErrMsg.assign(aclHostErrMsg);
    1243           1 :         return aclRecentErrMsg.c_str();
    1244             :     }
    1245             : 
    1246           5 :     aclRecentErrMsg = aclHostErrMsg + "\n" + aclRecentErrMsg;
    1247           5 :     ACL_LOG_INFO("execute aclGetRecentErrMsg successfully.");
    1248           5 :     return aclRecentErrMsg.c_str();
    1249             : }
    1250             : 
    1251           5 : aclError aclGetCannAttributeListImpl(const aclCannAttr **cannAttrList, size_t *num)
    1252             : {
    1253           5 :     ACL_REQUIRES_NOT_NULL_WITH_INPUT_REPORT(cannAttrList);
    1254           4 :     ACL_REQUIRES_NOT_NULL_WITH_INPUT_REPORT(num);
    1255           3 :     const aclError ret = acl::CannInfoUtils::GetAttributeList(cannAttrList, num);
    1256           3 :     if (ret != ACL_SUCCESS) {
    1257           2 :         ACL_LOG_ERROR("failed to get attrList, ret = %d", ret);
    1258           2 :         return ret;
    1259             :     }
    1260           1 :     ACL_LOG_INFO("execute aclGetCannAttributeList successfully.");
    1261           1 :     return ACL_SUCCESS;
    1262             : }
    1263             : 
    1264           9 : aclError aclGetCannAttributeImpl(aclCannAttr cannAttr, int32_t *value)
    1265             : {
    1266           9 :     ACL_REQUIRES_NOT_NULL_WITH_INPUT_REPORT(value);
    1267           8 :     const aclError ret = acl::CannInfoUtils::GetAttribute(cannAttr, value);
    1268           8 :     if (ret != ACL_SUCCESS) {
    1269           7 :         ACL_LOG_ERROR("failed to check, attr value = %d, ret = %d", static_cast<int32_t>(cannAttr), ret);
    1270           7 :         return ret;
    1271             :     }
    1272           1 :     ACL_LOG_INFO("execute aclGetCannAttribute successfully.");
    1273           1 :     return ACL_SUCCESS;
    1274             : }
    1275             : 
    1276           8 : aclError aclGetDeviceCapabilityImpl(uint32_t deviceId, aclDeviceInfo deviceInfo, int64_t *value)
    1277             : {
    1278           8 :     ACL_REQUIRES_NOT_NULL_WITH_INPUT_REPORT(value);
    1279           7 :     int32_t count = -1;
    1280           7 :     const rtError_t rtErr = rtGetDeviceCount(&count);
    1281           7 :     if (rtErr != RT_ERROR_NONE) {
    1282           1 :         ACL_LOG_CALL_ERROR("get device count failed, runtime result = %d.", static_cast<int32_t>(rtErr));
    1283           1 :         return ACL_GET_ERRCODE_RTS(rtErr);
    1284             :     }
    1285             :     // currently check only, deviceId with [0, count - 1]
    1286           6 :     ACL_CHECK_LESS_UINT(deviceId, static_cast<uint32_t>(count - 1));
    1287           6 :     const std::map<aclDeviceInfo, std::string> infoTypeToKey = {
    1288           6 :         {ACL_DEVICE_INFO_AI_CORE_NUM, "ai_core_cnt"},
    1289           6 :         {ACL_DEVICE_INFO_VECTOR_CORE_NUM, "vector_core_cnt"},
    1290           6 :         {ACL_DEVICE_INFO_L2_SIZE, "l2_size"}
    1291          42 :     };
    1292           6 :     const auto iter = infoTypeToKey.find(deviceInfo);
    1293           6 :     if (iter == infoTypeToKey.end()) {
    1294           1 :         ACL_LOG_WARN("get device info failed, invalid info type = %d", static_cast<int32_t>(deviceInfo));
    1295           1 :         return ACL_ERROR_INVALID_PARAM;
    1296             :     }
    1297           5 :     const auto &key = iter->second;
    1298           5 :     const aclError ret = GetPlatformInfoWithKey(key, value);
    1299           5 :     if (ret != ACL_SUCCESS) {
    1300           4 :         ACL_LOG_ERROR("get device info failed, info type = %d, key = %s", static_cast<int32_t>(deviceInfo), key.c_str());
    1301           4 :         return ret;
    1302             :     }
    1303           1 :     ACL_LOG_INFO("execute aclGetDeviceCapability successfully.");
    1304           1 :     return ACL_SUCCESS;
    1305             : }

Generated by: LCOV version 1.14