1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
use crate::{rand_int, rand_str, run_multi};
use alloc::{sync::Arc, vec::Vec};
use core::{convert::TryInto, fmt, ops::Range};
use kcore::{
chan::{Chan, ChanId, ChanKind},
dev::Device,
error::Result,
};
use ksched::{sync::Spinlock, task};
use std::{
fs::{File, OpenOptions},
io::SeekFrom,
path::Path,
};
use std::{
io::{Read, Seek, Write},
path::PathBuf,
process::Command,
};
use tempfile::{tempdir, TempDir};
use task::yield_now;
pub struct FileDisk {
file: Spinlock<File>,
}
impl FileDisk {
pub fn new(path: impl AsRef<Path>) -> Self {
Self {
file: Spinlock::new(
OpenOptions::new()
.read(true)
.write(true)
.open(path)
.unwrap(),
),
}
}
}
#[async_trait::async_trait_try]
impl Device for FileDisk {
async fn shutdown(self)
where
Self: Sized,
{
todo!()
}
async fn attach(&self, aname: &[u8]) -> Result<ChanId>
where
Self: Sized,
{
Ok(ChanId {
path: 0,
version: 0,
kind: ChanKind::File,
})
}
async fn open(
&self,
dir: &ChanId,
name: &[u8],
create_dir: Option<bool>,
) -> kcore::error::Result<Option<ChanId>> {
todo!()
}
async fn close(&self, c: ChanId) {
println!("disk close");
}
async fn remove(&self, c: &ChanId) -> kcore::error::Result<bool> {
todo!()
}
async fn stat(&self, c: &ChanId) -> kcore::error::Result<kcore::chan::Dirent> {
todo!()
}
async fn wstat(&self, c: &ChanId, dirent: &kcore::chan::Dirent) -> kcore::error::Result<()> {
todo!()
}
async fn read(&self, c: &ChanId, buf: &mut [u8], off: usize) -> kcore::error::Result<usize> {
let mut g = self.file.lock();
g.seek(SeekFrom::Start(off as u64)).unwrap();
Ok(g.read(buf).unwrap())
}
async fn write(&self, c: &ChanId, buf: &[u8], off: usize) -> kcore::error::Result<usize> {
let mut g = self.file.lock();
g.seek(SeekFrom::Start(off as u64)).unwrap();
Ok(g.write(buf).unwrap())
}
async fn truncate(&self, c: &ChanId, size: usize) -> Result<usize> {
todo!()
}
}
pub struct MemDisk {
file: Spinlock<Vec<u8>>,
}
impl MemDisk {
pub fn new(size: usize) -> Self {
Self {
file: Spinlock::new(vec![0; size]),
}
}
}
#[async_trait::async_trait_try]
impl Device for MemDisk {
async fn shutdown(self)
where
Self: Sized,
{
todo!()
}
async fn attach(&self, aname: &[u8]) -> Result<ChanId>
where
Self: Sized,
{
Ok(ChanId {
path: 0,
version: 0,
kind: ChanKind::File,
})
}
async fn open(
&self,
dir: &ChanId,
name: &[u8],
create_dir: Option<bool>,
) -> kcore::error::Result<Option<ChanId>> {
todo!()
}
async fn close(&self, c: ChanId) {
println!("disk close");
}
async fn remove(&self, c: &ChanId) -> kcore::error::Result<bool> {
todo!()
}
async fn stat(&self, c: &ChanId) -> kcore::error::Result<kcore::chan::Dirent> {
todo!()
}
async fn wstat(&self, c: &ChanId, dirent: &kcore::chan::Dirent) -> kcore::error::Result<()> {
todo!()
}
async fn read(&self, c: &ChanId, buf: &mut [u8], off: usize) -> kcore::error::Result<usize> {
let g = self.file.lock();
buf.copy_from_slice(g[off..off + buf.len()].try_into().unwrap());
Ok(buf.len())
}
async fn write(&self, c: &ChanId, buf: &[u8], off: usize) -> kcore::error::Result<usize> {
let mut g = self.file.lock();
g[off..off + buf.len()].copy_from_slice(buf);
Ok(buf.len())
}
async fn truncate(&self, c: &ChanId, size: usize) -> Result<usize> {
todo!()
}
}
pub fn gen_fat32img() -> (TempDir, PathBuf) {
let dir = tempdir().unwrap();
println!("path: {:?}", dir.path());
let out = Command::new("pwd").output().unwrap();
println!("stdout: {:?}", out);
let img_path = dir.path().join("test.img");
Command::new("touch")
.arg("test.img")
.current_dir(dir.path())
.output()
.unwrap();
Command::new("dd")
.arg("if=/dev/zero")
.arg("of=test.img")
.arg("seek=100000")
.arg("bs=512")
.arg("count=1")
.current_dir(dir.path())
.output()
.unwrap();
Command::new("mkfs.vfat")
.arg("-F 32")
.arg("test.img")
.current_dir(dir.path())
.output()
.unwrap();
Command::new("mcopy")
.arg("-i")
.arg(img_path.to_str().unwrap())
.arg("src")
.arg("::src")
.output()
.unwrap();
(dir, img_path)
}
pub async fn crud<T: Device + fmt::Debug + Send + Sync + 'static>(
fs: T,
req: Vec<(String, String, usize)>,
) {
let fs = Arc::new(fs);
for (name, data, off) in req {
let fs = fs.clone();
task::spawn(async move {
println!("file '{}' start", name);
let root = loop {
if let Ok(r) = Chan::attach(fs.clone(), b"").await {
break r;
}
yield_now().await;
};
println!("file '{}' attached", name);
let file = root
.open(name.as_bytes(), Some(false))
.await
.unwrap()
.unwrap();
file.close().await;
println!("file '{}' created", name);
let file = root.open(name.as_bytes(), None).await.unwrap().unwrap();
let sz = file.write(data.as_bytes(), off).await.unwrap();
assert_eq!(sz, data.as_bytes().len());
println!("file '{}' written", name);
yield_now().await;
let mut buf = Vec::new();
buf.resize(data.as_bytes().len(), 0);
let sz = file.read(&mut buf, off).await.unwrap();
assert_eq!(sz, buf.len());
assert_eq!(String::from_utf8(buf).unwrap(), data);
println!("file '{}' read", name);
let rm = file.remove().await.unwrap();
assert_eq!(rm, true, "file '{}' not removed", name);
println!("file '{}' can removed", name);
file.close().await;
println!("file '{}' removed after close", name);
debug_assert!(root.open(name.as_bytes(), None).await.unwrap().is_none());
root.close().await;
})
.unwrap();
}
let fs = loop {
if Arc::strong_count(&fs) == 1 {
break Arc::try_unwrap(fs).unwrap();
}
yield_now().await;
};
fs.shutdown().unwrap().await;
}
pub async fn create_dir<T: Device + fmt::Debug + Send + Sync + 'static>(
fs: T,
req: Vec<(String, String, usize)>,
) {
let fs = Arc::new(fs);
for (name, data, off) in req {
let fs = fs.clone();
task::spawn(async move {
println!("dir '{}' start", name);
let root = loop {
if let Ok(r) = Chan::attach(fs.clone(), b"").await {
break r;
}
yield_now().await;
};
println!("dir '{}' attached", name);
let dir = root
.open(name.as_bytes(), Some(true))
.await
.unwrap()
.unwrap();
dir.close().await;
println!("dir '{}' created", name);
let dir = root.open(name.as_bytes(), None).await.unwrap().unwrap();
assert!(dir.write(data.as_bytes(), off).await.is_err());
assert!(dir.open(b".", Some(false)).await.unwrap().is_some());
assert!(dir.open(b"..", Some(false)).await.unwrap().is_some());
let file = dir.open(b"tmp", Some(false)).await.unwrap().unwrap();
assert_eq!(dir.remove().await.unwrap(), false);
assert_eq!(file.remove().await.unwrap(), true);
file.close().await;
assert_eq!(dir.remove().await.unwrap(), true);
dir.close().await;
println!("dir '{}' removed", name);
debug_assert!(root.open(name.as_bytes(), None).await.unwrap().is_none());
root.close().await;
})
.unwrap();
}
let fs = loop {
if Arc::strong_count(&fs) == 1 {
break Arc::try_unwrap(fs).unwrap();
}
yield_now().await;
};
fs.shutdown().unwrap().await;
}