mnt.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. use crate::{
  2. filesystem::vfs::{
  3. mount::{MountFlags, MountList, MountPath},
  4. FileSystem, IndexNode, MountFS,
  5. },
  6. libs::{once::Once, spinlock::SpinLock},
  7. process::{fork::CloneFlags, namespace::NamespaceType, ProcessManager},
  8. };
  9. use alloc::string::String;
  10. use alloc::sync::{Arc, Weak};
  11. use alloc::vec::Vec;
  12. use system_error::SystemError;
  13. use super::{nsproxy::NsCommon, user_namespace::UserNamespace, NamespaceOps};
  14. static mut INIT_MNT_NAMESPACE: Option<Arc<MntNamespace>> = None;
  15. /// 初始化root mount namespace
  16. pub fn mnt_namespace_init() {
  17. static ONCE: Once = Once::new();
  18. ONCE.call_once(|| unsafe {
  19. INIT_MNT_NAMESPACE = Some(MntNamespace::new_root());
  20. });
  21. }
  22. int_like!(MntSharedGroupId, usize);
  23. /// 获取全局的根挂载namespace
  24. pub fn root_mnt_namespace() -> Arc<MntNamespace> {
  25. unsafe {
  26. INIT_MNT_NAMESPACE
  27. .as_ref()
  28. .expect("Mount namespace not initialized")
  29. .clone()
  30. }
  31. }
  32. pub struct MntNamespace {
  33. ns_common: NsCommon,
  34. self_ref: Weak<MntNamespace>,
  35. /// 父namespace的弱引用
  36. _parent: Option<Weak<MntNamespace>>,
  37. _user_ns: Arc<UserNamespace>,
  38. root_mountfs: Arc<MountFS>,
  39. inner: SpinLock<InnerMntNamespace>,
  40. }
  41. pub struct InnerMntNamespace {
  42. _dead: bool,
  43. mount_list: Arc<MountList>,
  44. }
  45. impl NamespaceOps for MntNamespace {
  46. fn ns_common(&self) -> &NsCommon {
  47. &self.ns_common
  48. }
  49. }
  50. impl MntNamespace {
  51. fn new_root() -> Arc<Self> {
  52. let mount_list = MountList::new();
  53. let ramfs = crate::filesystem::ramfs::RamFS::new();
  54. let ramfs = MountFS::new(
  55. ramfs,
  56. None,
  57. MountPropagation::new_private(),
  58. None,
  59. MountFlags::empty(),
  60. );
  61. let result = Arc::new_cyclic(|self_ref| Self {
  62. ns_common: NsCommon::new(0, NamespaceType::Mount),
  63. self_ref: self_ref.clone(),
  64. _parent: None,
  65. _user_ns: super::user_namespace::INIT_USER_NAMESPACE.clone(),
  66. root_mountfs: ramfs.clone(),
  67. inner: SpinLock::new(InnerMntNamespace {
  68. mount_list,
  69. _dead: false,
  70. }),
  71. });
  72. ramfs.set_namespace(Arc::downgrade(&result));
  73. result
  74. .add_mount(Arc::new(MountPath::from("/")), ramfs)
  75. .expect("Failed to add root mount");
  76. return result;
  77. }
  78. /// 强制替换本MountNamespace的根挂载文件系统
  79. ///
  80. /// 本方法仅供dragonos初始化时使用
  81. pub unsafe fn force_change_root_mountfs(&self, new_root: Arc<MountFS>) {
  82. let inner_guard = self.inner.lock();
  83. let ptr = self as *const Self as *mut Self;
  84. let self_mut = (ptr).as_mut().unwrap();
  85. self_mut.root_mountfs = new_root.clone();
  86. let (path, _, _) = inner_guard.mount_list.get_mount_point("/").unwrap();
  87. inner_guard.mount_list.insert(path, new_root);
  88. }
  89. /// Creates a copy of the mount namespace for process cloning.
  90. ///
  91. /// This function is called during process creation to determine whether to create
  92. /// a new mount namespace or share the existing one based on the clone flags.
  93. ///
  94. /// # Arguments
  95. /// * `clone_flags` - Flags that control namespace creation behavior
  96. /// * `user_ns` - The user namespace to associate with the new mount namespace
  97. ///
  98. /// # Returns
  99. /// * `Ok(Arc<MntNamespace>)` - The appropriate mount namespace for the new process
  100. /// * `Err(SystemError)` - If namespace creation fails
  101. ///
  102. /// # Behavior
  103. /// - If `CLONE_NEWNS` is not set, returns the current mount namespace
  104. /// - If `CLONE_NEWNS` is set, creates a new mount namespace (currently unimplemented)
  105. pub fn copy_mnt_ns(
  106. &self,
  107. clone_flags: &CloneFlags,
  108. _user_ns: Arc<UserNamespace>,
  109. ) -> Result<Arc<MntNamespace>, SystemError> {
  110. if !clone_flags.contains(CloneFlags::CLONE_NEWNS) {
  111. // Return the current mount namespace if CLONE_NEWNS is not set
  112. return Ok(self.self_ref.upgrade().unwrap());
  113. }
  114. todo!("Implement MntNamespace::copy_mnt_ns");
  115. }
  116. pub fn root_mntfs(&self) -> &Arc<MountFS> {
  117. &self.root_mountfs
  118. }
  119. /// 获取该挂载命名空间的根inode
  120. pub fn root_inode(&self) -> Arc<dyn IndexNode> {
  121. self.root_mountfs.root_inode()
  122. }
  123. pub fn add_mount(
  124. &self,
  125. mount_path: Arc<MountPath>,
  126. mntfs: Arc<MountFS>,
  127. ) -> Result<(), SystemError> {
  128. self.inner.lock().mount_list.insert(mount_path, mntfs);
  129. return Ok(());
  130. }
  131. pub fn mount_list(&self) -> Arc<MountList> {
  132. self.inner.lock().mount_list.clone()
  133. }
  134. pub fn remove_mount(&self, mount_path: &str) -> Option<Arc<MountFS>> {
  135. return self.inner.lock().mount_list.remove(mount_path);
  136. }
  137. pub fn get_mount_point(
  138. &self,
  139. mount_point: &str,
  140. ) -> Option<(Arc<MountPath>, String, Arc<MountFS>)> {
  141. self.inner.lock().mount_list.get_mount_point(mount_point)
  142. }
  143. }
  144. /// Manages mount propagation relationships and state for mount points.
  145. ///
  146. /// This struct tracks how mount events (mount, unmount, remount) propagate between
  147. /// mount points according to their propagation types. It maintains relationships
  148. /// between shared mounts, slave mounts, and their propagation groups.
  149. #[derive(Clone)]
  150. pub struct MountPropagation {
  151. /// The type of propagation behavior for this mount
  152. pub prop_type: PropagationType,
  153. /// Group ID for shared mounts that can propagate events to each other
  154. pub shared_group_id: Option<MntSharedGroupId>,
  155. /// Reference to the master mount for slave mounts
  156. pub master: Option<Weak<MountFS>>,
  157. /// List of slave mounts that receive events from this mount
  158. pub slaves: Vec<Weak<MountFS>>,
  159. /// Peer group ID for complex propagation relationships
  160. pub peer_group_id: Option<MntSharedGroupId>,
  161. /// Counter to prevent infinite loops during event propagation
  162. pub propagation_count: u32,
  163. }
  164. /// Defines the propagation type for mount points, controlling how mount events are shared.
  165. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  166. pub enum PropagationType {
  167. /// Mount events do not propagate to or from this mount
  168. Private,
  169. /// Mount events propagate bidirectionally with other mounts in the same peer group
  170. Shared,
  171. /// Mount events propagate from the master mount to this slave mount
  172. Slave,
  173. /// Mount cannot be bind mounted and events do not propagate
  174. Unbindable,
  175. }
  176. impl MountPropagation {
  177. pub fn new_private() -> Arc<Self> {
  178. Arc::new(Self {
  179. prop_type: PropagationType::Private,
  180. shared_group_id: None,
  181. master: None,
  182. slaves: Vec::new(),
  183. peer_group_id: None,
  184. propagation_count: 0,
  185. })
  186. }
  187. pub fn new_shared(group_id: MntSharedGroupId) -> Arc<Self> {
  188. Arc::new(Self {
  189. prop_type: PropagationType::Shared,
  190. shared_group_id: Some(group_id),
  191. master: None,
  192. slaves: Vec::new(),
  193. peer_group_id: Some(group_id),
  194. propagation_count: 0,
  195. })
  196. }
  197. pub fn new_slave(master: Weak<MountFS>) -> Arc<Self> {
  198. Arc::new(Self {
  199. prop_type: PropagationType::Slave,
  200. shared_group_id: None,
  201. master: Some(master),
  202. slaves: Vec::new(),
  203. peer_group_id: None,
  204. propagation_count: 0,
  205. })
  206. }
  207. pub fn new_unbindable() -> Arc<Self> {
  208. Arc::new(Self {
  209. prop_type: PropagationType::Unbindable,
  210. shared_group_id: None,
  211. master: None,
  212. slaves: Vec::new(),
  213. peer_group_id: None,
  214. propagation_count: 0,
  215. })
  216. }
  217. /// 添加一个从属挂载
  218. pub fn add_slave(&mut self, slave: Weak<MountFS>) {
  219. self.slaves.push(slave);
  220. }
  221. /// 移除一个从属挂载
  222. pub fn remove_slave(&mut self, slave: &Weak<MountFS>) {
  223. self.slaves.retain(|s| !Weak::ptr_eq(s, slave));
  224. }
  225. /// 清理无效的从属挂载引用
  226. pub fn cleanup_stale_slaves(&mut self) {
  227. self.slaves.retain(|s| s.upgrade().is_some());
  228. }
  229. /// 重置传播计数器
  230. pub fn reset_propagation_count(&mut self) {
  231. self.propagation_count = 0;
  232. }
  233. }
  234. impl ProcessManager {
  235. /// 获取当前进程的挂载namespace
  236. pub fn current_mntns() -> Arc<MntNamespace> {
  237. if Self::initialized() {
  238. ProcessManager::current_pcb().nsproxy.read().mnt_ns.clone()
  239. } else {
  240. root_mnt_namespace()
  241. }
  242. }
  243. }