VirtualBox

source: vbox/trunk/src/VBox/Devices/Storage/DevATA.cpp

Last change on this file was 106061, checked in by vboxsync, 3 months ago

Copyright year updates by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 334.2 KB
Line 
1/* $Id: DevATA.cpp 106061 2024-09-16 14:03:52Z vboxsync $ */
2/** @file
3 * VBox storage devices: ATA/ATAPI controller device (disk and cdrom).
4 */
5
6/*
7 * Copyright (C) 2006-2024 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#define LOG_GROUP LOG_GROUP_DEV_IDE
33#include <VBox/vmm/pdmdev.h>
34#include <VBox/vmm/pdmstorageifs.h>
35#include <iprt/assert.h>
36#include <iprt/string.h>
37#ifdef IN_RING3
38# include <iprt/mem.h>
39# include <iprt/mp.h>
40# include <iprt/semaphore.h>
41# include <iprt/thread.h>
42# include <iprt/time.h>
43# include <iprt/uuid.h>
44#endif /* IN_RING3 */
45#include <iprt/critsect.h>
46#include <iprt/asm.h>
47#include <VBox/vmm/stam.h>
48#include <VBox/vmm/mm.h>
49#include <VBox/vmm/pgm.h>
50
51#include <VBox/sup.h>
52#include <VBox/AssertGuest.h>
53#include <VBox/scsi.h>
54#include <VBox/scsiinline.h>
55#include <VBox/ata.h>
56
57#include "ATAPIPassthrough.h"
58#include "VBoxDD.h"
59
60
61/*********************************************************************************************************************************
62* Defined Constants And Macros *
63*********************************************************************************************************************************/
64/** Temporary instrumentation for tracking down potential virtual disk
65 * write performance issues. */
66#undef VBOX_INSTRUMENT_DMA_WRITES
67
68/** @name The SSM saved state versions.
69 * @{
70 */
71/** The current saved state version. */
72#define ATA_SAVED_STATE_VERSION 21
73/** Saved state version without iCurLBA for ATA commands. */
74#define ATA_SAVED_STATE_VERSION_WITHOUT_ATA_ILBA 20
75/** The saved state version used by VirtualBox 3.0.
76 * This lacks the config part and has the type at the and. */
77#define ATA_SAVED_STATE_VERSION_VBOX_30 19
78#define ATA_SAVED_STATE_VERSION_WITH_BOOL_TYPE 18
79#define ATA_SAVED_STATE_VERSION_WITHOUT_FULL_SENSE 16
80#define ATA_SAVED_STATE_VERSION_WITHOUT_EVENT_STATUS 17
81/** @} */
82
83/** Values read from an empty (with no devices attached) ATA bus. */
84#define ATA_EMPTY_BUS_DATA 0x7F
85#define ATA_EMPTY_BUS_DATA_32 0x7F7F7F7F
86
87/**
88 * Maximum number of sectors to transfer in a READ/WRITE MULTIPLE request.
89 * Set to 1 to disable multi-sector read support. According to the ATA
90 * specification this must be a power of 2 and it must fit in an 8 bit
91 * value. Thus the only valid values are 1, 2, 4, 8, 16, 32, 64 and 128.
92 */
93#define ATA_MAX_MULT_SECTORS 128
94
95/** The maxium I/O buffer size (for sanity). */
96#define ATA_MAX_SECTOR_SIZE _4K
97/** The maxium I/O buffer size (for sanity). */
98#define ATA_MAX_IO_BUFFER_SIZE (ATA_MAX_MULT_SECTORS * ATA_MAX_SECTOR_SIZE)
99
100/** Mask to be applied to all indexing into ATACONTROLLER::aIfs. */
101#define ATA_SELECTED_IF_MASK 1
102
103/**
104 * Fastest PIO mode supported by the drive.
105 */
106#define ATA_PIO_MODE_MAX 4
107/**
108 * Fastest MDMA mode supported by the drive.
109 */
110#define ATA_MDMA_MODE_MAX 2
111/**
112 * Fastest UDMA mode supported by the drive.
113 */
114#define ATA_UDMA_MODE_MAX 6
115
116/** ATAPI sense info size. */
117#define ATAPI_SENSE_SIZE 64
118
119/** The maximum number of release log entries per device. */
120#define MAX_LOG_REL_ERRORS 1024
121
122/* MediaEventStatus */
123#define ATA_EVENT_STATUS_UNCHANGED 0 /**< medium event status not changed */
124#define ATA_EVENT_STATUS_MEDIA_EJECT_REQUESTED 1 /**< medium eject requested (eject button pressed) */
125#define ATA_EVENT_STATUS_MEDIA_NEW 2 /**< new medium inserted */
126#define ATA_EVENT_STATUS_MEDIA_REMOVED 3 /**< medium removed */
127#define ATA_EVENT_STATUS_MEDIA_CHANGED 4 /**< medium was removed + new medium was inserted */
128
129/* Media track type */
130#define ATA_MEDIA_TYPE_UNKNOWN 0 /**< unknown CD type */
131#define ATA_MEDIA_NO_DISC 0x70 /**< Door closed, no medium */
132
133/** @defgroup grp_piix3atabmdma PIIX3 ATA Bus Master DMA
134 * @{
135 */
136
137/** @name BM_STATUS
138 * @{
139 */
140/** Currently performing a DMA operation. */
141#define BM_STATUS_DMAING 0x01
142/** An error occurred during the DMA operation. */
143#define BM_STATUS_ERROR 0x02
144/** The DMA unit has raised the IDE interrupt line. */
145#define BM_STATUS_INT 0x04
146/** User-defined bit 0, commonly used to signal that drive 0 supports DMA. */
147#define BM_STATUS_D0DMA 0x20
148/** User-defined bit 1, commonly used to signal that drive 1 supports DMA. */
149#define BM_STATUS_D1DMA 0x40
150/** @} */
151
152/** @name BM_CMD
153 * @{
154 */
155/** Start the DMA operation. */
156#define BM_CMD_START 0x01
157/** Data transfer direction: from device to memory if set. */
158#define BM_CMD_WRITE 0x08
159/** @} */
160
161/** Number of I/O ports per bus-master DMA controller. */
162#define BM_DMA_CTL_IOPORTS 8
163/** Mask corresponding to BM_DMA_CTL_IOPORTS. */
164#define BM_DMA_CTL_IOPORTS_MASK 7
165/** Shift count corresponding to BM_DMA_CTL_IOPORTS. */
166#define BM_DMA_CTL_IOPORTS_SHIFT 3
167
168/** @} */
169
170#define ATADEVSTATE_2_DEVINS(pIf) ( (pIf)->CTX_SUFF(pDevIns) )
171#define CONTROLLER_2_DEVINS(pController) ( (pController)->CTX_SUFF(pDevIns) )
172
173
174/*********************************************************************************************************************************
175* Structures and Typedefs *
176*********************************************************************************************************************************/
177/** @defgroup grp_piix3atabmdma PIIX3 ATA Bus Master DMA
178 * @{
179 */
180/** PIIX3 Bus Master DMA unit state. */
181typedef struct BMDMAState
182{
183 /** Command register. */
184 uint8_t u8Cmd;
185 /** Status register. */
186 uint8_t u8Status;
187 /** Explicit alignment padding. */
188 uint8_t abAlignment[2];
189 /** Address of the MMIO region in the guest's memory space. */
190 RTGCPHYS32 GCPhysAddr;
191} BMDMAState;
192
193/** PIIX3 Bus Master DMA descriptor entry. */
194typedef struct BMDMADesc
195{
196 /** Address of the DMA source/target buffer. */
197 RTGCPHYS32 GCPhysBuffer;
198 /** Size of the DMA source/target buffer. */
199 uint32_t cbBuffer;
200} BMDMADesc;
201/** @} */
202
203
204/**
205 * The shared state of an ATA device.
206 */
207typedef struct ATADEVSTATE
208{
209 /** The I/O buffer.
210 * @note Page aligned in case it helps. */
211 uint8_t abIOBuffer[ATA_MAX_IO_BUFFER_SIZE];
212
213 /** Flag indicating whether the current command uses LBA48 mode. */
214 bool fLBA48;
215 /** Flag indicating whether this drive implements the ATAPI command set. */
216 bool fATAPI;
217 /** Set if this interface has asserted the IRQ. */
218 bool fIrqPending;
219 /** Currently configured number of sectors in a multi-sector transfer. */
220 uint8_t cMultSectors;
221 /** Physical CHS disk geometry (static). */
222 PDMMEDIAGEOMETRY PCHSGeometry;
223 /** Translated CHS disk geometry (variable). */
224 PDMMEDIAGEOMETRY XCHSGeometry;
225 /** Total number of sectors on this disk. */
226 uint64_t cTotalSectors;
227 /** Sector size of the medium. */
228 uint32_t cbSector;
229 /** Number of sectors to transfer per IRQ. */
230 uint32_t cSectorsPerIRQ;
231
232 /** ATA/ATAPI register 1: feature (write-only). */
233 uint8_t uATARegFeature;
234 /** ATA/ATAPI register 1: feature, high order byte. */
235 uint8_t uATARegFeatureHOB;
236 /** ATA/ATAPI register 1: error (read-only). */
237 uint8_t uATARegError;
238 /** ATA/ATAPI register 2: sector count (read/write). */
239 uint8_t uATARegNSector;
240 /** ATA/ATAPI register 2: sector count, high order byte. */
241 uint8_t uATARegNSectorHOB;
242 /** ATA/ATAPI register 3: sector (read/write). */
243 uint8_t uATARegSector;
244 /** ATA/ATAPI register 3: sector, high order byte. */
245 uint8_t uATARegSectorHOB;
246 /** ATA/ATAPI register 4: cylinder low (read/write). */
247 uint8_t uATARegLCyl;
248 /** ATA/ATAPI register 4: cylinder low, high order byte. */
249 uint8_t uATARegLCylHOB;
250 /** ATA/ATAPI register 5: cylinder high (read/write). */
251 uint8_t uATARegHCyl;
252 /** ATA/ATAPI register 5: cylinder high, high order byte. */
253 uint8_t uATARegHCylHOB;
254 /** ATA/ATAPI register 6: select drive/head (read/write). */
255 uint8_t uATARegSelect;
256 /** ATA/ATAPI register 7: status (read-only). */
257 uint8_t uATARegStatus;
258 /** ATA/ATAPI register 7: command (write-only). */
259 uint8_t uATARegCommand;
260 /** ATA/ATAPI drive control register (write-only). */
261 uint8_t uATARegDevCtl;
262
263 /** Currently active transfer mode (MDMA/UDMA) and speed. */
264 uint8_t uATATransferMode;
265 /** Current transfer direction. */
266 uint8_t uTxDir;
267 /** Index of callback for begin transfer. */
268 uint8_t iBeginTransfer;
269 /** Index of callback for source/sink of data. */
270 uint8_t iSourceSink;
271 /** Flag indicating whether the current command transfers data in DMA mode. */
272 bool fDMA;
273 /** Set to indicate that ATAPI transfer semantics must be used. */
274 bool fATAPITransfer;
275
276 /** Total ATA/ATAPI transfer size, shared PIO/DMA. */
277 uint32_t cbTotalTransfer;
278 /** Elementary ATA/ATAPI transfer size, shared PIO/DMA. */
279 uint32_t cbElementaryTransfer;
280 /** Maximum ATAPI elementary transfer size, PIO only. */
281 uint32_t cbPIOTransferLimit;
282 /** ATAPI passthrough transfer size, shared PIO/DMA */
283 uint32_t cbAtapiPassthroughTransfer;
284 /** Current read/write buffer position, shared PIO/DMA. */
285 uint32_t iIOBufferCur;
286 /** First element beyond end of valid buffer content, shared PIO/DMA. */
287 uint32_t iIOBufferEnd;
288 /** Align the following fields correctly. */
289 uint32_t Alignment0;
290
291 /** ATA/ATAPI current PIO read/write transfer position. Not shared with DMA for safety reasons. */
292 uint32_t iIOBufferPIODataStart;
293 /** ATA/ATAPI current PIO read/write transfer end. Not shared with DMA for safety reasons. */
294 uint32_t iIOBufferPIODataEnd;
295
296 /** Current LBA position (both ATA/ATAPI). */
297 uint32_t iCurLBA;
298 /** ATAPI current sector size. */
299 uint32_t cbATAPISector;
300 /** ATAPI current command. */
301 uint8_t abATAPICmd[ATAPI_PACKET_SIZE];
302 /** ATAPI sense data. */
303 uint8_t abATAPISense[ATAPI_SENSE_SIZE];
304 /** HACK: Countdown till we report a newly unmounted drive as mounted. */
305 uint8_t cNotifiedMediaChange;
306 /** The same for GET_EVENT_STATUS for mechanism */
307 volatile uint32_t MediaEventStatus;
308
309 /** Media type if known. */
310 volatile uint32_t MediaTrackType;
311
312 /** The status LED state for this drive. */
313 PDMLED Led;
314
315 /** Size of I/O buffer. */
316 uint32_t cbIOBuffer;
317
318 /*
319 * No data that is part of the saved state after this point!!!!!
320 */
321
322 /** Counter for number of busy status seen in R3 in a row. */
323 uint8_t cBusyStatusHackR3;
324 /** Counter for number of busy status seen in GC/R0 in a row. */
325 uint8_t cBusyStatusHackRZ;
326 /** Defines the R3 yield rate by a mask (power of 2 minus one).
327 * Lower is more agressive. */
328 uint8_t cBusyStatusHackR3Rate;
329 /** Defines the R0/RC yield rate by a mask (power of 2 minus one).
330 * Lower is more agressive. */
331 uint8_t cBusyStatusHackRZRate;
332
333 /** Release statistics: number of ATA DMA commands. */
334 STAMCOUNTER StatATADMA;
335 /** Release statistics: number of ATA PIO commands. */
336 STAMCOUNTER StatATAPIO;
337 /** Release statistics: number of ATAPI PIO commands. */
338 STAMCOUNTER StatATAPIDMA;
339 /** Release statistics: number of ATAPI PIO commands. */
340 STAMCOUNTER StatATAPIPIO;
341#ifdef VBOX_INSTRUMENT_DMA_WRITES
342 /** Release statistics: number of DMA sector writes and the time spent. */
343 STAMPROFILEADV StatInstrVDWrites;
344#endif
345 /** Release statistics: Profiling RTThreadYield calls during status polling. */
346 STAMPROFILEADV StatStatusYields;
347
348 /** Statistics: number of read operations and the time spent reading. */
349 STAMPROFILEADV StatReads;
350 /** Statistics: number of bytes read. */
351 STAMCOUNTER StatBytesRead;
352 /** Statistics: number of write operations and the time spent writing. */
353 STAMPROFILEADV StatWrites;
354 /** Statistics: number of bytes written. */
355 STAMCOUNTER StatBytesWritten;
356 /** Statistics: number of flush operations and the time spend flushing. */
357 STAMPROFILE StatFlushes;
358
359 /** Enable passing through commands directly to the ATAPI drive. */
360 bool fATAPIPassthrough;
361 /** Flag whether to overwrite inquiry data in passthrough mode. */
362 bool fOverwriteInquiry;
363 /** Number of errors we've reported to the release log.
364 * This is to prevent flooding caused by something going horribly wrong.
365 * this value against MAX_LOG_REL_ERRORS in places likely to cause floods
366 * like the ones we currently seeing on the linux smoke tests (2006-11-10). */
367 uint32_t cErrors;
368 /** Timestamp of last started command. 0 if no command pending. */
369 uint64_t u64CmdTS;
370
371 /** The LUN number. */
372 uint32_t iLUN;
373 /** The controller number. */
374 uint8_t iCtl;
375 /** The device number. */
376 uint8_t iDev;
377 /** Set if the device is present. */
378 bool fPresent;
379 /** Explicit alignment. */
380 uint8_t bAlignment2;
381
382 /** The serial number to use for IDENTIFY DEVICE commands. */
383 char szSerialNumber[ATA_SERIAL_NUMBER_LENGTH+1];
384 /** The firmware revision to use for IDENTIFY DEVICE commands. */
385 char szFirmwareRevision[ATA_FIRMWARE_REVISION_LENGTH+1];
386 /** The model number to use for IDENTIFY DEVICE commands. */
387 char szModelNumber[ATA_MODEL_NUMBER_LENGTH+1];
388 /** The vendor identification string for SCSI INQUIRY commands. */
389 char szInquiryVendorId[SCSI_INQUIRY_VENDOR_ID_LENGTH+1];
390 /** The product identification string for SCSI INQUIRY commands. */
391 char szInquiryProductId[SCSI_INQUIRY_PRODUCT_ID_LENGTH+1];
392 /** The revision string for SCSI INQUIRY commands. */
393 char szInquiryRevision[SCSI_INQUIRY_REVISION_LENGTH+1];
394
395 /** Padding the structure to a multiple of 4096 for better I/O buffer alignment. */
396 uint8_t abAlignment4[7 + 3528];
397} ATADEVSTATE;
398AssertCompileMemberAlignment(ATADEVSTATE, cTotalSectors, 8);
399AssertCompileMemberAlignment(ATADEVSTATE, StatATADMA, 8);
400AssertCompileMemberAlignment(ATADEVSTATE, u64CmdTS, 8);
401AssertCompileMemberAlignment(ATADEVSTATE, szSerialNumber, 8);
402AssertCompileSizeAlignment(ATADEVSTATE, 4096); /* To align the buffer on a page boundrary. */
403/** Pointer to the shared state of an ATA device. */
404typedef ATADEVSTATE *PATADEVSTATE;
405
406
407/**
408 * The ring-3 state of an ATA device.
409 *
410 * @implements PDMIBASE
411 * @implements PDMIBLOCKPORT
412 * @implements PDMIMOUNTNOTIFY
413 */
414typedef struct ATADEVSTATER3
415{
416 /** Pointer to the attached driver's base interface. */
417 R3PTRTYPE(PPDMIBASE) pDrvBase;
418 /** Pointer to the attached driver's block interface. */
419 R3PTRTYPE(PPDMIMEDIA) pDrvMedia;
420 /** Pointer to the attached driver's mount interface.
421 * This is NULL if the driver isn't a removable unit. */
422 R3PTRTYPE(PPDMIMOUNT) pDrvMount;
423 /** The base interface. */
424 PDMIBASE IBase;
425 /** The block port interface. */
426 PDMIMEDIAPORT IPort;
427 /** The mount notify interface. */
428 PDMIMOUNTNOTIFY IMountNotify;
429
430 /** The LUN number. */
431 uint32_t iLUN;
432 /** The controller number. */
433 uint8_t iCtl;
434 /** The device number. */
435 uint8_t iDev;
436 /** Explicit alignment. */
437 uint8_t abAlignment2[2];
438 /** The device instance so we can get our bearings from an interface method. */
439 PPDMDEVINSR3 pDevIns;
440
441 /** The current tracklist of the loaded medium if passthrough is used. */
442 R3PTRTYPE(PTRACKLIST) pTrackList;
443} ATADEVSTATER3;
444/** Pointer to the ring-3 state of an ATA device. */
445typedef ATADEVSTATER3 *PATADEVSTATER3;
446
447
448/**
449 * Transfer request forwarded to the async I/O thread.
450 */
451typedef struct ATATransferRequest
452{
453 /** The interface index the request is for. */
454 uint8_t iIf;
455 /** The index of the begin transfer callback to call. */
456 uint8_t iBeginTransfer;
457 /** The index of the source sink callback to call for doing the transfer. */
458 uint8_t iSourceSink;
459 /** Transfer direction. */
460 uint8_t uTxDir;
461 /** How many bytes to transfer. */
462 uint32_t cbTotalTransfer;
463} ATATransferRequest;
464
465
466/**
467 * Abort request forwarded to the async I/O thread.
468 */
469typedef struct ATAAbortRequest
470{
471 /** The interface index the request is for. */
472 uint8_t iIf;
473 /** Flag whether to reset the drive. */
474 bool fResetDrive;
475} ATAAbortRequest;
476
477
478/**
479 * Request type indicator.
480 */
481typedef enum
482{
483 /** Begin a new transfer. */
484 ATA_AIO_NEW = 0,
485 /** Continue a DMA transfer. */
486 ATA_AIO_DMA,
487 /** Continue a PIO transfer. */
488 ATA_AIO_PIO,
489 /** Reset the drives on current controller, stop all transfer activity. */
490 ATA_AIO_RESET_ASSERTED,
491 /** Reset the drives on current controller, resume operation. */
492 ATA_AIO_RESET_CLEARED,
493 /** Abort the current transfer of a particular drive. */
494 ATA_AIO_ABORT
495} ATAAIO;
496
497
498/**
499 * Combining structure for an ATA request to the async I/O thread
500 * started with the request type insicator.
501 */
502typedef struct ATARequest
503{
504 /** Request type. */
505 ATAAIO ReqType;
506 /** Request type dependent data. */
507 union
508 {
509 /** Transfer request specific data. */
510 ATATransferRequest t;
511 /** Abort request specific data. */
512 ATAAbortRequest a;
513 } u;
514} ATARequest;
515
516
517/**
518 * The shared state of an ATA controller.
519 *
520 * Has two devices, the master (0) and the slave (1).
521 */
522typedef struct ATACONTROLLER
523{
524 /** The ATA/ATAPI interfaces of this controller. */
525 ATADEVSTATE aIfs[2];
526
527 /** The base of the first I/O Port range. */
528 RTIOPORT IOPortBase1;
529 /** The base of the second I/O Port range. (0 if none) */
530 RTIOPORT IOPortBase2;
531 /** The assigned IRQ. */
532 uint32_t irq;
533 /** Access critical section */
534 PDMCRITSECT lock;
535
536 /** Selected drive. */
537 uint8_t iSelectedIf;
538 /** The interface on which to handle async I/O. */
539 uint8_t iAIOIf;
540 /** The state of the async I/O thread. */
541 uint8_t uAsyncIOState;
542 /** Flag indicating whether the next transfer is part of the current command. */
543 bool fChainedTransfer;
544 /** Set when the reset processing is currently active on this controller. */
545 bool fReset;
546 /** Flag whether the current transfer needs to be redone. */
547 bool fRedo;
548 /** Flag whether the redo suspend has been finished. */
549 bool fRedoIdle;
550 /** Flag whether the DMA operation to be redone is the final transfer. */
551 bool fRedoDMALastDesc;
552 /** The BusMaster DMA state. */
553 BMDMAState BmDma;
554 /** Pointer to first DMA descriptor. */
555 RTGCPHYS32 GCPhysFirstDMADesc;
556 /** Pointer to last DMA descriptor. */
557 RTGCPHYS32 GCPhysLastDMADesc;
558 /** Pointer to current DMA buffer (for redo operations). */
559 RTGCPHYS32 GCPhysRedoDMABuffer;
560 /** Size of current DMA buffer (for redo operations). */
561 uint32_t cbRedoDMABuffer;
562
563 /** The event semaphore the thread is waiting on for requests. */
564 SUPSEMEVENT hAsyncIOSem;
565 /** The request queue for the AIO thread. One element is always unused. */
566 ATARequest aAsyncIORequests[4];
567 /** The position at which to insert a new request for the AIO thread. */
568 volatile uint8_t AsyncIOReqHead;
569 /** The position at which to get a new request for the AIO thread. */
570 volatile uint8_t AsyncIOReqTail;
571 /** The controller number. */
572 uint8_t iCtl;
573 /** Magic delay before triggering interrupts in DMA mode. */
574 uint32_t msDelayIRQ;
575 /** The lock protecting the request queue. */
576 PDMCRITSECT AsyncIORequestLock;
577
578 /** Timestamp we started the reset. */
579 uint64_t u64ResetTime;
580
581 /** The first port in the first I/O port range, regular operation. */
582 IOMIOPORTHANDLE hIoPorts1First;
583 /** The other ports in the first I/O port range, regular operation. */
584 IOMIOPORTHANDLE hIoPorts1Other;
585 /** The second I/O port range, regular operation. */
586 IOMIOPORTHANDLE hIoPorts2;
587 /** The first I/O port range, empty controller operation. */
588 IOMIOPORTHANDLE hIoPortsEmpty1;
589 /** The second I/O port range, empty controller operation. */
590 IOMIOPORTHANDLE hIoPortsEmpty2;
591
592 /* Statistics */
593 STAMCOUNTER StatAsyncOps;
594 uint64_t StatAsyncMinWait;
595 uint64_t StatAsyncMaxWait;
596 STAMCOUNTER StatAsyncTimeUS;
597 STAMPROFILEADV StatAsyncTime;
598 STAMPROFILE StatLockWait;
599 uint8_t abAlignment4[3328];
600} ATACONTROLLER;
601AssertCompileMemberAlignment(ATACONTROLLER, lock, 8);
602AssertCompileMemberAlignment(ATACONTROLLER, aIfs, 8);
603AssertCompileMemberAlignment(ATACONTROLLER, u64ResetTime, 8);
604AssertCompileMemberAlignment(ATACONTROLLER, StatAsyncOps, 8);
605AssertCompileMemberAlignment(ATACONTROLLER, AsyncIORequestLock, 8);
606AssertCompileSizeAlignment(ATACONTROLLER, 4096); /* To align the controllers, devices and I/O buffers on page boundaries. */
607/** Pointer to the shared state of an ATA controller. */
608typedef ATACONTROLLER *PATACONTROLLER;
609
610
611/**
612 * The ring-3 state of an ATA controller.
613 */
614typedef struct ATACONTROLLERR3
615{
616 /** The ATA/ATAPI interfaces of this controller. */
617 ATADEVSTATER3 aIfs[2];
618
619 /** Pointer to device instance. */
620 PPDMDEVINSR3 pDevIns;
621
622 /** The async I/O thread handle. NIL_RTTHREAD if no thread. */
623 RTTHREAD hAsyncIOThread;
624 /** The event semaphore the thread is waiting on during suspended I/O. */
625 RTSEMEVENT hSuspendIOSem;
626 /** Set when the destroying the device instance and the thread must exit. */
627 uint32_t volatile fShutdown;
628 /** Whether to call PDMDevHlpAsyncNotificationCompleted when idle. */
629 bool volatile fSignalIdle;
630
631 /** The controller number. */
632 uint8_t iCtl;
633
634 uint8_t abAlignment[3];
635} ATACONTROLLERR3;
636/** Pointer to the ring-3 state of an ATA controller. */
637typedef ATACONTROLLERR3 *PATACONTROLLERR3;
638
639
640/** ATA chipset type. */
641typedef enum CHIPSET
642{
643 /** PIIX3 chipset, must be 0 for saved state compatibility */
644 CHIPSET_PIIX3 = 0,
645 /** PIIX4 chipset, must be 1 for saved state compatibility */
646 CHIPSET_PIIX4,
647 /** ICH6 chipset */
648 CHIPSET_ICH6,
649 CHIPSET_32BIT_HACK=0x7fffffff
650} CHIPSET;
651AssertCompileSize(CHIPSET, 4);
652
653/**
654 * The shared state of a ATA PCI device.
655 */
656typedef struct ATASTATE
657{
658 /** The controllers. */
659 ATACONTROLLER aCts[2];
660 /** Flag indicating chipset being emulated. */
661 CHIPSET enmChipset;
662 /** Explicit alignment padding. */
663 uint8_t abAlignment1[7];
664 /** PCI region \#4: Bus-master DMA I/O ports. */
665 IOMIOPORTHANDLE hIoPortsBmDma;
666} ATASTATE;
667/** Pointer to the shared state of an ATA PCI device. */
668typedef ATASTATE *PATASTATE;
669
670
671/**
672 * The ring-3 state of a ATA PCI device.
673 *
674 * @implements PDMILEDPORTS
675 */
676typedef struct ATASTATER3
677{
678 /** The controllers. */
679 ATACONTROLLERR3 aCts[2];
680 /** Status LUN: Base interface. */
681 PDMIBASE IBase;
682 /** Status LUN: Leds interface. */
683 PDMILEDPORTS ILeds;
684 /** Status LUN: Partner of ILeds. */
685 R3PTRTYPE(PPDMILEDCONNECTORS) pLedsConnector;
686 /** Status LUN: Media Notify. */
687 R3PTRTYPE(PPDMIMEDIANOTIFY) pMediaNotify;
688 /** Pointer to device instance (for getting our bearings in interface methods). */
689 PPDMDEVINSR3 pDevIns;
690} ATASTATER3;
691/** Pointer to the ring-3 state of an ATA PCI device. */
692typedef ATASTATER3 *PATASTATER3;
693
694
695/**
696 * The ring-0 state of the ATA PCI device.
697 */
698typedef struct ATASTATER0
699{
700 uint64_t uUnused;
701} ATASTATER0;
702/** Pointer to the ring-0 state of an ATA PCI device. */
703typedef ATASTATER0 *PATASTATER0;
704
705
706/**
707 * The raw-mode state of the ATA PCI device.
708 */
709typedef struct ATASTATERC
710{
711 uint64_t uUnused;
712} ATASTATERC;
713/** Pointer to the raw-mode state of an ATA PCI device. */
714typedef ATASTATERC *PATASTATERC;
715
716
717/** The current context state of an ATA PCI device. */
718typedef CTX_SUFF(ATASTATE) ATASTATECC;
719/** Pointer to the current context state of an ATA PCI device. */
720typedef CTX_SUFF(PATASTATE) PATASTATECC;
721
722
723#ifndef VBOX_DEVICE_STRUCT_TESTCASE
724
725
726#ifdef IN_RING3
727DECLINLINE(void) ataSetStatusValue(PATACONTROLLER pCtl, PATADEVSTATE s, uint8_t stat)
728{
729 /* Freeze status register contents while processing RESET. */
730 if (!pCtl->fReset)
731 {
732 s->uATARegStatus = stat;
733 Log2(("%s: LUN#%d status %#04x\n", __FUNCTION__, s->iLUN, s->uATARegStatus));
734 }
735}
736#endif /* IN_RING3 */
737
738
739DECLINLINE(void) ataSetStatus(PATACONTROLLER pCtl, PATADEVSTATE s, uint8_t stat)
740{
741 /* Freeze status register contents while processing RESET. */
742 if (!pCtl->fReset)
743 {
744 s->uATARegStatus |= stat;
745 Log2(("%s: LUN#%d status %#04x\n", __FUNCTION__, s->iLUN, s->uATARegStatus));
746 }
747}
748
749
750DECLINLINE(void) ataUnsetStatus(PATACONTROLLER pCtl, PATADEVSTATE s, uint8_t stat)
751{
752 /* Freeze status register contents while processing RESET. */
753 if (!pCtl->fReset)
754 {
755 s->uATARegStatus &= ~stat;
756 Log2(("%s: LUN#%d status %#04x\n", __FUNCTION__, s->iLUN, s->uATARegStatus));
757 }
758}
759
760#if defined(IN_RING3) || defined(IN_RING0)
761
762# ifdef IN_RING3
763typedef void FNBEGINTRANSFER(PATACONTROLLER pCtl, PATADEVSTATE s);
764typedef FNBEGINTRANSFER *PFNBEGINTRANSFER;
765typedef bool FNSOURCESINK(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3);
766typedef FNSOURCESINK *PFNSOURCESINK;
767
768static FNBEGINTRANSFER ataR3ReadWriteSectorsBT;
769static FNBEGINTRANSFER ataR3PacketBT;
770static FNBEGINTRANSFER atapiR3CmdBT;
771static FNBEGINTRANSFER atapiR3PassthroughCmdBT;
772
773static FNSOURCESINK ataR3IdentifySS;
774static FNSOURCESINK ataR3FlushSS;
775static FNSOURCESINK ataR3ReadSectorsSS;
776static FNSOURCESINK ataR3WriteSectorsSS;
777static FNSOURCESINK ataR3ExecuteDeviceDiagnosticSS;
778static FNSOURCESINK ataR3TrimSS;
779static FNSOURCESINK ataR3PacketSS;
780static FNSOURCESINK ataR3InitDevParmSS;
781static FNSOURCESINK ataR3RecalibrateSS;
782static FNSOURCESINK atapiR3GetConfigurationSS;
783static FNSOURCESINK atapiR3GetEventStatusNotificationSS;
784static FNSOURCESINK atapiR3IdentifySS;
785static FNSOURCESINK atapiR3InquirySS;
786static FNSOURCESINK atapiR3MechanismStatusSS;
787static FNSOURCESINK atapiR3ModeSenseErrorRecoverySS;
788static FNSOURCESINK atapiR3ModeSenseCDStatusSS;
789static FNSOURCESINK atapiR3ReadSS;
790static FNSOURCESINK atapiR3ReadCapacitySS;
791static FNSOURCESINK atapiR3ReadDiscInformationSS;
792static FNSOURCESINK atapiR3ReadTOCNormalSS;
793static FNSOURCESINK atapiR3ReadTOCMultiSS;
794static FNSOURCESINK atapiR3ReadTOCRawSS;
795static FNSOURCESINK atapiR3ReadTrackInformationSS;
796static FNSOURCESINK atapiR3RequestSenseSS;
797static FNSOURCESINK atapiR3PassthroughSS;
798static FNSOURCESINK atapiR3ReadDVDStructureSS;
799# endif /* IN_RING3 */
800
801/**
802 * Begin of transfer function indexes for g_apfnBeginTransFuncs.
803 */
804typedef enum ATAFNBT
805{
806 ATAFN_BT_NULL = 0,
807 ATAFN_BT_READ_WRITE_SECTORS,
808 ATAFN_BT_PACKET,
809 ATAFN_BT_ATAPI_CMD,
810 ATAFN_BT_ATAPI_PASSTHROUGH_CMD,
811 ATAFN_BT_MAX
812} ATAFNBT;
813
814# ifdef IN_RING3
815/**
816 * Array of end transfer functions, the index is ATAFNET.
817 * Make sure ATAFNET and this array match!
818 */
819static const PFNBEGINTRANSFER g_apfnBeginTransFuncs[ATAFN_BT_MAX] =
820{
821 NULL,
822 ataR3ReadWriteSectorsBT,
823 ataR3PacketBT,
824 atapiR3CmdBT,
825 atapiR3PassthroughCmdBT,
826};
827# endif /* IN_RING3 */
828
829/**
830 * Source/sink function indexes for g_apfnSourceSinkFuncs.
831 */
832typedef enum ATAFNSS
833{
834 ATAFN_SS_NULL = 0,
835 ATAFN_SS_IDENTIFY,
836 ATAFN_SS_FLUSH,
837 ATAFN_SS_READ_SECTORS,
838 ATAFN_SS_WRITE_SECTORS,
839 ATAFN_SS_EXECUTE_DEVICE_DIAGNOSTIC,
840 ATAFN_SS_TRIM,
841 ATAFN_SS_PACKET,
842 ATAFN_SS_INITIALIZE_DEVICE_PARAMETERS,
843 ATAFN_SS_RECALIBRATE,
844 ATAFN_SS_ATAPI_GET_CONFIGURATION,
845 ATAFN_SS_ATAPI_GET_EVENT_STATUS_NOTIFICATION,
846 ATAFN_SS_ATAPI_IDENTIFY,
847 ATAFN_SS_ATAPI_INQUIRY,
848 ATAFN_SS_ATAPI_MECHANISM_STATUS,
849 ATAFN_SS_ATAPI_MODE_SENSE_ERROR_RECOVERY,
850 ATAFN_SS_ATAPI_MODE_SENSE_CD_STATUS,
851 ATAFN_SS_ATAPI_READ,
852 ATAFN_SS_ATAPI_READ_CAPACITY,
853 ATAFN_SS_ATAPI_READ_DISC_INFORMATION,
854 ATAFN_SS_ATAPI_READ_TOC_NORMAL,
855 ATAFN_SS_ATAPI_READ_TOC_MULTI,
856 ATAFN_SS_ATAPI_READ_TOC_RAW,
857 ATAFN_SS_ATAPI_READ_TRACK_INFORMATION,
858 ATAFN_SS_ATAPI_REQUEST_SENSE,
859 ATAFN_SS_ATAPI_PASSTHROUGH,
860 ATAFN_SS_ATAPI_READ_DVD_STRUCTURE,
861 ATAFN_SS_MAX
862} ATAFNSS;
863
864# ifdef IN_RING3
865/**
866 * Array of source/sink functions, the index is ATAFNSS.
867 * Make sure ATAFNSS and this array match!
868 */
869static const PFNSOURCESINK g_apfnSourceSinkFuncs[ATAFN_SS_MAX] =
870{
871 NULL,
872 ataR3IdentifySS,
873 ataR3FlushSS,
874 ataR3ReadSectorsSS,
875 ataR3WriteSectorsSS,
876 ataR3ExecuteDeviceDiagnosticSS,
877 ataR3TrimSS,
878 ataR3PacketSS,
879 ataR3InitDevParmSS,
880 ataR3RecalibrateSS,
881 atapiR3GetConfigurationSS,
882 atapiR3GetEventStatusNotificationSS,
883 atapiR3IdentifySS,
884 atapiR3InquirySS,
885 atapiR3MechanismStatusSS,
886 atapiR3ModeSenseErrorRecoverySS,
887 atapiR3ModeSenseCDStatusSS,
888 atapiR3ReadSS,
889 atapiR3ReadCapacitySS,
890 atapiR3ReadDiscInformationSS,
891 atapiR3ReadTOCNormalSS,
892 atapiR3ReadTOCMultiSS,
893 atapiR3ReadTOCRawSS,
894 atapiR3ReadTrackInformationSS,
895 atapiR3RequestSenseSS,
896 atapiR3PassthroughSS,
897 atapiR3ReadDVDStructureSS
898};
899# endif /* IN_RING3 */
900
901
902static const ATARequest g_ataDMARequest = { ATA_AIO_DMA, { { 0, 0, 0, 0, 0 } } };
903static const ATARequest g_ataPIORequest = { ATA_AIO_PIO, { { 0, 0, 0, 0, 0 } } };
904# ifdef IN_RING3
905static const ATARequest g_ataResetARequest = { ATA_AIO_RESET_ASSERTED, { { 0, 0, 0, 0, 0 } } };
906static const ATARequest g_ataResetCRequest = { ATA_AIO_RESET_CLEARED, { { 0, 0, 0, 0, 0 } } };
907# endif
908
909# ifdef IN_RING3
910static void ataR3AsyncIOClearRequests(PPDMDEVINS pDevIns, PATACONTROLLER pCtl)
911{
912 int rc = PDMDevHlpCritSectEnter(pDevIns, &pCtl->AsyncIORequestLock, VINF_SUCCESS);
913 PDM_CRITSECT_RELEASE_ASSERT_RC_DEV(pDevIns, &pCtl->AsyncIORequestLock, rc);
914
915 pCtl->AsyncIOReqHead = 0;
916 pCtl->AsyncIOReqTail = 0;
917
918 rc = PDMDevHlpCritSectLeave(pDevIns, &pCtl->AsyncIORequestLock);
919 AssertRC(rc);
920}
921# endif /* IN_RING3 */
922
923static void ataHCAsyncIOPutRequest(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, const ATARequest *pReq)
924{
925 int rc = PDMDevHlpCritSectEnter(pDevIns, &pCtl->AsyncIORequestLock, VINF_SUCCESS);
926 PDM_CRITSECT_RELEASE_ASSERT_RC_DEV(pDevIns, &pCtl->AsyncIORequestLock, rc);
927
928 uint8_t const iAsyncIORequest = pCtl->AsyncIOReqHead % RT_ELEMENTS(pCtl->aAsyncIORequests);
929 Assert((iAsyncIORequest + 1) % RT_ELEMENTS(pCtl->aAsyncIORequests) != pCtl->AsyncIOReqTail);
930 memcpy(&pCtl->aAsyncIORequests[iAsyncIORequest], pReq, sizeof(*pReq));
931 pCtl->AsyncIOReqHead = (iAsyncIORequest + 1) % RT_ELEMENTS(pCtl->aAsyncIORequests);
932
933 rc = PDMDevHlpCritSectLeave(pDevIns, &pCtl->AsyncIORequestLock);
934 AssertRC(rc);
935
936 rc = PDMDevHlpCritSectScheduleExitEvent(pDevIns, &pCtl->lock, pCtl->hAsyncIOSem);
937 if (RT_FAILURE(rc))
938 {
939 rc = PDMDevHlpSUPSemEventSignal(pDevIns, pCtl->hAsyncIOSem);
940 AssertRC(rc);
941 }
942}
943
944# ifdef IN_RING3
945
946static const ATARequest *ataR3AsyncIOGetCurrentRequest(PPDMDEVINS pDevIns, PATACONTROLLER pCtl)
947{
948 const ATARequest *pReq;
949
950 int rc = PDMDevHlpCritSectEnter(pDevIns, &pCtl->AsyncIORequestLock, VINF_SUCCESS);
951 PDM_CRITSECT_RELEASE_ASSERT_RC_DEV(pDevIns, &pCtl->AsyncIORequestLock, rc);
952
953 if (pCtl->AsyncIOReqHead != pCtl->AsyncIOReqTail)
954 pReq = &pCtl->aAsyncIORequests[pCtl->AsyncIOReqTail];
955 else
956 pReq = NULL;
957
958 rc = PDMDevHlpCritSectLeave(pDevIns, &pCtl->AsyncIORequestLock);
959 AssertRC(rc);
960 return pReq;
961}
962
963
964/**
965 * Remove the request with the given type, as it's finished. The request
966 * is not removed blindly, as this could mean a RESET request that is not
967 * yet processed (but has cleared the request queue) is lost.
968 *
969 * @param pDevIns The device instance.
970 * @param pCtl Controller for which to remove the request.
971 * @param ReqType Type of the request to remove.
972 */
973static void ataR3AsyncIORemoveCurrentRequest(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, ATAAIO ReqType)
974{
975 int rc = PDMDevHlpCritSectEnter(pDevIns, &pCtl->AsyncIORequestLock, VINF_SUCCESS);
976 PDM_CRITSECT_RELEASE_ASSERT_RC_DEV(pDevIns, &pCtl->AsyncIORequestLock, rc);
977
978 if (pCtl->AsyncIOReqHead != pCtl->AsyncIOReqTail && pCtl->aAsyncIORequests[pCtl->AsyncIOReqTail].ReqType == ReqType)
979 {
980 pCtl->AsyncIOReqTail++;
981 pCtl->AsyncIOReqTail %= RT_ELEMENTS(pCtl->aAsyncIORequests);
982 }
983
984 rc = PDMDevHlpCritSectLeave(pDevIns, &pCtl->AsyncIORequestLock);
985 AssertRC(rc);
986}
987
988
989/**
990 * Dump the request queue for a particular controller. First dump the queue
991 * contents, then the already processed entries, as long as they haven't been
992 * overwritten.
993 *
994 * @param pDevIns The device instance.
995 * @param pCtl Controller for which to dump the queue.
996 */
997static void ataR3AsyncIODumpRequests(PPDMDEVINS pDevIns, PATACONTROLLER pCtl)
998{
999 int rc = PDMDevHlpCritSectEnter(pDevIns, &pCtl->AsyncIORequestLock, VINF_SUCCESS);
1000 PDM_CRITSECT_RELEASE_ASSERT_RC_DEV(pDevIns, &pCtl->AsyncIORequestLock, rc);
1001
1002 LogRel(("PIIX3 ATA: Ctl#%d: request queue dump (topmost is current):\n", pCtl->iCtl));
1003 uint8_t curr = pCtl->AsyncIOReqTail;
1004 do
1005 {
1006 if (curr == pCtl->AsyncIOReqHead)
1007 LogRel(("PIIX3 ATA: Ctl#%d: processed requests (topmost is oldest):\n", pCtl->iCtl));
1008 switch (pCtl->aAsyncIORequests[curr].ReqType)
1009 {
1010 case ATA_AIO_NEW:
1011 LogRel(("new transfer request, iIf=%d iBeginTransfer=%d iSourceSink=%d cbTotalTransfer=%d uTxDir=%d\n",
1012 pCtl->aAsyncIORequests[curr].u.t.iIf, pCtl->aAsyncIORequests[curr].u.t.iBeginTransfer,
1013 pCtl->aAsyncIORequests[curr].u.t.iSourceSink, pCtl->aAsyncIORequests[curr].u.t.cbTotalTransfer,
1014 pCtl->aAsyncIORequests[curr].u.t.uTxDir));
1015 break;
1016 case ATA_AIO_DMA:
1017 LogRel(("dma transfer continuation\n"));
1018 break;
1019 case ATA_AIO_PIO:
1020 LogRel(("pio transfer continuation\n"));
1021 break;
1022 case ATA_AIO_RESET_ASSERTED:
1023 LogRel(("reset asserted request\n"));
1024 break;
1025 case ATA_AIO_RESET_CLEARED:
1026 LogRel(("reset cleared request\n"));
1027 break;
1028 case ATA_AIO_ABORT:
1029 LogRel(("abort request, iIf=%d fResetDrive=%d\n", pCtl->aAsyncIORequests[curr].u.a.iIf,
1030 pCtl->aAsyncIORequests[curr].u.a.fResetDrive));
1031 break;
1032 default:
1033 LogRel(("unknown request %d\n", pCtl->aAsyncIORequests[curr].ReqType));
1034 }
1035 curr = (curr + 1) % RT_ELEMENTS(pCtl->aAsyncIORequests);
1036 } while (curr != pCtl->AsyncIOReqTail);
1037
1038 rc = PDMDevHlpCritSectLeave(pDevIns, &pCtl->AsyncIORequestLock);
1039 AssertRC(rc);
1040}
1041
1042
1043/**
1044 * Checks whether the request queue for a particular controller is empty
1045 * or whether a particular controller is idle.
1046 *
1047 * @param pDevIns The device instance.
1048 * @param pCtl Controller for which to check the queue.
1049 * @param fStrict If set then the controller is checked to be idle.
1050 */
1051static bool ataR3AsyncIOIsIdle(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, bool fStrict)
1052{
1053 int rc = PDMDevHlpCritSectEnter(pDevIns, &pCtl->AsyncIORequestLock, VINF_SUCCESS);
1054 PDM_CRITSECT_RELEASE_ASSERT_RC_DEV(pDevIns, &pCtl->AsyncIORequestLock, rc);
1055
1056 bool fIdle = pCtl->fRedoIdle;
1057 if (!fIdle)
1058 fIdle = (pCtl->AsyncIOReqHead == pCtl->AsyncIOReqTail);
1059 if (fStrict)
1060 fIdle &= (pCtl->uAsyncIOState == ATA_AIO_NEW);
1061
1062 rc = PDMDevHlpCritSectLeave(pDevIns, &pCtl->AsyncIORequestLock);
1063 AssertRC(rc);
1064 return fIdle;
1065}
1066
1067
1068/**
1069 * Send a transfer request to the async I/O thread.
1070 *
1071 * @param pDevIns The device instance.
1072 * @param pCtl The ATA controller.
1073 * @param s Pointer to the ATA device state data.
1074 * @param cbTotalTransfer Data transfer size.
1075 * @param uTxDir Data transfer direction.
1076 * @param iBeginTransfer Index of BeginTransfer callback.
1077 * @param iSourceSink Index of SourceSink callback.
1078 * @param fChainedTransfer Whether this is a transfer that is part of the previous command/transfer.
1079 */
1080static void ataR3StartTransfer(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s,
1081 uint32_t cbTotalTransfer, uint8_t uTxDir, ATAFNBT iBeginTransfer,
1082 ATAFNSS iSourceSink, bool fChainedTransfer)
1083{
1084 ATARequest Req;
1085
1086 Assert(PDMDevHlpCritSectIsOwner(pDevIns, &pCtl->lock));
1087
1088 /* Do not issue new requests while the RESET line is asserted. */
1089 if (pCtl->fReset)
1090 {
1091 Log2(("%s: Ctl#%d: suppressed new request as RESET is active\n", __FUNCTION__, pCtl->iCtl));
1092 return;
1093 }
1094
1095 /* If the controller is already doing something else right now, ignore
1096 * the command that is being submitted. Some broken guests issue commands
1097 * twice (e.g. the Linux kernel that comes with Acronis True Image 8). */
1098 if (!fChainedTransfer && !ataR3AsyncIOIsIdle(pDevIns, pCtl, true /*fStrict*/))
1099 {
1100 Log(("%s: Ctl#%d: ignored command %#04x, controller state %d\n", __FUNCTION__, pCtl->iCtl, s->uATARegCommand, pCtl->uAsyncIOState));
1101 LogRel(("PIIX3 IDE: guest issued command %#04x while controller busy\n", s->uATARegCommand));
1102 return;
1103 }
1104
1105 Req.ReqType = ATA_AIO_NEW;
1106 if (fChainedTransfer)
1107 Req.u.t.iIf = pCtl->iAIOIf;
1108 else
1109 Req.u.t.iIf = pCtl->iSelectedIf;
1110 Req.u.t.cbTotalTransfer = cbTotalTransfer;
1111 Req.u.t.uTxDir = uTxDir;
1112 Req.u.t.iBeginTransfer = iBeginTransfer;
1113 Req.u.t.iSourceSink = iSourceSink;
1114 ataSetStatusValue(pCtl, s, ATA_STAT_BUSY);
1115 pCtl->fChainedTransfer = fChainedTransfer;
1116
1117 /*
1118 * Kick the worker thread into action.
1119 */
1120 Log2(("%s: Ctl#%d: message to async I/O thread, new request\n", __FUNCTION__, pCtl->iCtl));
1121 ataHCAsyncIOPutRequest(pDevIns, pCtl, &Req);
1122}
1123
1124
1125/**
1126 * Send an abort command request to the async I/O thread.
1127 *
1128 * @param pDevIns The device instance.
1129 * @param pCtl The ATA controller.
1130 * @param s Pointer to the ATA device state data.
1131 * @param fResetDrive Whether to reset the drive or just abort a command.
1132 */
1133static void ataR3AbortCurrentCommand(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, bool fResetDrive)
1134{
1135 ATARequest Req;
1136
1137 Assert(PDMDevHlpCritSectIsOwner(pDevIns, &pCtl->lock));
1138
1139 /* Do not issue new requests while the RESET line is asserted. */
1140 if (pCtl->fReset)
1141 {
1142 Log2(("%s: Ctl#%d: suppressed aborting command as RESET is active\n", __FUNCTION__, pCtl->iCtl));
1143 return;
1144 }
1145
1146 Req.ReqType = ATA_AIO_ABORT;
1147 Req.u.a.iIf = pCtl->iSelectedIf;
1148 Req.u.a.fResetDrive = fResetDrive;
1149 ataSetStatus(pCtl, s, ATA_STAT_BUSY);
1150 Log2(("%s: Ctl#%d: message to async I/O thread, abort command on LUN#%d\n", __FUNCTION__, pCtl->iCtl, s->iLUN));
1151 ataHCAsyncIOPutRequest(pDevIns, pCtl, &Req);
1152}
1153
1154# endif /* IN_RING3 */
1155
1156/**
1157 * Set the internal interrupt pending status, update INTREQ as appropriate.
1158 *
1159 * @param pDevIns The device instance.
1160 * @param pCtl The ATA controller.
1161 * @param s Pointer to the ATA device state data.
1162 */
1163static void ataHCSetIRQ(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s)
1164{
1165 if (!s->fIrqPending)
1166 {
1167 if (!(s->uATARegDevCtl & ATA_DEVCTL_DISABLE_IRQ))
1168 {
1169 Log2(("%s: LUN#%d asserting IRQ\n", __FUNCTION__, s->iLUN));
1170 /* The BMDMA unit unconditionally sets BM_STATUS_INT if the interrupt
1171 * line is asserted. It monitors the line for a rising edge. */
1172 pCtl->BmDma.u8Status |= BM_STATUS_INT;
1173 /* Only actually set the IRQ line if updating the currently selected drive. */
1174 if (s == &pCtl->aIfs[pCtl->iSelectedIf & ATA_SELECTED_IF_MASK])
1175 {
1176 /** @todo experiment with adaptive IRQ delivery: for reads it is
1177 * better to wait for IRQ delivery, as it reduces latency. */
1178 if (pCtl->irq == 16)
1179 PDMDevHlpPCISetIrq(pDevIns, 0, 1);
1180 else
1181 PDMDevHlpISASetIrq(pDevIns, pCtl->irq, 1);
1182 }
1183 }
1184 s->fIrqPending = true;
1185 }
1186}
1187
1188#endif /* IN_RING0 || IN_RING3 */
1189
1190/**
1191 * Clear the internal interrupt pending status, update INTREQ as appropriate.
1192 *
1193 * @param pDevIns The device instance.
1194 * @param pCtl The ATA controller.
1195 * @param s Pointer to the ATA device state data.
1196 */
1197static void ataUnsetIRQ(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s)
1198{
1199 if (s->fIrqPending)
1200 {
1201 if (!(s->uATARegDevCtl & ATA_DEVCTL_DISABLE_IRQ))
1202 {
1203 Log2(("%s: LUN#%d deasserting IRQ\n", __FUNCTION__, s->iLUN));
1204 /* Only actually unset the IRQ line if updating the currently selected drive. */
1205 if (s == &pCtl->aIfs[pCtl->iSelectedIf & ATA_SELECTED_IF_MASK])
1206 {
1207 if (pCtl->irq == 16)
1208 PDMDevHlpPCISetIrq(pDevIns, 0, 0);
1209 else
1210 PDMDevHlpISASetIrq(pDevIns, pCtl->irq, 0);
1211 }
1212 }
1213 s->fIrqPending = false;
1214 }
1215}
1216
1217#if defined(IN_RING0) || defined(IN_RING3)
1218
1219static void ataHCPIOTransferStart(PATACONTROLLER pCtl, PATADEVSTATE s, uint32_t start, uint32_t size)
1220{
1221 Log2(("%s: LUN#%d start %d size %d\n", __FUNCTION__, s->iLUN, start, size));
1222 s->iIOBufferPIODataStart = start;
1223 s->iIOBufferPIODataEnd = start + size;
1224 ataSetStatus(pCtl, s, ATA_STAT_DRQ | ATA_STAT_SEEK);
1225 ataUnsetStatus(pCtl, s, ATA_STAT_BUSY);
1226}
1227
1228
1229static void ataHCPIOTransferStop(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s)
1230{
1231 Log2(("%s: LUN#%d\n", __FUNCTION__, s->iLUN));
1232 if (s->fATAPITransfer)
1233 {
1234 s->uATARegNSector = (s->uATARegNSector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
1235 Log2(("%s: interrupt reason %#04x\n", __FUNCTION__, s->uATARegNSector));
1236 ataHCSetIRQ(pDevIns, pCtl, s);
1237 s->fATAPITransfer = false;
1238 }
1239 s->cbTotalTransfer = 0;
1240 s->cbElementaryTransfer = 0;
1241 s->iIOBufferPIODataStart = 0;
1242 s->iIOBufferPIODataEnd = 0;
1243 s->iBeginTransfer = ATAFN_BT_NULL;
1244 s->iSourceSink = ATAFN_SS_NULL;
1245}
1246
1247
1248static void ataHCPIOTransferLimitATAPI(PATADEVSTATE s)
1249{
1250 uint32_t cbLimit, cbTransfer;
1251
1252 cbLimit = s->cbPIOTransferLimit;
1253 /* Use maximum transfer size if the guest requested 0. Avoids a hang. */
1254 if (cbLimit == 0)
1255 cbLimit = 0xfffe;
1256 Log2(("%s: byte count limit=%d\n", __FUNCTION__, cbLimit));
1257 if (cbLimit == 0xffff)
1258 cbLimit--;
1259 cbTransfer = RT_MIN(s->cbTotalTransfer, s->iIOBufferEnd - s->iIOBufferCur);
1260 if (cbTransfer > cbLimit)
1261 {
1262 /* Byte count limit for clipping must be even in this case */
1263 if (cbLimit & 1)
1264 cbLimit--;
1265 cbTransfer = cbLimit;
1266 }
1267 s->uATARegLCyl = cbTransfer;
1268 s->uATARegHCyl = cbTransfer >> 8;
1269 s->cbElementaryTransfer = cbTransfer;
1270}
1271
1272# ifdef IN_RING3
1273
1274/**
1275 * Enters the lock protecting the controller data against concurrent access.
1276 *
1277 * @param pDevIns The device instance.
1278 * @param pCtl The controller to lock.
1279 */
1280DECLINLINE(void) ataR3LockEnter(PPDMDEVINS pDevIns, PATACONTROLLER pCtl)
1281{
1282 STAM_PROFILE_START(&pCtl->StatLockWait, a);
1283 int const rcLock = PDMDevHlpCritSectEnter(pDevIns, &pCtl->lock, VINF_SUCCESS);
1284 PDM_CRITSECT_RELEASE_ASSERT_RC_DEV(pDevIns, &pCtl->lock, rcLock);
1285 STAM_PROFILE_STOP(&pCtl->StatLockWait, a);
1286}
1287
1288/**
1289 * Leaves the lock protecting the controller against concurrent data access.
1290 *
1291 * @param pDevIns The device instance.
1292 * @param pCtl The controller to unlock.
1293 */
1294DECLINLINE(void) ataR3LockLeave(PPDMDEVINS pDevIns, PATACONTROLLER pCtl)
1295{
1296 PDMDevHlpCritSectLeave(pDevIns, &pCtl->lock);
1297}
1298
1299static uint32_t ataR3GetNSectors(PATADEVSTATE s)
1300{
1301 /* 0 means either 256 (LBA28) or 65536 (LBA48) sectors. */
1302 if (s->fLBA48)
1303 {
1304 if (!s->uATARegNSector && !s->uATARegNSectorHOB)
1305 return 65536;
1306 else
1307 return s->uATARegNSectorHOB << 8 | s->uATARegNSector;
1308 }
1309 else
1310 {
1311 if (!s->uATARegNSector)
1312 return 256;
1313 else
1314 return s->uATARegNSector;
1315 }
1316}
1317
1318
1319static void ataR3PadString(uint8_t *pbDst, const char *pbSrc, uint32_t cbSize)
1320{
1321 for (uint32_t i = 0; i < cbSize; i++)
1322 {
1323 if (*pbSrc)
1324 pbDst[i ^ 1] = *pbSrc++;
1325 else
1326 pbDst[i ^ 1] = ' ';
1327 }
1328}
1329
1330
1331#if 0 /* unused */
1332/**
1333 * Compares two MSF values.
1334 *
1335 * @returns 1 if the first value is greater than the second value.
1336 * 0 if both are equal
1337 * -1 if the first value is smaller than the second value.
1338 */
1339DECLINLINE(int) atapiCmpMSF(const uint8_t *pbMSF1, const uint8_t *pbMSF2)
1340{
1341 int iRes = 0;
1342
1343 for (unsigned i = 0; i < 3; i++)
1344 {
1345 if (pbMSF1[i] < pbMSF2[i])
1346 {
1347 iRes = -1;
1348 break;
1349 }
1350 else if (pbMSF1[i] > pbMSF2[i])
1351 {
1352 iRes = 1;
1353 break;
1354 }
1355 }
1356
1357 return iRes;
1358}
1359#endif /* unused */
1360
1361static void ataR3CmdOK(PATACONTROLLER pCtl, PATADEVSTATE s, uint8_t status)
1362{
1363 s->uATARegError = 0; /* Not needed by ATA spec, but cannot hurt. */
1364 ataSetStatusValue(pCtl, s, ATA_STAT_READY | status);
1365}
1366
1367
1368static void ataR3CmdError(PATACONTROLLER pCtl, PATADEVSTATE s, uint8_t uErrorCode)
1369{
1370 Log(("%s: code=%#x\n", __FUNCTION__, uErrorCode));
1371 Assert(uErrorCode);
1372 s->uATARegError = uErrorCode;
1373 ataSetStatusValue(pCtl, s, ATA_STAT_READY | ATA_STAT_SEEK | ATA_STAT_ERR);
1374 s->cbTotalTransfer = 0;
1375 s->cbElementaryTransfer = 0;
1376 s->iIOBufferCur = 0;
1377 s->iIOBufferEnd = 0;
1378 s->uTxDir = PDMMEDIATXDIR_NONE;
1379 s->iBeginTransfer = ATAFN_BT_NULL;
1380 s->iSourceSink = ATAFN_SS_NULL;
1381}
1382
1383static uint32_t ataR3Checksum(void* ptr, size_t count)
1384{
1385 uint8_t u8Sum = 0xa5, *p = (uint8_t*)ptr;
1386 size_t i;
1387
1388 for (i = 0; i < count; i++)
1389 {
1390 u8Sum += *p++;
1391 }
1392
1393 return (uint8_t)-(int32_t)u8Sum;
1394}
1395
1396/**
1397 * Sink/Source: IDENTIFY
1398 */
1399static bool ataR3IdentifySS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
1400{
1401 uint16_t *p;
1402 RT_NOREF(pDevIns);
1403
1404 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
1405 Assert(s->cbElementaryTransfer == 512);
1406
1407 p = (uint16_t *)&s->abIOBuffer[0];
1408 memset(p, 0, 512);
1409 p[0] = RT_H2LE_U16(0x0040);
1410 p[1] = RT_H2LE_U16(RT_MIN(s->PCHSGeometry.cCylinders, 16383));
1411 p[3] = RT_H2LE_U16(s->PCHSGeometry.cHeads);
1412 /* Block size; obsolete, but required for the BIOS. */
1413 p[5] = RT_H2LE_U16(s->cbSector);
1414 p[6] = RT_H2LE_U16(s->PCHSGeometry.cSectors);
1415 ataR3PadString((uint8_t *)(p + 10), s->szSerialNumber, ATA_SERIAL_NUMBER_LENGTH); /* serial number */
1416 p[20] = RT_H2LE_U16(3); /* XXX: retired, cache type */
1417 p[21] = RT_H2LE_U16(512); /* XXX: retired, cache size in sectors */
1418 p[22] = RT_H2LE_U16(0); /* ECC bytes per sector */
1419 ataR3PadString((uint8_t *)(p + 23), s->szFirmwareRevision, ATA_FIRMWARE_REVISION_LENGTH); /* firmware version */
1420 ataR3PadString((uint8_t *)(p + 27), s->szModelNumber, ATA_MODEL_NUMBER_LENGTH); /* model */
1421# if ATA_MAX_MULT_SECTORS > 1
1422 p[47] = RT_H2LE_U16(0x8000 | ATA_MAX_MULT_SECTORS);
1423# endif
1424 p[48] = RT_H2LE_U16(1); /* dword I/O, used by the BIOS */
1425 p[49] = RT_H2LE_U16(1 << 11 | 1 << 9 | 1 << 8); /* DMA and LBA supported */
1426 p[50] = RT_H2LE_U16(1 << 14); /* No drive specific standby timer minimum */
1427 p[51] = RT_H2LE_U16(240); /* PIO transfer cycle */
1428 p[52] = RT_H2LE_U16(240); /* DMA transfer cycle */
1429 p[53] = RT_H2LE_U16(1 | 1 << 1 | 1 << 2); /* words 54-58,64-70,88 valid */
1430 p[54] = RT_H2LE_U16(RT_MIN(s->XCHSGeometry.cCylinders, 16383));
1431 p[55] = RT_H2LE_U16(s->XCHSGeometry.cHeads);
1432 p[56] = RT_H2LE_U16(s->XCHSGeometry.cSectors);
1433 p[57] = RT_H2LE_U16( RT_MIN(s->XCHSGeometry.cCylinders, 16383)
1434 * s->XCHSGeometry.cHeads
1435 * s->XCHSGeometry.cSectors);
1436 p[58] = RT_H2LE_U16( RT_MIN(s->XCHSGeometry.cCylinders, 16383)
1437 * s->XCHSGeometry.cHeads
1438 * s->XCHSGeometry.cSectors >> 16);
1439 if (s->cMultSectors)
1440 p[59] = RT_H2LE_U16(0x100 | s->cMultSectors);
1441 if (s->cTotalSectors <= (1 << 28) - 1)
1442 {
1443 p[60] = RT_H2LE_U16(s->cTotalSectors);
1444 p[61] = RT_H2LE_U16(s->cTotalSectors >> 16);
1445 }
1446 else
1447 {
1448 /* Report maximum number of sectors possible with LBA28 */
1449 p[60] = RT_H2LE_U16(((1 << 28) - 1) & 0xffff);
1450 p[61] = RT_H2LE_U16(((1 << 28) - 1) >> 16);
1451 }
1452 p[63] = RT_H2LE_U16(ATA_TRANSFER_ID(ATA_MODE_MDMA, ATA_MDMA_MODE_MAX, s->uATATransferMode)); /* MDMA modes supported / mode enabled */
1453 p[64] = RT_H2LE_U16(ATA_PIO_MODE_MAX > 2 ? (1 << (ATA_PIO_MODE_MAX - 2)) - 1 : 0); /* PIO modes beyond PIO2 supported */
1454 p[65] = RT_H2LE_U16(120); /* minimum DMA multiword tx cycle time */
1455 p[66] = RT_H2LE_U16(120); /* recommended DMA multiword tx cycle time */
1456 p[67] = RT_H2LE_U16(120); /* minimum PIO cycle time without flow control */
1457 p[68] = RT_H2LE_U16(120); /* minimum PIO cycle time with IORDY flow control */
1458 if ( pDevR3->pDrvMedia->pfnDiscard
1459 || s->cbSector != 512
1460 || pDevR3->pDrvMedia->pfnIsNonRotational(pDevR3->pDrvMedia))
1461 {
1462 p[80] = RT_H2LE_U16(0x1f0); /* support everything up to ATA/ATAPI-8 ACS */
1463 p[81] = RT_H2LE_U16(0x28); /* conforms to ATA/ATAPI-8 ACS */
1464 }
1465 else
1466 {
1467 p[80] = RT_H2LE_U16(0x7e); /* support everything up to ATA/ATAPI-6 */
1468 p[81] = RT_H2LE_U16(0x22); /* conforms to ATA/ATAPI-6 */
1469 }
1470 p[82] = RT_H2LE_U16(1 << 3 | 1 << 5 | 1 << 6); /* supports power management, write cache and look-ahead */
1471 if (s->cTotalSectors <= (1 << 28) - 1)
1472 p[83] = RT_H2LE_U16(1 << 14 | 1 << 12); /* supports FLUSH CACHE */
1473 else
1474 p[83] = RT_H2LE_U16(1 << 14 | 1 << 10 | 1 << 12 | 1 << 13); /* supports LBA48, FLUSH CACHE and FLUSH CACHE EXT */
1475 p[84] = RT_H2LE_U16(1 << 14);
1476 p[85] = RT_H2LE_U16(1 << 3 | 1 << 5 | 1 << 6); /* enabled power management, write cache and look-ahead */
1477 if (s->cTotalSectors <= (1 << 28) - 1)
1478 p[86] = RT_H2LE_U16(1 << 12); /* enabled FLUSH CACHE */
1479 else
1480 p[86] = RT_H2LE_U16(1 << 10 | 1 << 12 | 1 << 13); /* enabled LBA48, FLUSH CACHE and FLUSH CACHE EXT */
1481 p[87] = RT_H2LE_U16(1 << 14);
1482 p[88] = RT_H2LE_U16(ATA_TRANSFER_ID(ATA_MODE_UDMA, ATA_UDMA_MODE_MAX, s->uATATransferMode)); /* UDMA modes supported / mode enabled */
1483 p[93] = RT_H2LE_U16((1 | 1 << 1) << ((s->iLUN & 1) == 0 ? 0 : 8) | 1 << 13 | 1 << 14);
1484 if (s->cTotalSectors > (1 << 28) - 1)
1485 {
1486 p[100] = RT_H2LE_U16(s->cTotalSectors);
1487 p[101] = RT_H2LE_U16(s->cTotalSectors >> 16);
1488 p[102] = RT_H2LE_U16(s->cTotalSectors >> 32);
1489 p[103] = RT_H2LE_U16(s->cTotalSectors >> 48);
1490 }
1491
1492 if (s->cbSector != 512)
1493 {
1494 uint32_t cSectorSizeInWords = s->cbSector / sizeof(uint16_t);
1495 /* Enable reporting of logical sector size. */
1496 p[106] |= RT_H2LE_U16(RT_BIT(12) | RT_BIT(14));
1497 p[117] = RT_H2LE_U16(cSectorSizeInWords);
1498 p[118] = RT_H2LE_U16(cSectorSizeInWords >> 16);
1499 }
1500
1501 if (pDevR3->pDrvMedia->pfnDiscard) /** @todo Set bit 14 in word 69 too? (Deterministic read after TRIM). */
1502 p[169] = RT_H2LE_U16(1); /* DATA SET MANAGEMENT command supported. */
1503 if (pDevR3->pDrvMedia->pfnIsNonRotational(pDevR3->pDrvMedia))
1504 p[217] = RT_H2LE_U16(1); /* Non-rotational medium */
1505 uint32_t uCsum = ataR3Checksum(p, 510);
1506 p[255] = RT_H2LE_U16(0xa5 | (uCsum << 8)); /* Integrity word */
1507 s->iSourceSink = ATAFN_SS_NULL;
1508 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
1509 return false;
1510}
1511
1512
1513/**
1514 * Sink/Source: FLUSH
1515 */
1516static bool ataR3FlushSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
1517{
1518 int rc;
1519
1520 Assert(s->uTxDir == PDMMEDIATXDIR_NONE);
1521 Assert(!s->cbElementaryTransfer);
1522
1523 ataR3LockLeave(pDevIns, pCtl);
1524
1525 STAM_PROFILE_START(&s->StatFlushes, f);
1526 rc = pDevR3->pDrvMedia->pfnFlush(pDevR3->pDrvMedia);
1527 AssertRC(rc);
1528 STAM_PROFILE_STOP(&s->StatFlushes, f);
1529
1530 ataR3LockEnter(pDevIns, pCtl);
1531 ataR3CmdOK(pCtl, s, 0);
1532 return false;
1533}
1534
1535/**
1536 * Sink/Source: ATAPI IDENTIFY
1537 */
1538static bool atapiR3IdentifySS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
1539{
1540 uint16_t *p;
1541 RT_NOREF(pDevIns, pDevR3);
1542
1543 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
1544 Assert(s->cbElementaryTransfer == 512);
1545
1546 p = (uint16_t *)&s->abIOBuffer[0];
1547 memset(p, 0, 512);
1548 /* Removable CDROM, 3ms response, 12 byte packets */
1549 p[0] = RT_H2LE_U16(2 << 14 | 5 << 8 | 1 << 7 | 0 << 5 | 0 << 0);
1550 ataR3PadString((uint8_t *)(p + 10), s->szSerialNumber, ATA_SERIAL_NUMBER_LENGTH); /* serial number */
1551 p[20] = RT_H2LE_U16(3); /* XXX: retired, cache type */
1552 p[21] = RT_H2LE_U16(512); /* XXX: retired, cache size in sectors */
1553 ataR3PadString((uint8_t *)(p + 23), s->szFirmwareRevision, ATA_FIRMWARE_REVISION_LENGTH); /* firmware version */
1554 ataR3PadString((uint8_t *)(p + 27), s->szModelNumber, ATA_MODEL_NUMBER_LENGTH); /* model */
1555 p[49] = RT_H2LE_U16(1 << 11 | 1 << 9 | 1 << 8); /* DMA and LBA supported */
1556 p[50] = RT_H2LE_U16(1 << 14); /* No drive specific standby timer minimum */
1557 p[51] = RT_H2LE_U16(240); /* PIO transfer cycle */
1558 p[52] = RT_H2LE_U16(240); /* DMA transfer cycle */
1559 p[53] = RT_H2LE_U16(1 << 1 | 1 << 2); /* words 64-70,88 are valid */
1560 p[63] = RT_H2LE_U16(ATA_TRANSFER_ID(ATA_MODE_MDMA, ATA_MDMA_MODE_MAX, s->uATATransferMode)); /* MDMA modes supported / mode enabled */
1561 p[64] = RT_H2LE_U16(ATA_PIO_MODE_MAX > 2 ? (1 << (ATA_PIO_MODE_MAX - 2)) - 1 : 0); /* PIO modes beyond PIO2 supported */
1562 p[65] = RT_H2LE_U16(120); /* minimum DMA multiword tx cycle time */
1563 p[66] = RT_H2LE_U16(120); /* recommended DMA multiword tx cycle time */
1564 p[67] = RT_H2LE_U16(120); /* minimum PIO cycle time without flow control */
1565 p[68] = RT_H2LE_U16(120); /* minimum PIO cycle time with IORDY flow control */
1566 p[73] = RT_H2LE_U16(0x003e); /* ATAPI CDROM major */
1567 p[74] = RT_H2LE_U16(9); /* ATAPI CDROM minor */
1568 p[75] = RT_H2LE_U16(1); /* queue depth 1 */
1569 p[80] = RT_H2LE_U16(0x7e); /* support everything up to ATA/ATAPI-6 */
1570 p[81] = RT_H2LE_U16(0x22); /* conforms to ATA/ATAPI-6 */
1571 p[82] = RT_H2LE_U16(1 << 4 | 1 << 9); /* supports packet command set and DEVICE RESET */
1572 p[83] = RT_H2LE_U16(1 << 14);
1573 p[84] = RT_H2LE_U16(1 << 14);
1574 p[85] = RT_H2LE_U16(1 << 4 | 1 << 9); /* enabled packet command set and DEVICE RESET */
1575 p[86] = RT_H2LE_U16(0);
1576 p[87] = RT_H2LE_U16(1 << 14);
1577 p[88] = RT_H2LE_U16(ATA_TRANSFER_ID(ATA_MODE_UDMA, ATA_UDMA_MODE_MAX, s->uATATransferMode)); /* UDMA modes supported / mode enabled */
1578 p[93] = RT_H2LE_U16((1 | 1 << 1) << ((s->iLUN & 1) == 0 ? 0 : 8) | 1 << 13 | 1 << 14);
1579 /* According to ATAPI-5 spec:
1580 *
1581 * The use of this word is optional.
1582 * If bits 7:0 of this word contain the signature A5h, bits 15:8
1583 * contain the data
1584 * structure checksum.
1585 * The data structure checksum is the twos complement of the sum of
1586 * all bytes in words 0 through 254 and the byte consisting of
1587 * bits 7:0 in word 255.
1588 * Each byte shall be added with unsigned arithmetic,
1589 * and overflow shall be ignored.
1590 * The sum of all 512 bytes is zero when the checksum is correct.
1591 */
1592 uint32_t uCsum = ataR3Checksum(p, 510);
1593 p[255] = RT_H2LE_U16(0xa5 | (uCsum << 8)); /* Integrity word */
1594
1595 s->iSourceSink = ATAFN_SS_NULL;
1596 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
1597 return false;
1598}
1599
1600
1601static void ataR3SetSignature(PATADEVSTATE s)
1602{
1603 s->uATARegSelect &= 0xf0; /* clear head */
1604 /* put signature */
1605 s->uATARegNSector = 1;
1606 s->uATARegSector = 1;
1607 if (s->fATAPI)
1608 {
1609 s->uATARegLCyl = 0x14;
1610 s->uATARegHCyl = 0xeb;
1611 }
1612 else
1613 {
1614 s->uATARegLCyl = 0;
1615 s->uATARegHCyl = 0;
1616 }
1617}
1618
1619
1620static uint64_t ataR3GetSector(PATADEVSTATE s)
1621{
1622 uint64_t iLBA;
1623 if (s->uATARegSelect & 0x40)
1624 {
1625 /* any LBA variant */
1626 if (s->fLBA48)
1627 {
1628 /* LBA48 */
1629 iLBA = ((uint64_t)s->uATARegHCylHOB << 40)
1630 | ((uint64_t)s->uATARegLCylHOB << 32)
1631 | ((uint64_t)s->uATARegSectorHOB << 24)
1632 | ((uint64_t)s->uATARegHCyl << 16)
1633 | ((uint64_t)s->uATARegLCyl << 8)
1634 | s->uATARegSector;
1635 }
1636 else
1637 {
1638 /* LBA */
1639 iLBA = ((uint32_t)(s->uATARegSelect & 0x0f) << 24)
1640 | ((uint32_t)s->uATARegHCyl << 16)
1641 | ((uint32_t)s->uATARegLCyl << 8)
1642 | s->uATARegSector;
1643 }
1644 }
1645 else
1646 {
1647 /* CHS */
1648 iLBA = (((uint32_t)s->uATARegHCyl << 8) | s->uATARegLCyl) * s->XCHSGeometry.cHeads * s->XCHSGeometry.cSectors
1649 + (s->uATARegSelect & 0x0f) * s->XCHSGeometry.cSectors
1650 + (s->uATARegSector - 1);
1651 LogFlowFunc(("CHS %u/%u/%u -> LBA %llu\n", ((uint32_t)s->uATARegHCyl << 8) | s->uATARegLCyl, s->uATARegSelect & 0x0f, s->uATARegSector, iLBA));
1652 }
1653 return iLBA;
1654}
1655
1656static void ataR3SetSector(PATADEVSTATE s, uint64_t iLBA)
1657{
1658 uint32_t cyl, r;
1659 if (s->uATARegSelect & 0x40)
1660 {
1661 /* any LBA variant */
1662 if (s->fLBA48)
1663 {
1664 /* LBA48 */
1665 s->uATARegHCylHOB = iLBA >> 40;
1666 s->uATARegLCylHOB = iLBA >> 32;
1667 s->uATARegSectorHOB = iLBA >> 24;
1668 s->uATARegHCyl = iLBA >> 16;
1669 s->uATARegLCyl = iLBA >> 8;
1670 s->uATARegSector = iLBA;
1671 }
1672 else
1673 {
1674 /* LBA */
1675 s->uATARegSelect = (s->uATARegSelect & 0xf0) | (iLBA >> 24);
1676 s->uATARegHCyl = (iLBA >> 16);
1677 s->uATARegLCyl = (iLBA >> 8);
1678 s->uATARegSector = (iLBA);
1679 }
1680 }
1681 else
1682 {
1683 /* CHS */
1684 AssertMsgReturnVoid(s->XCHSGeometry.cHeads && s->XCHSGeometry.cSectors, ("Device geometry not set!\n"));
1685 cyl = iLBA / (s->XCHSGeometry.cHeads * s->XCHSGeometry.cSectors);
1686 r = iLBA % (s->XCHSGeometry.cHeads * s->XCHSGeometry.cSectors);
1687 s->uATARegHCyl = cyl >> 8;
1688 s->uATARegLCyl = cyl;
1689 s->uATARegSelect = (s->uATARegSelect & 0xf0) | ((r / s->XCHSGeometry.cSectors) & 0x0f);
1690 s->uATARegSector = (r % s->XCHSGeometry.cSectors) + 1;
1691 LogFlowFunc(("LBA %llu -> CHS %u/%u/%u\n", iLBA, cyl, s->uATARegSelect & 0x0f, s->uATARegSector));
1692 }
1693}
1694
1695
1696static void ataR3WarningDiskFull(PPDMDEVINS pDevIns)
1697{
1698 int rc;
1699 LogRel(("PIIX3 ATA: Host disk full\n"));
1700 rc = PDMDevHlpVMSetRuntimeError(pDevIns, VMSETRTERR_FLAGS_SUSPEND | VMSETRTERR_FLAGS_NO_WAIT, "DevATA_DISKFULL",
1701 N_("Host system reported disk full. VM execution is suspended. You can resume after freeing some space"));
1702 AssertRC(rc);
1703}
1704
1705static void ataR3WarningFileTooBig(PPDMDEVINS pDevIns)
1706{
1707 int rc;
1708 LogRel(("PIIX3 ATA: File too big\n"));
1709 rc = PDMDevHlpVMSetRuntimeError(pDevIns, VMSETRTERR_FLAGS_SUSPEND | VMSETRTERR_FLAGS_NO_WAIT, "DevATA_FILETOOBIG",
1710 N_("Host system reported that the file size limit of the host file system has been exceeded. VM execution is suspended. You need to move your virtual hard disk to a filesystem which allows bigger files"));
1711 AssertRC(rc);
1712}
1713
1714static void ataR3WarningISCSI(PPDMDEVINS pDevIns)
1715{
1716 int rc;
1717 LogRel(("PIIX3 ATA: iSCSI target unavailable\n"));
1718 rc = PDMDevHlpVMSetRuntimeError(pDevIns, VMSETRTERR_FLAGS_SUSPEND | VMSETRTERR_FLAGS_NO_WAIT, "DevATA_ISCSIDOWN",
1719 N_("The iSCSI target has stopped responding. VM execution is suspended. You can resume when it is available again"));
1720 AssertRC(rc);
1721}
1722
1723static void ataR3WarningFileStale(PPDMDEVINS pDevIns)
1724{
1725 int rc;
1726 LogRel(("PIIX3 ATA: File handle became stale\n"));
1727 rc = PDMDevHlpVMSetRuntimeError(pDevIns, VMSETRTERR_FLAGS_SUSPEND | VMSETRTERR_FLAGS_NO_WAIT, "DevATA_FILESTALE",
1728 N_("The file became stale (often due to a restarted NFS server). VM execution is suspended. You can resume when it is available again"));
1729 AssertRC(rc);
1730}
1731
1732
1733static bool ataR3IsRedoSetWarning(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, int rc)
1734{
1735 Assert(!PDMDevHlpCritSectIsOwner(pDevIns, &pCtl->lock));
1736 if (rc == VERR_DISK_FULL)
1737 {
1738 pCtl->fRedoIdle = true;
1739 ataR3WarningDiskFull(pDevIns);
1740 return true;
1741 }
1742 if (rc == VERR_FILE_TOO_BIG)
1743 {
1744 pCtl->fRedoIdle = true;
1745 ataR3WarningFileTooBig(pDevIns);
1746 return true;
1747 }
1748 if (rc == VERR_BROKEN_PIPE || rc == VERR_NET_CONNECTION_REFUSED)
1749 {
1750 pCtl->fRedoIdle = true;
1751 /* iSCSI connection abort (first error) or failure to reestablish
1752 * connection (second error). Pause VM. On resume we'll retry. */
1753 ataR3WarningISCSI(pDevIns);
1754 return true;
1755 }
1756 if (rc == VERR_STALE_FILE_HANDLE)
1757 {
1758 pCtl->fRedoIdle = true;
1759 ataR3WarningFileStale(pDevIns);
1760 return true;
1761 }
1762 if (rc == VERR_VD_DEK_MISSING)
1763 {
1764 /* Error message already set. */
1765 pCtl->fRedoIdle = true;
1766 return true;
1767 }
1768
1769 return false;
1770}
1771
1772
1773static int ataR3ReadSectors(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3,
1774 uint64_t u64Sector, void *pvBuf, uint32_t cSectors, bool *pfRedo)
1775{
1776 int rc;
1777 uint32_t const cbSector = s->cbSector;
1778 uint32_t cbToRead = cSectors * cbSector;
1779 Assert(pvBuf == &s->abIOBuffer[0]);
1780 AssertReturnStmt(cbToRead <= sizeof(s->abIOBuffer), *pfRedo = false, VERR_BUFFER_OVERFLOW);
1781
1782 ataR3LockLeave(pDevIns, pCtl);
1783
1784 STAM_PROFILE_ADV_START(&s->StatReads, r);
1785 s->Led.Asserted.s.fReading = s->Led.Actual.s.fReading = 1;
1786 rc = pDevR3->pDrvMedia->pfnRead(pDevR3->pDrvMedia, u64Sector * cbSector, pvBuf, cbToRead);
1787 s->Led.Actual.s.fReading = 0;
1788 STAM_PROFILE_ADV_STOP(&s->StatReads, r);
1789 Log4(("ataR3ReadSectors: rc=%Rrc cSectors=%#x u64Sector=%llu\n%.*Rhxd\n",
1790 rc, cSectors, u64Sector, cbToRead, pvBuf));
1791
1792 STAM_REL_COUNTER_ADD(&s->StatBytesRead, cbToRead);
1793
1794 if (RT_SUCCESS(rc))
1795 *pfRedo = false;
1796 else
1797 *pfRedo = ataR3IsRedoSetWarning(pDevIns, pCtl, rc);
1798
1799 ataR3LockEnter(pDevIns, pCtl);
1800 return rc;
1801}
1802
1803
1804static int ataR3WriteSectors(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3,
1805 uint64_t u64Sector, const void *pvBuf, uint32_t cSectors, bool *pfRedo)
1806{
1807 int rc;
1808 uint32_t const cbSector = s->cbSector;
1809 uint32_t cbToWrite = cSectors * cbSector;
1810 Assert(pvBuf == &s->abIOBuffer[0]);
1811 AssertReturnStmt(cbToWrite <= sizeof(s->abIOBuffer), *pfRedo = false, VERR_BUFFER_OVERFLOW);
1812
1813 ataR3LockLeave(pDevIns, pCtl);
1814
1815 STAM_PROFILE_ADV_START(&s->StatWrites, w);
1816 s->Led.Asserted.s.fWriting = s->Led.Actual.s.fWriting = 1;
1817# ifdef VBOX_INSTRUMENT_DMA_WRITES
1818 if (s->fDMA)
1819 STAM_PROFILE_ADV_START(&s->StatInstrVDWrites, vw);
1820# endif
1821 rc = pDevR3->pDrvMedia->pfnWrite(pDevR3->pDrvMedia, u64Sector * cbSector, pvBuf, cbToWrite);
1822# ifdef VBOX_INSTRUMENT_DMA_WRITES
1823 if (s->fDMA)
1824 STAM_PROFILE_ADV_STOP(&s->StatInstrVDWrites, vw);
1825# endif
1826 s->Led.Actual.s.fWriting = 0;
1827 STAM_PROFILE_ADV_STOP(&s->StatWrites, w);
1828 Log4(("ataR3WriteSectors: rc=%Rrc cSectors=%#x u64Sector=%llu\n%.*Rhxd\n",
1829 rc, cSectors, u64Sector, cbToWrite, pvBuf));
1830
1831 STAM_REL_COUNTER_ADD(&s->StatBytesWritten, cbToWrite);
1832
1833 if (RT_SUCCESS(rc))
1834 *pfRedo = false;
1835 else
1836 *pfRedo = ataR3IsRedoSetWarning(pDevIns, pCtl, rc);
1837
1838 ataR3LockEnter(pDevIns, pCtl);
1839 return rc;
1840}
1841
1842
1843/**
1844 * Begin Transfer: READ/WRITE SECTORS
1845 */
1846static void ataR3ReadWriteSectorsBT(PATACONTROLLER pCtl, PATADEVSTATE s)
1847{
1848 uint32_t const cbSector = RT_MAX(s->cbSector, 1);
1849 uint32_t cSectors;
1850
1851 cSectors = s->cbTotalTransfer / cbSector;
1852 if (cSectors > s->cSectorsPerIRQ)
1853 s->cbElementaryTransfer = s->cSectorsPerIRQ * cbSector;
1854 else
1855 s->cbElementaryTransfer = cSectors * cbSector;
1856 if (s->uTxDir == PDMMEDIATXDIR_TO_DEVICE)
1857 ataR3CmdOK(pCtl, s, 0);
1858}
1859
1860
1861/**
1862 * Sink/Source: READ SECTORS
1863 */
1864static bool ataR3ReadSectorsSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
1865{
1866 uint32_t const cbSector = RT_MAX(s->cbSector, 1);
1867 uint32_t cSectors;
1868 uint64_t iLBA;
1869 bool fRedo;
1870 int rc;
1871
1872 cSectors = s->cbElementaryTransfer / cbSector;
1873 Assert(cSectors);
1874 iLBA = s->iCurLBA;
1875 Log(("%s: %d sectors at LBA %d\n", __FUNCTION__, cSectors, iLBA));
1876 rc = ataR3ReadSectors(pDevIns, pCtl, s, pDevR3, iLBA, s->abIOBuffer, cSectors, &fRedo);
1877 if (RT_SUCCESS(rc))
1878 {
1879 /* When READ SECTORS etc. finishes, the address in the task
1880 * file register points at the last sector read, not at the next
1881 * sector that would be read. This ensures the registers always
1882 * contain a valid sector address.
1883 */
1884 if (s->cbElementaryTransfer == s->cbTotalTransfer)
1885 {
1886 s->iSourceSink = ATAFN_SS_NULL;
1887 ataR3SetSector(s, iLBA + cSectors - 1);
1888 }
1889 else
1890 ataR3SetSector(s, iLBA + cSectors);
1891 s->uATARegNSector -= cSectors;
1892 s->iCurLBA += cSectors;
1893 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
1894 }
1895 else
1896 {
1897 if (fRedo)
1898 return fRedo;
1899 if (s->cErrors++ < MAX_LOG_REL_ERRORS)
1900 LogRel(("PIIX3 ATA: LUN#%d: disk read error (rc=%Rrc iSector=%#RX64 cSectors=%#RX32)\n",
1901 s->iLUN, rc, iLBA, cSectors));
1902
1903 /*
1904 * Check if we got interrupted. We don't need to set status variables
1905 * because the request was aborted.
1906 */
1907 if (rc != VERR_INTERRUPTED)
1908 ataR3CmdError(pCtl, s, ID_ERR);
1909 }
1910 return false;
1911}
1912
1913
1914/**
1915 * Sink/Source: WRITE SECTOR
1916 */
1917static bool ataR3WriteSectorsSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
1918{
1919 uint32_t const cbSector = RT_MAX(s->cbSector, 1);
1920 uint64_t iLBA;
1921 uint32_t cSectors;
1922 bool fRedo;
1923 int rc;
1924
1925 cSectors = s->cbElementaryTransfer / cbSector;
1926 Assert(cSectors);
1927 iLBA = s->iCurLBA;
1928 Log(("%s: %d sectors at LBA %d\n", __FUNCTION__, cSectors, iLBA));
1929 rc = ataR3WriteSectors(pDevIns, pCtl, s, pDevR3, iLBA, s->abIOBuffer, cSectors, &fRedo);
1930 if (RT_SUCCESS(rc))
1931 {
1932 ataR3SetSector(s, iLBA + cSectors);
1933 s->iCurLBA = iLBA + cSectors;
1934 if (!s->cbTotalTransfer)
1935 s->iSourceSink = ATAFN_SS_NULL;
1936 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
1937 }
1938 else
1939 {
1940 if (fRedo)
1941 return fRedo;
1942 if (s->cErrors++ < MAX_LOG_REL_ERRORS)
1943 LogRel(("PIIX3 ATA: LUN#%d: disk write error (rc=%Rrc iSector=%#RX64 cSectors=%#RX32)\n",
1944 s->iLUN, rc, iLBA, cSectors));
1945
1946 /*
1947 * Check if we got interrupted. We don't need to set status variables
1948 * because the request was aborted.
1949 */
1950 if (rc != VERR_INTERRUPTED)
1951 ataR3CmdError(pCtl, s, ID_ERR);
1952 }
1953 return false;
1954}
1955
1956
1957static void atapiR3CmdOK(PATACONTROLLER pCtl, PATADEVSTATE s)
1958{
1959 s->uATARegError = 0;
1960 ataSetStatusValue(pCtl, s, ATA_STAT_READY);
1961 s->uATARegNSector = (s->uATARegNSector & ~7)
1962 | ((s->uTxDir != PDMMEDIATXDIR_TO_DEVICE) ? ATAPI_INT_REASON_IO : 0)
1963 | (!s->cbTotalTransfer ? ATAPI_INT_REASON_CD : 0);
1964 Log2(("%s: interrupt reason %#04x\n", __FUNCTION__, s->uATARegNSector));
1965
1966 memset(s->abATAPISense, '\0', sizeof(s->abATAPISense));
1967 s->abATAPISense[0] = 0x70 | (1 << 7);
1968 s->abATAPISense[7] = 10;
1969}
1970
1971
1972static void atapiR3CmdError(PATACONTROLLER pCtl, PATADEVSTATE s, const uint8_t *pabATAPISense, size_t cbATAPISense)
1973{
1974 Log(("%s: sense=%#x (%s) asc=%#x ascq=%#x (%s)\n", __FUNCTION__, pabATAPISense[2] & 0x0f, SCSISenseText(pabATAPISense[2] & 0x0f),
1975 pabATAPISense[12], pabATAPISense[13], SCSISenseExtText(pabATAPISense[12], pabATAPISense[13])));
1976 s->uATARegError = pabATAPISense[2] << 4;
1977 ataSetStatusValue(pCtl, s, ATA_STAT_READY | ATA_STAT_ERR);
1978 s->uATARegNSector = (s->uATARegNSector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
1979 Log2(("%s: interrupt reason %#04x\n", __FUNCTION__, s->uATARegNSector));
1980 memset(s->abATAPISense, '\0', sizeof(s->abATAPISense));
1981 memcpy(s->abATAPISense, pabATAPISense, RT_MIN(cbATAPISense, sizeof(s->abATAPISense)));
1982 s->cbTotalTransfer = 0;
1983 s->cbElementaryTransfer = 0;
1984 s->cbAtapiPassthroughTransfer = 0;
1985 s->iIOBufferCur = 0;
1986 s->iIOBufferEnd = 0;
1987 s->uTxDir = PDMMEDIATXDIR_NONE;
1988 s->iBeginTransfer = ATAFN_BT_NULL;
1989 s->iSourceSink = ATAFN_SS_NULL;
1990}
1991
1992
1993/** @todo deprecated function - doesn't provide enough info. Replace by direct
1994 * calls to atapiR3CmdError() with full data. */
1995static void atapiR3CmdErrorSimple(PATACONTROLLER pCtl, PATADEVSTATE s, uint8_t uATAPISenseKey, uint8_t uATAPIASC)
1996{
1997 uint8_t abATAPISense[ATAPI_SENSE_SIZE];
1998 memset(abATAPISense, '\0', sizeof(abATAPISense));
1999 abATAPISense[0] = 0x70 | (1 << 7);
2000 abATAPISense[2] = uATAPISenseKey & 0x0f;
2001 abATAPISense[7] = 10;
2002 abATAPISense[12] = uATAPIASC;
2003 atapiR3CmdError(pCtl, s, abATAPISense, sizeof(abATAPISense));
2004}
2005
2006
2007/**
2008 * Begin Transfer: ATAPI command
2009 */
2010static void atapiR3CmdBT(PATACONTROLLER pCtl, PATADEVSTATE s)
2011{
2012 s->fATAPITransfer = true;
2013 s->cbElementaryTransfer = s->cbTotalTransfer;
2014 s->cbAtapiPassthroughTransfer = s->cbTotalTransfer;
2015 s->cbPIOTransferLimit = s->uATARegLCyl | (s->uATARegHCyl << 8);
2016 if (s->uTxDir == PDMMEDIATXDIR_TO_DEVICE)
2017 atapiR3CmdOK(pCtl, s);
2018}
2019
2020
2021/**
2022 * Begin Transfer: ATAPI Passthrough command
2023 */
2024static void atapiR3PassthroughCmdBT(PATACONTROLLER pCtl, PATADEVSTATE s)
2025{
2026 atapiR3CmdBT(pCtl, s);
2027}
2028
2029
2030/**
2031 * Sink/Source: READ
2032 */
2033static bool atapiR3ReadSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
2034{
2035 int rc;
2036 uint64_t cbBlockRegion = 0;
2037 VDREGIONDATAFORM enmDataForm;
2038
2039 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
2040 uint32_t const iATAPILBA = s->iCurLBA;
2041 uint32_t const cbTransfer = RT_MIN(s->cbTotalTransfer, RT_MIN(s->cbIOBuffer, ATA_MAX_IO_BUFFER_SIZE));
2042 uint32_t const cbATAPISector = s->cbATAPISector;
2043 uint32_t const cSectors = cbTransfer / cbATAPISector;
2044 Assert(cSectors * cbATAPISector <= cbTransfer);
2045 Log(("%s: %d sectors at LBA %d\n", __FUNCTION__, cSectors, iATAPILBA));
2046 AssertLogRelReturn(cSectors * cbATAPISector <= sizeof(s->abIOBuffer), false);
2047
2048 ataR3LockLeave(pDevIns, pCtl);
2049
2050 rc = pDevR3->pDrvMedia->pfnQueryRegionPropertiesForLba(pDevR3->pDrvMedia, iATAPILBA, NULL, NULL,
2051 &cbBlockRegion, &enmDataForm);
2052 if (RT_SUCCESS(rc))
2053 {
2054 STAM_PROFILE_ADV_START(&s->StatReads, r);
2055 s->Led.Asserted.s.fReading = s->Led.Actual.s.fReading = 1;
2056
2057 /* If the region block size and requested sector matches we can just pass the request through. */
2058 if (cbBlockRegion == cbATAPISector)
2059 rc = pDevR3->pDrvMedia->pfnRead(pDevR3->pDrvMedia, (uint64_t)iATAPILBA * cbATAPISector,
2060 s->abIOBuffer, cbATAPISector * cSectors);
2061 else
2062 {
2063 uint32_t const iEndSector = iATAPILBA + cSectors;
2064 ASSERT_GUEST(iEndSector >= iATAPILBA);
2065 if (cbBlockRegion == 2048 && cbATAPISector == 2352)
2066 {
2067 /* Generate the sync bytes. */
2068 uint8_t *pbBuf = s->abIOBuffer;
2069
2070 for (uint32_t i = iATAPILBA; i < iEndSector; i++)
2071 {
2072 /* Sync bytes, see 4.2.3.8 CD Main Channel Block Formats */
2073 *pbBuf++ = 0x00;
2074 memset(pbBuf, 0xff, 10);
2075 pbBuf += 10;
2076 *pbBuf++ = 0x00;
2077 /* MSF */
2078 scsiLBA2MSF(pbBuf, i);
2079 pbBuf += 3;
2080 *pbBuf++ = 0x01; /* mode 1 data */
2081 /* data */
2082 rc = pDevR3->pDrvMedia->pfnRead(pDevR3->pDrvMedia, (uint64_t)i * 2048, pbBuf, 2048);
2083 if (RT_FAILURE(rc))
2084 break;
2085 pbBuf += 2048;
2086 /**
2087 * @todo maybe compute ECC and parity, layout is:
2088 * 2072 4 EDC
2089 * 2076 172 P parity symbols
2090 * 2248 104 Q parity symbols
2091 */
2092 memset(pbBuf, 0, 280);
2093 pbBuf += 280;
2094 }
2095 }
2096 else if (cbBlockRegion == 2352 && cbATAPISector == 2048)
2097 {
2098 /* Read only the user data portion. */
2099 uint8_t *pbBuf = s->abIOBuffer;
2100
2101 for (uint32_t i = iATAPILBA; i < iEndSector; i++)
2102 {
2103 uint8_t abTmp[2352];
2104 uint8_t cbSkip;
2105
2106 rc = pDevR3->pDrvMedia->pfnRead(pDevR3->pDrvMedia, (uint64_t)i * 2352, &abTmp[0], 2352);
2107 if (RT_FAILURE(rc))
2108 break;
2109
2110 /* Mode 2 has an additional subheader before user data; we need to
2111 * skip 16 bytes for Mode 1 (sync + header) and 20 bytes for Mode 2 +
2112 * (sync + header + subheader).
2113 */
2114 switch (enmDataForm) {
2115 case VDREGIONDATAFORM_MODE2_2352:
2116 case VDREGIONDATAFORM_XA_2352:
2117 cbSkip = 24;
2118 break;
2119 case VDREGIONDATAFORM_MODE1_2352:
2120 cbSkip = 16;
2121 break;
2122 default:
2123 AssertMsgFailed(("Unexpected region form (%#u), using default skip value\n", enmDataForm));
2124 cbSkip = 16;
2125 }
2126 memcpy(pbBuf, &abTmp[cbSkip], 2048);
2127 pbBuf += 2048;
2128 }
2129 }
2130 else
2131 ASSERT_GUEST_MSG_FAILED(("Unsupported: cbBlockRegion=%u cbATAPISector=%u\n", cbBlockRegion, cbATAPISector));
2132 }
2133 s->Led.Actual.s.fReading = 0;
2134 STAM_PROFILE_ADV_STOP(&s->StatReads, r);
2135 }
2136
2137 ataR3LockEnter(pDevIns, pCtl);
2138
2139 if (RT_SUCCESS(rc))
2140 {
2141 STAM_REL_COUNTER_ADD(&s->StatBytesRead, cbATAPISector * cSectors);
2142
2143 /* The initial buffer end value has been set up based on the total
2144 * transfer size. But the I/O buffer size limits what can actually be
2145 * done in one transfer, so set the actual value of the buffer end. */
2146 s->cbElementaryTransfer = cbTransfer;
2147 if (cbTransfer >= s->cbTotalTransfer)
2148 s->iSourceSink = ATAFN_SS_NULL;
2149 atapiR3CmdOK(pCtl, s);
2150 s->iCurLBA = iATAPILBA + cSectors;
2151 }
2152 else
2153 {
2154 if (s->cErrors++ < MAX_LOG_REL_ERRORS)
2155 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM read error, %d sectors at LBA %d\n", s->iLUN, cSectors, iATAPILBA));
2156
2157 /*
2158 * Check if we got interrupted. We don't need to set status variables
2159 * because the request was aborted.
2160 */
2161 if (rc != VERR_INTERRUPTED)
2162 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_MEDIUM_ERROR, SCSI_ASC_READ_ERROR);
2163 }
2164 return false;
2165}
2166
2167/**
2168 * Sets the given media track type.
2169 */
2170static uint32_t ataR3MediumTypeSet(PATADEVSTATE s, uint32_t MediaTrackType)
2171{
2172 return ASMAtomicXchgU32(&s->MediaTrackType, MediaTrackType);
2173}
2174
2175
2176/**
2177 * Sink/Source: Passthrough
2178 */
2179static bool atapiR3PassthroughSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
2180{
2181 int rc = VINF_SUCCESS;
2182 uint8_t abATAPISense[ATAPI_SENSE_SIZE];
2183 uint32_t cbTransfer;
2184 PSTAMPROFILEADV pProf = NULL;
2185
2186 cbTransfer = RT_MIN(s->cbAtapiPassthroughTransfer, RT_MIN(s->cbIOBuffer, ATA_MAX_IO_BUFFER_SIZE));
2187
2188 if (s->uTxDir == PDMMEDIATXDIR_TO_DEVICE)
2189 Log3(("ATAPI PT data write (%d): %.*Rhxs\n", cbTransfer, cbTransfer, s->abIOBuffer));
2190
2191 /* Simple heuristics: if there is at least one sector of data
2192 * to transfer, it's worth updating the LEDs. */
2193 if (cbTransfer >= 2048)
2194 {
2195 if (s->uTxDir != PDMMEDIATXDIR_TO_DEVICE)
2196 {
2197 s->Led.Asserted.s.fReading = s->Led.Actual.s.fReading = 1;
2198 pProf = &s->StatReads;
2199 }
2200 else
2201 {
2202 s->Led.Asserted.s.fWriting = s->Led.Actual.s.fWriting = 1;
2203 pProf = &s->StatWrites;
2204 }
2205 }
2206
2207 ataR3LockLeave(pDevIns, pCtl);
2208
2209# if defined(LOG_ENABLED)
2210 char szBuf[1024];
2211
2212 memset(szBuf, 0, sizeof(szBuf));
2213
2214 switch (s->abATAPICmd[0])
2215 {
2216 case SCSI_MODE_SELECT_10:
2217 {
2218 size_t cbBlkDescLength = scsiBE2H_U16(&s->abIOBuffer[6]);
2219
2220 SCSILogModePage(szBuf, sizeof(szBuf) - 1,
2221 s->abIOBuffer + 8 + cbBlkDescLength,
2222 cbTransfer - 8 - cbBlkDescLength);
2223 break;
2224 }
2225 case SCSI_SEND_CUE_SHEET:
2226 {
2227 SCSILogCueSheet(szBuf, sizeof(szBuf) - 1,
2228 s->abIOBuffer, cbTransfer);
2229 break;
2230 }
2231 default:
2232 break;
2233 }
2234
2235 Log2(("%s\n", szBuf));
2236# endif
2237
2238 if (pProf) { STAM_PROFILE_ADV_START(pProf, b); }
2239
2240 Assert(s->cbATAPISector);
2241 const uint32_t cbATAPISector = RT_MAX(s->cbATAPISector, 1); /* paranoia */
2242 const uint32_t cbIOBuffer = RT_MIN(s->cbIOBuffer, ATA_MAX_IO_BUFFER_SIZE); /* ditto */
2243
2244 if ( cbTransfer > SCSI_MAX_BUFFER_SIZE
2245 || s->cbElementaryTransfer > cbIOBuffer)
2246 {
2247 /* Linux accepts commands with up to 100KB of data, but expects
2248 * us to handle commands with up to 128KB of data. The usual
2249 * imbalance of powers. */
2250 uint8_t abATAPICmd[ATAPI_PACKET_SIZE];
2251 uint32_t iATAPILBA, cSectors, cReqSectors, cbCurrTX;
2252 uint8_t *pbBuf = s->abIOBuffer;
2253 uint32_t cSectorsMax; /**< Maximum amount of sectors to read without exceeding the I/O buffer. */
2254
2255 cSectorsMax = cbTransfer / cbATAPISector;
2256 AssertStmt(cSectorsMax * s->cbATAPISector <= cbIOBuffer, cSectorsMax = cbIOBuffer / cbATAPISector);
2257
2258 switch (s->abATAPICmd[0])
2259 {
2260 case SCSI_READ_10:
2261 case SCSI_WRITE_10:
2262 case SCSI_WRITE_AND_VERIFY_10:
2263 iATAPILBA = scsiBE2H_U32(s->abATAPICmd + 2);
2264 cSectors = scsiBE2H_U16(s->abATAPICmd + 7);
2265 break;
2266 case SCSI_READ_12:
2267 case SCSI_WRITE_12:
2268 iATAPILBA = scsiBE2H_U32(s->abATAPICmd + 2);
2269 cSectors = scsiBE2H_U32(s->abATAPICmd + 6);
2270 break;
2271 case SCSI_READ_CD:
2272 iATAPILBA = scsiBE2H_U32(s->abATAPICmd + 2);
2273 cSectors = scsiBE2H_U24(s->abATAPICmd + 6);
2274 break;
2275 case SCSI_READ_CD_MSF:
2276 iATAPILBA = scsiMSF2LBA(s->abATAPICmd + 3);
2277 cSectors = scsiMSF2LBA(s->abATAPICmd + 6) - iATAPILBA;
2278 break;
2279 default:
2280 AssertMsgFailed(("Don't know how to split command %#04x\n", s->abATAPICmd[0]));
2281 if (s->cErrors++ < MAX_LOG_REL_ERRORS)
2282 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM passthrough split error\n", s->iLUN));
2283 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ILLEGAL_OPCODE);
2284 ataR3LockEnter(pDevIns, pCtl);
2285 return false;
2286 }
2287 cSectorsMax = RT_MIN(cSectorsMax, cSectors);
2288 memcpy(abATAPICmd, s->abATAPICmd, ATAPI_PACKET_SIZE);
2289 cReqSectors = 0;
2290 for (uint32_t i = cSectorsMax; i > 0; i -= cReqSectors)
2291 {
2292 if (i * cbATAPISector > SCSI_MAX_BUFFER_SIZE)
2293 cReqSectors = SCSI_MAX_BUFFER_SIZE / cbATAPISector;
2294 else
2295 cReqSectors = i;
2296 cbCurrTX = cbATAPISector * cReqSectors;
2297 switch (s->abATAPICmd[0])
2298 {
2299 case SCSI_READ_10:
2300 case SCSI_WRITE_10:
2301 case SCSI_WRITE_AND_VERIFY_10:
2302 scsiH2BE_U32(abATAPICmd + 2, iATAPILBA);
2303 scsiH2BE_U16(abATAPICmd + 7, cReqSectors);
2304 break;
2305 case SCSI_READ_12:
2306 case SCSI_WRITE_12:
2307 scsiH2BE_U32(abATAPICmd + 2, iATAPILBA);
2308 scsiH2BE_U32(abATAPICmd + 6, cReqSectors);
2309 break;
2310 case SCSI_READ_CD:
2311 scsiH2BE_U32(abATAPICmd + 2, iATAPILBA);
2312 scsiH2BE_U24(abATAPICmd + 6, cReqSectors);
2313 break;
2314 case SCSI_READ_CD_MSF:
2315 scsiLBA2MSF(abATAPICmd + 3, iATAPILBA);
2316 scsiLBA2MSF(abATAPICmd + 6, iATAPILBA + cReqSectors);
2317 break;
2318 }
2319 AssertLogRelReturn((uintptr_t)(pbBuf - &s->abIOBuffer[0]) + cbCurrTX <= sizeof(s->abIOBuffer), false);
2320 rc = pDevR3->pDrvMedia->pfnSendCmd(pDevR3->pDrvMedia, abATAPICmd, ATAPI_PACKET_SIZE, (PDMMEDIATXDIR)s->uTxDir,
2321 pbBuf, &cbCurrTX, abATAPISense, sizeof(abATAPISense), 30000 /**< @todo timeout */);
2322 if (rc != VINF_SUCCESS)
2323 break;
2324 iATAPILBA += cReqSectors;
2325 pbBuf += cbATAPISector * cReqSectors;
2326 }
2327
2328 if (RT_SUCCESS(rc))
2329 {
2330 /* Adjust ATAPI command for the next call. */
2331 switch (s->abATAPICmd[0])
2332 {
2333 case SCSI_READ_10:
2334 case SCSI_WRITE_10:
2335 case SCSI_WRITE_AND_VERIFY_10:
2336 scsiH2BE_U32(s->abATAPICmd + 2, iATAPILBA);
2337 scsiH2BE_U16(s->abATAPICmd + 7, cSectors - cSectorsMax);
2338 break;
2339 case SCSI_READ_12:
2340 case SCSI_WRITE_12:
2341 scsiH2BE_U32(s->abATAPICmd + 2, iATAPILBA);
2342 scsiH2BE_U32(s->abATAPICmd + 6, cSectors - cSectorsMax);
2343 break;
2344 case SCSI_READ_CD:
2345 scsiH2BE_U32(s->abATAPICmd + 2, iATAPILBA);
2346 scsiH2BE_U24(s->abATAPICmd + 6, cSectors - cSectorsMax);
2347 break;
2348 case SCSI_READ_CD_MSF:
2349 scsiLBA2MSF(s->abATAPICmd + 3, iATAPILBA);
2350 scsiLBA2MSF(s->abATAPICmd + 6, iATAPILBA + cSectors - cSectorsMax);
2351 break;
2352 default:
2353 AssertMsgFailed(("Don't know how to split command %#04x\n", s->abATAPICmd[0]));
2354 if (s->cErrors++ < MAX_LOG_REL_ERRORS)
2355 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM passthrough split error\n", s->iLUN));
2356 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ILLEGAL_OPCODE);
2357 return false;
2358 }
2359 }
2360 }
2361 else
2362 {
2363 AssertLogRelReturn(cbTransfer <= sizeof(s->abIOBuffer), false);
2364 rc = pDevR3->pDrvMedia->pfnSendCmd(pDevR3->pDrvMedia, s->abATAPICmd, ATAPI_PACKET_SIZE, (PDMMEDIATXDIR)s->uTxDir,
2365 s->abIOBuffer, &cbTransfer, abATAPISense, sizeof(abATAPISense), 30000 /**< @todo timeout */);
2366 }
2367 if (pProf) { STAM_PROFILE_ADV_STOP(pProf, b); }
2368
2369 ataR3LockEnter(pDevIns, pCtl);
2370
2371 /* Update the LEDs and the read/write statistics. */
2372 if (cbTransfer >= 2048)
2373 {
2374 if (s->uTxDir != PDMMEDIATXDIR_TO_DEVICE)
2375 {
2376 s->Led.Actual.s.fReading = 0;
2377 STAM_REL_COUNTER_ADD(&s->StatBytesRead, cbTransfer);
2378 }
2379 else
2380 {
2381 s->Led.Actual.s.fWriting = 0;
2382 STAM_REL_COUNTER_ADD(&s->StatBytesWritten, cbTransfer);
2383 }
2384 }
2385
2386 if (RT_SUCCESS(rc))
2387 {
2388 /* Do post processing for certain commands. */
2389 switch (s->abATAPICmd[0])
2390 {
2391 case SCSI_SEND_CUE_SHEET:
2392 case SCSI_READ_TOC_PMA_ATIP:
2393 {
2394 if (!pDevR3->pTrackList)
2395 rc = ATAPIPassthroughTrackListCreateEmpty(&pDevR3->pTrackList);
2396
2397 if (RT_SUCCESS(rc))
2398 rc = ATAPIPassthroughTrackListUpdate(pDevR3->pTrackList, s->abATAPICmd, s->abIOBuffer, sizeof(s->abIOBuffer));
2399
2400 if ( RT_FAILURE(rc)
2401 && s->cErrors++ < MAX_LOG_REL_ERRORS)
2402 LogRel(("ATA: Error (%Rrc) while updating the tracklist during %s, burning the disc might fail\n",
2403 rc, s->abATAPICmd[0] == SCSI_SEND_CUE_SHEET ? "SEND CUE SHEET" : "READ TOC/PMA/ATIP"));
2404 break;
2405 }
2406 case SCSI_SYNCHRONIZE_CACHE:
2407 {
2408 if (pDevR3->pTrackList)
2409 ATAPIPassthroughTrackListClear(pDevR3->pTrackList);
2410 break;
2411 }
2412 }
2413
2414 if (s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE)
2415 {
2416 /*
2417 * Reply with the same amount of data as the real drive
2418 * but only if the command wasn't split.
2419 */
2420 if (s->cbAtapiPassthroughTransfer < cbIOBuffer)
2421 s->cbTotalTransfer = cbTransfer;
2422
2423 if ( s->abATAPICmd[0] == SCSI_INQUIRY
2424 && s->fOverwriteInquiry)
2425 {
2426 /* Make sure that the real drive cannot be identified.
2427 * Motivation: changing the VM configuration should be as
2428 * invisible as possible to the guest. */
2429 Log3(("ATAPI PT inquiry data before (%d): %.*Rhxs\n", cbTransfer, cbTransfer, s->abIOBuffer));
2430 scsiPadStr(&s->abIOBuffer[8], "VBOX", 8);
2431 scsiPadStr(&s->abIOBuffer[16], "CD-ROM", 16);
2432 scsiPadStr(&s->abIOBuffer[32], "1.0", 4);
2433 }
2434
2435 if (cbTransfer)
2436 Log3(("ATAPI PT data read (%d):\n%.*Rhxd\n", cbTransfer, cbTransfer, s->abIOBuffer));
2437 }
2438
2439 /* The initial buffer end value has been set up based on the total
2440 * transfer size. But the I/O buffer size limits what can actually be
2441 * done in one transfer, so set the actual value of the buffer end. */
2442 Assert(cbTransfer <= s->cbAtapiPassthroughTransfer);
2443 s->cbElementaryTransfer = cbTransfer;
2444 s->cbAtapiPassthroughTransfer -= cbTransfer;
2445 if (!s->cbAtapiPassthroughTransfer)
2446 {
2447 s->iSourceSink = ATAFN_SS_NULL;
2448 atapiR3CmdOK(pCtl, s);
2449 }
2450 }
2451 else
2452 {
2453 if (s->cErrors < MAX_LOG_REL_ERRORS)
2454 {
2455 uint8_t u8Cmd = s->abATAPICmd[0];
2456 do
2457 {
2458 /* don't log superfluous errors */
2459 if ( rc == VERR_DEV_IO_ERROR
2460 && ( u8Cmd == SCSI_TEST_UNIT_READY
2461 || u8Cmd == SCSI_READ_CAPACITY
2462 || u8Cmd == SCSI_READ_DVD_STRUCTURE
2463 || u8Cmd == SCSI_READ_TOC_PMA_ATIP))
2464 break;
2465 s->cErrors++;
2466 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM passthrough cmd=%#04x sense=%d ASC=%#02x ASCQ=%#02x %Rrc\n",
2467 s->iLUN, u8Cmd, abATAPISense[2] & 0x0f, abATAPISense[12], abATAPISense[13], rc));
2468 } while (0);
2469 }
2470 atapiR3CmdError(pCtl, s, abATAPISense, sizeof(abATAPISense));
2471 }
2472 return false;
2473}
2474
2475
2476/**
2477 * Begin Transfer: Read DVD structures
2478 */
2479static bool atapiR3ReadDVDStructureSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
2480{
2481 uint8_t *buf = s->abIOBuffer;
2482 int media = s->abATAPICmd[1];
2483 int format = s->abATAPICmd[7];
2484 RT_NOREF(pDevIns, pDevR3);
2485
2486 AssertCompile(sizeof(s->abIOBuffer) > UINT16_MAX /* want a RT_MIN() below, but clang takes offence at always false stuff */);
2487 uint16_t max_len = scsiBE2H_U16(&s->abATAPICmd[8]);
2488 memset(buf, 0, max_len);
2489
2490 switch (format) {
2491 case 0x00:
2492 case 0x01:
2493 case 0x02:
2494 case 0x03:
2495 case 0x04:
2496 case 0x05:
2497 case 0x06:
2498 case 0x07:
2499 case 0x08:
2500 case 0x09:
2501 case 0x0a:
2502 case 0x0b:
2503 case 0x0c:
2504 case 0x0d:
2505 case 0x0e:
2506 case 0x0f:
2507 case 0x10:
2508 case 0x11:
2509 case 0x30:
2510 case 0x31:
2511 case 0xff:
2512 if (media == 0)
2513 {
2514 int uASC = SCSI_ASC_NONE;
2515
2516 switch (format)
2517 {
2518 case 0x0: /* Physical format information */
2519 {
2520 int layer = s->abATAPICmd[6];
2521 uint64_t total_sectors;
2522
2523 if (layer != 0)
2524 {
2525 uASC = -SCSI_ASC_INV_FIELD_IN_CMD_PACKET;
2526 break;
2527 }
2528
2529 total_sectors = s->cTotalSectors;
2530 total_sectors >>= 2;
2531 if (total_sectors == 0)
2532 {
2533 uASC = -SCSI_ASC_MEDIUM_NOT_PRESENT;
2534 break;
2535 }
2536
2537 buf[4] = 1; /* DVD-ROM, part version 1 */
2538 buf[5] = 0xf; /* 120mm disc, minimum rate unspecified */
2539 buf[6] = 1; /* one layer, read-only (per MMC-2 spec) */
2540 buf[7] = 0; /* default densities */
2541
2542 /* FIXME: 0x30000 per spec? */
2543 scsiH2BE_U32(buf + 8, 0); /* start sector */
2544 scsiH2BE_U32(buf + 12, total_sectors - 1); /* end sector */
2545 scsiH2BE_U32(buf + 16, total_sectors - 1); /* l0 end sector */
2546
2547 /* Size of buffer, not including 2 byte size field */
2548 scsiH2BE_U32(&buf[0], 2048 + 2);
2549
2550 /* 2k data + 4 byte header */
2551 uASC = (2048 + 4);
2552 break;
2553 }
2554 case 0x01: /* DVD copyright information */
2555 buf[4] = 0; /* no copyright data */
2556 buf[5] = 0; /* no region restrictions */
2557
2558 /* Size of buffer, not including 2 byte size field */
2559 scsiH2BE_U16(buf, 4 + 2);
2560
2561 /* 4 byte header + 4 byte data */
2562 uASC = (4 + 4);
2563 break;
2564
2565 case 0x03: /* BCA information - invalid field for no BCA info */
2566 uASC = -SCSI_ASC_INV_FIELD_IN_CMD_PACKET;
2567 break;
2568
2569 case 0x04: /* DVD disc manufacturing information */
2570 /* Size of buffer, not including 2 byte size field */
2571 scsiH2BE_U16(buf, 2048 + 2);
2572
2573 /* 2k data + 4 byte header */
2574 uASC = (2048 + 4);
2575 break;
2576 case 0xff:
2577 /*
2578 * This lists all the command capabilities above. Add new ones
2579 * in order and update the length and buffer return values.
2580 */
2581
2582 buf[4] = 0x00; /* Physical format */
2583 buf[5] = 0x40; /* Not writable, is readable */
2584 scsiH2BE_U16((buf + 6), 2048 + 4);
2585
2586 buf[8] = 0x01; /* Copyright info */
2587 buf[9] = 0x40; /* Not writable, is readable */
2588 scsiH2BE_U16((buf + 10), 4 + 4);
2589
2590 buf[12] = 0x03; /* BCA info */
2591 buf[13] = 0x40; /* Not writable, is readable */
2592 scsiH2BE_U16((buf + 14), 188 + 4);
2593
2594 buf[16] = 0x04; /* Manufacturing info */
2595 buf[17] = 0x40; /* Not writable, is readable */
2596 scsiH2BE_U16((buf + 18), 2048 + 4);
2597
2598 /* Size of buffer, not including 2 byte size field */
2599 scsiH2BE_U16(buf, 16 + 2);
2600
2601 /* data written + 4 byte header */
2602 uASC = (16 + 4);
2603 break;
2604 default: /** @todo formats beyond DVD-ROM requires */
2605 uASC = -SCSI_ASC_INV_FIELD_IN_CMD_PACKET;
2606 }
2607
2608 if (uASC < 0)
2609 {
2610 s->iSourceSink = ATAFN_SS_NULL;
2611 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, -uASC);
2612 return false;
2613 }
2614 break;
2615 }
2616 /** @todo BD support, fall through for now */
2617 RT_FALL_THRU();
2618
2619 /* Generic disk structures */
2620 case 0x80: /** @todo AACS volume identifier */
2621 case 0x81: /** @todo AACS media serial number */
2622 case 0x82: /** @todo AACS media identifier */
2623 case 0x83: /** @todo AACS media key block */
2624 case 0x90: /** @todo List of recognized format layers */
2625 case 0xc0: /** @todo Write protection status */
2626 default:
2627 s->iSourceSink = ATAFN_SS_NULL;
2628 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
2629 return false;
2630 }
2631
2632 s->iSourceSink = ATAFN_SS_NULL;
2633 atapiR3CmdOK(pCtl, s);
2634 return false;
2635}
2636
2637
2638static bool atapiR3ReadSectors(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s,
2639 uint32_t iATAPILBA, uint32_t cSectors, uint32_t cbSector)
2640{
2641 Assert(cSectors > 0);
2642 s->iCurLBA = iATAPILBA;
2643 s->cbATAPISector = cbSector;
2644 ataR3StartTransfer(pDevIns, pCtl, s, cSectors * cbSector,
2645 PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ, true);
2646 return false;
2647}
2648
2649
2650/**
2651 * Sink/Source: ATAPI READ CAPACITY
2652 */
2653static bool atapiR3ReadCapacitySS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
2654{
2655 uint8_t *pbBuf = s->abIOBuffer;
2656 RT_NOREF(pDevIns, pDevR3);
2657
2658 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
2659 Assert(s->cbElementaryTransfer <= 8);
2660 scsiH2BE_U32(pbBuf, s->cTotalSectors - 1);
2661 scsiH2BE_U32(pbBuf + 4, 2048);
2662 s->iSourceSink = ATAFN_SS_NULL;
2663 atapiR3CmdOK(pCtl, s);
2664 return false;
2665}
2666
2667
2668/**
2669 * Sink/Source: ATAPI READ DISCK INFORMATION
2670 */
2671static bool atapiR3ReadDiscInformationSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
2672{
2673 uint8_t *pbBuf = s->abIOBuffer;
2674 RT_NOREF(pDevIns, pDevR3);
2675
2676 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
2677 Assert(s->cbElementaryTransfer <= 34);
2678 memset(pbBuf, '\0', 34);
2679 scsiH2BE_U16(pbBuf, 32);
2680 pbBuf[2] = (0 << 4) | (3 << 2) | (2 << 0); /* not erasable, complete session, complete disc */
2681 pbBuf[3] = 1; /* number of first track */
2682 pbBuf[4] = 1; /* number of sessions (LSB) */
2683 pbBuf[5] = 1; /* first track number in last session (LSB) */
2684 pbBuf[6] = (uint8_t)pDevR3->pDrvMedia->pfnGetRegionCount(pDevR3->pDrvMedia); /* last track number in last session (LSB) */
2685 pbBuf[7] = (0 << 7) | (0 << 6) | (1 << 5) | (0 << 2) | (0 << 0); /* disc id not valid, disc bar code not valid, unrestricted use, not dirty, not RW medium */
2686 pbBuf[8] = 0; /* disc type = CD-ROM */
2687 pbBuf[9] = 0; /* number of sessions (MSB) */
2688 pbBuf[10] = 0; /* number of sessions (MSB) */
2689 pbBuf[11] = 0; /* number of sessions (MSB) */
2690 scsiH2BE_U32(pbBuf + 16, 0xffffffff); /* last session lead-in start time is not available */
2691 scsiH2BE_U32(pbBuf + 20, 0xffffffff); /* last possible start time for lead-out is not available */
2692 s->iSourceSink = ATAFN_SS_NULL;
2693 atapiR3CmdOK(pCtl, s);
2694 return false;
2695}
2696
2697
2698/**
2699 * Sink/Source: ATAPI READ TRACK INFORMATION
2700 */
2701static bool atapiR3ReadTrackInformationSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
2702{
2703 uint8_t *pbBuf = s->abIOBuffer;
2704 uint32_t u32LogAddr = scsiBE2H_U32(&s->abATAPICmd[2]);
2705 uint8_t u8LogAddrType = s->abATAPICmd[1] & 0x03;
2706 RT_NOREF(pDevIns);
2707
2708 int rc;
2709 uint64_t u64LbaStart = 0;
2710 uint32_t uRegion = 0;
2711 uint64_t cBlocks = 0;
2712 uint64_t cbBlock = 0;
2713 uint8_t u8DataMode = 0xf; /* Unknown data mode. */
2714 uint8_t u8TrackMode = 0;
2715 VDREGIONDATAFORM enmDataForm = VDREGIONDATAFORM_INVALID;
2716
2717 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
2718 Assert(s->cbElementaryTransfer <= 36);
2719
2720 switch (u8LogAddrType)
2721 {
2722 case 0x00:
2723 rc = pDevR3->pDrvMedia->pfnQueryRegionPropertiesForLba(pDevR3->pDrvMedia, u32LogAddr, &uRegion,
2724 NULL, NULL, NULL);
2725 if (RT_SUCCESS(rc))
2726 rc = pDevR3->pDrvMedia->pfnQueryRegionProperties(pDevR3->pDrvMedia, uRegion, &u64LbaStart,
2727 &cBlocks, &cbBlock, &enmDataForm);
2728 break;
2729 case 0x01:
2730 {
2731 if (u32LogAddr >= 1)
2732 {
2733 uRegion = u32LogAddr - 1;
2734 rc = pDevR3->pDrvMedia->pfnQueryRegionProperties(pDevR3->pDrvMedia, uRegion, &u64LbaStart,
2735 &cBlocks, &cbBlock, &enmDataForm);
2736 }
2737 else
2738 rc = VERR_NOT_FOUND; /** @todo Return lead-in information. */
2739 break;
2740 }
2741 case 0x02:
2742 default:
2743 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
2744 return false;
2745 }
2746
2747 if (RT_FAILURE(rc))
2748 {
2749 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
2750 return false;
2751 }
2752
2753 switch (enmDataForm)
2754 {
2755 case VDREGIONDATAFORM_MODE1_2048:
2756 case VDREGIONDATAFORM_MODE1_2352:
2757 case VDREGIONDATAFORM_MODE1_0:
2758 u8DataMode = 1;
2759 break;
2760 case VDREGIONDATAFORM_XA_2336:
2761 case VDREGIONDATAFORM_XA_2352:
2762 case VDREGIONDATAFORM_XA_0:
2763 case VDREGIONDATAFORM_MODE2_2336:
2764 case VDREGIONDATAFORM_MODE2_2352:
2765 case VDREGIONDATAFORM_MODE2_0:
2766 u8DataMode = 2;
2767 break;
2768 default:
2769 u8DataMode = 0xf;
2770 }
2771
2772 if (enmDataForm == VDREGIONDATAFORM_CDDA)
2773 u8TrackMode = 0x0;
2774 else
2775 u8TrackMode = 0x4;
2776
2777 memset(pbBuf, '\0', 36);
2778 scsiH2BE_U16(pbBuf, 34);
2779 pbBuf[2] = uRegion + 1; /* track number (LSB) */
2780 pbBuf[3] = 1; /* session number (LSB) */
2781 pbBuf[5] = (0 << 5) | (0 << 4) | u8TrackMode; /* not damaged, primary copy, data track */
2782 pbBuf[6] = (0 << 7) | (0 << 6) | (0 << 5) | (0 << 6) | u8DataMode; /* not reserved track, not blank, not packet writing, not fixed packet */
2783 pbBuf[7] = (0 << 1) | (0 << 0); /* last recorded address not valid, next recordable address not valid */
2784 scsiH2BE_U32(pbBuf + 8, (uint32_t)u64LbaStart); /* track start address is 0 */
2785 scsiH2BE_U32(pbBuf + 24, (uint32_t)cBlocks); /* track size */
2786 pbBuf[32] = 0; /* track number (MSB) */
2787 pbBuf[33] = 0; /* session number (MSB) */
2788 s->iSourceSink = ATAFN_SS_NULL;
2789 atapiR3CmdOK(pCtl, s);
2790 return false;
2791}
2792
2793static DECLCALLBACK(uint32_t) atapiR3GetConfigurationFillFeatureListProfiles(PATADEVSTATE s, uint8_t *pbBuf, size_t cbBuf)
2794{
2795 RT_NOREF(s);
2796 if (cbBuf < 3*4)
2797 return 0;
2798
2799 scsiH2BE_U16(pbBuf, 0x0); /* feature 0: list of profiles supported */
2800 pbBuf[2] = (0 << 2) | (1 << 1) | (1 << 0); /* version 0, persistent, current */
2801 pbBuf[3] = 8; /* additional bytes for profiles */
2802 /* The MMC-3 spec says that DVD-ROM read capability should be reported
2803 * before CD-ROM read capability. */
2804 scsiH2BE_U16(pbBuf + 4, 0x10); /* profile: read-only DVD */
2805 pbBuf[6] = (0 << 0); /* NOT current profile */
2806 scsiH2BE_U16(pbBuf + 8, 0x08); /* profile: read only CD */
2807 pbBuf[10] = (1 << 0); /* current profile */
2808
2809 return 3*4; /* Header + 2 profiles entries */
2810}
2811
2812static DECLCALLBACK(uint32_t) atapiR3GetConfigurationFillFeatureCore(PATADEVSTATE s, uint8_t *pbBuf, size_t cbBuf)
2813{
2814 RT_NOREF(s);
2815 if (cbBuf < 12)
2816 return 0;
2817
2818 scsiH2BE_U16(pbBuf, 0x1); /* feature 0001h: Core Feature */
2819 pbBuf[2] = (0x2 << 2) | RT_BIT(1) | RT_BIT(0); /* Version | Persistent | Current */
2820 pbBuf[3] = 8; /* Additional length */
2821 scsiH2BE_U16(pbBuf + 4, 0x00000002); /* Physical interface ATAPI. */
2822 pbBuf[8] = RT_BIT(0); /* DBE */
2823 /* Rest is reserved. */
2824
2825 return 12;
2826}
2827
2828static DECLCALLBACK(uint32_t) atapiR3GetConfigurationFillFeatureMorphing(PATADEVSTATE s, uint8_t *pbBuf, size_t cbBuf)
2829{
2830 RT_NOREF(s);
2831 if (cbBuf < 8)
2832 return 0;
2833
2834 scsiH2BE_U16(pbBuf, 0x2); /* feature 0002h: Morphing Feature */
2835 pbBuf[2] = (0x1 << 2) | RT_BIT(1) | RT_BIT(0); /* Version | Persistent | Current */
2836 pbBuf[3] = 4; /* Additional length */
2837 pbBuf[4] = RT_BIT(1) | 0x0; /* OCEvent | !ASYNC */
2838 /* Rest is reserved. */
2839
2840 return 8;
2841}
2842
2843static DECLCALLBACK(uint32_t) atapiR3GetConfigurationFillFeatureRemovableMedium(PATADEVSTATE s, uint8_t *pbBuf, size_t cbBuf)
2844{
2845 RT_NOREF(s);
2846 if (cbBuf < 8)
2847 return 0;
2848
2849 scsiH2BE_U16(pbBuf, 0x3); /* feature 0003h: Removable Medium Feature */
2850 pbBuf[2] = (0x2 << 2) | RT_BIT(1) | RT_BIT(0); /* Version | Persistent | Current */
2851 pbBuf[3] = 4; /* Additional length */
2852 /* Tray type loading | Load | Eject | !Pvnt Jmpr | !DBML | Lock */
2853 pbBuf[4] = (0x2 << 5) | RT_BIT(4) | RT_BIT(3) | (0x0 << 2) | (0x0 << 1) | RT_BIT(0);
2854 /* Rest is reserved. */
2855
2856 return 8;
2857}
2858
2859static DECLCALLBACK(uint32_t) atapiR3GetConfigurationFillFeatureRandomReadable (PATADEVSTATE s, uint8_t *pbBuf, size_t cbBuf)
2860{
2861 RT_NOREF(s);
2862 if (cbBuf < 12)
2863 return 0;
2864
2865 scsiH2BE_U16(pbBuf, 0x10); /* feature 0010h: Random Readable Feature */
2866 pbBuf[2] = (0x0 << 2) | RT_BIT(1) | RT_BIT(0); /* Version | Persistent | Current */
2867 pbBuf[3] = 8; /* Additional length */
2868 scsiH2BE_U32(pbBuf + 4, 2048); /* Logical block size. */
2869 scsiH2BE_U16(pbBuf + 8, 0x10); /* Blocking (0x10 for DVD, CD is not defined). */
2870 pbBuf[10] = 0; /* PP not present */
2871 /* Rest is reserved. */
2872
2873 return 12;
2874}
2875
2876static DECLCALLBACK(uint32_t) atapiR3GetConfigurationFillFeatureCDRead(PATADEVSTATE s, uint8_t *pbBuf, size_t cbBuf)
2877{
2878 RT_NOREF(s);
2879 if (cbBuf < 8)
2880 return 0;
2881
2882 scsiH2BE_U16(pbBuf, 0x1e); /* feature 001Eh: CD Read Feature */
2883 pbBuf[2] = (0x2 << 2) | RT_BIT(1) | RT_BIT(0); /* Version | Persistent | Current */
2884 pbBuf[3] = 0; /* Additional length */
2885 pbBuf[4] = (0x0 << 7) | (0x0 << 1) | 0x0; /* !DAP | !C2-Flags | !CD-Text. */
2886 /* Rest is reserved. */
2887
2888 return 8;
2889}
2890
2891static DECLCALLBACK(uint32_t) atapiR3GetConfigurationFillFeaturePowerManagement(PATADEVSTATE s, uint8_t *pbBuf, size_t cbBuf)
2892{
2893 RT_NOREF(s);
2894 if (cbBuf < 4)
2895 return 0;
2896
2897 scsiH2BE_U16(pbBuf, 0x100); /* feature 0100h: Power Management Feature */
2898 pbBuf[2] = (0x0 << 2) | RT_BIT(1) | RT_BIT(0); /* Version | Persistent | Current */
2899 pbBuf[3] = 0; /* Additional length */
2900
2901 return 4;
2902}
2903
2904static DECLCALLBACK(uint32_t) atapiR3GetConfigurationFillFeatureTimeout(PATADEVSTATE s, uint8_t *pbBuf, size_t cbBuf)
2905{
2906 RT_NOREF(s);
2907 if (cbBuf < 8)
2908 return 0;
2909
2910 scsiH2BE_U16(pbBuf, 0x105); /* feature 0105h: Timeout Feature */
2911 pbBuf[2] = (0x0 << 2) | RT_BIT(1) | RT_BIT(0); /* Version | Persistent | Current */
2912 pbBuf[3] = 4; /* Additional length */
2913 pbBuf[4] = 0x0; /* !Group3 */
2914
2915 return 8;
2916}
2917
2918/**
2919 * Callback to fill in the correct data for a feature.
2920 *
2921 * @returns Number of bytes written into the buffer.
2922 * @param s The ATA device state.
2923 * @param pbBuf The buffer to fill the data with.
2924 * @param cbBuf Size of the buffer.
2925 */
2926typedef DECLCALLBACKTYPE(uint32_t, FNATAPIR3FEATUREFILL,(PATADEVSTATE s, uint8_t *pbBuf, size_t cbBuf));
2927/** Pointer to a feature fill callback. */
2928typedef FNATAPIR3FEATUREFILL *PFNATAPIR3FEATUREFILL;
2929
2930/**
2931 * ATAPI feature descriptor.
2932 */
2933typedef struct ATAPIR3FEATDESC
2934{
2935 /** The feature number. */
2936 uint16_t u16Feat;
2937 /** The callback to fill in the correct data. */
2938 PFNATAPIR3FEATUREFILL pfnFeatureFill;
2939} ATAPIR3FEATDESC;
2940
2941/**
2942 * Array of known ATAPI feature descriptors.
2943 */
2944static const ATAPIR3FEATDESC s_aAtapiR3Features[] =
2945{
2946 { 0x0000, atapiR3GetConfigurationFillFeatureListProfiles},
2947 { 0x0001, atapiR3GetConfigurationFillFeatureCore},
2948 { 0x0002, atapiR3GetConfigurationFillFeatureMorphing},
2949 { 0x0003, atapiR3GetConfigurationFillFeatureRemovableMedium},
2950 { 0x0010, atapiR3GetConfigurationFillFeatureRandomReadable},
2951 { 0x001e, atapiR3GetConfigurationFillFeatureCDRead},
2952 { 0x0100, atapiR3GetConfigurationFillFeaturePowerManagement},
2953 { 0x0105, atapiR3GetConfigurationFillFeatureTimeout}
2954};
2955
2956/**
2957 * Sink/Source: ATAPI GET CONFIGURATION
2958 */
2959static bool atapiR3GetConfigurationSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
2960{
2961 uint32_t const cbIOBuffer = RT_MIN(s->cbIOBuffer, ATA_MAX_IO_BUFFER_SIZE);
2962 uint8_t *pbBuf = s->abIOBuffer;
2963 uint32_t cbBuf = cbIOBuffer;
2964 uint32_t cbCopied = 0;
2965 uint16_t u16Sfn = scsiBE2H_U16(&s->abATAPICmd[2]);
2966 uint8_t u8Rt = s->abATAPICmd[1] & 0x03;
2967 RT_NOREF(pDevIns, pDevR3);
2968
2969 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
2970 Assert(s->cbElementaryTransfer <= 80);
2971 /* Accept valid request types only. */
2972 if (u8Rt == 3)
2973 {
2974 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
2975 return false;
2976 }
2977 memset(pbBuf, '\0', cbBuf);
2978 /** @todo implement switching between CD-ROM and DVD-ROM profile (the only
2979 * way to differentiate them right now is based on the image size). */
2980 if (s->cTotalSectors)
2981 scsiH2BE_U16(pbBuf + 6, 0x08); /* current profile: read-only CD */
2982 else
2983 scsiH2BE_U16(pbBuf + 6, 0x00); /* current profile: none -> no media */
2984 cbBuf -= 8;
2985 pbBuf += 8;
2986
2987 if (u8Rt == 0x2)
2988 {
2989 for (uint32_t i = 0; i < RT_ELEMENTS(s_aAtapiR3Features); i++)
2990 {
2991 if (s_aAtapiR3Features[i].u16Feat == u16Sfn)
2992 {
2993 cbCopied = s_aAtapiR3Features[i].pfnFeatureFill(s, pbBuf, cbBuf);
2994 cbBuf -= cbCopied;
2995 pbBuf += cbCopied;
2996 break;
2997 }
2998 }
2999 }
3000 else
3001 {
3002 for (uint32_t i = 0; i < RT_ELEMENTS(s_aAtapiR3Features); i++)
3003 {
3004 if (s_aAtapiR3Features[i].u16Feat > u16Sfn)
3005 {
3006 cbCopied = s_aAtapiR3Features[i].pfnFeatureFill(s, pbBuf, cbBuf);
3007 cbBuf -= cbCopied;
3008 pbBuf += cbCopied;
3009 }
3010 }
3011 }
3012
3013 /* Set data length now - the field is not included in the final length. */
3014 scsiH2BE_U32(s->abIOBuffer, cbIOBuffer - cbBuf - 4);
3015
3016 /* Other profiles we might want to add in the future: 0x40 (BD-ROM) and 0x50 (HDDVD-ROM) */
3017 s->iSourceSink = ATAFN_SS_NULL;
3018 atapiR3CmdOK(pCtl, s);
3019 return false;
3020}
3021
3022
3023/**
3024 * Sink/Source: ATAPI GET EVENT STATUS NOTIFICATION
3025 */
3026static bool atapiR3GetEventStatusNotificationSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
3027{
3028 uint8_t *pbBuf = s->abIOBuffer;
3029 RT_NOREF(pDevIns, pDevR3);
3030
3031 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
3032 Assert(s->cbElementaryTransfer <= 8);
3033
3034 if (!(s->abATAPICmd[1] & 1))
3035 {
3036 /* no asynchronous operation supported */
3037 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
3038 return false;
3039 }
3040
3041 uint32_t OldStatus, NewStatus;
3042 do
3043 {
3044 OldStatus = ASMAtomicReadU32(&s->MediaEventStatus);
3045 NewStatus = ATA_EVENT_STATUS_UNCHANGED;
3046 switch (OldStatus)
3047 {
3048 case ATA_EVENT_STATUS_MEDIA_NEW:
3049 /* mount */
3050 scsiH2BE_U16(pbBuf + 0, 6);
3051 pbBuf[2] = 0x04; /* media */
3052 pbBuf[3] = 0x5e; /* supported = busy|media|external|power|operational */
3053 pbBuf[4] = 0x02; /* new medium */
3054 pbBuf[5] = 0x02; /* medium present / door closed */
3055 pbBuf[6] = 0x00;
3056 pbBuf[7] = 0x00;
3057 break;
3058
3059 case ATA_EVENT_STATUS_MEDIA_CHANGED:
3060 case ATA_EVENT_STATUS_MEDIA_REMOVED:
3061 /* umount */
3062 scsiH2BE_U16(pbBuf + 0, 6);
3063 pbBuf[2] = 0x04; /* media */
3064 pbBuf[3] = 0x5e; /* supported = busy|media|external|power|operational */
3065 pbBuf[4] = OldStatus == ATA_EVENT_STATUS_MEDIA_CHANGED ? 0x04 /* media changed */ : 0x03; /* media removed */
3066 pbBuf[5] = 0x00; /* medium absent / door closed */
3067 pbBuf[6] = 0x00;
3068 pbBuf[7] = 0x00;
3069 if (OldStatus == ATA_EVENT_STATUS_MEDIA_CHANGED)
3070 NewStatus = ATA_EVENT_STATUS_MEDIA_NEW;
3071 break;
3072
3073 case ATA_EVENT_STATUS_MEDIA_EJECT_REQUESTED: /* currently unused */
3074 scsiH2BE_U16(pbBuf + 0, 6);
3075 pbBuf[2] = 0x04; /* media */
3076 pbBuf[3] = 0x5e; /* supported = busy|media|external|power|operational */
3077 pbBuf[4] = 0x01; /* eject requested (eject button pressed) */
3078 pbBuf[5] = 0x02; /* medium present / door closed */
3079 pbBuf[6] = 0x00;
3080 pbBuf[7] = 0x00;
3081 break;
3082
3083 case ATA_EVENT_STATUS_UNCHANGED:
3084 default:
3085 scsiH2BE_U16(pbBuf + 0, 6);
3086 pbBuf[2] = 0x01; /* operational change request / notification */
3087 pbBuf[3] = 0x5e; /* supported = busy|media|external|power|operational */
3088 pbBuf[4] = 0x00;
3089 pbBuf[5] = 0x00;
3090 pbBuf[6] = 0x00;
3091 pbBuf[7] = 0x00;
3092 break;
3093 }
3094 } while (!ASMAtomicCmpXchgU32(&s->MediaEventStatus, NewStatus, OldStatus));
3095
3096 s->iSourceSink = ATAFN_SS_NULL;
3097 atapiR3CmdOK(pCtl, s);
3098 return false;
3099}
3100
3101
3102/**
3103 * Sink/Source: ATAPI INQUIRY
3104 */
3105static bool atapiR3InquirySS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
3106{
3107 uint8_t *pbBuf = s->abIOBuffer;
3108 RT_NOREF(pDevIns, pDevR3);
3109
3110 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
3111 Assert(s->cbElementaryTransfer <= 36);
3112 pbBuf[0] = 0x05; /* CD-ROM */
3113 pbBuf[1] = 0x80; /* removable */
3114# if 1/*ndef VBOX*/ /** @todo implement MESN + AENC. (async notification on removal and stuff.) */
3115 pbBuf[2] = 0x00; /* ISO */
3116 pbBuf[3] = 0x21; /* ATAPI-2 (XXX: put ATAPI-4 ?) */
3117# else
3118 pbBuf[2] = 0x00; /* ISO */
3119 pbBuf[3] = 0x91; /* format 1, MESN=1, AENC=9 ??? */
3120# endif
3121 pbBuf[4] = 31; /* additional length */
3122 pbBuf[5] = 0; /* reserved */
3123 pbBuf[6] = 0; /* reserved */
3124 pbBuf[7] = 0; /* reserved */
3125 scsiPadStr(pbBuf + 8, s->szInquiryVendorId, 8);
3126 scsiPadStr(pbBuf + 16, s->szInquiryProductId, 16);
3127 scsiPadStr(pbBuf + 32, s->szInquiryRevision, 4);
3128 s->iSourceSink = ATAFN_SS_NULL;
3129 atapiR3CmdOK(pCtl, s);
3130 return false;
3131}
3132
3133
3134/**
3135 * Sink/Source: ATAPI MODE SENSE ERROR RECOVERY
3136 */
3137static bool atapiR3ModeSenseErrorRecoverySS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
3138{
3139 uint8_t *pbBuf = s->abIOBuffer;
3140 RT_NOREF(pDevIns, pDevR3);
3141
3142 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
3143 Assert(s->cbElementaryTransfer <= 16);
3144 scsiH2BE_U16(&pbBuf[0], 16 + 6);
3145 pbBuf[2] = (uint8_t)s->MediaTrackType;
3146 pbBuf[3] = 0;
3147 pbBuf[4] = 0;
3148 pbBuf[5] = 0;
3149 pbBuf[6] = 0;
3150 pbBuf[7] = 0;
3151
3152 pbBuf[8] = 0x01;
3153 pbBuf[9] = 0x06;
3154 pbBuf[10] = 0x00; /* Maximum error recovery */
3155 pbBuf[11] = 0x05; /* 5 retries */
3156 pbBuf[12] = 0x00;
3157 pbBuf[13] = 0x00;
3158 pbBuf[14] = 0x00;
3159 pbBuf[15] = 0x00;
3160 s->iSourceSink = ATAFN_SS_NULL;
3161 atapiR3CmdOK(pCtl, s);
3162 return false;
3163}
3164
3165
3166/**
3167 * Sink/Source: ATAPI MODE SENSE CD STATUS
3168 */
3169static bool atapiR3ModeSenseCDStatusSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
3170{
3171 uint8_t *pbBuf = s->abIOBuffer;
3172 RT_NOREF(pDevIns);
3173
3174 /* 28 bytes of total returned data corresponds to ATAPI 2.6. Note that at least some versions
3175 * of NEC_IDE.SYS DOS driver (possibly other Oak Technology OTI-011 drivers) do not correctly
3176 * handle cases where more than 28 bytes are returned due to bugs. See @bugref{5869}.
3177 */
3178 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
3179 Assert(s->cbElementaryTransfer <= 28);
3180 scsiH2BE_U16(&pbBuf[0], 26);
3181 pbBuf[2] = (uint8_t)s->MediaTrackType;
3182 pbBuf[3] = 0;
3183 pbBuf[4] = 0;
3184 pbBuf[5] = 0;
3185 pbBuf[6] = 0;
3186 pbBuf[7] = 0;
3187
3188 pbBuf[8] = 0x2a;
3189 pbBuf[9] = 18; /* page length */
3190 pbBuf[10] = 0x08; /* DVD-ROM read support */
3191 pbBuf[11] = 0x00; /* no write support */
3192 /* The following claims we support audio play. This is obviously false,
3193 * but the Linux generic CDROM support makes many features depend on this
3194 * capability. If it's not set, this causes many things to be disabled. */
3195 pbBuf[12] = 0x71; /* multisession support, mode 2 form 1/2 support, audio play */
3196 pbBuf[13] = 0x00; /* no subchannel reads supported */
3197 pbBuf[14] = (1 << 0) | (1 << 3) | (1 << 5); /* lock supported, eject supported, tray type loading mechanism */
3198 if (pDevR3->pDrvMount && pDevR3->pDrvMount->pfnIsLocked(pDevR3->pDrvMount))
3199 pbBuf[14] |= 1 << 1; /* report lock state */
3200 pbBuf[15] = 0; /* no subchannel reads supported, no separate audio volume control, no changer etc. */
3201 scsiH2BE_U16(&pbBuf[16], 5632); /* (obsolete) claim 32x speed support */
3202 scsiH2BE_U16(&pbBuf[18], 2); /* number of audio volume levels */
3203 scsiH2BE_U16(&pbBuf[20], RT_MIN(s->cbIOBuffer, ATA_MAX_IO_BUFFER_SIZE) / _1K); /* buffer size supported in Kbyte */
3204 scsiH2BE_U16(&pbBuf[22], 5632); /* (obsolete) current read speed 32x */
3205 pbBuf[24] = 0; /* reserved */
3206 pbBuf[25] = 0; /* reserved for digital audio (see idx 15) */
3207 pbBuf[26] = 0; /* reserved */
3208 pbBuf[27] = 0; /* reserved */
3209 s->iSourceSink = ATAFN_SS_NULL;
3210 atapiR3CmdOK(pCtl, s);
3211 return false;
3212}
3213
3214
3215/**
3216 * Sink/Source: ATAPI REQUEST SENSE
3217 */
3218static bool atapiR3RequestSenseSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
3219{
3220 uint8_t *pbBuf = s->abIOBuffer;
3221 RT_NOREF(pDevIns, pDevR3);
3222
3223 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
3224 memset(pbBuf, '\0', RT_MIN(s->cbElementaryTransfer, sizeof(s->abIOBuffer)));
3225 AssertCompile(sizeof(s->abIOBuffer) >= sizeof(s->abATAPISense));
3226 memcpy(pbBuf, s->abATAPISense, RT_MIN(s->cbElementaryTransfer, sizeof(s->abATAPISense)));
3227 s->iSourceSink = ATAFN_SS_NULL;
3228 atapiR3CmdOK(pCtl, s);
3229 return false;
3230}
3231
3232
3233/**
3234 * Sink/Source: ATAPI MECHANISM STATUS
3235 */
3236static bool atapiR3MechanismStatusSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
3237{
3238 uint8_t *pbBuf = s->abIOBuffer;
3239 RT_NOREF(pDevIns, pDevR3);
3240
3241 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
3242 Assert(s->cbElementaryTransfer <= 8);
3243 scsiH2BE_U16(pbBuf, 0);
3244 /* no current LBA */
3245 pbBuf[2] = 0;
3246 pbBuf[3] = 0;
3247 pbBuf[4] = 0;
3248 pbBuf[5] = 1;
3249 scsiH2BE_U16(pbBuf + 6, 0);
3250 s->iSourceSink = ATAFN_SS_NULL;
3251 atapiR3CmdOK(pCtl, s);
3252 return false;
3253}
3254
3255
3256/**
3257 * Sink/Source: ATAPI READ TOC NORMAL
3258 */
3259static bool atapiR3ReadTOCNormalSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
3260{
3261 uint8_t *pbBuf = s->abIOBuffer;
3262 uint8_t *q;
3263 uint8_t iStartTrack;
3264 bool fMSF;
3265 uint32_t cbSize;
3266 RT_NOREF(pDevIns);
3267
3268 /* Track fields are 8-bit and 1-based, so cut the track count at 255,
3269 avoiding any potential buffer overflow issues below. */
3270 uint32_t cTracks = pDevR3->pDrvMedia->pfnGetRegionCount(pDevR3->pDrvMedia);
3271 AssertStmt(cTracks <= UINT8_MAX, cTracks = UINT8_MAX);
3272 AssertCompile(sizeof(s->abIOBuffer) >= 2 + 256 + 8);
3273
3274 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
3275 fMSF = (s->abATAPICmd[1] >> 1) & 1;
3276 iStartTrack = s->abATAPICmd[6];
3277 if (iStartTrack == 0)
3278 iStartTrack = 1;
3279
3280 if (iStartTrack > cTracks && iStartTrack != 0xaa)
3281 {
3282 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
3283 return false;
3284 }
3285 q = pbBuf + 2;
3286 *q++ = iStartTrack; /* first track number */
3287 *q++ = cTracks; /* last track number */
3288 for (uint32_t iTrack = iStartTrack; iTrack <= cTracks; iTrack++)
3289 {
3290 uint64_t uLbaStart = 0;
3291 VDREGIONDATAFORM enmDataForm = VDREGIONDATAFORM_MODE1_2048;
3292
3293 int rc = pDevR3->pDrvMedia->pfnQueryRegionProperties(pDevR3->pDrvMedia, iTrack - 1, &uLbaStart,
3294 NULL, NULL, &enmDataForm);
3295 AssertRC(rc);
3296
3297 *q++ = 0; /* reserved */
3298
3299 if (enmDataForm == VDREGIONDATAFORM_CDDA)
3300 *q++ = 0x10; /* ADR, control */
3301 else
3302 *q++ = 0x14; /* ADR, control */
3303
3304 *q++ = (uint8_t)iTrack; /* track number */
3305 *q++ = 0; /* reserved */
3306 if (fMSF)
3307 {
3308 *q++ = 0; /* reserved */
3309 scsiLBA2MSF(q, (uint32_t)uLbaStart);
3310 q += 3;
3311 }
3312 else
3313 {
3314 /* sector 0 */
3315 scsiH2BE_U32(q, (uint32_t)uLbaStart);
3316 q += 4;
3317 }
3318 }
3319 /* lead out track */
3320 *q++ = 0; /* reserved */
3321 *q++ = 0x14; /* ADR, control */
3322 *q++ = 0xaa; /* track number */
3323 *q++ = 0; /* reserved */
3324
3325 /* Query start and length of last track to get the start of the lead out track. */
3326 uint64_t uLbaStart = 0;
3327 uint64_t cBlocks = 0;
3328
3329 int rc = pDevR3->pDrvMedia->pfnQueryRegionProperties(pDevR3->pDrvMedia, cTracks - 1, &uLbaStart,
3330 &cBlocks, NULL, NULL);
3331 AssertRC(rc);
3332
3333 uLbaStart += cBlocks;
3334 if (fMSF)
3335 {
3336 *q++ = 0; /* reserved */
3337 scsiLBA2MSF(q, (uint32_t)uLbaStart);
3338 q += 3;
3339 }
3340 else
3341 {
3342 scsiH2BE_U32(q, (uint32_t)uLbaStart);
3343 q += 4;
3344 }
3345 cbSize = q - pbBuf;
3346 scsiH2BE_U16(pbBuf, cbSize - 2);
3347 if (cbSize < s->cbTotalTransfer)
3348 s->cbTotalTransfer = cbSize;
3349 s->iSourceSink = ATAFN_SS_NULL;
3350 atapiR3CmdOK(pCtl, s);
3351 return false;
3352}
3353
3354
3355/**
3356 * Sink/Source: ATAPI READ TOC MULTI
3357 */
3358static bool atapiR3ReadTOCMultiSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
3359{
3360 uint8_t *pbBuf = s->abIOBuffer;
3361 bool fMSF;
3362 RT_NOREF(pDevIns);
3363
3364 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
3365 Assert(s->cbElementaryTransfer <= 12);
3366 fMSF = (s->abATAPICmd[1] >> 1) & 1;
3367 /* multi session: only a single session defined */
3368 /** @todo double-check this stuff against what a real drive says for a CD-ROM (not a CD-R)
3369 * with only a single data session. Maybe solve the problem with "cdrdao read-toc" not being
3370 * able to figure out whether numbers are in BCD or hex. */
3371 memset(pbBuf, 0, 12);
3372 pbBuf[1] = 0x0a;
3373 pbBuf[2] = 0x01;
3374 pbBuf[3] = 0x01;
3375
3376 VDREGIONDATAFORM enmDataForm = VDREGIONDATAFORM_MODE1_2048;
3377 int rc = pDevR3->pDrvMedia->pfnQueryRegionProperties(pDevR3->pDrvMedia, 0, NULL, NULL, NULL, &enmDataForm);
3378 AssertRC(rc);
3379
3380 if (enmDataForm == VDREGIONDATAFORM_CDDA)
3381 pbBuf[5] = 0x10; /* ADR, control */
3382 else
3383 pbBuf[5] = 0x14; /* ADR, control */
3384
3385 pbBuf[6] = 1; /* first track in last complete session */
3386 if (fMSF)
3387 {
3388 pbBuf[8] = 0; /* reserved */
3389 scsiLBA2MSF(&pbBuf[9], 0);
3390 }
3391 else
3392 {
3393 /* sector 0 */
3394 scsiH2BE_U32(pbBuf + 8, 0);
3395 }
3396 s->iSourceSink = ATAFN_SS_NULL;
3397 atapiR3CmdOK(pCtl, s);
3398 return false;
3399}
3400
3401
3402/**
3403 * Sink/Source: ATAPI READ TOC RAW
3404 */
3405static bool atapiR3ReadTOCRawSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
3406{
3407 uint8_t *pbBuf = s->abIOBuffer;
3408 uint8_t *q;
3409 uint8_t iStartTrack;
3410 bool fMSF;
3411 uint32_t cbSize;
3412 RT_NOREF(pDevIns, pDevR3);
3413
3414 Assert(s->uTxDir == PDMMEDIATXDIR_FROM_DEVICE);
3415 fMSF = (s->abATAPICmd[1] >> 1) & 1;
3416 iStartTrack = s->abATAPICmd[6];
3417
3418 q = pbBuf + 2;
3419 *q++ = 1; /* first session */
3420 *q++ = 1; /* last session */
3421
3422 *q++ = 1; /* session number */
3423 *q++ = 0x14; /* data track */
3424 *q++ = 0; /* track number */
3425 *q++ = 0xa0; /* first track in program area */
3426 *q++ = 0; /* min */
3427 *q++ = 0; /* sec */
3428 *q++ = 0; /* frame */
3429 *q++ = 0;
3430 *q++ = 1; /* first track */
3431 *q++ = 0x00; /* disk type CD-DA or CD data */
3432 *q++ = 0;
3433
3434 *q++ = 1; /* session number */
3435 *q++ = 0x14; /* data track */
3436 *q++ = 0; /* track number */
3437 *q++ = 0xa1; /* last track in program area */
3438 *q++ = 0; /* min */
3439 *q++ = 0; /* sec */
3440 *q++ = 0; /* frame */
3441 *q++ = 0;
3442 *q++ = 1; /* last track */
3443 *q++ = 0;
3444 *q++ = 0;
3445
3446 *q++ = 1; /* session number */
3447 *q++ = 0x14; /* data track */
3448 *q++ = 0; /* track number */
3449 *q++ = 0xa2; /* lead-out */
3450 *q++ = 0; /* min */
3451 *q++ = 0; /* sec */
3452 *q++ = 0; /* frame */
3453 if (fMSF)
3454 {
3455 *q++ = 0; /* reserved */
3456 scsiLBA2MSF(q, s->cTotalSectors);
3457 q += 3;
3458 }
3459 else
3460 {
3461 scsiH2BE_U32(q, s->cTotalSectors);
3462 q += 4;
3463 }
3464
3465 *q++ = 1; /* session number */
3466 *q++ = 0x14; /* ADR, control */
3467 *q++ = 0; /* track number */
3468 *q++ = 1; /* point */
3469 *q++ = 0; /* min */
3470 *q++ = 0; /* sec */
3471 *q++ = 0; /* frame */
3472 if (fMSF)
3473 {
3474 *q++ = 0; /* reserved */
3475 scsiLBA2MSF(q, 0);
3476 q += 3;
3477 }
3478 else
3479 {
3480 /* sector 0 */
3481 scsiH2BE_U32(q, 0);
3482 q += 4;
3483 }
3484
3485 cbSize = q - pbBuf;
3486 scsiH2BE_U16(pbBuf, cbSize - 2);
3487 if (cbSize < s->cbTotalTransfer)
3488 s->cbTotalTransfer = cbSize;
3489 s->iSourceSink = ATAFN_SS_NULL;
3490 atapiR3CmdOK(pCtl, s);
3491 return false;
3492}
3493
3494
3495static void atapiR3ParseCmdVirtualATAPI(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
3496{
3497 const uint8_t *pbPacket = s->abATAPICmd;
3498 uint32_t cbMax;
3499 uint32_t cSectors, iATAPILBA;
3500
3501 switch (pbPacket[0])
3502 {
3503 case SCSI_TEST_UNIT_READY:
3504 if (s->cNotifiedMediaChange > 0)
3505 {
3506 if (s->cNotifiedMediaChange-- > 2)
3507 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3508 else
3509 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3510 }
3511 else
3512 {
3513 PPDMIMOUNT const pDrvMount = pDevR3->pDrvMount;
3514 if (pDrvMount && pDrvMount->pfnIsMounted(pDrvMount))
3515 atapiR3CmdOK(pCtl, s);
3516 else
3517 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3518 }
3519 break;
3520 case SCSI_GET_EVENT_STATUS_NOTIFICATION:
3521 cbMax = scsiBE2H_U16(pbPacket + 7);
3522 ataR3StartTransfer(pDevIns, pCtl, s, RT_MIN(cbMax, 8), PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_GET_EVENT_STATUS_NOTIFICATION, true);
3523 break;
3524 case SCSI_MODE_SENSE_10:
3525 {
3526 uint8_t uPageControl, uPageCode;
3527 cbMax = scsiBE2H_U16(pbPacket + 7);
3528 uPageControl = pbPacket[2] >> 6;
3529 uPageCode = pbPacket[2] & 0x3f;
3530 switch (uPageControl)
3531 {
3532 case SCSI_PAGECONTROL_CURRENT:
3533 switch (uPageCode)
3534 {
3535 case SCSI_MODEPAGE_ERROR_RECOVERY:
3536 ataR3StartTransfer(pDevIns, pCtl, s, RT_MIN(cbMax, 16), PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_MODE_SENSE_ERROR_RECOVERY, true);
3537 break;
3538 case SCSI_MODEPAGE_CD_STATUS:
3539 ataR3StartTransfer(pDevIns, pCtl, s, RT_MIN(cbMax, 28), PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_MODE_SENSE_CD_STATUS, true);
3540 break;
3541 default:
3542 goto error_cmd;
3543 }
3544 break;
3545 case SCSI_PAGECONTROL_CHANGEABLE:
3546 goto error_cmd;
3547 case SCSI_PAGECONTROL_DEFAULT:
3548 goto error_cmd;
3549 default:
3550 case SCSI_PAGECONTROL_SAVED:
3551 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_SAVING_PARAMETERS_NOT_SUPPORTED);
3552 break;
3553 }
3554 break;
3555 }
3556 case SCSI_REQUEST_SENSE:
3557 cbMax = pbPacket[4];
3558 ataR3StartTransfer(pDevIns, pCtl, s, RT_MIN(cbMax, 18), PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_REQUEST_SENSE, true);
3559 break;
3560 case SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL:
3561 {
3562 PPDMIMOUNT const pDrvMount = pDevR3->pDrvMount;
3563 if (pDrvMount && pDrvMount->pfnIsMounted(pDrvMount))
3564 {
3565 if (pbPacket[4] & 1)
3566 pDrvMount->pfnLock(pDrvMount);
3567 else
3568 pDrvMount->pfnUnlock(pDrvMount);
3569 atapiR3CmdOK(pCtl, s);
3570 }
3571 else
3572 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3573 break;
3574 }
3575 case SCSI_READ_10:
3576 case SCSI_READ_12:
3577 {
3578 if (s->cNotifiedMediaChange > 0)
3579 {
3580 s->cNotifiedMediaChange-- ;
3581 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3582 break;
3583 }
3584 if (!pDevR3->pDrvMount || !pDevR3->pDrvMount->pfnIsMounted(pDevR3->pDrvMount))
3585 {
3586 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3587 break;
3588 }
3589 if (pbPacket[0] == SCSI_READ_10)
3590 cSectors = scsiBE2H_U16(pbPacket + 7);
3591 else
3592 cSectors = scsiBE2H_U32(pbPacket + 6);
3593 iATAPILBA = scsiBE2H_U32(pbPacket + 2);
3594
3595 if (cSectors == 0)
3596 {
3597 atapiR3CmdOK(pCtl, s);
3598 break;
3599 }
3600
3601 /* Check that the sector size is valid. */
3602 VDREGIONDATAFORM enmDataForm = VDREGIONDATAFORM_INVALID;
3603 int rc = pDevR3->pDrvMedia->pfnQueryRegionPropertiesForLba(pDevR3->pDrvMedia, iATAPILBA,
3604 NULL, NULL, NULL, &enmDataForm);
3605 if (RT_UNLIKELY( rc == VERR_NOT_FOUND
3606 || ((uint64_t)iATAPILBA + cSectors > s->cTotalSectors)))
3607 {
3608 /* Rate limited logging, one log line per second. For
3609 * guests that insist on reading from places outside the
3610 * valid area this often generates too many release log
3611 * entries otherwise. */
3612 static uint64_t uLastLogTS = 0;
3613 if (RTTimeMilliTS() >= uLastLogTS + 1000)
3614 {
3615 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM block number %Ld invalid (READ)\n", s->iLUN, (uint64_t)iATAPILBA + cSectors));
3616 uLastLogTS = RTTimeMilliTS();
3617 }
3618 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_LOGICAL_BLOCK_OOR);
3619 break;
3620 }
3621 else if ( enmDataForm != VDREGIONDATAFORM_MODE1_2048
3622 && enmDataForm != VDREGIONDATAFORM_MODE1_2352
3623 && enmDataForm != VDREGIONDATAFORM_MODE2_2336
3624 && enmDataForm != VDREGIONDATAFORM_MODE2_2352
3625 && enmDataForm != VDREGIONDATAFORM_RAW)
3626 {
3627 uint8_t abATAPISense[ATAPI_SENSE_SIZE];
3628 RT_ZERO(abATAPISense);
3629
3630 abATAPISense[0] = 0x70 | (1 << 7);
3631 abATAPISense[2] = (SCSI_SENSE_ILLEGAL_REQUEST & 0x0f) | SCSI_SENSE_FLAG_ILI;
3632 scsiH2BE_U32(&abATAPISense[3], iATAPILBA);
3633 abATAPISense[7] = 10;
3634 abATAPISense[12] = SCSI_ASC_ILLEGAL_MODE_FOR_THIS_TRACK;
3635 atapiR3CmdError(pCtl, s, &abATAPISense[0], sizeof(abATAPISense));
3636 break;
3637 }
3638 atapiR3ReadSectors(pDevIns, pCtl, s, iATAPILBA, cSectors, 2048);
3639 break;
3640 }
3641 case SCSI_READ_CD_MSF:
3642 case SCSI_READ_CD:
3643 {
3644 if (s->cNotifiedMediaChange > 0)
3645 {
3646 s->cNotifiedMediaChange-- ;
3647 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3648 break;
3649 }
3650 if (!pDevR3->pDrvMount || !pDevR3->pDrvMount->pfnIsMounted(pDevR3->pDrvMount))
3651 {
3652 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3653 break;
3654 }
3655 if ((pbPacket[10] & 0x7) != 0)
3656 {
3657 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
3658 break;
3659 }
3660 if (pbPacket[0] == SCSI_READ_CD)
3661 {
3662 cSectors = (pbPacket[6] << 16) | (pbPacket[7] << 8) | pbPacket[8];
3663 iATAPILBA = scsiBE2H_U32(pbPacket + 2);
3664 }
3665 else /* READ CD MSF */
3666 {
3667 iATAPILBA = scsiMSF2LBA(pbPacket + 3);
3668 if (iATAPILBA > scsiMSF2LBA(pbPacket + 6))
3669 {
3670 Log2(("Start MSF %02u:%02u:%02u > end MSF %02u:%02u:%02u!\n", *(pbPacket + 3), *(pbPacket + 4), *(pbPacket + 5),
3671 *(pbPacket + 6), *(pbPacket + 7), *(pbPacket + 8)));
3672 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
3673 break;
3674 }
3675 cSectors = scsiMSF2LBA(pbPacket + 6) - iATAPILBA;
3676 Log2(("Start MSF %02u:%02u:%02u -> LBA %u\n", *(pbPacket + 3), *(pbPacket + 4), *(pbPacket + 5), iATAPILBA));
3677 Log2(("End MSF %02u:%02u:%02u -> %u sectors\n", *(pbPacket + 6), *(pbPacket + 7), *(pbPacket + 8), cSectors));
3678 }
3679 if (cSectors == 0)
3680 {
3681 atapiR3CmdOK(pCtl, s);
3682 break;
3683 }
3684 if ((uint64_t)iATAPILBA + cSectors > s->cTotalSectors)
3685 {
3686 /* Rate limited logging, one log line per second. For
3687 * guests that insist on reading from places outside the
3688 * valid area this often generates too many release log
3689 * entries otherwise. */
3690 static uint64_t uLastLogTS = 0;
3691 if (RTTimeMilliTS() >= uLastLogTS + 1000)
3692 {
3693 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM block number %Ld invalid (READ CD)\n", s->iLUN, (uint64_t)iATAPILBA + cSectors));
3694 uLastLogTS = RTTimeMilliTS();
3695 }
3696 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_LOGICAL_BLOCK_OOR);
3697 break;
3698 }
3699 /*
3700 * If the LBA is in an audio track we are required to ignore pretty much all
3701 * of the channel selection values (except 0x00) and map everything to 0x10
3702 * which means read user data with a sector size of 2352 bytes.
3703 *
3704 * (MMC-6 chapter 6.19.2.6)
3705 */
3706 uint8_t uChnSel = pbPacket[9] & 0xf8;
3707 VDREGIONDATAFORM enmDataForm;
3708 int rc = pDevR3->pDrvMedia->pfnQueryRegionPropertiesForLba(pDevR3->pDrvMedia, iATAPILBA,
3709 NULL, NULL, NULL, &enmDataForm);
3710 AssertRC(rc);
3711
3712 if (enmDataForm == VDREGIONDATAFORM_CDDA)
3713 {
3714 if (uChnSel == 0)
3715 {
3716 /* nothing */
3717 atapiR3CmdOK(pCtl, s);
3718 }
3719 else
3720 atapiR3ReadSectors(pDevIns, pCtl, s, iATAPILBA, cSectors, 2352);
3721 }
3722 else
3723 {
3724 switch (uChnSel)
3725 {
3726 case 0x00:
3727 /* nothing */
3728 atapiR3CmdOK(pCtl, s);
3729 break;
3730 case 0x10:
3731 /* normal read */
3732 atapiR3ReadSectors(pDevIns, pCtl, s, iATAPILBA, cSectors, 2048);
3733 break;
3734 case 0xf8:
3735 /* read all data */
3736 atapiR3ReadSectors(pDevIns, pCtl, s, iATAPILBA, cSectors, 2352);
3737 break;
3738 default:
3739 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM sector format not supported (%#x)\n", s->iLUN, pbPacket[9] & 0xf8));
3740 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
3741 break;
3742 }
3743 }
3744 break;
3745 }
3746 case SCSI_SEEK_10:
3747 {
3748 if (s->cNotifiedMediaChange > 0)
3749 {
3750 s->cNotifiedMediaChange-- ;
3751 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3752 break;
3753 }
3754 if (!pDevR3->pDrvMount || !pDevR3->pDrvMount->pfnIsMounted(pDevR3->pDrvMount))
3755 {
3756 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3757 break;
3758 }
3759 iATAPILBA = scsiBE2H_U32(pbPacket + 2);
3760 if (iATAPILBA > s->cTotalSectors)
3761 {
3762 /* Rate limited logging, one log line per second. For
3763 * guests that insist on seeking to places outside the
3764 * valid area this often generates too many release log
3765 * entries otherwise. */
3766 static uint64_t uLastLogTS = 0;
3767 if (RTTimeMilliTS() >= uLastLogTS + 1000)
3768 {
3769 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM block number %Ld invalid (SEEK)\n", s->iLUN, (uint64_t)iATAPILBA));
3770 uLastLogTS = RTTimeMilliTS();
3771 }
3772 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_LOGICAL_BLOCK_OOR);
3773 break;
3774 }
3775 atapiR3CmdOK(pCtl, s);
3776 ataSetStatus(pCtl, s, ATA_STAT_SEEK); /* Linux expects this. Required by ATAPI 2.x when seek completes. */
3777 break;
3778 }
3779 case SCSI_START_STOP_UNIT:
3780 {
3781 int rc = VINF_SUCCESS;
3782 switch (pbPacket[4] & 3)
3783 {
3784 case 0: /* 00 - Stop motor */
3785 case 1: /* 01 - Start motor */
3786 break;
3787 case 2: /* 10 - Eject media */
3788 {
3789 /* This must be done from EMT. */
3790 PATASTATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PATASTATER3);
3791 PPDMIMOUNT pDrvMount = pDevR3->pDrvMount;
3792 if (pDrvMount)
3793 {
3794 ataR3LockLeave(pDevIns, pCtl);
3795
3796 rc = PDMDevHlpVMReqPriorityCallWait(pDevIns, VMCPUID_ANY,
3797 (PFNRT)pDrvMount->pfnUnmount, 3,
3798 pDrvMount, false /*=fForce*/, true /*=fEject*/);
3799 Assert(RT_SUCCESS(rc) || rc == VERR_PDM_MEDIA_LOCKED || rc == VERR_PDM_MEDIA_NOT_MOUNTED);
3800 if (RT_SUCCESS(rc) && pThisCC->pMediaNotify)
3801 {
3802 rc = PDMDevHlpVMReqCallNoWait(pDevIns, VMCPUID_ANY,
3803 (PFNRT)pThisCC->pMediaNotify->pfnEjected, 2,
3804 pThisCC->pMediaNotify, s->iLUN);
3805 AssertRC(rc);
3806 }
3807
3808 ataR3LockEnter(pDevIns, pCtl);
3809 }
3810 else
3811 rc = VINF_SUCCESS;
3812 break;
3813 }
3814 case 3: /* 11 - Load media */
3815 /** @todo rc = pDevR3->pDrvMount->pfnLoadMedia(pDevR3->pDrvMount) */
3816 break;
3817 }
3818 if (RT_SUCCESS(rc))
3819 {
3820 atapiR3CmdOK(pCtl, s);
3821 ataSetStatus(pCtl, s, ATA_STAT_SEEK); /* Needed by NT 3.51/4.0, see @bugref{5869}. */
3822 }
3823 else
3824 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIA_LOAD_OR_EJECT_FAILED);
3825 break;
3826 }
3827 case SCSI_MECHANISM_STATUS:
3828 {
3829 cbMax = scsiBE2H_U16(pbPacket + 8);
3830 ataR3StartTransfer(pDevIns, pCtl, s, RT_MIN(cbMax, 8), PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_MECHANISM_STATUS, true);
3831 break;
3832 }
3833 case SCSI_READ_TOC_PMA_ATIP:
3834 {
3835 uint8_t format;
3836
3837 if (s->cNotifiedMediaChange > 0)
3838 {
3839 s->cNotifiedMediaChange-- ;
3840 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3841 break;
3842 }
3843 if (!pDevR3->pDrvMount || !pDevR3->pDrvMount->pfnIsMounted(pDevR3->pDrvMount))
3844 {
3845 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3846 break;
3847 }
3848 cbMax = scsiBE2H_U16(pbPacket + 7);
3849 /* SCSI MMC-3 spec says format is at offset 2 (lower 4 bits),
3850 * but Linux kernel uses offset 9 (topmost 2 bits). Hope that
3851 * the other field is clear... */
3852 format = (pbPacket[2] & 0xf) | (pbPacket[9] >> 6);
3853 switch (format)
3854 {
3855 case 0:
3856 ataR3StartTransfer(pDevIns, pCtl, s, cbMax, PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ_TOC_NORMAL, true);
3857 break;
3858 case 1:
3859 ataR3StartTransfer(pDevIns, pCtl, s, RT_MIN(cbMax, 12), PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ_TOC_MULTI, true);
3860 break;
3861 case 2:
3862 ataR3StartTransfer(pDevIns, pCtl, s, cbMax, PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ_TOC_RAW, true);
3863 break;
3864 default:
3865 error_cmd:
3866 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
3867 break;
3868 }
3869 break;
3870 }
3871 case SCSI_READ_CAPACITY:
3872 if (s->cNotifiedMediaChange > 0)
3873 {
3874 s->cNotifiedMediaChange-- ;
3875 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3876 break;
3877 }
3878 if (!pDevR3->pDrvMount || !pDevR3->pDrvMount->pfnIsMounted(pDevR3->pDrvMount))
3879 {
3880 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3881 break;
3882 }
3883 ataR3StartTransfer(pDevIns, pCtl, s, 8, PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ_CAPACITY, true);
3884 break;
3885 case SCSI_READ_DISC_INFORMATION:
3886 if (s->cNotifiedMediaChange > 0)
3887 {
3888 s->cNotifiedMediaChange-- ;
3889 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3890 break;
3891 }
3892 if (!pDevR3->pDrvMount || !pDevR3->pDrvMount->pfnIsMounted(pDevR3->pDrvMount))
3893 {
3894 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3895 break;
3896 }
3897 cbMax = scsiBE2H_U16(pbPacket + 7);
3898 ataR3StartTransfer(pDevIns, pCtl, s, RT_MIN(cbMax, 34), PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ_DISC_INFORMATION, true);
3899 break;
3900 case SCSI_READ_TRACK_INFORMATION:
3901 if (s->cNotifiedMediaChange > 0)
3902 {
3903 s->cNotifiedMediaChange-- ;
3904 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3905 break;
3906 }
3907 if (!pDevR3->pDrvMount || !pDevR3->pDrvMount->pfnIsMounted(pDevR3->pDrvMount))
3908 {
3909 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3910 break;
3911 }
3912 cbMax = scsiBE2H_U16(pbPacket + 7);
3913 ataR3StartTransfer(pDevIns, pCtl, s, RT_MIN(cbMax, 36), PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ_TRACK_INFORMATION, true);
3914 break;
3915 case SCSI_GET_CONFIGURATION:
3916 /* No media change stuff here, it can confuse Linux guests. */
3917 cbMax = scsiBE2H_U16(pbPacket + 7);
3918 ataR3StartTransfer(pDevIns, pCtl, s, RT_MIN(cbMax, 80), PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_GET_CONFIGURATION, true);
3919 break;
3920 case SCSI_INQUIRY:
3921 cbMax = scsiBE2H_U16(pbPacket + 3);
3922 ataR3StartTransfer(pDevIns, pCtl, s, RT_MIN(cbMax, 36), PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_INQUIRY, true);
3923 break;
3924 case SCSI_READ_DVD_STRUCTURE:
3925 cbMax = scsiBE2H_U16(pbPacket + 8);
3926 ataR3StartTransfer(pDevIns, pCtl, s, RT_MIN(cbMax, 4), PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ_DVD_STRUCTURE, true);
3927 break;
3928 default:
3929 atapiR3CmdErrorSimple(pCtl, s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ILLEGAL_OPCODE);
3930 break;
3931 }
3932}
3933
3934
3935/*
3936 * Parse ATAPI commands, passing them directly to the CD/DVD drive.
3937 */
3938static void atapiR3ParseCmdPassthrough(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
3939{
3940 const uint8_t *pbPacket = &s->abATAPICmd[0];
3941
3942 /* Some cases we have to handle here. */
3943 if ( pbPacket[0] == SCSI_GET_EVENT_STATUS_NOTIFICATION
3944 && ASMAtomicReadU32(&s->MediaEventStatus) != ATA_EVENT_STATUS_UNCHANGED)
3945 {
3946 uint32_t cbTransfer = scsiBE2H_U16(pbPacket + 7);
3947 ataR3StartTransfer(pDevIns, pCtl, s, RT_MIN(cbTransfer, 8), PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_GET_EVENT_STATUS_NOTIFICATION, true);
3948 }
3949 else if ( pbPacket[0] == SCSI_REQUEST_SENSE
3950 && (s->abATAPISense[2] & 0x0f) != SCSI_SENSE_NONE)
3951 ataR3StartTransfer(pDevIns, pCtl, s, RT_MIN(pbPacket[4], 18), PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_REQUEST_SENSE, true);
3952 else
3953 {
3954 size_t cbBuf = 0;
3955 size_t cbATAPISector = 0;
3956 size_t cbTransfer = 0;
3957 PDMMEDIATXDIR uTxDir = PDMMEDIATXDIR_NONE;
3958 uint8_t u8ScsiSts = SCSI_STATUS_OK;
3959
3960 if (pbPacket[0] == SCSI_FORMAT_UNIT || pbPacket[0] == SCSI_GET_PERFORMANCE)
3961 cbBuf = s->uATARegLCyl | (s->uATARegHCyl << 8); /* use ATAPI transfer length */
3962
3963 bool fPassthrough = ATAPIPassthroughParseCdb(pbPacket, sizeof(s->abATAPICmd), cbBuf, pDevR3->pTrackList,
3964 &s->abATAPISense[0], sizeof(s->abATAPISense), &uTxDir, &cbTransfer,
3965 &cbATAPISector, &u8ScsiSts);
3966 if (fPassthrough)
3967 {
3968 s->cbATAPISector = (uint32_t)cbATAPISector;
3969 Assert(s->cbATAPISector == (uint32_t)cbATAPISector);
3970 Assert(cbTransfer == (uint32_t)cbTransfer);
3971
3972 /*
3973 * Send a command to the drive, passing data in/out as required.
3974 * Commands which exceed the I/O buffer size are split below
3975 * or aborted if splitting is not implemented.
3976 */
3977 Log2(("ATAPI PT: max size %d\n", cbTransfer));
3978 if (cbTransfer == 0)
3979 uTxDir = PDMMEDIATXDIR_NONE;
3980 ataR3StartTransfer(pDevIns, pCtl, s, (uint32_t)cbTransfer, uTxDir, ATAFN_BT_ATAPI_PASSTHROUGH_CMD, ATAFN_SS_ATAPI_PASSTHROUGH, true);
3981 }
3982 else if (u8ScsiSts == SCSI_STATUS_CHECK_CONDITION)
3983 {
3984 /* Sense data is already set, end the request and notify the guest. */
3985 Log(("%s: sense=%#x (%s) asc=%#x ascq=%#x (%s)\n", __FUNCTION__, s->abATAPISense[2] & 0x0f, SCSISenseText(s->abATAPISense[2] & 0x0f),
3986 s->abATAPISense[12], s->abATAPISense[13], SCSISenseExtText(s->abATAPISense[12], s->abATAPISense[13])));
3987 s->uATARegError = s->abATAPISense[2] << 4;
3988 ataSetStatusValue(pCtl, s, ATA_STAT_READY | ATA_STAT_ERR);
3989 s->uATARegNSector = (s->uATARegNSector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
3990 Log2(("%s: interrupt reason %#04x\n", __FUNCTION__, s->uATARegNSector));
3991 s->cbTotalTransfer = 0;
3992 s->cbElementaryTransfer = 0;
3993 s->cbAtapiPassthroughTransfer = 0;
3994 s->iIOBufferCur = 0;
3995 s->iIOBufferEnd = 0;
3996 s->uTxDir = PDMMEDIATXDIR_NONE;
3997 s->iBeginTransfer = ATAFN_BT_NULL;
3998 s->iSourceSink = ATAFN_SS_NULL;
3999 }
4000 else if (u8ScsiSts == SCSI_STATUS_OK)
4001 atapiR3CmdOK(pCtl, s);
4002 }
4003}
4004
4005
4006static void atapiR3ParseCmd(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
4007{
4008 const uint8_t *pbPacket;
4009
4010 pbPacket = s->abATAPICmd;
4011# ifdef DEBUG
4012 Log(("%s: LUN#%d DMA=%d CMD=%#04x \"%s\"\n", __FUNCTION__, s->iLUN, s->fDMA, pbPacket[0], SCSICmdText(pbPacket[0])));
4013# else /* !DEBUG */
4014 Log(("%s: LUN#%d DMA=%d CMD=%#04x\n", __FUNCTION__, s->iLUN, s->fDMA, pbPacket[0]));
4015# endif /* !DEBUG */
4016 Log2(("%s: limit=%#x packet: %.*Rhxs\n", __FUNCTION__, s->uATARegLCyl | (s->uATARegHCyl << 8), ATAPI_PACKET_SIZE, pbPacket));
4017
4018 if (s->fATAPIPassthrough)
4019 atapiR3ParseCmdPassthrough(pDevIns, pCtl, s, pDevR3);
4020 else
4021 atapiR3ParseCmdVirtualATAPI(pDevIns, pCtl, s, pDevR3);
4022}
4023
4024
4025/**
4026 * Sink/Source: PACKET
4027 */
4028static bool ataR3PacketSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
4029{
4030 s->fDMA = !!(s->uATARegFeature & 1);
4031 memcpy(s->abATAPICmd, s->abIOBuffer, ATAPI_PACKET_SIZE);
4032 s->uTxDir = PDMMEDIATXDIR_NONE;
4033 s->cbTotalTransfer = 0;
4034 s->cbElementaryTransfer = 0;
4035 s->cbAtapiPassthroughTransfer = 0;
4036 atapiR3ParseCmd(pDevIns, pCtl, s, pDevR3);
4037 return false;
4038}
4039
4040
4041/**
4042 * SCSI_GET_EVENT_STATUS_NOTIFICATION should return "medium removed" event
4043 * from now on, regardless if there was a medium inserted or not.
4044 */
4045static void ataR3MediumRemoved(PATADEVSTATE s)
4046{
4047 ASMAtomicWriteU32(&s->MediaEventStatus, ATA_EVENT_STATUS_MEDIA_REMOVED);
4048}
4049
4050
4051/**
4052 * SCSI_GET_EVENT_STATUS_NOTIFICATION should return "medium inserted". If
4053 * there was already a medium inserted, don't forget to send the "medium
4054 * removed" event first.
4055 */
4056static void ataR3MediumInserted(PATADEVSTATE s)
4057{
4058 uint32_t OldStatus, NewStatus;
4059 do
4060 {
4061 OldStatus = ASMAtomicReadU32(&s->MediaEventStatus);
4062 switch (OldStatus)
4063 {
4064 case ATA_EVENT_STATUS_MEDIA_CHANGED:
4065 case ATA_EVENT_STATUS_MEDIA_REMOVED:
4066 /* no change, we will send "medium removed" + "medium inserted" */
4067 NewStatus = ATA_EVENT_STATUS_MEDIA_CHANGED;
4068 break;
4069 default:
4070 NewStatus = ATA_EVENT_STATUS_MEDIA_NEW;
4071 break;
4072 }
4073 } while (!ASMAtomicCmpXchgU32(&s->MediaEventStatus, NewStatus, OldStatus));
4074}
4075
4076
4077/**
4078 * @interface_method_impl{PDMIMOUNTNOTIFY,pfnMountNotify}
4079 */
4080static DECLCALLBACK(void) ataR3MountNotify(PPDMIMOUNTNOTIFY pInterface)
4081{
4082 PATADEVSTATER3 pIfR3 = RT_FROM_MEMBER(pInterface, ATADEVSTATER3, IMountNotify);
4083 PATASTATE pThis = PDMDEVINS_2_DATA(pIfR3->pDevIns, PATASTATE);
4084 PATADEVSTATE pIf = &RT_SAFE_SUBSCRIPT(RT_SAFE_SUBSCRIPT(pThis->aCts, pIfR3->iCtl).aIfs, pIfR3->iDev);
4085 Log(("%s: changing LUN#%d\n", __FUNCTION__, pIfR3->iLUN));
4086
4087 /* Ignore the call if we're called while being attached. */
4088 if (!pIfR3->pDrvMedia)
4089 return;
4090
4091 uint32_t cRegions = pIfR3->pDrvMedia->pfnGetRegionCount(pIfR3->pDrvMedia);
4092 for (uint32_t i = 0; i < cRegions; i++)
4093 {
4094 uint64_t cBlocks = 0;
4095 int rc = pIfR3->pDrvMedia->pfnQueryRegionProperties(pIfR3->pDrvMedia, i, NULL, &cBlocks, NULL, NULL);
4096 AssertRC(rc);
4097 pIf->cTotalSectors += cBlocks;
4098 }
4099
4100 LogRel(("PIIX3 ATA: LUN#%d: CD/DVD, total number of sectors %Ld, passthrough unchanged\n", pIf->iLUN, pIf->cTotalSectors));
4101
4102 /* Report media changed in TEST UNIT and other (probably incorrect) places. */
4103 if (pIf->cNotifiedMediaChange < 2)
4104 pIf->cNotifiedMediaChange = 1;
4105 ataR3MediumInserted(pIf);
4106 ataR3MediumTypeSet(pIf, ATA_MEDIA_TYPE_UNKNOWN);
4107}
4108
4109/**
4110 * @interface_method_impl{PDMIMOUNTNOTIFY,pfnUnmountNotify}
4111 */
4112static DECLCALLBACK(void) ataR3UnmountNotify(PPDMIMOUNTNOTIFY pInterface)
4113{
4114 PATADEVSTATER3 pIfR3 = RT_FROM_MEMBER(pInterface, ATADEVSTATER3, IMountNotify);
4115 PATASTATE pThis = PDMDEVINS_2_DATA(pIfR3->pDevIns, PATASTATE);
4116 PATADEVSTATE pIf = &RT_SAFE_SUBSCRIPT(RT_SAFE_SUBSCRIPT(pThis->aCts, pIfR3->iCtl).aIfs, pIfR3->iDev);
4117 Log(("%s:\n", __FUNCTION__));
4118 pIf->cTotalSectors = 0;
4119
4120 /*
4121 * Whatever I do, XP will not use the GET MEDIA STATUS nor the EVENT stuff.
4122 * However, it will respond to TEST UNIT with a 0x6 0x28 (media changed) sense code.
4123 * So, we'll give it 4 TEST UNIT command to catch up, two which the media is not
4124 * present and 2 in which it is changed.
4125 */
4126 pIf->cNotifiedMediaChange = 1;
4127 ataR3MediumRemoved(pIf);
4128 ataR3MediumTypeSet(pIf, ATA_MEDIA_NO_DISC);
4129}
4130
4131/**
4132 * Begin Transfer: PACKET
4133 */
4134static void ataR3PacketBT(PATACONTROLLER pCtl, PATADEVSTATE s)
4135{
4136 s->cbElementaryTransfer = s->cbTotalTransfer;
4137 s->cbAtapiPassthroughTransfer = s->cbTotalTransfer;
4138 s->uATARegNSector = (s->uATARegNSector & ~7) | ATAPI_INT_REASON_CD;
4139 Log2(("%s: interrupt reason %#04x\n", __FUNCTION__, s->uATARegNSector));
4140 ataSetStatusValue(pCtl, s, ATA_STAT_READY);
4141}
4142
4143
4144static void ataR3ResetDevice(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s)
4145{
4146 LogFlowFunc(("\n"));
4147 s->cMultSectors = ATA_MAX_MULT_SECTORS;
4148 s->cNotifiedMediaChange = 0;
4149 ASMAtomicWriteU32(&s->MediaEventStatus, ATA_EVENT_STATUS_UNCHANGED);
4150 ASMAtomicWriteU32(&s->MediaTrackType, ATA_MEDIA_TYPE_UNKNOWN);
4151 ataUnsetIRQ(pDevIns, pCtl, s);
4152
4153 s->uATARegSelect = 0x20;
4154 ataSetStatusValue(pCtl, s, ATA_STAT_READY | ATA_STAT_SEEK);
4155 ataR3SetSignature(s);
4156 s->cbTotalTransfer = 0;
4157 s->cbElementaryTransfer = 0;
4158 s->cbAtapiPassthroughTransfer = 0;
4159 s->iIOBufferPIODataStart = 0;
4160 s->iIOBufferPIODataEnd = 0;
4161 s->iBeginTransfer = ATAFN_BT_NULL;
4162 s->iSourceSink = ATAFN_SS_NULL;
4163 s->fDMA = false;
4164 s->fATAPITransfer = false;
4165 s->uATATransferMode = ATA_MODE_UDMA | 2; /* PIIX3 supports only up to UDMA2 */
4166
4167 s->XCHSGeometry = s->PCHSGeometry; /* Restore default CHS translation. */
4168
4169 s->uATARegFeature = 0;
4170}
4171
4172
4173static void ataR3DeviceDiag(PATACONTROLLER pCtl, PATADEVSTATE s)
4174{
4175 ataR3SetSignature(s);
4176 if (s->fATAPI)
4177 ataSetStatusValue(pCtl, s, 0); /* NOTE: READY is _not_ set */
4178 else
4179 ataSetStatusValue(pCtl, s, ATA_STAT_READY | ATA_STAT_SEEK);
4180 s->uATARegError = 0x01;
4181}
4182
4183
4184/**
4185 * Sink/Source: EXECUTE DEVICE DIAGNOTIC
4186 */
4187static bool ataR3ExecuteDeviceDiagnosticSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
4188{
4189 RT_NOREF(pDevIns, s, pDevR3);
4190
4191 /* EXECUTE DEVICE DIAGNOSTIC is a very special command which always
4192 * gets executed, regardless of which device is selected. As a side
4193 * effect, it always completes with device 0 selected.
4194 */
4195 for (uint32_t i = 0; i < RT_ELEMENTS(pCtl->aIfs); i++)
4196 ataR3DeviceDiag(pCtl, &pCtl->aIfs[i]);
4197
4198 LogRel(("ATA: LUN#%d: EXECUTE DEVICE DIAGNOSTIC, status %02X\n", s->iLUN, s->uATARegStatus));
4199 pCtl->iSelectedIf = 0;
4200
4201 return false;
4202}
4203
4204
4205/**
4206 * Sink/Source: INITIALIZE DEVICE PARAMETERS
4207 */
4208static bool ataR3InitDevParmSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
4209{
4210 RT_NOREF(pDevR3);
4211 LogFlowFunc(("\n"));
4212
4213 /* Technical Note:
4214 * On ST506 type drives with a separate controller, the INITIALIZE DRIVE PARAMETERS command was
4215 * required to inform the controller of drive geometry. The controller needed to know the
4216 * number of heads and sectors per track so that it could correctly advance to the next track
4217 * or cylinder when executing multi-sector commands. Setting a geometry that didn't match the
4218 * drive made very little sense because sectors had fixed CHS addresses. It was at best
4219 * possible to reduce the drive's capacity by limiting the number of heads and/or sectors
4220 * per track.
4221 *
4222 * IDE drives inherently have to know their true geometry, but most of them also support
4223 * programmable translation that can be set through the INITIALIZE DEVICE PARAMETERS command.
4224 * In fact most older IDE drives typically weren't operated using their default (native) geometry,
4225 * and with newer IDE drives that's not even an option.
4226 *
4227 * Up to and including ATA-5, the standard defined a CHS to LBA translation (since ATA-6, CHS
4228 * support is optional):
4229 *
4230 * LBA = (((cyl_num * heads_per_cyl) + head_num) * sectors_per_track) + sector_num - 1
4231 *
4232 * The INITIALIZE DEVICE PARAMETERS command sets the heads_per_cyl and sectors_per_track
4233 * values used in the above formula.
4234 *
4235 * Drives must obviously support an INITIALIZE DRIVE PARAMETERS command matching the drive's
4236 * default CHS translation. Everything else is optional.
4237 *
4238 * We support any geometry with non-zero sectors per track because there's no reason not to;
4239 * this behavior is common in many if not most IDE drives.
4240 */
4241
4242 PDMMEDIAGEOMETRY Geom = { 0 };
4243
4244 Geom.cHeads = (s->uATARegSelect & 0x0f) + 1; /* Effective range 1-16. */
4245 Geom.cSectors = s->uATARegNSector; /* Range 0-255, zero is not valid. */
4246
4247 if (Geom.cSectors)
4248 {
4249 uint64_t cCylinders = s->cTotalSectors / (Geom.cHeads * Geom.cSectors);
4250 Geom.cCylinders = RT_MAX(RT_MIN(cCylinders, 16383), 1);
4251
4252 s->XCHSGeometry = Geom;
4253
4254 ataR3LockLeave(pDevIns, pCtl);
4255 LogRel(("ATA: LUN#%d: INITIALIZE DEVICE PARAMETERS: %u sectors per track, %u heads\n",
4256 s->iLUN, s->uATARegNSector, (s->uATARegSelect & 0x0f) + 1));
4257 RTThreadSleep(pCtl->msDelayIRQ);
4258 ataR3LockEnter(pDevIns, pCtl);
4259 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
4260 }
4261 else
4262 {
4263 ataR3LockLeave(pDevIns, pCtl);
4264 LogRel(("ATA: LUN#%d: INITIALIZE DEVICE PARAMETERS error (zero sectors per track)!\n", s->iLUN));
4265 RTThreadSleep(pCtl->msDelayIRQ);
4266 ataR3LockEnter(pDevIns, pCtl);
4267 ataR3CmdError(pCtl, s, ABRT_ERR);
4268 }
4269 return false;
4270}
4271
4272
4273/**
4274 * Sink/Source: RECALIBRATE
4275 */
4276static bool ataR3RecalibrateSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
4277{
4278 RT_NOREF(pDevR3);
4279 LogFlowFunc(("\n"));
4280 ataR3LockLeave(pDevIns, pCtl);
4281 RTThreadSleep(pCtl->msDelayIRQ);
4282 ataR3LockEnter(pDevIns, pCtl);
4283 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
4284 return false;
4285}
4286
4287
4288static int ataR3TrimSectors(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3,
4289 uint64_t u64Sector, uint32_t cSectors, bool *pfRedo)
4290{
4291 RTRANGE TrimRange;
4292 int rc;
4293
4294 ataR3LockLeave(pDevIns, pCtl);
4295
4296 TrimRange.offStart = u64Sector * s->cbSector;
4297 TrimRange.cbRange = cSectors * s->cbSector;
4298
4299 s->Led.Asserted.s.fWriting = s->Led.Actual.s.fWriting = 1;
4300 rc = pDevR3->pDrvMedia->pfnDiscard(pDevR3->pDrvMedia, &TrimRange, 1);
4301 s->Led.Actual.s.fWriting = 0;
4302
4303 if (RT_SUCCESS(rc))
4304 *pfRedo = false;
4305 else
4306 *pfRedo = ataR3IsRedoSetWarning(pDevIns, pCtl, rc);
4307
4308 ataR3LockEnter(pDevIns, pCtl);
4309 return rc;
4310}
4311
4312
4313/**
4314 * Sink/Source: TRIM
4315 */
4316static bool ataR3TrimSS(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3)
4317{
4318 int rc = VERR_GENERAL_FAILURE;
4319 uint32_t cRangesMax;
4320 uint64_t *pu64Range = (uint64_t *)&s->abIOBuffer[0];
4321 bool fRedo = false;
4322
4323 cRangesMax = RT_MIN(s->cbElementaryTransfer, sizeof(s->abIOBuffer)) / sizeof(uint64_t);
4324 Assert(cRangesMax);
4325
4326 while (cRangesMax-- > 0)
4327 {
4328 if (ATA_RANGE_LENGTH_GET(*pu64Range) == 0)
4329 break;
4330
4331 rc = ataR3TrimSectors(pDevIns, pCtl, s, pDevR3, *pu64Range & ATA_RANGE_LBA_MASK,
4332 ATA_RANGE_LENGTH_GET(*pu64Range), &fRedo);
4333 if (RT_FAILURE(rc))
4334 break;
4335
4336 pu64Range++;
4337 }
4338
4339 if (RT_SUCCESS(rc))
4340 {
4341 s->iSourceSink = ATAFN_SS_NULL;
4342 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
4343 }
4344 else
4345 {
4346 if (fRedo)
4347 return fRedo;
4348 if (s->cErrors++ < MAX_LOG_REL_ERRORS)
4349 LogRel(("PIIX3 ATA: LUN#%d: disk trim error (rc=%Rrc iSector=%#RX64 cSectors=%#RX32)\n",
4350 s->iLUN, rc, *pu64Range & ATA_RANGE_LBA_MASK, ATA_RANGE_LENGTH_GET(*pu64Range)));
4351
4352 /*
4353 * Check if we got interrupted. We don't need to set status variables
4354 * because the request was aborted.
4355 */
4356 if (rc != VERR_INTERRUPTED)
4357 ataR3CmdError(pCtl, s, ID_ERR);
4358 }
4359
4360 return false;
4361}
4362
4363
4364static void ataR3ParseCmd(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, PATADEVSTATE s, PATADEVSTATER3 pDevR3, uint8_t cmd)
4365{
4366# ifdef DEBUG
4367 Log(("%s: LUN#%d CMD=%#04x \"%s\"\n", __FUNCTION__, s->iLUN, cmd, ATACmdText(cmd)));
4368# else /* !DEBUG */
4369 Log(("%s: LUN#%d CMD=%#04x\n", __FUNCTION__, s->iLUN, cmd));
4370# endif /* !DEBUG */
4371 s->fLBA48 = false;
4372 s->fDMA = false;
4373 if (cmd == ATA_IDLE_IMMEDIATE)
4374 {
4375 /* Detect Linux timeout recovery, first tries IDLE IMMEDIATE (which
4376 * would overwrite the failing command unfortunately), then RESET. */
4377 int32_t uCmdWait = -1;
4378 uint64_t uNow = RTTimeNanoTS();
4379 if (s->u64CmdTS)
4380 uCmdWait = (uNow - s->u64CmdTS) / 1000;
4381 LogRel(("PIIX3 ATA: LUN#%d: IDLE IMMEDIATE, CmdIf=%#04x (%d usec ago)\n",
4382 s->iLUN, s->uATARegCommand, uCmdWait));
4383 }
4384 s->uATARegCommand = cmd;
4385 switch (cmd)
4386 {
4387 case ATA_IDENTIFY_DEVICE:
4388 if (pDevR3->pDrvMedia && !s->fATAPI)
4389 ataR3StartTransfer(pDevIns, pCtl, s, 512, PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_NULL, ATAFN_SS_IDENTIFY, false);
4390 else
4391 {
4392 if (s->fATAPI)
4393 ataR3SetSignature(s);
4394 ataR3CmdError(pCtl, s, ABRT_ERR);
4395 ataUnsetStatus(pCtl, s, ATA_STAT_READY);
4396 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4397 }
4398 break;
4399 case ATA_RECALIBRATE:
4400 if (s->fATAPI)
4401 goto abort_cmd;
4402 ataR3StartTransfer(pDevIns, pCtl, s, 0, PDMMEDIATXDIR_NONE, ATAFN_BT_NULL, ATAFN_SS_RECALIBRATE, false);
4403 break;
4404 case ATA_INITIALIZE_DEVICE_PARAMETERS:
4405 if (s->fATAPI)
4406 goto abort_cmd;
4407 ataR3StartTransfer(pDevIns, pCtl, s, 0, PDMMEDIATXDIR_NONE, ATAFN_BT_NULL, ATAFN_SS_INITIALIZE_DEVICE_PARAMETERS, false);
4408 break;
4409 case ATA_SET_MULTIPLE_MODE:
4410 if ( s->uATARegNSector != 0
4411 && ( s->uATARegNSector > ATA_MAX_MULT_SECTORS
4412 || (s->uATARegNSector & (s->uATARegNSector - 1)) != 0))
4413 {
4414 ataR3CmdError(pCtl, s, ABRT_ERR);
4415 }
4416 else
4417 {
4418 Log2(("%s: set multi sector count to %d\n", __FUNCTION__, s->uATARegNSector));
4419 s->cMultSectors = s->uATARegNSector;
4420 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
4421 }
4422 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4423 break;
4424 case ATA_READ_VERIFY_SECTORS_EXT:
4425 s->fLBA48 = true;
4426 RT_FALL_THRU();
4427 case ATA_READ_VERIFY_SECTORS:
4428 case ATA_READ_VERIFY_SECTORS_WITHOUT_RETRIES:
4429 /* do sector number check ? */
4430 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
4431 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4432 break;
4433 case ATA_READ_SECTORS_EXT:
4434 s->fLBA48 = true;
4435 RT_FALL_THRU();
4436 case ATA_READ_SECTORS:
4437 case ATA_READ_SECTORS_WITHOUT_RETRIES:
4438 if (!pDevR3->pDrvMedia || s->fATAPI)
4439 goto abort_cmd;
4440 s->cSectorsPerIRQ = 1;
4441 s->iCurLBA = ataR3GetSector(s);
4442 ataR3StartTransfer(pDevIns, pCtl, s, ataR3GetNSectors(s) * s->cbSector, PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_READ_WRITE_SECTORS, ATAFN_SS_READ_SECTORS, false);
4443 break;
4444 case ATA_WRITE_SECTORS_EXT:
4445 s->fLBA48 = true;
4446 RT_FALL_THRU();
4447 case ATA_WRITE_SECTORS:
4448 case ATA_WRITE_SECTORS_WITHOUT_RETRIES:
4449 if (!pDevR3->pDrvMedia || s->fATAPI)
4450 goto abort_cmd;
4451 s->cSectorsPerIRQ = 1;
4452 s->iCurLBA = ataR3GetSector(s);
4453 ataR3StartTransfer(pDevIns, pCtl, s, ataR3GetNSectors(s) * s->cbSector, PDMMEDIATXDIR_TO_DEVICE, ATAFN_BT_READ_WRITE_SECTORS, ATAFN_SS_WRITE_SECTORS, false);
4454 break;
4455 case ATA_READ_MULTIPLE_EXT:
4456 s->fLBA48 = true;
4457 RT_FALL_THRU();
4458 case ATA_READ_MULTIPLE:
4459 if (!pDevR3->pDrvMedia || !s->cMultSectors || s->fATAPI)
4460 goto abort_cmd;
4461 s->cSectorsPerIRQ = s->cMultSectors;
4462 s->iCurLBA = ataR3GetSector(s);
4463 ataR3StartTransfer(pDevIns, pCtl, s, ataR3GetNSectors(s) * s->cbSector, PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_READ_WRITE_SECTORS, ATAFN_SS_READ_SECTORS, false);
4464 break;
4465 case ATA_WRITE_MULTIPLE_EXT:
4466 s->fLBA48 = true;
4467 RT_FALL_THRU();
4468 case ATA_WRITE_MULTIPLE:
4469 if (!pDevR3->pDrvMedia || !s->cMultSectors || s->fATAPI)
4470 goto abort_cmd;
4471 s->cSectorsPerIRQ = s->cMultSectors;
4472 s->iCurLBA = ataR3GetSector(s);
4473 ataR3StartTransfer(pDevIns, pCtl, s, ataR3GetNSectors(s) * s->cbSector, PDMMEDIATXDIR_TO_DEVICE, ATAFN_BT_READ_WRITE_SECTORS, ATAFN_SS_WRITE_SECTORS, false);
4474 break;
4475 case ATA_READ_DMA_EXT:
4476 s->fLBA48 = true;
4477 RT_FALL_THRU();
4478 case ATA_READ_DMA:
4479 case ATA_READ_DMA_WITHOUT_RETRIES:
4480 if (!pDevR3->pDrvMedia || s->fATAPI)
4481 goto abort_cmd;
4482 s->cSectorsPerIRQ = ATA_MAX_MULT_SECTORS;
4483 s->iCurLBA = ataR3GetSector(s);
4484 s->fDMA = true;
4485 ataR3StartTransfer(pDevIns, pCtl, s, ataR3GetNSectors(s) * s->cbSector, PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_READ_WRITE_SECTORS, ATAFN_SS_READ_SECTORS, false);
4486 break;
4487 case ATA_WRITE_DMA_EXT:
4488 s->fLBA48 = true;
4489 RT_FALL_THRU();
4490 case ATA_WRITE_DMA:
4491 case ATA_WRITE_DMA_WITHOUT_RETRIES:
4492 if (!pDevR3->pDrvMedia || s->fATAPI)
4493 goto abort_cmd;
4494 s->cSectorsPerIRQ = ATA_MAX_MULT_SECTORS;
4495 s->iCurLBA = ataR3GetSector(s);
4496 s->fDMA = true;
4497 ataR3StartTransfer(pDevIns, pCtl, s, ataR3GetNSectors(s) * s->cbSector, PDMMEDIATXDIR_TO_DEVICE, ATAFN_BT_READ_WRITE_SECTORS, ATAFN_SS_WRITE_SECTORS, false);
4498 break;
4499 case ATA_READ_NATIVE_MAX_ADDRESS_EXT:
4500 if (!pDevR3->pDrvMedia || s->fATAPI)
4501 goto abort_cmd;
4502 s->fLBA48 = true;
4503 ataR3SetSector(s, s->cTotalSectors - 1);
4504 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
4505 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4506 break;
4507 case ATA_SEEK: /* Used by the SCO OpenServer. Command is marked as obsolete */
4508 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
4509 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4510 break;
4511 case ATA_READ_NATIVE_MAX_ADDRESS:
4512 if (!pDevR3->pDrvMedia || s->fATAPI)
4513 goto abort_cmd;
4514 ataR3SetSector(s, RT_MIN(s->cTotalSectors, 1 << 28) - 1);
4515 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
4516 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4517 break;
4518 case ATA_CHECK_POWER_MODE:
4519 s->uATARegNSector = 0xff; /* drive active or idle */
4520 ataR3CmdOK(pCtl, s, 0);
4521 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4522 break;
4523 case ATA_SET_FEATURES:
4524 Log2(("%s: feature=%#x\n", __FUNCTION__, s->uATARegFeature));
4525 if (!pDevR3->pDrvMedia)
4526 goto abort_cmd;
4527 switch (s->uATARegFeature)
4528 {
4529 case 0x02: /* write cache enable */
4530 Log2(("%s: write cache enable\n", __FUNCTION__));
4531 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
4532 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4533 break;
4534 case 0xaa: /* read look-ahead enable */
4535 Log2(("%s: read look-ahead enable\n", __FUNCTION__));
4536 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
4537 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4538 break;
4539 case 0x55: /* read look-ahead disable */
4540 Log2(("%s: read look-ahead disable\n", __FUNCTION__));
4541 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
4542 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4543 break;
4544 case 0xcc: /* reverting to power-on defaults enable */
4545 Log2(("%s: revert to power-on defaults enable\n", __FUNCTION__));
4546 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
4547 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4548 break;
4549 case 0x66: /* reverting to power-on defaults disable */
4550 Log2(("%s: revert to power-on defaults disable\n", __FUNCTION__));
4551 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
4552 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4553 break;
4554 case 0x82: /* write cache disable */
4555 Log2(("%s: write cache disable\n", __FUNCTION__));
4556 /* As per the ATA/ATAPI-6 specs, a write cache disable
4557 * command MUST flush the write buffers to disc. */
4558 ataR3StartTransfer(pDevIns, pCtl, s, 0, PDMMEDIATXDIR_NONE, ATAFN_BT_NULL, ATAFN_SS_FLUSH, false);
4559 break;
4560 case 0x03: { /* set transfer mode */
4561 Log2(("%s: transfer mode %#04x\n", __FUNCTION__, s->uATARegNSector));
4562 switch (s->uATARegNSector & 0xf8)
4563 {
4564 case 0x00: /* PIO default */
4565 case 0x08: /* PIO mode */
4566 break;
4567 case ATA_MODE_MDMA: /* MDMA mode */
4568 s->uATATransferMode = (s->uATARegNSector & 0xf8) | RT_MIN(s->uATARegNSector & 0x07, ATA_MDMA_MODE_MAX);
4569 break;
4570 case ATA_MODE_UDMA: /* UDMA mode */
4571 s->uATATransferMode = (s->uATARegNSector & 0xf8) | RT_MIN(s->uATARegNSector & 0x07, ATA_UDMA_MODE_MAX);
4572 break;
4573 default:
4574 goto abort_cmd;
4575 }
4576 ataR3CmdOK(pCtl, s, ATA_STAT_SEEK);
4577 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4578 break;
4579 }
4580 default:
4581 goto abort_cmd;
4582 }
4583 /*
4584 * OS/2 workarond:
4585 * The OS/2 IDE driver from MCP2 appears to rely on the feature register being
4586 * reset here. According to the specification, this is a driver bug as the register
4587 * contents are undefined after the call. This means we can just as well reset it.
4588 */
4589 s->uATARegFeature = 0;
4590 break;
4591 case ATA_FLUSH_CACHE_EXT:
4592 case ATA_FLUSH_CACHE:
4593 if (!pDevR3->pDrvMedia || s->fATAPI)
4594 goto abort_cmd;
4595 ataR3StartTransfer(pDevIns, pCtl, s, 0, PDMMEDIATXDIR_NONE, ATAFN_BT_NULL, ATAFN_SS_FLUSH, false);
4596 break;
4597 case ATA_STANDBY_IMMEDIATE:
4598 ataR3CmdOK(pCtl, s, 0);
4599 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4600 break;
4601 case ATA_IDLE_IMMEDIATE:
4602 LogRel(("PIIX3 ATA: LUN#%d: aborting current command\n", s->iLUN));
4603 ataR3AbortCurrentCommand(pDevIns, pCtl, s, false);
4604 break;
4605 case ATA_SLEEP:
4606 ataR3CmdOK(pCtl, s, 0);
4607 ataHCSetIRQ(pDevIns, pCtl, s);
4608 break;
4609 /* ATAPI commands */
4610 case ATA_IDENTIFY_PACKET_DEVICE:
4611 if (s->fATAPI)
4612 ataR3StartTransfer(pDevIns, pCtl, s, 512, PDMMEDIATXDIR_FROM_DEVICE, ATAFN_BT_NULL, ATAFN_SS_ATAPI_IDENTIFY, false);
4613 else
4614 {
4615 ataR3CmdError(pCtl, s, ABRT_ERR);
4616 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4617 }
4618 break;
4619 case ATA_EXECUTE_DEVICE_DIAGNOSTIC:
4620 ataR3StartTransfer(pDevIns, pCtl, s, 0, PDMMEDIATXDIR_NONE, ATAFN_BT_NULL, ATAFN_SS_EXECUTE_DEVICE_DIAGNOSTIC, false);
4621 break;
4622 case ATA_DEVICE_RESET:
4623 if (!s->fATAPI)
4624 goto abort_cmd;
4625 LogRel(("PIIX3 ATA: LUN#%d: performing device RESET\n", s->iLUN));
4626 ataR3AbortCurrentCommand(pDevIns, pCtl, s, true);
4627 break;
4628 case ATA_PACKET:
4629 if (!s->fATAPI)
4630 goto abort_cmd;
4631 /* overlapping commands not supported */
4632 if (s->uATARegFeature & 0x02)
4633 goto abort_cmd;
4634 ataR3StartTransfer(pDevIns, pCtl, s, ATAPI_PACKET_SIZE, PDMMEDIATXDIR_TO_DEVICE, ATAFN_BT_PACKET, ATAFN_SS_PACKET, false);
4635 break;
4636 case ATA_DATA_SET_MANAGEMENT:
4637 if (!pDevR3->pDrvMedia || !pDevR3->pDrvMedia->pfnDiscard)
4638 goto abort_cmd;
4639 if ( !(s->uATARegFeature & UINT8_C(0x01))
4640 || (s->uATARegFeature & ~UINT8_C(0x01)))
4641 goto abort_cmd;
4642 s->fDMA = true;
4643 ataR3StartTransfer(pDevIns, pCtl, s, (s->uATARegNSectorHOB << 8 | s->uATARegNSector) * s->cbSector, PDMMEDIATXDIR_TO_DEVICE, ATAFN_BT_NULL, ATAFN_SS_TRIM, false);
4644 break;
4645 default:
4646 abort_cmd:
4647 ataR3CmdError(pCtl, s, ABRT_ERR);
4648 if (s->fATAPI)
4649 ataUnsetStatus(pCtl, s, ATA_STAT_READY);
4650 ataHCSetIRQ(pDevIns, pCtl, s); /* Shortcut, do not use AIO thread. */
4651 break;
4652 }
4653}
4654
4655# endif /* IN_RING3 */
4656#endif /* IN_RING0 || IN_RING3 */
4657
4658/*
4659 * Note: There are four distinct cases of port I/O handling depending on
4660 * which devices (if any) are attached to an IDE channel:
4661 *
4662 * 1) No device attached. No response to writes or reads (i.e. reads return
4663 * all bits set).
4664 *
4665 * 2) Both devices attached. Reads and writes are processed normally.
4666 *
4667 * 3) Device 0 only. If device 0 is selected, normal behavior applies. But
4668 * if Device 1 is selected, writes are still directed to Device 0 (except
4669 * commands are not executed), reads from control/command registers are
4670 * directed to Device 0, but status/alt status reads return 0. If Device 1
4671 * is a PACKET device, all reads return 0. See ATAPI-6 clause 9.16.1 and
4672 * Table 18 in clause 7.1.
4673 *
4674 * 4) Device 1 only - non-standard(!). Device 1 can't tell if Device 0 is
4675 * present or not and behaves the same. That means if Device 0 is selected,
4676 * Device 1 responds to writes (except commands are not executed) but does
4677 * not respond to reads. If Device 1 selected, normal behavior applies.
4678 * See ATAPI-6 clause 9.16.2 and Table 15 in clause 7.1.
4679 */
4680
4681static VBOXSTRICTRC ataIOPortWriteU8(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, uint32_t addr, uint32_t val, uintptr_t iCtl)
4682{
4683 RT_NOREF(iCtl);
4684 Log2(("%s: LUN#%d write addr=%#x val=%#04x\n", __FUNCTION__, pCtl->aIfs[pCtl->iSelectedIf & ATA_SELECTED_IF_MASK].iLUN, addr, val));
4685 addr &= 7;
4686 switch (addr)
4687 {
4688 case 0:
4689 break;
4690 case 1: /* feature register */
4691 /* NOTE: data is written to the two drives */
4692 pCtl->aIfs[0].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4693 pCtl->aIfs[1].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4694 pCtl->aIfs[0].uATARegFeatureHOB = pCtl->aIfs[0].uATARegFeature;
4695 pCtl->aIfs[1].uATARegFeatureHOB = pCtl->aIfs[1].uATARegFeature;
4696 pCtl->aIfs[0].uATARegFeature = val;
4697 pCtl->aIfs[1].uATARegFeature = val;
4698 break;
4699 case 2: /* sector count */
4700 pCtl->aIfs[0].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4701 pCtl->aIfs[1].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4702 pCtl->aIfs[0].uATARegNSectorHOB = pCtl->aIfs[0].uATARegNSector;
4703 pCtl->aIfs[1].uATARegNSectorHOB = pCtl->aIfs[1].uATARegNSector;
4704 pCtl->aIfs[0].uATARegNSector = val;
4705 pCtl->aIfs[1].uATARegNSector = val;
4706 break;
4707 case 3: /* sector number */
4708 pCtl->aIfs[0].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4709 pCtl->aIfs[1].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4710 pCtl->aIfs[0].uATARegSectorHOB = pCtl->aIfs[0].uATARegSector;
4711 pCtl->aIfs[1].uATARegSectorHOB = pCtl->aIfs[1].uATARegSector;
4712 pCtl->aIfs[0].uATARegSector = val;
4713 pCtl->aIfs[1].uATARegSector = val;
4714 break;
4715 case 4: /* cylinder low */
4716 pCtl->aIfs[0].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4717 pCtl->aIfs[1].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4718 pCtl->aIfs[0].uATARegLCylHOB = pCtl->aIfs[0].uATARegLCyl;
4719 pCtl->aIfs[1].uATARegLCylHOB = pCtl->aIfs[1].uATARegLCyl;
4720 pCtl->aIfs[0].uATARegLCyl = val;
4721 pCtl->aIfs[1].uATARegLCyl = val;
4722 break;
4723 case 5: /* cylinder high */
4724 pCtl->aIfs[0].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4725 pCtl->aIfs[1].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4726 pCtl->aIfs[0].uATARegHCylHOB = pCtl->aIfs[0].uATARegHCyl;
4727 pCtl->aIfs[1].uATARegHCylHOB = pCtl->aIfs[1].uATARegHCyl;
4728 pCtl->aIfs[0].uATARegHCyl = val;
4729 pCtl->aIfs[1].uATARegHCyl = val;
4730 break;
4731 case 6: /* drive/head */
4732 pCtl->aIfs[0].uATARegSelect = val & ~0x10;
4733 pCtl->aIfs[1].uATARegSelect = val | 0x10;
4734 if (((val >> 4) & ATA_SELECTED_IF_MASK) != pCtl->iSelectedIf)
4735 {
4736 /* select another drive */
4737 uintptr_t const iSelectedIf = (val >> 4) & ATA_SELECTED_IF_MASK;
4738 pCtl->iSelectedIf = (uint8_t)iSelectedIf;
4739 /* The IRQ line is multiplexed between the two drives, so
4740 * update the state when switching to another drive. Only need
4741 * to update interrupt line if it is enabled and there is a
4742 * state change. */
4743 if ( !(pCtl->aIfs[iSelectedIf].uATARegDevCtl & ATA_DEVCTL_DISABLE_IRQ)
4744 && pCtl->aIfs[iSelectedIf].fIrqPending != pCtl->aIfs[iSelectedIf ^ 1].fIrqPending)
4745 {
4746 if (pCtl->aIfs[iSelectedIf].fIrqPending)
4747 {
4748 Log2(("%s: LUN#%d asserting IRQ (drive select change)\n", __FUNCTION__, pCtl->aIfs[iSelectedIf].iLUN));
4749 /* The BMDMA unit unconditionally sets BM_STATUS_INT if
4750 * the interrupt line is asserted. It monitors the line
4751 * for a rising edge. */
4752 pCtl->BmDma.u8Status |= BM_STATUS_INT;
4753 if (pCtl->irq == 16)
4754 PDMDevHlpPCISetIrq(pDevIns, 0, 1);
4755 else
4756 PDMDevHlpISASetIrq(pDevIns, pCtl->irq, 1);
4757 }
4758 else
4759 {
4760 Log2(("%s: LUN#%d deasserting IRQ (drive select change)\n", __FUNCTION__, pCtl->aIfs[iSelectedIf].iLUN));
4761 if (pCtl->irq == 16)
4762 PDMDevHlpPCISetIrq(pDevIns, 0, 0);
4763 else
4764 PDMDevHlpISASetIrq(pDevIns, pCtl->irq, 0);
4765 }
4766 }
4767 }
4768 break;
4769 default:
4770 case 7: /* command */
4771 {
4772 /* ignore commands to non-existent device */
4773 uintptr_t iSelectedIf = pCtl->iSelectedIf & ATA_SELECTED_IF_MASK;
4774 PATADEVSTATE pDev = &pCtl->aIfs[iSelectedIf];
4775 if (iSelectedIf && !pDev->fPresent) /** @todo r=bird the iSelectedIf test here looks bogus... explain. */
4776 break;
4777#ifndef IN_RING3
4778 /* Don't do anything complicated in GC */
4779 return VINF_IOM_R3_IOPORT_WRITE;
4780#else /* IN_RING3 */
4781 PATASTATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PATASTATER3);
4782 ataUnsetIRQ(pDevIns, pCtl, &pCtl->aIfs[iSelectedIf]);
4783 ataR3ParseCmd(pDevIns, pCtl, &pCtl->aIfs[iSelectedIf], &pThisCC->aCts[iCtl].aIfs[iSelectedIf], val);
4784 break;
4785#endif /* !IN_RING3 */
4786 }
4787 }
4788 return VINF_SUCCESS;
4789}
4790
4791
4792static VBOXSTRICTRC ataIOPortReadU8(PPDMDEVINS pDevIns, PATACONTROLLER pCtl, uint32_t addr, uint32_t *pu32)
4793{
4794 PATADEVSTATE s = &pCtl->aIfs[pCtl->iSelectedIf & ATA_SELECTED_IF_MASK];
4795 uint32_t val;
4796 bool fHOB;
4797
4798 /* Check if the guest is reading from a non-existent device. */
4799 if (RT_LIKELY(s->fPresent))
4800 { /* likely */ }
4801 else
4802 {
4803 if (pCtl->iSelectedIf) /* Device 1 selected, Device 0 responding for it. */
4804 {
4805 Assert(pCtl->aIfs[0].fPresent);
4806
4807 /* When an ATAPI device 0 responds for non-present device 1, it generally
4808 * returns zeros on reads. The Error register is an exception. See clause 7.1,
4809 * table 16 in ATA-6 specification.
4810 */
4811 if (((addr & 7) != 1) && pCtl->aIfs[0].fATAPI)
4812 {
4813 Log2(("%s: addr=%#x, val=0: LUN#%d not attached/LUN#%d ATAPI\n", __FUNCTION__, addr, s->iLUN, pCtl->aIfs[0].iLUN));
4814 *pu32 = 0;
4815 return VINF_SUCCESS;
4816 }
4817 /* Else handle normally. */
4818 }
4819 else /* Device 0 selected (but not present). */
4820 {
4821 /* Because device 1 has no way to tell if there is device 0, the behavior is the same
4822 * as for an empty bus; see comments in ataIOPortReadEmptyBus(). Note that EFI (TianoCore)
4823 * relies on this behavior when detecting devices.
4824 */
4825 *pu32 = ATA_EMPTY_BUS_DATA;
4826 Log2(("%s: addr=%#x: LUN#%d not attached, val=%#02x\n", __FUNCTION__, addr, s->iLUN, *pu32));
4827 return VINF_SUCCESS;
4828 }
4829 }
4830
4831 fHOB = !!(s->uATARegDevCtl & (1 << 7));
4832 switch (addr & 7)
4833 {
4834 case 0: /* data register */
4835 val = 0xff;
4836 break;
4837 case 1: /* error register */
4838 /* The ATA specification is very terse when it comes to specifying
4839 * the precise effects of reading back the error/feature register.
4840 * The error register (read-only) shares the register number with
4841 * the feature register (write-only), so it seems that it's not
4842 * necessary to support the usual HOB readback here. */
4843 if (!s->fPresent)
4844 val = 0;
4845 else
4846 val = s->uATARegError;
4847 break;
4848 case 2: /* sector count */
4849 if (fHOB)
4850 val = s->uATARegNSectorHOB;
4851 else
4852 val = s->uATARegNSector;
4853 break;
4854 case 3: /* sector number */
4855 if (fHOB)
4856 val = s->uATARegSectorHOB;
4857 else
4858 val = s->uATARegSector;
4859 break;
4860 case 4: /* cylinder low */
4861 if (fHOB)
4862 val = s->uATARegLCylHOB;
4863 else
4864 val = s->uATARegLCyl;
4865 break;
4866 case 5: /* cylinder high */
4867 if (fHOB)
4868 val = s->uATARegHCylHOB;
4869 else
4870 val = s->uATARegHCyl;
4871 break;
4872 case 6: /* drive/head */
4873 /* This register must always work as long as there is at least
4874 * one drive attached to the controller. It is common between
4875 * both drives anyway (completely identical content). */
4876 if (!pCtl->aIfs[0].fPresent && !pCtl->aIfs[1].fPresent)
4877 val = 0;
4878 else
4879 val = s->uATARegSelect;
4880 break;
4881 default:
4882 case 7: /* primary status */
4883 {
4884 if (!s->fPresent)
4885 val = 0;
4886 else
4887 val = s->uATARegStatus;
4888
4889 /* Give the async I/O thread an opportunity to make progress,
4890 * don't let it starve by guests polling frequently. EMT has a
4891 * lower priority than the async I/O thread, but sometimes the
4892 * host OS doesn't care. With some guests we are only allowed to
4893 * be busy for about 5 milliseconds in some situations. Note that
4894 * this is no guarantee for any other VBox thread getting
4895 * scheduled, so this just lowers the CPU load a bit when drives
4896 * are busy. It cannot help with timing problems. */
4897 if (val & ATA_STAT_BUSY)
4898 {
4899#ifdef IN_RING3
4900 /* @bugref{1960}: Don't yield all the time, unless it's a reset (can be tricky). */
4901 bool fYield = (s->cBusyStatusHackR3++ & s->cBusyStatusHackR3Rate) == 0
4902 || pCtl->fReset;
4903
4904 ataR3LockLeave(pDevIns, pCtl);
4905
4906 /*
4907 * The thread might be stuck in an I/O operation due to a high I/O
4908 * load on the host (see @bugref{3301}). To perform the reset
4909 * successfully we interrupt the operation by sending a signal to
4910 * the thread if the thread didn't responded in 10ms.
4911 *
4912 * This works only on POSIX hosts (Windows has a CancelSynchronousIo
4913 * function which does the same but it was introduced with Vista) but
4914 * so far this hang was only observed on Linux and Mac OS X.
4915 *
4916 * This is a workaround and needs to be solved properly.
4917 */
4918 if (pCtl->fReset)
4919 {
4920 uint64_t u64ResetTimeStop = RTTimeMilliTS();
4921 if (u64ResetTimeStop - pCtl->u64ResetTime >= 10)
4922 {
4923 LogRel(("PIIX3 ATA LUN#%d: Async I/O thread probably stuck in operation, interrupting\n", s->iLUN));
4924 pCtl->u64ResetTime = u64ResetTimeStop;
4925# ifndef RT_OS_WINDOWS /* We've got this API on windows, but it doesn't necessarily interrupt I/O. */
4926 PATASTATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PATASTATER3);
4927 PATACONTROLLERR3 pCtlR3 = &RT_SAFE_SUBSCRIPT(pThisCC->aCts, pCtl->iCtl);
4928 RTThreadPoke(pCtlR3->hAsyncIOThread);
4929# endif
4930 Assert(fYield);
4931 }
4932 }
4933
4934 if (fYield)
4935 {
4936 STAM_REL_PROFILE_ADV_START(&s->StatStatusYields, a);
4937 RTThreadYield();
4938 STAM_REL_PROFILE_ADV_STOP(&s->StatStatusYields, a);
4939 }
4940 ASMNopPause();
4941
4942 ataR3LockEnter(pDevIns, pCtl);
4943
4944 val = s->uATARegStatus;
4945#else /* !IN_RING3 */
4946 /* Cannot yield CPU in raw-mode and ring-0 context. And switching
4947 * to host context for each and every busy status is too costly,
4948 * especially on SMP systems where we don't gain much by
4949 * yielding the CPU to someone else. */
4950 if ((s->cBusyStatusHackRZ++ & s->cBusyStatusHackRZRate) == 1)
4951 {
4952 s->cBusyStatusHackR3 = 0; /* Forces a yield. */
4953 return VINF_IOM_R3_IOPORT_READ;
4954 }
4955#endif /* !IN_RING3 */
4956 }
4957 else
4958 {
4959 s->cBusyStatusHackRZ = 0;
4960 s->cBusyStatusHackR3 = 0;
4961 }
4962 ataUnsetIRQ(pDevIns, pCtl, s);
4963 break;
4964 }
4965 }
4966 Log2(("%s: LUN#%d addr=%#x val=%#04x\n", __FUNCTION__, s->iLUN, addr, val));
4967 *pu32 = val;
4968 return VINF_SUCCESS;
4969}
4970
4971
4972/*
4973 * Read the Alternate status register. Does not affect interrupts.
4974 */
4975static uint32_t ataStatusRead(PATACONTROLLER pCtl, uint32_t uIoPortForLog)
4976{
4977 PATADEVSTATE s = &pCtl->aIfs[pCtl->iSelectedIf & ATA_SELECTED_IF_MASK];
4978 uint32_t val;
4979 RT_NOREF(uIoPortForLog);
4980
4981 Assert(pCtl->aIfs[0].fPresent || pCtl->aIfs[1].fPresent); /* Channel must not be empty. */
4982 if (pCtl->iSelectedIf == 1 && !s->fPresent)
4983 val = 0; /* Device 1 selected, Device 0 responding for it. */
4984 else
4985 val = s->uATARegStatus;
4986 Log2(("%s: LUN#%d read addr=%#x val=%#04x\n", __FUNCTION__,