a4b57572c10880da85f272c7d305c75d494c8ffd
[tpg/acess2.git] / Modules / Network / NE2000 / ne2000.c
1 /* Acess2
2  * NE2000 Driver
3  * 
4  * See: ~/Sources/bochs/bochs.../iodev/ne2k.cc
5  */
6 #define DEBUG   0
7 #define VERSION ((0<<8)|50)
8 #include <acess.h>
9 #include <modules.h>
10 #include <fs_devfs.h>
11 #include <drv_pci.h>
12 #include <tpl_drv_network.h>
13 #include <semaphore.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;
75 //       int    NumWaitingPackets;
76          int    NextRXPage;
77         
78          int    NextMemPage;    //!< Next Card Memory page to use
79         
80         Uint8   Buffer[RX_BUF_SIZE*256];
81         
82         char    Name[2];        // "0"
83         tVFS_Node       Node;
84         Uint8   MacAddr[6];
85 } tCard;
86
87 // === PROTOTYPES ===
88  int    Ne2k_Install(char **Arguments);
89 char    *Ne2k_ReadDir(tVFS_Node *Node, int Pos);
90 tVFS_Node       *Ne2k_FindDir(tVFS_Node *Node, const char *Name);
91  int    Ne2k_IOCtl(tVFS_Node *Node, int ID, void *Data);
92 Uint64  Ne2k_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
93 Uint64  Ne2k_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
94 Uint8   Ne2k_int_GetWritePage(tCard *Card, Uint16 Length);
95 void    Ne2k_IRQHandler(int IntNum);
96
97 // === GLOBALS ===
98 MODULE_DEFINE(0, VERSION, Ne2k, Ne2k_Install, NULL, NULL);
99 tDevFS_Driver   gNe2k_DriverInfo = {
100         NULL, "ne2k",
101         {
102         .NumACLs = 1,
103         .ACLs = &gVFS_ACL_EveryoneRX,
104         .Flags = VFS_FFLAG_DIRECTORY,
105         .ReadDir = Ne2k_ReadDir,
106         .FindDir = Ne2k_FindDir,
107         .IOCtl = Ne2k_IOCtl
108         }
109 };
110 Uint16  gNe2k_BaseAddress;
111  int    giNe2k_CardCount = 0;
112 tCard   *gpNe2k_Cards = NULL;
113
114 // === CODE ===
115 /**
116  * \fn int Ne2k_Install(char **Options)
117  * \brief Installs the NE2000 Driver
118  */
119 int Ne2k_Install(char **Options)
120 {
121          int    i, j, k;
122          int    count, id, base;
123         
124         // --- Scan PCI Bus ---
125         // Count Cards
126         giNe2k_CardCount = 0;
127         for( i = 0; i < NUM_COMPAT_DEVICES; i ++ )
128         {
129                 giNe2k_CardCount += PCI_CountDevices( csaCOMPAT_DEVICES[i].Vendor, csaCOMPAT_DEVICES[i].Device, 0 );
130         }
131         
132         if( giNe2k_CardCount == 0 ) {
133                 Log_Warning("Ne2k", "No cards detected");
134                 return MODULE_ERR_NOTNEEDED;
135         }
136         
137         // Enumerate Cards
138         k = 0;
139         gpNe2k_Cards = calloc( giNe2k_CardCount, sizeof(tCard) );
140         
141         for( i = 0; i < NUM_COMPAT_DEVICES; i ++ )
142         {
143                 count = PCI_CountDevices( csaCOMPAT_DEVICES[i].Vendor, csaCOMPAT_DEVICES[i].Device, 0 );
144                 for( j = 0; j < count; j ++,k ++ )
145                 {
146                         id = PCI_GetDevice( csaCOMPAT_DEVICES[i].Vendor, csaCOMPAT_DEVICES[i].Device, 0, j );
147                         // Create Structure
148                         base = PCI_AssignPort( id, 0, 0x20 );
149                         gpNe2k_Cards[ k ].IOBase = base;
150                         gpNe2k_Cards[ k ].IRQ = PCI_GetIRQ( id );
151                         gpNe2k_Cards[ k ].NextMemPage = 64;
152                         gpNe2k_Cards[ k ].NextRXPage = RX_FIRST;
153                         
154                         // Install IRQ Handler
155                         IRQ_AddHandler(gpNe2k_Cards[ k ].IRQ, Ne2k_IRQHandler);
156                         
157                         // Reset Card
158                         outb( base + 0x1F, inb(base + 0x1F) );
159                         while( (inb( base+ISR ) & 0x80) == 0 );
160                         outb( base + ISR, 0x80 );
161                         
162                         // Initialise Card
163                         outb( base + CMD, 0x40|0x21 );  // Page 1, No DMA, Stop
164                         outb( base + CURR, RX_FIRST );  // Current RX page
165                         outb( base + CMD, 0x21 );       // No DMA and Stop
166                         outb( base + DCR, 0x49 );       // Set WORD mode
167                         outb( base + IMR, 0x00 );       // Interrupt Mask Register
168                         outb( base + ISR, 0xFF );
169                         outb( base + RCR, 0x20 );       // Reciever to Monitor
170                         outb( base + TCR, 0x02 );       // Transmitter OFF (TCR.LB = 1, Internal Loopback)
171                         outb( base + RBCR0, 6*4 );      // Remote Byte Count
172                         outb( base + RBCR1, 0 );
173                         outb( base + RSAR0, 0 );        // Clear Source Address
174                         outb( base + RSAR1, 0 );
175                         outb( base + CMD, 0x0A );       // Remote Read, Start
176                         
177                         // Read MAC Address
178                         gpNe2k_Cards[ k ].MacAddr[0] = inb(base+0x10);//        inb(base+0x10);
179                         gpNe2k_Cards[ k ].MacAddr[1] = inb(base+0x10);//        inb(base+0x10);
180                         gpNe2k_Cards[ k ].MacAddr[2] = inb(base+0x10);//        inb(base+0x10);
181                         gpNe2k_Cards[ k ].MacAddr[3] = inb(base+0x10);//        inb(base+0x10);
182                         gpNe2k_Cards[ k ].MacAddr[4] = inb(base+0x10);//        inb(base+0x10);
183                         gpNe2k_Cards[ k ].MacAddr[5] = inb(base+0x10);//        inb(base+0x10);
184                         
185                         outb( base+PSTART, RX_FIRST);   // Set Receive Start
186                         outb( base+BNRY, RX_LAST-1);    // Set Boundary Page
187                         outb( base+PSTOP, RX_LAST);     // Set Stop Page
188                         outb( base+ISR, 0xFF ); // Clear all ints
189                         outb( base+CMD, 0x22 ); // No DMA, Start
190                         outb( base+IMR, 0x3F ); // Set Interupt Mask
191                         outb( base+RCR, 0x0F ); // Set WRAP and allow all packet matches
192                         outb( base+TCR, 0x00 ); // Set Normal Transmitter mode
193                         outb( base+TPSR, 0x40); // Set Transmit Start
194                         // Set MAC Address
195                         /*
196                         Ne2k_WriteReg(base, MAC0, gpNe2k_Cards[ k ].MacAddr[0]);
197                         Ne2k_WriteReg(base, MAC1, gpNe2k_Cards[ k ].MacAddr[1]);
198                         Ne2k_WriteReg(base, MAC2, gpNe2k_Cards[ k ].MacAddr[2]);
199                         Ne2k_WriteReg(base, MAC3, gpNe2k_Cards[ k ].MacAddr[3]);
200                         Ne2k_WriteReg(base, MAC4, gpNe2k_Cards[ k ].MacAddr[4]);
201                         Ne2k_WriteReg(base, MAC5, gpNe2k_Cards[ k ].MacAddr[5]);
202                         */
203                         
204                         Log_Log("Ne2k", "Card %i 0x%04x IRQ%i %02x:%02x:%02x:%02x:%02x:%02x",
205                                 k, base, gpNe2k_Cards[ k ].IRQ,
206                                 gpNe2k_Cards[k].MacAddr[0], gpNe2k_Cards[k].MacAddr[1],
207                                 gpNe2k_Cards[k].MacAddr[2], gpNe2k_Cards[k].MacAddr[3],
208                                 gpNe2k_Cards[k].MacAddr[4], gpNe2k_Cards[k].MacAddr[5]
209                                 );
210                         
211                         // Set VFS Node
212                         gpNe2k_Cards[ k ].Name[0] = '0'+k;
213                         gpNe2k_Cards[ k ].Name[1] = '\0';
214                         gpNe2k_Cards[ k ].Node.ImplPtr = &gpNe2k_Cards[ k ];
215                         gpNe2k_Cards[ k ].Node.NumACLs = 0;     // Root Only
216                         gpNe2k_Cards[ k ].Node.CTime = now();
217                         gpNe2k_Cards[ k ].Node.Write = Ne2k_Write;
218                         gpNe2k_Cards[ k ].Node.Read = Ne2k_Read;
219                         gpNe2k_Cards[ k ].Node.IOCtl = Ne2k_IOCtl;
220                         
221                         // Initialise packet semaphore
222                         // - Start at zero, no max
223                         Semaphore_Init( &gpNe2k_Cards[k].Semaphore, 0, 0, "NE2000", gpNe2k_Cards[ k ].Name );
224                 }
225         }
226         
227         gNe2k_DriverInfo.RootNode.Size = giNe2k_CardCount;
228         DevFS_AddDevice( &gNe2k_DriverInfo );
229         return MODULE_ERR_OK;
230 }
231
232 /**
233  * \fn char *Ne2k_ReadDir(tVFS_Node *Node, int Pos)
234  */
235 char *Ne2k_ReadDir(tVFS_Node *Node, int Pos)
236 {
237         char    ret[2];
238         if(Pos < 0 || Pos >= giNe2k_CardCount)  return NULL;
239         ret[0] = '0'+Pos;
240         ret[1] = '\0';
241         return strdup(ret);
242 }
243
244 /**
245  * \fn tVFS_Node *Ne2k_FindDir(tVFS_Node *Node, const char *Name)
246  */
247 tVFS_Node *Ne2k_FindDir(tVFS_Node *Node, const char *Name)
248 {
249         if(Name[0] == '\0' || Name[1] != '\0')  return NULL;
250         
251         return &gpNe2k_Cards[ Name[0]-'0' ].Node;
252 }
253
254 static const char *casIOCtls[] = { DRV_IOCTLNAMES, DRV_NETWORK_IOCTLNAMES, NULL };
255 /**
256  * \fn int Ne2k_IOCtl(tVFS_Node *Node, int ID, void *Data)
257  * \brief IOCtl calls for a network device
258  */
259 int Ne2k_IOCtl(tVFS_Node *Node, int ID, void *Data)
260 {
261         ENTER("pNode iID pData", Node, ID, Data);
262         switch( ID )
263         {
264         BASE_IOCTLS(DRV_TYPE_NETWORK, "NE2000", VERSION, casIOCtls);
265         }
266         
267         // If this is the root, return
268         if( Node == &gNe2k_DriverInfo.RootNode ) {
269                 LEAVE('i', 0);
270                 return 0;
271         }
272         
273         // Device specific settings
274         switch( ID )
275         {
276         case NET_IOCTL_GETMAC:
277                 if( !CheckMem(Data, 6) ) {
278                         LEAVE('i', -1);
279                         return -1;
280                 }
281                 memcpy( Data, ((tCard*)Node->ImplPtr)->MacAddr, 6 );
282                 LEAVE('i', 1);
283                 return 1;
284         }
285         LEAVE('i', 0);
286         return 0;
287 }
288
289 /**
290  * \fn Uint64 Ne2k_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
291  * \brief Send a packet from the network card
292  */
293 Uint64 Ne2k_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
294 {
295         tCard   *Card = (tCard*)Node->ImplPtr;
296         Uint16  *buf = Buffer;
297          int    rem = Length;
298          int    page;
299         
300         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
301         
302         // Sanity Check Length
303         if(Length > TX_BUF_SIZE*256) {
304                 Log_Warning(
305                         "Ne2k",
306                         "Ne2k_Write - Attempting to send over TX_BUF_SIZE*256 (%i) bytes (%i)",
307                         TX_BUF_SIZE*256, Length
308                         );
309                 LEAVE('i', 0);
310                 return 0;
311         }
312         
313         // Make sure that the card is in page 0
314         outb(Card->IOBase + CMD, 0|0x22);       // Page 0, Start, NoDMA
315         
316         // Clear Remote DMA Flag
317         outb(Card->IOBase + ISR, 0x40); // Bit 6
318         
319         // Send Size - Remote Byte Count Register
320         outb(Card->IOBase + TBCR0, Length & 0xFF);
321         outb(Card->IOBase + TBCR1, Length >> 8);
322         
323         // Send Size - Remote Byte Count Register
324         outb(Card->IOBase + RBCR0, Length & 0xFF);
325         outb(Card->IOBase + RBCR1, Length >> 8);
326         
327         // Set up transfer
328         outb(Card->IOBase + RSAR0, 0x00);       // Page Offset
329         page = Ne2k_int_GetWritePage(Card, Length);
330         outb(Card->IOBase + RSAR1, page);       // Page Offset
331         // Start
332         //outb(Card->IOBase + CMD, 0|0x18|0x4|0x2);     // Page 0, Transmit Packet, TXP, Start
333         outb(Card->IOBase + CMD, 0|0x10|0x2);   // Page 0, Remote Write, Start
334         
335         // Send Data
336         for(rem = Length; rem > 0; rem -= 2) {
337                 outw(Card->IOBase + 0x10, *buf++);
338         }
339         
340         while( inb(Card->IOBase + ISR) == 0 )   // Wait for Remote DMA Complete
341                 ;       //Proc_Yield();
342         
343         outb( Card->IOBase + ISR, 0x40 );       // ACK Interrupt
344         
345         // Send Packet
346         outb(Card->IOBase + TPSR, page);
347         outb(Card->IOBase + CMD, 0|0x10|0x4|0x2);
348         
349         // Complete DMA
350         //outb(Card->IOBase + CMD, 0|0x20);
351         
352         LEAVE('i', Length);
353         return Length;
354 }
355
356 /**
357  * \fn Uint64 Ne2k_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
358  * \brief Wait for and read a packet from the network card
359  */
360 Uint64 Ne2k_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
361 {
362         tCard   *Card = (tCard*)Node->ImplPtr;
363         Uint8   page;
364         Uint8   data[256];
365          int    i;
366         struct {
367                 Uint8   Status;
368                 Uint8   NextPacketPage;
369                 Uint16  Length; // Little Endian
370         }       *pktHdr;
371         
372         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
373         
374         // Wait for packets
375         Semaphore_Wait( &Card->Semaphore, 1 );
376         
377         // Make sure that the card is in bank 0
378         outb(Card->IOBase + CMD, 0|0x22);       // Bank 0, Start, NoDMA
379         
380         // Get current read page
381         page = Card->NextRXPage;
382         LOG("page = %i", page);
383         
384         // Set up transfer
385         outb(Card->IOBase + RBCR0, 0);
386         outb(Card->IOBase + RBCR1, 1);  // 256-bytes
387         outb(Card->IOBase + RSAR0, 0x00);       // Page Offset
388         outb(Card->IOBase + RSAR1, page);       // Page Number
389         outb(Card->IOBase + ISR, 0x40); // Bit 6 - Clear Remote DMA Flag
390         
391         outb(Card->IOBase + CMD, 0|0x08|0x2);   // Bank 0, Remote Read, Start
392         
393         // TODO: Less expensive
394         while( inb(Card->IOBase + ISR) & 0x40 )
395                 HALT();
396         
397         // Read data
398         for(i = 0; i < 128; i ++)
399                 ((Uint16*)data)[i] = inw(Card->IOBase + 0x10);
400                 
401         
402         // Clear Remote DMA Flag
403         outb(Card->IOBase + ISR, 0x40); // Bit 6
404         
405         pktHdr = (void*)data;
406         
407         LOG("pktHdr->NextPacketPage = %i", pktHdr->NextPacketPage);
408         
409         // Have we read all the required bytes yet?
410         if(pktHdr->Length < 256 - 4)
411         {
412                 if(Length > pktHdr->Length)
413                         Length = pktHdr->Length;
414                 memcpy(Buffer, &data[4], Length);
415                 page ++;
416                 if(page == RX_LAST+1)   page = RX_FIRST;
417         }
418         // No? oh damn, now we need to allocate a buffer
419         else
420         {
421                  int    ofs = 256/2;    // buffer write offset
422                  int    pages = pktHdr->NextPacketPage - page;
423                 // int  bufLen = (pktHdr->Length + 4 + 255) & ~255;
424                 char    *buf = malloc( pages*256 );
425                 
426                 LOG("pktHdr->Length (%i) > 256 - 4, allocated buffer %p", pktHdr->Length, buf);
427                 
428                 if(!buf) {
429                         LEAVE('i', -1);
430                         return -1;
431                 }
432                 
433                 // Copy the already read data
434                 memcpy(buf, data, 256);
435                 
436                 // Read all the needed pages
437 //              do
438 //              {
439                         page ++;
440                         if(page == RX_LAST+1)   page = RX_FIRST;
441                         
442                         outb(Card->IOBase + RBCR0, 0);  // 256-bytes (low)
443                         outb(Card->IOBase + RBCR1, pages-1);    // 256-bytes (high)
444                         outb(Card->IOBase + RSAR0, 0x00);       // Page Offset
445                         outb(Card->IOBase + RSAR1, page);       // Page Number
446                         outb(Card->IOBase + ISR, 0x40); // Bit 6 - Clear Remote DMA Flag
447                         outb(Card->IOBase + CMD, 0|0x08|0x2);   // Bank 0, Remote Read, Start
448                         // TODO: Less expensive
449                         while( inb(Card->IOBase + ISR) & 0x40 ) HALT();
450                         
451                         for(i = 0; i < 128*(pages-1); i ++)
452                                 ((Uint16*)buf)[ofs+i] = inw(Card->IOBase + 0x10);
453                         
454                         outb(Card->IOBase + ISR, 0x40); // Bit 6 - Clear Remote DMA Flag
455 //                      ofs += 128;
456 //              }       while(page != pktHdr->NextPacketPage-1);
457                 
458                 // Wrap length to the packet length
459                 if(Length > pktHdr->Length)
460                         Length = pktHdr->Length;
461                 else if( Length < pktHdr->Length ) {
462                         Log_Warning("NE2000", "Packet truncated! (%i bytes truncated to %i)",
463                                 pktHdr->Length, Length);
464                 }
465                 memcpy(Buffer, &buf[4], Length);
466                 
467                 free(buf);
468         }
469         
470         // Write BNRY (maximum page for incoming packets)
471         if(page == RX_FIRST)
472                 outb( Card->IOBase + BNRY, RX_LAST-1 );
473         else
474                 outb( Card->IOBase + BNRY, page-1 );
475         // Set next RX Page and decrement the waiting list
476         Card->NextRXPage = pktHdr->NextPacketPage;
477         
478         LEAVE('i', Length);
479         return Length;
480 }
481
482 /**
483  * \fn Uint8 Ne2k_int_GetWritePage(tCard *Card, Uint16 Length)
484  */
485 Uint8 Ne2k_int_GetWritePage(tCard *Card, Uint16 Length)
486 {
487         Uint8   ret = Card->NextMemPage;
488         
489         Card->NextMemPage += (Length + 0xFF) >> 8;
490         if(Card->NextMemPage >= TX_LAST) {
491                 Card->NextMemPage -= TX_BUF_SIZE;
492         }
493         
494         return ret;
495 }
496
497 /**
498  * \fn void Ne2k_IRQHandler(int IntNum)
499  */
500 void Ne2k_IRQHandler(int IntNum)
501 {
502          int    i;
503         Uint8   byte;
504         for( i = 0; i < giNe2k_CardCount; i++ )
505         {
506                 if(gpNe2k_Cards[i].IRQ == IntNum)
507                 {
508                         byte = inb( gpNe2k_Cards[i].IOBase + ISR );
509                         
510                         // 0: Packet recieved (no error)
511                         if( byte & 1 )
512                         {
513                                 //if( gpNe2k_Cards[i].NumWaitingPackets > MAX_PACKET_QUEUE )
514                                 //      gpNe2k_Cards[i].NumWaitingPackets = MAX_PACKET_QUEUE;
515                                 Semaphore_Signal( &gpNe2k_Cards[i].Semaphore, 1 );
516                         }
517                         // 1: Packet sent (no error)
518                         // 2: Recieved with error
519                         // 3: Transmission Halted (Excessive Collisions)
520                         // 4: Recieve Buffer Exhausted
521                         // 5: 
522                         // 6: Remote DMA Complete
523                         // 7: Reset
524                         //LOG("Clearing interrupts on card %i (was 0x%x)", i, byte);
525                         outb( gpNe2k_Cards[i].IOBase + ISR, 0xFF );     // Reset All
526                         return ;
527                 }
528         }
529         Log_Warning("Ne2k", "Recieved Unknown IRQ %i", IntNum);
530 }

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