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

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