Kernel/timers - Cleaning up timer code... might have made more mess
[tpg/acess2.git] / KernelLand / Modules / USB / UHCI / uhci.c
1 /*
2  * Acess 2 USB Stack
3  * - By John Hodge (thePowersGang)
4  *
5  * Universal Host Controller Interface
6  */
7 #define DEBUG   0
8 #define VERSION VER2(0,5)
9 #include <acess.h>
10 #include <vfs.h>
11 #include <drv_pci.h>
12 #include <modules.h>
13 #include <usb_host.h>
14 #include "uhci.h"
15 #include <timers.h>
16
17 // === CONSTANTS ===
18 #define MAX_CONTROLLERS 4
19 #define NUM_TDs 1024
20
21 // === PROTOTYPES ===
22  int    UHCI_Initialise(char **Arguments);
23 void    UHCI_Cleanup();
24 tUHCI_TD        *UHCI_int_AllocateTD(tUHCI_Controller *Cont);
25 void    UHCI_int_AppendTD(tUHCI_Controller *Cont, tUHCI_TD *TD);
26 void    *UHCI_int_SendTransaction(tUHCI_Controller *Cont, int Addr, Uint8 Type, int bTgl, tUSBHostCb Cb, void *CbData, void *Buf, size_t Length);
27 void    *UHCI_DataIN(void *Ptr, int Dest, int DataTgl, tUSBHostCb Cb, void *CbData, void *Buf, size_t Length);
28 void    *UHCI_DataOUT(void *Ptr, int Dest, int DataTgl, tUSBHostCb Cb, void *CbData,  void *Buf, size_t Length);
29 void    *UHCI_SendSetup(void *Ptr, int Dest, int DataTgl, tUSBHostCb Cb, void *CbData, void *Buf, size_t Length);
30  int    UHCI_IsTransferComplete(void *Ptr, void *Handle);
31  int    UHCI_Int_InitHost(tUHCI_Controller *Host);
32 void    UHCI_CheckPortUpdate(void *Ptr);
33 void    UHCI_InterruptHandler(int IRQ, void *Ptr);
34 // 
35 static void     _OutByte(tUHCI_Controller *Host, int Reg, Uint8 Value);
36 static void     _OutWord(tUHCI_Controller *Host, int Reg, Uint16 Value);
37 static void     _OutDWord(tUHCI_Controller *Host, int Reg, Uint32 Value);
38 static Uint16   _InWord(tUHCI_Controller *Host, int Reg);
39
40 // === GLOBALS ===
41 MODULE_DEFINE(0, VERSION, USB_UHCI, UHCI_Initialise, NULL, "USB_Core", NULL);
42 tUHCI_TD        gaUHCI_TDPool[NUM_TDs];
43 tUHCI_Controller        gUHCI_Controllers[MAX_CONTROLLERS];
44 tUSBHostDef     gUHCI_HostDef = {
45         .SendIN = UHCI_DataIN,
46         .SendOUT = UHCI_DataOUT,
47         .SendSETUP = UHCI_SendSetup,
48         .IsOpComplete = UHCI_IsTransferComplete,
49         .CheckPorts = UHCI_CheckPortUpdate
50         };
51
52 // === CODE ===
53 /**
54  * \fn int UHCI_Initialise()
55  * \brief Called to initialise the UHCI Driver
56  */
57 int UHCI_Initialise(char **Arguments)
58 {
59          int    i=0, id=-1;
60          int    ret;
61         
62         ENTER("");
63         
64         // Enumerate PCI Bus, getting a maximum of `MAX_CONTROLLERS` devices
65         while( (id = PCI_GetDeviceByClass(0x0C0300, 0xFFFFFF, id)) >= 0 && i < MAX_CONTROLLERS )
66         {
67                 tUHCI_Controller        *cinfo = &gUHCI_Controllers[i];
68                 Uint32  base_addr;
69                 // NOTE: Check "protocol" from PCI?
70                 
71                 cinfo->PciId = id;
72                 base_addr = PCI_GetBAR(id, 4);
73                 
74                 if( base_addr & 1 )
75                 {
76                         cinfo->IOBase = base_addr & ~1;
77                         cinfo->MemIOMap = NULL;
78                 }
79                 else
80                 {
81                         cinfo->MemIOMap = (void*)MM_MapHWPages(base_addr, 1);
82                 }
83                 cinfo->IRQNum = PCI_GetIRQ(id);
84                 
85                 Log_Debug("UHCI", "Controller PCI #%i: IO Base = 0x%x, IRQ %i",
86                         id, base_addr, cinfo->IRQNum);
87                 
88                 IRQ_AddHandler(cinfo->IRQNum, UHCI_InterruptHandler, cinfo);
89         
90                 // Initialise Host
91                 ret = UHCI_Int_InitHost(&gUHCI_Controllers[i]);
92                 // Detect an error
93                 if(ret != 0) {
94                         LEAVE('i', ret);
95                         return ret;
96                 }
97                 
98                 cinfo->RootHub = USB_RegisterHost(&gUHCI_HostDef, cinfo, 2);
99                 LOG("cinfo->RootHub = %p", cinfo->RootHub);
100
101                 i ++;
102         }
103
104         if(i == 0) {
105                 LEAVE('i', MODULE_ERR_NOTNEEDED);
106                 return MODULE_ERR_NOTNEEDED;
107         }
108
109         if(i == MAX_CONTROLLERS) {
110                 Log_Warning("UHCI", "Over "EXPAND_STR(MAX_CONTROLLERS)" UHCI controllers detected, ignoring rest");
111         }
112         LEAVE('i', MODULE_ERR_OK);
113         return MODULE_ERR_OK;
114 }
115
116 /**
117  * \fn void UHCI_Cleanup()
118  * \brief Called just before module is unloaded
119  */
120 void UHCI_Cleanup()
121 {
122 }
123
124 tUHCI_TD *UHCI_int_AllocateTD(tUHCI_Controller *Cont)
125 {
126          int    i;
127         for(i = 0; i < NUM_TDs; i ++)
128         {
129                 if(gaUHCI_TDPool[i].Link == 0) {
130                         gaUHCI_TDPool[i].Link = 1;
131                         gaUHCI_TDPool[i].Control = 1 << 23;
132                         return &gaUHCI_TDPool[i];
133                 }
134                 // Still in use? Skip
135                 if( gaUHCI_TDPool[i].Control & (1 << 23) )
136                         continue ;
137                 // Is there a callback on it? Skip
138                 if( gaUHCI_TDPool[i]._info.Callback )
139                         continue ;
140                 // TODO: Garbage collect, but that means removing from the list too
141                 #if 0
142                 // Ok, this is actually unused
143                 gaUHCI_TDPool[i].Link = 1;
144                 gaUHCI_TDPool[i].Control = 1 << 23;
145                 return &gaUHCI_TDPool[i];
146                 #endif
147         }
148         return NULL;
149 }
150
151 tUHCI_TD *UHCI_int_GetTDFromPhys(tPAddr PAddr)
152 {
153         // TODO: Fix this to work with a non-contiguous pool
154         static tPAddr   td_pool_base;
155         const int pool_size = NUM_TDs;
156          int    offset;
157         if(!td_pool_base)       td_pool_base = MM_GetPhysAddr( (tVAddr)gaUHCI_TDPool );
158         offset = (PAddr - td_pool_base) / sizeof(gaUHCI_TDPool[0]);
159         if( offset < 0 || offset >= pool_size )
160         {
161                 Log_Error("UHCI", "TD PAddr %P not from pool", PAddr);
162                 return NULL;
163         }
164         return gaUHCI_TDPool + offset;
165 }
166
167 void UHCI_int_AppendTD(tUHCI_Controller *Cont, tUHCI_TD *TD)
168 {
169          int    next_frame = (_InWord(Cont, FRNUM) + 2) & (1024-1);
170         tUHCI_TD        *prev_td;
171         Uint32  link;
172
173         // TODO: How to handle FRNUM incrementing while we are in this function?
174
175         // Empty list
176         if( Cont->FrameList[next_frame] & 1 )
177         {
178                 // TODO: Ensure 32-bit paddr
179                 Cont->FrameList[next_frame] = MM_GetPhysAddr( (tVAddr)TD );
180                 TD->Control |= (1 << 24);       // Ensure that there is an interrupt for each used frame
181                 LOG("next_frame = %i", next_frame);     
182                 return;
183         }
184
185         // Find the end of the list
186         link = Cont->FrameList[next_frame];
187         do {
188                 prev_td = UHCI_int_GetTDFromPhys(link);
189                 link = prev_td->Link;
190         } while( !(link & 1) );
191         
192         // Append
193         prev_td->Link = MM_GetPhysAddr( (tVAddr)TD );
194
195         LOG("next_frame = %i, prev_td = %p", next_frame, prev_td);
196 }
197
198 /**
199  * \brief Send a transaction to the USB bus
200  * \param Cont  Controller pointer
201  * \param Addr  Function Address * 16 + Endpoint
202  * \param bTgl  Data toggle value
203  */
204 void *UHCI_int_SendTransaction(
205         tUHCI_Controller *Cont, int Addr, Uint8 Type, int bTgl,
206         tUSBHostCb Cb, void *CbData, void *Data, size_t Length)
207 {
208         tUHCI_TD        *td;
209
210         if( Length > 0x400 )    return NULL;    // Controller allows up to 0x500, but USB doesn't
211
212         td = UHCI_int_AllocateTD(Cont);
213
214         if( !td ) {
215                 // TODO: Wait for one to free?
216                 Log_Error("UHCI", "No avaliable TDs, transaction dropped");
217                 return NULL;
218         }
219
220         td->Link = 1;
221         td->Control = (Length - 1) & 0x7FF;
222         td->Control |= (1 << 23);
223         td->Token  = ((Length - 1) & 0x7FF) << 21;
224         td->Token |= (bTgl & 1) << 19;
225         td->Token |= (Addr & 0xF) << 15;
226         td->Token |= ((Addr/16) & 0xFF) << 8;
227         td->Token |= Type;
228
229         // TODO: Ensure 32-bit paddr
230         if( ((tVAddr)Data & (PAGE_SIZE-1)) + Length > PAGE_SIZE ) {
231                 Log_Warning("UHCI", "TODO: Support non single page transfers (%x + %x > %x)",
232                         (tVAddr)Data & (PAGE_SIZE-1), Length, PAGE_SIZE
233                         );
234                 // TODO: Need to enable IOC to copy the data back
235 //              td->BufferPointer = 
236                 td->_info.bCopyData = 1;
237                 return NULL;
238         }
239         else {
240                 td->BufferPointer = MM_GetPhysAddr( (tVAddr)Data );
241                 td->_info.bCopyData = 0;
242         }
243
244         // Interrupt on completion
245         if( Cb ) {
246                 td->Control |= (1 << 24);
247                 LOG("IOC Cb=%p CbData=%p", Cb, CbData);
248                 td->_info.Callback = Cb;        // NOTE: if ERRPTR then the TD is kept allocated until checked
249                 td->_info.CallbackPtr = CbData;
250         }
251         
252         td->_info.DataPtr = Data;
253
254         UHCI_int_AppendTD(Cont, td);
255
256         return td;
257 }
258
259 void *UHCI_DataIN(void *Ptr, int Dest, int DataTgl, tUSBHostCb Cb, void *CbData, void *Buf, size_t Length)
260 {
261         return UHCI_int_SendTransaction(Ptr, Dest, 0x69, DataTgl, Cb, CbData, Buf, Length);
262 }
263
264 void *UHCI_DataOUT(void *Ptr, int Dest, int DataTgl, tUSBHostCb Cb, void *CbData, void *Buf, size_t Length)
265 {
266         return UHCI_int_SendTransaction(Ptr, Dest, 0xE1, DataTgl, Cb, CbData, Buf, Length);
267 }
268
269 void *UHCI_SendSetup(void *Ptr, int Dest, int DataTgl, tUSBHostCb Cb, void *CbData, void *Buf, size_t Length)
270 {
271         return UHCI_int_SendTransaction(Ptr, Dest, 0x2D, DataTgl, Cb, CbData, Buf, Length);
272 }
273
274 int UHCI_IsTransferComplete(void *Ptr, void *Handle)
275 {
276         tUHCI_TD        *td = Handle;
277          int    ret;
278         ret = !(td->Control & (1 << 23));
279         if(ret) {
280                 td->_info.Callback = NULL;
281                 td->Link = 0;
282         }
283         return ret;
284 }
285
286 // === INTERNAL FUNCTIONS ===
287 /**
288  * \fn int UHCI_Int_InitHost(tUCHI_Controller *Host)
289  * \brief Initialises a UHCI host controller
290  * \param Host  Pointer - Host to initialise
291  */
292 int UHCI_Int_InitHost(tUHCI_Controller *Host)
293 {
294         ENTER("pHost", Host);
295
296         _OutWord( Host, USBCMD, 4 );    // GRESET
297         // TODO: Wait for at least 10ms
298         _OutWord( Host, USBCMD, 0 );    // GRESET
299         
300         // Allocate Frame List
301         // - 1 Page, 32-bit address
302         // - 1 page = 1024  4 byte entries
303         Host->FrameList = (void *) MM_AllocDMA(1, 32, &Host->PhysFrameList);
304         if( !Host->FrameList ) {
305                 Log_Warning("UHCI", "Unable to allocate frame list, aborting");
306                 LEAVE('i', -1);
307                 return -1;
308         }
309         LOG("Allocated frame list 0x%x (0x%x)", Host->FrameList, Host->PhysFrameList);
310         memsetd( Host->FrameList, 1, 1024 );    // Clear List (Disabling all entries)
311         
312         //! \todo Properly fill frame list
313         
314         // Set frame length to 1 ms
315         _OutByte( Host, SOFMOD, 64 );
316         
317         // Set Frame List
318         _OutDWord( Host, FLBASEADD, Host->PhysFrameList );
319         _OutWord( Host, FRNUM, 0 );
320         
321         // Enable Interrupts
322         _OutWord( Host, USBINTR, 0x000F );
323         PCI_ConfigWrite( Host->PciId, 0xC0, 2, 0x2000 );
324
325         // Enable processing
326         _OutWord( Host, USBCMD, 0x0001 );
327
328         LEAVE('i', 0);
329         return 0;
330 }
331
332 void UHCI_CheckPortUpdate(void *Ptr)
333 {
334         tUHCI_Controller        *Host = Ptr;
335         // Enable ports
336         for( int i = 0; i < 2; i ++ )
337         {
338                  int    port = PORTSC1 + i*2;
339                 Uint16  status;
340         
341                 status = _InWord(Host, port);
342                 // Check for port change
343                 if( !(status & 0x0002) )        continue;
344                 _OutWord(Host, port, 0x0002);
345                 
346                 // Check if the port is connected
347                 if( !(status & 1) )
348                 {
349                         // Tell the USB code it's gone.
350                         USB_DeviceDisconnected(Host->RootHub, i);
351                         continue;
352                 }
353                 else
354                 {
355                         LOG("Port %i has something", i);
356                         // Reset port (set bit 9)
357                         LOG("Reset");
358                         _OutWord(Host, port, 0x0200);
359                         Time_Delay(50); // 50ms delay
360                         _OutWord(Host, port, _InWord(Host, port) & ~0x0200);
361                         // Enable port
362                         LOG("Enable");
363                         Time_Delay(50); // 50ms delay
364                         _OutWord(Host, port, _InWord(Host, port) | 0x0004);
365                         // Tell USB there's a new device
366                         USB_DeviceConnected(Host->RootHub, i);
367                 }
368         }
369 }
370
371 void UHCI_InterruptHandler(int IRQ, void *Ptr)
372 {
373         tUHCI_Controller *Host = Ptr;
374          int    frame = (_InWord(Host, FRNUM) - 1) & 0x3FF;
375         Uint16  status = _InWord(Host, USBSTS);
376 //      Log_Debug("UHCI", "UHIC Interrupt, status = 0x%x, frame = %i", status, frame);
377         
378         // Interrupt-on-completion
379         if( status & 1 )
380         {
381                 tPAddr  link;
382                 
383                 for( int i = 0; i < 10; i ++ )
384                 {
385                         link = Host->FrameList[frame];
386                         Host->FrameList[frame] = 1;
387                         while( link && !(link & 1) )
388                         {
389                                 tUHCI_TD *td = UHCI_int_GetTDFromPhys(link);
390                                  int    byte_count = (td->Control&0x7FF)+1;
391                                 LOG("link = 0x%x, td = %p, byte_count = %i", link, td, byte_count);
392                                 // Handle non-page aligned destination
393                                 // TODO: This will break if the destination is not in global memory
394                                 if(td->_info.bCopyData)
395                                 {
396                                         void *ptr = (void*)MM_MapTemp(td->BufferPointer);
397                                         Log_Debug("UHCI", "td->_info.DataPtr = %p", td->_info.DataPtr);
398                                         memcpy(td->_info.DataPtr, ptr, byte_count);
399                                         MM_FreeTemp((tVAddr)ptr);
400                                 }
401                                 // Callback
402                                 if(td->_info.Callback && td->_info.Callback != INVLPTR)
403                                 {
404                                         LOG("Calling cb %p", td->_info.Callback);
405                                         td->_info.Callback(td->_info.CallbackPtr, td->_info.DataPtr, byte_count);
406                                         td->_info.Callback = NULL;
407                                 }
408                                 link = td->Link;
409                                 if( td->_info.Callback != INVLPTR )
410                                         td->Link = 0;
411                         }
412                         
413                         if(frame == 0)
414                                 frame = 0x3ff;
415                         else
416                                 frame --;
417                 }
418                 
419 //              Host->LastCleanedFrame = frame;
420         }
421
422         LOG("status = 0x%02x", status);
423         _OutWord(Host, USBSTS, status);
424 }
425
426 void _OutByte(tUHCI_Controller *Host, int Reg, Uint8 Value)
427 {
428         if( Host->MemIOMap )
429                 ((Uint8*)Host->MemIOMap)[Reg] = Value;
430         else
431                 outb(Host->IOBase + Reg, Value);
432 }
433
434 void _OutWord(tUHCI_Controller *Host, int Reg, Uint16 Value)
435 {
436         if( Host->MemIOMap )
437                 Host->MemIOMap[Reg/2] = Value;
438         else
439                 outw(Host->IOBase + Reg, Value);
440 }
441
442 void _OutDWord(tUHCI_Controller *Host, int Reg, Uint32 Value)
443 {
444         if( Host->MemIOMap )
445                 ((Uint32*)Host->MemIOMap)[Reg/4] = Value;
446         else
447                 outd(Host->IOBase + Reg, Value);
448 }
449
450 Uint16 _InWord(tUHCI_Controller *Host, int Reg)
451 {
452         if( Host->MemIOMap )
453                 return Host->MemIOMap[Reg/2];
454         else
455                 return inw(Host->IOBase + Reg);
456 }
457

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