b1b96e6fef408da29058f00896dcdf79fd8e1b31
[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         // Map memory
137         if( gATA_BusMasterBase & 1 )
138         {
139                 gATA_BusMasterBase &= ~1;
140                 LOG("gATA_BusMasterBase = IO 0x%x", gATA_BusMasterBase);
141         }
142         else
143         {
144                 // MMIO
145                 gATA_BusMasterBasePtr = MM_MapHWPages( gATA_BusMasterBase, 1 ) + (gATA_BusMasterBase&0xFFF);
146                 LOG("gATA_BusMasterBasePtr = %p", gATA_BusMasterBasePtr);
147         }
148
149         // Register IRQs and get Buffers
150         IRQ_AddHandler( gATA_IRQPri, ATA_IRQHandlerPri, NULL );
151         IRQ_AddHandler( gATA_IRQSec, ATA_IRQHandlerSec, NULL );
152
153         tPAddr  paddr;
154         gATA_Buffers[0] = (void*)MM_AllocDMA(1, 32, &paddr);
155         gATA_PRDTs[0].PBufAddr = paddr;
156         gATA_Buffers[1] = (void*)MM_AllocDMA(1, 32, &paddr);
157         gATA_PRDTs[1].PBufAddr = paddr;
158
159         LOG("gATA_PRDTs = {PBufAddr: 0x%x, PBufAddr: 0x%x}", gATA_PRDTs[0].PBufAddr, gATA_PRDTs[1].PBufAddr);
160
161         // TODO: Ensure that this is within 32-bits
162         gaATA_PRDT_PAddrs[0] = MM_GetPhysAddr( &gATA_PRDTs[0] );
163         gaATA_PRDT_PAddrs[1] = MM_GetPhysAddr( &gATA_PRDTs[1] );
164         LOG("gaATA_PRDT_PAddrs = {0x%P, 0x%P}", gaATA_PRDT_PAddrs[0], gaATA_PRDT_PAddrs[1]);
165         #if PHYS_BITS > 32
166         if( gaATA_PRDT_PAddrs[0] >> 32 || gaATA_PRDT_PAddrs[1] >> 32 ) {
167                 Log_Error("ATA", "Physical addresses of PRDTs are not in 32-bits (%P and %P)",
168                         gaATA_PRDT_PAddrs[0], gaATA_PRDT_PAddrs[1]);
169                 LEAVE('i', MODULE_ERR_MISC);
170                 return MODULE_ERR_MISC;
171         }
172         #endif
173         ATA_int_BusMasterWriteDWord(4, gaATA_PRDT_PAddrs[0]);
174         ATA_int_BusMasterWriteDWord(12, gaATA_PRDT_PAddrs[1]);
175
176         // Enable controllers
177         outb(IDE_PRI_BASE+1, 1);
178         outb(IDE_SEC_BASE+1, 1);
179         outb(IDE_PRI_CTRL, 0);
180         outb(IDE_SEC_CTRL, 0);
181         
182         // Make sure interrupts are ACKed
183         ATA_int_BusMasterWriteByte(2, 0x4);
184         ATA_int_BusMasterWriteByte(10, 0x4);
185
186         // return
187         LEAVE('i', MODULE_ERR_OK);
188         return MODULE_ERR_OK;
189 }
190
191 /**
192  * \brief Get the size (in sectors) of a disk
193  * \param Disk  Disk to get size of
194  * \return Number of sectors reported
195  * 
196  * Does an ATA IDENTIFY
197  */
198 Uint64 ATA_GetDiskSize(int Disk)
199 {
200         union {
201                 Uint16  buf[256];
202                 tIdentify       identify;
203         }       data;
204         Uint16  base;
205         Uint8   val;
206          int    i;
207         ENTER("iDisk", Disk);
208
209         base = ATA_GetBasePort( Disk );
210
211         // Send Disk Selector
212         if(Disk & 1)    // Slave
213                 outb(base+6, 0xB0);
214         else    // Master
215                 outb(base+6, 0xA0);
216         IO_DELAY();
217         
218         // Check for a floating bus
219         if( 0xFF == inb(base+7) ) {
220                 LOG("Floating bus");
221                 LEAVE('i', 0);
222                 return 0;
223         }
224         
225         // Check for the controller
226         // - Write to two RW ports and attempt to read back
227         outb(base+0x02, 0x66);
228         outb(base+0x03, 0xFF);
229         if(inb(base+0x02) != 0x66 || inb(base+0x03) != 0xFF) {
230                 LOG("No controller");
231                 LEAVE('i', 0);
232                 return 0;
233         }
234
235         // Send ATA IDENTIFY
236         outb(base+7, HDD_IDENTIFY);
237         IO_DELAY();
238         val = inb(base+7);      // Read status
239         LOG("val = 0x%02x", val);
240         if(val == 0) {
241                 LEAVE('i', 0);
242                 return 0;       // Disk does not exist
243         }
244
245         // Poll until BSY clears or ERR is set
246         // TODO: Timeout?
247         while( (val & 0x80) && !(val & 1) )
248                 val = inb(base+7);
249         LOG("BSY unset (0x%x)", val);
250         // and, wait for DRQ to set
251         while( !(val & 0x08) && !(val & 1))
252                 val = inb(base+7);
253         LOG("DRQ set (0x%x)", val);
254
255         // Check for an error
256         if(val & 1) {
257                 LEAVE('i', 0);
258                 return 0;       // Error occured, so return false
259         }
260
261         // Read Data
262         for( i = 0; i < 256; i++ )
263                 data.buf[i] = inw(base);
264
265         // Return the disk size
266         if(data.identify.Sectors48 != 0) {
267                 LEAVE('X', data.identify.Sectors48);
268                 return data.identify.Sectors48;
269         }
270         else {
271                 LEAVE('x', data.identify.Sectors28);
272                 return data.identify.Sectors28;
273         }
274 }
275
276 /**
277  * \fn Uint16 ATA_GetPortBase(int Disk)
278  * \brief Returns the base port for a given disk
279  */
280 Uint16 ATA_GetBasePort(int Disk)
281 {
282         switch(Disk)
283         {
284         case 0: case 1:         return IDE_PRI_BASE;
285         case 2: case 3:         return IDE_SEC_BASE;
286         }
287         return 0;
288 }
289
290 int ATA_DoDMA(Uint8 Disk, Uint64 Address, Uint Count, int bWrite, void *Buffer)
291 {
292          int    cont = (Disk>>1)&1;     // Controller ID
293          int    disk = Disk & 1;
294         Uint16  base;
295          int    bUseBounceBuffer;
296
297         ENTER("iDisk XAddress iCount bbWrite pBuffer", Disk, Address, Count, bWrite, Buffer);
298
299         // Check if the count is small enough
300         if(Count > MAX_DMA_SECTORS) {
301                 Log_Warning("ATA", "Passed too many sectors for a bulk DMA (%i > %i)",
302                         Count, MAX_DMA_SECTORS);
303                 LEAVE('i');
304                 return 1;
305         }
306         
307         // Hack to make debug hexdump noticable
308         #if 1
309         memset(Buffer, 0xFF, Count*SECTOR_SIZE);
310         #endif
311
312         // Get exclusive access to the disk controller
313         Mutex_Acquire( &glaATA_ControllerLock[ cont ] );
314
315         // Set Size
316         gATA_PRDTs[ cont ].Bytes = Count * SECTOR_SIZE;
317         
318         // Detemine if the transfer can be done directly
319         tPAddr  buf_ps = MM_GetPhysAddr(Buffer);
320         tPAddr  buf_pe = MM_GetPhysAddr((char*)Buffer + Count * SECTOR_SIZE - 1);
321         if( buf_pe == buf_ps + Count * SECTOR_SIZE - 1 ) {
322                 // Contiguous, nice
323                 #if PHYS_BITS > 32
324                 if( buf_pe >> 32 ) {
325                         // Over 32-bits, need to copy anyway
326                         bUseBounceBuffer = 1;
327                         LOG("%P over 32-bit, using bounce buffer", buf_pe);
328                 }
329                 #endif
330         }
331         else {
332                 // TODO: Handle splitting the read into two?
333                 bUseBounceBuffer = 1;
334                 LOG("%P + 0x%x != %P, using bounce buffer", buf_ps, Count * SECTOR_SIZE, buf_pe);
335         }
336
337         // Set up destination / source buffers
338         if( bUseBounceBuffer ) {
339                 gATA_PRDTs[cont].PBufAddr = MM_GetPhysAddr(gATA_Buffers[cont]);
340                 if( bWrite )
341                         memcpy(gATA_Buffers[cont], Buffer, Count * SECTOR_SIZE);
342         }
343         else {
344                 gATA_PRDTs[cont].PBufAddr = MM_GetPhysAddr(Buffer);
345         }
346
347         // Get Port Base
348         base = ATA_GetBasePort(Disk);
349
350         // Reset IRQ Flag
351         gaATA_IRQs[cont] = 0;
352
353         
354         // TODO: What the ____ does this do?
355         #if 1
356         if( cont == 0 ) {
357                 outb(IDE_PRI_CTRL, 4);
358                 IO_DELAY();
359                 outb(IDE_PRI_CTRL, 0);
360         }
361         else {
362                 outb(IDE_SEC_CTRL, 4);
363                 IO_DELAY();
364                 outb(IDE_SEC_CTRL, 0);
365         }
366         #endif
367
368         // Set up transfer
369         if( Address > 0x0FFFFFFF )      // Use LBA48
370         {
371                 outb(base+0x6, 0x40 | (disk << 4));
372                 IO_DELAY();
373                 outb(base+0x2, 0 >> 8); // Upper Sector Count
374                 outb(base+0x3, Address >> 24);  // Low 2 Addr
375                 outb(base+0x4, Address >> 28);  // Mid 2 Addr
376                 outb(base+0x5, Address >> 32);  // High 2 Addr
377         }
378         else
379         {
380                 // Magic, Disk, High Address nibble
381                 outb(base+0x06, 0xE0 | (disk << 4) | ((Address >> 24) & 0x0F));
382                 //outb(base+0x06, 0xA0 | (disk << 4) | ((Address >> 24) & 0x0F));
383                 IO_DELAY();
384         }
385
386         //outb(base+0x01, 0x01);        //?
387         outb(base+0x02, Count & 0xFF);          // Sector Count
388         outb(base+0x03, Address & 0xFF);                // Low Addr
389         outb(base+0x04, (Address >> 8) & 0xFF); // Middle Addr
390         outb(base+0x05, (Address >> 16) & 0xFF);        // High Addr
391
392         LOG("Starting Transfer");
393         
394         // HACK: Ensure the PRDT is reset
395         ATA_int_BusMasterWriteDWord(cont*8+4, gaATA_PRDT_PAddrs[cont]);
396         ATA_int_BusMasterWriteByte(cont*8, 4);  // Reset IRQ
397         
398         LOG("gATA_PRDTs[%i].Bytes = %i", cont, gATA_PRDTs[cont].Bytes);
399         if( Address > 0x0FFFFFFF )
400                 outb(base+0x07, bWrite ? HDD_DMA_W48 : HDD_DMA_R48);    // Command (LBA48)
401         else
402                 outb(base+0x07, bWrite ? HDD_DMA_W28 : HDD_DMA_R28);    // Command (LBA28)
403
404         // Intialise timeout timer
405         Threads_ClearEvent(THREAD_EVENT_SHORTWAIT|THREAD_EVENT_TIMER);
406         tTimer *timeout = Time_AllocateTimer(NULL, NULL);
407         Time_ScheduleTimer(timeout, ATA_TIMEOUT);
408         gATA_WaitingThreads[cont] = Proc_GetCurThread();
409         
410         // Start transfer
411         ATA_int_BusMasterWriteByte( cont * 8, (bWrite ? 0 : 8) | 1 );   // Write(0)/Read(8) and start
412
413         // Wait for transfer to complete
414         Uint32 ev = Threads_WaitEvents(THREAD_EVENT_SHORTWAIT|THREAD_EVENT_TIMER);
415         Time_FreeTimer(timeout);
416
417         if( ev & THREAD_EVENT_TIMER ) {
418                 Log_Notice("ATA", "Timeout of %i ms exceeded", ATA_TIMEOUT);
419         }
420
421         // Complete Transfer
422         ATA_int_BusMasterWriteByte( cont * 8, (bWrite ? 0 : 8) );       // Write/Read and stop
423
424         #if DEBUG
425         {
426                 Uint8   val = inb(base+0x7);
427                 LOG("Status byte = 0x%02x, Controller Status = 0x%02x",
428                         val, ATA_int_BusMasterReadByte(cont * 8 + 2));
429         }
430         #else
431         inb(base+0x7);
432         #endif
433
434         if( gaATA_IRQs[cont] == 0 )
435         {
436                 if( ATA_int_BusMasterReadByte(cont * 8 + 2) & 0x4 ) {
437                         Log_Error("ATA", "BM Status reports an interrupt, but none recieved");
438                         ATA_int_BusMasterWriteByte(cont*8 + 2, 4);      // Clear interrupt
439                         goto _success;
440                 }
441
442                 #if 1
443                 Debug_HexDump("ATA", Buffer, 512);
444                 #endif
445                 
446                 // Release controller lock
447                 Mutex_Release( &glaATA_ControllerLock[ cont ] );
448                 Log_Warning("ATA",
449                         "Timeout on disk %i (%s sector 0x%llx)",
450                         Disk, bWrite ? "Writing" : "Reading", Address);
451                 // Return error
452                 LEAVE('i', 1);
453                 return 1;
454         }
455         
456         LOG("Transfer Completed & Acknowledged");
457 _success:
458         // Copy to destination buffer (if bounce was used and it was a read)
459         if( bUseBounceBuffer && !bWrite )
460                 memcpy( Buffer, gATA_Buffers[cont], Count*SECTOR_SIZE );
461         // Release controller lock
462         Mutex_Release( &glaATA_ControllerLock[ cont ] );
463
464         LEAVE('i', 0);
465         return 0;
466 }
467
468 /**
469  * \fn int ATA_ReadDMA(Uint8 Disk, Uint64 Address, Uint Count, void *Buffer)
470  * \return Boolean Failure
471  */
472 int ATA_ReadDMA(Uint8 Disk, Uint64 Address, Uint Count, void *Buffer)
473 {
474         return ATA_DoDMA(Disk, Address, Count, 0, Buffer);
475 }
476
477
478 /**
479  * \fn int ATA_WriteDMA(Uint8 Disk, Uint64 Address, Uint Count, void *Buffer)
480  * \brief Write up to \a MAX_DMA_SECTORS to a disk
481  * \param Disk  Disk ID to write to
482  * \param Address       LBA of first sector
483  * \param Count Number of sectors to write (must be >= \a MAX_DMA_SECTORS)
484  * \param Buffer        Source buffer for data
485  * \return Boolean Failure
486  */
487 int ATA_WriteDMA(Uint8 Disk, Uint64 Address, Uint Count, const void *Buffer)
488 {
489         return ATA_DoDMA(Disk, Address, Count, 1, (void*)Buffer);
490 }
491
492 /**
493  * \brief Primary ATA Channel IRQ handler
494  */
495 void ATA_IRQHandlerPri(int UNUSED(IRQ), void *UNUSED(Ptr))
496 {
497         Uint8   val;
498
499         // IRQ bit set for Primary Controller
500         val = ATA_int_BusMasterReadByte( 0x2 );
501         LOG("IRQ val = 0x%x", val);
502         if(val & 4)
503         {
504                 LOG("IRQ hit (val = 0x%x)", val);
505                 ATA_int_BusMasterWriteByte( 0x2, 4 );
506                 gaATA_IRQs[0] = 1;
507                 Threads_PostEvent(gATA_WaitingThreads[0], THREAD_EVENT_SHORTWAIT);
508                 return ;
509         }
510 }
511
512 /**
513  * \brief Second ATA Channel IRQ handler
514  */
515 void ATA_IRQHandlerSec(int UNUSED(IRQ), void *UNUSED(Ptr))
516 {
517         Uint8   val;
518         // IRQ bit set for Secondary Controller
519         val = ATA_int_BusMasterReadByte( 0xA );
520         LOG("IRQ val = 0x%x", val);
521         if(val & 4) {
522                 LOG("IRQ hit (val = 0x%x)", val);
523                 ATA_int_BusMasterWriteByte( 0xA, 4 );
524                 gaATA_IRQs[1] = 1;
525                 Threads_PostEvent(gATA_WaitingThreads[1], THREAD_EVENT_SHORTWAIT);
526                 return ;
527         }
528 }
529
530 /**
531  * \brief Read an 8-bit value from a Bus Master register
532  * \param Ofs   Register offset
533  */
534 Uint8 ATA_int_BusMasterReadByte(int Ofs)
535 {
536         if( gATA_BusMasterBasePtr )
537                 return *(Uint8*)(gATA_BusMasterBasePtr + Ofs);
538         else
539                 return inb( gATA_BusMasterBase + Ofs );
540 }
541
542 /**
543  * \brief Read an 32-bit value from a Bus Master register
544  * \param Ofs   Register offset
545  */
546 Uint32 ATA_int_BusMasterReadDWord(int Ofs)
547 {
548         if( gATA_BusMasterBasePtr )
549                 return *(Uint32*)(gATA_BusMasterBasePtr + Ofs);
550         else
551                 return ind( gATA_BusMasterBase + Ofs );
552 }
553
554 /**
555  * \brief Writes a byte to a Bus Master Register
556  * \param Ofs   Register Offset
557  * \param Value Value to write
558  */
559 void ATA_int_BusMasterWriteByte(int Ofs, Uint8 Value)
560 {
561         if( gATA_BusMasterBasePtr )
562                 *(Uint8*)(gATA_BusMasterBasePtr + Ofs) = Value;
563         else
564                 outb( gATA_BusMasterBase + Ofs, Value );
565 }
566
567 /**
568  * \brief Writes a 32-bit value to a Bus Master Register
569  * \param Ofs   Register offset
570  * \param Value Value to write
571  */
572 void ATA_int_BusMasterWriteDWord(int Ofs, Uint32 Value)
573 {
574         if( gATA_BusMasterBasePtr )
575                 *(Uint32*)(gATA_BusMasterBasePtr + Ofs) = Value;
576         else
577                 outd( gATA_BusMasterBase + Ofs, Value );
578 }

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