[FREELDR] Hack: Boot ReactOS even when a cdrom-drive does not report a proper geometry
[reactos.git] / boot / freeldr / freeldr / arch / i386 / hwdisk.c
1 /*
2 * FreeLoader
3 *
4 * Copyright (C) 2003, 2004 Eric Kohl
5 * Copyright (C) 2009 Hervé Poussineau
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 */
21
22 #include <freeldr.h>
23
24 #include <debug.h>
25 DBG_DEFAULT_CHANNEL(HWDETECT);
26
27 /*
28 * This is the common code for harddisk for both the PC and the XBOX.
29 */
30
31 typedef struct tagDISKCONTEXT
32 {
33 UCHAR DriveNumber;
34 ULONG SectorSize;
35 ULONGLONG SectorOffset;
36 ULONGLONG SectorCount;
37 ULONGLONG SectorNumber;
38 } DISKCONTEXT;
39
40 static const CHAR Hex[] = "0123456789abcdef";
41
42 /* Data cache for BIOS disks pre-enumeration */
43 UCHAR PcBiosDiskCount = 0;
44 static CHAR PcDiskIdentifier[32][20];
45
46 PVOID DiskReadBuffer;
47 SIZE_T DiskReadBufferSize;
48
49
50 /* FUNCTIONS *****************************************************************/
51
52 static ARC_STATUS
53 DiskClose(ULONG FileId)
54 {
55 DISKCONTEXT* Context = FsGetDeviceSpecific(FileId);
56 FrLdrTempFree(Context, TAG_HW_DISK_CONTEXT);
57 return ESUCCESS;
58 }
59
60 static ARC_STATUS
61 DiskGetFileInformation(ULONG FileId, FILEINFORMATION* Information)
62 {
63 DISKCONTEXT* Context = FsGetDeviceSpecific(FileId);
64
65 RtlZeroMemory(Information, sizeof(*Information));
66
67 /*
68 * The ARC specification mentions that for partitions, StartingAddress and
69 * EndingAddress are the start and end positions of the partition in terms
70 * of byte offsets from the start of the disk.
71 * CurrentAddress is the current offset into (i.e. relative to) the partition.
72 */
73 Information->StartingAddress.QuadPart = Context->SectorOffset * Context->SectorSize;
74 Information->EndingAddress.QuadPart = (Context->SectorOffset + Context->SectorCount) * Context->SectorSize;
75 Information->CurrentAddress.QuadPart = Context->SectorNumber * Context->SectorSize;
76
77 return ESUCCESS;
78 }
79
80 static ARC_STATUS
81 DiskOpen(CHAR* Path, OPENMODE OpenMode, ULONG* FileId)
82 {
83 DISKCONTEXT* Context;
84 UCHAR DriveNumber;
85 ULONG DrivePartition, SectorSize;
86 ULONGLONG SectorOffset = 0;
87 ULONGLONG SectorCount = 0;
88 PARTITION_TABLE_ENTRY PartitionTableEntry;
89
90 if (DiskReadBufferSize == 0)
91 {
92 ERR("DiskOpen(): DiskReadBufferSize is 0, something is wrong.\n");
93 ASSERT(FALSE);
94 return ENOMEM;
95 }
96
97 if (!DissectArcPath(Path, NULL, &DriveNumber, &DrivePartition))
98 return EINVAL;
99
100 if (DrivePartition == 0xff)
101 {
102 /* This is a CD-ROM device */
103 SectorSize = 2048;
104 }
105 else
106 {
107 /*
108 * This is either a floppy disk device (DrivePartition == 0) or
109 * a hard disk device (DrivePartition != 0 && DrivePartition != 0xFF)
110 * but it doesn't matter which one because they both have 512 bytes
111 * per sector.
112 */
113 SectorSize = 512;
114 }
115
116 if (DrivePartition != 0xff && DrivePartition != 0)
117 {
118 if (!DiskGetPartitionEntry(DriveNumber, DrivePartition, &PartitionTableEntry))
119 return EINVAL;
120
121 SectorOffset = PartitionTableEntry.SectorCountBeforePartition;
122 SectorCount = PartitionTableEntry.PartitionSectorCount;
123 }
124 else
125 {
126 GEOMETRY Geometry;
127 if (!MachDiskGetDriveGeometry(DriveNumber, &Geometry))
128 return EINVAL;
129
130 if (SectorSize != Geometry.BytesPerSector)
131 {
132 ERR("SectorSize (%lu) != Geometry.BytesPerSector (%lu), expect problems!\n",
133 SectorSize, Geometry.BytesPerSector);
134 }
135
136 SectorOffset = 0;
137 SectorCount = (ULONGLONG)Geometry.Cylinders * Geometry.Heads * Geometry.Sectors;
138 }
139
140 Context = FrLdrTempAlloc(sizeof(DISKCONTEXT), TAG_HW_DISK_CONTEXT);
141 if (!Context)
142 return ENOMEM;
143
144 Context->DriveNumber = DriveNumber;
145 Context->SectorSize = SectorSize;
146 Context->SectorOffset = SectorOffset;
147 Context->SectorCount = SectorCount;
148 Context->SectorNumber = 0;
149 FsSetDeviceSpecific(*FileId, Context);
150
151 return ESUCCESS;
152 }
153
154 static ARC_STATUS
155 DiskRead(ULONG FileId, VOID* Buffer, ULONG N, ULONG* Count)
156 {
157 DISKCONTEXT* Context = FsGetDeviceSpecific(FileId);
158 UCHAR* Ptr = (UCHAR*)Buffer;
159 ULONG Length, TotalSectors, MaxSectors, ReadSectors;
160 BOOLEAN ret;
161 ULONGLONG SectorOffset;
162
163 ASSERT(DiskReadBufferSize > 0);
164
165 TotalSectors = (N + Context->SectorSize - 1) / Context->SectorSize;
166 MaxSectors = DiskReadBufferSize / Context->SectorSize;
167 SectorOffset = Context->SectorOffset + Context->SectorNumber;
168
169 // If MaxSectors is 0, this will lead to infinite loop.
170 // In release builds assertions are disabled, however we also have sanity checks in DiskOpen()
171 ASSERT(MaxSectors > 0);
172
173 ret = TRUE;
174
175 while (TotalSectors)
176 {
177 ReadSectors = TotalSectors;
178 if (ReadSectors > MaxSectors)
179 ReadSectors = MaxSectors;
180
181 ret = MachDiskReadLogicalSectors(Context->DriveNumber,
182 SectorOffset,
183 ReadSectors,
184 DiskReadBuffer);
185 if (!ret)
186 break;
187
188 Length = ReadSectors * Context->SectorSize;
189 if (Length > N)
190 Length = N;
191
192 RtlCopyMemory(Ptr, DiskReadBuffer, Length);
193
194 Ptr += Length;
195 N -= Length;
196 SectorOffset += ReadSectors;
197 TotalSectors -= ReadSectors;
198 }
199
200 *Count = (ULONG)(Ptr - (UCHAR*)Buffer);
201
202 return (!ret) ? EIO : ESUCCESS;
203 }
204
205 static ARC_STATUS
206 DiskSeek(ULONG FileId, LARGE_INTEGER* Position, SEEKMODE SeekMode)
207 {
208 DISKCONTEXT* Context = FsGetDeviceSpecific(FileId);
209 LARGE_INTEGER NewPosition = *Position;
210
211 switch (SeekMode)
212 {
213 case SeekAbsolute:
214 break;
215 case SeekRelative:
216 NewPosition.QuadPart += (Context->SectorNumber * Context->SectorSize);
217 break;
218 default:
219 ASSERT(FALSE);
220 return EINVAL;
221 }
222
223 if (NewPosition.QuadPart & (Context->SectorSize - 1))
224 return EINVAL;
225
226 /* Convert in number of sectors */
227 NewPosition.QuadPart /= Context->SectorSize;
228
229 /* HACK: CDROMs may have a SectorCount of 0 */
230 if (Context->SectorCount != 0 && NewPosition.QuadPart >= Context->SectorCount)
231 return EINVAL;
232
233 Context->SectorNumber = NewPosition.QuadPart;
234 return ESUCCESS;
235 }
236
237 static const DEVVTBL DiskVtbl =
238 {
239 DiskClose,
240 DiskGetFileInformation,
241 DiskOpen,
242 DiskRead,
243 DiskSeek,
244 };
245
246
247 PCHAR
248 GetHarddiskIdentifier(UCHAR DriveNumber)
249 {
250 return PcDiskIdentifier[DriveNumber - 0x80];
251 }
252
253 static VOID
254 GetHarddiskInformation(UCHAR DriveNumber)
255 {
256 PMASTER_BOOT_RECORD Mbr;
257 PULONG Buffer;
258 ULONG i;
259 ULONG Checksum;
260 ULONG Signature;
261 BOOLEAN ValidPartitionTable;
262 CHAR ArcName[MAX_PATH];
263 PARTITION_TABLE_ENTRY PartitionTableEntry;
264 PCHAR Identifier = PcDiskIdentifier[DriveNumber - 0x80];
265
266 /* Detect disk partition type */
267 DiskDetectPartitionType(DriveNumber);
268
269 /* Read the MBR */
270 if (!MachDiskReadLogicalSectors(DriveNumber, 0ULL, 1, DiskReadBuffer))
271 {
272 ERR("Reading MBR failed\n");
273 /* We failed, use a default identifier */
274 sprintf(Identifier, "BIOSDISK%d", DriveNumber - 0x80 + 1);
275 return;
276 }
277
278 Buffer = (ULONG*)DiskReadBuffer;
279 Mbr = (PMASTER_BOOT_RECORD)DiskReadBuffer;
280
281 Signature = Mbr->Signature;
282 TRACE("Signature: %x\n", Signature);
283
284 /* Calculate the MBR checksum */
285 Checksum = 0;
286 for (i = 0; i < 512 / sizeof(ULONG); i++)
287 {
288 Checksum += Buffer[i];
289 }
290 Checksum = ~Checksum + 1;
291 TRACE("Checksum: %x\n", Checksum);
292
293 ValidPartitionTable = (Mbr->MasterBootRecordMagic == 0xAA55);
294
295 /* Fill out the ARC disk block */
296 sprintf(ArcName, "multi(0)disk(0)rdisk(%u)", DriveNumber - 0x80);
297 AddReactOSArcDiskInfo(ArcName, Signature, Checksum, ValidPartitionTable);
298
299 sprintf(ArcName, "multi(0)disk(0)rdisk(%u)partition(0)", DriveNumber - 0x80);
300 FsRegisterDevice(ArcName, &DiskVtbl);
301
302 /* Add partitions */
303 i = 1;
304 DiskReportError(FALSE);
305 while (DiskGetPartitionEntry(DriveNumber, i, &PartitionTableEntry))
306 {
307 if (PartitionTableEntry.SystemIndicator != PARTITION_ENTRY_UNUSED)
308 {
309 sprintf(ArcName, "multi(0)disk(0)rdisk(%u)partition(%lu)", DriveNumber - 0x80, i);
310 FsRegisterDevice(ArcName, &DiskVtbl);
311 }
312 i++;
313 }
314 DiskReportError(TRUE);
315
316 /* Convert checksum and signature to identifier string */
317 Identifier[0] = Hex[(Checksum >> 28) & 0x0F];
318 Identifier[1] = Hex[(Checksum >> 24) & 0x0F];
319 Identifier[2] = Hex[(Checksum >> 20) & 0x0F];
320 Identifier[3] = Hex[(Checksum >> 16) & 0x0F];
321 Identifier[4] = Hex[(Checksum >> 12) & 0x0F];
322 Identifier[5] = Hex[(Checksum >> 8) & 0x0F];
323 Identifier[6] = Hex[(Checksum >> 4) & 0x0F];
324 Identifier[7] = Hex[Checksum & 0x0F];
325 Identifier[8] = '-';
326 Identifier[9] = Hex[(Signature >> 28) & 0x0F];
327 Identifier[10] = Hex[(Signature >> 24) & 0x0F];
328 Identifier[11] = Hex[(Signature >> 20) & 0x0F];
329 Identifier[12] = Hex[(Signature >> 16) & 0x0F];
330 Identifier[13] = Hex[(Signature >> 12) & 0x0F];
331 Identifier[14] = Hex[(Signature >> 8) & 0x0F];
332 Identifier[15] = Hex[(Signature >> 4) & 0x0F];
333 Identifier[16] = Hex[Signature & 0x0F];
334 Identifier[17] = '-';
335 Identifier[18] = (ValidPartitionTable ? 'A' : 'X');
336 Identifier[19] = 0;
337 TRACE("Identifier: %s\n", Identifier);
338 }
339
340 static UCHAR
341 EnumerateHarddisks(OUT PBOOLEAN BootDriveReported)
342 {
343 UCHAR DiskCount, DriveNumber;
344 ULONG i;
345 BOOLEAN Changed;
346
347 *BootDriveReported = FALSE;
348
349 /* Count the number of visible harddisk drives */
350 DiskReportError(FALSE);
351 DiskCount = 0;
352 DriveNumber = 0x80;
353
354 ASSERT(DiskReadBufferSize > 0);
355
356 /*
357 * There are some really broken BIOSes out there. There are even BIOSes
358 * that happily report success when you ask them to read from non-existent
359 * harddisks. So, we set the buffer to known contents first, then try to
360 * read. If the BIOS reports success but the buffer contents haven't
361 * changed then we fail anyway.
362 */
363 memset(DiskReadBuffer, 0xcd, DiskReadBufferSize);
364 while (MachDiskReadLogicalSectors(DriveNumber, 0ULL, 1, DiskReadBuffer))
365 {
366 Changed = FALSE;
367 for (i = 0; !Changed && i < DiskReadBufferSize; i++)
368 {
369 Changed = ((PUCHAR)DiskReadBuffer)[i] != 0xcd;
370 }
371 if (!Changed)
372 {
373 TRACE("BIOS reports success for disk %d (0x%02X) but data didn't change\n",
374 (int)DiskCount, DriveNumber);
375 break;
376 }
377
378 /* Cache the BIOS hard disk information for later use */
379 GetHarddiskInformation(DriveNumber);
380
381 /* Check if we have seen the boot drive */
382 if (FrldrBootDrive == DriveNumber)
383 *BootDriveReported = TRUE;
384
385 DiskCount++;
386 DriveNumber++;
387 memset(DiskReadBuffer, 0xcd, DiskReadBufferSize);
388 }
389 DiskReportError(TRUE);
390
391 PcBiosDiskCount = DiskCount;
392 TRACE("BIOS reports %d harddisk%s\n",
393 (int)DiskCount, (DiskCount == 1) ? "" : "s");
394
395 return DiskCount;
396 }
397
398 static BOOLEAN
399 DiskIsDriveRemovable(UCHAR DriveNumber)
400 {
401 /*
402 * Hard disks use drive numbers >= 0x80 . So if the drive number
403 * indicates a hard disk then return FALSE.
404 * 0x49 is our magic ramdisk drive, so return FALSE for that too.
405 */
406 if ((DriveNumber >= 0x80) || (DriveNumber == 0x49))
407 return FALSE;
408
409 /* The drive is a floppy diskette so return TRUE */
410 return TRUE;
411 }
412
413 static BOOLEAN
414 DiskGetBootPath(BOOLEAN IsPxe)
415 {
416 if (*FrLdrBootPath)
417 return TRUE;
418
419 // FIXME! FIXME! Do this in some drive recognition procedure!!!!
420 if (IsPxe)
421 {
422 RtlStringCbCopyA(FrLdrBootPath, sizeof(FrLdrBootPath), "net(0)");
423 }
424 else
425 /* 0x49 is our magic ramdisk drive, so try to detect it first */
426 if (FrldrBootDrive == 0x49)
427 {
428 /* This is the ramdisk. See ArmInitializeBootDevices() too... */
429 // RtlStringCbPrintfA(FrLdrBootPath, sizeof(FrLdrBootPath), "ramdisk(%u)", 0);
430 RtlStringCbCopyA(FrLdrBootPath, sizeof(FrLdrBootPath), "ramdisk(0)");
431 }
432 else if (FrldrBootDrive < 0x80)
433 {
434 /* This is a floppy */
435 RtlStringCbPrintfA(FrLdrBootPath, sizeof(FrLdrBootPath),
436 "multi(0)disk(0)fdisk(%u)", FrldrBootDrive);
437 }
438 else if (FrldrBootPartition == 0xFF)
439 {
440 /* Boot Partition 0xFF is the magic value that indicates booting from CD-ROM (see isoboot.S) */
441 RtlStringCbPrintfA(FrLdrBootPath, sizeof(FrLdrBootPath),
442 "multi(0)disk(0)cdrom(%u)", FrldrBootDrive - 0x80);
443 }
444 else
445 {
446 ULONG BootPartition;
447 PARTITION_TABLE_ENTRY PartitionEntry;
448
449 /* This is a hard disk */
450 if (!DiskGetBootPartitionEntry(FrldrBootDrive, &PartitionEntry, &BootPartition))
451 {
452 ERR("Failed to get boot partition entry\n");
453 return FALSE;
454 }
455
456 FrldrBootPartition = BootPartition;
457
458 RtlStringCbPrintfA(FrLdrBootPath, sizeof(FrLdrBootPath),
459 "multi(0)disk(0)rdisk(%u)partition(%lu)",
460 FrldrBootDrive - 0x80, FrldrBootPartition);
461 }
462
463 return TRUE;
464 }
465
466 BOOLEAN
467 PcInitializeBootDevices(VOID)
468 {
469 UCHAR DiskCount;
470 BOOLEAN BootDriveReported = FALSE;
471 ULONG i;
472
473 DiskCount = EnumerateHarddisks(&BootDriveReported);
474
475 /* Initialize FrLdrBootPath, the boot path we're booting from (the "SystemPartition") */
476 DiskGetBootPath(PxeInit());
477
478 /* Add it, if it's a floppy or cdrom */
479 if ((FrldrBootDrive >= 0x80 && !BootDriveReported) ||
480 DiskIsDriveRemovable(FrldrBootDrive))
481 {
482 /* TODO: Check if it's really a CDROM drive */
483
484 PMASTER_BOOT_RECORD Mbr;
485 PULONG Buffer;
486 ULONG Checksum = 0;
487 ULONG Signature;
488
489 /* Read the MBR */
490 if (!MachDiskReadLogicalSectors(FrldrBootDrive, 16ULL, 1, DiskReadBuffer))
491 {
492 ERR("Reading MBR failed\n");
493 return FALSE;
494 }
495
496 Buffer = (ULONG*)DiskReadBuffer;
497 Mbr = (PMASTER_BOOT_RECORD)DiskReadBuffer;
498
499 Signature = Mbr->Signature;
500 TRACE("Signature: %x\n", Signature);
501
502 /* Calculate the MBR checksum */
503 for (i = 0; i < 2048 / sizeof(ULONG); i++)
504 {
505 Checksum += Buffer[i];
506 }
507 Checksum = ~Checksum + 1;
508 TRACE("Checksum: %x\n", Checksum);
509
510 /* Fill out the ARC disk block */
511 AddReactOSArcDiskInfo(FrLdrBootPath, Signature, Checksum, TRUE);
512
513 FsRegisterDevice(FrLdrBootPath, &DiskVtbl);
514 DiskCount++; // This is not accounted for in the number of pre-enumerated BIOS drives!
515 TRACE("Additional boot drive detected: 0x%02X\n", (int)FrldrBootDrive);
516 }
517
518 return (DiskCount != 0);
519 }