VirtualBox

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

Last change on this file since 36445 was 36445, checked in by vboxsync, 14 years ago

Input/USB: comments (typo).

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