[CMAKE]
[reactos.git] / ntoskrnl / fstub / disksup.c
1 /*
2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/fstub/disksup.c
5 * PURPOSE: I/O HAL Routines for Disk Access
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
7 * Eric Kohl
8 * Casper S. Hornstrup (chorns@users.sourceforge.net)
9 */
10
11 /* INCLUDES ******************************************************************/
12
13 #include <ntoskrnl.h>
14 #define NDEBUG
15 #include <debug.h>
16 #include <internal/hal.h>
17
18 /* DEPRECATED FUNCTIONS ******************************************************/
19
20 #if 1
21 const WCHAR DiskMountString[] = L"\\DosDevices\\%C:";
22
23 #define AUTO_DRIVE MAXULONG
24
25 #define PARTITION_MAGIC 0xaa55
26
27 #define EFI_PMBR_OSTYPE_EFI 0xEE
28
29 #include <pshpack1.h>
30
31 typedef struct _REG_DISK_MOUNT_INFO
32 {
33 ULONG Signature;
34 LARGE_INTEGER StartingOffset;
35 } REG_DISK_MOUNT_INFO, *PREG_DISK_MOUNT_INFO;
36
37 #include <poppack.h>
38
39 typedef enum _DISK_MANAGER
40 {
41 NoDiskManager,
42 OntrackDiskManager,
43 EZ_Drive
44 } DISK_MANAGER;
45
46 static BOOLEAN
47 HalpAssignDrive(IN PUNICODE_STRING PartitionName,
48 IN ULONG DriveNumber,
49 IN UCHAR DriveType,
50 IN ULONG Signature,
51 IN LARGE_INTEGER StartingOffset,
52 IN HANDLE hKey,
53 IN PUNICODE_STRING BootDevice,
54 OUT PUCHAR NtSystemPath)
55 {
56 WCHAR DriveNameBuffer[16];
57 UNICODE_STRING DriveName;
58 ULONG i;
59 NTSTATUS Status;
60 REG_DISK_MOUNT_INFO DiskMountInfo;
61
62 DPRINT("HalpAssignDrive()\n");
63
64 if ((DriveNumber != AUTO_DRIVE) && (DriveNumber < 26))
65 {
66 /* Force assignment */
67 KeAcquireGuardedMutex(&ObpDeviceMapLock);
68 if ((ObSystemDeviceMap->DriveMap & (1 << DriveNumber)) != 0)
69 {
70 DbgPrint("Drive letter already used!\n");
71 KeReleaseGuardedMutex(&ObpDeviceMapLock);
72 return FALSE;
73 }
74 KeReleaseGuardedMutex(&ObpDeviceMapLock);
75 }
76 else
77 {
78 /* Automatic assignment */
79 DriveNumber = AUTO_DRIVE;
80 KeAcquireGuardedMutex(&ObpDeviceMapLock);
81 for (i = 2; i < 26; i++)
82 {
83 if ((ObSystemDeviceMap->DriveMap & (1 << i)) == 0)
84 {
85 DriveNumber = i;
86 break;
87 }
88 }
89 KeReleaseGuardedMutex(&ObpDeviceMapLock);
90
91 if (DriveNumber == AUTO_DRIVE)
92 {
93 DbgPrint("No drive letter available!\n");
94 return FALSE;
95 }
96 }
97
98 DPRINT("DriveNumber %d\n", DriveNumber);
99
100 /* Build drive name */
101 swprintf(DriveNameBuffer,
102 L"\\??\\%C:",
103 'A' + DriveNumber);
104 RtlInitUnicodeString(&DriveName,
105 DriveNameBuffer);
106
107 DPRINT(" %wZ ==> %wZ\n",
108 &DriveName,
109 PartitionName);
110
111 /* Create symbolic link */
112 Status = IoCreateSymbolicLink(&DriveName,
113 PartitionName);
114
115 if (hKey &&
116 DriveType == DOSDEVICE_DRIVE_FIXED &&
117 Signature)
118 {
119 DiskMountInfo.Signature = Signature;
120 DiskMountInfo.StartingOffset = StartingOffset;
121 swprintf(DriveNameBuffer, DiskMountString, L'A' + DriveNumber);
122 RtlInitUnicodeString(&DriveName, DriveNameBuffer);
123
124 Status = ZwSetValueKey(hKey,
125 &DriveName,
126 0,
127 REG_BINARY,
128 &DiskMountInfo,
129 sizeof(DiskMountInfo));
130 if (!NT_SUCCESS(Status))
131 {
132 DPRINT1("ZwCreateValueKey failed for %wZ, status=%x\n", &DriveName, Status);
133 }
134 }
135
136 /* Check if this is a boot partition */
137 if (RtlCompareUnicodeString(PartitionName, BootDevice, FALSE) == 0)
138 {
139 /* Set NtSystemPath to that partition's disk letter */
140 *NtSystemPath = (UCHAR)('A' + DriveNumber);
141 }
142
143 return TRUE;
144 }
145
146 ULONG
147 xHalpGetRDiskCount(VOID)
148 {
149 NTSTATUS Status;
150 UNICODE_STRING ArcName;
151 PWCHAR ArcNameBuffer;
152 OBJECT_ATTRIBUTES ObjectAttributes;
153 HANDLE DirectoryHandle;
154 POBJECT_DIRECTORY_INFORMATION DirectoryInfo;
155 ULONG Skip;
156 ULONG ResultLength;
157 ULONG CurrentRDisk;
158 ULONG RDiskCount;
159 BOOLEAN First = TRUE;
160 ULONG Count;
161
162 DirectoryInfo = ExAllocatePool(PagedPool, 2 * PAGE_SIZE);
163 if (DirectoryInfo == NULL)
164 {
165 return 0;
166 }
167
168 RtlInitUnicodeString(&ArcName, L"\\ArcName");
169 InitializeObjectAttributes(&ObjectAttributes,
170 &ArcName,
171 0,
172 NULL,
173 NULL);
174
175 Status = ZwOpenDirectoryObject (&DirectoryHandle,
176 SYMBOLIC_LINK_ALL_ACCESS,
177 &ObjectAttributes);
178 if (!NT_SUCCESS(Status))
179 {
180 DPRINT1("ZwOpenDirectoryObject for %wZ failed, status=%lx\n", &ArcName, Status);
181 ExFreePool(DirectoryInfo);
182 return 0;
183 }
184
185 RDiskCount = 0;
186 Skip = 0;
187 while (NT_SUCCESS(Status))
188 {
189 Status = NtQueryDirectoryObject (DirectoryHandle,
190 DirectoryInfo,
191 2 * PAGE_SIZE,
192 FALSE,
193 First,
194 &Skip,
195 &ResultLength);
196 First = FALSE;
197 if (NT_SUCCESS(Status))
198 {
199 Count = 0;
200 while (DirectoryInfo[Count].Name.Buffer)
201 {
202 DPRINT("Count %x\n", Count);
203 DirectoryInfo[Count].Name.Buffer[DirectoryInfo[Count].Name.Length / sizeof(WCHAR)] = 0;
204 ArcNameBuffer = DirectoryInfo[Count].Name.Buffer;
205 if (DirectoryInfo[Count].Name.Length >= sizeof(L"multi(0)disk(0)rdisk(0)") - sizeof(WCHAR) &&
206 !_wcsnicmp(ArcNameBuffer, L"multi(0)disk(0)rdisk(", (sizeof(L"multi(0)disk(0)rdisk(") - sizeof(WCHAR)) / sizeof(WCHAR)))
207 {
208 DPRINT("%S\n", ArcNameBuffer);
209 ArcNameBuffer += (sizeof(L"multi(0)disk(0)rdisk(") - sizeof(WCHAR)) / sizeof(WCHAR);
210 CurrentRDisk = 0;
211 while (iswdigit(*ArcNameBuffer))
212 {
213 CurrentRDisk = CurrentRDisk * 10 + *ArcNameBuffer - L'0';
214 ArcNameBuffer++;
215 }
216 if (!_wcsicmp(ArcNameBuffer, L")") &&
217 CurrentRDisk >= RDiskCount)
218 {
219 RDiskCount = CurrentRDisk + 1;
220 }
221 }
222 Count++;
223 }
224 }
225 }
226 ExFreePool(DirectoryInfo);
227 return RDiskCount;
228 }
229
230 NTSTATUS
231 xHalpGetDiskNumberFromRDisk(ULONG RDisk, PULONG DiskNumber)
232 {
233 WCHAR NameBuffer[80];
234 UNICODE_STRING ArcName;
235 UNICODE_STRING LinkName;
236 OBJECT_ATTRIBUTES ObjectAttributes;
237 HANDLE LinkHandle;
238 NTSTATUS Status;
239
240 swprintf(NameBuffer,
241 L"\\ArcName\\multi(0)disk(0)rdisk(%lu)",
242 RDisk);
243
244 RtlInitUnicodeString(&ArcName, NameBuffer);
245 InitializeObjectAttributes(&ObjectAttributes,
246 &ArcName,
247 0,
248 NULL,
249 NULL);
250 Status = ZwOpenSymbolicLinkObject(&LinkHandle,
251 SYMBOLIC_LINK_ALL_ACCESS,
252 &ObjectAttributes);
253 if (!NT_SUCCESS(Status))
254 {
255 DPRINT1("ZwOpenSymbolicLinkObject failed for %wZ, status=%lx\n", &ArcName, Status);
256 return Status;
257 }
258
259 LinkName.Buffer = NameBuffer;
260 LinkName.Length = 0;
261 LinkName.MaximumLength = sizeof(NameBuffer);
262 Status = ZwQuerySymbolicLinkObject(LinkHandle,
263 &LinkName,
264 NULL);
265 ZwClose(LinkHandle);
266 if (!NT_SUCCESS(Status))
267 {
268 DPRINT1("ZwQuerySymbolicLinkObject failed, status=%lx\n", Status);
269 return Status;
270 }
271 if (LinkName.Length < sizeof(L"\\Device\\Harddisk0\\Partition0") - sizeof(WCHAR) ||
272 LinkName.Length >= sizeof(NameBuffer))
273 {
274 return STATUS_UNSUCCESSFUL;
275 }
276
277 NameBuffer[LinkName.Length / sizeof(WCHAR)] = 0;
278 if (_wcsnicmp(NameBuffer, L"\\Device\\Harddisk", (sizeof(L"\\Device\\Harddisk") - sizeof(WCHAR)) / sizeof(WCHAR)))
279 {
280 return STATUS_UNSUCCESSFUL;
281 }
282 LinkName.Buffer += (sizeof(L"\\Device\\Harddisk") - sizeof(WCHAR)) / sizeof(WCHAR);
283
284 if (!iswdigit(*LinkName.Buffer))
285 {
286 return STATUS_UNSUCCESSFUL;
287 }
288 *DiskNumber = 0;
289 while (iswdigit(*LinkName.Buffer))
290 {
291 *DiskNumber = *DiskNumber * 10 + *LinkName.Buffer - L'0';
292 LinkName.Buffer++;
293 }
294 if (_wcsicmp(LinkName.Buffer, L"\\Partition0"))
295 {
296 return STATUS_UNSUCCESSFUL;
297 }
298 return STATUS_SUCCESS;
299 }
300
301 NTSTATUS
302 FASTCALL
303 xHalQueryDriveLayout(IN PUNICODE_STRING DeviceName,
304 OUT PDRIVE_LAYOUT_INFORMATION *LayoutInfo)
305 {
306 IO_STATUS_BLOCK StatusBlock;
307 DISK_GEOMETRY DiskGeometry;
308 PDEVICE_OBJECT DeviceObject = NULL;
309 PFILE_OBJECT FileObject;
310 KEVENT Event;
311 PIRP Irp;
312 NTSTATUS Status;
313
314 DPRINT("xHalpQueryDriveLayout %wZ %p\n",
315 DeviceName,
316 LayoutInfo);
317
318 /* Get the drives sector size */
319 Status = IoGetDeviceObjectPointer(DeviceName,
320 FILE_READ_ATTRIBUTES,
321 &FileObject,
322 &DeviceObject);
323 if (!NT_SUCCESS(Status))
324 {
325 DPRINT("Status %x\n", Status);
326 return(Status);
327 }
328
329 KeInitializeEvent(&Event,
330 NotificationEvent,
331 FALSE);
332
333 Irp = IoBuildDeviceIoControlRequest(IOCTL_DISK_GET_DRIVE_GEOMETRY,
334 DeviceObject,
335 NULL,
336 0,
337 &DiskGeometry,
338 sizeof(DISK_GEOMETRY),
339 FALSE,
340 &Event,
341 &StatusBlock);
342 if (Irp == NULL)
343 {
344 ObDereferenceObject(FileObject);
345 return(STATUS_INSUFFICIENT_RESOURCES);
346 }
347
348 Status = IoCallDriver(DeviceObject,
349 Irp);
350 if (Status == STATUS_PENDING)
351 {
352 KeWaitForSingleObject(&Event,
353 Executive,
354 KernelMode,
355 FALSE,
356 NULL);
357 Status = StatusBlock.Status;
358 }
359 if (!NT_SUCCESS(Status))
360 {
361 if (DeviceObject->Characteristics & FILE_REMOVABLE_MEDIA)
362 {
363 DiskGeometry.BytesPerSector = 512;
364 }
365 else
366 {
367 ObDereferenceObject(FileObject);
368 return(Status);
369 }
370 }
371
372 DPRINT("DiskGeometry.BytesPerSector: %d\n",
373 DiskGeometry.BytesPerSector);
374
375 if (DeviceObject->Characteristics & FILE_REMOVABLE_MEDIA)
376 {
377 PDRIVE_LAYOUT_INFORMATION Buffer;
378
379 /* Allocate a partition list for a single entry. */
380 Buffer = ExAllocatePool(NonPagedPool,
381 sizeof(DRIVE_LAYOUT_INFORMATION));
382 if (Buffer != NULL)
383 {
384 RtlZeroMemory(Buffer,
385 sizeof(DRIVE_LAYOUT_INFORMATION));
386 Buffer->PartitionCount = 1;
387 *LayoutInfo = Buffer;
388
389 Status = STATUS_SUCCESS;
390 }
391 else
392 {
393 Status = STATUS_UNSUCCESSFUL;
394 }
395 }
396 else
397 {
398 /* Read the partition table */
399 Status = IoReadPartitionTable(DeviceObject,
400 DiskGeometry.BytesPerSector,
401 FALSE,
402 LayoutInfo);
403 }
404
405 ObDereferenceObject(FileObject);
406
407 return(Status);
408 }
409
410 VOID
411 FASTCALL
412 xHalIoAssignDriveLetters(IN PLOADER_PARAMETER_BLOCK LoaderBlock,
413 IN PSTRING NtDeviceName,
414 OUT PUCHAR NtSystemPath,
415 OUT PSTRING NtSystemPathString)
416 {
417 PDRIVE_LAYOUT_INFORMATION *LayoutArray;
418 PCONFIGURATION_INFORMATION ConfigInfo;
419 OBJECT_ATTRIBUTES ObjectAttributes;
420 IO_STATUS_BLOCK StatusBlock;
421 UNICODE_STRING UnicodeString1;
422 UNICODE_STRING UnicodeString2;
423 HANDLE FileHandle;
424 PWSTR Buffer1;
425 PWSTR Buffer2;
426 ULONG i, j, k;
427 ULONG DiskNumber;
428 ULONG RDisk;
429 NTSTATUS Status;
430 HANDLE hKey;
431 ULONG Length;
432 PKEY_VALUE_PARTIAL_INFORMATION PartialInformation;
433 PREG_DISK_MOUNT_INFO DiskMountInfo;
434 ULONG RDiskCount;
435 UNICODE_STRING BootDevice;
436
437 Status = RtlAnsiStringToUnicodeString(&BootDevice,
438 NtDeviceName,
439 TRUE);
440
441 DPRINT("xHalIoAssignDriveLetters()\n");
442
443 ConfigInfo = IoGetConfigurationInformation();
444
445 RDiskCount = xHalpGetRDiskCount();
446
447 DPRINT("RDiskCount %d\n", RDiskCount);
448
449 Buffer1 = (PWSTR)ExAllocatePool(PagedPool,
450 64 * sizeof(WCHAR));
451 Buffer2 = (PWSTR)ExAllocatePool(PagedPool,
452 32 * sizeof(WCHAR));
453
454 PartialInformation = (PKEY_VALUE_PARTIAL_INFORMATION)ExAllocatePool(PagedPool,
455 sizeof(KEY_VALUE_PARTIAL_INFORMATION) + sizeof(REG_DISK_MOUNT_INFO));
456
457 if (!Buffer1 || !Buffer2 || !PartialInformation) return;
458
459 DiskMountInfo = (PREG_DISK_MOUNT_INFO) PartialInformation->Data;
460
461 /* Open or Create the 'MountedDevices' key */
462 RtlInitUnicodeString(&UnicodeString1, L"\\Registry\\Machine\\SYSTEM\\MountedDevices");
463 InitializeObjectAttributes(&ObjectAttributes,
464 &UnicodeString1,
465 OBJ_CASE_INSENSITIVE,
466 NULL,
467 NULL);
468 Status = ZwOpenKey(&hKey,
469 KEY_ALL_ACCESS,
470 &ObjectAttributes);
471 if (!NT_SUCCESS(Status))
472 {
473 Status = ZwCreateKey(&hKey,
474 KEY_ALL_ACCESS,
475 &ObjectAttributes,
476 0,
477 NULL,
478 REG_OPTION_NON_VOLATILE,
479 NULL);
480 }
481 if (!NT_SUCCESS(Status))
482 {
483 hKey = NULL;
484 DPRINT("ZwCreateKey failed for %wZ, status=%x\n", &UnicodeString1, Status);
485 }
486
487 /* Create PhysicalDrive links */
488 DPRINT("Physical disk drives: %d\n", ConfigInfo->DiskCount);
489 for (i = 0; i < ConfigInfo->DiskCount; i++)
490 {
491 swprintf(Buffer1,
492 L"\\Device\\Harddisk%d\\Partition0",
493 i);
494 RtlInitUnicodeString(&UnicodeString1,
495 Buffer1);
496
497 InitializeObjectAttributes(&ObjectAttributes,
498 &UnicodeString1,
499 0,
500 NULL,
501 NULL);
502
503 Status = ZwOpenFile(&FileHandle,
504 FILE_READ_DATA | SYNCHRONIZE,
505 &ObjectAttributes,
506 &StatusBlock,
507 FILE_SHARE_READ,
508 FILE_SYNCHRONOUS_IO_NONALERT);
509 if (NT_SUCCESS(Status))
510 {
511 ZwClose(FileHandle);
512
513 swprintf(Buffer2,
514 L"\\??\\PhysicalDrive%d",
515 i);
516 RtlInitUnicodeString(&UnicodeString2,
517 Buffer2);
518
519 DPRINT("Creating link: %S ==> %S\n",
520 Buffer2,
521 Buffer1);
522
523 IoCreateSymbolicLink(&UnicodeString2,
524 &UnicodeString1);
525 }
526 }
527
528 /* Initialize layout array */
529 if (ConfigInfo->DiskCount == 0)
530 goto end_assign_disks;
531 LayoutArray = ExAllocatePool(NonPagedPool,
532 ConfigInfo->DiskCount * sizeof(PDRIVE_LAYOUT_INFORMATION));
533 if (!LayoutArray)
534 {
535 ExFreePool(PartialInformation);
536 ExFreePool(Buffer2);
537 ExFreePool(Buffer1);
538 if (hKey) ZwClose(hKey);
539 }
540
541 RtlZeroMemory(LayoutArray,
542 ConfigInfo->DiskCount * sizeof(PDRIVE_LAYOUT_INFORMATION));
543 for (i = 0; i < ConfigInfo->DiskCount; i++)
544 {
545 swprintf(Buffer1,
546 L"\\Device\\Harddisk%d\\Partition0",
547 i);
548 RtlInitUnicodeString(&UnicodeString1,
549 Buffer1);
550
551 Status = xHalQueryDriveLayout(&UnicodeString1,
552 &LayoutArray[i]);
553 if (!NT_SUCCESS(Status))
554 {
555 DbgPrint("xHalQueryDriveLayout() failed (Status = 0x%lx)\n",
556 Status);
557 LayoutArray[i] = NULL;
558 continue;
559 }
560 /* We don't use the RewritePartition value while mounting the disks.
561 * We use this value for marking pre-assigned (registry) partitions.
562 */
563 for (j = 0; j < LayoutArray[i]->PartitionCount; j++)
564 {
565 LayoutArray[i]->PartitionEntry[j].RewritePartition = FALSE;
566 }
567 }
568
569 #ifndef NDEBUG
570 /* Dump layout array */
571 for (i = 0; i < ConfigInfo->DiskCount; i++)
572 {
573 DPRINT("Harddisk %d:\n",
574 i);
575
576 if (LayoutArray[i] == NULL)
577 continue;
578
579 DPRINT("Logical partitions: %d\n",
580 LayoutArray[i]->PartitionCount);
581
582 for (j = 0; j < LayoutArray[i]->PartitionCount; j++)
583 {
584 DPRINT(" %d: nr:%x boot:%x type:%x startblock:%I64u count:%I64u\n",
585 j,
586 LayoutArray[i]->PartitionEntry[j].PartitionNumber,
587 LayoutArray[i]->PartitionEntry[j].BootIndicator,
588 LayoutArray[i]->PartitionEntry[j].PartitionType,
589 LayoutArray[i]->PartitionEntry[j].StartingOffset.QuadPart,
590 LayoutArray[i]->PartitionEntry[j].PartitionLength.QuadPart);
591 }
592 }
593 #endif
594
595 /* Assign pre-assigned (registry) partitions */
596 if (hKey)
597 {
598 for (k = 2; k < 26; k++)
599 {
600 swprintf(Buffer1, DiskMountString, L'A' + k);
601 RtlInitUnicodeString(&UnicodeString1, Buffer1);
602 Status = ZwQueryValueKey(hKey,
603 &UnicodeString1,
604 KeyValuePartialInformation,
605 PartialInformation,
606 sizeof(KEY_VALUE_PARTIAL_INFORMATION) + sizeof(REG_DISK_MOUNT_INFO),
607 &Length);
608 if (NT_SUCCESS(Status) &&
609 PartialInformation->Type == REG_BINARY &&
610 PartialInformation->DataLength == sizeof(REG_DISK_MOUNT_INFO))
611 {
612 DPRINT("%wZ => %08x:%08x%08x\n", &UnicodeString1, DiskMountInfo->Signature,
613 DiskMountInfo->StartingOffset.u.HighPart, DiskMountInfo->StartingOffset.u.LowPart);
614 {
615 BOOLEAN Found = FALSE;
616 for (i = 0; i < ConfigInfo->DiskCount; i++)
617 {
618 DPRINT("%x\n", LayoutArray[i]->Signature);
619 if (LayoutArray[i] &&
620 LayoutArray[i]->Signature &&
621 LayoutArray[i]->Signature == DiskMountInfo->Signature)
622 {
623 for (j = 0; j < LayoutArray[i]->PartitionCount; j++)
624 {
625 if (LayoutArray[i]->PartitionEntry[j].StartingOffset.QuadPart == DiskMountInfo->StartingOffset.QuadPart)
626 {
627 if (IsRecognizedPartition(LayoutArray[i]->PartitionEntry[j].PartitionType) &&
628 LayoutArray[i]->PartitionEntry[j].RewritePartition == FALSE)
629 {
630 swprintf(Buffer2,
631 L"\\Device\\Harddisk%d\\Partition%d",
632 i,
633 LayoutArray[i]->PartitionEntry[j].PartitionNumber);
634 RtlInitUnicodeString(&UnicodeString2,
635 Buffer2);
636
637 /* Assign drive */
638 DPRINT(" %wZ\n", &UnicodeString2);
639 Found = HalpAssignDrive(&UnicodeString2,
640 k,
641 DOSDEVICE_DRIVE_FIXED,
642 DiskMountInfo->Signature,
643 DiskMountInfo->StartingOffset,
644 NULL,
645 &BootDevice,
646 NtSystemPath);
647 /* Mark the partition as assigned */
648 LayoutArray[i]->PartitionEntry[j].RewritePartition = TRUE;
649 }
650 break;
651 }
652 }
653 }
654 }
655 if (Found == FALSE)
656 {
657 /* We didn't find a partition for this entry, remove them. */
658 Status = ZwDeleteValueKey(hKey, &UnicodeString1);
659 }
660 }
661 }
662 }
663 }
664
665 /* Assign bootable partition on first harddisk */
666 DPRINT("Assigning bootable primary partition on first harddisk:\n");
667 if (RDiskCount > 0)
668 {
669 Status = xHalpGetDiskNumberFromRDisk(0, &DiskNumber);
670 if (NT_SUCCESS(Status) &&
671 DiskNumber < ConfigInfo->DiskCount &&
672 LayoutArray[DiskNumber])
673 {
674 /* Search for bootable partition */
675 for (j = 0; j < NUM_PARTITION_TABLE_ENTRIES && j < LayoutArray[DiskNumber]->PartitionCount; j++)
676 {
677 if ((LayoutArray[DiskNumber]->PartitionEntry[j].BootIndicator == TRUE) &&
678 IsRecognizedPartition(LayoutArray[DiskNumber]->PartitionEntry[j].PartitionType))
679 {
680 if (LayoutArray[DiskNumber]->PartitionEntry[j].RewritePartition == FALSE)
681 {
682 swprintf(Buffer2,
683 L"\\Device\\Harddisk%lu\\Partition%d",
684 DiskNumber,
685 LayoutArray[DiskNumber]->PartitionEntry[j].PartitionNumber);
686 RtlInitUnicodeString(&UnicodeString2,
687 Buffer2);
688
689 /* Assign drive */
690 DPRINT(" %wZ\n", &UnicodeString2);
691 HalpAssignDrive(&UnicodeString2,
692 AUTO_DRIVE,
693 DOSDEVICE_DRIVE_FIXED,
694 LayoutArray[DiskNumber]->Signature,
695 LayoutArray[DiskNumber]->PartitionEntry[j].StartingOffset,
696 hKey,
697 &BootDevice,
698 NtSystemPath);
699 /* Mark the partition as assigned */
700 LayoutArray[DiskNumber]->PartitionEntry[j].RewritePartition = TRUE;
701 }
702 break;
703 }
704 }
705 }
706 }
707
708 /* Assign remaining primary partitions */
709 DPRINT("Assigning remaining primary partitions:\n");
710 for (RDisk = 0; RDisk < RDiskCount; RDisk++)
711 {
712 Status = xHalpGetDiskNumberFromRDisk(RDisk, &DiskNumber);
713 if (NT_SUCCESS(Status) &&
714 DiskNumber < ConfigInfo->DiskCount &&
715 LayoutArray[DiskNumber])
716 {
717 /* Search for primary partitions */
718 for (j = 0; (j < NUM_PARTITION_TABLE_ENTRIES) && (j < LayoutArray[DiskNumber]->PartitionCount); j++)
719 {
720 if (LayoutArray[DiskNumber]->PartitionEntry[j].RewritePartition == FALSE &&
721 IsRecognizedPartition(LayoutArray[DiskNumber]->PartitionEntry[j].PartitionType))
722 {
723 swprintf(Buffer2,
724 L"\\Device\\Harddisk%d\\Partition%d",
725 DiskNumber,
726 LayoutArray[DiskNumber]->PartitionEntry[j].PartitionNumber);
727 RtlInitUnicodeString(&UnicodeString2,
728 Buffer2);
729
730 /* Assign drive */
731 DPRINT(" %wZ\n",
732 &UnicodeString2);
733 HalpAssignDrive(&UnicodeString2,
734 AUTO_DRIVE,
735 DOSDEVICE_DRIVE_FIXED,
736 LayoutArray[DiskNumber]->Signature,
737 LayoutArray[DiskNumber]->PartitionEntry[j].StartingOffset,
738 hKey,
739 &BootDevice,
740 NtSystemPath);
741 /* Mark the partition as assigned */
742 LayoutArray[DiskNumber]->PartitionEntry[j].RewritePartition = TRUE;
743 }
744 }
745 }
746 }
747
748 /* Assign extended (logical) partitions */
749 DPRINT("Assigning extended (logical) partitions:\n");
750 for (RDisk = 0; RDisk < RDiskCount; RDisk++)
751 {
752 Status = xHalpGetDiskNumberFromRDisk(RDisk, &DiskNumber);
753 if (NT_SUCCESS(Status) &&
754 DiskNumber < ConfigInfo->DiskCount &&
755 LayoutArray[DiskNumber])
756 {
757 /* Search for extended partitions */
758 for (j = NUM_PARTITION_TABLE_ENTRIES; j < LayoutArray[DiskNumber]->PartitionCount; j++)
759 {
760 if (IsRecognizedPartition(LayoutArray[DiskNumber]->PartitionEntry[j].PartitionType) &&
761 LayoutArray[DiskNumber]->PartitionEntry[j].RewritePartition == FALSE &&
762 LayoutArray[DiskNumber]->PartitionEntry[j].PartitionNumber != 0)
763 {
764 swprintf(Buffer2,
765 L"\\Device\\Harddisk%d\\Partition%d",
766 DiskNumber,
767 LayoutArray[DiskNumber]->PartitionEntry[j].PartitionNumber);
768 RtlInitUnicodeString(&UnicodeString2,
769 Buffer2);
770
771 /* Assign drive */
772 DPRINT(" %wZ\n",
773 &UnicodeString2);
774 HalpAssignDrive(&UnicodeString2,
775 AUTO_DRIVE,
776 DOSDEVICE_DRIVE_FIXED,
777 LayoutArray[DiskNumber]->Signature,
778 LayoutArray[DiskNumber]->PartitionEntry[j].StartingOffset,
779 hKey,
780 &BootDevice,
781 NtSystemPath);
782 /* Mark the partition as assigned */
783 LayoutArray[DiskNumber]->PartitionEntry[j].RewritePartition = TRUE;
784 }
785 }
786 }
787 }
788
789 /* Assign remaining primary partitions without an arc-name */
790 DPRINT("Assigning remaining primary partitions:\n");
791 for (DiskNumber = 0; DiskNumber < ConfigInfo->DiskCount; DiskNumber++)
792 {
793 if (LayoutArray[DiskNumber])
794 {
795 /* Search for primary partitions */
796 for (j = 0; (j < NUM_PARTITION_TABLE_ENTRIES) && (j < LayoutArray[DiskNumber]->PartitionCount); j++)
797 {
798 if (LayoutArray[DiskNumber]->PartitionEntry[j].RewritePartition == FALSE &&
799 IsRecognizedPartition(LayoutArray[DiskNumber]->PartitionEntry[j].PartitionType))
800 {
801 swprintf(Buffer2,
802 L"\\Device\\Harddisk%d\\Partition%d",
803 DiskNumber,
804 LayoutArray[DiskNumber]->PartitionEntry[j].PartitionNumber);
805 RtlInitUnicodeString(&UnicodeString2,
806 Buffer2);
807
808 /* Assign drive */
809 DPRINT(" %wZ\n",
810 &UnicodeString2);
811 HalpAssignDrive(&UnicodeString2,
812 AUTO_DRIVE,
813 DOSDEVICE_DRIVE_FIXED,
814 LayoutArray[DiskNumber]->Signature,
815 LayoutArray[DiskNumber]->PartitionEntry[j].StartingOffset,
816 hKey,
817 &BootDevice,
818 NtSystemPath);
819 /* Mark the partition as assigned */
820 LayoutArray[DiskNumber]->PartitionEntry[j].RewritePartition = TRUE;
821 }
822 }
823 }
824 }
825
826 /* Assign extended (logical) partitions without an arc-name */
827 DPRINT("Assigning extended (logical) partitions:\n");
828 for (DiskNumber = 0; DiskNumber < ConfigInfo->DiskCount; DiskNumber++)
829 {
830 if (LayoutArray[DiskNumber])
831 {
832 /* Search for extended partitions */
833 for (j = NUM_PARTITION_TABLE_ENTRIES; j < LayoutArray[DiskNumber]->PartitionCount; j++)
834 {
835 if (IsRecognizedPartition(LayoutArray[DiskNumber]->PartitionEntry[j].PartitionType) &&
836 LayoutArray[DiskNumber]->PartitionEntry[j].RewritePartition == FALSE &&
837 LayoutArray[DiskNumber]->PartitionEntry[j].PartitionNumber != 0)
838 {
839 swprintf(Buffer2,
840 L"\\Device\\Harddisk%d\\Partition%d",
841 DiskNumber,
842 LayoutArray[DiskNumber]->PartitionEntry[j].PartitionNumber);
843 RtlInitUnicodeString(&UnicodeString2,
844 Buffer2);
845
846 /* Assign drive */
847 DPRINT(" %wZ\n",
848 &UnicodeString2);
849 HalpAssignDrive(&UnicodeString2,
850 AUTO_DRIVE,
851 DOSDEVICE_DRIVE_FIXED,
852 LayoutArray[DiskNumber]->Signature,
853 LayoutArray[DiskNumber]->PartitionEntry[j].StartingOffset,
854 hKey,
855 &BootDevice,
856 NtSystemPath);
857 /* Mark the partition as assigned */
858 LayoutArray[DiskNumber]->PartitionEntry[j].RewritePartition = TRUE;
859 }
860 }
861 }
862 }
863
864 /* Assign removable disk drives */
865 DPRINT("Assigning removable disk drives:\n");
866 for (i = 0; i < ConfigInfo->DiskCount; i++)
867 {
868 if (LayoutArray[i])
869 {
870 /* Search for virtual partitions */
871 if (LayoutArray[i]->PartitionCount == 1 &&
872 LayoutArray[i]->PartitionEntry[0].PartitionType == 0)
873 {
874 swprintf(Buffer2,
875 L"\\Device\\Harddisk%d\\Partition1",
876 i);
877 RtlInitUnicodeString(&UnicodeString2,
878 Buffer2);
879
880 /* Assign drive */
881 DPRINT(" %wZ\n",
882 &UnicodeString2);
883 HalpAssignDrive(&UnicodeString2,
884 AUTO_DRIVE,
885 DOSDEVICE_DRIVE_REMOVABLE,
886 0,
887 RtlConvertLongToLargeInteger(0),
888 hKey,
889 &BootDevice,
890 NtSystemPath);
891 }
892 }
893 }
894
895 /* Free layout array */
896 for (i = 0; i < ConfigInfo->DiskCount; i++)
897 {
898 if (LayoutArray[i] != NULL)
899 ExFreePool(LayoutArray[i]);
900 }
901 ExFreePool(LayoutArray);
902 end_assign_disks:
903
904 /* Assign floppy drives */
905 DPRINT("Floppy drives: %d\n", ConfigInfo->FloppyCount);
906 for (i = 0; i < ConfigInfo->FloppyCount; i++)
907 {
908 swprintf(Buffer1,
909 L"\\Device\\Floppy%d",
910 i);
911 RtlInitUnicodeString(&UnicodeString1,
912 Buffer1);
913
914 /* Assign drive letters A: or B: or first free drive letter */
915 DPRINT(" %wZ\n",
916 &UnicodeString1);
917 HalpAssignDrive(&UnicodeString1,
918 (i < 2) ? i : AUTO_DRIVE,
919 DOSDEVICE_DRIVE_REMOVABLE,
920 0,
921 RtlConvertLongToLargeInteger(0),
922 hKey,
923 &BootDevice,
924 NtSystemPath);
925 }
926
927 /* Assign cdrom drives */
928 DPRINT("CD-Rom drives: %d\n", ConfigInfo->CdRomCount);
929 for (i = 0; i < ConfigInfo->CdRomCount; i++)
930 {
931 swprintf(Buffer1,
932 L"\\Device\\CdRom%d",
933 i);
934 RtlInitUnicodeString(&UnicodeString1,
935 Buffer1);
936
937 /* Assign first free drive letter */
938 DPRINT(" %wZ\n", &UnicodeString1);
939 HalpAssignDrive(&UnicodeString1,
940 AUTO_DRIVE,
941 DOSDEVICE_DRIVE_CDROM,
942 0,
943 RtlConvertLongToLargeInteger(0),
944 hKey,
945 &BootDevice,
946 NtSystemPath);
947 }
948
949 /* Anything else to do? */
950
951 ExFreePool(PartialInformation);
952 ExFreePool(Buffer2);
953 ExFreePool(Buffer1);
954 if (hKey)
955 {
956 ZwClose(hKey);
957 }
958 }
959
960 #endif
961
962 /* PRIVATE FUNCTIONS *********************************************************/
963
964 NTSTATUS
965 NTAPI
966 HalpGetFullGeometry(IN PDEVICE_OBJECT DeviceObject,
967 IN PDISK_GEOMETRY Geometry,
968 OUT PULONGLONG RealSectorCount)
969 {
970 PIRP Irp;
971 IO_STATUS_BLOCK IoStatusBlock;
972 PKEVENT Event;
973 NTSTATUS Status;
974 PARTITION_INFORMATION PartitionInfo;
975 PAGED_CODE();
976
977 /* Allocate a non-paged event */
978 Event = ExAllocatePoolWithTag(NonPagedPool,
979 sizeof(KEVENT),
980 TAG_FILE_SYSTEM);
981 if (!Event) return STATUS_INSUFFICIENT_RESOURCES;
982
983 /* Initialize it */
984 KeInitializeEvent(Event, NotificationEvent, FALSE);
985
986 /* Build the IRP */
987 Irp = IoBuildDeviceIoControlRequest(IOCTL_DISK_GET_DRIVE_GEOMETRY,
988 DeviceObject,
989 NULL,
990 0UL,
991 Geometry,
992 sizeof(DISK_GEOMETRY),
993 FALSE,
994 Event,
995 &IoStatusBlock);
996 if (!Irp)
997 {
998 /* Fail, free the event */
999 ExFreePoolWithTag(Event, TAG_FILE_SYSTEM);
1000 return STATUS_INSUFFICIENT_RESOURCES;
1001 }
1002
1003 /* Call the driver and check if it's pending */
1004 Status = IoCallDriver(DeviceObject, Irp);
1005 if (Status == STATUS_PENDING)
1006 {
1007 /* Wait on the driver */
1008 KeWaitForSingleObject(Event, Executive, KernelMode, FALSE, NULL);
1009 Status = IoStatusBlock.Status;
1010 }
1011
1012 /* Check if the driver returned success */
1013 if(NT_SUCCESS(Status))
1014 {
1015 /* Build another IRP */
1016 Irp = IoBuildDeviceIoControlRequest(IOCTL_DISK_GET_PARTITION_INFO,
1017 DeviceObject,
1018 NULL,
1019 0UL,
1020 &PartitionInfo,
1021 sizeof(PARTITION_INFORMATION),
1022 FALSE,
1023 Event,
1024 &IoStatusBlock);
1025 if (!Irp)
1026 {
1027 /* Fail, free the event */
1028 ExFreePoolWithTag(Event, TAG_FILE_SYSTEM);
1029 return STATUS_INSUFFICIENT_RESOURCES;
1030 }
1031
1032 /* Call the driver and check if it's pending */
1033 Status = IoCallDriver(DeviceObject, Irp);
1034 if (Status == STATUS_PENDING)
1035 {
1036 /* Wait on the driver */
1037 KeWaitForSingleObject(Event, Executive, KernelMode, FALSE, NULL);
1038 Status = IoStatusBlock.Status;
1039 }
1040
1041 /* Check if the driver returned success */
1042 if(NT_SUCCESS(Status))
1043 {
1044 /* Get the number of sectors */
1045 *RealSectorCount = (PartitionInfo.PartitionLength.QuadPart /
1046 Geometry->BytesPerSector);
1047 }
1048 }
1049
1050 /* Free the event and return the Status */
1051 ExFreePoolWithTag(Event, TAG_FILE_SYSTEM);
1052 return Status;
1053 }
1054
1055 BOOLEAN
1056 NTAPI
1057 HalpIsValidPartitionEntry(IN PPARTITION_DESCRIPTOR Entry,
1058 IN ULONGLONG MaxOffset,
1059 IN ULONGLONG MaxSector)
1060 {
1061 ULONGLONG EndingSector;
1062 PAGED_CODE();
1063
1064 /* Unused partitions are considered valid */
1065 if (Entry->PartitionType == PARTITION_ENTRY_UNUSED) return TRUE;
1066
1067 /* Get the last sector of the partition */
1068 EndingSector = GET_STARTING_SECTOR(Entry) + GET_PARTITION_LENGTH(Entry);
1069
1070 /* Check if it's more then the maximum sector */
1071 if (EndingSector > MaxSector)
1072 {
1073 /* Invalid partition */
1074 DPRINT1("FSTUB: entry is invalid\n");
1075 DPRINT1("FSTUB: offset %#08lx\n", GET_STARTING_SECTOR(Entry));
1076 DPRINT1("FSTUB: length %#08lx\n", GET_PARTITION_LENGTH(Entry));
1077 DPRINT1("FSTUB: end %#I64x\n", EndingSector);
1078 DPRINT1("FSTUB: max %#I64x\n", MaxSector);
1079 return FALSE;
1080 }
1081 else if(GET_STARTING_SECTOR(Entry) > MaxOffset)
1082 {
1083 /* Invalid partition */
1084 DPRINT1("FSTUB: entry is invalid\n");
1085 DPRINT1("FSTUB: offset %#08lx\n", GET_STARTING_SECTOR(Entry));
1086 DPRINT1("FSTUB: length %#08lx\n", GET_PARTITION_LENGTH(Entry));
1087 DPRINT1("FSTUB: end %#I64x\n", EndingSector);
1088 DPRINT1("FSTUB: maxOffset %#I64x\n", MaxOffset);
1089 return FALSE;
1090 }
1091
1092 /* It's fine, return success */
1093 return TRUE;
1094 }
1095
1096 VOID
1097 NTAPI
1098 HalpCalculateChsValues(IN PLARGE_INTEGER PartitionOffset,
1099 IN PLARGE_INTEGER PartitionLength,
1100 IN CCHAR ShiftCount,
1101 IN ULONG SectorsPerTrack,
1102 IN ULONG NumberOfTracks,
1103 IN ULONG ConventionalCylinders,
1104 OUT PPARTITION_DESCRIPTOR PartitionDescriptor)
1105 {
1106 LARGE_INTEGER FirstSector, SectorCount;
1107 ULONG LastSector, Remainder, SectorsPerCylinder;
1108 ULONG StartingCylinder, EndingCylinder;
1109 ULONG StartingTrack, EndingTrack;
1110 ULONG StartingSector, EndingSector;
1111 PAGED_CODE();
1112
1113 /* Calculate the number of sectors for each cylinder */
1114 SectorsPerCylinder = SectorsPerTrack * NumberOfTracks;
1115
1116 /* Calculate the first sector, and the sector count */
1117 FirstSector.QuadPart = PartitionOffset->QuadPart >> ShiftCount;
1118 SectorCount.QuadPart = PartitionLength->QuadPart >> ShiftCount;
1119
1120 /* Now calculate the last sector */
1121 LastSector = FirstSector.LowPart + SectorCount.LowPart - 1;
1122
1123 /* Calculate the first and last cylinders */
1124 StartingCylinder = FirstSector.LowPart / SectorsPerCylinder;
1125 EndingCylinder = LastSector / SectorsPerCylinder;
1126
1127 /* Set the default number of cylinders */
1128 if (!ConventionalCylinders) ConventionalCylinders = 1024;
1129
1130 /* Normalize the values */
1131 if (StartingCylinder >= ConventionalCylinders)
1132 {
1133 /* Set the maximum to 1023 */
1134 StartingCylinder = ConventionalCylinders - 1;
1135 }
1136 if (EndingCylinder >= ConventionalCylinders)
1137 {
1138 /* Set the maximum to 1023 */
1139 EndingCylinder = ConventionalCylinders - 1;
1140 }
1141
1142 /* Calculate the starting head and sector that still remain */
1143 Remainder = FirstSector.LowPart % SectorsPerCylinder;
1144 StartingTrack = Remainder / SectorsPerTrack;
1145 StartingSector = Remainder % SectorsPerTrack;
1146
1147 /* Calculate the ending head and sector that still remain */
1148 Remainder = LastSector % SectorsPerCylinder;
1149 EndingTrack = Remainder / SectorsPerTrack;
1150 EndingSector = Remainder % SectorsPerTrack;
1151
1152 /* Set cylinder data for the MSB */
1153 PartitionDescriptor->StartingCylinderMsb = (UCHAR)StartingCylinder;
1154 PartitionDescriptor->EndingCylinderMsb = (UCHAR)EndingCylinder;
1155
1156 /* Set the track data */
1157 PartitionDescriptor->StartingTrack = (UCHAR)StartingTrack;
1158 PartitionDescriptor->EndingTrack = (UCHAR)EndingTrack;
1159
1160 /* Update cylinder data for the LSB */
1161 StartingCylinder = ((StartingSector + 1) & 0x3F) |
1162 ((StartingCylinder >> 2) & 0xC0);
1163 EndingCylinder = ((EndingSector + 1) & 0x3F) |
1164 ((EndingCylinder >> 2) & 0xC0);
1165
1166 /* Set the cylinder data for the LSB */
1167 PartitionDescriptor->StartingCylinderLsb = (UCHAR)StartingCylinder;
1168 PartitionDescriptor->EndingCylinderLsb = (UCHAR)EndingCylinder;
1169 }
1170
1171 VOID
1172 FASTCALL
1173 xHalGetPartialGeometry(IN PDEVICE_OBJECT DeviceObject,
1174 IN PULONG ConventionalCylinders,
1175 IN PLONGLONG DiskSize)
1176 {
1177 PDISK_GEOMETRY DiskGeometry = NULL;
1178 PIO_STATUS_BLOCK IoStatusBlock = NULL;
1179 PKEVENT Event = NULL;
1180 PIRP Irp;
1181 NTSTATUS Status;
1182
1183 /* Set defaults */
1184 *ConventionalCylinders = 0;
1185 *DiskSize = 0;
1186
1187 /* Allocate the structure in nonpaged pool */
1188 DiskGeometry = ExAllocatePoolWithTag(NonPagedPool,
1189 sizeof(DISK_GEOMETRY),
1190 TAG_FILE_SYSTEM);
1191 if (!DiskGeometry) goto Cleanup;
1192
1193 /* Allocate the status block in nonpaged pool */
1194 IoStatusBlock = ExAllocatePoolWithTag(NonPagedPool,
1195 sizeof(IO_STATUS_BLOCK),
1196 TAG_FILE_SYSTEM);
1197 if (!IoStatusBlock) goto Cleanup;
1198
1199 /* Allocate the event in nonpaged pool too */
1200 Event = ExAllocatePoolWithTag(NonPagedPool,
1201 sizeof(KEVENT),
1202 TAG_FILE_SYSTEM);
1203 if (!Event) goto Cleanup;
1204
1205 /* Initialize the event */
1206 KeInitializeEvent(Event, NotificationEvent, FALSE);
1207
1208 /* Build the IRP */
1209 Irp = IoBuildDeviceIoControlRequest(IOCTL_DISK_GET_DRIVE_GEOMETRY,
1210 DeviceObject,
1211 NULL,
1212 0,
1213 DiskGeometry,
1214 sizeof(DISK_GEOMETRY),
1215 FALSE,
1216 Event,
1217 IoStatusBlock);
1218 if (!Irp) goto Cleanup;
1219
1220 /* Now call the driver */
1221 Status = IoCallDriver(DeviceObject, Irp);
1222 if (Status == STATUS_PENDING)
1223 {
1224 /* Wait for it to complete */
1225 KeWaitForSingleObject(Event, Executive, KernelMode, FALSE, NULL);
1226 Status = IoStatusBlock->Status;
1227 }
1228
1229 /* Check driver status */
1230 if (NT_SUCCESS(Status))
1231 {
1232 /* Return the cylinder count */
1233 *ConventionalCylinders = DiskGeometry->Cylinders.LowPart;
1234
1235 /* Make sure it's not larger then 1024 */
1236 if (DiskGeometry->Cylinders.LowPart >= 1024)
1237 {
1238 /* Otherwise, normalize the value */
1239 *ConventionalCylinders = 1024;
1240 }
1241
1242 /* Calculate the disk size */
1243 *DiskSize = DiskGeometry->Cylinders.QuadPart *
1244 DiskGeometry->TracksPerCylinder *
1245 DiskGeometry->SectorsPerTrack *
1246 DiskGeometry->BytesPerSector;
1247 }
1248
1249 Cleanup:
1250 /* Free all the pointers */
1251 if (Event) ExFreePoolWithTag(Event, TAG_FILE_SYSTEM);
1252 if (IoStatusBlock) ExFreePool(IoStatusBlock);
1253 if (DiskGeometry) ExFreePool(DiskGeometry);
1254 return;
1255 }
1256
1257 VOID
1258 FASTCALL
1259 xHalExamineMBR(IN PDEVICE_OBJECT DeviceObject,
1260 IN ULONG SectorSize,
1261 IN ULONG MbrTypeIdentifier,
1262 OUT PVOID *MbrBuffer)
1263 {
1264 LARGE_INTEGER Offset;
1265 PUCHAR Buffer;
1266 ULONG BufferSize;
1267 KEVENT Event;
1268 IO_STATUS_BLOCK IoStatusBlock;
1269 PIRP Irp;
1270 PPARTITION_DESCRIPTOR PartitionDescriptor;
1271 NTSTATUS Status;
1272 PIO_STACK_LOCATION IoStackLocation;
1273 Offset.QuadPart = 0;
1274
1275 /* Assume failure */
1276 *MbrBuffer = NULL;
1277
1278 /* Normalize the buffer size */
1279 BufferSize = max(SectorSize, 512);
1280
1281 /* Allocate the buffer */
1282 Buffer = ExAllocatePoolWithTag(NonPagedPool,
1283 PAGE_SIZE > BufferSize ?
1284 PAGE_SIZE : BufferSize,
1285 TAG_FILE_SYSTEM);
1286 if (!Buffer) return;
1287
1288 /* Initialize the Event */
1289 KeInitializeEvent(&Event, NotificationEvent, FALSE);
1290
1291 /* Build the IRP */
1292 Irp = IoBuildSynchronousFsdRequest(IRP_MJ_READ,
1293 DeviceObject,
1294 Buffer,
1295 BufferSize,
1296 &Offset,
1297 &Event,
1298 &IoStatusBlock);
1299 if (!Irp)
1300 {
1301 /* Failed */
1302 ExFreePoolWithTag(Buffer, TAG_FILE_SYSTEM);
1303 return;
1304 }
1305
1306 /* Make sure to override volume verification */
1307 IoStackLocation = IoGetNextIrpStackLocation(Irp);
1308 IoStackLocation->Flags |= SL_OVERRIDE_VERIFY_VOLUME;
1309
1310 /* Call the driver */
1311 Status = IoCallDriver(DeviceObject, Irp);
1312 if (Status == STATUS_PENDING)
1313 {
1314 /* Wait for completion */
1315 KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL);
1316 Status = IoStatusBlock.Status;
1317 }
1318
1319 /* Check driver Status */
1320 if (NT_SUCCESS(Status))
1321 {
1322 /* Validate the MBR Signature */
1323 if (((PUSHORT)Buffer)[BOOT_SIGNATURE_OFFSET] != BOOT_RECORD_SIGNATURE)
1324 {
1325 /* Failed */
1326 ExFreePoolWithTag(Buffer, TAG_FILE_SYSTEM);
1327 return;
1328 }
1329
1330 /* Get the partition entry */
1331 PartitionDescriptor = (PPARTITION_DESCRIPTOR)
1332 &(((PUSHORT)Buffer)[PARTITION_TABLE_OFFSET]);
1333
1334 /* Make sure it's what the caller wanted */
1335 if (PartitionDescriptor->PartitionType != MbrTypeIdentifier)
1336 {
1337 /* It's not, free our buffer */
1338 ExFreePoolWithTag(Buffer, TAG_FILE_SYSTEM);
1339 }
1340 else
1341 {
1342 /* Check if this is a secondary entry */
1343 if (PartitionDescriptor->PartitionType == 0x54)
1344 {
1345 /* Return our buffer, but at sector 63 */
1346 *(PULONG)Buffer = 63;
1347 *MbrBuffer = Buffer;
1348 }
1349 else if (PartitionDescriptor->PartitionType == 0x55)
1350 {
1351 /* EZ Drive, return the buffer directly */
1352 *MbrBuffer = Buffer;
1353 }
1354 else
1355 {
1356 /* Otherwise crash on debug builds */
1357 ASSERT(PartitionDescriptor->PartitionType == 0x55);
1358 }
1359 }
1360 }
1361 }
1362
1363 VOID
1364 NTAPI
1365 FstubFixupEfiPartition(IN PPARTITION_DESCRIPTOR PartitionDescriptor,
1366 IN ULONGLONG MaxOffset)
1367 {
1368 ULONG PartitionLength;
1369 PAGED_CODE();
1370
1371 /* Compute partition length (according to MBR entry) */
1372 PartitionLength = PartitionDescriptor->StartingSectorLsb0 + PartitionDescriptor->PartitionLengthLsb0;
1373 /* In case the partition length goes beyond disk size... */
1374 if (PartitionLength > MaxOffset)
1375 {
1376 /* Resize partition to its maximum real length */
1377 PartitionDescriptor->PartitionLengthLsb0 = MaxOffset - PartitionDescriptor->StartingSectorLsb0;
1378 }
1379 }
1380
1381 NTSTATUS
1382 FASTCALL
1383 xHalIoReadPartitionTable(IN PDEVICE_OBJECT DeviceObject,
1384 IN ULONG SectorSize,
1385 IN BOOLEAN ReturnRecognizedPartitions,
1386 IN OUT PDRIVE_LAYOUT_INFORMATION *PartitionBuffer)
1387 {
1388 KEVENT Event;
1389 IO_STATUS_BLOCK IoStatusBlock;
1390 PIRP Irp;
1391 PPARTITION_DESCRIPTOR PartitionDescriptor;
1392 CCHAR Entry;
1393 NTSTATUS Status;
1394 PPARTITION_INFORMATION PartitionInfo;
1395 PUCHAR Buffer = NULL;
1396 ULONG BufferSize = 2048, InputSize;
1397 PDRIVE_LAYOUT_INFORMATION DriveLayoutInfo = NULL;
1398 LONG j = -1, i = -1, k;
1399 DISK_GEOMETRY DiskGeometry;
1400 LONGLONG EndSector, MaxSector, StartOffset;
1401 ULONGLONG MaxOffset;
1402 LARGE_INTEGER Offset, VolumeOffset;
1403 BOOLEAN IsPrimary = TRUE, IsEzDrive = FALSE, MbrFound = FALSE;
1404 BOOLEAN IsValid, IsEmpty = TRUE;
1405 PVOID MbrBuffer;
1406 PIO_STACK_LOCATION IoStackLocation;
1407 PBOOT_SECTOR_INFO BootSectorInfo = (PBOOT_SECTOR_INFO)Buffer;
1408 UCHAR PartitionType;
1409 LARGE_INTEGER HiddenSectors64;
1410 VolumeOffset.QuadPart = Offset.QuadPart = 0;
1411 PAGED_CODE();
1412
1413 /* Allocate the buffer */
1414 *PartitionBuffer = ExAllocatePoolWithTag(NonPagedPool,
1415 BufferSize,
1416 TAG_FILE_SYSTEM);
1417 if (!(*PartitionBuffer)) return STATUS_INSUFFICIENT_RESOURCES;
1418
1419 /* Normalize the buffer size */
1420 InputSize = max(512, SectorSize);
1421
1422 /* Check for EZ Drive */
1423 HalExamineMBR(DeviceObject, InputSize, 0x55, &MbrBuffer);
1424 if (MbrBuffer)
1425 {
1426 /* EZ Drive found, bias the offset */
1427 IsEzDrive = TRUE;
1428 ExFreePool(MbrBuffer);
1429 Offset.QuadPart = 512;
1430 }
1431
1432 /* Get drive geometry */
1433 Status = HalpGetFullGeometry(DeviceObject, &DiskGeometry, &MaxOffset);
1434 if (!NT_SUCCESS(Status))
1435 {
1436 ExFreePoolWithTag(*PartitionBuffer, TAG_FILE_SYSTEM);
1437 *PartitionBuffer = NULL;
1438 return Status;
1439 }
1440
1441 /* Get the end and maximum sector */
1442 EndSector = MaxOffset;
1443 MaxSector = MaxOffset << 1;
1444 DPRINT("FSTUB: MaxOffset = %#I64x, MaxSector = %#I64x\n",
1445 MaxOffset, MaxSector);
1446
1447 /* Allocate our buffer */
1448 Buffer = ExAllocatePoolWithTag(NonPagedPool, InputSize, TAG_FILE_SYSTEM);
1449 if (!Buffer)
1450 {
1451 /* Fail, free the input buffer */
1452 ExFreePoolWithTag(*PartitionBuffer, TAG_FILE_SYSTEM);
1453 *PartitionBuffer = NULL;
1454 return STATUS_INSUFFICIENT_RESOURCES;
1455 }
1456
1457 /* Start partition loop */
1458 do
1459 {
1460 /* Assume the partition is valid */
1461 IsValid = TRUE;
1462
1463 /* Initialize the event */
1464 KeInitializeEvent(&Event, NotificationEvent, FALSE);
1465
1466 /* Clear the buffer and build the IRP */
1467 RtlZeroMemory(Buffer, InputSize);
1468 Irp = IoBuildSynchronousFsdRequest(IRP_MJ_READ,
1469 DeviceObject,
1470 Buffer,
1471 InputSize,
1472 &Offset,
1473 &Event,
1474 &IoStatusBlock);
1475 if (!Irp)
1476 {
1477 /* Failed */
1478 Status = STATUS_INSUFFICIENT_RESOURCES;
1479 break;
1480 }
1481
1482 /* Make sure to disable volume verification */
1483 IoStackLocation = IoGetNextIrpStackLocation(Irp);
1484 IoStackLocation->Flags |= SL_OVERRIDE_VERIFY_VOLUME;
1485
1486 /* Call the driver */
1487 Status = IoCallDriver(DeviceObject, Irp);
1488 if (Status == STATUS_PENDING)
1489 {
1490 /* Wait for completion */
1491 KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL);
1492 Status = IoStatusBlock.Status;
1493 }
1494
1495 /* Normalize status code and check for failure */
1496 if (Status == STATUS_NO_DATA_DETECTED) Status = STATUS_SUCCESS;
1497 if (!NT_SUCCESS(Status)) break;
1498
1499 /* If we biased for EZ-Drive, unbias now */
1500 if (IsEzDrive && (Offset.QuadPart == 512)) Offset.QuadPart = 0;
1501
1502 /* Make sure this is a valid MBR */
1503 if (((PUSHORT)Buffer)[BOOT_SIGNATURE_OFFSET] != BOOT_RECORD_SIGNATURE)
1504 {
1505 /* It's not, fail */
1506 DPRINT1("FSTUB: (IoReadPartitionTable) No 0xaa55 found in "
1507 "partition table %d\n", j + 1);
1508 break;
1509 }
1510
1511 /* At this point we have a valid MBR */
1512 MbrFound = TRUE;
1513
1514 /* Check if we weren't given an offset */
1515 if (!Offset.QuadPart)
1516 {
1517 /* Then read the signature off the disk */
1518 (*PartitionBuffer)->Signature = ((PULONG)Buffer)
1519 [PARTITION_TABLE_OFFSET / 2 - 1];
1520 }
1521
1522 /* Get the partition descriptor array */
1523 PartitionDescriptor = (PPARTITION_DESCRIPTOR)
1524 &(((PUSHORT)Buffer)[PARTITION_TABLE_OFFSET]);
1525
1526 /* Start looping partitions */
1527 j++;
1528 DPRINT("FSTUB: Partition Table %d:\n", j);
1529 for (Entry = 1, k = 0; Entry <= 4; Entry++, PartitionDescriptor++)
1530 {
1531 /* Get the partition type */
1532 PartitionType = PartitionDescriptor->PartitionType;
1533
1534 /* Print debug messages */
1535 DPRINT("Partition Entry %d,%d: type %#x %s\n",
1536 j,
1537 Entry,
1538 PartitionType,
1539 (PartitionDescriptor->ActiveFlag) ? "Active" : "");
1540 DPRINT("\tOffset %#08lx for %#08lx Sectors\n",
1541 GET_STARTING_SECTOR(PartitionDescriptor),
1542 GET_PARTITION_LENGTH(PartitionDescriptor));
1543
1544 /* Check whether we're facing a protective MBR */
1545 if (PartitionType == EFI_PMBR_OSTYPE_EFI)
1546 {
1547 /* Partition length might be bigger than disk size */
1548 FstubFixupEfiPartition(PartitionDescriptor,
1549 MaxOffset);
1550 }
1551
1552 /* Make sure that the partition is valid, unless it's the first */
1553 if (!(HalpIsValidPartitionEntry(PartitionDescriptor,
1554 MaxOffset,
1555 MaxSector)) && !(j))
1556 {
1557 /* It's invalid, so fail */
1558 IsValid = FALSE;
1559 break;
1560 }
1561
1562 /* Check if it's a container */
1563 if (IsContainerPartition(PartitionType))
1564 {
1565 /* Increase the count of containers */
1566 if (++k != 1)
1567 {
1568 /* More then one table is invalid */
1569 DPRINT1("FSTUB: Multiple container partitions found in "
1570 "partition table %d\n - table is invalid\n",
1571 j);
1572 IsValid = FALSE;
1573 break;
1574 }
1575 }
1576
1577 /* Check if the partition is supposedly empty */
1578 if (IsEmpty)
1579 {
1580 /* But check if it actually has a start and/or length */
1581 if ((GET_STARTING_SECTOR(PartitionDescriptor)) ||
1582 (GET_PARTITION_LENGTH(PartitionDescriptor)))
1583 {
1584 /* So then it's not really empty */
1585 IsEmpty = FALSE;
1586 }
1587 }
1588
1589 /* Check if the caller wanted only recognized partitions */
1590 if (ReturnRecognizedPartitions)
1591 {
1592 /* Then check if this one is unused, or a container */
1593 if ((PartitionType == PARTITION_ENTRY_UNUSED) ||
1594 IsContainerPartition(PartitionType))
1595 {
1596 /* Skip it, since the caller doesn't want it */
1597 continue;
1598 }
1599 }
1600
1601 /* Increase the structure count and check if they can fit */
1602 if ((sizeof(DRIVE_LAYOUT_INFORMATION) +
1603 (++i * sizeof(PARTITION_INFORMATION))) >
1604 BufferSize)
1605 {
1606 /* Allocate a new buffer that's twice as big */
1607 DriveLayoutInfo = ExAllocatePoolWithTag(NonPagedPool,
1608 BufferSize << 1,
1609 TAG_FILE_SYSTEM);
1610 if (!DriveLayoutInfo)
1611 {
1612 /* Out of memory, unto this extra structure */
1613 --i;
1614 Status = STATUS_INSUFFICIENT_RESOURCES;
1615 break;
1616 }
1617
1618 /* Copy the contents of the old buffer */
1619 RtlMoveMemory(DriveLayoutInfo,
1620 *PartitionBuffer,
1621 BufferSize);
1622
1623 /* Free the old buffer and set this one as the new one */
1624 ExFreePoolWithTag(*PartitionBuffer, TAG_FILE_SYSTEM);
1625 *PartitionBuffer = DriveLayoutInfo;
1626
1627 /* Double the size */
1628 BufferSize <<= 1;
1629 }
1630
1631 /* Now get the current structure being filled and initialize it */
1632 PartitionInfo = &(*PartitionBuffer)->PartitionEntry[i];
1633 PartitionInfo->PartitionType = PartitionType;
1634 PartitionInfo->RewritePartition = FALSE;
1635
1636 /* Check if we're dealing with a partition that's in use */
1637 if (PartitionType != PARTITION_ENTRY_UNUSED)
1638 {
1639 /* Check if it's bootable */
1640 PartitionInfo->BootIndicator = PartitionDescriptor->
1641 ActiveFlag & 0x80 ?
1642 TRUE : FALSE;
1643
1644 /* Check if its' a container */
1645 if (IsContainerPartition(PartitionType))
1646 {
1647 /* Then don't recognize it and use the volume offset */
1648 PartitionInfo->RecognizedPartition = FALSE;
1649 StartOffset = VolumeOffset.QuadPart;
1650 }
1651 else
1652 {
1653 /* Then recognize it and use the partition offset */
1654 PartitionInfo->RecognizedPartition = TRUE;
1655 StartOffset = Offset.QuadPart;
1656 }
1657
1658 /* Get the starting offset */
1659 PartitionInfo->StartingOffset.QuadPart =
1660 StartOffset +
1661 UInt32x32To64(GET_STARTING_SECTOR(PartitionDescriptor),
1662 SectorSize);
1663
1664 /* Calculate the number of hidden sectors */
1665 HiddenSectors64.QuadPart = (PartitionInfo->
1666 StartingOffset.QuadPart -
1667 StartOffset) /
1668 SectorSize;
1669 PartitionInfo->HiddenSectors = HiddenSectors64.LowPart;
1670
1671 /* Get the partition length */
1672 PartitionInfo->PartitionLength.QuadPart =
1673 UInt32x32To64(GET_PARTITION_LENGTH(PartitionDescriptor),
1674 SectorSize);
1675
1676 /* FIXME: REACTOS HACK */
1677 PartitionInfo->PartitionNumber = i + 1;
1678 }
1679 else
1680 {
1681 /* Otherwise, clear all the relevant fields */
1682 PartitionInfo->BootIndicator = FALSE;
1683 PartitionInfo->RecognizedPartition = FALSE;
1684 PartitionInfo->StartingOffset.QuadPart = 0;
1685 PartitionInfo->PartitionLength.QuadPart = 0;
1686 PartitionInfo->HiddenSectors = 0;
1687
1688 /* FIXME: REACTOS HACK */
1689 PartitionInfo->PartitionNumber = 0;
1690 }
1691 }
1692
1693 /* Finish debug log, and check for failure */
1694 DPRINT("\n");
1695 if (!NT_SUCCESS(Status)) break;
1696
1697 /* Also check if we hit an invalid entry here */
1698 if (!IsValid)
1699 {
1700 /* We did, so break out of the loop minus one entry */
1701 j--;
1702 break;
1703 }
1704
1705 /* Reset the offset */
1706 Offset.QuadPart = 0;
1707
1708 /* Go back to the descriptor array and loop it */
1709 PartitionDescriptor = (PPARTITION_DESCRIPTOR)
1710 &(((PUSHORT)Buffer)[PARTITION_TABLE_OFFSET]);
1711 for (Entry = 1; Entry <= 4; Entry++, PartitionDescriptor++)
1712 {
1713 /* Check if this is a container partition, since we skipped them */
1714 if (IsContainerPartition(PartitionDescriptor->PartitionType))
1715 {
1716 /* Get its offset */
1717 Offset.QuadPart = VolumeOffset.QuadPart +
1718 UInt32x32To64(
1719 GET_STARTING_SECTOR(PartitionDescriptor),
1720 SectorSize);
1721
1722 /* If this is a primary partition, this is the volume offset */
1723 if (IsPrimary) VolumeOffset = Offset;
1724
1725 /* Also update the maximum sector */
1726 MaxSector = GET_PARTITION_LENGTH(PartitionDescriptor);
1727 DPRINT1("FSTUB: MaxSector now = %#08lx\n", MaxSector);
1728 break;
1729 }
1730 }
1731
1732 /* Loop the next partitions, which are not primary anymore */
1733 IsPrimary = FALSE;
1734 } while (Offset.HighPart | Offset.LowPart);
1735
1736 /* Check if this is a removable device that's probably a super-floppy */
1737 if ((DiskGeometry.MediaType == RemovableMedia) &&
1738 !(j) &&
1739 (MbrFound) &&
1740 (IsEmpty))
1741 {
1742 /* Read the jump bytes to detect super-floppy */
1743 if ((BootSectorInfo->JumpByte[0] == 0xeb) ||
1744 (BootSectorInfo->JumpByte[0] == 0xe9))
1745 {
1746 /* Super floppes don't have typical MBRs, so skip them */
1747 DPRINT1("FSTUB: Jump byte %#x found along with empty partition "
1748 "table - disk is a super floppy and has no valid MBR\n",
1749 BootSectorInfo->JumpByte);
1750 j = -1;
1751 }
1752 }
1753
1754 /* Check if we're still at partition -1 */
1755 if (j == -1)
1756 {
1757 /* The likely cause is the super floppy detection above */
1758 if ((MbrFound) || (DiskGeometry.MediaType == RemovableMedia))
1759 {
1760 /* Print out debugging information */
1761 DPRINT1("FSTUB: Drive %#p has no valid MBR. Make it into a "
1762 "super-floppy\n",
1763 DeviceObject);
1764 DPRINT1("FSTUB: Drive has %#08lx sectors and is %#016I64x "
1765 "bytes large\n",
1766 EndSector, EndSector * DiskGeometry.BytesPerSector);
1767
1768 /* We should at least have some sectors */
1769 if (EndSector > 0)
1770 {
1771 /* Get the entry we'll use */
1772 PartitionInfo = &(*PartitionBuffer)->PartitionEntry[0];
1773
1774 /* Fill it out with data for a super-floppy */
1775 PartitionInfo->RewritePartition = FALSE;
1776 PartitionInfo->RecognizedPartition = TRUE;
1777 PartitionInfo->PartitionType = PARTITION_FAT_16;
1778 PartitionInfo->BootIndicator = FALSE;
1779 PartitionInfo->HiddenSectors = 0;
1780 PartitionInfo->StartingOffset.QuadPart = 0;
1781 PartitionInfo->PartitionLength.QuadPart = (EndSector *
1782 DiskGeometry.
1783 BytesPerSector);
1784
1785 /* FIXME: REACTOS HACK */
1786 PartitionInfo->PartitionNumber = 0;
1787
1788 /* Set the signature and set the count back to 0 */
1789 (*PartitionBuffer)->Signature = 1;
1790 i = 0;
1791 }
1792 }
1793 else
1794 {
1795 /* Otherwise, this isn't a super floppy, so set an invalid count */
1796 i = -1;
1797 }
1798 }
1799
1800 /* Set the partition count */
1801 (*PartitionBuffer)->PartitionCount = ++i;
1802
1803 /* If we have no count, delete the signature */
1804 if (!i) (*PartitionBuffer)->Signature = 0;
1805
1806 /* Free the buffer and check for success */
1807 if (Buffer) ExFreePoolWithTag(Buffer, TAG_FILE_SYSTEM);
1808 if (!NT_SUCCESS(Status)) ExFreePoolWithTag(*PartitionBuffer, TAG_FILE_SYSTEM);
1809
1810 /* Return status */
1811 return Status;
1812 }
1813
1814 NTSTATUS
1815 FASTCALL
1816 xHalIoSetPartitionInformation(IN PDEVICE_OBJECT DeviceObject,
1817 IN ULONG SectorSize,
1818 IN ULONG PartitionNumber,
1819 IN ULONG PartitionType)
1820 {
1821 PIRP Irp;
1822 KEVENT Event;
1823 IO_STATUS_BLOCK IoStatusBlock;
1824 NTSTATUS Status;
1825 LARGE_INTEGER Offset, VolumeOffset;
1826 PUCHAR Buffer = NULL;
1827 ULONG BufferSize;
1828 ULONG i = 0;
1829 ULONG Entry;
1830 PPARTITION_DESCRIPTOR PartitionDescriptor;
1831 BOOLEAN IsPrimary = TRUE, IsEzDrive = FALSE;
1832 PVOID MbrBuffer;
1833 PIO_STACK_LOCATION IoStackLocation;
1834 VolumeOffset.QuadPart = Offset.QuadPart = 0;
1835 PAGED_CODE();
1836
1837 /* Normalize the buffer size */
1838 BufferSize = max(512, SectorSize);
1839
1840 /* Check for EZ Drive */
1841 HalExamineMBR(DeviceObject, BufferSize, 0x55, &MbrBuffer);
1842 if (MbrBuffer)
1843 {
1844 /* EZ Drive found, bias the offset */
1845 IsEzDrive = TRUE;
1846 ExFreePool(MbrBuffer);
1847 Offset.QuadPart = 512;
1848 }
1849
1850 /* Allocate our partition buffer */
1851 Buffer = ExAllocatePoolWithTag(NonPagedPool, PAGE_SIZE, TAG_FILE_SYSTEM);
1852 if (!Buffer) return STATUS_INSUFFICIENT_RESOURCES;
1853
1854 /* Initialize the event we'll use and loop partitions */
1855 KeInitializeEvent(&Event, NotificationEvent, FALSE);
1856 do
1857 {
1858 /* Reset the event since we reuse it */
1859 KeResetEvent(&Event);
1860
1861 /* Build the read IRP */
1862 Irp = IoBuildSynchronousFsdRequest(IRP_MJ_READ,
1863 DeviceObject,
1864 Buffer,
1865 BufferSize,
1866 &Offset,
1867 &Event,
1868 &IoStatusBlock);
1869 if (!Irp)
1870 {
1871 /* Fail */
1872 Status = STATUS_INSUFFICIENT_RESOURCES;
1873 break;
1874 }
1875
1876 /* Make sure to disable volume verification */
1877 IoStackLocation = IoGetNextIrpStackLocation(Irp);
1878 IoStackLocation->Flags |= SL_OVERRIDE_VERIFY_VOLUME;
1879
1880 /* Call the driver */
1881 Status = IoCallDriver(DeviceObject, Irp);
1882 if (Status == STATUS_PENDING)
1883 {
1884 /* Wait for completion */
1885 KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL);
1886 Status = IoStatusBlock.Status;
1887 }
1888
1889 /* Check for failure */
1890 if (!NT_SUCCESS(Status)) break;
1891
1892 /* If we biased for EZ-Drive, unbias now */
1893 if (IsEzDrive && (Offset.QuadPart == 512)) Offset.QuadPart = 0;
1894
1895 /* Make sure this is a valid MBR */
1896 if (((PUSHORT)Buffer)[BOOT_SIGNATURE_OFFSET] != BOOT_RECORD_SIGNATURE)
1897 {
1898 /* It's not, fail */
1899 Status = STATUS_BAD_MASTER_BOOT_RECORD;
1900 break;
1901 }
1902
1903 /* Get the partition descriptors and loop them */
1904 PartitionDescriptor = (PPARTITION_DESCRIPTOR)
1905 &(((PUSHORT)Buffer)[PARTITION_TABLE_OFFSET]);
1906 for (Entry = 1; Entry <= 4; Entry++, PartitionDescriptor++)
1907 {
1908 /* Check if it's unused or a container partition */
1909 if ((PartitionDescriptor->PartitionType ==
1910 PARTITION_ENTRY_UNUSED) ||
1911 (IsContainerPartition(PartitionDescriptor->PartitionType)))
1912 {
1913 /* Go to the next one */
1914 continue;
1915 }
1916
1917 /* It's a valid partition, so increase the partition count */
1918 if (++i == PartitionNumber)
1919 {
1920 /* We found a match, set the type */
1921 PartitionDescriptor->PartitionType = (UCHAR)PartitionType;
1922
1923 /* Reset the reusable event */
1924 KeResetEvent(&Event);
1925
1926 /* Build the write IRP */
1927 Irp = IoBuildSynchronousFsdRequest(IRP_MJ_WRITE,
1928 DeviceObject,
1929 Buffer,
1930 BufferSize,
1931 &Offset,
1932 &Event,
1933 &IoStatusBlock);
1934 if (!Irp)
1935 {
1936 /* Fail */
1937 Status = STATUS_INSUFFICIENT_RESOURCES;
1938 break;
1939 }
1940
1941 /* Disable volume verification */
1942 IoStackLocation = IoGetNextIrpStackLocation(Irp);
1943 IoStackLocation->Flags |= SL_OVERRIDE_VERIFY_VOLUME;
1944
1945 /* Call the driver */
1946 Status = IoCallDriver(DeviceObject, Irp);
1947 if (Status == STATUS_PENDING)
1948 {
1949 /* Wait for completion */
1950 KeWaitForSingleObject(&Event,
1951 Executive,
1952 KernelMode,
1953 FALSE,
1954 NULL);
1955 Status = IoStatusBlock.Status;
1956 }
1957
1958 /* We're done, break out of the loop */
1959 break;
1960 }
1961 }
1962
1963 /* If we looped all the partitions, break out */
1964 if (Entry <= NUM_PARTITION_TABLE_ENTRIES) break;
1965
1966 /* Nothing found yet, get the partition array again */
1967 PartitionDescriptor = (PPARTITION_DESCRIPTOR)
1968 &(((PUSHORT)Buffer)[PARTITION_TABLE_OFFSET]);
1969 for (Entry = 1; Entry <= 4; Entry++, PartitionDescriptor++)
1970 {
1971 /* Check if this was a container partition (we skipped these) */
1972 if (IsContainerPartition(PartitionDescriptor->PartitionType))
1973 {
1974 /* Update the partition offset */
1975 Offset.QuadPart = VolumeOffset.QuadPart +
1976 GET_STARTING_SECTOR(PartitionDescriptor) *
1977 SectorSize;
1978
1979 /* If this was the primary partition, update the volume too */
1980 if (IsPrimary) VolumeOffset = Offset;
1981 break;
1982 }
1983 }
1984
1985 /* Check if we already searched all the partitions */
1986 if (Entry > NUM_PARTITION_TABLE_ENTRIES)
1987 {
1988 /* Then we failed to find a good MBR */
1989 Status = STATUS_BAD_MASTER_BOOT_RECORD;
1990 break;
1991 }
1992
1993 /* Loop the next partitions, which are not primary anymore */
1994 IsPrimary = FALSE;
1995 } while (i < PartitionNumber);
1996
1997 /* Everything done, cleanup */
1998 if (Buffer) ExFreePool(Buffer);
1999 return Status;
2000 }
2001
2002 NTSTATUS
2003 FASTCALL
2004 xHalIoWritePartitionTable(IN PDEVICE_OBJECT DeviceObject,
2005 IN ULONG SectorSize,
2006 IN ULONG SectorsPerTrack,
2007 IN ULONG NumberOfHeads,
2008 IN PDRIVE_LAYOUT_INFORMATION PartitionBuffer)
2009 {
2010 KEVENT Event;
2011 IO_STATUS_BLOCK IoStatusBlock;
2012 PIRP Irp;
2013 NTSTATUS Status = STATUS_SUCCESS;
2014 ULONG BufferSize;
2015 PUSHORT Buffer;
2016 PPTE Entry;
2017 PPARTITION_TABLE PartitionTable;
2018 LARGE_INTEGER Offset, NextOffset, ExtendedOffset, SectorOffset;
2019 LARGE_INTEGER StartOffset, PartitionLength;
2020 ULONG i, j;
2021 CCHAR k;
2022 BOOLEAN IsEzDrive = FALSE, IsSuperFloppy = FALSE, DoRewrite = FALSE, IsMbr;
2023 ULONG ConventionalCylinders;
2024 LONGLONG DiskSize;
2025 PDISK_LAYOUT DiskLayout = (PDISK_LAYOUT)PartitionBuffer;
2026 PVOID MbrBuffer;
2027 UCHAR PartitionType;
2028 PIO_STACK_LOCATION IoStackLocation;
2029 PPARTITION_INFORMATION PartitionInfo = PartitionBuffer->PartitionEntry;
2030 PPARTITION_INFORMATION TableEntry;
2031 ExtendedOffset.QuadPart = NextOffset.QuadPart = Offset.QuadPart = 0;
2032 PAGED_CODE();
2033
2034 /* Normalize the buffer size */
2035 BufferSize = max(512, SectorSize);
2036
2037 /* Get the partial drive geometry */
2038 xHalGetPartialGeometry(DeviceObject, &ConventionalCylinders, &DiskSize);
2039
2040 /* Check for EZ Drive */
2041 HalExamineMBR(DeviceObject, BufferSize, 0x55, &MbrBuffer);
2042 if (MbrBuffer)
2043 {
2044 /* EZ Drive found, bias the offset */
2045 IsEzDrive = TRUE;
2046 ExFreePool(MbrBuffer);
2047 Offset.QuadPart = 512;
2048 }
2049
2050 /* Get the number of bits to shift to multiply by the sector size */
2051 for (k = 0; k < 32; k++) if ((SectorSize >> k) == 1) break;
2052
2053 /* Check if there's only one partition */
2054 if (PartitionBuffer->PartitionCount == 1)
2055 {
2056 /* Check if it has no starting offset or hidden sectors */
2057 if (!(PartitionInfo->StartingOffset.QuadPart) &&
2058 !(PartitionInfo->HiddenSectors))
2059 {
2060 /* Then it's a super floppy */
2061 IsSuperFloppy = TRUE;
2062
2063 /* Which also means it must be non-bootable FAT-16 */
2064 if ((PartitionInfo->PartitionNumber) ||
2065 (PartitionInfo->PartitionType != PARTITION_FAT_16) ||
2066 (PartitionInfo->BootIndicator))
2067 {
2068 /* It's not, so we fail */
2069 return STATUS_INVALID_PARAMETER;
2070 }
2071
2072 /* Check if it needs a rewrite, and disable EZ drive for sure */
2073 if (PartitionInfo->RewritePartition) DoRewrite = TRUE;
2074 IsEzDrive = FALSE;
2075 }
2076 }
2077
2078 /* Count the number of partition tables */
2079 DiskLayout->TableCount = (PartitionBuffer->PartitionCount + 4 - 1) / 4;
2080
2081 /* Allocate our partition buffer */
2082 Buffer = ExAllocatePoolWithTag(NonPagedPool, PAGE_SIZE, TAG_FILE_SYSTEM);
2083 if (!Buffer) return STATUS_INSUFFICIENT_RESOURCES;
2084
2085 /* Loop the entries */
2086 Entry = (PPTE)&Buffer[PARTITION_TABLE_OFFSET];
2087 for (i = 0; i < DiskLayout->TableCount; i++)
2088 {
2089 /* Set if this is the MBR partition */
2090 IsMbr= (BOOLEAN)!i;
2091
2092 /* Initialize th event */
2093 KeInitializeEvent(&Event, NotificationEvent, FALSE);
2094
2095 /* Build the read IRP */
2096 Irp = IoBuildSynchronousFsdRequest(IRP_MJ_READ,
2097 DeviceObject,
2098 Buffer,
2099 BufferSize,
2100 &Offset,
2101 &Event,
2102 &IoStatusBlock);
2103 if (!Irp)
2104 {
2105 /* Fail */
2106 Status = STATUS_INSUFFICIENT_RESOURCES;
2107 break;
2108 }
2109
2110 /* Make sure to disable volume verification */
2111 IoStackLocation = IoGetNextIrpStackLocation(Irp);
2112 IoStackLocation->Flags |= SL_OVERRIDE_VERIFY_VOLUME;
2113
2114 /* Call the driver */
2115 Status = IoCallDriver(DeviceObject, Irp);
2116 if (Status == STATUS_PENDING)
2117 {
2118 /* Wait for completion */
2119 KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL);
2120 Status = IoStatusBlock.Status;
2121 }
2122
2123 /* Check for failure */
2124 if (!NT_SUCCESS(Status)) break;
2125
2126 /* If we biased for EZ-Drive, unbias now */
2127 if (IsEzDrive && (Offset.QuadPart == 512)) Offset.QuadPart = 0;
2128
2129 /* Check if this is a normal disk */
2130 if (!IsSuperFloppy)
2131 {
2132 /* Set the boot record signature */
2133 Buffer[BOOT_SIGNATURE_OFFSET] = BOOT_RECORD_SIGNATURE;
2134
2135 /* By default, don't require a rewrite */
2136 DoRewrite = FALSE;
2137
2138 /* Check if we don't have an offset */
2139 if (!Offset.QuadPart)
2140 {
2141 /* Check if the signature doesn't match */
2142 if (((PULONG)Buffer)[PARTITION_TABLE_OFFSET / 2 - 1] !=
2143 PartitionBuffer->Signature)
2144 {
2145 /* Then write the signature and now w need a rewrite */
2146 ((PULONG)Buffer)[PARTITION_TABLE_OFFSET / 2 - 1] =
2147 PartitionBuffer->Signature;
2148 DoRewrite = TRUE;
2149 }
2150 }
2151
2152 /* Loop the partition table entries */
2153 PartitionTable = &DiskLayout->PartitionTable[i];
2154 for (j = 0; j < 4; j++)
2155 {
2156 /* Get the current entry and type */
2157 TableEntry = &PartitionTable->PartitionEntry[j];
2158 PartitionType = TableEntry->PartitionType;
2159
2160 /* Check if the entry needs a rewrite */
2161 if (TableEntry->RewritePartition)
2162 {
2163 /* Then we need one too */
2164 DoRewrite = TRUE;
2165
2166 /* Save the type and if it's a bootable partition */
2167 Entry[j].PartitionType = TableEntry->PartitionType;
2168 Entry[j].ActiveFlag = TableEntry->BootIndicator ? 0x80 : 0;
2169
2170 /* Make sure it's used */
2171 if (PartitionType != PARTITION_ENTRY_UNUSED)
2172 {
2173 /* Make sure it's not a container (unless primary) */
2174 if ((IsMbr) || !(IsContainerPartition(PartitionType)))
2175 {
2176 /* Use the partition offset */
2177 StartOffset.QuadPart = Offset.QuadPart;
2178 }
2179 else
2180 {
2181 /* Use the extended logical partition offset */
2182 StartOffset.QuadPart = ExtendedOffset.QuadPart;
2183 }
2184
2185 /* Set the sector offset */
2186 SectorOffset.QuadPart = TableEntry->
2187 StartingOffset.QuadPart -
2188 StartOffset.QuadPart;
2189
2190 /* Now calculate the starting sector */
2191 StartOffset.QuadPart = SectorOffset.QuadPart >> k;
2192 Entry[j].StartingSector = StartOffset.LowPart;
2193
2194 /* As well as the length */
2195 PartitionLength.QuadPart = TableEntry->PartitionLength.
2196 QuadPart >> k;
2197 Entry[j].PartitionLength = PartitionLength.LowPart;
2198
2199 /* Calculate the CHS values */
2200 HalpCalculateChsValues(&TableEntry->StartingOffset,
2201 &TableEntry->PartitionLength,
2202 k,
2203 SectorsPerTrack,
2204 NumberOfHeads,
2205 ConventionalCylinders,
2206 (PPARTITION_DESCRIPTOR)
2207 &Entry[j]);
2208 }
2209 else
2210 {
2211 /* Otherwise set up an empty entry */
2212 Entry[j].StartingSector = 0;
2213 Entry[j].PartitionLength = 0;
2214 Entry[j].StartingTrack = 0;
2215 Entry[j].EndingTrack = 0;
2216 Entry[j].StartingCylinder = 0;
2217 Entry[j].EndingCylinder = 0;
2218 }
2219 }
2220
2221 /* Check if this is a container partition */
2222 if (IsContainerPartition(PartitionType))
2223 {
2224 /* Then update the offset to use */
2225 NextOffset = TableEntry->StartingOffset;
2226 }
2227 }
2228 }
2229
2230 /* Check if we need to write back the buffer */
2231 if (DoRewrite)
2232 {
2233 /* We don't need to do this again */
2234 DoRewrite = FALSE;
2235
2236 /* Initialize the event */
2237 KeInitializeEvent(&Event, NotificationEvent, FALSE);
2238
2239 /* If we unbiased for EZ-Drive, rebias now */
2240 if ((IsEzDrive) && !(Offset.QuadPart)) Offset.QuadPart = 512;
2241
2242 /* Build the write IRP */
2243 Irp = IoBuildSynchronousFsdRequest(IRP_MJ_WRITE,
2244 DeviceObject,
2245 Buffer,
2246 BufferSize,
2247 &Offset,
2248 &Event,
2249 &IoStatusBlock);
2250 if (!Irp)
2251 {
2252 /* Fail */
2253 Status = STATUS_INSUFFICIENT_RESOURCES;
2254 break;
2255 }
2256
2257 /* Make sure to disable volume verification */
2258 IoStackLocation = IoGetNextIrpStackLocation(Irp);
2259 IoStackLocation->Flags |= SL_OVERRIDE_VERIFY_VOLUME;
2260
2261 /* Call the driver */
2262 Status = IoCallDriver(DeviceObject, Irp);
2263 if (Status == STATUS_PENDING)
2264 {
2265 /* Wait for completion */
2266 KeWaitForSingleObject(&Event,
2267 Executive,
2268 KernelMode,
2269 FALSE,
2270 NULL);
2271 Status = IoStatusBlock.Status;
2272 }
2273
2274 /* Check for failure */
2275 if (!NT_SUCCESS(Status)) break;
2276
2277 /* If we biased for EZ-Drive, unbias now */
2278 if (IsEzDrive && (Offset.QuadPart == 512)) Offset.QuadPart = 0;
2279 }
2280
2281 /* Update the partition offset and set the extended offset if needed */
2282 Offset = NextOffset;
2283 if (IsMbr) ExtendedOffset = NextOffset;
2284 }
2285
2286 /* If we had a buffer, free it, then return status */
2287 if (Buffer) ExFreePoolWithTag(Buffer, TAG_FILE_SYSTEM);
2288 return Status;
2289 }
2290
2291 /* PUBLIC FUNCTIONS **********************************************************/
2292
2293 /*
2294 * @implemented
2295 */
2296 VOID
2297 FASTCALL
2298 HalExamineMBR(IN PDEVICE_OBJECT DeviceObject,
2299 IN ULONG SectorSize,
2300 IN ULONG MbrTypeIdentifier,
2301 OUT PVOID *MbrBuffer)
2302 {
2303 HALDISPATCH->HalExamineMBR(DeviceObject,
2304 SectorSize,
2305 MbrTypeIdentifier,
2306 MbrBuffer);
2307 }
2308
2309 /*
2310 * @implemented
2311 */
2312 NTSTATUS
2313 FASTCALL
2314 IoReadPartitionTable(IN PDEVICE_OBJECT DeviceObject,
2315 IN ULONG SectorSize,
2316 IN BOOLEAN ReturnRecognizedPartitions,
2317 IN OUT PDRIVE_LAYOUT_INFORMATION *PartitionBuffer)
2318 {
2319 return HALDISPATCH->HalIoReadPartitionTable(DeviceObject,
2320 SectorSize,
2321 ReturnRecognizedPartitions,
2322 PartitionBuffer);
2323 }
2324
2325 /*
2326 * @implemented
2327 */
2328 NTSTATUS
2329 FASTCALL
2330 IoSetPartitionInformation(IN PDEVICE_OBJECT DeviceObject,
2331 IN ULONG SectorSize,
2332 IN ULONG PartitionNumber,
2333 IN ULONG PartitionType)
2334 {
2335 return HALDISPATCH->HalIoSetPartitionInformation(DeviceObject,
2336 SectorSize,
2337 PartitionNumber,
2338 PartitionType);
2339 }
2340
2341 /*
2342 * @implemented
2343 */
2344 NTSTATUS
2345 FASTCALL
2346 IoWritePartitionTable(IN PDEVICE_OBJECT DeviceObject,
2347 IN ULONG SectorSize,
2348 IN ULONG SectorsPerTrack,
2349 IN ULONG NumberOfHeads,
2350 IN PDRIVE_LAYOUT_INFORMATION PartitionBuffer)
2351 {
2352 return HALDISPATCH->HalIoWritePartitionTable(DeviceObject,
2353 SectorSize,
2354 SectorsPerTrack,
2355 NumberOfHeads,
2356 PartitionBuffer);
2357 }
2358
2359 /*
2360 * @implemented
2361 */
2362 VOID
2363 FASTCALL
2364 IoAssignDriveLetters(IN PLOADER_PARAMETER_BLOCK LoaderBlock,
2365 IN PSTRING NtDeviceName,
2366 OUT PUCHAR NtSystemPath,
2367 OUT PSTRING NtSystemPathString)
2368 {
2369 HALDISPATCH->HalIoAssignDriveLetters(LoaderBlock,
2370 NtDeviceName,
2371 NtSystemPath,
2372 NtSystemPathString);
2373 }
2374
2375 /* EOF */