VirtualBox

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

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

IDE: Make SCO OpenServer disk detection work

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