VirtualBox

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

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

fail, don't break, if there is buffer data and we haven't got any buffer.

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