PS2K.cpp revision b02e456866e14ac432ffdcb6314098ef962be65f
/** @file
* PS2K - PS/2 keyboard emulation.
*/
/*
* Copyright (C) 2007-2012 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
/*
* References:
*
* IBM PS/2 Technical Reference, Keyboards (101- and 102-Key), 1990
* Keyboard Scan Code Specification, Microsoft, 2000
*
* Notes:
* - The keyboard never sends partial scan-code sequences; if there isn't enough
* room left in the buffer for the entire sequence, the keystroke is discarded
* and an overrun code is sent instead.
* - Command responses do not disturb stored keystrokes and always have priority.
* - Caps Lock and Scroll Lock are normal keys from the keyboard's point of view.
* However, Num Lock is not and the keyboard internally tracks its state.
* - The way Print Screen works in scan set 1/2 is totally insane.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#define LOG_GROUP LOG_GROUP_DEV_KBD
#include "VBoxDD.h"
#define IN_PS2K
#include "PS2Dev.h"
/*******************************************************************************
* Defined Constants And Macros *
*******************************************************************************/
/** @name Keyboard commands sent by the system.
* @{ */
#define KCMD_LEDS 0xED
#define KCMD_ECHO 0xEE
#define KCMD_INVALID_1 0xEF
#define KCMD_SCANSET 0xF0
#define KCMD_INVALID_2 0xF1
#define KCMD_READ_ID 0xF2
#define KCMD_RATE_DELAY 0xF3
#define KCMD_ENABLE 0xF4
#define KCMD_DFLT_DISABLE 0xF5
#define KCMD_SET_DEFAULT 0xF6
#define KCMD_ALL_TYPEMATIC 0xF7
#define KCMD_ALL_MK_BRK 0xF8
#define KCMD_ALL_MAKE 0xF9
#define KCMD_ALL_TMB 0xFA
#define KCMD_TYPE_MATIC 0xFB
#define KCMD_TYPE_MK_BRK 0xFC
#define KCMD_TYPE_MAKE 0xFD
#define KCMD_RESEND 0xFE
#define KCMD_RESET 0xFF
/** @} */
/** @name Keyboard responses sent to the system.
* @{ */
#define KRSP_ID1 0xAB
#define KRSP_ID2 0x83
#define KRSP_BAT_OK 0xAA
#define KRSP_ECHO 0xEE
#define KRSP_ACK 0xFA
#define KRSP_RESEND 0xFE
/** @} */
/** @name HID modifier range.
* @{ */
#define HID_MODIFIER_FIRST 0xE0
#define HID_MODIFIER_LAST 0xE8
/** @} */
/** @name USB HID additional constants
* @{ */
/** The highest USB usage code reported by VirtualBox. */
#define VBOX_USB_MAX_USAGE_CODE 0xE7
/** The size of an array needed to store all USB usage codes */
/** @} */
/** @name Modifier key states. Sorted in USB HID code order.
* @{ */
#define MOD_LCTRL 0x01
#define MOD_LSHIFT 0x02
#define MOD_LALT 0x04
#define MOD_LGUI 0x08
#define MOD_RCTRL 0x10
#define MOD_RSHIFT 0x20
#define MOD_RALT 0x40
#define MOD_RGUI 0x80
/** @} */
/* Default typematic value. */
#define KBD_DFL_RATE_DELAY 0x2B
/** Define a simple PS/2 input device queue. */
typedef struct { \
} name
/* Internal keyboard queue sizes. The input queue doesn't need to be
* extra huge and the command queue only needs to handle a few bytes.
*/
#define KBD_KEY_QUEUE_SIZE 64
#define KBD_CMD_QUEUE_SIZE 4
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
/** Scancode translator state. */
typedef enum {
SS_IDLE, /**< Starting state. */
SS_EXT, /**< E0 byte was received. */
SS_EXT1 /**< E1 byte was received. */
} scan_state_t;
/** Typematic state. */
typedef enum {
KBD_TMS_IDLE = 0, /* No typematic key active. */
KBD_TMS_32BIT_HACK = 0x7fffffff
/**
* The PS/2 keyboard instance data.
*/
typedef struct PS2K
{
/** Pointer to parent device (keyboard controller). */
/** Set if keyboard is enabled ('scans' for input). */
bool fScanning;
/** Set NumLock is on. */
bool fNumLockOn;
/** Selected scan set. */
/** Modifier key state. */
/** Currently processed command (if any). */
/** Status indicator (LED) state. */
/** Usage code of current typematic key, if any. */
/** Current typematic repeat state. */
/** Buffer holding scan codes to be sent to the host. */
/** Command response queue (priority). */
/** Currently depressed keys. */
/** Typematic delay in milliseconds. */
unsigned uTypematicDelay;
/** Typematic repeat period in milliseconds. */
unsigned uTypematicRepeat;
#if HC_ARCH_BITS == 32
#endif
/** Command delay timer - RC Ptr. */
/** Typematic timer - RC Ptr. */
/** The device critical section protecting everything - R3 Ptr */
/** Command delay timer - R3 Ptr. */
/** Typematic timer - R3 Ptr. */
/** Command delay timer - R0 Ptr. */
/** Typematic timer - R0 Ptr. */
/**
* Keyboard port - LUN#0.
*
* @implements PDMIBASE
* @implements PDMIKEYBOARDPORT
*/
struct
{
/** The base interface for the keyboard port. */
/** The keyboard port base interface. */
/** The base interface of the attached keyboard driver. */
/** The keyboard interface of the attached keyboard driver. */
} Keyboard;
#ifndef VBOX_DEVICE_STRUCT_TESTCASE
/* Key type flags. */
/* Scan Set 3 typematic defaults. */
/* Special key values. */
/* Key definition structure. */
typedef struct {
} key_def;
/* USB to PS/2 conversion table for regular keys. */
};
/*
* Note 1: The behavior of these keys depends on the state of modifier keys
* at the time the key was pressed.
*
* Note 2: The key label depends on the national version of the keyboard.
*
* Note 3: Certain keys which have their own PS/2 scancodes do not exist on
* USB keyboards; the SysReq key is an example. The SysReq key scancode needs
* to be translated to the Print Screen HID usage code. The HID usage to PS/2
* scancode conversion then generates the correct sequence depending on the
* keyboard state.
*/
/* USB to PS/2 conversion table for modifier keys. */
static const key_def aPS2ModKeys[] = {
};
/*******************************************************************************
* Global Variables *
*******************************************************************************/
/*******************************************************************************
* Internal Functions *
*******************************************************************************/
/**
* Clear a queue.
*
* @param pQ Pointer to the queue.
*/
{
}
/**
* Add a byte to a queue.
*
* @param pQ Pointer to the queue.
* @param val The byte to store.
*/
{
/* Check if queue is full. */
{
return;
}
/* Insert data and update circular buffer write position. */
}
#ifdef IN_RING3
/**
* Save a queue state.
*
* @param pSSM SSM handle to write the state to.
* @param pQ Pointer to the queue.
*/
{
int i;
* positions aren't saved as they will be rebuilt on load.
*/
/* Save queue data - only the bytes actually used (typically zero). */
}
/**
* Load a queue state.
*
* @param pSSM SSM handle to read the state from.
* @param pQ Pointer to the queue.
*
*/
{
/* On load, always put the read pointer at zero. */
/* Recalculate queue positions and load data in one go. */
return rc;
}
#endif /* IN_RING3 */
/**
* Retrieve a byte from a queue.
*
* @param pQ Pointer to the queue.
* @param pVal Pointer to storage for the byte.
*
* @return int VINF_TRY_AGAIN if queue is empty,
* VINF_SUCCESS if a byte was read.
*/
{
int rc = VINF_TRY_AGAIN;
{
rc = VINF_SUCCESS;
} else
return rc;
}
/* Convert encoded typematic value to milliseconds. Note that the values are rated
* with +/- 20% accuracy, so there's no need for high precision.
*/
{
int A, B;
unsigned period;
/* The delay is easy: (1 + value) * 250 ms */
/* The rate is more complicated: (8 + A) * 2^B * 4.17 ms */
A = val & 7;
Log(("Typematic delay %u ms, repeat period %u ms\n",
}
{
LogFlowFunc(("Set keyboard defaults\n"));
/* Set default Scan Set 3 typematic values. */
/* Clear last typematic key?? */
}
/**
* Receive and process a byte sent by the keyboard controller.
*
* @param pThis The PS/2 keyboard instance data.
* @param cmd The command (or data) byte.
*/
{
bool fHandled = true;
switch (cmd)
{
case KCMD_ECHO:
break;
case KCMD_READ_ID:
break;
case KCMD_ENABLE:
/* Clear last typematic key?? */
break;
case KCMD_DFLT_DISABLE:
break;
case KCMD_SET_DEFAULT:
break;
case KCMD_ALL_TYPEMATIC:
case KCMD_ALL_MK_BRK:
case KCMD_ALL_MAKE:
case KCMD_ALL_TMB:
///@todo Set the key types here.
break;
case KCMD_RESEND:
break;
case KCMD_RESET:
///@todo reset more?
/* Delay BAT completion; the test may take hundreds of ms. */
break;
/* The following commands need a parameter. */
case KCMD_LEDS:
case KCMD_SCANSET:
case KCMD_RATE_DELAY:
case KCMD_TYPE_MATIC:
case KCMD_TYPE_MK_BRK:
case KCMD_TYPE_MAKE:
break;
default:
/* Sending a command instead of a parameter starts the new command. */
{
case KCMD_LEDS:
#ifndef IN_RING3
return VINF_IOM_R3_IOPORT_WRITE;
#else
{
if (cmd & 0x01)
if (cmd & 0x02)
if (cmd & 0x04)
}
#endif
break;
case KCMD_SCANSET:
if (cmd == 0)
else if (cmd < 4)
{
}
/* Other values are simply ignored. */
break;
case KCMD_RATE_DELAY:
break;
default:
fHandled = false;
}
/* Fall through only to handle unrecognized commands. */
if (fHandled)
break;
case KCMD_INVALID_1:
case KCMD_INVALID_2:
break;
}
// KBCUpdateInterrupts(pThis->pParent);
return VINF_SUCCESS;
}
/**
* Send a byte (keystroke or command response) to the keyboard controller.
*
* @returns VINF_SUCCESS or VINF_TRY_AGAIN.
* @param pThis The PS/2 keyboard instance data.
* @param pb Where to return the byte we've read.
* @remarks Caller must have entered the device critical section.
*/
{
int rc;
/* Anything in the command queue has priority over data
* in the keystroke queue. Additionally, keystrokes are
* blocked if a command is currently in progress, even if
* the command queue is empty.
*/
return rc;
}
#ifdef IN_RING3
{
unsigned int i = 0;
/* Find the key definition in somewhat sparse storage. */
pKeyDef = u8HidCode >= HID_MODIFIER_FIRST ? &aPS2ModKeys[u8HidCode - HID_MODIFIER_FIRST] : &aPS2Keys[u8HidCode];
/* Some keys are not processed at all; early return. */
{
LogFlow(("Skipping key processing.\n"));
return VINF_SUCCESS;
}
* of their state in addition to sending the scan code.
*/
if (u8HidCode >= HID_MODIFIER_FIRST)
{
if (fKeyDown)
else
}
/* Toggle NumLock state. */
pThis->fNumLockOn ^= true;
{
/* The basic scan set 1 and 2 logic is the same, only the scan codes differ.
* Since scan set 2 is used almost all the time, that case is handled first.
*/
abCodes[0] = 0;
if (fKeyDown)
{
/* Process key down event. */
{
"\xE0\x7E\xE0\xF0\x7E" : "\xE0\x46\xE0\xC6");
else
"\xE1\x14\x77\xE1\xF0\x14\xF0\x77" : "\xE1\x1D\x45\xE1\x9D\xC5");
}
{
/* Print Screen depends on all of Ctrl, Shift, *and* Alt! */
"\x84" : "\x54");
"\xE0\x7C" : "\xE0\x37");
else
"\xE0\x12\xE0\x7C" : "\xE0\x2A\xE0\x37");
}
{
/* The numeric pad keys fake Shift presses or releases
* depending on Num Lock and Shift key state. The '/'
* key behaves in a similar manner but does not depend on
* the Num Lock state.
*/
{
"\xE0\xF0\x12" : "\xE0\xAA");
"\xE0\xF0\x59" : "\xE0\xB6");
}
else
{
"\xE0\x12" : "\xE0\x2A");
/* Else Shift cancels NumLock, so no prefix! */
}
}
/* Feed the bytes to the queue if there is room. */
///@todo check empty space!
while (abCodes[i])
/* Standard processing for regular keys only. */
{
}
}
{
/* Process key up event except for keys which produce none. */
/* Handle Print Screen release. */
{
/* Undo faked Print Screen state as needed. */
"\xF0\x84" : "\xD4");
"\xE0\xF0\x7C" : "\xE0\xB7");
else
"\xE0\xF0\x7C\xE0\xF0\x12" : "\xE0\xB7\xE0\xAA");
}
else
{
/* Process base scan code for less unusual keys. */
} else {
}
/* Restore shift state for gray keys. */
{
{
"\xE0\x12" : "\xE0\x2A");
"\xE0\x59" : "\xE0\x36");
}
else
{
"\xE0\xF0\x12" : "\xE0\xAA");
}
}
}
/* Feed any additional bytes to the queue if there is room. */
///@todo check empty space!
while (abCodes[i])
}
}
else
{
/* Handle Scan Set 3 - very straightforward. */
if (fKeyDown)
{
}
else
{
/* Send a key release code unless it's a make only key. */
///@todo Look up the current typematic setting, not the default!
{
}
}
}
/* Set up or cancel typematic key repeat. */
if (fKeyDown)
{
{
}
}
else
{
pThis->u8TypematicKey = 0;
///@todo Cancel timer right away?
///@todo Cancel timer before pushing key up code!?
}
/* Poke the KBC to update its state. */
return VINF_SUCCESS;
}
/* Timer handler for emulating typematic keys. Note that only the last key
* held down repeats (if typematic).
*/
{
/* If the current typematic key is zero, the repeat was canceled just when
* the timer was about to run. In that case, do nothing.
*/
if (pThis->u8TypematicKey)
{
{
}
}
}
/* The keyboard BAT is specified to take several hundred milliseconds. We need
* to delay sending the result to the host for at least a tiny little while.
*/
{
///@todo Might want a PS2KCompleteCommand() to push last response, clear command, and kick the KBC...
/* Give the KBC a kick. */
}
/* Release any and all currently depressed keys. Used whenever the guest keyboard
* is likely to be out of sync with the host, such as when loading a saved state
* or resuming a suspended host.
*/
{
LogFlowFunc(("Releasing keys...\n"));
{
}
LogFlowFunc(("Done releasing keys\n"));
}
/**
* Debug device info handler. Prints basic keyboard state.
*
* @param pDevIns Device instance which registered the info.
* @param pHlp Callback functions for doing output.
* @param pszArgs Argument string. Optional and specific to the handler.
*/
static DECLCALLBACK(void) ps2kInfoState(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
{
}
/* -=-=-=-=-=- Keyboard: IBase -=-=-=-=-=- */
/**
* @interface_method_impl{PDMIBASE,pfnQueryInterface}
*/
{
return NULL;
}
/* -=-=-=-=-=- Keyboard: IKeyboardPort -=-=-=-=-=- */
/**
* Keyboard event handler.
*
* @returns VBox status code.
* @param pThis The PS2 keyboard instance data.
* @param u32Usage USB HID usage code with key
*/
{
bool fKeyDown;
bool fHaveEvent = true;
int rc = VINF_SUCCESS;
/* Extract the usage code and ensure it's valid. */
if (fKeyDown)
{
/* Due to host key repeat, we can get key events for keys which are
* already depressed. We need to ignore those. */
fHaveEvent = false;
}
else
{
/* NB: We allow key release events for keys which aren't depressed.
* That is unlikely to happen and should not cause trouble.
*/
}
if (fHaveEvent)
{
}
return rc;
}
{
int rc;
/* The 'BAT fail' scancode is reused as a signal to release keys. No actual
* key is allowed to use this scancode.
*/
{
}
else
{
}
return VINF_SUCCESS;
}
/**
* Attach command.
*
* This is called to let the device attach to a driver for a
* specified LUN.
*
* This is like plugging in the keyboard after turning on the
* system.
*
* @returns VBox status code.
* @param pThis The PS/2 keyboard instance data.
* @param pDevIns The device instance.
* @param iLUN The logical unit which is being detached.
* @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
*/
{
int rc;
/* The LUN must be 0, i.e. keyboard. */
("PS/2 keyboard does not support hotplugging\n"),
rc = PDMDevHlpDriverAttach(pDevIns, iLUN, &pThis->Keyboard.IBase, &pThis->Keyboard.pDrvBase, "Keyboard Port");
if (RT_SUCCESS(rc))
{
{
}
}
else if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
{
Log(("%s/%d: warning: no driver attached to LUN #0!\n", pDevIns->pReg->szName, pDevIns->iInstance));
rc = VINF_SUCCESS;
}
else
return rc;
}
{
LogFlowFunc(("Saving PS2K state\n"));
/* Save the basic keyboard state. */
/* Save the command and keystroke queues. */
/* Save the command delay timer. Note that the typematic repeat
* timer is *not* saved.
*/
/* Save any pressed keys. This is necessary to avoid "stuck"
* keys after a restore. Needs two passes.
*/
for (unsigned i = 0; i < sizeof(pThis->abDepressedKeys); ++i)
if (pThis->abDepressedKeys[i])
++cPressed;
/* Save the typematic settings for Scan Set 3. */
/* Currently not implemented. */
}
{
int rc;
/* Load the basic keyboard state. */
/* Load the command and keystroke queues. */
/* Load the command delay timer, just in case. */
/* Fake key up events for keys that were held down at the time the state was saved. */
/* If any keys were down, load and then release them. */
if (cPressed)
{
for (unsigned i = 0; i < cPressed; ++i)
{
}
}
/* Load typematic settings for Scan Set 3. */
while (cbTMSSize--)
{
}
return rc;
}
{
/* This *must* be done after the inital load because it may trigger
* interrupts and change the interrupt controller state.
*/
return VINF_SUCCESS;
}
{
LogFlowFunc(("Resetting PS2K\n"));
pThis->u8Modifiers = 0;
pThis->u8TypematicKey = 0;
/* Clear queues and any pressed keys. */
/* Activate the PS/2 keyboard by default. */
}
{
LogFlowFunc(("Relocating PS2K\n"));
}
{
int rc;
/* Initialize the queues. */
/*
* Initialize the critical section pointer(s).
*/
/*
*/
if (RT_FAILURE(rc))
return rc;
/*
* Create the command delay timer.
*/
if (RT_FAILURE(rc))
return rc;
/*
* Register debugger info callbacks.
*/
return rc;
}
#endif
///@todo The following should live with the KBC implementation.
/* Table used by the keyboard controller to optionally translate the incoming
* keyboard data. Note that the translation is designed for essentially taking
* Scan Set 2 input and producing Scan Set 1 output, but can be turned on and
* off regardless of what the keyboard is sending.
*/
0xff,0x43,0x41,0x3f,0x3d,0x3b,0x3c,0x58,0x64,0x44,0x42,0x40,0x3e,0x0f,0x29,0x59,
0x65,0x38,0x2a,0x70,0x1d,0x10,0x02,0x5a,0x66,0x71,0x2c,0x1f,0x1e,0x11,0x03,0x5b,
0x67,0x2e,0x2d,0x20,0x12,0x05,0x04,0x5c,0x68,0x39,0x2f,0x21,0x14,0x13,0x06,0x5d,
0x69,0x31,0x30,0x23,0x22,0x15,0x07,0x5e,0x6a,0x72,0x32,0x24,0x16,0x08,0x09,0x5f,
0x6b,0x33,0x25,0x17,0x18,0x0b,0x0a,0x60,0x6c,0x34,0x35,0x26,0x27,0x19,0x0c,0x61,
0x6d,0x73,0x28,0x74,0x1a,0x0d,0x62,0x6e,0x3a,0x36,0x1c,0x1b,0x75,0x2b,0x63,0x76,
0x55,0x56,0x77,0x78,0x79,0x7a,0x0e,0x7b,0x7c,0x4f,0x7d,0x4b,0x47,0x7e,0x7f,0x6f,
0x52,0x53,0x50,0x4c,0x4d,0x48,0x01,0x45,0x57,0x4e,0x51,0x4a,0x37,0x49,0x46,0x54
};
/**
* Convert an AT (Scan Set 2) scancode to PC (Scan Set 1).
*
* @param state Current state of the translator
* (xlat_state_t).
* @param scanIn Incoming scan code.
* @param pScanOut Pointer to outgoing scan code. The
* contents are only valid if returned
* state is not XS_BREAK.
*
* @return xlat_state_t New state of the translator.
*/
{
/* Preprocess the scan code for a 128-entry translation table. */
scan_in = 0x02;
scan_in = 0x7f;
else
/* Values 0x80 and above are passed through, except for 0xF0
* which indicates a key release.
*/
if (scan_in < 0x80)
{
/* Turn into break code if required. */
scan_out |= 0x80;
}
else
{
/* NB: F0 E0 10 will be translated to E0 E5 (high bit set on last byte)! */
}
LogFlowFunc(("scan code %02X translated to %02X; new state is %d\n",
return state;
}
#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */