context_spore/lib.rs
1//! 资源-孢子这一对抽象保证了基于上下文的驱动设计的安全性。
2//!
3//! 由于加速硬件与 CPU 是异构异步的,驱动引入了硬件上下文的概念,代表某个加速硬件上的一系列资源。
4//! 所有申请、释放加速器资源(包括存储空间、算力、调度能力等)的操作都需要在某个硬件上下文中进行。
5//! 同一个资源只能释放回申请它的上下文,不能串台。
6//!
7//! 在 ABI 中,这些限制需要程序员人为保证,对于包含多个上下文的应用程序来说,上下文管理非常难。
8//! 因此,cndrv crate 提出资源-孢子这一对抽象封装上下文上的资源,并借助编译器规则和运行时检查保证安全性。
9
10#![no_std]
11#![deny(warnings, missing_docs)]
12
13/// 资源的原始形式的表示。通常来自底层库的定义。
14pub trait AsRaw {
15 /// 原始形式的类型。
16 type Raw: Unpin + 'static;
17 /// # Safety
18 ///
19 /// The caller must ensure that the returned item is dropped before the original item.
20 unsafe fn as_raw(&self) -> Self::Raw;
21}
22
23/// 上下文资源。
24///
25/// 这个 trait 将资源的生命周期与上下文绑定,以保证资源的申请和释放在同一个上下文中完成。
26/// 处于上下文资源状态的资源对象可以参与相应的功能。例如,处于上下文资源状态的存储区域可以读写。
27/// 但是业务逻辑中,不可避免地会出现需要暂时切换当前上下文而不释放资源的情况,
28/// 因此资源提供 [`sporulate`](ContextResource::sporulate) 方法将资源转换为孢子。
29pub trait ContextResource<'ctx, Ctx> {
30 /// 上下文资源对应的孢子类型。
31 ///
32 /// 这个约束保证了资源与孢子一一对应。
33 type Spore: ContextSpore<Ctx, Resource<'ctx> = Self>
34 where
35 Ctx: 'ctx;
36
37 /// 将资源转换为孢子。
38 ///
39 /// # Safety
40 ///
41 /// 将资源转换为孢子总是安全的。
42 fn sporulate(self) -> Self::Spore;
43}
44
45/// 上下文孢子。
46///
47/// 这个 trait 移除上下文资源的生命周期约束,从而允许在上下文被换出时暂时保持资源存在。
48/// 但处于上下文孢子状态的资源通常不再允许参与相应的功能。
49/// 只有当申请这些资源的上下文被换回,并在上下文上将孢子恢复为资源后才能继续发挥作用。
50/// 上下文孢子提供 [`sprout`](ContextSpore::sprout) 方法将孢子转换为资源,
51/// 以及 [`sprout_ref`](ContextSpore::sprout_ref) 和 [`sprout_mut`](ContextSpore::sprout_mut) 方法获取资源的不可变和可变引用。
52/// 这些方法将引入运行时检查以保证孢子在正确的上下文上复原。
53pub trait ContextSpore<Ctx>: 'static + Send + Sync {
54 /// 上下文孢子对应的资源类型。
55 ///
56 /// 这个约束保证了资源与孢子一一对应。
57 type Resource<'ctx>: ContextResource<'ctx, Ctx, Spore = Self>
58 where
59 Ctx: 'ctx;
60
61 /// 将孢子转换为资源。
62 ///
63 /// # Safety
64 ///
65 /// 这个转换的安全性来源于运行时检查孢子是否属于已加载的目标上下文。
66 fn sprout(self, ctx: &Ctx) -> Self::Resource<'_>;
67
68 /// 从孢子中借出资源的不可变引用。
69 ///
70 /// # Safety
71 ///
72 /// 这个转换的安全性来源于运行时检查孢子是否属于已加载的目标上下文。
73 fn sprout_ref<'ctx>(&'ctx self, ctx: &'ctx Ctx) -> &'ctx Self::Resource<'ctx>;
74
75 /// 从孢子中借出资源的可变引用。
76 ///
77 /// # Safety
78 ///
79 /// 这个转换的安全性来源于运行时检查孢子是否属于已加载的目标上下文。
80 fn sprout_mut<'ctx>(&'ctx mut self, ctx: &'ctx Ctx) -> &'ctx mut Self::Resource<'ctx>;
81}
82
83/// 孢子惯用法。
84///
85/// 所有孢子类型应该满足这些能力以跨越上下文。
86///
87/// 宏提供 3 项能力:
88///
89/// - 所有孢子具有 `Send`;
90/// - 所有孢子具有 `Sync`;
91/// - 孢子类型绝不能自动释放,必须在合适的时机转化为资源以释放回正确的硬件上下文。
92/// 因此为孢子实现 `Drop` 并直接抛出异常以避免资源泄露;
93#[macro_export]
94macro_rules! spore_convention {
95 ($spore:ty) => {
96 unsafe impl Send for $spore {}
97 unsafe impl Sync for $spore {}
98 impl Drop for $spore {
99 #[inline]
100 fn drop(&mut self) {
101 unreachable!("Never drop ContextSpore");
102 }
103 }
104 };
105}
106
107/// 原始资源的标准容器。
108///
109/// 必须是可安全移动的类型,因为在资源和孢子之间转换时它将被移动。
110pub struct RawContainer<Ctx: Unpin + 'static, Rss: Unpin + 'static> {
111 /// 上下文标记的原始形式。
112 pub ctx: Ctx,
113 /// 资源的原始形式。
114 pub rss: Rss,
115}
116
117/// 实现资源和孢子的惯用法。
118#[macro_export]
119macro_rules! impl_spore {
120 ($resource:ident and $spore:ident by ($ctx:ty, $rss:ty)) => {
121 #[repr(transparent)]
122 pub struct $resource<'ctx>(
123 $crate::RawContainer<<$ctx as $crate::AsRaw>::Raw, $rss>,
124 std::marker::PhantomData<&'ctx ()>,
125 );
126
127 impl<'ctx> $resource<'ctx> {
128 #[inline]
129 pub fn ctx(&self) -> &'ctx $ctx {
130 unsafe { <$ctx>::from_raw(&self.0.ctx) }
131 }
132 }
133
134 #[repr(transparent)]
135 pub struct $spore($crate::RawContainer<<$ctx as $crate::AsRaw>::Raw, $rss>);
136
137 $crate::spore_convention!($spore);
138
139 impl $crate::ContextSpore<$ctx> for $spore {
140 type Resource<'ctx> = $resource<'ctx>;
141
142 #[inline]
143 fn sprout(self, ctx: &$ctx) -> Self::Resource<'_> {
144 assert_eq!(self.0.ctx, unsafe { <$ctx as $crate::AsRaw>::as_raw(ctx) });
145 // SAFETY: `transmute_copy` + `forget` 是手工实现移动语义。
146 // `RawContainer` 具有 `Unpin` 保证它的安全性。
147 let ans = unsafe { std::mem::transmute_copy(&self.0) };
148 std::mem::forget(self);
149 ans
150 }
151
152 #[inline]
153 fn sprout_ref<'ctx>(&'ctx self, ctx: &'ctx $ctx) -> &Self::Resource<'_> {
154 assert_eq!(self.0.ctx, unsafe { <$ctx as $crate::AsRaw>::as_raw(ctx) });
155 // SAFETY: 资源以引用的形式返回,因此在使用完成后不会释放。
156 unsafe { std::mem::transmute(&self.0) }
157 }
158
159 #[inline]
160 fn sprout_mut<'ctx>(&'ctx mut self, ctx: &'ctx $ctx) -> &mut Self::Resource<'_> {
161 assert_eq!(self.0.ctx, unsafe { <$ctx as $crate::AsRaw>::as_raw(ctx) });
162 // SAFETY: 资源以可变引用的形式返回,因此在使用完成后不会释放。
163 unsafe { std::mem::transmute(&mut self.0) }
164 }
165 }
166
167 impl<'ctx> $crate::ContextResource<'ctx, $ctx> for $resource<'ctx> {
168 type Spore = $spore;
169
170 #[inline]
171 fn sporulate(self) -> Self::Spore {
172 // SAFETY: `transmute_copy` + `forget` 是手工实现移动语义。
173 // `RawContainer` 具有 `Unpin` 保证它的安全性。
174 let s = unsafe { std::mem::transmute_copy(&self.0) };
175 std::mem::forget(self);
176 $spore(s)
177 }
178 }
179 };
180}