VirtualBox

source: vbox/trunk/src/VBox/Devices/Input/UsbKbd.cpp@ 49886

Last change on this file since 49886 was 49814, checked in by vboxsync, 11 years ago

Devices/USB: First part of the rework, move most of the work to dedicated threads to improve performance

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 55.1 KB
Line 
1/* $Id: UsbKbd.cpp 49814 2013-12-06 21:38:28Z vboxsync $ */
2/** @file
3 * UsbKbd - USB Human Interface Device Emulation, Keyboard.
4 */
5
6/*
7 * Copyright (C) 2007-2012 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/*******************************************************************************
19* Header Files *
20*******************************************************************************/
21#define LOG_GROUP LOG_GROUP_USB_KBD
22#include <VBox/vmm/pdmusb.h>
23#include <VBox/log.h>
24#include <VBox/err.h>
25#include <iprt/assert.h>
26#include <iprt/critsect.h>
27#include <iprt/mem.h>
28#include <iprt/semaphore.h>
29#include <iprt/string.h>
30#include <iprt/uuid.h>
31#include "VBoxDD.h"
32
33
34/*******************************************************************************
35* Defined Constants And Macros *
36*******************************************************************************/
37/** @name USB HID string IDs
38 * @{ */
39#define USBHID_STR_ID_MANUFACTURER 1
40#define USBHID_STR_ID_PRODUCT 2
41/** @} */
42
43/** @name USB HID specific descriptor types
44 * @{ */
45#define DT_IF_HID_DESCRIPTOR 0x21
46#define DT_IF_HID_REPORT 0x22
47/** @} */
48
49/** @name USB HID vendor and product IDs
50 * @{ */
51#define VBOX_USB_VENDOR 0x80EE
52#define USBHID_PID_KEYBOARD 0x0010
53/** @} */
54
55/** @name USB HID class specific requests
56 * @{ */
57#define HID_REQ_GET_REPORT 0x01
58#define HID_REQ_GET_IDLE 0x02
59#define HID_REQ_SET_REPORT 0x09
60#define HID_REQ_SET_IDLE 0x0A
61/** @} */
62
63/** @name USB HID additional constants
64 * @{ */
65/** The highest USB usage code reported by the VBox emulated keyboard */
66#define VBOX_USB_MAX_USAGE_CODE 0xE7
67/** The size of an array needed to store all USB usage codes */
68#define VBOX_USB_USAGE_ARRAY_SIZE (VBOX_USB_MAX_USAGE_CODE + 1)
69#define USBHID_USAGE_ROLL_OVER 1
70/** The usage code of the first modifier key. */
71#define USBHID_MODIFIER_FIRST 0xE0
72/** The usage code of the last modifier key. */
73#define USBHID_MODIFIER_LAST 0xE7
74/** @} */
75
76/*******************************************************************************
77* Structures and Typedefs *
78*******************************************************************************/
79
80/**
81 * The USB HID request state.
82 */
83typedef enum USBHIDREQSTATE
84{
85 /** Invalid status. */
86 USBHIDREQSTATE_INVALID = 0,
87 /** Ready to receive a new read request. */
88 USBHIDREQSTATE_READY,
89 /** Have (more) data for the host. */
90 USBHIDREQSTATE_DATA_TO_HOST,
91 /** Waiting to supply status information to the host. */
92 USBHIDREQSTATE_STATUS,
93 /** The end of the valid states. */
94 USBHIDREQSTATE_END
95} USBHIDREQSTATE;
96
97
98/**
99 * Endpoint status data.
100 */
101typedef struct USBHIDEP
102{
103 bool fHalted;
104} USBHIDEP;
105/** Pointer to the endpoint status. */
106typedef USBHIDEP *PUSBHIDEP;
107
108
109/**
110 * A URB queue.
111 */
112typedef struct USBHIDURBQUEUE
113{
114 /** The head pointer. */
115 PVUSBURB pHead;
116 /** Where to insert the next entry. */
117 PVUSBURB *ppTail;
118} USBHIDURBQUEUE;
119/** Pointer to a URB queue. */
120typedef USBHIDURBQUEUE *PUSBHIDURBQUEUE;
121/** Pointer to a const URB queue. */
122typedef USBHIDURBQUEUE const *PCUSBHIDURBQUEUE;
123
124
125/**
126 * The USB HID report structure for regular keys.
127 */
128typedef struct USBHIDK_REPORT
129{
130 uint8_t ShiftState; /**< Modifier keys bitfield */
131 uint8_t Reserved; /**< Currently unused */
132 uint8_t aKeys[6]; /**< Normal keys */
133} USBHIDK_REPORT, *PUSBHIDK_REPORT;
134
135/** Scancode translator state. */
136typedef enum {
137 SS_IDLE, /**< Starting state. */
138 SS_EXT, /**< E0 byte was received. */
139 SS_EXT1 /**< E1 byte was received. */
140} scan_state_t;
141
142/**
143 * The USB HID instance data.
144 */
145typedef struct USBHID
146{
147 /** Pointer back to the PDM USB Device instance structure. */
148 PPDMUSBINS pUsbIns;
149 /** Critical section protecting the device state. */
150 RTCRITSECT CritSect;
151
152 /** The current configuration.
153 * (0 - default, 1 - the one supported configuration, i.e configured.) */
154 uint8_t bConfigurationValue;
155 /** USB HID Idle value..
156 * (0 - only report state change, !=0 - report in bIdle * 4ms intervals.) */
157 uint8_t bIdle;
158 /** Endpoint 0 is the default control pipe, 1 is the dev->host interrupt one. */
159 USBHIDEP aEps[2];
160 /** The state of the HID (state machine).*/
161 USBHIDREQSTATE enmState;
162
163 /** State of the scancode translation. */
164 scan_state_t XlatState;
165
166 /** Pending to-host queue.
167 * The URBs waiting here are waiting for data to become available.
168 */
169 USBHIDURBQUEUE ToHostQueue;
170
171 /** Done queue
172 * The URBs stashed here are waiting to be reaped. */
173 USBHIDURBQUEUE DoneQueue;
174 /** Signalled when adding an URB to the done queue and fHaveDoneQueueWaiter
175 * is set. */
176 RTSEMEVENT hEvtDoneQueue;
177 /** Someone is waiting on the done queue. */
178 bool fHaveDoneQueueWaiter;
179 /** If device has pending changes. */
180 bool fHasPendingChanges;
181 /** Keypresses which have not yet been reported. A workaround for the
182 * problem of keys being released before the keypress could be reported. */
183 uint8_t abUnreportedKeys[VBOX_USB_USAGE_ARRAY_SIZE];
184 /** Currently depressed keys */
185 uint8_t abDepressedKeys[VBOX_USB_USAGE_ARRAY_SIZE];
186
187 /**
188 * Keyboard port - LUN#0.
189 *
190 * @implements PDMIBASE
191 * @implements PDMIKEYBOARDPORT
192 */
193 struct
194 {
195 /** The base interface for the keyboard port. */
196 PDMIBASE IBase;
197 /** The keyboard port base interface. */
198 PDMIKEYBOARDPORT IPort;
199
200 /** The base interface of the attached keyboard driver. */
201 R3PTRTYPE(PPDMIBASE) pDrvBase;
202 /** The keyboard interface of the attached keyboard driver. */
203 R3PTRTYPE(PPDMIKEYBOARDCONNECTOR) pDrv;
204 } Lun0;
205} USBHID;
206/** Pointer to the USB HID instance data. */
207typedef USBHID *PUSBHID;
208
209/*******************************************************************************
210* Global Variables *
211*******************************************************************************/
212static const PDMUSBDESCCACHESTRING g_aUsbHidStrings_en_US[] =
213{
214 { USBHID_STR_ID_MANUFACTURER, "VirtualBox" },
215 { USBHID_STR_ID_PRODUCT, "USB Keyboard" },
216};
217
218static const PDMUSBDESCCACHELANG g_aUsbHidLanguages[] =
219{
220 { 0x0409, RT_ELEMENTS(g_aUsbHidStrings_en_US), g_aUsbHidStrings_en_US }
221};
222
223static const VUSBDESCENDPOINTEX g_aUsbHidEndpointDescs[] =
224{
225 {
226 {
227 /* .bLength = */ sizeof(VUSBDESCENDPOINT),
228 /* .bDescriptorType = */ VUSB_DT_ENDPOINT,
229 /* .bEndpointAddress = */ 0x81 /* ep=1, in */,
230 /* .bmAttributes = */ 3 /* interrupt */,
231 /* .wMaxPacketSize = */ 8,
232 /* .bInterval = */ 10,
233 },
234 /* .pvMore = */ NULL,
235 /* .pvClass = */ NULL,
236 /* .cbClass = */ 0
237 },
238};
239
240/** HID report descriptor. */
241static const uint8_t g_UsbHidReportDesc[] =
242{
243 /* Usage Page */ 0x05, 0x01, /* Generic Desktop */
244 /* Usage */ 0x09, 0x06, /* Keyboard */
245 /* Collection */ 0xA1, 0x01, /* Application */
246 /* Usage Page */ 0x05, 0x07, /* Keyboard */
247 /* Usage Minimum */ 0x19, 0xE0, /* Left Ctrl Key */
248 /* Usage Maximum */ 0x29, 0xE7, /* Right GUI Key */
249 /* Logical Minimum */ 0x15, 0x00, /* 0 */
250 /* Logical Maximum */ 0x25, 0x01, /* 1 */
251 /* Report Count */ 0x95, 0x08, /* 8 */
252 /* Report Size */ 0x75, 0x01, /* 1 */
253 /* Input */ 0x81, 0x02, /* Data, Value, Absolute, Bit field */
254 /* Report Count */ 0x95, 0x01, /* 1 */
255 /* Report Size */ 0x75, 0x08, /* 8 (padding bits) */
256 /* Input */ 0x81, 0x01, /* Constant, Array, Absolute, Bit field */
257 /* Report Count */ 0x95, 0x05, /* 5 */
258 /* Report Size */ 0x75, 0x01, /* 1 */
259 /* Usage Page */ 0x05, 0x08, /* LEDs */
260 /* Usage Minimum */ 0x19, 0x01, /* Num Lock */
261 /* Usage Maximum */ 0x29, 0x05, /* Kana */
262 /* Output */ 0x91, 0x02, /* Data, Value, Absolute, Non-volatile,Bit field */
263 /* Report Count */ 0x95, 0x01, /* 1 */
264 /* Report Size */ 0x75, 0x03, /* 3 */
265 /* Output */ 0x91, 0x01, /* Constant, Value, Absolute, Non-volatile, Bit field */
266 /* Report Count */ 0x95, 0x06, /* 6 */
267 /* Report Size */ 0x75, 0x08, /* 8 */
268 /* Logical Minimum */ 0x15, 0x00, /* 0 */
269 /* Logical Maximum */ 0x26, 0xFF,0x00,/* 255 */
270 /* Usage Page */ 0x05, 0x07, /* Keyboard */
271 /* Usage Minimum */ 0x19, 0x00, /* 0 */
272 /* Usage Maximum */ 0x29, 0xFF, /* 255 */
273 /* Input */ 0x81, 0x00, /* Data, Array, Absolute, Bit field */
274 /* End Collection */ 0xC0,
275};
276
277/** Additional HID class interface descriptor. */
278static const uint8_t g_UsbHidIfHidDesc[] =
279{
280 /* .bLength = */ 0x09,
281 /* .bDescriptorType = */ 0x21, /* HID */
282 /* .bcdHID = */ 0x10, 0x01, /* 1.1 */
283 /* .bCountryCode = */ 0x0D, /* International (ISO) */
284 /* .bNumDescriptors = */ 1,
285 /* .bDescriptorType = */ 0x22, /* Report */
286 /* .wDescriptorLength = */ sizeof(g_UsbHidReportDesc), 0x00
287};
288
289static const VUSBDESCINTERFACEEX g_UsbHidInterfaceDesc =
290{
291 {
292 /* .bLength = */ sizeof(VUSBDESCINTERFACE),
293 /* .bDescriptorType = */ VUSB_DT_INTERFACE,
294 /* .bInterfaceNumber = */ 0,
295 /* .bAlternateSetting = */ 0,
296 /* .bNumEndpoints = */ 1,
297 /* .bInterfaceClass = */ 3 /* HID */,
298 /* .bInterfaceSubClass = */ 1 /* Boot Interface */,
299 /* .bInterfaceProtocol = */ 1 /* Keyboard */,
300 /* .iInterface = */ 0
301 },
302 /* .pvMore = */ NULL,
303 /* .pvClass = */ &g_UsbHidIfHidDesc,
304 /* .cbClass = */ sizeof(g_UsbHidIfHidDesc),
305 &g_aUsbHidEndpointDescs[0],
306 /* .pIAD = */ NULL,
307 /* .cbIAD = */ 0
308};
309
310static const VUSBINTERFACE g_aUsbHidInterfaces[] =
311{
312 { &g_UsbHidInterfaceDesc, /* .cSettings = */ 1 },
313};
314
315static const VUSBDESCCONFIGEX g_UsbHidConfigDesc =
316{
317 {
318 /* .bLength = */ sizeof(VUSBDESCCONFIG),
319 /* .bDescriptorType = */ VUSB_DT_CONFIG,
320 /* .wTotalLength = */ 0 /* recalculated on read */,
321 /* .bNumInterfaces = */ RT_ELEMENTS(g_aUsbHidInterfaces),
322 /* .bConfigurationValue =*/ 1,
323 /* .iConfiguration = */ 0,
324 /* .bmAttributes = */ RT_BIT(7),
325 /* .MaxPower = */ 50 /* 100mA */
326 },
327 NULL, /* pvMore */
328 &g_aUsbHidInterfaces[0],
329 NULL /* pvOriginal */
330};
331
332static const VUSBDESCDEVICE g_UsbHidDeviceDesc =
333{
334 /* .bLength = */ sizeof(g_UsbHidDeviceDesc),
335 /* .bDescriptorType = */ VUSB_DT_DEVICE,
336 /* .bcdUsb = */ 0x110, /* 1.1 */
337 /* .bDeviceClass = */ 0 /* Class specified in the interface desc. */,
338 /* .bDeviceSubClass = */ 0 /* Subclass specified in the interface desc. */,
339 /* .bDeviceProtocol = */ 0 /* Protocol specified in the interface desc. */,
340 /* .bMaxPacketSize0 = */ 8,
341 /* .idVendor = */ VBOX_USB_VENDOR,
342 /* .idProduct = */ USBHID_PID_KEYBOARD,
343 /* .bcdDevice = */ 0x0100, /* 1.0 */
344 /* .iManufacturer = */ USBHID_STR_ID_MANUFACTURER,
345 /* .iProduct = */ USBHID_STR_ID_PRODUCT,
346 /* .iSerialNumber = */ 0,
347 /* .bNumConfigurations = */ 1
348};
349
350static const PDMUSBDESCCACHE g_UsbHidDescCache =
351{
352 /* .pDevice = */ &g_UsbHidDeviceDesc,
353 /* .paConfigs = */ &g_UsbHidConfigDesc,
354 /* .paLanguages = */ g_aUsbHidLanguages,
355 /* .cLanguages = */ RT_ELEMENTS(g_aUsbHidLanguages),
356 /* .fUseCachedDescriptors = */ true,
357 /* .fUseCachedStringsDescriptors = */ true
358};
359
360
361/*
362 * Because of historical reasons and poor design, VirtualBox internally uses BIOS
363 * PC/XT style scan codes to represent keyboard events. Each key press and release is
364 * represented as a stream of bytes, typically only one byte but up to four-byte
365 * sequences are possible. In the typical case, the GUI front end generates the stream
366 * of scan codes which we need to translate back to a single up/down event.
367 *
368 * This function could possibly live somewhere else.
369 */
370
371/** Lookup table for converting PC/XT scan codes to USB HID usage codes. */
372/** We map the scan codes for F13 to F23 to the usage codes for Sun keyboard
373 * left-hand side function keys rather than to the standard F13 to F23 usage
374 * codes, since we suspect that there are more people wanting Sun keyboard
375 * emulation than emulation of other keyboards with extended function keys. */
376static uint8_t aScancode2Hid[] =
377{
378 0x00, 0x29, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, /* 00-07 */
379 0x24, 0x25, 0x26, 0x27, 0x2d, 0x2e, 0x2a, 0x2b, /* 08-1F */
380 0x14, 0x1a, 0x08, 0x15, 0x17, 0x1c, 0x18, 0x0c, /* 10-17 */
381 0x12, 0x13, 0x2f, 0x30, 0x28, 0xe0, 0x04, 0x16, /* 18-1F */
382 0x07, 0x09, 0x0a, 0x0b, 0x0d, 0x0e, 0x0f, 0x33, /* 20-27 */
383 0x34, 0x35, 0xe1, 0x31, 0x1d, 0x1b, 0x06, 0x19, /* 28-2F */
384 0x05, 0x11, 0x10, 0x36, 0x37, 0x38, 0xe5, 0x55, /* 30-37 */
385 0xe2, 0x2c, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, /* 38-3F */
386 0x3f, 0x40, 0x41, 0x42, 0x43, 0x53, 0x47, 0x5f, /* 40-47 */
387 0x60, 0x61, 0x56, 0x5c, 0x5d, 0x5e, 0x57, 0x59, /* 48-4F */
388 0x5a, 0x5b, 0x62, 0x63, 0x46, 0x00, 0x64, 0x44, /* 50-57 */
389 0x45, 0x67, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, /* 58-5F */
390 /* Sun keys: Props Undo Front Copy */
391 0x00, 0x00, 0x00, 0x00, 0x76, 0x7a, 0x77, 0x7c, /* 60-67 */
392 /* Open Paste Find Cut Stop Again Help */
393 0x74, 0x7d, 0x7e, 0x7b, 0x78, 0x79, 0x75, 0x00, /* 68-6F */
394 0x88, 0x91, 0x90, 0x87, 0x00, 0x00, 0x00, 0x00, /* 70-77 */
395 0x00, 0x8a, 0x00, 0x8b, 0x00, 0x89, 0x85, 0x00 /* 78-7F */
396};
397
398/** Lookup table for extended scancodes (arrow keys etc.). */
399static uint8_t aExtScan2Hid[] =
400{
401 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00-07 */
402 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 08-1F */
403 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10-17 */
404 0x00, 0x00, 0x00, 0x00, 0x58, 0xe4, 0x00, 0x00, /* 18-1F */
405 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 20-27 */
406 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28-2F */
407 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x00, 0x46, /* 30-37 */
408 0xe6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38-3F */
409 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x00, 0x4a, /* 40-47 */
410 0x52, 0x4b, 0x00, 0x50, 0x00, 0x4f, 0x00, 0x4d, /* 48-4F */
411 0x51, 0x4e, 0x49, 0x4c, 0x00, 0x00, 0x00, 0x00, /* 50-57 */
412 0x00, 0x00, 0x00, 0xe3, 0xe7, 0x65, 0x66, 0x00, /* 58-5F */
413 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 60-67 */
414 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 68-6F */
415 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 70-77 */
416 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* 78-7F */
417};
418
419/**
420 * Convert a PC scan code to a USB HID usage byte.
421 *
422 * @param state Current state of the translator (scan_state_t).
423 * @param scanCode Incoming scan code.
424 * @param pUsage Pointer to usage; high bit set for key up events. The
425 * contents are only valid if returned state is SS_IDLE.
426 *
427 * @return scan_state_t New state of the translator.
428 */
429static scan_state_t ScancodeToHidUsage(scan_state_t state, uint8_t scanCode, uint32_t *pUsage)
430{
431 uint32_t keyUp;
432 uint8_t usage;
433
434 Assert(pUsage);
435
436 /* Isolate the scan code and key break flag. */
437 keyUp = (scanCode & 0x80) << 24;
438
439 switch (state) {
440 case SS_IDLE:
441 if (scanCode == 0xE0) {
442 state = SS_EXT;
443 } else if (scanCode == 0xE1) {
444 state = SS_EXT1;
445 } else {
446 usage = aScancode2Hid[scanCode & 0x7F];
447 *pUsage = usage | keyUp;
448 /* Remain in SS_IDLE state. */
449 }
450 break;
451 case SS_EXT:
452 usage = aExtScan2Hid[scanCode & 0x7F];
453 *pUsage = usage | keyUp;
454 state = SS_IDLE;
455 break;
456 case SS_EXT1:
457 Assert(0); //@todo - sort out the Pause key
458 *pUsage = 0;
459 state = SS_IDLE;
460 break;
461 }
462 return state;
463}
464
465/*******************************************************************************
466* Internal Functions *
467*******************************************************************************/
468
469
470/**
471 * Initializes an URB queue.
472 *
473 * @param pQueue The URB queue.
474 */
475static void usbHidQueueInit(PUSBHIDURBQUEUE pQueue)
476{
477 pQueue->pHead = NULL;
478 pQueue->ppTail = &pQueue->pHead;
479}
480
481/**
482 * Inserts an URB at the end of the queue.
483 *
484 * @param pQueue The URB queue.
485 * @param pUrb The URB to insert.
486 */
487DECLINLINE(void) usbHidQueueAddTail(PUSBHIDURBQUEUE pQueue, PVUSBURB pUrb)
488{
489 pUrb->Dev.pNext = NULL;
490 *pQueue->ppTail = pUrb;
491 pQueue->ppTail = &pUrb->Dev.pNext;
492}
493
494
495/**
496 * Unlinks the head of the queue and returns it.
497 *
498 * @returns The head entry.
499 * @param pQueue The URB queue.
500 */
501DECLINLINE(PVUSBURB) usbHidQueueRemoveHead(PUSBHIDURBQUEUE pQueue)
502{
503 PVUSBURB pUrb = pQueue->pHead;
504 if (pUrb)
505 {
506 PVUSBURB pNext = pUrb->Dev.pNext;
507 pQueue->pHead = pNext;
508 if (!pNext)
509 pQueue->ppTail = &pQueue->pHead;
510 else
511 pUrb->Dev.pNext = NULL;
512 }
513 return pUrb;
514}
515
516
517/**
518 * Removes an URB from anywhere in the queue.
519 *
520 * @returns true if found, false if not.
521 * @param pQueue The URB queue.
522 * @param pUrb The URB to remove.
523 */
524DECLINLINE(bool) usbHidQueueRemove(PUSBHIDURBQUEUE pQueue, PVUSBURB pUrb)
525{
526 PVUSBURB pCur = pQueue->pHead;
527 if (pCur == pUrb)
528 pQueue->pHead = pUrb->Dev.pNext;
529 else
530 {
531 while (pCur)
532 {
533 if (pCur->Dev.pNext == pUrb)
534 {
535 pCur->Dev.pNext = pUrb->Dev.pNext;
536 break;
537 }
538 pCur = pCur->Dev.pNext;
539 }
540 if (!pCur)
541 return false;
542 }
543 if (!pUrb->Dev.pNext)
544 pQueue->ppTail = &pQueue->pHead;
545 return true;
546}
547
548
549/**
550 * Checks if the queue is empty or not.
551 *
552 * @returns true if it is, false if it isn't.
553 * @param pQueue The URB queue.
554 */
555DECLINLINE(bool) usbHidQueueIsEmpty(PCUSBHIDURBQUEUE pQueue)
556{
557 return pQueue->pHead == NULL;
558}
559
560
561/**
562 * Links an URB into the done queue.
563 *
564 * @param pThis The HID instance.
565 * @param pUrb The URB.
566 */
567static void usbHidLinkDone(PUSBHID pThis, PVUSBURB pUrb)
568{
569 usbHidQueueAddTail(&pThis->DoneQueue, pUrb);
570
571 if (pThis->fHaveDoneQueueWaiter)
572 {
573 int rc = RTSemEventSignal(pThis->hEvtDoneQueue);
574 AssertRC(rc);
575 }
576}
577
578
579
580/**
581 * Completes the URB with a stalled state, halting the pipe.
582 */
583static int usbHidCompleteStall(PUSBHID pThis, PUSBHIDEP pEp, PVUSBURB pUrb, const char *pszWhy)
584{
585 Log(("usbHidCompleteStall/#%u: pUrb=%p:%s: %s\n", pThis->pUsbIns->iInstance, pUrb, pUrb->pszDesc, pszWhy));
586
587 pUrb->enmStatus = VUSBSTATUS_STALL;
588
589 /** @todo figure out if the stall is global or pipe-specific or both. */
590 if (pEp)
591 pEp->fHalted = true;
592 else
593 {
594 pThis->aEps[0].fHalted = true;
595 pThis->aEps[1].fHalted = true;
596 }
597
598 usbHidLinkDone(pThis, pUrb);
599 return VINF_SUCCESS;
600}
601
602
603/**
604 * Completes the URB with a OK state.
605 */
606static int usbHidCompleteOk(PUSBHID pThis, PVUSBURB pUrb, size_t cbData)
607{
608 Log(("usbHidCompleteOk/#%u: pUrb=%p:%s cbData=%#zx\n", pThis->pUsbIns->iInstance, pUrb, pUrb->pszDesc, cbData));
609
610 pUrb->enmStatus = VUSBSTATUS_OK;
611 pUrb->cbData = (uint32_t)cbData;
612
613 usbHidLinkDone(pThis, pUrb);
614 return VINF_SUCCESS;
615}
616
617
618/**
619 * Reset worker for usbHidUsbReset, usbHidUsbSetConfiguration and
620 * usbHidHandleDefaultPipe.
621 *
622 * @returns VBox status code.
623 * @param pThis The HID instance.
624 * @param pUrb Set when usbHidHandleDefaultPipe is the
625 * caller.
626 * @param fSetConfig Set when usbHidUsbSetConfiguration is the
627 * caller.
628 */
629static int usbHidResetWorker(PUSBHID pThis, PVUSBURB pUrb, bool fSetConfig)
630{
631 /*
632 * Deactivate the keyboard.
633 */
634 pThis->Lun0.pDrv->pfnSetActive(pThis->Lun0.pDrv, false);
635
636 /*
637 * Reset the device state.
638 */
639 pThis->enmState = USBHIDREQSTATE_READY;
640 pThis->bIdle = 0;
641 pThis->fHasPendingChanges = false;
642
643 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aEps); i++)
644 pThis->aEps[i].fHalted = false;
645
646 if (!pUrb && !fSetConfig) /* (only device reset) */
647 pThis->bConfigurationValue = 0; /* default */
648
649 /*
650 * Ditch all pending URBs.
651 */
652 PVUSBURB pCurUrb;
653 while ((pCurUrb = usbHidQueueRemoveHead(&pThis->ToHostQueue)) != NULL)
654 {
655 pCurUrb->enmStatus = VUSBSTATUS_CRC;
656 usbHidLinkDone(pThis, pCurUrb);
657 }
658
659 if (pUrb)
660 return usbHidCompleteOk(pThis, pUrb, 0);
661 return VINF_SUCCESS;
662}
663
664#ifdef DEBUG
665# define HEX_DIGIT(x) (((x) < 0xa) ? ((x) + '0') : ((x) - 0xa + 'a'))
666static void usbHidComputePressed(PUSBHIDK_REPORT pReport, char* pszBuf, unsigned cbBuf)
667{
668 unsigned offBuf = 0;
669 unsigned i;
670 for (i = 0; i < RT_ELEMENTS(pReport->aKeys); ++i)
671 {
672 uint8_t uCode = pReport->aKeys[i];
673 if (uCode != 0)
674 {
675 if (offBuf + 4 >= cbBuf)
676 break;
677 pszBuf[offBuf++] = HEX_DIGIT(uCode >> 4);
678 pszBuf[offBuf++] = HEX_DIGIT(uCode & 0xf);
679 pszBuf[offBuf++] = ' ';
680 }
681 }
682 pszBuf[offBuf++] = '\0';
683}
684# undef HEX_DIGIT
685#endif
686
687/**
688 * Returns true if the usage code corresponds to a keyboard modifier key
689 * (left or right ctrl, shift, alt or GUI). The usage codes for these keys
690 * are the range 0xe0 to 0xe7.
691 */
692static bool usbHidUsageCodeIsModifier(uint8_t u8Usage)
693{
694 return u8Usage >= USBHID_MODIFIER_FIRST && u8Usage <= USBHID_MODIFIER_LAST;
695}
696
697/**
698 * Convert a USB HID usage code to a keyboard modifier flag. The arithmetic
699 * is simple: the modifier keys have usage codes from 0xe0 to 0xe7, and the
700 * lower nibble is the bit number of the flag.
701 */
702static uint8_t usbHidModifierToFlag(uint8_t u8Usage)
703{
704 Assert(usbHidUsageCodeIsModifier(u8Usage));
705 return RT_BIT(u8Usage & 0xf);
706}
707
708/**
709 * Create a USB HID keyboard report based on a vector of keys which have been
710 * pressed since the last report was created (so that we don't miss keys that
711 * are only pressed briefly) and a vector of currently depressed keys.
712 * The keys in the report aKeys array are in increasing order (important for
713 * the test case).
714 */
715static int usbHidFillReport(PUSBHIDK_REPORT pReport,
716 uint8_t *pabUnreportedKeys,
717 uint8_t *pabDepressedKeys)
718{
719 int rc = false;
720 unsigned iBuf = 0;
721 RT_ZERO(*pReport);
722 for (unsigned iKey = 0; iKey < VBOX_USB_USAGE_ARRAY_SIZE; ++iKey)
723 {
724 AssertReturn(iBuf <= RT_ELEMENTS(pReport->aKeys),
725 VERR_INTERNAL_ERROR);
726 if (pabUnreportedKeys[iKey] || pabDepressedKeys[iKey])
727 {
728 if (usbHidUsageCodeIsModifier(iKey))
729 pReport->ShiftState |= usbHidModifierToFlag(iKey);
730 else if (iBuf == RT_ELEMENTS(pReport->aKeys))
731 {
732 /* The USB HID spec says that the entire vector should be
733 * set to ErrorRollOver on overflow. We don't mind if this
734 * path is taken several times for one report. */
735 for (unsigned iBuf2 = 0;
736 iBuf2 < RT_ELEMENTS(pReport->aKeys); ++iBuf2)
737 pReport->aKeys[iBuf2] = USBHID_USAGE_ROLL_OVER;
738 }
739 else
740 {
741 pReport->aKeys[iBuf] = iKey;
742 ++iBuf;
743 /* More Korean keyboard hackery: Give the caller a hint that
744 * a key release event needs reporting.
745 */
746 if (iKey == 0x90 || iKey == 0x91)
747 rc = true;
748 }
749 /* Avoid "hanging" keys: If a key is unreported but no longer
750 * depressed, we'll need to report the key-up state, too.
751 */
752 if (pabUnreportedKeys[iKey] && !pabDepressedKeys[iKey])
753 rc = true;
754
755 pabUnreportedKeys[iKey] = 0;
756 }
757 }
758 return rc;
759}
760
761#ifdef DEBUG
762/** Test data for testing usbHidFillReport(). The format is:
763 * - Unreported keys (zero terminated array)
764 * - Depressed keys (zero terminated array)
765 * - Expected shift state in the report (single byte inside array)
766 * - Expected keys buffer contents (array of six bytes)
767 */
768static const uint8_t testUsbHidFillReportData[][4][10] = {
769 /* Just unreported, no modifiers */
770 {{4, 9, 0}, {0}, {0}, {4, 9, 0, 0, 0, 0}},
771 /* Just unreported, one modifier */
772 {{4, 9, 0xe2, 0}, {0}, {4}, {4, 9, 0, 0, 0, 0}},
773 /* Just unreported, two modifiers */
774 {{4, 9, 0xe2, 0xe4, 0}, {0}, {20}, {4, 9, 0, 0, 0, 0}},
775 /* Just depressed, no modifiers */
776 {{0}, {7, 20, 0}, {0}, {7, 20, 0, 0, 0, 0}},
777 /* Just depressed, one modifier */
778 {{0}, {7, 20, 0xe3, 0}, {8}, {7, 20, 0, 0, 0, 0}},
779 /* Just depressed, two modifiers */
780 {{0}, {7, 20, 0xe3, 0xe6, 0}, {72}, {7, 20, 0, 0, 0, 0}},
781 /* Unreported and depressed, no overlap, no modifiers */
782 {{5, 10, 0}, {8, 21, 0}, {0}, {5, 8, 10, 21, 0, 0}},
783 /* Unreported and depressed, one overlap, no modifiers */
784 {{5, 10, 0}, {8, 10, 21, 0}, {0}, {5, 8, 10, 21, 0, 0}},
785 /* Unreported and depressed, no overlap, non-overlapping modifiers */
786 {{5, 10, 0xe2, 0xe4, 0}, {8, 21, 0xe3, 0xe6, 0}, {92},
787 {5, 8, 10, 21, 0, 0}},
788 /* Unreported and depressed, one overlap, non-overlapping modifiers */
789 {{5, 10, 21, 0xe2, 0xe4, 0}, {8, 21, 0xe3, 0xe6, 0}, {92},
790 {5, 8, 10, 21, 0, 0}},
791 /* Unreported and depressed, no overlap, overlapping modifiers */
792 {{5, 10, 0xe2, 0xe4, 0}, {8, 21, 0xe3, 0xe4, 0}, {28},
793 {5, 8, 10, 21, 0, 0}},
794 /* Unreported and depressed, one overlap, overlapping modifiers */
795 {{5, 10, 0xe2, 0xe4, 0}, {5, 8, 21, 0xe3, 0xe4, 0}, {28},
796 {5, 8, 10, 21, 0, 0}},
797 /* Just too many unreported, no modifiers */
798 {{4, 9, 11, 12, 16, 18, 20, 0}, {0}, {0}, {1, 1, 1, 1, 1, 1}},
799 /* Just too many unreported, two modifiers */
800 {{4, 9, 11, 12, 16, 18, 20, 0xe2, 0xe4, 0}, {0}, {20},
801 {1, 1, 1, 1, 1, 1}},
802 /* Just too many depressed, no modifiers */
803 {{0}, {7, 20, 22, 25, 27, 29, 34, 0}, {0}, {1, 1, 1, 1, 1, 1}},
804 /* Just too many depressed, two modifiers */
805 {{0}, {7, 20, 22, 25, 27, 29, 34, 0xe3, 0xe5, 0}, {40},
806 {1, 1, 1, 1, 1, 1}},
807 /* Too many unreported and depressed, no overlap, no modifiers */
808 {{5, 10, 12, 13, 0}, {8, 9, 21, 0}, {0}, {1, 1, 1, 1, 1, 1}},
809 /* Eight unreported and depressed total, one overlap, no modifiers */
810 {{5, 10, 12, 13, 0}, {8, 10, 21, 22, 0}, {0}, {1, 1, 1, 1, 1, 1}},
811 /* Seven unreported and depressed total, one overlap, no modifiers */
812 {{5, 10, 12, 13, 0}, {8, 10, 21, 0}, {0}, {5, 8, 10, 12, 13, 21}},
813 /* Too many unreported and depressed, no overlap, two modifiers */
814 {{5, 10, 12, 13, 0xe2, 0}, {8, 9, 21, 0xe4, 0}, {20},
815 {1, 1, 1, 1, 1, 1}},
816 /* Eight unreported and depressed total, one overlap, two modifiers */
817 {{5, 10, 12, 13, 0xe1, 0}, {8, 10, 21, 22, 0xe2, 0}, {6},
818 {1, 1, 1, 1, 1, 1}},
819 /* Seven unreported and depressed total, one overlap, two modifiers */
820 {{5, 10, 12, 13, 0xe2, 0}, {8, 10, 21, 0xe3, 0}, {12},
821 {5, 8, 10, 12, 13, 21}}
822};
823
824/** Test case for usbHidFillReport() */
825class testUsbHidFillReport
826{
827 USBHIDK_REPORT mReport;
828 uint8_t mabUnreportedKeys[VBOX_USB_USAGE_ARRAY_SIZE];
829 uint8_t mabDepressedKeys[VBOX_USB_USAGE_ARRAY_SIZE];
830 const uint8_t (*mTests)[4][10];
831
832 void doTest(unsigned cTest, const uint8_t *paiUnreportedKeys,
833 const uint8_t *paiDepressedKeys, uint8_t aExpShiftState,
834 const uint8_t *pabExpKeys)
835 {
836 RT_ZERO(mReport);
837 RT_ZERO(mabUnreportedKeys);
838 RT_ZERO(mabDepressedKeys);
839 for (unsigned i = 0; paiUnreportedKeys[i] != 0; ++i)
840 mabUnreportedKeys[paiUnreportedKeys[i]] = 1;
841 for (unsigned i = 0; paiDepressedKeys[i] != 0; ++i)
842 mabUnreportedKeys[paiDepressedKeys[i]] = 1;
843 int rc = usbHidFillReport(&mReport, mabUnreportedKeys, mabDepressedKeys);
844 AssertMsgRC(rc, ("test %u\n", cTest));
845 AssertMsg(mReport.ShiftState == aExpShiftState, ("test %u\n", cTest));
846 for (unsigned i = 0; i < RT_ELEMENTS(mReport.aKeys); ++i)
847 AssertMsg(mReport.aKeys[i] == pabExpKeys[i], ("test %u\n", cTest));
848 }
849
850public:
851 testUsbHidFillReport(void) : mTests(&testUsbHidFillReportData[0])
852 {
853 for (unsigned i = 0; i < RT_ELEMENTS(testUsbHidFillReportData); ++i)
854 doTest(i, mTests[i][0], mTests[i][1], mTests[i][2][0],
855 mTests[i][3]);
856 }
857};
858
859static testUsbHidFillReport gsTestUsbHidFillReport;
860#endif
861
862/**
863 * Handles a SET_REPORT request sent to the default control pipe. Note
864 * that unrecognized requests are ignored without reporting an error.
865 */
866static void usbHidSetReport(PUSBHID pThis, PVUSBURB pUrb)
867{
868 PVUSBSETUP pSetup = (PVUSBSETUP)&pUrb->abData[0];
869 Assert(pSetup->bRequest == HID_REQ_SET_REPORT);
870
871 /* The LED report is the 3rd report, ID 0 (-> wValue 0x200). */
872 if (pSetup->wIndex == 0 && pSetup->wLength == 1 && pSetup->wValue == 0x200)
873 {
874 PDMKEYBLEDS enmLeds = PDMKEYBLEDS_NONE;
875 uint8_t u8LEDs = pUrb->abData[sizeof(*pSetup)];
876 LogFlowFunc(("Setting keybooard LEDs to u8LEDs=%02X\n", u8LEDs));
877
878 /* Translate LED state to PDM format and send upstream. */
879 if (u8LEDs & 0x01)
880 enmLeds = (PDMKEYBLEDS)(enmLeds | PDMKEYBLEDS_NUMLOCK);
881 if (u8LEDs & 0x02)
882 enmLeds = (PDMKEYBLEDS)(enmLeds | PDMKEYBLEDS_CAPSLOCK);
883 if (u8LEDs & 0x04)
884 enmLeds = (PDMKEYBLEDS)(enmLeds | PDMKEYBLEDS_SCROLLLOCK);
885
886 pThis->Lun0.pDrv->pfnLedStatusChange(pThis->Lun0.pDrv, enmLeds);
887 }
888}
889
890/**
891 * Sends a state report to the host if there is a pending URB.
892 */
893static int usbHidSendReport(PUSBHID pThis)
894{
895 PVUSBURB pUrb = usbHidQueueRemoveHead(&pThis->ToHostQueue);
896 if (pUrb)
897 {
898 PUSBHIDK_REPORT pReport = (PUSBHIDK_REPORT)&pUrb->abData[0];
899
900 int again = usbHidFillReport(pReport, pThis->abUnreportedKeys,
901 pThis->abDepressedKeys);
902 if (again)
903 pThis->fHasPendingChanges = true;
904 else
905 pThis->fHasPendingChanges = false;
906 return usbHidCompleteOk(pThis, pUrb, sizeof(*pReport));
907 }
908 else
909 {
910 Log2(("No available URB for USB kbd\n"));
911 pThis->fHasPendingChanges = true;
912 }
913 return VINF_EOF;
914}
915
916/**
917 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
918 */
919static DECLCALLBACK(void *) usbHidKeyboardQueryInterface(PPDMIBASE pInterface, const char *pszIID)
920{
921 PUSBHID pThis = RT_FROM_MEMBER(pInterface, USBHID, Lun0.IBase);
922 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThis->Lun0.IBase);
923 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIKEYBOARDPORT, &pThis->Lun0.IPort);
924 return NULL;
925}
926
927/* See the PS2K device. */
928#define KRSP_BAT_FAIL 0xFC /* Also a 'release keys' signal. */
929
930/**
931 * Keyboard event handler.
932 *
933 * @returns VBox status code.
934 * @param pInterface Pointer to the keyboard port interface (KBDState::Keyboard.IPort).
935 * @param u8KeyCode The keycode.
936 */
937static DECLCALLBACK(int) usbHidKeyboardPutEvent(PPDMIKEYBOARDPORT pInterface, uint8_t u8KeyCode)
938{
939 PUSBHID pThis = RT_FROM_MEMBER(pInterface, USBHID, Lun0.IPort);
940 uint32_t u32Usage = 0;
941 uint8_t u8HidCode;
942 int fKeyDown;
943 bool fHaveEvent = true;
944
945 RTCritSectEnter(&pThis->CritSect);
946
947 if (RT_UNLIKELY(u8KeyCode == KRSP_BAT_FAIL))
948 {
949 /* Clear all currently depressed and unreported keys. */
950 RT_ZERO(pThis->abDepressedKeys);
951 RT_ZERO(pThis->abUnreportedKeys);
952 usbHidSendReport(pThis);
953 }
954 else
955 {
956
957 pThis->XlatState = ScancodeToHidUsage(pThis->XlatState, u8KeyCode, &u32Usage);
958
959 if (pThis->XlatState == SS_IDLE)
960 {
961 /* The usage code is valid. */
962 fKeyDown = !(u32Usage & 0x80000000);
963 u8HidCode = u32Usage & 0xFF;
964 AssertReturn(u8HidCode <= VBOX_USB_MAX_USAGE_CODE, VERR_INTERNAL_ERROR);
965
966 LogFlowFunc(("key %s: 0x%x->0x%x\n",
967 fKeyDown ? "down" : "up", u8KeyCode, u8HidCode));
968
969 if (fKeyDown)
970 {
971 /* Due to host key repeat, we can get key events for keys which are
972 * already depressed. */
973 if (!pThis->abDepressedKeys[u8HidCode])
974 {
975 pThis->abUnreportedKeys[u8HidCode] = 1;
976
977 /* If a non-modifier key is being marked as unreported, also set
978 * all currently depressed modifer keys as unreported. This avoids
979 * problems where a simulated key sequence is sent too fast and
980 * by the time the key is reported, some previously reported
981 * modifiers are already released. This helps ensure that the guest
982 * sees the entire modifier(s)+key sequence in a single report.
983 */
984 if (!usbHidUsageCodeIsModifier(u8HidCode))
985 {
986 int iModKey;
987
988 for (iModKey = USBHID_MODIFIER_FIRST; iModKey <= USBHID_MODIFIER_LAST; ++iModKey)
989 if (pThis->abDepressedKeys[iModKey])
990 pThis->abUnreportedKeys[iModKey] = 1;
991 }
992 }
993 else
994 fHaveEvent = false;
995 pThis->abDepressedKeys[u8HidCode] = 1;
996 }
997 else
998 {
999 /* For stupid Korean keyboards, we have to fake a key up/down sequence
1000 * because they only send break codes for Hangul/Hanja keys.
1001 */
1002 if (u8HidCode == 0x90 || u8HidCode == 0x91)
1003 pThis->abUnreportedKeys[u8HidCode] = 1;
1004 pThis->abDepressedKeys[u8HidCode] = 0;
1005 }
1006
1007
1008 /* Send a report if the host is already waiting for it. */
1009 if (fHaveEvent)
1010 usbHidSendReport(pThis);
1011 }
1012 }
1013
1014 RTCritSectLeave(&pThis->CritSect);
1015
1016 return VINF_SUCCESS;
1017}
1018
1019/**
1020 * @copydoc PDMUSBREG::pfnUrbReap
1021 */
1022static DECLCALLBACK(PVUSBURB) usbHidUrbReap(PPDMUSBINS pUsbIns, RTMSINTERVAL cMillies)
1023{
1024 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1025 //LogFlow(("usbHidUrbReap/#%u: cMillies=%u\n", pUsbIns->iInstance, cMillies));
1026
1027 RTCritSectEnter(&pThis->CritSect);
1028
1029 PVUSBURB pUrb = usbHidQueueRemoveHead(&pThis->DoneQueue);
1030 if (!pUrb && cMillies)
1031 {
1032 /* Wait */
1033 pThis->fHaveDoneQueueWaiter = true;
1034 RTCritSectLeave(&pThis->CritSect);
1035
1036 RTSemEventWait(pThis->hEvtDoneQueue, cMillies);
1037
1038 RTCritSectEnter(&pThis->CritSect);
1039 pThis->fHaveDoneQueueWaiter = false;
1040
1041 pUrb = usbHidQueueRemoveHead(&pThis->DoneQueue);
1042 }
1043
1044 RTCritSectLeave(&pThis->CritSect);
1045
1046 if (pUrb)
1047 Log(("usbHidUrbReap/#%u: pUrb=%p:%s\n", pUsbIns->iInstance, pUrb, pUrb->pszDesc));
1048 return pUrb;
1049}
1050
1051
1052/**
1053 * @copydoc PDMUSBREG::pfnWakeup
1054 */
1055static DECLCALLBACK(int) usbHidWakeup(PPDMUSBINS pUsbIns)
1056{
1057 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1058
1059 return RTSemEventSignal(pThis->hEvtDoneQueue);
1060}
1061
1062
1063/**
1064 * @copydoc PDMUSBREG::pfnUrbCancel
1065 */
1066static DECLCALLBACK(int) usbHidUrbCancel(PPDMUSBINS pUsbIns, PVUSBURB pUrb)
1067{
1068 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1069 LogFlow(("usbHidUrbCancel/#%u: pUrb=%p:%s\n", pUsbIns->iInstance, pUrb, pUrb->pszDesc));
1070 RTCritSectEnter(&pThis->CritSect);
1071
1072 /*
1073 * Remove the URB from the to-host queue and move it onto the done queue.
1074 */
1075 if (usbHidQueueRemove(&pThis->ToHostQueue, pUrb))
1076 usbHidLinkDone(pThis, pUrb);
1077
1078 RTCritSectLeave(&pThis->CritSect);
1079 return VINF_SUCCESS;
1080}
1081
1082
1083/**
1084 * Handles request sent to the inbound (device to host) interrupt pipe. This is
1085 * rather different from bulk requests because an interrupt read URB may complete
1086 * after arbitrarily long time.
1087 */
1088static int usbHidHandleIntrDevToHost(PUSBHID pThis, PUSBHIDEP pEp, PVUSBURB pUrb)
1089{
1090 /*
1091 * Stall the request if the pipe is halted.
1092 */
1093 if (RT_UNLIKELY(pEp->fHalted))
1094 return usbHidCompleteStall(pThis, NULL, pUrb, "Halted pipe");
1095
1096 /*
1097 * Deal with the URB according to the state.
1098 */
1099 switch (pThis->enmState)
1100 {
1101 /*
1102 * We've data left to transfer to the host.
1103 */
1104 case USBHIDREQSTATE_DATA_TO_HOST:
1105 {
1106 AssertFailed();
1107 Log(("usbHidHandleIntrDevToHost: Entering STATUS\n"));
1108 return usbHidCompleteOk(pThis, pUrb, 0);
1109 }
1110
1111 /*
1112 * Status transfer.
1113 */
1114 case USBHIDREQSTATE_STATUS:
1115 {
1116 AssertFailed();
1117 Log(("usbHidHandleIntrDevToHost: Entering READY\n"));
1118 pThis->enmState = USBHIDREQSTATE_READY;
1119 return usbHidCompleteOk(pThis, pUrb, 0);
1120 }
1121
1122 case USBHIDREQSTATE_READY:
1123 usbHidQueueAddTail(&pThis->ToHostQueue, pUrb);
1124 /* If device was not set idle, send the current report right away. */
1125 if (pThis->bIdle != 0 || pThis->fHasPendingChanges)
1126 usbHidSendReport(pThis);
1127 LogFlow(("usbHidHandleIntrDevToHost: Sent report via %p:%s\n", pUrb, pUrb->pszDesc));
1128 return VINF_SUCCESS;
1129
1130 /*
1131 * Bad states, stall.
1132 */
1133 default:
1134 Log(("usbHidHandleIntrDevToHost: enmState=%d cbData=%#x\n", pThis->enmState, pUrb->cbData));
1135 return usbHidCompleteStall(pThis, NULL, pUrb, "Really bad state (D2H)!");
1136 }
1137}
1138
1139
1140/**
1141 * Handles request sent to the default control pipe.
1142 */
1143static int usbHidHandleDefaultPipe(PUSBHID pThis, PUSBHIDEP pEp, PVUSBURB pUrb)
1144{
1145 PVUSBSETUP pSetup = (PVUSBSETUP)&pUrb->abData[0];
1146 LogFlow(("usbHidHandleDefaultPipe: cbData=%d\n", pUrb->cbData));
1147
1148 AssertReturn(pUrb->cbData >= sizeof(*pSetup), VERR_VUSB_FAILED_TO_QUEUE_URB);
1149
1150 if ((pSetup->bmRequestType & VUSB_REQ_MASK) == VUSB_REQ_STANDARD)
1151 {
1152 switch (pSetup->bRequest)
1153 {
1154 case VUSB_REQ_GET_DESCRIPTOR:
1155 {
1156 switch (pSetup->bmRequestType)
1157 {
1158 case VUSB_TO_DEVICE | VUSB_REQ_STANDARD | VUSB_DIR_TO_HOST:
1159 {
1160 switch (pSetup->wValue >> 8)
1161 {
1162 case VUSB_DT_STRING:
1163 Log(("usbHid: GET_DESCRIPTOR DT_STRING wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1164 break;
1165 default:
1166 Log(("usbHid: GET_DESCRIPTOR, huh? wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1167 break;
1168 }
1169 break;
1170 }
1171
1172 case VUSB_TO_INTERFACE | VUSB_REQ_STANDARD | VUSB_DIR_TO_HOST:
1173 {
1174 switch (pSetup->wValue >> 8)
1175 {
1176 case DT_IF_HID_DESCRIPTOR:
1177 {
1178 uint32_t cbCopy;
1179
1180 /* Returned data is written after the setup message. */
1181 cbCopy = pUrb->cbData - sizeof(*pSetup);
1182 cbCopy = RT_MIN(cbCopy, sizeof(g_UsbHidIfHidDesc));
1183 Log(("usbHidKbd: GET_DESCRIPTOR DT_IF_HID_DESCRIPTOR wValue=%#x wIndex=%#x cbCopy=%#x\n", pSetup->wValue, pSetup->wIndex, cbCopy));
1184 memcpy(&pUrb->abData[sizeof(*pSetup)], &g_UsbHidIfHidDesc, cbCopy);
1185 return usbHidCompleteOk(pThis, pUrb, cbCopy + sizeof(*pSetup));
1186 }
1187
1188 case DT_IF_HID_REPORT:
1189 {
1190 uint32_t cbCopy;
1191
1192 /* Returned data is written after the setup message. */
1193 cbCopy = pUrb->cbData - sizeof(*pSetup);
1194 cbCopy = RT_MIN(cbCopy, sizeof(g_UsbHidReportDesc));
1195 Log(("usbHid: GET_DESCRIPTOR DT_IF_HID_REPORT wValue=%#x wIndex=%#x cbCopy=%#x\n", pSetup->wValue, pSetup->wIndex, cbCopy));
1196 memcpy(&pUrb->abData[sizeof(*pSetup)], &g_UsbHidReportDesc, cbCopy);
1197 return usbHidCompleteOk(pThis, pUrb, cbCopy + sizeof(*pSetup));
1198 }
1199
1200 default:
1201 Log(("usbHid: GET_DESCRIPTOR, huh? wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1202 break;
1203 }
1204 break;
1205 }
1206
1207 default:
1208 Log(("usbHid: Bad GET_DESCRIPTOR req: bmRequestType=%#x\n", pSetup->bmRequestType));
1209 return usbHidCompleteStall(pThis, pEp, pUrb, "Bad GET_DESCRIPTOR");
1210 }
1211 break;
1212 }
1213
1214 case VUSB_REQ_GET_STATUS:
1215 {
1216 uint16_t wRet = 0;
1217
1218 if (pSetup->wLength != 2)
1219 {
1220 Log(("usbHid: Bad GET_STATUS req: wLength=%#x\n", pSetup->wLength));
1221 break;
1222 }
1223 Assert(pSetup->wValue == 0);
1224 switch (pSetup->bmRequestType)
1225 {
1226 case VUSB_TO_DEVICE | VUSB_REQ_STANDARD | VUSB_DIR_TO_HOST:
1227 {
1228 Assert(pSetup->wIndex == 0);
1229 Log(("usbHid: GET_STATUS (device)\n"));
1230 wRet = 0; /* Not self-powered, no remote wakeup. */
1231 memcpy(&pUrb->abData[sizeof(*pSetup)], &wRet, sizeof(wRet));
1232 return usbHidCompleteOk(pThis, pUrb, sizeof(wRet) + sizeof(*pSetup));
1233 }
1234
1235 case VUSB_TO_INTERFACE | VUSB_REQ_STANDARD | VUSB_DIR_TO_HOST:
1236 {
1237 if (pSetup->wIndex == 0)
1238 {
1239 memcpy(&pUrb->abData[sizeof(*pSetup)], &wRet, sizeof(wRet));
1240 return usbHidCompleteOk(pThis, pUrb, sizeof(wRet) + sizeof(*pSetup));
1241 }
1242 else
1243 {
1244 Log(("usbHid: GET_STATUS (interface) invalid, wIndex=%#x\n", pSetup->wIndex));
1245 }
1246 break;
1247 }
1248
1249 case VUSB_TO_ENDPOINT | VUSB_REQ_STANDARD | VUSB_DIR_TO_HOST:
1250 {
1251 if (pSetup->wIndex < RT_ELEMENTS(pThis->aEps))
1252 {
1253 wRet = pThis->aEps[pSetup->wIndex].fHalted ? 1 : 0;
1254 memcpy(&pUrb->abData[sizeof(*pSetup)], &wRet, sizeof(wRet));
1255 return usbHidCompleteOk(pThis, pUrb, sizeof(wRet) + sizeof(*pSetup));
1256 }
1257 else
1258 {
1259 Log(("usbHid: GET_STATUS (endpoint) invalid, wIndex=%#x\n", pSetup->wIndex));
1260 }
1261 break;
1262 }
1263
1264 default:
1265 Log(("usbHid: Bad GET_STATUS req: bmRequestType=%#x\n", pSetup->bmRequestType));
1266 return usbHidCompleteStall(pThis, pEp, pUrb, "Bad GET_STATUS");
1267 }
1268 break;
1269 }
1270
1271 case VUSB_REQ_CLEAR_FEATURE:
1272 break;
1273 }
1274
1275 /** @todo implement this. */
1276 Log(("usbHid: Implement standard request: bmRequestType=%#x bRequest=%#x wValue=%#x wIndex=%#x wLength=%#x\n",
1277 pSetup->bmRequestType, pSetup->bRequest, pSetup->wValue, pSetup->wIndex, pSetup->wLength));
1278
1279 usbHidCompleteStall(pThis, pEp, pUrb, "TODO: standard request stuff");
1280 }
1281 else if ((pSetup->bmRequestType & VUSB_REQ_MASK) == VUSB_REQ_CLASS)
1282 {
1283 switch (pSetup->bRequest)
1284 {
1285 case HID_REQ_SET_IDLE:
1286 {
1287 switch (pSetup->bmRequestType)
1288 {
1289 case VUSB_TO_INTERFACE | VUSB_REQ_CLASS | VUSB_DIR_TO_DEVICE:
1290 {
1291 Log(("usbHid: SET_IDLE wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1292 pThis->bIdle = pSetup->wValue >> 8;
1293 /* Consider 24ms to mean zero for keyboards (see IOUSBHIDDriver) */
1294 if (pThis->bIdle == 6) pThis->bIdle = 0;
1295 return usbHidCompleteOk(pThis, pUrb, 0);
1296 }
1297 break;
1298 }
1299 break;
1300 }
1301 case HID_REQ_GET_IDLE:
1302 {
1303 switch (pSetup->bmRequestType)
1304 {
1305 case VUSB_TO_INTERFACE | VUSB_REQ_CLASS | VUSB_DIR_TO_HOST:
1306 {
1307 Log(("usbHid: GET_IDLE wValue=%#x wIndex=%#x, returning %#x\n", pSetup->wValue, pSetup->wIndex, pThis->bIdle));
1308 pUrb->abData[sizeof(*pSetup)] = pThis->bIdle;
1309 return usbHidCompleteOk(pThis, pUrb, 1);
1310 }
1311 break;
1312 }
1313 break;
1314 }
1315 case HID_REQ_SET_REPORT:
1316 {
1317 switch (pSetup->bmRequestType)
1318 {
1319 case VUSB_TO_INTERFACE | VUSB_REQ_CLASS | VUSB_DIR_TO_DEVICE:
1320 {
1321 Log(("usbHid: SET_REPORT wValue=%#x wIndex=%#x wLength=%#x\n", pSetup->wValue, pSetup->wIndex, pSetup->wLength));
1322 usbHidSetReport(pThis, pUrb);
1323 return usbHidCompleteOk(pThis, pUrb, 0);
1324 }
1325 break;
1326 }
1327 break;
1328 }
1329 }
1330 Log(("usbHid: Unimplemented class request: bmRequestType=%#x bRequest=%#x wValue=%#x wIndex=%#x wLength=%#x\n",
1331 pSetup->bmRequestType, pSetup->bRequest, pSetup->wValue, pSetup->wIndex, pSetup->wLength));
1332
1333 usbHidCompleteStall(pThis, pEp, pUrb, "TODO: class request stuff");
1334 }
1335 else
1336 {
1337 Log(("usbHid: Unknown control msg: bmRequestType=%#x bRequest=%#x wValue=%#x wIndex=%#x wLength=%#x\n",
1338 pSetup->bmRequestType, pSetup->bRequest, pSetup->wValue, pSetup->wIndex, pSetup->wLength));
1339 return usbHidCompleteStall(pThis, pEp, pUrb, "Unknown control msg");
1340 }
1341
1342 return VINF_SUCCESS;
1343}
1344
1345
1346/**
1347 * @copydoc PDMUSBREG::pfnUrbQueue
1348 */
1349static DECLCALLBACK(int) usbHidQueue(PPDMUSBINS pUsbIns, PVUSBURB pUrb)
1350{
1351 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1352 LogFlow(("usbHidQueue/#%u: pUrb=%p:%s EndPt=%#x\n", pUsbIns->iInstance, pUrb, pUrb->pszDesc, pUrb->EndPt));
1353 RTCritSectEnter(&pThis->CritSect);
1354
1355 /*
1356 * Parse on a per end-point basis.
1357 */
1358 int rc;
1359 switch (pUrb->EndPt)
1360 {
1361 case 0:
1362 rc = usbHidHandleDefaultPipe(pThis, &pThis->aEps[0], pUrb);
1363 break;
1364
1365 case 0x81:
1366 AssertFailed();
1367 case 0x01:
1368 rc = usbHidHandleIntrDevToHost(pThis, &pThis->aEps[1], pUrb);
1369 break;
1370
1371 default:
1372 AssertMsgFailed(("EndPt=%d\n", pUrb->EndPt));
1373 rc = VERR_VUSB_FAILED_TO_QUEUE_URB;
1374 break;
1375 }
1376
1377 RTCritSectLeave(&pThis->CritSect);
1378 return rc;
1379}
1380
1381
1382/**
1383 * @copydoc PDMUSBREG::pfnUsbClearHaltedEndpoint
1384 */
1385static DECLCALLBACK(int) usbHidUsbClearHaltedEndpoint(PPDMUSBINS pUsbIns, unsigned uEndpoint)
1386{
1387 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1388 LogFlow(("usbHidUsbClearHaltedEndpoint/#%u: uEndpoint=%#x\n", pUsbIns->iInstance, uEndpoint));
1389
1390 if ((uEndpoint & ~0x80) < RT_ELEMENTS(pThis->aEps))
1391 {
1392 RTCritSectEnter(&pThis->CritSect);
1393 pThis->aEps[(uEndpoint & ~0x80)].fHalted = false;
1394 RTCritSectLeave(&pThis->CritSect);
1395 }
1396
1397 return VINF_SUCCESS;
1398}
1399
1400
1401/**
1402 * @copydoc PDMUSBREG::pfnUsbSetInterface
1403 */
1404static DECLCALLBACK(int) usbHidUsbSetInterface(PPDMUSBINS pUsbIns, uint8_t bInterfaceNumber, uint8_t bAlternateSetting)
1405{
1406 LogFlow(("usbHidUsbSetInterface/#%u: bInterfaceNumber=%u bAlternateSetting=%u\n", pUsbIns->iInstance, bInterfaceNumber, bAlternateSetting));
1407 Assert(bAlternateSetting == 0);
1408 return VINF_SUCCESS;
1409}
1410
1411
1412/**
1413 * @copydoc PDMUSBREG::pfnUsbSetConfiguration
1414 */
1415static DECLCALLBACK(int) usbHidUsbSetConfiguration(PPDMUSBINS pUsbIns, uint8_t bConfigurationValue,
1416 const void *pvOldCfgDesc, const void *pvOldIfState, const void *pvNewCfgDesc)
1417{
1418 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1419 LogFlow(("usbHidUsbSetConfiguration/#%u: bConfigurationValue=%u\n", pUsbIns->iInstance, bConfigurationValue));
1420 Assert(bConfigurationValue == 1);
1421 RTCritSectEnter(&pThis->CritSect);
1422
1423 /*
1424 * If the same config is applied more than once, it's a kind of reset.
1425 */
1426 if (pThis->bConfigurationValue == bConfigurationValue)
1427 usbHidResetWorker(pThis, NULL, true /*fSetConfig*/); /** @todo figure out the exact difference */
1428 pThis->bConfigurationValue = bConfigurationValue;
1429
1430 /*
1431 * Tell the other end that the keyboard is now enabled and wants
1432 * to receive keystrokes.
1433 */
1434 pThis->Lun0.pDrv->pfnSetActive(pThis->Lun0.pDrv, true);
1435
1436 RTCritSectLeave(&pThis->CritSect);
1437 return VINF_SUCCESS;
1438}
1439
1440
1441/**
1442 * @copydoc PDMUSBREG::pfnUsbGetDescriptorCache
1443 */
1444static DECLCALLBACK(PCPDMUSBDESCCACHE) usbHidUsbGetDescriptorCache(PPDMUSBINS pUsbIns)
1445{
1446 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1447 LogFlow(("usbHidUsbGetDescriptorCache/#%u:\n", pUsbIns->iInstance));
1448 return &g_UsbHidDescCache;
1449}
1450
1451
1452/**
1453 * @copydoc PDMUSBREG::pfnUsbReset
1454 */
1455static DECLCALLBACK(int) usbHidUsbReset(PPDMUSBINS pUsbIns, bool fResetOnLinux)
1456{
1457 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1458 LogFlow(("usbHidUsbReset/#%u:\n", pUsbIns->iInstance));
1459 RTCritSectEnter(&pThis->CritSect);
1460
1461 int rc = usbHidResetWorker(pThis, NULL, false /*fSetConfig*/);
1462
1463 RTCritSectLeave(&pThis->CritSect);
1464 return rc;
1465}
1466
1467
1468/**
1469 * @copydoc PDMUSBREG::pfnDestruct
1470 */
1471static void usbHidDestruct(PPDMUSBINS pUsbIns)
1472{
1473 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1474 LogFlow(("usbHidDestruct/#%u:\n", pUsbIns->iInstance));
1475
1476 if (RTCritSectIsInitialized(&pThis->CritSect))
1477 {
1478 /* Let whoever runs in this critical section complete. */
1479 RTCritSectEnter(&pThis->CritSect);
1480 RTCritSectLeave(&pThis->CritSect);
1481 RTCritSectDelete(&pThis->CritSect);
1482 }
1483
1484 if (pThis->hEvtDoneQueue != NIL_RTSEMEVENT)
1485 {
1486 RTSemEventDestroy(pThis->hEvtDoneQueue);
1487 pThis->hEvtDoneQueue = NIL_RTSEMEVENT;
1488 }
1489}
1490
1491
1492/**
1493 * @copydoc PDMUSBREG::pfnConstruct
1494 */
1495static DECLCALLBACK(int) usbHidConstruct(PPDMUSBINS pUsbIns, int iInstance, PCFGMNODE pCfg, PCFGMNODE pCfgGlobal)
1496{
1497 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1498 Log(("usbHidConstruct/#%u:\n", iInstance));
1499
1500 /*
1501 * Perform the basic structure initialization first so the destructor
1502 * will not misbehave.
1503 */
1504 pThis->pUsbIns = pUsbIns;
1505 pThis->hEvtDoneQueue = NIL_RTSEMEVENT;
1506 pThis->XlatState = SS_IDLE;
1507 usbHidQueueInit(&pThis->ToHostQueue);
1508 usbHidQueueInit(&pThis->DoneQueue);
1509
1510 int rc = RTCritSectInit(&pThis->CritSect);
1511 AssertRCReturn(rc, rc);
1512
1513 rc = RTSemEventCreate(&pThis->hEvtDoneQueue);
1514 AssertRCReturn(rc, rc);
1515
1516 /*
1517 * Validate and read the configuration.
1518 */
1519 rc = CFGMR3ValidateConfig(pCfg, "/", "", "", "UsbHid", iInstance);
1520 if (RT_FAILURE(rc))
1521 return rc;
1522
1523 pThis->Lun0.IBase.pfnQueryInterface = usbHidKeyboardQueryInterface;
1524 pThis->Lun0.IPort.pfnPutEvent = usbHidKeyboardPutEvent;
1525
1526 /*
1527 * Attach the keyboard driver.
1528 */
1529 rc = PDMUsbHlpDriverAttach(pUsbIns, 0 /*iLun*/, &pThis->Lun0.IBase, &pThis->Lun0.pDrvBase, "Keyboard Port");
1530 if (RT_FAILURE(rc))
1531 return PDMUsbHlpVMSetError(pUsbIns, rc, RT_SRC_POS, N_("HID failed to attach keyboard driver"));
1532
1533 pThis->Lun0.pDrv = PDMIBASE_QUERY_INTERFACE(pThis->Lun0.pDrvBase, PDMIKEYBOARDCONNECTOR);
1534 if (!pThis->Lun0.pDrv)
1535 return PDMUsbHlpVMSetError(pUsbIns, VERR_PDM_MISSING_INTERFACE, RT_SRC_POS, N_("HID failed to query keyboard interface"));
1536
1537 return VINF_SUCCESS;
1538}
1539
1540
1541/**
1542 * The USB Human Interface Device (HID) Keyboard registration record.
1543 */
1544const PDMUSBREG g_UsbHidKbd =
1545{
1546 /* u32Version */
1547 PDM_USBREG_VERSION,
1548 /* szName */
1549 "HidKeyboard",
1550 /* pszDescription */
1551 "USB HID Keyboard.",
1552 /* fFlags */
1553 0,
1554 /* cMaxInstances */
1555 ~0U,
1556 /* cbInstance */
1557 sizeof(USBHID),
1558 /* pfnConstruct */
1559 usbHidConstruct,
1560 /* pfnDestruct */
1561 usbHidDestruct,
1562 /* pfnVMInitComplete */
1563 NULL,
1564 /* pfnVMPowerOn */
1565 NULL,
1566 /* pfnVMReset */
1567 NULL,
1568 /* pfnVMSuspend */
1569 NULL,
1570 /* pfnVMResume */
1571 NULL,
1572 /* pfnVMPowerOff */
1573 NULL,
1574 /* pfnHotPlugged */
1575 NULL,
1576 /* pfnHotUnplugged */
1577 NULL,
1578 /* pfnDriverAttach */
1579 NULL,
1580 /* pfnDriverDetach */
1581 NULL,
1582 /* pfnQueryInterface */
1583 NULL,
1584 /* pfnUsbReset */
1585 usbHidUsbReset,
1586 /* pfnUsbGetDescriptorCache */
1587 usbHidUsbGetDescriptorCache,
1588 /* pfnUsbSetConfiguration */
1589 usbHidUsbSetConfiguration,
1590 /* pfnUsbSetInterface */
1591 usbHidUsbSetInterface,
1592 /* pfnUsbClearHaltedEndpoint */
1593 usbHidUsbClearHaltedEndpoint,
1594 /* pfnUrbNew */
1595 NULL/*usbHidUrbNew*/,
1596 /* pfnUrbQueue */
1597 usbHidQueue,
1598 /* pfnUrbCancel */
1599 usbHidUrbCancel,
1600 /* pfnUrbReap */
1601 usbHidUrbReap,
1602 /* pfnWakeup */
1603 usbHidWakeup,
1604 /* u32TheEnd */
1605 PDM_USBREG_VERSION
1606};
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette