VirtualBox

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

Last change on this file since 45238 was 45025, checked in by vboxsync, 12 years ago

Update PDMDEVREG initialization comment so they refer to pfnMemSetup instead of pfnIOCtl.

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