2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/io/irp.c
5 * PURPOSE: IRP Handling Functions
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
8 * Filip Navara (navaraf@reactos.org)
11 /* INCLUDES ****************************************************************/
15 #include <internal/debug.h>
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 ExFreePoolWithTag(Irp
->AssociatedIrp
.SystemBuffer
, TAG_SYS_BUF
);
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
))
350 if (*((PULONG
)(Irp
->UserEvent
) - 1) != 0x87878787)
352 /* Dereference the event */
353 ObDereferenceObject(Irp
->UserEvent
);
357 DPRINT1("Not an executive event -- should not be dereferenced\n");
362 * Now, if this is a Synch I/O File Object, then this event is
363 * NOT an actual Executive Event, so we won't dereference it,
364 * and instead, we will signal the File Object
366 if ((FileObject
->Flags
& FO_SYNCHRONOUS_IO
) &&
367 !(Irp
->Flags
& IRP_OB_QUERY_NAME
))
369 /* Signal the file object and set the status */
370 KeSetEvent(&FileObject
->Event
, 0, FALSE
);
371 FileObject
->FinalStatus
= Irp
->IoStatus
.Status
;
375 * This could also be a create operation, in which case we want
376 * to make sure there's no APC fired.
378 if (Irp
->Flags
& IRP_CREATE_OPERATION
)
380 /* Clear the APC Routine and remember this */
381 Irp
->Overlay
.AsynchronousParameters
.UserApcRoutine
= NULL
;
382 SignaledCreateRequest
= TRUE
;
388 /* Signal the file object and set the status */
389 KeSetEvent(&FileObject
->Event
, 0, FALSE
);
390 FileObject
->FinalStatus
= Irp
->IoStatus
.Status
;
393 * This could also be a create operation, in which case we want
394 * to make sure there's no APC fired.
396 if (Irp
->Flags
& IRP_CREATE_OPERATION
)
398 /* Clear the APC Routine and remember this */
399 Irp
->Overlay
.AsynchronousParameters
.UserApcRoutine
= NULL
;
400 SignaledCreateRequest
= TRUE
;
404 /* Now that we've signaled the events, de-associate the IRP */
405 IopUnQueueIrpFromThread(Irp
);
407 /* Now check if a User APC Routine was requested */
408 if (Irp
->Overlay
.AsynchronousParameters
.UserApcRoutine
)
411 KeInitializeApc(&Irp
->Tail
.Apc
,
412 KeGetCurrentThread(),
413 CurrentApcEnvironment
,
415 IopAbortIrpKernelApc
,
416 (PKNORMAL_ROUTINE
)Irp
->
417 Overlay
.AsynchronousParameters
.UserApcRoutine
,
420 Overlay
.AsynchronousParameters
.UserApcContext
);
423 KeInsertQueueApc(&Irp
->Tail
.Apc
, Irp
->UserIosb
, NULL
, 2);
426 (Irp
->Overlay
.AsynchronousParameters
.UserApcContext
))
428 /* We have an I/O Completion setup... create the special Overlay */
429 Irp
->Tail
.CompletionKey
= Key
;
430 Irp
->Tail
.Overlay
.PacketType
= IrpCompletionPacket
;
431 KeInsertQueue(Port
, &Irp
->Tail
.Overlay
.ListEntry
);
435 /* Free the IRP since we don't need it anymore */
439 /* Check if we have a file object that wasn't part of a create */
440 if ((FileObject
) && !(SignaledCreateRequest
))
442 /* Dereference it, since it's not needed anymore either */
443 ObDereferenceObjectDeferDelete(FileObject
);
449 * Either we didn't return from the request, or we did return but this
450 * request was synchronous.
452 if ((Irp
->PendingReturned
) && (FileObject
))
454 /* So we did return with a synch operation, was it the IRP? */
455 if (Irp
->Flags
& IRP_SYNCHRONOUS_API
)
457 /* Yes, this IRP was synchronous, so return the I/O Status */
458 *Irp
->UserIosb
= Irp
->IoStatus
;
460 /* Now check if the user gave an event */
464 KeSetEvent(Irp
->UserEvent
, 0, FALSE
);
468 /* No event was given, so signal the FO instead */
469 KeSetEvent(&FileObject
->Event
, 0, FALSE
);
475 * It's not the IRP that was synchronous, it was the FO
476 * that was opened this way. Signal its event.
478 FileObject
->FinalStatus
= Irp
->IoStatus
.Status
;
479 KeSetEvent(&FileObject
->Event
, 0, FALSE
);
483 /* Now that we got here, we do this for incomplete I/Os as well */
484 if ((FileObject
) && !(Irp
->Flags
& IRP_CREATE_OPERATION
))
486 /* Dereference the File Object unless this was a create */
487 ObDereferenceObjectDeferDelete(FileObject
);
491 * Check if this was an Executive Event (remember that we know this
492 * by checking if the IRP is synchronous)
494 if ((Irp
->UserEvent
) &&
496 !(Irp
->Flags
& IRP_SYNCHRONOUS_API
))
498 /* This isn't a PKEVENT, so dereference it */
499 ObDereferenceObject(Irp
->UserEvent
);
502 /* Now that we've signaled the events, de-associate the IRP */
503 IopUnQueueIrpFromThread(Irp
);
505 /* Free the IRP as well */
510 /* FUNCTIONS *****************************************************************/
517 IoAllocateIrp(IN CCHAR StackSize
,
518 IN BOOLEAN ChargeQuota
)
521 USHORT Size
= IoSizeOfIrp(StackSize
);
524 PNPAGED_LOOKASIDE_LIST List
= NULL
;
525 PP_NPAGED_LOOKASIDE_NUMBER ListType
= LookasideSmallIrpList
;
527 /* Figure out which Lookaside List to use */
528 if ((StackSize
<= 8) && (ChargeQuota
== FALSE
))
530 /* Set Fixed Size Flag */
531 Flags
= IRP_ALLOCATED_FIXED_SIZE
;
533 /* See if we should use big list */
536 Size
= IoSizeOfIrp(8);
537 ListType
= LookasideLargeIrpList
;
541 Prcb
= KeGetCurrentPrcb();
543 /* Get the P List First */
544 List
= (PNPAGED_LOOKASIDE_LIST
)Prcb
->PPLookasideList
[ListType
].P
;
546 /* Attempt allocation */
547 List
->L
.TotalAllocates
++;
548 Irp
= (PIRP
)InterlockedPopEntrySList(&List
->L
.ListHead
);
550 /* Check if the P List failed */
553 /* Let the balancer know */
554 List
->L
.AllocateMisses
++;
557 List
= (PNPAGED_LOOKASIDE_LIST
)Prcb
->PPLookasideList
[ListType
].L
;
558 List
->L
.TotalAllocates
++;
559 Irp
= (PIRP
)InterlockedPopEntrySList(&List
->L
.ListHead
);
563 /* Check if we have to use the pool */
566 /* Did we try lookaside and fail? */
567 if (Flags
& IRP_ALLOCATED_FIXED_SIZE
) List
->L
.AllocateMisses
++;
569 /* Check if we should charge quota */
572 /* Irp = ExAllocatePoolWithQuotaTag(NonPagedPool, Size, TAG_IRP); */
574 Irp
= ExAllocatePoolWithTag(NonPagedPool
, Size
, TAG_IRP
);
578 /* Allocate the IRP With no Quota charge */
579 Irp
= ExAllocatePoolWithTag(NonPagedPool
, Size
, TAG_IRP
);
582 /* Make sure it was sucessful */
583 if (!Irp
) return(NULL
);
587 /* We have an IRP from Lookaside */
588 Flags
|= IRP_LOOKASIDE_ALLOCATION
;
592 if (ChargeQuota
) Flags
|= IRP_QUOTA_CHARGED
;
594 /* Now Initialize it */
595 IoInitializeIrp(Irp
, Size
, StackSize
);
597 /* Set the Allocation Flags */
598 Irp
->AllocationFlags
= Flags
;
601 IOTRACE(IO_IRP_DEBUG
,
602 "%s - Allocated IRP %p with allocation flags %lx\n",
614 IoBuildAsynchronousFsdRequest(IN ULONG MajorFunction
,
615 IN PDEVICE_OBJECT DeviceObject
,
618 IN PLARGE_INTEGER StartingOffset
,
619 IN PIO_STATUS_BLOCK IoStatusBlock
)
622 PIO_STACK_LOCATION StackPtr
;
625 Irp
= IoAllocateIrp(DeviceObject
->StackSize
, FALSE
);
626 if (!Irp
) return Irp
;
629 StackPtr
= IoGetNextIrpStackLocation(Irp
);
631 /* Write the Major function and then deal with it */
632 StackPtr
->MajorFunction
= (UCHAR
)MajorFunction
;
634 /* Do not handle the following here */
635 if ((MajorFunction
!= IRP_MJ_FLUSH_BUFFERS
) &&
636 (MajorFunction
!= IRP_MJ_SHUTDOWN
) &&
637 (MajorFunction
!= IRP_MJ_PNP
) &&
638 (MajorFunction
!= IRP_MJ_POWER
))
640 /* Check if this is Buffered IO */
641 if (DeviceObject
->Flags
& DO_BUFFERED_IO
)
643 /* Allocate the System Buffer */
644 Irp
->AssociatedIrp
.SystemBuffer
=
645 ExAllocatePoolWithTag(NonPagedPool
, Length
, TAG_SYS_BUF
);
646 if (!Irp
->AssociatedIrp
.SystemBuffer
)
648 /* Free the IRP and fail */
654 Irp
->Flags
= IRP_BUFFERED_IO
| IRP_DEALLOCATE_BUFFER
;
656 /* Handle special IRP_MJ_WRITE Case */
657 if (MajorFunction
== IRP_MJ_WRITE
)
659 /* Copy the buffer data */
660 RtlCopyMemory(Irp
->AssociatedIrp
.SystemBuffer
, Buffer
, Length
);
664 /* Set the Input Operation flag and set this as a User Buffer */
665 Irp
->Flags
|= IRP_INPUT_OPERATION
;
666 Irp
->UserBuffer
= Buffer
;
669 else if (DeviceObject
->Flags
& DO_DIRECT_IO
)
671 /* Use an MDL for Direct I/O */
672 Irp
->MdlAddress
= IoAllocateMdl(Buffer
,
677 if (!Irp
->MdlAddress
)
679 /* Free the IRP and fail */
688 MmProbeAndLockPages(Irp
->MdlAddress
,
690 MajorFunction
== IRP_MJ_READ
?
691 IoWriteAccess
: IoReadAccess
);
695 /* Free the IRP and its MDL */
696 IoFreeMdl(Irp
->MdlAddress
);
702 /* This is how we know if we failed during the probe */
703 if (!Irp
) return NULL
;
707 /* Neither, use the buffer */
708 Irp
->UserBuffer
= Buffer
;
711 /* Check if this is a read */
712 if (MajorFunction
== IRP_MJ_READ
)
714 /* Set the parameters for a read */
715 StackPtr
->Parameters
.Read
.Length
= Length
;
716 StackPtr
->Parameters
.Read
.ByteOffset
= *StartingOffset
;
718 else if (MajorFunction
== IRP_MJ_WRITE
)
720 /* Otherwise, set write parameters */
721 StackPtr
->Parameters
.Write
.Length
= Length
;
722 StackPtr
->Parameters
.Write
.ByteOffset
= *StartingOffset
;
726 /* Set the Current Thread and IOSB */
727 Irp
->UserIosb
= IoStatusBlock
;
728 Irp
->Tail
.Overlay
.Thread
= PsGetCurrentThread();
730 /* Set the Status Block after all is done */
731 IOTRACE(IO_IRP_DEBUG
,
732 "%s - Built IRP %p with Major, Buffer, DO %lx %p %p\n",
746 IoBuildDeviceIoControlRequest(IN ULONG IoControlCode
,
747 IN PDEVICE_OBJECT DeviceObject
,
748 IN PVOID InputBuffer
,
749 IN ULONG InputBufferLength
,
750 IN PVOID OutputBuffer
,
751 IN ULONG OutputBufferLength
,
752 IN BOOLEAN InternalDeviceIoControl
,
754 IN PIO_STATUS_BLOCK IoStatusBlock
)
757 PIO_STACK_LOCATION StackPtr
;
761 Irp
= IoAllocateIrp(DeviceObject
->StackSize
, FALSE
);
762 if (!Irp
) return Irp
;
765 StackPtr
= IoGetNextIrpStackLocation(Irp
);
767 /* Set the DevCtl Type */
768 StackPtr
->MajorFunction
= InternalDeviceIoControl
?
769 IRP_MJ_INTERNAL_DEVICE_CONTROL
:
770 IRP_MJ_DEVICE_CONTROL
;
772 /* Set the IOCTL Data */
773 StackPtr
->Parameters
.DeviceIoControl
.IoControlCode
= IoControlCode
;
774 StackPtr
->Parameters
.DeviceIoControl
.InputBufferLength
= InputBufferLength
;
775 StackPtr
->Parameters
.DeviceIoControl
.OutputBufferLength
=
778 /* Handle the Methods */
779 switch (IO_METHOD_FROM_CTL_CODE(IoControlCode
))
782 case METHOD_BUFFERED
:
784 /* Select the right Buffer Length */
785 BufferLength
= InputBufferLength
> OutputBufferLength
?
786 InputBufferLength
: OutputBufferLength
;
788 /* Make sure there is one */
791 /* Allocate the System Buffer */
792 Irp
->AssociatedIrp
.SystemBuffer
=
793 ExAllocatePoolWithTag(NonPagedPool
,
796 if (!Irp
->AssociatedIrp
.SystemBuffer
)
798 /* Free the IRP and fail */
803 /* Check if we got a buffer */
806 /* Copy into the System Buffer */
807 RtlCopyMemory(Irp
->AssociatedIrp
.SystemBuffer
,
812 /* Write the flags */
813 Irp
->Flags
= IRP_BUFFERED_IO
| IRP_DEALLOCATE_BUFFER
;
814 if (OutputBuffer
) Irp
->Flags
|= IRP_INPUT_OPERATION
;
816 /* Save the Buffer */
817 Irp
->UserBuffer
= OutputBuffer
;
821 /* Clear the Flags and Buffer */
823 Irp
->UserBuffer
= NULL
;
828 case METHOD_IN_DIRECT
:
829 case METHOD_OUT_DIRECT
:
831 /* Check if we got an input buffer */
834 /* Allocate the System Buffer */
835 Irp
->AssociatedIrp
.SystemBuffer
=
836 ExAllocatePoolWithTag(NonPagedPool
,
839 if (!Irp
->AssociatedIrp
.SystemBuffer
)
841 /* Free the IRP and fail */
846 /* Copy into the System Buffer */
847 RtlCopyMemory(Irp
->AssociatedIrp
.SystemBuffer
,
851 /* Write the flags */
852 Irp
->Flags
= IRP_BUFFERED_IO
| IRP_DEALLOCATE_BUFFER
;
859 /* Check if we got an output buffer */
862 /* Allocate the System Buffer */
863 Irp
->MdlAddress
= IoAllocateMdl(OutputBuffer
,
868 if (!Irp
->MdlAddress
)
870 /* Free the IRP and fail */
879 MmProbeAndLockPages(Irp
->MdlAddress
,
881 IO_METHOD_FROM_CTL_CODE(IoControlCode
) ==
883 IoReadAccess
: IoWriteAccess
);
888 IoFreeMdl(Irp
->MdlAddress
);
890 /* Free the input buffer and IRP */
891 if (InputBuffer
) ExFreePool(Irp
->AssociatedIrp
.SystemBuffer
);
897 /* This is how we know if probing failed */
898 if (!Irp
) return NULL
;
904 /* Just save the Buffer */
905 Irp
->UserBuffer
= OutputBuffer
;
906 StackPtr
->Parameters
.DeviceIoControl
.Type3InputBuffer
= InputBuffer
;
909 /* Now write the Event and IoSB */
910 Irp
->UserIosb
= IoStatusBlock
;
911 Irp
->UserEvent
= Event
;
913 /* Sync IRPs are queued to requestor thread's irp cancel/cleanup list */
914 Irp
->Tail
.Overlay
.Thread
= PsGetCurrentThread();
915 IoQueueThreadIrp(Irp
);
918 IOTRACE(IO_IRP_DEBUG
,
919 "%s - Built IRP %p with IOCTL, Buffers, DO %lx %p %p %p\n",
934 IoBuildSynchronousFsdRequest(IN ULONG MajorFunction
,
935 IN PDEVICE_OBJECT DeviceObject
,
938 IN PLARGE_INTEGER StartingOffset
,
940 IN PIO_STATUS_BLOCK IoStatusBlock
)
944 /* Do the big work to set up the IRP */
945 Irp
= IoBuildAsynchronousFsdRequest(MajorFunction
,
951 if (!Irp
) return NULL
;
953 /* Set the Event which makes it Syncronous */
954 Irp
->UserEvent
= Event
;
956 /* Sync IRPs are queued to requestor thread's irp cancel/cleanup list */
957 IoQueueThreadIrp(Irp
);
966 IoCancelIrp(IN PIRP Irp
)
969 PDRIVER_CANCEL CancelRoutine
;
970 IOTRACE(IO_IRP_DEBUG
,
971 "%s - Canceling IRP %p\n",
974 ASSERT(Irp
->Type
== IO_TYPE_IRP
);
976 /* Acquire the cancel lock and cancel the IRP */
977 IoAcquireCancelSpinLock(&OldIrql
);
980 /* Clear the cancel routine and get the old one */
981 CancelRoutine
= IoSetCancelRoutine(Irp
, NULL
);
984 /* We had a routine, make sure the IRP isn't completed */
985 if (Irp
->CurrentLocation
> (Irp
->StackCount
+ 1))
987 /* It is, bugcheck */
988 KeBugCheckEx(CANCEL_STATE_IN_COMPLETED_IRP
,
995 /* Set the cancel IRQL And call the routine */
996 Irp
->CancelIrql
= OldIrql
;
997 CancelRoutine(IoGetCurrentIrpStackLocation(Irp
)->DeviceObject
, Irp
);
1001 /* Otherwise, release the cancel lock and fail */
1002 IoReleaseCancelSpinLock(OldIrql
);
1011 IoCancelThreadIo(IN PETHREAD Thread
)
1014 ULONG Retries
= 3000;
1015 LARGE_INTEGER Interval
;
1016 PLIST_ENTRY ListHead
, NextEntry
;
1018 IOTRACE(IO_IRP_DEBUG
,
1019 "%s - Canceling IRPs for Thread %p\n",
1023 /* Raise to APC to protect the IrpList */
1024 OldIrql
= KfRaiseIrql(APC_LEVEL
);
1026 /* Start by cancelling all the IRPs in the current thread queue. */
1027 ListHead
= &Thread
->IrpList
;
1028 NextEntry
= ListHead
->Flink
;
1029 while (ListHead
!= NextEntry
)
1032 Irp
= CONTAINING_RECORD(NextEntry
, IRP
, ThreadListEntry
);
1037 /* Move to the next entry */
1038 NextEntry
= NextEntry
->Flink
;
1041 /* Wait 100 milliseconds */
1042 Interval
.QuadPart
= -1000000;
1044 /* Wait till all the IRPs are completed or cancelled. */
1045 while (!IsListEmpty(&Thread
->IrpList
))
1047 /* Now we can lower */
1048 KfLowerIrql(OldIrql
);
1050 /* Wait a short while and then look if all our IRPs were completed. */
1051 KeDelayExecutionThread(KernelMode
, FALSE
, &Interval
);
1054 * Don't stay here forever if some broken driver doesn't complete
1057 if (!(Retries
--)) IopRemoveThreadIrp();
1059 /* Raise the IRQL Again */
1060 OldIrql
= KfRaiseIrql(APC_LEVEL
);
1063 /* We're done, lower the IRQL */
1064 KfLowerIrql(OldIrql
);
1072 IoCallDriver(IN PDEVICE_OBJECT DeviceObject
,
1075 /* Call fast call */
1076 return IofCallDriver(DeviceObject
, Irp
);
1084 IoCompleteRequest(IN PIRP Irp
,
1085 IN CCHAR PriorityBoost
)
1087 /* Call the fastcall */
1088 IofCompleteRequest(Irp
, PriorityBoost
);
1096 IoEnqueueIrp(IN PIRP Irp
)
1098 /* This is the same as calling IoQueueThreadIrp */
1099 IoQueueThreadIrp(Irp
);
1107 IofCallDriver(IN PDEVICE_OBJECT DeviceObject
,
1110 PDRIVER_OBJECT DriverObject
;
1111 PIO_STACK_LOCATION Param
;
1113 /* Get the Driver Object */
1114 DriverObject
= DeviceObject
->DriverObject
;
1116 /* Decrease the current location and check if */
1117 Irp
->CurrentLocation
--;
1118 if (Irp
->CurrentLocation
<= 0)
1120 /* This IRP ran out of stack, bugcheck */
1121 KeBugCheckEx(NO_MORE_IRP_STACK_LOCATIONS
, (ULONG_PTR
)Irp
, 0, 0, 0);
1124 /* Now update the stack location */
1125 Param
= IoGetNextIrpStackLocation(Irp
);
1126 Irp
->Tail
.Overlay
.CurrentStackLocation
= Param
;
1128 /* Get the Device Object */
1129 Param
->DeviceObject
= DeviceObject
;
1132 return DriverObject
->MajorFunction
[Param
->MajorFunction
](DeviceObject
,
1138 IopClearStackLocation(IN PIO_STACK_LOCATION IoStackLocation
)
1140 IoStackLocation
->MinorFunction
= 0;
1141 IoStackLocation
->Flags
= 0;
1142 IoStackLocation
->Control
&= SL_ERROR_RETURNED
;
1143 IoStackLocation
->Parameters
.Others
.Argument1
= 0;
1144 IoStackLocation
->Parameters
.Others
.Argument2
= 0;
1145 IoStackLocation
->Parameters
.Others
.Argument3
= 0;
1146 IoStackLocation
->FileObject
= NULL
;
1154 IofCompleteRequest(IN PIRP Irp
,
1155 IN CCHAR PriorityBoost
)
1157 PIO_STACK_LOCATION StackPtr
, LastStackPtr
;
1158 PDEVICE_OBJECT DeviceObject
;
1159 PFILE_OBJECT FileObject
;
1166 NTSTATUS ErrorCode
= STATUS_SUCCESS
;
1167 IOTRACE(IO_IRP_DEBUG
,
1168 "%s - Completing IRP %p\n",
1172 /* Make sure this IRP isn't getting completed twice or is invalid */
1173 if ((Irp
->CurrentLocation
) > (Irp
->StackCount
+ 1))
1176 KeBugCheckEx(MULTIPLE_IRP_COMPLETE_REQUESTS
, (ULONG_PTR
)Irp
, 0, 0, 0);
1179 /* Some sanity checks */
1180 ASSERT(Irp
->Type
== IO_TYPE_IRP
);
1181 ASSERT(!Irp
->CancelRoutine
);
1182 ASSERT(Irp
->IoStatus
.Status
!= STATUS_PENDING
);
1183 ASSERT(Irp
->IoStatus
.Status
!= 0xFFFFFFFF);
1185 /* Get the last stack */
1186 LastStackPtr
= (PIO_STACK_LOCATION
)(Irp
+ 1);
1187 if (LastStackPtr
->Control
& SL_ERROR_RETURNED
)
1189 /* Get the error code */
1190 ErrorCode
= (NTSTATUS
)LastStackPtr
->Parameters
.Others
.Argument4
;
1193 /* Get the Current Stack and skip it */
1194 StackPtr
= IoGetCurrentIrpStackLocation(Irp
);
1195 IoSkipCurrentIrpStackLocation(Irp
);
1197 /* Loop the Stacks and complete the IRPs */
1200 /* Set Pending Returned */
1201 Irp
->PendingReturned
= StackPtr
->Control
& SL_PENDING_RETURNED
;
1203 /* Check if we failed */
1204 if (!NT_SUCCESS(Irp
->IoStatus
.Status
))
1206 /* Check if it was changed by a completion routine */
1207 if (Irp
->IoStatus
.Status
!= ErrorCode
)
1209 /* Update the error for the current stack */
1210 ErrorCode
= Irp
->IoStatus
.Status
;
1211 StackPtr
->Control
|= SL_ERROR_RETURNED
;
1212 LastStackPtr
->Parameters
.Others
.Argument4
= (PVOID
)ErrorCode
;
1213 LastStackPtr
->Control
|= SL_ERROR_RETURNED
;
1217 /* Check if there is a Completion Routine to Call */
1218 if ((NT_SUCCESS(Irp
->IoStatus
.Status
) &&
1219 (StackPtr
->Control
& SL_INVOKE_ON_SUCCESS
)) ||
1220 (!NT_SUCCESS(Irp
->IoStatus
.Status
) &&
1221 (StackPtr
->Control
& SL_INVOKE_ON_ERROR
)) ||
1223 (StackPtr
->Control
& SL_INVOKE_ON_CANCEL
)))
1225 /* Clear the stack location */
1226 IopClearStackLocation(StackPtr
);
1228 /* Check for highest-level device completion routines */
1229 if (Irp
->CurrentLocation
== (Irp
->StackCount
+ 1))
1231 /* Clear the DO, since the current stack location is invalid */
1232 DeviceObject
= NULL
;
1236 /* Otherwise, return the real one */
1237 DeviceObject
= IoGetCurrentIrpStackLocation(Irp
)->DeviceObject
;
1240 /* Call the completion routine */
1241 Status
= StackPtr
->CompletionRoutine(DeviceObject
,
1245 /* Don't touch the Packet in this case, since it might be gone! */
1246 if (Status
== STATUS_MORE_PROCESSING_REQUIRED
) return;
1250 /* Otherwise, check if this is a completed IRP */
1251 if ((Irp
->CurrentLocation
<= Irp
->StackCount
) &&
1252 (Irp
->PendingReturned
))
1254 /* Mark it as pending */
1255 IoMarkIrpPending(Irp
);
1258 /* Clear the stack location */
1259 IopClearStackLocation(StackPtr
);
1262 /* Move to next stack location and pointer */
1263 IoSkipCurrentIrpStackLocation(Irp
);
1265 } while (Irp
->CurrentLocation
<= (Irp
->StackCount
+ 1));
1267 /* Check if the IRP is an associated IRP */
1268 if (Irp
->Flags
& IRP_ASSOCIATED_IRP
)
1270 /* Get the master IRP and count */
1271 MasterIrp
= Irp
->AssociatedIrp
.MasterIrp
;
1272 MasterCount
= InterlockedDecrement(&MasterIrp
->AssociatedIrp
.IrpCount
);
1275 for (Mdl
= Irp
->MdlAddress
; Mdl
; Mdl
= NextMdl
)
1277 /* Go to the next one */
1278 NextMdl
= Mdl
->Next
;
1282 /* Free the IRP itself */
1285 /* Complete the Master IRP */
1286 if (!MasterCount
) IofCompleteRequest(MasterIrp
, PriorityBoost
);
1290 /* We don't support this yet */
1291 ASSERT(Irp
->IoStatus
.Status
!= STATUS_REPARSE
);
1293 /* Check if we have an auxiliary buffer */
1294 if (Irp
->Tail
.Overlay
.AuxiliaryBuffer
)
1297 ExFreePool(Irp
->Tail
.Overlay
.AuxiliaryBuffer
);
1298 Irp
->Tail
.Overlay
.AuxiliaryBuffer
= NULL
;
1301 /* Check if this is a Paging I/O or Close Operation */
1302 if (Irp
->Flags
& (IRP_PAGING_IO
| IRP_CLOSE_OPERATION
))
1304 /* Handle a Close Operation or Sync Paging I/O */
1305 if (Irp
->Flags
& (IRP_SYNCHRONOUS_PAGING_IO
| IRP_CLOSE_OPERATION
))
1307 /* Set the I/O Status and Signal the Event */
1308 Flags
= Irp
->Flags
& (IRP_SYNCHRONOUS_PAGING_IO
| IRP_PAGING_IO
);
1309 *Irp
->UserIosb
= Irp
->IoStatus
;
1310 KeSetEvent(Irp
->UserEvent
, PriorityBoost
, FALSE
);
1312 /* Free the IRP for a Paging I/O Only, Close is handled by us */
1313 if (Flags
) IoFreeIrp(Irp
);
1319 KeInitializeApc(&Irp
->Tail
.Apc
1320 &Irp
->Tail
.Overlay
.Thread
->Tcb
,
1321 Irp
->ApcEnvironment
,
1322 IopCompletePageWrite
,
1327 KeInsertQueueApc(&Irp
->Tail
.Apc
,
1332 /* Not implemented yet. */
1333 DPRINT1("Not supported!\n");
1338 /* Get out of here */
1342 /* Unlock MDL Pages, page 167. */
1343 Mdl
= Irp
->MdlAddress
;
1350 /* Check if we should exit because of a Deferred I/O (page 168) */
1351 if ((Irp
->Flags
& IRP_DEFER_IO_COMPLETION
) && !(Irp
->PendingReturned
))
1354 * Return without queuing the completion APC, since the caller will
1355 * take care of doing its own optimized completion at PASSIVE_LEVEL.
1360 /* Get the thread and file object */
1361 Thread
= Irp
->Tail
.Overlay
.Thread
;
1362 FileObject
= Irp
->Tail
.Overlay
.OriginalFileObject
;
1364 /* Make sure the IRP isn't canceled */
1367 /* Initialize the APC */
1368 KeInitializeApc(&Irp
->Tail
.Apc
,
1370 Irp
->ApcEnvironment
,
1378 KeInsertQueueApc(&Irp
->Tail
.Apc
,
1380 NULL
, /* This is used for REPARSE stuff */
1385 /* The IRP just got canceled... does a thread still own it? */
1386 Thread
= Irp
->Tail
.Overlay
.Thread
;
1389 /* Yes! There is still hope! Initialize the APC */
1390 KeInitializeApc(&Irp
->Tail
.Apc
,
1392 Irp
->ApcEnvironment
,
1400 KeInsertQueueApc(&Irp
->Tail
.Apc
,
1402 NULL
, /* This is used for REPARSE stuff */
1407 /* Nothing left for us to do, kill it */
1408 ASSERT(Irp
->Cancel
);
1409 IopCleanupIrp(Irp
, FileObject
);
1419 IoForwardIrpSynchronously(IN PDEVICE_OBJECT DeviceObject
,
1431 IoFreeIrp(IN PIRP Irp
)
1433 PNPAGED_LOOKASIDE_LIST List
;
1434 PP_NPAGED_LOOKASIDE_NUMBER ListType
= LookasideSmallIrpList
;
1436 IOTRACE(IO_IRP_DEBUG
,
1437 "%s - Freeing IRPs %p\n",
1441 /* Make sure the Thread IRP list is empty and that it OK to free it */
1442 ASSERT(Irp
->Type
== IO_TYPE_IRP
);
1443 ASSERT(IsListEmpty(&Irp
->ThreadListEntry
));
1444 ASSERT(Irp
->CurrentLocation
>= Irp
->StackCount
);
1446 /* If this was a pool alloc, free it with the pool */
1447 if (!(Irp
->AllocationFlags
& IRP_ALLOCATED_FIXED_SIZE
))
1454 /* Check if this was a Big IRP */
1455 if (Irp
->StackCount
!= 1) ListType
= LookasideLargeIrpList
;
1458 Prcb
= KeGetCurrentPrcb();
1460 /* Use the P List */
1461 List
= (PNPAGED_LOOKASIDE_LIST
)Prcb
->PPLookasideList
[ListType
].P
;
1462 List
->L
.TotalFrees
++;
1464 /* Check if the Free was within the Depth or not */
1465 if (ExQueryDepthSList(&List
->L
.ListHead
) >= List
->L
.Depth
)
1467 /* Let the balancer know */
1468 List
->L
.FreeMisses
++;
1470 /* Use the L List */
1471 List
= (PNPAGED_LOOKASIDE_LIST
)Prcb
->PPLookasideList
[ListType
].L
;
1472 List
->L
.TotalFrees
++;
1474 /* Check if the Free was within the Depth or not */
1475 if (ExQueryDepthSList(&List
->L
.ListHead
) >= List
->L
.Depth
)
1477 /* All lists failed, use the pool */
1478 List
->L
.FreeMisses
++;
1484 /* The free was within the Depth */
1487 InterlockedPushEntrySList(&List
->L
.ListHead
,
1488 (PSINGLE_LIST_ENTRY
)Irp
);
1497 IoGetRequestorProcess(IN PIRP Irp
)
1499 return(Irp
->Tail
.Overlay
.Thread
->ThreadsProcess
);
1507 IoGetRequestorProcessId(IN PIRP Irp
)
1509 return (ULONG
)(IoGetRequestorProcess(Irp
)->UniqueProcessId
);
1517 IoGetRequestorSessionId(IN PIRP Irp
,
1518 OUT PULONG pSessionId
)
1520 /* Return the session */
1521 *pSessionId
= IoGetRequestorProcess(Irp
)->Session
;
1522 return STATUS_SUCCESS
;
1530 IoGetTopLevelIrp(VOID
)
1532 return (PIRP
)PsGetCurrentThread()->TopLevelIrp
;
1540 IoInitializeIrp(IN PIRP Irp
,
1541 IN USHORT PacketSize
,
1545 IOTRACE(IO_IRP_DEBUG
,
1546 "%s - Initializing IRP %p\n",
1549 RtlZeroMemory(Irp
, PacketSize
);
1551 /* Set the Header and other data */
1552 Irp
->Type
= IO_TYPE_IRP
;
1553 Irp
->Size
= PacketSize
;
1554 Irp
->StackCount
= StackSize
;
1555 Irp
->CurrentLocation
= StackSize
+ 1;
1556 Irp
->ApcEnvironment
= KeGetCurrentThread()->ApcStateIndex
;
1557 Irp
->Tail
.Overlay
.CurrentStackLocation
= (PIO_STACK_LOCATION
)(Irp
+ 1) + StackSize
;
1559 /* Initialize the Thread List */
1560 InitializeListHead(&Irp
->ThreadListEntry
);
1568 IoIsOperationSynchronous(IN PIRP Irp
)
1570 /* Check the flags */
1571 if (!(Irp
->Flags
& (IRP_PAGING_IO
| IRP_SYNCHRONOUS_PAGING_IO
)) &&
1572 ((Irp
->Flags
& IRP_SYNCHRONOUS_PAGING_IO
) ||
1573 (Irp
->Flags
& IRP_SYNCHRONOUS_API
) ||
1574 (IoGetCurrentIrpStackLocation(Irp
)->FileObject
->Flags
&
1575 FO_SYNCHRONOUS_IO
)))
1577 /* Synch API or Paging I/O is OK, as is Sync File I/O */
1581 /* Otherwise, it is an asynchronous operation. */
1590 IoIsValidNameGraftingBuffer(IN PIRP Irp
,
1591 IN PREPARSE_DATA_BUFFER ReparseBuffer
)
1602 IoMakeAssociatedIrp(IN PIRP Irp
,
1606 IOTRACE(IO_IRP_DEBUG
,
1607 "%s - Associating IRP %p\n",
1611 /* Allocate the IRP */
1612 AssocIrp
= IoAllocateIrp(StackSize
, FALSE
);
1613 if (!AssocIrp
) return NULL
;
1616 AssocIrp
->Flags
|= IRP_ASSOCIATED_IRP
;
1618 /* Set the Thread */
1619 AssocIrp
->Tail
.Overlay
.Thread
= Irp
->Tail
.Overlay
.Thread
;
1621 /* Associate them */
1622 AssocIrp
->AssociatedIrp
.MasterIrp
= Irp
;
1631 IoQueueThreadIrp(IN PIRP Irp
)
1633 IOTRACE(IO_IRP_DEBUG
,
1634 "%s - Queueing IRP %p\n",
1638 /* Use our inlined routine */
1639 IopQueueIrpToThread(Irp
);
1644 * Reference: Chris Cant's "Writing WDM Device Drivers"
1648 IoReuseIrp(IN OUT PIRP Irp
,
1651 UCHAR AllocationFlags
;
1652 IOTRACE(IO_IRP_DEBUG
,
1653 "%s - Reusing IRP %p\n",
1657 /* Make sure it's OK to reuse it */
1658 ASSERT(!Irp
->CancelRoutine
);
1659 ASSERT(IsListEmpty(&Irp
->ThreadListEntry
));
1661 /* Get the old flags */
1662 AllocationFlags
= Irp
->AllocationFlags
;
1664 /* Reinitialize the IRP */
1665 IoInitializeIrp(Irp
, Irp
->Size
, Irp
->StackCount
);
1667 /* Duplicate the data */
1668 Irp
->IoStatus
.Status
= Status
;
1669 Irp
->AllocationFlags
= AllocationFlags
;
1677 IoSetTopLevelIrp(IN PIRP Irp
)
1680 PsGetCurrentThread()->TopLevelIrp
= (ULONG
)Irp
;