VirtualBox

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

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

That code path is only reached for PIO in case, which doesn't generate
the interrupt at the end. Copy/paste bug in combination with incorrect
manual constant propagation in the if condition.

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