VirtualBox

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

Last change on this file since 56622 was 56579, checked in by vboxsync, 9 years ago

Storage/ATA: fixed returned device strings from INQUIRY command (were byte swapped) caused by r101000

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 298.7 KB
Line 
1/* $Id: DevATA.cpp 56579 2015-06-22 16:08:08Z vboxsync $ */
2/** @file
3 * VBox storage devices: ATA/ATAPI controller device (disk and cdrom).
4 */
5
6/*
7 * Copyright (C) 2006-2015 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*******************************************************************************
20* Defined Constants And Macros *
21*******************************************************************************/
22/** Temporary instrumentation for tracking down potential virtual disk
23 * write performance issues. */
24#undef VBOX_INSTRUMENT_DMA_WRITES
25
26/** @name The SSM saved state versions.
27 * @{
28 */
29/** The current saved state version. */
30#define ATA_SAVED_STATE_VERSION 20
31/** The saved state version used by VirtualBox 3.0.
32 * This lacks the config part and has the type at the and. */
33#define ATA_SAVED_STATE_VERSION_VBOX_30 19
34#define ATA_SAVED_STATE_VERSION_WITH_BOOL_TYPE 18
35#define ATA_SAVED_STATE_VERSION_WITHOUT_FULL_SENSE 16
36#define ATA_SAVED_STATE_VERSION_WITHOUT_EVENT_STATUS 17
37/** @} */
38
39
40/*******************************************************************************
41* Header Files *
42*******************************************************************************/
43#define LOG_GROUP LOG_GROUP_DEV_IDE
44#include <VBox/vmm/pdmdev.h>
45#include <iprt/assert.h>
46#include <iprt/string.h>
47#ifdef IN_RING3
48# include <iprt/uuid.h>
49# include <iprt/semaphore.h>
50# include <iprt/thread.h>
51# include <iprt/time.h>
52# include <iprt/alloc.h>
53#endif /* IN_RING3 */
54#include <iprt/critsect.h>
55#include <iprt/asm.h>
56#include <VBox/vmm/stam.h>
57#include <VBox/vmm/mm.h>
58#include <VBox/vmm/pgm.h>
59
60#include <VBox/sup.h>
61#include <VBox/scsi.h>
62
63#include "PIIX3ATABmDma.h"
64#include "ide.h"
65#include "ATAPIPassthrough.h"
66#include "VBoxDD.h"
67
68
69/*******************************************************************************
70* Defined Constants And Macros *
71*******************************************************************************/
72/**
73 * Maximum number of sectors to transfer in a READ/WRITE MULTIPLE request.
74 * Set to 1 to disable multi-sector read support. According to the ATA
75 * specification this must be a power of 2 and it must fit in an 8 bit
76 * value. Thus the only valid values are 1, 2, 4, 8, 16, 32, 64 and 128.
77 */
78#define ATA_MAX_MULT_SECTORS 128
79
80/**
81 * Fastest PIO mode supported by the drive.
82 */
83#define ATA_PIO_MODE_MAX 4
84/**
85 * Fastest MDMA mode supported by the drive.
86 */
87#define ATA_MDMA_MODE_MAX 2
88/**
89 * Fastest UDMA mode supported by the drive.
90 */
91#define ATA_UDMA_MODE_MAX 6
92
93/** ATAPI sense info size. */
94#define ATAPI_SENSE_SIZE 64
95
96/** The maximum number of release log entries per device. */
97#define MAX_LOG_REL_ERRORS 1024
98
99/* MediaEventStatus */
100#define ATA_EVENT_STATUS_UNCHANGED 0 /**< medium event status not changed */
101#define ATA_EVENT_STATUS_MEDIA_NEW 1 /**< new medium inserted */
102#define ATA_EVENT_STATUS_MEDIA_REMOVED 2 /**< medium removed */
103#define ATA_EVENT_STATUS_MEDIA_CHANGED 3 /**< medium was removed + new medium was inserted */
104#define ATA_EVENT_STATUS_MEDIA_EJECT_REQUESTED 4 /**< medium eject requested (eject button pressed) */
105
106/* Media track type */
107#define ATA_MEDIA_TYPE_UNKNOWN 0 /**< unknown CD type */
108#define ATA_MEDIA_NO_DISC 0x70 /**< Door closed, no medium */
109
110/*******************************************************************************
111* Structures and Typedefs *
112*******************************************************************************/
113/**
114 * The state of an ATA device.
115 *
116 * @implements PDMIBASE
117 * @implements PDMIBLOCKPORT
118 * @implements PDMIMOUNTNOTIFY
119 */
120typedef struct ATADevState
121{
122 /** Flag indicating whether the current command uses LBA48 mode. */
123 bool fLBA48;
124 /** Flag indicating whether this drive implements the ATAPI command set. */
125 bool fATAPI;
126 /** Set if this interface has asserted the IRQ. */
127 bool fIrqPending;
128 /** Currently configured number of sectors in a multi-sector transfer. */
129 uint8_t cMultSectors;
130 /** PCHS disk geometry. */
131 PDMMEDIAGEOMETRY PCHSGeometry;
132 /** Total number of sectors on this disk. */
133 uint64_t cTotalSectors;
134 /** Sector size of the medium. */
135 uint32_t cbSector;
136 /** Number of sectors to transfer per IRQ. */
137 uint32_t cSectorsPerIRQ;
138
139 /** ATA/ATAPI register 1: feature (write-only). */
140 uint8_t uATARegFeature;
141 /** ATA/ATAPI register 1: feature, high order byte. */
142 uint8_t uATARegFeatureHOB;
143 /** ATA/ATAPI register 1: error (read-only). */
144 uint8_t uATARegError;
145 /** ATA/ATAPI register 2: sector count (read/write). */
146 uint8_t uATARegNSector;
147 /** ATA/ATAPI register 2: sector count, high order byte. */
148 uint8_t uATARegNSectorHOB;
149 /** ATA/ATAPI register 3: sector (read/write). */
150 uint8_t uATARegSector;
151 /** ATA/ATAPI register 3: sector, high order byte. */
152 uint8_t uATARegSectorHOB;
153 /** ATA/ATAPI register 4: cylinder low (read/write). */
154 uint8_t uATARegLCyl;
155 /** ATA/ATAPI register 4: cylinder low, high order byte. */
156 uint8_t uATARegLCylHOB;
157 /** ATA/ATAPI register 5: cylinder high (read/write). */
158 uint8_t uATARegHCyl;
159 /** ATA/ATAPI register 5: cylinder high, high order byte. */
160 uint8_t uATARegHCylHOB;
161 /** ATA/ATAPI register 6: select drive/head (read/write). */
162 uint8_t uATARegSelect;
163 /** ATA/ATAPI register 7: status (read-only). */
164 uint8_t uATARegStatus;
165 /** ATA/ATAPI register 7: command (write-only). */
166 uint8_t uATARegCommand;
167 /** ATA/ATAPI drive control register (write-only). */
168 uint8_t uATARegDevCtl;
169
170 /** Currently active transfer mode (MDMA/UDMA) and speed. */
171 uint8_t uATATransferMode;
172 /** Current transfer direction. */
173 uint8_t uTxDir;
174 /** Index of callback for begin transfer. */
175 uint8_t iBeginTransfer;
176 /** Index of callback for source/sink of data. */
177 uint8_t iSourceSink;
178 /** Flag indicating whether the current command transfers data in DMA mode. */
179 bool fDMA;
180 /** Set to indicate that ATAPI transfer semantics must be used. */
181 bool fATAPITransfer;
182
183 /** Total ATA/ATAPI transfer size, shared PIO/DMA. */
184 uint32_t cbTotalTransfer;
185 /** Elementary ATA/ATAPI transfer size, shared PIO/DMA. */
186 uint32_t cbElementaryTransfer;
187 /** Maximum ATAPI elementary transfer size, PIO only. */
188 uint32_t cbPIOTransferLimit;
189 /** ATAPI passthrough transfer size, shared PIO/DMA */
190 uint32_t cbAtapiPassthroughTransfer;
191 /** Current read/write buffer position, shared PIO/DMA. */
192 uint32_t iIOBufferCur;
193 /** First element beyond end of valid buffer content, shared PIO/DMA. */
194 uint32_t iIOBufferEnd;
195 /** Align the following fields correctly. */
196 uint32_t Alignment0;
197
198 /** ATA/ATAPI current PIO read/write transfer position. Not shared with DMA for safety reasons. */
199 uint32_t iIOBufferPIODataStart;
200 /** ATA/ATAPI current PIO read/write transfer end. Not shared with DMA for safety reasons. */
201 uint32_t iIOBufferPIODataEnd;
202
203 /** ATAPI current LBA position. */
204 uint32_t iATAPILBA;
205 /** ATAPI current sector size. */
206 uint32_t cbATAPISector;
207 /** ATAPI current command. */
208 uint8_t aATAPICmd[ATAPI_PACKET_SIZE];
209 /** ATAPI sense data. */
210 uint8_t abATAPISense[ATAPI_SENSE_SIZE];
211 /** HACK: Countdown till we report a newly unmounted drive as mounted. */
212 uint8_t cNotifiedMediaChange;
213 /** The same for GET_EVENT_STATUS for mechanism */
214 volatile uint32_t MediaEventStatus;
215
216 /** Media type if known. */
217 volatile uint32_t MediaTrackType;
218
219 /** The status LED state for this drive. */
220 PDMLED Led;
221
222 /** Size of I/O buffer. */
223 uint32_t cbIOBuffer;
224 /** Pointer to the I/O buffer. */
225 R3PTRTYPE(uint8_t *) pbIOBufferR3;
226 /** Pointer to the I/O buffer. */
227 R0PTRTYPE(uint8_t *) pbIOBufferR0;
228 /** Pointer to the I/O buffer. */
229 RCPTRTYPE(uint8_t *) pbIOBufferRC;
230
231 RTRCPTR Aligmnent1; /**< Align the statistics at an 8-byte boundary. */
232
233 /*
234 * No data that is part of the saved state after this point!!!!!
235 */
236
237 /* Release statistics: number of ATA DMA commands. */
238 STAMCOUNTER StatATADMA;
239 /* Release statistics: number of ATA PIO commands. */
240 STAMCOUNTER StatATAPIO;
241 /* Release statistics: number of ATAPI PIO commands. */
242 STAMCOUNTER StatATAPIDMA;
243 /* Release statistics: number of ATAPI PIO commands. */
244 STAMCOUNTER StatATAPIPIO;
245#ifdef VBOX_INSTRUMENT_DMA_WRITES
246 /* Release statistics: number of DMA sector writes and the time spent. */
247 STAMPROFILEADV StatInstrVDWrites;
248#endif
249
250 /** Statistics: number of read operations and the time spent reading. */
251 STAMPROFILEADV StatReads;
252 /** Statistics: number of bytes read. */
253 STAMCOUNTER StatBytesRead;
254 /** Statistics: number of write operations and the time spent writing. */
255 STAMPROFILEADV StatWrites;
256 /** Statistics: number of bytes written. */
257 STAMCOUNTER StatBytesWritten;
258 /** Statistics: number of flush operations and the time spend flushing. */
259 STAMPROFILE StatFlushes;
260
261 /** Mark the drive as having a non-rotational medium (i.e. as a SSD). */
262 bool fNonRotational;
263 /** Enable passing through commands directly to the ATAPI drive. */
264 bool fATAPIPassthrough;
265 /** Flag whether to overwrite inquiry data in passthrough mode. */
266 bool fOverwriteInquiry;
267 /** Number of errors we've reported to the release log.
268 * This is to prevent flooding caused by something going horribly wrong.
269 * this value against MAX_LOG_REL_ERRORS in places likely to cause floods
270 * like the ones we currently seeing on the linux smoke tests (2006-11-10). */
271 uint32_t cErrors;
272 /** Timestamp of last started command. 0 if no command pending. */
273 uint64_t u64CmdTS;
274
275 /** Pointer to the attached driver's base interface. */
276 R3PTRTYPE(PPDMIBASE) pDrvBase;
277 /** Pointer to the attached driver's block interface. */
278 R3PTRTYPE(PPDMIBLOCK) pDrvBlock;
279 /** Pointer to the attached driver's block bios interface. */
280 R3PTRTYPE(PPDMIBLOCKBIOS) pDrvBlockBios;
281 /** Pointer to the attached driver's mount interface.
282 * This is NULL if the driver isn't a removable unit. */
283 R3PTRTYPE(PPDMIMOUNT) pDrvMount;
284 /** The base interface. */
285 PDMIBASE IBase;
286 /** The block port interface. */
287 PDMIBLOCKPORT IPort;
288 /** The mount notify interface. */
289 PDMIMOUNTNOTIFY IMountNotify;
290 /** The LUN #. */
291 RTUINT iLUN;
292 RTUINT Alignment2; /**< Align pDevInsR3 correctly. */
293 /** Pointer to device instance. */
294 PPDMDEVINSR3 pDevInsR3;
295 /** Pointer to controller instance. */
296 R3PTRTYPE(struct ATACONTROLLER *) pControllerR3;
297 /** Pointer to device instance. */
298 PPDMDEVINSR0 pDevInsR0;
299 /** Pointer to controller instance. */
300 R0PTRTYPE(struct ATACONTROLLER *) pControllerR0;
301 /** Pointer to device instance. */
302 PPDMDEVINSRC pDevInsRC;
303 /** Pointer to controller instance. */
304 RCPTRTYPE(struct ATACONTROLLER *) pControllerRC;
305
306 /** The serial number to use for IDENTIFY DEVICE commands. */
307 char szSerialNumber[ATA_SERIAL_NUMBER_LENGTH+1];
308 /** The firmware revision to use for IDENTIFY DEVICE commands. */
309 char szFirmwareRevision[ATA_FIRMWARE_REVISION_LENGTH+1];
310 /** The model number to use for IDENTIFY DEVICE commands. */
311 char szModelNumber[ATA_MODEL_NUMBER_LENGTH+1];
312 /** The vendor identification string for SCSI INQUIRY commands. */
313 char szInquiryVendorId[ATAPI_INQUIRY_VENDOR_ID_LENGTH+1];
314 /** The product identification string for SCSI INQUIRY commands. */
315 char szInquiryProductId[ATAPI_INQUIRY_PRODUCT_ID_LENGTH+1];
316 /** The revision string for SCSI INQUIRY commands. */
317 char szInquiryRevision[ATAPI_INQUIRY_REVISION_LENGTH+1];
318 /** The current tracklist of the loaded medium if passthrough is used. */
319 R3PTRTYPE(PTRACKLIST) pTrackList;
320
321 uint8_t abAlignment4[HC_ARCH_BITS == 64 ? 7 : 3];
322} ATADevState;
323AssertCompileMemberAlignment(ATADevState, cTotalSectors, 8);
324AssertCompileMemberAlignment(ATADevState, StatATADMA, 8);
325AssertCompileMemberAlignment(ATADevState, u64CmdTS, 8);
326AssertCompileMemberAlignment(ATADevState, pDevInsR3, 8);
327AssertCompileMemberAlignment(ATADevState, szSerialNumber, 8);
328AssertCompileSizeAlignment(ATADevState, 8);
329
330
331typedef struct ATATransferRequest
332{
333 uint8_t iIf;
334 uint8_t iBeginTransfer;
335 uint8_t iSourceSink;
336 uint32_t cbTotalTransfer;
337 uint8_t uTxDir;
338} ATATransferRequest;
339
340
341typedef struct ATAAbortRequest
342{
343 uint8_t iIf;
344 bool fResetDrive;
345} ATAAbortRequest;
346
347
348typedef enum
349{
350 /** Begin a new transfer. */
351 ATA_AIO_NEW = 0,
352 /** Continue a DMA transfer. */
353 ATA_AIO_DMA,
354 /** Continue a PIO transfer. */
355 ATA_AIO_PIO,
356 /** Reset the drives on current controller, stop all transfer activity. */
357 ATA_AIO_RESET_ASSERTED,
358 /** Reset the drives on current controller, resume operation. */
359 ATA_AIO_RESET_CLEARED,
360 /** Abort the current transfer of a particular drive. */
361 ATA_AIO_ABORT
362} ATAAIO;
363
364
365typedef struct ATARequest
366{
367 ATAAIO ReqType;
368 union
369 {
370 ATATransferRequest t;
371 ATAAbortRequest a;
372 } u;
373} ATARequest;
374
375
376typedef struct ATACONTROLLER
377{
378 /** The base of the first I/O Port range. */
379 RTIOPORT IOPortBase1;
380 /** The base of the second I/O Port range. (0 if none) */
381 RTIOPORT IOPortBase2;
382 /** The assigned IRQ. */
383 RTUINT irq;
384 /** Access critical section */
385 PDMCRITSECT lock;
386
387 /** Selected drive. */
388 uint8_t iSelectedIf;
389 /** The interface on which to handle async I/O. */
390 uint8_t iAIOIf;
391 /** The state of the async I/O thread. */
392 uint8_t uAsyncIOState;
393 /** Flag indicating whether the next transfer is part of the current command. */
394 bool fChainedTransfer;
395 /** Set when the reset processing is currently active on this controller. */
396 bool fReset;
397 /** Flag whether the current transfer needs to be redone. */
398 bool fRedo;
399 /** Flag whether the redo suspend has been finished. */
400 bool fRedoIdle;
401 /** Flag whether the DMA operation to be redone is the final transfer. */
402 bool fRedoDMALastDesc;
403 /** The BusMaster DMA state. */
404 BMDMAState BmDma;
405 /** Pointer to first DMA descriptor. */
406 RTGCPHYS32 pFirstDMADesc;
407 /** Pointer to last DMA descriptor. */
408 RTGCPHYS32 pLastDMADesc;
409 /** Pointer to current DMA buffer (for redo operations). */
410 RTGCPHYS32 pRedoDMABuffer;
411 /** Size of current DMA buffer (for redo operations). */
412 uint32_t cbRedoDMABuffer;
413
414 /** The ATA/ATAPI interfaces of this controller. */
415 ATADevState aIfs[2];
416
417 /** Pointer to device instance. */
418 PPDMDEVINSR3 pDevInsR3;
419 /** Pointer to device instance. */
420 PPDMDEVINSR0 pDevInsR0;
421 /** Pointer to device instance. */
422 PPDMDEVINSRC pDevInsRC;
423
424 /** Set when the destroying the device instance and the thread must exit. */
425 uint32_t volatile fShutdown;
426 /** The async I/O thread handle. NIL_RTTHREAD if no thread. */
427 RTTHREAD AsyncIOThread;
428 /** The event semaphore the thread is waiting on for requests. */
429 SUPSEMEVENT hAsyncIOSem;
430 /** The support driver session handle. */
431 PSUPDRVSESSION pSupDrvSession;
432 /** The request queue for the AIO thread. One element is always unused. */
433 ATARequest aAsyncIORequests[4];
434 /** The position at which to insert a new request for the AIO thread. */
435 volatile uint8_t AsyncIOReqHead;
436 /** The position at which to get a new request for the AIO thread. */
437 volatile uint8_t AsyncIOReqTail;
438 /** Whether to call PDMDevHlpAsyncNotificationCompleted when idle. */
439 bool volatile fSignalIdle;
440 uint8_t Alignment3[1]; /**< Explicit padding of the 1 byte gap. */
441 /** Magic delay before triggering interrupts in DMA mode. */
442 uint32_t DelayIRQMillies;
443 /** The lock protecting the request queue. */
444 PDMCRITSECT AsyncIORequestLock;
445 /** The event semaphore the thread is waiting on during suspended I/O. */
446 RTSEMEVENT SuspendIOSem;
447#if 0 /*HC_ARCH_BITS == 32*/
448 uint32_t Alignment0;
449#endif
450
451 /** Timestamp we started the reset. */
452 uint64_t u64ResetTime;
453
454 /* Statistics */
455 STAMCOUNTER StatAsyncOps;
456 uint64_t StatAsyncMinWait;
457 uint64_t StatAsyncMaxWait;
458 STAMCOUNTER StatAsyncTimeUS;
459 STAMPROFILEADV StatAsyncTime;
460 STAMPROFILE StatLockWait;
461} ATACONTROLLER, *PATACONTROLLER;
462AssertCompileMemberAlignment(ATACONTROLLER, lock, 8);
463AssertCompileMemberAlignment(ATACONTROLLER, aIfs, 8);
464AssertCompileMemberAlignment(ATACONTROLLER, u64ResetTime, 8);
465AssertCompileMemberAlignment(ATACONTROLLER, StatAsyncOps, 8);
466
467typedef enum CHIPSET
468{
469 /** PIIX3 chipset, must be 0 for saved state compatibility */
470 CHIPSET_PIIX3 = 0,
471 /** PIIX4 chipset, must be 1 for saved state compatibility */
472 CHIPSET_PIIX4 = 1,
473 /** ICH6 chipset */
474 CHIPSET_ICH6 = 2
475} CHIPSET;
476
477/**
478 * The state of the ATA PCI device.
479 *
480 * @extends PCIDEVICE
481 * @implements PDMILEDPORTS
482 */
483typedef struct PCIATAState
484{
485 PCIDEVICE dev;
486 /** The controllers. */
487 ATACONTROLLER aCts[2];
488 /** Pointer to device instance. */
489 PPDMDEVINSR3 pDevIns;
490 /** Status LUN: Base interface. */
491 PDMIBASE IBase;
492 /** Status LUN: Leds interface. */
493 PDMILEDPORTS ILeds;
494 /** Status LUN: Partner of ILeds. */
495 R3PTRTYPE(PPDMILEDCONNECTORS) pLedsConnector;
496 /** Status LUN: Media Notify. */
497 R3PTRTYPE(PPDMIMEDIANOTIFY) pMediaNotify;
498 /** Flag whether RC is enabled. */
499 bool fRCEnabled;
500 /** Flag whether R0 is enabled. */
501 bool fR0Enabled;
502 /** Flag indicating chipset being emulated. */
503 uint8_t u8Type;
504 bool Alignment0[HC_ARCH_BITS == 64 ? 5 : 1 ]; /**< Align the struct size. */
505} PCIATAState;
506
507#define PDMIBASE_2_PCIATASTATE(pInterface) ( (PCIATAState *)((uintptr_t)(pInterface) - RT_OFFSETOF(PCIATAState, IBase)) )
508#define PDMILEDPORTS_2_PCIATASTATE(pInterface) ( (PCIATAState *)((uintptr_t)(pInterface) - RT_OFFSETOF(PCIATAState, ILeds)) )
509#define PDMIBLOCKPORT_2_ATASTATE(pInterface) ( (ATADevState *)((uintptr_t)(pInterface) - RT_OFFSETOF(ATADevState, IPort)) )
510#define PDMIMOUNT_2_ATASTATE(pInterface) ( (ATADevState *)((uintptr_t)(pInterface) - RT_OFFSETOF(ATADevState, IMount)) )
511#define PDMIMOUNTNOTIFY_2_ATASTATE(pInterface) ( (ATADevState *)((uintptr_t)(pInterface) - RT_OFFSETOF(ATADevState, IMountNotify)) )
512#define PCIDEV_2_PCIATASTATE(pPciDev) ( (PCIATAState *)(pPciDev) )
513
514#define ATACONTROLLER_IDX(pController) ( (pController) - PDMINS_2_DATA(CONTROLLER_2_DEVINS(pController), PCIATAState *)->aCts )
515
516#define ATADEVSTATE_2_CONTROLLER(pIf) ( (pIf)->CTX_SUFF(pController) )
517#define ATADEVSTATE_2_DEVINS(pIf) ( (pIf)->CTX_SUFF(pDevIns) )
518#define CONTROLLER_2_DEVINS(pController) ( (pController)->CTX_SUFF(pDevIns) )
519#define PDMIBASE_2_ATASTATE(pInterface) ( (ATADevState *)((uintptr_t)(pInterface) - RT_OFFSETOF(ATADevState, IBase)) )
520#define PDMIBLOCKPORT_2_ATASTATE(pInterface) ( (ATADevState *)((uintptr_t)(pInterface) - RT_OFFSETOF(ATADevState, IPort)) )
521
522#ifndef VBOX_DEVICE_STRUCT_TESTCASE
523/*******************************************************************************
524 * Internal Functions *
525 ******************************************************************************/
526RT_C_DECLS_BEGIN
527
528PDMBOTHCBDECL(int) ataIOPortWrite1Data(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t u32, unsigned cb);
529PDMBOTHCBDECL(int) ataIOPortRead1Data(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t *u32, unsigned cb);
530PDMBOTHCBDECL(int) ataIOPortWriteStr1Data(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint8_t const *pbSrc,
531 uint32_t *pcTransfers, unsigned cb);
532PDMBOTHCBDECL(int) ataIOPortReadStr1Data(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint8_t *pbDst,
533 uint32_t *pcTransfers, unsigned cb);
534PDMBOTHCBDECL(int) ataIOPortWrite1Other(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t u32, unsigned cb);
535PDMBOTHCBDECL(int) ataIOPortRead1Other(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t *u32, unsigned cb);
536PDMBOTHCBDECL(int) ataIOPortWrite2(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t u32, unsigned cb);
537PDMBOTHCBDECL(int) ataIOPortRead2(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t *u32, unsigned cb);
538PDMBOTHCBDECL(int) ataBMDMAIOPortWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t u32, unsigned cb);
539PDMBOTHCBDECL(int) ataBMDMAIOPortRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t *pu32, unsigned cb);
540RT_C_DECLS_END
541
542
543
544DECLINLINE(void) ataSetStatusValue(ATADevState *s, uint8_t stat)
545{
546 PATACONTROLLER pCtl = ATADEVSTATE_2_CONTROLLER(s);
547
548 /* Freeze status register contents while processing RESET. */
549 if (!pCtl->fReset)
550 {
551 s->uATARegStatus = stat;
552 Log2(("%s: LUN#%d status %#04x\n", __FUNCTION__, s->iLUN, s->uATARegStatus));
553 }
554}
555
556
557DECLINLINE(void) ataSetStatus(ATADevState *s, uint8_t stat)
558{
559 PATACONTROLLER pCtl = ATADEVSTATE_2_CONTROLLER(s);
560
561 /* Freeze status register contents while processing RESET. */
562 if (!pCtl->fReset)
563 {
564 s->uATARegStatus |= stat;
565 Log2(("%s: LUN#%d status %#04x\n", __FUNCTION__, s->iLUN, s->uATARegStatus));
566 }
567}
568
569
570DECLINLINE(void) ataUnsetStatus(ATADevState *s, uint8_t stat)
571{
572 PATACONTROLLER pCtl = ATADEVSTATE_2_CONTROLLER(s);
573
574 /* Freeze status register contents while processing RESET. */
575 if (!pCtl->fReset)
576 {
577 s->uATARegStatus &= ~stat;
578 Log2(("%s: LUN#%d status %#04x\n", __FUNCTION__, s->iLUN, s->uATARegStatus));
579 }
580}
581
582#if defined(IN_RING3) || defined(IN_RING0)
583
584# ifdef IN_RING3
585typedef void (*PBeginTransferFunc)(ATADevState *);
586typedef bool (*PSourceSinkFunc)(ATADevState *);
587
588static void ataR3ReadWriteSectorsBT(ATADevState *);
589static void ataR3PacketBT(ATADevState *);
590static void atapiR3CmdBT(ATADevState *);
591static void atapiR3PassthroughCmdBT(ATADevState *);
592
593static bool ataR3IdentifySS(ATADevState *);
594static bool ataR3FlushSS(ATADevState *);
595static bool ataR3ReadSectorsSS(ATADevState *);
596static bool ataR3WriteSectorsSS(ATADevState *);
597static bool ataR3ExecuteDeviceDiagnosticSS(ATADevState *);
598static bool ataR3TrimSS(ATADevState *);
599static bool ataR3PacketSS(ATADevState *);
600static bool atapiR3GetConfigurationSS(ATADevState *);
601static bool atapiR3GetEventStatusNotificationSS(ATADevState *);
602static bool atapiR3IdentifySS(ATADevState *);
603static bool atapiR3InquirySS(ATADevState *);
604static bool atapiR3MechanismStatusSS(ATADevState *);
605static bool atapiR3ModeSenseErrorRecoverySS(ATADevState *);
606static bool atapiR3ModeSenseCDStatusSS(ATADevState *);
607static bool atapiR3ReadSS(ATADevState *);
608static bool atapiR3ReadCapacitySS(ATADevState *);
609static bool atapiR3ReadDiscInformationSS(ATADevState *);
610static bool atapiR3ReadTOCNormalSS(ATADevState *);
611static bool atapiR3ReadTOCMultiSS(ATADevState *);
612static bool atapiR3ReadTOCRawSS(ATADevState *);
613static bool atapiR3ReadTrackInformationSS(ATADevState *);
614static bool atapiR3RequestSenseSS(ATADevState *);
615static bool atapiR3PassthroughSS(ATADevState *);
616static bool atapiR3ReadDVDStructureSS(ATADevState *);
617# endif /* IN_RING3 */
618
619/**
620 * Begin of transfer function indexes for g_apfnBeginTransFuncs.
621 */
622typedef enum ATAFNBT
623{
624 ATAFN_BT_NULL = 0,
625 ATAFN_BT_READ_WRITE_SECTORS,
626 ATAFN_BT_PACKET,
627 ATAFN_BT_ATAPI_CMD,
628 ATAFN_BT_ATAPI_PASSTHROUGH_CMD,
629 ATAFN_BT_MAX
630} ATAFNBT;
631
632# ifdef IN_RING3
633/**
634 * Array of end transfer functions, the index is ATAFNET.
635 * Make sure ATAFNET and this array match!
636 */
637static const PBeginTransferFunc g_apfnBeginTransFuncs[ATAFN_BT_MAX] =
638{
639 NULL,
640 ataR3ReadWriteSectorsBT,
641 ataR3PacketBT,
642 atapiR3CmdBT,
643 atapiR3PassthroughCmdBT,
644};
645# endif /* IN_RING3 */
646
647/**
648 * Source/sink function indexes for g_apfnSourceSinkFuncs.
649 */
650typedef enum ATAFNSS
651{
652 ATAFN_SS_NULL = 0,
653 ATAFN_SS_IDENTIFY,
654 ATAFN_SS_FLUSH,
655 ATAFN_SS_READ_SECTORS,
656 ATAFN_SS_WRITE_SECTORS,
657 ATAFN_SS_EXECUTE_DEVICE_DIAGNOSTIC,
658 ATAFN_SS_TRIM,
659 ATAFN_SS_PACKET,
660 ATAFN_SS_ATAPI_GET_CONFIGURATION,
661 ATAFN_SS_ATAPI_GET_EVENT_STATUS_NOTIFICATION,
662 ATAFN_SS_ATAPI_IDENTIFY,
663 ATAFN_SS_ATAPI_INQUIRY,
664 ATAFN_SS_ATAPI_MECHANISM_STATUS,
665 ATAFN_SS_ATAPI_MODE_SENSE_ERROR_RECOVERY,
666 ATAFN_SS_ATAPI_MODE_SENSE_CD_STATUS,
667 ATAFN_SS_ATAPI_READ,
668 ATAFN_SS_ATAPI_READ_CAPACITY,
669 ATAFN_SS_ATAPI_READ_DISC_INFORMATION,
670 ATAFN_SS_ATAPI_READ_TOC_NORMAL,
671 ATAFN_SS_ATAPI_READ_TOC_MULTI,
672 ATAFN_SS_ATAPI_READ_TOC_RAW,
673 ATAFN_SS_ATAPI_READ_TRACK_INFORMATION,
674 ATAFN_SS_ATAPI_REQUEST_SENSE,
675 ATAFN_SS_ATAPI_PASSTHROUGH,
676 ATAFN_SS_ATAPI_READ_DVD_STRUCTURE,
677 ATAFN_SS_MAX
678} ATAFNSS;
679
680# ifdef IN_RING3
681/**
682 * Array of source/sink functions, the index is ATAFNSS.
683 * Make sure ATAFNSS and this array match!
684 */
685static const PSourceSinkFunc g_apfnSourceSinkFuncs[ATAFN_SS_MAX] =
686{
687 NULL,
688 ataR3IdentifySS,
689 ataR3FlushSS,
690 ataR3ReadSectorsSS,
691 ataR3WriteSectorsSS,
692 ataR3ExecuteDeviceDiagnosticSS,
693 ataR3TrimSS,
694 ataR3PacketSS,
695 atapiR3GetConfigurationSS,
696 atapiR3GetEventStatusNotificationSS,
697 atapiR3IdentifySS,
698 atapiR3InquirySS,
699 atapiR3MechanismStatusSS,
700 atapiR3ModeSenseErrorRecoverySS,
701 atapiR3ModeSenseCDStatusSS,
702 atapiR3ReadSS,
703 atapiR3ReadCapacitySS,
704 atapiR3ReadDiscInformationSS,
705 atapiR3ReadTOCNormalSS,
706 atapiR3ReadTOCMultiSS,
707 atapiR3ReadTOCRawSS,
708 atapiR3ReadTrackInformationSS,
709 atapiR3RequestSenseSS,
710 atapiR3PassthroughSS,
711 atapiR3ReadDVDStructureSS
712};
713# endif /* IN_RING3 */
714
715
716static const ATARequest g_ataDMARequest = { ATA_AIO_DMA, { { 0, 0, 0, 0, 0 } } };
717static const ATARequest g_ataPIORequest = { ATA_AIO_PIO, { { 0, 0, 0, 0, 0 } } };
718static const ATARequest g_ataResetARequest = { ATA_AIO_RESET_ASSERTED, { { 0, 0, 0, 0, 0 } } };
719static const ATARequest g_ataResetCRequest = { ATA_AIO_RESET_CLEARED, { { 0, 0, 0, 0, 0 } } };
720
721# ifdef IN_RING3
722static void ataR3AsyncIOClearRequests(PATACONTROLLER pCtl)
723{
724 int rc = PDMCritSectEnter(&pCtl->AsyncIORequestLock, VINF_SUCCESS);
725 AssertRC(rc);
726
727 pCtl->AsyncIOReqHead = 0;
728 pCtl->AsyncIOReqTail = 0;
729
730 rc = PDMCritSectLeave(&pCtl->AsyncIORequestLock);
731 AssertRC(rc);
732}
733# endif /* IN_RING3 */
734
735static void ataHCAsyncIOPutRequest(PATACONTROLLER pCtl, const ATARequest *pReq)
736{
737 int rc = PDMCritSectEnter(&pCtl->AsyncIORequestLock, VINF_SUCCESS);
738 AssertRC(rc);
739
740 Assert((pCtl->AsyncIOReqHead + 1) % RT_ELEMENTS(pCtl->aAsyncIORequests) != pCtl->AsyncIOReqTail);
741 memcpy(&pCtl->aAsyncIORequests[pCtl->AsyncIOReqHead], pReq, sizeof(*pReq));
742 pCtl->AsyncIOReqHead++;
743 pCtl->AsyncIOReqHead %= RT_ELEMENTS(pCtl->aAsyncIORequests);
744
745 rc = PDMCritSectLeave(&pCtl->AsyncIORequestLock);
746 AssertRC(rc);
747
748 rc = PDMHCCritSectScheduleExitEvent(&pCtl->lock, pCtl->hAsyncIOSem);
749 if (RT_FAILURE(rc))
750 {
751 rc = SUPSemEventSignal(pCtl->pSupDrvSession, pCtl->hAsyncIOSem);
752 AssertRC(rc);
753 }
754}
755
756# ifdef IN_RING3
757
758static const ATARequest *ataR3AsyncIOGetCurrentRequest(PATACONTROLLER pCtl)
759{
760 const ATARequest *pReq;
761
762 int rc = PDMCritSectEnter(&pCtl->AsyncIORequestLock, VINF_SUCCESS);
763 AssertRC(rc);
764
765 if (pCtl->AsyncIOReqHead != pCtl->AsyncIOReqTail)
766 pReq = &pCtl->aAsyncIORequests[pCtl->AsyncIOReqTail];
767 else
768 pReq = NULL;
769
770 rc = PDMCritSectLeave(&pCtl->AsyncIORequestLock);
771 AssertRC(rc);
772 return pReq;
773}
774
775
776/**
777 * Remove the request with the given type, as it's finished. The request
778 * is not removed blindly, as this could mean a RESET request that is not
779 * yet processed (but has cleared the request queue) is lost.
780 *
781 * @param pCtl Controller for which to remove the request.
782 * @param ReqType Type of the request to remove.
783 */
784static void ataR3AsyncIORemoveCurrentRequest(PATACONTROLLER pCtl, ATAAIO ReqType)
785{
786 int rc = PDMCritSectEnter(&pCtl->AsyncIORequestLock, VINF_SUCCESS);
787 AssertRC(rc);
788
789 if (pCtl->AsyncIOReqHead != pCtl->AsyncIOReqTail && pCtl->aAsyncIORequests[pCtl->AsyncIOReqTail].ReqType == ReqType)
790 {
791 pCtl->AsyncIOReqTail++;
792 pCtl->AsyncIOReqTail %= RT_ELEMENTS(pCtl->aAsyncIORequests);
793 }
794
795 rc = PDMCritSectLeave(&pCtl->AsyncIORequestLock);
796 AssertRC(rc);
797}
798
799
800/**
801 * Dump the request queue for a particular controller. First dump the queue
802 * contents, then the already processed entries, as long as they haven't been
803 * overwritten.
804 *
805 * @param pCtl Controller for which to dump the queue.
806 */
807static void ataR3AsyncIODumpRequests(PATACONTROLLER pCtl)
808{
809 int rc = PDMCritSectEnter(&pCtl->AsyncIORequestLock, VINF_SUCCESS);
810 AssertRC(rc);
811
812 LogRel(("PIIX3 ATA: Ctl#%d: request queue dump (topmost is current):\n", ATACONTROLLER_IDX(pCtl)));
813 uint8_t curr = pCtl->AsyncIOReqTail;
814 do
815 {
816 if (curr == pCtl->AsyncIOReqHead)
817 LogRel(("PIIX3 ATA: Ctl#%d: processed requests (topmost is oldest):\n", ATACONTROLLER_IDX(pCtl)));
818 switch (pCtl->aAsyncIORequests[curr].ReqType)
819 {
820 case ATA_AIO_NEW:
821 LogRel(("new transfer request, iIf=%d iBeginTransfer=%d iSourceSink=%d cbTotalTransfer=%d uTxDir=%d\n", pCtl->aAsyncIORequests[curr].u.t.iIf, pCtl->aAsyncIORequests[curr].u.t.iBeginTransfer, pCtl->aAsyncIORequests[curr].u.t.iSourceSink, pCtl->aAsyncIORequests[curr].u.t.cbTotalTransfer, pCtl->aAsyncIORequests[curr].u.t.uTxDir));
822 break;
823 case ATA_AIO_DMA:
824 LogRel(("dma transfer continuation\n"));
825 break;
826 case ATA_AIO_PIO:
827 LogRel(("pio transfer continuation\n"));
828 break;
829 case ATA_AIO_RESET_ASSERTED:
830 LogRel(("reset asserted request\n"));
831 break;
832 case ATA_AIO_RESET_CLEARED:
833 LogRel(("reset cleared request\n"));
834 break;
835 case ATA_AIO_ABORT:
836 LogRel(("abort request, iIf=%d fResetDrive=%d\n", pCtl->aAsyncIORequests[curr].u.a.iIf, pCtl->aAsyncIORequests[curr].u.a.fResetDrive));
837 break;
838 default:
839 LogRel(("unknown request %d\n", pCtl->aAsyncIORequests[curr].ReqType));
840 }
841 curr = (curr + 1) % RT_ELEMENTS(pCtl->aAsyncIORequests);
842 } while (curr != pCtl->AsyncIOReqTail);
843
844 rc = PDMCritSectLeave(&pCtl->AsyncIORequestLock);
845 AssertRC(rc);
846}
847
848
849/**
850 * Checks whether the request queue for a particular controller is empty
851 * or whether a particular controller is idle.
852 *
853 * @param pCtl Controller for which to check the queue.
854 * @param fStrict If set then the controller is checked to be idle.
855 */
856static bool ataR3AsyncIOIsIdle(PATACONTROLLER pCtl, bool fStrict)
857{
858 int rc = PDMCritSectEnter(&pCtl->AsyncIORequestLock, VINF_SUCCESS);
859 AssertRC(rc);
860
861 bool fIdle = pCtl->fRedoIdle;
862 if (!fIdle)
863 fIdle = (pCtl->AsyncIOReqHead == pCtl->AsyncIOReqTail);
864 if (fStrict)
865 fIdle &= (pCtl->uAsyncIOState == ATA_AIO_NEW);
866
867 rc = PDMCritSectLeave(&pCtl->AsyncIORequestLock);
868 AssertRC(rc);
869 return fIdle;
870}
871
872
873/**
874 * Send a transfer request to the async I/O thread.
875 *
876 * @param s Pointer to the ATA device state data.
877 * @param cbTotalTransfer Data transfer size.
878 * @param uTxDir Data transfer direction.
879 * @param iBeginTransfer Index of BeginTransfer callback.
880 * @param iSourceSink Index of SourceSink callback.
881 * @param fChainedTransfer Whether this is a transfer that is part of the previous command/transfer.
882 */
883static void ataR3StartTransfer(ATADevState *s, uint32_t cbTotalTransfer, uint8_t uTxDir, ATAFNBT iBeginTransfer,
884 ATAFNSS iSourceSink, bool fChainedTransfer)
885{
886 PATACONTROLLER pCtl = ATADEVSTATE_2_CONTROLLER(s);
887 ATARequest Req;
888
889 Assert(PDMCritSectIsOwner(&pCtl->lock));
890
891 /* Do not issue new requests while the RESET line is asserted. */
892 if (pCtl->fReset)
893 {
894 Log2(("%s: Ctl#%d: suppressed new request as RESET is active\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl)));
895 return;
896 }
897
898 /* If the controller is already doing something else right now, ignore
899 * the command that is being submitted. Some broken guests issue commands
900 * twice (e.g. the Linux kernel that comes with Acronis True Image 8). */
901 if (!fChainedTransfer && !ataR3AsyncIOIsIdle(pCtl, true /*fStrict*/))
902 {
903 Log(("%s: Ctl#%d: ignored command %#04x, controller state %d\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl), s->uATARegCommand, pCtl->uAsyncIOState));
904 LogRel(("PIIX3 IDE: guest issued command %#04x while controller busy\n", s->uATARegCommand));
905 return;
906 }
907
908 Req.ReqType = ATA_AIO_NEW;
909 if (fChainedTransfer)
910 Req.u.t.iIf = pCtl->iAIOIf;
911 else
912 Req.u.t.iIf = pCtl->iSelectedIf;
913 Req.u.t.cbTotalTransfer = cbTotalTransfer;
914 Req.u.t.uTxDir = uTxDir;
915 Req.u.t.iBeginTransfer = iBeginTransfer;
916 Req.u.t.iSourceSink = iSourceSink;
917 ataSetStatusValue(s, ATA_STAT_BUSY);
918 pCtl->fChainedTransfer = fChainedTransfer;
919
920 /*
921 * Kick the worker thread into action.
922 */
923 Log2(("%s: Ctl#%d: message to async I/O thread, new request\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl)));
924 ataHCAsyncIOPutRequest(pCtl, &Req);
925}
926
927
928/**
929 * Send an abort command request to the async I/O thread.
930 *
931 * @param s Pointer to the ATA device state data.
932 * @param fResetDrive Whether to reset the drive or just abort a command.
933 */
934static void ataR3AbortCurrentCommand(ATADevState *s, bool fResetDrive)
935{
936 PATACONTROLLER pCtl = ATADEVSTATE_2_CONTROLLER(s);
937 ATARequest Req;
938
939 Assert(PDMCritSectIsOwner(&pCtl->lock));
940
941 /* Do not issue new requests while the RESET line is asserted. */
942 if (pCtl->fReset)
943 {
944 Log2(("%s: Ctl#%d: suppressed aborting command as RESET is active\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl)));
945 return;
946 }
947
948 Req.ReqType = ATA_AIO_ABORT;
949 Req.u.a.iIf = pCtl->iSelectedIf;
950 Req.u.a.fResetDrive = fResetDrive;
951 ataSetStatus(s, ATA_STAT_BUSY);
952 Log2(("%s: Ctl#%d: message to async I/O thread, abort command on LUN#%d\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl), s->iLUN));
953 ataHCAsyncIOPutRequest(pCtl, &Req);
954}
955# endif /* IN_RING3 */
956
957static void ataHCSetIRQ(ATADevState *s)
958{
959 PATACONTROLLER pCtl = ATADEVSTATE_2_CONTROLLER(s);
960 PPDMDEVINS pDevIns = ATADEVSTATE_2_DEVINS(s);
961
962 if (!(s->uATARegDevCtl & ATA_DEVCTL_DISABLE_IRQ))
963 {
964 Log2(("%s: LUN#%d asserting IRQ\n", __FUNCTION__, s->iLUN));
965 /* The BMDMA unit unconditionally sets BM_STATUS_INT if the interrupt
966 * line is asserted. It monitors the line for a rising edge. */
967 if (!s->fIrqPending)
968 pCtl->BmDma.u8Status |= BM_STATUS_INT;
969 /* Only actually set the IRQ line if updating the currently selected drive. */
970 if (s == &pCtl->aIfs[pCtl->iSelectedIf])
971 {
972 /** @todo experiment with adaptive IRQ delivery: for reads it is
973 * better to wait for IRQ delivery, as it reduces latency. */
974 if (pCtl->irq == 16)
975 PDMDevHlpPCISetIrq(pDevIns, 0, 1);
976 else
977 PDMDevHlpISASetIrq(pDevIns, pCtl->irq, 1);
978 }
979 }
980 s->fIrqPending = true;
981}
982
983#endif /* IN_RING0 || IN_RING3 */
984
985static void ataUnsetIRQ(ATADevState *s)
986{
987 PATACONTROLLER pCtl = ATADEVSTATE_2_CONTROLLER(s);
988 PPDMDEVINS pDevIns = ATADEVSTATE_2_DEVINS(s);
989
990 if (!(s->uATARegDevCtl & ATA_DEVCTL_DISABLE_IRQ))
991 {
992 Log2(("%s: LUN#%d deasserting IRQ\n", __FUNCTION__, s->iLUN));
993 /* Only actually unset the IRQ line if updating the currently selected drive. */
994 if (s == &pCtl->aIfs[pCtl->iSelectedIf])
995 {
996 if (pCtl->irq == 16)
997 PDMDevHlpPCISetIrq(pDevIns, 0, 0);
998 else
999 PDMDevHlpISASetIrq(pDevIns, pCtl->irq, 0);
1000 }
1001 }
1002 s->fIrqPending = false;
1003}
1004
1005#if defined(IN_RING0) || defined(IN_RING3)
1006
1007static void ataHCPIOTransferStart(ATADevState *s, uint32_t start, uint32_t size)
1008{
1009 Log2(("%s: LUN#%d start %d size %d\n", __FUNCTION__, s->iLUN, start, size));
1010 s->iIOBufferPIODataStart = start;
1011 s->iIOBufferPIODataEnd = start + size;
1012 ataSetStatus(s, ATA_STAT_DRQ | ATA_STAT_SEEK);
1013 ataUnsetStatus(s, ATA_STAT_BUSY);
1014}
1015
1016
1017static void ataHCPIOTransferStop(ATADevState *s)
1018{
1019 Log2(("%s: LUN#%d\n", __FUNCTION__, s->iLUN));
1020 if (s->fATAPITransfer)
1021 {
1022 s->uATARegNSector = (s->uATARegNSector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
1023 Log2(("%s: interrupt reason %#04x\n", __FUNCTION__, s->uATARegNSector));
1024 ataHCSetIRQ(s);
1025 s->fATAPITransfer = false;
1026 }
1027 s->cbTotalTransfer = 0;
1028 s->cbElementaryTransfer = 0;
1029 s->iIOBufferPIODataStart = 0;
1030 s->iIOBufferPIODataEnd = 0;
1031 s->iBeginTransfer = ATAFN_BT_NULL;
1032 s->iSourceSink = ATAFN_SS_NULL;
1033}
1034
1035
1036static void ataHCPIOTransferLimitATAPI(ATADevState *s)
1037{
1038 uint32_t cbLimit, cbTransfer;
1039
1040 cbLimit = s->cbPIOTransferLimit;
1041 /* Use maximum transfer size if the guest requested 0. Avoids a hang. */
1042 if (cbLimit == 0)
1043 cbLimit = 0xfffe;
1044 Log2(("%s: byte count limit=%d\n", __FUNCTION__, cbLimit));
1045 if (cbLimit == 0xffff)
1046 cbLimit--;
1047 cbTransfer = RT_MIN(s->cbTotalTransfer, s->iIOBufferEnd - s->iIOBufferCur);
1048 if (cbTransfer > cbLimit)
1049 {
1050 /* Byte count limit for clipping must be even in this case */
1051 if (cbLimit & 1)
1052 cbLimit--;
1053 cbTransfer = cbLimit;
1054 }
1055 s->uATARegLCyl = cbTransfer;
1056 s->uATARegHCyl = cbTransfer >> 8;
1057 s->cbElementaryTransfer = cbTransfer;
1058}
1059
1060# ifdef IN_RING3
1061
1062static uint32_t ataR3GetNSectors(ATADevState *s)
1063{
1064 /* 0 means either 256 (LBA28) or 65536 (LBA48) sectors. */
1065 if (s->fLBA48)
1066 {
1067 if (!s->uATARegNSector && !s->uATARegNSectorHOB)
1068 return 65536;
1069 else
1070 return s->uATARegNSectorHOB << 8 | s->uATARegNSector;
1071 }
1072 else
1073 {
1074 if (!s->uATARegNSector)
1075 return 256;
1076 else
1077 return s->uATARegNSector;
1078 }
1079}
1080
1081
1082static void ataR3PadString(uint8_t *pbDst, const char *pbSrc, uint32_t cbSize)
1083{
1084 for (uint32_t i = 0; i < cbSize; i++)
1085 {
1086 if (*pbSrc)
1087 pbDst[i ^ 1] = *pbSrc++;
1088 else
1089 pbDst[i ^ 1] = ' ';
1090 }
1091}
1092
1093
1094static void ataR3SCSIPadStr(uint8_t *pbDst, const char *pbSrc, uint32_t cbSize)
1095{
1096 for (uint32_t i = 0; i < cbSize; i++)
1097 {
1098 if (*pbSrc)
1099 pbDst[i] = *pbSrc++;
1100 else
1101 pbDst[i] = ' ';
1102 }
1103}
1104
1105
1106DECLINLINE(void) ataH2BE_U16(uint8_t *pbBuf, uint16_t val)
1107{
1108 pbBuf[0] = val >> 8;
1109 pbBuf[1] = val;
1110}
1111
1112
1113DECLINLINE(void) ataH2BE_U24(uint8_t *pbBuf, uint32_t val)
1114{
1115 pbBuf[0] = val >> 16;
1116 pbBuf[1] = val >> 8;
1117 pbBuf[2] = val;
1118}
1119
1120
1121DECLINLINE(void) ataH2BE_U32(uint8_t *pbBuf, uint32_t val)
1122{
1123 pbBuf[0] = val >> 24;
1124 pbBuf[1] = val >> 16;
1125 pbBuf[2] = val >> 8;
1126 pbBuf[3] = val;
1127}
1128
1129
1130DECLINLINE(uint16_t) ataBE2H_U16(const uint8_t *pbBuf)
1131{
1132 return (pbBuf[0] << 8) | pbBuf[1];
1133}
1134
1135
1136DECLINLINE(uint32_t) ataBE2H_U24(const uint8_t *pbBuf)
1137{
1138 return (pbBuf[0] << 16) | (pbBuf[1] << 8) | pbBuf[2];
1139}
1140
1141
1142DECLINLINE(uint32_t) ataBE2H_U32(const uint8_t *pbBuf)
1143{
1144 return (pbBuf[0] << 24) | (pbBuf[1] << 16) | (pbBuf[2] << 8) | pbBuf[3];
1145}
1146
1147
1148DECLINLINE(void) ataLBA2MSF(uint8_t *pbBuf, uint32_t iATAPILBA)
1149{
1150 iATAPILBA += 150;
1151 pbBuf[0] = (iATAPILBA / 75) / 60;
1152 pbBuf[1] = (iATAPILBA / 75) % 60;
1153 pbBuf[2] = iATAPILBA % 75;
1154}
1155
1156
1157DECLINLINE(uint32_t) ataMSF2LBA(const uint8_t *pbBuf)
1158{
1159 return (pbBuf[0] * 60 + pbBuf[1]) * 75 + pbBuf[2];
1160}
1161
1162/**
1163 * Compares two MSF values.
1164 *
1165 * @returns 1 if the first value is greater than the second value.
1166 * 0 if both are equal
1167 * -1 if the first value is smaller than the second value.
1168 */
1169DECLINLINE(int) atapiCmpMSF(const uint8_t *pbMSF1, const uint8_t *pbMSF2)
1170{
1171 int iRes = 0;
1172
1173 for (unsigned i = 0; i < 3; i++)
1174 {
1175 if (pbMSF1[i] < pbMSF2[i])
1176 {
1177 iRes = -1;
1178 break;
1179 }
1180 else if (pbMSF1[i] > pbMSF2[i])
1181 {
1182 iRes = 1;
1183 break;
1184 }
1185 }
1186
1187 return iRes;
1188}
1189
1190static void ataR3CmdOK(ATADevState *s, uint8_t status)
1191{
1192 s->uATARegError = 0; /* Not needed by ATA spec, but cannot hurt. */
1193 ataSetStatusValue(s, ATA_STAT_READY | status);
1194}
1195
1196
1197static void ataR3CmdError(ATADevState *s, uint8_t uErrorCode)
1198{
1199 Log(("%s: code=%#x\n", __FUNCTION__, uErrorCode));
1200 Assert(uErrorCode);
1201 s->uATARegError = uErrorCode;
1202 ataSetStatusValue(s, ATA_STAT_READY | ATA_STAT_ERR);
1203 s->cbTotalTransfer = 0;
1204 s->cbElementaryTransfer = 0;
1205 s->iIOBufferCur = 0;
1206 s->iIOBufferEnd = 0;
1207 s->uTxDir = PDMBLOCKTXDIR_NONE;
1208 s->iBeginTransfer = ATAFN_BT_NULL;
1209 s->iSourceSink = ATAFN_SS_NULL;
1210}
1211
1212static uint32_t ataR3Checksum(void* ptr, size_t count)
1213{
1214 uint8_t u8Sum = 0xa5, *p = (uint8_t*)ptr;
1215 size_t i;
1216
1217 for (i = 0; i < count; i++)
1218 {
1219 u8Sum += *p++;
1220 }
1221
1222 return (uint8_t)-(int32_t)u8Sum;
1223}
1224
1225static bool ataR3IdentifySS(ATADevState *s)
1226{
1227 uint16_t *p;
1228
1229 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
1230 Assert(s->cbElementaryTransfer == 512);
1231
1232 p = (uint16_t *)s->CTX_SUFF(pbIOBuffer);
1233 memset(p, 0, 512);
1234 p[0] = RT_H2LE_U16(0x0040);
1235 p[1] = RT_H2LE_U16(RT_MIN(s->PCHSGeometry.cCylinders, 16383));
1236 p[3] = RT_H2LE_U16(s->PCHSGeometry.cHeads);
1237 /* Block size; obsolete, but required for the BIOS. */
1238 p[5] = RT_H2LE_U16(s->cbSector);
1239 p[6] = RT_H2LE_U16(s->PCHSGeometry.cSectors);
1240 ataR3PadString((uint8_t *)(p + 10), s->szSerialNumber, ATA_SERIAL_NUMBER_LENGTH); /* serial number */
1241 p[20] = RT_H2LE_U16(3); /* XXX: retired, cache type */
1242 p[21] = RT_H2LE_U16(512); /* XXX: retired, cache size in sectors */
1243 p[22] = RT_H2LE_U16(0); /* ECC bytes per sector */
1244 ataR3PadString((uint8_t *)(p + 23), s->szFirmwareRevision, ATA_FIRMWARE_REVISION_LENGTH); /* firmware version */
1245 ataR3PadString((uint8_t *)(p + 27), s->szModelNumber, ATA_MODEL_NUMBER_LENGTH); /* model */
1246# if ATA_MAX_MULT_SECTORS > 1
1247 p[47] = RT_H2LE_U16(0x8000 | ATA_MAX_MULT_SECTORS);
1248# endif
1249 p[48] = RT_H2LE_U16(1); /* dword I/O, used by the BIOS */
1250 p[49] = RT_H2LE_U16(1 << 11 | 1 << 9 | 1 << 8); /* DMA and LBA supported */
1251 p[50] = RT_H2LE_U16(1 << 14); /* No drive specific standby timer minimum */
1252 p[51] = RT_H2LE_U16(240); /* PIO transfer cycle */
1253 p[52] = RT_H2LE_U16(240); /* DMA transfer cycle */
1254 p[53] = RT_H2LE_U16(1 | 1 << 1 | 1 << 2); /* words 54-58,64-70,88 valid */
1255 p[54] = RT_H2LE_U16(RT_MIN(s->PCHSGeometry.cCylinders, 16383));
1256 p[55] = RT_H2LE_U16(s->PCHSGeometry.cHeads);
1257 p[56] = RT_H2LE_U16(s->PCHSGeometry.cSectors);
1258 p[57] = RT_H2LE_U16( RT_MIN(s->PCHSGeometry.cCylinders, 16383)
1259 * s->PCHSGeometry.cHeads
1260 * s->PCHSGeometry.cSectors);
1261 p[58] = RT_H2LE_U16( RT_MIN(s->PCHSGeometry.cCylinders, 16383)
1262 * s->PCHSGeometry.cHeads
1263 * s->PCHSGeometry.cSectors >> 16);
1264 if (s->cMultSectors)
1265 p[59] = RT_H2LE_U16(0x100 | s->cMultSectors);
1266 if (s->cTotalSectors <= (1 << 28) - 1)
1267 {
1268 p[60] = RT_H2LE_U16(s->cTotalSectors);
1269 p[61] = RT_H2LE_U16(s->cTotalSectors >> 16);
1270 }
1271 else
1272 {
1273 /* Report maximum number of sectors possible with LBA28 */
1274 p[60] = RT_H2LE_U16(((1 << 28) - 1) & 0xffff);
1275 p[61] = RT_H2LE_U16(((1 << 28) - 1) >> 16);
1276 }
1277 p[63] = RT_H2LE_U16(ATA_TRANSFER_ID(ATA_MODE_MDMA, ATA_MDMA_MODE_MAX, s->uATATransferMode)); /* MDMA modes supported / mode enabled */
1278 p[64] = RT_H2LE_U16(ATA_PIO_MODE_MAX > 2 ? (1 << (ATA_PIO_MODE_MAX - 2)) - 1 : 0); /* PIO modes beyond PIO2 supported */
1279 p[65] = RT_H2LE_U16(120); /* minimum DMA multiword tx cycle time */
1280 p[66] = RT_H2LE_U16(120); /* recommended DMA multiword tx cycle time */
1281 p[67] = RT_H2LE_U16(120); /* minimum PIO cycle time without flow control */
1282 p[68] = RT_H2LE_U16(120); /* minimum PIO cycle time with IORDY flow control */
1283 if ( s->pDrvBlock->pfnDiscard
1284 || s->cbSector != 512
1285 || s->fNonRotational)
1286 {
1287 p[80] = RT_H2LE_U16(0x1f0); /* support everything up to ATA/ATAPI-8 ACS */
1288 p[81] = RT_H2LE_U16(0x28); /* conforms to ATA/ATAPI-8 ACS */
1289 }
1290 else
1291 {
1292 p[80] = RT_H2LE_U16(0x7e); /* support everything up to ATA/ATAPI-6 */
1293 p[81] = RT_H2LE_U16(0x22); /* conforms to ATA/ATAPI-6 */
1294 }
1295 p[82] = RT_H2LE_U16(1 << 3 | 1 << 5 | 1 << 6); /* supports power management, write cache and look-ahead */
1296 if (s->cTotalSectors <= (1 << 28) - 1)
1297 p[83] = RT_H2LE_U16(1 << 14 | 1 << 12); /* supports FLUSH CACHE */
1298 else
1299 p[83] = RT_H2LE_U16(1 << 14 | 1 << 10 | 1 << 12 | 1 << 13); /* supports LBA48, FLUSH CACHE and FLUSH CACHE EXT */
1300 p[84] = RT_H2LE_U16(1 << 14);
1301 p[85] = RT_H2LE_U16(1 << 3 | 1 << 5 | 1 << 6); /* enabled power management, write cache and look-ahead */
1302 if (s->cTotalSectors <= (1 << 28) - 1)
1303 p[86] = RT_H2LE_U16(1 << 12); /* enabled FLUSH CACHE */
1304 else
1305 p[86] = RT_H2LE_U16(1 << 10 | 1 << 12 | 1 << 13); /* enabled LBA48, FLUSH CACHE and FLUSH CACHE EXT */
1306 p[87] = RT_H2LE_U16(1 << 14);
1307 p[88] = RT_H2LE_U16(ATA_TRANSFER_ID(ATA_MODE_UDMA, ATA_UDMA_MODE_MAX, s->uATATransferMode)); /* UDMA modes supported / mode enabled */
1308 p[93] = RT_H2LE_U16((1 | 1 << 1) << ((s->iLUN & 1) == 0 ? 0 : 8) | 1 << 13 | 1 << 14);
1309 if (s->cTotalSectors > (1 << 28) - 1)
1310 {
1311 p[100] = RT_H2LE_U16(s->cTotalSectors);
1312 p[101] = RT_H2LE_U16(s->cTotalSectors >> 16);
1313 p[102] = RT_H2LE_U16(s->cTotalSectors >> 32);
1314 p[103] = RT_H2LE_U16(s->cTotalSectors >> 48);
1315 }
1316
1317 if (s->cbSector != 512)
1318 {
1319 uint32_t cSectorSizeInWords = s->cbSector / sizeof(uint16_t);
1320 /* Enable reporting of logical sector size. */
1321 p[106] |= RT_H2LE_U16(RT_BIT(12) | RT_BIT(14));
1322 p[117] = RT_H2LE_U16(cSectorSizeInWords);
1323 p[118] = RT_H2LE_U16(cSectorSizeInWords >> 16);
1324 }
1325
1326 if (s->pDrvBlock->pfnDiscard) /** @todo: Set bit 14 in word 69 too? (Deterministic read after TRIM). */
1327 p[169] = RT_H2LE_U16(1); /* DATA SET MANAGEMENT command supported. */
1328 if (s->fNonRotational)
1329 p[217] = RT_H2LE_U16(1); /* Non-rotational medium */
1330 uint32_t uCsum = ataR3Checksum(p, 510);
1331 p[255] = RT_H2LE_U16(0xa5 | (uCsum << 8)); /* Integrity word */
1332 s->iSourceSink = ATAFN_SS_NULL;
1333 ataR3CmdOK(s, ATA_STAT_SEEK);
1334 return false;
1335}
1336
1337
1338static bool ataR3FlushSS(ATADevState *s)
1339{
1340 PATACONTROLLER pCtl = ATADEVSTATE_2_CONTROLLER(s);
1341 int rc;
1342
1343 Assert(s->uTxDir == PDMBLOCKTXDIR_NONE);
1344 Assert(!s->cbElementaryTransfer);
1345
1346 PDMCritSectLeave(&pCtl->lock);
1347
1348 STAM_PROFILE_START(&s->StatFlushes, f);
1349 rc = s->pDrvBlock->pfnFlush(s->pDrvBlock);
1350 AssertRC(rc);
1351 STAM_PROFILE_STOP(&s->StatFlushes, f);
1352
1353 STAM_PROFILE_START(&pCtl->StatLockWait, a);
1354 PDMCritSectEnter(&pCtl->lock, VINF_SUCCESS);
1355 STAM_PROFILE_STOP(&pCtl->StatLockWait, a);
1356 ataR3CmdOK(s, 0);
1357 return false;
1358}
1359
1360static bool atapiR3IdentifySS(ATADevState *s)
1361{
1362 uint16_t *p;
1363
1364 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
1365 Assert(s->cbElementaryTransfer == 512);
1366
1367 p = (uint16_t *)s->CTX_SUFF(pbIOBuffer);
1368 memset(p, 0, 512);
1369 /* Removable CDROM, 3ms response, 12 byte packets */
1370 p[0] = RT_H2LE_U16(2 << 14 | 5 << 8 | 1 << 7 | 0 << 5 | 0 << 0);
1371 ataR3PadString((uint8_t *)(p + 10), s->szSerialNumber, ATA_SERIAL_NUMBER_LENGTH); /* serial number */
1372 p[20] = RT_H2LE_U16(3); /* XXX: retired, cache type */
1373 p[21] = RT_H2LE_U16(512); /* XXX: retired, cache size in sectors */
1374 ataR3PadString((uint8_t *)(p + 23), s->szFirmwareRevision, ATA_FIRMWARE_REVISION_LENGTH); /* firmware version */
1375 ataR3PadString((uint8_t *)(p + 27), s->szModelNumber, ATA_MODEL_NUMBER_LENGTH); /* model */
1376 p[49] = RT_H2LE_U16(1 << 11 | 1 << 9 | 1 << 8); /* DMA and LBA supported */
1377 p[50] = RT_H2LE_U16(1 << 14); /* No drive specific standby timer minimum */
1378 p[51] = RT_H2LE_U16(240); /* PIO transfer cycle */
1379 p[52] = RT_H2LE_U16(240); /* DMA transfer cycle */
1380 p[53] = RT_H2LE_U16(1 << 1 | 1 << 2); /* words 64-70,88 are valid */
1381 p[63] = RT_H2LE_U16(ATA_TRANSFER_ID(ATA_MODE_MDMA, ATA_MDMA_MODE_MAX, s->uATATransferMode)); /* MDMA modes supported / mode enabled */
1382 p[64] = RT_H2LE_U16(ATA_PIO_MODE_MAX > 2 ? (1 << (ATA_PIO_MODE_MAX - 2)) - 1 : 0); /* PIO modes beyond PIO2 supported */
1383 p[65] = RT_H2LE_U16(120); /* minimum DMA multiword tx cycle time */
1384 p[66] = RT_H2LE_U16(120); /* recommended DMA multiword tx cycle time */
1385 p[67] = RT_H2LE_U16(120); /* minimum PIO cycle time without flow control */
1386 p[68] = RT_H2LE_U16(120); /* minimum PIO cycle time with IORDY flow control */
1387 p[73] = RT_H2LE_U16(0x003e); /* ATAPI CDROM major */
1388 p[74] = RT_H2LE_U16(9); /* ATAPI CDROM minor */
1389 p[75] = RT_H2LE_U16(1); /* queue depth 1 */
1390 p[80] = RT_H2LE_U16(0x7e); /* support everything up to ATA/ATAPI-6 */
1391 p[81] = RT_H2LE_U16(0x22); /* conforms to ATA/ATAPI-6 */
1392 p[82] = RT_H2LE_U16(1 << 4 | 1 << 9); /* supports packet command set and DEVICE RESET */
1393 p[83] = RT_H2LE_U16(1 << 14);
1394 p[84] = RT_H2LE_U16(1 << 14);
1395 p[85] = RT_H2LE_U16(1 << 4 | 1 << 9); /* enabled packet command set and DEVICE RESET */
1396 p[86] = RT_H2LE_U16(0);
1397 p[87] = RT_H2LE_U16(1 << 14);
1398 p[88] = RT_H2LE_U16(ATA_TRANSFER_ID(ATA_MODE_UDMA, ATA_UDMA_MODE_MAX, s->uATATransferMode)); /* UDMA modes supported / mode enabled */
1399 p[93] = RT_H2LE_U16((1 | 1 << 1) << ((s->iLUN & 1) == 0 ? 0 : 8) | 1 << 13 | 1 << 14);
1400 /* According to ATAPI-5 spec:
1401 *
1402 * The use of this word is optional.
1403 * If bits 7:0 of this word contain the signature A5h, bits 15:8
1404 * contain the data
1405 * structure checksum.
1406 * The data structure checksum is the twos complement of the sum of
1407 * all bytes in words 0 through 254 and the byte consisting of
1408 * bits 7:0 in word 255.
1409 * Each byte shall be added with unsigned arithmetic,
1410 * and overflow shall be ignored.
1411 * The sum of all 512 bytes is zero when the checksum is correct.
1412 */
1413 uint32_t uCsum = ataR3Checksum(p, 510);
1414 p[255] = RT_H2LE_U16(0xa5 | (uCsum << 8)); /* Integrity word */
1415
1416 s->iSourceSink = ATAFN_SS_NULL;
1417 ataR3CmdOK(s, ATA_STAT_SEEK);
1418 return false;
1419}
1420
1421
1422static void ataR3SetSignature(ATADevState *s)
1423{
1424 s->uATARegSelect &= 0xf0; /* clear head */
1425 /* put signature */
1426 s->uATARegNSector = 1;
1427 s->uATARegSector = 1;
1428 if (s->fATAPI)
1429 {
1430 s->uATARegLCyl = 0x14;
1431 s->uATARegHCyl = 0xeb;
1432 }
1433 else if (s->pDrvBlock)
1434 {
1435 s->uATARegLCyl = 0;
1436 s->uATARegHCyl = 0;
1437 }
1438 else
1439 {
1440 s->uATARegLCyl = 0xff;
1441 s->uATARegHCyl = 0xff;
1442 }
1443}
1444
1445
1446static uint64_t ataR3GetSector(ATADevState *s)
1447{
1448 uint64_t iLBA;
1449 if (s->uATARegSelect & 0x40)
1450 {
1451 /* any LBA variant */
1452 if (s->fLBA48)
1453 {
1454 /* LBA48 */
1455 iLBA = ((uint64_t)s->uATARegHCylHOB << 40) |
1456 ((uint64_t)s->uATARegLCylHOB << 32) |
1457 ((uint64_t)s->uATARegSectorHOB << 24) |
1458 ((uint64_t)s->uATARegHCyl << 16) |
1459 ((uint64_t)s->uATARegLCyl << 8) |
1460 s->uATARegSector;
1461 }
1462 else
1463 {
1464 /* LBA */
1465 iLBA = ((s->uATARegSelect & 0x0f) << 24) | (s->uATARegHCyl << 16) |
1466 (s->uATARegLCyl << 8) | s->uATARegSector;
1467 }
1468 }
1469 else
1470 {
1471 /* CHS */
1472 iLBA = ((s->uATARegHCyl << 8) | s->uATARegLCyl) * s->PCHSGeometry.cHeads * s->PCHSGeometry.cSectors +
1473 (s->uATARegSelect & 0x0f) * s->PCHSGeometry.cSectors +
1474 (s->uATARegSector - 1);
1475 }
1476 return iLBA;
1477}
1478
1479static void ataR3SetSector(ATADevState *s, uint64_t iLBA)
1480{
1481 uint32_t cyl, r;
1482 if (s->uATARegSelect & 0x40)
1483 {
1484 /* any LBA variant */
1485 if (s->fLBA48)
1486 {
1487 /* LBA48 */
1488 s->uATARegHCylHOB = iLBA >> 40;
1489 s->uATARegLCylHOB = iLBA >> 32;
1490 s->uATARegSectorHOB = iLBA >> 24;
1491 s->uATARegHCyl = iLBA >> 16;
1492 s->uATARegLCyl = iLBA >> 8;
1493 s->uATARegSector = iLBA;
1494 }
1495 else
1496 {
1497 /* LBA */
1498 s->uATARegSelect = (s->uATARegSelect & 0xf0) | (iLBA >> 24);
1499 s->uATARegHCyl = (iLBA >> 16);
1500 s->uATARegLCyl = (iLBA >> 8);
1501 s->uATARegSector = (iLBA);
1502 }
1503 }
1504 else
1505 {
1506 /* CHS */
1507 cyl = iLBA / (s->PCHSGeometry.cHeads * s->PCHSGeometry.cSectors);
1508 r = iLBA % (s->PCHSGeometry.cHeads * s->PCHSGeometry.cSectors);
1509 s->uATARegHCyl = cyl >> 8;
1510 s->uATARegLCyl = cyl;
1511 s->uATARegSelect = (s->uATARegSelect & 0xf0) | ((r / s->PCHSGeometry.cSectors) & 0x0f);
1512 s->uATARegSector = (r % s->PCHSGeometry.cSectors) + 1;
1513 }
1514}
1515
1516
1517static void ataR3WarningDiskFull(PPDMDEVINS pDevIns)
1518{
1519 int rc;
1520 LogRel(("PIIX3 ATA: Host disk full\n"));
1521 rc = PDMDevHlpVMSetRuntimeError(pDevIns, VMSETRTERR_FLAGS_SUSPEND | VMSETRTERR_FLAGS_NO_WAIT, "DevATA_DISKFULL",
1522 N_("Host system reported disk full. VM execution is suspended. You can resume after freeing some space"));
1523 AssertRC(rc);
1524}
1525
1526static void ataR3WarningFileTooBig(PPDMDEVINS pDevIns)
1527{
1528 int rc;
1529 LogRel(("PIIX3 ATA: File too big\n"));
1530 rc = PDMDevHlpVMSetRuntimeError(pDevIns, VMSETRTERR_FLAGS_SUSPEND | VMSETRTERR_FLAGS_NO_WAIT, "DevATA_FILETOOBIG",
1531 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"));
1532 AssertRC(rc);
1533}
1534
1535static void ataR3WarningISCSI(PPDMDEVINS pDevIns)
1536{
1537 int rc;
1538 LogRel(("PIIX3 ATA: iSCSI target unavailable\n"));
1539 rc = PDMDevHlpVMSetRuntimeError(pDevIns, VMSETRTERR_FLAGS_SUSPEND | VMSETRTERR_FLAGS_NO_WAIT, "DevATA_ISCSIDOWN",
1540 N_("The iSCSI target has stopped responding. VM execution is suspended. You can resume when it is available again"));
1541 AssertRC(rc);
1542}
1543
1544static bool ataR3IsRedoSetWarning(ATADevState *s, int rc)
1545{
1546 PATACONTROLLER pCtl = ATADEVSTATE_2_CONTROLLER(s);
1547 Assert(!PDMCritSectIsOwner(&pCtl->lock));
1548 if (rc == VERR_DISK_FULL)
1549 {
1550 pCtl->fRedoIdle = true;
1551 ataR3WarningDiskFull(ATADEVSTATE_2_DEVINS(s));
1552 return true;
1553 }
1554 if (rc == VERR_FILE_TOO_BIG)
1555 {
1556 pCtl->fRedoIdle = true;
1557 ataR3WarningFileTooBig(ATADEVSTATE_2_DEVINS(s));
1558 return true;
1559 }
1560 if (rc == VERR_BROKEN_PIPE || rc == VERR_NET_CONNECTION_REFUSED)
1561 {
1562 pCtl->fRedoIdle = true;
1563 /* iSCSI connection abort (first error) or failure to reestablish
1564 * connection (second error). Pause VM. On resume we'll retry. */
1565 ataR3WarningISCSI(ATADEVSTATE_2_DEVINS(s));
1566 return true;
1567 }
1568 if (rc == VERR_VD_DEK_MISSING)
1569 {
1570 /* Error message already set. */
1571 pCtl->fRedoIdle = true;
1572 return true;
1573 }
1574
1575 return false;
1576}
1577
1578
1579static int ataR3ReadSectors(ATADevState *s, uint64_t u64Sector, void *pvBuf,
1580 uint32_t cSectors, bool *pfRedo)
1581{
1582 PATACONTROLLER pCtl = ATADEVSTATE_2_CONTROLLER(s);
1583 int rc;
1584
1585 PDMCritSectLeave(&pCtl->lock);
1586
1587 STAM_PROFILE_ADV_START(&s->StatReads, r);
1588 s->Led.Asserted.s.fReading = s->Led.Actual.s.fReading = 1;
1589 rc = s->pDrvBlock->pfnRead(s->pDrvBlock, u64Sector * s->cbSector, pvBuf, cSectors * s->cbSector);
1590 s->Led.Actual.s.fReading = 0;
1591 STAM_PROFILE_ADV_STOP(&s->StatReads, r);
1592 Log4(("ataR3ReadSectors: rc=%Rrc cSectors=%#x u64Sector=%llu\n%.*Rhxd\n",
1593 rc, cSectors, u64Sector, cSectors * s->cbSector, pvBuf));
1594
1595 STAM_REL_COUNTER_ADD(&s->StatBytesRead, cSectors * s->cbSector);
1596
1597 if (RT_SUCCESS(rc))
1598 *pfRedo = false;
1599 else
1600 *pfRedo = ataR3IsRedoSetWarning(s, rc);
1601
1602 STAM_PROFILE_START(&pCtl->StatLockWait, a);
1603 PDMCritSectEnter(&pCtl->lock, VINF_SUCCESS);
1604 STAM_PROFILE_STOP(&pCtl->StatLockWait, a);
1605 return rc;
1606}
1607
1608
1609static int ataR3WriteSectors(ATADevState *s, uint64_t u64Sector,
1610 const void *pvBuf, uint32_t cSectors, bool *pfRedo)
1611{
1612 PATACONTROLLER pCtl = ATADEVSTATE_2_CONTROLLER(s);
1613 int rc;
1614
1615 PDMCritSectLeave(&pCtl->lock);
1616
1617 STAM_PROFILE_ADV_START(&s->StatWrites, w);
1618 s->Led.Asserted.s.fWriting = s->Led.Actual.s.fWriting = 1;
1619# ifdef VBOX_INSTRUMENT_DMA_WRITES
1620 if (s->fDMA)
1621 STAM_PROFILE_ADV_START(&s->StatInstrVDWrites, vw);
1622# endif
1623 rc = s->pDrvBlock->pfnWrite(s->pDrvBlock, u64Sector * s->cbSector, pvBuf, cSectors * s->cbSector);
1624# ifdef VBOX_INSTRUMENT_DMA_WRITES
1625 if (s->fDMA)
1626 STAM_PROFILE_ADV_STOP(&s->StatInstrVDWrites, vw);
1627# endif
1628 s->Led.Actual.s.fWriting = 0;
1629 STAM_PROFILE_ADV_STOP(&s->StatWrites, w);
1630 Log4(("ataR3WriteSectors: rc=%Rrc cSectors=%#x u64Sector=%llu\n%.*Rhxd\n",
1631 rc, cSectors, u64Sector, cSectors * s->cbSector, pvBuf));
1632
1633 STAM_REL_COUNTER_ADD(&s->StatBytesWritten, cSectors * s->cbSector);
1634
1635 if (RT_SUCCESS(rc))
1636 *pfRedo = false;
1637 else
1638 *pfRedo = ataR3IsRedoSetWarning(s, rc);
1639
1640 STAM_PROFILE_START(&pCtl->StatLockWait, a);
1641 PDMCritSectEnter(&pCtl->lock, VINF_SUCCESS);
1642 STAM_PROFILE_STOP(&pCtl->StatLockWait, a);
1643 return rc;
1644}
1645
1646
1647static void ataR3ReadWriteSectorsBT(ATADevState *s)
1648{
1649 uint32_t cSectors;
1650
1651 cSectors = s->cbTotalTransfer / s->cbSector;
1652 if (cSectors > s->cSectorsPerIRQ)
1653 s->cbElementaryTransfer = s->cSectorsPerIRQ * s->cbSector;
1654 else
1655 s->cbElementaryTransfer = cSectors * s->cbSector;
1656 if (s->uTxDir == PDMBLOCKTXDIR_TO_DEVICE)
1657 ataR3CmdOK(s, 0);
1658}
1659
1660
1661static bool ataR3ReadSectorsSS(ATADevState *s)
1662{
1663 int rc;
1664 uint32_t cSectors;
1665 uint64_t iLBA;
1666 bool fRedo;
1667
1668 cSectors = s->cbElementaryTransfer / s->cbSector;
1669 Assert(cSectors);
1670 iLBA = ataR3GetSector(s);
1671 Log(("%s: %d sectors at LBA %d\n", __FUNCTION__, cSectors, iLBA));
1672 rc = ataR3ReadSectors(s, iLBA, s->CTX_SUFF(pbIOBuffer), cSectors, &fRedo);
1673 if (RT_SUCCESS(rc))
1674 {
1675 ataR3SetSector(s, iLBA + cSectors);
1676 if (s->cbElementaryTransfer == s->cbTotalTransfer)
1677 s->iSourceSink = ATAFN_SS_NULL;
1678 ataR3CmdOK(s, ATA_STAT_SEEK);
1679 }
1680 else
1681 {
1682 if (fRedo)
1683 return fRedo;
1684 if (s->cErrors++ < MAX_LOG_REL_ERRORS)
1685 LogRel(("PIIX3 ATA: LUN#%d: disk read error (rc=%Rrc iSector=%#RX64 cSectors=%#RX32)\n",
1686 s->iLUN, rc, iLBA, cSectors));
1687
1688 /*
1689 * Check if we got interrupted. We don't need to set status variables
1690 * because the request was aborted.
1691 */
1692 if (rc != VERR_INTERRUPTED)
1693 ataR3CmdError(s, ID_ERR);
1694 }
1695 return false;
1696}
1697
1698
1699static bool ataR3WriteSectorsSS(ATADevState *s)
1700{
1701 int rc;
1702 uint32_t cSectors;
1703 uint64_t iLBA;
1704 bool fRedo;
1705
1706 cSectors = s->cbElementaryTransfer / s->cbSector;
1707 Assert(cSectors);
1708 iLBA = ataR3GetSector(s);
1709 Log(("%s: %d sectors at LBA %d\n", __FUNCTION__, cSectors, iLBA));
1710 rc = ataR3WriteSectors(s, iLBA, s->CTX_SUFF(pbIOBuffer), cSectors, &fRedo);
1711 if (RT_SUCCESS(rc))
1712 {
1713 ataR3SetSector(s, iLBA + cSectors);
1714 if (!s->cbTotalTransfer)
1715 s->iSourceSink = ATAFN_SS_NULL;
1716 ataR3CmdOK(s, ATA_STAT_SEEK);
1717 }
1718 else
1719 {
1720 if (fRedo)
1721 return fRedo;
1722 if (s->cErrors++ < MAX_LOG_REL_ERRORS)
1723 LogRel(("PIIX3 ATA: LUN#%d: disk write error (rc=%Rrc iSector=%#RX64 cSectors=%#RX32)\n",
1724 s->iLUN, rc, iLBA, cSectors));
1725
1726 /*
1727 * Check if we got interrupted. We don't need to set status variables
1728 * because the request was aborted.
1729 */
1730 if (rc != VERR_INTERRUPTED)
1731 ataR3CmdError(s, ID_ERR);
1732 }
1733 return false;
1734}
1735
1736
1737static void atapiR3CmdOK(ATADevState *s)
1738{
1739 s->uATARegError = 0;
1740 ataSetStatusValue(s, ATA_STAT_READY);
1741 s->uATARegNSector = (s->uATARegNSector & ~7)
1742 | ((s->uTxDir != PDMBLOCKTXDIR_TO_DEVICE) ? ATAPI_INT_REASON_IO : 0)
1743 | (!s->cbTotalTransfer ? ATAPI_INT_REASON_CD : 0);
1744 Log2(("%s: interrupt reason %#04x\n", __FUNCTION__, s->uATARegNSector));
1745
1746 memset(s->abATAPISense, '\0', sizeof(s->abATAPISense));
1747 s->abATAPISense[0] = 0x70 | (1 << 7);
1748 s->abATAPISense[7] = 10;
1749}
1750
1751
1752static void atapiR3CmdError(ATADevState *s, const uint8_t *pabATAPISense, size_t cbATAPISense)
1753{
1754 Log(("%s: sense=%#x (%s) asc=%#x ascq=%#x (%s)\n", __FUNCTION__, pabATAPISense[2] & 0x0f, SCSISenseText(pabATAPISense[2] & 0x0f),
1755 pabATAPISense[12], pabATAPISense[13], SCSISenseExtText(pabATAPISense[12], pabATAPISense[13])));
1756 s->uATARegError = pabATAPISense[2] << 4;
1757 ataSetStatusValue(s, ATA_STAT_READY | ATA_STAT_ERR);
1758 s->uATARegNSector = (s->uATARegNSector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
1759 Log2(("%s: interrupt reason %#04x\n", __FUNCTION__, s->uATARegNSector));
1760 memset(s->abATAPISense, '\0', sizeof(s->abATAPISense));
1761 memcpy(s->abATAPISense, pabATAPISense, RT_MIN(cbATAPISense, sizeof(s->abATAPISense)));
1762 s->cbTotalTransfer = 0;
1763 s->cbElementaryTransfer = 0;
1764 s->cbAtapiPassthroughTransfer = 0;
1765 s->iIOBufferCur = 0;
1766 s->iIOBufferEnd = 0;
1767 s->uTxDir = PDMBLOCKTXDIR_NONE;
1768 s->iBeginTransfer = ATAFN_BT_NULL;
1769 s->iSourceSink = ATAFN_SS_NULL;
1770}
1771
1772
1773/** @todo deprecated function - doesn't provide enough info. Replace by direct
1774 * calls to atapiR3CmdError() with full data. */
1775static void atapiR3CmdErrorSimple(ATADevState *s, uint8_t uATAPISenseKey, uint8_t uATAPIASC)
1776{
1777 uint8_t abATAPISense[ATAPI_SENSE_SIZE];
1778 memset(abATAPISense, '\0', sizeof(abATAPISense));
1779 abATAPISense[0] = 0x70 | (1 << 7);
1780 abATAPISense[2] = uATAPISenseKey & 0x0f;
1781 abATAPISense[7] = 10;
1782 abATAPISense[12] = uATAPIASC;
1783 atapiR3CmdError(s, abATAPISense, sizeof(abATAPISense));
1784}
1785
1786
1787static void atapiR3CmdBT(ATADevState *s)
1788{
1789 s->fATAPITransfer = true;
1790 s->cbElementaryTransfer = s->cbTotalTransfer;
1791 s->cbAtapiPassthroughTransfer = s->cbTotalTransfer;
1792 s->cbPIOTransferLimit = s->uATARegLCyl | (s->uATARegHCyl << 8);
1793 if (s->uTxDir == PDMBLOCKTXDIR_TO_DEVICE)
1794 atapiR3CmdOK(s);
1795}
1796
1797
1798static void atapiR3PassthroughCmdBT(ATADevState *s)
1799{
1800 /** @todo implement an algorithm for correctly determining the read and
1801 * write sector size without sending additional commands to the drive.
1802 * This should be doable by saving processing the configuration requests
1803 * and replies. */
1804# if 0
1805 if (s->uTxDir == PDMBLOCKTXDIR_TO_DEVICE)
1806 {
1807 uint8_t cmd = s->aATAPICmd[0];
1808 if (cmd == SCSI_WRITE_10 || cmd == SCSI_WRITE_12 || cmd == SCSI_WRITE_AND_VERIFY_10)
1809 {
1810 uint8_t aModeSenseCmd[10];
1811 uint8_t aModeSenseResult[16];
1812 uint8_t uDummySense;
1813 uint32_t cbTransfer;
1814 int rc;
1815
1816 cbTransfer = sizeof(aModeSenseResult);
1817 aModeSenseCmd[0] = SCSI_MODE_SENSE_10;
1818 aModeSenseCmd[1] = 0x08; /* disable block descriptor = 1 */
1819 aModeSenseCmd[2] = (SCSI_PAGECONTROL_CURRENT << 6) | SCSI_MODEPAGE_WRITE_PARAMETER;
1820 aModeSenseCmd[3] = 0; /* subpage code */
1821 aModeSenseCmd[4] = 0; /* reserved */
1822 aModeSenseCmd[5] = 0; /* reserved */
1823 aModeSenseCmd[6] = 0; /* reserved */
1824 aModeSenseCmd[7] = cbTransfer >> 8;
1825 aModeSenseCmd[8] = cbTransfer & 0xff;
1826 aModeSenseCmd[9] = 0; /* control */
1827 rc = s->pDrvBlock->pfnSendCmd(s->pDrvBlock, aModeSenseCmd, PDMBLOCKTXDIR_FROM_DEVICE, aModeSenseResult, &cbTransfer, &uDummySense, 500);
1828 if (RT_FAILURE(rc))
1829 {
1830 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_NONE);
1831 return;
1832 }
1833 /* Select sector size based on the current data block type. */
1834 switch (aModeSenseResult[12] & 0x0f)
1835 {
1836 case 0:
1837 s->cbATAPISector = 2352;
1838 break;
1839 case 1:
1840 s->cbATAPISector = 2368;
1841 break;
1842 case 2:
1843 case 3:
1844 s->cbATAPISector = 2448;
1845 break;
1846 case 8:
1847 case 10:
1848 s->cbATAPISector = 2048;
1849 break;
1850 case 9:
1851 s->cbATAPISector = 2336;
1852 break;
1853 case 11:
1854 s->cbATAPISector = 2056;
1855 break;
1856 case 12:
1857 s->cbATAPISector = 2324;
1858 break;
1859 case 13:
1860 s->cbATAPISector = 2332;
1861 break;
1862 default:
1863 s->cbATAPISector = 0;
1864 }
1865 Log2(("%s: sector size %d\n", __FUNCTION__, s->cbATAPISector));
1866 s->cbTotalTransfer *= s->cbATAPISector;
1867 if (s->cbTotalTransfer == 0)
1868 s->uTxDir = PDMBLOCKTXDIR_NONE;
1869 }
1870 }
1871# endif
1872 atapiR3CmdBT(s);
1873}
1874
1875static bool atapiR3ReadSS(ATADevState *s)
1876{
1877 PATACONTROLLER pCtl = ATADEVSTATE_2_CONTROLLER(s);
1878 int rc = VINF_SUCCESS;
1879 uint32_t cbTransfer, cSectors;
1880
1881 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
1882 cbTransfer = RT_MIN(s->cbTotalTransfer, s->cbIOBuffer);
1883 cSectors = cbTransfer / s->cbATAPISector;
1884 Assert(cSectors * s->cbATAPISector <= cbTransfer);
1885 Log(("%s: %d sectors at LBA %d\n", __FUNCTION__, cSectors, s->iATAPILBA));
1886
1887 PDMCritSectLeave(&pCtl->lock);
1888
1889 STAM_PROFILE_ADV_START(&s->StatReads, r);
1890 s->Led.Asserted.s.fReading = s->Led.Actual.s.fReading = 1;
1891 switch (s->cbATAPISector)
1892 {
1893 case 2048:
1894 rc = s->pDrvBlock->pfnRead(s->pDrvBlock, (uint64_t)s->iATAPILBA * s->cbATAPISector, s->CTX_SUFF(pbIOBuffer), s->cbATAPISector * cSectors);
1895 break;
1896 case 2352:
1897 {
1898 uint8_t *pbBuf = s->CTX_SUFF(pbIOBuffer);
1899
1900 for (uint32_t i = s->iATAPILBA; i < s->iATAPILBA + cSectors; i++)
1901 {
1902 /* Sync bytes, see 4.2.3.8 CD Main Channel Block Formats */
1903 *pbBuf++ = 0x00;
1904 memset(pbBuf, 0xff, 10);
1905 pbBuf += 10;
1906 *pbBuf++ = 0x00;
1907 /* MSF */
1908 ataLBA2MSF(pbBuf, i);
1909 pbBuf += 3;
1910 *pbBuf++ = 0x01; /* mode 1 data */
1911 /* data */
1912 rc = s->pDrvBlock->pfnRead(s->pDrvBlock, (uint64_t)i * 2048, pbBuf, 2048);
1913 if (RT_FAILURE(rc))
1914 break;
1915 pbBuf += 2048;
1916 /**
1917 * @todo: maybe compute ECC and parity, layout is:
1918 * 2072 4 EDC
1919 * 2076 172 P parity symbols
1920 * 2248 104 Q parity symbols
1921 */
1922 memset(pbBuf, 0, 280);
1923 pbBuf += 280;
1924 }
1925 break;
1926 }
1927 default:
1928 break;
1929 }
1930 s->Led.Actual.s.fReading = 0;
1931 STAM_PROFILE_ADV_STOP(&s->StatReads, r);
1932
1933 STAM_PROFILE_START(&pCtl->StatLockWait, a);
1934 PDMCritSectEnter(&pCtl->lock, VINF_SUCCESS);
1935 STAM_PROFILE_STOP(&pCtl->StatLockWait, a);
1936
1937 if (RT_SUCCESS(rc))
1938 {
1939 STAM_REL_COUNTER_ADD(&s->StatBytesRead, s->cbATAPISector * cSectors);
1940
1941 /* The initial buffer end value has been set up based on the total
1942 * transfer size. But the I/O buffer size limits what can actually be
1943 * done in one transfer, so set the actual value of the buffer end. */
1944 s->cbElementaryTransfer = cbTransfer;
1945 if (cbTransfer >= s->cbTotalTransfer)
1946 s->iSourceSink = ATAFN_SS_NULL;
1947 atapiR3CmdOK(s);
1948 s->iATAPILBA += cSectors;
1949 }
1950 else
1951 {
1952 if (s->cErrors++ < MAX_LOG_REL_ERRORS)
1953 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM read error, %d sectors at LBA %d\n", s->iLUN, cSectors, s->iATAPILBA));
1954
1955 /*
1956 * Check if we got interrupted. We don't need to set status variables
1957 * because the request was aborted.
1958 */
1959 if (rc != VERR_INTERRUPTED)
1960 atapiR3CmdErrorSimple(s, SCSI_SENSE_MEDIUM_ERROR, SCSI_ASC_READ_ERROR);
1961 }
1962 return false;
1963}
1964
1965/**
1966 * Sets the given media track type.
1967 */
1968static uint32_t ataR3MediumTypeSet(ATADevState *s, uint32_t MediaTrackType)
1969{
1970 return ASMAtomicXchgU32(&s->MediaTrackType, MediaTrackType);
1971}
1972
1973static bool atapiR3PassthroughSS(ATADevState *s)
1974{
1975 PATACONTROLLER pCtl = ATADEVSTATE_2_CONTROLLER(s);
1976 int rc = VINF_SUCCESS;
1977 uint8_t abATAPISense[ATAPI_SENSE_SIZE];
1978 uint32_t cbTransfer;
1979 PSTAMPROFILEADV pProf = NULL;
1980
1981 cbTransfer = RT_MIN(s->cbAtapiPassthroughTransfer, s->cbIOBuffer);
1982
1983 if (s->uTxDir == PDMBLOCKTXDIR_TO_DEVICE)
1984 Log3(("ATAPI PT data write (%d): %.*Rhxs\n", cbTransfer, cbTransfer, s->CTX_SUFF(pbIOBuffer)));
1985
1986 /* Simple heuristics: if there is at least one sector of data
1987 * to transfer, it's worth updating the LEDs. */
1988 if (cbTransfer >= 2048)
1989 {
1990 if (s->uTxDir != PDMBLOCKTXDIR_TO_DEVICE)
1991 {
1992 s->Led.Asserted.s.fReading = s->Led.Actual.s.fReading = 1;
1993 pProf = &s->StatReads;
1994 }
1995 else
1996 {
1997 s->Led.Asserted.s.fWriting = s->Led.Actual.s.fWriting = 1;
1998 pProf = &s->StatWrites;
1999 }
2000 }
2001
2002 PDMCritSectLeave(&pCtl->lock);
2003
2004# if defined(LOG_ENABLED)
2005 char szBuf[1024];
2006
2007 memset(szBuf, 0, sizeof(szBuf));
2008
2009 switch (s->aATAPICmd[0])
2010 {
2011 case SCSI_MODE_SELECT_10:
2012 {
2013 size_t cbBlkDescLength = ataBE2H_U16(&s->CTX_SUFF(pbIOBuffer)[6]);
2014
2015 SCSILogModePage(szBuf, sizeof(szBuf) - 1,
2016 s->CTX_SUFF(pbIOBuffer) + 8 + cbBlkDescLength,
2017 cbTransfer - 8 - cbBlkDescLength);
2018 break;
2019 }
2020 case SCSI_SEND_CUE_SHEET:
2021 {
2022 SCSILogCueSheet(szBuf, sizeof(szBuf) - 1,
2023 s->CTX_SUFF(pbIOBuffer), cbTransfer);
2024 break;
2025 }
2026 default:
2027 break;
2028 }
2029
2030 Log2(("%s\n", szBuf));
2031# endif
2032
2033 if (pProf) { STAM_PROFILE_ADV_START(pProf, b); }
2034 if ( cbTransfer > SCSI_MAX_BUFFER_SIZE
2035 || s->cbElementaryTransfer > s->cbIOBuffer)
2036 {
2037 /* Linux accepts commands with up to 100KB of data, but expects
2038 * us to handle commands with up to 128KB of data. The usual
2039 * imbalance of powers. */
2040 uint8_t aATAPICmd[ATAPI_PACKET_SIZE];
2041 uint32_t iATAPILBA, cSectors, cReqSectors, cbCurrTX;
2042 uint8_t *pbBuf = s->CTX_SUFF(pbIOBuffer);
2043 uint32_t cSectorsMax; /**< Maximum amount of sectors to read without exceeding the I/O buffer. */
2044
2045 Assert(s->cbATAPISector);
2046 cSectorsMax = cbTransfer / s->cbATAPISector;
2047 Assert(cSectorsMax * s->cbATAPISector <= s->cbIOBuffer);
2048
2049 switch (s->aATAPICmd[0])
2050 {
2051 case SCSI_READ_10:
2052 case SCSI_WRITE_10:
2053 case SCSI_WRITE_AND_VERIFY_10:
2054 iATAPILBA = ataBE2H_U32(s->aATAPICmd + 2);
2055 cSectors = ataBE2H_U16(s->aATAPICmd + 7);
2056 break;
2057 case SCSI_READ_12:
2058 case SCSI_WRITE_12:
2059 iATAPILBA = ataBE2H_U32(s->aATAPICmd + 2);
2060 cSectors = ataBE2H_U32(s->aATAPICmd + 6);
2061 break;
2062 case SCSI_READ_CD:
2063 iATAPILBA = ataBE2H_U32(s->aATAPICmd + 2);
2064 cSectors = ataBE2H_U24(s->aATAPICmd + 6);
2065 break;
2066 case SCSI_READ_CD_MSF:
2067 iATAPILBA = ataMSF2LBA(s->aATAPICmd + 3);
2068 cSectors = ataMSF2LBA(s->aATAPICmd + 6) - iATAPILBA;
2069 break;
2070 default:
2071 AssertMsgFailed(("Don't know how to split command %#04x\n", s->aATAPICmd[0]));
2072 if (s->cErrors++ < MAX_LOG_REL_ERRORS)
2073 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM passthrough split error\n", s->iLUN));
2074 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ILLEGAL_OPCODE);
2075 {
2076 STAM_PROFILE_START(&pCtl->StatLockWait, a);
2077 PDMCritSectEnter(&pCtl->lock, VINF_SUCCESS);
2078 STAM_PROFILE_STOP(&pCtl->StatLockWait, a);
2079 }
2080 return false;
2081 }
2082 cSectorsMax = RT_MIN(cSectorsMax, cSectors);
2083 memcpy(aATAPICmd, s->aATAPICmd, ATAPI_PACKET_SIZE);
2084 cReqSectors = 0;
2085 for (uint32_t i = cSectorsMax; i > 0; i -= cReqSectors)
2086 {
2087 if (i * s->cbATAPISector > SCSI_MAX_BUFFER_SIZE)
2088 cReqSectors = SCSI_MAX_BUFFER_SIZE / s->cbATAPISector;
2089 else
2090 cReqSectors = i;
2091 cbCurrTX = s->cbATAPISector * cReqSectors;
2092 switch (s->aATAPICmd[0])
2093 {
2094 case SCSI_READ_10:
2095 case SCSI_WRITE_10:
2096 case SCSI_WRITE_AND_VERIFY_10:
2097 ataH2BE_U32(aATAPICmd + 2, iATAPILBA);
2098 ataH2BE_U16(aATAPICmd + 7, cReqSectors);
2099 break;
2100 case SCSI_READ_12:
2101 case SCSI_WRITE_12:
2102 ataH2BE_U32(aATAPICmd + 2, iATAPILBA);
2103 ataH2BE_U32(aATAPICmd + 6, cReqSectors);
2104 break;
2105 case SCSI_READ_CD:
2106 ataH2BE_U32(aATAPICmd + 2, iATAPILBA);
2107 ataH2BE_U24(aATAPICmd + 6, cReqSectors);
2108 break;
2109 case SCSI_READ_CD_MSF:
2110 ataLBA2MSF(aATAPICmd + 3, iATAPILBA);
2111 ataLBA2MSF(aATAPICmd + 6, iATAPILBA + cReqSectors);
2112 break;
2113 }
2114 rc = s->pDrvBlock->pfnSendCmd(s->pDrvBlock, aATAPICmd, (PDMBLOCKTXDIR)s->uTxDir, pbBuf, &cbCurrTX, abATAPISense, sizeof(abATAPISense), 30000 /**< @todo timeout */);
2115 if (rc != VINF_SUCCESS)
2116 break;
2117 iATAPILBA += cReqSectors;
2118 pbBuf += s->cbATAPISector * cReqSectors;
2119 }
2120
2121 if (RT_SUCCESS(rc))
2122 {
2123 /* Adjust ATAPI command for the next call. */
2124 switch (s->aATAPICmd[0])
2125 {
2126 case SCSI_READ_10:
2127 case SCSI_WRITE_10:
2128 case SCSI_WRITE_AND_VERIFY_10:
2129 ataH2BE_U32(s->aATAPICmd + 2, iATAPILBA);
2130 ataH2BE_U16(s->aATAPICmd + 7, cSectors - cSectorsMax);
2131 break;
2132 case SCSI_READ_12:
2133 case SCSI_WRITE_12:
2134 ataH2BE_U32(s->aATAPICmd + 2, iATAPILBA);
2135 ataH2BE_U32(s->aATAPICmd + 6, cSectors - cSectorsMax);
2136 break;
2137 case SCSI_READ_CD:
2138 ataH2BE_U32(s->aATAPICmd + 2, iATAPILBA);
2139 ataH2BE_U24(s->aATAPICmd + 6, cSectors - cSectorsMax);
2140 break;
2141 case SCSI_READ_CD_MSF:
2142 ataLBA2MSF(s->aATAPICmd + 3, iATAPILBA);
2143 ataLBA2MSF(s->aATAPICmd + 6, iATAPILBA + cSectors - cSectorsMax);
2144 break;
2145 default:
2146 AssertMsgFailed(("Don't know how to split command %#04x\n", s->aATAPICmd[0]));
2147 if (s->cErrors++ < MAX_LOG_REL_ERRORS)
2148 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM passthrough split error\n", s->iLUN));
2149 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ILLEGAL_OPCODE);
2150 return false;
2151 }
2152 }
2153 }
2154 else
2155 rc = s->pDrvBlock->pfnSendCmd(s->pDrvBlock, s->aATAPICmd, (PDMBLOCKTXDIR)s->uTxDir, s->CTX_SUFF(pbIOBuffer), &cbTransfer, abATAPISense, sizeof(abATAPISense), 30000 /**< @todo timeout */);
2156 if (pProf) { STAM_PROFILE_ADV_STOP(pProf, b); }
2157
2158 STAM_PROFILE_START(&pCtl->StatLockWait, a);
2159 PDMCritSectEnter(&pCtl->lock, VINF_SUCCESS);
2160 STAM_PROFILE_STOP(&pCtl->StatLockWait, a);
2161
2162 /* Update the LEDs and the read/write statistics. */
2163 if (cbTransfer >= 2048)
2164 {
2165 if (s->uTxDir != PDMBLOCKTXDIR_TO_DEVICE)
2166 {
2167 s->Led.Actual.s.fReading = 0;
2168 STAM_REL_COUNTER_ADD(&s->StatBytesRead, cbTransfer);
2169 }
2170 else
2171 {
2172 s->Led.Actual.s.fWriting = 0;
2173 STAM_REL_COUNTER_ADD(&s->StatBytesWritten, cbTransfer);
2174 }
2175 }
2176
2177 if (RT_SUCCESS(rc))
2178 {
2179 /* Do post processing for certain commands. */
2180 switch (s->aATAPICmd[0])
2181 {
2182 case SCSI_SEND_CUE_SHEET:
2183 case SCSI_READ_TOC_PMA_ATIP:
2184 {
2185 if (!s->pTrackList)
2186 rc = ATAPIPassthroughTrackListCreateEmpty(&s->pTrackList);
2187
2188 if (RT_SUCCESS(rc))
2189 rc = ATAPIPassthroughTrackListUpdate(s->pTrackList, s->aATAPICmd, s->CTX_SUFF(pbIOBuffer));
2190
2191 if ( RT_FAILURE(rc)
2192 && s->cErrors++ < MAX_LOG_REL_ERRORS)
2193 LogRel(("ATA: Error (%Rrc) while updating the tracklist during %s, burning the disc might fail\n",
2194 rc, s->aATAPICmd[0] == SCSI_SEND_CUE_SHEET ? "SEND CUE SHEET" : "READ TOC/PMA/ATIP"));
2195 break;
2196 }
2197 case SCSI_SYNCHRONIZE_CACHE:
2198 {
2199 if (s->pTrackList)
2200 ATAPIPassthroughTrackListClear(s->pTrackList);
2201 break;
2202 }
2203 }
2204
2205 if (s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE)
2206 {
2207 Assert(cbTransfer <= s->cbAtapiPassthroughTransfer);
2208 /*
2209 * Reply with the same amount of data as the real drive
2210 * but only if the command wasn't split.
2211 */
2212# if 0 /// @todo This destroys commands where cbTotalTransfer > cbIOBuffer
2213 if (s->cbElementaryTransfer < s->cbIOBuffer)
2214 s->cbTotalTransfer = cbTransfer;
2215# endif
2216
2217 if ( s->aATAPICmd[0] == SCSI_INQUIRY
2218 && s->fOverwriteInquiry)
2219 {
2220 /* Make sure that the real drive cannot be identified.
2221 * Motivation: changing the VM configuration should be as
2222 * invisible as possible to the guest. */
2223 Log3(("ATAPI PT inquiry data before (%d): %.*Rhxs\n", cbTransfer, cbTransfer, s->CTX_SUFF(pbIOBuffer)));
2224 ataR3SCSIPadStr(s->CTX_SUFF(pbIOBuffer) + 8, "VBOX", 8);
2225 ataR3SCSIPadStr(s->CTX_SUFF(pbIOBuffer) + 16, "CD-ROM", 16);
2226 ataR3SCSIPadStr(s->CTX_SUFF(pbIOBuffer) + 32, "1.0", 4);
2227 }
2228
2229 if (cbTransfer)
2230 Log3(("ATAPI PT data read (%d): %.*Rhxs\n", cbTransfer, cbTransfer, s->CTX_SUFF(pbIOBuffer)));
2231 }
2232
2233 /* The initial buffer end value has been set up based on the total
2234 * transfer size. But the I/O buffer size limits what can actually be
2235 * done in one transfer, so set the actual value of the buffer end. */
2236 s->cbElementaryTransfer = cbTransfer;
2237 if (cbTransfer >= s->cbAtapiPassthroughTransfer)
2238 {
2239 s->iSourceSink = ATAFN_SS_NULL;
2240 atapiR3CmdOK(s);
2241 }
2242 }
2243 else
2244 {
2245 if (s->cErrors < MAX_LOG_REL_ERRORS)
2246 {
2247 uint8_t u8Cmd = s->aATAPICmd[0];
2248 do
2249 {
2250 /* don't log superfluous errors */
2251 if ( rc == VERR_DEV_IO_ERROR
2252 && ( u8Cmd == SCSI_TEST_UNIT_READY
2253 || u8Cmd == SCSI_READ_CAPACITY
2254 || u8Cmd == SCSI_READ_DVD_STRUCTURE
2255 || u8Cmd == SCSI_READ_TOC_PMA_ATIP))
2256 break;
2257 s->cErrors++;
2258 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM passthrough cmd=%#04x sense=%d ASC=%#02x ASCQ=%#02x %Rrc\n",
2259 s->iLUN, u8Cmd, abATAPISense[2] & 0x0f, abATAPISense[12], abATAPISense[13], rc));
2260 } while (0);
2261 }
2262 atapiR3CmdError(s, abATAPISense, sizeof(abATAPISense));
2263 }
2264 return false;
2265}
2266
2267/** @todo Revise ASAP. */
2268static bool atapiR3ReadDVDStructureSS(ATADevState *s)
2269{
2270 uint8_t *buf = s->CTX_SUFF(pbIOBuffer);
2271 int media = s->aATAPICmd[1];
2272 int format = s->aATAPICmd[7];
2273
2274 uint16_t max_len = ataBE2H_U16(&s->aATAPICmd[8]);
2275
2276 memset(buf, 0, max_len);
2277
2278 switch (format) {
2279 case 0x00:
2280 case 0x01:
2281 case 0x02:
2282 case 0x03:
2283 case 0x04:
2284 case 0x05:
2285 case 0x06:
2286 case 0x07:
2287 case 0x08:
2288 case 0x09:
2289 case 0x0a:
2290 case 0x0b:
2291 case 0x0c:
2292 case 0x0d:
2293 case 0x0e:
2294 case 0x0f:
2295 case 0x10:
2296 case 0x11:
2297 case 0x30:
2298 case 0x31:
2299 case 0xff:
2300 if (media == 0)
2301 {
2302 int uASC = SCSI_ASC_NONE;
2303
2304 switch (format)
2305 {
2306 case 0x0: /* Physical format information */
2307 {
2308 int layer = s->aATAPICmd[6];
2309 uint64_t total_sectors;
2310
2311 if (layer != 0)
2312 {
2313 uASC = -SCSI_ASC_INV_FIELD_IN_CMD_PACKET;
2314 break;
2315 }
2316
2317 total_sectors = s->cTotalSectors;
2318 total_sectors >>= 2;
2319 if (total_sectors == 0)
2320 {
2321 uASC = -SCSI_ASC_MEDIUM_NOT_PRESENT;
2322 break;
2323 }
2324
2325 buf[4] = 1; /* DVD-ROM, part version 1 */
2326 buf[5] = 0xf; /* 120mm disc, minimum rate unspecified */
2327 buf[6] = 1; /* one layer, read-only (per MMC-2 spec) */
2328 buf[7] = 0; /* default densities */
2329
2330 /* FIXME: 0x30000 per spec? */
2331 ataH2BE_U32(buf + 8, 0); /* start sector */
2332 ataH2BE_U32(buf + 12, total_sectors - 1); /* end sector */
2333 ataH2BE_U32(buf + 16, total_sectors - 1); /* l0 end sector */
2334
2335 /* Size of buffer, not including 2 byte size field */
2336 ataH2BE_U32(&buf[0], 2048 + 2);
2337
2338 /* 2k data + 4 byte header */
2339 uASC = (2048 + 4);
2340 break;
2341 }
2342 case 0x01: /* DVD copyright information */
2343 buf[4] = 0; /* no copyright data */
2344 buf[5] = 0; /* no region restrictions */
2345
2346 /* Size of buffer, not including 2 byte size field */
2347 ataH2BE_U16(buf, 4 + 2);
2348
2349 /* 4 byte header + 4 byte data */
2350 uASC = (4 + 4);
2351 break;
2352
2353 case 0x03: /* BCA information - invalid field for no BCA info */
2354 uASC = -SCSI_ASC_INV_FIELD_IN_CMD_PACKET;
2355 break;
2356
2357 case 0x04: /* DVD disc manufacturing information */
2358 /* Size of buffer, not including 2 byte size field */
2359 ataH2BE_U16(buf, 2048 + 2);
2360
2361 /* 2k data + 4 byte header */
2362 uASC = (2048 + 4);
2363 break;
2364 case 0xff:
2365 /*
2366 * This lists all the command capabilities above. Add new ones
2367 * in order and update the length and buffer return values.
2368 */
2369
2370 buf[4] = 0x00; /* Physical format */
2371 buf[5] = 0x40; /* Not writable, is readable */
2372 ataH2BE_U16((buf + 6), 2048 + 4);
2373
2374 buf[8] = 0x01; /* Copyright info */
2375 buf[9] = 0x40; /* Not writable, is readable */
2376 ataH2BE_U16((buf + 10), 4 + 4);
2377
2378 buf[12] = 0x03; /* BCA info */
2379 buf[13] = 0x40; /* Not writable, is readable */
2380 ataH2BE_U16((buf + 14), 188 + 4);
2381
2382 buf[16] = 0x04; /* Manufacturing info */
2383 buf[17] = 0x40; /* Not writable, is readable */
2384 ataH2BE_U16((buf + 18), 2048 + 4);
2385
2386 /* Size of buffer, not including 2 byte size field */
2387 ataH2BE_U16(buf, 16 + 2);
2388
2389 /* data written + 4 byte header */
2390 uASC = (16 + 4);
2391 break;
2392 default: /* TODO: formats beyond DVD-ROM requires */
2393 uASC = -SCSI_ASC_INV_FIELD_IN_CMD_PACKET;
2394 }
2395
2396 if (uASC < 0)
2397 {
2398 s->iSourceSink = ATAFN_SS_NULL;
2399 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, -uASC);
2400 return false;
2401 }
2402 break;
2403 }
2404 /* TODO: BD support, fall through for now */
2405
2406 /* Generic disk structures */
2407 case 0x80: /* TODO: AACS volume identifier */
2408 case 0x81: /* TODO: AACS media serial number */
2409 case 0x82: /* TODO: AACS media identifier */
2410 case 0x83: /* TODO: AACS media key block */
2411 case 0x90: /* TODO: List of recognized format layers */
2412 case 0xc0: /* TODO: Write protection status */
2413 default:
2414 s->iSourceSink = ATAFN_SS_NULL;
2415 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST,
2416 SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
2417 return false;
2418 }
2419
2420 s->iSourceSink = ATAFN_SS_NULL;
2421 atapiR3CmdOK(s);
2422 return false;
2423}
2424
2425static bool atapiR3ReadSectors(ATADevState *s, uint32_t iATAPILBA, uint32_t cSectors, uint32_t cbSector)
2426{
2427 Assert(cSectors > 0);
2428 s->iATAPILBA = iATAPILBA;
2429 s->cbATAPISector = cbSector;
2430 ataR3StartTransfer(s, cSectors * cbSector, PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ, true);
2431 return false;
2432}
2433
2434
2435static bool atapiR3ReadCapacitySS(ATADevState *s)
2436{
2437 uint8_t *pbBuf = s->CTX_SUFF(pbIOBuffer);
2438
2439 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
2440 Assert(s->cbElementaryTransfer <= 8);
2441 ataH2BE_U32(pbBuf, s->cTotalSectors - 1);
2442 ataH2BE_U32(pbBuf + 4, 2048);
2443 s->iSourceSink = ATAFN_SS_NULL;
2444 atapiR3CmdOK(s);
2445 return false;
2446}
2447
2448
2449static bool atapiR3ReadDiscInformationSS(ATADevState *s)
2450{
2451 uint8_t *pbBuf = s->CTX_SUFF(pbIOBuffer);
2452
2453 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
2454 Assert(s->cbElementaryTransfer <= 34);
2455 memset(pbBuf, '\0', 34);
2456 ataH2BE_U16(pbBuf, 32);
2457 pbBuf[2] = (0 << 4) | (3 << 2) | (2 << 0); /* not erasable, complete session, complete disc */
2458 pbBuf[3] = 1; /* number of first track */
2459 pbBuf[4] = 1; /* number of sessions (LSB) */
2460 pbBuf[5] = 1; /* first track number in last session (LSB) */
2461 pbBuf[6] = 1; /* last track number in last session (LSB) */
2462 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 */
2463 pbBuf[8] = 0; /* disc type = CD-ROM */
2464 pbBuf[9] = 0; /* number of sessions (MSB) */
2465 pbBuf[10] = 0; /* number of sessions (MSB) */
2466 pbBuf[11] = 0; /* number of sessions (MSB) */
2467 ataH2BE_U32(pbBuf + 16, 0x00ffffff); /* last session lead-in start time is not available */
2468 ataH2BE_U32(pbBuf + 20, 0x00ffffff); /* last possible start time for lead-out is not available */
2469 s->iSourceSink = ATAFN_SS_NULL;
2470 atapiR3CmdOK(s);
2471 return false;
2472}
2473
2474
2475static bool atapiR3ReadTrackInformationSS(ATADevState *s)
2476{
2477 uint8_t *pbBuf = s->CTX_SUFF(pbIOBuffer);
2478
2479 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
2480 Assert(s->cbElementaryTransfer <= 36);
2481 /* Accept address/number type of 1 only, and only track 1 exists. */
2482 if ((s->aATAPICmd[1] & 0x03) != 1 || ataBE2H_U32(&s->aATAPICmd[2]) != 1)
2483 {
2484 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
2485 return false;
2486 }
2487 memset(pbBuf, '\0', 36);
2488 ataH2BE_U16(pbBuf, 34);
2489 pbBuf[2] = 1; /* track number (LSB) */
2490 pbBuf[3] = 1; /* session number (LSB) */
2491 pbBuf[5] = (0 << 5) | (0 << 4) | (4 << 0); /* not damaged, primary copy, data track */
2492 pbBuf[6] = (0 << 7) | (0 << 6) | (0 << 5) | (0 << 6) | (1 << 0); /* not reserved track, not blank, not packet writing, not fixed packet, data mode 1 */
2493 pbBuf[7] = (0 << 1) | (0 << 0); /* last recorded address not valid, next recordable address not valid */
2494 ataH2BE_U32(pbBuf + 8, 0); /* track start address is 0 */
2495 ataH2BE_U32(pbBuf + 24, s->cTotalSectors); /* track size */
2496 pbBuf[32] = 0; /* track number (MSB) */
2497 pbBuf[33] = 0; /* session number (MSB) */
2498 s->iSourceSink = ATAFN_SS_NULL;
2499 atapiR3CmdOK(s);
2500 return false;
2501}
2502
2503static uint32_t atapiR3GetConfigurationFillFeatureListProfiles(ATADevState *s, uint8_t *pbBuf, size_t cbBuf)
2504{
2505 if (cbBuf < 3*4)
2506 return 0;
2507
2508 ataH2BE_U16(pbBuf, 0x0); /* feature 0: list of profiles supported */
2509 pbBuf[2] = (0 << 2) | (1 << 1) | (1 << 0); /* version 0, persistent, current */
2510 pbBuf[3] = 8; /* additional bytes for profiles */
2511 /* The MMC-3 spec says that DVD-ROM read capability should be reported
2512 * before CD-ROM read capability. */
2513 ataH2BE_U16(pbBuf + 4, 0x10); /* profile: read-only DVD */
2514 pbBuf[6] = (0 << 0); /* NOT current profile */
2515 ataH2BE_U16(pbBuf + 8, 0x08); /* profile: read only CD */
2516 pbBuf[10] = (1 << 0); /* current profile */
2517
2518 return 3*4; /* Header + 2 profiles entries */
2519}
2520
2521static uint32_t atapiR3GetConfigurationFillFeatureCore(ATADevState *s, uint8_t *pbBuf, size_t cbBuf)
2522{
2523 if (cbBuf < 12)
2524 return 0;
2525
2526 ataH2BE_U16(pbBuf, 0x1); /* feature 0001h: Core Feature */
2527 pbBuf[2] = (0x2 << 2) | RT_BIT(1) | RT_BIT(0); /* Version | Persistent | Current */
2528 pbBuf[3] = 8; /* Additional length */
2529 ataH2BE_U16(pbBuf + 4, 0x00000002); /* Physical interface ATAPI. */
2530 pbBuf[8] = RT_BIT(0); /* DBE */
2531 /* Rest is reserved. */
2532
2533 return 12;
2534}
2535
2536static uint32_t atapiR3GetConfigurationFillFeatureMorphing(ATADevState *s, uint8_t *pbBuf, size_t cbBuf)
2537{
2538 if (cbBuf < 8)
2539 return 0;
2540
2541 ataH2BE_U16(pbBuf, 0x2); /* feature 0002h: Morphing Feature */
2542 pbBuf[2] = (0x1 << 2) | RT_BIT(1) | RT_BIT(0); /* Version | Persistent | Current */
2543 pbBuf[3] = 4; /* Additional length */
2544 pbBuf[4] = RT_BIT(1) | 0x0; /* OCEvent | !ASYNC */
2545 /* Rest is reserved. */
2546
2547 return 8;
2548}
2549
2550static uint32_t atapiR3GetConfigurationFillFeatureRemovableMedium(ATADevState *s, uint8_t *pbBuf, size_t cbBuf)
2551{
2552 if (cbBuf < 8)
2553 return 0;
2554
2555 ataH2BE_U16(pbBuf, 0x3); /* feature 0003h: Removable Medium Feature */
2556 pbBuf[2] = (0x2 << 2) | RT_BIT(1) | RT_BIT(0); /* Version | Persistent | Current */
2557 pbBuf[3] = 4; /* Additional length */
2558 /* Tray type loading | Load | Eject | !Pvnt Jmpr | !DBML | Lock */
2559 pbBuf[4] = (0x2 << 5) | RT_BIT(4) | RT_BIT(3) | (0x0 << 2) | (0x0 << 1) | RT_BIT(0);
2560 /* Rest is reserved. */
2561
2562 return 8;
2563}
2564
2565static uint32_t atapiR3GetConfigurationFillFeatureRandomReadable (ATADevState *s, uint8_t *pbBuf, size_t cbBuf)
2566{
2567 if (cbBuf < 12)
2568 return 0;
2569
2570 ataH2BE_U16(pbBuf, 0x10); /* feature 0010h: Random Readable Feature */
2571 pbBuf[2] = (0x0 << 2) | RT_BIT(1) | RT_BIT(0); /* Version | Persistent | Current */
2572 pbBuf[3] = 8; /* Additional length */
2573 ataH2BE_U32(pbBuf + 4, 2048); /* Logical block size. */
2574 ataH2BE_U16(pbBuf + 8, 0x10); /* Blocking (0x10 for DVD, CD is not defined). */
2575 pbBuf[10] = 0; /* PP not present */
2576 /* Rest is reserved. */
2577
2578 return 12;
2579}
2580
2581static uint32_t atapiR3GetConfigurationFillFeatureCDRead(ATADevState *s, uint8_t *pbBuf, size_t cbBuf)
2582{
2583 if (cbBuf < 8)
2584 return 0;
2585
2586 ataH2BE_U16(pbBuf, 0x1e); /* feature 001Eh: CD Read Feature */
2587 pbBuf[2] = (0x2 << 2) | RT_BIT(1) | RT_BIT(0); /* Version | Persistent | Current */
2588 pbBuf[3] = 0; /* Additional length */
2589 pbBuf[4] = (0x0 << 7) | (0x0 << 1) | 0x0; /* !DAP | !C2-Flags | !CD-Text. */
2590 /* Rest is reserved. */
2591
2592 return 8;
2593}
2594
2595static uint32_t atapiR3GetConfigurationFillFeaturePowerManagement(ATADevState *s, uint8_t *pbBuf, size_t cbBuf)
2596{
2597 if (cbBuf < 4)
2598 return 0;
2599
2600 ataH2BE_U16(pbBuf, 0x100); /* feature 0100h: Power Management Feature */
2601 pbBuf[2] = (0x0 << 2) | RT_BIT(1) | RT_BIT(0); /* Version | Persistent | Current */
2602 pbBuf[3] = 0; /* Additional length */
2603
2604 return 4;
2605}
2606
2607static uint32_t atapiR3GetConfigurationFillFeatureTimeout(ATADevState *s, uint8_t *pbBuf, size_t cbBuf)
2608{
2609 if (cbBuf < 8)
2610 return 0;
2611
2612 ataH2BE_U16(pbBuf, 0x105); /* feature 0105h: Timeout Feature */
2613 pbBuf[2] = (0x0 << 2) | RT_BIT(1) | RT_BIT(0); /* Version | Persistent | Current */
2614 pbBuf[3] = 4; /* Additional length */
2615 pbBuf[4] = 0x0; /* !Group3 */
2616
2617 return 8;
2618}
2619
2620static bool atapiR3GetConfigurationSS(ATADevState *s)
2621{
2622 uint8_t *pbBuf = s->CTX_SUFF(pbIOBuffer);
2623 uint32_t cbBuf = s->cbIOBuffer;
2624 uint32_t cbCopied = 0;
2625 uint16_t u16Sfn = ataBE2H_U16(&s->aATAPICmd[2]);
2626
2627 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
2628 Assert(s->cbElementaryTransfer <= 80);
2629 /* Accept valid request types only, and only starting feature 0. */
2630 if ((s->aATAPICmd[1] & 0x03) == 3 || u16Sfn != 0)
2631 {
2632 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
2633 return false;
2634 }
2635 memset(pbBuf, '\0', cbBuf);
2636 /** @todo implement switching between CD-ROM and DVD-ROM profile (the only
2637 * way to differentiate them right now is based on the image size). */
2638 if (s->cTotalSectors)
2639 ataH2BE_U16(pbBuf + 6, 0x08); /* current profile: read-only CD */
2640 else
2641 ataH2BE_U16(pbBuf + 6, 0x00); /* current profile: none -> no media */
2642 cbBuf -= 8;
2643 pbBuf += 8;
2644
2645 cbCopied = atapiR3GetConfigurationFillFeatureListProfiles(s, pbBuf, cbBuf);
2646 cbBuf -= cbCopied;
2647 pbBuf += cbCopied;
2648
2649 cbCopied = atapiR3GetConfigurationFillFeatureCore(s, pbBuf, cbBuf);
2650 cbBuf -= cbCopied;
2651 pbBuf += cbCopied;
2652
2653 cbCopied = atapiR3GetConfigurationFillFeatureMorphing(s, pbBuf, cbBuf);
2654 cbBuf -= cbCopied;
2655 pbBuf += cbCopied;
2656
2657 cbCopied = atapiR3GetConfigurationFillFeatureRemovableMedium(s, pbBuf, cbBuf);
2658 cbBuf -= cbCopied;
2659 pbBuf += cbCopied;
2660
2661 cbCopied = atapiR3GetConfigurationFillFeatureRandomReadable (s, pbBuf, cbBuf);
2662 cbBuf -= cbCopied;
2663 pbBuf += cbCopied;
2664
2665 cbCopied = atapiR3GetConfigurationFillFeatureCDRead(s, pbBuf, cbBuf);
2666 cbBuf -= cbCopied;
2667 pbBuf += cbCopied;
2668
2669 cbCopied = atapiR3GetConfigurationFillFeaturePowerManagement(s, pbBuf, cbBuf);
2670 cbBuf -= cbCopied;
2671 pbBuf += cbCopied;
2672
2673 cbCopied = atapiR3GetConfigurationFillFeatureTimeout(s, pbBuf, cbBuf);
2674 cbBuf -= cbCopied;
2675 pbBuf += cbCopied;
2676
2677 /* Set data length now - the field is not included in the final length. */
2678 ataH2BE_U32(s->CTX_SUFF(pbIOBuffer), s->cbIOBuffer - cbBuf - 4);
2679
2680 /* Other profiles we might want to add in the future: 0x40 (BD-ROM) and 0x50 (HDDVD-ROM) */
2681 s->iSourceSink = ATAFN_SS_NULL;
2682 atapiR3CmdOK(s);
2683 return false;
2684}
2685
2686
2687static bool atapiR3GetEventStatusNotificationSS(ATADevState *s)
2688{
2689 uint8_t *pbBuf = s->CTX_SUFF(pbIOBuffer);
2690
2691 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
2692 Assert(s->cbElementaryTransfer <= 8);
2693
2694 if (!(s->aATAPICmd[1] & 1))
2695 {
2696 /* no asynchronous operation supported */
2697 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
2698 return false;
2699 }
2700
2701 uint32_t OldStatus, NewStatus;
2702 do
2703 {
2704 OldStatus = ASMAtomicReadU32(&s->MediaEventStatus);
2705 NewStatus = ATA_EVENT_STATUS_UNCHANGED;
2706 switch (OldStatus)
2707 {
2708 case ATA_EVENT_STATUS_MEDIA_NEW:
2709 /* mount */
2710 ataH2BE_U16(pbBuf + 0, 6);
2711 pbBuf[2] = 0x04; /* media */
2712 pbBuf[3] = 0x5e; /* supported = busy|media|external|power|operational */
2713 pbBuf[4] = 0x02; /* new medium */
2714 pbBuf[5] = 0x02; /* medium present / door closed */
2715 pbBuf[6] = 0x00;
2716 pbBuf[7] = 0x00;
2717 break;
2718
2719 case ATA_EVENT_STATUS_MEDIA_CHANGED:
2720 case ATA_EVENT_STATUS_MEDIA_REMOVED:
2721 /* umount */
2722 ataH2BE_U16(pbBuf + 0, 6);
2723 pbBuf[2] = 0x04; /* media */
2724 pbBuf[3] = 0x5e; /* supported = busy|media|external|power|operational */
2725 pbBuf[4] = 0x03; /* media removal */
2726 pbBuf[5] = 0x00; /* medium absent / door closed */
2727 pbBuf[6] = 0x00;
2728 pbBuf[7] = 0x00;
2729 if (OldStatus == ATA_EVENT_STATUS_MEDIA_CHANGED)
2730 NewStatus = ATA_EVENT_STATUS_MEDIA_NEW;
2731 break;
2732
2733 case ATA_EVENT_STATUS_MEDIA_EJECT_REQUESTED: /* currently unused */
2734 ataH2BE_U16(pbBuf + 0, 6);
2735 pbBuf[2] = 0x04; /* media */
2736 pbBuf[3] = 0x5e; /* supported = busy|media|external|power|operational */
2737 pbBuf[4] = 0x01; /* eject requested (eject button pressed) */
2738 pbBuf[5] = 0x02; /* medium present / door closed */
2739 pbBuf[6] = 0x00;
2740 pbBuf[7] = 0x00;
2741 break;
2742
2743 case ATA_EVENT_STATUS_UNCHANGED:
2744 default:
2745 ataH2BE_U16(pbBuf + 0, 6);
2746 pbBuf[2] = 0x01; /* operational change request / notification */
2747 pbBuf[3] = 0x5e; /* supported = busy|media|external|power|operational */
2748 pbBuf[4] = 0x00;
2749 pbBuf[5] = 0x00;
2750 pbBuf[6] = 0x00;
2751 pbBuf[7] = 0x00;
2752 break;
2753 }
2754 } while (!ASMAtomicCmpXchgU32(&s->MediaEventStatus, NewStatus, OldStatus));
2755
2756 s->iSourceSink = ATAFN_SS_NULL;
2757 atapiR3CmdOK(s);
2758 return false;
2759}
2760
2761
2762static bool atapiR3InquirySS(ATADevState *s)
2763{
2764 uint8_t *pbBuf = s->CTX_SUFF(pbIOBuffer);
2765
2766 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
2767 Assert(s->cbElementaryTransfer <= 36);
2768 pbBuf[0] = 0x05; /* CD-ROM */
2769 pbBuf[1] = 0x80; /* removable */
2770# if 1/*ndef VBOX*/ /** @todo implement MESN + AENC. (async notification on removal and stuff.) */
2771 pbBuf[2] = 0x00; /* ISO */
2772 pbBuf[3] = 0x21; /* ATAPI-2 (XXX: put ATAPI-4 ?) */
2773# else
2774 pbBuf[2] = 0x00; /* ISO */
2775 pbBuf[3] = 0x91; /* format 1, MESN=1, AENC=9 ??? */
2776# endif
2777 pbBuf[4] = 31; /* additional length */
2778 pbBuf[5] = 0; /* reserved */
2779 pbBuf[6] = 0; /* reserved */
2780 pbBuf[7] = 0; /* reserved */
2781 ataR3SCSIPadStr(pbBuf + 8, s->szInquiryVendorId, 8);
2782 ataR3SCSIPadStr(pbBuf + 16, s->szInquiryProductId, 16);
2783 ataR3SCSIPadStr(pbBuf + 32, s->szInquiryRevision, 4);
2784 s->iSourceSink = ATAFN_SS_NULL;
2785 atapiR3CmdOK(s);
2786 return false;
2787}
2788
2789
2790static bool atapiR3ModeSenseErrorRecoverySS(ATADevState *s)
2791{
2792 uint8_t *pbBuf = s->CTX_SUFF(pbIOBuffer);
2793
2794 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
2795 Assert(s->cbElementaryTransfer <= 16);
2796 ataH2BE_U16(&pbBuf[0], 16 + 6);
2797 pbBuf[2] = (uint8_t)s->MediaTrackType;
2798 pbBuf[3] = 0;
2799 pbBuf[4] = 0;
2800 pbBuf[5] = 0;
2801 pbBuf[6] = 0;
2802 pbBuf[7] = 0;
2803
2804 pbBuf[8] = 0x01;
2805 pbBuf[9] = 0x06;
2806 pbBuf[10] = 0x00; /* Maximum error recovery */
2807 pbBuf[11] = 0x05; /* 5 retries */
2808 pbBuf[12] = 0x00;
2809 pbBuf[13] = 0x00;
2810 pbBuf[14] = 0x00;
2811 pbBuf[15] = 0x00;
2812 s->iSourceSink = ATAFN_SS_NULL;
2813 atapiR3CmdOK(s);
2814 return false;
2815}
2816
2817
2818static bool atapiR3ModeSenseCDStatusSS(ATADevState *s)
2819{
2820 uint8_t *pbBuf = s->CTX_SUFF(pbIOBuffer);
2821
2822 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
2823 Assert(s->cbElementaryTransfer <= 40);
2824 ataH2BE_U16(&pbBuf[0], 38);
2825 pbBuf[2] = (uint8_t)s->MediaTrackType;
2826 pbBuf[3] = 0;
2827 pbBuf[4] = 0;
2828 pbBuf[5] = 0;
2829 pbBuf[6] = 0;
2830 pbBuf[7] = 0;
2831
2832 pbBuf[8] = 0x2a;
2833 pbBuf[9] = 30; /* page length */
2834 pbBuf[10] = 0x08; /* DVD-ROM read support */
2835 pbBuf[11] = 0x00; /* no write support */
2836 /* The following claims we support audio play. This is obviously false,
2837 * but the Linux generic CDROM support makes many features depend on this
2838 * capability. If it's not set, this causes many things to be disabled. */
2839 pbBuf[12] = 0x71; /* multisession support, mode 2 form 1/2 support, audio play */
2840 pbBuf[13] = 0x00; /* no subchannel reads supported */
2841 pbBuf[14] = (1 << 0) | (1 << 3) | (1 << 5); /* lock supported, eject supported, tray type loading mechanism */
2842 if (s->pDrvMount->pfnIsLocked(s->pDrvMount))
2843 pbBuf[14] |= 1 << 1; /* report lock state */
2844 pbBuf[15] = 0; /* no subchannel reads supported, no separate audio volume control, no changer etc. */
2845 ataH2BE_U16(&pbBuf[16], 5632); /* (obsolete) claim 32x speed support */
2846 ataH2BE_U16(&pbBuf[18], 2); /* number of audio volume levels */
2847 ataH2BE_U16(&pbBuf[20], s->cbIOBuffer / _1K); /* buffer size supported in Kbyte */
2848 ataH2BE_U16(&pbBuf[22], 5632); /* (obsolete) current read speed 32x */
2849 pbBuf[24] = 0; /* reserved */
2850 pbBuf[25] = 0; /* reserved for digital audio (see idx 15) */
2851 ataH2BE_U16(&pbBuf[26], 0); /* (obsolete) maximum write speed */
2852 ataH2BE_U16(&pbBuf[28], 0); /* (obsolete) current write speed */
2853 ataH2BE_U16(&pbBuf[30], 0); /* copy management revision supported 0=no CSS */
2854 pbBuf[32] = 0; /* reserved */
2855 pbBuf[33] = 0; /* reserved */
2856 pbBuf[34] = 0; /* reserved */
2857 pbBuf[35] = 1; /* rotation control CAV */
2858 ataH2BE_U16(&pbBuf[36], 0); /* current write speed */
2859 ataH2BE_U16(&pbBuf[38], 0); /* number of write speed performance descriptors */
2860 s->iSourceSink = ATAFN_SS_NULL;
2861 atapiR3CmdOK(s);
2862 return false;
2863}
2864
2865
2866static bool atapiR3RequestSenseSS(ATADevState *s)
2867{
2868 uint8_t *pbBuf = s->CTX_SUFF(pbIOBuffer);
2869
2870 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
2871 memset(pbBuf, '\0', s->cbElementaryTransfer);
2872 memcpy(pbBuf, s->abATAPISense, RT_MIN(s->cbElementaryTransfer, sizeof(s->abATAPISense)));
2873 s->iSourceSink = ATAFN_SS_NULL;
2874 atapiR3CmdOK(s);
2875 return false;
2876}
2877
2878
2879static bool atapiR3MechanismStatusSS(ATADevState *s)
2880{
2881 uint8_t *pbBuf = s->CTX_SUFF(pbIOBuffer);
2882
2883 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
2884 Assert(s->cbElementaryTransfer <= 8);
2885 ataH2BE_U16(pbBuf, 0);
2886 /* no current LBA */
2887 pbBuf[2] = 0;
2888 pbBuf[3] = 0;
2889 pbBuf[4] = 0;
2890 pbBuf[5] = 1;
2891 ataH2BE_U16(pbBuf + 6, 0);
2892 s->iSourceSink = ATAFN_SS_NULL;
2893 atapiR3CmdOK(s);
2894 return false;
2895}
2896
2897
2898static bool atapiR3ReadTOCNormalSS(ATADevState *s)
2899{
2900 uint8_t *pbBuf = s->CTX_SUFF(pbIOBuffer), *q, iStartTrack;
2901 bool fMSF;
2902 uint32_t cbSize;
2903
2904 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
2905 fMSF = (s->aATAPICmd[1] >> 1) & 1;
2906 iStartTrack = s->aATAPICmd[6];
2907 if (iStartTrack > 1 && iStartTrack != 0xaa)
2908 {
2909 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
2910 return false;
2911 }
2912 q = pbBuf + 2;
2913 *q++ = 1; /* first session */
2914 *q++ = 1; /* last session */
2915 if (iStartTrack <= 1)
2916 {
2917 *q++ = 0; /* reserved */
2918 *q++ = 0x14; /* ADR, control */
2919 *q++ = 1; /* track number */
2920 *q++ = 0; /* reserved */
2921 if (fMSF)
2922 {
2923 *q++ = 0; /* reserved */
2924 ataLBA2MSF(q, 0);
2925 q += 3;
2926 }
2927 else
2928 {
2929 /* sector 0 */
2930 ataH2BE_U32(q, 0);
2931 q += 4;
2932 }
2933 }
2934 /* lead out track */
2935 *q++ = 0; /* reserved */
2936 *q++ = 0x14; /* ADR, control */
2937 *q++ = 0xaa; /* track number */
2938 *q++ = 0; /* reserved */
2939 if (fMSF)
2940 {
2941 *q++ = 0; /* reserved */
2942 ataLBA2MSF(q, s->cTotalSectors);
2943 q += 3;
2944 }
2945 else
2946 {
2947 ataH2BE_U32(q, s->cTotalSectors);
2948 q += 4;
2949 }
2950 cbSize = q - pbBuf;
2951 ataH2BE_U16(pbBuf, cbSize - 2);
2952 if (cbSize < s->cbTotalTransfer)
2953 s->cbTotalTransfer = cbSize;
2954 s->iSourceSink = ATAFN_SS_NULL;
2955 atapiR3CmdOK(s);
2956 return false;
2957}
2958
2959
2960static bool atapiR3ReadTOCMultiSS(ATADevState *s)
2961{
2962 uint8_t *pbBuf = s->CTX_SUFF(pbIOBuffer);
2963 bool fMSF;
2964
2965 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
2966 Assert(s->cbElementaryTransfer <= 12);
2967 fMSF = (s->aATAPICmd[1] >> 1) & 1;
2968 /* multi session: only a single session defined */
2969/** @todo double-check this stuff against what a real drive says for a CD-ROM (not a CD-R) with only a single data session. Maybe solve the problem with "cdrdao read-toc" not being able to figure out whether numbers are in BCD or hex. */
2970 memset(pbBuf, 0, 12);
2971 pbBuf[1] = 0x0a;
2972 pbBuf[2] = 0x01;
2973 pbBuf[3] = 0x01;
2974 pbBuf[5] = 0x14; /* ADR, control */
2975 pbBuf[6] = 1; /* first track in last complete session */
2976 if (fMSF)
2977 {
2978 pbBuf[8] = 0; /* reserved */
2979 ataLBA2MSF(&pbBuf[9], 0);
2980 }
2981 else
2982 {
2983 /* sector 0 */
2984 ataH2BE_U32(pbBuf + 8, 0);
2985 }
2986 s->iSourceSink = ATAFN_SS_NULL;
2987 atapiR3CmdOK(s);
2988 return false;
2989}
2990
2991
2992static bool atapiR3ReadTOCRawSS(ATADevState *s)
2993{
2994 uint8_t *pbBuf = s->CTX_SUFF(pbIOBuffer), *q, iStartTrack;
2995 bool fMSF;
2996 uint32_t cbSize;
2997
2998 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
2999 fMSF = (s->aATAPICmd[1] >> 1) & 1;
3000 iStartTrack = s->aATAPICmd[6];
3001
3002 q = pbBuf + 2;
3003 *q++ = 1; /* first session */
3004 *q++ = 1; /* last session */
3005
3006 *q++ = 1; /* session number */
3007 *q++ = 0x14; /* data track */
3008 *q++ = 0; /* track number */
3009 *q++ = 0xa0; /* first track in program area */
3010 *q++ = 0; /* min */
3011 *q++ = 0; /* sec */
3012 *q++ = 0; /* frame */
3013 *q++ = 0;
3014 *q++ = 1; /* first track */
3015 *q++ = 0x00; /* disk type CD-DA or CD data */
3016 *q++ = 0;
3017
3018 *q++ = 1; /* session number */
3019 *q++ = 0x14; /* data track */
3020 *q++ = 0; /* track number */
3021 *q++ = 0xa1; /* last track in program area */
3022 *q++ = 0; /* min */
3023 *q++ = 0; /* sec */
3024 *q++ = 0; /* frame */
3025 *q++ = 0;
3026 *q++ = 1; /* last track */
3027 *q++ = 0;
3028 *q++ = 0;
3029
3030 *q++ = 1; /* session number */
3031 *q++ = 0x14; /* data track */
3032 *q++ = 0; /* track number */
3033 *q++ = 0xa2; /* lead-out */
3034 *q++ = 0; /* min */
3035 *q++ = 0; /* sec */
3036 *q++ = 0; /* frame */
3037 if (fMSF)
3038 {
3039 *q++ = 0; /* reserved */
3040 ataLBA2MSF(q, s->cTotalSectors);
3041 q += 3;
3042 }
3043 else
3044 {
3045 ataH2BE_U32(q, s->cTotalSectors);
3046 q += 4;
3047 }
3048
3049 *q++ = 1; /* session number */
3050 *q++ = 0x14; /* ADR, control */
3051 *q++ = 0; /* track number */
3052 *q++ = 1; /* point */
3053 *q++ = 0; /* min */
3054 *q++ = 0; /* sec */
3055 *q++ = 0; /* frame */
3056 if (fMSF)
3057 {
3058 *q++ = 0; /* reserved */
3059 ataLBA2MSF(q, 0);
3060 q += 3;
3061 }
3062 else
3063 {
3064 /* sector 0 */
3065 ataH2BE_U32(q, 0);
3066 q += 4;
3067 }
3068
3069 cbSize = q - pbBuf;
3070 ataH2BE_U16(pbBuf, cbSize - 2);
3071 if (cbSize < s->cbTotalTransfer)
3072 s->cbTotalTransfer = cbSize;
3073 s->iSourceSink = ATAFN_SS_NULL;
3074 atapiR3CmdOK(s);
3075 return false;
3076}
3077
3078
3079static void atapiR3ParseCmdVirtualATAPI(ATADevState *s)
3080{
3081 const uint8_t *pbPacket;
3082 uint8_t *pbBuf;
3083 uint32_t cbMax;
3084
3085 pbPacket = s->aATAPICmd;
3086 pbBuf = s->CTX_SUFF(pbIOBuffer);
3087 switch (pbPacket[0])
3088 {
3089 case SCSI_TEST_UNIT_READY:
3090 if (s->cNotifiedMediaChange > 0)
3091 {
3092 if (s->cNotifiedMediaChange-- > 2)
3093 atapiR3CmdErrorSimple(s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3094 else
3095 atapiR3CmdErrorSimple(s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3096 }
3097 else if (s->pDrvMount->pfnIsMounted(s->pDrvMount))
3098 atapiR3CmdOK(s);
3099 else
3100 atapiR3CmdErrorSimple(s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3101 break;
3102 case SCSI_GET_EVENT_STATUS_NOTIFICATION:
3103 cbMax = ataBE2H_U16(pbPacket + 7);
3104 ataR3StartTransfer(s, RT_MIN(cbMax, 8), PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_GET_EVENT_STATUS_NOTIFICATION, true);
3105 break;
3106 case SCSI_MODE_SENSE_10:
3107 {
3108 uint8_t uPageControl, uPageCode;
3109 cbMax = ataBE2H_U16(pbPacket + 7);
3110 uPageControl = pbPacket[2] >> 6;
3111 uPageCode = pbPacket[2] & 0x3f;
3112 switch (uPageControl)
3113 {
3114 case SCSI_PAGECONTROL_CURRENT:
3115 switch (uPageCode)
3116 {
3117 case SCSI_MODEPAGE_ERROR_RECOVERY:
3118 ataR3StartTransfer(s, RT_MIN(cbMax, 16), PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_MODE_SENSE_ERROR_RECOVERY, true);
3119 break;
3120 case SCSI_MODEPAGE_CD_STATUS:
3121 ataR3StartTransfer(s, RT_MIN(cbMax, 40), PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_MODE_SENSE_CD_STATUS, true);
3122 break;
3123 default:
3124 goto error_cmd;
3125 }
3126 break;
3127 case SCSI_PAGECONTROL_CHANGEABLE:
3128 goto error_cmd;
3129 case SCSI_PAGECONTROL_DEFAULT:
3130 goto error_cmd;
3131 default:
3132 case SCSI_PAGECONTROL_SAVED:
3133 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_SAVING_PARAMETERS_NOT_SUPPORTED);
3134 break;
3135 }
3136 break;
3137 }
3138 case SCSI_REQUEST_SENSE:
3139 cbMax = pbPacket[4];
3140 ataR3StartTransfer(s, RT_MIN(cbMax, 18), PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_REQUEST_SENSE, true);
3141 break;
3142 case SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL:
3143 if (s->pDrvMount->pfnIsMounted(s->pDrvMount))
3144 {
3145 if (pbPacket[4] & 1)
3146 s->pDrvMount->pfnLock(s->pDrvMount);
3147 else
3148 s->pDrvMount->pfnUnlock(s->pDrvMount);
3149 atapiR3CmdOK(s);
3150 }
3151 else
3152 atapiR3CmdErrorSimple(s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3153 break;
3154 case SCSI_READ_10:
3155 case SCSI_READ_12:
3156 {
3157 uint32_t cSectors, iATAPILBA;
3158
3159 if (s->cNotifiedMediaChange > 0)
3160 {
3161 s->cNotifiedMediaChange-- ;
3162 atapiR3CmdErrorSimple(s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3163 break;
3164 }
3165 else if (!s->pDrvMount->pfnIsMounted(s->pDrvMount))
3166 {
3167 atapiR3CmdErrorSimple(s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3168 break;
3169 }
3170 if (pbPacket[0] == SCSI_READ_10)
3171 cSectors = ataBE2H_U16(pbPacket + 7);
3172 else
3173 cSectors = ataBE2H_U32(pbPacket + 6);
3174 iATAPILBA = ataBE2H_U32(pbPacket + 2);
3175 if (cSectors == 0)
3176 {
3177 atapiR3CmdOK(s);
3178 break;
3179 }
3180 if ((uint64_t)iATAPILBA + cSectors > s->cTotalSectors)
3181 {
3182 /* Rate limited logging, one log line per second. For
3183 * guests that insist on reading from places outside the
3184 * valid area this often generates too many release log
3185 * entries otherwise. */
3186 static uint64_t uLastLogTS = 0;
3187 if (RTTimeMilliTS() >= uLastLogTS + 1000)
3188 {
3189 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM block number %Ld invalid (READ)\n", s->iLUN, (uint64_t)iATAPILBA + cSectors));
3190 uLastLogTS = RTTimeMilliTS();
3191 }
3192 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_LOGICAL_BLOCK_OOR);
3193 break;
3194 }
3195 atapiR3ReadSectors(s, iATAPILBA, cSectors, 2048);
3196 break;
3197 }
3198 case SCSI_READ_CD:
3199 {
3200 uint32_t cSectors, iATAPILBA;
3201
3202 if (s->cNotifiedMediaChange > 0)
3203 {
3204 s->cNotifiedMediaChange-- ;
3205 atapiR3CmdErrorSimple(s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3206 break;
3207 }
3208 else if (!s->pDrvMount->pfnIsMounted(s->pDrvMount))
3209 {
3210 atapiR3CmdErrorSimple(s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3211 break;
3212 }
3213 cSectors = (pbPacket[6] << 16) | (pbPacket[7] << 8) | pbPacket[8];
3214 iATAPILBA = ataBE2H_U32(pbPacket + 2);
3215 if (cSectors == 0)
3216 {
3217 atapiR3CmdOK(s);
3218 break;
3219 }
3220 if ((uint64_t)iATAPILBA + cSectors > s->cTotalSectors)
3221 {
3222 /* Rate limited logging, one log line per second. For
3223 * guests that insist on reading from places outside the
3224 * valid area this often generates too many release log
3225 * entries otherwise. */
3226 static uint64_t uLastLogTS = 0;
3227 if (RTTimeMilliTS() >= uLastLogTS + 1000)
3228 {
3229 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM block number %Ld invalid (READ CD)\n", s->iLUN, (uint64_t)iATAPILBA + cSectors));
3230 uLastLogTS = RTTimeMilliTS();
3231 }
3232 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_LOGICAL_BLOCK_OOR);
3233 break;
3234 }
3235 switch (pbPacket[9] & 0xf8)
3236 {
3237 case 0x00:
3238 /* nothing */
3239 atapiR3CmdOK(s);
3240 break;
3241 case 0x10:
3242 /* normal read */
3243 atapiR3ReadSectors(s, iATAPILBA, cSectors, 2048);
3244 break;
3245 case 0xf8:
3246 /* read all data */
3247 atapiR3ReadSectors(s, iATAPILBA, cSectors, 2352);
3248 break;
3249 default:
3250 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM sector format not supported (%#x)\n", s->iLUN, pbPacket[9] & 0xf8));
3251 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
3252 break;
3253 }
3254 break;
3255 }
3256 case SCSI_SEEK_10:
3257 {
3258 uint32_t iATAPILBA;
3259 if (s->cNotifiedMediaChange > 0)
3260 {
3261 s->cNotifiedMediaChange-- ;
3262 atapiR3CmdErrorSimple(s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3263 break;
3264 }
3265 else if (!s->pDrvMount->pfnIsMounted(s->pDrvMount))
3266 {
3267 atapiR3CmdErrorSimple(s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3268 break;
3269 }
3270 iATAPILBA = ataBE2H_U32(pbPacket + 2);
3271 if (iATAPILBA > s->cTotalSectors)
3272 {
3273 /* Rate limited logging, one log line per second. For
3274 * guests that insist on seeking to places outside the
3275 * valid area this often generates too many release log
3276 * entries otherwise. */
3277 static uint64_t uLastLogTS = 0;
3278 if (RTTimeMilliTS() >= uLastLogTS + 1000)
3279 {
3280 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM block number %Ld invalid (SEEK)\n", s->iLUN, (uint64_t)iATAPILBA));
3281 uLastLogTS = RTTimeMilliTS();
3282 }
3283 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_LOGICAL_BLOCK_OOR);
3284 break;
3285 }
3286 atapiR3CmdOK(s);
3287 ataSetStatus(s, ATA_STAT_SEEK); /* Linux expects this. */
3288 break;
3289 }
3290 case SCSI_START_STOP_UNIT:
3291 {
3292 int rc = VINF_SUCCESS;
3293 switch (pbPacket[4] & 3)
3294 {
3295 case 0: /* 00 - Stop motor */
3296 case 1: /* 01 - Start motor */
3297 break;
3298 case 2: /* 10 - Eject media */
3299 {
3300 /* This must be done from EMT. */
3301 PATACONTROLLER pCtl = ATADEVSTATE_2_CONTROLLER(s);
3302 PPDMDEVINS pDevIns = ATADEVSTATE_2_DEVINS(s);
3303 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
3304
3305 PDMCritSectLeave(&pCtl->lock);
3306 rc = VMR3ReqPriorityCallWait(PDMDevHlpGetVM(pDevIns), VMCPUID_ANY,
3307 (PFNRT)s->pDrvMount->pfnUnmount, 3,
3308 s->pDrvMount, false /*=fForce*/, true /*=fEject*/);
3309 Assert(RT_SUCCESS(rc) || rc == VERR_PDM_MEDIA_LOCKED || rc == VERR_PDM_MEDIA_NOT_MOUNTED);
3310 if (RT_SUCCESS(rc) && pThis->pMediaNotify)
3311 {
3312 rc = VMR3ReqCallNoWait(PDMDevHlpGetVM(pDevIns), VMCPUID_ANY,
3313 (PFNRT)pThis->pMediaNotify->pfnEjected, 2,
3314 pThis->pMediaNotify, s->iLUN);
3315 AssertRC(rc);
3316 }
3317 {
3318 STAM_PROFILE_START(&pCtl->StatLockWait, a);
3319 PDMCritSectEnter(&pCtl->lock, VINF_SUCCESS);
3320 STAM_PROFILE_STOP(&pCtl->StatLockWait, a);
3321 }
3322 break;
3323 }
3324 case 3: /* 11 - Load media */
3325 /** @todo rc = s->pDrvMount->pfnLoadMedia(s->pDrvMount) */
3326 break;
3327 }
3328 if (RT_SUCCESS(rc))
3329 atapiR3CmdOK(s);
3330 else
3331 atapiR3CmdErrorSimple(s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIA_LOAD_OR_EJECT_FAILED);
3332 break;
3333 }
3334 case SCSI_MECHANISM_STATUS:
3335 {
3336 cbMax = ataBE2H_U16(pbPacket + 8);
3337 ataR3StartTransfer(s, RT_MIN(cbMax, 8), PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_MECHANISM_STATUS, true);
3338 break;
3339 }
3340 case SCSI_READ_TOC_PMA_ATIP:
3341 {
3342 uint8_t format;
3343
3344 if (s->cNotifiedMediaChange > 0)
3345 {
3346 s->cNotifiedMediaChange-- ;
3347 atapiR3CmdErrorSimple(s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3348 break;
3349 }
3350 else if (!s->pDrvMount->pfnIsMounted(s->pDrvMount))
3351 {
3352 atapiR3CmdErrorSimple(s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3353 break;
3354 }
3355 cbMax = ataBE2H_U16(pbPacket + 7);
3356 /* SCSI MMC-3 spec says format is at offset 2 (lower 4 bits),
3357 * but Linux kernel uses offset 9 (topmost 2 bits). Hope that
3358 * the other field is clear... */
3359 format = (pbPacket[2] & 0xf) | (pbPacket[9] >> 6);
3360 switch (format)
3361 {
3362 case 0:
3363 ataR3StartTransfer(s, cbMax, PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ_TOC_NORMAL, true);
3364 break;
3365 case 1:
3366 ataR3StartTransfer(s, RT_MIN(cbMax, 12), PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ_TOC_MULTI, true);
3367 break;
3368 case 2:
3369 ataR3StartTransfer(s, cbMax, PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ_TOC_RAW, true);
3370 break;
3371 default:
3372 error_cmd:
3373 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
3374 break;
3375 }
3376 break;
3377 }
3378 case SCSI_READ_CAPACITY:
3379 if (s->cNotifiedMediaChange > 0)
3380 {
3381 s->cNotifiedMediaChange-- ;
3382 atapiR3CmdErrorSimple(s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3383 break;
3384 }
3385 else if (!s->pDrvMount->pfnIsMounted(s->pDrvMount))
3386 {
3387 atapiR3CmdErrorSimple(s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3388 break;
3389 }
3390 ataR3StartTransfer(s, 8, PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ_CAPACITY, true);
3391 break;
3392 case SCSI_READ_DISC_INFORMATION:
3393 if (s->cNotifiedMediaChange > 0)
3394 {
3395 s->cNotifiedMediaChange-- ;
3396 atapiR3CmdErrorSimple(s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3397 break;
3398 }
3399 else if (!s->pDrvMount->pfnIsMounted(s->pDrvMount))
3400 {
3401 atapiR3CmdErrorSimple(s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3402 break;
3403 }
3404 cbMax = ataBE2H_U16(pbPacket + 7);
3405 ataR3StartTransfer(s, RT_MIN(cbMax, 34), PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ_DISC_INFORMATION, true);
3406 break;
3407 case SCSI_READ_TRACK_INFORMATION:
3408 if (s->cNotifiedMediaChange > 0)
3409 {
3410 s->cNotifiedMediaChange-- ;
3411 atapiR3CmdErrorSimple(s, SCSI_SENSE_UNIT_ATTENTION, SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED); /* media changed */
3412 break;
3413 }
3414 else if (!s->pDrvMount->pfnIsMounted(s->pDrvMount))
3415 {
3416 atapiR3CmdErrorSimple(s, SCSI_SENSE_NOT_READY, SCSI_ASC_MEDIUM_NOT_PRESENT);
3417 break;
3418 }
3419 cbMax = ataBE2H_U16(pbPacket + 7);
3420 ataR3StartTransfer(s, RT_MIN(cbMax, 36), PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ_TRACK_INFORMATION, true);
3421 break;
3422 case SCSI_GET_CONFIGURATION:
3423 /* No media change stuff here, it can confuse Linux guests. */
3424 cbMax = ataBE2H_U16(pbPacket + 7);
3425 ataR3StartTransfer(s, RT_MIN(cbMax, 80), PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_GET_CONFIGURATION, true);
3426 break;
3427 case SCSI_INQUIRY:
3428 cbMax = ataBE2H_U16(pbPacket + 3);
3429 ataR3StartTransfer(s, RT_MIN(cbMax, 36), PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_INQUIRY, true);
3430 break;
3431 case SCSI_READ_DVD_STRUCTURE:
3432 {
3433 cbMax = ataBE2H_U16(pbPacket + 8);
3434 ataR3StartTransfer(s, RT_MIN(cbMax, 4), PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_READ_DVD_STRUCTURE, true);
3435 break;
3436 }
3437 default:
3438 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ILLEGAL_OPCODE);
3439 break;
3440 }
3441}
3442
3443
3444/*
3445 * Parse ATAPI commands, passing them directly to the CD/DVD drive.
3446 */
3447static void atapiR3ParseCmdPassthrough(ATADevState *s)
3448{
3449 const uint8_t *pbPacket;
3450 uint8_t *pbBuf;
3451 uint32_t cSectors, iATAPILBA;
3452 uint32_t cbTransfer = 0;
3453 PDMBLOCKTXDIR uTxDir = PDMBLOCKTXDIR_NONE;
3454
3455 pbPacket = s->aATAPICmd;
3456 pbBuf = s->CTX_SUFF(pbIOBuffer);
3457 switch (pbPacket[0])
3458 {
3459 case SCSI_BLANK:
3460 goto sendcmd;
3461 case SCSI_CLOSE_TRACK_SESSION:
3462 goto sendcmd;
3463 case SCSI_ERASE_10:
3464 iATAPILBA = ataBE2H_U32(pbPacket + 2);
3465 cbTransfer = ataBE2H_U16(pbPacket + 7);
3466 Log2(("ATAPI PT: lba %d\n", iATAPILBA));
3467 uTxDir = PDMBLOCKTXDIR_TO_DEVICE;
3468 goto sendcmd;
3469 case SCSI_FORMAT_UNIT:
3470 cbTransfer = s->uATARegLCyl | (s->uATARegHCyl << 8); /* use ATAPI transfer length */
3471 uTxDir = PDMBLOCKTXDIR_TO_DEVICE;
3472 goto sendcmd;
3473 case SCSI_GET_CONFIGURATION:
3474 cbTransfer = ataBE2H_U16(pbPacket + 7);
3475 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3476 goto sendcmd;
3477 case SCSI_GET_EVENT_STATUS_NOTIFICATION:
3478 cbTransfer = ataBE2H_U16(pbPacket + 7);
3479 if (ASMAtomicReadU32(&s->MediaEventStatus) != ATA_EVENT_STATUS_UNCHANGED)
3480 {
3481 ataR3StartTransfer(s, RT_MIN(cbTransfer, 8), PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_GET_EVENT_STATUS_NOTIFICATION, true);
3482 break;
3483 }
3484 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3485 goto sendcmd;
3486 case SCSI_GET_PERFORMANCE:
3487 cbTransfer = s->uATARegLCyl | (s->uATARegHCyl << 8); /* use ATAPI transfer length */
3488 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3489 goto sendcmd;
3490 case SCSI_INQUIRY:
3491 cbTransfer = ataBE2H_U16(pbPacket + 3);
3492 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3493 goto sendcmd;
3494 case SCSI_LOAD_UNLOAD_MEDIUM:
3495 goto sendcmd;
3496 case SCSI_MECHANISM_STATUS:
3497 cbTransfer = ataBE2H_U16(pbPacket + 8);
3498 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3499 goto sendcmd;
3500 case SCSI_MODE_SELECT_10:
3501 cbTransfer = ataBE2H_U16(pbPacket + 7);
3502 uTxDir = PDMBLOCKTXDIR_TO_DEVICE;
3503 goto sendcmd;
3504 case SCSI_MODE_SENSE_10:
3505 cbTransfer = ataBE2H_U16(pbPacket + 7);
3506 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3507 goto sendcmd;
3508 case SCSI_PAUSE_RESUME:
3509 goto sendcmd;
3510 case SCSI_PLAY_AUDIO_10:
3511 goto sendcmd;
3512 case SCSI_PLAY_AUDIO_12:
3513 goto sendcmd;
3514 case SCSI_PLAY_AUDIO_MSF:
3515 goto sendcmd;
3516 case SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL:
3517 /** @todo do not forget to unlock when a VM is shut down */
3518 goto sendcmd;
3519 case SCSI_READ_10:
3520 iATAPILBA = ataBE2H_U32(pbPacket + 2);
3521 cSectors = ataBE2H_U16(pbPacket + 7);
3522 Log2(("ATAPI PT: lba %d sectors %d\n", iATAPILBA, cSectors));
3523 s->cbATAPISector = 2048;
3524 cbTransfer = cSectors * s->cbATAPISector;
3525 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3526 goto sendcmd;
3527 case SCSI_READ_12:
3528 iATAPILBA = ataBE2H_U32(pbPacket + 2);
3529 cSectors = ataBE2H_U32(pbPacket + 6);
3530 Log2(("ATAPI PT: lba %d sectors %d\n", iATAPILBA, cSectors));
3531 s->cbATAPISector = 2048;
3532 cbTransfer = cSectors * s->cbATAPISector;
3533 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3534 goto sendcmd;
3535 case SCSI_READ_BUFFER:
3536 cbTransfer = ataBE2H_U24(pbPacket + 6);
3537 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3538 goto sendcmd;
3539 case SCSI_READ_BUFFER_CAPACITY:
3540 cbTransfer = ataBE2H_U16(pbPacket + 7);
3541 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3542 goto sendcmd;
3543 case SCSI_READ_CAPACITY:
3544 cbTransfer = 8;
3545 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3546 goto sendcmd;
3547 case SCSI_READ_CD:
3548 case SCSI_READ_CD_MSF:
3549 {
3550 /* Get sector size based on the expected sector type field. */
3551 switch ((pbPacket[1] >> 2) & 0x7)
3552 {
3553 case 0x0: /* All types. */
3554 {
3555 uint32_t iLbaStart;
3556
3557 if (pbPacket[0] == SCSI_READ_CD)
3558 iLbaStart = ataBE2H_U32(&pbPacket[2]);
3559 else
3560 iLbaStart = ataMSF2LBA(&pbPacket[3]);
3561
3562 if (s->pTrackList)
3563 s->cbATAPISector = ATAPIPassthroughTrackListGetSectorSizeFromLba(s->pTrackList, iLbaStart);
3564 else
3565 s->cbATAPISector = 2048; /* Might be incorrect if we couldn't determine the type. */
3566 break;
3567 }
3568 case 0x1: /* CD-DA */
3569 s->cbATAPISector = 2352;
3570 break;
3571 case 0x2: /* Mode 1 */
3572 s->cbATAPISector = 2048;
3573 break;
3574 case 0x3: /* Mode 2 formless */
3575 s->cbATAPISector = 2336;
3576 break;
3577 case 0x4: /* Mode 2 form 1 */
3578 s->cbATAPISector = 2048;
3579 break;
3580 case 0x5: /* Mode 2 form 2 */
3581 s->cbATAPISector = 2324;
3582 break;
3583 default: /* Reserved */
3584 AssertMsgFailed(("Unknown sector type\n"));
3585 s->cbATAPISector = 0; /** @todo we should probably fail the command here already. */
3586 }
3587
3588 if (pbPacket[0] == SCSI_READ_CD)
3589 cbTransfer = ataBE2H_U24(pbPacket + 6) * s->cbATAPISector;
3590 else /* SCSI_READ_MSF */
3591 {
3592 cSectors = ataMSF2LBA(pbPacket + 6) - ataMSF2LBA(pbPacket + 3);
3593 if (cSectors > 32)
3594 cSectors = 32; /* Limit transfer size to 64~74K. Safety first. In any case this can only harm software doing CDDA extraction. */
3595 cbTransfer = cSectors * s->cbATAPISector;
3596 }
3597 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3598 goto sendcmd;
3599 }
3600 case SCSI_READ_DISC_INFORMATION:
3601 cbTransfer = ataBE2H_U16(pbPacket + 7);
3602 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3603 goto sendcmd;
3604 case SCSI_READ_DVD_STRUCTURE:
3605 cbTransfer = ataBE2H_U16(pbPacket + 8);
3606 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3607 goto sendcmd;
3608 case SCSI_READ_FORMAT_CAPACITIES:
3609 cbTransfer = ataBE2H_U16(pbPacket + 7);
3610 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3611 goto sendcmd;
3612 case SCSI_READ_SUBCHANNEL:
3613 cbTransfer = ataBE2H_U16(pbPacket + 7);
3614 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3615 goto sendcmd;
3616 case SCSI_READ_TOC_PMA_ATIP:
3617 cbTransfer = ataBE2H_U16(pbPacket + 7);
3618 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3619 goto sendcmd;
3620 case SCSI_READ_TRACK_INFORMATION:
3621 cbTransfer = ataBE2H_U16(pbPacket + 7);
3622 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3623 goto sendcmd;
3624 case SCSI_REPAIR_TRACK:
3625 goto sendcmd;
3626 case SCSI_REPORT_KEY:
3627 cbTransfer = ataBE2H_U16(pbPacket + 8);
3628 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3629 goto sendcmd;
3630 case SCSI_REQUEST_SENSE:
3631 cbTransfer = pbPacket[4];
3632 if ((s->abATAPISense[2] & 0x0f) != SCSI_SENSE_NONE)
3633 {
3634 ataR3StartTransfer(s, RT_MIN(cbTransfer, 18), PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_ATAPI_CMD, ATAFN_SS_ATAPI_REQUEST_SENSE, true);
3635 break;
3636 }
3637 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3638 goto sendcmd;
3639 case SCSI_RESERVE_TRACK:
3640 goto sendcmd;
3641 case SCSI_SCAN:
3642 goto sendcmd;
3643 case SCSI_SEEK_10:
3644 goto sendcmd;
3645 case SCSI_SEND_CUE_SHEET:
3646 cbTransfer = ataBE2H_U24(pbPacket + 6);
3647 uTxDir = PDMBLOCKTXDIR_TO_DEVICE;
3648 goto sendcmd;
3649 case SCSI_SEND_DVD_STRUCTURE:
3650 cbTransfer = ataBE2H_U16(pbPacket + 8);
3651 uTxDir = PDMBLOCKTXDIR_TO_DEVICE;
3652 goto sendcmd;
3653 case SCSI_SEND_EVENT:
3654 cbTransfer = ataBE2H_U16(pbPacket + 8);
3655 uTxDir = PDMBLOCKTXDIR_TO_DEVICE;
3656 goto sendcmd;
3657 case SCSI_SEND_KEY:
3658 cbTransfer = ataBE2H_U16(pbPacket + 8);
3659 uTxDir = PDMBLOCKTXDIR_TO_DEVICE;
3660 goto sendcmd;
3661 case SCSI_SEND_OPC_INFORMATION:
3662 cbTransfer = ataBE2H_U16(pbPacket + 7);
3663 uTxDir = PDMBLOCKTXDIR_TO_DEVICE;
3664 goto sendcmd;
3665 case SCSI_SET_CD_SPEED:
3666 goto sendcmd;
3667 case SCSI_SET_READ_AHEAD:
3668 goto sendcmd;
3669 case SCSI_SET_STREAMING:
3670 cbTransfer = ataBE2H_U16(pbPacket + 9);
3671 uTxDir = PDMBLOCKTXDIR_TO_DEVICE;
3672 goto sendcmd;
3673 case SCSI_START_STOP_UNIT:
3674 goto sendcmd;
3675 case SCSI_STOP_PLAY_SCAN:
3676 goto sendcmd;
3677 case SCSI_SYNCHRONIZE_CACHE:
3678 goto sendcmd;
3679 case SCSI_TEST_UNIT_READY:
3680 goto sendcmd;
3681 case SCSI_VERIFY_10:
3682 goto sendcmd;
3683 case SCSI_WRITE_10:
3684 case SCSI_WRITE_AND_VERIFY_10:
3685 iATAPILBA = ataBE2H_U32(pbPacket + 2);
3686 cSectors = ataBE2H_U16(pbPacket + 7);
3687 if (s->pTrackList)
3688 s->cbATAPISector = ATAPIPassthroughTrackListGetSectorSizeFromLba(s->pTrackList, iATAPILBA);
3689 else
3690 s->cbATAPISector = 2048;
3691 Log2(("ATAPI PT: lba %d sectors %d sector size %d\n", iATAPILBA, cSectors, s->cbATAPISector));
3692 cbTransfer = cSectors * s->cbATAPISector;
3693 uTxDir = PDMBLOCKTXDIR_TO_DEVICE;
3694 goto sendcmd;
3695 case SCSI_WRITE_12:
3696 iATAPILBA = ataBE2H_U32(pbPacket + 2);
3697 cSectors = ataBE2H_U32(pbPacket + 6);
3698 if (s->pTrackList)
3699 s->cbATAPISector = ATAPIPassthroughTrackListGetSectorSizeFromLba(s->pTrackList, iATAPILBA);
3700 else
3701 s->cbATAPISector = 2048;
3702 Log2(("ATAPI PT: lba %d sectors %d sector size %d\n", iATAPILBA, cSectors, s->cbATAPISector));
3703 cbTransfer = cSectors * s->cbATAPISector;
3704 uTxDir = PDMBLOCKTXDIR_TO_DEVICE;
3705 goto sendcmd;
3706 case SCSI_WRITE_BUFFER:
3707 switch (pbPacket[1] & 0x1f)
3708 {
3709 case 0x04: /* download microcode */
3710 case 0x05: /* download microcode and save */
3711 case 0x06: /* download microcode with offsets */
3712 case 0x07: /* download microcode with offsets and save */
3713 case 0x0e: /* download microcode with offsets and defer activation */
3714 case 0x0f: /* activate deferred microcode */
3715 LogRel(("PIIX3 ATA: LUN#%d: CD-ROM passthrough command attempted to update firmware, blocked\n", s->iLUN));
3716 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
3717 break;
3718 default:
3719 cbTransfer = ataBE2H_U16(pbPacket + 6);
3720 uTxDir = PDMBLOCKTXDIR_TO_DEVICE;
3721 goto sendcmd;
3722 }
3723 break;
3724 case SCSI_REPORT_LUNS: /* Not part of MMC-3, but used by Windows. */
3725 cbTransfer = ataBE2H_U32(pbPacket + 6);
3726 uTxDir = PDMBLOCKTXDIR_FROM_DEVICE;
3727 goto sendcmd;
3728 case SCSI_REZERO_UNIT:
3729 /* Obsolete command used by cdrecord. What else would one expect?
3730 * This command is not sent to the drive, it is handled internally,
3731 * as the Linux kernel doesn't like it (message "scsi: unknown
3732 * opcode 0x01" in syslog) and replies with a sense code of 0,
3733 * which sends cdrecord to an endless loop. */
3734 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ILLEGAL_OPCODE);
3735 break;
3736 default:
3737 LogRel(("PIIX3 ATA: LUN#%d: passthrough unimplemented for command %#x\n", s->iLUN, pbPacket[0]));
3738 atapiR3CmdErrorSimple(s, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ILLEGAL_OPCODE);
3739 break;
3740 sendcmd:
3741 /*
3742 * Send a command to the drive, passing data in/out as required.
3743 * Commands which exceed the I/O buffer size are split below
3744 * or aborted if splitting is not implemented.
3745 */
3746 Log2(("ATAPI PT: max size %d\n", cbTransfer));
3747 if (cbTransfer == 0)
3748 uTxDir = PDMBLOCKTXDIR_NONE;
3749 ataR3StartTransfer(s, cbTransfer, uTxDir, ATAFN_BT_ATAPI_PASSTHROUGH_CMD, ATAFN_SS_ATAPI_PASSTHROUGH, true);
3750 }
3751}
3752
3753
3754static void atapiR3ParseCmd(ATADevState *s)
3755{
3756 const uint8_t *pbPacket;
3757
3758 pbPacket = s->aATAPICmd;
3759# ifdef DEBUG
3760 Log(("%s: LUN#%d DMA=%d CMD=%#04x \"%s\"\n", __FUNCTION__, s->iLUN, s->fDMA, pbPacket[0], SCSICmdText(pbPacket[0])));
3761# else /* !DEBUG */
3762 Log(("%s: LUN#%d DMA=%d CMD=%#04x\n", __FUNCTION__, s->iLUN, s->fDMA, pbPacket[0]));
3763# endif /* !DEBUG */
3764 Log2(("%s: limit=%#x packet: %.*Rhxs\n", __FUNCTION__, s->uATARegLCyl | (s->uATARegHCyl << 8), ATAPI_PACKET_SIZE, pbPacket));
3765
3766 if (s->fATAPIPassthrough)
3767 atapiR3ParseCmdPassthrough(s);
3768 else
3769 atapiR3ParseCmdVirtualATAPI(s);
3770}
3771
3772
3773static bool ataR3PacketSS(ATADevState *s)
3774{
3775 s->fDMA = !!(s->uATARegFeature & 1);
3776 memcpy(s->aATAPICmd, s->CTX_SUFF(pbIOBuffer), ATAPI_PACKET_SIZE);
3777 s->uTxDir = PDMBLOCKTXDIR_NONE;
3778 s->cbTotalTransfer = 0;
3779 s->cbElementaryTransfer = 0;
3780 s->cbAtapiPassthroughTransfer = 0;
3781 atapiR3ParseCmd(s);
3782 return false;
3783}
3784
3785
3786/**
3787 * SCSI_GET_EVENT_STATUS_NOTIFICATION should return "medium removed" event
3788 * from now on, regardless if there was a medium inserted or not.
3789 */
3790static void ataR3MediumRemoved(ATADevState *s)
3791{
3792 ASMAtomicWriteU32(&s->MediaEventStatus, ATA_EVENT_STATUS_MEDIA_REMOVED);
3793}
3794
3795
3796/**
3797 * SCSI_GET_EVENT_STATUS_NOTIFICATION should return "medium inserted". If
3798 * there was already a medium inserted, don't forget to send the "medium
3799 * removed" event first.
3800 */
3801static void ataR3MediumInserted(ATADevState *s)
3802{
3803 uint32_t OldStatus, NewStatus;
3804 do
3805 {
3806 OldStatus = ASMAtomicReadU32(&s->MediaEventStatus);
3807 switch (OldStatus)
3808 {
3809 case ATA_EVENT_STATUS_MEDIA_CHANGED:
3810 case ATA_EVENT_STATUS_MEDIA_REMOVED:
3811 /* no change, we will send "medium removed" + "medium inserted" */
3812 NewStatus = ATA_EVENT_STATUS_MEDIA_CHANGED;
3813 break;
3814 default:
3815 NewStatus = ATA_EVENT_STATUS_MEDIA_NEW;
3816 break;
3817 }
3818 } while (!ASMAtomicCmpXchgU32(&s->MediaEventStatus, NewStatus, OldStatus));
3819}
3820
3821
3822/**
3823 * @interface_method_impl{PDMIMOUNTNOTIFY, pfnMountNotify}
3824 */
3825static DECLCALLBACK(void) ataR3MountNotify(PPDMIMOUNTNOTIFY pInterface)
3826{
3827 ATADevState *pIf = PDMIMOUNTNOTIFY_2_ATASTATE(pInterface);
3828 Log(("%s: changing LUN#%d\n", __FUNCTION__, pIf->iLUN));
3829
3830 /* Ignore the call if we're called while being attached. */
3831 if (!pIf->pDrvBlock)
3832 return;
3833
3834 if (pIf->fATAPI)
3835 pIf->cTotalSectors = pIf->pDrvBlock->pfnGetSize(pIf->pDrvBlock) / 2048;
3836 else
3837 pIf->cTotalSectors = pIf->pDrvBlock->pfnGetSize(pIf->pDrvBlock) / pIf->cbSector;
3838
3839 LogRel(("PIIX3 ATA: LUN#%d: CD/DVD, total number of sectors %Ld, passthrough unchanged\n", pIf->iLUN, pIf->cTotalSectors));
3840
3841 /* Report media changed in TEST UNIT and other (probably incorrect) places. */
3842 if (pIf->cNotifiedMediaChange < 2)
3843 pIf->cNotifiedMediaChange = 1;
3844 ataR3MediumInserted(pIf);
3845 ataR3MediumTypeSet(pIf, ATA_MEDIA_TYPE_UNKNOWN);
3846}
3847
3848/**
3849 * @interface_method_impl{PDMIMOUNTNOTIFY, pfnUnmountNotify}
3850 */
3851static DECLCALLBACK(void) ataR3UnmountNotify(PPDMIMOUNTNOTIFY pInterface)
3852{
3853 ATADevState *pIf = PDMIMOUNTNOTIFY_2_ATASTATE(pInterface);
3854 Log(("%s:\n", __FUNCTION__));
3855 pIf->cTotalSectors = 0;
3856
3857 /*
3858 * Whatever I do, XP will not use the GET MEDIA STATUS nor the EVENT stuff.
3859 * However, it will respond to TEST UNIT with a 0x6 0x28 (media changed) sense code.
3860 * So, we'll give it 4 TEST UNIT command to catch up, two which the media is not
3861 * present and 2 in which it is changed.
3862 */
3863 pIf->cNotifiedMediaChange = 1;
3864 ataR3MediumRemoved(pIf);
3865 ataR3MediumTypeSet(pIf, ATA_MEDIA_NO_DISC);
3866}
3867
3868static void ataR3PacketBT(ATADevState *s)
3869{
3870 s->cbElementaryTransfer = s->cbTotalTransfer;
3871 s->cbAtapiPassthroughTransfer = s->cbTotalTransfer;
3872 s->uATARegNSector = (s->uATARegNSector & ~7) | ATAPI_INT_REASON_CD;
3873 Log2(("%s: interrupt reason %#04x\n", __FUNCTION__, s->uATARegNSector));
3874 ataSetStatusValue(s, ATA_STAT_READY);
3875}
3876
3877
3878static void ataR3ResetDevice(ATADevState *s)
3879{
3880 s->cMultSectors = ATA_MAX_MULT_SECTORS;
3881 s->cNotifiedMediaChange = 0;
3882 ASMAtomicWriteU32(&s->MediaEventStatus, ATA_EVENT_STATUS_UNCHANGED);
3883 ASMAtomicWriteU32(&s->MediaTrackType, ATA_MEDIA_TYPE_UNKNOWN);
3884 ataUnsetIRQ(s);
3885
3886 s->uATARegSelect = 0x20;
3887 ataSetStatusValue(s, ATA_STAT_READY);
3888 ataR3SetSignature(s);
3889 s->cbTotalTransfer = 0;
3890 s->cbElementaryTransfer = 0;
3891 s->cbAtapiPassthroughTransfer = 0;
3892 s->iIOBufferPIODataStart = 0;
3893 s->iIOBufferPIODataEnd = 0;
3894 s->iBeginTransfer = ATAFN_BT_NULL;
3895 s->iSourceSink = ATAFN_SS_NULL;
3896 s->fDMA = false;
3897 s->fATAPITransfer = false;
3898 s->uATATransferMode = ATA_MODE_UDMA | 2; /* PIIX3 supports only up to UDMA2 */
3899
3900 s->uATARegFeature = 0;
3901}
3902
3903
3904static bool ataR3ExecuteDeviceDiagnosticSS(ATADevState *s)
3905{
3906 ataR3SetSignature(s);
3907 if (s->fATAPI)
3908 ataSetStatusValue(s, 0); /* NOTE: READY is _not_ set */
3909 else
3910 ataSetStatusValue(s, ATA_STAT_READY | ATA_STAT_SEEK);
3911 s->uATARegError = 0x01;
3912 return false;
3913}
3914
3915
3916static int ataR3TrimSectors(ATADevState *s, uint64_t u64Sector, uint32_t cSectors,
3917 bool *pfRedo)
3918{
3919 RTRANGE TrimRange;
3920 PATACONTROLLER pCtl = ATADEVSTATE_2_CONTROLLER(s);
3921 int rc;
3922
3923 PDMCritSectLeave(&pCtl->lock);
3924
3925 TrimRange.offStart = u64Sector * s->cbSector;
3926 TrimRange.cbRange = cSectors * s->cbSector;
3927
3928 s->Led.Asserted.s.fWriting = s->Led.Actual.s.fWriting = 1;
3929 rc = s->pDrvBlock->pfnDiscard(s->pDrvBlock, &TrimRange, 1);
3930 s->Led.Actual.s.fWriting = 0;
3931
3932 if (RT_SUCCESS(rc))
3933 *pfRedo = false;
3934 else
3935 *pfRedo = ataR3IsRedoSetWarning(s, rc);
3936
3937 STAM_PROFILE_START(&pCtl->StatLockWait, a);
3938 PDMCritSectEnter(&pCtl->lock, VINF_SUCCESS);
3939 STAM_PROFILE_STOP(&pCtl->StatLockWait, a);
3940 return rc;
3941}
3942
3943
3944static bool ataR3TrimSS(ATADevState *s)
3945{
3946 int rc = VERR_GENERAL_FAILURE;
3947 uint32_t cRangesMax;
3948 uint64_t *pu64Range = (uint64_t *)s->CTX_SUFF(pbIOBuffer);
3949 bool fRedo = false;
3950
3951 cRangesMax = s->cbElementaryTransfer / sizeof(uint64_t);
3952 Assert(cRangesMax);
3953
3954 while (cRangesMax-- > 0)
3955 {
3956 if (ATA_RANGE_LENGTH_GET(*pu64Range) == 0)
3957 break;
3958
3959 rc = ataR3TrimSectors(s, *pu64Range & ATA_RANGE_LBA_MASK,
3960 ATA_RANGE_LENGTH_GET(*pu64Range), &fRedo);
3961 if (RT_FAILURE(rc))
3962 break;
3963
3964 pu64Range++;
3965 }
3966
3967 if (RT_SUCCESS(rc))
3968 {
3969 s->iSourceSink = ATAFN_SS_NULL;
3970 ataR3CmdOK(s, ATA_STAT_SEEK);
3971 }
3972 else
3973 {
3974 if (fRedo)
3975 return fRedo;
3976 if (s->cErrors++ < MAX_LOG_REL_ERRORS)
3977 LogRel(("PIIX3 ATA: LUN#%d: disk trim error (rc=%Rrc iSector=%#RX64 cSectors=%#RX32)\n",
3978 s->iLUN, rc, *pu64Range & ATA_RANGE_LBA_MASK, ATA_RANGE_LENGTH_GET(*pu64Range)));
3979
3980 /*
3981 * Check if we got interrupted. We don't need to set status variables
3982 * because the request was aborted.
3983 */
3984 if (rc != VERR_INTERRUPTED)
3985 ataR3CmdError(s, ID_ERR);
3986 }
3987
3988 return false;
3989}
3990
3991
3992static void ataR3ParseCmd(ATADevState *s, uint8_t cmd)
3993{
3994# ifdef DEBUG
3995 Log(("%s: LUN#%d CMD=%#04x \"%s\"\n", __FUNCTION__, s->iLUN, cmd, ATACmdText(cmd)));
3996# else /* !DEBUG */
3997 Log(("%s: LUN#%d CMD=%#04x\n", __FUNCTION__, s->iLUN, cmd));
3998# endif /* !DEBUG */
3999 s->fLBA48 = false;
4000 s->fDMA = false;
4001 if (cmd == ATA_IDLE_IMMEDIATE)
4002 {
4003 /* Detect Linux timeout recovery, first tries IDLE IMMEDIATE (which
4004 * would overwrite the failing command unfortunately), then RESET. */
4005 int32_t uCmdWait = -1;
4006 uint64_t uNow = RTTimeNanoTS();
4007 if (s->u64CmdTS)
4008 uCmdWait = (uNow - s->u64CmdTS) / 1000;
4009 LogRel(("PIIX3 ATA: LUN#%d: IDLE IMMEDIATE, CmdIf=%#04x (%d usec ago)\n",
4010 s->iLUN, s->uATARegCommand, uCmdWait));
4011 }
4012 s->uATARegCommand = cmd;
4013 switch (cmd)
4014 {
4015 case ATA_IDENTIFY_DEVICE:
4016 if (s->pDrvBlock && !s->fATAPI)
4017 ataR3StartTransfer(s, 512, PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_NULL, ATAFN_SS_IDENTIFY, false);
4018 else
4019 {
4020 if (s->fATAPI)
4021 ataR3SetSignature(s);
4022 ataR3CmdError(s, ABRT_ERR);
4023 ataUnsetStatus(s, ATA_STAT_READY);
4024 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4025 }
4026 break;
4027 case ATA_RECALIBRATE:
4028 if (s->fATAPI)
4029 goto abort_cmd;
4030 /* fall through */
4031 case ATA_INITIALIZE_DEVICE_PARAMETERS:
4032 ataR3CmdOK(s, ATA_STAT_SEEK);
4033 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4034 break;
4035 case ATA_SET_MULTIPLE_MODE:
4036 if ( s->uATARegNSector != 0
4037 && ( s->uATARegNSector > ATA_MAX_MULT_SECTORS
4038 || (s->uATARegNSector & (s->uATARegNSector - 1)) != 0))
4039 {
4040 ataR3CmdError(s, ABRT_ERR);
4041 }
4042 else
4043 {
4044 Log2(("%s: set multi sector count to %d\n", __FUNCTION__, s->uATARegNSector));
4045 s->cMultSectors = s->uATARegNSector;
4046 ataR3CmdOK(s, 0);
4047 }
4048 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4049 break;
4050 case ATA_READ_VERIFY_SECTORS_EXT:
4051 s->fLBA48 = true;
4052 case ATA_READ_VERIFY_SECTORS:
4053 case ATA_READ_VERIFY_SECTORS_WITHOUT_RETRIES:
4054 /* do sector number check ? */
4055 ataR3CmdOK(s, ATA_STAT_SEEK);
4056 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4057 break;
4058 case ATA_READ_SECTORS_EXT:
4059 s->fLBA48 = true;
4060 case ATA_READ_SECTORS:
4061 case ATA_READ_SECTORS_WITHOUT_RETRIES:
4062 if (!s->pDrvBlock || s->fATAPI)
4063 goto abort_cmd;
4064 s->cSectorsPerIRQ = 1;
4065 ataR3StartTransfer(s, ataR3GetNSectors(s) * s->cbSector, PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_READ_WRITE_SECTORS, ATAFN_SS_READ_SECTORS, false);
4066 break;
4067 case ATA_WRITE_SECTORS_EXT:
4068 s->fLBA48 = true;
4069 case ATA_WRITE_SECTORS:
4070 case ATA_WRITE_SECTORS_WITHOUT_RETRIES:
4071 if (!s->pDrvBlock || s->fATAPI)
4072 goto abort_cmd;
4073 s->cSectorsPerIRQ = 1;
4074 ataR3StartTransfer(s, ataR3GetNSectors(s) * s->cbSector, PDMBLOCKTXDIR_TO_DEVICE, ATAFN_BT_READ_WRITE_SECTORS, ATAFN_SS_WRITE_SECTORS, false);
4075 break;
4076 case ATA_READ_MULTIPLE_EXT:
4077 s->fLBA48 = true;
4078 case ATA_READ_MULTIPLE:
4079 if (!s->pDrvBlock || !s->cMultSectors || s->fATAPI)
4080 goto abort_cmd;
4081 s->cSectorsPerIRQ = s->cMultSectors;
4082 ataR3StartTransfer(s, ataR3GetNSectors(s) * s->cbSector, PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_READ_WRITE_SECTORS, ATAFN_SS_READ_SECTORS, false);
4083 break;
4084 case ATA_WRITE_MULTIPLE_EXT:
4085 s->fLBA48 = true;
4086 case ATA_WRITE_MULTIPLE:
4087 if (!s->pDrvBlock || !s->cMultSectors || s->fATAPI)
4088 goto abort_cmd;
4089 s->cSectorsPerIRQ = s->cMultSectors;
4090 ataR3StartTransfer(s, ataR3GetNSectors(s) * s->cbSector, PDMBLOCKTXDIR_TO_DEVICE, ATAFN_BT_READ_WRITE_SECTORS, ATAFN_SS_WRITE_SECTORS, false);
4091 break;
4092 case ATA_READ_DMA_EXT:
4093 s->fLBA48 = true;
4094 case ATA_READ_DMA:
4095 case ATA_READ_DMA_WITHOUT_RETRIES:
4096 if (!s->pDrvBlock || s->fATAPI)
4097 goto abort_cmd;
4098 s->cSectorsPerIRQ = ATA_MAX_MULT_SECTORS;
4099 s->fDMA = true;
4100 ataR3StartTransfer(s, ataR3GetNSectors(s) * s->cbSector, PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_READ_WRITE_SECTORS, ATAFN_SS_READ_SECTORS, false);
4101 break;
4102 case ATA_WRITE_DMA_EXT:
4103 s->fLBA48 = true;
4104 case ATA_WRITE_DMA:
4105 case ATA_WRITE_DMA_WITHOUT_RETRIES:
4106 if (!s->pDrvBlock || s->fATAPI)
4107 goto abort_cmd;
4108 s->cSectorsPerIRQ = ATA_MAX_MULT_SECTORS;
4109 s->fDMA = true;
4110 ataR3StartTransfer(s, ataR3GetNSectors(s) * s->cbSector, PDMBLOCKTXDIR_TO_DEVICE, ATAFN_BT_READ_WRITE_SECTORS, ATAFN_SS_WRITE_SECTORS, false);
4111 break;
4112 case ATA_READ_NATIVE_MAX_ADDRESS_EXT:
4113 s->fLBA48 = true;
4114 ataR3SetSector(s, s->cTotalSectors - 1);
4115 ataR3CmdOK(s, 0);
4116 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4117 break;
4118 case ATA_SEEK: /* Used by the SCO OpenServer. Command is marked as obsolete */
4119 ataR3CmdOK(s, 0);
4120 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4121 break;
4122 case ATA_READ_NATIVE_MAX_ADDRESS:
4123 ataR3SetSector(s, RT_MIN(s->cTotalSectors, 1 << 28) - 1);
4124 ataR3CmdOK(s, 0);
4125 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4126 break;
4127 case ATA_CHECK_POWER_MODE:
4128 s->uATARegNSector = 0xff; /* drive active or idle */
4129 ataR3CmdOK(s, 0);
4130 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4131 break;
4132 case ATA_SET_FEATURES:
4133 Log2(("%s: feature=%#x\n", __FUNCTION__, s->uATARegFeature));
4134 if (!s->pDrvBlock)
4135 goto abort_cmd;
4136 switch (s->uATARegFeature)
4137 {
4138 case 0x02: /* write cache enable */
4139 Log2(("%s: write cache enable\n", __FUNCTION__));
4140 ataR3CmdOK(s, ATA_STAT_SEEK);
4141 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4142 break;
4143 case 0xaa: /* read look-ahead enable */
4144 Log2(("%s: read look-ahead enable\n", __FUNCTION__));
4145 ataR3CmdOK(s, ATA_STAT_SEEK);
4146 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4147 break;
4148 case 0x55: /* read look-ahead disable */
4149 Log2(("%s: read look-ahead disable\n", __FUNCTION__));
4150 ataR3CmdOK(s, ATA_STAT_SEEK);
4151 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4152 break;
4153 case 0xcc: /* reverting to power-on defaults enable */
4154 Log2(("%s: revert to power-on defaults enable\n", __FUNCTION__));
4155 ataR3CmdOK(s, ATA_STAT_SEEK);
4156 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4157 break;
4158 case 0x66: /* reverting to power-on defaults disable */
4159 Log2(("%s: revert to power-on defaults disable\n", __FUNCTION__));
4160 ataR3CmdOK(s, ATA_STAT_SEEK);
4161 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4162 break;
4163 case 0x82: /* write cache disable */
4164 Log2(("%s: write cache disable\n", __FUNCTION__));
4165 /* As per the ATA/ATAPI-6 specs, a write cache disable
4166 * command MUST flush the write buffers to disc. */
4167 ataR3StartTransfer(s, 0, PDMBLOCKTXDIR_NONE, ATAFN_BT_NULL, ATAFN_SS_FLUSH, false);
4168 break;
4169 case 0x03: { /* set transfer mode */
4170 Log2(("%s: transfer mode %#04x\n", __FUNCTION__, s->uATARegNSector));
4171 switch (s->uATARegNSector & 0xf8)
4172 {
4173 case 0x00: /* PIO default */
4174 case 0x08: /* PIO mode */
4175 break;
4176 case ATA_MODE_MDMA: /* MDMA mode */
4177 s->uATATransferMode = (s->uATARegNSector & 0xf8) | RT_MIN(s->uATARegNSector & 0x07, ATA_MDMA_MODE_MAX);
4178 break;
4179 case ATA_MODE_UDMA: /* UDMA mode */
4180 s->uATATransferMode = (s->uATARegNSector & 0xf8) | RT_MIN(s->uATARegNSector & 0x07, ATA_UDMA_MODE_MAX);
4181 break;
4182 default:
4183 goto abort_cmd;
4184 }
4185 ataR3CmdOK(s, ATA_STAT_SEEK);
4186 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4187 break;
4188 }
4189 default:
4190 goto abort_cmd;
4191 }
4192 /*
4193 * OS/2 workarond:
4194 * The OS/2 IDE driver from MCP2 appears to rely on the feature register being
4195 * reset here. According to the specification, this is a driver bug as the register
4196 * contents are undefined after the call. This means we can just as well reset it.
4197 */
4198 s->uATARegFeature = 0;
4199 break;
4200 case ATA_FLUSH_CACHE_EXT:
4201 case ATA_FLUSH_CACHE:
4202 if (!s->pDrvBlock || s->fATAPI)
4203 goto abort_cmd;
4204 ataR3StartTransfer(s, 0, PDMBLOCKTXDIR_NONE, ATAFN_BT_NULL, ATAFN_SS_FLUSH, false);
4205 break;
4206 case ATA_STANDBY_IMMEDIATE:
4207 ataR3CmdOK(s, 0);
4208 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4209 break;
4210 case ATA_IDLE_IMMEDIATE:
4211 LogRel(("PIIX3 ATA: LUN#%d: aborting current command\n", s->iLUN));
4212 ataR3AbortCurrentCommand(s, false);
4213 break;
4214 case ATA_SLEEP:
4215 ataR3CmdOK(s, 0);
4216 ataHCSetIRQ(s);
4217 break;
4218 /* ATAPI commands */
4219 case ATA_IDENTIFY_PACKET_DEVICE:
4220 if (s->fATAPI)
4221 ataR3StartTransfer(s, 512, PDMBLOCKTXDIR_FROM_DEVICE, ATAFN_BT_NULL, ATAFN_SS_ATAPI_IDENTIFY, false);
4222 else
4223 {
4224 ataR3CmdError(s, ABRT_ERR);
4225 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4226 }
4227 break;
4228 case ATA_EXECUTE_DEVICE_DIAGNOSTIC:
4229 ataR3StartTransfer(s, 0, PDMBLOCKTXDIR_NONE, ATAFN_BT_NULL, ATAFN_SS_EXECUTE_DEVICE_DIAGNOSTIC, false);
4230 break;
4231 case ATA_DEVICE_RESET:
4232 if (!s->fATAPI)
4233 goto abort_cmd;
4234 LogRel(("PIIX3 ATA: LUN#%d: performing device RESET\n", s->iLUN));
4235 ataR3AbortCurrentCommand(s, true);
4236 break;
4237 case ATA_PACKET:
4238 if (!s->fATAPI)
4239 goto abort_cmd;
4240 /* overlapping commands not supported */
4241 if (s->uATARegFeature & 0x02)
4242 goto abort_cmd;
4243 ataR3StartTransfer(s, ATAPI_PACKET_SIZE, PDMBLOCKTXDIR_TO_DEVICE, ATAFN_BT_PACKET, ATAFN_SS_PACKET, false);
4244 break;
4245 case ATA_DATA_SET_MANAGEMENT:
4246 if (!s->pDrvBlock || !s->pDrvBlock->pfnDiscard)
4247 goto abort_cmd;
4248 if ( !(s->uATARegFeature & UINT8_C(0x01))
4249 || (s->uATARegFeature & ~UINT8_C(0x01)))
4250 goto abort_cmd;
4251 s->fDMA = true;
4252 ataR3StartTransfer(s, (s->uATARegNSectorHOB << 8 | s->uATARegNSector) * s->cbSector, PDMBLOCKTXDIR_TO_DEVICE, ATAFN_BT_NULL, ATAFN_SS_TRIM, false);
4253 break;
4254 default:
4255 abort_cmd:
4256 ataR3CmdError(s, ABRT_ERR);
4257 if (s->fATAPI)
4258 ataUnsetStatus(s, ATA_STAT_READY);
4259 ataHCSetIRQ(s); /* Shortcut, do not use AIO thread. */
4260 break;
4261 }
4262}
4263
4264# endif /* IN_RING3 */
4265#endif /* IN_RING0 || IN_RING3 */
4266
4267/*
4268 * Note: There are four distinct cases of port I/O handling depending on
4269 * which devices (if any) are attached to an IDE channel:
4270 *
4271 * 1) No device attached. No response to writes or reads (i.e. reads return
4272 * all bits set).
4273 *
4274 * 2) Both devices attached. Reads and writes are processed normally.
4275 *
4276 * 3) Device 0 only. If device 0 is selected, normal behavior applies. But
4277 * if Device 1 is selected, writes are still directed to Device 0 (except
4278 * commands are not executed), reads from control/command registers are
4279 * directed to Device 0, but status/alt status reads return 0. If Device 1
4280 * is a PACKET device, all reads return 0. See ATAPI-6 clause 9.16.1 and
4281 * Table 18 in clause 7.1.
4282 *
4283 * 4) Device 1 only - non-standard(!). Device 1 can't tell if Device 0 is
4284 * present or not and behaves the same. That means if Device 0 is selected,
4285 * Device 1 responds to writes (except commands are not executed) but does
4286 * not respond to reads. If Device 1 selected, normal behavior applies.
4287 * See ATAPI-6 clause 9.16.2 and Table 15 in clause 7.1.
4288 */
4289
4290static int ataIOPortWriteU8(PATACONTROLLER pCtl, uint32_t addr, uint32_t val)
4291{
4292 Log2(("%s: LUN#%d write addr=%#x val=%#04x\n", __FUNCTION__, pCtl->aIfs[pCtl->iSelectedIf].iLUN, addr, val));
4293 addr &= 7;
4294 switch (addr)
4295 {
4296 case 0:
4297 break;
4298 case 1: /* feature register */
4299 /* NOTE: data is written to the two drives */
4300 pCtl->aIfs[0].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4301 pCtl->aIfs[1].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4302 pCtl->aIfs[0].uATARegFeatureHOB = pCtl->aIfs[0].uATARegFeature;
4303 pCtl->aIfs[1].uATARegFeatureHOB = pCtl->aIfs[1].uATARegFeature;
4304 pCtl->aIfs[0].uATARegFeature = val;
4305 pCtl->aIfs[1].uATARegFeature = val;
4306 break;
4307 case 2: /* sector count */
4308 pCtl->aIfs[0].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4309 pCtl->aIfs[1].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4310 pCtl->aIfs[0].uATARegNSectorHOB = pCtl->aIfs[0].uATARegNSector;
4311 pCtl->aIfs[1].uATARegNSectorHOB = pCtl->aIfs[1].uATARegNSector;
4312 pCtl->aIfs[0].uATARegNSector = val;
4313 pCtl->aIfs[1].uATARegNSector = val;
4314 break;
4315 case 3: /* sector number */
4316 pCtl->aIfs[0].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4317 pCtl->aIfs[1].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4318 pCtl->aIfs[0].uATARegSectorHOB = pCtl->aIfs[0].uATARegSector;
4319 pCtl->aIfs[1].uATARegSectorHOB = pCtl->aIfs[1].uATARegSector;
4320 pCtl->aIfs[0].uATARegSector = val;
4321 pCtl->aIfs[1].uATARegSector = val;
4322 break;
4323 case 4: /* cylinder low */
4324 pCtl->aIfs[0].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4325 pCtl->aIfs[1].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4326 pCtl->aIfs[0].uATARegLCylHOB = pCtl->aIfs[0].uATARegLCyl;
4327 pCtl->aIfs[1].uATARegLCylHOB = pCtl->aIfs[1].uATARegLCyl;
4328 pCtl->aIfs[0].uATARegLCyl = val;
4329 pCtl->aIfs[1].uATARegLCyl = val;
4330 break;
4331 case 5: /* cylinder high */
4332 pCtl->aIfs[0].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4333 pCtl->aIfs[1].uATARegDevCtl &= ~ATA_DEVCTL_HOB;
4334 pCtl->aIfs[0].uATARegHCylHOB = pCtl->aIfs[0].uATARegHCyl;
4335 pCtl->aIfs[1].uATARegHCylHOB = pCtl->aIfs[1].uATARegHCyl;
4336 pCtl->aIfs[0].uATARegHCyl = val;
4337 pCtl->aIfs[1].uATARegHCyl = val;
4338 break;
4339 case 6: /* drive/head */
4340 pCtl->aIfs[0].uATARegSelect = (val & ~0x10) | 0xa0;
4341 pCtl->aIfs[1].uATARegSelect = (val | 0x10) | 0xa0;
4342 if (((val >> 4) & 1) != pCtl->iSelectedIf)
4343 {
4344 PPDMDEVINS pDevIns = CONTROLLER_2_DEVINS(pCtl);
4345
4346 /* select another drive */
4347 pCtl->iSelectedIf = (val >> 4) & 1;
4348 /* The IRQ line is multiplexed between the two drives, so
4349 * update the state when switching to another drive. Only need
4350 * to update interrupt line if it is enabled and there is a
4351 * state change. */
4352 if ( !(pCtl->aIfs[pCtl->iSelectedIf].uATARegDevCtl & ATA_DEVCTL_DISABLE_IRQ)
4353 && ( pCtl->aIfs[pCtl->iSelectedIf].fIrqPending
4354 != pCtl->aIfs[pCtl->iSelectedIf ^ 1].fIrqPending))
4355 {
4356 if (pCtl->aIfs[pCtl->iSelectedIf].fIrqPending)
4357 {
4358 Log2(("%s: LUN#%d asserting IRQ (drive select change)\n", __FUNCTION__, pCtl->aIfs[pCtl->iSelectedIf].iLUN));
4359 /* The BMDMA unit unconditionally sets BM_STATUS_INT if
4360 * the interrupt line is asserted. It monitors the line
4361 * for a rising edge. */
4362 pCtl->BmDma.u8Status |= BM_STATUS_INT;
4363 if (pCtl->irq == 16)
4364 PDMDevHlpPCISetIrq(pDevIns, 0, 1);
4365 else
4366 PDMDevHlpISASetIrq(pDevIns, pCtl->irq, 1);
4367 }
4368 else
4369 {
4370 Log2(("%s: LUN#%d deasserting IRQ (drive select change)\n", __FUNCTION__, pCtl->aIfs[pCtl->iSelectedIf].iLUN));
4371 if (pCtl->irq == 16)
4372 PDMDevHlpPCISetIrq(pDevIns, 0, 0);
4373 else
4374 PDMDevHlpISASetIrq(pDevIns, pCtl->irq, 0);
4375 }
4376 }
4377 }
4378 break;
4379 default:
4380 case 7: /* command */
4381 /* ignore commands to non-existent device */
4382 if (pCtl->iSelectedIf && !pCtl->aIfs[pCtl->iSelectedIf].pDrvBlock)
4383 break;
4384#ifndef IN_RING3
4385 /* Don't do anything complicated in GC */
4386 return VINF_IOM_R3_IOPORT_WRITE;
4387#else /* IN_RING3 */
4388 ataR3ParseCmd(&pCtl->aIfs[pCtl->iSelectedIf], val);
4389#endif /* !IN_RING3 */
4390 }
4391 return VINF_SUCCESS;
4392}
4393
4394
4395static int ataIOPortReadU8(PATACONTROLLER pCtl, uint32_t addr, uint32_t *pu32)
4396{
4397 ATADevState *s = &pCtl->aIfs[pCtl->iSelectedIf];
4398 uint32_t val;
4399 bool fHOB;
4400
4401 /* Check if the guest is reading from a non-existent device. */
4402 if (!s->pDrvBlock)
4403 {
4404 if (pCtl->iSelectedIf) /* Device 1 selected, Device 0 responding for it. */
4405 {
4406 if (!pCtl->aIfs[0].pDrvBlock) /** @todo this case should never get here! */
4407 {
4408 Log2(("%s: addr=%#x: no device on channel\n", __FUNCTION__, addr));
4409 return VERR_IOM_IOPORT_UNUSED;
4410 }
4411 if (((addr & 7) != 1) && pCtl->aIfs[0].fATAPI) {
4412 Log2(("%s: addr=%#x, val=0: LUN#%d not attached/LUN#%d ATAPI\n", __FUNCTION__, addr,
4413 s->iLUN, pCtl->aIfs[0].iLUN));
4414 *pu32 = 0;
4415 return VINF_SUCCESS;
4416 }
4417 /* Else handle normally. */
4418 }
4419 else /* Device 0 selected (but not present). */
4420 {
4421 Log2(("%s: addr=%#x: LUN#%d not attached\n", __FUNCTION__, addr, s->iLUN));
4422 return VERR_IOM_IOPORT_UNUSED;
4423 }
4424 }
4425 fHOB = !!(s->uATARegDevCtl & (1 << 7));
4426 switch (addr & 7)
4427 {
4428 case 0: /* data register */
4429 val = 0xff;
4430 break;
4431 case 1: /* error register */
4432 /* The ATA specification is very terse when it comes to specifying
4433 * the precise effects of reading back the error/feature register.
4434 * The error register (read-only) shares the register number with
4435 * the feature register (write-only), so it seems that it's not
4436 * necessary to support the usual HOB readback here. */
4437 if (!s->pDrvBlock)
4438 val = 0;
4439 else
4440 val = s->uATARegError;
4441 break;
4442 case 2: /* sector count */
4443 if (fHOB)
4444 val = s->uATARegNSectorHOB;
4445 else
4446 val = s->uATARegNSector;
4447 break;
4448 case 3: /* sector number */
4449 if (fHOB)
4450 val = s->uATARegSectorHOB;
4451 else
4452 val = s->uATARegSector;
4453 break;
4454 case 4: /* cylinder low */
4455 if (fHOB)
4456 val = s->uATARegLCylHOB;
4457 else
4458 val = s->uATARegLCyl;
4459 break;
4460 case 5: /* cylinder high */
4461 if (fHOB)
4462 val = s->uATARegHCylHOB;
4463 else
4464 val = s->uATARegHCyl;
4465 break;
4466 case 6: /* drive/head */
4467 /* This register must always work as long as there is at least
4468 * one drive attached to the controller. It is common between
4469 * both drives anyway (completely identical content). */
4470 if (!pCtl->aIfs[0].pDrvBlock && !pCtl->aIfs[1].pDrvBlock)
4471 val = 0;
4472 else
4473 val = s->uATARegSelect;
4474 break;
4475 default:
4476 case 7: /* primary status */
4477 {
4478 /* Counter for number of busy status seen in GC in a row. */
4479 static unsigned cBusy = 0;
4480
4481 if (!s->pDrvBlock)
4482 val = 0;
4483 else
4484 val = s->uATARegStatus;
4485
4486 /* Give the async I/O thread an opportunity to make progress,
4487 * don't let it starve by guests polling frequently. EMT has a
4488 * lower priority than the async I/O thread, but sometimes the
4489 * host OS doesn't care. With some guests we are only allowed to
4490 * be busy for about 5 milliseconds in some situations. Note that
4491 * this is no guarantee for any other VBox thread getting
4492 * scheduled, so this just lowers the CPU load a bit when drives
4493 * are busy. It cannot help with timing problems. */
4494 if (val & ATA_STAT_BUSY)
4495 {
4496#ifdef IN_RING3
4497 cBusy = 0;
4498 PDMCritSectLeave(&pCtl->lock);
4499
4500#ifndef RT_OS_WINDOWS
4501 /*
4502 * The thread might be stuck in an I/O operation
4503 * due to a high I/O load on the host. (see @bugref{3301})
4504 * To perform the reset successfully
4505 * we interrupt the operation by sending a signal to the thread
4506 * if the thread didn't responded in 10ms.
4507 * This works only on POSIX hosts (Windows has a CancelSynchronousIo function which
4508 * does the same but it was introduced with Vista) but so far
4509 * this hang was only observed on Linux and Mac OS X.
4510 *
4511 * This is a workaround and needs to be solved properly.
4512 */
4513 if (pCtl->fReset)
4514 {
4515 uint64_t u64ResetTimeStop = RTTimeMilliTS();
4516
4517 if ((u64ResetTimeStop - pCtl->u64ResetTime) >= 10)
4518 {
4519 LogRel(("PIIX3 ATA LUN#%d: Async I/O thread probably stuck in operation, interrupting\n", s->iLUN));
4520 pCtl->u64ResetTime = u64ResetTimeStop;
4521 RTThreadPoke(pCtl->AsyncIOThread);
4522 }
4523 }
4524#endif
4525
4526 RTThreadYield();
4527
4528 {
4529 STAM_PROFILE_START(&pCtl->StatLockWait, a);
4530 PDMCritSectEnter(&pCtl->lock, VINF_SUCCESS);
4531 STAM_PROFILE_STOP(&pCtl->StatLockWait, a);
4532 }
4533
4534 val = s->uATARegStatus;
4535#else /* !IN_RING3 */
4536 /* Cannot yield CPU in raw-mode and ring-0 context. And switching
4537 * to host context for each and every busy status is too costly,
4538 * especially on SMP systems where we don't gain much by
4539 * yielding the CPU to someone else. */
4540 if (++cBusy >= 20)
4541 {
4542 cBusy = 0;
4543 return VINF_IOM_R3_IOPORT_READ;
4544 }
4545#endif /* !IN_RING3 */
4546 }
4547 else
4548 cBusy = 0;
4549 ataUnsetIRQ(s);
4550 break;
4551 }
4552 }
4553 Log2(("%s: LUN#%d addr=%#x val=%#04x\n", __FUNCTION__, s->iLUN, addr, val));
4554 *pu32 = val;
4555 return VINF_SUCCESS;
4556}
4557
4558
4559static uint32_t ataStatusRead(PATACONTROLLER pCtl, uint32_t addr)
4560{
4561 ATADevState *s = &pCtl->aIfs[pCtl->iSelectedIf];
4562 uint32_t val;
4563
4564 //@todo: The handler should not be even registered if there
4565 // is no device on an IDE channel.
4566 if (!pCtl->aIfs[0].pDrvBlock && !pCtl->aIfs[1].pDrvBlock)
4567 val = 0xff;
4568 else if (pCtl->iSelectedIf == 1 && !s->pDrvBlock)
4569 val = 0; /* Device 1 selected, Device 0 responding for it. */
4570 else
4571 val = s->uATARegStatus;
4572 Log2(("%s: addr=%#x val=%#04x\n", __FUNCTION__, addr, val));
4573 return val;
4574}
4575
4576static int ataControlWrite(PATACONTROLLER pCtl, uint32_t addr, uint32_t val)
4577{
4578#ifndef IN_RING3
4579 if ((val ^ pCtl->aIfs[0].uATARegDevCtl) & ATA_DEVCTL_RESET)
4580 return VINF_IOM_R3_IOPORT_WRITE; /* The RESET stuff is too complicated for RC+R0. */
4581#endif /* !IN_RING3 */
4582
4583 Log2(("%s: addr=%#x val=%#04x\n", __FUNCTION__, addr, val));
4584 /* RESET is common for both drives attached to a controller. */
4585 if ( !(pCtl->aIfs[0].uATARegDevCtl & ATA_DEVCTL_RESET)
4586 && (val & ATA_DEVCTL_RESET))
4587 {
4588#ifdef IN_RING3
4589 /* Software RESET low to high */
4590 int32_t uCmdWait0 = -1;
4591 int32_t uCmdWait1 = -1;
4592 uint64_t uNow = RTTimeNanoTS();
4593 if (pCtl->aIfs[0].u64CmdTS)
4594 uCmdWait0 = (uNow - pCtl->aIfs[0].u64CmdTS) / 1000;
4595 if (pCtl->aIfs[1].u64CmdTS)
4596 uCmdWait1 = (uNow - pCtl->aIfs[1].u64CmdTS) / 1000;
4597 LogRel(("PIIX3 ATA: Ctl#%d: RESET, DevSel=%d AIOIf=%d CmdIf0=%#04x (%d usec ago) CmdIf1=%#04x (%d usec ago)\n",
4598 ATACONTROLLER_IDX(pCtl), pCtl->iSelectedIf, pCtl->iAIOIf,
4599 pCtl->aIfs[0].uATARegCommand, uCmdWait0,
4600 pCtl->aIfs[1].uATARegCommand, uCmdWait1));
4601 pCtl->fReset = true;
4602 /* Everything must be done after the reset flag is set, otherwise
4603 * there are unavoidable races with the currently executing request
4604 * (which might just finish in the mean time). */
4605 pCtl->fChainedTransfer = false;
4606 for (uint32_t i = 0; i < RT_ELEMENTS(pCtl->aIfs); i++)
4607 {
4608 ataR3ResetDevice(&pCtl->aIfs[i]);
4609 /* The following cannot be done using ataSetStatusValue() since the
4610 * reset flag is already set, which suppresses all status changes. */
4611 pCtl->aIfs[i].uATARegStatus = ATA_STAT_BUSY | ATA_STAT_SEEK;
4612 Log2(("%s: LUN#%d status %#04x\n", __FUNCTION__, pCtl->aIfs[i].iLUN, pCtl->aIfs[i].uATARegStatus));
4613 pCtl->aIfs[i].uATARegError = 0x01;
4614 }
4615 ataR3AsyncIOClearRequests(pCtl);
4616 Log2(("%s: Ctl#%d: message to async I/O thread, resetA\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl)));
4617 if (val & ATA_DEVCTL_HOB)
4618 {
4619 val &= ~ATA_DEVCTL_HOB;
4620 Log2(("%s: ignored setting HOB\n", __FUNCTION__));
4621 }
4622
4623 /* Save the timestamp we started the reset. */
4624 pCtl->u64ResetTime = RTTimeMilliTS();
4625
4626 /* Issue the reset request now. */
4627 ataHCAsyncIOPutRequest(pCtl, &g_ataResetARequest);
4628#else /* !IN_RING3 */
4629 AssertMsgFailed(("RESET handling is too complicated for GC\n"));
4630#endif /* IN_RING3 */
4631 }
4632 else if ( (pCtl->aIfs[0].uATARegDevCtl & ATA_DEVCTL_RESET)
4633 && !(val & ATA_DEVCTL_RESET))
4634 {
4635#ifdef IN_RING3
4636 /* Software RESET high to low */
4637 Log(("%s: deasserting RESET\n", __FUNCTION__));
4638 Log2(("%s: Ctl#%d: message to async I/O thread, resetC\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl)));
4639 if (val & ATA_DEVCTL_HOB)
4640 {
4641 val &= ~ATA_DEVCTL_HOB;
4642 Log2(("%s: ignored setting HOB\n", __FUNCTION__));
4643 }
4644 ataHCAsyncIOPutRequest(pCtl, &g_ataResetCRequest);
4645#else /* !IN_RING3 */
4646 AssertMsgFailed(("RESET handling is too complicated for GC\n"));
4647#endif /* IN_RING3 */
4648 }
4649
4650 /* Change of interrupt disable flag. Update interrupt line if interrupt
4651 * is pending on the current interface. */
4652 if ( ((val ^ pCtl->aIfs[0].uATARegDevCtl) & ATA_DEVCTL_DISABLE_IRQ)
4653 && pCtl->aIfs[pCtl->iSelectedIf].fIrqPending)
4654 {
4655 if (!(val & ATA_DEVCTL_DISABLE_IRQ))
4656 {
4657 Log2(("%s: LUN#%d asserting IRQ (interrupt disable change)\n", __FUNCTION__, pCtl->aIfs[pCtl->iSelectedIf].iLUN));
4658 /* The BMDMA unit unconditionally sets BM_STATUS_INT if the
4659 * interrupt line is asserted. It monitors the line for a rising
4660 * edge. */
4661 pCtl->BmDma.u8Status |= BM_STATUS_INT;
4662 if (pCtl->irq == 16)
4663 PDMDevHlpPCISetIrq(CONTROLLER_2_DEVINS(pCtl), 0, 1);
4664 else
4665 PDMDevHlpISASetIrq(CONTROLLER_2_DEVINS(pCtl), pCtl->irq, 1);
4666 }
4667 else
4668 {
4669 Log2(("%s: LUN#%d deasserting IRQ (interrupt disable change)\n", __FUNCTION__, pCtl->aIfs[pCtl->iSelectedIf].iLUN));
4670 if (pCtl->irq == 16)
4671 PDMDevHlpPCISetIrq(CONTROLLER_2_DEVINS(pCtl), 0, 0);
4672 else
4673 PDMDevHlpISASetIrq(CONTROLLER_2_DEVINS(pCtl), pCtl->irq, 0);
4674 }
4675 }
4676
4677 if (val & ATA_DEVCTL_HOB)
4678 Log2(("%s: set HOB\n", __FUNCTION__));
4679
4680 pCtl->aIfs[0].uATARegDevCtl = val;
4681 pCtl->aIfs[1].uATARegDevCtl = val;
4682
4683 return VINF_SUCCESS;
4684}
4685
4686#if defined(IN_RING0) || defined(IN_RING3)
4687
4688static void ataHCPIOTransfer(PATACONTROLLER pCtl)
4689{
4690 ATADevState *s;
4691
4692 s = &pCtl->aIfs[pCtl->iAIOIf];
4693 Log3(("%s: if=%p\n", __FUNCTION__, s));
4694
4695 if (s->cbTotalTransfer && s->iIOBufferCur > s->iIOBufferEnd)
4696 {
4697# ifdef IN_RING3
4698 LogRel(("PIIX3 ATA: LUN#%d: %s data in the middle of a PIO transfer - VERY SLOW\n", s->iLUN, s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE ? "loading" : "storing"));
4699 /* Any guest OS that triggers this case has a pathetic ATA driver.
4700 * In a real system it would block the CPU via IORDY, here we do it
4701 * very similarly by not continuing with the current instruction
4702 * until the transfer to/from the storage medium is completed. */
4703 if (s->iSourceSink != ATAFN_SS_NULL)
4704 {
4705 bool fRedo;
4706 uint8_t status = s->uATARegStatus;
4707 ataSetStatusValue(s, ATA_STAT_BUSY);
4708 Log2(("%s: calling source/sink function\n", __FUNCTION__));
4709 fRedo = g_apfnSourceSinkFuncs[s->iSourceSink](s);
4710 pCtl->fRedo = fRedo;
4711 if (RT_UNLIKELY(fRedo))
4712 return;
4713 ataSetStatusValue(s, status);
4714 s->iIOBufferCur = 0;
4715 s->iIOBufferEnd = s->cbElementaryTransfer;
4716 }
4717# else
4718 AssertReleaseFailed();
4719# endif
4720 }
4721 if (s->cbTotalTransfer)
4722 {
4723 if (s->fATAPITransfer)
4724 ataHCPIOTransferLimitATAPI(s);
4725
4726 if (s->uTxDir == PDMBLOCKTXDIR_TO_DEVICE && s->cbElementaryTransfer > s->cbTotalTransfer)
4727 s->cbElementaryTransfer = s->cbTotalTransfer;
4728
4729 Log2(("%s: %s tx_size=%d elem_tx_size=%d index=%d end=%d\n",
4730 __FUNCTION__, s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE ? "T2I" : "I2T",
4731 s->cbTotalTransfer, s->cbElementaryTransfer,
4732 s->iIOBufferCur, s->iIOBufferEnd));
4733 ataHCPIOTransferStart(s, s->iIOBufferCur, s->cbElementaryTransfer);
4734 s->cbTotalTransfer -= s->cbElementaryTransfer;
4735 s->iIOBufferCur += s->cbElementaryTransfer;
4736
4737 if (s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE && s->cbElementaryTransfer > s->cbTotalTransfer)
4738 s->cbElementaryTransfer = s->cbTotalTransfer;
4739 }
4740 else
4741 ataHCPIOTransferStop(s);
4742}
4743
4744
4745DECLINLINE(void) ataHCPIOTransferFinish(PATACONTROLLER pCtl, ATADevState *s)
4746{
4747 /* Do not interfere with RESET processing if the PIO transfer finishes
4748 * while the RESET line is asserted. */
4749 if (pCtl->fReset)
4750 {
4751 Log2(("%s: Ctl#%d: suppressed continuing PIO transfer as RESET is active\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl)));
4752 return;
4753 }
4754
4755 if ( s->uTxDir == PDMBLOCKTXDIR_TO_DEVICE
4756 || ( s->iSourceSink != ATAFN_SS_NULL
4757 && s->iIOBufferCur >= s->iIOBufferEnd))
4758 {
4759 /* Need to continue the transfer in the async I/O thread. This is
4760 * the case for write operations or generally for not yet finished
4761 * transfers (some data might need to be read). */
4762 ataUnsetStatus(s, ATA_STAT_READY | ATA_STAT_DRQ);
4763 ataSetStatus(s, ATA_STAT_BUSY);
4764
4765 Log2(("%s: Ctl#%d: message to async I/O thread, continuing PIO transfer\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl)));
4766 ataHCAsyncIOPutRequest(pCtl, &g_ataPIORequest);
4767 }
4768 else
4769 {
4770 /* Either everything finished (though some data might still be pending)
4771 * or some data is pending before the next read is due. */
4772
4773 /* Continue a previously started transfer. */
4774 ataUnsetStatus(s, ATA_STAT_DRQ);
4775 ataSetStatus(s, ATA_STAT_READY);
4776
4777 if (s->cbTotalTransfer)
4778 {
4779 /* There is more to transfer, happens usually for large ATAPI
4780 * reads - the protocol limits the chunk size to 65534 bytes. */
4781 ataHCPIOTransfer(pCtl);
4782 ataHCSetIRQ(s);
4783 }
4784 else
4785 {
4786 Log2(("%s: Ctl#%d: skipping message to async I/O thread, ending PIO transfer\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl)));
4787 /* Finish PIO transfer. */
4788 ataHCPIOTransfer(pCtl);
4789 Assert(!pCtl->fRedo);
4790 }
4791 }
4792}
4793
4794#endif /* IN_RING0 || IN_RING3 */
4795
4796/**
4797 * Fallback for ataCopyPioData124 that handles unaligned and out of bounds cases.
4798 *
4799 * @param pIf The device interface to work with.
4800 * @param pbDst The destination buffer.
4801 * @param pbSrc The source buffer.
4802 * @param cbCopy The number of bytes to copy, either 1, 2 or 4 bytes.
4803 */
4804DECL_NO_INLINE(static, void) ataCopyPioData124Slow(ATADevState *pIf, uint8_t *pbDst, const uint8_t *pbSrc, uint32_t cbCopy)
4805{
4806 uint32_t const offStart = pIf->iIOBufferPIODataStart;
4807 uint32_t const offNext = offStart + cbCopy;
4808
4809 if (offStart + cbCopy > pIf->cbIOBuffer)
4810 {
4811 Log(("%s: cbCopy=%#x offStart=%#x cbIOBuffer=%#x offNext=%#x (iIOBufferPIODataEnd=%#x)\n",
4812 __FUNCTION__, cbCopy, offStart, pIf->cbIOBuffer, offNext, pIf->iIOBufferPIODataEnd));
4813 if (offStart < pIf->cbIOBuffer)
4814 cbCopy = pIf->cbIOBuffer - offStart;
4815 else
4816 cbCopy = 0;
4817 }
4818
4819 switch (cbCopy)
4820 {
4821 case 4: pbDst[3] = pbSrc[3]; /* fall thru */
4822 case 3: pbDst[2] = pbSrc[2]; /* fall thru */
4823 case 2: pbDst[1] = pbSrc[1]; /* fall thru */
4824 case 1: pbDst[0] = pbSrc[0]; /* fall thru */
4825 case 0: break;
4826 default: AssertFailed(); /* impossible */
4827 }
4828
4829 pIf->iIOBufferPIODataStart = offNext;
4830
4831}
4832
4833
4834/**
4835 * Work for ataDataWrite & ataDataRead that copies data without using memcpy.
4836 *
4837 * This also updates pIf->iIOBufferPIODataStart.
4838 *
4839 * The two buffers are either stack (32-bit aligned) or somewhere within
4840 * pIf->pbIOBuffer.
4841 *
4842 * @param pIf The device interface to work with.
4843 * @param pbDst The destination buffer.
4844 * @param pbSrc The source buffer.
4845 * @param cbCopy The number of bytes to copy, either 1, 2 or 4 bytes.
4846 */
4847DECLINLINE(void) ataCopyPioData124(ATADevState *pIf, uint8_t *pbDst, const uint8_t *pbSrc, uint32_t cbCopy)
4848{
4849 /*
4850 * Quick bounds checking can be done by checking that the pbIOBuffer offset
4851 * (iIOBufferPIODataStart) is aligned at the transfer size (which is ASSUMED
4852 * to be 1, 2 or 4). However, since we're paranoid and don't currently
4853 * trust iIOBufferPIODataEnd to be within bounds, we current check against the
4854 * IO buffer size too.
4855 */
4856 Assert(cbCopy == 1 || cbCopy == 2 || cbCopy == 4);
4857 uint32_t const offStart = pIf->iIOBufferPIODataStart;
4858 if (RT_LIKELY( !(offStart & (cbCopy - 1))
4859 && offStart + cbCopy <= pIf->cbIOBuffer))
4860 {
4861 switch (cbCopy)
4862 {
4863 case 4: *(uint32_t *)pbDst = *(uint32_t const *)pbSrc; break;
4864 case 2: *(uint16_t *)pbDst = *(uint16_t const *)pbSrc; break;
4865 case 1: *pbDst = *pbSrc; break;
4866 }
4867 pIf->iIOBufferPIODataStart = offStart + cbCopy;
4868 }
4869 else
4870 ataCopyPioData124Slow(pIf, pbDst, pbSrc, cbCopy);
4871}
4872
4873
4874/**
4875 * Port I/O Handler for primary port range OUT operations.
4876 * @see FNIOMIOPORTOUT for details.
4877 */
4878PDMBOTHCBDECL(int) ataIOPortWrite1Data(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t u32, unsigned cb)
4879{
4880 uint32_t i = (uint32_t)(uintptr_t)pvUser;
4881 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
4882 PATACONTROLLER pCtl = &pThis->aCts[i];
4883
4884 Assert(i < 2);
4885 Assert(Port == pCtl->IOPortBase1);
4886 Assert(cb == 2 || cb == 4); /* Writes to the data port may be 16-bit or 32-bit. */
4887
4888 int rc = PDMCritSectEnter(&pCtl->lock, VINF_IOM_R3_IOPORT_WRITE);
4889 if (rc == VINF_SUCCESS)
4890 {
4891 ATADevState *s = &pCtl->aIfs[pCtl->iSelectedIf];
4892
4893 if (s->iIOBufferPIODataStart < s->iIOBufferPIODataEnd)
4894 {
4895 Assert(s->uTxDir == PDMBLOCKTXDIR_TO_DEVICE);
4896 uint8_t *pbDst = s->CTX_SUFF(pbIOBuffer) + s->iIOBufferPIODataStart;
4897 uint8_t const *pbSrc = (uint8_t const *)&u32;
4898
4899#ifdef IN_RC
4900 /* Raw-mode: The ataHCPIOTransfer following the last transfer unit
4901 requires I/O thread signalling, we must go to ring-3 for that. */
4902 if (s->iIOBufferPIODataStart + cb < s->iIOBufferPIODataEnd)
4903 ataCopyPioData124(s, pbDst, pbSrc, cb);
4904 else
4905 rc = VINF_IOM_R3_IOPORT_WRITE;
4906
4907#elif defined(IN_RING0)
4908 /* Ring-0: We can do I/O thread signalling here, however for paranoid reasons
4909 triggered by a special case in ataHCPIOTransferFinish, we take extra care here. */
4910 if (s->iIOBufferPIODataStart + cb < s->iIOBufferPIODataEnd)
4911 ataCopyPioData124(s, pbDst, pbSrc, cb);
4912 else if (s->uTxDir == PDMBLOCKTXDIR_TO_DEVICE) /* paranoia */
4913 {
4914 ataCopyPioData124(s, pbDst, pbSrc, cb);
4915 ataHCPIOTransferFinish(pCtl, s);
4916 }
4917 else
4918 {
4919 Log(("%s: Unexpected\n",__FUNCTION__));
4920 rc = VINF_IOM_R3_IOPORT_WRITE;
4921 }
4922
4923#else /* IN_RING 3*/
4924 ataCopyPioData124(s, pbDst, pbSrc, cb);
4925 if (s->iIOBufferPIODataStart >= s->iIOBufferPIODataEnd)
4926 ataHCPIOTransferFinish(pCtl, s);
4927#endif /* IN_RING 3*/
4928 }
4929 else
4930 Log2(("%s: DUMMY data\n", __FUNCTION__));
4931
4932 Log3(("%s: addr=%#x val=%.*Rhxs rc=%d\n", __FUNCTION__, Port, cb, &u32, rc));
4933 PDMCritSectLeave(&pCtl->lock);
4934 }
4935 else
4936 Log3(("%s: addr=%#x -> %d\n", __FUNCTION__, Port, rc));
4937 return rc;
4938}
4939
4940
4941/**
4942 * Port I/O Handler for primary port range IN operations.
4943 * @see FNIOMIOPORTIN for details.
4944 */
4945PDMBOTHCBDECL(int) ataIOPortRead1Data(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t *pu32, unsigned cb)
4946{
4947 uint32_t i = (uint32_t)(uintptr_t)pvUser;
4948 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
4949 PATACONTROLLER pCtl = &pThis->aCts[i];
4950
4951 Assert(i < 2);
4952 Assert(Port == pCtl->IOPortBase1);
4953
4954 /* Reads from the data register may be 16-bit or 32-bit. Byte accesses are
4955 upgraded to word. */
4956 Assert(cb == 1 || cb == 2 || cb == 4);
4957 uint32_t cbActual = cb != 1 ? cb : 2;
4958 *pu32 = 0;
4959
4960 int rc = PDMCritSectEnter(&pCtl->lock, VINF_IOM_R3_IOPORT_READ);
4961 if (rc == VINF_SUCCESS)
4962 {
4963 ATADevState *s = &pCtl->aIfs[pCtl->iSelectedIf];
4964
4965 if (s->iIOBufferPIODataStart < s->iIOBufferPIODataEnd)
4966 {
4967 Assert(s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE);
4968 uint8_t const *pbSrc = s->CTX_SUFF(pbIOBuffer) + s->iIOBufferPIODataStart;
4969 uint8_t *pbDst = (uint8_t *)pu32;
4970
4971#ifdef IN_RC
4972 /* All but the last transfer unit is simple enough for RC, but
4973 * sending a request to the async IO thread is too complicated. */
4974 if (s->iIOBufferPIODataStart + cbActual < s->iIOBufferPIODataEnd)
4975 ataCopyPioData124(s, pbDst, pbSrc, cbActual);
4976 else
4977 rc = VINF_IOM_R3_IOPORT_READ;
4978
4979#elif defined(IN_RING0)
4980 /* Ring-0: We can do I/O thread signalling here. However there is one
4981 case in ataHCPIOTransfer that does a LogRel and would (but not from
4982 here) call directly into the driver code. We detect that odd case
4983 here cand return to ring-3 to handle it. */
4984 if (s->iIOBufferPIODataStart + cbActual < s->iIOBufferPIODataEnd)
4985 ataCopyPioData124(s, pbDst, pbSrc, cbActual);
4986 else if ( s->cbTotalTransfer == 0
4987 || s->iSourceSink != ATAFN_SS_NULL
4988 || s->iIOBufferCur <= s->iIOBufferEnd)
4989 {
4990 ataCopyPioData124(s, pbDst, pbSrc, cbActual);
4991 ataHCPIOTransferFinish(pCtl, s);
4992 }
4993 else
4994 {
4995 Log(("%s: Unexpected\n",__FUNCTION__));
4996 rc = VINF_IOM_R3_IOPORT_READ;
4997 }
4998
4999#else /* IN_RING3 */
5000 ataCopyPioData124(s, pbDst, pbSrc, cbActual);
5001 if (s->iIOBufferPIODataStart >= s->iIOBufferPIODataEnd)
5002 ataHCPIOTransferFinish(pCtl, s);
5003#endif /* IN_RING3 */
5004
5005 /* Just to be on the safe side (caller takes care of this, really). */
5006 if (cb == 1)
5007 *pu32 &= 0xff;
5008 }
5009 else
5010 {
5011 Log2(("%s: DUMMY data\n", __FUNCTION__));
5012 memset(pu32, 0xff, cb);
5013 }
5014 Log3(("%s: addr=%#x val=%.*Rhxs rc=%d\n", __FUNCTION__, Port, cb, pu32, rc));
5015
5016 PDMCritSectLeave(&pCtl->lock);
5017 }
5018 else
5019 Log3(("%s: addr=%#x -> %d\n", __FUNCTION__, Port, rc));
5020
5021 return rc;
5022}
5023
5024
5025/**
5026 * Port I/O Handler for primary port range IN string operations.
5027 * @see FNIOMIOPORTINSTRING for details.
5028 */
5029PDMBOTHCBDECL(int) ataIOPortReadStr1Data(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint8_t *pbDst,
5030 uint32_t *pcTransfers, unsigned cb)
5031{
5032 uint32_t i = (uint32_t)(uintptr_t)pvUser;
5033 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
5034 PATACONTROLLER pCtl = &pThis->aCts[i];
5035
5036 Assert(i < 2);
5037 Assert(Port == pCtl->IOPortBase1);
5038 Assert(*pcTransfers > 0);
5039
5040 int rc;
5041 if (cb == 2 || cb == 4)
5042 {
5043 rc = PDMCritSectEnter(&pCtl->lock, VINF_IOM_R3_IOPORT_READ);
5044 if (rc == VINF_SUCCESS)
5045 {
5046 ATADevState *s = &pCtl->aIfs[pCtl->iSelectedIf];
5047
5048 uint32_t const offStart = s->iIOBufferPIODataStart;
5049 if (offStart < s->iIOBufferPIODataEnd)
5050 {
5051 /*
5052 * Figure how much we can copy. Usually it's the same as the request.
5053 * The last transfer unit cannot be handled in RC, as it involves
5054 * thread communication. In R0 we let the non-string callback handle it,
5055 * and ditto for overflows/dummy data.
5056 */
5057 uint32_t cAvailable = (s->iIOBufferPIODataEnd - offStart) / cb;
5058#ifndef IN_RING3
5059 if (cAvailable > 0)
5060 cAvailable--;
5061#endif
5062 uint32_t const cRequested = *pcTransfers;
5063 if (cAvailable > cRequested)
5064 cAvailable = cRequested;
5065 uint32_t const cbTransfer = cAvailable * cb;
5066 if ( offStart + cbTransfer <= s->cbIOBuffer
5067 && cbTransfer > 0)
5068 {
5069 /*
5070 * Do the transfer.
5071 */
5072 uint8_t const *pbSrc = s->CTX_SUFF(pbIOBuffer) + offStart;
5073 memcpy(pbDst, pbSrc, cbTransfer);
5074 Log3(("%s: addr=%#x cb=%#x cbTransfer=%#x val=%.*Rhxd\n",
5075 __FUNCTION__, Port, cb, cbTransfer, cbTransfer, pbSrc));
5076 s->iIOBufferPIODataStart = offStart + cbTransfer;
5077
5078#ifdef IN_RING3
5079 if (s->iIOBufferPIODataStart >= s->iIOBufferPIODataEnd)
5080 ataHCPIOTransferFinish(pCtl, s);
5081#endif
5082 *pcTransfers = cRequested - cAvailable;
5083 }
5084 else
5085 Log2(("%s: DUMMY/Overflow!\n", __FUNCTION__));
5086 }
5087 else
5088 {
5089 /*
5090 * Dummy read (shouldn't happen) return 0xff like the non-string handler.
5091 */
5092 Log2(("%s: DUMMY data (%#x bytes)\n", __FUNCTION__, *pcTransfers * cb));
5093 memset(pbDst, 0xff, *pcTransfers * cb);
5094 *pcTransfers = 0;
5095 }
5096
5097 PDMCritSectLeave(&pCtl->lock);
5098 }
5099 }
5100 /*
5101 * Let the non-string I/O callback handle 1 byte reads.
5102 */
5103 else
5104 {
5105 Log2(("%s: 1 byte read (%#x transfers)\n", *pcTransfers));
5106 AssertFailed();
5107 rc = VINF_SUCCESS;
5108 }
5109 return rc;
5110}
5111
5112
5113/**
5114 * Port I/O Handler for primary port range OUT string operations.
5115 * @see FNIOMIOPORTOUTSTRING for details.
5116 */
5117PDMBOTHCBDECL(int) ataIOPortWriteStr1Data(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint8_t const *pbSrc,
5118 uint32_t *pcTransfers, unsigned cb)
5119{
5120 uint32_t i = (uint32_t)(uintptr_t)pvUser;
5121 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
5122 PATACONTROLLER pCtl = &pThis->aCts[i];
5123
5124 Assert(i < 2);
5125 Assert(Port == pCtl->IOPortBase1);
5126 Assert(*pcTransfers > 0);
5127
5128 int rc;
5129 if (cb == 2 || cb == 4)
5130 {
5131 rc = PDMCritSectEnter(&pCtl->lock, VINF_IOM_R3_IOPORT_WRITE);
5132 if (rc == VINF_SUCCESS)
5133 {
5134 ATADevState *s = &pCtl->aIfs[pCtl->iSelectedIf];
5135
5136 uint32_t const offStart = s->iIOBufferPIODataStart;
5137 if (offStart < s->iIOBufferPIODataEnd)
5138 {
5139 /*
5140 * Figure how much we can copy. Usually it's the same as the request.
5141 * The last transfer unit cannot be handled in RC, as it involves
5142 * thread communication. In R0 we let the non-string callback handle it,
5143 * and ditto for overflows/dummy data.
5144 */
5145 uint32_t cAvailable = (s->iIOBufferPIODataEnd - offStart) / cb;
5146#ifndef IN_RING3
5147 if (cAvailable)
5148 cAvailable--;
5149#endif
5150 uint32_t const cRequested = *pcTransfers;
5151 if (cAvailable > cRequested)
5152 cAvailable = cRequested;
5153 uint32_t const cbTransfer = cAvailable * cb;
5154 if ( offStart + cbTransfer <= s->cbIOBuffer
5155 && cbTransfer)
5156 {
5157 /*
5158 * Do the transfer.
5159 */
5160 void *pvDst = s->CTX_SUFF(pbIOBuffer) + offStart;
5161 memcpy(pvDst, pbSrc, cbTransfer);
5162 Log3(("%s: addr=%#x val=%.*Rhxs\n", __FUNCTION__, Port, cbTransfer, pvDst));
5163 s->iIOBufferPIODataStart = offStart + cbTransfer;
5164
5165#ifdef IN_RING3
5166 if (s->iIOBufferPIODataStart >= s->iIOBufferPIODataEnd)
5167 ataHCPIOTransferFinish(pCtl, s);
5168#endif
5169 *pcTransfers = cRequested - cAvailable;
5170 }
5171 else
5172 Log2(("%s: DUMMY/Overflow!\n", __FUNCTION__));
5173 }
5174 else
5175 {
5176 Log2(("%s: DUMMY data (%#x bytes)\n", __FUNCTION__, *pcTransfers * cb));
5177 *pcTransfers = 0;
5178 }
5179
5180 PDMCritSectLeave(&pCtl->lock);
5181 }
5182 }
5183 /*
5184 * Let the non-string I/O callback handle 1 byte reads.
5185 */
5186 else
5187 {
5188 Log2(("%s: 1 byte write (%#x transfers)\n", *pcTransfers));
5189 AssertFailed();
5190 rc = VINF_SUCCESS;
5191 }
5192
5193 return rc;
5194}
5195
5196
5197#ifdef IN_RING3
5198
5199static void ataR3DMATransferStop(ATADevState *s)
5200{
5201 s->cbTotalTransfer = 0;
5202 s->cbElementaryTransfer = 0;
5203 s->iBeginTransfer = ATAFN_BT_NULL;
5204 s->iSourceSink = ATAFN_SS_NULL;
5205}
5206
5207
5208/**
5209 * Perform the entire DMA transfer in one go (unless a source/sink operation
5210 * has to be redone or a RESET comes in between). Unlike the PIO counterpart
5211 * this function cannot handle empty transfers.
5212 *
5213 * @param pCtl Controller for which to perform the transfer.
5214 */
5215static void ataR3DMATransfer(PATACONTROLLER pCtl)
5216{
5217 PPDMDEVINS pDevIns = CONTROLLER_2_DEVINS(pCtl);
5218 ATADevState *s = &pCtl->aIfs[pCtl->iAIOIf];
5219 bool fRedo;
5220 RTGCPHYS32 pDesc;
5221 uint32_t cbTotalTransfer, cbElementaryTransfer;
5222 uint32_t iIOBufferCur, iIOBufferEnd;
5223 uint32_t dmalen;
5224 PDMBLOCKTXDIR uTxDir;
5225 bool fLastDesc = false;
5226
5227 Assert(sizeof(BMDMADesc) == 8);
5228
5229 fRedo = pCtl->fRedo;
5230 if (RT_LIKELY(!fRedo))
5231 Assert(s->cbTotalTransfer);
5232 uTxDir = (PDMBLOCKTXDIR)s->uTxDir;
5233 cbTotalTransfer = s->cbTotalTransfer;
5234 cbElementaryTransfer = s->cbElementaryTransfer;
5235 iIOBufferCur = s->iIOBufferCur;
5236 iIOBufferEnd = s->iIOBufferEnd;
5237
5238 /* The DMA loop is designed to hold the lock only when absolutely
5239 * necessary. This avoids long freezes should the guest access the
5240 * ATA registers etc. for some reason. */
5241 PDMCritSectLeave(&pCtl->lock);
5242
5243 Log2(("%s: %s tx_size=%d elem_tx_size=%d index=%d end=%d\n",
5244 __FUNCTION__, uTxDir == PDMBLOCKTXDIR_FROM_DEVICE ? "T2I" : "I2T",
5245 cbTotalTransfer, cbElementaryTransfer,
5246 iIOBufferCur, iIOBufferEnd));
5247 for (pDesc = pCtl->pFirstDMADesc; pDesc <= pCtl->pLastDMADesc; pDesc += sizeof(BMDMADesc))
5248 {
5249 BMDMADesc DMADesc;
5250 RTGCPHYS32 pBuffer;
5251 uint32_t cbBuffer;
5252
5253 if (RT_UNLIKELY(fRedo))
5254 {
5255 pBuffer = pCtl->pRedoDMABuffer;
5256 cbBuffer = pCtl->cbRedoDMABuffer;
5257 fLastDesc = pCtl->fRedoDMALastDesc;
5258 }
5259 else
5260 {
5261 PDMDevHlpPhysRead(pDevIns, pDesc, &DMADesc, sizeof(BMDMADesc));
5262 pBuffer = RT_LE2H_U32(DMADesc.pBuffer);
5263 cbBuffer = RT_LE2H_U32(DMADesc.cbBuffer);
5264 fLastDesc = !!(cbBuffer & 0x80000000);
5265 cbBuffer &= 0xfffe;
5266 if (cbBuffer == 0)
5267 cbBuffer = 0x10000;
5268 if (cbBuffer > cbTotalTransfer)
5269 cbBuffer = cbTotalTransfer;
5270 }
5271
5272 while (RT_UNLIKELY(fRedo) || (cbBuffer && cbTotalTransfer))
5273 {
5274 if (RT_LIKELY(!fRedo))
5275 {
5276 dmalen = RT_MIN(cbBuffer, iIOBufferEnd - iIOBufferCur);
5277 Log2(("%s: DMA desc %#010x: addr=%#010x size=%#010x orig_size=%#010x\n", __FUNCTION__,
5278 (int)pDesc, pBuffer, cbBuffer, RT_LE2H_U32(DMADesc.cbBuffer) & 0xfffe));
5279
5280 PCIATAState *pATAState = PDMINS_2_DATA(pDevIns, PCIATAState *);
5281 AssertPtr(pATAState);
5282 if (uTxDir == PDMBLOCKTXDIR_FROM_DEVICE)
5283 PDMDevHlpPCIPhysWrite(pDevIns, pBuffer, s->CTX_SUFF(pbIOBuffer) + iIOBufferCur, dmalen);
5284 else
5285 PDMDevHlpPCIPhysRead(pDevIns, pBuffer, s->CTX_SUFF(pbIOBuffer) + iIOBufferCur, dmalen);
5286
5287 iIOBufferCur += dmalen;
5288 cbTotalTransfer -= dmalen;
5289 cbBuffer -= dmalen;
5290 pBuffer += dmalen;
5291 }
5292 if ( iIOBufferCur == iIOBufferEnd
5293 && (uTxDir == PDMBLOCKTXDIR_TO_DEVICE || cbTotalTransfer))
5294 {
5295 if (uTxDir == PDMBLOCKTXDIR_FROM_DEVICE && cbElementaryTransfer > cbTotalTransfer)
5296 cbElementaryTransfer = cbTotalTransfer;
5297
5298 {
5299 STAM_PROFILE_START(&pCtl->StatLockWait, a);
5300 PDMCritSectEnter(&pCtl->lock, VINF_SUCCESS);
5301 STAM_PROFILE_STOP(&pCtl->StatLockWait, a);
5302 }
5303
5304 /* The RESET handler could have cleared the DMA transfer
5305 * state (since we didn't hold the lock until just now
5306 * the guest can continue in parallel). If so, the state
5307 * is already set up so the loop is exited immediately. */
5308 if (s->iSourceSink != ATAFN_SS_NULL)
5309 {
5310 s->iIOBufferCur = iIOBufferCur;
5311 s->iIOBufferEnd = iIOBufferEnd;
5312 s->cbElementaryTransfer = cbElementaryTransfer;
5313 s->cbTotalTransfer = cbTotalTransfer;
5314 Log2(("%s: calling source/sink function\n", __FUNCTION__));
5315 fRedo = g_apfnSourceSinkFuncs[s->iSourceSink](s);
5316 if (RT_UNLIKELY(fRedo))
5317 {
5318 pCtl->pFirstDMADesc = pDesc;
5319 pCtl->pRedoDMABuffer = pBuffer;
5320 pCtl->cbRedoDMABuffer = cbBuffer;
5321 pCtl->fRedoDMALastDesc = fLastDesc;
5322 }
5323 else
5324 {
5325 cbTotalTransfer = s->cbTotalTransfer;
5326 cbElementaryTransfer = s->cbElementaryTransfer;
5327
5328 if (uTxDir == PDMBLOCKTXDIR_TO_DEVICE && cbElementaryTransfer > cbTotalTransfer)
5329 cbElementaryTransfer = cbTotalTransfer;
5330 iIOBufferCur = 0;
5331 iIOBufferEnd = cbElementaryTransfer;
5332 }
5333 pCtl->fRedo = fRedo;
5334 }
5335 else
5336 {
5337 /* This forces the loop to exit immediately. */
5338 pDesc = pCtl->pLastDMADesc + 1;
5339 }
5340
5341 PDMCritSectLeave(&pCtl->lock);
5342 if (RT_UNLIKELY(fRedo))
5343 break;
5344 }
5345 }
5346
5347 if (RT_UNLIKELY(fRedo))
5348 break;
5349
5350 /* end of transfer */
5351 if (!cbTotalTransfer || fLastDesc)
5352 break;
5353
5354 {
5355 STAM_PROFILE_START(&pCtl->StatLockWait, a);
5356 PDMCritSectEnter(&pCtl->lock, VINF_SUCCESS);
5357 STAM_PROFILE_STOP(&pCtl->StatLockWait, a);
5358 }
5359
5360 if (!(pCtl->BmDma.u8Cmd & BM_CMD_START) || pCtl->fReset)
5361 {
5362 LogRel(("PIIX3 ATA: Ctl#%d: ABORT DMA%s\n", ATACONTROLLER_IDX(pCtl), pCtl->fReset ? " due to RESET" : ""));
5363 if (!pCtl->fReset)
5364 ataR3DMATransferStop(s);
5365 /* This forces the loop to exit immediately. */
5366 pDesc = pCtl->pLastDMADesc + 1;
5367 }
5368
5369 PDMCritSectLeave(&pCtl->lock);
5370 }
5371
5372 {
5373 STAM_PROFILE_START(&pCtl->StatLockWait, a);
5374 PDMCritSectEnter(&pCtl->lock, VINF_SUCCESS);
5375 STAM_PROFILE_STOP(&pCtl->StatLockWait, a);
5376 }
5377
5378 if (RT_UNLIKELY(fRedo))
5379 return;
5380
5381 if (fLastDesc)
5382 pCtl->BmDma.u8Status &= ~BM_STATUS_DMAING;
5383 s->cbTotalTransfer = cbTotalTransfer;
5384 s->cbElementaryTransfer = cbElementaryTransfer;
5385 s->iIOBufferCur = iIOBufferCur;
5386 s->iIOBufferEnd = iIOBufferEnd;
5387}
5388
5389/**
5390 * Signal PDM that we're idle (if we actually are).
5391 *
5392 * @param pCtl The controller.
5393 */
5394static void ataR3AsyncSignalIdle(PATACONTROLLER pCtl)
5395{
5396 /*
5397 * Take the lock here and recheck the idle indicator to avoid
5398 * unnecessary work and racing ataR3WaitForAsyncIOIsIdle.
5399 */
5400 int rc = PDMCritSectEnter(&pCtl->AsyncIORequestLock, VINF_SUCCESS);
5401 AssertRC(rc);
5402
5403 if ( pCtl->fSignalIdle
5404 && ataR3AsyncIOIsIdle(pCtl, false /*fStrict*/))
5405 {
5406 PDMDevHlpAsyncNotificationCompleted(pCtl->pDevInsR3);
5407 RTThreadUserSignal(pCtl->AsyncIOThread); /* for ataR3Construct/ataR3ResetCommon. */
5408 }
5409
5410 rc = PDMCritSectLeave(&pCtl->AsyncIORequestLock);
5411 AssertRC(rc);
5412}
5413
5414/**
5415 * Async I/O thread for an interface.
5416 *
5417 * Once upon a time this was readable code with several loops and a different
5418 * semaphore for each purpose. But then came the "how can one save the state in
5419 * the middle of a PIO transfer" question. The solution was to use an ASM,
5420 * which is what's there now.
5421 */
5422static DECLCALLBACK(int) ataR3AsyncIOThread(RTTHREAD ThreadSelf, void *pvUser)
5423{
5424 const ATARequest *pReq;
5425 uint64_t u64TS = 0; /* shut up gcc */
5426 uint64_t uWait;
5427 int rc = VINF_SUCCESS;
5428 PATACONTROLLER pCtl = (PATACONTROLLER)pvUser;
5429 ATADevState *s;
5430
5431 pReq = NULL;
5432 pCtl->fChainedTransfer = false;
5433 while (!pCtl->fShutdown)
5434 {
5435 /* Keep this thread from doing anything as long as EMT is suspended. */
5436 while (pCtl->fRedoIdle)
5437 {
5438 if (pCtl->fSignalIdle)
5439 ataR3AsyncSignalIdle(pCtl);
5440 rc = RTSemEventWait(pCtl->SuspendIOSem, RT_INDEFINITE_WAIT);
5441 /* Continue if we got a signal by RTThreadPoke().
5442 * We will get notified if there is a request to process.
5443 */
5444 if (RT_UNLIKELY(rc == VERR_INTERRUPTED))
5445 continue;
5446 if (RT_FAILURE(rc) || pCtl->fShutdown)
5447 break;
5448
5449 pCtl->fRedoIdle = false;
5450 }
5451
5452 /* Wait for work. */
5453 while (pReq == NULL)
5454 {
5455 if (pCtl->fSignalIdle)
5456 ataR3AsyncSignalIdle(pCtl);
5457 rc = SUPSemEventWaitNoResume(pCtl->pSupDrvSession, pCtl->hAsyncIOSem, RT_INDEFINITE_WAIT);
5458 /* Continue if we got a signal by RTThreadPoke().
5459 * We will get notified if there is a request to process.
5460 */
5461 if (RT_UNLIKELY(rc == VERR_INTERRUPTED))
5462 continue;
5463 if (RT_FAILURE(rc) || RT_UNLIKELY(pCtl->fShutdown))
5464 break;
5465
5466 pReq = ataR3AsyncIOGetCurrentRequest(pCtl);
5467 }
5468
5469 if (RT_FAILURE(rc) || pCtl->fShutdown)
5470 break;
5471
5472 if (pReq == NULL)
5473 continue;
5474
5475 ATAAIO ReqType = pReq->ReqType;
5476
5477 Log2(("%s: Ctl#%d: state=%d, req=%d\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl), pCtl->uAsyncIOState, ReqType));
5478 if (pCtl->uAsyncIOState != ReqType)
5479 {
5480 /* The new state is not the state that was expected by the normal
5481 * state changes. This is either a RESET/ABORT or there's something
5482 * really strange going on. */
5483 if ( (pCtl->uAsyncIOState == ATA_AIO_PIO || pCtl->uAsyncIOState == ATA_AIO_DMA)
5484 && (ReqType == ATA_AIO_PIO || ReqType == ATA_AIO_DMA))
5485 {
5486 /* Incorrect sequence of PIO/DMA states. Dump request queue. */
5487 ataR3AsyncIODumpRequests(pCtl);
5488 }
5489 AssertReleaseMsg(ReqType == ATA_AIO_RESET_ASSERTED || ReqType == ATA_AIO_RESET_CLEARED || ReqType == ATA_AIO_ABORT || pCtl->uAsyncIOState == ReqType, ("I/O state inconsistent: state=%d request=%d\n", pCtl->uAsyncIOState, ReqType));
5490 }
5491
5492 /* Do our work. */
5493 {
5494 STAM_PROFILE_START(&pCtl->StatLockWait, a);
5495 PDMCritSectEnter(&pCtl->lock, VINF_SUCCESS);
5496 STAM_PROFILE_STOP(&pCtl->StatLockWait, a);
5497 }
5498
5499 if (pCtl->uAsyncIOState == ATA_AIO_NEW && !pCtl->fChainedTransfer)
5500 {
5501 u64TS = RTTimeNanoTS();
5502#if defined(DEBUG) || defined(VBOX_WITH_STATISTICS)
5503 STAM_PROFILE_ADV_START(&pCtl->StatAsyncTime, a);
5504#endif
5505 }
5506
5507 switch (ReqType)
5508 {
5509 case ATA_AIO_NEW:
5510
5511 pCtl->iAIOIf = pReq->u.t.iIf;
5512 s = &pCtl->aIfs[pCtl->iAIOIf];
5513 s->cbTotalTransfer = pReq->u.t.cbTotalTransfer;
5514 s->uTxDir = pReq->u.t.uTxDir;
5515 s->iBeginTransfer = pReq->u.t.iBeginTransfer;
5516 s->iSourceSink = pReq->u.t.iSourceSink;
5517 s->iIOBufferEnd = 0;
5518 s->u64CmdTS = u64TS;
5519
5520 if (s->fATAPI)
5521 {
5522 if (pCtl->fChainedTransfer)
5523 {
5524 /* Only count the actual transfers, not the PIO
5525 * transfer of the ATAPI command bytes. */
5526 if (s->fDMA)
5527 STAM_REL_COUNTER_INC(&s->StatATAPIDMA);
5528 else
5529 STAM_REL_COUNTER_INC(&s->StatATAPIPIO);
5530 }
5531 }
5532 else
5533 {
5534 if (s->fDMA)
5535 STAM_REL_COUNTER_INC(&s->StatATADMA);
5536 else
5537 STAM_REL_COUNTER_INC(&s->StatATAPIO);
5538 }
5539
5540 pCtl->fChainedTransfer = false;
5541
5542 if (s->iBeginTransfer != ATAFN_BT_NULL)
5543 {
5544 Log2(("%s: Ctl#%d: calling begin transfer function\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl)));
5545 g_apfnBeginTransFuncs[s->iBeginTransfer](s);
5546 s->iBeginTransfer = ATAFN_BT_NULL;
5547 if (s->uTxDir != PDMBLOCKTXDIR_FROM_DEVICE)
5548 s->iIOBufferEnd = s->cbElementaryTransfer;
5549 }
5550 else
5551 {
5552 s->cbElementaryTransfer = s->cbTotalTransfer;
5553 s->iIOBufferEnd = s->cbTotalTransfer;
5554 }
5555 s->iIOBufferCur = 0;
5556
5557 if (s->uTxDir != PDMBLOCKTXDIR_TO_DEVICE)
5558 {
5559 if (s->iSourceSink != ATAFN_SS_NULL)
5560 {
5561 bool fRedo;
5562 Log2(("%s: Ctl#%d: calling source/sink function\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl)));
5563 fRedo = g_apfnSourceSinkFuncs[s->iSourceSink](s);
5564 pCtl->fRedo = fRedo;
5565 if (RT_UNLIKELY(fRedo && !pCtl->fReset))
5566 {
5567 /* Operation failed at the initial transfer, restart
5568 * everything from scratch by resending the current
5569 * request. Occurs very rarely, not worth optimizing. */
5570 LogRel(("%s: Ctl#%d: redo entire operation\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl)));
5571 ataHCAsyncIOPutRequest(pCtl, pReq);
5572 break;
5573 }
5574 }
5575 else
5576 ataR3CmdOK(s, 0);
5577 s->iIOBufferEnd = s->cbElementaryTransfer;
5578
5579 }
5580
5581 /* Do not go into the transfer phase if RESET is asserted.
5582 * The CritSect is released while waiting for the host OS
5583 * to finish the I/O, thus RESET is possible here. Most
5584 * important: do not change uAsyncIOState. */
5585 if (pCtl->fReset)
5586 break;
5587
5588 if (s->fDMA)
5589 {
5590 if (s->cbTotalTransfer)
5591 {
5592 ataSetStatus(s, ATA_STAT_DRQ);
5593
5594 pCtl->uAsyncIOState = ATA_AIO_DMA;
5595 /* If BMDMA is already started, do the transfer now. */
5596 if (pCtl->BmDma.u8Cmd & BM_CMD_START)
5597 {
5598 Log2(("%s: Ctl#%d: message to async I/O thread, continuing DMA transfer immediately\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl)));
5599 ataHCAsyncIOPutRequest(pCtl, &g_ataDMARequest);
5600 }
5601 }
5602 else
5603 {
5604 Assert(s->uTxDir == PDMBLOCKTXDIR_NONE); /* Any transfer which has an initial transfer size of 0 must be marked as such. */
5605 /* Finish DMA transfer. */
5606 ataR3DMATransferStop(s);
5607 ataHCSetIRQ(s);
5608 pCtl->uAsyncIOState = ATA_AIO_NEW;
5609 }
5610 }
5611 else
5612 {
5613 if (s->cbTotalTransfer)
5614 {
5615 ataHCPIOTransfer(pCtl);
5616 Assert(!pCtl->fRedo);
5617 if (s->fATAPITransfer || s->uTxDir != PDMBLOCKTXDIR_TO_DEVICE)
5618 ataHCSetIRQ(s);
5619
5620 if (s->uTxDir == PDMBLOCKTXDIR_TO_DEVICE || s->iSourceSink != ATAFN_SS_NULL)
5621 {
5622 /* Write operations and not yet finished transfers
5623 * must be completed in the async I/O thread. */
5624 pCtl->uAsyncIOState = ATA_AIO_PIO;
5625 }
5626 else
5627 {
5628 /* Finished read operation can be handled inline
5629 * in the end of PIO transfer handling code. Linux
5630 * depends on this, as it waits only briefly for
5631 * devices to become ready after incoming data
5632 * transfer. Cannot find anything in the ATA spec
5633 * that backs this assumption, but as all kernels
5634 * are affected (though most of the time it does
5635 * not cause any harm) this must work. */
5636 pCtl->uAsyncIOState = ATA_AIO_NEW;
5637 }
5638 }
5639 else
5640 {
5641 Assert(s->uTxDir == PDMBLOCKTXDIR_NONE); /* Any transfer which has an initial transfer size of 0 must be marked as such. */
5642 /* Finish PIO transfer. */
5643 ataHCPIOTransfer(pCtl);
5644 Assert(!pCtl->fRedo);
5645 if (!s->fATAPITransfer)
5646 ataHCSetIRQ(s);
5647 pCtl->uAsyncIOState = ATA_AIO_NEW;
5648 }
5649 }
5650 break;
5651
5652 case ATA_AIO_DMA:
5653 {
5654 BMDMAState *bm = &pCtl->BmDma;
5655 s = &pCtl->aIfs[pCtl->iAIOIf]; /* Do not remove or there's an instant crash after loading the saved state */
5656 ATAFNSS iOriginalSourceSink = (ATAFNSS)s->iSourceSink; /* Used by the hack below, but gets reset by then. */
5657
5658 if (s->uTxDir == PDMBLOCKTXDIR_FROM_DEVICE)
5659 AssertRelease(bm->u8Cmd & BM_CMD_WRITE);
5660 else
5661 AssertRelease(!(bm->u8Cmd & BM_CMD_WRITE));
5662
5663 if (RT_LIKELY(!pCtl->fRedo))
5664 {
5665 /* The specs say that the descriptor table must not cross a
5666 * 4K boundary. */
5667 pCtl->pFirstDMADesc = bm->pvAddr;
5668 pCtl->pLastDMADesc = RT_ALIGN_32(bm->pvAddr + 1, _4K) - sizeof(BMDMADesc);
5669 }
5670 ataR3DMATransfer(pCtl);
5671
5672 if (RT_UNLIKELY(pCtl->fRedo && !pCtl->fReset))
5673 {
5674 LogRel(("PIIX3 ATA: Ctl#%d: redo DMA operation\n", ATACONTROLLER_IDX(pCtl)));
5675 ataHCAsyncIOPutRequest(pCtl, &g_ataDMARequest);
5676 break;
5677 }
5678
5679 /* The infamous delay IRQ hack. */
5680 if ( iOriginalSourceSink == ATAFN_SS_WRITE_SECTORS
5681 && s->cbTotalTransfer == 0
5682 && pCtl->DelayIRQMillies)
5683 {
5684 /* Delay IRQ for writing. Required to get the Win2K
5685 * installation work reliably (otherwise it crashes,
5686 * usually during component install). So far no better
5687 * solution has been found. */
5688 Log(("%s: delay IRQ hack\n", __FUNCTION__));
5689 PDMCritSectLeave(&pCtl->lock);
5690 RTThreadSleep(pCtl->DelayIRQMillies);
5691 PDMCritSectEnter(&pCtl->lock, VINF_SUCCESS);
5692 }
5693
5694 ataUnsetStatus(s, ATA_STAT_DRQ);
5695 Assert(!pCtl->fChainedTransfer);
5696 Assert(s->iSourceSink == ATAFN_SS_NULL);
5697 if (s->fATAPITransfer)
5698 {
5699 s->uATARegNSector = (s->uATARegNSector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
5700 Log2(("%s: Ctl#%d: interrupt reason %#04x\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl), s->uATARegNSector));
5701 s->fATAPITransfer = false;
5702 }
5703 ataHCSetIRQ(s);
5704 pCtl->uAsyncIOState = ATA_AIO_NEW;
5705 break;
5706 }
5707
5708 case ATA_AIO_PIO:
5709 s = &pCtl->aIfs[pCtl->iAIOIf]; /* Do not remove or there's an instant crash after loading the saved state */
5710
5711 if (s->iSourceSink != ATAFN_SS_NULL)
5712 {
5713 bool fRedo;
5714 Log2(("%s: Ctl#%d: calling source/sink function\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl)));
5715 fRedo = g_apfnSourceSinkFuncs[s->iSourceSink](s);
5716 pCtl->fRedo = fRedo;
5717 if (RT_UNLIKELY(fRedo && !pCtl->fReset))
5718 {
5719 LogRel(("PIIX3 ATA: Ctl#%d: redo PIO operation\n", ATACONTROLLER_IDX(pCtl)));
5720 ataHCAsyncIOPutRequest(pCtl, &g_ataPIORequest);
5721 break;
5722 }
5723 s->iIOBufferCur = 0;
5724 s->iIOBufferEnd = s->cbElementaryTransfer;
5725 }
5726 else
5727 {
5728 /* Continue a previously started transfer. */
5729 ataUnsetStatus(s, ATA_STAT_BUSY);
5730 ataSetStatus(s, ATA_STAT_READY);
5731 }
5732
5733 /* It is possible that the drives on this controller get RESET
5734 * during the above call to the source/sink function. If that's
5735 * the case, don't restart the transfer and don't finish it the
5736 * usual way. RESET handling took care of all that already.
5737 * Most important: do not change uAsyncIOState. */
5738 if (pCtl->fReset)
5739 break;
5740
5741 if (s->cbTotalTransfer)
5742 {
5743 ataHCPIOTransfer(pCtl);
5744 ataHCSetIRQ(s);
5745
5746 if (s->uTxDir == PDMBLOCKTXDIR_TO_DEVICE || s->iSourceSink != ATAFN_SS_NULL)
5747 {
5748 /* Write operations and not yet finished transfers
5749 * must be completed in the async I/O thread. */
5750 pCtl->uAsyncIOState = ATA_AIO_PIO;
5751 }
5752 else
5753 {
5754 /* Finished read operation can be handled inline
5755 * in the end of PIO transfer handling code. Linux
5756 * depends on this, as it waits only briefly for
5757 * devices to become ready after incoming data
5758 * transfer. Cannot find anything in the ATA spec
5759 * that backs this assumption, but as all kernels
5760 * are affected (though most of the time it does
5761 * not cause any harm) this must work. */
5762 pCtl->uAsyncIOState = ATA_AIO_NEW;
5763 }
5764 }
5765 else
5766 {
5767 /* Finish PIO transfer. */
5768 ataHCPIOTransfer(pCtl);
5769 if ( !pCtl->fChainedTransfer
5770 && !s->fATAPITransfer
5771 && s->uTxDir != PDMBLOCKTXDIR_FROM_DEVICE)
5772 {
5773 ataHCSetIRQ(s);
5774 }
5775 pCtl->uAsyncIOState = ATA_AIO_NEW;
5776 }
5777 break;
5778
5779 case ATA_AIO_RESET_ASSERTED:
5780 pCtl->uAsyncIOState = ATA_AIO_RESET_CLEARED;
5781 ataHCPIOTransferStop(&pCtl->aIfs[0]);
5782 ataHCPIOTransferStop(&pCtl->aIfs[1]);
5783 /* Do not change the DMA registers, they are not affected by the
5784 * ATA controller reset logic. It should be sufficient to issue a
5785 * new command, which is now possible as the state is cleared. */
5786 break;
5787
5788 case ATA_AIO_RESET_CLEARED:
5789 pCtl->uAsyncIOState = ATA_AIO_NEW;
5790 pCtl->fReset = false;
5791 /* Ensure that half-completed transfers are not redone. A reset
5792 * cancels the entire transfer, so continuing is wrong. */
5793 pCtl->fRedo = false;
5794 pCtl->fRedoDMALastDesc = false;
5795 LogRel(("PIIX3 ATA: Ctl#%d: finished processing RESET\n",
5796 ATACONTROLLER_IDX(pCtl)));
5797 for (uint32_t i = 0; i < RT_ELEMENTS(pCtl->aIfs); i++)
5798 {
5799 if (pCtl->aIfs[i].fATAPI)
5800 ataSetStatusValue(&pCtl->aIfs[i], 0); /* NOTE: READY is _not_ set */
5801 else
5802 ataSetStatusValue(&pCtl->aIfs[i], ATA_STAT_READY | ATA_STAT_SEEK);
5803 ataR3SetSignature(&pCtl->aIfs[i]);
5804 }
5805 break;
5806
5807 case ATA_AIO_ABORT:
5808 /* Abort the current command no matter what. There cannot be
5809 * any command activity on the other drive otherwise using
5810 * one thread per controller wouldn't work at all. */
5811 s = &pCtl->aIfs[pReq->u.a.iIf];
5812
5813 pCtl->uAsyncIOState = ATA_AIO_NEW;
5814 /* Do not change the DMA registers, they are not affected by the
5815 * ATA controller reset logic. It should be sufficient to issue a
5816 * new command, which is now possible as the state is cleared. */
5817 if (pReq->u.a.fResetDrive)
5818 {
5819 ataR3ResetDevice(s);
5820 ataR3ExecuteDeviceDiagnosticSS(s);
5821 }
5822 else
5823 {
5824 /* Stop any pending DMA transfer. */
5825 s->fDMA = false;
5826 ataHCPIOTransferStop(s);
5827 ataUnsetStatus(s, ATA_STAT_BUSY | ATA_STAT_DRQ | ATA_STAT_SEEK | ATA_STAT_ERR);
5828 ataSetStatus(s, ATA_STAT_READY);
5829 ataHCSetIRQ(s);
5830 }
5831 break;
5832
5833 default:
5834 AssertMsgFailed(("Undefined async I/O state %d\n", pCtl->uAsyncIOState));
5835 }
5836
5837 ataR3AsyncIORemoveCurrentRequest(pCtl, ReqType);
5838 pReq = ataR3AsyncIOGetCurrentRequest(pCtl);
5839
5840 if (pCtl->uAsyncIOState == ATA_AIO_NEW && !pCtl->fChainedTransfer)
5841 {
5842# if defined(DEBUG) || defined(VBOX_WITH_STATISTICS)
5843 STAM_PROFILE_ADV_STOP(&pCtl->StatAsyncTime, a);
5844# endif
5845
5846 u64TS = RTTimeNanoTS() - u64TS;
5847 uWait = u64TS / 1000;
5848 Log(("%s: Ctl#%d: LUN#%d finished I/O transaction in %d microseconds\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl), pCtl->aIfs[pCtl->iAIOIf].iLUN, (uint32_t)(uWait)));
5849 /* Mark command as finished. */
5850 pCtl->aIfs[pCtl->iAIOIf].u64CmdTS = 0;
5851
5852 /*
5853 * Release logging of command execution times depends on the
5854 * command type. ATAPI commands often take longer (due to CD/DVD
5855 * spin up time etc.) so the threshold is different.
5856 */
5857 if (pCtl->aIfs[pCtl->iAIOIf].uATARegCommand != ATA_PACKET)
5858 {
5859 if (uWait > 8 * 1000 * 1000)
5860 {
5861 /*
5862 * Command took longer than 8 seconds. This is close
5863 * enough or over the guest's command timeout, so place
5864 * an entry in the release log to allow tracking such
5865 * timing errors (which are often caused by the host).
5866 */
5867 LogRel(("PIIX3 ATA: execution time for ATA command %#04x was %d seconds\n", pCtl->aIfs[pCtl->iAIOIf].uATARegCommand, uWait / (1000 * 1000)));
5868 }
5869 }
5870 else
5871 {
5872 if (uWait > 20 * 1000 * 1000)
5873 {
5874 /*
5875 * Command took longer than 20 seconds. This is close
5876 * enough or over the guest's command timeout, so place
5877 * an entry in the release log to allow tracking such
5878 * timing errors (which are often caused by the host).
5879 */
5880 LogRel(("PIIX3 ATA: execution time for ATAPI command %#04x was %d seconds\n", pCtl->aIfs[pCtl->iAIOIf].aATAPICmd[0], uWait / (1000 * 1000)));
5881 }
5882 }
5883
5884# if defined(DEBUG) || defined(VBOX_WITH_STATISTICS)
5885 if (uWait < pCtl->StatAsyncMinWait || !pCtl->StatAsyncMinWait)
5886 pCtl->StatAsyncMinWait = uWait;
5887 if (uWait > pCtl->StatAsyncMaxWait)
5888 pCtl->StatAsyncMaxWait = uWait;
5889
5890 STAM_COUNTER_ADD(&pCtl->StatAsyncTimeUS, uWait);
5891 STAM_COUNTER_INC(&pCtl->StatAsyncOps);
5892# endif /* DEBUG || VBOX_WITH_STATISTICS */
5893 }
5894
5895 PDMCritSectLeave(&pCtl->lock);
5896 }
5897
5898 /* Signal the ultimate idleness. */
5899 RTThreadUserSignal(pCtl->AsyncIOThread);
5900 if (pCtl->fSignalIdle)
5901 PDMDevHlpAsyncNotificationCompleted(pCtl->pDevInsR3);
5902
5903 /* Cleanup the state. */
5904 /* Do not destroy request lock yet, still needed for proper shutdown. */
5905 pCtl->fShutdown = false;
5906
5907 Log2(("%s: Ctl#%d: return %Rrc\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl), rc));
5908 return rc;
5909}
5910
5911#endif /* IN_RING3 */
5912
5913static uint32_t ataBMDMACmdReadB(PATACONTROLLER pCtl, uint32_t addr)
5914{
5915 uint32_t val = pCtl->BmDma.u8Cmd;
5916 Log2(("%s: addr=%#06x val=%#04x\n", __FUNCTION__, addr, val));
5917 return val;
5918}
5919
5920
5921static void ataBMDMACmdWriteB(PATACONTROLLER pCtl, uint32_t addr, uint32_t val)
5922{
5923 Log2(("%s: addr=%#06x val=%#04x\n", __FUNCTION__, addr, val));
5924 if (!(val & BM_CMD_START))
5925 {
5926 pCtl->BmDma.u8Status &= ~BM_STATUS_DMAING;
5927 pCtl->BmDma.u8Cmd = val & (BM_CMD_START | BM_CMD_WRITE);
5928 }
5929 else
5930 {
5931#ifndef IN_RC
5932 /* Check whether the guest OS wants to change DMA direction in
5933 * mid-flight. Not allowed, according to the PIIX3 specs. */
5934 Assert(!(pCtl->BmDma.u8Status & BM_STATUS_DMAING) || !((val ^ pCtl->BmDma.u8Cmd) & 0x04));
5935 uint8_t uOldBmDmaStatus = pCtl->BmDma.u8Status;
5936 pCtl->BmDma.u8Status |= BM_STATUS_DMAING;
5937 pCtl->BmDma.u8Cmd = val & (BM_CMD_START | BM_CMD_WRITE);
5938
5939 /* Do not continue DMA transfers while the RESET line is asserted. */
5940 if (pCtl->fReset)
5941 {
5942 Log2(("%s: Ctl#%d: suppressed continuing DMA transfer as RESET is active\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl)));
5943 return;
5944 }
5945
5946 /* Do not start DMA transfers if there's a PIO transfer going on,
5947 * or if there is already a transfer started on this controller. */
5948 if ( !pCtl->aIfs[pCtl->iSelectedIf].fDMA
5949 || (uOldBmDmaStatus & BM_STATUS_DMAING))
5950 return;
5951
5952 if (pCtl->aIfs[pCtl->iAIOIf].uATARegStatus & ATA_STAT_DRQ)
5953 {
5954 Log2(("%s: Ctl#%d: message to async I/O thread, continuing DMA transfer\n", __FUNCTION__, ATACONTROLLER_IDX(pCtl)));
5955 ataHCAsyncIOPutRequest(pCtl, &g_ataDMARequest);
5956 }
5957#else /* !IN_RING3 */
5958 AssertMsgFailed(("DMA START handling is too complicated for RC\n"));
5959#endif /* IN_RING3 */
5960 }
5961}
5962
5963static uint32_t ataBMDMAStatusReadB(PATACONTROLLER pCtl, uint32_t addr)
5964{
5965 uint32_t val = pCtl->BmDma.u8Status;
5966 Log2(("%s: addr=%#06x val=%#04x\n", __FUNCTION__, addr, val));
5967 return val;
5968}
5969
5970static void ataBMDMAStatusWriteB(PATACONTROLLER pCtl, uint32_t addr, uint32_t val)
5971{
5972 Log2(("%s: addr=%#06x val=%#04x\n", __FUNCTION__, addr, val));
5973 pCtl->BmDma.u8Status = (val & (BM_STATUS_D0DMA | BM_STATUS_D1DMA))
5974 | (pCtl->BmDma.u8Status & BM_STATUS_DMAING)
5975 | (pCtl->BmDma.u8Status & ~val & (BM_STATUS_ERROR | BM_STATUS_INT));
5976}
5977
5978static uint32_t ataBMDMAAddrReadL(PATACONTROLLER pCtl, uint32_t addr)
5979{
5980 uint32_t val = (uint32_t)pCtl->BmDma.pvAddr;
5981 Log2(("%s: addr=%#06x val=%#010x\n", __FUNCTION__, addr, val));
5982 return val;
5983}
5984
5985static void ataBMDMAAddrWriteL(PATACONTROLLER pCtl, uint32_t addr, uint32_t val)
5986{
5987 Log2(("%s: addr=%#06x val=%#010x\n", __FUNCTION__, addr, val));
5988 pCtl->BmDma.pvAddr = val & ~3;
5989}
5990
5991static void ataBMDMAAddrWriteLowWord(PATACONTROLLER pCtl, uint32_t addr, uint32_t val)
5992{
5993 Log2(("%s: addr=%#06x val=%#010x\n", __FUNCTION__, addr, val));
5994 pCtl->BmDma.pvAddr = (pCtl->BmDma.pvAddr & 0xFFFF0000) | RT_LOWORD(val & ~3);
5995
5996}
5997
5998static void ataBMDMAAddrWriteHighWord(PATACONTROLLER pCtl, uint32_t addr, uint32_t val)
5999{
6000 Log2(("%s: addr=%#06x val=%#010x\n", __FUNCTION__, addr, val));
6001 pCtl->BmDma.pvAddr = (RT_LOWORD(val) << 16) | RT_LOWORD(pCtl->BmDma.pvAddr);
6002}
6003
6004#define VAL(port, size) ( ((port) & 7) | ((size) << 3) )
6005
6006/**
6007 * Port I/O Handler for bus master DMA IN operations.
6008 * @see FNIOMIOPORTIN for details.
6009 */
6010PDMBOTHCBDECL(int) ataBMDMAIOPortRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t *pu32, unsigned cb)
6011{
6012 uint32_t i = (uint32_t)(uintptr_t)pvUser;
6013 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
6014 PATACONTROLLER pCtl = &pThis->aCts[i];
6015
6016 int rc = PDMCritSectEnter(&pCtl->lock, VINF_IOM_R3_IOPORT_READ);
6017 if (rc != VINF_SUCCESS)
6018 return rc;
6019 switch (VAL(Port, cb))
6020 {
6021 case VAL(0, 1): *pu32 = ataBMDMACmdReadB(pCtl, Port); break;
6022 case VAL(0, 2): *pu32 = ataBMDMACmdReadB(pCtl, Port); break;
6023 case VAL(2, 1): *pu32 = ataBMDMAStatusReadB(pCtl, Port); break;
6024 case VAL(2, 2): *pu32 = ataBMDMAStatusReadB(pCtl, Port); break;
6025 case VAL(4, 4): *pu32 = ataBMDMAAddrReadL(pCtl, Port); break;
6026 case VAL(0, 4):
6027 /* The SCO OpenServer tries to read 4 bytes starting from offset 0. */
6028 *pu32 = ataBMDMACmdReadB(pCtl, Port) | (ataBMDMAStatusReadB(pCtl, Port) << 16);
6029 break;
6030 default:
6031 AssertMsgFailed(("%s: Unsupported read from port %x size=%d\n", __FUNCTION__, Port, cb));
6032 PDMCritSectLeave(&pCtl->lock);
6033 return VERR_IOM_IOPORT_UNUSED;
6034 }
6035 PDMCritSectLeave(&pCtl->lock);
6036 return rc;
6037}
6038
6039/**
6040 * Port I/O Handler for bus master DMA OUT operations.
6041 * @see FNIOMIOPORTOUT for details.
6042 */
6043PDMBOTHCBDECL(int) ataBMDMAIOPortWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t u32, unsigned cb)
6044{
6045 uint32_t i = (uint32_t)(uintptr_t)pvUser;
6046 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
6047 PATACONTROLLER pCtl = &pThis->aCts[i];
6048
6049 int rc = PDMCritSectEnter(&pCtl->lock, VINF_IOM_R3_IOPORT_WRITE);
6050 if (rc != VINF_SUCCESS)
6051 return rc;
6052 switch (VAL(Port, cb))
6053 {
6054 case VAL(0, 1):
6055#ifdef IN_RC
6056 if (u32 & BM_CMD_START)
6057 {
6058 rc = VINF_IOM_R3_IOPORT_WRITE;
6059 break;
6060 }
6061#endif
6062 ataBMDMACmdWriteB(pCtl, Port, u32);
6063 break;
6064 case VAL(2, 1): ataBMDMAStatusWriteB(pCtl, Port, u32); break;
6065 case VAL(4, 4): ataBMDMAAddrWriteL(pCtl, Port, u32); break;
6066 case VAL(4, 2): ataBMDMAAddrWriteLowWord(pCtl, Port, u32); break;
6067 case VAL(6, 2): ataBMDMAAddrWriteHighWord(pCtl, Port, u32); break;
6068 default: AssertMsgFailed(("%s: Unsupported write to port %x size=%d val=%x\n", __FUNCTION__, Port, cb, u32)); break;
6069 }
6070 PDMCritSectLeave(&pCtl->lock);
6071 return rc;
6072}
6073
6074#undef VAL
6075
6076#ifdef IN_RING3
6077
6078/**
6079 * Callback function for mapping an PCI I/O region.
6080 *
6081 * @return VBox status code.
6082 * @param pPciDev Pointer to PCI device. Use pPciDev->pDevIns to get the device instance.
6083 * @param iRegion The region number.
6084 * @param GCPhysAddress Physical address of the region. If iType is PCI_ADDRESS_SPACE_IO, this is an
6085 * I/O port, else it's a physical address.
6086 * This address is *NOT* relative to pci_mem_base like earlier!
6087 * @param enmType One of the PCI_ADDRESS_SPACE_* values.
6088 */
6089static DECLCALLBACK(int) ataR3BMDMAIORangeMap(PPCIDEVICE pPciDev, /*unsigned*/ int iRegion,
6090 RTGCPHYS GCPhysAddress, uint32_t cb, PCIADDRESSSPACE enmType)
6091{
6092 PCIATAState *pThis = PCIDEV_2_PCIATASTATE(pPciDev);
6093 int rc = VINF_SUCCESS;
6094 Assert(enmType == PCI_ADDRESS_SPACE_IO);
6095 Assert(iRegion == 4);
6096 AssertMsg(RT_ALIGN(GCPhysAddress, 8) == GCPhysAddress, ("Expected 8 byte alignment. GCPhysAddress=%#x\n", GCPhysAddress));
6097
6098 /* Register the port range. */
6099 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
6100 {
6101 int rc2 = PDMDevHlpIOPortRegister(pPciDev->pDevIns, (RTIOPORT)GCPhysAddress + i * 8, 8,
6102 (RTHCPTR)(uintptr_t)i, ataBMDMAIOPortWrite, ataBMDMAIOPortRead,
6103 NULL, NULL, "ATA Bus Master DMA");
6104 AssertRC(rc2);
6105 if (rc2 < rc)
6106 rc = rc2;
6107
6108 if (pThis->fRCEnabled)
6109 {
6110 rc2 = PDMDevHlpIOPortRegisterRC(pPciDev->pDevIns, (RTIOPORT)GCPhysAddress + i * 8, 8,
6111 (RTGCPTR)i, "ataBMDMAIOPortWrite", "ataBMDMAIOPortRead",
6112 NULL, NULL, "ATA Bus Master DMA");
6113 AssertRC(rc2);
6114 if (rc2 < rc)
6115 rc = rc2;
6116 }
6117 if (pThis->fR0Enabled)
6118 {
6119 rc2 = PDMDevHlpIOPortRegisterR0(pPciDev->pDevIns, (RTIOPORT)GCPhysAddress + i * 8, 8,
6120 (RTR0PTR)i, "ataBMDMAIOPortWrite", "ataBMDMAIOPortRead",
6121 NULL, NULL, "ATA Bus Master DMA");
6122 AssertRC(rc2);
6123 if (rc2 < rc)
6124 rc = rc2;
6125 }
6126 }
6127 return rc;
6128}
6129
6130
6131/* -=-=-=-=-=- PCIATAState::IBase -=-=-=-=-=- */
6132
6133/**
6134 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
6135 */
6136static DECLCALLBACK(void *) ataR3Status_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
6137{
6138 PCIATAState *pThis = PDMIBASE_2_PCIATASTATE(pInterface);
6139 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThis->IBase);
6140 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDPORTS, &pThis->ILeds);
6141 return NULL;
6142}
6143
6144
6145/* -=-=-=-=-=- PCIATAState::ILeds -=-=-=-=-=- */
6146
6147/**
6148 * Gets the pointer to the status LED of a unit.
6149 *
6150 * @returns VBox status code.
6151 * @param pInterface Pointer to the interface structure containing the called function pointer.
6152 * @param iLUN The unit which status LED we desire.
6153 * @param ppLed Where to store the LED pointer.
6154 */
6155static DECLCALLBACK(int) ataR3Status_QueryStatusLed(PPDMILEDPORTS pInterface, unsigned iLUN, PPDMLED *ppLed)
6156{
6157 PCIATAState *pThis = PDMILEDPORTS_2_PCIATASTATE(pInterface);
6158 if (iLUN < 4)
6159 {
6160 switch (iLUN)
6161 {
6162 case 0: *ppLed = &pThis->aCts[0].aIfs[0].Led; break;
6163 case 1: *ppLed = &pThis->aCts[0].aIfs[1].Led; break;
6164 case 2: *ppLed = &pThis->aCts[1].aIfs[0].Led; break;
6165 case 3: *ppLed = &pThis->aCts[1].aIfs[1].Led; break;
6166 }
6167 Assert((*ppLed)->u32Magic == PDMLED_MAGIC);
6168 return VINF_SUCCESS;
6169 }
6170 return VERR_PDM_LUN_NOT_FOUND;
6171}
6172
6173
6174/* -=-=-=-=-=- ATADevState::IBase -=-=-=-=-=- */
6175
6176/**
6177 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
6178 */
6179static DECLCALLBACK(void *) ataR3QueryInterface(PPDMIBASE pInterface, const char *pszIID)
6180{
6181 ATADevState *pIf = PDMIBASE_2_ATASTATE(pInterface);
6182 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pIf->IBase);
6183 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBLOCKPORT, &pIf->IPort);
6184 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMOUNTNOTIFY, &pIf->IMountNotify);
6185 return NULL;
6186}
6187
6188
6189/* -=-=-=-=-=- ATADevState::IPort -=-=-=-=-=- */
6190
6191/**
6192 * @interface_method_impl{PDMIBLOCKPORT,pfnQueryDeviceLocation}
6193 */
6194static DECLCALLBACK(int) ataR3QueryDeviceLocation(PPDMIBLOCKPORT pInterface, const char **ppcszController,
6195 uint32_t *piInstance, uint32_t *piLUN)
6196{
6197 ATADevState *pIf = PDMIBLOCKPORT_2_ATASTATE(pInterface);
6198 PPDMDEVINS pDevIns = pIf->CTX_SUFF(pDevIns);
6199
6200 AssertPtrReturn(ppcszController, VERR_INVALID_POINTER);
6201 AssertPtrReturn(piInstance, VERR_INVALID_POINTER);
6202 AssertPtrReturn(piLUN, VERR_INVALID_POINTER);
6203
6204 *ppcszController = pDevIns->pReg->szName;
6205 *piInstance = pDevIns->iInstance;
6206 *piLUN = pIf->iLUN;
6207
6208 return VINF_SUCCESS;
6209}
6210
6211#endif /* IN_RING3 */
6212
6213/* -=-=-=-=-=- Wrappers -=-=-=-=-=- */
6214
6215
6216/**
6217 * Port I/O Handler for primary port range OUT operations.
6218 * @see FNIOMIOPORTOUT for details.
6219 */
6220PDMBOTHCBDECL(int) ataIOPortWrite1Other(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t u32, unsigned cb)
6221{
6222 uint32_t i = (uint32_t)(uintptr_t)pvUser;
6223 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
6224 PATACONTROLLER pCtl = &pThis->aCts[i];
6225
6226 Assert(i < 2);
6227 Assert(Port != pCtl->IOPortBase1);
6228
6229 int rc = PDMCritSectEnter(&pCtl->lock, VINF_IOM_R3_IOPORT_WRITE);
6230 if (rc == VINF_SUCCESS)
6231 {
6232 /* Writes to the other command block ports should be 8-bit only. If they
6233 * are not, the high bits are simply discarded. Undocumented, but observed
6234 * on a real PIIX4 system.
6235 */
6236 if (cb > 1)
6237 Log(("ataIOPortWrite1: suspect write to port %x val=%x size=%d\n", Port, u32, cb));
6238
6239 rc = ataIOPortWriteU8(pCtl, Port, u32);
6240
6241 PDMCritSectLeave(&pCtl->lock);
6242 }
6243 return rc;
6244}
6245
6246
6247/**
6248 * Port I/O Handler for primary port range IN operations.
6249 * @see FNIOMIOPORTIN for details.
6250 */
6251PDMBOTHCBDECL(int) ataIOPortRead1Other(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t *pu32, unsigned cb)
6252{
6253 uint32_t i = (uint32_t)(uintptr_t)pvUser;
6254 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
6255 PATACONTROLLER pCtl = &pThis->aCts[i];
6256
6257 Assert(i < 2);
6258 Assert(Port != pCtl->IOPortBase1);
6259
6260 int rc = PDMCritSectEnter(&pCtl->lock, VINF_IOM_R3_IOPORT_READ);
6261 if (rc == VINF_SUCCESS)
6262 {
6263 /* Reads from the other command block registers should be 8-bit only.
6264 * If they are not, the low byte is propagated to the high bits.
6265 * Undocumented, but observed on a real PIIX4 system.
6266 */
6267 rc = ataIOPortReadU8(pCtl, Port, pu32);
6268 if (cb > 1)
6269 {
6270 uint32_t pad;
6271
6272 /* Replicate the 8-bit result into the upper three bytes. */
6273 pad = *pu32 & 0xff;
6274 pad = pad | (pad << 8);
6275 pad = pad | (pad << 16);
6276 *pu32 = pad;
6277 Log(("ataIOPortRead1: suspect read from port %x size=%d\n", Port, cb));
6278 }
6279 PDMCritSectLeave(&pCtl->lock);
6280 }
6281 return rc;
6282}
6283
6284
6285/**
6286 * Port I/O Handler for secondary port range OUT operations.
6287 * @see FNIOMIOPORTOUT for details.
6288 */
6289PDMBOTHCBDECL(int) ataIOPortWrite2(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t u32, unsigned cb)
6290{
6291 uint32_t i = (uint32_t)(uintptr_t)pvUser;
6292 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
6293 PATACONTROLLER pCtl = &pThis->aCts[i];
6294 int rc;
6295
6296 Assert(i < 2);
6297
6298 if (cb == 1)
6299 {
6300 rc = PDMCritSectEnter(&pCtl->lock, VINF_IOM_R3_IOPORT_WRITE);
6301 if (rc == VINF_SUCCESS)
6302 {
6303 rc = ataControlWrite(pCtl, Port, u32);
6304 PDMCritSectLeave(&pCtl->lock);
6305 }
6306 }
6307 else
6308 rc = VINF_SUCCESS;
6309 return rc;
6310}
6311
6312
6313/**
6314 * Port I/O Handler for secondary port range IN operations.
6315 * @see FNIOMIOPORTIN for details.
6316 */
6317PDMBOTHCBDECL(int) ataIOPortRead2(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t *pu32, unsigned cb)
6318{
6319 uint32_t i = (uint32_t)(uintptr_t)pvUser;
6320 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
6321 PATACONTROLLER pCtl = &pThis->aCts[i];
6322 int rc;
6323
6324 Assert(i < 2);
6325
6326 if (cb == 1)
6327 {
6328 rc = PDMCritSectEnter(&pCtl->lock, VINF_IOM_R3_IOPORT_READ);
6329 if (rc == VINF_SUCCESS)
6330 {
6331 *pu32 = ataStatusRead(pCtl, Port);
6332 PDMCritSectLeave(&pCtl->lock);
6333 }
6334 }
6335 else
6336 rc = VERR_IOM_IOPORT_UNUSED;
6337 return rc;
6338}
6339
6340#ifdef IN_RING3
6341
6342
6343DECLINLINE(void) ataR3RelocBuffer(PPDMDEVINS pDevIns, ATADevState *s)
6344{
6345 if (s->pbIOBufferR3)
6346 s->pbIOBufferRC = MMHyperR3ToRC(PDMDevHlpGetVM(pDevIns), s->pbIOBufferR3);
6347}
6348
6349
6350/**
6351 * Detach notification.
6352 *
6353 * The DVD drive has been unplugged.
6354 *
6355 * @param pDevIns The device instance.
6356 * @param iLUN The logical unit which is being detached.
6357 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
6358 */
6359static DECLCALLBACK(void) ataR3Detach(PPDMDEVINS pDevIns, unsigned iLUN, uint32_t fFlags)
6360{
6361 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
6362 PATACONTROLLER pCtl;
6363 ATADevState *pIf;
6364 unsigned iController;
6365 unsigned iInterface;
6366
6367 AssertMsg(fFlags & PDM_TACH_FLAGS_NOT_HOT_PLUG,
6368 ("PIIX3IDE: Device does not support hotplugging\n"));
6369
6370 /*
6371 * Locate the controller and stuff.
6372 */
6373 iController = iLUN / RT_ELEMENTS(pThis->aCts[0].aIfs);
6374 AssertReleaseMsg(iController < RT_ELEMENTS(pThis->aCts), ("iController=%d iLUN=%d\n", iController, iLUN));
6375 pCtl = &pThis->aCts[iController];
6376
6377 iInterface = iLUN % RT_ELEMENTS(pThis->aCts[0].aIfs);
6378 pIf = &pCtl->aIfs[iInterface];
6379
6380 /*
6381 * Zero some important members.
6382 */
6383 pIf->pDrvBase = NULL;
6384 pIf->pDrvBlock = NULL;
6385 pIf->pDrvBlockBios = NULL;
6386 pIf->pDrvMount = NULL;
6387
6388 /*
6389 * In case there was a medium inserted.
6390 */
6391 ataR3MediumRemoved(pIf);
6392}
6393
6394
6395/**
6396 * Configure a LUN.
6397 *
6398 * @returns VBox status code.
6399 * @param pDevIns The device instance.
6400 * @param pIf The ATA unit state.
6401 */
6402static int ataR3ConfigLun(PPDMDEVINS pDevIns, ATADevState *pIf)
6403{
6404 int rc = VINF_SUCCESS;
6405 PDMBLOCKTYPE enmType;
6406
6407 /*
6408 * Query Block, Bios and Mount interfaces.
6409 */
6410 pIf->pDrvBlock = PDMIBASE_QUERY_INTERFACE(pIf->pDrvBase, PDMIBLOCK);
6411 if (!pIf->pDrvBlock)
6412 {
6413 AssertMsgFailed(("Configuration error: LUN#%d hasn't a block interface!\n", pIf->iLUN));
6414 return VERR_PDM_MISSING_INTERFACE;
6415 }
6416
6417 /** @todo implement the BIOS invisible code path. */
6418 pIf->pDrvBlockBios = PDMIBASE_QUERY_INTERFACE(pIf->pDrvBase, PDMIBLOCKBIOS);
6419 if (!pIf->pDrvBlockBios)
6420 {
6421 AssertMsgFailed(("Configuration error: LUN#%d hasn't a block BIOS interface!\n", pIf->iLUN));
6422 return VERR_PDM_MISSING_INTERFACE;
6423 }
6424 pIf->pDrvMount = PDMIBASE_QUERY_INTERFACE(pIf->pDrvBase, PDMIMOUNT);
6425
6426 /*
6427 * Validate type.
6428 */
6429 enmType = pIf->pDrvBlock->pfnGetType(pIf->pDrvBlock);
6430 if ( enmType != PDMBLOCKTYPE_CDROM
6431 && enmType != PDMBLOCKTYPE_DVD
6432 && enmType != PDMBLOCKTYPE_HARD_DISK)
6433 {
6434 AssertMsgFailed(("Configuration error: LUN#%d isn't a disk or cd/dvd-rom. enmType=%d\n", pIf->iLUN, enmType));
6435 return VERR_PDM_UNSUPPORTED_BLOCK_TYPE;
6436 }
6437 if ( ( enmType == PDMBLOCKTYPE_DVD
6438 || enmType == PDMBLOCKTYPE_CDROM)
6439 && !pIf->pDrvMount)
6440 {
6441 AssertMsgFailed(("Internal error: cdrom without a mountable interface, WTF???!\n"));
6442 return VERR_INTERNAL_ERROR;
6443 }
6444 pIf->fATAPI = enmType == PDMBLOCKTYPE_DVD || enmType == PDMBLOCKTYPE_CDROM;
6445 pIf->fATAPIPassthrough = pIf->fATAPI ? (pIf->pDrvBlock->pfnSendCmd != NULL) : false;
6446
6447 /*
6448 * Allocate I/O buffer.
6449 */
6450 if (pIf->fATAPI)
6451 pIf->cbSector = 2048;
6452 else
6453 pIf->cbSector = pIf->pDrvBlock->pfnGetSectorSize(pIf->pDrvBlock);
6454
6455 PVM pVM = PDMDevHlpGetVM(pDevIns);
6456 if (pIf->cbIOBuffer)
6457 {
6458 /* Buffer is (probably) already allocated. Validate the fields,
6459 * because memory corruption can also overwrite pIf->cbIOBuffer. */
6460 if (pIf->fATAPI)
6461 AssertRelease(pIf->cbIOBuffer == _128K);
6462 else
6463 AssertRelease(pIf->cbIOBuffer == ATA_MAX_MULT_SECTORS * pIf->cbSector);
6464 Assert(pIf->pbIOBufferR3);
6465 Assert(pIf->pbIOBufferR0 == MMHyperR3ToR0(pVM, pIf->pbIOBufferR3));
6466 Assert(pIf->pbIOBufferRC == MMHyperR3ToRC(pVM, pIf->pbIOBufferR3));
6467 }
6468 else
6469 {
6470 if (pIf->fATAPI)
6471 pIf->cbIOBuffer = _128K;
6472 else
6473 pIf->cbIOBuffer = ATA_MAX_MULT_SECTORS * pIf->cbSector;
6474 Assert(!pIf->pbIOBufferR3);
6475 rc = MMR3HyperAllocOnceNoRel(pVM, pIf->cbIOBuffer, 0, MM_TAG_PDM_DEVICE_USER, (void **)&pIf->pbIOBufferR3);
6476 if (RT_FAILURE(rc))
6477 return VERR_NO_MEMORY;
6478 pIf->pbIOBufferR0 = MMHyperR3ToR0(pVM, pIf->pbIOBufferR3);
6479 pIf->pbIOBufferRC = MMHyperR3ToRC(pVM, pIf->pbIOBufferR3);
6480 }
6481
6482 /*
6483 * Init geometry (only for non-CD/DVD media).
6484 */
6485 if (pIf->fATAPI)
6486 {
6487 pIf->cTotalSectors = pIf->pDrvBlock->pfnGetSize(pIf->pDrvBlock) / pIf->cbSector;
6488 pIf->PCHSGeometry.cCylinders = 0; /* dummy */
6489 pIf->PCHSGeometry.cHeads = 0; /* dummy */
6490 pIf->PCHSGeometry.cSectors = 0; /* dummy */
6491 LogRel(("PIIX3 ATA: LUN#%d: CD/DVD, total number of sectors %Ld, passthrough %s\n", pIf->iLUN, pIf->cTotalSectors, (pIf->fATAPIPassthrough ? "enabled" : "disabled")));
6492 }
6493 else
6494 {
6495 pIf->cTotalSectors = pIf->pDrvBlock->pfnGetSize(pIf->pDrvBlock) / pIf->cbSector;
6496 rc = pIf->pDrvBlockBios->pfnGetPCHSGeometry(pIf->pDrvBlockBios,
6497 &pIf->PCHSGeometry);
6498 if (rc == VERR_PDM_MEDIA_NOT_MOUNTED)
6499 {
6500 pIf->PCHSGeometry.cCylinders = 0;
6501 pIf->PCHSGeometry.cHeads = 16; /*??*/
6502 pIf->PCHSGeometry.cSectors = 63; /*??*/
6503 }
6504 else if (rc == VERR_PDM_GEOMETRY_NOT_SET)
6505 {
6506 pIf->PCHSGeometry.cCylinders = 0; /* autodetect marker */
6507 rc = VINF_SUCCESS;
6508 }
6509 AssertRC(rc);
6510
6511 if ( pIf->PCHSGeometry.cCylinders == 0
6512 || pIf->PCHSGeometry.cHeads == 0
6513 || pIf->PCHSGeometry.cSectors == 0
6514 )
6515 {
6516 uint64_t cCylinders = pIf->cTotalSectors / (16 * 63);
6517 pIf->PCHSGeometry.cCylinders = RT_MAX(RT_MIN(cCylinders, 16383), 1);
6518 pIf->PCHSGeometry.cHeads = 16;
6519 pIf->PCHSGeometry.cSectors = 63;
6520 /* Set the disk geometry information. Ignore errors. */
6521 pIf->pDrvBlockBios->pfnSetPCHSGeometry(pIf->pDrvBlockBios,
6522 &pIf->PCHSGeometry);
6523 rc = VINF_SUCCESS;
6524 }
6525 LogRel(("PIIX3 ATA: LUN#%d: disk, PCHS=%u/%u/%u, total number of sectors %Ld\n", pIf->iLUN, pIf->PCHSGeometry.cCylinders, pIf->PCHSGeometry.cHeads, pIf->PCHSGeometry.cSectors, pIf->cTotalSectors));
6526
6527 if (pIf->pDrvBlock->pfnDiscard)
6528 LogRel(("PIIX3 ATA: LUN#%d: TRIM enabled\n", pIf->iLUN));
6529 }
6530 return rc;
6531}
6532
6533
6534/**
6535 * Attach command.
6536 *
6537 * This is called when we change block driver for the DVD drive.
6538 *
6539 * @returns VBox status code.
6540 * @param pDevIns The device instance.
6541 * @param iLUN The logical unit which is being detached.
6542 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
6543 */
6544static DECLCALLBACK(int) ataR3Attach(PPDMDEVINS pDevIns, unsigned iLUN, uint32_t fFlags)
6545{
6546 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
6547 PATACONTROLLER pCtl;
6548 ATADevState *pIf;
6549 int rc;
6550 unsigned iController;
6551 unsigned iInterface;
6552
6553 AssertMsgReturn(fFlags & PDM_TACH_FLAGS_NOT_HOT_PLUG,
6554 ("PIIX3IDE: Device does not support hotplugging\n"),
6555 VERR_INVALID_PARAMETER);
6556
6557 /*
6558 * Locate the controller and stuff.
6559 */
6560 iController = iLUN / RT_ELEMENTS(pThis->aCts[0].aIfs);
6561 AssertReleaseMsg(iController < RT_ELEMENTS(pThis->aCts), ("iController=%d iLUN=%d\n", iController, iLUN));
6562 pCtl = &pThis->aCts[iController];
6563
6564 iInterface = iLUN % RT_ELEMENTS(pThis->aCts[0].aIfs);
6565 pIf = &pCtl->aIfs[iInterface];
6566
6567 /* the usual paranoia */
6568 AssertRelease(!pIf->pDrvBase);
6569 AssertRelease(!pIf->pDrvBlock);
6570 Assert(ATADEVSTATE_2_CONTROLLER(pIf) == pCtl);
6571 Assert(pIf->iLUN == iLUN);
6572
6573 /*
6574 * Try attach the block device and get the interfaces,
6575 * required as well as optional.
6576 */
6577 rc = PDMDevHlpDriverAttach(pDevIns, pIf->iLUN, &pIf->IBase, &pIf->pDrvBase, NULL);
6578 if (RT_SUCCESS(rc))
6579 {
6580 rc = ataR3ConfigLun(pDevIns, pIf);
6581 /*
6582 * In case there is a medium inserted.
6583 */
6584 ataR3MediumInserted(pIf);
6585 ataR3MediumTypeSet(pIf, ATA_MEDIA_TYPE_UNKNOWN);
6586 }
6587 else
6588 AssertMsgFailed(("Failed to attach LUN#%d. rc=%Rrc\n", pIf->iLUN, rc));
6589
6590 if (RT_FAILURE(rc))
6591 {
6592 pIf->pDrvBase = NULL;
6593 pIf->pDrvBlock = NULL;
6594 }
6595 return rc;
6596}
6597
6598
6599/**
6600 * Resume notification.
6601 *
6602 * @returns VBox status.
6603 * @param pDevIns The device instance data.
6604 */
6605static DECLCALLBACK(void) ataR3Resume(PPDMDEVINS pDevIns)
6606{
6607 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
6608 int rc;
6609
6610 Log(("%s:\n", __FUNCTION__));
6611 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
6612 {
6613 if (pThis->aCts[i].fRedo && pThis->aCts[i].fRedoIdle)
6614 {
6615 rc = RTSemEventSignal(pThis->aCts[i].SuspendIOSem);
6616 AssertRC(rc);
6617 }
6618 }
6619 return;
6620}
6621
6622
6623/**
6624 * Checks if all (both) the async I/O threads have quiesced.
6625 *
6626 * @returns true on success.
6627 * @returns false when one or more threads is still processing.
6628 * @param pThis Pointer to the instance data.
6629 */
6630static bool ataR3AllAsyncIOIsIdle(PPDMDEVINS pDevIns)
6631{
6632 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
6633
6634 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
6635 if (pThis->aCts[i].AsyncIOThread != NIL_RTTHREAD)
6636 {
6637 bool fRc = ataR3AsyncIOIsIdle(&pThis->aCts[i], false /*fStrict*/);
6638 if (!fRc)
6639 {
6640 /* Make it signal PDM & itself when its done */
6641 PDMCritSectEnter(&pThis->aCts[i].AsyncIORequestLock, VERR_IGNORED);
6642 ASMAtomicWriteBool(&pThis->aCts[i].fSignalIdle, true);
6643 PDMCritSectLeave(&pThis->aCts[i].AsyncIORequestLock);
6644
6645 fRc = ataR3AsyncIOIsIdle(&pThis->aCts[i], false /*fStrict*/);
6646 if (!fRc)
6647 {
6648#if 0 /** @todo Need to do some time tracking here... */
6649 LogRel(("PIIX3 ATA: Ctl#%u is still executing, DevSel=%d AIOIf=%d CmdIf0=%#04x CmdIf1=%#04x\n",
6650 i, pThis->aCts[i].iSelectedIf, pThis->aCts[i].iAIOIf,
6651 pThis->aCts[i].aIfs[0].uATARegCommand, pThis->aCts[i].aIfs[1].uATARegCommand));
6652#endif
6653 return false;
6654 }
6655 }
6656 ASMAtomicWriteBool(&pThis->aCts[i].fSignalIdle, false);
6657 }
6658 return true;
6659}
6660
6661/**
6662 * Prepare state save and load operation.
6663 *
6664 * @returns VBox status code.
6665 * @param pDevIns Device instance of the device which registered the data unit.
6666 * @param pSSM SSM operation handle.
6667 */
6668static DECLCALLBACK(int) ataR3SaveLoadPrep(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
6669{
6670 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
6671
6672 /* sanity - the suspend notification will wait on the async stuff. */
6673 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
6674 AssertLogRelMsgReturn(ataR3AsyncIOIsIdle(&pThis->aCts[i], false /*fStrict*/),
6675 ("i=%u\n", i),
6676 VERR_SSM_IDE_ASYNC_TIMEOUT);
6677 return VINF_SUCCESS;
6678}
6679
6680/**
6681 * @copydoc FNSSMDEVLIVEEXEC
6682 */
6683static DECLCALLBACK(int) ataR3LiveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uPass)
6684{
6685 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
6686
6687 SSMR3PutU8(pSSM, pThis->u8Type);
6688 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
6689 {
6690 SSMR3PutBool(pSSM, true); /* For controller enabled / disabled. */
6691 for (uint32_t j = 0; j < RT_ELEMENTS(pThis->aCts[i].aIfs); j++)
6692 {
6693 SSMR3PutBool(pSSM, pThis->aCts[i].aIfs[j].pDrvBase != NULL);
6694 SSMR3PutStrZ(pSSM, pThis->aCts[i].aIfs[j].szSerialNumber);
6695 SSMR3PutStrZ(pSSM, pThis->aCts[i].aIfs[j].szFirmwareRevision);
6696 SSMR3PutStrZ(pSSM, pThis->aCts[i].aIfs[j].szModelNumber);
6697 }
6698 }
6699
6700 return VINF_SSM_DONT_CALL_AGAIN;
6701}
6702
6703/**
6704 * @copydoc FNSSMDEVSAVEEXEC
6705 */
6706static DECLCALLBACK(int) ataR3SaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
6707{
6708 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
6709
6710 ataR3LiveExec(pDevIns, pSSM, SSM_PASS_FINAL);
6711
6712 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
6713 {
6714 SSMR3PutU8(pSSM, pThis->aCts[i].iSelectedIf);
6715 SSMR3PutU8(pSSM, pThis->aCts[i].iAIOIf);
6716 SSMR3PutU8(pSSM, pThis->aCts[i].uAsyncIOState);
6717 SSMR3PutBool(pSSM, pThis->aCts[i].fChainedTransfer);
6718 SSMR3PutBool(pSSM, pThis->aCts[i].fReset);
6719 SSMR3PutBool(pSSM, pThis->aCts[i].fRedo);
6720 SSMR3PutBool(pSSM, pThis->aCts[i].fRedoIdle);
6721 SSMR3PutBool(pSSM, pThis->aCts[i].fRedoDMALastDesc);
6722 SSMR3PutMem(pSSM, &pThis->aCts[i].BmDma, sizeof(pThis->aCts[i].BmDma));
6723 SSMR3PutGCPhys32(pSSM, pThis->aCts[i].pFirstDMADesc);
6724 SSMR3PutGCPhys32(pSSM, pThis->aCts[i].pLastDMADesc);
6725 SSMR3PutGCPhys32(pSSM, pThis->aCts[i].pRedoDMABuffer);
6726 SSMR3PutU32(pSSM, pThis->aCts[i].cbRedoDMABuffer);
6727
6728 for (uint32_t j = 0; j < RT_ELEMENTS(pThis->aCts[i].aIfs); j++)
6729 {
6730 SSMR3PutBool(pSSM, pThis->aCts[i].aIfs[j].fLBA48);
6731 SSMR3PutBool(pSSM, pThis->aCts[i].aIfs[j].fATAPI);
6732 SSMR3PutBool(pSSM, pThis->aCts[i].aIfs[j].fIrqPending);
6733 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].cMultSectors);
6734 SSMR3PutU32(pSSM, pThis->aCts[i].aIfs[j].PCHSGeometry.cCylinders);
6735 SSMR3PutU32(pSSM, pThis->aCts[i].aIfs[j].PCHSGeometry.cHeads);
6736 SSMR3PutU32(pSSM, pThis->aCts[i].aIfs[j].PCHSGeometry.cSectors);
6737 SSMR3PutU32(pSSM, pThis->aCts[i].aIfs[j].cSectorsPerIRQ);
6738 SSMR3PutU64(pSSM, pThis->aCts[i].aIfs[j].cTotalSectors);
6739 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATARegFeature);
6740 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATARegFeatureHOB);
6741 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATARegError);
6742 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATARegNSector);
6743 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATARegNSectorHOB);
6744 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATARegSector);
6745 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATARegSectorHOB);
6746 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATARegLCyl);
6747 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATARegLCylHOB);
6748 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATARegHCyl);
6749 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATARegHCylHOB);
6750 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATARegSelect);
6751 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATARegStatus);
6752 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATARegCommand);
6753 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATARegDevCtl);
6754 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uATATransferMode);
6755 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].uTxDir);
6756 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].iBeginTransfer);
6757 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].iSourceSink);
6758 SSMR3PutBool(pSSM, pThis->aCts[i].aIfs[j].fDMA);
6759 SSMR3PutBool(pSSM, pThis->aCts[i].aIfs[j].fATAPITransfer);
6760 SSMR3PutU32(pSSM, pThis->aCts[i].aIfs[j].cbTotalTransfer);
6761 SSMR3PutU32(pSSM, pThis->aCts[i].aIfs[j].cbElementaryTransfer);
6762 SSMR3PutU32(pSSM, pThis->aCts[i].aIfs[j].iIOBufferCur);
6763 SSMR3PutU32(pSSM, pThis->aCts[i].aIfs[j].iIOBufferEnd);
6764 SSMR3PutU32(pSSM, pThis->aCts[i].aIfs[j].iIOBufferPIODataStart);
6765 SSMR3PutU32(pSSM, pThis->aCts[i].aIfs[j].iIOBufferPIODataEnd);
6766 SSMR3PutU32(pSSM, pThis->aCts[i].aIfs[j].iATAPILBA);
6767 SSMR3PutU32(pSSM, pThis->aCts[i].aIfs[j].cbATAPISector);
6768 SSMR3PutMem(pSSM, &pThis->aCts[i].aIfs[j].aATAPICmd, sizeof(pThis->aCts[i].aIfs[j].aATAPICmd));
6769 SSMR3PutMem(pSSM, &pThis->aCts[i].aIfs[j].abATAPISense, sizeof(pThis->aCts[i].aIfs[j].abATAPISense));
6770 SSMR3PutU8(pSSM, pThis->aCts[i].aIfs[j].cNotifiedMediaChange);
6771 SSMR3PutU32(pSSM, pThis->aCts[i].aIfs[j].MediaEventStatus);
6772 SSMR3PutMem(pSSM, &pThis->aCts[i].aIfs[j].Led, sizeof(pThis->aCts[i].aIfs[j].Led));
6773 SSMR3PutU32(pSSM, pThis->aCts[i].aIfs[j].cbIOBuffer);
6774 if (pThis->aCts[i].aIfs[j].cbIOBuffer)
6775 SSMR3PutMem(pSSM, pThis->aCts[i].aIfs[j].CTX_SUFF(pbIOBuffer), pThis->aCts[i].aIfs[j].cbIOBuffer);
6776 else
6777 Assert(pThis->aCts[i].aIfs[j].CTX_SUFF(pbIOBuffer) == NULL);
6778 }
6779 }
6780
6781 return SSMR3PutU32(pSSM, ~0); /* sanity/terminator */
6782}
6783
6784/**
6785 * Converts the LUN number into a message string.
6786 */
6787static const char *ataR3StringifyLun(unsigned iLun)
6788{
6789 switch (iLun)
6790 {
6791 case 0: return "primary master";
6792 case 1: return "primary slave";
6793 case 2: return "secondary master";
6794 case 3: return "secondary slave";
6795 default: AssertFailedReturn("unknown lun");
6796 }
6797}
6798
6799/**
6800 * FNSSMDEVLOADEXEC
6801 */
6802static DECLCALLBACK(int) ataR3LoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
6803{
6804 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
6805 int rc;
6806 uint32_t u32;
6807
6808 if ( uVersion != ATA_SAVED_STATE_VERSION
6809 && uVersion != ATA_SAVED_STATE_VERSION_VBOX_30
6810 && uVersion != ATA_SAVED_STATE_VERSION_WITHOUT_FULL_SENSE
6811 && uVersion != ATA_SAVED_STATE_VERSION_WITHOUT_EVENT_STATUS
6812 && uVersion != ATA_SAVED_STATE_VERSION_WITH_BOOL_TYPE)
6813 {
6814 AssertMsgFailed(("uVersion=%d\n", uVersion));
6815 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
6816 }
6817
6818 /*
6819 * Verify the configuration.
6820 */
6821 if (uVersion > ATA_SAVED_STATE_VERSION_VBOX_30)
6822 {
6823 uint8_t u8Type;
6824 rc = SSMR3GetU8(pSSM, &u8Type);
6825 AssertRCReturn(rc, rc);
6826 if (u8Type != pThis->u8Type)
6827 return SSMR3SetCfgError(pSSM, RT_SRC_POS, N_("Config mismatch: u8Type - saved=%u config=%u"), u8Type, pThis->u8Type);
6828
6829 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
6830 {
6831 bool fEnabled;
6832 rc = SSMR3GetBool(pSSM, &fEnabled);
6833 AssertRCReturn(rc, rc);
6834 if (!fEnabled)
6835 return SSMR3SetCfgError(pSSM, RT_SRC_POS, N_("Ctr#%u onfig mismatch: fEnabled != true"), i);
6836
6837 for (uint32_t j = 0; j < RT_ELEMENTS(pThis->aCts[i].aIfs); j++)
6838 {
6839 ATADevState const *pIf = &pThis->aCts[i].aIfs[j];
6840
6841 bool fInUse;
6842 rc = SSMR3GetBool(pSSM, &fInUse);
6843 AssertRCReturn(rc, rc);
6844 if (fInUse != (pIf->pDrvBase != NULL))
6845 return SSMR3SetCfgError(pSSM, RT_SRC_POS,
6846 N_("The %s VM is missing a %s device. Please make sure the source and target VMs have compatible storage configurations"),
6847 fInUse ? "target" : "source", ataR3StringifyLun(pIf->iLUN) );
6848
6849 char szSerialNumber[ATA_SERIAL_NUMBER_LENGTH+1];
6850 rc = SSMR3GetStrZ(pSSM, szSerialNumber, sizeof(szSerialNumber));
6851 AssertRCReturn(rc, rc);
6852 if (strcmp(szSerialNumber, pIf->szSerialNumber))
6853 LogRel(("PIIX3 ATA: LUN#%u config mismatch: Serial number - saved='%s' config='%s'\n",
6854 pIf->iLUN, szSerialNumber, pIf->szSerialNumber));
6855
6856 char szFirmwareRevision[ATA_FIRMWARE_REVISION_LENGTH+1];
6857 rc = SSMR3GetStrZ(pSSM, szFirmwareRevision, sizeof(szFirmwareRevision));
6858 AssertRCReturn(rc, rc);
6859 if (strcmp(szFirmwareRevision, pIf->szFirmwareRevision))
6860 LogRel(("PIIX3 ATA: LUN#%u config mismatch: Firmware revision - saved='%s' config='%s'\n",
6861 pIf->iLUN, szFirmwareRevision, pIf->szFirmwareRevision));
6862
6863 char szModelNumber[ATA_MODEL_NUMBER_LENGTH+1];
6864 rc = SSMR3GetStrZ(pSSM, szModelNumber, sizeof(szModelNumber));
6865 AssertRCReturn(rc, rc);
6866 if (strcmp(szModelNumber, pIf->szModelNumber))
6867 LogRel(("PIIX3 ATA: LUN#%u config mismatch: Model number - saved='%s' config='%s'\n",
6868 pIf->iLUN, szModelNumber, pIf->szModelNumber));
6869 }
6870 }
6871 }
6872 if (uPass != SSM_PASS_FINAL)
6873 return VINF_SUCCESS;
6874
6875 /*
6876 * Restore valid parts of the PCIATAState structure
6877 */
6878 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
6879 {
6880 /* integrity check */
6881 if (!ataR3AsyncIOIsIdle(&pThis->aCts[i], false))
6882 {
6883 AssertMsgFailed(("Async I/O for controller %d is active\n", i));
6884 return VERR_INTERNAL_ERROR_4;
6885 }
6886
6887 SSMR3GetU8(pSSM, &pThis->aCts[i].iSelectedIf);
6888 SSMR3GetU8(pSSM, &pThis->aCts[i].iAIOIf);
6889 SSMR3GetU8(pSSM, &pThis->aCts[i].uAsyncIOState);
6890 SSMR3GetBool(pSSM, &pThis->aCts[i].fChainedTransfer);
6891 SSMR3GetBool(pSSM, (bool *)&pThis->aCts[i].fReset);
6892 SSMR3GetBool(pSSM, (bool *)&pThis->aCts[i].fRedo);
6893 SSMR3GetBool(pSSM, (bool *)&pThis->aCts[i].fRedoIdle);
6894 SSMR3GetBool(pSSM, (bool *)&pThis->aCts[i].fRedoDMALastDesc);
6895 SSMR3GetMem(pSSM, &pThis->aCts[i].BmDma, sizeof(pThis->aCts[i].BmDma));
6896 SSMR3GetGCPhys32(pSSM, &pThis->aCts[i].pFirstDMADesc);
6897 SSMR3GetGCPhys32(pSSM, &pThis->aCts[i].pLastDMADesc);
6898 SSMR3GetGCPhys32(pSSM, &pThis->aCts[i].pRedoDMABuffer);
6899 SSMR3GetU32(pSSM, &pThis->aCts[i].cbRedoDMABuffer);
6900
6901 for (uint32_t j = 0; j < RT_ELEMENTS(pThis->aCts[i].aIfs); j++)
6902 {
6903 SSMR3GetBool(pSSM, &pThis->aCts[i].aIfs[j].fLBA48);
6904 SSMR3GetBool(pSSM, &pThis->aCts[i].aIfs[j].fATAPI);
6905 SSMR3GetBool(pSSM, &pThis->aCts[i].aIfs[j].fIrqPending);
6906 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].cMultSectors);
6907 SSMR3GetU32(pSSM, &pThis->aCts[i].aIfs[j].PCHSGeometry.cCylinders);
6908 SSMR3GetU32(pSSM, &pThis->aCts[i].aIfs[j].PCHSGeometry.cHeads);
6909 SSMR3GetU32(pSSM, &pThis->aCts[i].aIfs[j].PCHSGeometry.cSectors);
6910 SSMR3GetU32(pSSM, &pThis->aCts[i].aIfs[j].cSectorsPerIRQ);
6911 SSMR3GetU64(pSSM, &pThis->aCts[i].aIfs[j].cTotalSectors);
6912 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATARegFeature);
6913 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATARegFeatureHOB);
6914 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATARegError);
6915 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATARegNSector);
6916 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATARegNSectorHOB);
6917 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATARegSector);
6918 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATARegSectorHOB);
6919 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATARegLCyl);
6920 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATARegLCylHOB);
6921 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATARegHCyl);
6922 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATARegHCylHOB);
6923 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATARegSelect);
6924 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATARegStatus);
6925 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATARegCommand);
6926 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATARegDevCtl);
6927 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uATATransferMode);
6928 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].uTxDir);
6929 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].iBeginTransfer);
6930 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].iSourceSink);
6931 SSMR3GetBool(pSSM, &pThis->aCts[i].aIfs[j].fDMA);
6932 SSMR3GetBool(pSSM, &pThis->aCts[i].aIfs[j].fATAPITransfer);
6933 SSMR3GetU32(pSSM, &pThis->aCts[i].aIfs[j].cbTotalTransfer);
6934 SSMR3GetU32(pSSM, &pThis->aCts[i].aIfs[j].cbElementaryTransfer);
6935 /* NB: cbPIOTransferLimit could be saved/restored but it's sufficient
6936 * to re-calculate it here, with a tiny risk that it could be
6937 * unnecessarily low for the current transfer only. Could be changed
6938 * when changing the saved state in the future.
6939 */
6940 pThis->aCts[i].aIfs[j].cbPIOTransferLimit = (pThis->aCts[i].aIfs[j].uATARegHCyl << 8) | pThis->aCts[i].aIfs[j].uATARegLCyl;
6941 SSMR3GetU32(pSSM, &pThis->aCts[i].aIfs[j].iIOBufferCur);
6942 SSMR3GetU32(pSSM, &pThis->aCts[i].aIfs[j].iIOBufferEnd);
6943 SSMR3GetU32(pSSM, &pThis->aCts[i].aIfs[j].iIOBufferPIODataStart);
6944 SSMR3GetU32(pSSM, &pThis->aCts[i].aIfs[j].iIOBufferPIODataEnd);
6945 SSMR3GetU32(pSSM, &pThis->aCts[i].aIfs[j].iATAPILBA);
6946 SSMR3GetU32(pSSM, &pThis->aCts[i].aIfs[j].cbATAPISector);
6947 SSMR3GetMem(pSSM, &pThis->aCts[i].aIfs[j].aATAPICmd, sizeof(pThis->aCts[i].aIfs[j].aATAPICmd));
6948 if (uVersion > ATA_SAVED_STATE_VERSION_WITHOUT_FULL_SENSE)
6949 {
6950 SSMR3GetMem(pSSM, pThis->aCts[i].aIfs[j].abATAPISense, sizeof(pThis->aCts[i].aIfs[j].abATAPISense));
6951 }
6952 else
6953 {
6954 uint8_t uATAPISenseKey, uATAPIASC;
6955 memset(pThis->aCts[i].aIfs[j].abATAPISense, '\0', sizeof(pThis->aCts[i].aIfs[j].abATAPISense));
6956 pThis->aCts[i].aIfs[j].abATAPISense[0] = 0x70 | (1 << 7);
6957 pThis->aCts[i].aIfs[j].abATAPISense[7] = 10;
6958 SSMR3GetU8(pSSM, &uATAPISenseKey);
6959 SSMR3GetU8(pSSM, &uATAPIASC);
6960 pThis->aCts[i].aIfs[j].abATAPISense[2] = uATAPISenseKey & 0x0f;
6961 pThis->aCts[i].aIfs[j].abATAPISense[12] = uATAPIASC;
6962 }
6963 /** @todo triple-check this hack after passthrough is working */
6964 SSMR3GetU8(pSSM, &pThis->aCts[i].aIfs[j].cNotifiedMediaChange);
6965 if (uVersion > ATA_SAVED_STATE_VERSION_WITHOUT_EVENT_STATUS)
6966 SSMR3GetU32(pSSM, (uint32_t*)&pThis->aCts[i].aIfs[j].MediaEventStatus);
6967 else
6968 pThis->aCts[i].aIfs[j].MediaEventStatus = ATA_EVENT_STATUS_UNCHANGED;
6969 SSMR3GetMem(pSSM, &pThis->aCts[i].aIfs[j].Led, sizeof(pThis->aCts[i].aIfs[j].Led));
6970 SSMR3GetU32(pSSM, &pThis->aCts[i].aIfs[j].cbIOBuffer);
6971 if (pThis->aCts[i].aIfs[j].cbIOBuffer)
6972 {
6973 if (pThis->aCts[i].aIfs[j].CTX_SUFF(pbIOBuffer))
6974 SSMR3GetMem(pSSM, pThis->aCts[i].aIfs[j].CTX_SUFF(pbIOBuffer), pThis->aCts[i].aIfs[j].cbIOBuffer);
6975 else
6976 {
6977 LogRel(("ATA: No buffer for %d/%d\n", i, j));
6978 if (SSMR3HandleGetAfter(pSSM) != SSMAFTER_DEBUG_IT)
6979 return SSMR3SetCfgError(pSSM, RT_SRC_POS, N_("No buffer for %d/%d"), i, j);
6980
6981 /* skip the buffer if we're loading for the debugger / animator. */
6982 uint8_t u8Ignored;
6983 size_t cbLeft = pThis->aCts[i].aIfs[j].cbIOBuffer;
6984 while (cbLeft-- > 0)
6985 SSMR3GetU8(pSSM, &u8Ignored);
6986 }
6987 }
6988 else
6989 Assert(pThis->aCts[i].aIfs[j].CTX_SUFF(pbIOBuffer) == NULL);
6990 }
6991 }
6992 if (uVersion <= ATA_SAVED_STATE_VERSION_VBOX_30)
6993 SSMR3GetU8(pSSM, &pThis->u8Type);
6994
6995 rc = SSMR3GetU32(pSSM, &u32);
6996 if (RT_FAILURE(rc))
6997 return rc;
6998 if (u32 != ~0U)
6999 {
7000 AssertMsgFailed(("u32=%#x expected ~0\n", u32));
7001 rc = VERR_SSM_DATA_UNIT_FORMAT_CHANGED;
7002 return rc;
7003 }
7004
7005 return VINF_SUCCESS;
7006}
7007
7008
7009/**
7010 * Callback employed by ataSuspend and ataR3PowerOff.
7011 *
7012 * @returns true if we've quiesced, false if we're still working.
7013 * @param pDevIns The device instance.
7014 */
7015static DECLCALLBACK(bool) ataR3IsAsyncSuspendOrPowerOffDone(PPDMDEVINS pDevIns)
7016{
7017 return ataR3AllAsyncIOIsIdle(pDevIns);
7018}
7019
7020
7021/**
7022 * Common worker for ataSuspend and ataR3PowerOff.
7023 */
7024static void ataR3SuspendOrPowerOff(PPDMDEVINS pDevIns)
7025{
7026 if (!ataR3AllAsyncIOIsIdle(pDevIns))
7027 PDMDevHlpSetAsyncNotification(pDevIns, ataR3IsAsyncSuspendOrPowerOffDone);
7028}
7029
7030
7031/**
7032 * Power Off notification.
7033 *
7034 * @returns VBox status.
7035 * @param pDevIns The device instance data.
7036 */
7037static DECLCALLBACK(void) ataR3PowerOff(PPDMDEVINS pDevIns)
7038{
7039 Log(("%s:\n", __FUNCTION__));
7040 ataR3SuspendOrPowerOff(pDevIns);
7041}
7042
7043
7044/**
7045 * Suspend notification.
7046 *
7047 * @returns VBox status.
7048 * @param pDevIns The device instance data.
7049 */
7050static DECLCALLBACK(void) ataR3Suspend(PPDMDEVINS pDevIns)
7051{
7052 Log(("%s:\n", __FUNCTION__));
7053 ataR3SuspendOrPowerOff(pDevIns);
7054}
7055
7056
7057/**
7058 * Callback employed by ataR3Reset.
7059 *
7060 * @returns true if we've quiesced, false if we're still working.
7061 * @param pDevIns The device instance.
7062 */
7063static DECLCALLBACK(bool) ataR3IsAsyncResetDone(PPDMDEVINS pDevIns)
7064{
7065 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
7066
7067 if (!ataR3AllAsyncIOIsIdle(pDevIns))
7068 return false;
7069
7070 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
7071 {
7072 PDMCritSectEnter(&pThis->aCts[i].lock, VERR_INTERNAL_ERROR);
7073 for (uint32_t j = 0; j < RT_ELEMENTS(pThis->aCts[i].aIfs); j++)
7074 ataR3ResetDevice(&pThis->aCts[i].aIfs[j]);
7075 PDMCritSectLeave(&pThis->aCts[i].lock);
7076 }
7077 return true;
7078}
7079
7080
7081/**
7082 * Common reset worker for ataR3Reset and ataR3Construct.
7083 *
7084 * @returns VBox status.
7085 * @param pDevIns The device instance data.
7086 * @param fConstruct Indicates who is calling.
7087 */
7088static int ataR3ResetCommon(PPDMDEVINS pDevIns, bool fConstruct)
7089{
7090 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
7091
7092 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
7093 {
7094 PDMCritSectEnter(&pThis->aCts[i].lock, VERR_INTERNAL_ERROR);
7095
7096 pThis->aCts[i].iSelectedIf = 0;
7097 pThis->aCts[i].iAIOIf = 0;
7098 pThis->aCts[i].BmDma.u8Cmd = 0;
7099 /* Report that both drives present on the bus are in DMA mode. This
7100 * pretends that there is a BIOS that has set it up. Normal reset
7101 * default is 0x00. */
7102 pThis->aCts[i].BmDma.u8Status = (pThis->aCts[i].aIfs[0].pDrvBase != NULL ? BM_STATUS_D0DMA : 0)
7103 | (pThis->aCts[i].aIfs[1].pDrvBase != NULL ? BM_STATUS_D1DMA : 0);
7104 pThis->aCts[i].BmDma.pvAddr = 0;
7105
7106 pThis->aCts[i].fReset = true;
7107 pThis->aCts[i].fRedo = false;
7108 pThis->aCts[i].fRedoIdle = false;
7109 ataR3AsyncIOClearRequests(&pThis->aCts[i]);
7110 Log2(("%s: Ctl#%d: message to async I/O thread, reset controller\n", __FUNCTION__, i));
7111 ataHCAsyncIOPutRequest(&pThis->aCts[i], &g_ataResetARequest);
7112 ataHCAsyncIOPutRequest(&pThis->aCts[i], &g_ataResetCRequest);
7113
7114 PDMCritSectLeave(&pThis->aCts[i].lock);
7115 }
7116
7117 int rcRet = VINF_SUCCESS;
7118 if (!fConstruct)
7119 {
7120 /*
7121 * Setup asynchronous notification completion if the requests haven't
7122 * completed yet.
7123 */
7124 if (!ataR3IsAsyncResetDone(pDevIns))
7125 PDMDevHlpSetAsyncNotification(pDevIns, ataR3IsAsyncResetDone);
7126 }
7127 else
7128 {
7129 /*
7130 * Wait for the requests for complete.
7131 *
7132 * Would be real nice if we could do it all from EMT(0) and not
7133 * involve the worker threads, then we could dispense with all the
7134 * waiting and semaphore ping-pong here...
7135 */
7136 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
7137 {
7138 if (pThis->aCts[i].AsyncIOThread != NIL_RTTHREAD)
7139 {
7140 int rc = PDMCritSectEnter(&pThis->aCts[i].AsyncIORequestLock, VERR_IGNORED);
7141 AssertRC(rc);
7142
7143 ASMAtomicWriteBool(&pThis->aCts[i].fSignalIdle, true);
7144 rc = RTThreadUserReset(pThis->aCts[i].AsyncIOThread);
7145 AssertRC(rc);
7146
7147 rc = PDMCritSectLeave(&pThis->aCts[i].AsyncIORequestLock);
7148 AssertRC(rc);
7149
7150 if (!ataR3AsyncIOIsIdle(&pThis->aCts[i], false /*fStrict*/))
7151 {
7152 rc = RTThreadUserWait(pThis->aCts[i].AsyncIOThread, 30*1000 /*ms*/);
7153 if (RT_FAILURE(rc))
7154 rc = RTThreadUserWait(pThis->aCts[i].AsyncIOThread, 1000 /*ms*/);
7155 if (RT_FAILURE(rc))
7156 {
7157 AssertRC(rc);
7158 rcRet = rc;
7159 }
7160 }
7161 }
7162 ASMAtomicWriteBool(&pThis->aCts[i].fSignalIdle, false);
7163 }
7164 if (RT_SUCCESS(rcRet))
7165 {
7166 rcRet = ataR3IsAsyncResetDone(pDevIns) ? VINF_SUCCESS : VERR_INTERNAL_ERROR;
7167 AssertRC(rcRet);
7168 }
7169 }
7170 return rcRet;
7171}
7172
7173/**
7174 * Reset notification.
7175 *
7176 * @param pDevIns The device instance data.
7177 */
7178static DECLCALLBACK(void) ataR3Reset(PPDMDEVINS pDevIns)
7179{
7180 ataR3ResetCommon(pDevIns, false /*fConstruct*/);
7181}
7182
7183/**
7184 * @copydoc FNPDMDEVRELOCATE
7185 */
7186static DECLCALLBACK(void) ataR3Relocate(PPDMDEVINS pDevIns, RTGCINTPTR offDelta)
7187{
7188 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
7189
7190 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
7191 {
7192 pThis->aCts[i].pDevInsRC += offDelta;
7193 pThis->aCts[i].aIfs[0].pDevInsRC += offDelta;
7194 pThis->aCts[i].aIfs[0].pControllerRC += offDelta;
7195 ataR3RelocBuffer(pDevIns, &pThis->aCts[i].aIfs[0]);
7196 pThis->aCts[i].aIfs[1].pDevInsRC += offDelta;
7197 pThis->aCts[i].aIfs[1].pControllerRC += offDelta;
7198 ataR3RelocBuffer(pDevIns, &pThis->aCts[i].aIfs[1]);
7199 }
7200}
7201
7202/**
7203 * Destroy a driver instance.
7204 *
7205 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
7206 * resources can be freed correctly.
7207 *
7208 * @param pDevIns The device instance data.
7209 */
7210static DECLCALLBACK(int) ataR3Destruct(PPDMDEVINS pDevIns)
7211{
7212 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
7213 int rc;
7214
7215 Log(("ataR3Destruct\n"));
7216 PDMDEV_CHECK_VERSIONS_RETURN_QUIET(pDevIns);
7217
7218 /*
7219 * Tell the async I/O threads to terminate.
7220 */
7221 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
7222 {
7223 if (pThis->aCts[i].AsyncIOThread != NIL_RTTHREAD)
7224 {
7225 ASMAtomicWriteU32(&pThis->aCts[i].fShutdown, true);
7226 rc = SUPSemEventSignal(pThis->aCts[i].pSupDrvSession, pThis->aCts[i].hAsyncIOSem);
7227 AssertRC(rc);
7228 rc = RTSemEventSignal(pThis->aCts[i].SuspendIOSem);
7229 AssertRC(rc);
7230 }
7231 }
7232
7233 /*
7234 * Wait for the threads to terminate before destroying their resources.
7235 */
7236 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
7237 {
7238 if (pThis->aCts[i].AsyncIOThread != NIL_RTTHREAD)
7239 {
7240 rc = RTThreadWait(pThis->aCts[i].AsyncIOThread, 30000 /* 30 s*/, NULL);
7241 if (RT_SUCCESS(rc))
7242 pThis->aCts[i].AsyncIOThread = NIL_RTTHREAD;
7243 else
7244 LogRel(("PIIX3 ATA Dtor: Ctl#%u is still executing, DevSel=%d AIOIf=%d CmdIf0=%#04x CmdIf1=%#04x rc=%Rrc\n",
7245 i, pThis->aCts[i].iSelectedIf, pThis->aCts[i].iAIOIf,
7246 pThis->aCts[i].aIfs[0].uATARegCommand, pThis->aCts[i].aIfs[1].uATARegCommand, rc));
7247 }
7248 }
7249
7250 /*
7251 * Free resources.
7252 */
7253 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
7254 {
7255 if (PDMCritSectIsInitialized(&pThis->aCts[i].AsyncIORequestLock))
7256 PDMR3CritSectDelete(&pThis->aCts[i].AsyncIORequestLock);
7257 if (pThis->aCts[i].hAsyncIOSem != NIL_SUPSEMEVENT)
7258 {
7259 SUPSemEventClose(pThis->aCts[i].pSupDrvSession, pThis->aCts[i].hAsyncIOSem);
7260 pThis->aCts[i].hAsyncIOSem = NIL_SUPSEMEVENT;
7261 }
7262 if (pThis->aCts[i].SuspendIOSem != NIL_RTSEMEVENT)
7263 {
7264 RTSemEventDestroy(pThis->aCts[i].SuspendIOSem);
7265 pThis->aCts[i].SuspendIOSem = NIL_RTSEMEVENT;
7266 }
7267
7268 /* try one final time */
7269 if (pThis->aCts[i].AsyncIOThread != NIL_RTTHREAD)
7270 {
7271 rc = RTThreadWait(pThis->aCts[i].AsyncIOThread, 1 /*ms*/, NULL);
7272 if (RT_SUCCESS(rc))
7273 {
7274 pThis->aCts[i].AsyncIOThread = NIL_RTTHREAD;
7275 LogRel(("PIIX3 ATA Dtor: Ctl#%u actually completed.\n", i));
7276 }
7277 }
7278
7279 for (uint32_t iIf = 0; iIf < RT_ELEMENTS(pThis->aCts[i].aIfs); iIf++)
7280 {
7281 if (pThis->aCts[i].aIfs[iIf].pTrackList)
7282 {
7283 ATAPIPassthroughTrackListDestroy(pThis->aCts[i].aIfs[iIf].pTrackList);
7284 pThis->aCts[i].aIfs[iIf].pTrackList = NULL;
7285 }
7286 }
7287 }
7288
7289 return VINF_SUCCESS;
7290}
7291
7292/**
7293 * Convert config value to DEVPCBIOSBOOT.
7294 *
7295 * @returns VBox status code.
7296 * @param pDevIns The device instance data.
7297 * @param pCfg Configuration handle.
7298 * @param penmChipset Where to store the chipset type.
7299 */
7300static int ataR3ControllerFromCfg(PPDMDEVINS pDevIns, PCFGMNODE pCfg, CHIPSET *penmChipset)
7301{
7302 char szType[20];
7303
7304 int rc = CFGMR3QueryStringDef(pCfg, "Type", &szType[0], sizeof(szType), "PIIX4");
7305 if (RT_FAILURE(rc))
7306 return PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS,
7307 N_("Configuration error: Querying \"Type\" as a string failed"));
7308 if (!strcmp(szType, "PIIX3"))
7309 *penmChipset = CHIPSET_PIIX3;
7310 else if (!strcmp(szType, "PIIX4"))
7311 *penmChipset = CHIPSET_PIIX4;
7312 else if (!strcmp(szType, "ICH6"))
7313 *penmChipset = CHIPSET_ICH6;
7314 else
7315 {
7316 PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS,
7317 N_("Configuration error: The \"Type\" value \"%s\" is unknown"),
7318 szType);
7319 rc = VERR_INTERNAL_ERROR;
7320 }
7321 return rc;
7322}
7323
7324/**
7325 * @interface_method_impl{PDMDEVREG,pfnConstruct}
7326 */
7327static DECLCALLBACK(int) ataR3Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
7328{
7329 PCIATAState *pThis = PDMINS_2_DATA(pDevIns, PCIATAState *);
7330 PPDMIBASE pBase;
7331 int rc;
7332 bool fRCEnabled;
7333 bool fR0Enabled;
7334 uint32_t DelayIRQMillies;
7335
7336 Assert(iInstance == 0);
7337 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
7338
7339 /*
7340 * Initialize NIL handle values (for the destructor).
7341 */
7342 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
7343 {
7344 pThis->aCts[i].hAsyncIOSem = NIL_SUPSEMEVENT;
7345 pThis->aCts[i].SuspendIOSem = NIL_RTSEMEVENT;
7346 pThis->aCts[i].AsyncIOThread = NIL_RTTHREAD;
7347 }
7348
7349 /*
7350 * Validate and read configuration.
7351 */
7352 if (!CFGMR3AreValuesValid(pCfg,
7353 "GCEnabled\0"
7354 "R0Enabled\0"
7355 "IRQDelay\0"
7356 "Type\0")
7357 /** @todo || invalid keys */)
7358 return PDMDEV_SET_ERROR(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES,
7359 N_("PIIX3 configuration error: unknown option specified"));
7360
7361 rc = CFGMR3QueryBoolDef(pCfg, "GCEnabled", &fRCEnabled, true);
7362 if (RT_FAILURE(rc))
7363 return PDMDEV_SET_ERROR(pDevIns, rc,
7364 N_("PIIX3 configuration error: failed to read GCEnabled as boolean"));
7365 Log(("%s: fRCEnabled=%d\n", __FUNCTION__, fRCEnabled));
7366
7367 rc = CFGMR3QueryBoolDef(pCfg, "R0Enabled", &fR0Enabled, true);
7368 if (RT_FAILURE(rc))
7369 return PDMDEV_SET_ERROR(pDevIns, rc,
7370 N_("PIIX3 configuration error: failed to read R0Enabled as boolean"));
7371 Log(("%s: fR0Enabled=%d\n", __FUNCTION__, fR0Enabled));
7372
7373 rc = CFGMR3QueryU32Def(pCfg, "IRQDelay", &DelayIRQMillies, 0);
7374 if (RT_FAILURE(rc))
7375 return PDMDEV_SET_ERROR(pDevIns, rc,
7376 N_("PIIX3 configuration error: failed to read IRQDelay as integer"));
7377 Log(("%s: DelayIRQMillies=%d\n", __FUNCTION__, DelayIRQMillies));
7378 Assert(DelayIRQMillies < 50);
7379
7380 CHIPSET enmChipset = CHIPSET_PIIX3;
7381 rc = ataR3ControllerFromCfg(pDevIns, pCfg, &enmChipset);
7382 if (RT_FAILURE(rc))
7383 return rc;
7384 pThis->u8Type = (uint8_t)enmChipset;
7385
7386 /*
7387 * Initialize data (most of it anyway).
7388 */
7389 /* Status LUN. */
7390 pThis->IBase.pfnQueryInterface = ataR3Status_QueryInterface;
7391 pThis->ILeds.pfnQueryStatusLed = ataR3Status_QueryStatusLed;
7392
7393 /* PCI configuration space. */
7394 PCIDevSetVendorId(&pThis->dev, 0x8086); /* Intel */
7395
7396 /*
7397 * When adding more IDE chipsets, don't forget to update pci_bios_init_device()
7398 * as it explicitly checks for PCI id for IDE controllers.
7399 */
7400 switch (pThis->u8Type)
7401 {
7402 case CHIPSET_ICH6:
7403 PCIDevSetDeviceId(&pThis->dev, 0x269e); /* ICH6 IDE */
7404 /** @todo: do we need it? Do we need anything else? */
7405 pThis->dev.config[0x48] = 0x00; /* UDMACTL */
7406 pThis->dev.config[0x4A] = 0x00; /* UDMATIM */
7407 pThis->dev.config[0x4B] = 0x00;
7408 {
7409 /*
7410 * See www.intel.com/Assets/PDF/manual/298600.pdf p. 30
7411 * Report
7412 * WR_Ping-Pong_EN: must be set
7413 * PCR0, PCR1: 80-pin primary cable reporting for both disks
7414 * SCR0, SCR1: 80-pin secondary cable reporting for both disks
7415 */
7416 uint16_t u16Config = (1<<10) | (1<<7) | (1<<6) | (1<<5) | (1<<4) ;
7417 pThis->dev.config[0x54] = u16Config & 0xff;
7418 pThis->dev.config[0x55] = u16Config >> 8;
7419 }
7420 break;
7421 case CHIPSET_PIIX4:
7422 PCIDevSetDeviceId(&pThis->dev, 0x7111); /* PIIX4 IDE */
7423 PCIDevSetRevisionId(&pThis->dev, 0x01); /* PIIX4E */
7424 pThis->dev.config[0x48] = 0x00; /* UDMACTL */
7425 pThis->dev.config[0x4A] = 0x00; /* UDMATIM */
7426 pThis->dev.config[0x4B] = 0x00;
7427 break;
7428 case CHIPSET_PIIX3:
7429 PCIDevSetDeviceId(&pThis->dev, 0x7010); /* PIIX3 IDE */
7430 break;
7431 default:
7432 AssertMsgFailed(("Unsupported IDE chipset type: %d\n", pThis->u8Type));
7433 }
7434
7435 PCIDevSetCommand( &pThis->dev, PCI_COMMAND_IOACCESS | PCI_COMMAND_MEMACCESS | PCI_COMMAND_BUSMASTER);
7436 PCIDevSetClassProg( &pThis->dev, 0x8a); /* programming interface = PCI_IDE bus master is supported */
7437 PCIDevSetClassSub( &pThis->dev, 0x01); /* class_sub = PCI_IDE */
7438 PCIDevSetClassBase( &pThis->dev, 0x01); /* class_base = PCI_mass_storage */
7439 PCIDevSetHeaderType(&pThis->dev, 0x00);
7440
7441 pThis->pDevIns = pDevIns;
7442 pThis->fRCEnabled = fRCEnabled;
7443 pThis->fR0Enabled = fR0Enabled;
7444 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
7445 {
7446 pThis->aCts[i].pDevInsR3 = pDevIns;
7447 pThis->aCts[i].pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
7448 pThis->aCts[i].pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
7449 pThis->aCts[i].DelayIRQMillies = (uint32_t)DelayIRQMillies;
7450 for (uint32_t j = 0; j < RT_ELEMENTS(pThis->aCts[i].aIfs); j++)
7451 {
7452 ATADevState *pIf = &pThis->aCts[i].aIfs[j];
7453
7454 pIf->iLUN = i * RT_ELEMENTS(pThis->aCts) + j;
7455 pIf->pDevInsR3 = pDevIns;
7456 pIf->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
7457 pIf->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
7458 pIf->pControllerR3 = &pThis->aCts[i];
7459 pIf->pControllerR0 = MMHyperR3ToR0(PDMDevHlpGetVM(pDevIns), &pThis->aCts[i]);
7460 pIf->pControllerRC = MMHyperR3ToRC(PDMDevHlpGetVM(pDevIns), &pThis->aCts[i]);
7461 pIf->IBase.pfnQueryInterface = ataR3QueryInterface;
7462 pIf->IMountNotify.pfnMountNotify = ataR3MountNotify;
7463 pIf->IMountNotify.pfnUnmountNotify = ataR3UnmountNotify;
7464 pIf->IPort.pfnQueryDeviceLocation = ataR3QueryDeviceLocation;
7465 pIf->Led.u32Magic = PDMLED_MAGIC;
7466 }
7467 }
7468
7469 Assert(RT_ELEMENTS(pThis->aCts) == 2);
7470 pThis->aCts[0].irq = 14;
7471 pThis->aCts[0].IOPortBase1 = 0x1f0;
7472 pThis->aCts[0].IOPortBase2 = 0x3f6;
7473 pThis->aCts[1].irq = 15;
7474 pThis->aCts[1].IOPortBase1 = 0x170;
7475 pThis->aCts[1].IOPortBase2 = 0x376;
7476
7477 /*
7478 * Set the default critical section to NOP as we lock on controller level.
7479 */
7480 rc = PDMDevHlpSetDeviceCritSect(pDevIns, PDMDevHlpCritSectGetNop(pDevIns));
7481 AssertRCReturn(rc, rc);
7482
7483 /*
7484 * Register the PCI device.
7485 * N.B. There's a hack in the PIIX3 PCI bridge device to assign this
7486 * device the slot next to itself.
7487 */
7488 rc = PDMDevHlpPCIRegister(pDevIns, &pThis->dev);
7489 if (RT_FAILURE(rc))
7490 return PDMDEV_SET_ERROR(pDevIns, rc,
7491 N_("PIIX3 cannot register PCI device"));
7492 //AssertMsg(pThis->dev.devfn == 9 || iInstance != 0, ("pThis->dev.devfn=%d\n", pThis->dev.devfn));
7493 rc = PDMDevHlpPCIIORegionRegister(pDevIns, 4, 0x10, PCI_ADDRESS_SPACE_IO, ataR3BMDMAIORangeMap);
7494 if (RT_FAILURE(rc))
7495 return PDMDEV_SET_ERROR(pDevIns, rc,
7496 N_("PIIX3 cannot register PCI I/O region for BMDMA"));
7497
7498 /*
7499 * Register the I/O ports.
7500 * The ports are all hardcoded and enforced by the PIIX3 host bridge controller.
7501 */
7502 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
7503 {
7504 rc = PDMDevHlpIOPortRegister(pDevIns, pThis->aCts[i].IOPortBase1, 1, (RTHCPTR)(uintptr_t)i,
7505 ataIOPortWrite1Data, ataIOPortRead1Data,
7506 ataIOPortWriteStr1Data, ataIOPortReadStr1Data, "ATA I/O Base 1 - Data");
7507 AssertLogRelRCReturn(rc, rc);
7508 rc = PDMDevHlpIOPortRegister(pDevIns, pThis->aCts[i].IOPortBase1 + 1, 7, (RTHCPTR)(uintptr_t)i,
7509 ataIOPortWrite1Other, ataIOPortRead1Other, NULL, NULL, "ATA I/O Base 1 - Other");
7510
7511 AssertLogRelRCReturn(rc, rc);
7512 if (fRCEnabled)
7513 {
7514 rc = PDMDevHlpIOPortRegisterRC(pDevIns, pThis->aCts[i].IOPortBase1, 1, (RTGCPTR)i,
7515 "ataIOPortWrite1Data", "ataIOPortRead1Data",
7516 "ataIOPortWriteStr1Data", "ataIOPortReadStr1Data", "ATA I/O Base 1 - Data");
7517 AssertLogRelRCReturn(rc, rc);
7518 rc = PDMDevHlpIOPortRegisterRC(pDevIns, pThis->aCts[i].IOPortBase1 + 1, 7, (RTGCPTR)i,
7519 "ataIOPortWrite1Other", "ataIOPortRead1Other", NULL, NULL, "ATA I/O Base 1 - Other");
7520 AssertLogRelRCReturn(rc, rc);
7521 }
7522
7523 if (fR0Enabled)
7524 {
7525#if 0
7526 rc = PDMDevHlpIOPortRegisterR0(pDevIns, pThis->aCts[i].IOPortBase1, 1, (RTR0PTR)i,
7527 "ataIOPortWrite1Data", "ataIOPortRead1Data", NULL, NULL, "ATA I/O Base 1 - Data");
7528#else
7529 rc = PDMDevHlpIOPortRegisterR0(pDevIns, pThis->aCts[i].IOPortBase1, 1, (RTR0PTR)i,
7530 "ataIOPortWrite1Data", "ataIOPortRead1Data",
7531 "ataIOPortWriteStr1Data", "ataIOPortReadStr1Data", "ATA I/O Base 1 - Data");
7532#endif
7533 AssertLogRelRCReturn(rc, rc);
7534 rc = PDMDevHlpIOPortRegisterR0(pDevIns, pThis->aCts[i].IOPortBase1 + 1, 7, (RTR0PTR)i,
7535 "ataIOPortWrite1Other", "ataIOPortRead1Other", NULL, NULL, "ATA I/O Base 1 - Other");
7536 AssertLogRelRCReturn(rc, rc);
7537 }
7538
7539 rc = PDMDevHlpIOPortRegister(pDevIns, pThis->aCts[i].IOPortBase2, 1, (RTHCPTR)(uintptr_t)i,
7540 ataIOPortWrite2, ataIOPortRead2, NULL, NULL, "ATA I/O Base 2");
7541 if (RT_FAILURE(rc))
7542 return PDMDEV_SET_ERROR(pDevIns, rc, N_("PIIX3 cannot register base2 I/O handlers"));
7543
7544 if (fRCEnabled)
7545 {
7546 rc = PDMDevHlpIOPortRegisterRC(pDevIns, pThis->aCts[i].IOPortBase2, 1, (RTGCPTR)i,
7547 "ataIOPortWrite2", "ataIOPortRead2", NULL, NULL, "ATA I/O Base 2");
7548 if (RT_FAILURE(rc))
7549 return PDMDEV_SET_ERROR(pDevIns, rc, N_("PIIX3 cannot register base2 I/O handlers (GC)"));
7550 }
7551 if (fR0Enabled)
7552 {
7553 rc = PDMDevHlpIOPortRegisterR0(pDevIns, pThis->aCts[i].IOPortBase2, 1, (RTR0PTR)i,
7554 "ataIOPortWrite2", "ataIOPortRead2", NULL, NULL, "ATA I/O Base 2");
7555 if (RT_FAILURE(rc))
7556 return PDMDEV_SET_ERROR(pDevIns, rc, N_("PIIX3 cannot register base2 I/O handlers (R0)"));
7557 }
7558
7559 for (uint32_t j = 0; j < RT_ELEMENTS(pThis->aCts[i].aIfs); j++)
7560 {
7561 ATADevState *pIf = &pThis->aCts[i].aIfs[j];
7562 PDMDevHlpSTAMRegisterF(pDevIns, &pIf->StatATADMA, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES,
7563 "Number of ATA DMA transfers.", "/Devices/IDE%d/ATA%d/Unit%d/DMA", iInstance, i, j);
7564 PDMDevHlpSTAMRegisterF(pDevIns, &pIf->StatATAPIO, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES,
7565 "Number of ATA PIO transfers.", "/Devices/IDE%d/ATA%d/Unit%d/PIO", iInstance, i, j);
7566 PDMDevHlpSTAMRegisterF(pDevIns, &pIf->StatATAPIDMA, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES,
7567 "Number of ATAPI DMA transfers.", "/Devices/IDE%d/ATA%d/Unit%d/AtapiDMA", iInstance, i, j);
7568 PDMDevHlpSTAMRegisterF(pDevIns, &pIf->StatATAPIPIO, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES,
7569 "Number of ATAPI PIO transfers.", "/Devices/IDE%d/ATA%d/Unit%d/AtapiPIO", iInstance, i, j);
7570#ifdef VBOX_WITH_STATISTICS /** @todo release too. */
7571 PDMDevHlpSTAMRegisterF(pDevIns, &pIf->StatReads, STAMTYPE_PROFILE_ADV, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL,
7572 "Profiling of the read operations.", "/Devices/IDE%d/ATA%d/Unit%d/Reads", iInstance, i, j);
7573#endif
7574 PDMDevHlpSTAMRegisterF(pDevIns, &pIf->StatBytesRead, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES,
7575 "Amount of data read.", "/Devices/IDE%d/ATA%d/Unit%d/ReadBytes", iInstance, i, j);
7576#ifdef VBOX_INSTRUMENT_DMA_WRITES
7577 PDMDevHlpSTAMRegisterF(pDevIns, &pIf->StatInstrVDWrites,STAMTYPE_PROFILE_ADV, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL,
7578 "Profiling of the VD DMA write operations.", "/Devices/IDE%d/ATA%d/Unit%d/InstrVDWrites", iInstance, i, j);
7579#endif
7580#ifdef VBOX_WITH_STATISTICS
7581 PDMDevHlpSTAMRegisterF(pDevIns, &pIf->StatWrites, STAMTYPE_PROFILE_ADV, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL,
7582 "Profiling of the write operations.", "/Devices/IDE%d/ATA%d/Unit%d/Writes", iInstance, i, j);
7583#endif
7584 PDMDevHlpSTAMRegisterF(pDevIns, &pIf->StatBytesWritten, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES,
7585 "Amount of data written.", "/Devices/IDE%d/ATA%d/Unit%d/WrittenBytes", iInstance, i, j);
7586#ifdef VBOX_WITH_STATISTICS
7587 PDMDevHlpSTAMRegisterF(pDevIns, &pIf->StatFlushes, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL,
7588 "Profiling of the flush operations.", "/Devices/IDE%d/ATA%d/Unit%d/Flushes", iInstance, i, j);
7589#endif
7590 }
7591#ifdef VBOX_WITH_STATISTICS /** @todo release too. */
7592 PDMDevHlpSTAMRegisterF(pDevIns, &pThis->aCts[i].StatAsyncOps, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES,
7593 "The number of async operations.", "/Devices/IDE%d/ATA%d/Async/Operations", iInstance, i);
7594 /** @todo STAMUNIT_MICROSECS */
7595 PDMDevHlpSTAMRegisterF(pDevIns, &pThis->aCts[i].StatAsyncMinWait, STAMTYPE_U64_RESET, STAMVISIBILITY_ALWAYS, STAMUNIT_NONE,
7596 "Minimum wait in microseconds.", "/Devices/IDE%d/ATA%d/Async/MinWait", iInstance, i);
7597 PDMDevHlpSTAMRegisterF(pDevIns, &pThis->aCts[i].StatAsyncMaxWait, STAMTYPE_U64_RESET, STAMVISIBILITY_ALWAYS, STAMUNIT_NONE,
7598 "Maximum wait in microseconds.", "/Devices/IDE%d/ATA%d/Async/MaxWait", iInstance, i);
7599 PDMDevHlpSTAMRegisterF(pDevIns, &pThis->aCts[i].StatAsyncTimeUS, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_NONE,
7600 "Total time spent in microseconds.", "/Devices/IDE%d/ATA%d/Async/TotalTimeUS", iInstance, i);
7601 PDMDevHlpSTAMRegisterF(pDevIns, &pThis->aCts[i].StatAsyncTime, STAMTYPE_PROFILE_ADV, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL,
7602 "Profiling of async operations.", "/Devices/IDE%d/ATA%d/Async/Time", iInstance, i);
7603 PDMDevHlpSTAMRegisterF(pDevIns, &pThis->aCts[i].StatLockWait, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL,
7604 "Profiling of locks.", "/Devices/IDE%d/ATA%d/Async/LockWait", iInstance, i);
7605#endif /* VBOX_WITH_STATISTICS */
7606
7607 /* Initialize per-controller critical section. */
7608 rc = PDMDevHlpCritSectInit(pDevIns, &pThis->aCts[i].lock, RT_SRC_POS, "ATA#%u-Ctl", i);
7609 AssertLogRelRCReturn(rc, rc);
7610
7611 /* Initialize per-controller async I/O request critical section. */
7612 rc = PDMDevHlpCritSectInit(pDevIns, &pThis->aCts[i].AsyncIORequestLock, RT_SRC_POS, "ATA#%u-Req", i);
7613 AssertLogRelRCReturn(rc, rc);
7614 }
7615
7616 /*
7617 * Attach status driver (optional).
7618 */
7619 rc = PDMDevHlpDriverAttach(pDevIns, PDM_STATUS_LUN, &pThis->IBase, &pBase, "Status Port");
7620 if (RT_SUCCESS(rc))
7621 {
7622 pThis->pLedsConnector = PDMIBASE_QUERY_INTERFACE(pBase, PDMILEDCONNECTORS);
7623 pThis->pMediaNotify = PDMIBASE_QUERY_INTERFACE(pBase, PDMIMEDIANOTIFY);
7624 }
7625 else if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
7626 {
7627 AssertMsgFailed(("Failed to attach to status driver. rc=%Rrc\n", rc));
7628 return PDMDEV_SET_ERROR(pDevIns, rc, N_("PIIX3 cannot attach to status driver"));
7629 }
7630
7631 /*
7632 * Attach the units.
7633 */
7634 uint32_t cbTotalBuffer = 0;
7635 for (uint32_t i = 0; i < RT_ELEMENTS(pThis->aCts); i++)
7636 {
7637 PATACONTROLLER pCtl = &pThis->aCts[i];
7638
7639 /*
7640 * Start the worker thread.
7641 */
7642 pCtl->uAsyncIOState = ATA_AIO_NEW;
7643 pCtl->pSupDrvSession = PDMDevHlpGetSupDrvSession(pDevIns);
7644 rc = SUPSemEventCreate(pCtl->pSupDrvSession, &pCtl->hAsyncIOSem);
7645 AssertLogRelRCReturn(rc, rc);
7646 rc = RTSemEventCreate(&pCtl->SuspendIOSem);
7647 AssertLogRelRCReturn(rc, rc);
7648
7649 ataR3AsyncIOClearRequests(pCtl);
7650 rc = RTThreadCreateF(&pCtl->AsyncIOThread, ataR3AsyncIOThread, (void *)pCtl, 128*1024 /*cbStack*/,
7651 RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "ATA-%u", i);
7652 AssertLogRelRCReturn(rc, rc);
7653 Assert( pCtl->AsyncIOThread != NIL_RTTHREAD && pCtl->hAsyncIOSem != NIL_SUPSEMEVENT
7654 && pCtl->SuspendIOSem != NIL_RTSEMEVENT && PDMCritSectIsInitialized(&pCtl->AsyncIORequestLock));
7655 Log(("%s: controller %d AIO thread id %#x; sem %p susp_sem %p\n", __FUNCTION__, i, pCtl->AsyncIOThread, pCtl->hAsyncIOSem, pCtl->SuspendIOSem));
7656
7657 for (uint32_t j = 0; j < RT_ELEMENTS(pCtl->aIfs); j++)
7658 {
7659 static const char *s_apszDescs[RT_ELEMENTS(pThis->aCts)][RT_ELEMENTS(pCtl->aIfs)] =
7660 {
7661 { "Primary Master", "Primary Slave" },
7662 { "Secondary Master", "Secondary Slave" }
7663 };
7664
7665 /*
7666 * Try attach the block device and get the interfaces,
7667 * required as well as optional.
7668 */
7669 ATADevState *pIf = &pCtl->aIfs[j];
7670
7671 rc = PDMDevHlpDriverAttach(pDevIns, pIf->iLUN, &pIf->IBase, &pIf->pDrvBase, s_apszDescs[i][j]);
7672 if (RT_SUCCESS(rc))
7673 {
7674 rc = ataR3ConfigLun(pDevIns, pIf);
7675 if (RT_SUCCESS(rc))
7676 {
7677 /*
7678 * Init vendor product data.
7679 */
7680 static const char *s_apszCFGMKeys[RT_ELEMENTS(pThis->aCts)][RT_ELEMENTS(pCtl->aIfs)] =
7681 {
7682 { "PrimaryMaster", "PrimarySlave" },
7683 { "SecondaryMaster", "SecondarySlave" }
7684 };
7685
7686 /* Generate a default serial number. */
7687 char szSerial[ATA_SERIAL_NUMBER_LENGTH+1];
7688 RTUUID Uuid;
7689 if (pIf->pDrvBlock)
7690 rc = pIf->pDrvBlock->pfnGetUuid(pIf->pDrvBlock, &Uuid);
7691 else
7692 RTUuidClear(&Uuid);
7693
7694 if (RT_FAILURE(rc) || RTUuidIsNull(&Uuid))
7695 {
7696 /* Generate a predictable serial for drives which don't have a UUID. */
7697 RTStrPrintf(szSerial, sizeof(szSerial), "VB%x-%04x%04x",
7698 pIf->iLUN + pDevIns->iInstance * 32,
7699 pThis->aCts[i].IOPortBase1, pThis->aCts[i].IOPortBase2);
7700 }
7701 else
7702 RTStrPrintf(szSerial, sizeof(szSerial), "VB%08x-%08x", Uuid.au32[0], Uuid.au32[3]);
7703
7704 /* Get user config if present using defaults otherwise. */
7705 PCFGMNODE pCfgNode = CFGMR3GetChild(pCfg, s_apszCFGMKeys[i][j]);
7706 rc = CFGMR3QueryStringDef(pCfgNode, "SerialNumber", pIf->szSerialNumber, sizeof(pIf->szSerialNumber),
7707 szSerial);
7708 if (RT_FAILURE(rc))
7709 {
7710 if (rc == VERR_CFGM_NOT_ENOUGH_SPACE)
7711 return PDMDEV_SET_ERROR(pDevIns, VERR_INVALID_PARAMETER,
7712 N_("PIIX3 configuration error: \"SerialNumber\" is longer than 20 bytes"));
7713 return PDMDEV_SET_ERROR(pDevIns, rc,
7714 N_("PIIX3 configuration error: failed to read \"SerialNumber\" as string"));
7715 }
7716
7717 rc = CFGMR3QueryStringDef(pCfgNode, "FirmwareRevision", pIf->szFirmwareRevision, sizeof(pIf->szFirmwareRevision),
7718 "1.0");
7719 if (RT_FAILURE(rc))
7720 {
7721 if (rc == VERR_CFGM_NOT_ENOUGH_SPACE)
7722 return PDMDEV_SET_ERROR(pDevIns, VERR_INVALID_PARAMETER,
7723 N_("PIIX3 configuration error: \"FirmwareRevision\" is longer than 8 bytes"));
7724 return PDMDEV_SET_ERROR(pDevIns, rc,
7725 N_("PIIX3 configuration error: failed to read \"FirmwareRevision\" as string"));
7726 }
7727
7728 rc = CFGMR3QueryStringDef(pCfgNode, "ModelNumber", pIf->szModelNumber, sizeof(pIf->szModelNumber),
7729 pIf->fATAPI ? "VBOX CD-ROM" : "VBOX HARDDISK");
7730 if (RT_FAILURE(rc))
7731 {
7732 if (rc == VERR_CFGM_NOT_ENOUGH_SPACE)
7733 return PDMDEV_SET_ERROR(pDevIns, VERR_INVALID_PARAMETER,
7734 N_("PIIX3 configuration error: \"ModelNumber\" is longer than 40 bytes"));
7735 return PDMDEV_SET_ERROR(pDevIns, rc,
7736 N_("PIIX3 configuration error: failed to read \"ModelNumber\" as string"));
7737 }
7738
7739 rc = CFGMR3QueryBoolDef(pCfgNode, "NonRotationalMedium", &pIf->fNonRotational, false);
7740 if (RT_FAILURE(rc))
7741 return PDMDEV_SET_ERROR(pDevIns, rc,
7742 N_("PIIX3 configuration error: failed to read \"NonRotationalMedium\" as boolean"));
7743
7744 /* There are three other identification strings for CD drives used for INQUIRY */
7745 if (pIf->fATAPI)
7746 {
7747 rc = CFGMR3QueryStringDef(pCfgNode, "ATAPIVendorId", pIf->szInquiryVendorId, sizeof(pIf->szInquiryVendorId),
7748 "VBOX");
7749 if (RT_FAILURE(rc))
7750 {
7751 if (rc == VERR_CFGM_NOT_ENOUGH_SPACE)
7752 return PDMDEV_SET_ERROR(pDevIns, VERR_INVALID_PARAMETER,
7753 N_("PIIX3 configuration error: \"ATAPIVendorId\" is longer than 16 bytes"));
7754 return PDMDEV_SET_ERROR(pDevIns, rc,
7755 N_("PIIX3 configuration error: failed to read \"ATAPIVendorId\" as string"));
7756 }
7757
7758 rc = CFGMR3QueryStringDef(pCfgNode, "ATAPIProductId", pIf->szInquiryProductId, sizeof(pIf->szInquiryProductId),
7759 "CD-ROM");
7760 if (RT_FAILURE(rc))
7761 {
7762 if (rc == VERR_CFGM_NOT_ENOUGH_SPACE)
7763 return PDMDEV_SET_ERROR(pDevIns, VERR_INVALID_PARAMETER,
7764 N_("PIIX3 configuration error: \"ATAPIProductId\" is longer than 16 bytes"));
7765 return PDMDEV_SET_ERROR(pDevIns, rc,
7766 N_("PIIX3 configuration error: failed to read \"ATAPIProductId\" as string"));
7767 }
7768
7769 rc = CFGMR3QueryStringDef(pCfgNode, "ATAPIRevision", pIf->szInquiryRevision, sizeof(pIf->szInquiryRevision),
7770 "1.0");
7771 if (RT_FAILURE(rc))
7772 {
7773 if (rc == VERR_CFGM_NOT_ENOUGH_SPACE)
7774 return PDMDEV_SET_ERROR(pDevIns, VERR_INVALID_PARAMETER,
7775 N_("PIIX3 configuration error: \"ATAPIRevision\" is longer than 4 bytes"));
7776 return PDMDEV_SET_ERROR(pDevIns, rc,
7777 N_("PIIX3 configuration error: failed to read \"ATAPIRevision\" as string"));
7778 }
7779
7780 rc = CFGMR3QueryBoolDef(pCfgNode, "OverwriteInquiry", &pIf->fOverwriteInquiry, true);
7781 if (RT_FAILURE(rc))
7782 return PDMDEV_SET_ERROR(pDevIns, rc,
7783 N_("PIIX3 configuration error: failed to read \"OverwriteInquiry\" as boolean"));
7784 }
7785 }
7786
7787 }
7788 else if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
7789 {
7790 pIf->pDrvBase = NULL;
7791 pIf->pDrvBlock = NULL;
7792 pIf->cbIOBuffer = 0;
7793 pIf->pbIOBufferR3 = NULL;
7794 pIf->pbIOBufferR0 = NIL_RTR0PTR;
7795 pIf->pbIOBufferRC = NIL_RTGCPTR;
7796 LogRel(("PIIX3 ATA: LUN#%d: no unit\n", pIf->iLUN));
7797 }
7798 else
7799 {
7800 switch (rc)
7801 {
7802 case VERR_ACCESS_DENIED:
7803 /* Error already cached by DrvHostBase */
7804 return rc;
7805 default:
7806 return PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS,
7807 N_("PIIX3 cannot attach drive to the %s"),
7808 s_apszDescs[i][j]);
7809 }
7810 }
7811 cbTotalBuffer += pIf->cbIOBuffer;
7812 }
7813 }
7814
7815 rc = PDMDevHlpSSMRegisterEx(pDevIns, ATA_SAVED_STATE_VERSION, sizeof(*pThis) + cbTotalBuffer, NULL,
7816 NULL, ataR3LiveExec, NULL,
7817 ataR3SaveLoadPrep, ataR3SaveExec, NULL,
7818 ataR3SaveLoadPrep, ataR3LoadExec, NULL);
7819 if (RT_FAILURE(rc))
7820 return PDMDEV_SET_ERROR(pDevIns, rc, N_("PIIX3 cannot register save state handlers"));
7821
7822 /*
7823 * Initialize the device state.
7824 */
7825 return ataR3ResetCommon(pDevIns, true /*fConstruct*/);
7826}
7827
7828
7829/**
7830 * The device registration structure.
7831 */
7832const PDMDEVREG g_DevicePIIX3IDE =
7833{
7834 /* u32Version */
7835 PDM_DEVREG_VERSION,
7836 /* szName */
7837 "piix3ide",
7838 /* szRCMod */
7839 "VBoxDDRC.rc",
7840 /* szR0Mod */
7841 "VBoxDDR0.r0",
7842 /* pszDescription */
7843 "Intel PIIX3 ATA controller.\n"
7844 " LUN #0 is primary master.\n"
7845 " LUN #1 is primary slave.\n"
7846 " LUN #2 is secondary master.\n"
7847 " LUN #3 is secondary slave.\n"
7848 " LUN #999 is the LED/Status connector.",
7849 /* fFlags */
7850 PDM_DEVREG_FLAGS_DEFAULT_BITS | PDM_DEVREG_FLAGS_RC | PDM_DEVREG_FLAGS_R0 |
7851 PDM_DEVREG_FLAGS_FIRST_SUSPEND_NOTIFICATION | PDM_DEVREG_FLAGS_FIRST_POWEROFF_NOTIFICATION |
7852 PDM_DEVREG_FLAGS_FIRST_RESET_NOTIFICATION,
7853 /* fClass */
7854 PDM_DEVREG_CLASS_STORAGE,
7855 /* cMaxInstances */
7856 1,
7857 /* cbInstance */
7858 sizeof(PCIATAState),
7859 /* pfnConstruct */
7860 ataR3Construct,
7861 /* pfnDestruct */
7862 ataR3Destruct,
7863 /* pfnRelocate */
7864 ataR3Relocate,
7865 /* pfnMemSetup */
7866 NULL,
7867 /* pfnPowerOn */
7868 NULL,
7869 /* pfnReset */
7870 ataR3Reset,
7871 /* pfnSuspend */
7872 ataR3Suspend,
7873 /* pfnResume */
7874 ataR3Resume,
7875 /* pfnAttach */
7876 ataR3Attach,
7877 /* pfnDetach */
7878 ataR3Detach,
7879 /* pfnQueryInterface. */
7880 NULL,
7881 /* pfnInitComplete */
7882 NULL,
7883 /* pfnPowerOff */
7884 ataR3PowerOff,
7885 /* pfnSoftReset */
7886 NULL,
7887 /* u32VersionEnd */
7888 PDM_DEVREG_VERSION
7889};
7890#endif /* IN_RING3 */
7891#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette