kobako 0.29.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (291) hide show
  1. checksums.yaml +4 -4
  2. data/.release-please-manifest.json +1 -1
  3. data/CHANGELOG.md +552 -10
  4. data/Cargo.lock +595 -139
  5. data/README.md +126 -564
  6. data/ROADMAP.md +3 -2
  7. data/crates/kobako-runtime/CHANGELOG.md +488 -1
  8. data/crates/kobako-runtime/Cargo.toml +73 -15
  9. data/crates/kobako-runtime/README.md +11 -4
  10. data/crates/kobako-runtime/src/cred.rs +124 -0
  11. data/crates/kobako-runtime/src/dispatch.rs +5 -6
  12. data/crates/kobako-runtime/src/endpoint/buffer.rs +301 -0
  13. data/crates/kobako-runtime/src/endpoint/dispatch.rs +292 -0
  14. data/crates/kobako-runtime/src/endpoint/invoke.rs +181 -0
  15. data/crates/kobako-runtime/src/endpoint.rs +267 -0
  16. data/crates/kobako-runtime/src/errno.rs +391 -0
  17. data/crates/kobako-runtime/src/error.rs +31 -10
  18. data/crates/kobako-runtime/src/filesystem/anon_inodes.rs +52 -0
  19. data/crates/kobako-runtime/src/filesystem/bind/fid.rs +82 -0
  20. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +274 -0
  21. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +248 -0
  22. data/crates/kobako-runtime/src/filesystem/bind.rs +2857 -0
  23. data/crates/kobako-runtime/src/filesystem/overlay/file.rs +89 -0
  24. data/crates/kobako-runtime/src/filesystem/overlay/inode.rs +106 -0
  25. data/crates/kobako-runtime/src/filesystem/overlay/path.rs +263 -0
  26. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +128 -0
  27. data/crates/kobako-runtime/src/filesystem/overlay/stack/dir.rs +238 -0
  28. data/crates/kobako-runtime/src/filesystem/overlay/stack/namei.rs +135 -0
  29. data/crates/kobako-runtime/src/filesystem/overlay/stack/readdir.rs +54 -0
  30. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +316 -739
  31. data/crates/kobako-runtime/src/filesystem/overlay.rs +2627 -1154
  32. data/crates/kobako-runtime/src/filesystem/pipe.rs +224 -0
  33. data/crates/kobako-runtime/src/filesystem/rdir.rs +84 -0
  34. data/crates/kobako-runtime/src/filesystem/tmpfs/seed.rs +32 -0
  35. data/crates/kobako-runtime/src/filesystem/tmpfs/tmpfile.rs +32 -0
  36. data/crates/kobako-runtime/src/filesystem/tmpfs/whiteout.rs +107 -0
  37. data/crates/kobako-runtime/src/filesystem/tmpfs/xattr.rs +22 -0
  38. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +1997 -0
  39. data/crates/kobako-runtime/src/filesystem/wrap.rs +208 -0
  40. data/crates/kobako-runtime/src/filesystem.rs +25 -388
  41. data/crates/kobako-runtime/src/fork.rs +96 -0
  42. data/crates/kobako-runtime/src/grant.rs +3 -0
  43. data/crates/kobako-runtime/src/hashtable.rs +46 -0
  44. data/crates/kobako-runtime/src/lib.rs +27 -11
  45. data/crates/kobako-runtime/src/limits.rs +195 -0
  46. data/crates/kobako-runtime/src/locking/seqlock.rs +66 -0
  47. data/crates/kobako-runtime/src/locking.rs +228 -0
  48. data/crates/kobako-runtime/src/memcg.rs +383 -0
  49. data/crates/kobako-runtime/src/mount.rs +86 -101
  50. data/crates/kobako-runtime/src/net/backends.rs +43 -0
  51. data/crates/kobako-runtime/src/net/connections.rs +179 -0
  52. data/crates/kobako-runtime/src/net/credential.rs +125 -0
  53. data/crates/kobako-runtime/src/net/egress.rs +160 -0
  54. data/crates/kobako-runtime/src/net/family.rs +181 -0
  55. data/crates/kobako-runtime/src/net/http.rs +2733 -0
  56. data/crates/kobako-runtime/src/net/lookup.rs +285 -0
  57. data/crates/kobako-runtime/src/net/mock.rs +251 -0
  58. data/crates/kobako-runtime/src/net/namespace.rs +1366 -0
  59. data/crates/kobako-runtime/src/net/reactor.rs +531 -0
  60. data/crates/kobako-runtime/src/net/resolv/darwin.rs +275 -0
  61. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +469 -0
  62. data/crates/kobako-runtime/src/net/resolv/stub.rs +536 -0
  63. data/crates/kobako-runtime/src/net/resolv/windows.rs +248 -0
  64. data/crates/kobako-runtime/src/net/resolv.rs +227 -0
  65. data/crates/kobako-runtime/src/net/socket.rs +870 -0
  66. data/crates/kobako-runtime/src/net/tcp.rs +1588 -0
  67. data/crates/kobako-runtime/src/net/tls.rs +58 -0
  68. data/crates/kobako-runtime/src/net/transport.rs +279 -0
  69. data/crates/kobako-runtime/src/net/udp.rs +1003 -0
  70. data/crates/kobako-runtime/src/net.rs +42 -0
  71. data/crates/kobako-runtime/src/network/builder.rs +177 -0
  72. data/crates/kobako-runtime/src/network/ruleset.rs +777 -0
  73. data/crates/kobako-runtime/src/network.rs +551 -0
  74. data/crates/kobako-runtime/src/policy.rs +16 -0
  75. data/crates/kobako-runtime/src/profile.rs +37 -16
  76. data/crates/kobako-runtime/src/runtime.rs +3 -5
  77. data/crates/kobako-runtime/src/sched.rs +311 -0
  78. data/crates/kobako-runtime/src/security/entry_policy.rs +22 -0
  79. data/crates/kobako-runtime/src/security/hooks.rs +242 -0
  80. data/crates/kobako-runtime/src/security/mount_policy.rs +158 -0
  81. data/crates/kobako-runtime/src/security.rs +601 -0
  82. data/crates/kobako-runtime/src/snapshot.rs +121 -2
  83. data/crates/kobako-runtime/src/vfs/attr.rs +162 -0
  84. data/crates/kobako-runtime/src/vfs/dentry.rs +1466 -0
  85. data/crates/kobako-runtime/src/vfs/file.rs +1911 -0
  86. data/crates/kobako-runtime/src/vfs/inode.rs +425 -0
  87. data/crates/kobako-runtime/src/vfs/kern_path.rs +213 -0
  88. data/crates/kobako-runtime/src/vfs/mount.rs +60 -0
  89. data/crates/kobako-runtime/src/vfs/namei.rs +5837 -0
  90. data/crates/kobako-runtime/src/vfs/namespace.rs +162 -0
  91. data/crates/kobako-runtime/src/vfs/open_files.rs +69 -0
  92. data/crates/kobako-runtime/src/vfs/openat2.rs +116 -0
  93. data/crates/kobako-runtime/src/vfs/path.rs +64 -0
  94. data/crates/kobako-runtime/src/vfs/readdir.rs +163 -0
  95. data/crates/kobako-runtime/src/vfs/stat.rs +293 -0
  96. data/crates/kobako-runtime/src/vfs/super_block.rs +126 -0
  97. data/crates/kobako-runtime/src/vfs/utimes.rs +299 -0
  98. data/crates/kobako-runtime/src/vfs.rs +63 -0
  99. data/crates/kobako-runtime/src/wait.rs +356 -0
  100. data/crates/kobako-transport/CHANGELOG.md +39 -2
  101. data/crates/kobako-transport/Cargo.toml +3 -3
  102. data/crates/kobako-transport/README.md +8 -8
  103. data/crates/kobako-transport/src/abi.rs +78 -72
  104. data/crates/kobako-transport/src/envelope/bytes.rs +49 -30
  105. data/crates/kobako-transport/src/envelope/call.rs +37 -9
  106. data/crates/kobako-transport/src/envelope/compile_reply.rs +2 -2
  107. data/crates/kobako-transport/src/envelope/error_record.rs +24 -3
  108. data/crates/kobako-transport/src/envelope/fault.rs +2 -2
  109. data/crates/kobako-transport/src/envelope/name.rs +99 -0
  110. data/crates/kobako-transport/src/envelope/outcome.rs +11 -11
  111. data/crates/kobako-transport/src/envelope/preamble.rs +34 -31
  112. data/crates/kobako-transport/src/envelope/reply.rs +29 -29
  113. data/crates/kobako-transport/src/envelope/request.rs +2 -2
  114. data/crates/kobako-transport/src/envelope/run.rs +1 -1
  115. data/crates/kobako-transport/src/envelope/unsupported.rs +12 -12
  116. data/crates/kobako-transport/src/envelope.rs +15 -10
  117. data/crates/kobako-wasmtime/CHANGELOG.md +315 -8
  118. data/crates/kobako-wasmtime/Cargo.toml +35 -15
  119. data/crates/kobako-wasmtime/README.md +11 -6
  120. data/crates/kobako-wasmtime/build/preview2.rs +1339 -0
  121. data/crates/kobako-wasmtime/build.rs +16 -0
  122. data/crates/kobako-wasmtime/src/abi.rs +19 -47
  123. data/crates/kobako-wasmtime/src/ambient.rs +33 -19
  124. data/crates/kobako-wasmtime/src/cache.rs +28 -20
  125. data/crates/kobako-wasmtime/src/config.rs +59 -60
  126. data/crates/kobako-wasmtime/src/driver.rs +63 -145
  127. data/crates/kobako-wasmtime/src/exports.rs +147 -32
  128. data/crates/kobako-wasmtime/src/guest.rs +44 -0
  129. data/crates/kobako-wasmtime/src/guest_binary.rs +14 -0
  130. data/crates/kobako-wasmtime/src/imports.rs +48 -18
  131. data/crates/kobako-wasmtime/src/instance_pre.rs +7 -7
  132. data/crates/kobako-wasmtime/src/invocation.rs +93 -51
  133. data/crates/kobako-wasmtime/src/lib.rs +6 -7
  134. data/crates/kobako-wasmtime/src/limiter.rs +52 -211
  135. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +309 -0
  136. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +70 -57
  137. data/crates/kobako-wasmtime/src/preview1/differential.rs +137 -27
  138. data/crates/kobako-wasmtime/src/preview1/errno.rs +90 -233
  139. data/crates/kobako-wasmtime/src/preview1/fd.rs +1301 -522
  140. data/crates/kobako-wasmtime/src/preview1/memory.rs +126 -150
  141. data/crates/kobako-wasmtime/src/preview1/mount_view/wrap.rs +192 -0
  142. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +1989 -708
  143. data/crates/kobako-wasmtime/src/preview1/path.rs +181 -365
  144. data/crates/kobako-wasmtime/src/preview1/poll.rs +345 -173
  145. data/crates/kobako-wasmtime/src/preview1/sock.rs +10 -25
  146. data/crates/kobako-wasmtime/src/preview1/testsuite-expected.txt +6 -0
  147. data/crates/kobako-wasmtime/src/preview1/testsuite.rs +147 -0
  148. data/crates/kobako-wasmtime/src/preview1.rs +471 -416
  149. data/crates/kobako-wasmtime/src/preview2/abi.rs +227 -0
  150. data/crates/kobako-wasmtime/src/preview2/error.rs +118 -0
  151. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +122 -0
  152. data/crates/kobako-wasmtime/src/preview2/host.rs +3959 -0
  153. data/crates/kobako-wasmtime/src/preview2/http.rs +1503 -0
  154. data/crates/kobako-wasmtime/src/preview2/io.rs +315 -0
  155. data/crates/kobako-wasmtime/src/preview2/sockets.rs +379 -0
  156. data/crates/kobako-wasmtime/src/preview2/table.rs +305 -0
  157. data/crates/kobako-wasmtime/src/preview2.rs +57 -0
  158. data/crates/kobako-wasmtime/src/trap.rs +31 -16
  159. data/crates/kobako-wasmtime/src/wasi.rs +238 -93
  160. data/crates/kobako-wasmtime/wit/deps/cli.wit +233 -0
  161. data/crates/kobako-wasmtime/wit/deps/clocks.wit +162 -0
  162. data/crates/kobako-wasmtime/wit/deps/filesystem.wit +589 -0
  163. data/crates/kobako-wasmtime/wit/deps/http.wit +733 -0
  164. data/crates/kobako-wasmtime/wit/deps/io.wit +299 -0
  165. data/crates/kobako-wasmtime/wit/deps/random.wit +92 -0
  166. data/crates/kobako-wasmtime/wit/deps/sockets.wit +949 -0
  167. data/crates/kobako-wasmtime/witx/typenames.witx +750 -0
  168. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +441 -0
  169. data/data/kobako.wasm +0 -0
  170. data/ext/kobako/Cargo.toml +1 -1
  171. data/ext/kobako/src/{runtime/errors.rs → errors.rs} +35 -27
  172. data/ext/kobako/src/escape.rs +98 -0
  173. data/ext/kobako/src/{runtime/filesystem → filesystem}/grants.rs +36 -16
  174. data/ext/kobako/src/filesystem/ruby.rs +689 -0
  175. data/ext/kobako/src/filesystem.rs +217 -0
  176. data/ext/kobako/src/gvl.rs +306 -0
  177. data/ext/kobako/src/lib.rs +64 -3
  178. data/ext/kobako/src/network/mock.rs +187 -0
  179. data/ext/kobako/src/network.rs +591 -0
  180. data/ext/kobako/src/runtime/bridge.rs +31 -30
  181. data/ext/kobako/src/runtime/snapshot.rs +5 -5
  182. data/ext/kobako/src/runtime.rs +221 -138
  183. data/ext/kobako/src/wire.rs +42 -0
  184. data/lib/kobako/catalog/extensions.rb +19 -7
  185. data/lib/kobako/catalog/flags.rb +4 -6
  186. data/lib/kobako/catalog/grants.rb +5 -4
  187. data/lib/kobako/catalog/handles.rb +9 -31
  188. data/lib/kobako/catalog/mount.rb +12 -12
  189. data/lib/kobako/catalog/network.rb +35 -0
  190. data/lib/kobako/catalog/replacements.rb +28 -0
  191. data/lib/kobako/catalog/services.rb +7 -21
  192. data/lib/kobako/catalog/snippets.rb +10 -25
  193. data/lib/kobako/catalog.rb +4 -1
  194. data/lib/kobako/codec/{utils.rb → boundary.rb} +5 -3
  195. data/lib/kobako/codec/decoder.rb +12 -12
  196. data/lib/kobako/codec/ext_types.rb +5 -7
  197. data/lib/kobako/codec/handle_walk.rb +5 -47
  198. data/lib/kobako/codec/nesting.rb +7 -7
  199. data/lib/kobako/codec/value_budget.rb +134 -42
  200. data/lib/kobako/codec.rb +1 -1
  201. data/lib/kobako/context.rb +28 -15
  202. data/lib/kobako/errors.rb +15 -12
  203. data/lib/kobako/extension.rb +3 -2
  204. data/lib/kobako/filesystem.rb +53 -15
  205. data/lib/kobako/handle.rb +2 -2
  206. data/lib/kobako/names.rb +28 -0
  207. data/lib/kobako/network.rb +210 -0
  208. data/lib/kobako/outcome.rb +7 -7
  209. data/lib/kobako/payload/arguments.rb +2 -2
  210. data/lib/kobako/pool.rb +47 -25
  211. data/lib/kobako/runtime.rb +3 -2
  212. data/lib/kobako/sandbox.rb +113 -56
  213. data/lib/kobako/sandbox_options.rb +41 -107
  214. data/lib/kobako/snippet/bytecode.rb +1 -1
  215. data/lib/kobako/snippet/source.rb +1 -1
  216. data/lib/kobako/transport/argument_wrap.rb +64 -0
  217. data/lib/kobako/transport/block_failure.rb +1 -1
  218. data/lib/kobako/transport/dispatcher.rb +10 -10
  219. data/lib/kobako/transport/exposure.rb +28 -17
  220. data/lib/kobako/transport/reflection.rb +28 -11
  221. data/lib/kobako/transport/run.rb +13 -28
  222. data/lib/kobako/transport/yielder.rb +3 -10
  223. data/lib/kobako/transport.rb +1 -0
  224. data/lib/kobako/version.rb +1 -1
  225. data/lib/kobako.rb +38 -0
  226. data/release-please-config.json +16 -0
  227. data/sig/core/thread.rbs +6 -0
  228. data/sig/kobako/catalog/extensions.rbs +5 -3
  229. data/sig/kobako/catalog/grants.rbs +7 -4
  230. data/sig/kobako/catalog/handles.rbs +2 -4
  231. data/sig/kobako/catalog/mount.rbs +3 -5
  232. data/sig/kobako/catalog/network.rbs +20 -0
  233. data/sig/kobako/catalog/replacements.rbs +14 -0
  234. data/sig/kobako/catalog/services.rbs +1 -5
  235. data/sig/kobako/catalog/snippets.rbs +3 -5
  236. data/sig/kobako/catalog.rbs +1 -1
  237. data/sig/kobako/codec/boundary.rbs +9 -0
  238. data/sig/kobako/codec/decoder.rbs +1 -1
  239. data/sig/kobako/codec/handle_walk.rbs +0 -6
  240. data/sig/kobako/codec/nesting.rbs +2 -2
  241. data/sig/kobako/codec/value_budget.rbs +48 -5
  242. data/sig/kobako/codec.rbs +1 -2
  243. data/sig/kobako/context.rbs +4 -2
  244. data/sig/kobako/errors.rbs +4 -4
  245. data/sig/kobako/filesystem.rbs +38 -15
  246. data/sig/kobako/guest_yielder.rbs +1 -1
  247. data/sig/kobako/network.rbs +115 -0
  248. data/sig/kobako/outcome.rbs +1 -1
  249. data/sig/kobako/payload/arguments.rbs +1 -1
  250. data/sig/kobako/pool.rbs +8 -4
  251. data/sig/kobako/runtime.rbs +32 -3
  252. data/sig/kobako/sandbox.rbs +22 -7
  253. data/sig/kobako/sandbox_options.rbs +29 -38
  254. data/sig/kobako/transport/argument_wrap.rbs +15 -0
  255. data/sig/kobako/transport/dispatcher.rbs +2 -2
  256. data/sig/kobako/transport/error.rbs +1 -1
  257. data/sig/kobako/transport/exposure.rbs +3 -5
  258. data/sig/kobako/transport/reflection.rbs +12 -2
  259. data/sig/kobako/transport/run.rbs +3 -5
  260. data/sig/kobako/transport/yielder.rbs +0 -3
  261. data/sig/kobako/transport.rbs +2 -2
  262. data/sig/kobako.rbs +13 -0
  263. metadata +131 -34
  264. data/crates/kobako-runtime/src/filesystem/directory/spelling.rs +0 -194
  265. data/crates/kobako-runtime/src/filesystem/directory.rs +0 -1082
  266. data/crates/kobako-runtime/src/filesystem/memory.rs +0 -1100
  267. data/crates/kobako-runtime/src/filesystem/overlay/exclusive.rs +0 -88
  268. data/crates/kobako-runtime/src/filesystem/path.rs +0 -60
  269. data/crates/kobako-runtime/src/filesystem/temporary.rs +0 -167
  270. data/crates/kobako-wasmtime/src/capture.rs +0 -96
  271. data/crates/kobako-wasmtime/src/descriptors.rs +0 -167
  272. data/crates/kobako-wasmtime/src/dispatch.rs +0 -125
  273. data/crates/kobako-wasmtime/src/guest_mem.rs +0 -271
  274. data/crates/kobako-wasmtime/src/io.rs +0 -89
  275. data/crates/kobako-wasmtime/src/preview1/args.rs +0 -60
  276. data/crates/kobako-wasmtime/src/preview1/beneath.rs +0 -188
  277. data/crates/kobako-wasmtime/tests/compile_posture.rs +0 -43
  278. data/crates/kobako-wasmtime/tests/guest_file.rs +0 -1054
  279. data/crates/kobako-wasmtime/tests/preamble_flags.rs +0 -70
  280. data/crates/kobako-wasmtime/tests/snippet_compile.rs +0 -95
  281. data/crates/kobako-wasmtime/tests/support/mod.rs +0 -30
  282. data/crates/kobako-wasmtime/tests/unanswered_call.rs +0 -86
  283. data/crates/kobako-wasmtime/tests/unsupported_call.rs +0 -51
  284. data/ext/kobako/src/runtime/escape.rs +0 -53
  285. data/ext/kobako/src/runtime/filesystem/ruby.rs +0 -400
  286. data/ext/kobako/src/runtime/filesystem.rs +0 -236
  287. data/ext/kobako/src/runtime/gvl.rs +0 -112
  288. data/lib/kobako/constant_name.rb +0 -8
  289. data/sig/kobako/codec/utils.rbs +0 -9
  290. data/sig/kobako/constant_name.rbs +0 -3
  291. /data/ext/kobako/src/{runtime/pinned_value.rs → pinned_value.rs} +0 -0
@@ -0,0 +1,1466 @@
1
+ //! The names of one Filesystem a walk has reached, each kept by the
2
+ //! directory above it and its name there while something holds it, as
3
+ //! Linux's dentries are: a directory moved through the VFS takes every one
4
+ //! beneath it along, and one removed or replaced through it is dead. A name
5
+ //! found standing stays for the next walk, as Linux's dcache keeps it, up to a
6
+ //! bound; the walk asks `revalidate` before trusting it, so what changed behind
7
+ //! the runtime's back is found again.
8
+
9
+ use std::any::Any;
10
+ use std::num::NonZeroUsize;
11
+ use std::sync::atomic::{AtomicUsize, Ordering};
12
+ use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError, Weak};
13
+ use std::thread::ThreadId;
14
+
15
+ use lru::LruCache;
16
+
17
+ use super::file::FileOperations;
18
+ use super::inode::{Identity, Inode, InodeOperations, Lookup};
19
+ use super::{Errno, FileType, Kstat, OpenHow, SuperBlock};
20
+ use crate::hashtable::Hashtable;
21
+ use crate::locking::seqlock::SeqLock;
22
+ use crate::locking::RwSemaphoreGuard;
23
+ use crate::sched;
24
+
25
+ /// What a Filesystem answers about a name rather than an entry, as Linux's
26
+ /// `dentry_operations`: a name may stand for nothing, so no inode can answer
27
+ /// for it.
28
+ pub trait DentryOperations: Send + Sync {
29
+ /// Whether `dentry`, a name the runtime still holds in `dir`, names what
30
+ /// it recorded, as `d_revalidate` answers; `false` has the runtime drop
31
+ /// it and take the name afresh.
32
+ fn revalidate(&self, dir: &dyn InodeOperations, dentry: &Dentry) -> Result<bool, Errno>;
33
+
34
+ /// Whether `dentry` goes once nothing holds it, rather than stay for the
35
+ /// next walk, as `d_delete` answers. A name whose `revalidate` cannot tell
36
+ /// a change must answer `true`, since it would be trusted when reached again.
37
+ fn delete(&self, _dentry: &Dentry) -> bool {
38
+ false
39
+ }
40
+ }
41
+
42
+ /// The most names a Filesystem keeps that nothing holds.
43
+ const MAX_CACHED_DENTRIES: NonZeroUsize = NonZeroUsize::new(1024).expect("the bound is not zero");
44
+
45
+ /// Every move of a dentry, as Linux's `rename_lock`, so a walk up its
46
+ /// parents answers where the dentry stood at one instant, and a walk learns of a
47
+ /// move landing meanwhile.
48
+ pub(super) static RENAME_LOCK: SeqLock = SeqLock::new();
49
+
50
+ /// One name of a Filesystem, and where it stands now. Only the VFS makes
51
+ /// one, so a Filesystem reads the name a call is about from it.
52
+ pub struct Dentry {
53
+ state: Mutex<State>,
54
+ /// This dentry, for whoever is handed it to keep, as Linux's `dget`
55
+ /// takes a reference to any dentry it is handed.
56
+ this: Weak<Dentry>,
57
+ /// The tables of its Filesystem instance a walk finds it in, as `d_sb`
58
+ /// reaches the instance a dentry belongs to.
59
+ hashtables: Arc<Hashtables>,
60
+ /// What the Filesystem keeps on the name, set once, as Linux's
61
+ /// `d_fsdata` holds a filesystem's own state for a dentry.
62
+ fsdata: OnceLock<Arc<dyn Any + Send + Sync>>,
63
+ /// What answers about this name, as `d_alloc` copies `__s_d_op` from the
64
+ /// super block.
65
+ ops: Option<Arc<dyn DentryOperations>>,
66
+ /// Wakes the walks waiting while another looks this name up, as Linux's
67
+ /// `d_wait_lookup` waits for `DCACHE_PAR_LOOKUP` to clear.
68
+ wait: Condvar,
69
+ /// How many mount namespaces stand a mount on it, as Linux's
70
+ /// `DCACHE_MOUNTED` marks a mount point while any mount stands there.
71
+ mounts: AtomicUsize,
72
+ }
73
+
74
+ /// Where a walk asking for a lookup stands, as `d_alloc_parallel` answers.
75
+ enum InLookup {
76
+ /// A lookup already answered for the name.
77
+ Answered,
78
+ /// This walk asks, and ends the lookup once answered.
79
+ Begun,
80
+ /// This walk's own lookup of the name is under way, and asks again within it.
81
+ Within,
82
+ }
83
+
84
+ struct State {
85
+ /// The directory above, `None` where the dentry is a root, which stands as
86
+ /// its own parent, as Linux's `d_parent == self`, held without a cycle.
87
+ parent: Option<Arc<Dentry>>,
88
+ name: String,
89
+ /// What the name stands for once a lookup found it, `None` while the
90
+ /// dentry is negative.
91
+ inode: Option<Arc<Inode>>,
92
+ /// Where the lookup of the name stands, so a negative dentry says nothing
93
+ /// stands there rather than that nobody asked.
94
+ asked: LookupState,
95
+ /// Whether a walk finds it by its name, as Linux's `d_hash` links it into
96
+ /// `dentry_hashtable`; one still in lookup, or let go of, is not.
97
+ hashed: bool,
98
+ }
99
+
100
+ /// Where the lookup of a name stands, as `DCACHE_PAR_LOOKUP` marks a dentry a
101
+ /// walk is asking its Filesystem about and `d_add` ends that.
102
+ #[derive(Clone, Copy, PartialEq, Eq)]
103
+ enum LookupState {
104
+ /// No lookup answered for the name: none asked yet, or the one that did
105
+ /// ended without an answer here, as `d_lookup_done` leaves a dentry.
106
+ Unasked,
107
+ /// In lookup for the walk that made the dentry, which has yet to ask, as
108
+ /// `d_alloc_parallel` marks the dentry it makes.
109
+ Allocated(ThreadId),
110
+ /// The walk asking the Filesystem what stands here, while it asks.
111
+ Asking(ThreadId),
112
+ /// A lookup answered for the name, or a call made what stands there.
113
+ Answered,
114
+ }
115
+
116
+ impl Dentry {
117
+ fn new(
118
+ parent: Option<Arc<Dentry>>,
119
+ name: &str,
120
+ ops: Option<Arc<dyn DentryOperations>>,
121
+ hashtables: &Arc<Hashtables>,
122
+ ) -> Arc<Self> {
123
+ Arc::new_cyclic(|this| Self {
124
+ state: Mutex::new(State {
125
+ parent,
126
+ name: name.to_string(),
127
+ inode: None,
128
+ asked: LookupState::Unasked,
129
+ hashed: false,
130
+ }),
131
+ this: this.clone(),
132
+ hashtables: hashtables.clone(),
133
+ fsdata: OnceLock::new(),
134
+ ops,
135
+ wait: Condvar::new(),
136
+ mounts: AtomicUsize::new(0),
137
+ })
138
+ }
139
+
140
+ /// A mount stands on it from now on, as Linux's `d_set_mounted`.
141
+ pub(crate) fn d_set_mounted(&self) {
142
+ self.mounts.fetch_add(1, Ordering::SeqCst);
143
+ }
144
+
145
+ /// A mount standing on it is gone, as `unpin_mountpoint` lets go of it and
146
+ /// `maybe_free_mountpoint` clears `DCACHE_MOUNTED` once the last one goes.
147
+ pub(crate) fn unpin_mountpoint(&self) {
148
+ self.mounts.fetch_sub(1, Ordering::SeqCst);
149
+ }
150
+
151
+ /// Whether a mount stands on it, as Linux's `d_mountpoint`.
152
+ pub(crate) fn d_mountpoint(&self) -> bool {
153
+ self.mounts.load(Ordering::SeqCst) > 0
154
+ }
155
+
156
+ /// What answers about this name, the same for every dentry of one
157
+ /// Filesystem.
158
+ pub fn ops(&self) -> Option<&Arc<dyn DentryOperations>> {
159
+ self.ops.as_ref()
160
+ }
161
+
162
+ /// The directory above, this dentry itself at a root, as Linux's
163
+ /// `dget_parent` takes it.
164
+ pub(crate) fn parent(&self) -> Arc<Dentry> {
165
+ self.parent_and_name().0
166
+ }
167
+
168
+ /// Whether this dentry is a root, standing as its own parent, as Linux's
169
+ /// `IS_ROOT` answers.
170
+ pub(crate) fn is_root(&self) -> bool {
171
+ self.state().parent.is_none()
172
+ }
173
+
174
+ /// The directory above and the name there, read together, so a move
175
+ /// landing meanwhile cannot pair one's parent with the other's name, as 9p
176
+ /// holds `rename_sem` to read both.
177
+ pub(crate) fn parent_and_name(&self) -> (Arc<Dentry>, String) {
178
+ let state = self.state();
179
+ let parent = state.parent.clone().unwrap_or_else(|| self.get());
180
+ (parent, state.name.clone())
181
+ }
182
+
183
+ /// This dentry, kept for as long as the caller holds it, as Linux's
184
+ /// `dget` does.
185
+ pub(crate) fn get(&self) -> Arc<Dentry> {
186
+ self.this
187
+ .upgrade()
188
+ .expect("a dentry handed out is held by whoever handed it")
189
+ }
190
+
191
+ fn state(&self) -> MutexGuard<'_, State> {
192
+ self.state.lock().unwrap_or_else(PoisonError::into_inner)
193
+ }
194
+
195
+ /// The name in the directory above, empty for the root.
196
+ pub fn name(&self) -> String {
197
+ self.state().name.clone()
198
+ }
199
+
200
+ /// Where this name stands now beneath the Filesystem's root, from a
201
+ /// leading `/` that alone names the root, as Linux's `dentry_path_raw`
202
+ /// answers.
203
+ pub fn path_raw(&self) -> String {
204
+ format!("/{}", self.names().join("/"))
205
+ }
206
+
207
+ /// Each name from the Filesystem's root down to this directory, as Linux's
208
+ /// `__dentry_path` walks up until `IS_ROOT`.
209
+ fn names(&self) -> Vec<String> {
210
+ RENAME_LOCK.read(|| {
211
+ let mut names = Vec::new();
212
+ let mut at = self.get();
213
+ while !at.is_root() {
214
+ let (parent, name) = at.parent_and_name();
215
+ names.push(name);
216
+ at = parent;
217
+ }
218
+ names.reverse();
219
+ names
220
+ })
221
+ }
222
+
223
+ /// Hold the directory this names shared, as
224
+ /// `inode_lock_shared(d_inode(dentry))`.
225
+ pub(crate) fn inode_lock_shared(&self) -> Result<RwSemaphoreGuard, Errno> {
226
+ self.inode().ok_or(Errno::NotFound)?.lock_shared()
227
+ }
228
+
229
+ /// Hold the directory this names exclusive, as
230
+ /// `inode_lock(d_inode(dentry))`.
231
+ pub(crate) fn inode_lock(&self) -> Result<RwSemaphoreGuard, Errno> {
232
+ self.inode().ok_or(Errno::NotFound)?.lock()
233
+ }
234
+
235
+ /// Whether the directory this names was removed or replaced, as
236
+ /// `IS_DEADDIR(d_inode(dentry))`.
237
+ pub(crate) fn is_deaddir(&self) -> bool {
238
+ self.inode().is_some_and(|inode| inode.is_deaddir())
239
+ }
240
+
241
+ /// Mark the directory this names removed or replaced.
242
+ pub(super) fn mark_dead(&self) {
243
+ if let Some(inode) = self.inode() {
244
+ inode.mark_dead();
245
+ }
246
+ }
247
+
248
+ /// What the name stands for, `None` while the dentry is negative, as
249
+ /// Linux's `d_inode` reads it.
250
+ pub fn inode(&self) -> Option<Arc<Inode>> {
251
+ self.state().inode.clone()
252
+ }
253
+
254
+ /// What answers for the entry this names, as `d_inode(dentry)->i_op`.
255
+ pub(crate) fn inode_ops(&self) -> Result<Arc<dyn InodeOperations>, Errno> {
256
+ match self.inode() {
257
+ Some(inode) => Ok(inode.ops().clone()),
258
+ None => Err(Errno::NotFound),
259
+ }
260
+ }
261
+
262
+ /// Record `inode` as what the name stands for, `None` where nothing
263
+ /// does, as a Filesystem's lookup hands Linux's `d_add` what it found.
264
+ /// A dentry already naming something keeps it, as Linux instantiates a
265
+ /// dentry once, so a later lookup never hides a change `d_revalidate`
266
+ /// must see.
267
+ pub fn add(&self, inode: Option<Arc<Inode>>) {
268
+ match inode {
269
+ Some(inode) => self.hashtables.iget5_locked(inode).add_hashed(self),
270
+ None => self.rehash(),
271
+ }
272
+ }
273
+
274
+ /// End the lookup of this name with an answer, and let a walk find it by
275
+ /// its name from now on, waking every walk waiting on it, as Linux's
276
+ /// `__d_add` takes it out of `in_lookup_hashtable` and `__d_rehash`es it.
277
+ pub(super) fn rehash(&self) {
278
+ {
279
+ let mut table = self.hashtables.dentry_hashtable();
280
+ let mut in_lookup = self.hashtables.in_lookup_hashtable();
281
+ let (parent, name) = self.parent_and_name();
282
+ let at = key(&parent, &name);
283
+ let this = self.get();
284
+ if in_lookup
285
+ .get(&at)
286
+ .is_some_and(|held| Arc::ptr_eq(&held, &this))
287
+ {
288
+ in_lookup.remove(&at);
289
+ }
290
+ let mut state = self.state();
291
+ state.asked = LookupState::Answered;
292
+ if !state.hashed {
293
+ table.insert(at, &this);
294
+ state.hashed = true;
295
+ }
296
+ }
297
+ self.wait.notify_all();
298
+ }
299
+
300
+ /// Whether a walk finds this dentry by its name, as Linux's `!d_unhashed`
301
+ /// answers.
302
+ pub(super) fn hashed(&self) -> bool {
303
+ self.state().hashed
304
+ }
305
+
306
+ /// Record `inode` on this dentry, which no walk finds by a name, as
307
+ /// `d_instantiate` hangs a root or a pseudo dentry on `i_dentry` under
308
+ /// `i_lock`.
309
+ pub(crate) fn instantiate(&self, inode: Arc<Inode>) {
310
+ let mut held = inode.dentry();
311
+ self.__instantiate(inode.clone(), &mut held);
312
+ }
313
+
314
+ /// Record `inode` here unless the dentry already names something, a
315
+ /// directory's `held` dentry being this one from then on, as
316
+ /// `__d_instantiate` hangs the dentry on `i_dentry`. The caller holds
317
+ /// `held`, the inode's lock on the dentry it keeps.
318
+ pub(super) fn __instantiate(&self, inode: Arc<Inode>, held: &mut Weak<Dentry>) {
319
+ let mut state = self.state();
320
+ if state.inode.is_none() {
321
+ if inode.file_type() == FileType::Dir {
322
+ *held = self.this.clone();
323
+ }
324
+ state.inode = Some(inode);
325
+ }
326
+ }
327
+
328
+ /// What the Filesystem keeps on the name, set once, as Linux's
329
+ /// `d_fsdata` holds a filesystem's own state for a dentry.
330
+ pub fn fsdata(&self) -> &OnceLock<Arc<dyn Any + Send + Sync>> {
331
+ &self.fsdata
332
+ }
333
+
334
+ /// Whether this goes once nothing holds it, as `d_delete` answers; a name
335
+ /// no one answers for stays.
336
+ pub(crate) fn goes_when_unused(&self) -> bool {
337
+ self.ops.as_ref().is_some_and(|ops| ops.delete(self))
338
+ }
339
+
340
+ /// Whether both names stand for one entry, as hard links do, which Linux's
341
+ /// `vfs_rename` answers as having nothing to move, comparing `source ==
342
+ /// target`. A Filesystem naming no identity cannot tell.
343
+ pub(crate) fn names_the_entry_of(&self, other: &Dentry) -> bool {
344
+ let identity = |dentry: &Dentry| dentry.inode().and_then(|inode| inode.identity());
345
+ identity(self).is_some() && identity(self) == identity(other)
346
+ }
347
+
348
+ /// Whether a walk is still looking the name up, as Linux's `d_in_lookup`
349
+ /// tells a Filesystem's `atomic_open` the dentry it must look up first.
350
+ pub fn in_lookup(&self) -> bool {
351
+ matches!(
352
+ self.state().asked,
353
+ LookupState::Allocated(_) | LookupState::Asking(_)
354
+ )
355
+ }
356
+
357
+ /// Ask the directory `dir` of `sb` what stands here where no lookup answered
358
+ /// yet, and record it, as Linux's `lookup_fast` keeps a dentry, a negative
359
+ /// one too, and `__lookup_slow` asks `->lookup` for one just made. The
360
+ /// dentry to use in place of this one is handed back as `d_splice_alias`
361
+ /// hands it, none where this one records the answer.
362
+ pub(crate) fn lookup_inode(
363
+ &self,
364
+ sb: &SuperBlock,
365
+ dir: &Dentry,
366
+ ) -> Result<Option<Arc<Dentry>>, Errno> {
367
+ let asked = self.ask_in_lookup(|| {
368
+ let found = dir.inode_ops()?.lookup(self)?;
369
+ self.splice_alias(sb, found)
370
+ })?;
371
+ Ok(asked.flatten())
372
+ }
373
+
374
+ /// What `ask` answers for this name where no lookup answered yet, none where
375
+ /// one did. The walk `d_alloc_parallel` made the dentry for asks, as it
376
+ /// holds the dentry in lookup, and `d_lookup_done` ends that.
377
+ pub(crate) fn ask_in_lookup<T>(
378
+ &self,
379
+ ask: impl FnOnce() -> Result<T, Errno>,
380
+ ) -> Result<Option<T>, Errno> {
381
+ let ends = match self.begin_lookup()? {
382
+ InLookup::Answered => return Ok(None),
383
+ InLookup::Begun => true,
384
+ InLookup::Within => false,
385
+ };
386
+ let asked = ask();
387
+ if ends {
388
+ self.lookup_done();
389
+ }
390
+ asked.map(Some)
391
+ }
392
+
393
+ /// Record what a lookup found at this name of `sb`, as Linux's
394
+ /// `d_splice_alias` does, handing back the dentry to use in place of this
395
+ /// one, none where this one records it. A directory already standing at
396
+ /// another dentry keeps that one, moved here, as a directory has one
397
+ /// dentry: a move that would put it beneath itself answers ELOOP, and one
398
+ /// whose locks another call holds answers ESTALE. An entry stored under
399
+ /// another spelling is recorded on that spelling's dentry, as `d_add_ci`
400
+ /// does.
401
+ pub(crate) fn splice_alias(
402
+ &self,
403
+ sb: &SuperBlock,
404
+ found: Lookup,
405
+ ) -> Result<Option<Arc<Dentry>>, Errno> {
406
+ let inode = match found {
407
+ Lookup::Found(inode) => self.hashtables.iget5_locked(inode),
408
+ Lookup::Absent => {
409
+ self.add(None);
410
+ return Ok(None);
411
+ }
412
+ Lookup::Spelled { name, inode } => return self.add_ci(sb, &name, inode).map(Some),
413
+ };
414
+ match inode.find_alias_or_add(self) {
415
+ None => Ok(None),
416
+ Some(alias) => {
417
+ self.get().unalias(sb, &alias)?;
418
+ Ok(Some(alias))
419
+ }
420
+ }
421
+ }
422
+
423
+ /// The dentry of `name`, the spelling the directory above stores the
424
+ /// entry under, with `inode` spliced on it, as Linux's `d_add_ci` finds
425
+ /// that spelling's dentry, or makes one, rather than asking the
426
+ /// Filesystem again. One already held there is taken as it stands, as
427
+ /// `d_hash_and_lookup` asks no `d_revalidate`.
428
+ pub(crate) fn add_ci(
429
+ &self,
430
+ sb: &SuperBlock,
431
+ name: &str,
432
+ inode: Arc<Inode>,
433
+ ) -> Result<Arc<Dentry>, Errno> {
434
+ let found = sb.dentries().alloc_parallel(&self.parent(), name)?;
435
+ let spliced = found.ask_in_lookup(|| found.splice_alias(sb, Lookup::Found(inode)))?;
436
+ Ok(spliced.flatten().unwrap_or(found))
437
+ }
438
+
439
+ /// `alias`, where a directory of `sb` stands, moved to this dentry's name,
440
+ /// taking its place, as Linux's `__d_unalias` moves it under `rename_lock`.
441
+ /// One that would stand beneath itself answers ELOOP, as `d_ancestor`
442
+ /// refuses it; so does a root, which only a Filesystem handing one inode
443
+ /// to two instances reaches. A move out of another directory takes that
444
+ /// directory's lock and the instance's `rename_mutex` without waiting,
445
+ /// since the caller holds the lock of the one it looks the name up in,
446
+ /// and answers ESTALE where another call holds either.
447
+ fn unalias(self: &Arc<Self>, sb: &SuperBlock, alias: &Arc<Dentry>) -> Result<(), Errno> {
448
+ let (parent, name) = self.parent_and_name();
449
+ let mut table = self.hashtables.dentry_hashtable();
450
+ RENAME_LOCK.write(|| {
451
+ if d_ancestor(alias, self) || alias.is_root() {
452
+ return Err(Errno::FilesystemLoop);
453
+ }
454
+ let (old_parent, old_name) = alias.parent_and_name();
455
+ let _held = match Arc::ptr_eq(&old_parent, &parent) {
456
+ true => None,
457
+ false => {
458
+ let stale = || Errno::StaleNetworkFileHandle;
459
+ let rename = sb.rename_mutex().down_write_trylock().ok_or_else(stale)?;
460
+ let dir = old_parent
461
+ .inode()
462
+ .expect("a directory holding a dentry names its inode")
463
+ .trylock_shared();
464
+ Some((rename, dir.ok_or_else(stale)?))
465
+ }
466
+ };
467
+ let mut state = alias.state();
468
+ if state.hashed {
469
+ table.remove(&key(&old_parent, &old_name));
470
+ }
471
+ table.insert(key(&parent, &name), alias);
472
+ state.hashed = true;
473
+ state.parent = Some(parent.clone());
474
+ state.name = name.clone();
475
+ Ok(())
476
+ })
477
+ }
478
+
479
+ /// Begin the lookup the calling walk holds the dentry in lookup for, or one
480
+ /// nobody asked yet, once no other walk holds it. A Filesystem asking the
481
+ /// runtime about the name its own lookup is answering asks it again within
482
+ /// that lookup, as it would otherwise wait on itself.
483
+ fn begin_lookup(&self) -> Result<InLookup, Errno> {
484
+ self.wait_lookup()?;
485
+ let mut state = self.state();
486
+ Ok(match state.asked {
487
+ LookupState::Asking(_) => InLookup::Within,
488
+ LookupState::Answered => InLookup::Answered,
489
+ LookupState::Allocated(_) | LookupState::Unasked => {
490
+ state.asked = LookupState::Asking(sched::current());
491
+ InLookup::Begun
492
+ }
493
+ })
494
+ }
495
+
496
+ /// Wait while another walk holds this name in lookup, until the walk's run
497
+ /// is to stop, as Linux's `d_wait_lookup` does, answering whether the
498
+ /// calling walk holds it in lookup itself.
499
+ fn wait_lookup(&self) -> Result<bool, Errno> {
500
+ let current = sched::current();
501
+ loop {
502
+ let state = self.state();
503
+ match state.asked {
504
+ LookupState::Allocated(walk) | LookupState::Asking(walk) if walk == current => {
505
+ return Ok(true)
506
+ }
507
+ LookupState::Allocated(_) | LookupState::Asking(_)
508
+ if sched::fatal_signal_pending() =>
509
+ {
510
+ return Err(Errno::Interrupted)
511
+ }
512
+ LookupState::Allocated(_) | LookupState::Asking(_) => {
513
+ drop(state);
514
+ sched::schedule(&mut || {
515
+ let state = self.state();
516
+ if matches!(
517
+ state.asked,
518
+ LookupState::Allocated(_) | LookupState::Asking(_)
519
+ ) {
520
+ drop(
521
+ self.wait
522
+ .wait_timeout(state, sched::sleep_slice())
523
+ .unwrap_or_else(PoisonError::into_inner),
524
+ );
525
+ }
526
+ });
527
+ }
528
+ LookupState::Unasked | LookupState::Answered => return Ok(false),
529
+ }
530
+ }
531
+ }
532
+
533
+ /// End this walk's lookup where no answer did, taking the dentry out of
534
+ /// `in_lookup_hashtable` and waking every walk waiting on it, as
535
+ /// `d_lookup_done` does; each of them looks the name up again.
536
+ fn lookup_done(&self) {
537
+ {
538
+ let mut in_lookup = self.hashtables.in_lookup_hashtable();
539
+ let (parent, name) = self.parent_and_name();
540
+ let at = key(&parent, &name);
541
+ let mut state = self.state();
542
+ if matches!(
543
+ state.asked,
544
+ LookupState::Allocated(_) | LookupState::Asking(_)
545
+ ) {
546
+ if in_lookup
547
+ .get(&at)
548
+ .is_some_and(|held| std::ptr::eq(held.as_ref(), self))
549
+ {
550
+ in_lookup.remove(&at);
551
+ }
552
+ state.asked = LookupState::Unasked;
553
+ }
554
+ }
555
+ self.wait.notify_all();
556
+ }
557
+
558
+ /// What kind of entry this records, `NotFound` where it records none, as
559
+ /// Linux's `d_is_*` read a dentry without asking its filesystem.
560
+ pub(crate) fn file_type(&self) -> Result<FileType, Errno> {
561
+ self.inode()
562
+ .map(|inode| inode.file_type())
563
+ .ok_or(Errno::NotFound)
564
+ }
565
+
566
+ /// What the entry this records reports of itself, `NotFound` where it
567
+ /// records none, as `vfs_getattr` asks the inode a dentry holds.
568
+ pub(crate) fn getattr(&self) -> Result<Kstat, Errno> {
569
+ match self.inode() {
570
+ Some(inode) => inode.ops().getattr(self),
571
+ None => Err(Errno::NotFound),
572
+ }
573
+ }
574
+
575
+ /// Open the file this records as `how` asks, as `vfs_open` finds
576
+ /// `f_op->open` on the inode a dentry holds.
577
+ pub(crate) fn open(&self, how: &OpenHow) -> Result<Box<dyn FileOperations>, Errno> {
578
+ match self.inode() {
579
+ Some(inode) => inode.ops().open(self, how),
580
+ None => Err(Errno::NotFound),
581
+ }
582
+ }
583
+
584
+ /// Where the link this records points, as `vfs_readlink` asks the inode a
585
+ /// dentry holds; anything else refuses as `readlinkat` does.
586
+ pub(crate) fn get_link(&self) -> Result<String, Errno> {
587
+ match self.inode() {
588
+ Some(inode) => inode.ops().get_link(self),
589
+ None => Err(Errno::NotFound),
590
+ }
591
+ }
592
+
593
+ /// Whether this dentry is `ancestor` or stands beneath it, as Linux's
594
+ /// `is_subdir` answers.
595
+ pub(crate) fn is_subdir(self: &Arc<Self>, ancestor: &Arc<Dentry>) -> bool {
596
+ Arc::ptr_eq(self, ancestor) || RENAME_LOCK.read(|| d_ancestor(ancestor, self))
597
+ }
598
+ }
599
+
600
+ /// Whether `ancestor` stands above `dentry`, as Linux's `d_ancestor` answers.
601
+ /// The caller holds `RENAME_LOCK`, so no move lands during the walk up.
602
+ fn d_ancestor(ancestor: &Arc<Dentry>, dentry: &Arc<Dentry>) -> bool {
603
+ let mut at = dentry.clone();
604
+ while !at.is_root() {
605
+ at = at.parent();
606
+ if Arc::ptr_eq(&at, ancestor) {
607
+ return true;
608
+ }
609
+ }
610
+ false
611
+ }
612
+
613
+ /// A dentry holds the one above it, and moves can stack them as deep as a
614
+ /// Filesystem holds directories, so the last reference lets go of each in a
615
+ /// loop, as Linux's `dput` walks up in one.
616
+ impl Drop for Dentry {
617
+ fn drop(&mut self) {
618
+ let parent = |dentry: &mut Dentry| {
619
+ dentry
620
+ .state
621
+ .get_mut()
622
+ .unwrap_or_else(PoisonError::into_inner)
623
+ .parent
624
+ .take()
625
+ };
626
+ let mut above = parent(self);
627
+ while let Some(mut dentry) = above.and_then(Arc::into_inner) {
628
+ above = parent(&mut dentry);
629
+ }
630
+ }
631
+ }
632
+
633
+ /// The directory above a name, by its address, and the name there.
634
+ type Key = (usize, String);
635
+
636
+ fn key(parent: &Arc<Dentry>, name: &str) -> Key {
637
+ (Arc::as_ptr(parent) as usize, name.to_string())
638
+ }
639
+
640
+ /// The dentries of one Filesystem a walk finds by the directory above and the
641
+ /// name there.
642
+ struct Hashtables {
643
+ /// Those a lookup answered, as Linux's `dentry_hashtable`.
644
+ dentry_hashtable: Mutex<Hashtable<Key, Dentry>>,
645
+ /// Those a walk is still looking up, as Linux's `in_lookup_hashtable`, so
646
+ /// any other walk reaching the name waits for that answer.
647
+ in_lookup_hashtable: Mutex<Hashtable<Key, Dentry>>,
648
+ /// The directories in use, by the identity each reports, as Linux's
649
+ /// `inode_hashtable`, so a directory a Filesystem answers anew is the
650
+ /// inode it already was and keeps its one dentry.
651
+ inode_hashtable: Mutex<Hashtable<Identity, Inode>>,
652
+ }
653
+
654
+ impl Hashtables {
655
+ /// The inode in use for the directory `inode` reports, or `inode` itself,
656
+ /// kept for the next lookup, as `iget5_locked` finds a live inode by its
657
+ /// number before it hands a new one. A directory removed is found no more,
658
+ /// and an entry naming no identity is never kept.
659
+ fn iget5_locked(&self, inode: Arc<Inode>) -> Arc<Inode> {
660
+ let Some(identity) = inode
661
+ .identity()
662
+ .filter(|_| inode.file_type() == FileType::Dir)
663
+ else {
664
+ return inode;
665
+ };
666
+ let mut table = self.inode_hashtable();
667
+ match table.get(&identity) {
668
+ Some(found) if found.file_type() == FileType::Dir && !found.is_deaddir() => found,
669
+ _ => {
670
+ table.insert(identity, &inode);
671
+ inode
672
+ }
673
+ }
674
+ }
675
+
676
+ fn inode_hashtable(&self) -> MutexGuard<'_, Hashtable<Identity, Inode>> {
677
+ self.inode_hashtable
678
+ .lock()
679
+ .unwrap_or_else(PoisonError::into_inner)
680
+ }
681
+
682
+ fn dentry_hashtable(&self) -> MutexGuard<'_, Hashtable<Key, Dentry>> {
683
+ self.dentry_hashtable
684
+ .lock()
685
+ .unwrap_or_else(PoisonError::into_inner)
686
+ }
687
+
688
+ /// Taken after `dentry_hashtable` where a call holds both.
689
+ fn in_lookup_hashtable(&self) -> MutexGuard<'_, Hashtable<Key, Dentry>> {
690
+ self.in_lookup_hashtable
691
+ .lock()
692
+ .unwrap_or_else(PoisonError::into_inner)
693
+ }
694
+ }
695
+
696
+ /// Every name of one Filesystem something still holds, by the directory
697
+ /// above it and its name there.
698
+ pub(crate) struct Dentries {
699
+ ops: Option<Arc<dyn DentryOperations>>,
700
+ hashtables: Arc<Hashtables>,
701
+ /// The names kept for the next walk, most recently found last, as Linux's
702
+ /// `d_lru`, each by its address.
703
+ lru: Mutex<LruCache<usize, Arc<Dentry>>>,
704
+ }
705
+
706
+ impl Dentries {
707
+ pub(crate) fn new(ops: Option<Arc<dyn DentryOperations>>) -> Self {
708
+ let hashtables = Arc::new(Hashtables {
709
+ dentry_hashtable: Mutex::default(),
710
+ in_lookup_hashtable: Mutex::default(),
711
+ inode_hashtable: Mutex::default(),
712
+ });
713
+ Self {
714
+ ops,
715
+ hashtables,
716
+ lru: Mutex::new(LruCache::new(MAX_CACHED_DENTRIES)),
717
+ }
718
+ }
719
+
720
+ /// What every dentry of this table answers through.
721
+ pub(super) fn ops(&self) -> Option<&Arc<dyn DentryOperations>> {
722
+ self.ops.as_ref()
723
+ }
724
+
725
+ fn lru(&self) -> MutexGuard<'_, LruCache<usize, Arc<Dentry>>> {
726
+ self.lru.lock().unwrap_or_else(PoisonError::into_inner)
727
+ }
728
+
729
+ /// Keep `dentry`, which a lookup answered for, standing or not, for the next
730
+ /// walk, unless no walk finds it by its name any more or its Filesystem lets
731
+ /// it go, as `retain_dentry` adds a hashed dentry `d_delete` allows to the
732
+ /// LRU. What this pushes out goes once the table is let go of, as its
733
+ /// release may reach another Filesystem.
734
+ /// The check and the keeping run under the dentry's lock, which `unhash`
735
+ /// takes too, as both hold `d_lock`.
736
+ pub(crate) fn retain(&self, dentry: &Arc<Dentry>) {
737
+ if dentry.goes_when_unused() {
738
+ return;
739
+ }
740
+ let state = dentry.state();
741
+ if !state.hashed {
742
+ return;
743
+ }
744
+ let pushed_out = self
745
+ .lru()
746
+ .push(Arc::as_ptr(dentry) as usize, dentry.clone());
747
+ drop(state);
748
+ drop(pushed_out);
749
+ }
750
+
751
+ /// Have every dentry made from now on answer through `ops`, as
752
+ /// `set_default_d_op` sets `__s_d_op` for each `d_alloc` after it.
753
+ pub(super) fn set_ops(&mut self, ops: Arc<dyn DentryOperations>) {
754
+ self.ops = Some(ops);
755
+ }
756
+
757
+ /// A root dentry recording `inode`, as `d_make_root` allocates one under no
758
+ /// name and instantiates it.
759
+ pub(super) fn make_root(&self, inode: Arc<Inode>) -> Arc<Dentry> {
760
+ let root = Dentry::new(None, "", self.ops.clone(), &self.hashtables);
761
+ root.instantiate(inode);
762
+ root
763
+ }
764
+
765
+ /// A dentry no walk reaches, a root of its own under no name, as
766
+ /// `d_alloc_pseudo` makes one for what is only ever open.
767
+ pub(crate) fn alloc_pseudo(&self) -> Arc<Dentry> {
768
+ Dentry::new(None, "", self.ops.clone(), &self.hashtables)
769
+ }
770
+
771
+ /// The dentry a lookup answered for `name` in `parent`, or a new one in
772
+ /// lookup for the calling walk, as Linux's `d_alloc_parallel` finds or
773
+ /// makes one. A walk finding the name in lookup by another waits for that
774
+ /// walk's answer, until its run is to stop, and takes the dentry where the
775
+ /// answer left it at the name, or looks again, as `d_alloc_parallel`
776
+ /// retries on a mismatch.
777
+ pub(crate) fn alloc_parallel(
778
+ &self,
779
+ parent: &Arc<Dentry>,
780
+ name: &str,
781
+ ) -> Result<Arc<Dentry>, Errno> {
782
+ let at = key(parent, name);
783
+ loop {
784
+ let waited = {
785
+ let table = self.hashtables.dentry_hashtable();
786
+ if let Some(found) = table.get(&at) {
787
+ return Ok(found);
788
+ }
789
+ let mut in_lookup = self.hashtables.in_lookup_hashtable();
790
+ match in_lookup.get(&at) {
791
+ Some(waited) => waited,
792
+ None => {
793
+ let made = Dentry::new(
794
+ Some(parent.clone()),
795
+ name,
796
+ self.ops.clone(),
797
+ &self.hashtables,
798
+ );
799
+ made.state().asked = LookupState::Allocated(sched::current());
800
+ in_lookup.insert(at, &made);
801
+ return Ok(made);
802
+ }
803
+ }
804
+ };
805
+ if waited.wait_lookup()? {
806
+ return Ok(waited);
807
+ }
808
+ let (above, called) = waited.parent_and_name();
809
+ if waited.hashed() && Arc::ptr_eq(&above, parent) && called == name {
810
+ return Ok(waited);
811
+ }
812
+ }
813
+ }
814
+
815
+ /// The dentry a lookup answered for `name` in `parent`, as `d_lookup` finds
816
+ /// one.
817
+ pub(crate) fn lookup(&self, parent: &Arc<Dentry>, name: &str) -> Option<Arc<Dentry>> {
818
+ self.hashtables.dentry_hashtable().get(&key(parent, name))
819
+ }
820
+
821
+ /// Whether `dentry` was let go of from its name, as Linux's `d_unlinked`
822
+ /// answers; a root never is.
823
+ pub(crate) fn unlinked(&self, dentry: &Arc<Dentry>) -> bool {
824
+ !dentry.is_root() && !dentry.hashed()
825
+ }
826
+
827
+ /// Let go of `dentry`, which no longer names what stood at its name when
828
+ /// `RENAME_LOCK` read `asked`, and of the names kept beneath it, as Linux's
829
+ /// `d_invalidate` drops it and shrinks what is below a positive one. One a
830
+ /// move carried elsewhere since stays where it went: every move takes this
831
+ /// table before it writes, so none lands between the check and the drop.
832
+ pub(crate) fn invalidate(&self, dentry: &Arc<Dentry>, asked: usize) {
833
+ {
834
+ let mut table = self.hashtables.dentry_hashtable();
835
+ if RENAME_LOCK.read_seqretry(asked) || !dentry.hashed() {
836
+ return;
837
+ }
838
+ drop_hashed(&mut table, dentry);
839
+ }
840
+ let kept = self.lru().pop(&(Arc::as_ptr(dentry) as usize));
841
+ drop(kept);
842
+ if dentry.inode().is_some() {
843
+ self.shrink_dcache_parent(dentry);
844
+ }
845
+ }
846
+
847
+ /// Let go of the names kept for the next walk beneath `parent`, as Linux's
848
+ /// `shrink_dcache_parent` frees the unused dentries below one; one something
849
+ /// still holds stays with its holder. They are found through the LRU, the
850
+ /// only place keeping a dentry nothing else holds, rather than a list of
851
+ /// children.
852
+ pub(crate) fn shrink_dcache_parent(&self, parent: &Arc<Dentry>) {
853
+ let kept: Vec<Arc<Dentry>> = self.lru().iter().map(|(_, held)| held.clone()).collect();
854
+ // Decided before the LRU's lock is taken, as `retain` holds a name's lock
855
+ // while it takes the LRU's.
856
+ let beneath: Vec<usize> = kept
857
+ .iter()
858
+ .filter(|held| !Arc::ptr_eq(held, parent) && held.is_subdir(parent))
859
+ .map(|held| Arc::as_ptr(held) as usize)
860
+ .collect();
861
+ let let_go: Vec<_> = {
862
+ let mut lru = self.lru();
863
+ beneath.iter().filter_map(|at| lru.pop(at)).collect()
864
+ };
865
+ drop(let_go);
866
+ drop(kept);
867
+ }
868
+
869
+ /// Let go of `dentry` from its name, so the next lookup of the name makes
870
+ /// another and whoever holds this one keeps it, as Linux's `d_drop` unhashes
871
+ /// one for `d_invalidate` and for a `d_delete` of one still in use.
872
+ pub(crate) fn unhash(&self, dentry: &Arc<Dentry>) {
873
+ drop_hashed(&mut self.hashtables.dentry_hashtable(), dentry);
874
+ let kept = self.lru().pop(&(Arc::as_ptr(dentry) as usize));
875
+ drop(kept);
876
+ }
877
+
878
+ /// `dentry` moved to the name `target` stands at, taking every one beneath
879
+ /// it along, and `target` let go of, as Linux's `d_move` follows a rename.
880
+ /// A walk finding `dentry` by a name reaches it throughout, so it is never
881
+ /// taken for unlinked.
882
+ pub(crate) fn move_dentry(&self, dentry: &Arc<Dentry>, target: &Arc<Dentry>) {
883
+ self.unhash(target);
884
+ let mut table = self.hashtables.dentry_hashtable();
885
+ let (parent, name) = target.parent_and_name();
886
+ let (from, from_name) = dentry.parent_and_name();
887
+ RENAME_LOCK.write(|| {
888
+ let mut state = dentry.state();
889
+ if state.hashed {
890
+ table.remove(&key(&from, &from_name));
891
+ }
892
+ table.insert(key(&parent, &name), dentry);
893
+ state.hashed = true;
894
+ state.parent = Some(parent.clone());
895
+ state.name = name.clone();
896
+ });
897
+ }
898
+
899
+ /// `first` and `second` trade the names they stand at, as Linux's
900
+ /// `d_exchange` follows an exchange, so whoever holds either reaches
901
+ /// it where it went.
902
+ pub(crate) fn exchange(&self, first: &Arc<Dentry>, second: &Arc<Dentry>) {
903
+ let mut table = self.hashtables.dentry_hashtable();
904
+ let (first_at, second_at) = (first.parent_and_name(), second.parent_and_name());
905
+ RENAME_LOCK.write(|| {
906
+ let (mut one, mut other) = (first.state(), second.state());
907
+ for (state, (parent, name)) in [(&one, &first_at), (&other, &second_at)] {
908
+ if state.hashed {
909
+ table.remove(&key(parent, name));
910
+ }
911
+ }
912
+ table.insert(key(&second_at.0, &second_at.1), first);
913
+ table.insert(key(&first_at.0, &first_at.1), second);
914
+ std::mem::swap(&mut one.parent, &mut other.parent);
915
+ std::mem::swap(&mut one.name, &mut other.name);
916
+ (one.hashed, other.hashed) = (true, true);
917
+ });
918
+ }
919
+ }
920
+
921
+ /// Take `dentry` out of `table` where it is hashed, as Linux's `___d_drop`.
922
+ fn drop_hashed(table: &mut Hashtable<Key, Dentry>, dentry: &Arc<Dentry>) {
923
+ let (parent, name) = dentry.parent_and_name();
924
+ let mut state = dentry.state();
925
+ if state.hashed {
926
+ table.remove(&key(&parent, &name));
927
+ state.hashed = false;
928
+ }
929
+ }
930
+
931
+ #[cfg(test)]
932
+ mod tests {
933
+ use std::any::Any;
934
+ use std::sync::Arc;
935
+
936
+ use super::{Dentries, Dentry};
937
+ use crate::filesystem::{
938
+ FileOperations, FileType, Filesystem, InodeOperations, Kstat, Lookup, Tmpfs,
939
+ };
940
+ use crate::mount::{Access, Mount};
941
+ use crate::vfs::kern_path::{kern_path, KernPath};
942
+ use crate::vfs::{self, File, Finish, Identity, Inode, OpenHow, Path};
943
+ use crate::Errno;
944
+
945
+ /// A root of `dentries` standing for a directory, as `d_make_root` makes one.
946
+ fn make_dir_root(dentries: &Dentries) -> Arc<Dentry> {
947
+ let ops: Arc<dyn InodeOperations> = Arc::new(Tmpfs::new());
948
+ dentries.make_root(Inode::new(&Kstat::new(FileType::Dir, 0), ops))
949
+ }
950
+
951
+ /// The dentry of `name` in `parent`, a lookup having answered that nothing
952
+ /// stands there, so a walk finds it by its name.
953
+ fn negative(dentries: &Dentries, parent: &Arc<Dentry>, name: &str) -> Arc<Dentry> {
954
+ let made = dentries
955
+ .alloc_parallel(parent, name)
956
+ .expect("no other walk holds the name");
957
+ made.add(None);
958
+ made
959
+ }
960
+
961
+ /// A Filesystem answering each call by the path its dentry stands at,
962
+ /// as one written in Ruby does, so a removed directory it opened
963
+ /// reaches whatever stands at that path later and keeps no death of
964
+ /// its own.
965
+ struct ByPath {
966
+ root: KernPath,
967
+ }
968
+
969
+ /// The path `dentry` stands at beneath a `ByPath`'s root, as a path-based
970
+ /// Filesystem builds its own from `dentry_path_raw`.
971
+ fn at(dentry: &Dentry) -> String {
972
+ dentry.path_raw()[1..].to_owned()
973
+ }
974
+
975
+ /// A name it recorded nothing for is looked up again, as a Ruby Filesystem's
976
+ /// `revalidate` answers, so one it made is found where the make left it.
977
+ impl super::DentryOperations for ByPath {
978
+ fn revalidate(&self, _dir: &dyn InodeOperations, dentry: &Dentry) -> Result<bool, Errno> {
979
+ Ok(dentry.inode().is_some())
980
+ }
981
+ }
982
+
983
+ impl crate::vfs::FileSystemType for ByPath {
984
+ fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), Errno> {
985
+ sb.set_default_d_op(self.clone());
986
+ sb.d_make_root(Inode::new(&Kstat::new(FileType::Dir, 0), self));
987
+ Ok(())
988
+ }
989
+ }
990
+
991
+ impl InodeOperations for ByPath {
992
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
993
+ self.root.vfs_lstat(&at(dentry))
994
+ }
995
+
996
+ fn lookup(&self, dentry: &Dentry) -> Result<Lookup, Errno> {
997
+ match self.root.vfs_lstat(&at(dentry)) {
998
+ Ok(found) => Ok(Lookup::Found(Inode::new(
999
+ &found,
1000
+ Arc::new(Self {
1001
+ root: self.root.clone(),
1002
+ }),
1003
+ ))),
1004
+ Err(Errno::NotFound) => Ok(Lookup::Absent),
1005
+ Err(err) => Err(err),
1006
+ }
1007
+ }
1008
+
1009
+ fn open(&self, dentry: &Dentry, how: &OpenHow) -> Result<Box<dyn FileOperations>, Errno> {
1010
+ if dentry.file_type() == Ok(FileType::Dir) {
1011
+ return Ok(Box::new(ByPathDir(self.root.clone())));
1012
+ }
1013
+ self.root.open(&at(dentry), how)
1014
+ }
1015
+
1016
+ fn atomic_open(&self, dentry: &Dentry, how: &OpenHow) -> Result<Finish, Errno> {
1017
+ if dentry.in_lookup() {
1018
+ let found = self.lookup(dentry)?;
1019
+ if !how.create || !matches!(found, Lookup::Absent) {
1020
+ return Ok(Finish::Lookup(found));
1021
+ }
1022
+ }
1023
+ if !how.create {
1024
+ return Ok(Finish::NoOpen { created: false });
1025
+ }
1026
+ let file = self.root.create(&at(dentry), how)?;
1027
+ Ok(Finish::Open {
1028
+ file,
1029
+ created: true,
1030
+ })
1031
+ }
1032
+
1033
+ fn mkdir(&self, dentry: &Dentry) -> Result<(), Errno> {
1034
+ self.root.vfs_mkdir(&at(dentry))
1035
+ }
1036
+
1037
+ fn rmdir(&self, dentry: &Dentry) -> Result<(), Errno> {
1038
+ self.root.vfs_rmdir(&at(dentry))
1039
+ }
1040
+
1041
+ fn unlink(&self, dentry: &Dentry) -> Result<(), Errno> {
1042
+ self.root.vfs_unlink(&at(dentry))
1043
+ }
1044
+
1045
+ fn rename(
1046
+ &self,
1047
+ old: &Dentry,
1048
+ new_dir: &dyn InodeOperations,
1049
+ new: &Dentry,
1050
+ _flags: Option<crate::vfs::RenameFlag>,
1051
+ ) -> Result<(), Errno> {
1052
+ (new_dir as &dyn Any)
1053
+ .downcast_ref::<Self>()
1054
+ .ok_or(Errno::CrossesDevices)?;
1055
+ self.root.rename(&at(old), &self.root, &at(new))
1056
+ }
1057
+ }
1058
+
1059
+ /// A directory of a `ByPath`, open.
1060
+ struct ByPathDir(KernPath);
1061
+
1062
+ impl FileOperations for ByPathDir {
1063
+ fn iterate_shared(
1064
+ &mut self,
1065
+ dentry: &Dentry,
1066
+ ctx: &mut vfs::DirContext<'_>,
1067
+ ) -> Result<(), Errno> {
1068
+ let entries = match at(dentry).as_str() {
1069
+ "" => self.0.iterate_dir(),
1070
+ at => self.0.open_dir(at)?.iterate_dir(),
1071
+ }?;
1072
+ crate::filesystem::Rdir::default().iterate_shared(dentry, ctx, || Ok(entries))
1073
+ }
1074
+ }
1075
+
1076
+ fn by_path(tmpfs: &Arc<Tmpfs>) -> Arc<Filesystem> {
1077
+ Filesystem::new(ByPath {
1078
+ root: kern_path(tmpfs.clone()),
1079
+ })
1080
+ .expect("the instance must stand")
1081
+ }
1082
+
1083
+ fn root_of(filesystem: &Arc<Filesystem>) -> Path {
1084
+ let mount = Mount::new("/data", filesystem.clone(), Access::ReadWrite)
1085
+ .expect("/data is a guest path");
1086
+ Path::root(mount.mnt())
1087
+ }
1088
+
1089
+ fn open_dir(start: &Path, path: &str) -> Path {
1090
+ let how = OpenHow {
1091
+ read: true,
1092
+ directory: true,
1093
+ ..OpenHow::default()
1094
+ };
1095
+ match vfs::kern_path::filp_open(&Arc::default(), start, path, &how) {
1096
+ Ok(dir) => dir.path().clone(),
1097
+ Err(_) => panic!("{path} must open as a directory"),
1098
+ }
1099
+ }
1100
+
1101
+ // Linux's `path_init` reads `rename_lock` with `__read_seqcount_begin`,
1102
+ // which spins past a write under way, so a walk begun during a move is
1103
+ // never answered EAGAIN for that move.
1104
+ // @behavior RT-265
1105
+ #[test]
1106
+ fn a_walk_begun_during_a_move_begins_once_it_lands() {
1107
+ use crate::locking::seqlock::SeqLock;
1108
+ use crate::sched::testing::MAX_WAIT;
1109
+ use std::sync::mpsc;
1110
+ use std::thread;
1111
+
1112
+ let lock = Arc::new(SeqLock::new());
1113
+ let (entered, entering) = mpsc::channel();
1114
+ let (release, releasing) = mpsc::channel::<()>();
1115
+ let writer = {
1116
+ let lock = lock.clone();
1117
+ thread::spawn(move || {
1118
+ lock.write(|| {
1119
+ entered.send(()).ok();
1120
+ releasing.recv_timeout(MAX_WAIT).ok();
1121
+ })
1122
+ })
1123
+ };
1124
+ entering
1125
+ .recv_timeout(MAX_WAIT)
1126
+ .expect("the write must begin");
1127
+ let reader = {
1128
+ let lock = lock.clone();
1129
+ thread::spawn(move || lock.read_seqbegin())
1130
+ };
1131
+ thread::sleep(std::time::Duration::from_millis(50));
1132
+ let waited = !reader.is_finished();
1133
+ release.send(()).ok();
1134
+ crate::sched::testing::join("the write", writer);
1135
+ let begun = crate::sched::testing::join("the read", reader);
1136
+ assert_eq!(
1137
+ (waited, begun, lock.read_seqretry(begun)),
1138
+ (true, 2, false),
1139
+ "SeqLock::read_seqbegin during a write must wait for it to end and answer where the \
1140
+ writes stand after it, which no later read finds changed"
1141
+ );
1142
+ }
1143
+
1144
+ // `d_revalidate` compares what the dentry recorded first, so a later
1145
+ // lookup replacing it would hide the change it is there to see.
1146
+ #[test]
1147
+ fn a_dentry_keeps_what_a_lookup_first_found_there() {
1148
+ let ops: Arc<dyn InodeOperations> = Arc::new(Tmpfs::new());
1149
+ let (first, second) = (
1150
+ Kstat::new(FileType::Dir, 0).with_identity(1, 2),
1151
+ Kstat::new(FileType::Dir, 0).with_identity(1, 3),
1152
+ );
1153
+ let dentries = Dentries::new(None);
1154
+ let dentry = negative(&dentries, &make_dir_root(&dentries), "dir");
1155
+ dentry.add(Some(Inode::new(&first, ops.clone())));
1156
+ dentry.add(Some(Inode::new(&second, ops)));
1157
+ assert_eq!(
1158
+ dentry.inode().and_then(|inode| inode.identity()),
1159
+ Identity::of(&first),
1160
+ "Dentry::add after a negative lookup and then a positive one must keep the first \
1161
+ inode recorded"
1162
+ );
1163
+ }
1164
+
1165
+ // The Filesystem answers by path, so only the dentry the removal marked
1166
+ // keeps the make from landing in the directory made in its place.
1167
+ // @behavior RT-159
1168
+ #[test]
1169
+ fn a_directory_removed_through_the_vfs_makes_nothing_more_whatever_its_filesystem() {
1170
+ let tmpfs: Arc<Tmpfs> = Arc::new([("dir/keep", "x")].into_iter().collect());
1171
+ let root = root_of(&by_path(&tmpfs));
1172
+ let dir = open_dir(&root, "dir");
1173
+ vfs::filename_unlinkat(&Arc::default(), &root, "dir/keep").expect("the file must go");
1174
+ vfs::filename_rmdir(&Arc::default(), &root, "dir").expect("the directory must go");
1175
+ vfs::filename_mkdirat(&Arc::default(), &root, "dir")
1176
+ .expect("another directory must be made");
1177
+ vfs::filename_mkdirat(&Arc::default(), &root, "dir/other")
1178
+ .expect("an entry must be made in it");
1179
+ assert_eq!(
1180
+ (
1181
+ vfs::filename_mkdirat(&Arc::default(), &dir, "made"),
1182
+ File::dentry_open(
1183
+ dir.clone(),
1184
+ &OpenHow {
1185
+ read: true,
1186
+ ..OpenHow::default()
1187
+ },
1188
+ &Arc::default()
1189
+ )
1190
+ .expect("the directory must open")
1191
+ .iterate_dir(&mut vfs::DirContext::new(0, &mut |_| true)),
1192
+ kern_path(tmpfs.clone()).vfs_lstat("dir/made").err()
1193
+ ),
1194
+ (
1195
+ Err(Errno::NotFound),
1196
+ Err(Errno::NotFound),
1197
+ Some(Errno::NotFound)
1198
+ ),
1199
+ "vfs::filename_mkdirat and File::iterate_dir through a directory vfs::filename_rmdir removed, over \
1200
+ a Filesystem answering by path, must each answer NotFound, as Linux asks \
1201
+ IS_DEADDIR, and make nothing in the directory made in its place"
1202
+ );
1203
+ }
1204
+
1205
+ // @behavior RT-160
1206
+ #[test]
1207
+ fn a_directory_removed_beneath_one_mount_is_removed_beneath_another_of_its_instance() {
1208
+ let tmpfs: Arc<Tmpfs> = Arc::new([("dir/keep", "x")].into_iter().collect());
1209
+ let instance = by_path(&tmpfs);
1210
+ let (first, second) = (root_of(&instance), root_of(&instance));
1211
+ let dir = open_dir(&first, "dir");
1212
+ vfs::filename_unlinkat(&Arc::default(), &second, "dir/keep").expect("the file must go");
1213
+ vfs::filename_rmdir(&Arc::default(), &second, "dir").expect("the directory must go");
1214
+ vfs::filename_mkdirat(&Arc::default(), &second, "dir")
1215
+ .expect("another directory must be made");
1216
+ assert_eq!(
1217
+ vfs::filename_mkdirat(&Arc::default(), &dir, "made"),
1218
+ Err(Errno::NotFound),
1219
+ "vfs::filename_mkdirat through a directory opened beneath one Mount, once vfs::filename_rmdir \
1220
+ removed it beneath another Mount of the same Filesystem, must answer NotFound"
1221
+ );
1222
+ }
1223
+
1224
+ // Built directly, as a path cannot reach this deep. A depth a recursive
1225
+ // release cannot survive on this stack is what tells it from a loop.
1226
+ // @behavior RT-199
1227
+ #[test]
1228
+ fn a_dentry_goes_however_deep_it_stands() {
1229
+ let dentries = Dentries::new(None);
1230
+ let mut leaf = make_dir_root(&dentries);
1231
+ for _ in 0..200_000 {
1232
+ leaf = dentries
1233
+ .alloc_parallel(&leaf, "a")
1234
+ .expect("no other walk holds the name");
1235
+ }
1236
+ let released = std::thread::Builder::new()
1237
+ .stack_size(64 * 1024)
1238
+ .spawn(move || drop(leaf))
1239
+ .expect("the thread must start")
1240
+ .join();
1241
+ assert!(
1242
+ released.is_ok(),
1243
+ "a dentry 200000 directories deep, dropped on a 64 KiB stack, must go without \
1244
+ overflowing it"
1245
+ );
1246
+ }
1247
+
1248
+ // Only a name kept beneath the invalidated directory is let go of: a name
1249
+ // beside it stays for the next walk.
1250
+ #[test]
1251
+ fn a_directory_let_go_of_takes_the_names_kept_beneath_it() {
1252
+ let dentries = Dentries::new(None);
1253
+ let root = make_dir_root(&dentries);
1254
+ let ops: Arc<dyn InodeOperations> = Arc::new(Tmpfs::new());
1255
+ let dir = dentries
1256
+ .alloc_parallel(&root, "dir")
1257
+ .expect("no other walk holds the name");
1258
+ dir.add(Some(Inode::new(&Kstat::new(FileType::Dir, 0), ops)));
1259
+ let kept = |dentry: Arc<Dentry>| {
1260
+ dentries.retain(&dentry);
1261
+ Arc::downgrade(&dentry)
1262
+ };
1263
+ let beneath = kept(negative(
1264
+ &dentries,
1265
+ &negative(&dentries, &dir, "sub"),
1266
+ "leaf",
1267
+ ));
1268
+ let beside = kept(negative(&dentries, &root, "other"));
1269
+ // The rename lock is the process's, so another test's rename can
1270
+ // move it between the read and the invalidation, which then keeps
1271
+ // the name as a raced revalidation does; ask again until one ran
1272
+ // undisturbed.
1273
+ loop {
1274
+ let asked = super::RENAME_LOCK.read_seqbegin();
1275
+ dentries.invalidate(&dir, asked);
1276
+ if !super::RENAME_LOCK.read_seqretry(asked) {
1277
+ break;
1278
+ }
1279
+ }
1280
+ assert_eq!(
1281
+ (beneath.upgrade().is_some(), beside.upgrade().is_some()),
1282
+ (false, true),
1283
+ "Dentries::invalidate of a directory must let go of the names kept beneath it and \
1284
+ keep the others, as d_invalidate calls shrink_dcache_parent"
1285
+ );
1286
+ }
1287
+
1288
+ // A walk let go of the dentry while another still held it, so only
1289
+ // refusing the unhashed one keeps that walk's retain from keeping a dentry
1290
+ // no walk can find, whose Filesystem state may be stale.
1291
+ #[test]
1292
+ fn a_dentry_let_go_of_is_not_kept_for_the_next_walk() {
1293
+ let dentries = Dentries::new(None);
1294
+ let dentry = negative(&dentries, &make_dir_root(&dentries), "gone");
1295
+ dentries.unhash(&dentry);
1296
+ dentries.retain(&dentry);
1297
+ let held = Arc::downgrade(&dentry);
1298
+ drop(dentry);
1299
+ assert!(
1300
+ held.upgrade().is_none(),
1301
+ "Dentries::retain of a dentry Dentries::unhash let go of must not keep it, as \
1302
+ retain_dentry refuses an unhashed one"
1303
+ );
1304
+ }
1305
+
1306
+ #[test]
1307
+ fn the_root_stands_at_a_lone_slash() {
1308
+ let dentries = super::Dentries::new(None);
1309
+ assert_eq!(
1310
+ make_dir_root(&dentries).path_raw(),
1311
+ "/",
1312
+ "Dentry::path_raw of the root must answer a lone /, as dentry_path_raw answers"
1313
+ );
1314
+ }
1315
+
1316
+ #[test]
1317
+ fn an_exchange_swaps_two_dentries() {
1318
+ let dentries = super::Dentries::new(None);
1319
+ let root = make_dir_root(&dentries);
1320
+ let a = negative(&dentries, &root, "a");
1321
+ let b = negative(&dentries, &negative(&dentries, &root, "d"), "b");
1322
+ dentries.exchange(&a, &b);
1323
+ assert_eq!(
1324
+ (
1325
+ a.path_raw(),
1326
+ b.path_raw(),
1327
+ dentries
1328
+ .lookup(&root, "a")
1329
+ .is_some_and(|found| Arc::ptr_eq(&found, &b))
1330
+ ),
1331
+ ("/d/b".to_string(), "/a".to_string(), true),
1332
+ "Dentries::exchange must hand each dentry the other's name, and find each by its new \
1333
+ name"
1334
+ );
1335
+ }
1336
+
1337
+ /// Witnesses of a race, each run only by `rake crates:stress`: the race
1338
+ /// lands a few times in many tries, and only an optimized build makes
1339
+ /// that many in seconds.
1340
+ mod stress {
1341
+ use std::sync::atomic::{AtomicBool, Ordering};
1342
+ use std::sync::Arc;
1343
+ use std::thread;
1344
+
1345
+ use super::super::{Dentries, Dentry};
1346
+ use super::{make_dir_root, negative};
1347
+
1348
+ /// The dentry a rename onto `name` in `dir` replaces.
1349
+ fn target(dentries: &Dentries, dir: &Arc<Dentry>, name: &str) -> Arc<Dentry> {
1350
+ dentries
1351
+ .alloc_parallel(dir, name)
1352
+ .expect("no other walk holds the name")
1353
+ }
1354
+
1355
+ // `x` is named `z` only while `b` stands beneath `y`, so `z/b/leaf`
1356
+ // is a path `leaf` never stood at: only a read taking `b`'s parent
1357
+ // before the moves and `x`'s name after them answers it.
1358
+ // @behavior RT-172
1359
+ #[test]
1360
+ #[ignore = "a stress witness; run by rake crates:stress"]
1361
+ fn a_path_asked_while_directories_above_it_move_names_one_that_stood() {
1362
+ let dentries = Arc::new(Dentries::new(None));
1363
+ let root = make_dir_root(&dentries);
1364
+ let (x, y) = (
1365
+ negative(&dentries, &root, "x"),
1366
+ negative(&dentries, &root, "y"),
1367
+ );
1368
+ let b = negative(&dentries, &x, "b");
1369
+ let leaf = negative(&dentries, &b, "leaf");
1370
+ let stop = Arc::new(AtomicBool::new(false));
1371
+ let moving = {
1372
+ let (dentries, stop) = (dentries.clone(), stop.clone());
1373
+ thread::spawn(move || {
1374
+ while !stop.load(Ordering::SeqCst) {
1375
+ dentries.move_dentry(&b, &target(&dentries, &y, "b"));
1376
+ dentries.move_dentry(&x, &target(&dentries, &root, "z"));
1377
+ dentries.move_dentry(&x, &target(&dentries, &root, "x"));
1378
+ dentries.move_dentry(&b, &target(&dentries, &x, "b"));
1379
+ }
1380
+ })
1381
+ };
1382
+ let torn = (0..5_000_000)
1383
+ .filter(|_| leaf.path_raw().starts_with("/z/"))
1384
+ .count();
1385
+ stop.store(true, Ordering::SeqCst);
1386
+ moving.join().expect("the moves must not panic");
1387
+ assert_eq!(
1388
+ torn, 0,
1389
+ "Dentry::path_raw while Dentries::move_dentry moves the directories above it must \
1390
+ answer only a path the dentry stood at"
1391
+ );
1392
+ }
1393
+
1394
+ // `retain` holds the name's lock before the LRU's, so only deciding what
1395
+ // stands beneath the directory before taking the LRU's keeps the two
1396
+ // from each holding what the other waits on.
1397
+ // @behavior RT-331
1398
+ #[test]
1399
+ #[ignore = "a stress witness; run by rake crates:stress"]
1400
+ fn a_name_kept_while_the_names_beneath_its_directory_go_waits_on_neither() {
1401
+ let dentries = Arc::new(Dentries::new(None));
1402
+ let dir = negative(&dentries, &make_dir_root(&dentries), "dir");
1403
+ let leaf = negative(&dentries, &dir, "leaf");
1404
+ let stop = Arc::new(AtomicBool::new(false));
1405
+ let keeping = {
1406
+ let (dentries, stop, leaf) = (dentries.clone(), stop.clone(), leaf.clone());
1407
+ thread::spawn(move || {
1408
+ while !stop.load(Ordering::SeqCst) {
1409
+ dentries.retain(&leaf);
1410
+ }
1411
+ })
1412
+ };
1413
+ let shrinking = {
1414
+ let (dentries, stop) = (dentries.clone(), stop.clone());
1415
+ thread::spawn(move || {
1416
+ while !stop.load(Ordering::SeqCst) {
1417
+ dentries.shrink_dcache_parent(&dir);
1418
+ }
1419
+ })
1420
+ };
1421
+ thread::sleep(std::time::Duration::from_secs(2));
1422
+ stop.store(true, Ordering::SeqCst);
1423
+ crate::sched::testing::join(
1424
+ "Dentries::retain racing Dentries::shrink_dcache_parent",
1425
+ keeping,
1426
+ );
1427
+ crate::sched::testing::join(
1428
+ "Dentries::shrink_dcache_parent racing Dentries::retain",
1429
+ shrinking,
1430
+ );
1431
+ }
1432
+
1433
+ // Each move keeps the dentry in the table, so only a read of its parent
1434
+ // before the move and its name after it finds nothing at that key.
1435
+ // @behavior RT-228
1436
+ #[test]
1437
+ #[ignore = "a stress witness; run by rake crates:stress"]
1438
+ fn a_directory_moving_through_the_vfs_is_never_taken_for_unlinked() {
1439
+ let dentries = Arc::new(Dentries::new(None));
1440
+ let root = make_dir_root(&dentries);
1441
+ let (x, y) = (
1442
+ negative(&dentries, &root, "x"),
1443
+ negative(&dentries, &root, "y"),
1444
+ );
1445
+ let moved = negative(&dentries, &x, "a");
1446
+ let stop = Arc::new(AtomicBool::new(false));
1447
+ let moving = {
1448
+ let (dentries, stop, moved) = (dentries.clone(), stop.clone(), moved.clone());
1449
+ thread::spawn(move || {
1450
+ while !stop.load(Ordering::SeqCst) {
1451
+ dentries.move_dentry(&moved, &target(&dentries, &y, "b"));
1452
+ dentries.move_dentry(&moved, &target(&dentries, &x, "a"));
1453
+ }
1454
+ })
1455
+ };
1456
+ let unlinked = (0..5_000_000).filter(|_| dentries.unlinked(&moved)).count();
1457
+ stop.store(true, Ordering::SeqCst);
1458
+ moving.join().expect("the moves must not panic");
1459
+ assert_eq!(
1460
+ unlinked, 0,
1461
+ "Dentries::unlinked while Dentries::move_dentry moves the dentry must answer that \
1462
+ it still stands"
1463
+ );
1464
+ }
1465
+ }
1466
+ }