disk_get_vmgs/
lib.rs

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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! A disk backend using the GET's VMGS block interface.
//!
//! This is coded as a general-purpose block device (I guess you could boot a VM
//! off of it), but it is likely only useful for using as the VMGS backing
//! device.

#![cfg(target_os = "linux")]

use disk_backend::DiskError;
use disk_backend::DiskIo;
use guest_emulation_transport::GuestEmulationTransportClient;
use guestmem::MemoryRead;
use guestmem::MemoryWrite;
use inspect::Inspect;
use save_restore::SavedBlockStorageMetadata;
use scsi_buffers::RequestBuffers;
use std::io;
use thiserror::Error;

/// An implementation of [`DiskIo`] backed by the GET.
#[derive(Clone, Debug, Inspect)]
pub struct GetVmgsDisk {
    get: GuestEmulationTransportClient,
    sector_size: u32,
    sector_shift: u32,
    physical_sector_size: u32,
    sector_count: u64,
    max_transfer_sectors: u32,
    max_transfer_size_bytes: u32,
}

/// An error that can occur when creating a new [`GetVmgsDisk`].
#[derive(Debug, Error)]
pub enum NewGetVmgsDiskError {
    /// An IO error occurred while fetching the device info.
    #[error("GET VMGS IO error")]
    Io(#[source] guest_emulation_transport::error::VmgsIoError),
    /// The sector size is not a power of two.
    #[error("invalid sector size")]
    InvalidSectorSize,
    /// The physical sector size is not a power of two or is smaller than the sector size.
    #[error("invalid physical sector size")]
    InvalidPhysicalSectorSize,
    /// The sector count is too large.
    #[error("invalid sector count")]
    InvalidSectorCount,
    /// The disk ends with a partial physical sector.
    #[error("disk ends with a partial physical sector")]
    IncompletePhysicalSector,
    /// The maximum transfer size is smaller than the physical sector size.
    #[error("transfer size is smaller than the physical sector size")]
    InvalidMaxTransferSize,
}

impl GetVmgsDisk {
    /// Returns a new disk instance, communicating read and write IOs over the
    /// `get` transport.
    pub async fn new(get: GuestEmulationTransportClient) -> Result<Self, NewGetVmgsDiskError> {
        let response = get
            .vmgs_get_device_info()
            .await
            .map_err(NewGetVmgsDiskError::Io)?;
        Self::new_inner(
            get,
            response.bytes_per_logical_sector.into(),
            response.bytes_per_physical_sector.into(),
            response.capacity,
            response.maximum_transfer_size_bytes,
        )
    }

    /// Create a disk using metadata previously-fetched via [`Self::save_meta`].
    ///
    /// # Caution
    ///
    /// This method does not confirm that the provided `meta` is what would be
    /// provided by `get`. Callers MUST ensure that the provided `meta` matches
    /// the provided `get` instance.
    ///
    /// Failing to do so may result in data corruption/loss, though, notably: it
    /// will _not_ result in any memory-unsafety (hence why the function isn't
    /// marked `unsafe`).
    pub fn restore_with_meta(
        get: GuestEmulationTransportClient,
        meta: SavedBlockStorageMetadata,
    ) -> Result<Self, NewGetVmgsDiskError> {
        Self::new_inner(
            get,
            meta.sector_size,
            meta.physical_sector_size,
            meta.sector_count,
            meta.max_transfer_size_bytes,
        )
    }

    /// Save the metadata for this disk, for use in passing to
    /// [`Self::restore_with_meta`]
    pub fn save_meta(&self) -> SavedBlockStorageMetadata {
        SavedBlockStorageMetadata {
            capacity: self.sector_count * self.sector_size as u64,
            logical_sector_size: self.sector_size,
            sector_count: self.sector_count,
            sector_size: self.sector_size,
            physical_sector_size: self.physical_sector_size,
            max_transfer_size_bytes: self.max_transfer_size_bytes,
        }
    }

    fn new_inner(
        get: GuestEmulationTransportClient,
        sector_size: u32,
        physical_sector_size: u32,
        sector_count: u64,
        max_transfer_size: u32,
    ) -> Result<Self, NewGetVmgsDiskError> {
        if !sector_size.is_power_of_two() {
            Err(NewGetVmgsDiskError::InvalidSectorSize)
        } else if !physical_sector_size.is_power_of_two() || physical_sector_size < sector_size {
            Err(NewGetVmgsDiskError::InvalidPhysicalSectorSize)
        } else if sector_count.checked_mul(sector_size as u64).is_none() {
            Err(NewGetVmgsDiskError::InvalidSectorCount)
        } else if sector_count % (physical_sector_size / sector_size) as u64 != 0 {
            Err(NewGetVmgsDiskError::IncompletePhysicalSector)
        } else if max_transfer_size < physical_sector_size {
            Err(NewGetVmgsDiskError::InvalidMaxTransferSize)
        } else {
            Ok(GetVmgsDisk {
                get,
                sector_size,
                sector_shift: sector_size.trailing_zeros(),
                physical_sector_size,
                sector_count,
                max_transfer_size_bytes: max_transfer_size,
                // Always transfer in multiples of the physical sector size, if possible.
                max_transfer_sectors: max_transfer_size / physical_sector_size
                    * physical_sector_size
                    / sector_size,
            })
        }
    }
}

impl DiskIo for GetVmgsDisk {
    fn disk_type(&self) -> &str {
        "vmgs-get"
    }

    fn sector_count(&self) -> u64 {
        self.sector_count
    }

    fn sector_size(&self) -> u32 {
        self.sector_size
    }

    fn disk_id(&self) -> Option<[u8; 16]> {
        None
    }

    fn physical_sector_size(&self) -> u32 {
        self.physical_sector_size
    }

    fn is_fua_respected(&self) -> bool {
        false
    }

    fn is_read_only(&self) -> bool {
        false
    }

    async fn read_vectored(
        &self,
        buffers: &RequestBuffers<'_>,
        mut sector: u64,
    ) -> Result<(), DiskError> {
        let mut writer = buffers.writer();
        let mut remaining_sectors = buffers.len() >> self.sector_shift;
        if sector + remaining_sectors as u64 > self.sector_count {
            return Err(DiskError::IllegalBlock);
        }
        while remaining_sectors != 0 {
            let this_sector_count = remaining_sectors.min(self.max_transfer_sectors as usize);
            let data = self
                .get
                .vmgs_read(sector, this_sector_count as u32, self.sector_size)
                .await
                .map_err(|err| DiskError::Io(io::Error::new(io::ErrorKind::Other, err)))?;

            writer.write(&data)?;
            sector += this_sector_count as u64;
            remaining_sectors -= this_sector_count;
        }
        Ok(())
    }

    async fn write_vectored(
        &self,
        buffers: &RequestBuffers<'_>,
        mut sector: u64,
        _fua: bool,
    ) -> Result<(), DiskError> {
        let mut reader = buffers.reader();
        let mut remaining_sector_count = buffers.len() >> self.sector_shift;
        if sector + remaining_sector_count as u64 > self.sector_count {
            return Err(DiskError::IllegalBlock);
        }
        while remaining_sector_count != 0 {
            let this_sector_count = remaining_sector_count.min(self.max_transfer_sectors as usize);
            let data = reader.read_n(this_sector_count << self.sector_shift)?;
            self.get
                .vmgs_write(sector, data, self.sector_size)
                .await
                .map_err(|err| DiskError::Io(io::Error::new(io::ErrorKind::Other, err)))?;

            remaining_sector_count -= this_sector_count;
            sector += this_sector_count as u64;
        }
        Ok(())
    }

    /// Issues an asynchronous flush operation to the disk.
    async fn sync_cache(&self) -> Result<(), DiskError> {
        self.get
            .vmgs_flush()
            .await
            .map_err(|err| DiskError::Io(io::Error::new(io::ErrorKind::Other, err)))
    }

    async fn unmap(
        &self,
        _sector: u64,
        _count: u64,
        _block_level_only: bool,
    ) -> Result<(), DiskError> {
        Ok(())
    }

    fn unmap_behavior(&self) -> disk_backend::UnmapBehavior {
        disk_backend::UnmapBehavior::Ignored
    }
}

/// Save/restore structure definitions.
pub mod save_restore {
    use mesh::payload::Protobuf;

    /// Metadata for a saved block storage device.
    #[derive(Protobuf, Clone)]
    #[mesh(package = "vmgs")]
    pub struct SavedBlockStorageMetadata {
        /// The byte capacity. Redundant with sector_count * sector_size.
        #[mesh(1)]
        pub capacity: u64,
        /// The logical sector size. Identical to sector_size.
        #[mesh(2)]
        pub logical_sector_size: u32,
        /// The number of sectors.
        #[mesh(3)]
        pub sector_count: u64,
        /// The sector size in bytes.
        #[mesh(4)]
        pub sector_size: u32,
        /// The physical sector size in bytes.
        #[mesh(5)]
        pub physical_sector_size: u32,
        /// The maximum transfer size in bytes.
        #[mesh(6)]
        pub max_transfer_size_bytes: u32,
    }
}

// TODO: remove the VMGS specific tests and just test the `DiskIo` interfaces.
#[cfg(test)]
mod tests {
    use super::*;
    use disk_backend::Disk;
    use guest_emulation_transport::api::ProtocolVersion;
    use guest_emulation_transport::test_utilities::TestGet;
    use guest_emulation_transport::test_utilities::new_transport_pair;
    use pal_async::DefaultDriver;
    use pal_async::async_test;
    use pal_async::task::Task;
    use vmgs::FileId;
    use vmgs::Vmgs;
    use vmgs_broker::VmgsClient;
    use vmgs_broker::spawn_vmgs_broker;

    async fn spawn_vmgs(driver: &DefaultDriver) -> (VmgsClient, TestGet, Task<()>) {
        let get = new_transport_pair(driver, None, ProtocolVersion::NICKEL_REV2).await;
        let vmgs_get = GetVmgsDisk::new(get.client.clone()).await.unwrap();
        let vmgs = Vmgs::format_new(Disk::new(vmgs_get).unwrap())
            .await
            .unwrap();
        let (vmgs, task) = spawn_vmgs_broker(driver, vmgs);
        (vmgs, get, task)
    }

    #[async_test]
    async fn basic_read_write(driver: DefaultDriver) {
        let (vmgs, _get, _task) = spawn_vmgs(&driver).await;
        let file_id = FileId::BIOS_NVRAM;

        // write
        let buf = b"hello world".to_vec();
        vmgs.write_file(file_id, buf.clone()).await.unwrap();

        // read
        let info = vmgs.get_file_info(file_id).await.unwrap();
        assert_eq!(info.valid_bytes as usize, buf.len());
        let read_buf = vmgs.read_file(file_id).await.unwrap();

        assert_eq!(buf, read_buf);
    }

    #[async_test]
    async fn multiple_read_write(driver: DefaultDriver) {
        let (vmgs, _get, _task) = spawn_vmgs(&driver).await;
        let file_id_1 = FileId::BIOS_NVRAM;
        let file_id_2 = FileId::TPM_PPI;
        let buf_1 = b"Data data data".to_vec();
        let buf_2 = b"password".to_vec();
        let buf_3 = b"other data data".to_vec();

        vmgs.write_file(file_id_1, buf_1.clone()).await.unwrap();
        let info = vmgs.get_file_info(file_id_1).await.unwrap();
        assert_eq!(info.valid_bytes as usize, buf_1.len());
        let read_buf_1 = vmgs.read_file(file_id_1).await.unwrap();
        assert_eq!(buf_1, read_buf_1);

        vmgs.write_file(file_id_2, buf_2.clone()).await.unwrap();
        let info = vmgs.get_file_info(file_id_2).await.unwrap();
        assert_eq!(info.valid_bytes as usize, buf_2.len());
        let read_buf_2 = vmgs.read_file(file_id_2).await.unwrap();
        assert_eq!(buf_2, read_buf_2);

        vmgs.write_file(file_id_1, buf_3.clone()).await.unwrap();
        let info = vmgs.get_file_info(file_id_1).await.unwrap();
        assert_eq!(info.valid_bytes as usize, buf_3.len());
        let read_buf_3 = vmgs.read_file(file_id_1).await.unwrap();
        assert_eq!(buf_3, read_buf_3);

        vmgs.write_file(file_id_1, buf_1.clone()).await.unwrap();
        let info = vmgs.get_file_info(file_id_1).await.unwrap();
        assert_eq!(info.valid_bytes as usize, buf_1.len());
        let read_buf_1 = vmgs.read_file(file_id_1).await.unwrap();
        assert_eq!(buf_1, read_buf_1);

        vmgs.write_file(file_id_2, buf_2.clone()).await.unwrap();
        let info = vmgs.get_file_info(file_id_2).await.unwrap();
        assert_eq!(info.valid_bytes as usize, buf_2.len());
        let read_buf_2 = vmgs.read_file(file_id_2).await.unwrap();
        assert_eq!(buf_2, read_buf_2);

        vmgs.write_file(file_id_1, buf_3.clone()).await.unwrap();
        let info = vmgs.get_file_info(file_id_1).await.unwrap();
        assert_eq!(info.valid_bytes as usize, buf_3.len());
        let read_buf_3 = vmgs.read_file(file_id_1).await.unwrap();
        assert_eq!(buf_3, read_buf_3);
    }

    #[async_test]
    async fn test_empty_write(driver: DefaultDriver) {
        let (vmgs, _get, _task) = spawn_vmgs(&driver).await;
        let file_id = FileId::BIOS_NVRAM;

        let buf: Vec<u8> = Vec::new();
        vmgs.write_file(file_id, buf.clone()).await.unwrap();

        // read
        let info = vmgs.get_file_info(file_id).await.unwrap();
        assert_eq!(info.valid_bytes as usize, 0);
        let read_buf = vmgs.read_file(file_id).await.unwrap();

        assert_eq!(buf, read_buf);
        assert_eq!(read_buf.len(), 0);
    }

    #[async_test]
    async fn test_read_write_large(driver: DefaultDriver) {
        let (vmgs, _get, _task) = spawn_vmgs(&driver).await;
        let file_id = FileId::BIOS_NVRAM;

        // write
        let buf: Vec<u8> = (0..).map(|x| x as u8).take(1024 * 4 * 4 + 1).collect();
        vmgs.write_file(file_id, buf.clone()).await.unwrap();

        // read
        let info = vmgs.get_file_info(file_id).await.unwrap();
        assert_eq!(info.valid_bytes as usize, buf.len());
        let read_buf = vmgs.read_file(file_id).await.unwrap();

        assert_eq!(buf, read_buf);
    }

    #[async_test]
    async fn test_read_write_encryption(driver: DefaultDriver) {
        let get = new_transport_pair(&driver, None, ProtocolVersion::NICKEL_REV2).await;
        let vmgs_get = GetVmgsDisk::new(get.client.clone()).await.unwrap();
        let mut vmgs = Vmgs::format_new(Disk::new(vmgs_get).unwrap())
            .await
            .unwrap();
        let file_id = FileId::BIOS_NVRAM;
        let encryption_key = vec![1; 32];

        vmgs.add_new_encryption_key(&encryption_key, vmgs::EncryptionAlgorithm::AES_GCM)
            .await
            .unwrap();

        // write
        let buf: Vec<u8> = (0..).map(|x| x as u8).take(1024 * 4 * 4 + 1).collect();
        vmgs.write_file_encrypted(file_id, &buf).await.unwrap();

        // read
        let info = vmgs.get_file_info(file_id).unwrap();
        assert_eq!(info.valid_bytes as usize, buf.len());
        let read_buf = vmgs.read_file(file_id).await.unwrap();

        assert_eq!(buf, read_buf);

        drop(vmgs);

        let vmgs_get = GetVmgsDisk::new(get.client.clone()).await.unwrap();
        let mut vmgs = Vmgs::open(Disk::new(vmgs_get).unwrap()).await.unwrap();

        let read_buf = vmgs.read_file(file_id).await.unwrap();

        assert_ne!(buf, read_buf);

        vmgs.unlock_with_encryption_key(&encryption_key)
            .await
            .unwrap();

        let (vmgs, _task) = spawn_vmgs_broker(&driver, vmgs);

        let info = vmgs.get_file_info(file_id).await.unwrap();
        assert_eq!(info.valid_bytes as usize, buf.len());
        let read_buf = vmgs.read_file(file_id).await.unwrap();

        assert_eq!(buf, read_buf);
    }
}