Modules/ATA - Soft reset devices during startup
[tpg/acess2.git] / KernelLand / Modules / Storage / ATA / io.c
1 /*
2  * Acess2 IDE Harddisk Driver
3  * - io.c
4  *
5  * Disk Input/Output control
6  */
7 #define DEBUG   0
8 #include <acess.h>
9 #include <modules.h>    // Needed for error codes
10 #include <drv_pci.h>
11 #include "common.h"
12 #include <events.h>
13 #include <timers.h>
14
15 // === MACROS ===
16 #define IO_DELAY()      do{inb(0x80); inb(0x80); inb(0x80); inb(0x80);}while(0)
17
18 // === Constants ===
19 #define IDE_PRI_BASE    0x1F0
20 #define IDE_PRI_CTRL    0x3F6
21 #define IDE_SEC_BASE    0x170
22 #define IDE_SEC_CTRL    0x376
23
24 #define IDE_PRDT_LAST   0x8000
25 /**
26  \enum HddControls
27  \brief Commands to be sent to HDD_CMD
28 */
29 enum HddControls {
30         HDD_PIO_R28 = 0x20,
31         HDD_PIO_R48 = 0x24,
32         HDD_DMA_R48 = 0x25,
33         HDD_PIO_W28 = 0x30,
34         HDD_PIO_W48 = 0x34,
35         HDD_DMA_W48 = 0x35,
36         HDD_DMA_R28 = 0xC8,
37         HDD_DMA_W28 = 0xCA,
38         HDD_IDENTIFY = 0xEC
39 };
40
41 // === TYPES ===
42 /**
43  * \brief PRDT Entry
44  */
45 typedef struct
46 {
47         Uint32  PBufAddr;       // Physical Buffer Address
48         Uint16  Bytes;  // Size of transfer entry
49         Uint16  Flags;  // Flags
50 } __attribute__ ((packed))      tPRDT_Ent;
51
52 /**
53  * \brief Structure returned by the ATA IDENTIFY command
54  */
55 typedef struct
56 {
57         Uint16  Flags;          // 1
58         Uint16  Usused1[9];     // 10
59         char    SerialNum[20];  // 20
60         Uint16  Usused2[3];     // 23
61         char    FirmwareVer[8]; // 27
62         char    ModelNumber[40];        // 47
63         Uint16  SectPerInt;     // 48 - Low byte only
64         Uint16  Unused3;        // 49
65         Uint16  Capabilities[2];        // 51
66         Uint16  Unused4[2];     // 53
67         Uint16  ValidExtData;   // 54
68         Uint16  Unused5[5];      // 59
69         Uint16  SizeOfRWMultiple;       // 60
70         Uint32  Sectors28;      // LBA 28 Sector Count
71         Uint16  Unused6[100-62];
72         Uint64  Sectors48;      // LBA 48 Sector Count
73         Uint16  Unused7[256-104];
74 } __attribute__ ((packed))      tIdentify;
75
76 // === PROTOTYPES ===
77  int    ATA_SetupIO(void);
78 Uint64  ATA_GetDiskSize(int Disk);
79 Uint16  ATA_GetBasePort(int Disk);
80 // Read/Write DMA
81  int    ATA_ReadDMA(Uint8 Disk, Uint64 Address, Uint Count, void *Buffer);
82  int    ATA_WriteDMA(Uint8 Disk, Uint64 Address, Uint Count, const void *Buffer);
83 // IRQs
84 void    ATA_IRQHandlerPri(int UNUSED(IRQ), void *UNUSED(Ptr));
85 void    ATA_IRQHandlerSec(int UNUSED(IRQ), void *UNUSED(Ptr));
86 // Controller IO
87 Uint8   ATA_int_BusMasterReadByte(int Ofs);
88 Uint32  ATA_int_BusMasterReadDWord(int Ofs);
89 void    ATA_int_BusMasterWriteByte(int Ofs, Uint8 Value);
90 void    ATA_int_BusMasterWriteDWord(int Ofs, Uint32 Value);
91
92 // === GLOBALS ===
93 // - BusMaster IO Addresses
94 Uint32  gATA_BusMasterBase;     //!< True Address (IO/MMIO)
95 Uint8   *gATA_BusMasterBasePtr; //!< Paging Mapped MMIO (If needed)
96 // - IRQs
97  int    gATA_IRQPri = 14;
98  int    gATA_IRQSec = 15;
99 volatile int    gaATA_IRQs[2] = {0};
100 tThread *gATA_WaitingThreads[2];
101 // - Locks to avoid tripping
102 tMutex  glaATA_ControllerLock[2];
103 // - Buffers!
104 void    *gATA_Buffers[2];
105 // - PRDTs
106 tPRDT_Ent       gATA_PRDTs[2] = {
107         {0, 512, IDE_PRDT_LAST},
108         {0, 512, IDE_PRDT_LAST}
109 };
110 tPAddr  gaATA_PRDT_PAddrs[2];
111
112 // === CODE ===
113 /**
114  * \brief Sets up the ATA controller's DMA mode
115  */
116 int ATA_SetupIO(void)
117 {
118          int    ent;
119
120         ENTER("");
121
122         // Get IDE Controller's PCI Entry
123         ent = PCI_GetDeviceByClass(0x010100, 0xFFFF00, -1);
124         LOG("ent = %i", ent);
125         gATA_BusMasterBase = PCI_GetBAR(ent, 4);
126         if( gATA_BusMasterBase == 0 ) {
127                 Log_Warning("ATA", "Unable to find a Bus Master DMA controller");
128                 // TODO: Use PIO mode instead
129                 LEAVE('i', MODULE_ERR_NOTNEEDED);
130                 return MODULE_ERR_NOTNEEDED;
131         }
132         
133         LOG("BAR5 = 0x%x", PCI_GetBAR(ent, 5));
134         LOG("IRQ = %i", PCI_GetIRQ(ent));
135
136         // Ensure controllers are present where we think they should be
137         for( int i = 0; i < 2; i ++ )
138         {
139                 Uint16  base = ATA_GetBasePort( i*2 );
140                 // Send Disk Selector
141                 outb(base+6, 0xA0);
142                 IO_DELAY();
143                 // Check for a floating bus
144                 if( 0xFF == inb(base+7) ) {
145                         Log_Error("ATA", "Floating bus at address 0x%x", base+7);
146                         LEAVE('i', MODULE_ERR_MISC);
147                         return MODULE_ERR_MISC;
148                 }
149         
150                 // Check for the controller
151                 // - Write to two RW ports and attempt to read back
152                 outb(base+0x02, 0x66);
153                 outb(base+0x03, 0xFF);
154                 if(inb(base+0x02) != 0x66 || inb(base+0x03) != 0xFF) {
155                         Log_Error("ATA", "Unable to write to 0x%x/0x%x", base+2, base+3);
156                         LEAVE('i', MODULE_ERR_MISC);
157                         return MODULE_ERR_MISC;
158                 }
159         }
160         
161         // Map memory
162         if( gATA_BusMasterBase & 1 )
163         {
164                 gATA_BusMasterBase &= ~1;
165                 LOG("gATA_BusMasterBase = IO 0x%x", gATA_BusMasterBase);
166         }
167         else
168         {
169                 // MMIO
170                 gATA_BusMasterBasePtr = MM_MapHWPages( gATA_BusMasterBase, 1 ) + (gATA_BusMasterBase&0xFFF);
171                 LOG("gATA_BusMasterBasePtr = %p", gATA_BusMasterBasePtr);
172         }
173
174         // Register IRQs and get Buffers
175         IRQ_AddHandler( gATA_IRQPri, ATA_IRQHandlerPri, NULL );
176         IRQ_AddHandler( gATA_IRQSec, ATA_IRQHandlerSec, NULL );
177
178         tPAddr  paddr;
179         gATA_Buffers[0] = (void*)MM_AllocDMA(1, 32, &paddr);
180         gATA_PRDTs[0].PBufAddr = paddr;
181         gATA_Buffers[1] = (void*)MM_AllocDMA(1, 32, &paddr);
182         gATA_PRDTs[1].PBufAddr = paddr;
183
184         LOG("gATA_PRDTs = {PBufAddr: 0x%x, PBufAddr: 0x%x}", gATA_PRDTs[0].PBufAddr, gATA_PRDTs[1].PBufAddr);
185
186         gaATA_PRDT_PAddrs[0] = MM_GetPhysAddr( &gATA_PRDTs[0] );
187         gaATA_PRDT_PAddrs[1] = MM_GetPhysAddr( &gATA_PRDTs[1] );
188         LOG("gaATA_PRDT_PAddrs = {0x%P, 0x%P}", gaATA_PRDT_PAddrs[0], gaATA_PRDT_PAddrs[1]);
189         #if PHYS_BITS > 32
190         // Ensure that this is within 32-bits
191         if( gaATA_PRDT_PAddrs[0] >> 32 || gaATA_PRDT_PAddrs[1] >> 32 ) {
192                 Log_Error("ATA", "Physical addresses of PRDTs are not in 32-bits (%P and %P)",
193                         gaATA_PRDT_PAddrs[0], gaATA_PRDT_PAddrs[1]);
194                 LEAVE('i', MODULE_ERR_MISC);
195                 return MODULE_ERR_MISC;
196         }
197         #endif
198         ATA_int_BusMasterWriteDWord(4, gaATA_PRDT_PAddrs[0]);
199         ATA_int_BusMasterWriteDWord(12, gaATA_PRDT_PAddrs[1]);
200
201         // Enable controllers
202         outb(IDE_PRI_BASE+1, 1);
203         outb(IDE_SEC_BASE+1, 1);
204         outb(IDE_PRI_CTRL, 0);
205         outb(IDE_SEC_CTRL, 0);
206
207         
208         // Soft reset all drives
209         outb(IDE_PRI_CTRL, 4);
210         outb(IDE_SEC_CTRL, 4);
211         IO_DELAY();
212         outb(IDE_PRI_CTRL, 0);
213         outb(IDE_SEC_CTRL, 0);
214         
215         // Make sure interrupts are ACKed
216         ATA_int_BusMasterWriteByte(2, 0x4);
217         ATA_int_BusMasterWriteByte(10, 0x4);
218
219         // return
220         LEAVE('i', MODULE_ERR_OK);
221         return MODULE_ERR_OK;
222 }
223
224 /**
225  * \brief Get the size (in sectors) of a disk
226  * \param Disk  Disk to get size of
227  * \return Number of sectors reported
228  * 
229  * Does an ATA IDENTIFY
230  */
231 Uint64 ATA_GetDiskSize(int Disk)
232 {
233         union {
234                 Uint16  buf[256];
235                 tIdentify       identify;
236         }       data;
237         Uint16  base;
238         Uint8   val;
239
240         ENTER("iDisk", Disk);
241
242         base = ATA_GetBasePort( Disk );
243
244         // Send Disk Selector
245         // - Slave / Master
246         outb(base+6, 0xA0 | (Disk & 1) << 4);
247         IO_DELAY();
248         
249         // Send ATA IDENTIFY
250         outb(base+7, HDD_IDENTIFY);
251         IO_DELAY();
252         val = inb(base+7);      // Read status
253         LOG("val = 0x%02x", val);
254         if(val == 0) {
255                 LEAVE('i', 0);
256                 return 0;       // Disk does not exist
257         }
258
259         // Poll until BSY clears or ERR is set
260         tTime   endtime = now() + 2*1000;       // 2 second timeout
261         // TODO: Timeout?
262         while( (val & 0x80) && !(val & 1) && now() < endtime )
263                 val = inb(base+7);
264         LOG("BSY unset (0x%x)", val);
265         // and, wait for DRQ to set
266         while( !(val & 0x08) && !(val & 1) && now() < endtime )
267                 val = inb(base+7);
268         LOG("DRQ set (0x%x)", val);
269
270         if(now() >= endtime) {
271                 Log_Warning("ATA", "Timeout on ATA IDENTIFY (Disk %i)", Disk);
272                 LEAVE('i', 0);
273                 return 0;
274         }
275
276         // Check for an error
277         if(val & 1) {
278                 LEAVE('i', 0);
279                 return 0;       // Error occured, so return false
280         }
281
282         // Read Data
283         for( int i = 0; i < 256; i++ )
284                 data.buf[i] = inw(base);
285
286         // Return the disk size
287         if(data.identify.Sectors48 != 0) {
288                 LEAVE('X', data.identify.Sectors48);
289                 return data.identify.Sectors48;
290         }
291         else {
292                 LEAVE('x', data.identify.Sectors28);
293                 return data.identify.Sectors28;
294         }
295 }
296
297 /**
298  * \fn Uint16 ATA_GetPortBase(int Disk)
299  * \brief Returns the base port for a given disk
300  */
301 Uint16 ATA_GetBasePort(int Disk)
302 {
303         switch(Disk)
304         {
305         case 0: case 1:         return IDE_PRI_BASE;
306         case 2: case 3:         return IDE_SEC_BASE;
307         }
308         return 0;
309 }
310
311 int ATA_DoDMA(Uint8 Disk, Uint64 Address, Uint Count, int bWrite, void *Buffer)
312 {
313          int    cont = (Disk>>1)&1;     // Controller ID
314          int    disk = Disk & 1;
315         Uint16  base;
316          int    bUseBounceBuffer = 0;
317
318         ENTER("iDisk XAddress iCount bbWrite pBuffer", Disk, Address, Count, bWrite, Buffer);
319
320         // Check if the count is small enough
321         if(Count > MAX_DMA_SECTORS) {
322                 Log_Warning("ATA", "Passed too many sectors for a bulk DMA (%i > %i)",
323                         Count, MAX_DMA_SECTORS);
324                 LEAVE('i');
325                 return 1;
326         }
327         
328         // Hack to make debug hexdump noticable
329         #if 1
330         memset(Buffer, 0xFF, Count*SECTOR_SIZE);
331         #endif
332
333         // Get exclusive access to the disk controller
334         Mutex_Acquire( &glaATA_ControllerLock[ cont ] );
335
336         // Set Size
337         gATA_PRDTs[ cont ].Bytes = Count * SECTOR_SIZE;
338         
339         // Detemine if the transfer can be done directly
340         tPAddr  buf_ps = MM_GetPhysAddr(Buffer);
341         tPAddr  buf_pe = MM_GetPhysAddr((char*)Buffer + Count * SECTOR_SIZE - 1);
342         if( buf_pe == buf_ps + Count * SECTOR_SIZE - 1 ) {
343                 // Contiguous, nice
344                 #if PHYS_BITS > 32
345                 if( buf_pe >> 32 ) {
346                         // Over 32-bits, need to copy anyway
347                         bUseBounceBuffer = 1;
348                         LOG("%P over 32-bit, using bounce buffer", buf_pe);
349                 }
350                 #endif
351         }
352         else {
353                 // TODO: Handle splitting the read into two?
354                 bUseBounceBuffer = 1;
355                 LOG("%P + 0x%x != %P, using bounce buffer", buf_ps, Count * SECTOR_SIZE, buf_pe);
356         }
357
358         // Set up destination / source buffers
359         if( bUseBounceBuffer ) {
360                 gATA_PRDTs[cont].PBufAddr = MM_GetPhysAddr(gATA_Buffers[cont]);
361                 if( bWrite )
362                         memcpy(gATA_Buffers[cont], Buffer, Count * SECTOR_SIZE);
363         }
364         else {
365                 gATA_PRDTs[cont].PBufAddr = MM_GetPhysAddr(Buffer);
366         }
367
368         // Get Port Base
369         base = ATA_GetBasePort(Disk);
370
371         // Reset IRQ Flag
372         gaATA_IRQs[cont] = 0;
373
374         // Set up transfer
375         if( Address > 0x0FFFFFFF )      // Use LBA48
376         {
377                 outb(base+0x6, 0x40 | (disk << 4));
378                 IO_DELAY();
379                 outb(base+0x2, 0 >> 8); // Upper Sector Count
380                 outb(base+0x3, Address >> 24);  // Low 2 Addr
381                 outb(base+0x4, Address >> 28);  // Mid 2 Addr
382                 outb(base+0x5, Address >> 32);  // High 2 Addr
383         }
384         else
385         {
386                 // Magic, Disk, High Address nibble
387                 outb(base+0x06, 0xE0 | (disk << 4) | ((Address >> 24) & 0x0F));
388                 //outb(base+0x06, 0xA0 | (disk << 4) | ((Address >> 24) & 0x0F));
389                 IO_DELAY();
390         }
391
392         //outb(base+0x01, 0x01);        //?
393         outb(base+0x02, Count & 0xFF);          // Sector Count
394         outb(base+0x03, Address & 0xFF);                // Low Addr
395         outb(base+0x04, (Address >> 8) & 0xFF); // Middle Addr
396         outb(base+0x05, (Address >> 16) & 0xFF);        // High Addr
397
398         LOG("Starting Transfer");
399         
400         // HACK: Ensure the PRDT is reset
401         ATA_int_BusMasterWriteDWord(cont*8+4, gaATA_PRDT_PAddrs[cont]);
402         ATA_int_BusMasterWriteByte(cont*8, 4);  // Reset IRQ
403         
404         LOG("gATA_PRDTs[%i].Bytes = %i", cont, gATA_PRDTs[cont].Bytes);
405         if( Address > 0x0FFFFFFF )
406                 outb(base+0x07, bWrite ? HDD_DMA_W48 : HDD_DMA_R48);    // Command (LBA48)
407         else
408                 outb(base+0x07, bWrite ? HDD_DMA_W28 : HDD_DMA_R28);    // Command (LBA28)
409
410         // Intialise timeout timer
411         Threads_ClearEvent(THREAD_EVENT_SHORTWAIT|THREAD_EVENT_TIMER);
412         tTimer *timeout = Time_AllocateTimer(NULL, NULL);
413         Time_ScheduleTimer(timeout, ATA_TIMEOUT);
414         gATA_WaitingThreads[cont] = Proc_GetCurThread();
415         
416         // Start transfer
417         ATA_int_BusMasterWriteByte( cont * 8, (bWrite ? 0 : 8) | 1 );   // Write(0)/Read(8) and start
418
419         // Wait for transfer to complete
420         Uint32 ev = Threads_WaitEvents(THREAD_EVENT_SHORTWAIT|THREAD_EVENT_TIMER);
421         Time_FreeTimer(timeout);
422
423         if( ev & THREAD_EVENT_TIMER ) {
424                 Log_Notice("ATA", "Timeout of %i ms exceeded", ATA_TIMEOUT);
425         }
426
427         // Complete Transfer
428         ATA_int_BusMasterWriteByte( cont * 8, (bWrite ? 0 : 8) );       // Write/Read and stop
429
430         #if DEBUG
431         {
432                 Uint8   val = inb(base+0x7);
433                 LOG("Status byte = 0x%02x, Controller Status = 0x%02x",
434                         val, ATA_int_BusMasterReadByte(cont * 8 + 2));
435         }
436         #else
437         inb(base+0x7);
438         #endif
439
440         if( gaATA_IRQs[cont] == 0 )
441         {
442                 if( ATA_int_BusMasterReadByte(cont * 8 + 2) & 0x4 ) {
443                         Log_Error("ATA", "BM Status reports an interrupt, but none recieved");
444                         ATA_int_BusMasterWriteByte(cont*8 + 2, 4);      // Clear interrupt
445                         goto _success;
446                 }
447
448                 #if 1
449                 Debug_HexDump("ATA", Buffer, 512);
450                 #endif
451                 
452                 // Release controller lock
453                 Mutex_Release( &glaATA_ControllerLock[ cont ] );
454                 Log_Warning("ATA",
455                         "Timeout on disk %i (%s sector 0x%llx)",
456                         Disk, bWrite ? "Writing" : "Reading", Address);
457                 // Return error
458                 LEAVE('i', 1);
459                 return 1;
460         }
461         
462         LOG("Transfer Completed & Acknowledged");
463 _success:
464         // Copy to destination buffer (if bounce was used and it was a read)
465         if( bUseBounceBuffer && !bWrite )
466                 memcpy( Buffer, gATA_Buffers[cont], Count*SECTOR_SIZE );
467         // Release controller lock
468         Mutex_Release( &glaATA_ControllerLock[ cont ] );
469
470         LEAVE('i', 0);
471         return 0;
472 }
473
474 /**
475  * \fn int ATA_ReadDMA(Uint8 Disk, Uint64 Address, Uint Count, void *Buffer)
476  * \return Boolean Failure
477  */
478 int ATA_ReadDMA(Uint8 Disk, Uint64 Address, Uint Count, void *Buffer)
479 {
480         return ATA_DoDMA(Disk, Address, Count, 0, Buffer);
481 }
482
483
484 /**
485  * \fn int ATA_WriteDMA(Uint8 Disk, Uint64 Address, Uint Count, void *Buffer)
486  * \brief Write up to \a MAX_DMA_SECTORS to a disk
487  * \param Disk  Disk ID to write to
488  * \param Address       LBA of first sector
489  * \param Count Number of sectors to write (must be >= \a MAX_DMA_SECTORS)
490  * \param Buffer        Source buffer for data
491  * \return Boolean Failure
492  */
493 int ATA_WriteDMA(Uint8 Disk, Uint64 Address, Uint Count, const void *Buffer)
494 {
495         return ATA_DoDMA(Disk, Address, Count, 1, (void*)Buffer);
496 }
497
498 /**
499  * \brief Primary ATA Channel IRQ handler
500  */
501 void ATA_IRQHandlerPri(int UNUSED(IRQ), void *UNUSED(Ptr))
502 {
503         Uint8   val;
504
505         // IRQ bit set for Primary Controller
506         val = ATA_int_BusMasterReadByte( 0x2 );
507         LOG("IRQ val = 0x%x", val);
508         if(val & 4)
509         {
510                 LOG("IRQ hit (val = 0x%x)", val);
511                 ATA_int_BusMasterWriteByte( 0x2, 4 );
512                 gaATA_IRQs[0] = 1;
513                 Threads_PostEvent(gATA_WaitingThreads[0], THREAD_EVENT_SHORTWAIT);
514                 return ;
515         }
516 }
517
518 /**
519  * \brief Second ATA Channel IRQ handler
520  */
521 void ATA_IRQHandlerSec(int UNUSED(IRQ), void *UNUSED(Ptr))
522 {
523         Uint8   val;
524         // IRQ bit set for Secondary Controller
525         val = ATA_int_BusMasterReadByte( 0xA );
526         LOG("IRQ val = 0x%x", val);
527         if(val & 4) {
528                 LOG("IRQ hit (val = 0x%x)", val);
529                 ATA_int_BusMasterWriteByte( 0xA, 4 );
530                 gaATA_IRQs[1] = 1;
531                 Threads_PostEvent(gATA_WaitingThreads[1], THREAD_EVENT_SHORTWAIT);
532                 return ;
533         }
534 }
535
536 /**
537  * \brief Read an 8-bit value from a Bus Master register
538  * \param Ofs   Register offset
539  */
540 Uint8 ATA_int_BusMasterReadByte(int Ofs)
541 {
542         if( gATA_BusMasterBasePtr )
543                 return *(Uint8*)(gATA_BusMasterBasePtr + Ofs);
544         else
545                 return inb( gATA_BusMasterBase + Ofs );
546 }
547
548 /**
549  * \brief Read an 32-bit value from a Bus Master register
550  * \param Ofs   Register offset
551  */
552 Uint32 ATA_int_BusMasterReadDWord(int Ofs)
553 {
554         if( gATA_BusMasterBasePtr )
555                 return *(Uint32*)(gATA_BusMasterBasePtr + Ofs);
556         else
557                 return ind( gATA_BusMasterBase + Ofs );
558 }
559
560 /**
561  * \brief Writes a byte to a Bus Master Register
562  * \param Ofs   Register Offset
563  * \param Value Value to write
564  */
565 void ATA_int_BusMasterWriteByte(int Ofs, Uint8 Value)
566 {
567         if( gATA_BusMasterBasePtr )
568                 *(Uint8*)(gATA_BusMasterBasePtr + Ofs) = Value;
569         else
570                 outb( gATA_BusMasterBase + Ofs, Value );
571 }
572
573 /**
574  * \brief Writes a 32-bit value to a Bus Master Register
575  * \param Ofs   Register offset
576  * \param Value Value to write
577  */
578 void ATA_int_BusMasterWriteDWord(int Ofs, Uint32 Value)
579 {
580         if( gATA_BusMasterBasePtr )
581                 *(Uint32*)(gATA_BusMasterBasePtr + Ofs) = Value;
582         else
583                 outd( gATA_BusMasterBase + Ofs, Value );
584 }

UCC git Repository :: git.ucc.asn.au