]> git.sur5r.net Git - u-boot/blob - common/usb_kbd.c
87f4125a9f2f19ef92ca88b92ea8160c3961cabe
[u-boot] / common / usb_kbd.c
1 /*
2  * (C) Copyright 2001
3  * Denis Peter, MPL AG Switzerland
4  *
5  * Part of this source has been derived from the Linux USB
6  * project.
7  *
8  * SPDX-License-Identifier:     GPL-2.0+
9  */
10 #include <common.h>
11 #include <malloc.h>
12 #include <stdio_dev.h>
13 #include <asm/byteorder.h>
14
15 #include <usb.h>
16
17 /*
18  * If overwrite_console returns 1, the stdin, stderr and stdout
19  * are switched to the serial port, else the settings in the
20  * environment are used
21  */
22 #ifdef CONFIG_SYS_CONSOLE_OVERWRITE_ROUTINE
23 extern int overwrite_console(void);
24 #else
25 int overwrite_console(void)
26 {
27         return 0;
28 }
29 #endif
30
31 /* Keyboard sampling rate */
32 #define REPEAT_RATE     (40 / 4)        /* 40msec -> 25cps */
33 #define REPEAT_DELAY    10              /* 10 x REPEAT_RATE = 400msec */
34
35 #define NUM_LOCK        0x53
36 #define CAPS_LOCK       0x39
37 #define SCROLL_LOCK     0x47
38
39 /* Modifier bits */
40 #define LEFT_CNTR       (1 << 0)
41 #define LEFT_SHIFT      (1 << 1)
42 #define LEFT_ALT        (1 << 2)
43 #define LEFT_GUI        (1 << 3)
44 #define RIGHT_CNTR      (1 << 4)
45 #define RIGHT_SHIFT     (1 << 5)
46 #define RIGHT_ALT       (1 << 6)
47 #define RIGHT_GUI       (1 << 7)
48
49 /* Size of the keyboard buffer */
50 #define USB_KBD_BUFFER_LEN      0x20
51
52 /* Device name */
53 #define DEVNAME                 "usbkbd"
54
55 /* Keyboard maps */
56 static const unsigned char usb_kbd_numkey[] = {
57         '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
58         '\r', 0x1b, '\b', '\t', ' ', '-', '=', '[', ']',
59         '\\', '#', ';', '\'', '`', ',', '.', '/'
60 };
61 static const unsigned char usb_kbd_numkey_shifted[] = {
62         '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',
63         '\r', 0x1b, '\b', '\t', ' ', '_', '+', '{', '}',
64         '|', '~', ':', '"', '~', '<', '>', '?'
65 };
66
67 static const unsigned char usb_kbd_num_keypad[] = {
68         '/', '*', '-', '+', '\r',
69         '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
70         '.', 0, 0, 0, '='
71 };
72
73 /*
74  * map arrow keys to ^F/^B ^N/^P, can't really use the proper
75  * ANSI sequence for arrow keys because the queuing code breaks
76  * when a single keypress expands to 3 queue elements
77  */
78 static const unsigned char usb_kbd_arrow[] = {
79         0x6, 0x2, 0xe, 0x10
80 };
81
82 /*
83  * NOTE: It's important for the NUM, CAPS, SCROLL-lock bits to be in this
84  *       order. See usb_kbd_setled() function!
85  */
86 #define USB_KBD_NUMLOCK         (1 << 0)
87 #define USB_KBD_CAPSLOCK        (1 << 1)
88 #define USB_KBD_SCROLLLOCK      (1 << 2)
89 #define USB_KBD_CTRL            (1 << 3)
90
91 #define USB_KBD_LEDMASK         \
92         (USB_KBD_NUMLOCK | USB_KBD_CAPSLOCK | USB_KBD_SCROLLLOCK)
93
94 /*
95  * USB Keyboard reports are 8 bytes in boot protocol.
96  * Appendix B of HID Device Class Definition 1.11
97  */
98 #define USB_KBD_BOOT_REPORT_SIZE 8
99
100 struct usb_kbd_pdata {
101         uint32_t        repeat_delay;
102
103         uint32_t        usb_in_pointer;
104         uint32_t        usb_out_pointer;
105         uint8_t         usb_kbd_buffer[USB_KBD_BUFFER_LEN];
106
107         uint8_t         *new;
108         uint8_t         old[USB_KBD_BOOT_REPORT_SIZE];
109
110         uint8_t         flags;
111 };
112
113 extern int __maybe_unused net_busy_flag;
114
115 /* The period of time between two calls of usb_kbd_testc(). */
116 static unsigned long __maybe_unused kbd_testc_tms;
117
118 /* Generic keyboard event polling. */
119 void usb_kbd_generic_poll(void)
120 {
121         struct stdio_dev *dev;
122         struct usb_device *usb_kbd_dev;
123         struct usb_kbd_pdata *data;
124         struct usb_interface *iface;
125         struct usb_endpoint_descriptor *ep;
126         int pipe;
127         int maxp;
128
129         /* Get the pointer to USB Keyboard device pointer */
130         dev = stdio_get_by_name(DEVNAME);
131         usb_kbd_dev = (struct usb_device *)dev->priv;
132         data = usb_kbd_dev->privptr;
133         iface = &usb_kbd_dev->config.if_desc[0];
134         ep = &iface->ep_desc[0];
135         pipe = usb_rcvintpipe(usb_kbd_dev, ep->bEndpointAddress);
136
137         /* Submit a interrupt transfer request */
138         maxp = usb_maxpacket(usb_kbd_dev, pipe);
139         usb_submit_int_msg(usb_kbd_dev, pipe, data->new,
140                 min(maxp, USB_KBD_BOOT_REPORT_SIZE),
141                 ep->bInterval);
142 }
143
144 /* Puts character in the queue and sets up the in and out pointer. */
145 static void usb_kbd_put_queue(struct usb_kbd_pdata *data, char c)
146 {
147         if (data->usb_in_pointer == USB_KBD_BUFFER_LEN - 1) {
148                 /* Check for buffer full. */
149                 if (data->usb_out_pointer == 0)
150                         return;
151
152                 data->usb_in_pointer = 0;
153         } else {
154                 /* Check for buffer full. */
155                 if (data->usb_in_pointer == data->usb_out_pointer - 1)
156                         return;
157
158                 data->usb_in_pointer++;
159         }
160
161         data->usb_kbd_buffer[data->usb_in_pointer] = c;
162 }
163
164 /*
165  * Set the LEDs. Since this is used in the irq routine, the control job is
166  * issued with a timeout of 0. This means, that the job is queued without
167  * waiting for job completion.
168  */
169 static void usb_kbd_setled(struct usb_device *dev)
170 {
171         struct usb_interface *iface = &dev->config.if_desc[0];
172         struct usb_kbd_pdata *data = dev->privptr;
173         ALLOC_ALIGN_BUFFER(uint32_t, leds, 1, USB_DMA_MINALIGN);
174
175         *leds = data->flags & USB_KBD_LEDMASK;
176         usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
177                 USB_REQ_SET_REPORT, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
178                 0x200, iface->desc.bInterfaceNumber, leds, 1, 0);
179 }
180
181 #define CAPITAL_MASK    0x20
182 /* Translate the scancode in ASCII */
183 static int usb_kbd_translate(struct usb_kbd_pdata *data, unsigned char scancode,
184                                 unsigned char modifier, int pressed)
185 {
186         uint8_t keycode = 0;
187
188         /* Key released */
189         if (pressed == 0) {
190                 data->repeat_delay = 0;
191                 return 0;
192         }
193
194         if (pressed == 2) {
195                 data->repeat_delay++;
196                 if (data->repeat_delay < REPEAT_DELAY)
197                         return 0;
198
199                 data->repeat_delay = REPEAT_DELAY;
200         }
201
202         /* Alphanumeric values */
203         if ((scancode > 3) && (scancode <= 0x1d)) {
204                 keycode = scancode - 4 + 'a';
205
206                 if (data->flags & USB_KBD_CAPSLOCK)
207                         keycode &= ~CAPITAL_MASK;
208
209                 if (modifier & (LEFT_SHIFT | RIGHT_SHIFT)) {
210                         /* Handle CAPSLock + Shift pressed simultaneously */
211                         if (keycode & CAPITAL_MASK)
212                                 keycode &= ~CAPITAL_MASK;
213                         else
214                                 keycode |= CAPITAL_MASK;
215                 }
216         }
217
218         if ((scancode > 0x1d) && (scancode < 0x3a)) {
219                 /* Shift pressed */
220                 if (modifier & (LEFT_SHIFT | RIGHT_SHIFT))
221                         keycode = usb_kbd_numkey_shifted[scancode - 0x1e];
222                 else
223                         keycode = usb_kbd_numkey[scancode - 0x1e];
224         }
225
226         /* Arrow keys */
227         if ((scancode >= 0x4f) && (scancode <= 0x52))
228                 keycode = usb_kbd_arrow[scancode - 0x4f];
229
230         /* Numeric keypad */
231         if ((scancode >= 0x54) && (scancode <= 0x67))
232                 keycode = usb_kbd_num_keypad[scancode - 0x54];
233
234         if (data->flags & USB_KBD_CTRL)
235                 keycode = scancode - 0x3;
236
237         if (pressed == 1) {
238                 if (scancode == NUM_LOCK) {
239                         data->flags ^= USB_KBD_NUMLOCK;
240                         return 1;
241                 }
242
243                 if (scancode == CAPS_LOCK) {
244                         data->flags ^= USB_KBD_CAPSLOCK;
245                         return 1;
246                 }
247                 if (scancode == SCROLL_LOCK) {
248                         data->flags ^= USB_KBD_SCROLLLOCK;
249                         return 1;
250                 }
251         }
252
253         /* Report keycode if any */
254         if (keycode) {
255                 debug("%c", keycode);
256                 usb_kbd_put_queue(data, keycode);
257         }
258
259         return 0;
260 }
261
262 static uint32_t usb_kbd_service_key(struct usb_device *dev, int i, int up)
263 {
264         uint32_t res = 0;
265         struct usb_kbd_pdata *data = dev->privptr;
266         uint8_t *new;
267         uint8_t *old;
268
269         if (up) {
270                 new = data->old;
271                 old = data->new;
272         } else {
273                 new = data->new;
274                 old = data->old;
275         }
276
277         if ((old[i] > 3) &&
278             (memscan(new + 2, old[i], USB_KBD_BOOT_REPORT_SIZE - 2) ==
279                         new + USB_KBD_BOOT_REPORT_SIZE)) {
280                 res |= usb_kbd_translate(data, old[i], data->new[0], up);
281         }
282
283         return res;
284 }
285
286 /* Interrupt service routine */
287 static int usb_kbd_irq_worker(struct usb_device *dev)
288 {
289         struct usb_kbd_pdata *data = dev->privptr;
290         int i, res = 0;
291
292         /* No combo key pressed */
293         if (data->new[0] == 0x00)
294                 data->flags &= ~USB_KBD_CTRL;
295         /* Left or Right Ctrl pressed */
296         else if ((data->new[0] == LEFT_CNTR) || (data->new[0] == RIGHT_CNTR))
297                 data->flags |= USB_KBD_CTRL;
298
299         for (i = 2; i < USB_KBD_BOOT_REPORT_SIZE; i++) {
300                 res |= usb_kbd_service_key(dev, i, 0);
301                 res |= usb_kbd_service_key(dev, i, 1);
302         }
303
304         /* Key is still pressed */
305         if ((data->new[2] > 3) && (data->old[2] == data->new[2]))
306                 res |= usb_kbd_translate(data, data->new[2], data->new[0], 2);
307
308         if (res == 1)
309                 usb_kbd_setled(dev);
310
311         memcpy(data->old, data->new, USB_KBD_BOOT_REPORT_SIZE);
312
313         return 1;
314 }
315
316 /* Keyboard interrupt handler */
317 static int usb_kbd_irq(struct usb_device *dev)
318 {
319         if ((dev->irq_status != 0) ||
320             (dev->irq_act_len != USB_KBD_BOOT_REPORT_SIZE)) {
321                 debug("USB KBD: Error %lX, len %d\n",
322                       dev->irq_status, dev->irq_act_len);
323                 return 1;
324         }
325
326         return usb_kbd_irq_worker(dev);
327 }
328
329 /* Interrupt polling */
330 static inline void usb_kbd_poll_for_event(struct usb_device *dev)
331 {
332 #if     defined(CONFIG_SYS_USB_EVENT_POLL)
333         struct usb_interface *iface;
334         struct usb_endpoint_descriptor *ep;
335         struct usb_kbd_pdata *data;
336         int pipe;
337         int maxp;
338
339         /* Get the pointer to USB Keyboard device pointer */
340         data = dev->privptr;
341         iface = &dev->config.if_desc[0];
342         ep = &iface->ep_desc[0];
343         pipe = usb_rcvintpipe(dev, ep->bEndpointAddress);
344
345         /* Submit a interrupt transfer request */
346         maxp = usb_maxpacket(dev, pipe);
347         usb_submit_int_msg(dev, pipe, &data->new[0],
348                 min(maxp, USB_KBD_BOOT_REPORT_SIZE),
349                 ep->bInterval);
350
351         usb_kbd_irq_worker(dev);
352 #elif   defined(CONFIG_SYS_USB_EVENT_POLL_VIA_CONTROL_EP)
353         struct usb_interface *iface;
354         struct usb_kbd_pdata *data = dev->privptr;
355         iface = &dev->config.if_desc[0];
356         usb_get_report(dev, iface->desc.bInterfaceNumber,
357                        1, 0, data->new, USB_KBD_BOOT_REPORT_SIZE);
358         if (memcmp(data->old, data->new, USB_KBD_BOOT_REPORT_SIZE))
359                 usb_kbd_irq_worker(dev);
360 #endif
361 }
362
363 /* test if a character is in the queue */
364 static int usb_kbd_testc(struct stdio_dev *sdev)
365 {
366         struct stdio_dev *dev;
367         struct usb_device *usb_kbd_dev;
368         struct usb_kbd_pdata *data;
369
370 #ifdef CONFIG_CMD_NET
371         /*
372          * If net_busy_flag is 1, NET transfer is running,
373          * then we check key-pressed every second (first check may be
374          * less than 1 second) to improve TFTP booting performance.
375          */
376         if (net_busy_flag && (get_timer(kbd_testc_tms) < CONFIG_SYS_HZ))
377                 return 0;
378         kbd_testc_tms = get_timer(0);
379 #endif
380         dev = stdio_get_by_name(DEVNAME);
381         usb_kbd_dev = (struct usb_device *)dev->priv;
382         data = usb_kbd_dev->privptr;
383
384         usb_kbd_poll_for_event(usb_kbd_dev);
385
386         return !(data->usb_in_pointer == data->usb_out_pointer);
387 }
388
389 /* gets the character from the queue */
390 static int usb_kbd_getc(struct stdio_dev *sdev)
391 {
392         struct stdio_dev *dev;
393         struct usb_device *usb_kbd_dev;
394         struct usb_kbd_pdata *data;
395
396         dev = stdio_get_by_name(DEVNAME);
397         usb_kbd_dev = (struct usb_device *)dev->priv;
398         data = usb_kbd_dev->privptr;
399
400         while (data->usb_in_pointer == data->usb_out_pointer)
401                 usb_kbd_poll_for_event(usb_kbd_dev);
402
403         if (data->usb_out_pointer == USB_KBD_BUFFER_LEN - 1)
404                 data->usb_out_pointer = 0;
405         else
406                 data->usb_out_pointer++;
407
408         return data->usb_kbd_buffer[data->usb_out_pointer];
409 }
410
411 /* probes the USB device dev for keyboard type. */
412 static int usb_kbd_probe(struct usb_device *dev, unsigned int ifnum)
413 {
414         struct usb_interface *iface;
415         struct usb_endpoint_descriptor *ep;
416         struct usb_kbd_pdata *data;
417         int pipe, maxp;
418
419         if (dev->descriptor.bNumConfigurations != 1)
420                 return 0;
421
422         iface = &dev->config.if_desc[ifnum];
423
424         if (iface->desc.bInterfaceClass != 3)
425                 return 0;
426
427         if (iface->desc.bInterfaceSubClass != 1)
428                 return 0;
429
430         if (iface->desc.bInterfaceProtocol != 1)
431                 return 0;
432
433         if (iface->desc.bNumEndpoints != 1)
434                 return 0;
435
436         ep = &iface->ep_desc[0];
437
438         /* Check if endpoint 1 is interrupt endpoint */
439         if (!(ep->bEndpointAddress & 0x80))
440                 return 0;
441
442         if ((ep->bmAttributes & 3) != 3)
443                 return 0;
444
445         debug("USB KBD: found set protocol...\n");
446
447         data = malloc(sizeof(struct usb_kbd_pdata));
448         if (!data) {
449                 printf("USB KBD: Error allocating private data\n");
450                 return 0;
451         }
452
453         /* Clear private data */
454         memset(data, 0, sizeof(struct usb_kbd_pdata));
455
456         /* allocate input buffer aligned and sized to USB DMA alignment */
457         data->new = memalign(USB_DMA_MINALIGN,
458                 roundup(USB_KBD_BOOT_REPORT_SIZE, USB_DMA_MINALIGN));
459
460         /* Insert private data into USB device structure */
461         dev->privptr = data;
462
463         /* Set IRQ handler */
464         dev->irq_handle = usb_kbd_irq;
465
466         pipe = usb_rcvintpipe(dev, ep->bEndpointAddress);
467         maxp = usb_maxpacket(dev, pipe);
468
469         /* We found a USB Keyboard, install it. */
470         usb_set_protocol(dev, iface->desc.bInterfaceNumber, 0);
471
472         debug("USB KBD: found set idle...\n");
473         usb_set_idle(dev, iface->desc.bInterfaceNumber, REPEAT_RATE, 0);
474
475         debug("USB KBD: enable interrupt pipe...\n");
476         if (usb_submit_int_msg(dev, pipe, data->new,
477                                min(maxp, USB_KBD_BOOT_REPORT_SIZE),
478                                ep->bInterval) < 0) {
479                 printf("Failed to get keyboard state from device %04x:%04x\n",
480                        dev->descriptor.idVendor, dev->descriptor.idProduct);
481                 /* Abort, we don't want to use that non-functional keyboard. */
482                 return 0;
483         }
484
485         /* Success. */
486         return 1;
487 }
488
489 /* Search for keyboard and register it if found. */
490 int drv_usb_kbd_init(void)
491 {
492         struct stdio_dev usb_kbd_dev, *old_dev;
493         struct usb_device *dev;
494         char *stdinname = getenv("stdin");
495         int error, i;
496
497         /* Scan all USB Devices */
498         for (i = 0; i < USB_MAX_DEVICE; i++) {
499                 /* Get USB device. */
500                 dev = usb_get_dev_index(i);
501                 if (!dev)
502                         return -1;
503
504                 if (dev->devnum == -1)
505                         continue;
506
507                 /* Try probing the keyboard */
508                 if (usb_kbd_probe(dev, 0) != 1)
509                         continue;
510
511                 /* We found a keyboard, check if it is already registered. */
512                 debug("USB KBD: found set up device.\n");
513                 old_dev = stdio_get_by_name(DEVNAME);
514                 if (old_dev) {
515                         /* Already registered, just return ok. */
516                         debug("USB KBD: is already registered.\n");
517                         usb_kbd_deregister();
518                         return 1;
519                 }
520
521                 /* Register the keyboard */
522                 debug("USB KBD: register.\n");
523                 memset(&usb_kbd_dev, 0, sizeof(struct stdio_dev));
524                 strcpy(usb_kbd_dev.name, DEVNAME);
525                 usb_kbd_dev.flags =  DEV_FLAGS_INPUT | DEV_FLAGS_SYSTEM;
526                 usb_kbd_dev.getc = usb_kbd_getc;
527                 usb_kbd_dev.tstc = usb_kbd_testc;
528                 usb_kbd_dev.priv = (void *)dev;
529                 error = stdio_register(&usb_kbd_dev);
530                 if (error)
531                         return error;
532
533 #ifdef CONFIG_CONSOLE_MUX
534                 error = iomux_doenv(stdin, stdinname);
535                 if (error)
536                         return error;
537 #else
538                 /* Check if this is the standard input device. */
539                 if (strcmp(stdinname, DEVNAME))
540                         return 1;
541
542                 /* Reassign the console */
543                 if (overwrite_console())
544                         return 1;
545
546                 error = console_assign(stdin, DEVNAME);
547                 if (error)
548                         return error;
549 #endif
550
551                 return 1;
552         }
553
554         /* No USB Keyboard found */
555         return -1;
556 }
557
558 /* Deregister the keyboard. */
559 int usb_kbd_deregister(void)
560 {
561 #ifdef CONFIG_SYS_STDIO_DEREGISTER
562         return stdio_deregister(DEVNAME);
563 #else
564         return 1;
565 #endif
566 }