Renamed tpl_drv_* to api_drv_* (a more fitting name)
[tpg/acess2.git] / Modules / Network / RTL8139 / rtl8139.c
1 /*
2  * Acess2 RTL8139 Driver
3  * - By John Hodge (thePowersGang)
4  */
5 #define DEBUG   0
6 #define VERSION ((0<<8)|20)
7 #include <acess.h>
8 #include <modules.h>
9 #include <fs_devfs.h>
10 #include <drv_pci.h>
11 #include <api_drv_network.h>
12 #include <semaphore.h>
13
14 // === CONSTANTS ===
15 #define VENDOR_ID       0x10EC
16 #define DEVICE_ID       0x8139
17
18 enum eRTL8139_Regs
19 {
20         // MAC Address
21         MAC0, MAC1, MAC2,
22         MAC3, MAC4, MAC5,
23         
24         // Multicast Registers
25         MAR0 = 0x08, MAR1, MAR2, MAR3,
26         MAR4, MAR5, MAR6, MAR7,
27         
28         // Transmit status of descriptors 0 - 3
29         TSD0 = 0x10,    TSD1 = 0x14,
30         TSD2 = 0x18,    TSD3 = 0x1C,
31         // Transmit start addresses
32         TSAD0 = 0x20,   TSAD1 = 0x24,
33         TSAD2 = 0x28,   TSAD3 = 0x2C,
34         
35         RBSTART = 0x30, //!< Recieve Buffer Start (DWord)
36         // Early Recieve Byte Count
37         ERBCR = 0x34,   // 16-bits
38         // Early RX Status Register
39         ERSR = 0x36,
40         
41         // ??, ??, ??, RST, RE, TE, ??, ??
42         CMD     = 0x37,
43         
44         CAPR    = 0x38, // Current address of packet read
45         CBA     = 0x3A, // Current Buffer Address - Total byte count in RX buffer
46         
47         IMR     = 0x3C, // Interrupt mask register
48         ISR     = 0x3E, // Interrupt status register
49         
50         TCR     = 0x40, // Transmit Configuration Register
51         RCR     = 0x44, // Recieve Configuration Register
52         TCTR    = 0x48, // 32-bit timer (count)
53         MPC     = 0x4C, // Missed packet count (due to RX overflow)
54         
55         CR_9346 = 0x50,
56         CONFIG0 = 0x51,
57         CONFIG1 = 0x52,
58         // 0x53 resvd
59         TIMERINT = 0x54,        // Fires a timeout when TCTR equals this value
60         
61 };
62
63 #define FLAG_ISR_TOK    0x04
64 #define FLAG_ISR_ROK    0x01
65
66 // === TYPES ===
67 typedef struct sCard
68 {
69         Uint16  IOBase;
70         Uint8   IRQ;
71         
72          int    NumWaitingPackets;
73         
74         char    *ReceiveBuffer;
75         tPAddr  PhysReceiveBuffer;
76          int    ReceiveBufferLength;
77          int    SeenOfs;        //!< End of the most recently seen packet (by IRQ)
78         tMutex  ReadMutex;
79         tSemaphore      ReadSemaphore;
80         
81         char    *TransmitBuffers[4];
82         tPAddr  PhysTransmitBuffers[4];
83         tMutex  TransmitInUse[4];
84         tMutex  CurTXProtector; //!< Protects \a .CurTXDescriptor
85          int    CurTXDescriptor;
86         
87         char    Name[2];
88         tVFS_Node       Node;
89         Uint8   MacAddr[6];
90 }       tCard;
91
92 // === PROTOTYPES ===
93  int    RTL8139_Install(char **Options);
94 char    *RTL8139_ReadDir(tVFS_Node *Node, int Pos);
95 tVFS_Node       *RTL8139_FindDir(tVFS_Node *Node, const char *Filename);
96  int    RTL8139_RootIOCtl(tVFS_Node *Node, int ID, void *Arg);
97 Uint64  RTL8139_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
98 Uint64  RTL8139_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
99  int    RTL8139_IOCtl(tVFS_Node *Node, int ID, void *Arg);
100 void    RTL8139_IRQHandler(int Num);
101
102 // === GLOBALS ===
103 MODULE_DEFINE(0, VERSION, RTL8139, RTL8139_Install, NULL, NULL);
104 tDevFS_Driver   gRTL8139_DriverInfo = {
105         NULL, "RTL8139",
106         {
107         .NumACLs = 1,
108         .ACLs = &gVFS_ACL_EveryoneRX,
109         .Flags = VFS_FFLAG_DIRECTORY,
110         .ReadDir = RTL8139_ReadDir,
111         .FindDir = RTL8139_FindDir,
112         .IOCtl = RTL8139_RootIOCtl
113         }
114 };
115  int    giRTL8139_CardCount;
116 tCard   *gaRTL8139_Cards;
117
118 // === CODE ===
119 /**
120  * \brief Installs the RTL8139 Driver
121  */
122 int RTL8139_Install(char **Options)
123 {
124          int    id = -1;
125          int    i = 0;
126         Uint16  base;
127         tCard   *card;
128         
129         giRTL8139_CardCount = PCI_CountDevices(VENDOR_ID, DEVICE_ID);
130         Log_Debug("RTL8139", "%i cards", giRTL8139_CardCount);
131         
132         if( giRTL8139_CardCount == 0 )  return MODULE_ERR_NOTNEEDED;
133         
134         gaRTL8139_Cards = calloc( giRTL8139_CardCount, sizeof(tCard) );
135         
136         //while( (id = PCI_GetDevice(0x10EC, 0x8139, 0, id)) != -1 )
137         while( (id = PCI_GetDevice(VENDOR_ID, DEVICE_ID, i)) != -1 )
138         {
139                 card = &gaRTL8139_Cards[i];
140                 base = PCI_GetBAR( id, 0 );
141                 if( !(base & 1) ) {
142                         Log_Warning("RTL8139", "Driver does not support MMIO, skipping card");
143                         card->IOBase = 0;
144                         card->IRQ = 0;
145                         continue ;
146                 }
147                 base &= ~1;
148                 card->IOBase = base;
149                 card->IRQ = PCI_GetIRQ( id );
150                 
151                 // Install IRQ Handler
152                 IRQ_AddHandler(card->IRQ, RTL8139_IRQHandler);
153                 
154                 // Power on
155                 outb( base + CONFIG1, 0x00 );
156
157                 // Reset (0x10 to CMD)
158                 outb( base + CMD, 0x10 );       
159                 while( inb(base + CMD) & 0x10 ) ;
160                 
161                 // Set up recieve buffer
162                 // - Allocate 3 pages below 4GiB for the recieve buffer (Allows 8k+16+1500)
163                 card->ReceiveBuffer = (void*)MM_AllocDMA( 3, 32, &card->PhysReceiveBuffer );
164                 card->ReceiveBufferLength = 8*1024;
165                 outd(base + RBSTART, (Uint32)card->PhysReceiveBuffer);
166                 outd(base + CBA, 0);
167                 outd(base + CAPR, 0);
168                 // Set IMR to Transmit OK and Receive OK
169                 outw(base + IMR, 0x5);
170                 
171                 // Set up transmit buffers
172                 // - 2 non-contiguous pages (each page can fit 2 1500 byte packets)
173                 card->TransmitBuffers[0] = (void*)MM_AllocDMA( 1, 32, &card->PhysTransmitBuffers[0] );
174                 card->TransmitBuffers[1] = card->TransmitBuffers[0] + 0x800;
175                 card->PhysTransmitBuffers[1] = card->PhysTransmitBuffers[0] + 0x800;
176                 
177                 card->TransmitBuffers[2] = (void*)MM_AllocDMA( 1, 32, &card->PhysTransmitBuffers[2] );
178                 card->TransmitBuffers[3] = card->TransmitBuffers[2] + 0x800;
179                 card->PhysTransmitBuffers[3] = card->PhysTransmitBuffers[2] + 0x800;
180                 
181                 outd(base + TSAD0, card->PhysTransmitBuffers[0]);
182                 outd(base + TSAD1, card->PhysTransmitBuffers[1]);
183                 outd(base + TSAD2, card->PhysTransmitBuffers[2]);
184                 outd(base + TSAD3, card->PhysTransmitBuffers[3]);
185                 
186                 // Set recieve buffer size and recieve mask
187                 // - Bit 7 being set tells the card to overflow the recieve buffer if needed
188                 //   (i.e. when the packet starts at the end of the bufffer, it overflows up
189                 //    to 1500 bytes)
190                 outd(base + RCR, 0x8F);
191         
192                 // Recive Enable and Transmit Enable    
193                 outb(base + CMD, 0x0C);
194                 
195                 // Get the card's MAC address
196                 card->MacAddr[0] = inb(base+MAC0);
197                 card->MacAddr[1] = inb(base+MAC1);
198                 card->MacAddr[2] = inb(base+MAC2);
199                 card->MacAddr[3] = inb(base+MAC3);
200                 card->MacAddr[4] = inb(base+MAC4);
201                 card->MacAddr[5] = inb(base+MAC5);
202                 
203                 // Set VFS Node
204                 card->Name[0] = '0'+i;
205                 card->Name[1] = '\0';
206                 card->Node.ImplPtr = card;
207                 card->Node.NumACLs = 0;
208                 card->Node.CTime = now();
209                 card->Node.Write = RTL8139_Write;
210                 card->Node.Read = RTL8139_Read;
211                 card->Node.IOCtl = RTL8139_IOCtl;
212                 
213                 Log_Log("RTL8139", "Card %i 0x%04x, IRQ %i %02x:%02x:%02x:%02x:%02x:%02x",
214                         i, card->IOBase, card->IRQ,
215                         card->MacAddr[0], card->MacAddr[1], card->MacAddr[2],
216                         card->MacAddr[3], card->MacAddr[4], card->MacAddr[5]
217                         );
218                 
219                 i ++;
220         }
221         
222         gRTL8139_DriverInfo.RootNode.Size = giRTL8139_CardCount;
223         DevFS_AddDevice( &gRTL8139_DriverInfo );
224         
225         return MODULE_ERR_OK;
226 }
227
228 // --- Root Functions ---
229 char *RTL8139_ReadDir(tVFS_Node *Node, int Pos)
230 {
231         if( Pos < 0 || Pos >= giRTL8139_CardCount )     return NULL;
232         
233         return strdup( gaRTL8139_Cards[Pos].Name );
234 }
235
236 tVFS_Node *RTL8139_FindDir(tVFS_Node *Node, const char *Filename)
237 {
238         //TODO: It might be an idea to supprt >10 cards
239         if(Filename[0] == '\0' || Filename[1] != '\0')  return NULL;
240         if(Filename[0] < '0' || Filename[0] > '9')      return NULL;
241         return &gaRTL8139_Cards[ Filename[0]-'0' ].Node;
242 }
243
244 const char *csaRTL8139_RootIOCtls[] = {DRV_IOCTLNAMES, NULL};
245 int RTL8139_RootIOCtl(tVFS_Node *Node, int ID, void *Data)
246 {
247         ENTER("pNode iID pData", Node, ID, Data);
248         switch(ID)
249         {
250         BASE_IOCTLS(DRV_TYPE_NETWORK, "RTL8139", VERSION, csaRTL8139_RootIOCtls);
251         }
252         LEAVE('i', 0);
253         return 0;
254 }
255
256 // --- File Functions ---
257 Uint64 RTL8139_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
258 {
259         tCard   *card = Node->ImplPtr;
260         Uint16  read_ofs, pkt_length;
261          int    new_read_ofs;
262
263         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
264
265 retry:
266         if( Semaphore_Wait( &card->ReadSemaphore, 1 ) != 1 )
267         {
268                 LEAVE_RET('i', 0);
269         }
270         
271         Mutex_Acquire( &card->ReadMutex );
272         
273         read_ofs = inw( card->IOBase + CAPR );
274         LOG("raw read_ofs = %i", read_ofs);
275         read_ofs = (read_ofs + 0x10) & 0xFFFF;
276         LOG("read_ofs = %i", read_ofs);
277         
278         pkt_length = *(Uint16*)&card->ReceiveBuffer[read_ofs+2];
279         
280         // Calculate new read offset
281         new_read_ofs = read_ofs + pkt_length + 4;
282         new_read_ofs = (new_read_ofs + 3) & ~3; // Align
283         if(new_read_ofs > card->ReceiveBufferLength) {
284                 LOG("wrapping read_ofs");
285                 new_read_ofs -= card->ReceiveBufferLength;
286         }
287         new_read_ofs -= 0x10;   // I dunno
288         LOG("new_read_ofs = %i", new_read_ofs);
289         
290         // Check for errors
291         if( *(Uint16*)&card->ReceiveBuffer[read_ofs] & 0x1E ) {
292                 // Update CAPR
293                 outw(card->IOBase + CAPR, new_read_ofs);
294                 Mutex_Release( &card->ReadMutex );
295                 goto retry;     // I feel evil
296         }
297         
298         // Get packet
299         if( Length > pkt_length )       Length = pkt_length;
300         memcpy(Buffer, &card->ReceiveBuffer[read_ofs+4], Length);
301         
302         // Update CAPR
303         outw(card->IOBase + CAPR, new_read_ofs);
304         
305         Mutex_Release( &card->ReadMutex );
306         
307         LEAVE('i', Length);
308         
309         return Length;
310 }
311
312 Uint64 RTL8139_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
313 {
314          int    td;
315         Uint32  status;
316         tCard   *card = Node->ImplPtr;
317         
318         if( Length > 1500 )     return 0;       // MTU exceeded
319         
320         ENTER("pNode XLength pBuffer", Node, Length, Buffer);
321         
322         // TODO: Implement a semaphore for avaliable transmit buffers
323
324         // Find an avaliable descriptor
325         Mutex_Acquire(&card->CurTXProtector);
326         td = card->CurTXDescriptor;
327         card->CurTXDescriptor ++;
328         card->CurTXDescriptor %= 4;
329         Mutex_Release(&card->CurTXProtector);
330         // - Lock it
331         Mutex_Acquire( &card->TransmitInUse[td] );
332         
333         LOG("td = %i", td);
334         
335         // Transmit using descriptor `td`
336         LOG("card->PhysTransmitBuffers[td] = %P", card->PhysTransmitBuffers[td]);
337         outd(card->IOBase + TSAD0 + td*4, card->PhysTransmitBuffers[td]);
338         LOG("card->TransmitBuffers[td] = %p", card->TransmitBuffers[td]);
339         // Copy to buffer
340         memcpy(card->TransmitBuffers[td], Buffer, Length);
341         // Start
342         status = 0;
343         status |= Length & 0x1FFF;      // 0-12: Length
344         status |= 0 << 13;      // 13: OWN bit
345         status |= (0 & 0x3F) << 16;     // 16-21: Early TX threshold (zero atm, TODO: check)
346         LOG("status = 0x%08x", status);
347         outd(card->IOBase + TSD0 + td*4, status);
348         
349         LEAVE('i', (int)Length);
350         
351         return Length;
352 }
353
354 const char *csaRTL8139_NodeIOCtls[] = {DRV_IOCTLNAMES, NULL};
355 int RTL8139_IOCtl(tVFS_Node *Node, int ID, void *Data)
356 {
357         tCard   *card = Node->ImplPtr;
358         ENTER("pNode iID pData", Node, ID, Data);
359         switch(ID)
360         {
361         BASE_IOCTLS(DRV_TYPE_NETWORK, "RTL8139", VERSION, csaRTL8139_NodeIOCtls);
362         case NET_IOCTL_GETMAC:
363                 if( !CheckMem(Data, 6) ) {
364                         LEAVE('i', -1);
365                         return -1;
366                 }
367                 memcpy( Data, card->MacAddr, 6 );
368                 LEAVE('i', 1);
369                 return 1;
370         }
371         LEAVE('i', 0);
372         return 0;
373 }
374
375 void RTL8139_IRQHandler(int Num)
376 {
377          int    i, j;
378         tCard   *card;
379         Uint16  status;
380
381         LOG("Num = %i", Num);
382         
383         for( i = 0; i < giRTL8139_CardCount; i ++ )
384         {
385                 card = &gaRTL8139_Cards[i];
386                 if( Num != card->IRQ )  break;
387                 
388                 status = inw(card->IOBase + ISR);
389                 LOG("status = 0x%02x", status);
390                 
391                 // Transmit OK, a transmit descriptor is now free
392                 if( status & FLAG_ISR_TOK )
393                 {
394                         for( j = 0; j < 4; j ++ )
395                         {
396                                 if( ind(card->IOBase + TSD0 + j*4) & 0x8000 ) { // TSD TOK
397                                         Mutex_Release( &card->TransmitInUse[j] );
398                                         // TODO: Update semaphore once implemented
399                                 }
400                         }
401                         outw(card->IOBase + ISR, FLAG_ISR_TOK);
402                 }
403                 
404                 // Recieve OK, inform read
405                 if( status & FLAG_ISR_ROK )
406                 {
407                          int    read_ofs, end_ofs;
408                          int    packet_count = 0;
409                          int    len;
410                         
411                         // Scan recieve buffer for packets
412                         end_ofs = inw(card->IOBase + CBA);
413                         read_ofs = card->SeenOfs;
414                         LOG("read_ofs = %i, end_ofs = %i", read_ofs, end_ofs);
415                         if( read_ofs > end_ofs )
416                         {
417                                 while( read_ofs < card->ReceiveBufferLength )
418                                 {
419                                         packet_count ++;
420                                         len = *(Uint16*)&card->ReceiveBuffer[read_ofs+2];
421                                         LOG("%i 0x%x Pkt Hdr: 0x%04x, len: 0x%04x",
422                                                 packet_count, read_ofs,
423                                                 *(Uint16*)&card->ReceiveBuffer[read_ofs],
424                                                 len
425                                                 );
426                                         if(len > 2000) {
427                                                 Log_Warning("RTL8139", "IRQ: Packet in buffer exceeds sanity (%i>2000)", len);
428                                         }
429                                         read_ofs += len + 4;
430                                         read_ofs = (read_ofs + 3) & ~3; // Align
431                                 }
432                                 read_ofs -= card->ReceiveBufferLength;
433                                 LOG("wrapped read_ofs");
434                         }
435                         while( read_ofs < end_ofs )
436                         {
437                                 packet_count ++;
438                                 LOG("%i 0x%x Pkt Hdr: 0x%04x, len: 0x%04x",
439                                         packet_count, read_ofs,
440                                         *(Uint16*)&card->ReceiveBuffer[read_ofs],
441                                         *(Uint16*)&card->ReceiveBuffer[read_ofs+2]
442                                         );
443                                 read_ofs += *(Uint16*)&card->ReceiveBuffer[read_ofs+2] + 4;
444                                 read_ofs = (read_ofs + 3) & ~3; // Align
445                         }
446                         if( read_ofs != end_ofs ) {
447                                 Log_Warning("RTL8139", "IRQ: read_ofs (%i) != end_ofs(%i)", read_ofs, end_ofs);
448                                 read_ofs = end_ofs;
449                         }
450                         card->SeenOfs = read_ofs;
451                         
452                         LOG("packet_count = %i, read_ofs = 0x%x", packet_count, read_ofs);
453                         
454                         if( packet_count )
455                         {
456                                 if( Semaphore_Signal( &card->ReadSemaphore, packet_count ) != packet_count ) {
457                                         // Oops?
458                                 }
459                                 VFS_MarkAvaliable( &card->Node, 1 );
460                         }
461                         
462                         outw(card->IOBase + ISR, FLAG_ISR_ROK);
463                 }
464         }
465 }

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