Modules/USB - Slight commenting updates in HID
[tpg/acess2.git] / KernelLand / 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, const void *Buffer);
99  int    RTL8139_IOCtl(tVFS_Node *Node, int ID, void *Arg);
100 void    RTL8139_IRQHandler(int Num, void *Ptr);
101
102 // === GLOBALS ===
103 MODULE_DEFINE(0, VERSION, RTL8139, RTL8139_Install, NULL, NULL);
104 tVFS_NodeType   gRTL8139_RootNodeType = {
105         .ReadDir = RTL8139_ReadDir,
106         .FindDir = RTL8139_FindDir,
107         .IOCtl = RTL8139_IOCtl
108         };
109 tVFS_NodeType   gRTL8139_DevNodeType = {
110         .Write = RTL8139_Write,
111         .Read = RTL8139_Read,
112         .IOCtl = RTL8139_IOCtl  
113         };
114 tDevFS_Driver   gRTL8139_DriverInfo = {
115         NULL, "RTL8139",
116         {
117         .NumACLs = 1,
118         .ACLs = &gVFS_ACL_EveryoneRX,
119         .Flags = VFS_FFLAG_DIRECTORY,
120         .Type = &gRTL8139_RootNodeType
121         }
122 };
123  int    giRTL8139_CardCount;
124 tCard   *gaRTL8139_Cards;
125
126 // === CODE ===
127 /**
128  * \brief Installs the RTL8139 Driver
129  */
130 int RTL8139_Install(char **Options)
131 {
132          int    id = -1;
133          int    i = 0;
134         Uint16  base;
135         tCard   *card;
136         
137         giRTL8139_CardCount = PCI_CountDevices(VENDOR_ID, DEVICE_ID);
138         
139         if( giRTL8139_CardCount == 0 )  return MODULE_ERR_NOTNEEDED;
140
141         Log_Debug("RTL8139", "%i cards", giRTL8139_CardCount);  
142         gaRTL8139_Cards = calloc( giRTL8139_CardCount, sizeof(tCard) );
143         
144         for( i = 0 ; (id = PCI_GetDevice(VENDOR_ID, DEVICE_ID, i)) != -1; i ++ )
145         {
146                 card = &gaRTL8139_Cards[i];
147                 base = PCI_GetBAR( id, 0 );
148                 if( !(base & 1) ) {
149                         Log_Warning("RTL8139", "Driver does not support MMIO, skipping card (addr %x)",
150                                 base);
151                         card->IOBase = 0;
152                         card->IRQ = 0;
153                         continue ;
154                 }
155                 base &= ~1;
156                 card->IOBase = base;
157                 card->IRQ = PCI_GetIRQ( id );
158                 
159                 // Install IRQ Handler
160                 IRQ_AddHandler(card->IRQ, RTL8139_IRQHandler, card);
161                 
162                 // Power on
163                 outb( base + CONFIG1, 0x00 );
164
165                 // Reset (0x10 to CMD)
166                 outb( base + CMD, 0x10 );       
167                 while( inb(base + CMD) & 0x10 ) ;
168                 
169                 // Set up recieve buffer
170                 // - Allocate 3 pages below 4GiB for the recieve buffer (Allows 8k+16+1500)
171                 card->ReceiveBuffer = (void*)MM_AllocDMA( 3, 32, &card->PhysReceiveBuffer );
172                 card->ReceiveBufferLength = 8*1024;
173                 outd(base + RBSTART, (Uint32)card->PhysReceiveBuffer);
174                 outd(base + CBA, 0);
175                 outd(base + CAPR, 0);
176                 // Set IMR to Transmit OK and Receive OK
177                 outw(base + IMR, 0x5);
178                 
179                 // Set up transmit buffers
180                 // - 2 non-contiguous pages (each page can fit 2 1500 byte packets)
181                 card->TransmitBuffers[0] = (void*)MM_AllocDMA( 1, 32, &card->PhysTransmitBuffers[0] );
182                 card->TransmitBuffers[1] = card->TransmitBuffers[0] + 0x800;
183                 card->PhysTransmitBuffers[1] = card->PhysTransmitBuffers[0] + 0x800;
184                 
185                 card->TransmitBuffers[2] = (void*)MM_AllocDMA( 1, 32, &card->PhysTransmitBuffers[2] );
186                 card->TransmitBuffers[3] = card->TransmitBuffers[2] + 0x800;
187                 card->PhysTransmitBuffers[3] = card->PhysTransmitBuffers[2] + 0x800;
188                 
189                 outd(base + TSAD0, card->PhysTransmitBuffers[0]);
190                 outd(base + TSAD1, card->PhysTransmitBuffers[1]);
191                 outd(base + TSAD2, card->PhysTransmitBuffers[2]);
192                 outd(base + TSAD3, card->PhysTransmitBuffers[3]);
193                 
194                 // Set recieve buffer size and recieve mask
195                 // - Bit 7 being set tells the card to overflow the recieve buffer if needed
196                 //   (i.e. when the packet starts at the end of the bufffer, it overflows up
197                 //    to 1500 bytes)
198                 outd(base + RCR, 0x8F);
199         
200                 // Recive Enable and Transmit Enable    
201                 outb(base + CMD, 0x0C);
202                 
203                 // Get the card's MAC address
204                 card->MacAddr[0] = inb(base+MAC0);
205                 card->MacAddr[1] = inb(base+MAC1);
206                 card->MacAddr[2] = inb(base+MAC2);
207                 card->MacAddr[3] = inb(base+MAC3);
208                 card->MacAddr[4] = inb(base+MAC4);
209                 card->MacAddr[5] = inb(base+MAC5);
210                 
211                 // Set VFS Node
212                 card->Name[0] = '0'+i;
213                 card->Name[1] = '\0';
214                 card->Node.ImplPtr = card;
215                 card->Node.NumACLs = 0;
216                 card->Node.CTime = now();
217                 card->Node.Type = &gRTL8139_DevNodeType;
218                 
219                 Log_Log("RTL8139", "Card %i 0x%04x, IRQ %i %02x:%02x:%02x:%02x:%02x:%02x",
220                         i, card->IOBase, card->IRQ,
221                         card->MacAddr[0], card->MacAddr[1], card->MacAddr[2],
222                         card->MacAddr[3], card->MacAddr[4], card->MacAddr[5]
223                         );
224         }
225         
226         gRTL8139_DriverInfo.RootNode.Size = giRTL8139_CardCount;
227         DevFS_AddDevice( &gRTL8139_DriverInfo );
228         
229         return MODULE_ERR_OK;
230 }
231
232 // --- Root Functions ---
233 char *RTL8139_ReadDir(tVFS_Node *Node, int Pos)
234 {
235         if( Pos < 0 || Pos >= giRTL8139_CardCount )     return NULL;
236         
237         return strdup( gaRTL8139_Cards[Pos].Name );
238 }
239
240 tVFS_Node *RTL8139_FindDir(tVFS_Node *Node, const char *Filename)
241 {
242         //TODO: It might be an idea to supprt >10 cards
243         if(Filename[0] == '\0' || Filename[1] != '\0')  return NULL;
244         if(Filename[0] < '0' || Filename[0] > '9')      return NULL;
245         return &gaRTL8139_Cards[ Filename[0]-'0' ].Node;
246 }
247
248 const char *csaRTL8139_RootIOCtls[] = {DRV_IOCTLNAMES, NULL};
249 int RTL8139_RootIOCtl(tVFS_Node *Node, int ID, void *Data)
250 {
251         ENTER("pNode iID pData", Node, ID, Data);
252         switch(ID)
253         {
254         BASE_IOCTLS(DRV_TYPE_NETWORK, "RTL8139", VERSION, csaRTL8139_RootIOCtls);
255         }
256         LEAVE('i', 0);
257         return 0;
258 }
259
260 // --- File Functions ---
261 Uint64 RTL8139_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
262 {
263         tCard   *card = Node->ImplPtr;
264         Uint16  read_ofs, pkt_length;
265          int    new_read_ofs;
266
267         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
268
269 retry:
270         if( Semaphore_Wait( &card->ReadSemaphore, 1 ) != 1 )
271         {
272                 LEAVE_RET('i', 0);
273         }
274         
275         Mutex_Acquire( &card->ReadMutex );
276         
277         read_ofs = inw( card->IOBase + CAPR );
278         LOG("raw read_ofs = %i", read_ofs);
279         read_ofs = (read_ofs + 0x10) & 0xFFFF;
280         LOG("read_ofs = %i", read_ofs);
281         
282         pkt_length = *(Uint16*)&card->ReceiveBuffer[read_ofs+2];
283         
284         // Calculate new read offset
285         new_read_ofs = read_ofs + pkt_length + 4;
286         new_read_ofs = (new_read_ofs + 3) & ~3; // Align
287         if(new_read_ofs > card->ReceiveBufferLength) {
288                 LOG("wrapping read_ofs");
289                 new_read_ofs -= card->ReceiveBufferLength;
290         }
291         new_read_ofs -= 0x10;   // I dunno
292         LOG("new_read_ofs = %i", new_read_ofs);
293         
294         // Check for errors
295         if( *(Uint16*)&card->ReceiveBuffer[read_ofs] & 0x1E ) {
296                 // Update CAPR
297                 outw(card->IOBase + CAPR, new_read_ofs);
298                 Mutex_Release( &card->ReadMutex );
299                 goto retry;     // I feel evil
300         }
301         
302         // Get packet
303         if( Length > pkt_length )       Length = pkt_length;
304         memcpy(Buffer, &card->ReceiveBuffer[read_ofs+4], Length);
305         
306         // Update CAPR
307         outw(card->IOBase + CAPR, new_read_ofs);
308         
309         Mutex_Release( &card->ReadMutex );
310         
311         LEAVE('i', Length);
312         
313         return Length;
314 }
315
316 Uint64 RTL8139_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, const void *Buffer)
317 {
318          int    td;
319         Uint32  status;
320         tCard   *card = Node->ImplPtr;
321         
322         if( Length > 1500 )     return 0;       // MTU exceeded
323         
324         ENTER("pNode XLength pBuffer", Node, Length, Buffer);
325         
326         // TODO: Implement a semaphore for avaliable transmit buffers
327
328         // Find an avaliable descriptor
329         Mutex_Acquire(&card->CurTXProtector);
330         td = card->CurTXDescriptor;
331         card->CurTXDescriptor ++;
332         card->CurTXDescriptor %= 4;
333         Mutex_Release(&card->CurTXProtector);
334         // - Lock it
335         Mutex_Acquire( &card->TransmitInUse[td] );
336         
337         LOG("td = %i", td);
338         
339         // Transmit using descriptor `td`
340         LOG("card->PhysTransmitBuffers[td] = %P", card->PhysTransmitBuffers[td]);
341         outd(card->IOBase + TSAD0 + td*4, card->PhysTransmitBuffers[td]);
342         LOG("card->TransmitBuffers[td] = %p", card->TransmitBuffers[td]);
343         // Copy to buffer
344         memcpy(card->TransmitBuffers[td], Buffer, Length);
345         // Start
346         status = 0;
347         status |= Length & 0x1FFF;      // 0-12: Length
348         status |= 0 << 13;      // 13: OWN bit
349         status |= (0 & 0x3F) << 16;     // 16-21: Early TX threshold (zero atm, TODO: check)
350         LOG("status = 0x%08x", status);
351         outd(card->IOBase + TSD0 + td*4, status);
352         
353         LEAVE('i', (int)Length);
354         
355         return Length;
356 }
357
358 const char *csaRTL8139_NodeIOCtls[] = {DRV_IOCTLNAMES, NULL};
359 int RTL8139_IOCtl(tVFS_Node *Node, int ID, void *Data)
360 {
361         tCard   *card = Node->ImplPtr;
362         ENTER("pNode iID pData", Node, ID, Data);
363         switch(ID)
364         {
365         BASE_IOCTLS(DRV_TYPE_NETWORK, "RTL8139", VERSION, csaRTL8139_NodeIOCtls);
366         case NET_IOCTL_GETMAC:
367                 if( !CheckMem(Data, 6) ) {
368                         LEAVE('i', -1);
369                         return -1;
370                 }
371                 memcpy( Data, card->MacAddr, 6 );
372                 LEAVE('i', 1);
373                 return 1;
374         }
375         LEAVE('i', 0);
376         return 0;
377 }
378
379 void RTL8139_IRQHandler(int Num, void *Ptr)
380 {
381          int    j;
382         tCard   *card = Ptr;
383         Uint16  status;
384
385         LOG("Num = %i", Num);
386         
387         if( Num != card->IRQ )  return;
388                 
389         status = inw(card->IOBase + ISR);
390         LOG("status = 0x%02x", status);
391                 
392         // Transmit OK, a transmit descriptor is now free
393         if( status & FLAG_ISR_TOK )
394         {
395                 for( j = 0; j < 4; j ++ )
396                 {
397                         if( ind(card->IOBase + TSD0 + j*4) & 0x8000 ) { // TSD TOK
398                                 Mutex_Release( &card->TransmitInUse[j] );
399                                 // TODO: Update semaphore once implemented
400                         }
401                 }
402                 outw(card->IOBase + ISR, FLAG_ISR_TOK);
403         }
404         
405         // Recieve OK, inform read
406         if( status & FLAG_ISR_ROK )
407         {
408                  int    read_ofs, end_ofs;
409                  int    packet_count = 0;
410                  int    len;
411                 
412                 // Scan recieve buffer for packets
413                 end_ofs = inw(card->IOBase + CBA);
414                 read_ofs = card->SeenOfs;
415                 LOG("read_ofs = %i, end_ofs = %i", read_ofs, end_ofs);
416                 if( read_ofs > end_ofs )
417                 {
418                         while( read_ofs < card->ReceiveBufferLength )
419                         {
420                                 packet_count ++;
421                                 len = *(Uint16*)&card->ReceiveBuffer[read_ofs+2];
422                                 LOG("%i 0x%x Pkt Hdr: 0x%04x, len: 0x%04x",
423                                         packet_count, read_ofs,
424                                         *(Uint16*)&card->ReceiveBuffer[read_ofs],
425                                         len
426                                         );
427                                 if(len > 2000) {
428                                         Log_Warning("RTL8139", "IRQ: Packet in buffer exceeds sanity (%i>2000)", len);
429                                 }
430                                 read_ofs += len + 4;
431                                 read_ofs = (read_ofs + 3) & ~3; // Align
432                         }
433                         read_ofs -= card->ReceiveBufferLength;
434                         LOG("wrapped read_ofs");
435                 }
436                 while( read_ofs < end_ofs )
437                 {
438                         packet_count ++;
439                         LOG("%i 0x%x Pkt Hdr: 0x%04x, len: 0x%04x",
440                                 packet_count, read_ofs,
441                                 *(Uint16*)&card->ReceiveBuffer[read_ofs],
442                                 *(Uint16*)&card->ReceiveBuffer[read_ofs+2]
443                                 );
444                         read_ofs += *(Uint16*)&card->ReceiveBuffer[read_ofs+2] + 4;
445                         read_ofs = (read_ofs + 3) & ~3; // Align
446                 }
447                 if( read_ofs != end_ofs ) {
448                         Log_Warning("RTL8139", "IRQ: read_ofs (%i) != end_ofs(%i)", read_ofs, end_ofs);
449                         read_ofs = end_ofs;
450                 }
451                 card->SeenOfs = read_ofs;
452                 
453                 LOG("packet_count = %i, read_ofs = 0x%x", packet_count, read_ofs);
454                 
455                 if( packet_count )
456                 {
457                         if( Semaphore_Signal( &card->ReadSemaphore, packet_count ) != packet_count ) {
458                                 // Oops?
459                         }
460                         VFS_MarkAvaliable( &card->Node, 1 );
461                 }
462                 
463                 outw(card->IOBase + ISR, FLAG_ISR_ROK);
464         }       
465 }

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