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

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