VirtualBox

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

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

Eliminated HCPTRTYPE and replaced with R3R0PTRTYPE where necessary.

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

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