[NTOSKRNL] Dereference page file objects in MM shutdown phase 1
[reactos.git] / ntoskrnl / po / poshtdwn.c
1 /*
2 * PROJECT: ReactOS Kernel
3 * LICENSE: BSD - See COPYING.ARM in the top level directory
4 * FILE: ntoskrnl/po/poshtdwn.c
5 * PURPOSE: Power Manager Shutdown Code
6 * PROGRAMMERS: ReactOS Portable Systems Group
7 */
8
9 /* INCLUDES ******************************************************************/
10
11 #include <ntoskrnl.h>
12 #ifdef NEWCC
13 #include <cache/newcc.h>
14 #endif
15 #define NDEBUG
16 #include <debug.h>
17
18 /* GLOBALS *******************************************************************/
19
20 ULONG PopShutdownPowerOffPolicy;
21 KEVENT PopShutdownEvent;
22 PPOP_SHUTDOWN_WAIT_ENTRY PopShutdownThreadList;
23 LIST_ENTRY PopShutdownQueue;
24 KGUARDED_MUTEX PopShutdownListMutex;
25 BOOLEAN PopShutdownListAvailable;
26
27
28 /* PRIVATE FUNCTIONS *********************************************************/
29
30 VOID
31 NTAPI
32 PopInitShutdownList(VOID)
33 {
34 PAGED_CODE();
35
36 /* Initialize the global shutdown event */
37 KeInitializeEvent(&PopShutdownEvent, NotificationEvent, FALSE);
38
39 /* Initialize the shutdown lists */
40 PopShutdownThreadList = NULL;
41 InitializeListHead(&PopShutdownQueue);
42
43 /* Initialize the shutdown list lock */
44 KeInitializeGuardedMutex(&PopShutdownListMutex);
45
46 /* The list is available now */
47 PopShutdownListAvailable = TRUE;
48 }
49
50 NTSTATUS
51 NTAPI
52 PoRequestShutdownWait(
53 _In_ PETHREAD Thread)
54 {
55 PPOP_SHUTDOWN_WAIT_ENTRY ShutDownWaitEntry;
56 NTSTATUS Status;
57 PAGED_CODE();
58
59 /* Allocate a new shutdown wait entry */
60 ShutDownWaitEntry = ExAllocatePoolWithTag(PagedPool, sizeof(*ShutDownWaitEntry), 'LSoP');
61 if (ShutDownWaitEntry == NULL)
62 {
63 return STATUS_NO_MEMORY;
64 }
65
66 /* Reference the thread and save it in the wait entry */
67 ObReferenceObject(Thread);
68 ShutDownWaitEntry->Thread = Thread;
69
70 /* Acquire the shutdown list lock */
71 KeAcquireGuardedMutex(&PopShutdownListMutex);
72
73 /* Check if the list is still available */
74 if (PopShutdownListAvailable)
75 {
76 /* Insert the item in the list */
77 ShutDownWaitEntry->NextEntry = PopShutdownThreadList;
78 PopShutdownThreadList = ShutDownWaitEntry;
79
80 /* We are successful */
81 Status = STATUS_SUCCESS;
82 }
83 else
84 {
85 /* We cannot proceed, cleanup and return failure */
86 ObDereferenceObject(Thread);
87 ExFreePoolWithTag(ShutDownWaitEntry, 'LSoP');
88 Status = STATUS_UNSUCCESSFUL;
89 }
90
91 /* Release the list lock */
92 KeReleaseGuardedMutex(&PopShutdownListMutex);
93
94 /* Return the status */
95 return Status;
96 }
97
98 VOID
99 NTAPI
100 PopProcessShutDownLists(VOID)
101 {
102 PPOP_SHUTDOWN_WAIT_ENTRY ShutDownWaitEntry;
103 PWORK_QUEUE_ITEM WorkItem;
104 PLIST_ENTRY ListEntry;
105
106 /* First signal the shutdown event */
107 KeSetEvent(&PopShutdownEvent, IO_NO_INCREMENT, FALSE);
108
109 /* Acquire the shutdown list lock */
110 KeAcquireGuardedMutex(&PopShutdownListMutex);
111
112 /* Block any further attempts to register a shutdown event */
113 PopShutdownListAvailable = FALSE;
114
115 /* Release the list lock, since we are exclusively using the lists now */
116 KeReleaseGuardedMutex(&PopShutdownListMutex);
117
118 /* Process the shutdown queue */
119 while (!IsListEmpty(&PopShutdownQueue))
120 {
121 /* Get the head entry */
122 ListEntry = RemoveHeadList(&PopShutdownQueue);
123 WorkItem = CONTAINING_RECORD(ListEntry, WORK_QUEUE_ITEM, List);
124
125 /* Call the shutdown worker routine */
126 WorkItem->WorkerRoutine(WorkItem->Parameter);
127 }
128
129 /* Now process the shutdown thread list */
130 while (PopShutdownThreadList != NULL)
131 {
132 /* Get the top entry and remove it from the list */
133 ShutDownWaitEntry = PopShutdownThreadList;
134 PopShutdownThreadList = PopShutdownThreadList->NextEntry;
135
136 /* Wait for the thread to finish and dereference it */
137 KeWaitForSingleObject(ShutDownWaitEntry->Thread, 0, 0, 0, 0);
138 ObfDereferenceObject(ShutDownWaitEntry->Thread);
139
140 /* Finally free the entry */
141 ExFreePoolWithTag(ShutDownWaitEntry, 'LSoP');
142 }
143 }
144
145 VOID
146 NTAPI
147 PopShutdownHandler(VOID)
148 {
149 PUCHAR Logo1, Logo2;
150 ULONG i;
151
152 /* Stop all interrupts */
153 KeRaiseIrqlToDpcLevel();
154 _disable();
155
156 /* Do we have boot video */
157 if (InbvIsBootDriverInstalled())
158 {
159 /* Yes we do, cleanup for shutdown screen */
160 if (!InbvCheckDisplayOwnership()) InbvAcquireDisplayOwnership();
161 InbvResetDisplay();
162 InbvSolidColorFill(0, 0, 639, 479, 0);
163 InbvEnableDisplayString(TRUE);
164 InbvSetScrollRegion(0, 0, 639, 479);
165
166 /* Display shutdown logo and message */
167 Logo1 = InbvGetResourceAddress(IDB_SHUTDOWN_MSG);
168 Logo2 = InbvGetResourceAddress(IDB_DEFAULT_LOGO);
169 if ((Logo1) && (Logo2))
170 {
171 InbvBitBlt(Logo1, 220, 352);
172 InbvBitBlt(Logo2, 222, 111);
173 }
174 }
175 else
176 {
177 /* Do it in text-mode */
178 for (i = 0; i < 25; i++) InbvDisplayString("\r\n");
179 InbvDisplayString(" ");
180 InbvDisplayString("The system may be powered off now.\r\n");
181 }
182
183 /* Hang the system */
184 for (;;) HalHaltSystem();
185 }
186
187 VOID
188 NTAPI
189 PopShutdownSystem(IN POWER_ACTION SystemAction)
190 {
191 /* Note should notify caller of NtPowerInformation(PowerShutdownNotification) */
192
193 /* Unload symbols */
194 DPRINT("It's the final countdown...%lx\n", SystemAction);
195 DbgUnLoadImageSymbols(NULL, (PVOID)-1, 0);
196
197 /* Run the thread on the boot processor */
198 KeSetSystemAffinityThread(1);
199
200 /* Now check what the caller wants */
201 switch (SystemAction)
202 {
203 /* Reset */
204 case PowerActionShutdownReset:
205
206 /* Try platform driver first, then legacy */
207 //PopInvokeSystemStateHandler(PowerStateShutdownReset, NULL);
208 PopSetSystemPowerState(PowerSystemShutdown, SystemAction);
209 HalReturnToFirmware(HalRebootRoutine);
210 break;
211
212 case PowerActionShutdown:
213
214 /* Check for group policy that says to use "it is now safe" screen */
215 if (PopShutdownPowerOffPolicy)
216 {
217 /* FIXFIX: Switch to legacy shutdown handler */
218 //PopPowerStateHandlers[PowerStateShutdownOff].Handler = PopShutdownHandler;
219 }
220
221 case PowerActionShutdownOff:
222
223 /* Call shutdown handler */
224 //PopInvokeSystemStateHandler(PowerStateShutdownOff, NULL);
225
226 /* ReactOS Hack */
227 PopSetSystemPowerState(PowerSystemShutdown, SystemAction);
228 PopShutdownHandler();
229
230 /* If that didn't work, call the HAL */
231 HalReturnToFirmware(HalPowerDownRoutine);
232 break;
233
234 default:
235 break;
236 }
237
238 /* Anything else should not happen */
239 KeBugCheckEx(INTERNAL_POWER_ERROR, 5, 0, 0, 0);
240 }
241
242 VOID
243 NTAPI
244 PopGracefulShutdown(IN PVOID Context)
245 {
246 PEPROCESS Process = NULL;
247
248 /* Process the registered waits and work items */
249 PopProcessShutDownLists();
250
251 /* Loop every process */
252 Process = PsGetNextProcess(Process);
253 while (Process)
254 {
255 /* Make sure this isn't the idle or initial process */
256 if ((Process != PsInitialSystemProcess) && (Process != PsIdleProcess))
257 {
258 /* Print it */
259 DPRINT1("%15s is still RUNNING (%p)\n", Process->ImageFileName, Process->UniqueProcessId);
260 }
261
262 /* Get the next process */
263 Process = PsGetNextProcess(Process);
264 }
265
266 /* First, the HAL handles any "end of boot" special functionality */
267 DPRINT("HAL shutting down\n");
268 HalEndOfBoot();
269
270 /* Shut down the Shim cache if enabled */
271 ApphelpCacheShutdown();
272
273 /* In this step, the I/O manager does first-chance shutdown notification */
274 DPRINT("I/O manager shutting down in phase 0\n");
275 IoShutdownSystem(0);
276
277 /* In this step, all workers are killed and hives are flushed */
278 DPRINT("Configuration Manager shutting down\n");
279 CmShutdownSystem();
280
281 /* Shut down the Executive */
282 DPRINT("Executive shutting down\n");
283 ExShutdownSystem();
284
285 /* Note that modified pages should be written here (MiShutdownSystem) */
286 MmShutdownSystem(0);
287
288 /* Flush all user files before we start shutting down IO */
289 /* This is where modified pages are written back by the IO manager */
290 CcShutdownSystem();
291
292 /* In this step, the I/O manager does last-chance shutdown notification */
293 DPRINT("I/O manager shutting down in phase 1\n");
294 IoShutdownSystem(1);
295 CcWaitForCurrentLazyWriterActivity();
296
297 /* FIXME: Calling Mm shutdown phase 1 here to get page file dereference
298 * but it shouldn't be called here. Only phase 2 should be called.
299 */
300 MmShutdownSystem(1);
301
302 /* Note that here, we should broadcast the power IRP to devices */
303
304 /* In this step, the HAL disables any wake timers */
305 DPRINT("Disabling wake timers\n");
306 HalSetWakeEnable(FALSE);
307
308 /* And finally the power request is sent */
309 DPRINT("Taking the system down\n");
310 PopShutdownSystem(PopAction.Action);
311 }
312
313 VOID
314 NTAPI
315 PopReadShutdownPolicy(VOID)
316 {
317 UNICODE_STRING KeyString;
318 OBJECT_ATTRIBUTES ObjectAttributes;
319 NTSTATUS Status;
320 HANDLE KeyHandle;
321 ULONG Length;
322 UCHAR Buffer[sizeof(KEY_VALUE_PARTIAL_INFORMATION) + sizeof(ULONG)];
323 PKEY_VALUE_PARTIAL_INFORMATION Info = (PVOID)Buffer;
324
325 /* Setup object attributes */
326 RtlInitUnicodeString(&KeyString,
327 L"\\Registry\\Machine\\Software\\Policies\\Microsoft\\Windows NT");
328 InitializeObjectAttributes(&ObjectAttributes,
329 &KeyString,
330 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
331 NULL,
332 NULL);
333
334 /* Open the key */
335 Status = ZwOpenKey(&KeyHandle, KEY_READ, &ObjectAttributes);
336 if (NT_SUCCESS(Status))
337 {
338 /* Open the policy value and query it */
339 RtlInitUnicodeString(&KeyString, L"DontPowerOffAfterShutdown");
340 Status = ZwQueryValueKey(KeyHandle,
341 &KeyString,
342 KeyValuePartialInformation,
343 &Info,
344 sizeof(Info),
345 &Length);
346 if ((NT_SUCCESS(Status)) && (Info->Type == REG_DWORD))
347 {
348 /* Read the policy */
349 PopShutdownPowerOffPolicy = *Info->Data == 1;
350 }
351
352 /* Close the key */
353 ZwClose(KeyHandle);
354 }
355 }
356
357 /* PUBLIC FUNCTIONS **********************************************************/
358
359 /*
360 * @unimplemented
361 */
362 NTSTATUS
363 NTAPI
364 PoQueueShutdownWorkItem(
365 _In_ PWORK_QUEUE_ITEM WorkItem)
366 {
367 NTSTATUS Status;
368
369 /* Acquire the shutdown list lock */
370 KeAcquireGuardedMutex(&PopShutdownListMutex);
371
372 /* Check if the list is (already/still) available */
373 if (PopShutdownListAvailable)
374 {
375 /* Insert the item into the list */
376 InsertTailList(&PopShutdownQueue, &WorkItem->List);
377 Status = STATUS_SUCCESS;
378 }
379 else
380 {
381 /* We are already in shutdown */
382 Status = STATUS_SYSTEM_SHUTDOWN;
383 }
384
385 /* Release the list lock */
386 KeReleaseGuardedMutex(&PopShutdownListMutex);
387
388 return Status;
389 }
390
391 /*
392 * @implemented
393 */
394 NTSTATUS
395 NTAPI
396 PoRequestShutdownEvent(OUT PVOID *Event)
397 {
398 NTSTATUS Status;
399 PAGED_CODE();
400
401 /* Initialize to NULL */
402 if (Event) *Event = NULL;
403
404 /* Request a shutdown wait */
405 Status = PoRequestShutdownWait(PsGetCurrentThread());
406 if (!NT_SUCCESS(Status))
407 {
408 return Status;
409 }
410
411 /* Return the global shutdown event */
412 if (Event) *Event = &PopShutdownEvent;
413 return STATUS_SUCCESS;
414 }
415