VirtualBox

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

Last change on this file since 39976 was 37795, checked in by vboxsync, 13 years ago

Devices: use helpers

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