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