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

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