VirtualBox

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

Last change on this file since 3199 was 3146, checked in by vboxsync, 18 years ago

Emulate all weird aspects of the IRQ line multiplexing. No guest has
dared to even come close to requiring this, but who knows what the
future brings.

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

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