Modules/E1000 - "handle" RXDMT0 by just logging
[tpg/acess2.git] / KernelLand / Modules / Network / E1000 / e1000.c
1 /*
2  * Acess2 E1000 Network Driver
3  * - By John Hodge (thePowersGang)
4  *
5  * e1000.c
6  * - Intel 8254x Network Card Driver (core)
7  */
8 #define DEBUG   0
9 #define VERSION VER2(0,1)
10 #include <acess.h>
11 #include "e1000.h"
12 #include <modules.h>
13 #include <drv_pci.h>
14 #include <IPStack/include/adapters_api.h>
15 #include <timers.h>     // Time_Delay
16
17 const struct sSupportedCard {
18         Uint16  Vendor, Device;
19 } caSupportedCards[] = {
20         {0x8086, 0x100E},       // 82540EM-A Desktop
21         {0x8086, 0x1010},       // 82546EB-A1 Copper Dual Port
22         {0x8086, 0x1012},       // 82546EB-A1 Fiber
23         {0x8086, 0x1019},       // 82547[EG]I Copper
24         {0x8086, 0x101A},       // 82547EI Mobile
25         {0x8086, 0x101D},       // 82546EB-A1 Copper Quad Port
26 };
27 const int ciNumSupportedCards = sizeof(caSupportedCards)/sizeof(caSupportedCards[0]);
28
29 // === PROTOTYPES ===
30  int    E1000_Install(char **Arguments);
31  int    E1000_Cleanup(void);
32 tIPStackBuffer  *E1000_WaitForPacket(void *Ptr);
33  int    E1000_SendPacket(void *Ptr, tIPStackBuffer *Buffer);
34 void    E1000_IRQHandler(int Num, void *Ptr);
35  int    E1000_int_InitialiseCard(tCard *Card);
36 Uint16  E1000_int_ReadEEPROM(tCard *Card, Uint8 WordIdx);
37
38 // === GLOBALS ===
39 MODULE_DEFINE(0, VERSION, E1000, E1000_Install, E1000_Cleanup, NULL);
40 tIPStack_AdapterType    gE1000_AdapterType = {
41         .Name = "E1000",
42         .Type = ADAPTERTYPE_ETHERNET_1G,        // TODO: Differentiate differnet wire protos and speeds
43         .Flags = ADAPTERFLAG_OFFLOAD_MAC,       // TODO: IP/TCP/UDP checksum offloading
44         .SendPacket = E1000_SendPacket,
45         .WaitForPacket = E1000_WaitForPacket
46         };
47 tCard   *gaE1000_Cards;
48
49 // === CODE ===
50 int E1000_Install(char **Arguments)
51 {
52          int    card_count = 0;
53         for( int modelidx = 0; modelidx < ciNumSupportedCards; modelidx ++ )
54         {
55                 const struct sSupportedCard     *cardtype = &caSupportedCards[modelidx];
56                 card_count += PCI_CountDevices(cardtype->Vendor, cardtype->Device);
57         }
58         LOG("card_count = %i", card_count);
59         if( card_count == 0 ) {
60                 LOG("Zero cards located");
61                 return MODULE_ERR_NOTNEEDED;
62         }
63
64         // Allocate card array
65         gaE1000_Cards = calloc(sizeof(tCard), card_count);
66         if( !gaE1000_Cards ) {
67                 return MODULE_ERR_MALLOC;
68         }       
69
70         // Initialise cards
71         int card_idx = 0;
72         for( int modelidx = 0; modelidx < ciNumSupportedCards; modelidx ++ )
73         {
74                 const struct sSupportedCard     *cardtype = &caSupportedCards[modelidx];
75                 for( int id = -1, i = 0; (id = PCI_GetDevice(cardtype->Vendor, cardtype->Device, i)) != -1; i ++ )
76                 {
77                         tCard   *card = &gaE1000_Cards[card_idx++];
78                         card->MMIOBasePhys = PCI_GetValidBAR(id, 0, PCI_BARTYPE_MEMNP);
79                         if( !card->MMIOBasePhys ) {
80                                 Log_Warning("E1000", "Dev %i: BAR0 should be non-prefetchable memory", id);
81                                 continue;
82                         }
83
84                         card->IRQ = PCI_GetIRQ(id);
85                         IRQ_AddHandler(card->IRQ, E1000_IRQHandler, card);
86                         PCI_SetCommand(id, PCI_CMD_MEMENABLE|PCI_CMD_BUSMASTER, 0);
87                 
88                         Log_Debug("E1000", "Card %i: %P IRQ %i", card_idx, card->MMIOBasePhys, card->IRQ);
89
90                         if( E1000_int_InitialiseCard(card) ) {
91                                 return MODULE_ERR_MALLOC;
92                         }
93                         
94                         card->IPStackHandle = IPStack_Adapter_Add(&gE1000_AdapterType, card, card->MacAddr);
95                 }
96         }
97         return MODULE_ERR_OK;
98 }
99
100 int E1000_Cleanup(void)
101 {
102         return 0;
103 }
104
105 void E1000_int_ReleaseRXD(void *Arg, size_t HeadLen, size_t FootLen, const void *Data)
106 {
107         tCard   **cardptr = Arg;
108         tCard   *Card = *cardptr;
109          int    rxd = (Arg - (void*)Card->RXBackHandles) / sizeof(void*);
110
111         LOG("RXD %p %i being released", Card, rxd);
112         ASSERT(rxd >= 0 && rxd < NUM_RX_DESC);
113
114         Card->RXDescs[rxd].Status = 0;
115         Mutex_Acquire(&Card->lRXDescs);
116         if( rxd == REG32(Card, REG_RDT) ) {
117                 while( rxd != Card->FirstUnseenRXD && !(Card->RXDescs[rxd].Status & RXD_STS_DD) ) {
118                         rxd ++;
119                         if( rxd == NUM_RX_DESC )
120                                 rxd = 0;
121                 }
122                 REG32(Card, REG_RDT) = rxd;
123                 LOG("Updated RDT=%i", rxd);
124         }
125         Mutex_Release(&Card->lRXDescs);
126 }
127
128 tIPStackBuffer *E1000_WaitForPacket(void *Ptr)
129 {
130         tCard   *Card = Ptr;
131         
132         if( Semaphore_Wait(&Card->AvailPackets, 1) != 1 )
133                 return NULL;
134         
135         ENTER("pPtr", Ptr);
136
137         Mutex_Acquire(&Card->lRXDescs);
138          int    first_rxd = Card->FirstUnseenRXD;
139          int    last_rxd = first_rxd;
140          int    nDesc = 1;
141         while( last_rxd != Card->LastUnseenRXD  ) {
142                 if( !(Card->RXDescs[last_rxd].Status & RXD_STS_DD) )
143                         break;  // Oops, should ahve found an EOP first
144                 if( Card->RXDescs[last_rxd].Status & RXD_STS_EOP )
145                         break;
146                 nDesc ++;
147                 last_rxd = (last_rxd + 1) % NUM_RX_DESC;
148         }
149         Card->FirstUnseenRXD = (last_rxd + 1) % NUM_RX_DESC;
150         Mutex_Release(&Card->lRXDescs);
151
152         LOG("nDesc = %i, first_rxd = %i", nDesc, first_rxd);
153         tIPStackBuffer *ret = IPStack_Buffer_CreateBuffer(nDesc);
154          int    rxd = first_rxd;
155         for( int i = 0; i < nDesc; i ++ )
156         {
157                 IPStack_Buffer_AppendSubBuffer(ret, 0, Card->RXDescs[rxd].Length, Card->RXBuffers[rxd],
158                         E1000_int_ReleaseRXD, &Card->RXBackHandles[rxd]);
159         }
160
161         LEAVE('p', ret);
162         return ret;
163 }
164
165 int E1000_SendPacket(void *Ptr, tIPStackBuffer *Buffer)
166 {
167         tCard   *Card = Ptr;
168
169         ENTER("pPtr pBuffer", Ptr, Buffer);
170
171          int    nDesc = 0;
172         size_t  len;
173         const void      *ptr;
174         // Count sub-buffers (including splitting cross-page entries)
175          int    idx = -1;
176         while( (idx = IPStack_Buffer_GetBuffer(Buffer, idx, &len, &ptr)) != -1 )
177         {
178                 if( len > PAGE_SIZE ) {
179                         LOG("len=%i > PAGE_SIZE", len);
180                         LEAVE('i', EINVAL);
181                         return EINVAL;
182                 }
183                 if( MM_GetPhysAddr(ptr) + len-1 != MM_GetPhysAddr((char*)ptr + len-1) ) {
184                         LOG("Buffer %p+%i spans non-contig physical pages", ptr, len);
185                         nDesc ++;
186                 }
187                 nDesc ++;
188         }
189         
190         // Request set of TX descriptors
191         int rv = Semaphore_Wait(&Card->FreeTxDescs, nDesc);
192         if(rv != nDesc) {
193                 LEAVE('i', EINTR);
194                 return EINTR;
195         }
196         Mutex_Acquire(&Card->lTXDescs);
197          int    first_txd = Card->FirstFreeTXD;
198         Card->FirstFreeTXD = (first_txd + nDesc) % NUM_TX_DESC;
199          int    last_txd = (first_txd + nDesc-1) % NUM_TX_DESC;
200
201         LOG("first_txd = %i, last_txd = %i", first_txd, last_txd);
202
203         // Populate buffers
204         idx = -1;
205          int txd = first_txd;
206         while( (idx = IPStack_Buffer_GetBuffer(Buffer, idx, &len, &ptr)) != -1 )
207         {
208                 if( MM_GetPhysAddr(ptr) + len-1 != MM_GetPhysAddr((char*)ptr + len-1) )
209                 {
210                         size_t  remlen = PAGE_SIZE - ((tVAddr)ptr & (PAGE_SIZE-1));
211                         // Split in two
212                         // - First Page
213                         Card->TXDescs[txd].Buffer = MM_GetPhysAddr(ptr);
214                         Card->TXDescs[txd].Length = remlen;
215                         Card->TXDescs[txd].CMD = TXD_CMD_RS;
216                         txd = (txd + 1) % NUM_TX_DESC;
217                         // - Second page
218                         Card->TXDescs[txd].Buffer = MM_GetPhysAddr((char*)ptr + remlen);
219                         Card->TXDescs[txd].Length = len - remlen;
220                         Card->TXDescs[txd].CMD = TXD_CMD_RS;
221                 }
222                 else
223                 {
224                         // Single
225                         volatile tTXDesc *txdp = &Card->TXDescs[txd];
226                         txdp->Buffer = MM_GetPhysAddr(ptr);
227                         txdp->Length = len;
228                         txdp->CMD = TXD_CMD_RS;
229                         LOG("%P: %llx %x %x", MM_GetPhysAddr((void*)txdp), txdp->Buffer, txdp->Length, txdp->CMD);
230                 }
231                 txd = (txd + 1) % NUM_TX_DESC;
232         }
233         Card->TXDescs[last_txd].CMD |= TXD_CMD_EOP|TXD_CMD_IDE|TXD_CMD_IFCS;
234         Card->TXSrcBuffers[last_txd] = Buffer;
235
236         __sync_synchronize();
237         #if DEBUG
238         {
239                 volatile tTXDesc *txdp = Card->TXDescs + last_txd;
240                 LOG("%p %P: %llx %x %x", txdp, MM_GetPhysAddr((void*)txdp), txdp->Buffer, txdp->Length, txdp->CMD);
241                 volatile tTXDesc *txdp_base = MM_MapTemp(MM_GetPhysAddr((void*)Card->TXDescs));
242                 txdp = txdp_base + last_txd;
243                 LOG("%p %P: %llx %x %x", txdp, MM_GetPhysAddr((void*)txdp), txdp->Buffer, txdp->Length, txdp->CMD);
244                 MM_FreeTemp( (void*)txdp_base);
245         }
246         #endif
247         // Trigger TX
248         IPStack_Buffer_LockBuffer(Buffer);
249         LOG("Triggering TX - Buffers[%i]=%p", last_txd, Buffer);
250         REG32(Card, REG_TDT) = Card->FirstFreeTXD;
251         Mutex_Release(&Card->lTXDescs);
252         LOG("Waiting for TX to complete");
253         
254         // Wait for completion (lock will block, then release straight away)
255         IPStack_Buffer_LockBuffer(Buffer);
256         IPStack_Buffer_UnlockBuffer(Buffer);
257
258         // TODO: Check status bits
259
260         LEAVE('i', 0);
261         return 0;
262 }
263
264 void E1000_IRQHandler(int Num, void *Ptr)
265 {
266         tCard   *Card = Ptr;
267         
268         Uint32  icr = REG32(Card, REG_ICR);
269         if( icr == 0 )
270                 return ;
271         LOG("icr = %x", icr);
272
273         // Transmit descriptor written
274         if( (icr & ICR_TXDW) || (icr & ICR_TXQE) )
275         {
276                  int    nReleased = 0;
277                  int    txd = Card->LastFreeTXD;
278                  int    nReleasedAtLastDD = 0;
279                  int    idxOfLastDD = txd;
280                 // Walk descriptors looking for the first non-complete descriptor
281                 LOG("TX %i:%i", Card->LastFreeTXD, Card->FirstFreeTXD);
282                 while( txd != Card->FirstFreeTXD )
283                 {
284                         nReleased ++;
285                         if(Card->TXDescs[txd].Status & TXD_STS_DD) {
286                                 nReleasedAtLastDD = nReleased;
287                                 idxOfLastDD = txd;
288                         }
289                         txd ++;
290                         if(txd == NUM_TX_DESC)
291                                 txd = 0;
292                 }
293                 if( nReleasedAtLastDD )
294                 {
295                         // Unlock buffers
296                         txd = Card->LastFreeTXD;
297                         LOG("TX unlocking range %i-%i", txd, idxOfLastDD);
298                         while( txd != (idxOfLastDD+1)%NUM_TX_DESC )
299                         {
300                                 if( Card->TXSrcBuffers[txd] ) {
301                                         LOG("- Unlocking %i:%p", txd, Card->TXSrcBuffers[txd]);
302                                         IPStack_Buffer_UnlockBuffer( Card->TXSrcBuffers[txd] );
303                                         Card->TXSrcBuffers[txd] = NULL;
304                                 }
305                                 txd ++;
306                                 if(txd == NUM_TX_DESC)
307                                         txd = 0;
308                         }
309                         // Update last free
310                         Card->LastFreeTXD = txd;
311                         Semaphore_Signal(&Card->FreeTxDescs, nReleasedAtLastDD);
312                         LOG("nReleased = %i", nReleasedAtLastDD);
313                 }
314                 else
315                 {
316                         LOG("No completed TXDs");
317                 }
318         }       
319
320         if( icr & ICR_LSC )
321         {
322                 // Link status change
323                 LOG("LSC");
324                 // TODO: Detect link drop/raise and poke IPStack
325         }
326
327         if( icr & ICR_RXO )
328         {
329                 LOG("RX Overrun");
330         }
331         
332         // Pending packet (s)
333         if( icr & ICR_RXT0 )
334         {
335                  int    nPackets = 0;
336                 LOG("RX %i:%i", Card->LastUnseenRXD, Card->FirstUnseenRXD);
337                 while( (Card->RXDescs[Card->LastUnseenRXD].Status & RXD_STS_DD) )
338                 {
339                         if( Card->RXDescs[Card->LastUnseenRXD].Status & RXD_STS_EOP )
340                                 nPackets ++;
341                         Card->LastUnseenRXD ++;
342                         if( Card->LastUnseenRXD == NUM_RX_DESC )
343                                 Card->LastUnseenRXD = 0;
344                         
345                         if( Card->LastUnseenRXD == Card->FirstUnseenRXD )
346                                 break;
347                 }
348                 Semaphore_Signal(&Card->AvailPackets, nPackets);
349                 LOG("nPackets = %i", nPackets);
350         }
351         
352         // Transmit Descriptor Low Threshold hit
353         if( icr & ICR_TXD_LOW )
354         {
355                 
356         }
357
358         // Receive Descriptor Minimum Threshold Reached
359         // - We're reading too slow
360         if( icr & ICR_RXDMT0 )
361         {
362                 LOG("RX descs running out");
363         }
364         
365         icr &= ~(ICR_RXT0|ICR_LSC|ICR_TXQE|ICR_TXDW|ICR_TXD_LOW|ICR_RXDMT0);
366         if( icr )
367                 Log_Warning("E1000", "Unhandled ICR bits 0x%x", icr);
368 }
369
370 // TODO: Move this function into Kernel/drvutil.c
371 /**
372  * \brief Allocate a set of buffers in hardware mapped space
373  * 
374  * Allocates \a NumBufs buffers using shared pages (if \a BufSize is less than a page) or
375  * as a set of contiugious allocations.
376  */
377 int DrvUtil_AllocBuffers(void **Buffers, int NumBufs, int PhysBits, size_t BufSize)
378 {
379         if( BufSize >= PAGE_SIZE )
380         {
381                 const int       pages_per_buf = BufSize / PAGE_SIZE;
382                 ASSERT(pages_per_buf * PAGE_SIZE == BufSize);
383                 for( int i = 0; i < NumBufs; i ++ ) {
384                         Buffers[i] = (void*)MM_AllocDMA(pages_per_buf, PhysBits, NULL);
385                         if( !Buffers[i] )       return 1;
386                 }
387         }
388         else
389         {
390                 size_t  ofs = 0;
391                 const int       bufs_per_page = PAGE_SIZE / BufSize;
392                 ASSERT(bufs_per_page * BufSize == PAGE_SIZE);
393                 void    *page = NULL;
394                 for( int i = 0; i < NumBufs; i ++ )
395                 {
396                         if( ofs == 0 ) {
397                                 page = (void*)MM_AllocDMA(1, PhysBits, NULL);
398                                 if( !page )     return 1;
399                         }
400                         Buffers[i] = (char*)page + ofs;
401                         ofs += BufSize;
402                         if( ofs >= PAGE_SIZE )
403                                 ofs = 0;
404                 }
405         }
406         return 0;
407 }
408
409 int E1000_int_InitialiseCard(tCard *Card)
410 {
411         ENTER("pCard", Card);
412         
413         // Map required structures
414         Card->MMIOBase = (void*)MM_MapHWPages( Card->MMIOBasePhys, 7 );
415         if( !Card->MMIOBase ) {
416                 Log_Error("E1000", "%p: Failed to map MMIO Space (7 pages)", Card);
417                 LEAVE('i', 1);
418                 return 1;
419         }
420
421         // --- Read MAC address from EEPROM ---
422         {
423                 Uint16  macword;
424                 macword = E1000_int_ReadEEPROM(Card, 0);
425                 Card->MacAddr[0] = macword & 0xFF;
426                 Card->MacAddr[1] = macword >> 8;
427                 macword = E1000_int_ReadEEPROM(Card, 1);
428                 Card->MacAddr[2] = macword & 0xFF;
429                 Card->MacAddr[3] = macword >> 8;
430                 macword = E1000_int_ReadEEPROM(Card, 2);
431                 Card->MacAddr[4] = macword & 0xFF;
432                 Card->MacAddr[5] = macword >> 8;
433         }
434         Log_Log("E1000", "%p: MAC Address %02x:%02x:%02x:%02x:%02x:%02x",
435                 Card,
436                 Card->MacAddr[0], Card->MacAddr[1],
437                 Card->MacAddr[2], Card->MacAddr[3],
438                 Card->MacAddr[4], Card->MacAddr[5]);
439         
440         // --- Prepare for RX ---
441         LOG("RX Preparation");
442         Card->RXDescs = (void*)MM_AllocDMA(1, 64, NULL);
443         if( !Card->RXDescs ) {
444                 LEAVE('i', 2);
445                 return 2;
446         }
447         if( DrvUtil_AllocBuffers(Card->RXBuffers, NUM_RX_DESC, 64, RX_DESC_BSIZE) ) {
448                 LEAVE('i', 3);
449                 return 3;
450         }
451         for( int i = 0; i < NUM_RX_DESC; i ++ )
452         {
453                 Card->RXDescs[i].Buffer = MM_GetPhysAddr(Card->RXBuffers[i]);
454                 Card->RXDescs[i].Status = 0;    // Clear RXD_STS_DD, gives it to the card
455                 Card->RXBackHandles[i] = Card;
456         }
457         
458         REG64(Card, REG_RDBAL) = MM_GetPhysAddr((void*)Card->RXDescs);
459         REG32(Card, REG_RDLEN) = NUM_RX_DESC * 16;
460         REG32(Card, REG_RDH) = 0;
461         REG32(Card, REG_RDT) = NUM_RX_DESC;
462         // Hardware size, Multicast promisc, Accept broadcast, Interrupt at 1/4 Rx descs free
463         REG32(Card, REG_RCTL) = RX_DESC_BSIZEHW | RCTL_MPE | RCTL_BAM | RCTL_RDMTS_1_4;
464         Card->FirstUnseenRXD = 0;
465         Card->LastUnseenRXD = 0;
466
467         // --- Prepare for TX ---
468         LOG("TX Preparation");
469         Card->TXDescs = (void*)MM_AllocDMA(1, 64, NULL);
470         if( !Card->RXDescs ) {
471                 LEAVE('i', 4);
472                 return 4;
473         }
474         LOG("Card->RXDescs = %p [%P]", Card->TXDescs, MM_GetPhysAddr((void*)Card->TXDescs));
475         for( int i = 0; i < NUM_TX_DESC; i ++ )
476         {
477                 Card->TXDescs[i].Buffer = 0;
478                 Card->TXDescs[i].CMD = 0;
479         }
480         REG64(Card, REG_TDBAL) = MM_GetPhysAddr((void*)Card->TXDescs);
481         REG32(Card, REG_TDLEN) = NUM_TX_DESC * 16;
482         REG32(Card, REG_TDH) = 0;
483         REG32(Card, REG_TDT) = 0;
484         // Enable, pad short packets
485         REG32(Card, REG_TCTL) = TCTL_EN | TCTL_PSP | (0x0F << TCTL_CT_ofs) | (0x40 << TCTL_COLD_ofs);
486         Card->FirstFreeTXD = 0;
487
488         // -- Prepare Semaphores
489         Semaphore_Init(&Card->FreeTxDescs, NUM_TX_DESC, NUM_TX_DESC, "E1000", "TXDescs");
490         Semaphore_Init(&Card->AvailPackets, 0, NUM_RX_DESC, "E1000", "RXDescs");
491
492         // --- Prepare for full operation ---
493         LOG("Starting card");
494         REG32(Card, REG_CTRL) = CTRL_SLU|CTRL_ASDE;     // Link up, auto speed detection
495         REG32(Card, REG_IMS) = 0x1F6DC; // Interrupt mask
496         (void)REG32(Card, REG_ICR);     // Discard pending interrupts
497         REG32(Card, REG_RCTL) |= RCTL_EN;
498         LEAVE('i', 0);
499         return 0;
500 }
501
502 Uint16 E1000_int_ReadEEPROM(tCard *Card, Uint8 WordIdx)
503 {
504         REG32(Card, REG_EERD) = ((Uint32)WordIdx << 8) | 1;
505         Uint32  tmp;
506         while( !((tmp = REG32(Card, REG_EERD)) & (1 << 4)) ) {
507                 // TODO: use something like Time_MicroDelay instead
508                 Time_Delay(1);
509         }
510         
511         return tmp >> 16;
512 }

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