VirtualBox

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

Last change on this file since 7630 was 7630, checked in by vboxsync, 17 years ago

Keep hitting the assertion in the wait code. Attempt to improve this by avoiding calling RTTimeMilliTS twice (RT_MAX() promise double eval of the winner) and force signed math.

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