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