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

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