d67494d508d345e948012160fcdb5a117a9c1125
[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 if (NewPosition.QuadPart >= Context->SectorCount)
229 return EINVAL;
230
231 Context->SectorNumber = NewPosition.QuadPart;
232 return ESUCCESS;
233 }
234
235 static const DEVVTBL DiskVtbl =
236 {
237 DiskClose,
238 DiskGetFileInformation,
239 DiskOpen,
240 DiskRead,
241 DiskSeek,
242 };
243
244
245 PCHAR
246 GetHarddiskIdentifier(UCHAR DriveNumber)
247 {
248 return PcDiskIdentifier[DriveNumber - 0x80];
249 }
250
251 static VOID
252 GetHarddiskInformation(UCHAR DriveNumber)
253 {
254 PMASTER_BOOT_RECORD Mbr;
255 PULONG Buffer;
256 ULONG i;
257 ULONG Checksum;
258 ULONG Signature;
259 BOOLEAN ValidPartitionTable;
260 CHAR ArcName[MAX_PATH];
261 PARTITION_TABLE_ENTRY PartitionTableEntry;
262 PCHAR Identifier = PcDiskIdentifier[DriveNumber - 0x80];
263
264 /* Detect disk partition type */
265 DiskDetectPartitionType(DriveNumber);
266
267 /* Read the MBR */
268 if (!MachDiskReadLogicalSectors(DriveNumber, 0ULL, 1, DiskReadBuffer))
269 {
270 ERR("Reading MBR failed\n");
271 /* We failed, use a default identifier */
272 sprintf(Identifier, "BIOSDISK%d", DriveNumber - 0x80 + 1);
273 return;
274 }
275
276 Buffer = (ULONG*)DiskReadBuffer;
277 Mbr = (PMASTER_BOOT_RECORD)DiskReadBuffer;
278
279 Signature = Mbr->Signature;
280 TRACE("Signature: %x\n", Signature);
281
282 /* Calculate the MBR checksum */
283 Checksum = 0;
284 for (i = 0; i < 512 / sizeof(ULONG); i++)
285 {
286 Checksum += Buffer[i];
287 }
288 Checksum = ~Checksum + 1;
289 TRACE("Checksum: %x\n", Checksum);
290
291 ValidPartitionTable = (Mbr->MasterBootRecordMagic == 0xAA55);
292
293 /* Fill out the ARC disk block */
294 sprintf(ArcName, "multi(0)disk(0)rdisk(%u)", DriveNumber - 0x80);
295 AddReactOSArcDiskInfo(ArcName, Signature, Checksum, ValidPartitionTable);
296
297 sprintf(ArcName, "multi(0)disk(0)rdisk(%u)partition(0)", DriveNumber - 0x80);
298 FsRegisterDevice(ArcName, &DiskVtbl);
299
300 /* Add partitions */
301 i = 1;
302 DiskReportError(FALSE);
303 while (DiskGetPartitionEntry(DriveNumber, i, &PartitionTableEntry))
304 {
305 if (PartitionTableEntry.SystemIndicator != PARTITION_ENTRY_UNUSED)
306 {
307 sprintf(ArcName, "multi(0)disk(0)rdisk(%u)partition(%lu)", DriveNumber - 0x80, i);
308 FsRegisterDevice(ArcName, &DiskVtbl);
309 }
310 i++;
311 }
312 DiskReportError(TRUE);
313
314 /* Convert checksum and signature to identifier string */
315 Identifier[0] = Hex[(Checksum >> 28) & 0x0F];
316 Identifier[1] = Hex[(Checksum >> 24) & 0x0F];
317 Identifier[2] = Hex[(Checksum >> 20) & 0x0F];
318 Identifier[3] = Hex[(Checksum >> 16) & 0x0F];
319 Identifier[4] = Hex[(Checksum >> 12) & 0x0F];
320 Identifier[5] = Hex[(Checksum >> 8) & 0x0F];
321 Identifier[6] = Hex[(Checksum >> 4) & 0x0F];
322 Identifier[7] = Hex[Checksum & 0x0F];
323 Identifier[8] = '-';
324 Identifier[9] = Hex[(Signature >> 28) & 0x0F];
325 Identifier[10] = Hex[(Signature >> 24) & 0x0F];
326 Identifier[11] = Hex[(Signature >> 20) & 0x0F];
327 Identifier[12] = Hex[(Signature >> 16) & 0x0F];
328 Identifier[13] = Hex[(Signature >> 12) & 0x0F];
329 Identifier[14] = Hex[(Signature >> 8) & 0x0F];
330 Identifier[15] = Hex[(Signature >> 4) & 0x0F];
331 Identifier[16] = Hex[Signature & 0x0F];
332 Identifier[17] = '-';
333 Identifier[18] = (ValidPartitionTable ? 'A' : 'X');
334 Identifier[19] = 0;
335 TRACE("Identifier: %s\n", Identifier);
336 }
337
338 static UCHAR
339 EnumerateHarddisks(OUT PBOOLEAN BootDriveReported)
340 {
341 UCHAR DiskCount, DriveNumber;
342 ULONG i;
343 BOOLEAN Changed;
344
345 *BootDriveReported = FALSE;
346
347 /* Count the number of visible harddisk drives */
348 DiskReportError(FALSE);
349 DiskCount = 0;
350 DriveNumber = 0x80;
351
352 ASSERT(DiskReadBufferSize > 0);
353
354 /*
355 * There are some really broken BIOSes out there. There are even BIOSes
356 * that happily report success when you ask them to read from non-existent
357 * harddisks. So, we set the buffer to known contents first, then try to
358 * read. If the BIOS reports success but the buffer contents haven't
359 * changed then we fail anyway.
360 */
361 memset(DiskReadBuffer, 0xcd, DiskReadBufferSize);
362 while (MachDiskReadLogicalSectors(DriveNumber, 0ULL, 1, DiskReadBuffer))
363 {
364 Changed = FALSE;
365 for (i = 0; !Changed && i < DiskReadBufferSize; i++)
366 {
367 Changed = ((PUCHAR)DiskReadBuffer)[i] != 0xcd;
368 }
369 if (!Changed)
370 {
371 TRACE("BIOS reports success for disk %d (0x%02X) but data didn't change\n",
372 (int)DiskCount, DriveNumber);
373 break;
374 }
375
376 /* Cache the BIOS hard disk information for later use */
377 GetHarddiskInformation(DriveNumber);
378
379 /* Check if we have seen the boot drive */
380 if (FrldrBootDrive == DriveNumber)
381 *BootDriveReported = TRUE;
382
383 DiskCount++;
384 DriveNumber++;
385 memset(DiskReadBuffer, 0xcd, DiskReadBufferSize);
386 }
387 DiskReportError(TRUE);
388
389 PcBiosDiskCount = DiskCount;
390 TRACE("BIOS reports %d harddisk%s\n",
391 (int)DiskCount, (DiskCount == 1) ? "" : "s");
392
393 return DiskCount;
394 }
395
396 static BOOLEAN
397 DiskIsDriveRemovable(UCHAR DriveNumber)
398 {
399 /*
400 * Hard disks use drive numbers >= 0x80 . So if the drive number
401 * indicates a hard disk then return FALSE.
402 * 0x49 is our magic ramdisk drive, so return FALSE for that too.
403 */
404 if ((DriveNumber >= 0x80) || (DriveNumber == 0x49))
405 return FALSE;
406
407 /* The drive is a floppy diskette so return TRUE */
408 return TRUE;
409 }
410
411 static BOOLEAN
412 DiskGetBootPath(BOOLEAN IsPxe)
413 {
414 if (*FrLdrBootPath)
415 return TRUE;
416
417 // FIXME! FIXME! Do this in some drive recognition procedure!!!!
418 if (IsPxe)
419 {
420 RtlStringCbCopyA(FrLdrBootPath, sizeof(FrLdrBootPath), "net(0)");
421 }
422 else
423 /* 0x49 is our magic ramdisk drive, so try to detect it first */
424 if (FrldrBootDrive == 0x49)
425 {
426 /* This is the ramdisk. See ArmInitializeBootDevices() too... */
427 // RtlStringCbPrintfA(FrLdrBootPath, sizeof(FrLdrBootPath), "ramdisk(%u)", 0);
428 RtlStringCbCopyA(FrLdrBootPath, sizeof(FrLdrBootPath), "ramdisk(0)");
429 }
430 else if (FrldrBootDrive < 0x80)
431 {
432 /* This is a floppy */
433 RtlStringCbPrintfA(FrLdrBootPath, sizeof(FrLdrBootPath),
434 "multi(0)disk(0)fdisk(%u)", FrldrBootDrive);
435 }
436 else if (FrldrBootPartition == 0xFF)
437 {
438 /* Boot Partition 0xFF is the magic value that indicates booting from CD-ROM (see isoboot.S) */
439 RtlStringCbPrintfA(FrLdrBootPath, sizeof(FrLdrBootPath),
440 "multi(0)disk(0)cdrom(%u)", FrldrBootDrive - 0x80);
441 }
442 else
443 {
444 ULONG BootPartition;
445 PARTITION_TABLE_ENTRY PartitionEntry;
446
447 /* This is a hard disk */
448 if (!DiskGetBootPartitionEntry(FrldrBootDrive, &PartitionEntry, &BootPartition))
449 {
450 ERR("Failed to get boot partition entry\n");
451 return FALSE;
452 }
453
454 FrldrBootPartition = BootPartition;
455
456 RtlStringCbPrintfA(FrLdrBootPath, sizeof(FrLdrBootPath),
457 "multi(0)disk(0)rdisk(%u)partition(%lu)",
458 FrldrBootDrive - 0x80, FrldrBootPartition);
459 }
460
461 return TRUE;
462 }
463
464 BOOLEAN
465 PcInitializeBootDevices(VOID)
466 {
467 UCHAR DiskCount;
468 BOOLEAN BootDriveReported = FALSE;
469 ULONG i;
470
471 DiskCount = EnumerateHarddisks(&BootDriveReported);
472
473 /* Initialize FrLdrBootPath, the boot path we're booting from (the "SystemPartition") */
474 DiskGetBootPath(PxeInit());
475
476 /* Add it, if it's a floppy or cdrom */
477 if ((FrldrBootDrive >= 0x80 && !BootDriveReported) ||
478 DiskIsDriveRemovable(FrldrBootDrive))
479 {
480 /* TODO: Check if it's really a CDROM drive */
481
482 PMASTER_BOOT_RECORD Mbr;
483 PULONG Buffer;
484 ULONG Checksum = 0;
485 ULONG Signature;
486
487 /* Read the MBR */
488 if (!MachDiskReadLogicalSectors(FrldrBootDrive, 16ULL, 1, DiskReadBuffer))
489 {
490 ERR("Reading MBR failed\n");
491 return FALSE;
492 }
493
494 Buffer = (ULONG*)DiskReadBuffer;
495 Mbr = (PMASTER_BOOT_RECORD)DiskReadBuffer;
496
497 Signature = Mbr->Signature;
498 TRACE("Signature: %x\n", Signature);
499
500 /* Calculate the MBR checksum */
501 for (i = 0; i < 2048 / sizeof(ULONG); i++)
502 {
503 Checksum += Buffer[i];
504 }
505 Checksum = ~Checksum + 1;
506 TRACE("Checksum: %x\n", Checksum);
507
508 /* Fill out the ARC disk block */
509 AddReactOSArcDiskInfo(FrLdrBootPath, Signature, Checksum, TRUE);
510
511 FsRegisterDevice(FrLdrBootPath, &DiskVtbl);
512 DiskCount++; // This is not accounted for in the number of pre-enumerated BIOS drives!
513 TRACE("Additional boot drive detected: 0x%02X\n", (int)FrldrBootDrive);
514 }
515
516 return (DiskCount != 0);
517 }