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 : /*!
12 : * \file kernel_print_lock.cpp
13 : * \brief
14 : */
15 : #include <pthread.h>
16 : #include <sys/mman.h>
17 : #include <cstdint>
18 : #include <cerrno>
19 : #include <csignal>
20 : #include "stub_def.h"
21 :
22 : namespace AscendC {
23 : KernelPrintLock* KernelPrintLock::printLock = nullptr;
24 16 : void KernelPrintLock::Init()
25 : {
26 16 : pthread_rwlockattr_init(&attr);
27 16 : pthread_rwlockattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
28 16 : pthread_rwlock_init(&lock, &attr);
29 16 : }
30 :
31 12 : void KernelPrintLock::UnInit()
32 : {
33 12 : pthread_rwlock_destroy(&lock);
34 12 : pthread_rwlockattr_destroy(&attr);
35 12 : }
36 :
37 0 : int KernelPrintLock::Lock() { return pthread_rwlock_wrlock(&lock); }
38 0 : int KernelPrintLock::Unlock() { return pthread_rwlock_unlock(&lock); }
39 :
40 20 : KernelPrintLock* KernelPrintLock::CreateLock()
41 : {
42 20 : if (printLock == nullptr) {
43 20 : printLock = (KernelPrintLock*)mmap(
44 : nullptr, sizeof(KernelPrintLock), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
45 20 : if (static_cast<int>(reinterpret_cast<intptr_t>(printLock)) == -1) {
46 4 : printf("CreateLock Fail : KernelPrintLock map fail. Error Code : %d", errno);
47 4 : raise(SIGABRT);
48 : } else {
49 16 : printLock->Init();
50 : }
51 : }
52 20 : return printLock;
53 : }
54 20 : void KernelPrintLock::FreeLock()
55 : {
56 20 : if (printLock == nullptr) {
57 8 : return;
58 : }
59 12 : printLock->UnInit();
60 12 : if (munmap(printLock, sizeof(KernelPrintLock)) == -1) {
61 4 : printf("FreeLock Fail : KernelPrintLock Unmap fail. Error Code : %d", errno);
62 : }
63 12 : printLock = nullptr;
64 : }
65 0 : KernelPrintLock::~KernelPrintLock()
66 : {
67 0 : if (printLock == nullptr) {
68 0 : return;
69 : }
70 0 : pthread_rwlock_destroy(&lock);
71 0 : pthread_rwlockattr_destroy(&attr);
72 0 : }
73 : } // namespace AscendC
|