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,1997 @@
1
+ //! `Tmpfs`: a Filesystem held in memory, living as long as the Host
2
+ //! App's object does.
3
+
4
+ use std::any::Any;
5
+ use std::collections::BTreeMap;
6
+ use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
7
+ use std::sync::{Arc, Mutex, MutexGuard};
8
+ use std::time::SystemTime;
9
+
10
+ use super::{
11
+ DentryOperations, DirEntry, Errno, FileOperations, FileSystemType, FileType, Filesystem, Iattr,
12
+ InodeOperations, Kiocb, Kstat, Lookup, OpenHow, RenameFlag, SetTime,
13
+ };
14
+ use crate::vfs::{dir_emit_dots, generic_file_llseek, generic_read_dir, DirContext, Whence};
15
+ use crate::vfs::{get_anon_bdev, Dentry, Identity, Inode, NAME_MAX};
16
+ use whiteout::Whiteout;
17
+
18
+ mod seed;
19
+ mod tmpfile;
20
+ mod whiteout;
21
+ mod xattr;
22
+
23
+ use seed::{ancestors, name};
24
+
25
+ /// Files and directories held in tmpfs. Every Invocation it is handed to
26
+ /// shares it, so what one writes the next reads. What its files hold
27
+ /// together, and how many entries it holds, are bounded as a tmpfs mount
28
+ /// bounds its size and its inodes, so a guest cannot grow it past what
29
+ /// the Host App allowed. A directory opened beneath it is a Tmpfs too,
30
+ /// following that directory wherever it moves, as a tmpfs descriptor
31
+ /// follows its inode.
32
+ pub struct Tmpfs {
33
+ tree: Arc<Tree>,
34
+ dir: Arc<Dir>,
35
+ }
36
+
37
+ /// What every directory of one Tmpfs shares. No lock spans it: the VFS
38
+ /// holds each directory a call changes and serializes moves between
39
+ /// directories, as Linux's tmpfs relies on `i_rwsem` and
40
+ /// `s_vfs_rename_mutex`.
41
+ struct Tree {
42
+ space: Arc<Space>,
43
+ inodes_follow_limit: AtomicBool,
44
+ /// The device number this Tmpfs reports, its own as each tmpfs mount
45
+ /// has its own, so it shares an identity with no other Filesystem.
46
+ dev: u64,
47
+ /// The inode number the next directory takes, so each one made has an
48
+ /// identity no other directory of this Tmpfs had.
49
+ next_ino: AtomicU64,
50
+ }
51
+
52
+ #[derive(Clone)]
53
+ enum Node {
54
+ File(Arc<Mutex<Content>>),
55
+ Directory(Arc<Dir>),
56
+ /// An Overlay's whiteout, as tmpfs holds a character device 0:0.
57
+ Whiteout(Arc<Whiteout>),
58
+ }
59
+
60
+ impl Node {
61
+ /// Mark an entry no directory holds any more, which a handle may outlive, as
62
+ /// `shmem_unlink` and `shmem_rmdir` drop its last links.
63
+ fn drop_name(&self) {
64
+ match self {
65
+ Self::File(data) => lock(data).names = 0,
66
+ Self::Directory(dir) => dir.state().removed = true,
67
+ Self::Whiteout(_) => {}
68
+ }
69
+ }
70
+
71
+ /// A name of it came or went, as `simple_rename_timestamp` and
72
+ /// `shmem_unlink` move an inode's `st_ctime`.
73
+ fn touch_changed(&self) {
74
+ let now = SystemTime::now();
75
+ match self {
76
+ Self::File(data) => lock(data).times.ctime = now,
77
+ Self::Directory(dir) => dir.state().times.ctime = now,
78
+ Self::Whiteout(whiteout) => whiteout.times().ctime = now,
79
+ }
80
+ }
81
+
82
+ /// Refuse a directory holding anything, whiteouts among them, as
83
+ /// `simple_empty` answers before a removal or a replacement takes it.
84
+ fn ensure_empty(&self) -> Result<(), Errno> {
85
+ match self {
86
+ Self::Directory(dir) if !dir.state().entries.is_empty() => {
87
+ Err(Errno::DirectoryNotEmpty)
88
+ }
89
+ _ => Ok(()),
90
+ }
91
+ }
92
+
93
+ fn file_type(&self) -> FileType {
94
+ match self {
95
+ Self::File(_) => FileType::RegFile,
96
+ Self::Directory(_) => FileType::Dir,
97
+ Self::Whiteout(_) => FileType::Chrdev,
98
+ }
99
+ }
100
+
101
+ /// Its entry in a listing of a Tmpfs on `dev`, named as a stat of it is.
102
+ fn dir_entry(&self, name: &str, dev: u64) -> DirEntry {
103
+ let entry = DirEntry::new(name, self.file_type());
104
+ match self {
105
+ Self::File(content) => {
106
+ let content = lock(content);
107
+ entry.with_identity(content.dev, content.ino)
108
+ }
109
+ Self::Directory(dir) => entry.with_identity(dev, dir.ino),
110
+ Self::Whiteout(whiteout) => entry.with_identity(dev, whiteout.ino()),
111
+ }
112
+ }
113
+ }
114
+
115
+ /// A directory and its inode number. Each entry is held under its own
116
+ /// name in its directory, as a tmpfs holds one name to each entry, so the
117
+ /// names it holds stay bounded by its inodes however its directories move.
118
+ struct Dir {
119
+ ino: u64,
120
+ /// What it counts against for as long as anything holds it, as tmpfs frees
121
+ /// an inode when the last reference to it goes.
122
+ space: Arc<Space>,
123
+ state: Mutex<State>,
124
+ }
125
+
126
+ struct State {
127
+ entries: BTreeMap<String, Node>,
128
+ /// Each name by its stable position in a listing, as `simple_offset_ctx`
129
+ /// keeps one, so a listing going on reads the directory as it stands without
130
+ /// holding what it began with.
131
+ offsets: BTreeMap<u64, String>,
132
+ offset_of: BTreeMap<String, u64>,
133
+ next_offset: u64,
134
+ /// How many of `entries` are directories, as `inc_nlink` keeps a
135
+ /// directory's count, so no stat reads every entry.
136
+ subdirectories: u64,
137
+ /// Whether no directory holds it any more, so it counts no name.
138
+ removed: bool,
139
+ /// The directory's extended attributes, as tmpfs keeps the `trusted.*`
140
+ /// ones an Overlay marks a directory opaque with.
141
+ xattrs: BTreeMap<String, Vec<u8>>,
142
+ times: Times,
143
+ }
144
+
145
+ impl State {
146
+ /// Hold `node` under `name`, answering what stood there. The name takes the
147
+ /// next position in a listing, as `simple_offset_add` hands one out.
148
+ fn hold(&mut self, name: &str, node: Node) -> Option<Node> {
149
+ self.subdirectories += u64::from(matches!(node, Node::Directory(_)));
150
+ let replaced = self.entries.insert(name.to_string(), node);
151
+ self.subdirectories -= u64::from(matches!(replaced, Some(Node::Directory(_))));
152
+ self.forget_offset(name);
153
+ self.offsets.insert(self.next_offset, name.to_string());
154
+ self.offset_of.insert(name.to_string(), self.next_offset);
155
+ self.next_offset += 1;
156
+ replaced
157
+ }
158
+
159
+ /// Leave `name` out of a listing from now on, as `simple_offset_remove`.
160
+ fn forget_offset(&mut self, name: &str) {
161
+ if let Some(offset) = self.offset_of.remove(name) {
162
+ self.offsets.remove(&offset);
163
+ }
164
+ }
165
+
166
+ /// The first entry a listing at `pos` reaches, and the position it stands at.
167
+ fn entry_from(&self, pos: u64) -> Option<(u64, &str, &Node)> {
168
+ let (offset, name) = self.offsets.range(pos..).next()?;
169
+ Some((*offset, name, self.entries.get(name)?))
170
+ }
171
+
172
+ /// Hold `node` under `name`, a change to the directory's content.
173
+ fn insert(&mut self, name: &str, node: Node) {
174
+ node.touch_changed();
175
+ if let Some(replaced) = self.hold(name, node) {
176
+ replaced.drop_name();
177
+ replaced.touch_changed();
178
+ }
179
+ self.times.touch();
180
+ }
181
+
182
+ /// Hold `node`, which keeps a name elsewhere, in place of what stands at
183
+ /// `name`, which does too, a change to the directory's content.
184
+ fn exchange(&mut self, name: &str, node: Node) {
185
+ node.touch_changed();
186
+ self.hold(name, node);
187
+ self.times.touch();
188
+ }
189
+
190
+ /// Take the entry `name` away, to stand elsewhere, a change to the
191
+ /// directory's content.
192
+ fn take(&mut self, name: &str) {
193
+ self.entries.remove(name).inspect(|taken| {
194
+ self.subdirectories -= u64::from(matches!(taken, Node::Directory(_)));
195
+ });
196
+ self.forget_offset(name);
197
+ self.times.touch();
198
+ }
199
+
200
+ /// Take the entry `name` away for good, a change to the directory's content.
201
+ fn remove(&mut self, name: &str) {
202
+ if let Some(removed) = self.entries.get(name).cloned() {
203
+ removed.drop_name();
204
+ removed.touch_changed();
205
+ }
206
+ self.take(name);
207
+ }
208
+ }
209
+
210
+ /// An entry's three times, as a tmpfs mounted `noatime` keeps them: reading
211
+ /// touches nothing, a change to its content moves `st_mtime` and `st_ctime`
212
+ /// together, and a change to its names or attributes `st_ctime` alone.
213
+ #[derive(Clone, Copy)]
214
+ struct Times {
215
+ atime: SystemTime,
216
+ mtime: SystemTime,
217
+ ctime: SystemTime,
218
+ }
219
+
220
+ impl Times {
221
+ fn now() -> Self {
222
+ let now = SystemTime::now();
223
+ Self {
224
+ atime: now,
225
+ mtime: now,
226
+ ctime: now,
227
+ }
228
+ }
229
+
230
+ /// Its content changed.
231
+ fn touch(&mut self) {
232
+ let now = SystemTime::now();
233
+ self.mtime = now;
234
+ self.ctime = now;
235
+ }
236
+
237
+ /// Set the times `attr` names, if it names any, as `shmem_setattr` takes them
238
+ /// from `setattr_copy`, all at the one moment the change lands, which counts
239
+ /// as a change to the entry.
240
+ fn apply(&mut self, attr: &Iattr) {
241
+ if attr.atime.is_none() && attr.mtime.is_none() {
242
+ return;
243
+ }
244
+ if let Some(set) = attr.atime {
245
+ self.atime = attr.time_of(set);
246
+ }
247
+ if let Some(set) = attr.mtime {
248
+ self.mtime = attr.time_of(set);
249
+ }
250
+ self.ctime = attr.time_of(SetTime::Now);
251
+ }
252
+
253
+ fn report(self, stat: Kstat) -> Kstat {
254
+ stat.with_times(Some(self.atime), Some(self.mtime), Some(self.ctime))
255
+ }
256
+ }
257
+
258
+ impl Dir {
259
+ fn new(ino: u64, space: Arc<Space>) -> Arc<Self> {
260
+ Arc::new(Self {
261
+ ino,
262
+ space,
263
+ state: Mutex::new(State {
264
+ entries: BTreeMap::new(),
265
+ offsets: BTreeMap::new(),
266
+ offset_of: BTreeMap::new(),
267
+ next_offset: 2,
268
+ subdirectories: 0,
269
+ removed: false,
270
+ xattrs: BTreeMap::new(),
271
+ times: Times::now(),
272
+ }),
273
+ })
274
+ }
275
+
276
+ /// What the directory reports: two names and one more for each
277
+ /// directory it holds, as a tmpfs counts `.` and each `..` beneath it,
278
+ /// and a size of `BOGO_DIRENT_SIZE` for each of its entries and those
279
+ /// two, as a tmpfs sizes a directory. One removed counts no name.
280
+ fn getattr(&self, dev: u64) -> Kstat {
281
+ let state = self.state();
282
+ let size = (2 + state.entries.len() as u64) * BOGO_DIRENT_SIZE;
283
+ let nlink = match state.removed {
284
+ true => 0,
285
+ false => 2 + state.subdirectories,
286
+ };
287
+ state.times.report(
288
+ Kstat::new(FileType::Dir, size)
289
+ .with_identity(dev, self.ino)
290
+ .with_nlink(nlink),
291
+ )
292
+ }
293
+
294
+ fn state(&self) -> MutexGuard<'_, State> {
295
+ self.state
296
+ .lock()
297
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
298
+ }
299
+
300
+ /// What stands at `name` in this directory.
301
+ fn get(&self, name: &str) -> Result<Node, Errno> {
302
+ self.state()
303
+ .entries
304
+ .get(name)
305
+ .cloned()
306
+ .ok_or(Errno::NotFound)
307
+ }
308
+
309
+ /// Hand `nested` every directory this one holds, leaving it holding
310
+ /// nothing.
311
+ fn take_directories(&mut self, nested: &mut Vec<Arc<Dir>>) {
312
+ let state = self
313
+ .state
314
+ .get_mut()
315
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
316
+ for (_, node) in std::mem::take(&mut state.entries) {
317
+ if let Node::Directory(dir) = node {
318
+ nested.push(dir);
319
+ }
320
+ }
321
+ }
322
+ }
323
+
324
+ /// A guest can stack directories as deep as its inodes reach, so the last
325
+ /// reference to one lets go of everything beneath it in a loop, as Linux's
326
+ /// `dput` walks up in one, and no depth outruns the thread's stack.
327
+ impl Drop for Dir {
328
+ fn drop(&mut self) {
329
+ let mut nested = Vec::new();
330
+ self.take_directories(&mut nested);
331
+ while let Some(dir) = nested.pop() {
332
+ if let Some(mut dir) = Arc::into_inner(dir) {
333
+ dir.take_directories(&mut nested);
334
+ }
335
+ }
336
+ self.space.inodes.give(1);
337
+ }
338
+ }
339
+
340
+ /// What a Tmpfs holds: the bytes of its files, and its entries, each
341
+ /// file and directory and the root counting one as an inode does.
342
+ struct Space {
343
+ bytes: Counter,
344
+ inodes: Counter,
345
+ }
346
+
347
+ /// How much of one thing is used, counted against the limit the Host App
348
+ /// set, as shmem counts `used_blocks` against `max_blocks`.
349
+ struct Counter {
350
+ limit: AtomicUsize,
351
+ used: AtomicUsize,
352
+ }
353
+
354
+ impl Counter {
355
+ fn new(limit: Option<usize>) -> Self {
356
+ Self {
357
+ limit: AtomicUsize::new(limit.unwrap_or(usize::MAX)),
358
+ used: AtomicUsize::new(0),
359
+ }
360
+ }
361
+
362
+ fn set_limit(&self, limit: Option<usize>) {
363
+ self.limit
364
+ .store(limit.unwrap_or(usize::MAX), Ordering::Relaxed);
365
+ }
366
+
367
+ /// Count `amount` more, refusing when it would pass the limit.
368
+ fn take(&self, amount: usize) -> Result<(), Errno> {
369
+ let limit = self.limit.load(Ordering::Relaxed);
370
+ self.used
371
+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |used| {
372
+ used.checked_add(amount).filter(|&total| total <= limit)
373
+ })
374
+ .map(drop)
375
+ .map_err(|_| Errno::StorageFull)
376
+ }
377
+
378
+ /// Count `amount` more without refusing, for what the Host App seeds.
379
+ fn add(&self, amount: usize) {
380
+ self.used.fetch_add(amount, Ordering::Relaxed);
381
+ }
382
+
383
+ fn give(&self, amount: usize) {
384
+ self.used.fetch_sub(amount, Ordering::Relaxed);
385
+ }
386
+ }
387
+
388
+ /// One file's bytes, counted against its Tmpfs's space, with the file's
389
+ /// inode, for as long as they live, which outlasts the file's name while
390
+ /// a handle holds them.
391
+ struct Content {
392
+ bytes: Vec<u8>,
393
+ space: Arc<Space>,
394
+ times: Times,
395
+ dev: u64,
396
+ ino: u64,
397
+ /// One while a directory holds it, as a Tmpfs holds no hard links.
398
+ names: u64,
399
+ }
400
+
401
+ impl Content {
402
+ /// A file the Host App seeds, counted but never refused.
403
+ fn seed(bytes: Vec<u8>, tree: &Tree) -> Arc<Mutex<Self>> {
404
+ tree.space.bytes.add(bytes.len());
405
+ tree.space.inodes.add(1);
406
+ Self::new(bytes, tree)
407
+ }
408
+
409
+ /// An empty file the guest creates, refused once no inode is left.
410
+ fn create(tree: &Tree) -> Result<Arc<Mutex<Self>>, Errno> {
411
+ tree.space.inodes.take(1)?;
412
+ Ok(Self::new(Vec::new(), tree))
413
+ }
414
+
415
+ fn new(bytes: Vec<u8>, tree: &Tree) -> Arc<Mutex<Self>> {
416
+ Arc::new(Mutex::new(Self {
417
+ bytes,
418
+ space: tree.space.clone(),
419
+ times: Times::now(),
420
+ dev: tree.dev,
421
+ ino: tree.next_ino.fetch_add(1, Ordering::Relaxed),
422
+ names: 1,
423
+ }))
424
+ }
425
+
426
+ fn getattr(&self) -> Kstat {
427
+ self.times.report(
428
+ Kstat::new(FileType::RegFile, self.bytes.len() as u64)
429
+ .with_identity(self.dev, self.ino)
430
+ .with_nlink(self.names),
431
+ )
432
+ }
433
+
434
+ /// Resize to `len`, refusing a growth past the space left or past what
435
+ /// can be allocated, rather than aborting the host process.
436
+ fn resize(&mut self, len: usize) -> Result<(), Errno> {
437
+ let growth = len.saturating_sub(self.bytes.len());
438
+ if growth > 0 {
439
+ self.space.bytes.take(growth)?;
440
+ if self.bytes.try_reserve_exact(growth).is_err() {
441
+ self.space.bytes.give(growth);
442
+ return Err(Errno::StorageFull);
443
+ }
444
+ }
445
+ self.space.bytes.give(self.bytes.len().saturating_sub(len));
446
+ self.bytes.resize(len, 0);
447
+ self.bytes.shrink_to(len);
448
+ Ok(())
449
+ }
450
+ }
451
+
452
+ impl Drop for Content {
453
+ fn drop(&mut self) {
454
+ self.space.bytes.give(self.bytes.len());
455
+ self.space.inodes.give(1);
456
+ }
457
+ }
458
+
459
+ /// The inodes a limit of `bytes` allows unless given its own: one for
460
+ /// each 4 KiB page the bytes span, as a tmpfs counts one page to each
461
+ /// file, and one for the root.
462
+ fn inodes_for(bytes: Option<usize>) -> Option<usize> {
463
+ bytes.map(|bytes| bytes.div_ceil(PAGE).saturating_add(1))
464
+ }
465
+
466
+ const PAGE: usize = 4096;
467
+
468
+ /// The size a tmpfs counts for each name a directory holds.
469
+ const BOGO_DIRENT_SIZE: u64 = 20;
470
+
471
+ impl Tmpfs {
472
+ /// The most bytes a Tmpfs's files hold unless given a limit of their
473
+ /// own: the size Docker gives a `--tmpfs` mount.
474
+ pub const DEFAULT_SIZE: usize = 64 * 1024 * 1024;
475
+
476
+ pub fn new() -> Self {
477
+ let space = Space {
478
+ bytes: Counter::new(Some(Self::DEFAULT_SIZE)),
479
+ inodes: Counter::new(inodes_for(Some(Self::DEFAULT_SIZE))),
480
+ };
481
+ space.inodes.add(1);
482
+ let space = Arc::new(space);
483
+ Self {
484
+ tree: Arc::new(Tree {
485
+ space: space.clone(),
486
+ inodes_follow_limit: AtomicBool::new(true),
487
+ dev: get_anon_bdev(),
488
+ next_ino: AtomicU64::new(2),
489
+ }),
490
+ dir: Dir::new(1, space),
491
+ }
492
+ }
493
+
494
+ /// A directory with an inode number no directory of this Tmpfs had.
495
+ fn new_directory(&self) -> Arc<Dir> {
496
+ Dir::new(
497
+ self.tree.next_ino.fetch_add(1, Ordering::Relaxed),
498
+ self.tree.space.clone(),
499
+ )
500
+ }
501
+
502
+ /// This Tmpfs with its files holding at most `size` bytes together,
503
+ /// or without bound for `None`, as a tmpfs mount's `size` does. Unless
504
+ /// given `nr_inodes` of its own, its entries follow the size: one for
505
+ /// each 4 KiB it spans, and the root. What it was seeded with counts,
506
+ /// but is never refused.
507
+ pub fn with_size(self, size: Option<usize>) -> Self {
508
+ self.tree.space.bytes.set_limit(size);
509
+ if self.tree.inodes_follow_limit.load(Ordering::Relaxed) {
510
+ self.tree.space.inodes.set_limit(inodes_for(size));
511
+ }
512
+ self
513
+ }
514
+
515
+ /// This Tmpfs holding at most `nr_inodes` entries, the root among them,
516
+ /// or without bound for `None`, as a tmpfs mount's `nr_inodes` does.
517
+ pub fn with_nr_inodes(self, nr_inodes: Option<usize>) -> Self {
518
+ self.tree.space.inodes.set_limit(nr_inodes);
519
+ self.tree
520
+ .inodes_follow_limit
521
+ .store(false, Ordering::Relaxed);
522
+ self
523
+ }
524
+
525
+ /// The directory `dir` of this Tmpfs, as a Tmpfs of its own.
526
+ fn beneath(&self, dir: Arc<Dir>) -> Self {
527
+ Self {
528
+ tree: self.tree.clone(),
529
+ dir,
530
+ }
531
+ }
532
+ }
533
+
534
+ impl Default for Tmpfs {
535
+ fn default() -> Self {
536
+ Self::new()
537
+ }
538
+ }
539
+
540
+ /// Why a list of files cannot seed a Tmpfs as given.
541
+ #[derive(Clone, Debug, PartialEq, Eq)]
542
+ #[non_exhaustive]
543
+ pub enum SeedError {
544
+ /// A path naming the root, where no file can stand.
545
+ Root,
546
+ /// A file given twice.
547
+ Twice(String),
548
+ /// A path given as a file where another path needs a directory, or
549
+ /// the reverse.
550
+ FileAndDirectory(String),
551
+ /// A path naming `..`, which no runtime hands a Filesystem, so the
552
+ /// file would never be reached.
553
+ DotDot(String),
554
+ }
555
+
556
+ impl std::fmt::Display for SeedError {
557
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
558
+ match self {
559
+ Self::Root => write!(f, "a Tmpfs seeds no file at its root"),
560
+ Self::Twice(path) => write!(f, "a Tmpfs seeds {path} twice"),
561
+ Self::FileAndDirectory(path) => {
562
+ write!(f, "a Tmpfs seeds {path} as both a file and a directory")
563
+ }
564
+ Self::DotDot(path) => write!(f, "a Tmpfs seeds no path through `..`, got {path}"),
565
+ }
566
+ }
567
+ }
568
+
569
+ impl std::error::Error for SeedError {}
570
+
571
+ impl Tmpfs {
572
+ /// A Tmpfs seeded with files, each `(path, contents)`, its directories
573
+ /// created along the way, or why no Tmpfs holds the list as given.
574
+ pub fn try_from_iter<P, C, I>(files: I) -> Result<Self, SeedError>
575
+ where
576
+ P: AsRef<str>,
577
+ C: Into<Vec<u8>>,
578
+ I: IntoIterator<Item = (P, C)>,
579
+ {
580
+ let tmpfs = Self::new();
581
+ for (path, contents) in files {
582
+ let path = seed::normalize(path.as_ref())?;
583
+ let mut dir = tmpfs.dir.clone();
584
+ for above in ancestors(&path) {
585
+ let standing = dir.state().entries.get(name(above)).cloned();
586
+ let next = standing.unwrap_or_else(|| {
587
+ tmpfs.tree.space.inodes.add(1);
588
+ let made = Node::Directory(tmpfs.new_directory());
589
+ dir.state().hold(name(above), made.clone());
590
+ made
591
+ });
592
+ dir = match next {
593
+ Node::Directory(inner) => inner,
594
+ Node::File(_) | Node::Whiteout(_) => {
595
+ return Err(SeedError::FileAndDirectory(above.to_string()))
596
+ }
597
+ };
598
+ }
599
+ let mut state = dir.state();
600
+ match state.entries.get(name(&path)) {
601
+ Some(Node::Directory(_)) => return Err(SeedError::FileAndDirectory(path)),
602
+ Some(Node::File(_) | Node::Whiteout(_)) => return Err(SeedError::Twice(path)),
603
+ None => {}
604
+ }
605
+ state.hold(
606
+ name(&path),
607
+ Node::File(Content::seed(contents.into(), &tmpfs.tree)),
608
+ );
609
+ }
610
+ Ok(tmpfs)
611
+ }
612
+ }
613
+
614
+ /// A Tmpfs seeded with files, each `(path, contents)`, its directories
615
+ /// created along the way.
616
+ ///
617
+ /// # Panics
618
+ ///
619
+ /// When `Tmpfs::try_from_iter` refuses the list: a list written into the
620
+ /// Host App's own code that no Tmpfs holds is a defect in that code.
621
+ impl<P: AsRef<str>, C: Into<Vec<u8>>> FromIterator<(P, C)> for Tmpfs {
622
+ fn from_iter<I: IntoIterator<Item = (P, C)>>(files: I) -> Self {
623
+ Self::try_from_iter(files).unwrap_or_else(|error| panic!("{error}"))
624
+ }
625
+ }
626
+
627
+ impl Tmpfs {
628
+ /// What `node`, an entry of this Tmpfs, reports of itself. A whiteout is
629
+ /// a character device 0:0 with an inode of its own, as tmpfs makes one.
630
+ fn node_getattr(&self, node: &Node) -> Kstat {
631
+ match node {
632
+ Node::File(data) => lock(data).getattr(),
633
+ Node::Directory(dir) => dir.getattr(self.tree.dev),
634
+ Node::Whiteout(whiteout) => whiteout.getattr(),
635
+ }
636
+ }
637
+
638
+ /// The inode answering for `node`, an entry of this Tmpfs.
639
+ fn inode_of(&self, node: Node) -> Arc<Inode> {
640
+ let stat = self.node_getattr(&node);
641
+ let ops: Arc<dyn InodeOperations> = match node {
642
+ Node::Directory(dir) => Arc::new(self.beneath(dir)),
643
+ Node::File(data) => Arc::new(TmpfsRegular { data }),
644
+ Node::Whiteout(whiteout) => Arc::new(TmpfsWhiteout(whiteout)),
645
+ };
646
+ Inode::new(&stat, ops)
647
+ }
648
+
649
+ /// Put `node` at the name `dentry` carries and record it there, as
650
+ /// `shmem_mknod` calls `d_make_persistent`.
651
+ fn make(&self, dentry: &Dentry, node: Node) -> Result<(), Errno> {
652
+ self.dir.state().insert(&dentry.name(), node.clone());
653
+ dentry.add(Some(self.inode_of(node)));
654
+ Ok(())
655
+ }
656
+ }
657
+
658
+ impl FileSystemType for Tmpfs {
659
+ fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), Errno> {
660
+ sb.set_default_d_op(Arc::new(TmpfsDentry));
661
+ sb.set_dontcache();
662
+ sb.d_make_root(Inode::new(&self.dir.getattr(self.tree.dev), self));
663
+ Ok(())
664
+ }
665
+ }
666
+
667
+ /// A directory of a Tmpfs answers for the names in it. A file answers
668
+ /// through `TmpfsRegular`, and a whiteout, a character device 0:0 with no
669
+ /// driver to open it, through `TmpfsWhiteout`.
670
+ impl InodeOperations for Tmpfs {
671
+ fn getattr(&self, _dentry: &Dentry) -> Result<Kstat, Errno> {
672
+ Ok(self.dir.getattr(self.tree.dev))
673
+ }
674
+
675
+ fn setattr(&self, _dentry: &Dentry, attr: &Iattr) -> Result<(), Errno> {
676
+ self.dir.state().times.apply(attr);
677
+ Ok(())
678
+ }
679
+
680
+ /// A Tmpfs matches names byte for byte and holds no links, and refuses a
681
+ /// name past `NAME_MAX`, as `simple_lookup` does.
682
+ fn lookup(&self, dentry: &Dentry) -> Result<Lookup, Errno> {
683
+ let name = dentry.name();
684
+ if name.len() > NAME_MAX {
685
+ return Err(Errno::InvalidFilename);
686
+ }
687
+ let node = match self.dir.get(&name) {
688
+ Ok(node) => node,
689
+ Err(Errno::NotFound) => return Ok(Lookup::Absent),
690
+ Err(err) => return Err(err),
691
+ };
692
+ Ok(Lookup::Found(self.inode_of(node)))
693
+ }
694
+
695
+ fn create(&self, dentry: &Dentry) -> Result<(), Errno> {
696
+ let data = Content::create(&self.tree)?;
697
+ self.make(dentry, Node::File(data))
698
+ }
699
+
700
+ fn open(&self, _dentry: &Dentry, _how: &OpenHow) -> Result<Box<dyn FileOperations>, Errno> {
701
+ Ok(Box::new(TmpfsDir {
702
+ dir: self.dir.clone(),
703
+ dev: self.tree.dev,
704
+ }))
705
+ }
706
+
707
+ fn mkdir(&self, dentry: &Dentry) -> Result<(), Errno> {
708
+ self.tree.space.inodes.take(1)?;
709
+ self.make(dentry, Node::Directory(self.new_directory()))
710
+ }
711
+
712
+ /// The VFS found a directory at the name, as `shmem_rmdir` leaves it to,
713
+ /// so only whether it holds anything is left to answer.
714
+ fn rmdir(&self, dentry: &Dentry) -> Result<(), Errno> {
715
+ let name = dentry.name();
716
+ let mut state = self.dir.state();
717
+ if let Some(removed) = state.entries.get(&name) {
718
+ removed.ensure_empty()?;
719
+ }
720
+ state.remove(&name);
721
+ Ok(())
722
+ }
723
+
724
+ /// The VFS found no directory at the name, as `shmem_unlink` leaves it to.
725
+ fn unlink(&self, dentry: &Dentry) -> Result<(), Errno> {
726
+ self.dir.state().remove(&dentry.name());
727
+ Ok(())
728
+ }
729
+
730
+ fn rename(
731
+ &self,
732
+ old: &Dentry,
733
+ new_dir: &dyn InodeOperations,
734
+ new: &Dentry,
735
+ flags: Option<RenameFlag>,
736
+ ) -> Result<(), Errno> {
737
+ let target = (new_dir as &dyn Any)
738
+ .downcast_ref::<Self>()
739
+ .ok_or(Errno::CrossesDevices)?;
740
+ self.rename_at(&old.name(), target, &new.name(), flags)
741
+ }
742
+ }
743
+
744
+ /// A directory of a Tmpfs, open.
745
+ struct TmpfsDir {
746
+ dir: Arc<Dir>,
747
+ dev: u64,
748
+ }
749
+
750
+ impl FileOperations for TmpfsDir {
751
+ fn llseek(
752
+ &mut self,
753
+ dentry: &Dentry,
754
+ pos: u64,
755
+ offset: i64,
756
+ whence: Whence,
757
+ ) -> Result<u64, Errno> {
758
+ generic_file_llseek(dentry, pos, offset, whence)
759
+ }
760
+
761
+ fn read_iter(&mut self, _iocb: &mut Kiocb, _buf: &mut [u8]) -> Result<usize, Errno> {
762
+ generic_read_dir()
763
+ }
764
+
765
+ /// Reads on from each name's stable position, as `offset_readdir` does, so
766
+ /// nothing is held between two calls.
767
+ fn iterate_shared(&mut self, dentry: &Dentry, ctx: &mut DirContext<'_>) -> Result<(), Errno> {
768
+ if !dir_emit_dots(dentry, ctx) {
769
+ return Ok(());
770
+ }
771
+ loop {
772
+ let found = {
773
+ let state = self.dir.state();
774
+ state
775
+ .entry_from(ctx.pos())
776
+ .map(|(offset, name, node)| (offset, node.dir_entry(name, self.dev)))
777
+ };
778
+ let Some((offset, entry)) = found else {
779
+ return Ok(());
780
+ };
781
+ ctx.set_pos(offset);
782
+ if !ctx.dir_emit(&entry) {
783
+ return Ok(());
784
+ }
785
+ ctx.set_pos(offset + 1);
786
+ }
787
+ }
788
+
789
+ /// A Tmpfs holds nothing to make durable, as tmpfs names `noop_fsync` for
790
+ /// its directories too.
791
+ fn fsync(&mut self, _datasync: bool) -> Result<(), Errno> {
792
+ Ok(())
793
+ }
794
+ }
795
+
796
+ /// A Tmpfs handed to more than one Filesystem instance changes through each,
797
+ /// behind the others' dentries, so a dentry recording an identity is valid
798
+ /// only while that entry stands at its name here, as NFS compares the handle
799
+ /// a fresh lookup finds. One recording none has nothing to compare. Moves
800
+ /// through two instances take no common lock, so together they are undefined.
801
+ pub(super) struct TmpfsDentry;
802
+
803
+ impl DentryOperations for TmpfsDentry {
804
+ fn revalidate(&self, dir: &dyn InodeOperations, dentry: &Dentry) -> Result<bool, Errno> {
805
+ let Some(dir) = (dir as &dyn Any).downcast_ref::<Tmpfs>() else {
806
+ return Ok(true);
807
+ };
808
+ let found = dir.dir.get(&dentry.name()).ok();
809
+ let Some(inode) = dentry.inode() else {
810
+ return Ok(found.is_none());
811
+ };
812
+ let Some(identity) = inode.identity() else {
813
+ return Ok(true);
814
+ };
815
+ Ok(found.is_some_and(|node| Identity::of(&dir.node_getattr(&node)) == Some(identity)))
816
+ }
817
+ }
818
+
819
+ /// A file of a Tmpfs.
820
+ struct TmpfsRegular {
821
+ data: Arc<Mutex<Content>>,
822
+ }
823
+
824
+ impl InodeOperations for TmpfsRegular {
825
+ fn getattr(&self, _dentry: &Dentry) -> Result<Kstat, Errno> {
826
+ Ok(lock(&self.data).getattr())
827
+ }
828
+
829
+ fn setattr(&self, _dentry: &Dentry, attr: &Iattr) -> Result<(), Errno> {
830
+ let mut data = lock(&self.data);
831
+ if let Some(len) = attr.size {
832
+ let len = usize::try_from(len).map_err(|_| Errno::InvalidInput)?;
833
+ data.resize(len)?;
834
+ }
835
+ data.times.apply(attr);
836
+ Ok(())
837
+ }
838
+
839
+ fn open(&self, _dentry: &Dentry, _how: &OpenHow) -> Result<Box<dyn FileOperations>, Errno> {
840
+ Ok(Box::new(TmpfsFile {
841
+ data: self.data.clone(),
842
+ }))
843
+ }
844
+ }
845
+
846
+ /// A whiteout a Tmpfs holds for an Overlay above it.
847
+ struct TmpfsWhiteout(Arc<Whiteout>);
848
+
849
+ impl InodeOperations for TmpfsWhiteout {
850
+ fn getattr(&self, _dentry: &Dentry) -> Result<Kstat, Errno> {
851
+ Ok(self.0.getattr())
852
+ }
853
+
854
+ /// Its times, as `shmem_setattr` sets a device's; it holds no size.
855
+ fn setattr(&self, _dentry: &Dentry, attr: &Iattr) -> Result<(), Errno> {
856
+ self.0.times().apply(attr);
857
+ Ok(())
858
+ }
859
+ }
860
+
861
+ fn lock(data: &Mutex<Content>) -> MutexGuard<'_, Content> {
862
+ data.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
863
+ }
864
+
865
+ fn write(data: &mut Content, buf: &[u8], start: usize) -> Result<usize, Errno> {
866
+ if buf.is_empty() {
867
+ return Ok(0);
868
+ }
869
+ let end = start.checked_add(buf.len()).ok_or(Errno::InvalidInput)?;
870
+ if data.bytes.len() < end {
871
+ data.resize(end)?;
872
+ }
873
+ data.bytes[start..end].copy_from_slice(buf);
874
+ data.times.touch();
875
+ Ok(buf.len())
876
+ }
877
+
878
+ /// An open file of a Tmpfs, sharing its bytes with every other handle on
879
+ /// the same path.
880
+ pub(crate) struct TmpfsFile {
881
+ data: Arc<Mutex<Content>>,
882
+ }
883
+
884
+ impl FileOperations for TmpfsFile {
885
+ fn llseek(
886
+ &mut self,
887
+ dentry: &Dentry,
888
+ pos: u64,
889
+ offset: i64,
890
+ whence: Whence,
891
+ ) -> Result<u64, Errno> {
892
+ generic_file_llseek(dentry, pos, offset, whence)
893
+ }
894
+
895
+ fn read_iter(&mut self, iocb: &mut Kiocb, buf: &mut [u8]) -> Result<usize, Errno> {
896
+ let data = &lock(&self.data).bytes;
897
+ let start = usize::try_from(iocb.pos)
898
+ .unwrap_or(usize::MAX)
899
+ .min(data.len());
900
+ let read = buf.len().min(data.len() - start);
901
+ buf[..read].copy_from_slice(&data[start..start + read]);
902
+ iocb.pos += read as u64;
903
+ Ok(read)
904
+ }
905
+
906
+ /// The end is read and written under one lock, so another handle's
907
+ /// append lands before or after this one, never over it.
908
+ fn write_iter(&mut self, iocb: &mut Kiocb, buf: &[u8]) -> Result<usize, Errno> {
909
+ let mut data = lock(&self.data);
910
+ let start = match iocb.append {
911
+ true => data.bytes.len(),
912
+ false => usize::try_from(iocb.pos).map_err(|_| Errno::InvalidInput)?,
913
+ };
914
+ let written = write(&mut data, buf, start)?;
915
+ iocb.pos = (start + written) as u64;
916
+ drop(data);
917
+ crate::vfs::generic_write_sync(self, iocb, written)
918
+ }
919
+
920
+ /// Nothing outlives the Tmpfs, so there is nothing to flush, as shmem's
921
+ /// `noop_fsync`.
922
+ fn fsync(&mut self, _datasync: bool) -> Result<(), Errno> {
923
+ Ok(())
924
+ }
925
+
926
+ /// Grow the file to where the room ends, as `shmem_fallocate` moves `i_size`
927
+ /// past it. A Tmpfs holds every byte up to its end, so the room is taken from
928
+ /// its size or refused as out of space.
929
+ fn fallocate(&mut self, offset: u64, len: u64) -> Result<(), Errno> {
930
+ let end = usize::try_from(offset + len).map_err(|_| Errno::StorageFull)?;
931
+ let mut data = lock(&self.data);
932
+ if data.bytes.len() < end {
933
+ data.resize(end)?;
934
+ }
935
+ data.times.touch();
936
+ Ok(())
937
+ }
938
+ }
939
+
940
+ #[cfg(test)]
941
+ mod tests {
942
+ use super::*;
943
+ use crate::vfs::kern_path::{kern_path, KernPath};
944
+
945
+ #[derive(Default)]
946
+ struct CountsLookups(std::sync::atomic::AtomicUsize);
947
+
948
+ impl crate::filesystem::wrap::Hook for CountsLookups {
949
+ fn lookup(&self, inner: &dyn InodeOperations, dentry: &Dentry) -> Result<Lookup, Errno> {
950
+ self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
951
+ inner.lookup(dentry)
952
+ }
953
+ }
954
+
955
+ // @behavior FS-195
956
+ #[test]
957
+ fn a_listing_goes_on_from_a_position_each_name_keeps() {
958
+ use crate::vfs::{DirContext, File, Path};
959
+ let tmpfs: Tmpfs = [("a", ""), ("b", ""), ("c", "")].into_iter().collect();
960
+ let mount = crate::mount::Mount::new(
961
+ "/data",
962
+ Filesystem::new(tmpfs).expect("the instance must stand"),
963
+ crate::mount::Access::ReadWrite,
964
+ )
965
+ .expect("/data is a guest path");
966
+ let cred = Arc::default();
967
+ let mut dir = File::root(mount.mnt(), &cred).expect("the root opens");
968
+ let list = |dir: &mut File, pos, room: usize| {
969
+ let mut seen = Vec::new();
970
+ let mut actor = |emit: &crate::vfs::DirEmit<'_>| {
971
+ let took = seen.len() < room;
972
+ if took {
973
+ seen.push(emit.name.to_string());
974
+ }
975
+ took
976
+ };
977
+ let pos: u64 = pos;
978
+ dir.llseek(pos as i64, crate::vfs::Whence::Set)
979
+ .expect("the directory seeks");
980
+ dir.iterate_dir(&mut DirContext::new(0, &mut actor))
981
+ .expect("the directory lists");
982
+ (seen, dir.pos())
983
+ };
984
+ let first = list(&mut dir, 2, 1);
985
+ let root = Path::root(mount.mnt());
986
+ crate::vfs::filename_unlinkat(&cred, &root, "a").expect("the name goes");
987
+ crate::vfs::filename_unlinkat(&cred, &root, "b").expect("the name goes");
988
+ let how = crate::vfs::OpenHow {
989
+ write: true,
990
+ create: true,
991
+ ..crate::vfs::OpenHow::default()
992
+ };
993
+ crate::vfs::kern_path::filp_open(&cred, &root, "d", &how).expect("the name is made");
994
+ let (first, next) = first;
995
+ assert_eq!(
996
+ (first, list(&mut dir, next, usize::MAX).0),
997
+ (
998
+ vec!["a".to_string()],
999
+ vec!["c".to_string(), "d".to_string()]
1000
+ ),
1001
+ "File::iterate_dir going on over a Tmpfs must repeat nothing, pass over what was \
1002
+ removed, and hold what was made since, as offset_readdir reads on from each name's \
1003
+ stable offset"
1004
+ );
1005
+ }
1006
+
1007
+ // @behavior FS-192
1008
+ #[test]
1009
+ fn a_tmpfs_keeps_no_name_nothing_holds() {
1010
+ let counts = Arc::new(CountsLookups::default());
1011
+ let tmpfs: Tmpfs = [("file", "f")].into_iter().collect();
1012
+ let wrapped = crate::filesystem::wrap::Wrap::new(Arc::new(tmpfs), counts.clone());
1013
+ let mount = crate::mount::Mount::new(
1014
+ "/data",
1015
+ Filesystem::new(wrapped).expect("the instance must stand"),
1016
+ crate::mount::Access::ReadWrite,
1017
+ )
1018
+ .expect("/data is a guest path");
1019
+ let root = crate::vfs::Path::root(mount.mnt());
1020
+ for _ in 0..2 {
1021
+ crate::vfs::vfs_fstatat(&Arc::default(), &root, "file", false)
1022
+ .expect("the file stands");
1023
+ }
1024
+ assert_eq!(
1025
+ counts.0.load(std::sync::atomic::Ordering::SeqCst),
1026
+ 2,
1027
+ "vfs::vfs_fstatat twice of a Tmpfs's file must ask its lookup each time, as \
1028
+ shmem sets DCACHE_DONTCACHE"
1029
+ );
1030
+ }
1031
+
1032
+ // Each file leaves one name and takes another, so only keeping the count
1033
+ // through the swap reports both as still named.
1034
+ // @behavior FS-168
1035
+ #[test]
1036
+ fn an_exchange_leaves_both_files_named() {
1037
+ let filesystem = crate::filesystem::Filesystem::new(
1038
+ [("a", "first"), ("b", "second")]
1039
+ .into_iter()
1040
+ .collect::<Tmpfs>(),
1041
+ )
1042
+ .expect("the instance must stand");
1043
+ let dentries = filesystem.dentries();
1044
+ let root = filesystem.root().expect(crate::vfs::MADE_ROOT).clone();
1045
+ let at = |name| {
1046
+ dentries
1047
+ .alloc_parallel(&root, name)
1048
+ .expect("no other walk holds the name")
1049
+ };
1050
+ let (first, second) = (at("a"), at("b"));
1051
+ let dir = root.inode().expect("the root stands").ops().clone();
1052
+ dir.rename(&first, dir.as_ref(), &second, Some(RenameFlag::Exchange))
1053
+ .expect("the two must swap");
1054
+ let nlink = |name| {
1055
+ let dentry = at(name);
1056
+ dentry
1057
+ .lookup_inode(&filesystem, &root)
1058
+ .expect("the name must be found");
1059
+ dentry.getattr().map(|metadata| metadata.nlink)
1060
+ };
1061
+ assert_eq!(
1062
+ (nlink("a"), nlink("b")),
1063
+ (Ok(1), Ok(1)),
1064
+ "InodeOperations::rename of a Tmpfs asked to exchange two files must leave each with \
1065
+ one name"
1066
+ );
1067
+ }
1068
+
1069
+ // Linux's VFS sets no limit on one name, so this is the Tmpfs's own.
1070
+ // @behavior FS-154
1071
+ #[test]
1072
+ fn a_name_past_its_limit_is_too_long_for_a_tmpfs() {
1073
+ let fs = kern_path(Arc::new(Tmpfs::new()));
1074
+ let how = OpenHow {
1075
+ write: true,
1076
+ ..OpenHow::default()
1077
+ };
1078
+ assert!(
1079
+ fs.create(&"x".repeat(NAME_MAX), &how).is_ok()
1080
+ && matches!(
1081
+ fs.vfs_lstat(&"x".repeat(NAME_MAX + 1)),
1082
+ Err(Errno::InvalidFilename)
1083
+ ),
1084
+ "a name of NAME_MAX bytes must land in a Tmpfs, and one past it answer ENAMETOOLONG"
1085
+ );
1086
+ }
1087
+
1088
+ // The space a Tmpfs counts is what bounds the host's memory, and a count
1089
+ // alone cannot tell, so only what the file still holds on to can.
1090
+ // @behavior FS-149
1091
+ #[test]
1092
+ fn a_file_cut_short_lets_go_of_what_it_held() {
1093
+ let tmpfs = Tmpfs::new();
1094
+ let content = Content::create(&tmpfs.tree).expect("the file must make");
1095
+ let mut data = lock(&content);
1096
+ data.resize(1 << 20).expect("the file must grow");
1097
+ data.resize(16).expect("the file must shrink");
1098
+ assert!(
1099
+ data.bytes.capacity() < 1 << 20,
1100
+ "Content::resize down to 16 bytes from 1 MiB must let go of the rest, holding {}",
1101
+ data.bytes.capacity()
1102
+ );
1103
+ }
1104
+
1105
+ // @behavior FS-150
1106
+ #[test]
1107
+ fn a_file_past_its_limit_can_still_shrink() {
1108
+ let tmpfs = Tmpfs::try_from_iter([("file", vec![0; 100])])
1109
+ .expect("the seed must fit")
1110
+ .with_size(Some(10));
1111
+ let fs = kern_path(Arc::new(tmpfs));
1112
+ assert_eq!(
1113
+ fs.truncate("file", 5),
1114
+ Ok(()),
1115
+ "a truncate through Tmpfs of a file seeded past its limit must shrink it"
1116
+ );
1117
+ }
1118
+
1119
+ /// `tmpfs` reached through the VFS.
1120
+ // Built directly, as a path cannot reach this deep and stacking chains
1121
+ // through the VFS takes a moving of each. A depth a recursive release
1122
+ // cannot survive on this stack is what tells it from a loop.
1123
+ // @behavior FS-145
1124
+ #[test]
1125
+ fn a_tmpfs_goes_however_deep_its_directories_stand() {
1126
+ let tmpfs = Tmpfs::new();
1127
+ let mut at = tmpfs.dir.clone();
1128
+ for _ in 0..200_000 {
1129
+ let below = tmpfs.new_directory();
1130
+ at.state()
1131
+ .entries
1132
+ .insert("a".to_string(), Node::Directory(below.clone()));
1133
+ at = below;
1134
+ }
1135
+ drop(at);
1136
+ let released = std::thread::Builder::new()
1137
+ .stack_size(64 * 1024)
1138
+ .spawn(move || drop(tmpfs))
1139
+ .expect("the thread must start")
1140
+ .join();
1141
+ assert!(
1142
+ released.is_ok(),
1143
+ "a Tmpfs 200000 directories deep, dropped on a 64 KiB stack, must go without \
1144
+ overflowing it"
1145
+ );
1146
+ }
1147
+
1148
+ // A whiteout made where the upper of an Overlay is mounted on its own
1149
+ // shows there, so it answers as the inode `shmem_mknod` makes for it.
1150
+ // @behavior FS-216
1151
+ #[test]
1152
+ fn a_whiteout_reports_an_inode_and_times_of_its_own() {
1153
+ let tmpfs = Tmpfs::new();
1154
+ tmpfs.whiteout("w").expect("the whiteout must be made");
1155
+ let fs = at(tmpfs);
1156
+ let set = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_000);
1157
+ fs.setattr("w", &Iattr::for_times(None, Some(SetTime::At(set))))
1158
+ .expect("the whiteout's times must be set");
1159
+ let stat = fs.vfs_lstat("w").expect("the whiteout must stat");
1160
+ let listed = fs.iterate_dir().expect("the directory must list");
1161
+ let entry = listed
1162
+ .iter()
1163
+ .find(|entry| entry.name == "w")
1164
+ .expect("the whiteout is listed");
1165
+ assert_eq!(
1166
+ (
1167
+ stat.file_type,
1168
+ stat.ino != 0,
1169
+ entry.ino == stat.ino,
1170
+ stat.nlink,
1171
+ stat.mtime
1172
+ ),
1173
+ (FileType::Chrdev, true, true, 1, Some(set)),
1174
+ "a whiteout in a Tmpfs through KernPath must stat as a character device with an \
1175
+ inode number its listing shares, one link, and the times set on it"
1176
+ );
1177
+ }
1178
+
1179
+ fn at(tmpfs: Tmpfs) -> KernPath {
1180
+ kern_path(Arc::new(tmpfs))
1181
+ }
1182
+
1183
+ fn read_all(fs: &KernPath, path: &str) -> Vec<u8> {
1184
+ let mut file = fs
1185
+ .open(
1186
+ path,
1187
+ &OpenHow {
1188
+ read: true,
1189
+ ..OpenHow::default()
1190
+ },
1191
+ )
1192
+ .expect("the file must open");
1193
+ let mut buf = vec![0; 64];
1194
+ let read = file
1195
+ .read_iter(&mut Kiocb::new(0), &mut buf)
1196
+ .expect("the file must read");
1197
+ buf.truncate(read);
1198
+ buf
1199
+ }
1200
+
1201
+ // @behavior FS-001
1202
+ #[test]
1203
+ fn a_tmpfs_serves_the_files_it_was_seeded_with() {
1204
+ let tmpfs = at([("/config/app.yml", "name: kobako")].into_iter().collect());
1205
+ assert_eq!(
1206
+ read_all(&tmpfs, "config/app.yml"),
1207
+ b"name: kobako",
1208
+ "a file seeded into Tmpfs through FromIterator must read back its content"
1209
+ );
1210
+ }
1211
+
1212
+ // @behavior FS-067
1213
+ #[test]
1214
+ fn a_tmpfs_tried_with_a_list_it_cannot_hold_answers_why() {
1215
+ let refused = [
1216
+ Tmpfs::try_from_iter([("/", "x")]),
1217
+ Tmpfs::try_from_iter([("a", "x"), ("a/b", "y")]),
1218
+ Tmpfs::try_from_iter([("a", "x"), ("/a", "y")]),
1219
+ ]
1220
+ .map(|tried| tried.map(drop));
1221
+ assert_eq!(
1222
+ refused,
1223
+ [
1224
+ Err(SeedError::Root),
1225
+ Err(SeedError::FileAndDirectory("a".to_string())),
1226
+ Err(SeedError::Twice("a".to_string())),
1227
+ ],
1228
+ "a list naming the root, a file beneath a file, or a file twice through \
1229
+ Tmpfs::try_from_iter must answer the SeedError naming it"
1230
+ );
1231
+ }
1232
+
1233
+ // A runtime never hands a Filesystem `..`, so a file seeded through one
1234
+ // would be held where no call reaches it.
1235
+ // @behavior FS-087
1236
+ #[test]
1237
+ fn a_tmpfs_tried_with_a_path_through_dot_dot_answers_why() {
1238
+ assert_eq!(
1239
+ Tmpfs::try_from_iter([("a/../b", "x")]).map(drop),
1240
+ Err(SeedError::DotDot("a/../b".to_string())),
1241
+ "a list naming a path through `..` through Tmpfs::try_from_iter must answer \
1242
+ SeedError::DotDot naming it"
1243
+ );
1244
+ }
1245
+
1246
+ // @behavior FS-062
1247
+ #[test]
1248
+ #[should_panic(expected = "a Tmpfs seeds no file at its root")]
1249
+ fn a_tmpfs_seeded_at_its_root_panics() {
1250
+ let _: Tmpfs = [("/", "x")].into_iter().collect();
1251
+ }
1252
+
1253
+ // @behavior FS-062
1254
+ #[test]
1255
+ #[should_panic(expected = "a Tmpfs seeds a as both a file and a directory")]
1256
+ fn a_tmpfs_seeded_with_a_file_beneath_a_file_panics() {
1257
+ let _: Tmpfs = [("a", "x"), ("a/b", "y")].into_iter().collect();
1258
+ }
1259
+
1260
+ // @behavior FS-062
1261
+ #[test]
1262
+ #[should_panic(expected = "a Tmpfs seeds a as both a file and a directory")]
1263
+ fn a_tmpfs_seeded_with_a_file_over_a_directory_panics() {
1264
+ let _: Tmpfs = [("a/b", "y"), ("a", "x")].into_iter().collect();
1265
+ }
1266
+
1267
+ // @behavior FS-062
1268
+ #[test]
1269
+ #[should_panic(expected = "a Tmpfs seeds a twice")]
1270
+ fn a_tmpfs_seeded_with_one_path_twice_panics() {
1271
+ let _: Tmpfs = [("a", "x"), ("a", "y")].into_iter().collect();
1272
+ }
1273
+
1274
+ // @behavior FS-002
1275
+ #[test]
1276
+ fn a_tmpfs_keeps_what_was_written() {
1277
+ let tmpfs = at(Tmpfs::new());
1278
+ let mut file = tmpfs
1279
+ .open_or_create(
1280
+ "notes.txt",
1281
+ &OpenHow {
1282
+ write: true,
1283
+ ..OpenHow::default()
1284
+ },
1285
+ )
1286
+ .expect("a new file must be created");
1287
+ file.write_iter(&mut Kiocb::new(0), b"kept")
1288
+ .expect("the write must land");
1289
+ drop(file);
1290
+ assert_eq!(
1291
+ read_all(&tmpfs, "notes.txt"),
1292
+ b"kept",
1293
+ "a file written through Tmpfs::open must read back from the same Tmpfs"
1294
+ );
1295
+ }
1296
+
1297
+ #[test]
1298
+ fn a_directory_with_entries_is_not_removed() {
1299
+ let tmpfs = at([("dir/file", "x")].into_iter().collect());
1300
+ assert_eq!(tmpfs.vfs_rmdir("dir"), Err(Errno::DirectoryNotEmpty));
1301
+ assert_eq!(tmpfs.vfs_unlink("dir/file"), Ok(()));
1302
+ assert_eq!(tmpfs.vfs_rmdir("dir"), Ok(()));
1303
+ assert_eq!(tmpfs.vfs_lstat("dir"), Err(Errno::NotFound));
1304
+ }
1305
+
1306
+ #[test]
1307
+ fn a_renamed_directory_carries_its_entries() {
1308
+ let tmpfs = at([("old/inner/file", "x")].into_iter().collect());
1309
+ tmpfs
1310
+ .rename("old", &tmpfs, "new")
1311
+ .expect("the rename must succeed");
1312
+ assert_eq!(read_all(&tmpfs, "new/inner/file"), b"x");
1313
+ assert_eq!(tmpfs.vfs_lstat("old"), Err(Errno::NotFound));
1314
+ }
1315
+
1316
+ fn writable(fs: &KernPath, path: &str) -> Box<dyn FileOperations> {
1317
+ fs.open_or_create(
1318
+ path,
1319
+ &OpenHow {
1320
+ write: true,
1321
+ ..OpenHow::default()
1322
+ },
1323
+ )
1324
+ .expect("the file must open")
1325
+ }
1326
+
1327
+ // @behavior FS-022
1328
+ #[test]
1329
+ fn a_write_past_a_tmpfs_size_is_refused() {
1330
+ let tmpfs: Tmpfs = [("file", "x")].into_iter().collect();
1331
+ let tmpfs = at(tmpfs.with_size(Some(4)));
1332
+ assert_eq!(
1333
+ (
1334
+ writable(&tmpfs, "file").write_iter(&mut Kiocb::new(1), b"four"),
1335
+ read_all(&tmpfs, "file")
1336
+ ),
1337
+ (Err(Errno::StorageFull), b"x".to_vec()),
1338
+ "a write growing a Tmpfs's files past its limit through TmpfsFile::write_iter must \
1339
+ answer StorageFull and leave the file as it was"
1340
+ );
1341
+ }
1342
+
1343
+ // @behavior FS-096
1344
+ #[test]
1345
+ fn a_write_of_no_bytes_leaves_a_tmpfs_file_as_it_was() {
1346
+ let tmpfs = at([("file", "")].into_iter().collect());
1347
+ assert_eq!(
1348
+ (
1349
+ writable(&tmpfs, "file").write_iter(&mut Kiocb::new(1000), b""),
1350
+ read_all(&tmpfs, "file")
1351
+ ),
1352
+ (Ok(0), Vec::new()),
1353
+ "an empty write past the end through TmpfsFile::write_iter must answer 0 and leave \
1354
+ the file empty"
1355
+ );
1356
+ }
1357
+
1358
+ // @behavior FS-023
1359
+ #[test]
1360
+ fn a_tmpfs_holds_its_default_size() {
1361
+ let tmpfs = at(Tmpfs::new());
1362
+ let _file = writable(&tmpfs, "file");
1363
+ let mib_64 = 64 * 1024 * 1024;
1364
+ assert_eq!(
1365
+ (
1366
+ tmpfs.truncate("file", mib_64),
1367
+ tmpfs.truncate("file", mib_64 + 1)
1368
+ ),
1369
+ (Ok(()), Err(Errno::StorageFull)),
1370
+ "a Tmpfs given no limit through Tmpfs::new must hold 64 MiB and refuse a byte more"
1371
+ );
1372
+ }
1373
+
1374
+ // @behavior FS-024
1375
+ #[test]
1376
+ fn a_tmpfs_without_a_size_grows_past_the_default() {
1377
+ let tmpfs = at(Tmpfs::new().with_size(None));
1378
+ let _file = writable(&tmpfs, "file");
1379
+ assert_eq!(
1380
+ tmpfs.truncate("file", Tmpfs::DEFAULT_SIZE as u64 + 1),
1381
+ Ok(()),
1382
+ "a Tmpfs given no limit through Tmpfs::with_size(None) must grow past 64 MiB"
1383
+ );
1384
+ }
1385
+
1386
+ // @behavior FS-025
1387
+ #[test]
1388
+ fn a_removed_file_returns_its_space() {
1389
+ let tmpfs = at(Tmpfs::new().with_size(Some(4)));
1390
+ writable(&tmpfs, "first")
1391
+ .write_iter(&mut Kiocb::new(0), b"four")
1392
+ .expect("the first file must fit");
1393
+ tmpfs.vfs_unlink("first").expect("the file must remove");
1394
+ assert_eq!(
1395
+ writable(&tmpfs, "second").write_iter(&mut Kiocb::new(0), b"four"),
1396
+ Ok(4),
1397
+ "the space a file removed through vfs_unlink held must be free for the next"
1398
+ );
1399
+ }
1400
+
1401
+ // A length past `isize::MAX` is one no allocator can hand out, so the
1402
+ // refusal does not depend on how much the host has free.
1403
+ // @behavior FS-026
1404
+ #[test]
1405
+ fn a_file_grown_past_what_can_be_allocated_is_refused() {
1406
+ let tmpfs: Tmpfs = [("file", "x")].into_iter().collect();
1407
+ let tmpfs = at(tmpfs.with_size(None));
1408
+ let mut file = writable(&tmpfs, "file");
1409
+ let unallocatable = isize::MAX as u64 + 1;
1410
+ assert_eq!(
1411
+ (
1412
+ tmpfs.truncate("file", unallocatable),
1413
+ file.write_iter(&mut Kiocb::new(unallocatable), b"x"),
1414
+ read_all(&tmpfs, "file")
1415
+ ),
1416
+ (
1417
+ Err(Errno::StorageFull),
1418
+ Err(Errno::StorageFull),
1419
+ b"x".to_vec()
1420
+ ),
1421
+ "a length no allocator can hand out through TmpfsRegular::setattr and TmpfsFile::write_iter must \
1422
+ answer StorageFull rather than abort"
1423
+ );
1424
+ }
1425
+
1426
+ #[test]
1427
+ fn a_path_beneath_a_file_is_not_a_directory() {
1428
+ let tmpfs = at([("file", "x")].into_iter().collect());
1429
+ assert_eq!(tmpfs.vfs_lstat("file/inner"), Err(Errno::NotADirectory));
1430
+ }
1431
+
1432
+ fn create(fs: &KernPath, path: &str) -> Result<(), Errno> {
1433
+ fs.open_or_create(
1434
+ path,
1435
+ &OpenHow {
1436
+ write: true,
1437
+ ..OpenHow::default()
1438
+ },
1439
+ )
1440
+ .map(drop)
1441
+ }
1442
+
1443
+ // Three inodes hold the root, one file, and one directory, so neither
1444
+ // kind of entry gets past the count.
1445
+ // @behavior FS-030
1446
+ #[test]
1447
+ fn a_tmpfs_holds_at_most_its_inodes() {
1448
+ let tmpfs = at(Tmpfs::new().with_nr_inodes(Some(3)));
1449
+ assert_eq!(
1450
+ (
1451
+ create(&tmpfs, "file"),
1452
+ tmpfs.vfs_mkdir("dir"),
1453
+ create(&tmpfs, "past"),
1454
+ tmpfs.vfs_mkdir("past_dir"),
1455
+ ),
1456
+ (
1457
+ Ok(()),
1458
+ Ok(()),
1459
+ Err(Errno::StorageFull),
1460
+ Err(Errno::StorageFull)
1461
+ ),
1462
+ "a Tmpfs given inodes through Tmpfs::with_nr_inodes must refuse a file or directory \
1463
+ past them, the root counted, as out of space"
1464
+ );
1465
+ }
1466
+
1467
+ // @behavior FS-031
1468
+ #[test]
1469
+ fn a_tmpfs_inodes_follow_its_size() {
1470
+ let tmpfs = at(Tmpfs::new().with_size(Some(2 * 4096)));
1471
+ assert_eq!(
1472
+ (
1473
+ create(&tmpfs, "a"),
1474
+ create(&tmpfs, "b"),
1475
+ create(&tmpfs, "c")
1476
+ ),
1477
+ (Ok(()), Ok(()), Err(Errno::StorageFull)),
1478
+ "a Tmpfs given only a limit through Tmpfs::with_size must hold one entry for each \
1479
+ 4 KiB of it and the root"
1480
+ );
1481
+ }
1482
+
1483
+ // The second handle opened before the first appended, so only an end
1484
+ // read as the append lands puts its bytes after the first's.
1485
+ // @behavior FS-036
1486
+ #[test]
1487
+ fn a_tmpfs_appends_at_the_end_as_it_stands() {
1488
+ let tmpfs = at([("log", "a")].into_iter().collect());
1489
+ let mut first = writable(&tmpfs, "log");
1490
+ let mut second = writable(&tmpfs, "log");
1491
+ let (mut from_first, mut from_second) =
1492
+ (Kiocb::new(0).with_append(), Kiocb::new(0).with_append());
1493
+ assert_eq!(
1494
+ (
1495
+ first.write_iter(&mut from_first, b"bb"),
1496
+ from_first.pos,
1497
+ second.write_iter(&mut from_second, b"ccc"),
1498
+ from_second.pos,
1499
+ read_all(&tmpfs, "log")
1500
+ ),
1501
+ (Ok(2), 3, Ok(3), 6, b"abbccc".to_vec()),
1502
+ "TmpfsFile::append through two handles on one file must land each at the end as it \
1503
+ stands, answering where it landed"
1504
+ );
1505
+ }
1506
+
1507
+ // The VFS refuses a move onto an entry of another kind, as
1508
+ // `may_delete_dentry` does, and the Tmpfs a directory still holding
1509
+ // entries, as `shmem_rename2` does, so the two keep each move here
1510
+ // from replacing its target.
1511
+ // @behavior FS-133
1512
+ #[test]
1513
+ fn a_tmpfs_replaces_only_what_rename_lets_a_move_replace() {
1514
+ let tmpfs = at([("file", "f"), ("full/inner", "i")].into_iter().collect());
1515
+ tmpfs
1516
+ .vfs_mkdir("empty")
1517
+ .expect("the directory must be made");
1518
+ let moves = [
1519
+ ("file", "empty"),
1520
+ ("file", "full"),
1521
+ ("empty", "file"),
1522
+ ("empty", "full"),
1523
+ ]
1524
+ .map(|(from, to)| tmpfs.rename(from, &tmpfs, to).err());
1525
+ let mut standing: Vec<String> = tmpfs
1526
+ .iterate_dir()
1527
+ .expect("the root must list")
1528
+ .into_iter()
1529
+ .map(|entry| entry.name)
1530
+ .collect();
1531
+ standing.sort();
1532
+ assert_eq!(
1533
+ (moves, standing),
1534
+ (
1535
+ [
1536
+ Some(Errno::IsADirectory),
1537
+ Some(Errno::IsADirectory),
1538
+ Some(Errno::NotADirectory),
1539
+ Some(Errno::DirectoryNotEmpty),
1540
+ ],
1541
+ vec!["empty".to_string(), "file".to_string(), "full".to_string()]
1542
+ ),
1543
+ "Tmpfs::rename of a file onto a directory, and of a directory onto a file or a \
1544
+ directory holding entries, must answer EISDIR, ENOTDIR, and ENOTEMPTY, moving nothing"
1545
+ );
1546
+ }
1547
+
1548
+ // A directory replaced by a rename gives its inode back as a removed
1549
+ // one does, so both leave room for the next.
1550
+ // @behavior FS-034
1551
+ #[test]
1552
+ fn a_removed_directory_gives_its_inode_back() {
1553
+ let tmpfs = at(Tmpfs::new().with_nr_inodes(Some(3)));
1554
+ tmpfs.vfs_mkdir("a").expect("the first directory must fit");
1555
+ tmpfs.vfs_mkdir("b").expect("the second directory must fit");
1556
+ tmpfs.vfs_rmdir("a").expect("the directory must remove");
1557
+ let after_removal = tmpfs.vfs_mkdir("c");
1558
+ tmpfs
1559
+ .rename("c", &tmpfs, "b")
1560
+ .expect("a directory must replace an empty one");
1561
+ assert_eq!(
1562
+ (after_removal, tmpfs.vfs_mkdir("d")),
1563
+ (Ok(()), Ok(())),
1564
+ "a directory removed through vfs_rmdir, or replaced through Tmpfs::rename, \
1565
+ must give its inode back"
1566
+ );
1567
+ }
1568
+
1569
+ // The removed file's handle is still open, so its inode is given back
1570
+ // only when the handle goes, as Linux keeps an unlinked file's inode.
1571
+ // @behavior FS-032
1572
+ #[test]
1573
+ fn a_removed_file_gives_its_inode_back_once_closed() {
1574
+ let tmpfs = at(Tmpfs::new().with_nr_inodes(Some(2)));
1575
+ let handle = writable(&tmpfs, "first");
1576
+ tmpfs.vfs_unlink("first").expect("the file must remove");
1577
+ let while_open = create(&tmpfs, "second");
1578
+ drop(handle);
1579
+ assert_eq!(
1580
+ (while_open, create(&tmpfs, "second")),
1581
+ (Err(Errno::StorageFull), Ok(())),
1582
+ "the inode of a file removed through vfs_unlink must stay taken while a \
1583
+ handle holds it, and be free once it closes"
1584
+ );
1585
+ }
1586
+
1587
+ // A host's `st_dev` never sets the top bit, so a device carrying it
1588
+ // cannot name a host's device, nor one another Filesystem took.
1589
+ // @behavior FS-085
1590
+ #[test]
1591
+ fn a_device_of_its_own_stands_apart_from_every_other_device() {
1592
+ let (first, second) = (get_anon_bdev(), get_anon_bdev());
1593
+ let tmpfs = at(Tmpfs::new())
1594
+ .vfs_getattr()
1595
+ .expect("the root must stand")
1596
+ .dev;
1597
+ assert!(
1598
+ [first, second, tmpfs].iter().all(|dev| dev >> 63 == 1)
1599
+ && first != second
1600
+ && tmpfs != first
1601
+ && tmpfs != second,
1602
+ "devices from get_anon_bdev and a Tmpfs's root must each set the top bit \
1603
+ and differ from one another"
1604
+ );
1605
+ }
1606
+
1607
+ fn names(dir: &Dir) -> Vec<String> {
1608
+ dir.state()
1609
+ .entries
1610
+ .iter()
1611
+ .flat_map(|(name, node)| {
1612
+ let beneath = match node {
1613
+ Node::Directory(inner) => names(inner),
1614
+ Node::File(_) | Node::Whiteout(_) => Vec::new(),
1615
+ };
1616
+ std::iter::once(name.clone()).chain(beneath)
1617
+ })
1618
+ .collect()
1619
+ }
1620
+
1621
+ // Each round nests the file one level deeper, so a Tmpfs holding
1622
+ // whole paths would hold names growing with the depth; held under its
1623
+ // own name, every entry stays the one letter it was given.
1624
+ // @behavior FS-094
1625
+ #[test]
1626
+ fn a_tmpfs_holds_each_entry_under_its_own_name() {
1627
+ let held: Arc<Tmpfs> = Arc::new([("d/f", "x")].into_iter().collect());
1628
+ let tmpfs = kern_path(held.clone());
1629
+ for _ in 0..64 {
1630
+ tmpfs
1631
+ .vfs_mkdir("n")
1632
+ .expect("the new directory must be made");
1633
+ tmpfs
1634
+ .rename("d", &tmpfs, "n/d")
1635
+ .expect("the directory must move into the new one");
1636
+ tmpfs
1637
+ .rename("n", &tmpfs, "d")
1638
+ .expect("the new directory must take the old name");
1639
+ }
1640
+ let held = names(&held.dir);
1641
+ assert_eq!(
1642
+ (held, read_all(&tmpfs, &format!("{}f", "d/".repeat(65)))),
1643
+ (
1644
+ std::iter::repeat_n("d".to_string(), 65)
1645
+ .chain(["f".to_string()])
1646
+ .collect::<Vec<_>>(),
1647
+ b"x".to_vec()
1648
+ ),
1649
+ "a directory moved deeper 64 times through Tmpfs::rename must leave every entry \
1650
+ holding only its own name, and the file reading where it now lies"
1651
+ );
1652
+ }
1653
+
1654
+ // @behavior FS-105
1655
+ #[test]
1656
+ fn a_directory_opened_from_a_tmpfs_follows_it_when_it_moves() {
1657
+ let tmpfs = at([("dir/.keep", "")].into_iter().collect());
1658
+ let dir = tmpfs.open_dir("dir").expect("the directory must open");
1659
+ tmpfs
1660
+ .rename("dir", &tmpfs, "moved")
1661
+ .expect("the directory must move");
1662
+ create(&dir, "made").expect("the file must be made");
1663
+ assert_eq!(
1664
+ (
1665
+ tmpfs.vfs_lstat("moved/made").map(|m| m.file_type),
1666
+ tmpfs.vfs_lstat("dir/made").map(|m| m.file_type)
1667
+ ),
1668
+ (Ok(FileType::RegFile), Err(Errno::NotFound)),
1669
+ "a file made through a directory Tmpfs::open_dir opened before Tmpfs::rename moved \
1670
+ it must stand beneath the directory's new path"
1671
+ );
1672
+ }
1673
+
1674
+ // @behavior FS-106
1675
+ #[test]
1676
+ fn a_tmpfs_directory_removed_while_opened_makes_nothing_more() {
1677
+ let tmpfs = at(Tmpfs::new());
1678
+ tmpfs.vfs_mkdir("dir").expect("the directory must be made");
1679
+ let dir = tmpfs.open_dir("dir").expect("the directory must open");
1680
+ tmpfs.vfs_rmdir("dir").expect("the directory must remove");
1681
+ assert_eq!(
1682
+ (
1683
+ create(&dir, "made"),
1684
+ dir.vfs_mkdir("inner"),
1685
+ dir.iterate_dir().map(|entries| entries.len()),
1686
+ dir.vfs_lstat("").map(|m| m.file_type)
1687
+ ),
1688
+ (
1689
+ Err(Errno::NotFound),
1690
+ Err(Errno::NotFound),
1691
+ Ok(0),
1692
+ Ok(FileType::Dir)
1693
+ ),
1694
+ "a directory Tmpfs::open_dir opened, once vfs_rmdir removed it, must make \
1695
+ nothing, list nothing, and still stat as a directory"
1696
+ );
1697
+ }
1698
+
1699
+ // @behavior FS-107
1700
+ #[test]
1701
+ fn a_tmpfs_directory_never_moves_beneath_itself() {
1702
+ let tmpfs = at(Tmpfs::new());
1703
+ tmpfs.vfs_mkdir("a").expect("the directory must be made");
1704
+ tmpfs
1705
+ .vfs_mkdir("a/b")
1706
+ .expect("the inner directory must be made");
1707
+ let inner = tmpfs.open_dir("a/b").expect("the directory must open");
1708
+ assert_eq!(
1709
+ (
1710
+ tmpfs.rename("a", &inner, "a"),
1711
+ tmpfs.vfs_lstat("a/b").map(|m| m.file_type)
1712
+ ),
1713
+ (Err(Errno::InvalidInput), Ok(FileType::Dir)),
1714
+ "Tmpfs::rename of a directory into one opened beneath it must answer InvalidInput \
1715
+ and move nothing"
1716
+ );
1717
+ }
1718
+
1719
+ // The content stands as it was, so only `st_ctime` tells the name moved, as
1720
+ // `simple_rename_timestamp` moves it alone. The wait passes the clock's
1721
+ // resolution, so the two times cannot pass for one.
1722
+ // @behavior FS-177
1723
+ #[test]
1724
+ fn a_moved_file_moves_only_its_changed_time() {
1725
+ let tmpfs = at([("file", "x")].into_iter().collect());
1726
+ let before = tmpfs.vfs_lstat("file").expect("the file must stand");
1727
+ std::thread::sleep(std::time::Duration::from_millis(20));
1728
+ tmpfs
1729
+ .rename("file", &tmpfs, "moved")
1730
+ .expect("the move must land");
1731
+ let after = tmpfs.vfs_lstat("moved").expect("the file must stand");
1732
+ assert!(
1733
+ after.ctime > before.ctime && after.mtime == before.mtime,
1734
+ "Tmpfs::rename of a file must move its changed time and leave its modified time"
1735
+ );
1736
+ }
1737
+
1738
+ // Linux's `notify_change` reads `current_time` once and `shmem_setattr` sets
1739
+ // every time from it, so a clock read for each would leave them apart. A
1740
+ // moment long past tells the one handed from one read here.
1741
+ // @behavior FS-199
1742
+ #[test]
1743
+ fn times_set_to_now_read_the_one_moment_the_change_lands() {
1744
+ let tmpfs = at([("file", "x")].into_iter().collect());
1745
+ let landed = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1);
1746
+ let now = Some(SetTime::Now);
1747
+ tmpfs
1748
+ .setattr(
1749
+ "file",
1750
+ &Iattr {
1751
+ ctime: Some(landed),
1752
+ ..Iattr::for_times(now, now)
1753
+ },
1754
+ )
1755
+ .expect("the times must be set");
1756
+ let set = tmpfs.vfs_lstat("file").expect("the file must stand");
1757
+ assert_eq!(
1758
+ (set.atime, set.mtime, set.ctime),
1759
+ (Some(landed), Some(landed), Some(landed)),
1760
+ "Tmpfs::setattr setting both times to now must set them and its changed time to the \
1761
+ moment the change lands"
1762
+ );
1763
+ }
1764
+
1765
+ // tmpfs frees an inode when the last reference goes, so a directory removed
1766
+ // while it is open still counts, and only its close lets another be made.
1767
+ // @behavior FS-173
1768
+ #[test]
1769
+ fn a_removed_directory_something_holds_keeps_its_inode() {
1770
+ let mount = crate::mount::Mount::new(
1771
+ "/data",
1772
+ Filesystem::new(Tmpfs::new().with_nr_inodes(Some(2))).expect("the instance must stand"),
1773
+ crate::mount::Access::ReadWrite,
1774
+ )
1775
+ .expect("/data is a guest path");
1776
+ let root = crate::vfs::Path::root(mount.mnt());
1777
+ let cred = Arc::default();
1778
+ crate::vfs::filename_mkdirat(&cred, &root, "held").expect("the directory must be made");
1779
+ let how = crate::vfs::OpenHow {
1780
+ read: true,
1781
+ ..Default::default()
1782
+ };
1783
+ let Ok(open) = crate::vfs::kern_path::filp_open(&cred, &root, "held", &how) else {
1784
+ panic!("the directory must open");
1785
+ };
1786
+ crate::vfs::filename_rmdir(&cred, &root, "held").expect("the directory must be removed");
1787
+ let while_open = crate::vfs::filename_mkdirat(&cred, &root, "next");
1788
+ drop(open);
1789
+ assert_eq!(
1790
+ (
1791
+ while_open,
1792
+ crate::vfs::filename_mkdirat(&cred, &root, "next")
1793
+ ),
1794
+ (Err(Errno::StorageFull), Ok(())),
1795
+ "vfs::filename_mkdirat in a Tmpfs out of inodes must answer ENOSPC while a removed \
1796
+ directory stays open, and succeed once it closes"
1797
+ );
1798
+ }
1799
+
1800
+ // @behavior FS-109
1801
+ #[test]
1802
+ fn a_rename_into_a_directory_of_another_tmpfs_crosses_devices() {
1803
+ let mount = |tmpfs: Tmpfs| {
1804
+ crate::mount::Mount::new(
1805
+ "/data",
1806
+ Filesystem::new(tmpfs).expect("the instance must stand"),
1807
+ crate::mount::Access::ReadWrite,
1808
+ )
1809
+ .expect("/data is a guest path")
1810
+ };
1811
+ let (from, to) = (
1812
+ mount([("file", "x")].into_iter().collect()),
1813
+ mount(Tmpfs::new()),
1814
+ );
1815
+ let root = |mount: &crate::mount::Mount| crate::vfs::Path::root(mount.mnt());
1816
+ let cred = Arc::default();
1817
+ assert_eq!(
1818
+ (
1819
+ crate::vfs::filename_renameat2(&cred, &root(&from), "file", &root(&to), "file"),
1820
+ crate::vfs::vfs_fstatat(&cred, &root(&from), "file", false).map(|found| found.size),
1821
+ ),
1822
+ (Err(Errno::CrossesDevices), Ok(1)),
1823
+ "vfs::filename_renameat2 into a directory of another Tmpfs must answer EXDEV and \
1824
+ leave the file"
1825
+ );
1826
+ }
1827
+
1828
+ // The write waits past the clock's resolution, so a time left where
1829
+ // the file was made cannot pass for one the write moved.
1830
+ // @behavior FS-115
1831
+ #[test]
1832
+ fn a_tmpfs_keeps_a_files_times_as_a_tmpfs_mounted_noatime_does() {
1833
+ let tmpfs = at(Tmpfs::new());
1834
+ let how = OpenHow {
1835
+ read: true,
1836
+ write: true,
1837
+ ..OpenHow::default()
1838
+ };
1839
+ let mut file = tmpfs
1840
+ .open_or_create("file", &how)
1841
+ .expect("the file must be made");
1842
+ file.write_iter(&mut Kiocb::new(0), b"ab")
1843
+ .expect("the file must take a write");
1844
+ let made = tmpfs.vfs_lstat("file").expect("the file must report");
1845
+ file.read_iter(&mut Kiocb::new(0), &mut [0; 1])
1846
+ .expect("the file must read");
1847
+ std::thread::sleep(std::time::Duration::from_millis(10));
1848
+ file.write_iter(&mut Kiocb::new(0), b"c")
1849
+ .expect("the file must take a write within its length");
1850
+ let written = tmpfs.vfs_lstat("file").expect("the file must stand");
1851
+ assert_eq!(
1852
+ (
1853
+ written.atime == made.atime,
1854
+ written.mtime > made.mtime,
1855
+ written.ctime == written.mtime,
1856
+ ),
1857
+ (true, true, true),
1858
+ "vfs_lstat of a file read and then written must keep its access time from \
1859
+ when it was made, and move its modification and change times to the write"
1860
+ );
1861
+ }
1862
+
1863
+ // @behavior FS-116
1864
+ #[test]
1865
+ fn a_tmpfs_counts_a_directorys_names_as_a_tmpfs_does() {
1866
+ let tmpfs = at([("dir/file", "x")].into_iter().collect());
1867
+ tmpfs.vfs_mkdir("dir/a").expect("a directory must be made");
1868
+ tmpfs.vfs_mkdir("dir/b").expect("a directory must be made");
1869
+ let nlink = |path| tmpfs.vfs_lstat(path).expect("the entry must stand").nlink;
1870
+ assert_eq!(
1871
+ (nlink("dir"), nlink("dir/file")),
1872
+ (4, 1),
1873
+ "vfs_lstat of a directory holding a file and two directories must count four \
1874
+ names, and of the file one"
1875
+ );
1876
+ }
1877
+
1878
+ // A Tmpfs is the one Filesystem answering this itself, so only its own count
1879
+ // can leave a removed directory reporting names it no longer has.
1880
+ // @behavior FS-178
1881
+ #[test]
1882
+ fn a_removed_directory_something_holds_counts_no_name() {
1883
+ let tmpfs = at(Tmpfs::new());
1884
+ for path in ["gone", "replaced", "moved", "other"] {
1885
+ tmpfs.vfs_mkdir(path).expect("a directory must be made");
1886
+ }
1887
+ let held = |path| tmpfs.open_dir(path).expect("the directory must open");
1888
+ let (gone, replaced, moved) = (held("gone"), held("replaced"), held("moved"));
1889
+ tmpfs.vfs_rmdir("gone").expect("the directory must go");
1890
+ tmpfs
1891
+ .rename("other", &tmpfs, "replaced")
1892
+ .expect("the move must replace the directory");
1893
+ tmpfs
1894
+ .rename("moved", &tmpfs, "there")
1895
+ .expect("the move must land");
1896
+ let nlink = |dir: &KernPath| dir.vfs_getattr().expect("the directory must answer").nlink;
1897
+ assert_eq!(
1898
+ (nlink(&gone), nlink(&replaced), nlink(&moved)),
1899
+ (0, 0, 2),
1900
+ "vfs_getattr of a held Tmpfs directory removed, or replaced by a move, must count no \
1901
+ name, and of one that moved must count its two"
1902
+ );
1903
+ }
1904
+
1905
+ // @behavior FS-137
1906
+ #[test]
1907
+ fn a_tmpfs_sizes_a_directory_as_a_tmpfs_does() {
1908
+ let tmpfs = at([("dir/file", "x")].into_iter().collect());
1909
+ tmpfs.vfs_mkdir("dir/a").expect("a directory must be made");
1910
+ tmpfs.vfs_mkdir("empty").expect("a directory must be made");
1911
+ let len = |path| {
1912
+ tmpfs
1913
+ .vfs_lstat(path)
1914
+ .expect("the directory must stand")
1915
+ .size
1916
+ };
1917
+ assert_eq!(
1918
+ (len("dir"), len("empty")),
1919
+ (80, 40),
1920
+ "vfs_lstat of a directory holding two entries must report a size of 80, and of \
1921
+ an empty one 40"
1922
+ );
1923
+ }
1924
+
1925
+ // @behavior FS-070
1926
+ #[test]
1927
+ fn a_tmpfs_gives_each_directory_it_makes_an_identity_of_its_own() {
1928
+ let tmpfs = at(Tmpfs::new());
1929
+ tmpfs.vfs_mkdir("dir").expect("the directory must be made");
1930
+ let identity = |path| {
1931
+ let metadata = tmpfs.vfs_lstat(path).expect("the directory must stand");
1932
+ (metadata.dev, metadata.ino)
1933
+ };
1934
+ let before = identity("dir");
1935
+ tmpfs
1936
+ .rename("dir", &tmpfs, "moved")
1937
+ .expect("the directory must move");
1938
+ tmpfs
1939
+ .vfs_mkdir("dir")
1940
+ .expect("another directory must be made");
1941
+ assert_eq!(
1942
+ (identity("moved") == before, identity("dir") == before),
1943
+ (true, false),
1944
+ "a directory moved through Tmpfs::rename must keep its identity, and one made at its \
1945
+ old path through vfs_mkdir must have another"
1946
+ );
1947
+ }
1948
+
1949
+ mod stress {
1950
+ use std::sync::atomic::{AtomicBool, Ordering};
1951
+
1952
+ use super::*;
1953
+
1954
+ // A move leaves its old directory before it reaches the new one, so only
1955
+ // a stat landing between the two shows a move counted as a removal.
1956
+ // @behavior FS-201
1957
+ #[test]
1958
+ #[ignore = "a stress witness; run by rake crates:stress"]
1959
+ fn a_moved_file_keeps_its_names_through_the_move() {
1960
+ let mount = crate::mount::Mount::new(
1961
+ "/data",
1962
+ Filesystem::new([("a", "x")].into_iter().collect::<Tmpfs>())
1963
+ .expect("the instance must stand"),
1964
+ crate::mount::Access::ReadWrite,
1965
+ )
1966
+ .expect("/data is a guest path");
1967
+ let root = crate::vfs::Path::root(mount.mnt());
1968
+ let how = crate::vfs::OpenHow {
1969
+ read: true,
1970
+ ..Default::default()
1971
+ };
1972
+ let held = crate::vfs::kern_path::filp_open(&Arc::default(), &root, "a", &how)
1973
+ .unwrap_or_else(|_| panic!("the file must open"));
1974
+ let stop = AtomicBool::new(false);
1975
+ let nameless = std::thread::scope(|scope| {
1976
+ scope.spawn(|| {
1977
+ while !stop.load(Ordering::SeqCst) {
1978
+ for (from, to) in [("a", "b"), ("b", "a")] {
1979
+ crate::vfs::filename_renameat2(&Arc::default(), &root, from, &root, to)
1980
+ .unwrap_or_else(|_| panic!("the move must land"));
1981
+ }
1982
+ }
1983
+ });
1984
+ let nameless = (0..200_000)
1985
+ .filter(|_| held.getattr().is_ok_and(|found| found.nlink == 0))
1986
+ .count();
1987
+ stop.store(true, Ordering::SeqCst);
1988
+ nameless
1989
+ });
1990
+ assert_eq!(
1991
+ nameless, 0,
1992
+ "File::getattr of a Tmpfs file another thread keeps moving must never report it \
1993
+ with no name"
1994
+ );
1995
+ }
1996
+ }
1997
+ }