Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2711 lines
94 KiB

  1. /****************************** Module Header ******************************\
  2. * Module Name: pnp.c
  3. *
  4. * Copyright (c) 1985 - 1999, Microsoft Corporation
  5. *
  6. * This module tracks device interface changes so we can keep track of know how many mice and
  7. * keyboards and mouse
  8. * and mouse reports.
  9. *
  10. * History:
  11. * 97-10-16 IanJa Interpreted from a dream that Ken Ray had.
  12. \***************************************************************************/
  13. #include "precomp.h"
  14. #pragma hdrstop
  15. BOOL gbFirstConnectionDone;
  16. DEVICE_TEMPLATE aDeviceTemplate[DEVICE_TYPE_MAX + 1] = {
  17. // DEVICE_TYPE_MOUSE
  18. {
  19. sizeof(GENERIC_DEVICE_INFO)+sizeof(MOUSE_DEVICE_INFO), // cbDeviceInfo
  20. &GUID_CLASS_MOUSE, // pClassGUID
  21. PMAP_MOUCLASS_PARAMS, // uiRegistrySection
  22. L"mouclass", // pwszClassName
  23. DD_MOUSE_DEVICE_NAME_U L"0", // pwszDefDevName
  24. DD_MOUSE_DEVICE_NAME_U L"Legacy0", // pwszLegacyDevName
  25. IOCTL_MOUSE_QUERY_ATTRIBUTES, // IOCTL_Attr
  26. FIELD_OFFSET(DEVICEINFO, mouse.Attr), // offAttr
  27. sizeof((PDEVICEINFO)NULL)->mouse.Attr, // cbAttr
  28. FIELD_OFFSET(DEVICEINFO, mouse.Data), // offData
  29. sizeof((PDEVICEINFO)NULL)->mouse.Data, // cbData
  30. ProcessMouseInput, // Reader routine
  31. NULL // pkeHidChange
  32. },
  33. // DEVICE_TYPE_KEYBOARD
  34. {
  35. sizeof(GENERIC_DEVICE_INFO)+sizeof(KEYBOARD_DEVICE_INFO), // cbDeviceInfo
  36. &GUID_CLASS_KEYBOARD, // pClassGUID
  37. PMAP_KBDCLASS_PARAMS, // uiRegistrySection
  38. L"kbdclass", // pwszClassName
  39. DD_KEYBOARD_DEVICE_NAME_U L"0", // pwszDefDevName
  40. DD_KEYBOARD_DEVICE_NAME_U L"Legacy0", // pwszLegacyDevName
  41. IOCTL_KEYBOARD_QUERY_ATTRIBUTES, // IOCTL_Attr
  42. FIELD_OFFSET(DEVICEINFO, keyboard.Attr), // offAttr
  43. sizeof((PDEVICEINFO)NULL)->keyboard.Attr, // cbAttr
  44. FIELD_OFFSET(DEVICEINFO, keyboard.Data), // offData
  45. sizeof((PDEVICEINFO)NULL)->keyboard.Data, // cbData
  46. ProcessKeyboardInput, // Reader routine
  47. NULL // pkeHidChange
  48. },
  49. #ifdef GENERIC_INPUT
  50. // DEVICE_TYPE_HID
  51. {
  52. sizeof(GENERIC_DEVICE_INFO)+sizeof(HID_DEVICE_INFO), // cbDeviceInfo
  53. &GUID_CLASS_INPUT, // pClassGUID
  54. 0, // uiRegistrySection. LATER: add real one
  55. L"hid", // pwszClassName
  56. L"", // pwszDefDevName
  57. L"", // pwszLegacyDevName
  58. 0, // IOCTL_ATTR
  59. 0, // offAttr
  60. 0, // cbAttr
  61. 0, // offData
  62. 0, // cbData
  63. ProcessHidInput, // Reader routine
  64. NULL, // pkeHidChange,
  65. DT_HID, // dwFlags
  66. },
  67. #endif
  68. // Add new input device type template here
  69. };
  70. //
  71. // We need to remember device class notification entries since we need
  72. // them to unregister the device class notification when we disconnect
  73. // from the console.
  74. //
  75. PVOID aDeviceClassNotificationEntry[DEVICE_TYPE_MAX + 1];
  76. #ifdef DIAGNOSE_IO
  77. NTSTATUS gKbdIoctlLEDSStatus = -1; // last IOCTL_KEYBOARD_QUERY_INDICATORS
  78. #endif
  79. typedef struct _CDROM_NOTIFY {
  80. LIST_ENTRY Entry;
  81. ULONG Size;
  82. PVOID RegistrationHandle;
  83. ULONG Event;
  84. // Must be last field
  85. MOUNTMGR_DRIVE_LETTER_TARGET DeviceName;
  86. } CDROM_NOTIFY, *PCDROM_NOTIFY;
  87. PVOID gCDROMClassRegistrationEntry;
  88. LIST_ENTRY gCDROMNotifyList;
  89. LIST_ENTRY gMediaChangeList;
  90. PFAST_MUTEX gMediaChangeMutex;
  91. HANDLE gpEventMediaChange;
  92. #define EVENT_CDROM_MEDIA_ARRIVAL 1
  93. #define EVENT_CDROM_MEDIA_REMOVAL 2
  94. /***************************************************************************\
  95. * Win32kPnPDriverEntry
  96. *
  97. * This is the callback function when we call IoCreateDriver to create a
  98. * PnP Driver Object. In this function, we need to remember the DriverObject.
  99. *
  100. * Parameters:
  101. * DriverObject - Pointer to the driver object created by the system.
  102. * RegistryPath - is NULL.
  103. *
  104. * Return Value: STATUS_SUCCESS
  105. *
  106. * History:
  107. * 10-20-97 IanJa Taken from ntos\io\pnpinit.c
  108. \***************************************************************************/
  109. NTSTATUS Win32kPnPDriverEntry(
  110. IN PDRIVER_OBJECT DriverObject,
  111. IN PUNICODE_STRING pustrRegistryPath)
  112. {
  113. UNREFERENCED_PARAMETER(pustrRegistryPath);
  114. TAGMSG1(DBGTAG_PNP,
  115. "Win32kPnPDriverEntry(DriverObject 0x%p)",
  116. DriverObject);
  117. //
  118. // Squirrel away the pointer to our driver object.
  119. //
  120. gpWin32kDriverObject = DriverObject;
  121. return STATUS_SUCCESS;
  122. }
  123. /***************************************************************************\
  124. * Initialize the global event used in notifying CSR that media has changed.
  125. *
  126. * History:
  127. \***************************************************************************/
  128. NTSTATUS InitializeMediaChange(
  129. HANDLE hMediaRequestEvent)
  130. {
  131. NTSTATUS Status;
  132. if (!IsRemoteConnection()) {
  133. InitializeListHead(&gCDROMNotifyList);
  134. InitializeListHead(&gMediaChangeList);
  135. Status = ObReferenceObjectByHandle(hMediaRequestEvent,
  136. EVENT_ALL_ACCESS,
  137. *ExEventObjectType,
  138. KernelMode,
  139. &gpEventMediaChange,
  140. NULL);
  141. if (!NT_SUCCESS(Status)) {
  142. return Status;
  143. }
  144. gMediaChangeMutex = UserAllocPoolNonPagedNS(sizeof(FAST_MUTEX), TAG_PNP);
  145. if (gMediaChangeMutex) {
  146. ExInitializeFastMutex(gMediaChangeMutex);
  147. } else {
  148. Status = STATUS_NO_MEMORY;
  149. }
  150. } else {
  151. Status = STATUS_SUCCESS;
  152. }
  153. return Status;
  154. }
  155. VOID
  156. CleanupMediaChange(
  157. VOID)
  158. {
  159. if (gMediaChangeMutex) {
  160. UserFreePool(gMediaChangeMutex);
  161. gMediaChangeMutex = 0;
  162. }
  163. }
  164. __inline VOID EnterMediaCrit(
  165. VOID)
  166. {
  167. KeEnterCriticalRegion();
  168. ExAcquireFastMutexUnsafe(gMediaChangeMutex);
  169. }
  170. __inline VOID LeaveMediaCrit(
  171. VOID)
  172. {
  173. ExReleaseFastMutexUnsafe(gMediaChangeMutex);
  174. KeLeaveCriticalRegion();
  175. }
  176. /***************************************************************************\
  177. * Routines to support CDROM driver letters.
  178. *
  179. * Execution Context:
  180. *
  181. * History:
  182. \***************************************************************************/
  183. ULONG xxxGetDeviceChangeInfo(
  184. VOID)
  185. {
  186. UNICODE_STRING name;
  187. PFILE_OBJECT FileObject;
  188. PDEVICE_OBJECT DeviceObject;
  189. KEVENT event;
  190. PIRP irp;
  191. MOUNTMGR_DRIVE_LETTER_INFORMATION output;
  192. IO_STATUS_BLOCK ioStatus;
  193. NTSTATUS status;
  194. PCDROM_NOTIFY pContext;
  195. PTHREADINFO ptiCurrent;
  196. TL tlContext;
  197. TL tlFileObject;
  198. ULONG retval = 0;
  199. if (!(ISCSRSS())) {
  200. return 0;
  201. }
  202. EnterMediaCrit();
  203. if (!IsListEmpty(&gMediaChangeList)) {
  204. pContext = (PCDROM_NOTIFY)RemoveTailList(&gMediaChangeList);
  205. } else {
  206. pContext = NULL;
  207. }
  208. LeaveMediaCrit();
  209. if (pContext == NULL) {
  210. return 0;
  211. }
  212. ptiCurrent = PtiCurrent();
  213. ThreadLockPool(ptiCurrent, pContext, &tlContext);
  214. RtlInitUnicodeString(&name, MOUNTMGR_DEVICE_NAME);
  215. status = IoGetDeviceObjectPointer(&name,
  216. FILE_READ_ATTRIBUTES,
  217. &FileObject,
  218. &DeviceObject);
  219. if (NT_SUCCESS(status)) {
  220. PushW32ThreadLock(FileObject, &tlFileObject, UserDereferenceObject);
  221. KeInitializeEvent(&event, NotificationEvent, FALSE);
  222. irp = IoBuildDeviceIoControlRequest(IOCTL_MOUNTMGR_NEXT_DRIVE_LETTER,
  223. DeviceObject,
  224. &pContext->DeviceName,
  225. sizeof(MOUNTMGR_DRIVE_LETTER_TARGET) +
  226. pContext->DeviceName.DeviceNameLength,
  227. &output,
  228. sizeof(output),
  229. FALSE,
  230. &event,
  231. &ioStatus);
  232. if (irp) {
  233. /*
  234. * This IoCallDriver may block nearly for good --- the device
  235. * may be in the D3 state and IoCallDriver could take way
  236. * too long, waiting for its powering up.
  237. * They may not even return STATUS_PENDING. We'd better
  238. * leave the critsec here.
  239. */
  240. LeaveCrit();
  241. status = IoCallDriver(DeviceObject, irp);
  242. if (status == STATUS_PENDING) {
  243. KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
  244. status = ioStatus.Status;
  245. }
  246. EnterCrit();
  247. if ((status == STATUS_SUCCESS) && (output.CurrentDriveLetter)) {
  248. UserAssert((output.CurrentDriveLetter - 'A') < 30);
  249. retval = 1 << (output.CurrentDriveLetter - 'A');
  250. if (pContext->Event & EVENT_CDROM_MEDIA_ARRIVAL) {
  251. retval |= HMCE_ARRIVAL;
  252. }
  253. }
  254. }
  255. PopAndFreeW32ThreadLock(&tlFileObject);
  256. }
  257. //
  258. // Allways free the request
  259. //
  260. ThreadUnlockAndFreePool(ptiCurrent, &tlContext);
  261. return retval;
  262. }
  263. /***************************************************************************\
  264. * Handle device notifications such as MediaChanged
  265. *
  266. * Execution Context:
  267. *
  268. * History:
  269. \***************************************************************************/
  270. NTSTATUS DeviceCDROMNotify(
  271. IN PTARGET_DEVICE_CUSTOM_NOTIFICATION Notification,
  272. IN PCDROM_NOTIFY pContext)
  273. {
  274. PCDROM_NOTIFY pNew;
  275. CheckCritOut();
  276. if (IsRemoteConnection()) {
  277. return STATUS_SUCCESS;
  278. }
  279. UserAssert(pContext);
  280. if (IsEqualGUID(&Notification->Event, &GUID_IO_MEDIA_ARRIVAL)) {
  281. pContext->Event = EVENT_CDROM_MEDIA_ARRIVAL;
  282. } else if (IsEqualGUID(&Notification->Event, &GUID_IO_MEDIA_REMOVAL)) {
  283. pContext->Event = EVENT_CDROM_MEDIA_REMOVAL;
  284. } else if (IsEqualGUID(&Notification->Event, &GUID_TARGET_DEVICE_REMOVE_COMPLETE)) {
  285. EnterMediaCrit();
  286. if (!gCDROMClassRegistrationEntry) {
  287. // This is being cleaned up by xxxUnregisterDeviceNotifications
  288. LeaveMediaCrit();
  289. return STATUS_SUCCESS;
  290. }
  291. RemoveEntryList(&pContext->Entry);
  292. LeaveMediaCrit();
  293. IoUnregisterPlugPlayNotification(pContext->RegistrationHandle);
  294. UserFreePool(pContext);
  295. return STATUS_SUCCESS;
  296. }
  297. #ifdef AUTORUN_CURSOR
  298. else if (IsEqualGUID(&Notification->Event, &GUID_IO_DEVICE_BECOMING_READY)) {
  299. PDEVICE_EVENT_BECOMING_READY pdebr = (DEVICE_EVENT_BECOMING_READY*)Notification->CustomDataBuffer;
  300. ShowAutorunCursor(pdebr->Estimated100msToReady * 10);
  301. return STATUS_SUCCESS;
  302. }
  303. #endif
  304. else {
  305. return STATUS_SUCCESS;
  306. }
  307. //
  308. // Process the arrival or removal.
  309. //
  310. // We must queue this otherwise we end up bugchecking on Terminal Server
  311. // This is due to opening a handle from within the system process which
  312. // requires us to do an attach process.
  313. //
  314. pNew = UserAllocPoolNonPaged(pContext->Size, TAG_PNP);
  315. if (pNew) {
  316. RtlCopyMemory(pNew, pContext, pContext->Size);
  317. EnterMediaCrit();
  318. InsertHeadList(&gMediaChangeList, &pNew->Entry);
  319. LeaveMediaCrit();
  320. KeSetEvent(gpEventMediaChange, EVENT_INCREMENT, FALSE);
  321. }
  322. return STATUS_SUCCESS;
  323. }
  324. /***************************************************************************\
  325. * DeviceClassCDROMNotify
  326. *
  327. * This gets called when CDROM appears or disappears
  328. *
  329. \***************************************************************************/
  330. NTSTATUS
  331. DeviceClassCDROMNotify (
  332. IN PDEVICE_INTERFACE_CHANGE_NOTIFICATION classChange,
  333. IN PVOID Unused
  334. )
  335. {
  336. NTSTATUS Status = STATUS_SUCCESS;
  337. PFILE_OBJECT FileObject;
  338. PDEVICE_OBJECT DeviceObject;
  339. PCDROM_NOTIFY pContext;
  340. ULONG Size;
  341. UNREFERENCED_PARAMETER(Unused);
  342. CheckCritOut();
  343. /*
  344. * Sanity check the DeviceType, and that it matches the InterfaceClassGuid
  345. */
  346. UserAssert(IsEqualGUID(&classChange->InterfaceClassGuid, &CdRomClassGuid));
  347. if (IsEqualGUID(&classChange->Event, &GUID_DEVICE_INTERFACE_ARRIVAL)) {
  348. Status = IoGetDeviceObjectPointer(classChange->SymbolicLinkName,
  349. FILE_READ_ATTRIBUTES,
  350. &FileObject,
  351. &DeviceObject);
  352. if (NT_SUCCESS(Status)) {
  353. Size = sizeof(CDROM_NOTIFY) + classChange->SymbolicLinkName->Length;
  354. pContext = (PCDROM_NOTIFY) UserAllocPool(Size, TAG_PNP);
  355. //
  356. // Register For MediaChangeNotifications on all the CDROMs.
  357. //
  358. if (pContext) {
  359. pContext->Size = Size;
  360. pContext->DeviceName.DeviceNameLength = classChange->SymbolicLinkName->Length;
  361. RtlCopyMemory(pContext->DeviceName.DeviceName,
  362. classChange->SymbolicLinkName->Buffer,
  363. pContext->DeviceName.DeviceNameLength);
  364. if (NT_SUCCESS(IoRegisterPlugPlayNotification (
  365. EventCategoryTargetDeviceChange,
  366. 0,
  367. FileObject,
  368. gpWin32kDriverObject,
  369. DeviceCDROMNotify,
  370. pContext,
  371. &(pContext->RegistrationHandle)))) {
  372. EnterMediaCrit();
  373. InsertHeadList(&gCDROMNotifyList, &pContext->Entry);
  374. LeaveMediaCrit();
  375. } else {
  376. RIPMSG2(RIP_WARNING,
  377. "Failed to register CDROM Device Notification '%.*ws'.",
  378. pContext->DeviceName.DeviceNameLength,
  379. pContext->DeviceName.DeviceName);
  380. UserFreePool(pContext);
  381. }
  382. } else {
  383. RIPMSG2(RIP_WARNING,
  384. "Failed to allocate pool block for CDROM '%.*ws'.",
  385. pContext->DeviceName.DeviceNameLength,
  386. pContext->DeviceName.DeviceName);
  387. }
  388. ObDereferenceObject(FileObject);
  389. }
  390. } else if (IsEqualGUID(&classChange->Event, &GUID_DEVICE_INTERFACE_REMOVAL)) {
  391. //
  392. // Do nothing - we already remove the registration.
  393. //
  394. } else {
  395. RIPMSG0(RIP_ERROR, "Unrecognized Event GUID");
  396. }
  397. return STATUS_SUCCESS;
  398. }
  399. #ifdef TRACK_PNP_NOTIFICATION
  400. PPNP_NOTIFICATION_RECORD gpPnpNotificationRecord;
  401. DWORD gdwPnpNotificationRecSize = 256;
  402. UINT giPnpSeq;
  403. BOOL gfRecordPnpNotification = TRUE;
  404. VOID CleanupPnpNotificationRecord(
  405. VOID)
  406. {
  407. CheckDeviceInfoListCritIn();
  408. gfRecordPnpNotification = FALSE;
  409. if (gpPnpNotificationRecord) {
  410. UserFreePool(gpPnpNotificationRecord);
  411. gpPnpNotificationRecord = NULL;
  412. }
  413. }
  414. VOID RecordPnpNotification(
  415. PNP_NOTIFICATION_TYPE type,
  416. PDEVICEINFO pDeviceInfo,
  417. ULONG_PTR NotificationCode)
  418. {
  419. UINT iIndex;
  420. UINT i = 0;
  421. PUNICODE_STRING pName = NULL;
  422. HANDLE hDeviceInfo = NULL;
  423. CheckDeviceInfoListCritIn();
  424. UserAssert(gfRecordPnpNotification);
  425. if (gpPnpNotificationRecord == NULL) {
  426. gpPnpNotificationRecord = UserAllocPoolZInit(sizeof *gpPnpNotificationRecord * gdwPnpNotificationRecSize, TAG_PNP);
  427. }
  428. if (gpPnpNotificationRecord == NULL) {
  429. return;
  430. }
  431. iIndex = giPnpSeq % gdwPnpNotificationRecSize;
  432. gpPnpNotificationRecord[iIndex].pKThread = PsGetCurrentThread();
  433. gpPnpNotificationRecord[iIndex].iSeq = ++giPnpSeq; // the first record is numbered as 1.
  434. gpPnpNotificationRecord[iIndex].type = type;
  435. /*
  436. * If there is a pathname, copy it here.
  437. */
  438. switch (type) {
  439. case PNP_NTF_CLASSNOTIFY:
  440. /*
  441. * pDeviceInfo is actually a pUnicodeString.
  442. */
  443. pName = (PUNICODE_STRING)pDeviceInfo;
  444. pDeviceInfo = NULL;
  445. break;
  446. case PNP_NTF_DEVICENOTIFY_UNLISTED:
  447. /*
  448. * pDeviceInfo is invalid, cannot be looked up.
  449. */
  450. UserAssert(pName == NULL);
  451. break;
  452. default:
  453. if (pDeviceInfo) {
  454. pName = &pDeviceInfo->ustrName;
  455. hDeviceInfo = PtoHq(pDeviceInfo);
  456. }
  457. break;
  458. }
  459. UserAssert(i == 0);
  460. if (pName) {
  461. for ( ; i < ARRAY_SIZE(gpPnpNotificationRecord[iIndex].szPathName) - 1 && i < (UINT)pName->Length / sizeof(WCHAR); ++i) {
  462. gpPnpNotificationRecord[iIndex].szPathName[i] = (UCHAR)pName->Buffer[i];
  463. }
  464. }
  465. gpPnpNotificationRecord[iIndex].szPathName[i] = 0;
  466. /*
  467. * Store the rest of information
  468. */
  469. gpPnpNotificationRecord[iIndex].pDeviceInfo = pDeviceInfo;
  470. gpPnpNotificationRecord[iIndex].hDeviceInfo = hDeviceInfo;
  471. gpPnpNotificationRecord[iIndex].NotificationCode = NotificationCode;
  472. /*
  473. * Store the stack trace.
  474. */
  475. RtlWalkFrameChain(gpPnpNotificationRecord[iIndex].trace,
  476. ARRAY_SIZE(gpPnpNotificationRecord[iIndex].trace),
  477. 0);
  478. }
  479. #endif // TRACK_PNP_NOTIFICATION
  480. /***************************************************************************\
  481. * CreateDeviceInfo
  482. *
  483. * This creates an instance of an input device for USER. To do this it:
  484. * - Allocates a DEVICEINFO struct
  485. * - Adds it to USER's list of input devices
  486. * - Initializes some of the fields
  487. * - Signals the input servicing thread to open and read the new device.
  488. *
  489. * Type - the device type (DEVICE_TYPE_MOUSE, DEVICE_TYPE_KEYBOARD)
  490. * Name - the device name.
  491. * When trying to open a HYDRA client's mouse, Name is NULL.
  492. * bFlags - some initial flags to set (eg: GDIF_NOTPNP)
  493. *
  494. * THIS FUNCTION IS CALLED IN THE CONTEXT OF THE KERNEL PROCESS
  495. * so we mustn't open the mouse here, else the handle we get will not belong
  496. * to the Win32k process.
  497. *
  498. * History:
  499. * 11-26-90 DavidPe Created.
  500. * 01-07-98 IanJa Plug & Play
  501. \***************************************************************************/
  502. PDEVICEINFO CreateDeviceInfo(DWORD DeviceType, PUNICODE_STRING pustrName, BYTE bFlags)
  503. {
  504. PDEVICEINFO pDeviceInfo = NULL;
  505. CheckCritIn();
  506. BEGINATOMICCHECK();
  507. UserAssert(pustrName != NULL);
  508. TAGMSGF4(DBGTAG_PNP, "CreateDeviceInfo(%d, %.*ws, %x)", DeviceType, pustrName->Length / sizeof(WCHAR), pustrName->Buffer, bFlags);
  509. if (DeviceType > DEVICE_TYPE_MAX) {
  510. RIPMSGF1(RIP_ERROR, "Unknown DeviceType %lx", DeviceType);
  511. }
  512. #if defined(PRERELEASE) && defined(CHECK_DEVICE_DUPLICATE)
  513. {
  514. PDEVICEINFO pdi;
  515. CheckCritIn();
  516. EnterDeviceInfoListCrit();
  517. for (pdi = gpDeviceInfoList; pdi; pdi = pdi->pNext) {
  518. if (wcsncmp(pustrName->Buffer, pdi->ustrName.Buffer, pdi->ustrName.Length / sizeof(WCHAR)) == 0) {
  519. TAGMSGF1(DBGTAG_PNP, "the new device is already in the list! %p", pdi);
  520. break;
  521. }
  522. }
  523. LeaveDeviceInfoListCrit();
  524. }
  525. #endif
  526. #ifdef GENERIC_INPUT
  527. pDeviceInfo = (PDEVICEINFO)HMAllocObject(NULL, NULL, (BYTE)TYPE_DEVICEINFO, (DWORD)aDeviceTemplate[DeviceType].cbDeviceInfo);
  528. #else
  529. pDeviceInfo = UserAllocPoolZInit(aDeviceTemplate[DeviceType].cbDeviceInfo, TAG_PNP);
  530. #endif
  531. if (pDeviceInfo == NULL) {
  532. RIPMSGF0(RIP_WARNING, "out of memory allocating DEVICEINFO");
  533. EXITATOMICCHECK();
  534. return NULL;
  535. }
  536. if (pustrName->Buffer != NULL) {
  537. pDeviceInfo->ustrName.Buffer = UserAllocPool(pustrName->Length, TAG_PNP);
  538. if (pDeviceInfo->ustrName.Buffer == NULL) {
  539. RIPMSGF2(RIP_WARNING, "Can't duplicate string %.*ws",
  540. pustrName->Length / sizeof(WCHAR),
  541. pustrName->Buffer);
  542. goto CreateFailed;
  543. }
  544. pDeviceInfo->ustrName.MaximumLength = pustrName->Length;
  545. RtlCopyUnicodeString(&pDeviceInfo->ustrName, pustrName);
  546. }
  547. pDeviceInfo->type = (BYTE)DeviceType;
  548. pDeviceInfo->bFlags |= bFlags;
  549. /*
  550. * Create this device's HidChangeCompletion event. When the RIT completes
  551. * a synchronous ProcessDeviceChanges() it signals the HidChangeCompletion
  552. * event to wake the requesting RequestDeviceChange() which is blocking on
  553. * the event.
  554. * Each device has it's own HidChangeCompletion event,
  555. * since multiple PnP notification may arrive for several different
  556. * devices simultaneously. (see #331320 IanJa)
  557. */
  558. pDeviceInfo->pkeHidChangeCompleted = CreateKernelEvent(SynchronizationEvent, FALSE);
  559. if (pDeviceInfo->pkeHidChangeCompleted == NULL) {
  560. RIPMSGF0(RIP_WARNING,
  561. "failed to create pkeHidChangeCompleted");
  562. goto CreateFailed;
  563. }
  564. EnterDeviceInfoListCrit();
  565. #ifdef TRACK_PNP_NOTIFICATION
  566. /*
  567. * Placing tracking code here may miss the failure cases above,
  568. * but they're pretty exceptional cases that can be safely ignored.
  569. */
  570. if (gfRecordPnpNotification) {
  571. RecordPnpNotification(PNP_NTF_CREATEDEVICEINFO, pDeviceInfo, DeviceType);
  572. }
  573. #endif
  574. #ifdef GENERIC_INPUT
  575. if (aDeviceTemplate[DeviceType].dwFlags & DT_HID) {
  576. /*
  577. * Create HID specific information.
  578. */
  579. pDeviceInfo->hid.pHidDesc = HidCreateDeviceInfo(pDeviceInfo);
  580. if (pDeviceInfo->hid.pHidDesc == NULL) {
  581. /*
  582. * Something wrong happened and we failed to
  583. * create the device information.
  584. * Or the device is not our target.
  585. * Should bail out anyway.
  586. */
  587. TAGMSGF0(DBGTAG_PNP, "HidCreateDeviceInfo bailed out.");
  588. LeaveDeviceInfoListCrit();
  589. goto CreateFailed;
  590. }
  591. }
  592. #endif
  593. /*
  594. * Link it in
  595. */
  596. pDeviceInfo->pNext = gpDeviceInfoList;
  597. gpDeviceInfoList = pDeviceInfo;
  598. /*
  599. * Tell the RIT there is a new device so that it can open it and start
  600. * reading from it. This is non-blocking (no GDIAF_PNPWAITING bit set)
  601. */
  602. RequestDeviceChange(pDeviceInfo, GDIAF_ARRIVED, TRUE);
  603. LeaveDeviceInfoListCrit();
  604. EXITATOMICCHECK();
  605. return pDeviceInfo;
  606. CreateFailed:
  607. if (pDeviceInfo) {
  608. if (pDeviceInfo->ustrName.Buffer) {
  609. UserFreePool(pDeviceInfo->ustrName.Buffer);
  610. }
  611. #ifdef GENERIC_INPUT
  612. if (pDeviceInfo->hid.pHidDesc) {
  613. FreeHidDesc(pDeviceInfo->hid.pHidDesc);
  614. #if DBG
  615. pDeviceInfo->hid.pHidDesc = NULL;
  616. #endif
  617. }
  618. if (pDeviceInfo->pkeHidChangeCompleted) {
  619. FreeKernelEvent(&pDeviceInfo->pkeHidChangeCompleted);
  620. }
  621. HMFreeObject(pDeviceInfo);
  622. #else
  623. UserFreePool(pDeviceInfo);
  624. #endif
  625. }
  626. ENDATOMICCHECK();
  627. return NULL;
  628. }
  629. /***************************************************************************\
  630. * DeviceClassNotify
  631. *
  632. * This gets called when an input device is attached or detached.
  633. * If this happens during initialization (for mice already connected) we
  634. * come here by in the context of the RIT. If hot-(un)plugging a mouse,
  635. * then we are called on a thread from the Kernel process.
  636. *
  637. * History:
  638. * 10-20-97 IanJa Taken from some old code of KenRay's
  639. \***************************************************************************/
  640. NTSTATUS
  641. DeviceClassNotify (
  642. IN PDEVICE_INTERFACE_CHANGE_NOTIFICATION classChange,
  643. IN PVOID DeviceType // (context)
  644. )
  645. {
  646. DWORD dwDeviceType;
  647. CheckCritOut();
  648. dwDeviceType = PtrToUlong( DeviceType );
  649. TAGMSG2(DBGTAG_PNP, "enter DeviceClassNotify(%lx, %lx)", classChange, dwDeviceType);
  650. /*
  651. * Sanity check the DeviceType, and that it matches the InterfaceClassGuid
  652. */
  653. UserAssert(dwDeviceType <= DEVICE_TYPE_MAX);
  654. UserAssert(IsEqualGUID(&classChange->InterfaceClassGuid, aDeviceTemplate[dwDeviceType].pClassGUID));
  655. if (IsRemoteConnection()) {
  656. return STATUS_SUCCESS;
  657. }
  658. TAGMSG3(DBGTAG_PNP | RIP_THERESMORE, " Event GUID %lx, %x, %x",
  659. classChange->Event.Data1,
  660. classChange->Event.Data2,
  661. classChange->Event.Data3);
  662. TAGMSG8(DBGTAG_PNP | RIP_THERESMORE, " %2x%2x%2x%2x%2x%2x%2x%2x",
  663. classChange->Event.Data4[0], classChange->Event.Data4[1],
  664. classChange->Event.Data4[2], classChange->Event.Data4[3],
  665. classChange->Event.Data4[4], classChange->Event.Data4[5],
  666. classChange->Event.Data4[6], classChange->Event.Data4[7]);
  667. TAGMSG4(DBGTAG_PNP | RIP_THERESMORE, " InterfaceClassGuid %lx, %lx, %lx, %lx",
  668. ((DWORD *)&(classChange->InterfaceClassGuid))[0],
  669. ((DWORD *)&(classChange->InterfaceClassGuid))[1],
  670. ((DWORD *)&(classChange->InterfaceClassGuid))[2],
  671. ((DWORD *)&(classChange->InterfaceClassGuid))[3]);
  672. TAGMSG1(DBGTAG_PNP | RIP_THERESMORE, " SymbolicLinkName %ws", classChange->SymbolicLinkName->Buffer);
  673. if (IsEqualGUID(&classChange->Event, &GUID_DEVICE_INTERFACE_ARRIVAL)) {
  674. // A new hid device class association has arrived
  675. EnterCrit();
  676. TRACE_INIT(("DeviceClassNotify - SymbolicLinkName : %ws \n", classChange->SymbolicLinkName->Buffer));
  677. #ifdef TRACK_PNP_NOTIFICATION
  678. if (gfRecordPnpNotification) {
  679. CheckDeviceInfoListCritOut();
  680. EnterDeviceInfoListCrit();
  681. RecordPnpNotification(PNP_NTF_CLASSNOTIFY, (PVOID)classChange->SymbolicLinkName, (ULONG_PTR)DeviceType);
  682. LeaveDeviceInfoListCrit();
  683. }
  684. #endif
  685. CreateDeviceInfo(dwDeviceType, classChange->SymbolicLinkName, 0);
  686. LeaveCrit();
  687. TAGMSG0(DBGTAG_PNP, "=== CREATED ===");
  688. }
  689. return STATUS_SUCCESS;
  690. }
  691. /****************************************************************************\
  692. * If a device class "all-for-one" setting (ConnectMultiplePorts) is on,
  693. * then we just open the device the old (non-PnP) way and return TRUE. (As a
  694. * safety feature we also do this if gpWin32kDriverObject is NULL, because this
  695. * driver object is needed to register for PnP device class notifications)
  696. * Otherwise, return FALSE so we can continue and register for Arrival/Departure
  697. * notifications.
  698. *
  699. * This code was originally intended to be temporary until ConnectMultiplePorts
  700. * was finally turned off.
  701. * But now I think we have to keep it for backward compatibility with
  702. * drivers that filter Pointer/KeyboardClass0 and/or those that replace
  703. * Pointer/KeyboardClass0 by putting a different name in the registry under
  704. * System\CurrentControlSet\Services\RIT\mouclass (or kbbclass)
  705. \****************************************************************************/
  706. BOOL
  707. OpenMultiplePortDevice(DWORD DeviceType)
  708. {
  709. WCHAR awchDeviceName[MAX_PATH];
  710. UNICODE_STRING DeviceName;
  711. PDEVICE_TEMPLATE pDevTpl;
  712. PDEVICEINFO pDeviceInfo;
  713. PWCHAR pwchNameIndex;
  714. UINT uiConnectMultiplePorts = 0;
  715. CheckCritIn();
  716. if (DeviceType <= DEVICE_TYPE_MAX) {
  717. pDevTpl = &aDeviceTemplate[DeviceType];
  718. } else {
  719. RIPMSG1(RIP_ERROR, "OpenMultiplePortDevice(%d) - unknown type", DeviceType);
  720. return FALSE;
  721. }
  722. if (IsRemoteConnection()) {
  723. return FALSE;
  724. }
  725. #ifdef GENERIC_INPUT
  726. if (pDevTpl->dwFlags & DT_HID) {
  727. /*
  728. * HID devices don't need multiple port
  729. */
  730. return FALSE;
  731. }
  732. #endif // GENERIC_INPUT
  733. /*
  734. * Note that we don't need to FastOpenUserProfileMapping() here since
  735. * uiRegistrySection (PMAP_MOUCLASS_PARAMS/PMAP_KBDCLASS_PARAMS) is a
  736. * machine setiing, not a user setting.
  737. */
  738. FastGetProfileDwordW(NULL,
  739. pDevTpl->uiRegistrySection, L"ConnectMultiplePorts", 0, &uiConnectMultiplePorts, 0);
  740. /*
  741. * Open the device for read access.
  742. */
  743. if (uiConnectMultiplePorts || (gpWin32kDriverObject == NULL)) {
  744. /*
  745. * Find out if there is a name substitution in the registry.
  746. * Note that we don't need to FastOpenUserProfileMapping() here since
  747. * PMAP_INPUT is a machine setting, not a user setting.
  748. */
  749. FastGetProfileStringW(NULL,
  750. PMAP_INPUT,
  751. pDevTpl->pwszClassName,
  752. pDevTpl->pwszDefDevName, // if no substitution, use this default
  753. awchDeviceName,
  754. sizeof(awchDeviceName)/sizeof(WCHAR),
  755. 0);
  756. RtlInitUnicodeString(&DeviceName, awchDeviceName);
  757. pDeviceInfo = CreateDeviceInfo(DeviceType, &DeviceName, GDIF_NOTPNP);
  758. if (pDeviceInfo) {
  759. return TRUE;
  760. }
  761. } else {
  762. DeviceName.Length = 0;
  763. DeviceName.MaximumLength = sizeof(awchDeviceName);
  764. DeviceName.Buffer = awchDeviceName;
  765. RtlAppendUnicodeToString(&DeviceName, pDevTpl->pwszLegacyDevName);
  766. pwchNameIndex = &DeviceName.Buffer[(DeviceName.Length / sizeof(WCHAR)) - 1];
  767. for (*pwchNameIndex = L'0'; *pwchNameIndex <= L'9'; (*pwchNameIndex)++) {
  768. CreateDeviceInfo(DeviceType, &DeviceName, GDIF_NOTPNP);
  769. }
  770. }
  771. return FALSE;
  772. }
  773. /***************************************************************************\
  774. * RegisterCDROMNotify
  775. *
  776. * History:
  777. * 08-21-00 VTan Created
  778. \***************************************************************************/
  779. VOID RegisterCDROMNotify(
  780. VOID)
  781. {
  782. UserAssert(!IsRemoteConnection());
  783. UserAssert(gpWin32kDriverObject != NULL);
  784. if (gpWin32kDriverObject != NULL) {
  785. IoRegisterPlugPlayNotification (
  786. EventCategoryDeviceInterfaceChange,
  787. PNPNOTIFY_DEVICE_INTERFACE_INCLUDE_EXISTING_INTERFACES,
  788. (PVOID) &CdRomClassGuid,
  789. gpWin32kDriverObject,
  790. (PDRIVER_NOTIFICATION_CALLBACK_ROUTINE)DeviceClassCDROMNotify,
  791. NULL,
  792. &gCDROMClassRegistrationEntry);
  793. }
  794. }
  795. /***************************************************************************\
  796. * RegisterForDeviceClassNotifications
  797. *
  798. * Get ready to receive notifications that a mouse or keyboard is plugged in
  799. * or removed, then request notifications by registering for them.
  800. *
  801. * History:
  802. * 10-20-97 IanJa Taken from ntos\io\pnpinit.c
  803. \***************************************************************************/
  804. NTSTATUS
  805. xxxRegisterForDeviceClassNotifications(
  806. VOID)
  807. {
  808. IO_NOTIFICATION_EVENT_CATEGORY eventCategory;
  809. ULONG eventFlags;
  810. NTSTATUS Status;
  811. UNICODE_STRING ustrDriverName;
  812. DWORD DeviceType;
  813. CheckCritIn();
  814. TAGMSG0(DBGTAG_PNP, "enter xxxRegisterForDeviceClassNotifications()");
  815. /*
  816. * Remote hydra session indicates CreateDeviceInfo in xxxRemoteReconnect.
  817. */
  818. UserAssert(!IsRemoteConnection());
  819. if (!gbFirstConnectionDone) {
  820. if (!gbRemoteSession) {
  821. // Session 0
  822. /*
  823. * This must be done before devices are registered for device
  824. * notifications which will occur as a result of CreateDeviceInfo.
  825. */
  826. RtlInitUnicodeString(&ustrDriverName, L"\\Driver\\Win32k");
  827. Status = IoCreateDriver(&ustrDriverName, Win32kPnPDriverEntry);
  828. TAGMSG1(DBGTAG_PNP | RIP_THERESMORE, "IoCreateDriver returned status = %lx", Status);
  829. TAGMSG1(DBGTAG_PNP, "gpWin32kDriverObject = %lx", gpWin32kDriverObject);
  830. if (!NT_SUCCESS(Status)) {
  831. RIPMSG1(RIP_ERROR, "IoCreateDriver failed, status %lx", Status);
  832. Status = STATUS_SUCCESS;
  833. }
  834. UserAssert(gpWin32kDriverObject);
  835. } else {
  836. UserAssert(gpWin32kDriverObject == NULL);
  837. /*
  838. * Non-Zero session attached to the console
  839. */
  840. RtlInitUnicodeString(&ustrDriverName, L"\\Driver\\Win32k");
  841. //
  842. // Attempt to open the driver object
  843. //
  844. Status = ObReferenceObjectByName(&ustrDriverName,
  845. OBJ_CASE_INSENSITIVE,
  846. NULL,
  847. 0,
  848. *IoDriverObjectType,
  849. KernelMode,
  850. NULL,
  851. &gpWin32kDriverObject);
  852. if (!NT_SUCCESS(Status)) {
  853. RIPMSG1(RIP_ERROR, "ObReferenceObjectByName failed, status %lx", Status);
  854. Status = STATUS_SUCCESS;
  855. }
  856. UserAssert(gpWin32kDriverObject);
  857. }
  858. }
  859. //
  860. // We are only interested in DeviceClasses changing.
  861. //
  862. eventCategory = EventCategoryDeviceInterfaceChange;
  863. //
  864. // We want to be notified for all devices that are in the system.
  865. // those that are know now, and those that will arive later.
  866. // This allows us to have one code path for adding devices, and eliminates
  867. // the nasty race condition. If we were only interested in the devices
  868. // that exist at this one moment in time, and not future devices, we
  869. // would call IoGetDeviceClassAssociations.
  870. //
  871. eventFlags = PNPNOTIFY_DEVICE_INTERFACE_INCLUDE_EXISTING_INTERFACES;
  872. /*
  873. * For all input device types:
  874. * If they are Multiple Port Devices (ie: not PnP) just open them
  875. * Else Register them for PnP notifications (they will be opened when the
  876. * arrival notification arrives.
  877. * If devices are already attached, we will received immediate notification
  878. * during the call to IoRegisterPlugPlayNotification, so we must LeaveCrit
  879. * because the callback routine DeviceClassNotify expects it.
  880. */
  881. for (DeviceType = 0; DeviceType <= DEVICE_TYPE_MAX; DeviceType++) {
  882. if (!OpenMultiplePortDevice(DeviceType) && (gpWin32kDriverObject != NULL)) {
  883. /*
  884. * Make the registration.
  885. */
  886. TAGMSG1(DBGTAG_PNP, "Registering device type %d", DeviceType);
  887. LeaveCrit(); // for DeviceClassNotify
  888. Status = IoRegisterPlugPlayNotification (
  889. eventCategory,
  890. eventFlags,
  891. (PVOID)aDeviceTemplate[DeviceType].pClassGUID,
  892. gpWin32kDriverObject,
  893. (PDRIVER_NOTIFICATION_CALLBACK_ROUTINE)DeviceClassNotify,
  894. LongToPtr( DeviceType ),
  895. &aDeviceClassNotificationEntry[DeviceType]);
  896. EnterCrit();
  897. TAGMSG1(DBGTAG_PNP, "Registration returned status %lx", Status);
  898. if (!NT_SUCCESS(Status)) {
  899. RIPMSG2(RIP_ERROR, "IoRegisterPlugPlayNotification(%d) failed, status %lx",
  900. DeviceType, Status);
  901. }
  902. }
  903. }
  904. // Now Register for CD_ROM notifications
  905. LeaveCrit(); // for DeviceClassNotify
  906. if (!gbFirstConnectionDone && gpWin32kDriverObject != NULL) {
  907. if (!IsRemoteConnection()) {
  908. RegisterCDROMNotify();
  909. }
  910. gbFirstConnectionDone = TRUE;
  911. }
  912. EnterCrit();
  913. return Status;
  914. }
  915. /***************************************************************************\
  916. * UnregisterDeviceClassNotifications
  917. *
  918. * Remove device class notification registrations.
  919. *
  920. * History:
  921. * 02-28-00 Earhart Created
  922. \***************************************************************************/
  923. VOID
  924. xxxUnregisterDeviceClassNotifications(
  925. VOID)
  926. {
  927. // Our input devices will automatically unregister themselves; we
  928. // need to clean up cdrom, though.
  929. PLIST_ENTRY pNext;
  930. PCDROM_NOTIFY pContext;
  931. PVOID RegistrationEntry;
  932. EnterMediaCrit();
  933. if (gCDROMClassRegistrationEntry) {
  934. RegistrationEntry = gCDROMClassRegistrationEntry;
  935. gCDROMClassRegistrationEntry = NULL;
  936. LeaveMediaCrit();
  937. IoUnregisterPlugPlayNotification(RegistrationEntry);
  938. EnterMediaCrit();
  939. }
  940. while (TRUE) {
  941. pNext = RemoveHeadList(&gCDROMNotifyList);
  942. if (!pNext || pNext == &gCDROMNotifyList) {
  943. break;
  944. }
  945. pContext = CONTAINING_RECORD(pNext, CDROM_NOTIFY, Entry);
  946. LeaveMediaCrit(); /* in case there's a notification pending */
  947. IoUnregisterPlugPlayNotification(pContext->RegistrationHandle);
  948. UserFreePool(pContext);
  949. EnterMediaCrit();
  950. }
  951. LeaveMediaCrit();
  952. }
  953. /***************************************************************************\
  954. * GetKbdExId
  955. *
  956. * Get extended keyboard id with WMI
  957. *
  958. * History:
  959. * 01-02-01 Hiroyama Created
  960. \***************************************************************************/
  961. NTSTATUS GetKbdExId(
  962. HANDLE hDevice,
  963. PKEYBOARD_ID_EX pIdEx)
  964. {
  965. PWNODE_SINGLE_INSTANCE pNode;
  966. ULONG size;
  967. PVOID p = NULL;
  968. NTSTATUS status;
  969. UNICODE_STRING str;
  970. status = IoWMIOpenBlock((LPGUID)&MSKeyboard_ExtendedID_GUID, WMIGUID_QUERY, &p);
  971. if (NT_SUCCESS(status)) {
  972. status = IoWMIHandleToInstanceName(p, hDevice, &str);
  973. TAGMSG2(DBGTAG_PNP, "GetKbdExId: DevName='%.*ws'",
  974. str.Length / sizeof(WCHAR),
  975. str.Buffer);
  976. if (NT_SUCCESS(status)) {
  977. // Get the size
  978. size = 0;
  979. IoWMIQuerySingleInstance(p, &str, &size, NULL);
  980. size += sizeof *pIdEx;
  981. pNode = UserAllocPoolNonPaged(size, TAG_KBDEXID);
  982. if (pNode) {
  983. status = IoWMIQuerySingleInstance(p, &str, &size, pNode);
  984. if (NT_SUCCESS(status)) {
  985. *pIdEx = *(PKEYBOARD_ID_EX)(((PUCHAR)pNode) + pNode->DataBlockOffset);
  986. }
  987. UserFreePool(pNode);
  988. }
  989. RtlFreeUnicodeString(&str);
  990. }
  991. ObDereferenceObject(p);
  992. }
  993. return status;
  994. }
  995. /***************************************************************************\
  996. * QueryDeviceInfo
  997. *
  998. * Query the device information. This function is an async function,
  999. * so be sure any buffers it uses aren't allocated on the stack!
  1000. *
  1001. * If this is an asynchronous IOCTL, perhaps we should be waiting on
  1002. * the file handle or on an event for it to succeed?
  1003. *
  1004. * This function must called by the RIT, not directly by PnP notification
  1005. * (else the handle we issue the IOCTL on will be invalid)
  1006. *
  1007. * History:
  1008. * 01-20-99 IanJa Created.
  1009. \***************************************************************************/
  1010. NTSTATUS
  1011. QueryDeviceInfo(
  1012. PDEVICEINFO pDeviceInfo)
  1013. {
  1014. NTSTATUS Status;
  1015. PDEVICE_TEMPLATE pDevTpl = &aDeviceTemplate[pDeviceInfo->type];
  1016. KEYBOARD_ID_EX IdEx;
  1017. #ifdef GENERIC_INPUT
  1018. UserAssert(pDeviceInfo->type != DEVICE_TYPE_HID);
  1019. #endif
  1020. #ifdef DIAGNOSE_IO
  1021. pDeviceInfo->AttrStatus =
  1022. #endif
  1023. Status = ZwDeviceIoControlFile(pDeviceInfo->handle, NULL, NULL, NULL,
  1024. &pDeviceInfo->iosb,
  1025. pDevTpl->IOCTL_Attr,
  1026. NULL, 0,
  1027. (PVOID)((PBYTE)pDeviceInfo + pDevTpl->offAttr),
  1028. pDevTpl->cbAttr);
  1029. if (!NT_SUCCESS(Status)) {
  1030. RIPMSG2(RIP_WARNING, "QueryDeviceInfo(%p): IOCTL failed - Status %lx",
  1031. pDeviceInfo, Status);
  1032. }
  1033. TAGMSG1(DBGTAG_PNP, "IOCTL_*_QUERY_ATTRIBUTES returns Status %lx", Status);
  1034. if (pDeviceInfo->type == DEVICE_TYPE_KEYBOARD) {
  1035. if (NT_SUCCESS(GetKbdExId(pDeviceInfo->handle, &IdEx))) {
  1036. TAGMSG4(DBGTAG_PNP, "QueryDeviceInfo: kbd (%x,%x) ExId:(%x,%x)",
  1037. pDeviceInfo->keyboard.Attr.KeyboardIdentifier.Type, pDeviceInfo->keyboard.Attr.KeyboardIdentifier.Subtype,
  1038. IdEx.Type, IdEx.Subtype);
  1039. pDeviceInfo->keyboard.IdEx = IdEx;
  1040. } else {
  1041. // What can we do?
  1042. pDeviceInfo->keyboard.IdEx.Type = pDeviceInfo->keyboard.Attr.KeyboardIdentifier.Type;
  1043. pDeviceInfo->keyboard.IdEx.Subtype = pDeviceInfo->keyboard.Attr.KeyboardIdentifier.Subtype;
  1044. TAGMSG3(DBGTAG_PNP, "QueryDeviceInfo: failed to get ExId for pDevice=%p, fallback to (%x,%x)",
  1045. pDeviceInfo, pDeviceInfo->keyboard.IdEx.Type, pDeviceInfo->keyboard.IdEx.Subtype);
  1046. }
  1047. }
  1048. return Status;
  1049. }
  1050. /***************************************************************************\
  1051. * OpenDevice
  1052. *
  1053. * This function opens an input device for USER, mouse or keyboard.
  1054. *
  1055. *
  1056. * Return value
  1057. * BOOL did the operation succeed?
  1058. *
  1059. * When trying to open a HYDRA client's mouse (or kbd?), pDeviceInfo->ustrName
  1060. * is NULL.
  1061. *
  1062. * This function must called by the RIT, not directly by PnP
  1063. * notification (that way the handle we are about to create will be in the right
  1064. * our process)
  1065. *
  1066. * History:
  1067. * 11-26-90 DavidPe Created.
  1068. * 01-07-98 IanJa Plug & Play
  1069. * 04-17-98 IanJa Only open mice in RIT context.
  1070. \***************************************************************************/
  1071. BOOL OpenDevice(
  1072. PDEVICEINFO pDeviceInfo)
  1073. {
  1074. OBJECT_ATTRIBUTES ObjectAttributes;
  1075. NTSTATUS Status;
  1076. ULONG ulAccessMode = FILE_READ_DATA | SYNCHRONIZE;
  1077. ULONG ulShareMode = FILE_SHARE_WRITE;
  1078. UINT i;
  1079. CheckCritIn();
  1080. UserAssert((PtiCurrentShared() == gptiRit) || (PtiCurrentShared() == gTermIO.ptiDesktop));
  1081. TAGMSG4(DBGTAG_PNP, "OpenDevice(): Opening type %d (%lx %.*ws)",
  1082. pDeviceInfo->type, pDeviceInfo->handle, pDeviceInfo->ustrName.Length / sizeof(WCHAR), pDeviceInfo->ustrName.Buffer);
  1083. #ifdef DIAGNOSE_IO
  1084. pDeviceInfo->OpenerProcess = PsGetCurrentProcessId();
  1085. #endif
  1086. if (IsRemoteConnection()) {
  1087. TRACE_INIT(("OpenDevice - Remote mode\n"));
  1088. /*
  1089. * For other than the console, the mouse handle is
  1090. * set before createwinstation.
  1091. */
  1092. pDeviceInfo->bFlags |= GDIF_NOTPNP;
  1093. switch (pDeviceInfo->type) {
  1094. case DEVICE_TYPE_MOUSE:
  1095. pDeviceInfo->handle = ghRemoteMouseChannel;
  1096. if (ghRemoteMouseChannel == NULL) {
  1097. return FALSE;
  1098. }
  1099. break;
  1100. case DEVICE_TYPE_KEYBOARD:
  1101. pDeviceInfo->handle = ghRemoteKeyboardChannel;
  1102. if (ghRemoteKeyboardChannel == NULL) {
  1103. return FALSE;
  1104. }
  1105. break;
  1106. default:
  1107. RIPMSG2(RIP_ERROR, "Unknown device type %d DeviceInfo %#p",
  1108. pDeviceInfo->type, pDeviceInfo);
  1109. return FALSE;
  1110. }
  1111. } else {
  1112. InitializeObjectAttributes(&ObjectAttributes, &(pDeviceInfo->ustrName), 0, NULL, NULL);
  1113. #ifdef GENERIC_INPUT
  1114. if (pDeviceInfo->type == DEVICE_TYPE_HID) {
  1115. ulAccessMode |= FILE_WRITE_DATA;
  1116. ulShareMode |= FILE_SHARE_READ;
  1117. }
  1118. #endif
  1119. // USB devices are slow, so they may not have been closed before we
  1120. // open again here so let us delay execution for some time and try
  1121. // to open them again. We delay 1/10th of a second for a max of 30
  1122. // times, making a total wait time of 3 seconds.
  1123. //
  1124. // If we fast user switch too fast, the serial port may be in the
  1125. // process of closing where it stalls execution. This is a rare
  1126. // case where we may open the serial port while it is stalling
  1127. // and get back STATUS_ACCESS_DENIED and lose the user's device.
  1128. // In this case, we should retry the open and it should succeed
  1129. // once the serial port has closed.
  1130. for (i = 0; i < MAX_RETRIES_TO_OPEN; i++) {
  1131. #ifdef DIAGNOSE_IO
  1132. pDeviceInfo->OpenStatus =
  1133. #endif
  1134. Status = ZwCreateFile(&pDeviceInfo->handle, ulAccessMode,
  1135. &ObjectAttributes, &pDeviceInfo->iosb, NULL, 0, ulShareMode, FILE_OPEN_IF, 0, NULL, 0);
  1136. if ((STATUS_SHARING_VIOLATION == Status) ||
  1137. (Status == STATUS_ACCESS_DENIED)) {
  1138. // Sleep for 1/10th of a second
  1139. UserSleep(100);
  1140. } else {
  1141. // Device opened successfully or some other error occured
  1142. break;
  1143. }
  1144. }
  1145. TAGMSG2(DBGTAG_PNP, "ZwCreateFile returns handle %lx, Status %lx",
  1146. pDeviceInfo->handle, Status);
  1147. if (!NT_SUCCESS(Status)) {
  1148. if ((pDeviceInfo->bFlags & GDIF_NOTPNP) == 0) {
  1149. /*
  1150. * Don't warn about PS/2 mice: the PointerClassLegacy0 -9 and
  1151. * KeyboardClassLegacy0 - 9 will usually fail to be created
  1152. */
  1153. RIPMSG1(RIP_WARNING, "OpenDevice: ZwCreateFile failed with Status %lx", Status);
  1154. }
  1155. TRACE_INIT(("OpenDevice: ZwCreateFile failed with Status %lx", Status));
  1156. /*
  1157. * Don't FreeDeviceInfo here because that alters gpDeviceInfoList
  1158. * which our caller, ProcessDeviceChanges, is traversing.
  1159. * Instead, let ProcessDeviceChanges do it.
  1160. */
  1161. return FALSE;
  1162. }
  1163. }
  1164. #ifdef GENERIC_INPUT
  1165. /*
  1166. * All the HID Information has been already acquired through
  1167. * HidCreateDeviceInfo. Let's skip HID deviceinfo here.
  1168. */
  1169. if (pDeviceInfo->type != DEVICE_TYPE_HID) {
  1170. #endif
  1171. Status = QueryDeviceInfo(pDeviceInfo);
  1172. #ifdef GENERIC_INPUT
  1173. }
  1174. #endif
  1175. return NT_SUCCESS(Status);
  1176. }
  1177. VOID CloseDevice(
  1178. PDEVICEINFO pDeviceInfo)
  1179. {
  1180. NTSTATUS Status;
  1181. IO_STATUS_BLOCK IoStatusBlock;
  1182. CheckCritIn();
  1183. #ifdef TRACK_PNP_NOTIFICATION
  1184. if (gfRecordPnpNotification) {
  1185. CheckDeviceInfoListCritIn();
  1186. RecordPnpNotification(PNP_NTF_CLOSEDEVICE, pDeviceInfo, pDeviceInfo->usActions);
  1187. }
  1188. #endif // TRACK_PNP_NOTIFICATION
  1189. TAGMSG5(DBGTAG_PNP, "CloseDevice(%p): closing type %d (%lx %.*ws)",
  1190. pDeviceInfo,
  1191. pDeviceInfo->type, pDeviceInfo->handle,
  1192. pDeviceInfo->ustrName.Length / sizeof(WCHAR), pDeviceInfo->ustrName.Buffer);
  1193. if (pDeviceInfo->handle) {
  1194. UserAssert(pDeviceInfo->OpenerProcess == PsGetCurrentProcessId());
  1195. ZwCancelIoFile(pDeviceInfo->handle, &IoStatusBlock);
  1196. UserAssertMsg2(NT_SUCCESS(IoStatusBlock.Status), "NtCancelIoFile handle %x failed status %#x",
  1197. pDeviceInfo->handle, IoStatusBlock.Status);
  1198. if (pDeviceInfo->handle == ghRemoteMouseChannel) {
  1199. UserAssert(pDeviceInfo->type == DEVICE_TYPE_MOUSE);
  1200. pDeviceInfo->handle = 0;
  1201. return;
  1202. }
  1203. if (pDeviceInfo->handle == ghRemoteKeyboardChannel) {
  1204. UserAssert(pDeviceInfo->type == DEVICE_TYPE_KEYBOARD);
  1205. pDeviceInfo->handle = 0;
  1206. return;
  1207. }
  1208. Status = ZwClose(pDeviceInfo->handle);
  1209. UserAssertMsg2(NT_SUCCESS(Status), "ZwClose handle %x failed status %#x",
  1210. pDeviceInfo->handle, Status);
  1211. pDeviceInfo->handle = 0;
  1212. } else {
  1213. #ifdef GENERIC_INPUT
  1214. if (pDeviceInfo->type == DEVICE_TYPE_HID) {
  1215. /*
  1216. * HID devices may be closed regardless the error conditions.
  1217. */
  1218. TAGMSG2(DBGTAG_PNP, "CloseDevice: hid: pDeviceInfo->iosb.Status=%x, ReadStatus=%x",
  1219. pDeviceInfo->iosb.Status, pDeviceInfo->ReadStatus);
  1220. } else {
  1221. #endif
  1222. /*
  1223. * Assert the IO was cancelled or we tried to read the device
  1224. * after the first close (which set the handle to 0 - an invalid handle)
  1225. */
  1226. UserAssert((pDeviceInfo->iosb.Status == STATUS_CANCELLED) ||
  1227. (pDeviceInfo->ReadStatus == STATUS_INVALID_HANDLE));
  1228. #ifdef GENERIC_INPUT
  1229. }
  1230. #endif
  1231. }
  1232. }
  1233. /*****************************************************************************\
  1234. * RegisterForDeviceChangeNotifications()
  1235. *
  1236. * Device Notifications such as QueryRemove, RemoveCancelled, RemoveComplete
  1237. * tell us what is going on with the mouse.
  1238. * To register for device notifications:
  1239. * (1) Obtain a pointer to the device object (pFileObject)
  1240. * (2) Register for target device change notifications, saving the
  1241. * notification handle (which we will need in order to deregister)
  1242. *
  1243. * It doesn't matter too much if this fails: we just won't be able to eject the
  1244. * hardware via the UI very successfully. (We can still just yank it though).
  1245. * This will also fail if the ConnectMultiplePorts was set for this device.
  1246. *
  1247. * 1998-10-05 IanJa Created
  1248. \*****************************************************************************/
  1249. BOOL RegisterForDeviceChangeNotifications(
  1250. PDEVICEINFO pDeviceInfo)
  1251. {
  1252. PFILE_OBJECT pFileObject;
  1253. NTSTATUS Status;
  1254. /*
  1255. * In or Out of User critical section:
  1256. * In when called from RIT ProcessDeviceChanges();
  1257. * Out when called from the DeviceNotify callback
  1258. */
  1259. if (IsRemoteConnection()) {
  1260. TRACE_INIT(("RegisterForDeviceChangeNotifications called for remote session\n"));
  1261. return TRUE;
  1262. }
  1263. CheckCritIn();
  1264. UserAssert((PtiCurrentShared() == gptiRit) || (PtiCurrentShared() == gTermIO.ptiDesktop));
  1265. UserAssert(pDeviceInfo->handle);
  1266. UserAssert(pDeviceInfo->OpenerProcess == PsGetCurrentProcessId());
  1267. if (pDeviceInfo->bFlags & GDIF_NOTPNP) {
  1268. return TRUE;
  1269. }
  1270. Status = ObReferenceObjectByHandle(pDeviceInfo->handle,
  1271. 0,
  1272. NULL,
  1273. KernelMode,
  1274. (PVOID)&pFileObject,
  1275. NULL);
  1276. if (NT_SUCCESS(Status)) {
  1277. Status = IoRegisterPlugPlayNotification (
  1278. EventCategoryTargetDeviceChange, // EventCategory
  1279. 0, // EventCategoryFlags
  1280. (PVOID)pFileObject, // EventCategoryData
  1281. gpWin32kDriverObject, // DriverObject
  1282. // (PDRIVER_NOTIFICATION_CALLBACK_ROUTINE)
  1283. DeviceNotify,
  1284. (PVOID)pDeviceInfo, // Context
  1285. &pDeviceInfo->NotificationEntry);
  1286. ObDereferenceObject(pFileObject);
  1287. if (!NT_SUCCESS(Status)) {
  1288. // This is only OK if ConnectMultiplePorts is on (ie: not a PnP device)
  1289. // For the record, the old RIPMSG referred NTBUG #333453.
  1290. RIPMSG3(RIP_ERROR,
  1291. "IoRegisterPlugPlayNotification failed on device %.*ws, status %lx",
  1292. pDeviceInfo->ustrName.Length / sizeof(WCHAR),
  1293. pDeviceInfo->ustrName.Buffer, Status);
  1294. }
  1295. } else {
  1296. // non-catastrophic error (won't be able to remove device)
  1297. RIPMSG2(RIP_ERROR, "Can't get pFileObject from handle %lx, status %lx",
  1298. pDeviceInfo->handle, Status);
  1299. }
  1300. return NT_SUCCESS(Status);
  1301. }
  1302. BOOL UnregisterForDeviceChangeNotifications(PDEVICEINFO pDeviceInfo)
  1303. {
  1304. NTSTATUS Status;
  1305. #ifdef TRACK_PNP_NOTIFICATION
  1306. if (gfRecordPnpNotification) {
  1307. CheckDeviceInfoListCritIn();
  1308. RecordPnpNotification(PNP_NTF_UNREGISTER_NOTIFICATION, pDeviceInfo, pDeviceInfo->usActions);
  1309. }
  1310. #endif
  1311. CheckCritIn();
  1312. UserAssert((PtiCurrentShared() == gptiRit) || (PtiCurrentShared() == gTermIO.ptiDesktop));
  1313. UserAssert(pDeviceInfo->OpenerProcess == PsGetCurrentProcessId());
  1314. if (pDeviceInfo->NotificationEntry == NULL) {
  1315. /*
  1316. * This happens for non-PnP devices or if the earlier
  1317. * IoRegisterPlugPlayNotification() failed. Return now since
  1318. * IoUnregisterPlugPlayNotification(NULL) will bluescreen.
  1319. * And other case is also when we detach remote devices (which are
  1320. * not PnP) when reconnecting locally.
  1321. */
  1322. return TRUE;
  1323. }
  1324. // non-PnP devices should not have any NotificationEntry:
  1325. UserAssert((pDeviceInfo->bFlags & GDIF_NOTPNP) == 0);
  1326. TAGMSG4(DBGTAG_PNP, "UnregisterForDeviceChangeNotifications(): type %d (%lx %.*ws)",
  1327. pDeviceInfo->type, pDeviceInfo, pDeviceInfo->ustrName.Length / sizeof(WCHAR), pDeviceInfo->ustrName.Buffer);
  1328. Status = IoUnregisterPlugPlayNotification(pDeviceInfo->NotificationEntry);
  1329. if (!NT_SUCCESS(Status)) {
  1330. RIPMSG2(RIP_ERROR,
  1331. "IoUnregisterPlugPlayNotification failed Status = %lx, DEVICEINFO %lx",
  1332. Status, pDeviceInfo);
  1333. return FALSE;
  1334. }
  1335. pDeviceInfo->NotificationEntry = 0;
  1336. return TRUE;
  1337. }
  1338. /***************************************************************************\
  1339. * Handle device notifications such as QueryRemove, CancelRemove etc.
  1340. *
  1341. * Execution Context:
  1342. * when yanked: a non-WIN32 thread.
  1343. * via UI: ??? (won't see this except from laptop being undocked?)
  1344. *
  1345. * History:
  1346. \***************************************************************************/
  1347. __inline USHORT GetPnpActionFromGuid(
  1348. GUID *pEvent)
  1349. {
  1350. USHORT usAction = 0;
  1351. if (IsEqualGUID(pEvent, &GUID_TARGET_DEVICE_QUERY_REMOVE)) {
  1352. TAGMSG0(DBGTAG_PNP | RIP_NONAME, "QueryRemove");
  1353. usAction = GDIAF_QUERYREMOVE;
  1354. } else if (IsEqualGUID(pEvent, &GUID_TARGET_DEVICE_REMOVE_CANCELLED)) {
  1355. TAGMSG0(DBGTAG_PNP | RIP_NONAME, "RemoveCancelled");
  1356. usAction = GDIAF_REMOVECANCELLED;
  1357. } else if (IsEqualGUID(pEvent, &GUID_TARGET_DEVICE_REMOVE_COMPLETE)) {
  1358. TAGMSG1(DBGTAG_PNP | RIP_NONAME, "RemoveComplete (process %#x)", PsGetCurrentProcessId());
  1359. usAction = GDIAF_DEPARTED;
  1360. } else {
  1361. TAGMSG4(DBGTAG_PNP | RIP_NONAME, "GUID Unknown: %lx:%lx:%lx:%x...",
  1362. pEvent->Data1, pEvent->Data2,
  1363. pEvent->Data3, pEvent->Data4[0]);
  1364. }
  1365. return usAction;
  1366. }
  1367. NTSTATUS DeviceNotify(
  1368. IN PPLUGPLAY_NOTIFY_HDR pNotification,
  1369. IN PDEVICEINFO pDeviceInfo) // should the context be a kernel address?
  1370. {
  1371. USHORT usAction;
  1372. PDEVICEINFO pDeviceInfoTmp;
  1373. CheckCritOut();
  1374. CheckDeviceInfoListCritOut();
  1375. /*
  1376. * Check the validity of pDeviceInfo.
  1377. */
  1378. EnterDeviceInfoListCrit();
  1379. for (pDeviceInfoTmp = gpDeviceInfoList; pDeviceInfoTmp; pDeviceInfoTmp = pDeviceInfoTmp->pNext) {
  1380. if (pDeviceInfoTmp == pDeviceInfo) {
  1381. break;
  1382. }
  1383. }
  1384. if (pDeviceInfoTmp == NULL) {
  1385. /*
  1386. * This is an unknown device, most likely the one already freed.
  1387. */
  1388. #ifdef TRACK_PNP_NOTIFICATION
  1389. if (gfRecordPnpNotification) {
  1390. RecordPnpNotification(PNP_NTF_DEVICENOTIFY_UNLISTED, pDeviceInfo, GetPnpActionFromGuid(&pNotification->Event));
  1391. }
  1392. #endif
  1393. RIPMSG1(RIP_ERROR, "win32k!DeviceNotify: Notification for unlisted DEVICEINFO %p, contact ntuserdt!", pDeviceInfo);
  1394. LeaveDeviceInfoListCrit();
  1395. /*
  1396. * Not to prevent device removal etc.,
  1397. * return success here.
  1398. */
  1399. return STATUS_SUCCESS;
  1400. }
  1401. #ifdef TRACK_PNP_NOTIFICATION
  1402. if (gfRecordPnpNotification) {
  1403. RecordPnpNotification(PNP_NTF_DEVICENOTIFY, pDeviceInfo, GetPnpActionFromGuid(&pNotification->Event));
  1404. }
  1405. #endif
  1406. LeaveDeviceInfoListCrit();
  1407. if (IsRemoteConnection()) {
  1408. return STATUS_SUCCESS;
  1409. }
  1410. TAGMSG1(DBGTAG_PNP | RIP_THERESMORE, "DeviceNotify >>> %lx", pDeviceInfo);
  1411. UserAssert(pDeviceInfo->OpenerProcess != PsGetCurrentProcessId());
  1412. UserAssert(pDeviceInfo->usActions == 0);
  1413. usAction = GetPnpActionFromGuid(&pNotification->Event);
  1414. if (usAction == 0) {
  1415. return STATUS_UNSUCCESSFUL;
  1416. }
  1417. /*
  1418. * Signal the RIT to ProcessDeviceChanges()
  1419. * Wait for completion according to the GDIAF_PNPWAITING bit
  1420. */
  1421. CheckCritOut();
  1422. CheckDeviceInfoListCritOut();
  1423. /*
  1424. * There is small window where we can get a PnP notification for a device that
  1425. * we just have unregister unregistered a notification for and that we are deleting
  1426. * so for PnP notification we need to check the device is valid (still in the list
  1427. * and not being deleted.
  1428. */
  1429. EnterDeviceInfoListCrit();
  1430. pDeviceInfoTmp = gpDeviceInfoList;
  1431. while (pDeviceInfoTmp) {
  1432. if (pDeviceInfoTmp == pDeviceInfo ) {
  1433. if (!(pDeviceInfo->usActions & (GDIAF_FREEME | GDIAF_DEPARTED))) {
  1434. KeResetEvent(gpEventPnPWainting);
  1435. gbPnPWaiting = TRUE;
  1436. RequestDeviceChange(pDeviceInfo, (USHORT)(usAction | GDIAF_PNPWAITING), TRUE);
  1437. gbPnPWaiting = FALSE;
  1438. KeSetEvent(gpEventPnPWainting, EVENT_INCREMENT, FALSE);
  1439. }
  1440. break;
  1441. }
  1442. pDeviceInfoTmp = pDeviceInfoTmp->pNext;
  1443. }
  1444. LeaveDeviceInfoListCrit();
  1445. return STATUS_SUCCESS;
  1446. }
  1447. /***************************************************************************\
  1448. * StartDeviceRead
  1449. *
  1450. * This function makes an asynchronous read request to the input device driver,
  1451. * unless the device has been marked for destruction (GDIAF_FREEME)
  1452. *
  1453. * Returns:
  1454. * The next DeviceInfo on the list if this device was freed: If the caller
  1455. * was not already in the DeviceInfoList critical section, the this must be
  1456. * ignored as it is not safe.
  1457. * NULL if the read succeeded.
  1458. *
  1459. * History:
  1460. * 11-26-90 DavidPe Created.
  1461. * 10-20-98 IanJa Generalized for PnP input devices
  1462. \***************************************************************************/
  1463. PDEVICEINFO StartDeviceRead(
  1464. PDEVICEINFO pDeviceInfo)
  1465. {
  1466. PDEVICE_TEMPLATE pDevTpl;
  1467. #ifdef GENERIC_INPUT
  1468. PVOID pBuffer;
  1469. ULONG ulLengthToRead;
  1470. #endif
  1471. #if !defined(GENERIC_INPUT)
  1472. pDeviceInfo->bFlags |= GDIF_READING;
  1473. #endif
  1474. /*
  1475. * If this device need to be freed, abandon
  1476. * reading now and request the free.
  1477. */
  1478. if (pDeviceInfo->usActions & GDIAF_FREEME) {
  1479. #ifdef GENERIC_INPUT
  1480. BEGIN_REENTERCRIT() {
  1481. #if DBG
  1482. if (fAlreadyHadCrit) {
  1483. CheckDeviceInfoListCritIn();
  1484. }
  1485. #endif
  1486. #endif
  1487. BEGIN_REENTER_DEVICEINFOLISTCRIT() {
  1488. pDeviceInfo->bFlags &= ~GDIF_READING;
  1489. pDeviceInfo = FreeDeviceInfo(pDeviceInfo);
  1490. } END_REENTER_DEVICEINFOLISTCRIT();
  1491. #ifdef GENERIC_INPUT
  1492. } END_REENTERCRIT();
  1493. #endif
  1494. return pDeviceInfo;
  1495. }
  1496. if (gbExitInProgress || gbStopReadInput) {
  1497. // Let's not post any more reads when we're trying to exit, eh?
  1498. pDeviceInfo->bFlags &= ~GDIF_READING;
  1499. pDeviceInfo->iosb.Status = STATUS_UNSUCCESSFUL;
  1500. return NULL;
  1501. }
  1502. /*
  1503. * Initialize in case read fails
  1504. */
  1505. pDeviceInfo->iosb.Status = STATUS_UNSUCCESSFUL; // catch concurrent writes?
  1506. pDeviceInfo->iosb.Information = 0;
  1507. pDevTpl = &aDeviceTemplate[pDeviceInfo->type];
  1508. UserAssert(pDeviceInfo->OpenerProcess == PsGetCurrentProcessId());
  1509. #ifdef GENERIC_INPUT
  1510. if (pDeviceInfo->type == DEVICE_TYPE_HID) {
  1511. UserAssert(pDeviceInfo->hid.pTLCInfo);
  1512. if (pDeviceInfo->handle == NULL) {
  1513. /*
  1514. * Currently this device is not requested by anyone.
  1515. */
  1516. TAGMSG1(DBGTAG_PNP, "StartDeviceRead: pDevInfo=%p has been closed on demand.", pDeviceInfo);
  1517. BEGIN_REENTER_DEVICEINFOLISTCRIT()
  1518. if (pDeviceInfo->handle == NULL) {
  1519. if (pDeviceInfo->bFlags & GDIF_READING) {
  1520. pDeviceInfo->bFlags &= ~GDIF_READING;
  1521. TAGMSG1(DBGTAG_PNP, "StartDeviceRead: pDevInfo=%p, bFlags has been reset.", pDeviceInfo);
  1522. }
  1523. }
  1524. END_REENTER_DEVICEINFOLISTCRIT();
  1525. return NULL;
  1526. }
  1527. pBuffer = pDeviceInfo->hid.pHidDesc->pInputBuffer;
  1528. ulLengthToRead = pDeviceInfo->hid.pHidDesc->hidpCaps.InputReportByteLength * MAXIMUM_ITEMS_READ;
  1529. } else {
  1530. pBuffer = (PBYTE)pDeviceInfo + pDevTpl->offData;
  1531. ulLengthToRead = pDevTpl->cbData;
  1532. }
  1533. #endif
  1534. if (pDeviceInfo->handle == NULL) {
  1535. BEGIN_REENTER_DEVICEINFOLISTCRIT() {
  1536. /*
  1537. * Make sure the handle is truely NULL.
  1538. * If this is the case, perhaps this is called from APC
  1539. * that happened at bad timing, like in the middle of
  1540. * device removal query, when ProcessDeviceChanges completed
  1541. * but RequestDeviceChange is not awaken for the complete event.
  1542. * The code can olnly simply bail out once in the situation.
  1543. */
  1544. if (pDeviceInfo->handle == NULL) {
  1545. pDeviceInfo->bFlags &= ~GDIF_READING;
  1546. pDeviceInfo->ReadStatus = STATUS_INVALID_HANDLE;
  1547. }
  1548. } END_REENTER_DEVICEINFOLISTCRIT();
  1549. return NULL;
  1550. }
  1551. #ifdef GENERIC_INPUT
  1552. pDeviceInfo->bFlags |= GDIF_READING;
  1553. #endif
  1554. LOGTIME(pDeviceInfo->timeStartRead);
  1555. #ifdef DIAGNOSE_IO
  1556. pDeviceInfo->nReadsOutstanding++;
  1557. #endif
  1558. UserAssert(pDeviceInfo->handle);
  1559. /*
  1560. * Avoid to start reading NULL device handle.
  1561. * This happen when the DeviceNotify receives QUERY_REMOVE
  1562. * and the RIT finishes processing it, but RequestDeviceChange
  1563. * has not finished its wait.
  1564. */
  1565. #ifdef GENERIC_INPUT
  1566. pDeviceInfo->ReadStatus = ZwReadFile(
  1567. pDeviceInfo->handle,
  1568. NULL, // hReadEvent
  1569. InputApc, // InputApc()
  1570. pDeviceInfo, // ApcContext
  1571. &pDeviceInfo->iosb,
  1572. pBuffer,
  1573. ulLengthToRead,
  1574. PZERO(LARGE_INTEGER), NULL);
  1575. #else
  1576. pDeviceInfo->ReadStatus = ZwReadFile(
  1577. pDeviceInfo->handle,
  1578. NULL, // hReadEvent
  1579. InputApc, // InputApc()
  1580. pDeviceInfo, // ApcContext
  1581. &pDeviceInfo->iosb,
  1582. (PVOID)((PBYTE)pDeviceInfo + pDevTpl->offData),
  1583. pDevTpl->cbData,
  1584. PZERO(LARGE_INTEGER), NULL);
  1585. #endif
  1586. LOGTIME(pDeviceInfo->timeEndRead);
  1587. #if DBG
  1588. if (pDeviceInfo->bFlags & GDIF_DBGREAD) {
  1589. TAGMSG2(DBGTAG_PNP, "ZwReadFile of Device handle %lx returned status %lx",
  1590. pDeviceInfo->handle, pDeviceInfo->ReadStatus);
  1591. }
  1592. #endif
  1593. if (!NT_SUCCESS(pDeviceInfo->ReadStatus)) {
  1594. BEGIN_REENTER_DEVICEINFOLISTCRIT() {
  1595. /*
  1596. * If insufficient resources, retry the read the next time the RIT
  1597. * wakes up for the ID_TIMER event by incrementing gnRetryReadInput
  1598. * (Cheaper than setting our own timer),
  1599. * Else just abandon reading.
  1600. */
  1601. if (pDeviceInfo->ReadStatus == STATUS_INSUFFICIENT_RESOURCES) {
  1602. if (pDeviceInfo->nRetryRead++ < MAXIMUM_READ_RETRIES) {
  1603. pDeviceInfo->usActions |= GDIAF_RETRYREAD;
  1604. gnRetryReadInput++;
  1605. }
  1606. } else {
  1607. pDeviceInfo->bFlags &= ~GDIF_READING;
  1608. }
  1609. #ifdef DIAGNOSE_IO
  1610. pDeviceInfo->nReadsOutstanding--;
  1611. #endif
  1612. } END_REENTER_DEVICEINFOLISTCRIT();
  1613. } else {
  1614. pDeviceInfo->nRetryRead = 0;
  1615. }
  1616. if (!gbRemoteSession && !NT_SUCCESS(pDeviceInfo->ReadStatus))
  1617. RIPMSG2(RIP_WARNING, "StartDeviceRead %#p failed Status %#x",
  1618. pDeviceInfo, pDeviceInfo->ReadStatus);
  1619. return NULL;
  1620. }
  1621. #ifdef GENERIC_INPUT
  1622. /***************************************************************************\
  1623. * StopDeviceRead
  1624. *
  1625. * History:
  1626. * XX-XX-00 Hiroyama created
  1627. \***************************************************************************/
  1628. PDEVICEINFO StopDeviceRead(
  1629. PDEVICEINFO pDeviceInfo)
  1630. {
  1631. IO_STATUS_BLOCK IoStatusBlock;
  1632. TAGMSG1(DBGTAG_PNP, "StopDeviceRead(%p)", pDeviceInfo);
  1633. CheckCritIn();
  1634. CheckDeviceInfoListCritIn();
  1635. UserAssert(pDeviceInfo->type == DEVICE_TYPE_HID);
  1636. UserAssert(pDeviceInfo->handle);
  1637. UserAssert(pDeviceInfo->OpenerProcess == PsGetCurrentProcessId());
  1638. /*
  1639. * Stop reading this HID device.
  1640. */
  1641. pDeviceInfo->bFlags &= ~GDIF_READING;
  1642. ZwCancelIoFile(pDeviceInfo->handle, &IoStatusBlock);
  1643. UserAssertMsg2(NT_SUCCESS(IoStatusBlock.Status), "NtCancelIoFile handle %x failed status %#x",
  1644. pDeviceInfo->handle, IoStatusBlock.Status);
  1645. CloseDevice(pDeviceInfo);
  1646. return NULL;
  1647. }
  1648. #endif
  1649. /***************************************************************************\
  1650. * IsKnownKeyboardType
  1651. *
  1652. * Checks if the given type/subtype is the known IDs
  1653. * History:
  1654. * XX-XX-00 Hiroyama created
  1655. \***************************************************************************/
  1656. __inline BOOL IsKnownKeyboardType(
  1657. DWORD dwType,
  1658. DWORD dwSubType)
  1659. {
  1660. switch (dwType) {
  1661. case 4: // Generic
  1662. if ((BYTE)dwSubType == 0xff) {
  1663. /*
  1664. * Bogus subtype, most likely invalid Hydra device.
  1665. */
  1666. return FALSE;
  1667. }
  1668. return TRUE;
  1669. case 7: // Japanese
  1670. case 8: // Korean
  1671. return TRUE;
  1672. default:
  1673. break;
  1674. }
  1675. return FALSE;
  1676. }
  1677. /***************************************************************************\
  1678. * IsPS2Keyboard
  1679. *
  1680. * return TRUE for the PS/2 device name
  1681. * XX-XX-00 Hiroyama created
  1682. \***************************************************************************/
  1683. __inline BOOL IsPS2Keyboard(
  1684. LPWSTR pwszDevice)
  1685. {
  1686. static const WCHAR wszPS2Header[] = L"\\??\\Root#*";
  1687. static const WCHAR wszPS2HeaderACPI[] = L"\\??\\ACPI#*";
  1688. return wcsncmp(pwszDevice, wszPS2Header, ARRAY_SIZE(wszPS2Header) - 1) == 0 ||
  1689. wcsncmp(pwszDevice, wszPS2HeaderACPI, ARRAY_SIZE(wszPS2HeaderACPI) - 1) == 0;
  1690. }
  1691. __inline BOOL IsRDPKeyboard(
  1692. LPWSTR pwszDevice)
  1693. {
  1694. static const WCHAR wszRDPHeader[] = L"\\??\\Root#RDP";
  1695. return wcsncmp(pwszDevice, wszRDPHeader, ARRAY_SIZE(wszRDPHeader) - 1) == 0;
  1696. }
  1697. VOID ProcessDeviceChanges(
  1698. DWORD DeviceType)
  1699. {
  1700. PDEVICEINFO pDeviceInfo;
  1701. USHORT usOriginalActions;
  1702. #if DBG
  1703. volatile int nChanges = 0;
  1704. ULONG timeStartReadPrev;
  1705. #endif
  1706. /*
  1707. * Reset summary information for all Mice and Keyboards
  1708. */
  1709. DWORD nMice = 0;
  1710. DWORD nWheels = 0;
  1711. DWORD nMaxButtons = 0;
  1712. int nKeyboards = 0;
  1713. BOOLEAN fKeyboardIdSet = FALSE;
  1714. #ifdef GENERIC_INPUT
  1715. int nHid = 0;
  1716. #endif
  1717. CheckCritIn();
  1718. BEGINATOMICCHECK();
  1719. UserAssert((PtiCurrentShared() == gptiRit) || (PtiCurrentShared() == gTermIO.ptiDesktop));
  1720. EnterDeviceInfoListCrit();
  1721. BEGINATOMICDEVICEINFOLISTCHECK();
  1722. #ifdef TRACK_PNP_NOTIFICATION
  1723. if (gfRecordPnpNotification) {
  1724. RecordPnpNotification(PNP_NTF_PROCESSDEVICECHANGES, NULL, DeviceType);
  1725. }
  1726. #endif
  1727. if (DeviceType == DEVICE_TYPE_KEYBOARD) {
  1728. /*
  1729. * Set the fallback value.
  1730. */
  1731. gKeyboardInfo = gKeyboardDefaultInfo;
  1732. }
  1733. /*
  1734. * Look for devices to Create (those which have newly arrived)
  1735. * and for devices to Terminate (these which have just departed)
  1736. * and for device change notifications.
  1737. * Make sure the actions are processed in the right order in case we
  1738. * are being asked for more than one action per device: for example,
  1739. * we sometimes get QueryRemove followed quickly by RemoveCancelled
  1740. * and both actions arrive here together: we should do them in the
  1741. * correct order.
  1742. */
  1743. pDeviceInfo = gpDeviceInfoList;
  1744. while (pDeviceInfo) {
  1745. if (pDeviceInfo->type != DeviceType) {
  1746. pDeviceInfo = pDeviceInfo->pNext;
  1747. continue;
  1748. }
  1749. usOriginalActions = pDeviceInfo->usActions;
  1750. UserAssert((usOriginalActions == 0) || (usOriginalActions & ~GDIAF_PNPWAITING));
  1751. /*
  1752. * Refresh Mouse:
  1753. * We read a MOUSE_ATTRIBUTES_CHANGED flag when a PS/2 mouse
  1754. * is plugged back in. Find out the attributes of the device.
  1755. */
  1756. if (pDeviceInfo->usActions & GDIAF_REFRESH_MOUSE) {
  1757. pDeviceInfo->usActions &= ~GDIAF_REFRESH_MOUSE;
  1758. UserAssert(pDeviceInfo->type == DEVICE_TYPE_MOUSE);
  1759. #if DBG
  1760. nChanges++;
  1761. #endif
  1762. TAGMSG1(DBGTAG_PNP, "QueryDeviceInfo: %lx", pDeviceInfo);
  1763. QueryDeviceInfo(pDeviceInfo);
  1764. }
  1765. /*
  1766. * QueryRemove:
  1767. * Close the file object, but retain the DEVICEINFO struct and the
  1768. * registration in case we later get a RemoveCancelled.
  1769. */
  1770. if (pDeviceInfo->usActions & GDIAF_QUERYREMOVE) {
  1771. pDeviceInfo->usActions &= ~GDIAF_QUERYREMOVE;
  1772. #if DBG
  1773. nChanges++;
  1774. #endif
  1775. TAGMSG1(DBGTAG_PNP, "QueryRemove: %lx", pDeviceInfo);
  1776. CloseDevice(pDeviceInfo);
  1777. }
  1778. /*
  1779. * New device arrived or RemoveCancelled:
  1780. * If new device, Open it, register for notifications and start reading
  1781. * If RemoveCancelled, unregister the old notfications first
  1782. */
  1783. if (pDeviceInfo->usActions & (GDIAF_ARRIVED | GDIAF_REMOVECANCELLED)) {
  1784. // Reopen the file object, (this is a new file object, of course),
  1785. // Unregister for the old file, register with this new one.
  1786. if (pDeviceInfo->usActions & GDIAF_REMOVECANCELLED) {
  1787. pDeviceInfo->usActions &= ~GDIAF_REMOVECANCELLED;
  1788. #if DBG
  1789. nChanges++;
  1790. #endif
  1791. TAGMSG1(DBGTAG_PNP, "RemoveCancelled: %lx", pDeviceInfo);
  1792. UnregisterForDeviceChangeNotifications(pDeviceInfo);
  1793. }
  1794. #if DBG
  1795. if (pDeviceInfo->usActions & GDIAF_ARRIVED) {
  1796. nChanges++;
  1797. }
  1798. #endif
  1799. pDeviceInfo->usActions &= ~GDIAF_ARRIVED;
  1800. if (OpenDevice(pDeviceInfo)) {
  1801. PDEVICEINFO pDeviceInfoNext;
  1802. if (!IsRemoteConnection()) {
  1803. RegisterForDeviceChangeNotifications(pDeviceInfo);
  1804. }
  1805. #ifdef GENERIC_INPUT
  1806. if (pDeviceInfo->type == DEVICE_TYPE_HID) {
  1807. /*
  1808. * If this device is not requested, close the device now.
  1809. */
  1810. UserAssert(pDeviceInfo->handle);
  1811. UserAssert(pDeviceInfo->hid.pTLCInfo);
  1812. if (pDeviceInfo->handle && !HidTLCActive(pDeviceInfo->hid.pTLCInfo)) {
  1813. StopDeviceRead(pDeviceInfo); // also closes the handle
  1814. }
  1815. }
  1816. if (!((IsRemoteConnection()) && (pDeviceInfo->usActions & GDIAF_RECONNECT)) && pDeviceInfo->handle) {
  1817. pDeviceInfoNext = StartDeviceRead(pDeviceInfo);
  1818. if (pDeviceInfoNext) {
  1819. /*
  1820. * pDeviceInfo was freed, move onto the next
  1821. */
  1822. pDeviceInfo = pDeviceInfoNext;
  1823. continue;
  1824. }
  1825. }
  1826. #else
  1827. if (!((IsRemoteConnection()) && (pDeviceInfo->usActions & GDIAF_RECONNECT))) {
  1828. pDeviceInfoNext = StartDeviceRead(pDeviceInfo);
  1829. if (pDeviceInfoNext) {
  1830. /*
  1831. * pDeviceInfo wasa freed, move onto the next
  1832. */
  1833. pDeviceInfo = pDeviceInfoNext;
  1834. continue;
  1835. }
  1836. }
  1837. #endif
  1838. pDeviceInfo->usActions &= ~GDIAF_RECONNECT;
  1839. } else {
  1840. /*
  1841. * If the Open failed, we free the device here, and move on to
  1842. * the next device.
  1843. * Assert to catch re-open failure upon RemoveCancelled.
  1844. */
  1845. #if DBG
  1846. if ((usOriginalActions & GDIAF_ARRIVED) == 0) {
  1847. RIPMSG2(RIP_WARNING, "Re-Open %#p failed status %x during RemoveCancelled",
  1848. pDeviceInfo, pDeviceInfo->OpenStatus);
  1849. }
  1850. #endif
  1851. #ifdef GENERIC_INPUT
  1852. if (pDeviceInfo->type == DEVICE_TYPE_HID) {
  1853. /*
  1854. * Some other applications may open this device
  1855. * exclusively. We may succeed to open it later on, so
  1856. * keep this deviceinfo around until it's physically
  1857. * detached.
  1858. */
  1859. RIPMSG1(RIP_WARNING, "ProcessDeviceChanges: failed to open the device %p",
  1860. pDeviceInfo);
  1861. } else {
  1862. #endif
  1863. pDeviceInfo = FreeDeviceInfo(pDeviceInfo);
  1864. continue;
  1865. #ifdef GENERIC_INPUT
  1866. }
  1867. #endif
  1868. }
  1869. }
  1870. /*
  1871. * RemoveComplete:
  1872. * Close the file object, if you have not already done so, Unregister.
  1873. * FreeDeviceInfo here (which will actually request a free from the
  1874. * reader or the PnP requestor thread), and move on to the next device.
  1875. */
  1876. if (pDeviceInfo->usActions & GDIAF_DEPARTED) {
  1877. pDeviceInfo->usActions &= ~GDIAF_DEPARTED;
  1878. #if DBG
  1879. nChanges++;
  1880. #endif
  1881. TAGMSG1(DBGTAG_PNP, "RemoveComplete: %lx (process %#x)", pDeviceInfo);
  1882. CloseDevice(pDeviceInfo);
  1883. UnregisterForDeviceChangeNotifications(pDeviceInfo);
  1884. pDeviceInfo = FreeDeviceInfo(pDeviceInfo);
  1885. continue;
  1886. }
  1887. if (pDeviceInfo->usActions & GDIAF_IME_STATUS) {
  1888. pDeviceInfo->usActions &= ~GDIAF_IME_STATUS;
  1889. #if DBG
  1890. nChanges++;
  1891. #endif
  1892. if ((pDeviceInfo->type == DEVICE_TYPE_KEYBOARD) && (pDeviceInfo->handle)) {
  1893. if (FUJITSU_KBD_CONSOLE(pDeviceInfo->keyboard.Attr.KeyboardIdentifier) ||
  1894. (gbRemoteSession &&
  1895. FUJITSU_KBD_REMOTE(gRemoteClientKeyboardType))
  1896. ) {
  1897. /*
  1898. * Fill up the KEYBOARD_IME_STATUS structure.
  1899. */
  1900. ZwDeviceIoControlFile(pDeviceInfo->handle, NULL, NULL, NULL,
  1901. &giosbKbdControl, IOCTL_KEYBOARD_SET_IME_STATUS,
  1902. (PVOID)&gKbdImeStatus, sizeof(gKbdImeStatus), NULL, 0);
  1903. }
  1904. }
  1905. }
  1906. if (pDeviceInfo->usActions & GDIAF_RETRYREAD) {
  1907. PDEVICEINFO pDeviceInfoNext;
  1908. pDeviceInfo->usActions &= ~GDIAF_RETRYREAD;
  1909. UserAssert(pDeviceInfo->ReadStatus == STATUS_INSUFFICIENT_RESOURCES);
  1910. #if DBG
  1911. timeStartReadPrev = pDeviceInfo->timeStartRead;
  1912. #endif
  1913. TAGMSG2(DBGTAG_PNP, "Retry Read %#p after %lx ticks",
  1914. pDeviceInfo, pDeviceInfo->timeStartRead - timeStartReadPrev);
  1915. pDeviceInfoNext = StartDeviceRead(pDeviceInfo);
  1916. if (pDeviceInfoNext) {
  1917. /*
  1918. * pDeviceInfo wasa freed, move onto the next
  1919. */
  1920. pDeviceInfo = pDeviceInfoNext;
  1921. continue;
  1922. }
  1923. }
  1924. #ifdef GENERIC_INPUT
  1925. if (pDeviceInfo->usActions & GDIAF_STARTREAD) {
  1926. pDeviceInfo->usActions &= ~GDIAF_STARTREAD;
  1927. #if DBG
  1928. timeStartReadPrev = pDeviceInfo->timeStartRead;
  1929. #endif
  1930. TAGMSG1(DBGTAG_PNP, "Start Read %#p", pDeviceInfo);
  1931. UserAssert(pDeviceInfo->handle == NULL);
  1932. UserAssert(pDeviceInfo->type == DEVICE_TYPE_HID);
  1933. UserAssert(HidTLCActive(pDeviceInfo->hid.pTLCInfo)); // a bit over active assert?
  1934. if (!OpenDevice(pDeviceInfo)) {
  1935. /*
  1936. * Failed to open, perhaps some other applications
  1937. * has opened this device exclusively.
  1938. * We can't do nothing more than ignoring the failure.
  1939. * Let's get going.
  1940. */
  1941. RIPMSG1(RIP_WARNING, "ProcessDeviceChanges: STARTREAD failed to reopen the device %p",
  1942. pDeviceInfo);
  1943. } else {
  1944. PDEVICEINFO pDeviceInfoNext;
  1945. pDeviceInfoNext = StartDeviceRead(pDeviceInfo);
  1946. if (pDeviceInfoNext) {
  1947. /*
  1948. * pDeviceInfo was freed, move onto the next
  1949. */
  1950. pDeviceInfo = pDeviceInfoNext;
  1951. continue;
  1952. }
  1953. }
  1954. }
  1955. if (pDeviceInfo->usActions & GDIAF_STOPREAD) {
  1956. pDeviceInfo->usActions &= ~GDIAF_STOPREAD;
  1957. UserAssert(pDeviceInfo->type == DEVICE_TYPE_HID);
  1958. if (pDeviceInfo->handle) {
  1959. PDEVICEINFO pDeviceInfoNext;
  1960. /*
  1961. * StopDeviceRead cancels pending I/O,
  1962. * and closes the device handle,
  1963. * but basically the deviceinfo itself keeps
  1964. * alive.
  1965. */
  1966. pDeviceInfoNext = StopDeviceRead(pDeviceInfo);
  1967. if (pDeviceInfoNext) {
  1968. /*
  1969. * pDeviceInfo was freed, move onto the next
  1970. */
  1971. pDeviceInfo = pDeviceInfoNext;
  1972. }
  1973. } else {
  1974. RIPMSG1(RIP_WARNING, "ProcessDeviceChanges: STOPREAD, but handle is already NULL for %p",
  1975. pDeviceInfo);
  1976. }
  1977. }
  1978. #endif
  1979. /*
  1980. * Gather summary information on open devices
  1981. */
  1982. if (pDeviceInfo->handle) {
  1983. switch (pDeviceInfo->type) {
  1984. case DEVICE_TYPE_MOUSE:
  1985. UserAssert(PtiCurrentShared() == gTermIO.ptiDesktop);
  1986. if (pDeviceInfo->usActions & GDIAF_REFRESH_MOUSE) {
  1987. pDeviceInfo->usActions &= ~GDIAF_REFRESH_MOUSE;
  1988. #if DBG
  1989. nChanges++;
  1990. #endif
  1991. }
  1992. nMice++;
  1993. nMaxButtons = max(nMaxButtons, pDeviceInfo->mouse.Attr.NumberOfButtons);
  1994. switch(pDeviceInfo->mouse.Attr.MouseIdentifier) {
  1995. case WHEELMOUSE_I8042_HARDWARE:
  1996. case WHEELMOUSE_SERIAL_HARDWARE:
  1997. case WHEELMOUSE_HID_HARDWARE:
  1998. nWheels++;
  1999. }
  2000. break;
  2001. case DEVICE_TYPE_KEYBOARD:
  2002. UserAssert(PtiCurrentShared() == gptiRit);
  2003. // LEDStatus held in win32k.sys and later force the new keyboard
  2004. // to be set accordingly.
  2005. if (pDeviceInfo->ustrName.Buffer == NULL) {
  2006. /*
  2007. * This most likely is a bogus Hydra device.
  2008. */
  2009. RIPMSG1(RIP_WARNING, "ProcessDeviceChanges: KBD pDevInfo=%p has no name!", pDeviceInfo);
  2010. if (!fKeyboardIdSet) {
  2011. /*
  2012. * If keyboard id/attr is not set, try to get it from this device
  2013. * anyway. If there are legit PS/2 devices after this, we'll get
  2014. * a chance to re-aquire more meaningful id/attr.
  2015. */
  2016. goto get_attr_anyway;
  2017. }
  2018. } else {
  2019. NTSTATUS Status;
  2020. if ((!fKeyboardIdSet || IsPS2Keyboard(pDeviceInfo->ustrName.Buffer)) &&
  2021. !IsRDPKeyboard(pDeviceInfo->ustrName.Buffer)) {
  2022. get_attr_anyway:
  2023. #if 0
  2024. /*
  2025. * LATER: when other GI stuff in ntinput.c goes in,
  2026. * move this boot-time LED and type/subtype initialization to
  2027. * ntinput.c where the RIT is initialized.
  2028. */
  2029. #ifdef DIAGNOSE_IO
  2030. gKbdIoctlLEDSStatus =
  2031. #endif
  2032. Status = ZwDeviceIoControlFile(pDeviceInfo->handle, NULL, NULL, NULL,
  2033. &giosbKbdControl, IOCTL_KEYBOARD_QUERY_INDICATORS,
  2034. NULL, 0,
  2035. (PVOID)&gklpBootTime, sizeof(gklpBootTime));
  2036. UserAssertMsg2(NT_SUCCESS(Status),
  2037. "IOCTL_KEYBOARD_QUERY_INDICATORS failed: DeviceInfo %#x, Status %#x",
  2038. pDeviceInfo, Status);
  2039. TAGMSG1(DBGTAG_PNP, "ProcessDeviceChanges: led flag is %x", gklpBootTime.LedFlags);
  2040. #else
  2041. UNREFERENCED_PARAMETER(Status);
  2042. #endif // 0
  2043. if (IsKnownKeyboardType(pDeviceInfo->keyboard.Attr.KeyboardIdentifier.Type,
  2044. pDeviceInfo->keyboard.Attr.KeyboardIdentifier.Subtype)) {
  2045. USHORT NumberOfFunctionKeysSave = gKeyboardInfo.NumberOfFunctionKeys;
  2046. gKeyboardInfo = pDeviceInfo->keyboard.Attr;
  2047. /*
  2048. * Store the maximum number of function keys into gKeyboardInfo.
  2049. */
  2050. if (NumberOfFunctionKeysSave > gKeyboardInfo.NumberOfFunctionKeys) {
  2051. gKeyboardInfo.NumberOfFunctionKeys = NumberOfFunctionKeysSave;
  2052. }
  2053. } else {
  2054. RIPMSG3(RIP_WARNING, "ProcessDeviceChanges: kbd pDevInfo %p has bogus type/subtype=%x/%x",
  2055. pDeviceInfo,
  2056. pDeviceInfo->keyboard.Attr.KeyboardIdentifier.Type,
  2057. pDeviceInfo->keyboard.Attr.KeyboardIdentifier.Subtype);
  2058. }
  2059. if (pDeviceInfo->ustrName.Buffer) {
  2060. /*
  2061. * If this is a legit device, remember it so that we won't
  2062. * try to get other non PS/2 keyboard id/attr.
  2063. */
  2064. fKeyboardIdSet = TRUE;
  2065. }
  2066. }
  2067. }
  2068. nKeyboards++;
  2069. break;
  2070. #ifdef GENERIC_INPUT
  2071. case DEVICE_TYPE_HID:
  2072. ++nHid;
  2073. break;
  2074. #endif
  2075. default:
  2076. // Add code for a new type of input device here
  2077. RIPMSG2(RIP_ERROR, "pDeviceInfo %#p has strange type %d",
  2078. pDeviceInfo, pDeviceInfo->type);
  2079. break;
  2080. }
  2081. }
  2082. #ifdef GENERIC_INPUT
  2083. else if (pDeviceInfo->type == DEVICE_TYPE_HID) {
  2084. ++nHid;
  2085. TAGMSG1(DBGTAG_PNP, "ProcessDeviceChanges: HID DeviceInfo %p", pDeviceInfo);
  2086. }
  2087. #endif
  2088. /*
  2089. * Notify the PnP thread that a change has been completed
  2090. */
  2091. if (usOriginalActions & GDIAF_PNPWAITING) {
  2092. KeSetEvent(pDeviceInfo->pkeHidChangeCompleted, EVENT_INCREMENT, FALSE);
  2093. }
  2094. pDeviceInfo = pDeviceInfo->pNext;
  2095. }
  2096. ENDATOMICDEVICEINFOLISTCHECK();
  2097. LeaveDeviceInfoListCrit();
  2098. switch (DeviceType) {
  2099. case DEVICE_TYPE_MOUSE:
  2100. /*
  2101. * Apply summary information for Mice
  2102. */
  2103. if (nMice) {
  2104. if (gnMice == 0) {
  2105. /*
  2106. * We had no mouse before but we have one now: add a cursor
  2107. */
  2108. SET_GTERMF(GTERMF_MOUSE);
  2109. SYSMET(MOUSEPRESENT) = TRUE;
  2110. SetGlobalCursorLevel(0);
  2111. UserAssert(PpiFromProcess(gpepCSRSS)->ptiList->iCursorLevel == 0);
  2112. UserAssert(PpiFromProcess(gpepCSRSS)->ptiList->pq->iCursorLevel == 0);
  2113. GreMovePointer(gpDispInfo->hDev, gpsi->ptCursor.x, gpsi->ptCursor.y,
  2114. MP_PROCEDURAL);
  2115. }
  2116. } else {
  2117. if (gnMice != 0) {
  2118. /*
  2119. * We had a mouse before but we don't now: remove the cursor
  2120. */
  2121. CLEAR_GTERMF(GTERMF_MOUSE);
  2122. SYSMET(MOUSEPRESENT) = FALSE;
  2123. SetGlobalCursorLevel(-1);
  2124. /*
  2125. * Don't leave mouse buttons stuck down, clear the global button
  2126. * state here, otherwise weird stuff might happen.
  2127. * Also do this in Alt-Tab processing and zzzCancelJournalling.
  2128. */
  2129. #if DBG
  2130. if (gwMouseOwnerButton)
  2131. RIPMSG1(RIP_WARNING,
  2132. "gwMouseOwnerButton=%x, being cleared forcibly\n",
  2133. gwMouseOwnerButton);
  2134. #endif
  2135. gwMouseOwnerButton = 0;
  2136. }
  2137. }
  2138. /*
  2139. * Mouse button count represents the number of buttons on the mouse with
  2140. * the most buttons.
  2141. */
  2142. SYSMET(CMOUSEBUTTONS) = nMaxButtons;
  2143. SYSMET(MOUSEWHEELPRESENT) = (nWheels > 0);
  2144. gnMice = nMice;
  2145. break;
  2146. case DEVICE_TYPE_KEYBOARD:
  2147. /*
  2148. * Apply summary information for Keyboards
  2149. */
  2150. if (nKeyboards > gnKeyboards) {
  2151. /*
  2152. * We have more keyboards, let set their LEDs properly
  2153. */
  2154. UpdateKeyLights(FALSE);
  2155. /*
  2156. * The new keyboard arrived. Tell the RIT to set
  2157. * the repeat rate.
  2158. */
  2159. RequestKeyboardRateUpdate();
  2160. }
  2161. if ((nKeyboards != 0) && (gnKeyboards == 0)) {
  2162. /*
  2163. * We had no keyboard but we have one now: set the system hotkeys.
  2164. */
  2165. SetDebugHotKeys();
  2166. }
  2167. gnKeyboards = nKeyboards;
  2168. break;
  2169. #ifdef GENERIC_INPUT
  2170. case DEVICE_TYPE_HID:
  2171. gnHid = nHid;
  2172. break;
  2173. #endif
  2174. default:
  2175. break;
  2176. }
  2177. ENDATOMICCHECK();
  2178. }
  2179. /***************************************************************************\
  2180. * RequestDeviceChange()
  2181. *
  2182. * Flag the Device for the specified actions, then set its pkeHidChange to
  2183. * trigger the RIT to perform the actions.
  2184. * The current thread may not be able to do this if it is a PnP notification
  2185. * from another process.
  2186. *
  2187. * History:
  2188. * 01-20-99 IanJa Created.
  2189. \***************************************************************************/
  2190. VOID RequestDeviceChange(
  2191. PDEVICEINFO pDeviceInfo,
  2192. USHORT usAction,
  2193. BOOL fInDeviceInfoListCrit)
  2194. {
  2195. PDEVICE_TEMPLATE pDevTpl = &aDeviceTemplate[pDeviceInfo->type];
  2196. UserAssert(pDevTpl->pkeHidChange != NULL);
  2197. UserAssert((usAction & GDIAF_FREEME) == 0);
  2198. UserAssert((pDeviceInfo->usActions & GDIAF_PNPWAITING) == 0);
  2199. #if DBG
  2200. if (pDeviceInfo->usActions != 0) {
  2201. TAGMSG3(DBGTAG_PNP, "RequestDeviceChange(%#p, %x), but action %x pending",
  2202. pDeviceInfo, usAction, pDeviceInfo->usActions);
  2203. }
  2204. /*
  2205. * We can't ask for synchronized actions to be performed on the Device List
  2206. * if we are holding the Device List lock or the User Critical Section:
  2207. * ProcessDeviceChanges() requires both of these itself.
  2208. */
  2209. //if (usAction & GDIAF_PNPWAITING) {
  2210. // CheckDeviceInfoListCritOut();
  2211. // CheckCritOut();
  2212. //}
  2213. #endif
  2214. TAGMSG2(DBGTAG_PNP, "RequestDeviceChange(%p, %x)", pDeviceInfo, usAction);
  2215. /*
  2216. * Grab the DeviceInfoList critical section if we don't already have it
  2217. */
  2218. UserAssert(!fInDeviceInfoListCrit == !ExIsResourceAcquiredExclusiveLite(gpresDeviceInfoList));
  2219. #ifdef TRACK_PNP_NOTIFICATION
  2220. if (gfRecordPnpNotification) {
  2221. if (!fInDeviceInfoListCrit) {
  2222. EnterDeviceInfoListCrit();
  2223. }
  2224. RecordPnpNotification(PNP_NTF_REQUESTDEVICECHANGE, pDeviceInfo, usAction);
  2225. if (!fInDeviceInfoListCrit) {
  2226. LeaveDeviceInfoListCrit();
  2227. }
  2228. }
  2229. #endif
  2230. #ifdef GENERIC_INPUT
  2231. if (!fInDeviceInfoListCrit) {
  2232. EnterDeviceInfoListCrit();
  2233. }
  2234. CheckDeviceInfoListCritIn();
  2235. pDeviceInfo->usActions |= usAction;
  2236. if ((pDeviceInfo->usActions & (GDIAF_STARTREAD | GDIAF_STOPREAD)) == (GDIAF_STARTREAD | GDIAF_STOPREAD)) {
  2237. pDeviceInfo->usActions &= ~(GDIAF_STARTREAD | GDIAF_STOPREAD);
  2238. }
  2239. if (!fInDeviceInfoListCrit) {
  2240. LeaveDeviceInfoListCrit();
  2241. }
  2242. #else
  2243. if (fInDeviceInfoListCrit) {
  2244. CheckDeviceInfoListCritIn();
  2245. pDeviceInfo->usActions |= usAction;
  2246. } else {
  2247. EnterDeviceInfoListCrit();
  2248. pDeviceInfo->usActions |= usAction;
  2249. LeaveDeviceInfoListCrit();
  2250. }
  2251. #endif
  2252. if (usAction & GDIAF_PNPWAITING) {
  2253. CheckDeviceInfoListCritIn();
  2254. KeSetEvent(pDevTpl->pkeHidChange, EVENT_INCREMENT, FALSE);
  2255. LeaveDeviceInfoListCrit();
  2256. KeWaitForSingleObject(pDeviceInfo->pkeHidChangeCompleted, WrUserRequest, KernelMode, FALSE, NULL);
  2257. #ifdef GENERIC_INPUT
  2258. BESURE_IN_USERCRIT(pDeviceInfo->usActions & GDIAF_FREEME);
  2259. #endif
  2260. EnterDeviceInfoListCrit();
  2261. /*
  2262. * Assert that nothing else cleared GDIAF_PNPWAITING - only do it here.
  2263. * Check that the action we were waiting for actually occurred.
  2264. */
  2265. UserAssert(pDeviceInfo->usActions & GDIAF_PNPWAITING);
  2266. pDeviceInfo->usActions &= ~GDIAF_PNPWAITING;
  2267. UserAssert((pDeviceInfo->usActions & usAction) == 0);
  2268. if (pDeviceInfo->usActions & GDIAF_FREEME) {
  2269. FreeDeviceInfo(pDeviceInfo);
  2270. }
  2271. #ifdef GENERIC_INPUT
  2272. LeaveDeviceInfoListCrit();
  2273. END_IN_USERCRIT();
  2274. EnterDeviceInfoListCrit();
  2275. #endif
  2276. } else {
  2277. KeSetEvent(pDevTpl->pkeHidChange, EVENT_INCREMENT, FALSE);
  2278. }
  2279. }
  2280. /***************************************************************************\
  2281. * RemoveInputDevices()
  2282. *
  2283. * Used to detach input devices from a session. When disconnecting from a
  2284. * session that owns the local input devices we need to release them so that
  2285. * the new session that will take ownership of local console can use them
  2286. *
  2287. \***************************************************************************/
  2288. VOID RemoveInputDevices(
  2289. VOID)
  2290. {
  2291. PDEVICEINFO pDeviceInfo;
  2292. ULONG DeviceType;
  2293. NTSTATUS Status;
  2294. /*
  2295. * First Thing is to remove device class notification.
  2296. */
  2297. for (DeviceType = 0; DeviceType <= DEVICE_TYPE_MAX; DeviceType++) {
  2298. if (aDeviceClassNotificationEntry[DeviceType] != NULL) {
  2299. IoUnregisterPlugPlayNotification(aDeviceClassNotificationEntry[DeviceType]);
  2300. aDeviceClassNotificationEntry[DeviceType] = NULL;
  2301. }
  2302. }
  2303. /*
  2304. * Then walk the device liste detaching mice and keyboads.
  2305. */
  2306. EnterDeviceInfoListCrit();
  2307. PNP_SAFE_DEVICECRIT_IN();
  2308. pDeviceInfo = gpDeviceInfoList;
  2309. while (pDeviceInfo) {
  2310. #ifdef GENERIC_INPUT
  2311. if (pDeviceInfo->usActions & (GDIAF_DEPARTED | GDIAF_FREEME)) {
  2312. pDeviceInfo = pDeviceInfo->pNext;
  2313. continue;
  2314. }
  2315. #else
  2316. if ((pDeviceInfo->type != DEVICE_TYPE_KEYBOARD && pDeviceInfo->type != DEVICE_TYPE_MOUSE) ||
  2317. (pDeviceInfo->usActions & GDIAF_DEPARTED) ||
  2318. (pDeviceInfo->usActions & GDIAF_FREEME) ) {
  2319. pDeviceInfo = pDeviceInfo->pNext;
  2320. continue;
  2321. }
  2322. #endif
  2323. #ifdef PRERELEASE
  2324. pDeviceInfo->fForcedDetach = TRUE;
  2325. #endif
  2326. RequestDeviceChange(pDeviceInfo, GDIAF_DEPARTED, TRUE);
  2327. pDeviceInfo = gpDeviceInfoList;
  2328. }
  2329. LeaveDeviceInfoListCrit();
  2330. }
  2331. /***************************************************************************\
  2332. * AttachInputDevices
  2333. *
  2334. * Used to Attach input devices to a session.
  2335. *
  2336. \***************************************************************************/
  2337. BOOL AttachInputDevices(
  2338. BOOL bLocalDevices)
  2339. {
  2340. UNICODE_STRING ustrName;
  2341. BOOL fSuccess = TRUE;
  2342. if (!bLocalDevices) {
  2343. RtlInitUnicodeString(&ustrName, NULL);
  2344. fSuccess &= !!CreateDeviceInfo(DEVICE_TYPE_MOUSE, &ustrName, 0);
  2345. fSuccess &= !!CreateDeviceInfo(DEVICE_TYPE_KEYBOARD, &ustrName, 0);
  2346. if (!fSuccess) {
  2347. RIPMSG0(RIP_WARNING, "AttachInputDevices Failed the creation of input devices");
  2348. }
  2349. } else {
  2350. /*
  2351. * For local devices just register Device class notification and let
  2352. * PnP call us back.
  2353. */
  2354. xxxRegisterForDeviceClassNotifications();
  2355. }
  2356. return fSuccess;
  2357. }