VirtualBox

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

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

Just do the simple 30 second wait for each worker thread. There shouldn't be timeouts, but it seems there is something busted in the linux (64-bit) multiple release event semaphores that makes them time out too early. (linux 2.6.23)

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