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