2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/io/iomgr/irp.c
5 * PURPOSE: IRP Handling Functions
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
8 * Filip Navara (navaraf@reactos.org)
11 /* INCLUDES ****************************************************************/
17 /* Undefine some macros we implement here */
19 #undef IoCompleteRequest
21 /* PRIVATE FUNCTIONS ********************************************************/
25 IopFreeIrpKernelApc(IN PKAPC Apc
,
26 IN PKNORMAL_ROUTINE
*NormalRoutine
,
27 IN PVOID
*NormalContext
,
28 IN PVOID
*SystemArgument1
,
29 IN PVOID
*SystemArgument2
)
32 IoFreeIrp(CONTAINING_RECORD(Apc
, IRP
, Tail
.Apc
));
37 IopAbortIrpKernelApc(IN PKAPC Apc
)
40 IoFreeIrp(CONTAINING_RECORD(Apc
, IRP
, Tail
.Apc
));
45 IopCleanupFailedIrp(IN PFILE_OBJECT FileObject
,
46 IN PKEVENT EventObject OPTIONAL
,
47 IN PVOID Buffer OPTIONAL
)
51 /* Dereference the event */
52 if (EventObject
) ObDereferenceObject(EventObject
);
54 /* Free a buffer, if any */
55 if (Buffer
) ExFreePool(Buffer
);
57 /* If this was a file opened for synch I/O, then unlock it */
58 if (FileObject
->Flags
& FO_SYNCHRONOUS_IO
) IopUnlockFileObject(FileObject
);
60 /* Now dereference it and return */
61 ObDereferenceObject(FileObject
);
62 return STATUS_INSUFFICIENT_RESOURCES
;
67 IopAbortInterruptedIrp(IN PKEVENT EventObject
,
75 /* Raise IRQL to APC */
76 KeRaiseIrql(APC_LEVEL
, &OldIrql
);
78 /* Check if nobody completed it yet */
79 if (!KeReadStateEvent(EventObject
))
81 /* First, cancel it */
82 CancelResult
= IoCancelIrp(Irp
);
85 /* Check if we cancelled it */
88 /* Wait for the IRP to be cancelled */
89 Wait
.QuadPart
= -100000;
90 while (!KeReadStateEvent(EventObject
))
92 /* Delay indefintely */
93 KeDelayExecutionThread(KernelMode
, FALSE
, &Wait
);
98 /* No cancellation done, so wait for the I/O system to kill it */
99 KeWaitForSingleObject(EventObject
,
108 /* We got preempted, so give up */
109 KeLowerIrql(OldIrql
);
115 IopRemoveThreadIrp(VOID
)
120 PLIST_ENTRY IrpEntry
;
121 PIO_ERROR_LOG_PACKET ErrorLogEntry
;
122 PDEVICE_OBJECT DeviceObject
= NULL
;
123 PIO_STACK_LOCATION IoStackLocation
;
125 /* First, raise to APC to protect IrpList */
126 KeRaiseIrql(APC_LEVEL
, &OldIrql
);
128 /* Get the Thread and check the list */
129 IrpThread
= PsGetCurrentThread();
130 if (IsListEmpty(&IrpThread
->IrpList
))
132 /* It got completed now, so quit */
133 KeLowerIrql(OldIrql
);
137 /* Get the misbehaving IRP */
138 IrpEntry
= IrpThread
->IrpList
.Flink
;
139 DeadIrp
= CONTAINING_RECORD(IrpEntry
, IRP
, ThreadListEntry
);
140 IOTRACE(IO_IRP_DEBUG
,
141 "%s - Deassociating IRP %p for %p\n",
146 /* Don't cancel the IRP if it's already been completed far */
147 if (DeadIrp
->CurrentLocation
== (DeadIrp
->StackCount
+ 2))
150 KeLowerIrql(OldIrql
);
154 /* Disown the IRP! */
155 DeadIrp
->Tail
.Overlay
.Thread
= NULL
;
156 RemoveHeadList(&IrpThread
->IrpList
);
157 InitializeListHead(&DeadIrp
->ThreadListEntry
);
159 /* Get the stack location and check if it's valid */
160 IoStackLocation
= IoGetCurrentIrpStackLocation(DeadIrp
);
161 if (DeadIrp
->CurrentLocation
<= DeadIrp
->StackCount
)
163 /* Get the device object */
164 DeviceObject
= IoStackLocation
->DeviceObject
;
167 /* Lower IRQL now, since we have the pointers we need */
168 KeLowerIrql(OldIrql
);
170 /* Check if we can send an Error Log Entry*/
173 /* Allocate an entry */
174 ErrorLogEntry
= IoAllocateErrorLogEntry(DeviceObject
,
175 sizeof(IO_ERROR_LOG_PACKET
));
178 /* Write the entry */
179 ErrorLogEntry
->ErrorCode
= 0xBAADF00D; /* FIXME */
180 IoWriteErrorLogEntry(ErrorLogEntry
);
187 IopCleanupIrp(IN PIRP Irp
,
188 IN PFILE_OBJECT FileObject
)
191 IOTRACE(IO_IRP_DEBUG
,
192 "%s - Cleaning IRP %p for %p\n",
197 /* Check if there's an MDL */
198 while ((Mdl
= Irp
->MdlAddress
))
200 /* Clear all of them */
201 Irp
->MdlAddress
= Mdl
->Next
;
205 /* Check if the IRP has system buffer */
206 if (Irp
->Flags
& IRP_DEALLOCATE_BUFFER
)
208 /* Free the buffer */
209 ExFreePoolWithTag(Irp
->AssociatedIrp
.SystemBuffer
, TAG_SYS_BUF
);
212 /* Check if this IRP has a user event, a file object, and is async */
213 if ((Irp
->UserEvent
) &&
214 !(Irp
->Flags
& IRP_SYNCHRONOUS_API
) &&
217 /* Dereference the User Event */
218 ObDereferenceObject(Irp
->UserEvent
);
221 /* Check if we have a file object and this isn't a create operation */
222 if ((FileObject
) && !(Irp
->Flags
& IRP_CREATE_OPERATION
))
224 /* Dereference the file object */
225 ObDereferenceObject(FileObject
);
234 IopCompleteRequest(IN PKAPC Apc
,
235 IN PKNORMAL_ROUTINE
* NormalRoutine
,
236 IN PVOID
* NormalContext
,
237 IN PVOID
* SystemArgument1
,
238 IN PVOID
* SystemArgument2
)
240 PFILE_OBJECT FileObject
;
243 PVOID Port
= NULL
, Key
= NULL
;
244 BOOLEAN SignaledCreateRequest
= FALSE
;
246 /* Get data from the APC */
247 FileObject
= (PFILE_OBJECT
)*SystemArgument1
;
248 Irp
= CONTAINING_RECORD(Apc
, IRP
, Tail
.Apc
);
249 IOTRACE(IO_IRP_DEBUG
,
250 "%s - Completing IRP %p for %p\n",
256 ASSERT(Irp
->IoStatus
.Status
!= 0xFFFFFFFF);
258 /* Check if we have a file object */
259 if (*SystemArgument2
)
261 /* Check if we're reparsing */
262 if ((Irp
->IoStatus
.Status
== STATUS_REPARSE
) &&
263 (Irp
->IoStatus
.Information
== IO_REPARSE_TAG_MOUNT_POINT
))
265 /* We should never get this yet */
266 DPRINT1("Reparse support not yet present!\n");
271 /* Handle Buffered case first */
272 if (Irp
->Flags
& IRP_BUFFERED_IO
)
274 /* Check if we have an input buffer and if we succeeded */
275 if ((Irp
->Flags
& IRP_INPUT_OPERATION
) &&
276 (Irp
->IoStatus
.Status
!= STATUS_VERIFY_REQUIRED
) &&
277 !(NT_ERROR(Irp
->IoStatus
.Status
)))
279 /* Copy the buffer back to the user */
280 RtlCopyMemory(Irp
->UserBuffer
,
281 Irp
->AssociatedIrp
.SystemBuffer
,
282 Irp
->IoStatus
.Information
);
285 /* Also check if we should de-allocate it */
286 if (Irp
->Flags
& IRP_DEALLOCATE_BUFFER
)
289 ExFreePool(Irp
->AssociatedIrp
.SystemBuffer
);
293 /* Now we got rid of these two... */
294 Irp
->Flags
&= ~(IRP_BUFFERED_IO
| IRP_DEALLOCATE_BUFFER
);
296 /* Check if there's an MDL */
297 for (Mdl
= Irp
->MdlAddress
; Mdl
; Mdl
= NextMdl
)
305 Irp
->MdlAddress
= NULL
;
308 * Check if either the request was completed without any errors
309 * (but warnings are OK!), or if it was completed with an error, but
310 * did return from a pending I/O Operation and is not synchronous.
312 if (!(NT_ERROR(Irp
->IoStatus
.Status
)) ||
313 (NT_ERROR(Irp
->IoStatus
.Status
) &&
314 (Irp
->PendingReturned
) &&
315 !(IsIrpSynchronous(Irp
, FileObject
))))
317 /* Get any information we need from the FO before we kill it */
318 if ((FileObject
) && (FileObject
->CompletionContext
))
320 /* Save Completion Data */
321 Port
= FileObject
->CompletionContext
->Port
;
322 Key
= FileObject
->CompletionContext
->Key
;
325 /* Use SEH to make sure we don't write somewhere invalid */
328 /* Save the IOSB Information */
329 *Irp
->UserIosb
= Irp
->IoStatus
;
333 /* Ignore any error */
337 /* Check if we have an event or a file object */
340 /* At the very least, this is a PKEVENT, so signal it always */
341 KeSetEvent(Irp
->UserEvent
, 0, FALSE
);
343 /* Check if we also have a File Object */
346 /* Check if this is an Asynch API */
347 if (!(Irp
->Flags
& IRP_SYNCHRONOUS_API
))
349 /* Dereference the event */
350 ObDereferenceObject(Irp
->UserEvent
);
354 * Now, if this is a Synch I/O File Object, then this event is
355 * NOT an actual Executive Event, so we won't dereference it,
356 * and instead, we will signal the File Object
358 if ((FileObject
->Flags
& FO_SYNCHRONOUS_IO
) &&
359 !(Irp
->Flags
& IRP_OB_QUERY_NAME
))
361 /* Signal the file object and set the status */
362 KeSetEvent(&FileObject
->Event
, 0, FALSE
);
363 FileObject
->FinalStatus
= Irp
->IoStatus
.Status
;
367 * This could also be a create operation, in which case we want
368 * to make sure there's no APC fired.
370 if (Irp
->Flags
& IRP_CREATE_OPERATION
)
372 /* Clear the APC Routine and remember this */
373 Irp
->Overlay
.AsynchronousParameters
.UserApcRoutine
= NULL
;
374 SignaledCreateRequest
= TRUE
;
380 /* Signal the file object and set the status */
381 KeSetEvent(&FileObject
->Event
, 0, FALSE
);
382 FileObject
->FinalStatus
= Irp
->IoStatus
.Status
;
385 * This could also be a create operation, in which case we want
386 * to make sure there's no APC fired.
388 if (Irp
->Flags
& IRP_CREATE_OPERATION
)
390 /* Clear the APC Routine and remember this */
391 Irp
->Overlay
.AsynchronousParameters
.UserApcRoutine
= NULL
;
392 SignaledCreateRequest
= TRUE
;
396 /* Now that we've signaled the events, de-associate the IRP */
397 IopUnQueueIrpFromThread(Irp
);
399 /* Now check if a User APC Routine was requested */
400 if (Irp
->Overlay
.AsynchronousParameters
.UserApcRoutine
)
403 KeInitializeApc(&Irp
->Tail
.Apc
,
404 KeGetCurrentThread(),
405 CurrentApcEnvironment
,
407 IopAbortIrpKernelApc
,
408 (PKNORMAL_ROUTINE
)Irp
->
409 Overlay
.AsynchronousParameters
.UserApcRoutine
,
412 Overlay
.AsynchronousParameters
.UserApcContext
);
415 KeInsertQueueApc(&Irp
->Tail
.Apc
, Irp
->UserIosb
, NULL
, 2);
418 (Irp
->Overlay
.AsynchronousParameters
.UserApcContext
))
420 /* We have an I/O Completion setup... create the special Overlay */
421 Irp
->Tail
.CompletionKey
= Key
;
422 Irp
->Tail
.Overlay
.PacketType
= IopCompletionPacketIrp
;
423 KeInsertQueue(Port
, &Irp
->Tail
.Overlay
.ListEntry
);
427 /* Free the IRP since we don't need it anymore */
431 /* Check if we have a file object that wasn't part of a create */
432 if ((FileObject
) && !(SignaledCreateRequest
))
434 /* Dereference it, since it's not needed anymore either */
435 ObDereferenceObjectDeferDelete(FileObject
);
441 * Either we didn't return from the request, or we did return but this
442 * request was synchronous.
444 if ((Irp
->PendingReturned
) && (FileObject
))
446 /* So we did return with a synch operation, was it the IRP? */
447 if (Irp
->Flags
& IRP_SYNCHRONOUS_API
)
449 /* Yes, this IRP was synchronous, so return the I/O Status */
450 *Irp
->UserIosb
= Irp
->IoStatus
;
452 /* Now check if the user gave an event */
456 KeSetEvent(Irp
->UserEvent
, 0, FALSE
);
460 /* No event was given, so signal the FO instead */
461 KeSetEvent(&FileObject
->Event
, 0, FALSE
);
467 * It's not the IRP that was synchronous, it was the FO
468 * that was opened this way. Signal its event.
470 FileObject
->FinalStatus
= Irp
->IoStatus
.Status
;
471 KeSetEvent(&FileObject
->Event
, 0, FALSE
);
475 /* Now that we got here, we do this for incomplete I/Os as well */
476 if ((FileObject
) && !(Irp
->Flags
& IRP_CREATE_OPERATION
))
478 /* Dereference the File Object unless this was a create */
479 ObDereferenceObjectDeferDelete(FileObject
);
483 * Check if this was an Executive Event (remember that we know this
484 * by checking if the IRP is synchronous)
486 if ((Irp
->UserEvent
) &&
488 !(Irp
->Flags
& IRP_SYNCHRONOUS_API
))
490 /* This isn't a PKEVENT, so dereference it */
491 ObDereferenceObject(Irp
->UserEvent
);
494 /* Now that we've signaled the events, de-associate the IRP */
495 IopUnQueueIrpFromThread(Irp
);
497 /* Free the IRP as well */
502 /* FUNCTIONS *****************************************************************/
509 IoAllocateIrp(IN CCHAR StackSize
,
510 IN BOOLEAN ChargeQuota
)
513 USHORT Size
= IoSizeOfIrp(StackSize
);
516 PNPAGED_LOOKASIDE_LIST List
= NULL
;
517 PP_NPAGED_LOOKASIDE_NUMBER ListType
= LookasideSmallIrpList
;
519 /* Set Charge Quota Flag */
520 if (ChargeQuota
) Flags
|= IRP_QUOTA_CHARGED
;
522 /* Figure out which Lookaside List to use */
523 if ((StackSize
<= 8) && (ChargeQuota
== FALSE
))
525 /* Set Fixed Size Flag */
526 Flags
= IRP_ALLOCATED_FIXED_SIZE
;
528 /* See if we should use big list */
531 Size
= IoSizeOfIrp(8);
532 ListType
= LookasideLargeIrpList
;
536 Prcb
= KeGetCurrentPrcb();
538 /* Get the P List First */
539 List
= (PNPAGED_LOOKASIDE_LIST
)Prcb
->PPLookasideList
[ListType
].P
;
541 /* Attempt allocation */
542 List
->L
.TotalAllocates
++;
543 Irp
= (PIRP
)InterlockedPopEntrySList(&List
->L
.ListHead
);
545 /* Check if the P List failed */
548 /* Let the balancer know */
549 List
->L
.AllocateMisses
++;
552 List
= (PNPAGED_LOOKASIDE_LIST
)Prcb
->PPLookasideList
[ListType
].L
;
553 List
->L
.TotalAllocates
++;
554 Irp
= (PIRP
)InterlockedPopEntrySList(&List
->L
.ListHead
);
558 /* Check if we have to use the pool */
561 /* Did we try lookaside and fail? */
562 if (Flags
& IRP_ALLOCATED_FIXED_SIZE
) List
->L
.AllocateMisses
++;
564 /* Check if we should charge quota */
567 /* Irp = ExAllocatePoolWithQuotaTag(NonPagedPool, Size, TAG_IRP); */
569 Irp
= ExAllocatePoolWithTag(NonPagedPool
, Size
, TAG_IRP
);
573 /* Allocate the IRP With no Quota charge */
574 Irp
= ExAllocatePoolWithTag(NonPagedPool
, Size
, TAG_IRP
);
577 /* Make sure it was sucessful */
578 if (!Irp
) return(NULL
);
582 /* We have an IRP from Lookaside */
583 if (ChargeQuota
) Flags
|= IRP_LOOKASIDE_ALLOCATION
;
585 /* In this case there is no charge quota */
586 Flags
&= ~IRP_QUOTA_CHARGED
;
589 /* Now Initialize it */
590 IoInitializeIrp(Irp
, Size
, StackSize
);
592 /* Set the Allocation Flags */
593 Irp
->AllocationFlags
= Flags
;
596 IOTRACE(IO_IRP_DEBUG
,
597 "%s - Allocated IRP %p with allocation flags %lx\n",
609 IoBuildAsynchronousFsdRequest(IN ULONG MajorFunction
,
610 IN PDEVICE_OBJECT DeviceObject
,
613 IN PLARGE_INTEGER StartingOffset
,
614 IN PIO_STATUS_BLOCK IoStatusBlock
)
617 PIO_STACK_LOCATION StackPtr
;
620 Irp
= IoAllocateIrp(DeviceObject
->StackSize
, FALSE
);
621 if (!Irp
) return NULL
;
624 StackPtr
= IoGetNextIrpStackLocation(Irp
);
626 /* Write the Major function and then deal with it */
627 StackPtr
->MajorFunction
= (UCHAR
)MajorFunction
;
629 /* Do not handle the following here */
630 if ((MajorFunction
!= IRP_MJ_FLUSH_BUFFERS
) &&
631 (MajorFunction
!= IRP_MJ_SHUTDOWN
) &&
632 (MajorFunction
!= IRP_MJ_PNP
) &&
633 (MajorFunction
!= IRP_MJ_POWER
))
635 /* Check if this is Buffered IO */
636 if (DeviceObject
->Flags
& DO_BUFFERED_IO
)
638 /* Allocate the System Buffer */
639 Irp
->AssociatedIrp
.SystemBuffer
=
640 ExAllocatePoolWithTag(NonPagedPool
, Length
, TAG_SYS_BUF
);
641 if (!Irp
->AssociatedIrp
.SystemBuffer
)
643 /* Free the IRP and fail */
649 Irp
->Flags
= IRP_BUFFERED_IO
| IRP_DEALLOCATE_BUFFER
;
651 /* Handle special IRP_MJ_WRITE Case */
652 if (MajorFunction
== IRP_MJ_WRITE
)
654 /* Copy the buffer data */
655 RtlCopyMemory(Irp
->AssociatedIrp
.SystemBuffer
, Buffer
, Length
);
659 /* Set the Input Operation flag and set this as a User Buffer */
660 Irp
->Flags
|= IRP_INPUT_OPERATION
;
661 Irp
->UserBuffer
= Buffer
;
664 else if (DeviceObject
->Flags
& DO_DIRECT_IO
)
666 /* Use an MDL for Direct I/O */
667 Irp
->MdlAddress
= IoAllocateMdl(Buffer
,
672 if (!Irp
->MdlAddress
)
674 /* Free the IRP and fail */
683 MmProbeAndLockPages(Irp
->MdlAddress
,
685 MajorFunction
== IRP_MJ_READ
?
686 IoWriteAccess
: IoReadAccess
);
690 /* Free the IRP and its MDL */
691 IoFreeMdl(Irp
->MdlAddress
);
697 /* This is how we know if we failed during the probe */
698 if (!Irp
) return NULL
;
702 /* Neither, use the buffer */
703 Irp
->UserBuffer
= Buffer
;
706 /* Check if this is a read */
707 if (MajorFunction
== IRP_MJ_READ
)
709 /* Set the parameters for a read */
710 StackPtr
->Parameters
.Read
.Length
= Length
;
711 StackPtr
->Parameters
.Read
.ByteOffset
= *StartingOffset
;
713 else if (MajorFunction
== IRP_MJ_WRITE
)
715 /* Otherwise, set write parameters */
716 StackPtr
->Parameters
.Write
.Length
= Length
;
717 StackPtr
->Parameters
.Write
.ByteOffset
= *StartingOffset
;
721 /* Set the Current Thread and IOSB */
722 Irp
->UserIosb
= IoStatusBlock
;
723 Irp
->Tail
.Overlay
.Thread
= PsGetCurrentThread();
726 IOTRACE(IO_IRP_DEBUG
,
727 "%s - Built IRP %p with Major, Buffer, DO %lx %p %p\n",
741 IoBuildDeviceIoControlRequest(IN ULONG IoControlCode
,
742 IN PDEVICE_OBJECT DeviceObject
,
743 IN PVOID InputBuffer
,
744 IN ULONG InputBufferLength
,
745 IN PVOID OutputBuffer
,
746 IN ULONG OutputBufferLength
,
747 IN BOOLEAN InternalDeviceIoControl
,
749 IN PIO_STATUS_BLOCK IoStatusBlock
)
752 PIO_STACK_LOCATION StackPtr
;
756 Irp
= IoAllocateIrp(DeviceObject
->StackSize
, FALSE
);
757 if (!Irp
) return NULL
;
760 StackPtr
= IoGetNextIrpStackLocation(Irp
);
762 /* Set the DevCtl Type */
763 StackPtr
->MajorFunction
= InternalDeviceIoControl
?
764 IRP_MJ_INTERNAL_DEVICE_CONTROL
:
765 IRP_MJ_DEVICE_CONTROL
;
767 /* Set the IOCTL Data */
768 StackPtr
->Parameters
.DeviceIoControl
.IoControlCode
= IoControlCode
;
769 StackPtr
->Parameters
.DeviceIoControl
.InputBufferLength
= InputBufferLength
;
770 StackPtr
->Parameters
.DeviceIoControl
.OutputBufferLength
=
773 /* Handle the Methods */
774 switch (IO_METHOD_FROM_CTL_CODE(IoControlCode
))
777 case METHOD_BUFFERED
:
779 /* Select the right Buffer Length */
780 BufferLength
= InputBufferLength
> OutputBufferLength
?
781 InputBufferLength
: OutputBufferLength
;
783 /* Make sure there is one */
786 /* Allocate the System Buffer */
787 Irp
->AssociatedIrp
.SystemBuffer
=
788 ExAllocatePoolWithTag(NonPagedPool
,
791 if (!Irp
->AssociatedIrp
.SystemBuffer
)
793 /* Free the IRP and fail */
798 /* Check if we got a buffer */
801 /* Copy into the System Buffer */
802 RtlCopyMemory(Irp
->AssociatedIrp
.SystemBuffer
,
807 /* Write the flags */
808 Irp
->Flags
= IRP_BUFFERED_IO
| IRP_DEALLOCATE_BUFFER
;
809 if (OutputBuffer
) Irp
->Flags
|= IRP_INPUT_OPERATION
;
811 /* Save the Buffer */
812 Irp
->UserBuffer
= OutputBuffer
;
816 /* Clear the Flags and Buffer */
818 Irp
->UserBuffer
= NULL
;
823 case METHOD_IN_DIRECT
:
824 case METHOD_OUT_DIRECT
:
826 /* Check if we got an input buffer */
829 /* Allocate the System Buffer */
830 Irp
->AssociatedIrp
.SystemBuffer
=
831 ExAllocatePoolWithTag(NonPagedPool
,
834 if (!Irp
->AssociatedIrp
.SystemBuffer
)
836 /* Free the IRP and fail */
841 /* Copy into the System Buffer */
842 RtlCopyMemory(Irp
->AssociatedIrp
.SystemBuffer
,
846 /* Write the flags */
847 Irp
->Flags
= IRP_BUFFERED_IO
| IRP_DEALLOCATE_BUFFER
;
851 /* Clear the flags */
855 /* Check if we got an output buffer */
858 /* Allocate the System Buffer */
859 Irp
->MdlAddress
= IoAllocateMdl(OutputBuffer
,
864 if (!Irp
->MdlAddress
)
866 /* Free the IRP and fail */
875 MmProbeAndLockPages(Irp
->MdlAddress
,
877 IO_METHOD_FROM_CTL_CODE(IoControlCode
) ==
879 IoReadAccess
: IoWriteAccess
);
884 IoFreeMdl(Irp
->MdlAddress
);
886 /* Free the input buffer and IRP */
887 if (InputBuffer
) ExFreePool(Irp
->AssociatedIrp
.SystemBuffer
);
893 /* This is how we know if probing failed */
894 if (!Irp
) return NULL
;
900 /* Just save the Buffer */
901 Irp
->UserBuffer
= OutputBuffer
;
902 StackPtr
->Parameters
.DeviceIoControl
.Type3InputBuffer
= InputBuffer
;
905 /* Now write the Event and IoSB */
906 Irp
->UserIosb
= IoStatusBlock
;
907 Irp
->UserEvent
= Event
;
909 /* Sync IRPs are queued to requestor thread's irp cancel/cleanup list */
910 Irp
->Tail
.Overlay
.Thread
= PsGetCurrentThread();
911 IoQueueThreadIrp(Irp
);
914 IOTRACE(IO_IRP_DEBUG
,
915 "%s - Built IRP %p with IOCTL, Buffers, DO %lx %p %p %p\n",
930 IoBuildSynchronousFsdRequest(IN ULONG MajorFunction
,
931 IN PDEVICE_OBJECT DeviceObject
,
934 IN PLARGE_INTEGER StartingOffset
,
936 IN PIO_STATUS_BLOCK IoStatusBlock
)
940 /* Do the big work to set up the IRP */
941 Irp
= IoBuildAsynchronousFsdRequest(MajorFunction
,
947 if (!Irp
) return NULL
;
949 /* Set the Event which makes it Syncronous */
950 Irp
->UserEvent
= Event
;
952 /* Sync IRPs are queued to requestor thread's irp cancel/cleanup list */
953 IoQueueThreadIrp(Irp
);
962 IoCancelIrp(IN PIRP Irp
)
966 PDRIVER_CANCEL CancelRoutine
;
967 IOTRACE(IO_IRP_DEBUG
,
968 "%s - Canceling IRP %p\n",
971 ASSERT(Irp
->Type
== IO_TYPE_IRP
);
972 IrqlAtEntry
= KeGetCurrentIrql();
974 /* Acquire the cancel lock and cancel the IRP */
975 IoAcquireCancelSpinLock(&OldIrql
);
978 /* Clear the cancel routine and get the old one */
979 CancelRoutine
= (PVOID
)IoSetCancelRoutine(Irp
, NULL
);
982 /* We had a routine, make sure the IRP isn't completed */
983 if (Irp
->CurrentLocation
> (Irp
->StackCount
+ 1))
985 /* It is, bugcheck */
986 KeBugCheckEx(CANCEL_STATE_IN_COMPLETED_IRP
,
993 /* Set the cancel IRQL And call the routine */
994 Irp
->CancelIrql
= OldIrql
;
995 CancelRoutine(IoGetCurrentIrpStackLocation(Irp
)->DeviceObject
, Irp
);
996 ASSERT(IrqlAtEntry
== KeGetCurrentIrql());
1000 /* Otherwise, release the cancel lock and fail */
1001 IoReleaseCancelSpinLock(OldIrql
);
1010 IoCancelThreadIo(IN PETHREAD Thread
)
1013 ULONG Retries
= 3000;
1014 LARGE_INTEGER Interval
;
1015 PLIST_ENTRY ListHead
, NextEntry
;
1017 IOTRACE(IO_IRP_DEBUG
,
1018 "%s - Canceling IRPs for Thread %p\n",
1022 /* Raise to APC to protect the IrpList */
1023 KeRaiseIrql(APC_LEVEL
, &OldIrql
);
1025 /* Start by cancelling all the IRPs in the current thread queue. */
1026 ListHead
= &Thread
->IrpList
;
1027 NextEntry
= ListHead
->Flink
;
1028 while (ListHead
!= NextEntry
)
1031 Irp
= CONTAINING_RECORD(NextEntry
, IRP
, ThreadListEntry
);
1036 /* Move to the next entry */
1037 NextEntry
= NextEntry
->Flink
;
1040 /* Wait 100 milliseconds */
1041 Interval
.QuadPart
= -1000000;
1043 /* Wait till all the IRPs are completed or cancelled. */
1044 while (!IsListEmpty(&Thread
->IrpList
))
1046 /* Now we can lower */
1047 KeLowerIrql(OldIrql
);
1049 /* Wait a short while and then look if all our IRPs were completed. */
1050 KeDelayExecutionThread(KernelMode
, FALSE
, &Interval
);
1053 * Don't stay here forever if some broken driver doesn't complete
1058 /* Print out a message and remove the IRP */
1059 DPRINT1("Broken driver did not complete!\n");
1060 IopRemoveThreadIrp();
1063 /* Raise the IRQL Again */
1064 KeRaiseIrql(APC_LEVEL
, &OldIrql
);
1067 /* We're done, lower the IRQL */
1068 KeLowerIrql(OldIrql
);
1076 IoCallDriver(IN PDEVICE_OBJECT DeviceObject
,
1080 return IofCallDriver(DeviceObject
, Irp
);
1088 IoCompleteRequest(IN PIRP Irp
,
1089 IN CCHAR PriorityBoost
)
1091 /* Call the fastcall */
1092 IofCompleteRequest(Irp
, PriorityBoost
);
1100 IoEnqueueIrp(IN PIRP Irp
)
1102 /* This is the same as calling IoQueueThreadIrp */
1103 IoQueueThreadIrp(Irp
);
1111 IofCallDriver(IN PDEVICE_OBJECT DeviceObject
,
1114 PDRIVER_OBJECT DriverObject
;
1115 PIO_STACK_LOCATION StackPtr
;
1117 /* Get the Driver Object */
1118 DriverObject
= DeviceObject
->DriverObject
;
1120 /* Decrease the current location and check if */
1121 Irp
->CurrentLocation
--;
1122 if (Irp
->CurrentLocation
<= 0)
1124 /* This IRP ran out of stack, bugcheck */
1125 KeBugCheckEx(NO_MORE_IRP_STACK_LOCATIONS
, (ULONG_PTR
)Irp
, 0, 0, 0);
1128 /* Now update the stack location */
1129 StackPtr
= IoGetNextIrpStackLocation(Irp
);
1130 Irp
->Tail
.Overlay
.CurrentStackLocation
= StackPtr
;
1132 /* Get the Device Object */
1133 StackPtr
->DeviceObject
= DeviceObject
;
1136 return DriverObject
->MajorFunction
[StackPtr
->MajorFunction
](DeviceObject
,
1142 IopClearStackLocation(IN PIO_STACK_LOCATION IoStackLocation
)
1144 IoStackLocation
->MinorFunction
= 0;
1145 IoStackLocation
->Flags
= 0;
1146 IoStackLocation
->Control
&= SL_ERROR_RETURNED
;
1147 IoStackLocation
->Parameters
.Others
.Argument1
= 0;
1148 IoStackLocation
->Parameters
.Others
.Argument2
= 0;
1149 IoStackLocation
->Parameters
.Others
.Argument3
= 0;
1150 IoStackLocation
->FileObject
= NULL
;
1158 IofCompleteRequest(IN PIRP Irp
,
1159 IN CCHAR PriorityBoost
)
1161 PIO_STACK_LOCATION StackPtr
, LastStackPtr
;
1162 PDEVICE_OBJECT DeviceObject
;
1163 PFILE_OBJECT FileObject
;
1170 NTSTATUS ErrorCode
= STATUS_SUCCESS
;
1171 IOTRACE(IO_IRP_DEBUG
,
1172 "%s - Completing IRP %p\n",
1176 /* Make sure this IRP isn't getting completed twice or is invalid */
1177 if ((Irp
->CurrentLocation
) > (Irp
->StackCount
+ 1))
1180 KeBugCheckEx(MULTIPLE_IRP_COMPLETE_REQUESTS
, (ULONG_PTR
)Irp
, 0, 0, 0);
1183 /* Some sanity checks */
1184 ASSERT(Irp
->Type
== IO_TYPE_IRP
);
1185 ASSERT(!Irp
->CancelRoutine
);
1186 ASSERT(Irp
->IoStatus
.Status
!= STATUS_PENDING
);
1187 ASSERT(Irp
->IoStatus
.Status
!= 0xFFFFFFFF);
1189 /* Get the last stack */
1190 LastStackPtr
= (PIO_STACK_LOCATION
)(Irp
+ 1);
1191 if (LastStackPtr
->Control
& SL_ERROR_RETURNED
)
1193 /* Get the error code */
1194 ErrorCode
= PtrToUlong(LastStackPtr
->Parameters
.Others
.Argument4
);
1197 /* Get the Current Stack and skip it */
1198 StackPtr
= IoGetCurrentIrpStackLocation(Irp
);
1199 IoSkipCurrentIrpStackLocation(Irp
);
1201 /* Loop the Stacks and complete the IRPs */
1204 /* Set Pending Returned */
1205 Irp
->PendingReturned
= StackPtr
->Control
& SL_PENDING_RETURNED
;
1207 /* Check if we failed */
1208 if (!NT_SUCCESS(Irp
->IoStatus
.Status
))
1210 /* Check if it was changed by a completion routine */
1211 if (Irp
->IoStatus
.Status
!= ErrorCode
)
1213 /* Update the error for the current stack */
1214 ErrorCode
= Irp
->IoStatus
.Status
;
1215 StackPtr
->Control
|= SL_ERROR_RETURNED
;
1216 LastStackPtr
->Parameters
.Others
.Argument4
= UlongToPtr(ErrorCode
);
1217 LastStackPtr
->Control
|= SL_ERROR_RETURNED
;
1221 /* Check if there is a Completion Routine to Call */
1222 if ((NT_SUCCESS(Irp
->IoStatus
.Status
) &&
1223 (StackPtr
->Control
& SL_INVOKE_ON_SUCCESS
)) ||
1224 (!NT_SUCCESS(Irp
->IoStatus
.Status
) &&
1225 (StackPtr
->Control
& SL_INVOKE_ON_ERROR
)) ||
1227 (StackPtr
->Control
& SL_INVOKE_ON_CANCEL
)))
1229 /* Clear the stack location */
1230 IopClearStackLocation(StackPtr
);
1232 /* Check for highest-level device completion routines */
1233 if (Irp
->CurrentLocation
== (Irp
->StackCount
+ 1))
1235 /* Clear the DO, since the current stack location is invalid */
1236 DeviceObject
= NULL
;
1240 /* Otherwise, return the real one */
1241 DeviceObject
= IoGetCurrentIrpStackLocation(Irp
)->DeviceObject
;
1244 /* Call the completion routine */
1245 Status
= StackPtr
->CompletionRoutine(DeviceObject
,
1249 /* Don't touch the Packet in this case, since it might be gone! */
1250 if (Status
== STATUS_MORE_PROCESSING_REQUIRED
) return;
1254 /* Otherwise, check if this is a completed IRP */
1255 if ((Irp
->CurrentLocation
<= Irp
->StackCount
) &&
1256 (Irp
->PendingReturned
))
1258 /* Mark it as pending */
1259 IoMarkIrpPending(Irp
);
1262 /* Clear the stack location */
1263 IopClearStackLocation(StackPtr
);
1266 /* Move to next stack location and pointer */
1267 IoSkipCurrentIrpStackLocation(Irp
);
1269 } while (Irp
->CurrentLocation
<= (Irp
->StackCount
+ 1));
1271 /* Check if the IRP is an associated IRP */
1272 if (Irp
->Flags
& IRP_ASSOCIATED_IRP
)
1274 /* Get the master IRP and count */
1275 MasterIrp
= Irp
->AssociatedIrp
.MasterIrp
;
1276 MasterCount
= InterlockedDecrement(&MasterIrp
->AssociatedIrp
.IrpCount
);
1279 for (Mdl
= Irp
->MdlAddress
; Mdl
; Mdl
= NextMdl
)
1281 /* Go to the next one */
1282 NextMdl
= Mdl
->Next
;
1286 /* Free the IRP itself */
1289 /* Complete the Master IRP */
1290 if (!MasterCount
) IofCompleteRequest(MasterIrp
, PriorityBoost
);
1294 /* We don't support this yet */
1295 ASSERT(Irp
->IoStatus
.Status
!= STATUS_REPARSE
);
1297 /* Check if we have an auxiliary buffer */
1298 if (Irp
->Tail
.Overlay
.AuxiliaryBuffer
)
1301 ExFreePool(Irp
->Tail
.Overlay
.AuxiliaryBuffer
);
1302 Irp
->Tail
.Overlay
.AuxiliaryBuffer
= NULL
;
1305 /* Check if this is a Paging I/O or Close Operation */
1306 if (Irp
->Flags
& (IRP_PAGING_IO
| IRP_CLOSE_OPERATION
))
1308 /* Handle a Close Operation or Sync Paging I/O */
1309 if (Irp
->Flags
& (IRP_SYNCHRONOUS_PAGING_IO
| IRP_CLOSE_OPERATION
))
1311 /* Set the I/O Status and Signal the Event */
1312 Flags
= Irp
->Flags
& (IRP_SYNCHRONOUS_PAGING_IO
| IRP_PAGING_IO
);
1313 *Irp
->UserIosb
= Irp
->IoStatus
;
1314 KeSetEvent(Irp
->UserEvent
, PriorityBoost
, FALSE
);
1316 /* Free the IRP for a Paging I/O Only, Close is handled by us */
1317 if (Flags
) IoFreeIrp(Irp
);
1323 KeInitializeApc(&Irp
->Tail
.Apc
1324 &Irp
->Tail
.Overlay
.Thread
->Tcb
,
1325 Irp
->ApcEnvironment
,
1326 IopCompletePageWrite
,
1331 KeInsertQueueApc(&Irp
->Tail
.Apc
,
1336 /* Not implemented yet. */
1337 DPRINT1("Not supported!\n");
1342 /* Get out of here */
1346 /* Unlock MDL Pages, page 167. */
1347 Mdl
= Irp
->MdlAddress
;
1354 /* Check if we should exit because of a Deferred I/O (page 168) */
1355 if ((Irp
->Flags
& IRP_DEFER_IO_COMPLETION
) && !(Irp
->PendingReturned
))
1358 * Return without queuing the completion APC, since the caller will
1359 * take care of doing its own optimized completion at PASSIVE_LEVEL.
1364 /* Get the thread and file object */
1365 Thread
= Irp
->Tail
.Overlay
.Thread
;
1366 FileObject
= Irp
->Tail
.Overlay
.OriginalFileObject
;
1368 /* Make sure the IRP isn't canceled */
1371 /* Initialize the APC */
1372 KeInitializeApc(&Irp
->Tail
.Apc
,
1374 Irp
->ApcEnvironment
,
1382 KeInsertQueueApc(&Irp
->Tail
.Apc
,
1384 NULL
, /* This is used for REPARSE stuff */
1389 /* The IRP just got canceled... does a thread still own it? */
1390 Thread
= Irp
->Tail
.Overlay
.Thread
;
1393 /* Yes! There is still hope! Initialize the APC */
1394 KeInitializeApc(&Irp
->Tail
.Apc
,
1396 Irp
->ApcEnvironment
,
1404 KeInsertQueueApc(&Irp
->Tail
.Apc
,
1406 NULL
, /* This is used for REPARSE stuff */
1411 /* Nothing left for us to do, kill it */
1412 ASSERT(Irp
->Cancel
);
1413 IopCleanupIrp(Irp
, FileObject
);
1420 IopSynchronousCompletion(IN PDEVICE_OBJECT DeviceObject
,
1424 if (Irp
->PendingReturned
)
1425 KeSetEvent((PKEVENT
)Context
, IO_NO_INCREMENT
, FALSE
);
1426 return STATUS_MORE_PROCESSING_REQUIRED
;
1434 IoForwardIrpSynchronously(IN PDEVICE_OBJECT DeviceObject
,
1440 /* Check if next stack location is available */
1441 if (Irp
->CurrentLocation
< Irp
->StackCount
)
1443 /* No more stack location */
1447 /* Initialize event */
1448 KeInitializeEvent(&Event
, NotificationEvent
, FALSE
);
1450 /* Copy stack location for next driver */
1451 IoCopyCurrentIrpStackLocationToNext(Irp
);
1453 /* Set a completion routine, which will signal the event */
1454 IoSetCompletionRoutine(Irp
, IopSynchronousCompletion
, &Event
, TRUE
, TRUE
, TRUE
);
1456 /* Call next driver */
1457 Status
= IoCallDriver(DeviceObject
, Irp
);
1459 /* Check if irp is pending */
1460 if (Status
== STATUS_PENDING
)
1462 /* Yes, wait for its completion */
1463 KeWaitForSingleObject(&Event
, Suspended
, KernelMode
, FALSE
, NULL
);
1466 /* Return success */
1475 IoFreeIrp(IN PIRP Irp
)
1477 PNPAGED_LOOKASIDE_LIST List
;
1478 PP_NPAGED_LOOKASIDE_NUMBER ListType
= LookasideSmallIrpList
;
1480 IOTRACE(IO_IRP_DEBUG
,
1481 "%s - Freeing IRPs %p\n",
1485 /* Make sure the Thread IRP list is empty and that it OK to free it */
1486 ASSERT(Irp
->Type
== IO_TYPE_IRP
);
1487 ASSERT(IsListEmpty(&Irp
->ThreadListEntry
));
1488 ASSERT(Irp
->CurrentLocation
>= Irp
->StackCount
);
1490 /* If this was a pool alloc, free it with the pool */
1491 if (!(Irp
->AllocationFlags
& IRP_ALLOCATED_FIXED_SIZE
))
1494 ExFreePoolWithTag(Irp
, TAG_IRP
);
1498 /* Check if this was a Big IRP */
1499 if (Irp
->StackCount
!= 1) ListType
= LookasideLargeIrpList
;
1502 Prcb
= KeGetCurrentPrcb();
1504 /* Use the P List */
1505 List
= (PNPAGED_LOOKASIDE_LIST
)Prcb
->PPLookasideList
[ListType
].P
;
1506 List
->L
.TotalFrees
++;
1508 /* Check if the Free was within the Depth or not */
1509 if (ExQueryDepthSList(&List
->L
.ListHead
) >= List
->L
.Depth
)
1511 /* Let the balancer know */
1512 List
->L
.FreeMisses
++;
1514 /* Use the L List */
1515 List
= (PNPAGED_LOOKASIDE_LIST
)Prcb
->PPLookasideList
[ListType
].L
;
1516 List
->L
.TotalFrees
++;
1518 /* Check if the Free was within the Depth or not */
1519 if (ExQueryDepthSList(&List
->L
.ListHead
) >= List
->L
.Depth
)
1521 /* All lists failed, use the pool */
1522 List
->L
.FreeMisses
++;
1523 ExFreePoolWithTag(Irp
, TAG_IRP
);
1528 /* The free was within the Depth */
1531 InterlockedPushEntrySList(&List
->L
.ListHead
,
1532 (PSINGLE_LIST_ENTRY
)Irp
);
1542 IoGetPagingIoPriority(IN PIRP Irp
)
1544 IO_PAGING_PRIORITY Priority
;
1550 /* Check what priority it has */
1551 if (Flags
& 0x8000) // FIXME: Undocumented flag
1554 Priority
= IoPagingPriorityHigh
;
1556 else if (Flags
& IRP_PAGING_IO
)
1558 /* Normal priority */
1559 Priority
= IoPagingPriorityNormal
;
1563 /* Invalid -- not a paging IRP */
1564 Priority
= IoPagingPriorityInvalid
;
1567 /* Return the priority */
1576 IoGetRequestorProcess(IN PIRP Irp
)
1578 /* Return the requestor process */
1579 return Irp
->Tail
.Overlay
.Thread
->ThreadsProcess
;
1587 IoGetRequestorProcessId(IN PIRP Irp
)
1589 /* Return the requestor process' id */
1590 return PtrToUlong(IoGetRequestorProcess(Irp
)->UniqueProcessId
);
1598 IoGetRequestorSessionId(IN PIRP Irp
,
1599 OUT PULONG pSessionId
)
1601 /* Return the session */
1602 *pSessionId
= IoGetRequestorProcess(Irp
)->Session
;
1603 return STATUS_SUCCESS
;
1611 IoGetTopLevelIrp(VOID
)
1613 /* Return the IRP */
1614 return (PIRP
)PsGetCurrentThread()->TopLevelIrp
;
1622 IoInitializeIrp(IN PIRP Irp
,
1623 IN USHORT PacketSize
,
1627 IOTRACE(IO_IRP_DEBUG
,
1628 "%s - Initializing IRP %p\n",
1631 RtlZeroMemory(Irp
, PacketSize
);
1633 /* Set the Header and other data */
1634 Irp
->Type
= IO_TYPE_IRP
;
1635 Irp
->Size
= PacketSize
;
1636 Irp
->StackCount
= StackSize
;
1637 Irp
->CurrentLocation
= StackSize
+ 1;
1638 Irp
->ApcEnvironment
= KeGetCurrentThread()->ApcStateIndex
;
1639 Irp
->Tail
.Overlay
.CurrentStackLocation
= (PIO_STACK_LOCATION
)(Irp
+ 1) + StackSize
;
1641 /* Initialize the Thread List */
1642 InitializeListHead(&Irp
->ThreadListEntry
);
1650 IoIsOperationSynchronous(IN PIRP Irp
)
1652 /* Check the flags */
1653 if (!(Irp
->Flags
& (IRP_PAGING_IO
| IRP_SYNCHRONOUS_PAGING_IO
)) &&
1654 ((Irp
->Flags
& IRP_SYNCHRONOUS_PAGING_IO
) ||
1655 (Irp
->Flags
& IRP_SYNCHRONOUS_API
) ||
1656 (IoGetCurrentIrpStackLocation(Irp
)->FileObject
->Flags
&
1657 FO_SYNCHRONOUS_IO
)))
1659 /* Synch API or Paging I/O is OK, as is Sync File I/O */
1663 /* Otherwise, it is an asynchronous operation. */
1672 IoIsValidNameGraftingBuffer(IN PIRP Irp
,
1673 IN PREPARSE_DATA_BUFFER ReparseBuffer
)
1684 IoMakeAssociatedIrp(IN PIRP Irp
,
1688 IOTRACE(IO_IRP_DEBUG
,
1689 "%s - Associating IRP %p\n",
1693 /* Allocate the IRP */
1694 AssocIrp
= IoAllocateIrp(StackSize
, FALSE
);
1695 if (!AssocIrp
) return NULL
;
1698 AssocIrp
->Flags
|= IRP_ASSOCIATED_IRP
;
1700 /* Set the Thread */
1701 AssocIrp
->Tail
.Overlay
.Thread
= Irp
->Tail
.Overlay
.Thread
;
1703 /* Associate them */
1704 AssocIrp
->AssociatedIrp
.MasterIrp
= Irp
;
1713 IoQueueThreadIrp(IN PIRP Irp
)
1715 IOTRACE(IO_IRP_DEBUG
,
1716 "%s - Queueing IRP %p\n",
1720 /* Use our inlined routine */
1721 IopQueueIrpToThread(Irp
);
1726 * Reference: Chris Cant's "Writing WDM Device Drivers"
1730 IoReuseIrp(IN OUT PIRP Irp
,
1733 UCHAR AllocationFlags
;
1734 IOTRACE(IO_IRP_DEBUG
,
1735 "%s - Reusing IRP %p\n",
1739 /* Make sure it's OK to reuse it */
1740 ASSERT(!Irp
->CancelRoutine
);
1741 ASSERT(IsListEmpty(&Irp
->ThreadListEntry
));
1743 /* Get the old flags */
1744 AllocationFlags
= Irp
->AllocationFlags
;
1746 /* Reinitialize the IRP */
1747 IoInitializeIrp(Irp
, Irp
->Size
, Irp
->StackCount
);
1749 /* Duplicate the data */
1750 Irp
->IoStatus
.Status
= Status
;
1751 Irp
->AllocationFlags
= AllocationFlags
;
1759 IoSetTopLevelIrp(IN PIRP Irp
)
1762 PsGetCurrentThread()->TopLevelIrp
= (ULONG_PTR
)Irp
;