Skip to main content

scsidisk/scsidvd/
mod.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4use super::AsyncScsiDisk;
5use super::SavedSenseData;
6use super::ScsiResult;
7use super::ScsiSaveRestore;
8use super::scsi;
9use crate::Request;
10use crate::ScsiSavedState;
11use crate::SenseDataSlot;
12use disk_backend::Disk;
13use disk_backend::DiskError;
14use guestmem::AccessError;
15use guestmem::MemoryRead;
16use guestmem::MemoryWrite;
17use parking_lot::Mutex;
18use parking_lot::RwLock;
19use scsi::AdditionalSenseCode;
20use scsi::FeatureNumber::FeaturePowerManagement;
21use scsi::FeatureNumber::FeatureRealTimeStreaming;
22use scsi::FeatureNumber::FeatureTimeout;
23use scsi::ScsiOp;
24use scsi::ScsiStatus;
25use scsi::SenseData;
26use scsi::SenseKey;
27use scsi::srb::SrbStatus;
28use scsi_buffers::RequestBuffers;
29use scsi_core::save_restore::DriveState;
30use scsi_core::save_restore::IsoMediumEvent;
31use scsi_core::save_restore::ScsiDvdSavedState;
32use stackfuture::StackFuture;
33use std::sync::Arc;
34use thiserror::Error;
35use tracing::Instrument;
36use vmcore::save_restore::RestoreError;
37use vmcore::save_restore::SaveError;
38use zerocopy::FromBytes;
39use zerocopy::FromZeros;
40use zerocopy::Immutable;
41use zerocopy::IntoBytes;
42use zerocopy::KnownLayout;
43
44#[derive(Clone)]
45enum Media {
46    Unloaded,
47    Loaded(Disk),
48}
49
50pub struct SimpleScsiDvd {
51    media: Arc<RwLock<Media>>,
52    media_state: Arc<Mutex<MediaState>>,
53    sense_data: SenseDataSlot,
54}
55
56#[derive(Debug, Default)]
57struct MediaState {
58    drive_state: DriveState,
59    pending_medium_event: IsoMediumEvent,
60    persistent: bool,
61    prevent: bool,
62}
63
64#[derive(Error, Debug)]
65enum ScsiDvdError {
66    #[error("illegal request, asc: {0:?}, qualifier: {1:?}")]
67    IllegalRequest(AdditionalSenseCode, u8),
68    #[error("data overrun")]
69    DataOverrun,
70    #[error("memory access error")]
71    MemoryAccess(#[source] AccessError),
72    #[error("io error")]
73    IoError(#[source] DiskError),
74    #[error("not ready, sense key: {0:?}, qualifier: {1}")]
75    SenseNotReady(AdditionalSenseCode, u8),
76    #[error("invalid request - no sense data")]
77    IllegalRequestNoSenseData,
78}
79
80struct RequestParametersIso<'a> {
81    tx: usize,
82    offset: u64,
83    disk: Option<&'a Disk>,
84}
85
86impl AsyncScsiDisk for SimpleScsiDvd {
87    fn clear_nexus_state(&self) {
88        self.sense_data.set(None);
89        let mut media_state = self.media_state.lock();
90        // The tray lock is the one that bites: an initiator that set PREVENT and
91        // then went away would otherwise leave the next one unable to eject, its
92        // START STOP UNIT failed with MEDIUM_REMOVAL_PREVENTED by a decision it
93        // never made.
94        media_state.prevent = false;
95        media_state.persistent = false;
96        // Queued for an initiator that is gone. The next one learns the current
97        // media state from its own TEST UNIT READY or GET EVENT STATUS.
98        media_state.pending_medium_event = IsoMediumEvent::None;
99        // drive_state and the media itself are deliberately untouched: an ejected
100        // tray stays ejected, as it would on a real drive.
101    }
102
103    fn execute_scsi<'a>(
104        &'a self,
105        external_data: &'a RequestBuffers<'a>,
106        request: &'a Request,
107    ) -> StackFuture<'a, ScsiResult, { super::ASYNC_SCSI_DISK_STACK_SIZE }> {
108        StackFuture::from(async move {
109            let op = request.scsiop();
110
111            // The command uses this copy of the media throughout, so a media
112            // change while it runs does not affect it. Nothing holds `media`
113            // across the disk I/O: a command never waits for another command,
114            // and a media change never waits for a command.
115            // The guard is dropped at the end of this block, before the command
116            // runs. (`drop` alone does not end its scope for the `Send` check
117            // on this future.)
118            let media = {
119                let guard = self.media.read();
120                guard.clone()
121            };
122            let result = match op {
123                ScsiOp::INQUIRY => self.handle_inquiry_iso(external_data, request),
124                ScsiOp::TEST_UNIT_READY => self.handle_test_unit_ready_iso(),
125                ScsiOp::READ | ScsiOp::READ12 | ScsiOp::READ16 => {
126                    self.handle_data_cdb_async_iso(&media, external_data, request)
127                        .instrument(tracing::trace_span!("handle_data_cdb_async", ?op,))
128                        .await
129                }
130                ScsiOp::GET_EVENT_STATUS => self.handle_get_event_status(external_data, request),
131                ScsiOp::GET_CONFIGURATION => {
132                    self.handle_get_configuration_iso(external_data, request)
133                }
134                ScsiOp::READ_CAPACITY => self.handle_read_capacity_iso(&media, external_data),
135                ScsiOp::READ_TOC => self.handle_read_toc(&media, external_data, request),
136                ScsiOp::START_STOP_UNIT => self.handle_start_stop_unit(request).await,
137                ScsiOp::MODE_SENSE10 => self.handle_mode_sense_iso(external_data, request),
138                ScsiOp::REQUEST_SENSE => self.handle_request_sense_iso(external_data, request),
139                ScsiOp::MEDIUM_REMOVAL => self.handle_medium_removal_iso(request),
140                ScsiOp::MODE_SELECT10 => self.handle_mode_select_iso(request, external_data),
141                ScsiOp::READ_TRACK_INFORMATION => {
142                    self.handle_read_track_information_iso(&media, external_data, request)
143                }
144                ScsiOp::READ_DVD_STRUCTURE => {
145                    self.handle_read_dvd_structure(external_data, request)
146                }
147                ScsiOp::GET_PERFORMANCE => {
148                    self.handle_get_performance(&media, external_data, request)
149                }
150                ScsiOp::MECHANISM_STATUS => self.handle_mechanism_status(external_data, request),
151                ScsiOp::READ_BUFFER_CAPACITY => {
152                    self.handle_read_buffer_capacity(external_data, request)
153                }
154                ScsiOp::READ_DISC_INFORMATION => {
155                    self.handle_read_disc_information(external_data, request)
156                }
157                ScsiOp::SET_STREAMING => self.handle_set_streaming(&media, external_data, request),
158                _ => {
159                    tracelimit::warn_ratelimited!(op = ?op, "illegal command");
160                    Err(ScsiDvdError::IllegalRequest(
161                        AdditionalSenseCode::ILLEGAL_COMMAND,
162                        0,
163                    ))
164                }
165            };
166
167            self.process_result(result, op)
168        })
169    }
170}
171
172impl inspect::Inspect for SimpleScsiDvd {
173    fn inspect(&self, req: inspect::Request<'_>) {
174        let mut resp = req.respond();
175
176        resp.field("drive_state", self.media_state.lock().drive_state);
177
178        if let Media::Loaded(disk) = &*self.media.read() {
179            resp.field("backend", disk);
180        }
181    }
182}
183
184const ISO_SECTOR_SIZE: u32 = 2048;
185
186impl SimpleScsiDvd {
187    pub fn new(disk: Option<Disk>) -> Self {
188        assert!(
189            disk.as_ref()
190                .is_none_or(|disk| disk.sector_size() <= ISO_SECTOR_SIZE)
191        );
192
193        let (media, pending_medium_event, drive_state) = if let Some(disk) = disk {
194            (
195                RwLock::new(Media::Loaded(disk)).into(),
196                IsoMediumEvent::MediaToMedia,
197                DriveState::MediumPresentTrayClosed,
198            )
199        } else {
200            (
201                RwLock::new(Media::Unloaded).into(),
202                IsoMediumEvent::MediaToNoMedia,
203                DriveState::MediumNotPresentTrayClosed,
204            )
205        };
206
207        SimpleScsiDvd {
208            media,
209            media_state: Arc::new(Mutex::new(MediaState {
210                pending_medium_event,
211                drive_state,
212                ..Default::default()
213            })),
214            sense_data: SenseDataSlot::default(),
215        }
216    }
217
218    pub fn change_media(&self, disk: Option<Disk>) {
219        if let Some(disk) = disk {
220            // Insert medium
221            let mut media = self.media.write();
222
223            let mut media_state = self.media_state.lock();
224            media_state.drive_state = DriveState::MediumPresentTrayOpen;
225            media_state.pending_medium_event = IsoMediumEvent::NoMediaToMedia;
226
227            *media = Media::Loaded(disk);
228
229            tracing::debug!("completed host initiated insert");
230        } else {
231            // Eject medium
232            let mut media = self.media.write();
233            let mut media_state = self.media_state.lock();
234
235            // This will cause the next GESN or TUR command to report medium removal
236            media_state.drive_state = DriveState::MediumNotPresentTrayOpen;
237            media_state.pending_medium_event = IsoMediumEvent::MediaToNoMedia;
238
239            *media = Media::Unloaded;
240
241            tracing::debug!("completed host initiated eject");
242        }
243    }
244
245    fn sector_shift(&self) -> u8 {
246        ISO_SECTOR_SIZE.trailing_zeros() as u8
247    }
248
249    /// Returns the loaded disk, or the error for an empty drive.
250    fn loaded_disk<'a>(&self, media: &'a Media) -> Result<&'a Disk, ScsiDvdError> {
251        self.validate_media_for_read()?;
252        match media {
253            Media::Loaded(disk) => Ok(disk),
254            // The drive state is saved and restored, the media is not, so the
255            // two can disagree after a restore.
256            Media::Unloaded => Err(ScsiDvdError::SenseNotReady(
257                AdditionalSenseCode::NO_MEDIA_IN_DEVICE,
258                if self.media_state.lock().drive_state.tray_open() {
259                    scsi::MEDIUM_NOT_PRESENT_TRAY_OPEN
260                } else {
261                    scsi::MEDIUM_NOT_PRESENT_TRAY_CLOSED
262                },
263            )),
264        }
265    }
266}
267
268/// Returns the capacity of `disk` in ISO sectors.
269fn iso_sector_count(disk: &Disk) -> u64 {
270    disk.sector_count() / disk_balancer(disk)
271}
272
273fn disk_balancer(disk: &Disk) -> u64 {
274    // Per protocol, the sector size for an ISO is 2048. Any read request which
275    // goes to backend disk with sector size <= 2048 then we need to convert
276    // read offset and sector count accordingly.
277    // e.g.: If disk backend has sector_size = 512 then a read request at sector n
278    // should actually go to sector 4*n of backend disk. If sector count of
279    // backend device is n then it should be reported as sector count/4 to the guest.
280    (ISO_SECTOR_SIZE / disk.sector_size()) as u64
281}
282
283impl ScsiSaveRestore for SimpleScsiDvd {
284    fn save(&self) -> Result<Option<ScsiSavedState>, SaveError> {
285        let sense = self.sense_data.get();
286        let sense_data = sense.map(|sense| SavedSenseData {
287            sense_key: sense.header.sense_key.0,
288            additional_sense_code: sense.additional_sense_code.0,
289            additional_sense_code_qualifier: sense.additional_sense_code_qualifier,
290        });
291
292        let media_state = self.media_state.lock();
293        Ok(Some(ScsiSavedState::ScsiDvd(ScsiDvdSavedState {
294            sense_data,
295            persistent: media_state.persistent,
296            prevent: media_state.prevent,
297            drive_state: media_state.drive_state,
298            pending_medium_event: media_state.pending_medium_event,
299        })))
300    }
301
302    fn restore(&self, state: &ScsiSavedState) -> Result<(), RestoreError> {
303        if let ScsiSavedState::ScsiDvd(dvd_state) = state {
304            let ScsiDvdSavedState {
305                sense_data,
306                persistent,
307                prevent,
308                drive_state,
309                pending_medium_event,
310            } = *dvd_state;
311
312            // restore sense data
313            self.sense_data.set(
314                sense_data
315                    .map(|sense| {
316                        SenseData::new(
317                            SenseKey(sense.sense_key),
318                            AdditionalSenseCode(sense.additional_sense_code),
319                            sense.additional_sense_code_qualifier,
320                        )
321                    })
322                    .as_ref(),
323            );
324
325            let mut media_state = self.media_state.lock();
326            media_state.drive_state = drive_state;
327            media_state.pending_medium_event = pending_medium_event;
328            media_state.persistent = persistent;
329            media_state.prevent = prevent;
330            Ok(())
331        } else {
332            Err(RestoreError::InvalidSavedState(anyhow::anyhow!(
333                "saved state didn't match expected format ScsiDvdSavedState"
334            )))
335        }
336    }
337}
338
339/// Writes a VPD page.
340///
341/// Assumes that allocation_length is already validated to be at least
342/// `size_of::<scsi::VpdPageHeader>()`.
343fn write_vpd_page<T: ?Sized + IntoBytes + Immutable + KnownLayout>(
344    external_data: &RequestBuffers<'_>,
345    allocation_length: usize,
346    page_code: u8,
347    page_data: &T,
348) -> Result<usize, ScsiDvdError> {
349    let header = scsi::VpdPageHeader {
350        device_type: scsi::READ_ONLY_DIRECT_ACCESS_DEVICE,
351        page_code,
352        reserved: 0,
353        page_length: size_of_val(page_data).try_into().unwrap(),
354    };
355
356    let tx = std::cmp::min(
357        allocation_length,
358        size_of_val(&header) + size_of_val(page_data),
359    );
360
361    let mut writer = external_data.writer();
362    writer
363        .write(header.as_bytes())
364        .map_err(ScsiDvdError::MemoryAccess)?;
365
366    writer
367        .write(&page_data.as_bytes()[..tx - size_of_val(&header)])
368        .map_err(ScsiDvdError::MemoryAccess)?;
369
370    Ok(tx)
371}
372
373impl SimpleScsiDvd {
374    fn handle_inquiry_iso(
375        &self,
376        external_data: &RequestBuffers<'_>,
377        request: &Request,
378    ) -> Result<usize, ScsiDvdError> {
379        let cdb = scsi::CdbInquiry::read_from_prefix(&request.cdb[..])
380            .unwrap()
381            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
382
383        let allocation_length = cdb.allocation_length.get() as usize;
384
385        if external_data.len() < allocation_length {
386            return Err(ScsiDvdError::DataOverrun);
387        }
388        // If the PAGE CODE field is not set to zero when the EVPD bit is set to zero,
389        // the command shall be terminated with CHECK CONDITION status, with the sense key
390        // set to ILLEGAL REQUEST, and the additional sense code set to INVALID FIELD IN CDB.
391        let enable_vpd = cdb.flags.vpd();
392        if cdb.page_code != 0 && !enable_vpd {
393            return Err(ScsiDvdError::IllegalRequest(
394                AdditionalSenseCode::INVALID_CDB,
395                0,
396            ));
397        }
398
399        if enable_vpd {
400            if allocation_length < size_of::<scsi::VpdPageHeader>() {
401                return Err(ScsiDvdError::DataOverrun);
402            }
403
404            match cdb.page_code {
405                scsi::VPD_SUPPORTED_PAGES => {
406                    self.handle_vpd_supported_pages_iso(external_data, allocation_length)
407                }
408                scsi::VPD_DEVICE_IDENTIFIERS => {
409                    self.handle_vpd_device_identifiers_iso(external_data, allocation_length)
410                }
411                _ => Err(ScsiDvdError::IllegalRequest(
412                    AdditionalSenseCode::INVALID_CDB,
413                    0,
414                )),
415            }
416        } else {
417            self.handle_no_vpd_page_iso(external_data, allocation_length)
418        }
419    }
420
421    fn handle_test_unit_ready_iso(&self) -> Result<usize, ScsiDvdError> {
422        let drive_state = self.media_state.lock().drive_state;
423
424        match drive_state {
425            DriveState::MediumPresentTrayOpen => Ok(0),
426            DriveState::MediumPresentTrayClosed => Ok(0),
427            DriveState::MediumNotPresentTrayOpen => Err(ScsiDvdError::SenseNotReady(
428                AdditionalSenseCode::NO_MEDIA_IN_DEVICE,
429                scsi::MEDIUM_NOT_PRESENT_TRAY_OPEN,
430            )),
431            DriveState::MediumNotPresentTrayClosed => Err(ScsiDvdError::SenseNotReady(
432                AdditionalSenseCode::NO_MEDIA_IN_DEVICE,
433                scsi::MEDIUM_NOT_PRESENT_TRAY_CLOSED,
434            )),
435        }
436    }
437
438    async fn handle_data_cdb_async_iso(
439        &self,
440        media: &Media,
441        external_data: &RequestBuffers<'_>,
442        request: &Request,
443    ) -> Result<usize, ScsiDvdError> {
444        let op = request.scsiop();
445        let p = self.validate_data_cdb_iso(media, external_data, request, op)?;
446
447        if let Some(disk) = p.disk {
448            disk.read_vectored(&external_data.subrange(0, p.tx), p.offset)
449                .await
450                .map_err(ScsiDvdError::IoError)?;
451        }
452
453        Ok(p.tx)
454    }
455
456    fn handle_get_event_status(
457        &self,
458        external_data: &RequestBuffers<'_>,
459        request: &Request,
460    ) -> Result<usize, ScsiDvdError> {
461        let cdb = scsi::CdbGetEventStatusNotification::read_from_prefix(&request.cdb[..])
462            .unwrap()
463            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
464        let allocation_length = cdb.event_list_length.get() as usize;
465        let mut pending_medium_event = IsoMediumEvent::None;
466
467        //  Make sure buffer is as big as the requested size
468        if allocation_length > external_data.len() {
469            return Err(ScsiDvdError::DataOverrun);
470        }
471
472        // don't support asynchronous mode
473        if !cdb.flags.immediate() {
474            return Err(ScsiDvdError::IllegalRequest(
475                AdditionalSenseCode::INVALID_CDB,
476                0x00,
477            ));
478        }
479
480        // Go through the possible event notifications in priority order.
481        // only one event class should be reported at once.
482        // if no event has occurred, the driver shall report the "no change"
483        // event for the highest priority requested event class.
484        let mut media_status = scsi::NotificationMediaStatus::new_zeroed();
485        {
486            let mut media_state = self.media_state.lock();
487            if cdb.notification_class_request.media_status() {
488                pending_medium_event = media_state.pending_medium_event;
489                match media_state.pending_medium_event {
490                    IsoMediumEvent::None => (),
491                    IsoMediumEvent::NoMediaToMedia => {
492                        media_status.media_event = scsi::NOTIFICATION_MEDIA_EVENT_NEW_MEDIA;
493                        media_status.status_info.set_media_present(true);
494
495                        media_state.drive_state = DriveState::MediumPresentTrayClosed;
496                        media_state.pending_medium_event = IsoMediumEvent::None;
497                    }
498                    IsoMediumEvent::MediaToNoMedia => {
499                        media_status.media_event = scsi::NOTIFICATION_MEDIA_EVENT_MEDIA_REMOVAL;
500                        media_status.status_info.set_media_present(false);
501
502                        media_state.pending_medium_event = IsoMediumEvent::None;
503                    }
504                    IsoMediumEvent::MediaToMedia => {
505                        media_status.media_event = scsi::NOTIFICATION_MEDIA_EVENT_MEDIA_REMOVAL;
506                        media_status.status_info.set_media_present(false);
507
508                        media_state.drive_state = DriveState::MediumNotPresentTrayOpen;
509                        media_state.pending_medium_event = IsoMediumEvent::NoMediaToMedia;
510                    }
511                }
512
513                media_status
514                    .status_info
515                    .set_door_tray_open(media_state.drive_state.tray_open());
516            }
517        }
518
519        let data_transfer_length = if pending_medium_event != IsoMediumEvent::None {
520            let header_size = self.iso_init_event_header(
521                external_data,
522                allocation_length,
523                (size_of::<scsi::NotificationEventStatusHeader>() + size_of_val(&media_status)
524                    - size_of::<u16>()) as u16,
525                false,
526                scsi::NOTIFICATION_MEDIA_STATUS_CLASS_EVENTS,
527            )?;
528
529            let body_size =
530                std::cmp::min(size_of_val(&media_status), allocation_length - header_size);
531
532            external_data
533                .subrange(header_size, external_data.len() - header_size)
534                .writer()
535                .write(&media_status.as_bytes()[..body_size])
536                .map_err(ScsiDvdError::MemoryAccess)?;
537
538            if media_status.media_event == scsi::NOTIFICATION_MEDIA_EVENT_NEW_MEDIA {
539                tracing::info!("media arrival");
540            } else if media_status.media_event == scsi::NOTIFICATION_MEDIA_EVENT_MEDIA_REMOVAL {
541                tracing::info!("media removal");
542            }
543            header_size + body_size
544        } else {
545            if cdb.notification_class_request.operational_change() {
546                let persistent_prevented = self.media_state.lock().persistent;
547                let operational_status = scsi::NotificationOperationalStatus {
548                    operation_event: scsi::NOTIFICATION_POWER_EVENT_NO_CHANGE,
549                    flags: scsi::OperationalStatusFlags::new()
550                        .with_operational_status(scsi::NOTIFICATION_OPERATIONAL_STATUS_AVAILABLE)
551                        .with_reserved2(0x00)
552                        .with_persistent_prevented(persistent_prevented),
553                    operation: 0.into(),
554                };
555
556                let header_size = self.iso_init_event_header(
557                    external_data,
558                    allocation_length,
559                    (size_of::<scsi::NotificationEventStatusHeader>()
560                        + size_of_val(&operational_status)
561                        - size_of::<u16>()) as u16,
562                    false,
563                    scsi::NOTIFICATION_OPERATIONAL_CHANGE_CLASS_EVENTS,
564                )?;
565
566                let body_size = std::cmp::min(
567                    size_of_val(&operational_status),
568                    allocation_length - header_size,
569                );
570                external_data
571                    .subrange(header_size, external_data.len() - header_size)
572                    .writer()
573                    .write(&operational_status.as_bytes()[..body_size])
574                    .map_err(ScsiDvdError::MemoryAccess)?;
575
576                header_size + body_size
577            } else if cdb.notification_class_request.power_management() {
578                let header_size = self.iso_init_event_header(
579                    external_data,
580                    allocation_length,
581                    (size_of::<scsi::NotificationEventStatusHeader>()
582                        + size_of::<scsi::NotificationPowerStatus>()
583                        - size_of::<u16>()) as u16,
584                    false,
585                    scsi::NOTIFICATION_POWER_MANAGEMENT_CLASS_EVENTS,
586                )?;
587                let data = scsi::NotificationPowerStatus {
588                    power_event: scsi::NOTIFICATION_POWER_EVENT_NO_CHANGE,
589                    power_status: scsi::NOTIFICATION_POWER_STATUS_ACTIVE,
590                    reserved: [0x00, 0x00],
591                };
592                let body_size = std::cmp::min(
593                    size_of::<scsi::NotificationPowerStatus>(),
594                    allocation_length - header_size,
595                );
596                external_data
597                    .subrange(header_size, external_data.len() - header_size)
598                    .writer()
599                    .write(&data.as_bytes()[..body_size])
600                    .map_err(ScsiDvdError::MemoryAccess)?;
601
602                header_size + body_size
603            } else if cdb.notification_class_request.external_request() {
604                let persistent_prevented = self.media_state.lock().persistent;
605                let external_status = scsi::NotificationExternalStatus {
606                    external_event: scsi::NOTIFICATION_EXTERNAL_EVENT_NO_CHANGE,
607                    flags: scsi::ExternalStatusFlags::new()
608                        .with_external_status(scsi::NOTIFICATION_EXTERNAL_STATUS_READY)
609                        .with_reserved2(0x00)
610                        .with_persistent_prevented(persistent_prevented),
611                    reserved: [0x00, 0x00],
612                };
613
614                let header_size = self.iso_init_event_header(
615                    external_data,
616                    allocation_length,
617                    (size_of::<scsi::NotificationEventStatusHeader>()
618                        + size_of_val(&external_status)
619                        - size_of::<u16>()) as u16,
620                    false,
621                    scsi::NOTIFICATION_EXTERNAL_REQUEST_CLASS_EVENTS,
622                )?;
623                let body_size = std::cmp::min(
624                    size_of_val(&external_status),
625                    allocation_length - header_size,
626                );
627                external_data
628                    .subrange(header_size, external_data.len() - header_size)
629                    .writer()
630                    .write(&external_status.as_bytes()[..body_size])
631                    .map_err(ScsiDvdError::MemoryAccess)?;
632
633                header_size + body_size
634            } else if cdb.notification_class_request.multi_host() {
635                let header_size = self.iso_init_event_header(
636                    external_data,
637                    allocation_length,
638                    (size_of::<scsi::NotificationEventStatusHeader>()
639                        + size_of::<scsi::NotificationMultiHostStatus>()
640                        - size_of::<u16>()) as u16,
641                    false,
642                    scsi::NOTIFICATION_MULTI_HOST_CLASS_EVENTS,
643                )?;
644                let multi_host_status = scsi::NotificationMultiHostStatus {
645                    multi_host_event: scsi::NOTIFICATION_MULTI_HOST_EVENT_NO_CHANGE,
646                    flags: scsi::MultiHostStatusFlags::new()
647                        .with_multi_host_status(scsi::NOTIFICATION_MULTI_HOST_STATUS_READY)
648                        .with_reserved2(0x00)
649                        .with_persistent_prevented(self.media_state.lock().persistent),
650                    priority: 0.into(),
651                };
652                let body_size = std::cmp::min(
653                    size_of_val(&multi_host_status),
654                    allocation_length - header_size,
655                );
656                external_data
657                    .subrange(header_size, external_data.len() - header_size)
658                    .writer()
659                    .write(&multi_host_status.as_bytes()[..body_size])
660                    .map_err(ScsiDvdError::MemoryAccess)?;
661
662                header_size + body_size
663            } else if cdb.notification_class_request.media_status() {
664                let header_size = self.iso_init_event_header(
665                    external_data,
666                    allocation_length,
667                    (size_of::<scsi::NotificationEventStatusHeader>() + size_of_val(&media_status)
668                        - size_of::<u16>()) as u16,
669                    false,
670                    scsi::NOTIFICATION_MEDIA_STATUS_CLASS_EVENTS,
671                )?;
672                media_status
673                    .status_info
674                    .set_door_tray_open(self.media_state.lock().drive_state.tray_open());
675                media_status
676                    .status_info
677                    .set_media_present(self.media_state.lock().drive_state.medium_present());
678                let datab: &[u8] = media_status.as_bytes();
679                let body_size =
680                    std::cmp::min(size_of_val(&media_status), allocation_length - header_size);
681                external_data
682                    .subrange(header_size, external_data.len() - header_size)
683                    .writer()
684                    .write(&datab[..body_size])
685                    .map_err(ScsiDvdError::MemoryAccess)?;
686                header_size + body_size
687            } else if cdb.notification_class_request.device_busy() {
688                let header_size = self.iso_init_event_header(
689                    external_data,
690                    allocation_length,
691                    (size_of::<scsi::NotificationEventStatusHeader>()
692                        + size_of::<scsi::NotificationBusyStatus>()
693                        - size_of::<u16>()) as u16,
694                    false,
695                    scsi::NOTIFICATION_DEVICE_BUSY_CLASS_EVENTS,
696                )?;
697                let data = scsi::NotificationBusyStatus {
698                    device_busy_event: scsi::NOTIFICATION_BUSY_EVENT_NO_EVENT,
699                    device_busy_status: scsi::NOTIFICATION_BUSY_STATUS_NO_EVENT,
700                    time: 0.into(),
701                };
702                let body_size = std::cmp::min(size_of_val(&data), allocation_length - header_size);
703                external_data
704                    .subrange(header_size, external_data.len() - header_size)
705                    .writer()
706                    .write(&data.as_bytes()[..body_size])
707                    .map_err(ScsiDvdError::MemoryAccess)?;
708
709                header_size + body_size
710            } else {
711                self.iso_init_event_header(
712                    external_data,
713                    allocation_length,
714                    (size_of::<scsi::NotificationEventStatusHeader>() - size_of::<u16>()) as u16,
715                    false,
716                    scsi::NOTIFICATION_NO_CLASS_EVENTS,
717                )?
718            }
719        };
720
721        Ok(data_transfer_length)
722    }
723
724    fn handle_get_configuration_iso(
725        &self,
726        external_data: &RequestBuffers<'_>,
727        request: &Request,
728    ) -> Result<usize, ScsiDvdError> {
729        let cdb = scsi::CdbGetConfiguration::read_from_prefix(&request.cdb[..])
730            .unwrap()
731            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
732        let request_type = cdb.flags.request_type();
733        let starting_feature = cdb.starting_feature.get() as usize;
734        let allocation_length = cdb.allocation_length.get() as usize;
735        let mut feature_size: usize = 0;
736
737        if allocation_length > external_data.len() {
738            return Err(ScsiDvdError::DataOverrun);
739        }
740        let mut bytes_used =
741            std::cmp::min(allocation_length, size_of::<scsi::GetConfigurationHeader>());
742        let header_size = bytes_used;
743        let mut bytes_req = size_of::<scsi::GetConfigurationHeader>();
744        match request_type {
745            scsi::RequestType::ALL => {
746                // Return all the Feature Descriptors Supported
747                for i in 0..scsi::LIST_OF_FEATURES.len() {
748                    if (scsi::LIST_OF_FEATURES[i] as usize) >= starting_feature {
749                        bytes_used += self.iso_get_feature_page(
750                            &external_data.subrange(bytes_used, external_data.len() - bytes_used),
751                            allocation_length - bytes_used,
752                            scsi::LIST_OF_FEATURES[i],
753                            false,
754                            &mut feature_size,
755                        )?;
756                        bytes_req += feature_size;
757                    }
758                }
759
760                // data_length field indicates the amount of data available given a sufficient allocation length
761                // following this field. Thus the size of itself should be excluded.
762                self.iso_init_configuration_header(
763                    &external_data.subrange(0, header_size),
764                    bytes_req,
765                )?;
766            }
767            scsi::RequestType::CURRENT => {
768                // Return all the Feature Descriptors Supported
769                for i in 0..scsi::LIST_OF_FEATURES.len() {
770                    if (scsi::LIST_OF_FEATURES[i] as usize) >= starting_feature {
771                        bytes_used += self.iso_get_feature_page(
772                            &external_data.subrange(bytes_used, external_data.len() - bytes_used),
773                            allocation_length - bytes_used,
774                            scsi::LIST_OF_FEATURES[i],
775                            true,
776                            &mut feature_size,
777                        )?;
778                        bytes_req += feature_size;
779                    }
780                }
781
782                // data_length field indicates the amount of data available given a sufficient allocation length
783                // following this field. Thus the size of itself should be excluded.
784                self.iso_init_configuration_header(
785                    &external_data.subrange(0, header_size),
786                    bytes_req,
787                )?;
788            }
789
790            scsi::RequestType::ONE => {
791                // Return only the Feature Descriptor that has been requested
792                bytes_used += self.iso_get_feature_page(
793                    &external_data.subrange(bytes_used, external_data.len() - bytes_used),
794                    allocation_length - bytes_used,
795                    scsi::FeatureNumber::try_from(starting_feature).unwrap(),
796                    false,
797                    &mut feature_size,
798                )?;
799
800                bytes_req += feature_size;
801
802                self.iso_init_configuration_header(
803                    &external_data.subrange(0, header_size),
804                    bytes_req,
805                )?;
806            }
807            _ => return Err(ScsiDvdError::IllegalRequestNoSenseData),
808        }
809
810        Ok(bytes_used)
811    }
812
813    fn handle_read_capacity_iso(
814        &self,
815        media: &Media,
816        external_data: &RequestBuffers<'_>,
817    ) -> Result<usize, ScsiDvdError> {
818        let tx = size_of::<scsi::ReadCapacityData>();
819
820        // media is no longer accessible
821        let disk = self.loaded_disk(media)?;
822
823        let last_lba = std::cmp::min(iso_sector_count(disk) - 1, u32::MAX.into());
824        let data = scsi::ReadCapacityData {
825            logical_block_address: (last_lba as u32).into(),
826            bytes_per_block: ISO_SECTOR_SIZE.into(),
827        };
828
829        external_data
830            .writer()
831            .write(&data.as_bytes()[..tx])
832            .map_err(ScsiDvdError::MemoryAccess)?;
833
834        Ok(tx)
835    }
836
837    fn handle_read_toc(
838        &self,
839        media: &Media,
840        external_data: &RequestBuffers<'_>,
841        request: &Request,
842    ) -> Result<usize, ScsiDvdError> {
843        let cdb = scsi::CdbReadToc::read_from_prefix(&request.cdb[..])
844            .unwrap()
845            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
846        let allocation_length = cdb.allocation_length.get() as usize;
847        let format = cdb.format2 & 0x0f;
848        let msf = cdb.flag1.msf();
849        let mut formatted_toc = scsi::ReadTocFormattedToc {
850            length: 0x0802.into(),
851            first_complete_session: 0x01,
852            last_complete_session: 0x01,
853            track1: scsi::TrackData {
854                reserved: 0x00,
855                flag: scsi::TrackDataFlag::new().with_control(0x4).with_adr(0x1),
856                track_number: 0x01,
857                reserved1: 0x00,
858                address: [0; 4],
859            },
860            trackaa: scsi::TrackData {
861                reserved: 0x00,
862                flag: scsi::TrackDataFlag::new().with_control(0x4).with_adr(0x1),
863                track_number: 0xaa,
864                reserved1: 0x00,
865                address: [0; 4],
866            },
867        };
868        let mut session_data = scsi::CdromTocSessionData {
869            length: 0x000a.into(),
870            first_complete_session: 0x01,
871            last_complete_session: 0x01,
872            track_data: scsi::TrackData {
873                reserved: 0x00,
874                flag: scsi::TrackDataFlag::new().with_control(0x4).with_adr(0x1),
875                track_number: 0x01,
876                reserved1: 0x00,
877                address: [0; 4],
878            },
879        };
880        let data_transfer_length: usize;
881
882        let disk = self.loaded_disk(media)?;
883
884        let last_lba = std::cmp::min(iso_sector_count(disk) - 1, u32::MAX.into());
885        if allocation_length > external_data.len() {
886            return Err(ScsiDvdError::DataOverrun);
887        }
888        match format {
889            scsi::CDROM_READ_TOC_EX_FORMAT_TOC => {
890                if msf {
891                    formatted_toc.track1.address = [0x00, 0x00, 0x02, 0x00];
892                    formatted_toc.trackaa.address = [
893                        0x00,
894                        (((last_lba + 150) / 75) / 60) as u8,
895                        (((last_lba + 150) / 75) % 60) as u8,
896                        ((last_lba + 150) % 75) as u8,
897                    ]
898                } else {
899                    formatted_toc.track1.address = [0x00, 0x00, 0x00, 0x00];
900                    formatted_toc.trackaa.address = [
901                        (last_lba >> 24) as u8,
902                        (last_lba >> 16) as u8,
903                        (last_lba >> 8) as u8,
904                        last_lba as u8,
905                    ]
906                }
907                data_transfer_length =
908                    std::cmp::min(allocation_length, size_of::<scsi::ReadTocFormattedToc>());
909                external_data
910                    .writer()
911                    .write(&formatted_toc.as_bytes()[..data_transfer_length])
912                    .map_err(ScsiDvdError::MemoryAccess)?;
913            }
914            scsi::CDROM_READ_TOC_EX_FORMAT_SESSION => {
915                if msf {
916                    session_data.track_data.address = [0x00, 0x00, 0x02, 0x00];
917                } else {
918                    session_data.track_data.address = [0x00, 0x00, 0x00, 0x00];
919                }
920                data_transfer_length =
921                    std::cmp::min(allocation_length, size_of::<scsi::CdromTocSessionData>());
922                external_data
923                    .writer()
924                    .write(&session_data.as_bytes()[..data_transfer_length])
925                    .map_err(ScsiDvdError::MemoryAccess)?;
926            }
927            _ => {
928                return Err(ScsiDvdError::IllegalRequest(
929                    AdditionalSenseCode::INVALID_CDB,
930                    0x00,
931                ));
932            }
933        }
934        Ok(data_transfer_length)
935    }
936
937    async fn handle_start_stop_unit(&self, request: &Request) -> Result<usize, ScsiDvdError> {
938        let cdb = scsi::StartStop::read_from_prefix(&request.cdb[..])
939            .unwrap()
940            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
941        let start = cdb.flag.start();
942        let load_eject = cdb.flag.load_eject();
943
944        match (load_eject, start) {
945            (false, false) => (), // stop the disc, do nothing here
946            (false, true) => (),  // start the disc and make ready for access, do nothing here
947            (true, false) => {
948                let mut previous_media = None;
949                {
950                    // Take `media` before `media_state`, as `change_media` does.
951                    let mut media = self.media.write();
952                    let mut media_state = self.media_state.lock();
953                    // eject the disc if permitted
954                    if !media_state.prevent {
955                        if media_state.drive_state == DriveState::MediumPresentTrayClosed {
956                            // This will cause the next GESN or TUR command to report medium removal
957                            media_state.pending_medium_event = IsoMediumEvent::MediaToNoMedia;
958
959                            previous_media = Some(std::mem::replace(&mut *media, Media::Unloaded));
960
961                            tracing::debug!("handling guest initiated eject");
962                        }
963
964                        media_state.drive_state = DriveState::MediumNotPresentTrayOpen;
965                    } else if media_state.drive_state.medium_present() {
966                        return Err(ScsiDvdError::IllegalRequest(
967                            AdditionalSenseCode::MEDIUM_REMOVAL_PREVENTED,
968                            0x02,
969                        ));
970                    } else {
971                        return Err(ScsiDvdError::SenseNotReady(
972                            AdditionalSenseCode::MEDIUM_REMOVAL_PREVENTED,
973                            0x02,
974                        ));
975                    }
976                }
977                if let Some(media) = previous_media {
978                    if let Media::Loaded(disk) = media {
979                        if let Err(e) = disk.eject().await {
980                            tracelimit::error_ratelimited!(error = ?e, "eject error");
981                        } else {
982                            tracing::debug!("guest initiated eject complete");
983                        }
984                    } else {
985                        tracelimit::warn_ratelimited!("attempted to eject unloaded media");
986                    }
987                }
988            }
989            (true, true) => {
990                let mut media_state = self.media_state.lock();
991                if media_state.drive_state.tray_open() {
992                    // Once the drive is ejected through SCSI, the media is permanently removed.
993                    media_state.drive_state = DriveState::MediumNotPresentTrayClosed;
994                }
995            }
996        }
997
998        Ok(0)
999    }
1000
1001    fn handle_request_sense_iso(
1002        &self,
1003        external_data: &RequestBuffers<'_>,
1004        request: &Request,
1005    ) -> Result<usize, ScsiDvdError> {
1006        let cdb = scsi::CdbRequestSense::read_from_prefix(&request.cdb[..])
1007            .unwrap()
1008            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
1009        let allocation_length = cdb.allocation_length as usize;
1010        let new_sense_data =
1011            SenseData::new(SenseKey::NO_SENSE, AdditionalSenseCode::NO_SENSE, 0x00);
1012
1013        self.sense_data.set(Some(&new_sense_data));
1014
1015        if external_data.len() < allocation_length {
1016            Err(ScsiDvdError::DataOverrun)
1017        } else {
1018            let tx = std::cmp::min(allocation_length, size_of::<SenseData>());
1019            external_data
1020                .writer()
1021                .write(&new_sense_data.as_bytes()[..tx])
1022                .map_err(ScsiDvdError::MemoryAccess)?;
1023            Ok(tx)
1024        }
1025    }
1026
1027    fn handle_mode_sense_iso(
1028        &self,
1029        external_data: &RequestBuffers<'_>,
1030        request: &Request,
1031    ) -> Result<usize, ScsiDvdError> {
1032        let cdb = scsi::ModeSense10::read_from_prefix(&request.cdb[..])
1033            .unwrap()
1034            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
1035        let page_code = cdb.flags2.page_code();
1036        let allocation_length = cdb.allocation_length.get() as usize;
1037        let pc = cdb.flags2.pc() << 6;
1038
1039        let mut bytes_used = std::cmp::min(allocation_length, super::MODE_PARAMETER_HEADER10_SIZE);
1040        let buffer_size_header = bytes_used;
1041        let mut bytes_required = super::MODE_PARAMETER_HEADER10_SIZE as u16;
1042        let mut mode_page_size: u16 = 0;
1043
1044        if external_data.len() < allocation_length {
1045            return Err(ScsiDvdError::DataOverrun);
1046        }
1047
1048        if pc == scsi::MODE_SENSE_SAVED_VALUES {
1049            return Err(ScsiDvdError::IllegalRequest(
1050                AdditionalSenseCode::SAVING_PARAMETER_NOT_SUPPORTED,
1051                0,
1052            ));
1053        }
1054
1055        // Copy as much data from the mode page table as the remaining buffer.
1056        // If remaining buffer is big enough to copy the whole page, copy
1057        // the whole page length.
1058        match page_code {
1059            scsi::MODE_PAGE_ERROR_RECOVERY
1060            | scsi::MODE_PAGE_POWER_CONDITION
1061            | scsi::MODE_PAGE_CDVD_INACTIVITY => {
1062                bytes_used += self
1063                    .iso_get_mode_page(
1064                        &external_data.subrange(bytes_used, external_data.len() - bytes_used),
1065                        allocation_length - bytes_used,
1066                        page_code,
1067                        &mut mode_page_size,
1068                    )
1069                    .unwrap();
1070                bytes_required += mode_page_size;
1071                self.iso_init_mode_sense_header(
1072                    &external_data.subrange(0, super::MODE_PARAMETER_HEADER10_SIZE),
1073                    allocation_length,
1074                    bytes_required,
1075                )?;
1076                Ok(bytes_used)
1077            }
1078            scsi::MODE_SENSE_RETURN_ALL => {
1079                for i in 0..scsi::LIST_OF_MODE_PAGES.len() {
1080                    bytes_used += self
1081                        .iso_get_mode_page(
1082                            &external_data.subrange(bytes_used, external_data.len() - bytes_used),
1083                            allocation_length - bytes_used,
1084                            scsi::LIST_OF_MODE_PAGES[i],
1085                            &mut mode_page_size,
1086                        )
1087                        .unwrap();
1088                    bytes_required += mode_page_size;
1089                }
1090                self.iso_init_mode_sense_header(
1091                    &external_data.subrange(0, buffer_size_header),
1092                    allocation_length,
1093                    bytes_required,
1094                )?;
1095                Ok(bytes_used)
1096            }
1097            _ => Err(ScsiDvdError::IllegalRequest(
1098                AdditionalSenseCode::INVALID_CDB,
1099                0,
1100            )),
1101        }
1102    }
1103
1104    fn handle_medium_removal_iso(&self, request: &Request) -> Result<usize, ScsiDvdError> {
1105        let cdb = scsi::CdbMediaRemoval::read_from_prefix(&request.cdb[..])
1106            .unwrap()
1107            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
1108
1109        // prevent/allow media removal based on the Persistent/Prevent bits
1110        let mut media_state = self.media_state.lock();
1111        media_state.persistent = cdb.flags.persistent();
1112        media_state.prevent = cdb.flags.prevent();
1113        Ok(0)
1114    }
1115
1116    fn handle_mode_select_iso(
1117        &self,
1118        request: &Request,
1119        external_data: &RequestBuffers<'_>,
1120    ) -> Result<usize, ScsiDvdError> {
1121        let cdb = scsi::ModeSelect10::read_from_prefix(&request.cdb[..])
1122            .unwrap()
1123            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
1124
1125        let sp_bit = cdb.flags.spbit();
1126        let request_length = cdb.parameter_list_length.get() as usize;
1127        if request_length == 0 {
1128            return Ok(0);
1129        }
1130
1131        if request_length > external_data.len() {
1132            return Err(ScsiDvdError::DataOverrun);
1133        }
1134
1135        // If the parameter list length results in the truncation of any mode parameter header,
1136        // mode parameter block descriptor(s), or mode page, then the command shall be terminated
1137        // with CHECK CONDITION status, with the sense key set to ILLEGAL REQUEST, and the
1138        // additional sense code set to PARAMETER LIST LENGTH ERROR.
1139        if request_length < super::MODE_PARAMETER_HEADER10_SIZE {
1140            return Err(ScsiDvdError::IllegalRequest(
1141                AdditionalSenseCode::PARAMETER_LIST_LENGTH,
1142                0x00,
1143            ));
1144        }
1145
1146        // Don't support saving pages.
1147        if sp_bit {
1148            return Err(ScsiDvdError::IllegalRequest(
1149                AdditionalSenseCode::INVALID_CDB,
1150                0x00,
1151            ));
1152        }
1153
1154        if request_length == super::MODE_PARAMETER_HEADER10_SIZE {
1155            return Ok(0);
1156        }
1157
1158        // Parse pages.
1159        // All 3 mode pages supported have the same length
1160        if request_length
1161            < super::MODE_PARAMETER_HEADER10_SIZE + size_of::<scsi::ModeReadWriteRecoveryPage>()
1162        {
1163            return Err(ScsiDvdError::IllegalRequest(
1164                AdditionalSenseCode::PARAMETER_LIST_LENGTH,
1165                0x00,
1166            ));
1167        }
1168
1169        let mut buffer: Vec<u8> = vec![0; request_length];
1170        external_data
1171            .reader()
1172            .read(&mut buffer)
1173            .map_err(ScsiDvdError::MemoryAccess)?;
1174
1175        let mode_page_error_recovery = scsi::ModeReadWriteRecoveryPage::read_from_prefix(
1176            &buffer[super::MODE_PARAMETER_HEADER10_SIZE
1177                ..super::MODE_PARAMETER_HEADER10_SIZE
1178                    + size_of::<scsi::ModeReadWriteRecoveryPage>()],
1179        )
1180        .unwrap()
1181        .0; // TODO: zerocopy: from-prefix (read_from_prefix): use-rest-of-range, zerocopy: err (https://github.com/microsoft/openvmm/issues/759)
1182        match mode_page_error_recovery.page_code {
1183            scsi::MODE_PAGE_ERROR_RECOVERY => {
1184                // ModePageErrorRecovery = (PMODE_READ_WRITE_RECOVERY_PAGE) (Buffer + sizeof (MODE_PARAMETER_HEADER10));
1185
1186                // parse Read/Write error recovery mode page
1187                Ok(0)
1188            }
1189            scsi::MODE_PAGE_POWER_CONDITION => {
1190                // ModePagePowerCondition = (PPOWER_CONDITION_PAGE) (Buffer + sizeof (MODE_PARAMETER_HEADER10));
1191
1192                // parse power condition mode page
1193                Ok(0)
1194            }
1195            scsi::MODE_PAGE_CDVD_INACTIVITY => {
1196                // ModePageTimeoutProtect = (PMODE_SENSE_MODE_PAGE_TIMEOUT_PROTECT) (Buffer + sizeof (MODE_PARAMETER_HEADER10));
1197
1198                // parse timeout and protect mode page
1199                Ok(0)
1200            }
1201            _ => Err(ScsiDvdError::IllegalRequestNoSenseData),
1202        }
1203    }
1204
1205    fn handle_read_track_information_iso(
1206        &self,
1207        media: &Media,
1208        external_data: &RequestBuffers<'_>,
1209        request: &Request,
1210    ) -> Result<usize, ScsiDvdError> {
1211        let cdb = scsi::CdbReadTrackInformation::read_from_prefix(&request.cdb[..])
1212            .unwrap()
1213            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
1214        let number_type = cdb.flag.number_type();
1215        let open = cdb.flag.open();
1216        let logical_track_number = cdb.logical_track_number.get() as usize;
1217        let allocation_length = cdb.allocation_length.get() as usize;
1218
1219        let disk = self.loaded_disk(media)?;
1220        let last_lba = std::cmp::min(iso_sector_count(disk) - 1, u32::MAX.into()) as u32;
1221
1222        if allocation_length > external_data.len() {
1223            return Err(ScsiDvdError::DataOverrun);
1224        }
1225
1226        // If it is not possible for the currently mounted disc to have open tracks, and Open is set to one,
1227        // then the command shall be terminated with CHECK CONDITION status and sense bytes SK/ASC/ASCQ
1228        // shall be set to ILLEGAL REQUEST/ INVALID FIELD IN CDB.
1229        if open {
1230            return Err(ScsiDvdError::IllegalRequest(
1231                AdditionalSenseCode::INVALID_CDB,
1232                0x00,
1233            ));
1234        }
1235
1236        match number_type {
1237            0x0 => {
1238                // MAX = Last Possible Lead-out Start Address as returned by the READ DISC INFORMATION
1239                // command (0x00). If LBA >= MAX, the command shall be terminated with CHECK CONDITION status
1240                // and sense bytes SK/ASC/ ASCQ shall be set to ILLEGAL REQUEST/LOGICAL BLOCK ADDRESS OUT OF RANGE.
1241                return Err(ScsiDvdError::IllegalRequest(
1242                    AdditionalSenseCode::ILLEGAL_BLOCK,
1243                    0x00,
1244                ));
1245            }
1246            0x1 => {
1247                if logical_track_number != 1 {
1248                    // If the currently mounted disc is not CD, the command shall be terminated with CHECK CONDITION
1249                    // status and sense bytes SK/ASC/ASCQ shall be set to ILLEGAL REQUEST/INVALID FIELD IN CDB
1250                    //
1251                    // If TM is the Last Track Number in the Last Session as returned in READ DISC INFORMATION command
1252                    // Standard Disc Information. If LTN > TM, the command shall be terminated with CHECK CONDITION status
1253                    // and sense bytes SK/ASC/ASCQ shall be set to ILLEGAL REQUEST/INVALID FIELD IN CDB.
1254                    return Err(ScsiDvdError::IllegalRequest(
1255                        AdditionalSenseCode::INVALID_CDB,
1256                        0x00,
1257                    ));
1258                }
1259            }
1260            0x2 => {
1261                // SM is the Number of Sessions as returned by the READ DISC INFORMATION command. If LogicalTrackNumber > SM,
1262                // the command shall be terminated with CHECK CONDITION status and sense bytes SK/ASC/ASCQ shall be set to
1263                // ILLEGAL REQUEST/INVALID FIELD IN CDB.
1264                if logical_track_number != 1 {
1265                    return Err(ScsiDvdError::IllegalRequest(
1266                        AdditionalSenseCode::INVALID_CDB,
1267                        0x00,
1268                    ));
1269                }
1270            }
1271            _ => {
1272                return Err(ScsiDvdError::IllegalRequestNoSenseData);
1273            }
1274        }
1275        // Fill in logical track size
1276        let track_information = scsi::TrackInformation3 {
1277            length: 0x002e.into(),
1278            track_number_lsb: 0x01,
1279            session_number_lsb: 0x01,
1280            reserved: 0x00,
1281            track_mode: 0x04,
1282            /*
1283               UCHAR DataMode      : 4 = 0x1;
1284               UCHAR FixedPacket   : 1 = 0x0;
1285               UCHAR Packet        : 1 = 0x1;
1286               UCHAR Blank         : 1 = 0x0;
1287               UCHAR ReservedTrack : 1 = 0x0;
1288            */
1289            data_mode: 0b00100001,
1290            track_size: last_lba.into(),
1291            ..FromZeros::new_zeroed()
1292        };
1293        let tx = std::cmp::min(allocation_length, size_of::<scsi::TrackInformation3>());
1294        external_data
1295            .writer()
1296            .write(&track_information.as_bytes()[..tx])
1297            .map_err(ScsiDvdError::MemoryAccess)?;
1298        Ok(tx)
1299    }
1300
1301    fn handle_read_dvd_structure(
1302        &self,
1303        external_data: &RequestBuffers<'_>,
1304        request: &Request,
1305    ) -> Result<usize, ScsiDvdError> {
1306        let cdb = scsi::CdbReadDVDStructure::read_from_prefix(&request.cdb[..])
1307            .unwrap()
1308            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
1309        let media_type = cdb.media_type;
1310        let layer = cdb.layer;
1311        let allocation_length = cdb.allocation_length.get() as usize;
1312
1313        self.validate_media_for_read()?;
1314
1315        if allocation_length > external_data.len() {
1316            return Err(ScsiDvdError::DataOverrun);
1317        }
1318
1319        // only single layer DVD media type is supported
1320        if media_type != 0 {
1321            return Err(ScsiDvdError::IllegalRequest(
1322                AdditionalSenseCode::INVALID_MEDIA,
1323                scsi::SCSI_SENSEQ_INCOMPATIBLE_FORMAT,
1324            ));
1325        }
1326
1327        if layer != 0 {
1328            return Err(ScsiDvdError::IllegalRequestNoSenseData);
1329        }
1330
1331        match cdb.format {
1332            scsi::DVD_FORMAT_LEAD_IN => {
1333                let tx = std::cmp::min(
1334                    allocation_length,
1335                    size_of::<scsi::ReadDVDStructurePhysicalFormatInformation>(),
1336                );
1337                let data = scsi::ReadDVDStructurePhysicalFormatInformation {
1338                    length: 0x802.into(),
1339                    reserved: [0x00, 0x00],
1340                    reserved2: 0x00,    // Part Version = 0 & Disk Category = DVD-ROM
1341                    maximum_rate: 0x04, // Maximum Rate = 30.24 Mbps & Disc Size = 120 mm,
1342                    /*
1343                        Layer Type = layer contains embossed data
1344                        Track = PTP
1345                        Number of Layers = 1
1346                        Reserved
1347                    */
1348                    layer: 0x00,
1349                    reserved3: 0x00, // Track Density = 0.74 um/track & Linear Density = 0.267 um/bit,
1350                    reserved4: 0x00,
1351                    starting_physical_sector: [0x03, 0x00, 0x00],
1352                    reserved5: 0x00,
1353                    end_physical_sector: [0x00, 0x00, 0x00],
1354                    reserved6: 0x00,
1355                    end_physical_sector_in_layer0: [0x00, 0x00, 0x00],
1356                    bca: 0x00,
1357                };
1358                external_data
1359                    .writer()
1360                    .write(&data.as_bytes()[..tx])
1361                    .map_err(ScsiDvdError::MemoryAccess)?;
1362                Ok(tx)
1363            }
1364            scsi::DVD_FORMAT_COPYRIGHT => {
1365                let tx = std::cmp::min(
1366                    allocation_length,
1367                    size_of::<scsi::ReadDVDStructureCopyrightInformation>(),
1368                );
1369                let data = scsi::ReadDVDStructureCopyrightInformation {
1370                    data_length: 0x0006.into(),
1371                    reserved: 0x00,
1372                    copyright_protection_system: 0x00,
1373                    region_management_information: 0x00,
1374                    reserved2: [0x00, 0x00],
1375                };
1376                external_data
1377                    .writer()
1378                    .write(&data.as_bytes()[..tx])
1379                    .map_err(ScsiDvdError::MemoryAccess)?;
1380                Ok(tx)
1381            }
1382            scsi::DVD_FORMAT_BCA => {
1383                // It is not mandatory for DVD players to support reading the BCA,
1384                // but DVD-ROM drives should according to the Mount Fuji specification.
1385                // However, if a DVD media does not have BCA, the command should be terminated.
1386                Err(ScsiDvdError::IllegalRequestNoSenseData)
1387            }
1388            scsi::DVD_FORMAT_MANUFACTURING => {
1389                let tx = std::cmp::min(
1390                    allocation_length,
1391                    size_of::<scsi::ReadDVDStructureManufacturingStructure>(),
1392                );
1393                let data = scsi::ReadDVDStructureManufacturingStructure {
1394                    data_length: 0x0802.into(),
1395                    reserved: [0x00, 0x00],
1396                };
1397                external_data
1398                    .writer()
1399                    .write(&data.as_bytes()[..tx])
1400                    .map_err(ScsiDvdError::MemoryAccess)?;
1401                Ok(tx)
1402            }
1403            _ => Err(ScsiDvdError::IllegalRequest(
1404                AdditionalSenseCode::INVALID_CDB,
1405                0x00,
1406            )),
1407        }
1408    }
1409
1410    fn handle_get_performance(
1411        &self,
1412        media: &Media,
1413        external_data: &RequestBuffers<'_>,
1414        request: &Request,
1415    ) -> Result<usize, ScsiDvdError> {
1416        let cdb = scsi::CdbGetPerformance::read_from_prefix(&request.cdb[..])
1417            .unwrap()
1418            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
1419        let data_type = cdb.data_type;
1420        let write = cdb.flags.write();
1421        let tolerance = cdb.flags.tolerance();
1422        let except = cdb.flags.except();
1423        let mut nominal_performance = scsi::GetPerformanceNominalPerformanceDescriptor {
1424            start_lba: 0.into(),
1425            start_performance: scsi::PERFORMANCE_1000_BYTES_PER_SECOND.into(),
1426            end_lba: 0.into(),
1427            end_performance: scsi::PERFORMANCE_1000_BYTES_PER_SECOND.into(),
1428        };
1429
1430        let maximum_number_of_descriptors = cdb.maximum_number_of_descriptors.get();
1431        let mut data_transfer_length: u64;
1432
1433        let disk = self.loaded_disk(media)?;
1434
1435        let last_lba = std::cmp::min(iso_sector_count(disk) - 1, u32::MAX.into())
1436            .try_into()
1437            .expect("last_lba must be u32");
1438        match data_type {
1439            scsi::PERFORMANCE_TYPE_PERFORMANCE_DATA => {
1440                // only read performance data will be returned
1441                // 0x2 is the only defined tolerance value
1442                if write || (tolerance != 0x2) {
1443                    return Err(ScsiDvdError::IllegalRequestNoSenseData);
1444                }
1445                match except {
1446                    scsi::PERFORMANCE_EXCEPT_NOMINAL_PERFORMANCE => {
1447                        // Patch the end lba
1448                        nominal_performance.end_lba.set(last_lba);
1449                        // The Performance Data Length field shall specify the amount of result data excluding
1450                        // the Performance Data Length itself
1451                        let header_size = self.iso_init_performance_header(
1452                            external_data,
1453                            external_data.len().try_into().unwrap(),
1454                            (size_of::<scsi::GetPerformanceHeader>()
1455                                + size_of::<scsi::GetPerformanceNominalPerformanceDescriptor>()
1456                                - size_of::<u64>())
1457                            .try_into()
1458                            .unwrap(),
1459                            0,
1460                        )?;
1461                        data_transfer_length = header_size.try_into().unwrap();
1462                        if maximum_number_of_descriptors >= 1 {
1463                            let body_size = std::cmp::min(
1464                                external_data.len() - header_size,
1465                                size_of::<scsi::GetPerformanceNominalPerformanceDescriptor>(),
1466                            );
1467                            external_data
1468                                .subrange(header_size, external_data.len() - header_size)
1469                                .writer()
1470                                .write(&nominal_performance.as_bytes()[..body_size])
1471                                .map_err(ScsiDvdError::MemoryAccess)?;
1472                            data_transfer_length += body_size as u64;
1473                        }
1474                    }
1475                    scsi::PERFORMANCE_EXCEPT_ENTIRE_PERFORMANCE_LIST
1476                    | scsi::PERFORMANCE_EXCEPT_PERFORMANCE_EXCEPTIONS_ONLY => {
1477                        // The Performance Data Length field shall specify the amount of result data excluding
1478                        // the Performance Data Length itself
1479                        let header_size = self.iso_init_performance_header(
1480                            external_data,
1481                            external_data.len().try_into().unwrap(),
1482                            (size_of::<scsi::GetPerformanceHeader>() - size_of::<u64>())
1483                                .try_into()
1484                                .unwrap(),
1485                            1,
1486                        )?;
1487                        data_transfer_length = header_size.try_into().unwrap();
1488                    }
1489                    _ => {
1490                        return Err(ScsiDvdError::IllegalRequestNoSenseData);
1491                    }
1492                }
1493            }
1494            _ => {
1495                // don't support all other types
1496                return Err(ScsiDvdError::IllegalRequest(
1497                    AdditionalSenseCode::INVALID_CDB,
1498                    0x00,
1499                ));
1500            }
1501        }
1502        Ok(data_transfer_length as usize)
1503    }
1504
1505    fn handle_mechanism_status(
1506        &self,
1507        external_data: &RequestBuffers<'_>,
1508        request: &Request,
1509    ) -> Result<usize, ScsiDvdError> {
1510        let cdb = scsi::CdbMechStatus::read_from_prefix(&request.cdb[..])
1511            .unwrap()
1512            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
1513        let allocation_length = cdb.allocation_length.get() as usize;
1514
1515        if allocation_length > external_data.len() {
1516            return Err(ScsiDvdError::DataOverrun);
1517        }
1518
1519        // copy the standard header
1520        // since the device is a DVD-ROM, not a medium changer, no slot table will be returned
1521        let mechanism_status_header: scsi::MechanismStatusHeader = scsi::MechanismStatusHeader {
1522            flags: scsi::MechanismStatusHeaderFlags::new()
1523                .with_door_open(self.media_state.lock().drive_state.tray_open()),
1524            ..FromZeros::new_zeroed()
1525        };
1526        let tx = std::cmp::min(allocation_length, size_of::<scsi::MechanismStatusHeader>());
1527        external_data
1528            .writer()
1529            .write(&mechanism_status_header.as_bytes()[..tx])
1530            .map_err(ScsiDvdError::MemoryAccess)?;
1531
1532        Ok(tx)
1533    }
1534
1535    fn handle_read_buffer_capacity(
1536        &self,
1537        external_data: &RequestBuffers<'_>,
1538        request: &Request,
1539    ) -> Result<usize, ScsiDvdError> {
1540        let cdb = scsi::CdbReadBufferCapacity::read_from_prefix(&request.cdb[..])
1541            .unwrap()
1542            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
1543        let block_info = cdb.flags.block_info();
1544        let allocation_length = cdb.allocation_length.get() as usize;
1545
1546        if allocation_length > external_data.len() {
1547            return Err(ScsiDvdError::DataOverrun);
1548        }
1549
1550        let tx = std::cmp::min(allocation_length, size_of::<scsi::ReadBufferCapacityData>());
1551
1552        let data = scsi::ReadBufferCapacityData {
1553            data_length: (size_of::<scsi::ReadBufferCapacityData>() as u16 - 2).into(),
1554            block_data_returned: block_info as u8,
1555            ..FromZeros::new_zeroed()
1556        };
1557
1558        external_data
1559            .writer()
1560            .write(&data.as_bytes()[..tx])
1561            .map_err(ScsiDvdError::MemoryAccess)?;
1562
1563        Ok(tx)
1564    }
1565
1566    fn handle_read_disc_information(
1567        &self,
1568        external_data: &RequestBuffers<'_>,
1569        request: &Request,
1570    ) -> Result<usize, ScsiDvdError> {
1571        let cdb = scsi::CdbReadDiscInformation::read_from_prefix(&request.cdb[..])
1572            .unwrap()
1573            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
1574        let data_type = cdb.flags.data_type();
1575        let allocation_length = cdb.allocation_length.get() as usize;
1576
1577        self.validate_media_for_read()?;
1578        if allocation_length > external_data.len() {
1579            return Err(ScsiDvdError::DataOverrun);
1580        }
1581
1582        // only standard disc information is supported
1583        if data_type != 0x0 {
1584            return Err(ScsiDvdError::IllegalRequest(
1585                AdditionalSenseCode::INVALID_CDB,
1586                0x00,
1587            ));
1588        }
1589
1590        let tx = std::cmp::min(allocation_length, size_of::<scsi::DiscInformation>());
1591        let data = scsi::DiscInformation {
1592            length: 0x0020.into(),
1593            flags1: scsi::DiscInfoFlags1::new()
1594                .with_disc_status(0x2)
1595                .with_last_session_status(0x3)
1596                .with_erasable(false)
1597                .with_reserved1(0x0),
1598            first_track_number: 0x01,
1599            number_of_sessions_lsb: 0x01,
1600            last_session_first_track_lsb: 0x01,
1601            last_session_last_track_lsb: 0x01,
1602            flags2: scsi::DiscInfoFlags2::new()
1603                .with_mrw_status(0)
1604                .with_mrw_dirty_bit(false)
1605                .with_reserved2(0)
1606                .with_uru(true)
1607                .with_dbc_v(false)
1608                .with_did_v(false),
1609            ..FromZeros::new_zeroed()
1610        };
1611        external_data
1612            .writer()
1613            .write(&data.as_bytes()[..tx])
1614            .map_err(ScsiDvdError::MemoryAccess)?;
1615
1616        Ok(tx)
1617    }
1618
1619    fn handle_set_streaming(
1620        &self,
1621        media: &Media,
1622        external_data: &RequestBuffers<'_>,
1623        request: &Request,
1624    ) -> Result<usize, ScsiDvdError> {
1625        let cdb = scsi::CdbSetStreaming::read_from_prefix(&request.cdb[..])
1626            .unwrap()
1627            .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
1628        let parameter_list_length = usize::from(cdb.parameter_list_length);
1629        let mut buffer = vec![0; parameter_list_length];
1630
1631        if parameter_list_length == 0 {
1632            return Ok(0);
1633        }
1634
1635        let disk = self.loaded_disk(media)?;
1636
1637        if parameter_list_length > external_data.len() {
1638            return Err(ScsiDvdError::DataOverrun);
1639        }
1640
1641        // If the Parameter List Length results in the truncation of Performance Descriptor,
1642        // the command shall be terminated with CHECK CONDITION status and sense bytes SK/ASC/ASCQ
1643        // shall be set to ILLEGAL REQUEST/PARAMETER LIST LENGTH ERROR.
1644        if parameter_list_length < size_of::<scsi::SetStreamingPerformanceDescriptor>() {
1645            return Err(ScsiDvdError::IllegalRequest(
1646                AdditionalSenseCode::PARAMETER_LIST_LENGTH,
1647                0x00,
1648            ));
1649        }
1650
1651        // process the command
1652        // just do sanity check, and success the command if nothing specified is wrong
1653        external_data
1654            .reader()
1655            .read(&mut buffer)
1656            .map_err(ScsiDvdError::MemoryAccess)?;
1657        let performance_descriptor =
1658            scsi::SetStreamingPerformanceDescriptor::read_from_prefix(&buffer[..])
1659                .unwrap()
1660                .0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
1661
1662        // If RDD bit is set to one, it shall indicate that the drive is to return to its
1663        // default performance settings and the remaining fields in this descriptor shall be ignored.
1664        if performance_descriptor.flags.rdd() {
1665            return Ok(0);
1666        }
1667        let last_lba = std::cmp::min(iso_sector_count(disk) - 1, u32::MAX.into()) as u32;
1668
1669        if u32::from(performance_descriptor.start_lba) > last_lba
1670            || u32::from(performance_descriptor.end_lba) > last_lba
1671        {
1672            return Err(ScsiDvdError::IllegalRequestNoSenseData);
1673        }
1674
1675        Ok(0)
1676    }
1677}
1678
1679impl SimpleScsiDvd {
1680    fn iso_init_event_header(
1681        &self,
1682        external_data: &RequestBuffers<'_>,
1683        buffer_size: usize,
1684        event_data_length: u16,
1685        nea: bool,
1686        notification_class: u8,
1687    ) -> Result<usize, ScsiDvdError> {
1688        let mut header: scsi::NotificationEventStatusHeader =
1689            scsi::NotificationEventStatusHeader::new_zeroed();
1690        header.event_data_length.set(event_data_length);
1691        header.flags.set_nea(nea);
1692        header.flags.set_notification_class(notification_class);
1693        header.supported_event_classes = scsi::NotificationEventClasses::new()
1694            .with_operational_change(true)
1695            .with_power_management(true)
1696            .with_external_request(true)
1697            .with_media_status(true)
1698            .with_multi_host(true)
1699            .with_device_busy(true);
1700        let tx: usize = std::cmp::min(
1701            size_of::<scsi::NotificationEventStatusHeader>(),
1702            buffer_size,
1703        );
1704        external_data
1705            .writer()
1706            .write(&header.as_bytes()[..tx])
1707            .map_err(ScsiDvdError::MemoryAccess)?;
1708        Ok(tx)
1709    }
1710
1711    fn iso_get_feature_page(
1712        &self,
1713        external_data: &RequestBuffers<'_>,
1714        buffer_size: usize,
1715        feature_code: scsi::FeatureNumber,
1716        current_only: bool,
1717        feature_size: &mut usize,
1718    ) -> Result<usize, ScsiDvdError> {
1719        let mut bytes_used: usize = 0;
1720        let mut profile_list = scsi::GetConfigurationFeatureDataProfileList {
1721            header: scsi::FeatureHeader {
1722                feature_code: (scsi::FeatureNumber::FeatureProfileList as u16).into(),
1723                flags: scsi::FeatureHeaderFlags::new()
1724                    .with_current(true)
1725                    .with_persistent(true)
1726                    .with_version(0)
1727                    .with_reserved(0),
1728                additional_length: (2 * (size_of::<scsi::FeatureDataProfileList>() as u8)),
1729            },
1730            profile: [
1731                scsi::FeatureDataProfileList {
1732                    profile_number: scsi::PROFILE_DVD_ROM.into(),
1733                    current: 0x01,
1734                    reserved: 0x00,
1735                },
1736                scsi::FeatureDataProfileList {
1737                    profile_number: scsi::PROFILE_CD_ROM.into(),
1738                    current: 0x00,
1739                    reserved: 0x00,
1740                },
1741            ],
1742        };
1743        let mut random_readable = scsi::FeatureDataRandomReadable {
1744            header: scsi::FeatureHeader {
1745                feature_code: (scsi::FeatureNumber::FeatureRandomReadable as u16).into(),
1746                flags: scsi::FeatureHeaderFlags::new()
1747                    .with_current(true)
1748                    .with_persistent(false)
1749                    .with_version(0)
1750                    .with_reserved(0),
1751                additional_length: 0x08,
1752            },
1753            logical_block_size: scsi::ISO_SECTOR_SIZE.into(),
1754            blocking: 16.into(),
1755            error_recovery_page_present: 0x01,
1756            reserved: 0x00,
1757        };
1758
1759        let mut dvd_read = scsi::FeatureDataDvdRead {
1760            header: scsi::FeatureHeader {
1761                feature_code: (scsi::FeatureNumber::FeatureDvdRead as u16).into(),
1762                flags: scsi::FeatureHeaderFlags::new()
1763                    .with_current(true)
1764                    .with_persistent(false)
1765                    .with_version(0x01)
1766                    .with_reserved(0),
1767                additional_length: 0x04,
1768            },
1769            multi_110: 0x00,
1770            reserved: 0x00,
1771            dual_dash_r: 0x00,
1772            reserved2: 0x00,
1773        };
1774
1775        let mut real_time_streaming = scsi::FeatureDataRealTimeStreaming {
1776            header: scsi::FeatureHeader {
1777                feature_code: (FeatureRealTimeStreaming as u16).into(),
1778                flags: scsi::FeatureHeaderFlags::new()
1779                    .with_current(true)
1780                    .with_persistent(true)
1781                    .with_version(0x05)
1782                    .with_reserved(0),
1783                additional_length: 0x04,
1784            },
1785            flags: scsi::RealTimeStreamingFlags::new()
1786                .with_stream_recording(false)
1787                .with_write_speed_in_get_perf(false)
1788                .with_write_speed_in_mp2_a(false)
1789                .with_set_cdspeed(false)
1790                .with_read_buffer_capacity_block(true)
1791                .with_reserved1(0x00),
1792            reserved: [0x00, 0x00, 0x00],
1793        };
1794
1795        *feature_size = 0;
1796        match feature_code {
1797            scsi::FeatureNumber::FeatureProfileList => {
1798                profile_list.profile[0].current =
1799                    self.media_state.lock().drive_state.medium_present() as u8;
1800                *feature_size = size_of::<scsi::GetConfigurationFeatureDataProfileList>();
1801                bytes_used = std::cmp::min(*feature_size, buffer_size);
1802                if bytes_used > 0 {
1803                    external_data
1804                        .writer()
1805                        .write(&profile_list.as_bytes()[..bytes_used])
1806                        .map_err(ScsiDvdError::MemoryAccess)?;
1807                }
1808            }
1809            scsi::FeatureNumber::FeatureCore => {
1810                *feature_size = size_of::<scsi::FeatureDataCore>();
1811                bytes_used = std::cmp::min(*feature_size, buffer_size);
1812                let data = scsi::FeatureDataCore {
1813                    header: scsi::FeatureHeader {
1814                        feature_code: (scsi::FeatureNumber::FeatureCore as u16).into(),
1815                        flags: scsi::FeatureHeaderFlags::new()
1816                            .with_current(true)
1817                            .with_persistent(true)
1818                            .with_version(0x02)
1819                            .with_reserved(0),
1820                        additional_length: 0x08,
1821                    },
1822                    ..FromZeros::new_zeroed()
1823                };
1824                if bytes_used > 0 {
1825                    external_data
1826                        .writer()
1827                        .write(&data.as_bytes()[..bytes_used])
1828                        .map_err(ScsiDvdError::MemoryAccess)?;
1829                }
1830            }
1831            scsi::FeatureNumber::FeatureMorphing => {
1832                *feature_size = size_of::<scsi::FeatureDataMorphing>();
1833                bytes_used = std::cmp::min(*feature_size, buffer_size);
1834                let data = scsi::FeatureDataMorphing {
1835                    header: scsi::FeatureHeader {
1836                        feature_code: (scsi::FeatureNumber::FeatureMorphing as u16).into(),
1837                        flags: scsi::FeatureHeaderFlags::new()
1838                            .with_current(true)
1839                            .with_persistent(true)
1840                            .with_version(0x02)
1841                            .with_reserved(0),
1842                        additional_length: 0x08,
1843                    },
1844                    flags: scsi::FeatureMorphingFlags::new()
1845                        .with_asynchronous(false)
1846                        .with_ocevent(true)
1847                        .with_reserved1(0x00),
1848                    reserved2: [0x00, 0x00, 0x00],
1849                };
1850                if bytes_used > 0 {
1851                    external_data
1852                        .writer()
1853                        .write(&data.as_bytes()[..bytes_used])
1854                        .map_err(ScsiDvdError::MemoryAccess)?;
1855                }
1856            }
1857            scsi::FeatureNumber::FeatureRemovableMedium => {
1858                *feature_size = size_of::<scsi::FeatureDataRemovableMedium>();
1859                bytes_used = std::cmp::min(*feature_size, buffer_size);
1860                let data = scsi::FeatureDataRemovableMedium {
1861                    header: scsi::FeatureHeader {
1862                        feature_code: (scsi::FeatureNumber::FeatureRemovableMedium as u16).into(),
1863                        flags: scsi::FeatureHeaderFlags::new()
1864                            .with_current(true)
1865                            .with_persistent(true)
1866                            .with_version(0x01)
1867                            .with_reserved(0),
1868                        additional_length: 0x04,
1869                    },
1870                    flags: scsi::RemovableMediumFlags::new()
1871                        .with_lockable(true)
1872                        .with_dbml(false)
1873                        .with_default_to_prevent(false)
1874                        .with_eject(true)
1875                        .with_load(true)
1876                        .with_loading_mechanism(0x01),
1877                    reserved2: [0x00, 0x00, 0x00],
1878                };
1879                if bytes_used > 0 {
1880                    external_data
1881                        .writer()
1882                        .write(&data.as_bytes()[..bytes_used])
1883                        .map_err(ScsiDvdError::MemoryAccess)?;
1884                }
1885            }
1886            scsi::FeatureNumber::FeatureRandomReadable => {
1887                let medium_present = self.media_state.lock().drive_state.medium_present();
1888                if !current_only || medium_present {
1889                    random_readable.header.flags.set_current(medium_present);
1890                    *feature_size = size_of::<scsi::FeatureDataRandomReadable>();
1891                    bytes_used = std::cmp::min(*feature_size, buffer_size);
1892                    if bytes_used > 0 {
1893                        external_data
1894                            .writer()
1895                            .write(&random_readable.as_bytes()[..bytes_used])
1896                            .map_err(ScsiDvdError::MemoryAccess)?;
1897                    }
1898                }
1899            }
1900            scsi::FeatureNumber::FeatureCdRead => {
1901                if !current_only {
1902                    *feature_size = size_of::<scsi::FeatureDataCdRead>();
1903                    bytes_used = std::cmp::min(*feature_size, buffer_size);
1904                    let data = scsi::FeatureDataCdRead {
1905                        header: scsi::FeatureHeader {
1906                            feature_code: (scsi::FeatureNumber::FeatureCdRead as u16).into(),
1907                            flags: scsi::FeatureHeaderFlags::new()
1908                                .with_current(false)
1909                                .with_persistent(false)
1910                                .with_version(0x02)
1911                                .with_reserved(0),
1912                            additional_length: 0x04,
1913                        },
1914                        flags: scsi::CDReadFlags::new()
1915                            .with_cd_text(false)
1916                            .with_c2_error_data(false)
1917                            .with_reserved(0x00)
1918                            .with_digital_audio_play(false),
1919                        reserved2: [0x00, 0x00, 0x00],
1920                    };
1921                    if bytes_used > 0 {
1922                        external_data
1923                            .writer()
1924                            .write(&data.as_bytes()[..bytes_used])
1925                            .map_err(ScsiDvdError::MemoryAccess)?;
1926                    }
1927                }
1928            }
1929            scsi::FeatureNumber::FeatureDvdRead => {
1930                let medium_present = self.media_state.lock().drive_state.medium_present();
1931                if !current_only || medium_present {
1932                    *feature_size = size_of::<scsi::FeatureDataDvdRead>();
1933                    bytes_used = std::cmp::min(*feature_size, buffer_size);
1934                    dvd_read.header.flags.set_current(medium_present);
1935                    if bytes_used > 0 {
1936                        external_data
1937                            .writer()
1938                            .write(&dvd_read.as_bytes()[..bytes_used])
1939                            .map_err(ScsiDvdError::MemoryAccess)?;
1940                    }
1941                }
1942            }
1943            FeaturePowerManagement => {
1944                *feature_size = size_of::<scsi::FeatureDataPowerManagement>();
1945                bytes_used = std::cmp::min(*feature_size, buffer_size);
1946                let data = scsi::FeatureDataPowerManagement {
1947                    header: scsi::FeatureHeader {
1948                        feature_code: (FeaturePowerManagement as u16).into(),
1949                        flags: scsi::FeatureHeaderFlags::new()
1950                            .with_current(true)
1951                            .with_persistent(true)
1952                            .with_version(0x00)
1953                            .with_reserved(0),
1954                        additional_length: 0x00,
1955                    },
1956                };
1957                if bytes_used > 0 {
1958                    external_data
1959                        .writer()
1960                        .write(&data.as_bytes()[..bytes_used])
1961                        .map_err(ScsiDvdError::MemoryAccess)?;
1962                }
1963            }
1964            FeatureTimeout => {
1965                *feature_size = size_of::<scsi::FeatureDataTimeout>();
1966                bytes_used = std::cmp::min(*feature_size, buffer_size);
1967                let data = scsi::FeatureDataTimeout {
1968                    header: scsi::FeatureHeader {
1969                        feature_code: (FeatureTimeout as u16).into(),
1970                        flags: scsi::FeatureHeaderFlags::new()
1971                            .with_current(true)
1972                            .with_persistent(true)
1973                            .with_version(0x01)
1974                            .with_reserved(0),
1975                        additional_length: 0x04,
1976                    },
1977                    group: 0x01,
1978                    reserved: 0x00,
1979                    unit_length: 512.into(),
1980                };
1981                if bytes_used > 0 {
1982                    external_data
1983                        .writer()
1984                        .write(&data.as_bytes()[..bytes_used])
1985                        .map_err(ScsiDvdError::MemoryAccess)?;
1986                }
1987            }
1988            FeatureRealTimeStreaming => {
1989                let medium_present = self.media_state.lock().drive_state.medium_present();
1990                if !current_only || medium_present {
1991                    *feature_size = size_of::<scsi::FeatureDataRealTimeStreaming>();
1992                    bytes_used = std::cmp::min(*feature_size, buffer_size);
1993                    real_time_streaming.header.flags.set_current(medium_present);
1994                    if bytes_used > 0 {
1995                        external_data
1996                            .writer()
1997                            .write(&real_time_streaming.as_bytes()[..bytes_used])
1998                            .map_err(ScsiDvdError::MemoryAccess)?;
1999                    }
2000                }
2001            }
2002            _ => {}
2003        }
2004        Ok(bytes_used)
2005    }
2006
2007    fn iso_init_configuration_header(
2008        &self,
2009        external_data: &RequestBuffers<'_>,
2010        data_length: usize,
2011    ) -> Result<usize, ScsiDvdError> {
2012        let current_profile = if self.media_state.lock().drive_state.medium_present() {
2013            scsi::PROFILE_DVD_ROM
2014        } else {
2015            0
2016        };
2017
2018        // data_length field indicates the amount of data available given a sufficient allocation length
2019        // following this field. Thus the size of itself should be excluded.
2020        let header = scsi::GetConfigurationHeader {
2021            data_length: (data_length as u32).into(),
2022            current_profile: current_profile.into(),
2023            ..FromZeros::new_zeroed()
2024        };
2025
2026        let tx = external_data.len();
2027
2028        external_data
2029            .writer()
2030            .write(&header.as_bytes()[..tx])
2031            .map_err(ScsiDvdError::MemoryAccess)?;
2032
2033        Ok(tx)
2034    }
2035
2036    fn handle_no_vpd_page_iso(
2037        &self,
2038        external_data: &RequestBuffers<'_>,
2039        allocation_length: usize,
2040    ) -> Result<usize, ScsiDvdError> {
2041        // return standard inquiry data
2042        let data = scsi::InquiryData {
2043            header: scsi::InquiryDataHeader {
2044                device_type: 0x05,
2045                flags2: scsi::InquiryDataFlag2::new().with_removable_media(true),
2046                versions: 0x00,
2047                flags3: scsi::InquiryDataFlag3::new()
2048                    .with_response_data_format(scsi::T10_RESPONSE_DATA_SPC3),
2049                additional_length: (scsi::INQUIRY_DATA_BUFFER_SIZE
2050                    - (size_of::<scsi::InquiryDataHeader>() as u8)),
2051            },
2052            vendor_id: *b"Msft    ",
2053            product_id: *b"Virtual DVD-ROM ",
2054            product_revision_level: *b"1.0 ",
2055            ..FromZeros::new_zeroed()
2056        };
2057
2058        let tx = std::cmp::min(allocation_length, size_of::<scsi::InquiryData>());
2059        external_data
2060            .writer()
2061            .write(&data.as_bytes()[..tx])
2062            .map_err(ScsiDvdError::MemoryAccess)?;
2063
2064        Ok(tx)
2065    }
2066
2067    fn handle_vpd_supported_pages_iso(
2068        &self,
2069        external_data: &RequestBuffers<'_>,
2070        allocation_length: usize,
2071    ) -> Result<usize, ScsiDvdError> {
2072        let page = [scsi::VPD_SUPPORTED_PAGES, scsi::VPD_DEVICE_IDENTIFIERS];
2073
2074        write_vpd_page(
2075            external_data,
2076            allocation_length,
2077            scsi::VPD_SUPPORTED_PAGES,
2078            &page,
2079        )
2080    }
2081
2082    fn handle_vpd_device_identifiers_iso(
2083        &self,
2084        external_data: &RequestBuffers<'_>,
2085        allocation_length: usize,
2086    ) -> Result<usize, ScsiDvdError> {
2087        // This is the ID used by VHDMP on Windows.
2088        let context_guid = [
2089            0x73, 0x05, 0xe3, 0x43, 0x77, 0x03, 0x54, 0x46, 0x94, 0x95, 0x7d, 0x7c, 0xed, 0x62,
2090            0x4a, 0x7d,
2091        ];
2092        let page = scsi::IsoVpdIdentifiers {
2093            id_page: scsi::VpdIdentificationDescriptor {
2094                code_set: scsi::VPD_CODE_SET_BINARY,
2095                identifiertype: scsi::VPD_IDENTIFIER_TYPE_VENDOR_ID,
2096                reserved3: 0x00,
2097                identifier_length: (size_of::<scsi::IsoVpdIdentifiers>()
2098                    - size_of::<scsi::VpdIdentificationDescriptor>())
2099                    as u8,
2100            },
2101            vendor_id: *b"Msft    ",
2102            context_guid,
2103        };
2104
2105        write_vpd_page(
2106            external_data,
2107            allocation_length,
2108            scsi::VPD_DEVICE_IDENTIFIERS,
2109            &page,
2110        )
2111    }
2112
2113    fn validate_data_cdb_iso<'a>(
2114        &self,
2115        media: &'a Media,
2116        external_data: &RequestBuffers<'_>,
2117        request: &Request,
2118        op: ScsiOp,
2119    ) -> Result<RequestParametersIso<'a>, ScsiDvdError> {
2120        let (len, offset) = match op {
2121            ScsiOp::READ => {
2122                let cdb = scsi::Cdb10::read_from_prefix(&request.cdb[..]).unwrap().0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
2123                (
2124                    cdb.transfer_blocks.get() as u64,
2125                    cdb.logical_block.get() as u64,
2126                )
2127            }
2128            ScsiOp::READ12 => {
2129                let cdb = scsi::Cdb12::read_from_prefix(&request.cdb[..]).unwrap().0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
2130                (
2131                    cdb.transfer_blocks.get() as u64,
2132                    cdb.logical_block.get() as u64,
2133                )
2134            }
2135            ScsiOp::READ16 => {
2136                let cdb = scsi::Cdb16::read_from_prefix(&request.cdb[..]).unwrap().0; // TODO: zerocopy: use-rest-of-range (https://github.com/microsoft/openvmm/issues/759)
2137                (cdb.transfer_blocks.get() as u64, cdb.logical_block.get())
2138            }
2139            _ => unreachable!(),
2140        };
2141
2142        if len == 0 {
2143            return Ok(RequestParametersIso {
2144                tx: len as usize,
2145                offset: 0,
2146                disk: None,
2147            });
2148        }
2149
2150        let disk = self.loaded_disk(media)?;
2151        let sector_count = iso_sector_count(disk);
2152
2153        let sector_shift = self.sector_shift();
2154        let max = external_data.len() >> sector_shift;
2155        if len as usize > max {
2156            tracelimit::error_ratelimited!(len, max, "illegal block");
2157            return Err(ScsiDvdError::IllegalRequest(
2158                AdditionalSenseCode::ILLEGAL_BLOCK,
2159                0,
2160            ));
2161        }
2162
2163        if sector_count <= offset || sector_count - offset < len {
2164            tracelimit::error_ratelimited!(sector_count, offset, len, "illegal block");
2165            return Err(ScsiDvdError::IllegalRequest(
2166                AdditionalSenseCode::ILLEGAL_BLOCK,
2167                0,
2168            ));
2169        }
2170
2171        let tx = (len as usize) << sector_shift;
2172        Ok(RequestParametersIso {
2173            tx,
2174            offset: (offset * disk_balancer(disk)),
2175            disk: Some(disk),
2176        })
2177    }
2178
2179    fn iso_get_mode_page(
2180        &self,
2181        external_data: &RequestBuffers<'_>,
2182        buffer_size: usize,
2183        page_code: u8,
2184        mode_page_size: &mut u16,
2185    ) -> Result<usize, ScsiDvdError> {
2186        let tx: usize;
2187        let page_size: usize;
2188        match page_code {
2189            scsi::MODE_PAGE_ERROR_RECOVERY => {
2190                page_size = size_of::<scsi::ModeReadWriteRecoveryPage>();
2191                tx = std::cmp::min(page_size, buffer_size);
2192                let data = scsi::ModeReadWriteRecoveryPage {
2193                    page_code: 0x01,
2194                    page_length: 0x0a,
2195                    bit_info: 0u8,
2196                    read_retry_count: 0u8,
2197                    reserved: [0u8, 0u8, 0u8, 0u8],
2198                    write_retry_count: 0u8,
2199                    reserved2: [0u8, 0u8, 0u8],
2200                };
2201                external_data
2202                    .writer()
2203                    .write(&data.as_bytes()[..tx])
2204                    .map_err(ScsiDvdError::MemoryAccess)?;
2205                *mode_page_size = page_size as u16;
2206            }
2207            scsi::MODE_PAGE_POWER_CONDITION => {
2208                page_size = size_of::<scsi::PowerConditionPage>();
2209                tx = std::cmp::min(page_size, buffer_size);
2210                let data = scsi::PowerConditionPage {
2211                    page_code: 0x1a,
2212                    page_length: 0x0a,
2213                    ..FromZeros::new_zeroed()
2214                };
2215                external_data
2216                    .writer()
2217                    .write(&data.as_bytes()[..tx])
2218                    .map_err(ScsiDvdError::MemoryAccess)?;
2219                *mode_page_size = page_size as u16;
2220            }
2221            scsi::MODE_PAGE_CDVD_INACTIVITY => {
2222                page_size = size_of::<scsi::ModeSenseModePageTimeoutProtect>();
2223                tx = std::cmp::min(page_size, buffer_size);
2224                let data = scsi::ModeSenseModePageTimeoutProtect {
2225                    page_code: 0x1d,
2226                    page_length: 0x0a,
2227                    reserved: [0u8, 0u8],
2228                    bit_info: 0x00,
2229                    reserved2: 0x00,
2230                    group_one_minimum_timeout: [0x00, 0x05],
2231                    group_two_minimum_timeout: [0x00, 0x14],
2232                    group_three_timeout: [0x00, 0x0a],
2233                };
2234                external_data
2235                    .writer()
2236                    .write(&data.as_bytes()[..tx])
2237                    .map_err(ScsiDvdError::MemoryAccess)?;
2238                *mode_page_size = page_size as u16;
2239            }
2240            _ => {
2241                *mode_page_size = 0;
2242                tx = 0;
2243            }
2244        };
2245        Ok(tx)
2246    }
2247
2248    fn iso_init_mode_sense_header(
2249        &self,
2250        external_data: &RequestBuffers<'_>,
2251        buffer_size: usize,
2252        data_length: u16,
2253    ) -> Result<usize, ScsiDvdError> {
2254        let data = scsi::ModeParameterHeader10 {
2255            mode_data_length: (data_length - (size_of::<u16>() as u16)).into(),
2256            block_descriptor_length: 0.into(),
2257            ..FromZeros::new_zeroed()
2258        };
2259        let tx = std::cmp::min(super::MODE_PARAMETER_HEADER10_SIZE, buffer_size);
2260        external_data
2261            .writer()
2262            .write(&data.as_bytes()[..tx])
2263            .map_err(ScsiDvdError::MemoryAccess)?;
2264        Ok(tx)
2265    }
2266
2267    fn validate_media_for_read(&self) -> Result<(), ScsiDvdError> {
2268        let drive_state = self.media_state.lock().drive_state;
2269
2270        match drive_state {
2271            DriveState::MediumPresentTrayOpen => Ok(()),
2272            DriveState::MediumPresentTrayClosed => Ok(()),
2273            DriveState::MediumNotPresentTrayOpen => Err(ScsiDvdError::SenseNotReady(
2274                AdditionalSenseCode::NO_MEDIA_IN_DEVICE,
2275                scsi::MEDIUM_NOT_PRESENT_TRAY_OPEN,
2276            )),
2277            DriveState::MediumNotPresentTrayClosed => Err(ScsiDvdError::SenseNotReady(
2278                AdditionalSenseCode::NO_MEDIA_IN_DEVICE,
2279                scsi::MEDIUM_NOT_PRESENT_TRAY_CLOSED,
2280            )),
2281        }
2282    }
2283
2284    fn iso_init_performance_header(
2285        &self,
2286        external_data: &RequestBuffers<'_>,
2287        buffer_size: u64,
2288        data_length: u64,
2289        except: u8,
2290    ) -> Result<usize, ScsiDvdError> {
2291        let header = scsi::GetPerformanceHeader {
2292            total_data_length: (data_length as u32).into(),
2293            except: except & 0x01,
2294            ..FromZeros::new_zeroed()
2295        };
2296
2297        let tx =
2298            std::cmp::min(size_of::<scsi::GetPerformanceHeader>() as u64, buffer_size) as usize;
2299        external_data
2300            .writer()
2301            .write(&header.as_bytes()[..tx])
2302            .map_err(ScsiDvdError::MemoryAccess)?;
2303        Ok(tx)
2304    }
2305
2306    fn process_result(&self, result: Result<usize, ScsiDvdError>, op: ScsiOp) -> ScsiResult {
2307        let result = match result {
2308            Ok(tx) => ScsiResult {
2309                scsi_status: ScsiStatus::GOOD,
2310                srb_status: SrbStatus::SUCCESS,
2311                tx,
2312                sense_data: None,
2313            },
2314            Err(err) => match err {
2315                ScsiDvdError::IllegalRequest(sense_code, sense_qualifier) => ScsiResult {
2316                    scsi_status: ScsiStatus::CHECK_CONDITION,
2317                    srb_status: SrbStatus::ERROR,
2318                    tx: 0,
2319                    sense_data: Some(illegal_request_sense_iso(sense_code, sense_qualifier)),
2320                },
2321                ScsiDvdError::DataOverrun => ScsiResult {
2322                    scsi_status: ScsiStatus::CHECK_CONDITION,
2323                    srb_status: SrbStatus::DATA_OVERRUN,
2324                    tx: 0,
2325                    sense_data: None,
2326                },
2327                ScsiDvdError::MemoryAccess(_) => ScsiResult {
2328                    scsi_status: ScsiStatus::CHECK_CONDITION,
2329                    srb_status: SrbStatus::INVALID_REQUEST,
2330                    tx: 0,
2331                    sense_data: Some(illegal_request_sense_iso(
2332                        AdditionalSenseCode::INVALID_CDB,
2333                        0,
2334                    )),
2335                },
2336                ScsiDvdError::SenseNotReady(sense_code, sense_qualifier) => ScsiResult {
2337                    scsi_status: ScsiStatus::CHECK_CONDITION,
2338                    srb_status: SrbStatus::ERROR,
2339                    tx: 0,
2340                    sense_data: Some(SenseData::new(
2341                        SenseKey::NOT_READY,
2342                        sense_code,
2343                        sense_qualifier,
2344                    )),
2345                },
2346                ScsiDvdError::IoError(err) => match err {
2347                    DiskError::UnsupportedEject => ScsiResult {
2348                        scsi_status: ScsiStatus::CHECK_CONDITION,
2349                        srb_status: SrbStatus::INVALID_REQUEST,
2350                        tx: 0,
2351                        sense_data: Some(illegal_request_sense_iso(
2352                            AdditionalSenseCode::ILLEGAL_COMMAND,
2353                            0,
2354                        )),
2355                    },
2356                    DiskError::ReservationConflict => ScsiResult {
2357                        scsi_status: ScsiStatus::RESERVATION_CONFLICT,
2358                        srb_status: SrbStatus::ERROR,
2359                        tx: 0,
2360                        sense_data: Some(SenseData::new(
2361                            SenseKey::ILLEGAL_REQUEST,
2362                            AdditionalSenseCode::COMMAND_SEQUENCE_ERROR,
2363                            scsi::SCSI_SENSEQ_CAPACITY_DATA_CHANGED,
2364                        )),
2365                    },
2366                    _ => ScsiResult {
2367                        scsi_status: ScsiStatus::CHECK_CONDITION,
2368                        srb_status: SrbStatus::ERROR,
2369                        tx: 0,
2370                        sense_data: None,
2371                    },
2372                },
2373                ScsiDvdError::IllegalRequestNoSenseData => ScsiResult {
2374                    scsi_status: ScsiStatus::CHECK_CONDITION,
2375                    srb_status: SrbStatus::INVALID_REQUEST,
2376                    tx: 0,
2377                    sense_data: None,
2378                },
2379            },
2380        };
2381
2382        self.sense_data.set(result.sense_data.as_ref());
2383        tracing::trace!(scsi_result = ?result, ?op, "process_result completed.");
2384
2385        result
2386    }
2387}
2388
2389fn illegal_request_sense_iso(sense_code: AdditionalSenseCode, sense_qualifier: u8) -> SenseData {
2390    match sense_code {
2391        AdditionalSenseCode::ILLEGAL_COMMAND
2392        | AdditionalSenseCode::INVALID_CDB
2393        | AdditionalSenseCode::NO_SENSE
2394        | AdditionalSenseCode::INVALID_FIELD_PARAMETER_LIST
2395        | AdditionalSenseCode::PARAMETER_LIST_LENGTH
2396        | AdditionalSenseCode::ILLEGAL_BLOCK
2397        | AdditionalSenseCode::INVALID_MEDIA
2398        | AdditionalSenseCode::SAVING_PARAMETER_NOT_SUPPORTED
2399        | AdditionalSenseCode::MEDIUM_REMOVAL_PREVENTED => {
2400            SenseData::new(SenseKey::ILLEGAL_REQUEST, sense_code, sense_qualifier)
2401        }
2402        _ => unreachable!(),
2403    }
2404}
2405
2406#[cfg(test)]
2407mod tests {
2408    use super::Media;
2409    use super::disk_balancer;
2410    use super::iso_sector_count;
2411    use crate::SavedSenseData;
2412    use crate::ScsiSaveRestore;
2413    use crate::ScsiSavedState;
2414    use crate::scsi;
2415    use crate::scsidvd::ISO_SECTOR_SIZE;
2416    use crate::scsidvd::SimpleScsiDvd;
2417    use disk_backend::Disk;
2418    use disk_backend::DiskError;
2419    use disk_backend::DiskIo;
2420    use disk_backend::UnmapBehavior;
2421    use disk_hook::DiskOperation;
2422    use disk_hook::HookDisk;
2423    use futures::FutureExt;
2424    use guestmem::GuestMemory;
2425    use inspect::Inspect;
2426    use pal_async::async_test;
2427    use scsi::AdditionalSenseCode;
2428    use scsi::ScsiOp;
2429    use scsi::SenseKey;
2430    use scsi_buffers::OwnedRequestBuffers;
2431    use scsi_buffers::RequestBuffers;
2432    use scsi_core::AsyncScsiDisk;
2433    use scsi_core::Request;
2434    use scsi_core::save_restore::DriveState;
2435    use scsi_core::save_restore::IsoMediumEvent;
2436    use scsi_core::save_restore::ScsiDvdSavedState;
2437    use std::pin::pin;
2438    use std::sync::Arc;
2439    use std::sync::Barrier;
2440    use std::sync::atomic::AtomicBool;
2441    use std::sync::atomic::Ordering;
2442    use std::sync::mpsc;
2443    use std::time::Duration;
2444    use test_with_tracing::test;
2445    use zerocopy::IntoBytes;
2446
2447    async fn new_scsi_dvd(sector_size: u32, sector_count: u64, read_only: bool) -> SimpleScsiDvd {
2448        let size = sector_count * u64::from(sector_size);
2449        let disk = HookDisk::new(size, sector_size)
2450            .with_fua_respected(false)
2451            .with_unmap_behavior(UnmapBehavior::Ignored);
2452        let len = usize::try_from(size).unwrap();
2453        let mut mem = GuestMemory::allocate(len);
2454        fill_repeat_data_buffer(
2455            &mut mem.inner_buf_mut().unwrap()[..len],
2456            sector_size as usize,
2457        );
2458        disk.write_vectored(
2459            &OwnedRequestBuffers::linear(0, len, false).buffer(&mem),
2460            0,
2461            false,
2462        )
2463        .await
2464        .unwrap();
2465        let scsi_dvd = SimpleScsiDvd::new(Some(disk.with_read_only(read_only).into_disk()));
2466        let sector_shift = ISO_SECTOR_SIZE.trailing_zeros() as u8;
2467        assert_eq!(scsi_dvd.sector_shift(), sector_shift);
2468        if let Media::Loaded(disk) = &*scsi_dvd.media.read() {
2469            assert_eq!(iso_sector_count(disk), sector_count / disk_balancer(disk));
2470            assert_eq!(disk.is_read_only(), read_only);
2471            assert_eq!(disk.sector_size(), sector_size);
2472            assert_eq!(disk.physical_sector_size(), sector_size);
2473            assert_eq!(disk.disk_id(), None);
2474            assert!(!disk.is_fua_respected());
2475            assert_eq!(disk.unmap_behavior(), UnmapBehavior::Ignored);
2476        } else {
2477            panic!("unexpected Media::Unloaded");
2478        }
2479        scsi_dvd
2480    }
2481
2482    fn fill_repeat_data_buffer(buf: &mut [u8], sector_size: usize) {
2483        assert!(sector_size > 2);
2484        assert!(buf.len().is_multiple_of(sector_size));
2485        buf.fill(0);
2486        for sector in buf.chunks_exact_mut(sector_size) {
2487            sector[sector_size / 2 - 1] = 2;
2488            sector[sector_size / 2] = 3;
2489        }
2490    }
2491
2492    async fn check_execute_scsi(
2493        scsi_dvd: &mut SimpleScsiDvd,
2494        external_data: &RequestBuffers<'_>,
2495        request: &Request,
2496        pass: bool,
2497    ) {
2498        let result = scsi_dvd.execute_scsi(external_data, request).await;
2499        match pass {
2500            true if result.scsi_status != scsi::ScsiStatus::GOOD => {
2501                panic!(
2502                    "execute_scsi failed! request: {:?} result: {:?}",
2503                    request, result
2504                );
2505            }
2506            false if result.scsi_status == scsi::ScsiStatus::GOOD => {
2507                panic!(
2508                    "execute_scsi passed! request: {:?} result: {:?}",
2509                    request, result
2510                );
2511            }
2512            _ => (),
2513        }
2514    }
2515
2516    fn make_cdb16_request(operation_code: ScsiOp, start_lba: u64, lba_count: u32) -> Request {
2517        let cdb = scsi::Cdb16 {
2518            operation_code,
2519            flags: scsi::Cdb16Flags::new(),
2520            logical_block: start_lba.into(),
2521            transfer_blocks: lba_count.into(),
2522            reserved2: 0,
2523            control: 0,
2524        };
2525        let mut data = [0u8; 16];
2526        data[..].copy_from_slice(cdb.as_bytes());
2527        Request {
2528            cdb: data,
2529            srb_flags: 0,
2530        }
2531    }
2532
2533    fn check_guest_memory(
2534        guest_mem: &GuestMemory,
2535        start_lba: u64,
2536        buff: &[u8],
2537        sector_size: usize,
2538    ) -> bool {
2539        let mut b = vec![0u8; buff.len()];
2540        if guest_mem.read_at(start_lba, &mut b).is_err() {
2541            panic!("guest_mem read error");
2542        };
2543        buff[..].eq(&b[..]) && (b[sector_size / 2 - 1] == 2) && (b[sector_size / 2] == 3)
2544    }
2545
2546    fn save_scsi_dvd(scsi_dvd: &SimpleScsiDvd) -> ScsiDvdSavedState {
2547        let saved_state =
2548            if let Some(ScsiSavedState::ScsiDvd(saved_state)) = scsi_dvd.save().unwrap() {
2549                saved_state
2550            } else {
2551                panic!("saved_state cannot be none")
2552            };
2553        let media_state = scsi_dvd.media_state.lock();
2554        assert_eq!(saved_state.persistent, media_state.persistent);
2555        assert_eq!(saved_state.prevent, media_state.prevent);
2556        assert_eq!(saved_state.drive_state, media_state.drive_state);
2557        assert_eq!(
2558            saved_state.pending_medium_event,
2559            media_state.pending_medium_event
2560        );
2561        let sense = scsi_dvd.sense_data.get();
2562        let sense_data = sense.map(|sense| SavedSenseData {
2563            sense_key: sense.header.sense_key.0,
2564            additional_sense_code: sense.additional_sense_code.0,
2565            additional_sense_code_qualifier: sense.additional_sense_code_qualifier,
2566        });
2567        assert_eq!(saved_state.sense_data, sense_data);
2568        saved_state
2569    }
2570
2571    fn restore_scsi_dvd(saved_state: ScsiDvdSavedState, scsi_dvd: &SimpleScsiDvd) {
2572        if scsi_dvd
2573            .restore(&ScsiSavedState::ScsiDvd(saved_state))
2574            .is_err()
2575        {
2576            panic!("restore scsi dvd failed. saved_state {:?}", saved_state);
2577        }
2578
2579        let media_state = scsi_dvd.media_state.lock();
2580        assert_eq!(saved_state.persistent, media_state.persistent);
2581        assert_eq!(saved_state.prevent, media_state.prevent);
2582        assert_eq!(saved_state.drive_state, media_state.drive_state);
2583        assert_eq!(
2584            saved_state.pending_medium_event,
2585            media_state.pending_medium_event
2586        );
2587        let sense = scsi_dvd.sense_data.get();
2588        let sense_data = sense.map(|sense| SavedSenseData {
2589            sense_key: sense.header.sense_key.0,
2590            additional_sense_code: sense.additional_sense_code.0,
2591            additional_sense_code_qualifier: sense.additional_sense_code_qualifier,
2592        });
2593        assert_eq!(saved_state.sense_data, sense_data);
2594    }
2595
2596    #[async_test]
2597    async fn validate_new_scsi_dvd() {
2598        for sector_size in [512, ISO_SECTOR_SIZE] {
2599            for read_only in [false, true] {
2600                new_scsi_dvd(sector_size, 2048, read_only).await;
2601            }
2602        }
2603    }
2604
2605    fn make_medium_removal_request(prevent: bool, persistent: bool) -> Request {
2606        let cdb = scsi::CdbMediaRemoval {
2607            operation_code: ScsiOp::MEDIUM_REMOVAL,
2608            lun: 0,
2609            reserved: [0; 2],
2610            flags: scsi::MediaRemovalFlags::new()
2611                .with_prevent(prevent)
2612                .with_persistent(persistent),
2613        };
2614        let mut data = [0u8; 16];
2615        data[..size_of::<scsi::CdbMediaRemoval>()].copy_from_slice(cdb.as_bytes());
2616        Request {
2617            cdb: data,
2618            srb_flags: 0,
2619        }
2620    }
2621
2622    fn make_eject_request() -> Request {
2623        let cdb = scsi::StartStop {
2624            operation_code: ScsiOp::START_STOP_UNIT,
2625            immediate: 0,
2626            reserved2: [0; 2],
2627            flag: scsi::StartStopFlags::new()
2628                .with_start(false)
2629                .with_load_eject(true),
2630            control: 0,
2631        };
2632        let mut data = [0u8; 16];
2633        data[..size_of::<scsi::StartStop>()].copy_from_slice(cdb.as_bytes());
2634        Request {
2635            cdb: data,
2636            srb_flags: 0,
2637        }
2638    }
2639
2640    /// A tray lock belongs to the initiator that set it, not to the drive.
2641    ///
2642    /// PREVENT ALLOW MEDIUM REMOVAL is scoped to the I_T nexus, so when the nexus
2643    /// goes away - the guest closed the channel, or was reset in place, which
2644    /// closes it too - the lock has to go with it. Otherwise the next guest to
2645    /// boot cannot eject, and its START STOP UNIT is failed with
2646    /// MEDIUM_REMOVAL_PREVENTED by a decision it never made (umbrella #186).
2647    ///
2648    /// The first eject is the control: without it a pass would only show that
2649    /// ejecting works, not that clearing the nexus is what made it work.
2650    #[async_test]
2651    async fn validate_tray_lock_does_not_outlive_the_nexus() {
2652        let mut scsi_dvd = new_scsi_dvd(ISO_SECTOR_SIZE, 2048, true).await;
2653        let external_data = OwnedRequestBuffers::new(&[0]);
2654        let guest_mem = GuestMemory::allocate(ISO_SECTOR_SIZE as usize);
2655
2656        check_execute_scsi(
2657            &mut scsi_dvd,
2658            &external_data.buffer(&guest_mem),
2659            &make_medium_removal_request(true, true),
2660            true,
2661        )
2662        .await;
2663        assert!(scsi_dvd.media_state.lock().prevent);
2664        // Set PERSISTENT as well, so that the assertion after the clear can fail.
2665        assert!(scsi_dvd.media_state.lock().persistent);
2666
2667        // Locked, so this one must be refused.
2668        check_execute_scsi(
2669            &mut scsi_dvd,
2670            &external_data.buffer(&guest_mem),
2671            &make_eject_request(),
2672            false,
2673        )
2674        .await;
2675
2676        scsi_dvd.clear_nexus_state();
2677        assert!(!scsi_dvd.media_state.lock().prevent);
2678        assert!(!scsi_dvd.media_state.lock().persistent);
2679
2680        // Same command, same drive, same media: it succeeds now only because the
2681        // lock did not survive the nexus.
2682        check_execute_scsi(
2683            &mut scsi_dvd,
2684            &external_data.buffer(&guest_mem),
2685            &make_eject_request(),
2686            true,
2687        )
2688        .await;
2689    }
2690
2691    /// Sense data and a queued medium-change event are per-nexus too, and the
2692    /// tray state is NOT.
2693    ///
2694    /// The second half is the guard against over-clearing: an ejected tray must
2695    /// stay ejected, as it would on real hardware, so a fix that resets the whole
2696    /// MediaState would fail here.
2697    ///
2698    /// Order matters. The eject has to come FIRST and the failing command last:
2699    /// a command that succeeds clears the sense slot on its way out, so an eject
2700    /// placed after it would leave the slot empty and the sense assertion would
2701    /// hold whether or not anything cleared it. Written the other way round this
2702    /// test passed against a `clear_nexus_state` mutated to do nothing at all.
2703    #[async_test]
2704    async fn validate_sense_clears_but_the_tray_state_survives() {
2705        let mut scsi_dvd = new_scsi_dvd(ISO_SECTOR_SIZE, 2048, true).await;
2706        let external_data = OwnedRequestBuffers::new(&[0]);
2707        let guest_mem = GuestMemory::allocate(ISO_SECTOR_SIZE as usize);
2708
2709        check_execute_scsi(
2710            &mut scsi_dvd,
2711            &external_data.buffer(&guest_mem),
2712            &make_eject_request(),
2713            true,
2714        )
2715        .await;
2716        let ejected = scsi_dvd.media_state.lock().drive_state;
2717        // The eject queued a medium-change event, which belongs to this initiator.
2718        assert_eq!(
2719            scsi_dvd.media_state.lock().pending_medium_event,
2720            IsoMediumEvent::MediaToNoMedia
2721        );
2722
2723        // A failed command leaves sense data behind for the initiator to collect.
2724        check_execute_scsi(
2725            &mut scsi_dvd,
2726            &external_data.buffer(&guest_mem),
2727            &make_cdb16_request(ScsiOp::READ16, 4096, 1),
2728            false,
2729        )
2730        .await;
2731        assert!(scsi_dvd.sense_data.get().is_some());
2732
2733        scsi_dvd.clear_nexus_state();
2734
2735        assert!(scsi_dvd.sense_data.get().is_none());
2736        assert_eq!(
2737            scsi_dvd.media_state.lock().pending_medium_event,
2738            IsoMediumEvent::None
2739        );
2740        assert_eq!(
2741            scsi_dvd.media_state.lock().drive_state,
2742            ejected,
2743            "the tray belongs to the drive, not to the initiator"
2744        );
2745    }
2746
2747    #[async_test]
2748    async fn validate_read16() {
2749        for sector_size in [512, ISO_SECTOR_SIZE] {
2750            let mut scsi_dvd = new_scsi_dvd(sector_size, 2048, true).await;
2751            let lba_count = 2;
2752            let len = (ISO_SECTOR_SIZE * lba_count) as usize;
2753            let external_data = OwnedRequestBuffers::linear(0, len, true);
2754            let guest_mem = GuestMemory::allocate(len);
2755            let mut data = vec![0; len];
2756            fill_repeat_data_buffer(&mut data, sector_size as usize);
2757
2758            let sector_count =
2759                iso_sector_count(scsi_dvd.loaded_disk(&scsi_dvd.media.read()).unwrap());
2760            for start_lba in [0, 3, sector_count - u64::from(lba_count)] {
2761                guest_mem.fill_at(0, 0xff, len).unwrap();
2762                let request = make_cdb16_request(ScsiOp::READ16, start_lba, lba_count);
2763                check_execute_scsi(
2764                    &mut scsi_dvd,
2765                    &external_data.buffer(&guest_mem),
2766                    &request,
2767                    true,
2768                )
2769                .await;
2770                assert!(check_guest_memory(
2771                    &guest_mem,
2772                    0,
2773                    &data,
2774                    sector_size as usize
2775                ));
2776            }
2777        }
2778    }
2779
2780    #[async_test]
2781    async fn validate_save_restore_scsi_dvd_no_change() {
2782        let scsi_dvd = new_scsi_dvd(512, 2048, true).await;
2783        let saved_state = save_scsi_dvd(&scsi_dvd);
2784        restore_scsi_dvd(saved_state, &scsi_dvd);
2785    }
2786
2787    #[async_test]
2788    async fn validate_save_restore_scsi_dvd_with_sense_data() {
2789        let scsi_dvd = new_scsi_dvd(512, 2048, true).await;
2790        let mut saved_state = save_scsi_dvd(&scsi_dvd);
2791        saved_state.sense_data = Some(SavedSenseData {
2792            sense_key: SenseKey::UNIT_ATTENTION.0,
2793            additional_sense_code: AdditionalSenseCode::OPERATING_CONDITIONS_CHANGED.0,
2794            additional_sense_code_qualifier: scsi::SCSI_SENSEQ_OPERATING_DEFINITION_CHANGED,
2795        });
2796        restore_scsi_dvd(saved_state, &scsi_dvd);
2797    }
2798
2799    /// A disk that calls a hook from `sector_count()`.
2800    #[derive(Inspect)]
2801    #[inspect(skip)]
2802    struct SectorCountHookDisk(Box<dyn Fn() + Send + Sync>);
2803
2804    impl DiskIo for SectorCountHookDisk {
2805        fn disk_type(&self) -> &str {
2806            "sector-count-hook"
2807        }
2808
2809        fn sector_count(&self) -> u64 {
2810            (self.0)();
2811            2048
2812        }
2813
2814        fn sector_size(&self) -> u32 {
2815            512
2816        }
2817
2818        fn physical_sector_size(&self) -> u32 {
2819            512
2820        }
2821
2822        fn disk_id(&self) -> Option<[u8; 16]> {
2823            None
2824        }
2825
2826        fn is_read_only(&self) -> bool {
2827            true
2828        }
2829
2830        fn is_fua_respected(&self) -> bool {
2831            false
2832        }
2833
2834        fn unmap_behavior(&self) -> UnmapBehavior {
2835            UnmapBehavior::Ignored
2836        }
2837
2838        async fn read_vectored(
2839            &self,
2840            _buffers: &RequestBuffers<'_>,
2841            _sector: u64,
2842        ) -> Result<(), DiskError> {
2843            Err(DiskError::InvalidInput)
2844        }
2845
2846        async fn write_vectored(
2847            &self,
2848            _buffers: &RequestBuffers<'_>,
2849            _sector: u64,
2850            _fua: bool,
2851        ) -> Result<(), DiskError> {
2852            Err(DiskError::InvalidInput)
2853        }
2854
2855        async fn sync_cache(&self) -> Result<(), DiskError> {
2856            Ok(())
2857        }
2858
2859        async fn unmap(
2860            &self,
2861            _sector: u64,
2862            _count: u64,
2863            _block_level_only: bool,
2864        ) -> Result<(), DiskError> {
2865            Err(DiskError::InvalidInput)
2866        }
2867    }
2868
2869    fn make_request(cdb: &[u8]) -> Request {
2870        let mut data = [0u8; 16];
2871        data[..cdb.len()].copy_from_slice(cdb);
2872        Request {
2873            cdb: data,
2874            srb_flags: 0,
2875        }
2876    }
2877
2878    /// Runs `request` on a drive whose media is `disk(pause)`, with the disk
2879    /// calling `pause` where the command should stop. While the command is
2880    /// stopped, runs `change` and checks that the change completes without
2881    /// waiting for the command. Returns the command's status and the first
2882    /// four bytes it transferred.
2883    fn check_media_change_during_command(
2884        disk: impl FnOnce(Box<dyn Fn() + Send + Sync>) -> Disk,
2885        request: Request,
2886        change: fn(&SimpleScsiDvd),
2887    ) -> (scsi::ScsiStatus, [u8; 4]) {
2888        let barrier = Arc::new(Barrier::new(2));
2889        let disk = disk(Box::new({
2890            let barrier = barrier.clone();
2891            let paused = AtomicBool::new(false);
2892            move || {
2893                // Only the command under test pauses.
2894                if !paused.swap(true, Ordering::SeqCst) {
2895                    barrier.wait();
2896                    barrier.wait();
2897                }
2898            }
2899        }));
2900        let scsi_dvd = Arc::new(SimpleScsiDvd::new(Some(disk)));
2901
2902        let (command_done, command_result) = mpsc::channel();
2903        std::thread::spawn({
2904            let scsi_dvd = scsi_dvd.clone();
2905            move || {
2906                let external_data = OwnedRequestBuffers::linear(0, ISO_SECTOR_SIZE as usize, true);
2907                let guest_mem = GuestMemory::allocate(ISO_SECTOR_SIZE as usize);
2908                let result = pal_async::local::block_on(
2909                    scsi_dvd.execute_scsi(&external_data.buffer(&guest_mem), &request),
2910                );
2911                let mut data = [0; 4];
2912                guest_mem.read_at(0, &mut data).unwrap();
2913                command_done.send((result.scsi_status, data)).unwrap();
2914            }
2915        });
2916        barrier.wait();
2917        let (change_done, change_result) = mpsc::channel();
2918        std::thread::spawn({
2919            let scsi_dvd = scsi_dvd.clone();
2920            move || {
2921                change(&scsi_dvd);
2922                change_done.send(()).unwrap();
2923            }
2924        });
2925        change_result
2926            .recv_timeout(Duration::from_secs(10))
2927            .expect("the media change waited for the command");
2928        assert_eq!(
2929            scsi_dvd.media_state.lock().drive_state,
2930            DriveState::MediumNotPresentTrayOpen
2931        );
2932        assert!(matches!(*scsi_dvd.media.read(), Media::Unloaded));
2933        barrier.wait();
2934
2935        // The command finishes with the disk it started with.
2936        command_result
2937            .recv_timeout(Duration::from_secs(10))
2938            .expect("the command did not finish")
2939    }
2940
2941    /// Checks `change` during READ CAPACITY while it asks the disk for its
2942    /// size, and during READ16 while its disk read is in flight.
2943    fn check_media_change_during_commands(change: fn(&SimpleScsiDvd)) {
2944        let result = check_media_change_during_command(
2945            |pause| Disk::new(SectorCountHookDisk(pause)).unwrap(),
2946            make_request(&[ScsiOp::READ_CAPACITY.0]),
2947            change,
2948        );
2949        assert_eq!(
2950            result,
2951            (scsi::ScsiStatus::GOOD, (2048u32 / 4 - 1).to_be_bytes())
2952        );
2953
2954        let result = check_media_change_during_command(
2955            |pause| {
2956                let disk = HookDisk::new(1024 * 1024, 512)
2957                    .with_sync_hook(move |op| {
2958                        if matches!(op, DiskOperation::Read { .. }) {
2959                            pause();
2960                        }
2961                        Ok(())
2962                    })
2963                    .into_disk();
2964                let mem = GuestMemory::allocate(ISO_SECTOR_SIZE as usize);
2965                mem.fill_at(0, 0x5a, ISO_SECTOR_SIZE as usize).unwrap();
2966                let buffers = OwnedRequestBuffers::linear(0, ISO_SECTOR_SIZE as usize, false);
2967                pal_async::local::block_on(disk.write_vectored(&buffers.buffer(&mem), 0, false))
2968                    .unwrap();
2969                disk
2970            },
2971            make_cdb16_request(ScsiOp::READ16, 0, 1),
2972            change,
2973        );
2974        assert_eq!(result, (scsi::ScsiStatus::GOOD, [0x5a; 4]));
2975    }
2976
2977    #[test]
2978    fn host_eject_does_not_wait_for_running_commands() {
2979        check_media_change_during_commands(|scsi_dvd| scsi_dvd.change_media(None));
2980    }
2981
2982    #[test]
2983    fn guest_eject_does_not_wait_for_running_commands() {
2984        check_media_change_during_commands(|scsi_dvd| {
2985            let external_data = OwnedRequestBuffers::new(&[0]);
2986            let guest_mem = GuestMemory::allocate(ISO_SECTOR_SIZE as usize);
2987            let result = pal_async::local::block_on(
2988                scsi_dvd.execute_scsi(&external_data.buffer(&guest_mem), &make_eject_request()),
2989            );
2990            assert_eq!(result.scsi_status, scsi::ScsiStatus::GOOD);
2991        });
2992    }
2993
2994    /// Returns a disk with `byte` in its first ISO sector, whose first read
2995    /// waits for `released` if it is given.
2996    async fn filled_disk(byte: u8, released: Option<mesh::OneshotReceiver<()>>) -> Disk {
2997        let mut disk = HookDisk::new(1024 * 1024, 512);
2998        if let Some(released) = released {
2999            let released = parking_lot::Mutex::new(Some(released));
3000            disk = disk.with_async_hook(move |op| {
3001                let released = matches!(op, DiskOperation::Read { .. })
3002                    .then(|| released.lock().take())
3003                    .flatten();
3004                async move {
3005                    if let Some(released) = released {
3006                        let _ = released.await;
3007                    }
3008                    Ok(())
3009                }
3010            });
3011        }
3012        let disk = disk.into_disk();
3013        let mem = GuestMemory::allocate(ISO_SECTOR_SIZE as usize);
3014        mem.fill_at(0, byte, ISO_SECTOR_SIZE as usize).unwrap();
3015        let buffers = OwnedRequestBuffers::linear(0, ISO_SECTOR_SIZE as usize, false);
3016        disk.write_vectored(&buffers.buffer(&mem), 0, false)
3017            .await
3018            .unwrap();
3019        disk
3020    }
3021
3022    /// storvsp runs each channel's commands in that channel's worker, and on a
3023    /// reset it stops all the workers and then drains the channels one at a
3024    /// time. A command that waits for a command on another channel would never
3025    /// finish there, so a command must complete while another one is stuck.
3026    #[async_test]
3027    async fn commands_do_not_wait_for_each_other() {
3028        let (release, released) = mesh::oneshot();
3029        let scsi_dvd = SimpleScsiDvd::new(Some(filled_disk(0x5a, Some(released)).await));
3030
3031        // A READ16 whose disk read does not complete, as if its channel had
3032        // been stopped.
3033        let read_data = OwnedRequestBuffers::linear(0, ISO_SECTOR_SIZE as usize, true);
3034        let read_mem = GuestMemory::allocate(ISO_SECTOR_SIZE as usize);
3035        let read_request = make_cdb16_request(ScsiOp::READ16, 0, 1);
3036        let read_buffers = read_data.buffer(&read_mem);
3037        let mut read = pin!(scsi_dvd.execute_scsi(&read_buffers, &read_request));
3038        assert!(futures::poll!(read.as_mut()).is_pending());
3039
3040        // Other commands complete without it being polled.
3041        let external_data = OwnedRequestBuffers::linear(0, ISO_SECTOR_SIZE as usize, true);
3042        let guest_mem = GuestMemory::allocate(ISO_SECTOR_SIZE as usize);
3043        for request in [
3044            make_request(&[ScsiOp::TEST_UNIT_READY.0]),
3045            make_request(&[ScsiOp::READ_CAPACITY.0]),
3046            make_request(&[ScsiOp::READ_TOC.0, 0, 0, 0, 0, 0, 0, 0, 12]),
3047        ] {
3048            let result = scsi_dvd
3049                .execute_scsi(&external_data.buffer(&guest_mem), &request)
3050                .now_or_never()
3051                .expect("the command waited for the stuck READ16");
3052            assert_eq!(result.scsi_status, scsi::ScsiStatus::GOOD, "{request:?}");
3053        }
3054
3055        // So does a media change, and the commands after it use the new disk.
3056        scsi_dvd.change_media(Some(filled_disk(0xa5, None).await));
3057        let result = scsi_dvd
3058            .execute_scsi(&external_data.buffer(&guest_mem), &read_request)
3059            .now_or_never()
3060            .expect("the READ16 of the new disk waited for the stuck READ16");
3061        assert_eq!(result.scsi_status, scsi::ScsiStatus::GOOD);
3062        let mut data = [0; 4];
3063        guest_mem.read_at(0, &mut data).unwrap();
3064        assert_eq!(data, [0xa5; 4]);
3065
3066        // The READ16 that was in flight finishes from the disk it started with.
3067        release.send(());
3068        assert_eq!(read.await.scsi_status, scsi::ScsiStatus::GOOD);
3069        read_mem.read_at(0, &mut data).unwrap();
3070        assert_eq!(data, [0x5a; 4]);
3071    }
3072
3073    #[async_test]
3074    async fn validate_media_missing_behind_drive_state() {
3075        let scsi_dvd = new_scsi_dvd(ISO_SECTOR_SIZE, 2048, true).await;
3076        // The drive state says that the medium is present but there is none,
3077        // as can happen after a restore: the drive state is restored, the
3078        // media is not.
3079        *scsi_dvd.media.write() = Media::Unloaded;
3080
3081        let external_data = OwnedRequestBuffers::linear(0, ISO_SECTOR_SIZE as usize, true);
3082        let guest_mem = GuestMemory::allocate(ISO_SECTOR_SIZE as usize);
3083        for (drive_state, qualifier) in [
3084            (
3085                DriveState::MediumPresentTrayClosed,
3086                scsi::MEDIUM_NOT_PRESENT_TRAY_CLOSED,
3087            ),
3088            (
3089                DriveState::MediumPresentTrayOpen,
3090                scsi::MEDIUM_NOT_PRESENT_TRAY_OPEN,
3091            ),
3092        ] {
3093            scsi_dvd.media_state.lock().drive_state = drive_state;
3094            for request in [
3095                make_cdb16_request(ScsiOp::READ16, 0, 1),
3096                make_request(&[ScsiOp::READ_CAPACITY.0]),
3097                make_request(&[ScsiOp::READ_TOC.0, 0, 0, 0, 0, 0, 0, 0, 12]),
3098            ] {
3099                let result = scsi_dvd
3100                    .execute_scsi(&external_data.buffer(&guest_mem), &request)
3101                    .await;
3102                let sense = result.sense_data.expect("no sense data");
3103                assert_eq!(
3104                    (
3105                        result.scsi_status,
3106                        sense.header.sense_key,
3107                        sense.additional_sense_code,
3108                        sense.additional_sense_code_qualifier
3109                    ),
3110                    (
3111                        scsi::ScsiStatus::CHECK_CONDITION,
3112                        SenseKey::NOT_READY,
3113                        AdditionalSenseCode::NO_MEDIA_IN_DEVICE,
3114                        qualifier
3115                    ),
3116                    "{drive_state:?} {request:?}"
3117                );
3118            }
3119        }
3120    }
3121}