1 // SPDX-License-Identifier: GPL-2.0+
4 * Denis Peter, MPL AG Switzerland
6 * Part of this source has been derived from the Linux USB
17 #include <stdio_dev.h>
19 #include <asm/byteorder.h>
21 #include <asm/state.h>
27 * If overwrite_console returns 1, the stdin, stderr and stdout
28 * are switched to the serial port, else the settings in the
29 * environment are used
31 #ifdef CONFIG_SYS_CONSOLE_OVERWRITE_ROUTINE
32 extern int overwrite_console(void);
34 int overwrite_console(void)
40 /* Keyboard sampling rate */
41 #define REPEAT_RATE 40 /* 40msec -> 25cps */
42 #define REPEAT_DELAY 10 /* 10 x REPEAT_RATE = 400msec */
45 #define CAPS_LOCK 0x39
46 #define SCROLL_LOCK 0x47
49 #define LEFT_CNTR (1 << 0)
50 #define LEFT_SHIFT (1 << 1)
51 #define LEFT_ALT (1 << 2)
52 #define LEFT_GUI (1 << 3)
53 #define RIGHT_CNTR (1 << 4)
54 #define RIGHT_SHIFT (1 << 5)
55 #define RIGHT_ALT (1 << 6)
56 #define RIGHT_GUI (1 << 7)
58 /* Size of the keyboard buffer */
59 #define USB_KBD_BUFFER_LEN 0x20
62 #define DEVNAME "usbkbd"
65 static const unsigned char usb_kbd_numkey[] = {
66 '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
67 '\r', 0x1b, '\b', '\t', ' ', '-', '=', '[', ']',
68 '\\', '#', ';', '\'', '`', ',', '.', '/'
70 static const unsigned char usb_kbd_numkey_shifted[] = {
71 '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',
72 '\r', 0x1b, '\b', '\t', ' ', '_', '+', '{', '}',
73 '|', '~', ':', '"', '~', '<', '>', '?'
76 static const unsigned char usb_kbd_num_keypad[] = {
77 '/', '*', '-', '+', '\r',
78 '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
82 static const u8 usb_special_keys[] = {
83 #ifdef CONFIG_USB_KEYBOARD_FN_KEYS
84 '2', 'H', '5', '3', 'F', '6', 'C', 'D', 'B', 'A'
91 * NOTE: It's important for the NUM, CAPS, SCROLL-lock bits to be in this
92 * order. See usb_kbd_setled() function!
94 #define USB_KBD_NUMLOCK (1 << 0)
95 #define USB_KBD_CAPSLOCK (1 << 1)
96 #define USB_KBD_SCROLLLOCK (1 << 2)
97 #define USB_KBD_CTRL (1 << 3)
99 #define USB_KBD_LEDMASK \
100 (USB_KBD_NUMLOCK | USB_KBD_CAPSLOCK | USB_KBD_SCROLLLOCK)
102 struct usb_kbd_pdata {
103 unsigned long intpipe;
106 unsigned long last_report;
107 struct int_queue *intq;
109 uint32_t repeat_delay;
111 uint32_t usb_in_pointer;
112 uint32_t usb_out_pointer;
113 uint8_t usb_kbd_buffer[USB_KBD_BUFFER_LEN];
116 uint8_t old[USB_KBD_BOOT_REPORT_SIZE];
121 extern int __maybe_unused net_busy_flag;
123 /* The period of time between two calls of usb_kbd_testc(). */
124 static unsigned long kbd_testc_tms;
126 /* Puts character in the queue and sets up the in and out pointer. */
127 static void usb_kbd_put_queue(struct usb_kbd_pdata *data, u8 c)
129 if (data->usb_in_pointer == USB_KBD_BUFFER_LEN - 1) {
130 /* Check for buffer full. */
131 if (data->usb_out_pointer == 0)
134 data->usb_in_pointer = 0;
136 /* Check for buffer full. */
137 if (data->usb_in_pointer == data->usb_out_pointer - 1)
140 data->usb_in_pointer++;
143 data->usb_kbd_buffer[data->usb_in_pointer] = c;
147 * Set the LEDs. Since this is used in the irq routine, the control job is
148 * issued with a timeout of 0. This means, that the job is queued without
149 * waiting for job completion.
151 static void usb_kbd_setled(struct usb_device *dev)
153 struct usb_interface *iface = &dev->config.if_desc[0];
154 struct usb_kbd_pdata *data = dev->privptr;
155 ALLOC_ALIGN_BUFFER(uint32_t, leds, 1, USB_DMA_MINALIGN);
157 *leds = data->flags & USB_KBD_LEDMASK;
158 usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
159 USB_REQ_SET_REPORT, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
160 0x200, iface->desc.bInterfaceNumber, leds, 1, 0);
163 #define CAPITAL_MASK 0x20
164 /* Translate the scancode in ASCII */
165 static int usb_kbd_translate(struct usb_kbd_pdata *data, unsigned char scancode,
166 unsigned char modifier, int pressed)
172 data->repeat_delay = 0;
177 data->repeat_delay++;
178 if (data->repeat_delay < REPEAT_DELAY)
181 data->repeat_delay = REPEAT_DELAY;
184 /* Alphanumeric values */
185 if ((scancode > 3) && (scancode <= 0x1d)) {
186 keycode = scancode - 4 + 'a';
188 if (data->flags & USB_KBD_CAPSLOCK)
189 keycode &= ~CAPITAL_MASK;
191 if (modifier & (LEFT_SHIFT | RIGHT_SHIFT)) {
192 /* Handle CAPSLock + Shift pressed simultaneously */
193 if (keycode & CAPITAL_MASK)
194 keycode &= ~CAPITAL_MASK;
196 keycode |= CAPITAL_MASK;
200 if ((scancode > 0x1d) && (scancode < 0x39)) {
202 if (modifier & (LEFT_SHIFT | RIGHT_SHIFT))
203 keycode = usb_kbd_numkey_shifted[scancode - 0x1e];
205 keycode = usb_kbd_numkey[scancode - 0x1e];
209 if ((scancode >= 0x54) && (scancode <= 0x67))
210 keycode = usb_kbd_num_keypad[scancode - 0x54];
212 if (data->flags & USB_KBD_CTRL)
213 keycode = scancode - 0x3;
216 if (scancode == NUM_LOCK) {
217 data->flags ^= USB_KBD_NUMLOCK;
221 if (scancode == CAPS_LOCK) {
222 data->flags ^= USB_KBD_CAPSLOCK;
225 if (scancode == SCROLL_LOCK) {
226 data->flags ^= USB_KBD_SCROLLLOCK;
231 /* Report keycode if any */
233 debug("%c", keycode);
234 usb_kbd_put_queue(data, keycode);
238 #ifdef CONFIG_USB_KEYBOARD_FN_KEYS
239 if (scancode < 0x3a || scancode > 0x52 ||
240 scancode == 0x46 || scancode == 0x47)
243 usb_kbd_put_queue(data, 0x1b);
244 if (scancode < 0x3e) {
246 usb_kbd_put_queue(data, 0x4f);
247 usb_kbd_put_queue(data, scancode - 0x3a + 'P');
250 usb_kbd_put_queue(data, '[');
251 if (scancode < 0x42) {
253 usb_kbd_put_queue(data, '1');
254 if (scancode == 0x3e)
256 keycode = scancode - 0x3f + '7';
257 } else if (scancode < 0x49) {
259 usb_kbd_put_queue(data, '2');
262 keycode = scancode - 0x42 + '0';
265 * INSERT, HOME, PAGE UP, DELETE, END, PAGE DOWN,
266 * RIGHT, LEFT, DOWN, UP
268 keycode = usb_special_keys[scancode - 0x49];
270 usb_kbd_put_queue(data, keycode);
271 if (scancode < 0x4f && scancode != 0x4a && scancode != 0x4d)
272 usb_kbd_put_queue(data, '~');
275 /* Left, Right, Up, Down */
276 if (scancode > 0x4e && scancode < 0x53) {
277 usb_kbd_put_queue(data, 0x1b);
278 usb_kbd_put_queue(data, '[');
279 usb_kbd_put_queue(data, usb_special_keys[scancode - 0x4f]);
283 #endif /* CONFIG_USB_KEYBOARD_FN_KEYS */
286 static uint32_t usb_kbd_service_key(struct usb_device *dev, int i, int up)
289 struct usb_kbd_pdata *data = dev->privptr;
302 (memscan(new + 2, old[i], USB_KBD_BOOT_REPORT_SIZE - 2) ==
303 new + USB_KBD_BOOT_REPORT_SIZE)) {
304 res |= usb_kbd_translate(data, old[i], data->new[0], up);
310 /* Interrupt service routine */
311 static int usb_kbd_irq_worker(struct usb_device *dev)
313 struct usb_kbd_pdata *data = dev->privptr;
316 /* No combo key pressed */
317 if (data->new[0] == 0x00)
318 data->flags &= ~USB_KBD_CTRL;
319 /* Left or Right Ctrl pressed */
320 else if ((data->new[0] == LEFT_CNTR) || (data->new[0] == RIGHT_CNTR))
321 data->flags |= USB_KBD_CTRL;
323 for (i = 2; i < USB_KBD_BOOT_REPORT_SIZE; i++) {
324 res |= usb_kbd_service_key(dev, i, 0);
325 res |= usb_kbd_service_key(dev, i, 1);
328 /* Key is still pressed */
329 if ((data->new[2] > 3) && (data->old[2] == data->new[2]))
330 res |= usb_kbd_translate(data, data->new[2], data->new[0], 2);
335 memcpy(data->old, data->new, USB_KBD_BOOT_REPORT_SIZE);
340 /* Keyboard interrupt handler */
341 static int usb_kbd_irq(struct usb_device *dev)
343 if ((dev->irq_status != 0) ||
344 (dev->irq_act_len != USB_KBD_BOOT_REPORT_SIZE)) {
345 debug("USB KBD: Error %lX, len %d\n",
346 dev->irq_status, dev->irq_act_len);
350 return usb_kbd_irq_worker(dev);
353 /* Interrupt polling */
354 static inline void usb_kbd_poll_for_event(struct usb_device *dev)
356 #if defined(CONFIG_SYS_USB_EVENT_POLL)
357 struct usb_kbd_pdata *data = dev->privptr;
359 /* Submit an interrupt transfer request */
360 if (usb_int_msg(dev, data->intpipe, &data->new[0],
361 data->intpktsize, data->intinterval, true) >= 0)
362 usb_kbd_irq_worker(dev);
363 #elif defined(CONFIG_SYS_USB_EVENT_POLL_VIA_CONTROL_EP) || \
364 defined(CONFIG_SYS_USB_EVENT_POLL_VIA_INT_QUEUE)
365 #if defined(CONFIG_SYS_USB_EVENT_POLL_VIA_CONTROL_EP)
366 struct usb_interface *iface;
367 struct usb_kbd_pdata *data = dev->privptr;
368 iface = &dev->config.if_desc[0];
369 usb_get_report(dev, iface->desc.bInterfaceNumber,
370 1, 0, data->new, USB_KBD_BOOT_REPORT_SIZE);
371 if (memcmp(data->old, data->new, USB_KBD_BOOT_REPORT_SIZE)) {
372 usb_kbd_irq_worker(dev);
374 struct usb_kbd_pdata *data = dev->privptr;
375 if (poll_int_queue(dev, data->intq)) {
376 usb_kbd_irq_worker(dev);
377 /* We've consumed all queued int packets, create new */
378 destroy_int_queue(dev, data->intq);
379 data->intq = create_int_queue(dev, data->intpipe, 1,
380 USB_KBD_BOOT_REPORT_SIZE, data->new,
383 data->last_report = get_timer(0);
384 /* Repeat last usb hid report every REPEAT_RATE ms for keyrepeat */
385 } else if (data->last_report != -1 &&
386 get_timer(data->last_report) > REPEAT_RATE) {
387 usb_kbd_irq_worker(dev);
388 data->last_report = get_timer(0);
393 /* test if a character is in the queue */
394 static int usb_kbd_testc(struct stdio_dev *sdev)
396 struct stdio_dev *dev;
397 struct usb_device *usb_kbd_dev;
398 struct usb_kbd_pdata *data;
401 * Polling the keyboard for an event can take dozens of milliseconds.
402 * Add a delay between polls to avoid blocking activity which polls
403 * rapidly, like the UEFI console timer.
405 unsigned long poll_delay = CONFIG_SYS_HZ / 50;
407 #ifdef CONFIG_CMD_NET
409 * If net_busy_flag is 1, NET transfer is running,
410 * then we check key-pressed every second (first check may be
411 * less than 1 second) to improve TFTP booting performance.
414 poll_delay = CONFIG_SYS_HZ;
417 #ifdef CONFIG_SANDBOX
419 * Skip delaying polls if a test requests it.
421 if (state_get_skip_delays())
425 dev = stdio_get_by_name(sdev->name);
426 usb_kbd_dev = (struct usb_device *)dev->priv;
427 data = usb_kbd_dev->privptr;
429 if (get_timer(kbd_testc_tms) >= poll_delay) {
430 usb_kbd_poll_for_event(usb_kbd_dev);
431 kbd_testc_tms = get_timer(0);
434 return !(data->usb_in_pointer == data->usb_out_pointer);
437 /* gets the character from the queue */
438 static int usb_kbd_getc(struct stdio_dev *sdev)
440 struct stdio_dev *dev;
441 struct usb_device *usb_kbd_dev;
442 struct usb_kbd_pdata *data;
444 dev = stdio_get_by_name(sdev->name);
445 usb_kbd_dev = (struct usb_device *)dev->priv;
446 data = usb_kbd_dev->privptr;
448 while (data->usb_in_pointer == data->usb_out_pointer) {
450 usb_kbd_poll_for_event(usb_kbd_dev);
453 if (data->usb_out_pointer == USB_KBD_BUFFER_LEN - 1)
454 data->usb_out_pointer = 0;
456 data->usb_out_pointer++;
458 return data->usb_kbd_buffer[data->usb_out_pointer];
461 /* probes the USB device dev for keyboard type. */
462 static int usb_kbd_probe_dev(struct usb_device *dev, unsigned int ifnum)
464 struct usb_interface *iface;
465 struct usb_endpoint_descriptor *ep;
466 struct usb_kbd_pdata *data;
469 if (dev->descriptor.bNumConfigurations != 1)
472 iface = &dev->config.if_desc[ifnum];
474 if (iface->desc.bInterfaceClass != USB_CLASS_HID)
477 if (iface->desc.bInterfaceSubClass != USB_SUB_HID_BOOT)
480 if (iface->desc.bInterfaceProtocol != USB_PROT_HID_KEYBOARD)
483 for (epNum = 0; epNum < iface->desc.bNumEndpoints; epNum++) {
484 ep = &iface->ep_desc[epNum];
486 /* Check if endpoint is interrupt IN endpoint */
487 if ((ep->bmAttributes & 3) != 3)
490 if (ep->bEndpointAddress & 0x80)
494 if (epNum == iface->desc.bNumEndpoints)
497 debug("USB KBD: found interrupt EP: 0x%x\n", ep->bEndpointAddress);
499 data = malloc(sizeof(struct usb_kbd_pdata));
501 printf("USB KBD: Error allocating private data\n");
505 /* Clear private data */
506 memset(data, 0, sizeof(struct usb_kbd_pdata));
508 /* allocate input buffer aligned and sized to USB DMA alignment */
509 data->new = memalign(USB_DMA_MINALIGN,
510 roundup(USB_KBD_BOOT_REPORT_SIZE, USB_DMA_MINALIGN));
512 /* Insert private data into USB device structure */
515 /* Set IRQ handler */
516 dev->irq_handle = usb_kbd_irq;
518 data->intpipe = usb_rcvintpipe(dev, ep->bEndpointAddress);
519 data->intpktsize = min(usb_maxpacket(dev, data->intpipe),
520 USB_KBD_BOOT_REPORT_SIZE);
521 data->intinterval = ep->bInterval;
522 data->last_report = -1;
524 /* We found a USB Keyboard, install it. */
525 debug("USB KBD: set boot protocol\n");
526 usb_set_protocol(dev, iface->desc.bInterfaceNumber, 0);
528 #if !defined(CONFIG_SYS_USB_EVENT_POLL_VIA_CONTROL_EP) && \
529 !defined(CONFIG_SYS_USB_EVENT_POLL_VIA_INT_QUEUE)
530 debug("USB KBD: set idle interval...\n");
531 usb_set_idle(dev, iface->desc.bInterfaceNumber, REPEAT_RATE / 4, 0);
533 debug("USB KBD: set idle interval=0...\n");
534 usb_set_idle(dev, iface->desc.bInterfaceNumber, 0, 0);
537 debug("USB KBD: enable interrupt pipe...\n");
538 #ifdef CONFIG_SYS_USB_EVENT_POLL_VIA_INT_QUEUE
539 data->intq = create_int_queue(dev, data->intpipe, 1,
540 USB_KBD_BOOT_REPORT_SIZE, data->new,
543 #elif defined(CONFIG_SYS_USB_EVENT_POLL_VIA_CONTROL_EP)
544 if (usb_get_report(dev, iface->desc.bInterfaceNumber,
545 1, 0, data->new, USB_KBD_BOOT_REPORT_SIZE) < 0) {
547 if (usb_int_msg(dev, data->intpipe, data->new, data->intpktsize,
548 data->intinterval, false) < 0) {
550 printf("Failed to get keyboard state from device %04x:%04x\n",
551 dev->descriptor.idVendor, dev->descriptor.idProduct);
552 /* Abort, we don't want to use that non-functional keyboard. */
560 static int probe_usb_keyboard(struct usb_device *dev)
563 struct stdio_dev usb_kbd_dev;
566 /* Try probing the keyboard */
567 if (usb_kbd_probe_dev(dev, 0) != 1)
570 /* Register the keyboard */
571 debug("USB KBD: register.\n");
572 memset(&usb_kbd_dev, 0, sizeof(struct stdio_dev));
573 strcpy(usb_kbd_dev.name, DEVNAME);
574 usb_kbd_dev.flags = DEV_FLAGS_INPUT;
575 usb_kbd_dev.getc = usb_kbd_getc;
576 usb_kbd_dev.tstc = usb_kbd_testc;
577 usb_kbd_dev.priv = (void *)dev;
578 error = stdio_register(&usb_kbd_dev);
582 stdinname = env_get("stdin");
583 #if CONFIG_IS_ENABLED(CONSOLE_MUX)
584 error = iomux_doenv(stdin, stdinname);
588 /* Check if this is the standard input device. */
589 if (strcmp(stdinname, DEVNAME))
592 /* Reassign the console */
593 if (overwrite_console())
596 error = console_assign(stdin, DEVNAME);
604 #if !CONFIG_IS_ENABLED(DM_USB)
605 /* Search for keyboard and register it if found. */
606 int drv_usb_kbd_init(void)
610 debug("%s: Probing for keyboard\n", __func__);
611 /* Scan all USB Devices */
612 for (i = 0; i < USB_MAX_DEVICE; i++) {
613 struct usb_device *dev;
615 /* Get USB device. */
616 dev = usb_get_dev_index(i);
620 if (dev->devnum == -1)
623 error = probe_usb_keyboard(dev);
626 if (error && error != -ENOENT)
630 /* No USB Keyboard found */
634 /* Deregister the keyboard. */
635 int usb_kbd_deregister(int force)
637 #if CONFIG_IS_ENABLED(SYS_STDIO_DEREGISTER)
638 struct stdio_dev *dev;
639 struct usb_device *usb_kbd_dev;
640 struct usb_kbd_pdata *data;
642 dev = stdio_get_by_name(DEVNAME);
644 usb_kbd_dev = (struct usb_device *)dev->priv;
645 data = usb_kbd_dev->privptr;
646 #if CONFIG_IS_ENABLED(CONSOLE_MUX)
647 if (iomux_replace_device(stdin, DEVNAME, force ? "nulldev" : ""))
650 if (stdio_deregister_dev(dev, force) != 0)
652 #ifdef CONFIG_SYS_USB_EVENT_POLL_VIA_INT_QUEUE
653 destroy_int_queue(usb_kbd_dev, data->intq);
667 #if CONFIG_IS_ENABLED(DM_USB)
669 static int usb_kbd_probe(struct udevice *dev)
671 struct usb_device *udev = dev_get_parent_priv(dev);
673 return probe_usb_keyboard(udev);
676 static int usb_kbd_remove(struct udevice *dev)
678 struct usb_device *udev = dev_get_parent_priv(dev);
679 struct usb_kbd_pdata *data;
680 struct stdio_dev *sdev;
683 sdev = stdio_get_by_name(DEVNAME);
688 data = udev->privptr;
689 #if CONFIG_IS_ENABLED(CONSOLE_MUX)
690 if (iomux_replace_device(stdin, DEVNAME, "nulldev")) {
695 if (stdio_deregister_dev(sdev, true)) {
699 #ifdef CONFIG_SYS_USB_EVENT_POLL_VIA_INT_QUEUE
700 destroy_int_queue(udev, data->intq);
707 printf("%s: warning, ret=%d", __func__, ret);
711 static const struct udevice_id usb_kbd_ids[] = {
712 { .compatible = "usb-keyboard" },
716 U_BOOT_DRIVER(usb_kbd) = {
718 .id = UCLASS_KEYBOARD,
719 .of_match = usb_kbd_ids,
720 .probe = usb_kbd_probe,
721 .remove = usb_kbd_remove,
724 static const struct usb_device_id kbd_id_table[] = {
726 .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS |
727 USB_DEVICE_ID_MATCH_INT_SUBCLASS |
728 USB_DEVICE_ID_MATCH_INT_PROTOCOL,
729 .bInterfaceClass = USB_CLASS_HID,
730 .bInterfaceSubClass = USB_SUB_HID_BOOT,
731 .bInterfaceProtocol = USB_PROT_HID_KEYBOARD,
733 { } /* Terminating entry */
736 U_BOOT_USB_DEVICE(usb_kbd, kbd_id_table);