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

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