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

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