Merge branch 'master' of git://localhost/acess2
[tpg/acess2.git] / KernelLand / Modules / USB / Core / usb_devinit.c
1 /*
2  * Acess 2 USB Stack
3  * - By John Hodge (thePowersGang)
4  *
5  * usb_devinit.c
6  * - USB Device Initialisation
7  */
8 #define DEBUG   0
9 #include <acess.h>
10 #include <vfs.h>
11 #include <drv_pci.h>
12 #include "usb.h"
13 #include "usb_proto.h"
14 #include "usb_lowlevel.h"
15
16 #define DUMP_DESCRIPTORS        1
17
18 // === PROTOTYPES ===
19 void    USB_DeviceConnected(tUSBHub *Hub, int Port);
20 void    USB_DeviceDisconnected(tUSBHub *Hub, int Port);
21 void    *USB_GetDeviceDataPtr(tUSBInterface *Dev);
22 void    USB_SetDeviceDataPtr(tUSBInterface *Dev, void *Ptr);
23  int    USB_int_AllocateAddress(tUSBHost *Host);
24 void    USB_int_DeallocateAddress(tUSBHost *Host, int Address);
25
26 // === CODE ===
27 void USB_DeviceConnected(tUSBHub *Hub, int Port)
28 {
29         tUSBDevice      tmpdev;
30         tUSBDevice      *dev = &tmpdev;
31         if( Port >= Hub->nPorts )       return ;
32         if( Hub->Devices[Port] )        return ;
33
34         ENTER("pHub iPort", Hub, Port);
35
36         // Device should be in 'Default' state
37         
38         // Create structure
39         dev->ParentHub = Hub;
40         dev->Host = Hub->Interface->Dev->Host;
41         dev->Address = 0;
42
43         // 1. Assign an address
44         dev->Address = USB_int_AllocateAddress(dev->Host);
45         if(dev->Address == 0) {
46                 Log_Error("USB", "No addresses avaliable on host %p", dev->Host);
47                 free(dev);
48                 LEAVE('-');
49                 return ;
50         }
51         USB_int_SendSetupSetAddress(dev->Host, dev->Address);
52         LOG("Assigned address %i", dev->Address);
53
54         dev->EndpointHandles[0] = dev->Host->HostDef->InitControl(dev->Host->Ptr, dev->Address << 4, 64);
55         for( int i = 1; i < 16; i ++ )
56                 dev->EndpointHandles[i] = 0;
57
58         // 2. Get device information
59         {
60                 struct sDescriptor_Device       desc;
61                 desc.Length = 0;
62                 LOG("Getting device descriptor");
63                 // Endpoint 0, Desc Type 1, Index 0
64                 USB_int_ReadDescriptor(dev, 0, 1, 0, sizeof(desc), &desc);
65
66                 if( desc.Length < sizeof(desc) ) {
67                         Log_Error("USB", "Device descriptor undersized (%i<%i)", desc.Length, sizeof(desc));
68                         USB_int_DeallocateAddress(dev->Host, dev->Address);
69                         LEAVE('-');
70                         return;
71                 }
72                 if( desc.Type != 1 ) {
73                         Log_Error("USB", "Device descriptor type invalid (%i!=1)", desc.Type);
74                         USB_int_DeallocateAddress(dev->Host, dev->Address);
75                         LEAVE('-');
76                         return;
77                 }
78
79                 #if DUMP_DESCRIPTORS            
80                 LOG("Device Descriptor = {");
81                 LOG(" .Length = %i", desc.Length);
82                 LOG(" .Type = %i", desc.Type);
83                 LOG(" .USBVersion = 0x%04x", LittleEndian16(desc.USBVersion));
84                 LOG(" .DeviceClass = 0x%02x", desc.DeviceClass);
85                 LOG(" .DeviceSubClass = 0x%02x", desc.DeviceSubClass);
86                 LOG(" .DeviceProtocol = 0x%02x", desc.DeviceProtocol);
87                 LOG(" .MaxPacketSize = 0x%02x", desc.MaxPacketSize);
88                 LOG(" .VendorID = 0x%04x",  LittleEndian16(desc.VendorID));
89                 LOG(" .ProductID = 0x%04x", LittleEndian16(desc.ProductID));
90                 LOG(" .DeviceID = 0x%04x",  LittleEndian16(desc.DeviceID));
91                 LOG(" .ManufacturerStr = Str %i", desc.ManufacturerStr);
92                 LOG(" .ProductStr = Str %i", desc.ProductStr);
93                 LOG(" .SerialNumberStr = Str %i", desc.SerialNumberStr);
94                 LOG(" .NumConfigurations = %i", desc.NumConfigurations);
95                 LOG("}");
96         
97                 #if DEBUG
98                 if( desc.ManufacturerStr )
99                 {
100                         char    *tmp = USB_int_GetDeviceString(dev, 0, desc.ManufacturerStr);
101                         if( tmp ) {
102                                 LOG("ManufacturerStr = '%s'", tmp);
103                                 free(tmp);
104                         }
105                 }
106                 if( desc.ProductStr )
107                 {
108                         char    *tmp = USB_int_GetDeviceString(dev, 0, desc.ProductStr);
109                         if( tmp ) {
110                                 LOG("ProductStr = '%s'", tmp);
111                                 free(tmp);
112                         }
113                 }
114                 if( desc.SerialNumberStr )
115                 {
116                         char    *tmp = USB_int_GetDeviceString(dev, 0, desc.SerialNumberStr);
117                         if( tmp ) {
118                                 LOG("SerialNumbertStr = '%s'", tmp);
119                                 free(tmp);
120                         }
121                 }
122                 #endif
123                 #endif
124                 
125                 memcpy(&dev->DevDesc, &desc, sizeof(desc));
126         }
127
128         // 3. Get configurations
129         // TODO: Support alternate configurations
130         for( int i = 0; i < 1; i ++ )
131         {
132                 struct sDescriptor_Configuration        desc;
133                 Uint8   *full_buf;
134                 size_t  ptr_ofs = 0;
135                 size_t  total_length;
136         
137                 USB_int_ReadDescriptor(dev, 0, 2, i, sizeof(desc), &desc);
138                 if( desc.Length < sizeof(desc) ) {
139                         // ERROR: 
140                 }
141                 if( desc.Type != 2 ) {
142                         // ERROR: 
143                 }
144                 // TODO: Check return length? (Do we get a length?)
145                 #if DUMP_DESCRIPTORS
146                 LOG("Configuration Descriptor %i = {", i);
147                 LOG(" .Length = %i", desc.Length);
148                 LOG(" .Type = %i", desc.Type);
149                 LOG(" .TotalLength = 0x%x", LittleEndian16(desc.TotalLength));
150                 LOG(" .NumInterfaces = %i", desc.NumInterfaces);
151                 LOG(" .ConfigurationValue = %i", desc.ConfigurationValue);
152                 LOG(" .ConfigurationStr = %i", desc.ConfigurationStr);
153                 LOG(" .AttributesBmp = 0b%b", desc.AttributesBmp);
154                 LOG(" .MaxPower = %i (*2mA)", desc.MaxPower);
155                 LOG("}");
156                 if( desc.ConfigurationStr ) {
157                         char    *tmp = USB_int_GetDeviceString(dev, 0, desc.ConfigurationStr);
158                         LOG("ConfigurationStr = '%s'", tmp);
159                         free(tmp);
160                 }
161                 #endif
162
163                 if( desc.NumInterfaces == 0 ) {
164                         Log_Notice("USB", "Device does not have any interfaces");
165                         continue ;
166                 }
167
168                 // TODO: Split here and allow some method of selection
169
170                 // Allocate device now that we have the configuration
171                 dev = malloc(sizeof(tUSBDevice) + desc.NumInterfaces * sizeof(void*));
172                 memcpy(dev, &tmpdev, sizeof(tUSBDevice));
173                 dev->nInterfaces = desc.NumInterfaces;
174         
175                 // Allocate a temp buffer for config info
176                 total_length = LittleEndian16(desc.TotalLength);
177                 full_buf = malloc( total_length );
178                 USB_int_ReadDescriptor(dev, 0, 2, i, total_length, full_buf);
179                 ptr_ofs += desc.Length;
180
181
182                 // Interfaces!
183                 for( int j = 0; ptr_ofs < total_length && j < desc.NumInterfaces; j ++ )
184                 {
185                         struct sDescriptor_Interface *iface;
186                         tUSBInterface   *dev_if;
187                         size_t  iface_base_ofs;
188
189                         iface = (void*)(full_buf + ptr_ofs);
190                         if( iface->Length == 0 ) {
191                                 Log_Warning("USB", "Bad USB descriptor (length = 0)");
192                                 break ;
193                         }
194                         ptr_ofs += iface->Length;
195                         if( ptr_ofs > total_length ) {
196                                 // Sanity fail
197                                 break;
198                         }
199                         iface_base_ofs = ptr_ofs;
200                         // Check type
201                         if( iface->Type != 4 ) {
202                                 LOG("Not an interface (type = %i)", iface->Type);
203                                 j --;   // Counteract j++ in loop
204                                 continue ;
205                         }
206
207                         #if DUMP_DESCRIPTORS
208                         LOG("Interface %i/%i = {", i, j);
209                         LOG(" .InterfaceNum = %i", iface->InterfaceNum);
210                         LOG(" .NumEndpoints = %i", iface->NumEndpoints);
211                         LOG(" .InterfaceClass = 0x%x", iface->InterfaceClass);
212                         LOG(" .InterfaceSubClass = 0x%x", iface->InterfaceSubClass);
213                         LOG(" .InterfaceProcol = 0x%x", iface->InterfaceProtocol);
214                         if( iface->InterfaceStr ) {
215                                 char    *tmp = USB_int_GetDeviceString(dev, 0, iface->InterfaceStr);
216                                 LOG(" .InterfaceStr = %i '%s'", iface->InterfaceStr, tmp);
217                                 free(tmp);
218                         }
219                         LOG("}");
220                         #endif
221
222                         dev_if = malloc(
223                                 sizeof(tUSBInterface)
224                                 + iface->NumEndpoints*sizeof(dev_if->Endpoints[0])
225                                 );
226                         dev_if->Dev = dev;
227                         dev_if->Driver = NULL;
228                         dev_if->Data = NULL;
229                         dev_if->nEndpoints = iface->NumEndpoints;
230                         memcpy(&dev_if->IfaceDesc, iface, sizeof(*iface));
231                         dev->Interfaces[j] = dev_if;
232
233                         // Copy interface data
234                         for( int k = 0; ptr_ofs < total_length && k < iface->NumEndpoints; k ++ )
235                         {
236                                 struct sDescriptor_Endpoint *endpt;
237                                 
238                                 endpt = (void*)(full_buf + ptr_ofs);
239                                 ptr_ofs += endpt->Length;
240                                 if( ptr_ofs > total_length ) {
241                                         // Sanity fail
242                                         break;
243                                 }
244
245                                 // Check type
246                                 if( endpt->Type != 5 ) {
247                                         // Oops?
248                                         LOG("Not endpoint, Type = %i", endpt->Type);
249                                         k --;
250                                         continue ;
251                                 }
252
253                                 LOG("Endpoint %i/%i/%i = {", i, j, k);
254                                 LOG(" .Address = 0x%2x", endpt->Address);
255                                 LOG(" .Attributes = 0b%8b", endpt->Attributes);
256                                 LOG(" .MaxPacketSize = %i", LittleEndian16(endpt->MaxPacketSize));
257                                 LOG(" .PollingInterval = %i", endpt->PollingInterval);
258                                 LOG("}");
259         
260                                 // Make sure things don't break
261                                 if( !((endpt->Address & 0x7F) < 15) ) {
262                                         Log_Error("USB", "Endpoint number %i>16", endpt->Address & 0x7F);
263                                         k --;
264                                         continue ;
265                                 }
266
267                                 dev_if->Endpoints[k].Next = NULL;
268                                 dev_if->Endpoints[k].Interface = dev_if;
269                                 dev_if->Endpoints[k].EndpointIdx = k;
270                                 dev_if->Endpoints[k].EndpointNum = endpt->Address & 0x7F;
271                                 dev_if->Endpoints[k].PollingPeriod = endpt->PollingInterval;
272                                 dev_if->Endpoints[k].MaxPacketSize = LittleEndian16(endpt->MaxPacketSize);
273                                 dev_if->Endpoints[k].Type = endpt->Attributes | (endpt->Address & 0x80);
274                                 dev_if->Endpoints[k].PollingAtoms = 0;
275                                 dev_if->Endpoints[k].InputData = NULL;
276                                 
277                                 // TODO: Register endpoint early
278                                  int    ep_num = endpt->Address & 15;
279                                 if( dev->EndpointHandles[ep_num] ) {
280                                         Log_Notice("USB", "Device %p:%i ep %i reused", dev->Host->Ptr, dev->Address, ep_num);
281                                 }
282                                 else {
283                                          int    addr = dev->Address*16+ep_num;
284                                          int    mps = dev_if->Endpoints[k].MaxPacketSize;
285                                         void *handle = NULL;
286                                         switch( endpt->Attributes & 3)
287                                         {
288                                         case 0: // Control
289                                                 handle = dev->Host->HostDef->InitControl(dev->Host->Ptr, addr, mps);
290                                                 break;
291                                         case 1: // Isochronous
292                                         //      handle = dev->Host->HostDef->InitIsoch(dev->Host->Ptr, addr, mps);
293                                                 break;
294                                         case 2: // Bulk
295                                                 handle = dev->Host->HostDef->InitBulk(dev->Host->Ptr, addr, mps);
296                                                 break;
297                                         case 3: // Interrupt
298                                         //      handle = dev->Host->HostDef->InitInterrupt(dev->Host->Ptr, addr, ...);
299                                                 break;
300                                         }
301                                         dev->EndpointHandles[ep_num] = handle;
302                                 }
303                         }
304                         
305                         // Initialise driver
306                         dev_if->Driver = USB_int_FindDriverByClass(
307                                  ((int)iface->InterfaceClass << 16)
308                                 |((int)iface->InterfaceSubClass << 8)
309                                 |((int)iface->InterfaceProtocol << 0)
310                                 );
311                         if(!dev_if->Driver) {
312                                 Log_Notice("USB", "No driver for Class %02x:%02x:%02x",
313                                         iface->InterfaceClass, iface->InterfaceSubClass, iface->InterfaceProtocol
314                                         );
315                         }
316                         else {
317                                 LOG("Driver '%s' in use", dev_if->Driver->Name);
318                                 dev_if->Driver->Connected(
319                                         dev_if,
320                                         full_buf + iface_base_ofs, ptr_ofs - iface_base_ofs
321                                         );
322                         }
323                 }
324                 
325                 free(full_buf);
326         }
327         
328         Hub->Devices[Port] = dev;
329         
330         // Done.
331         LEAVE('-');
332 }
333
334 void USB_DeviceDisconnected(tUSBHub *Hub, int Port)
335 {
336         tUSBDevice      *dev;
337         if( !Hub->Devices[Port] ) {
338                 Log_Error("USB", "Non-registered device disconnected");
339                 return;
340         }
341         dev = Hub->Devices[Port];
342
343         // TODO: Free related resources
344         // - Endpoint registrations
345         for( int i = 0; i < 16; i ++ )
346         {
347                 if(dev->EndpointHandles[i])
348                         dev->Host->HostDef->RemEndpoint(dev->Host->Ptr, dev->EndpointHandles[i]);
349         }
350
351         // - Bus Address
352         USB_int_DeallocateAddress(dev->Host, dev->Address);
353         // - Inform handler
354         // - Allocate memory
355         free(dev);
356 }
357
358 void *USB_GetDeviceDataPtr(tUSBInterface *Dev) { return Dev->Data; }
359 void USB_SetDeviceDataPtr(tUSBInterface *Dev, void *Ptr) { Dev->Data = Ptr; }
360
361 int USB_int_AllocateAddress(tUSBHost *Host)
362 {
363          int    i;
364         for( i = 1; i < 128; i ++ )
365         {
366                 if(Host->AddressBitmap[i/8] & (1 << (i%8)))
367                         continue ;
368                 Host->AddressBitmap[i/8] |= 1 << (i%8);
369                 return i;
370         }
371         return 0;
372 }
373
374 void USB_int_DeallocateAddress(tUSBHost *Host, int Address)
375 {
376         Host->AddressBitmap[Address/8] &= ~(1 << (Address%8));
377 }
378

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