5535bb351a22025957ff242dd84c9d7596d289fe
[ppcskel.git] / usb / core / core.c
1 /*
2  * Copyright (c) 2006, Benedikt Sauter <sauter@ixbat.de>
3  * All rights reserved.
4  *
5  * Short descripton of file:
6  *
7  *
8  * Redistribution and use in source and binary forms, with or without 
9  * modification, are permitted provided that the following conditions 
10  * are met:
11  *
12  *       * Redistributions of source code must retain the above copyright 
13  *               notice, this list of conditions and the following disclaimer.
14  *       * Redistributions in binary form must reproduce the above 
15  *               copyright notice, this list of conditions and the following 
16  *               disclaimer in the documentation and/or other materials provided 
17  *               with the distribution.
18  *       * Neither the name of the FH Augsburg nor the names of its 
19  *               contributors may be used to endorse or promote products derived 
20  *               from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
25  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
26  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
28  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
32  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34
35 //#include <stdlib.h>
36 #include "core.h"
37 #include "../host/host.h"
38 #include "usb.h"
39 #include "../usbspec/usb11spec.h"
40 #include "../lib/list.h"
41 #include "../../malloc.h"
42 #include "../../bootmii_ppc.h" //printf
43 #include "../../string.h" //memset
44
45 /**
46  * Initialize USB stack.
47  */
48 void usb_init(u32 reg)
49 {
50         core.drivers = list_create();
51         core.devices = list_create();
52         core.nextaddress = 1;
53         hcdi_init(reg);
54 }
55
56 /**
57  * Get next free usb device address.
58  */
59 u8 usb_next_address()
60 {
61         u8 addr = core.nextaddress;
62         core.nextaddress++;
63         return addr;
64 }
65
66
67 /**
68  * Call this function periodically for 
69  * control and transfer management.
70  */
71 void usb_periodic()
72 {
73         // call ever registered driver  
74         struct usb_driver *drv;
75         struct element *iterator = core.drivers->head;
76         while (iterator != NULL) {
77                 drv = (struct usb_driver *) iterator->data;
78                 drv->check();
79                 iterator = iterator->next;
80         }
81 }
82
83
84 /** 
85  * Enumerate new device and create data structures 
86  * for the core. usb_add_device expected that
87  * the device answers to address zero.
88  */
89 struct usb_device *usb_add_device(u8 lowspeed, u32 reg)
90 {
91         struct usb_device *dev = (struct usb_device *) malloc(sizeof(struct usb_device));
92         dev->conf = (struct usb_conf *) malloc(sizeof(struct usb_conf));
93         dev->address = 0;
94         dev->fullspeed = lowspeed ? 0 : 1;
95         /* send at first time only 8 bytes for lowspeed devices
96          * 64 bytes for fullspeed
97          */
98         dev->bMaxPacketSize0 = lowspeed ? 8 : 64;
99         dev->ohci = reg;
100
101         dev->epSize[0] = 8;
102         dev->epSize[1] = 64;
103         dev->epSize[2] = 64;
104
105         dev->epTogl[0] = 0;
106         dev->epTogl[1] = 0;
107         dev->epTogl[2] = 0;
108
109         s8 ret;
110         ret = usb_get_desc_dev_simple(dev);
111         if(ret < 0) {
112                 return (void*) -1;
113         }
114
115 #define WTF
116 #ifdef WTF
117         printf("lololol PADDING WTF :O lolololololo \n");
118         printf("lololololool PADDING WTF :O lolololololo \n");
119         printf("lolololool PADDING WTF :O lololoololo \n");
120         printf("lololololool PADDING WTF :O lolololololo \n");
121         printf("lolololool PADDING WTF :O lolololololo \n");
122         printf("lololololool PADDING WTF :O lolololololo \n");
123         printf("lollllool PADDING WTF :O lolololololo \n");
124 #endif
125         u8 address = usb_next_address();
126         ret = usb_set_address(dev, address);
127         dev->address = address;
128         printf("set address to %d\n", dev->address);
129
130         /* get device descriptor&co */
131         ret = usb_get_desc_dev(dev);
132         if(ret < 0)
133                 return (void*) -1;
134
135         /* print device info */
136         //lsusb(dev);
137
138         //HID only!
139 #define GET_PROTOCOL 0x03
140 #define SET_PROTOCOL 0x0b
141 #define GETit 0xa1
142 #define SETit 0x21
143
144
145         u8 buf[255];
146 #if 1
147         /* select configuration */
148         wait_ms(500);
149         ret = usb_set_configuration(dev, 1);
150         printf("=============\nusb_set_configuration(ret: %d): %d\n", ret, dev->conf->bConfigurationValue);
151         wait_ms(500);
152 #if 0
153         wait_ms(500);
154         printf("=============\nusb_get_configuration: %d (should be 1 here)\n", usb_get_configuration(dev));
155 #endif
156 #endif
157
158 #if 1
159         memset(buf, 0, 0xff);
160         usb_control_msg(dev, (1<<5)|1, SET_CONFIGURATION, 0x200, 0x0, 0x0, buf, 0);
161         printf("wtf request\n");
162         hexdump((void*)buf, 0x8);
163 #endif
164
165
166 #if 0
167         /* set protocol */
168         /* see p48 in HID spec */
169         memset(buf, 0, 8);
170         usb_control_msg(dev, SETit, SET_PROTOCOL, 0 /*boot protocol*/, 0 /*interface number*/, 0 /*length*/, buf, 0);
171         printf("=============\nhid_set_protocol %d\n", 0);
172         hexdump((void*)buf, 8);
173 #endif
174 #if 0
175         memset(buf, 0, 8);
176         usb_control_msg(dev, GETit, GET_PROTOCOL, 0, 0, 4, buf, 0);
177         printf("=============\nusb_get_protocol: %d\n", buf[0]);
178         hexdump((void*)buf, 8);
179 #endif
180
181 #if 1
182         /* I just don't know why on some devices 
183          * {s,g}et_{configuration,interface} won't work.
184          * may the setter works and getter are poorly implemented?
185          * however, I try here some interrupt inputs, assuming 
186          * the setters are fine*/
187
188         memset(buf, 0, 8);
189         s8 epnum = dev->conf->intf->endp->bEndpointAddress & 0xf;
190         printf("epnum: 0x%04X\n", epnum);
191         u8 muh = 10;
192         while(muh--) {
193                 (void) usb_interrupt_read(dev, epnum, buf, 8, 0);
194                 printf("============\nusb_interrupt_read:\n");
195                 hexdump((void*)buf, 8);
196                 udelay(2000000);
197         }
198 #endif
199
200 #if 0
201         /* add device to device list */
202         element *tmp = (element *) malloc(sizeof(element));
203         tmp->data = (void *) dev;
204         list_add_tail(core.devices, tmp);
205
206         usb_probe_driver();
207 #endif
208
209         return dev;
210 }
211
212 void lsusb(struct usb_device *dev)
213 {
214         printf("=== Device Descriptor === \n");
215         printf("bLength 0x%02X\n", dev->bLength);
216         printf("bDescriptorType 0x%02X\n", dev->bDeviceClass);
217         printf("bcdUSB 0x%04X\n", dev->bcdUSB);
218         printf("bDeviceClass 0x%02X\n", dev->bDeviceClass);
219         printf("bDeviceSubClass 0x%02X\n", dev->bDeviceSubClass);
220         printf("bDeviceProtocoll 0x%02X\n", dev->bDeviceProtocoll);
221         printf("bMaxPacketSize 0x%02X\n", dev->bMaxPacketSize0);
222         printf("idVendor 0x%04X\n", dev->idVendor);
223         printf("idProduct 0x%04X\n", dev->idProduct);
224         printf("bcdDevice 0x%04X\n", dev->bcdDevice);
225         printf("iManufacturer(0x%02X): \"%s\"\n", dev->iManufacturer, dev->iManufacturer ? usb_get_string_simple(dev, dev->iManufacturer) : "no String");
226         printf("iProduct(0x%02X): \"%s\"\n", dev->iProduct, dev->iProduct ? usb_get_string_simple(dev, dev->iProduct) : "no String");
227         printf("iSerialNumber(0x%02X): \"%s\"\n", dev->iSerialNumber, dev->iSerialNumber ? usb_get_string_simple(dev, dev->iSerialNumber) : "no String");
228         printf("bNumConfigurations 0x%02X\n", dev->bNumConfigurations);
229
230         u8 c, i, e;
231         struct usb_conf *conf = dev->conf;
232         for(c=0; c <= dev->bNumConfigurations; c++) {
233                 printf("  === Configuration Descriptor %d ===\n", c+1);
234                 printf("  bLength 0x%02X\n", conf->bLength);
235                 printf("  bDescriptorType 0x%02X\n", conf->bDescriptorType);
236                 printf("  wTotalLength 0x%04X\n", conf->wTotalLength);
237                 printf("  bNumInterfaces 0x%02X\n", conf->bNumInterfaces);
238                 printf("  bConfigurationValue 0x%02X\n", conf->bConfigurationValue);
239                 printf("  iConfiguration (0x%02X): \"%s\"\n", conf->iConfiguration, conf->iConfiguration ? usb_get_string_simple(dev, conf->iConfiguration) : "no String");
240                 printf("  bmAttributes 0x%02X\n", conf->bmAttributes);
241                 printf("  bMaxPower 0x%02X\n", conf->bMaxPower);
242
243                 struct usb_intf *ifs = conf->intf;
244                 for(i=1; i <= conf->bNumInterfaces; i++) {
245                         printf("    === Interface Descriptor %d ===\n", i);
246                         printf("    bLength 0x%02X\n", ifs->bLength);
247                         printf("    bDescriptorType 0x%02X\n", ifs->bDescriptorType);
248                         printf("    bInterfaceNumber 0x%02X\n", ifs->bInterfaceNumber);
249                         printf("    bAlternateSetting 0x%02X\n", ifs->bAlternateSetting);
250                         printf("    bNumEndpoints 0x%02X\n", ifs->bNumEndpoints);
251                         printf("    bInterfaceClass 0x%02X\n", ifs->bInterfaceClass);
252                         printf("    bInterfaceSubClass 0x%02X\n", ifs->bInterfaceSubClass);
253                         printf("    bInterfaceProtocol 0x%02X\n", ifs->bInterfaceProtocol);
254                         printf("    iInterface (0x%02X): \"%s\"\n", ifs->iInterface, ifs->iInterface ? usb_get_string_simple(dev, ifs->iInterface) : "no String");
255
256                         struct usb_endp *ed = ifs->endp;
257                         for(e=1; e <= ifs->bNumEndpoints; e++) {
258                                 printf("      === Endpoint Descriptor %d ===\n", e);
259                                 printf("      bLength 0x%02X\n", ed->bLength);
260                                 printf("      bDescriptorType 0x%02X\n", ed->bDescriptorType);
261                                 printf("      bEndpointAddress 0x%02X\n", ed->bEndpointAddress);
262                                 printf("      bmAttributes 0x%02X\n", ed->bmAttributes);
263                                 printf("      wMaxPacketSize 0x%02X\n", ed->wMaxPacketSize);
264                                 printf("      bInterval 0x%02X\n", ed->bInterval);
265
266                                 ed = ed->next;
267                         } //endpoint
268
269                         ifs = ifs->next;
270                 } //interface
271
272                 conf = conf->next;
273         } //configuration
274 }
275
276 /**
277  * Find currently detached device and remove
278  * data structures
279  */
280 u8 usb_remove_device(struct usb_device * dev)
281 {
282         // FIXME!!!! dieser quatsch ist nur temporaer
283         free(core.devices->head);
284         free(core.devices);
285         core.devices = list_create();
286         return 1;
287 }
288
289 /**
290  * Register new driver at usb stack.
291  */
292 u8 usb_register_driver(struct usb_driver * dev)
293 {
294         /* add driver to driver list */
295         struct element *tmp = (struct element *) malloc(sizeof(struct element));
296         tmp->data = (void *) dev;
297         tmp->next = NULL;
298         list_add_tail(core.drivers, tmp);
299
300
301         /** 
302          * first check to find a suitable device 
303          * (root hub drivers need this call here)
304          */
305         dev->probe();
306
307         return 1;
308 }
309
310
311 /**
312  * Call every probe function from every registered
313  * driver, to check if there is a valid driver
314  * for the new device.  
315  */
316 void usb_probe_driver()
317 {
318         // call ever registered driver  
319         struct usb_driver *drv;
320         struct element *iterator = core.drivers->head;
321         while (iterator != NULL) {
322                 drv = (struct usb_driver *) iterator->data;
323                 drv->probe();
324                 iterator = iterator->next;
325         }
326 }
327
328 /**
329  * Not implemented.
330  */
331 struct usb_irp *usb_get_irp()
332 {
333         return 0;
334 }
335
336 /**
337  * Not implemented.
338  */
339 u8 usb_remove_irp(struct usb_irp *irp)
340 {
341
342         return 1;
343 }
344
345 /**
346  * Takes usb_irp and split it into
347  * several usb packeges (SETUP,IN,OUT)
348  * In the usbstack they are transported with the
349  * usb_transfer_descriptor data structure.
350  */
351 u16 usb_submit_irp(struct usb_irp *irp)
352 {
353         struct usb_transfer_descriptor *td;
354         u8 runloop = 1;
355         u16 restlength = irp->len;
356         u8 *td_buf_ptr = irp->buffer;
357         u8 mybuf[64];
358
359         u8 togl = irp->dev->epTogl[(irp->endpoint & 0x7F)];
360
361         switch (irp->type) {
362         case USB_CTRL:
363                 /* alle requests mit dem gleichen algorithmus zerteilen
364                  * das einzige ist der spezielle get_Device_descriptor request
365                  * bei dem eine laenge von 64 angegeben ist.
366                  * wenn man an adresse 0 einen get_device_desciptor schickt
367                  * dann reichen die ersten 8 byte.
368                  */
369
370                 /***************** Setup Stage ***********************/
371                 td = usb_create_transfer_descriptor(irp);
372                 td->pid = USB_PID_SETUP;
373                 td->buffer = irp->buffer;
374
375                 /* control message are always 8 bytes */
376                 td->actlen = 8;
377
378                 togl = 0;
379                 /* start with data0 */
380                 td->togl = togl;
381                 togl = togl ? 0 : 1;
382
383                 /**** send token ****/
384                 hcdi_enqueue(td, irp->dev->ohci);
385
386                 /***************** Data Stage ***********************/
387                 /**
388                  * You can see at bit 7 of bmRequestType if this stage is used,
389                  * default requests are always 8 byte greate, from
390                  * host to device. Stage 3 is only neccessary if the request
391                  * expected datas from the device.
392                  * bit7 - 1 = from device to host -> yes we need data stage
393                  * bit7 - 0 = from host to device -> no send zero packet
394                  *
395                  * nach einem setup token kann nur ein IN token in stage 3 folgen
396                  * nie aber ein OUT. Ein Zero OUT wird nur als Bestaetigung benoetigt.
397                  *
398                  *
399                  * bit7 = 1
400                  *      Device to Host
401                  *      - es kommen noch Daten mit PID_IN an
402                  *      - host beendet mit PID_OUT DATA1 Zero
403                  * bit7 - 0
404                  *      Host zu Device (wie set address)
405                  *      - device sendet ein PID_IN DATA1 Zero Packet als bestaetigung
406                  */
407                 memcpy(mybuf, irp->buffer, td->actlen);
408                 usb_device_request *setup = (usb_device_request *) mybuf;
409                 u8 bmRequestType = setup->bmRequestType;
410                 free(td);
411
412                 /* check bit 7 of bmRequestType */
413                 if (bmRequestType & 0x80) { 
414                         /* schleife die die tds generiert */
415                         while (runloop && (restlength > 0)) {
416                                 td = usb_create_transfer_descriptor(irp);
417                                 td->actlen = irp->epsize;
418                                 /* stop loop if all bytes are send */
419                                 if (restlength < irp->epsize) {
420                                         runloop = 0;
421                                         td->actlen = restlength;
422                                 }
423
424                                 td->buffer = td_buf_ptr;
425                                 /* move pointer for next packet */
426                                 td_buf_ptr += irp->epsize;
427
428                                 td->pid = USB_PID_IN;
429                                 td->togl = togl;
430                                 togl = togl ? 0 : 1;
431
432                                 /* wenn device descriptor von adresse 0 angefragt wird werden nur
433                                  * die ersten 8 byte abgefragt
434                                  */
435                                 if (setup->bRequest == GET_DESCRIPTOR && (setup->wValue & 0xff) == 1
436                                                 && td->devaddress == 0) {
437                                         /* stop loop */
438                                         runloop = 0;
439                                 }
440
441                                 /**** send token ****/
442                                 hcdi_enqueue(td, irp->dev->ohci);
443
444                                 /* pruefe ob noch weitere Pakete vom Device abgeholt werden muessen */
445                                 restlength = restlength - irp->epsize;
446                                 free(td);
447                         }
448                 }
449
450
451                 /***************** Status Stage ***********************/
452                 /* Zero packet for end */
453                 td = usb_create_transfer_descriptor(irp);
454                 td->togl = 1;                                                           /* zero data packet = always DATA1 packet */
455                 td->actlen = 0;
456                 td->buffer = NULL;
457
458                 /**
459                  * bit7 = 1, host beendet mit PID_OUT DATA1 Zero
460                  * bit7 = 0, device sendet ein PID_IN DATA1 Zero Packet als bestaetigung
461                  */
462                 /* check bit 7 of bmRequestType */
463                 if (bmRequestType & 0x80) {
464                         td->pid = USB_PID_OUT;
465                 } else {
466                         td->pid = USB_PID_IN;
467                 }
468                 /**** send token ****/
469                 hcdi_enqueue(td, irp->dev->ohci);
470                 free(td);
471                 break;
472
473         case USB_BULK:
474                 //u8 runloop=1;
475                 //u16 restlength = irp->len;
476                 //char * td_buf_ptr=irp->buffer;
477
478                 /* schleife die die tds generiert */
479                 while (runloop) {
480                         td = usb_create_transfer_descriptor(irp);
481                         td->endpoint = td->endpoint & 0x7F;                             /* clear direction bit */
482
483                         /* max packet size for given endpoint */
484                         td->actlen = irp->epsize;
485
486                         /* Generate In Packet  */
487                         if (irp->endpoint & 0x80)
488                                 td->pid = USB_PID_IN;
489                         else
490                                 /* Generate Out Packet */
491                                 td->pid = USB_PID_OUT;
492
493                         /* stop loop if all bytes are send */
494                         if (restlength <= irp->epsize) {
495                                 runloop = 0;
496                                 td->actlen = restlength;
497                         }
498
499                         td->buffer = td_buf_ptr;
500                         /* move pointer for next packet */
501                         td_buf_ptr = td_buf_ptr + irp->epsize;
502
503                         td->togl = togl;
504                         togl = togl ? 0 : 1;
505                                 /**** send token ****/
506                         hcdi_enqueue(td, irp->dev->ohci);
507                         free(td);
508                 }
509                 /* next togl */
510                 //if(td->pid == USB_PID_OUT) {
511                 //if(togl==0) togl=1; else togl=0;
512                 //}
513                 irp->dev->epTogl[(irp->endpoint & 0x7F)] = togl;
514
515                 break;
516         
517         case USB_INTR:
518                 //u8 runloop=1;
519                 //u16 restlength = irp->len;
520                 //char * td_buf_ptr=irp->buffer;
521
522                 /* schleife die die tds generiert */
523                 while (runloop && (restlength > 0)) {
524                         td = usb_create_transfer_descriptor(irp);
525                         /* max packet size for given endpoint */
526                         td->actlen = irp->epsize;
527
528                         td->pid = USB_PID_IN;
529                         /* TODO: USB_PID_OUT */
530
531                         /* stop loop if all bytes are send */
532                         if (restlength < irp->epsize) {
533                                 runloop = 0;
534                                 td->actlen = restlength;
535                         }
536
537                         td->buffer = td_buf_ptr;
538                         /* move pointer for next packet */
539                         td_buf_ptr += irp->epsize;
540
541                         td->togl = togl;
542                         togl = togl ? 0 : 1;
543                                 
544                         /**** send token ****/
545                         hcdi_enqueue(td, irp->dev->ohci);
546                         restlength = restlength - irp->epsize;
547                         free(td);
548                 }
549                 break;
550                 irp->dev->epTogl[(irp->endpoint & 0x7F)] = togl;
551         }
552         hcdi_fire(irp->dev->ohci);
553
554         return 1;
555 }
556
557
558
559 /** 
560  * Create a transfer descriptor with an parent irp.
561  */
562 struct usb_transfer_descriptor *usb_create_transfer_descriptor(struct usb_irp * irp)
563 {
564         struct usb_transfer_descriptor *td =
565                         (struct usb_transfer_descriptor *) malloc(sizeof(struct usb_transfer_descriptor));
566
567         td->devaddress = irp->dev->address;
568         td->endpoint = irp->endpoint;
569         td->iso = 0;
570         td->state = USB_TRANSFER_DESCR_NONE;
571         td->maxp = irp->epsize;
572         td->fullspeed = irp->dev->fullspeed;
573         td->type = irp->type;
574
575         return td;
576 }
577