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

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