Source code of Windows XP (NT5)
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.

2177 lines
55 KiB

  1. /*++
  2. Copyright (c) 1991 Microsoft Corporation
  3. Module Name:
  4. vdmints.c
  5. Abstract:
  6. Vdm kernel Virtual interrupt support
  7. Author:
  8. 13-Oct-1993 Jonathan Lew (Jonle)
  9. Notes:
  10. Revision History:
  11. --*/
  12. #include "vdmp.h"
  13. #include <ntos.h>
  14. #include <zwapi.h>
  15. //
  16. // Define thread priority boost for vdm hardware interrupt.
  17. //
  18. #define VDM_HWINT_INCREMENT EVENT_INCREMENT
  19. //
  20. // internal function prototypes
  21. //
  22. VOID
  23. VdmpQueueIntApcRoutine (
  24. IN PKAPC Apc,
  25. IN PKNORMAL_ROUTINE *NormalRoutine,
  26. IN PVOID *NormalContext,
  27. IN PVOID *SystemArgument1,
  28. IN PVOID *SystemArgument2
  29. );
  30. VOID
  31. VdmpQueueIntNormalRoutine (
  32. IN PVOID NormalContext,
  33. IN PVOID SystemArgument1,
  34. IN PVOID SystemArgument2
  35. );
  36. VOID
  37. VdmpDelayIntDpcRoutine (
  38. IN PKDPC Dpc,
  39. IN PVOID DeferredContext,
  40. IN PVOID SystemArgument1,
  41. IN PVOID SystemArgument2
  42. );
  43. VOID
  44. VdmpDelayIntApcRoutine (
  45. IN PKAPC Apc,
  46. IN PKNORMAL_ROUTINE *NormalRoutine,
  47. IN PVOID *NormalContext,
  48. IN PVOID *SystemArgument1,
  49. IN PVOID *SystemArgument2
  50. );
  51. int
  52. VdmpRestartDelayedInterrupts(
  53. PVDMICAUSERDATA pIcaUserData
  54. );
  55. int
  56. VdmpIcaScan(
  57. PVDMICAUSERDATA pIcaUserData,
  58. PVDMVIRTUALICA pIcaAdapter
  59. );
  60. int
  61. VdmpIcaAccept(
  62. PVDMICAUSERDATA pIcaUserData,
  63. PVDMVIRTUALICA pIcaAdapter
  64. );
  65. ULONG
  66. GetIretHookAddress(
  67. PKTRAP_FRAME TrapFrame,
  68. PVDMICAUSERDATA pIcaUserData,
  69. int IrqNum
  70. );
  71. VOID
  72. PushRmInterrupt(
  73. PKTRAP_FRAME TrapFrame,
  74. ULONG IretHookAddress,
  75. PVDM_TIB VdmTib,
  76. ULONG InterruptNumber
  77. );
  78. NTSTATUS
  79. PushPmInterrupt(
  80. PKTRAP_FRAME TrapFrame,
  81. ULONG IretHookAddress,
  82. PVDM_TIB VdmTib,
  83. ULONG InterruptNumber
  84. );
  85. VOID
  86. VdmpRundownRoutine (
  87. IN PKAPC Apc
  88. );
  89. int
  90. VdmpExceptionHandler(
  91. IN PEXCEPTION_POINTERS ExceptionInfo
  92. );
  93. #pragma alloc_text(PAGE, VdmpQueueIntNormalRoutine)
  94. #pragma alloc_text(PAGE, VdmDispatchInterrupts)
  95. #pragma alloc_text(PAGE, VdmpRestartDelayedInterrupts)
  96. #pragma alloc_text(PAGE, VdmpIcaScan)
  97. #pragma alloc_text(PAGE, VdmpIcaAccept)
  98. #pragma alloc_text(PAGE, GetIretHookAddress)
  99. #pragma alloc_text(PAGE, PushRmInterrupt)
  100. #pragma alloc_text(PAGE, PushPmInterrupt)
  101. #pragma alloc_text(PAGE, VdmpDispatchableIntPending)
  102. #pragma alloc_text(PAGE, VdmpIsThreadTerminating)
  103. #pragma alloc_text(PAGE, VdmpRundownRoutine)
  104. #pragma alloc_text(PAGE, VdmpExceptionHandler)
  105. extern POBJECT_TYPE ExSemaphoreObjectType;
  106. extern POBJECT_TYPE ExEventObjectType;
  107. #if DBG
  108. //
  109. // Make this variable nonzero to enable stricter ntvdm checking. Note this
  110. // cannot be left on by default because a malicious app can provoke the asserts.
  111. //
  112. ULONG VdmStrict;
  113. #endif
  114. NTSTATUS
  115. VdmpQueueInterrupt(
  116. IN HANDLE ThreadHandle
  117. )
  118. /*++
  119. Routine Description:
  120. Queues a user mode APC to the specifed application thread
  121. which will dispatch an interrupt.
  122. if APC is already queued to specified thread
  123. does nothing
  124. if APC is queued to the wrong thread
  125. dequeue it
  126. Reset the user APC for the specifed thread
  127. Insert the APC in the queue for the specifed thread
  128. Arguments:
  129. ThreadHandle - handle of thread to insert QueueIntApcRoutine
  130. Return Value:
  131. NTSTATUS.
  132. --*/
  133. {
  134. KIRQL OldIrql;
  135. PEPROCESS Process;
  136. PETHREAD Thread;
  137. NTSTATUS Status;
  138. PVDM_PROCESS_OBJECTS pVdmObjects;
  139. PAGED_CODE();
  140. Status = ObReferenceObjectByHandle(ThreadHandle,
  141. THREAD_QUERY_INFORMATION,
  142. PsThreadType,
  143. KeGetPreviousMode(),
  144. &Thread,
  145. NULL
  146. );
  147. if (!NT_SUCCESS(Status)) {
  148. return Status;
  149. }
  150. Process = PsGetCurrentProcess();
  151. if (Process != Thread->ThreadsProcess || Process->VdmObjects == NULL) {
  152. Status = STATUS_INVALID_PARAMETER_1;
  153. }
  154. else {
  155. //
  156. // Insert kernel APC.
  157. //
  158. // N.B. The delay interrupt lock is used to synchronize access to APC
  159. // objects that are manipulated by VDM.
  160. //
  161. pVdmObjects = Process->VdmObjects;
  162. ExAcquireSpinLock(&pVdmObjects->DelayIntSpinLock, &OldIrql);
  163. if (!KeVdmInsertQueueApc(&pVdmObjects->QueuedIntApc,
  164. &Thread->Tcb,
  165. KernelMode,
  166. VdmpQueueIntApcRoutine,
  167. VdmpRundownRoutine,
  168. VdmpQueueIntNormalRoutine, // normal routine
  169. (PVOID)KernelMode, // NormalContext
  170. 0))
  171. {
  172. Status = STATUS_UNSUCCESSFUL;
  173. }
  174. else {
  175. Status = STATUS_SUCCESS;
  176. }
  177. ExReleaseSpinLock(&pVdmObjects->DelayIntSpinLock, OldIrql);
  178. }
  179. ObDereferenceObject(Thread);
  180. return Status;
  181. }
  182. VOID
  183. VdmpQueueIntApcRoutine (
  184. IN PKAPC Apc,
  185. IN PKNORMAL_ROUTINE *NormalRoutine,
  186. IN PVOID *NormalContext,
  187. IN PVOID *SystemArgument1,
  188. IN PVOID *SystemArgument2
  189. )
  190. /*++
  191. Routine Description:
  192. Kernel and User mode Special Apc routine to dispatch virtual
  193. interrupts to the vdm.
  194. For KernelMode routine:
  195. if vdm is running in application mode
  196. queue a UserModeApc to the same thread
  197. else do nothing
  198. For UserMode routine
  199. if vdm is running in application mode dispatch virtual interrupts
  200. else do nothing
  201. Arguments:
  202. Apc - Supplies a pointer to the APC object used to invoke this routine.
  203. NormalRoutine - Supplies a pointer to a pointer to the normal routine
  204. function that was specified when the APC was initialized.
  205. NormalContext - Supplies a pointer to the processor mode
  206. specifying that this is a Kernel Mode or UserMode apc
  207. SystemArgument1 -
  208. SystemArgument2 - NOT USED
  209. Supplies a set of two pointers to two arguments that contain
  210. untyped data.
  211. Return Value:
  212. None.
  213. --*/
  214. {
  215. LONG VdmState;
  216. KIRQL OldIrql;
  217. PVDM_PROCESS_OBJECTS pVdmObjects;
  218. NTSTATUS Status;
  219. PETHREAD Thread;
  220. PKTRAP_FRAME TrapFrame;
  221. PVDM_TIB VdmTib;
  222. PAGED_CODE();
  223. UNREFERENCED_PARAMETER (SystemArgument1);
  224. UNREFERENCED_PARAMETER (SystemArgument2);
  225. //
  226. // Clear address of thread object in APC object.
  227. //
  228. // N.B. The delay interrupt lock is used to synchronize access to APC
  229. // objects that are manipulated by VDM.
  230. //
  231. pVdmObjects = PsGetCurrentProcess()->VdmObjects;
  232. ExAcquireSpinLock(&pVdmObjects->DelayIntSpinLock, &OldIrql);
  233. KeVdmClearApcThreadAddress(Apc);
  234. ExReleaseSpinLock(&pVdmObjects->DelayIntSpinLock, OldIrql);
  235. //
  236. // Get the trap frame for the current thread if it is not terminating.
  237. //
  238. Thread = PsGetCurrentThread();
  239. if (PsIsThreadTerminating(Thread)) {
  240. return;
  241. }
  242. TrapFrame = VdmGetTrapFrame(&Thread->Tcb);
  243. try {
  244. //
  245. // if no pending interrupts, ignore this APC.
  246. //
  247. if (!(*FIXED_NTVDMSTATE_LINEAR_PC_AT & VDM_INTERRUPT_PENDING)) {
  248. return;
  249. }
  250. if (VdmpDispatchableIntPending(TrapFrame->EFlags)) {
  251. //
  252. // if we are in v86 mode or segmented protected mode
  253. // then queue the UserMode Apc, which will dispatch
  254. // the hardware interrupt
  255. //
  256. if ((TrapFrame->EFlags & EFLAGS_V86_MASK) ||
  257. (TrapFrame->SegCs != (KGDT_R3_CODE | RPL_MASK))) {
  258. if (*(KPROCESSOR_MODE *)NormalContext == KernelMode) {
  259. //
  260. // Insert user APC.
  261. //
  262. // N.B. The delay interrupt lock is used to synchronize
  263. // access to APC objects that are manipulated by VDM.
  264. //
  265. VdmState = *FIXED_NTVDMSTATE_LINEAR_PC_AT;
  266. ExAcquireSpinLock(&pVdmObjects->DelayIntSpinLock,
  267. &OldIrql);
  268. KeVdmInsertQueueApc(&pVdmObjects->QueuedIntUserApc,
  269. &Thread->Tcb,
  270. UserMode,
  271. VdmpQueueIntApcRoutine,
  272. VdmpRundownRoutine,
  273. NULL, // normal routine
  274. (PVOID)UserMode, // NormalContext
  275. VdmState & VDM_INT_HARDWARE
  276. ? VDM_HWINT_INCREMENT : 0);
  277. ExReleaseSpinLock(&pVdmObjects->DelayIntSpinLock, OldIrql);
  278. }
  279. else {
  280. ASSERT(*NormalContext == (PVOID)UserMode);
  281. Status = VdmpGetVdmTib(&VdmTib);
  282. if (!NT_SUCCESS(Status)) {
  283. return;
  284. }
  285. //VdmTib = (PsGetCurrentProcess()->VdmObjects)->VdmTib;
  286. // VdmTib =
  287. // ((PVDM_PROCESS_OBJECTS)(PsGetCurrentProcess()->VdmObjects))->VdmTib;
  288. //
  289. // If there are no hardware ints, dispatch timer ints
  290. // else dispatch hw interrupts
  291. //
  292. if (*FIXED_NTVDMSTATE_LINEAR_PC_AT & VDM_INT_TIMER &&
  293. !(*FIXED_NTVDMSTATE_LINEAR_PC_AT & VDM_INT_HARDWARE))
  294. {
  295. VdmTib->EventInfo.Event = VdmIntAck;
  296. VdmTib->EventInfo.InstructionSize = 0;
  297. VdmTib->EventInfo.IntAckInfo = 0;
  298. VdmEndExecution(TrapFrame, VdmTib);
  299. }
  300. else {
  301. VdmDispatchInterrupts(TrapFrame, VdmTib);
  302. }
  303. }
  304. }
  305. else {
  306. //
  307. // If we are not in application mode and wow is all blocked
  308. // then Wake up WowExec by setting the wow idle event
  309. //
  310. if (*NormalRoutine && !(*FIXED_NTVDMSTATE_LINEAR_PC_AT & VDM_WOWBLOCKED)) {
  311. *NormalRoutine = NULL;
  312. }
  313. #if 0
  314. //
  315. // If we got here it's because:
  316. //
  317. // 1. interrupt is enabled by VdmCheckPMCliTimeStamp, the
  318. // vdmcontext EFlags may not reflect the interrupt state.
  319. // Because if the caller is not main thread, the vdmcontext
  320. // cannot be set.
  321. //
  322. // 2. EndExecution is called and trap frame is no longer
  323. // vdm context. We need to reflect the interrupt state
  324. // back to vdmcontext.
  325. //
  326. Status = VdmpGetVdmTib(&VdmTib);
  327. if (NT_SUCCESS(Status)) {
  328. VdmTib->VdmContext.EFlags |= EFLAGS_INTERRUPT_MASK;
  329. }
  330. #endif
  331. }
  332. }
  333. // WARNING this may set VIP for flat if VPI is ever set in CR4
  334. else if (((KeI386VirtualIntExtensions & V86_VIRTUAL_INT_EXTENSIONS) &&
  335. (TrapFrame->EFlags & EFLAGS_V86_MASK)) ||
  336. ((KeI386VirtualIntExtensions & PM_VIRTUAL_INT_EXTENSIONS) &&
  337. !(TrapFrame->EFlags & EFLAGS_V86_MASK))) {
  338. //
  339. // The CPU traps EVERY instruction if VIF and VIP are both ON.
  340. // Make sure that you set VIP ON only when there are pending
  341. // interrupts, i.e. (*FIXED_NTVDMSTATE_LINEAR_PC_AT & VDM_INTERRUPT_PENDING) != 0.
  342. //
  343. #if DBG
  344. if (VdmStrict) {
  345. ASSERT(*FIXED_NTVDMSTATE_LINEAR_PC_AT & VDM_INTERRUPT_PENDING);
  346. }
  347. #endif
  348. TrapFrame->EFlags |= EFLAGS_VIP;
  349. }
  350. }
  351. except(VdmpExceptionHandler(GetExceptionInformation())) {
  352. #if 0
  353. VdmDispatchException(TrapFrame,
  354. GetExceptionCode(),
  355. (PVOID)TrapFrame->Eip,
  356. 0,0,0,0 // no parameters
  357. );
  358. #endif
  359. }
  360. }
  361. VOID
  362. VdmpQueueIntNormalRoutine (
  363. IN PVOID NormalContext,
  364. IN PVOID SystemArgument1,
  365. IN PVOID SystemArgument2
  366. )
  367. /*++
  368. Routine Description:
  369. Arguments:
  370. Return Value:
  371. None.
  372. --*/
  373. {
  374. PETHREAD Thread;
  375. PKEVENT Event;
  376. NTSTATUS Status;
  377. PKTRAP_FRAME TrapFrame;
  378. PVDM_PROCESS_OBJECTS pVdmObjects;
  379. HANDLE CapturedHandle;
  380. UNREFERENCED_PARAMETER (NormalContext);
  381. UNREFERENCED_PARAMETER (SystemArgument1);
  382. UNREFERENCED_PARAMETER (SystemArgument2);
  383. //
  384. // Wake up WowExec by setting the wow idle event
  385. //
  386. pVdmObjects = PsGetCurrentProcess()->VdmObjects;
  387. try {
  388. CapturedHandle = *pVdmObjects->pIcaUserData->phWowIdleEvent;
  389. }
  390. except(VdmpExceptionHandler(GetExceptionInformation())) {
  391. Thread = PsGetCurrentThread();
  392. TrapFrame = VdmGetTrapFrame(&Thread->Tcb);
  393. #if 0
  394. VdmDispatchException(TrapFrame,
  395. GetExceptionCode(),
  396. (PVOID)TrapFrame->Eip,
  397. 0,0,0,0 // no parameters
  398. );
  399. #endif
  400. return;
  401. }
  402. Status = ObReferenceObjectByHandle (CapturedHandle,
  403. EVENT_MODIFY_STATE,
  404. ExEventObjectType,
  405. UserMode,
  406. &Event,
  407. NULL);
  408. if (NT_SUCCESS(Status)) {
  409. KeSetEvent(Event, EVENT_INCREMENT, FALSE);
  410. ObDereferenceObject(Event);
  411. }
  412. }
  413. VOID
  414. VdmRundownDpcs (
  415. IN PEPROCESS Process
  416. )
  417. {
  418. PVDM_PROCESS_OBJECTS pVdmObjects;
  419. PETHREAD Thread, MainThread;
  420. PDELAYINTIRQ pDelayIntIrq;
  421. KIRQL OldIrql;
  422. PLIST_ENTRY Next;
  423. pVdmObjects = Process->VdmObjects;
  424. //
  425. // Free up the DelayedIntList, canceling pending timers.
  426. //
  427. KeAcquireSpinLock (&pVdmObjects->DelayIntSpinLock, &OldIrql);
  428. Next = pVdmObjects->DelayIntListHead.Flink;
  429. while (Next != &pVdmObjects->DelayIntListHead) {
  430. pDelayIntIrq = CONTAINING_RECORD(Next, DELAYINTIRQ, DelayIntListEntry);
  431. Next = Next->Flink;
  432. if (KeCancelTimer (&pDelayIntIrq->Timer)) {
  433. Thread = pDelayIntIrq->Thread;
  434. pDelayIntIrq->Thread = NULL;
  435. if (Thread != NULL) {
  436. ObDereferenceObject (Thread);
  437. }
  438. MainThread = pDelayIntIrq->MainThread;
  439. pDelayIntIrq->MainThread = NULL;
  440. if (MainThread != NULL) {
  441. ObDereferenceObject (MainThread);
  442. }
  443. ObDereferenceObject (Process);
  444. }
  445. }
  446. if (pVdmObjects->MainThread != NULL) {
  447. ObDereferenceObject (pVdmObjects->MainThread);
  448. pVdmObjects->MainThread = NULL;
  449. }
  450. KeReleaseSpinLock (&pVdmObjects->DelayIntSpinLock, OldIrql);
  451. }
  452. NTSTATUS
  453. VdmDispatchInterrupts(
  454. PKTRAP_FRAME TrapFrame,
  455. PVDM_TIB VdmTib
  456. )
  457. /*++
  458. Routine Description:
  459. This routine dispatches interrupts to the vdm.
  460. Assumes that we are in application mode and NOT MONITOR context.
  461. This routine may switch from application context back to monitor
  462. context, if it cannot handle the interrupt (Ica in AEOI, or timer
  463. int pending).
  464. Arguments:
  465. TrapFrame address of current trapframe
  466. VdmTib address of current vdm tib
  467. Return Value:
  468. None.
  469. --*/
  470. {
  471. NTSTATUS Status;
  472. ULONG IretHookAddress;
  473. ULONG InterruptNumber;
  474. int IrqLineNum;
  475. USHORT IcaRotate = 0;
  476. PVDMICAUSERDATA pIcaUserData;
  477. PVDMVIRTUALICA pIcaAdapter;
  478. VDMEVENTCLASS VdmEvent = VdmMaxEvent;
  479. PAGED_CODE();
  480. pIcaUserData = ((PVDM_PROCESS_OBJECTS)PsGetCurrentProcess()->VdmObjects)->pIcaUserData;
  481. try {
  482. //
  483. // Probe pointers in IcaUserData which will be touched
  484. //
  485. ProbeForWrite(pIcaUserData->pAddrIretBopTable,
  486. (TrapFrame->EFlags & EFLAGS_V86_MASK)
  487. ? VDM_RM_IRETBOPSIZE*16 : VDM_PM_IRETBOPSIZE*16,
  488. sizeof(ULONG)
  489. );
  490. //
  491. // Take the Ica Lock, if this fails raise status as we can't
  492. // safely recover the critical section state
  493. //
  494. Status = VdmpEnterIcaLock(pIcaUserData->pIcaLock);
  495. if (!NT_SUCCESS(Status)) {
  496. ExRaiseStatus(Status);
  497. }
  498. if (*pIcaUserData->pUndelayIrq) {
  499. VdmpRestartDelayedInterrupts(pIcaUserData);
  500. }
  501. VDIretry:
  502. //
  503. // Clear the VIP bit
  504. //
  505. if (((KeI386VirtualIntExtensions & V86_VIRTUAL_INT_EXTENSIONS) &&
  506. (TrapFrame->EFlags & EFLAGS_V86_MASK)) ||
  507. ((KeI386VirtualIntExtensions & PM_VIRTUAL_INT_EXTENSIONS) &&
  508. !(TrapFrame->EFlags & EFLAGS_V86_MASK)) ) {
  509. TrapFrame->EFlags &= ~EFLAGS_VIP;
  510. }
  511. //
  512. // Mark the vdm state as hw int dispatched. Must use the lock as
  513. // kernel mode DelayedIntApcRoutine changes the bit as well
  514. //
  515. InterlockedAnd (FIXED_NTVDMSTATE_LINEAR_PC_AT, ~VDM_INT_HARDWARE);
  516. pIcaAdapter = pIcaUserData->pIcaMaster;
  517. IrqLineNum = VdmpIcaAccept(pIcaUserData, pIcaAdapter);
  518. if (IrqLineNum >= 0) {
  519. UCHAR bit = (UCHAR)(1 << IrqLineNum);
  520. if (pIcaUserData->pIcaMaster->ica_ssr & bit) {
  521. pIcaAdapter = pIcaUserData->pIcaSlave;
  522. IrqLineNum = VdmpIcaAccept(pIcaUserData, pIcaAdapter);
  523. if (IrqLineNum < 0) {
  524. pIcaUserData->pIcaMaster->ica_isr &= ~bit;
  525. }
  526. }
  527. }
  528. //
  529. // Skip spurious ints
  530. //
  531. if (IrqLineNum < 0) {
  532. //
  533. // Check for delayed interrupts which need to be restarted
  534. //
  535. if (*pIcaUserData->pUndelayIrq &&
  536. VdmpRestartDelayedInterrupts(pIcaUserData) != -1)
  537. {
  538. goto VDIretry;
  539. }
  540. Status = VdmpLeaveIcaLock(pIcaUserData->pIcaLock);
  541. if (!NT_SUCCESS(Status)) {
  542. ExRaiseStatus(Status);
  543. }
  544. return Status;
  545. }
  546. //
  547. // Capture the AutoEoi mode case for special handling
  548. //
  549. if (pIcaAdapter->ica_mode & ICA_AEOI) {
  550. VdmEvent = VdmIntAck;
  551. VdmTib->EventInfo.IntAckInfo = (ULONG)IcaRotate | VDMINTACK_AEOI;
  552. if (pIcaAdapter == pIcaUserData->pIcaSlave) {
  553. VdmTib->EventInfo.IntAckInfo |= VDMINTACK_SLAVE;
  554. }
  555. }
  556. InterruptNumber = IrqLineNum + pIcaAdapter->ica_base;
  557. //
  558. // Get the IretHookAddress ... if any
  559. //
  560. if (pIcaAdapter == pIcaUserData->pIcaSlave) {
  561. IrqLineNum += 8;
  562. }
  563. IretHookAddress = GetIretHookAddress( TrapFrame,
  564. pIcaUserData,
  565. IrqLineNum
  566. );
  567. if (*FIXED_NTVDMSTATE_LINEAR_PC_AT & VDM_TRACE_HISTORY) {
  568. VdmTraceEvent(VDMTR_KERNEL_HW_INT,
  569. (USHORT)InterruptNumber,
  570. 0,
  571. TrapFrame);
  572. }
  573. //
  574. // Push the interrupt frames
  575. //
  576. if (TrapFrame->EFlags & EFLAGS_V86_MASK) {
  577. PushRmInterrupt(TrapFrame,
  578. IretHookAddress,
  579. VdmTib,
  580. InterruptNumber
  581. );
  582. }
  583. else {
  584. Status = PushPmInterrupt(
  585. TrapFrame,
  586. IretHookAddress,
  587. VdmTib,
  588. InterruptNumber
  589. );
  590. if (!NT_SUCCESS(Status)) {
  591. VdmpLeaveIcaLock(pIcaUserData->pIcaLock);
  592. ExRaiseStatus(Status);
  593. }
  594. }
  595. //
  596. // Disable interrupts and the trap flag
  597. //
  598. if (((KeI386VirtualIntExtensions & V86_VIRTUAL_INT_EXTENSIONS) &&
  599. (TrapFrame->EFlags & EFLAGS_V86_MASK)) ||
  600. ((KeI386VirtualIntExtensions & PM_VIRTUAL_INT_EXTENSIONS) &&
  601. !(TrapFrame->EFlags & EFLAGS_V86_MASK)) )
  602. {
  603. TrapFrame->EFlags &= ~EFLAGS_VIF;
  604. }
  605. else if (!KeI386VdmIoplAllowed ||
  606. !(TrapFrame->EFlags & EFLAGS_V86_MASK))
  607. {
  608. *FIXED_NTVDMSTATE_LINEAR_PC_AT &= ~VDM_VIRTUAL_INTERRUPTS;
  609. }
  610. else {
  611. TrapFrame->EFlags &= ~EFLAGS_INTERRUPT_MASK;
  612. }
  613. TrapFrame->EFlags &= ~(EFLAGS_NT_MASK | EFLAGS_TF_MASK);
  614. KeBoostPriorityThread(KeGetCurrentThread(), VDM_HWINT_INCREMENT);
  615. //
  616. // Release the ica lock
  617. //
  618. Status = VdmpLeaveIcaLock(pIcaUserData->pIcaLock);
  619. if (!NT_SUCCESS(Status)) {
  620. ExRaiseStatus(Status);
  621. }
  622. //
  623. // check to see if we are supposed to switch back to monitor context
  624. //
  625. if (VdmEvent != VdmMaxEvent) {
  626. VdmTib->EventInfo.Event = VdmIntAck;
  627. VdmTib->EventInfo.InstructionSize = 0;
  628. VdmEndExecution(TrapFrame, VdmTib);
  629. }
  630. }
  631. except(VdmpExceptionHandler(GetExceptionInformation())) {
  632. Status = GetExceptionCode();
  633. #if 0
  634. VdmDispatchException(TrapFrame,
  635. Status,
  636. (PVOID)TrapFrame->Eip,
  637. 0,0,0,0 // no parameters
  638. );
  639. #endif
  640. }
  641. return Status;
  642. }
  643. int
  644. VdmpRestartDelayedInterrupts(
  645. PVDMICAUSERDATA pIcaUserData
  646. )
  647. {
  648. int line;
  649. PAGED_CODE();
  650. try {
  651. *pIcaUserData->pUndelayIrq = 0;
  652. line = VdmpIcaScan(pIcaUserData, pIcaUserData->pIcaSlave);
  653. if (line != -1) {
  654. // set the slave
  655. pIcaUserData->pIcaSlave->ica_int_line = line;
  656. pIcaUserData->pIcaSlave->ica_cpu_int = TRUE;
  657. // set the master cascade
  658. line = pIcaUserData->pIcaSlave->ica_ssr;
  659. pIcaUserData->pIcaMaster->ica_irr |= 1 << line;
  660. pIcaUserData->pIcaMaster->ica_count[line]++;
  661. }
  662. line = VdmpIcaScan(pIcaUserData, pIcaUserData->pIcaMaster);
  663. if (line != -1) {
  664. pIcaUserData->pIcaMaster->ica_cpu_int = TRUE;
  665. pIcaUserData->pIcaMaster->ica_int_line = TRUE;
  666. }
  667. }
  668. except(EXCEPTION_EXECUTE_HANDLER) {
  669. line = -1;
  670. NOTHING;
  671. }
  672. return line;
  673. }
  674. int
  675. VdmpIcaScan(
  676. PVDMICAUSERDATA pIcaUserData,
  677. PVDMVIRTUALICA pIcaAdapter
  678. )
  679. /*++
  680. Routine Description:
  681. Similar to softpc\base\system\ica.c - scan_irr(),
  682. Check the IRR, the IMR and the ISR to determine which interrupt
  683. should be delivered.
  684. A bit set in the IRR will generate an interrupt if:
  685. IMR bit, DelayIret bit, DelayIrq bit AND ISR higher priority bits
  686. are clear (unless Special Mask Mode, in which case ISR is ignored)
  687. If there is no bit set, then return -1
  688. Arguments:
  689. PVDMICAUSERDATA pIcaUserData - addr of ica userdata
  690. PVDMVIRTUALICA pIcaAdapter - addr of ica adapter
  691. Return Value:
  692. int IrqLineNum for the specific adapter (0 to 7)
  693. -1 for none
  694. --*/
  695. {
  696. int i,line;
  697. UCHAR bit;
  698. ULONG IrrImrDelay;
  699. ULONG ActiveIsr;
  700. PAGED_CODE();
  701. IrrImrDelay = *pIcaUserData->pDelayIrq | *pIcaUserData->pDelayIret;
  702. if (pIcaAdapter == pIcaUserData->pIcaSlave) {
  703. IrrImrDelay >>= 8;
  704. }
  705. IrrImrDelay = pIcaAdapter->ica_irr & ~(pIcaAdapter->ica_imr | (UCHAR)IrrImrDelay);
  706. if (IrrImrDelay) {
  707. /*
  708. * Does the current mode require the ica to prevent
  709. * interrupts if that line is still active (ie in the isr)?
  710. *
  711. * Normal Case: Used by DOS and Win3.1/S the isr prevents interrupts.
  712. * Special Mask Mode, Special Fully Nested Mode do not block
  713. * interrupts using bits in the isr. SMM is the mode used
  714. * by Windows95 and Win3.1/E.
  715. *
  716. */
  717. ActiveIsr = (pIcaAdapter->ica_mode & (ICA_SMM|ICA_SFNM))
  718. ? 0 : pIcaAdapter->ica_isr;
  719. for(i = 0; i < 8; i++) {
  720. line = (pIcaAdapter->ica_hipri + i) & 7;
  721. bit = (UCHAR) (1 << line);
  722. if (ActiveIsr & bit) {
  723. break; /* No nested interrupt possible */
  724. }
  725. if (IrrImrDelay & bit) {
  726. return line;
  727. }
  728. }
  729. }
  730. return -1;
  731. }
  732. int
  733. VdmpIcaAccept(
  734. PVDMICAUSERDATA pIcaUserData,
  735. PVDMVIRTUALICA pIcaAdapter
  736. )
  737. /*++
  738. Routine Description:
  739. Does the equivalent of a cpu IntAck cycle retrieving the Irql Line Num
  740. for interrupt dispatch, and setting the ica state to reflect that
  741. the interrupt is in service.
  742. Similar to softpc\base\system\ica.c - ica_accept() scan_irr(),
  743. except that this code rejects interrupt dispatching if the ica
  744. is in Auto-EOI as this may involve a new interrupt cycle, and
  745. eoi hooks to be activated.
  746. Arguments:
  747. PVDMICAUSERDATA pIcaUserData - addr of ica userdata
  748. PVDMVIRTUALICA pIcaAdapter - addr of ica adapter
  749. Return Value:
  750. ULONG IrqLineNum for the specific adapter (0 to 7)
  751. returns -1 if there are no interrupts to generate (spurious ints
  752. are normally done on line 7
  753. --*/
  754. {
  755. int line;
  756. UCHAR bit;
  757. PAGED_CODE();
  758. //
  759. // Drop the INT line, and scan the ica
  760. //
  761. pIcaAdapter->ica_cpu_int = FALSE;
  762. try {
  763. line = VdmpIcaScan(pIcaUserData, pIcaAdapter);
  764. } except (EXCEPTION_EXECUTE_HANDLER) {
  765. return -1;
  766. }
  767. if (line < 0) {
  768. return -1;
  769. }
  770. bit = (UCHAR)(1 << line);
  771. pIcaAdapter->ica_isr |= bit;
  772. //
  773. // decrement the count and clear the IRR bit
  774. // ensure the count doesn't wrap past zero.
  775. //
  776. if (--(pIcaAdapter->ica_count[line]) <= 0) {
  777. pIcaAdapter->ica_irr &= ~bit;
  778. pIcaAdapter->ica_count[line] = 0;
  779. }
  780. return line;
  781. }
  782. ULONG
  783. GetIretHookAddress(
  784. PKTRAP_FRAME TrapFrame,
  785. PVDMICAUSERDATA pIcaUserData,
  786. int IrqNum
  787. )
  788. /*++
  789. Routine Description:
  790. Retrieves the IretHookAddress from the real mode\protect mode
  791. iret hook bop table. This function is equivalent to
  792. softpc\base\system\ica.c - ica_iret_hook_needed()
  793. Arguments:
  794. TrapFrame - address of current trapframe
  795. pIcaUserData - addr of ica data
  796. IrqNum - IrqLineNum
  797. Return Value:
  798. ULONG IretHookAddress. seg:offset or sel:offset Iret Hook,
  799. 0 if none
  800. --*/
  801. {
  802. ULONG IrqMask;
  803. ULONG AddrBopTable;
  804. int IretBopSize;
  805. PAGED_CODE();
  806. IrqMask = 1 << IrqNum;
  807. if (!(IrqMask & *pIcaUserData->pIretHooked) ||
  808. !*pIcaUserData->pAddrIretBopTable )
  809. {
  810. return 0;
  811. }
  812. if (TrapFrame->EFlags & EFLAGS_V86_MASK) {
  813. AddrBopTable = *pIcaUserData->pAddrIretBopTable;
  814. IretBopSize = VDM_RM_IRETBOPSIZE;
  815. }
  816. else {
  817. AddrBopTable = (VDM_PM_IRETBOPSEG << 16) | VDM_PM_IRETBOPOFF;
  818. IretBopSize = VDM_PM_IRETBOPSIZE;
  819. }
  820. *pIcaUserData->pDelayIret |= IrqMask;
  821. return AddrBopTable + IretBopSize * IrqNum;
  822. }
  823. VOID
  824. PushRmInterrupt(
  825. PKTRAP_FRAME TrapFrame,
  826. ULONG IretHookAddress,
  827. PVDM_TIB VdmTib,
  828. ULONG InterruptNumber
  829. )
  830. /*++
  831. Routine Description:
  832. Pushes RealMode interrupt frame onto the UserMode stack in the TrapFrame
  833. Arguments:
  834. TrapFrame - address of current trapframe
  835. IretHookAddress - address of Iret Hook, 0 if none
  836. VdmTib - address of current vdm tib
  837. InterruptNumber - interrupt number to reflect
  838. Return Value:
  839. None.
  840. --*/
  841. {
  842. ULONG UserSS;
  843. USHORT UserSP;
  844. USHORT NewCS;
  845. USHORT NewIP;
  846. PAGED_CODE();
  847. //
  848. // Get pointers to current stack
  849. //
  850. UserSS = TrapFrame->HardwareSegSs << 4;
  851. UserSP = (USHORT) TrapFrame->HardwareEsp;
  852. //
  853. // load interrupt stack frame, pushing flags, Cs and ip
  854. //
  855. UserSP -= 2;
  856. *(PUSHORT)(UserSS + UserSP) = (USHORT)TrapFrame->EFlags;
  857. UserSP -= 2;
  858. *(PUSHORT)(UserSS + UserSP) = (USHORT)TrapFrame->SegCs;
  859. UserSP -= 2;
  860. *(PUSHORT)(UserSS + UserSP) = (USHORT)TrapFrame->Eip;
  861. //
  862. // load IretHook stack frame if one exists
  863. //
  864. if (IretHookAddress) {
  865. UserSP -= 2;
  866. *(PUSHORT)(UserSS + UserSP) = (USHORT)(TrapFrame->EFlags & ~EFLAGS_TF_MASK);
  867. UserSP -= 2;
  868. *(PUSHORT)(UserSS + UserSP) = (USHORT)(IretHookAddress >> 16);
  869. UserSP -= 2;
  870. *(PUSHORT)(UserSS + UserSP) = (USHORT)IretHookAddress;
  871. }
  872. //
  873. // Set new sp, ip, and cs.
  874. //
  875. if ((VdmTib->VdmInterruptTable)[InterruptNumber].Flags & VDM_INT_HOOKED) {
  876. NewCS = (USHORT) (VdmTib->DpmiInfo.DosxRmReflector >> 16);
  877. NewIP = (USHORT) VdmTib->DpmiInfo.DosxRmReflector;
  878. //
  879. // now encode the interrupt number into CS
  880. //
  881. NewCS = (USHORT) (NewCS - InterruptNumber);
  882. NewIP = (USHORT) (NewIP + (InterruptNumber*16));
  883. } else {
  884. PUSHORT pIvtEntry = (PUSHORT) (InterruptNumber * 4);
  885. NewIP = *pIvtEntry++;
  886. NewCS = *pIvtEntry;
  887. }
  888. TrapFrame->HardwareEsp = UserSP;
  889. TrapFrame->Eip = NewIP;
  890. TrapFrame->SegCs = NewCS;
  891. }
  892. NTSTATUS
  893. PushPmInterrupt(
  894. PKTRAP_FRAME TrapFrame,
  895. ULONG IretHookAddress,
  896. PVDM_TIB VdmTib,
  897. ULONG InterruptNumber
  898. )
  899. /*++
  900. Routine Description:
  901. Pushes ProtectMode interrupt frame onto the UserMode stack in the TrapFrame
  902. Raises an exception if an invalid stack is found
  903. Arguments:
  904. TrapFrame - address of current trapframe
  905. IretHookAddress - address of Iret Hook, 0 if none
  906. VdmTib - address of current vdm tib
  907. InterruptNumber - interrupt number to reflect
  908. Return Value:
  909. None.
  910. --*/
  911. {
  912. ULONG Flags,Base,Limit;
  913. ULONG VdmSp, VdmSpOrg;
  914. PUSHORT VdmStackPointer;
  915. BOOLEAN Frame32 = (BOOLEAN) VdmTib->DpmiInfo.Flags;
  916. PAGED_CODE();
  917. //
  918. // Switch to "locked" dpmi stack if lock count is zero
  919. // This emulates the win3.1 Begin_Use_Locked_PM_Stack function.
  920. //
  921. if (!VdmTib->DpmiInfo.LockCount++) {
  922. VdmTib->DpmiInfo.SaveEsp = TrapFrame->HardwareEsp;
  923. VdmTib->DpmiInfo.SaveEip = TrapFrame->Eip;
  924. VdmTib->DpmiInfo.SaveSsSelector = (USHORT) TrapFrame->HardwareSegSs;
  925. TrapFrame->HardwareEsp = 0x1000;
  926. TrapFrame->HardwareSegSs = (ULONG) VdmTib->DpmiInfo.SsSelector | 0x7;
  927. }
  928. //
  929. // Use Sp or Esp ?
  930. //
  931. if (!Ki386GetSelectorParameters((USHORT)TrapFrame->HardwareSegSs,
  932. &Flags, &Base, &Limit))
  933. {
  934. return STATUS_ACCESS_VIOLATION;
  935. }
  936. //
  937. // Adjust the limit for page granularity
  938. //
  939. if (Flags & SEL_TYPE_2GIG) {
  940. Limit = (Limit << 12) | 0xfff;
  941. }
  942. if (Limit != 0xffffffff) Limit++;
  943. VdmSp = (Flags & SEL_TYPE_BIG) ? TrapFrame->HardwareEsp
  944. : (USHORT)TrapFrame->HardwareEsp;
  945. //
  946. // Get pointer to current stack
  947. //
  948. VdmStackPointer = (PUSHORT)(Base + VdmSp);
  949. //
  950. // Create enough room for iret hook frame
  951. //
  952. VdmSpOrg = VdmSp;
  953. if (IretHookAddress) {
  954. if (Frame32) {
  955. VdmSp -= 3*sizeof(ULONG);
  956. } else {
  957. VdmSp -= 3*sizeof(USHORT);
  958. }
  959. }
  960. //
  961. // Create enough room for 2 iret frames
  962. //
  963. if (Frame32) {
  964. VdmSp -= 6*sizeof(ULONG);
  965. } else {
  966. VdmSp -= 6*sizeof(USHORT);
  967. }
  968. //
  969. // Set Final Value of Sp\Esp, do this before checking stack
  970. // limits so that invalid esp is visible to debuggers
  971. //
  972. if (Flags & SEL_TYPE_BIG) {
  973. TrapFrame->HardwareEsp = VdmSp;
  974. }
  975. else {
  976. TrapFrame->HardwareEsp = (USHORT)VdmSp;
  977. }
  978. //
  979. // Check stack limits
  980. // If any of the following conditions are TRUE
  981. // - New stack pointer wraps (not enuf space)
  982. // - If normal stack and Sp not below limit
  983. // - If Expand Down stack and Sp not above limit
  984. //
  985. // Then raise a Stack Fault
  986. //
  987. if ( VdmSp >= VdmSpOrg ||
  988. !(Flags & SEL_TYPE_ED) && VdmSpOrg > Limit ||
  989. (Flags & SEL_TYPE_ED) && VdmSp < Limit )
  990. {
  991. return STATUS_ACCESS_VIOLATION;
  992. }
  993. //
  994. // Build the Hw Int iret frame
  995. //
  996. if (Frame32) {
  997. *(--(PULONG)VdmStackPointer) = TrapFrame->EFlags;
  998. *(PUSHORT)(--(PULONG)VdmStackPointer) = (USHORT)TrapFrame->SegCs;
  999. *(--(PULONG)VdmStackPointer) = TrapFrame->Eip;
  1000. *(--(PULONG)VdmStackPointer) = TrapFrame->EFlags & ~EFLAGS_TF_MASK;
  1001. *(--(PULONG)VdmStackPointer) = VdmTib->DpmiInfo.DosxIntIretD >> 16;
  1002. *(--(PULONG)VdmStackPointer) = VdmTib->DpmiInfo.DosxIntIretD & 0xffff;
  1003. } else {
  1004. *(--(PUSHORT)VdmStackPointer) = (USHORT)TrapFrame->EFlags;
  1005. *(--(PUSHORT)VdmStackPointer) = (USHORT)TrapFrame->SegCs;
  1006. *(--(PUSHORT)VdmStackPointer) = (USHORT)TrapFrame->Eip;
  1007. *(--(PUSHORT)VdmStackPointer) = (USHORT)(TrapFrame->EFlags & ~EFLAGS_TF_MASK);
  1008. *(--(PULONG)VdmStackPointer) = VdmTib->DpmiInfo.DosxIntIret;
  1009. }
  1010. //
  1011. // Point cs and ip at interrupt handler
  1012. //
  1013. TrapFrame->SegCs = (VdmTib->VdmInterruptTable)[InterruptNumber].CsSelector | 0x7;
  1014. TrapFrame->Eip = (VdmTib->VdmInterruptTable)[InterruptNumber].Eip;
  1015. //
  1016. // Turn off trace bit so we don't trace the iret hook
  1017. //
  1018. TrapFrame->EFlags &= ~EFLAGS_TF_MASK;
  1019. //
  1020. // Build the Irethook Iret frame, if one exists
  1021. //
  1022. if (IretHookAddress) {
  1023. ULONG SegCs, Eip;
  1024. //
  1025. // Point cs and eip at the iret hook, so when we build
  1026. // the frame below, the correct contents are set
  1027. //
  1028. SegCs = IretHookAddress >> 16;
  1029. Eip = IretHookAddress & 0xFFFF;
  1030. if (Frame32) {
  1031. *(--(PULONG)VdmStackPointer) = TrapFrame->EFlags;
  1032. *(PUSHORT)(--(PULONG)VdmStackPointer) = (USHORT)SegCs;
  1033. *(--(PULONG)VdmStackPointer) = Eip;
  1034. } else {
  1035. *(--(PUSHORT)VdmStackPointer) = (USHORT)TrapFrame->EFlags;
  1036. *(--(PUSHORT)VdmStackPointer) = (USHORT)SegCs;
  1037. *(--(PUSHORT)VdmStackPointer) = (USHORT)Eip;
  1038. }
  1039. }
  1040. return STATUS_SUCCESS;
  1041. }
  1042. NTSTATUS
  1043. VdmpDelayInterrupt (
  1044. PVDMDELAYINTSDATA pdsd
  1045. )
  1046. /*++
  1047. Routine Description:
  1048. Sets a timer to dispatch the delayed interrupt through KeSetTimer.
  1049. When the timer fires a user mode APC is queued to queue the interrupt.
  1050. This function uses lazy allocation routines to allocate internal
  1051. data structures (nonpaged pool) on a per Irq basis, and needs to
  1052. be notified when specific Irq Lines no longer need Delayed
  1053. Interrupt services.
  1054. The caller must own the IcaLock to synchronize access to the
  1055. Irq lists.
  1056. WARNING: - Until the Delayed interrupt fires or is cancelled,
  1057. the specific Irq line will not generate any interrupts.
  1058. - The APC routine, does not take the HostIca lock, when
  1059. unblocking the IrqLine. Devices which use delayed Interrupts
  1060. should not queue ANY additional interrupts for the same IRQ
  1061. line until the delayed interrupt has fired or been cancelled.
  1062. Arguments:
  1063. pdsd.Delay Delay Interval in usecs
  1064. if Delay is 0xFFFFFFFF then per Irq Line nonpaged
  1065. data structures are freed. No Timers are set.
  1066. else the Delay is used as the timer delay.
  1067. pdsd.DelayIrqLine IrqLine Number
  1068. pdsd.hThread Thread Handle of CurrentMonitorTeb
  1069. Return Value:
  1070. NTSTATUS.
  1071. --*/
  1072. {
  1073. VDMDELAYINTSDATA Capturedpdsd;
  1074. PVDM_PROCESS_OBJECTS pVdmObjects;
  1075. PLIST_ENTRY Next;
  1076. PEPROCESS Process;
  1077. PDELAYINTIRQ pDelayIntIrq;
  1078. PDELAYINTIRQ NewIrq;
  1079. PETHREAD Thread, MainThread;
  1080. NTSTATUS Status;
  1081. KIRQL OldIrql;
  1082. ULONG IrqLine;
  1083. ULONG Delay;
  1084. PULONG pDelayIrq;
  1085. PULONG pUndelayIrq;
  1086. LARGE_INTEGER liDelay;
  1087. LOGICAL FreeIrqLine;
  1088. LOGICAL AlreadyInUse;
  1089. //
  1090. // Get a pointer to pVdmObjects
  1091. //
  1092. Process = PsGetCurrentProcess();
  1093. pVdmObjects = Process->VdmObjects;
  1094. if (pVdmObjects == NULL) {
  1095. return STATUS_INVALID_PARAMETER_1;
  1096. }
  1097. Status = STATUS_SUCCESS;
  1098. Thread = MainThread = NULL;
  1099. FreeIrqLine = TRUE;
  1100. AlreadyInUse = FALSE;
  1101. try {
  1102. //
  1103. // Probe the parameters
  1104. //
  1105. ProbeForRead(pdsd, sizeof(VDMDELAYINTSDATA), sizeof(ULONG));
  1106. RtlCopyMemory (&Capturedpdsd, pdsd, sizeof (VDMDELAYINTSDATA));
  1107. } except(EXCEPTION_EXECUTE_HANDLER) {
  1108. return GetExceptionCode();
  1109. }
  1110. //
  1111. // Form a BitMask for the IrqLine Number
  1112. //
  1113. IrqLine = 1 << Capturedpdsd.DelayIrqLine;
  1114. if (!IrqLine) {
  1115. return STATUS_INVALID_PARAMETER_2;
  1116. }
  1117. ExAcquireFastMutex(&pVdmObjects->DelayIntFastMutex);
  1118. pDelayIrq = pVdmObjects->pIcaUserData->pDelayIrq;
  1119. pUndelayIrq = pVdmObjects->pIcaUserData->pUndelayIrq;
  1120. try {
  1121. ProbeForWriteUlong(pDelayIrq);
  1122. ProbeForWriteUlong(pUndelayIrq);
  1123. } except(EXCEPTION_EXECUTE_HANDLER) {
  1124. ExReleaseFastMutex(&pVdmObjects->DelayIntFastMutex);
  1125. return GetExceptionCode();
  1126. }
  1127. //
  1128. // Convert the Delay parameter into hundredths of nanosecs
  1129. //
  1130. Delay = Capturedpdsd.Delay;
  1131. //
  1132. // Check to see if we need to reset the timer resolution
  1133. //
  1134. if (Delay == 0xFFFFFFFF) {
  1135. ZwSetTimerResolution(KeMaximumIncrement, FALSE, &Delay);
  1136. NewIrq = NULL;
  1137. goto FindIrq;
  1138. }
  1139. FreeIrqLine = FALSE;
  1140. //
  1141. // Convert delay to hundreths of nanosecs
  1142. // and ensure min delay of 1 msec
  1143. //
  1144. Delay = Delay < 1000 ? 10000 : Delay * 10;
  1145. //
  1146. // If the delay time is close to the system's clock rate
  1147. // then adjust the system's clock rate and if needed
  1148. // the delay time so that the timer will fire before the
  1149. // the due time.
  1150. //
  1151. if (Delay < 150000) {
  1152. ULONG ul = Delay >> 1;
  1153. if (ul < KeTimeIncrement && KeTimeIncrement > KeMinimumIncrement) {
  1154. ZwSetTimerResolution(ul, TRUE, (PULONG)&liDelay.LowPart);
  1155. }
  1156. if (Delay < KeTimeIncrement) {
  1157. // can't set system clock rate low enuf, so use half delay
  1158. Delay >>= 1;
  1159. }
  1160. else if (Delay < (KeTimeIncrement << 1)) {
  1161. // Real close to the system clock rate, lower delay
  1162. // proportionally, to avoid missing clock cycles.
  1163. Delay -= KeTimeIncrement >> 1;
  1164. }
  1165. }
  1166. //
  1167. // Reference the Target Thread
  1168. //
  1169. Status = ObReferenceObjectByHandle (Capturedpdsd.hThread,
  1170. THREAD_QUERY_INFORMATION,
  1171. PsThreadType,
  1172. KeGetPreviousMode(),
  1173. &Thread,
  1174. NULL);
  1175. if (!NT_SUCCESS(Status)) {
  1176. ExReleaseFastMutex(&pVdmObjects->DelayIntFastMutex);
  1177. return Status;
  1178. }
  1179. MainThread = pVdmObjects->MainThread;
  1180. ObReferenceObject (MainThread);
  1181. NewIrq = NULL;
  1182. FindIrq:
  1183. ExAcquireSpinLock(&pVdmObjects->DelayIntSpinLock, &OldIrql);
  1184. //
  1185. // Search the DelayedIntList for a matching Irq Line.
  1186. //
  1187. Next = pVdmObjects->DelayIntListHead.Flink;
  1188. while (Next != &pVdmObjects->DelayIntListHead) {
  1189. pDelayIntIrq = CONTAINING_RECORD(Next, DELAYINTIRQ, DelayIntListEntry);
  1190. if (pDelayIntIrq->IrqLine == IrqLine) {
  1191. break;
  1192. }
  1193. Next = Next->Flink;
  1194. }
  1195. if (Next == &pVdmObjects->DelayIntListHead) {
  1196. pDelayIntIrq = NULL;
  1197. if (FreeIrqLine) {
  1198. goto VidExit;
  1199. }
  1200. if (NewIrq == NULL) {
  1201. ExReleaseSpinLock(&pVdmObjects->DelayIntSpinLock, OldIrql);
  1202. //
  1203. // If a DelayIntIrq does not exist for this irql, allocate one
  1204. // from nonpaged pool and initialize it
  1205. //
  1206. NewIrq = ExAllocatePoolWithTag (NonPagedPool,
  1207. sizeof(DELAYINTIRQ),
  1208. ' MDV');
  1209. if (!NewIrq) {
  1210. Status = STATUS_NO_MEMORY;
  1211. AlreadyInUse = TRUE;
  1212. goto VidExit2;
  1213. }
  1214. try {
  1215. PsChargePoolQuota(Process, NonPagedPool, sizeof(DELAYINTIRQ));
  1216. }
  1217. except(EXCEPTION_EXECUTE_HANDLER) {
  1218. Status = GetExceptionCode();
  1219. ExFreePool(NewIrq);
  1220. AlreadyInUse = TRUE;
  1221. goto VidExit2;
  1222. }
  1223. RtlZeroMemory(NewIrq, sizeof(DELAYINTIRQ));
  1224. NewIrq->IrqLine = IrqLine;
  1225. KeInitializeTimer(&NewIrq->Timer);
  1226. KeInitializeDpc(&NewIrq->Dpc,
  1227. VdmpDelayIntDpcRoutine,
  1228. Process);
  1229. goto FindIrq;
  1230. }
  1231. InsertTailList (&pVdmObjects->DelayIntListHead,
  1232. &NewIrq->DelayIntListEntry);
  1233. pDelayIntIrq = NewIrq;
  1234. }
  1235. else if (NewIrq != NULL) {
  1236. ExFreePool (NewIrq);
  1237. PsReturnPoolQuota (Process, NonPagedPool, sizeof(DELAYINTIRQ));
  1238. }
  1239. if (Delay == 0xFFFFFFFF) {
  1240. if (pDelayIntIrq->InUse == VDMDELAY_KTIMER) {
  1241. pDelayIntIrq->InUse = VDMDELAY_NOTINUSE;
  1242. pDelayIntIrq = NULL;
  1243. }
  1244. }
  1245. else if (pDelayIntIrq->InUse == VDMDELAY_NOTINUSE) {
  1246. liDelay = RtlEnlargedIntegerMultiply(Delay, -1);
  1247. if (KeSetTimerEx (&pDelayIntIrq->Timer, liDelay, 0, &pDelayIntIrq->Dpc) == FALSE) {
  1248. ObReferenceObject(Process);
  1249. }
  1250. }
  1251. VidExit:
  1252. if (pDelayIntIrq && !pDelayIntIrq->InUse) {
  1253. if (NT_SUCCESS(Status)) {
  1254. //
  1255. // Save PETHREAD of Target thread for the dpc routine
  1256. // the DPC routine will deref the threads.
  1257. //
  1258. pDelayIntIrq->InUse = VDMDELAY_KTIMER;
  1259. pDelayIntIrq->Thread = Thread;
  1260. Thread = NULL;
  1261. pDelayIntIrq->MainThread = MainThread;
  1262. MainThread = NULL;
  1263. }
  1264. else {
  1265. pDelayIntIrq->InUse = VDMDELAY_NOTINUSE;
  1266. pDelayIntIrq->Thread = NULL;
  1267. FreeIrqLine = TRUE;
  1268. }
  1269. }
  1270. else {
  1271. AlreadyInUse = TRUE;
  1272. }
  1273. ExReleaseSpinLock(&pVdmObjects->DelayIntSpinLock, OldIrql);
  1274. VidExit2:
  1275. try {
  1276. if (FreeIrqLine) {
  1277. *pDelayIrq &= ~IrqLine;
  1278. InterlockedOr ((PLONG)pUndelayIrq, IrqLine);
  1279. }
  1280. else if (!AlreadyInUse) { // TakeIrqLine
  1281. *pDelayIrq |= IrqLine;
  1282. InterlockedAnd ((PLONG)pUndelayIrq, ~IrqLine);
  1283. }
  1284. }
  1285. except(EXCEPTION_EXECUTE_HANDLER) {
  1286. Status = GetExceptionCode();
  1287. }
  1288. ExReleaseFastMutex(&pVdmObjects->DelayIntFastMutex);
  1289. if (Thread) {
  1290. ObDereferenceObject(Thread);
  1291. }
  1292. if (MainThread) {
  1293. ObDereferenceObject(MainThread);
  1294. }
  1295. return Status;
  1296. }
  1297. VOID
  1298. VdmpDelayIntDpcRoutine (
  1299. IN PKDPC Dpc,
  1300. IN PVOID DeferredContext,
  1301. IN PVOID SystemArgument1,
  1302. IN PVOID SystemArgument2
  1303. )
  1304. /*++
  1305. Routine Description:
  1306. This function is the DPC routine that is called when a DelayedInterrupt
  1307. timer expires. Its function is to insert the associated APC into the
  1308. target thread's APC queue.
  1309. Arguments:
  1310. Dpc - Supplies a pointer to a control object of type DPC.
  1311. DeferredContext - Supplies a pointer to the Target EProcess
  1312. SystemArgument1, SystemArgument2 - Supplies a set of two pointers to
  1313. two arguments that contain untyped data that are
  1314. NOT USED.
  1315. Return Value:
  1316. None.
  1317. --*/
  1318. {
  1319. LOGICAL FreeEntireVdm;
  1320. PVDM_PROCESS_OBJECTS pVdmObjects;
  1321. PEPROCESS Process;
  1322. PETHREAD Thread, MainThread;
  1323. PLIST_ENTRY Next;
  1324. PDELAYINTIRQ pDelayIntIrq;
  1325. UNREFERENCED_PARAMETER (SystemArgument1);
  1326. UNREFERENCED_PARAMETER (SystemArgument2);
  1327. FreeEntireVdm = FALSE;
  1328. //
  1329. // Get address of Process VdmObjects
  1330. //
  1331. Process = (PEPROCESS)DeferredContext;
  1332. pVdmObjects = (PVDM_PROCESS_OBJECTS)Process->VdmObjects;
  1333. ASSERT (KeGetCurrentIrql () == DISPATCH_LEVEL);
  1334. ExAcquireSpinLockAtDpcLevel(&pVdmObjects->DelayIntSpinLock);
  1335. //
  1336. // Search the DelayedIntList for the matching Dpc.
  1337. //
  1338. Next = pVdmObjects->DelayIntListHead.Flink;
  1339. while (Next != &pVdmObjects->DelayIntListHead) {
  1340. pDelayIntIrq = CONTAINING_RECORD(Next,DELAYINTIRQ,DelayIntListEntry);
  1341. if (&pDelayIntIrq->Dpc == Dpc) {
  1342. break;
  1343. }
  1344. Next = Next->Flink;
  1345. }
  1346. if (Next == &pVdmObjects->DelayIntListHead) {
  1347. ExReleaseSpinLockFromDpcLevel(&pVdmObjects->DelayIntSpinLock);
  1348. }
  1349. else {
  1350. Thread = pDelayIntIrq->Thread;
  1351. pDelayIntIrq->Thread = NULL;
  1352. MainThread = pDelayIntIrq->MainThread;
  1353. pDelayIntIrq->MainThread = NULL;
  1354. if (pDelayIntIrq->InUse) {
  1355. if ((Thread && KeVdmInsertQueueApc(&pDelayIntIrq->Apc,
  1356. &Thread->Tcb,
  1357. KernelMode,
  1358. VdmpDelayIntApcRoutine,
  1359. VdmpRundownRoutine,
  1360. VdmpQueueIntNormalRoutine, // normal routine
  1361. NULL, // NormalContext
  1362. VDM_HWINT_INCREMENT
  1363. ))
  1364. ||
  1365. (MainThread && KeVdmInsertQueueApc(&pDelayIntIrq->Apc,
  1366. &MainThread->Tcb,
  1367. KernelMode,
  1368. VdmpDelayIntApcRoutine,
  1369. VdmpRundownRoutine,
  1370. VdmpQueueIntNormalRoutine, // normal routine
  1371. NULL, // NormalContext
  1372. VDM_HWINT_INCREMENT
  1373. )))
  1374. {
  1375. pDelayIntIrq->InUse = VDMDELAY_KAPC;
  1376. }
  1377. else {
  1378. // This hwinterrupt line is blocked forever.
  1379. pDelayIntIrq->InUse = VDMDELAY_NOTINUSE;
  1380. }
  1381. }
  1382. ExReleaseSpinLockFromDpcLevel(&pVdmObjects->DelayIntSpinLock);
  1383. if (Thread) {
  1384. ObDereferenceObject (Thread);
  1385. }
  1386. if (MainThread) {
  1387. ObDereferenceObject (MainThread);
  1388. }
  1389. ObDereferenceObject (Process);
  1390. }
  1391. return;
  1392. }
  1393. VOID
  1394. VdmpDelayIntApcRoutine (
  1395. IN PKAPC Apc,
  1396. IN PKNORMAL_ROUTINE *NormalRoutine,
  1397. IN PVOID *NormalContext,
  1398. IN PVOID *SystemArgument1,
  1399. IN PVOID *SystemArgument2
  1400. )
  1401. /*++
  1402. Routine Description:
  1403. This function is the special APC routine that is called to
  1404. dispatch a delayed interrupt. This routine clears the IrqLine
  1405. bit, VdmpQueueIntApcRoutine will restart interrupts.
  1406. Arguments:
  1407. Apc - Supplies a pointer to the APC object used to invoke this routine.
  1408. NormalRoutine - Supplies a pointer to a pointer to an optional
  1409. normal routine, which is executed when wow is blocked.
  1410. NormalContext - Supplies a pointer to a pointer to an arbitrary data
  1411. structure that was specified when the APC was initialized and is
  1412. NOT USED.
  1413. SystemArgument1, SystemArgument2 - Supplies a set of two pointers to
  1414. two arguments that contain untyped data that are
  1415. NOT USED.
  1416. Return Value:
  1417. None.
  1418. --*/
  1419. {
  1420. KIRQL OldIrql;
  1421. PLIST_ENTRY Next;
  1422. PDELAYINTIRQ pDelayIntIrq;
  1423. KPROCESSOR_MODE ProcessorMode;
  1424. PULONG pDelayIrq;
  1425. PULONG pUndelayIrq;
  1426. PULONG pDelayIret;
  1427. ULONG IrqLine;
  1428. LOGICAL FreeIrqLine;
  1429. LOGICAL QueueApc;
  1430. PVDM_PROCESS_OBJECTS pVdmObjects;
  1431. UNREFERENCED_PARAMETER (NormalContext);
  1432. FreeIrqLine = FALSE;
  1433. //
  1434. // Clear address of thread object in APC object.
  1435. //
  1436. // N.B. The delay interrupt lock is used to synchronize access to APC
  1437. // objects that are manipulated by VDM.
  1438. //
  1439. pVdmObjects = PsGetCurrentProcess()->VdmObjects;
  1440. ExAcquireFastMutex(&pVdmObjects->DelayIntFastMutex);
  1441. ExAcquireSpinLock(&pVdmObjects->DelayIntSpinLock, &OldIrql);
  1442. KeVdmClearApcThreadAddress(Apc);
  1443. //
  1444. // Search the DelayedIntList for the pDelayIntIrq.
  1445. //
  1446. Next = pVdmObjects->DelayIntListHead.Flink;
  1447. while (Next != &pVdmObjects->DelayIntListHead) {
  1448. pDelayIntIrq = CONTAINING_RECORD(Next,DELAYINTIRQ,DelayIntListEntry);
  1449. if (&pDelayIntIrq->Apc == Apc) {
  1450. break;
  1451. }
  1452. Next = Next->Flink;
  1453. }
  1454. if (Next != &pVdmObjects->DelayIntListHead) {
  1455. //
  1456. // Found the IrqLine in the DelayedIntList, restart interrupts.
  1457. //
  1458. if (pDelayIntIrq->InUse) {
  1459. pDelayIntIrq->InUse = VDMDELAY_NOTINUSE;
  1460. IrqLine = pDelayIntIrq->IrqLine;
  1461. FreeIrqLine = TRUE;
  1462. }
  1463. }
  1464. ExReleaseSpinLock(&pVdmObjects->DelayIntSpinLock, OldIrql);
  1465. if (FreeIrqLine == FALSE) {
  1466. ExReleaseFastMutex(&pVdmObjects->DelayIntFastMutex);
  1467. return;
  1468. }
  1469. pDelayIrq = pVdmObjects->pIcaUserData->pDelayIrq;
  1470. pUndelayIrq = pVdmObjects->pIcaUserData->pUndelayIrq;
  1471. pDelayIret = pVdmObjects->pIcaUserData->pDelayIret;
  1472. QueueApc = FALSE;
  1473. try {
  1474. //
  1475. // These variables are being modified without holding the
  1476. // ICA lock. This should be OK because none of the ntvdm
  1477. // devices (timer, mouse etc. should ever do a delayed int
  1478. // while a previous delayed interrupt is still pending.
  1479. //
  1480. *pDelayIrq &= ~IrqLine;
  1481. InterlockedOr ((PLONG)pUndelayIrq, IrqLine);
  1482. //
  1483. // If we are waiting for an iret hook we have nothing left to do
  1484. // since the iret hook will restart interrupts.
  1485. //
  1486. if (!(IrqLine & *pDelayIret)) {
  1487. //
  1488. // set hardware int pending
  1489. //
  1490. InterlockedOr (FIXED_NTVDMSTATE_LINEAR_PC_AT, VDM_INT_HARDWARE);
  1491. //
  1492. // Queue a usermode APC to dispatch interrupts, note
  1493. // try protection is not needed.
  1494. //
  1495. if (NormalRoutine) {
  1496. QueueApc = TRUE;
  1497. }
  1498. }
  1499. }
  1500. except(VdmpExceptionHandler(GetExceptionInformation())) {
  1501. NOTHING;
  1502. }
  1503. if (QueueApc == TRUE) {
  1504. ProcessorMode = KernelMode;
  1505. VdmpQueueIntApcRoutine(Apc,
  1506. NormalRoutine,
  1507. (PVOID *)&ProcessorMode,
  1508. SystemArgument1,
  1509. SystemArgument2);
  1510. }
  1511. ExReleaseFastMutex(&pVdmObjects->DelayIntFastMutex);
  1512. return;
  1513. }
  1514. BOOLEAN
  1515. VdmpDispatchableIntPending(
  1516. ULONG EFlags
  1517. )
  1518. /*++
  1519. Routine Description:
  1520. This routine determines whether or not there is a dispatchable
  1521. virtual interrupt to dispatch.
  1522. Arguments:
  1523. EFlags -- supplies a pointer to the EFlags to be checked
  1524. Return Value:
  1525. True -- a virtual interrupt should be dispatched
  1526. False -- no virtual interrupt should be dispatched
  1527. --*/
  1528. {
  1529. PAGED_CODE();
  1530. //
  1531. // Insure that we are not trying to run with IOPL and pentium extensions
  1532. //
  1533. ASSERT((!(KeI386VdmIoplAllowed &&
  1534. (KeI386VirtualIntExtensions & (V86_VIRTUAL_INT_EXTENSIONS |
  1535. PM_VIRTUAL_INT_EXTENSIONS)))));
  1536. //
  1537. // The accesses to FIXED_NTVDMSTATE_LINEAR_PC_AT may be invalid so
  1538. // wrap this in an exception handler.
  1539. //
  1540. try {
  1541. if (EFlags & EFLAGS_V86_MASK) {
  1542. if (KeI386VirtualIntExtensions & V86_VIRTUAL_INT_EXTENSIONS) {
  1543. if(0 != (EFlags & EFLAGS_VIF)) {
  1544. return TRUE;
  1545. }
  1546. } else if (KeI386VdmIoplAllowed) {
  1547. if (0 != (EFlags & EFLAGS_INTERRUPT_MASK)) {
  1548. return TRUE;
  1549. }
  1550. } else {
  1551. if (0 != (*FIXED_NTVDMSTATE_LINEAR_PC_AT & VDM_VIRTUAL_INTERRUPTS)) {
  1552. return TRUE;
  1553. }
  1554. }
  1555. } else {
  1556. if (KeI386VirtualIntExtensions & PM_VIRTUAL_INT_EXTENSIONS) {
  1557. if (0 != (EFlags & EFLAGS_VIF)) {
  1558. return TRUE;
  1559. }
  1560. } else {
  1561. if ((*FIXED_NTVDMSTATE_LINEAR_PC_AT & VDM_VIRTUAL_INTERRUPTS) == 0) {
  1562. VdmCheckPMCliTimeStamp();
  1563. }
  1564. if (0 != (*FIXED_NTVDMSTATE_LINEAR_PC_AT & VDM_VIRTUAL_INTERRUPTS)) {
  1565. return TRUE;
  1566. }
  1567. }
  1568. }
  1569. }
  1570. except (EXCEPTION_EXECUTE_HANDLER) {
  1571. NOTHING;
  1572. }
  1573. return FALSE;
  1574. }
  1575. NTSTATUS
  1576. VdmpIsThreadTerminating(
  1577. HANDLE ThreadId
  1578. )
  1579. /*++
  1580. Routine Description:
  1581. This routine determines if the specified thread is terminating or not.
  1582. Arguments:
  1583. Return Value:
  1584. True --
  1585. False -
  1586. --*/
  1587. {
  1588. CLIENT_ID Cid;
  1589. PETHREAD Thread;
  1590. NTSTATUS Status;
  1591. PAGED_CODE();
  1592. //
  1593. // If the owning thread juest exited the IcaLock the
  1594. // OwningThread Tid may be NULL, return success, since
  1595. // we don't know what the owning threads state was.
  1596. //
  1597. if (!ThreadId) {
  1598. return STATUS_SUCCESS;
  1599. }
  1600. Cid.UniqueProcess = NtCurrentTeb()->ClientId.UniqueProcess;
  1601. Cid.UniqueThread = ThreadId;
  1602. Status = PsLookupProcessThreadByCid(&Cid, NULL, &Thread);
  1603. if (NT_SUCCESS(Status)) {
  1604. Status = PsIsThreadTerminating(Thread) ? STATUS_THREAD_IS_TERMINATING
  1605. : STATUS_SUCCESS;
  1606. ObDereferenceObject(Thread);
  1607. }
  1608. return Status;
  1609. }
  1610. VOID
  1611. VdmpRundownRoutine (
  1612. IN PKAPC Apc
  1613. )
  1614. /*++
  1615. Routine Description:
  1616. The function is the rundown routine for VDM APCs and is called on thread
  1617. termination. The fact that this function is called means that none of the
  1618. APC objects specified by the process VDM structure will not get freed.
  1619. They must be freed when the process terminates.
  1620. Arguments:
  1621. Apc - Supplies a pointer to an APC object to be rundown.
  1622. Return Value:
  1623. None.
  1624. --*/
  1625. {
  1626. //
  1627. // Clear the Irqline, but don't requeue the APC.
  1628. //
  1629. VdmpDelayIntApcRoutine(Apc, NULL, NULL, NULL, NULL);
  1630. return;
  1631. }
  1632. int
  1633. VdmpExceptionHandler(
  1634. IN PEXCEPTION_POINTERS ExceptionInfo
  1635. )
  1636. {
  1637. #if DBG
  1638. PEXCEPTION_RECORD ExceptionRecord;
  1639. ULONG NumberParameters;
  1640. PULONG ExceptionInformation;
  1641. #endif
  1642. PAGED_CODE();
  1643. #if DBG
  1644. ExceptionRecord = ExceptionInfo->ExceptionRecord;
  1645. DbgPrint("VdmExRecord ExCode %x Flags %x Address %x\n",
  1646. ExceptionRecord->ExceptionCode,
  1647. ExceptionRecord->ExceptionFlags,
  1648. ExceptionRecord->ExceptionAddress
  1649. );
  1650. NumberParameters = ExceptionRecord->NumberParameters;
  1651. if (NumberParameters) {
  1652. DbgPrint("VdmExRecord Parameters:\n");
  1653. ExceptionInformation = ExceptionRecord->ExceptionInformation;
  1654. while (NumberParameters--) {
  1655. DbgPrint("\t%x\n", *ExceptionInformation);
  1656. }
  1657. }
  1658. #endif
  1659. return EXCEPTION_EXECUTE_HANDLER;
  1660. }