VirtualBox

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

Last change on this file since 33016 was 32943, checked in by vboxsync, 14 years ago

Storage/ATA: Clean up suspending the VM on certain errors, and make sure that a paused VM can be powered off straight away.

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