VirtualBox

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

Last change on this file since 44516 was 44022, checked in by vboxsync, 12 years ago

Typo fix.

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