These changes are the raw update to qemu-2.6.
[kvmfornfv.git] / qemu / roms / ipxe / src / arch / i386 / interface / pcbios / int13.c
1 /*
2  * Copyright (C) 2006 Michael Brown <mbrown@fensystems.co.uk>.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301, USA.
18  *
19  * You can also choose to distribute this program under the terms of
20  * the Unmodified Binary Distribution Licence (as given in the file
21  * COPYING.UBDL), provided that you have satisfied its requirements.
22  */
23
24 FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
25
26 #include <stdint.h>
27 #include <stdlib.h>
28 #include <limits.h>
29 #include <byteswap.h>
30 #include <errno.h>
31 #include <assert.h>
32 #include <ipxe/list.h>
33 #include <ipxe/blockdev.h>
34 #include <ipxe/io.h>
35 #include <ipxe/open.h>
36 #include <ipxe/uri.h>
37 #include <ipxe/process.h>
38 #include <ipxe/xfer.h>
39 #include <ipxe/retry.h>
40 #include <ipxe/timer.h>
41 #include <ipxe/acpi.h>
42 #include <ipxe/sanboot.h>
43 #include <ipxe/device.h>
44 #include <ipxe/pci.h>
45 #include <ipxe/iso9660.h>
46 #include <ipxe/eltorito.h>
47 #include <realmode.h>
48 #include <bios.h>
49 #include <biosint.h>
50 #include <bootsector.h>
51 #include <int13.h>
52
53 /** @file
54  *
55  * INT 13 emulation
56  *
57  * This module provides a mechanism for exporting block devices via
58  * the BIOS INT 13 disk interrupt interface.  
59  *
60  */
61
62 /**
63  * Overall timeout for INT 13 commands (independent of underlying device
64  *
65  * Underlying devices should ideally never become totally stuck.
66  * However, if they do, then the INT 13 mechanism provides no means
67  * for the caller to cancel the operation, and the machine appears to
68  * hang.  Use an overall timeout for all commands to avoid this
69  * problem and bounce timeout failures to the caller.
70  */
71 #define INT13_COMMAND_TIMEOUT ( 15 * TICKS_PER_SEC )
72
73 /** An INT 13 emulated drive */
74 struct int13_drive {
75         /** Reference count */
76         struct refcnt refcnt;
77         /** List of all registered drives */
78         struct list_head list;
79
80         /** Block device URI */
81         struct uri *uri;
82         /** Underlying block device interface */
83         struct interface block;
84
85         /** BIOS in-use drive number (0x00-0xff) */
86         unsigned int drive;
87         /** BIOS natural drive number (0x00-0xff)
88          *
89          * This is the drive number that would have been assigned by
90          * 'naturally' appending the drive to the end of the BIOS
91          * drive list.
92          *
93          * If the emulated drive replaces a preexisting drive, this is
94          * the drive number that the preexisting drive gets remapped
95          * to.
96          */
97         unsigned int natural_drive;
98
99         /** Block device capacity */
100         struct block_device_capacity capacity;
101         /** INT 13 emulated blocksize shift
102          *
103          * To allow for emulation of CD-ROM access, this represents
104          * the left-shift required to translate from INT 13 blocks to
105          * underlying blocks.
106          */
107         unsigned int blksize_shift;
108
109         /** Number of cylinders
110          *
111          * The cylinder number field in an INT 13 call is ten bits
112          * wide, giving a maximum of 1024 cylinders.  Conventionally,
113          * when the 7.8GB limit of a CHS address is exceeded, it is
114          * the number of cylinders that is increased beyond the
115          * addressable limit.
116          */
117         unsigned int cylinders;
118         /** Number of heads
119          *
120          * The head number field in an INT 13 call is eight bits wide,
121          * giving a maximum of 256 heads.  However, apparently all
122          * versions of MS-DOS up to and including Win95 fail with 256
123          * heads, so the maximum encountered in practice is 255.
124          */
125         unsigned int heads;
126         /** Number of sectors per track
127          *
128          * The sector number field in an INT 13 call is six bits wide,
129          * giving a maximum of 63 sectors, since sector numbering
130          * (unlike head and cylinder numbering) starts at 1, not 0.
131          */
132         unsigned int sectors_per_track;
133
134         /** Drive is a CD-ROM */
135         int is_cdrom;
136         /** Address of El Torito boot catalog (if any) */
137         unsigned int boot_catalog;
138
139         /** Underlying device status, if in error */
140         int block_rc;
141         /** Status of last operation */
142         int last_status;
143 };
144
145 /** Vector for chaining to other INT 13 handlers */
146 static struct segoff __text16 ( int13_vector );
147 #define int13_vector __use_text16 ( int13_vector )
148
149 /** Assembly wrapper */
150 extern void int13_wrapper ( void );
151
152 /** Dummy floppy disk parameter table */
153 static struct int13_fdd_parameters __data16 ( int13_fdd_params ) = {
154         /* 512 bytes per sector */
155         .bytes_per_sector = 0x02,
156         /* Highest sectors per track that we ever return */
157         .sectors_per_track = 48,
158 };
159 #define int13_fdd_params __use_data16 ( int13_fdd_params )
160
161 /** List of registered emulated drives */
162 static LIST_HEAD ( int13s );
163
164 /**
165  * Equipment word
166  *
167  * This is a cached copy of the BIOS Data Area equipment word at
168  * 40:10.
169  */
170 static uint16_t equipment_word;
171
172 /**
173  * Number of BIOS floppy disk drives
174  *
175  * This is derived from the equipment word.  It is held in .text16 to
176  * allow for easy access by the INT 13,08 wrapper.
177  */
178 static uint8_t __text16 ( num_fdds );
179 #define num_fdds __use_text16 ( num_fdds )
180
181 /**
182  * Number of BIOS hard disk drives
183  *
184  * This is a cached copy of the BIOS Data Area number of hard disk
185  * drives at 40:75.  It is held in .text16 to allow for easy access by
186  * the INT 13,08 wrapper.
187  */
188 static uint8_t __text16 ( num_drives );
189 #define num_drives __use_text16 ( num_drives )
190
191 /**
192  * Calculate INT 13 drive sector size
193  *
194  * @v int13             Emulated drive
195  * @ret blksize         Sector size
196  */
197 static inline size_t int13_blksize ( struct int13_drive *int13 ) {
198         return ( int13->capacity.blksize << int13->blksize_shift );
199 }
200
201 /**
202  * Calculate INT 13 drive capacity
203  *
204  * @v int13             Emulated drive
205  * @ret blocks          Number of blocks
206  */
207 static inline uint64_t int13_capacity ( struct int13_drive *int13 ) {
208         return ( int13->capacity.blocks >> int13->blksize_shift );
209 }
210
211 /**
212  * Calculate INT 13 drive capacity (limited to 32 bits)
213  *
214  * @v int13             Emulated drive
215  * @ret blocks          Number of blocks
216  */
217 static inline uint32_t int13_capacity32 ( struct int13_drive *int13 ) {
218         uint64_t capacity = int13_capacity ( int13 );
219         return ( ( capacity <= 0xffffffffUL ) ? capacity : 0xffffffff );
220 }
221
222 /**
223  * Test if INT 13 drive is a floppy disk drive
224  *
225  * @v int13             Emulated drive
226  * @ret is_fdd          Emulated drive is a floppy disk
227  */
228 static inline int int13_is_fdd ( struct int13_drive *int13 ) {
229         return ( ! ( int13->drive & 0x80 ) );
230 }
231
232 /** An INT 13 command */
233 struct int13_command {
234         /** Status */
235         int rc;
236         /** INT 13 drive */
237         struct int13_drive *int13;
238         /** Underlying block device interface */
239         struct interface block;
240         /** Command timeout timer */
241         struct retry_timer timer;
242 };
243
244 /**
245  * Record INT 13 drive capacity
246  *
247  * @v command           INT 13 command
248  * @v capacity          Block device capacity
249  */
250 static void int13_command_capacity ( struct int13_command *command,
251                                      struct block_device_capacity *capacity ) {
252         memcpy ( &command->int13->capacity, capacity,
253                  sizeof ( command->int13->capacity ) );
254 }
255
256 /**
257  * Close INT 13 command
258  *
259  * @v command           INT 13 command
260  * @v rc                Reason for close
261  */
262 static void int13_command_close ( struct int13_command *command, int rc ) {
263         intf_restart ( &command->block, rc );
264         stop_timer ( &command->timer );
265         command->rc = rc;
266 }
267
268 /**
269  * Handle INT 13 command timer expiry
270  *
271  * @v timer             Timer
272  */
273 static void int13_command_expired ( struct retry_timer *timer,
274                                     int over __unused ) {
275         struct int13_command *command =
276                 container_of ( timer, struct int13_command, timer );
277
278         int13_command_close ( command, -ETIMEDOUT );
279 }
280
281 /** INT 13 command interface operations */
282 static struct interface_operation int13_command_op[] = {
283         INTF_OP ( intf_close, struct int13_command *, int13_command_close ),
284         INTF_OP ( block_capacity, struct int13_command *,
285                   int13_command_capacity ),
286 };
287
288 /** INT 13 command interface descriptor */
289 static struct interface_descriptor int13_command_desc =
290         INTF_DESC ( struct int13_command, block, int13_command_op );
291
292 /**
293  * Open (or reopen) INT 13 emulated drive underlying block device
294  *
295  * @v int13             Emulated drive
296  * @ret rc              Return status code
297  */
298 static int int13_reopen_block ( struct int13_drive *int13 ) {
299         int rc;
300
301         /* Close any existing block device */
302         intf_restart ( &int13->block, -ECONNRESET );
303
304         /* Open block device */
305         if ( ( rc = xfer_open_uri ( &int13->block, int13->uri ) ) != 0 ) {
306                 DBGC ( int13, "INT13 drive %02x could not reopen block "
307                        "device: %s\n", int13->drive, strerror ( rc ) );
308                 int13->block_rc = rc;
309                 return rc;
310         }
311
312         /* Clear block device error status */
313         int13->block_rc = 0;
314
315         return 0;
316 }
317
318 /**
319  * Prepare to issue INT 13 command
320  *
321  * @v command           INT 13 command
322  * @v int13             Emulated drive
323  * @ret rc              Return status code
324  */
325 static int int13_command_start ( struct int13_command *command,
326                                  struct int13_drive *int13 ) {
327         int rc;
328
329         /* Sanity check */
330         assert ( command->int13 == NULL );
331         assert ( ! timer_running ( &command->timer ) );
332
333         /* Reopen block device if necessary */
334         if ( ( int13->block_rc != 0 ) &&
335              ( ( rc = int13_reopen_block ( int13 ) ) != 0 ) )
336                 return rc;
337
338         /* Initialise command */
339         command->rc = -EINPROGRESS;
340         command->int13 = int13;
341         start_timer_fixed ( &command->timer, INT13_COMMAND_TIMEOUT );
342
343         /* Wait for block control interface to become ready */
344         while ( ( command->rc == -EINPROGRESS ) &&
345                 ( xfer_window ( &int13->block ) == 0 ) ) {
346                 step();
347         }
348
349         return ( ( command->rc == -EINPROGRESS ) ?
350                  int13->block_rc : command->rc );
351 }
352
353 /**
354  * Wait for INT 13 command to complete
355  *
356  * @v command           INT 13 command
357  * @ret rc              Return status code
358  */
359 static int int13_command_wait ( struct int13_command *command ) {
360
361         /* Sanity check */
362         assert ( timer_running ( &command->timer ) );
363
364         /* Wait for command to complete */
365         while ( command->rc == -EINPROGRESS )
366                 step();
367
368         assert ( ! timer_running ( &command->timer ) );
369         return command->rc;
370 }
371
372 /**
373  * Terminate INT 13 command
374  *
375  * @v command           INT 13 command
376  */
377 static void int13_command_stop ( struct int13_command *command ) {
378         stop_timer ( &command->timer );
379         command->int13 = NULL;
380 }
381
382 /** The single active INT 13 command */
383 static struct int13_command int13_command = {
384         .block = INTF_INIT ( int13_command_desc ),
385         .timer = TIMER_INIT ( int13_command_expired ),
386 };
387
388 /**
389  * Read from or write to INT 13 drive
390  *
391  * @v int13             Emulated drive
392  * @v lba               Starting logical block address
393  * @v count             Number of logical blocks
394  * @v buffer            Data buffer
395  * @v block_rw          Block read/write method
396  * @ret rc              Return status code
397  */
398 static int int13_rw ( struct int13_drive *int13, uint64_t lba,
399                       unsigned int count, userptr_t buffer,
400                       int ( * block_rw ) ( struct interface *control,
401                                            struct interface *data,
402                                            uint64_t lba, unsigned int count,
403                                            userptr_t buffer, size_t len ) ) {
404         struct int13_command *command = &int13_command;
405         unsigned int frag_count;
406         size_t frag_len;
407         int rc;
408
409         /* Translate to underlying blocksize */
410         lba <<= int13->blksize_shift;
411         count <<= int13->blksize_shift;
412
413         while ( count ) {
414
415                 /* Determine fragment length */
416                 frag_count = count;
417                 if ( frag_count > int13->capacity.max_count )
418                         frag_count = int13->capacity.max_count;
419                 frag_len = ( int13->capacity.blksize * frag_count );
420
421                 /* Issue command */
422                 if ( ( ( rc = int13_command_start ( command, int13 ) ) != 0 ) ||
423                      ( ( rc = block_rw ( &int13->block, &command->block, lba,
424                                          frag_count, buffer,
425                                          frag_len ) ) != 0 ) ||
426                      ( ( rc = int13_command_wait ( command ) ) != 0 ) ) {
427                         int13_command_stop ( command );
428                         return rc;
429                 }
430                 int13_command_stop ( command );
431
432                 /* Move to next fragment */
433                 lba += frag_count;
434                 count -= frag_count;
435                 buffer = userptr_add ( buffer, frag_len );
436         }
437
438         return 0;
439 }
440
441 /**
442  * Read INT 13 drive capacity
443  *
444  * @v int13             Emulated drive
445  * @ret rc              Return status code
446  */
447 static int int13_read_capacity ( struct int13_drive *int13 ) {
448         struct int13_command *command = &int13_command;
449         int rc;
450
451         /* Issue command */
452         if ( ( ( rc = int13_command_start ( command, int13 ) ) != 0 ) ||
453              ( ( rc = block_read_capacity ( &int13->block,
454                                             &command->block ) ) != 0 ) ||
455              ( ( rc = int13_command_wait ( command ) ) != 0 ) ) {
456                 int13_command_stop ( command );
457                 return rc;
458         }
459
460         int13_command_stop ( command );
461         return 0;
462 }
463
464 /**
465  * Parse ISO9660 parameters
466  *
467  * @v int13             Emulated drive
468  * @v scratch           Scratch area for single-sector reads
469  * @ret rc              Return status code
470  *
471  * Reads and parses ISO9660 parameters, if present.
472  */
473 static int int13_parse_iso9660 ( struct int13_drive *int13, void *scratch ) {
474         static const struct iso9660_primary_descriptor_fixed primary_check = {
475                 .type = ISO9660_TYPE_PRIMARY,
476                 .id = ISO9660_ID,
477         };
478         struct iso9660_primary_descriptor *primary = scratch;
479         static const struct eltorito_descriptor_fixed boot_check = {
480                 .type = ISO9660_TYPE_BOOT,
481                 .id = ISO9660_ID,
482                 .version = 1,
483                 .system_id = "EL TORITO SPECIFICATION",
484         };
485         struct eltorito_descriptor *boot = scratch;
486         unsigned int blksize;
487         unsigned int blksize_shift;
488         int rc;
489
490         /* Calculate required blocksize shift */
491         blksize = int13_blksize ( int13 );
492         blksize_shift = 0;
493         while ( blksize < ISO9660_BLKSIZE ) {
494                 blksize <<= 1;
495                 blksize_shift++;
496         }
497         if ( blksize > ISO9660_BLKSIZE ) {
498                 /* Do nothing if the blksize is invalid for CD-ROM access */
499                 return 0;
500         }
501
502         /* Read primary volume descriptor */
503         if ( ( rc = int13_rw ( int13,
504                                ( ISO9660_PRIMARY_LBA << blksize_shift ), 1,
505                                virt_to_user ( primary ), block_read ) ) != 0 ){
506                 DBGC ( int13, "INT13 drive %02x could not read ISO9660 "
507                        "primary volume descriptor: %s\n",
508                        int13->drive, strerror ( rc ) );
509                 return rc;
510         }
511
512         /* Do nothing unless this is an ISO image */
513         if ( memcmp ( primary, &primary_check, sizeof ( primary_check ) ) != 0 )
514                 return 0;
515         DBGC ( int13, "INT13 drive %02x contains an ISO9660 filesystem; "
516                "treating as CD-ROM\n", int13->drive );
517         int13->is_cdrom = 1;
518
519         /* Read boot record volume descriptor */
520         if ( ( rc = int13_rw ( int13,
521                                ( ELTORITO_LBA << blksize_shift ), 1,
522                                virt_to_user ( boot ), block_read ) ) != 0 ) {
523                 DBGC ( int13, "INT13 drive %02x could not read El Torito boot "
524                        "record volume descriptor: %s\n",
525                        int13->drive, strerror ( rc ) );
526                 return rc;
527         }
528
529         /* Check for an El Torito boot catalog */
530         if ( memcmp ( boot, &boot_check, sizeof ( boot_check ) ) == 0 ) {
531                 int13->boot_catalog = boot->sector;
532                 DBGC ( int13, "INT13 drive %02x has an El Torito boot catalog "
533                        "at LBA %08x\n", int13->drive, int13->boot_catalog );
534         } else {
535                 DBGC ( int13, "INT13 drive %02x has no El Torito boot "
536                        "catalog\n", int13->drive );
537         }
538
539         /* Configure drive for no-emulation CD-ROM access */
540         int13->blksize_shift += blksize_shift;
541
542         return 0;
543 }
544
545 /**
546  * Guess INT 13 hard disk drive geometry
547  *
548  * @v int13             Emulated drive
549  * @v scratch           Scratch area for single-sector reads
550  * @ret heads           Guessed number of heads
551  * @ret sectors         Guessed number of sectors per track
552  * @ret rc              Return status code
553  *
554  * Guesses the drive geometry by inspecting the partition table.
555  */
556 static int int13_guess_geometry_hdd ( struct int13_drive *int13, void *scratch,
557                                       unsigned int *heads,
558                                       unsigned int *sectors ) {
559         struct master_boot_record *mbr = scratch;
560         struct partition_table_entry *partition;
561         unsigned int i;
562         int rc;
563
564         /* Default guess is xx/255/63 */
565         *heads = 255;
566         *sectors = 63;
567
568         /* Read partition table */
569         if ( ( rc = int13_rw ( int13, 0, 1, virt_to_user ( mbr ),
570                                block_read ) ) != 0 ) {
571                 DBGC ( int13, "INT13 drive %02x could not read "
572                        "partition table to guess geometry: %s\n",
573                        int13->drive, strerror ( rc ) );
574                 return rc;
575         }
576         DBGC2 ( int13, "INT13 drive %02x has MBR:\n", int13->drive );
577         DBGC2_HDA ( int13, 0, mbr, sizeof ( *mbr ) );
578         DBGC ( int13, "INT13 drive %02x has signature %08x\n",
579                int13->drive, mbr->signature );
580
581         /* Scan through partition table and modify guesses for
582          * heads and sectors_per_track if we find any used
583          * partitions.
584          */
585         for ( i = 0 ; i < 4 ; i++ ) {
586                 partition = &mbr->partitions[i];
587                 if ( ! partition->type )
588                         continue;
589                 *heads = ( PART_HEAD ( partition->chs_end ) + 1 );
590                 *sectors = PART_SECTOR ( partition->chs_end );
591                 DBGC ( int13, "INT13 drive %02x guessing C/H/S xx/%d/%d based "
592                        "on partition %d\n",
593                        int13->drive, *heads, *sectors, ( i + 1 ) );
594         }
595
596         return 0;
597 }
598
599 /** Recognised floppy disk geometries */
600 static const struct int13_fdd_geometry int13_fdd_geometries[] = {
601         INT13_FDD_GEOMETRY ( 40, 1, 8 ),
602         INT13_FDD_GEOMETRY ( 40, 1, 9 ),
603         INT13_FDD_GEOMETRY ( 40, 2, 8 ),
604         INT13_FDD_GEOMETRY ( 40, 1, 9 ),
605         INT13_FDD_GEOMETRY ( 80, 2, 8 ),
606         INT13_FDD_GEOMETRY ( 80, 2, 9 ),
607         INT13_FDD_GEOMETRY ( 80, 2, 15 ),
608         INT13_FDD_GEOMETRY ( 80, 2, 18 ),
609         INT13_FDD_GEOMETRY ( 80, 2, 20 ),
610         INT13_FDD_GEOMETRY ( 80, 2, 21 ),
611         INT13_FDD_GEOMETRY ( 82, 2, 21 ),
612         INT13_FDD_GEOMETRY ( 83, 2, 21 ),
613         INT13_FDD_GEOMETRY ( 80, 2, 22 ),
614         INT13_FDD_GEOMETRY ( 80, 2, 23 ),
615         INT13_FDD_GEOMETRY ( 80, 2, 24 ),
616         INT13_FDD_GEOMETRY ( 80, 2, 36 ),
617         INT13_FDD_GEOMETRY ( 80, 2, 39 ),
618         INT13_FDD_GEOMETRY ( 80, 2, 40 ),
619         INT13_FDD_GEOMETRY ( 80, 2, 44 ),
620         INT13_FDD_GEOMETRY ( 80, 2, 48 ),
621 };
622
623 /**
624  * Guess INT 13 floppy disk drive geometry
625  *
626  * @v int13             Emulated drive
627  * @ret heads           Guessed number of heads
628  * @ret sectors         Guessed number of sectors per track
629  * @ret rc              Return status code
630  *
631  * Guesses the drive geometry by inspecting the disk size.
632  */
633 static int int13_guess_geometry_fdd ( struct int13_drive *int13,
634                                       unsigned int *heads,
635                                       unsigned int *sectors ) {
636         unsigned int blocks = int13_capacity ( int13 );
637         const struct int13_fdd_geometry *geometry;
638         unsigned int cylinders;
639         unsigned int i;
640
641         /* Look for a match against a known geometry */
642         for ( i = 0 ; i < ( sizeof ( int13_fdd_geometries ) /
643                             sizeof ( int13_fdd_geometries[0] ) ) ; i++ ) {
644                 geometry = &int13_fdd_geometries[i];
645                 cylinders = INT13_FDD_CYLINDERS ( geometry );
646                 *heads = INT13_FDD_HEADS ( geometry );
647                 *sectors = INT13_FDD_SECTORS ( geometry );
648                 if ( ( cylinders * (*heads) * (*sectors) ) == blocks ) {
649                         DBGC ( int13, "INT13 drive %02x guessing C/H/S "
650                                "%d/%d/%d based on size %dK\n", int13->drive,
651                                cylinders, *heads, *sectors, ( blocks / 2 ) );
652                         return 0;
653                 }
654         }
655
656         /* Otherwise, assume a partial disk image in the most common
657          * format (1440K, 80/2/18).
658          */
659         *heads = 2;
660         *sectors = 18;
661         DBGC ( int13, "INT13 drive %02x guessing C/H/S xx/%d/%d based on size "
662                "%dK\n", int13->drive, *heads, *sectors, ( blocks / 2 ) );
663         return 0;
664 }
665
666 /**
667  * Guess INT 13 drive geometry
668  *
669  * @v int13             Emulated drive
670  * @v scratch           Scratch area for single-sector reads
671  * @ret rc              Return status code
672  */
673 static int int13_guess_geometry ( struct int13_drive *int13, void *scratch ) {
674         unsigned int guessed_heads;
675         unsigned int guessed_sectors;
676         unsigned int blocks;
677         unsigned int blocks_per_cyl;
678         int rc;
679
680         /* Don't even try when the blksize is invalid for C/H/S access */
681         if ( int13_blksize ( int13 ) != INT13_BLKSIZE )
682                 return 0;
683
684         /* Guess geometry according to drive type */
685         if ( int13_is_fdd ( int13 ) ) {
686                 if ( ( rc = int13_guess_geometry_fdd ( int13, &guessed_heads,
687                                                        &guessed_sectors )) != 0)
688                         return rc;
689         } else {
690                 if ( ( rc = int13_guess_geometry_hdd ( int13, scratch,
691                                                        &guessed_heads,
692                                                        &guessed_sectors )) != 0)
693                         return rc;
694         }
695
696         /* Apply guesses if no geometry already specified */
697         if ( ! int13->heads )
698                 int13->heads = guessed_heads;
699         if ( ! int13->sectors_per_track )
700                 int13->sectors_per_track = guessed_sectors;
701         if ( ! int13->cylinders ) {
702                 /* Avoid attempting a 64-bit divide on a 32-bit system */
703                 blocks = int13_capacity32 ( int13 );
704                 blocks_per_cyl = ( int13->heads * int13->sectors_per_track );
705                 assert ( blocks_per_cyl != 0 );
706                 int13->cylinders = ( blocks / blocks_per_cyl );
707                 if ( int13->cylinders > 1024 )
708                         int13->cylinders = 1024;
709         }
710
711         return 0;
712 }
713
714 /**
715  * Update BIOS drive count
716  */
717 static void int13_sync_num_drives ( void ) {
718         struct int13_drive *int13;
719         uint8_t *counter;
720         uint8_t max_drive;
721         uint8_t required;
722
723         /* Get current drive counts */
724         get_real ( equipment_word, BDA_SEG, BDA_EQUIPMENT_WORD );
725         get_real ( num_drives, BDA_SEG, BDA_NUM_DRIVES );
726         num_fdds = ( ( equipment_word & 0x0001 ) ?
727                      ( ( ( equipment_word >> 6 ) & 0x3 ) + 1 ) : 0 );
728
729         /* Ensure count is large enough to cover all of our emulated drives */
730         list_for_each_entry ( int13, &int13s, list ) {
731                 counter = ( int13_is_fdd ( int13 ) ? &num_fdds : &num_drives );
732                 max_drive = int13->drive;
733                 if ( max_drive < int13->natural_drive )
734                         max_drive = int13->natural_drive;
735                 required = ( ( max_drive & 0x7f ) + 1 );
736                 if ( *counter < required ) {
737                         *counter = required;
738                         DBGC ( int13, "INT13 drive %02x added to drive count: "
739                                "%d HDDs, %d FDDs\n",
740                                int13->drive, num_drives, num_fdds );
741                 }
742         }
743
744         /* Update current drive count */
745         equipment_word &= ~( ( 0x3 << 6 ) | 0x0001 );
746         if ( num_fdds ) {
747                 equipment_word |= ( 0x0001 |
748                                     ( ( ( num_fdds - 1 ) & 0x3 ) << 6 ) );
749         }
750         put_real ( equipment_word, BDA_SEG, BDA_EQUIPMENT_WORD );
751         put_real ( num_drives, BDA_SEG, BDA_NUM_DRIVES );
752 }
753
754 /**
755  * Check number of drives
756  */
757 static void int13_check_num_drives ( void ) {
758         uint16_t check_equipment_word;
759         uint8_t check_num_drives;
760
761         get_real ( check_equipment_word, BDA_SEG, BDA_EQUIPMENT_WORD );
762         get_real ( check_num_drives, BDA_SEG, BDA_NUM_DRIVES );
763         if ( ( check_equipment_word != equipment_word ) ||
764              ( check_num_drives != num_drives ) ) {
765                 int13_sync_num_drives();
766         }
767 }
768
769 /**
770  * INT 13, 00 - Reset disk system
771  *
772  * @v int13             Emulated drive
773  * @ret status          Status code
774  */
775 static int int13_reset ( struct int13_drive *int13,
776                          struct i386_all_regs *ix86 __unused ) {
777         int rc;
778
779         DBGC2 ( int13, "Reset drive\n" );
780
781         /* Reopen underlying block device */
782         if ( ( rc = int13_reopen_block ( int13 ) ) != 0 )
783                 return -INT13_STATUS_RESET_FAILED;
784
785         /* Check that block device is functional */
786         if ( ( rc = int13_read_capacity ( int13 ) ) != 0 )
787                 return -INT13_STATUS_RESET_FAILED;
788
789         return 0;
790 }
791
792 /**
793  * INT 13, 01 - Get status of last operation
794  *
795  * @v int13             Emulated drive
796  * @ret status          Status code
797  */
798 static int int13_get_last_status ( struct int13_drive *int13,
799                                    struct i386_all_regs *ix86 __unused ) {
800         DBGC2 ( int13, "Get status of last operation\n" );
801         return int13->last_status;
802 }
803
804 /**
805  * Read / write sectors
806  *
807  * @v int13             Emulated drive
808  * @v al                Number of sectors to read or write (must be nonzero)
809  * @v ch                Low bits of cylinder number
810  * @v cl (bits 7:6)     High bits of cylinder number
811  * @v cl (bits 5:0)     Sector number
812  * @v dh                Head number
813  * @v es:bx             Data buffer
814  * @v block_rw          Block read/write method
815  * @ret status          Status code
816  * @ret al              Number of sectors read or written
817  */
818 static int int13_rw_sectors ( struct int13_drive *int13,
819                               struct i386_all_regs *ix86,
820                               int ( * block_rw ) ( struct interface *control,
821                                                    struct interface *data,
822                                                    uint64_t lba,
823                                                    unsigned int count,
824                                                    userptr_t buffer,
825                                                    size_t len ) ) {
826         unsigned int cylinder, head, sector;
827         unsigned long lba;
828         unsigned int count;
829         userptr_t buffer;
830         int rc;
831
832         /* Validate blocksize */
833         if ( int13_blksize ( int13 ) != INT13_BLKSIZE ) {
834                 DBGC ( int13, "\nINT 13 drive %02x invalid blocksize (%zd) "
835                        "for non-extended read/write\n",
836                        int13->drive, int13_blksize ( int13 ) );
837                 return -INT13_STATUS_INVALID;
838         }
839
840         /* Calculate parameters */
841         cylinder = ( ( ( ix86->regs.cl & 0xc0 ) << 2 ) | ix86->regs.ch );
842         head = ix86->regs.dh;
843         sector = ( ix86->regs.cl & 0x3f );
844         if ( ( cylinder >= int13->cylinders ) ||
845              ( head >= int13->heads ) ||
846              ( sector < 1 ) || ( sector > int13->sectors_per_track ) ) {
847                 DBGC ( int13, "C/H/S %d/%d/%d out of range for geometry "
848                        "%d/%d/%d\n", cylinder, head, sector, int13->cylinders,
849                        int13->heads, int13->sectors_per_track );
850                 return -INT13_STATUS_INVALID;
851         }
852         lba = ( ( ( ( cylinder * int13->heads ) + head )
853                   * int13->sectors_per_track ) + sector - 1 );
854         count = ix86->regs.al;
855         buffer = real_to_user ( ix86->segs.es, ix86->regs.bx );
856
857         DBGC2 ( int13, "C/H/S %d/%d/%d = LBA %08lx <-> %04x:%04x (count %d)\n",
858                 cylinder, head, sector, lba, ix86->segs.es, ix86->regs.bx,
859                 count );
860
861         /* Read from / write to block device */
862         if ( ( rc = int13_rw ( int13, lba, count, buffer, block_rw ) ) != 0 ) {
863                 DBGC ( int13, "INT13 drive %02x I/O failed: %s\n",
864                        int13->drive, strerror ( rc ) );
865                 return -INT13_STATUS_READ_ERROR;
866         }
867
868         return 0;
869 }
870
871 /**
872  * INT 13, 02 - Read sectors
873  *
874  * @v int13             Emulated drive
875  * @v al                Number of sectors to read (must be nonzero)
876  * @v ch                Low bits of cylinder number
877  * @v cl (bits 7:6)     High bits of cylinder number
878  * @v cl (bits 5:0)     Sector number
879  * @v dh                Head number
880  * @v es:bx             Data buffer
881  * @ret status          Status code
882  * @ret al              Number of sectors read
883  */
884 static int int13_read_sectors ( struct int13_drive *int13,
885                                 struct i386_all_regs *ix86 ) {
886         DBGC2 ( int13, "Read: " );
887         return int13_rw_sectors ( int13, ix86, block_read );
888 }
889
890 /**
891  * INT 13, 03 - Write sectors
892  *
893  * @v int13             Emulated drive
894  * @v al                Number of sectors to write (must be nonzero)
895  * @v ch                Low bits of cylinder number
896  * @v cl (bits 7:6)     High bits of cylinder number
897  * @v cl (bits 5:0)     Sector number
898  * @v dh                Head number
899  * @v es:bx             Data buffer
900  * @ret status          Status code
901  * @ret al              Number of sectors written
902  */
903 static int int13_write_sectors ( struct int13_drive *int13,
904                                  struct i386_all_regs *ix86 ) {
905         DBGC2 ( int13, "Write: " );
906         return int13_rw_sectors ( int13, ix86, block_write );
907 }
908
909 /**
910  * INT 13, 08 - Get drive parameters
911  *
912  * @v int13             Emulated drive
913  * @ret status          Status code
914  * @ret ch              Low bits of maximum cylinder number
915  * @ret cl (bits 7:6)   High bits of maximum cylinder number
916  * @ret cl (bits 5:0)   Maximum sector number
917  * @ret dh              Maximum head number
918  * @ret dl              Number of drives
919  */
920 static int int13_get_parameters ( struct int13_drive *int13,
921                                   struct i386_all_regs *ix86 ) {
922         unsigned int max_cylinder = int13->cylinders - 1;
923         unsigned int max_head = int13->heads - 1;
924         unsigned int max_sector = int13->sectors_per_track; /* sic */
925
926         DBGC2 ( int13, "Get drive parameters\n" );
927
928         /* Validate blocksize */
929         if ( int13_blksize ( int13 ) != INT13_BLKSIZE ) {
930                 DBGC ( int13, "\nINT 13 drive %02x invalid blocksize (%zd) "
931                        "for non-extended parameters\n",
932                        int13->drive, int13_blksize ( int13 ) );
933                 return -INT13_STATUS_INVALID;
934         }
935
936         /* Common parameters */
937         ix86->regs.ch = ( max_cylinder & 0xff );
938         ix86->regs.cl = ( ( ( max_cylinder >> 8 ) << 6 ) | max_sector );
939         ix86->regs.dh = max_head;
940         ix86->regs.dl = ( int13_is_fdd ( int13 ) ? num_fdds : num_drives );
941
942         /* Floppy-specific parameters */
943         if ( int13_is_fdd ( int13 ) ) {
944                 ix86->regs.bl = INT13_FDD_TYPE_1M44;
945                 ix86->segs.es = rm_ds;
946                 ix86->regs.di = __from_data16 ( &int13_fdd_params );
947         }
948
949         return 0;
950 }
951
952 /**
953  * INT 13, 15 - Get disk type
954  *
955  * @v int13             Emulated drive
956  * @ret ah              Type code
957  * @ret cx:dx           Sector count
958  * @ret status          Status code / disk type
959  */
960 static int int13_get_disk_type ( struct int13_drive *int13,
961                                  struct i386_all_regs *ix86 ) {
962         uint32_t blocks;
963
964         DBGC2 ( int13, "Get disk type\n" );
965
966         if ( int13_is_fdd ( int13 ) ) {
967                 return INT13_DISK_TYPE_FDD;
968         } else {
969                 blocks = int13_capacity32 ( int13 );
970                 ix86->regs.cx = ( blocks >> 16 );
971                 ix86->regs.dx = ( blocks & 0xffff );
972                 return INT13_DISK_TYPE_HDD;
973         }
974 }
975
976 /**
977  * INT 13, 41 - Extensions installation check
978  *
979  * @v int13             Emulated drive
980  * @v bx                0x55aa
981  * @ret bx              0xaa55
982  * @ret cx              Extensions API support bitmap
983  * @ret status          Status code / API version
984  */
985 static int int13_extension_check ( struct int13_drive *int13 __unused,
986                                    struct i386_all_regs *ix86 ) {
987         if ( ix86->regs.bx == 0x55aa ) {
988                 DBGC2 ( int13, "INT13 extensions installation check\n" );
989                 ix86->regs.bx = 0xaa55;
990                 ix86->regs.cx = ( INT13_EXTENSION_LINEAR |
991                                   INT13_EXTENSION_EDD |
992                                   INT13_EXTENSION_64BIT );
993                 return INT13_EXTENSION_VER_3_0;
994         } else {
995                 return -INT13_STATUS_INVALID;
996         }
997 }
998
999 /**
1000  * Extended read / write
1001  *
1002  * @v int13             Emulated drive
1003  * @v ds:si             Disk address packet
1004  * @v block_rw          Block read/write method
1005  * @ret status          Status code
1006  */
1007 static int int13_extended_rw ( struct int13_drive *int13,
1008                                struct i386_all_regs *ix86,
1009                                int ( * block_rw ) ( struct interface *control,
1010                                                     struct interface *data,
1011                                                     uint64_t lba,
1012                                                     unsigned int count,
1013                                                     userptr_t buffer,
1014                                                     size_t len ) ) {
1015         struct int13_disk_address addr;
1016         uint8_t bufsize;
1017         uint64_t lba;
1018         unsigned long count;
1019         userptr_t buffer;
1020         int rc;
1021
1022         /* Extended reads are not allowed on floppy drives.
1023          * ELTORITO.SYS seems to assume that we are really a CD-ROM if
1024          * we support extended reads for a floppy drive.
1025          */
1026         if ( int13_is_fdd ( int13 ) )
1027                 return -INT13_STATUS_INVALID;
1028
1029         /* Get buffer size */
1030         get_real ( bufsize, ix86->segs.ds,
1031                    ( ix86->regs.si + offsetof ( typeof ( addr ), bufsize ) ) );
1032         if ( bufsize < offsetof ( typeof ( addr ), buffer_phys ) ) {
1033                 DBGC2 ( int13, "<invalid buffer size %#02x\n>\n", bufsize );
1034                 return -INT13_STATUS_INVALID;
1035         }
1036
1037         /* Read parameters from disk address structure */
1038         memset ( &addr, 0, sizeof ( addr ) );
1039         copy_from_real ( &addr, ix86->segs.ds, ix86->regs.si, bufsize );
1040         lba = addr.lba;
1041         DBGC2 ( int13, "LBA %08llx <-> ", ( ( unsigned long long ) lba ) );
1042         if ( ( addr.count == 0xff ) ||
1043              ( ( addr.buffer.segment == 0xffff ) &&
1044                ( addr.buffer.offset == 0xffff ) ) ) {
1045                 buffer = phys_to_user ( addr.buffer_phys );
1046                 DBGC2 ( int13, "%08llx",
1047                         ( ( unsigned long long ) addr.buffer_phys ) );
1048         } else {
1049                 buffer = real_to_user ( addr.buffer.segment,
1050                                         addr.buffer.offset );
1051                 DBGC2 ( int13, "%04x:%04x", addr.buffer.segment,
1052                         addr.buffer.offset );
1053         }
1054         if ( addr.count <= 0x7f ) {
1055                 count = addr.count;
1056         } else if ( addr.count == 0xff ) {
1057                 count = addr.long_count;
1058         } else {
1059                 DBGC2 ( int13, " <invalid count %#02x>\n", addr.count );
1060                 return -INT13_STATUS_INVALID;
1061         }
1062         DBGC2 ( int13, " (count %ld)\n", count );
1063
1064         /* Read from / write to block device */
1065         if ( ( rc = int13_rw ( int13, lba, count, buffer, block_rw ) ) != 0 ) {
1066                 DBGC ( int13, "INT13 drive %02x extended I/O failed: %s\n",
1067                        int13->drive, strerror ( rc ) );
1068                 /* Record that no blocks were transferred successfully */
1069                 addr.count = 0;
1070                 put_real ( addr.count, ix86->segs.ds,
1071                            ( ix86->regs.si +
1072                              offsetof ( typeof ( addr ), count ) ) );
1073                 return -INT13_STATUS_READ_ERROR;
1074         }
1075
1076         return 0;
1077 }
1078
1079 /**
1080  * INT 13, 42 - Extended read
1081  *
1082  * @v int13             Emulated drive
1083  * @v ds:si             Disk address packet
1084  * @ret status          Status code
1085  */
1086 static int int13_extended_read ( struct int13_drive *int13,
1087                                  struct i386_all_regs *ix86 ) {
1088         DBGC2 ( int13, "Extended read: " );
1089         return int13_extended_rw ( int13, ix86, block_read );
1090 }
1091
1092 /**
1093  * INT 13, 43 - Extended write
1094  *
1095  * @v int13             Emulated drive
1096  * @v ds:si             Disk address packet
1097  * @ret status          Status code
1098  */
1099 static int int13_extended_write ( struct int13_drive *int13,
1100                                   struct i386_all_regs *ix86 ) {
1101         DBGC2 ( int13, "Extended write: " );
1102         return int13_extended_rw ( int13, ix86, block_write );
1103 }
1104
1105 /**
1106  * INT 13, 44 - Verify sectors
1107  *
1108  * @v int13             Emulated drive
1109  * @v ds:si             Disk address packet
1110  * @ret status          Status code
1111  */
1112 static int int13_extended_verify ( struct int13_drive *int13,
1113                                    struct i386_all_regs *ix86 ) {
1114         struct int13_disk_address addr;
1115         uint64_t lba;
1116         unsigned long count;
1117
1118         /* Read parameters from disk address structure */
1119         if ( DBG_EXTRA ) {
1120                 copy_from_real ( &addr, ix86->segs.ds, ix86->regs.si,
1121                                  sizeof ( addr ));
1122                 lba = addr.lba;
1123                 count = addr.count;
1124                 DBGC2 ( int13, "Verify: LBA %08llx (count %ld)\n",
1125                         ( ( unsigned long long ) lba ), count );
1126         }
1127
1128         /* We have no mechanism for verifying sectors */
1129         return -INT13_STATUS_INVALID;
1130 }
1131
1132 /**
1133  * INT 13, 44 - Extended seek
1134  *
1135  * @v int13             Emulated drive
1136  * @v ds:si             Disk address packet
1137  * @ret status          Status code
1138  */
1139 static int int13_extended_seek ( struct int13_drive *int13,
1140                                  struct i386_all_regs *ix86 ) {
1141         struct int13_disk_address addr;
1142         uint64_t lba;
1143         unsigned long count;
1144
1145         /* Read parameters from disk address structure */
1146         if ( DBG_EXTRA ) {
1147                 copy_from_real ( &addr, ix86->segs.ds, ix86->regs.si,
1148                                  sizeof ( addr ));
1149                 lba = addr.lba;
1150                 count = addr.count;
1151                 DBGC2 ( int13, "Seek: LBA %08llx (count %ld)\n",
1152                         ( ( unsigned long long ) lba ), count );
1153         }
1154
1155         /* Ignore and return success */
1156         return 0;
1157 }
1158
1159 /**
1160  * Build device path information
1161  *
1162  * @v int13             Emulated drive
1163  * @v dpi               Device path information
1164  * @ret rc              Return status code
1165  */
1166 static int int13_device_path_info ( struct int13_drive *int13,
1167                                     struct edd_device_path_information *dpi ) {
1168         struct device *device;
1169         struct device_description *desc;
1170         unsigned int i;
1171         uint8_t sum = 0;
1172         int rc;
1173
1174         /* Reopen block device if necessary */
1175         if ( ( int13->block_rc != 0 ) &&
1176              ( ( rc = int13_reopen_block ( int13 ) ) != 0 ) )
1177                 return rc;
1178
1179         /* Get underlying hardware device */
1180         device = identify_device ( &int13->block );
1181         if ( ! device ) {
1182                 DBGC ( int13, "INT13 drive %02x cannot identify hardware "
1183                        "device\n", int13->drive );
1184                 return -ENODEV;
1185         }
1186
1187         /* Fill in bus type and interface path */
1188         desc = &device->desc;
1189         switch ( desc->bus_type ) {
1190         case BUS_TYPE_PCI:
1191                 dpi->host_bus_type.type = EDD_BUS_TYPE_PCI;
1192                 dpi->interface_path.pci.bus = PCI_BUS ( desc->location );
1193                 dpi->interface_path.pci.slot = PCI_SLOT ( desc->location );
1194                 dpi->interface_path.pci.function = PCI_FUNC ( desc->location );
1195                 dpi->interface_path.pci.channel = 0xff; /* unused */
1196                 break;
1197         default:
1198                 DBGC ( int13, "INT13 drive %02x unrecognised bus type %d\n",
1199                        int13->drive, desc->bus_type );
1200                 return -ENOTSUP;
1201         }
1202
1203         /* Get EDD block device description */
1204         if ( ( rc = edd_describe ( &int13->block, &dpi->interface_type,
1205                                    &dpi->device_path ) ) != 0 ) {
1206                 DBGC ( int13, "INT13 drive %02x cannot identify block device: "
1207                        "%s\n", int13->drive, strerror ( rc ) );
1208                 return rc;
1209         }
1210
1211         /* Fill in common fields and fix checksum */
1212         dpi->key = EDD_DEVICE_PATH_INFO_KEY;
1213         dpi->len = sizeof ( *dpi );
1214         for ( i = 0 ; i < sizeof ( *dpi ) ; i++ )
1215                 sum += *( ( ( uint8_t * ) dpi ) + i );
1216         dpi->checksum -= sum;
1217
1218         return 0;
1219 }
1220
1221 /**
1222  * INT 13, 48 - Get extended parameters
1223  *
1224  * @v int13             Emulated drive
1225  * @v ds:si             Drive parameter table
1226  * @ret status          Status code
1227  */
1228 static int int13_get_extended_parameters ( struct int13_drive *int13,
1229                                            struct i386_all_regs *ix86 ) {
1230         struct int13_disk_parameters params;
1231         struct segoff address;
1232         size_t len = sizeof ( params );
1233         uint16_t bufsize;
1234         int rc;
1235
1236         /* Get buffer size */
1237         get_real ( bufsize, ix86->segs.ds,
1238                    ( ix86->regs.si + offsetof ( typeof ( params ), bufsize )));
1239
1240         DBGC2 ( int13, "Get extended drive parameters to %04x:%04x+%02x\n",
1241                 ix86->segs.ds, ix86->regs.si, bufsize );
1242
1243         /* Build drive parameters */
1244         memset ( &params, 0, sizeof ( params ) );
1245         params.flags = INT13_FL_DMA_TRANSPARENT;
1246         if ( ( int13->cylinders < 1024 ) &&
1247              ( int13_capacity ( int13 ) <= INT13_MAX_CHS_SECTORS ) ) {
1248                 params.flags |= INT13_FL_CHS_VALID;
1249         }
1250         params.cylinders = int13->cylinders;
1251         params.heads = int13->heads;
1252         params.sectors_per_track = int13->sectors_per_track;
1253         params.sectors = int13_capacity ( int13 );
1254         params.sector_size = int13_blksize ( int13 );
1255         memset ( &params.dpte, 0xff, sizeof ( params.dpte ) );
1256         if ( ( rc = int13_device_path_info ( int13, &params.dpi ) ) != 0 ) {
1257                 DBGC ( int13, "INT13 drive %02x could not provide device "
1258                        "path information: %s\n",
1259                        int13->drive, strerror ( rc ) );
1260                 len = offsetof ( typeof ( params ), dpi );
1261         }
1262
1263         /* Calculate returned "buffer size" (which will be less than
1264          * the length actually copied if device path information is
1265          * present).
1266          */
1267         if ( bufsize < offsetof ( typeof ( params ), dpte ) )
1268                 return -INT13_STATUS_INVALID;
1269         if ( bufsize < offsetof ( typeof ( params ), dpi ) ) {
1270                 params.bufsize = offsetof ( typeof ( params ), dpte );
1271         } else {
1272                 params.bufsize = offsetof ( typeof ( params ), dpi );
1273         }
1274
1275         DBGC ( int13, "INT 13 drive %02x described using extended "
1276                "parameters:\n", int13->drive );
1277         address.segment = ix86->segs.ds;
1278         address.offset = ix86->regs.si;
1279         DBGC_HDA ( int13, address, &params, len );
1280
1281         /* Return drive parameters */
1282         if ( len > bufsize )
1283                 len = bufsize;
1284         copy_to_real ( ix86->segs.ds, ix86->regs.si, &params, len );
1285
1286         return 0;
1287 }
1288
1289 /**
1290  * INT 13, 4b - Get status or terminate CD-ROM emulation
1291  *
1292  * @v int13             Emulated drive
1293  * @v ds:si             Specification packet
1294  * @ret status          Status code
1295  */
1296 static int int13_cdrom_status_terminate ( struct int13_drive *int13,
1297                                           struct i386_all_regs *ix86 ) {
1298         struct int13_cdrom_specification specification;
1299
1300         DBGC2 ( int13, "Get CD-ROM emulation status to %04x:%04x%s\n",
1301                 ix86->segs.ds, ix86->regs.si,
1302                 ( ix86->regs.al ? "" : " and terminate" ) );
1303
1304         /* Fail if we are not a CD-ROM */
1305         if ( ! int13->is_cdrom ) {
1306                 DBGC ( int13, "INT13 drive %02x is not a CD-ROM\n",
1307                        int13->drive );
1308                 return -INT13_STATUS_INVALID;
1309         }
1310
1311         /* Build specification packet */
1312         memset ( &specification, 0, sizeof ( specification ) );
1313         specification.size = sizeof ( specification );
1314         specification.drive = int13->drive;
1315
1316         /* Return specification packet */
1317         copy_to_real ( ix86->segs.ds, ix86->regs.si, &specification,
1318                        sizeof ( specification ) );
1319
1320         return 0;
1321 }
1322
1323
1324 /**
1325  * INT 13, 4d - Read CD-ROM boot catalog
1326  *
1327  * @v int13             Emulated drive
1328  * @v ds:si             Command packet
1329  * @ret status          Status code
1330  */
1331 static int int13_cdrom_read_boot_catalog ( struct int13_drive *int13,
1332                                            struct i386_all_regs *ix86 ) {
1333         struct int13_cdrom_boot_catalog_command command;
1334         int rc;
1335
1336         /* Read parameters from command packet */
1337         copy_from_real ( &command, ix86->segs.ds, ix86->regs.si,
1338                          sizeof ( command ) );
1339         DBGC2 ( int13, "Read CD-ROM boot catalog to %08x\n", command.buffer );
1340
1341         /* Fail if we have no boot catalog */
1342         if ( ! int13->boot_catalog ) {
1343                 DBGC ( int13, "INT13 drive %02x has no boot catalog\n",
1344                        int13->drive );
1345                 return -INT13_STATUS_INVALID;
1346         }
1347
1348         /* Read from boot catalog */
1349         if ( ( rc = int13_rw ( int13, ( int13->boot_catalog + command.start ),
1350                                command.count, phys_to_user ( command.buffer ),
1351                                block_read ) ) != 0 ) {
1352                 DBGC ( int13, "INT13 drive %02x could not read boot catalog: "
1353                        "%s\n", int13->drive, strerror ( rc ) );
1354                 return -INT13_STATUS_READ_ERROR;
1355         }
1356
1357         return 0;
1358 }
1359
1360 /**
1361  * INT 13 handler
1362  *
1363  */
1364 static __asmcall void int13 ( struct i386_all_regs *ix86 ) {
1365         int command = ix86->regs.ah;
1366         unsigned int bios_drive = ix86->regs.dl;
1367         struct int13_drive *int13;
1368         int status;
1369
1370         /* Check BIOS hasn't killed off our drive */
1371         int13_check_num_drives();
1372
1373         list_for_each_entry ( int13, &int13s, list ) {
1374
1375                 if ( bios_drive != int13->drive ) {
1376                         /* Remap any accesses to this drive's natural number */
1377                         if ( bios_drive == int13->natural_drive ) {
1378                                 DBGC2 ( int13, "INT13,%02x (%02x) remapped to "
1379                                         "(%02x)\n", ix86->regs.ah,
1380                                         bios_drive, int13->drive );
1381                                 ix86->regs.dl = int13->drive;
1382                                 return;
1383                         } else if ( ( ( bios_drive & 0x7f ) == 0x7f ) &&
1384                                     ( command == INT13_CDROM_STATUS_TERMINATE )
1385                                     && int13->is_cdrom ) {
1386                                 /* Catch non-drive-specific CD-ROM calls */
1387                         } else {
1388                                 continue;
1389                         }
1390                 }
1391                 
1392                 DBGC2 ( int13, "INT13,%02x (%02x): ",
1393                         ix86->regs.ah, bios_drive );
1394
1395                 switch ( command ) {
1396                 case INT13_RESET:
1397                         status = int13_reset ( int13, ix86 );
1398                         break;
1399                 case INT13_GET_LAST_STATUS:
1400                         status = int13_get_last_status ( int13, ix86 );
1401                         break;
1402                 case INT13_READ_SECTORS:
1403                         status = int13_read_sectors ( int13, ix86 );
1404                         break;
1405                 case INT13_WRITE_SECTORS:
1406                         status = int13_write_sectors ( int13, ix86 );
1407                         break;
1408                 case INT13_GET_PARAMETERS:
1409                         status = int13_get_parameters ( int13, ix86 );
1410                         break;
1411                 case INT13_GET_DISK_TYPE:
1412                         status = int13_get_disk_type ( int13, ix86 );
1413                         break;
1414                 case INT13_EXTENSION_CHECK:
1415                         status = int13_extension_check ( int13, ix86 );
1416                         break;
1417                 case INT13_EXTENDED_READ:
1418                         status = int13_extended_read ( int13, ix86 );
1419                         break;
1420                 case INT13_EXTENDED_WRITE:
1421                         status = int13_extended_write ( int13, ix86 );
1422                         break;
1423                 case INT13_EXTENDED_VERIFY:
1424                         status = int13_extended_verify ( int13, ix86 );
1425                         break;
1426                 case INT13_EXTENDED_SEEK:
1427                         status = int13_extended_seek ( int13, ix86 );
1428                         break;
1429                 case INT13_GET_EXTENDED_PARAMETERS:
1430                         status = int13_get_extended_parameters ( int13, ix86 );
1431                         break;
1432                 case INT13_CDROM_STATUS_TERMINATE:
1433                         status = int13_cdrom_status_terminate ( int13, ix86 );
1434                         break;
1435                 case INT13_CDROM_READ_BOOT_CATALOG:
1436                         status = int13_cdrom_read_boot_catalog ( int13, ix86 );
1437                         break;
1438                 default:
1439                         DBGC2 ( int13, "*** Unrecognised INT13 ***\n" );
1440                         status = -INT13_STATUS_INVALID;
1441                         break;
1442                 }
1443
1444                 /* Store status for INT 13,01 */
1445                 int13->last_status = status;
1446
1447                 /* Negative status indicates an error */
1448                 if ( status < 0 ) {
1449                         status = -status;
1450                         DBGC ( int13, "INT13,%02x (%02x) failed with status "
1451                                "%02x\n", ix86->regs.ah, int13->drive, status );
1452                 } else {
1453                         ix86->flags &= ~CF;
1454                 }
1455                 ix86->regs.ah = status;
1456
1457                 /* Set OF to indicate to wrapper not to chain this call */
1458                 ix86->flags |= OF;
1459
1460                 return;
1461         }
1462 }
1463
1464 /**
1465  * Hook INT 13 handler
1466  *
1467  */
1468 static void int13_hook_vector ( void ) {
1469         /* Assembly wrapper to call int13().  int13() sets OF if we
1470          * should not chain to the previous handler.  (The wrapper
1471          * clears CF and OF before calling int13()).
1472          */
1473         __asm__  __volatile__ (
1474                TEXT16_CODE ( "\nint13_wrapper:\n\t"
1475                              /* Preserve %ax and %dx for future reference */
1476                              "pushw %%bp\n\t"
1477                              "movw %%sp, %%bp\n\t"                           
1478                              "pushw %%ax\n\t"
1479                              "pushw %%dx\n\t"
1480                              /* Clear OF, set CF, call int13() */
1481                              "orb $0, %%al\n\t" 
1482                              "stc\n\t"
1483                              "pushl %0\n\t"
1484                              "pushw %%cs\n\t"
1485                              "call prot_call\n\t"
1486                              /* Chain if OF not set */
1487                              "jo 1f\n\t"
1488                              "pushfw\n\t"
1489                              "lcall *%%cs:int13_vector\n\t"
1490                              "\n1:\n\t"
1491                              /* Overwrite flags for iret */
1492                              "pushfw\n\t"
1493                              "popw 6(%%bp)\n\t"
1494                              /* Fix up %dl:
1495                               *
1496                               * INT 13,15 : do nothing if hard disk
1497                               * INT 13,08 : load with number of drives
1498                               * all others: restore original value
1499                               */
1500                              "cmpb $0x15, -1(%%bp)\n\t"
1501                              "jne 2f\n\t"
1502                              "testb $0x80, -4(%%bp)\n\t"
1503                              "jnz 3f\n\t"
1504                              "\n2:\n\t"
1505                              "movb -4(%%bp), %%dl\n\t"
1506                              "cmpb $0x08, -1(%%bp)\n\t"
1507                              "jne 3f\n\t"
1508                              "testb $0x80, %%dl\n\t"
1509                              "movb %%cs:num_drives, %%dl\n\t"
1510                              "jnz 3f\n\t"
1511                              "movb %%cs:num_fdds, %%dl\n\t"
1512                              /* Return */
1513                              "\n3:\n\t"
1514                              "movw %%bp, %%sp\n\t"
1515                              "popw %%bp\n\t"
1516                              "iret\n\t" )
1517                : : "i" ( int13 ) );
1518
1519         hook_bios_interrupt ( 0x13, ( unsigned int ) int13_wrapper,
1520                               &int13_vector );
1521 }
1522
1523 /**
1524  * Unhook INT 13 handler
1525  */
1526 static void int13_unhook_vector ( void ) {
1527         unhook_bios_interrupt ( 0x13, ( unsigned int ) int13_wrapper,
1528                                 &int13_vector );
1529 }
1530
1531 /**
1532  * Check INT13 emulated drive flow control window
1533  *
1534  * @v int13             Emulated drive
1535  */
1536 static size_t int13_block_window ( struct int13_drive *int13 __unused ) {
1537
1538         /* We are never ready to receive data via this interface.
1539          * This prevents objects that support both block and stream
1540          * interfaces from attempting to send us stream data.
1541          */
1542         return 0;
1543 }
1544
1545 /**
1546  * Handle INT 13 emulated drive underlying block device closing
1547  *
1548  * @v int13             Emulated drive
1549  * @v rc                Reason for close
1550  */
1551 static void int13_block_close ( struct int13_drive *int13, int rc ) {
1552
1553         /* Any closing is an error from our point of view */
1554         if ( rc == 0 )
1555                 rc = -ENOTCONN;
1556
1557         DBGC ( int13, "INT13 drive %02x went away: %s\n",
1558                int13->drive, strerror ( rc ) );
1559
1560         /* Record block device error code */
1561         int13->block_rc = rc;
1562
1563         /* Shut down interfaces */
1564         intf_restart ( &int13->block, rc );
1565 }
1566
1567 /** INT 13 drive interface operations */
1568 static struct interface_operation int13_block_op[] = {
1569         INTF_OP ( xfer_window, struct int13_drive *, int13_block_window ),
1570         INTF_OP ( intf_close, struct int13_drive *, int13_block_close ),
1571 };
1572
1573 /** INT 13 drive interface descriptor */
1574 static struct interface_descriptor int13_block_desc =
1575         INTF_DESC ( struct int13_drive, block, int13_block_op );
1576
1577 /**
1578  * Free INT 13 emulated drive
1579  *
1580  * @v refcnt            Reference count
1581  */
1582 static void int13_free ( struct refcnt *refcnt ) {
1583         struct int13_drive *int13 =
1584                 container_of ( refcnt, struct int13_drive, refcnt );
1585
1586         uri_put ( int13->uri );
1587         free ( int13 );
1588 }
1589
1590 /**
1591  * Hook INT 13 emulated drive
1592  *
1593  * @v uri               URI
1594  * @v drive             Drive number
1595  * @ret rc              Return status code
1596  *
1597  * Registers the drive with the INT 13 emulation subsystem, and hooks
1598  * the INT 13 interrupt vector (if not already hooked).
1599  */
1600 static int int13_hook ( struct uri *uri, unsigned int drive ) {
1601         struct int13_drive *int13;
1602         unsigned int natural_drive;
1603         void *scratch;
1604         int rc;
1605
1606         /* Calculate natural drive number */
1607         int13_sync_num_drives();
1608         natural_drive = ( ( drive & 0x80 ) ? ( num_drives | 0x80 ) : num_fdds );
1609
1610         /* Check that drive number is not in use */
1611         list_for_each_entry ( int13, &int13s, list ) {
1612                 if ( int13->drive == drive ) {
1613                         rc = -EADDRINUSE;
1614                         goto err_in_use;
1615                 }
1616         }
1617
1618         /* Allocate and initialise structure */
1619         int13 = zalloc ( sizeof ( *int13 ) );
1620         if ( ! int13 ) {
1621                 rc = -ENOMEM;
1622                 goto err_zalloc;
1623         }
1624         ref_init ( &int13->refcnt, int13_free );
1625         intf_init ( &int13->block, &int13_block_desc, &int13->refcnt );
1626         int13->uri = uri_get ( uri );
1627         int13->drive = drive;
1628         int13->natural_drive = natural_drive;
1629
1630         /* Open block device interface */
1631         if ( ( rc = int13_reopen_block ( int13 ) ) != 0 )
1632                 goto err_reopen_block;
1633
1634         /* Read device capacity */
1635         if ( ( rc = int13_read_capacity ( int13 ) ) != 0 )
1636                 goto err_read_capacity;
1637
1638         /* Allocate scratch area */
1639         scratch = malloc ( int13_blksize ( int13 ) );
1640         if ( ! scratch )
1641                 goto err_alloc_scratch;
1642
1643         /* Parse parameters, if present */
1644         if ( ( rc = int13_parse_iso9660 ( int13, scratch ) ) != 0 )
1645                 goto err_parse_iso9660;
1646
1647         /* Give drive a default geometry */
1648         if ( ( rc = int13_guess_geometry ( int13, scratch ) ) != 0 )
1649                 goto err_guess_geometry;
1650
1651         DBGC ( int13, "INT13 drive %02x (naturally %02x) registered with C/H/S "
1652                "geometry %d/%d/%d\n", int13->drive, int13->natural_drive,
1653                int13->cylinders, int13->heads, int13->sectors_per_track );
1654
1655         /* Hook INT 13 vector if not already hooked */
1656         if ( list_empty ( &int13s ) ) {
1657                 int13_hook_vector();
1658                 devices_get();
1659         }
1660
1661         /* Add to list of emulated drives */
1662         list_add ( &int13->list, &int13s );
1663
1664         /* Update BIOS drive count */
1665         int13_sync_num_drives();
1666
1667         free ( scratch );
1668         return 0;
1669
1670  err_guess_geometry:
1671  err_parse_iso9660:
1672         free ( scratch );
1673  err_alloc_scratch:
1674  err_read_capacity:
1675  err_reopen_block:
1676         intf_shutdown ( &int13->block, rc );
1677         ref_put ( &int13->refcnt );
1678  err_zalloc:
1679  err_in_use:
1680         return rc;
1681 }
1682
1683 /**
1684  * Find INT 13 emulated drive by drive number
1685  *
1686  * @v drive             Drive number
1687  * @ret int13           Emulated drive, or NULL
1688  */
1689 static struct int13_drive * int13_find ( unsigned int drive ) {
1690         struct int13_drive *int13;
1691
1692         list_for_each_entry ( int13, &int13s, list ) {
1693                 if ( int13->drive == drive )
1694                         return int13;
1695         }
1696         return NULL;
1697 }
1698
1699 /**
1700  * Unhook INT 13 emulated drive
1701  *
1702  * @v drive             Drive number
1703  *
1704  * Unregisters the drive from the INT 13 emulation subsystem.  If this
1705  * is the last emulated drive, the INT 13 vector is unhooked (if
1706  * possible).
1707  */
1708 static void int13_unhook ( unsigned int drive ) {
1709         struct int13_drive *int13;
1710
1711         /* Find drive */
1712         int13 = int13_find ( drive );
1713         if ( ! int13 ) {
1714                 DBG ( "INT13 cannot find emulated drive %02x\n", drive );
1715                 return;
1716         }
1717
1718         /* Shut down interfaces */
1719         intf_shutdown ( &int13->block, 0 );
1720
1721         /* Remove from list of emulated drives */
1722         list_del ( &int13->list );
1723
1724         /* Should adjust BIOS drive count, but it's difficult
1725          * to do so reliably.
1726          */
1727
1728         DBGC ( int13, "INT13 drive %02x unregistered\n", int13->drive );
1729
1730         /* Unhook INT 13 vector if no more drives */
1731         if ( list_empty ( &int13s ) ) {
1732                 devices_put();
1733                 int13_unhook_vector();
1734         }
1735
1736         /* Drop list's reference to drive */
1737         ref_put ( &int13->refcnt );
1738 }
1739
1740 /**
1741  * Load and verify master boot record from INT 13 drive
1742  *
1743  * @v drive             Drive number
1744  * @v address           Boot code address to fill in
1745  * @ret rc              Return status code
1746  */
1747 static int int13_load_mbr ( unsigned int drive, struct segoff *address ) {
1748         uint8_t status;
1749         int discard_b, discard_c, discard_d;
1750         uint16_t magic;
1751
1752         /* Use INT 13, 02 to read the MBR */
1753         address->segment = 0;
1754         address->offset = 0x7c00;
1755         __asm__ __volatile__ ( REAL_CODE ( "pushw %%es\n\t"
1756                                            "pushl %%ebx\n\t"
1757                                            "popw %%bx\n\t"
1758                                            "popw %%es\n\t"
1759                                            "stc\n\t"
1760                                            "sti\n\t"
1761                                            "int $0x13\n\t"
1762                                            "sti\n\t" /* BIOS bugs */
1763                                            "jc 1f\n\t"
1764                                            "xorw %%ax, %%ax\n\t"
1765                                            "\n1:\n\t"
1766                                            "popw %%es\n\t" )
1767                                : "=a" ( status ), "=b" ( discard_b ),
1768                                  "=c" ( discard_c ), "=d" ( discard_d )
1769                                : "a" ( 0x0201 ), "b" ( *address ),
1770                                  "c" ( 1 ), "d" ( drive ) );
1771         if ( status ) {
1772                 DBG ( "INT13 drive %02x could not read MBR (status %02x)\n",
1773                       drive, status );
1774                 return -EIO;
1775         }
1776
1777         /* Check magic signature */
1778         get_real ( magic, address->segment,
1779                    ( address->offset +
1780                      offsetof ( struct master_boot_record, magic ) ) );
1781         if ( magic != INT13_MBR_MAGIC ) {
1782                 DBG ( "INT13 drive %02x does not contain a valid MBR\n",
1783                       drive );
1784                 return -ENOEXEC;
1785         }
1786
1787         return 0;
1788 }
1789
1790 /** El Torito boot catalog command packet */
1791 static struct int13_cdrom_boot_catalog_command __data16 ( eltorito_cmd ) = {
1792         .size = sizeof ( struct int13_cdrom_boot_catalog_command ),
1793         .count = 1,
1794         .buffer = 0x7c00,
1795         .start = 0,
1796 };
1797 #define eltorito_cmd __use_data16 ( eltorito_cmd )
1798
1799 /** El Torito disk address packet */
1800 static struct int13_disk_address __bss16 ( eltorito_address );
1801 #define eltorito_address __use_data16 ( eltorito_address )
1802
1803 /**
1804  * Load and verify El Torito boot record from INT 13 drive
1805  *
1806  * @v drive             Drive number
1807  * @v address           Boot code address to fill in
1808  * @ret rc              Return status code
1809  */
1810 static int int13_load_eltorito ( unsigned int drive, struct segoff *address ) {
1811         struct {
1812                 struct eltorito_validation_entry valid;
1813                 struct eltorito_boot_entry boot;
1814         } __attribute__ (( packed )) catalog;
1815         uint8_t status;
1816
1817         /* Use INT 13, 4d to read the boot catalog */
1818         __asm__ __volatile__ ( REAL_CODE ( "stc\n\t"
1819                                            "sti\n\t"
1820                                            "int $0x13\n\t"
1821                                            "sti\n\t" /* BIOS bugs */
1822                                            "jc 1f\n\t"
1823                                            "xorw %%ax, %%ax\n\t"
1824                                            "\n1:\n\t" )
1825                                : "=a" ( status )
1826                                : "a" ( 0x4d00 ), "d" ( drive ),
1827                                  "S" ( __from_data16 ( &eltorito_cmd ) ) );
1828         if ( status ) {
1829                 DBG ( "INT13 drive %02x could not read El Torito boot catalog "
1830                       "(status %02x)\n", drive, status );
1831                 return -EIO;
1832         }
1833         copy_from_user ( &catalog, phys_to_user ( eltorito_cmd.buffer ), 0,
1834                          sizeof ( catalog ) );
1835
1836         /* Sanity checks */
1837         if ( catalog.valid.platform_id != ELTORITO_PLATFORM_X86 ) {
1838                 DBG ( "INT13 drive %02x El Torito specifies unknown platform "
1839                       "%02x\n", drive, catalog.valid.platform_id );
1840                 return -ENOEXEC;
1841         }
1842         if ( catalog.boot.indicator != ELTORITO_BOOTABLE ) {
1843                 DBG ( "INT13 drive %02x El Torito is not bootable\n", drive );
1844                 return -ENOEXEC;
1845         }
1846         if ( catalog.boot.media_type != ELTORITO_NO_EMULATION ) {
1847                 DBG ( "INT13 drive %02x El Torito requires emulation "
1848                        "type %02x\n", drive, catalog.boot.media_type );
1849                 return -ENOTSUP;
1850         }
1851         DBG ( "INT13 drive %02x El Torito boot image at LBA %08x (count %d)\n",
1852               drive, catalog.boot.start, catalog.boot.length );
1853         address->segment = ( catalog.boot.load_segment ?
1854                              catalog.boot.load_segment : 0x7c0 );
1855         address->offset = 0;
1856         DBG ( "INT13 drive %02x El Torito boot image loads at %04x:%04x\n",
1857               drive, address->segment, address->offset );
1858
1859         /* Use INT 13, 42 to read the boot image */
1860         eltorito_address.bufsize =
1861                 offsetof ( typeof ( eltorito_address ), buffer_phys );
1862         eltorito_address.count = catalog.boot.length;
1863         eltorito_address.buffer = *address;
1864         eltorito_address.lba = catalog.boot.start;
1865         __asm__ __volatile__ ( REAL_CODE ( "stc\n\t"
1866                                            "sti\n\t"
1867                                            "int $0x13\n\t"
1868                                            "sti\n\t" /* BIOS bugs */
1869                                            "jc 1f\n\t"
1870                                            "xorw %%ax, %%ax\n\t"
1871                                            "\n1:\n\t" )
1872                                : "=a" ( status )
1873                                : "a" ( 0x4200 ), "d" ( drive ),
1874                                  "S" ( __from_data16 ( &eltorito_address ) ) );
1875         if ( status ) {
1876                 DBG ( "INT13 drive %02x could not read El Torito boot image "
1877                       "(status %02x)\n", drive, status );
1878                 return -EIO;
1879         }
1880
1881         return 0;
1882 }
1883
1884 /**
1885  * Attempt to boot from an INT 13 drive
1886  *
1887  * @v drive             Drive number
1888  * @ret rc              Return status code
1889  *
1890  * This boots from the specified INT 13 drive by loading the Master
1891  * Boot Record to 0000:7c00 and jumping to it.  INT 18 is hooked to
1892  * capture an attempt by the MBR to boot the next device.  (This is
1893  * the closest thing to a return path from an MBR).
1894  *
1895  * Note that this function can never return success, by definition.
1896  */
1897 static int int13_boot ( unsigned int drive ) {
1898         struct memory_map memmap;
1899         struct segoff address;
1900         int rc;
1901
1902         /* Look for a usable boot sector */
1903         if ( ( ( rc = int13_load_mbr ( drive, &address ) ) != 0 ) &&
1904              ( ( rc = int13_load_eltorito ( drive, &address ) ) != 0 ) )
1905                 return rc;
1906
1907         /* Dump out memory map prior to boot, if memmap debugging is
1908          * enabled.  Not required for program flow, but we have so
1909          * many problems that turn out to be memory-map related that
1910          * it's worth doing.
1911          */
1912         get_memmap ( &memmap );
1913
1914         /* Jump to boot sector */
1915         if ( ( rc = call_bootsector ( address.segment, address.offset,
1916                                       drive ) ) != 0 ) {
1917                 DBG ( "INT13 drive %02x boot returned: %s\n",
1918                       drive, strerror ( rc ) );
1919                 return rc;
1920         }
1921
1922         return -ECANCELED; /* -EIMPOSSIBLE */
1923 }
1924
1925 /** A boot firmware table generated by iPXE */
1926 union xbft_table {
1927         /** ACPI header */
1928         struct acpi_description_header acpi;
1929         /** Padding */
1930         char pad[768];
1931 };
1932
1933 /** The boot firmware table generated by iPXE */
1934 static union xbft_table __bss16 ( xbftab ) __attribute__ (( aligned ( 16 ) ));
1935 #define xbftab __use_data16 ( xbftab )
1936
1937 /**
1938  * Describe INT 13 emulated drive for SAN-booted operating system
1939  *
1940  * @v drive             Drive number
1941  * @ret rc              Return status code
1942  */
1943 static int int13_describe ( unsigned int drive ) {
1944         struct int13_drive *int13;
1945         struct segoff xbft_address;
1946         int rc;
1947
1948         /* Find drive */
1949         int13 = int13_find ( drive );
1950         if ( ! int13 ) {
1951                 DBG ( "INT13 cannot find emulated drive %02x\n", drive );
1952                 return -ENODEV;
1953         }
1954
1955         /* Reopen block device if necessary */
1956         if ( ( int13->block_rc != 0 ) &&
1957              ( ( rc = int13_reopen_block ( int13 ) ) != 0 ) )
1958                 return rc;
1959
1960         /* Clear table */
1961         memset ( &xbftab, 0, sizeof ( xbftab ) );
1962
1963         /* Fill in common parameters */
1964         strncpy ( xbftab.acpi.oem_id, "FENSYS",
1965                   sizeof ( xbftab.acpi.oem_id ) );
1966         strncpy ( xbftab.acpi.oem_table_id, "iPXE",
1967                   sizeof ( xbftab.acpi.oem_table_id ) );
1968
1969         /* Fill in remaining parameters */
1970         if ( ( rc = acpi_describe ( &int13->block, &xbftab.acpi,
1971                                     sizeof ( xbftab ) ) ) != 0 ) {
1972                 DBGC ( int13, "INT13 drive %02x could not create ACPI "
1973                        "description: %s\n", int13->drive, strerror ( rc ) );
1974                 return rc;
1975         }
1976
1977         /* Fix up ACPI checksum */
1978         acpi_fix_checksum ( &xbftab.acpi );
1979         xbft_address.segment = rm_ds;
1980         xbft_address.offset = __from_data16 ( &xbftab );
1981         DBGC ( int13, "INT13 drive %02x described using boot firmware "
1982                "table:\n", int13->drive );
1983         DBGC_HDA ( int13, xbft_address, &xbftab,
1984                    le32_to_cpu ( xbftab.acpi.length ) );
1985
1986         return 0;
1987 }
1988
1989 PROVIDE_SANBOOT_INLINE ( pcbios, san_default_drive );
1990 PROVIDE_SANBOOT ( pcbios, san_hook, int13_hook );
1991 PROVIDE_SANBOOT ( pcbios, san_unhook, int13_unhook );
1992 PROVIDE_SANBOOT ( pcbios, san_boot, int13_boot );
1993 PROVIDE_SANBOOT ( pcbios, san_describe, int13_describe );