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

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