3 * Denis Peter, MPL AG Switzerland
5 * Part of this source has been derived from the Linux USB
8 * SPDX-License-Identifier: GPL-2.0+
12 #include <stdio_dev.h>
13 #include <asm/byteorder.h>
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
22 #ifdef CONFIG_SYS_CONSOLE_OVERWRITE_ROUTINE
23 extern int overwrite_console(void);
25 int overwrite_console(void)
31 /* Keyboard sampling rate */
32 #define REPEAT_RATE (40 / 4) /* 40msec -> 25cps */
33 #define REPEAT_DELAY 10 /* 10 x REPEAT_RATE = 400msec */
36 #define CAPS_LOCK 0x39
37 #define SCROLL_LOCK 0x47
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)
49 /* Size of the keyboard buffer */
50 #define USB_KBD_BUFFER_LEN 0x20
53 #define DEVNAME "usbkbd"
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 '\\', '#', ';', '\'', '`', ',', '.', '/'
61 static const unsigned char usb_kbd_numkey_shifted[] = {
62 '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',
63 '\r', 0x1b, '\b', '\t', ' ', '_', '+', '{', '}',
64 '|', '~', ':', '"', '~', '<', '>', '?'
67 static const unsigned char usb_kbd_num_keypad[] = {
68 '/', '*', '-', '+', '\r',
69 '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
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
78 static const unsigned char usb_kbd_arrow[] = {
83 * NOTE: It's important for the NUM, CAPS, SCROLL-lock bits to be in this
84 * order. See usb_kbd_setled() function!
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)
91 #define USB_KBD_LEDMASK \
92 (USB_KBD_NUMLOCK | USB_KBD_CAPSLOCK | USB_KBD_SCROLLLOCK)
94 struct usb_kbd_pdata {
95 uint32_t repeat_delay;
97 uint32_t usb_in_pointer;
98 uint32_t usb_out_pointer;
99 uint8_t usb_kbd_buffer[USB_KBD_BUFFER_LEN];
107 extern int __maybe_unused net_busy_flag;
109 /* The period of time between two calls of usb_kbd_testc(). */
110 static unsigned long __maybe_unused kbd_testc_tms;
112 /* Generic keyboard event polling. */
113 void usb_kbd_generic_poll(void)
115 struct stdio_dev *dev;
116 struct usb_device *usb_kbd_dev;
117 struct usb_kbd_pdata *data;
118 struct usb_interface *iface;
119 struct usb_endpoint_descriptor *ep;
123 /* Get the pointer to USB Keyboard device pointer */
124 dev = stdio_get_by_name(DEVNAME);
125 usb_kbd_dev = (struct usb_device *)dev->priv;
126 data = usb_kbd_dev->privptr;
127 iface = &usb_kbd_dev->config.if_desc[0];
128 ep = &iface->ep_desc[0];
129 pipe = usb_rcvintpipe(usb_kbd_dev, ep->bEndpointAddress);
131 /* Submit a interrupt transfer request */
132 maxp = usb_maxpacket(usb_kbd_dev, pipe);
133 usb_submit_int_msg(usb_kbd_dev, pipe, data->new,
134 maxp > 8 ? 8 : maxp, ep->bInterval);
137 /* Puts character in the queue and sets up the in and out pointer. */
138 static void usb_kbd_put_queue(struct usb_kbd_pdata *data, char c)
140 if (data->usb_in_pointer == USB_KBD_BUFFER_LEN - 1) {
141 /* Check for buffer full. */
142 if (data->usb_out_pointer == 0)
145 data->usb_in_pointer = 0;
147 /* Check for buffer full. */
148 if (data->usb_in_pointer == data->usb_out_pointer - 1)
151 data->usb_in_pointer++;
154 data->usb_kbd_buffer[data->usb_in_pointer] = c;
158 * Set the LEDs. Since this is used in the irq routine, the control job is
159 * issued with a timeout of 0. This means, that the job is queued without
160 * waiting for job completion.
162 static void usb_kbd_setled(struct usb_device *dev)
164 struct usb_interface *iface = &dev->config.if_desc[0];
165 struct usb_kbd_pdata *data = dev->privptr;
166 uint32_t leds = data->flags & USB_KBD_LEDMASK;
168 usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
169 USB_REQ_SET_REPORT, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
170 0x200, iface->desc.bInterfaceNumber, (void *)&leds, 1, 0);
173 #define CAPITAL_MASK 0x20
174 /* Translate the scancode in ASCII */
175 static int usb_kbd_translate(struct usb_kbd_pdata *data, unsigned char scancode,
176 unsigned char modifier, int pressed)
182 data->repeat_delay = 0;
187 data->repeat_delay++;
188 if (data->repeat_delay < REPEAT_DELAY)
191 data->repeat_delay = REPEAT_DELAY;
194 /* Alphanumeric values */
195 if ((scancode > 3) && (scancode <= 0x1d)) {
196 keycode = scancode - 4 + 'a';
198 if (data->flags & USB_KBD_CAPSLOCK)
199 keycode &= ~CAPITAL_MASK;
201 if (modifier & (LEFT_SHIFT | RIGHT_SHIFT)) {
202 /* Handle CAPSLock + Shift pressed simultaneously */
203 if (keycode & CAPITAL_MASK)
204 keycode &= ~CAPITAL_MASK;
206 keycode |= CAPITAL_MASK;
210 if ((scancode > 0x1d) && (scancode < 0x3a)) {
212 if (modifier & (LEFT_SHIFT | RIGHT_SHIFT))
213 keycode = usb_kbd_numkey_shifted[scancode - 0x1e];
215 keycode = usb_kbd_numkey[scancode - 0x1e];
219 if ((scancode >= 0x4f) && (scancode <= 0x52))
220 keycode = usb_kbd_arrow[scancode - 0x4f];
223 if ((scancode >= 0x54) && (scancode <= 0x67))
224 keycode = usb_kbd_num_keypad[scancode - 0x54];
226 if (data->flags & USB_KBD_CTRL)
227 keycode = scancode - 0x3;
230 if (scancode == NUM_LOCK) {
231 data->flags ^= USB_KBD_NUMLOCK;
235 if (scancode == CAPS_LOCK) {
236 data->flags ^= USB_KBD_CAPSLOCK;
239 if (scancode == SCROLL_LOCK) {
240 data->flags ^= USB_KBD_SCROLLLOCK;
245 /* Report keycode if any */
247 debug("%c", keycode);
248 usb_kbd_put_queue(data, keycode);
254 static uint32_t usb_kbd_service_key(struct usb_device *dev, int i, int up)
257 struct usb_kbd_pdata *data = dev->privptr;
269 if ((old[i] > 3) && (memscan(new + 2, old[i], 6) == new + 8))
270 res |= usb_kbd_translate(data, old[i], data->new[0], up);
275 /* Interrupt service routine */
276 static int usb_kbd_irq_worker(struct usb_device *dev)
278 struct usb_kbd_pdata *data = dev->privptr;
281 /* No combo key pressed */
282 if (data->new[0] == 0x00)
283 data->flags &= ~USB_KBD_CTRL;
284 /* Left or Right Ctrl pressed */
285 else if ((data->new[0] == LEFT_CNTR) || (data->new[0] == RIGHT_CNTR))
286 data->flags |= USB_KBD_CTRL;
288 for (i = 2; i < 8; i++) {
289 res |= usb_kbd_service_key(dev, i, 0);
290 res |= usb_kbd_service_key(dev, i, 1);
293 /* Key is still pressed */
294 if ((data->new[2] > 3) && (data->old[2] == data->new[2]))
295 res |= usb_kbd_translate(data, data->new[2], data->new[0], 2);
300 memcpy(data->old, data->new, 8);
305 /* Keyboard interrupt handler */
306 static int usb_kbd_irq(struct usb_device *dev)
308 if ((dev->irq_status != 0) || (dev->irq_act_len != 8)) {
309 debug("USB KBD: Error %lX, len %d\n",
310 dev->irq_status, dev->irq_act_len);
314 return usb_kbd_irq_worker(dev);
317 /* Interrupt polling */
318 static inline void usb_kbd_poll_for_event(struct usb_device *dev)
320 #if defined(CONFIG_SYS_USB_EVENT_POLL)
321 struct usb_interface *iface;
322 struct usb_endpoint_descriptor *ep;
323 struct usb_kbd_pdata *data;
327 /* Get the pointer to USB Keyboard device pointer */
329 iface = &dev->config.if_desc[0];
330 ep = &iface->ep_desc[0];
331 pipe = usb_rcvintpipe(dev, ep->bEndpointAddress);
333 /* Submit a interrupt transfer request */
334 maxp = usb_maxpacket(dev, pipe);
335 usb_submit_int_msg(dev, pipe, &data->new[0],
336 maxp > 8 ? 8 : maxp, ep->bInterval);
338 usb_kbd_irq_worker(dev);
339 #elif defined(CONFIG_SYS_USB_EVENT_POLL_VIA_CONTROL_EP)
340 struct usb_interface *iface;
341 struct usb_kbd_pdata *data = dev->privptr;
342 iface = &dev->config.if_desc[0];
343 usb_get_report(dev, iface->desc.bInterfaceNumber,
344 1, 0, data->new, sizeof(data->new));
345 if (memcmp(data->old, data->new, sizeof(data->new)))
346 usb_kbd_irq_worker(dev);
350 /* test if a character is in the queue */
351 static int usb_kbd_testc(void)
353 struct stdio_dev *dev;
354 struct usb_device *usb_kbd_dev;
355 struct usb_kbd_pdata *data;
357 #ifdef CONFIG_CMD_NET
359 * If net_busy_flag is 1, NET transfer is running,
360 * then we check key-pressed every second (first check may be
361 * less than 1 second) to improve TFTP booting performance.
363 if (net_busy_flag && (get_timer(kbd_testc_tms) < CONFIG_SYS_HZ))
365 kbd_testc_tms = get_timer(0);
367 dev = stdio_get_by_name(DEVNAME);
368 usb_kbd_dev = (struct usb_device *)dev->priv;
369 data = usb_kbd_dev->privptr;
371 usb_kbd_poll_for_event(usb_kbd_dev);
373 return !(data->usb_in_pointer == data->usb_out_pointer);
376 /* gets the character from the queue */
377 static int usb_kbd_getc(void)
379 struct stdio_dev *dev;
380 struct usb_device *usb_kbd_dev;
381 struct usb_kbd_pdata *data;
383 dev = stdio_get_by_name(DEVNAME);
384 usb_kbd_dev = (struct usb_device *)dev->priv;
385 data = usb_kbd_dev->privptr;
387 while (data->usb_in_pointer == data->usb_out_pointer)
388 usb_kbd_poll_for_event(usb_kbd_dev);
390 if (data->usb_out_pointer == USB_KBD_BUFFER_LEN - 1)
391 data->usb_out_pointer = 0;
393 data->usb_out_pointer++;
395 return data->usb_kbd_buffer[data->usb_out_pointer];
398 /* probes the USB device dev for keyboard type. */
399 static int usb_kbd_probe(struct usb_device *dev, unsigned int ifnum)
401 struct usb_interface *iface;
402 struct usb_endpoint_descriptor *ep;
403 struct usb_kbd_pdata *data;
406 if (dev->descriptor.bNumConfigurations != 1)
409 iface = &dev->config.if_desc[ifnum];
411 if (iface->desc.bInterfaceClass != 3)
414 if (iface->desc.bInterfaceSubClass != 1)
417 if (iface->desc.bInterfaceProtocol != 1)
420 if (iface->desc.bNumEndpoints != 1)
423 ep = &iface->ep_desc[0];
425 /* Check if endpoint 1 is interrupt endpoint */
426 if (!(ep->bEndpointAddress & 0x80))
429 if ((ep->bmAttributes & 3) != 3)
432 debug("USB KBD: found set protocol...\n");
434 data = malloc(sizeof(struct usb_kbd_pdata));
436 printf("USB KBD: Error allocating private data\n");
440 /* Clear private data */
441 memset(data, 0, sizeof(struct usb_kbd_pdata));
443 /* allocate input buffer aligned and sized to USB DMA alignment */
444 data->new = memalign(USB_DMA_MINALIGN, roundup(8, USB_DMA_MINALIGN));
446 /* Insert private data into USB device structure */
449 /* Set IRQ handler */
450 dev->irq_handle = usb_kbd_irq;
452 pipe = usb_rcvintpipe(dev, ep->bEndpointAddress);
453 maxp = usb_maxpacket(dev, pipe);
455 /* We found a USB Keyboard, install it. */
456 usb_set_protocol(dev, iface->desc.bInterfaceNumber, 0);
458 debug("USB KBD: found set idle...\n");
459 usb_set_idle(dev, iface->desc.bInterfaceNumber, REPEAT_RATE, 0);
461 debug("USB KBD: enable interrupt pipe...\n");
462 if (usb_submit_int_msg(dev, pipe, data->new, maxp > 8 ? 8 : maxp,
463 ep->bInterval) < 0) {
464 printf("Failed to get keyboard state from device %04x:%04x\n",
465 dev->descriptor.idVendor, dev->descriptor.idProduct);
466 /* Abort, we don't want to use that non-functional keyboard. */
474 /* Search for keyboard and register it if found. */
475 int drv_usb_kbd_init(void)
477 struct stdio_dev usb_kbd_dev, *old_dev;
478 struct usb_device *dev;
479 char *stdinname = getenv("stdin");
482 /* Scan all USB Devices */
483 for (i = 0; i < USB_MAX_DEVICE; i++) {
484 /* Get USB device. */
485 dev = usb_get_dev_index(i);
489 if (dev->devnum == -1)
492 /* Try probing the keyboard */
493 if (usb_kbd_probe(dev, 0) != 1)
496 /* We found a keyboard, check if it is already registered. */
497 debug("USB KBD: found set up device.\n");
498 old_dev = stdio_get_by_name(DEVNAME);
500 /* Already registered, just return ok. */
501 debug("USB KBD: is already registered.\n");
502 usb_kbd_deregister();
506 /* Register the keyboard */
507 debug("USB KBD: register.\n");
508 memset(&usb_kbd_dev, 0, sizeof(struct stdio_dev));
509 strcpy(usb_kbd_dev.name, DEVNAME);
510 usb_kbd_dev.flags = DEV_FLAGS_INPUT | DEV_FLAGS_SYSTEM;
511 usb_kbd_dev.putc = NULL;
512 usb_kbd_dev.puts = NULL;
513 usb_kbd_dev.getc = usb_kbd_getc;
514 usb_kbd_dev.tstc = usb_kbd_testc;
515 usb_kbd_dev.priv = (void *)dev;
516 error = stdio_register(&usb_kbd_dev);
520 #ifdef CONFIG_CONSOLE_MUX
521 error = iomux_doenv(stdin, stdinname);
525 /* Check if this is the standard input device. */
526 if (strcmp(stdinname, DEVNAME))
529 /* Reassign the console */
530 if (overwrite_console())
533 error = console_assign(stdin, DEVNAME);
541 /* No USB Keyboard found */
545 /* Deregister the keyboard. */
546 int usb_kbd_deregister(void)
548 #ifdef CONFIG_SYS_STDIO_DEREGISTER
549 return stdio_deregister(DEVNAME);