Bugfix ntoskrnl : IoBuildAsynchronousFsdRequest the param DeviceObject, can be NULL...
[reactos.git] / reactos / ntoskrnl / io / iomgr / irp.c
1 /*
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)
7 * Gunnar Dalsnes
8 * Filip Navara (navaraf@reactos.org)
9 */
10
11 /* INCLUDES ****************************************************************/
12
13 #include <ntoskrnl.h>
14 #define NDEBUG
15 #include <internal/debug.h>
16
17 /* Undefine some macros we implement here */
18 #undef IoCallDriver
19 #undef IoCompleteRequest
20
21 /* PRIVATE FUNCTIONS ********************************************************/
22
23 VOID
24 NTAPI
25 IopFreeIrpKernelApc(IN PKAPC Apc,
26 IN PKNORMAL_ROUTINE *NormalRoutine,
27 IN PVOID *NormalContext,
28 IN PVOID *SystemArgument1,
29 IN PVOID *SystemArgument2)
30 {
31 /* Free the IRP */
32 IoFreeIrp(CONTAINING_RECORD(Apc, IRP, Tail.Apc));
33 }
34
35 VOID
36 NTAPI
37 IopAbortIrpKernelApc(IN PKAPC Apc)
38 {
39 /* Free the IRP */
40 IoFreeIrp(CONTAINING_RECORD(Apc, IRP, Tail.Apc));
41 }
42
43 NTSTATUS
44 NTAPI
45 IopCleanupFailedIrp(IN PFILE_OBJECT FileObject,
46 IN PKEVENT EventObject OPTIONAL,
47 IN PVOID Buffer OPTIONAL)
48 {
49 PAGED_CODE();
50
51 /* Dereference the event */
52 if (EventObject) ObDereferenceObject(EventObject);
53
54 /* Free a buffer, if any */
55 if (Buffer) ExFreePool(Buffer);
56
57 /* If this was a file opened for synch I/O, then unlock it */
58 if (FileObject->Flags & FO_SYNCHRONOUS_IO) IopUnlockFileObject(FileObject);
59
60 /* Now dereference it and return */
61 ObDereferenceObject(FileObject);
62 return STATUS_INSUFFICIENT_RESOURCES;
63 }
64
65 VOID
66 NTAPI
67 IopAbortInterruptedIrp(IN PKEVENT EventObject,
68 IN PIRP Irp)
69 {
70 KIRQL OldIrql;
71 BOOLEAN CancelResult;
72 LARGE_INTEGER Wait;
73 PAGED_CODE();
74
75 /* Raise IRQL to APC */
76 KeRaiseIrql(APC_LEVEL, &OldIrql);
77
78 /* Check if nobody completed it yet */
79 if (!KeReadStateEvent(EventObject))
80 {
81 /* First, cancel it */
82 CancelResult = IoCancelIrp(Irp);
83 KeLowerIrql(OldIrql);
84
85 /* Check if we cancelled it */
86 if (CancelResult)
87 {
88 /* Wait for the IRP to be cancelled */
89 Wait.QuadPart = -100000;
90 while (!KeReadStateEvent(EventObject))
91 {
92 /* Delay indefintely */
93 KeDelayExecutionThread(KernelMode, FALSE, &Wait);
94 }
95 }
96 else
97 {
98 /* No cancellation done, so wait for the I/O system to kill it */
99 KeWaitForSingleObject(EventObject,
100 Executive,
101 KernelMode,
102 FALSE,
103 NULL);
104 }
105 }
106 else
107 {
108 /* We got preempted, so give up */
109 KeLowerIrql(OldIrql);
110 }
111 }
112
113 VOID
114 NTAPI
115 IopRemoveThreadIrp(VOID)
116 {
117 KIRQL OldIrql;
118 PIRP DeadIrp;
119 PETHREAD IrpThread;
120 PLIST_ENTRY IrpEntry;
121 PIO_ERROR_LOG_PACKET ErrorLogEntry;
122 PDEVICE_OBJECT DeviceObject = NULL;
123 PIO_STACK_LOCATION IoStackLocation;
124
125 /* First, raise to APC to protect IrpList */
126 KeRaiseIrql(APC_LEVEL, &OldIrql);
127
128 /* Get the Thread and check the list */
129 IrpThread = PsGetCurrentThread();
130 if (IsListEmpty(&IrpThread->IrpList))
131 {
132 /* It got completed now, so quit */
133 KeLowerIrql(OldIrql);
134 return;
135 }
136
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",
142 __FUNCTION__,
143 DeadIrp,
144 IrpThread);
145
146 /* Don't cancel the IRP if it's already been completed far */
147 if (DeadIrp->CurrentLocation == (DeadIrp->StackCount + 2))
148 {
149 /* Return */
150 KeLowerIrql(OldIrql);
151 return;
152 }
153
154 /* Disown the IRP! */
155 DeadIrp->Tail.Overlay.Thread = NULL;
156 RemoveHeadList(&IrpThread->IrpList);
157 InitializeListHead(&DeadIrp->ThreadListEntry);
158
159 /* Get the stack location and check if it's valid */
160 IoStackLocation = IoGetCurrentIrpStackLocation(DeadIrp);
161 if (DeadIrp->CurrentLocation <= DeadIrp->StackCount)
162 {
163 /* Get the device object */
164 DeviceObject = IoStackLocation->DeviceObject;
165 }
166
167 /* Lower IRQL now, since we have the pointers we need */
168 KeLowerIrql(OldIrql);
169
170 /* Check if we can send an Error Log Entry*/
171 if (DeviceObject)
172 {
173 /* Allocate an entry */
174 ErrorLogEntry = IoAllocateErrorLogEntry(DeviceObject,
175 sizeof(IO_ERROR_LOG_PACKET));
176 if (ErrorLogEntry)
177 {
178 /* Write the entry */
179 ErrorLogEntry->ErrorCode = 0xBAADF00D; /* FIXME */
180 IoWriteErrorLogEntry(ErrorLogEntry);
181 }
182 }
183 }
184
185 VOID
186 NTAPI
187 IopCleanupIrp(IN PIRP Irp,
188 IN PFILE_OBJECT FileObject)
189 {
190 PMDL Mdl;
191 IOTRACE(IO_IRP_DEBUG,
192 "%s - Cleaning IRP %p for %p\n",
193 __FUNCTION__,
194 Irp,
195 FileObject);
196
197 /* Check if there's an MDL */
198 while ((Mdl = Irp->MdlAddress))
199 {
200 /* Clear all of them */
201 Irp->MdlAddress = Mdl->Next;
202 IoFreeMdl(Mdl);
203 }
204
205 /* Check if the IRP has system buffer */
206 if (Irp->Flags & IRP_DEALLOCATE_BUFFER)
207 {
208 /* Free the buffer */
209 ExFreePoolWithTag(Irp->AssociatedIrp.SystemBuffer, TAG_SYS_BUF);
210 }
211
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) &&
215 (FileObject))
216 {
217 /* Dereference the User Event */
218 ObDereferenceObject(Irp->UserEvent);
219 }
220
221 /* Check if we have a file object and this isn't a create operation */
222 if ((FileObject) && !(Irp->Flags & IRP_CREATE_OPERATION))
223 {
224 /* Dereference the file object */
225 ObDereferenceObject(FileObject);
226 }
227
228 /* Free the IRP */
229 IoFreeIrp(Irp);
230 }
231
232 VOID
233 NTAPI
234 IopCompleteRequest(IN PKAPC Apc,
235 IN PKNORMAL_ROUTINE* NormalRoutine,
236 IN PVOID* NormalContext,
237 IN PVOID* SystemArgument1,
238 IN PVOID* SystemArgument2)
239 {
240 PFILE_OBJECT FileObject;
241 PIRP Irp;
242 PMDL Mdl, NextMdl;
243 PVOID Port = NULL, Key = NULL;
244 BOOLEAN SignaledCreateRequest = FALSE;
245
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",
251 __FUNCTION__,
252 Irp,
253 FileObject);
254
255 /* Sanity check */
256 ASSERT(Irp->IoStatus.Status != 0xFFFFFFFF);
257
258 /* Check if we have a file object */
259 if (*SystemArgument2)
260 {
261 /* Check if we're reparsing */
262 if ((Irp->IoStatus.Status == STATUS_REPARSE) &&
263 (Irp->IoStatus.Information == IO_REPARSE_TAG_MOUNT_POINT))
264 {
265 /* We should never get this yet */
266 DPRINT1("Reparse support not yet present!\n");
267 while (TRUE);
268 }
269 }
270
271 /* Handle Buffered case first */
272 if (Irp->Flags & IRP_BUFFERED_IO)
273 {
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)))
278 {
279 /* Copy the buffer back to the user */
280 RtlCopyMemory(Irp->UserBuffer,
281 Irp->AssociatedIrp.SystemBuffer,
282 Irp->IoStatus.Information);
283 }
284
285 /* Also check if we should de-allocate it */
286 if (Irp->Flags & IRP_DEALLOCATE_BUFFER)
287 {
288 /* Deallocate it */
289 ExFreePoolWithTag(Irp->AssociatedIrp.SystemBuffer, TAG_SYS_BUF);
290 }
291 }
292
293 /* Now we got rid of these two... */
294 Irp->Flags &= ~(IRP_BUFFERED_IO | IRP_DEALLOCATE_BUFFER);
295
296 /* Check if there's an MDL */
297 for (Mdl = Irp->MdlAddress; Mdl; Mdl = NextMdl)
298 {
299 /* Free it */
300 NextMdl = Mdl->Next;
301 IoFreeMdl(Mdl);
302 }
303
304 /* No MDLs left */
305 Irp->MdlAddress = NULL;
306
307 /*
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.
311 */
312 if (!(NT_ERROR(Irp->IoStatus.Status)) ||
313 (NT_ERROR(Irp->IoStatus.Status) &&
314 (Irp->PendingReturned) &&
315 !(IsIrpSynchronous(Irp, FileObject))))
316 {
317 /* Get any information we need from the FO before we kill it */
318 if ((FileObject) && (FileObject->CompletionContext))
319 {
320 /* Save Completion Data */
321 Port = FileObject->CompletionContext->Port;
322 Key = FileObject->CompletionContext->Key;
323 }
324
325 /* Use SEH to make sure we don't write somewhere invalid */
326 _SEH_TRY
327 {
328 /* Save the IOSB Information */
329 *Irp->UserIosb = Irp->IoStatus;
330 }
331 _SEH_HANDLE
332 {
333 /* Ignore any error */
334 }
335 _SEH_END;
336
337 /* Check if we have an event or a file object */
338 if (Irp->UserEvent)
339 {
340 /* At the very least, this is a PKEVENT, so signal it always */
341 KeSetEvent(Irp->UserEvent, 0, FALSE);
342
343 /* Check if we also have a File Object */
344 if (FileObject)
345 {
346 /* Check if this is an Asynch API */
347 if (!(Irp->Flags & IRP_SYNCHRONOUS_API))
348 {
349 /* HACK */
350 if (*((PULONG)(Irp->UserEvent) - 1) != 0x87878787)
351 {
352 /* Dereference the event */
353 ObDereferenceObject(Irp->UserEvent);
354 }
355 else
356 {
357 DPRINT1("Not an executive event -- should not be dereferenced\n");
358 }
359 }
360
361 /*
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
365 */
366 if ((FileObject->Flags & FO_SYNCHRONOUS_IO) &&
367 !(Irp->Flags & IRP_OB_QUERY_NAME))
368 {
369 /* Signal the file object and set the status */
370 KeSetEvent(&FileObject->Event, 0, FALSE);
371 FileObject->FinalStatus = Irp->IoStatus.Status;
372 }
373
374 /*
375 * This could also be a create operation, in which case we want
376 * to make sure there's no APC fired.
377 */
378 if (Irp->Flags & IRP_CREATE_OPERATION)
379 {
380 /* Clear the APC Routine and remember this */
381 Irp->Overlay.AsynchronousParameters.UserApcRoutine = NULL;
382 SignaledCreateRequest = TRUE;
383 }
384 }
385 }
386 else if (FileObject)
387 {
388 /* Signal the file object and set the status */
389 KeSetEvent(&FileObject->Event, 0, FALSE);
390 FileObject->FinalStatus = Irp->IoStatus.Status;
391
392 /*
393 * This could also be a create operation, in which case we want
394 * to make sure there's no APC fired.
395 */
396 if (Irp->Flags & IRP_CREATE_OPERATION)
397 {
398 /* Clear the APC Routine and remember this */
399 Irp->Overlay.AsynchronousParameters.UserApcRoutine = NULL;
400 SignaledCreateRequest = TRUE;
401 }
402 }
403
404 /* Now that we've signaled the events, de-associate the IRP */
405 IopUnQueueIrpFromThread(Irp);
406
407 /* Now check if a User APC Routine was requested */
408 if (Irp->Overlay.AsynchronousParameters.UserApcRoutine)
409 {
410 /* Initialize it */
411 KeInitializeApc(&Irp->Tail.Apc,
412 KeGetCurrentThread(),
413 CurrentApcEnvironment,
414 IopFreeIrpKernelApc,
415 IopAbortIrpKernelApc,
416 (PKNORMAL_ROUTINE)Irp->
417 Overlay.AsynchronousParameters.UserApcRoutine,
418 Irp->RequestorMode,
419 Irp->
420 Overlay.AsynchronousParameters.UserApcContext);
421
422 /* Queue it */
423 KeInsertQueueApc(&Irp->Tail.Apc, Irp->UserIosb, NULL, 2);
424 }
425 else if ((Port) &&
426 (Irp->Overlay.AsynchronousParameters.UserApcContext))
427 {
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);
432 }
433 else
434 {
435 /* Free the IRP since we don't need it anymore */
436 IoFreeIrp(Irp);
437 }
438
439 /* Check if we have a file object that wasn't part of a create */
440 if ((FileObject) && !(SignaledCreateRequest))
441 {
442 /* Dereference it, since it's not needed anymore either */
443 ObDereferenceObjectDeferDelete(FileObject);
444 }
445 }
446 else
447 {
448 /*
449 * Either we didn't return from the request, or we did return but this
450 * request was synchronous.
451 */
452 if ((Irp->PendingReturned) && (FileObject))
453 {
454 /* So we did return with a synch operation, was it the IRP? */
455 if (Irp->Flags & IRP_SYNCHRONOUS_API)
456 {
457 /* Yes, this IRP was synchronous, so return the I/O Status */
458 *Irp->UserIosb = Irp->IoStatus;
459
460 /* Now check if the user gave an event */
461 if (Irp->UserEvent)
462 {
463 /* Signal it */
464 KeSetEvent(Irp->UserEvent, 0, FALSE);
465 }
466 else
467 {
468 /* No event was given, so signal the FO instead */
469 KeSetEvent(&FileObject->Event, 0, FALSE);
470 }
471 }
472 else
473 {
474 /*
475 * It's not the IRP that was synchronous, it was the FO
476 * that was opened this way. Signal its event.
477 */
478 FileObject->FinalStatus = Irp->IoStatus.Status;
479 KeSetEvent(&FileObject->Event, 0, FALSE);
480 }
481 }
482
483 /* Now that we got here, we do this for incomplete I/Os as well */
484 if ((FileObject) && !(Irp->Flags & IRP_CREATE_OPERATION))
485 {
486 /* Dereference the File Object unless this was a create */
487 ObDereferenceObjectDeferDelete(FileObject);
488 }
489
490 /*
491 * Check if this was an Executive Event (remember that we know this
492 * by checking if the IRP is synchronous)
493 */
494 if ((Irp->UserEvent) &&
495 (FileObject) &&
496 !(Irp->Flags & IRP_SYNCHRONOUS_API))
497 {
498 /* This isn't a PKEVENT, so dereference it */
499 ObDereferenceObject(Irp->UserEvent);
500 }
501
502 /* Now that we've signaled the events, de-associate the IRP */
503 IopUnQueueIrpFromThread(Irp);
504
505 /* Free the IRP as well */
506 IoFreeIrp(Irp);
507 }
508 }
509
510 /* FUNCTIONS *****************************************************************/
511
512 /*
513 * @implemented
514 */
515 PIRP
516 NTAPI
517 IoAllocateIrp(IN CCHAR StackSize,
518 IN BOOLEAN ChargeQuota)
519 {
520 PIRP Irp = NULL;
521 USHORT Size = IoSizeOfIrp(StackSize);
522 PKPRCB Prcb;
523 UCHAR Flags = 0;
524 PNPAGED_LOOKASIDE_LIST List = NULL;
525 PP_NPAGED_LOOKASIDE_NUMBER ListType = LookasideSmallIrpList;
526
527 /* Figure out which Lookaside List to use */
528 if ((StackSize <= 8) && (ChargeQuota == FALSE))
529 {
530 /* Set Fixed Size Flag */
531 Flags = IRP_ALLOCATED_FIXED_SIZE;
532
533 /* See if we should use big list */
534 if (StackSize != 1)
535 {
536 Size = IoSizeOfIrp(8);
537 ListType = LookasideLargeIrpList;
538 }
539
540 /* Get the PRCB */
541 Prcb = KeGetCurrentPrcb();
542
543 /* Get the P List First */
544 List = (PNPAGED_LOOKASIDE_LIST)Prcb->PPLookasideList[ListType].P;
545
546 /* Attempt allocation */
547 List->L.TotalAllocates++;
548 Irp = (PIRP)InterlockedPopEntrySList(&List->L.ListHead);
549
550 /* Check if the P List failed */
551 if (!Irp)
552 {
553 /* Let the balancer know */
554 List->L.AllocateMisses++;
555
556 /* Try the L List */
557 List = (PNPAGED_LOOKASIDE_LIST)Prcb->PPLookasideList[ListType].L;
558 List->L.TotalAllocates++;
559 Irp = (PIRP)InterlockedPopEntrySList(&List->L.ListHead);
560 }
561 }
562
563 /* Check if we have to use the pool */
564 if (!Irp)
565 {
566 /* Did we try lookaside and fail? */
567 if (Flags & IRP_ALLOCATED_FIXED_SIZE) List->L.AllocateMisses++;
568
569 /* Check if we should charge quota */
570 if (ChargeQuota)
571 {
572 /* Irp = ExAllocatePoolWithQuotaTag(NonPagedPool, Size, TAG_IRP); */
573 /* FIXME */
574 Irp = ExAllocatePoolWithTag(NonPagedPool, Size, TAG_IRP);
575 }
576 else
577 {
578 /* Allocate the IRP With no Quota charge */
579 Irp = ExAllocatePoolWithTag(NonPagedPool, Size, TAG_IRP);
580 }
581
582 /* Make sure it was sucessful */
583 if (!Irp) return(NULL);
584 }
585 else
586 {
587 /* We have an IRP from Lookaside */
588 Flags |= IRP_LOOKASIDE_ALLOCATION;
589 }
590
591 /* Set Flag */
592 if (ChargeQuota) Flags |= IRP_QUOTA_CHARGED;
593
594 /* Now Initialize it */
595 IoInitializeIrp(Irp, Size, StackSize);
596
597 /* Set the Allocation Flags */
598 Irp->AllocationFlags = Flags;
599
600 /* Return it */
601 IOTRACE(IO_IRP_DEBUG,
602 "%s - Allocated IRP %p with allocation flags %lx\n",
603 __FUNCTION__,
604 Irp,
605 Flags);
606 return Irp;
607 }
608
609 /*
610 * @implemented
611 */
612 PIRP
613 NTAPI
614 IoBuildAsynchronousFsdRequest(IN ULONG MajorFunction,
615 IN PDEVICE_OBJECT DeviceObject,
616 IN PVOID Buffer,
617 IN ULONG Length,
618 IN PLARGE_INTEGER StartingOffset,
619 IN PIO_STATUS_BLOCK IoStatusBlock)
620 {
621 PIRP Irp;
622 PIO_STACK_LOCATION StackPtr;
623
624 /* Check if DeviceObject is NULL dxg.sys will send in NULL if we got a PCI graphic card */
625 if (DeviceObject == NULL) return NULL;
626
627 /* Allocate IRP */
628 Irp = IoAllocateIrp(DeviceObject->StackSize, FALSE);
629 if (!Irp) return Irp;
630
631 /* Get the Stack */
632 StackPtr = IoGetNextIrpStackLocation(Irp);
633
634 /* Write the Major function and then deal with it */
635 StackPtr->MajorFunction = (UCHAR)MajorFunction;
636
637 /* Do not handle the following here */
638 if ((MajorFunction != IRP_MJ_FLUSH_BUFFERS) &&
639 (MajorFunction != IRP_MJ_SHUTDOWN) &&
640 (MajorFunction != IRP_MJ_PNP) &&
641 (MajorFunction != IRP_MJ_POWER))
642 {
643 /* Check if this is Buffered IO */
644 if (DeviceObject->Flags & DO_BUFFERED_IO)
645 {
646 /* Allocate the System Buffer */
647 Irp->AssociatedIrp.SystemBuffer =
648 ExAllocatePoolWithTag(NonPagedPool, Length, TAG_SYS_BUF);
649 if (!Irp->AssociatedIrp.SystemBuffer)
650 {
651 /* Free the IRP and fail */
652 IoFreeIrp(Irp);
653 return NULL;
654 }
655
656 /* Set flags */
657 Irp->Flags = IRP_BUFFERED_IO | IRP_DEALLOCATE_BUFFER;
658
659 /* Handle special IRP_MJ_WRITE Case */
660 if (MajorFunction == IRP_MJ_WRITE)
661 {
662 /* Copy the buffer data */
663 RtlCopyMemory(Irp->AssociatedIrp.SystemBuffer, Buffer, Length);
664 }
665 else
666 {
667 /* Set the Input Operation flag and set this as a User Buffer */
668 Irp->Flags |= IRP_INPUT_OPERATION;
669 Irp->UserBuffer = Buffer;
670 }
671 }
672 else if (DeviceObject->Flags & DO_DIRECT_IO)
673 {
674 /* Use an MDL for Direct I/O */
675 Irp->MdlAddress = IoAllocateMdl(Buffer,
676 Length,
677 FALSE,
678 FALSE,
679 NULL);
680 if (!Irp->MdlAddress)
681 {
682 /* Free the IRP and fail */
683 IoFreeIrp(Irp);
684 return NULL;
685 }
686
687 /* Probe and Lock */
688 _SEH_TRY
689 {
690 /* Do the probe */
691 MmProbeAndLockPages(Irp->MdlAddress,
692 KernelMode,
693 MajorFunction == IRP_MJ_READ ?
694 IoWriteAccess : IoReadAccess);
695 }
696 _SEH_HANDLE
697 {
698 /* Free the IRP and its MDL */
699 IoFreeMdl(Irp->MdlAddress);
700 IoFreeIrp(Irp);
701 Irp = NULL;
702 }
703 _SEH_END;
704
705 /* This is how we know if we failed during the probe */
706 if (!Irp) return NULL;
707 }
708 else
709 {
710 /* Neither, use the buffer */
711 Irp->UserBuffer = Buffer;
712 }
713
714 /* Check if this is a read */
715 if (MajorFunction == IRP_MJ_READ)
716 {
717 /* Set the parameters for a read */
718 StackPtr->Parameters.Read.Length = Length;
719 StackPtr->Parameters.Read.ByteOffset = *StartingOffset;
720 }
721 else if (MajorFunction == IRP_MJ_WRITE)
722 {
723 /* Otherwise, set write parameters */
724 StackPtr->Parameters.Write.Length = Length;
725 StackPtr->Parameters.Write.ByteOffset = *StartingOffset;
726 }
727 }
728
729 /* Set the Current Thread and IOSB */
730 Irp->UserIosb = IoStatusBlock;
731 Irp->Tail.Overlay.Thread = PsGetCurrentThread();
732
733 /* Set the Status Block after all is done */
734 IOTRACE(IO_IRP_DEBUG,
735 "%s - Built IRP %p with Major, Buffer, DO %lx %p %p\n",
736 __FUNCTION__,
737 Irp,
738 MajorFunction,
739 Buffer,
740 DeviceObject);
741 return Irp;
742 }
743
744 /*
745 * @implemented
746 */
747 PIRP
748 NTAPI
749 IoBuildDeviceIoControlRequest(IN ULONG IoControlCode,
750 IN PDEVICE_OBJECT DeviceObject,
751 IN PVOID InputBuffer,
752 IN ULONG InputBufferLength,
753 IN PVOID OutputBuffer,
754 IN ULONG OutputBufferLength,
755 IN BOOLEAN InternalDeviceIoControl,
756 IN PKEVENT Event,
757 IN PIO_STATUS_BLOCK IoStatusBlock)
758 {
759 PIRP Irp;
760 PIO_STACK_LOCATION StackPtr;
761 ULONG BufferLength;
762
763 /* Allocate IRP */
764 Irp = IoAllocateIrp(DeviceObject->StackSize, FALSE);
765 if (!Irp) return Irp;
766
767 /* Get the Stack */
768 StackPtr = IoGetNextIrpStackLocation(Irp);
769
770 /* Set the DevCtl Type */
771 StackPtr->MajorFunction = InternalDeviceIoControl ?
772 IRP_MJ_INTERNAL_DEVICE_CONTROL :
773 IRP_MJ_DEVICE_CONTROL;
774
775 /* Set the IOCTL Data */
776 StackPtr->Parameters.DeviceIoControl.IoControlCode = IoControlCode;
777 StackPtr->Parameters.DeviceIoControl.InputBufferLength = InputBufferLength;
778 StackPtr->Parameters.DeviceIoControl.OutputBufferLength =
779 OutputBufferLength;
780
781 /* Handle the Methods */
782 switch (IO_METHOD_FROM_CTL_CODE(IoControlCode))
783 {
784 /* Buffered I/O */
785 case METHOD_BUFFERED:
786
787 /* Select the right Buffer Length */
788 BufferLength = InputBufferLength > OutputBufferLength ?
789 InputBufferLength : OutputBufferLength;
790
791 /* Make sure there is one */
792 if (BufferLength)
793 {
794 /* Allocate the System Buffer */
795 Irp->AssociatedIrp.SystemBuffer =
796 ExAllocatePoolWithTag(NonPagedPool,
797 BufferLength,
798 TAG_SYS_BUF);
799 if (!Irp->AssociatedIrp.SystemBuffer)
800 {
801 /* Free the IRP and fail */
802 IoFreeIrp(Irp);
803 return NULL;
804 }
805
806 /* Check if we got a buffer */
807 if (InputBuffer)
808 {
809 /* Copy into the System Buffer */
810 RtlCopyMemory(Irp->AssociatedIrp.SystemBuffer,
811 InputBuffer,
812 InputBufferLength);
813 }
814
815 /* Write the flags */
816 Irp->Flags = IRP_BUFFERED_IO | IRP_DEALLOCATE_BUFFER;
817 if (OutputBuffer) Irp->Flags |= IRP_INPUT_OPERATION;
818
819 /* Save the Buffer */
820 Irp->UserBuffer = OutputBuffer;
821 }
822 else
823 {
824 /* Clear the Flags and Buffer */
825 Irp->Flags = 0;
826 Irp->UserBuffer = NULL;
827 }
828 break;
829
830 /* Direct I/O */
831 case METHOD_IN_DIRECT:
832 case METHOD_OUT_DIRECT:
833
834 /* Check if we got an input buffer */
835 if (InputBuffer)
836 {
837 /* Allocate the System Buffer */
838 Irp->AssociatedIrp.SystemBuffer =
839 ExAllocatePoolWithTag(NonPagedPool,
840 InputBufferLength,
841 TAG_SYS_BUF);
842 if (!Irp->AssociatedIrp.SystemBuffer)
843 {
844 /* Free the IRP and fail */
845 IoFreeIrp(Irp);
846 return NULL;
847 }
848
849 /* Copy into the System Buffer */
850 RtlCopyMemory(Irp->AssociatedIrp.SystemBuffer,
851 InputBuffer,
852 InputBufferLength);
853
854 /* Write the flags */
855 Irp->Flags = IRP_BUFFERED_IO | IRP_DEALLOCATE_BUFFER;
856 }
857 else
858 {
859 Irp->Flags = 0;
860 }
861
862 /* Check if we got an output buffer */
863 if (OutputBuffer)
864 {
865 /* Allocate the System Buffer */
866 Irp->MdlAddress = IoAllocateMdl(OutputBuffer,
867 OutputBufferLength,
868 FALSE,
869 FALSE,
870 Irp);
871 if (!Irp->MdlAddress)
872 {
873 /* Free the IRP and fail */
874 IoFreeIrp(Irp);
875 return NULL;
876 }
877
878 /* Probe and Lock */
879 _SEH_TRY
880 {
881 /* Do the probe */
882 MmProbeAndLockPages(Irp->MdlAddress,
883 KernelMode,
884 IO_METHOD_FROM_CTL_CODE(IoControlCode) ==
885 METHOD_IN_DIRECT ?
886 IoReadAccess : IoWriteAccess);
887 }
888 _SEH_HANDLE
889 {
890 /* Free the MDL */
891 IoFreeMdl(Irp->MdlAddress);
892
893 /* Free the input buffer and IRP */
894 if (InputBuffer) ExFreePool(Irp->AssociatedIrp.SystemBuffer);
895 IoFreeIrp(Irp);
896 Irp = NULL;
897 }
898 _SEH_END;
899
900 /* This is how we know if probing failed */
901 if (!Irp) return NULL;
902 }
903 break;
904
905 case METHOD_NEITHER:
906
907 /* Just save the Buffer */
908 Irp->UserBuffer = OutputBuffer;
909 StackPtr->Parameters.DeviceIoControl.Type3InputBuffer = InputBuffer;
910 }
911
912 /* Now write the Event and IoSB */
913 Irp->UserIosb = IoStatusBlock;
914 Irp->UserEvent = Event;
915
916 /* Sync IRPs are queued to requestor thread's irp cancel/cleanup list */
917 Irp->Tail.Overlay.Thread = PsGetCurrentThread();
918 IoQueueThreadIrp(Irp);
919
920 /* Return the IRP */
921 IOTRACE(IO_IRP_DEBUG,
922 "%s - Built IRP %p with IOCTL, Buffers, DO %lx %p %p %p\n",
923 __FUNCTION__,
924 Irp,
925 IoControlCode,
926 InputBuffer,
927 OutputBuffer,
928 DeviceObject);
929 return Irp;
930 }
931
932 /*
933 * @implemented
934 */
935 PIRP
936 NTAPI
937 IoBuildSynchronousFsdRequest(IN ULONG MajorFunction,
938 IN PDEVICE_OBJECT DeviceObject,
939 IN PVOID Buffer,
940 IN ULONG Length,
941 IN PLARGE_INTEGER StartingOffset,
942 IN PKEVENT Event,
943 IN PIO_STATUS_BLOCK IoStatusBlock)
944 {
945 PIRP Irp;
946
947 /* Do the big work to set up the IRP */
948 Irp = IoBuildAsynchronousFsdRequest(MajorFunction,
949 DeviceObject,
950 Buffer,
951 Length,
952 StartingOffset,
953 IoStatusBlock );
954 if (!Irp) return NULL;
955
956 /* Set the Event which makes it Syncronous */
957 Irp->UserEvent = Event;
958
959 /* Sync IRPs are queued to requestor thread's irp cancel/cleanup list */
960 IoQueueThreadIrp(Irp);
961 return Irp;
962 }
963
964 /*
965 * @implemented
966 */
967 BOOLEAN
968 NTAPI
969 IoCancelIrp(IN PIRP Irp)
970 {
971 KIRQL OldIrql;
972 PDRIVER_CANCEL CancelRoutine;
973 IOTRACE(IO_IRP_DEBUG,
974 "%s - Canceling IRP %p\n",
975 __FUNCTION__,
976 Irp);
977 ASSERT(Irp->Type == IO_TYPE_IRP);
978
979 /* Acquire the cancel lock and cancel the IRP */
980 IoAcquireCancelSpinLock(&OldIrql);
981 Irp->Cancel = TRUE;
982
983 /* Clear the cancel routine and get the old one */
984 CancelRoutine = IoSetCancelRoutine(Irp, NULL);
985 if (CancelRoutine)
986 {
987 /* We had a routine, make sure the IRP isn't completed */
988 if (Irp->CurrentLocation > (Irp->StackCount + 1))
989 {
990 /* It is, bugcheck */
991 KeBugCheckEx(CANCEL_STATE_IN_COMPLETED_IRP,
992 (ULONG_PTR)Irp,
993 0,
994 0,
995 0);
996 }
997
998 /* Set the cancel IRQL And call the routine */
999 Irp->CancelIrql = OldIrql;
1000 CancelRoutine(IoGetCurrentIrpStackLocation(Irp)->DeviceObject, Irp);
1001 return TRUE;
1002 }
1003
1004 /* Otherwise, release the cancel lock and fail */
1005 IoReleaseCancelSpinLock(OldIrql);
1006 return FALSE;
1007 }
1008
1009 /*
1010 * @implemented
1011 */
1012 VOID
1013 NTAPI
1014 IoCancelThreadIo(IN PETHREAD Thread)
1015 {
1016 KIRQL OldIrql;
1017 ULONG Retries = 3000;
1018 LARGE_INTEGER Interval;
1019 PLIST_ENTRY ListHead, NextEntry;
1020 PIRP Irp;
1021 IOTRACE(IO_IRP_DEBUG,
1022 "%s - Canceling IRPs for Thread %p\n",
1023 __FUNCTION__,
1024 Thread);
1025
1026 /* Raise to APC to protect the IrpList */
1027 KeRaiseIrql(APC_LEVEL, &OldIrql);
1028
1029 /* Start by cancelling all the IRPs in the current thread queue. */
1030 ListHead = &Thread->IrpList;
1031 NextEntry = ListHead->Flink;
1032 while (ListHead != NextEntry)
1033 {
1034 /* Get the IRP */
1035 Irp = CONTAINING_RECORD(NextEntry, IRP, ThreadListEntry);
1036
1037 /* Cancel it */
1038 IoCancelIrp(Irp);
1039
1040 /* Move to the next entry */
1041 NextEntry = NextEntry->Flink;
1042 }
1043
1044 /* Wait 100 milliseconds */
1045 Interval.QuadPart = -1000000;
1046
1047 /* Wait till all the IRPs are completed or cancelled. */
1048 while (!IsListEmpty(&Thread->IrpList))
1049 {
1050 /* Now we can lower */
1051 KeLowerIrql(OldIrql);
1052
1053 /* Wait a short while and then look if all our IRPs were completed. */
1054 KeDelayExecutionThread(KernelMode, FALSE, &Interval);
1055
1056 /*
1057 * Don't stay here forever if some broken driver doesn't complete
1058 * the IRP.
1059 */
1060 if (!(Retries--)) IopRemoveThreadIrp();
1061
1062 /* Raise the IRQL Again */
1063 KeRaiseIrql(APC_LEVEL, &OldIrql);
1064 }
1065
1066 /* We're done, lower the IRQL */
1067 KeLowerIrql(OldIrql);
1068 }
1069
1070 /*
1071 * @implemented
1072 */
1073 NTSTATUS
1074 NTAPI
1075 IoCallDriver(IN PDEVICE_OBJECT DeviceObject,
1076 IN PIRP Irp)
1077 {
1078 /* Call fast call */
1079 return IofCallDriver(DeviceObject, Irp);
1080 }
1081
1082 /*
1083 * @implemented
1084 */
1085 VOID
1086 NTAPI
1087 IoCompleteRequest(IN PIRP Irp,
1088 IN CCHAR PriorityBoost)
1089 {
1090 /* Call the fastcall */
1091 IofCompleteRequest(Irp, PriorityBoost);
1092 }
1093
1094 /*
1095 * @implemented
1096 */
1097 VOID
1098 NTAPI
1099 IoEnqueueIrp(IN PIRP Irp)
1100 {
1101 /* This is the same as calling IoQueueThreadIrp */
1102 IoQueueThreadIrp(Irp);
1103 }
1104
1105 /*
1106 * @implemented
1107 */
1108 NTSTATUS
1109 FASTCALL
1110 IofCallDriver(IN PDEVICE_OBJECT DeviceObject,
1111 IN PIRP Irp)
1112 {
1113 PDRIVER_OBJECT DriverObject;
1114 PIO_STACK_LOCATION Param;
1115
1116 /* Get the Driver Object */
1117 DriverObject = DeviceObject->DriverObject;
1118
1119 /* Decrease the current location and check if */
1120 Irp->CurrentLocation--;
1121 if (Irp->CurrentLocation <= 0)
1122 {
1123 /* This IRP ran out of stack, bugcheck */
1124 KeBugCheckEx(NO_MORE_IRP_STACK_LOCATIONS, (ULONG_PTR)Irp, 0, 0, 0);
1125 }
1126
1127 /* Now update the stack location */
1128 Param = IoGetNextIrpStackLocation(Irp);
1129 Irp->Tail.Overlay.CurrentStackLocation = Param;
1130
1131 /* Get the Device Object */
1132 Param->DeviceObject = DeviceObject;
1133
1134 /* Call it */
1135 return DriverObject->MajorFunction[Param->MajorFunction](DeviceObject,
1136 Irp);
1137 }
1138
1139 FORCEINLINE
1140 VOID
1141 IopClearStackLocation(IN PIO_STACK_LOCATION IoStackLocation)
1142 {
1143 IoStackLocation->MinorFunction = 0;
1144 IoStackLocation->Flags = 0;
1145 IoStackLocation->Control &= SL_ERROR_RETURNED;
1146 IoStackLocation->Parameters.Others.Argument1 = 0;
1147 IoStackLocation->Parameters.Others.Argument2 = 0;
1148 IoStackLocation->Parameters.Others.Argument3 = 0;
1149 IoStackLocation->FileObject = NULL;
1150 }
1151
1152 /*
1153 * @implemented
1154 */
1155 VOID
1156 FASTCALL
1157 IofCompleteRequest(IN PIRP Irp,
1158 IN CCHAR PriorityBoost)
1159 {
1160 PIO_STACK_LOCATION StackPtr, LastStackPtr;
1161 PDEVICE_OBJECT DeviceObject;
1162 PFILE_OBJECT FileObject;
1163 PETHREAD Thread;
1164 NTSTATUS Status;
1165 PMDL Mdl, NextMdl;
1166 ULONG MasterCount;
1167 PIRP MasterIrp;
1168 ULONG Flags;
1169 NTSTATUS ErrorCode = STATUS_SUCCESS;
1170 IOTRACE(IO_IRP_DEBUG,
1171 "%s - Completing IRP %p\n",
1172 __FUNCTION__,
1173 Irp);
1174
1175 /* Make sure this IRP isn't getting completed twice or is invalid */
1176 if ((Irp->CurrentLocation) > (Irp->StackCount + 1))
1177 {
1178 /* Bugcheck */
1179 KeBugCheckEx(MULTIPLE_IRP_COMPLETE_REQUESTS, (ULONG_PTR)Irp, 0, 0, 0);
1180 }
1181
1182 /* Some sanity checks */
1183 ASSERT(Irp->Type == IO_TYPE_IRP);
1184 ASSERT(!Irp->CancelRoutine);
1185 ASSERT(Irp->IoStatus.Status != STATUS_PENDING);
1186 ASSERT(Irp->IoStatus.Status != 0xFFFFFFFF);
1187
1188 /* Get the last stack */
1189 LastStackPtr = (PIO_STACK_LOCATION)(Irp + 1);
1190 if (LastStackPtr->Control & SL_ERROR_RETURNED)
1191 {
1192 /* Get the error code */
1193 ErrorCode = (NTSTATUS)LastStackPtr->Parameters.Others.Argument4;
1194 }
1195
1196 /* Get the Current Stack and skip it */
1197 StackPtr = IoGetCurrentIrpStackLocation(Irp);
1198 IoSkipCurrentIrpStackLocation(Irp);
1199
1200 /* Loop the Stacks and complete the IRPs */
1201 do
1202 {
1203 /* Set Pending Returned */
1204 Irp->PendingReturned = StackPtr->Control & SL_PENDING_RETURNED;
1205
1206 /* Check if we failed */
1207 if (!NT_SUCCESS(Irp->IoStatus.Status))
1208 {
1209 /* Check if it was changed by a completion routine */
1210 if (Irp->IoStatus.Status != ErrorCode)
1211 {
1212 /* Update the error for the current stack */
1213 ErrorCode = Irp->IoStatus.Status;
1214 StackPtr->Control |= SL_ERROR_RETURNED;
1215 LastStackPtr->Parameters.Others.Argument4 = (PVOID)ErrorCode;
1216 LastStackPtr->Control |= SL_ERROR_RETURNED;
1217 }
1218 }
1219
1220 /* Check if there is a Completion Routine to Call */
1221 if ((NT_SUCCESS(Irp->IoStatus.Status) &&
1222 (StackPtr->Control & SL_INVOKE_ON_SUCCESS)) ||
1223 (!NT_SUCCESS(Irp->IoStatus.Status) &&
1224 (StackPtr->Control & SL_INVOKE_ON_ERROR)) ||
1225 (Irp->Cancel &&
1226 (StackPtr->Control & SL_INVOKE_ON_CANCEL)))
1227 {
1228 /* Clear the stack location */
1229 IopClearStackLocation(StackPtr);
1230
1231 /* Check for highest-level device completion routines */
1232 if (Irp->CurrentLocation == (Irp->StackCount + 1))
1233 {
1234 /* Clear the DO, since the current stack location is invalid */
1235 DeviceObject = NULL;
1236 }
1237 else
1238 {
1239 /* Otherwise, return the real one */
1240 DeviceObject = IoGetCurrentIrpStackLocation(Irp)->DeviceObject;
1241 }
1242
1243 /* Call the completion routine */
1244 Status = StackPtr->CompletionRoutine(DeviceObject,
1245 Irp,
1246 StackPtr->Context);
1247
1248 /* Don't touch the Packet in this case, since it might be gone! */
1249 if (Status == STATUS_MORE_PROCESSING_REQUIRED) return;
1250 }
1251 else
1252 {
1253 /* Otherwise, check if this is a completed IRP */
1254 if ((Irp->CurrentLocation <= Irp->StackCount) &&
1255 (Irp->PendingReturned))
1256 {
1257 /* Mark it as pending */
1258 IoMarkIrpPending(Irp);
1259 }
1260
1261 /* Clear the stack location */
1262 IopClearStackLocation(StackPtr);
1263 }
1264
1265 /* Move to next stack location and pointer */
1266 IoSkipCurrentIrpStackLocation(Irp);
1267 StackPtr++;
1268 } while (Irp->CurrentLocation <= (Irp->StackCount + 1));
1269
1270 /* Check if the IRP is an associated IRP */
1271 if (Irp->Flags & IRP_ASSOCIATED_IRP)
1272 {
1273 /* Get the master IRP and count */
1274 MasterIrp = Irp->AssociatedIrp.MasterIrp;
1275 MasterCount = InterlockedDecrement(&MasterIrp->AssociatedIrp.IrpCount);
1276
1277 /* Free the MDLs */
1278 for (Mdl = Irp->MdlAddress; Mdl; Mdl = NextMdl)
1279 {
1280 /* Go to the next one */
1281 NextMdl = Mdl->Next;
1282 IoFreeMdl(Mdl);
1283 }
1284
1285 /* Free the IRP itself */
1286 IoFreeIrp(Irp);
1287
1288 /* Complete the Master IRP */
1289 if (!MasterCount) IofCompleteRequest(MasterIrp, PriorityBoost);
1290 return;
1291 }
1292
1293 /* We don't support this yet */
1294 ASSERT(Irp->IoStatus.Status != STATUS_REPARSE);
1295
1296 /* Check if we have an auxiliary buffer */
1297 if (Irp->Tail.Overlay.AuxiliaryBuffer)
1298 {
1299 /* Free it */
1300 ExFreePool(Irp->Tail.Overlay.AuxiliaryBuffer);
1301 Irp->Tail.Overlay.AuxiliaryBuffer = NULL;
1302 }
1303
1304 /* Check if this is a Paging I/O or Close Operation */
1305 if (Irp->Flags & (IRP_PAGING_IO | IRP_CLOSE_OPERATION))
1306 {
1307 /* Handle a Close Operation or Sync Paging I/O */
1308 if (Irp->Flags & (IRP_SYNCHRONOUS_PAGING_IO | IRP_CLOSE_OPERATION))
1309 {
1310 /* Set the I/O Status and Signal the Event */
1311 Flags = Irp->Flags & (IRP_SYNCHRONOUS_PAGING_IO | IRP_PAGING_IO);
1312 *Irp->UserIosb = Irp->IoStatus;
1313 KeSetEvent(Irp->UserEvent, PriorityBoost, FALSE);
1314
1315 /* Free the IRP for a Paging I/O Only, Close is handled by us */
1316 if (Flags) IoFreeIrp(Irp);
1317 }
1318 else
1319 {
1320 #if 0
1321 /* Page 166 */
1322 KeInitializeApc(&Irp->Tail.Apc
1323 &Irp->Tail.Overlay.Thread->Tcb,
1324 Irp->ApcEnvironment,
1325 IopCompletePageWrite,
1326 NULL,
1327 NULL,
1328 KernelMode,
1329 NULL);
1330 KeInsertQueueApc(&Irp->Tail.Apc,
1331 NULL,
1332 NULL,
1333 PriorityBoost);
1334 #else
1335 /* Not implemented yet. */
1336 DPRINT1("Not supported!\n");
1337 while (TRUE);
1338 #endif
1339 }
1340
1341 /* Get out of here */
1342 return;
1343 }
1344
1345 /* Unlock MDL Pages, page 167. */
1346 Mdl = Irp->MdlAddress;
1347 while (Mdl)
1348 {
1349 MmUnlockPages(Mdl);
1350 Mdl = Mdl->Next;
1351 }
1352
1353 /* Check if we should exit because of a Deferred I/O (page 168) */
1354 if ((Irp->Flags & IRP_DEFER_IO_COMPLETION) && !(Irp->PendingReturned))
1355 {
1356 /*
1357 * Return without queuing the completion APC, since the caller will
1358 * take care of doing its own optimized completion at PASSIVE_LEVEL.
1359 */
1360 return;
1361 }
1362
1363 /* Get the thread and file object */
1364 Thread = Irp->Tail.Overlay.Thread;
1365 FileObject = Irp->Tail.Overlay.OriginalFileObject;
1366
1367 /* Make sure the IRP isn't canceled */
1368 if (!Irp->Cancel)
1369 {
1370 /* Initialize the APC */
1371 KeInitializeApc(&Irp->Tail.Apc,
1372 &Thread->Tcb,
1373 Irp->ApcEnvironment,
1374 IopCompleteRequest,
1375 NULL,
1376 NULL,
1377 KernelMode,
1378 NULL);
1379
1380 /* Queue it */
1381 KeInsertQueueApc(&Irp->Tail.Apc,
1382 FileObject,
1383 NULL, /* This is used for REPARSE stuff */
1384 PriorityBoost);
1385 }
1386 else
1387 {
1388 /* The IRP just got canceled... does a thread still own it? */
1389 Thread = Irp->Tail.Overlay.Thread;
1390 if (Thread)
1391 {
1392 /* Yes! There is still hope! Initialize the APC */
1393 KeInitializeApc(&Irp->Tail.Apc,
1394 &Thread->Tcb,
1395 Irp->ApcEnvironment,
1396 IopCompleteRequest,
1397 NULL,
1398 NULL,
1399 KernelMode,
1400 NULL);
1401
1402 /* Queue it */
1403 KeInsertQueueApc(&Irp->Tail.Apc,
1404 FileObject,
1405 NULL, /* This is used for REPARSE stuff */
1406 PriorityBoost);
1407 }
1408 else
1409 {
1410 /* Nothing left for us to do, kill it */
1411 ASSERT(Irp->Cancel);
1412 IopCleanupIrp(Irp, FileObject);
1413 }
1414 }
1415 }
1416
1417 NTSTATUS
1418 NTAPI
1419 IopSynchronousCompletion(
1420 IN PDEVICE_OBJECT DeviceObject,
1421 IN PIRP Irp,
1422 IN PVOID Context)
1423 {
1424 if (Irp->PendingReturned)
1425 KeSetEvent((PKEVENT)Context, IO_NO_INCREMENT, FALSE);
1426 return STATUS_MORE_PROCESSING_REQUIRED;
1427 }
1428
1429 /*
1430 * @implemented
1431 */
1432 BOOLEAN
1433 NTAPI
1434 IoForwardIrpSynchronously(IN PDEVICE_OBJECT DeviceObject,
1435 IN PIRP Irp)
1436 {
1437 KEVENT Event;
1438 NTSTATUS Status;
1439
1440 /* Check if next stack location is available */
1441 if (Irp->CurrentLocation < Irp->StackCount)
1442 {
1443 /* No more stack location */
1444 return FALSE;
1445 }
1446
1447 /* Initialize event */
1448 KeInitializeEvent(&Event, NotificationEvent, FALSE);
1449
1450 /* Copy stack location for next driver */
1451 IoCopyCurrentIrpStackLocationToNext(Irp);
1452
1453 /* Set a completion routine, which will signal the event */
1454 IoSetCompletionRoutine(Irp, IopSynchronousCompletion, &Event, TRUE, TRUE, TRUE);
1455
1456 /* Call next driver */
1457 Status = IoCallDriver(DeviceObject, Irp);
1458
1459 /* Check if irp is pending */
1460 if (Status == STATUS_PENDING)
1461 {
1462 /* Yes, wait for its completion */
1463 KeWaitForSingleObject(&Event, Suspended, KernelMode, FALSE, NULL);
1464 }
1465
1466 return TRUE;
1467 }
1468
1469 /*
1470 * @implemented
1471 */
1472 VOID
1473 NTAPI
1474 IoFreeIrp(IN PIRP Irp)
1475 {
1476 PNPAGED_LOOKASIDE_LIST List;
1477 PP_NPAGED_LOOKASIDE_NUMBER ListType = LookasideSmallIrpList;
1478 PKPRCB Prcb;
1479 IOTRACE(IO_IRP_DEBUG,
1480 "%s - Freeing IRPs %p\n",
1481 __FUNCTION__,
1482 Irp);
1483
1484 /* Make sure the Thread IRP list is empty and that it OK to free it */
1485 ASSERT(Irp->Type == IO_TYPE_IRP);
1486 ASSERT(IsListEmpty(&Irp->ThreadListEntry));
1487 ASSERT(Irp->CurrentLocation >= Irp->StackCount);
1488
1489 /* If this was a pool alloc, free it with the pool */
1490 if (!(Irp->AllocationFlags & IRP_ALLOCATED_FIXED_SIZE))
1491 {
1492 /* Free it */
1493 ExFreePool(Irp);
1494 }
1495 else
1496 {
1497 /* Check if this was a Big IRP */
1498 if (Irp->StackCount != 1) ListType = LookasideLargeIrpList;
1499
1500 /* Get the PRCB */
1501 Prcb = KeGetCurrentPrcb();
1502
1503 /* Use the P List */
1504 List = (PNPAGED_LOOKASIDE_LIST)Prcb->PPLookasideList[ListType].P;
1505 List->L.TotalFrees++;
1506
1507 /* Check if the Free was within the Depth or not */
1508 if (ExQueryDepthSList(&List->L.ListHead) >= List->L.Depth)
1509 {
1510 /* Let the balancer know */
1511 List->L.FreeMisses++;
1512
1513 /* Use the L List */
1514 List = (PNPAGED_LOOKASIDE_LIST)Prcb->PPLookasideList[ListType].L;
1515 List->L.TotalFrees++;
1516
1517 /* Check if the Free was within the Depth or not */
1518 if (ExQueryDepthSList(&List->L.ListHead) >= List->L.Depth)
1519 {
1520 /* All lists failed, use the pool */
1521 List->L.FreeMisses++;
1522 ExFreePool(Irp);
1523 Irp = NULL;
1524 }
1525 }
1526
1527 /* The free was within the Depth */
1528 if (Irp)
1529 {
1530 InterlockedPushEntrySList(&List->L.ListHead,
1531 (PSINGLE_LIST_ENTRY)Irp);
1532 }
1533 }
1534 }
1535
1536 /*
1537 * @implemented
1538 */
1539 PEPROCESS NTAPI
1540 IoGetRequestorProcess(IN PIRP Irp)
1541 {
1542 return(Irp->Tail.Overlay.Thread->ThreadsProcess);
1543 }
1544
1545 /*
1546 * @implemented
1547 */
1548 ULONG
1549 NTAPI
1550 IoGetRequestorProcessId(IN PIRP Irp)
1551 {
1552 return (ULONG)(IoGetRequestorProcess(Irp)->UniqueProcessId);
1553 }
1554
1555 /*
1556 * @implemented
1557 */
1558 NTSTATUS
1559 NTAPI
1560 IoGetRequestorSessionId(IN PIRP Irp,
1561 OUT PULONG pSessionId)
1562 {
1563 /* Return the session */
1564 *pSessionId = IoGetRequestorProcess(Irp)->Session;
1565 return STATUS_SUCCESS;
1566 }
1567
1568 /*
1569 * @implemented
1570 */
1571 PIRP
1572 NTAPI
1573 IoGetTopLevelIrp(VOID)
1574 {
1575 return (PIRP)PsGetCurrentThread()->TopLevelIrp;
1576 }
1577
1578 /*
1579 * @implemented
1580 */
1581 VOID
1582 NTAPI
1583 IoInitializeIrp(IN PIRP Irp,
1584 IN USHORT PacketSize,
1585 IN CCHAR StackSize)
1586 {
1587 /* Clear it */
1588 IOTRACE(IO_IRP_DEBUG,
1589 "%s - Initializing IRP %p\n",
1590 __FUNCTION__,
1591 Irp);
1592 RtlZeroMemory(Irp, PacketSize);
1593
1594 /* Set the Header and other data */
1595 Irp->Type = IO_TYPE_IRP;
1596 Irp->Size = PacketSize;
1597 Irp->StackCount = StackSize;
1598 Irp->CurrentLocation = StackSize + 1;
1599 Irp->ApcEnvironment = KeGetCurrentThread()->ApcStateIndex;
1600 Irp->Tail.Overlay.CurrentStackLocation = (PIO_STACK_LOCATION)(Irp + 1) + StackSize;
1601
1602 /* Initialize the Thread List */
1603 InitializeListHead(&Irp->ThreadListEntry);
1604 }
1605
1606 /*
1607 * @implemented
1608 */
1609 BOOLEAN
1610 NTAPI
1611 IoIsOperationSynchronous(IN PIRP Irp)
1612 {
1613 /* Check the flags */
1614 if (!(Irp->Flags & (IRP_PAGING_IO | IRP_SYNCHRONOUS_PAGING_IO)) &&
1615 ((Irp->Flags & IRP_SYNCHRONOUS_PAGING_IO) ||
1616 (Irp->Flags & IRP_SYNCHRONOUS_API) ||
1617 (IoGetCurrentIrpStackLocation(Irp)->FileObject->Flags &
1618 FO_SYNCHRONOUS_IO)))
1619 {
1620 /* Synch API or Paging I/O is OK, as is Sync File I/O */
1621 return TRUE;
1622 }
1623
1624 /* Otherwise, it is an asynchronous operation. */
1625 return FALSE;
1626 }
1627
1628 /*
1629 * @unimplemented
1630 */
1631 BOOLEAN
1632 NTAPI
1633 IoIsValidNameGraftingBuffer(IN PIRP Irp,
1634 IN PREPARSE_DATA_BUFFER ReparseBuffer)
1635 {
1636 UNIMPLEMENTED;
1637 return FALSE;
1638 }
1639
1640 /*
1641 * @implemented
1642 */
1643 PIRP
1644 NTAPI
1645 IoMakeAssociatedIrp(IN PIRP Irp,
1646 IN CCHAR StackSize)
1647 {
1648 PIRP AssocIrp;
1649 IOTRACE(IO_IRP_DEBUG,
1650 "%s - Associating IRP %p\n",
1651 __FUNCTION__,
1652 Irp);
1653
1654 /* Allocate the IRP */
1655 AssocIrp = IoAllocateIrp(StackSize, FALSE);
1656 if (!AssocIrp) return NULL;
1657
1658 /* Set the Flags */
1659 AssocIrp->Flags |= IRP_ASSOCIATED_IRP;
1660
1661 /* Set the Thread */
1662 AssocIrp->Tail.Overlay.Thread = Irp->Tail.Overlay.Thread;
1663
1664 /* Associate them */
1665 AssocIrp->AssociatedIrp.MasterIrp = Irp;
1666 return AssocIrp;
1667 }
1668
1669 /*
1670 * @implemented
1671 */
1672 VOID
1673 NTAPI
1674 IoQueueThreadIrp(IN PIRP Irp)
1675 {
1676 IOTRACE(IO_IRP_DEBUG,
1677 "%s - Queueing IRP %p\n",
1678 __FUNCTION__,
1679 Irp);
1680
1681 /* Use our inlined routine */
1682 IopQueueIrpToThread(Irp);
1683 }
1684
1685 /*
1686 * @implemented
1687 * Reference: Chris Cant's "Writing WDM Device Drivers"
1688 */
1689 VOID
1690 NTAPI
1691 IoReuseIrp(IN OUT PIRP Irp,
1692 IN NTSTATUS Status)
1693 {
1694 UCHAR AllocationFlags;
1695 IOTRACE(IO_IRP_DEBUG,
1696 "%s - Reusing IRP %p\n",
1697 __FUNCTION__,
1698 Irp);
1699
1700 /* Make sure it's OK to reuse it */
1701 ASSERT(!Irp->CancelRoutine);
1702 ASSERT(IsListEmpty(&Irp->ThreadListEntry));
1703
1704 /* Get the old flags */
1705 AllocationFlags = Irp->AllocationFlags;
1706
1707 /* Reinitialize the IRP */
1708 IoInitializeIrp(Irp, Irp->Size, Irp->StackCount);
1709
1710 /* Duplicate the data */
1711 Irp->IoStatus.Status = Status;
1712 Irp->AllocationFlags = AllocationFlags;
1713 }
1714
1715 /*
1716 * @implemented
1717 */
1718 VOID
1719 NTAPI
1720 IoSetTopLevelIrp(IN PIRP Irp)
1721 {
1722 /* Set the IRP */
1723 PsGetCurrentThread()->TopLevelIrp = (ULONG)Irp;
1724 }
1725
1726 /* EOF */