Fixed compile errors, added Semaphore code
[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
14 // === CONSTANTS ===
15 #define MEM_START       0x40
16 #define MEM_END         0xC0
17 #define RX_FIRST        (MEM_START)
18 #define RX_LAST         (MEM_START+RX_BUF_SIZE-1)
19 #define RX_BUF_SIZE     0x40
20 #define TX_FIRST        (MEM_START+RX_BUF_SIZE)
21 #define TX_LAST         (MEM_END)
22 #define TX_BUF_SIZE     0x40
23 #define MAX_PACKET_QUEUE        10
24
25 static const struct {
26         Uint16  Vendor;
27         Uint16  Device;
28 } csaCOMPAT_DEVICES[] = {
29         {0x10EC, 0x8029},       // Realtek 8029
30         {0x10EC, 0x8129}        // Realtek 8129
31 };
32 #define NUM_COMPAT_DEVICES      ((int)(sizeof(csaCOMPAT_DEVICES)/sizeof(csaCOMPAT_DEVICES[0])))
33
34 enum eNe2k_Page0Read {
35         CMD = 0,        //!< the master command register
36         CLDA0,          //!< Current Local DMA Address 0
37         CLDA1,          //!< Current Local DMA Address 1
38         BNRY,           //!< Boundary Pointer (for ringbuffer)
39         TSR,            //!< Transmit Status Register
40         NCR,            //!< collisions counter
41         FIFO,           //!< (for what purpose ??)
42         ISR,            //!< Interrupt Status Register
43         CRDA0,          //!< Current Remote DMA Address 0
44         CRDA1,          //!< Current Remote DMA Address 1
45         RSR = 0xC       //!< Receive Status Register
46 };
47
48 enum eNe2k_Page0Write {
49         PSTART = 1,     //!< page start (init only)
50         PSTOP,          //!< page stop  (init only)
51         TPSR = 4,       //!< transmit page start address
52         TBCR0,          //!< transmit byte count (low)
53         TBCR1,          //!< transmit byte count (high)
54         RSAR0 = 8,      //!< remote start address (lo)
55         RSAR1,  //!< remote start address (hi)
56         RBCR0,  //!< remote byte count (lo)
57         RBCR1,  //!< remote byte count (hi)
58         RCR,    //!< receive config register
59         TCR,    //!< transmit config register
60         DCR,    //!< data config register    (init)
61         IMR             //!< interrupt mask register (init)
62 };
63
64 enum eNe2k_Page1Read {
65         CURR = 7        //!< current page
66 };
67
68 // === TYPES ===
69 typedef struct sNe2k_Card {
70         Uint16  IOBase; //!< IO Port Address from PCI
71         Uint8   IRQ;    //!< IRQ Assigned from PCI
72         
73          int    NumWaitingPackets;
74          int    NextRXPage;
75         
76          int    NextMemPage;    //!< Next Card Memory page to use
77         
78         Uint8   Buffer[RX_BUF_SIZE*256];
79         
80         char    Name[2];        // "0"
81         tVFS_Node       Node;
82         Uint8   MacAddr[6];
83 } tCard;
84
85 // === PROTOTYPES ===
86  int    Ne2k_Install(char **Arguments);
87 char    *Ne2k_ReadDir(tVFS_Node *Node, int Pos);
88 tVFS_Node       *Ne2k_FindDir(tVFS_Node *Node, const char *Name);
89  int    Ne2k_IOCtl(tVFS_Node *Node, int ID, void *Data);
90 Uint64  Ne2k_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
91 Uint64  Ne2k_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
92 Uint8   Ne2k_int_GetWritePage(tCard *Card, Uint16 Length);
93 void    Ne2k_IRQHandler(int IntNum);
94
95 // === GLOBALS ===
96 MODULE_DEFINE(0, VERSION, Ne2k, Ne2k_Install, NULL, NULL);
97 tDevFS_Driver   gNe2k_DriverInfo = {
98         NULL, "ne2k",
99         {
100         .NumACLs = 1,
101         .ACLs = &gVFS_ACL_EveryoneRX,
102         .Flags = VFS_FFLAG_DIRECTORY,
103         .ReadDir = Ne2k_ReadDir,
104         .FindDir = Ne2k_FindDir,
105         .IOCtl = Ne2k_IOCtl
106         }
107 };
108 Uint16  gNe2k_BaseAddress;
109  int    giNe2k_CardCount = 0;
110 tCard   *gpNe2k_Cards = NULL;
111
112 // === CODE ===
113 /**
114  * \fn int Ne2k_Install(char **Options)
115  * \brief Installs the NE2000 Driver
116  */
117 int Ne2k_Install(char **Options)
118 {
119          int    i, j, k;
120          int    count, id, base;
121         
122         // --- Scan PCI Bus ---
123         // Count Cards
124         giNe2k_CardCount = 0;
125         for( i = 0; i < NUM_COMPAT_DEVICES; i ++ )
126         {
127                 giNe2k_CardCount += PCI_CountDevices( csaCOMPAT_DEVICES[i].Vendor, csaCOMPAT_DEVICES[i].Device, 0 );
128         }
129         
130         if( giNe2k_CardCount == 0 ) {
131                 Log_Warning("Ne2k", "No cards detected");
132                 return MODULE_ERR_NOTNEEDED;
133         }
134         
135         // Enumerate Cards
136         k = 0;
137         gpNe2k_Cards = calloc( giNe2k_CardCount, sizeof(tCard) );
138         
139         for( i = 0; i < NUM_COMPAT_DEVICES; i ++ )
140         {
141                 count = PCI_CountDevices( csaCOMPAT_DEVICES[i].Vendor, csaCOMPAT_DEVICES[i].Device, 0 );
142                 for( j = 0; j < count; j ++,k ++ )
143                 {
144                         id = PCI_GetDevice( csaCOMPAT_DEVICES[i].Vendor, csaCOMPAT_DEVICES[i].Device, 0, j );
145                         // Create Structure
146                         base = PCI_AssignPort( id, 0, 0x20 );
147                         gpNe2k_Cards[ k ].IOBase = base;
148                         gpNe2k_Cards[ k ].IRQ = PCI_GetIRQ( id );
149                         gpNe2k_Cards[ k ].NextMemPage = 64;
150                         gpNe2k_Cards[ k ].NextRXPage = RX_FIRST;
151                         
152                         // Install IRQ Handler
153                         IRQ_AddHandler(gpNe2k_Cards[ k ].IRQ, Ne2k_IRQHandler);
154                         
155                         // Reset Card
156                         outb( base + 0x1F, inb(base + 0x1F) );
157                         while( (inb( base+ISR ) & 0x80) == 0 );
158                         outb( base + ISR, 0x80 );
159                         
160                         // Initialise Card
161                         outb( base + CMD, 0x40|0x21 );  // Page 1, No DMA, Stop
162                         outb( base + CURR, RX_FIRST );  // Current RX page
163                         outb( base + CMD, 0x21 );       // No DMA and Stop
164                         outb( base + DCR, 0x49 );       // Set WORD mode
165                         outb( base + IMR, 0x00 );       // Interrupt Mask Register
166                         outb( base + ISR, 0xFF );
167                         outb( base + RCR, 0x20 );       // Reciever to Monitor
168                         outb( base + TCR, 0x02 );       // Transmitter OFF (TCR.LB = 1, Internal Loopback)
169                         outb( base + RBCR0, 6*4 );      // Remote Byte Count
170                         outb( base + RBCR1, 0 );
171                         outb( base + RSAR0, 0 );        // Clear Source Address
172                         outb( base + RSAR1, 0 );
173                         outb( base + CMD, 0x0A );       // Remote Read, Start
174                         
175                         // Read MAC Address
176                         gpNe2k_Cards[ k ].MacAddr[0] = inb(base+0x10);//        inb(base+0x10);
177                         gpNe2k_Cards[ k ].MacAddr[1] = inb(base+0x10);//        inb(base+0x10);
178                         gpNe2k_Cards[ k ].MacAddr[2] = inb(base+0x10);//        inb(base+0x10);
179                         gpNe2k_Cards[ k ].MacAddr[3] = inb(base+0x10);//        inb(base+0x10);
180                         gpNe2k_Cards[ k ].MacAddr[4] = inb(base+0x10);//        inb(base+0x10);
181                         gpNe2k_Cards[ k ].MacAddr[5] = inb(base+0x10);//        inb(base+0x10);
182                         
183                         outb( base+PSTART, RX_FIRST);   // Set Receive Start
184                         outb( base+BNRY, RX_LAST-1);    // Set Boundary Page
185                         outb( base+PSTOP, RX_LAST);     // Set Stop Page
186                         outb( base+ISR, 0xFF ); // Clear all ints
187                         outb( base+CMD, 0x22 ); // No DMA, Start
188                         outb( base+IMR, 0x3F ); // Set Interupt Mask
189                         outb( base+RCR, 0x0F ); // Set WRAP and allow all packet matches
190                         outb( base+TCR, 0x00 ); // Set Normal Transmitter mode
191                         outb( base+TPSR, 0x40); // Set Transmit Start
192                         // Set MAC Address
193                         /*
194                         Ne2k_WriteReg(base, MAC0, gpNe2k_Cards[ k ].MacAddr[0]);
195                         Ne2k_WriteReg(base, MAC1, gpNe2k_Cards[ k ].MacAddr[1]);
196                         Ne2k_WriteReg(base, MAC2, gpNe2k_Cards[ k ].MacAddr[2]);
197                         Ne2k_WriteReg(base, MAC3, gpNe2k_Cards[ k ].MacAddr[3]);
198                         Ne2k_WriteReg(base, MAC4, gpNe2k_Cards[ k ].MacAddr[4]);
199                         Ne2k_WriteReg(base, MAC5, gpNe2k_Cards[ k ].MacAddr[5]);
200                         */
201                         
202                         Log_Log("Ne2k", "Card %i 0x%04x IRQ%i %02x:%02x:%02x:%02x:%02x:%02x",
203                                 k, base, gpNe2k_Cards[ k ].IRQ,
204                                 gpNe2k_Cards[k].MacAddr[0], gpNe2k_Cards[k].MacAddr[1],
205                                 gpNe2k_Cards[k].MacAddr[2], gpNe2k_Cards[k].MacAddr[3],
206                                 gpNe2k_Cards[k].MacAddr[4], gpNe2k_Cards[k].MacAddr[5]
207                                 );
208                         
209                         // Set VFS Node
210                         gpNe2k_Cards[ k ].Name[0] = '0'+k;
211                         gpNe2k_Cards[ k ].Name[1] = '\0';
212                         gpNe2k_Cards[ k ].Node.ImplPtr = &gpNe2k_Cards[ k ];
213                         gpNe2k_Cards[ k ].Node.NumACLs = 0;     // Root Only
214                         gpNe2k_Cards[ k ].Node.CTime = now();
215                         gpNe2k_Cards[ k ].Node.Write = Ne2k_Write;
216                         gpNe2k_Cards[ k ].Node.Read = Ne2k_Read;
217                         gpNe2k_Cards[ k ].Node.IOCtl = Ne2k_IOCtl;
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, void *Buffer)
285  * \brief Send a packet from the network card
286  */
287 Uint64 Ne2k_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
288 {
289         tCard   *Card = (tCard*)Node->ImplPtr;
290         Uint16  *buf = Buffer;
291          int    rem = Length;
292          int    page;
293         
294         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
295         
296         // Sanity Check Length
297         if(Length > TX_BUF_SIZE*256) {
298                 Log_Warning(
299                         "Ne2k",
300                         "Ne2k_Write - Attempting to send over TX_BUF_SIZE*256 (%i) bytes (%i)",
301                         TX_BUF_SIZE*256, Length
302                         );
303                 LEAVE('i', 0);
304                 return 0;
305         }
306         
307         // Make sure that the card is in page 0
308         outb(Card->IOBase + CMD, 0|0x22);       // Page 0, Start, NoDMA
309         
310         // Clear Remote DMA Flag
311         outb(Card->IOBase + ISR, 0x40); // Bit 6
312         
313         // Send Size - Remote Byte Count Register
314         outb(Card->IOBase + TBCR0, Length & 0xFF);
315         outb(Card->IOBase + TBCR1, Length >> 8);
316         
317         // Send Size - Remote Byte Count Register
318         outb(Card->IOBase + RBCR0, Length & 0xFF);
319         outb(Card->IOBase + RBCR1, Length >> 8);
320         
321         // Set up transfer
322         outb(Card->IOBase + RSAR0, 0x00);       // Page Offset
323         page = Ne2k_int_GetWritePage(Card, Length);
324         outb(Card->IOBase + RSAR1, page);       // Page Offset
325         // Start
326         //outb(Card->IOBase + CMD, 0|0x18|0x4|0x2);     // Page 0, Transmit Packet, TXP, Start
327         outb(Card->IOBase + CMD, 0|0x10|0x2);   // Page 0, Remote Write, Start
328         
329         // Send Data
330         for(rem = Length; rem > 0; rem -= 2) {
331                 outw(Card->IOBase + 0x10, *buf++);
332         }
333         
334         while( inb(Card->IOBase + ISR) == 0 )   // Wait for Remote DMA Complete
335                 ;       //Proc_Yield();
336         
337         outb( Card->IOBase + ISR, 0x40 );       // ACK Interrupt
338         
339         // Send Packet
340         outb(Card->IOBase + TPSR, page);
341         outb(Card->IOBase + CMD, 0|0x10|0x4|0x2);
342         
343         // Complete DMA
344         //outb(Card->IOBase + CMD, 0|0x20);
345         
346         LEAVE('i', Length);
347         return Length;
348 }
349
350 /**
351  * \fn Uint64 Ne2k_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
352  * \brief Wait for and read a packet from the network card
353  */
354 Uint64 Ne2k_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
355 {
356         tCard   *Card = (tCard*)Node->ImplPtr;
357         Uint8   page;
358         Uint8   data[256];
359          int    i;
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         // TODO: Use MutexP/MutexV instead
369         while(Card->NumWaitingPackets == 0)     Threads_Yield();
370         
371         // Make sure that the card is in page 0
372         outb(Card->IOBase + CMD, 0|0x22);       // Page 0, Start, NoDMA
373         
374         // Get BOUNDARY
375         page = Card->NextRXPage;
376         
377         // Set up transfer
378         outb(Card->IOBase + RBCR0, 0);
379         outb(Card->IOBase + RBCR1, 1);  // 256-bytes
380         outb(Card->IOBase + RSAR0, 0x00);       // Page Offset
381         outb(Card->IOBase + RSAR1, page);       // Page Number
382         
383         outb(Card->IOBase + CMD, 0|0x08|0x2);   // Page 0, Remote Read, Start
384         
385         // Clear Remote DMA Flag
386         outb(Card->IOBase + ISR, 0x40); // Bit 6
387         
388         // Read data
389         for(i = 0; i < 128; i ++)
390                 ((Uint16*)data)[i] = inw(Card->IOBase + 0x10);
391         
392         pktHdr = (void*)data;
393         //Log("Ne2k_Read: Recieved packet (%i bytes)", pktHdr->Length);
394         
395         // Have we read all the required bytes yet?
396         if(pktHdr->Length < 256 - 4)
397         {
398                 if(Length > pktHdr->Length)
399                         Length = pktHdr->Length;
400                 memcpy(Buffer, &data[4], Length);
401                 page ++;
402                 if(page == RX_LAST+1)   page = RX_FIRST;
403         }
404         // No? oh damn, now we need to allocate a buffer
405         else {
406                  int    j = 256/2;
407                 char    *buf = malloc( (pktHdr->Length + 4 + 255) & ~255 );
408                 
409                 if(!buf) {
410                         LEAVE('i', -1);
411                         return -1;
412                 }
413                 
414                 memcpy(buf, data, 256);
415                 
416                 page ++;
417                 while(page != pktHdr->NextPacketPage)
418                 {
419                         if(page == RX_LAST+1)   page = RX_FIRST;
420                         
421                         outb(Card->IOBase + RBCR0, 0);
422                         outb(Card->IOBase + RBCR1, 1);  // 256-bytes
423                         outb(Card->IOBase + RSAR0, 0x00);       // Page Offset
424                         outb(Card->IOBase + RSAR1, page);       // Page Number
425                         outb(Card->IOBase + CMD, 0|0x08|0x2);   // Page 0, Remote Read, Start
426                         
427                         for(i = 0; i < 128; i ++)
428                                 ((Uint16*)buf)[j+i] = inw(Card->IOBase + 0x10);
429                         j += 128;
430                         page ++;
431                 }
432                 
433                 if(Length > pktHdr->Length)
434                         Length = pktHdr->Length;
435                 memcpy(Buffer, &buf[4], Length);
436         }
437         
438         // Write BNRY
439         if(page == RX_FIRST)
440                 outb( Card->IOBase + BNRY, RX_LAST );
441         else
442                 outb( Card->IOBase + BNRY, page-1 );
443         // Set next RX Page and decrement the waiting list
444         Card->NextRXPage = page;
445         Card->NumWaitingPackets --;
446         
447         LEAVE('i', Length);
448         return Length;
449 }
450
451 /**
452  * \fn Uint8 Ne2k_int_GetWritePage(tCard *Card, Uint16 Length)
453  */
454 Uint8 Ne2k_int_GetWritePage(tCard *Card, Uint16 Length)
455 {
456         Uint8   ret = Card->NextMemPage;
457         
458         Card->NextMemPage += (Length + 0xFF) >> 8;
459         if(Card->NextMemPage >= TX_LAST) {
460                 Card->NextMemPage -= TX_BUF_SIZE;
461         }
462         
463         return ret;
464 }
465
466 /**
467  * \fn void Ne2k_IRQHandler(int IntNum)
468  */
469 void Ne2k_IRQHandler(int IntNum)
470 {
471          int    i;
472         Uint8   byte;
473         for( i = 0; i < giNe2k_CardCount; i++ )
474         {
475                 if(gpNe2k_Cards[i].IRQ == IntNum)
476                 {
477                         byte = inb( gpNe2k_Cards[i].IOBase + ISR );
478                         
479                         // 0: Packet recieved (no error)
480                         if( byte & 1 )
481                         {
482                                 gpNe2k_Cards[i].NumWaitingPackets ++;
483                                 if( gpNe2k_Cards[i].NumWaitingPackets > MAX_PACKET_QUEUE )
484                                         gpNe2k_Cards[i].NumWaitingPackets = MAX_PACKET_QUEUE;
485                         }
486                         // 1: Packet sent (no error)
487                         // 2: Recieved with error
488                         // 3: Transmission Halted (Excessive Collisions)
489                         // 4: Recieve Buffer Exhausted
490                         // 5: 
491                         // 6: Remote DMA Complete
492                         // 7: Reset
493                         //LOG("Clearing interrupts on card %i (was 0x%x)\n", i, byte);
494                         outb( gpNe2k_Cards[i].IOBase + ISR, 0xFF );     // Reset All
495                         return ;
496                 }
497         }
498         Log_Warning("Ne2k", "Recieved Unknown IRQ %i", IntNum);
499 }

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