VirtualBox

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

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

cosmetics

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

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