bounce_buffer.hpp
1 /*
2  * 版权所有 (c) 2024-2025, NVIDIA CORPORATION.
3  *
4  * 根据 Apache 许可证 2.0 版(以下简称“许可证”)获得许可;
5  * 除非遵守许可证的规定,否则不得使用此文件。
6  * 您可以在以下位置获取许可证副本:
7  *
8  * https://apache.ac.cn/licenses/LICENSE-2.0
9  *
10  * 除非适用法律要求或书面同意,否则软件
11  * 根据许可证分发是基于“按原样”的基础上进行的,
12  * 不带任何形式的明示或暗示保证或条件。
13  * 有关管理权限和限制的特定语言,请参见许可证。
14  *
15  */
16 #pragma once
17 
18 #include <stack>
19 
20 #include <kvikio/defaults.hpp>
21 
22 namespace kvikio {
23 
30 class AllocRetain {
31  private
32  std::mutex _mutex{};
33  // Stack of free allocations
34  std::stack<void*> _free_allocs{};
35  // The size of each allocation in `_free_allocs`
36  std::size_t _size{defaults::bounce_buffer_size()};
37 
38  public
42  class Alloc {
43  private
44  AllocRetain* _manager;
45  void* _alloc;
46  std::size_t const _size;
47 
48  public
49  Alloc(AllocRetain* manager, void* alloc, std::size_t size);
50  Alloc(Alloc const&) = delete;
51  Alloc& operator=(Alloc const&) = delete;
52  Alloc(Alloc&& o) = delete;
53  Alloc& operator=(Alloc&& o) = delete;
54  ~Alloc() noexcept;
55  void* get() noexcept;
56  void* get(std::ptrdiff_t offset) noexcept;
57  std::size_t size() noexcept;
58  };
59 
60  AllocRetain() = default;
61 
62  // Notice, we do not clear the allocations at destruction thus the allocations leaks
63  // at exit. We do this because `AllocRetain::instance()` stores the allocations in a
64  // static stack that are destructed below main, which is not allowed in CUDA:
65  // <https://docs.nvda.net.cn/cuda/cuda-c-programming-guide/index.html#initialization>
66  ~AllocRetain() noexcept = default;
67 
68  private
76  std::size_t _clear();
77 
83  void _ensure_alloc_size();
84 
85  public
86  [[nodiscard]] Alloc get();
87 
88  void put(void* alloc, std::size_t size);
89 
95  std::size_t clear();
96 
97  KVIKIO_EXPORT static AllocRetain& instance();
98 
99  AllocRetain(AllocRetain const&) = delete;
100  AllocRetain& operator=(AllocRetain const&) = delete;
101  AllocRetain(AllocRetain&& o) = delete;
102  AllocRetain& operator=(AllocRetain&& o) = delete;
103 };
104 
105 } // namespace kvikio
用于保留主机内存分配的单例类。
std::size_t clear()
释放所有保留的分配。
static std::size_t bounce_buffer_size()
获取用于在主机内存中暂存数据的反弹缓冲区的大小。
KvikIO 命名空间。
定义: batch.hpp:27