VirtualBox

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

Last change on this file since 47631 was 47316, checked in by vboxsync, 11 years ago

UsbKbd: Do not drop SysReq.

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