IPStack - Reworking of network device API
[tpg/acess2.git] / KernelLand / Modules / Network / NE2000 / ne2000.c
1 /*
2  * Acess2 NE2000 Driver
3  * - By John Hodge (thePowersGang)
4  * 
5  * See: ~/Sources/bochs/bochs.../iodev/ne2k.cc
6  */
7 #define DEBUG   1
8 #define VERSION VER2(0,6)
9 #include <acess.h>
10 #include <modules.h>
11 #include <drv_pci.h>
12 #include <semaphore.h>
13 #include <IPStack/include/adapters_api.h>
14
15 // === CONSTANTS ===
16 #define MEM_START       0x40
17 #define MEM_END         0xC0
18 #define RX_FIRST        (MEM_START)
19 #define RX_LAST         (MEM_START+RX_BUF_SIZE-1)
20 #define RX_BUF_SIZE     0x40
21 #define TX_FIRST        (MEM_START+RX_BUF_SIZE)
22 #define TX_LAST         (MEM_END)
23 #define TX_BUF_SIZE     0x40
24 #define MAX_PACKET_QUEUE        10
25
26 static const struct {
27         Uint16  Vendor;
28         Uint16  Device;
29 } csaCOMPAT_DEVICES[] = {
30         {0x10EC, 0x8029},       // Realtek 8029
31         {0x10EC, 0x8129}        // Realtek 8129
32 };
33 #define NUM_COMPAT_DEVICES      ((int)(sizeof(csaCOMPAT_DEVICES)/sizeof(csaCOMPAT_DEVICES[0])))
34
35 enum eNe2k_Page0Read {
36         CMD = 0,        //!< the master command register
37         CLDA0,          //!< Current Local DMA Address 0
38         CLDA1,          //!< Current Local DMA Address 1
39         BNRY,           //!< Boundary Pointer (for ringbuffer)
40         TSR,            //!< Transmit Status Register
41         NCR,            //!< collisions counter
42         FIFO,           //!< (for what purpose ??)
43         ISR,            //!< Interrupt Status Register
44         CRDA0,          //!< Current Remote DMA Address 0
45         CRDA1,          //!< Current Remote DMA Address 1
46         RSR = 0xC       //!< Receive Status Register
47 };
48
49 enum eNe2k_Page0Write {
50         PSTART = 1,     //!< page start (init only)
51         PSTOP,          //!< page stop  (init only)
52         TPSR = 4,       //!< transmit page start address
53         TBCR0,          //!< transmit byte count (low)
54         TBCR1,          //!< transmit byte count (high)
55         RSAR0 = 8,      //!< remote start address (lo)
56         RSAR1,  //!< remote start address (hi)
57         RBCR0,  //!< remote byte count (lo)
58         RBCR1,  //!< remote byte count (hi)
59         RCR,    //!< receive config register
60         TCR,    //!< transmit config register
61         DCR,    //!< data config register    (init)
62         IMR             //!< interrupt mask register (init)
63 };
64
65 enum eNe2k_Page1Read {
66         CURR = 7        //!< current page
67 };
68
69 // === TYPES ===
70 typedef struct sNe2k_Card {
71         Uint16  IOBase; //!< IO Port Address from PCI
72         Uint8   IRQ;    //!< IRQ Assigned from PCI
73         
74         tSemaphore      Semaphore;      //!< Semaphore for incoming packets
75          int    NextRXPage;     //!< Next expected RX page
76         
77          int    NextMemPage;    //!< Next Card Memory page to use
78                 
79         void    *IPStackHandle;
80         Uint8   MacAddr[6];     //!< Cached MAC address
81 } tCard;
82
83 // === PROTOTYPES ===
84  int    Ne2k_Install(char **Arguments);
85
86  int    Ne2k_SendPacket(void *Ptr, tIPStackBuffer *Buffer);
87 tIPStackBuffer  *Ne2k_WaitForPacket(void *Ptr);
88
89  int    Ne2k_int_ReadDMA(tCard *Card, int FirstPage, int NumPages, void *Buffer);
90 Uint8   Ne2k_int_GetWritePage(tCard *Card, Uint16 Length);
91 void    Ne2k_IRQHandler(int IntNum, void *Ptr);
92
93 // === GLOBALS ===
94 MODULE_DEFINE(0, VERSION, Ne2k, Ne2k_Install, NULL, NULL);
95 tIPStack_AdapterType    gNe2k_AdapterType = {
96         .Name = "Ne2k",
97         .Type = 0,      // TODO: Differentiate differnet wire protos and speeds
98         .Flags = 0,     // TODO: IP checksum offloading, MAC checksum offloading etc
99         .SendPacket = Ne2k_SendPacket,
100         .WaitForPacket = Ne2k_WaitForPacket
101 };
102  int    giNe2k_CardCount = 0;
103 tCard   *gpNe2k_Cards = NULL;
104
105 // === CODE ===
106 /**
107  * \fn int Ne2k_Install(char **Options)
108  * \brief Installs the NE2000 Driver
109  */
110 int Ne2k_Install(char **Options)
111 {
112          int    i, j, k;
113          int    count, base;
114         tPCIDev id;
115         
116         // --- Scan PCI Bus ---
117         // Count Cards
118         giNe2k_CardCount = 0;
119         for( i = 0; i < NUM_COMPAT_DEVICES; i ++ )
120         {
121                 giNe2k_CardCount += PCI_CountDevices( csaCOMPAT_DEVICES[i].Vendor, csaCOMPAT_DEVICES[i].Device );
122         }
123         if( giNe2k_CardCount == 0 )     return MODULE_ERR_NOTNEEDED;
124
125         LOG("%i NE2K cards found", giNe2k_CardCount);
126         
127         // Enumerate Cards
128         k = 0;
129         gpNe2k_Cards = calloc( giNe2k_CardCount, sizeof(tCard) );
130         
131         for( i = 0; i < NUM_COMPAT_DEVICES; i ++ )
132         {
133                 count = PCI_CountDevices( csaCOMPAT_DEVICES[i].Vendor, csaCOMPAT_DEVICES[i].Device );
134                 for( j = 0; j < count; j ++, k ++ )
135                 {
136                         tCard   *card = &gpNe2k_Cards[k];
137                         
138                         id = PCI_GetDevice( csaCOMPAT_DEVICES[i].Vendor, csaCOMPAT_DEVICES[i].Device, j );
139                         // Create Structure
140                         base = PCI_GetBAR( id, 0 );
141                         LOG("%i: %i/%i id = %i, base = 0x%x", k, i, j, id, base);
142                         if( !(base & 1) ) {
143                                 Log_Warning("Ne2k", "PCI %i's BARs are incorrect (BAR0 is not IO)", id);
144                                 continue ;
145                         }
146                         base &= ~1;
147                         card->IOBase = base;
148                         card->IRQ = PCI_GetIRQ( id );
149                         card->NextMemPage = 64;
150                         card->NextRXPage = RX_FIRST;
151                         
152                         // Install IRQ Handler
153                         IRQ_AddHandler(card->IRQ, Ne2k_IRQHandler, &gpNe2k_Cards[k]);
154                         LOG("%i: IRQ %i mapped, IOBase = 0x%x", k, card->IRQ, card->IOBase);
155                         
156                         // Reset Card
157                         outb( base + 0x1F, inb(base + 0x1F) );
158                         while( (inb( base + ISR ) & 0x80) == 0 );
159                         outb( base + ISR, 0x80 );
160                 
161                         LOG("Reset done");
162         
163                         // Initialise Card
164                         outb( base + CMD, 0x40|0x21 );  // Page 1, No DMA, Stop
165                         outb( base + CURR, RX_FIRST );  // Current RX page
166                         outb( base + CMD, 0x21 );       // No DMA and Stop
167                         outb( base + DCR, 0x49 );       // Set WORD mode
168                         outb( base + IMR, 0x00 );       // Interrupt Mask Register
169                         outb( base + ISR, 0xFF );
170                         outb( base + RCR, 0x20 );       // Reciever to Monitor
171                         outb( base + TCR, 0x02 );       // Transmitter OFF (TCR.LB = 1, Internal Loopback)
172                         
173                         // Read MAC Address
174                         outb( base + RBCR0, 6*4 );      // Remote Byte Count
175                         outb( base + RBCR1, 0 );
176                         outb( base + RSAR0, 0 );        // Clear Source Address
177                         outb( base + RSAR1, 0 );
178                         outb( base + CMD, 0x0A );       // Remote Read, Start
179                         card->MacAddr[0] = inb(base+0x10);//    inb(base+0x10);
180                         card->MacAddr[1] = inb(base+0x10);//    inb(base+0x10);
181                         card->MacAddr[2] = inb(base+0x10);//    inb(base+0x10);
182                         card->MacAddr[3] = inb(base+0x10);//    inb(base+0x10);
183                         card->MacAddr[4] = inb(base+0x10);//    inb(base+0x10);
184                         card->MacAddr[5] = inb(base+0x10);//    inb(base+0x10);
185                         
186                         outb( base+PSTART, RX_FIRST);   // Set Receive Start
187                         outb( base+BNRY, RX_LAST-1);    // Set Boundary Page
188                         outb( base+PSTOP, RX_LAST);     // Set Stop Page
189                         outb( base+ISR, 0xFF ); // Clear all ints
190                         outb( base+CMD, 0x22 ); // No DMA, Start
191                         outb( base+IMR, 0x3F ); // Set Interupt Mask
192                         outb( base+RCR, 0x0F ); // Set WRAP and allow all packet matches
193                         outb( base+TCR, 0x00 ); // Set Normal Transmitter mode
194                         outb( base+TPSR, 0x40); // Set Transmit Start
195                         
196                         Log_Log("Ne2k", "Card %i 0x%04x IRQ%i %02x:%02x:%02x:%02x:%02x:%02x",
197                                 k, base, card->IRQ,
198                                 card->MacAddr[0], card->MacAddr[1],
199                                 card->MacAddr[2], card->MacAddr[3],
200                                 card->MacAddr[4], card->MacAddr[5]
201                                 );
202                         
203                         card->IPStackHandle = IPStack_Adapter_Add(&gNe2k_AdapterType, card, card->MacAddr);
204                         
205                         // Initialise packet semaphore
206                         // - Start at zero, no max
207                         char    name[10];
208                         sprintf(name, "%i", k-1);
209                         Semaphore_Init( &card->Semaphore, 0, 0, "NE2000", name );
210                 }
211         }
212         
213         return MODULE_ERR_OK;
214 }
215
216 /**
217  * \brief Send a packet from the network card
218  */
219 int Ne2k_SendPacket(void *Ptr, tIPStackBuffer *Buffer)
220 {
221         tCard   *Card = Ptr;
222          int    length;
223          int    page;
224         
225         ENTER("pPtr pBuffer", Ptr, Buffer);
226         
227         length = IPStack_Buffer_GetLength(Buffer);
228
229         // TODO: Lock
230         
231         // Sanity Check Length
232         if(length > TX_BUF_SIZE*256) {
233                 Log_Warning(
234                         "Ne2k",
235                         "Ne2k_Write - Attempting to send over TX_BUF_SIZE*256 (%i) bytes (%i)",
236                         TX_BUF_SIZE*256, length
237                         );
238                 LEAVE('i', -1);
239                 return -1;
240         }
241         
242         // Make sure that the card is in page 0
243         outb(Card->IOBase + CMD, 0|0x22);       // Page 0, Start, NoDMA
244         
245         // Clear Remote DMA Flag
246         outb(Card->IOBase + ISR, 0x40); // Bit 6
247         
248         // Send Size - Transfer Byte Count Register
249         outb(Card->IOBase + TBCR0, length & 0xFF);
250         outb(Card->IOBase + TBCR1, length >> 8);
251         
252         // Send Size - Remote Byte Count Register
253         outb(Card->IOBase + RBCR0, length & 0xFF);
254         outb(Card->IOBase + RBCR1, length >> 8);
255         
256         // Set up transfer
257         outb(Card->IOBase + RSAR0, 0x00);       // Page Offset
258         page = Ne2k_int_GetWritePage(Card, length);
259         outb(Card->IOBase + RSAR1, page);       // Page Offset
260         // Start
261         outb(Card->IOBase + CMD, 0|0x10|0x2);   // Page 0, Remote Write, Start
262         
263         // Send Data
264         size_t  buflen;
265         const void      *bufptr;
266         for(int id = -1; (id = IPStack_Buffer_GetBuffer(Buffer, -1, &buflen, &bufptr)) != -1; )
267         {
268                 const Uint16    *buf = bufptr;
269                 if( buflen & 1 )
270                         Log_Notice("NE2000", "Alignment issue in TX buffer");
271                 buflen = (buflen + 1) / 2;
272                 while(buflen --)
273                         outw(Card->IOBase + 0x10, *buf++);
274         }
275         
276         while( !(inb(Card->IOBase + ISR) & 0x40) )      // Wait for Remote DMA Complete
277                 ;       //Proc_Yield();
278         
279         outb( Card->IOBase + ISR, 0x40 );       // ACK Interrupt
280         
281         // Send Packet
282         outb(Card->IOBase + TPSR, page);
283         outb(Card->IOBase + CMD, 0|0x10|0x4|0x2);
284         
285         // Complete DMA
286         //outb(Card->IOBase + CMD, 0|0x20);
287         
288         LEAVE('i', 0);
289         return 0;
290 }
291
292 void _FreeHeapSubBuf(void *Arg, size_t Pre, size_t Post, const void *DataBuf)
293 {
294         free(Arg);
295 }
296
297 /**
298  * \brief Wait for and read a packet from the network card
299  */
300 tIPStackBuffer *Ne2k_WaitForPacket(void *Ptr)
301 {
302         tCard   *Card = Ptr;
303         Uint8   page;
304         Uint8   data[256];
305         void    *buf;
306         tIPStackBuffer  *ret;
307         struct {
308                 Uint8   Status;
309                 Uint8   NextPacketPage;
310                 Uint16  Length; // Little Endian
311         }       *pktHdr;
312         
313         ENTER("pPtr", Ptr);
314         
315         // Wait for packets
316         if( Semaphore_Wait( &Card->Semaphore, 1 ) != 1 )
317         {
318                 // Error or interrupted
319                 LEAVE('n');
320                 return NULL;
321         }
322         
323         outb(Card->IOBase, 0x22 | (1 << 6));    // Page 6
324         LOG("CURR : 0x%02x", inb(Card->IOBase + CURR));
325         
326         // Get current read page
327         page = Card->NextRXPage;
328         LOG("page = %i", page);
329         
330         Ne2k_int_ReadDMA(Card, page, 1, data);
331         
332         pktHdr = (void*)data;
333         
334         LOG("pktHdr->Status = 0x%x", pktHdr->Status);
335         LOG("pktHdr->NextPacketPage = %i", pktHdr->NextPacketPage);
336         LOG("pktHdr->Length = 0x%03x", pktHdr->Length);
337
338         ret = IPStack_Buffer_CreateBuffer(1);
339         if(!ret)        LEAVE_RET('n', NULL);
340         buf = malloc( pktHdr->Length );
341         if(!buf)        LEAVE_RET('n', NULL);
342         IPStack_Buffer_AppendSubBuffer(ret, pktHdr->Length, 0, buf, _FreeHeapSubBuf, buf);
343
344         // Have we read all the required bytes yet?
345         if(pktHdr->Length < 256 - 4)
346         {
347                 memcpy(buf, &data[4], pktHdr->Length);
348         }
349         // No? oh damn, now we need to allocate a buffer
350         else
351         {
352                  int    pages = pktHdr->NextPacketPage - page;
353                 Uint8   *writepos = buf;
354                  int    rem_bytes = pktHdr->Length;
355                 
356                 LOG("pktHdr->Length (%i) > 256 - 4, allocated buffer %p", pktHdr->Length, buf);
357                 
358                 
359                 // Copy the already read data
360                 memcpy(writepos, data+4, 256-4);
361                 writepos += 256-4;
362                 rem_bytes -= 256-4;
363                 
364                 // Read all the needed pages
365                 page ++;
366                 if(page == RX_LAST+1)   page = RX_FIRST;
367
368                 // - Body Pages
369                 if( pages > 2 )
370                 {
371                         if( page + pages - 2 > RX_LAST )
372                         {
373                                  int    first_count = RX_LAST - page + 1;
374                                 Ne2k_int_ReadDMA(Card, page, first_count, writepos);
375                                 Ne2k_int_ReadDMA(Card, RX_FIRST, pages-2-first_count, writepos + first_count*256);
376                                 writepos += (pages-2-first_count) * 256;
377                         }
378                         else
379                                 Ne2k_int_ReadDMA(Card, page, pages - 2, writepos);
380                         page += pages - 2;
381                         if(page > RX_LAST)      page -= (RX_LAST-RX_FIRST)+1;
382                         writepos += (pages-2) * 256;
383                         rem_bytes -= (pages-2) * 256;
384                 }
385
386                 ASSERT(rem_bytes > 0 && rem_bytes <= 0x100);
387
388                 // Final page
389                 Ne2k_int_ReadDMA(Card, page, 1, data);
390                 memcpy(writepos, data, rem_bytes);
391         }
392         
393         // Write BNRY (maximum page for incoming packets)
394         if(pktHdr->NextPacketPage == RX_FIRST)
395                 outb( Card->IOBase + BNRY, RX_LAST-1 );
396         else
397                 outb( Card->IOBase + BNRY, pktHdr->NextPacketPage-1 );
398         // Set next RX Page and decrement the waiting list
399         Card->NextRXPage = pktHdr->NextPacketPage;
400         
401         LEAVE('p', ret);
402         return ret;
403 }
404
405 int Ne2k_int_ReadDMA(tCard *Card, int FirstPage, int NumPages, void *Buffer)
406 {
407          int    i;
408         
409         // Sanity check
410         if( !(0 <= FirstPage && FirstPage < 256) ) {
411                 Log_Warning("NE2000", "Ne2k_int_ReadDMA: BUG - FirstPage(%i) not 8-bit", FirstPage);
412                 return -1;
413         }
414         if( !(0 <= NumPages && NumPages < 256) ) {
415                 Log_Warning("NE2000", "Ne2k_int_ReadDMA: BUG - NumPages(%i) not 8-bit", NumPages);
416                 return -1;
417         }
418         
419         ENTER("pCard iFirstPage iNumPages pBuffer", Card, FirstPage, NumPages, Buffer);
420         
421         // Make sure that the card is in bank 0
422         outb(Card->IOBase + CMD, 0|0x22);       // Bank 0, Start, NoDMA
423         outb(Card->IOBase + ISR, 0x40); // Clear Remote DMA Flag
424         
425         // Set up transfer
426         outb(Card->IOBase + RBCR0, 0);
427         outb(Card->IOBase + RBCR1, NumPages);   // page count
428         outb(Card->IOBase + RSAR0, 0x00);       // Page Offset
429         outb(Card->IOBase + RSAR1, FirstPage);  // Page Number
430         outb(Card->IOBase + CMD, 0|0x08|0x2);   // Bank 0, Remote Read, Start
431         
432         // TODO: Less expensive
433         //while( !(inb(Card->IOBase + ISR) & 0x40) ) {
434         //      HALT();
435         //      LOG("inb(ISR) = 0x%02x", inb(Card->IOBase + ISR));
436         //}
437         HALT(); // Small delay?
438         
439         // Read data
440         for(i = 0; i < 128*NumPages; i ++)
441                 ((Uint16*)Buffer)[i] = inw(Card->IOBase + 0x10);
442                 
443         
444         outb(Card->IOBase + ISR, 0x40); // Clear Remote DMA Flag
445         
446         LEAVE('i', NumPages);
447         return NumPages;
448 }
449
450 /**
451  * \fn Uint8 Ne2k_int_GetWritePage(tCard *Card, Uint16 Length)
452  */
453 Uint8 Ne2k_int_GetWritePage(tCard *Card, Uint16 Length)
454 {
455         Uint8   ret = Card->NextMemPage;
456         
457         Card->NextMemPage += (Length + 0xFF) >> 8;
458         if(Card->NextMemPage >= TX_LAST) {
459                 Card->NextMemPage -= TX_BUF_SIZE;
460         }
461         
462         return ret;
463 }
464
465 /**
466  * \fn void Ne2k_IRQHandler(int IntNum)
467  */
468 void Ne2k_IRQHandler(int IntNum, void *Ptr)
469 {
470         Uint8   byte;
471         tCard   *card = Ptr;
472
473         if(card->IRQ != IntNum) return;
474         
475         byte = inb( card->IOBase + ISR );
476         
477         LOG("byte = 0x%02x", byte);
478                         
479                         
480         // Reset All (save for RDMA), that's polled
481         outb( card->IOBase + ISR, 0xFF&(~0x40) );
482                         
483         // 0: Packet recieved (no error)
484         if( byte & 1 )
485         {
486                 //if( card->NumWaitingPackets > MAX_PACKET_QUEUE )
487                 //      card->NumWaitingPackets = MAX_PACKET_QUEUE;
488                 if( Semaphore_Signal( &card->Semaphore, 1 ) != 1 ) {
489                         // Oops?
490                 }
491         }
492         // 1: Packet sent (no error)
493         // 2: Recieved with error
494         // 3: Transmission Halted (Excessive Collisions)
495         // 4: Recieve Buffer Exhausted
496         // 5: 
497         // 6: Remote DMA Complete
498         // 7: Reset
499 }

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