VirtualBox

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

Last change on this file since 49068 was 48947, checked in by vboxsync, 11 years ago

Devices: Whitespace and svn:keyword cleanups by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 54.3 KB
Line 
1/* $Id: UsbKbd.cpp 48947 2013-10-07 21:41:00Z 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/**
928 * Keyboard event handler.
929 *
930 * @returns VBox status code.
931 * @param pInterface Pointer to the keyboard port interface (KBDState::Keyboard.IPort).
932 * @param u8KeyCode The keycode.
933 */
934static DECLCALLBACK(int) usbHidKeyboardPutEvent(PPDMIKEYBOARDPORT pInterface, uint8_t u8KeyCode)
935{
936 PUSBHID pThis = RT_FROM_MEMBER(pInterface, USBHID, Lun0.IPort);
937 uint32_t u32Usage = 0;
938 uint8_t u8HidCode;
939 int fKeyDown;
940 bool fHaveEvent = true;
941
942 RTCritSectEnter(&pThis->CritSect);
943
944 pThis->XlatState = ScancodeToHidUsage(pThis->XlatState, u8KeyCode, &u32Usage);
945
946 if (pThis->XlatState == SS_IDLE)
947 {
948 /* The usage code is valid. */
949 fKeyDown = !(u32Usage & 0x80000000);
950 u8HidCode = u32Usage & 0xFF;
951 AssertReturn(u8HidCode <= VBOX_USB_MAX_USAGE_CODE, VERR_INTERNAL_ERROR);
952
953 LogFlowFunc(("key %s: 0x%x->0x%x\n",
954 fKeyDown ? "down" : "up", u8KeyCode, u8HidCode));
955
956 if (fKeyDown)
957 {
958 /* Due to host key repeat, we can get key events for keys which are
959 * already depressed. */
960 if (!pThis->abDepressedKeys[u8HidCode])
961 {
962 pThis->abUnreportedKeys[u8HidCode] = 1;
963
964 /* If a non-modifier key is being marked as unreported, also set
965 * all currently depressed modifer keys as unreported. This avoids
966 * problems where a simulated key sequence is sent too fast and
967 * by the time the key is reported, some previously reported
968 * modifiers are already released. This helps ensure that the guest
969 * sees the entire modifier(s)+key sequence in a single report.
970 */
971 if (!usbHidUsageCodeIsModifier(u8HidCode))
972 {
973 int iModKey;
974
975 for (iModKey = USBHID_MODIFIER_FIRST; iModKey <= USBHID_MODIFIER_LAST; ++iModKey)
976 if (pThis->abDepressedKeys[iModKey])
977 pThis->abUnreportedKeys[iModKey] = 1;
978 }
979 }
980 else
981 fHaveEvent = false;
982 pThis->abDepressedKeys[u8HidCode] = 1;
983 }
984 else
985 {
986 /* For stupid Korean keyboards, we have to fake a key up/down sequence
987 * because they only send break codes for Hangul/Hanja keys.
988 */
989 if (u8HidCode == 0x90 || u8HidCode == 0x91)
990 pThis->abUnreportedKeys[u8HidCode] = 1;
991 pThis->abDepressedKeys[u8HidCode] = 0;
992 }
993
994
995 /* Send a report if the host is already waiting for it. */
996 if (fHaveEvent)
997 usbHidSendReport(pThis);
998 }
999
1000 RTCritSectLeave(&pThis->CritSect);
1001
1002 return VINF_SUCCESS;
1003}
1004
1005/**
1006 * @copydoc PDMUSBREG::pfnUrbReap
1007 */
1008static DECLCALLBACK(PVUSBURB) usbHidUrbReap(PPDMUSBINS pUsbIns, RTMSINTERVAL cMillies)
1009{
1010 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1011 //LogFlow(("usbHidUrbReap/#%u: cMillies=%u\n", pUsbIns->iInstance, cMillies));
1012
1013 RTCritSectEnter(&pThis->CritSect);
1014
1015 PVUSBURB pUrb = usbHidQueueRemoveHead(&pThis->DoneQueue);
1016 if (!pUrb && cMillies)
1017 {
1018 /* Wait */
1019 pThis->fHaveDoneQueueWaiter = true;
1020 RTCritSectLeave(&pThis->CritSect);
1021
1022 RTSemEventWait(pThis->hEvtDoneQueue, cMillies);
1023
1024 RTCritSectEnter(&pThis->CritSect);
1025 pThis->fHaveDoneQueueWaiter = false;
1026
1027 pUrb = usbHidQueueRemoveHead(&pThis->DoneQueue);
1028 }
1029
1030 RTCritSectLeave(&pThis->CritSect);
1031
1032 if (pUrb)
1033 Log(("usbHidUrbReap/#%u: pUrb=%p:%s\n", pUsbIns->iInstance, pUrb, pUrb->pszDesc));
1034 return pUrb;
1035}
1036
1037
1038/**
1039 * @copydoc PDMUSBREG::pfnUrbCancel
1040 */
1041static DECLCALLBACK(int) usbHidUrbCancel(PPDMUSBINS pUsbIns, PVUSBURB pUrb)
1042{
1043 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1044 LogFlow(("usbHidUrbCancel/#%u: pUrb=%p:%s\n", pUsbIns->iInstance, pUrb, pUrb->pszDesc));
1045 RTCritSectEnter(&pThis->CritSect);
1046
1047 /*
1048 * Remove the URB from the to-host queue and move it onto the done queue.
1049 */
1050 if (usbHidQueueRemove(&pThis->ToHostQueue, pUrb))
1051 usbHidLinkDone(pThis, pUrb);
1052
1053 RTCritSectLeave(&pThis->CritSect);
1054 return VINF_SUCCESS;
1055}
1056
1057
1058/**
1059 * Handles request sent to the inbound (device to host) interrupt pipe. This is
1060 * rather different from bulk requests because an interrupt read URB may complete
1061 * after arbitrarily long time.
1062 */
1063static int usbHidHandleIntrDevToHost(PUSBHID pThis, PUSBHIDEP pEp, PVUSBURB pUrb)
1064{
1065 /*
1066 * Stall the request if the pipe is halted.
1067 */
1068 if (RT_UNLIKELY(pEp->fHalted))
1069 return usbHidCompleteStall(pThis, NULL, pUrb, "Halted pipe");
1070
1071 /*
1072 * Deal with the URB according to the state.
1073 */
1074 switch (pThis->enmState)
1075 {
1076 /*
1077 * We've data left to transfer to the host.
1078 */
1079 case USBHIDREQSTATE_DATA_TO_HOST:
1080 {
1081 AssertFailed();
1082 Log(("usbHidHandleIntrDevToHost: Entering STATUS\n"));
1083 return usbHidCompleteOk(pThis, pUrb, 0);
1084 }
1085
1086 /*
1087 * Status transfer.
1088 */
1089 case USBHIDREQSTATE_STATUS:
1090 {
1091 AssertFailed();
1092 Log(("usbHidHandleIntrDevToHost: Entering READY\n"));
1093 pThis->enmState = USBHIDREQSTATE_READY;
1094 return usbHidCompleteOk(pThis, pUrb, 0);
1095 }
1096
1097 case USBHIDREQSTATE_READY:
1098 usbHidQueueAddTail(&pThis->ToHostQueue, pUrb);
1099 /* If device was not set idle, send the current report right away. */
1100 if (pThis->bIdle != 0 || pThis->fHasPendingChanges)
1101 usbHidSendReport(pThis);
1102 LogFlow(("usbHidHandleIntrDevToHost: Sent report via %p:%s\n", pUrb, pUrb->pszDesc));
1103 return VINF_SUCCESS;
1104
1105 /*
1106 * Bad states, stall.
1107 */
1108 default:
1109 Log(("usbHidHandleIntrDevToHost: enmState=%d cbData=%#x\n", pThis->enmState, pUrb->cbData));
1110 return usbHidCompleteStall(pThis, NULL, pUrb, "Really bad state (D2H)!");
1111 }
1112}
1113
1114
1115/**
1116 * Handles request sent to the default control pipe.
1117 */
1118static int usbHidHandleDefaultPipe(PUSBHID pThis, PUSBHIDEP pEp, PVUSBURB pUrb)
1119{
1120 PVUSBSETUP pSetup = (PVUSBSETUP)&pUrb->abData[0];
1121 LogFlow(("usbHidHandleDefaultPipe: cbData=%d\n", pUrb->cbData));
1122
1123 AssertReturn(pUrb->cbData >= sizeof(*pSetup), VERR_VUSB_FAILED_TO_QUEUE_URB);
1124
1125 if ((pSetup->bmRequestType & VUSB_REQ_MASK) == VUSB_REQ_STANDARD)
1126 {
1127 switch (pSetup->bRequest)
1128 {
1129 case VUSB_REQ_GET_DESCRIPTOR:
1130 {
1131 switch (pSetup->bmRequestType)
1132 {
1133 case VUSB_TO_DEVICE | VUSB_REQ_STANDARD | VUSB_DIR_TO_HOST:
1134 {
1135 switch (pSetup->wValue >> 8)
1136 {
1137 case VUSB_DT_STRING:
1138 Log(("usbHid: GET_DESCRIPTOR DT_STRING wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1139 break;
1140 default:
1141 Log(("usbHid: GET_DESCRIPTOR, huh? wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1142 break;
1143 }
1144 break;
1145 }
1146
1147 case VUSB_TO_INTERFACE | VUSB_REQ_STANDARD | VUSB_DIR_TO_HOST:
1148 {
1149 switch (pSetup->wValue >> 8)
1150 {
1151 case DT_IF_HID_DESCRIPTOR:
1152 {
1153 uint32_t cbCopy;
1154
1155 /* Returned data is written after the setup message. */
1156 cbCopy = pUrb->cbData - sizeof(*pSetup);
1157 cbCopy = RT_MIN(cbCopy, sizeof(g_UsbHidIfHidDesc));
1158 Log(("usbHidKbd: GET_DESCRIPTOR DT_IF_HID_DESCRIPTOR wValue=%#x wIndex=%#x cbCopy=%#x\n", pSetup->wValue, pSetup->wIndex, cbCopy));
1159 memcpy(&pUrb->abData[sizeof(*pSetup)], &g_UsbHidIfHidDesc, cbCopy);
1160 return usbHidCompleteOk(pThis, pUrb, cbCopy + sizeof(*pSetup));
1161 }
1162
1163 case DT_IF_HID_REPORT:
1164 {
1165 uint32_t cbCopy;
1166
1167 /* Returned data is written after the setup message. */
1168 cbCopy = pUrb->cbData - sizeof(*pSetup);
1169 cbCopy = RT_MIN(cbCopy, sizeof(g_UsbHidReportDesc));
1170 Log(("usbHid: GET_DESCRIPTOR DT_IF_HID_REPORT wValue=%#x wIndex=%#x cbCopy=%#x\n", pSetup->wValue, pSetup->wIndex, cbCopy));
1171 memcpy(&pUrb->abData[sizeof(*pSetup)], &g_UsbHidReportDesc, cbCopy);
1172 return usbHidCompleteOk(pThis, pUrb, cbCopy + sizeof(*pSetup));
1173 }
1174
1175 default:
1176 Log(("usbHid: GET_DESCRIPTOR, huh? wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1177 break;
1178 }
1179 break;
1180 }
1181
1182 default:
1183 Log(("usbHid: Bad GET_DESCRIPTOR req: bmRequestType=%#x\n", pSetup->bmRequestType));
1184 return usbHidCompleteStall(pThis, pEp, pUrb, "Bad GET_DESCRIPTOR");
1185 }
1186 break;
1187 }
1188
1189 case VUSB_REQ_GET_STATUS:
1190 {
1191 uint16_t wRet = 0;
1192
1193 if (pSetup->wLength != 2)
1194 {
1195 Log(("usbHid: Bad GET_STATUS req: wLength=%#x\n", pSetup->wLength));
1196 break;
1197 }
1198 Assert(pSetup->wValue == 0);
1199 switch (pSetup->bmRequestType)
1200 {
1201 case VUSB_TO_DEVICE | VUSB_REQ_STANDARD | VUSB_DIR_TO_HOST:
1202 {
1203 Assert(pSetup->wIndex == 0);
1204 Log(("usbHid: GET_STATUS (device)\n"));
1205 wRet = 0; /* Not self-powered, no remote wakeup. */
1206 memcpy(&pUrb->abData[sizeof(*pSetup)], &wRet, sizeof(wRet));
1207 return usbHidCompleteOk(pThis, pUrb, sizeof(wRet) + sizeof(*pSetup));
1208 }
1209
1210 case VUSB_TO_INTERFACE | VUSB_REQ_STANDARD | VUSB_DIR_TO_HOST:
1211 {
1212 if (pSetup->wIndex == 0)
1213 {
1214 memcpy(&pUrb->abData[sizeof(*pSetup)], &wRet, sizeof(wRet));
1215 return usbHidCompleteOk(pThis, pUrb, sizeof(wRet) + sizeof(*pSetup));
1216 }
1217 else
1218 {
1219 Log(("usbHid: GET_STATUS (interface) invalid, wIndex=%#x\n", pSetup->wIndex));
1220 }
1221 break;
1222 }
1223
1224 case VUSB_TO_ENDPOINT | VUSB_REQ_STANDARD | VUSB_DIR_TO_HOST:
1225 {
1226 if (pSetup->wIndex < RT_ELEMENTS(pThis->aEps))
1227 {
1228 wRet = pThis->aEps[pSetup->wIndex].fHalted ? 1 : 0;
1229 memcpy(&pUrb->abData[sizeof(*pSetup)], &wRet, sizeof(wRet));
1230 return usbHidCompleteOk(pThis, pUrb, sizeof(wRet) + sizeof(*pSetup));
1231 }
1232 else
1233 {
1234 Log(("usbHid: GET_STATUS (endpoint) invalid, wIndex=%#x\n", pSetup->wIndex));
1235 }
1236 break;
1237 }
1238
1239 default:
1240 Log(("usbHid: Bad GET_STATUS req: bmRequestType=%#x\n", pSetup->bmRequestType));
1241 return usbHidCompleteStall(pThis, pEp, pUrb, "Bad GET_STATUS");
1242 }
1243 break;
1244 }
1245
1246 case VUSB_REQ_CLEAR_FEATURE:
1247 break;
1248 }
1249
1250 /** @todo implement this. */
1251 Log(("usbHid: Implement standard request: bmRequestType=%#x bRequest=%#x wValue=%#x wIndex=%#x wLength=%#x\n",
1252 pSetup->bmRequestType, pSetup->bRequest, pSetup->wValue, pSetup->wIndex, pSetup->wLength));
1253
1254 usbHidCompleteStall(pThis, pEp, pUrb, "TODO: standard request stuff");
1255 }
1256 else if ((pSetup->bmRequestType & VUSB_REQ_MASK) == VUSB_REQ_CLASS)
1257 {
1258 switch (pSetup->bRequest)
1259 {
1260 case HID_REQ_SET_IDLE:
1261 {
1262 switch (pSetup->bmRequestType)
1263 {
1264 case VUSB_TO_INTERFACE | VUSB_REQ_CLASS | VUSB_DIR_TO_DEVICE:
1265 {
1266 Log(("usbHid: SET_IDLE wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1267 pThis->bIdle = pSetup->wValue >> 8;
1268 /* Consider 24ms to mean zero for keyboards (see IOUSBHIDDriver) */
1269 if (pThis->bIdle == 6) pThis->bIdle = 0;
1270 return usbHidCompleteOk(pThis, pUrb, 0);
1271 }
1272 break;
1273 }
1274 break;
1275 }
1276 case HID_REQ_GET_IDLE:
1277 {
1278 switch (pSetup->bmRequestType)
1279 {
1280 case VUSB_TO_INTERFACE | VUSB_REQ_CLASS | VUSB_DIR_TO_HOST:
1281 {
1282 Log(("usbHid: GET_IDLE wValue=%#x wIndex=%#x, returning %#x\n", pSetup->wValue, pSetup->wIndex, pThis->bIdle));
1283 pUrb->abData[sizeof(*pSetup)] = pThis->bIdle;
1284 return usbHidCompleteOk(pThis, pUrb, 1);
1285 }
1286 break;
1287 }
1288 break;
1289 }
1290 case HID_REQ_SET_REPORT:
1291 {
1292 switch (pSetup->bmRequestType)
1293 {
1294 case VUSB_TO_INTERFACE | VUSB_REQ_CLASS | VUSB_DIR_TO_DEVICE:
1295 {
1296 Log(("usbHid: SET_REPORT wValue=%#x wIndex=%#x wLength=%#x\n", pSetup->wValue, pSetup->wIndex, pSetup->wLength));
1297 usbHidSetReport(pThis, pUrb);
1298 return usbHidCompleteOk(pThis, pUrb, 0);
1299 }
1300 break;
1301 }
1302 break;
1303 }
1304 }
1305 Log(("usbHid: Unimplemented class request: bmRequestType=%#x bRequest=%#x wValue=%#x wIndex=%#x wLength=%#x\n",
1306 pSetup->bmRequestType, pSetup->bRequest, pSetup->wValue, pSetup->wIndex, pSetup->wLength));
1307
1308 usbHidCompleteStall(pThis, pEp, pUrb, "TODO: class request stuff");
1309 }
1310 else
1311 {
1312 Log(("usbHid: Unknown control msg: bmRequestType=%#x bRequest=%#x wValue=%#x wIndex=%#x wLength=%#x\n",
1313 pSetup->bmRequestType, pSetup->bRequest, pSetup->wValue, pSetup->wIndex, pSetup->wLength));
1314 return usbHidCompleteStall(pThis, pEp, pUrb, "Unknown control msg");
1315 }
1316
1317 return VINF_SUCCESS;
1318}
1319
1320
1321/**
1322 * @copydoc PDMUSBREG::pfnUrbQueue
1323 */
1324static DECLCALLBACK(int) usbHidQueue(PPDMUSBINS pUsbIns, PVUSBURB pUrb)
1325{
1326 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1327 LogFlow(("usbHidQueue/#%u: pUrb=%p:%s EndPt=%#x\n", pUsbIns->iInstance, pUrb, pUrb->pszDesc, pUrb->EndPt));
1328 RTCritSectEnter(&pThis->CritSect);
1329
1330 /*
1331 * Parse on a per end-point basis.
1332 */
1333 int rc;
1334 switch (pUrb->EndPt)
1335 {
1336 case 0:
1337 rc = usbHidHandleDefaultPipe(pThis, &pThis->aEps[0], pUrb);
1338 break;
1339
1340 case 0x81:
1341 AssertFailed();
1342 case 0x01:
1343 rc = usbHidHandleIntrDevToHost(pThis, &pThis->aEps[1], pUrb);
1344 break;
1345
1346 default:
1347 AssertMsgFailed(("EndPt=%d\n", pUrb->EndPt));
1348 rc = VERR_VUSB_FAILED_TO_QUEUE_URB;
1349 break;
1350 }
1351
1352 RTCritSectLeave(&pThis->CritSect);
1353 return rc;
1354}
1355
1356
1357/**
1358 * @copydoc PDMUSBREG::pfnUsbClearHaltedEndpoint
1359 */
1360static DECLCALLBACK(int) usbHidUsbClearHaltedEndpoint(PPDMUSBINS pUsbIns, unsigned uEndpoint)
1361{
1362 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1363 LogFlow(("usbHidUsbClearHaltedEndpoint/#%u: uEndpoint=%#x\n", pUsbIns->iInstance, uEndpoint));
1364
1365 if ((uEndpoint & ~0x80) < RT_ELEMENTS(pThis->aEps))
1366 {
1367 RTCritSectEnter(&pThis->CritSect);
1368 pThis->aEps[(uEndpoint & ~0x80)].fHalted = false;
1369 RTCritSectLeave(&pThis->CritSect);
1370 }
1371
1372 return VINF_SUCCESS;
1373}
1374
1375
1376/**
1377 * @copydoc PDMUSBREG::pfnUsbSetInterface
1378 */
1379static DECLCALLBACK(int) usbHidUsbSetInterface(PPDMUSBINS pUsbIns, uint8_t bInterfaceNumber, uint8_t bAlternateSetting)
1380{
1381 LogFlow(("usbHidUsbSetInterface/#%u: bInterfaceNumber=%u bAlternateSetting=%u\n", pUsbIns->iInstance, bInterfaceNumber, bAlternateSetting));
1382 Assert(bAlternateSetting == 0);
1383 return VINF_SUCCESS;
1384}
1385
1386
1387/**
1388 * @copydoc PDMUSBREG::pfnUsbSetConfiguration
1389 */
1390static DECLCALLBACK(int) usbHidUsbSetConfiguration(PPDMUSBINS pUsbIns, uint8_t bConfigurationValue,
1391 const void *pvOldCfgDesc, const void *pvOldIfState, const void *pvNewCfgDesc)
1392{
1393 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1394 LogFlow(("usbHidUsbSetConfiguration/#%u: bConfigurationValue=%u\n", pUsbIns->iInstance, bConfigurationValue));
1395 Assert(bConfigurationValue == 1);
1396 RTCritSectEnter(&pThis->CritSect);
1397
1398 /*
1399 * If the same config is applied more than once, it's a kind of reset.
1400 */
1401 if (pThis->bConfigurationValue == bConfigurationValue)
1402 usbHidResetWorker(pThis, NULL, true /*fSetConfig*/); /** @todo figure out the exact difference */
1403 pThis->bConfigurationValue = bConfigurationValue;
1404
1405 /*
1406 * Tell the other end that the keyboard is now enabled and wants
1407 * to receive keystrokes.
1408 */
1409 pThis->Lun0.pDrv->pfnSetActive(pThis->Lun0.pDrv, true);
1410
1411 RTCritSectLeave(&pThis->CritSect);
1412 return VINF_SUCCESS;
1413}
1414
1415
1416/**
1417 * @copydoc PDMUSBREG::pfnUsbGetDescriptorCache
1418 */
1419static DECLCALLBACK(PCPDMUSBDESCCACHE) usbHidUsbGetDescriptorCache(PPDMUSBINS pUsbIns)
1420{
1421 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1422 LogFlow(("usbHidUsbGetDescriptorCache/#%u:\n", pUsbIns->iInstance));
1423 return &g_UsbHidDescCache;
1424}
1425
1426
1427/**
1428 * @copydoc PDMUSBREG::pfnUsbReset
1429 */
1430static DECLCALLBACK(int) usbHidUsbReset(PPDMUSBINS pUsbIns, bool fResetOnLinux)
1431{
1432 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1433 LogFlow(("usbHidUsbReset/#%u:\n", pUsbIns->iInstance));
1434 RTCritSectEnter(&pThis->CritSect);
1435
1436 int rc = usbHidResetWorker(pThis, NULL, false /*fSetConfig*/);
1437
1438 RTCritSectLeave(&pThis->CritSect);
1439 return rc;
1440}
1441
1442
1443/**
1444 * @copydoc PDMUSBREG::pfnDestruct
1445 */
1446static void usbHidDestruct(PPDMUSBINS pUsbIns)
1447{
1448 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1449 LogFlow(("usbHidDestruct/#%u:\n", pUsbIns->iInstance));
1450
1451 if (RTCritSectIsInitialized(&pThis->CritSect))
1452 {
1453 /* Let whoever runs in this critical section complete. */
1454 RTCritSectEnter(&pThis->CritSect);
1455 RTCritSectLeave(&pThis->CritSect);
1456 RTCritSectDelete(&pThis->CritSect);
1457 }
1458
1459 if (pThis->hEvtDoneQueue != NIL_RTSEMEVENT)
1460 {
1461 RTSemEventDestroy(pThis->hEvtDoneQueue);
1462 pThis->hEvtDoneQueue = NIL_RTSEMEVENT;
1463 }
1464}
1465
1466
1467/**
1468 * @copydoc PDMUSBREG::pfnConstruct
1469 */
1470static DECLCALLBACK(int) usbHidConstruct(PPDMUSBINS pUsbIns, int iInstance, PCFGMNODE pCfg, PCFGMNODE pCfgGlobal)
1471{
1472 PUSBHID pThis = PDMINS_2_DATA(pUsbIns, PUSBHID);
1473 Log(("usbHidConstruct/#%u:\n", iInstance));
1474
1475 /*
1476 * Perform the basic structure initialization first so the destructor
1477 * will not misbehave.
1478 */
1479 pThis->pUsbIns = pUsbIns;
1480 pThis->hEvtDoneQueue = NIL_RTSEMEVENT;
1481 pThis->XlatState = SS_IDLE;
1482 usbHidQueueInit(&pThis->ToHostQueue);
1483 usbHidQueueInit(&pThis->DoneQueue);
1484
1485 int rc = RTCritSectInit(&pThis->CritSect);
1486 AssertRCReturn(rc, rc);
1487
1488 rc = RTSemEventCreate(&pThis->hEvtDoneQueue);
1489 AssertRCReturn(rc, rc);
1490
1491 /*
1492 * Validate and read the configuration.
1493 */
1494 rc = CFGMR3ValidateConfig(pCfg, "/", "", "", "UsbHid", iInstance);
1495 if (RT_FAILURE(rc))
1496 return rc;
1497
1498 pThis->Lun0.IBase.pfnQueryInterface = usbHidKeyboardQueryInterface;
1499 pThis->Lun0.IPort.pfnPutEvent = usbHidKeyboardPutEvent;
1500
1501 /*
1502 * Attach the keyboard driver.
1503 */
1504 rc = PDMUsbHlpDriverAttach(pUsbIns, 0 /*iLun*/, &pThis->Lun0.IBase, &pThis->Lun0.pDrvBase, "Keyboard Port");
1505 if (RT_FAILURE(rc))
1506 return PDMUsbHlpVMSetError(pUsbIns, rc, RT_SRC_POS, N_("HID failed to attach keyboard driver"));
1507
1508 pThis->Lun0.pDrv = PDMIBASE_QUERY_INTERFACE(pThis->Lun0.pDrvBase, PDMIKEYBOARDCONNECTOR);
1509 if (!pThis->Lun0.pDrv)
1510 return PDMUsbHlpVMSetError(pUsbIns, VERR_PDM_MISSING_INTERFACE, RT_SRC_POS, N_("HID failed to query keyboard interface"));
1511
1512 return VINF_SUCCESS;
1513}
1514
1515
1516/**
1517 * The USB Human Interface Device (HID) Keyboard registration record.
1518 */
1519const PDMUSBREG g_UsbHidKbd =
1520{
1521 /* u32Version */
1522 PDM_USBREG_VERSION,
1523 /* szName */
1524 "HidKeyboard",
1525 /* pszDescription */
1526 "USB HID Keyboard.",
1527 /* fFlags */
1528 0,
1529 /* cMaxInstances */
1530 ~0U,
1531 /* cbInstance */
1532 sizeof(USBHID),
1533 /* pfnConstruct */
1534 usbHidConstruct,
1535 /* pfnDestruct */
1536 usbHidDestruct,
1537 /* pfnVMInitComplete */
1538 NULL,
1539 /* pfnVMPowerOn */
1540 NULL,
1541 /* pfnVMReset */
1542 NULL,
1543 /* pfnVMSuspend */
1544 NULL,
1545 /* pfnVMResume */
1546 NULL,
1547 /* pfnVMPowerOff */
1548 NULL,
1549 /* pfnHotPlugged */
1550 NULL,
1551 /* pfnHotUnplugged */
1552 NULL,
1553 /* pfnDriverAttach */
1554 NULL,
1555 /* pfnDriverDetach */
1556 NULL,
1557 /* pfnQueryInterface */
1558 NULL,
1559 /* pfnUsbReset */
1560 usbHidUsbReset,
1561 /* pfnUsbGetDescriptorCache */
1562 usbHidUsbGetDescriptorCache,
1563 /* pfnUsbSetConfiguration */
1564 usbHidUsbSetConfiguration,
1565 /* pfnUsbSetInterface */
1566 usbHidUsbSetInterface,
1567 /* pfnUsbClearHaltedEndpoint */
1568 usbHidUsbClearHaltedEndpoint,
1569 /* pfnUrbNew */
1570 NULL/*usbHidUrbNew*/,
1571 /* pfnUrbQueue */
1572 usbHidQueue,
1573 /* pfnUrbCancel */
1574 usbHidUrbCancel,
1575 /* pfnUrbReap */
1576 usbHidUrbReap,
1577 /* u32TheEnd */
1578 PDM_USBREG_VERSION
1579};
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