• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef COMMON_COMPONENTS_COMMON_PAGE_CACHE_H
17 #define COMMON_COMPONENTS_COMMON_PAGE_CACHE_H
18 
19 #include "common_components/common/mem_common.h"
20 
21 namespace common {
22 class PageCache {
23 public:
24     // Return the singleton object of PageCache
GetInstance()25     static PageCache* GetInstance() { return &instance_; }
26 
27     // Get a k-page Span
28     Span* NewSpan(size_t k);
29 
30     std::mutex& GetPageMutex();
31 
32     // Pass in a small fixed-length memory block to obtain the Span object corresponding to the page it is located in.
33     Span* MapObjectToSpan(void* obj);
34 
35     // Try to merge the pages before and after the span to alleviate the external fragmentation problem.
36     void ReleaseSpanToPageCache(Span* span);
37 
38 private:
39     std::mutex pageMtx_;
40     SpanList pageCacheSpans_[MAX_NPAGES];
41     std::unordered_map<pageID, Span*> idSpanMap_; // The mapping between page numbers and span objects.
42 
43 private:
PageCache()44     PageCache() noexcept {}
45 
46     PageCache(const PageCache&) = delete;
47     PageCache& operator=(const PageCache&) = delete;
48 
49     static PageCache instance_;
50 };
51 
52 class ScopedPageCacheMutex {
53 public:
ScopedPageCacheMutex()54     explicit ScopedPageCacheMutex() { PageCache::GetInstance()->GetPageMutex().lock(); }
55 
~ScopedPageCacheMutex()56     ~ScopedPageCacheMutex() { PageCache::GetInstance()->GetPageMutex().unlock(); }
57 };
58 } // namespace common
59 #endif
60