smoo-gadget-core 0.0.1

Reverse USB Mass Storage
Documentation
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
use crate::{ExportSpec, PersistedExportRecord, StateStore};
use anyhow::{Result, anyhow, ensure};
use smoo_gadget_ublk::{SmooUblk, SmooUblkDevice, UblkCtrlHandle, UblkQueueRuntime};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tracing::info;

#[derive(Clone, Copy, Debug)]
pub struct RuntimeTunables {
    pub queue_count: u16,
    pub queue_depth: u16,
    pub max_io_bytes: Option<usize>,
    pub dma_heap: Option<crate::DmaHeap>,
}

pub enum ExportState {
    New,
    RecoveringPending { dev_id: u32 },
    Device(DeviceHandle),
    Deleted,
}

pub enum DeviceHandle {
    Starting {
        dev_id: u32,
        ctrl: UblkCtrlHandle,
        queues: Arc<UblkQueueRuntime>,
    },
    Online {
        dev_id: u32,
        ctrl: UblkCtrlHandle,
        queues: Arc<UblkQueueRuntime>,
    },
    ShuttingDown {
        dev_id: u32,
        ctrl: UblkCtrlHandle,
        queues: Arc<UblkQueueRuntime>,
    },
    Failed {
        dev_id: u32,
        ctrl: Option<UblkCtrlHandle>,
        queues: Option<Arc<UblkQueueRuntime>>,
        last_error: String,
    },
}

impl DeviceHandle {
    pub fn dev_id(&self) -> u32 {
        match self {
            DeviceHandle::Starting { dev_id, .. }
            | DeviceHandle::Online { dev_id, .. }
            | DeviceHandle::ShuttingDown { dev_id, .. }
            | DeviceHandle::Failed { dev_id, .. } => *dev_id,
        }
    }

    pub fn queues(&self) -> Option<Arc<UblkQueueRuntime>> {
        match self {
            DeviceHandle::Starting { queues, .. }
            | DeviceHandle::Online { queues, .. }
            | DeviceHandle::ShuttingDown { queues, .. } => Some(queues.clone()),
            DeviceHandle::Failed { queues, .. } => queues.clone(),
        }
    }

    pub fn ctrl_mut(&mut self) -> Option<&mut UblkCtrlHandle> {
        match self {
            DeviceHandle::Starting { ctrl, .. }
            | DeviceHandle::Online { ctrl, .. }
            | DeviceHandle::ShuttingDown { ctrl, .. } => Some(ctrl),
            DeviceHandle::Failed { ctrl, .. } => ctrl.as_mut(),
        }
    }

    pub fn ctrl(&self) -> Option<&UblkCtrlHandle> {
        match self {
            DeviceHandle::Starting { ctrl, .. }
            | DeviceHandle::Online { ctrl, .. }
            | DeviceHandle::ShuttingDown { ctrl, .. } => Some(ctrl),
            DeviceHandle::Failed { ctrl, .. } => ctrl.as_ref(),
        }
    }

    pub fn is_online(&self) -> bool {
        matches!(self, DeviceHandle::Online { .. })
    }

    pub fn recovery_pending(&self) -> bool {
        self.ctrl()
            .map(|ctrl| ctrl.recovery_pending())
            .unwrap_or(false)
    }

    pub fn into_device(self) -> Option<SmooUblkDevice> {
        match self {
            DeviceHandle::Starting { ctrl, queues, .. }
            | DeviceHandle::Online { ctrl, queues, .. }
            | DeviceHandle::ShuttingDown { ctrl, queues, .. } => {
                Some(SmooUblkDevice::from_parts(ctrl, queues))
            }
            DeviceHandle::Failed {
                ctrl: Some(ctrl),
                queues: Some(queues),
                ..
            } => Some(SmooUblkDevice::from_parts(ctrl, queues)),
            _ => None,
        }
    }
}

pub struct ExportReconcileContext<'a> {
    pub ublk: &'a mut SmooUblk,
    pub state_store: &'a mut StateStore,
    pub tunables: RuntimeTunables,
}

fn error_is_missing(err: &anyhow::Error) -> bool {
    err.chain()
        .find_map(|cause| cause.downcast_ref::<std::io::Error>())
        .and_then(|io_err| io_err.raw_os_error())
        .is_some_and(|code| code == libc::ENOENT || code == libc::EINVAL)
}

pub struct ExportController {
    pub export_id: u32,
    pub spec: ExportSpec,
    pub state: ExportState,
    pub retry_backoff: Duration,
    pub next_retry_at: Option<Instant>,
}

impl ExportController {
    pub fn new(export_id: u32, spec: ExportSpec, state: ExportState) -> Self {
        Self {
            export_id,
            spec,
            state,
            retry_backoff: Duration::from_secs(1),
            next_retry_at: None,
        }
    }

    pub fn dev_id(&self) -> Option<u32> {
        match &self.state {
            ExportState::RecoveringPending { dev_id } => Some(*dev_id),
            ExportState::Device(handle) => Some(handle.dev_id()),
            _ => None,
        }
    }

    pub fn device_handle(&self) -> Option<&DeviceHandle> {
        match &self.state {
            ExportState::Device(handle) => Some(handle),
            _ => None,
        }
    }

    pub fn device_handle_mut(&mut self) -> Option<&mut DeviceHandle> {
        match &mut self.state {
            ExportState::Device(handle) => Some(handle),
            _ => None,
        }
    }

    pub fn take_device_handles(&mut self) -> Option<(UblkCtrlHandle, Arc<UblkQueueRuntime>)> {
        let mut handles = None;
        self.state = match std::mem::replace(&mut self.state, ExportState::New) {
            ExportState::Device(handle) => {
                match handle {
                    DeviceHandle::Starting { ctrl, queues, .. }
                    | DeviceHandle::Online { ctrl, queues, .. }
                    | DeviceHandle::ShuttingDown { ctrl, queues, .. } => {
                        handles = Some((ctrl, queues));
                    }
                    DeviceHandle::Failed {
                        ctrl: Some(ctrl),
                        queues: Some(queues),
                        ..
                    } => handles = Some((ctrl, queues)),
                    _ => {}
                }
                ExportState::Deleted
            }
            other => other,
        };
        handles
    }

    pub fn fail_device(&mut self, message: String) {
        self.state = match std::mem::replace(&mut self.state, ExportState::New) {
            ExportState::Device(handle) => match handle {
                DeviceHandle::Starting {
                    dev_id,
                    ctrl,
                    queues,
                }
                | DeviceHandle::Online {
                    dev_id,
                    ctrl,
                    queues,
                }
                | DeviceHandle::ShuttingDown {
                    dev_id,
                    ctrl,
                    queues,
                } => ExportState::Device(DeviceHandle::Failed {
                    dev_id,
                    ctrl: Some(ctrl),
                    queues: Some(queues),
                    last_error: message,
                }),
                DeviceHandle::Failed {
                    dev_id,
                    ctrl,
                    queues,
                    ..
                } => ExportState::Device(DeviceHandle::Failed {
                    dev_id,
                    ctrl,
                    queues,
                    last_error: message,
                }),
            },
            ExportState::RecoveringPending { dev_id } => {
                ExportState::Device(DeviceHandle::Failed {
                    dev_id,
                    ctrl: None,
                    queues: None,
                    last_error: message,
                })
            }
            other => other,
        };
        self.next_retry_at = Some(Instant::now() + self.retry_backoff);
    }

    pub fn needs_reconcile(&self, now: Instant) -> bool {
        match &self.state {
            ExportState::New | ExportState::RecoveringPending { .. } => {
                self.next_retry_at.is_none_or(|retry_at| now >= retry_at)
            }
            ExportState::Device(handle) => match handle {
                DeviceHandle::Online { .. } => false,
                DeviceHandle::Failed { .. } => {
                    self.next_retry_at.is_none_or(|retry_at| now >= retry_at)
                }
                _ => true,
            },
            ExportState::Deleted => false,
        }
    }

    pub fn is_active_for_status(&self) -> bool {
        matches!(self.state, ExportState::Device(DeviceHandle::Online { .. }))
    }

    pub fn take_handle(&mut self) -> Option<DeviceHandle> {
        let mut handle = None;
        self.state = match std::mem::replace(&mut self.state, ExportState::New) {
            ExportState::Device(inner) => {
                handle = Some(inner);
                ExportState::Deleted
            }
            other => other,
        };
        handle
    }

    pub async fn reconcile(&mut self, cx: &mut ExportReconcileContext<'_>) -> Result<()> {
        let now = Instant::now();
        self.state = match std::mem::replace(&mut self.state, ExportState::New) {
            ExportState::New => {
                let block_size = self.spec.block_size as usize;
                let blocks = self
                    .spec
                    .size_bytes
                    .checked_div(block_size as u64)
                    .unwrap_or(0);
                ensure!(blocks > 0, "export size too small");
                let block_count =
                    usize::try_from(blocks).map_err(|_| anyhow!("block count overflow"))?;
                let device = cx
                    .ublk
                    .setup_device(
                        block_size,
                        block_count,
                        cx.tunables.queue_count,
                        cx.tunables.queue_depth,
                        cx.tunables.max_io_bytes,
                    )
                    .await?;
                let dev_id = device.dev_id();
                cx.state_store.upsert_record(PersistedExportRecord {
                    export_id: self.export_id,
                    spec: self.spec.clone(),
                    assigned_dev_id: Some(dev_id),
                });
                cx.state_store.persist()?;
                let (ctrl, queues) = device.into_parts();
                self.next_retry_at = None;
                ExportState::Device(DeviceHandle::Starting {
                    dev_id,
                    ctrl,
                    queues,
                })
            }
            ExportState::RecoveringPending { dev_id } => {
                match cx.ublk.recover_existing_device(dev_id).await {
                    Ok(device) => {
                        let (ctrl, queues) = device.into_parts();
                        self.next_retry_at = None;
                        ExportState::Device(DeviceHandle::Starting {
                            dev_id,
                            ctrl,
                            queues,
                        })
                    }
                    Err(err) => {
                        if error_is_missing(&err) {
                            cx.state_store
                                .update_record(self.export_id, |record| {
                                    record.assigned_dev_id = None
                                })
                                .ok();
                            cx.state_store.persist().ok();
                            self.next_retry_at = None;
                            ExportState::New
                        } else {
                            self.next_retry_at = Some(now + self.retry_backoff);
                            ExportState::Device(DeviceHandle::Failed {
                                dev_id,
                                ctrl: None,
                                queues: None,
                                last_error: format!("recover device {dev_id} failed: {err:#}"),
                            })
                        }
                    }
                }
            }
            ExportState::Device(handle) => match handle {
                DeviceHandle::Starting {
                    dev_id,
                    mut ctrl,
                    queues,
                } => {
                    let start_result = ctrl.poll_start_result();
                    match start_result {
                        Some(Ok(())) => {
                            let mut device = SmooUblkDevice::from_parts(ctrl, queues.clone());
                            if device.recovery_pending() {
                                cx.ublk.finalize_recovery(&mut device).await?;
                            }
                            info!(
                                export_id = self.export_id,
                                dev_id,
                                queue_count = queues.queue_count(),
                                queue_depth = queues.queue_depth(),
                                block_size = queues.block_size(),
                                block_count = queues.block_count(),
                                max_io_bytes = queues.max_io_bytes(),
                                ioctl_encode = queues.ioctl_encode(),
                                buffer_len = queues.buffer_len(),
                                "ublk target online"
                            );
                            let (ctrl, queues) = device.into_parts();
                            self.next_retry_at = None;
                            ExportState::Device(DeviceHandle::Online {
                                dev_id,
                                ctrl,
                                queues,
                            })
                        }
                        Some(Err(err)) => {
                            ctrl.shutdown();
                            self.next_retry_at = Some(now + self.retry_backoff);
                            ExportState::Device(DeviceHandle::Failed {
                                dev_id,
                                ctrl: Some(ctrl),
                                queues: Some(queues),
                                last_error: format!("start_dev failed: {err:#}"),
                            })
                        }
                        None => {
                            if ctrl.start_deadline_passed(now) {
                                ctrl.mark_start_timed_out();
                                self.next_retry_at = Some(now + self.retry_backoff);
                                ExportState::Device(DeviceHandle::Failed {
                                    dev_id,
                                    ctrl: Some(ctrl),
                                    queues: Some(queues),
                                    last_error: "start_dev timed out".to_string(),
                                })
                            } else {
                                ExportState::Device(DeviceHandle::Starting {
                                    dev_id,
                                    ctrl,
                                    queues,
                                })
                            }
                        }
                    }
                }
                DeviceHandle::Online {
                    dev_id,
                    ctrl,
                    queues,
                } => {
                    self.next_retry_at = None;
                    ExportState::Device(DeviceHandle::Online {
                        dev_id,
                        ctrl,
                        queues,
                    })
                }
                DeviceHandle::ShuttingDown {
                    dev_id: _,
                    ctrl,
                    queues,
                } => {
                    cx.ublk
                        .stop_dev(SmooUblkDevice::from_parts(ctrl, queues), true)
                        .await?;
                    cx.state_store
                        .update_record(self.export_id, |record| record.assigned_dev_id = None)
                        .ok();
                    cx.state_store.persist().ok();
                    self.next_retry_at = None;
                    ExportState::Deleted
                }
                DeviceHandle::Failed {
                    dev_id,
                    mut ctrl,
                    mut queues,
                    last_error,
                } => {
                    if let Some(retry_at) = self.next_retry_at {
                        if now < retry_at {
                            self.next_retry_at = Some(retry_at);
                            ExportState::Device(DeviceHandle::Failed {
                                dev_id,
                                ctrl,
                                queues,
                                last_error,
                            })
                        } else {
                            if let (Some(ctrl_val), Some(queues_val)) = (ctrl.take(), queues.take())
                            {
                                let _ = cx
                                    .ublk
                                    .stop_dev(
                                        SmooUblkDevice::from_parts(ctrl_val, queues_val),
                                        true,
                                    )
                                    .await;
                            } else if let Some(mut ctrl_val) = ctrl.take() {
                                ctrl_val.shutdown();
                            }
                            cx.state_store
                                .update_record(self.export_id, |record| {
                                    record.assigned_dev_id = None
                                })
                                .ok();
                            cx.state_store.persist().ok();
                            self.next_retry_at = None;
                            ExportState::New
                        }
                    } else {
                        self.next_retry_at = None;
                        ExportState::New
                    }
                }
            },
            ExportState::Deleted => ExportState::Deleted,
        };
        Ok(())
    }
}

pub struct GadgetRuntime {
    pub exports: HashMap<u32, ExportController>,
    pub state_store: StateStore,
    pub tunables: RuntimeTunables,
}

impl GadgetRuntime {
    pub fn new(state_store: StateStore, tunables: RuntimeTunables) -> Self {
        Self {
            exports: HashMap::new(),
            state_store,
            tunables,
        }
    }

    pub fn rebuild_exports(&mut self, records: Vec<PersistedExportRecord>) {
        self.exports = records
            .into_iter()
            .map(|record| {
                let state = match record.assigned_dev_id {
                    Some(dev_id) => ExportState::RecoveringPending { dev_id },
                    None => ExportState::New,
                };
                let controller = ExportController::new(record.export_id, record.spec, state);
                (record.export_id, controller)
            })
            .collect();
    }
}