VirtualBox

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

最後變更 在這個檔案從7058是 7058,由 vboxsync 提交於 17 年 前

Added (disabled) instrumentation for measuring the time DMA writes to virtual disks take.

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

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