Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ powershell -ExecutionPolicy Bypass -File driver\install.ps1

## Troubleshooting

`status.ps1` sits next to the installer, in `driver` in a checkout. It reads the driver's state through a vendor feature report. That covers whether input arrives, whether the last rumble write failed and the last NTSTATUS from the side facing the controller. With `-Watch` it prints the raw Stadia input reports. The controller has to be connected.
`status.ps1` sits next to the installer, in `driver` in a checkout. It reads the driver's state through a vendor feature report. That covers whether input arrives, whether the last rumble write failed and the last NTSTATUS from the side facing the controller, and over USB how often the input reader failed and how the driver recovered. With `-Watch` it prints the raw Stadia input reports, with `-TestRecovery` it has the driver go through that recovery first. The controller has to be connected.

Rumble can only be tested through XInput, because xinputhid blocks HID output writes from above.

Expand Down
1 change: 1 addition & 0 deletions driver/bluetooth.c
Original file line number Diff line number Diff line change
Expand Up @@ -330,4 +330,5 @@ const TRANSPORT BluetoothTransport = {
BluetoothStart,
BluetoothStop,
BluetoothSendOutputReport,
NULL,
};
1 change: 1 addition & 0 deletions driver/stadia.c
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ StadiaInputReport(PDEVICE_CONTEXT Context, const UCHAR *Report, size_t Length)
UCHAR controls[PAD_CONTROLS_LEN];

AcquireSRWLockExclusive(&Context->Lock);
Context->InputReports++;
Context->RawReportLength = (UCHAR)min(Length, RAW_REPORT_MAX);
RtlCopyMemory(Context->RawReport, Report, Context->RawReportLength);
ReleaseSRWLockExclusive(&Context->Lock);
Expand Down
41 changes: 34 additions & 7 deletions driver/status.ps1
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# Asks the driver what it is doing, through the status feature report of the
# controller it presents. With -Watch it keeps printing the raw Stadia input
# reports as they change, until Ctrl+C.
param([switch]$Watch)
# reports as they change, until Ctrl+C. With -TestRecovery it first has the
# driver go through the recovery from a failed USB input reader.
param([switch]$Watch, [switch]$TestRecovery)

$ErrorActionPreference = 'Stop'

Expand All @@ -27,6 +28,8 @@ public static class WinStadiaHid {
public static extern bool HidD_GetSerialNumberString(IntPtr handle, StringBuilder buffer, int length);
[DllImport("hid.dll", SetLastError = true)]
public static extern bool HidD_GetFeature(IntPtr handle, byte[] report, int length);
[DllImport("hid.dll", SetLastError = true)]
public static extern bool HidD_SetFeature(IntPtr handle, byte[] report, int length);
[DllImport("cfgmgr32.dll", CharSet = CharSet.Unicode)]
public static extern int CM_Get_Device_Interface_List_SizeW(out uint length, ref Guid guid, string id, uint flags);
[DllImport("cfgmgr32.dll", CharSet = CharSet.Unicode)]
Expand Down Expand Up @@ -72,7 +75,10 @@ function Open-Pad {

# Status report: [1] last rumble write failed, [2..5] last error NTSTATUS
# (little endian), [6] length of the last raw Stadia input report, [7..22]
# that report, [23..26] rumble writes that reached the controller.
# that report, [23..26] rumble writes that reached the controller, [27..30]
# USBD status of the last USB reader failure, [31..34] reader failures,
# [35..38] pipe resets, [39..42] device restarts, [43..46] input reports
# received (all little endian).
function Read-Status($handle) {
$report = New-Object byte[] $statusReportLength
$report[0] = $statusReportId
Expand All @@ -81,21 +87,42 @@ function Read-Status($handle) {
}
$raw = if ($report[6] -gt 0) { $report[7..(6 + $report[6])] } else { @() }
[pscustomobject]@{
RumbleFailed = $report[1] -ne 0
Error = [BitConverter]::ToUInt32($report, 2)
RawReport = ($raw | ForEach-Object { $_.ToString('X2') }) -join ' '
RumbleWrites = [BitConverter]::ToUInt32($report, 23)
RumbleFailed = $report[1] -ne 0
Error = [BitConverter]::ToUInt32($report, 2)
RawReport = ($raw | ForEach-Object { $_.ToString('X2') }) -join ' '
RumbleWrites = [BitConverter]::ToUInt32($report, 23)
UsbdStatus = [BitConverter]::ToUInt32($report, 27)
ReaderFailures = [BitConverter]::ToUInt32($report, 31)
PipeResets = [BitConverter]::ToUInt32($report, 35)
DeviceRestarts = [BitConverter]::ToUInt32($report, 39)
InputReports = [BitConverter]::ToUInt32($report, 43)
}
}

$pad = Open-Pad
try {
if ($TestRecovery) {
$command = New-Object byte[] $statusReportLength
$command[0] = $statusReportId
$command[1] = 1
if (-not [WinStadiaHid]::HidD_SetFeature($pad, $command, $command.Length)) {
throw "starting the recovery failed, error $([Runtime.InteropServices.Marshal]::GetLastWin32Error())"
}
'Recovery started.'
Start-Sleep -Milliseconds 500
}

$status = Read-Status $pad
$text = if ($status.RawReport) { 'running, receiving input' } else { 'running, no input received yet' }
if ($status.RumbleFailed) { $text += ', last rumble write failed' }
if ($status.Error) { $text += ', last error 0x{0:X8}' -f $status.Error }
"Driver: $text"
"Rumble writes: $($status.RumbleWrites)"
"Input reports: $($status.InputReports)"
if ($status.ReaderFailures) {
"USB reader failures: $($status.ReaderFailures), last USBD status 0x{0:X8}" -f $status.UsbdStatus
"Recovered by pipe resets: $($status.PipeResets), device restarts: $($status.DeviceRestarts)"
}

if ($Watch) {
'Raw input reports, press Ctrl+C to stop.'
Expand Down
114 changes: 109 additions & 5 deletions driver/usb.c
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
#include "winstadia.h"

#define WRITE_TIMEOUT_MS 500
// A reader failure this soon after a pipe reset means the reset did not
// help; the device is restarted then.
#define RECOVERY_RETRY_MS 5000

// HID class request and report type, for output reports sent through the
// control endpoint.
Expand All @@ -13,6 +16,7 @@

EVT_WDF_USB_READER_COMPLETION_ROUTINE EvtUsbInputReport;
EVT_WDF_USB_READERS_FAILED EvtUsbReadersFailed;
EVT_WDF_WORKITEM EvtUsbRecovery;

VOID
EvtUsbInputReport(WDFUSBPIPE Pipe, WDFMEMORY Buffer, size_t NumBytesTransferred, WDFCONTEXT Context)
Expand All @@ -22,14 +26,87 @@ EvtUsbInputReport(WDFUSBPIPE Pipe, WDFMEMORY Buffer, size_t NumBytesTransferred,
StadiaInputReport(Context, WdfMemoryGetBuffer(Buffer, NULL), NumBytesTransferred);
}

static VOID
UsbReaderFailed(PDEVICE_CONTEXT Context, NTSTATUS Status, USBD_STATUS UsbdStatus)
{
AcquireSRWLockExclusive(&Context->Lock);
Context->LastError = Status;
Context->LastUsbdStatus = UsbdStatus;
Context->ReaderFailures++;
ReleaseSRWLockExclusive(&Context->Lock);

// No input arrives from here on, so games must not keep seeing the
// buttons the controller last reported as held.
PadReleaseControls(Context);

// Returning TRUE asks the framework to reset the pipe and restart the
// reader, but in UMDF it never does: it first checks that the port is
// connected, and FxUsbDevice::IsConnected always fails in user mode. The
// reader then stayed down until the controller was replugged. The work
// item recovers instead.
WdfWorkItemEnqueue(Context->RecoveryWorkItem);
}

BOOLEAN
EvtUsbReadersFailed(WDFUSBPIPE Pipe, NTSTATUS Status, USBD_STATUS UsbdStatus)
{
UNREFERENCED_PARAMETER(UsbdStatus);
UsbReaderFailed(GetDeviceContext(WdfIoTargetGetDevice(WdfUsbTargetPipeGetIoTarget(Pipe))), Status, UsbdStatus);
return FALSE;
}

static VOID
CountRecovery(PDEVICE_CONTEXT Context, ULONG *Counter, NTSTATUS Status)
{
AcquireSRWLockExclusive(&Context->Lock);
(*Counter)++;
if (!NT_SUCCESS(Status)) {
Context->LastError = Status;
}
ReleaseSRWLockExclusive(&Context->Lock);
}

// Resets the input pipe and restarts the reader. When that fails, or the
// reader fails again soon after, it gives up on the device: asking for a
// restart removes it, and on USB it stays away until it is replugged, but
// with its controls released rather than stuck. A port reset, the step in
// between that the USB documentation recommends, left the controller's
// output pipe hanging on the first rumble write after it.
VOID
EvtUsbRecovery(WDFWORKITEM WorkItem)
{
WDFDEVICE device = WdfWorkItemGetParentObject(WorkItem);
PDEVICE_CONTEXT context = GetDeviceContext(device);
WDFIOTARGET input = WdfUsbTargetPipeGetIoTarget(context->InputPipe);
ULONGLONG now = GetTickCount64();
NTSTATUS status = STATUS_UNSUCCESSFUL;
BOOLEAN running;
BOOLEAN retry;

AcquireSRWLockShared(&context->Lock);
running = context->UsbRunning;
ReleaseSRWLockShared(&context->Lock);
if (!running) {
return;
}

StadiaRecordError(GetDeviceContext(WdfIoTargetGetDevice(WdfUsbTargetPipeGetIoTarget(Pipe))), Status);
// Have the framework reset the pipe and restart the reader.
return TRUE;
retry = context->LastRecoveryTick != 0 && now - context->LastRecoveryTick < RECOVERY_RETRY_MS;
context->LastRecoveryTick = now;
if (!retry) {
// The reset goes through while the target is stopped; stopping it
// first is what lets Start send the readers again.
WdfIoTargetStop(input, WdfIoTargetCancelSentIo);
status = WdfUsbTargetPipeResetSynchronously(context->InputPipe, NULL, NULL);
if (NT_SUCCESS(status)) {
status = WdfIoTargetStart(input);
}
CountRecovery(context, &context->PipeResets, status);
if (NT_SUCCESS(status)) {
return;
}
}

CountRecovery(context, &context->DeviceRestarts, STATUS_SUCCESS);
WdfDeviceSetFailed(device, WdfDeviceFailedAttemptRestart);
}

static NTSTATUS
Expand Down Expand Up @@ -61,6 +138,8 @@ UsbPrepareHardware(WDFDEVICE Device)
WDF_USB_DEVICE_SELECT_CONFIG_PARAMS selectParams;
WDF_USB_CONTINUOUS_READER_CONFIG readerConfig;
WDF_USB_PIPE_INFORMATION pipeInfo;
WDF_WORKITEM_CONFIG workItemConfig;
WDF_OBJECT_ATTRIBUTES attributes;
WDFUSBINTERFACE usbInterface;
ULONG inputPacketSize = 0;
NTSTATUS status;
Expand Down Expand Up @@ -103,6 +182,15 @@ UsbPrepareHardware(WDFDEVICE Device)
return STATUS_DEVICE_CONFIGURATION_ERROR;
}

WDF_WORKITEM_CONFIG_INIT(&workItemConfig, EvtUsbRecovery);
workItemConfig.AutomaticSerialization = FALSE;
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
attributes.ParentObject = Device;
status = WdfWorkItemCreate(&workItemConfig, &attributes, &context->RecoveryWorkItem);
if (!NT_SUCCESS(status)) {
return status;
}

WDF_USB_CONTINUOUS_READER_CONFIG_INIT(&readerConfig, EvtUsbInputReport, context, inputPacketSize);
readerConfig.EvtUsbTargetPipeReadersFailed = EvtUsbReadersFailed;
return WdfUsbTargetPipeConfigContinuousReader(context->InputPipe, &readerConfig);
Expand All @@ -111,13 +199,29 @@ UsbPrepareHardware(WDFDEVICE Device)
static NTSTATUS
UsbStart(PDEVICE_CONTEXT Context)
{
AcquireSRWLockExclusive(&Context->Lock);
Context->UsbRunning = TRUE;
ReleaseSRWLockExclusive(&Context->Lock);
return WdfIoTargetStart(WdfUsbTargetPipeGetIoTarget(Context->InputPipe));
}

static VOID
UsbStop(PDEVICE_CONTEXT Context)
{
// A recovery still running would start the reader again.
AcquireSRWLockExclusive(&Context->Lock);
Context->UsbRunning = FALSE;
ReleaseSRWLockExclusive(&Context->Lock);
WdfWorkItemFlush(Context->RecoveryWorkItem);
WdfIoTargetStop(WdfUsbTargetPipeGetIoTarget(Context->InputPipe), WdfIoTargetCancelSentIo);
}

const TRANSPORT UsbTransport = {UsbPrepareHardware, UsbStart, UsbStop, UsbSendOutputReport};
// For status.ps1 -TestRecovery: goes through a reader failure without one.
static NTSTATUS
UsbTestRecovery(PDEVICE_CONTEXT Context)
{
UsbReaderFailed(Context, STATUS_UNSUCCESSFUL, 0);
return STATUS_SUCCESS;
}

const TRANSPORT UsbTransport = {UsbPrepareHardware, UsbStart, UsbStop, UsbSendOutputReport, UsbTestRecovery};
49 changes: 48 additions & 1 deletion driver/winstadia.c
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@
#define MAX_INPUT_REPORT_LEN GAMEPAD_REPORT_LEN
#define STATUS_REPORT_LEN 64
#define STATUS_RUMBLE_WRITES_INDEX (7 + RAW_REPORT_MAX)
#define STATUS_USBD_STATUS_INDEX (STATUS_RUMBLE_WRITES_INDEX + 4)
#define STATUS_READER_FAILURES_INDEX (STATUS_USBD_STATUS_INDEX + 4)
#define STATUS_PIPE_RESETS_INDEX (STATUS_READER_FAILURES_INDEX + 4)
#define STATUS_DEVICE_RESTARTS_INDEX (STATUS_PIPE_RESETS_INDEX + 4)
#define STATUS_INPUT_REPORTS_INDEX (STATUS_DEVICE_RESTARTS_INDEX + 4)
#define STATUS_COMMAND_TEST_RECOVERY 0x01

// Rumble output report: [1] motor enable mask, [2] left trigger, [3] right
// trigger, [4] strong, [5] weak, each 0..100, [6..9] timing, which the Stadia
Expand Down Expand Up @@ -313,6 +319,12 @@ PadPublishControls(PDEVICE_CONTEXT Context, const UCHAR *Controls)
ReleaseSRWLockExclusive(&Context->Lock);
}

VOID
PadReleaseControls(PDEVICE_CONTEXT Context)
{
PadPublishControls(Context, IdleControls);
}

static NTSTATUS
ReadReport(PDEVICE_CONTEXT Context, WDFREQUEST Request, BOOLEAN *Complete)
{
Expand Down Expand Up @@ -391,17 +403,49 @@ GetFeature(PDEVICE_CONTEXT Context, WDFREQUEST Request)

// [1] rumble failed, [2..5] last error NTSTATUS (LE), [6] length of the
// last raw Stadia input report, [7..22] that report, [23..26] rumble
// writes that reached the controller (LE)
// writes that reached the controller, [27..30] USBD status of the last
// reader failure, [31..34] reader failures, [35..38] pipe resets,
// [39..42] device restarts asked for, [43..46] input reports received
// (all LE)
AcquireSRWLockShared(&Context->Lock);
report[1] = Context->RumbleFailed;
RtlCopyMemory(report + 2, &Context->LastError, sizeof(NTSTATUS));
report[6] = Context->RawReportLength;
RtlCopyMemory(report + 7, Context->RawReport, Context->RawReportLength);
RtlCopyMemory(report + STATUS_RUMBLE_WRITES_INDEX, &Context->RumbleWrites, sizeof(ULONG));
RtlCopyMemory(report + STATUS_USBD_STATUS_INDEX, &Context->LastUsbdStatus, sizeof(USBD_STATUS));
RtlCopyMemory(report + STATUS_READER_FAILURES_INDEX, &Context->ReaderFailures, sizeof(ULONG));
RtlCopyMemory(report + STATUS_PIPE_RESETS_INDEX, &Context->PipeResets, sizeof(ULONG));
RtlCopyMemory(report + STATUS_DEVICE_RESTARTS_INDEX, &Context->DeviceRestarts, sizeof(ULONG));
RtlCopyMemory(report + STATUS_INPUT_REPORTS_INDEX, &Context->InputReports, sizeof(ULONG));
ReleaseSRWLockShared(&Context->Lock);
return CopyToRequest(Request, report, sizeof(report));
}

// Setting the status report runs a command, [1]: 1 = go through the recovery
// from a failed input reader, as status.ps1 -TestRecovery does.
static NTSTATUS
SetFeature(PDEVICE_CONTEXT Context, WDFREQUEST Request)
{
PUCHAR report;
size_t length;
NTSTATUS status = GetInputBuffer(Request, 2, &report, &length);
if (!NT_SUCCESS(status)) {
return status;
}
if (report[0] != REPORT_ID_STATUS || report[1] != STATUS_COMMAND_TEST_RECOVERY) {
return STATUS_INVALID_PARAMETER;
}
if (Context->Transport->TestRecovery == NULL) {
return STATUS_NOT_SUPPORTED;
}
status = Context->Transport->TestRecovery(Context);
if (NT_SUCCESS(status)) {
WdfRequestSetInformation(Request, length);
}
return status;
}

static NTSTATUS
GetString(WDFREQUEST Request)
{
Expand Down Expand Up @@ -466,6 +510,9 @@ EvtIoDeviceControl(
case IOCTL_UMDF_HID_GET_FEATURE:
status = GetFeature(context, Request);
break;
case IOCTL_UMDF_HID_SET_FEATURE:
status = SetFeature(context, Request);
break;
case IOCTL_UMDF_HID_GET_INPUT_REPORT:
status = GetInputReport(context, Request);
break;
Expand Down
17 changes: 17 additions & 0 deletions driver/winstadia.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ typedef struct _TRANSPORT {
VOID (*Stop)(PDEVICE_CONTEXT Context);
// The report starts with its ID. May block; the caller holds RumbleLock.
NTSTATUS (*SendOutputReport)(PDEVICE_CONTEXT Context, PUCHAR Report, size_t Length);
// Runs the recovery from a failed input reader; NULL where there is none.
NTSTATUS (*TestRecovery)(PDEVICE_CONTEXT Context);
} TRANSPORT;

extern const TRANSPORT UsbTransport;
Expand Down Expand Up @@ -66,6 +68,13 @@ struct _DEVICE_CONTEXT {
BOOLEAN RumbleFailed;
NTSTATUS LastError;
ULONG RumbleWrites;
// Every input report from the transport, changed or not.
ULONG InputReports;
// USB input reader failures and what was done about them.
USBD_STATUS LastUsbdStatus;
ULONG ReaderFailures;
ULONG PipeResets;
ULONG DeviceRestarts;

// Motor speeds: those asked for and those the controller has, both
// guarded by the lock. The work item writes the difference, so that a
Expand All @@ -85,6 +94,11 @@ struct _DEVICE_CONTEXT {
// then go through the control endpoint.
WDFUSBPIPE OutputPipe;
UCHAR InterfaceNumber;
// Brings the input pipe back after the reader failed. Running is guarded
// by the lock, the tick of the last recovery belongs to the work item.
WDFWORKITEM RecoveryWorkItem;
BOOLEAN UsbRunning;
ULONGLONG LastRecoveryTick;

// Bluetooth transport.
WDFIOTARGET LowerDriver;
Expand All @@ -104,6 +118,9 @@ WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(DEVICE_CONTEXT, GetDeviceContext)

// Publishes new control values as input reports, if they changed.
VOID PadPublishControls(PDEVICE_CONTEXT Context, const UCHAR *Controls);
// Publishes all controls released and centered, for when input stops
// arriving, so that games do not keep the last buttons held.
VOID PadReleaseControls(PDEVICE_CONTEXT Context);

EVT_WDF_DEVICE_PREPARE_HARDWARE StadiaPrepareHardware;
EVT_WDF_DEVICE_D0_ENTRY StadiaD0Entry;
Expand Down