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

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